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 void tc_windup(void);
137 static void cpu_tick_calibrate(int);
139 void dtrace_getnanotime(struct timespec *tsp);
142 sysctl_kern_boottime(SYSCTL_HANDLER_ARGS)
148 if (req->flags & SCTL_MASK32) {
149 tv[0] = boottime.tv_sec;
150 tv[1] = boottime.tv_usec;
151 return SYSCTL_OUT(req, tv, sizeof(tv));
155 return SYSCTL_OUT(req, &boottime, sizeof(boottime));
159 sysctl_kern_timecounter_get(SYSCTL_HANDLER_ARGS)
162 struct timecounter *tc = arg1;
164 ncount = tc->tc_get_timecount(tc);
165 return sysctl_handle_int(oidp, &ncount, 0, req);
169 sysctl_kern_timecounter_freq(SYSCTL_HANDLER_ARGS)
172 struct timecounter *tc = arg1;
174 freq = tc->tc_frequency;
175 return sysctl_handle_64(oidp, &freq, 0, req);
179 * Return the difference between the timehands' counter value now and what
180 * was when we copied it to the timehands' offset_count.
182 static __inline u_int
183 tc_delta(struct timehands *th)
185 struct timecounter *tc;
188 return ((tc->tc_get_timecount(tc) - th->th_offset_count) &
189 tc->tc_counter_mask);
193 tc_getgen(struct timehands *th)
197 return (atomic_load_acq_int(&th->th_generation));
201 gen = th->th_generation;
208 tc_setgen(struct timehands *th, u_int newgen)
212 atomic_store_rel_int(&th->th_generation, newgen);
215 th->th_generation = newgen;
220 * Functions for reading the time. We have to loop until we are sure that
221 * the timehands that we operated on was not updated under our feet. See
222 * the comment in <sys/time.h> for a description of these 12 functions.
227 fbclock_binuptime(struct bintime *bt)
229 struct timehands *th;
236 bintime_addx(bt, th->th_scale * tc_delta(th));
237 } while (gen == 0 || gen != tc_getgen(th));
241 fbclock_nanouptime(struct timespec *tsp)
245 fbclock_binuptime(&bt);
246 bintime2timespec(&bt, tsp);
250 fbclock_microuptime(struct timeval *tvp)
254 fbclock_binuptime(&bt);
255 bintime2timeval(&bt, tvp);
259 fbclock_bintime(struct bintime *bt)
262 fbclock_binuptime(bt);
263 bintime_add(bt, &boottimebin);
267 fbclock_nanotime(struct timespec *tsp)
271 fbclock_bintime(&bt);
272 bintime2timespec(&bt, tsp);
276 fbclock_microtime(struct timeval *tvp)
280 fbclock_bintime(&bt);
281 bintime2timeval(&bt, tvp);
285 fbclock_getbinuptime(struct bintime *bt)
287 struct timehands *th;
294 } while (gen == 0 || gen != tc_getgen(th));
298 fbclock_getnanouptime(struct timespec *tsp)
300 struct timehands *th;
306 bintime2timespec(&th->th_offset, tsp);
307 } while (gen == 0 || gen != tc_getgen(th));
311 fbclock_getmicrouptime(struct timeval *tvp)
313 struct timehands *th;
319 bintime2timeval(&th->th_offset, tvp);
320 } while (gen == 0 || gen != tc_getgen(th));
324 fbclock_getbintime(struct bintime *bt)
326 struct timehands *th;
333 } while (gen == 0 || gen != tc_getgen(th));
334 bintime_add(bt, &boottimebin);
338 fbclock_getnanotime(struct timespec *tsp)
340 struct timehands *th;
346 *tsp = th->th_nanotime;
347 } while (gen == 0 || gen != tc_getgen(th));
351 fbclock_getmicrotime(struct timeval *tvp)
353 struct timehands *th;
359 *tvp = th->th_microtime;
360 } while (gen == 0 || gen != tc_getgen(th));
364 binuptime(struct bintime *bt)
366 struct timehands *th;
373 bintime_addx(bt, th->th_scale * tc_delta(th));
374 } while (gen == 0 || gen != tc_getgen(th));
378 nanouptime(struct timespec *tsp)
383 bintime2timespec(&bt, tsp);
387 microuptime(struct timeval *tvp)
392 bintime2timeval(&bt, tvp);
396 bintime(struct bintime *bt)
400 bintime_add(bt, &boottimebin);
404 nanotime(struct timespec *tsp)
409 bintime2timespec(&bt, tsp);
413 microtime(struct timeval *tvp)
418 bintime2timeval(&bt, tvp);
422 getbinuptime(struct bintime *bt)
424 struct timehands *th;
431 } while (gen == 0 || gen != tc_getgen(th));
435 getnanouptime(struct timespec *tsp)
437 struct timehands *th;
443 bintime2timespec(&th->th_offset, tsp);
444 } while (gen == 0 || gen != tc_getgen(th));
448 getmicrouptime(struct timeval *tvp)
450 struct timehands *th;
456 bintime2timeval(&th->th_offset, tvp);
457 } while (gen == 0 || gen != tc_getgen(th));
461 getbintime(struct bintime *bt)
463 struct timehands *th;
470 } while (gen == 0 || gen != tc_getgen(th));
471 bintime_add(bt, &boottimebin);
475 getnanotime(struct timespec *tsp)
477 struct timehands *th;
483 *tsp = th->th_nanotime;
484 } while (gen == 0 || gen != tc_getgen(th));
488 getmicrotime(struct timeval *tvp)
490 struct timehands *th;
496 *tvp = th->th_microtime;
497 } while (gen == 0 || gen != tc_getgen(th));
503 * Support for feed-forward synchronization algorithms. This is heavily inspired
504 * by the timehands mechanism but kept independent from it. *_windup() functions
505 * have some connection to avoid accessing the timecounter hardware more than
509 /* Feed-forward clock estimates kept updated by the synchronization daemon. */
510 struct ffclock_estimate ffclock_estimate;
511 struct bintime ffclock_boottime; /* Feed-forward boot time estimate. */
512 uint32_t ffclock_status; /* Feed-forward clock status. */
513 int8_t ffclock_updated; /* New estimates are available. */
514 struct mtx ffclock_mtx; /* Mutex on ffclock_estimate. */
517 struct ffclock_estimate cest;
518 struct bintime tick_time;
519 struct bintime tick_time_lerp;
520 ffcounter tick_ffcount;
521 uint64_t period_lerp;
522 volatile uint8_t gen;
523 struct fftimehands *next;
526 #define NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))
528 static struct fftimehands ffth[10];
529 static struct fftimehands *volatile fftimehands = ffth;
534 struct fftimehands *cur;
535 struct fftimehands *last;
537 memset(ffth, 0, sizeof(ffth));
539 last = ffth + NUM_ELEMENTS(ffth) - 1;
540 for (cur = ffth; cur < last; cur++)
545 ffclock_status = FFCLOCK_STA_UNSYNC;
546 mtx_init(&ffclock_mtx, "ffclock lock", NULL, MTX_DEF);
550 * Reset the feed-forward clock estimates. Called from inittodr() to get things
551 * kick started and uses the timecounter nominal frequency as a first period
552 * estimate. Note: this function may be called several time just after boot.
553 * Note: this is the only function that sets the value of boot time for the
554 * monotonic (i.e. uptime) version of the feed-forward clock.
557 ffclock_reset_clock(struct timespec *ts)
559 struct timecounter *tc;
560 struct ffclock_estimate cest;
562 tc = timehands->th_counter;
563 memset(&cest, 0, sizeof(struct ffclock_estimate));
565 timespec2bintime(ts, &ffclock_boottime);
566 timespec2bintime(ts, &(cest.update_time));
567 ffclock_read_counter(&cest.update_ffcount);
568 cest.leapsec_next = 0;
569 cest.period = ((1ULL << 63) / tc->tc_frequency) << 1;
572 cest.status = FFCLOCK_STA_UNSYNC;
573 cest.leapsec_total = 0;
576 mtx_lock(&ffclock_mtx);
577 bcopy(&cest, &ffclock_estimate, sizeof(struct ffclock_estimate));
578 ffclock_updated = INT8_MAX;
579 mtx_unlock(&ffclock_mtx);
581 printf("ffclock reset: %s (%llu Hz), time = %ld.%09lu\n", tc->tc_name,
582 (unsigned long long)tc->tc_frequency, (long)ts->tv_sec,
583 (unsigned long)ts->tv_nsec);
587 * Sub-routine to convert a time interval measured in RAW counter units to time
588 * in seconds stored in bintime format.
589 * NOTE: bintime_mul requires u_int, but the value of the ffcounter may be
590 * larger than the max value of u_int (on 32 bit architecture). Loop to consume
594 ffclock_convert_delta(ffcounter ffdelta, uint64_t period, struct bintime *bt)
597 ffcounter delta, delta_max;
599 delta_max = (1ULL << (8 * sizeof(unsigned int))) - 1;
602 if (ffdelta > delta_max)
608 bintime_mul(&bt2, (unsigned int)delta);
609 bintime_add(bt, &bt2);
611 } while (ffdelta > 0);
615 * Update the fftimehands.
616 * Push the tick ffcount and time(s) forward based on current clock estimate.
617 * The conversion from ffcounter to bintime relies on the difference clock
618 * principle, whose accuracy relies on computing small time intervals. If a new
619 * clock estimate has been passed by the synchronisation daemon, make it
620 * current, and compute the linear interpolation for monotonic time if needed.
623 ffclock_windup(unsigned int delta)
625 struct ffclock_estimate *cest;
626 struct fftimehands *ffth;
627 struct bintime bt, gap_lerp;
630 unsigned int polling;
631 uint8_t forward_jump, ogen;
634 * Pick the next timehand, copy current ffclock estimates and move tick
635 * times and counter forward.
638 ffth = fftimehands->next;
642 bcopy(&fftimehands->cest, cest, sizeof(struct ffclock_estimate));
643 ffdelta = (ffcounter)delta;
644 ffth->period_lerp = fftimehands->period_lerp;
646 ffth->tick_time = fftimehands->tick_time;
647 ffclock_convert_delta(ffdelta, cest->period, &bt);
648 bintime_add(&ffth->tick_time, &bt);
650 ffth->tick_time_lerp = fftimehands->tick_time_lerp;
651 ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt);
652 bintime_add(&ffth->tick_time_lerp, &bt);
654 ffth->tick_ffcount = fftimehands->tick_ffcount + ffdelta;
657 * Assess the status of the clock, if the last update is too old, it is
658 * likely the synchronisation daemon is dead and the clock is free
661 if (ffclock_updated == 0) {
662 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
663 ffclock_convert_delta(ffdelta, cest->period, &bt);
664 if (bt.sec > 2 * FFCLOCK_SKM_SCALE)
665 ffclock_status |= FFCLOCK_STA_UNSYNC;
669 * If available, grab updated clock estimates and make them current.
670 * Recompute time at this tick using the updated estimates. The clock
671 * estimates passed the feed-forward synchronisation daemon may result
672 * in time conversion that is not monotonically increasing (just after
673 * the update). time_lerp is a particular linear interpolation over the
674 * synchronisation algo polling period that ensures monotonicity for the
675 * clock ids requesting it.
677 if (ffclock_updated > 0) {
678 bcopy(&ffclock_estimate, cest, sizeof(struct ffclock_estimate));
679 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
680 ffth->tick_time = cest->update_time;
681 ffclock_convert_delta(ffdelta, cest->period, &bt);
682 bintime_add(&ffth->tick_time, &bt);
684 /* ffclock_reset sets ffclock_updated to INT8_MAX */
685 if (ffclock_updated == INT8_MAX)
686 ffth->tick_time_lerp = ffth->tick_time;
688 if (bintime_cmp(&ffth->tick_time, &ffth->tick_time_lerp, >))
693 bintime_clear(&gap_lerp);
695 gap_lerp = ffth->tick_time;
696 bintime_sub(&gap_lerp, &ffth->tick_time_lerp);
698 gap_lerp = ffth->tick_time_lerp;
699 bintime_sub(&gap_lerp, &ffth->tick_time);
703 * The reset from the RTC clock may be far from accurate, and
704 * reducing the gap between real time and interpolated time
705 * could take a very long time if the interpolated clock insists
706 * on strict monotonicity. The clock is reset under very strict
707 * conditions (kernel time is known to be wrong and
708 * synchronization daemon has been restarted recently.
709 * ffclock_boottime absorbs the jump to ensure boot time is
710 * correct and uptime functions stay consistent.
712 if (((ffclock_status & FFCLOCK_STA_UNSYNC) == FFCLOCK_STA_UNSYNC) &&
713 ((cest->status & FFCLOCK_STA_UNSYNC) == 0) &&
714 ((cest->status & FFCLOCK_STA_WARMUP) == FFCLOCK_STA_WARMUP)) {
716 bintime_add(&ffclock_boottime, &gap_lerp);
718 bintime_sub(&ffclock_boottime, &gap_lerp);
719 ffth->tick_time_lerp = ffth->tick_time;
720 bintime_clear(&gap_lerp);
723 ffclock_status = cest->status;
724 ffth->period_lerp = cest->period;
727 * Compute corrected period used for the linear interpolation of
728 * time. The rate of linear interpolation is capped to 5000PPM
731 if (bintime_isset(&gap_lerp)) {
732 ffdelta = cest->update_ffcount;
733 ffdelta -= fftimehands->cest.update_ffcount;
734 ffclock_convert_delta(ffdelta, cest->period, &bt);
737 bt.frac = 5000000 * (uint64_t)18446744073LL;
738 bintime_mul(&bt, polling);
739 if (bintime_cmp(&gap_lerp, &bt, >))
742 /* Approximate 1 sec by 1-(1/2^64) to ease arithmetic */
744 if (gap_lerp.sec > 0) {
746 frac /= ffdelta / gap_lerp.sec;
748 frac += gap_lerp.frac / ffdelta;
751 ffth->period_lerp += frac;
753 ffth->period_lerp -= frac;
765 * Adjust the fftimehands when the timecounter is changed. Stating the obvious,
766 * the old and new hardware counter cannot be read simultaneously. tc_windup()
767 * does read the two counters 'back to back', but a few cycles are effectively
768 * lost, and not accumulated in tick_ffcount. This is a fairly radical
769 * operation for a feed-forward synchronization daemon, and it is its job to not
770 * pushing irrelevant data to the kernel. Because there is no locking here,
771 * simply force to ignore pending or next update to give daemon a chance to
772 * realize the counter has changed.
775 ffclock_change_tc(struct timehands *th)
777 struct fftimehands *ffth;
778 struct ffclock_estimate *cest;
779 struct timecounter *tc;
783 ffth = fftimehands->next;
788 bcopy(&(fftimehands->cest), cest, sizeof(struct ffclock_estimate));
789 cest->period = ((1ULL << 63) / tc->tc_frequency ) << 1;
792 cest->status |= FFCLOCK_STA_UNSYNC;
794 ffth->tick_ffcount = fftimehands->tick_ffcount;
795 ffth->tick_time_lerp = fftimehands->tick_time_lerp;
796 ffth->tick_time = fftimehands->tick_time;
797 ffth->period_lerp = cest->period;
799 /* Do not lock but ignore next update from synchronization daemon. */
809 * Retrieve feed-forward counter and time of last kernel tick.
812 ffclock_last_tick(ffcounter *ffcount, struct bintime *bt, uint32_t flags)
814 struct fftimehands *ffth;
818 * No locking but check generation has not changed. Also need to make
819 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
824 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP)
825 *bt = ffth->tick_time_lerp;
827 *bt = ffth->tick_time;
828 *ffcount = ffth->tick_ffcount;
829 } while (gen == 0 || gen != ffth->gen);
833 * Absolute clock conversion. Low level function to convert ffcounter to
834 * bintime. The ffcounter is converted using the current ffclock period estimate
835 * or the "interpolated period" to ensure monotonicity.
836 * NOTE: this conversion may have been deferred, and the clock updated since the
837 * hardware counter has been read.
840 ffclock_convert_abs(ffcounter ffcount, struct bintime *bt, uint32_t flags)
842 struct fftimehands *ffth;
848 * No locking but check generation has not changed. Also need to make
849 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
854 if (ffcount > ffth->tick_ffcount)
855 ffdelta = ffcount - ffth->tick_ffcount;
857 ffdelta = ffth->tick_ffcount - ffcount;
859 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP) {
860 *bt = ffth->tick_time_lerp;
861 ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt2);
863 *bt = ffth->tick_time;
864 ffclock_convert_delta(ffdelta, ffth->cest.period, &bt2);
867 if (ffcount > ffth->tick_ffcount)
868 bintime_add(bt, &bt2);
870 bintime_sub(bt, &bt2);
871 } while (gen == 0 || gen != ffth->gen);
875 * Difference clock conversion.
876 * Low level function to Convert a time interval measured in RAW counter units
877 * into bintime. The difference clock allows measuring small intervals much more
878 * reliably than the absolute clock.
881 ffclock_convert_diff(ffcounter ffdelta, struct bintime *bt)
883 struct fftimehands *ffth;
886 /* No locking but check generation has not changed. */
890 ffclock_convert_delta(ffdelta, ffth->cest.period, bt);
891 } while (gen == 0 || gen != ffth->gen);
895 * Access to current ffcounter value.
898 ffclock_read_counter(ffcounter *ffcount)
900 struct timehands *th;
901 struct fftimehands *ffth;
902 unsigned int gen, delta;
905 * ffclock_windup() called from tc_windup(), safe to rely on
906 * th->th_generation only, for correct delta and ffcounter.
912 delta = tc_delta(th);
913 *ffcount = ffth->tick_ffcount;
914 } while (gen == 0 || gen != tc_getgen(th));
920 binuptime(struct bintime *bt)
923 binuptime_fromclock(bt, sysclock_active);
927 nanouptime(struct timespec *tsp)
930 nanouptime_fromclock(tsp, sysclock_active);
934 microuptime(struct timeval *tvp)
937 microuptime_fromclock(tvp, sysclock_active);
941 bintime(struct bintime *bt)
944 bintime_fromclock(bt, sysclock_active);
948 nanotime(struct timespec *tsp)
951 nanotime_fromclock(tsp, sysclock_active);
955 microtime(struct timeval *tvp)
958 microtime_fromclock(tvp, sysclock_active);
962 getbinuptime(struct bintime *bt)
965 getbinuptime_fromclock(bt, sysclock_active);
969 getnanouptime(struct timespec *tsp)
972 getnanouptime_fromclock(tsp, sysclock_active);
976 getmicrouptime(struct timeval *tvp)
979 getmicrouptime_fromclock(tvp, sysclock_active);
983 getbintime(struct bintime *bt)
986 getbintime_fromclock(bt, sysclock_active);
990 getnanotime(struct timespec *tsp)
993 getnanotime_fromclock(tsp, sysclock_active);
997 getmicrotime(struct timeval *tvp)
1000 getmicrouptime_fromclock(tvp, sysclock_active);
1003 #endif /* FFCLOCK */
1006 * This is a clone of getnanotime and used for walltimestamps.
1007 * The dtrace_ prefix prevents fbt from creating probes for
1008 * it so walltimestamp can be safely used in all fbt probes.
1011 dtrace_getnanotime(struct timespec *tsp)
1013 struct timehands *th;
1018 gen = tc_getgen(th);
1019 *tsp = th->th_nanotime;
1020 } while (gen == 0 || gen != tc_getgen(th));
1024 * System clock currently providing time to the system. Modifiable via sysctl
1025 * when the FFCLOCK option is defined.
1027 int sysclock_active = SYSCLOCK_FBCK;
1029 /* Internal NTP status and error estimates. */
1030 extern int time_status;
1031 extern long time_esterror;
1034 * Take a snapshot of sysclock data which can be used to compare system clocks
1035 * and generate timestamps after the fact.
1038 sysclock_getsnapshot(struct sysclock_snap *clock_snap, int fast)
1040 struct fbclock_info *fbi;
1041 struct timehands *th;
1043 unsigned int delta, gen;
1046 struct fftimehands *ffth;
1047 struct ffclock_info *ffi;
1048 struct ffclock_estimate cest;
1050 ffi = &clock_snap->ff_info;
1053 fbi = &clock_snap->fb_info;
1058 gen = tc_getgen(th);
1059 fbi->th_scale = th->th_scale;
1060 fbi->tick_time = th->th_offset;
1063 ffi->tick_time = ffth->tick_time_lerp;
1064 ffi->tick_time_lerp = ffth->tick_time_lerp;
1065 ffi->period = ffth->cest.period;
1066 ffi->period_lerp = ffth->period_lerp;
1067 clock_snap->ffcount = ffth->tick_ffcount;
1071 delta = tc_delta(th);
1072 } while (gen == 0 || gen != tc_getgen(th));
1074 clock_snap->delta = delta;
1075 clock_snap->sysclock_active = sysclock_active;
1077 /* Record feedback clock status and error. */
1078 clock_snap->fb_info.status = time_status;
1079 /* XXX: Very crude estimate of feedback clock error. */
1080 bt.sec = time_esterror / 1000000;
1081 bt.frac = ((time_esterror - bt.sec) * 1000000) *
1082 (uint64_t)18446744073709ULL;
1083 clock_snap->fb_info.error = bt;
1087 clock_snap->ffcount += delta;
1089 /* Record feed-forward clock leap second adjustment. */
1090 ffi->leapsec_adjustment = cest.leapsec_total;
1091 if (clock_snap->ffcount > cest.leapsec_next)
1092 ffi->leapsec_adjustment -= cest.leapsec;
1094 /* Record feed-forward clock status and error. */
1095 clock_snap->ff_info.status = cest.status;
1096 ffcount = clock_snap->ffcount - cest.update_ffcount;
1097 ffclock_convert_delta(ffcount, cest.period, &bt);
1098 /* 18446744073709 = int(2^64/1e12), err_bound_rate in [ps/s]. */
1099 bintime_mul(&bt, cest.errb_rate * (uint64_t)18446744073709ULL);
1100 /* 18446744073 = int(2^64 / 1e9), since err_abs in [ns]. */
1101 bintime_addx(&bt, cest.errb_abs * (uint64_t)18446744073ULL);
1102 clock_snap->ff_info.error = bt;
1107 * Convert a sysclock snapshot into a struct bintime based on the specified
1108 * clock source and flags.
1111 sysclock_snap2bintime(struct sysclock_snap *cs, struct bintime *bt,
1112 int whichclock, uint32_t flags)
1119 switch (whichclock) {
1121 *bt = cs->fb_info.tick_time;
1123 /* If snapshot was created with !fast, delta will be >0. */
1125 bintime_addx(bt, cs->fb_info.th_scale * cs->delta);
1127 if ((flags & FBCLOCK_UPTIME) == 0)
1128 bintime_add(bt, &boottimebin);
1132 if (flags & FFCLOCK_LERP) {
1133 *bt = cs->ff_info.tick_time_lerp;
1134 period = cs->ff_info.period_lerp;
1136 *bt = cs->ff_info.tick_time;
1137 period = cs->ff_info.period;
1140 /* If snapshot was created with !fast, delta will be >0. */
1141 if (cs->delta > 0) {
1142 ffclock_convert_delta(cs->delta, period, &bt2);
1143 bintime_add(bt, &bt2);
1146 /* Leap second adjustment. */
1147 if (flags & FFCLOCK_LEAPSEC)
1148 bt->sec -= cs->ff_info.leapsec_adjustment;
1150 /* Boot time adjustment, for uptime/monotonic clocks. */
1151 if (flags & FFCLOCK_UPTIME)
1152 bintime_sub(bt, &ffclock_boottime);
1164 * Initialize a new timecounter and possibly use it.
1167 tc_init(struct timecounter *tc)
1170 struct sysctl_oid *tc_root;
1172 u = tc->tc_frequency / tc->tc_counter_mask;
1173 /* XXX: We need some margin here, 10% is a guess */
1176 if (u > hz && tc->tc_quality >= 0) {
1177 tc->tc_quality = -2000;
1179 printf("Timecounter \"%s\" frequency %ju Hz",
1180 tc->tc_name, (uintmax_t)tc->tc_frequency);
1181 printf(" -- Insufficient hz, needs at least %u\n", u);
1183 } else if (tc->tc_quality >= 0 || bootverbose) {
1184 printf("Timecounter \"%s\" frequency %ju Hz quality %d\n",
1185 tc->tc_name, (uintmax_t)tc->tc_frequency,
1189 tc->tc_next = timecounters;
1192 * Set up sysctl tree for this counter.
1194 tc_root = SYSCTL_ADD_NODE(NULL,
1195 SYSCTL_STATIC_CHILDREN(_kern_timecounter_tc), OID_AUTO, tc->tc_name,
1196 CTLFLAG_RW, 0, "timecounter description");
1197 SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1198 "mask", CTLFLAG_RD, &(tc->tc_counter_mask), 0,
1199 "mask for implemented bits");
1200 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1201 "counter", CTLTYPE_UINT | CTLFLAG_RD, tc, sizeof(*tc),
1202 sysctl_kern_timecounter_get, "IU", "current timecounter value");
1203 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1204 "frequency", CTLTYPE_U64 | CTLFLAG_RD, tc, sizeof(*tc),
1205 sysctl_kern_timecounter_freq, "QU", "timecounter frequency");
1206 SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1207 "quality", CTLFLAG_RD, &(tc->tc_quality), 0,
1208 "goodness of time counter");
1210 * Never automatically use a timecounter with negative quality.
1211 * Even though we run on the dummy counter, switching here may be
1212 * worse since this timecounter may not be monotonous.
1214 if (tc->tc_quality < 0)
1216 if (tc->tc_quality < timecounter->tc_quality)
1218 if (tc->tc_quality == timecounter->tc_quality &&
1219 tc->tc_frequency < timecounter->tc_frequency)
1221 (void)tc->tc_get_timecount(tc);
1222 (void)tc->tc_get_timecount(tc);
1226 /* Report the frequency of the current timecounter. */
1228 tc_getfrequency(void)
1231 return (timehands->th_counter->tc_frequency);
1235 * Step our concept of UTC. This is done by modifying our estimate of
1240 tc_setclock(struct timespec *ts)
1242 struct timespec tbef, taft;
1243 struct bintime bt, bt2;
1245 cpu_tick_calibrate(1);
1247 timespec2bintime(ts, &bt);
1249 bintime_sub(&bt, &bt2);
1250 bintime_add(&bt2, &boottimebin);
1252 bintime2timeval(&bt, &boottime);
1254 /* XXX fiddle all the little crinkly bits around the fiords... */
1257 if (timestepwarnings) {
1259 "Time stepped from %jd.%09ld to %jd.%09ld (%jd.%09ld)\n",
1260 (intmax_t)tbef.tv_sec, tbef.tv_nsec,
1261 (intmax_t)taft.tv_sec, taft.tv_nsec,
1262 (intmax_t)ts->tv_sec, ts->tv_nsec);
1264 cpu_tick_calibrate(1);
1268 * Initialize the next struct timehands in the ring and make
1269 * it the active timehands. Along the way we might switch to a different
1270 * timecounter and/or do seconds processing in NTP. Slightly magic.
1276 struct timehands *th, *tho;
1278 u_int delta, ncount, ogen;
1283 * Make the next timehands a copy of the current one, but do not
1284 * overwrite the generation or next pointer. While we update
1285 * the contents, the generation must be zero.
1289 ogen = th->th_generation;
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 tc_setgen(th, 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 ||
1442 strcmp(newname, tc->tc_name) == 0)
1444 for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
1445 if (strcmp(newname, newtc->tc_name) != 0)
1448 /* Warm up new timecounter. */
1449 (void)newtc->tc_get_timecount(newtc);
1450 (void)newtc->tc_get_timecount(newtc);
1452 timecounter = newtc;
1455 * The vdso timehands update is deferred until the next
1458 * This is prudent given that 'timekeep_push_vdso()' does not
1459 * use any locking and that it can be called in hard interrupt
1460 * context via 'tc_windup()'.
1467 SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware, CTLTYPE_STRING | CTLFLAG_RW,
1468 0, 0, sysctl_kern_timecounter_hardware, "A",
1469 "Timecounter hardware selected");
1472 /* Report or change the active timecounter hardware. */
1474 sysctl_kern_timecounter_choice(SYSCTL_HANDLER_ARGS)
1477 struct timecounter *tc;
1480 sbuf_new_for_sysctl(&sb, NULL, 0, req);
1481 for (tc = timecounters; tc != NULL; tc = tc->tc_next) {
1482 if (tc != timecounters)
1483 sbuf_putc(&sb, ' ');
1484 sbuf_printf(&sb, "%s(%d)", tc->tc_name, tc->tc_quality);
1486 error = sbuf_finish(&sb);
1491 SYSCTL_PROC(_kern_timecounter, OID_AUTO, choice, CTLTYPE_STRING | CTLFLAG_RD,
1492 0, 0, sysctl_kern_timecounter_choice, "A", "Timecounter hardware detected");
1495 * RFC 2783 PPS-API implementation.
1499 * Return true if the driver is aware of the abi version extensions in the
1500 * pps_state structure, and it supports at least the given abi version number.
1503 abi_aware(struct pps_state *pps, int vers)
1506 return ((pps->kcmode & KCMODE_ABIFLAG) && pps->driver_abi >= vers);
1510 pps_fetch(struct pps_fetch_args *fapi, struct pps_state *pps)
1513 pps_seq_t aseq, cseq;
1516 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1520 * If no timeout is requested, immediately return whatever values were
1521 * most recently captured. If timeout seconds is -1, that's a request
1522 * to block without a timeout. WITNESS won't let us sleep forever
1523 * without a lock (we really don't need a lock), so just repeatedly
1524 * sleep a long time.
1526 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec) {
1527 if (fapi->timeout.tv_sec == -1)
1530 tv.tv_sec = fapi->timeout.tv_sec;
1531 tv.tv_usec = fapi->timeout.tv_nsec / 1000;
1534 aseq = pps->ppsinfo.assert_sequence;
1535 cseq = pps->ppsinfo.clear_sequence;
1536 while (aseq == pps->ppsinfo.assert_sequence &&
1537 cseq == pps->ppsinfo.clear_sequence) {
1538 if (abi_aware(pps, 1) && pps->driver_mtx != NULL) {
1539 if (pps->flags & PPSFLAG_MTX_SPIN) {
1540 err = msleep_spin(pps, pps->driver_mtx,
1543 err = msleep(pps, pps->driver_mtx, PCATCH,
1547 err = tsleep(pps, PCATCH, "ppsfch", timo);
1549 if (err == EWOULDBLOCK && fapi->timeout.tv_sec == -1) {
1551 } else if (err != 0) {
1557 pps->ppsinfo.current_mode = pps->ppsparam.mode;
1558 fapi->pps_info_buf = pps->ppsinfo;
1564 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
1567 struct pps_fetch_args *fapi;
1569 struct pps_fetch_ffc_args *fapi_ffc;
1572 struct pps_kcbind_args *kapi;
1575 KASSERT(pps != NULL, ("NULL pps pointer in pps_ioctl"));
1577 case PPS_IOC_CREATE:
1579 case PPS_IOC_DESTROY:
1581 case PPS_IOC_SETPARAMS:
1582 app = (pps_params_t *)data;
1583 if (app->mode & ~pps->ppscap)
1586 /* Ensure only a single clock is selected for ffc timestamp. */
1587 if ((app->mode & PPS_TSCLK_MASK) == PPS_TSCLK_MASK)
1590 pps->ppsparam = *app;
1592 case PPS_IOC_GETPARAMS:
1593 app = (pps_params_t *)data;
1594 *app = pps->ppsparam;
1595 app->api_version = PPS_API_VERS_1;
1597 case PPS_IOC_GETCAP:
1598 *(int*)data = pps->ppscap;
1601 fapi = (struct pps_fetch_args *)data;
1602 return (pps_fetch(fapi, pps));
1604 case PPS_IOC_FETCH_FFCOUNTER:
1605 fapi_ffc = (struct pps_fetch_ffc_args *)data;
1606 if (fapi_ffc->tsformat && fapi_ffc->tsformat !=
1609 if (fapi_ffc->timeout.tv_sec || fapi_ffc->timeout.tv_nsec)
1610 return (EOPNOTSUPP);
1611 pps->ppsinfo_ffc.current_mode = pps->ppsparam.mode;
1612 fapi_ffc->pps_info_buf_ffc = pps->ppsinfo_ffc;
1613 /* Overwrite timestamps if feedback clock selected. */
1614 switch (pps->ppsparam.mode & PPS_TSCLK_MASK) {
1615 case PPS_TSCLK_FBCK:
1616 fapi_ffc->pps_info_buf_ffc.assert_timestamp =
1617 pps->ppsinfo.assert_timestamp;
1618 fapi_ffc->pps_info_buf_ffc.clear_timestamp =
1619 pps->ppsinfo.clear_timestamp;
1621 case PPS_TSCLK_FFWD:
1627 #endif /* FFCLOCK */
1628 case PPS_IOC_KCBIND:
1630 kapi = (struct pps_kcbind_args *)data;
1631 /* XXX Only root should be able to do this */
1632 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1634 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1636 if (kapi->edge & ~pps->ppscap)
1638 pps->kcmode = (kapi->edge & KCMODE_EDGEMASK) |
1639 (pps->kcmode & KCMODE_ABIFLAG);
1642 return (EOPNOTSUPP);
1650 pps_init(struct pps_state *pps)
1652 pps->ppscap |= PPS_TSFMT_TSPEC | PPS_CANWAIT;
1653 if (pps->ppscap & PPS_CAPTUREASSERT)
1654 pps->ppscap |= PPS_OFFSETASSERT;
1655 if (pps->ppscap & PPS_CAPTURECLEAR)
1656 pps->ppscap |= PPS_OFFSETCLEAR;
1658 pps->ppscap |= PPS_TSCLK_MASK;
1660 pps->kcmode &= ~KCMODE_ABIFLAG;
1664 pps_init_abi(struct pps_state *pps)
1668 if (pps->driver_abi > 0) {
1669 pps->kcmode |= KCMODE_ABIFLAG;
1670 pps->kernel_abi = PPS_ABI_VERSION;
1675 pps_capture(struct pps_state *pps)
1677 struct timehands *th;
1679 KASSERT(pps != NULL, ("NULL pps pointer in pps_capture"));
1681 pps->capgen = tc_getgen(th);
1684 pps->capffth = fftimehands;
1686 pps->capcount = th->th_counter->tc_get_timecount(th->th_counter);
1687 if (pps->capgen != tc_getgen(th))
1692 pps_event(struct pps_state *pps, int event)
1695 struct timespec ts, *tsp, *osp;
1696 u_int tcount, *pcount;
1700 struct timespec *tsp_ffc;
1701 pps_seq_t *pseq_ffc;
1705 KASSERT(pps != NULL, ("NULL pps pointer in pps_event"));
1706 /* If the timecounter was wound up underneath us, bail out. */
1707 if (pps->capgen == 0 || pps->capgen != tc_getgen(pps->capth))
1710 /* Things would be easier with arrays. */
1711 if (event == PPS_CAPTUREASSERT) {
1712 tsp = &pps->ppsinfo.assert_timestamp;
1713 osp = &pps->ppsparam.assert_offset;
1714 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1715 fhard = pps->kcmode & PPS_CAPTUREASSERT;
1716 pcount = &pps->ppscount[0];
1717 pseq = &pps->ppsinfo.assert_sequence;
1719 ffcount = &pps->ppsinfo_ffc.assert_ffcount;
1720 tsp_ffc = &pps->ppsinfo_ffc.assert_timestamp;
1721 pseq_ffc = &pps->ppsinfo_ffc.assert_sequence;
1724 tsp = &pps->ppsinfo.clear_timestamp;
1725 osp = &pps->ppsparam.clear_offset;
1726 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1727 fhard = pps->kcmode & PPS_CAPTURECLEAR;
1728 pcount = &pps->ppscount[1];
1729 pseq = &pps->ppsinfo.clear_sequence;
1731 ffcount = &pps->ppsinfo_ffc.clear_ffcount;
1732 tsp_ffc = &pps->ppsinfo_ffc.clear_timestamp;
1733 pseq_ffc = &pps->ppsinfo_ffc.clear_sequence;
1738 * If the timecounter changed, we cannot compare the count values, so
1739 * we have to drop the rest of the PPS-stuff until the next event.
1741 if (pps->ppstc != pps->capth->th_counter) {
1742 pps->ppstc = pps->capth->th_counter;
1743 *pcount = pps->capcount;
1744 pps->ppscount[2] = pps->capcount;
1748 /* Convert the count to a timespec. */
1749 tcount = pps->capcount - pps->capth->th_offset_count;
1750 tcount &= pps->capth->th_counter->tc_counter_mask;
1751 bt = pps->capth->th_offset;
1752 bintime_addx(&bt, pps->capth->th_scale * tcount);
1753 bintime_add(&bt, &boottimebin);
1754 bintime2timespec(&bt, &ts);
1756 /* If the timecounter was wound up underneath us, bail out. */
1757 if (pps->capgen != tc_getgen(pps->capth))
1760 *pcount = pps->capcount;
1765 timespecadd(tsp, osp);
1766 if (tsp->tv_nsec < 0) {
1767 tsp->tv_nsec += 1000000000;
1773 *ffcount = pps->capffth->tick_ffcount + tcount;
1774 bt = pps->capffth->tick_time;
1775 ffclock_convert_delta(tcount, pps->capffth->cest.period, &bt);
1776 bintime_add(&bt, &pps->capffth->tick_time);
1777 bintime2timespec(&bt, &ts);
1787 * Feed the NTP PLL/FLL.
1788 * The FLL wants to know how many (hardware) nanoseconds
1789 * elapsed since the previous event.
1791 tcount = pps->capcount - pps->ppscount[2];
1792 pps->ppscount[2] = pps->capcount;
1793 tcount &= pps->capth->th_counter->tc_counter_mask;
1794 scale = (uint64_t)1 << 63;
1795 scale /= pps->capth->th_counter->tc_frequency;
1799 bintime_addx(&bt, scale * tcount);
1800 bintime2timespec(&bt, &ts);
1801 hardpps(tsp, ts.tv_nsec + 1000000000 * ts.tv_sec);
1805 /* Wakeup anyone sleeping in pps_fetch(). */
1810 * Timecounters need to be updated every so often to prevent the hardware
1811 * counter from overflowing. Updating also recalculates the cached values
1812 * used by the get*() family of functions, so their precision depends on
1813 * the update frequency.
1817 SYSCTL_INT(_kern_timecounter, OID_AUTO, tick, CTLFLAG_RD, &tc_tick, 0,
1818 "Approximate number of hardclock ticks in a millisecond");
1821 tc_ticktock(int cnt)
1826 if (count < tc_tick)
1832 static void __inline
1833 tc_adjprecision(void)
1837 if (tc_timepercentage > 0) {
1838 t = (99 + tc_timepercentage) / tc_timepercentage;
1839 tc_precexp = fls(t + (t >> 1)) - 1;
1840 FREQ2BT(hz / tc_tick, &bt_timethreshold);
1841 FREQ2BT(hz, &bt_tickthreshold);
1842 bintime_shift(&bt_timethreshold, tc_precexp);
1843 bintime_shift(&bt_tickthreshold, tc_precexp);
1846 bt_timethreshold.sec = INT_MAX;
1847 bt_timethreshold.frac = ~(uint64_t)0;
1848 bt_tickthreshold = bt_timethreshold;
1850 sbt_timethreshold = bttosbt(bt_timethreshold);
1851 sbt_tickthreshold = bttosbt(bt_tickthreshold);
1855 sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS)
1859 val = tc_timepercentage;
1860 error = sysctl_handle_int(oidp, &val, 0, req);
1861 if (error != 0 || req->newptr == NULL)
1863 tc_timepercentage = val;
1872 inittimecounter(void *dummy)
1878 * Set the initial timeout to
1879 * max(1, <approx. number of hardclock ticks in a millisecond>).
1880 * People should probably not use the sysctl to set the timeout
1881 * to smaller than its inital value, since that value is the
1882 * smallest reasonable one. If they want better timestamps they
1883 * should use the non-"get"* functions.
1886 tc_tick = (hz + 500) / 1000;
1890 FREQ2BT(hz, &tick_bt);
1891 tick_sbt = bttosbt(tick_bt);
1892 tick_rate = hz / tc_tick;
1893 FREQ2BT(tick_rate, &tc_tick_bt);
1894 tc_tick_sbt = bttosbt(tc_tick_bt);
1895 p = (tc_tick * 1000000) / hz;
1896 printf("Timecounters tick every %d.%03u msec\n", p / 1000, p % 1000);
1901 /* warm up new timecounter (again) and get rolling. */
1902 (void)timecounter->tc_get_timecount(timecounter);
1903 (void)timecounter->tc_get_timecount(timecounter);
1907 SYSINIT(timecounter, SI_SUB_CLOCKS, SI_ORDER_SECOND, inittimecounter, NULL);
1909 /* Cpu tick handling -------------------------------------------------*/
1911 static int cpu_tick_variable;
1912 static uint64_t cpu_tick_frequency;
1917 static uint64_t base;
1918 static unsigned last;
1920 struct timecounter *tc;
1922 tc = timehands->th_counter;
1923 u = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
1925 base += (uint64_t)tc->tc_counter_mask + 1;
1931 cpu_tick_calibration(void)
1933 static time_t last_calib;
1935 if (time_uptime != last_calib && !(time_uptime & 0xf)) {
1936 cpu_tick_calibrate(0);
1937 last_calib = time_uptime;
1942 * This function gets called every 16 seconds on only one designated
1943 * CPU in the system from hardclock() via cpu_tick_calibration()().
1945 * Whenever the real time clock is stepped we get called with reset=1
1946 * to make sure we handle suspend/resume and similar events correctly.
1950 cpu_tick_calibrate(int reset)
1952 static uint64_t c_last;
1953 uint64_t c_this, c_delta;
1954 static struct bintime t_last;
1955 struct bintime t_this, t_delta;
1959 /* The clock was stepped, abort & reset */
1964 /* we don't calibrate fixed rate cputicks */
1965 if (!cpu_tick_variable)
1968 getbinuptime(&t_this);
1969 c_this = cpu_ticks();
1970 if (t_last.sec != 0) {
1971 c_delta = c_this - c_last;
1973 bintime_sub(&t_delta, &t_last);
1976 * 2^(64-20) / 16[s] =
1978 * 17.592.186.044.416 / 16 =
1979 * 1.099.511.627.776 [Hz]
1981 divi = t_delta.sec << 20;
1982 divi |= t_delta.frac >> (64 - 20);
1985 if (c_delta > cpu_tick_frequency) {
1986 if (0 && bootverbose)
1987 printf("cpu_tick increased to %ju Hz\n",
1989 cpu_tick_frequency = c_delta;
1997 set_cputicker(cpu_tick_f *func, uint64_t freq, unsigned var)
2001 cpu_ticks = tc_cpu_ticks;
2003 cpu_tick_frequency = freq;
2004 cpu_tick_variable = var;
2013 if (cpu_ticks == tc_cpu_ticks)
2014 return (tc_getfrequency());
2015 return (cpu_tick_frequency);
2019 * We need to be slightly careful converting cputicks to microseconds.
2020 * There is plenty of margin in 64 bits of microseconds (half a million
2021 * years) and in 64 bits at 4 GHz (146 years), but if we do a multiply
2022 * before divide conversion (to retain precision) we find that the
2023 * margin shrinks to 1.5 hours (one millionth of 146y).
2024 * With a three prong approach we never lose significant bits, no
2025 * matter what the cputick rate and length of timeinterval is.
2029 cputick2usec(uint64_t tick)
2032 if (tick > 18446744073709551LL) /* floor(2^64 / 1000) */
2033 return (tick / (cpu_tickrate() / 1000000LL));
2034 else if (tick > 18446744073709LL) /* floor(2^64 / 1000000) */
2035 return ((tick * 1000LL) / (cpu_tickrate() / 1000LL));
2037 return ((tick * 1000000LL) / cpu_tickrate());
2040 cpu_tick_f *cpu_ticks = tc_cpu_ticks;
2042 static int vdso_th_enable = 1;
2044 sysctl_fast_gettime(SYSCTL_HANDLER_ARGS)
2046 int old_vdso_th_enable, error;
2048 old_vdso_th_enable = vdso_th_enable;
2049 error = sysctl_handle_int(oidp, &old_vdso_th_enable, 0, req);
2052 vdso_th_enable = old_vdso_th_enable;
2055 SYSCTL_PROC(_kern_timecounter, OID_AUTO, fast_gettime,
2056 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
2057 NULL, 0, sysctl_fast_gettime, "I", "Enable fast time of day");
2060 tc_fill_vdso_timehands(struct vdso_timehands *vdso_th)
2062 struct timehands *th;
2066 vdso_th->th_algo = VDSO_TH_ALGO_1;
2067 vdso_th->th_scale = th->th_scale;
2068 vdso_th->th_offset_count = th->th_offset_count;
2069 vdso_th->th_counter_mask = th->th_counter->tc_counter_mask;
2070 vdso_th->th_offset = th->th_offset;
2071 vdso_th->th_boottime = boottimebin;
2072 enabled = cpu_fill_vdso_timehands(vdso_th, th->th_counter);
2073 if (!vdso_th_enable)
2078 #ifdef COMPAT_FREEBSD32
2080 tc_fill_vdso_timehands32(struct vdso_timehands32 *vdso_th32)
2082 struct timehands *th;
2086 vdso_th32->th_algo = VDSO_TH_ALGO_1;
2087 *(uint64_t *)&vdso_th32->th_scale[0] = th->th_scale;
2088 vdso_th32->th_offset_count = th->th_offset_count;
2089 vdso_th32->th_counter_mask = th->th_counter->tc_counter_mask;
2090 vdso_th32->th_offset.sec = th->th_offset.sec;
2091 *(uint64_t *)&vdso_th32->th_offset.frac[0] = th->th_offset.frac;
2092 vdso_th32->th_boottime.sec = boottimebin.sec;
2093 *(uint64_t *)&vdso_th32->th_boottime.frac[0] = boottimebin.frac;
2094 enabled = cpu_fill_vdso_timehands32(vdso_th32, th->th_counter);
2095 if (!vdso_th_enable)