2 * ----------------------------------------------------------------------------
3 * "THE BEER-WARE LICENSE" (Revision 42):
4 * <phk@FreeBSD.ORG> wrote this file. As long as you retain this notice you
5 * can do whatever you want with this stuff. If we meet some day, and you think
6 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
7 * ----------------------------------------------------------------------------
9 * Copyright (c) 2011 The FreeBSD Foundation
10 * All rights reserved.
12 * Portions of this software were developed by Julien Ridoux at the University
13 * of Melbourne under sponsorship from the FreeBSD Foundation.
16 #include <sys/cdefs.h>
17 __FBSDID("$FreeBSD$");
19 #include "opt_compat.h"
21 #include "opt_ffclock.h"
23 #include <sys/param.h>
24 #include <sys/kernel.h>
25 #include <sys/limits.h>
27 #include <sys/mutex.h>
28 #include <sys/sysctl.h>
29 #include <sys/syslog.h>
30 #include <sys/systm.h>
31 #include <sys/timeffc.h>
32 #include <sys/timepps.h>
33 #include <sys/timetc.h>
34 #include <sys/timex.h>
38 * A large step happens on boot. This constant detects such steps.
39 * It is relatively small so that ntp_update_second gets called enough
40 * in the typical 'missed a couple of seconds' case, but doesn't loop
41 * forever when the time step is large.
43 #define LARGE_STEP 200
46 * Implement a dummy timecounter which we can use until we get a real one
47 * in the air. This allows the console and other early stuff to use
52 dummy_get_timecount(struct timecounter *tc)
59 static struct timecounter dummy_timecounter = {
60 dummy_get_timecount, 0, ~0u, 1000000, "dummy", -1000000
64 /* These fields must be initialized by the driver. */
65 struct timecounter *th_counter;
66 int64_t th_adjustment;
68 u_int th_offset_count;
69 struct bintime th_offset;
70 struct timeval th_microtime;
71 struct timespec th_nanotime;
72 /* Fields not to be copied in tc_windup start with th_generation. */
73 volatile u_int th_generation;
74 struct timehands *th_next;
77 static struct timehands th0;
78 static struct timehands th9 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th0};
79 static struct timehands th8 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th9};
80 static struct timehands th7 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th8};
81 static struct timehands th6 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th7};
82 static struct timehands th5 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th6};
83 static struct timehands th4 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th5};
84 static struct timehands th3 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th4};
85 static struct timehands th2 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th3};
86 static struct timehands th1 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th2};
87 static struct timehands th0 = {
90 (uint64_t)-1 / 1000000,
99 static struct timehands *volatile timehands = &th0;
100 struct timecounter *timecounter = &dummy_timecounter;
101 static struct timecounter *timecounters = &dummy_timecounter;
103 int tc_min_ticktock_freq = 1;
105 volatile time_t time_second = 1;
106 volatile time_t time_uptime = 1;
108 struct bintime boottimebin;
109 struct timeval boottime;
110 static int sysctl_kern_boottime(SYSCTL_HANDLER_ARGS);
111 SYSCTL_PROC(_kern, KERN_BOOTTIME, boottime, CTLTYPE_STRUCT|CTLFLAG_RD,
112 NULL, 0, sysctl_kern_boottime, "S,timeval", "System boottime");
114 SYSCTL_NODE(_kern, OID_AUTO, timecounter, CTLFLAG_RW, 0, "");
115 static SYSCTL_NODE(_kern_timecounter, OID_AUTO, tc, CTLFLAG_RW, 0, "");
117 static int timestepwarnings;
118 SYSCTL_INT(_kern_timecounter, OID_AUTO, stepwarnings, CTLFLAG_RW,
119 ×tepwarnings, 0, "Log time steps");
121 struct bintime bt_timethreshold;
122 struct bintime bt_tickthreshold;
123 sbintime_t sbt_timethreshold;
124 sbintime_t sbt_tickthreshold;
125 struct bintime tc_tick_bt;
126 sbintime_t tc_tick_sbt;
128 int tc_timepercentage = TC_DEFAULTPERC;
129 TUNABLE_INT("kern.timecounter.alloweddeviation", &tc_timepercentage);
130 static int sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS);
131 SYSCTL_PROC(_kern_timecounter, OID_AUTO, alloweddeviation,
132 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 0,
133 sysctl_kern_timecounter_adjprecision, "I",
134 "Allowed time interval deviation in percents");
136 static void tc_windup(void);
137 static void cpu_tick_calibrate(int);
139 void dtrace_getnanotime(struct timespec *tsp);
142 sysctl_kern_boottime(SYSCTL_HANDLER_ARGS)
148 if (req->flags & SCTL_MASK32) {
149 tv[0] = boottime.tv_sec;
150 tv[1] = boottime.tv_usec;
151 return SYSCTL_OUT(req, tv, sizeof(tv));
155 return SYSCTL_OUT(req, &boottime, sizeof(boottime));
159 sysctl_kern_timecounter_get(SYSCTL_HANDLER_ARGS)
162 struct timecounter *tc = arg1;
164 ncount = tc->tc_get_timecount(tc);
165 return sysctl_handle_int(oidp, &ncount, 0, req);
169 sysctl_kern_timecounter_freq(SYSCTL_HANDLER_ARGS)
172 struct timecounter *tc = arg1;
174 freq = tc->tc_frequency;
175 return sysctl_handle_64(oidp, &freq, 0, req);
179 * Return the difference between the timehands' counter value now and what
180 * was when we copied it to the timehands' offset_count.
182 static __inline u_int
183 tc_delta(struct timehands *th)
185 struct timecounter *tc;
188 return ((tc->tc_get_timecount(tc) - th->th_offset_count) &
189 tc->tc_counter_mask);
193 * Functions for reading the time. We have to loop until we are sure that
194 * the timehands that we operated on was not updated under our feet. See
195 * the comment in <sys/time.h> for a description of these 12 functions.
200 fbclock_binuptime(struct bintime *bt)
202 struct timehands *th;
207 gen = th->th_generation;
209 bintime_addx(bt, th->th_scale * tc_delta(th));
210 } while (gen == 0 || gen != th->th_generation);
214 fbclock_nanouptime(struct timespec *tsp)
218 fbclock_binuptime(&bt);
219 bintime2timespec(&bt, tsp);
223 fbclock_microuptime(struct timeval *tvp)
227 fbclock_binuptime(&bt);
228 bintime2timeval(&bt, tvp);
232 fbclock_bintime(struct bintime *bt)
235 fbclock_binuptime(bt);
236 bintime_add(bt, &boottimebin);
240 fbclock_nanotime(struct timespec *tsp)
244 fbclock_bintime(&bt);
245 bintime2timespec(&bt, tsp);
249 fbclock_microtime(struct timeval *tvp)
253 fbclock_bintime(&bt);
254 bintime2timeval(&bt, tvp);
258 fbclock_getbinuptime(struct bintime *bt)
260 struct timehands *th;
265 gen = th->th_generation;
267 } while (gen == 0 || gen != th->th_generation);
271 fbclock_getnanouptime(struct timespec *tsp)
273 struct timehands *th;
278 gen = th->th_generation;
279 bintime2timespec(&th->th_offset, tsp);
280 } while (gen == 0 || gen != th->th_generation);
284 fbclock_getmicrouptime(struct timeval *tvp)
286 struct timehands *th;
291 gen = th->th_generation;
292 bintime2timeval(&th->th_offset, tvp);
293 } while (gen == 0 || gen != th->th_generation);
297 fbclock_getbintime(struct bintime *bt)
299 struct timehands *th;
304 gen = th->th_generation;
306 } while (gen == 0 || gen != th->th_generation);
307 bintime_add(bt, &boottimebin);
311 fbclock_getnanotime(struct timespec *tsp)
313 struct timehands *th;
318 gen = th->th_generation;
319 *tsp = th->th_nanotime;
320 } while (gen == 0 || gen != th->th_generation);
324 fbclock_getmicrotime(struct timeval *tvp)
326 struct timehands *th;
331 gen = th->th_generation;
332 *tvp = th->th_microtime;
333 } while (gen == 0 || gen != th->th_generation);
337 binuptime(struct bintime *bt)
339 struct timehands *th;
344 gen = th->th_generation;
346 bintime_addx(bt, th->th_scale * tc_delta(th));
347 } while (gen == 0 || gen != th->th_generation);
351 nanouptime(struct timespec *tsp)
356 bintime2timespec(&bt, tsp);
360 microuptime(struct timeval *tvp)
365 bintime2timeval(&bt, tvp);
369 bintime(struct bintime *bt)
373 bintime_add(bt, &boottimebin);
377 nanotime(struct timespec *tsp)
382 bintime2timespec(&bt, tsp);
386 microtime(struct timeval *tvp)
391 bintime2timeval(&bt, tvp);
395 getbinuptime(struct bintime *bt)
397 struct timehands *th;
402 gen = th->th_generation;
404 } while (gen == 0 || gen != th->th_generation);
408 getnanouptime(struct timespec *tsp)
410 struct timehands *th;
415 gen = th->th_generation;
416 bintime2timespec(&th->th_offset, tsp);
417 } while (gen == 0 || gen != th->th_generation);
421 getmicrouptime(struct timeval *tvp)
423 struct timehands *th;
428 gen = th->th_generation;
429 bintime2timeval(&th->th_offset, tvp);
430 } while (gen == 0 || gen != th->th_generation);
434 getbintime(struct bintime *bt)
436 struct timehands *th;
441 gen = th->th_generation;
443 } while (gen == 0 || gen != th->th_generation);
444 bintime_add(bt, &boottimebin);
448 getnanotime(struct timespec *tsp)
450 struct timehands *th;
455 gen = th->th_generation;
456 *tsp = th->th_nanotime;
457 } while (gen == 0 || gen != th->th_generation);
461 getmicrotime(struct timeval *tvp)
463 struct timehands *th;
468 gen = th->th_generation;
469 *tvp = th->th_microtime;
470 } while (gen == 0 || gen != th->th_generation);
476 * Support for feed-forward synchronization algorithms. This is heavily inspired
477 * by the timehands mechanism but kept independent from it. *_windup() functions
478 * have some connection to avoid accessing the timecounter hardware more than
482 /* Feed-forward clock estimates kept updated by the synchronization daemon. */
483 struct ffclock_estimate ffclock_estimate;
484 struct bintime ffclock_boottime; /* Feed-forward boot time estimate. */
485 uint32_t ffclock_status; /* Feed-forward clock status. */
486 int8_t ffclock_updated; /* New estimates are available. */
487 struct mtx ffclock_mtx; /* Mutex on ffclock_estimate. */
490 struct ffclock_estimate cest;
491 struct bintime tick_time;
492 struct bintime tick_time_lerp;
493 ffcounter tick_ffcount;
494 uint64_t period_lerp;
495 volatile uint8_t gen;
496 struct fftimehands *next;
499 #define NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))
501 static struct fftimehands ffth[10];
502 static struct fftimehands *volatile fftimehands = ffth;
507 struct fftimehands *cur;
508 struct fftimehands *last;
510 memset(ffth, 0, sizeof(ffth));
512 last = ffth + NUM_ELEMENTS(ffth) - 1;
513 for (cur = ffth; cur < last; cur++)
518 ffclock_status = FFCLOCK_STA_UNSYNC;
519 mtx_init(&ffclock_mtx, "ffclock lock", NULL, MTX_DEF);
523 * Reset the feed-forward clock estimates. Called from inittodr() to get things
524 * kick started and uses the timecounter nominal frequency as a first period
525 * estimate. Note: this function may be called several time just after boot.
526 * Note: this is the only function that sets the value of boot time for the
527 * monotonic (i.e. uptime) version of the feed-forward clock.
530 ffclock_reset_clock(struct timespec *ts)
532 struct timecounter *tc;
533 struct ffclock_estimate cest;
535 tc = timehands->th_counter;
536 memset(&cest, 0, sizeof(struct ffclock_estimate));
538 timespec2bintime(ts, &ffclock_boottime);
539 timespec2bintime(ts, &(cest.update_time));
540 ffclock_read_counter(&cest.update_ffcount);
541 cest.leapsec_next = 0;
542 cest.period = ((1ULL << 63) / tc->tc_frequency) << 1;
545 cest.status = FFCLOCK_STA_UNSYNC;
546 cest.leapsec_total = 0;
549 mtx_lock(&ffclock_mtx);
550 bcopy(&cest, &ffclock_estimate, sizeof(struct ffclock_estimate));
551 ffclock_updated = INT8_MAX;
552 mtx_unlock(&ffclock_mtx);
554 printf("ffclock reset: %s (%llu Hz), time = %ld.%09lu\n", tc->tc_name,
555 (unsigned long long)tc->tc_frequency, (long)ts->tv_sec,
556 (unsigned long)ts->tv_nsec);
560 * Sub-routine to convert a time interval measured in RAW counter units to time
561 * in seconds stored in bintime format.
562 * NOTE: bintime_mul requires u_int, but the value of the ffcounter may be
563 * larger than the max value of u_int (on 32 bit architecture). Loop to consume
567 ffclock_convert_delta(ffcounter ffdelta, uint64_t period, struct bintime *bt)
570 ffcounter delta, delta_max;
572 delta_max = (1ULL << (8 * sizeof(unsigned int))) - 1;
575 if (ffdelta > delta_max)
581 bintime_mul(&bt2, (unsigned int)delta);
582 bintime_add(bt, &bt2);
584 } while (ffdelta > 0);
588 * Update the fftimehands.
589 * Push the tick ffcount and time(s) forward based on current clock estimate.
590 * The conversion from ffcounter to bintime relies on the difference clock
591 * principle, whose accuracy relies on computing small time intervals. If a new
592 * clock estimate has been passed by the synchronisation daemon, make it
593 * current, and compute the linear interpolation for monotonic time if needed.
596 ffclock_windup(unsigned int delta)
598 struct ffclock_estimate *cest;
599 struct fftimehands *ffth;
600 struct bintime bt, gap_lerp;
603 unsigned int polling;
604 uint8_t forward_jump, ogen;
607 * Pick the next timehand, copy current ffclock estimates and move tick
608 * times and counter forward.
611 ffth = fftimehands->next;
615 bcopy(&fftimehands->cest, cest, sizeof(struct ffclock_estimate));
616 ffdelta = (ffcounter)delta;
617 ffth->period_lerp = fftimehands->period_lerp;
619 ffth->tick_time = fftimehands->tick_time;
620 ffclock_convert_delta(ffdelta, cest->period, &bt);
621 bintime_add(&ffth->tick_time, &bt);
623 ffth->tick_time_lerp = fftimehands->tick_time_lerp;
624 ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt);
625 bintime_add(&ffth->tick_time_lerp, &bt);
627 ffth->tick_ffcount = fftimehands->tick_ffcount + ffdelta;
630 * Assess the status of the clock, if the last update is too old, it is
631 * likely the synchronisation daemon is dead and the clock is free
634 if (ffclock_updated == 0) {
635 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
636 ffclock_convert_delta(ffdelta, cest->period, &bt);
637 if (bt.sec > 2 * FFCLOCK_SKM_SCALE)
638 ffclock_status |= FFCLOCK_STA_UNSYNC;
642 * If available, grab updated clock estimates and make them current.
643 * Recompute time at this tick using the updated estimates. The clock
644 * estimates passed the feed-forward synchronisation daemon may result
645 * in time conversion that is not monotonically increasing (just after
646 * the update). time_lerp is a particular linear interpolation over the
647 * synchronisation algo polling period that ensures monotonicity for the
648 * clock ids requesting it.
650 if (ffclock_updated > 0) {
651 bcopy(&ffclock_estimate, cest, sizeof(struct ffclock_estimate));
652 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
653 ffth->tick_time = cest->update_time;
654 ffclock_convert_delta(ffdelta, cest->period, &bt);
655 bintime_add(&ffth->tick_time, &bt);
657 /* ffclock_reset sets ffclock_updated to INT8_MAX */
658 if (ffclock_updated == INT8_MAX)
659 ffth->tick_time_lerp = ffth->tick_time;
661 if (bintime_cmp(&ffth->tick_time, &ffth->tick_time_lerp, >))
666 bintime_clear(&gap_lerp);
668 gap_lerp = ffth->tick_time;
669 bintime_sub(&gap_lerp, &ffth->tick_time_lerp);
671 gap_lerp = ffth->tick_time_lerp;
672 bintime_sub(&gap_lerp, &ffth->tick_time);
676 * The reset from the RTC clock may be far from accurate, and
677 * reducing the gap between real time and interpolated time
678 * could take a very long time if the interpolated clock insists
679 * on strict monotonicity. The clock is reset under very strict
680 * conditions (kernel time is known to be wrong and
681 * synchronization daemon has been restarted recently.
682 * ffclock_boottime absorbs the jump to ensure boot time is
683 * correct and uptime functions stay consistent.
685 if (((ffclock_status & FFCLOCK_STA_UNSYNC) == FFCLOCK_STA_UNSYNC) &&
686 ((cest->status & FFCLOCK_STA_UNSYNC) == 0) &&
687 ((cest->status & FFCLOCK_STA_WARMUP) == FFCLOCK_STA_WARMUP)) {
689 bintime_add(&ffclock_boottime, &gap_lerp);
691 bintime_sub(&ffclock_boottime, &gap_lerp);
692 ffth->tick_time_lerp = ffth->tick_time;
693 bintime_clear(&gap_lerp);
696 ffclock_status = cest->status;
697 ffth->period_lerp = cest->period;
700 * Compute corrected period used for the linear interpolation of
701 * time. The rate of linear interpolation is capped to 5000PPM
704 if (bintime_isset(&gap_lerp)) {
705 ffdelta = cest->update_ffcount;
706 ffdelta -= fftimehands->cest.update_ffcount;
707 ffclock_convert_delta(ffdelta, cest->period, &bt);
710 bt.frac = 5000000 * (uint64_t)18446744073LL;
711 bintime_mul(&bt, polling);
712 if (bintime_cmp(&gap_lerp, &bt, >))
715 /* Approximate 1 sec by 1-(1/2^64) to ease arithmetic */
717 if (gap_lerp.sec > 0) {
719 frac /= ffdelta / gap_lerp.sec;
721 frac += gap_lerp.frac / ffdelta;
724 ffth->period_lerp += frac;
726 ffth->period_lerp -= frac;
738 * Adjust the fftimehands when the timecounter is changed. Stating the obvious,
739 * the old and new hardware counter cannot be read simultaneously. tc_windup()
740 * does read the two counters 'back to back', but a few cycles are effectively
741 * lost, and not accumulated in tick_ffcount. This is a fairly radical
742 * operation for a feed-forward synchronization daemon, and it is its job to not
743 * pushing irrelevant data to the kernel. Because there is no locking here,
744 * simply force to ignore pending or next update to give daemon a chance to
745 * realize the counter has changed.
748 ffclock_change_tc(struct timehands *th)
750 struct fftimehands *ffth;
751 struct ffclock_estimate *cest;
752 struct timecounter *tc;
756 ffth = fftimehands->next;
761 bcopy(&(fftimehands->cest), cest, sizeof(struct ffclock_estimate));
762 cest->period = ((1ULL << 63) / tc->tc_frequency ) << 1;
765 cest->status |= FFCLOCK_STA_UNSYNC;
767 ffth->tick_ffcount = fftimehands->tick_ffcount;
768 ffth->tick_time_lerp = fftimehands->tick_time_lerp;
769 ffth->tick_time = fftimehands->tick_time;
770 ffth->period_lerp = cest->period;
772 /* Do not lock but ignore next update from synchronization daemon. */
782 * Retrieve feed-forward counter and time of last kernel tick.
785 ffclock_last_tick(ffcounter *ffcount, struct bintime *bt, uint32_t flags)
787 struct fftimehands *ffth;
791 * No locking but check generation has not changed. Also need to make
792 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
797 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP)
798 *bt = ffth->tick_time_lerp;
800 *bt = ffth->tick_time;
801 *ffcount = ffth->tick_ffcount;
802 } while (gen == 0 || gen != ffth->gen);
806 * Absolute clock conversion. Low level function to convert ffcounter to
807 * bintime. The ffcounter is converted using the current ffclock period estimate
808 * or the "interpolated period" to ensure monotonicity.
809 * NOTE: this conversion may have been deferred, and the clock updated since the
810 * hardware counter has been read.
813 ffclock_convert_abs(ffcounter ffcount, struct bintime *bt, uint32_t flags)
815 struct fftimehands *ffth;
821 * No locking but check generation has not changed. Also need to make
822 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
827 if (ffcount > ffth->tick_ffcount)
828 ffdelta = ffcount - ffth->tick_ffcount;
830 ffdelta = ffth->tick_ffcount - ffcount;
832 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP) {
833 *bt = ffth->tick_time_lerp;
834 ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt2);
836 *bt = ffth->tick_time;
837 ffclock_convert_delta(ffdelta, ffth->cest.period, &bt2);
840 if (ffcount > ffth->tick_ffcount)
841 bintime_add(bt, &bt2);
843 bintime_sub(bt, &bt2);
844 } while (gen == 0 || gen != ffth->gen);
848 * Difference clock conversion.
849 * Low level function to Convert a time interval measured in RAW counter units
850 * into bintime. The difference clock allows measuring small intervals much more
851 * reliably than the absolute clock.
854 ffclock_convert_diff(ffcounter ffdelta, struct bintime *bt)
856 struct fftimehands *ffth;
859 /* No locking but check generation has not changed. */
863 ffclock_convert_delta(ffdelta, ffth->cest.period, bt);
864 } while (gen == 0 || gen != ffth->gen);
868 * Access to current ffcounter value.
871 ffclock_read_counter(ffcounter *ffcount)
873 struct timehands *th;
874 struct fftimehands *ffth;
875 unsigned int gen, delta;
878 * ffclock_windup() called from tc_windup(), safe to rely on
879 * th->th_generation only, for correct delta and ffcounter.
883 gen = th->th_generation;
885 delta = tc_delta(th);
886 *ffcount = ffth->tick_ffcount;
887 } while (gen == 0 || gen != th->th_generation);
893 binuptime(struct bintime *bt)
896 binuptime_fromclock(bt, sysclock_active);
900 nanouptime(struct timespec *tsp)
903 nanouptime_fromclock(tsp, sysclock_active);
907 microuptime(struct timeval *tvp)
910 microuptime_fromclock(tvp, sysclock_active);
914 bintime(struct bintime *bt)
917 bintime_fromclock(bt, sysclock_active);
921 nanotime(struct timespec *tsp)
924 nanotime_fromclock(tsp, sysclock_active);
928 microtime(struct timeval *tvp)
931 microtime_fromclock(tvp, sysclock_active);
935 getbinuptime(struct bintime *bt)
938 getbinuptime_fromclock(bt, sysclock_active);
942 getnanouptime(struct timespec *tsp)
945 getnanouptime_fromclock(tsp, sysclock_active);
949 getmicrouptime(struct timeval *tvp)
952 getmicrouptime_fromclock(tvp, sysclock_active);
956 getbintime(struct bintime *bt)
959 getbintime_fromclock(bt, sysclock_active);
963 getnanotime(struct timespec *tsp)
966 getnanotime_fromclock(tsp, sysclock_active);
970 getmicrotime(struct timeval *tvp)
973 getmicrouptime_fromclock(tvp, sysclock_active);
979 * This is a clone of getnanotime and used for walltimestamps.
980 * The dtrace_ prefix prevents fbt from creating probes for
981 * it so walltimestamp can be safely used in all fbt probes.
984 dtrace_getnanotime(struct timespec *tsp)
986 struct timehands *th;
991 gen = th->th_generation;
992 *tsp = th->th_nanotime;
993 } while (gen == 0 || gen != th->th_generation);
997 * System clock currently providing time to the system. Modifiable via sysctl
998 * when the FFCLOCK option is defined.
1000 int sysclock_active = SYSCLOCK_FBCK;
1002 /* Internal NTP status and error estimates. */
1003 extern int time_status;
1004 extern long time_esterror;
1007 * Take a snapshot of sysclock data which can be used to compare system clocks
1008 * and generate timestamps after the fact.
1011 sysclock_getsnapshot(struct sysclock_snap *clock_snap, int fast)
1013 struct fbclock_info *fbi;
1014 struct timehands *th;
1016 unsigned int delta, gen;
1019 struct fftimehands *ffth;
1020 struct ffclock_info *ffi;
1021 struct ffclock_estimate cest;
1023 ffi = &clock_snap->ff_info;
1026 fbi = &clock_snap->fb_info;
1031 gen = th->th_generation;
1032 fbi->th_scale = th->th_scale;
1033 fbi->tick_time = th->th_offset;
1036 ffi->tick_time = ffth->tick_time_lerp;
1037 ffi->tick_time_lerp = ffth->tick_time_lerp;
1038 ffi->period = ffth->cest.period;
1039 ffi->period_lerp = ffth->period_lerp;
1040 clock_snap->ffcount = ffth->tick_ffcount;
1044 delta = tc_delta(th);
1045 } while (gen == 0 || gen != th->th_generation);
1047 clock_snap->delta = delta;
1048 clock_snap->sysclock_active = sysclock_active;
1050 /* Record feedback clock status and error. */
1051 clock_snap->fb_info.status = time_status;
1052 /* XXX: Very crude estimate of feedback clock error. */
1053 bt.sec = time_esterror / 1000000;
1054 bt.frac = ((time_esterror - bt.sec) * 1000000) *
1055 (uint64_t)18446744073709ULL;
1056 clock_snap->fb_info.error = bt;
1060 clock_snap->ffcount += delta;
1062 /* Record feed-forward clock leap second adjustment. */
1063 ffi->leapsec_adjustment = cest.leapsec_total;
1064 if (clock_snap->ffcount > cest.leapsec_next)
1065 ffi->leapsec_adjustment -= cest.leapsec;
1067 /* Record feed-forward clock status and error. */
1068 clock_snap->ff_info.status = cest.status;
1069 ffcount = clock_snap->ffcount - cest.update_ffcount;
1070 ffclock_convert_delta(ffcount, cest.period, &bt);
1071 /* 18446744073709 = int(2^64/1e12), err_bound_rate in [ps/s]. */
1072 bintime_mul(&bt, cest.errb_rate * (uint64_t)18446744073709ULL);
1073 /* 18446744073 = int(2^64 / 1e9), since err_abs in [ns]. */
1074 bintime_addx(&bt, cest.errb_abs * (uint64_t)18446744073ULL);
1075 clock_snap->ff_info.error = bt;
1080 * Convert a sysclock snapshot into a struct bintime based on the specified
1081 * clock source and flags.
1084 sysclock_snap2bintime(struct sysclock_snap *cs, struct bintime *bt,
1085 int whichclock, uint32_t flags)
1092 switch (whichclock) {
1094 *bt = cs->fb_info.tick_time;
1096 /* If snapshot was created with !fast, delta will be >0. */
1098 bintime_addx(bt, cs->fb_info.th_scale * cs->delta);
1100 if ((flags & FBCLOCK_UPTIME) == 0)
1101 bintime_add(bt, &boottimebin);
1105 if (flags & FFCLOCK_LERP) {
1106 *bt = cs->ff_info.tick_time_lerp;
1107 period = cs->ff_info.period_lerp;
1109 *bt = cs->ff_info.tick_time;
1110 period = cs->ff_info.period;
1113 /* If snapshot was created with !fast, delta will be >0. */
1114 if (cs->delta > 0) {
1115 ffclock_convert_delta(cs->delta, period, &bt2);
1116 bintime_add(bt, &bt2);
1119 /* Leap second adjustment. */
1120 if (flags & FFCLOCK_LEAPSEC)
1121 bt->sec -= cs->ff_info.leapsec_adjustment;
1123 /* Boot time adjustment, for uptime/monotonic clocks. */
1124 if (flags & FFCLOCK_UPTIME)
1125 bintime_sub(bt, &ffclock_boottime);
1137 * Initialize a new timecounter and possibly use it.
1140 tc_init(struct timecounter *tc)
1143 struct sysctl_oid *tc_root;
1145 u = tc->tc_frequency / tc->tc_counter_mask;
1146 /* XXX: We need some margin here, 10% is a guess */
1149 if (u > hz && tc->tc_quality >= 0) {
1150 tc->tc_quality = -2000;
1152 printf("Timecounter \"%s\" frequency %ju Hz",
1153 tc->tc_name, (uintmax_t)tc->tc_frequency);
1154 printf(" -- Insufficient hz, needs at least %u\n", u);
1156 } else if (tc->tc_quality >= 0 || bootverbose) {
1157 printf("Timecounter \"%s\" frequency %ju Hz quality %d\n",
1158 tc->tc_name, (uintmax_t)tc->tc_frequency,
1162 tc->tc_next = timecounters;
1165 * Set up sysctl tree for this counter.
1167 tc_root = SYSCTL_ADD_NODE(NULL,
1168 SYSCTL_STATIC_CHILDREN(_kern_timecounter_tc), OID_AUTO, tc->tc_name,
1169 CTLFLAG_RW, 0, "timecounter description");
1170 SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1171 "mask", CTLFLAG_RD, &(tc->tc_counter_mask), 0,
1172 "mask for implemented bits");
1173 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1174 "counter", CTLTYPE_UINT | CTLFLAG_RD, tc, sizeof(*tc),
1175 sysctl_kern_timecounter_get, "IU", "current timecounter value");
1176 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1177 "frequency", CTLTYPE_U64 | CTLFLAG_RD, tc, sizeof(*tc),
1178 sysctl_kern_timecounter_freq, "QU", "timecounter frequency");
1179 SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1180 "quality", CTLFLAG_RD, &(tc->tc_quality), 0,
1181 "goodness of time counter");
1183 * Never automatically use a timecounter with negative quality.
1184 * Even though we run on the dummy counter, switching here may be
1185 * worse since this timecounter may not be monotonous.
1187 if (tc->tc_quality < 0)
1189 if (tc->tc_quality < timecounter->tc_quality)
1191 if (tc->tc_quality == timecounter->tc_quality &&
1192 tc->tc_frequency < timecounter->tc_frequency)
1194 (void)tc->tc_get_timecount(tc);
1195 (void)tc->tc_get_timecount(tc);
1199 /* Report the frequency of the current timecounter. */
1201 tc_getfrequency(void)
1204 return (timehands->th_counter->tc_frequency);
1208 * Step our concept of UTC. This is done by modifying our estimate of
1213 tc_setclock(struct timespec *ts)
1215 struct timespec tbef, taft;
1216 struct bintime bt, bt2;
1218 cpu_tick_calibrate(1);
1220 timespec2bintime(ts, &bt);
1222 bintime_sub(&bt, &bt2);
1223 bintime_add(&bt2, &boottimebin);
1225 bintime2timeval(&bt, &boottime);
1227 /* XXX fiddle all the little crinkly bits around the fiords... */
1230 if (timestepwarnings) {
1232 "Time stepped from %jd.%09ld to %jd.%09ld (%jd.%09ld)\n",
1233 (intmax_t)tbef.tv_sec, tbef.tv_nsec,
1234 (intmax_t)taft.tv_sec, taft.tv_nsec,
1235 (intmax_t)ts->tv_sec, ts->tv_nsec);
1237 cpu_tick_calibrate(1);
1241 * Initialize the next struct timehands in the ring and make
1242 * it the active timehands. Along the way we might switch to a different
1243 * timecounter and/or do seconds processing in NTP. Slightly magic.
1249 struct timehands *th, *tho;
1251 u_int delta, ncount, ogen;
1256 * Make the next timehands a copy of the current one, but do not
1257 * overwrite the generation or next pointer. While we update
1258 * the contents, the generation must be zero.
1262 ogen = th->th_generation;
1263 th->th_generation = 0;
1264 bcopy(tho, th, offsetof(struct timehands, th_generation));
1267 * Capture a timecounter delta on the current timecounter and if
1268 * changing timecounters, a counter value from the new timecounter.
1269 * Update the offset fields accordingly.
1271 delta = tc_delta(th);
1272 if (th->th_counter != timecounter)
1273 ncount = timecounter->tc_get_timecount(timecounter);
1277 ffclock_windup(delta);
1279 th->th_offset_count += delta;
1280 th->th_offset_count &= th->th_counter->tc_counter_mask;
1281 while (delta > th->th_counter->tc_frequency) {
1282 /* Eat complete unadjusted seconds. */
1283 delta -= th->th_counter->tc_frequency;
1284 th->th_offset.sec++;
1286 if ((delta > th->th_counter->tc_frequency / 2) &&
1287 (th->th_scale * delta < ((uint64_t)1 << 63))) {
1288 /* The product th_scale * delta just barely overflows. */
1289 th->th_offset.sec++;
1291 bintime_addx(&th->th_offset, th->th_scale * delta);
1294 * Hardware latching timecounters may not generate interrupts on
1295 * PPS events, so instead we poll them. There is a finite risk that
1296 * the hardware might capture a count which is later than the one we
1297 * got above, and therefore possibly in the next NTP second which might
1298 * have a different rate than the current NTP second. It doesn't
1299 * matter in practice.
1301 if (tho->th_counter->tc_poll_pps)
1302 tho->th_counter->tc_poll_pps(tho->th_counter);
1305 * Deal with NTP second processing. The for loop normally
1306 * iterates at most once, but in extreme situations it might
1307 * keep NTP sane if timeouts are not run for several seconds.
1308 * At boot, the time step can be large when the TOD hardware
1309 * has been read, so on really large steps, we call
1310 * ntp_update_second only twice. We need to call it twice in
1311 * case we missed a leap second.
1314 bintime_add(&bt, &boottimebin);
1315 i = bt.sec - tho->th_microtime.tv_sec;
1318 for (; i > 0; i--) {
1320 ntp_update_second(&th->th_adjustment, &bt.sec);
1322 boottimebin.sec += bt.sec - t;
1324 /* Update the UTC timestamps used by the get*() functions. */
1325 /* XXX shouldn't do this here. Should force non-`get' versions. */
1326 bintime2timeval(&bt, &th->th_microtime);
1327 bintime2timespec(&bt, &th->th_nanotime);
1329 /* Now is a good time to change timecounters. */
1330 if (th->th_counter != timecounter) {
1332 if ((timecounter->tc_flags & TC_FLAGS_C2STOP) != 0)
1333 cpu_disable_c2_sleep++;
1334 if ((th->th_counter->tc_flags & TC_FLAGS_C2STOP) != 0)
1335 cpu_disable_c2_sleep--;
1337 th->th_counter = timecounter;
1338 th->th_offset_count = ncount;
1339 tc_min_ticktock_freq = max(1, timecounter->tc_frequency /
1340 (((uint64_t)timecounter->tc_counter_mask + 1) / 3));
1342 ffclock_change_tc(th);
1347 * Recalculate the scaling factor. We want the number of 1/2^64
1348 * fractions of a second per period of the hardware counter, taking
1349 * into account the th_adjustment factor which the NTP PLL/adjtime(2)
1350 * processing provides us with.
1352 * The th_adjustment is nanoseconds per second with 32 bit binary
1353 * fraction and we want 64 bit binary fraction of second:
1355 * x = a * 2^32 / 10^9 = a * 4.294967296
1357 * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
1358 * we can only multiply by about 850 without overflowing, that
1359 * leaves no suitably precise fractions for multiply before divide.
1361 * Divide before multiply with a fraction of 2199/512 results in a
1362 * systematic undercompensation of 10PPM of th_adjustment. On a
1363 * 5000PPM adjustment this is a 0.05PPM error. This is acceptable.
1365 * We happily sacrifice the lowest of the 64 bits of our result
1366 * to the goddess of code clarity.
1369 scale = (uint64_t)1 << 63;
1370 scale += (th->th_adjustment / 1024) * 2199;
1371 scale /= th->th_counter->tc_frequency;
1372 th->th_scale = scale * 2;
1375 * Now that the struct timehands is again consistent, set the new
1376 * generation number, making sure to not make it zero.
1380 th->th_generation = ogen;
1382 /* Go live with the new struct timehands. */
1384 switch (sysclock_active) {
1387 time_second = th->th_microtime.tv_sec;
1388 time_uptime = th->th_offset.sec;
1392 time_second = fftimehands->tick_time_lerp.sec;
1393 time_uptime = fftimehands->tick_time_lerp.sec - ffclock_boottime.sec;
1399 timekeep_push_vdso();
1402 /* Report or change the active timecounter hardware. */
1404 sysctl_kern_timecounter_hardware(SYSCTL_HANDLER_ARGS)
1407 struct timecounter *newtc, *tc;
1411 strlcpy(newname, tc->tc_name, sizeof(newname));
1413 error = sysctl_handle_string(oidp, &newname[0], sizeof(newname), req);
1414 if (error != 0 || req->newptr == NULL ||
1415 strcmp(newname, tc->tc_name) == 0)
1417 for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
1418 if (strcmp(newname, newtc->tc_name) != 0)
1421 /* Warm up new timecounter. */
1422 (void)newtc->tc_get_timecount(newtc);
1423 (void)newtc->tc_get_timecount(newtc);
1425 timecounter = newtc;
1426 timekeep_push_vdso();
1432 SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware, CTLTYPE_STRING | CTLFLAG_RW,
1433 0, 0, sysctl_kern_timecounter_hardware, "A",
1434 "Timecounter hardware selected");
1437 /* Report or change the active timecounter hardware. */
1439 sysctl_kern_timecounter_choice(SYSCTL_HANDLER_ARGS)
1442 struct timecounter *tc;
1447 for (tc = timecounters; error == 0 && tc != NULL; tc = tc->tc_next) {
1448 sprintf(buf, "%s%s(%d)",
1449 spc, tc->tc_name, tc->tc_quality);
1450 error = SYSCTL_OUT(req, buf, strlen(buf));
1456 SYSCTL_PROC(_kern_timecounter, OID_AUTO, choice, CTLTYPE_STRING | CTLFLAG_RD,
1457 0, 0, sysctl_kern_timecounter_choice, "A", "Timecounter hardware detected");
1460 * RFC 2783 PPS-API implementation.
1464 * Return true if the driver is aware of the abi version extensions in the
1465 * pps_state structure, and it supports at least the given abi version number.
1468 abi_aware(struct pps_state *pps, int vers)
1471 return ((pps->kcmode & KCMODE_ABIFLAG) && pps->driver_abi >= vers);
1475 pps_fetch(struct pps_fetch_args *fapi, struct pps_state *pps)
1478 pps_seq_t aseq, cseq;
1481 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1485 * If no timeout is requested, immediately return whatever values were
1486 * most recently captured. If timeout seconds is -1, that's a request
1487 * to block without a timeout. WITNESS won't let us sleep forever
1488 * without a lock (we really don't need a lock), so just repeatedly
1489 * sleep a long time.
1491 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec) {
1492 if (fapi->timeout.tv_sec == -1)
1495 tv.tv_sec = fapi->timeout.tv_sec;
1496 tv.tv_usec = fapi->timeout.tv_nsec / 1000;
1499 aseq = pps->ppsinfo.assert_sequence;
1500 cseq = pps->ppsinfo.clear_sequence;
1501 while (aseq == pps->ppsinfo.assert_sequence &&
1502 cseq == pps->ppsinfo.clear_sequence) {
1503 if (abi_aware(pps, 1) && pps->driver_mtx != NULL) {
1504 if (pps->flags & PPSFLAG_MTX_SPIN) {
1505 err = msleep_spin(pps, pps->driver_mtx,
1508 err = msleep(pps, pps->driver_mtx, PCATCH,
1512 err = tsleep(pps, PCATCH, "ppsfch", timo);
1514 if (err == EWOULDBLOCK) {
1515 if (fapi->timeout.tv_sec == -1) {
1520 } else if (err != 0) {
1526 pps->ppsinfo.current_mode = pps->ppsparam.mode;
1527 fapi->pps_info_buf = pps->ppsinfo;
1533 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
1536 struct pps_fetch_args *fapi;
1538 struct pps_fetch_ffc_args *fapi_ffc;
1541 struct pps_kcbind_args *kapi;
1544 KASSERT(pps != NULL, ("NULL pps pointer in pps_ioctl"));
1546 case PPS_IOC_CREATE:
1548 case PPS_IOC_DESTROY:
1550 case PPS_IOC_SETPARAMS:
1551 app = (pps_params_t *)data;
1552 if (app->mode & ~pps->ppscap)
1555 /* Ensure only a single clock is selected for ffc timestamp. */
1556 if ((app->mode & PPS_TSCLK_MASK) == PPS_TSCLK_MASK)
1559 pps->ppsparam = *app;
1561 case PPS_IOC_GETPARAMS:
1562 app = (pps_params_t *)data;
1563 *app = pps->ppsparam;
1564 app->api_version = PPS_API_VERS_1;
1566 case PPS_IOC_GETCAP:
1567 *(int*)data = pps->ppscap;
1570 fapi = (struct pps_fetch_args *)data;
1571 return (pps_fetch(fapi, pps));
1573 case PPS_IOC_FETCH_FFCOUNTER:
1574 fapi_ffc = (struct pps_fetch_ffc_args *)data;
1575 if (fapi_ffc->tsformat && fapi_ffc->tsformat !=
1578 if (fapi_ffc->timeout.tv_sec || fapi_ffc->timeout.tv_nsec)
1579 return (EOPNOTSUPP);
1580 pps->ppsinfo_ffc.current_mode = pps->ppsparam.mode;
1581 fapi_ffc->pps_info_buf_ffc = pps->ppsinfo_ffc;
1582 /* Overwrite timestamps if feedback clock selected. */
1583 switch (pps->ppsparam.mode & PPS_TSCLK_MASK) {
1584 case PPS_TSCLK_FBCK:
1585 fapi_ffc->pps_info_buf_ffc.assert_timestamp =
1586 pps->ppsinfo.assert_timestamp;
1587 fapi_ffc->pps_info_buf_ffc.clear_timestamp =
1588 pps->ppsinfo.clear_timestamp;
1590 case PPS_TSCLK_FFWD:
1596 #endif /* FFCLOCK */
1597 case PPS_IOC_KCBIND:
1599 kapi = (struct pps_kcbind_args *)data;
1600 /* XXX Only root should be able to do this */
1601 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1603 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1605 if (kapi->edge & ~pps->ppscap)
1607 pps->kcmode = (kapi->edge & KCMODE_EDGEMASK) |
1608 (pps->kcmode & KCMODE_ABIFLAG);
1611 return (EOPNOTSUPP);
1619 pps_init(struct pps_state *pps)
1621 pps->ppscap |= PPS_TSFMT_TSPEC | PPS_CANWAIT;
1622 if (pps->ppscap & PPS_CAPTUREASSERT)
1623 pps->ppscap |= PPS_OFFSETASSERT;
1624 if (pps->ppscap & PPS_CAPTURECLEAR)
1625 pps->ppscap |= PPS_OFFSETCLEAR;
1627 pps->ppscap |= PPS_TSCLK_MASK;
1629 pps->kcmode &= ~KCMODE_ABIFLAG;
1633 pps_init_abi(struct pps_state *pps)
1637 if (pps->driver_abi > 0) {
1638 pps->kcmode |= KCMODE_ABIFLAG;
1639 pps->kernel_abi = PPS_ABI_VERSION;
1644 pps_capture(struct pps_state *pps)
1646 struct timehands *th;
1648 KASSERT(pps != NULL, ("NULL pps pointer in pps_capture"));
1650 pps->capgen = th->th_generation;
1653 pps->capffth = fftimehands;
1655 pps->capcount = th->th_counter->tc_get_timecount(th->th_counter);
1656 if (pps->capgen != th->th_generation)
1661 pps_event(struct pps_state *pps, int event)
1664 struct timespec ts, *tsp, *osp;
1665 u_int tcount, *pcount;
1669 struct timespec *tsp_ffc;
1670 pps_seq_t *pseq_ffc;
1674 KASSERT(pps != NULL, ("NULL pps pointer in pps_event"));
1675 /* Nothing to do if not currently set to capture this event type. */
1676 if ((event & pps->ppsparam.mode) == 0)
1678 /* If the timecounter was wound up underneath us, bail out. */
1679 if (pps->capgen == 0 || pps->capgen != pps->capth->th_generation)
1682 /* Things would be easier with arrays. */
1683 if (event == PPS_CAPTUREASSERT) {
1684 tsp = &pps->ppsinfo.assert_timestamp;
1685 osp = &pps->ppsparam.assert_offset;
1686 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1687 fhard = pps->kcmode & PPS_CAPTUREASSERT;
1688 pcount = &pps->ppscount[0];
1689 pseq = &pps->ppsinfo.assert_sequence;
1691 ffcount = &pps->ppsinfo_ffc.assert_ffcount;
1692 tsp_ffc = &pps->ppsinfo_ffc.assert_timestamp;
1693 pseq_ffc = &pps->ppsinfo_ffc.assert_sequence;
1696 tsp = &pps->ppsinfo.clear_timestamp;
1697 osp = &pps->ppsparam.clear_offset;
1698 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1699 fhard = pps->kcmode & PPS_CAPTURECLEAR;
1700 pcount = &pps->ppscount[1];
1701 pseq = &pps->ppsinfo.clear_sequence;
1703 ffcount = &pps->ppsinfo_ffc.clear_ffcount;
1704 tsp_ffc = &pps->ppsinfo_ffc.clear_timestamp;
1705 pseq_ffc = &pps->ppsinfo_ffc.clear_sequence;
1710 * If the timecounter changed, we cannot compare the count values, so
1711 * we have to drop the rest of the PPS-stuff until the next event.
1713 if (pps->ppstc != pps->capth->th_counter) {
1714 pps->ppstc = pps->capth->th_counter;
1715 *pcount = pps->capcount;
1716 pps->ppscount[2] = pps->capcount;
1720 /* Convert the count to a timespec. */
1721 tcount = pps->capcount - pps->capth->th_offset_count;
1722 tcount &= pps->capth->th_counter->tc_counter_mask;
1723 bt = pps->capth->th_offset;
1724 bintime_addx(&bt, pps->capth->th_scale * tcount);
1725 bintime_add(&bt, &boottimebin);
1726 bintime2timespec(&bt, &ts);
1728 /* If the timecounter was wound up underneath us, bail out. */
1729 if (pps->capgen != pps->capth->th_generation)
1732 *pcount = pps->capcount;
1737 timespecadd(tsp, osp);
1738 if (tsp->tv_nsec < 0) {
1739 tsp->tv_nsec += 1000000000;
1745 *ffcount = pps->capffth->tick_ffcount + tcount;
1746 bt = pps->capffth->tick_time;
1747 ffclock_convert_delta(tcount, pps->capffth->cest.period, &bt);
1748 bintime_add(&bt, &pps->capffth->tick_time);
1749 bintime2timespec(&bt, &ts);
1759 * Feed the NTP PLL/FLL.
1760 * The FLL wants to know how many (hardware) nanoseconds
1761 * elapsed since the previous event.
1763 tcount = pps->capcount - pps->ppscount[2];
1764 pps->ppscount[2] = pps->capcount;
1765 tcount &= pps->capth->th_counter->tc_counter_mask;
1766 scale = (uint64_t)1 << 63;
1767 scale /= pps->capth->th_counter->tc_frequency;
1771 bintime_addx(&bt, scale * tcount);
1772 bintime2timespec(&bt, &ts);
1773 hardpps(tsp, ts.tv_nsec + 1000000000 * ts.tv_sec);
1777 /* Wakeup anyone sleeping in pps_fetch(). */
1782 * Timecounters need to be updated every so often to prevent the hardware
1783 * counter from overflowing. Updating also recalculates the cached values
1784 * used by the get*() family of functions, so their precision depends on
1785 * the update frequency.
1789 SYSCTL_INT(_kern_timecounter, OID_AUTO, tick, CTLFLAG_RD, &tc_tick, 0,
1790 "Approximate number of hardclock ticks in a millisecond");
1793 tc_ticktock(int cnt)
1798 if (count < tc_tick)
1804 static void __inline
1805 tc_adjprecision(void)
1809 if (tc_timepercentage > 0) {
1810 t = (99 + tc_timepercentage) / tc_timepercentage;
1811 tc_precexp = fls(t + (t >> 1)) - 1;
1812 FREQ2BT(hz / tc_tick, &bt_timethreshold);
1813 FREQ2BT(hz, &bt_tickthreshold);
1814 bintime_shift(&bt_timethreshold, tc_precexp);
1815 bintime_shift(&bt_tickthreshold, tc_precexp);
1818 bt_timethreshold.sec = INT_MAX;
1819 bt_timethreshold.frac = ~(uint64_t)0;
1820 bt_tickthreshold = bt_timethreshold;
1822 sbt_timethreshold = bttosbt(bt_timethreshold);
1823 sbt_tickthreshold = bttosbt(bt_tickthreshold);
1827 sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS)
1831 val = tc_timepercentage;
1832 error = sysctl_handle_int(oidp, &val, 0, req);
1833 if (error != 0 || req->newptr == NULL)
1835 tc_timepercentage = val;
1841 inittimecounter(void *dummy)
1847 * Set the initial timeout to
1848 * max(1, <approx. number of hardclock ticks in a millisecond>).
1849 * People should probably not use the sysctl to set the timeout
1850 * to smaller than its inital value, since that value is the
1851 * smallest reasonable one. If they want better timestamps they
1852 * should use the non-"get"* functions.
1855 tc_tick = (hz + 500) / 1000;
1859 FREQ2BT(hz, &tick_bt);
1860 tick_sbt = bttosbt(tick_bt);
1861 tick_rate = hz / tc_tick;
1862 FREQ2BT(tick_rate, &tc_tick_bt);
1863 tc_tick_sbt = bttosbt(tc_tick_bt);
1864 p = (tc_tick * 1000000) / hz;
1865 printf("Timecounters tick every %d.%03u msec\n", p / 1000, p % 1000);
1870 /* warm up new timecounter (again) and get rolling. */
1871 (void)timecounter->tc_get_timecount(timecounter);
1872 (void)timecounter->tc_get_timecount(timecounter);
1876 SYSINIT(timecounter, SI_SUB_CLOCKS, SI_ORDER_SECOND, inittimecounter, NULL);
1878 /* Cpu tick handling -------------------------------------------------*/
1880 static int cpu_tick_variable;
1881 static uint64_t cpu_tick_frequency;
1886 static uint64_t base;
1887 static unsigned last;
1889 struct timecounter *tc;
1891 tc = timehands->th_counter;
1892 u = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
1894 base += (uint64_t)tc->tc_counter_mask + 1;
1900 cpu_tick_calibration(void)
1902 static time_t last_calib;
1904 if (time_uptime != last_calib && !(time_uptime & 0xf)) {
1905 cpu_tick_calibrate(0);
1906 last_calib = time_uptime;
1911 * This function gets called every 16 seconds on only one designated
1912 * CPU in the system from hardclock() via cpu_tick_calibration()().
1914 * Whenever the real time clock is stepped we get called with reset=1
1915 * to make sure we handle suspend/resume and similar events correctly.
1919 cpu_tick_calibrate(int reset)
1921 static uint64_t c_last;
1922 uint64_t c_this, c_delta;
1923 static struct bintime t_last;
1924 struct bintime t_this, t_delta;
1928 /* The clock was stepped, abort & reset */
1933 /* we don't calibrate fixed rate cputicks */
1934 if (!cpu_tick_variable)
1937 getbinuptime(&t_this);
1938 c_this = cpu_ticks();
1939 if (t_last.sec != 0) {
1940 c_delta = c_this - c_last;
1942 bintime_sub(&t_delta, &t_last);
1945 * 2^(64-20) / 16[s] =
1947 * 17.592.186.044.416 / 16 =
1948 * 1.099.511.627.776 [Hz]
1950 divi = t_delta.sec << 20;
1951 divi |= t_delta.frac >> (64 - 20);
1954 if (c_delta > cpu_tick_frequency) {
1955 if (0 && bootverbose)
1956 printf("cpu_tick increased to %ju Hz\n",
1958 cpu_tick_frequency = c_delta;
1966 set_cputicker(cpu_tick_f *func, uint64_t freq, unsigned var)
1970 cpu_ticks = tc_cpu_ticks;
1972 cpu_tick_frequency = freq;
1973 cpu_tick_variable = var;
1982 if (cpu_ticks == tc_cpu_ticks)
1983 return (tc_getfrequency());
1984 return (cpu_tick_frequency);
1988 * We need to be slightly careful converting cputicks to microseconds.
1989 * There is plenty of margin in 64 bits of microseconds (half a million
1990 * years) and in 64 bits at 4 GHz (146 years), but if we do a multiply
1991 * before divide conversion (to retain precision) we find that the
1992 * margin shrinks to 1.5 hours (one millionth of 146y).
1993 * With a three prong approach we never lose significant bits, no
1994 * matter what the cputick rate and length of timeinterval is.
1998 cputick2usec(uint64_t tick)
2001 if (tick > 18446744073709551LL) /* floor(2^64 / 1000) */
2002 return (tick / (cpu_tickrate() / 1000000LL));
2003 else if (tick > 18446744073709LL) /* floor(2^64 / 1000000) */
2004 return ((tick * 1000LL) / (cpu_tickrate() / 1000LL));
2006 return ((tick * 1000000LL) / cpu_tickrate());
2009 cpu_tick_f *cpu_ticks = tc_cpu_ticks;
2011 static int vdso_th_enable = 1;
2013 sysctl_fast_gettime(SYSCTL_HANDLER_ARGS)
2015 int old_vdso_th_enable, error;
2017 old_vdso_th_enable = vdso_th_enable;
2018 error = sysctl_handle_int(oidp, &old_vdso_th_enable, 0, req);
2021 vdso_th_enable = old_vdso_th_enable;
2022 timekeep_push_vdso();
2025 SYSCTL_PROC(_kern_timecounter, OID_AUTO, fast_gettime,
2026 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
2027 NULL, 0, sysctl_fast_gettime, "I", "Enable fast time of day");
2030 tc_fill_vdso_timehands(struct vdso_timehands *vdso_th)
2032 struct timehands *th;
2036 vdso_th->th_algo = VDSO_TH_ALGO_1;
2037 vdso_th->th_scale = th->th_scale;
2038 vdso_th->th_offset_count = th->th_offset_count;
2039 vdso_th->th_counter_mask = th->th_counter->tc_counter_mask;
2040 vdso_th->th_offset = th->th_offset;
2041 vdso_th->th_boottime = boottimebin;
2042 enabled = cpu_fill_vdso_timehands(vdso_th);
2043 if (!vdso_th_enable)
2048 #ifdef COMPAT_FREEBSD32
2050 tc_fill_vdso_timehands32(struct vdso_timehands32 *vdso_th32)
2052 struct timehands *th;
2056 vdso_th32->th_algo = VDSO_TH_ALGO_1;
2057 *(uint64_t *)&vdso_th32->th_scale[0] = th->th_scale;
2058 vdso_th32->th_offset_count = th->th_offset_count;
2059 vdso_th32->th_counter_mask = th->th_counter->tc_counter_mask;
2060 vdso_th32->th_offset.sec = th->th_offset.sec;
2061 *(uint64_t *)&vdso_th32->th_offset.frac[0] = th->th_offset.frac;
2062 vdso_th32->th_boottime.sec = boottimebin.sec;
2063 *(uint64_t *)&vdso_th32->th_boottime.frac[0] = boottimebin.frac;
2064 enabled = cpu_fill_vdso_timehands32(vdso_th32);
2065 if (!vdso_th_enable)