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