xref: /freebsd/sys/x86/x86/tsc.c (revision f8b865d1d62d17626ab993212963277c06cc25b8)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 1998-2003 Poul-Henning Kamp
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include "opt_clock.h"
33 
34 #include <sys/param.h>
35 #include <sys/bus.h>
36 #include <sys/cpu.h>
37 #include <sys/limits.h>
38 #include <sys/malloc.h>
39 #include <sys/systm.h>
40 #include <sys/sysctl.h>
41 #include <sys/time.h>
42 #include <sys/timetc.h>
43 #include <sys/kernel.h>
44 #include <sys/power.h>
45 #include <sys/smp.h>
46 #include <sys/vdso.h>
47 #include <machine/clock.h>
48 #include <machine/cputypes.h>
49 #include <machine/md_var.h>
50 #include <machine/specialreg.h>
51 #include <x86/vmware.h>
52 #include <dev/acpica/acpi_hpet.h>
53 
54 #include "cpufreq_if.h"
55 
56 uint64_t	tsc_freq;
57 int		tsc_is_invariant;
58 int		tsc_perf_stat;
59 
60 static eventhandler_tag tsc_levels_tag, tsc_pre_tag, tsc_post_tag;
61 
62 SYSCTL_INT(_kern_timecounter, OID_AUTO, invariant_tsc, CTLFLAG_RDTUN,
63     &tsc_is_invariant, 0, "Indicates whether the TSC is P-state invariant");
64 
65 #ifdef SMP
66 int	smp_tsc;
67 SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc, CTLFLAG_RDTUN, &smp_tsc, 0,
68     "Indicates whether the TSC is safe to use in SMP mode");
69 
70 int	smp_tsc_adjust = 0;
71 SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc_adjust, CTLFLAG_RDTUN,
72     &smp_tsc_adjust, 0, "Try to adjust TSC on APs to match BSP");
73 #endif
74 
75 static int	tsc_shift = 1;
76 SYSCTL_INT(_kern_timecounter, OID_AUTO, tsc_shift, CTLFLAG_RDTUN,
77     &tsc_shift, 0, "Shift to pre-apply for the maximum TSC frequency");
78 
79 static int	tsc_disabled;
80 SYSCTL_INT(_machdep, OID_AUTO, disable_tsc, CTLFLAG_RDTUN, &tsc_disabled, 0,
81     "Disable x86 Time Stamp Counter");
82 
83 static int	tsc_skip_calibration;
84 SYSCTL_INT(_machdep, OID_AUTO, disable_tsc_calibration, CTLFLAG_RDTUN,
85     &tsc_skip_calibration, 0, "Disable TSC frequency calibration");
86 
87 static void tsc_freq_changed(void *arg, const struct cf_level *level,
88     int status);
89 static void tsc_freq_changing(void *arg, const struct cf_level *level,
90     int *status);
91 static unsigned tsc_get_timecount(struct timecounter *tc);
92 static inline unsigned tsc_get_timecount_low(struct timecounter *tc);
93 static unsigned tsc_get_timecount_lfence(struct timecounter *tc);
94 static unsigned tsc_get_timecount_low_lfence(struct timecounter *tc);
95 static unsigned tsc_get_timecount_mfence(struct timecounter *tc);
96 static unsigned tsc_get_timecount_low_mfence(struct timecounter *tc);
97 static void tsc_levels_changed(void *arg, int unit);
98 static uint32_t x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th,
99     struct timecounter *tc);
100 #ifdef COMPAT_FREEBSD32
101 static uint32_t x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
102     struct timecounter *tc);
103 #endif
104 
105 static struct timecounter tsc_timecounter = {
106 	.tc_get_timecount =		tsc_get_timecount,
107 	.tc_counter_mask =		~0u,
108 	.tc_name =			"TSC",
109 	.tc_quality =			800,	/* adjusted in code */
110 	.tc_fill_vdso_timehands = 	x86_tsc_vdso_timehands,
111 #ifdef COMPAT_FREEBSD32
112 	.tc_fill_vdso_timehands32 = 	x86_tsc_vdso_timehands32,
113 #endif
114 };
115 
116 static void
117 tsc_freq_vmware(void)
118 {
119 	u_int regs[4];
120 
121 	if (hv_high >= 0x40000010) {
122 		do_cpuid(0x40000010, regs);
123 		tsc_freq = regs[0] * 1000;
124 	} else {
125 		vmware_hvcall(VMW_HVCMD_GETHZ, regs);
126 		if (regs[1] != UINT_MAX)
127 			tsc_freq = regs[0] | ((uint64_t)regs[1] << 32);
128 	}
129 	tsc_is_invariant = 1;
130 }
131 
132 static void
133 tsc_freq_intel(void)
134 {
135 	char brand[48];
136 	u_int regs[4];
137 	uint64_t freq;
138 	char *p;
139 	u_int i;
140 
141 	/*
142 	 * Intel Processor Identification and the CPUID Instruction
143 	 * Application Note 485.
144 	 * http://www.intel.com/assets/pdf/appnote/241618.pdf
145 	 */
146 	if (cpu_exthigh >= 0x80000004) {
147 		p = brand;
148 		for (i = 0x80000002; i < 0x80000005; i++) {
149 			do_cpuid(i, regs);
150 			memcpy(p, regs, sizeof(regs));
151 			p += sizeof(regs);
152 		}
153 		p = NULL;
154 		for (i = 0; i < sizeof(brand) - 1; i++)
155 			if (brand[i] == 'H' && brand[i + 1] == 'z')
156 				p = brand + i;
157 		if (p != NULL) {
158 			p -= 5;
159 			switch (p[4]) {
160 			case 'M':
161 				i = 1;
162 				break;
163 			case 'G':
164 				i = 1000;
165 				break;
166 			case 'T':
167 				i = 1000000;
168 				break;
169 			default:
170 				return;
171 			}
172 #define	C2D(c)	((c) - '0')
173 			if (p[1] == '.') {
174 				freq = C2D(p[0]) * 1000;
175 				freq += C2D(p[2]) * 100;
176 				freq += C2D(p[3]) * 10;
177 				freq *= i * 1000;
178 			} else {
179 				freq = C2D(p[0]) * 1000;
180 				freq += C2D(p[1]) * 100;
181 				freq += C2D(p[2]) * 10;
182 				freq += C2D(p[3]);
183 				freq *= i * 1000000;
184 			}
185 #undef C2D
186 			tsc_freq = freq;
187 		}
188 	}
189 }
190 
191 static void
192 probe_tsc_freq(void)
193 {
194 	u_int regs[4];
195 	uint64_t tsc1, tsc2;
196 
197 	if (cpu_high >= 6) {
198 		do_cpuid(6, regs);
199 		if ((regs[2] & CPUID_PERF_STAT) != 0) {
200 			/*
201 			 * XXX Some emulators expose host CPUID without actual
202 			 * support for these MSRs.  We must test whether they
203 			 * really work.
204 			 */
205 			wrmsr(MSR_MPERF, 0);
206 			wrmsr(MSR_APERF, 0);
207 			DELAY(10);
208 			if (rdmsr(MSR_MPERF) > 0 && rdmsr(MSR_APERF) > 0)
209 				tsc_perf_stat = 1;
210 		}
211 	}
212 
213 	if (vm_guest == VM_GUEST_VMWARE) {
214 		tsc_freq_vmware();
215 		return;
216 	}
217 
218 	switch (cpu_vendor_id) {
219 	case CPU_VENDOR_AMD:
220 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
221 		    (vm_guest == VM_GUEST_NO &&
222 		    CPUID_TO_FAMILY(cpu_id) >= 0x10))
223 			tsc_is_invariant = 1;
224 		if (cpu_feature & CPUID_SSE2) {
225 			tsc_timecounter.tc_get_timecount =
226 			    tsc_get_timecount_mfence;
227 		}
228 		break;
229 	case CPU_VENDOR_INTEL:
230 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
231 		    (vm_guest == VM_GUEST_NO &&
232 		    ((CPUID_TO_FAMILY(cpu_id) == 0x6 &&
233 		    CPUID_TO_MODEL(cpu_id) >= 0xe) ||
234 		    (CPUID_TO_FAMILY(cpu_id) == 0xf &&
235 		    CPUID_TO_MODEL(cpu_id) >= 0x3))))
236 			tsc_is_invariant = 1;
237 		if (cpu_feature & CPUID_SSE2) {
238 			tsc_timecounter.tc_get_timecount =
239 			    tsc_get_timecount_lfence;
240 		}
241 		break;
242 	case CPU_VENDOR_CENTAUR:
243 		if (vm_guest == VM_GUEST_NO &&
244 		    CPUID_TO_FAMILY(cpu_id) == 0x6 &&
245 		    CPUID_TO_MODEL(cpu_id) >= 0xf &&
246 		    (rdmsr(0x1203) & 0x100000000ULL) == 0)
247 			tsc_is_invariant = 1;
248 		if (cpu_feature & CPUID_SSE2) {
249 			tsc_timecounter.tc_get_timecount =
250 			    tsc_get_timecount_lfence;
251 		}
252 		break;
253 	}
254 
255 	if (tsc_skip_calibration) {
256 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
257 			tsc_freq_intel();
258 		return;
259 	}
260 
261 	if (bootverbose)
262 	        printf("Calibrating TSC clock ... ");
263 	tsc1 = rdtsc();
264 	DELAY(1000000);
265 	tsc2 = rdtsc();
266 	tsc_freq = tsc2 - tsc1;
267 	if (bootverbose)
268 		printf("TSC clock: %ju Hz\n", (intmax_t)tsc_freq);
269 }
270 
271 void
272 init_TSC(void)
273 {
274 
275 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
276 		return;
277 
278 #ifdef __i386__
279 	/* The TSC is known to be broken on certain CPUs. */
280 	switch (cpu_vendor_id) {
281 	case CPU_VENDOR_AMD:
282 		switch (cpu_id & 0xFF0) {
283 		case 0x500:
284 			/* K5 Model 0 */
285 			return;
286 		}
287 		break;
288 	case CPU_VENDOR_CENTAUR:
289 		switch (cpu_id & 0xff0) {
290 		case 0x540:
291 			/*
292 			 * http://www.centtech.com/c6_data_sheet.pdf
293 			 *
294 			 * I-12 RDTSC may return incoherent values in EDX:EAX
295 			 * I-13 RDTSC hangs when certain event counters are used
296 			 */
297 			return;
298 		}
299 		break;
300 	case CPU_VENDOR_NSC:
301 		switch (cpu_id & 0xff0) {
302 		case 0x540:
303 			if ((cpu_id & CPUID_STEPPING) == 0)
304 				return;
305 			break;
306 		}
307 		break;
308 	}
309 #endif
310 
311 	probe_tsc_freq();
312 
313 	/*
314 	 * Inform CPU accounting about our boot-time clock rate.  This will
315 	 * be updated if someone loads a cpufreq driver after boot that
316 	 * discovers a new max frequency.
317 	 */
318 	if (tsc_freq != 0)
319 		set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
320 
321 	if (tsc_is_invariant)
322 		return;
323 
324 	/* Register to find out about changes in CPU frequency. */
325 	tsc_pre_tag = EVENTHANDLER_REGISTER(cpufreq_pre_change,
326 	    tsc_freq_changing, NULL, EVENTHANDLER_PRI_FIRST);
327 	tsc_post_tag = EVENTHANDLER_REGISTER(cpufreq_post_change,
328 	    tsc_freq_changed, NULL, EVENTHANDLER_PRI_FIRST);
329 	tsc_levels_tag = EVENTHANDLER_REGISTER(cpufreq_levels_changed,
330 	    tsc_levels_changed, NULL, EVENTHANDLER_PRI_ANY);
331 }
332 
333 #ifdef SMP
334 
335 /*
336  * RDTSC is not a serializing instruction, and does not drain
337  * instruction stream, so we need to drain the stream before executing
338  * it.  It could be fixed by use of RDTSCP, except the instruction is
339  * not available everywhere.
340  *
341  * Use CPUID for draining in the boot-time SMP constistency test.  The
342  * timecounters use MFENCE for AMD CPUs, and LFENCE for others (Intel
343  * and VIA) when SSE2 is present, and nothing on older machines which
344  * also do not issue RDTSC prematurely.  There, testing for SSE2 and
345  * vendor is too cumbersome, and we learn about TSC presence from CPUID.
346  *
347  * Do not use do_cpuid(), since we do not need CPUID results, which
348  * have to be written into memory with do_cpuid().
349  */
350 #define	TSC_READ(x)							\
351 static void								\
352 tsc_read_##x(void *arg)							\
353 {									\
354 	uint64_t *tsc = arg;						\
355 	u_int cpu = PCPU_GET(cpuid);					\
356 									\
357 	__asm __volatile("cpuid" : : : "eax", "ebx", "ecx", "edx");	\
358 	tsc[cpu * 3 + x] = rdtsc();					\
359 }
360 TSC_READ(0)
361 TSC_READ(1)
362 TSC_READ(2)
363 #undef TSC_READ
364 
365 #define	N	1000
366 
367 static void
368 comp_smp_tsc(void *arg)
369 {
370 	uint64_t *tsc;
371 	int64_t d1, d2;
372 	u_int cpu = PCPU_GET(cpuid);
373 	u_int i, j, size;
374 
375 	size = (mp_maxid + 1) * 3;
376 	for (i = 0, tsc = arg; i < N; i++, tsc += size)
377 		CPU_FOREACH(j) {
378 			if (j == cpu)
379 				continue;
380 			d1 = tsc[cpu * 3 + 1] - tsc[j * 3];
381 			d2 = tsc[cpu * 3 + 2] - tsc[j * 3 + 1];
382 			if (d1 <= 0 || d2 <= 0) {
383 				smp_tsc = 0;
384 				return;
385 			}
386 		}
387 }
388 
389 static void
390 adj_smp_tsc(void *arg)
391 {
392 	uint64_t *tsc;
393 	int64_t d, min, max;
394 	u_int cpu = PCPU_GET(cpuid);
395 	u_int first, i, size;
396 
397 	first = CPU_FIRST();
398 	if (cpu == first)
399 		return;
400 	min = INT64_MIN;
401 	max = INT64_MAX;
402 	size = (mp_maxid + 1) * 3;
403 	for (i = 0, tsc = arg; i < N; i++, tsc += size) {
404 		d = tsc[first * 3] - tsc[cpu * 3 + 1];
405 		if (d > min)
406 			min = d;
407 		d = tsc[first * 3 + 1] - tsc[cpu * 3 + 2];
408 		if (d > min)
409 			min = d;
410 		d = tsc[first * 3 + 1] - tsc[cpu * 3];
411 		if (d < max)
412 			max = d;
413 		d = tsc[first * 3 + 2] - tsc[cpu * 3 + 1];
414 		if (d < max)
415 			max = d;
416 	}
417 	if (min > max)
418 		return;
419 	d = min / 2 + max / 2;
420 	__asm __volatile (
421 		"movl $0x10, %%ecx\n\t"
422 		"rdmsr\n\t"
423 		"addl %%edi, %%eax\n\t"
424 		"adcl %%esi, %%edx\n\t"
425 		"wrmsr\n"
426 		: /* No output */
427 		: "D" ((uint32_t)d), "S" ((uint32_t)(d >> 32))
428 		: "ax", "cx", "dx", "cc"
429 	);
430 }
431 
432 static int
433 test_tsc(void)
434 {
435 	uint64_t *data, *tsc;
436 	u_int i, size, adj;
437 
438 	if ((!smp_tsc && !tsc_is_invariant) || vm_guest)
439 		return (-100);
440 	size = (mp_maxid + 1) * 3;
441 	data = malloc(sizeof(*data) * size * N, M_TEMP, M_WAITOK);
442 	adj = 0;
443 retry:
444 	for (i = 0, tsc = data; i < N; i++, tsc += size)
445 		smp_rendezvous(tsc_read_0, tsc_read_1, tsc_read_2, tsc);
446 	smp_tsc = 1;	/* XXX */
447 	smp_rendezvous(smp_no_rendezvous_barrier, comp_smp_tsc,
448 	    smp_no_rendezvous_barrier, data);
449 	if (!smp_tsc && adj < smp_tsc_adjust) {
450 		adj++;
451 		smp_rendezvous(smp_no_rendezvous_barrier, adj_smp_tsc,
452 		    smp_no_rendezvous_barrier, data);
453 		goto retry;
454 	}
455 	free(data, M_TEMP);
456 	if (bootverbose)
457 		printf("SMP: %sed TSC synchronization test%s\n",
458 		    smp_tsc ? "pass" : "fail",
459 		    adj > 0 ? " after adjustment" : "");
460 	if (smp_tsc && tsc_is_invariant) {
461 		switch (cpu_vendor_id) {
462 		case CPU_VENDOR_AMD:
463 			/*
464 			 * Starting with Family 15h processors, TSC clock
465 			 * source is in the north bridge.  Check whether
466 			 * we have a single-socket/multi-core platform.
467 			 * XXX Need more work for complex cases.
468 			 */
469 			if (CPUID_TO_FAMILY(cpu_id) < 0x15 ||
470 			    (amd_feature2 & AMDID2_CMP) == 0 ||
471 			    smp_cpus > (cpu_procinfo2 & AMDID_CMP_CORES) + 1)
472 				break;
473 			return (1000);
474 		case CPU_VENDOR_INTEL:
475 			/*
476 			 * XXX Assume Intel platforms have synchronized TSCs.
477 			 */
478 			return (1000);
479 		}
480 		return (800);
481 	}
482 	return (-100);
483 }
484 
485 #undef N
486 
487 #else
488 
489 /*
490  * The function is not called, it is provided to avoid linking failure
491  * on uniprocessor kernel.
492  */
493 static int
494 test_tsc(void)
495 {
496 
497 	return (0);
498 }
499 
500 #endif /* SMP */
501 
502 static void
503 init_TSC_tc(void)
504 {
505 	uint64_t max_freq;
506 	int shift;
507 
508 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
509 		return;
510 
511 	/*
512 	 * Limit timecounter frequency to fit in an int and prevent it from
513 	 * overflowing too fast.
514 	 */
515 	max_freq = UINT_MAX;
516 
517 	/*
518 	 * We can not use the TSC if we support APM.  Precise timekeeping
519 	 * on an APM'ed machine is at best a fools pursuit, since
520 	 * any and all of the time spent in various SMM code can't
521 	 * be reliably accounted for.  Reading the RTC is your only
522 	 * source of reliable time info.  The i8254 loses too, of course,
523 	 * but we need to have some kind of time...
524 	 * We don't know at this point whether APM is going to be used
525 	 * or not, nor when it might be activated.  Play it safe.
526 	 */
527 	if (power_pm_get_type() == POWER_PM_TYPE_APM) {
528 		tsc_timecounter.tc_quality = -1000;
529 		if (bootverbose)
530 			printf("TSC timecounter disabled: APM enabled.\n");
531 		goto init;
532 	}
533 
534 	/*
535 	 * Intel CPUs without a C-state invariant TSC can stop the TSC
536 	 * in either C2 or C3.  Disable use of C2 and C3 while using
537 	 * the TSC as the timecounter.  The timecounter can be changed
538 	 * to enable C2 and C3.
539 	 *
540 	 * Note that the TSC is used as the cputicker for computing
541 	 * thread runtime regardless of the timecounter setting, so
542 	 * using an alternate timecounter and enabling C2 or C3 can
543 	 * result incorrect runtimes for kernel idle threads (but not
544 	 * for any non-idle threads).
545 	 */
546 	if (cpu_vendor_id == CPU_VENDOR_INTEL &&
547 	    (amd_pminfo & AMDPM_TSC_INVARIANT) == 0) {
548 		tsc_timecounter.tc_flags |= TC_FLAGS_C2STOP;
549 		if (bootverbose)
550 			printf("TSC timecounter disables C2 and C3.\n");
551 	}
552 
553 	/*
554 	 * We can not use the TSC in SMP mode unless the TSCs on all CPUs
555 	 * are synchronized.  If the user is sure that the system has
556 	 * synchronized TSCs, set kern.timecounter.smp_tsc tunable to a
557 	 * non-zero value.  The TSC seems unreliable in virtualized SMP
558 	 * environments, so it is set to a negative quality in those cases.
559 	 */
560 	if (mp_ncpus > 1)
561 		tsc_timecounter.tc_quality = test_tsc();
562 	else if (tsc_is_invariant)
563 		tsc_timecounter.tc_quality = 1000;
564 	max_freq >>= tsc_shift;
565 
566 init:
567 	for (shift = 0; shift <= 31 && (tsc_freq >> shift) > max_freq; shift++)
568 		;
569 	if ((cpu_feature & CPUID_SSE2) != 0 && mp_ncpus > 1) {
570 		if (cpu_vendor_id == CPU_VENDOR_AMD) {
571 			tsc_timecounter.tc_get_timecount = shift > 0 ?
572 			    tsc_get_timecount_low_mfence :
573 			    tsc_get_timecount_mfence;
574 		} else {
575 			tsc_timecounter.tc_get_timecount = shift > 0 ?
576 			    tsc_get_timecount_low_lfence :
577 			    tsc_get_timecount_lfence;
578 		}
579 	} else {
580 		tsc_timecounter.tc_get_timecount = shift > 0 ?
581 		    tsc_get_timecount_low : tsc_get_timecount;
582 	}
583 	if (shift > 0) {
584 		tsc_timecounter.tc_name = "TSC-low";
585 		if (bootverbose)
586 			printf("TSC timecounter discards lower %d bit(s)\n",
587 			    shift);
588 	}
589 	if (tsc_freq != 0) {
590 		tsc_timecounter.tc_frequency = tsc_freq >> shift;
591 		tsc_timecounter.tc_priv = (void *)(intptr_t)shift;
592 		tc_init(&tsc_timecounter);
593 	}
594 }
595 SYSINIT(tsc_tc, SI_SUB_SMP, SI_ORDER_ANY, init_TSC_tc, NULL);
596 
597 /*
598  * When cpufreq levels change, find out about the (new) max frequency.  We
599  * use this to update CPU accounting in case it got a lower estimate at boot.
600  */
601 static void
602 tsc_levels_changed(void *arg, int unit)
603 {
604 	device_t cf_dev;
605 	struct cf_level *levels;
606 	int count, error;
607 	uint64_t max_freq;
608 
609 	/* Only use values from the first CPU, assuming all are equal. */
610 	if (unit != 0)
611 		return;
612 
613 	/* Find the appropriate cpufreq device instance. */
614 	cf_dev = devclass_get_device(devclass_find("cpufreq"), unit);
615 	if (cf_dev == NULL) {
616 		printf("tsc_levels_changed() called but no cpufreq device?\n");
617 		return;
618 	}
619 
620 	/* Get settings from the device and find the max frequency. */
621 	count = 64;
622 	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
623 	if (levels == NULL)
624 		return;
625 	error = CPUFREQ_LEVELS(cf_dev, levels, &count);
626 	if (error == 0 && count != 0) {
627 		max_freq = (uint64_t)levels[0].total_set.freq * 1000000;
628 		set_cputicker(rdtsc, max_freq, 1);
629 	} else
630 		printf("tsc_levels_changed: no max freq found\n");
631 	free(levels, M_TEMP);
632 }
633 
634 /*
635  * If the TSC timecounter is in use, veto the pending change.  It may be
636  * possible in the future to handle a dynamically-changing timecounter rate.
637  */
638 static void
639 tsc_freq_changing(void *arg, const struct cf_level *level, int *status)
640 {
641 
642 	if (*status != 0 || timecounter != &tsc_timecounter)
643 		return;
644 
645 	printf("timecounter TSC must not be in use when "
646 	    "changing frequencies; change denied\n");
647 	*status = EBUSY;
648 }
649 
650 /* Update TSC freq with the value indicated by the caller. */
651 static void
652 tsc_freq_changed(void *arg, const struct cf_level *level, int status)
653 {
654 	uint64_t freq;
655 
656 	/* If there was an error during the transition, don't do anything. */
657 	if (tsc_disabled || status != 0)
658 		return;
659 
660 	/* Total setting for this level gives the new frequency in MHz. */
661 	freq = (uint64_t)level->total_set.freq * 1000000;
662 	atomic_store_rel_64(&tsc_freq, freq);
663 	tsc_timecounter.tc_frequency =
664 	    freq >> (int)(intptr_t)tsc_timecounter.tc_priv;
665 }
666 
667 static int
668 sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
669 {
670 	int error;
671 	uint64_t freq;
672 
673 	freq = atomic_load_acq_64(&tsc_freq);
674 	if (freq == 0)
675 		return (EOPNOTSUPP);
676 	error = sysctl_handle_64(oidp, &freq, 0, req);
677 	if (error == 0 && req->newptr != NULL) {
678 		atomic_store_rel_64(&tsc_freq, freq);
679 		atomic_store_rel_64(&tsc_timecounter.tc_frequency,
680 		    freq >> (int)(intptr_t)tsc_timecounter.tc_priv);
681 	}
682 	return (error);
683 }
684 
685 SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq, CTLTYPE_U64 | CTLFLAG_RW,
686     0, 0, sysctl_machdep_tsc_freq, "QU", "Time Stamp Counter frequency");
687 
688 static u_int
689 tsc_get_timecount(struct timecounter *tc __unused)
690 {
691 
692 	return (rdtsc32());
693 }
694 
695 static inline u_int
696 tsc_get_timecount_low(struct timecounter *tc)
697 {
698 	uint32_t rv;
699 
700 	__asm __volatile("rdtsc; shrd %%cl, %%edx, %0"
701 	    : "=a" (rv) : "c" ((int)(intptr_t)tc->tc_priv) : "edx");
702 	return (rv);
703 }
704 
705 static u_int
706 tsc_get_timecount_lfence(struct timecounter *tc __unused)
707 {
708 
709 	lfence();
710 	return (rdtsc32());
711 }
712 
713 static u_int
714 tsc_get_timecount_low_lfence(struct timecounter *tc)
715 {
716 
717 	lfence();
718 	return (tsc_get_timecount_low(tc));
719 }
720 
721 static u_int
722 tsc_get_timecount_mfence(struct timecounter *tc __unused)
723 {
724 
725 	mfence();
726 	return (rdtsc32());
727 }
728 
729 static u_int
730 tsc_get_timecount_low_mfence(struct timecounter *tc)
731 {
732 
733 	mfence();
734 	return (tsc_get_timecount_low(tc));
735 }
736 
737 static uint32_t
738 x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th, struct timecounter *tc)
739 {
740 
741 	vdso_th->th_algo = VDSO_TH_ALGO_X86_TSC;
742 	vdso_th->th_x86_shift = (int)(intptr_t)tc->tc_priv;
743 	vdso_th->th_x86_hpet_idx = 0xffffffff;
744 	bzero(vdso_th->th_res, sizeof(vdso_th->th_res));
745 	return (1);
746 }
747 
748 #ifdef COMPAT_FREEBSD32
749 static uint32_t
750 x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
751     struct timecounter *tc)
752 {
753 
754 	vdso_th32->th_algo = VDSO_TH_ALGO_X86_TSC;
755 	vdso_th32->th_x86_shift = (int)(intptr_t)tc->tc_priv;
756 	vdso_th32->th_x86_hpet_idx = 0xffffffff;
757 	bzero(vdso_th32->th_res, sizeof(vdso_th32->th_res));
758 	return (1);
759 }
760 #endif
761