xref: /freebsd/sys/x86/x86/tsc.c (revision 93626d54370292b09cd0ca604b144737109e9071)
1dd7d207dSJung-uk Kim /*-
24d846d26SWarner Losh  * SPDX-License-Identifier: BSD-2-Clause
3ebf5747bSPedro F. Giffuni  *
4dd7d207dSJung-uk Kim  * Copyright (c) 1998-2003 Poul-Henning Kamp
5dd7d207dSJung-uk Kim  * All rights reserved.
6dd7d207dSJung-uk Kim  *
7dd7d207dSJung-uk Kim  * Redistribution and use in source and binary forms, with or without
8dd7d207dSJung-uk Kim  * modification, are permitted provided that the following conditions
9dd7d207dSJung-uk Kim  * are met:
10dd7d207dSJung-uk Kim  * 1. Redistributions of source code must retain the above copyright
11dd7d207dSJung-uk Kim  *    notice, this list of conditions and the following disclaimer.
12dd7d207dSJung-uk Kim  * 2. Redistributions in binary form must reproduce the above copyright
13dd7d207dSJung-uk Kim  *    notice, this list of conditions and the following disclaimer in the
14dd7d207dSJung-uk Kim  *    documentation and/or other materials provided with the distribution.
15dd7d207dSJung-uk Kim  *
16dd7d207dSJung-uk Kim  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17dd7d207dSJung-uk Kim  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18dd7d207dSJung-uk Kim  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19dd7d207dSJung-uk Kim  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20dd7d207dSJung-uk Kim  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21dd7d207dSJung-uk Kim  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22dd7d207dSJung-uk Kim  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23dd7d207dSJung-uk Kim  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24dd7d207dSJung-uk Kim  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25dd7d207dSJung-uk Kim  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26dd7d207dSJung-uk Kim  * SUCH DAMAGE.
27dd7d207dSJung-uk Kim  */
28dd7d207dSJung-uk Kim 
29dd7d207dSJung-uk Kim #include <sys/cdefs.h>
30dd7d207dSJung-uk Kim __FBSDID("$FreeBSD$");
31dd7d207dSJung-uk Kim 
32dd7d207dSJung-uk Kim #include "opt_clock.h"
33dd7d207dSJung-uk Kim 
34dd7d207dSJung-uk Kim #include <sys/param.h>
3522875f88SMark Johnston #include <sys/systm.h>
36dd7d207dSJung-uk Kim #include <sys/bus.h>
37dd7d207dSJung-uk Kim #include <sys/cpu.h>
38e2e050c8SConrad Meyer #include <sys/eventhandler.h>
395da5812bSJung-uk Kim #include <sys/limits.h>
40dd7d207dSJung-uk Kim #include <sys/malloc.h>
4122875f88SMark Johnston #include <sys/proc.h>
4222875f88SMark Johnston #include <sys/sched.h>
43dd7d207dSJung-uk Kim #include <sys/sysctl.h>
44dd7d207dSJung-uk Kim #include <sys/time.h>
45dd7d207dSJung-uk Kim #include <sys/timetc.h>
46dd7d207dSJung-uk Kim #include <sys/kernel.h>
47dd7d207dSJung-uk Kim #include <sys/smp.h>
48aea81038SKonstantin Belousov #include <sys/vdso.h>
49dd7d207dSJung-uk Kim #include <machine/clock.h>
50dd7d207dSJung-uk Kim #include <machine/cputypes.h>
51c2705ceaSColin Percival #include <machine/fpu.h>
52dd7d207dSJung-uk Kim #include <machine/md_var.h>
53dd7d207dSJung-uk Kim #include <machine/specialreg.h>
5401e1933dSJohn Baldwin #include <x86/vmware.h>
5516808549SKonstantin Belousov #include <dev/acpica/acpi_hpet.h>
56ce3bf750SKonstantin Belousov #include <contrib/dev/acpica/include/acpi.h>
57dd7d207dSJung-uk Kim 
58dd7d207dSJung-uk Kim #include "cpufreq_if.h"
59dd7d207dSJung-uk Kim 
60dd7d207dSJung-uk Kim uint64_t	tsc_freq;
61dd7d207dSJung-uk Kim int		tsc_is_invariant;
62155094d7SJung-uk Kim int		tsc_perf_stat;
639cb32882SColin Percival static int	tsc_early_calib_exact;
64155094d7SJung-uk Kim 
65dd7d207dSJung-uk Kim static eventhandler_tag tsc_levels_tag, tsc_pre_tag, tsc_post_tag;
66dd7d207dSJung-uk Kim 
67dd7d207dSJung-uk Kim SYSCTL_INT(_kern_timecounter, OID_AUTO, invariant_tsc, CTLFLAG_RDTUN,
68dd7d207dSJung-uk Kim     &tsc_is_invariant, 0, "Indicates whether the TSC is P-state invariant");
69dd7d207dSJung-uk Kim 
70dd7d207dSJung-uk Kim #ifdef SMP
711472b87fSNeel Natu int	smp_tsc;
72dd7d207dSJung-uk Kim SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc, CTLFLAG_RDTUN, &smp_tsc, 0,
73dd7d207dSJung-uk Kim     "Indicates whether the TSC is safe to use in SMP mode");
74b2c63698SAlexander Motin 
75b2c63698SAlexander Motin int	smp_tsc_adjust = 0;
76b2c63698SAlexander Motin SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc_adjust, CTLFLAG_RDTUN,
77b2c63698SAlexander Motin     &smp_tsc_adjust, 0, "Try to adjust TSC on APs to match BSP");
78dd7d207dSJung-uk Kim #endif
79dd7d207dSJung-uk Kim 
80e7f1427dSKonstantin Belousov static int	tsc_shift = 1;
81e7f1427dSKonstantin Belousov SYSCTL_INT(_kern_timecounter, OID_AUTO, tsc_shift, CTLFLAG_RDTUN,
82e7f1427dSKonstantin Belousov     &tsc_shift, 0, "Shift to pre-apply for the maximum TSC frequency");
83e7f1427dSKonstantin Belousov 
8479422085SJung-uk Kim static int	tsc_disabled;
8579422085SJung-uk Kim SYSCTL_INT(_machdep, OID_AUTO, disable_tsc, CTLFLAG_RDTUN, &tsc_disabled, 0,
8679422085SJung-uk Kim     "Disable x86 Time Stamp Counter");
8779422085SJung-uk Kim 
88a4e4127fSJung-uk Kim static int	tsc_skip_calibration;
89ab23c278SKonstantin Belousov SYSCTL_INT(_machdep, OID_AUTO, disable_tsc_calibration, CTLFLAG_RDTUN,
90ab23c278SKonstantin Belousov     &tsc_skip_calibration, 0,
9122875f88SMark Johnston     "Disable early TSC frequency calibration");
92a4e4127fSJung-uk Kim 
93dd7d207dSJung-uk Kim static void tsc_freq_changed(void *arg, const struct cf_level *level,
94dd7d207dSJung-uk Kim     int status);
95dd7d207dSJung-uk Kim static void tsc_freq_changing(void *arg, const struct cf_level *level,
96dd7d207dSJung-uk Kim     int *status);
97826fc3ccSKonstantin Belousov static u_int tsc_get_timecount(struct timecounter *tc);
98826fc3ccSKonstantin Belousov static inline u_int tsc_get_timecount_low(struct timecounter *tc);
99826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_lfence(struct timecounter *tc);
100826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_low_lfence(struct timecounter *tc);
101826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_mfence(struct timecounter *tc);
102826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_low_mfence(struct timecounter *tc);
1039e680e40SKonstantin Belousov static u_int tscp_get_timecount(struct timecounter *tc);
1049e680e40SKonstantin Belousov static u_int tscp_get_timecount_low(struct timecounter *tc);
105dd7d207dSJung-uk Kim static void tsc_levels_changed(void *arg, int unit);
10616808549SKonstantin Belousov static uint32_t x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th,
10716808549SKonstantin Belousov     struct timecounter *tc);
10816808549SKonstantin Belousov #ifdef COMPAT_FREEBSD32
10916808549SKonstantin Belousov static uint32_t x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
11016808549SKonstantin Belousov     struct timecounter *tc);
11116808549SKonstantin Belousov #endif
112dd7d207dSJung-uk Kim 
113dd7d207dSJung-uk Kim static struct timecounter tsc_timecounter = {
11416808549SKonstantin Belousov 	.tc_get_timecount =		tsc_get_timecount,
11516808549SKonstantin Belousov 	.tc_counter_mask =		~0u,
11616808549SKonstantin Belousov 	.tc_name =			"TSC",
11716808549SKonstantin Belousov 	.tc_quality =			800,	/* adjusted in code */
11816808549SKonstantin Belousov 	.tc_fill_vdso_timehands = 	x86_tsc_vdso_timehands,
11916808549SKonstantin Belousov #ifdef COMPAT_FREEBSD32
12016808549SKonstantin Belousov 	.tc_fill_vdso_timehands32 = 	x86_tsc_vdso_timehands32,
12116808549SKonstantin Belousov #endif
122dd7d207dSJung-uk Kim };
123dd7d207dSJung-uk Kim 
1244a432614SColin Percival static int
1254a432614SColin Percival tsc_freq_cpuid_vm(void)
1264a432614SColin Percival {
1274a432614SColin Percival 	u_int regs[4];
1284a432614SColin Percival 
1294a432614SColin Percival 	if (vm_guest == VM_GUEST_NO)
1304a432614SColin Percival 		return (false);
1314a432614SColin Percival 	if (hv_high < 0x40000010)
1324a432614SColin Percival 		return (false);
1334a432614SColin Percival 	do_cpuid(0x40000010, regs);
1344a432614SColin Percival 	tsc_freq = (uint64_t)(regs[0]) * 1000;
1354a432614SColin Percival 	tsc_early_calib_exact = 1;
1364a432614SColin Percival 	return (true);
1374a432614SColin Percival }
1384a432614SColin Percival 
13901e1933dSJohn Baldwin static void
1405da5812bSJung-uk Kim tsc_freq_vmware(void)
1415da5812bSJung-uk Kim {
1425da5812bSJung-uk Kim 	u_int regs[4];
1435da5812bSJung-uk Kim 
1445da5812bSJung-uk Kim 	vmware_hvcall(VMW_HVCMD_GETHZ, regs);
1455da5812bSJung-uk Kim 	if (regs[1] != UINT_MAX)
1465da5812bSJung-uk Kim 		tsc_freq = regs[0] | ((uint64_t)regs[1] << 32);
1479cb32882SColin Percival 	tsc_early_calib_exact = 1;
1485da5812bSJung-uk Kim }
1495da5812bSJung-uk Kim 
1501ca34862SRoger Pau Monné static void
1511ca34862SRoger Pau Monné tsc_freq_xen(void)
1521ca34862SRoger Pau Monné {
1531ca34862SRoger Pau Monné 	u_int regs[4];
1541ca34862SRoger Pau Monné 
1551ca34862SRoger Pau Monné 	/*
1561ca34862SRoger Pau Monné 	 * Must run *after* generic tsc_freq_cpuid_vm, so that when Xen is
1571ca34862SRoger Pau Monné 	 * emulating Viridian support the Viridian leaf is used instead.
1581ca34862SRoger Pau Monné 	 */
1591ca34862SRoger Pau Monné 	KASSERT(hv_high >= 0x40000003, ("Invalid max hypervisor leaf on Xen"));
1601ca34862SRoger Pau Monné 	cpuid_count(0x40000003, 0, regs);
1611ca34862SRoger Pau Monné 	tsc_freq = (uint64_t)(regs[2]) * 1000;
1621ca34862SRoger Pau Monné 	tsc_early_calib_exact = 1;
1631ca34862SRoger Pau Monné }
1641ca34862SRoger Pau Monné 
165506a906cSKonstantin Belousov /*
16622875f88SMark Johnston  * Calculate TSC frequency using information from the CPUID leaf 0x15 'Time
16722875f88SMark Johnston  * Stamp Counter and Nominal Core Crystal Clock'.  If leaf 0x15 is not
16822875f88SMark Johnston  * functional, as it is on Skylake/Kabylake, try 0x16 'Processor Frequency
16922875f88SMark Johnston  * Information'.  Leaf 0x16 is described in the SDM as informational only, but
17022875f88SMark Johnston  * we can use this value until late calibration is complete.
171506a906cSKonstantin Belousov  */
172506a906cSKonstantin Belousov static bool
173bd8a359fSKonstantin Belousov tsc_freq_cpuid(uint64_t *res)
174506a906cSKonstantin Belousov {
175506a906cSKonstantin Belousov 	u_int regs[4];
176506a906cSKonstantin Belousov 
177506a906cSKonstantin Belousov 	if (cpu_high < 0x15)
178506a906cSKonstantin Belousov 		return (false);
179506a906cSKonstantin Belousov 	do_cpuid(0x15, regs);
180a9d0e007SKonstantin Belousov 	if (regs[0] != 0 && regs[1] != 0 && regs[2] != 0) {
181bd8a359fSKonstantin Belousov 		*res = (uint64_t)regs[2] * regs[1] / regs[0];
182506a906cSKonstantin Belousov 		return (true);
183506a906cSKonstantin Belousov 	}
184506a906cSKonstantin Belousov 
185a9d0e007SKonstantin Belousov 	if (cpu_high < 0x16)
186a9d0e007SKonstantin Belousov 		return (false);
187a9d0e007SKonstantin Belousov 	do_cpuid(0x16, regs);
188a9d0e007SKonstantin Belousov 	if (regs[0] != 0) {
189bd8a359fSKonstantin Belousov 		*res = (uint64_t)regs[0] * 1000000;
190a9d0e007SKonstantin Belousov 		return (true);
191a9d0e007SKonstantin Belousov 	}
192a9d0e007SKonstantin Belousov 
193a9d0e007SKonstantin Belousov 	return (false);
194a9d0e007SKonstantin Belousov }
195a9d0e007SKonstantin Belousov 
19622875f88SMark Johnston static bool
19722875f88SMark Johnston tsc_freq_intel_brand(uint64_t *res)
198dd7d207dSJung-uk Kim {
199a4e4127fSJung-uk Kim 	char brand[48];
200a4e4127fSJung-uk Kim 	u_int regs[4];
201a4e4127fSJung-uk Kim 	uint64_t freq;
202a4e4127fSJung-uk Kim 	char *p;
203a4e4127fSJung-uk Kim 	u_int i;
204dd7d207dSJung-uk Kim 
205a4e4127fSJung-uk Kim 	/*
206a4e4127fSJung-uk Kim 	 * Intel Processor Identification and the CPUID Instruction
207a4e4127fSJung-uk Kim 	 * Application Note 485.
208a4e4127fSJung-uk Kim 	 * http://www.intel.com/assets/pdf/appnote/241618.pdf
209a4e4127fSJung-uk Kim 	 */
210a4e4127fSJung-uk Kim 	if (cpu_exthigh >= 0x80000004) {
211a4e4127fSJung-uk Kim 		p = brand;
212a4e4127fSJung-uk Kim 		for (i = 0x80000002; i < 0x80000005; i++) {
213a4e4127fSJung-uk Kim 			do_cpuid(i, regs);
214a4e4127fSJung-uk Kim 			memcpy(p, regs, sizeof(regs));
215a4e4127fSJung-uk Kim 			p += sizeof(regs);
216a4e4127fSJung-uk Kim 		}
217a4e4127fSJung-uk Kim 		p = NULL;
218a4e4127fSJung-uk Kim 		for (i = 0; i < sizeof(brand) - 1; i++)
219a4e4127fSJung-uk Kim 			if (brand[i] == 'H' && brand[i + 1] == 'z')
220a4e4127fSJung-uk Kim 				p = brand + i;
221a4e4127fSJung-uk Kim 		if (p != NULL) {
222a4e4127fSJung-uk Kim 			p -= 5;
223a4e4127fSJung-uk Kim 			switch (p[4]) {
224a4e4127fSJung-uk Kim 			case 'M':
225a4e4127fSJung-uk Kim 				i = 1;
226a4e4127fSJung-uk Kim 				break;
227a4e4127fSJung-uk Kim 			case 'G':
228a4e4127fSJung-uk Kim 				i = 1000;
229a4e4127fSJung-uk Kim 				break;
230a4e4127fSJung-uk Kim 			case 'T':
231a4e4127fSJung-uk Kim 				i = 1000000;
232a4e4127fSJung-uk Kim 				break;
233a4e4127fSJung-uk Kim 			default:
23422875f88SMark Johnston 				return (false);
235a4e4127fSJung-uk Kim 			}
236a4e4127fSJung-uk Kim #define	C2D(c)	((c) - '0')
237a4e4127fSJung-uk Kim 			if (p[1] == '.') {
238a4e4127fSJung-uk Kim 				freq = C2D(p[0]) * 1000;
239a4e4127fSJung-uk Kim 				freq += C2D(p[2]) * 100;
240a4e4127fSJung-uk Kim 				freq += C2D(p[3]) * 10;
241a4e4127fSJung-uk Kim 				freq *= i * 1000;
242a4e4127fSJung-uk Kim 			} else {
243a4e4127fSJung-uk Kim 				freq = C2D(p[0]) * 1000;
244a4e4127fSJung-uk Kim 				freq += C2D(p[1]) * 100;
245a4e4127fSJung-uk Kim 				freq += C2D(p[2]) * 10;
246a4e4127fSJung-uk Kim 				freq += C2D(p[3]);
247a4e4127fSJung-uk Kim 				freq *= i * 1000000;
248a4e4127fSJung-uk Kim 			}
249a4e4127fSJung-uk Kim #undef C2D
25022875f88SMark Johnston 			*res = freq;
25122875f88SMark Johnston 			return (true);
252a4e4127fSJung-uk Kim 		}
253a4e4127fSJung-uk Kim 	}
25422875f88SMark Johnston 	return (false);
25522875f88SMark Johnston }
25622875f88SMark Johnston 
25722875f88SMark Johnston static void
258075e2779SMark Johnston tsc_freq_tc(uint64_t *res)
25922875f88SMark Johnston {
26022875f88SMark Johnston 	uint64_t tsc1, tsc2;
26122875f88SMark Johnston 	int64_t overhead;
26222875f88SMark Johnston 	int count, i;
26322875f88SMark Johnston 
26422875f88SMark Johnston 	overhead = 0;
26522875f88SMark Johnston 	for (i = 0, count = 8; i < count; i++) {
26622875f88SMark Johnston 		tsc1 = rdtsc_ordered();
26722875f88SMark Johnston 		DELAY(0);
26822875f88SMark Johnston 		tsc2 = rdtsc_ordered();
26922875f88SMark Johnston 		if (i > 0)
27022875f88SMark Johnston 			overhead += tsc2 - tsc1;
27122875f88SMark Johnston 	}
27222875f88SMark Johnston 	overhead /= count;
27322875f88SMark Johnston 
27422875f88SMark Johnston 	tsc1 = rdtsc_ordered();
27522875f88SMark Johnston 	DELAY(100000);
27622875f88SMark Johnston 	tsc2 = rdtsc_ordered();
27722875f88SMark Johnston 	tsc_freq = (tsc2 - tsc1 - overhead) * 10;
278a4e4127fSJung-uk Kim }
279dd7d207dSJung-uk Kim 
280075e2779SMark Johnston /*
281075e2779SMark Johnston  * Try to determine the TSC frequency using CPUID or hypercalls.  If successful,
282075e2779SMark Johnston  * this lets use the TSC for early DELAY() calls instead of the 8254 timer,
283075e2779SMark Johnston  * which may be unreliable or entirely absent on contemporary systems.  However,
284075e2779SMark Johnston  * avoid calibrating using the 8254 here so as to give hypervisors a chance to
285075e2779SMark Johnston  * register a timecounter that can be used instead.
286075e2779SMark Johnston  */
287a4e4127fSJung-uk Kim static void
288075e2779SMark Johnston probe_tsc_freq_early(void)
289a4e4127fSJung-uk Kim {
29084369dd5SMark Johnston #ifdef __i386__
29184369dd5SMark Johnston 	/* The TSC is known to be broken on certain CPUs. */
29284369dd5SMark Johnston 	switch (cpu_vendor_id) {
29384369dd5SMark Johnston 	case CPU_VENDOR_AMD:
29484369dd5SMark Johnston 		switch (cpu_id & 0xFF0) {
29584369dd5SMark Johnston 		case 0x500:
29684369dd5SMark Johnston 			/* K5 Model 0 */
29784369dd5SMark Johnston 			tsc_disabled = 1;
29884369dd5SMark Johnston 			return;
2995da5812bSJung-uk Kim 		}
30084369dd5SMark Johnston 		break;
30184369dd5SMark Johnston 	case CPU_VENDOR_CENTAUR:
30284369dd5SMark Johnston 		switch (cpu_id & 0xff0) {
30384369dd5SMark Johnston 		case 0x540:
30484369dd5SMark Johnston 			/*
30584369dd5SMark Johnston 			 * http://www.centtech.com/c6_data_sheet.pdf
30684369dd5SMark Johnston 			 *
30784369dd5SMark Johnston 			 * I-12 RDTSC may return incoherent values in EDX:EAX
30884369dd5SMark Johnston 			 * I-13 RDTSC hangs when certain event counters are used
30984369dd5SMark Johnston 			 */
31084369dd5SMark Johnston 			tsc_disabled = 1;
31184369dd5SMark Johnston 			return;
31284369dd5SMark Johnston 		}
31384369dd5SMark Johnston 		break;
31484369dd5SMark Johnston 	case CPU_VENDOR_NSC:
31584369dd5SMark Johnston 		switch (cpu_id & 0xff0) {
31684369dd5SMark Johnston 		case 0x540:
31784369dd5SMark Johnston 			if ((cpu_id & CPUID_STEPPING) == 0) {
31884369dd5SMark Johnston 				tsc_disabled = 1;
31984369dd5SMark Johnston 				return;
32084369dd5SMark Johnston 			}
32184369dd5SMark Johnston 			break;
32284369dd5SMark Johnston 		}
32384369dd5SMark Johnston 		break;
32484369dd5SMark Johnston 	}
32584369dd5SMark Johnston #endif
3265da5812bSJung-uk Kim 
327dd7d207dSJung-uk Kim 	switch (cpu_vendor_id) {
328dd7d207dSJung-uk Kim 	case CPU_VENDOR_AMD:
3292ee49facSKonstantin Belousov 	case CPU_VENDOR_HYGON:
330a106a27cSJung-uk Kim 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
331a106a27cSJung-uk Kim 		    (vm_guest == VM_GUEST_NO &&
332a106a27cSJung-uk Kim 		    CPUID_TO_FAMILY(cpu_id) >= 0x10))
333dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
334814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
335814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
336814124c3SKonstantin Belousov 			    tsc_get_timecount_mfence;
337814124c3SKonstantin Belousov 		}
338dd7d207dSJung-uk Kim 		break;
339dd7d207dSJung-uk Kim 	case CPU_VENDOR_INTEL:
340a106a27cSJung-uk Kim 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
341a106a27cSJung-uk Kim 		    (vm_guest == VM_GUEST_NO &&
342a106a27cSJung-uk Kim 		    ((CPUID_TO_FAMILY(cpu_id) == 0x6 &&
343dd7d207dSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0xe) ||
344dd7d207dSJung-uk Kim 		    (CPUID_TO_FAMILY(cpu_id) == 0xf &&
345a106a27cSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0x3))))
346dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
347814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
348814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
349814124c3SKonstantin Belousov 			    tsc_get_timecount_lfence;
350814124c3SKonstantin Belousov 		}
351dd7d207dSJung-uk Kim 		break;
352dd7d207dSJung-uk Kim 	case CPU_VENDOR_CENTAUR:
353a106a27cSJung-uk Kim 		if (vm_guest == VM_GUEST_NO &&
354a106a27cSJung-uk Kim 		    CPUID_TO_FAMILY(cpu_id) == 0x6 &&
355dd7d207dSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0xf &&
356dd7d207dSJung-uk Kim 		    (rdmsr(0x1203) & 0x100000000ULL) == 0)
357dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
358814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
359814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
360814124c3SKonstantin Belousov 			    tsc_get_timecount_lfence;
361814124c3SKonstantin Belousov 		}
362dd7d207dSJung-uk Kim 		break;
363dd7d207dSJung-uk Kim 	}
364dd7d207dSJung-uk Kim 
36584369dd5SMark Johnston 	if (tsc_freq_cpuid_vm()) {
36684369dd5SMark Johnston 		if (bootverbose)
36784369dd5SMark Johnston 			printf(
36884369dd5SMark Johnston 		    "Early TSC frequency %juHz derived from hypervisor CPUID\n",
36984369dd5SMark Johnston 			    (uintmax_t)tsc_freq);
37084369dd5SMark Johnston 	} else if (vm_guest == VM_GUEST_VMWARE) {
371fd980febSColin Percival 		tsc_freq_vmware();
37284369dd5SMark Johnston 		if (bootverbose)
37384369dd5SMark Johnston 			printf(
37484369dd5SMark Johnston 		    "Early TSC frequency %juHz derived from VMWare hypercall\n",
37584369dd5SMark Johnston 			    (uintmax_t)tsc_freq);
3761ca34862SRoger Pau Monné 	} else if (vm_guest == VM_GUEST_XEN) {
3771ca34862SRoger Pau Monné 		tsc_freq_xen();
3781ca34862SRoger Pau Monné 		if (bootverbose)
3791ca34862SRoger Pau Monné 			printf(
3801ca34862SRoger Pau Monné 			"Early TSC frequency %juHz derived from Xen CPUID\n",
3811ca34862SRoger Pau Monné 			    (uintmax_t)tsc_freq);
38284369dd5SMark Johnston 	} else if (tsc_freq_cpuid(&tsc_freq)) {
383bd8a359fSKonstantin Belousov 		/*
38422875f88SMark Johnston 		 * If possible, use the value obtained from CPUID as the initial
38522875f88SMark Johnston 		 * frequency.  This will be refined later during boot but is
38622875f88SMark Johnston 		 * good enough for now.  The 8254 PIT is not functional on some
38722875f88SMark Johnston 		 * newer platforms anyway, so don't delay our boot for what
38822875f88SMark Johnston 		 * might be a garbage result.  Late calibration is required if
38922875f88SMark Johnston 		 * the initial frequency was obtained from CPUID.16H, as the
39022875f88SMark Johnston 		 * derived value may be off by as much as 1%.
391bd8a359fSKonstantin Belousov 		 */
392a4e4127fSJung-uk Kim 		if (bootverbose)
39322875f88SMark Johnston 			printf("Early TSC frequency %juHz derived from CPUID\n",
39422875f88SMark Johnston 			    (uintmax_t)tsc_freq);
395075e2779SMark Johnston 	}
396075e2779SMark Johnston }
397075e2779SMark Johnston 
398075e2779SMark Johnston /*
399075e2779SMark Johnston  * If we were unable to determine the TSC frequency via CPU registers, try
400075e2779SMark Johnston  * to calibrate against a known clock.
401075e2779SMark Johnston  */
402075e2779SMark Johnston static void
403075e2779SMark Johnston probe_tsc_freq_late(void)
404075e2779SMark Johnston {
405075e2779SMark Johnston 	if (tsc_freq != 0)
406075e2779SMark Johnston 		return;
407075e2779SMark Johnston 
408075e2779SMark Johnston 	if (tsc_skip_calibration) {
40922875f88SMark Johnston 		/*
41022875f88SMark Johnston 		 * Try to parse the brand string to obtain the nominal TSC
41122875f88SMark Johnston 		 * frequency.
41222875f88SMark Johnston 		 */
41322875f88SMark Johnston 		if (cpu_vendor_id == CPU_VENDOR_INTEL &&
41422875f88SMark Johnston 		    tsc_freq_intel_brand(&tsc_freq)) {
41522875f88SMark Johnston 			if (bootverbose)
41622875f88SMark Johnston 				printf(
41722875f88SMark Johnston 		    "Early TSC frequency %juHz derived from brand string\n",
41822875f88SMark Johnston 				    (uintmax_t)tsc_freq);
41922875f88SMark Johnston 		} else {
42022875f88SMark Johnston 			tsc_disabled = 1;
42122875f88SMark Johnston 		}
42222875f88SMark Johnston 	} else {
42322875f88SMark Johnston 		/*
424075e2779SMark Johnston 		 * Calibrate against a timecounter or the 8254 PIT.  This
425075e2779SMark Johnston 		 * estimate will be refined later in tsc_calib().
42622875f88SMark Johnston 		 */
427075e2779SMark Johnston 		tsc_freq_tc(&tsc_freq);
42822875f88SMark Johnston 		if (bootverbose)
42922875f88SMark Johnston 			printf(
43022875f88SMark Johnston 		    "Early TSC frequency %juHz calibrated from 8254 PIT\n",
43122875f88SMark Johnston 			    (uintmax_t)tsc_freq);
43222875f88SMark Johnston 	}
433075e2779SMark Johnston }
434075e2779SMark Johnston 
435075e2779SMark Johnston void
436075e2779SMark Johnston start_TSC(void)
437075e2779SMark Johnston {
438075e2779SMark Johnston 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
439075e2779SMark Johnston 		return;
440075e2779SMark Johnston 
441075e2779SMark Johnston 	probe_tsc_freq_late();
44284369dd5SMark Johnston 
44384369dd5SMark Johnston 	if (cpu_power_ecx & CPUID_PERF_STAT) {
44484369dd5SMark Johnston 		/*
44584369dd5SMark Johnston 		 * XXX Some emulators expose host CPUID without actual support
44684369dd5SMark Johnston 		 * for these MSRs.  We must test whether they really work.
44784369dd5SMark Johnston 		 */
44884369dd5SMark Johnston 		wrmsr(MSR_MPERF, 0);
44984369dd5SMark Johnston 		wrmsr(MSR_APERF, 0);
45084369dd5SMark Johnston 		DELAY(10);
45184369dd5SMark Johnston 		if (rdmsr(MSR_MPERF) > 0 && rdmsr(MSR_APERF) > 0)
45284369dd5SMark Johnston 			tsc_perf_stat = 1;
45384369dd5SMark Johnston 	}
454a4e4127fSJung-uk Kim 
455dd7d207dSJung-uk Kim 	/*
456dd7d207dSJung-uk Kim 	 * Inform CPU accounting about our boot-time clock rate.  This will
457dd7d207dSJung-uk Kim 	 * be updated if someone loads a cpufreq driver after boot that
458dd7d207dSJung-uk Kim 	 * discovers a new max frequency.
45922875f88SMark Johnston 	 *
46022875f88SMark Johnston 	 * The frequency may also be updated after late calibration is complete;
46122875f88SMark Johnston 	 * however, we register the TSC as the ticker now to avoid switching
46222875f88SMark Johnston 	 * counters after much of the kernel has already booted and potentially
46322875f88SMark Johnston 	 * sampled the CPU clock.
464dd7d207dSJung-uk Kim 	 */
465a4e4127fSJung-uk Kim 	if (tsc_freq != 0)
4665ac44f72SJung-uk Kim 		set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
467dd7d207dSJung-uk Kim 
468dd7d207dSJung-uk Kim 	if (tsc_is_invariant)
469dd7d207dSJung-uk Kim 		return;
470dd7d207dSJung-uk Kim 
471dd7d207dSJung-uk Kim 	/* Register to find out about changes in CPU frequency. */
472dd7d207dSJung-uk Kim 	tsc_pre_tag = EVENTHANDLER_REGISTER(cpufreq_pre_change,
473dd7d207dSJung-uk Kim 	    tsc_freq_changing, NULL, EVENTHANDLER_PRI_FIRST);
474dd7d207dSJung-uk Kim 	tsc_post_tag = EVENTHANDLER_REGISTER(cpufreq_post_change,
475dd7d207dSJung-uk Kim 	    tsc_freq_changed, NULL, EVENTHANDLER_PRI_FIRST);
476dd7d207dSJung-uk Kim 	tsc_levels_tag = EVENTHANDLER_REGISTER(cpufreq_levels_changed,
477dd7d207dSJung-uk Kim 	    tsc_levels_changed, NULL, EVENTHANDLER_PRI_ANY);
478dd7d207dSJung-uk Kim }
479dd7d207dSJung-uk Kim 
48065e7d70bSJung-uk Kim #ifdef SMP
48165e7d70bSJung-uk Kim 
482814124c3SKonstantin Belousov /*
483814124c3SKonstantin Belousov  * RDTSC is not a serializing instruction, and does not drain
484814124c3SKonstantin Belousov  * instruction stream, so we need to drain the stream before executing
485814124c3SKonstantin Belousov  * it.  It could be fixed by use of RDTSCP, except the instruction is
486814124c3SKonstantin Belousov  * not available everywhere.
487814124c3SKonstantin Belousov  *
488814124c3SKonstantin Belousov  * Use CPUID for draining in the boot-time SMP constistency test.  The
489814124c3SKonstantin Belousov  * timecounters use MFENCE for AMD CPUs, and LFENCE for others (Intel
490814124c3SKonstantin Belousov  * and VIA) when SSE2 is present, and nothing on older machines which
491814124c3SKonstantin Belousov  * also do not issue RDTSC prematurely.  There, testing for SSE2 and
492e1a18e46SKonstantin Belousov  * vendor is too cumbersome, and we learn about TSC presence from CPUID.
493814124c3SKonstantin Belousov  *
494814124c3SKonstantin Belousov  * Do not use do_cpuid(), since we do not need CPUID results, which
495814124c3SKonstantin Belousov  * have to be written into memory with do_cpuid().
496814124c3SKonstantin Belousov  */
49765e7d70bSJung-uk Kim #define	TSC_READ(x)							\
49865e7d70bSJung-uk Kim static void								\
49965e7d70bSJung-uk Kim tsc_read_##x(void *arg)							\
50065e7d70bSJung-uk Kim {									\
5017bfcb3bbSJim Harris 	uint64_t *tsc = arg;						\
50265e7d70bSJung-uk Kim 	u_int cpu = PCPU_GET(cpuid);					\
50365e7d70bSJung-uk Kim 									\
504814124c3SKonstantin Belousov 	__asm __volatile("cpuid" : : : "eax", "ebx", "ecx", "edx");	\
5057bfcb3bbSJim Harris 	tsc[cpu * 3 + x] = rdtsc();					\
50665e7d70bSJung-uk Kim }
50765e7d70bSJung-uk Kim TSC_READ(0)
50865e7d70bSJung-uk Kim TSC_READ(1)
50965e7d70bSJung-uk Kim TSC_READ(2)
51065e7d70bSJung-uk Kim #undef TSC_READ
51165e7d70bSJung-uk Kim 
51265e7d70bSJung-uk Kim #define	N	1000
51365e7d70bSJung-uk Kim 
51465e7d70bSJung-uk Kim static void
51565e7d70bSJung-uk Kim comp_smp_tsc(void *arg)
51665e7d70bSJung-uk Kim {
5177bfcb3bbSJim Harris 	uint64_t *tsc;
5187bfcb3bbSJim Harris 	int64_t d1, d2;
51965e7d70bSJung-uk Kim 	u_int cpu = PCPU_GET(cpuid);
52065e7d70bSJung-uk Kim 	u_int i, j, size;
52165e7d70bSJung-uk Kim 
52265e7d70bSJung-uk Kim 	size = (mp_maxid + 1) * 3;
52365e7d70bSJung-uk Kim 	for (i = 0, tsc = arg; i < N; i++, tsc += size)
52465e7d70bSJung-uk Kim 		CPU_FOREACH(j) {
52565e7d70bSJung-uk Kim 			if (j == cpu)
52665e7d70bSJung-uk Kim 				continue;
52765e7d70bSJung-uk Kim 			d1 = tsc[cpu * 3 + 1] - tsc[j * 3];
52865e7d70bSJung-uk Kim 			d2 = tsc[cpu * 3 + 2] - tsc[j * 3 + 1];
52965e7d70bSJung-uk Kim 			if (d1 <= 0 || d2 <= 0) {
53065e7d70bSJung-uk Kim 				smp_tsc = 0;
53165e7d70bSJung-uk Kim 				return;
53265e7d70bSJung-uk Kim 			}
53365e7d70bSJung-uk Kim 		}
53465e7d70bSJung-uk Kim }
53565e7d70bSJung-uk Kim 
536b2c63698SAlexander Motin static void
537b2c63698SAlexander Motin adj_smp_tsc(void *arg)
538b2c63698SAlexander Motin {
539b2c63698SAlexander Motin 	uint64_t *tsc;
540b2c63698SAlexander Motin 	int64_t d, min, max;
541b2c63698SAlexander Motin 	u_int cpu = PCPU_GET(cpuid);
542b2c63698SAlexander Motin 	u_int first, i, size;
543b2c63698SAlexander Motin 
544b2c63698SAlexander Motin 	first = CPU_FIRST();
545b2c63698SAlexander Motin 	if (cpu == first)
546b2c63698SAlexander Motin 		return;
547b2c63698SAlexander Motin 	min = INT64_MIN;
548b2c63698SAlexander Motin 	max = INT64_MAX;
549b2c63698SAlexander Motin 	size = (mp_maxid + 1) * 3;
550b2c63698SAlexander Motin 	for (i = 0, tsc = arg; i < N; i++, tsc += size) {
551b2c63698SAlexander Motin 		d = tsc[first * 3] - tsc[cpu * 3 + 1];
552b2c63698SAlexander Motin 		if (d > min)
553b2c63698SAlexander Motin 			min = d;
554b2c63698SAlexander Motin 		d = tsc[first * 3 + 1] - tsc[cpu * 3 + 2];
555b2c63698SAlexander Motin 		if (d > min)
556b2c63698SAlexander Motin 			min = d;
557b2c63698SAlexander Motin 		d = tsc[first * 3 + 1] - tsc[cpu * 3];
558b2c63698SAlexander Motin 		if (d < max)
559b2c63698SAlexander Motin 			max = d;
560b2c63698SAlexander Motin 		d = tsc[first * 3 + 2] - tsc[cpu * 3 + 1];
561b2c63698SAlexander Motin 		if (d < max)
562b2c63698SAlexander Motin 			max = d;
563b2c63698SAlexander Motin 	}
564b2c63698SAlexander Motin 	if (min > max)
565b2c63698SAlexander Motin 		return;
566b2c63698SAlexander Motin 	d = min / 2 + max / 2;
567b2c63698SAlexander Motin 	__asm __volatile (
568b2c63698SAlexander Motin 		"movl $0x10, %%ecx\n\t"
569b2c63698SAlexander Motin 		"rdmsr\n\t"
570b2c63698SAlexander Motin 		"addl %%edi, %%eax\n\t"
571b2c63698SAlexander Motin 		"adcl %%esi, %%edx\n\t"
572b2c63698SAlexander Motin 		"wrmsr\n"
573b2c63698SAlexander Motin 		: /* No output */
574b2c63698SAlexander Motin 		: "D" ((uint32_t)d), "S" ((uint32_t)(d >> 32))
575b2c63698SAlexander Motin 		: "ax", "cx", "dx", "cc"
576b2c63698SAlexander Motin 	);
577b2c63698SAlexander Motin }
578b2c63698SAlexander Motin 
57965e7d70bSJung-uk Kim static int
580279be68bSAndriy Gapon test_tsc(int adj_max_count)
58165e7d70bSJung-uk Kim {
5827bfcb3bbSJim Harris 	uint64_t *data, *tsc;
583b2c63698SAlexander Motin 	u_int i, size, adj;
58465e7d70bSJung-uk Kim 
58584eaf2ccSKonstantin Belousov 	if ((!smp_tsc && !tsc_is_invariant))
58665e7d70bSJung-uk Kim 		return (-100);
5878cc15b0dSKyle Evans 	/*
5888cc15b0dSKyle Evans 	 * Misbehavior of TSC under VirtualBox has been observed.  In
5898cc15b0dSKyle Evans 	 * particular, threads doing small (~1 second) sleeps may miss their
5908cc15b0dSKyle Evans 	 * wakeup and hang around in sleep state, causing hangs on shutdown.
5918cc15b0dSKyle Evans 	 */
5928cc15b0dSKyle Evans 	if (vm_guest == VM_GUEST_VBOX)
5938cc15b0dSKyle Evans 		return (0);
5948cc15b0dSKyle Evans 
595cd165c8bSColin Percival 	TSENTER();
59665e7d70bSJung-uk Kim 	size = (mp_maxid + 1) * 3;
59765e7d70bSJung-uk Kim 	data = malloc(sizeof(*data) * size * N, M_TEMP, M_WAITOK);
598b2c63698SAlexander Motin 	adj = 0;
599b2c63698SAlexander Motin retry:
60065e7d70bSJung-uk Kim 	for (i = 0, tsc = data; i < N; i++, tsc += size)
60165e7d70bSJung-uk Kim 		smp_rendezvous(tsc_read_0, tsc_read_1, tsc_read_2, tsc);
60265e7d70bSJung-uk Kim 	smp_tsc = 1;	/* XXX */
60367d955aaSPatrick Kelsey 	smp_rendezvous(smp_no_rendezvous_barrier, comp_smp_tsc,
60467d955aaSPatrick Kelsey 	    smp_no_rendezvous_barrier, data);
605279be68bSAndriy Gapon 	if (!smp_tsc && adj < adj_max_count) {
606b2c63698SAlexander Motin 		adj++;
60767d955aaSPatrick Kelsey 		smp_rendezvous(smp_no_rendezvous_barrier, adj_smp_tsc,
60867d955aaSPatrick Kelsey 		    smp_no_rendezvous_barrier, data);
609b2c63698SAlexander Motin 		goto retry;
610b2c63698SAlexander Motin 	}
61165e7d70bSJung-uk Kim 	free(data, M_TEMP);
61265e7d70bSJung-uk Kim 	if (bootverbose)
613b2c63698SAlexander Motin 		printf("SMP: %sed TSC synchronization test%s\n",
614b2c63698SAlexander Motin 		    smp_tsc ? "pass" : "fail",
615b2c63698SAlexander Motin 		    adj > 0 ? " after adjustment" : "");
616cd165c8bSColin Percival 	TSEXIT();
61726e6537aSJung-uk Kim 	if (smp_tsc && tsc_is_invariant) {
61826e6537aSJung-uk Kim 		switch (cpu_vendor_id) {
61926e6537aSJung-uk Kim 		case CPU_VENDOR_AMD:
6202ee49facSKonstantin Belousov 		case CPU_VENDOR_HYGON:
62126e6537aSJung-uk Kim 			/*
622450d86fcSJung-uk Kim 			 * Processor Programming Reference (PPR) for AMD
623450d86fcSJung-uk Kim 			 * Family 17h states that the TSC uses a common
624450d86fcSJung-uk Kim 			 * reference for all sockets, cores and threads.
625450d86fcSJung-uk Kim 			 */
626450d86fcSJung-uk Kim 			if (CPUID_TO_FAMILY(cpu_id) >= 0x17)
627450d86fcSJung-uk Kim 				return (1000);
628450d86fcSJung-uk Kim 			/*
62926e6537aSJung-uk Kim 			 * Starting with Family 15h processors, TSC clock
63026e6537aSJung-uk Kim 			 * source is in the north bridge.  Check whether
63126e6537aSJung-uk Kim 			 * we have a single-socket/multi-core platform.
63226e6537aSJung-uk Kim 			 * XXX Need more work for complex cases.
63326e6537aSJung-uk Kim 			 */
63426e6537aSJung-uk Kim 			if (CPUID_TO_FAMILY(cpu_id) < 0x15 ||
63526e6537aSJung-uk Kim 			    (amd_feature2 & AMDID2_CMP) == 0 ||
63626e6537aSJung-uk Kim 			    smp_cpus > (cpu_procinfo2 & AMDID_CMP_CORES) + 1)
63726e6537aSJung-uk Kim 				break;
63826e6537aSJung-uk Kim 			return (1000);
63926e6537aSJung-uk Kim 		case CPU_VENDOR_INTEL:
64026e6537aSJung-uk Kim 			/*
64126e6537aSJung-uk Kim 			 * XXX Assume Intel platforms have synchronized TSCs.
64226e6537aSJung-uk Kim 			 */
64326e6537aSJung-uk Kim 			return (1000);
64426e6537aSJung-uk Kim 		}
64526e6537aSJung-uk Kim 		return (800);
64626e6537aSJung-uk Kim 	}
64726e6537aSJung-uk Kim 	return (-100);
64865e7d70bSJung-uk Kim }
64965e7d70bSJung-uk Kim 
65065e7d70bSJung-uk Kim #undef N
65165e7d70bSJung-uk Kim 
65265e7d70bSJung-uk Kim #endif /* SMP */
65365e7d70bSJung-uk Kim 
65465e7d70bSJung-uk Kim static void
655dd7d207dSJung-uk Kim init_TSC_tc(void)
656dd7d207dSJung-uk Kim {
65795f2f098SJung-uk Kim 	uint64_t max_freq;
65895f2f098SJung-uk Kim 	int shift;
659dd7d207dSJung-uk Kim 
66038b8542cSJung-uk Kim 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
661dd7d207dSJung-uk Kim 		return;
662dd7d207dSJung-uk Kim 
663dd7d207dSJung-uk Kim 	/*
66495f2f098SJung-uk Kim 	 * Limit timecounter frequency to fit in an int and prevent it from
66595f2f098SJung-uk Kim 	 * overflowing too fast.
66695f2f098SJung-uk Kim 	 */
66795f2f098SJung-uk Kim 	max_freq = UINT_MAX;
66895f2f098SJung-uk Kim 
66995f2f098SJung-uk Kim 	/*
67092597e06SJohn Baldwin 	 * Intel CPUs without a C-state invariant TSC can stop the TSC
671d1411416SJohn Baldwin 	 * in either C2 or C3.  Disable use of C2 and C3 while using
672d1411416SJohn Baldwin 	 * the TSC as the timecounter.  The timecounter can be changed
673d1411416SJohn Baldwin 	 * to enable C2 and C3.
674d1411416SJohn Baldwin 	 *
675d1411416SJohn Baldwin 	 * Note that the TSC is used as the cputicker for computing
676d1411416SJohn Baldwin 	 * thread runtime regardless of the timecounter setting, so
677d1411416SJohn Baldwin 	 * using an alternate timecounter and enabling C2 or C3 can
678d1411416SJohn Baldwin 	 * result incorrect runtimes for kernel idle threads (but not
679d1411416SJohn Baldwin 	 * for any non-idle threads).
680a49399a9SJung-uk Kim 	 */
6818cd59625SKonstantin Belousov 	if (cpu_vendor_id == CPU_VENDOR_INTEL &&
682a49399a9SJung-uk Kim 	    (amd_pminfo & AMDPM_TSC_INVARIANT) == 0) {
68392597e06SJohn Baldwin 		tsc_timecounter.tc_flags |= TC_FLAGS_C2STOP;
684a49399a9SJung-uk Kim 		if (bootverbose)
685d1411416SJohn Baldwin 			printf("TSC timecounter disables C2 and C3.\n");
686a49399a9SJung-uk Kim 	}
687a49399a9SJung-uk Kim 
688dd7d207dSJung-uk Kim 	/*
689e7f1427dSKonstantin Belousov 	 * We can not use the TSC in SMP mode unless the TSCs on all CPUs
690e7f1427dSKonstantin Belousov 	 * are synchronized.  If the user is sure that the system has
691e7f1427dSKonstantin Belousov 	 * synchronized TSCs, set kern.timecounter.smp_tsc tunable to a
692e7f1427dSKonstantin Belousov 	 * non-zero value.  The TSC seems unreliable in virtualized SMP
6935cf8ac1bSMike Silbersack 	 * environments, so it is set to a negative quality in those cases.
694dd7d207dSJung-uk Kim 	 */
695ba79ab82SAndriy Gapon #ifdef SMP
696e7f1427dSKonstantin Belousov 	if (mp_ncpus > 1)
697279be68bSAndriy Gapon 		tsc_timecounter.tc_quality = test_tsc(smp_tsc_adjust);
698ba79ab82SAndriy Gapon 	else
699ba79ab82SAndriy Gapon #endif /* SMP */
700ba79ab82SAndriy Gapon 	if (tsc_is_invariant)
70126e6537aSJung-uk Kim 		tsc_timecounter.tc_quality = 1000;
702e7f1427dSKonstantin Belousov 	max_freq >>= tsc_shift;
70326e6537aSJung-uk Kim 
704e7f1427dSKonstantin Belousov 	for (shift = 0; shift <= 31 && (tsc_freq >> shift) > max_freq; shift++)
70595f2f098SJung-uk Kim 		;
7069e680e40SKonstantin Belousov 
7079e680e40SKonstantin Belousov 	/*
7089e680e40SKonstantin Belousov 	 * Timecounter implementation selection, top to bottom:
7099e680e40SKonstantin Belousov 	 * - If RDTSCP is available, use RDTSCP.
7109e680e40SKonstantin Belousov 	 * - If fence instructions are provided (SSE2), use LFENCE;RDTSC
7119e680e40SKonstantin Belousov 	 *   on Intel, and MFENCE;RDTSC on AMD.
7129e680e40SKonstantin Belousov 	 * - For really old CPUs, just use RDTSC.
7139e680e40SKonstantin Belousov 	 */
7149f47eeffSKonstantin Belousov 	if ((amd_feature & AMDID_RDTSCP) != 0) {
7159e680e40SKonstantin Belousov 		tsc_timecounter.tc_get_timecount = shift > 0 ?
7169e680e40SKonstantin Belousov 		    tscp_get_timecount_low : tscp_get_timecount;
7179e680e40SKonstantin Belousov 	} else if ((cpu_feature & CPUID_SSE2) != 0 && mp_ncpus > 1) {
7182ee49facSKonstantin Belousov 		if (cpu_vendor_id == CPU_VENDOR_AMD ||
7192ee49facSKonstantin Belousov 		    cpu_vendor_id == CPU_VENDOR_HYGON) {
720e7f1427dSKonstantin Belousov 			tsc_timecounter.tc_get_timecount = shift > 0 ?
721e7f1427dSKonstantin Belousov 			    tsc_get_timecount_low_mfence :
722e7f1427dSKonstantin Belousov 			    tsc_get_timecount_mfence;
723814124c3SKonstantin Belousov 		} else {
724e7f1427dSKonstantin Belousov 			tsc_timecounter.tc_get_timecount = shift > 0 ?
725e7f1427dSKonstantin Belousov 			    tsc_get_timecount_low_lfence :
726e7f1427dSKonstantin Belousov 			    tsc_get_timecount_lfence;
727814124c3SKonstantin Belousov 		}
728e7f1427dSKonstantin Belousov 	} else {
729e7f1427dSKonstantin Belousov 		tsc_timecounter.tc_get_timecount = shift > 0 ?
730e7f1427dSKonstantin Belousov 		    tsc_get_timecount_low : tsc_get_timecount;
731e7f1427dSKonstantin Belousov 	}
732e7f1427dSKonstantin Belousov 	if (shift > 0) {
73395f2f098SJung-uk Kim 		tsc_timecounter.tc_name = "TSC-low";
73495f2f098SJung-uk Kim 		if (bootverbose)
735bc8e4ad2SJung-uk Kim 			printf("TSC timecounter discards lower %d bit(s)\n",
73695f2f098SJung-uk Kim 			    shift);
73795f2f098SJung-uk Kim 	}
738bc34c87eSJung-uk Kim 	if (tsc_freq != 0) {
73995f2f098SJung-uk Kim 		tsc_timecounter.tc_frequency = tsc_freq >> shift;
74095f2f098SJung-uk Kim 		tsc_timecounter.tc_priv = (void *)(intptr_t)shift;
74122875f88SMark Johnston 
74222875f88SMark Johnston 		/*
74322875f88SMark Johnston 		 * Timecounter registration is deferred until after late
74422875f88SMark Johnston 		 * calibration is finished.
74522875f88SMark Johnston 		 */
746dd7d207dSJung-uk Kim 	}
747dd7d207dSJung-uk Kim }
74865e7d70bSJung-uk Kim SYSINIT(tsc_tc, SI_SUB_SMP, SI_ORDER_ANY, init_TSC_tc, NULL);
749dd7d207dSJung-uk Kim 
75022875f88SMark Johnston static void
75122875f88SMark Johnston tsc_update_freq(uint64_t new_freq)
75222875f88SMark Johnston {
75322875f88SMark Johnston 	atomic_store_rel_64(&tsc_freq, new_freq);
75422875f88SMark Johnston 	atomic_store_rel_64(&tsc_timecounter.tc_frequency,
75522875f88SMark Johnston 	    new_freq >> (int)(intptr_t)tsc_timecounter.tc_priv);
75622875f88SMark Johnston }
75722875f88SMark Johnston 
75884369dd5SMark Johnston void
75984369dd5SMark Johnston tsc_init(void)
76084369dd5SMark Johnston {
76184369dd5SMark Johnston 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
76284369dd5SMark Johnston 		return;
76384369dd5SMark Johnston 
764075e2779SMark Johnston 	probe_tsc_freq_early();
76584369dd5SMark Johnston }
76684369dd5SMark Johnston 
76722875f88SMark Johnston /*
76822875f88SMark Johnston  * Perform late calibration of the TSC frequency once ACPI-based timecounters
769553af8f1SMark Johnston  * are available.  At this point timehands are not set up, so we read the
770553af8f1SMark Johnston  * highest-quality timecounter directly rather than using (s)binuptime().
77122875f88SMark Johnston  */
772553af8f1SMark Johnston void
773553af8f1SMark Johnston tsc_calibrate(void)
77422875f88SMark Johnston {
775c2705ceaSColin Percival 	uint64_t freq;
77622875f88SMark Johnston 
77722875f88SMark Johnston 	if (tsc_disabled)
77822875f88SMark Johnston 		return;
7799cb32882SColin Percival 	if (tsc_early_calib_exact)
7809cb32882SColin Percival 		goto calibrated;
78122875f88SMark Johnston 
782c2705ceaSColin Percival 	fpu_kern_enter(curthread, NULL, FPU_KERN_NOCTX);
783c2705ceaSColin Percival 	freq = clockcalib(rdtsc_ordered, "TSC");
784c2705ceaSColin Percival 	fpu_kern_leave(curthread, NULL);
785698727d6SColin Percival 	tsc_update_freq(freq);
786c2705ceaSColin Percival 
7879cb32882SColin Percival calibrated:
78822875f88SMark Johnston 	tc_init(&tsc_timecounter);
78922875f88SMark Johnston 	set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
79022875f88SMark Johnston }
79122875f88SMark Johnston 
792279be68bSAndriy Gapon void
793279be68bSAndriy Gapon resume_TSC(void)
794279be68bSAndriy Gapon {
795ba79ab82SAndriy Gapon #ifdef SMP
796279be68bSAndriy Gapon 	int quality;
797279be68bSAndriy Gapon 
798279be68bSAndriy Gapon 	/* If TSC was not good on boot, it is unlikely to become good now. */
799279be68bSAndriy Gapon 	if (tsc_timecounter.tc_quality < 0)
800279be68bSAndriy Gapon 		return;
801279be68bSAndriy Gapon 	/* Nothing to do with UP. */
802279be68bSAndriy Gapon 	if (mp_ncpus < 2)
803279be68bSAndriy Gapon 		return;
804279be68bSAndriy Gapon 
805279be68bSAndriy Gapon 	/*
806279be68bSAndriy Gapon 	 * If TSC was good, a single synchronization should be enough,
807279be68bSAndriy Gapon 	 * but honour smp_tsc_adjust if it's set.
808279be68bSAndriy Gapon 	 */
809279be68bSAndriy Gapon 	quality = test_tsc(MAX(smp_tsc_adjust, 1));
810279be68bSAndriy Gapon 	if (quality != tsc_timecounter.tc_quality) {
811279be68bSAndriy Gapon 		printf("TSC timecounter quality changed: %d -> %d\n",
812279be68bSAndriy Gapon 		    tsc_timecounter.tc_quality, quality);
813279be68bSAndriy Gapon 		tsc_timecounter.tc_quality = quality;
814279be68bSAndriy Gapon 	}
815ba79ab82SAndriy Gapon #endif /* SMP */
816279be68bSAndriy Gapon }
817279be68bSAndriy Gapon 
818dd7d207dSJung-uk Kim /*
819dd7d207dSJung-uk Kim  * When cpufreq levels change, find out about the (new) max frequency.  We
820dd7d207dSJung-uk Kim  * use this to update CPU accounting in case it got a lower estimate at boot.
821dd7d207dSJung-uk Kim  */
822dd7d207dSJung-uk Kim static void
823dd7d207dSJung-uk Kim tsc_levels_changed(void *arg, int unit)
824dd7d207dSJung-uk Kim {
825dd7d207dSJung-uk Kim 	device_t cf_dev;
826dd7d207dSJung-uk Kim 	struct cf_level *levels;
827dd7d207dSJung-uk Kim 	int count, error;
828dd7d207dSJung-uk Kim 	uint64_t max_freq;
829dd7d207dSJung-uk Kim 
830dd7d207dSJung-uk Kim 	/* Only use values from the first CPU, assuming all are equal. */
831dd7d207dSJung-uk Kim 	if (unit != 0)
832dd7d207dSJung-uk Kim 		return;
833dd7d207dSJung-uk Kim 
834dd7d207dSJung-uk Kim 	/* Find the appropriate cpufreq device instance. */
835dd7d207dSJung-uk Kim 	cf_dev = devclass_get_device(devclass_find("cpufreq"), unit);
836dd7d207dSJung-uk Kim 	if (cf_dev == NULL) {
837dd7d207dSJung-uk Kim 		printf("tsc_levels_changed() called but no cpufreq device?\n");
838dd7d207dSJung-uk Kim 		return;
839dd7d207dSJung-uk Kim 	}
840dd7d207dSJung-uk Kim 
841dd7d207dSJung-uk Kim 	/* Get settings from the device and find the max frequency. */
842dd7d207dSJung-uk Kim 	count = 64;
843dd7d207dSJung-uk Kim 	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
844dd7d207dSJung-uk Kim 	if (levels == NULL)
845dd7d207dSJung-uk Kim 		return;
846dd7d207dSJung-uk Kim 	error = CPUFREQ_LEVELS(cf_dev, levels, &count);
847dd7d207dSJung-uk Kim 	if (error == 0 && count != 0) {
848dd7d207dSJung-uk Kim 		max_freq = (uint64_t)levels[0].total_set.freq * 1000000;
8498701571dSMitchell Horne 		set_cputicker(rdtsc, max_freq, true);
850dd7d207dSJung-uk Kim 	} else
851dd7d207dSJung-uk Kim 		printf("tsc_levels_changed: no max freq found\n");
852dd7d207dSJung-uk Kim 	free(levels, M_TEMP);
853dd7d207dSJung-uk Kim }
854dd7d207dSJung-uk Kim 
855dd7d207dSJung-uk Kim /*
856dd7d207dSJung-uk Kim  * If the TSC timecounter is in use, veto the pending change.  It may be
857dd7d207dSJung-uk Kim  * possible in the future to handle a dynamically-changing timecounter rate.
858dd7d207dSJung-uk Kim  */
859dd7d207dSJung-uk Kim static void
860dd7d207dSJung-uk Kim tsc_freq_changing(void *arg, const struct cf_level *level, int *status)
861dd7d207dSJung-uk Kim {
862dd7d207dSJung-uk Kim 
863dd7d207dSJung-uk Kim 	if (*status != 0 || timecounter != &tsc_timecounter)
864dd7d207dSJung-uk Kim 		return;
865dd7d207dSJung-uk Kim 
866dd7d207dSJung-uk Kim 	printf("timecounter TSC must not be in use when "
867dd7d207dSJung-uk Kim 	    "changing frequencies; change denied\n");
868dd7d207dSJung-uk Kim 	*status = EBUSY;
869dd7d207dSJung-uk Kim }
870dd7d207dSJung-uk Kim 
871dd7d207dSJung-uk Kim /* Update TSC freq with the value indicated by the caller. */
872dd7d207dSJung-uk Kim static void
873dd7d207dSJung-uk Kim tsc_freq_changed(void *arg, const struct cf_level *level, int status)
874dd7d207dSJung-uk Kim {
8753453537fSJung-uk Kim 	uint64_t freq;
876dd7d207dSJung-uk Kim 
877dd7d207dSJung-uk Kim 	/* If there was an error during the transition, don't do anything. */
87879422085SJung-uk Kim 	if (tsc_disabled || status != 0)
879dd7d207dSJung-uk Kim 		return;
880dd7d207dSJung-uk Kim 
881dd7d207dSJung-uk Kim 	/* Total setting for this level gives the new frequency in MHz. */
8823453537fSJung-uk Kim 	freq = (uint64_t)level->total_set.freq * 1000000;
88322875f88SMark Johnston 	tsc_update_freq(freq);
884dd7d207dSJung-uk Kim }
885dd7d207dSJung-uk Kim 
886dd7d207dSJung-uk Kim static int
887dd7d207dSJung-uk Kim sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
888dd7d207dSJung-uk Kim {
889dd7d207dSJung-uk Kim 	int error;
890dd7d207dSJung-uk Kim 	uint64_t freq;
891dd7d207dSJung-uk Kim 
8923453537fSJung-uk Kim 	freq = atomic_load_acq_64(&tsc_freq);
8933453537fSJung-uk Kim 	if (freq == 0)
894dd7d207dSJung-uk Kim 		return (EOPNOTSUPP);
895cbc134adSMatthew D Fleming 	error = sysctl_handle_64(oidp, &freq, 0, req);
89622875f88SMark Johnston 	if (error == 0 && req->newptr != NULL)
89722875f88SMark Johnston 		tsc_update_freq(freq);
898dd7d207dSJung-uk Kim 	return (error);
899dd7d207dSJung-uk Kim }
9007029da5cSPawel Biernacki SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq,
9011d6fb900SAlexander Motin     CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
9027029da5cSPawel Biernacki     0, 0, sysctl_machdep_tsc_freq, "QU",
9037029da5cSPawel Biernacki     "Time Stamp Counter frequency");
904dd7d207dSJung-uk Kim 
905727c7b2dSJung-uk Kim static u_int
90695f2f098SJung-uk Kim tsc_get_timecount(struct timecounter *tc __unused)
907dd7d207dSJung-uk Kim {
908727c7b2dSJung-uk Kim 
909727c7b2dSJung-uk Kim 	return (rdtsc32());
910dd7d207dSJung-uk Kim }
91195f2f098SJung-uk Kim 
9129e680e40SKonstantin Belousov static u_int
9139e680e40SKonstantin Belousov tscp_get_timecount(struct timecounter *tc __unused)
9149e680e40SKonstantin Belousov {
9159e680e40SKonstantin Belousov 
9169e680e40SKonstantin Belousov 	return (rdtscp32());
9179e680e40SKonstantin Belousov }
9189e680e40SKonstantin Belousov 
919814124c3SKonstantin Belousov static inline u_int
920bc8e4ad2SJung-uk Kim tsc_get_timecount_low(struct timecounter *tc)
92195f2f098SJung-uk Kim {
9225df88f46SJung-uk Kim 	uint32_t rv;
92395f2f098SJung-uk Kim 
9245df88f46SJung-uk Kim 	__asm __volatile("rdtsc; shrd %%cl, %%edx, %0"
9255df88f46SJung-uk Kim 	    : "=a" (rv) : "c" ((int)(intptr_t)tc->tc_priv) : "edx");
9265df88f46SJung-uk Kim 	return (rv);
92795f2f098SJung-uk Kim }
928aea81038SKonstantin Belousov 
929814124c3SKonstantin Belousov static u_int
9309e680e40SKonstantin Belousov tscp_get_timecount_low(struct timecounter *tc)
9319e680e40SKonstantin Belousov {
9329e680e40SKonstantin Belousov 	uint32_t rv;
9339e680e40SKonstantin Belousov 
9349e680e40SKonstantin Belousov 	__asm __volatile("rdtscp; movl %1, %%ecx; shrd %%cl, %%edx, %0"
935a013e285SKonstantin Belousov 	    : "=&a" (rv) : "m" (tc->tc_priv) : "ecx", "edx");
9369e680e40SKonstantin Belousov 	return (rv);
9379e680e40SKonstantin Belousov }
9389e680e40SKonstantin Belousov 
9399e680e40SKonstantin Belousov static u_int
940814124c3SKonstantin Belousov tsc_get_timecount_lfence(struct timecounter *tc __unused)
941814124c3SKonstantin Belousov {
942814124c3SKonstantin Belousov 
943814124c3SKonstantin Belousov 	lfence();
944814124c3SKonstantin Belousov 	return (rdtsc32());
945814124c3SKonstantin Belousov }
946814124c3SKonstantin Belousov 
947814124c3SKonstantin Belousov static u_int
948814124c3SKonstantin Belousov tsc_get_timecount_low_lfence(struct timecounter *tc)
949814124c3SKonstantin Belousov {
950814124c3SKonstantin Belousov 
951814124c3SKonstantin Belousov 	lfence();
952814124c3SKonstantin Belousov 	return (tsc_get_timecount_low(tc));
953814124c3SKonstantin Belousov }
954814124c3SKonstantin Belousov 
955814124c3SKonstantin Belousov static u_int
956814124c3SKonstantin Belousov tsc_get_timecount_mfence(struct timecounter *tc __unused)
957814124c3SKonstantin Belousov {
958814124c3SKonstantin Belousov 
959814124c3SKonstantin Belousov 	mfence();
960814124c3SKonstantin Belousov 	return (rdtsc32());
961814124c3SKonstantin Belousov }
962814124c3SKonstantin Belousov 
963814124c3SKonstantin Belousov static u_int
964814124c3SKonstantin Belousov tsc_get_timecount_low_mfence(struct timecounter *tc)
965814124c3SKonstantin Belousov {
966814124c3SKonstantin Belousov 
967814124c3SKonstantin Belousov 	mfence();
968814124c3SKonstantin Belousov 	return (tsc_get_timecount_low(tc));
969814124c3SKonstantin Belousov }
970814124c3SKonstantin Belousov 
97116808549SKonstantin Belousov static uint32_t
97216808549SKonstantin Belousov x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th, struct timecounter *tc)
973aea81038SKonstantin Belousov {
974aea81038SKonstantin Belousov 
97516808549SKonstantin Belousov 	vdso_th->th_algo = VDSO_TH_ALGO_X86_TSC;
976d1b1b600SNeel Natu 	vdso_th->th_x86_shift = (int)(intptr_t)tc->tc_priv;
97716808549SKonstantin Belousov 	vdso_th->th_x86_hpet_idx = 0xffffffff;
978d4b2d303SAdam Fenn 	vdso_th->th_x86_pvc_last_systime = 0;
979d4b2d303SAdam Fenn 	vdso_th->th_x86_pvc_stable_mask = 0;
980aea81038SKonstantin Belousov 	bzero(vdso_th->th_res, sizeof(vdso_th->th_res));
98116808549SKonstantin Belousov 	return (1);
982aea81038SKonstantin Belousov }
983aea81038SKonstantin Belousov 
984aea81038SKonstantin Belousov #ifdef COMPAT_FREEBSD32
98516808549SKonstantin Belousov static uint32_t
98616808549SKonstantin Belousov x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
987d1b1b600SNeel Natu     struct timecounter *tc)
988aea81038SKonstantin Belousov {
989aea81038SKonstantin Belousov 
99016808549SKonstantin Belousov 	vdso_th32->th_algo = VDSO_TH_ALGO_X86_TSC;
991d1b1b600SNeel Natu 	vdso_th32->th_x86_shift = (int)(intptr_t)tc->tc_priv;
99216808549SKonstantin Belousov 	vdso_th32->th_x86_hpet_idx = 0xffffffff;
993*93626d54SKonstantin Belousov 	vdso_th32->th_x86_pvc_last_systime[0] = 0;
994*93626d54SKonstantin Belousov 	vdso_th32->th_x86_pvc_last_systime[1] = 0;
995d4b2d303SAdam Fenn 	vdso_th32->th_x86_pvc_stable_mask = 0;
996aea81038SKonstantin Belousov 	bzero(vdso_th32->th_res, sizeof(vdso_th32->th_res));
99716808549SKonstantin Belousov 	return (1);
998aea81038SKonstantin Belousov }
999aea81038SKonstantin Belousov #endif
1000