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);
1212 /* Report the frequency of the current timecounter. */
1214 tc_getfrequency(void)
1217 return (timehands->th_counter->tc_frequency);
1221 sleeping_on_old_rtc(struct thread *td)
1225 * td_rtcgen is modified by curthread when it is running,
1226 * and by other threads in this function. By finding the thread
1227 * on a sleepqueue and holding the lock on the sleepqueue
1228 * chain, we guarantee that the thread is not running and that
1229 * modifying td_rtcgen is safe. Setting td_rtcgen to zero informs
1230 * the thread that it was woken due to a real-time clock adjustment.
1231 * (The declaration of td_rtcgen refers to this comment.)
1233 if (td->td_rtcgen != 0 && td->td_rtcgen != rtc_generation) {
1240 static struct mtx tc_setclock_mtx;
1241 MTX_SYSINIT(tc_setclock_init, &tc_setclock_mtx, "tcsetc", MTX_SPIN);
1244 * Step our concept of UTC. This is done by modifying our estimate of
1248 tc_setclock(struct timespec *ts)
1250 struct timespec tbef, taft;
1251 struct bintime bt, bt2;
1253 timespec2bintime(ts, &bt);
1255 mtx_lock_spin(&tc_setclock_mtx);
1256 cpu_tick_calibrate(1);
1258 bintime_sub(&bt, &bt2);
1260 /* XXX fiddle all the little crinkly bits around the fiords... */
1262 mtx_unlock_spin(&tc_setclock_mtx);
1264 /* Avoid rtc_generation == 0, since td_rtcgen == 0 is special. */
1265 atomic_add_rel_int(&rtc_generation, 2);
1266 sleepq_chains_remove_matching(sleeping_on_old_rtc);
1267 if (timestepwarnings) {
1270 "Time stepped from %jd.%09ld to %jd.%09ld (%jd.%09ld)\n",
1271 (intmax_t)tbef.tv_sec, tbef.tv_nsec,
1272 (intmax_t)taft.tv_sec, taft.tv_nsec,
1273 (intmax_t)ts->tv_sec, ts->tv_nsec);
1278 * Initialize the next struct timehands in the ring and make
1279 * it the active timehands. Along the way we might switch to a different
1280 * timecounter and/or do seconds processing in NTP. Slightly magic.
1283 tc_windup(struct bintime *new_boottimebin)
1286 struct timehands *th, *tho;
1288 u_int delta, ncount, ogen;
1293 * Make the next timehands a copy of the current one, but do
1294 * not overwrite the generation or next pointer. While we
1295 * update the contents, the generation must be zero. We need
1296 * to ensure that the zero generation is visible before the
1297 * data updates become visible, which requires release fence.
1298 * For similar reasons, re-reading of the generation after the
1299 * data is read should use acquire fence.
1303 ogen = th->th_generation;
1304 th->th_generation = 0;
1305 atomic_thread_fence_rel();
1306 memcpy(th, tho, offsetof(struct timehands, th_generation));
1307 if (new_boottimebin != NULL)
1308 th->th_boottime = *new_boottimebin;
1311 * Capture a timecounter delta on the current timecounter and if
1312 * changing timecounters, a counter value from the new timecounter.
1313 * Update the offset fields accordingly.
1315 delta = tc_delta(th);
1316 if (th->th_counter != timecounter)
1317 ncount = timecounter->tc_get_timecount(timecounter);
1321 ffclock_windup(delta);
1323 th->th_offset_count += delta;
1324 th->th_offset_count &= th->th_counter->tc_counter_mask;
1325 while (delta > th->th_counter->tc_frequency) {
1326 /* Eat complete unadjusted seconds. */
1327 delta -= th->th_counter->tc_frequency;
1328 th->th_offset.sec++;
1330 if ((delta > th->th_counter->tc_frequency / 2) &&
1331 (th->th_scale * delta < ((uint64_t)1 << 63))) {
1332 /* The product th_scale * delta just barely overflows. */
1333 th->th_offset.sec++;
1335 bintime_addx(&th->th_offset, th->th_scale * delta);
1338 * Hardware latching timecounters may not generate interrupts on
1339 * PPS events, so instead we poll them. There is a finite risk that
1340 * the hardware might capture a count which is later than the one we
1341 * got above, and therefore possibly in the next NTP second which might
1342 * have a different rate than the current NTP second. It doesn't
1343 * matter in practice.
1345 if (tho->th_counter->tc_poll_pps)
1346 tho->th_counter->tc_poll_pps(tho->th_counter);
1349 * Deal with NTP second processing. The for loop normally
1350 * iterates at most once, but in extreme situations it might
1351 * keep NTP sane if timeouts are not run for several seconds.
1352 * At boot, the time step can be large when the TOD hardware
1353 * has been read, so on really large steps, we call
1354 * ntp_update_second only twice. We need to call it twice in
1355 * case we missed a leap second.
1358 bintime_add(&bt, &th->th_boottime);
1359 i = bt.sec - tho->th_microtime.tv_sec;
1362 for (; i > 0; i--) {
1364 ntp_update_second(&th->th_adjustment, &bt.sec);
1366 th->th_boottime.sec += bt.sec - t;
1368 /* Update the UTC timestamps used by the get*() functions. */
1369 th->th_bintime = bt;
1370 bintime2timeval(&bt, &th->th_microtime);
1371 bintime2timespec(&bt, &th->th_nanotime);
1373 /* Now is a good time to change timecounters. */
1374 if (th->th_counter != timecounter) {
1376 if ((timecounter->tc_flags & TC_FLAGS_C2STOP) != 0)
1377 cpu_disable_c2_sleep++;
1378 if ((th->th_counter->tc_flags & TC_FLAGS_C2STOP) != 0)
1379 cpu_disable_c2_sleep--;
1381 th->th_counter = timecounter;
1382 th->th_offset_count = ncount;
1383 tc_min_ticktock_freq = max(1, timecounter->tc_frequency /
1384 (((uint64_t)timecounter->tc_counter_mask + 1) / 3));
1386 ffclock_change_tc(th);
1391 * Recalculate the scaling factor. We want the number of 1/2^64
1392 * fractions of a second per period of the hardware counter, taking
1393 * into account the th_adjustment factor which the NTP PLL/adjtime(2)
1394 * processing provides us with.
1396 * The th_adjustment is nanoseconds per second with 32 bit binary
1397 * fraction and we want 64 bit binary fraction of second:
1399 * x = a * 2^32 / 10^9 = a * 4.294967296
1401 * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
1402 * we can only multiply by about 850 without overflowing, that
1403 * leaves no suitably precise fractions for multiply before divide.
1405 * Divide before multiply with a fraction of 2199/512 results in a
1406 * systematic undercompensation of 10PPM of th_adjustment. On a
1407 * 5000PPM adjustment this is a 0.05PPM error. This is acceptable.
1409 * We happily sacrifice the lowest of the 64 bits of our result
1410 * to the goddess of code clarity.
1413 scale = (uint64_t)1 << 63;
1414 scale += (th->th_adjustment / 1024) * 2199;
1415 scale /= th->th_counter->tc_frequency;
1416 th->th_scale = scale * 2;
1417 th->th_large_delta = MIN(((uint64_t)1 << 63) / scale, UINT_MAX);
1420 * Now that the struct timehands is again consistent, set the new
1421 * generation number, making sure to not make it zero.
1425 atomic_store_rel_int(&th->th_generation, ogen);
1427 /* Go live with the new struct timehands. */
1429 switch (sysclock_active) {
1432 time_second = th->th_microtime.tv_sec;
1433 time_uptime = th->th_offset.sec;
1437 time_second = fftimehands->tick_time_lerp.sec;
1438 time_uptime = fftimehands->tick_time_lerp.sec - ffclock_boottime.sec;
1444 timekeep_push_vdso();
1447 /* Report or change the active timecounter hardware. */
1449 sysctl_kern_timecounter_hardware(SYSCTL_HANDLER_ARGS)
1452 struct timecounter *newtc, *tc;
1456 strlcpy(newname, tc->tc_name, sizeof(newname));
1458 error = sysctl_handle_string(oidp, &newname[0], sizeof(newname), req);
1459 if (error != 0 || req->newptr == NULL)
1461 /* Record that the tc in use now was specifically chosen. */
1463 if (strcmp(newname, tc->tc_name) == 0)
1465 for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
1466 if (strcmp(newname, newtc->tc_name) != 0)
1469 /* Warm up new timecounter. */
1470 (void)newtc->tc_get_timecount(newtc);
1472 timecounter = newtc;
1475 * The vdso timehands update is deferred until the next
1478 * This is prudent given that 'timekeep_push_vdso()' does not
1479 * use any locking and that it can be called in hard interrupt
1480 * context via 'tc_windup()'.
1487 SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware,
1488 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 0,
1489 sysctl_kern_timecounter_hardware, "A",
1490 "Timecounter hardware selected");
1492 /* Report the available timecounter hardware. */
1494 sysctl_kern_timecounter_choice(SYSCTL_HANDLER_ARGS)
1497 struct timecounter *tc;
1500 sbuf_new_for_sysctl(&sb, NULL, 0, req);
1501 for (tc = timecounters; tc != NULL; tc = tc->tc_next) {
1502 if (tc != timecounters)
1503 sbuf_putc(&sb, ' ');
1504 sbuf_printf(&sb, "%s(%d)", tc->tc_name, tc->tc_quality);
1506 error = sbuf_finish(&sb);
1511 SYSCTL_PROC(_kern_timecounter, OID_AUTO, choice,
1512 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, 0, 0,
1513 sysctl_kern_timecounter_choice, "A",
1514 "Timecounter hardware detected");
1517 * RFC 2783 PPS-API implementation.
1521 * Return true if the driver is aware of the abi version extensions in the
1522 * pps_state structure, and it supports at least the given abi version number.
1525 abi_aware(struct pps_state *pps, int vers)
1528 return ((pps->kcmode & KCMODE_ABIFLAG) && pps->driver_abi >= vers);
1532 pps_fetch(struct pps_fetch_args *fapi, struct pps_state *pps)
1535 pps_seq_t aseq, cseq;
1538 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1542 * If no timeout is requested, immediately return whatever values were
1543 * most recently captured. If timeout seconds is -1, that's a request
1544 * to block without a timeout. WITNESS won't let us sleep forever
1545 * without a lock (we really don't need a lock), so just repeatedly
1546 * sleep a long time.
1548 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec) {
1549 if (fapi->timeout.tv_sec == -1)
1552 tv.tv_sec = fapi->timeout.tv_sec;
1553 tv.tv_usec = fapi->timeout.tv_nsec / 1000;
1556 aseq = atomic_load_int(&pps->ppsinfo.assert_sequence);
1557 cseq = atomic_load_int(&pps->ppsinfo.clear_sequence);
1558 while (aseq == atomic_load_int(&pps->ppsinfo.assert_sequence) &&
1559 cseq == atomic_load_int(&pps->ppsinfo.clear_sequence)) {
1560 if (abi_aware(pps, 1) && pps->driver_mtx != NULL) {
1561 if (pps->flags & PPSFLAG_MTX_SPIN) {
1562 err = msleep_spin(pps, pps->driver_mtx,
1565 err = msleep(pps, pps->driver_mtx, PCATCH,
1569 err = tsleep(pps, PCATCH, "ppsfch", timo);
1571 if (err == EWOULDBLOCK) {
1572 if (fapi->timeout.tv_sec == -1) {
1577 } else if (err != 0) {
1583 pps->ppsinfo.current_mode = pps->ppsparam.mode;
1584 fapi->pps_info_buf = pps->ppsinfo;
1590 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
1593 struct pps_fetch_args *fapi;
1595 struct pps_fetch_ffc_args *fapi_ffc;
1598 struct pps_kcbind_args *kapi;
1601 KASSERT(pps != NULL, ("NULL pps pointer in pps_ioctl"));
1603 case PPS_IOC_CREATE:
1605 case PPS_IOC_DESTROY:
1607 case PPS_IOC_SETPARAMS:
1608 app = (pps_params_t *)data;
1609 if (app->mode & ~pps->ppscap)
1612 /* Ensure only a single clock is selected for ffc timestamp. */
1613 if ((app->mode & PPS_TSCLK_MASK) == PPS_TSCLK_MASK)
1616 pps->ppsparam = *app;
1618 case PPS_IOC_GETPARAMS:
1619 app = (pps_params_t *)data;
1620 *app = pps->ppsparam;
1621 app->api_version = PPS_API_VERS_1;
1623 case PPS_IOC_GETCAP:
1624 *(int*)data = pps->ppscap;
1627 fapi = (struct pps_fetch_args *)data;
1628 return (pps_fetch(fapi, pps));
1630 case PPS_IOC_FETCH_FFCOUNTER:
1631 fapi_ffc = (struct pps_fetch_ffc_args *)data;
1632 if (fapi_ffc->tsformat && fapi_ffc->tsformat !=
1635 if (fapi_ffc->timeout.tv_sec || fapi_ffc->timeout.tv_nsec)
1636 return (EOPNOTSUPP);
1637 pps->ppsinfo_ffc.current_mode = pps->ppsparam.mode;
1638 fapi_ffc->pps_info_buf_ffc = pps->ppsinfo_ffc;
1639 /* Overwrite timestamps if feedback clock selected. */
1640 switch (pps->ppsparam.mode & PPS_TSCLK_MASK) {
1641 case PPS_TSCLK_FBCK:
1642 fapi_ffc->pps_info_buf_ffc.assert_timestamp =
1643 pps->ppsinfo.assert_timestamp;
1644 fapi_ffc->pps_info_buf_ffc.clear_timestamp =
1645 pps->ppsinfo.clear_timestamp;
1647 case PPS_TSCLK_FFWD:
1653 #endif /* FFCLOCK */
1654 case PPS_IOC_KCBIND:
1656 kapi = (struct pps_kcbind_args *)data;
1657 /* XXX Only root should be able to do this */
1658 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1660 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1662 if (kapi->edge & ~pps->ppscap)
1664 pps->kcmode = (kapi->edge & KCMODE_EDGEMASK) |
1665 (pps->kcmode & KCMODE_ABIFLAG);
1668 return (EOPNOTSUPP);
1676 pps_init(struct pps_state *pps)
1678 pps->ppscap |= PPS_TSFMT_TSPEC | PPS_CANWAIT;
1679 if (pps->ppscap & PPS_CAPTUREASSERT)
1680 pps->ppscap |= PPS_OFFSETASSERT;
1681 if (pps->ppscap & PPS_CAPTURECLEAR)
1682 pps->ppscap |= PPS_OFFSETCLEAR;
1684 pps->ppscap |= PPS_TSCLK_MASK;
1686 pps->kcmode &= ~KCMODE_ABIFLAG;
1690 pps_init_abi(struct pps_state *pps)
1694 if (pps->driver_abi > 0) {
1695 pps->kcmode |= KCMODE_ABIFLAG;
1696 pps->kernel_abi = PPS_ABI_VERSION;
1701 pps_capture(struct pps_state *pps)
1703 struct timehands *th;
1705 KASSERT(pps != NULL, ("NULL pps pointer in pps_capture"));
1707 pps->capgen = atomic_load_acq_int(&th->th_generation);
1710 pps->capffth = fftimehands;
1712 pps->capcount = th->th_counter->tc_get_timecount(th->th_counter);
1713 atomic_thread_fence_acq();
1714 if (pps->capgen != th->th_generation)
1719 pps_event(struct pps_state *pps, int event)
1722 struct timespec ts, *tsp, *osp;
1723 u_int tcount, *pcount;
1727 struct timespec *tsp_ffc;
1728 pps_seq_t *pseq_ffc;
1735 KASSERT(pps != NULL, ("NULL pps pointer in pps_event"));
1736 /* Nothing to do if not currently set to capture this event type. */
1737 if ((event & pps->ppsparam.mode) == 0)
1739 /* If the timecounter was wound up underneath us, bail out. */
1740 if (pps->capgen == 0 || pps->capgen !=
1741 atomic_load_acq_int(&pps->capth->th_generation))
1744 /* Things would be easier with arrays. */
1745 if (event == PPS_CAPTUREASSERT) {
1746 tsp = &pps->ppsinfo.assert_timestamp;
1747 osp = &pps->ppsparam.assert_offset;
1748 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1750 fhard = pps->kcmode & PPS_CAPTUREASSERT;
1752 pcount = &pps->ppscount[0];
1753 pseq = &pps->ppsinfo.assert_sequence;
1755 ffcount = &pps->ppsinfo_ffc.assert_ffcount;
1756 tsp_ffc = &pps->ppsinfo_ffc.assert_timestamp;
1757 pseq_ffc = &pps->ppsinfo_ffc.assert_sequence;
1760 tsp = &pps->ppsinfo.clear_timestamp;
1761 osp = &pps->ppsparam.clear_offset;
1762 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1764 fhard = pps->kcmode & PPS_CAPTURECLEAR;
1766 pcount = &pps->ppscount[1];
1767 pseq = &pps->ppsinfo.clear_sequence;
1769 ffcount = &pps->ppsinfo_ffc.clear_ffcount;
1770 tsp_ffc = &pps->ppsinfo_ffc.clear_timestamp;
1771 pseq_ffc = &pps->ppsinfo_ffc.clear_sequence;
1776 * If the timecounter changed, we cannot compare the count values, so
1777 * we have to drop the rest of the PPS-stuff until the next event.
1779 if (pps->ppstc != pps->capth->th_counter) {
1780 pps->ppstc = pps->capth->th_counter;
1781 *pcount = pps->capcount;
1782 pps->ppscount[2] = pps->capcount;
1786 /* Convert the count to a timespec. */
1787 tcount = pps->capcount - pps->capth->th_offset_count;
1788 tcount &= pps->capth->th_counter->tc_counter_mask;
1789 bt = pps->capth->th_bintime;
1790 bintime_addx(&bt, pps->capth->th_scale * tcount);
1791 bintime2timespec(&bt, &ts);
1793 /* If the timecounter was wound up underneath us, bail out. */
1794 atomic_thread_fence_acq();
1795 if (pps->capgen != pps->capth->th_generation)
1798 *pcount = pps->capcount;
1803 timespecadd(tsp, osp, tsp);
1804 if (tsp->tv_nsec < 0) {
1805 tsp->tv_nsec += 1000000000;
1811 *ffcount = pps->capffth->tick_ffcount + tcount;
1812 bt = pps->capffth->tick_time;
1813 ffclock_convert_delta(tcount, pps->capffth->cest.period, &bt);
1814 bintime_add(&bt, &pps->capffth->tick_time);
1815 bintime2timespec(&bt, &ts);
1825 * Feed the NTP PLL/FLL.
1826 * The FLL wants to know how many (hardware) nanoseconds
1827 * elapsed since the previous event.
1829 tcount = pps->capcount - pps->ppscount[2];
1830 pps->ppscount[2] = pps->capcount;
1831 tcount &= pps->capth->th_counter->tc_counter_mask;
1832 scale = (uint64_t)1 << 63;
1833 scale /= pps->capth->th_counter->tc_frequency;
1837 bintime_addx(&bt, scale * tcount);
1838 bintime2timespec(&bt, &ts);
1839 hardpps(tsp, ts.tv_nsec + 1000000000 * ts.tv_sec);
1843 /* Wakeup anyone sleeping in pps_fetch(). */
1848 * Timecounters need to be updated every so often to prevent the hardware
1849 * counter from overflowing. Updating also recalculates the cached values
1850 * used by the get*() family of functions, so their precision depends on
1851 * the update frequency.
1855 SYSCTL_INT(_kern_timecounter, OID_AUTO, tick, CTLFLAG_RD, &tc_tick, 0,
1856 "Approximate number of hardclock ticks in a millisecond");
1859 tc_ticktock(int cnt)
1863 if (mtx_trylock_spin(&tc_setclock_mtx)) {
1865 if (count >= tc_tick) {
1869 mtx_unlock_spin(&tc_setclock_mtx);
1873 static void __inline
1874 tc_adjprecision(void)
1878 if (tc_timepercentage > 0) {
1879 t = (99 + tc_timepercentage) / tc_timepercentage;
1880 tc_precexp = fls(t + (t >> 1)) - 1;
1881 FREQ2BT(hz / tc_tick, &bt_timethreshold);
1882 FREQ2BT(hz, &bt_tickthreshold);
1883 bintime_shift(&bt_timethreshold, tc_precexp);
1884 bintime_shift(&bt_tickthreshold, tc_precexp);
1887 bt_timethreshold.sec = INT_MAX;
1888 bt_timethreshold.frac = ~(uint64_t)0;
1889 bt_tickthreshold = bt_timethreshold;
1891 sbt_timethreshold = bttosbt(bt_timethreshold);
1892 sbt_tickthreshold = bttosbt(bt_tickthreshold);
1896 sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS)
1900 val = tc_timepercentage;
1901 error = sysctl_handle_int(oidp, &val, 0, req);
1902 if (error != 0 || req->newptr == NULL)
1904 tc_timepercentage = val;
1912 /* Set up the requested number of timehands. */
1914 inittimehands(void *dummy)
1916 struct timehands *thp;
1919 TUNABLE_INT_FETCH("kern.timecounter.timehands_count",
1921 if (timehands_count < 1)
1922 timehands_count = 1;
1923 if (timehands_count > nitems(ths))
1924 timehands_count = nitems(ths);
1925 for (i = 1, thp = &ths[0]; i < timehands_count; thp = &ths[i++])
1926 thp->th_next = &ths[i];
1927 thp->th_next = &ths[0];
1929 SYSINIT(timehands, SI_SUB_TUNABLES, SI_ORDER_ANY, inittimehands, NULL);
1932 inittimecounter(void *dummy)
1938 * Set the initial timeout to
1939 * max(1, <approx. number of hardclock ticks in a millisecond>).
1940 * People should probably not use the sysctl to set the timeout
1941 * to smaller than its initial value, since that value is the
1942 * smallest reasonable one. If they want better timestamps they
1943 * should use the non-"get"* functions.
1946 tc_tick = (hz + 500) / 1000;
1950 FREQ2BT(hz, &tick_bt);
1951 tick_sbt = bttosbt(tick_bt);
1952 tick_rate = hz / tc_tick;
1953 FREQ2BT(tick_rate, &tc_tick_bt);
1954 tc_tick_sbt = bttosbt(tc_tick_bt);
1955 p = (tc_tick * 1000000) / hz;
1956 printf("Timecounters tick every %d.%03u msec\n", p / 1000, p % 1000);
1962 /* warm up new timecounter (again) and get rolling. */
1963 (void)timecounter->tc_get_timecount(timecounter);
1964 mtx_lock_spin(&tc_setclock_mtx);
1966 mtx_unlock_spin(&tc_setclock_mtx);
1969 SYSINIT(timecounter, SI_SUB_CLOCKS, SI_ORDER_SECOND, inittimecounter, NULL);
1971 /* Cpu tick handling -------------------------------------------------*/
1973 static int cpu_tick_variable;
1974 static uint64_t cpu_tick_frequency;
1976 DPCPU_DEFINE_STATIC(uint64_t, tc_cpu_ticks_base);
1977 DPCPU_DEFINE_STATIC(unsigned, tc_cpu_ticks_last);
1982 struct timecounter *tc;
1983 uint64_t res, *base;
1987 base = DPCPU_PTR(tc_cpu_ticks_base);
1988 last = DPCPU_PTR(tc_cpu_ticks_last);
1989 tc = timehands->th_counter;
1990 u = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
1992 *base += (uint64_t)tc->tc_counter_mask + 1;
2000 cpu_tick_calibration(void)
2002 static time_t last_calib;
2004 if (time_uptime != last_calib && !(time_uptime & 0xf)) {
2005 cpu_tick_calibrate(0);
2006 last_calib = time_uptime;
2011 * This function gets called every 16 seconds on only one designated
2012 * CPU in the system from hardclock() via cpu_tick_calibration()().
2014 * Whenever the real time clock is stepped we get called with reset=1
2015 * to make sure we handle suspend/resume and similar events correctly.
2019 cpu_tick_calibrate(int reset)
2021 static uint64_t c_last;
2022 uint64_t c_this, c_delta;
2023 static struct bintime t_last;
2024 struct bintime t_this, t_delta;
2028 /* The clock was stepped, abort & reset */
2033 /* we don't calibrate fixed rate cputicks */
2034 if (!cpu_tick_variable)
2037 getbinuptime(&t_this);
2038 c_this = cpu_ticks();
2039 if (t_last.sec != 0) {
2040 c_delta = c_this - c_last;
2042 bintime_sub(&t_delta, &t_last);
2045 * 2^(64-20) / 16[s] =
2047 * 17.592.186.044.416 / 16 =
2048 * 1.099.511.627.776 [Hz]
2050 divi = t_delta.sec << 20;
2051 divi |= t_delta.frac >> (64 - 20);
2054 if (c_delta > cpu_tick_frequency) {
2055 if (0 && bootverbose)
2056 printf("cpu_tick increased to %ju Hz\n",
2058 cpu_tick_frequency = c_delta;
2066 set_cputicker(cpu_tick_f *func, uint64_t freq, unsigned var)
2070 cpu_ticks = tc_cpu_ticks;
2072 cpu_tick_frequency = freq;
2073 cpu_tick_variable = var;
2082 if (cpu_ticks == tc_cpu_ticks)
2083 return (tc_getfrequency());
2084 return (cpu_tick_frequency);
2088 * We need to be slightly careful converting cputicks to microseconds.
2089 * There is plenty of margin in 64 bits of microseconds (half a million
2090 * years) and in 64 bits at 4 GHz (146 years), but if we do a multiply
2091 * before divide conversion (to retain precision) we find that the
2092 * margin shrinks to 1.5 hours (one millionth of 146y).
2093 * With a three prong approach we never lose significant bits, no
2094 * matter what the cputick rate and length of timeinterval is.
2098 cputick2usec(uint64_t tick)
2101 if (tick > 18446744073709551LL) /* floor(2^64 / 1000) */
2102 return (tick / (cpu_tickrate() / 1000000LL));
2103 else if (tick > 18446744073709LL) /* floor(2^64 / 1000000) */
2104 return ((tick * 1000LL) / (cpu_tickrate() / 1000LL));
2106 return ((tick * 1000000LL) / cpu_tickrate());
2109 cpu_tick_f *cpu_ticks = tc_cpu_ticks;
2111 static int vdso_th_enable = 1;
2113 sysctl_fast_gettime(SYSCTL_HANDLER_ARGS)
2115 int old_vdso_th_enable, error;
2117 old_vdso_th_enable = vdso_th_enable;
2118 error = sysctl_handle_int(oidp, &old_vdso_th_enable, 0, req);
2121 vdso_th_enable = old_vdso_th_enable;
2124 SYSCTL_PROC(_kern_timecounter, OID_AUTO, fast_gettime,
2125 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
2126 NULL, 0, sysctl_fast_gettime, "I", "Enable fast time of day");
2129 tc_fill_vdso_timehands(struct vdso_timehands *vdso_th)
2131 struct timehands *th;
2135 vdso_th->th_scale = th->th_scale;
2136 vdso_th->th_offset_count = th->th_offset_count;
2137 vdso_th->th_counter_mask = th->th_counter->tc_counter_mask;
2138 vdso_th->th_offset = th->th_offset;
2139 vdso_th->th_boottime = th->th_boottime;
2140 if (th->th_counter->tc_fill_vdso_timehands != NULL) {
2141 enabled = th->th_counter->tc_fill_vdso_timehands(vdso_th,
2145 if (!vdso_th_enable)
2150 #ifdef COMPAT_FREEBSD32
2152 tc_fill_vdso_timehands32(struct vdso_timehands32 *vdso_th32)
2154 struct timehands *th;
2158 *(uint64_t *)&vdso_th32->th_scale[0] = th->th_scale;
2159 vdso_th32->th_offset_count = th->th_offset_count;
2160 vdso_th32->th_counter_mask = th->th_counter->tc_counter_mask;
2161 vdso_th32->th_offset.sec = th->th_offset.sec;
2162 *(uint64_t *)&vdso_th32->th_offset.frac[0] = th->th_offset.frac;
2163 vdso_th32->th_boottime.sec = th->th_boottime.sec;
2164 *(uint64_t *)&vdso_th32->th_boottime.frac[0] = th->th_boottime.frac;
2165 if (th->th_counter->tc_fill_vdso_timehands32 != NULL) {
2166 enabled = th->th_counter->tc_fill_vdso_timehands32(vdso_th32,
2170 if (!vdso_th_enable)