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