xref: /openbsd-src/sys/kern/kern_tc.c (revision 0d88cff5397f65b7fee068981b08d234c688e143)
1 /*	$OpenBSD: kern_tc.c,v 1.59 2020/06/26 18:48:31 cheloha Exp $ */
2 
3 /*
4  * Copyright (c) 2000 Poul-Henning Kamp <phk@FreeBSD.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 /*
20  * If we meet some day, and you think this stuff is worth it, you
21  * can buy me a beer in return. Poul-Henning Kamp
22  */
23 
24 #include <sys/param.h>
25 #include <sys/atomic.h>
26 #include <sys/kernel.h>
27 #include <sys/mutex.h>
28 #include <sys/rwlock.h>
29 #include <sys/stdint.h>
30 #include <sys/timeout.h>
31 #include <sys/sysctl.h>
32 #include <sys/syslog.h>
33 #include <sys/systm.h>
34 #include <sys/timetc.h>
35 #include <sys/queue.h>
36 #include <sys/malloc.h>
37 
38 /*
39  * A large step happens on boot.  This constant detects such steps.
40  * It is relatively small so that ntp_update_second gets called enough
41  * in the typical 'missed a couple of seconds' case, but doesn't loop
42  * forever when the time step is large.
43  */
44 #define LARGE_STEP	200
45 
46 u_int dummy_get_timecount(struct timecounter *);
47 
48 int sysctl_tc_hardware(void *, size_t *, void *, size_t);
49 int sysctl_tc_choice(void *, size_t *, void *, size_t);
50 
51 /*
52  * Implement a dummy timecounter which we can use until we get a real one
53  * in the air.  This allows the console and other early stuff to use
54  * time services.
55  */
56 
57 u_int
58 dummy_get_timecount(struct timecounter *tc)
59 {
60 	static u_int now;
61 
62 	return (++now);
63 }
64 
65 static struct timecounter dummy_timecounter = {
66 	dummy_get_timecount, 0, ~0u, 1000000, "dummy", -1000000
67 };
68 
69 /*
70  * Locks used to protect struct members, global variables in this file:
71  *	I	immutable after initialization
72  *	t	tc_lock
73  *	w	windup_mtx
74  */
75 
76 struct timehands {
77 	/* These fields must be initialized by the driver. */
78 	struct timecounter	*th_counter;		/* [w] */
79 	int64_t			th_adjtimedelta;	/* [tw] */
80 	int64_t			th_adjustment;		/* [w] */
81 	u_int64_t		th_scale;		/* [w] */
82 	u_int	 		th_offset_count;	/* [w] */
83 	struct bintime		th_boottime;		/* [tw] */
84 	struct bintime		th_offset;		/* [w] */
85 	struct bintime		th_naptime;		/* [w] */
86 	struct timeval		th_microtime;		/* [w] */
87 	struct timespec		th_nanotime;		/* [w] */
88 	/* Fields not to be copied in tc_windup start with th_generation. */
89 	volatile u_int		th_generation;		/* [w] */
90 	struct timehands	*th_next;		/* [I] */
91 };
92 
93 static struct timehands th0;
94 static struct timehands th1 = {
95 	.th_next = &th0
96 };
97 static struct timehands th0 = {
98 	.th_counter = &dummy_timecounter,
99 	.th_scale = UINT64_MAX / 1000000,
100 	.th_offset = { .sec = 1, .frac = 0 },
101 	.th_generation = 1,
102 	.th_next = &th1
103 };
104 
105 struct rwlock tc_lock = RWLOCK_INITIALIZER("tc_lock");
106 
107 /*
108  * tc_windup() must be called before leaving this mutex.
109  */
110 struct mutex windup_mtx = MUTEX_INITIALIZER(IPL_CLOCK);
111 
112 static struct timehands *volatile timehands = &th0;		/* [w] */
113 struct timecounter *timecounter = &dummy_timecounter;		/* [t] */
114 static SLIST_HEAD(, timecounter) tc_list = SLIST_HEAD_INITIALIZER(tc_list);
115 
116 /*
117  * These are updated from tc_windup().  They are useful when
118  * examining kernel core dumps.
119  */
120 volatile time_t time_second = 1;
121 volatile time_t time_uptime = 0;
122 
123 static int timestepwarnings;
124 
125 void ntp_update_second(struct timehands *);
126 void tc_windup(struct bintime *, struct bintime *, int64_t *);
127 
128 /*
129  * Return the difference between the timehands' counter value now and what
130  * was when we copied it to the timehands' offset_count.
131  */
132 static __inline u_int
133 tc_delta(struct timehands *th)
134 {
135 	struct timecounter *tc;
136 
137 	tc = th->th_counter;
138 	return ((tc->tc_get_timecount(tc) - th->th_offset_count) &
139 	    tc->tc_counter_mask);
140 }
141 
142 /*
143  * Functions for reading the time.  We have to loop until we are sure that
144  * the timehands that we operated on was not updated under our feet.  See
145  * the comment in <sys/time.h> for a description of these functions.
146  */
147 
148 void
149 binboottime(struct bintime *bt)
150 {
151 	struct timehands *th;
152 	u_int gen;
153 
154 	do {
155 		th = timehands;
156 		gen = th->th_generation;
157 		membar_consumer();
158 		*bt = th->th_boottime;
159 		membar_consumer();
160 	} while (gen == 0 || gen != th->th_generation);
161 }
162 
163 void
164 microboottime(struct timeval *tvp)
165 {
166 	struct bintime bt;
167 
168 	binboottime(&bt);
169 	BINTIME_TO_TIMEVAL(&bt, tvp);
170 }
171 
172 void
173 nanoboottime(struct timespec *tsp)
174 {
175 	struct bintime bt;
176 
177 	binboottime(&bt);
178 	BINTIME_TO_TIMESPEC(&bt, tsp);
179 }
180 
181 void
182 binuptime(struct bintime *bt)
183 {
184 	struct timehands *th;
185 	u_int gen;
186 
187 	do {
188 		th = timehands;
189 		gen = th->th_generation;
190 		membar_consumer();
191 		*bt = th->th_offset;
192 		bintimeaddfrac(bt, th->th_scale * tc_delta(th), bt);
193 		membar_consumer();
194 	} while (gen == 0 || gen != th->th_generation);
195 }
196 
197 void
198 nanouptime(struct timespec *tsp)
199 {
200 	struct bintime bt;
201 
202 	binuptime(&bt);
203 	BINTIME_TO_TIMESPEC(&bt, tsp);
204 }
205 
206 void
207 microuptime(struct timeval *tvp)
208 {
209 	struct bintime bt;
210 
211 	binuptime(&bt);
212 	BINTIME_TO_TIMEVAL(&bt, tvp);
213 }
214 
215 time_t
216 getuptime(void)
217 {
218 #if defined(__LP64__)
219 	return time_uptime;	/* atomic */
220 #else
221 	time_t now;
222 	struct timehands *th;
223 	u_int gen;
224 
225 	do {
226 		th = timehands;
227 		gen = th->th_generation;
228 		membar_consumer();
229 		now = th->th_offset.sec;
230 		membar_consumer();
231 	} while (gen == 0 || gen != th->th_generation);
232 
233 	return now;
234 #endif
235 }
236 
237 void
238 binruntime(struct bintime *bt)
239 {
240 	struct timehands *th;
241 	u_int gen;
242 
243 	do {
244 		th = timehands;
245 		gen = th->th_generation;
246 		membar_consumer();
247 		bintimeaddfrac(&th->th_offset, th->th_scale * tc_delta(th), bt);
248 		bintimesub(bt, &th->th_naptime, bt);
249 		membar_consumer();
250 	} while (gen == 0 || gen != th->th_generation);
251 }
252 
253 void
254 nanoruntime(struct timespec *ts)
255 {
256 	struct bintime bt;
257 
258 	binruntime(&bt);
259 	BINTIME_TO_TIMESPEC(&bt, ts);
260 }
261 
262 void
263 bintime(struct bintime *bt)
264 {
265 	struct timehands *th;
266 	u_int gen;
267 
268 	do {
269 		th = timehands;
270 		gen = th->th_generation;
271 		membar_consumer();
272 		*bt = th->th_offset;
273 		bintimeaddfrac(bt, th->th_scale * tc_delta(th), bt);
274 		bintimeadd(bt, &th->th_boottime, bt);
275 		membar_consumer();
276 	} while (gen == 0 || gen != th->th_generation);
277 }
278 
279 void
280 nanotime(struct timespec *tsp)
281 {
282 	struct bintime bt;
283 
284 	bintime(&bt);
285 	BINTIME_TO_TIMESPEC(&bt, tsp);
286 }
287 
288 void
289 microtime(struct timeval *tvp)
290 {
291 	struct bintime bt;
292 
293 	bintime(&bt);
294 	BINTIME_TO_TIMEVAL(&bt, tvp);
295 }
296 
297 time_t
298 gettime(void)
299 {
300 #if defined(__LP64__)
301 	return time_second;	/* atomic */
302 #else
303 	time_t now;
304 	struct timehands *th;
305 	u_int gen;
306 
307 	do {
308 		th = timehands;
309 		gen = th->th_generation;
310 		membar_consumer();
311 		now = th->th_microtime.tv_sec;
312 		membar_consumer();
313 	} while (gen == 0 || gen != th->th_generation);
314 
315 	return now;
316 #endif
317 }
318 
319 void
320 getnanouptime(struct timespec *tsp)
321 {
322 	struct timehands *th;
323 	u_int gen;
324 
325 	do {
326 		th = timehands;
327 		gen = th->th_generation;
328 		membar_consumer();
329 		BINTIME_TO_TIMESPEC(&th->th_offset, tsp);
330 		membar_consumer();
331 	} while (gen == 0 || gen != th->th_generation);
332 }
333 
334 void
335 getmicrouptime(struct timeval *tvp)
336 {
337 	struct timehands *th;
338 	u_int gen;
339 
340 	do {
341 		th = timehands;
342 		gen = th->th_generation;
343 		membar_consumer();
344 		BINTIME_TO_TIMEVAL(&th->th_offset, tvp);
345 		membar_consumer();
346 	} while (gen == 0 || gen != th->th_generation);
347 }
348 
349 void
350 getnanotime(struct timespec *tsp)
351 {
352 	struct timehands *th;
353 	u_int gen;
354 
355 	do {
356 		th = timehands;
357 		gen = th->th_generation;
358 		membar_consumer();
359 		*tsp = th->th_nanotime;
360 		membar_consumer();
361 	} while (gen == 0 || gen != th->th_generation);
362 }
363 
364 void
365 getmicrotime(struct timeval *tvp)
366 {
367 	struct timehands *th;
368 	u_int gen;
369 
370 	do {
371 		th = timehands;
372 		gen = th->th_generation;
373 		membar_consumer();
374 		*tvp = th->th_microtime;
375 		membar_consumer();
376 	} while (gen == 0 || gen != th->th_generation);
377 }
378 
379 /*
380  * Initialize a new timecounter and possibly use it.
381  */
382 void
383 tc_init(struct timecounter *tc)
384 {
385 	u_int64_t tmp;
386 	u_int u;
387 
388 	u = tc->tc_frequency / tc->tc_counter_mask;
389 	/* XXX: We need some margin here, 10% is a guess */
390 	u *= 11;
391 	u /= 10;
392 	if (tc->tc_quality >= 0) {
393 		if (u > hz) {
394 			tc->tc_quality = -2000;
395 			printf("Timecounter \"%s\" frequency %lu Hz",
396 			    tc->tc_name, (unsigned long)tc->tc_frequency);
397 			printf(" -- Insufficient hz, needs at least %u\n", u);
398 		}
399 	}
400 
401 	/* Determine the counter's precision. */
402 	for (tmp = 1; (tmp & tc->tc_counter_mask) == 0; tmp <<= 1)
403 		continue;
404 	tc->tc_precision = tmp;
405 
406 	SLIST_INSERT_HEAD(&tc_list, tc, tc_next);
407 
408 	/*
409 	 * Never automatically use a timecounter with negative quality.
410 	 * Even though we run on the dummy counter, switching here may be
411 	 * worse since this timecounter may not be monotonic.
412 	 */
413 	if (tc->tc_quality < 0)
414 		return;
415 	if (tc->tc_quality < timecounter->tc_quality)
416 		return;
417 	if (tc->tc_quality == timecounter->tc_quality &&
418 	    tc->tc_frequency < timecounter->tc_frequency)
419 		return;
420 	(void)tc->tc_get_timecount(tc);
421 	enqueue_randomness(tc->tc_get_timecount(tc));
422 
423 	timecounter = tc;
424 }
425 
426 /* Report the frequency of the current timecounter. */
427 u_int64_t
428 tc_getfrequency(void)
429 {
430 	return (timehands->th_counter->tc_frequency);
431 }
432 
433 /* Report the precision of the current timecounter. */
434 u_int64_t
435 tc_getprecision(void)
436 {
437 	return (timehands->th_counter->tc_precision);
438 }
439 
440 /*
441  * Step our concept of UTC, aka the realtime clock.
442  * This is done by modifying our estimate of when we booted.
443  *
444  * Any ongoing adjustment is meaningless after a clock jump,
445  * so we zero adjtimedelta here as well.
446  */
447 void
448 tc_setrealtimeclock(const struct timespec *ts)
449 {
450 	struct timespec ts2;
451 	struct bintime bt, bt2;
452 	int64_t zero = 0;
453 
454 	rw_enter_write(&tc_lock);
455 	mtx_enter(&windup_mtx);
456 	binuptime(&bt2);
457 	TIMESPEC_TO_BINTIME(ts, &bt);
458 	bintimesub(&bt, &bt2, &bt);
459 	bintimeadd(&bt2, &timehands->th_boottime, &bt2);
460 
461 	/* XXX fiddle all the little crinkly bits around the fiords... */
462 	tc_windup(&bt, NULL, &zero);
463 	mtx_leave(&windup_mtx);
464 	rw_exit_write(&tc_lock);
465 
466 	enqueue_randomness(ts->tv_sec);
467 
468 	if (timestepwarnings) {
469 		BINTIME_TO_TIMESPEC(&bt2, &ts2);
470 		log(LOG_INFO, "Time stepped from %lld.%09ld to %lld.%09ld\n",
471 		    (long long)ts2.tv_sec, ts2.tv_nsec,
472 		    (long long)ts->tv_sec, ts->tv_nsec);
473 	}
474 }
475 
476 /*
477  * Step the monotonic and realtime clocks, triggering any timeouts that
478  * should have occurred across the interval.
479  */
480 void
481 tc_setclock(const struct timespec *ts)
482 {
483 	struct bintime bt, old_naptime, naptime;
484 	struct timespec earlier;
485 	static int first = 1;
486 #ifndef SMALL_KERNEL
487 	long long adj_ticks;
488 #endif
489 
490 	/*
491 	 * When we're called for the first time, during boot when
492 	 * the root partition is mounted, we need to set boottime.
493 	 */
494 	if (first) {
495 		tc_setrealtimeclock(ts);
496 		first = 0;
497 		return;
498 	}
499 
500 	enqueue_randomness(ts->tv_sec);
501 
502 	mtx_enter(&windup_mtx);
503 	TIMESPEC_TO_BINTIME(ts, &bt);
504 	bintimesub(&bt, &timehands->th_boottime, &bt);
505 	old_naptime = timehands->th_naptime;
506 	/* XXX fiddle all the little crinkly bits around the fiords... */
507 	tc_windup(NULL, &bt, NULL);
508 	naptime = timehands->th_naptime;
509 	mtx_leave(&windup_mtx);
510 
511 	if (bintimecmp(&old_naptime, &naptime, ==)) {
512 		BINTIME_TO_TIMESPEC(&bt, &earlier);
513 		printf("%s: cannot rewind uptime to %lld.%09ld\n",
514 		    __func__, (long long)earlier.tv_sec, earlier.tv_nsec);
515 	}
516 
517 #ifndef SMALL_KERNEL
518 	/* convert the bintime to ticks */
519 	bintimesub(&naptime, &old_naptime, &bt);
520 	adj_ticks = (uint64_t)hz * bt.sec +
521 	    (((uint64_t)1000000 * (uint32_t)(bt.frac >> 32)) >> 32) / tick;
522 	if (adj_ticks > 0) {
523 		if (adj_ticks > INT_MAX)
524 			adj_ticks = INT_MAX;
525 		timeout_adjust_ticks(adj_ticks);
526 	}
527 #endif
528 }
529 
530 /*
531  * Initialize the next struct timehands in the ring and make
532  * it the active timehands.  Along the way we might switch to a different
533  * timecounter and/or do seconds processing in NTP.  Slightly magic.
534  */
535 void
536 tc_windup(struct bintime *new_boottime, struct bintime *new_offset,
537     int64_t *new_adjtimedelta)
538 {
539 	struct bintime bt;
540 	struct timecounter *active_tc;
541 	struct timehands *th, *tho;
542 	u_int64_t scale;
543 	u_int delta, ncount, ogen;
544 	int i;
545 
546 	if (new_boottime != NULL || new_adjtimedelta != NULL)
547 		rw_assert_wrlock(&tc_lock);
548 	MUTEX_ASSERT_LOCKED(&windup_mtx);
549 
550 	active_tc = timecounter;
551 
552 	/*
553 	 * Make the next timehands a copy of the current one, but do not
554 	 * overwrite the generation or next pointer.  While we update
555 	 * the contents, the generation must be zero.
556 	 */
557 	tho = timehands;
558 	th = tho->th_next;
559 	ogen = th->th_generation;
560 	th->th_generation = 0;
561 	membar_producer();
562 	memcpy(th, tho, offsetof(struct timehands, th_generation));
563 
564 	/*
565 	 * Capture a timecounter delta on the current timecounter and if
566 	 * changing timecounters, a counter value from the new timecounter.
567 	 * Update the offset fields accordingly.
568 	 */
569 	delta = tc_delta(th);
570 	if (th->th_counter != active_tc)
571 		ncount = active_tc->tc_get_timecount(active_tc);
572 	else
573 		ncount = 0;
574 	th->th_offset_count += delta;
575 	th->th_offset_count &= th->th_counter->tc_counter_mask;
576 	bintimeaddfrac(&th->th_offset, th->th_scale * delta, &th->th_offset);
577 
578 	/*
579 	 * Ignore new offsets that predate the current offset.
580 	 * If changing the offset, first increase the naptime
581 	 * accordingly.
582 	 */
583 	if (new_offset != NULL && bintimecmp(&th->th_offset, new_offset, <)) {
584 		bintimesub(new_offset, &th->th_offset, &bt);
585 		bintimeadd(&th->th_naptime, &bt, &th->th_naptime);
586 		th->th_offset = *new_offset;
587 	}
588 
589 #ifdef notyet
590 	/*
591 	 * Hardware latching timecounters may not generate interrupts on
592 	 * PPS events, so instead we poll them.  There is a finite risk that
593 	 * the hardware might capture a count which is later than the one we
594 	 * got above, and therefore possibly in the next NTP second which might
595 	 * have a different rate than the current NTP second.  It doesn't
596 	 * matter in practice.
597 	 */
598 	if (tho->th_counter->tc_poll_pps)
599 		tho->th_counter->tc_poll_pps(tho->th_counter);
600 #endif
601 
602 	/*
603 	 * If changing the boot time or clock adjustment, do so before
604 	 * NTP processing.
605 	 */
606 	if (new_boottime != NULL)
607 		th->th_boottime = *new_boottime;
608 	if (new_adjtimedelta != NULL)
609 		th->th_adjtimedelta = *new_adjtimedelta;
610 
611 	/*
612 	 * Deal with NTP second processing.  The for loop normally
613 	 * iterates at most once, but in extreme situations it might
614 	 * keep NTP sane if timeouts are not run for several seconds.
615 	 * At boot, the time step can be large when the TOD hardware
616 	 * has been read, so on really large steps, we call
617 	 * ntp_update_second only twice.  We need to call it twice in
618 	 * case we missed a leap second.
619 	 */
620 	bt = th->th_offset;
621 	bintimeadd(&bt, &th->th_boottime, &bt);
622 	i = bt.sec - tho->th_microtime.tv_sec;
623 	if (i > LARGE_STEP)
624 		i = 2;
625 	for (; i > 0; i--)
626 		ntp_update_second(th);
627 
628 	/* Update the UTC timestamps used by the get*() functions. */
629 	/* XXX shouldn't do this here.  Should force non-`get' versions. */
630 	BINTIME_TO_TIMEVAL(&bt, &th->th_microtime);
631 	BINTIME_TO_TIMESPEC(&bt, &th->th_nanotime);
632 
633 	/* Now is a good time to change timecounters. */
634 	if (th->th_counter != active_tc) {
635 		th->th_counter = active_tc;
636 		th->th_offset_count = ncount;
637 	}
638 
639 	/*-
640 	 * Recalculate the scaling factor.  We want the number of 1/2^64
641 	 * fractions of a second per period of the hardware counter, taking
642 	 * into account the th_adjustment factor which the NTP PLL/adjtime(2)
643 	 * processing provides us with.
644 	 *
645 	 * The th_adjustment is nanoseconds per second with 32 bit binary
646 	 * fraction and we want 64 bit binary fraction of second:
647 	 *
648 	 *	 x = a * 2^32 / 10^9 = a * 4.294967296
649 	 *
650 	 * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
651 	 * we can only multiply by about 850 without overflowing, but that
652 	 * leaves suitably precise fractions for multiply before divide.
653 	 *
654 	 * Divide before multiply with a fraction of 2199/512 results in a
655 	 * systematic undercompensation of 10PPM of th_adjustment.  On a
656 	 * 5000PPM adjustment this is a 0.05PPM error.  This is acceptable.
657  	 *
658 	 * We happily sacrifice the lowest of the 64 bits of our result
659 	 * to the goddess of code clarity.
660 	 *
661 	 */
662 	scale = (u_int64_t)1 << 63;
663 	scale += \
664 	    ((th->th_adjustment + th->th_counter->tc_freq_adj) / 1024) * 2199;
665 	scale /= th->th_counter->tc_frequency;
666 	th->th_scale = scale * 2;
667 
668 	/*
669 	 * Now that the struct timehands is again consistent, set the new
670 	 * generation number, making sure to not make it zero.
671 	 */
672 	if (++ogen == 0)
673 		ogen = 1;
674 	membar_producer();
675 	th->th_generation = ogen;
676 
677 	/* Go live with the new struct timehands. */
678 	time_second = th->th_microtime.tv_sec;
679 	time_uptime = th->th_offset.sec;
680 	membar_producer();
681 	timehands = th;
682 }
683 
684 /* Report or change the active timecounter hardware. */
685 int
686 sysctl_tc_hardware(void *oldp, size_t *oldlenp, void *newp, size_t newlen)
687 {
688 	char newname[32];
689 	struct timecounter *newtc, *tc;
690 	int error;
691 
692 	tc = timecounter;
693 	strlcpy(newname, tc->tc_name, sizeof(newname));
694 
695 	error = sysctl_string(oldp, oldlenp, newp, newlen, newname, sizeof(newname));
696 	if (error != 0 || strcmp(newname, tc->tc_name) == 0)
697 		return (error);
698 	SLIST_FOREACH(newtc, &tc_list, tc_next) {
699 		if (strcmp(newname, newtc->tc_name) != 0)
700 			continue;
701 
702 		/* Warm up new timecounter. */
703 		(void)newtc->tc_get_timecount(newtc);
704 		(void)newtc->tc_get_timecount(newtc);
705 
706 		rw_enter_write(&tc_lock);
707 		timecounter = newtc;
708 		rw_exit_write(&tc_lock);
709 
710 		return (0);
711 	}
712 	return (EINVAL);
713 }
714 
715 /* Report or change the active timecounter hardware. */
716 int
717 sysctl_tc_choice(void *oldp, size_t *oldlenp, void *newp, size_t newlen)
718 {
719 	char buf[32], *spc, *choices;
720 	struct timecounter *tc;
721 	int error, maxlen;
722 
723 	if (SLIST_EMPTY(&tc_list))
724 		return (sysctl_rdstring(oldp, oldlenp, newp, ""));
725 
726 	spc = "";
727 	maxlen = 0;
728 	SLIST_FOREACH(tc, &tc_list, tc_next)
729 		maxlen += sizeof(buf);
730 	choices = malloc(maxlen, M_TEMP, M_WAITOK);
731 	*choices = '\0';
732 	SLIST_FOREACH(tc, &tc_list, tc_next) {
733 		snprintf(buf, sizeof(buf), "%s%s(%d)",
734 		    spc, tc->tc_name, tc->tc_quality);
735 		spc = " ";
736 		strlcat(choices, buf, maxlen);
737 	}
738 	error = sysctl_rdstring(oldp, oldlenp, newp, choices);
739 	free(choices, M_TEMP, maxlen);
740 	return (error);
741 }
742 
743 /*
744  * Timecounters need to be updated every so often to prevent the hardware
745  * counter from overflowing.  Updating also recalculates the cached values
746  * used by the get*() family of functions, so their precision depends on
747  * the update frequency.
748  */
749 static int tc_tick;
750 
751 void
752 tc_ticktock(void)
753 {
754 	static int count;
755 
756 	if (++count < tc_tick)
757 		return;
758 	if (!mtx_enter_try(&windup_mtx))
759 		return;
760 	count = 0;
761 	tc_windup(NULL, NULL, NULL);
762 	mtx_leave(&windup_mtx);
763 }
764 
765 void
766 inittimecounter(void)
767 {
768 #ifdef DEBUG
769 	u_int p;
770 #endif
771 
772 	/*
773 	 * Set the initial timeout to
774 	 * max(1, <approx. number of hardclock ticks in a millisecond>).
775 	 * People should probably not use the sysctl to set the timeout
776 	 * to smaller than its initial value, since that value is the
777 	 * smallest reasonable one.  If they want better timestamps they
778 	 * should use the non-"get"* functions.
779 	 */
780 	if (hz > 1000)
781 		tc_tick = (hz + 500) / 1000;
782 	else
783 		tc_tick = 1;
784 #ifdef DEBUG
785 	p = (tc_tick * 1000000) / hz;
786 	printf("Timecounters tick every %d.%03u msec\n", p / 1000, p % 1000);
787 #endif
788 
789 	/* warm up new timecounter (again) and get rolling. */
790 	(void)timecounter->tc_get_timecount(timecounter);
791 	(void)timecounter->tc_get_timecount(timecounter);
792 }
793 
794 /*
795  * Return timecounter-related information.
796  */
797 int
798 sysctl_tc(int *name, u_int namelen, void *oldp, size_t *oldlenp,
799     void *newp, size_t newlen)
800 {
801 	if (namelen != 1)
802 		return (ENOTDIR);
803 
804 	switch (name[0]) {
805 	case KERN_TIMECOUNTER_TICK:
806 		return (sysctl_rdint(oldp, oldlenp, newp, tc_tick));
807 	case KERN_TIMECOUNTER_TIMESTEPWARNINGS:
808 		return (sysctl_int(oldp, oldlenp, newp, newlen,
809 		    &timestepwarnings));
810 	case KERN_TIMECOUNTER_HARDWARE:
811 		return (sysctl_tc_hardware(oldp, oldlenp, newp, newlen));
812 	case KERN_TIMECOUNTER_CHOICE:
813 		return (sysctl_tc_choice(oldp, oldlenp, newp, newlen));
814 	default:
815 		return (EOPNOTSUPP);
816 	}
817 	/* NOTREACHED */
818 }
819 
820 /*
821  * Skew the timehands according to any adjtime(2) adjustment.
822  */
823 void
824 ntp_update_second(struct timehands *th)
825 {
826 	int64_t adj;
827 
828 	MUTEX_ASSERT_LOCKED(&windup_mtx);
829 
830 	if (th->th_adjtimedelta > 0)
831 		adj = MIN(5000, th->th_adjtimedelta);
832 	else
833 		adj = MAX(-5000, th->th_adjtimedelta);
834 	th->th_adjtimedelta -= adj;
835 	th->th_adjustment = (adj * 1000) << 32;
836 }
837 
838 void
839 tc_adjfreq(int64_t *old, int64_t *new)
840 {
841 	if (old != NULL) {
842 		rw_assert_anylock(&tc_lock);
843 		*old = timecounter->tc_freq_adj;
844 	}
845 	if (new != NULL) {
846 		rw_assert_wrlock(&tc_lock);
847 		mtx_enter(&windup_mtx);
848 		timecounter->tc_freq_adj = *new;
849 		tc_windup(NULL, NULL, NULL);
850 		mtx_leave(&windup_mtx);
851 	}
852 }
853 
854 void
855 tc_adjtime(int64_t *old, int64_t *new)
856 {
857 	struct timehands *th;
858 	u_int gen;
859 
860 	if (old != NULL) {
861 		do {
862 			th = timehands;
863 			gen = th->th_generation;
864 			membar_consumer();
865 			*old = th->th_adjtimedelta;
866 			membar_consumer();
867 		} while (gen == 0 || gen != th->th_generation);
868 	}
869 	if (new != NULL) {
870 		rw_assert_wrlock(&tc_lock);
871 		mtx_enter(&windup_mtx);
872 		tc_windup(NULL, NULL, new);
873 		mtx_leave(&windup_mtx);
874 	}
875 }
876