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