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>
21 __FBSDID("$FreeBSD$");
24 #include "opt_ffclock.h"
26 #include <sys/param.h>
27 #include <sys/kernel.h>
28 #include <sys/limits.h>
30 #include <sys/mutex.h>
33 #include <sys/sleepqueue.h>
34 #include <sys/sysctl.h>
35 #include <sys/syslog.h>
36 #include <sys/systm.h>
37 #include <sys/timeffc.h>
38 #include <sys/timepps.h>
39 #include <sys/timetc.h>
40 #include <sys/timex.h>
44 * A large step happens on boot. This constant detects such steps.
45 * It is relatively small so that ntp_update_second gets called enough
46 * in the typical 'missed a couple of seconds' case, but doesn't loop
47 * forever when the time step is large.
49 #define LARGE_STEP 200
52 * Implement a dummy timecounter which we can use until we get a real one
53 * in the air. This allows the console and other early stuff to use
58 dummy_get_timecount(struct timecounter *tc)
65 static struct timecounter dummy_timecounter = {
66 dummy_get_timecount, 0, ~0u, 1000000, "dummy", -1000000
70 /* These fields must be initialized by the driver. */
71 struct timecounter *th_counter;
72 int64_t th_adjustment;
75 u_int th_offset_count;
76 struct bintime th_offset;
77 struct bintime th_bintime;
78 struct timeval th_microtime;
79 struct timespec th_nanotime;
80 struct bintime th_boottime;
81 /* Fields not to be copied in tc_windup start with th_generation. */
83 struct timehands *th_next;
86 static struct timehands ths[16] = {
88 .th_counter = &dummy_timecounter,
89 .th_scale = (uint64_t)-1 / 1000000,
90 .th_large_delta = 1000000,
91 .th_offset = { .sec = 1 },
96 static struct timehands *volatile timehands = &ths[0];
97 struct timecounter *timecounter = &dummy_timecounter;
98 static struct timecounter *timecounters = &dummy_timecounter;
100 /* Mutex to protect the timecounter list. */
101 static struct mtx tc_lock;
103 int tc_min_ticktock_freq = 1;
105 volatile time_t time_second = 1;
106 volatile time_t time_uptime = 1;
109 * The system time is always computed by summing the estimated boot time and the
110 * system uptime. The timehands track boot time, but it changes when the system
111 * time is set by the user, stepped by ntpd or adjusted when resuming. It
112 * is set to new_time - uptime.
114 static int sysctl_kern_boottime(SYSCTL_HANDLER_ARGS);
115 SYSCTL_PROC(_kern, KERN_BOOTTIME, boottime,
116 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
117 sysctl_kern_boottime, "S,timeval",
118 "Estimated system boottime");
120 SYSCTL_NODE(_kern, OID_AUTO, timecounter, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
122 static SYSCTL_NODE(_kern_timecounter, OID_AUTO, tc,
123 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
126 static int timestepwarnings;
127 SYSCTL_INT(_kern_timecounter, OID_AUTO, stepwarnings, CTLFLAG_RWTUN,
128 ×tepwarnings, 0, "Log time steps");
130 static int timehands_count = 2;
131 SYSCTL_INT(_kern_timecounter, OID_AUTO, timehands_count,
132 CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
133 &timehands_count, 0, "Count of timehands in rotation");
135 struct bintime bt_timethreshold;
136 struct bintime bt_tickthreshold;
137 sbintime_t sbt_timethreshold;
138 sbintime_t sbt_tickthreshold;
139 struct bintime tc_tick_bt;
140 sbintime_t tc_tick_sbt;
142 int tc_timepercentage = TC_DEFAULTPERC;
143 static int sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS);
144 SYSCTL_PROC(_kern_timecounter, OID_AUTO, alloweddeviation,
145 CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, 0, 0,
146 sysctl_kern_timecounter_adjprecision, "I",
147 "Allowed time interval deviation in percents");
149 volatile int rtc_generation = 1;
151 static int tc_chosen; /* Non-zero if a specific tc was chosen via sysctl. */
152 static char tc_from_tunable[16];
154 static void tc_windup(struct bintime *new_boottimebin);
155 static void cpu_tick_calibrate(int);
157 void dtrace_getnanotime(struct timespec *tsp);
158 void dtrace_getnanouptime(struct timespec *tsp);
161 sysctl_kern_boottime(SYSCTL_HANDLER_ARGS)
163 struct timeval boottime;
165 getboottime(&boottime);
167 /* i386 is the only arch which uses a 32bits time_t */
172 if (req->flags & SCTL_MASK32) {
173 tv[0] = boottime.tv_sec;
174 tv[1] = boottime.tv_usec;
175 return (SYSCTL_OUT(req, tv, sizeof(tv)));
179 return (SYSCTL_OUT(req, &boottime, sizeof(boottime)));
183 sysctl_kern_timecounter_get(SYSCTL_HANDLER_ARGS)
186 struct timecounter *tc = arg1;
188 ncount = tc->tc_get_timecount(tc);
189 return (sysctl_handle_int(oidp, &ncount, 0, req));
193 sysctl_kern_timecounter_freq(SYSCTL_HANDLER_ARGS)
196 struct timecounter *tc = arg1;
198 freq = tc->tc_frequency;
199 return (sysctl_handle_64(oidp, &freq, 0, req));
203 * Return the difference between the timehands' counter value now and what
204 * was when we copied it to the timehands' offset_count.
206 static __inline u_int
207 tc_delta(struct timehands *th)
209 struct timecounter *tc;
212 return ((tc->tc_get_timecount(tc) - th->th_offset_count) &
213 tc->tc_counter_mask);
217 bintime_add_tc_delta(struct bintime *bt, uint64_t scale,
218 uint64_t large_delta, uint64_t delta)
222 if (__predict_false(delta >= large_delta)) {
223 /* Avoid overflow for scale * delta. */
224 x = (scale >> 32) * delta;
226 bintime_addx(bt, x << 32);
227 bintime_addx(bt, (scale & 0xffffffff) * delta);
229 bintime_addx(bt, scale * delta);
234 * Functions for reading the time. We have to loop until we are sure that
235 * the timehands that we operated on was not updated under our feet. See
236 * the comment in <sys/time.h> for a description of these 12 functions.
240 bintime_off(struct bintime *bt, u_int off)
242 struct timehands *th;
245 u_int delta, gen, large_delta;
249 gen = atomic_load_acq_int(&th->th_generation);
250 btp = (struct bintime *)((vm_offset_t)th + off);
252 scale = th->th_scale;
253 delta = tc_delta(th);
254 large_delta = th->th_large_delta;
255 atomic_thread_fence_acq();
256 } while (gen == 0 || gen != th->th_generation);
258 bintime_add_tc_delta(bt, scale, large_delta, delta);
260 #define GETTHBINTIME(dst, member) \
262 _Static_assert(_Generic(((struct timehands *)NULL)->member, \
263 struct bintime: 1, default: 0) == 1, \
264 "struct timehands member is not of struct bintime type"); \
265 bintime_off(dst, __offsetof(struct timehands, member)); \
269 getthmember(void *out, size_t out_size, u_int off)
271 struct timehands *th;
276 gen = atomic_load_acq_int(&th->th_generation);
277 memcpy(out, (char *)th + off, out_size);
278 atomic_thread_fence_acq();
279 } while (gen == 0 || gen != th->th_generation);
281 #define GETTHMEMBER(dst, member) \
283 _Static_assert(_Generic(*dst, \
284 __typeof(((struct timehands *)NULL)->member): 1, \
286 "*dst and struct timehands member have different types"); \
287 getthmember(dst, sizeof(*dst), __offsetof(struct timehands, \
293 fbclock_binuptime(struct bintime *bt)
296 GETTHBINTIME(bt, th_offset);
300 fbclock_nanouptime(struct timespec *tsp)
304 fbclock_binuptime(&bt);
305 bintime2timespec(&bt, tsp);
309 fbclock_microuptime(struct timeval *tvp)
313 fbclock_binuptime(&bt);
314 bintime2timeval(&bt, tvp);
318 fbclock_bintime(struct bintime *bt)
321 GETTHBINTIME(bt, th_bintime);
325 fbclock_nanotime(struct timespec *tsp)
329 fbclock_bintime(&bt);
330 bintime2timespec(&bt, tsp);
334 fbclock_microtime(struct timeval *tvp)
338 fbclock_bintime(&bt);
339 bintime2timeval(&bt, tvp);
343 fbclock_getbinuptime(struct bintime *bt)
346 GETTHMEMBER(bt, th_offset);
350 fbclock_getnanouptime(struct timespec *tsp)
354 GETTHMEMBER(&bt, th_offset);
355 bintime2timespec(&bt, tsp);
359 fbclock_getmicrouptime(struct timeval *tvp)
363 GETTHMEMBER(&bt, th_offset);
364 bintime2timeval(&bt, tvp);
368 fbclock_getbintime(struct bintime *bt)
371 GETTHMEMBER(bt, th_bintime);
375 fbclock_getnanotime(struct timespec *tsp)
378 GETTHMEMBER(tsp, th_nanotime);
382 fbclock_getmicrotime(struct timeval *tvp)
385 GETTHMEMBER(tvp, th_microtime);
390 binuptime(struct bintime *bt)
393 GETTHBINTIME(bt, th_offset);
397 nanouptime(struct timespec *tsp)
402 bintime2timespec(&bt, tsp);
406 microuptime(struct timeval *tvp)
411 bintime2timeval(&bt, tvp);
415 bintime(struct bintime *bt)
418 GETTHBINTIME(bt, th_bintime);
422 nanotime(struct timespec *tsp)
427 bintime2timespec(&bt, tsp);
431 microtime(struct timeval *tvp)
436 bintime2timeval(&bt, tvp);
440 getbinuptime(struct bintime *bt)
443 GETTHMEMBER(bt, th_offset);
447 getnanouptime(struct timespec *tsp)
451 GETTHMEMBER(&bt, th_offset);
452 bintime2timespec(&bt, tsp);
456 getmicrouptime(struct timeval *tvp)
460 GETTHMEMBER(&bt, th_offset);
461 bintime2timeval(&bt, tvp);
465 getbintime(struct bintime *bt)
468 GETTHMEMBER(bt, th_bintime);
472 getnanotime(struct timespec *tsp)
475 GETTHMEMBER(tsp, th_nanotime);
479 getmicrotime(struct timeval *tvp)
482 GETTHMEMBER(tvp, th_microtime);
487 getboottime(struct timeval *boottime)
489 struct bintime boottimebin;
491 getboottimebin(&boottimebin);
492 bintime2timeval(&boottimebin, boottime);
496 getboottimebin(struct bintime *boottimebin)
499 GETTHMEMBER(boottimebin, th_boottime);
504 * Support for feed-forward synchronization algorithms. This is heavily inspired
505 * by the timehands mechanism but kept independent from it. *_windup() functions
506 * have some connection to avoid accessing the timecounter hardware more than
510 /* Feed-forward clock estimates kept updated by the synchronization daemon. */
511 struct ffclock_estimate ffclock_estimate;
512 struct bintime ffclock_boottime; /* Feed-forward boot time estimate. */
513 uint32_t ffclock_status; /* Feed-forward clock status. */
514 int8_t ffclock_updated; /* New estimates are available. */
515 struct mtx ffclock_mtx; /* Mutex on ffclock_estimate. */
518 struct ffclock_estimate cest;
519 struct bintime tick_time;
520 struct bintime tick_time_lerp;
521 ffcounter tick_ffcount;
522 uint64_t period_lerp;
523 volatile uint8_t gen;
524 struct fftimehands *next;
527 #define NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))
529 static struct fftimehands ffth[10];
530 static struct fftimehands *volatile fftimehands = ffth;
535 struct fftimehands *cur;
536 struct fftimehands *last;
538 memset(ffth, 0, sizeof(ffth));
540 last = ffth + NUM_ELEMENTS(ffth) - 1;
541 for (cur = ffth; cur < last; cur++)
546 ffclock_status = FFCLOCK_STA_UNSYNC;
547 mtx_init(&ffclock_mtx, "ffclock lock", NULL, MTX_DEF);
551 * Reset the feed-forward clock estimates. Called from inittodr() to get things
552 * kick started and uses the timecounter nominal frequency as a first period
553 * estimate. Note: this function may be called several time just after boot.
554 * Note: this is the only function that sets the value of boot time for the
555 * monotonic (i.e. uptime) version of the feed-forward clock.
558 ffclock_reset_clock(struct timespec *ts)
560 struct timecounter *tc;
561 struct ffclock_estimate cest;
563 tc = timehands->th_counter;
564 memset(&cest, 0, sizeof(struct ffclock_estimate));
566 timespec2bintime(ts, &ffclock_boottime);
567 timespec2bintime(ts, &(cest.update_time));
568 ffclock_read_counter(&cest.update_ffcount);
569 cest.leapsec_next = 0;
570 cest.period = ((1ULL << 63) / tc->tc_frequency) << 1;
573 cest.status = FFCLOCK_STA_UNSYNC;
574 cest.leapsec_total = 0;
577 mtx_lock(&ffclock_mtx);
578 bcopy(&cest, &ffclock_estimate, sizeof(struct ffclock_estimate));
579 ffclock_updated = INT8_MAX;
580 mtx_unlock(&ffclock_mtx);
582 printf("ffclock reset: %s (%llu Hz), time = %ld.%09lu\n", tc->tc_name,
583 (unsigned long long)tc->tc_frequency, (long)ts->tv_sec,
584 (unsigned long)ts->tv_nsec);
588 * Sub-routine to convert a time interval measured in RAW counter units to time
589 * in seconds stored in bintime format.
590 * NOTE: bintime_mul requires u_int, but the value of the ffcounter may be
591 * larger than the max value of u_int (on 32 bit architecture). Loop to consume
595 ffclock_convert_delta(ffcounter ffdelta, uint64_t period, struct bintime *bt)
598 ffcounter delta, delta_max;
600 delta_max = (1ULL << (8 * sizeof(unsigned int))) - 1;
603 if (ffdelta > delta_max)
609 bintime_mul(&bt2, (unsigned int)delta);
610 bintime_add(bt, &bt2);
612 } while (ffdelta > 0);
616 * Update the fftimehands.
617 * Push the tick ffcount and time(s) forward based on current clock estimate.
618 * The conversion from ffcounter to bintime relies on the difference clock
619 * principle, whose accuracy relies on computing small time intervals. If a new
620 * clock estimate has been passed by the synchronisation daemon, make it
621 * current, and compute the linear interpolation for monotonic time if needed.
624 ffclock_windup(unsigned int delta)
626 struct ffclock_estimate *cest;
627 struct fftimehands *ffth;
628 struct bintime bt, gap_lerp;
631 unsigned int polling;
632 uint8_t forward_jump, ogen;
635 * Pick the next timehand, copy current ffclock estimates and move tick
636 * times and counter forward.
639 ffth = fftimehands->next;
643 bcopy(&fftimehands->cest, cest, sizeof(struct ffclock_estimate));
644 ffdelta = (ffcounter)delta;
645 ffth->period_lerp = fftimehands->period_lerp;
647 ffth->tick_time = fftimehands->tick_time;
648 ffclock_convert_delta(ffdelta, cest->period, &bt);
649 bintime_add(&ffth->tick_time, &bt);
651 ffth->tick_time_lerp = fftimehands->tick_time_lerp;
652 ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt);
653 bintime_add(&ffth->tick_time_lerp, &bt);
655 ffth->tick_ffcount = fftimehands->tick_ffcount + ffdelta;
658 * Assess the status of the clock, if the last update is too old, it is
659 * likely the synchronisation daemon is dead and the clock is free
662 if (ffclock_updated == 0) {
663 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
664 ffclock_convert_delta(ffdelta, cest->period, &bt);
665 if (bt.sec > 2 * FFCLOCK_SKM_SCALE)
666 ffclock_status |= FFCLOCK_STA_UNSYNC;
670 * If available, grab updated clock estimates and make them current.
671 * Recompute time at this tick using the updated estimates. The clock
672 * estimates passed the feed-forward synchronisation daemon may result
673 * in time conversion that is not monotonically increasing (just after
674 * the update). time_lerp is a particular linear interpolation over the
675 * synchronisation algo polling period that ensures monotonicity for the
676 * clock ids requesting it.
678 if (ffclock_updated > 0) {
679 bcopy(&ffclock_estimate, cest, sizeof(struct ffclock_estimate));
680 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
681 ffth->tick_time = cest->update_time;
682 ffclock_convert_delta(ffdelta, cest->period, &bt);
683 bintime_add(&ffth->tick_time, &bt);
685 /* ffclock_reset sets ffclock_updated to INT8_MAX */
686 if (ffclock_updated == INT8_MAX)
687 ffth->tick_time_lerp = ffth->tick_time;
689 if (bintime_cmp(&ffth->tick_time, &ffth->tick_time_lerp, >))
694 bintime_clear(&gap_lerp);
696 gap_lerp = ffth->tick_time;
697 bintime_sub(&gap_lerp, &ffth->tick_time_lerp);
699 gap_lerp = ffth->tick_time_lerp;
700 bintime_sub(&gap_lerp, &ffth->tick_time);
704 * The reset from the RTC clock may be far from accurate, and
705 * reducing the gap between real time and interpolated time
706 * could take a very long time if the interpolated clock insists
707 * on strict monotonicity. The clock is reset under very strict
708 * conditions (kernel time is known to be wrong and
709 * synchronization daemon has been restarted recently.
710 * ffclock_boottime absorbs the jump to ensure boot time is
711 * correct and uptime functions stay consistent.
713 if (((ffclock_status & FFCLOCK_STA_UNSYNC) == FFCLOCK_STA_UNSYNC) &&
714 ((cest->status & FFCLOCK_STA_UNSYNC) == 0) &&
715 ((cest->status & FFCLOCK_STA_WARMUP) == FFCLOCK_STA_WARMUP)) {
717 bintime_add(&ffclock_boottime, &gap_lerp);
719 bintime_sub(&ffclock_boottime, &gap_lerp);
720 ffth->tick_time_lerp = ffth->tick_time;
721 bintime_clear(&gap_lerp);
724 ffclock_status = cest->status;
725 ffth->period_lerp = cest->period;
728 * Compute corrected period used for the linear interpolation of
729 * time. The rate of linear interpolation is capped to 5000PPM
732 if (bintime_isset(&gap_lerp)) {
733 ffdelta = cest->update_ffcount;
734 ffdelta -= fftimehands->cest.update_ffcount;
735 ffclock_convert_delta(ffdelta, cest->period, &bt);
738 bt.frac = 5000000 * (uint64_t)18446744073LL;
739 bintime_mul(&bt, polling);
740 if (bintime_cmp(&gap_lerp, &bt, >))
743 /* Approximate 1 sec by 1-(1/2^64) to ease arithmetic */
745 if (gap_lerp.sec > 0) {
747 frac /= ffdelta / gap_lerp.sec;
749 frac += gap_lerp.frac / ffdelta;
752 ffth->period_lerp += frac;
754 ffth->period_lerp -= frac;
766 * Adjust the fftimehands when the timecounter is changed. Stating the obvious,
767 * the old and new hardware counter cannot be read simultaneously. tc_windup()
768 * does read the two counters 'back to back', but a few cycles are effectively
769 * lost, and not accumulated in tick_ffcount. This is a fairly radical
770 * operation for a feed-forward synchronization daemon, and it is its job to not
771 * pushing irrelevant data to the kernel. Because there is no locking here,
772 * simply force to ignore pending or next update to give daemon a chance to
773 * realize the counter has changed.
776 ffclock_change_tc(struct timehands *th)
778 struct fftimehands *ffth;
779 struct ffclock_estimate *cest;
780 struct timecounter *tc;
784 ffth = fftimehands->next;
789 bcopy(&(fftimehands->cest), cest, sizeof(struct ffclock_estimate));
790 cest->period = ((1ULL << 63) / tc->tc_frequency ) << 1;
793 cest->status |= FFCLOCK_STA_UNSYNC;
795 ffth->tick_ffcount = fftimehands->tick_ffcount;
796 ffth->tick_time_lerp = fftimehands->tick_time_lerp;
797 ffth->tick_time = fftimehands->tick_time;
798 ffth->period_lerp = cest->period;
800 /* Do not lock but ignore next update from synchronization daemon. */
810 * Retrieve feed-forward counter and time of last kernel tick.
813 ffclock_last_tick(ffcounter *ffcount, struct bintime *bt, uint32_t flags)
815 struct fftimehands *ffth;
819 * No locking but check generation has not changed. Also need to make
820 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
825 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP)
826 *bt = ffth->tick_time_lerp;
828 *bt = ffth->tick_time;
829 *ffcount = ffth->tick_ffcount;
830 } while (gen == 0 || gen != ffth->gen);
834 * Absolute clock conversion. Low level function to convert ffcounter to
835 * bintime. The ffcounter is converted using the current ffclock period estimate
836 * or the "interpolated period" to ensure monotonicity.
837 * NOTE: this conversion may have been deferred, and the clock updated since the
838 * hardware counter has been read.
841 ffclock_convert_abs(ffcounter ffcount, struct bintime *bt, uint32_t flags)
843 struct fftimehands *ffth;
849 * No locking but check generation has not changed. Also need to make
850 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
855 if (ffcount > ffth->tick_ffcount)
856 ffdelta = ffcount - ffth->tick_ffcount;
858 ffdelta = ffth->tick_ffcount - ffcount;
860 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP) {
861 *bt = ffth->tick_time_lerp;
862 ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt2);
864 *bt = ffth->tick_time;
865 ffclock_convert_delta(ffdelta, ffth->cest.period, &bt2);
868 if (ffcount > ffth->tick_ffcount)
869 bintime_add(bt, &bt2);
871 bintime_sub(bt, &bt2);
872 } while (gen == 0 || gen != ffth->gen);
876 * Difference clock conversion.
877 * Low level function to Convert a time interval measured in RAW counter units
878 * into bintime. The difference clock allows measuring small intervals much more
879 * reliably than the absolute clock.
882 ffclock_convert_diff(ffcounter ffdelta, struct bintime *bt)
884 struct fftimehands *ffth;
887 /* No locking but check generation has not changed. */
891 ffclock_convert_delta(ffdelta, ffth->cest.period, bt);
892 } while (gen == 0 || gen != ffth->gen);
896 * Access to current ffcounter value.
899 ffclock_read_counter(ffcounter *ffcount)
901 struct timehands *th;
902 struct fftimehands *ffth;
903 unsigned int gen, delta;
906 * ffclock_windup() called from tc_windup(), safe to rely on
907 * th->th_generation only, for correct delta and ffcounter.
911 gen = atomic_load_acq_int(&th->th_generation);
913 delta = tc_delta(th);
914 *ffcount = ffth->tick_ffcount;
915 atomic_thread_fence_acq();
916 } while (gen == 0 || gen != th->th_generation);
922 binuptime(struct bintime *bt)
925 binuptime_fromclock(bt, sysclock_active);
929 nanouptime(struct timespec *tsp)
932 nanouptime_fromclock(tsp, sysclock_active);
936 microuptime(struct timeval *tvp)
939 microuptime_fromclock(tvp, sysclock_active);
943 bintime(struct bintime *bt)
946 bintime_fromclock(bt, sysclock_active);
950 nanotime(struct timespec *tsp)
953 nanotime_fromclock(tsp, sysclock_active);
957 microtime(struct timeval *tvp)
960 microtime_fromclock(tvp, sysclock_active);
964 getbinuptime(struct bintime *bt)
967 getbinuptime_fromclock(bt, sysclock_active);
971 getnanouptime(struct timespec *tsp)
974 getnanouptime_fromclock(tsp, sysclock_active);
978 getmicrouptime(struct timeval *tvp)
981 getmicrouptime_fromclock(tvp, sysclock_active);
985 getbintime(struct bintime *bt)
988 getbintime_fromclock(bt, sysclock_active);
992 getnanotime(struct timespec *tsp)
995 getnanotime_fromclock(tsp, sysclock_active);
999 getmicrotime(struct timeval *tvp)
1002 getmicrouptime_fromclock(tvp, sysclock_active);
1005 #endif /* FFCLOCK */
1008 * This is a clone of getnanotime and used for walltimestamps.
1009 * The dtrace_ prefix prevents fbt from creating probes for
1010 * it so walltimestamp can be safely used in all fbt probes.
1013 dtrace_getnanotime(struct timespec *tsp)
1016 GETTHMEMBER(tsp, th_nanotime);
1020 * This is a clone of getnanouptime used for time since boot.
1021 * The dtrace_ prefix prevents fbt from creating probes for
1022 * it so an uptime that can be safely used in all fbt probes.
1025 dtrace_getnanouptime(struct timespec *tsp)
1029 GETTHMEMBER(&bt, th_offset);
1030 bintime2timespec(&bt, tsp);
1034 * System clock currently providing time to the system. Modifiable via sysctl
1035 * when the FFCLOCK option is defined.
1037 int sysclock_active = SYSCLOCK_FBCK;
1039 /* Internal NTP status and error estimates. */
1040 extern int time_status;
1041 extern long time_esterror;
1044 * Take a snapshot of sysclock data which can be used to compare system clocks
1045 * and generate timestamps after the fact.
1048 sysclock_getsnapshot(struct sysclock_snap *clock_snap, int fast)
1050 struct fbclock_info *fbi;
1051 struct timehands *th;
1053 unsigned int delta, gen;
1056 struct fftimehands *ffth;
1057 struct ffclock_info *ffi;
1058 struct ffclock_estimate cest;
1060 ffi = &clock_snap->ff_info;
1063 fbi = &clock_snap->fb_info;
1068 gen = atomic_load_acq_int(&th->th_generation);
1069 fbi->th_scale = th->th_scale;
1070 fbi->tick_time = th->th_offset;
1073 ffi->tick_time = ffth->tick_time_lerp;
1074 ffi->tick_time_lerp = ffth->tick_time_lerp;
1075 ffi->period = ffth->cest.period;
1076 ffi->period_lerp = ffth->period_lerp;
1077 clock_snap->ffcount = ffth->tick_ffcount;
1081 delta = tc_delta(th);
1082 atomic_thread_fence_acq();
1083 } while (gen == 0 || gen != th->th_generation);
1085 clock_snap->delta = delta;
1086 clock_snap->sysclock_active = sysclock_active;
1088 /* Record feedback clock status and error. */
1089 clock_snap->fb_info.status = time_status;
1090 /* XXX: Very crude estimate of feedback clock error. */
1091 bt.sec = time_esterror / 1000000;
1092 bt.frac = ((time_esterror - bt.sec) * 1000000) *
1093 (uint64_t)18446744073709ULL;
1094 clock_snap->fb_info.error = bt;
1098 clock_snap->ffcount += delta;
1100 /* Record feed-forward clock leap second adjustment. */
1101 ffi->leapsec_adjustment = cest.leapsec_total;
1102 if (clock_snap->ffcount > cest.leapsec_next)
1103 ffi->leapsec_adjustment -= cest.leapsec;
1105 /* Record feed-forward clock status and error. */
1106 clock_snap->ff_info.status = cest.status;
1107 ffcount = clock_snap->ffcount - cest.update_ffcount;
1108 ffclock_convert_delta(ffcount, cest.period, &bt);
1109 /* 18446744073709 = int(2^64/1e12), err_bound_rate in [ps/s]. */
1110 bintime_mul(&bt, cest.errb_rate * (uint64_t)18446744073709ULL);
1111 /* 18446744073 = int(2^64 / 1e9), since err_abs in [ns]. */
1112 bintime_addx(&bt, cest.errb_abs * (uint64_t)18446744073ULL);
1113 clock_snap->ff_info.error = bt;
1118 * Convert a sysclock snapshot into a struct bintime based on the specified
1119 * clock source and flags.
1122 sysclock_snap2bintime(struct sysclock_snap *cs, struct bintime *bt,
1123 int whichclock, uint32_t flags)
1125 struct bintime boottimebin;
1131 switch (whichclock) {
1133 *bt = cs->fb_info.tick_time;
1135 /* If snapshot was created with !fast, delta will be >0. */
1137 bintime_addx(bt, cs->fb_info.th_scale * cs->delta);
1139 if ((flags & FBCLOCK_UPTIME) == 0) {
1140 getboottimebin(&boottimebin);
1141 bintime_add(bt, &boottimebin);
1146 if (flags & FFCLOCK_LERP) {
1147 *bt = cs->ff_info.tick_time_lerp;
1148 period = cs->ff_info.period_lerp;
1150 *bt = cs->ff_info.tick_time;
1151 period = cs->ff_info.period;
1154 /* If snapshot was created with !fast, delta will be >0. */
1155 if (cs->delta > 0) {
1156 ffclock_convert_delta(cs->delta, period, &bt2);
1157 bintime_add(bt, &bt2);
1160 /* Leap second adjustment. */
1161 if (flags & FFCLOCK_LEAPSEC)
1162 bt->sec -= cs->ff_info.leapsec_adjustment;
1164 /* Boot time adjustment, for uptime/monotonic clocks. */
1165 if (flags & FFCLOCK_UPTIME)
1166 bintime_sub(bt, &ffclock_boottime);
1178 * Initialize a new timecounter and possibly use it.
1181 tc_init(struct timecounter *tc)
1184 struct sysctl_oid *tc_root;
1186 u = tc->tc_frequency / tc->tc_counter_mask;
1187 /* XXX: We need some margin here, 10% is a guess */
1190 if (u > hz && tc->tc_quality >= 0) {
1191 tc->tc_quality = -2000;
1193 printf("Timecounter \"%s\" frequency %ju Hz",
1194 tc->tc_name, (uintmax_t)tc->tc_frequency);
1195 printf(" -- Insufficient hz, needs at least %u\n", u);
1197 } else if (tc->tc_quality >= 0 || bootverbose) {
1198 printf("Timecounter \"%s\" frequency %ju Hz quality %d\n",
1199 tc->tc_name, (uintmax_t)tc->tc_frequency,
1204 * Set up sysctl tree for this counter.
1206 tc_root = SYSCTL_ADD_NODE_WITH_LABEL(NULL,
1207 SYSCTL_STATIC_CHILDREN(_kern_timecounter_tc), OID_AUTO, tc->tc_name,
1208 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1209 "timecounter description", "timecounter");
1210 SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1211 "mask", CTLFLAG_RD, &(tc->tc_counter_mask), 0,
1212 "mask for implemented bits");
1213 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1214 "counter", CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, tc,
1215 sizeof(*tc), sysctl_kern_timecounter_get, "IU",
1216 "current timecounter value");
1217 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1218 "frequency", CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, tc,
1219 sizeof(*tc), sysctl_kern_timecounter_freq, "QU",
1220 "timecounter frequency");
1221 SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1222 "quality", CTLFLAG_RD, &(tc->tc_quality), 0,
1223 "goodness of time counter");
1226 tc->tc_next = timecounters;
1230 * Do not automatically switch if the current tc was specifically
1231 * chosen. Never automatically use a timecounter with negative quality.
1232 * Even though we run on the dummy counter, switching here may be
1233 * worse since this timecounter may not be monotonic.
1237 if (tc->tc_quality < 0)
1239 if (tc_from_tunable[0] != '\0' &&
1240 strcmp(tc->tc_name, tc_from_tunable) == 0) {
1242 tc_from_tunable[0] = '\0';
1244 if (tc->tc_quality < timecounter->tc_quality)
1246 if (tc->tc_quality == timecounter->tc_quality &&
1247 tc->tc_frequency < timecounter->tc_frequency)
1250 (void)tc->tc_get_timecount(tc);
1253 mtx_unlock(&tc_lock);
1256 /* Report the frequency of the current timecounter. */
1258 tc_getfrequency(void)
1261 return (timehands->th_counter->tc_frequency);
1265 sleeping_on_old_rtc(struct thread *td)
1269 * td_rtcgen is modified by curthread when it is running,
1270 * and by other threads in this function. By finding the thread
1271 * on a sleepqueue and holding the lock on the sleepqueue
1272 * chain, we guarantee that the thread is not running and that
1273 * modifying td_rtcgen is safe. Setting td_rtcgen to zero informs
1274 * the thread that it was woken due to a real-time clock adjustment.
1275 * (The declaration of td_rtcgen refers to this comment.)
1277 if (td->td_rtcgen != 0 && td->td_rtcgen != rtc_generation) {
1284 static struct mtx tc_setclock_mtx;
1285 MTX_SYSINIT(tc_setclock_init, &tc_setclock_mtx, "tcsetc", MTX_SPIN);
1288 * Step our concept of UTC. This is done by modifying our estimate of
1292 tc_setclock(struct timespec *ts)
1294 struct timespec tbef, taft;
1295 struct bintime bt, bt2;
1297 timespec2bintime(ts, &bt);
1299 mtx_lock_spin(&tc_setclock_mtx);
1300 cpu_tick_calibrate(1);
1302 bintime_sub(&bt, &bt2);
1304 /* XXX fiddle all the little crinkly bits around the fiords... */
1306 mtx_unlock_spin(&tc_setclock_mtx);
1308 /* Avoid rtc_generation == 0, since td_rtcgen == 0 is special. */
1309 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);