The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/kern/kern_tc.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * ----------------------------------------------------------------------------
    3  * "THE BEER-WARE LICENSE" (Revision 42):
    4  * <phk@FreeBSD.ORG> wrote this file.  As long as you retain this notice you
    5  * can do whatever you want with this stuff. If we meet some day, and you think
    6  * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
    7  * ----------------------------------------------------------------------------
    8  *
    9  * Copyright (c) 2011 The FreeBSD Foundation
   10  * All rights reserved.
   11  *
   12  * Portions of this software were developed by Julien Ridoux at the University
   13  * of Melbourne under sponsorship from the FreeBSD Foundation.
   14  */
   15 
   16 #include <sys/cdefs.h>
   17 __FBSDID("$FreeBSD: releng/10.2/sys/kern/kern_tc.c 285753 2015-07-21 15:06:22Z kib $");
   18 
   19 #include "opt_compat.h"
   20 #include "opt_ntp.h"
   21 #include "opt_ffclock.h"
   22 
   23 #include <sys/param.h>
   24 #include <sys/kernel.h>
   25 #include <sys/limits.h>
   26 #include <sys/lock.h>
   27 #include <sys/mutex.h>
   28 #include <sys/sysctl.h>
   29 #include <sys/syslog.h>
   30 #include <sys/systm.h>
   31 #include <sys/timeffc.h>
   32 #include <sys/timepps.h>
   33 #include <sys/timetc.h>
   34 #include <sys/timex.h>
   35 #include <sys/vdso.h>
   36 
   37 /*
   38  * A large step happens on boot.  This constant detects such steps.
   39  * It is relatively small so that ntp_update_second gets called enough
   40  * in the typical 'missed a couple of seconds' case, but doesn't loop
   41  * forever when the time step is large.
   42  */
   43 #define LARGE_STEP      200
   44 
   45 /*
   46  * Implement a dummy timecounter which we can use until we get a real one
   47  * in the air.  This allows the console and other early stuff to use
   48  * time services.
   49  */
   50 
   51 static u_int
   52 dummy_get_timecount(struct timecounter *tc)
   53 {
   54         static u_int now;
   55 
   56         return (++now);
   57 }
   58 
   59 static struct timecounter dummy_timecounter = {
   60         dummy_get_timecount, 0, ~0u, 1000000, "dummy", -1000000
   61 };
   62 
   63 struct timehands {
   64         /* These fields must be initialized by the driver. */
   65         struct timecounter      *th_counter;
   66         int64_t                 th_adjustment;
   67         uint64_t                th_scale;
   68         u_int                   th_offset_count;
   69         struct bintime          th_offset;
   70         struct timeval          th_microtime;
   71         struct timespec         th_nanotime;
   72         /* Fields not to be copied in tc_windup start with th_generation. */
   73         volatile u_int          th_generation;
   74         struct timehands        *th_next;
   75 };
   76 
   77 static struct timehands th0;
   78 static struct timehands th9 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th0};
   79 static struct timehands th8 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th9};
   80 static struct timehands th7 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th8};
   81 static struct timehands th6 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th7};
   82 static struct timehands th5 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th6};
   83 static struct timehands th4 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th5};
   84 static struct timehands th3 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th4};
   85 static struct timehands th2 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th3};
   86 static struct timehands th1 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th2};
   87 static struct timehands th0 = {
   88         &dummy_timecounter,
   89         0,
   90         (uint64_t)-1 / 1000000,
   91         0,
   92         {1, 0},
   93         {0, 0},
   94         {0, 0},
   95         1,
   96         &th1
   97 };
   98 
   99 static struct timehands *volatile timehands = &th0;
  100 struct timecounter *timecounter = &dummy_timecounter;
  101 static struct timecounter *timecounters = &dummy_timecounter;
  102 
  103 int tc_min_ticktock_freq = 1;
  104 
  105 volatile time_t time_second = 1;
  106 volatile time_t time_uptime = 1;
  107 
  108 struct bintime boottimebin;
  109 struct timeval boottime;
  110 static int sysctl_kern_boottime(SYSCTL_HANDLER_ARGS);
  111 SYSCTL_PROC(_kern, KERN_BOOTTIME, boottime, CTLTYPE_STRUCT|CTLFLAG_RD,
  112     NULL, 0, sysctl_kern_boottime, "S,timeval", "System boottime");
  113 
  114 SYSCTL_NODE(_kern, OID_AUTO, timecounter, CTLFLAG_RW, 0, "");
  115 static SYSCTL_NODE(_kern_timecounter, OID_AUTO, tc, CTLFLAG_RW, 0, "");
  116 
  117 static int timestepwarnings;
  118 SYSCTL_INT(_kern_timecounter, OID_AUTO, stepwarnings, CTLFLAG_RW,
  119     &timestepwarnings, 0, "Log time steps");
  120 
  121 struct bintime bt_timethreshold;
  122 struct bintime bt_tickthreshold;
  123 sbintime_t sbt_timethreshold;
  124 sbintime_t sbt_tickthreshold;
  125 struct bintime tc_tick_bt;
  126 sbintime_t tc_tick_sbt;
  127 int tc_precexp;
  128 int tc_timepercentage = TC_DEFAULTPERC;
  129 TUNABLE_INT("kern.timecounter.alloweddeviation", &tc_timepercentage);
  130 static int sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS);
  131 SYSCTL_PROC(_kern_timecounter, OID_AUTO, alloweddeviation,
  132     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 0,
  133     sysctl_kern_timecounter_adjprecision, "I",
  134     "Allowed time interval deviation in percents");
  135 
  136 static void tc_windup(void);
  137 static void cpu_tick_calibrate(int);
  138 
  139 void dtrace_getnanotime(struct timespec *tsp);
  140 
  141 static int
  142 sysctl_kern_boottime(SYSCTL_HANDLER_ARGS)
  143 {
  144 #ifndef __mips__
  145 #ifdef SCTL_MASK32
  146         int tv[2];
  147 
  148         if (req->flags & SCTL_MASK32) {
  149                 tv[0] = boottime.tv_sec;
  150                 tv[1] = boottime.tv_usec;
  151                 return SYSCTL_OUT(req, tv, sizeof(tv));
  152         } else
  153 #endif
  154 #endif
  155                 return SYSCTL_OUT(req, &boottime, sizeof(boottime));
  156 }
  157 
  158 static int
  159 sysctl_kern_timecounter_get(SYSCTL_HANDLER_ARGS)
  160 {
  161         u_int ncount;
  162         struct timecounter *tc = arg1;
  163 
  164         ncount = tc->tc_get_timecount(tc);
  165         return sysctl_handle_int(oidp, &ncount, 0, req);
  166 }
  167 
  168 static int
  169 sysctl_kern_timecounter_freq(SYSCTL_HANDLER_ARGS)
  170 {
  171         uint64_t freq;
  172         struct timecounter *tc = arg1;
  173 
  174         freq = tc->tc_frequency;
  175         return sysctl_handle_64(oidp, &freq, 0, req);
  176 }
  177 
  178 /*
  179  * Return the difference between the timehands' counter value now and what
  180  * was when we copied it to the timehands' offset_count.
  181  */
  182 static __inline u_int
  183 tc_delta(struct timehands *th)
  184 {
  185         struct timecounter *tc;
  186 
  187         tc = th->th_counter;
  188         return ((tc->tc_get_timecount(tc) - th->th_offset_count) &
  189             tc->tc_counter_mask);
  190 }
  191 
  192 /*
  193  * Functions for reading the time.  We have to loop until we are sure that
  194  * the timehands that we operated on was not updated under our feet.  See
  195  * the comment in <sys/time.h> for a description of these 12 functions.
  196  */
  197 
  198 #ifdef FFCLOCK
  199 void
  200 fbclock_binuptime(struct bintime *bt)
  201 {
  202         struct timehands *th;
  203         unsigned int gen;
  204 
  205         do {
  206                 th = timehands;
  207                 gen = th->th_generation;
  208                 *bt = th->th_offset;
  209                 bintime_addx(bt, th->th_scale * tc_delta(th));
  210         } while (gen == 0 || gen != th->th_generation);
  211 }
  212 
  213 void
  214 fbclock_nanouptime(struct timespec *tsp)
  215 {
  216         struct bintime bt;
  217 
  218         fbclock_binuptime(&bt);
  219         bintime2timespec(&bt, tsp);
  220 }
  221 
  222 void
  223 fbclock_microuptime(struct timeval *tvp)
  224 {
  225         struct bintime bt;
  226 
  227         fbclock_binuptime(&bt);
  228         bintime2timeval(&bt, tvp);
  229 }
  230 
  231 void
  232 fbclock_bintime(struct bintime *bt)
  233 {
  234 
  235         fbclock_binuptime(bt);
  236         bintime_add(bt, &boottimebin);
  237 }
  238 
  239 void
  240 fbclock_nanotime(struct timespec *tsp)
  241 {
  242         struct bintime bt;
  243 
  244         fbclock_bintime(&bt);
  245         bintime2timespec(&bt, tsp);
  246 }
  247 
  248 void
  249 fbclock_microtime(struct timeval *tvp)
  250 {
  251         struct bintime bt;
  252 
  253         fbclock_bintime(&bt);
  254         bintime2timeval(&bt, tvp);
  255 }
  256 
  257 void
  258 fbclock_getbinuptime(struct bintime *bt)
  259 {
  260         struct timehands *th;
  261         unsigned int gen;
  262 
  263         do {
  264                 th = timehands;
  265                 gen = th->th_generation;
  266                 *bt = th->th_offset;
  267         } while (gen == 0 || gen != th->th_generation);
  268 }
  269 
  270 void
  271 fbclock_getnanouptime(struct timespec *tsp)
  272 {
  273         struct timehands *th;
  274         unsigned int gen;
  275 
  276         do {
  277                 th = timehands;
  278                 gen = th->th_generation;
  279                 bintime2timespec(&th->th_offset, tsp);
  280         } while (gen == 0 || gen != th->th_generation);
  281 }
  282 
  283 void
  284 fbclock_getmicrouptime(struct timeval *tvp)
  285 {
  286         struct timehands *th;
  287         unsigned int gen;
  288 
  289         do {
  290                 th = timehands;
  291                 gen = th->th_generation;
  292                 bintime2timeval(&th->th_offset, tvp);
  293         } while (gen == 0 || gen != th->th_generation);
  294 }
  295 
  296 void
  297 fbclock_getbintime(struct bintime *bt)
  298 {
  299         struct timehands *th;
  300         unsigned int gen;
  301 
  302         do {
  303                 th = timehands;
  304                 gen = th->th_generation;
  305                 *bt = th->th_offset;
  306         } while (gen == 0 || gen != th->th_generation);
  307         bintime_add(bt, &boottimebin);
  308 }
  309 
  310 void
  311 fbclock_getnanotime(struct timespec *tsp)
  312 {
  313         struct timehands *th;
  314         unsigned int gen;
  315 
  316         do {
  317                 th = timehands;
  318                 gen = th->th_generation;
  319                 *tsp = th->th_nanotime;
  320         } while (gen == 0 || gen != th->th_generation);
  321 }
  322 
  323 void
  324 fbclock_getmicrotime(struct timeval *tvp)
  325 {
  326         struct timehands *th;
  327         unsigned int gen;
  328 
  329         do {
  330                 th = timehands;
  331                 gen = th->th_generation;
  332                 *tvp = th->th_microtime;
  333         } while (gen == 0 || gen != th->th_generation);
  334 }
  335 #else /* !FFCLOCK */
  336 void
  337 binuptime(struct bintime *bt)
  338 {
  339         struct timehands *th;
  340         u_int gen;
  341 
  342         do {
  343                 th = timehands;
  344                 gen = th->th_generation;
  345                 *bt = th->th_offset;
  346                 bintime_addx(bt, th->th_scale * tc_delta(th));
  347         } while (gen == 0 || gen != th->th_generation);
  348 }
  349 
  350 void
  351 nanouptime(struct timespec *tsp)
  352 {
  353         struct bintime bt;
  354 
  355         binuptime(&bt);
  356         bintime2timespec(&bt, tsp);
  357 }
  358 
  359 void
  360 microuptime(struct timeval *tvp)
  361 {
  362         struct bintime bt;
  363 
  364         binuptime(&bt);
  365         bintime2timeval(&bt, tvp);
  366 }
  367 
  368 void
  369 bintime(struct bintime *bt)
  370 {
  371 
  372         binuptime(bt);
  373         bintime_add(bt, &boottimebin);
  374 }
  375 
  376 void
  377 nanotime(struct timespec *tsp)
  378 {
  379         struct bintime bt;
  380 
  381         bintime(&bt);
  382         bintime2timespec(&bt, tsp);
  383 }
  384 
  385 void
  386 microtime(struct timeval *tvp)
  387 {
  388         struct bintime bt;
  389 
  390         bintime(&bt);
  391         bintime2timeval(&bt, tvp);
  392 }
  393 
  394 void
  395 getbinuptime(struct bintime *bt)
  396 {
  397         struct timehands *th;
  398         u_int gen;
  399 
  400         do {
  401                 th = timehands;
  402                 gen = th->th_generation;
  403                 *bt = th->th_offset;
  404         } while (gen == 0 || gen != th->th_generation);
  405 }
  406 
  407 void
  408 getnanouptime(struct timespec *tsp)
  409 {
  410         struct timehands *th;
  411         u_int gen;
  412 
  413         do {
  414                 th = timehands;
  415                 gen = th->th_generation;
  416                 bintime2timespec(&th->th_offset, tsp);
  417         } while (gen == 0 || gen != th->th_generation);
  418 }
  419 
  420 void
  421 getmicrouptime(struct timeval *tvp)
  422 {
  423         struct timehands *th;
  424         u_int gen;
  425 
  426         do {
  427                 th = timehands;
  428                 gen = th->th_generation;
  429                 bintime2timeval(&th->th_offset, tvp);
  430         } while (gen == 0 || gen != th->th_generation);
  431 }
  432 
  433 void
  434 getbintime(struct bintime *bt)
  435 {
  436         struct timehands *th;
  437         u_int gen;
  438 
  439         do {
  440                 th = timehands;
  441                 gen = th->th_generation;
  442                 *bt = th->th_offset;
  443         } while (gen == 0 || gen != th->th_generation);
  444         bintime_add(bt, &boottimebin);
  445 }
  446 
  447 void
  448 getnanotime(struct timespec *tsp)
  449 {
  450         struct timehands *th;
  451         u_int gen;
  452 
  453         do {
  454                 th = timehands;
  455                 gen = th->th_generation;
  456                 *tsp = th->th_nanotime;
  457         } while (gen == 0 || gen != th->th_generation);
  458 }
  459 
  460 void
  461 getmicrotime(struct timeval *tvp)
  462 {
  463         struct timehands *th;
  464         u_int gen;
  465 
  466         do {
  467                 th = timehands;
  468                 gen = th->th_generation;
  469                 *tvp = th->th_microtime;
  470         } while (gen == 0 || gen != th->th_generation);
  471 }
  472 #endif /* FFCLOCK */
  473 
  474 #ifdef FFCLOCK
  475 /*
  476  * Support for feed-forward synchronization algorithms. This is heavily inspired
  477  * by the timehands mechanism but kept independent from it. *_windup() functions
  478  * have some connection to avoid accessing the timecounter hardware more than
  479  * necessary.
  480  */
  481 
  482 /* Feed-forward clock estimates kept updated by the synchronization daemon. */
  483 struct ffclock_estimate ffclock_estimate;
  484 struct bintime ffclock_boottime;        /* Feed-forward boot time estimate. */
  485 uint32_t ffclock_status;                /* Feed-forward clock status. */
  486 int8_t ffclock_updated;                 /* New estimates are available. */
  487 struct mtx ffclock_mtx;                 /* Mutex on ffclock_estimate. */
  488 
  489 struct fftimehands {
  490         struct ffclock_estimate cest;
  491         struct bintime          tick_time;
  492         struct bintime          tick_time_lerp;
  493         ffcounter               tick_ffcount;
  494         uint64_t                period_lerp;
  495         volatile uint8_t        gen;
  496         struct fftimehands      *next;
  497 };
  498 
  499 #define NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))
  500 
  501 static struct fftimehands ffth[10];
  502 static struct fftimehands *volatile fftimehands = ffth;
  503 
  504 static void
  505 ffclock_init(void)
  506 {
  507         struct fftimehands *cur;
  508         struct fftimehands *last;
  509 
  510         memset(ffth, 0, sizeof(ffth));
  511 
  512         last = ffth + NUM_ELEMENTS(ffth) - 1;
  513         for (cur = ffth; cur < last; cur++)
  514                 cur->next = cur + 1;
  515         last->next = ffth;
  516 
  517         ffclock_updated = 0;
  518         ffclock_status = FFCLOCK_STA_UNSYNC;
  519         mtx_init(&ffclock_mtx, "ffclock lock", NULL, MTX_DEF);
  520 }
  521 
  522 /*
  523  * Reset the feed-forward clock estimates. Called from inittodr() to get things
  524  * kick started and uses the timecounter nominal frequency as a first period
  525  * estimate. Note: this function may be called several time just after boot.
  526  * Note: this is the only function that sets the value of boot time for the
  527  * monotonic (i.e. uptime) version of the feed-forward clock.
  528  */
  529 void
  530 ffclock_reset_clock(struct timespec *ts)
  531 {
  532         struct timecounter *tc;
  533         struct ffclock_estimate cest;
  534 
  535         tc = timehands->th_counter;
  536         memset(&cest, 0, sizeof(struct ffclock_estimate));
  537 
  538         timespec2bintime(ts, &ffclock_boottime);
  539         timespec2bintime(ts, &(cest.update_time));
  540         ffclock_read_counter(&cest.update_ffcount);
  541         cest.leapsec_next = 0;
  542         cest.period = ((1ULL << 63) / tc->tc_frequency) << 1;
  543         cest.errb_abs = 0;
  544         cest.errb_rate = 0;
  545         cest.status = FFCLOCK_STA_UNSYNC;
  546         cest.leapsec_total = 0;
  547         cest.leapsec = 0;
  548 
  549         mtx_lock(&ffclock_mtx);
  550         bcopy(&cest, &ffclock_estimate, sizeof(struct ffclock_estimate));
  551         ffclock_updated = INT8_MAX;
  552         mtx_unlock(&ffclock_mtx);
  553 
  554         printf("ffclock reset: %s (%llu Hz), time = %ld.%09lu\n", tc->tc_name,
  555             (unsigned long long)tc->tc_frequency, (long)ts->tv_sec,
  556             (unsigned long)ts->tv_nsec);
  557 }
  558 
  559 /*
  560  * Sub-routine to convert a time interval measured in RAW counter units to time
  561  * in seconds stored in bintime format.
  562  * NOTE: bintime_mul requires u_int, but the value of the ffcounter may be
  563  * larger than the max value of u_int (on 32 bit architecture). Loop to consume
  564  * extra cycles.
  565  */
  566 static void
  567 ffclock_convert_delta(ffcounter ffdelta, uint64_t period, struct bintime *bt)
  568 {
  569         struct bintime bt2;
  570         ffcounter delta, delta_max;
  571 
  572         delta_max = (1ULL << (8 * sizeof(unsigned int))) - 1;
  573         bintime_clear(bt);
  574         do {
  575                 if (ffdelta > delta_max)
  576                         delta = delta_max;
  577                 else
  578                         delta = ffdelta;
  579                 bt2.sec = 0;
  580                 bt2.frac = period;
  581                 bintime_mul(&bt2, (unsigned int)delta);
  582                 bintime_add(bt, &bt2);
  583                 ffdelta -= delta;
  584         } while (ffdelta > 0);
  585 }
  586 
  587 /*
  588  * Update the fftimehands.
  589  * Push the tick ffcount and time(s) forward based on current clock estimate.
  590  * The conversion from ffcounter to bintime relies on the difference clock
  591  * principle, whose accuracy relies on computing small time intervals. If a new
  592  * clock estimate has been passed by the synchronisation daemon, make it
  593  * current, and compute the linear interpolation for monotonic time if needed.
  594  */
  595 static void
  596 ffclock_windup(unsigned int delta)
  597 {
  598         struct ffclock_estimate *cest;
  599         struct fftimehands *ffth;
  600         struct bintime bt, gap_lerp;
  601         ffcounter ffdelta;
  602         uint64_t frac;
  603         unsigned int polling;
  604         uint8_t forward_jump, ogen;
  605 
  606         /*
  607          * Pick the next timehand, copy current ffclock estimates and move tick
  608          * times and counter forward.
  609          */
  610         forward_jump = 0;
  611         ffth = fftimehands->next;
  612         ogen = ffth->gen;
  613         ffth->gen = 0;
  614         cest = &ffth->cest;
  615         bcopy(&fftimehands->cest, cest, sizeof(struct ffclock_estimate));
  616         ffdelta = (ffcounter)delta;
  617         ffth->period_lerp = fftimehands->period_lerp;
  618 
  619         ffth->tick_time = fftimehands->tick_time;
  620         ffclock_convert_delta(ffdelta, cest->period, &bt);
  621         bintime_add(&ffth->tick_time, &bt);
  622 
  623         ffth->tick_time_lerp = fftimehands->tick_time_lerp;
  624         ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt);
  625         bintime_add(&ffth->tick_time_lerp, &bt);
  626 
  627         ffth->tick_ffcount = fftimehands->tick_ffcount + ffdelta;
  628 
  629         /*
  630          * Assess the status of the clock, if the last update is too old, it is
  631          * likely the synchronisation daemon is dead and the clock is free
  632          * running.
  633          */
  634         if (ffclock_updated == 0) {
  635                 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
  636                 ffclock_convert_delta(ffdelta, cest->period, &bt);
  637                 if (bt.sec > 2 * FFCLOCK_SKM_SCALE)
  638                         ffclock_status |= FFCLOCK_STA_UNSYNC;
  639         }
  640 
  641         /*
  642          * If available, grab updated clock estimates and make them current.
  643          * Recompute time at this tick using the updated estimates. The clock
  644          * estimates passed the feed-forward synchronisation daemon may result
  645          * in time conversion that is not monotonically increasing (just after
  646          * the update). time_lerp is a particular linear interpolation over the
  647          * synchronisation algo polling period that ensures monotonicity for the
  648          * clock ids requesting it.
  649          */
  650         if (ffclock_updated > 0) {
  651                 bcopy(&ffclock_estimate, cest, sizeof(struct ffclock_estimate));
  652                 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
  653                 ffth->tick_time = cest->update_time;
  654                 ffclock_convert_delta(ffdelta, cest->period, &bt);
  655                 bintime_add(&ffth->tick_time, &bt);
  656 
  657                 /* ffclock_reset sets ffclock_updated to INT8_MAX */
  658                 if (ffclock_updated == INT8_MAX)
  659                         ffth->tick_time_lerp = ffth->tick_time;
  660 
  661                 if (bintime_cmp(&ffth->tick_time, &ffth->tick_time_lerp, >))
  662                         forward_jump = 1;
  663                 else
  664                         forward_jump = 0;
  665 
  666                 bintime_clear(&gap_lerp);
  667                 if (forward_jump) {
  668                         gap_lerp = ffth->tick_time;
  669                         bintime_sub(&gap_lerp, &ffth->tick_time_lerp);
  670                 } else {
  671                         gap_lerp = ffth->tick_time_lerp;
  672                         bintime_sub(&gap_lerp, &ffth->tick_time);
  673                 }
  674 
  675                 /*
  676                  * The reset from the RTC clock may be far from accurate, and
  677                  * reducing the gap between real time and interpolated time
  678                  * could take a very long time if the interpolated clock insists
  679                  * on strict monotonicity. The clock is reset under very strict
  680                  * conditions (kernel time is known to be wrong and
  681                  * synchronization daemon has been restarted recently.
  682                  * ffclock_boottime absorbs the jump to ensure boot time is
  683                  * correct and uptime functions stay consistent.
  684                  */
  685                 if (((ffclock_status & FFCLOCK_STA_UNSYNC) == FFCLOCK_STA_UNSYNC) &&
  686                     ((cest->status & FFCLOCK_STA_UNSYNC) == 0) &&
  687                     ((cest->status & FFCLOCK_STA_WARMUP) == FFCLOCK_STA_WARMUP)) {
  688                         if (forward_jump)
  689                                 bintime_add(&ffclock_boottime, &gap_lerp);
  690                         else
  691                                 bintime_sub(&ffclock_boottime, &gap_lerp);
  692                         ffth->tick_time_lerp = ffth->tick_time;
  693                         bintime_clear(&gap_lerp);
  694                 }
  695 
  696                 ffclock_status = cest->status;
  697                 ffth->period_lerp = cest->period;
  698 
  699                 /*
  700                  * Compute corrected period used for the linear interpolation of
  701                  * time. The rate of linear interpolation is capped to 5000PPM
  702                  * (5ms/s).
  703                  */
  704                 if (bintime_isset(&gap_lerp)) {
  705                         ffdelta = cest->update_ffcount;
  706                         ffdelta -= fftimehands->cest.update_ffcount;
  707                         ffclock_convert_delta(ffdelta, cest->period, &bt);
  708                         polling = bt.sec;
  709                         bt.sec = 0;
  710                         bt.frac = 5000000 * (uint64_t)18446744073LL;
  711                         bintime_mul(&bt, polling);
  712                         if (bintime_cmp(&gap_lerp, &bt, >))
  713                                 gap_lerp = bt;
  714 
  715                         /* Approximate 1 sec by 1-(1/2^64) to ease arithmetic */
  716                         frac = 0;
  717                         if (gap_lerp.sec > 0) {
  718                                 frac -= 1;
  719                                 frac /= ffdelta / gap_lerp.sec;
  720                         }
  721                         frac += gap_lerp.frac / ffdelta;
  722 
  723                         if (forward_jump)
  724                                 ffth->period_lerp += frac;
  725                         else
  726                                 ffth->period_lerp -= frac;
  727                 }
  728 
  729                 ffclock_updated = 0;
  730         }
  731         if (++ogen == 0)
  732                 ogen = 1;
  733         ffth->gen = ogen;
  734         fftimehands = ffth;
  735 }
  736 
  737 /*
  738  * Adjust the fftimehands when the timecounter is changed. Stating the obvious,
  739  * the old and new hardware counter cannot be read simultaneously. tc_windup()
  740  * does read the two counters 'back to back', but a few cycles are effectively
  741  * lost, and not accumulated in tick_ffcount. This is a fairly radical
  742  * operation for a feed-forward synchronization daemon, and it is its job to not
  743  * pushing irrelevant data to the kernel. Because there is no locking here,
  744  * simply force to ignore pending or next update to give daemon a chance to
  745  * realize the counter has changed.
  746  */
  747 static void
  748 ffclock_change_tc(struct timehands *th)
  749 {
  750         struct fftimehands *ffth;
  751         struct ffclock_estimate *cest;
  752         struct timecounter *tc;
  753         uint8_t ogen;
  754 
  755         tc = th->th_counter;
  756         ffth = fftimehands->next;
  757         ogen = ffth->gen;
  758         ffth->gen = 0;
  759 
  760         cest = &ffth->cest;
  761         bcopy(&(fftimehands->cest), cest, sizeof(struct ffclock_estimate));
  762         cest->period = ((1ULL << 63) / tc->tc_frequency ) << 1;
  763         cest->errb_abs = 0;
  764         cest->errb_rate = 0;
  765         cest->status |= FFCLOCK_STA_UNSYNC;
  766 
  767         ffth->tick_ffcount = fftimehands->tick_ffcount;
  768         ffth->tick_time_lerp = fftimehands->tick_time_lerp;
  769         ffth->tick_time = fftimehands->tick_time;
  770         ffth->period_lerp = cest->period;
  771 
  772         /* Do not lock but ignore next update from synchronization daemon. */
  773         ffclock_updated--;
  774 
  775         if (++ogen == 0)
  776                 ogen = 1;
  777         ffth->gen = ogen;
  778         fftimehands = ffth;
  779 }
  780 
  781 /*
  782  * Retrieve feed-forward counter and time of last kernel tick.
  783  */
  784 void
  785 ffclock_last_tick(ffcounter *ffcount, struct bintime *bt, uint32_t flags)
  786 {
  787         struct fftimehands *ffth;
  788         uint8_t gen;
  789 
  790         /*
  791          * No locking but check generation has not changed. Also need to make
  792          * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
  793          */
  794         do {
  795                 ffth = fftimehands;
  796                 gen = ffth->gen;
  797                 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP)
  798                         *bt = ffth->tick_time_lerp;
  799                 else
  800                         *bt = ffth->tick_time;
  801                 *ffcount = ffth->tick_ffcount;
  802         } while (gen == 0 || gen != ffth->gen);
  803 }
  804 
  805 /*
  806  * Absolute clock conversion. Low level function to convert ffcounter to
  807  * bintime. The ffcounter is converted using the current ffclock period estimate
  808  * or the "interpolated period" to ensure monotonicity.
  809  * NOTE: this conversion may have been deferred, and the clock updated since the
  810  * hardware counter has been read.
  811  */
  812 void
  813 ffclock_convert_abs(ffcounter ffcount, struct bintime *bt, uint32_t flags)
  814 {
  815         struct fftimehands *ffth;
  816         struct bintime bt2;
  817         ffcounter ffdelta;
  818         uint8_t gen;
  819 
  820         /*
  821          * No locking but check generation has not changed. Also need to make
  822          * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
  823          */
  824         do {
  825                 ffth = fftimehands;
  826                 gen = ffth->gen;
  827                 if (ffcount > ffth->tick_ffcount)
  828                         ffdelta = ffcount - ffth->tick_ffcount;
  829                 else
  830                         ffdelta = ffth->tick_ffcount - ffcount;
  831 
  832                 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP) {
  833                         *bt = ffth->tick_time_lerp;
  834                         ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt2);
  835                 } else {
  836                         *bt = ffth->tick_time;
  837                         ffclock_convert_delta(ffdelta, ffth->cest.period, &bt2);
  838                 }
  839 
  840                 if (ffcount > ffth->tick_ffcount)
  841                         bintime_add(bt, &bt2);
  842                 else
  843                         bintime_sub(bt, &bt2);
  844         } while (gen == 0 || gen != ffth->gen);
  845 }
  846 
  847 /*
  848  * Difference clock conversion.
  849  * Low level function to Convert a time interval measured in RAW counter units
  850  * into bintime. The difference clock allows measuring small intervals much more
  851  * reliably than the absolute clock.
  852  */
  853 void
  854 ffclock_convert_diff(ffcounter ffdelta, struct bintime *bt)
  855 {
  856         struct fftimehands *ffth;
  857         uint8_t gen;
  858 
  859         /* No locking but check generation has not changed. */
  860         do {
  861                 ffth = fftimehands;
  862                 gen = ffth->gen;
  863                 ffclock_convert_delta(ffdelta, ffth->cest.period, bt);
  864         } while (gen == 0 || gen != ffth->gen);
  865 }
  866 
  867 /*
  868  * Access to current ffcounter value.
  869  */
  870 void
  871 ffclock_read_counter(ffcounter *ffcount)
  872 {
  873         struct timehands *th;
  874         struct fftimehands *ffth;
  875         unsigned int gen, delta;
  876 
  877         /*
  878          * ffclock_windup() called from tc_windup(), safe to rely on
  879          * th->th_generation only, for correct delta and ffcounter.
  880          */
  881         do {
  882                 th = timehands;
  883                 gen = th->th_generation;
  884                 ffth = fftimehands;
  885                 delta = tc_delta(th);
  886                 *ffcount = ffth->tick_ffcount;
  887         } while (gen == 0 || gen != th->th_generation);
  888 
  889         *ffcount += delta;
  890 }
  891 
  892 void
  893 binuptime(struct bintime *bt)
  894 {
  895 
  896         binuptime_fromclock(bt, sysclock_active);
  897 }
  898 
  899 void
  900 nanouptime(struct timespec *tsp)
  901 {
  902 
  903         nanouptime_fromclock(tsp, sysclock_active);
  904 }
  905 
  906 void
  907 microuptime(struct timeval *tvp)
  908 {
  909 
  910         microuptime_fromclock(tvp, sysclock_active);
  911 }
  912 
  913 void
  914 bintime(struct bintime *bt)
  915 {
  916 
  917         bintime_fromclock(bt, sysclock_active);
  918 }
  919 
  920 void
  921 nanotime(struct timespec *tsp)
  922 {
  923 
  924         nanotime_fromclock(tsp, sysclock_active);
  925 }
  926 
  927 void
  928 microtime(struct timeval *tvp)
  929 {
  930 
  931         microtime_fromclock(tvp, sysclock_active);
  932 }
  933 
  934 void
  935 getbinuptime(struct bintime *bt)
  936 {
  937 
  938         getbinuptime_fromclock(bt, sysclock_active);
  939 }
  940 
  941 void
  942 getnanouptime(struct timespec *tsp)
  943 {
  944 
  945         getnanouptime_fromclock(tsp, sysclock_active);
  946 }
  947 
  948 void
  949 getmicrouptime(struct timeval *tvp)
  950 {
  951 
  952         getmicrouptime_fromclock(tvp, sysclock_active);
  953 }
  954 
  955 void
  956 getbintime(struct bintime *bt)
  957 {
  958 
  959         getbintime_fromclock(bt, sysclock_active);
  960 }
  961 
  962 void
  963 getnanotime(struct timespec *tsp)
  964 {
  965 
  966         getnanotime_fromclock(tsp, sysclock_active);
  967 }
  968 
  969 void
  970 getmicrotime(struct timeval *tvp)
  971 {
  972 
  973         getmicrouptime_fromclock(tvp, sysclock_active);
  974 }
  975 
  976 #endif /* FFCLOCK */
  977 
  978 /*
  979  * This is a clone of getnanotime and used for walltimestamps.
  980  * The dtrace_ prefix prevents fbt from creating probes for
  981  * it so walltimestamp can be safely used in all fbt probes.
  982  */
  983 void
  984 dtrace_getnanotime(struct timespec *tsp)
  985 {
  986         struct timehands *th;
  987         u_int gen;
  988 
  989         do {
  990                 th = timehands;
  991                 gen = th->th_generation;
  992                 *tsp = th->th_nanotime;
  993         } while (gen == 0 || gen != th->th_generation);
  994 }
  995 
  996 /*
  997  * System clock currently providing time to the system. Modifiable via sysctl
  998  * when the FFCLOCK option is defined.
  999  */
 1000 int sysclock_active = SYSCLOCK_FBCK;
 1001 
 1002 /* Internal NTP status and error estimates. */
 1003 extern int time_status;
 1004 extern long time_esterror;
 1005 
 1006 /*
 1007  * Take a snapshot of sysclock data which can be used to compare system clocks
 1008  * and generate timestamps after the fact.
 1009  */
 1010 void
 1011 sysclock_getsnapshot(struct sysclock_snap *clock_snap, int fast)
 1012 {
 1013         struct fbclock_info *fbi;
 1014         struct timehands *th;
 1015         struct bintime bt;
 1016         unsigned int delta, gen;
 1017 #ifdef FFCLOCK
 1018         ffcounter ffcount;
 1019         struct fftimehands *ffth;
 1020         struct ffclock_info *ffi;
 1021         struct ffclock_estimate cest;
 1022 
 1023         ffi = &clock_snap->ff_info;
 1024 #endif
 1025 
 1026         fbi = &clock_snap->fb_info;
 1027         delta = 0;
 1028 
 1029         do {
 1030                 th = timehands;
 1031                 gen = th->th_generation;
 1032                 fbi->th_scale = th->th_scale;
 1033                 fbi->tick_time = th->th_offset;
 1034 #ifdef FFCLOCK
 1035                 ffth = fftimehands;
 1036                 ffi->tick_time = ffth->tick_time_lerp;
 1037                 ffi->tick_time_lerp = ffth->tick_time_lerp;
 1038                 ffi->period = ffth->cest.period;
 1039                 ffi->period_lerp = ffth->period_lerp;
 1040                 clock_snap->ffcount = ffth->tick_ffcount;
 1041                 cest = ffth->cest;
 1042 #endif
 1043                 if (!fast)
 1044                         delta = tc_delta(th);
 1045         } while (gen == 0 || gen != th->th_generation);
 1046 
 1047         clock_snap->delta = delta;
 1048         clock_snap->sysclock_active = sysclock_active;
 1049 
 1050         /* Record feedback clock status and error. */
 1051         clock_snap->fb_info.status = time_status;
 1052         /* XXX: Very crude estimate of feedback clock error. */
 1053         bt.sec = time_esterror / 1000000;
 1054         bt.frac = ((time_esterror - bt.sec) * 1000000) *
 1055             (uint64_t)18446744073709ULL;
 1056         clock_snap->fb_info.error = bt;
 1057 
 1058 #ifdef FFCLOCK
 1059         if (!fast)
 1060                 clock_snap->ffcount += delta;
 1061 
 1062         /* Record feed-forward clock leap second adjustment. */
 1063         ffi->leapsec_adjustment = cest.leapsec_total;
 1064         if (clock_snap->ffcount > cest.leapsec_next)
 1065                 ffi->leapsec_adjustment -= cest.leapsec;
 1066 
 1067         /* Record feed-forward clock status and error. */
 1068         clock_snap->ff_info.status = cest.status;
 1069         ffcount = clock_snap->ffcount - cest.update_ffcount;
 1070         ffclock_convert_delta(ffcount, cest.period, &bt);
 1071         /* 18446744073709 = int(2^64/1e12), err_bound_rate in [ps/s]. */
 1072         bintime_mul(&bt, cest.errb_rate * (uint64_t)18446744073709ULL);
 1073         /* 18446744073 = int(2^64 / 1e9), since err_abs in [ns]. */
 1074         bintime_addx(&bt, cest.errb_abs * (uint64_t)18446744073ULL);
 1075         clock_snap->ff_info.error = bt;
 1076 #endif
 1077 }
 1078 
 1079 /*
 1080  * Convert a sysclock snapshot into a struct bintime based on the specified
 1081  * clock source and flags.
 1082  */
 1083 int
 1084 sysclock_snap2bintime(struct sysclock_snap *cs, struct bintime *bt,
 1085     int whichclock, uint32_t flags)
 1086 {
 1087 #ifdef FFCLOCK
 1088         struct bintime bt2;
 1089         uint64_t period;
 1090 #endif
 1091 
 1092         switch (whichclock) {
 1093         case SYSCLOCK_FBCK:
 1094                 *bt = cs->fb_info.tick_time;
 1095 
 1096                 /* If snapshot was created with !fast, delta will be >0. */
 1097                 if (cs->delta > 0)
 1098                         bintime_addx(bt, cs->fb_info.th_scale * cs->delta);
 1099 
 1100                 if ((flags & FBCLOCK_UPTIME) == 0)
 1101                         bintime_add(bt, &boottimebin);
 1102                 break;
 1103 #ifdef FFCLOCK
 1104         case SYSCLOCK_FFWD:
 1105                 if (flags & FFCLOCK_LERP) {
 1106                         *bt = cs->ff_info.tick_time_lerp;
 1107                         period = cs->ff_info.period_lerp;
 1108                 } else {
 1109                         *bt = cs->ff_info.tick_time;
 1110                         period = cs->ff_info.period;
 1111                 }
 1112 
 1113                 /* If snapshot was created with !fast, delta will be >0. */
 1114                 if (cs->delta > 0) {
 1115                         ffclock_convert_delta(cs->delta, period, &bt2);
 1116                         bintime_add(bt, &bt2);
 1117                 }
 1118 
 1119                 /* Leap second adjustment. */
 1120                 if (flags & FFCLOCK_LEAPSEC)
 1121                         bt->sec -= cs->ff_info.leapsec_adjustment;
 1122 
 1123                 /* Boot time adjustment, for uptime/monotonic clocks. */
 1124                 if (flags & FFCLOCK_UPTIME)
 1125                         bintime_sub(bt, &ffclock_boottime);
 1126                 break;
 1127 #endif
 1128         default:
 1129                 return (EINVAL);
 1130                 break;
 1131         }
 1132 
 1133         return (0);
 1134 }
 1135 
 1136 /*
 1137  * Initialize a new timecounter and possibly use it.
 1138  */
 1139 void
 1140 tc_init(struct timecounter *tc)
 1141 {
 1142         u_int u;
 1143         struct sysctl_oid *tc_root;
 1144 
 1145         u = tc->tc_frequency / tc->tc_counter_mask;
 1146         /* XXX: We need some margin here, 10% is a guess */
 1147         u *= 11;
 1148         u /= 10;
 1149         if (u > hz && tc->tc_quality >= 0) {
 1150                 tc->tc_quality = -2000;
 1151                 if (bootverbose) {
 1152                         printf("Timecounter \"%s\" frequency %ju Hz",
 1153                             tc->tc_name, (uintmax_t)tc->tc_frequency);
 1154                         printf(" -- Insufficient hz, needs at least %u\n", u);
 1155                 }
 1156         } else if (tc->tc_quality >= 0 || bootverbose) {
 1157                 printf("Timecounter \"%s\" frequency %ju Hz quality %d\n",
 1158                     tc->tc_name, (uintmax_t)tc->tc_frequency,
 1159                     tc->tc_quality);
 1160         }
 1161 
 1162         tc->tc_next = timecounters;
 1163         timecounters = tc;
 1164         /*
 1165          * Set up sysctl tree for this counter.
 1166          */
 1167         tc_root = SYSCTL_ADD_NODE(NULL,
 1168             SYSCTL_STATIC_CHILDREN(_kern_timecounter_tc), OID_AUTO, tc->tc_name,
 1169             CTLFLAG_RW, 0, "timecounter description");
 1170         SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
 1171             "mask", CTLFLAG_RD, &(tc->tc_counter_mask), 0,
 1172             "mask for implemented bits");
 1173         SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
 1174             "counter", CTLTYPE_UINT | CTLFLAG_RD, tc, sizeof(*tc),
 1175             sysctl_kern_timecounter_get, "IU", "current timecounter value");
 1176         SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
 1177             "frequency", CTLTYPE_U64 | CTLFLAG_RD, tc, sizeof(*tc),
 1178              sysctl_kern_timecounter_freq, "QU", "timecounter frequency");
 1179         SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
 1180             "quality", CTLFLAG_RD, &(tc->tc_quality), 0,
 1181             "goodness of time counter");
 1182         /*
 1183          * Never automatically use a timecounter with negative quality.
 1184          * Even though we run on the dummy counter, switching here may be
 1185          * worse since this timecounter may not be monotonous.
 1186          */
 1187         if (tc->tc_quality < 0)
 1188                 return;
 1189         if (tc->tc_quality < timecounter->tc_quality)
 1190                 return;
 1191         if (tc->tc_quality == timecounter->tc_quality &&
 1192             tc->tc_frequency < timecounter->tc_frequency)
 1193                 return;
 1194         (void)tc->tc_get_timecount(tc);
 1195         (void)tc->tc_get_timecount(tc);
 1196         timecounter = tc;
 1197 }
 1198 
 1199 /* Report the frequency of the current timecounter. */
 1200 uint64_t
 1201 tc_getfrequency(void)
 1202 {
 1203 
 1204         return (timehands->th_counter->tc_frequency);
 1205 }
 1206 
 1207 /*
 1208  * Step our concept of UTC.  This is done by modifying our estimate of
 1209  * when we booted.
 1210  * XXX: not locked.
 1211  */
 1212 void
 1213 tc_setclock(struct timespec *ts)
 1214 {
 1215         struct timespec tbef, taft;
 1216         struct bintime bt, bt2;
 1217 
 1218         cpu_tick_calibrate(1);
 1219         nanotime(&tbef);
 1220         timespec2bintime(ts, &bt);
 1221         binuptime(&bt2);
 1222         bintime_sub(&bt, &bt2);
 1223         bintime_add(&bt2, &boottimebin);
 1224         boottimebin = bt;
 1225         bintime2timeval(&bt, &boottime);
 1226 
 1227         /* XXX fiddle all the little crinkly bits around the fiords... */
 1228         tc_windup();
 1229         nanotime(&taft);
 1230         if (timestepwarnings) {
 1231                 log(LOG_INFO,
 1232                     "Time stepped from %jd.%09ld to %jd.%09ld (%jd.%09ld)\n",
 1233                     (intmax_t)tbef.tv_sec, tbef.tv_nsec,
 1234                     (intmax_t)taft.tv_sec, taft.tv_nsec,
 1235                     (intmax_t)ts->tv_sec, ts->tv_nsec);
 1236         }
 1237         cpu_tick_calibrate(1);
 1238 }
 1239 
 1240 /*
 1241  * Initialize the next struct timehands in the ring and make
 1242  * it the active timehands.  Along the way we might switch to a different
 1243  * timecounter and/or do seconds processing in NTP.  Slightly magic.
 1244  */
 1245 static void
 1246 tc_windup(void)
 1247 {
 1248         struct bintime bt;
 1249         struct timehands *th, *tho;
 1250         uint64_t scale;
 1251         u_int delta, ncount, ogen;
 1252         int i;
 1253         time_t t;
 1254 
 1255         /*
 1256          * Make the next timehands a copy of the current one, but do not
 1257          * overwrite the generation or next pointer.  While we update
 1258          * the contents, the generation must be zero.
 1259          */
 1260         tho = timehands;
 1261         th = tho->th_next;
 1262         ogen = th->th_generation;
 1263         th->th_generation = 0;
 1264         bcopy(tho, th, offsetof(struct timehands, th_generation));
 1265 
 1266         /*
 1267          * Capture a timecounter delta on the current timecounter and if
 1268          * changing timecounters, a counter value from the new timecounter.
 1269          * Update the offset fields accordingly.
 1270          */
 1271         delta = tc_delta(th);
 1272         if (th->th_counter != timecounter)
 1273                 ncount = timecounter->tc_get_timecount(timecounter);
 1274         else
 1275                 ncount = 0;
 1276 #ifdef FFCLOCK
 1277         ffclock_windup(delta);
 1278 #endif
 1279         th->th_offset_count += delta;
 1280         th->th_offset_count &= th->th_counter->tc_counter_mask;
 1281         while (delta > th->th_counter->tc_frequency) {
 1282                 /* Eat complete unadjusted seconds. */
 1283                 delta -= th->th_counter->tc_frequency;
 1284                 th->th_offset.sec++;
 1285         }
 1286         if ((delta > th->th_counter->tc_frequency / 2) &&
 1287             (th->th_scale * delta < ((uint64_t)1 << 63))) {
 1288                 /* The product th_scale * delta just barely overflows. */
 1289                 th->th_offset.sec++;
 1290         }
 1291         bintime_addx(&th->th_offset, th->th_scale * delta);
 1292 
 1293         /*
 1294          * Hardware latching timecounters may not generate interrupts on
 1295          * PPS events, so instead we poll them.  There is a finite risk that
 1296          * the hardware might capture a count which is later than the one we
 1297          * got above, and therefore possibly in the next NTP second which might
 1298          * have a different rate than the current NTP second.  It doesn't
 1299          * matter in practice.
 1300          */
 1301         if (tho->th_counter->tc_poll_pps)
 1302                 tho->th_counter->tc_poll_pps(tho->th_counter);
 1303 
 1304         /*
 1305          * Deal with NTP second processing.  The for loop normally
 1306          * iterates at most once, but in extreme situations it might
 1307          * keep NTP sane if timeouts are not run for several seconds.
 1308          * At boot, the time step can be large when the TOD hardware
 1309          * has been read, so on really large steps, we call
 1310          * ntp_update_second only twice.  We need to call it twice in
 1311          * case we missed a leap second.
 1312          */
 1313         bt = th->th_offset;
 1314         bintime_add(&bt, &boottimebin);
 1315         i = bt.sec - tho->th_microtime.tv_sec;
 1316         if (i > LARGE_STEP)
 1317                 i = 2;
 1318         for (; i > 0; i--) {
 1319                 t = bt.sec;
 1320                 ntp_update_second(&th->th_adjustment, &bt.sec);
 1321                 if (bt.sec != t)
 1322                         boottimebin.sec += bt.sec - t;
 1323         }
 1324         /* Update the UTC timestamps used by the get*() functions. */
 1325         /* XXX shouldn't do this here.  Should force non-`get' versions. */
 1326         bintime2timeval(&bt, &th->th_microtime);
 1327         bintime2timespec(&bt, &th->th_nanotime);
 1328 
 1329         /* Now is a good time to change timecounters. */
 1330         if (th->th_counter != timecounter) {
 1331 #ifndef __arm__
 1332                 if ((timecounter->tc_flags & TC_FLAGS_C2STOP) != 0)
 1333                         cpu_disable_c2_sleep++;
 1334                 if ((th->th_counter->tc_flags & TC_FLAGS_C2STOP) != 0)
 1335                         cpu_disable_c2_sleep--;
 1336 #endif
 1337                 th->th_counter = timecounter;
 1338                 th->th_offset_count = ncount;
 1339                 tc_min_ticktock_freq = max(1, timecounter->tc_frequency /
 1340                     (((uint64_t)timecounter->tc_counter_mask + 1) / 3));
 1341 #ifdef FFCLOCK
 1342                 ffclock_change_tc(th);
 1343 #endif
 1344         }
 1345 
 1346         /*-
 1347          * Recalculate the scaling factor.  We want the number of 1/2^64
 1348          * fractions of a second per period of the hardware counter, taking
 1349          * into account the th_adjustment factor which the NTP PLL/adjtime(2)
 1350          * processing provides us with.
 1351          *
 1352          * The th_adjustment is nanoseconds per second with 32 bit binary
 1353          * fraction and we want 64 bit binary fraction of second:
 1354          *
 1355          *       x = a * 2^32 / 10^9 = a * 4.294967296
 1356          *
 1357          * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
 1358          * we can only multiply by about 850 without overflowing, that
 1359          * leaves no suitably precise fractions for multiply before divide.
 1360          *
 1361          * Divide before multiply with a fraction of 2199/512 results in a
 1362          * systematic undercompensation of 10PPM of th_adjustment.  On a
 1363          * 5000PPM adjustment this is a 0.05PPM error.  This is acceptable.
 1364          *
 1365          * We happily sacrifice the lowest of the 64 bits of our result
 1366          * to the goddess of code clarity.
 1367          *
 1368          */
 1369         scale = (uint64_t)1 << 63;
 1370         scale += (th->th_adjustment / 1024) * 2199;
 1371         scale /= th->th_counter->tc_frequency;
 1372         th->th_scale = scale * 2;
 1373 
 1374         /*
 1375          * Now that the struct timehands is again consistent, set the new
 1376          * generation number, making sure to not make it zero.
 1377          */
 1378         if (++ogen == 0)
 1379                 ogen = 1;
 1380         th->th_generation = ogen;
 1381 
 1382         /* Go live with the new struct timehands. */
 1383 #ifdef FFCLOCK
 1384         switch (sysclock_active) {
 1385         case SYSCLOCK_FBCK:
 1386 #endif
 1387                 time_second = th->th_microtime.tv_sec;
 1388                 time_uptime = th->th_offset.sec;
 1389 #ifdef FFCLOCK
 1390                 break;
 1391         case SYSCLOCK_FFWD:
 1392                 time_second = fftimehands->tick_time_lerp.sec;
 1393                 time_uptime = fftimehands->tick_time_lerp.sec - ffclock_boottime.sec;
 1394                 break;
 1395         }
 1396 #endif
 1397 
 1398         timehands = th;
 1399         timekeep_push_vdso();
 1400 }
 1401 
 1402 /* Report or change the active timecounter hardware. */
 1403 static int
 1404 sysctl_kern_timecounter_hardware(SYSCTL_HANDLER_ARGS)
 1405 {
 1406         char newname[32];
 1407         struct timecounter *newtc, *tc;
 1408         int error;
 1409 
 1410         tc = timecounter;
 1411         strlcpy(newname, tc->tc_name, sizeof(newname));
 1412 
 1413         error = sysctl_handle_string(oidp, &newname[0], sizeof(newname), req);
 1414         if (error != 0 || req->newptr == NULL ||
 1415             strcmp(newname, tc->tc_name) == 0)
 1416                 return (error);
 1417         for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
 1418                 if (strcmp(newname, newtc->tc_name) != 0)
 1419                         continue;
 1420 
 1421                 /* Warm up new timecounter. */
 1422                 (void)newtc->tc_get_timecount(newtc);
 1423                 (void)newtc->tc_get_timecount(newtc);
 1424 
 1425                 timecounter = newtc;
 1426                 timekeep_push_vdso();
 1427                 return (0);
 1428         }
 1429         return (EINVAL);
 1430 }
 1431 
 1432 SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware, CTLTYPE_STRING | CTLFLAG_RW,
 1433     0, 0, sysctl_kern_timecounter_hardware, "A",
 1434     "Timecounter hardware selected");
 1435 
 1436 
 1437 /* Report or change the active timecounter hardware. */
 1438 static int
 1439 sysctl_kern_timecounter_choice(SYSCTL_HANDLER_ARGS)
 1440 {
 1441         char buf[32], *spc;
 1442         struct timecounter *tc;
 1443         int error;
 1444 
 1445         spc = "";
 1446         error = 0;
 1447         for (tc = timecounters; error == 0 && tc != NULL; tc = tc->tc_next) {
 1448                 sprintf(buf, "%s%s(%d)",
 1449                     spc, tc->tc_name, tc->tc_quality);
 1450                 error = SYSCTL_OUT(req, buf, strlen(buf));
 1451                 spc = " ";
 1452         }
 1453         return (error);
 1454 }
 1455 
 1456 SYSCTL_PROC(_kern_timecounter, OID_AUTO, choice, CTLTYPE_STRING | CTLFLAG_RD,
 1457     0, 0, sysctl_kern_timecounter_choice, "A", "Timecounter hardware detected");
 1458 
 1459 /*
 1460  * RFC 2783 PPS-API implementation.
 1461  */
 1462 
 1463 /*
 1464  *  Return true if the driver is aware of the abi version extensions in the
 1465  *  pps_state structure, and it supports at least the given abi version number.
 1466  */
 1467 static inline int
 1468 abi_aware(struct pps_state *pps, int vers)
 1469 {
 1470 
 1471         return ((pps->kcmode & KCMODE_ABIFLAG) && pps->driver_abi >= vers);
 1472 }
 1473 
 1474 static int
 1475 pps_fetch(struct pps_fetch_args *fapi, struct pps_state *pps)
 1476 {
 1477         int err, timo;
 1478         pps_seq_t aseq, cseq;
 1479         struct timeval tv;
 1480 
 1481         if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
 1482                 return (EINVAL);
 1483 
 1484         /*
 1485          * If no timeout is requested, immediately return whatever values were
 1486          * most recently captured.  If timeout seconds is -1, that's a request
 1487          * to block without a timeout.  WITNESS won't let us sleep forever
 1488          * without a lock (we really don't need a lock), so just repeatedly
 1489          * sleep a long time.
 1490          */
 1491         if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec) {
 1492                 if (fapi->timeout.tv_sec == -1)
 1493                         timo = 0x7fffffff;
 1494                 else {
 1495                         tv.tv_sec = fapi->timeout.tv_sec;
 1496                         tv.tv_usec = fapi->timeout.tv_nsec / 1000;
 1497                         timo = tvtohz(&tv);
 1498                 }
 1499                 aseq = pps->ppsinfo.assert_sequence;
 1500                 cseq = pps->ppsinfo.clear_sequence;
 1501                 while (aseq == pps->ppsinfo.assert_sequence &&
 1502                     cseq == pps->ppsinfo.clear_sequence) {
 1503                         if (abi_aware(pps, 1) && pps->driver_mtx != NULL) {
 1504                                 if (pps->flags & PPSFLAG_MTX_SPIN) {
 1505                                         err = msleep_spin(pps, pps->driver_mtx,
 1506                                             "ppsfch", timo);
 1507                                 } else {
 1508                                         err = msleep(pps, pps->driver_mtx, PCATCH,
 1509                                             "ppsfch", timo);
 1510                                 }
 1511                         } else {
 1512                                 err = tsleep(pps, PCATCH, "ppsfch", timo);
 1513                         }
 1514                         if (err == EWOULDBLOCK && fapi->timeout.tv_sec == -1) {
 1515                                 continue;
 1516                         } else if (err != 0) {
 1517                                 return (err);
 1518                         }
 1519                 }
 1520         }
 1521 
 1522         pps->ppsinfo.current_mode = pps->ppsparam.mode;
 1523         fapi->pps_info_buf = pps->ppsinfo;
 1524 
 1525         return (0);
 1526 }
 1527 
 1528 int
 1529 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
 1530 {
 1531         pps_params_t *app;
 1532         struct pps_fetch_args *fapi;
 1533 #ifdef FFCLOCK
 1534         struct pps_fetch_ffc_args *fapi_ffc;
 1535 #endif
 1536 #ifdef PPS_SYNC
 1537         struct pps_kcbind_args *kapi;
 1538 #endif
 1539 
 1540         KASSERT(pps != NULL, ("NULL pps pointer in pps_ioctl"));
 1541         switch (cmd) {
 1542         case PPS_IOC_CREATE:
 1543                 return (0);
 1544         case PPS_IOC_DESTROY:
 1545                 return (0);
 1546         case PPS_IOC_SETPARAMS:
 1547                 app = (pps_params_t *)data;
 1548                 if (app->mode & ~pps->ppscap)
 1549                         return (EINVAL);
 1550 #ifdef FFCLOCK
 1551                 /* Ensure only a single clock is selected for ffc timestamp. */
 1552                 if ((app->mode & PPS_TSCLK_MASK) == PPS_TSCLK_MASK)
 1553                         return (EINVAL);
 1554 #endif
 1555                 pps->ppsparam = *app;
 1556                 return (0);
 1557         case PPS_IOC_GETPARAMS:
 1558                 app = (pps_params_t *)data;
 1559                 *app = pps->ppsparam;
 1560                 app->api_version = PPS_API_VERS_1;
 1561                 return (0);
 1562         case PPS_IOC_GETCAP:
 1563                 *(int*)data = pps->ppscap;
 1564                 return (0);
 1565         case PPS_IOC_FETCH:
 1566                 fapi = (struct pps_fetch_args *)data;
 1567                 return (pps_fetch(fapi, pps));
 1568 #ifdef FFCLOCK
 1569         case PPS_IOC_FETCH_FFCOUNTER:
 1570                 fapi_ffc = (struct pps_fetch_ffc_args *)data;
 1571                 if (fapi_ffc->tsformat && fapi_ffc->tsformat !=
 1572                     PPS_TSFMT_TSPEC)
 1573                         return (EINVAL);
 1574                 if (fapi_ffc->timeout.tv_sec || fapi_ffc->timeout.tv_nsec)
 1575                         return (EOPNOTSUPP);
 1576                 pps->ppsinfo_ffc.current_mode = pps->ppsparam.mode;
 1577                 fapi_ffc->pps_info_buf_ffc = pps->ppsinfo_ffc;
 1578                 /* Overwrite timestamps if feedback clock selected. */
 1579                 switch (pps->ppsparam.mode & PPS_TSCLK_MASK) {
 1580                 case PPS_TSCLK_FBCK:
 1581                         fapi_ffc->pps_info_buf_ffc.assert_timestamp =
 1582                             pps->ppsinfo.assert_timestamp;
 1583                         fapi_ffc->pps_info_buf_ffc.clear_timestamp =
 1584                             pps->ppsinfo.clear_timestamp;
 1585                         break;
 1586                 case PPS_TSCLK_FFWD:
 1587                         break;
 1588                 default:
 1589                         break;
 1590                 }
 1591                 return (0);
 1592 #endif /* FFCLOCK */
 1593         case PPS_IOC_KCBIND:
 1594 #ifdef PPS_SYNC
 1595                 kapi = (struct pps_kcbind_args *)data;
 1596                 /* XXX Only root should be able to do this */
 1597                 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
 1598                         return (EINVAL);
 1599                 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
 1600                         return (EINVAL);
 1601                 if (kapi->edge & ~pps->ppscap)
 1602                         return (EINVAL);
 1603                 pps->kcmode = (kapi->edge & KCMODE_EDGEMASK) |
 1604                     (pps->kcmode & KCMODE_ABIFLAG);
 1605                 return (0);
 1606 #else
 1607                 return (EOPNOTSUPP);
 1608 #endif
 1609         default:
 1610                 return (ENOIOCTL);
 1611         }
 1612 }
 1613 
 1614 void
 1615 pps_init(struct pps_state *pps)
 1616 {
 1617         pps->ppscap |= PPS_TSFMT_TSPEC | PPS_CANWAIT;
 1618         if (pps->ppscap & PPS_CAPTUREASSERT)
 1619                 pps->ppscap |= PPS_OFFSETASSERT;
 1620         if (pps->ppscap & PPS_CAPTURECLEAR)
 1621                 pps->ppscap |= PPS_OFFSETCLEAR;
 1622 #ifdef FFCLOCK
 1623         pps->ppscap |= PPS_TSCLK_MASK;
 1624 #endif
 1625         pps->kcmode &= ~KCMODE_ABIFLAG;
 1626 }
 1627 
 1628 void
 1629 pps_init_abi(struct pps_state *pps)
 1630 {
 1631 
 1632         pps_init(pps);
 1633         if (pps->driver_abi > 0) {
 1634                 pps->kcmode |= KCMODE_ABIFLAG;
 1635                 pps->kernel_abi = PPS_ABI_VERSION;
 1636         }
 1637 }
 1638 
 1639 void
 1640 pps_capture(struct pps_state *pps)
 1641 {
 1642         struct timehands *th;
 1643 
 1644         KASSERT(pps != NULL, ("NULL pps pointer in pps_capture"));
 1645         th = timehands;
 1646         pps->capgen = th->th_generation;
 1647         pps->capth = th;
 1648 #ifdef FFCLOCK
 1649         pps->capffth = fftimehands;
 1650 #endif
 1651         pps->capcount = th->th_counter->tc_get_timecount(th->th_counter);
 1652         if (pps->capgen != th->th_generation)
 1653                 pps->capgen = 0;
 1654 }
 1655 
 1656 void
 1657 pps_event(struct pps_state *pps, int event)
 1658 {
 1659         struct bintime bt;
 1660         struct timespec ts, *tsp, *osp;
 1661         u_int tcount, *pcount;
 1662         int foff, fhard;
 1663         pps_seq_t *pseq;
 1664 #ifdef FFCLOCK
 1665         struct timespec *tsp_ffc;
 1666         pps_seq_t *pseq_ffc;
 1667         ffcounter *ffcount;
 1668 #endif
 1669 
 1670         KASSERT(pps != NULL, ("NULL pps pointer in pps_event"));
 1671         /* If the timecounter was wound up underneath us, bail out. */
 1672         if (pps->capgen == 0 || pps->capgen != pps->capth->th_generation)
 1673                 return;
 1674 
 1675         /* Things would be easier with arrays. */
 1676         if (event == PPS_CAPTUREASSERT) {
 1677                 tsp = &pps->ppsinfo.assert_timestamp;
 1678                 osp = &pps->ppsparam.assert_offset;
 1679                 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
 1680                 fhard = pps->kcmode & PPS_CAPTUREASSERT;
 1681                 pcount = &pps->ppscount[0];
 1682                 pseq = &pps->ppsinfo.assert_sequence;
 1683 #ifdef FFCLOCK
 1684                 ffcount = &pps->ppsinfo_ffc.assert_ffcount;
 1685                 tsp_ffc = &pps->ppsinfo_ffc.assert_timestamp;
 1686                 pseq_ffc = &pps->ppsinfo_ffc.assert_sequence;
 1687 #endif
 1688         } else {
 1689                 tsp = &pps->ppsinfo.clear_timestamp;
 1690                 osp = &pps->ppsparam.clear_offset;
 1691                 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
 1692                 fhard = pps->kcmode & PPS_CAPTURECLEAR;
 1693                 pcount = &pps->ppscount[1];
 1694                 pseq = &pps->ppsinfo.clear_sequence;
 1695 #ifdef FFCLOCK
 1696                 ffcount = &pps->ppsinfo_ffc.clear_ffcount;
 1697                 tsp_ffc = &pps->ppsinfo_ffc.clear_timestamp;
 1698                 pseq_ffc = &pps->ppsinfo_ffc.clear_sequence;
 1699 #endif
 1700         }
 1701 
 1702         /*
 1703          * If the timecounter changed, we cannot compare the count values, so
 1704          * we have to drop the rest of the PPS-stuff until the next event.
 1705          */
 1706         if (pps->ppstc != pps->capth->th_counter) {
 1707                 pps->ppstc = pps->capth->th_counter;
 1708                 *pcount = pps->capcount;
 1709                 pps->ppscount[2] = pps->capcount;
 1710                 return;
 1711         }
 1712 
 1713         /* Convert the count to a timespec. */
 1714         tcount = pps->capcount - pps->capth->th_offset_count;
 1715         tcount &= pps->capth->th_counter->tc_counter_mask;
 1716         bt = pps->capth->th_offset;
 1717         bintime_addx(&bt, pps->capth->th_scale * tcount);
 1718         bintime_add(&bt, &boottimebin);
 1719         bintime2timespec(&bt, &ts);
 1720 
 1721         /* If the timecounter was wound up underneath us, bail out. */
 1722         if (pps->capgen != pps->capth->th_generation)
 1723                 return;
 1724 
 1725         *pcount = pps->capcount;
 1726         (*pseq)++;
 1727         *tsp = ts;
 1728 
 1729         if (foff) {
 1730                 timespecadd(tsp, osp);
 1731                 if (tsp->tv_nsec < 0) {
 1732                         tsp->tv_nsec += 1000000000;
 1733                         tsp->tv_sec -= 1;
 1734                 }
 1735         }
 1736 
 1737 #ifdef FFCLOCK
 1738         *ffcount = pps->capffth->tick_ffcount + tcount;
 1739         bt = pps->capffth->tick_time;
 1740         ffclock_convert_delta(tcount, pps->capffth->cest.period, &bt);
 1741         bintime_add(&bt, &pps->capffth->tick_time);
 1742         bintime2timespec(&bt, &ts);
 1743         (*pseq_ffc)++;
 1744         *tsp_ffc = ts;
 1745 #endif
 1746 
 1747 #ifdef PPS_SYNC
 1748         if (fhard) {
 1749                 uint64_t scale;
 1750 
 1751                 /*
 1752                  * Feed the NTP PLL/FLL.
 1753                  * The FLL wants to know how many (hardware) nanoseconds
 1754                  * elapsed since the previous event.
 1755                  */
 1756                 tcount = pps->capcount - pps->ppscount[2];
 1757                 pps->ppscount[2] = pps->capcount;
 1758                 tcount &= pps->capth->th_counter->tc_counter_mask;
 1759                 scale = (uint64_t)1 << 63;
 1760                 scale /= pps->capth->th_counter->tc_frequency;
 1761                 scale *= 2;
 1762                 bt.sec = 0;
 1763                 bt.frac = 0;
 1764                 bintime_addx(&bt, scale * tcount);
 1765                 bintime2timespec(&bt, &ts);
 1766                 hardpps(tsp, ts.tv_nsec + 1000000000 * ts.tv_sec);
 1767         }
 1768 #endif
 1769 
 1770         /* Wakeup anyone sleeping in pps_fetch().  */
 1771         wakeup(pps);
 1772 }
 1773 
 1774 /*
 1775  * Timecounters need to be updated every so often to prevent the hardware
 1776  * counter from overflowing.  Updating also recalculates the cached values
 1777  * used by the get*() family of functions, so their precision depends on
 1778  * the update frequency.
 1779  */
 1780 
 1781 static int tc_tick;
 1782 SYSCTL_INT(_kern_timecounter, OID_AUTO, tick, CTLFLAG_RD, &tc_tick, 0,
 1783     "Approximate number of hardclock ticks in a millisecond");
 1784 
 1785 void
 1786 tc_ticktock(int cnt)
 1787 {
 1788         static int count;
 1789 
 1790         count += cnt;
 1791         if (count < tc_tick)
 1792                 return;
 1793         count = 0;
 1794         tc_windup();
 1795 }
 1796 
 1797 static void __inline
 1798 tc_adjprecision(void)
 1799 {
 1800         int t;
 1801 
 1802         if (tc_timepercentage > 0) {
 1803                 t = (99 + tc_timepercentage) / tc_timepercentage;
 1804                 tc_precexp = fls(t + (t >> 1)) - 1;
 1805                 FREQ2BT(hz / tc_tick, &bt_timethreshold);
 1806                 FREQ2BT(hz, &bt_tickthreshold);
 1807                 bintime_shift(&bt_timethreshold, tc_precexp);
 1808                 bintime_shift(&bt_tickthreshold, tc_precexp);
 1809         } else {
 1810                 tc_precexp = 31;
 1811                 bt_timethreshold.sec = INT_MAX;
 1812                 bt_timethreshold.frac = ~(uint64_t)0;
 1813                 bt_tickthreshold = bt_timethreshold;
 1814         }
 1815         sbt_timethreshold = bttosbt(bt_timethreshold);
 1816         sbt_tickthreshold = bttosbt(bt_tickthreshold);
 1817 }
 1818 
 1819 static int
 1820 sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS)
 1821 {
 1822         int error, val;
 1823 
 1824         val = tc_timepercentage;
 1825         error = sysctl_handle_int(oidp, &val, 0, req);
 1826         if (error != 0 || req->newptr == NULL)
 1827                 return (error);
 1828         tc_timepercentage = val;
 1829         tc_adjprecision();
 1830         return (0);
 1831 }
 1832 
 1833 static void
 1834 inittimecounter(void *dummy)
 1835 {
 1836         u_int p;
 1837         int tick_rate;
 1838 
 1839         /*
 1840          * Set the initial timeout to
 1841          * max(1, <approx. number of hardclock ticks in a millisecond>).
 1842          * People should probably not use the sysctl to set the timeout
 1843          * to smaller than its inital value, since that value is the
 1844          * smallest reasonable one.  If they want better timestamps they
 1845          * should use the non-"get"* functions.
 1846          */
 1847         if (hz > 1000)
 1848                 tc_tick = (hz + 500) / 1000;
 1849         else
 1850                 tc_tick = 1;
 1851         tc_adjprecision();
 1852         FREQ2BT(hz, &tick_bt);
 1853         tick_sbt = bttosbt(tick_bt);
 1854         tick_rate = hz / tc_tick;
 1855         FREQ2BT(tick_rate, &tc_tick_bt);
 1856         tc_tick_sbt = bttosbt(tc_tick_bt);
 1857         p = (tc_tick * 1000000) / hz;
 1858         printf("Timecounters tick every %d.%03u msec\n", p / 1000, p % 1000);
 1859 
 1860 #ifdef FFCLOCK
 1861         ffclock_init();
 1862 #endif
 1863         /* warm up new timecounter (again) and get rolling. */
 1864         (void)timecounter->tc_get_timecount(timecounter);
 1865         (void)timecounter->tc_get_timecount(timecounter);
 1866         tc_windup();
 1867 }
 1868 
 1869 SYSINIT(timecounter, SI_SUB_CLOCKS, SI_ORDER_SECOND, inittimecounter, NULL);
 1870 
 1871 /* Cpu tick handling -------------------------------------------------*/
 1872 
 1873 static int cpu_tick_variable;
 1874 static uint64_t cpu_tick_frequency;
 1875 
 1876 static uint64_t
 1877 tc_cpu_ticks(void)
 1878 {
 1879         static uint64_t base;
 1880         static unsigned last;
 1881         unsigned u;
 1882         struct timecounter *tc;
 1883 
 1884         tc = timehands->th_counter;
 1885         u = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
 1886         if (u < last)
 1887                 base += (uint64_t)tc->tc_counter_mask + 1;
 1888         last = u;
 1889         return (u + base);
 1890 }
 1891 
 1892 void
 1893 cpu_tick_calibration(void)
 1894 {
 1895         static time_t last_calib;
 1896 
 1897         if (time_uptime != last_calib && !(time_uptime & 0xf)) {
 1898                 cpu_tick_calibrate(0);
 1899                 last_calib = time_uptime;
 1900         }
 1901 }
 1902 
 1903 /*
 1904  * This function gets called every 16 seconds on only one designated
 1905  * CPU in the system from hardclock() via cpu_tick_calibration()().
 1906  *
 1907  * Whenever the real time clock is stepped we get called with reset=1
 1908  * to make sure we handle suspend/resume and similar events correctly.
 1909  */
 1910 
 1911 static void
 1912 cpu_tick_calibrate(int reset)
 1913 {
 1914         static uint64_t c_last;
 1915         uint64_t c_this, c_delta;
 1916         static struct bintime  t_last;
 1917         struct bintime t_this, t_delta;
 1918         uint32_t divi;
 1919 
 1920         if (reset) {
 1921                 /* The clock was stepped, abort & reset */
 1922                 t_last.sec = 0;
 1923                 return;
 1924         }
 1925 
 1926         /* we don't calibrate fixed rate cputicks */
 1927         if (!cpu_tick_variable)
 1928                 return;
 1929 
 1930         getbinuptime(&t_this);
 1931         c_this = cpu_ticks();
 1932         if (t_last.sec != 0) {
 1933                 c_delta = c_this - c_last;
 1934                 t_delta = t_this;
 1935                 bintime_sub(&t_delta, &t_last);
 1936                 /*
 1937                  * Headroom:
 1938                  *      2^(64-20) / 16[s] =
 1939                  *      2^(44) / 16[s] =
 1940                  *      17.592.186.044.416 / 16 =
 1941                  *      1.099.511.627.776 [Hz]
 1942                  */
 1943                 divi = t_delta.sec << 20;
 1944                 divi |= t_delta.frac >> (64 - 20);
 1945                 c_delta <<= 20;
 1946                 c_delta /= divi;
 1947                 if (c_delta > cpu_tick_frequency) {
 1948                         if (0 && bootverbose)
 1949                                 printf("cpu_tick increased to %ju Hz\n",
 1950                                     c_delta);
 1951                         cpu_tick_frequency = c_delta;
 1952                 }
 1953         }
 1954         c_last = c_this;
 1955         t_last = t_this;
 1956 }
 1957 
 1958 void
 1959 set_cputicker(cpu_tick_f *func, uint64_t freq, unsigned var)
 1960 {
 1961 
 1962         if (func == NULL) {
 1963                 cpu_ticks = tc_cpu_ticks;
 1964         } else {
 1965                 cpu_tick_frequency = freq;
 1966                 cpu_tick_variable = var;
 1967                 cpu_ticks = func;
 1968         }
 1969 }
 1970 
 1971 uint64_t
 1972 cpu_tickrate(void)
 1973 {
 1974 
 1975         if (cpu_ticks == tc_cpu_ticks) 
 1976                 return (tc_getfrequency());
 1977         return (cpu_tick_frequency);
 1978 }
 1979 
 1980 /*
 1981  * We need to be slightly careful converting cputicks to microseconds.
 1982  * There is plenty of margin in 64 bits of microseconds (half a million
 1983  * years) and in 64 bits at 4 GHz (146 years), but if we do a multiply
 1984  * before divide conversion (to retain precision) we find that the
 1985  * margin shrinks to 1.5 hours (one millionth of 146y).
 1986  * With a three prong approach we never lose significant bits, no
 1987  * matter what the cputick rate and length of timeinterval is.
 1988  */
 1989 
 1990 uint64_t
 1991 cputick2usec(uint64_t tick)
 1992 {
 1993 
 1994         if (tick > 18446744073709551LL)         /* floor(2^64 / 1000) */
 1995                 return (tick / (cpu_tickrate() / 1000000LL));
 1996         else if (tick > 18446744073709LL)       /* floor(2^64 / 1000000) */
 1997                 return ((tick * 1000LL) / (cpu_tickrate() / 1000LL));
 1998         else
 1999                 return ((tick * 1000000LL) / cpu_tickrate());
 2000 }
 2001 
 2002 cpu_tick_f      *cpu_ticks = tc_cpu_ticks;
 2003 
 2004 static int vdso_th_enable = 1;
 2005 static int
 2006 sysctl_fast_gettime(SYSCTL_HANDLER_ARGS)
 2007 {
 2008         int old_vdso_th_enable, error;
 2009 
 2010         old_vdso_th_enable = vdso_th_enable;
 2011         error = sysctl_handle_int(oidp, &old_vdso_th_enable, 0, req);
 2012         if (error != 0)
 2013                 return (error);
 2014         vdso_th_enable = old_vdso_th_enable;
 2015         timekeep_push_vdso();
 2016         return (0);
 2017 }
 2018 SYSCTL_PROC(_kern_timecounter, OID_AUTO, fast_gettime,
 2019     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
 2020     NULL, 0, sysctl_fast_gettime, "I", "Enable fast time of day");
 2021 
 2022 uint32_t
 2023 tc_fill_vdso_timehands(struct vdso_timehands *vdso_th)
 2024 {
 2025         struct timehands *th;
 2026         uint32_t enabled;
 2027 
 2028         th = timehands;
 2029         vdso_th->th_algo = VDSO_TH_ALGO_1;
 2030         vdso_th->th_scale = th->th_scale;
 2031         vdso_th->th_offset_count = th->th_offset_count;
 2032         vdso_th->th_counter_mask = th->th_counter->tc_counter_mask;
 2033         vdso_th->th_offset = th->th_offset;
 2034         vdso_th->th_boottime = boottimebin;
 2035         enabled = cpu_fill_vdso_timehands(vdso_th);
 2036         if (!vdso_th_enable)
 2037                 enabled = 0;
 2038         return (enabled);
 2039 }
 2040 
 2041 #ifdef COMPAT_FREEBSD32
 2042 uint32_t
 2043 tc_fill_vdso_timehands32(struct vdso_timehands32 *vdso_th32)
 2044 {
 2045         struct timehands *th;
 2046         uint32_t enabled;
 2047 
 2048         th = timehands;
 2049         vdso_th32->th_algo = VDSO_TH_ALGO_1;
 2050         *(uint64_t *)&vdso_th32->th_scale[0] = th->th_scale;
 2051         vdso_th32->th_offset_count = th->th_offset_count;
 2052         vdso_th32->th_counter_mask = th->th_counter->tc_counter_mask;
 2053         vdso_th32->th_offset.sec = th->th_offset.sec;
 2054         *(uint64_t *)&vdso_th32->th_offset.frac[0] = th->th_offset.frac;
 2055         vdso_th32->th_boottime.sec = boottimebin.sec;
 2056         *(uint64_t *)&vdso_th32->th_boottime.frac[0] = boottimebin.frac;
 2057         enabled = cpu_fill_vdso_timehands32(vdso_th32);
 2058         if (!vdso_th_enable)
 2059                 enabled = 0;
 2060         return (enabled);
 2061 }
 2062 #endif

Cache object: f1ada5231f22d525985b516a3c8c3ead


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.