2 * SPDX-License-Identifier: Beerware
4 * ----------------------------------------------------------------------------
5 * "THE BEER-WARE LICENSE" (Revision 42):
6 * <phk@FreeBSD.ORG> wrote this file. As long as you retain this notice you
7 * can do whatever you want with this stuff. If we meet some day, and you think
8 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
9 * ----------------------------------------------------------------------------
11 * Copyright (c) 2011, 2015, 2016 The FreeBSD Foundation
13 * Portions of this software were developed by Julien Ridoux at the University
14 * of Melbourne under sponsorship from the FreeBSD Foundation.
16 * Portions of this software were developed by Konstantin Belousov
17 * under sponsorship from the FreeBSD Foundation.
20 #include <sys/cdefs.h>
22 #include "opt_ffclock.h"
24 #include <sys/param.h>
25 #include <sys/kernel.h>
26 #include <sys/limits.h>
28 #include <sys/mutex.h>
31 #include <sys/sleepqueue.h>
32 #include <sys/sysctl.h>
33 #include <sys/syslog.h>
34 #include <sys/systm.h>
35 #include <sys/timeffc.h>
36 #include <sys/timepps.h>
37 #include <sys/timerfd.h>
38 #include <sys/timetc.h>
39 #include <sys/timex.h>
43 * A large step happens on boot. This constant detects such steps.
44 * It is relatively small so that ntp_update_second gets called enough
45 * in the typical 'missed a couple of seconds' case, but doesn't loop
46 * forever when the time step is large.
48 #define LARGE_STEP 200
51 * Implement a dummy timecounter which we can use until we get a real one
52 * in the air. This allows the console and other early stuff to use
57 dummy_get_timecount(struct timecounter *tc)
64 static struct timecounter dummy_timecounter = {
65 dummy_get_timecount, 0, ~0u, 1000000, "dummy", -1000000
69 /* These fields must be initialized by the driver. */
70 struct timecounter *th_counter;
71 int64_t th_adjustment;
74 u_int th_offset_count;
75 struct bintime th_offset;
76 struct bintime th_bintime;
77 struct timeval th_microtime;
78 struct timespec th_nanotime;
79 struct bintime th_boottime;
80 /* Fields not to be copied in tc_windup start with th_generation. */
82 struct timehands *th_next;
85 static struct timehands ths[16] = {
87 .th_counter = &dummy_timecounter,
88 .th_scale = (uint64_t)-1 / 1000000,
89 .th_large_delta = 1000000,
90 .th_offset = { .sec = 1 },
95 static struct timehands *volatile timehands = &ths[0];
96 struct timecounter *timecounter = &dummy_timecounter;
97 static struct timecounter *timecounters = &dummy_timecounter;
99 /* Mutex to protect the timecounter list. */
100 static struct mtx tc_lock;
102 int tc_min_ticktock_freq = 1;
104 volatile time_t time_second = 1;
105 volatile time_t time_uptime = 1;
108 * The system time is always computed by summing the estimated boot time and the
109 * system uptime. The timehands track boot time, but it changes when the system
110 * time is set by the user, stepped by ntpd or adjusted when resuming. It
111 * is set to new_time - uptime.
113 static int sysctl_kern_boottime(SYSCTL_HANDLER_ARGS);
114 SYSCTL_PROC(_kern, KERN_BOOTTIME, boottime,
115 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
116 sysctl_kern_boottime, "S,timeval",
117 "Estimated system boottime");
119 SYSCTL_NODE(_kern, OID_AUTO, timecounter, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
121 static SYSCTL_NODE(_kern_timecounter, OID_AUTO, tc,
122 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
125 static int timestepwarnings;
126 SYSCTL_INT(_kern_timecounter, OID_AUTO, stepwarnings, CTLFLAG_RWTUN,
127 ×tepwarnings, 0, "Log time steps");
129 static int timehands_count = 2;
130 SYSCTL_INT(_kern_timecounter, OID_AUTO, timehands_count,
131 CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
132 &timehands_count, 0, "Count of timehands in rotation");
134 struct bintime bt_timethreshold;
135 struct bintime bt_tickthreshold;
136 sbintime_t sbt_timethreshold;
137 sbintime_t sbt_tickthreshold;
138 struct bintime tc_tick_bt;
139 sbintime_t tc_tick_sbt;
141 int tc_timepercentage = TC_DEFAULTPERC;
142 static int sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS);
143 SYSCTL_PROC(_kern_timecounter, OID_AUTO, alloweddeviation,
144 CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, 0, 0,
145 sysctl_kern_timecounter_adjprecision, "I",
146 "Allowed time interval deviation in percents");
148 volatile int rtc_generation = 1;
150 static int tc_chosen; /* Non-zero if a specific tc was chosen via sysctl. */
151 static char tc_from_tunable[16];
153 static void tc_windup(struct bintime *new_boottimebin);
154 static void cpu_tick_calibrate(int);
156 void dtrace_getnanotime(struct timespec *tsp);
157 void dtrace_getnanouptime(struct timespec *tsp);
160 sysctl_kern_boottime(SYSCTL_HANDLER_ARGS)
162 struct timeval boottime;
164 getboottime(&boottime);
166 /* i386 is the only arch which uses a 32bits time_t */
171 if (req->flags & SCTL_MASK32) {
172 tv[0] = boottime.tv_sec;
173 tv[1] = boottime.tv_usec;
174 return (SYSCTL_OUT(req, tv, sizeof(tv)));
178 return (SYSCTL_OUT(req, &boottime, sizeof(boottime)));
182 sysctl_kern_timecounter_get(SYSCTL_HANDLER_ARGS)
185 struct timecounter *tc = arg1;
187 ncount = tc->tc_get_timecount(tc);
188 return (sysctl_handle_int(oidp, &ncount, 0, req));
192 sysctl_kern_timecounter_freq(SYSCTL_HANDLER_ARGS)
195 struct timecounter *tc = arg1;
197 freq = tc->tc_frequency;
198 return (sysctl_handle_64(oidp, &freq, 0, req));
202 * Return the difference between the timehands' counter value now and what
203 * was when we copied it to the timehands' offset_count.
205 static __inline u_int
206 tc_delta(struct timehands *th)
208 struct timecounter *tc;
211 return ((tc->tc_get_timecount(tc) - th->th_offset_count) &
212 tc->tc_counter_mask);
216 bintime_add_tc_delta(struct bintime *bt, uint64_t scale,
217 uint64_t large_delta, uint64_t delta)
221 if (__predict_false(delta >= large_delta)) {
222 /* Avoid overflow for scale * delta. */
223 x = (scale >> 32) * delta;
225 bintime_addx(bt, x << 32);
226 bintime_addx(bt, (scale & 0xffffffff) * delta);
228 bintime_addx(bt, scale * delta);
233 * Functions for reading the time. We have to loop until we are sure that
234 * the timehands that we operated on was not updated under our feet. See
235 * the comment in <sys/time.h> for a description of these 12 functions.
239 bintime_off(struct bintime *bt, u_int off)
241 struct timehands *th;
244 u_int delta, gen, large_delta;
248 gen = atomic_load_acq_int(&th->th_generation);
249 btp = (struct bintime *)((vm_offset_t)th + off);
251 scale = th->th_scale;
252 delta = tc_delta(th);
253 large_delta = th->th_large_delta;
254 atomic_thread_fence_acq();
255 } while (gen == 0 || gen != th->th_generation);
257 bintime_add_tc_delta(bt, scale, large_delta, delta);
259 #define GETTHBINTIME(dst, member) \
261 _Static_assert(_Generic(((struct timehands *)NULL)->member, \
262 struct bintime: 1, default: 0) == 1, \
263 "struct timehands member is not of struct bintime type"); \
264 bintime_off(dst, __offsetof(struct timehands, member)); \
268 getthmember(void *out, size_t out_size, u_int off)
270 struct timehands *th;
275 gen = atomic_load_acq_int(&th->th_generation);
276 memcpy(out, (char *)th + off, out_size);
277 atomic_thread_fence_acq();
278 } while (gen == 0 || gen != th->th_generation);
280 #define GETTHMEMBER(dst, member) \
282 _Static_assert(_Generic(*dst, \
283 __typeof(((struct timehands *)NULL)->member): 1, \
285 "*dst and struct timehands member have different types"); \
286 getthmember(dst, sizeof(*dst), __offsetof(struct timehands, \
292 fbclock_binuptime(struct bintime *bt)
295 GETTHBINTIME(bt, th_offset);
299 fbclock_nanouptime(struct timespec *tsp)
303 fbclock_binuptime(&bt);
304 bintime2timespec(&bt, tsp);
308 fbclock_microuptime(struct timeval *tvp)
312 fbclock_binuptime(&bt);
313 bintime2timeval(&bt, tvp);
317 fbclock_bintime(struct bintime *bt)
320 GETTHBINTIME(bt, th_bintime);
324 fbclock_nanotime(struct timespec *tsp)
328 fbclock_bintime(&bt);
329 bintime2timespec(&bt, tsp);
333 fbclock_microtime(struct timeval *tvp)
337 fbclock_bintime(&bt);
338 bintime2timeval(&bt, tvp);
342 fbclock_getbinuptime(struct bintime *bt)
345 GETTHMEMBER(bt, th_offset);
349 fbclock_getnanouptime(struct timespec *tsp)
353 GETTHMEMBER(&bt, th_offset);
354 bintime2timespec(&bt, tsp);
358 fbclock_getmicrouptime(struct timeval *tvp)
362 GETTHMEMBER(&bt, th_offset);
363 bintime2timeval(&bt, tvp);
367 fbclock_getbintime(struct bintime *bt)
370 GETTHMEMBER(bt, th_bintime);
374 fbclock_getnanotime(struct timespec *tsp)
377 GETTHMEMBER(tsp, th_nanotime);
381 fbclock_getmicrotime(struct timeval *tvp)
384 GETTHMEMBER(tvp, th_microtime);
389 binuptime(struct bintime *bt)
392 GETTHBINTIME(bt, th_offset);
396 nanouptime(struct timespec *tsp)
401 bintime2timespec(&bt, tsp);
405 microuptime(struct timeval *tvp)
410 bintime2timeval(&bt, tvp);
414 bintime(struct bintime *bt)
417 GETTHBINTIME(bt, th_bintime);
421 nanotime(struct timespec *tsp)
426 bintime2timespec(&bt, tsp);
430 microtime(struct timeval *tvp)
435 bintime2timeval(&bt, tvp);
439 getbinuptime(struct bintime *bt)
442 GETTHMEMBER(bt, th_offset);
446 getnanouptime(struct timespec *tsp)
450 GETTHMEMBER(&bt, th_offset);
451 bintime2timespec(&bt, tsp);
455 getmicrouptime(struct timeval *tvp)
459 GETTHMEMBER(&bt, th_offset);
460 bintime2timeval(&bt, tvp);
464 getbintime(struct bintime *bt)
467 GETTHMEMBER(bt, th_bintime);
471 getnanotime(struct timespec *tsp)
474 GETTHMEMBER(tsp, th_nanotime);
478 getmicrotime(struct timeval *tvp)
481 GETTHMEMBER(tvp, th_microtime);
486 getboottime(struct timeval *boottime)
488 struct bintime boottimebin;
490 getboottimebin(&boottimebin);
491 bintime2timeval(&boottimebin, boottime);
495 getboottimebin(struct bintime *boottimebin)
498 GETTHMEMBER(boottimebin, th_boottime);
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.
910 gen = atomic_load_acq_int(&th->th_generation);
912 delta = tc_delta(th);
913 *ffcount = ffth->tick_ffcount;
914 atomic_thread_fence_acq();
915 } while (gen == 0 || gen != th->th_generation);
921 binuptime(struct bintime *bt)
924 binuptime_fromclock(bt, sysclock_active);
928 nanouptime(struct timespec *tsp)
931 nanouptime_fromclock(tsp, sysclock_active);
935 microuptime(struct timeval *tvp)
938 microuptime_fromclock(tvp, sysclock_active);
942 bintime(struct bintime *bt)
945 bintime_fromclock(bt, sysclock_active);
949 nanotime(struct timespec *tsp)
952 nanotime_fromclock(tsp, sysclock_active);
956 microtime(struct timeval *tvp)
959 microtime_fromclock(tvp, sysclock_active);
963 getbinuptime(struct bintime *bt)
966 getbinuptime_fromclock(bt, sysclock_active);
970 getnanouptime(struct timespec *tsp)
973 getnanouptime_fromclock(tsp, sysclock_active);
977 getmicrouptime(struct timeval *tvp)
980 getmicrouptime_fromclock(tvp, sysclock_active);
984 getbintime(struct bintime *bt)
987 getbintime_fromclock(bt, sysclock_active);
991 getnanotime(struct timespec *tsp)
994 getnanotime_fromclock(tsp, sysclock_active);
998 getmicrotime(struct timeval *tvp)
1001 getmicrouptime_fromclock(tvp, sysclock_active);
1004 #endif /* FFCLOCK */
1007 * This is a clone of getnanotime and used for walltimestamps.
1008 * The dtrace_ prefix prevents fbt from creating probes for
1009 * it so walltimestamp can be safely used in all fbt probes.
1012 dtrace_getnanotime(struct timespec *tsp)
1015 GETTHMEMBER(tsp, th_nanotime);
1019 * This is a clone of getnanouptime used for time since boot.
1020 * The dtrace_ prefix prevents fbt from creating probes for
1021 * it so an uptime that can be safely used in all fbt probes.
1024 dtrace_getnanouptime(struct timespec *tsp)
1028 GETTHMEMBER(&bt, th_offset);
1029 bintime2timespec(&bt, tsp);
1033 * System clock currently providing time to the system. Modifiable via sysctl
1034 * when the FFCLOCK option is defined.
1036 int sysclock_active = SYSCLOCK_FBCK;
1038 /* Internal NTP status and error estimates. */
1039 extern int time_status;
1040 extern long time_esterror;
1043 * Take a snapshot of sysclock data which can be used to compare system clocks
1044 * and generate timestamps after the fact.
1047 sysclock_getsnapshot(struct sysclock_snap *clock_snap, int fast)
1049 struct fbclock_info *fbi;
1050 struct timehands *th;
1052 unsigned int delta, gen;
1055 struct fftimehands *ffth;
1056 struct ffclock_info *ffi;
1057 struct ffclock_estimate cest;
1059 ffi = &clock_snap->ff_info;
1062 fbi = &clock_snap->fb_info;
1067 gen = atomic_load_acq_int(&th->th_generation);
1068 fbi->th_scale = th->th_scale;
1069 fbi->tick_time = th->th_offset;
1072 ffi->tick_time = ffth->tick_time_lerp;
1073 ffi->tick_time_lerp = ffth->tick_time_lerp;
1074 ffi->period = ffth->cest.period;
1075 ffi->period_lerp = ffth->period_lerp;
1076 clock_snap->ffcount = ffth->tick_ffcount;
1080 delta = tc_delta(th);
1081 atomic_thread_fence_acq();
1082 } while (gen == 0 || gen != th->th_generation);
1084 clock_snap->delta = delta;
1085 clock_snap->sysclock_active = sysclock_active;
1087 /* Record feedback clock status and error. */
1088 clock_snap->fb_info.status = time_status;
1089 /* XXX: Very crude estimate of feedback clock error. */
1090 bt.sec = time_esterror / 1000000;
1091 bt.frac = ((time_esterror - bt.sec) * 1000000) *
1092 (uint64_t)18446744073709ULL;
1093 clock_snap->fb_info.error = bt;
1097 clock_snap->ffcount += delta;
1099 /* Record feed-forward clock leap second adjustment. */
1100 ffi->leapsec_adjustment = cest.leapsec_total;
1101 if (clock_snap->ffcount > cest.leapsec_next)
1102 ffi->leapsec_adjustment -= cest.leapsec;
1104 /* Record feed-forward clock status and error. */
1105 clock_snap->ff_info.status = cest.status;
1106 ffcount = clock_snap->ffcount - cest.update_ffcount;
1107 ffclock_convert_delta(ffcount, cest.period, &bt);
1108 /* 18446744073709 = int(2^64/1e12), err_bound_rate in [ps/s]. */
1109 bintime_mul(&bt, cest.errb_rate * (uint64_t)18446744073709ULL);
1110 /* 18446744073 = int(2^64 / 1e9), since err_abs in [ns]. */
1111 bintime_addx(&bt, cest.errb_abs * (uint64_t)18446744073ULL);
1112 clock_snap->ff_info.error = bt;
1117 * Convert a sysclock snapshot into a struct bintime based on the specified
1118 * clock source and flags.
1121 sysclock_snap2bintime(struct sysclock_snap *cs, struct bintime *bt,
1122 int whichclock, uint32_t flags)
1124 struct bintime boottimebin;
1130 switch (whichclock) {
1132 *bt = cs->fb_info.tick_time;
1134 /* If snapshot was created with !fast, delta will be >0. */
1136 bintime_addx(bt, cs->fb_info.th_scale * cs->delta);
1138 if ((flags & FBCLOCK_UPTIME) == 0) {
1139 getboottimebin(&boottimebin);
1140 bintime_add(bt, &boottimebin);
1145 if (flags & FFCLOCK_LERP) {
1146 *bt = cs->ff_info.tick_time_lerp;
1147 period = cs->ff_info.period_lerp;
1149 *bt = cs->ff_info.tick_time;
1150 period = cs->ff_info.period;
1153 /* If snapshot was created with !fast, delta will be >0. */
1154 if (cs->delta > 0) {
1155 ffclock_convert_delta(cs->delta, period, &bt2);
1156 bintime_add(bt, &bt2);
1159 /* Leap second adjustment. */
1160 if (flags & FFCLOCK_LEAPSEC)
1161 bt->sec -= cs->ff_info.leapsec_adjustment;
1163 /* Boot time adjustment, for uptime/monotonic clocks. */
1164 if (flags & FFCLOCK_UPTIME)
1165 bintime_sub(bt, &ffclock_boottime);
1177 * Initialize a new timecounter and possibly use it.
1180 tc_init(struct timecounter *tc)
1183 struct sysctl_oid *tc_root;
1185 u = tc->tc_frequency / tc->tc_counter_mask;
1186 /* XXX: We need some margin here, 10% is a guess */
1189 if (u > hz && tc->tc_quality >= 0) {
1190 tc->tc_quality = -2000;
1192 printf("Timecounter \"%s\" frequency %ju Hz",
1193 tc->tc_name, (uintmax_t)tc->tc_frequency);
1194 printf(" -- Insufficient hz, needs at least %u\n", u);
1196 } else if (tc->tc_quality >= 0 || bootverbose) {
1197 printf("Timecounter \"%s\" frequency %ju Hz quality %d\n",
1198 tc->tc_name, (uintmax_t)tc->tc_frequency,
1203 * Set up sysctl tree for this counter.
1205 tc_root = SYSCTL_ADD_NODE_WITH_LABEL(NULL,
1206 SYSCTL_STATIC_CHILDREN(_kern_timecounter_tc), OID_AUTO, tc->tc_name,
1207 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1208 "timecounter description", "timecounter");
1209 SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1210 "mask", CTLFLAG_RD, &(tc->tc_counter_mask), 0,
1211 "mask for implemented bits");
1212 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1213 "counter", CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, tc,
1214 sizeof(*tc), sysctl_kern_timecounter_get, "IU",
1215 "current timecounter value");
1216 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1217 "frequency", CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, tc,
1218 sizeof(*tc), sysctl_kern_timecounter_freq, "QU",
1219 "timecounter frequency");
1220 SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1221 "quality", CTLFLAG_RD, &(tc->tc_quality), 0,
1222 "goodness of time counter");
1225 tc->tc_next = timecounters;
1229 * Do not automatically switch if the current tc was specifically
1230 * chosen. Never automatically use a timecounter with negative quality.
1231 * Even though we run on the dummy counter, switching here may be
1232 * worse since this timecounter may not be monotonic.
1236 if (tc->tc_quality < 0)
1238 if (tc_from_tunable[0] != '\0' &&
1239 strcmp(tc->tc_name, tc_from_tunable) == 0) {
1241 tc_from_tunable[0] = '\0';
1243 if (tc->tc_quality < timecounter->tc_quality)
1245 if (tc->tc_quality == timecounter->tc_quality &&
1246 tc->tc_frequency < timecounter->tc_frequency)
1249 (void)tc->tc_get_timecount(tc);
1252 mtx_unlock(&tc_lock);
1255 /* Report the frequency of the current timecounter. */
1257 tc_getfrequency(void)
1260 return (timehands->th_counter->tc_frequency);
1264 sleeping_on_old_rtc(struct thread *td)
1268 * td_rtcgen is modified by curthread when it is running,
1269 * and by other threads in this function. By finding the thread
1270 * on a sleepqueue and holding the lock on the sleepqueue
1271 * chain, we guarantee that the thread is not running and that
1272 * modifying td_rtcgen is safe. Setting td_rtcgen to zero informs
1273 * the thread that it was woken due to a real-time clock adjustment.
1274 * (The declaration of td_rtcgen refers to this comment.)
1276 if (td->td_rtcgen != 0 && td->td_rtcgen != rtc_generation) {
1283 static struct mtx tc_setclock_mtx;
1284 MTX_SYSINIT(tc_setclock_init, &tc_setclock_mtx, "tcsetc", MTX_SPIN);
1287 * Step our concept of UTC. This is done by modifying our estimate of
1291 tc_setclock(struct timespec *ts)
1293 struct timespec tbef, taft;
1294 struct bintime bt, bt2;
1296 timespec2bintime(ts, &bt);
1298 mtx_lock_spin(&tc_setclock_mtx);
1299 cpu_tick_calibrate(1);
1301 bintime_sub(&bt, &bt2);
1303 /* XXX fiddle all the little crinkly bits around the fiords... */
1305 mtx_unlock_spin(&tc_setclock_mtx);
1307 /* Avoid rtc_generation == 0, since td_rtcgen == 0 is special. */
1308 atomic_add_rel_int(&rtc_generation, 2);
1310 sleepq_chains_remove_matching(sleeping_on_old_rtc);
1311 if (timestepwarnings) {
1314 "Time stepped from %jd.%09ld to %jd.%09ld (%jd.%09ld)\n",
1315 (intmax_t)tbef.tv_sec, tbef.tv_nsec,
1316 (intmax_t)taft.tv_sec, taft.tv_nsec,
1317 (intmax_t)ts->tv_sec, ts->tv_nsec);
1322 * Recalculate the scaling factor. We want the number of 1/2^64
1323 * fractions of a second per period of the hardware counter, taking
1324 * into account the th_adjustment factor which the NTP PLL/adjtime(2)
1325 * processing provides us with.
1327 * The th_adjustment is nanoseconds per second with 32 bit binary
1328 * fraction and we want 64 bit binary fraction of second:
1330 * x = a * 2^32 / 10^9 = a * 4.294967296
1332 * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
1333 * we can only multiply by about 850 without overflowing, that
1334 * leaves no suitably precise fractions for multiply before divide.
1336 * Divide before multiply with a fraction of 2199/512 results in a
1337 * systematic undercompensation of 10PPM of th_adjustment. On a
1338 * 5000PPM adjustment this is a 0.05PPM error. This is acceptable.
1340 * We happily sacrifice the lowest of the 64 bits of our result
1341 * to the goddess of code clarity.
1344 recalculate_scaling_factor_and_large_delta(struct timehands *th)
1348 scale = (uint64_t)1 << 63;
1349 scale += (th->th_adjustment / 1024) * 2199;
1350 scale /= th->th_counter->tc_frequency;
1351 th->th_scale = scale * 2;
1352 th->th_large_delta = MIN(((uint64_t)1 << 63) / scale, UINT_MAX);
1356 * Initialize the next struct timehands in the ring and make
1357 * it the active timehands. Along the way we might switch to a different
1358 * timecounter and/or do seconds processing in NTP. Slightly magic.
1361 tc_windup(struct bintime *new_boottimebin)
1364 struct timecounter *tc;
1365 struct timehands *th, *tho;
1366 u_int delta, ncount, ogen;
1371 * Make the next timehands a copy of the current one, but do
1372 * not overwrite the generation or next pointer. While we
1373 * update the contents, the generation must be zero. We need
1374 * to ensure that the zero generation is visible before the
1375 * data updates become visible, which requires release fence.
1376 * For similar reasons, re-reading of the generation after the
1377 * data is read should use acquire fence.
1381 ogen = th->th_generation;
1382 th->th_generation = 0;
1383 atomic_thread_fence_rel();
1384 memcpy(th, tho, offsetof(struct timehands, th_generation));
1385 if (new_boottimebin != NULL)
1386 th->th_boottime = *new_boottimebin;
1389 * Capture a timecounter delta on the current timecounter and if
1390 * changing timecounters, a counter value from the new timecounter.
1391 * Update the offset fields accordingly.
1393 tc = atomic_load_ptr(&timecounter);
1394 delta = tc_delta(th);
1395 if (th->th_counter != tc)
1396 ncount = tc->tc_get_timecount(tc);
1400 ffclock_windup(delta);
1402 th->th_offset_count += delta;
1403 th->th_offset_count &= th->th_counter->tc_counter_mask;
1404 bintime_add_tc_delta(&th->th_offset, th->th_scale,
1405 th->th_large_delta, delta);
1408 * Hardware latching timecounters may not generate interrupts on
1409 * PPS events, so instead we poll them. There is a finite risk that
1410 * the hardware might capture a count which is later than the one we
1411 * got above, and therefore possibly in the next NTP second which might
1412 * have a different rate than the current NTP second. It doesn't
1413 * matter in practice.
1415 if (tho->th_counter->tc_poll_pps)
1416 tho->th_counter->tc_poll_pps(tho->th_counter);
1419 * Deal with NTP second processing. The loop normally
1420 * iterates at most once, but in extreme situations it might
1421 * keep NTP sane if timeouts are not run for several seconds.
1422 * At boot, the time step can be large when the TOD hardware
1423 * has been read, so on really large steps, we call
1424 * ntp_update_second only twice. We need to call it twice in
1425 * case we missed a leap second.
1428 bintime_add(&bt, &th->th_boottime);
1429 i = bt.sec - tho->th_microtime.tv_sec;
1436 ntp_update_second(&th->th_adjustment, &bt.sec);
1438 th->th_boottime.sec += bt.sec - t;
1442 recalculate_scaling_factor_and_large_delta(th);
1445 /* Update the UTC timestamps used by the get*() functions. */
1446 th->th_bintime = bt;
1447 bintime2timeval(&bt, &th->th_microtime);
1448 bintime2timespec(&bt, &th->th_nanotime);
1450 /* Now is a good time to change timecounters. */
1451 if (th->th_counter != tc) {
1453 if ((tc->tc_flags & TC_FLAGS_C2STOP) != 0)
1454 cpu_disable_c2_sleep++;
1455 if ((th->th_counter->tc_flags & TC_FLAGS_C2STOP) != 0)
1456 cpu_disable_c2_sleep--;
1458 th->th_counter = tc;
1459 th->th_offset_count = ncount;
1460 tc_min_ticktock_freq = max(1, tc->tc_frequency /
1461 (((uint64_t)tc->tc_counter_mask + 1) / 3));
1462 recalculate_scaling_factor_and_large_delta(th);
1464 ffclock_change_tc(th);
1469 * Now that the struct timehands is again consistent, set the new
1470 * generation number, making sure to not make it zero.
1474 atomic_store_rel_int(&th->th_generation, ogen);
1476 /* Go live with the new struct timehands. */
1478 switch (sysclock_active) {
1481 time_second = th->th_microtime.tv_sec;
1482 time_uptime = th->th_offset.sec;
1486 time_second = fftimehands->tick_time_lerp.sec;
1487 time_uptime = fftimehands->tick_time_lerp.sec - ffclock_boottime.sec;
1493 timekeep_push_vdso();
1496 /* Report or change the active timecounter hardware. */
1498 sysctl_kern_timecounter_hardware(SYSCTL_HANDLER_ARGS)
1501 struct timecounter *newtc, *tc;
1506 strlcpy(newname, tc->tc_name, sizeof(newname));
1507 mtx_unlock(&tc_lock);
1509 error = sysctl_handle_string(oidp, &newname[0], sizeof(newname), req);
1510 if (error != 0 || req->newptr == NULL)
1514 /* Record that the tc in use now was specifically chosen. */
1516 if (strcmp(newname, tc->tc_name) == 0) {
1517 mtx_unlock(&tc_lock);
1520 for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
1521 if (strcmp(newname, newtc->tc_name) != 0)
1524 /* Warm up new timecounter. */
1525 (void)newtc->tc_get_timecount(newtc);
1527 timecounter = newtc;
1530 * The vdso timehands update is deferred until the next
1533 * This is prudent given that 'timekeep_push_vdso()' does not
1534 * use any locking and that it can be called in hard interrupt
1535 * context via 'tc_windup()'.
1539 mtx_unlock(&tc_lock);
1540 return (newtc != NULL ? 0 : EINVAL);
1542 SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware,
1543 CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, 0, 0,
1544 sysctl_kern_timecounter_hardware, "A",
1545 "Timecounter hardware selected");
1547 /* Report the available timecounter hardware. */
1549 sysctl_kern_timecounter_choice(SYSCTL_HANDLER_ARGS)
1552 struct timecounter *tc;
1555 error = sysctl_wire_old_buffer(req, 0);
1558 sbuf_new_for_sysctl(&sb, NULL, 0, req);
1560 for (tc = timecounters; tc != NULL; tc = tc->tc_next) {
1561 if (tc != timecounters)
1562 sbuf_putc(&sb, ' ');
1563 sbuf_printf(&sb, "%s(%d)", tc->tc_name, tc->tc_quality);
1565 mtx_unlock(&tc_lock);
1566 error = sbuf_finish(&sb);
1571 SYSCTL_PROC(_kern_timecounter, OID_AUTO, choice,
1572 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, 0, 0,
1573 sysctl_kern_timecounter_choice, "A",
1574 "Timecounter hardware detected");
1577 * RFC 2783 PPS-API implementation.
1581 * Return true if the driver is aware of the abi version extensions in the
1582 * pps_state structure, and it supports at least the given abi version number.
1585 abi_aware(struct pps_state *pps, int vers)
1588 return ((pps->kcmode & KCMODE_ABIFLAG) && pps->driver_abi >= vers);
1592 pps_fetch(struct pps_fetch_args *fapi, struct pps_state *pps)
1595 pps_seq_t aseq, cseq;
1598 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1602 * If no timeout is requested, immediately return whatever values were
1603 * most recently captured. If timeout seconds is -1, that's a request
1604 * to block without a timeout. WITNESS won't let us sleep forever
1605 * without a lock (we really don't need a lock), so just repeatedly
1606 * sleep a long time.
1608 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec) {
1609 if (fapi->timeout.tv_sec == -1)
1612 tv.tv_sec = fapi->timeout.tv_sec;
1613 tv.tv_usec = fapi->timeout.tv_nsec / 1000;
1616 aseq = atomic_load_int(&pps->ppsinfo.assert_sequence);
1617 cseq = atomic_load_int(&pps->ppsinfo.clear_sequence);
1618 while (aseq == atomic_load_int(&pps->ppsinfo.assert_sequence) &&
1619 cseq == atomic_load_int(&pps->ppsinfo.clear_sequence)) {
1620 if (abi_aware(pps, 1) && pps->driver_mtx != NULL) {
1621 if (pps->flags & PPSFLAG_MTX_SPIN) {
1622 err = msleep_spin(pps, pps->driver_mtx,
1625 err = msleep(pps, pps->driver_mtx, PCATCH,
1629 err = tsleep(pps, PCATCH, "ppsfch", timo);
1631 if (err == EWOULDBLOCK) {
1632 if (fapi->timeout.tv_sec == -1) {
1637 } else if (err != 0) {
1643 pps->ppsinfo.current_mode = pps->ppsparam.mode;
1644 fapi->pps_info_buf = pps->ppsinfo;
1650 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
1653 struct pps_fetch_args *fapi;
1655 struct pps_fetch_ffc_args *fapi_ffc;
1658 struct pps_kcbind_args *kapi;
1661 KASSERT(pps != NULL, ("NULL pps pointer in pps_ioctl"));
1663 case PPS_IOC_CREATE:
1665 case PPS_IOC_DESTROY:
1667 case PPS_IOC_SETPARAMS:
1668 app = (pps_params_t *)data;
1669 if (app->mode & ~pps->ppscap)
1672 /* Ensure only a single clock is selected for ffc timestamp. */
1673 if ((app->mode & PPS_TSCLK_MASK) == PPS_TSCLK_MASK)
1676 pps->ppsparam = *app;
1678 case PPS_IOC_GETPARAMS:
1679 app = (pps_params_t *)data;
1680 *app = pps->ppsparam;
1681 app->api_version = PPS_API_VERS_1;
1683 case PPS_IOC_GETCAP:
1684 *(int*)data = pps->ppscap;
1687 fapi = (struct pps_fetch_args *)data;
1688 return (pps_fetch(fapi, pps));
1690 case PPS_IOC_FETCH_FFCOUNTER:
1691 fapi_ffc = (struct pps_fetch_ffc_args *)data;
1692 if (fapi_ffc->tsformat && fapi_ffc->tsformat !=
1695 if (fapi_ffc->timeout.tv_sec || fapi_ffc->timeout.tv_nsec)
1696 return (EOPNOTSUPP);
1697 pps->ppsinfo_ffc.current_mode = pps->ppsparam.mode;
1698 fapi_ffc->pps_info_buf_ffc = pps->ppsinfo_ffc;
1699 /* Overwrite timestamps if feedback clock selected. */
1700 switch (pps->ppsparam.mode & PPS_TSCLK_MASK) {
1701 case PPS_TSCLK_FBCK:
1702 fapi_ffc->pps_info_buf_ffc.assert_timestamp =
1703 pps->ppsinfo.assert_timestamp;
1704 fapi_ffc->pps_info_buf_ffc.clear_timestamp =
1705 pps->ppsinfo.clear_timestamp;
1707 case PPS_TSCLK_FFWD:
1713 #endif /* FFCLOCK */
1714 case PPS_IOC_KCBIND:
1716 kapi = (struct pps_kcbind_args *)data;
1717 /* XXX Only root should be able to do this */
1718 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1720 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1722 if (kapi->edge & ~pps->ppscap)
1724 pps->kcmode = (kapi->edge & KCMODE_EDGEMASK) |
1725 (pps->kcmode & KCMODE_ABIFLAG);
1728 return (EOPNOTSUPP);
1736 pps_init(struct pps_state *pps)
1738 pps->ppscap |= PPS_TSFMT_TSPEC | PPS_CANWAIT;
1739 if (pps->ppscap & PPS_CAPTUREASSERT)
1740 pps->ppscap |= PPS_OFFSETASSERT;
1741 if (pps->ppscap & PPS_CAPTURECLEAR)
1742 pps->ppscap |= PPS_OFFSETCLEAR;
1744 pps->ppscap |= PPS_TSCLK_MASK;
1746 pps->kcmode &= ~KCMODE_ABIFLAG;
1750 pps_init_abi(struct pps_state *pps)
1754 if (pps->driver_abi > 0) {
1755 pps->kcmode |= KCMODE_ABIFLAG;
1756 pps->kernel_abi = PPS_ABI_VERSION;
1761 pps_capture(struct pps_state *pps)
1763 struct timehands *th;
1764 struct timecounter *tc;
1766 KASSERT(pps != NULL, ("NULL pps pointer in pps_capture"));
1768 pps->capgen = atomic_load_acq_int(&th->th_generation);
1771 pps->capffth = fftimehands;
1773 tc = th->th_counter;
1774 pps->capcount = tc->tc_get_timecount(tc);
1778 pps_event(struct pps_state *pps, int event)
1780 struct timehands *capth;
1781 struct timecounter *captc;
1782 uint64_t capth_scale;
1784 struct timespec *tsp, *osp;
1785 u_int tcount, *pcount;
1789 struct timespec *tsp_ffc;
1790 pps_seq_t *pseq_ffc;
1797 KASSERT(pps != NULL, ("NULL pps pointer in pps_event"));
1798 /* Nothing to do if not currently set to capture this event type. */
1799 if ((event & pps->ppsparam.mode) == 0)
1802 /* Make a snapshot of the captured timehand */
1804 captc = capth->th_counter;
1805 capth_scale = capth->th_scale;
1806 tcount = capth->th_offset_count;
1807 bt = capth->th_bintime;
1809 /* If the timecounter was wound up underneath us, bail out. */
1810 atomic_thread_fence_acq();
1811 if (pps->capgen == 0 || pps->capgen != capth->th_generation)
1814 /* Things would be easier with arrays. */
1815 if (event == PPS_CAPTUREASSERT) {
1816 tsp = &pps->ppsinfo.assert_timestamp;
1817 osp = &pps->ppsparam.assert_offset;
1818 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1820 fhard = pps->kcmode & PPS_CAPTUREASSERT;
1822 pcount = &pps->ppscount[0];
1823 pseq = &pps->ppsinfo.assert_sequence;
1825 ffcount = &pps->ppsinfo_ffc.assert_ffcount;
1826 tsp_ffc = &pps->ppsinfo_ffc.assert_timestamp;
1827 pseq_ffc = &pps->ppsinfo_ffc.assert_sequence;
1830 tsp = &pps->ppsinfo.clear_timestamp;
1831 osp = &pps->ppsparam.clear_offset;
1832 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1834 fhard = pps->kcmode & PPS_CAPTURECLEAR;
1836 pcount = &pps->ppscount[1];
1837 pseq = &pps->ppsinfo.clear_sequence;
1839 ffcount = &pps->ppsinfo_ffc.clear_ffcount;
1840 tsp_ffc = &pps->ppsinfo_ffc.clear_timestamp;
1841 pseq_ffc = &pps->ppsinfo_ffc.clear_sequence;
1845 *pcount = pps->capcount;
1848 * If the timecounter changed, we cannot compare the count values, so
1849 * we have to drop the rest of the PPS-stuff until the next event.
1851 if (__predict_false(pps->ppstc != captc)) {
1853 pps->ppscount[2] = pps->capcount;
1859 /* Convert the count to a timespec. */
1860 tcount = pps->capcount - tcount;
1861 tcount &= captc->tc_counter_mask;
1862 bintime_addx(&bt, capth_scale * tcount);
1863 bintime2timespec(&bt, tsp);
1866 timespecadd(tsp, osp, tsp);
1867 if (tsp->tv_nsec < 0) {
1868 tsp->tv_nsec += 1000000000;
1874 *ffcount = pps->capffth->tick_ffcount + tcount;
1875 bt = pps->capffth->tick_time;
1876 ffclock_convert_delta(tcount, pps->capffth->cest.period, &bt);
1877 bintime_add(&bt, &pps->capffth->tick_time);
1879 bintime2timespec(&bt, tsp_ffc);
1884 uint64_t delta_nsec;
1888 * Feed the NTP PLL/FLL.
1889 * The FLL wants to know how many (hardware) nanoseconds
1890 * elapsed since the previous event.
1892 tcount = pps->capcount - pps->ppscount[2];
1893 pps->ppscount[2] = pps->capcount;
1894 tcount &= captc->tc_counter_mask;
1895 delta_nsec = 1000000000;
1896 delta_nsec *= tcount;
1897 freq = captc->tc_frequency;
1898 delta_nsec = (delta_nsec + freq / 2) / freq;
1899 hardpps(tsp, (long)delta_nsec);
1903 /* Wakeup anyone sleeping in pps_fetch(). */
1908 * Timecounters need to be updated every so often to prevent the hardware
1909 * counter from overflowing. Updating also recalculates the cached values
1910 * used by the get*() family of functions, so their precision depends on
1911 * the update frequency.
1915 SYSCTL_INT(_kern_timecounter, OID_AUTO, tick, CTLFLAG_RD, &tc_tick, 0,
1916 "Approximate number of hardclock ticks in a millisecond");
1919 tc_ticktock(int cnt)
1923 if (mtx_trylock_spin(&tc_setclock_mtx)) {
1925 if (count >= tc_tick) {
1929 mtx_unlock_spin(&tc_setclock_mtx);
1933 static void __inline
1934 tc_adjprecision(void)
1938 if (tc_timepercentage > 0) {
1939 t = (99 + tc_timepercentage) / tc_timepercentage;
1940 tc_precexp = fls(t + (t >> 1)) - 1;
1941 FREQ2BT(hz / tc_tick, &bt_timethreshold);
1942 FREQ2BT(hz, &bt_tickthreshold);
1943 bintime_shift(&bt_timethreshold, tc_precexp);
1944 bintime_shift(&bt_tickthreshold, tc_precexp);
1947 bt_timethreshold.sec = INT_MAX;
1948 bt_timethreshold.frac = ~(uint64_t)0;
1949 bt_tickthreshold = bt_timethreshold;
1951 sbt_timethreshold = bttosbt(bt_timethreshold);
1952 sbt_tickthreshold = bttosbt(bt_tickthreshold);
1956 sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS)
1960 val = tc_timepercentage;
1961 error = sysctl_handle_int(oidp, &val, 0, req);
1962 if (error != 0 || req->newptr == NULL)
1964 tc_timepercentage = val;
1972 /* Set up the requested number of timehands. */
1974 inittimehands(void *dummy)
1976 struct timehands *thp;
1979 TUNABLE_INT_FETCH("kern.timecounter.timehands_count",
1981 if (timehands_count < 1)
1982 timehands_count = 1;
1983 if (timehands_count > nitems(ths))
1984 timehands_count = nitems(ths);
1985 for (i = 1, thp = &ths[0]; i < timehands_count; thp = &ths[i++])
1986 thp->th_next = &ths[i];
1987 thp->th_next = &ths[0];
1989 TUNABLE_STR_FETCH("kern.timecounter.hardware", tc_from_tunable,
1990 sizeof(tc_from_tunable));
1992 mtx_init(&tc_lock, "tc", NULL, MTX_DEF);
1994 SYSINIT(timehands, SI_SUB_TUNABLES, SI_ORDER_ANY, inittimehands, NULL);
1997 inittimecounter(void *dummy)
2003 * Set the initial timeout to
2004 * max(1, <approx. number of hardclock ticks in a millisecond>).
2005 * People should probably not use the sysctl to set the timeout
2006 * to smaller than its initial value, since that value is the
2007 * smallest reasonable one. If they want better timestamps they
2008 * should use the non-"get"* functions.
2011 tc_tick = (hz + 500) / 1000;
2015 FREQ2BT(hz, &tick_bt);
2016 tick_sbt = bttosbt(tick_bt);
2017 tick_rate = hz / tc_tick;
2018 FREQ2BT(tick_rate, &tc_tick_bt);
2019 tc_tick_sbt = bttosbt(tc_tick_bt);
2020 p = (tc_tick * 1000000) / hz;
2021 printf("Timecounters tick every %d.%03u msec\n", p / 1000, p % 1000);
2027 /* warm up new timecounter (again) and get rolling. */
2028 (void)timecounter->tc_get_timecount(timecounter);
2029 mtx_lock_spin(&tc_setclock_mtx);
2031 mtx_unlock_spin(&tc_setclock_mtx);
2034 SYSINIT(timecounter, SI_SUB_CLOCKS, SI_ORDER_SECOND, inittimecounter, NULL);
2036 /* Cpu tick handling -------------------------------------------------*/
2038 static bool cpu_tick_variable;
2039 static uint64_t cpu_tick_frequency;
2041 DPCPU_DEFINE_STATIC(uint64_t, tc_cpu_ticks_base);
2042 DPCPU_DEFINE_STATIC(unsigned, tc_cpu_ticks_last);
2047 struct timecounter *tc;
2048 uint64_t res, *base;
2052 base = DPCPU_PTR(tc_cpu_ticks_base);
2053 last = DPCPU_PTR(tc_cpu_ticks_last);
2054 tc = timehands->th_counter;
2055 u = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
2057 *base += (uint64_t)tc->tc_counter_mask + 1;
2065 cpu_tick_calibration(void)
2067 static time_t last_calib;
2069 if (time_uptime != last_calib && !(time_uptime & 0xf)) {
2070 cpu_tick_calibrate(0);
2071 last_calib = time_uptime;
2076 * This function gets called every 16 seconds on only one designated
2077 * CPU in the system from hardclock() via cpu_tick_calibration()().
2079 * Whenever the real time clock is stepped we get called with reset=1
2080 * to make sure we handle suspend/resume and similar events correctly.
2084 cpu_tick_calibrate(int reset)
2086 static uint64_t c_last;
2087 uint64_t c_this, c_delta;
2088 static struct bintime t_last;
2089 struct bintime t_this, t_delta;
2093 /* The clock was stepped, abort & reset */
2098 /* we don't calibrate fixed rate cputicks */
2099 if (!cpu_tick_variable)
2102 getbinuptime(&t_this);
2103 c_this = cpu_ticks();
2104 if (t_last.sec != 0) {
2105 c_delta = c_this - c_last;
2107 bintime_sub(&t_delta, &t_last);
2110 * 2^(64-20) / 16[s] =
2112 * 17.592.186.044.416 / 16 =
2113 * 1.099.511.627.776 [Hz]
2115 divi = t_delta.sec << 20;
2116 divi |= t_delta.frac >> (64 - 20);
2119 if (c_delta > cpu_tick_frequency) {
2120 if (0 && bootverbose)
2121 printf("cpu_tick increased to %ju Hz\n",
2123 cpu_tick_frequency = c_delta;
2131 set_cputicker(cpu_tick_f *func, uint64_t freq, bool isvariable)
2135 cpu_ticks = tc_cpu_ticks;
2137 cpu_tick_frequency = freq;
2138 cpu_tick_variable = isvariable;
2147 if (cpu_ticks == tc_cpu_ticks)
2148 return (tc_getfrequency());
2149 return (cpu_tick_frequency);
2153 * We need to be slightly careful converting cputicks to microseconds.
2154 * There is plenty of margin in 64 bits of microseconds (half a million
2155 * years) and in 64 bits at 4 GHz (146 years), but if we do a multiply
2156 * before divide conversion (to retain precision) we find that the
2157 * margin shrinks to 1.5 hours (one millionth of 146y).
2161 cputick2usec(uint64_t tick)
2164 tr = cpu_tickrate();
2165 return ((tick / tr) * 1000000ULL) + ((tick % tr) * 1000000ULL) / tr;
2168 cpu_tick_f *cpu_ticks = tc_cpu_ticks;
2170 static int vdso_th_enable = 1;
2172 sysctl_fast_gettime(SYSCTL_HANDLER_ARGS)
2174 int old_vdso_th_enable, error;
2176 old_vdso_th_enable = vdso_th_enable;
2177 error = sysctl_handle_int(oidp, &old_vdso_th_enable, 0, req);
2180 vdso_th_enable = old_vdso_th_enable;
2183 SYSCTL_PROC(_kern_timecounter, OID_AUTO, fast_gettime,
2184 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
2185 NULL, 0, sysctl_fast_gettime, "I", "Enable fast time of day");
2188 tc_fill_vdso_timehands(struct vdso_timehands *vdso_th)
2190 struct timehands *th;
2194 vdso_th->th_scale = th->th_scale;
2195 vdso_th->th_offset_count = th->th_offset_count;
2196 vdso_th->th_counter_mask = th->th_counter->tc_counter_mask;
2197 vdso_th->th_offset = th->th_offset;
2198 vdso_th->th_boottime = th->th_boottime;
2199 if (th->th_counter->tc_fill_vdso_timehands != NULL) {
2200 enabled = th->th_counter->tc_fill_vdso_timehands(vdso_th,
2204 if (!vdso_th_enable)
2209 #ifdef COMPAT_FREEBSD32
2211 tc_fill_vdso_timehands32(struct vdso_timehands32 *vdso_th32)
2213 struct timehands *th;
2217 *(uint64_t *)&vdso_th32->th_scale[0] = th->th_scale;
2218 vdso_th32->th_offset_count = th->th_offset_count;
2219 vdso_th32->th_counter_mask = th->th_counter->tc_counter_mask;
2220 vdso_th32->th_offset.sec = th->th_offset.sec;
2221 *(uint64_t *)&vdso_th32->th_offset.frac[0] = th->th_offset.frac;
2222 vdso_th32->th_boottime.sec = th->th_boottime.sec;
2223 *(uint64_t *)&vdso_th32->th_boottime.frac[0] = th->th_boottime.frac;
2224 if (th->th_counter->tc_fill_vdso_timehands32 != NULL) {
2225 enabled = th->th_counter->tc_fill_vdso_timehands32(vdso_th32,
2229 if (!vdso_th_enable)
2235 #include "opt_ddb.h"
2237 #include <ddb/ddb.h>
2239 DB_SHOW_COMMAND(timecounter, db_show_timecounter)
2241 struct timehands *th;
2242 struct timecounter *tc;
2246 tc = th->th_counter;
2247 val1 = tc->tc_get_timecount(tc);
2248 __compiler_membar();
2249 val2 = tc->tc_get_timecount(tc);
2251 db_printf("timecounter %p %s\n", tc, tc->tc_name);
2252 db_printf(" mask %#x freq %ju qual %d flags %#x priv %p\n",
2253 tc->tc_counter_mask, (uintmax_t)tc->tc_frequency, tc->tc_quality,
2254 tc->tc_flags, tc->tc_priv);
2255 db_printf(" val %#x %#x\n", val1, val2);
2256 db_printf("timehands adj %#jx scale %#jx ldelta %d off_cnt %d gen %d\n",
2257 (uintmax_t)th->th_adjustment, (uintmax_t)th->th_scale,
2258 th->th_large_delta, th->th_offset_count, th->th_generation);
2259 db_printf(" offset %jd %jd boottime %jd %jd\n",
2260 (intmax_t)th->th_offset.sec, (uintmax_t)th->th_offset.frac,
2261 (intmax_t)th->th_boottime.sec, (uintmax_t)th->th_boottime.frac);