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