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 static int sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS);
132 SYSCTL_PROC(_kern_timecounter, OID_AUTO, alloweddeviation,
133 CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, 0, 0,
134 sysctl_kern_timecounter_adjprecision, "I",
135 "Allowed time interval deviation in percents");
137 static void tc_windup(void);
138 static void cpu_tick_calibrate(int);
140 void dtrace_getnanotime(struct timespec *tsp);
143 sysctl_kern_boottime(SYSCTL_HANDLER_ARGS)
149 if (req->flags & SCTL_MASK32) {
150 tv[0] = boottime.tv_sec;
151 tv[1] = boottime.tv_usec;
152 return SYSCTL_OUT(req, tv, sizeof(tv));
156 return SYSCTL_OUT(req, &boottime, sizeof(boottime));
160 sysctl_kern_timecounter_get(SYSCTL_HANDLER_ARGS)
163 struct timecounter *tc = arg1;
165 ncount = tc->tc_get_timecount(tc);
166 return sysctl_handle_int(oidp, &ncount, 0, req);
170 sysctl_kern_timecounter_freq(SYSCTL_HANDLER_ARGS)
173 struct timecounter *tc = arg1;
175 freq = tc->tc_frequency;
176 return sysctl_handle_64(oidp, &freq, 0, req);
180 * Return the difference between the timehands' counter value now and what
181 * was when we copied it to the timehands' offset_count.
183 static __inline u_int
184 tc_delta(struct timehands *th)
186 struct timecounter *tc;
189 return ((tc->tc_get_timecount(tc) - th->th_offset_count) &
190 tc->tc_counter_mask);
194 * Functions for reading the time. We have to loop until we are sure that
195 * the timehands that we operated on was not updated under our feet. See
196 * the comment in <sys/time.h> for a description of these 12 functions.
201 fbclock_binuptime(struct bintime *bt)
203 struct timehands *th;
208 gen = th->th_generation;
210 bintime_addx(bt, th->th_scale * tc_delta(th));
211 } while (gen == 0 || gen != th->th_generation);
215 fbclock_nanouptime(struct timespec *tsp)
219 fbclock_binuptime(&bt);
220 bintime2timespec(&bt, tsp);
224 fbclock_microuptime(struct timeval *tvp)
228 fbclock_binuptime(&bt);
229 bintime2timeval(&bt, tvp);
233 fbclock_bintime(struct bintime *bt)
236 fbclock_binuptime(bt);
237 bintime_add(bt, &boottimebin);
241 fbclock_nanotime(struct timespec *tsp)
245 fbclock_bintime(&bt);
246 bintime2timespec(&bt, tsp);
250 fbclock_microtime(struct timeval *tvp)
254 fbclock_bintime(&bt);
255 bintime2timeval(&bt, tvp);
259 fbclock_getbinuptime(struct bintime *bt)
261 struct timehands *th;
266 gen = th->th_generation;
268 } while (gen == 0 || gen != th->th_generation);
272 fbclock_getnanouptime(struct timespec *tsp)
274 struct timehands *th;
279 gen = th->th_generation;
280 bintime2timespec(&th->th_offset, tsp);
281 } while (gen == 0 || gen != th->th_generation);
285 fbclock_getmicrouptime(struct timeval *tvp)
287 struct timehands *th;
292 gen = th->th_generation;
293 bintime2timeval(&th->th_offset, tvp);
294 } while (gen == 0 || gen != th->th_generation);
298 fbclock_getbintime(struct bintime *bt)
300 struct timehands *th;
305 gen = th->th_generation;
307 } while (gen == 0 || gen != th->th_generation);
308 bintime_add(bt, &boottimebin);
312 fbclock_getnanotime(struct timespec *tsp)
314 struct timehands *th;
319 gen = th->th_generation;
320 *tsp = th->th_nanotime;
321 } while (gen == 0 || gen != th->th_generation);
325 fbclock_getmicrotime(struct timeval *tvp)
327 struct timehands *th;
332 gen = th->th_generation;
333 *tvp = th->th_microtime;
334 } while (gen == 0 || gen != th->th_generation);
338 binuptime(struct bintime *bt)
340 struct timehands *th;
345 gen = th->th_generation;
347 bintime_addx(bt, th->th_scale * tc_delta(th));
348 } while (gen == 0 || gen != th->th_generation);
352 nanouptime(struct timespec *tsp)
357 bintime2timespec(&bt, tsp);
361 microuptime(struct timeval *tvp)
366 bintime2timeval(&bt, tvp);
370 bintime(struct bintime *bt)
374 bintime_add(bt, &boottimebin);
378 nanotime(struct timespec *tsp)
383 bintime2timespec(&bt, tsp);
387 microtime(struct timeval *tvp)
392 bintime2timeval(&bt, tvp);
396 getbinuptime(struct bintime *bt)
398 struct timehands *th;
403 gen = th->th_generation;
405 } while (gen == 0 || gen != th->th_generation);
409 getnanouptime(struct timespec *tsp)
411 struct timehands *th;
416 gen = th->th_generation;
417 bintime2timespec(&th->th_offset, tsp);
418 } while (gen == 0 || gen != th->th_generation);
422 getmicrouptime(struct timeval *tvp)
424 struct timehands *th;
429 gen = th->th_generation;
430 bintime2timeval(&th->th_offset, tvp);
431 } while (gen == 0 || gen != th->th_generation);
435 getbintime(struct bintime *bt)
437 struct timehands *th;
442 gen = th->th_generation;
444 } while (gen == 0 || gen != th->th_generation);
445 bintime_add(bt, &boottimebin);
449 getnanotime(struct timespec *tsp)
451 struct timehands *th;
456 gen = th->th_generation;
457 *tsp = th->th_nanotime;
458 } while (gen == 0 || gen != th->th_generation);
462 getmicrotime(struct timeval *tvp)
464 struct timehands *th;
469 gen = th->th_generation;
470 *tvp = th->th_microtime;
471 } while (gen == 0 || gen != th->th_generation);
477 * Support for feed-forward synchronization algorithms. This is heavily inspired
478 * by the timehands mechanism but kept independent from it. *_windup() functions
479 * have some connection to avoid accessing the timecounter hardware more than
483 /* Feed-forward clock estimates kept updated by the synchronization daemon. */
484 struct ffclock_estimate ffclock_estimate;
485 struct bintime ffclock_boottime; /* Feed-forward boot time estimate. */
486 uint32_t ffclock_status; /* Feed-forward clock status. */
487 int8_t ffclock_updated; /* New estimates are available. */
488 struct mtx ffclock_mtx; /* Mutex on ffclock_estimate. */
491 struct ffclock_estimate cest;
492 struct bintime tick_time;
493 struct bintime tick_time_lerp;
494 ffcounter tick_ffcount;
495 uint64_t period_lerp;
496 volatile uint8_t gen;
497 struct fftimehands *next;
500 #define NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))
502 static struct fftimehands ffth[10];
503 static struct fftimehands *volatile fftimehands = ffth;
508 struct fftimehands *cur;
509 struct fftimehands *last;
511 memset(ffth, 0, sizeof(ffth));
513 last = ffth + NUM_ELEMENTS(ffth) - 1;
514 for (cur = ffth; cur < last; cur++)
519 ffclock_status = FFCLOCK_STA_UNSYNC;
520 mtx_init(&ffclock_mtx, "ffclock lock", NULL, MTX_DEF);
524 * Reset the feed-forward clock estimates. Called from inittodr() to get things
525 * kick started and uses the timecounter nominal frequency as a first period
526 * estimate. Note: this function may be called several time just after boot.
527 * Note: this is the only function that sets the value of boot time for the
528 * monotonic (i.e. uptime) version of the feed-forward clock.
531 ffclock_reset_clock(struct timespec *ts)
533 struct timecounter *tc;
534 struct ffclock_estimate cest;
536 tc = timehands->th_counter;
537 memset(&cest, 0, sizeof(struct ffclock_estimate));
539 timespec2bintime(ts, &ffclock_boottime);
540 timespec2bintime(ts, &(cest.update_time));
541 ffclock_read_counter(&cest.update_ffcount);
542 cest.leapsec_next = 0;
543 cest.period = ((1ULL << 63) / tc->tc_frequency) << 1;
546 cest.status = FFCLOCK_STA_UNSYNC;
547 cest.leapsec_total = 0;
550 mtx_lock(&ffclock_mtx);
551 bcopy(&cest, &ffclock_estimate, sizeof(struct ffclock_estimate));
552 ffclock_updated = INT8_MAX;
553 mtx_unlock(&ffclock_mtx);
555 printf("ffclock reset: %s (%llu Hz), time = %ld.%09lu\n", tc->tc_name,
556 (unsigned long long)tc->tc_frequency, (long)ts->tv_sec,
557 (unsigned long)ts->tv_nsec);
561 * Sub-routine to convert a time interval measured in RAW counter units to time
562 * in seconds stored in bintime format.
563 * NOTE: bintime_mul requires u_int, but the value of the ffcounter may be
564 * larger than the max value of u_int (on 32 bit architecture). Loop to consume
568 ffclock_convert_delta(ffcounter ffdelta, uint64_t period, struct bintime *bt)
571 ffcounter delta, delta_max;
573 delta_max = (1ULL << (8 * sizeof(unsigned int))) - 1;
576 if (ffdelta > delta_max)
582 bintime_mul(&bt2, (unsigned int)delta);
583 bintime_add(bt, &bt2);
585 } while (ffdelta > 0);
589 * Update the fftimehands.
590 * Push the tick ffcount and time(s) forward based on current clock estimate.
591 * The conversion from ffcounter to bintime relies on the difference clock
592 * principle, whose accuracy relies on computing small time intervals. If a new
593 * clock estimate has been passed by the synchronisation daemon, make it
594 * current, and compute the linear interpolation for monotonic time if needed.
597 ffclock_windup(unsigned int delta)
599 struct ffclock_estimate *cest;
600 struct fftimehands *ffth;
601 struct bintime bt, gap_lerp;
604 unsigned int polling;
605 uint8_t forward_jump, ogen;
608 * Pick the next timehand, copy current ffclock estimates and move tick
609 * times and counter forward.
612 ffth = fftimehands->next;
616 bcopy(&fftimehands->cest, cest, sizeof(struct ffclock_estimate));
617 ffdelta = (ffcounter)delta;
618 ffth->period_lerp = fftimehands->period_lerp;
620 ffth->tick_time = fftimehands->tick_time;
621 ffclock_convert_delta(ffdelta, cest->period, &bt);
622 bintime_add(&ffth->tick_time, &bt);
624 ffth->tick_time_lerp = fftimehands->tick_time_lerp;
625 ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt);
626 bintime_add(&ffth->tick_time_lerp, &bt);
628 ffth->tick_ffcount = fftimehands->tick_ffcount + ffdelta;
631 * Assess the status of the clock, if the last update is too old, it is
632 * likely the synchronisation daemon is dead and the clock is free
635 if (ffclock_updated == 0) {
636 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
637 ffclock_convert_delta(ffdelta, cest->period, &bt);
638 if (bt.sec > 2 * FFCLOCK_SKM_SCALE)
639 ffclock_status |= FFCLOCK_STA_UNSYNC;
643 * If available, grab updated clock estimates and make them current.
644 * Recompute time at this tick using the updated estimates. The clock
645 * estimates passed the feed-forward synchronisation daemon may result
646 * in time conversion that is not monotonically increasing (just after
647 * the update). time_lerp is a particular linear interpolation over the
648 * synchronisation algo polling period that ensures monotonicity for the
649 * clock ids requesting it.
651 if (ffclock_updated > 0) {
652 bcopy(&ffclock_estimate, cest, sizeof(struct ffclock_estimate));
653 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
654 ffth->tick_time = cest->update_time;
655 ffclock_convert_delta(ffdelta, cest->period, &bt);
656 bintime_add(&ffth->tick_time, &bt);
658 /* ffclock_reset sets ffclock_updated to INT8_MAX */
659 if (ffclock_updated == INT8_MAX)
660 ffth->tick_time_lerp = ffth->tick_time;
662 if (bintime_cmp(&ffth->tick_time, &ffth->tick_time_lerp, >))
667 bintime_clear(&gap_lerp);
669 gap_lerp = ffth->tick_time;
670 bintime_sub(&gap_lerp, &ffth->tick_time_lerp);
672 gap_lerp = ffth->tick_time_lerp;
673 bintime_sub(&gap_lerp, &ffth->tick_time);
677 * The reset from the RTC clock may be far from accurate, and
678 * reducing the gap between real time and interpolated time
679 * could take a very long time if the interpolated clock insists
680 * on strict monotonicity. The clock is reset under very strict
681 * conditions (kernel time is known to be wrong and
682 * synchronization daemon has been restarted recently.
683 * ffclock_boottime absorbs the jump to ensure boot time is
684 * correct and uptime functions stay consistent.
686 if (((ffclock_status & FFCLOCK_STA_UNSYNC) == FFCLOCK_STA_UNSYNC) &&
687 ((cest->status & FFCLOCK_STA_UNSYNC) == 0) &&
688 ((cest->status & FFCLOCK_STA_WARMUP) == FFCLOCK_STA_WARMUP)) {
690 bintime_add(&ffclock_boottime, &gap_lerp);
692 bintime_sub(&ffclock_boottime, &gap_lerp);
693 ffth->tick_time_lerp = ffth->tick_time;
694 bintime_clear(&gap_lerp);
697 ffclock_status = cest->status;
698 ffth->period_lerp = cest->period;
701 * Compute corrected period used for the linear interpolation of
702 * time. The rate of linear interpolation is capped to 5000PPM
705 if (bintime_isset(&gap_lerp)) {
706 ffdelta = cest->update_ffcount;
707 ffdelta -= fftimehands->cest.update_ffcount;
708 ffclock_convert_delta(ffdelta, cest->period, &bt);
711 bt.frac = 5000000 * (uint64_t)18446744073LL;
712 bintime_mul(&bt, polling);
713 if (bintime_cmp(&gap_lerp, &bt, >))
716 /* Approximate 1 sec by 1-(1/2^64) to ease arithmetic */
718 if (gap_lerp.sec > 0) {
720 frac /= ffdelta / gap_lerp.sec;
722 frac += gap_lerp.frac / ffdelta;
725 ffth->period_lerp += frac;
727 ffth->period_lerp -= frac;
739 * Adjust the fftimehands when the timecounter is changed. Stating the obvious,
740 * the old and new hardware counter cannot be read simultaneously. tc_windup()
741 * does read the two counters 'back to back', but a few cycles are effectively
742 * lost, and not accumulated in tick_ffcount. This is a fairly radical
743 * operation for a feed-forward synchronization daemon, and it is its job to not
744 * pushing irrelevant data to the kernel. Because there is no locking here,
745 * simply force to ignore pending or next update to give daemon a chance to
746 * realize the counter has changed.
749 ffclock_change_tc(struct timehands *th)
751 struct fftimehands *ffth;
752 struct ffclock_estimate *cest;
753 struct timecounter *tc;
757 ffth = fftimehands->next;
762 bcopy(&(fftimehands->cest), cest, sizeof(struct ffclock_estimate));
763 cest->period = ((1ULL << 63) / tc->tc_frequency ) << 1;
766 cest->status |= FFCLOCK_STA_UNSYNC;
768 ffth->tick_ffcount = fftimehands->tick_ffcount;
769 ffth->tick_time_lerp = fftimehands->tick_time_lerp;
770 ffth->tick_time = fftimehands->tick_time;
771 ffth->period_lerp = cest->period;
773 /* Do not lock but ignore next update from synchronization daemon. */
783 * Retrieve feed-forward counter and time of last kernel tick.
786 ffclock_last_tick(ffcounter *ffcount, struct bintime *bt, uint32_t flags)
788 struct fftimehands *ffth;
792 * No locking but check generation has not changed. Also need to make
793 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
798 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP)
799 *bt = ffth->tick_time_lerp;
801 *bt = ffth->tick_time;
802 *ffcount = ffth->tick_ffcount;
803 } while (gen == 0 || gen != ffth->gen);
807 * Absolute clock conversion. Low level function to convert ffcounter to
808 * bintime. The ffcounter is converted using the current ffclock period estimate
809 * or the "interpolated period" to ensure monotonicity.
810 * NOTE: this conversion may have been deferred, and the clock updated since the
811 * hardware counter has been read.
814 ffclock_convert_abs(ffcounter ffcount, struct bintime *bt, uint32_t flags)
816 struct fftimehands *ffth;
822 * No locking but check generation has not changed. Also need to make
823 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
828 if (ffcount > ffth->tick_ffcount)
829 ffdelta = ffcount - ffth->tick_ffcount;
831 ffdelta = ffth->tick_ffcount - ffcount;
833 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP) {
834 *bt = ffth->tick_time_lerp;
835 ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt2);
837 *bt = ffth->tick_time;
838 ffclock_convert_delta(ffdelta, ffth->cest.period, &bt2);
841 if (ffcount > ffth->tick_ffcount)
842 bintime_add(bt, &bt2);
844 bintime_sub(bt, &bt2);
845 } while (gen == 0 || gen != ffth->gen);
849 * Difference clock conversion.
850 * Low level function to Convert a time interval measured in RAW counter units
851 * into bintime. The difference clock allows measuring small intervals much more
852 * reliably than the absolute clock.
855 ffclock_convert_diff(ffcounter ffdelta, struct bintime *bt)
857 struct fftimehands *ffth;
860 /* No locking but check generation has not changed. */
864 ffclock_convert_delta(ffdelta, ffth->cest.period, bt);
865 } while (gen == 0 || gen != ffth->gen);
869 * Access to current ffcounter value.
872 ffclock_read_counter(ffcounter *ffcount)
874 struct timehands *th;
875 struct fftimehands *ffth;
876 unsigned int gen, delta;
879 * ffclock_windup() called from tc_windup(), safe to rely on
880 * th->th_generation only, for correct delta and ffcounter.
884 gen = th->th_generation;
886 delta = tc_delta(th);
887 *ffcount = ffth->tick_ffcount;
888 } while (gen == 0 || gen != th->th_generation);
894 binuptime(struct bintime *bt)
897 binuptime_fromclock(bt, sysclock_active);
901 nanouptime(struct timespec *tsp)
904 nanouptime_fromclock(tsp, sysclock_active);
908 microuptime(struct timeval *tvp)
911 microuptime_fromclock(tvp, sysclock_active);
915 bintime(struct bintime *bt)
918 bintime_fromclock(bt, sysclock_active);
922 nanotime(struct timespec *tsp)
925 nanotime_fromclock(tsp, sysclock_active);
929 microtime(struct timeval *tvp)
932 microtime_fromclock(tvp, sysclock_active);
936 getbinuptime(struct bintime *bt)
939 getbinuptime_fromclock(bt, sysclock_active);
943 getnanouptime(struct timespec *tsp)
946 getnanouptime_fromclock(tsp, sysclock_active);
950 getmicrouptime(struct timeval *tvp)
953 getmicrouptime_fromclock(tvp, sysclock_active);
957 getbintime(struct bintime *bt)
960 getbintime_fromclock(bt, sysclock_active);
964 getnanotime(struct timespec *tsp)
967 getnanotime_fromclock(tsp, sysclock_active);
971 getmicrotime(struct timeval *tvp)
974 getmicrouptime_fromclock(tvp, sysclock_active);
980 * This is a clone of getnanotime and used for walltimestamps.
981 * The dtrace_ prefix prevents fbt from creating probes for
982 * it so walltimestamp can be safely used in all fbt probes.
985 dtrace_getnanotime(struct timespec *tsp)
987 struct timehands *th;
992 gen = th->th_generation;
993 *tsp = th->th_nanotime;
994 } while (gen == 0 || gen != th->th_generation);
998 * System clock currently providing time to the system. Modifiable via sysctl
999 * when the FFCLOCK option is defined.
1001 int sysclock_active = SYSCLOCK_FBCK;
1003 /* Internal NTP status and error estimates. */
1004 extern int time_status;
1005 extern long time_esterror;
1008 * Take a snapshot of sysclock data which can be used to compare system clocks
1009 * and generate timestamps after the fact.
1012 sysclock_getsnapshot(struct sysclock_snap *clock_snap, int fast)
1014 struct fbclock_info *fbi;
1015 struct timehands *th;
1017 unsigned int delta, gen;
1020 struct fftimehands *ffth;
1021 struct ffclock_info *ffi;
1022 struct ffclock_estimate cest;
1024 ffi = &clock_snap->ff_info;
1027 fbi = &clock_snap->fb_info;
1032 gen = th->th_generation;
1033 fbi->th_scale = th->th_scale;
1034 fbi->tick_time = th->th_offset;
1037 ffi->tick_time = ffth->tick_time_lerp;
1038 ffi->tick_time_lerp = ffth->tick_time_lerp;
1039 ffi->period = ffth->cest.period;
1040 ffi->period_lerp = ffth->period_lerp;
1041 clock_snap->ffcount = ffth->tick_ffcount;
1045 delta = tc_delta(th);
1046 } while (gen == 0 || gen != th->th_generation);
1048 clock_snap->delta = delta;
1049 clock_snap->sysclock_active = sysclock_active;
1051 /* Record feedback clock status and error. */
1052 clock_snap->fb_info.status = time_status;
1053 /* XXX: Very crude estimate of feedback clock error. */
1054 bt.sec = time_esterror / 1000000;
1055 bt.frac = ((time_esterror - bt.sec) * 1000000) *
1056 (uint64_t)18446744073709ULL;
1057 clock_snap->fb_info.error = bt;
1061 clock_snap->ffcount += delta;
1063 /* Record feed-forward clock leap second adjustment. */
1064 ffi->leapsec_adjustment = cest.leapsec_total;
1065 if (clock_snap->ffcount > cest.leapsec_next)
1066 ffi->leapsec_adjustment -= cest.leapsec;
1068 /* Record feed-forward clock status and error. */
1069 clock_snap->ff_info.status = cest.status;
1070 ffcount = clock_snap->ffcount - cest.update_ffcount;
1071 ffclock_convert_delta(ffcount, cest.period, &bt);
1072 /* 18446744073709 = int(2^64/1e12), err_bound_rate in [ps/s]. */
1073 bintime_mul(&bt, cest.errb_rate * (uint64_t)18446744073709ULL);
1074 /* 18446744073 = int(2^64 / 1e9), since err_abs in [ns]. */
1075 bintime_addx(&bt, cest.errb_abs * (uint64_t)18446744073ULL);
1076 clock_snap->ff_info.error = bt;
1081 * Convert a sysclock snapshot into a struct bintime based on the specified
1082 * clock source and flags.
1085 sysclock_snap2bintime(struct sysclock_snap *cs, struct bintime *bt,
1086 int whichclock, uint32_t flags)
1093 switch (whichclock) {
1095 *bt = cs->fb_info.tick_time;
1097 /* If snapshot was created with !fast, delta will be >0. */
1099 bintime_addx(bt, cs->fb_info.th_scale * cs->delta);
1101 if ((flags & FBCLOCK_UPTIME) == 0)
1102 bintime_add(bt, &boottimebin);
1106 if (flags & FFCLOCK_LERP) {
1107 *bt = cs->ff_info.tick_time_lerp;
1108 period = cs->ff_info.period_lerp;
1110 *bt = cs->ff_info.tick_time;
1111 period = cs->ff_info.period;
1114 /* If snapshot was created with !fast, delta will be >0. */
1115 if (cs->delta > 0) {
1116 ffclock_convert_delta(cs->delta, period, &bt2);
1117 bintime_add(bt, &bt2);
1120 /* Leap second adjustment. */
1121 if (flags & FFCLOCK_LEAPSEC)
1122 bt->sec -= cs->ff_info.leapsec_adjustment;
1124 /* Boot time adjustment, for uptime/monotonic clocks. */
1125 if (flags & FFCLOCK_UPTIME)
1126 bintime_sub(bt, &ffclock_boottime);
1138 * Initialize a new timecounter and possibly use it.
1141 tc_init(struct timecounter *tc)
1144 struct sysctl_oid *tc_root;
1146 u = tc->tc_frequency / tc->tc_counter_mask;
1147 /* XXX: We need some margin here, 10% is a guess */
1150 if (u > hz && tc->tc_quality >= 0) {
1151 tc->tc_quality = -2000;
1153 printf("Timecounter \"%s\" frequency %ju Hz",
1154 tc->tc_name, (uintmax_t)tc->tc_frequency);
1155 printf(" -- Insufficient hz, needs at least %u\n", u);
1157 } else if (tc->tc_quality >= 0 || bootverbose) {
1158 printf("Timecounter \"%s\" frequency %ju Hz quality %d\n",
1159 tc->tc_name, (uintmax_t)tc->tc_frequency,
1163 tc->tc_next = timecounters;
1166 * Set up sysctl tree for this counter.
1168 tc_root = SYSCTL_ADD_NODE(NULL,
1169 SYSCTL_STATIC_CHILDREN(_kern_timecounter_tc), OID_AUTO, tc->tc_name,
1170 CTLFLAG_RW, 0, "timecounter description");
1171 SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1172 "mask", CTLFLAG_RD, &(tc->tc_counter_mask), 0,
1173 "mask for implemented bits");
1174 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1175 "counter", CTLTYPE_UINT | CTLFLAG_RD, tc, sizeof(*tc),
1176 sysctl_kern_timecounter_get, "IU", "current timecounter value");
1177 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1178 "frequency", CTLTYPE_U64 | CTLFLAG_RD, tc, sizeof(*tc),
1179 sysctl_kern_timecounter_freq, "QU", "timecounter frequency");
1180 SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1181 "quality", CTLFLAG_RD, &(tc->tc_quality), 0,
1182 "goodness of time counter");
1184 * Never automatically use a timecounter with negative quality.
1185 * Even though we run on the dummy counter, switching here may be
1186 * worse since this timecounter may not be monotonous.
1188 if (tc->tc_quality < 0)
1190 if (tc->tc_quality < timecounter->tc_quality)
1192 if (tc->tc_quality == timecounter->tc_quality &&
1193 tc->tc_frequency < timecounter->tc_frequency)
1195 (void)tc->tc_get_timecount(tc);
1196 (void)tc->tc_get_timecount(tc);
1200 /* Report the frequency of the current timecounter. */
1202 tc_getfrequency(void)
1205 return (timehands->th_counter->tc_frequency);
1209 * Step our concept of UTC. This is done by modifying our estimate of
1214 tc_setclock(struct timespec *ts)
1216 struct timespec tbef, taft;
1217 struct bintime bt, bt2;
1219 cpu_tick_calibrate(1);
1221 timespec2bintime(ts, &bt);
1223 bintime_sub(&bt, &bt2);
1224 bintime_add(&bt2, &boottimebin);
1226 bintime2timeval(&bt, &boottime);
1228 /* XXX fiddle all the little crinkly bits around the fiords... */
1231 if (timestepwarnings) {
1233 "Time stepped from %jd.%09ld to %jd.%09ld (%jd.%09ld)\n",
1234 (intmax_t)tbef.tv_sec, tbef.tv_nsec,
1235 (intmax_t)taft.tv_sec, taft.tv_nsec,
1236 (intmax_t)ts->tv_sec, ts->tv_nsec);
1238 cpu_tick_calibrate(1);
1242 * Initialize the next struct timehands in the ring and make
1243 * it the active timehands. Along the way we might switch to a different
1244 * timecounter and/or do seconds processing in NTP. Slightly magic.
1250 struct timehands *th, *tho;
1252 u_int delta, ncount, ogen;
1257 * Make the next timehands a copy of the current one, but do not
1258 * overwrite the generation or next pointer. While we update
1259 * the contents, the generation must be zero.
1263 ogen = th->th_generation;
1264 th->th_generation = 0;
1265 bcopy(tho, th, offsetof(struct timehands, th_generation));
1268 * Capture a timecounter delta on the current timecounter and if
1269 * changing timecounters, a counter value from the new timecounter.
1270 * Update the offset fields accordingly.
1272 delta = tc_delta(th);
1273 if (th->th_counter != timecounter)
1274 ncount = timecounter->tc_get_timecount(timecounter);
1278 ffclock_windup(delta);
1280 th->th_offset_count += delta;
1281 th->th_offset_count &= th->th_counter->tc_counter_mask;
1282 while (delta > th->th_counter->tc_frequency) {
1283 /* Eat complete unadjusted seconds. */
1284 delta -= th->th_counter->tc_frequency;
1285 th->th_offset.sec++;
1287 if ((delta > th->th_counter->tc_frequency / 2) &&
1288 (th->th_scale * delta < ((uint64_t)1 << 63))) {
1289 /* The product th_scale * delta just barely overflows. */
1290 th->th_offset.sec++;
1292 bintime_addx(&th->th_offset, th->th_scale * delta);
1295 * Hardware latching timecounters may not generate interrupts on
1296 * PPS events, so instead we poll them. There is a finite risk that
1297 * the hardware might capture a count which is later than the one we
1298 * got above, and therefore possibly in the next NTP second which might
1299 * have a different rate than the current NTP second. It doesn't
1300 * matter in practice.
1302 if (tho->th_counter->tc_poll_pps)
1303 tho->th_counter->tc_poll_pps(tho->th_counter);
1306 * Deal with NTP second processing. The for loop normally
1307 * iterates at most once, but in extreme situations it might
1308 * keep NTP sane if timeouts are not run for several seconds.
1309 * At boot, the time step can be large when the TOD hardware
1310 * has been read, so on really large steps, we call
1311 * ntp_update_second only twice. We need to call it twice in
1312 * case we missed a leap second.
1315 bintime_add(&bt, &boottimebin);
1316 i = bt.sec - tho->th_microtime.tv_sec;
1319 for (; i > 0; i--) {
1321 ntp_update_second(&th->th_adjustment, &bt.sec);
1323 boottimebin.sec += bt.sec - t;
1325 /* Update the UTC timestamps used by the get*() functions. */
1326 /* XXX shouldn't do this here. Should force non-`get' versions. */
1327 bintime2timeval(&bt, &th->th_microtime);
1328 bintime2timespec(&bt, &th->th_nanotime);
1330 /* Now is a good time to change timecounters. */
1331 if (th->th_counter != timecounter) {
1333 if ((timecounter->tc_flags & TC_FLAGS_C2STOP) != 0)
1334 cpu_disable_c2_sleep++;
1335 if ((th->th_counter->tc_flags & TC_FLAGS_C2STOP) != 0)
1336 cpu_disable_c2_sleep--;
1338 th->th_counter = timecounter;
1339 th->th_offset_count = ncount;
1340 tc_min_ticktock_freq = max(1, timecounter->tc_frequency /
1341 (((uint64_t)timecounter->tc_counter_mask + 1) / 3));
1343 ffclock_change_tc(th);
1348 * Recalculate the scaling factor. We want the number of 1/2^64
1349 * fractions of a second per period of the hardware counter, taking
1350 * into account the th_adjustment factor which the NTP PLL/adjtime(2)
1351 * processing provides us with.
1353 * The th_adjustment is nanoseconds per second with 32 bit binary
1354 * fraction and we want 64 bit binary fraction of second:
1356 * x = a * 2^32 / 10^9 = a * 4.294967296
1358 * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
1359 * we can only multiply by about 850 without overflowing, that
1360 * leaves no suitably precise fractions for multiply before divide.
1362 * Divide before multiply with a fraction of 2199/512 results in a
1363 * systematic undercompensation of 10PPM of th_adjustment. On a
1364 * 5000PPM adjustment this is a 0.05PPM error. This is acceptable.
1366 * We happily sacrifice the lowest of the 64 bits of our result
1367 * to the goddess of code clarity.
1370 scale = (uint64_t)1 << 63;
1371 scale += (th->th_adjustment / 1024) * 2199;
1372 scale /= th->th_counter->tc_frequency;
1373 th->th_scale = scale * 2;
1376 * Now that the struct timehands is again consistent, set the new
1377 * generation number, making sure to not make it zero.
1381 th->th_generation = ogen;
1383 /* Go live with the new struct timehands. */
1385 switch (sysclock_active) {
1388 time_second = th->th_microtime.tv_sec;
1389 time_uptime = th->th_offset.sec;
1393 time_second = fftimehands->tick_time_lerp.sec;
1394 time_uptime = fftimehands->tick_time_lerp.sec - ffclock_boottime.sec;
1400 timekeep_push_vdso();
1403 /* Report or change the active timecounter hardware. */
1405 sysctl_kern_timecounter_hardware(SYSCTL_HANDLER_ARGS)
1408 struct timecounter *newtc, *tc;
1412 strlcpy(newname, tc->tc_name, sizeof(newname));
1414 error = sysctl_handle_string(oidp, &newname[0], sizeof(newname), req);
1415 if (error != 0 || req->newptr == NULL ||
1416 strcmp(newname, tc->tc_name) == 0)
1418 for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
1419 if (strcmp(newname, newtc->tc_name) != 0)
1422 /* Warm up new timecounter. */
1423 (void)newtc->tc_get_timecount(newtc);
1424 (void)newtc->tc_get_timecount(newtc);
1426 timecounter = newtc;
1427 timekeep_push_vdso();
1433 SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware, CTLTYPE_STRING | CTLFLAG_RW,
1434 0, 0, sysctl_kern_timecounter_hardware, "A",
1435 "Timecounter hardware selected");
1438 /* Report or change the active timecounter hardware. */
1440 sysctl_kern_timecounter_choice(SYSCTL_HANDLER_ARGS)
1443 struct timecounter *tc;
1448 for (tc = timecounters; error == 0 && tc != NULL; tc = tc->tc_next) {
1449 sprintf(buf, "%s%s(%d)",
1450 spc, tc->tc_name, tc->tc_quality);
1451 error = SYSCTL_OUT(req, buf, strlen(buf));
1457 SYSCTL_PROC(_kern_timecounter, OID_AUTO, choice, CTLTYPE_STRING | CTLFLAG_RD,
1458 0, 0, sysctl_kern_timecounter_choice, "A", "Timecounter hardware detected");
1461 * RFC 2783 PPS-API implementation.
1465 pps_fetch(struct pps_fetch_args *fapi, struct pps_state *pps)
1468 pps_seq_t aseq, cseq;
1471 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1475 * If no timeout is requested, immediately return whatever values were
1476 * most recently captured. If timeout seconds is -1, that's a request
1477 * to block without a timeout. WITNESS won't let us sleep forever
1478 * without a lock (we really don't need a lock), so just repeatedly
1479 * sleep a long time.
1481 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec) {
1482 if (fapi->timeout.tv_sec == -1)
1485 tv.tv_sec = fapi->timeout.tv_sec;
1486 tv.tv_usec = fapi->timeout.tv_nsec / 1000;
1489 aseq = pps->ppsinfo.assert_sequence;
1490 cseq = pps->ppsinfo.clear_sequence;
1491 while (aseq == pps->ppsinfo.assert_sequence &&
1492 cseq == pps->ppsinfo.clear_sequence) {
1493 err = tsleep(pps, PCATCH, "ppsfch", timo);
1494 if (err == EWOULDBLOCK && fapi->timeout.tv_sec == -1) {
1496 } else if (err != 0) {
1502 pps->ppsinfo.current_mode = pps->ppsparam.mode;
1503 fapi->pps_info_buf = pps->ppsinfo;
1509 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
1512 struct pps_fetch_args *fapi;
1514 struct pps_fetch_ffc_args *fapi_ffc;
1517 struct pps_kcbind_args *kapi;
1520 KASSERT(pps != NULL, ("NULL pps pointer in pps_ioctl"));
1522 case PPS_IOC_CREATE:
1524 case PPS_IOC_DESTROY:
1526 case PPS_IOC_SETPARAMS:
1527 app = (pps_params_t *)data;
1528 if (app->mode & ~pps->ppscap)
1531 /* Ensure only a single clock is selected for ffc timestamp. */
1532 if ((app->mode & PPS_TSCLK_MASK) == PPS_TSCLK_MASK)
1535 pps->ppsparam = *app;
1537 case PPS_IOC_GETPARAMS:
1538 app = (pps_params_t *)data;
1539 *app = pps->ppsparam;
1540 app->api_version = PPS_API_VERS_1;
1542 case PPS_IOC_GETCAP:
1543 *(int*)data = pps->ppscap;
1546 fapi = (struct pps_fetch_args *)data;
1547 return (pps_fetch(fapi, pps));
1549 case PPS_IOC_FETCH_FFCOUNTER:
1550 fapi_ffc = (struct pps_fetch_ffc_args *)data;
1551 if (fapi_ffc->tsformat && fapi_ffc->tsformat !=
1554 if (fapi_ffc->timeout.tv_sec || fapi_ffc->timeout.tv_nsec)
1555 return (EOPNOTSUPP);
1556 pps->ppsinfo_ffc.current_mode = pps->ppsparam.mode;
1557 fapi_ffc->pps_info_buf_ffc = pps->ppsinfo_ffc;
1558 /* Overwrite timestamps if feedback clock selected. */
1559 switch (pps->ppsparam.mode & PPS_TSCLK_MASK) {
1560 case PPS_TSCLK_FBCK:
1561 fapi_ffc->pps_info_buf_ffc.assert_timestamp =
1562 pps->ppsinfo.assert_timestamp;
1563 fapi_ffc->pps_info_buf_ffc.clear_timestamp =
1564 pps->ppsinfo.clear_timestamp;
1566 case PPS_TSCLK_FFWD:
1572 #endif /* FFCLOCK */
1573 case PPS_IOC_KCBIND:
1575 kapi = (struct pps_kcbind_args *)data;
1576 /* XXX Only root should be able to do this */
1577 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1579 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1581 if (kapi->edge & ~pps->ppscap)
1583 pps->kcmode = kapi->edge;
1586 return (EOPNOTSUPP);
1594 pps_init(struct pps_state *pps)
1596 pps->ppscap |= PPS_TSFMT_TSPEC | PPS_CANWAIT;
1597 if (pps->ppscap & PPS_CAPTUREASSERT)
1598 pps->ppscap |= PPS_OFFSETASSERT;
1599 if (pps->ppscap & PPS_CAPTURECLEAR)
1600 pps->ppscap |= PPS_OFFSETCLEAR;
1602 pps->ppscap |= PPS_TSCLK_MASK;
1607 pps_capture(struct pps_state *pps)
1609 struct timehands *th;
1611 KASSERT(pps != NULL, ("NULL pps pointer in pps_capture"));
1613 pps->capgen = th->th_generation;
1616 pps->capffth = fftimehands;
1618 pps->capcount = th->th_counter->tc_get_timecount(th->th_counter);
1619 if (pps->capgen != th->th_generation)
1624 pps_event(struct pps_state *pps, int event)
1627 struct timespec ts, *tsp, *osp;
1628 u_int tcount, *pcount;
1632 struct timespec *tsp_ffc;
1633 pps_seq_t *pseq_ffc;
1637 KASSERT(pps != NULL, ("NULL pps pointer in pps_event"));
1638 /* If the timecounter was wound up underneath us, bail out. */
1639 if (pps->capgen == 0 || pps->capgen != pps->capth->th_generation)
1642 /* Things would be easier with arrays. */
1643 if (event == PPS_CAPTUREASSERT) {
1644 tsp = &pps->ppsinfo.assert_timestamp;
1645 osp = &pps->ppsparam.assert_offset;
1646 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1647 fhard = pps->kcmode & PPS_CAPTUREASSERT;
1648 pcount = &pps->ppscount[0];
1649 pseq = &pps->ppsinfo.assert_sequence;
1651 ffcount = &pps->ppsinfo_ffc.assert_ffcount;
1652 tsp_ffc = &pps->ppsinfo_ffc.assert_timestamp;
1653 pseq_ffc = &pps->ppsinfo_ffc.assert_sequence;
1656 tsp = &pps->ppsinfo.clear_timestamp;
1657 osp = &pps->ppsparam.clear_offset;
1658 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1659 fhard = pps->kcmode & PPS_CAPTURECLEAR;
1660 pcount = &pps->ppscount[1];
1661 pseq = &pps->ppsinfo.clear_sequence;
1663 ffcount = &pps->ppsinfo_ffc.clear_ffcount;
1664 tsp_ffc = &pps->ppsinfo_ffc.clear_timestamp;
1665 pseq_ffc = &pps->ppsinfo_ffc.clear_sequence;
1670 * If the timecounter changed, we cannot compare the count values, so
1671 * we have to drop the rest of the PPS-stuff until the next event.
1673 if (pps->ppstc != pps->capth->th_counter) {
1674 pps->ppstc = pps->capth->th_counter;
1675 *pcount = pps->capcount;
1676 pps->ppscount[2] = pps->capcount;
1680 /* Convert the count to a timespec. */
1681 tcount = pps->capcount - pps->capth->th_offset_count;
1682 tcount &= pps->capth->th_counter->tc_counter_mask;
1683 bt = pps->capth->th_offset;
1684 bintime_addx(&bt, pps->capth->th_scale * tcount);
1685 bintime_add(&bt, &boottimebin);
1686 bintime2timespec(&bt, &ts);
1688 /* If the timecounter was wound up underneath us, bail out. */
1689 if (pps->capgen != pps->capth->th_generation)
1692 *pcount = pps->capcount;
1697 timespecadd(tsp, osp);
1698 if (tsp->tv_nsec < 0) {
1699 tsp->tv_nsec += 1000000000;
1705 *ffcount = pps->capffth->tick_ffcount + tcount;
1706 bt = pps->capffth->tick_time;
1707 ffclock_convert_delta(tcount, pps->capffth->cest.period, &bt);
1708 bintime_add(&bt, &pps->capffth->tick_time);
1709 bintime2timespec(&bt, &ts);
1719 * Feed the NTP PLL/FLL.
1720 * The FLL wants to know how many (hardware) nanoseconds
1721 * elapsed since the previous event.
1723 tcount = pps->capcount - pps->ppscount[2];
1724 pps->ppscount[2] = pps->capcount;
1725 tcount &= pps->capth->th_counter->tc_counter_mask;
1726 scale = (uint64_t)1 << 63;
1727 scale /= pps->capth->th_counter->tc_frequency;
1731 bintime_addx(&bt, scale * tcount);
1732 bintime2timespec(&bt, &ts);
1733 hardpps(tsp, ts.tv_nsec + 1000000000 * ts.tv_sec);
1737 /* Wakeup anyone sleeping in pps_fetch(). */
1742 * Timecounters need to be updated every so often to prevent the hardware
1743 * counter from overflowing. Updating also recalculates the cached values
1744 * used by the get*() family of functions, so their precision depends on
1745 * the update frequency.
1749 SYSCTL_INT(_kern_timecounter, OID_AUTO, tick, CTLFLAG_RD, &tc_tick, 0,
1750 "Approximate number of hardclock ticks in a millisecond");
1753 tc_ticktock(int cnt)
1758 if (count < tc_tick)
1764 static void __inline
1765 tc_adjprecision(void)
1769 if (tc_timepercentage > 0) {
1770 t = (99 + tc_timepercentage) / tc_timepercentage;
1771 tc_precexp = fls(t + (t >> 1)) - 1;
1772 FREQ2BT(hz / tc_tick, &bt_timethreshold);
1773 FREQ2BT(hz, &bt_tickthreshold);
1774 bintime_shift(&bt_timethreshold, tc_precexp);
1775 bintime_shift(&bt_tickthreshold, tc_precexp);
1778 bt_timethreshold.sec = INT_MAX;
1779 bt_timethreshold.frac = ~(uint64_t)0;
1780 bt_tickthreshold = bt_timethreshold;
1782 sbt_timethreshold = bttosbt(bt_timethreshold);
1783 sbt_tickthreshold = bttosbt(bt_tickthreshold);
1787 sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS)
1791 val = tc_timepercentage;
1792 error = sysctl_handle_int(oidp, &val, 0, req);
1793 if (error != 0 || req->newptr == NULL)
1795 tc_timepercentage = val;
1804 inittimecounter(void *dummy)
1810 * Set the initial timeout to
1811 * max(1, <approx. number of hardclock ticks in a millisecond>).
1812 * People should probably not use the sysctl to set the timeout
1813 * to smaller than its inital value, since that value is the
1814 * smallest reasonable one. If they want better timestamps they
1815 * should use the non-"get"* functions.
1818 tc_tick = (hz + 500) / 1000;
1822 FREQ2BT(hz, &tick_bt);
1823 tick_sbt = bttosbt(tick_bt);
1824 tick_rate = hz / tc_tick;
1825 FREQ2BT(tick_rate, &tc_tick_bt);
1826 tc_tick_sbt = bttosbt(tc_tick_bt);
1827 p = (tc_tick * 1000000) / hz;
1828 printf("Timecounters tick every %d.%03u msec\n", p / 1000, p % 1000);
1833 /* warm up new timecounter (again) and get rolling. */
1834 (void)timecounter->tc_get_timecount(timecounter);
1835 (void)timecounter->tc_get_timecount(timecounter);
1839 SYSINIT(timecounter, SI_SUB_CLOCKS, SI_ORDER_SECOND, inittimecounter, NULL);
1841 /* Cpu tick handling -------------------------------------------------*/
1843 static int cpu_tick_variable;
1844 static uint64_t cpu_tick_frequency;
1849 static uint64_t base;
1850 static unsigned last;
1852 struct timecounter *tc;
1854 tc = timehands->th_counter;
1855 u = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
1857 base += (uint64_t)tc->tc_counter_mask + 1;
1863 cpu_tick_calibration(void)
1865 static time_t last_calib;
1867 if (time_uptime != last_calib && !(time_uptime & 0xf)) {
1868 cpu_tick_calibrate(0);
1869 last_calib = time_uptime;
1874 * This function gets called every 16 seconds on only one designated
1875 * CPU in the system from hardclock() via cpu_tick_calibration()().
1877 * Whenever the real time clock is stepped we get called with reset=1
1878 * to make sure we handle suspend/resume and similar events correctly.
1882 cpu_tick_calibrate(int reset)
1884 static uint64_t c_last;
1885 uint64_t c_this, c_delta;
1886 static struct bintime t_last;
1887 struct bintime t_this, t_delta;
1891 /* The clock was stepped, abort & reset */
1896 /* we don't calibrate fixed rate cputicks */
1897 if (!cpu_tick_variable)
1900 getbinuptime(&t_this);
1901 c_this = cpu_ticks();
1902 if (t_last.sec != 0) {
1903 c_delta = c_this - c_last;
1905 bintime_sub(&t_delta, &t_last);
1908 * 2^(64-20) / 16[s] =
1910 * 17.592.186.044.416 / 16 =
1911 * 1.099.511.627.776 [Hz]
1913 divi = t_delta.sec << 20;
1914 divi |= t_delta.frac >> (64 - 20);
1917 if (c_delta > cpu_tick_frequency) {
1918 if (0 && bootverbose)
1919 printf("cpu_tick increased to %ju Hz\n",
1921 cpu_tick_frequency = c_delta;
1929 set_cputicker(cpu_tick_f *func, uint64_t freq, unsigned var)
1933 cpu_ticks = tc_cpu_ticks;
1935 cpu_tick_frequency = freq;
1936 cpu_tick_variable = var;
1945 if (cpu_ticks == tc_cpu_ticks)
1946 return (tc_getfrequency());
1947 return (cpu_tick_frequency);
1951 * We need to be slightly careful converting cputicks to microseconds.
1952 * There is plenty of margin in 64 bits of microseconds (half a million
1953 * years) and in 64 bits at 4 GHz (146 years), but if we do a multiply
1954 * before divide conversion (to retain precision) we find that the
1955 * margin shrinks to 1.5 hours (one millionth of 146y).
1956 * With a three prong approach we never lose significant bits, no
1957 * matter what the cputick rate and length of timeinterval is.
1961 cputick2usec(uint64_t tick)
1964 if (tick > 18446744073709551LL) /* floor(2^64 / 1000) */
1965 return (tick / (cpu_tickrate() / 1000000LL));
1966 else if (tick > 18446744073709LL) /* floor(2^64 / 1000000) */
1967 return ((tick * 1000LL) / (cpu_tickrate() / 1000LL));
1969 return ((tick * 1000000LL) / cpu_tickrate());
1972 cpu_tick_f *cpu_ticks = tc_cpu_ticks;
1974 static int vdso_th_enable = 1;
1976 sysctl_fast_gettime(SYSCTL_HANDLER_ARGS)
1978 int old_vdso_th_enable, error;
1980 old_vdso_th_enable = vdso_th_enable;
1981 error = sysctl_handle_int(oidp, &old_vdso_th_enable, 0, req);
1984 vdso_th_enable = old_vdso_th_enable;
1985 timekeep_push_vdso();
1988 SYSCTL_PROC(_kern_timecounter, OID_AUTO, fast_gettime,
1989 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1990 NULL, 0, sysctl_fast_gettime, "I", "Enable fast time of day");
1993 tc_fill_vdso_timehands(struct vdso_timehands *vdso_th)
1995 struct timehands *th;
1999 vdso_th->th_algo = VDSO_TH_ALGO_1;
2000 vdso_th->th_scale = th->th_scale;
2001 vdso_th->th_offset_count = th->th_offset_count;
2002 vdso_th->th_counter_mask = th->th_counter->tc_counter_mask;
2003 vdso_th->th_offset = th->th_offset;
2004 vdso_th->th_boottime = boottimebin;
2005 enabled = cpu_fill_vdso_timehands(vdso_th);
2006 if (!vdso_th_enable)
2011 #ifdef COMPAT_FREEBSD32
2013 tc_fill_vdso_timehands32(struct vdso_timehands32 *vdso_th32)
2015 struct timehands *th;
2019 vdso_th32->th_algo = VDSO_TH_ALGO_1;
2020 *(uint64_t *)&vdso_th32->th_scale[0] = th->th_scale;
2021 vdso_th32->th_offset_count = th->th_offset_count;
2022 vdso_th32->th_counter_mask = th->th_counter->tc_counter_mask;
2023 vdso_th32->th_offset.sec = th->th_offset.sec;
2024 *(uint64_t *)&vdso_th32->th_offset.frac[0] = th->th_offset.frac;
2025 vdso_th32->th_boottime.sec = boottimebin.sec;
2026 *(uint64_t *)&vdso_th32->th_boottime.frac[0] = boottimebin.frac;
2027 enabled = cpu_fill_vdso_timehands32(vdso_th32);
2028 if (!vdso_th_enable)