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