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