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