kern_tc.c revision 156270
1/*-
2 * ----------------------------------------------------------------------------
3 * "THE BEER-WARE LICENSE" (Revision 42):
4 * <phk@FreeBSD.ORG> wrote this file.  As long as you retain this notice you
5 * can do whatever you want with this stuff. If we meet some day, and you think
6 * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
7 * ----------------------------------------------------------------------------
8 */
9
10#include <sys/cdefs.h>
11__FBSDID("$FreeBSD: head/sys/kern/kern_tc.c 156270 2006-03-04 06:06:43Z phk $");
12
13#include "opt_ntp.h"
14
15#include <sys/param.h>
16#include <sys/kernel.h>
17#include <sys/sysctl.h>
18#include <sys/syslog.h>
19#include <sys/systm.h>
20#include <sys/timepps.h>
21#include <sys/timetc.h>
22#include <sys/timex.h>
23
24/*
25 * A large step happens on boot.  This constant detects such steps.
26 * It is relatively small so that ntp_update_second gets called enough
27 * in the typical 'missed a couple of seconds' case, but doesn't loop
28 * forever when the time step is large.
29 */
30#define LARGE_STEP	200
31
32/*
33 * Implement a dummy timecounter which we can use until we get a real one
34 * in the air.  This allows the console and other early stuff to use
35 * time services.
36 */
37
38static u_int
39dummy_get_timecount(struct timecounter *tc)
40{
41	static u_int now;
42
43	return (++now);
44}
45
46static struct timecounter dummy_timecounter = {
47	dummy_get_timecount, 0, ~0u, 1000000, "dummy", -1000000
48};
49
50struct timehands {
51	/* These fields must be initialized by the driver. */
52	struct timecounter	*th_counter;
53	int64_t			th_adjustment;
54	u_int64_t		th_scale;
55	u_int	 		th_offset_count;
56	struct bintime		th_offset;
57	struct timeval		th_microtime;
58	struct timespec		th_nanotime;
59	/* Fields not to be copied in tc_windup start with th_generation. */
60	volatile u_int		th_generation;
61	struct timehands	*th_next;
62};
63
64static struct timehands th0;
65static struct timehands th9 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th0};
66static struct timehands th8 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th9};
67static struct timehands th7 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th8};
68static struct timehands th6 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th7};
69static struct timehands th5 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th6};
70static struct timehands th4 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th5};
71static struct timehands th3 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th4};
72static struct timehands th2 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th3};
73static struct timehands th1 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th2};
74static struct timehands th0 = {
75	&dummy_timecounter,
76	0,
77	(uint64_t)-1 / 1000000,
78	0,
79	{1, 0},
80	{0, 0},
81	{0, 0},
82	1,
83	&th1
84};
85
86static struct timehands *volatile timehands = &th0;
87struct timecounter *timecounter = &dummy_timecounter;
88static struct timecounter *timecounters = &dummy_timecounter;
89
90time_t time_second = 1;
91time_t time_uptime = 1;
92
93static struct bintime boottimebin;
94struct timeval boottime;
95static int sysctl_kern_boottime(SYSCTL_HANDLER_ARGS);
96SYSCTL_PROC(_kern, KERN_BOOTTIME, boottime, CTLTYPE_STRUCT|CTLFLAG_RD,
97    NULL, 0, sysctl_kern_boottime, "S,timeval", "System boottime");
98
99SYSCTL_NODE(_kern, OID_AUTO, timecounter, CTLFLAG_RW, 0, "");
100
101static int timestepwarnings;
102SYSCTL_INT(_kern_timecounter, OID_AUTO, stepwarnings, CTLFLAG_RW,
103    &timestepwarnings, 0, "");
104
105#define TC_STATS(foo) \
106	static u_int foo; \
107	SYSCTL_UINT(_kern_timecounter, OID_AUTO, foo, CTLFLAG_RD, &foo, 0, "");\
108	struct __hack
109
110TC_STATS(nbinuptime);    TC_STATS(nnanouptime);    TC_STATS(nmicrouptime);
111TC_STATS(nbintime);      TC_STATS(nnanotime);      TC_STATS(nmicrotime);
112TC_STATS(ngetbinuptime); TC_STATS(ngetnanouptime); TC_STATS(ngetmicrouptime);
113TC_STATS(ngetbintime);   TC_STATS(ngetnanotime);   TC_STATS(ngetmicrotime);
114TC_STATS(nsetclock);
115
116#undef TC_STATS
117
118static void tc_windup(void);
119static void cpu_tick_calibrate(int);
120
121static int
122sysctl_kern_boottime(SYSCTL_HANDLER_ARGS)
123{
124#ifdef SCTL_MASK32
125	int tv[2];
126
127	if (req->flags & SCTL_MASK32) {
128		tv[0] = boottime.tv_sec;
129		tv[1] = boottime.tv_usec;
130		return SYSCTL_OUT(req, tv, sizeof(tv));
131	} else
132#endif
133		return SYSCTL_OUT(req, &boottime, sizeof(boottime));
134}
135
136/*
137 * Return the difference between the timehands' counter value now and what
138 * was when we copied it to the timehands' offset_count.
139 */
140static __inline u_int
141tc_delta(struct timehands *th)
142{
143	struct timecounter *tc;
144
145	tc = th->th_counter;
146	return ((tc->tc_get_timecount(tc) - th->th_offset_count) &
147	    tc->tc_counter_mask);
148}
149
150/*
151 * Functions for reading the time.  We have to loop until we are sure that
152 * the timehands that we operated on was not updated under our feet.  See
153 * the comment in <sys/time.h> for a description of these 12 functions.
154 */
155
156void
157binuptime(struct bintime *bt)
158{
159	struct timehands *th;
160	u_int gen;
161
162	nbinuptime++;
163	do {
164		th = timehands;
165		gen = th->th_generation;
166		*bt = th->th_offset;
167		bintime_addx(bt, th->th_scale * tc_delta(th));
168	} while (gen == 0 || gen != th->th_generation);
169}
170
171void
172nanouptime(struct timespec *tsp)
173{
174	struct bintime bt;
175
176	nnanouptime++;
177	binuptime(&bt);
178	bintime2timespec(&bt, tsp);
179}
180
181void
182microuptime(struct timeval *tvp)
183{
184	struct bintime bt;
185
186	nmicrouptime++;
187	binuptime(&bt);
188	bintime2timeval(&bt, tvp);
189}
190
191void
192bintime(struct bintime *bt)
193{
194
195	nbintime++;
196	binuptime(bt);
197	bintime_add(bt, &boottimebin);
198}
199
200void
201nanotime(struct timespec *tsp)
202{
203	struct bintime bt;
204
205	nnanotime++;
206	bintime(&bt);
207	bintime2timespec(&bt, tsp);
208}
209
210void
211microtime(struct timeval *tvp)
212{
213	struct bintime bt;
214
215	nmicrotime++;
216	bintime(&bt);
217	bintime2timeval(&bt, tvp);
218}
219
220void
221getbinuptime(struct bintime *bt)
222{
223	struct timehands *th;
224	u_int gen;
225
226	ngetbinuptime++;
227	do {
228		th = timehands;
229		gen = th->th_generation;
230		*bt = th->th_offset;
231	} while (gen == 0 || gen != th->th_generation);
232}
233
234void
235getnanouptime(struct timespec *tsp)
236{
237	struct timehands *th;
238	u_int gen;
239
240	ngetnanouptime++;
241	do {
242		th = timehands;
243		gen = th->th_generation;
244		bintime2timespec(&th->th_offset, tsp);
245	} while (gen == 0 || gen != th->th_generation);
246}
247
248void
249getmicrouptime(struct timeval *tvp)
250{
251	struct timehands *th;
252	u_int gen;
253
254	ngetmicrouptime++;
255	do {
256		th = timehands;
257		gen = th->th_generation;
258		bintime2timeval(&th->th_offset, tvp);
259	} while (gen == 0 || gen != th->th_generation);
260}
261
262void
263getbintime(struct bintime *bt)
264{
265	struct timehands *th;
266	u_int gen;
267
268	ngetbintime++;
269	do {
270		th = timehands;
271		gen = th->th_generation;
272		*bt = th->th_offset;
273	} while (gen == 0 || gen != th->th_generation);
274	bintime_add(bt, &boottimebin);
275}
276
277void
278getnanotime(struct timespec *tsp)
279{
280	struct timehands *th;
281	u_int gen;
282
283	ngetnanotime++;
284	do {
285		th = timehands;
286		gen = th->th_generation;
287		*tsp = th->th_nanotime;
288	} while (gen == 0 || gen != th->th_generation);
289}
290
291void
292getmicrotime(struct timeval *tvp)
293{
294	struct timehands *th;
295	u_int gen;
296
297	ngetmicrotime++;
298	do {
299		th = timehands;
300		gen = th->th_generation;
301		*tvp = th->th_microtime;
302	} while (gen == 0 || gen != th->th_generation);
303}
304
305/*
306 * Initialize a new timecounter and possibly use it.
307 */
308void
309tc_init(struct timecounter *tc)
310{
311	u_int u;
312
313	u = tc->tc_frequency / tc->tc_counter_mask;
314	/* XXX: We need some margin here, 10% is a guess */
315	u *= 11;
316	u /= 10;
317	if (u > hz && tc->tc_quality >= 0) {
318		tc->tc_quality = -2000;
319		if (bootverbose) {
320			printf("Timecounter \"%s\" frequency %ju Hz",
321			    tc->tc_name, (uintmax_t)tc->tc_frequency);
322			printf(" -- Insufficient hz, needs at least %u\n", u);
323		}
324	} else if (tc->tc_quality >= 0 || bootverbose) {
325		printf("Timecounter \"%s\" frequency %ju Hz quality %d\n",
326		    tc->tc_name, (uintmax_t)tc->tc_frequency,
327		    tc->tc_quality);
328	}
329
330	tc->tc_next = timecounters;
331	timecounters = tc;
332	/*
333	 * Never automatically use a timecounter with negative quality.
334	 * Even though we run on the dummy counter, switching here may be
335	 * worse since this timecounter may not be monotonous.
336	 */
337	if (tc->tc_quality < 0)
338		return;
339	if (tc->tc_quality < timecounter->tc_quality)
340		return;
341	if (tc->tc_quality == timecounter->tc_quality &&
342	    tc->tc_frequency < timecounter->tc_frequency)
343		return;
344	(void)tc->tc_get_timecount(tc);
345	(void)tc->tc_get_timecount(tc);
346	timecounter = tc;
347}
348
349/* Report the frequency of the current timecounter. */
350u_int64_t
351tc_getfrequency(void)
352{
353
354	return (timehands->th_counter->tc_frequency);
355}
356
357/*
358 * Step our concept of UTC.  This is done by modifying our estimate of
359 * when we booted.
360 * XXX: not locked.
361 */
362void
363tc_setclock(struct timespec *ts)
364{
365	struct timespec tbef, taft;
366	struct bintime bt, bt2;
367
368	cpu_tick_calibrate(1);
369	nsetclock++;
370	nanotime(&tbef);
371	timespec2bintime(ts, &bt);
372	binuptime(&bt2);
373	bintime_sub(&bt, &bt2);
374	bintime_add(&bt2, &boottimebin);
375	boottimebin = bt;
376	bintime2timeval(&bt, &boottime);
377
378	/* XXX fiddle all the little crinkly bits around the fiords... */
379	tc_windup();
380	nanotime(&taft);
381	if (timestepwarnings) {
382		log(LOG_INFO,
383		    "Time stepped from %jd.%09ld to %jd.%09ld (%jd.%09ld)\n",
384		    (intmax_t)tbef.tv_sec, tbef.tv_nsec,
385		    (intmax_t)taft.tv_sec, taft.tv_nsec,
386		    (intmax_t)ts->tv_sec, ts->tv_nsec);
387	}
388	cpu_tick_calibrate(1);
389}
390
391/*
392 * Initialize the next struct timehands in the ring and make
393 * it the active timehands.  Along the way we might switch to a different
394 * timecounter and/or do seconds processing in NTP.  Slightly magic.
395 */
396static void
397tc_windup(void)
398{
399	struct bintime bt;
400	struct timehands *th, *tho;
401	u_int64_t scale;
402	u_int delta, ncount, ogen;
403	int i;
404	time_t t;
405
406	/*
407	 * Make the next timehands a copy of the current one, but do not
408	 * overwrite the generation or next pointer.  While we update
409	 * the contents, the generation must be zero.
410	 */
411	tho = timehands;
412	th = tho->th_next;
413	ogen = th->th_generation;
414	th->th_generation = 0;
415	bcopy(tho, th, offsetof(struct timehands, th_generation));
416
417	/*
418	 * Capture a timecounter delta on the current timecounter and if
419	 * changing timecounters, a counter value from the new timecounter.
420	 * Update the offset fields accordingly.
421	 */
422	delta = tc_delta(th);
423	if (th->th_counter != timecounter)
424		ncount = timecounter->tc_get_timecount(timecounter);
425	else
426		ncount = 0;
427	th->th_offset_count += delta;
428	th->th_offset_count &= th->th_counter->tc_counter_mask;
429	bintime_addx(&th->th_offset, th->th_scale * delta);
430
431	/*
432	 * Hardware latching timecounters may not generate interrupts on
433	 * PPS events, so instead we poll them.  There is a finite risk that
434	 * the hardware might capture a count which is later than the one we
435	 * got above, and therefore possibly in the next NTP second which might
436	 * have a different rate than the current NTP second.  It doesn't
437	 * matter in practice.
438	 */
439	if (tho->th_counter->tc_poll_pps)
440		tho->th_counter->tc_poll_pps(tho->th_counter);
441
442	/*
443	 * Deal with NTP second processing.  The for loop normally
444	 * iterates at most once, but in extreme situations it might
445	 * keep NTP sane if timeouts are not run for several seconds.
446	 * At boot, the time step can be large when the TOD hardware
447	 * has been read, so on really large steps, we call
448	 * ntp_update_second only twice.  We need to call it twice in
449	 * case we missed a leap second.
450	 */
451	bt = th->th_offset;
452	bintime_add(&bt, &boottimebin);
453	i = bt.sec - tho->th_microtime.tv_sec;
454	if (i > LARGE_STEP)
455		i = 2;
456	for (; i > 0; i--) {
457		t = bt.sec;
458		ntp_update_second(&th->th_adjustment, &bt.sec);
459		if (bt.sec != t)
460			boottimebin.sec += bt.sec - t;
461	}
462	/* Update the UTC timestamps used by the get*() functions. */
463	/* XXX shouldn't do this here.  Should force non-`get' versions. */
464	bintime2timeval(&bt, &th->th_microtime);
465	bintime2timespec(&bt, &th->th_nanotime);
466
467	/* Now is a good time to change timecounters. */
468	if (th->th_counter != timecounter) {
469		th->th_counter = timecounter;
470		th->th_offset_count = ncount;
471	}
472
473	/*-
474	 * Recalculate the scaling factor.  We want the number of 1/2^64
475	 * fractions of a second per period of the hardware counter, taking
476	 * into account the th_adjustment factor which the NTP PLL/adjtime(2)
477	 * processing provides us with.
478	 *
479	 * The th_adjustment is nanoseconds per second with 32 bit binary
480	 * fraction and we want 64 bit binary fraction of second:
481	 *
482	 *	 x = a * 2^32 / 10^9 = a * 4.294967296
483	 *
484	 * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
485	 * we can only multiply by about 850 without overflowing, that
486	 * leaves no suitably precise fractions for multiply before divide.
487	 *
488	 * Divide before multiply with a fraction of 2199/512 results in a
489	 * systematic undercompensation of 10PPM of th_adjustment.  On a
490	 * 5000PPM adjustment this is a 0.05PPM error.  This is acceptable.
491 	 *
492	 * We happily sacrifice the lowest of the 64 bits of our result
493	 * to the goddess of code clarity.
494	 *
495	 */
496	scale = (u_int64_t)1 << 63;
497	scale += (th->th_adjustment / 1024) * 2199;
498	scale /= th->th_counter->tc_frequency;
499	th->th_scale = scale * 2;
500
501	/*
502	 * Now that the struct timehands is again consistent, set the new
503	 * generation number, making sure to not make it zero.
504	 */
505	if (++ogen == 0)
506		ogen = 1;
507	th->th_generation = ogen;
508
509	/* Go live with the new struct timehands. */
510	time_second = th->th_microtime.tv_sec;
511	time_uptime = th->th_offset.sec;
512	timehands = th;
513}
514
515/* Report or change the active timecounter hardware. */
516static int
517sysctl_kern_timecounter_hardware(SYSCTL_HANDLER_ARGS)
518{
519	char newname[32];
520	struct timecounter *newtc, *tc;
521	int error;
522
523	tc = timecounter;
524	strlcpy(newname, tc->tc_name, sizeof(newname));
525
526	error = sysctl_handle_string(oidp, &newname[0], sizeof(newname), req);
527	if (error != 0 || req->newptr == NULL ||
528	    strcmp(newname, tc->tc_name) == 0)
529		return (error);
530	for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
531		if (strcmp(newname, newtc->tc_name) != 0)
532			continue;
533
534		/* Warm up new timecounter. */
535		(void)newtc->tc_get_timecount(newtc);
536		(void)newtc->tc_get_timecount(newtc);
537
538		timecounter = newtc;
539		return (0);
540	}
541	return (EINVAL);
542}
543
544SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware, CTLTYPE_STRING | CTLFLAG_RW,
545    0, 0, sysctl_kern_timecounter_hardware, "A", "");
546
547
548/* Report or change the active timecounter hardware. */
549static int
550sysctl_kern_timecounter_choice(SYSCTL_HANDLER_ARGS)
551{
552	char buf[32], *spc;
553	struct timecounter *tc;
554	int error;
555
556	spc = "";
557	error = 0;
558	for (tc = timecounters; error == 0 && tc != NULL; tc = tc->tc_next) {
559		sprintf(buf, "%s%s(%d)",
560		    spc, tc->tc_name, tc->tc_quality);
561		error = SYSCTL_OUT(req, buf, strlen(buf));
562		spc = " ";
563	}
564	return (error);
565}
566
567SYSCTL_PROC(_kern_timecounter, OID_AUTO, choice, CTLTYPE_STRING | CTLFLAG_RD,
568    0, 0, sysctl_kern_timecounter_choice, "A", "");
569
570/*
571 * RFC 2783 PPS-API implementation.
572 */
573
574int
575pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
576{
577	pps_params_t *app;
578	struct pps_fetch_args *fapi;
579#ifdef PPS_SYNC
580	struct pps_kcbind_args *kapi;
581#endif
582
583	KASSERT(pps != NULL, ("NULL pps pointer in pps_ioctl"));
584	switch (cmd) {
585	case PPS_IOC_CREATE:
586		return (0);
587	case PPS_IOC_DESTROY:
588		return (0);
589	case PPS_IOC_SETPARAMS:
590		app = (pps_params_t *)data;
591		if (app->mode & ~pps->ppscap)
592			return (EINVAL);
593		pps->ppsparam = *app;
594		return (0);
595	case PPS_IOC_GETPARAMS:
596		app = (pps_params_t *)data;
597		*app = pps->ppsparam;
598		app->api_version = PPS_API_VERS_1;
599		return (0);
600	case PPS_IOC_GETCAP:
601		*(int*)data = pps->ppscap;
602		return (0);
603	case PPS_IOC_FETCH:
604		fapi = (struct pps_fetch_args *)data;
605		if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
606			return (EINVAL);
607		if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec)
608			return (EOPNOTSUPP);
609		pps->ppsinfo.current_mode = pps->ppsparam.mode;
610		fapi->pps_info_buf = pps->ppsinfo;
611		return (0);
612	case PPS_IOC_KCBIND:
613#ifdef PPS_SYNC
614		kapi = (struct pps_kcbind_args *)data;
615		/* XXX Only root should be able to do this */
616		if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
617			return (EINVAL);
618		if (kapi->kernel_consumer != PPS_KC_HARDPPS)
619			return (EINVAL);
620		if (kapi->edge & ~pps->ppscap)
621			return (EINVAL);
622		pps->kcmode = kapi->edge;
623		return (0);
624#else
625		return (EOPNOTSUPP);
626#endif
627	default:
628		return (ENOIOCTL);
629	}
630}
631
632void
633pps_init(struct pps_state *pps)
634{
635	pps->ppscap |= PPS_TSFMT_TSPEC;
636	if (pps->ppscap & PPS_CAPTUREASSERT)
637		pps->ppscap |= PPS_OFFSETASSERT;
638	if (pps->ppscap & PPS_CAPTURECLEAR)
639		pps->ppscap |= PPS_OFFSETCLEAR;
640}
641
642void
643pps_capture(struct pps_state *pps)
644{
645	struct timehands *th;
646
647	KASSERT(pps != NULL, ("NULL pps pointer in pps_capture"));
648	th = timehands;
649	pps->capgen = th->th_generation;
650	pps->capth = th;
651	pps->capcount = th->th_counter->tc_get_timecount(th->th_counter);
652	if (pps->capgen != th->th_generation)
653		pps->capgen = 0;
654}
655
656void
657pps_event(struct pps_state *pps, int event)
658{
659	struct bintime bt;
660	struct timespec ts, *tsp, *osp;
661	u_int tcount, *pcount;
662	int foff, fhard;
663	pps_seq_t *pseq;
664
665	KASSERT(pps != NULL, ("NULL pps pointer in pps_event"));
666	/* If the timecounter was wound up underneath us, bail out. */
667	if (pps->capgen == 0 || pps->capgen != pps->capth->th_generation)
668		return;
669
670	/* Things would be easier with arrays. */
671	if (event == PPS_CAPTUREASSERT) {
672		tsp = &pps->ppsinfo.assert_timestamp;
673		osp = &pps->ppsparam.assert_offset;
674		foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
675		fhard = pps->kcmode & PPS_CAPTUREASSERT;
676		pcount = &pps->ppscount[0];
677		pseq = &pps->ppsinfo.assert_sequence;
678	} else {
679		tsp = &pps->ppsinfo.clear_timestamp;
680		osp = &pps->ppsparam.clear_offset;
681		foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
682		fhard = pps->kcmode & PPS_CAPTURECLEAR;
683		pcount = &pps->ppscount[1];
684		pseq = &pps->ppsinfo.clear_sequence;
685	}
686
687	/*
688	 * If the timecounter changed, we cannot compare the count values, so
689	 * we have to drop the rest of the PPS-stuff until the next event.
690	 */
691	if (pps->ppstc != pps->capth->th_counter) {
692		pps->ppstc = pps->capth->th_counter;
693		*pcount = pps->capcount;
694		pps->ppscount[2] = pps->capcount;
695		return;
696	}
697
698	/* Convert the count to a timespec. */
699	tcount = pps->capcount - pps->capth->th_offset_count;
700	tcount &= pps->capth->th_counter->tc_counter_mask;
701	bt = pps->capth->th_offset;
702	bintime_addx(&bt, pps->capth->th_scale * tcount);
703	bintime_add(&bt, &boottimebin);
704	bintime2timespec(&bt, &ts);
705
706	/* If the timecounter was wound up underneath us, bail out. */
707	if (pps->capgen != pps->capth->th_generation)
708		return;
709
710	*pcount = pps->capcount;
711	(*pseq)++;
712	*tsp = ts;
713
714	if (foff) {
715		timespecadd(tsp, osp);
716		if (tsp->tv_nsec < 0) {
717			tsp->tv_nsec += 1000000000;
718			tsp->tv_sec -= 1;
719		}
720	}
721#ifdef PPS_SYNC
722	if (fhard) {
723		u_int64_t scale;
724
725		/*
726		 * Feed the NTP PLL/FLL.
727		 * The FLL wants to know how many (hardware) nanoseconds
728		 * elapsed since the previous event.
729		 */
730		tcount = pps->capcount - pps->ppscount[2];
731		pps->ppscount[2] = pps->capcount;
732		tcount &= pps->capth->th_counter->tc_counter_mask;
733		scale = (u_int64_t)1 << 63;
734		scale /= pps->capth->th_counter->tc_frequency;
735		scale *= 2;
736		bt.sec = 0;
737		bt.frac = 0;
738		bintime_addx(&bt, scale * tcount);
739		bintime2timespec(&bt, &ts);
740		hardpps(tsp, ts.tv_nsec + 1000000000 * ts.tv_sec);
741	}
742#endif
743}
744
745/*
746 * Timecounters need to be updated every so often to prevent the hardware
747 * counter from overflowing.  Updating also recalculates the cached values
748 * used by the get*() family of functions, so their precision depends on
749 * the update frequency.
750 */
751
752static int tc_tick;
753SYSCTL_INT(_kern_timecounter, OID_AUTO, tick, CTLFLAG_RD, &tc_tick, 0, "");
754
755void
756tc_ticktock(void)
757{
758	static int count;
759	static time_t last_calib;
760
761	if (++count < tc_tick)
762		return;
763	count = 0;
764	tc_windup();
765	if (time_uptime != last_calib && !(time_uptime & 0xf)) {
766		cpu_tick_calibrate(0);
767		last_calib = time_uptime;
768	}
769}
770
771static void
772inittimecounter(void *dummy)
773{
774	u_int p;
775
776	/*
777	 * Set the initial timeout to
778	 * max(1, <approx. number of hardclock ticks in a millisecond>).
779	 * People should probably not use the sysctl to set the timeout
780	 * to smaller than its inital value, since that value is the
781	 * smallest reasonable one.  If they want better timestamps they
782	 * should use the non-"get"* functions.
783	 */
784	if (hz > 1000)
785		tc_tick = (hz + 500) / 1000;
786	else
787		tc_tick = 1;
788	p = (tc_tick * 1000000) / hz;
789	printf("Timecounters tick every %d.%03u msec\n", p / 1000, p % 1000);
790
791	/* warm up new timecounter (again) and get rolling. */
792	(void)timecounter->tc_get_timecount(timecounter);
793	(void)timecounter->tc_get_timecount(timecounter);
794}
795
796SYSINIT(timecounter, SI_SUB_CLOCKS, SI_ORDER_SECOND, inittimecounter, NULL)
797
798/* Cpu tick handling -------------------------------------------------*/
799
800static int cpu_tick_variable;
801static uint64_t	cpu_tick_frequency;
802
803static
804uint64_t
805tc_cpu_ticks(void)
806{
807	static uint64_t base;
808	static unsigned last;
809	unsigned u;
810	struct timecounter *tc;
811
812	tc = timehands->th_counter;
813	u = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
814	if (u < last)
815		base += tc->tc_counter_mask + 1;
816	last = u;
817	return (u + base);
818}
819
820/*
821 * This function gets called ever 16 seconds on only one designated
822 * CPU in the system from hardclock() via tc_ticktock().
823 *
824 * Whenever the real time clock is stepped we get called with reset=1
825 * to make sure we handle suspend/resume and similar events correctly.
826 */
827
828static void
829cpu_tick_calibrate(int reset)
830{
831	static uint64_t c_last;
832	uint64_t c_this, c_delta;
833	static struct bintime  t_last;
834	struct bintime t_this, t_delta;
835	uint32_t divi;
836
837	if (reset) {
838		/* The clock was stepped, abort & reset */
839		t_last.sec = 0;
840		return;
841	}
842
843	/* we don't calibrate fixed rate cputicks */
844	if (!cpu_tick_variable)
845		return;
846
847	getbinuptime(&t_this);
848	c_this = cpu_ticks();
849	if (t_last.sec != 0) {
850		c_delta = c_this - c_last;
851		t_delta = t_this;
852		bintime_sub(&t_delta, &t_last);
853		if (bootverbose) {
854			printf("%ju.%016jx ",
855			    (uintmax_t)t_delta.sec, (uintmax_t)t_delta.frac);
856		}
857		/*
858		 * Validate that 16 +/- 1/256 seconds passed.
859		 * After division by 16 this gives us a precision of
860		 * roughly 250PPM which is sufficient
861		 */
862		if (t_delta.sec > 16 || (
863		    t_delta.sec == 16 && t_delta.frac >= (0x01LL << 56))) {
864			/* too long */
865			if (bootverbose)
866				printf("\ttoo long\n");
867		} else if (t_delta.sec < 15 ||
868		    (t_delta.sec == 15 && t_delta.frac <= (0xffLL << 56))) {
869			/* too short */
870			if (bootverbose)
871				printf("\ttoo short\n");
872		} else {
873			/* just right */
874			/*
875			 * Headroom:
876			 * 	2^(64-20) / 16[s] =
877			 * 	2^(44) / 16[s] =
878			 * 	17.592.186.044.416 / 16 =
879			 * 	1.099.511.627.776 [Hz]
880			 */
881			divi = t_delta.sec << 20;
882			divi |= t_delta.frac >> (64 - 20);
883			c_delta <<= 20;
884			if (bootverbose)
885				printf(" %ju / %ju",
886				    (uintmax_t)c_delta, (uintmax_t)divi);
887			c_delta /= divi;
888			if (bootverbose)
889				printf(" = %ju", c_delta);
890			if (c_delta  > cpu_tick_frequency) {
891				if (bootverbose)
892					printf("\thigher\n");
893				cpu_tick_frequency = c_delta;
894			} else {
895				if (bootverbose)
896					printf("\tlower\n");
897			}
898		}
899	}
900	c_last = c_this;
901	t_last = t_this;
902}
903
904void
905set_cputicker(cpu_tick_f *func, uint64_t freq, unsigned var)
906{
907
908	if (func == NULL) {
909		cpu_ticks = tc_cpu_ticks;
910	} else {
911		cpu_tick_frequency = freq;
912		cpu_tick_variable = var;
913		cpu_ticks = func;
914	}
915}
916
917uint64_t
918cpu_tickrate(void)
919{
920
921	if (cpu_ticks == tc_cpu_ticks)
922		return (tc_getfrequency());
923	return (cpu_tick_frequency);
924}
925
926/*
927 * We need to be slightly careful converting cputicks to microseconds.
928 * There is plenty of margin in 64 bits of microseconds (half a million
929 * years) and in 64 bits at 4 GHz (146 years), but if we do a multiply
930 * before divide conversion (to retain precision) we find that the
931 * margin shrinks to 1.5 hours (one millionth of 146y).
932 * With a three prong approach we never loose significant bits, no
933 * matter what the cputick rate and length of timeinterval is.
934 */
935
936uint64_t
937cputick2usec(uint64_t tick)
938{
939
940	if (tick > 18446744073709551LL)		/* floor(2^64 / 1000) */
941		return (tick / (cpu_tickrate() / 1000000LL));
942	else if (tick > 18446744073709LL)	/* floor(2^64 / 1000000) */
943		return ((tick * 1000LL) / (cpu_tickrate() / 1000LL));
944	else
945		return ((tick * 1000000LL) / cpu_tickrate());
946}
947
948cpu_tick_f	*cpu_ticks = tc_cpu_ticks;
949