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