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