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