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