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