xref: /freebsd/sys/kern/kern_tc.c (revision da5137ab)
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 static __inline void
217 bintime_add_tc_delta(struct bintime *bt, uint64_t scale,
218     uint64_t large_delta, uint64_t delta)
219 {
220 	uint64_t x;
221 
222 	if (__predict_false(delta >= large_delta)) {
223 		/* Avoid overflow for scale * delta. */
224 		x = (scale >> 32) * delta;
225 		bt->sec += x >> 32;
226 		bintime_addx(bt, x << 32);
227 		bintime_addx(bt, (scale & 0xffffffff) * delta);
228 	} else {
229 		bintime_addx(bt, scale * delta);
230 	}
231 }
232 
233 /*
234  * Functions for reading the time.  We have to loop until we are sure that
235  * the timehands that we operated on was not updated under our feet.  See
236  * the comment in <sys/time.h> for a description of these 12 functions.
237  */
238 
239 static __inline void
240 bintime_off(struct bintime *bt, u_int off)
241 {
242 	struct timehands *th;
243 	struct bintime *btp;
244 	uint64_t scale;
245 	u_int delta, gen, large_delta;
246 
247 	do {
248 		th = timehands;
249 		gen = atomic_load_acq_int(&th->th_generation);
250 		btp = (struct bintime *)((vm_offset_t)th + off);
251 		*bt = *btp;
252 		scale = th->th_scale;
253 		delta = tc_delta(th);
254 		large_delta = th->th_large_delta;
255 		atomic_thread_fence_acq();
256 	} while (gen == 0 || gen != th->th_generation);
257 
258 	bintime_add_tc_delta(bt, scale, large_delta, delta);
259 }
260 #define	GETTHBINTIME(dst, member)					\
261 do {									\
262 	_Static_assert(_Generic(((struct timehands *)NULL)->member,	\
263 	    struct bintime: 1, default: 0) == 1,			\
264 	    "struct timehands member is not of struct bintime type");	\
265 	bintime_off(dst, __offsetof(struct timehands, member));		\
266 } while (0)
267 
268 static __inline void
269 getthmember(void *out, size_t out_size, u_int off)
270 {
271 	struct timehands *th;
272 	u_int gen;
273 
274 	do {
275 		th = timehands;
276 		gen = atomic_load_acq_int(&th->th_generation);
277 		memcpy(out, (char *)th + off, out_size);
278 		atomic_thread_fence_acq();
279 	} while (gen == 0 || gen != th->th_generation);
280 }
281 #define	GETTHMEMBER(dst, member)					\
282 do {									\
283 	_Static_assert(_Generic(*dst,					\
284 	    __typeof(((struct timehands *)NULL)->member): 1,		\
285 	    default: 0) == 1,						\
286 	    "*dst and struct timehands member have different types");	\
287 	getthmember(dst, sizeof(*dst), __offsetof(struct timehands,	\
288 	    member));							\
289 } while (0)
290 
291 #ifdef FFCLOCK
292 void
293 fbclock_binuptime(struct bintime *bt)
294 {
295 
296 	GETTHBINTIME(bt, th_offset);
297 }
298 
299 void
300 fbclock_nanouptime(struct timespec *tsp)
301 {
302 	struct bintime bt;
303 
304 	fbclock_binuptime(&bt);
305 	bintime2timespec(&bt, tsp);
306 }
307 
308 void
309 fbclock_microuptime(struct timeval *tvp)
310 {
311 	struct bintime bt;
312 
313 	fbclock_binuptime(&bt);
314 	bintime2timeval(&bt, tvp);
315 }
316 
317 void
318 fbclock_bintime(struct bintime *bt)
319 {
320 
321 	GETTHBINTIME(bt, th_bintime);
322 }
323 
324 void
325 fbclock_nanotime(struct timespec *tsp)
326 {
327 	struct bintime bt;
328 
329 	fbclock_bintime(&bt);
330 	bintime2timespec(&bt, tsp);
331 }
332 
333 void
334 fbclock_microtime(struct timeval *tvp)
335 {
336 	struct bintime bt;
337 
338 	fbclock_bintime(&bt);
339 	bintime2timeval(&bt, tvp);
340 }
341 
342 void
343 fbclock_getbinuptime(struct bintime *bt)
344 {
345 
346 	GETTHMEMBER(bt, th_offset);
347 }
348 
349 void
350 fbclock_getnanouptime(struct timespec *tsp)
351 {
352 	struct bintime bt;
353 
354 	GETTHMEMBER(&bt, th_offset);
355 	bintime2timespec(&bt, tsp);
356 }
357 
358 void
359 fbclock_getmicrouptime(struct timeval *tvp)
360 {
361 	struct bintime bt;
362 
363 	GETTHMEMBER(&bt, th_offset);
364 	bintime2timeval(&bt, tvp);
365 }
366 
367 void
368 fbclock_getbintime(struct bintime *bt)
369 {
370 
371 	GETTHMEMBER(bt, th_bintime);
372 }
373 
374 void
375 fbclock_getnanotime(struct timespec *tsp)
376 {
377 
378 	GETTHMEMBER(tsp, th_nanotime);
379 }
380 
381 void
382 fbclock_getmicrotime(struct timeval *tvp)
383 {
384 
385 	GETTHMEMBER(tvp, th_microtime);
386 }
387 #else /* !FFCLOCK */
388 
389 void
390 binuptime(struct bintime *bt)
391 {
392 
393 	GETTHBINTIME(bt, th_offset);
394 }
395 
396 void
397 nanouptime(struct timespec *tsp)
398 {
399 	struct bintime bt;
400 
401 	binuptime(&bt);
402 	bintime2timespec(&bt, tsp);
403 }
404 
405 void
406 microuptime(struct timeval *tvp)
407 {
408 	struct bintime bt;
409 
410 	binuptime(&bt);
411 	bintime2timeval(&bt, tvp);
412 }
413 
414 void
415 bintime(struct bintime *bt)
416 {
417 
418 	GETTHBINTIME(bt, th_bintime);
419 }
420 
421 void
422 nanotime(struct timespec *tsp)
423 {
424 	struct bintime bt;
425 
426 	bintime(&bt);
427 	bintime2timespec(&bt, tsp);
428 }
429 
430 void
431 microtime(struct timeval *tvp)
432 {
433 	struct bintime bt;
434 
435 	bintime(&bt);
436 	bintime2timeval(&bt, tvp);
437 }
438 
439 void
440 getbinuptime(struct bintime *bt)
441 {
442 
443 	GETTHMEMBER(bt, th_offset);
444 }
445 
446 void
447 getnanouptime(struct timespec *tsp)
448 {
449 	struct bintime bt;
450 
451 	GETTHMEMBER(&bt, th_offset);
452 	bintime2timespec(&bt, tsp);
453 }
454 
455 void
456 getmicrouptime(struct timeval *tvp)
457 {
458 	struct bintime bt;
459 
460 	GETTHMEMBER(&bt, th_offset);
461 	bintime2timeval(&bt, tvp);
462 }
463 
464 void
465 getbintime(struct bintime *bt)
466 {
467 
468 	GETTHMEMBER(bt, th_bintime);
469 }
470 
471 void
472 getnanotime(struct timespec *tsp)
473 {
474 
475 	GETTHMEMBER(tsp, th_nanotime);
476 }
477 
478 void
479 getmicrotime(struct timeval *tvp)
480 {
481 
482 	GETTHMEMBER(tvp, th_microtime);
483 }
484 #endif /* FFCLOCK */
485 
486 void
487 getboottime(struct timeval *boottime)
488 {
489 	struct bintime boottimebin;
490 
491 	getboottimebin(&boottimebin);
492 	bintime2timeval(&boottimebin, boottime);
493 }
494 
495 void
496 getboottimebin(struct bintime *boottimebin)
497 {
498 
499 	GETTHMEMBER(boottimebin, th_boottime);
500 }
501 
502 #ifdef FFCLOCK
503 /*
504  * Support for feed-forward synchronization algorithms. This is heavily inspired
505  * by the timehands mechanism but kept independent from it. *_windup() functions
506  * have some connection to avoid accessing the timecounter hardware more than
507  * necessary.
508  */
509 
510 /* Feed-forward clock estimates kept updated by the synchronization daemon. */
511 struct ffclock_estimate ffclock_estimate;
512 struct bintime ffclock_boottime;	/* Feed-forward boot time estimate. */
513 uint32_t ffclock_status;		/* Feed-forward clock status. */
514 int8_t ffclock_updated;			/* New estimates are available. */
515 struct mtx ffclock_mtx;			/* Mutex on ffclock_estimate. */
516 
517 struct fftimehands {
518 	struct ffclock_estimate	cest;
519 	struct bintime		tick_time;
520 	struct bintime		tick_time_lerp;
521 	ffcounter		tick_ffcount;
522 	uint64_t		period_lerp;
523 	volatile uint8_t	gen;
524 	struct fftimehands	*next;
525 };
526 
527 #define	NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))
528 
529 static struct fftimehands ffth[10];
530 static struct fftimehands *volatile fftimehands = ffth;
531 
532 static void
533 ffclock_init(void)
534 {
535 	struct fftimehands *cur;
536 	struct fftimehands *last;
537 
538 	memset(ffth, 0, sizeof(ffth));
539 
540 	last = ffth + NUM_ELEMENTS(ffth) - 1;
541 	for (cur = ffth; cur < last; cur++)
542 		cur->next = cur + 1;
543 	last->next = ffth;
544 
545 	ffclock_updated = 0;
546 	ffclock_status = FFCLOCK_STA_UNSYNC;
547 	mtx_init(&ffclock_mtx, "ffclock lock", NULL, MTX_DEF);
548 }
549 
550 /*
551  * Reset the feed-forward clock estimates. Called from inittodr() to get things
552  * kick started and uses the timecounter nominal frequency as a first period
553  * estimate. Note: this function may be called several time just after boot.
554  * Note: this is the only function that sets the value of boot time for the
555  * monotonic (i.e. uptime) version of the feed-forward clock.
556  */
557 void
558 ffclock_reset_clock(struct timespec *ts)
559 {
560 	struct timecounter *tc;
561 	struct ffclock_estimate cest;
562 
563 	tc = timehands->th_counter;
564 	memset(&cest, 0, sizeof(struct ffclock_estimate));
565 
566 	timespec2bintime(ts, &ffclock_boottime);
567 	timespec2bintime(ts, &(cest.update_time));
568 	ffclock_read_counter(&cest.update_ffcount);
569 	cest.leapsec_next = 0;
570 	cest.period = ((1ULL << 63) / tc->tc_frequency) << 1;
571 	cest.errb_abs = 0;
572 	cest.errb_rate = 0;
573 	cest.status = FFCLOCK_STA_UNSYNC;
574 	cest.leapsec_total = 0;
575 	cest.leapsec = 0;
576 
577 	mtx_lock(&ffclock_mtx);
578 	bcopy(&cest, &ffclock_estimate, sizeof(struct ffclock_estimate));
579 	ffclock_updated = INT8_MAX;
580 	mtx_unlock(&ffclock_mtx);
581 
582 	printf("ffclock reset: %s (%llu Hz), time = %ld.%09lu\n", tc->tc_name,
583 	    (unsigned long long)tc->tc_frequency, (long)ts->tv_sec,
584 	    (unsigned long)ts->tv_nsec);
585 }
586 
587 /*
588  * Sub-routine to convert a time interval measured in RAW counter units to time
589  * in seconds stored in bintime format.
590  * NOTE: bintime_mul requires u_int, but the value of the ffcounter may be
591  * larger than the max value of u_int (on 32 bit architecture). Loop to consume
592  * extra cycles.
593  */
594 static void
595 ffclock_convert_delta(ffcounter ffdelta, uint64_t period, struct bintime *bt)
596 {
597 	struct bintime bt2;
598 	ffcounter delta, delta_max;
599 
600 	delta_max = (1ULL << (8 * sizeof(unsigned int))) - 1;
601 	bintime_clear(bt);
602 	do {
603 		if (ffdelta > delta_max)
604 			delta = delta_max;
605 		else
606 			delta = ffdelta;
607 		bt2.sec = 0;
608 		bt2.frac = period;
609 		bintime_mul(&bt2, (unsigned int)delta);
610 		bintime_add(bt, &bt2);
611 		ffdelta -= delta;
612 	} while (ffdelta > 0);
613 }
614 
615 /*
616  * Update the fftimehands.
617  * Push the tick ffcount and time(s) forward based on current clock estimate.
618  * The conversion from ffcounter to bintime relies on the difference clock
619  * principle, whose accuracy relies on computing small time intervals. If a new
620  * clock estimate has been passed by the synchronisation daemon, make it
621  * current, and compute the linear interpolation for monotonic time if needed.
622  */
623 static void
624 ffclock_windup(unsigned int delta)
625 {
626 	struct ffclock_estimate *cest;
627 	struct fftimehands *ffth;
628 	struct bintime bt, gap_lerp;
629 	ffcounter ffdelta;
630 	uint64_t frac;
631 	unsigned int polling;
632 	uint8_t forward_jump, ogen;
633 
634 	/*
635 	 * Pick the next timehand, copy current ffclock estimates and move tick
636 	 * times and counter forward.
637 	 */
638 	forward_jump = 0;
639 	ffth = fftimehands->next;
640 	ogen = ffth->gen;
641 	ffth->gen = 0;
642 	cest = &ffth->cest;
643 	bcopy(&fftimehands->cest, cest, sizeof(struct ffclock_estimate));
644 	ffdelta = (ffcounter)delta;
645 	ffth->period_lerp = fftimehands->period_lerp;
646 
647 	ffth->tick_time = fftimehands->tick_time;
648 	ffclock_convert_delta(ffdelta, cest->period, &bt);
649 	bintime_add(&ffth->tick_time, &bt);
650 
651 	ffth->tick_time_lerp = fftimehands->tick_time_lerp;
652 	ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt);
653 	bintime_add(&ffth->tick_time_lerp, &bt);
654 
655 	ffth->tick_ffcount = fftimehands->tick_ffcount + ffdelta;
656 
657 	/*
658 	 * Assess the status of the clock, if the last update is too old, it is
659 	 * likely the synchronisation daemon is dead and the clock is free
660 	 * running.
661 	 */
662 	if (ffclock_updated == 0) {
663 		ffdelta = ffth->tick_ffcount - cest->update_ffcount;
664 		ffclock_convert_delta(ffdelta, cest->period, &bt);
665 		if (bt.sec > 2 * FFCLOCK_SKM_SCALE)
666 			ffclock_status |= FFCLOCK_STA_UNSYNC;
667 	}
668 
669 	/*
670 	 * If available, grab updated clock estimates and make them current.
671 	 * Recompute time at this tick using the updated estimates. The clock
672 	 * estimates passed the feed-forward synchronisation daemon may result
673 	 * in time conversion that is not monotonically increasing (just after
674 	 * the update). time_lerp is a particular linear interpolation over the
675 	 * synchronisation algo polling period that ensures monotonicity for the
676 	 * clock ids requesting it.
677 	 */
678 	if (ffclock_updated > 0) {
679 		bcopy(&ffclock_estimate, cest, sizeof(struct ffclock_estimate));
680 		ffdelta = ffth->tick_ffcount - cest->update_ffcount;
681 		ffth->tick_time = cest->update_time;
682 		ffclock_convert_delta(ffdelta, cest->period, &bt);
683 		bintime_add(&ffth->tick_time, &bt);
684 
685 		/* ffclock_reset sets ffclock_updated to INT8_MAX */
686 		if (ffclock_updated == INT8_MAX)
687 			ffth->tick_time_lerp = ffth->tick_time;
688 
689 		if (bintime_cmp(&ffth->tick_time, &ffth->tick_time_lerp, >))
690 			forward_jump = 1;
691 		else
692 			forward_jump = 0;
693 
694 		bintime_clear(&gap_lerp);
695 		if (forward_jump) {
696 			gap_lerp = ffth->tick_time;
697 			bintime_sub(&gap_lerp, &ffth->tick_time_lerp);
698 		} else {
699 			gap_lerp = ffth->tick_time_lerp;
700 			bintime_sub(&gap_lerp, &ffth->tick_time);
701 		}
702 
703 		/*
704 		 * The reset from the RTC clock may be far from accurate, and
705 		 * reducing the gap between real time and interpolated time
706 		 * could take a very long time if the interpolated clock insists
707 		 * on strict monotonicity. The clock is reset under very strict
708 		 * conditions (kernel time is known to be wrong and
709 		 * synchronization daemon has been restarted recently.
710 		 * ffclock_boottime absorbs the jump to ensure boot time is
711 		 * correct and uptime functions stay consistent.
712 		 */
713 		if (((ffclock_status & FFCLOCK_STA_UNSYNC) == FFCLOCK_STA_UNSYNC) &&
714 		    ((cest->status & FFCLOCK_STA_UNSYNC) == 0) &&
715 		    ((cest->status & FFCLOCK_STA_WARMUP) == FFCLOCK_STA_WARMUP)) {
716 			if (forward_jump)
717 				bintime_add(&ffclock_boottime, &gap_lerp);
718 			else
719 				bintime_sub(&ffclock_boottime, &gap_lerp);
720 			ffth->tick_time_lerp = ffth->tick_time;
721 			bintime_clear(&gap_lerp);
722 		}
723 
724 		ffclock_status = cest->status;
725 		ffth->period_lerp = cest->period;
726 
727 		/*
728 		 * Compute corrected period used for the linear interpolation of
729 		 * time. The rate of linear interpolation is capped to 5000PPM
730 		 * (5ms/s).
731 		 */
732 		if (bintime_isset(&gap_lerp)) {
733 			ffdelta = cest->update_ffcount;
734 			ffdelta -= fftimehands->cest.update_ffcount;
735 			ffclock_convert_delta(ffdelta, cest->period, &bt);
736 			polling = bt.sec;
737 			bt.sec = 0;
738 			bt.frac = 5000000 * (uint64_t)18446744073LL;
739 			bintime_mul(&bt, polling);
740 			if (bintime_cmp(&gap_lerp, &bt, >))
741 				gap_lerp = bt;
742 
743 			/* Approximate 1 sec by 1-(1/2^64) to ease arithmetic */
744 			frac = 0;
745 			if (gap_lerp.sec > 0) {
746 				frac -= 1;
747 				frac /= ffdelta / gap_lerp.sec;
748 			}
749 			frac += gap_lerp.frac / ffdelta;
750 
751 			if (forward_jump)
752 				ffth->period_lerp += frac;
753 			else
754 				ffth->period_lerp -= frac;
755 		}
756 
757 		ffclock_updated = 0;
758 	}
759 	if (++ogen == 0)
760 		ogen = 1;
761 	ffth->gen = ogen;
762 	fftimehands = ffth;
763 }
764 
765 /*
766  * Adjust the fftimehands when the timecounter is changed. Stating the obvious,
767  * the old and new hardware counter cannot be read simultaneously. tc_windup()
768  * does read the two counters 'back to back', but a few cycles are effectively
769  * lost, and not accumulated in tick_ffcount. This is a fairly radical
770  * operation for a feed-forward synchronization daemon, and it is its job to not
771  * pushing irrelevant data to the kernel. Because there is no locking here,
772  * simply force to ignore pending or next update to give daemon a chance to
773  * realize the counter has changed.
774  */
775 static void
776 ffclock_change_tc(struct timehands *th)
777 {
778 	struct fftimehands *ffth;
779 	struct ffclock_estimate *cest;
780 	struct timecounter *tc;
781 	uint8_t ogen;
782 
783 	tc = th->th_counter;
784 	ffth = fftimehands->next;
785 	ogen = ffth->gen;
786 	ffth->gen = 0;
787 
788 	cest = &ffth->cest;
789 	bcopy(&(fftimehands->cest), cest, sizeof(struct ffclock_estimate));
790 	cest->period = ((1ULL << 63) / tc->tc_frequency ) << 1;
791 	cest->errb_abs = 0;
792 	cest->errb_rate = 0;
793 	cest->status |= FFCLOCK_STA_UNSYNC;
794 
795 	ffth->tick_ffcount = fftimehands->tick_ffcount;
796 	ffth->tick_time_lerp = fftimehands->tick_time_lerp;
797 	ffth->tick_time = fftimehands->tick_time;
798 	ffth->period_lerp = cest->period;
799 
800 	/* Do not lock but ignore next update from synchronization daemon. */
801 	ffclock_updated--;
802 
803 	if (++ogen == 0)
804 		ogen = 1;
805 	ffth->gen = ogen;
806 	fftimehands = ffth;
807 }
808 
809 /*
810  * Retrieve feed-forward counter and time of last kernel tick.
811  */
812 void
813 ffclock_last_tick(ffcounter *ffcount, struct bintime *bt, uint32_t flags)
814 {
815 	struct fftimehands *ffth;
816 	uint8_t gen;
817 
818 	/*
819 	 * No locking but check generation has not changed. Also need to make
820 	 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
821 	 */
822 	do {
823 		ffth = fftimehands;
824 		gen = ffth->gen;
825 		if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP)
826 			*bt = ffth->tick_time_lerp;
827 		else
828 			*bt = ffth->tick_time;
829 		*ffcount = ffth->tick_ffcount;
830 	} while (gen == 0 || gen != ffth->gen);
831 }
832 
833 /*
834  * Absolute clock conversion. Low level function to convert ffcounter to
835  * bintime. The ffcounter is converted using the current ffclock period estimate
836  * or the "interpolated period" to ensure monotonicity.
837  * NOTE: this conversion may have been deferred, and the clock updated since the
838  * hardware counter has been read.
839  */
840 void
841 ffclock_convert_abs(ffcounter ffcount, struct bintime *bt, uint32_t flags)
842 {
843 	struct fftimehands *ffth;
844 	struct bintime bt2;
845 	ffcounter ffdelta;
846 	uint8_t gen;
847 
848 	/*
849 	 * No locking but check generation has not changed. Also need to make
850 	 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
851 	 */
852 	do {
853 		ffth = fftimehands;
854 		gen = ffth->gen;
855 		if (ffcount > ffth->tick_ffcount)
856 			ffdelta = ffcount - ffth->tick_ffcount;
857 		else
858 			ffdelta = ffth->tick_ffcount - ffcount;
859 
860 		if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP) {
861 			*bt = ffth->tick_time_lerp;
862 			ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt2);
863 		} else {
864 			*bt = ffth->tick_time;
865 			ffclock_convert_delta(ffdelta, ffth->cest.period, &bt2);
866 		}
867 
868 		if (ffcount > ffth->tick_ffcount)
869 			bintime_add(bt, &bt2);
870 		else
871 			bintime_sub(bt, &bt2);
872 	} while (gen == 0 || gen != ffth->gen);
873 }
874 
875 /*
876  * Difference clock conversion.
877  * Low level function to Convert a time interval measured in RAW counter units
878  * into bintime. The difference clock allows measuring small intervals much more
879  * reliably than the absolute clock.
880  */
881 void
882 ffclock_convert_diff(ffcounter ffdelta, struct bintime *bt)
883 {
884 	struct fftimehands *ffth;
885 	uint8_t gen;
886 
887 	/* No locking but check generation has not changed. */
888 	do {
889 		ffth = fftimehands;
890 		gen = ffth->gen;
891 		ffclock_convert_delta(ffdelta, ffth->cest.period, bt);
892 	} while (gen == 0 || gen != ffth->gen);
893 }
894 
895 /*
896  * Access to current ffcounter value.
897  */
898 void
899 ffclock_read_counter(ffcounter *ffcount)
900 {
901 	struct timehands *th;
902 	struct fftimehands *ffth;
903 	unsigned int gen, delta;
904 
905 	/*
906 	 * ffclock_windup() called from tc_windup(), safe to rely on
907 	 * th->th_generation only, for correct delta and ffcounter.
908 	 */
909 	do {
910 		th = timehands;
911 		gen = atomic_load_acq_int(&th->th_generation);
912 		ffth = fftimehands;
913 		delta = tc_delta(th);
914 		*ffcount = ffth->tick_ffcount;
915 		atomic_thread_fence_acq();
916 	} while (gen == 0 || gen != th->th_generation);
917 
918 	*ffcount += delta;
919 }
920 
921 void
922 binuptime(struct bintime *bt)
923 {
924 
925 	binuptime_fromclock(bt, sysclock_active);
926 }
927 
928 void
929 nanouptime(struct timespec *tsp)
930 {
931 
932 	nanouptime_fromclock(tsp, sysclock_active);
933 }
934 
935 void
936 microuptime(struct timeval *tvp)
937 {
938 
939 	microuptime_fromclock(tvp, sysclock_active);
940 }
941 
942 void
943 bintime(struct bintime *bt)
944 {
945 
946 	bintime_fromclock(bt, sysclock_active);
947 }
948 
949 void
950 nanotime(struct timespec *tsp)
951 {
952 
953 	nanotime_fromclock(tsp, sysclock_active);
954 }
955 
956 void
957 microtime(struct timeval *tvp)
958 {
959 
960 	microtime_fromclock(tvp, sysclock_active);
961 }
962 
963 void
964 getbinuptime(struct bintime *bt)
965 {
966 
967 	getbinuptime_fromclock(bt, sysclock_active);
968 }
969 
970 void
971 getnanouptime(struct timespec *tsp)
972 {
973 
974 	getnanouptime_fromclock(tsp, sysclock_active);
975 }
976 
977 void
978 getmicrouptime(struct timeval *tvp)
979 {
980 
981 	getmicrouptime_fromclock(tvp, sysclock_active);
982 }
983 
984 void
985 getbintime(struct bintime *bt)
986 {
987 
988 	getbintime_fromclock(bt, sysclock_active);
989 }
990 
991 void
992 getnanotime(struct timespec *tsp)
993 {
994 
995 	getnanotime_fromclock(tsp, sysclock_active);
996 }
997 
998 void
999 getmicrotime(struct timeval *tvp)
1000 {
1001 
1002 	getmicrouptime_fromclock(tvp, sysclock_active);
1003 }
1004 
1005 #endif /* FFCLOCK */
1006 
1007 /*
1008  * This is a clone of getnanotime and used for walltimestamps.
1009  * The dtrace_ prefix prevents fbt from creating probes for
1010  * it so walltimestamp can be safely used in all fbt probes.
1011  */
1012 void
1013 dtrace_getnanotime(struct timespec *tsp)
1014 {
1015 
1016 	GETTHMEMBER(tsp, th_nanotime);
1017 }
1018 
1019 /*
1020  * This is a clone of getnanouptime used for time since boot.
1021  * The dtrace_ prefix prevents fbt from creating probes for
1022  * it so an uptime that can be safely used in all fbt probes.
1023  */
1024 void
1025 dtrace_getnanouptime(struct timespec *tsp)
1026 {
1027 	struct bintime bt;
1028 
1029 	GETTHMEMBER(&bt, th_offset);
1030 	bintime2timespec(&bt, tsp);
1031 }
1032 
1033 /*
1034  * System clock currently providing time to the system. Modifiable via sysctl
1035  * when the FFCLOCK option is defined.
1036  */
1037 int sysclock_active = SYSCLOCK_FBCK;
1038 
1039 /* Internal NTP status and error estimates. */
1040 extern int time_status;
1041 extern long time_esterror;
1042 
1043 /*
1044  * Take a snapshot of sysclock data which can be used to compare system clocks
1045  * and generate timestamps after the fact.
1046  */
1047 void
1048 sysclock_getsnapshot(struct sysclock_snap *clock_snap, int fast)
1049 {
1050 	struct fbclock_info *fbi;
1051 	struct timehands *th;
1052 	struct bintime bt;
1053 	unsigned int delta, gen;
1054 #ifdef FFCLOCK
1055 	ffcounter ffcount;
1056 	struct fftimehands *ffth;
1057 	struct ffclock_info *ffi;
1058 	struct ffclock_estimate cest;
1059 
1060 	ffi = &clock_snap->ff_info;
1061 #endif
1062 
1063 	fbi = &clock_snap->fb_info;
1064 	delta = 0;
1065 
1066 	do {
1067 		th = timehands;
1068 		gen = atomic_load_acq_int(&th->th_generation);
1069 		fbi->th_scale = th->th_scale;
1070 		fbi->tick_time = th->th_offset;
1071 #ifdef FFCLOCK
1072 		ffth = fftimehands;
1073 		ffi->tick_time = ffth->tick_time_lerp;
1074 		ffi->tick_time_lerp = ffth->tick_time_lerp;
1075 		ffi->period = ffth->cest.period;
1076 		ffi->period_lerp = ffth->period_lerp;
1077 		clock_snap->ffcount = ffth->tick_ffcount;
1078 		cest = ffth->cest;
1079 #endif
1080 		if (!fast)
1081 			delta = tc_delta(th);
1082 		atomic_thread_fence_acq();
1083 	} while (gen == 0 || gen != th->th_generation);
1084 
1085 	clock_snap->delta = delta;
1086 	clock_snap->sysclock_active = sysclock_active;
1087 
1088 	/* Record feedback clock status and error. */
1089 	clock_snap->fb_info.status = time_status;
1090 	/* XXX: Very crude estimate of feedback clock error. */
1091 	bt.sec = time_esterror / 1000000;
1092 	bt.frac = ((time_esterror - bt.sec) * 1000000) *
1093 	    (uint64_t)18446744073709ULL;
1094 	clock_snap->fb_info.error = bt;
1095 
1096 #ifdef FFCLOCK
1097 	if (!fast)
1098 		clock_snap->ffcount += delta;
1099 
1100 	/* Record feed-forward clock leap second adjustment. */
1101 	ffi->leapsec_adjustment = cest.leapsec_total;
1102 	if (clock_snap->ffcount > cest.leapsec_next)
1103 		ffi->leapsec_adjustment -= cest.leapsec;
1104 
1105 	/* Record feed-forward clock status and error. */
1106 	clock_snap->ff_info.status = cest.status;
1107 	ffcount = clock_snap->ffcount - cest.update_ffcount;
1108 	ffclock_convert_delta(ffcount, cest.period, &bt);
1109 	/* 18446744073709 = int(2^64/1e12), err_bound_rate in [ps/s]. */
1110 	bintime_mul(&bt, cest.errb_rate * (uint64_t)18446744073709ULL);
1111 	/* 18446744073 = int(2^64 / 1e9), since err_abs in [ns]. */
1112 	bintime_addx(&bt, cest.errb_abs * (uint64_t)18446744073ULL);
1113 	clock_snap->ff_info.error = bt;
1114 #endif
1115 }
1116 
1117 /*
1118  * Convert a sysclock snapshot into a struct bintime based on the specified
1119  * clock source and flags.
1120  */
1121 int
1122 sysclock_snap2bintime(struct sysclock_snap *cs, struct bintime *bt,
1123     int whichclock, uint32_t flags)
1124 {
1125 	struct bintime boottimebin;
1126 #ifdef FFCLOCK
1127 	struct bintime bt2;
1128 	uint64_t period;
1129 #endif
1130 
1131 	switch (whichclock) {
1132 	case SYSCLOCK_FBCK:
1133 		*bt = cs->fb_info.tick_time;
1134 
1135 		/* If snapshot was created with !fast, delta will be >0. */
1136 		if (cs->delta > 0)
1137 			bintime_addx(bt, cs->fb_info.th_scale * cs->delta);
1138 
1139 		if ((flags & FBCLOCK_UPTIME) == 0) {
1140 			getboottimebin(&boottimebin);
1141 			bintime_add(bt, &boottimebin);
1142 		}
1143 		break;
1144 #ifdef FFCLOCK
1145 	case SYSCLOCK_FFWD:
1146 		if (flags & FFCLOCK_LERP) {
1147 			*bt = cs->ff_info.tick_time_lerp;
1148 			period = cs->ff_info.period_lerp;
1149 		} else {
1150 			*bt = cs->ff_info.tick_time;
1151 			period = cs->ff_info.period;
1152 		}
1153 
1154 		/* If snapshot was created with !fast, delta will be >0. */
1155 		if (cs->delta > 0) {
1156 			ffclock_convert_delta(cs->delta, period, &bt2);
1157 			bintime_add(bt, &bt2);
1158 		}
1159 
1160 		/* Leap second adjustment. */
1161 		if (flags & FFCLOCK_LEAPSEC)
1162 			bt->sec -= cs->ff_info.leapsec_adjustment;
1163 
1164 		/* Boot time adjustment, for uptime/monotonic clocks. */
1165 		if (flags & FFCLOCK_UPTIME)
1166 			bintime_sub(bt, &ffclock_boottime);
1167 		break;
1168 #endif
1169 	default:
1170 		return (EINVAL);
1171 		break;
1172 	}
1173 
1174 	return (0);
1175 }
1176 
1177 /*
1178  * Initialize a new timecounter and possibly use it.
1179  */
1180 void
1181 tc_init(struct timecounter *tc)
1182 {
1183 	u_int u;
1184 	struct sysctl_oid *tc_root;
1185 
1186 	u = tc->tc_frequency / tc->tc_counter_mask;
1187 	/* XXX: We need some margin here, 10% is a guess */
1188 	u *= 11;
1189 	u /= 10;
1190 	if (u > hz && tc->tc_quality >= 0) {
1191 		tc->tc_quality = -2000;
1192 		if (bootverbose) {
1193 			printf("Timecounter \"%s\" frequency %ju Hz",
1194 			    tc->tc_name, (uintmax_t)tc->tc_frequency);
1195 			printf(" -- Insufficient hz, needs at least %u\n", u);
1196 		}
1197 	} else if (tc->tc_quality >= 0 || bootverbose) {
1198 		printf("Timecounter \"%s\" frequency %ju Hz quality %d\n",
1199 		    tc->tc_name, (uintmax_t)tc->tc_frequency,
1200 		    tc->tc_quality);
1201 	}
1202 
1203 	/*
1204 	 * Set up sysctl tree for this counter.
1205 	 */
1206 	tc_root = SYSCTL_ADD_NODE_WITH_LABEL(NULL,
1207 	    SYSCTL_STATIC_CHILDREN(_kern_timecounter_tc), OID_AUTO, tc->tc_name,
1208 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1209 	    "timecounter description", "timecounter");
1210 	SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1211 	    "mask", CTLFLAG_RD, &(tc->tc_counter_mask), 0,
1212 	    "mask for implemented bits");
1213 	SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1214 	    "counter", CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, tc,
1215 	    sizeof(*tc), sysctl_kern_timecounter_get, "IU",
1216 	    "current timecounter value");
1217 	SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1218 	    "frequency", CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, tc,
1219 	    sizeof(*tc), sysctl_kern_timecounter_freq, "QU",
1220 	    "timecounter frequency");
1221 	SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1222 	    "quality", CTLFLAG_RD, &(tc->tc_quality), 0,
1223 	    "goodness of time counter");
1224 
1225 	mtx_lock(&tc_lock);
1226 	tc->tc_next = timecounters;
1227 	timecounters = tc;
1228 
1229 	/*
1230 	 * Do not automatically switch if the current tc was specifically
1231 	 * chosen.  Never automatically use a timecounter with negative quality.
1232 	 * Even though we run on the dummy counter, switching here may be
1233 	 * worse since this timecounter may not be monotonic.
1234 	 */
1235 	if (tc_chosen)
1236 		goto unlock;
1237 	if (tc->tc_quality < 0)
1238 		goto unlock;
1239 	if (tc_from_tunable[0] != '\0' &&
1240 	    strcmp(tc->tc_name, tc_from_tunable) == 0) {
1241 		tc_chosen = 1;
1242 		tc_from_tunable[0] = '\0';
1243 	} else {
1244 		if (tc->tc_quality < timecounter->tc_quality)
1245 			goto unlock;
1246 		if (tc->tc_quality == timecounter->tc_quality &&
1247 		    tc->tc_frequency < timecounter->tc_frequency)
1248 			goto unlock;
1249 	}
1250 	(void)tc->tc_get_timecount(tc);
1251 	timecounter = tc;
1252 unlock:
1253 	mtx_unlock(&tc_lock);
1254 }
1255 
1256 /* Report the frequency of the current timecounter. */
1257 uint64_t
1258 tc_getfrequency(void)
1259 {
1260 
1261 	return (timehands->th_counter->tc_frequency);
1262 }
1263 
1264 static bool
1265 sleeping_on_old_rtc(struct thread *td)
1266 {
1267 
1268 	/*
1269 	 * td_rtcgen is modified by curthread when it is running,
1270 	 * and by other threads in this function.  By finding the thread
1271 	 * on a sleepqueue and holding the lock on the sleepqueue
1272 	 * chain, we guarantee that the thread is not running and that
1273 	 * modifying td_rtcgen is safe.  Setting td_rtcgen to zero informs
1274 	 * the thread that it was woken due to a real-time clock adjustment.
1275 	 * (The declaration of td_rtcgen refers to this comment.)
1276 	 */
1277 	if (td->td_rtcgen != 0 && td->td_rtcgen != rtc_generation) {
1278 		td->td_rtcgen = 0;
1279 		return (true);
1280 	}
1281 	return (false);
1282 }
1283 
1284 static struct mtx tc_setclock_mtx;
1285 MTX_SYSINIT(tc_setclock_init, &tc_setclock_mtx, "tcsetc", MTX_SPIN);
1286 
1287 /*
1288  * Step our concept of UTC.  This is done by modifying our estimate of
1289  * when we booted.
1290  */
1291 void
1292 tc_setclock(struct timespec *ts)
1293 {
1294 	struct timespec tbef, taft;
1295 	struct bintime bt, bt2;
1296 
1297 	timespec2bintime(ts, &bt);
1298 	nanotime(&tbef);
1299 	mtx_lock_spin(&tc_setclock_mtx);
1300 	cpu_tick_calibrate(1);
1301 	binuptime(&bt2);
1302 	bintime_sub(&bt, &bt2);
1303 
1304 	/* XXX fiddle all the little crinkly bits around the fiords... */
1305 	tc_windup(&bt);
1306 	mtx_unlock_spin(&tc_setclock_mtx);
1307 
1308 	/* Avoid rtc_generation == 0, since td_rtcgen == 0 is special. */
1309 	atomic_add_rel_int(&rtc_generation, 2);
1310 	sleepq_chains_remove_matching(sleeping_on_old_rtc);
1311 	if (timestepwarnings) {
1312 		nanotime(&taft);
1313 		log(LOG_INFO,
1314 		    "Time stepped from %jd.%09ld to %jd.%09ld (%jd.%09ld)\n",
1315 		    (intmax_t)tbef.tv_sec, tbef.tv_nsec,
1316 		    (intmax_t)taft.tv_sec, taft.tv_nsec,
1317 		    (intmax_t)ts->tv_sec, ts->tv_nsec);
1318 	}
1319 }
1320 
1321 /*
1322  * Recalculate the scaling factor.  We want the number of 1/2^64
1323  * fractions of a second per period of the hardware counter, taking
1324  * into account the th_adjustment factor which the NTP PLL/adjtime(2)
1325  * processing provides us with.
1326  *
1327  * The th_adjustment is nanoseconds per second with 32 bit binary
1328  * fraction and we want 64 bit binary fraction of second:
1329  *
1330  *	 x = a * 2^32 / 10^9 = a * 4.294967296
1331  *
1332  * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
1333  * we can only multiply by about 850 without overflowing, that
1334  * leaves no suitably precise fractions for multiply before divide.
1335  *
1336  * Divide before multiply with a fraction of 2199/512 results in a
1337  * systematic undercompensation of 10PPM of th_adjustment.  On a
1338  * 5000PPM adjustment this is a 0.05PPM error.  This is acceptable.
1339  *
1340  * We happily sacrifice the lowest of the 64 bits of our result
1341  * to the goddess of code clarity.
1342  */
1343 static void
1344 recalculate_scaling_factor_and_large_delta(struct timehands *th)
1345 {
1346 	uint64_t scale;
1347 
1348 	scale = (uint64_t)1 << 63;
1349 	scale += (th->th_adjustment / 1024) * 2199;
1350 	scale /= th->th_counter->tc_frequency;
1351 	th->th_scale = scale * 2;
1352 	th->th_large_delta = MIN(((uint64_t)1 << 63) / scale, UINT_MAX);
1353 }
1354 
1355 /*
1356  * Initialize the next struct timehands in the ring and make
1357  * it the active timehands.  Along the way we might switch to a different
1358  * timecounter and/or do seconds processing in NTP.  Slightly magic.
1359  */
1360 static void
1361 tc_windup(struct bintime *new_boottimebin)
1362 {
1363 	struct bintime bt;
1364 	struct timecounter *tc;
1365 	struct timehands *th, *tho;
1366 	u_int delta, ncount, ogen;
1367 	int i;
1368 	time_t t;
1369 
1370 	/*
1371 	 * Make the next timehands a copy of the current one, but do
1372 	 * not overwrite the generation or next pointer.  While we
1373 	 * update the contents, the generation must be zero.  We need
1374 	 * to ensure that the zero generation is visible before the
1375 	 * data updates become visible, which requires release fence.
1376 	 * For similar reasons, re-reading of the generation after the
1377 	 * data is read should use acquire fence.
1378 	 */
1379 	tho = timehands;
1380 	th = tho->th_next;
1381 	ogen = th->th_generation;
1382 	th->th_generation = 0;
1383 	atomic_thread_fence_rel();
1384 	memcpy(th, tho, offsetof(struct timehands, th_generation));
1385 	if (new_boottimebin != NULL)
1386 		th->th_boottime = *new_boottimebin;
1387 
1388 	/*
1389 	 * Capture a timecounter delta on the current timecounter and if
1390 	 * changing timecounters, a counter value from the new timecounter.
1391 	 * Update the offset fields accordingly.
1392 	 */
1393 	tc = atomic_load_ptr(&timecounter);
1394 	delta = tc_delta(th);
1395 	if (th->th_counter != tc)
1396 		ncount = tc->tc_get_timecount(tc);
1397 	else
1398 		ncount = 0;
1399 #ifdef FFCLOCK
1400 	ffclock_windup(delta);
1401 #endif
1402 	th->th_offset_count += delta;
1403 	th->th_offset_count &= th->th_counter->tc_counter_mask;
1404 	bintime_add_tc_delta(&th->th_offset, th->th_scale,
1405 	    th->th_large_delta, delta);
1406 
1407 	/*
1408 	 * Hardware latching timecounters may not generate interrupts on
1409 	 * PPS events, so instead we poll them.  There is a finite risk that
1410 	 * the hardware might capture a count which is later than the one we
1411 	 * got above, and therefore possibly in the next NTP second which might
1412 	 * have a different rate than the current NTP second.  It doesn't
1413 	 * matter in practice.
1414 	 */
1415 	if (tho->th_counter->tc_poll_pps)
1416 		tho->th_counter->tc_poll_pps(tho->th_counter);
1417 
1418 	/*
1419 	 * Deal with NTP second processing.  The loop normally
1420 	 * iterates at most once, but in extreme situations it might
1421 	 * keep NTP sane if timeouts are not run for several seconds.
1422 	 * At boot, the time step can be large when the TOD hardware
1423 	 * has been read, so on really large steps, we call
1424 	 * ntp_update_second only twice.  We need to call it twice in
1425 	 * case we missed a leap second.
1426 	 */
1427 	bt = th->th_offset;
1428 	bintime_add(&bt, &th->th_boottime);
1429 	i = bt.sec - tho->th_microtime.tv_sec;
1430 	if (i > 0) {
1431 		if (i > LARGE_STEP)
1432 			i = 2;
1433 
1434 		do {
1435 			t = bt.sec;
1436 			ntp_update_second(&th->th_adjustment, &bt.sec);
1437 			if (bt.sec != t)
1438 				th->th_boottime.sec += bt.sec - t;
1439 			--i;
1440 		} while (i > 0);
1441 
1442 		recalculate_scaling_factor_and_large_delta(th);
1443 	}
1444 
1445 	/* Update the UTC timestamps used by the get*() functions. */
1446 	th->th_bintime = bt;
1447 	bintime2timeval(&bt, &th->th_microtime);
1448 	bintime2timespec(&bt, &th->th_nanotime);
1449 
1450 	/* Now is a good time to change timecounters. */
1451 	if (th->th_counter != tc) {
1452 #ifndef __arm__
1453 		if ((tc->tc_flags & TC_FLAGS_C2STOP) != 0)
1454 			cpu_disable_c2_sleep++;
1455 		if ((th->th_counter->tc_flags & TC_FLAGS_C2STOP) != 0)
1456 			cpu_disable_c2_sleep--;
1457 #endif
1458 		th->th_counter = tc;
1459 		th->th_offset_count = ncount;
1460 		tc_min_ticktock_freq = max(1, tc->tc_frequency /
1461 		    (((uint64_t)tc->tc_counter_mask + 1) / 3));
1462 		recalculate_scaling_factor_and_large_delta(th);
1463 #ifdef FFCLOCK
1464 		ffclock_change_tc(th);
1465 #endif
1466 	}
1467 
1468 	/*
1469 	 * Now that the struct timehands is again consistent, set the new
1470 	 * generation number, making sure to not make it zero.
1471 	 */
1472 	if (++ogen == 0)
1473 		ogen = 1;
1474 	atomic_store_rel_int(&th->th_generation, ogen);
1475 
1476 	/* Go live with the new struct timehands. */
1477 #ifdef FFCLOCK
1478 	switch (sysclock_active) {
1479 	case SYSCLOCK_FBCK:
1480 #endif
1481 		time_second = th->th_microtime.tv_sec;
1482 		time_uptime = th->th_offset.sec;
1483 #ifdef FFCLOCK
1484 		break;
1485 	case SYSCLOCK_FFWD:
1486 		time_second = fftimehands->tick_time_lerp.sec;
1487 		time_uptime = fftimehands->tick_time_lerp.sec - ffclock_boottime.sec;
1488 		break;
1489 	}
1490 #endif
1491 
1492 	timehands = th;
1493 	timekeep_push_vdso();
1494 }
1495 
1496 /* Report or change the active timecounter hardware. */
1497 static int
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  */
2159 
2160 uint64_t
2161 cputick2usec(uint64_t tick)
2162 {
2163 	uint64_t tr;
2164 	tr = cpu_tickrate();
2165 	return ((tick / tr) * 1000000ULL) + ((tick % tr) * 1000000ULL) / tr;
2166 }
2167 
2168 cpu_tick_f	*cpu_ticks = tc_cpu_ticks;
2169 
2170 static int vdso_th_enable = 1;
2171 static int
2172 sysctl_fast_gettime(SYSCTL_HANDLER_ARGS)
2173 {
2174 	int old_vdso_th_enable, error;
2175 
2176 	old_vdso_th_enable = vdso_th_enable;
2177 	error = sysctl_handle_int(oidp, &old_vdso_th_enable, 0, req);
2178 	if (error != 0)
2179 		return (error);
2180 	vdso_th_enable = old_vdso_th_enable;
2181 	return (0);
2182 }
2183 SYSCTL_PROC(_kern_timecounter, OID_AUTO, fast_gettime,
2184     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
2185     NULL, 0, sysctl_fast_gettime, "I", "Enable fast time of day");
2186 
2187 uint32_t
2188 tc_fill_vdso_timehands(struct vdso_timehands *vdso_th)
2189 {
2190 	struct timehands *th;
2191 	uint32_t enabled;
2192 
2193 	th = timehands;
2194 	vdso_th->th_scale = th->th_scale;
2195 	vdso_th->th_offset_count = th->th_offset_count;
2196 	vdso_th->th_counter_mask = th->th_counter->tc_counter_mask;
2197 	vdso_th->th_offset = th->th_offset;
2198 	vdso_th->th_boottime = th->th_boottime;
2199 	if (th->th_counter->tc_fill_vdso_timehands != NULL) {
2200 		enabled = th->th_counter->tc_fill_vdso_timehands(vdso_th,
2201 		    th->th_counter);
2202 	} else
2203 		enabled = 0;
2204 	if (!vdso_th_enable)
2205 		enabled = 0;
2206 	return (enabled);
2207 }
2208 
2209 #ifdef COMPAT_FREEBSD32
2210 uint32_t
2211 tc_fill_vdso_timehands32(struct vdso_timehands32 *vdso_th32)
2212 {
2213 	struct timehands *th;
2214 	uint32_t enabled;
2215 
2216 	th = timehands;
2217 	*(uint64_t *)&vdso_th32->th_scale[0] = th->th_scale;
2218 	vdso_th32->th_offset_count = th->th_offset_count;
2219 	vdso_th32->th_counter_mask = th->th_counter->tc_counter_mask;
2220 	vdso_th32->th_offset.sec = th->th_offset.sec;
2221 	*(uint64_t *)&vdso_th32->th_offset.frac[0] = th->th_offset.frac;
2222 	vdso_th32->th_boottime.sec = th->th_boottime.sec;
2223 	*(uint64_t *)&vdso_th32->th_boottime.frac[0] = th->th_boottime.frac;
2224 	if (th->th_counter->tc_fill_vdso_timehands32 != NULL) {
2225 		enabled = th->th_counter->tc_fill_vdso_timehands32(vdso_th32,
2226 		    th->th_counter);
2227 	} else
2228 		enabled = 0;
2229 	if (!vdso_th_enable)
2230 		enabled = 0;
2231 	return (enabled);
2232 }
2233 #endif
2234 
2235 #include "opt_ddb.h"
2236 #ifdef DDB
2237 #include <ddb/ddb.h>
2238 
2239 DB_SHOW_COMMAND(timecounter, db_show_timecounter)
2240 {
2241 	struct timehands *th;
2242 	struct timecounter *tc;
2243 	u_int val1, val2;
2244 
2245 	th = timehands;
2246 	tc = th->th_counter;
2247 	val1 = tc->tc_get_timecount(tc);
2248 	__compiler_membar();
2249 	val2 = tc->tc_get_timecount(tc);
2250 
2251 	db_printf("timecounter %p %s\n", tc, tc->tc_name);
2252 	db_printf("  mask %#x freq %ju qual %d flags %#x priv %p\n",
2253 	    tc->tc_counter_mask, (uintmax_t)tc->tc_frequency, tc->tc_quality,
2254 	    tc->tc_flags, tc->tc_priv);
2255 	db_printf("  val %#x %#x\n", val1, val2);
2256 	db_printf("timehands adj %#jx scale %#jx ldelta %d off_cnt %d gen %d\n",
2257 	    (uintmax_t)th->th_adjustment, (uintmax_t)th->th_scale,
2258 	    th->th_large_delta, th->th_offset_count, th->th_generation);
2259 	db_printf("  offset %jd %jd boottime %jd %jd\n",
2260 	    (intmax_t)th->th_offset.sec, (uintmax_t)th->th_offset.frac,
2261 	    (intmax_t)th->th_boottime.sec, (uintmax_t)th->th_boottime.frac);
2262 }
2263 #endif
2264