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