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