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