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