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