Home | History | Annotate | Line # | Download | only in kern
kern_tc.c revision 1.27.6.2
      1 /* $NetBSD: kern_tc.c,v 1.27.6.2 2008/01/08 22:11:37 bouyer 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.27.6.2 2008/01/08 22:11:37 bouyer Exp $");
     15 
     16 #include "opt_ntp.h"
     17 
     18 #include <sys/param.h>
     19 #ifdef __HAVE_TIMECOUNTER	/* XXX */
     20 #include <sys/kernel.h>
     21 #include <sys/reboot.h>	/* XXX just to get AB_VERBOSE */
     22 #include <sys/sysctl.h>
     23 #include <sys/syslog.h>
     24 #include <sys/systm.h>
     25 #include <sys/timepps.h>
     26 #include <sys/timetc.h>
     27 #include <sys/timex.h>
     28 #include <sys/evcnt.h>
     29 #include <sys/kauth.h>
     30 #include <sys/mutex.h>
     31 #include <sys/atomic.h>
     32 
     33 /*
     34  * A large step happens on boot.  This constant detects such steps.
     35  * It is relatively small so that ntp_update_second gets called enough
     36  * in the typical 'missed a couple of seconds' case, but doesn't loop
     37  * forever when the time step is large.
     38  */
     39 #define LARGE_STEP	200
     40 
     41 /*
     42  * Implement a dummy timecounter which we can use until we get a real one
     43  * in the air.  This allows the console and other early stuff to use
     44  * time services.
     45  */
     46 
     47 static u_int
     48 dummy_get_timecount(struct timecounter *tc)
     49 {
     50 	static u_int now;
     51 
     52 	return (++now);
     53 }
     54 
     55 static struct timecounter dummy_timecounter = {
     56 	dummy_get_timecount, 0, ~0u, 1000000, "dummy", -1000000, NULL, NULL,
     57 };
     58 
     59 struct timehands {
     60 	/* These fields must be initialized by the driver. */
     61 	struct timecounter	*th_counter;
     62 	int64_t			th_adjustment;
     63 	u_int64_t		th_scale;
     64 	u_int	 		th_offset_count;
     65 	struct bintime		th_offset;
     66 	struct timeval		th_microtime;
     67 	struct timespec		th_nanotime;
     68 	/* Fields not to be copied in tc_windup start with th_generation. */
     69 	volatile u_int		th_generation;
     70 	struct timehands	*th_next;
     71 };
     72 
     73 static struct timehands th0;
     74 static struct timehands th9 = { .th_next = &th0, };
     75 static struct timehands th8 = { .th_next = &th9, };
     76 static struct timehands th7 = { .th_next = &th8, };
     77 static struct timehands th6 = { .th_next = &th7, };
     78 static struct timehands th5 = { .th_next = &th6, };
     79 static struct timehands th4 = { .th_next = &th5, };
     80 static struct timehands th3 = { .th_next = &th4, };
     81 static struct timehands th2 = { .th_next = &th3, };
     82 static struct timehands th1 = { .th_next = &th2, };
     83 static struct timehands th0 = {
     84 	.th_counter = &dummy_timecounter,
     85 	.th_scale = (uint64_t)-1 / 1000000,
     86 	.th_offset = { .sec = 1, .frac = 0 },
     87 	.th_generation = 1,
     88 	.th_next = &th1,
     89 };
     90 
     91 static struct timehands *volatile timehands = &th0;
     92 struct timecounter *timecounter = &dummy_timecounter;
     93 static struct timecounter *timecounters = &dummy_timecounter;
     94 
     95 time_t time_second = 1;
     96 time_t time_uptime = 1;
     97 
     98 static struct bintime timebasebin;
     99 
    100 static int timestepwarnings;
    101 
    102 extern kmutex_t time_lock;
    103 static kmutex_t tc_windup_lock;
    104 
    105 #ifdef __FreeBSD__
    106 SYSCTL_INT(_kern_timecounter, OID_AUTO, stepwarnings, CTLFLAG_RW,
    107     &timestepwarnings, 0, "");
    108 #endif /* __FreeBSD__ */
    109 
    110 /*
    111  * sysctl helper routine for kern.timercounter.hardware
    112  */
    113 static int
    114 sysctl_kern_timecounter_hardware(SYSCTLFN_ARGS)
    115 {
    116 	struct sysctlnode node;
    117 	int error;
    118 	char newname[MAX_TCNAMELEN];
    119 	struct timecounter *newtc, *tc;
    120 
    121 	tc = timecounter;
    122 
    123 	strlcpy(newname, tc->tc_name, sizeof(newname));
    124 
    125 	node = *rnode;
    126 	node.sysctl_data = newname;
    127 	node.sysctl_size = sizeof(newname);
    128 
    129 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    130 
    131 	if (error ||
    132 	    newp == NULL ||
    133 	    strncmp(newname, tc->tc_name, sizeof(newname)) == 0)
    134 		return error;
    135 
    136 	if (l != NULL && (error = kauth_authorize_system(l->l_cred,
    137 	    KAUTH_SYSTEM_TIME, KAUTH_REQ_SYSTEM_TIME_TIMECOUNTERS, newname,
    138 	    NULL, NULL)) != 0)
    139 		return (error);
    140 
    141 	if (!cold)
    142 		mutex_enter(&time_lock);
    143 	error = EINVAL;
    144 	for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
    145 		if (strcmp(newname, newtc->tc_name) != 0)
    146 			continue;
    147 		/* Warm up new timecounter. */
    148 		(void)newtc->tc_get_timecount(newtc);
    149 		(void)newtc->tc_get_timecount(newtc);
    150 		timecounter = newtc;
    151 		error = 0;
    152 		break;
    153 	}
    154 	if (!cold)
    155 		mutex_exit(&time_lock);
    156 	return error;
    157 }
    158 
    159 static int
    160 sysctl_kern_timecounter_choice(SYSCTLFN_ARGS)
    161 {
    162 	char buf[MAX_TCNAMELEN+48];
    163 	char *where = oldp;
    164 	const char *spc;
    165 	struct timecounter *tc;
    166 	size_t needed, left, slen;
    167 	int error;
    168 
    169 	if (newp != NULL)
    170 		return (EPERM);
    171 	if (namelen != 0)
    172 		return (EINVAL);
    173 
    174 	spc = "";
    175 	error = 0;
    176 	needed = 0;
    177 	left = *oldlenp;
    178 
    179 	mutex_enter(&time_lock);
    180 	for (tc = timecounters; error == 0 && tc != NULL; tc = tc->tc_next) {
    181 		if (where == NULL) {
    182 			needed += sizeof(buf);  /* be conservative */
    183 		} else {
    184 			slen = snprintf(buf, sizeof(buf), "%s%s(q=%d, f=%" PRId64
    185 					" Hz)", spc, tc->tc_name, tc->tc_quality,
    186 					tc->tc_frequency);
    187 			if (left < slen + 1)
    188 				break;
    189 			/* XXX use sysctl_copyout? (from sysctl_hw_disknames) */
    190 			/* XXX copyout with held lock. */
    191 			error = copyout(buf, where, slen + 1);
    192 			spc = " ";
    193 			where += slen;
    194 			needed += slen;
    195 			left -= slen;
    196 		}
    197 	}
    198 	mutex_exit(&time_lock);
    199 
    200 	*oldlenp = needed;
    201 	return (error);
    202 }
    203 
    204 SYSCTL_SETUP(sysctl_timecounter_setup, "sysctl timecounter setup")
    205 {
    206 	const struct sysctlnode *node;
    207 
    208 	sysctl_createv(clog, 0, NULL, &node,
    209 		       CTLFLAG_PERMANENT,
    210 		       CTLTYPE_NODE, "timecounter",
    211 		       SYSCTL_DESCR("time counter information"),
    212 		       NULL, 0, NULL, 0,
    213 		       CTL_KERN, CTL_CREATE, CTL_EOL);
    214 
    215 	if (node != NULL) {
    216 		sysctl_createv(clog, 0, NULL, NULL,
    217 			       CTLFLAG_PERMANENT,
    218 			       CTLTYPE_STRING, "choice",
    219 			       SYSCTL_DESCR("available counters"),
    220 			       sysctl_kern_timecounter_choice, 0, NULL, 0,
    221 			       CTL_KERN, node->sysctl_num, CTL_CREATE, CTL_EOL);
    222 
    223 		sysctl_createv(clog, 0, NULL, NULL,
    224 			       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    225 			       CTLTYPE_STRING, "hardware",
    226 			       SYSCTL_DESCR("currently active time counter"),
    227 			       sysctl_kern_timecounter_hardware, 0, NULL, MAX_TCNAMELEN,
    228 			       CTL_KERN, node->sysctl_num, CTL_CREATE, CTL_EOL);
    229 
    230 		sysctl_createv(clog, 0, NULL, NULL,
    231 			       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    232 			       CTLTYPE_INT, "timestepwarnings",
    233 			       SYSCTL_DESCR("log time steps"),
    234 			       NULL, 0, &timestepwarnings, 0,
    235 			       CTL_KERN, node->sysctl_num, CTL_CREATE, CTL_EOL);
    236 	}
    237 }
    238 
    239 #define	TC_STATS(name)							\
    240 static struct evcnt n##name =						\
    241     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "timecounter", #name);	\
    242 EVCNT_ATTACH_STATIC(n##name)
    243 
    244 TC_STATS(binuptime);    TC_STATS(nanouptime);    TC_STATS(microuptime);
    245 TC_STATS(bintime);      TC_STATS(nanotime);      TC_STATS(microtime);
    246 TC_STATS(getbinuptime); TC_STATS(getnanouptime); TC_STATS(getmicrouptime);
    247 TC_STATS(getbintime);   TC_STATS(getnanotime);   TC_STATS(getmicrotime);
    248 TC_STATS(setclock);
    249 
    250 #undef TC_STATS
    251 
    252 static void tc_windup(void);
    253 
    254 /*
    255  * Return the difference between the timehands' counter value now and what
    256  * was when we copied it to the timehands' offset_count.
    257  */
    258 static __inline u_int
    259 tc_delta(struct timehands *th)
    260 {
    261 	struct timecounter *tc;
    262 
    263 	tc = th->th_counter;
    264 	return ((tc->tc_get_timecount(tc) -
    265 		 th->th_offset_count) & tc->tc_counter_mask);
    266 }
    267 
    268 /*
    269  * Functions for reading the time.  We have to loop until we are sure that
    270  * the timehands that we operated on was not updated under our feet.  See
    271  * the comment in <sys/timevar.h> for a description of these 12 functions.
    272  */
    273 
    274 void
    275 binuptime(struct bintime *bt)
    276 {
    277 	struct timehands *th;
    278 	u_int gen;
    279 
    280 	nbinuptime.ev_count++;
    281 	do {
    282 		th = timehands;
    283 		gen = th->th_generation;
    284 		*bt = th->th_offset;
    285 		bintime_addx(bt, th->th_scale * tc_delta(th));
    286 	} while (gen == 0 || gen != th->th_generation);
    287 }
    288 
    289 void
    290 nanouptime(struct timespec *tsp)
    291 {
    292 	struct bintime bt;
    293 
    294 	nnanouptime.ev_count++;
    295 	binuptime(&bt);
    296 	bintime2timespec(&bt, tsp);
    297 }
    298 
    299 void
    300 microuptime(struct timeval *tvp)
    301 {
    302 	struct bintime bt;
    303 
    304 	nmicrouptime.ev_count++;
    305 	binuptime(&bt);
    306 	bintime2timeval(&bt, tvp);
    307 }
    308 
    309 void
    310 bintime(struct bintime *bt)
    311 {
    312 
    313 	nbintime.ev_count++;
    314 	binuptime(bt);
    315 	bintime_add(bt, &timebasebin);
    316 }
    317 
    318 void
    319 nanotime(struct timespec *tsp)
    320 {
    321 	struct bintime bt;
    322 
    323 	nnanotime.ev_count++;
    324 	bintime(&bt);
    325 	bintime2timespec(&bt, tsp);
    326 }
    327 
    328 void
    329 microtime(struct timeval *tvp)
    330 {
    331 	struct bintime bt;
    332 
    333 	nmicrotime.ev_count++;
    334 	bintime(&bt);
    335 	bintime2timeval(&bt, tvp);
    336 }
    337 
    338 void
    339 getbinuptime(struct bintime *bt)
    340 {
    341 	struct timehands *th;
    342 	u_int gen;
    343 
    344 	ngetbinuptime.ev_count++;
    345 	do {
    346 		th = timehands;
    347 		gen = th->th_generation;
    348 		*bt = th->th_offset;
    349 	} while (gen == 0 || gen != th->th_generation);
    350 }
    351 
    352 void
    353 getnanouptime(struct timespec *tsp)
    354 {
    355 	struct timehands *th;
    356 	u_int gen;
    357 
    358 	ngetnanouptime.ev_count++;
    359 	do {
    360 		th = timehands;
    361 		gen = th->th_generation;
    362 		bintime2timespec(&th->th_offset, tsp);
    363 	} while (gen == 0 || gen != th->th_generation);
    364 }
    365 
    366 void
    367 getmicrouptime(struct timeval *tvp)
    368 {
    369 	struct timehands *th;
    370 	u_int gen;
    371 
    372 	ngetmicrouptime.ev_count++;
    373 	do {
    374 		th = timehands;
    375 		gen = th->th_generation;
    376 		bintime2timeval(&th->th_offset, tvp);
    377 	} while (gen == 0 || gen != th->th_generation);
    378 }
    379 
    380 void
    381 getbintime(struct bintime *bt)
    382 {
    383 	struct timehands *th;
    384 	u_int gen;
    385 
    386 	ngetbintime.ev_count++;
    387 	do {
    388 		th = timehands;
    389 		gen = th->th_generation;
    390 		*bt = th->th_offset;
    391 	} while (gen == 0 || gen != th->th_generation);
    392 	bintime_add(bt, &timebasebin);
    393 }
    394 
    395 void
    396 getnanotime(struct timespec *tsp)
    397 {
    398 	struct timehands *th;
    399 	u_int gen;
    400 
    401 	ngetnanotime.ev_count++;
    402 	do {
    403 		th = timehands;
    404 		gen = th->th_generation;
    405 		*tsp = th->th_nanotime;
    406 	} while (gen == 0 || gen != th->th_generation);
    407 }
    408 
    409 void
    410 getmicrotime(struct timeval *tvp)
    411 {
    412 	struct timehands *th;
    413 	u_int gen;
    414 
    415 	ngetmicrotime.ev_count++;
    416 	do {
    417 		th = timehands;
    418 		gen = th->th_generation;
    419 		*tvp = th->th_microtime;
    420 	} while (gen == 0 || gen != th->th_generation);
    421 }
    422 
    423 /*
    424  * Initialize a new timecounter and possibly use it.
    425  */
    426 void
    427 tc_init(struct timecounter *tc)
    428 {
    429 	u_int u;
    430 
    431 	u = tc->tc_frequency / tc->tc_counter_mask;
    432 	/* XXX: We need some margin here, 10% is a guess */
    433 	u *= 11;
    434 	u /= 10;
    435 	if (u > hz && tc->tc_quality >= 0) {
    436 		tc->tc_quality = -2000;
    437 		aprint_verbose(
    438 		    "timecounter: Timecounter \"%s\" frequency %ju Hz",
    439 			    tc->tc_name, (uintmax_t)tc->tc_frequency);
    440 		aprint_verbose(" -- Insufficient hz, needs at least %u\n", u);
    441 	} else if (tc->tc_quality >= 0 || bootverbose) {
    442 		aprint_verbose(
    443 		    "timecounter: Timecounter \"%s\" frequency %ju Hz "
    444 		    "quality %d\n", tc->tc_name, (uintmax_t)tc->tc_frequency,
    445 		    tc->tc_quality);
    446 	}
    447 
    448 	mutex_enter(&time_lock);
    449 	mutex_spin_enter(&tc_windup_lock);
    450 	tc->tc_next = timecounters;
    451 	timecounters = tc;
    452 	/*
    453 	 * Never automatically use a timecounter with negative quality.
    454 	 * Even though we run on the dummy counter, switching here may be
    455 	 * worse since this timecounter may not be monotonous.
    456 	 */
    457 	if (tc->tc_quality >= 0 && (tc->tc_quality > timecounter->tc_quality ||
    458 	    (tc->tc_quality == timecounter->tc_quality &&
    459 	    tc->tc_frequency > timecounter->tc_frequency))) {
    460 		(void)tc->tc_get_timecount(tc);
    461 		(void)tc->tc_get_timecount(tc);
    462 		timecounter = tc;
    463 		tc_windup();
    464 	}
    465 	mutex_spin_exit(&tc_windup_lock);
    466 	mutex_exit(&time_lock);
    467 }
    468 
    469 /*
    470  * Stop using a timecounter and remove it from the timecounters list.
    471  */
    472 int
    473 tc_detach(struct timecounter *target)
    474 {
    475 	struct timecounter *best, *tc;
    476 	struct timecounter **tcp = NULL;
    477 	int rc = 0;
    478 
    479 	mutex_enter(&time_lock);
    480 	for (tcp = &timecounters, tc = timecounters;
    481 	     tc != NULL;
    482 	     tcp = &tc->tc_next, tc = tc->tc_next) {
    483 		if (tc == target)
    484 			break;
    485 	}
    486 	if (tc == NULL) {
    487 		rc = ESRCH;
    488 		goto out;
    489 	}
    490 	*tcp = tc->tc_next;
    491 
    492 	if (timecounter != target)
    493 		goto out;
    494 
    495 	for (best = tc = timecounters; tc != NULL; tc = tc->tc_next) {
    496 		if (tc->tc_quality > best->tc_quality)
    497 			best = tc;
    498 		else if (tc->tc_quality < best->tc_quality)
    499 			continue;
    500 		else if (tc->tc_frequency > best->tc_frequency)
    501 			best = tc;
    502 	}
    503 	mutex_spin_enter(&tc_windup_lock);
    504 	(void)best->tc_get_timecount(best);
    505 	(void)best->tc_get_timecount(best);
    506 	timecounter = best;
    507 	tc_windup();
    508 	mutex_spin_exit(&tc_windup_lock);
    509 out:
    510 	mutex_exit(&time_lock);
    511 	return rc;
    512 }
    513 
    514 /* Report the frequency of the current timecounter. */
    515 u_int64_t
    516 tc_getfrequency(void)
    517 {
    518 
    519 	return (timehands->th_counter->tc_frequency);
    520 }
    521 
    522 /*
    523  * Step our concept of UTC.  This is done by modifying our estimate of
    524  * when we booted.
    525  */
    526 void
    527 tc_setclock(struct timespec *ts)
    528 {
    529 	struct timespec ts2;
    530 	struct bintime bt, bt2;
    531 
    532 	mutex_spin_enter(&tc_windup_lock);
    533 	nsetclock.ev_count++;
    534 	binuptime(&bt2);
    535 	timespec2bintime(ts, &bt);
    536 	bintime_sub(&bt, &bt2);
    537 	bintime_add(&bt2, &timebasebin);
    538 	timebasebin = bt;
    539 	tc_windup();
    540 	mutex_spin_exit(&tc_windup_lock);
    541 
    542 	if (timestepwarnings) {
    543 		bintime2timespec(&bt2, &ts2);
    544 		log(LOG_INFO, "Time stepped from %jd.%09ld to %jd.%09ld\n",
    545 		    (intmax_t)ts2.tv_sec, ts2.tv_nsec,
    546 		    (intmax_t)ts->tv_sec, ts->tv_nsec);
    547 	}
    548 }
    549 
    550 /*
    551  * Initialize the next struct timehands in the ring and make
    552  * it the active timehands.  Along the way we might switch to a different
    553  * timecounter and/or do seconds processing in NTP.  Slightly magic.
    554  */
    555 static void
    556 tc_windup(void)
    557 {
    558 	struct bintime bt;
    559 	struct timehands *th, *tho;
    560 	u_int64_t scale;
    561 	u_int delta, ncount, ogen;
    562 	int i, s_update;
    563 	time_t t;
    564 
    565 	KASSERT(mutex_owned(&tc_windup_lock));
    566 
    567 	s_update = 0;
    568 
    569 	/*
    570 	 * Make the next timehands a copy of the current one, but do not
    571 	 * overwrite the generation or next pointer.  While we update
    572 	 * the contents, the generation must be zero.  Ensure global
    573 	 * visibility of the generation before proceeding.
    574 	 */
    575 	tho = timehands;
    576 	th = tho->th_next;
    577 	ogen = th->th_generation;
    578 	th->th_generation = 0;
    579 	membar_producer();
    580 	bcopy(tho, th, offsetof(struct timehands, th_generation));
    581 
    582 	/*
    583 	 * Capture a timecounter delta on the current timecounter and if
    584 	 * changing timecounters, a counter value from the new timecounter.
    585 	 * Update the offset fields accordingly.
    586 	 */
    587 	delta = tc_delta(th);
    588 	if (th->th_counter != timecounter)
    589 		ncount = timecounter->tc_get_timecount(timecounter);
    590 	else
    591 		ncount = 0;
    592 	th->th_offset_count += delta;
    593 	th->th_offset_count &= th->th_counter->tc_counter_mask;
    594 	bintime_addx(&th->th_offset, th->th_scale * delta);
    595 
    596 	/*
    597 	 * Hardware latching timecounters may not generate interrupts on
    598 	 * PPS events, so instead we poll them.  There is a finite risk that
    599 	 * the hardware might capture a count which is later than the one we
    600 	 * got above, and therefore possibly in the next NTP second which might
    601 	 * have a different rate than the current NTP second.  It doesn't
    602 	 * matter in practice.
    603 	 */
    604 	if (tho->th_counter->tc_poll_pps)
    605 		tho->th_counter->tc_poll_pps(tho->th_counter);
    606 
    607 	/*
    608 	 * Deal with NTP second processing.  The for loop normally
    609 	 * iterates at most once, but in extreme situations it might
    610 	 * keep NTP sane if timeouts are not run for several seconds.
    611 	 * At boot, the time step can be large when the TOD hardware
    612 	 * has been read, so on really large steps, we call
    613 	 * ntp_update_second only twice.  We need to call it twice in
    614 	 * case we missed a leap second.
    615 	 * If NTP is not compiled in ntp_update_second still calculates
    616 	 * the adjustment resulting from adjtime() calls.
    617 	 */
    618 	bt = th->th_offset;
    619 	bintime_add(&bt, &timebasebin);
    620 	i = bt.sec - tho->th_microtime.tv_sec;
    621 	if (i > LARGE_STEP)
    622 		i = 2;
    623 	for (; i > 0; i--) {
    624 		t = bt.sec;
    625 		ntp_update_second(&th->th_adjustment, &bt.sec);
    626 		s_update = 1;
    627 		if (bt.sec != t)
    628 			timebasebin.sec += bt.sec - t;
    629 	}
    630 
    631 	/* Update the UTC timestamps used by the get*() functions. */
    632 	/* XXX shouldn't do this here.  Should force non-`get' versions. */
    633 	bintime2timeval(&bt, &th->th_microtime);
    634 	bintime2timespec(&bt, &th->th_nanotime);
    635 
    636 	/* Now is a good time to change timecounters. */
    637 	if (th->th_counter != timecounter) {
    638 		th->th_counter = timecounter;
    639 		th->th_offset_count = ncount;
    640 		s_update = 1;
    641 	}
    642 
    643 	/*-
    644 	 * Recalculate the scaling factor.  We want the number of 1/2^64
    645 	 * fractions of a second per period of the hardware counter, taking
    646 	 * into account the th_adjustment factor which the NTP PLL/adjtime(2)
    647 	 * processing provides us with.
    648 	 *
    649 	 * The th_adjustment is nanoseconds per second with 32 bit binary
    650 	 * fraction and we want 64 bit binary fraction of second:
    651 	 *
    652 	 *	 x = a * 2^32 / 10^9 = a * 4.294967296
    653 	 *
    654 	 * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
    655 	 * we can only multiply by about 850 without overflowing, but that
    656 	 * leaves suitably precise fractions for multiply before divide.
    657 	 *
    658 	 * Divide before multiply with a fraction of 2199/512 results in a
    659 	 * systematic undercompensation of 10PPM of th_adjustment.  On a
    660 	 * 5000PPM adjustment this is a 0.05PPM error.  This is acceptable.
    661  	 *
    662 	 * We happily sacrifice the lowest of the 64 bits of our result
    663 	 * to the goddess of code clarity.
    664 	 *
    665 	 */
    666 	if (s_update) {
    667 		scale = (u_int64_t)1 << 63;
    668 		scale += (th->th_adjustment / 1024) * 2199;
    669 		scale /= th->th_counter->tc_frequency;
    670 		th->th_scale = scale * 2;
    671 	}
    672 	/*
    673 	 * Now that the struct timehands is again consistent, set the new
    674 	 * generation number, making sure to not make it zero.  Ensure
    675 	 * changes are globally visible before changing.
    676 	 */
    677 	if (++ogen == 0)
    678 		ogen = 1;
    679 	membar_producer();
    680 	th->th_generation = ogen;
    681 
    682 	/*
    683 	 * Go live with the new struct timehands.  Ensure changes are
    684 	 * globally visible before changing.
    685 	 */
    686 	time_second = th->th_microtime.tv_sec;
    687 	time_uptime = th->th_offset.sec;
    688 	membar_producer();
    689 	timehands = th;
    690 
    691 	/*
    692 	 * Force users of the old timehand to move on.  This is
    693 	 * necessary for MP systems; we need to ensure that the
    694 	 * consumers will move away from the old timehand before
    695 	 * we begin updating it again when we eventually wrap
    696 	 * around.
    697 	 */
    698 	if (++tho->th_generation == 0)
    699 		tho->th_generation = 1;
    700 }
    701 
    702 /*
    703  * RFC 2783 PPS-API implementation.
    704  */
    705 
    706 int
    707 pps_ioctl(u_long cmd, void *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 
    878 void
    879 tc_ticktock(void)
    880 {
    881 	static int count;
    882 
    883 	if (++count < tc_tick)
    884 		return;
    885 	count = 0;
    886 	mutex_spin_enter(&tc_windup_lock);
    887 	tc_windup();
    888 	mutex_spin_exit(&tc_windup_lock);
    889 }
    890 
    891 void
    892 inittimecounter(void)
    893 {
    894 	u_int p;
    895 
    896 	mutex_init(&tc_windup_lock, MUTEX_DEFAULT, IPL_SCHED);
    897 
    898 	/*
    899 	 * Set the initial timeout to
    900 	 * max(1, <approx. number of hardclock ticks in a millisecond>).
    901 	 * People should probably not use the sysctl to set the timeout
    902 	 * to smaller than its inital value, since that value is the
    903 	 * smallest reasonable one.  If they want better timestamps they
    904 	 * should use the non-"get"* functions.
    905 	 */
    906 	if (hz > 1000)
    907 		tc_tick = (hz + 500) / 1000;
    908 	else
    909 		tc_tick = 1;
    910 	p = (tc_tick * 1000000) / hz;
    911 	aprint_verbose("timecounter: Timecounters tick every %d.%03u msec\n",
    912 	    p / 1000, p % 1000);
    913 
    914 	/* warm up new timecounter (again) and get rolling. */
    915 	(void)timecounter->tc_get_timecount(timecounter);
    916 	(void)timecounter->tc_get_timecount(timecounter);
    917 }
    918 
    919 #endif /* __HAVE_TIMECOUNTER */
    920