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