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