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>
28 #include <sys/mutex.h>
30 #include <sys/sysctl.h>
31 #include <sys/syslog.h>
32 #include <sys/systm.h>
33 #include <sys/timeffc.h>
34 #include <sys/timepps.h>
35 #include <sys/timetc.h>
36 #include <sys/timex.h>
40 * A large step happens on boot. This constant detects such steps.
41 * It is relatively small so that ntp_update_second gets called enough
42 * in the typical 'missed a couple of seconds' case, but doesn't loop
43 * forever when the time step is large.
45 #define LARGE_STEP 200
48 * Implement a dummy timecounter which we can use until we get a real one
49 * in the air. This allows the console and other early stuff to use
54 dummy_get_timecount(struct timecounter *tc)
61 static struct timecounter dummy_timecounter = {
62 dummy_get_timecount, 0, ~0u, 1000000, "dummy", -1000000
66 /* These fields must be initialized by the driver. */
67 struct timecounter *th_counter;
68 int64_t th_adjustment;
70 u_int th_offset_count;
71 struct bintime th_offset;
72 struct timeval th_microtime;
73 struct timespec th_nanotime;
74 /* Fields not to be copied in tc_windup start with th_generation. */
75 volatile u_int th_generation;
76 struct timehands *th_next;
79 static struct timehands th0;
80 static struct timehands th9 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th0};
81 static struct timehands th8 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th9};
82 static struct timehands th7 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th8};
83 static struct timehands th6 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th7};
84 static struct timehands th5 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th6};
85 static struct timehands th4 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th5};
86 static struct timehands th3 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th4};
87 static struct timehands th2 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th3};
88 static struct timehands th1 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th2};
89 static struct timehands th0 = {
92 (uint64_t)-1 / 1000000,
101 static struct timehands *volatile timehands = &th0;
102 struct timecounter *timecounter = &dummy_timecounter;
103 static struct timecounter *timecounters = &dummy_timecounter;
105 int tc_min_ticktock_freq = 1;
107 volatile time_t time_second = 1;
108 volatile time_t time_uptime = 1;
110 struct bintime boottimebin;
111 struct timeval boottime;
112 static int sysctl_kern_boottime(SYSCTL_HANDLER_ARGS);
113 SYSCTL_PROC(_kern, KERN_BOOTTIME, boottime, CTLTYPE_STRUCT|CTLFLAG_RD,
114 NULL, 0, sysctl_kern_boottime, "S,timeval", "System boottime");
116 SYSCTL_NODE(_kern, OID_AUTO, timecounter, CTLFLAG_RW, 0, "");
117 static SYSCTL_NODE(_kern_timecounter, OID_AUTO, tc, CTLFLAG_RW, 0, "");
119 static int timestepwarnings;
120 SYSCTL_INT(_kern_timecounter, OID_AUTO, stepwarnings, CTLFLAG_RW,
121 ×tepwarnings, 0, "Log time steps");
123 struct bintime bt_timethreshold;
124 struct bintime bt_tickthreshold;
125 sbintime_t sbt_timethreshold;
126 sbintime_t sbt_tickthreshold;
127 struct bintime tc_tick_bt;
128 sbintime_t tc_tick_sbt;
130 int tc_timepercentage = TC_DEFAULTPERC;
131 TUNABLE_INT("kern.timecounter.alloweddeviation", &tc_timepercentage);
132 static int sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS);
133 SYSCTL_PROC(_kern_timecounter, OID_AUTO, alloweddeviation,
134 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 0,
135 sysctl_kern_timecounter_adjprecision, "I",
136 "Allowed time interval deviation in percents");
138 static void tc_windup(void);
139 static void cpu_tick_calibrate(int);
141 void dtrace_getnanotime(struct timespec *tsp);
144 sysctl_kern_boottime(SYSCTL_HANDLER_ARGS)
150 if (req->flags & SCTL_MASK32) {
151 tv[0] = boottime.tv_sec;
152 tv[1] = boottime.tv_usec;
153 return SYSCTL_OUT(req, tv, sizeof(tv));
157 return SYSCTL_OUT(req, &boottime, sizeof(boottime));
161 sysctl_kern_timecounter_get(SYSCTL_HANDLER_ARGS)
164 struct timecounter *tc = arg1;
166 ncount = tc->tc_get_timecount(tc);
167 return sysctl_handle_int(oidp, &ncount, 0, req);
171 sysctl_kern_timecounter_freq(SYSCTL_HANDLER_ARGS)
174 struct timecounter *tc = arg1;
176 freq = tc->tc_frequency;
177 return sysctl_handle_64(oidp, &freq, 0, req);
181 * Return the difference between the timehands' counter value now and what
182 * was when we copied it to the timehands' offset_count.
184 static __inline u_int
185 tc_delta(struct timehands *th)
187 struct timecounter *tc;
190 return ((tc->tc_get_timecount(tc) - th->th_offset_count) &
191 tc->tc_counter_mask);
195 * Functions for reading the time. We have to loop until we are sure that
196 * the timehands that we operated on was not updated under our feet. See
197 * the comment in <sys/time.h> for a description of these 12 functions.
202 fbclock_binuptime(struct bintime *bt)
204 struct timehands *th;
209 gen = th->th_generation;
211 bintime_addx(bt, th->th_scale * tc_delta(th));
212 } while (gen == 0 || gen != th->th_generation);
216 fbclock_nanouptime(struct timespec *tsp)
220 fbclock_binuptime(&bt);
221 bintime2timespec(&bt, tsp);
225 fbclock_microuptime(struct timeval *tvp)
229 fbclock_binuptime(&bt);
230 bintime2timeval(&bt, tvp);
234 fbclock_bintime(struct bintime *bt)
237 fbclock_binuptime(bt);
238 bintime_add(bt, &boottimebin);
242 fbclock_nanotime(struct timespec *tsp)
246 fbclock_bintime(&bt);
247 bintime2timespec(&bt, tsp);
251 fbclock_microtime(struct timeval *tvp)
255 fbclock_bintime(&bt);
256 bintime2timeval(&bt, tvp);
260 fbclock_getbinuptime(struct bintime *bt)
262 struct timehands *th;
267 gen = th->th_generation;
269 } while (gen == 0 || gen != th->th_generation);
273 fbclock_getnanouptime(struct timespec *tsp)
275 struct timehands *th;
280 gen = th->th_generation;
281 bintime2timespec(&th->th_offset, tsp);
282 } while (gen == 0 || gen != th->th_generation);
286 fbclock_getmicrouptime(struct timeval *tvp)
288 struct timehands *th;
293 gen = th->th_generation;
294 bintime2timeval(&th->th_offset, tvp);
295 } while (gen == 0 || gen != th->th_generation);
299 fbclock_getbintime(struct bintime *bt)
301 struct timehands *th;
306 gen = th->th_generation;
308 } while (gen == 0 || gen != th->th_generation);
309 bintime_add(bt, &boottimebin);
313 fbclock_getnanotime(struct timespec *tsp)
315 struct timehands *th;
320 gen = th->th_generation;
321 *tsp = th->th_nanotime;
322 } while (gen == 0 || gen != th->th_generation);
326 fbclock_getmicrotime(struct timeval *tvp)
328 struct timehands *th;
333 gen = th->th_generation;
334 *tvp = th->th_microtime;
335 } while (gen == 0 || gen != th->th_generation);
339 binuptime(struct bintime *bt)
341 struct timehands *th;
346 gen = th->th_generation;
348 bintime_addx(bt, th->th_scale * tc_delta(th));
349 } while (gen == 0 || gen != th->th_generation);
353 nanouptime(struct timespec *tsp)
358 bintime2timespec(&bt, tsp);
362 microuptime(struct timeval *tvp)
367 bintime2timeval(&bt, tvp);
371 bintime(struct bintime *bt)
375 bintime_add(bt, &boottimebin);
379 nanotime(struct timespec *tsp)
384 bintime2timespec(&bt, tsp);
388 microtime(struct timeval *tvp)
393 bintime2timeval(&bt, tvp);
397 getbinuptime(struct bintime *bt)
399 struct timehands *th;
404 gen = th->th_generation;
406 } while (gen == 0 || gen != th->th_generation);
410 getnanouptime(struct timespec *tsp)
412 struct timehands *th;
417 gen = th->th_generation;
418 bintime2timespec(&th->th_offset, tsp);
419 } while (gen == 0 || gen != th->th_generation);
423 getmicrouptime(struct timeval *tvp)
425 struct timehands *th;
430 gen = th->th_generation;
431 bintime2timeval(&th->th_offset, tvp);
432 } while (gen == 0 || gen != th->th_generation);
436 getbintime(struct bintime *bt)
438 struct timehands *th;
443 gen = th->th_generation;
445 } while (gen == 0 || gen != th->th_generation);
446 bintime_add(bt, &boottimebin);
450 getnanotime(struct timespec *tsp)
452 struct timehands *th;
457 gen = th->th_generation;
458 *tsp = th->th_nanotime;
459 } while (gen == 0 || gen != th->th_generation);
463 getmicrotime(struct timeval *tvp)
465 struct timehands *th;
470 gen = th->th_generation;
471 *tvp = th->th_microtime;
472 } while (gen == 0 || gen != th->th_generation);
478 * Support for feed-forward synchronization algorithms. This is heavily inspired
479 * by the timehands mechanism but kept independent from it. *_windup() functions
480 * have some connection to avoid accessing the timecounter hardware more than
484 /* Feed-forward clock estimates kept updated by the synchronization daemon. */
485 struct ffclock_estimate ffclock_estimate;
486 struct bintime ffclock_boottime; /* Feed-forward boot time estimate. */
487 uint32_t ffclock_status; /* Feed-forward clock status. */
488 int8_t ffclock_updated; /* New estimates are available. */
489 struct mtx ffclock_mtx; /* Mutex on ffclock_estimate. */
492 struct ffclock_estimate cest;
493 struct bintime tick_time;
494 struct bintime tick_time_lerp;
495 ffcounter tick_ffcount;
496 uint64_t period_lerp;
497 volatile uint8_t gen;
498 struct fftimehands *next;
501 #define NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))
503 static struct fftimehands ffth[10];
504 static struct fftimehands *volatile fftimehands = ffth;
509 struct fftimehands *cur;
510 struct fftimehands *last;
512 memset(ffth, 0, sizeof(ffth));
514 last = ffth + NUM_ELEMENTS(ffth) - 1;
515 for (cur = ffth; cur < last; cur++)
520 ffclock_status = FFCLOCK_STA_UNSYNC;
521 mtx_init(&ffclock_mtx, "ffclock lock", NULL, MTX_DEF);
525 * Reset the feed-forward clock estimates. Called from inittodr() to get things
526 * kick started and uses the timecounter nominal frequency as a first period
527 * estimate. Note: this function may be called several time just after boot.
528 * Note: this is the only function that sets the value of boot time for the
529 * monotonic (i.e. uptime) version of the feed-forward clock.
532 ffclock_reset_clock(struct timespec *ts)
534 struct timecounter *tc;
535 struct ffclock_estimate cest;
537 tc = timehands->th_counter;
538 memset(&cest, 0, sizeof(struct ffclock_estimate));
540 timespec2bintime(ts, &ffclock_boottime);
541 timespec2bintime(ts, &(cest.update_time));
542 ffclock_read_counter(&cest.update_ffcount);
543 cest.leapsec_next = 0;
544 cest.period = ((1ULL << 63) / tc->tc_frequency) << 1;
547 cest.status = FFCLOCK_STA_UNSYNC;
548 cest.leapsec_total = 0;
551 mtx_lock(&ffclock_mtx);
552 bcopy(&cest, &ffclock_estimate, sizeof(struct ffclock_estimate));
553 ffclock_updated = INT8_MAX;
554 mtx_unlock(&ffclock_mtx);
556 printf("ffclock reset: %s (%llu Hz), time = %ld.%09lu\n", tc->tc_name,
557 (unsigned long long)tc->tc_frequency, (long)ts->tv_sec,
558 (unsigned long)ts->tv_nsec);
562 * Sub-routine to convert a time interval measured in RAW counter units to time
563 * in seconds stored in bintime format.
564 * NOTE: bintime_mul requires u_int, but the value of the ffcounter may be
565 * larger than the max value of u_int (on 32 bit architecture). Loop to consume
569 ffclock_convert_delta(ffcounter ffdelta, uint64_t period, struct bintime *bt)
572 ffcounter delta, delta_max;
574 delta_max = (1ULL << (8 * sizeof(unsigned int))) - 1;
577 if (ffdelta > delta_max)
583 bintime_mul(&bt2, (unsigned int)delta);
584 bintime_add(bt, &bt2);
586 } while (ffdelta > 0);
590 * Update the fftimehands.
591 * Push the tick ffcount and time(s) forward based on current clock estimate.
592 * The conversion from ffcounter to bintime relies on the difference clock
593 * principle, whose accuracy relies on computing small time intervals. If a new
594 * clock estimate has been passed by the synchronisation daemon, make it
595 * current, and compute the linear interpolation for monotonic time if needed.
598 ffclock_windup(unsigned int delta)
600 struct ffclock_estimate *cest;
601 struct fftimehands *ffth;
602 struct bintime bt, gap_lerp;
605 unsigned int polling;
606 uint8_t forward_jump, ogen;
609 * Pick the next timehand, copy current ffclock estimates and move tick
610 * times and counter forward.
613 ffth = fftimehands->next;
617 bcopy(&fftimehands->cest, cest, sizeof(struct ffclock_estimate));
618 ffdelta = (ffcounter)delta;
619 ffth->period_lerp = fftimehands->period_lerp;
621 ffth->tick_time = fftimehands->tick_time;
622 ffclock_convert_delta(ffdelta, cest->period, &bt);
623 bintime_add(&ffth->tick_time, &bt);
625 ffth->tick_time_lerp = fftimehands->tick_time_lerp;
626 ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt);
627 bintime_add(&ffth->tick_time_lerp, &bt);
629 ffth->tick_ffcount = fftimehands->tick_ffcount + ffdelta;
632 * Assess the status of the clock, if the last update is too old, it is
633 * likely the synchronisation daemon is dead and the clock is free
636 if (ffclock_updated == 0) {
637 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
638 ffclock_convert_delta(ffdelta, cest->period, &bt);
639 if (bt.sec > 2 * FFCLOCK_SKM_SCALE)
640 ffclock_status |= FFCLOCK_STA_UNSYNC;
644 * If available, grab updated clock estimates and make them current.
645 * Recompute time at this tick using the updated estimates. The clock
646 * estimates passed the feed-forward synchronisation daemon may result
647 * in time conversion that is not monotonically increasing (just after
648 * the update). time_lerp is a particular linear interpolation over the
649 * synchronisation algo polling period that ensures monotonicity for the
650 * clock ids requesting it.
652 if (ffclock_updated > 0) {
653 bcopy(&ffclock_estimate, cest, sizeof(struct ffclock_estimate));
654 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
655 ffth->tick_time = cest->update_time;
656 ffclock_convert_delta(ffdelta, cest->period, &bt);
657 bintime_add(&ffth->tick_time, &bt);
659 /* ffclock_reset sets ffclock_updated to INT8_MAX */
660 if (ffclock_updated == INT8_MAX)
661 ffth->tick_time_lerp = ffth->tick_time;
663 if (bintime_cmp(&ffth->tick_time, &ffth->tick_time_lerp, >))
668 bintime_clear(&gap_lerp);
670 gap_lerp = ffth->tick_time;
671 bintime_sub(&gap_lerp, &ffth->tick_time_lerp);
673 gap_lerp = ffth->tick_time_lerp;
674 bintime_sub(&gap_lerp, &ffth->tick_time);
678 * The reset from the RTC clock may be far from accurate, and
679 * reducing the gap between real time and interpolated time
680 * could take a very long time if the interpolated clock insists
681 * on strict monotonicity. The clock is reset under very strict
682 * conditions (kernel time is known to be wrong and
683 * synchronization daemon has been restarted recently.
684 * ffclock_boottime absorbs the jump to ensure boot time is
685 * correct and uptime functions stay consistent.
687 if (((ffclock_status & FFCLOCK_STA_UNSYNC) == FFCLOCK_STA_UNSYNC) &&
688 ((cest->status & FFCLOCK_STA_UNSYNC) == 0) &&
689 ((cest->status & FFCLOCK_STA_WARMUP) == FFCLOCK_STA_WARMUP)) {
691 bintime_add(&ffclock_boottime, &gap_lerp);
693 bintime_sub(&ffclock_boottime, &gap_lerp);
694 ffth->tick_time_lerp = ffth->tick_time;
695 bintime_clear(&gap_lerp);
698 ffclock_status = cest->status;
699 ffth->period_lerp = cest->period;
702 * Compute corrected period used for the linear interpolation of
703 * time. The rate of linear interpolation is capped to 5000PPM
706 if (bintime_isset(&gap_lerp)) {
707 ffdelta = cest->update_ffcount;
708 ffdelta -= fftimehands->cest.update_ffcount;
709 ffclock_convert_delta(ffdelta, cest->period, &bt);
712 bt.frac = 5000000 * (uint64_t)18446744073LL;
713 bintime_mul(&bt, polling);
714 if (bintime_cmp(&gap_lerp, &bt, >))
717 /* Approximate 1 sec by 1-(1/2^64) to ease arithmetic */
719 if (gap_lerp.sec > 0) {
721 frac /= ffdelta / gap_lerp.sec;
723 frac += gap_lerp.frac / ffdelta;
726 ffth->period_lerp += frac;
728 ffth->period_lerp -= frac;
740 * Adjust the fftimehands when the timecounter is changed. Stating the obvious,
741 * the old and new hardware counter cannot be read simultaneously. tc_windup()
742 * does read the two counters 'back to back', but a few cycles are effectively
743 * lost, and not accumulated in tick_ffcount. This is a fairly radical
744 * operation for a feed-forward synchronization daemon, and it is its job to not
745 * pushing irrelevant data to the kernel. Because there is no locking here,
746 * simply force to ignore pending or next update to give daemon a chance to
747 * realize the counter has changed.
750 ffclock_change_tc(struct timehands *th)
752 struct fftimehands *ffth;
753 struct ffclock_estimate *cest;
754 struct timecounter *tc;
758 ffth = fftimehands->next;
763 bcopy(&(fftimehands->cest), cest, sizeof(struct ffclock_estimate));
764 cest->period = ((1ULL << 63) / tc->tc_frequency ) << 1;
767 cest->status |= FFCLOCK_STA_UNSYNC;
769 ffth->tick_ffcount = fftimehands->tick_ffcount;
770 ffth->tick_time_lerp = fftimehands->tick_time_lerp;
771 ffth->tick_time = fftimehands->tick_time;
772 ffth->period_lerp = cest->period;
774 /* Do not lock but ignore next update from synchronization daemon. */
784 * Retrieve feed-forward counter and time of last kernel tick.
787 ffclock_last_tick(ffcounter *ffcount, struct bintime *bt, uint32_t flags)
789 struct fftimehands *ffth;
793 * No locking but check generation has not changed. Also need to make
794 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
799 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP)
800 *bt = ffth->tick_time_lerp;
802 *bt = ffth->tick_time;
803 *ffcount = ffth->tick_ffcount;
804 } while (gen == 0 || gen != ffth->gen);
808 * Absolute clock conversion. Low level function to convert ffcounter to
809 * bintime. The ffcounter is converted using the current ffclock period estimate
810 * or the "interpolated period" to ensure monotonicity.
811 * NOTE: this conversion may have been deferred, and the clock updated since the
812 * hardware counter has been read.
815 ffclock_convert_abs(ffcounter ffcount, struct bintime *bt, uint32_t flags)
817 struct fftimehands *ffth;
823 * No locking but check generation has not changed. Also need to make
824 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
829 if (ffcount > ffth->tick_ffcount)
830 ffdelta = ffcount - ffth->tick_ffcount;
832 ffdelta = ffth->tick_ffcount - ffcount;
834 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP) {
835 *bt = ffth->tick_time_lerp;
836 ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt2);
838 *bt = ffth->tick_time;
839 ffclock_convert_delta(ffdelta, ffth->cest.period, &bt2);
842 if (ffcount > ffth->tick_ffcount)
843 bintime_add(bt, &bt2);
845 bintime_sub(bt, &bt2);
846 } while (gen == 0 || gen != ffth->gen);
850 * Difference clock conversion.
851 * Low level function to Convert a time interval measured in RAW counter units
852 * into bintime. The difference clock allows measuring small intervals much more
853 * reliably than the absolute clock.
856 ffclock_convert_diff(ffcounter ffdelta, struct bintime *bt)
858 struct fftimehands *ffth;
861 /* No locking but check generation has not changed. */
865 ffclock_convert_delta(ffdelta, ffth->cest.period, bt);
866 } while (gen == 0 || gen != ffth->gen);
870 * Access to current ffcounter value.
873 ffclock_read_counter(ffcounter *ffcount)
875 struct timehands *th;
876 struct fftimehands *ffth;
877 unsigned int gen, delta;
880 * ffclock_windup() called from tc_windup(), safe to rely on
881 * th->th_generation only, for correct delta and ffcounter.
885 gen = th->th_generation;
887 delta = tc_delta(th);
888 *ffcount = ffth->tick_ffcount;
889 } while (gen == 0 || gen != th->th_generation);
895 binuptime(struct bintime *bt)
898 binuptime_fromclock(bt, sysclock_active);
902 nanouptime(struct timespec *tsp)
905 nanouptime_fromclock(tsp, sysclock_active);
909 microuptime(struct timeval *tvp)
912 microuptime_fromclock(tvp, sysclock_active);
916 bintime(struct bintime *bt)
919 bintime_fromclock(bt, sysclock_active);
923 nanotime(struct timespec *tsp)
926 nanotime_fromclock(tsp, sysclock_active);
930 microtime(struct timeval *tvp)
933 microtime_fromclock(tvp, sysclock_active);
937 getbinuptime(struct bintime *bt)
940 getbinuptime_fromclock(bt, sysclock_active);
944 getnanouptime(struct timespec *tsp)
947 getnanouptime_fromclock(tsp, sysclock_active);
951 getmicrouptime(struct timeval *tvp)
954 getmicrouptime_fromclock(tvp, sysclock_active);
958 getbintime(struct bintime *bt)
961 getbintime_fromclock(bt, sysclock_active);
965 getnanotime(struct timespec *tsp)
968 getnanotime_fromclock(tsp, sysclock_active);
972 getmicrotime(struct timeval *tvp)
975 getmicrouptime_fromclock(tvp, sysclock_active);
981 * This is a clone of getnanotime and used for walltimestamps.
982 * The dtrace_ prefix prevents fbt from creating probes for
983 * it so walltimestamp can be safely used in all fbt probes.
986 dtrace_getnanotime(struct timespec *tsp)
988 struct timehands *th;
993 gen = th->th_generation;
994 *tsp = th->th_nanotime;
995 } while (gen == 0 || gen != th->th_generation);
999 * System clock currently providing time to the system. Modifiable via sysctl
1000 * when the FFCLOCK option is defined.
1002 int sysclock_active = SYSCLOCK_FBCK;
1004 /* Internal NTP status and error estimates. */
1005 extern int time_status;
1006 extern long time_esterror;
1009 * Take a snapshot of sysclock data which can be used to compare system clocks
1010 * and generate timestamps after the fact.
1013 sysclock_getsnapshot(struct sysclock_snap *clock_snap, int fast)
1015 struct fbclock_info *fbi;
1016 struct timehands *th;
1018 unsigned int delta, gen;
1021 struct fftimehands *ffth;
1022 struct ffclock_info *ffi;
1023 struct ffclock_estimate cest;
1025 ffi = &clock_snap->ff_info;
1028 fbi = &clock_snap->fb_info;
1033 gen = th->th_generation;
1034 fbi->th_scale = th->th_scale;
1035 fbi->tick_time = th->th_offset;
1038 ffi->tick_time = ffth->tick_time_lerp;
1039 ffi->tick_time_lerp = ffth->tick_time_lerp;
1040 ffi->period = ffth->cest.period;
1041 ffi->period_lerp = ffth->period_lerp;
1042 clock_snap->ffcount = ffth->tick_ffcount;
1046 delta = tc_delta(th);
1047 } while (gen == 0 || gen != th->th_generation);
1049 clock_snap->delta = delta;
1050 clock_snap->sysclock_active = sysclock_active;
1052 /* Record feedback clock status and error. */
1053 clock_snap->fb_info.status = time_status;
1054 /* XXX: Very crude estimate of feedback clock error. */
1055 bt.sec = time_esterror / 1000000;
1056 bt.frac = ((time_esterror - bt.sec) * 1000000) *
1057 (uint64_t)18446744073709ULL;
1058 clock_snap->fb_info.error = bt;
1062 clock_snap->ffcount += delta;
1064 /* Record feed-forward clock leap second adjustment. */
1065 ffi->leapsec_adjustment = cest.leapsec_total;
1066 if (clock_snap->ffcount > cest.leapsec_next)
1067 ffi->leapsec_adjustment -= cest.leapsec;
1069 /* Record feed-forward clock status and error. */
1070 clock_snap->ff_info.status = cest.status;
1071 ffcount = clock_snap->ffcount - cest.update_ffcount;
1072 ffclock_convert_delta(ffcount, cest.period, &bt);
1073 /* 18446744073709 = int(2^64/1e12), err_bound_rate in [ps/s]. */
1074 bintime_mul(&bt, cest.errb_rate * (uint64_t)18446744073709ULL);
1075 /* 18446744073 = int(2^64 / 1e9), since err_abs in [ns]. */
1076 bintime_addx(&bt, cest.errb_abs * (uint64_t)18446744073ULL);
1077 clock_snap->ff_info.error = bt;
1082 * Convert a sysclock snapshot into a struct bintime based on the specified
1083 * clock source and flags.
1086 sysclock_snap2bintime(struct sysclock_snap *cs, struct bintime *bt,
1087 int whichclock, uint32_t flags)
1094 switch (whichclock) {
1096 *bt = cs->fb_info.tick_time;
1098 /* If snapshot was created with !fast, delta will be >0. */
1100 bintime_addx(bt, cs->fb_info.th_scale * cs->delta);
1102 if ((flags & FBCLOCK_UPTIME) == 0)
1103 bintime_add(bt, &boottimebin);
1107 if (flags & FFCLOCK_LERP) {
1108 *bt = cs->ff_info.tick_time_lerp;
1109 period = cs->ff_info.period_lerp;
1111 *bt = cs->ff_info.tick_time;
1112 period = cs->ff_info.period;
1115 /* If snapshot was created with !fast, delta will be >0. */
1116 if (cs->delta > 0) {
1117 ffclock_convert_delta(cs->delta, period, &bt2);
1118 bintime_add(bt, &bt2);
1121 /* Leap second adjustment. */
1122 if (flags & FFCLOCK_LEAPSEC)
1123 bt->sec -= cs->ff_info.leapsec_adjustment;
1125 /* Boot time adjustment, for uptime/monotonic clocks. */
1126 if (flags & FFCLOCK_UPTIME)
1127 bintime_sub(bt, &ffclock_boottime);
1139 * Initialize a new timecounter and possibly use it.
1142 tc_init(struct timecounter *tc)
1145 struct sysctl_oid *tc_root;
1147 u = tc->tc_frequency / tc->tc_counter_mask;
1148 /* XXX: We need some margin here, 10% is a guess */
1151 if (u > hz && tc->tc_quality >= 0) {
1152 tc->tc_quality = -2000;
1154 printf("Timecounter \"%s\" frequency %ju Hz",
1155 tc->tc_name, (uintmax_t)tc->tc_frequency);
1156 printf(" -- Insufficient hz, needs at least %u\n", u);
1158 } else if (tc->tc_quality >= 0 || bootverbose) {
1159 printf("Timecounter \"%s\" frequency %ju Hz quality %d\n",
1160 tc->tc_name, (uintmax_t)tc->tc_frequency,
1164 tc->tc_next = timecounters;
1167 * Set up sysctl tree for this counter.
1169 tc_root = SYSCTL_ADD_NODE(NULL,
1170 SYSCTL_STATIC_CHILDREN(_kern_timecounter_tc), OID_AUTO, tc->tc_name,
1171 CTLFLAG_RW, 0, "timecounter description");
1172 SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1173 "mask", CTLFLAG_RD, &(tc->tc_counter_mask), 0,
1174 "mask for implemented bits");
1175 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1176 "counter", CTLTYPE_UINT | CTLFLAG_RD, tc, sizeof(*tc),
1177 sysctl_kern_timecounter_get, "IU", "current timecounter value");
1178 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1179 "frequency", CTLTYPE_U64 | CTLFLAG_RD, tc, sizeof(*tc),
1180 sysctl_kern_timecounter_freq, "QU", "timecounter frequency");
1181 SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1182 "quality", CTLFLAG_RD, &(tc->tc_quality), 0,
1183 "goodness of time counter");
1185 * Never automatically use a timecounter with negative quality.
1186 * Even though we run on the dummy counter, switching here may be
1187 * worse since this timecounter may not be monotonous.
1189 if (tc->tc_quality < 0)
1191 if (tc->tc_quality < timecounter->tc_quality)
1193 if (tc->tc_quality == timecounter->tc_quality &&
1194 tc->tc_frequency < timecounter->tc_frequency)
1196 (void)tc->tc_get_timecount(tc);
1197 (void)tc->tc_get_timecount(tc);
1201 /* Report the frequency of the current timecounter. */
1203 tc_getfrequency(void)
1206 return (timehands->th_counter->tc_frequency);
1210 * Step our concept of UTC. This is done by modifying our estimate of
1215 tc_setclock(struct timespec *ts)
1217 struct timespec tbef, taft;
1218 struct bintime bt, bt2;
1220 cpu_tick_calibrate(1);
1222 timespec2bintime(ts, &bt);
1224 bintime_sub(&bt, &bt2);
1225 bintime_add(&bt2, &boottimebin);
1227 bintime2timeval(&bt, &boottime);
1229 /* XXX fiddle all the little crinkly bits around the fiords... */
1232 if (timestepwarnings) {
1234 "Time stepped from %jd.%09ld to %jd.%09ld (%jd.%09ld)\n",
1235 (intmax_t)tbef.tv_sec, tbef.tv_nsec,
1236 (intmax_t)taft.tv_sec, taft.tv_nsec,
1237 (intmax_t)ts->tv_sec, ts->tv_nsec);
1239 cpu_tick_calibrate(1);
1243 * Initialize the next struct timehands in the ring and make
1244 * it the active timehands. Along the way we might switch to a different
1245 * timecounter and/or do seconds processing in NTP. Slightly magic.
1251 struct timehands *th, *tho;
1253 u_int delta, ncount, ogen;
1258 * Make the next timehands a copy of the current one, but do not
1259 * overwrite the generation or next pointer. While we update
1260 * the contents, the generation must be zero.
1264 ogen = th->th_generation;
1265 th->th_generation = 0;
1266 bcopy(tho, th, offsetof(struct timehands, th_generation));
1269 * Capture a timecounter delta on the current timecounter and if
1270 * changing timecounters, a counter value from the new timecounter.
1271 * Update the offset fields accordingly.
1273 delta = tc_delta(th);
1274 if (th->th_counter != timecounter)
1275 ncount = timecounter->tc_get_timecount(timecounter);
1279 ffclock_windup(delta);
1281 th->th_offset_count += delta;
1282 th->th_offset_count &= th->th_counter->tc_counter_mask;
1283 while (delta > th->th_counter->tc_frequency) {
1284 /* Eat complete unadjusted seconds. */
1285 delta -= th->th_counter->tc_frequency;
1286 th->th_offset.sec++;
1288 if ((delta > th->th_counter->tc_frequency / 2) &&
1289 (th->th_scale * delta < ((uint64_t)1 << 63))) {
1290 /* The product th_scale * delta just barely overflows. */
1291 th->th_offset.sec++;
1293 bintime_addx(&th->th_offset, th->th_scale * delta);
1296 * Hardware latching timecounters may not generate interrupts on
1297 * PPS events, so instead we poll them. There is a finite risk that
1298 * the hardware might capture a count which is later than the one we
1299 * got above, and therefore possibly in the next NTP second which might
1300 * have a different rate than the current NTP second. It doesn't
1301 * matter in practice.
1303 if (tho->th_counter->tc_poll_pps)
1304 tho->th_counter->tc_poll_pps(tho->th_counter);
1307 * Deal with NTP second processing. The for loop normally
1308 * iterates at most once, but in extreme situations it might
1309 * keep NTP sane if timeouts are not run for several seconds.
1310 * At boot, the time step can be large when the TOD hardware
1311 * has been read, so on really large steps, we call
1312 * ntp_update_second only twice. We need to call it twice in
1313 * case we missed a leap second.
1316 bintime_add(&bt, &boottimebin);
1317 i = bt.sec - tho->th_microtime.tv_sec;
1320 for (; i > 0; i--) {
1322 ntp_update_second(&th->th_adjustment, &bt.sec);
1324 boottimebin.sec += bt.sec - t;
1326 /* Update the UTC timestamps used by the get*() functions. */
1327 /* XXX shouldn't do this here. Should force non-`get' versions. */
1328 bintime2timeval(&bt, &th->th_microtime);
1329 bintime2timespec(&bt, &th->th_nanotime);
1331 /* Now is a good time to change timecounters. */
1332 if (th->th_counter != timecounter) {
1334 if ((timecounter->tc_flags & TC_FLAGS_C3STOP) != 0)
1335 cpu_disable_deep_sleep++;
1336 if ((th->th_counter->tc_flags & TC_FLAGS_C3STOP) != 0)
1337 cpu_disable_deep_sleep--;
1339 th->th_counter = timecounter;
1340 th->th_offset_count = ncount;
1341 tc_min_ticktock_freq = max(1, timecounter->tc_frequency /
1342 (((uint64_t)timecounter->tc_counter_mask + 1) / 3));
1344 ffclock_change_tc(th);
1349 * Recalculate the scaling factor. We want the number of 1/2^64
1350 * fractions of a second per period of the hardware counter, taking
1351 * into account the th_adjustment factor which the NTP PLL/adjtime(2)
1352 * processing provides us with.
1354 * The th_adjustment is nanoseconds per second with 32 bit binary
1355 * fraction and we want 64 bit binary fraction of second:
1357 * x = a * 2^32 / 10^9 = a * 4.294967296
1359 * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
1360 * we can only multiply by about 850 without overflowing, that
1361 * leaves no suitably precise fractions for multiply before divide.
1363 * Divide before multiply with a fraction of 2199/512 results in a
1364 * systematic undercompensation of 10PPM of th_adjustment. On a
1365 * 5000PPM adjustment this is a 0.05PPM error. This is acceptable.
1367 * We happily sacrifice the lowest of the 64 bits of our result
1368 * to the goddess of code clarity.
1371 scale = (uint64_t)1 << 63;
1372 scale += (th->th_adjustment / 1024) * 2199;
1373 scale /= th->th_counter->tc_frequency;
1374 th->th_scale = scale * 2;
1377 * Now that the struct timehands is again consistent, set the new
1378 * generation number, making sure to not make it zero.
1382 th->th_generation = ogen;
1384 /* Go live with the new struct timehands. */
1386 switch (sysclock_active) {
1389 time_second = th->th_microtime.tv_sec;
1390 time_uptime = th->th_offset.sec;
1394 time_second = fftimehands->tick_time_lerp.sec;
1395 time_uptime = fftimehands->tick_time_lerp.sec - ffclock_boottime.sec;
1401 timekeep_push_vdso();
1404 /* Report or change the active timecounter hardware. */
1406 sysctl_kern_timecounter_hardware(SYSCTL_HANDLER_ARGS)
1409 struct timecounter *newtc, *tc;
1413 strlcpy(newname, tc->tc_name, sizeof(newname));
1415 error = sysctl_handle_string(oidp, &newname[0], sizeof(newname), req);
1416 if (error != 0 || req->newptr == NULL ||
1417 strcmp(newname, tc->tc_name) == 0)
1419 for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
1420 if (strcmp(newname, newtc->tc_name) != 0)
1423 /* Warm up new timecounter. */
1424 (void)newtc->tc_get_timecount(newtc);
1425 (void)newtc->tc_get_timecount(newtc);
1427 timecounter = newtc;
1428 timekeep_push_vdso();
1434 SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware, CTLTYPE_STRING | CTLFLAG_RW,
1435 0, 0, sysctl_kern_timecounter_hardware, "A",
1436 "Timecounter hardware selected");
1439 /* Report or change the active timecounter hardware. */
1441 sysctl_kern_timecounter_choice(SYSCTL_HANDLER_ARGS)
1444 struct timecounter *tc;
1449 for (tc = timecounters; error == 0 && tc != NULL; tc = tc->tc_next) {
1450 sprintf(buf, "%s%s(%d)",
1451 spc, tc->tc_name, tc->tc_quality);
1452 error = SYSCTL_OUT(req, buf, strlen(buf));
1458 SYSCTL_PROC(_kern_timecounter, OID_AUTO, choice, CTLTYPE_STRING | CTLFLAG_RD,
1459 0, 0, sysctl_kern_timecounter_choice, "A", "Timecounter hardware detected");
1462 * RFC 2783 PPS-API implementation.
1466 pps_fetch(struct pps_fetch_args *fapi, struct pps_state *pps)
1469 pps_seq_t aseq, cseq;
1472 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1476 * If no timeout is requested, immediately return whatever values were
1477 * most recently captured. If timeout seconds is -1, that's a request
1478 * to block without a timeout. WITNESS won't let us sleep forever
1479 * without a lock (we really don't need a lock), so just repeatedly
1480 * sleep a long time.
1482 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec) {
1483 if (fapi->timeout.tv_sec == -1)
1486 tv.tv_sec = fapi->timeout.tv_sec;
1487 tv.tv_usec = fapi->timeout.tv_nsec / 1000;
1490 aseq = pps->ppsinfo.assert_sequence;
1491 cseq = pps->ppsinfo.clear_sequence;
1492 while (aseq == pps->ppsinfo.assert_sequence &&
1493 cseq == pps->ppsinfo.clear_sequence) {
1494 err = tsleep(pps, PCATCH, "ppsfch", timo);
1495 if (err == EWOULDBLOCK && fapi->timeout.tv_sec == -1) {
1497 } else if (err != 0) {
1503 pps->ppsinfo.current_mode = pps->ppsparam.mode;
1504 fapi->pps_info_buf = pps->ppsinfo;
1510 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
1513 struct pps_fetch_args *fapi;
1515 struct pps_fetch_ffc_args *fapi_ffc;
1518 struct pps_kcbind_args *kapi;
1521 KASSERT(pps != NULL, ("NULL pps pointer in pps_ioctl"));
1523 case PPS_IOC_CREATE:
1525 case PPS_IOC_DESTROY:
1527 case PPS_IOC_SETPARAMS:
1528 app = (pps_params_t *)data;
1529 if (app->mode & ~pps->ppscap)
1532 /* Ensure only a single clock is selected for ffc timestamp. */
1533 if ((app->mode & PPS_TSCLK_MASK) == PPS_TSCLK_MASK)
1536 pps->ppsparam = *app;
1538 case PPS_IOC_GETPARAMS:
1539 app = (pps_params_t *)data;
1540 *app = pps->ppsparam;
1541 app->api_version = PPS_API_VERS_1;
1543 case PPS_IOC_GETCAP:
1544 *(int*)data = pps->ppscap;
1547 fapi = (struct pps_fetch_args *)data;
1548 return (pps_fetch(fapi, pps));
1550 case PPS_IOC_FETCH_FFCOUNTER:
1551 fapi_ffc = (struct pps_fetch_ffc_args *)data;
1552 if (fapi_ffc->tsformat && fapi_ffc->tsformat !=
1555 if (fapi_ffc->timeout.tv_sec || fapi_ffc->timeout.tv_nsec)
1556 return (EOPNOTSUPP);
1557 pps->ppsinfo_ffc.current_mode = pps->ppsparam.mode;
1558 fapi_ffc->pps_info_buf_ffc = pps->ppsinfo_ffc;
1559 /* Overwrite timestamps if feedback clock selected. */
1560 switch (pps->ppsparam.mode & PPS_TSCLK_MASK) {
1561 case PPS_TSCLK_FBCK:
1562 fapi_ffc->pps_info_buf_ffc.assert_timestamp =
1563 pps->ppsinfo.assert_timestamp;
1564 fapi_ffc->pps_info_buf_ffc.clear_timestamp =
1565 pps->ppsinfo.clear_timestamp;
1567 case PPS_TSCLK_FFWD:
1573 #endif /* FFCLOCK */
1574 case PPS_IOC_KCBIND:
1576 kapi = (struct pps_kcbind_args *)data;
1577 /* XXX Only root should be able to do this */
1578 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1580 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1582 if (kapi->edge & ~pps->ppscap)
1584 pps->kcmode = kapi->edge;
1587 return (EOPNOTSUPP);
1595 pps_init(struct pps_state *pps)
1597 pps->ppscap |= PPS_TSFMT_TSPEC | PPS_CANWAIT;
1598 if (pps->ppscap & PPS_CAPTUREASSERT)
1599 pps->ppscap |= PPS_OFFSETASSERT;
1600 if (pps->ppscap & PPS_CAPTURECLEAR)
1601 pps->ppscap |= PPS_OFFSETCLEAR;
1603 pps->ppscap |= PPS_TSCLK_MASK;
1608 pps_capture(struct pps_state *pps)
1610 struct timehands *th;
1612 KASSERT(pps != NULL, ("NULL pps pointer in pps_capture"));
1614 pps->capgen = th->th_generation;
1617 pps->capffth = fftimehands;
1619 pps->capcount = th->th_counter->tc_get_timecount(th->th_counter);
1620 if (pps->capgen != th->th_generation)
1625 pps_event(struct pps_state *pps, int event)
1628 struct timespec ts, *tsp, *osp;
1629 u_int tcount, *pcount;
1633 struct timespec *tsp_ffc;
1634 pps_seq_t *pseq_ffc;
1638 KASSERT(pps != NULL, ("NULL pps pointer in pps_event"));
1639 /* If the timecounter was wound up underneath us, bail out. */
1640 if (pps->capgen == 0 || pps->capgen != pps->capth->th_generation)
1643 /* Things would be easier with arrays. */
1644 if (event == PPS_CAPTUREASSERT) {
1645 tsp = &pps->ppsinfo.assert_timestamp;
1646 osp = &pps->ppsparam.assert_offset;
1647 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1648 fhard = pps->kcmode & PPS_CAPTUREASSERT;
1649 pcount = &pps->ppscount[0];
1650 pseq = &pps->ppsinfo.assert_sequence;
1652 ffcount = &pps->ppsinfo_ffc.assert_ffcount;
1653 tsp_ffc = &pps->ppsinfo_ffc.assert_timestamp;
1654 pseq_ffc = &pps->ppsinfo_ffc.assert_sequence;
1657 tsp = &pps->ppsinfo.clear_timestamp;
1658 osp = &pps->ppsparam.clear_offset;
1659 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1660 fhard = pps->kcmode & PPS_CAPTURECLEAR;
1661 pcount = &pps->ppscount[1];
1662 pseq = &pps->ppsinfo.clear_sequence;
1664 ffcount = &pps->ppsinfo_ffc.clear_ffcount;
1665 tsp_ffc = &pps->ppsinfo_ffc.clear_timestamp;
1666 pseq_ffc = &pps->ppsinfo_ffc.clear_sequence;
1671 * If the timecounter changed, we cannot compare the count values, so
1672 * we have to drop the rest of the PPS-stuff until the next event.
1674 if (pps->ppstc != pps->capth->th_counter) {
1675 pps->ppstc = pps->capth->th_counter;
1676 *pcount = pps->capcount;
1677 pps->ppscount[2] = pps->capcount;
1681 /* Convert the count to a timespec. */
1682 tcount = pps->capcount - pps->capth->th_offset_count;
1683 tcount &= pps->capth->th_counter->tc_counter_mask;
1684 bt = pps->capth->th_offset;
1685 bintime_addx(&bt, pps->capth->th_scale * tcount);
1686 bintime_add(&bt, &boottimebin);
1687 bintime2timespec(&bt, &ts);
1689 /* If the timecounter was wound up underneath us, bail out. */
1690 if (pps->capgen != pps->capth->th_generation)
1693 *pcount = pps->capcount;
1698 timespecadd(tsp, osp);
1699 if (tsp->tv_nsec < 0) {
1700 tsp->tv_nsec += 1000000000;
1706 *ffcount = pps->capffth->tick_ffcount + tcount;
1707 bt = pps->capffth->tick_time;
1708 ffclock_convert_delta(tcount, pps->capffth->cest.period, &bt);
1709 bintime_add(&bt, &pps->capffth->tick_time);
1710 bintime2timespec(&bt, &ts);
1720 * Feed the NTP PLL/FLL.
1721 * The FLL wants to know how many (hardware) nanoseconds
1722 * elapsed since the previous event.
1724 tcount = pps->capcount - pps->ppscount[2];
1725 pps->ppscount[2] = pps->capcount;
1726 tcount &= pps->capth->th_counter->tc_counter_mask;
1727 scale = (uint64_t)1 << 63;
1728 scale /= pps->capth->th_counter->tc_frequency;
1732 bintime_addx(&bt, scale * tcount);
1733 bintime2timespec(&bt, &ts);
1734 hardpps(tsp, ts.tv_nsec + 1000000000 * ts.tv_sec);
1738 /* Wakeup anyone sleeping in pps_fetch(). */
1743 * Timecounters need to be updated every so often to prevent the hardware
1744 * counter from overflowing. Updating also recalculates the cached values
1745 * used by the get*() family of functions, so their precision depends on
1746 * the update frequency.
1750 SYSCTL_INT(_kern_timecounter, OID_AUTO, tick, CTLFLAG_RD, &tc_tick, 0,
1751 "Approximate number of hardclock ticks in a millisecond");
1754 tc_ticktock(int cnt)
1759 if (count < tc_tick)
1765 static void __inline
1766 tc_adjprecision(void)
1770 if (tc_timepercentage > 0) {
1771 t = (99 + tc_timepercentage) / tc_timepercentage;
1772 tc_precexp = fls(t + (t >> 1)) - 1;
1773 FREQ2BT(hz / tc_tick, &bt_timethreshold);
1774 FREQ2BT(hz, &bt_tickthreshold);
1775 bintime_shift(&bt_timethreshold, tc_precexp);
1776 bintime_shift(&bt_tickthreshold, tc_precexp);
1779 bt_timethreshold.sec = INT_MAX;
1780 bt_timethreshold.frac = ~(uint64_t)0;
1781 bt_tickthreshold = bt_timethreshold;
1783 sbt_timethreshold = bttosbt(bt_timethreshold);
1784 sbt_tickthreshold = bttosbt(bt_tickthreshold);
1788 sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS)
1792 val = tc_timepercentage;
1793 error = sysctl_handle_int(oidp, &val, 0, req);
1794 if (error != 0 || req->newptr == NULL)
1796 tc_timepercentage = val;
1802 inittimecounter(void *dummy)
1808 * Set the initial timeout to
1809 * max(1, <approx. number of hardclock ticks in a millisecond>).
1810 * People should probably not use the sysctl to set the timeout
1811 * to smaller than its inital value, since that value is the
1812 * smallest reasonable one. If they want better timestamps they
1813 * should use the non-"get"* functions.
1816 tc_tick = (hz + 500) / 1000;
1820 FREQ2BT(hz, &tick_bt);
1821 tick_sbt = bttosbt(tick_bt);
1822 tick_rate = hz / tc_tick;
1823 FREQ2BT(tick_rate, &tc_tick_bt);
1824 tc_tick_sbt = bttosbt(tc_tick_bt);
1825 p = (tc_tick * 1000000) / hz;
1826 printf("Timecounters tick every %d.%03u msec\n", p / 1000, p % 1000);
1831 /* warm up new timecounter (again) and get rolling. */
1832 (void)timecounter->tc_get_timecount(timecounter);
1833 (void)timecounter->tc_get_timecount(timecounter);
1837 SYSINIT(timecounter, SI_SUB_CLOCKS, SI_ORDER_SECOND, inittimecounter, NULL);
1839 /* Cpu tick handling -------------------------------------------------*/
1841 static int cpu_tick_variable;
1842 static uint64_t cpu_tick_frequency;
1847 static uint64_t base;
1848 static unsigned last;
1850 struct timecounter *tc;
1852 tc = timehands->th_counter;
1853 u = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
1855 base += (uint64_t)tc->tc_counter_mask + 1;
1861 cpu_tick_calibration(void)
1863 static time_t last_calib;
1865 if (time_uptime != last_calib && !(time_uptime & 0xf)) {
1866 cpu_tick_calibrate(0);
1867 last_calib = time_uptime;
1872 * This function gets called every 16 seconds on only one designated
1873 * CPU in the system from hardclock() via cpu_tick_calibration()().
1875 * Whenever the real time clock is stepped we get called with reset=1
1876 * to make sure we handle suspend/resume and similar events correctly.
1880 cpu_tick_calibrate(int reset)
1882 static uint64_t c_last;
1883 uint64_t c_this, c_delta;
1884 static struct bintime t_last;
1885 struct bintime t_this, t_delta;
1889 /* The clock was stepped, abort & reset */
1894 /* we don't calibrate fixed rate cputicks */
1895 if (!cpu_tick_variable)
1898 getbinuptime(&t_this);
1899 c_this = cpu_ticks();
1900 if (t_last.sec != 0) {
1901 c_delta = c_this - c_last;
1903 bintime_sub(&t_delta, &t_last);
1906 * 2^(64-20) / 16[s] =
1908 * 17.592.186.044.416 / 16 =
1909 * 1.099.511.627.776 [Hz]
1911 divi = t_delta.sec << 20;
1912 divi |= t_delta.frac >> (64 - 20);
1915 if (c_delta > cpu_tick_frequency) {
1916 if (0 && bootverbose)
1917 printf("cpu_tick increased to %ju Hz\n",
1919 cpu_tick_frequency = c_delta;
1927 set_cputicker(cpu_tick_f *func, uint64_t freq, unsigned var)
1931 cpu_ticks = tc_cpu_ticks;
1933 cpu_tick_frequency = freq;
1934 cpu_tick_variable = var;
1943 if (cpu_ticks == tc_cpu_ticks)
1944 return (tc_getfrequency());
1945 return (cpu_tick_frequency);
1949 * We need to be slightly careful converting cputicks to microseconds.
1950 * There is plenty of margin in 64 bits of microseconds (half a million
1951 * years) and in 64 bits at 4 GHz (146 years), but if we do a multiply
1952 * before divide conversion (to retain precision) we find that the
1953 * margin shrinks to 1.5 hours (one millionth of 146y).
1954 * With a three prong approach we never lose significant bits, no
1955 * matter what the cputick rate and length of timeinterval is.
1959 cputick2usec(uint64_t tick)
1962 if (tick > 18446744073709551LL) /* floor(2^64 / 1000) */
1963 return (tick / (cpu_tickrate() / 1000000LL));
1964 else if (tick > 18446744073709LL) /* floor(2^64 / 1000000) */
1965 return ((tick * 1000LL) / (cpu_tickrate() / 1000LL));
1967 return ((tick * 1000000LL) / cpu_tickrate());
1970 cpu_tick_f *cpu_ticks = tc_cpu_ticks;
1972 static int vdso_th_enable = 1;
1974 sysctl_fast_gettime(SYSCTL_HANDLER_ARGS)
1976 int old_vdso_th_enable, error;
1978 old_vdso_th_enable = vdso_th_enable;
1979 error = sysctl_handle_int(oidp, &old_vdso_th_enable, 0, req);
1982 vdso_th_enable = old_vdso_th_enable;
1983 timekeep_push_vdso();
1986 SYSCTL_PROC(_kern_timecounter, OID_AUTO, fast_gettime,
1987 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1988 NULL, 0, sysctl_fast_gettime, "I", "Enable fast time of day");
1991 tc_fill_vdso_timehands(struct vdso_timehands *vdso_th)
1993 struct timehands *th;
1997 vdso_th->th_algo = VDSO_TH_ALGO_1;
1998 vdso_th->th_scale = th->th_scale;
1999 vdso_th->th_offset_count = th->th_offset_count;
2000 vdso_th->th_counter_mask = th->th_counter->tc_counter_mask;
2001 vdso_th->th_offset = th->th_offset;
2002 vdso_th->th_boottime = boottimebin;
2003 enabled = cpu_fill_vdso_timehands(vdso_th);
2004 if (!vdso_th_enable)
2009 #ifdef COMPAT_FREEBSD32
2011 tc_fill_vdso_timehands32(struct vdso_timehands32 *vdso_th32)
2013 struct timehands *th;
2017 vdso_th32->th_algo = VDSO_TH_ALGO_1;
2018 *(uint64_t *)&vdso_th32->th_scale[0] = th->th_scale;
2019 vdso_th32->th_offset_count = th->th_offset_count;
2020 vdso_th32->th_counter_mask = th->th_counter->tc_counter_mask;
2021 vdso_th32->th_offset.sec = th->th_offset.sec;
2022 *(uint64_t *)&vdso_th32->th_offset.frac[0] = th->th_offset.frac;
2023 vdso_th32->th_boottime.sec = boottimebin.sec;
2024 *(uint64_t *)&vdso_th32->th_boottime.frac[0] = boottimebin.frac;
2025 enabled = cpu_fill_vdso_timehands32(vdso_th32);
2026 if (!vdso_th_enable)