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