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

Cache object: 8c8f4ffe30a5844329fbd3433c2e5171


[ 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.