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