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