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