xref: /freebsd/sys/x86/x86/tsc.c (revision ecaab0fb)
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 #include "opt_clock.h"
31dd7d207dSJung-uk Kim 
32dd7d207dSJung-uk Kim #include <sys/param.h>
3322875f88SMark Johnston #include <sys/systm.h>
34dd7d207dSJung-uk Kim #include <sys/bus.h>
35dd7d207dSJung-uk Kim #include <sys/cpu.h>
36e2e050c8SConrad Meyer #include <sys/eventhandler.h>
375da5812bSJung-uk Kim #include <sys/limits.h>
38dd7d207dSJung-uk Kim #include <sys/malloc.h>
3922875f88SMark Johnston #include <sys/proc.h>
4022875f88SMark Johnston #include <sys/sched.h>
41dd7d207dSJung-uk Kim #include <sys/sysctl.h>
42dd7d207dSJung-uk Kim #include <sys/time.h>
43dd7d207dSJung-uk Kim #include <sys/timetc.h>
44dd7d207dSJung-uk Kim #include <sys/kernel.h>
45dd7d207dSJung-uk Kim #include <sys/smp.h>
46aea81038SKonstantin Belousov #include <sys/vdso.h>
47dd7d207dSJung-uk Kim #include <machine/clock.h>
48dd7d207dSJung-uk Kim #include <machine/cputypes.h>
49c2705ceaSColin Percival #include <machine/fpu.h>
50dd7d207dSJung-uk Kim #include <machine/md_var.h>
51dd7d207dSJung-uk Kim #include <machine/specialreg.h>
5201e1933dSJohn Baldwin #include <x86/vmware.h>
5316808549SKonstantin Belousov #include <dev/acpica/acpi_hpet.h>
54ce3bf750SKonstantin Belousov #include <contrib/dev/acpica/include/acpi.h>
55dd7d207dSJung-uk Kim 
56dd7d207dSJung-uk Kim #include "cpufreq_if.h"
57dd7d207dSJung-uk Kim 
58dd7d207dSJung-uk Kim uint64_t	tsc_freq;
59dd7d207dSJung-uk Kim int		tsc_is_invariant;
60155094d7SJung-uk Kim int		tsc_perf_stat;
619cb32882SColin Percival static int	tsc_early_calib_exact;
62155094d7SJung-uk Kim 
63dd7d207dSJung-uk Kim static eventhandler_tag tsc_levels_tag, tsc_pre_tag, tsc_post_tag;
64dd7d207dSJung-uk Kim 
65dd7d207dSJung-uk Kim SYSCTL_INT(_kern_timecounter, OID_AUTO, invariant_tsc, CTLFLAG_RDTUN,
66dd7d207dSJung-uk Kim     &tsc_is_invariant, 0, "Indicates whether the TSC is P-state invariant");
67dd7d207dSJung-uk Kim 
68dd7d207dSJung-uk Kim #ifdef SMP
691472b87fSNeel Natu int	smp_tsc;
70dd7d207dSJung-uk Kim SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc, CTLFLAG_RDTUN, &smp_tsc, 0,
71dd7d207dSJung-uk Kim     "Indicates whether the TSC is safe to use in SMP mode");
72b2c63698SAlexander Motin 
73b2c63698SAlexander Motin int	smp_tsc_adjust = 0;
74b2c63698SAlexander Motin SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc_adjust, CTLFLAG_RDTUN,
75b2c63698SAlexander Motin     &smp_tsc_adjust, 0, "Try to adjust TSC on APs to match BSP");
76dd7d207dSJung-uk Kim #endif
77dd7d207dSJung-uk Kim 
78e7f1427dSKonstantin Belousov static int	tsc_shift = 1;
79e7f1427dSKonstantin Belousov SYSCTL_INT(_kern_timecounter, OID_AUTO, tsc_shift, CTLFLAG_RDTUN,
80e7f1427dSKonstantin Belousov     &tsc_shift, 0, "Shift to pre-apply for the maximum TSC frequency");
81e7f1427dSKonstantin Belousov 
8279422085SJung-uk Kim static int	tsc_disabled;
8379422085SJung-uk Kim SYSCTL_INT(_machdep, OID_AUTO, disable_tsc, CTLFLAG_RDTUN, &tsc_disabled, 0,
8479422085SJung-uk Kim     "Disable x86 Time Stamp Counter");
8579422085SJung-uk Kim 
86a4e4127fSJung-uk Kim static int	tsc_skip_calibration;
87ab23c278SKonstantin Belousov SYSCTL_INT(_machdep, OID_AUTO, disable_tsc_calibration, CTLFLAG_RDTUN,
88ab23c278SKonstantin Belousov     &tsc_skip_calibration, 0,
8922875f88SMark Johnston     "Disable early TSC frequency calibration");
90a4e4127fSJung-uk Kim 
91dd7d207dSJung-uk Kim static void tsc_freq_changed(void *arg, const struct cf_level *level,
92dd7d207dSJung-uk Kim     int status);
93dd7d207dSJung-uk Kim static void tsc_freq_changing(void *arg, const struct cf_level *level,
94dd7d207dSJung-uk Kim     int *status);
95826fc3ccSKonstantin Belousov static u_int tsc_get_timecount(struct timecounter *tc);
96826fc3ccSKonstantin Belousov static inline u_int tsc_get_timecount_low(struct timecounter *tc);
97826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_lfence(struct timecounter *tc);
98826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_low_lfence(struct timecounter *tc);
99826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_mfence(struct timecounter *tc);
100826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_low_mfence(struct timecounter *tc);
1019e680e40SKonstantin Belousov static u_int tscp_get_timecount(struct timecounter *tc);
1029e680e40SKonstantin Belousov static u_int tscp_get_timecount_low(struct timecounter *tc);
103dd7d207dSJung-uk Kim static void tsc_levels_changed(void *arg, int unit);
10416808549SKonstantin Belousov static uint32_t x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th,
10516808549SKonstantin Belousov     struct timecounter *tc);
10616808549SKonstantin Belousov #ifdef COMPAT_FREEBSD32
10716808549SKonstantin Belousov static uint32_t x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
10816808549SKonstantin Belousov     struct timecounter *tc);
10916808549SKonstantin Belousov #endif
110dd7d207dSJung-uk Kim 
111dd7d207dSJung-uk Kim static struct timecounter tsc_timecounter = {
11216808549SKonstantin Belousov 	.tc_get_timecount =		tsc_get_timecount,
11316808549SKonstantin Belousov 	.tc_counter_mask =		~0u,
11416808549SKonstantin Belousov 	.tc_name =			"TSC",
11516808549SKonstantin Belousov 	.tc_quality =			800,	/* adjusted in code */
11616808549SKonstantin Belousov 	.tc_fill_vdso_timehands = 	x86_tsc_vdso_timehands,
11716808549SKonstantin Belousov #ifdef COMPAT_FREEBSD32
11816808549SKonstantin Belousov 	.tc_fill_vdso_timehands32 = 	x86_tsc_vdso_timehands32,
11916808549SKonstantin Belousov #endif
120dd7d207dSJung-uk Kim };
121dd7d207dSJung-uk Kim 
1224a432614SColin Percival static int
tsc_freq_cpuid_vm(void)1234a432614SColin Percival tsc_freq_cpuid_vm(void)
1244a432614SColin Percival {
1254a432614SColin Percival 	u_int regs[4];
1264a432614SColin Percival 
1274a432614SColin Percival 	if (vm_guest == VM_GUEST_NO)
1284a432614SColin Percival 		return (false);
1294a432614SColin Percival 	if (hv_high < 0x40000010)
1304a432614SColin Percival 		return (false);
1314a432614SColin Percival 	do_cpuid(0x40000010, regs);
1324a432614SColin Percival 	tsc_freq = (uint64_t)(regs[0]) * 1000;
1334a432614SColin Percival 	tsc_early_calib_exact = 1;
1344a432614SColin Percival 	return (true);
1354a432614SColin Percival }
1364a432614SColin Percival 
13701e1933dSJohn Baldwin static void
tsc_freq_vmware(void)1385da5812bSJung-uk Kim tsc_freq_vmware(void)
1395da5812bSJung-uk Kim {
1405da5812bSJung-uk Kim 	u_int regs[4];
1415da5812bSJung-uk Kim 
142*ecaab0fbSStephen J. Kiernan 	vmware_hvcall(0, VMW_HVCMD_GETHZ, VMW_HVCMD_DEFAULT_PARAM, regs);
1435da5812bSJung-uk Kim 	if (regs[1] != UINT_MAX)
1445da5812bSJung-uk Kim 		tsc_freq = regs[0] | ((uint64_t)regs[1] << 32);
1459cb32882SColin Percival 	tsc_early_calib_exact = 1;
1465da5812bSJung-uk Kim }
1475da5812bSJung-uk Kim 
1481ca34862SRoger Pau Monné static void
tsc_freq_xen(void)1491ca34862SRoger Pau Monné tsc_freq_xen(void)
1501ca34862SRoger Pau Monné {
1511ca34862SRoger Pau Monné 	u_int regs[4];
1521ca34862SRoger Pau Monné 
1531ca34862SRoger Pau Monné 	/*
1541ca34862SRoger Pau Monné 	 * Must run *after* generic tsc_freq_cpuid_vm, so that when Xen is
1551ca34862SRoger Pau Monné 	 * emulating Viridian support the Viridian leaf is used instead.
1561ca34862SRoger Pau Monné 	 */
1571ca34862SRoger Pau Monné 	KASSERT(hv_high >= 0x40000003, ("Invalid max hypervisor leaf on Xen"));
1581ca34862SRoger Pau Monné 	cpuid_count(0x40000003, 0, regs);
1591ca34862SRoger Pau Monné 	tsc_freq = (uint64_t)(regs[2]) * 1000;
1601ca34862SRoger Pau Monné 	tsc_early_calib_exact = 1;
1611ca34862SRoger Pau Monné }
1621ca34862SRoger Pau Monné 
163506a906cSKonstantin Belousov /*
16422875f88SMark Johnston  * Calculate TSC frequency using information from the CPUID leaf 0x15 'Time
16522875f88SMark Johnston  * Stamp Counter and Nominal Core Crystal Clock'.  If leaf 0x15 is not
16622875f88SMark Johnston  * functional, as it is on Skylake/Kabylake, try 0x16 'Processor Frequency
16722875f88SMark Johnston  * Information'.  Leaf 0x16 is described in the SDM as informational only, but
16822875f88SMark Johnston  * we can use this value until late calibration is complete.
169506a906cSKonstantin Belousov  */
170506a906cSKonstantin Belousov static bool
tsc_freq_cpuid(uint64_t * res)171bd8a359fSKonstantin Belousov tsc_freq_cpuid(uint64_t *res)
172506a906cSKonstantin Belousov {
173506a906cSKonstantin Belousov 	u_int regs[4];
174506a906cSKonstantin Belousov 
175506a906cSKonstantin Belousov 	if (cpu_high < 0x15)
176506a906cSKonstantin Belousov 		return (false);
177506a906cSKonstantin Belousov 	do_cpuid(0x15, regs);
178a9d0e007SKonstantin Belousov 	if (regs[0] != 0 && regs[1] != 0 && regs[2] != 0) {
179bd8a359fSKonstantin Belousov 		*res = (uint64_t)regs[2] * regs[1] / regs[0];
180506a906cSKonstantin Belousov 		return (true);
181506a906cSKonstantin Belousov 	}
182506a906cSKonstantin Belousov 
183a9d0e007SKonstantin Belousov 	if (cpu_high < 0x16)
184a9d0e007SKonstantin Belousov 		return (false);
185a9d0e007SKonstantin Belousov 	do_cpuid(0x16, regs);
186a9d0e007SKonstantin Belousov 	if (regs[0] != 0) {
187bd8a359fSKonstantin Belousov 		*res = (uint64_t)regs[0] * 1000000;
188a9d0e007SKonstantin Belousov 		return (true);
189a9d0e007SKonstantin Belousov 	}
190a9d0e007SKonstantin Belousov 
191a9d0e007SKonstantin Belousov 	return (false);
192a9d0e007SKonstantin Belousov }
193a9d0e007SKonstantin Belousov 
19422875f88SMark Johnston static bool
tsc_freq_intel_brand(uint64_t * res)19522875f88SMark Johnston tsc_freq_intel_brand(uint64_t *res)
196dd7d207dSJung-uk Kim {
197a4e4127fSJung-uk Kim 	char brand[48];
198a4e4127fSJung-uk Kim 	u_int regs[4];
199a4e4127fSJung-uk Kim 	uint64_t freq;
200a4e4127fSJung-uk Kim 	char *p;
201a4e4127fSJung-uk Kim 	u_int i;
202dd7d207dSJung-uk Kim 
203a4e4127fSJung-uk Kim 	/*
204a4e4127fSJung-uk Kim 	 * Intel Processor Identification and the CPUID Instruction
205a4e4127fSJung-uk Kim 	 * Application Note 485.
206a4e4127fSJung-uk Kim 	 * http://www.intel.com/assets/pdf/appnote/241618.pdf
207a4e4127fSJung-uk Kim 	 */
208a4e4127fSJung-uk Kim 	if (cpu_exthigh >= 0x80000004) {
209a4e4127fSJung-uk Kim 		p = brand;
210a4e4127fSJung-uk Kim 		for (i = 0x80000002; i < 0x80000005; i++) {
211a4e4127fSJung-uk Kim 			do_cpuid(i, regs);
212a4e4127fSJung-uk Kim 			memcpy(p, regs, sizeof(regs));
213a4e4127fSJung-uk Kim 			p += sizeof(regs);
214a4e4127fSJung-uk Kim 		}
215a4e4127fSJung-uk Kim 		p = NULL;
216a4e4127fSJung-uk Kim 		for (i = 0; i < sizeof(brand) - 1; i++)
217a4e4127fSJung-uk Kim 			if (brand[i] == 'H' && brand[i + 1] == 'z')
218a4e4127fSJung-uk Kim 				p = brand + i;
219a4e4127fSJung-uk Kim 		if (p != NULL) {
220a4e4127fSJung-uk Kim 			p -= 5;
221a4e4127fSJung-uk Kim 			switch (p[4]) {
222a4e4127fSJung-uk Kim 			case 'M':
223a4e4127fSJung-uk Kim 				i = 1;
224a4e4127fSJung-uk Kim 				break;
225a4e4127fSJung-uk Kim 			case 'G':
226a4e4127fSJung-uk Kim 				i = 1000;
227a4e4127fSJung-uk Kim 				break;
228a4e4127fSJung-uk Kim 			case 'T':
229a4e4127fSJung-uk Kim 				i = 1000000;
230a4e4127fSJung-uk Kim 				break;
231a4e4127fSJung-uk Kim 			default:
23222875f88SMark Johnston 				return (false);
233a4e4127fSJung-uk Kim 			}
234a4e4127fSJung-uk Kim #define	C2D(c)	((c) - '0')
235a4e4127fSJung-uk Kim 			if (p[1] == '.') {
236a4e4127fSJung-uk Kim 				freq = C2D(p[0]) * 1000;
237a4e4127fSJung-uk Kim 				freq += C2D(p[2]) * 100;
238a4e4127fSJung-uk Kim 				freq += C2D(p[3]) * 10;
239a4e4127fSJung-uk Kim 				freq *= i * 1000;
240a4e4127fSJung-uk Kim 			} else {
241a4e4127fSJung-uk Kim 				freq = C2D(p[0]) * 1000;
242a4e4127fSJung-uk Kim 				freq += C2D(p[1]) * 100;
243a4e4127fSJung-uk Kim 				freq += C2D(p[2]) * 10;
244a4e4127fSJung-uk Kim 				freq += C2D(p[3]);
245a4e4127fSJung-uk Kim 				freq *= i * 1000000;
246a4e4127fSJung-uk Kim 			}
247a4e4127fSJung-uk Kim #undef C2D
24822875f88SMark Johnston 			*res = freq;
24922875f88SMark Johnston 			return (true);
250a4e4127fSJung-uk Kim 		}
251a4e4127fSJung-uk Kim 	}
25222875f88SMark Johnston 	return (false);
25322875f88SMark Johnston }
25422875f88SMark Johnston 
25522875f88SMark Johnston static void
tsc_freq_tc(uint64_t * res)256075e2779SMark Johnston tsc_freq_tc(uint64_t *res)
25722875f88SMark Johnston {
25822875f88SMark Johnston 	uint64_t tsc1, tsc2;
25922875f88SMark Johnston 	int64_t overhead;
26022875f88SMark Johnston 	int count, i;
26122875f88SMark Johnston 
26222875f88SMark Johnston 	overhead = 0;
26322875f88SMark Johnston 	for (i = 0, count = 8; i < count; i++) {
26422875f88SMark Johnston 		tsc1 = rdtsc_ordered();
26522875f88SMark Johnston 		DELAY(0);
26622875f88SMark Johnston 		tsc2 = rdtsc_ordered();
26722875f88SMark Johnston 		if (i > 0)
26822875f88SMark Johnston 			overhead += tsc2 - tsc1;
26922875f88SMark Johnston 	}
27022875f88SMark Johnston 	overhead /= count;
27122875f88SMark Johnston 
27222875f88SMark Johnston 	tsc1 = rdtsc_ordered();
27322875f88SMark Johnston 	DELAY(100000);
27422875f88SMark Johnston 	tsc2 = rdtsc_ordered();
27522875f88SMark Johnston 	tsc_freq = (tsc2 - tsc1 - overhead) * 10;
276a4e4127fSJung-uk Kim }
277dd7d207dSJung-uk Kim 
278075e2779SMark Johnston /*
279075e2779SMark Johnston  * Try to determine the TSC frequency using CPUID or hypercalls.  If successful,
280075e2779SMark Johnston  * this lets use the TSC for early DELAY() calls instead of the 8254 timer,
281075e2779SMark Johnston  * which may be unreliable or entirely absent on contemporary systems.  However,
282075e2779SMark Johnston  * avoid calibrating using the 8254 here so as to give hypervisors a chance to
283075e2779SMark Johnston  * register a timecounter that can be used instead.
284075e2779SMark Johnston  */
285a4e4127fSJung-uk Kim static void
probe_tsc_freq_early(void)286075e2779SMark Johnston probe_tsc_freq_early(void)
287a4e4127fSJung-uk Kim {
28884369dd5SMark Johnston #ifdef __i386__
28984369dd5SMark Johnston 	/* The TSC is known to be broken on certain CPUs. */
29084369dd5SMark Johnston 	switch (cpu_vendor_id) {
29184369dd5SMark Johnston 	case CPU_VENDOR_AMD:
29284369dd5SMark Johnston 		switch (cpu_id & 0xFF0) {
29384369dd5SMark Johnston 		case 0x500:
29484369dd5SMark Johnston 			/* K5 Model 0 */
29584369dd5SMark Johnston 			tsc_disabled = 1;
29684369dd5SMark Johnston 			return;
2975da5812bSJung-uk Kim 		}
29884369dd5SMark Johnston 		break;
29984369dd5SMark Johnston 	case CPU_VENDOR_CENTAUR:
30084369dd5SMark Johnston 		switch (cpu_id & 0xff0) {
30184369dd5SMark Johnston 		case 0x540:
30284369dd5SMark Johnston 			/*
30384369dd5SMark Johnston 			 * http://www.centtech.com/c6_data_sheet.pdf
30484369dd5SMark Johnston 			 *
30584369dd5SMark Johnston 			 * I-12 RDTSC may return incoherent values in EDX:EAX
30684369dd5SMark Johnston 			 * I-13 RDTSC hangs when certain event counters are used
30784369dd5SMark Johnston 			 */
30884369dd5SMark Johnston 			tsc_disabled = 1;
30984369dd5SMark Johnston 			return;
31084369dd5SMark Johnston 		}
31184369dd5SMark Johnston 		break;
31284369dd5SMark Johnston 	case CPU_VENDOR_NSC:
31384369dd5SMark Johnston 		switch (cpu_id & 0xff0) {
31484369dd5SMark Johnston 		case 0x540:
31584369dd5SMark Johnston 			if ((cpu_id & CPUID_STEPPING) == 0) {
31684369dd5SMark Johnston 				tsc_disabled = 1;
31784369dd5SMark Johnston 				return;
31884369dd5SMark Johnston 			}
31984369dd5SMark Johnston 			break;
32084369dd5SMark Johnston 		}
32184369dd5SMark Johnston 		break;
32284369dd5SMark Johnston 	}
32384369dd5SMark Johnston #endif
3245da5812bSJung-uk Kim 
325dd7d207dSJung-uk Kim 	switch (cpu_vendor_id) {
326dd7d207dSJung-uk Kim 	case CPU_VENDOR_AMD:
3272ee49facSKonstantin Belousov 	case CPU_VENDOR_HYGON:
328a106a27cSJung-uk Kim 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
329a106a27cSJung-uk Kim 		    (vm_guest == VM_GUEST_NO &&
330a106a27cSJung-uk Kim 		    CPUID_TO_FAMILY(cpu_id) >= 0x10))
331dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
332814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
333814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
334814124c3SKonstantin Belousov 			    tsc_get_timecount_mfence;
335814124c3SKonstantin Belousov 		}
336dd7d207dSJung-uk Kim 		break;
337dd7d207dSJung-uk Kim 	case CPU_VENDOR_INTEL:
338a106a27cSJung-uk Kim 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
339a106a27cSJung-uk Kim 		    (vm_guest == VM_GUEST_NO &&
340a106a27cSJung-uk Kim 		    ((CPUID_TO_FAMILY(cpu_id) == 0x6 &&
341dd7d207dSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0xe) ||
342dd7d207dSJung-uk Kim 		    (CPUID_TO_FAMILY(cpu_id) == 0xf &&
343a106a27cSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0x3))))
344dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
345814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
346814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
347814124c3SKonstantin Belousov 			    tsc_get_timecount_lfence;
348814124c3SKonstantin Belousov 		}
349dd7d207dSJung-uk Kim 		break;
350dd7d207dSJung-uk Kim 	case CPU_VENDOR_CENTAUR:
351a106a27cSJung-uk Kim 		if (vm_guest == VM_GUEST_NO &&
352a106a27cSJung-uk Kim 		    CPUID_TO_FAMILY(cpu_id) == 0x6 &&
353dd7d207dSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0xf &&
354dd7d207dSJung-uk Kim 		    (rdmsr(0x1203) & 0x100000000ULL) == 0)
355dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
356814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
357814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
358814124c3SKonstantin Belousov 			    tsc_get_timecount_lfence;
359814124c3SKonstantin Belousov 		}
360dd7d207dSJung-uk Kim 		break;
361dd7d207dSJung-uk Kim 	}
362dd7d207dSJung-uk Kim 
36384369dd5SMark Johnston 	if (tsc_freq_cpuid_vm()) {
36484369dd5SMark Johnston 		if (bootverbose)
36584369dd5SMark Johnston 			printf(
36684369dd5SMark Johnston 		    "Early TSC frequency %juHz derived from hypervisor CPUID\n",
36784369dd5SMark Johnston 			    (uintmax_t)tsc_freq);
36884369dd5SMark Johnston 	} else if (vm_guest == VM_GUEST_VMWARE) {
369fd980febSColin Percival 		tsc_freq_vmware();
37084369dd5SMark Johnston 		if (bootverbose)
37184369dd5SMark Johnston 			printf(
37284369dd5SMark Johnston 		    "Early TSC frequency %juHz derived from VMWare hypercall\n",
37384369dd5SMark Johnston 			    (uintmax_t)tsc_freq);
3741ca34862SRoger Pau Monné 	} else if (vm_guest == VM_GUEST_XEN) {
3751ca34862SRoger Pau Monné 		tsc_freq_xen();
3761ca34862SRoger Pau Monné 		if (bootverbose)
3771ca34862SRoger Pau Monné 			printf(
3781ca34862SRoger Pau Monné 			"Early TSC frequency %juHz derived from Xen CPUID\n",
3791ca34862SRoger Pau Monné 			    (uintmax_t)tsc_freq);
38084369dd5SMark Johnston 	} else if (tsc_freq_cpuid(&tsc_freq)) {
381bd8a359fSKonstantin Belousov 		/*
38222875f88SMark Johnston 		 * If possible, use the value obtained from CPUID as the initial
38322875f88SMark Johnston 		 * frequency.  This will be refined later during boot but is
38422875f88SMark Johnston 		 * good enough for now.  The 8254 PIT is not functional on some
38522875f88SMark Johnston 		 * newer platforms anyway, so don't delay our boot for what
38622875f88SMark Johnston 		 * might be a garbage result.  Late calibration is required if
38722875f88SMark Johnston 		 * the initial frequency was obtained from CPUID.16H, as the
38822875f88SMark Johnston 		 * derived value may be off by as much as 1%.
389bd8a359fSKonstantin Belousov 		 */
390a4e4127fSJung-uk Kim 		if (bootverbose)
39122875f88SMark Johnston 			printf("Early TSC frequency %juHz derived from CPUID\n",
39222875f88SMark Johnston 			    (uintmax_t)tsc_freq);
393075e2779SMark Johnston 	}
394075e2779SMark Johnston }
395075e2779SMark Johnston 
396075e2779SMark Johnston /*
397075e2779SMark Johnston  * If we were unable to determine the TSC frequency via CPU registers, try
398075e2779SMark Johnston  * to calibrate against a known clock.
399075e2779SMark Johnston  */
400075e2779SMark Johnston static void
probe_tsc_freq_late(void)401075e2779SMark Johnston probe_tsc_freq_late(void)
402075e2779SMark Johnston {
403075e2779SMark Johnston 	if (tsc_freq != 0)
404075e2779SMark Johnston 		return;
405075e2779SMark Johnston 
406075e2779SMark Johnston 	if (tsc_skip_calibration) {
40722875f88SMark Johnston 		/*
40822875f88SMark Johnston 		 * Try to parse the brand string to obtain the nominal TSC
40922875f88SMark Johnston 		 * frequency.
41022875f88SMark Johnston 		 */
41122875f88SMark Johnston 		if (cpu_vendor_id == CPU_VENDOR_INTEL &&
41222875f88SMark Johnston 		    tsc_freq_intel_brand(&tsc_freq)) {
41322875f88SMark Johnston 			if (bootverbose)
41422875f88SMark Johnston 				printf(
41522875f88SMark Johnston 		    "Early TSC frequency %juHz derived from brand string\n",
41622875f88SMark Johnston 				    (uintmax_t)tsc_freq);
41722875f88SMark Johnston 		} else {
41822875f88SMark Johnston 			tsc_disabled = 1;
41922875f88SMark Johnston 		}
42022875f88SMark Johnston 	} else {
42122875f88SMark Johnston 		/*
422075e2779SMark Johnston 		 * Calibrate against a timecounter or the 8254 PIT.  This
423075e2779SMark Johnston 		 * estimate will be refined later in tsc_calib().
42422875f88SMark Johnston 		 */
425075e2779SMark Johnston 		tsc_freq_tc(&tsc_freq);
42622875f88SMark Johnston 		if (bootverbose)
42722875f88SMark Johnston 			printf(
42822875f88SMark Johnston 		    "Early TSC frequency %juHz calibrated from 8254 PIT\n",
42922875f88SMark Johnston 			    (uintmax_t)tsc_freq);
43022875f88SMark Johnston 	}
431075e2779SMark Johnston }
432075e2779SMark Johnston 
433075e2779SMark Johnston void
start_TSC(void)434075e2779SMark Johnston start_TSC(void)
435075e2779SMark Johnston {
436075e2779SMark Johnston 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
437075e2779SMark Johnston 		return;
438075e2779SMark Johnston 
439075e2779SMark Johnston 	probe_tsc_freq_late();
44084369dd5SMark Johnston 
44184369dd5SMark Johnston 	if (cpu_power_ecx & CPUID_PERF_STAT) {
44284369dd5SMark Johnston 		/*
44384369dd5SMark Johnston 		 * XXX Some emulators expose host CPUID without actual support
44484369dd5SMark Johnston 		 * for these MSRs.  We must test whether they really work.
44584369dd5SMark Johnston 		 */
44684369dd5SMark Johnston 		wrmsr(MSR_MPERF, 0);
44784369dd5SMark Johnston 		wrmsr(MSR_APERF, 0);
44884369dd5SMark Johnston 		DELAY(10);
44984369dd5SMark Johnston 		if (rdmsr(MSR_MPERF) > 0 && rdmsr(MSR_APERF) > 0)
45084369dd5SMark Johnston 			tsc_perf_stat = 1;
45184369dd5SMark Johnston 	}
452a4e4127fSJung-uk Kim 
453dd7d207dSJung-uk Kim 	/*
454dd7d207dSJung-uk Kim 	 * Inform CPU accounting about our boot-time clock rate.  This will
455dd7d207dSJung-uk Kim 	 * be updated if someone loads a cpufreq driver after boot that
456dd7d207dSJung-uk Kim 	 * discovers a new max frequency.
45722875f88SMark Johnston 	 *
45822875f88SMark Johnston 	 * The frequency may also be updated after late calibration is complete;
45922875f88SMark Johnston 	 * however, we register the TSC as the ticker now to avoid switching
46022875f88SMark Johnston 	 * counters after much of the kernel has already booted and potentially
46122875f88SMark Johnston 	 * sampled the CPU clock.
462dd7d207dSJung-uk Kim 	 */
463a4e4127fSJung-uk Kim 	if (tsc_freq != 0)
4645ac44f72SJung-uk Kim 		set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
465dd7d207dSJung-uk Kim 
466dd7d207dSJung-uk Kim 	if (tsc_is_invariant)
467dd7d207dSJung-uk Kim 		return;
468dd7d207dSJung-uk Kim 
469dd7d207dSJung-uk Kim 	/* Register to find out about changes in CPU frequency. */
470dd7d207dSJung-uk Kim 	tsc_pre_tag = EVENTHANDLER_REGISTER(cpufreq_pre_change,
471dd7d207dSJung-uk Kim 	    tsc_freq_changing, NULL, EVENTHANDLER_PRI_FIRST);
472dd7d207dSJung-uk Kim 	tsc_post_tag = EVENTHANDLER_REGISTER(cpufreq_post_change,
473dd7d207dSJung-uk Kim 	    tsc_freq_changed, NULL, EVENTHANDLER_PRI_FIRST);
474dd7d207dSJung-uk Kim 	tsc_levels_tag = EVENTHANDLER_REGISTER(cpufreq_levels_changed,
475dd7d207dSJung-uk Kim 	    tsc_levels_changed, NULL, EVENTHANDLER_PRI_ANY);
476dd7d207dSJung-uk Kim }
477dd7d207dSJung-uk Kim 
47865e7d70bSJung-uk Kim #ifdef SMP
47965e7d70bSJung-uk Kim 
480814124c3SKonstantin Belousov /*
481814124c3SKonstantin Belousov  * RDTSC is not a serializing instruction, and does not drain
482814124c3SKonstantin Belousov  * instruction stream, so we need to drain the stream before executing
483814124c3SKonstantin Belousov  * it.  It could be fixed by use of RDTSCP, except the instruction is
484814124c3SKonstantin Belousov  * not available everywhere.
485814124c3SKonstantin Belousov  *
486814124c3SKonstantin Belousov  * Use CPUID for draining in the boot-time SMP constistency test.  The
487814124c3SKonstantin Belousov  * timecounters use MFENCE for AMD CPUs, and LFENCE for others (Intel
488814124c3SKonstantin Belousov  * and VIA) when SSE2 is present, and nothing on older machines which
489814124c3SKonstantin Belousov  * also do not issue RDTSC prematurely.  There, testing for SSE2 and
490e1a18e46SKonstantin Belousov  * vendor is too cumbersome, and we learn about TSC presence from CPUID.
491814124c3SKonstantin Belousov  *
492814124c3SKonstantin Belousov  * Do not use do_cpuid(), since we do not need CPUID results, which
493814124c3SKonstantin Belousov  * have to be written into memory with do_cpuid().
494814124c3SKonstantin Belousov  */
49565e7d70bSJung-uk Kim #define	TSC_READ(x)							\
49665e7d70bSJung-uk Kim static void								\
49765e7d70bSJung-uk Kim tsc_read_##x(void *arg)							\
49865e7d70bSJung-uk Kim {									\
4997bfcb3bbSJim Harris 	uint64_t *tsc = arg;						\
50065e7d70bSJung-uk Kim 	u_int cpu = PCPU_GET(cpuid);					\
50165e7d70bSJung-uk Kim 									\
502814124c3SKonstantin Belousov 	__asm __volatile("cpuid" : : : "eax", "ebx", "ecx", "edx");	\
5037bfcb3bbSJim Harris 	tsc[cpu * 3 + x] = rdtsc();					\
50465e7d70bSJung-uk Kim }
50565e7d70bSJung-uk Kim TSC_READ(0)
50665e7d70bSJung-uk Kim TSC_READ(1)
50765e7d70bSJung-uk Kim TSC_READ(2)
50865e7d70bSJung-uk Kim #undef TSC_READ
50965e7d70bSJung-uk Kim 
51065e7d70bSJung-uk Kim #define	N	1000
51165e7d70bSJung-uk Kim 
51265e7d70bSJung-uk Kim static void
comp_smp_tsc(void * arg)51365e7d70bSJung-uk Kim comp_smp_tsc(void *arg)
51465e7d70bSJung-uk Kim {
5157bfcb3bbSJim Harris 	uint64_t *tsc;
5167bfcb3bbSJim Harris 	int64_t d1, d2;
51765e7d70bSJung-uk Kim 	u_int cpu = PCPU_GET(cpuid);
51865e7d70bSJung-uk Kim 	u_int i, j, size;
51965e7d70bSJung-uk Kim 
52065e7d70bSJung-uk Kim 	size = (mp_maxid + 1) * 3;
52165e7d70bSJung-uk Kim 	for (i = 0, tsc = arg; i < N; i++, tsc += size)
52265e7d70bSJung-uk Kim 		CPU_FOREACH(j) {
52365e7d70bSJung-uk Kim 			if (j == cpu)
52465e7d70bSJung-uk Kim 				continue;
52565e7d70bSJung-uk Kim 			d1 = tsc[cpu * 3 + 1] - tsc[j * 3];
52665e7d70bSJung-uk Kim 			d2 = tsc[cpu * 3 + 2] - tsc[j * 3 + 1];
52765e7d70bSJung-uk Kim 			if (d1 <= 0 || d2 <= 0) {
52865e7d70bSJung-uk Kim 				smp_tsc = 0;
52965e7d70bSJung-uk Kim 				return;
53065e7d70bSJung-uk Kim 			}
53165e7d70bSJung-uk Kim 		}
53265e7d70bSJung-uk Kim }
53365e7d70bSJung-uk Kim 
534b2c63698SAlexander Motin static void
adj_smp_tsc(void * arg)535b2c63698SAlexander Motin adj_smp_tsc(void *arg)
536b2c63698SAlexander Motin {
537b2c63698SAlexander Motin 	uint64_t *tsc;
538b2c63698SAlexander Motin 	int64_t d, min, max;
539b2c63698SAlexander Motin 	u_int cpu = PCPU_GET(cpuid);
540b2c63698SAlexander Motin 	u_int first, i, size;
541b2c63698SAlexander Motin 
542b2c63698SAlexander Motin 	first = CPU_FIRST();
543b2c63698SAlexander Motin 	if (cpu == first)
544b2c63698SAlexander Motin 		return;
545b2c63698SAlexander Motin 	min = INT64_MIN;
546b2c63698SAlexander Motin 	max = INT64_MAX;
547b2c63698SAlexander Motin 	size = (mp_maxid + 1) * 3;
548b2c63698SAlexander Motin 	for (i = 0, tsc = arg; i < N; i++, tsc += size) {
549b2c63698SAlexander Motin 		d = tsc[first * 3] - tsc[cpu * 3 + 1];
550b2c63698SAlexander Motin 		if (d > min)
551b2c63698SAlexander Motin 			min = d;
552b2c63698SAlexander Motin 		d = tsc[first * 3 + 1] - tsc[cpu * 3 + 2];
553b2c63698SAlexander Motin 		if (d > min)
554b2c63698SAlexander Motin 			min = d;
555b2c63698SAlexander Motin 		d = tsc[first * 3 + 1] - tsc[cpu * 3];
556b2c63698SAlexander Motin 		if (d < max)
557b2c63698SAlexander Motin 			max = d;
558b2c63698SAlexander Motin 		d = tsc[first * 3 + 2] - tsc[cpu * 3 + 1];
559b2c63698SAlexander Motin 		if (d < max)
560b2c63698SAlexander Motin 			max = d;
561b2c63698SAlexander Motin 	}
562b2c63698SAlexander Motin 	if (min > max)
563b2c63698SAlexander Motin 		return;
564b2c63698SAlexander Motin 	d = min / 2 + max / 2;
565b2c63698SAlexander Motin 	__asm __volatile (
566b2c63698SAlexander Motin 		"movl $0x10, %%ecx\n\t"
567b2c63698SAlexander Motin 		"rdmsr\n\t"
568b2c63698SAlexander Motin 		"addl %%edi, %%eax\n\t"
569b2c63698SAlexander Motin 		"adcl %%esi, %%edx\n\t"
570b2c63698SAlexander Motin 		"wrmsr\n"
571b2c63698SAlexander Motin 		: /* No output */
572b2c63698SAlexander Motin 		: "D" ((uint32_t)d), "S" ((uint32_t)(d >> 32))
573b2c63698SAlexander Motin 		: "ax", "cx", "dx", "cc"
574b2c63698SAlexander Motin 	);
575b2c63698SAlexander Motin }
576b2c63698SAlexander Motin 
57765e7d70bSJung-uk Kim static int
test_tsc(int adj_max_count)578279be68bSAndriy Gapon test_tsc(int adj_max_count)
57965e7d70bSJung-uk Kim {
5807bfcb3bbSJim Harris 	uint64_t *data, *tsc;
581b2c63698SAlexander Motin 	u_int i, size, adj;
58265e7d70bSJung-uk Kim 
58384eaf2ccSKonstantin Belousov 	if ((!smp_tsc && !tsc_is_invariant))
58465e7d70bSJung-uk Kim 		return (-100);
5858cc15b0dSKyle Evans 	/*
5868cc15b0dSKyle Evans 	 * Misbehavior of TSC under VirtualBox has been observed.  In
5878cc15b0dSKyle Evans 	 * particular, threads doing small (~1 second) sleeps may miss their
5888cc15b0dSKyle Evans 	 * wakeup and hang around in sleep state, causing hangs on shutdown.
5898cc15b0dSKyle Evans 	 */
5908cc15b0dSKyle Evans 	if (vm_guest == VM_GUEST_VBOX)
5918cc15b0dSKyle Evans 		return (0);
5928cc15b0dSKyle Evans 
593cd165c8bSColin Percival 	TSENTER();
59465e7d70bSJung-uk Kim 	size = (mp_maxid + 1) * 3;
59565e7d70bSJung-uk Kim 	data = malloc(sizeof(*data) * size * N, M_TEMP, M_WAITOK);
596b2c63698SAlexander Motin 	adj = 0;
597b2c63698SAlexander Motin retry:
59865e7d70bSJung-uk Kim 	for (i = 0, tsc = data; i < N; i++, tsc += size)
59965e7d70bSJung-uk Kim 		smp_rendezvous(tsc_read_0, tsc_read_1, tsc_read_2, tsc);
60065e7d70bSJung-uk Kim 	smp_tsc = 1;	/* XXX */
60167d955aaSPatrick Kelsey 	smp_rendezvous(smp_no_rendezvous_barrier, comp_smp_tsc,
60267d955aaSPatrick Kelsey 	    smp_no_rendezvous_barrier, data);
603279be68bSAndriy Gapon 	if (!smp_tsc && adj < adj_max_count) {
604b2c63698SAlexander Motin 		adj++;
60567d955aaSPatrick Kelsey 		smp_rendezvous(smp_no_rendezvous_barrier, adj_smp_tsc,
60667d955aaSPatrick Kelsey 		    smp_no_rendezvous_barrier, data);
607b2c63698SAlexander Motin 		goto retry;
608b2c63698SAlexander Motin 	}
60965e7d70bSJung-uk Kim 	free(data, M_TEMP);
61065e7d70bSJung-uk Kim 	if (bootverbose)
611b2c63698SAlexander Motin 		printf("SMP: %sed TSC synchronization test%s\n",
612b2c63698SAlexander Motin 		    smp_tsc ? "pass" : "fail",
613b2c63698SAlexander Motin 		    adj > 0 ? " after adjustment" : "");
614cd165c8bSColin Percival 	TSEXIT();
61526e6537aSJung-uk Kim 	if (smp_tsc && tsc_is_invariant) {
61626e6537aSJung-uk Kim 		switch (cpu_vendor_id) {
61726e6537aSJung-uk Kim 		case CPU_VENDOR_AMD:
6182ee49facSKonstantin Belousov 		case CPU_VENDOR_HYGON:
61926e6537aSJung-uk Kim 			/*
620450d86fcSJung-uk Kim 			 * Processor Programming Reference (PPR) for AMD
621450d86fcSJung-uk Kim 			 * Family 17h states that the TSC uses a common
622450d86fcSJung-uk Kim 			 * reference for all sockets, cores and threads.
623450d86fcSJung-uk Kim 			 */
624450d86fcSJung-uk Kim 			if (CPUID_TO_FAMILY(cpu_id) >= 0x17)
625450d86fcSJung-uk Kim 				return (1000);
626450d86fcSJung-uk Kim 			/*
62726e6537aSJung-uk Kim 			 * Starting with Family 15h processors, TSC clock
62826e6537aSJung-uk Kim 			 * source is in the north bridge.  Check whether
62926e6537aSJung-uk Kim 			 * we have a single-socket/multi-core platform.
63026e6537aSJung-uk Kim 			 * XXX Need more work for complex cases.
63126e6537aSJung-uk Kim 			 */
63226e6537aSJung-uk Kim 			if (CPUID_TO_FAMILY(cpu_id) < 0x15 ||
63326e6537aSJung-uk Kim 			    (amd_feature2 & AMDID2_CMP) == 0 ||
63426e6537aSJung-uk Kim 			    smp_cpus > (cpu_procinfo2 & AMDID_CMP_CORES) + 1)
63526e6537aSJung-uk Kim 				break;
63626e6537aSJung-uk Kim 			return (1000);
63726e6537aSJung-uk Kim 		case CPU_VENDOR_INTEL:
63826e6537aSJung-uk Kim 			/*
63926e6537aSJung-uk Kim 			 * XXX Assume Intel platforms have synchronized TSCs.
64026e6537aSJung-uk Kim 			 */
64126e6537aSJung-uk Kim 			return (1000);
64226e6537aSJung-uk Kim 		}
64326e6537aSJung-uk Kim 		return (800);
64426e6537aSJung-uk Kim 	}
64526e6537aSJung-uk Kim 	return (-100);
64665e7d70bSJung-uk Kim }
64765e7d70bSJung-uk Kim 
64865e7d70bSJung-uk Kim #undef N
64965e7d70bSJung-uk Kim 
65065e7d70bSJung-uk Kim #endif /* SMP */
65165e7d70bSJung-uk Kim 
65265e7d70bSJung-uk Kim static void
init_TSC_tc(void)653dd7d207dSJung-uk Kim init_TSC_tc(void)
654dd7d207dSJung-uk Kim {
65595f2f098SJung-uk Kim 	uint64_t max_freq;
65695f2f098SJung-uk Kim 	int shift;
657dd7d207dSJung-uk Kim 
65838b8542cSJung-uk Kim 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
659dd7d207dSJung-uk Kim 		return;
660dd7d207dSJung-uk Kim 
661dd7d207dSJung-uk Kim 	/*
66295f2f098SJung-uk Kim 	 * Limit timecounter frequency to fit in an int and prevent it from
66395f2f098SJung-uk Kim 	 * overflowing too fast.
66495f2f098SJung-uk Kim 	 */
66595f2f098SJung-uk Kim 	max_freq = UINT_MAX;
66695f2f098SJung-uk Kim 
66795f2f098SJung-uk Kim 	/*
66892597e06SJohn Baldwin 	 * Intel CPUs without a C-state invariant TSC can stop the TSC
669d1411416SJohn Baldwin 	 * in either C2 or C3.  Disable use of C2 and C3 while using
670d1411416SJohn Baldwin 	 * the TSC as the timecounter.  The timecounter can be changed
671d1411416SJohn Baldwin 	 * to enable C2 and C3.
672d1411416SJohn Baldwin 	 *
673d1411416SJohn Baldwin 	 * Note that the TSC is used as the cputicker for computing
674d1411416SJohn Baldwin 	 * thread runtime regardless of the timecounter setting, so
675d1411416SJohn Baldwin 	 * using an alternate timecounter and enabling C2 or C3 can
676d1411416SJohn Baldwin 	 * result incorrect runtimes for kernel idle threads (but not
677d1411416SJohn Baldwin 	 * for any non-idle threads).
678a49399a9SJung-uk Kim 	 */
6798cd59625SKonstantin Belousov 	if (cpu_vendor_id == CPU_VENDOR_INTEL &&
680a49399a9SJung-uk Kim 	    (amd_pminfo & AMDPM_TSC_INVARIANT) == 0) {
68192597e06SJohn Baldwin 		tsc_timecounter.tc_flags |= TC_FLAGS_C2STOP;
682a49399a9SJung-uk Kim 		if (bootverbose)
683d1411416SJohn Baldwin 			printf("TSC timecounter disables C2 and C3.\n");
684a49399a9SJung-uk Kim 	}
685a49399a9SJung-uk Kim 
686dd7d207dSJung-uk Kim 	/*
687e7f1427dSKonstantin Belousov 	 * We can not use the TSC in SMP mode unless the TSCs on all CPUs
688e7f1427dSKonstantin Belousov 	 * are synchronized.  If the user is sure that the system has
689e7f1427dSKonstantin Belousov 	 * synchronized TSCs, set kern.timecounter.smp_tsc tunable to a
690e7f1427dSKonstantin Belousov 	 * non-zero value.  The TSC seems unreliable in virtualized SMP
6915cf8ac1bSMike Silbersack 	 * environments, so it is set to a negative quality in those cases.
692dd7d207dSJung-uk Kim 	 */
693ba79ab82SAndriy Gapon #ifdef SMP
694e7f1427dSKonstantin Belousov 	if (mp_ncpus > 1)
695279be68bSAndriy Gapon 		tsc_timecounter.tc_quality = test_tsc(smp_tsc_adjust);
696ba79ab82SAndriy Gapon 	else
697ba79ab82SAndriy Gapon #endif /* SMP */
698ba79ab82SAndriy Gapon 	if (tsc_is_invariant)
69926e6537aSJung-uk Kim 		tsc_timecounter.tc_quality = 1000;
700e7f1427dSKonstantin Belousov 	max_freq >>= tsc_shift;
70126e6537aSJung-uk Kim 
702e7f1427dSKonstantin Belousov 	for (shift = 0; shift <= 31 && (tsc_freq >> shift) > max_freq; shift++)
70395f2f098SJung-uk Kim 		;
7049e680e40SKonstantin Belousov 
7059e680e40SKonstantin Belousov 	/*
7069e680e40SKonstantin Belousov 	 * Timecounter implementation selection, top to bottom:
7079e680e40SKonstantin Belousov 	 * - If RDTSCP is available, use RDTSCP.
7089e680e40SKonstantin Belousov 	 * - If fence instructions are provided (SSE2), use LFENCE;RDTSC
7099e680e40SKonstantin Belousov 	 *   on Intel, and MFENCE;RDTSC on AMD.
7109e680e40SKonstantin Belousov 	 * - For really old CPUs, just use RDTSC.
7119e680e40SKonstantin Belousov 	 */
7129f47eeffSKonstantin Belousov 	if ((amd_feature & AMDID_RDTSCP) != 0) {
7139e680e40SKonstantin Belousov 		tsc_timecounter.tc_get_timecount = shift > 0 ?
7149e680e40SKonstantin Belousov 		    tscp_get_timecount_low : tscp_get_timecount;
7159e680e40SKonstantin Belousov 	} else if ((cpu_feature & CPUID_SSE2) != 0 && mp_ncpus > 1) {
7162ee49facSKonstantin Belousov 		if (cpu_vendor_id == CPU_VENDOR_AMD ||
7172ee49facSKonstantin Belousov 		    cpu_vendor_id == CPU_VENDOR_HYGON) {
718e7f1427dSKonstantin Belousov 			tsc_timecounter.tc_get_timecount = shift > 0 ?
719e7f1427dSKonstantin Belousov 			    tsc_get_timecount_low_mfence :
720e7f1427dSKonstantin Belousov 			    tsc_get_timecount_mfence;
721814124c3SKonstantin Belousov 		} else {
722e7f1427dSKonstantin Belousov 			tsc_timecounter.tc_get_timecount = shift > 0 ?
723e7f1427dSKonstantin Belousov 			    tsc_get_timecount_low_lfence :
724e7f1427dSKonstantin Belousov 			    tsc_get_timecount_lfence;
725814124c3SKonstantin Belousov 		}
726e7f1427dSKonstantin Belousov 	} else {
727e7f1427dSKonstantin Belousov 		tsc_timecounter.tc_get_timecount = shift > 0 ?
728e7f1427dSKonstantin Belousov 		    tsc_get_timecount_low : tsc_get_timecount;
729e7f1427dSKonstantin Belousov 	}
730e7f1427dSKonstantin Belousov 	if (shift > 0) {
73195f2f098SJung-uk Kim 		tsc_timecounter.tc_name = "TSC-low";
73295f2f098SJung-uk Kim 		if (bootverbose)
733bc8e4ad2SJung-uk Kim 			printf("TSC timecounter discards lower %d bit(s)\n",
73495f2f098SJung-uk Kim 			    shift);
73595f2f098SJung-uk Kim 	}
736bc34c87eSJung-uk Kim 	if (tsc_freq != 0) {
73795f2f098SJung-uk Kim 		tsc_timecounter.tc_frequency = tsc_freq >> shift;
73895f2f098SJung-uk Kim 		tsc_timecounter.tc_priv = (void *)(intptr_t)shift;
73922875f88SMark Johnston 
74022875f88SMark Johnston 		/*
74122875f88SMark Johnston 		 * Timecounter registration is deferred until after late
74222875f88SMark Johnston 		 * calibration is finished.
74322875f88SMark Johnston 		 */
744dd7d207dSJung-uk Kim 	}
745dd7d207dSJung-uk Kim }
74665e7d70bSJung-uk Kim SYSINIT(tsc_tc, SI_SUB_SMP, SI_ORDER_ANY, init_TSC_tc, NULL);
747dd7d207dSJung-uk Kim 
74822875f88SMark Johnston static void
tsc_update_freq(uint64_t new_freq)74922875f88SMark Johnston tsc_update_freq(uint64_t new_freq)
75022875f88SMark Johnston {
75122875f88SMark Johnston 	atomic_store_rel_64(&tsc_freq, new_freq);
75222875f88SMark Johnston 	atomic_store_rel_64(&tsc_timecounter.tc_frequency,
75322875f88SMark Johnston 	    new_freq >> (int)(intptr_t)tsc_timecounter.tc_priv);
75422875f88SMark Johnston }
75522875f88SMark Johnston 
75684369dd5SMark Johnston void
tsc_init(void)75784369dd5SMark Johnston tsc_init(void)
75884369dd5SMark Johnston {
75984369dd5SMark Johnston 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
76084369dd5SMark Johnston 		return;
76184369dd5SMark Johnston 
762075e2779SMark Johnston 	probe_tsc_freq_early();
76384369dd5SMark Johnston }
76484369dd5SMark Johnston 
76522875f88SMark Johnston /*
76622875f88SMark Johnston  * Perform late calibration of the TSC frequency once ACPI-based timecounters
767553af8f1SMark Johnston  * are available.  At this point timehands are not set up, so we read the
768553af8f1SMark Johnston  * highest-quality timecounter directly rather than using (s)binuptime().
76922875f88SMark Johnston  */
770553af8f1SMark Johnston void
tsc_calibrate(void)771553af8f1SMark Johnston tsc_calibrate(void)
77222875f88SMark Johnston {
773c2705ceaSColin Percival 	uint64_t freq;
77422875f88SMark Johnston 
77522875f88SMark Johnston 	if (tsc_disabled)
77622875f88SMark Johnston 		return;
7779cb32882SColin Percival 	if (tsc_early_calib_exact)
7789cb32882SColin Percival 		goto calibrated;
77922875f88SMark Johnston 
780c2705ceaSColin Percival 	fpu_kern_enter(curthread, NULL, FPU_KERN_NOCTX);
781c2705ceaSColin Percival 	freq = clockcalib(rdtsc_ordered, "TSC");
782c2705ceaSColin Percival 	fpu_kern_leave(curthread, NULL);
783698727d6SColin Percival 	tsc_update_freq(freq);
784c2705ceaSColin Percival 
7859cb32882SColin Percival calibrated:
78622875f88SMark Johnston 	tc_init(&tsc_timecounter);
78722875f88SMark Johnston 	set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
78822875f88SMark Johnston }
78922875f88SMark Johnston 
790279be68bSAndriy Gapon void
resume_TSC(void)791279be68bSAndriy Gapon resume_TSC(void)
792279be68bSAndriy Gapon {
793ba79ab82SAndriy Gapon #ifdef SMP
794279be68bSAndriy Gapon 	int quality;
795279be68bSAndriy Gapon 
796279be68bSAndriy Gapon 	/* If TSC was not good on boot, it is unlikely to become good now. */
797279be68bSAndriy Gapon 	if (tsc_timecounter.tc_quality < 0)
798279be68bSAndriy Gapon 		return;
799279be68bSAndriy Gapon 	/* Nothing to do with UP. */
800279be68bSAndriy Gapon 	if (mp_ncpus < 2)
801279be68bSAndriy Gapon 		return;
802279be68bSAndriy Gapon 
803279be68bSAndriy Gapon 	/*
804279be68bSAndriy Gapon 	 * If TSC was good, a single synchronization should be enough,
805279be68bSAndriy Gapon 	 * but honour smp_tsc_adjust if it's set.
806279be68bSAndriy Gapon 	 */
807279be68bSAndriy Gapon 	quality = test_tsc(MAX(smp_tsc_adjust, 1));
808279be68bSAndriy Gapon 	if (quality != tsc_timecounter.tc_quality) {
809279be68bSAndriy Gapon 		printf("TSC timecounter quality changed: %d -> %d\n",
810279be68bSAndriy Gapon 		    tsc_timecounter.tc_quality, quality);
811279be68bSAndriy Gapon 		tsc_timecounter.tc_quality = quality;
812279be68bSAndriy Gapon 	}
813ba79ab82SAndriy Gapon #endif /* SMP */
814279be68bSAndriy Gapon }
815279be68bSAndriy Gapon 
816dd7d207dSJung-uk Kim /*
817dd7d207dSJung-uk Kim  * When cpufreq levels change, find out about the (new) max frequency.  We
818dd7d207dSJung-uk Kim  * use this to update CPU accounting in case it got a lower estimate at boot.
819dd7d207dSJung-uk Kim  */
820dd7d207dSJung-uk Kim static void
tsc_levels_changed(void * arg,int unit)821dd7d207dSJung-uk Kim tsc_levels_changed(void *arg, int unit)
822dd7d207dSJung-uk Kim {
823dd7d207dSJung-uk Kim 	device_t cf_dev;
824dd7d207dSJung-uk Kim 	struct cf_level *levels;
825dd7d207dSJung-uk Kim 	int count, error;
826dd7d207dSJung-uk Kim 	uint64_t max_freq;
827dd7d207dSJung-uk Kim 
828dd7d207dSJung-uk Kim 	/* Only use values from the first CPU, assuming all are equal. */
829dd7d207dSJung-uk Kim 	if (unit != 0)
830dd7d207dSJung-uk Kim 		return;
831dd7d207dSJung-uk Kim 
832dd7d207dSJung-uk Kim 	/* Find the appropriate cpufreq device instance. */
833dd7d207dSJung-uk Kim 	cf_dev = devclass_get_device(devclass_find("cpufreq"), unit);
834dd7d207dSJung-uk Kim 	if (cf_dev == NULL) {
835dd7d207dSJung-uk Kim 		printf("tsc_levels_changed() called but no cpufreq device?\n");
836dd7d207dSJung-uk Kim 		return;
837dd7d207dSJung-uk Kim 	}
838dd7d207dSJung-uk Kim 
839dd7d207dSJung-uk Kim 	/* Get settings from the device and find the max frequency. */
840dd7d207dSJung-uk Kim 	count = 64;
841dd7d207dSJung-uk Kim 	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
842dd7d207dSJung-uk Kim 	if (levels == NULL)
843dd7d207dSJung-uk Kim 		return;
844dd7d207dSJung-uk Kim 	error = CPUFREQ_LEVELS(cf_dev, levels, &count);
845dd7d207dSJung-uk Kim 	if (error == 0 && count != 0) {
846dd7d207dSJung-uk Kim 		max_freq = (uint64_t)levels[0].total_set.freq * 1000000;
8478701571dSMitchell Horne 		set_cputicker(rdtsc, max_freq, true);
848dd7d207dSJung-uk Kim 	} else
849dd7d207dSJung-uk Kim 		printf("tsc_levels_changed: no max freq found\n");
850dd7d207dSJung-uk Kim 	free(levels, M_TEMP);
851dd7d207dSJung-uk Kim }
852dd7d207dSJung-uk Kim 
853dd7d207dSJung-uk Kim /*
854dd7d207dSJung-uk Kim  * If the TSC timecounter is in use, veto the pending change.  It may be
855dd7d207dSJung-uk Kim  * possible in the future to handle a dynamically-changing timecounter rate.
856dd7d207dSJung-uk Kim  */
857dd7d207dSJung-uk Kim static void
tsc_freq_changing(void * arg,const struct cf_level * level,int * status)858dd7d207dSJung-uk Kim tsc_freq_changing(void *arg, const struct cf_level *level, int *status)
859dd7d207dSJung-uk Kim {
860dd7d207dSJung-uk Kim 
861dd7d207dSJung-uk Kim 	if (*status != 0 || timecounter != &tsc_timecounter)
862dd7d207dSJung-uk Kim 		return;
863dd7d207dSJung-uk Kim 
864dd7d207dSJung-uk Kim 	printf("timecounter TSC must not be in use when "
865dd7d207dSJung-uk Kim 	    "changing frequencies; change denied\n");
866dd7d207dSJung-uk Kim 	*status = EBUSY;
867dd7d207dSJung-uk Kim }
868dd7d207dSJung-uk Kim 
869dd7d207dSJung-uk Kim /* Update TSC freq with the value indicated by the caller. */
870dd7d207dSJung-uk Kim static void
tsc_freq_changed(void * arg,const struct cf_level * level,int status)871dd7d207dSJung-uk Kim tsc_freq_changed(void *arg, const struct cf_level *level, int status)
872dd7d207dSJung-uk Kim {
8733453537fSJung-uk Kim 	uint64_t freq;
874dd7d207dSJung-uk Kim 
875dd7d207dSJung-uk Kim 	/* If there was an error during the transition, don't do anything. */
87679422085SJung-uk Kim 	if (tsc_disabled || status != 0)
877dd7d207dSJung-uk Kim 		return;
878dd7d207dSJung-uk Kim 
879dd7d207dSJung-uk Kim 	/* Total setting for this level gives the new frequency in MHz. */
8803453537fSJung-uk Kim 	freq = (uint64_t)level->total_set.freq * 1000000;
88122875f88SMark Johnston 	tsc_update_freq(freq);
882dd7d207dSJung-uk Kim }
883dd7d207dSJung-uk Kim 
884dd7d207dSJung-uk Kim static int
sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)885dd7d207dSJung-uk Kim sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
886dd7d207dSJung-uk Kim {
887dd7d207dSJung-uk Kim 	int error;
888dd7d207dSJung-uk Kim 	uint64_t freq;
889dd7d207dSJung-uk Kim 
8903453537fSJung-uk Kim 	freq = atomic_load_acq_64(&tsc_freq);
8913453537fSJung-uk Kim 	if (freq == 0)
892dd7d207dSJung-uk Kim 		return (EOPNOTSUPP);
893cbc134adSMatthew D Fleming 	error = sysctl_handle_64(oidp, &freq, 0, req);
89422875f88SMark Johnston 	if (error == 0 && req->newptr != NULL)
89522875f88SMark Johnston 		tsc_update_freq(freq);
896dd7d207dSJung-uk Kim 	return (error);
897dd7d207dSJung-uk Kim }
8987029da5cSPawel Biernacki SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq,
8991d6fb900SAlexander Motin     CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
9007029da5cSPawel Biernacki     0, 0, sysctl_machdep_tsc_freq, "QU",
9017029da5cSPawel Biernacki     "Time Stamp Counter frequency");
902dd7d207dSJung-uk Kim 
903727c7b2dSJung-uk Kim static u_int
tsc_get_timecount(struct timecounter * tc __unused)90495f2f098SJung-uk Kim tsc_get_timecount(struct timecounter *tc __unused)
905dd7d207dSJung-uk Kim {
906727c7b2dSJung-uk Kim 
907727c7b2dSJung-uk Kim 	return (rdtsc32());
908dd7d207dSJung-uk Kim }
90995f2f098SJung-uk Kim 
9109e680e40SKonstantin Belousov static u_int
tscp_get_timecount(struct timecounter * tc __unused)9119e680e40SKonstantin Belousov tscp_get_timecount(struct timecounter *tc __unused)
9129e680e40SKonstantin Belousov {
9139e680e40SKonstantin Belousov 
9149e680e40SKonstantin Belousov 	return (rdtscp32());
9159e680e40SKonstantin Belousov }
9169e680e40SKonstantin Belousov 
917814124c3SKonstantin Belousov static inline u_int
tsc_get_timecount_low(struct timecounter * tc)918bc8e4ad2SJung-uk Kim tsc_get_timecount_low(struct timecounter *tc)
91995f2f098SJung-uk Kim {
9205df88f46SJung-uk Kim 	uint32_t rv;
92195f2f098SJung-uk Kim 
9225df88f46SJung-uk Kim 	__asm __volatile("rdtsc; shrd %%cl, %%edx, %0"
9235df88f46SJung-uk Kim 	    : "=a" (rv) : "c" ((int)(intptr_t)tc->tc_priv) : "edx");
9245df88f46SJung-uk Kim 	return (rv);
92595f2f098SJung-uk Kim }
926aea81038SKonstantin Belousov 
927814124c3SKonstantin Belousov static u_int
tscp_get_timecount_low(struct timecounter * tc)9289e680e40SKonstantin Belousov tscp_get_timecount_low(struct timecounter *tc)
9299e680e40SKonstantin Belousov {
9309e680e40SKonstantin Belousov 	uint32_t rv;
9319e680e40SKonstantin Belousov 
9329e680e40SKonstantin Belousov 	__asm __volatile("rdtscp; movl %1, %%ecx; shrd %%cl, %%edx, %0"
933a013e285SKonstantin Belousov 	    : "=&a" (rv) : "m" (tc->tc_priv) : "ecx", "edx");
9349e680e40SKonstantin Belousov 	return (rv);
9359e680e40SKonstantin Belousov }
9369e680e40SKonstantin Belousov 
9379e680e40SKonstantin Belousov static u_int
tsc_get_timecount_lfence(struct timecounter * tc __unused)938814124c3SKonstantin Belousov tsc_get_timecount_lfence(struct timecounter *tc __unused)
939814124c3SKonstantin Belousov {
940814124c3SKonstantin Belousov 
941814124c3SKonstantin Belousov 	lfence();
942814124c3SKonstantin Belousov 	return (rdtsc32());
943814124c3SKonstantin Belousov }
944814124c3SKonstantin Belousov 
945814124c3SKonstantin Belousov static u_int
tsc_get_timecount_low_lfence(struct timecounter * tc)946814124c3SKonstantin Belousov tsc_get_timecount_low_lfence(struct timecounter *tc)
947814124c3SKonstantin Belousov {
948814124c3SKonstantin Belousov 
949814124c3SKonstantin Belousov 	lfence();
950814124c3SKonstantin Belousov 	return (tsc_get_timecount_low(tc));
951814124c3SKonstantin Belousov }
952814124c3SKonstantin Belousov 
953814124c3SKonstantin Belousov static u_int
tsc_get_timecount_mfence(struct timecounter * tc __unused)954814124c3SKonstantin Belousov tsc_get_timecount_mfence(struct timecounter *tc __unused)
955814124c3SKonstantin Belousov {
956814124c3SKonstantin Belousov 
957814124c3SKonstantin Belousov 	mfence();
958814124c3SKonstantin Belousov 	return (rdtsc32());
959814124c3SKonstantin Belousov }
960814124c3SKonstantin Belousov 
961814124c3SKonstantin Belousov static u_int
tsc_get_timecount_low_mfence(struct timecounter * tc)962814124c3SKonstantin Belousov tsc_get_timecount_low_mfence(struct timecounter *tc)
963814124c3SKonstantin Belousov {
964814124c3SKonstantin Belousov 
965814124c3SKonstantin Belousov 	mfence();
966814124c3SKonstantin Belousov 	return (tsc_get_timecount_low(tc));
967814124c3SKonstantin Belousov }
968814124c3SKonstantin Belousov 
96916808549SKonstantin Belousov static uint32_t
x86_tsc_vdso_timehands(struct vdso_timehands * vdso_th,struct timecounter * tc)97016808549SKonstantin Belousov x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th, struct timecounter *tc)
971aea81038SKonstantin Belousov {
972aea81038SKonstantin Belousov 
97316808549SKonstantin Belousov 	vdso_th->th_algo = VDSO_TH_ALGO_X86_TSC;
974d1b1b600SNeel Natu 	vdso_th->th_x86_shift = (int)(intptr_t)tc->tc_priv;
97516808549SKonstantin Belousov 	vdso_th->th_x86_hpet_idx = 0xffffffff;
976d4b2d303SAdam Fenn 	vdso_th->th_x86_pvc_last_systime = 0;
977d4b2d303SAdam Fenn 	vdso_th->th_x86_pvc_stable_mask = 0;
978aea81038SKonstantin Belousov 	bzero(vdso_th->th_res, sizeof(vdso_th->th_res));
97916808549SKonstantin Belousov 	return (1);
980aea81038SKonstantin Belousov }
981aea81038SKonstantin Belousov 
982aea81038SKonstantin Belousov #ifdef COMPAT_FREEBSD32
98316808549SKonstantin Belousov static uint32_t
x86_tsc_vdso_timehands32(struct vdso_timehands32 * vdso_th32,struct timecounter * tc)98416808549SKonstantin Belousov x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
985d1b1b600SNeel Natu     struct timecounter *tc)
986aea81038SKonstantin Belousov {
987aea81038SKonstantin Belousov 
98816808549SKonstantin Belousov 	vdso_th32->th_algo = VDSO_TH_ALGO_X86_TSC;
989d1b1b600SNeel Natu 	vdso_th32->th_x86_shift = (int)(intptr_t)tc->tc_priv;
99016808549SKonstantin Belousov 	vdso_th32->th_x86_hpet_idx = 0xffffffff;
99193626d54SKonstantin Belousov 	vdso_th32->th_x86_pvc_last_systime[0] = 0;
99293626d54SKonstantin Belousov 	vdso_th32->th_x86_pvc_last_systime[1] = 0;
993d4b2d303SAdam Fenn 	vdso_th32->th_x86_pvc_stable_mask = 0;
994aea81038SKonstantin Belousov 	bzero(vdso_th32->th_res, sizeof(vdso_th32->th_res));
99516808549SKonstantin Belousov 	return (1);
996aea81038SKonstantin Belousov }
997aea81038SKonstantin Belousov #endif
998