xref: /freebsd/sys/kern/kern_tc.c (revision 7045ac437bcc31db541a3a8e2abcb16d922d30bf)
139acc78aSPoul-Henning Kamp /*-
264de3fddSPedro F. Giffuni  * SPDX-License-Identifier: Beerware
364de3fddSPedro F. Giffuni  *
491266b96SPoul-Henning Kamp  * ----------------------------------------------------------------------------
591266b96SPoul-Henning Kamp  * "THE BEER-WARE LICENSE" (Revision 42):
691266b96SPoul-Henning Kamp  * <phk@FreeBSD.ORG> wrote this file.  As long as you retain this notice you
791266b96SPoul-Henning Kamp  * can do whatever you want with this stuff. If we meet some day, and you think
891266b96SPoul-Henning Kamp  * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
991266b96SPoul-Henning Kamp  * ----------------------------------------------------------------------------
10b0fdc837SLawrence Stewart  *
1116808549SKonstantin Belousov  * Copyright (c) 2011, 2015, 2016 The FreeBSD Foundation
12b0fdc837SLawrence Stewart  * All rights reserved.
13b0fdc837SLawrence Stewart  *
14b0fdc837SLawrence Stewart  * Portions of this software were developed by Julien Ridoux at the University
15b0fdc837SLawrence Stewart  * of Melbourne under sponsorship from the FreeBSD Foundation.
1616808549SKonstantin Belousov  *
1716808549SKonstantin Belousov  * Portions of this software were developed by Konstantin Belousov
1816808549SKonstantin Belousov  * under sponsorship from the FreeBSD Foundation.
19df8bae1dSRodney W. Grimes  */
20df8bae1dSRodney W. Grimes 
21677b542eSDavid E. O'Brien #include <sys/cdefs.h>
22677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
23677b542eSDavid E. O'Brien 
2432c20357SPoul-Henning Kamp #include "opt_ntp.h"
25b0fdc837SLawrence Stewart #include "opt_ffclock.h"
2632c20357SPoul-Henning Kamp 
27df8bae1dSRodney W. Grimes #include <sys/param.h>
2891266b96SPoul-Henning Kamp #include <sys/kernel.h>
295b999a6bSDavide Italiano #include <sys/limits.h>
30b0fdc837SLawrence Stewart #include <sys/lock.h>
31b0fdc837SLawrence Stewart #include <sys/mutex.h>
329dbdf2a1SEric van Gyzen #include <sys/proc.h>
3391d9eda2SIan Lepore #include <sys/sbuf.h>
349dbdf2a1SEric van Gyzen #include <sys/sleepqueue.h>
3591266b96SPoul-Henning Kamp #include <sys/sysctl.h>
364e74721cSPoul-Henning Kamp #include <sys/syslog.h>
3791266b96SPoul-Henning Kamp #include <sys/systm.h>
38b0fdc837SLawrence Stewart #include <sys/timeffc.h>
3932c20357SPoul-Henning Kamp #include <sys/timepps.h>
4048e5da55SPoul-Henning Kamp #include <sys/timetc.h>
4139acc78aSPoul-Henning Kamp #include <sys/timex.h>
42aea81038SKonstantin Belousov #include <sys/vdso.h>
4339acc78aSPoul-Henning Kamp 
443bac064fSPoul-Henning Kamp /*
45c1cccd1eSWarner Losh  * A large step happens on boot.  This constant detects such steps.
46c1cccd1eSWarner Losh  * It is relatively small so that ntp_update_second gets called enough
47c1cccd1eSWarner Losh  * in the typical 'missed a couple of seconds' case, but doesn't loop
48c1cccd1eSWarner Losh  * forever when the time step is large.
494f2073fbSWarner Losh  */
504f2073fbSWarner Losh #define LARGE_STEP	200
514f2073fbSWarner Losh 
524f2073fbSWarner Losh /*
5362efba6aSPoul-Henning Kamp  * Implement a dummy timecounter which we can use until we get a real one
5462efba6aSPoul-Henning Kamp  * in the air.  This allows the console and other early stuff to use
5562efba6aSPoul-Henning Kamp  * time services.
563bac064fSPoul-Henning Kamp  */
573bac064fSPoul-Henning Kamp 
586b00cf46SPoul-Henning Kamp static u_int
5962efba6aSPoul-Henning Kamp dummy_get_timecount(struct timecounter *tc)
6062efba6aSPoul-Henning Kamp {
616b00cf46SPoul-Henning Kamp 	static u_int now;
6262efba6aSPoul-Henning Kamp 
6362efba6aSPoul-Henning Kamp 	return (++now);
6462efba6aSPoul-Henning Kamp }
6562efba6aSPoul-Henning Kamp 
6662efba6aSPoul-Henning Kamp static struct timecounter dummy_timecounter = {
6778a49a45SPoul-Henning Kamp 	dummy_get_timecount, 0, ~0u, 1000000, "dummy", -1000000
6862efba6aSPoul-Henning Kamp };
6962efba6aSPoul-Henning Kamp 
7062efba6aSPoul-Henning Kamp struct timehands {
7162efba6aSPoul-Henning Kamp 	/* These fields must be initialized by the driver. */
726b00cf46SPoul-Henning Kamp 	struct timecounter	*th_counter;
736b00cf46SPoul-Henning Kamp 	int64_t			th_adjustment;
7460ae52f7SEd Schouten 	uint64_t		th_scale;
756b00cf46SPoul-Henning Kamp 	u_int	 		th_offset_count;
766b00cf46SPoul-Henning Kamp 	struct bintime		th_offset;
7750c22263SKonstantin Belousov 	struct bintime		th_bintime;
786b00cf46SPoul-Henning Kamp 	struct timeval		th_microtime;
796b00cf46SPoul-Henning Kamp 	struct timespec		th_nanotime;
805760b029SKonstantin Belousov 	struct bintime		th_boottime;
8139acc78aSPoul-Henning Kamp 	/* Fields not to be copied in tc_windup start with th_generation. */
822c6946dcSKonstantin Belousov 	u_int			th_generation;
836b00cf46SPoul-Henning Kamp 	struct timehands	*th_next;
8462efba6aSPoul-Henning Kamp };
8562efba6aSPoul-Henning Kamp 
865b1c0294SDavid E. O'Brien static struct timehands th0;
87a83c016fSKonstantin Belousov static struct timehands th1 = {
88a83c016fSKonstantin Belousov 	.th_next = &th0
89a83c016fSKonstantin Belousov };
90f5d157fbSPoul-Henning Kamp static struct timehands th0 = {
91a83c016fSKonstantin Belousov 	.th_counter = &dummy_timecounter,
92a83c016fSKonstantin Belousov 	.th_scale = (uint64_t)-1 / 1000000,
93a83c016fSKonstantin Belousov 	.th_offset = { .sec = 1 },
94a83c016fSKonstantin Belousov 	.th_generation = 1,
95a83c016fSKonstantin Belousov 	.th_next = &th1
96f5d157fbSPoul-Henning Kamp };
9762efba6aSPoul-Henning Kamp 
9862efba6aSPoul-Henning Kamp static struct timehands *volatile timehands = &th0;
9962efba6aSPoul-Henning Kamp struct timecounter *timecounter = &dummy_timecounter;
10062efba6aSPoul-Henning Kamp static struct timecounter *timecounters = &dummy_timecounter;
1013bac064fSPoul-Henning Kamp 
1020e189873SAlexander Motin int tc_min_ticktock_freq = 1;
1030e189873SAlexander Motin 
104a8df530dSJohn Baldwin volatile time_t time_second = 1;
105a8df530dSJohn Baldwin volatile time_t time_uptime = 1;
106227ee8a1SPoul-Henning Kamp 
107a7bc3102SPeter Wemm static int sysctl_kern_boottime(SYSCTL_HANDLER_ARGS);
108a7bc3102SPeter Wemm SYSCTL_PROC(_kern, KERN_BOOTTIME, boottime, CTLTYPE_STRUCT|CTLFLAG_RD,
109a7bc3102SPeter Wemm     NULL, 0, sysctl_kern_boottime, "S,timeval", "System boottime");
11037d38777SBruce Evans 
11191266b96SPoul-Henning Kamp SYSCTL_NODE(_kern, OID_AUTO, timecounter, CTLFLAG_RW, 0, "");
1126472ac3dSEd Schouten static SYSCTL_NODE(_kern_timecounter, OID_AUTO, tc, CTLFLAG_RW, 0, "");
11391266b96SPoul-Henning Kamp 
1144e74721cSPoul-Henning Kamp static int timestepwarnings;
1154e74721cSPoul-Henning Kamp SYSCTL_INT(_kern_timecounter, OID_AUTO, stepwarnings, CTLFLAG_RW,
1162baa5cddSRebecca Cran     &timestepwarnings, 0, "Log time steps");
1174e74721cSPoul-Henning Kamp 
1185b999a6bSDavide Italiano struct bintime bt_timethreshold;
1195b999a6bSDavide Italiano struct bintime bt_tickthreshold;
1205b999a6bSDavide Italiano sbintime_t sbt_timethreshold;
1215b999a6bSDavide Italiano sbintime_t sbt_tickthreshold;
1225b999a6bSDavide Italiano struct bintime tc_tick_bt;
1235b999a6bSDavide Italiano sbintime_t tc_tick_sbt;
1245b999a6bSDavide Italiano int tc_precexp;
1255b999a6bSDavide Italiano int tc_timepercentage = TC_DEFAULTPERC;
1265b999a6bSDavide Italiano static int sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS);
1275b999a6bSDavide Italiano SYSCTL_PROC(_kern_timecounter, OID_AUTO, alloweddeviation,
128af3b2549SHans Petter Selasky     CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, 0, 0,
1295b999a6bSDavide Italiano     sysctl_kern_timecounter_adjprecision, "I",
1305b999a6bSDavide Italiano     "Allowed time interval deviation in percents");
1315b999a6bSDavide Italiano 
1329dbdf2a1SEric van Gyzen volatile int rtc_generation = 1;
1339dbdf2a1SEric van Gyzen 
134e8bac3f2SIan Lepore static int tc_chosen;	/* Non-zero if a specific tc was chosen via sysctl. */
135e8bac3f2SIan Lepore 
1365760b029SKonstantin Belousov static void tc_windup(struct bintime *new_boottimebin);
137e8444a7eSPoul-Henning Kamp static void cpu_tick_calibrate(int);
1389e1b5510SPoul-Henning Kamp 
13957d025c3SGeorge V. Neville-Neil void dtrace_getnanotime(struct timespec *tsp);
14057d025c3SGeorge V. Neville-Neil 
141a7bc3102SPeter Wemm static int
142a7bc3102SPeter Wemm sysctl_kern_boottime(SYSCTL_HANDLER_ARGS)
143a7bc3102SPeter Wemm {
144584b675eSKonstantin Belousov 	struct timeval boottime;
145584b675eSKonstantin Belousov 
146584b675eSKonstantin Belousov 	getboottime(&boottime);
147584b675eSKonstantin Belousov 
148*7045ac43SOlivier Houchard /* i386 is the only arch which uses a 32bits time_t */
149*7045ac43SOlivier Houchard #ifdef __amd64__
150a7bc3102SPeter Wemm #ifdef SCTL_MASK32
151a7bc3102SPeter Wemm 	int tv[2];
152a7bc3102SPeter Wemm 
153a7bc3102SPeter Wemm 	if (req->flags & SCTL_MASK32) {
154a7bc3102SPeter Wemm 		tv[0] = boottime.tv_sec;
155a7bc3102SPeter Wemm 		tv[1] = boottime.tv_usec;
156584b675eSKonstantin Belousov 		return (SYSCTL_OUT(req, tv, sizeof(tv)));
157584b675eSKonstantin Belousov 	}
158a7bc3102SPeter Wemm #endif
1599624d947SJuli Mallett #endif
160584b675eSKonstantin Belousov 	return (SYSCTL_OUT(req, &boottime, sizeof(boottime)));
161a7bc3102SPeter Wemm }
1625b1a8eb3SPoul-Henning Kamp 
16393ef14a7SDavid Malone static int
16493ef14a7SDavid Malone sysctl_kern_timecounter_get(SYSCTL_HANDLER_ARGS)
16593ef14a7SDavid Malone {
16693ef14a7SDavid Malone 	u_int ncount;
16793ef14a7SDavid Malone 	struct timecounter *tc = arg1;
16893ef14a7SDavid Malone 
16993ef14a7SDavid Malone 	ncount = tc->tc_get_timecount(tc);
1704d29106eSKonstantin Belousov 	return (sysctl_handle_int(oidp, &ncount, 0, req));
17193ef14a7SDavid Malone }
17293ef14a7SDavid Malone 
17393ef14a7SDavid Malone static int
17493ef14a7SDavid Malone sysctl_kern_timecounter_freq(SYSCTL_HANDLER_ARGS)
17593ef14a7SDavid Malone {
17660ae52f7SEd Schouten 	uint64_t freq;
17793ef14a7SDavid Malone 	struct timecounter *tc = arg1;
17893ef14a7SDavid Malone 
17993ef14a7SDavid Malone 	freq = tc->tc_frequency;
1804d29106eSKonstantin Belousov 	return (sysctl_handle_64(oidp, &freq, 0, req));
18193ef14a7SDavid Malone }
18293ef14a7SDavid Malone 
18339acc78aSPoul-Henning Kamp /*
18439acc78aSPoul-Henning Kamp  * Return the difference between the timehands' counter value now and what
18539acc78aSPoul-Henning Kamp  * was when we copied it to the timehands' offset_count.
18639acc78aSPoul-Henning Kamp  */
1876b00cf46SPoul-Henning Kamp static __inline u_int
1886b00cf46SPoul-Henning Kamp tc_delta(struct timehands *th)
189e796e00dSPoul-Henning Kamp {
1906b00cf46SPoul-Henning Kamp 	struct timecounter *tc;
191e796e00dSPoul-Henning Kamp 
1926b00cf46SPoul-Henning Kamp 	tc = th->th_counter;
1936b00cf46SPoul-Henning Kamp 	return ((tc->tc_get_timecount(tc) - th->th_offset_count) &
1946b00cf46SPoul-Henning Kamp 	    tc->tc_counter_mask);
195e796e00dSPoul-Henning Kamp }
196a0502b19SPoul-Henning Kamp 
19739acc78aSPoul-Henning Kamp /*
1986b00cf46SPoul-Henning Kamp  * Functions for reading the time.  We have to loop until we are sure that
19939acc78aSPoul-Henning Kamp  * the timehands that we operated on was not updated under our feet.  See
20039acc78aSPoul-Henning Kamp  * the comment in <sys/time.h> for a description of these 12 functions.
2016b00cf46SPoul-Henning Kamp  */
2026b00cf46SPoul-Henning Kamp 
2039bce0f05SLawrence Stewart #ifdef FFCLOCK
204e977bac3SLawrence Stewart void
2059bce0f05SLawrence Stewart fbclock_binuptime(struct bintime *bt)
2069bce0f05SLawrence Stewart {
2079bce0f05SLawrence Stewart 	struct timehands *th;
2089bce0f05SLawrence Stewart 	unsigned int gen;
2099bce0f05SLawrence Stewart 
2109bce0f05SLawrence Stewart 	do {
2119bce0f05SLawrence Stewart 		th = timehands;
212f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
2139bce0f05SLawrence Stewart 		*bt = th->th_offset;
2149bce0f05SLawrence Stewart 		bintime_addx(bt, th->th_scale * tc_delta(th));
215f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
216f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
2179bce0f05SLawrence Stewart }
2189bce0f05SLawrence Stewart 
219e977bac3SLawrence Stewart void
2209bce0f05SLawrence Stewart fbclock_nanouptime(struct timespec *tsp)
2219bce0f05SLawrence Stewart {
2229bce0f05SLawrence Stewart 	struct bintime bt;
2239bce0f05SLawrence Stewart 
224c2a4ee99SLawrence Stewart 	fbclock_binuptime(&bt);
2259bce0f05SLawrence Stewart 	bintime2timespec(&bt, tsp);
2269bce0f05SLawrence Stewart }
2279bce0f05SLawrence Stewart 
228e977bac3SLawrence Stewart void
2299bce0f05SLawrence Stewart fbclock_microuptime(struct timeval *tvp)
2309bce0f05SLawrence Stewart {
2319bce0f05SLawrence Stewart 	struct bintime bt;
2329bce0f05SLawrence Stewart 
233c2a4ee99SLawrence Stewart 	fbclock_binuptime(&bt);
2349bce0f05SLawrence Stewart 	bintime2timeval(&bt, tvp);
2359bce0f05SLawrence Stewart }
2369bce0f05SLawrence Stewart 
237e977bac3SLawrence Stewart void
2389bce0f05SLawrence Stewart fbclock_bintime(struct bintime *bt)
2399bce0f05SLawrence Stewart {
2405760b029SKonstantin Belousov 	struct timehands *th;
2415760b029SKonstantin Belousov 	unsigned int gen;
2429bce0f05SLawrence Stewart 
2435760b029SKonstantin Belousov 	do {
2445760b029SKonstantin Belousov 		th = timehands;
2455760b029SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
24650c22263SKonstantin Belousov 		*bt = th->th_bintime;
2475760b029SKonstantin Belousov 		bintime_addx(bt, th->th_scale * tc_delta(th));
2485760b029SKonstantin Belousov 		atomic_thread_fence_acq();
2495760b029SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
2509bce0f05SLawrence Stewart }
2519bce0f05SLawrence Stewart 
252e977bac3SLawrence Stewart void
2539bce0f05SLawrence Stewart fbclock_nanotime(struct timespec *tsp)
2549bce0f05SLawrence Stewart {
2559bce0f05SLawrence Stewart 	struct bintime bt;
2569bce0f05SLawrence Stewart 
257c2a4ee99SLawrence Stewart 	fbclock_bintime(&bt);
2589bce0f05SLawrence Stewart 	bintime2timespec(&bt, tsp);
2599bce0f05SLawrence Stewart }
2609bce0f05SLawrence Stewart 
261e977bac3SLawrence Stewart void
2629bce0f05SLawrence Stewart fbclock_microtime(struct timeval *tvp)
2639bce0f05SLawrence Stewart {
2649bce0f05SLawrence Stewart 	struct bintime bt;
2659bce0f05SLawrence Stewart 
266c2a4ee99SLawrence Stewart 	fbclock_bintime(&bt);
2679bce0f05SLawrence Stewart 	bintime2timeval(&bt, tvp);
2689bce0f05SLawrence Stewart }
2699bce0f05SLawrence Stewart 
270e977bac3SLawrence Stewart void
2719bce0f05SLawrence Stewart fbclock_getbinuptime(struct bintime *bt)
2729bce0f05SLawrence Stewart {
2739bce0f05SLawrence Stewart 	struct timehands *th;
2749bce0f05SLawrence Stewart 	unsigned int gen;
2759bce0f05SLawrence Stewart 
2769bce0f05SLawrence Stewart 	do {
2779bce0f05SLawrence Stewart 		th = timehands;
278f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
2799bce0f05SLawrence Stewart 		*bt = th->th_offset;
280f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
281f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
2829bce0f05SLawrence Stewart }
2839bce0f05SLawrence Stewart 
284e977bac3SLawrence Stewart void
2859bce0f05SLawrence Stewart fbclock_getnanouptime(struct timespec *tsp)
2869bce0f05SLawrence Stewart {
2879bce0f05SLawrence Stewart 	struct timehands *th;
2889bce0f05SLawrence Stewart 	unsigned int gen;
2899bce0f05SLawrence Stewart 
2909bce0f05SLawrence Stewart 	do {
2919bce0f05SLawrence Stewart 		th = timehands;
292f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
2939bce0f05SLawrence Stewart 		bintime2timespec(&th->th_offset, tsp);
294f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
295f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
2969bce0f05SLawrence Stewart }
2979bce0f05SLawrence Stewart 
298e977bac3SLawrence Stewart void
2999bce0f05SLawrence Stewart fbclock_getmicrouptime(struct timeval *tvp)
3009bce0f05SLawrence Stewart {
3019bce0f05SLawrence Stewart 	struct timehands *th;
3029bce0f05SLawrence Stewart 	unsigned int gen;
3039bce0f05SLawrence Stewart 
3049bce0f05SLawrence Stewart 	do {
3059bce0f05SLawrence Stewart 		th = timehands;
306f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
3079bce0f05SLawrence Stewart 		bintime2timeval(&th->th_offset, tvp);
308f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
309f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
3109bce0f05SLawrence Stewart }
3119bce0f05SLawrence Stewart 
312e977bac3SLawrence Stewart void
3139bce0f05SLawrence Stewart fbclock_getbintime(struct bintime *bt)
3149bce0f05SLawrence Stewart {
3159bce0f05SLawrence Stewart 	struct timehands *th;
3169bce0f05SLawrence Stewart 	unsigned int gen;
3179bce0f05SLawrence Stewart 
3189bce0f05SLawrence Stewart 	do {
3199bce0f05SLawrence Stewart 		th = timehands;
320f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
32150c22263SKonstantin Belousov 		*bt = th->th_bintime;
322f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
323f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
3249bce0f05SLawrence Stewart }
3259bce0f05SLawrence Stewart 
326e977bac3SLawrence Stewart void
3279bce0f05SLawrence Stewart fbclock_getnanotime(struct timespec *tsp)
3289bce0f05SLawrence Stewart {
3299bce0f05SLawrence Stewart 	struct timehands *th;
3309bce0f05SLawrence Stewart 	unsigned int gen;
3319bce0f05SLawrence Stewart 
3329bce0f05SLawrence Stewart 	do {
3339bce0f05SLawrence Stewart 		th = timehands;
334f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
3359bce0f05SLawrence Stewart 		*tsp = th->th_nanotime;
336f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
337f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
3389bce0f05SLawrence Stewart }
3399bce0f05SLawrence Stewart 
340e977bac3SLawrence Stewart void
3419bce0f05SLawrence Stewart fbclock_getmicrotime(struct timeval *tvp)
3429bce0f05SLawrence Stewart {
3439bce0f05SLawrence Stewart 	struct timehands *th;
3449bce0f05SLawrence Stewart 	unsigned int gen;
3459bce0f05SLawrence Stewart 
3469bce0f05SLawrence Stewart 	do {
3479bce0f05SLawrence Stewart 		th = timehands;
348f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
3499bce0f05SLawrence Stewart 		*tvp = th->th_microtime;
350f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
351f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
3529bce0f05SLawrence Stewart }
3539bce0f05SLawrence Stewart #else /* !FFCLOCK */
354a0502b19SPoul-Henning Kamp void
3552028c0cdSPoul-Henning Kamp binuptime(struct bintime *bt)
3562028c0cdSPoul-Henning Kamp {
3576b00cf46SPoul-Henning Kamp 	struct timehands *th;
3586b00cf46SPoul-Henning Kamp 	u_int gen;
3592028c0cdSPoul-Henning Kamp 
3605b7d8efaSPoul-Henning Kamp 	do {
3616b00cf46SPoul-Henning Kamp 		th = timehands;
362f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
3636b00cf46SPoul-Henning Kamp 		*bt = th->th_offset;
3646b00cf46SPoul-Henning Kamp 		bintime_addx(bt, th->th_scale * tc_delta(th));
365f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
366f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
3672028c0cdSPoul-Henning Kamp }
3682028c0cdSPoul-Henning Kamp 
3692028c0cdSPoul-Henning Kamp void
37039acc78aSPoul-Henning Kamp nanouptime(struct timespec *tsp)
371056abcabSPoul-Henning Kamp {
372056abcabSPoul-Henning Kamp 	struct bintime bt;
373056abcabSPoul-Henning Kamp 
374056abcabSPoul-Henning Kamp 	binuptime(&bt);
37539acc78aSPoul-Henning Kamp 	bintime2timespec(&bt, tsp);
376056abcabSPoul-Henning Kamp }
377056abcabSPoul-Henning Kamp 
378056abcabSPoul-Henning Kamp void
37939acc78aSPoul-Henning Kamp microuptime(struct timeval *tvp)
380056abcabSPoul-Henning Kamp {
381056abcabSPoul-Henning Kamp 	struct bintime bt;
382056abcabSPoul-Henning Kamp 
383056abcabSPoul-Henning Kamp 	binuptime(&bt);
38439acc78aSPoul-Henning Kamp 	bintime2timeval(&bt, tvp);
385056abcabSPoul-Henning Kamp }
386056abcabSPoul-Henning Kamp 
387056abcabSPoul-Henning Kamp void
3882028c0cdSPoul-Henning Kamp bintime(struct bintime *bt)
3892028c0cdSPoul-Henning Kamp {
3905760b029SKonstantin Belousov 	struct timehands *th;
3915760b029SKonstantin Belousov 	u_int gen;
3922028c0cdSPoul-Henning Kamp 
3935760b029SKonstantin Belousov 	do {
3945760b029SKonstantin Belousov 		th = timehands;
3955760b029SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
39650c22263SKonstantin Belousov 		*bt = th->th_bintime;
3975760b029SKonstantin Belousov 		bintime_addx(bt, th->th_scale * tc_delta(th));
3985760b029SKonstantin Belousov 		atomic_thread_fence_acq();
3995760b029SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
4002028c0cdSPoul-Henning Kamp }
4012028c0cdSPoul-Henning Kamp 
4022028c0cdSPoul-Henning Kamp void
40339acc78aSPoul-Henning Kamp nanotime(struct timespec *tsp)
40400af9731SPoul-Henning Kamp {
4052028c0cdSPoul-Henning Kamp 	struct bintime bt;
40600af9731SPoul-Henning Kamp 
4072028c0cdSPoul-Henning Kamp 	bintime(&bt);
40839acc78aSPoul-Henning Kamp 	bintime2timespec(&bt, tsp);
40948115288SPoul-Henning Kamp }
41048115288SPoul-Henning Kamp 
41148115288SPoul-Henning Kamp void
41239acc78aSPoul-Henning Kamp microtime(struct timeval *tvp)
413056abcabSPoul-Henning Kamp {
414056abcabSPoul-Henning Kamp 	struct bintime bt;
415056abcabSPoul-Henning Kamp 
416056abcabSPoul-Henning Kamp 	bintime(&bt);
41739acc78aSPoul-Henning Kamp 	bintime2timeval(&bt, tvp);
418056abcabSPoul-Henning Kamp }
419056abcabSPoul-Henning Kamp 
420056abcabSPoul-Henning Kamp void
421056abcabSPoul-Henning Kamp getbinuptime(struct bintime *bt)
42200af9731SPoul-Henning Kamp {
4236b00cf46SPoul-Henning Kamp 	struct timehands *th;
4246b00cf46SPoul-Henning Kamp 	u_int gen;
42500af9731SPoul-Henning Kamp 
4265b7d8efaSPoul-Henning Kamp 	do {
4276b00cf46SPoul-Henning Kamp 		th = timehands;
428f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
4296b00cf46SPoul-Henning Kamp 		*bt = th->th_offset;
430f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
431f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
432a0502b19SPoul-Henning Kamp }
433a0502b19SPoul-Henning Kamp 
434a0502b19SPoul-Henning Kamp void
435c21410e1SPoul-Henning Kamp getnanouptime(struct timespec *tsp)
436a0502b19SPoul-Henning Kamp {
4376b00cf46SPoul-Henning Kamp 	struct timehands *th;
4386b00cf46SPoul-Henning Kamp 	u_int gen;
439a0502b19SPoul-Henning Kamp 
4405b7d8efaSPoul-Henning Kamp 	do {
4416b00cf46SPoul-Henning Kamp 		th = timehands;
442f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
4436b00cf46SPoul-Henning Kamp 		bintime2timespec(&th->th_offset, tsp);
444f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
445f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
446a0502b19SPoul-Henning Kamp }
447a0502b19SPoul-Henning Kamp 
448c7c9a816SPoul-Henning Kamp void
449056abcabSPoul-Henning Kamp getmicrouptime(struct timeval *tvp)
450c7c9a816SPoul-Henning Kamp {
4516b00cf46SPoul-Henning Kamp 	struct timehands *th;
4526b00cf46SPoul-Henning Kamp 	u_int gen;
4537ec73f64SPoul-Henning Kamp 
454056abcabSPoul-Henning Kamp 	do {
4556b00cf46SPoul-Henning Kamp 		th = timehands;
456f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
4576b00cf46SPoul-Henning Kamp 		bintime2timeval(&th->th_offset, tvp);
458f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
459f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
4607ec73f64SPoul-Henning Kamp }
4617ec73f64SPoul-Henning Kamp 
4627ec73f64SPoul-Henning Kamp void
463056abcabSPoul-Henning Kamp getbintime(struct bintime *bt)
4647ec73f64SPoul-Henning Kamp {
4656b00cf46SPoul-Henning Kamp 	struct timehands *th;
4666b00cf46SPoul-Henning Kamp 	u_int gen;
4677ec73f64SPoul-Henning Kamp 
468056abcabSPoul-Henning Kamp 	do {
4696b00cf46SPoul-Henning Kamp 		th = timehands;
470f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
47150c22263SKonstantin Belousov 		*bt = th->th_bintime;
472f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
473f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
474056abcabSPoul-Henning Kamp }
475056abcabSPoul-Henning Kamp 
476056abcabSPoul-Henning Kamp void
477056abcabSPoul-Henning Kamp getnanotime(struct timespec *tsp)
478056abcabSPoul-Henning Kamp {
4796b00cf46SPoul-Henning Kamp 	struct timehands *th;
4806b00cf46SPoul-Henning Kamp 	u_int gen;
481056abcabSPoul-Henning Kamp 
482056abcabSPoul-Henning Kamp 	do {
4836b00cf46SPoul-Henning Kamp 		th = timehands;
484f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
4856b00cf46SPoul-Henning Kamp 		*tsp = th->th_nanotime;
486f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
487f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
488056abcabSPoul-Henning Kamp }
489056abcabSPoul-Henning Kamp 
490056abcabSPoul-Henning Kamp void
491056abcabSPoul-Henning Kamp getmicrotime(struct timeval *tvp)
492056abcabSPoul-Henning Kamp {
4936b00cf46SPoul-Henning Kamp 	struct timehands *th;
4946b00cf46SPoul-Henning Kamp 	u_int gen;
495056abcabSPoul-Henning Kamp 
496056abcabSPoul-Henning Kamp 	do {
4976b00cf46SPoul-Henning Kamp 		th = timehands;
498f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
4996b00cf46SPoul-Henning Kamp 		*tvp = th->th_microtime;
500f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
501f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
5027ec73f64SPoul-Henning Kamp }
5039bce0f05SLawrence Stewart #endif /* FFCLOCK */
5047ec73f64SPoul-Henning Kamp 
505584b675eSKonstantin Belousov void
506584b675eSKonstantin Belousov getboottime(struct timeval *boottime)
507584b675eSKonstantin Belousov {
5085760b029SKonstantin Belousov 	struct bintime boottimebin;
509584b675eSKonstantin Belousov 
5105760b029SKonstantin Belousov 	getboottimebin(&boottimebin);
5115760b029SKonstantin Belousov 	bintime2timeval(&boottimebin, boottime);
512584b675eSKonstantin Belousov }
513584b675eSKonstantin Belousov 
514584b675eSKonstantin Belousov void
515584b675eSKonstantin Belousov getboottimebin(struct bintime *boottimebin)
516584b675eSKonstantin Belousov {
5175760b029SKonstantin Belousov 	struct timehands *th;
5185760b029SKonstantin Belousov 	u_int gen;
519584b675eSKonstantin Belousov 
5205760b029SKonstantin Belousov 	do {
5215760b029SKonstantin Belousov 		th = timehands;
5225760b029SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
5235760b029SKonstantin Belousov 		*boottimebin = th->th_boottime;
5245760b029SKonstantin Belousov 		atomic_thread_fence_acq();
5255760b029SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
526584b675eSKonstantin Belousov }
527584b675eSKonstantin Belousov 
528b0fdc837SLawrence Stewart #ifdef FFCLOCK
529b0fdc837SLawrence Stewart /*
530b0fdc837SLawrence Stewart  * Support for feed-forward synchronization algorithms. This is heavily inspired
531b0fdc837SLawrence Stewart  * by the timehands mechanism but kept independent from it. *_windup() functions
532b0fdc837SLawrence Stewart  * have some connection to avoid accessing the timecounter hardware more than
533b0fdc837SLawrence Stewart  * necessary.
534b0fdc837SLawrence Stewart  */
535b0fdc837SLawrence Stewart 
536b0fdc837SLawrence Stewart /* Feed-forward clock estimates kept updated by the synchronization daemon. */
537b0fdc837SLawrence Stewart struct ffclock_estimate ffclock_estimate;
538b0fdc837SLawrence Stewart struct bintime ffclock_boottime;	/* Feed-forward boot time estimate. */
539b0fdc837SLawrence Stewart uint32_t ffclock_status;		/* Feed-forward clock status. */
540b0fdc837SLawrence Stewart int8_t ffclock_updated;			/* New estimates are available. */
541b0fdc837SLawrence Stewart struct mtx ffclock_mtx;			/* Mutex on ffclock_estimate. */
542b0fdc837SLawrence Stewart 
543b0fdc837SLawrence Stewart struct fftimehands {
544b0fdc837SLawrence Stewart 	struct ffclock_estimate	cest;
545b0fdc837SLawrence Stewart 	struct bintime		tick_time;
546b0fdc837SLawrence Stewart 	struct bintime		tick_time_lerp;
547b0fdc837SLawrence Stewart 	ffcounter		tick_ffcount;
548b0fdc837SLawrence Stewart 	uint64_t		period_lerp;
549b0fdc837SLawrence Stewart 	volatile uint8_t	gen;
550b0fdc837SLawrence Stewart 	struct fftimehands	*next;
551b0fdc837SLawrence Stewart };
552b0fdc837SLawrence Stewart 
553b0fdc837SLawrence Stewart #define	NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))
554b0fdc837SLawrence Stewart 
555b0fdc837SLawrence Stewart static struct fftimehands ffth[10];
556b0fdc837SLawrence Stewart static struct fftimehands *volatile fftimehands = ffth;
557b0fdc837SLawrence Stewart 
558b0fdc837SLawrence Stewart static void
559b0fdc837SLawrence Stewart ffclock_init(void)
560b0fdc837SLawrence Stewart {
561b0fdc837SLawrence Stewart 	struct fftimehands *cur;
562b0fdc837SLawrence Stewart 	struct fftimehands *last;
563b0fdc837SLawrence Stewart 
564b0fdc837SLawrence Stewart 	memset(ffth, 0, sizeof(ffth));
565b0fdc837SLawrence Stewart 
566b0fdc837SLawrence Stewart 	last = ffth + NUM_ELEMENTS(ffth) - 1;
567b0fdc837SLawrence Stewart 	for (cur = ffth; cur < last; cur++)
568b0fdc837SLawrence Stewart 		cur->next = cur + 1;
569b0fdc837SLawrence Stewart 	last->next = ffth;
570b0fdc837SLawrence Stewart 
571b0fdc837SLawrence Stewart 	ffclock_updated = 0;
572b0fdc837SLawrence Stewart 	ffclock_status = FFCLOCK_STA_UNSYNC;
573b0fdc837SLawrence Stewart 	mtx_init(&ffclock_mtx, "ffclock lock", NULL, MTX_DEF);
574b0fdc837SLawrence Stewart }
575b0fdc837SLawrence Stewart 
576b0fdc837SLawrence Stewart /*
577b0fdc837SLawrence Stewart  * Reset the feed-forward clock estimates. Called from inittodr() to get things
578b0fdc837SLawrence Stewart  * kick started and uses the timecounter nominal frequency as a first period
579b0fdc837SLawrence Stewart  * estimate. Note: this function may be called several time just after boot.
580b0fdc837SLawrence Stewart  * Note: this is the only function that sets the value of boot time for the
581b0fdc837SLawrence Stewart  * monotonic (i.e. uptime) version of the feed-forward clock.
582b0fdc837SLawrence Stewart  */
583b0fdc837SLawrence Stewart void
584b0fdc837SLawrence Stewart ffclock_reset_clock(struct timespec *ts)
585b0fdc837SLawrence Stewart {
586b0fdc837SLawrence Stewart 	struct timecounter *tc;
587b0fdc837SLawrence Stewart 	struct ffclock_estimate cest;
588b0fdc837SLawrence Stewart 
589b0fdc837SLawrence Stewart 	tc = timehands->th_counter;
590b0fdc837SLawrence Stewart 	memset(&cest, 0, sizeof(struct ffclock_estimate));
591b0fdc837SLawrence Stewart 
592b0fdc837SLawrence Stewart 	timespec2bintime(ts, &ffclock_boottime);
593b0fdc837SLawrence Stewart 	timespec2bintime(ts, &(cest.update_time));
594b0fdc837SLawrence Stewart 	ffclock_read_counter(&cest.update_ffcount);
595b0fdc837SLawrence Stewart 	cest.leapsec_next = 0;
596b0fdc837SLawrence Stewart 	cest.period = ((1ULL << 63) / tc->tc_frequency) << 1;
597b0fdc837SLawrence Stewart 	cest.errb_abs = 0;
598b0fdc837SLawrence Stewart 	cest.errb_rate = 0;
599b0fdc837SLawrence Stewart 	cest.status = FFCLOCK_STA_UNSYNC;
600b0fdc837SLawrence Stewart 	cest.leapsec_total = 0;
601b0fdc837SLawrence Stewart 	cest.leapsec = 0;
602b0fdc837SLawrence Stewart 
603b0fdc837SLawrence Stewart 	mtx_lock(&ffclock_mtx);
604b0fdc837SLawrence Stewart 	bcopy(&cest, &ffclock_estimate, sizeof(struct ffclock_estimate));
605b0fdc837SLawrence Stewart 	ffclock_updated = INT8_MAX;
606b0fdc837SLawrence Stewart 	mtx_unlock(&ffclock_mtx);
607b0fdc837SLawrence Stewart 
608b0fdc837SLawrence Stewart 	printf("ffclock reset: %s (%llu Hz), time = %ld.%09lu\n", tc->tc_name,
609b0fdc837SLawrence Stewart 	    (unsigned long long)tc->tc_frequency, (long)ts->tv_sec,
610b0fdc837SLawrence Stewart 	    (unsigned long)ts->tv_nsec);
611b0fdc837SLawrence Stewart }
612b0fdc837SLawrence Stewart 
613b0fdc837SLawrence Stewart /*
614b0fdc837SLawrence Stewart  * Sub-routine to convert a time interval measured in RAW counter units to time
615b0fdc837SLawrence Stewart  * in seconds stored in bintime format.
616b0fdc837SLawrence Stewart  * NOTE: bintime_mul requires u_int, but the value of the ffcounter may be
617b0fdc837SLawrence Stewart  * larger than the max value of u_int (on 32 bit architecture). Loop to consume
618b0fdc837SLawrence Stewart  * extra cycles.
619b0fdc837SLawrence Stewart  */
620b0fdc837SLawrence Stewart static void
621b0fdc837SLawrence Stewart ffclock_convert_delta(ffcounter ffdelta, uint64_t period, struct bintime *bt)
622b0fdc837SLawrence Stewart {
623b0fdc837SLawrence Stewart 	struct bintime bt2;
624b0fdc837SLawrence Stewart 	ffcounter delta, delta_max;
625b0fdc837SLawrence Stewart 
626b0fdc837SLawrence Stewart 	delta_max = (1ULL << (8 * sizeof(unsigned int))) - 1;
627b0fdc837SLawrence Stewart 	bintime_clear(bt);
628b0fdc837SLawrence Stewart 	do {
629b0fdc837SLawrence Stewart 		if (ffdelta > delta_max)
630b0fdc837SLawrence Stewart 			delta = delta_max;
631b0fdc837SLawrence Stewart 		else
632b0fdc837SLawrence Stewart 			delta = ffdelta;
633b0fdc837SLawrence Stewart 		bt2.sec = 0;
634b0fdc837SLawrence Stewart 		bt2.frac = period;
635b0fdc837SLawrence Stewart 		bintime_mul(&bt2, (unsigned int)delta);
636b0fdc837SLawrence Stewart 		bintime_add(bt, &bt2);
637b0fdc837SLawrence Stewart 		ffdelta -= delta;
638b0fdc837SLawrence Stewart 	} while (ffdelta > 0);
639b0fdc837SLawrence Stewart }
640b0fdc837SLawrence Stewart 
641b0fdc837SLawrence Stewart /*
642b0fdc837SLawrence Stewart  * Update the fftimehands.
643b0fdc837SLawrence Stewart  * Push the tick ffcount and time(s) forward based on current clock estimate.
644b0fdc837SLawrence Stewart  * The conversion from ffcounter to bintime relies on the difference clock
645b0fdc837SLawrence Stewart  * principle, whose accuracy relies on computing small time intervals. If a new
646b0fdc837SLawrence Stewart  * clock estimate has been passed by the synchronisation daemon, make it
647b0fdc837SLawrence Stewart  * current, and compute the linear interpolation for monotonic time if needed.
648b0fdc837SLawrence Stewart  */
649b0fdc837SLawrence Stewart static void
650b0fdc837SLawrence Stewart ffclock_windup(unsigned int delta)
651b0fdc837SLawrence Stewart {
652b0fdc837SLawrence Stewart 	struct ffclock_estimate *cest;
653b0fdc837SLawrence Stewart 	struct fftimehands *ffth;
654b0fdc837SLawrence Stewart 	struct bintime bt, gap_lerp;
655b0fdc837SLawrence Stewart 	ffcounter ffdelta;
656b0fdc837SLawrence Stewart 	uint64_t frac;
657b0fdc837SLawrence Stewart 	unsigned int polling;
658b0fdc837SLawrence Stewart 	uint8_t forward_jump, ogen;
659b0fdc837SLawrence Stewart 
660b0fdc837SLawrence Stewart 	/*
661b0fdc837SLawrence Stewart 	 * Pick the next timehand, copy current ffclock estimates and move tick
662b0fdc837SLawrence Stewart 	 * times and counter forward.
663b0fdc837SLawrence Stewart 	 */
664b0fdc837SLawrence Stewart 	forward_jump = 0;
665b0fdc837SLawrence Stewart 	ffth = fftimehands->next;
666b0fdc837SLawrence Stewart 	ogen = ffth->gen;
667b0fdc837SLawrence Stewart 	ffth->gen = 0;
668b0fdc837SLawrence Stewart 	cest = &ffth->cest;
669b0fdc837SLawrence Stewart 	bcopy(&fftimehands->cest, cest, sizeof(struct ffclock_estimate));
670b0fdc837SLawrence Stewart 	ffdelta = (ffcounter)delta;
671b0fdc837SLawrence Stewart 	ffth->period_lerp = fftimehands->period_lerp;
672b0fdc837SLawrence Stewart 
673b0fdc837SLawrence Stewart 	ffth->tick_time = fftimehands->tick_time;
674b0fdc837SLawrence Stewart 	ffclock_convert_delta(ffdelta, cest->period, &bt);
675b0fdc837SLawrence Stewart 	bintime_add(&ffth->tick_time, &bt);
676b0fdc837SLawrence Stewart 
677b0fdc837SLawrence Stewart 	ffth->tick_time_lerp = fftimehands->tick_time_lerp;
678b0fdc837SLawrence Stewart 	ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt);
679b0fdc837SLawrence Stewart 	bintime_add(&ffth->tick_time_lerp, &bt);
680b0fdc837SLawrence Stewart 
681b0fdc837SLawrence Stewart 	ffth->tick_ffcount = fftimehands->tick_ffcount + ffdelta;
682b0fdc837SLawrence Stewart 
683b0fdc837SLawrence Stewart 	/*
684b0fdc837SLawrence Stewart 	 * Assess the status of the clock, if the last update is too old, it is
685b0fdc837SLawrence Stewart 	 * likely the synchronisation daemon is dead and the clock is free
686b0fdc837SLawrence Stewart 	 * running.
687b0fdc837SLawrence Stewart 	 */
688b0fdc837SLawrence Stewart 	if (ffclock_updated == 0) {
689b0fdc837SLawrence Stewart 		ffdelta = ffth->tick_ffcount - cest->update_ffcount;
690b0fdc837SLawrence Stewart 		ffclock_convert_delta(ffdelta, cest->period, &bt);
691b0fdc837SLawrence Stewart 		if (bt.sec > 2 * FFCLOCK_SKM_SCALE)
692b0fdc837SLawrence Stewart 			ffclock_status |= FFCLOCK_STA_UNSYNC;
693b0fdc837SLawrence Stewart 	}
694b0fdc837SLawrence Stewart 
695b0fdc837SLawrence Stewart 	/*
696b0fdc837SLawrence Stewart 	 * If available, grab updated clock estimates and make them current.
697b0fdc837SLawrence Stewart 	 * Recompute time at this tick using the updated estimates. The clock
698b0fdc837SLawrence Stewart 	 * estimates passed the feed-forward synchronisation daemon may result
699b0fdc837SLawrence Stewart 	 * in time conversion that is not monotonically increasing (just after
700b0fdc837SLawrence Stewart 	 * the update). time_lerp is a particular linear interpolation over the
701b0fdc837SLawrence Stewart 	 * synchronisation algo polling period that ensures monotonicity for the
702b0fdc837SLawrence Stewart 	 * clock ids requesting it.
703b0fdc837SLawrence Stewart 	 */
704b0fdc837SLawrence Stewart 	if (ffclock_updated > 0) {
705b0fdc837SLawrence Stewart 		bcopy(&ffclock_estimate, cest, sizeof(struct ffclock_estimate));
706b0fdc837SLawrence Stewart 		ffdelta = ffth->tick_ffcount - cest->update_ffcount;
707b0fdc837SLawrence Stewart 		ffth->tick_time = cest->update_time;
708b0fdc837SLawrence Stewart 		ffclock_convert_delta(ffdelta, cest->period, &bt);
709b0fdc837SLawrence Stewart 		bintime_add(&ffth->tick_time, &bt);
710b0fdc837SLawrence Stewart 
711b0fdc837SLawrence Stewart 		/* ffclock_reset sets ffclock_updated to INT8_MAX */
712b0fdc837SLawrence Stewart 		if (ffclock_updated == INT8_MAX)
713b0fdc837SLawrence Stewart 			ffth->tick_time_lerp = ffth->tick_time;
714b0fdc837SLawrence Stewart 
715b0fdc837SLawrence Stewart 		if (bintime_cmp(&ffth->tick_time, &ffth->tick_time_lerp, >))
716b0fdc837SLawrence Stewart 			forward_jump = 1;
717b0fdc837SLawrence Stewart 		else
718b0fdc837SLawrence Stewart 			forward_jump = 0;
719b0fdc837SLawrence Stewart 
720b0fdc837SLawrence Stewart 		bintime_clear(&gap_lerp);
721b0fdc837SLawrence Stewart 		if (forward_jump) {
722b0fdc837SLawrence Stewart 			gap_lerp = ffth->tick_time;
723b0fdc837SLawrence Stewart 			bintime_sub(&gap_lerp, &ffth->tick_time_lerp);
724b0fdc837SLawrence Stewart 		} else {
725b0fdc837SLawrence Stewart 			gap_lerp = ffth->tick_time_lerp;
726b0fdc837SLawrence Stewart 			bintime_sub(&gap_lerp, &ffth->tick_time);
727b0fdc837SLawrence Stewart 		}
728b0fdc837SLawrence Stewart 
729b0fdc837SLawrence Stewart 		/*
730b0fdc837SLawrence Stewart 		 * The reset from the RTC clock may be far from accurate, and
731b0fdc837SLawrence Stewart 		 * reducing the gap between real time and interpolated time
732b0fdc837SLawrence Stewart 		 * could take a very long time if the interpolated clock insists
733b0fdc837SLawrence Stewart 		 * on strict monotonicity. The clock is reset under very strict
734b0fdc837SLawrence Stewart 		 * conditions (kernel time is known to be wrong and
735b0fdc837SLawrence Stewart 		 * synchronization daemon has been restarted recently.
736b0fdc837SLawrence Stewart 		 * ffclock_boottime absorbs the jump to ensure boot time is
737b0fdc837SLawrence Stewart 		 * correct and uptime functions stay consistent.
738b0fdc837SLawrence Stewart 		 */
739b0fdc837SLawrence Stewart 		if (((ffclock_status & FFCLOCK_STA_UNSYNC) == FFCLOCK_STA_UNSYNC) &&
740b0fdc837SLawrence Stewart 		    ((cest->status & FFCLOCK_STA_UNSYNC) == 0) &&
741b0fdc837SLawrence Stewart 		    ((cest->status & FFCLOCK_STA_WARMUP) == FFCLOCK_STA_WARMUP)) {
742b0fdc837SLawrence Stewart 			if (forward_jump)
743b0fdc837SLawrence Stewart 				bintime_add(&ffclock_boottime, &gap_lerp);
744b0fdc837SLawrence Stewart 			else
745b0fdc837SLawrence Stewart 				bintime_sub(&ffclock_boottime, &gap_lerp);
746b0fdc837SLawrence Stewart 			ffth->tick_time_lerp = ffth->tick_time;
747b0fdc837SLawrence Stewart 			bintime_clear(&gap_lerp);
748b0fdc837SLawrence Stewart 		}
749b0fdc837SLawrence Stewart 
750b0fdc837SLawrence Stewart 		ffclock_status = cest->status;
751b0fdc837SLawrence Stewart 		ffth->period_lerp = cest->period;
752b0fdc837SLawrence Stewart 
753b0fdc837SLawrence Stewart 		/*
754b0fdc837SLawrence Stewart 		 * Compute corrected period used for the linear interpolation of
755b0fdc837SLawrence Stewart 		 * time. The rate of linear interpolation is capped to 5000PPM
756b0fdc837SLawrence Stewart 		 * (5ms/s).
757b0fdc837SLawrence Stewart 		 */
758b0fdc837SLawrence Stewart 		if (bintime_isset(&gap_lerp)) {
759b0fdc837SLawrence Stewart 			ffdelta = cest->update_ffcount;
760b0fdc837SLawrence Stewart 			ffdelta -= fftimehands->cest.update_ffcount;
761b0fdc837SLawrence Stewart 			ffclock_convert_delta(ffdelta, cest->period, &bt);
762b0fdc837SLawrence Stewart 			polling = bt.sec;
763b0fdc837SLawrence Stewart 			bt.sec = 0;
764b0fdc837SLawrence Stewart 			bt.frac = 5000000 * (uint64_t)18446744073LL;
765b0fdc837SLawrence Stewart 			bintime_mul(&bt, polling);
766b0fdc837SLawrence Stewart 			if (bintime_cmp(&gap_lerp, &bt, >))
767b0fdc837SLawrence Stewart 				gap_lerp = bt;
768b0fdc837SLawrence Stewart 
769b0fdc837SLawrence Stewart 			/* Approximate 1 sec by 1-(1/2^64) to ease arithmetic */
770b0fdc837SLawrence Stewart 			frac = 0;
771b0fdc837SLawrence Stewart 			if (gap_lerp.sec > 0) {
772b0fdc837SLawrence Stewart 				frac -= 1;
773b0fdc837SLawrence Stewart 				frac /= ffdelta / gap_lerp.sec;
774b0fdc837SLawrence Stewart 			}
775b0fdc837SLawrence Stewart 			frac += gap_lerp.frac / ffdelta;
776b0fdc837SLawrence Stewart 
777b0fdc837SLawrence Stewart 			if (forward_jump)
778b0fdc837SLawrence Stewart 				ffth->period_lerp += frac;
779b0fdc837SLawrence Stewart 			else
780b0fdc837SLawrence Stewart 				ffth->period_lerp -= frac;
781b0fdc837SLawrence Stewart 		}
782b0fdc837SLawrence Stewart 
783b0fdc837SLawrence Stewart 		ffclock_updated = 0;
784b0fdc837SLawrence Stewart 	}
785b0fdc837SLawrence Stewart 	if (++ogen == 0)
786b0fdc837SLawrence Stewart 		ogen = 1;
787b0fdc837SLawrence Stewart 	ffth->gen = ogen;
788b0fdc837SLawrence Stewart 	fftimehands = ffth;
789b0fdc837SLawrence Stewart }
790b0fdc837SLawrence Stewart 
791b0fdc837SLawrence Stewart /*
792b0fdc837SLawrence Stewart  * Adjust the fftimehands when the timecounter is changed. Stating the obvious,
793b0fdc837SLawrence Stewart  * the old and new hardware counter cannot be read simultaneously. tc_windup()
794b0fdc837SLawrence Stewart  * does read the two counters 'back to back', but a few cycles are effectively
795b0fdc837SLawrence Stewart  * lost, and not accumulated in tick_ffcount. This is a fairly radical
796b0fdc837SLawrence Stewart  * operation for a feed-forward synchronization daemon, and it is its job to not
797b0fdc837SLawrence Stewart  * pushing irrelevant data to the kernel. Because there is no locking here,
798b0fdc837SLawrence Stewart  * simply force to ignore pending or next update to give daemon a chance to
799b0fdc837SLawrence Stewart  * realize the counter has changed.
800b0fdc837SLawrence Stewart  */
801b0fdc837SLawrence Stewart static void
802b0fdc837SLawrence Stewart ffclock_change_tc(struct timehands *th)
803b0fdc837SLawrence Stewart {
804b0fdc837SLawrence Stewart 	struct fftimehands *ffth;
805b0fdc837SLawrence Stewart 	struct ffclock_estimate *cest;
806b0fdc837SLawrence Stewart 	struct timecounter *tc;
807b0fdc837SLawrence Stewart 	uint8_t ogen;
808b0fdc837SLawrence Stewart 
809b0fdc837SLawrence Stewart 	tc = th->th_counter;
810b0fdc837SLawrence Stewart 	ffth = fftimehands->next;
811b0fdc837SLawrence Stewart 	ogen = ffth->gen;
812b0fdc837SLawrence Stewart 	ffth->gen = 0;
813b0fdc837SLawrence Stewart 
814b0fdc837SLawrence Stewart 	cest = &ffth->cest;
815b0fdc837SLawrence Stewart 	bcopy(&(fftimehands->cest), cest, sizeof(struct ffclock_estimate));
816b0fdc837SLawrence Stewart 	cest->period = ((1ULL << 63) / tc->tc_frequency ) << 1;
817b0fdc837SLawrence Stewart 	cest->errb_abs = 0;
818b0fdc837SLawrence Stewart 	cest->errb_rate = 0;
819b0fdc837SLawrence Stewart 	cest->status |= FFCLOCK_STA_UNSYNC;
820b0fdc837SLawrence Stewart 
821b0fdc837SLawrence Stewart 	ffth->tick_ffcount = fftimehands->tick_ffcount;
822b0fdc837SLawrence Stewart 	ffth->tick_time_lerp = fftimehands->tick_time_lerp;
823b0fdc837SLawrence Stewart 	ffth->tick_time = fftimehands->tick_time;
824b0fdc837SLawrence Stewart 	ffth->period_lerp = cest->period;
825b0fdc837SLawrence Stewart 
826b0fdc837SLawrence Stewart 	/* Do not lock but ignore next update from synchronization daemon. */
827b0fdc837SLawrence Stewart 	ffclock_updated--;
828b0fdc837SLawrence Stewart 
829b0fdc837SLawrence Stewart 	if (++ogen == 0)
830b0fdc837SLawrence Stewart 		ogen = 1;
831b0fdc837SLawrence Stewart 	ffth->gen = ogen;
832b0fdc837SLawrence Stewart 	fftimehands = ffth;
833b0fdc837SLawrence Stewart }
834b0fdc837SLawrence Stewart 
835b0fdc837SLawrence Stewart /*
836b0fdc837SLawrence Stewart  * Retrieve feed-forward counter and time of last kernel tick.
837b0fdc837SLawrence Stewart  */
838b0fdc837SLawrence Stewart void
839b0fdc837SLawrence Stewart ffclock_last_tick(ffcounter *ffcount, struct bintime *bt, uint32_t flags)
840b0fdc837SLawrence Stewart {
841b0fdc837SLawrence Stewart 	struct fftimehands *ffth;
842b0fdc837SLawrence Stewart 	uint8_t gen;
843b0fdc837SLawrence Stewart 
844b0fdc837SLawrence Stewart 	/*
845b0fdc837SLawrence Stewart 	 * No locking but check generation has not changed. Also need to make
846b0fdc837SLawrence Stewart 	 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
847b0fdc837SLawrence Stewart 	 */
848b0fdc837SLawrence Stewart 	do {
849b0fdc837SLawrence Stewart 		ffth = fftimehands;
850b0fdc837SLawrence Stewart 		gen = ffth->gen;
851b0fdc837SLawrence Stewart 		if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP)
852b0fdc837SLawrence Stewart 			*bt = ffth->tick_time_lerp;
853b0fdc837SLawrence Stewart 		else
854b0fdc837SLawrence Stewart 			*bt = ffth->tick_time;
855b0fdc837SLawrence Stewart 		*ffcount = ffth->tick_ffcount;
856b0fdc837SLawrence Stewart 	} while (gen == 0 || gen != ffth->gen);
857b0fdc837SLawrence Stewart }
858b0fdc837SLawrence Stewart 
859b0fdc837SLawrence Stewart /*
860b0fdc837SLawrence Stewart  * Absolute clock conversion. Low level function to convert ffcounter to
861b0fdc837SLawrence Stewart  * bintime. The ffcounter is converted using the current ffclock period estimate
862b0fdc837SLawrence Stewart  * or the "interpolated period" to ensure monotonicity.
863b0fdc837SLawrence Stewart  * NOTE: this conversion may have been deferred, and the clock updated since the
864b0fdc837SLawrence Stewart  * hardware counter has been read.
865b0fdc837SLawrence Stewart  */
866b0fdc837SLawrence Stewart void
867b0fdc837SLawrence Stewart ffclock_convert_abs(ffcounter ffcount, struct bintime *bt, uint32_t flags)
868b0fdc837SLawrence Stewart {
869b0fdc837SLawrence Stewart 	struct fftimehands *ffth;
870b0fdc837SLawrence Stewart 	struct bintime bt2;
871b0fdc837SLawrence Stewart 	ffcounter ffdelta;
872b0fdc837SLawrence Stewart 	uint8_t gen;
873b0fdc837SLawrence Stewart 
874b0fdc837SLawrence Stewart 	/*
875b0fdc837SLawrence Stewart 	 * No locking but check generation has not changed. Also need to make
876b0fdc837SLawrence Stewart 	 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
877b0fdc837SLawrence Stewart 	 */
878b0fdc837SLawrence Stewart 	do {
879b0fdc837SLawrence Stewart 		ffth = fftimehands;
880b0fdc837SLawrence Stewart 		gen = ffth->gen;
881b0fdc837SLawrence Stewart 		if (ffcount > ffth->tick_ffcount)
882b0fdc837SLawrence Stewart 			ffdelta = ffcount - ffth->tick_ffcount;
883b0fdc837SLawrence Stewart 		else
884b0fdc837SLawrence Stewart 			ffdelta = ffth->tick_ffcount - ffcount;
885b0fdc837SLawrence Stewart 
886b0fdc837SLawrence Stewart 		if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP) {
887b0fdc837SLawrence Stewart 			*bt = ffth->tick_time_lerp;
888b0fdc837SLawrence Stewart 			ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt2);
889b0fdc837SLawrence Stewart 		} else {
890b0fdc837SLawrence Stewart 			*bt = ffth->tick_time;
891b0fdc837SLawrence Stewart 			ffclock_convert_delta(ffdelta, ffth->cest.period, &bt2);
892b0fdc837SLawrence Stewart 		}
893b0fdc837SLawrence Stewart 
894b0fdc837SLawrence Stewart 		if (ffcount > ffth->tick_ffcount)
895b0fdc837SLawrence Stewart 			bintime_add(bt, &bt2);
896b0fdc837SLawrence Stewart 		else
897b0fdc837SLawrence Stewart 			bintime_sub(bt, &bt2);
898b0fdc837SLawrence Stewart 	} while (gen == 0 || gen != ffth->gen);
899b0fdc837SLawrence Stewart }
900b0fdc837SLawrence Stewart 
901b0fdc837SLawrence Stewart /*
902b0fdc837SLawrence Stewart  * Difference clock conversion.
903b0fdc837SLawrence Stewart  * Low level function to Convert a time interval measured in RAW counter units
904b0fdc837SLawrence Stewart  * into bintime. The difference clock allows measuring small intervals much more
905b0fdc837SLawrence Stewart  * reliably than the absolute clock.
906b0fdc837SLawrence Stewart  */
907b0fdc837SLawrence Stewart void
908b0fdc837SLawrence Stewart ffclock_convert_diff(ffcounter ffdelta, struct bintime *bt)
909b0fdc837SLawrence Stewart {
910b0fdc837SLawrence Stewart 	struct fftimehands *ffth;
911b0fdc837SLawrence Stewart 	uint8_t gen;
912b0fdc837SLawrence Stewart 
913b0fdc837SLawrence Stewart 	/* No locking but check generation has not changed. */
914b0fdc837SLawrence Stewart 	do {
915b0fdc837SLawrence Stewart 		ffth = fftimehands;
916b0fdc837SLawrence Stewart 		gen = ffth->gen;
917b0fdc837SLawrence Stewart 		ffclock_convert_delta(ffdelta, ffth->cest.period, bt);
918b0fdc837SLawrence Stewart 	} while (gen == 0 || gen != ffth->gen);
919b0fdc837SLawrence Stewart }
920b0fdc837SLawrence Stewart 
921b0fdc837SLawrence Stewart /*
922b0fdc837SLawrence Stewart  * Access to current ffcounter value.
923b0fdc837SLawrence Stewart  */
924b0fdc837SLawrence Stewart void
925b0fdc837SLawrence Stewart ffclock_read_counter(ffcounter *ffcount)
926b0fdc837SLawrence Stewart {
927b0fdc837SLawrence Stewart 	struct timehands *th;
928b0fdc837SLawrence Stewart 	struct fftimehands *ffth;
929b0fdc837SLawrence Stewart 	unsigned int gen, delta;
930b0fdc837SLawrence Stewart 
931b0fdc837SLawrence Stewart 	/*
932b0fdc837SLawrence Stewart 	 * ffclock_windup() called from tc_windup(), safe to rely on
933b0fdc837SLawrence Stewart 	 * th->th_generation only, for correct delta and ffcounter.
934b0fdc837SLawrence Stewart 	 */
935b0fdc837SLawrence Stewart 	do {
936b0fdc837SLawrence Stewart 		th = timehands;
937f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
938b0fdc837SLawrence Stewart 		ffth = fftimehands;
939b0fdc837SLawrence Stewart 		delta = tc_delta(th);
940b0fdc837SLawrence Stewart 		*ffcount = ffth->tick_ffcount;
941f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
942f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
943b0fdc837SLawrence Stewart 
944b0fdc837SLawrence Stewart 	*ffcount += delta;
945b0fdc837SLawrence Stewart }
9469bce0f05SLawrence Stewart 
9479bce0f05SLawrence Stewart void
9489bce0f05SLawrence Stewart binuptime(struct bintime *bt)
9499bce0f05SLawrence Stewart {
9509bce0f05SLawrence Stewart 
95188394fe4SLawrence Stewart 	binuptime_fromclock(bt, sysclock_active);
9529bce0f05SLawrence Stewart }
9539bce0f05SLawrence Stewart 
9549bce0f05SLawrence Stewart void
9559bce0f05SLawrence Stewart nanouptime(struct timespec *tsp)
9569bce0f05SLawrence Stewart {
9579bce0f05SLawrence Stewart 
95888394fe4SLawrence Stewart 	nanouptime_fromclock(tsp, sysclock_active);
9599bce0f05SLawrence Stewart }
9609bce0f05SLawrence Stewart 
9619bce0f05SLawrence Stewart void
9629bce0f05SLawrence Stewart microuptime(struct timeval *tvp)
9639bce0f05SLawrence Stewart {
9649bce0f05SLawrence Stewart 
96588394fe4SLawrence Stewart 	microuptime_fromclock(tvp, sysclock_active);
9669bce0f05SLawrence Stewart }
9679bce0f05SLawrence Stewart 
9689bce0f05SLawrence Stewart void
9699bce0f05SLawrence Stewart bintime(struct bintime *bt)
9709bce0f05SLawrence Stewart {
9719bce0f05SLawrence Stewart 
97288394fe4SLawrence Stewart 	bintime_fromclock(bt, sysclock_active);
9739bce0f05SLawrence Stewart }
9749bce0f05SLawrence Stewart 
9759bce0f05SLawrence Stewart void
9769bce0f05SLawrence Stewart nanotime(struct timespec *tsp)
9779bce0f05SLawrence Stewart {
9789bce0f05SLawrence Stewart 
97988394fe4SLawrence Stewart 	nanotime_fromclock(tsp, sysclock_active);
9809bce0f05SLawrence Stewart }
9819bce0f05SLawrence Stewart 
9829bce0f05SLawrence Stewart void
9839bce0f05SLawrence Stewart microtime(struct timeval *tvp)
9849bce0f05SLawrence Stewart {
9859bce0f05SLawrence Stewart 
98688394fe4SLawrence Stewart 	microtime_fromclock(tvp, sysclock_active);
9879bce0f05SLawrence Stewart }
9889bce0f05SLawrence Stewart 
9899bce0f05SLawrence Stewart void
9909bce0f05SLawrence Stewart getbinuptime(struct bintime *bt)
9919bce0f05SLawrence Stewart {
9929bce0f05SLawrence Stewart 
99388394fe4SLawrence Stewart 	getbinuptime_fromclock(bt, sysclock_active);
9949bce0f05SLawrence Stewart }
9959bce0f05SLawrence Stewart 
9969bce0f05SLawrence Stewart void
9979bce0f05SLawrence Stewart getnanouptime(struct timespec *tsp)
9989bce0f05SLawrence Stewart {
9999bce0f05SLawrence Stewart 
100088394fe4SLawrence Stewart 	getnanouptime_fromclock(tsp, sysclock_active);
10019bce0f05SLawrence Stewart }
10029bce0f05SLawrence Stewart 
10039bce0f05SLawrence Stewart void
10049bce0f05SLawrence Stewart getmicrouptime(struct timeval *tvp)
10059bce0f05SLawrence Stewart {
10069bce0f05SLawrence Stewart 
100788394fe4SLawrence Stewart 	getmicrouptime_fromclock(tvp, sysclock_active);
10089bce0f05SLawrence Stewart }
10099bce0f05SLawrence Stewart 
10109bce0f05SLawrence Stewart void
10119bce0f05SLawrence Stewart getbintime(struct bintime *bt)
10129bce0f05SLawrence Stewart {
10139bce0f05SLawrence Stewart 
101488394fe4SLawrence Stewart 	getbintime_fromclock(bt, sysclock_active);
10159bce0f05SLawrence Stewart }
10169bce0f05SLawrence Stewart 
10179bce0f05SLawrence Stewart void
10189bce0f05SLawrence Stewart getnanotime(struct timespec *tsp)
10199bce0f05SLawrence Stewart {
10209bce0f05SLawrence Stewart 
102188394fe4SLawrence Stewart 	getnanotime_fromclock(tsp, sysclock_active);
10229bce0f05SLawrence Stewart }
10239bce0f05SLawrence Stewart 
10249bce0f05SLawrence Stewart void
10259bce0f05SLawrence Stewart getmicrotime(struct timeval *tvp)
10269bce0f05SLawrence Stewart {
10279bce0f05SLawrence Stewart 
102888394fe4SLawrence Stewart 	getmicrouptime_fromclock(tvp, sysclock_active);
10299bce0f05SLawrence Stewart }
10306cedd609SLawrence Stewart 
1031b0fdc837SLawrence Stewart #endif /* FFCLOCK */
1032b0fdc837SLawrence Stewart 
103339acc78aSPoul-Henning Kamp /*
103457d025c3SGeorge V. Neville-Neil  * This is a clone of getnanotime and used for walltimestamps.
103557d025c3SGeorge V. Neville-Neil  * The dtrace_ prefix prevents fbt from creating probes for
103657d025c3SGeorge V. Neville-Neil  * it so walltimestamp can be safely used in all fbt probes.
103757d025c3SGeorge V. Neville-Neil  */
103857d025c3SGeorge V. Neville-Neil void
103957d025c3SGeorge V. Neville-Neil dtrace_getnanotime(struct timespec *tsp)
104057d025c3SGeorge V. Neville-Neil {
104157d025c3SGeorge V. Neville-Neil 	struct timehands *th;
104257d025c3SGeorge V. Neville-Neil 	u_int gen;
104357d025c3SGeorge V. Neville-Neil 
104457d025c3SGeorge V. Neville-Neil 	do {
104557d025c3SGeorge V. Neville-Neil 		th = timehands;
1046f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
104757d025c3SGeorge V. Neville-Neil 		*tsp = th->th_nanotime;
1048f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
1049f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
105057d025c3SGeorge V. Neville-Neil }
105157d025c3SGeorge V. Neville-Neil 
105257d025c3SGeorge V. Neville-Neil /*
10536cedd609SLawrence Stewart  * System clock currently providing time to the system. Modifiable via sysctl
10546cedd609SLawrence Stewart  * when the FFCLOCK option is defined.
10556cedd609SLawrence Stewart  */
10566cedd609SLawrence Stewart int sysclock_active = SYSCLOCK_FBCK;
10576cedd609SLawrence Stewart 
10586cedd609SLawrence Stewart /* Internal NTP status and error estimates. */
10596cedd609SLawrence Stewart extern int time_status;
10606cedd609SLawrence Stewart extern long time_esterror;
10616cedd609SLawrence Stewart 
10626cedd609SLawrence Stewart /*
10636cedd609SLawrence Stewart  * Take a snapshot of sysclock data which can be used to compare system clocks
10646cedd609SLawrence Stewart  * and generate timestamps after the fact.
10656cedd609SLawrence Stewart  */
10666cedd609SLawrence Stewart void
10676cedd609SLawrence Stewart sysclock_getsnapshot(struct sysclock_snap *clock_snap, int fast)
10686cedd609SLawrence Stewart {
10696cedd609SLawrence Stewart 	struct fbclock_info *fbi;
10706cedd609SLawrence Stewart 	struct timehands *th;
10716cedd609SLawrence Stewart 	struct bintime bt;
10726cedd609SLawrence Stewart 	unsigned int delta, gen;
10736cedd609SLawrence Stewart #ifdef FFCLOCK
10746cedd609SLawrence Stewart 	ffcounter ffcount;
10756cedd609SLawrence Stewart 	struct fftimehands *ffth;
10766cedd609SLawrence Stewart 	struct ffclock_info *ffi;
10776cedd609SLawrence Stewart 	struct ffclock_estimate cest;
10786cedd609SLawrence Stewart 
10796cedd609SLawrence Stewart 	ffi = &clock_snap->ff_info;
10806cedd609SLawrence Stewart #endif
10816cedd609SLawrence Stewart 
10826cedd609SLawrence Stewart 	fbi = &clock_snap->fb_info;
10836cedd609SLawrence Stewart 	delta = 0;
10846cedd609SLawrence Stewart 
10856cedd609SLawrence Stewart 	do {
10866cedd609SLawrence Stewart 		th = timehands;
1087f4b5a972SKonstantin Belousov 		gen = atomic_load_acq_int(&th->th_generation);
10886cedd609SLawrence Stewart 		fbi->th_scale = th->th_scale;
10896cedd609SLawrence Stewart 		fbi->tick_time = th->th_offset;
10906cedd609SLawrence Stewart #ifdef FFCLOCK
10916cedd609SLawrence Stewart 		ffth = fftimehands;
10926cedd609SLawrence Stewart 		ffi->tick_time = ffth->tick_time_lerp;
10936cedd609SLawrence Stewart 		ffi->tick_time_lerp = ffth->tick_time_lerp;
10946cedd609SLawrence Stewart 		ffi->period = ffth->cest.period;
10956cedd609SLawrence Stewart 		ffi->period_lerp = ffth->period_lerp;
10966cedd609SLawrence Stewart 		clock_snap->ffcount = ffth->tick_ffcount;
10976cedd609SLawrence Stewart 		cest = ffth->cest;
10986cedd609SLawrence Stewart #endif
10996cedd609SLawrence Stewart 		if (!fast)
11006cedd609SLawrence Stewart 			delta = tc_delta(th);
1101f4b5a972SKonstantin Belousov 		atomic_thread_fence_acq();
1102f4b5a972SKonstantin Belousov 	} while (gen == 0 || gen != th->th_generation);
11036cedd609SLawrence Stewart 
11046cedd609SLawrence Stewart 	clock_snap->delta = delta;
11056cedd609SLawrence Stewart 	clock_snap->sysclock_active = sysclock_active;
11066cedd609SLawrence Stewart 
11076cedd609SLawrence Stewart 	/* Record feedback clock status and error. */
11086cedd609SLawrence Stewart 	clock_snap->fb_info.status = time_status;
11096cedd609SLawrence Stewart 	/* XXX: Very crude estimate of feedback clock error. */
11106cedd609SLawrence Stewart 	bt.sec = time_esterror / 1000000;
11116cedd609SLawrence Stewart 	bt.frac = ((time_esterror - bt.sec) * 1000000) *
11126cedd609SLawrence Stewart 	    (uint64_t)18446744073709ULL;
11136cedd609SLawrence Stewart 	clock_snap->fb_info.error = bt;
11146cedd609SLawrence Stewart 
11156cedd609SLawrence Stewart #ifdef FFCLOCK
11166cedd609SLawrence Stewart 	if (!fast)
11176cedd609SLawrence Stewart 		clock_snap->ffcount += delta;
11186cedd609SLawrence Stewart 
11196cedd609SLawrence Stewart 	/* Record feed-forward clock leap second adjustment. */
11206cedd609SLawrence Stewart 	ffi->leapsec_adjustment = cest.leapsec_total;
11216cedd609SLawrence Stewart 	if (clock_snap->ffcount > cest.leapsec_next)
11226cedd609SLawrence Stewart 		ffi->leapsec_adjustment -= cest.leapsec;
11236cedd609SLawrence Stewart 
11246cedd609SLawrence Stewart 	/* Record feed-forward clock status and error. */
11256cedd609SLawrence Stewart 	clock_snap->ff_info.status = cest.status;
11266cedd609SLawrence Stewart 	ffcount = clock_snap->ffcount - cest.update_ffcount;
11276cedd609SLawrence Stewart 	ffclock_convert_delta(ffcount, cest.period, &bt);
11286cedd609SLawrence Stewart 	/* 18446744073709 = int(2^64/1e12), err_bound_rate in [ps/s]. */
11296cedd609SLawrence Stewart 	bintime_mul(&bt, cest.errb_rate * (uint64_t)18446744073709ULL);
11306cedd609SLawrence Stewart 	/* 18446744073 = int(2^64 / 1e9), since err_abs in [ns]. */
11316cedd609SLawrence Stewart 	bintime_addx(&bt, cest.errb_abs * (uint64_t)18446744073ULL);
11326cedd609SLawrence Stewart 	clock_snap->ff_info.error = bt;
11336cedd609SLawrence Stewart #endif
11346cedd609SLawrence Stewart }
11356cedd609SLawrence Stewart 
11366cedd609SLawrence Stewart /*
11376cedd609SLawrence Stewart  * Convert a sysclock snapshot into a struct bintime based on the specified
11386cedd609SLawrence Stewart  * clock source and flags.
11396cedd609SLawrence Stewart  */
11406cedd609SLawrence Stewart int
11416cedd609SLawrence Stewart sysclock_snap2bintime(struct sysclock_snap *cs, struct bintime *bt,
11426cedd609SLawrence Stewart     int whichclock, uint32_t flags)
11436cedd609SLawrence Stewart {
1144584b675eSKonstantin Belousov 	struct bintime boottimebin;
11456cedd609SLawrence Stewart #ifdef FFCLOCK
11466cedd609SLawrence Stewart 	struct bintime bt2;
11476cedd609SLawrence Stewart 	uint64_t period;
11486cedd609SLawrence Stewart #endif
11496cedd609SLawrence Stewart 
11506cedd609SLawrence Stewart 	switch (whichclock) {
11516cedd609SLawrence Stewart 	case SYSCLOCK_FBCK:
11526cedd609SLawrence Stewart 		*bt = cs->fb_info.tick_time;
11536cedd609SLawrence Stewart 
11546cedd609SLawrence Stewart 		/* If snapshot was created with !fast, delta will be >0. */
11556cedd609SLawrence Stewart 		if (cs->delta > 0)
11566cedd609SLawrence Stewart 			bintime_addx(bt, cs->fb_info.th_scale * cs->delta);
11576cedd609SLawrence Stewart 
1158584b675eSKonstantin Belousov 		if ((flags & FBCLOCK_UPTIME) == 0) {
1159584b675eSKonstantin Belousov 			getboottimebin(&boottimebin);
11606cedd609SLawrence Stewart 			bintime_add(bt, &boottimebin);
1161584b675eSKonstantin Belousov 		}
11626cedd609SLawrence Stewart 		break;
11636cedd609SLawrence Stewart #ifdef FFCLOCK
11646cedd609SLawrence Stewart 	case SYSCLOCK_FFWD:
11656cedd609SLawrence Stewart 		if (flags & FFCLOCK_LERP) {
11666cedd609SLawrence Stewart 			*bt = cs->ff_info.tick_time_lerp;
11676cedd609SLawrence Stewart 			period = cs->ff_info.period_lerp;
11686cedd609SLawrence Stewart 		} else {
11696cedd609SLawrence Stewart 			*bt = cs->ff_info.tick_time;
11706cedd609SLawrence Stewart 			period = cs->ff_info.period;
11716cedd609SLawrence Stewart 		}
11726cedd609SLawrence Stewart 
11736cedd609SLawrence Stewart 		/* If snapshot was created with !fast, delta will be >0. */
11746cedd609SLawrence Stewart 		if (cs->delta > 0) {
11756cedd609SLawrence Stewart 			ffclock_convert_delta(cs->delta, period, &bt2);
11766cedd609SLawrence Stewart 			bintime_add(bt, &bt2);
11776cedd609SLawrence Stewart 		}
11786cedd609SLawrence Stewart 
11796cedd609SLawrence Stewart 		/* Leap second adjustment. */
11806cedd609SLawrence Stewart 		if (flags & FFCLOCK_LEAPSEC)
11816cedd609SLawrence Stewart 			bt->sec -= cs->ff_info.leapsec_adjustment;
11826cedd609SLawrence Stewart 
11836cedd609SLawrence Stewart 		/* Boot time adjustment, for uptime/monotonic clocks. */
11846cedd609SLawrence Stewart 		if (flags & FFCLOCK_UPTIME)
11856cedd609SLawrence Stewart 			bintime_sub(bt, &ffclock_boottime);
1186de02885aSKevin Lo 		break;
11876cedd609SLawrence Stewart #endif
11886cedd609SLawrence Stewart 	default:
11896cedd609SLawrence Stewart 		return (EINVAL);
11906cedd609SLawrence Stewart 		break;
11916cedd609SLawrence Stewart 	}
11926cedd609SLawrence Stewart 
11936cedd609SLawrence Stewart 	return (0);
11946cedd609SLawrence Stewart }
11956cedd609SLawrence Stewart 
11966cedd609SLawrence Stewart /*
119778a49a45SPoul-Henning Kamp  * Initialize a new timecounter and possibly use it.
11984e2befc0SPoul-Henning Kamp  */
11997ec73f64SPoul-Henning Kamp void
120091266b96SPoul-Henning Kamp tc_init(struct timecounter *tc)
12017ec73f64SPoul-Henning Kamp {
1202555a5de2SPoul-Henning Kamp 	u_int u;
120393ef14a7SDavid Malone 	struct sysctl_oid *tc_root;
12047ec73f64SPoul-Henning Kamp 
1205c679c734SPoul-Henning Kamp 	u = tc->tc_frequency / tc->tc_counter_mask;
1206555a5de2SPoul-Henning Kamp 	/* XXX: We need some margin here, 10% is a guess */
1207555a5de2SPoul-Henning Kamp 	u *= 11;
1208555a5de2SPoul-Henning Kamp 	u /= 10;
1209c679c734SPoul-Henning Kamp 	if (u > hz && tc->tc_quality >= 0) {
1210c679c734SPoul-Henning Kamp 		tc->tc_quality = -2000;
1211c679c734SPoul-Henning Kamp 		if (bootverbose) {
1212c679c734SPoul-Henning Kamp 			printf("Timecounter \"%s\" frequency %ju Hz",
1213555a5de2SPoul-Henning Kamp 			    tc->tc_name, (uintmax_t)tc->tc_frequency);
1214c679c734SPoul-Henning Kamp 			printf(" -- Insufficient hz, needs at least %u\n", u);
1215c679c734SPoul-Henning Kamp 		}
1216c679c734SPoul-Henning Kamp 	} else if (tc->tc_quality >= 0 || bootverbose) {
1217555a5de2SPoul-Henning Kamp 		printf("Timecounter \"%s\" frequency %ju Hz quality %d\n",
1218555a5de2SPoul-Henning Kamp 		    tc->tc_name, (uintmax_t)tc->tc_frequency,
121978a49a45SPoul-Henning Kamp 		    tc->tc_quality);
1220e46eeb89SPoul-Henning Kamp 	}
1221c679c734SPoul-Henning Kamp 
122262efba6aSPoul-Henning Kamp 	tc->tc_next = timecounters;
122362efba6aSPoul-Henning Kamp 	timecounters = tc;
1224555a5de2SPoul-Henning Kamp 	/*
122593ef14a7SDavid Malone 	 * Set up sysctl tree for this counter.
122693ef14a7SDavid Malone 	 */
1227fd0f5970SEd Schouten 	tc_root = SYSCTL_ADD_NODE_WITH_LABEL(NULL,
122893ef14a7SDavid Malone 	    SYSCTL_STATIC_CHILDREN(_kern_timecounter_tc), OID_AUTO, tc->tc_name,
1229fd0f5970SEd Schouten 	    CTLFLAG_RW, 0, "timecounter description", "timecounter");
123093ef14a7SDavid Malone 	SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
123193ef14a7SDavid Malone 	    "mask", CTLFLAG_RD, &(tc->tc_counter_mask), 0,
123293ef14a7SDavid Malone 	    "mask for implemented bits");
123393ef14a7SDavid Malone 	SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
123493ef14a7SDavid Malone 	    "counter", CTLTYPE_UINT | CTLFLAG_RD, tc, sizeof(*tc),
123593ef14a7SDavid Malone 	    sysctl_kern_timecounter_get, "IU", "current timecounter value");
123693ef14a7SDavid Malone 	SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1237cbc134adSMatthew D Fleming 	    "frequency", CTLTYPE_U64 | CTLFLAG_RD, tc, sizeof(*tc),
1238041b706bSDavid Malone 	     sysctl_kern_timecounter_freq, "QU", "timecounter frequency");
123993ef14a7SDavid Malone 	SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
124093ef14a7SDavid Malone 	    "quality", CTLFLAG_RD, &(tc->tc_quality), 0,
124193ef14a7SDavid Malone 	    "goodness of time counter");
124293ef14a7SDavid Malone 	/*
1243e8bac3f2SIan Lepore 	 * Do not automatically switch if the current tc was specifically
1244e8bac3f2SIan Lepore 	 * chosen.  Never automatically use a timecounter with negative quality.
1245555a5de2SPoul-Henning Kamp 	 * Even though we run on the dummy counter, switching here may be
1246e8bac3f2SIan Lepore 	 * worse since this timecounter may not be monotonic.
1247555a5de2SPoul-Henning Kamp 	 */
1248e8bac3f2SIan Lepore 	if (tc_chosen)
1249e8bac3f2SIan Lepore 		return;
125078a49a45SPoul-Henning Kamp 	if (tc->tc_quality < 0)
125178a49a45SPoul-Henning Kamp 		return;
125278a49a45SPoul-Henning Kamp 	if (tc->tc_quality < timecounter->tc_quality)
125378a49a45SPoul-Henning Kamp 		return;
1254555a5de2SPoul-Henning Kamp 	if (tc->tc_quality == timecounter->tc_quality &&
1255555a5de2SPoul-Henning Kamp 	    tc->tc_frequency < timecounter->tc_frequency)
1256555a5de2SPoul-Henning Kamp 		return;
1257555a5de2SPoul-Henning Kamp 	(void)tc->tc_get_timecount(tc);
1258555a5de2SPoul-Henning Kamp 	(void)tc->tc_get_timecount(tc);
12597ec73f64SPoul-Henning Kamp 	timecounter = tc;
126062efba6aSPoul-Henning Kamp }
126162efba6aSPoul-Henning Kamp 
126239acc78aSPoul-Henning Kamp /* Report the frequency of the current timecounter. */
126360ae52f7SEd Schouten uint64_t
126462efba6aSPoul-Henning Kamp tc_getfrequency(void)
126562efba6aSPoul-Henning Kamp {
126662efba6aSPoul-Henning Kamp 
12676b00cf46SPoul-Henning Kamp 	return (timehands->th_counter->tc_frequency);
12687ec73f64SPoul-Henning Kamp }
12697ec73f64SPoul-Henning Kamp 
12709dbdf2a1SEric van Gyzen static bool
12719dbdf2a1SEric van Gyzen sleeping_on_old_rtc(struct thread *td)
12729dbdf2a1SEric van Gyzen {
12739dbdf2a1SEric van Gyzen 
12748addc72bSEric van Gyzen 	/*
12758addc72bSEric van Gyzen 	 * td_rtcgen is modified by curthread when it is running,
12768addc72bSEric van Gyzen 	 * and by other threads in this function.  By finding the thread
12778addc72bSEric van Gyzen 	 * on a sleepqueue and holding the lock on the sleepqueue
12788addc72bSEric van Gyzen 	 * chain, we guarantee that the thread is not running and that
12798addc72bSEric van Gyzen 	 * modifying td_rtcgen is safe.  Setting td_rtcgen to zero informs
12808addc72bSEric van Gyzen 	 * the thread that it was woken due to a real-time clock adjustment.
12818addc72bSEric van Gyzen 	 * (The declaration of td_rtcgen refers to this comment.)
12828addc72bSEric van Gyzen 	 */
12839dbdf2a1SEric van Gyzen 	if (td->td_rtcgen != 0 && td->td_rtcgen != rtc_generation) {
12849dbdf2a1SEric van Gyzen 		td->td_rtcgen = 0;
12859dbdf2a1SEric van Gyzen 		return (true);
12869dbdf2a1SEric van Gyzen 	}
12879dbdf2a1SEric van Gyzen 	return (false);
12889dbdf2a1SEric van Gyzen }
12899dbdf2a1SEric van Gyzen 
12905760b029SKonstantin Belousov static struct mtx tc_setclock_mtx;
12915760b029SKonstantin Belousov MTX_SYSINIT(tc_setclock_init, &tc_setclock_mtx, "tcsetc", MTX_SPIN);
12925760b029SKonstantin Belousov 
129339acc78aSPoul-Henning Kamp /*
12944e82e5f6SWarner Losh  * Step our concept of UTC.  This is done by modifying our estimate of
12954e74721cSPoul-Henning Kamp  * when we booted.
12966b00cf46SPoul-Henning Kamp  */
12977ec73f64SPoul-Henning Kamp void
129891266b96SPoul-Henning Kamp tc_setclock(struct timespec *ts)
12997ec73f64SPoul-Henning Kamp {
13005b51d1deSPoul-Henning Kamp 	struct timespec tbef, taft;
13014e74721cSPoul-Henning Kamp 	struct bintime bt, bt2;
13027ec73f64SPoul-Henning Kamp 
13034e74721cSPoul-Henning Kamp 	timespec2bintime(ts, &bt);
13045760b029SKonstantin Belousov 	nanotime(&tbef);
13055760b029SKonstantin Belousov 	mtx_lock_spin(&tc_setclock_mtx);
13065760b029SKonstantin Belousov 	cpu_tick_calibrate(1);
13075b51d1deSPoul-Henning Kamp 	binuptime(&bt2);
13084e74721cSPoul-Henning Kamp 	bintime_sub(&bt, &bt2);
130939acc78aSPoul-Henning Kamp 
131039acc78aSPoul-Henning Kamp 	/* XXX fiddle all the little crinkly bits around the fiords... */
13115760b029SKonstantin Belousov 	tc_windup(&bt);
13125760b029SKonstantin Belousov 	mtx_unlock_spin(&tc_setclock_mtx);
13138addc72bSEric van Gyzen 
13149dbdf2a1SEric van Gyzen 	/* Avoid rtc_generation == 0, since td_rtcgen == 0 is special. */
13159dbdf2a1SEric van Gyzen 	atomic_add_rel_int(&rtc_generation, 2);
13169dbdf2a1SEric van Gyzen 	sleepq_chains_remove_matching(sleeping_on_old_rtc);
13174e74721cSPoul-Henning Kamp 	if (timestepwarnings) {
13185760b029SKonstantin Belousov 		nanotime(&taft);
13195b51d1deSPoul-Henning Kamp 		log(LOG_INFO,
13205b51d1deSPoul-Henning Kamp 		    "Time stepped from %jd.%09ld to %jd.%09ld (%jd.%09ld)\n",
13215b51d1deSPoul-Henning Kamp 		    (intmax_t)tbef.tv_sec, tbef.tv_nsec,
13225b51d1deSPoul-Henning Kamp 		    (intmax_t)taft.tv_sec, taft.tv_nsec,
1323ee57aeeaSPoul-Henning Kamp 		    (intmax_t)ts->tv_sec, ts->tv_nsec);
13244e74721cSPoul-Henning Kamp 	}
13257ec73f64SPoul-Henning Kamp }
13267ec73f64SPoul-Henning Kamp 
132739acc78aSPoul-Henning Kamp /*
132839acc78aSPoul-Henning Kamp  * Initialize the next struct timehands in the ring and make
13296b00cf46SPoul-Henning Kamp  * it the active timehands.  Along the way we might switch to a different
13306b00cf46SPoul-Henning Kamp  * timecounter and/or do seconds processing in NTP.  Slightly magic.
13316b00cf46SPoul-Henning Kamp  */
13329e1b5510SPoul-Henning Kamp static void
13335760b029SKonstantin Belousov tc_windup(struct bintime *new_boottimebin)
13347ec73f64SPoul-Henning Kamp {
13352028c0cdSPoul-Henning Kamp 	struct bintime bt;
133639acc78aSPoul-Henning Kamp 	struct timehands *th, *tho;
133760ae52f7SEd Schouten 	uint64_t scale;
133839acc78aSPoul-Henning Kamp 	u_int delta, ncount, ogen;
133939acc78aSPoul-Henning Kamp 	int i;
13404f2073fbSWarner Losh 	time_t t;
13417ec73f64SPoul-Henning Kamp 
134239acc78aSPoul-Henning Kamp 	/*
1343f4b5a972SKonstantin Belousov 	 * Make the next timehands a copy of the current one, but do
1344f4b5a972SKonstantin Belousov 	 * not overwrite the generation or next pointer.  While we
1345f4b5a972SKonstantin Belousov 	 * update the contents, the generation must be zero.  We need
1346f4b5a972SKonstantin Belousov 	 * to ensure that the zero generation is visible before the
1347f4b5a972SKonstantin Belousov 	 * data updates become visible, which requires release fence.
1348f4b5a972SKonstantin Belousov 	 * For similar reasons, re-reading of the generation after the
1349f4b5a972SKonstantin Belousov 	 * data is read should use acquire fence.
13506b00cf46SPoul-Henning Kamp 	 */
13516b00cf46SPoul-Henning Kamp 	tho = timehands;
13526b00cf46SPoul-Henning Kamp 	th = tho->th_next;
13536b00cf46SPoul-Henning Kamp 	ogen = th->th_generation;
1354f4b5a972SKonstantin Belousov 	th->th_generation = 0;
1355f4b5a972SKonstantin Belousov 	atomic_thread_fence_rel();
13565ec2c936SMateusz Guzik 	memcpy(th, tho, offsetof(struct timehands, th_generation));
13575760b029SKonstantin Belousov 	if (new_boottimebin != NULL)
13585760b029SKonstantin Belousov 		th->th_boottime = *new_boottimebin;
13596b00cf46SPoul-Henning Kamp 
136039acc78aSPoul-Henning Kamp 	/*
13616b00cf46SPoul-Henning Kamp 	 * Capture a timecounter delta on the current timecounter and if
13626b00cf46SPoul-Henning Kamp 	 * changing timecounters, a counter value from the new timecounter.
13636b00cf46SPoul-Henning Kamp 	 * Update the offset fields accordingly.
13646b00cf46SPoul-Henning Kamp 	 */
13656b00cf46SPoul-Henning Kamp 	delta = tc_delta(th);
13666b00cf46SPoul-Henning Kamp 	if (th->th_counter != timecounter)
13676b00cf46SPoul-Henning Kamp 		ncount = timecounter->tc_get_timecount(timecounter);
136839acc78aSPoul-Henning Kamp 	else
136939acc78aSPoul-Henning Kamp 		ncount = 0;
1370b0fdc837SLawrence Stewart #ifdef FFCLOCK
1371b0fdc837SLawrence Stewart 	ffclock_windup(delta);
1372b0fdc837SLawrence Stewart #endif
13736b00cf46SPoul-Henning Kamp 	th->th_offset_count += delta;
13746b00cf46SPoul-Henning Kamp 	th->th_offset_count &= th->th_counter->tc_counter_mask;
1375aa519c0aSColin Percival 	while (delta > th->th_counter->tc_frequency) {
1376aa519c0aSColin Percival 		/* Eat complete unadjusted seconds. */
1377aa519c0aSColin Percival 		delta -= th->th_counter->tc_frequency;
1378aa519c0aSColin Percival 		th->th_offset.sec++;
1379aa519c0aSColin Percival 	}
1380aa519c0aSColin Percival 	if ((delta > th->th_counter->tc_frequency / 2) &&
1381772d1e42SColin Percival 	    (th->th_scale * delta < ((uint64_t)1 << 63))) {
1382aa519c0aSColin Percival 		/* The product th_scale * delta just barely overflows. */
1383aa519c0aSColin Percival 		th->th_offset.sec++;
1384aa519c0aSColin Percival 	}
13856b00cf46SPoul-Henning Kamp 	bintime_addx(&th->th_offset, th->th_scale * delta);
13866b00cf46SPoul-Henning Kamp 
138739acc78aSPoul-Henning Kamp 	/*
13886b00cf46SPoul-Henning Kamp 	 * Hardware latching timecounters may not generate interrupts on
13896b00cf46SPoul-Henning Kamp 	 * PPS events, so instead we poll them.  There is a finite risk that
13906b00cf46SPoul-Henning Kamp 	 * the hardware might capture a count which is later than the one we
13916b00cf46SPoul-Henning Kamp 	 * got above, and therefore possibly in the next NTP second which might
13926b00cf46SPoul-Henning Kamp 	 * have a different rate than the current NTP second.  It doesn't
13936b00cf46SPoul-Henning Kamp 	 * matter in practice.
13946b00cf46SPoul-Henning Kamp 	 */
13956b00cf46SPoul-Henning Kamp 	if (tho->th_counter->tc_poll_pps)
13966b00cf46SPoul-Henning Kamp 		tho->th_counter->tc_poll_pps(tho->th_counter);
13976b00cf46SPoul-Henning Kamp 
139839acc78aSPoul-Henning Kamp 	/*
1399c1cccd1eSWarner Losh 	 * Deal with NTP second processing.  The for loop normally
1400c1cccd1eSWarner Losh 	 * iterates at most once, but in extreme situations it might
1401c1cccd1eSWarner Losh 	 * keep NTP sane if timeouts are not run for several seconds.
1402c1cccd1eSWarner Losh 	 * At boot, the time step can be large when the TOD hardware
1403c1cccd1eSWarner Losh 	 * has been read, so on really large steps, we call
1404c1cccd1eSWarner Losh 	 * ntp_update_second only twice.  We need to call it twice in
1405c1cccd1eSWarner Losh 	 * case we missed a leap second.
14064f2073fbSWarner Losh 	 */
14074f2073fbSWarner Losh 	bt = th->th_offset;
14085760b029SKonstantin Belousov 	bintime_add(&bt, &th->th_boottime);
140945cc9f5fSWarner Losh 	i = bt.sec - tho->th_microtime.tv_sec;
141045cc9f5fSWarner Losh 	if (i > LARGE_STEP)
141145cc9f5fSWarner Losh 		i = 2;
141245cc9f5fSWarner Losh 	for (; i > 0; i--) {
14134f2073fbSWarner Losh 		t = bt.sec;
14144f2073fbSWarner Losh 		ntp_update_second(&th->th_adjustment, &bt.sec);
14154f2073fbSWarner Losh 		if (bt.sec != t)
14165760b029SKonstantin Belousov 			th->th_boottime.sec += bt.sec - t;
14174f2073fbSWarner Losh 	}
1418c1cccd1eSWarner Losh 	/* Update the UTC timestamps used by the get*() functions. */
141970e3b262SKonstantin Belousov 	th->th_bintime = bt;
1420c1cccd1eSWarner Losh 	bintime2timeval(&bt, &th->th_microtime);
1421c1cccd1eSWarner Losh 	bintime2timespec(&bt, &th->th_nanotime);
14226b00cf46SPoul-Henning Kamp 
14236b00cf46SPoul-Henning Kamp 	/* Now is a good time to change timecounters. */
14246b00cf46SPoul-Henning Kamp 	if (th->th_counter != timecounter) {
142508e1b4f4SJung-uk Kim #ifndef __arm__
142692597e06SJohn Baldwin 		if ((timecounter->tc_flags & TC_FLAGS_C2STOP) != 0)
142792597e06SJohn Baldwin 			cpu_disable_c2_sleep++;
142892597e06SJohn Baldwin 		if ((th->th_counter->tc_flags & TC_FLAGS_C2STOP) != 0)
142992597e06SJohn Baldwin 			cpu_disable_c2_sleep--;
143008e1b4f4SJung-uk Kim #endif
14316b00cf46SPoul-Henning Kamp 		th->th_counter = timecounter;
14326b00cf46SPoul-Henning Kamp 		th->th_offset_count = ncount;
14330e189873SAlexander Motin 		tc_min_ticktock_freq = max(1, timecounter->tc_frequency /
14340e189873SAlexander Motin 		    (((uint64_t)timecounter->tc_counter_mask + 1) / 3));
1435b0fdc837SLawrence Stewart #ifdef FFCLOCK
1436b0fdc837SLawrence Stewart 		ffclock_change_tc(th);
1437b0fdc837SLawrence Stewart #endif
14387ec73f64SPoul-Henning Kamp 	}
14397ec73f64SPoul-Henning Kamp 
14401a996ed1SEdward Tomasz Napierala 	/*-
14416b00cf46SPoul-Henning Kamp 	 * Recalculate the scaling factor.  We want the number of 1/2^64
14426b00cf46SPoul-Henning Kamp 	 * fractions of a second per period of the hardware counter, taking
14436b00cf46SPoul-Henning Kamp 	 * into account the th_adjustment factor which the NTP PLL/adjtime(2)
14446b00cf46SPoul-Henning Kamp 	 * processing provides us with.
14456b00cf46SPoul-Henning Kamp 	 *
14466b00cf46SPoul-Henning Kamp 	 * The th_adjustment is nanoseconds per second with 32 bit binary
1447d94e3652SPoul-Henning Kamp 	 * fraction and we want 64 bit binary fraction of second:
14486b00cf46SPoul-Henning Kamp 	 *
14496b00cf46SPoul-Henning Kamp 	 *	 x = a * 2^32 / 10^9 = a * 4.294967296
14506b00cf46SPoul-Henning Kamp 	 *
14516b00cf46SPoul-Henning Kamp 	 * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
1452e8444a7eSPoul-Henning Kamp 	 * we can only multiply by about 850 without overflowing, that
1453e8444a7eSPoul-Henning Kamp 	 * leaves no suitably precise fractions for multiply before divide.
14546b00cf46SPoul-Henning Kamp 	 *
14556b00cf46SPoul-Henning Kamp 	 * Divide before multiply with a fraction of 2199/512 results in a
14566b00cf46SPoul-Henning Kamp 	 * systematic undercompensation of 10PPM of th_adjustment.  On a
14576b00cf46SPoul-Henning Kamp 	 * 5000PPM adjustment this is a 0.05PPM error.  This is acceptable.
14586b00cf46SPoul-Henning Kamp  	 *
14596b00cf46SPoul-Henning Kamp 	 * We happily sacrifice the lowest of the 64 bits of our result
14606b00cf46SPoul-Henning Kamp 	 * to the goddess of code clarity.
146139acc78aSPoul-Henning Kamp 	 *
14626b00cf46SPoul-Henning Kamp 	 */
146360ae52f7SEd Schouten 	scale = (uint64_t)1 << 63;
14646b00cf46SPoul-Henning Kamp 	scale += (th->th_adjustment / 1024) * 2199;
14656b00cf46SPoul-Henning Kamp 	scale /= th->th_counter->tc_frequency;
14666b00cf46SPoul-Henning Kamp 	th->th_scale = scale * 2;
14676b00cf46SPoul-Henning Kamp 
146839acc78aSPoul-Henning Kamp 	/*
146939acc78aSPoul-Henning Kamp 	 * Now that the struct timehands is again consistent, set the new
14706b00cf46SPoul-Henning Kamp 	 * generation number, making sure to not make it zero.
14716b00cf46SPoul-Henning Kamp 	 */
14726b00cf46SPoul-Henning Kamp 	if (++ogen == 0)
147339acc78aSPoul-Henning Kamp 		ogen = 1;
1474f4b5a972SKonstantin Belousov 	atomic_store_rel_int(&th->th_generation, ogen);
14756b00cf46SPoul-Henning Kamp 
147639acc78aSPoul-Henning Kamp 	/* Go live with the new struct timehands. */
14779bce0f05SLawrence Stewart #ifdef FFCLOCK
14789bce0f05SLawrence Stewart 	switch (sysclock_active) {
14799bce0f05SLawrence Stewart 	case SYSCLOCK_FBCK:
14809bce0f05SLawrence Stewart #endif
14816b00cf46SPoul-Henning Kamp 		time_second = th->th_microtime.tv_sec;
148238b0884cSPoul-Henning Kamp 		time_uptime = th->th_offset.sec;
14839bce0f05SLawrence Stewart #ifdef FFCLOCK
14849bce0f05SLawrence Stewart 		break;
14859bce0f05SLawrence Stewart 	case SYSCLOCK_FFWD:
14869bce0f05SLawrence Stewart 		time_second = fftimehands->tick_time_lerp.sec;
14879bce0f05SLawrence Stewart 		time_uptime = fftimehands->tick_time_lerp.sec - ffclock_boottime.sec;
14889bce0f05SLawrence Stewart 		break;
14899bce0f05SLawrence Stewart 	}
14909bce0f05SLawrence Stewart #endif
14919bce0f05SLawrence Stewart 
14926b00cf46SPoul-Henning Kamp 	timehands = th;
149321c295efSKonstantin Belousov 	timekeep_push_vdso();
14946b00cf46SPoul-Henning Kamp }
14956b00cf46SPoul-Henning Kamp 
149639acc78aSPoul-Henning Kamp /* Report or change the active timecounter hardware. */
14976b6ef746SBruce Evans static int
149882d9ae4eSPoul-Henning Kamp sysctl_kern_timecounter_hardware(SYSCTL_HANDLER_ARGS)
14996b6ef746SBruce Evans {
15006b6ef746SBruce Evans 	char newname[32];
15016b6ef746SBruce Evans 	struct timecounter *newtc, *tc;
15026b6ef746SBruce Evans 	int error;
15036b6ef746SBruce Evans 
150462efba6aSPoul-Henning Kamp 	tc = timecounter;
1505e80fb434SRobert Drehmel 	strlcpy(newname, tc->tc_name, sizeof(newname));
1506e80fb434SRobert Drehmel 
15076b6ef746SBruce Evans 	error = sysctl_handle_string(oidp, &newname[0], sizeof(newname), req);
1508e8bac3f2SIan Lepore 	if (error != 0 || req->newptr == NULL)
150962efba6aSPoul-Henning Kamp 		return (error);
1510e8bac3f2SIan Lepore 	/* Record that the tc in use now was specifically chosen. */
1511e8bac3f2SIan Lepore 	tc_chosen = 1;
1512e8bac3f2SIan Lepore 	if (strcmp(newname, tc->tc_name) == 0)
1513e8bac3f2SIan Lepore 		return (0);
151462efba6aSPoul-Henning Kamp 	for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
151539acc78aSPoul-Henning Kamp 		if (strcmp(newname, newtc->tc_name) != 0)
151662efba6aSPoul-Henning Kamp 			continue;
151739acc78aSPoul-Henning Kamp 
15186b6ef746SBruce Evans 		/* Warm up new timecounter. */
15196b6ef746SBruce Evans 		(void)newtc->tc_get_timecount(newtc);
152062efba6aSPoul-Henning Kamp 		(void)newtc->tc_get_timecount(newtc);
152139acc78aSPoul-Henning Kamp 
152262efba6aSPoul-Henning Kamp 		timecounter = newtc;
1523d1b1b600SNeel Natu 
1524d1b1b600SNeel Natu 		/*
1525d1b1b600SNeel Natu 		 * The vdso timehands update is deferred until the next
1526d1b1b600SNeel Natu 		 * 'tc_windup()'.
1527d1b1b600SNeel Natu 		 *
1528d1b1b600SNeel Natu 		 * This is prudent given that 'timekeep_push_vdso()' does not
1529d1b1b600SNeel Natu 		 * use any locking and that it can be called in hard interrupt
1530d1b1b600SNeel Natu 		 * context via 'tc_windup()'.
1531d1b1b600SNeel Natu 		 */
15326b6ef746SBruce Evans 		return (0);
15336b6ef746SBruce Evans 	}
15346b6ef746SBruce Evans 	return (EINVAL);
15356b6ef746SBruce Evans }
15366b6ef746SBruce Evans 
15376b6ef746SBruce Evans SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware, CTLTYPE_STRING | CTLFLAG_RW,
1538b389be97SRebecca Cran     0, 0, sysctl_kern_timecounter_hardware, "A",
1539b389be97SRebecca Cran     "Timecounter hardware selected");
15406b6ef746SBruce Evans 
154178a49a45SPoul-Henning Kamp 
1542e8bac3f2SIan Lepore /* Report the available timecounter hardware. */
154378a49a45SPoul-Henning Kamp static int
154478a49a45SPoul-Henning Kamp sysctl_kern_timecounter_choice(SYSCTL_HANDLER_ARGS)
154578a49a45SPoul-Henning Kamp {
154691d9eda2SIan Lepore 	struct sbuf sb;
154778a49a45SPoul-Henning Kamp 	struct timecounter *tc;
154878a49a45SPoul-Henning Kamp 	int error;
154978a49a45SPoul-Henning Kamp 
155091d9eda2SIan Lepore 	sbuf_new_for_sysctl(&sb, NULL, 0, req);
155191d9eda2SIan Lepore 	for (tc = timecounters; tc != NULL; tc = tc->tc_next) {
155291d9eda2SIan Lepore 		if (tc != timecounters)
155391d9eda2SIan Lepore 			sbuf_putc(&sb, ' ');
155491d9eda2SIan Lepore 		sbuf_printf(&sb, "%s(%d)", tc->tc_name, tc->tc_quality);
155578a49a45SPoul-Henning Kamp 	}
155691d9eda2SIan Lepore 	error = sbuf_finish(&sb);
155791d9eda2SIan Lepore 	sbuf_delete(&sb);
155878a49a45SPoul-Henning Kamp 	return (error);
155978a49a45SPoul-Henning Kamp }
156078a49a45SPoul-Henning Kamp 
156178a49a45SPoul-Henning Kamp SYSCTL_PROC(_kern_timecounter, OID_AUTO, choice, CTLTYPE_STRING | CTLFLAG_RD,
15622baa5cddSRebecca Cran     0, 0, sysctl_kern_timecounter_choice, "A", "Timecounter hardware detected");
156378a49a45SPoul-Henning Kamp 
156439acc78aSPoul-Henning Kamp /*
15656b00cf46SPoul-Henning Kamp  * RFC 2783 PPS-API implementation.
15666b00cf46SPoul-Henning Kamp  */
15677ec73f64SPoul-Henning Kamp 
156828315e27SIan Lepore /*
156928315e27SIan Lepore  *  Return true if the driver is aware of the abi version extensions in the
157028315e27SIan Lepore  *  pps_state structure, and it supports at least the given abi version number.
157128315e27SIan Lepore  */
157228315e27SIan Lepore static inline int
157328315e27SIan Lepore abi_aware(struct pps_state *pps, int vers)
157428315e27SIan Lepore {
157528315e27SIan Lepore 
157628315e27SIan Lepore 	return ((pps->kcmode & KCMODE_ABIFLAG) && pps->driver_abi >= vers);
157728315e27SIan Lepore }
157828315e27SIan Lepore 
1579a1137de9SIan Lepore static int
1580a1137de9SIan Lepore pps_fetch(struct pps_fetch_args *fapi, struct pps_state *pps)
1581a1137de9SIan Lepore {
1582a1137de9SIan Lepore 	int err, timo;
1583a1137de9SIan Lepore 	pps_seq_t aseq, cseq;
1584a1137de9SIan Lepore 	struct timeval tv;
1585a1137de9SIan Lepore 
1586a1137de9SIan Lepore 	if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1587a1137de9SIan Lepore 		return (EINVAL);
1588a1137de9SIan Lepore 
1589a1137de9SIan Lepore 	/*
1590a1137de9SIan Lepore 	 * If no timeout is requested, immediately return whatever values were
1591a1137de9SIan Lepore 	 * most recently captured.  If timeout seconds is -1, that's a request
1592a1137de9SIan Lepore 	 * to block without a timeout.  WITNESS won't let us sleep forever
1593a1137de9SIan Lepore 	 * without a lock (we really don't need a lock), so just repeatedly
1594a1137de9SIan Lepore 	 * sleep a long time.
1595a1137de9SIan Lepore 	 */
1596a1137de9SIan Lepore 	if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec) {
1597a1137de9SIan Lepore 		if (fapi->timeout.tv_sec == -1)
1598a1137de9SIan Lepore 			timo = 0x7fffffff;
1599a1137de9SIan Lepore 		else {
1600a1137de9SIan Lepore 			tv.tv_sec = fapi->timeout.tv_sec;
1601a1137de9SIan Lepore 			tv.tv_usec = fapi->timeout.tv_nsec / 1000;
1602a1137de9SIan Lepore 			timo = tvtohz(&tv);
1603a1137de9SIan Lepore 		}
16046f697994SKonstantin Belousov 		aseq = atomic_load_int(&pps->ppsinfo.assert_sequence);
16056f697994SKonstantin Belousov 		cseq = atomic_load_int(&pps->ppsinfo.clear_sequence);
16066f697994SKonstantin Belousov 		while (aseq == atomic_load_int(&pps->ppsinfo.assert_sequence) &&
16076f697994SKonstantin Belousov 		    cseq == atomic_load_int(&pps->ppsinfo.clear_sequence)) {
160828315e27SIan Lepore 			if (abi_aware(pps, 1) && pps->driver_mtx != NULL) {
160928315e27SIan Lepore 				if (pps->flags & PPSFLAG_MTX_SPIN) {
161028315e27SIan Lepore 					err = msleep_spin(pps, pps->driver_mtx,
161128315e27SIan Lepore 					    "ppsfch", timo);
161228315e27SIan Lepore 				} else {
161328315e27SIan Lepore 					err = msleep(pps, pps->driver_mtx, PCATCH,
161428315e27SIan Lepore 					    "ppsfch", timo);
161528315e27SIan Lepore 				}
161628315e27SIan Lepore 			} else {
1617a1137de9SIan Lepore 				err = tsleep(pps, PCATCH, "ppsfch", timo);
161828315e27SIan Lepore 			}
16196f7a9f7cSIan Lepore 			if (err == EWOULDBLOCK) {
16206f7a9f7cSIan Lepore 				if (fapi->timeout.tv_sec == -1) {
1621a1137de9SIan Lepore 					continue;
16226f7a9f7cSIan Lepore 				} else {
16236f7a9f7cSIan Lepore 					return (ETIMEDOUT);
16246f7a9f7cSIan Lepore 				}
1625a1137de9SIan Lepore 			} else if (err != 0) {
1626a1137de9SIan Lepore 				return (err);
1627a1137de9SIan Lepore 			}
1628a1137de9SIan Lepore 		}
1629a1137de9SIan Lepore 	}
1630a1137de9SIan Lepore 
1631a1137de9SIan Lepore 	pps->ppsinfo.current_mode = pps->ppsparam.mode;
1632a1137de9SIan Lepore 	fapi->pps_info_buf = pps->ppsinfo;
1633a1137de9SIan Lepore 
1634a1137de9SIan Lepore 	return (0);
1635a1137de9SIan Lepore }
1636a1137de9SIan Lepore 
163732c20357SPoul-Henning Kamp int
163832c20357SPoul-Henning Kamp pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
163932c20357SPoul-Henning Kamp {
164032c20357SPoul-Henning Kamp 	pps_params_t *app;
1641b7424f2dSJohn Hay 	struct pps_fetch_args *fapi;
164265e359a1SLawrence Stewart #ifdef FFCLOCK
164365e359a1SLawrence Stewart 	struct pps_fetch_ffc_args *fapi_ffc;
164465e359a1SLawrence Stewart #endif
1645de3f8889SPeter Wemm #ifdef PPS_SYNC
1646b7424f2dSJohn Hay 	struct pps_kcbind_args *kapi;
1647de3f8889SPeter Wemm #endif
164832c20357SPoul-Henning Kamp 
1649d8e8b675SPoul-Henning Kamp 	KASSERT(pps != NULL, ("NULL pps pointer in pps_ioctl"));
165032c20357SPoul-Henning Kamp 	switch (cmd) {
165132c20357SPoul-Henning Kamp 	case PPS_IOC_CREATE:
165232c20357SPoul-Henning Kamp 		return (0);
165332c20357SPoul-Henning Kamp 	case PPS_IOC_DESTROY:
165432c20357SPoul-Henning Kamp 		return (0);
165532c20357SPoul-Henning Kamp 	case PPS_IOC_SETPARAMS:
165632c20357SPoul-Henning Kamp 		app = (pps_params_t *)data;
165732c20357SPoul-Henning Kamp 		if (app->mode & ~pps->ppscap)
165832c20357SPoul-Henning Kamp 			return (EINVAL);
165965e359a1SLawrence Stewart #ifdef FFCLOCK
166065e359a1SLawrence Stewart 		/* Ensure only a single clock is selected for ffc timestamp. */
166165e359a1SLawrence Stewart 		if ((app->mode & PPS_TSCLK_MASK) == PPS_TSCLK_MASK)
166265e359a1SLawrence Stewart 			return (EINVAL);
166365e359a1SLawrence Stewart #endif
166432c20357SPoul-Henning Kamp 		pps->ppsparam = *app;
166532c20357SPoul-Henning Kamp 		return (0);
166632c20357SPoul-Henning Kamp 	case PPS_IOC_GETPARAMS:
166732c20357SPoul-Henning Kamp 		app = (pps_params_t *)data;
166832c20357SPoul-Henning Kamp 		*app = pps->ppsparam;
1669b7424f2dSJohn Hay 		app->api_version = PPS_API_VERS_1;
167032c20357SPoul-Henning Kamp 		return (0);
167132c20357SPoul-Henning Kamp 	case PPS_IOC_GETCAP:
167232c20357SPoul-Henning Kamp 		*(int*)data = pps->ppscap;
167332c20357SPoul-Henning Kamp 		return (0);
167432c20357SPoul-Henning Kamp 	case PPS_IOC_FETCH:
1675b7424f2dSJohn Hay 		fapi = (struct pps_fetch_args *)data;
1676a1137de9SIan Lepore 		return (pps_fetch(fapi, pps));
167765e359a1SLawrence Stewart #ifdef FFCLOCK
167865e359a1SLawrence Stewart 	case PPS_IOC_FETCH_FFCOUNTER:
167965e359a1SLawrence Stewart 		fapi_ffc = (struct pps_fetch_ffc_args *)data;
168065e359a1SLawrence Stewart 		if (fapi_ffc->tsformat && fapi_ffc->tsformat !=
168165e359a1SLawrence Stewart 		    PPS_TSFMT_TSPEC)
168265e359a1SLawrence Stewart 			return (EINVAL);
168365e359a1SLawrence Stewart 		if (fapi_ffc->timeout.tv_sec || fapi_ffc->timeout.tv_nsec)
168465e359a1SLawrence Stewart 			return (EOPNOTSUPP);
168565e359a1SLawrence Stewart 		pps->ppsinfo_ffc.current_mode = pps->ppsparam.mode;
168665e359a1SLawrence Stewart 		fapi_ffc->pps_info_buf_ffc = pps->ppsinfo_ffc;
168765e359a1SLawrence Stewart 		/* Overwrite timestamps if feedback clock selected. */
168865e359a1SLawrence Stewart 		switch (pps->ppsparam.mode & PPS_TSCLK_MASK) {
168965e359a1SLawrence Stewart 		case PPS_TSCLK_FBCK:
169065e359a1SLawrence Stewart 			fapi_ffc->pps_info_buf_ffc.assert_timestamp =
169165e359a1SLawrence Stewart 			    pps->ppsinfo.assert_timestamp;
169265e359a1SLawrence Stewart 			fapi_ffc->pps_info_buf_ffc.clear_timestamp =
169365e359a1SLawrence Stewart 			    pps->ppsinfo.clear_timestamp;
169465e359a1SLawrence Stewart 			break;
169565e359a1SLawrence Stewart 		case PPS_TSCLK_FFWD:
169665e359a1SLawrence Stewart 			break;
169765e359a1SLawrence Stewart 		default:
169865e359a1SLawrence Stewart 			break;
169965e359a1SLawrence Stewart 		}
170065e359a1SLawrence Stewart 		return (0);
170165e359a1SLawrence Stewart #endif /* FFCLOCK */
1702b7424f2dSJohn Hay 	case PPS_IOC_KCBIND:
1703b7424f2dSJohn Hay #ifdef PPS_SYNC
1704b7424f2dSJohn Hay 		kapi = (struct pps_kcbind_args *)data;
1705b7424f2dSJohn Hay 		/* XXX Only root should be able to do this */
1706b7424f2dSJohn Hay 		if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1707b7424f2dSJohn Hay 			return (EINVAL);
1708b7424f2dSJohn Hay 		if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1709b7424f2dSJohn Hay 			return (EINVAL);
1710b7424f2dSJohn Hay 		if (kapi->edge & ~pps->ppscap)
1711b7424f2dSJohn Hay 			return (EINVAL);
171228315e27SIan Lepore 		pps->kcmode = (kapi->edge & KCMODE_EDGEMASK) |
171328315e27SIan Lepore 		    (pps->kcmode & KCMODE_ABIFLAG);
1714b7424f2dSJohn Hay 		return (0);
1715b7424f2dSJohn Hay #else
1716b7424f2dSJohn Hay 		return (EOPNOTSUPP);
1717b7424f2dSJohn Hay #endif
171832c20357SPoul-Henning Kamp 	default:
1719f8385624SPoul-Henning Kamp 		return (ENOIOCTL);
172032c20357SPoul-Henning Kamp 	}
172132c20357SPoul-Henning Kamp }
172232c20357SPoul-Henning Kamp 
172332c20357SPoul-Henning Kamp void
172432c20357SPoul-Henning Kamp pps_init(struct pps_state *pps)
172532c20357SPoul-Henning Kamp {
1726a1137de9SIan Lepore 	pps->ppscap |= PPS_TSFMT_TSPEC | PPS_CANWAIT;
172732c20357SPoul-Henning Kamp 	if (pps->ppscap & PPS_CAPTUREASSERT)
172832c20357SPoul-Henning Kamp 		pps->ppscap |= PPS_OFFSETASSERT;
172932c20357SPoul-Henning Kamp 	if (pps->ppscap & PPS_CAPTURECLEAR)
173032c20357SPoul-Henning Kamp 		pps->ppscap |= PPS_OFFSETCLEAR;
173165e359a1SLawrence Stewart #ifdef FFCLOCK
173265e359a1SLawrence Stewart 	pps->ppscap |= PPS_TSCLK_MASK;
173365e359a1SLawrence Stewart #endif
173428315e27SIan Lepore 	pps->kcmode &= ~KCMODE_ABIFLAG;
173528315e27SIan Lepore }
173628315e27SIan Lepore 
173728315e27SIan Lepore void
173828315e27SIan Lepore pps_init_abi(struct pps_state *pps)
173928315e27SIan Lepore {
174028315e27SIan Lepore 
174128315e27SIan Lepore 	pps_init(pps);
174228315e27SIan Lepore 	if (pps->driver_abi > 0) {
174328315e27SIan Lepore 		pps->kcmode |= KCMODE_ABIFLAG;
174428315e27SIan Lepore 		pps->kernel_abi = PPS_ABI_VERSION;
174528315e27SIan Lepore 	}
174632c20357SPoul-Henning Kamp }
174732c20357SPoul-Henning Kamp 
174832c20357SPoul-Henning Kamp void
17497bf758bfSPoul-Henning Kamp pps_capture(struct pps_state *pps)
17507bf758bfSPoul-Henning Kamp {
17516b00cf46SPoul-Henning Kamp 	struct timehands *th;
17527bf758bfSPoul-Henning Kamp 
1753d8e8b675SPoul-Henning Kamp 	KASSERT(pps != NULL, ("NULL pps pointer in pps_capture"));
17546b00cf46SPoul-Henning Kamp 	th = timehands;
1755f4b5a972SKonstantin Belousov 	pps->capgen = atomic_load_acq_int(&th->th_generation);
17566b00cf46SPoul-Henning Kamp 	pps->capth = th;
175765e359a1SLawrence Stewart #ifdef FFCLOCK
175865e359a1SLawrence Stewart 	pps->capffth = fftimehands;
175965e359a1SLawrence Stewart #endif
17606b00cf46SPoul-Henning Kamp 	pps->capcount = th->th_counter->tc_get_timecount(th->th_counter);
1761f4b5a972SKonstantin Belousov 	atomic_thread_fence_acq();
1762f4b5a972SKonstantin Belousov 	if (pps->capgen != th->th_generation)
17636b00cf46SPoul-Henning Kamp 		pps->capgen = 0;
17647bf758bfSPoul-Henning Kamp }
17657bf758bfSPoul-Henning Kamp 
17667bf758bfSPoul-Henning Kamp void
17677bf758bfSPoul-Henning Kamp pps_event(struct pps_state *pps, int event)
176832c20357SPoul-Henning Kamp {
176939acc78aSPoul-Henning Kamp 	struct bintime bt;
177032c20357SPoul-Henning Kamp 	struct timespec ts, *tsp, *osp;
17716b00cf46SPoul-Henning Kamp 	u_int tcount, *pcount;
1772aaca7045SEnji Cooper 	int foff;
177332c20357SPoul-Henning Kamp 	pps_seq_t *pseq;
177465e359a1SLawrence Stewart #ifdef FFCLOCK
177565e359a1SLawrence Stewart 	struct timespec *tsp_ffc;
177665e359a1SLawrence Stewart 	pps_seq_t *pseq_ffc;
177765e359a1SLawrence Stewart 	ffcounter *ffcount;
177865e359a1SLawrence Stewart #endif
1779aaca7045SEnji Cooper #ifdef PPS_SYNC
1780aaca7045SEnji Cooper 	int fhard;
1781aaca7045SEnji Cooper #endif
178232c20357SPoul-Henning Kamp 
1783d8e8b675SPoul-Henning Kamp 	KASSERT(pps != NULL, ("NULL pps pointer in pps_event"));
1784721b5817SIan Lepore 	/* Nothing to do if not currently set to capture this event type. */
1785721b5817SIan Lepore 	if ((event & pps->ppsparam.mode) == 0)
1786721b5817SIan Lepore 		return;
178739acc78aSPoul-Henning Kamp 	/* If the timecounter was wound up underneath us, bail out. */
1788f4b5a972SKonstantin Belousov 	if (pps->capgen == 0 || pps->capgen !=
1789f4b5a972SKonstantin Belousov 	    atomic_load_acq_int(&pps->capth->th_generation))
17907bf758bfSPoul-Henning Kamp 		return;
17917bf758bfSPoul-Henning Kamp 
179239acc78aSPoul-Henning Kamp 	/* Things would be easier with arrays. */
179332c20357SPoul-Henning Kamp 	if (event == PPS_CAPTUREASSERT) {
179432c20357SPoul-Henning Kamp 		tsp = &pps->ppsinfo.assert_timestamp;
179532c20357SPoul-Henning Kamp 		osp = &pps->ppsparam.assert_offset;
179632c20357SPoul-Henning Kamp 		foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1797aaca7045SEnji Cooper #ifdef PPS_SYNC
1798b7424f2dSJohn Hay 		fhard = pps->kcmode & PPS_CAPTUREASSERT;
1799aaca7045SEnji Cooper #endif
180032c20357SPoul-Henning Kamp 		pcount = &pps->ppscount[0];
180132c20357SPoul-Henning Kamp 		pseq = &pps->ppsinfo.assert_sequence;
180265e359a1SLawrence Stewart #ifdef FFCLOCK
180365e359a1SLawrence Stewart 		ffcount = &pps->ppsinfo_ffc.assert_ffcount;
180465e359a1SLawrence Stewart 		tsp_ffc = &pps->ppsinfo_ffc.assert_timestamp;
180565e359a1SLawrence Stewart 		pseq_ffc = &pps->ppsinfo_ffc.assert_sequence;
180665e359a1SLawrence Stewart #endif
180732c20357SPoul-Henning Kamp 	} else {
180832c20357SPoul-Henning Kamp 		tsp = &pps->ppsinfo.clear_timestamp;
180932c20357SPoul-Henning Kamp 		osp = &pps->ppsparam.clear_offset;
181032c20357SPoul-Henning Kamp 		foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1811aaca7045SEnji Cooper #ifdef PPS_SYNC
1812b7424f2dSJohn Hay 		fhard = pps->kcmode & PPS_CAPTURECLEAR;
1813aaca7045SEnji Cooper #endif
181432c20357SPoul-Henning Kamp 		pcount = &pps->ppscount[1];
181532c20357SPoul-Henning Kamp 		pseq = &pps->ppsinfo.clear_sequence;
181665e359a1SLawrence Stewart #ifdef FFCLOCK
181765e359a1SLawrence Stewart 		ffcount = &pps->ppsinfo_ffc.clear_ffcount;
181865e359a1SLawrence Stewart 		tsp_ffc = &pps->ppsinfo_ffc.clear_timestamp;
181965e359a1SLawrence Stewart 		pseq_ffc = &pps->ppsinfo_ffc.clear_sequence;
182065e359a1SLawrence Stewart #endif
182132c20357SPoul-Henning Kamp 	}
182232c20357SPoul-Henning Kamp 
182339acc78aSPoul-Henning Kamp 	/*
18246b00cf46SPoul-Henning Kamp 	 * If the timecounter changed, we cannot compare the count values, so
18256b00cf46SPoul-Henning Kamp 	 * we have to drop the rest of the PPS-stuff until the next event.
18266b00cf46SPoul-Henning Kamp 	 */
18276b00cf46SPoul-Henning Kamp 	if (pps->ppstc != pps->capth->th_counter) {
18286b00cf46SPoul-Henning Kamp 		pps->ppstc = pps->capth->th_counter;
18297bf758bfSPoul-Henning Kamp 		*pcount = pps->capcount;
18307bf758bfSPoul-Henning Kamp 		pps->ppscount[2] = pps->capcount;
183132c20357SPoul-Henning Kamp 		return;
183232c20357SPoul-Henning Kamp 	}
183332c20357SPoul-Henning Kamp 
183439acc78aSPoul-Henning Kamp 	/* Convert the count to a timespec. */
18356b00cf46SPoul-Henning Kamp 	tcount = pps->capcount - pps->capth->th_offset_count;
18366b00cf46SPoul-Henning Kamp 	tcount &= pps->capth->th_counter->tc_counter_mask;
183750c22263SKonstantin Belousov 	bt = pps->capth->th_bintime;
18386b00cf46SPoul-Henning Kamp 	bintime_addx(&bt, pps->capth->th_scale * tcount);
18392028c0cdSPoul-Henning Kamp 	bintime2timespec(&bt, &ts);
184032c20357SPoul-Henning Kamp 
184139acc78aSPoul-Henning Kamp 	/* If the timecounter was wound up underneath us, bail out. */
1842f4b5a972SKonstantin Belousov 	atomic_thread_fence_acq();
1843f4b5a972SKonstantin Belousov 	if (pps->capgen != pps->capth->th_generation)
18447bf758bfSPoul-Henning Kamp 		return;
18457bf758bfSPoul-Henning Kamp 
18467bf758bfSPoul-Henning Kamp 	*pcount = pps->capcount;
184732c20357SPoul-Henning Kamp 	(*pseq)++;
184832c20357SPoul-Henning Kamp 	*tsp = ts;
184932c20357SPoul-Henning Kamp 
185032c20357SPoul-Henning Kamp 	if (foff) {
18516040822cSAlan Somers 		timespecadd(tsp, osp, tsp);
185232c20357SPoul-Henning Kamp 		if (tsp->tv_nsec < 0) {
185332c20357SPoul-Henning Kamp 			tsp->tv_nsec += 1000000000;
185432c20357SPoul-Henning Kamp 			tsp->tv_sec -= 1;
185532c20357SPoul-Henning Kamp 		}
185632c20357SPoul-Henning Kamp 	}
185765e359a1SLawrence Stewart 
185865e359a1SLawrence Stewart #ifdef FFCLOCK
185965e359a1SLawrence Stewart 	*ffcount = pps->capffth->tick_ffcount + tcount;
186065e359a1SLawrence Stewart 	bt = pps->capffth->tick_time;
186165e359a1SLawrence Stewart 	ffclock_convert_delta(tcount, pps->capffth->cest.period, &bt);
186265e359a1SLawrence Stewart 	bintime_add(&bt, &pps->capffth->tick_time);
186365e359a1SLawrence Stewart 	bintime2timespec(&bt, &ts);
186465e359a1SLawrence Stewart 	(*pseq_ffc)++;
186565e359a1SLawrence Stewart 	*tsp_ffc = ts;
186665e359a1SLawrence Stewart #endif
186765e359a1SLawrence Stewart 
186832c20357SPoul-Henning Kamp #ifdef PPS_SYNC
186932c20357SPoul-Henning Kamp 	if (fhard) {
187060ae52f7SEd Schouten 		uint64_t scale;
1871ce9fac00SPoul-Henning Kamp 
187239acc78aSPoul-Henning Kamp 		/*
18736b00cf46SPoul-Henning Kamp 		 * Feed the NTP PLL/FLL.
1874b1e7e201SJohn Hay 		 * The FLL wants to know how many (hardware) nanoseconds
1875b1e7e201SJohn Hay 		 * elapsed since the previous event.
18766b00cf46SPoul-Henning Kamp 		 */
18777bf758bfSPoul-Henning Kamp 		tcount = pps->capcount - pps->ppscount[2];
18787bf758bfSPoul-Henning Kamp 		pps->ppscount[2] = pps->capcount;
18796b00cf46SPoul-Henning Kamp 		tcount &= pps->capth->th_counter->tc_counter_mask;
188060ae52f7SEd Schouten 		scale = (uint64_t)1 << 63;
1881b1e7e201SJohn Hay 		scale /= pps->capth->th_counter->tc_frequency;
1882b1e7e201SJohn Hay 		scale *= 2;
18832028c0cdSPoul-Henning Kamp 		bt.sec = 0;
18842028c0cdSPoul-Henning Kamp 		bt.frac = 0;
1885b1e7e201SJohn Hay 		bintime_addx(&bt, scale * tcount);
18862028c0cdSPoul-Henning Kamp 		bintime2timespec(&bt, &ts);
18872028c0cdSPoul-Henning Kamp 		hardpps(tsp, ts.tv_nsec + 1000000000 * ts.tv_sec);
188832c20357SPoul-Henning Kamp 	}
188932c20357SPoul-Henning Kamp #endif
1890a1137de9SIan Lepore 
1891a1137de9SIan Lepore 	/* Wakeup anyone sleeping in pps_fetch().  */
1892a1137de9SIan Lepore 	wakeup(pps);
189332c20357SPoul-Henning Kamp }
18949e1b5510SPoul-Henning Kamp 
189539acc78aSPoul-Henning Kamp /*
18969e1b5510SPoul-Henning Kamp  * Timecounters need to be updated every so often to prevent the hardware
18979e1b5510SPoul-Henning Kamp  * counter from overflowing.  Updating also recalculates the cached values
18989e1b5510SPoul-Henning Kamp  * used by the get*() family of functions, so their precision depends on
18999e1b5510SPoul-Henning Kamp  * the update frequency.
19009e1b5510SPoul-Henning Kamp  */
19019e1b5510SPoul-Henning Kamp 
19029e1b5510SPoul-Henning Kamp static int tc_tick;
1903b389be97SRebecca Cran SYSCTL_INT(_kern_timecounter, OID_AUTO, tick, CTLFLAG_RD, &tc_tick, 0,
1904b389be97SRebecca Cran     "Approximate number of hardclock ticks in a millisecond");
19059e1b5510SPoul-Henning Kamp 
1906e7fa55afSPoul-Henning Kamp void
19070e189873SAlexander Motin tc_ticktock(int cnt)
19089e1b5510SPoul-Henning Kamp {
1909e7fa55afSPoul-Henning Kamp 	static int count;
19109e1b5510SPoul-Henning Kamp 
19115760b029SKonstantin Belousov 	if (mtx_trylock_spin(&tc_setclock_mtx)) {
19120e189873SAlexander Motin 		count += cnt;
19135760b029SKonstantin Belousov 		if (count >= tc_tick) {
1914e7fa55afSPoul-Henning Kamp 			count = 0;
19155760b029SKonstantin Belousov 			tc_windup(NULL);
19165760b029SKonstantin Belousov 		}
19175760b029SKonstantin Belousov 		mtx_unlock_spin(&tc_setclock_mtx);
19185760b029SKonstantin Belousov 	}
19199e1b5510SPoul-Henning Kamp }
19209e1b5510SPoul-Henning Kamp 
19215b999a6bSDavide Italiano static void __inline
19225b999a6bSDavide Italiano tc_adjprecision(void)
19235b999a6bSDavide Italiano {
19245b999a6bSDavide Italiano 	int t;
19255b999a6bSDavide Italiano 
19265b999a6bSDavide Italiano 	if (tc_timepercentage > 0) {
19275b999a6bSDavide Italiano 		t = (99 + tc_timepercentage) / tc_timepercentage;
19285b999a6bSDavide Italiano 		tc_precexp = fls(t + (t >> 1)) - 1;
19295b999a6bSDavide Italiano 		FREQ2BT(hz / tc_tick, &bt_timethreshold);
19305b999a6bSDavide Italiano 		FREQ2BT(hz, &bt_tickthreshold);
19315b999a6bSDavide Italiano 		bintime_shift(&bt_timethreshold, tc_precexp);
19325b999a6bSDavide Italiano 		bintime_shift(&bt_tickthreshold, tc_precexp);
19335b999a6bSDavide Italiano 	} else {
19345b999a6bSDavide Italiano 		tc_precexp = 31;
19355b999a6bSDavide Italiano 		bt_timethreshold.sec = INT_MAX;
19365b999a6bSDavide Italiano 		bt_timethreshold.frac = ~(uint64_t)0;
19375b999a6bSDavide Italiano 		bt_tickthreshold = bt_timethreshold;
19385b999a6bSDavide Italiano 	}
19395b999a6bSDavide Italiano 	sbt_timethreshold = bttosbt(bt_timethreshold);
19405b999a6bSDavide Italiano 	sbt_tickthreshold = bttosbt(bt_tickthreshold);
19415b999a6bSDavide Italiano }
19425b999a6bSDavide Italiano 
19435b999a6bSDavide Italiano static int
19445b999a6bSDavide Italiano sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS)
19455b999a6bSDavide Italiano {
19465b999a6bSDavide Italiano 	int error, val;
19475b999a6bSDavide Italiano 
19485b999a6bSDavide Italiano 	val = tc_timepercentage;
19495b999a6bSDavide Italiano 	error = sysctl_handle_int(oidp, &val, 0, req);
19505b999a6bSDavide Italiano 	if (error != 0 || req->newptr == NULL)
19515b999a6bSDavide Italiano 		return (error);
19525b999a6bSDavide Italiano 	tc_timepercentage = val;
1953af3b2549SHans Petter Selasky 	if (cold)
1954af3b2549SHans Petter Selasky 		goto done;
19555b999a6bSDavide Italiano 	tc_adjprecision();
1956af3b2549SHans Petter Selasky done:
19575b999a6bSDavide Italiano 	return (0);
19585b999a6bSDavide Italiano }
19595b999a6bSDavide Italiano 
19609e1b5510SPoul-Henning Kamp static void
19619e1b5510SPoul-Henning Kamp inittimecounter(void *dummy)
19629e1b5510SPoul-Henning Kamp {
19639e1b5510SPoul-Henning Kamp 	u_int p;
19645b999a6bSDavide Italiano 	int tick_rate;
19659e1b5510SPoul-Henning Kamp 
196639acc78aSPoul-Henning Kamp 	/*
196739acc78aSPoul-Henning Kamp 	 * Set the initial timeout to
196839acc78aSPoul-Henning Kamp 	 * max(1, <approx. number of hardclock ticks in a millisecond>).
196939acc78aSPoul-Henning Kamp 	 * People should probably not use the sysctl to set the timeout
1970e3043798SPedro F. Giffuni 	 * to smaller than its initial value, since that value is the
197139acc78aSPoul-Henning Kamp 	 * smallest reasonable one.  If they want better timestamps they
197239acc78aSPoul-Henning Kamp 	 * should use the non-"get"* functions.
197339acc78aSPoul-Henning Kamp 	 */
19749e1b5510SPoul-Henning Kamp 	if (hz > 1000)
19759e1b5510SPoul-Henning Kamp 		tc_tick = (hz + 500) / 1000;
19769e1b5510SPoul-Henning Kamp 	else
19779e1b5510SPoul-Henning Kamp 		tc_tick = 1;
19785b999a6bSDavide Italiano 	tc_adjprecision();
19795b999a6bSDavide Italiano 	FREQ2BT(hz, &tick_bt);
19805b999a6bSDavide Italiano 	tick_sbt = bttosbt(tick_bt);
19815b999a6bSDavide Italiano 	tick_rate = hz / tc_tick;
19825b999a6bSDavide Italiano 	FREQ2BT(tick_rate, &tc_tick_bt);
19835b999a6bSDavide Italiano 	tc_tick_sbt = bttosbt(tc_tick_bt);
19849e1b5510SPoul-Henning Kamp 	p = (tc_tick * 1000000) / hz;
19859e1b5510SPoul-Henning Kamp 	printf("Timecounters tick every %d.%03u msec\n", p / 1000, p % 1000);
198639acc78aSPoul-Henning Kamp 
1987b0fdc837SLawrence Stewart #ifdef FFCLOCK
1988b0fdc837SLawrence Stewart 	ffclock_init();
1989b0fdc837SLawrence Stewart #endif
199048e5da55SPoul-Henning Kamp 	/* warm up new timecounter (again) and get rolling. */
199139acc78aSPoul-Henning Kamp 	(void)timecounter->tc_get_timecount(timecounter);
199239acc78aSPoul-Henning Kamp 	(void)timecounter->tc_get_timecount(timecounter);
19935760b029SKonstantin Belousov 	mtx_lock_spin(&tc_setclock_mtx);
19945760b029SKonstantin Belousov 	tc_windup(NULL);
19955760b029SKonstantin Belousov 	mtx_unlock_spin(&tc_setclock_mtx);
19969e1b5510SPoul-Henning Kamp }
19979e1b5510SPoul-Henning Kamp 
1998237fdd78SRobert Watson SYSINIT(timecounter, SI_SUB_CLOCKS, SI_ORDER_SECOND, inittimecounter, NULL);
19995b1a8eb3SPoul-Henning Kamp 
2000e8444a7eSPoul-Henning Kamp /* Cpu tick handling -------------------------------------------------*/
2001e8444a7eSPoul-Henning Kamp 
2002e8444a7eSPoul-Henning Kamp static int cpu_tick_variable;
2003e8444a7eSPoul-Henning Kamp static uint64_t	cpu_tick_frequency;
2004e8444a7eSPoul-Henning Kamp 
20052bf95012SAndrew Turner DPCPU_DEFINE_STATIC(uint64_t, tc_cpu_ticks_base);
20062bf95012SAndrew Turner DPCPU_DEFINE_STATIC(unsigned, tc_cpu_ticks_last);
2007b2557db6SKonstantin Belousov 
200888ca07e7SJohn Baldwin static uint64_t
20095b1a8eb3SPoul-Henning Kamp tc_cpu_ticks(void)
20105b1a8eb3SPoul-Henning Kamp {
20115b1a8eb3SPoul-Henning Kamp 	struct timecounter *tc;
2012b2557db6SKonstantin Belousov 	uint64_t res, *base;
2013b2557db6SKonstantin Belousov 	unsigned u, *last;
20145b1a8eb3SPoul-Henning Kamp 
2015b2557db6SKonstantin Belousov 	critical_enter();
2016b2557db6SKonstantin Belousov 	base = DPCPU_PTR(tc_cpu_ticks_base);
2017b2557db6SKonstantin Belousov 	last = DPCPU_PTR(tc_cpu_ticks_last);
20185b1a8eb3SPoul-Henning Kamp 	tc = timehands->th_counter;
20195b1a8eb3SPoul-Henning Kamp 	u = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
2020b2557db6SKonstantin Belousov 	if (u < *last)
2021b2557db6SKonstantin Belousov 		*base += (uint64_t)tc->tc_counter_mask + 1;
2022b2557db6SKonstantin Belousov 	*last = u;
2023b2557db6SKonstantin Belousov 	res = u + *base;
2024b2557db6SKonstantin Belousov 	critical_exit();
2025b2557db6SKonstantin Belousov 	return (res);
20265b1a8eb3SPoul-Henning Kamp }
20275b1a8eb3SPoul-Henning Kamp 
2028a157e425SAlexander Motin void
2029a157e425SAlexander Motin cpu_tick_calibration(void)
2030a157e425SAlexander Motin {
2031a157e425SAlexander Motin 	static time_t last_calib;
2032a157e425SAlexander Motin 
2033a157e425SAlexander Motin 	if (time_uptime != last_calib && !(time_uptime & 0xf)) {
2034a157e425SAlexander Motin 		cpu_tick_calibrate(0);
2035a157e425SAlexander Motin 		last_calib = time_uptime;
2036a157e425SAlexander Motin 	}
2037a157e425SAlexander Motin }
2038a157e425SAlexander Motin 
2039e8444a7eSPoul-Henning Kamp /*
20406b4d690cSWarner Losh  * This function gets called every 16 seconds on only one designated
2041a157e425SAlexander Motin  * CPU in the system from hardclock() via cpu_tick_calibration()().
2042e8444a7eSPoul-Henning Kamp  *
2043e8444a7eSPoul-Henning Kamp  * Whenever the real time clock is stepped we get called with reset=1
2044e8444a7eSPoul-Henning Kamp  * to make sure we handle suspend/resume and similar events correctly.
2045e8444a7eSPoul-Henning Kamp  */
2046e8444a7eSPoul-Henning Kamp 
2047e8444a7eSPoul-Henning Kamp static void
2048e8444a7eSPoul-Henning Kamp cpu_tick_calibrate(int reset)
2049e8444a7eSPoul-Henning Kamp {
2050e8444a7eSPoul-Henning Kamp 	static uint64_t c_last;
2051e8444a7eSPoul-Henning Kamp 	uint64_t c_this, c_delta;
2052e8444a7eSPoul-Henning Kamp 	static struct bintime  t_last;
2053e8444a7eSPoul-Henning Kamp 	struct bintime t_this, t_delta;
2054301af28aSPoul-Henning Kamp 	uint32_t divi;
2055e8444a7eSPoul-Henning Kamp 
2056e8444a7eSPoul-Henning Kamp 	if (reset) {
2057e8444a7eSPoul-Henning Kamp 		/* The clock was stepped, abort & reset */
2058e8444a7eSPoul-Henning Kamp 		t_last.sec = 0;
2059e8444a7eSPoul-Henning Kamp 		return;
2060e8444a7eSPoul-Henning Kamp 	}
2061e8444a7eSPoul-Henning Kamp 
2062e8444a7eSPoul-Henning Kamp 	/* we don't calibrate fixed rate cputicks */
2063e8444a7eSPoul-Henning Kamp 	if (!cpu_tick_variable)
2064e8444a7eSPoul-Henning Kamp 		return;
2065e8444a7eSPoul-Henning Kamp 
2066e8444a7eSPoul-Henning Kamp 	getbinuptime(&t_this);
2067e8444a7eSPoul-Henning Kamp 	c_this = cpu_ticks();
2068e8444a7eSPoul-Henning Kamp 	if (t_last.sec != 0) {
2069e8444a7eSPoul-Henning Kamp 		c_delta = c_this - c_last;
2070e8444a7eSPoul-Henning Kamp 		t_delta = t_this;
2071e8444a7eSPoul-Henning Kamp 		bintime_sub(&t_delta, &t_last);
2072e8444a7eSPoul-Henning Kamp 		/*
2073301af28aSPoul-Henning Kamp 		 * Headroom:
2074301af28aSPoul-Henning Kamp 		 * 	2^(64-20) / 16[s] =
2075301af28aSPoul-Henning Kamp 		 * 	2^(44) / 16[s] =
2076301af28aSPoul-Henning Kamp 		 * 	17.592.186.044.416 / 16 =
2077301af28aSPoul-Henning Kamp 		 * 	1.099.511.627.776 [Hz]
2078301af28aSPoul-Henning Kamp 		 */
2079301af28aSPoul-Henning Kamp 		divi = t_delta.sec << 20;
2080301af28aSPoul-Henning Kamp 		divi |= t_delta.frac >> (64 - 20);
2081301af28aSPoul-Henning Kamp 		c_delta <<= 20;
2082301af28aSPoul-Henning Kamp 		c_delta /= divi;
2083e8444a7eSPoul-Henning Kamp 		if (c_delta > cpu_tick_frequency) {
208459048707SPoul-Henning Kamp 			if (0 && bootverbose)
2085fef527eeSPoul-Henning Kamp 				printf("cpu_tick increased to %ju Hz\n",
20866cda760fSPoul-Henning Kamp 				    c_delta);
2087e8444a7eSPoul-Henning Kamp 			cpu_tick_frequency = c_delta;
2088e8444a7eSPoul-Henning Kamp 		}
2089e8444a7eSPoul-Henning Kamp 	}
2090e8444a7eSPoul-Henning Kamp 	c_last = c_this;
2091e8444a7eSPoul-Henning Kamp 	t_last = t_this;
2092e8444a7eSPoul-Henning Kamp }
2093e8444a7eSPoul-Henning Kamp 
2094e8444a7eSPoul-Henning Kamp void
2095e8444a7eSPoul-Henning Kamp set_cputicker(cpu_tick_f *func, uint64_t freq, unsigned var)
2096e8444a7eSPoul-Henning Kamp {
2097e8444a7eSPoul-Henning Kamp 
2098e8444a7eSPoul-Henning Kamp 	if (func == NULL) {
2099e8444a7eSPoul-Henning Kamp 		cpu_ticks = tc_cpu_ticks;
2100e8444a7eSPoul-Henning Kamp 	} else {
2101e8444a7eSPoul-Henning Kamp 		cpu_tick_frequency = freq;
2102e8444a7eSPoul-Henning Kamp 		cpu_tick_variable = var;
2103e8444a7eSPoul-Henning Kamp 		cpu_ticks = func;
2104e8444a7eSPoul-Henning Kamp 	}
2105e8444a7eSPoul-Henning Kamp }
2106e8444a7eSPoul-Henning Kamp 
2107e8444a7eSPoul-Henning Kamp uint64_t
2108e8444a7eSPoul-Henning Kamp cpu_tickrate(void)
2109e8444a7eSPoul-Henning Kamp {
2110e8444a7eSPoul-Henning Kamp 
2111e8444a7eSPoul-Henning Kamp 	if (cpu_ticks == tc_cpu_ticks)
2112e8444a7eSPoul-Henning Kamp 		return (tc_getfrequency());
2113e8444a7eSPoul-Henning Kamp 	return (cpu_tick_frequency);
2114e8444a7eSPoul-Henning Kamp }
2115e8444a7eSPoul-Henning Kamp 
2116e8444a7eSPoul-Henning Kamp /*
2117e8444a7eSPoul-Henning Kamp  * We need to be slightly careful converting cputicks to microseconds.
2118e8444a7eSPoul-Henning Kamp  * There is plenty of margin in 64 bits of microseconds (half a million
2119e8444a7eSPoul-Henning Kamp  * years) and in 64 bits at 4 GHz (146 years), but if we do a multiply
2120e8444a7eSPoul-Henning Kamp  * before divide conversion (to retain precision) we find that the
2121e8444a7eSPoul-Henning Kamp  * margin shrinks to 1.5 hours (one millionth of 146y).
2122776fc0e9SYaroslav Tykhiy  * With a three prong approach we never lose significant bits, no
2123e8444a7eSPoul-Henning Kamp  * matter what the cputick rate and length of timeinterval is.
2124e8444a7eSPoul-Henning Kamp  */
2125e8444a7eSPoul-Henning Kamp 
2126e8444a7eSPoul-Henning Kamp uint64_t
2127e8444a7eSPoul-Henning Kamp cputick2usec(uint64_t tick)
2128e8444a7eSPoul-Henning Kamp {
2129e8444a7eSPoul-Henning Kamp 
2130e8444a7eSPoul-Henning Kamp 	if (tick > 18446744073709551LL)		/* floor(2^64 / 1000) */
2131e8444a7eSPoul-Henning Kamp 		return (tick / (cpu_tickrate() / 1000000LL));
2132e8444a7eSPoul-Henning Kamp 	else if (tick > 18446744073709LL)	/* floor(2^64 / 1000000) */
2133e8444a7eSPoul-Henning Kamp 		return ((tick * 1000LL) / (cpu_tickrate() / 1000LL));
2134e8444a7eSPoul-Henning Kamp 	else
2135e8444a7eSPoul-Henning Kamp 		return ((tick * 1000000LL) / cpu_tickrate());
2136e8444a7eSPoul-Henning Kamp }
2137e8444a7eSPoul-Henning Kamp 
2138e8444a7eSPoul-Henning Kamp cpu_tick_f	*cpu_ticks = tc_cpu_ticks;
2139aea81038SKonstantin Belousov 
2140aea81038SKonstantin Belousov static int vdso_th_enable = 1;
2141aea81038SKonstantin Belousov static int
2142aea81038SKonstantin Belousov sysctl_fast_gettime(SYSCTL_HANDLER_ARGS)
2143aea81038SKonstantin Belousov {
2144aea81038SKonstantin Belousov 	int old_vdso_th_enable, error;
2145aea81038SKonstantin Belousov 
2146aea81038SKonstantin Belousov 	old_vdso_th_enable = vdso_th_enable;
2147aea81038SKonstantin Belousov 	error = sysctl_handle_int(oidp, &old_vdso_th_enable, 0, req);
2148aea81038SKonstantin Belousov 	if (error != 0)
2149aea81038SKonstantin Belousov 		return (error);
2150aea81038SKonstantin Belousov 	vdso_th_enable = old_vdso_th_enable;
2151aea81038SKonstantin Belousov 	return (0);
2152aea81038SKonstantin Belousov }
2153aea81038SKonstantin Belousov SYSCTL_PROC(_kern_timecounter, OID_AUTO, fast_gettime,
2154aea81038SKonstantin Belousov     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
2155aea81038SKonstantin Belousov     NULL, 0, sysctl_fast_gettime, "I", "Enable fast time of day");
2156aea81038SKonstantin Belousov 
2157aea81038SKonstantin Belousov uint32_t
2158aea81038SKonstantin Belousov tc_fill_vdso_timehands(struct vdso_timehands *vdso_th)
2159aea81038SKonstantin Belousov {
2160aea81038SKonstantin Belousov 	struct timehands *th;
2161aea81038SKonstantin Belousov 	uint32_t enabled;
2162aea81038SKonstantin Belousov 
2163aea81038SKonstantin Belousov 	th = timehands;
2164aea81038SKonstantin Belousov 	vdso_th->th_scale = th->th_scale;
2165aea81038SKonstantin Belousov 	vdso_th->th_offset_count = th->th_offset_count;
2166aea81038SKonstantin Belousov 	vdso_th->th_counter_mask = th->th_counter->tc_counter_mask;
2167aea81038SKonstantin Belousov 	vdso_th->th_offset = th->th_offset;
21685760b029SKonstantin Belousov 	vdso_th->th_boottime = th->th_boottime;
216916808549SKonstantin Belousov 	if (th->th_counter->tc_fill_vdso_timehands != NULL) {
217016808549SKonstantin Belousov 		enabled = th->th_counter->tc_fill_vdso_timehands(vdso_th,
217116808549SKonstantin Belousov 		    th->th_counter);
217216808549SKonstantin Belousov 	} else
217316808549SKonstantin Belousov 		enabled = 0;
2174aea81038SKonstantin Belousov 	if (!vdso_th_enable)
2175aea81038SKonstantin Belousov 		enabled = 0;
2176aea81038SKonstantin Belousov 	return (enabled);
2177aea81038SKonstantin Belousov }
2178aea81038SKonstantin Belousov 
2179aea81038SKonstantin Belousov #ifdef COMPAT_FREEBSD32
2180aea81038SKonstantin Belousov uint32_t
2181aea81038SKonstantin Belousov tc_fill_vdso_timehands32(struct vdso_timehands32 *vdso_th32)
2182aea81038SKonstantin Belousov {
2183aea81038SKonstantin Belousov 	struct timehands *th;
2184aea81038SKonstantin Belousov 	uint32_t enabled;
2185aea81038SKonstantin Belousov 
2186aea81038SKonstantin Belousov 	th = timehands;
2187aea81038SKonstantin Belousov 	*(uint64_t *)&vdso_th32->th_scale[0] = th->th_scale;
2188aea81038SKonstantin Belousov 	vdso_th32->th_offset_count = th->th_offset_count;
2189aea81038SKonstantin Belousov 	vdso_th32->th_counter_mask = th->th_counter->tc_counter_mask;
2190aea81038SKonstantin Belousov 	vdso_th32->th_offset.sec = th->th_offset.sec;
2191aea81038SKonstantin Belousov 	*(uint64_t *)&vdso_th32->th_offset.frac[0] = th->th_offset.frac;
21925760b029SKonstantin Belousov 	vdso_th32->th_boottime.sec = th->th_boottime.sec;
21935760b029SKonstantin Belousov 	*(uint64_t *)&vdso_th32->th_boottime.frac[0] = th->th_boottime.frac;
219416808549SKonstantin Belousov 	if (th->th_counter->tc_fill_vdso_timehands32 != NULL) {
219516808549SKonstantin Belousov 		enabled = th->th_counter->tc_fill_vdso_timehands32(vdso_th32,
219616808549SKonstantin Belousov 		    th->th_counter);
219716808549SKonstantin Belousov 	} else
219816808549SKonstantin Belousov 		enabled = 0;
2199aea81038SKonstantin Belousov 	if (!vdso_th_enable)
2200aea81038SKonstantin Belousov 		enabled = 0;
2201aea81038SKonstantin Belousov 	return (enabled);
2202aea81038SKonstantin Belousov }
2203aea81038SKonstantin Belousov #endif
2204