2 * SPDX-License-Identifier: Beerware
4 * ----------------------------------------------------------------------------
5 * "THE BEER-WARE LICENSE" (Revision 42):
6 * <phk@FreeBSD.ORG> wrote this file. As long as you retain this notice you
7 * can do whatever you want with this stuff. If we meet some day, and you think
8 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
9 * ----------------------------------------------------------------------------
11 * Copyright (c) 2011, 2015, 2016 The FreeBSD Foundation
12 * All rights reserved.
14 * Portions of this software were developed by Julien Ridoux at the University
15 * of Melbourne under sponsorship from the FreeBSD Foundation.
17 * Portions of this software were developed by Konstantin Belousov
18 * under sponsorship from the FreeBSD Foundation.
21 #include <sys/cdefs.h>
22 __FBSDID("$FreeBSD$");
25 #include "opt_ffclock.h"
27 #include <sys/param.h>
28 #include <sys/kernel.h>
29 #include <sys/limits.h>
31 #include <sys/mutex.h>
34 #include <sys/sleepqueue.h>
35 #include <sys/sysctl.h>
36 #include <sys/syslog.h>
37 #include <sys/systm.h>
38 #include <sys/timeffc.h>
39 #include <sys/timepps.h>
40 #include <sys/timetc.h>
41 #include <sys/timex.h>
45 * A large step happens on boot. This constant detects such steps.
46 * It is relatively small so that ntp_update_second gets called enough
47 * in the typical 'missed a couple of seconds' case, but doesn't loop
48 * forever when the time step is large.
50 #define LARGE_STEP 200
53 * Implement a dummy timecounter which we can use until we get a real one
54 * in the air. This allows the console and other early stuff to use
59 dummy_get_timecount(struct timecounter *tc)
66 static struct timecounter dummy_timecounter = {
67 dummy_get_timecount, 0, ~0u, 1000000, "dummy", -1000000
71 /* These fields must be initialized by the driver. */
72 struct timecounter *th_counter;
73 int64_t th_adjustment;
76 u_int th_offset_count;
77 struct bintime th_offset;
78 struct bintime th_bintime;
79 struct timeval th_microtime;
80 struct timespec th_nanotime;
81 struct bintime th_boottime;
82 /* Fields not to be copied in tc_windup start with th_generation. */
84 struct timehands *th_next;
87 static struct timehands ths[16] = {
89 .th_counter = &dummy_timecounter,
90 .th_scale = (uint64_t)-1 / 1000000,
91 .th_large_delta = 1000000,
92 .th_offset = { .sec = 1 },
97 static struct timehands *volatile timehands = &ths[0];
98 struct timecounter *timecounter = &dummy_timecounter;
99 static struct timecounter *timecounters = &dummy_timecounter;
101 int tc_min_ticktock_freq = 1;
103 volatile time_t time_second = 1;
104 volatile time_t time_uptime = 1;
106 static int sysctl_kern_boottime(SYSCTL_HANDLER_ARGS);
107 SYSCTL_PROC(_kern, KERN_BOOTTIME, boottime,
108 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
109 sysctl_kern_boottime, "S,timeval",
112 SYSCTL_NODE(_kern, OID_AUTO, timecounter, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
114 static SYSCTL_NODE(_kern_timecounter, OID_AUTO, tc,
115 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
118 static int timestepwarnings;
119 SYSCTL_INT(_kern_timecounter, OID_AUTO, stepwarnings, CTLFLAG_RW,
120 ×tepwarnings, 0, "Log time steps");
122 static int timehands_count = 2;
123 SYSCTL_INT(_kern_timecounter, OID_AUTO, timehands_count,
124 CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
125 &timehands_count, 0, "Count of timehands in rotation");
127 struct bintime bt_timethreshold;
128 struct bintime bt_tickthreshold;
129 sbintime_t sbt_timethreshold;
130 sbintime_t sbt_tickthreshold;
131 struct bintime tc_tick_bt;
132 sbintime_t tc_tick_sbt;
134 int tc_timepercentage = TC_DEFAULTPERC;
135 static int sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS);
136 SYSCTL_PROC(_kern_timecounter, OID_AUTO, alloweddeviation,
137 CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, 0, 0,
138 sysctl_kern_timecounter_adjprecision, "I",
139 "Allowed time interval deviation in percents");
141 volatile int rtc_generation = 1;
143 static int tc_chosen; /* Non-zero if a specific tc was chosen via sysctl. */
145 static void tc_windup(struct bintime *new_boottimebin);
146 static void cpu_tick_calibrate(int);
148 void dtrace_getnanotime(struct timespec *tsp);
151 sysctl_kern_boottime(SYSCTL_HANDLER_ARGS)
153 struct timeval boottime;
155 getboottime(&boottime);
157 /* i386 is the only arch which uses a 32bits time_t */
162 if (req->flags & SCTL_MASK32) {
163 tv[0] = boottime.tv_sec;
164 tv[1] = boottime.tv_usec;
165 return (SYSCTL_OUT(req, tv, sizeof(tv)));
169 return (SYSCTL_OUT(req, &boottime, sizeof(boottime)));
173 sysctl_kern_timecounter_get(SYSCTL_HANDLER_ARGS)
176 struct timecounter *tc = arg1;
178 ncount = tc->tc_get_timecount(tc);
179 return (sysctl_handle_int(oidp, &ncount, 0, req));
183 sysctl_kern_timecounter_freq(SYSCTL_HANDLER_ARGS)
186 struct timecounter *tc = arg1;
188 freq = tc->tc_frequency;
189 return (sysctl_handle_64(oidp, &freq, 0, req));
193 * Return the difference between the timehands' counter value now and what
194 * was when we copied it to the timehands' offset_count.
196 static __inline u_int
197 tc_delta(struct timehands *th)
199 struct timecounter *tc;
202 return ((tc->tc_get_timecount(tc) - th->th_offset_count) &
203 tc->tc_counter_mask);
207 * Functions for reading the time. We have to loop until we are sure that
208 * the timehands that we operated on was not updated under our feet. See
209 * the comment in <sys/time.h> for a description of these 12 functions.
213 bintime_off(struct bintime *bt, u_int off)
215 struct timehands *th;
218 u_int delta, gen, large_delta;
222 gen = atomic_load_acq_int(&th->th_generation);
223 btp = (struct bintime *)((vm_offset_t)th + off);
225 scale = th->th_scale;
226 delta = tc_delta(th);
227 large_delta = th->th_large_delta;
228 atomic_thread_fence_acq();
229 } while (gen == 0 || gen != th->th_generation);
231 if (__predict_false(delta >= large_delta)) {
232 /* Avoid overflow for scale * delta. */
233 x = (scale >> 32) * delta;
235 bintime_addx(bt, x << 32);
236 bintime_addx(bt, (scale & 0xffffffff) * delta);
238 bintime_addx(bt, scale * delta);
241 #define GETTHBINTIME(dst, member) \
243 _Static_assert(_Generic(((struct timehands *)NULL)->member, \
244 struct bintime: 1, default: 0) == 1, \
245 "struct timehands member is not of struct bintime type"); \
246 bintime_off(dst, __offsetof(struct timehands, member)); \
250 getthmember(void *out, size_t out_size, u_int off)
252 struct timehands *th;
257 gen = atomic_load_acq_int(&th->th_generation);
258 memcpy(out, (char *)th + off, out_size);
259 atomic_thread_fence_acq();
260 } while (gen == 0 || gen != th->th_generation);
262 #define GETTHMEMBER(dst, member) \
264 _Static_assert(_Generic(*dst, \
265 __typeof(((struct timehands *)NULL)->member): 1, \
267 "*dst and struct timehands member have different types"); \
268 getthmember(dst, sizeof(*dst), __offsetof(struct timehands, \
274 fbclock_binuptime(struct bintime *bt)
277 GETTHBINTIME(bt, th_offset);
281 fbclock_nanouptime(struct timespec *tsp)
285 fbclock_binuptime(&bt);
286 bintime2timespec(&bt, tsp);
290 fbclock_microuptime(struct timeval *tvp)
294 fbclock_binuptime(&bt);
295 bintime2timeval(&bt, tvp);
299 fbclock_bintime(struct bintime *bt)
302 GETTHBINTIME(bt, th_bintime);
306 fbclock_nanotime(struct timespec *tsp)
310 fbclock_bintime(&bt);
311 bintime2timespec(&bt, tsp);
315 fbclock_microtime(struct timeval *tvp)
319 fbclock_bintime(&bt);
320 bintime2timeval(&bt, tvp);
324 fbclock_getbinuptime(struct bintime *bt)
327 GETTHMEMBER(bt, th_offset);
331 fbclock_getnanouptime(struct timespec *tsp)
335 GETTHMEMBER(&bt, th_offset);
336 bintime2timespec(&bt, tsp);
340 fbclock_getmicrouptime(struct timeval *tvp)
344 GETTHMEMBER(&bt, th_offset);
345 bintime2timeval(&bt, tvp);
349 fbclock_getbintime(struct bintime *bt)
352 GETTHMEMBER(bt, th_bintime);
356 fbclock_getnanotime(struct timespec *tsp)
359 GETTHMEMBER(tsp, th_nanotime);
363 fbclock_getmicrotime(struct timeval *tvp)
366 GETTHMEMBER(tvp, th_microtime);
371 binuptime(struct bintime *bt)
374 GETTHBINTIME(bt, th_offset);
378 nanouptime(struct timespec *tsp)
383 bintime2timespec(&bt, tsp);
387 microuptime(struct timeval *tvp)
392 bintime2timeval(&bt, tvp);
396 bintime(struct bintime *bt)
399 GETTHBINTIME(bt, th_bintime);
403 nanotime(struct timespec *tsp)
408 bintime2timespec(&bt, tsp);
412 microtime(struct timeval *tvp)
417 bintime2timeval(&bt, tvp);
421 getbinuptime(struct bintime *bt)
424 GETTHMEMBER(bt, th_offset);
428 getnanouptime(struct timespec *tsp)
432 GETTHMEMBER(&bt, th_offset);
433 bintime2timespec(&bt, tsp);
437 getmicrouptime(struct timeval *tvp)
441 GETTHMEMBER(&bt, th_offset);
442 bintime2timeval(&bt, tvp);
446 getbintime(struct bintime *bt)
449 GETTHMEMBER(bt, th_bintime);
453 getnanotime(struct timespec *tsp)
456 GETTHMEMBER(tsp, th_nanotime);
460 getmicrotime(struct timeval *tvp)
463 GETTHMEMBER(tvp, th_microtime);
468 getboottime(struct timeval *boottime)
470 struct bintime boottimebin;
472 getboottimebin(&boottimebin);
473 bintime2timeval(&boottimebin, boottime);
477 getboottimebin(struct bintime *boottimebin)
480 GETTHMEMBER(boottimebin, th_boottime);
485 * Support for feed-forward synchronization algorithms. This is heavily inspired
486 * by the timehands mechanism but kept independent from it. *_windup() functions
487 * have some connection to avoid accessing the timecounter hardware more than
491 /* Feed-forward clock estimates kept updated by the synchronization daemon. */
492 struct ffclock_estimate ffclock_estimate;
493 struct bintime ffclock_boottime; /* Feed-forward boot time estimate. */
494 uint32_t ffclock_status; /* Feed-forward clock status. */
495 int8_t ffclock_updated; /* New estimates are available. */
496 struct mtx ffclock_mtx; /* Mutex on ffclock_estimate. */
499 struct ffclock_estimate cest;
500 struct bintime tick_time;
501 struct bintime tick_time_lerp;
502 ffcounter tick_ffcount;
503 uint64_t period_lerp;
504 volatile uint8_t gen;
505 struct fftimehands *next;
508 #define NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))
510 static struct fftimehands ffth[10];
511 static struct fftimehands *volatile fftimehands = ffth;
516 struct fftimehands *cur;
517 struct fftimehands *last;
519 memset(ffth, 0, sizeof(ffth));
521 last = ffth + NUM_ELEMENTS(ffth) - 1;
522 for (cur = ffth; cur < last; cur++)
527 ffclock_status = FFCLOCK_STA_UNSYNC;
528 mtx_init(&ffclock_mtx, "ffclock lock", NULL, MTX_DEF);
532 * Reset the feed-forward clock estimates. Called from inittodr() to get things
533 * kick started and uses the timecounter nominal frequency as a first period
534 * estimate. Note: this function may be called several time just after boot.
535 * Note: this is the only function that sets the value of boot time for the
536 * monotonic (i.e. uptime) version of the feed-forward clock.
539 ffclock_reset_clock(struct timespec *ts)
541 struct timecounter *tc;
542 struct ffclock_estimate cest;
544 tc = timehands->th_counter;
545 memset(&cest, 0, sizeof(struct ffclock_estimate));
547 timespec2bintime(ts, &ffclock_boottime);
548 timespec2bintime(ts, &(cest.update_time));
549 ffclock_read_counter(&cest.update_ffcount);
550 cest.leapsec_next = 0;
551 cest.period = ((1ULL << 63) / tc->tc_frequency) << 1;
554 cest.status = FFCLOCK_STA_UNSYNC;
555 cest.leapsec_total = 0;
558 mtx_lock(&ffclock_mtx);
559 bcopy(&cest, &ffclock_estimate, sizeof(struct ffclock_estimate));
560 ffclock_updated = INT8_MAX;
561 mtx_unlock(&ffclock_mtx);
563 printf("ffclock reset: %s (%llu Hz), time = %ld.%09lu\n", tc->tc_name,
564 (unsigned long long)tc->tc_frequency, (long)ts->tv_sec,
565 (unsigned long)ts->tv_nsec);
569 * Sub-routine to convert a time interval measured in RAW counter units to time
570 * in seconds stored in bintime format.
571 * NOTE: bintime_mul requires u_int, but the value of the ffcounter may be
572 * larger than the max value of u_int (on 32 bit architecture). Loop to consume
576 ffclock_convert_delta(ffcounter ffdelta, uint64_t period, struct bintime *bt)
579 ffcounter delta, delta_max;
581 delta_max = (1ULL << (8 * sizeof(unsigned int))) - 1;
584 if (ffdelta > delta_max)
590 bintime_mul(&bt2, (unsigned int)delta);
591 bintime_add(bt, &bt2);
593 } while (ffdelta > 0);
597 * Update the fftimehands.
598 * Push the tick ffcount and time(s) forward based on current clock estimate.
599 * The conversion from ffcounter to bintime relies on the difference clock
600 * principle, whose accuracy relies on computing small time intervals. If a new
601 * clock estimate has been passed by the synchronisation daemon, make it
602 * current, and compute the linear interpolation for monotonic time if needed.
605 ffclock_windup(unsigned int delta)
607 struct ffclock_estimate *cest;
608 struct fftimehands *ffth;
609 struct bintime bt, gap_lerp;
612 unsigned int polling;
613 uint8_t forward_jump, ogen;
616 * Pick the next timehand, copy current ffclock estimates and move tick
617 * times and counter forward.
620 ffth = fftimehands->next;
624 bcopy(&fftimehands->cest, cest, sizeof(struct ffclock_estimate));
625 ffdelta = (ffcounter)delta;
626 ffth->period_lerp = fftimehands->period_lerp;
628 ffth->tick_time = fftimehands->tick_time;
629 ffclock_convert_delta(ffdelta, cest->period, &bt);
630 bintime_add(&ffth->tick_time, &bt);
632 ffth->tick_time_lerp = fftimehands->tick_time_lerp;
633 ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt);
634 bintime_add(&ffth->tick_time_lerp, &bt);
636 ffth->tick_ffcount = fftimehands->tick_ffcount + ffdelta;
639 * Assess the status of the clock, if the last update is too old, it is
640 * likely the synchronisation daemon is dead and the clock is free
643 if (ffclock_updated == 0) {
644 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
645 ffclock_convert_delta(ffdelta, cest->period, &bt);
646 if (bt.sec > 2 * FFCLOCK_SKM_SCALE)
647 ffclock_status |= FFCLOCK_STA_UNSYNC;
651 * If available, grab updated clock estimates and make them current.
652 * Recompute time at this tick using the updated estimates. The clock
653 * estimates passed the feed-forward synchronisation daemon may result
654 * in time conversion that is not monotonically increasing (just after
655 * the update). time_lerp is a particular linear interpolation over the
656 * synchronisation algo polling period that ensures monotonicity for the
657 * clock ids requesting it.
659 if (ffclock_updated > 0) {
660 bcopy(&ffclock_estimate, cest, sizeof(struct ffclock_estimate));
661 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
662 ffth->tick_time = cest->update_time;
663 ffclock_convert_delta(ffdelta, cest->period, &bt);
664 bintime_add(&ffth->tick_time, &bt);
666 /* ffclock_reset sets ffclock_updated to INT8_MAX */
667 if (ffclock_updated == INT8_MAX)
668 ffth->tick_time_lerp = ffth->tick_time;
670 if (bintime_cmp(&ffth->tick_time, &ffth->tick_time_lerp, >))
675 bintime_clear(&gap_lerp);
677 gap_lerp = ffth->tick_time;
678 bintime_sub(&gap_lerp, &ffth->tick_time_lerp);
680 gap_lerp = ffth->tick_time_lerp;
681 bintime_sub(&gap_lerp, &ffth->tick_time);
685 * The reset from the RTC clock may be far from accurate, and
686 * reducing the gap between real time and interpolated time
687 * could take a very long time if the interpolated clock insists
688 * on strict monotonicity. The clock is reset under very strict
689 * conditions (kernel time is known to be wrong and
690 * synchronization daemon has been restarted recently.
691 * ffclock_boottime absorbs the jump to ensure boot time is
692 * correct and uptime functions stay consistent.
694 if (((ffclock_status & FFCLOCK_STA_UNSYNC) == FFCLOCK_STA_UNSYNC) &&
695 ((cest->status & FFCLOCK_STA_UNSYNC) == 0) &&
696 ((cest->status & FFCLOCK_STA_WARMUP) == FFCLOCK_STA_WARMUP)) {
698 bintime_add(&ffclock_boottime, &gap_lerp);
700 bintime_sub(&ffclock_boottime, &gap_lerp);
701 ffth->tick_time_lerp = ffth->tick_time;
702 bintime_clear(&gap_lerp);
705 ffclock_status = cest->status;
706 ffth->period_lerp = cest->period;
709 * Compute corrected period used for the linear interpolation of
710 * time. The rate of linear interpolation is capped to 5000PPM
713 if (bintime_isset(&gap_lerp)) {
714 ffdelta = cest->update_ffcount;
715 ffdelta -= fftimehands->cest.update_ffcount;
716 ffclock_convert_delta(ffdelta, cest->period, &bt);
719 bt.frac = 5000000 * (uint64_t)18446744073LL;
720 bintime_mul(&bt, polling);
721 if (bintime_cmp(&gap_lerp, &bt, >))
724 /* Approximate 1 sec by 1-(1/2^64) to ease arithmetic */
726 if (gap_lerp.sec > 0) {
728 frac /= ffdelta / gap_lerp.sec;
730 frac += gap_lerp.frac / ffdelta;
733 ffth->period_lerp += frac;
735 ffth->period_lerp -= frac;
747 * Adjust the fftimehands when the timecounter is changed. Stating the obvious,
748 * the old and new hardware counter cannot be read simultaneously. tc_windup()
749 * does read the two counters 'back to back', but a few cycles are effectively
750 * lost, and not accumulated in tick_ffcount. This is a fairly radical
751 * operation for a feed-forward synchronization daemon, and it is its job to not
752 * pushing irrelevant data to the kernel. Because there is no locking here,
753 * simply force to ignore pending or next update to give daemon a chance to
754 * realize the counter has changed.
757 ffclock_change_tc(struct timehands *th)
759 struct fftimehands *ffth;
760 struct ffclock_estimate *cest;
761 struct timecounter *tc;
765 ffth = fftimehands->next;
770 bcopy(&(fftimehands->cest), cest, sizeof(struct ffclock_estimate));
771 cest->period = ((1ULL << 63) / tc->tc_frequency ) << 1;
774 cest->status |= FFCLOCK_STA_UNSYNC;
776 ffth->tick_ffcount = fftimehands->tick_ffcount;
777 ffth->tick_time_lerp = fftimehands->tick_time_lerp;
778 ffth->tick_time = fftimehands->tick_time;
779 ffth->period_lerp = cest->period;
781 /* Do not lock but ignore next update from synchronization daemon. */
791 * Retrieve feed-forward counter and time of last kernel tick.
794 ffclock_last_tick(ffcounter *ffcount, struct bintime *bt, uint32_t flags)
796 struct fftimehands *ffth;
800 * No locking but check generation has not changed. Also need to make
801 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
806 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP)
807 *bt = ffth->tick_time_lerp;
809 *bt = ffth->tick_time;
810 *ffcount = ffth->tick_ffcount;
811 } while (gen == 0 || gen != ffth->gen);
815 * Absolute clock conversion. Low level function to convert ffcounter to
816 * bintime. The ffcounter is converted using the current ffclock period estimate
817 * or the "interpolated period" to ensure monotonicity.
818 * NOTE: this conversion may have been deferred, and the clock updated since the
819 * hardware counter has been read.
822 ffclock_convert_abs(ffcounter ffcount, struct bintime *bt, uint32_t flags)
824 struct fftimehands *ffth;
830 * No locking but check generation has not changed. Also need to make
831 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
836 if (ffcount > ffth->tick_ffcount)
837 ffdelta = ffcount - ffth->tick_ffcount;
839 ffdelta = ffth->tick_ffcount - ffcount;
841 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP) {
842 *bt = ffth->tick_time_lerp;
843 ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt2);
845 *bt = ffth->tick_time;
846 ffclock_convert_delta(ffdelta, ffth->cest.period, &bt2);
849 if (ffcount > ffth->tick_ffcount)
850 bintime_add(bt, &bt2);
852 bintime_sub(bt, &bt2);
853 } while (gen == 0 || gen != ffth->gen);
857 * Difference clock conversion.
858 * Low level function to Convert a time interval measured in RAW counter units
859 * into bintime. The difference clock allows measuring small intervals much more
860 * reliably than the absolute clock.
863 ffclock_convert_diff(ffcounter ffdelta, struct bintime *bt)
865 struct fftimehands *ffth;
868 /* No locking but check generation has not changed. */
872 ffclock_convert_delta(ffdelta, ffth->cest.period, bt);
873 } while (gen == 0 || gen != ffth->gen);
877 * Access to current ffcounter value.
880 ffclock_read_counter(ffcounter *ffcount)
882 struct timehands *th;
883 struct fftimehands *ffth;
884 unsigned int gen, delta;
887 * ffclock_windup() called from tc_windup(), safe to rely on
888 * th->th_generation only, for correct delta and ffcounter.
892 gen = atomic_load_acq_int(&th->th_generation);
894 delta = tc_delta(th);
895 *ffcount = ffth->tick_ffcount;
896 atomic_thread_fence_acq();
897 } while (gen == 0 || gen != th->th_generation);
903 binuptime(struct bintime *bt)
906 binuptime_fromclock(bt, sysclock_active);
910 nanouptime(struct timespec *tsp)
913 nanouptime_fromclock(tsp, sysclock_active);
917 microuptime(struct timeval *tvp)
920 microuptime_fromclock(tvp, sysclock_active);
924 bintime(struct bintime *bt)
927 bintime_fromclock(bt, sysclock_active);
931 nanotime(struct timespec *tsp)
934 nanotime_fromclock(tsp, sysclock_active);
938 microtime(struct timeval *tvp)
941 microtime_fromclock(tvp, sysclock_active);
945 getbinuptime(struct bintime *bt)
948 getbinuptime_fromclock(bt, sysclock_active);
952 getnanouptime(struct timespec *tsp)
955 getnanouptime_fromclock(tsp, sysclock_active);
959 getmicrouptime(struct timeval *tvp)
962 getmicrouptime_fromclock(tvp, sysclock_active);
966 getbintime(struct bintime *bt)
969 getbintime_fromclock(bt, sysclock_active);
973 getnanotime(struct timespec *tsp)
976 getnanotime_fromclock(tsp, sysclock_active);
980 getmicrotime(struct timeval *tvp)
983 getmicrouptime_fromclock(tvp, sysclock_active);
989 * This is a clone of getnanotime and used for walltimestamps.
990 * The dtrace_ prefix prevents fbt from creating probes for
991 * it so walltimestamp can be safely used in all fbt probes.
994 dtrace_getnanotime(struct timespec *tsp)
997 GETTHMEMBER(tsp, th_nanotime);
1001 * System clock currently providing time to the system. Modifiable via sysctl
1002 * when the FFCLOCK option is defined.
1004 int sysclock_active = SYSCLOCK_FBCK;
1006 /* Internal NTP status and error estimates. */
1007 extern int time_status;
1008 extern long time_esterror;
1011 * Take a snapshot of sysclock data which can be used to compare system clocks
1012 * and generate timestamps after the fact.
1015 sysclock_getsnapshot(struct sysclock_snap *clock_snap, int fast)
1017 struct fbclock_info *fbi;
1018 struct timehands *th;
1020 unsigned int delta, gen;
1023 struct fftimehands *ffth;
1024 struct ffclock_info *ffi;
1025 struct ffclock_estimate cest;
1027 ffi = &clock_snap->ff_info;
1030 fbi = &clock_snap->fb_info;
1035 gen = atomic_load_acq_int(&th->th_generation);
1036 fbi->th_scale = th->th_scale;
1037 fbi->tick_time = th->th_offset;
1040 ffi->tick_time = ffth->tick_time_lerp;
1041 ffi->tick_time_lerp = ffth->tick_time_lerp;
1042 ffi->period = ffth->cest.period;
1043 ffi->period_lerp = ffth->period_lerp;
1044 clock_snap->ffcount = ffth->tick_ffcount;
1048 delta = tc_delta(th);
1049 atomic_thread_fence_acq();
1050 } while (gen == 0 || gen != th->th_generation);
1052 clock_snap->delta = delta;
1053 clock_snap->sysclock_active = sysclock_active;
1055 /* Record feedback clock status and error. */
1056 clock_snap->fb_info.status = time_status;
1057 /* XXX: Very crude estimate of feedback clock error. */
1058 bt.sec = time_esterror / 1000000;
1059 bt.frac = ((time_esterror - bt.sec) * 1000000) *
1060 (uint64_t)18446744073709ULL;
1061 clock_snap->fb_info.error = bt;
1065 clock_snap->ffcount += delta;
1067 /* Record feed-forward clock leap second adjustment. */
1068 ffi->leapsec_adjustment = cest.leapsec_total;
1069 if (clock_snap->ffcount > cest.leapsec_next)
1070 ffi->leapsec_adjustment -= cest.leapsec;
1072 /* Record feed-forward clock status and error. */
1073 clock_snap->ff_info.status = cest.status;
1074 ffcount = clock_snap->ffcount - cest.update_ffcount;
1075 ffclock_convert_delta(ffcount, cest.period, &bt);
1076 /* 18446744073709 = int(2^64/1e12), err_bound_rate in [ps/s]. */
1077 bintime_mul(&bt, cest.errb_rate * (uint64_t)18446744073709ULL);
1078 /* 18446744073 = int(2^64 / 1e9), since err_abs in [ns]. */
1079 bintime_addx(&bt, cest.errb_abs * (uint64_t)18446744073ULL);
1080 clock_snap->ff_info.error = bt;
1085 * Convert a sysclock snapshot into a struct bintime based on the specified
1086 * clock source and flags.
1089 sysclock_snap2bintime(struct sysclock_snap *cs, struct bintime *bt,
1090 int whichclock, uint32_t flags)
1092 struct bintime boottimebin;
1098 switch (whichclock) {
1100 *bt = cs->fb_info.tick_time;
1102 /* If snapshot was created with !fast, delta will be >0. */
1104 bintime_addx(bt, cs->fb_info.th_scale * cs->delta);
1106 if ((flags & FBCLOCK_UPTIME) == 0) {
1107 getboottimebin(&boottimebin);
1108 bintime_add(bt, &boottimebin);
1113 if (flags & FFCLOCK_LERP) {
1114 *bt = cs->ff_info.tick_time_lerp;
1115 period = cs->ff_info.period_lerp;
1117 *bt = cs->ff_info.tick_time;
1118 period = cs->ff_info.period;
1121 /* If snapshot was created with !fast, delta will be >0. */
1122 if (cs->delta > 0) {
1123 ffclock_convert_delta(cs->delta, period, &bt2);
1124 bintime_add(bt, &bt2);
1127 /* Leap second adjustment. */
1128 if (flags & FFCLOCK_LEAPSEC)
1129 bt->sec -= cs->ff_info.leapsec_adjustment;
1131 /* Boot time adjustment, for uptime/monotonic clocks. */
1132 if (flags & FFCLOCK_UPTIME)
1133 bintime_sub(bt, &ffclock_boottime);
1145 * Initialize a new timecounter and possibly use it.
1148 tc_init(struct timecounter *tc)
1151 struct sysctl_oid *tc_root;
1153 u = tc->tc_frequency / tc->tc_counter_mask;
1154 /* XXX: We need some margin here, 10% is a guess */
1157 if (u > hz && tc->tc_quality >= 0) {
1158 tc->tc_quality = -2000;
1160 printf("Timecounter \"%s\" frequency %ju Hz",
1161 tc->tc_name, (uintmax_t)tc->tc_frequency);
1162 printf(" -- Insufficient hz, needs at least %u\n", u);
1164 } else if (tc->tc_quality >= 0 || bootverbose) {
1165 printf("Timecounter \"%s\" frequency %ju Hz quality %d\n",
1166 tc->tc_name, (uintmax_t)tc->tc_frequency,
1170 tc->tc_next = timecounters;
1173 * Set up sysctl tree for this counter.
1175 tc_root = SYSCTL_ADD_NODE_WITH_LABEL(NULL,
1176 SYSCTL_STATIC_CHILDREN(_kern_timecounter_tc), OID_AUTO, tc->tc_name,
1177 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1178 "timecounter description", "timecounter");
1179 SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1180 "mask", CTLFLAG_RD, &(tc->tc_counter_mask), 0,
1181 "mask for implemented bits");
1182 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1183 "counter", CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, tc,
1184 sizeof(*tc), sysctl_kern_timecounter_get, "IU",
1185 "current timecounter value");
1186 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1187 "frequency", CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, tc,
1188 sizeof(*tc), sysctl_kern_timecounter_freq, "QU",
1189 "timecounter frequency");
1190 SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1191 "quality", CTLFLAG_RD, &(tc->tc_quality), 0,
1192 "goodness of time counter");
1194 * Do not automatically switch if the current tc was specifically
1195 * chosen. Never automatically use a timecounter with negative quality.
1196 * Even though we run on the dummy counter, switching here may be
1197 * worse since this timecounter may not be monotonic.
1201 if (tc->tc_quality < 0)
1203 if (tc->tc_quality < timecounter->tc_quality)
1205 if (tc->tc_quality == timecounter->tc_quality &&
1206 tc->tc_frequency < timecounter->tc_frequency)
1208 (void)tc->tc_get_timecount(tc);
1209 (void)tc->tc_get_timecount(tc);
1213 /* Report the frequency of the current timecounter. */
1215 tc_getfrequency(void)
1218 return (timehands->th_counter->tc_frequency);
1222 sleeping_on_old_rtc(struct thread *td)
1226 * td_rtcgen is modified by curthread when it is running,
1227 * and by other threads in this function. By finding the thread
1228 * on a sleepqueue and holding the lock on the sleepqueue
1229 * chain, we guarantee that the thread is not running and that
1230 * modifying td_rtcgen is safe. Setting td_rtcgen to zero informs
1231 * the thread that it was woken due to a real-time clock adjustment.
1232 * (The declaration of td_rtcgen refers to this comment.)
1234 if (td->td_rtcgen != 0 && td->td_rtcgen != rtc_generation) {
1241 static struct mtx tc_setclock_mtx;
1242 MTX_SYSINIT(tc_setclock_init, &tc_setclock_mtx, "tcsetc", MTX_SPIN);
1245 * Step our concept of UTC. This is done by modifying our estimate of
1249 tc_setclock(struct timespec *ts)
1251 struct timespec tbef, taft;
1252 struct bintime bt, bt2;
1254 timespec2bintime(ts, &bt);
1256 mtx_lock_spin(&tc_setclock_mtx);
1257 cpu_tick_calibrate(1);
1259 bintime_sub(&bt, &bt2);
1261 /* XXX fiddle all the little crinkly bits around the fiords... */
1263 mtx_unlock_spin(&tc_setclock_mtx);
1265 /* Avoid rtc_generation == 0, since td_rtcgen == 0 is special. */
1266 atomic_add_rel_int(&rtc_generation, 2);
1267 sleepq_chains_remove_matching(sleeping_on_old_rtc);
1268 if (timestepwarnings) {
1271 "Time stepped from %jd.%09ld to %jd.%09ld (%jd.%09ld)\n",
1272 (intmax_t)tbef.tv_sec, tbef.tv_nsec,
1273 (intmax_t)taft.tv_sec, taft.tv_nsec,
1274 (intmax_t)ts->tv_sec, ts->tv_nsec);
1279 * Initialize the next struct timehands in the ring and make
1280 * it the active timehands. Along the way we might switch to a different
1281 * timecounter and/or do seconds processing in NTP. Slightly magic.
1284 tc_windup(struct bintime *new_boottimebin)
1287 struct timehands *th, *tho;
1289 u_int delta, ncount, ogen;
1294 * Make the next timehands a copy of the current one, but do
1295 * not overwrite the generation or next pointer. While we
1296 * update the contents, the generation must be zero. We need
1297 * to ensure that the zero generation is visible before the
1298 * data updates become visible, which requires release fence.
1299 * For similar reasons, re-reading of the generation after the
1300 * data is read should use acquire fence.
1304 ogen = th->th_generation;
1305 th->th_generation = 0;
1306 atomic_thread_fence_rel();
1307 memcpy(th, tho, offsetof(struct timehands, th_generation));
1308 if (new_boottimebin != NULL)
1309 th->th_boottime = *new_boottimebin;
1312 * Capture a timecounter delta on the current timecounter and if
1313 * changing timecounters, a counter value from the new timecounter.
1314 * Update the offset fields accordingly.
1316 delta = tc_delta(th);
1317 if (th->th_counter != timecounter)
1318 ncount = timecounter->tc_get_timecount(timecounter);
1322 ffclock_windup(delta);
1324 th->th_offset_count += delta;
1325 th->th_offset_count &= th->th_counter->tc_counter_mask;
1326 while (delta > th->th_counter->tc_frequency) {
1327 /* Eat complete unadjusted seconds. */
1328 delta -= th->th_counter->tc_frequency;
1329 th->th_offset.sec++;
1331 if ((delta > th->th_counter->tc_frequency / 2) &&
1332 (th->th_scale * delta < ((uint64_t)1 << 63))) {
1333 /* The product th_scale * delta just barely overflows. */
1334 th->th_offset.sec++;
1336 bintime_addx(&th->th_offset, th->th_scale * delta);
1339 * Hardware latching timecounters may not generate interrupts on
1340 * PPS events, so instead we poll them. There is a finite risk that
1341 * the hardware might capture a count which is later than the one we
1342 * got above, and therefore possibly in the next NTP second which might
1343 * have a different rate than the current NTP second. It doesn't
1344 * matter in practice.
1346 if (tho->th_counter->tc_poll_pps)
1347 tho->th_counter->tc_poll_pps(tho->th_counter);
1350 * Deal with NTP second processing. The for loop normally
1351 * iterates at most once, but in extreme situations it might
1352 * keep NTP sane if timeouts are not run for several seconds.
1353 * At boot, the time step can be large when the TOD hardware
1354 * has been read, so on really large steps, we call
1355 * ntp_update_second only twice. We need to call it twice in
1356 * case we missed a leap second.
1359 bintime_add(&bt, &th->th_boottime);
1360 i = bt.sec - tho->th_microtime.tv_sec;
1363 for (; i > 0; i--) {
1365 ntp_update_second(&th->th_adjustment, &bt.sec);
1367 th->th_boottime.sec += bt.sec - t;
1369 /* Update the UTC timestamps used by the get*() functions. */
1370 th->th_bintime = bt;
1371 bintime2timeval(&bt, &th->th_microtime);
1372 bintime2timespec(&bt, &th->th_nanotime);
1374 /* Now is a good time to change timecounters. */
1375 if (th->th_counter != timecounter) {
1377 if ((timecounter->tc_flags & TC_FLAGS_C2STOP) != 0)
1378 cpu_disable_c2_sleep++;
1379 if ((th->th_counter->tc_flags & TC_FLAGS_C2STOP) != 0)
1380 cpu_disable_c2_sleep--;
1382 th->th_counter = timecounter;
1383 th->th_offset_count = ncount;
1384 tc_min_ticktock_freq = max(1, timecounter->tc_frequency /
1385 (((uint64_t)timecounter->tc_counter_mask + 1) / 3));
1387 ffclock_change_tc(th);
1392 * Recalculate the scaling factor. We want the number of 1/2^64
1393 * fractions of a second per period of the hardware counter, taking
1394 * into account the th_adjustment factor which the NTP PLL/adjtime(2)
1395 * processing provides us with.
1397 * The th_adjustment is nanoseconds per second with 32 bit binary
1398 * fraction and we want 64 bit binary fraction of second:
1400 * x = a * 2^32 / 10^9 = a * 4.294967296
1402 * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
1403 * we can only multiply by about 850 without overflowing, that
1404 * leaves no suitably precise fractions for multiply before divide.
1406 * Divide before multiply with a fraction of 2199/512 results in a
1407 * systematic undercompensation of 10PPM of th_adjustment. On a
1408 * 5000PPM adjustment this is a 0.05PPM error. This is acceptable.
1410 * We happily sacrifice the lowest of the 64 bits of our result
1411 * to the goddess of code clarity.
1414 scale = (uint64_t)1 << 63;
1415 scale += (th->th_adjustment / 1024) * 2199;
1416 scale /= th->th_counter->tc_frequency;
1417 th->th_scale = scale * 2;
1418 th->th_large_delta = MIN(((uint64_t)1 << 63) / scale, UINT_MAX);
1421 * Now that the struct timehands is again consistent, set the new
1422 * generation number, making sure to not make it zero.
1426 atomic_store_rel_int(&th->th_generation, ogen);
1428 /* Go live with the new struct timehands. */
1430 switch (sysclock_active) {
1433 time_second = th->th_microtime.tv_sec;
1434 time_uptime = th->th_offset.sec;
1438 time_second = fftimehands->tick_time_lerp.sec;
1439 time_uptime = fftimehands->tick_time_lerp.sec - ffclock_boottime.sec;
1445 timekeep_push_vdso();
1448 /* Report or change the active timecounter hardware. */
1450 sysctl_kern_timecounter_hardware(SYSCTL_HANDLER_ARGS)
1453 struct timecounter *newtc, *tc;
1457 strlcpy(newname, tc->tc_name, sizeof(newname));
1459 error = sysctl_handle_string(oidp, &newname[0], sizeof(newname), req);
1460 if (error != 0 || req->newptr == NULL)
1462 /* Record that the tc in use now was specifically chosen. */
1464 if (strcmp(newname, tc->tc_name) == 0)
1466 for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
1467 if (strcmp(newname, newtc->tc_name) != 0)
1470 /* Warm up new timecounter. */
1471 (void)newtc->tc_get_timecount(newtc);
1472 (void)newtc->tc_get_timecount(newtc);
1474 timecounter = newtc;
1477 * The vdso timehands update is deferred until the next
1480 * This is prudent given that 'timekeep_push_vdso()' does not
1481 * use any locking and that it can be called in hard interrupt
1482 * context via 'tc_windup()'.
1489 SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware,
1490 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 0,
1491 sysctl_kern_timecounter_hardware, "A",
1492 "Timecounter hardware selected");
1494 /* Report the available timecounter hardware. */
1496 sysctl_kern_timecounter_choice(SYSCTL_HANDLER_ARGS)
1499 struct timecounter *tc;
1502 sbuf_new_for_sysctl(&sb, NULL, 0, req);
1503 for (tc = timecounters; tc != NULL; tc = tc->tc_next) {
1504 if (tc != timecounters)
1505 sbuf_putc(&sb, ' ');
1506 sbuf_printf(&sb, "%s(%d)", tc->tc_name, tc->tc_quality);
1508 error = sbuf_finish(&sb);
1513 SYSCTL_PROC(_kern_timecounter, OID_AUTO, choice,
1514 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, 0, 0,
1515 sysctl_kern_timecounter_choice, "A",
1516 "Timecounter hardware detected");
1519 * RFC 2783 PPS-API implementation.
1523 * Return true if the driver is aware of the abi version extensions in the
1524 * pps_state structure, and it supports at least the given abi version number.
1527 abi_aware(struct pps_state *pps, int vers)
1530 return ((pps->kcmode & KCMODE_ABIFLAG) && pps->driver_abi >= vers);
1534 pps_fetch(struct pps_fetch_args *fapi, struct pps_state *pps)
1537 pps_seq_t aseq, cseq;
1540 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1544 * If no timeout is requested, immediately return whatever values were
1545 * most recently captured. If timeout seconds is -1, that's a request
1546 * to block without a timeout. WITNESS won't let us sleep forever
1547 * without a lock (we really don't need a lock), so just repeatedly
1548 * sleep a long time.
1550 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec) {
1551 if (fapi->timeout.tv_sec == -1)
1554 tv.tv_sec = fapi->timeout.tv_sec;
1555 tv.tv_usec = fapi->timeout.tv_nsec / 1000;
1558 aseq = atomic_load_int(&pps->ppsinfo.assert_sequence);
1559 cseq = atomic_load_int(&pps->ppsinfo.clear_sequence);
1560 while (aseq == atomic_load_int(&pps->ppsinfo.assert_sequence) &&
1561 cseq == atomic_load_int(&pps->ppsinfo.clear_sequence)) {
1562 if (abi_aware(pps, 1) && pps->driver_mtx != NULL) {
1563 if (pps->flags & PPSFLAG_MTX_SPIN) {
1564 err = msleep_spin(pps, pps->driver_mtx,
1567 err = msleep(pps, pps->driver_mtx, PCATCH,
1571 err = tsleep(pps, PCATCH, "ppsfch", timo);
1573 if (err == EWOULDBLOCK) {
1574 if (fapi->timeout.tv_sec == -1) {
1579 } else if (err != 0) {
1585 pps->ppsinfo.current_mode = pps->ppsparam.mode;
1586 fapi->pps_info_buf = pps->ppsinfo;
1592 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
1595 struct pps_fetch_args *fapi;
1597 struct pps_fetch_ffc_args *fapi_ffc;
1600 struct pps_kcbind_args *kapi;
1603 KASSERT(pps != NULL, ("NULL pps pointer in pps_ioctl"));
1605 case PPS_IOC_CREATE:
1607 case PPS_IOC_DESTROY:
1609 case PPS_IOC_SETPARAMS:
1610 app = (pps_params_t *)data;
1611 if (app->mode & ~pps->ppscap)
1614 /* Ensure only a single clock is selected for ffc timestamp. */
1615 if ((app->mode & PPS_TSCLK_MASK) == PPS_TSCLK_MASK)
1618 pps->ppsparam = *app;
1620 case PPS_IOC_GETPARAMS:
1621 app = (pps_params_t *)data;
1622 *app = pps->ppsparam;
1623 app->api_version = PPS_API_VERS_1;
1625 case PPS_IOC_GETCAP:
1626 *(int*)data = pps->ppscap;
1629 fapi = (struct pps_fetch_args *)data;
1630 return (pps_fetch(fapi, pps));
1632 case PPS_IOC_FETCH_FFCOUNTER:
1633 fapi_ffc = (struct pps_fetch_ffc_args *)data;
1634 if (fapi_ffc->tsformat && fapi_ffc->tsformat !=
1637 if (fapi_ffc->timeout.tv_sec || fapi_ffc->timeout.tv_nsec)
1638 return (EOPNOTSUPP);
1639 pps->ppsinfo_ffc.current_mode = pps->ppsparam.mode;
1640 fapi_ffc->pps_info_buf_ffc = pps->ppsinfo_ffc;
1641 /* Overwrite timestamps if feedback clock selected. */
1642 switch (pps->ppsparam.mode & PPS_TSCLK_MASK) {
1643 case PPS_TSCLK_FBCK:
1644 fapi_ffc->pps_info_buf_ffc.assert_timestamp =
1645 pps->ppsinfo.assert_timestamp;
1646 fapi_ffc->pps_info_buf_ffc.clear_timestamp =
1647 pps->ppsinfo.clear_timestamp;
1649 case PPS_TSCLK_FFWD:
1655 #endif /* FFCLOCK */
1656 case PPS_IOC_KCBIND:
1658 kapi = (struct pps_kcbind_args *)data;
1659 /* XXX Only root should be able to do this */
1660 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1662 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1664 if (kapi->edge & ~pps->ppscap)
1666 pps->kcmode = (kapi->edge & KCMODE_EDGEMASK) |
1667 (pps->kcmode & KCMODE_ABIFLAG);
1670 return (EOPNOTSUPP);
1678 pps_init(struct pps_state *pps)
1680 pps->ppscap |= PPS_TSFMT_TSPEC | PPS_CANWAIT;
1681 if (pps->ppscap & PPS_CAPTUREASSERT)
1682 pps->ppscap |= PPS_OFFSETASSERT;
1683 if (pps->ppscap & PPS_CAPTURECLEAR)
1684 pps->ppscap |= PPS_OFFSETCLEAR;
1686 pps->ppscap |= PPS_TSCLK_MASK;
1688 pps->kcmode &= ~KCMODE_ABIFLAG;
1692 pps_init_abi(struct pps_state *pps)
1696 if (pps->driver_abi > 0) {
1697 pps->kcmode |= KCMODE_ABIFLAG;
1698 pps->kernel_abi = PPS_ABI_VERSION;
1703 pps_capture(struct pps_state *pps)
1705 struct timehands *th;
1707 KASSERT(pps != NULL, ("NULL pps pointer in pps_capture"));
1709 pps->capgen = atomic_load_acq_int(&th->th_generation);
1712 pps->capffth = fftimehands;
1714 pps->capcount = th->th_counter->tc_get_timecount(th->th_counter);
1715 atomic_thread_fence_acq();
1716 if (pps->capgen != th->th_generation)
1721 pps_event(struct pps_state *pps, int event)
1724 struct timespec ts, *tsp, *osp;
1725 u_int tcount, *pcount;
1729 struct timespec *tsp_ffc;
1730 pps_seq_t *pseq_ffc;
1737 KASSERT(pps != NULL, ("NULL pps pointer in pps_event"));
1738 /* Nothing to do if not currently set to capture this event type. */
1739 if ((event & pps->ppsparam.mode) == 0)
1741 /* If the timecounter was wound up underneath us, bail out. */
1742 if (pps->capgen == 0 || pps->capgen !=
1743 atomic_load_acq_int(&pps->capth->th_generation))
1746 /* Things would be easier with arrays. */
1747 if (event == PPS_CAPTUREASSERT) {
1748 tsp = &pps->ppsinfo.assert_timestamp;
1749 osp = &pps->ppsparam.assert_offset;
1750 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1752 fhard = pps->kcmode & PPS_CAPTUREASSERT;
1754 pcount = &pps->ppscount[0];
1755 pseq = &pps->ppsinfo.assert_sequence;
1757 ffcount = &pps->ppsinfo_ffc.assert_ffcount;
1758 tsp_ffc = &pps->ppsinfo_ffc.assert_timestamp;
1759 pseq_ffc = &pps->ppsinfo_ffc.assert_sequence;
1762 tsp = &pps->ppsinfo.clear_timestamp;
1763 osp = &pps->ppsparam.clear_offset;
1764 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1766 fhard = pps->kcmode & PPS_CAPTURECLEAR;
1768 pcount = &pps->ppscount[1];
1769 pseq = &pps->ppsinfo.clear_sequence;
1771 ffcount = &pps->ppsinfo_ffc.clear_ffcount;
1772 tsp_ffc = &pps->ppsinfo_ffc.clear_timestamp;
1773 pseq_ffc = &pps->ppsinfo_ffc.clear_sequence;
1778 * If the timecounter changed, we cannot compare the count values, so
1779 * we have to drop the rest of the PPS-stuff until the next event.
1781 if (pps->ppstc != pps->capth->th_counter) {
1782 pps->ppstc = pps->capth->th_counter;
1783 *pcount = pps->capcount;
1784 pps->ppscount[2] = pps->capcount;
1788 /* Convert the count to a timespec. */
1789 tcount = pps->capcount - pps->capth->th_offset_count;
1790 tcount &= pps->capth->th_counter->tc_counter_mask;
1791 bt = pps->capth->th_bintime;
1792 bintime_addx(&bt, pps->capth->th_scale * tcount);
1793 bintime2timespec(&bt, &ts);
1795 /* If the timecounter was wound up underneath us, bail out. */
1796 atomic_thread_fence_acq();
1797 if (pps->capgen != pps->capth->th_generation)
1800 *pcount = pps->capcount;
1805 timespecadd(tsp, osp, tsp);
1806 if (tsp->tv_nsec < 0) {
1807 tsp->tv_nsec += 1000000000;
1813 *ffcount = pps->capffth->tick_ffcount + tcount;
1814 bt = pps->capffth->tick_time;
1815 ffclock_convert_delta(tcount, pps->capffth->cest.period, &bt);
1816 bintime_add(&bt, &pps->capffth->tick_time);
1817 bintime2timespec(&bt, &ts);
1827 * Feed the NTP PLL/FLL.
1828 * The FLL wants to know how many (hardware) nanoseconds
1829 * elapsed since the previous event.
1831 tcount = pps->capcount - pps->ppscount[2];
1832 pps->ppscount[2] = pps->capcount;
1833 tcount &= pps->capth->th_counter->tc_counter_mask;
1834 scale = (uint64_t)1 << 63;
1835 scale /= pps->capth->th_counter->tc_frequency;
1839 bintime_addx(&bt, scale * tcount);
1840 bintime2timespec(&bt, &ts);
1841 hardpps(tsp, ts.tv_nsec + 1000000000 * ts.tv_sec);
1845 /* Wakeup anyone sleeping in pps_fetch(). */
1850 * Timecounters need to be updated every so often to prevent the hardware
1851 * counter from overflowing. Updating also recalculates the cached values
1852 * used by the get*() family of functions, so their precision depends on
1853 * the update frequency.
1857 SYSCTL_INT(_kern_timecounter, OID_AUTO, tick, CTLFLAG_RD, &tc_tick, 0,
1858 "Approximate number of hardclock ticks in a millisecond");
1861 tc_ticktock(int cnt)
1865 if (mtx_trylock_spin(&tc_setclock_mtx)) {
1867 if (count >= tc_tick) {
1871 mtx_unlock_spin(&tc_setclock_mtx);
1875 static void __inline
1876 tc_adjprecision(void)
1880 if (tc_timepercentage > 0) {
1881 t = (99 + tc_timepercentage) / tc_timepercentage;
1882 tc_precexp = fls(t + (t >> 1)) - 1;
1883 FREQ2BT(hz / tc_tick, &bt_timethreshold);
1884 FREQ2BT(hz, &bt_tickthreshold);
1885 bintime_shift(&bt_timethreshold, tc_precexp);
1886 bintime_shift(&bt_tickthreshold, tc_precexp);
1889 bt_timethreshold.sec = INT_MAX;
1890 bt_timethreshold.frac = ~(uint64_t)0;
1891 bt_tickthreshold = bt_timethreshold;
1893 sbt_timethreshold = bttosbt(bt_timethreshold);
1894 sbt_tickthreshold = bttosbt(bt_tickthreshold);
1898 sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS)
1902 val = tc_timepercentage;
1903 error = sysctl_handle_int(oidp, &val, 0, req);
1904 if (error != 0 || req->newptr == NULL)
1906 tc_timepercentage = val;
1914 /* Set up the requested number of timehands. */
1916 inittimehands(void *dummy)
1918 struct timehands *thp;
1921 TUNABLE_INT_FETCH("kern.timecounter.timehands_count",
1923 if (timehands_count < 1)
1924 timehands_count = 1;
1925 if (timehands_count > nitems(ths))
1926 timehands_count = nitems(ths);
1927 for (i = 1, thp = &ths[0]; i < timehands_count; thp = &ths[i++])
1928 thp->th_next = &ths[i];
1929 thp->th_next = &ths[0];
1931 SYSINIT(timehands, SI_SUB_TUNABLES, SI_ORDER_ANY, inittimehands, NULL);
1934 inittimecounter(void *dummy)
1940 * Set the initial timeout to
1941 * max(1, <approx. number of hardclock ticks in a millisecond>).
1942 * People should probably not use the sysctl to set the timeout
1943 * to smaller than its initial value, since that value is the
1944 * smallest reasonable one. If they want better timestamps they
1945 * should use the non-"get"* functions.
1948 tc_tick = (hz + 500) / 1000;
1952 FREQ2BT(hz, &tick_bt);
1953 tick_sbt = bttosbt(tick_bt);
1954 tick_rate = hz / tc_tick;
1955 FREQ2BT(tick_rate, &tc_tick_bt);
1956 tc_tick_sbt = bttosbt(tc_tick_bt);
1957 p = (tc_tick * 1000000) / hz;
1958 printf("Timecounters tick every %d.%03u msec\n", p / 1000, p % 1000);
1964 /* warm up new timecounter (again) and get rolling. */
1965 (void)timecounter->tc_get_timecount(timecounter);
1966 (void)timecounter->tc_get_timecount(timecounter);
1967 mtx_lock_spin(&tc_setclock_mtx);
1969 mtx_unlock_spin(&tc_setclock_mtx);
1972 SYSINIT(timecounter, SI_SUB_CLOCKS, SI_ORDER_SECOND, inittimecounter, NULL);
1974 /* Cpu tick handling -------------------------------------------------*/
1976 static int cpu_tick_variable;
1977 static uint64_t cpu_tick_frequency;
1979 DPCPU_DEFINE_STATIC(uint64_t, tc_cpu_ticks_base);
1980 DPCPU_DEFINE_STATIC(unsigned, tc_cpu_ticks_last);
1985 struct timecounter *tc;
1986 uint64_t res, *base;
1990 base = DPCPU_PTR(tc_cpu_ticks_base);
1991 last = DPCPU_PTR(tc_cpu_ticks_last);
1992 tc = timehands->th_counter;
1993 u = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
1995 *base += (uint64_t)tc->tc_counter_mask + 1;
2003 cpu_tick_calibration(void)
2005 static time_t last_calib;
2007 if (time_uptime != last_calib && !(time_uptime & 0xf)) {
2008 cpu_tick_calibrate(0);
2009 last_calib = time_uptime;
2014 * This function gets called every 16 seconds on only one designated
2015 * CPU in the system from hardclock() via cpu_tick_calibration()().
2017 * Whenever the real time clock is stepped we get called with reset=1
2018 * to make sure we handle suspend/resume and similar events correctly.
2022 cpu_tick_calibrate(int reset)
2024 static uint64_t c_last;
2025 uint64_t c_this, c_delta;
2026 static struct bintime t_last;
2027 struct bintime t_this, t_delta;
2031 /* The clock was stepped, abort & reset */
2036 /* we don't calibrate fixed rate cputicks */
2037 if (!cpu_tick_variable)
2040 getbinuptime(&t_this);
2041 c_this = cpu_ticks();
2042 if (t_last.sec != 0) {
2043 c_delta = c_this - c_last;
2045 bintime_sub(&t_delta, &t_last);
2048 * 2^(64-20) / 16[s] =
2050 * 17.592.186.044.416 / 16 =
2051 * 1.099.511.627.776 [Hz]
2053 divi = t_delta.sec << 20;
2054 divi |= t_delta.frac >> (64 - 20);
2057 if (c_delta > cpu_tick_frequency) {
2058 if (0 && bootverbose)
2059 printf("cpu_tick increased to %ju Hz\n",
2061 cpu_tick_frequency = c_delta;
2069 set_cputicker(cpu_tick_f *func, uint64_t freq, unsigned var)
2073 cpu_ticks = tc_cpu_ticks;
2075 cpu_tick_frequency = freq;
2076 cpu_tick_variable = var;
2085 if (cpu_ticks == tc_cpu_ticks)
2086 return (tc_getfrequency());
2087 return (cpu_tick_frequency);
2091 * We need to be slightly careful converting cputicks to microseconds.
2092 * There is plenty of margin in 64 bits of microseconds (half a million
2093 * years) and in 64 bits at 4 GHz (146 years), but if we do a multiply
2094 * before divide conversion (to retain precision) we find that the
2095 * margin shrinks to 1.5 hours (one millionth of 146y).
2096 * With a three prong approach we never lose significant bits, no
2097 * matter what the cputick rate and length of timeinterval is.
2101 cputick2usec(uint64_t tick)
2104 if (tick > 18446744073709551LL) /* floor(2^64 / 1000) */
2105 return (tick / (cpu_tickrate() / 1000000LL));
2106 else if (tick > 18446744073709LL) /* floor(2^64 / 1000000) */
2107 return ((tick * 1000LL) / (cpu_tickrate() / 1000LL));
2109 return ((tick * 1000000LL) / cpu_tickrate());
2112 cpu_tick_f *cpu_ticks = tc_cpu_ticks;
2114 static int vdso_th_enable = 1;
2116 sysctl_fast_gettime(SYSCTL_HANDLER_ARGS)
2118 int old_vdso_th_enable, error;
2120 old_vdso_th_enable = vdso_th_enable;
2121 error = sysctl_handle_int(oidp, &old_vdso_th_enable, 0, req);
2124 vdso_th_enable = old_vdso_th_enable;
2127 SYSCTL_PROC(_kern_timecounter, OID_AUTO, fast_gettime,
2128 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
2129 NULL, 0, sysctl_fast_gettime, "I", "Enable fast time of day");
2132 tc_fill_vdso_timehands(struct vdso_timehands *vdso_th)
2134 struct timehands *th;
2138 vdso_th->th_scale = th->th_scale;
2139 vdso_th->th_offset_count = th->th_offset_count;
2140 vdso_th->th_counter_mask = th->th_counter->tc_counter_mask;
2141 vdso_th->th_offset = th->th_offset;
2142 vdso_th->th_boottime = th->th_boottime;
2143 if (th->th_counter->tc_fill_vdso_timehands != NULL) {
2144 enabled = th->th_counter->tc_fill_vdso_timehands(vdso_th,
2148 if (!vdso_th_enable)
2153 #ifdef COMPAT_FREEBSD32
2155 tc_fill_vdso_timehands32(struct vdso_timehands32 *vdso_th32)
2157 struct timehands *th;
2161 *(uint64_t *)&vdso_th32->th_scale[0] = th->th_scale;
2162 vdso_th32->th_offset_count = th->th_offset_count;
2163 vdso_th32->th_counter_mask = th->th_counter->tc_counter_mask;
2164 vdso_th32->th_offset.sec = th->th_offset.sec;
2165 *(uint64_t *)&vdso_th32->th_offset.frac[0] = th->th_offset.frac;
2166 vdso_th32->th_boottime.sec = th->th_boottime.sec;
2167 *(uint64_t *)&vdso_th32->th_boottime.frac[0] = th->th_boottime.frac;
2168 if (th->th_counter->tc_fill_vdso_timehands32 != NULL) {
2169 enabled = th->th_counter->tc_fill_vdso_timehands32(vdso_th32,
2173 if (!vdso_th_enable)