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