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