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