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