xref: /freebsd/sys/x86/x86/tsc.c (revision 075e2779aca7cbd8f201ce0e1bb60318d0cbd8b8)
1dd7d207dSJung-uk Kim /*-
2ebf5747bSPedro F. Giffuni  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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 
150506a906cSKonstantin Belousov /*
15122875f88SMark Johnston  * Calculate TSC frequency using information from the CPUID leaf 0x15 'Time
15222875f88SMark Johnston  * Stamp Counter and Nominal Core Crystal Clock'.  If leaf 0x15 is not
15322875f88SMark Johnston  * functional, as it is on Skylake/Kabylake, try 0x16 'Processor Frequency
15422875f88SMark Johnston  * Information'.  Leaf 0x16 is described in the SDM as informational only, but
15522875f88SMark Johnston  * we can use this value until late calibration is complete.
156506a906cSKonstantin Belousov  */
157506a906cSKonstantin Belousov static bool
158bd8a359fSKonstantin Belousov tsc_freq_cpuid(uint64_t *res)
159506a906cSKonstantin Belousov {
160506a906cSKonstantin Belousov 	u_int regs[4];
161506a906cSKonstantin Belousov 
162506a906cSKonstantin Belousov 	if (cpu_high < 0x15)
163506a906cSKonstantin Belousov 		return (false);
164506a906cSKonstantin Belousov 	do_cpuid(0x15, regs);
165a9d0e007SKonstantin Belousov 	if (regs[0] != 0 && regs[1] != 0 && regs[2] != 0) {
166bd8a359fSKonstantin Belousov 		*res = (uint64_t)regs[2] * regs[1] / regs[0];
167506a906cSKonstantin Belousov 		return (true);
168506a906cSKonstantin Belousov 	}
169506a906cSKonstantin Belousov 
170a9d0e007SKonstantin Belousov 	if (cpu_high < 0x16)
171a9d0e007SKonstantin Belousov 		return (false);
172a9d0e007SKonstantin Belousov 	do_cpuid(0x16, regs);
173a9d0e007SKonstantin Belousov 	if (regs[0] != 0) {
174bd8a359fSKonstantin Belousov 		*res = (uint64_t)regs[0] * 1000000;
175a9d0e007SKonstantin Belousov 		return (true);
176a9d0e007SKonstantin Belousov 	}
177a9d0e007SKonstantin Belousov 
178a9d0e007SKonstantin Belousov 	return (false);
179a9d0e007SKonstantin Belousov }
180a9d0e007SKonstantin Belousov 
18122875f88SMark Johnston static bool
18222875f88SMark Johnston tsc_freq_intel_brand(uint64_t *res)
183dd7d207dSJung-uk Kim {
184a4e4127fSJung-uk Kim 	char brand[48];
185a4e4127fSJung-uk Kim 	u_int regs[4];
186a4e4127fSJung-uk Kim 	uint64_t freq;
187a4e4127fSJung-uk Kim 	char *p;
188a4e4127fSJung-uk Kim 	u_int i;
189dd7d207dSJung-uk Kim 
190a4e4127fSJung-uk Kim 	/*
191a4e4127fSJung-uk Kim 	 * Intel Processor Identification and the CPUID Instruction
192a4e4127fSJung-uk Kim 	 * Application Note 485.
193a4e4127fSJung-uk Kim 	 * http://www.intel.com/assets/pdf/appnote/241618.pdf
194a4e4127fSJung-uk Kim 	 */
195a4e4127fSJung-uk Kim 	if (cpu_exthigh >= 0x80000004) {
196a4e4127fSJung-uk Kim 		p = brand;
197a4e4127fSJung-uk Kim 		for (i = 0x80000002; i < 0x80000005; i++) {
198a4e4127fSJung-uk Kim 			do_cpuid(i, regs);
199a4e4127fSJung-uk Kim 			memcpy(p, regs, sizeof(regs));
200a4e4127fSJung-uk Kim 			p += sizeof(regs);
201a4e4127fSJung-uk Kim 		}
202a4e4127fSJung-uk Kim 		p = NULL;
203a4e4127fSJung-uk Kim 		for (i = 0; i < sizeof(brand) - 1; i++)
204a4e4127fSJung-uk Kim 			if (brand[i] == 'H' && brand[i + 1] == 'z')
205a4e4127fSJung-uk Kim 				p = brand + i;
206a4e4127fSJung-uk Kim 		if (p != NULL) {
207a4e4127fSJung-uk Kim 			p -= 5;
208a4e4127fSJung-uk Kim 			switch (p[4]) {
209a4e4127fSJung-uk Kim 			case 'M':
210a4e4127fSJung-uk Kim 				i = 1;
211a4e4127fSJung-uk Kim 				break;
212a4e4127fSJung-uk Kim 			case 'G':
213a4e4127fSJung-uk Kim 				i = 1000;
214a4e4127fSJung-uk Kim 				break;
215a4e4127fSJung-uk Kim 			case 'T':
216a4e4127fSJung-uk Kim 				i = 1000000;
217a4e4127fSJung-uk Kim 				break;
218a4e4127fSJung-uk Kim 			default:
21922875f88SMark Johnston 				return (false);
220a4e4127fSJung-uk Kim 			}
221a4e4127fSJung-uk Kim #define	C2D(c)	((c) - '0')
222a4e4127fSJung-uk Kim 			if (p[1] == '.') {
223a4e4127fSJung-uk Kim 				freq = C2D(p[0]) * 1000;
224a4e4127fSJung-uk Kim 				freq += C2D(p[2]) * 100;
225a4e4127fSJung-uk Kim 				freq += C2D(p[3]) * 10;
226a4e4127fSJung-uk Kim 				freq *= i * 1000;
227a4e4127fSJung-uk Kim 			} else {
228a4e4127fSJung-uk Kim 				freq = C2D(p[0]) * 1000;
229a4e4127fSJung-uk Kim 				freq += C2D(p[1]) * 100;
230a4e4127fSJung-uk Kim 				freq += C2D(p[2]) * 10;
231a4e4127fSJung-uk Kim 				freq += C2D(p[3]);
232a4e4127fSJung-uk Kim 				freq *= i * 1000000;
233a4e4127fSJung-uk Kim 			}
234a4e4127fSJung-uk Kim #undef C2D
23522875f88SMark Johnston 			*res = freq;
23622875f88SMark Johnston 			return (true);
237a4e4127fSJung-uk Kim 		}
238a4e4127fSJung-uk Kim 	}
23922875f88SMark Johnston 	return (false);
24022875f88SMark Johnston }
24122875f88SMark Johnston 
24222875f88SMark Johnston static void
243*075e2779SMark Johnston tsc_freq_tc(uint64_t *res)
24422875f88SMark Johnston {
24522875f88SMark Johnston 	uint64_t tsc1, tsc2;
24622875f88SMark Johnston 	int64_t overhead;
24722875f88SMark Johnston 	int count, i;
24822875f88SMark Johnston 
24922875f88SMark Johnston 	overhead = 0;
25022875f88SMark Johnston 	for (i = 0, count = 8; i < count; i++) {
25122875f88SMark Johnston 		tsc1 = rdtsc_ordered();
25222875f88SMark Johnston 		DELAY(0);
25322875f88SMark Johnston 		tsc2 = rdtsc_ordered();
25422875f88SMark Johnston 		if (i > 0)
25522875f88SMark Johnston 			overhead += tsc2 - tsc1;
25622875f88SMark Johnston 	}
25722875f88SMark Johnston 	overhead /= count;
25822875f88SMark Johnston 
25922875f88SMark Johnston 	tsc1 = rdtsc_ordered();
26022875f88SMark Johnston 	DELAY(100000);
26122875f88SMark Johnston 	tsc2 = rdtsc_ordered();
26222875f88SMark Johnston 	tsc_freq = (tsc2 - tsc1 - overhead) * 10;
263a4e4127fSJung-uk Kim }
264dd7d207dSJung-uk Kim 
265*075e2779SMark Johnston /*
266*075e2779SMark Johnston  * Try to determine the TSC frequency using CPUID or hypercalls.  If successful,
267*075e2779SMark Johnston  * this lets use the TSC for early DELAY() calls instead of the 8254 timer,
268*075e2779SMark Johnston  * which may be unreliable or entirely absent on contemporary systems.  However,
269*075e2779SMark Johnston  * avoid calibrating using the 8254 here so as to give hypervisors a chance to
270*075e2779SMark Johnston  * register a timecounter that can be used instead.
271*075e2779SMark Johnston  */
272a4e4127fSJung-uk Kim static void
273*075e2779SMark Johnston probe_tsc_freq_early(void)
274a4e4127fSJung-uk Kim {
27584369dd5SMark Johnston #ifdef __i386__
27684369dd5SMark Johnston 	/* The TSC is known to be broken on certain CPUs. */
27784369dd5SMark Johnston 	switch (cpu_vendor_id) {
27884369dd5SMark Johnston 	case CPU_VENDOR_AMD:
27984369dd5SMark Johnston 		switch (cpu_id & 0xFF0) {
28084369dd5SMark Johnston 		case 0x500:
28184369dd5SMark Johnston 			/* K5 Model 0 */
28284369dd5SMark Johnston 			tsc_disabled = 1;
28384369dd5SMark Johnston 			return;
2845da5812bSJung-uk Kim 		}
28584369dd5SMark Johnston 		break;
28684369dd5SMark Johnston 	case CPU_VENDOR_CENTAUR:
28784369dd5SMark Johnston 		switch (cpu_id & 0xff0) {
28884369dd5SMark Johnston 		case 0x540:
28984369dd5SMark Johnston 			/*
29084369dd5SMark Johnston 			 * http://www.centtech.com/c6_data_sheet.pdf
29184369dd5SMark Johnston 			 *
29284369dd5SMark Johnston 			 * I-12 RDTSC may return incoherent values in EDX:EAX
29384369dd5SMark Johnston 			 * I-13 RDTSC hangs when certain event counters are used
29484369dd5SMark Johnston 			 */
29584369dd5SMark Johnston 			tsc_disabled = 1;
29684369dd5SMark Johnston 			return;
29784369dd5SMark Johnston 		}
29884369dd5SMark Johnston 		break;
29984369dd5SMark Johnston 	case CPU_VENDOR_NSC:
30084369dd5SMark Johnston 		switch (cpu_id & 0xff0) {
30184369dd5SMark Johnston 		case 0x540:
30284369dd5SMark Johnston 			if ((cpu_id & CPUID_STEPPING) == 0) {
30384369dd5SMark Johnston 				tsc_disabled = 1;
30484369dd5SMark Johnston 				return;
30584369dd5SMark Johnston 			}
30684369dd5SMark Johnston 			break;
30784369dd5SMark Johnston 		}
30884369dd5SMark Johnston 		break;
30984369dd5SMark Johnston 	}
31084369dd5SMark Johnston #endif
3115da5812bSJung-uk Kim 
312dd7d207dSJung-uk Kim 	switch (cpu_vendor_id) {
313dd7d207dSJung-uk Kim 	case CPU_VENDOR_AMD:
3142ee49facSKonstantin Belousov 	case CPU_VENDOR_HYGON:
315a106a27cSJung-uk Kim 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
316a106a27cSJung-uk Kim 		    (vm_guest == VM_GUEST_NO &&
317a106a27cSJung-uk Kim 		    CPUID_TO_FAMILY(cpu_id) >= 0x10))
318dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
319814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
320814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
321814124c3SKonstantin Belousov 			    tsc_get_timecount_mfence;
322814124c3SKonstantin Belousov 		}
323dd7d207dSJung-uk Kim 		break;
324dd7d207dSJung-uk Kim 	case CPU_VENDOR_INTEL:
325a106a27cSJung-uk Kim 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
326a106a27cSJung-uk Kim 		    (vm_guest == VM_GUEST_NO &&
327a106a27cSJung-uk Kim 		    ((CPUID_TO_FAMILY(cpu_id) == 0x6 &&
328dd7d207dSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0xe) ||
329dd7d207dSJung-uk Kim 		    (CPUID_TO_FAMILY(cpu_id) == 0xf &&
330a106a27cSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0x3))))
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_lfence;
335814124c3SKonstantin Belousov 		}
336dd7d207dSJung-uk Kim 		break;
337dd7d207dSJung-uk Kim 	case CPU_VENDOR_CENTAUR:
338a106a27cSJung-uk Kim 		if (vm_guest == VM_GUEST_NO &&
339a106a27cSJung-uk Kim 		    CPUID_TO_FAMILY(cpu_id) == 0x6 &&
340dd7d207dSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0xf &&
341dd7d207dSJung-uk Kim 		    (rdmsr(0x1203) & 0x100000000ULL) == 0)
342dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
343814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
344814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
345814124c3SKonstantin Belousov 			    tsc_get_timecount_lfence;
346814124c3SKonstantin Belousov 		}
347dd7d207dSJung-uk Kim 		break;
348dd7d207dSJung-uk Kim 	}
349dd7d207dSJung-uk Kim 
35084369dd5SMark Johnston 	if (tsc_freq_cpuid_vm()) {
35184369dd5SMark Johnston 		if (bootverbose)
35284369dd5SMark Johnston 			printf(
35384369dd5SMark Johnston 		    "Early TSC frequency %juHz derived from hypervisor CPUID\n",
35484369dd5SMark Johnston 			    (uintmax_t)tsc_freq);
35584369dd5SMark Johnston 	} else if (vm_guest == VM_GUEST_VMWARE) {
356fd980febSColin Percival 		tsc_freq_vmware();
35784369dd5SMark Johnston 		if (bootverbose)
35884369dd5SMark Johnston 			printf(
35984369dd5SMark Johnston 		    "Early TSC frequency %juHz derived from VMWare hypercall\n",
36084369dd5SMark Johnston 			    (uintmax_t)tsc_freq);
36184369dd5SMark Johnston 	} else if (tsc_freq_cpuid(&tsc_freq)) {
362bd8a359fSKonstantin Belousov 		/*
36322875f88SMark Johnston 		 * If possible, use the value obtained from CPUID as the initial
36422875f88SMark Johnston 		 * frequency.  This will be refined later during boot but is
36522875f88SMark Johnston 		 * good enough for now.  The 8254 PIT is not functional on some
36622875f88SMark Johnston 		 * newer platforms anyway, so don't delay our boot for what
36722875f88SMark Johnston 		 * might be a garbage result.  Late calibration is required if
36822875f88SMark Johnston 		 * the initial frequency was obtained from CPUID.16H, as the
36922875f88SMark Johnston 		 * derived value may be off by as much as 1%.
370bd8a359fSKonstantin Belousov 		 */
371a4e4127fSJung-uk Kim 		if (bootverbose)
37222875f88SMark Johnston 			printf("Early TSC frequency %juHz derived from CPUID\n",
37322875f88SMark Johnston 			    (uintmax_t)tsc_freq);
374*075e2779SMark Johnston 	}
375*075e2779SMark Johnston }
376*075e2779SMark Johnston 
377*075e2779SMark Johnston /*
378*075e2779SMark Johnston  * If we were unable to determine the TSC frequency via CPU registers, try
379*075e2779SMark Johnston  * to calibrate against a known clock.
380*075e2779SMark Johnston  */
381*075e2779SMark Johnston static void
382*075e2779SMark Johnston probe_tsc_freq_late(void)
383*075e2779SMark Johnston {
384*075e2779SMark Johnston 	if (tsc_freq != 0)
385*075e2779SMark Johnston 		return;
386*075e2779SMark Johnston 
387*075e2779SMark Johnston 	if (tsc_skip_calibration) {
38822875f88SMark Johnston 		/*
38922875f88SMark Johnston 		 * Try to parse the brand string to obtain the nominal TSC
39022875f88SMark Johnston 		 * frequency.
39122875f88SMark Johnston 		 */
39222875f88SMark Johnston 		if (cpu_vendor_id == CPU_VENDOR_INTEL &&
39322875f88SMark Johnston 		    tsc_freq_intel_brand(&tsc_freq)) {
39422875f88SMark Johnston 			if (bootverbose)
39522875f88SMark Johnston 				printf(
39622875f88SMark Johnston 		    "Early TSC frequency %juHz derived from brand string\n",
39722875f88SMark Johnston 				    (uintmax_t)tsc_freq);
39822875f88SMark Johnston 		} else {
39922875f88SMark Johnston 			tsc_disabled = 1;
40022875f88SMark Johnston 		}
40122875f88SMark Johnston 	} else {
40222875f88SMark Johnston 		/*
403*075e2779SMark Johnston 		 * Calibrate against a timecounter or the 8254 PIT.  This
404*075e2779SMark Johnston 		 * estimate will be refined later in tsc_calib().
40522875f88SMark Johnston 		 */
406*075e2779SMark Johnston 		tsc_freq_tc(&tsc_freq);
40722875f88SMark Johnston 		if (bootverbose)
40822875f88SMark Johnston 			printf(
40922875f88SMark Johnston 		    "Early TSC frequency %juHz calibrated from 8254 PIT\n",
41022875f88SMark Johnston 			    (uintmax_t)tsc_freq);
41122875f88SMark Johnston 	}
412*075e2779SMark Johnston }
413*075e2779SMark Johnston 
414*075e2779SMark Johnston void
415*075e2779SMark Johnston start_TSC(void)
416*075e2779SMark Johnston {
417*075e2779SMark Johnston 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
418*075e2779SMark Johnston 		return;
419*075e2779SMark Johnston 
420*075e2779SMark Johnston 	probe_tsc_freq_late();
42184369dd5SMark Johnston 
42284369dd5SMark Johnston 	if (cpu_power_ecx & CPUID_PERF_STAT) {
42384369dd5SMark Johnston 		/*
42484369dd5SMark Johnston 		 * XXX Some emulators expose host CPUID without actual support
42584369dd5SMark Johnston 		 * for these MSRs.  We must test whether they really work.
42684369dd5SMark Johnston 		 */
42784369dd5SMark Johnston 		wrmsr(MSR_MPERF, 0);
42884369dd5SMark Johnston 		wrmsr(MSR_APERF, 0);
42984369dd5SMark Johnston 		DELAY(10);
43084369dd5SMark Johnston 		if (rdmsr(MSR_MPERF) > 0 && rdmsr(MSR_APERF) > 0)
43184369dd5SMark Johnston 			tsc_perf_stat = 1;
43284369dd5SMark Johnston 	}
433a4e4127fSJung-uk Kim 
434dd7d207dSJung-uk Kim 	/*
435dd7d207dSJung-uk Kim 	 * Inform CPU accounting about our boot-time clock rate.  This will
436dd7d207dSJung-uk Kim 	 * be updated if someone loads a cpufreq driver after boot that
437dd7d207dSJung-uk Kim 	 * discovers a new max frequency.
43822875f88SMark Johnston 	 *
43922875f88SMark Johnston 	 * The frequency may also be updated after late calibration is complete;
44022875f88SMark Johnston 	 * however, we register the TSC as the ticker now to avoid switching
44122875f88SMark Johnston 	 * counters after much of the kernel has already booted and potentially
44222875f88SMark Johnston 	 * sampled the CPU clock.
443dd7d207dSJung-uk Kim 	 */
444a4e4127fSJung-uk Kim 	if (tsc_freq != 0)
4455ac44f72SJung-uk Kim 		set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
446dd7d207dSJung-uk Kim 
447dd7d207dSJung-uk Kim 	if (tsc_is_invariant)
448dd7d207dSJung-uk Kim 		return;
449dd7d207dSJung-uk Kim 
450dd7d207dSJung-uk Kim 	/* Register to find out about changes in CPU frequency. */
451dd7d207dSJung-uk Kim 	tsc_pre_tag = EVENTHANDLER_REGISTER(cpufreq_pre_change,
452dd7d207dSJung-uk Kim 	    tsc_freq_changing, NULL, EVENTHANDLER_PRI_FIRST);
453dd7d207dSJung-uk Kim 	tsc_post_tag = EVENTHANDLER_REGISTER(cpufreq_post_change,
454dd7d207dSJung-uk Kim 	    tsc_freq_changed, NULL, EVENTHANDLER_PRI_FIRST);
455dd7d207dSJung-uk Kim 	tsc_levels_tag = EVENTHANDLER_REGISTER(cpufreq_levels_changed,
456dd7d207dSJung-uk Kim 	    tsc_levels_changed, NULL, EVENTHANDLER_PRI_ANY);
457dd7d207dSJung-uk Kim }
458dd7d207dSJung-uk Kim 
45965e7d70bSJung-uk Kim #ifdef SMP
46065e7d70bSJung-uk Kim 
461814124c3SKonstantin Belousov /*
462814124c3SKonstantin Belousov  * RDTSC is not a serializing instruction, and does not drain
463814124c3SKonstantin Belousov  * instruction stream, so we need to drain the stream before executing
464814124c3SKonstantin Belousov  * it.  It could be fixed by use of RDTSCP, except the instruction is
465814124c3SKonstantin Belousov  * not available everywhere.
466814124c3SKonstantin Belousov  *
467814124c3SKonstantin Belousov  * Use CPUID for draining in the boot-time SMP constistency test.  The
468814124c3SKonstantin Belousov  * timecounters use MFENCE for AMD CPUs, and LFENCE for others (Intel
469814124c3SKonstantin Belousov  * and VIA) when SSE2 is present, and nothing on older machines which
470814124c3SKonstantin Belousov  * also do not issue RDTSC prematurely.  There, testing for SSE2 and
471e1a18e46SKonstantin Belousov  * vendor is too cumbersome, and we learn about TSC presence from CPUID.
472814124c3SKonstantin Belousov  *
473814124c3SKonstantin Belousov  * Do not use do_cpuid(), since we do not need CPUID results, which
474814124c3SKonstantin Belousov  * have to be written into memory with do_cpuid().
475814124c3SKonstantin Belousov  */
47665e7d70bSJung-uk Kim #define	TSC_READ(x)							\
47765e7d70bSJung-uk Kim static void								\
47865e7d70bSJung-uk Kim tsc_read_##x(void *arg)							\
47965e7d70bSJung-uk Kim {									\
4807bfcb3bbSJim Harris 	uint64_t *tsc = arg;						\
48165e7d70bSJung-uk Kim 	u_int cpu = PCPU_GET(cpuid);					\
48265e7d70bSJung-uk Kim 									\
483814124c3SKonstantin Belousov 	__asm __volatile("cpuid" : : : "eax", "ebx", "ecx", "edx");	\
4847bfcb3bbSJim Harris 	tsc[cpu * 3 + x] = rdtsc();					\
48565e7d70bSJung-uk Kim }
48665e7d70bSJung-uk Kim TSC_READ(0)
48765e7d70bSJung-uk Kim TSC_READ(1)
48865e7d70bSJung-uk Kim TSC_READ(2)
48965e7d70bSJung-uk Kim #undef TSC_READ
49065e7d70bSJung-uk Kim 
49165e7d70bSJung-uk Kim #define	N	1000
49265e7d70bSJung-uk Kim 
49365e7d70bSJung-uk Kim static void
49465e7d70bSJung-uk Kim comp_smp_tsc(void *arg)
49565e7d70bSJung-uk Kim {
4967bfcb3bbSJim Harris 	uint64_t *tsc;
4977bfcb3bbSJim Harris 	int64_t d1, d2;
49865e7d70bSJung-uk Kim 	u_int cpu = PCPU_GET(cpuid);
49965e7d70bSJung-uk Kim 	u_int i, j, size;
50065e7d70bSJung-uk Kim 
50165e7d70bSJung-uk Kim 	size = (mp_maxid + 1) * 3;
50265e7d70bSJung-uk Kim 	for (i = 0, tsc = arg; i < N; i++, tsc += size)
50365e7d70bSJung-uk Kim 		CPU_FOREACH(j) {
50465e7d70bSJung-uk Kim 			if (j == cpu)
50565e7d70bSJung-uk Kim 				continue;
50665e7d70bSJung-uk Kim 			d1 = tsc[cpu * 3 + 1] - tsc[j * 3];
50765e7d70bSJung-uk Kim 			d2 = tsc[cpu * 3 + 2] - tsc[j * 3 + 1];
50865e7d70bSJung-uk Kim 			if (d1 <= 0 || d2 <= 0) {
50965e7d70bSJung-uk Kim 				smp_tsc = 0;
51065e7d70bSJung-uk Kim 				return;
51165e7d70bSJung-uk Kim 			}
51265e7d70bSJung-uk Kim 		}
51365e7d70bSJung-uk Kim }
51465e7d70bSJung-uk Kim 
515b2c63698SAlexander Motin static void
516b2c63698SAlexander Motin adj_smp_tsc(void *arg)
517b2c63698SAlexander Motin {
518b2c63698SAlexander Motin 	uint64_t *tsc;
519b2c63698SAlexander Motin 	int64_t d, min, max;
520b2c63698SAlexander Motin 	u_int cpu = PCPU_GET(cpuid);
521b2c63698SAlexander Motin 	u_int first, i, size;
522b2c63698SAlexander Motin 
523b2c63698SAlexander Motin 	first = CPU_FIRST();
524b2c63698SAlexander Motin 	if (cpu == first)
525b2c63698SAlexander Motin 		return;
526b2c63698SAlexander Motin 	min = INT64_MIN;
527b2c63698SAlexander Motin 	max = INT64_MAX;
528b2c63698SAlexander Motin 	size = (mp_maxid + 1) * 3;
529b2c63698SAlexander Motin 	for (i = 0, tsc = arg; i < N; i++, tsc += size) {
530b2c63698SAlexander Motin 		d = tsc[first * 3] - tsc[cpu * 3 + 1];
531b2c63698SAlexander Motin 		if (d > min)
532b2c63698SAlexander Motin 			min = d;
533b2c63698SAlexander Motin 		d = tsc[first * 3 + 1] - tsc[cpu * 3 + 2];
534b2c63698SAlexander Motin 		if (d > min)
535b2c63698SAlexander Motin 			min = d;
536b2c63698SAlexander Motin 		d = tsc[first * 3 + 1] - tsc[cpu * 3];
537b2c63698SAlexander Motin 		if (d < max)
538b2c63698SAlexander Motin 			max = d;
539b2c63698SAlexander Motin 		d = tsc[first * 3 + 2] - tsc[cpu * 3 + 1];
540b2c63698SAlexander Motin 		if (d < max)
541b2c63698SAlexander Motin 			max = d;
542b2c63698SAlexander Motin 	}
543b2c63698SAlexander Motin 	if (min > max)
544b2c63698SAlexander Motin 		return;
545b2c63698SAlexander Motin 	d = min / 2 + max / 2;
546b2c63698SAlexander Motin 	__asm __volatile (
547b2c63698SAlexander Motin 		"movl $0x10, %%ecx\n\t"
548b2c63698SAlexander Motin 		"rdmsr\n\t"
549b2c63698SAlexander Motin 		"addl %%edi, %%eax\n\t"
550b2c63698SAlexander Motin 		"adcl %%esi, %%edx\n\t"
551b2c63698SAlexander Motin 		"wrmsr\n"
552b2c63698SAlexander Motin 		: /* No output */
553b2c63698SAlexander Motin 		: "D" ((uint32_t)d), "S" ((uint32_t)(d >> 32))
554b2c63698SAlexander Motin 		: "ax", "cx", "dx", "cc"
555b2c63698SAlexander Motin 	);
556b2c63698SAlexander Motin }
557b2c63698SAlexander Motin 
55865e7d70bSJung-uk Kim static int
559279be68bSAndriy Gapon test_tsc(int adj_max_count)
56065e7d70bSJung-uk Kim {
5617bfcb3bbSJim Harris 	uint64_t *data, *tsc;
562b2c63698SAlexander Motin 	u_int i, size, adj;
56365e7d70bSJung-uk Kim 
56484eaf2ccSKonstantin Belousov 	if ((!smp_tsc && !tsc_is_invariant))
56565e7d70bSJung-uk Kim 		return (-100);
5668cc15b0dSKyle Evans 	/*
5678cc15b0dSKyle Evans 	 * Misbehavior of TSC under VirtualBox has been observed.  In
5688cc15b0dSKyle Evans 	 * particular, threads doing small (~1 second) sleeps may miss their
5698cc15b0dSKyle Evans 	 * wakeup and hang around in sleep state, causing hangs on shutdown.
5708cc15b0dSKyle Evans 	 */
5718cc15b0dSKyle Evans 	if (vm_guest == VM_GUEST_VBOX)
5728cc15b0dSKyle Evans 		return (0);
5738cc15b0dSKyle Evans 
574cd165c8bSColin Percival 	TSENTER();
57565e7d70bSJung-uk Kim 	size = (mp_maxid + 1) * 3;
57665e7d70bSJung-uk Kim 	data = malloc(sizeof(*data) * size * N, M_TEMP, M_WAITOK);
577b2c63698SAlexander Motin 	adj = 0;
578b2c63698SAlexander Motin retry:
57965e7d70bSJung-uk Kim 	for (i = 0, tsc = data; i < N; i++, tsc += size)
58065e7d70bSJung-uk Kim 		smp_rendezvous(tsc_read_0, tsc_read_1, tsc_read_2, tsc);
58165e7d70bSJung-uk Kim 	smp_tsc = 1;	/* XXX */
58267d955aaSPatrick Kelsey 	smp_rendezvous(smp_no_rendezvous_barrier, comp_smp_tsc,
58367d955aaSPatrick Kelsey 	    smp_no_rendezvous_barrier, data);
584279be68bSAndriy Gapon 	if (!smp_tsc && adj < adj_max_count) {
585b2c63698SAlexander Motin 		adj++;
58667d955aaSPatrick Kelsey 		smp_rendezvous(smp_no_rendezvous_barrier, adj_smp_tsc,
58767d955aaSPatrick Kelsey 		    smp_no_rendezvous_barrier, data);
588b2c63698SAlexander Motin 		goto retry;
589b2c63698SAlexander Motin 	}
59065e7d70bSJung-uk Kim 	free(data, M_TEMP);
59165e7d70bSJung-uk Kim 	if (bootverbose)
592b2c63698SAlexander Motin 		printf("SMP: %sed TSC synchronization test%s\n",
593b2c63698SAlexander Motin 		    smp_tsc ? "pass" : "fail",
594b2c63698SAlexander Motin 		    adj > 0 ? " after adjustment" : "");
595cd165c8bSColin Percival 	TSEXIT();
59626e6537aSJung-uk Kim 	if (smp_tsc && tsc_is_invariant) {
59726e6537aSJung-uk Kim 		switch (cpu_vendor_id) {
59826e6537aSJung-uk Kim 		case CPU_VENDOR_AMD:
5992ee49facSKonstantin Belousov 		case CPU_VENDOR_HYGON:
60026e6537aSJung-uk Kim 			/*
601450d86fcSJung-uk Kim 			 * Processor Programming Reference (PPR) for AMD
602450d86fcSJung-uk Kim 			 * Family 17h states that the TSC uses a common
603450d86fcSJung-uk Kim 			 * reference for all sockets, cores and threads.
604450d86fcSJung-uk Kim 			 */
605450d86fcSJung-uk Kim 			if (CPUID_TO_FAMILY(cpu_id) >= 0x17)
606450d86fcSJung-uk Kim 				return (1000);
607450d86fcSJung-uk Kim 			/*
60826e6537aSJung-uk Kim 			 * Starting with Family 15h processors, TSC clock
60926e6537aSJung-uk Kim 			 * source is in the north bridge.  Check whether
61026e6537aSJung-uk Kim 			 * we have a single-socket/multi-core platform.
61126e6537aSJung-uk Kim 			 * XXX Need more work for complex cases.
61226e6537aSJung-uk Kim 			 */
61326e6537aSJung-uk Kim 			if (CPUID_TO_FAMILY(cpu_id) < 0x15 ||
61426e6537aSJung-uk Kim 			    (amd_feature2 & AMDID2_CMP) == 0 ||
61526e6537aSJung-uk Kim 			    smp_cpus > (cpu_procinfo2 & AMDID_CMP_CORES) + 1)
61626e6537aSJung-uk Kim 				break;
61726e6537aSJung-uk Kim 			return (1000);
61826e6537aSJung-uk Kim 		case CPU_VENDOR_INTEL:
61926e6537aSJung-uk Kim 			/*
62026e6537aSJung-uk Kim 			 * XXX Assume Intel platforms have synchronized TSCs.
62126e6537aSJung-uk Kim 			 */
62226e6537aSJung-uk Kim 			return (1000);
62326e6537aSJung-uk Kim 		}
62426e6537aSJung-uk Kim 		return (800);
62526e6537aSJung-uk Kim 	}
62626e6537aSJung-uk Kim 	return (-100);
62765e7d70bSJung-uk Kim }
62865e7d70bSJung-uk Kim 
62965e7d70bSJung-uk Kim #undef N
63065e7d70bSJung-uk Kim 
63165e7d70bSJung-uk Kim #endif /* SMP */
63265e7d70bSJung-uk Kim 
63365e7d70bSJung-uk Kim static void
634dd7d207dSJung-uk Kim init_TSC_tc(void)
635dd7d207dSJung-uk Kim {
63695f2f098SJung-uk Kim 	uint64_t max_freq;
63795f2f098SJung-uk Kim 	int shift;
638dd7d207dSJung-uk Kim 
63938b8542cSJung-uk Kim 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
640dd7d207dSJung-uk Kim 		return;
641dd7d207dSJung-uk Kim 
642dd7d207dSJung-uk Kim 	/*
64395f2f098SJung-uk Kim 	 * Limit timecounter frequency to fit in an int and prevent it from
64495f2f098SJung-uk Kim 	 * overflowing too fast.
64595f2f098SJung-uk Kim 	 */
64695f2f098SJung-uk Kim 	max_freq = UINT_MAX;
64795f2f098SJung-uk Kim 
64895f2f098SJung-uk Kim 	/*
64992597e06SJohn Baldwin 	 * Intel CPUs without a C-state invariant TSC can stop the TSC
650d1411416SJohn Baldwin 	 * in either C2 or C3.  Disable use of C2 and C3 while using
651d1411416SJohn Baldwin 	 * the TSC as the timecounter.  The timecounter can be changed
652d1411416SJohn Baldwin 	 * to enable C2 and C3.
653d1411416SJohn Baldwin 	 *
654d1411416SJohn Baldwin 	 * Note that the TSC is used as the cputicker for computing
655d1411416SJohn Baldwin 	 * thread runtime regardless of the timecounter setting, so
656d1411416SJohn Baldwin 	 * using an alternate timecounter and enabling C2 or C3 can
657d1411416SJohn Baldwin 	 * result incorrect runtimes for kernel idle threads (but not
658d1411416SJohn Baldwin 	 * for any non-idle threads).
659a49399a9SJung-uk Kim 	 */
6608cd59625SKonstantin Belousov 	if (cpu_vendor_id == CPU_VENDOR_INTEL &&
661a49399a9SJung-uk Kim 	    (amd_pminfo & AMDPM_TSC_INVARIANT) == 0) {
66292597e06SJohn Baldwin 		tsc_timecounter.tc_flags |= TC_FLAGS_C2STOP;
663a49399a9SJung-uk Kim 		if (bootverbose)
664d1411416SJohn Baldwin 			printf("TSC timecounter disables C2 and C3.\n");
665a49399a9SJung-uk Kim 	}
666a49399a9SJung-uk Kim 
667dd7d207dSJung-uk Kim 	/*
668e7f1427dSKonstantin Belousov 	 * We can not use the TSC in SMP mode unless the TSCs on all CPUs
669e7f1427dSKonstantin Belousov 	 * are synchronized.  If the user is sure that the system has
670e7f1427dSKonstantin Belousov 	 * synchronized TSCs, set kern.timecounter.smp_tsc tunable to a
671e7f1427dSKonstantin Belousov 	 * non-zero value.  The TSC seems unreliable in virtualized SMP
6725cf8ac1bSMike Silbersack 	 * environments, so it is set to a negative quality in those cases.
673dd7d207dSJung-uk Kim 	 */
674ba79ab82SAndriy Gapon #ifdef SMP
675e7f1427dSKonstantin Belousov 	if (mp_ncpus > 1)
676279be68bSAndriy Gapon 		tsc_timecounter.tc_quality = test_tsc(smp_tsc_adjust);
677ba79ab82SAndriy Gapon 	else
678ba79ab82SAndriy Gapon #endif /* SMP */
679ba79ab82SAndriy Gapon 	if (tsc_is_invariant)
68026e6537aSJung-uk Kim 		tsc_timecounter.tc_quality = 1000;
681e7f1427dSKonstantin Belousov 	max_freq >>= tsc_shift;
68226e6537aSJung-uk Kim 
683e7f1427dSKonstantin Belousov 	for (shift = 0; shift <= 31 && (tsc_freq >> shift) > max_freq; shift++)
68495f2f098SJung-uk Kim 		;
6859e680e40SKonstantin Belousov 
6869e680e40SKonstantin Belousov 	/*
6879e680e40SKonstantin Belousov 	 * Timecounter implementation selection, top to bottom:
6889e680e40SKonstantin Belousov 	 * - If RDTSCP is available, use RDTSCP.
6899e680e40SKonstantin Belousov 	 * - If fence instructions are provided (SSE2), use LFENCE;RDTSC
6909e680e40SKonstantin Belousov 	 *   on Intel, and MFENCE;RDTSC on AMD.
6919e680e40SKonstantin Belousov 	 * - For really old CPUs, just use RDTSC.
6929e680e40SKonstantin Belousov 	 */
6939f47eeffSKonstantin Belousov 	if ((amd_feature & AMDID_RDTSCP) != 0) {
6949e680e40SKonstantin Belousov 		tsc_timecounter.tc_get_timecount = shift > 0 ?
6959e680e40SKonstantin Belousov 		    tscp_get_timecount_low : tscp_get_timecount;
6969e680e40SKonstantin Belousov 	} else if ((cpu_feature & CPUID_SSE2) != 0 && mp_ncpus > 1) {
6972ee49facSKonstantin Belousov 		if (cpu_vendor_id == CPU_VENDOR_AMD ||
6982ee49facSKonstantin Belousov 		    cpu_vendor_id == CPU_VENDOR_HYGON) {
699e7f1427dSKonstantin Belousov 			tsc_timecounter.tc_get_timecount = shift > 0 ?
700e7f1427dSKonstantin Belousov 			    tsc_get_timecount_low_mfence :
701e7f1427dSKonstantin Belousov 			    tsc_get_timecount_mfence;
702814124c3SKonstantin Belousov 		} else {
703e7f1427dSKonstantin Belousov 			tsc_timecounter.tc_get_timecount = shift > 0 ?
704e7f1427dSKonstantin Belousov 			    tsc_get_timecount_low_lfence :
705e7f1427dSKonstantin Belousov 			    tsc_get_timecount_lfence;
706814124c3SKonstantin Belousov 		}
707e7f1427dSKonstantin Belousov 	} else {
708e7f1427dSKonstantin Belousov 		tsc_timecounter.tc_get_timecount = shift > 0 ?
709e7f1427dSKonstantin Belousov 		    tsc_get_timecount_low : tsc_get_timecount;
710e7f1427dSKonstantin Belousov 	}
711e7f1427dSKonstantin Belousov 	if (shift > 0) {
71295f2f098SJung-uk Kim 		tsc_timecounter.tc_name = "TSC-low";
71395f2f098SJung-uk Kim 		if (bootverbose)
714bc8e4ad2SJung-uk Kim 			printf("TSC timecounter discards lower %d bit(s)\n",
71595f2f098SJung-uk Kim 			    shift);
71695f2f098SJung-uk Kim 	}
717bc34c87eSJung-uk Kim 	if (tsc_freq != 0) {
71895f2f098SJung-uk Kim 		tsc_timecounter.tc_frequency = tsc_freq >> shift;
71995f2f098SJung-uk Kim 		tsc_timecounter.tc_priv = (void *)(intptr_t)shift;
72022875f88SMark Johnston 
72122875f88SMark Johnston 		/*
72222875f88SMark Johnston 		 * Timecounter registration is deferred until after late
72322875f88SMark Johnston 		 * calibration is finished.
72422875f88SMark Johnston 		 */
725dd7d207dSJung-uk Kim 	}
726dd7d207dSJung-uk Kim }
72765e7d70bSJung-uk Kim SYSINIT(tsc_tc, SI_SUB_SMP, SI_ORDER_ANY, init_TSC_tc, NULL);
728dd7d207dSJung-uk Kim 
72922875f88SMark Johnston static void
73022875f88SMark Johnston tsc_update_freq(uint64_t new_freq)
73122875f88SMark Johnston {
73222875f88SMark Johnston 	atomic_store_rel_64(&tsc_freq, new_freq);
73322875f88SMark Johnston 	atomic_store_rel_64(&tsc_timecounter.tc_frequency,
73422875f88SMark Johnston 	    new_freq >> (int)(intptr_t)tsc_timecounter.tc_priv);
73522875f88SMark Johnston }
73622875f88SMark Johnston 
73784369dd5SMark Johnston void
73884369dd5SMark Johnston tsc_init(void)
73984369dd5SMark Johnston {
74084369dd5SMark Johnston 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
74184369dd5SMark Johnston 		return;
74284369dd5SMark Johnston 
743*075e2779SMark Johnston 	probe_tsc_freq_early();
74484369dd5SMark Johnston }
74584369dd5SMark Johnston 
74622875f88SMark Johnston /*
74722875f88SMark Johnston  * Perform late calibration of the TSC frequency once ACPI-based timecounters
748553af8f1SMark Johnston  * are available.  At this point timehands are not set up, so we read the
749553af8f1SMark Johnston  * highest-quality timecounter directly rather than using (s)binuptime().
75022875f88SMark Johnston  */
751553af8f1SMark Johnston void
752553af8f1SMark Johnston tsc_calibrate(void)
75322875f88SMark Johnston {
754c2705ceaSColin Percival 	uint64_t freq;
75522875f88SMark Johnston 
75622875f88SMark Johnston 	if (tsc_disabled)
75722875f88SMark Johnston 		return;
7589cb32882SColin Percival 	if (tsc_early_calib_exact)
7599cb32882SColin Percival 		goto calibrated;
76022875f88SMark Johnston 
761c2705ceaSColin Percival 	fpu_kern_enter(curthread, NULL, FPU_KERN_NOCTX);
762c2705ceaSColin Percival 	freq = clockcalib(rdtsc_ordered, "TSC");
763c2705ceaSColin Percival 	fpu_kern_leave(curthread, NULL);
764698727d6SColin Percival 	tsc_update_freq(freq);
765c2705ceaSColin Percival 
7669cb32882SColin Percival calibrated:
76722875f88SMark Johnston 	tc_init(&tsc_timecounter);
76822875f88SMark Johnston 	set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
76922875f88SMark Johnston }
77022875f88SMark Johnston 
771279be68bSAndriy Gapon void
772279be68bSAndriy Gapon resume_TSC(void)
773279be68bSAndriy Gapon {
774ba79ab82SAndriy Gapon #ifdef SMP
775279be68bSAndriy Gapon 	int quality;
776279be68bSAndriy Gapon 
777279be68bSAndriy Gapon 	/* If TSC was not good on boot, it is unlikely to become good now. */
778279be68bSAndriy Gapon 	if (tsc_timecounter.tc_quality < 0)
779279be68bSAndriy Gapon 		return;
780279be68bSAndriy Gapon 	/* Nothing to do with UP. */
781279be68bSAndriy Gapon 	if (mp_ncpus < 2)
782279be68bSAndriy Gapon 		return;
783279be68bSAndriy Gapon 
784279be68bSAndriy Gapon 	/*
785279be68bSAndriy Gapon 	 * If TSC was good, a single synchronization should be enough,
786279be68bSAndriy Gapon 	 * but honour smp_tsc_adjust if it's set.
787279be68bSAndriy Gapon 	 */
788279be68bSAndriy Gapon 	quality = test_tsc(MAX(smp_tsc_adjust, 1));
789279be68bSAndriy Gapon 	if (quality != tsc_timecounter.tc_quality) {
790279be68bSAndriy Gapon 		printf("TSC timecounter quality changed: %d -> %d\n",
791279be68bSAndriy Gapon 		    tsc_timecounter.tc_quality, quality);
792279be68bSAndriy Gapon 		tsc_timecounter.tc_quality = quality;
793279be68bSAndriy Gapon 	}
794ba79ab82SAndriy Gapon #endif /* SMP */
795279be68bSAndriy Gapon }
796279be68bSAndriy Gapon 
797dd7d207dSJung-uk Kim /*
798dd7d207dSJung-uk Kim  * When cpufreq levels change, find out about the (new) max frequency.  We
799dd7d207dSJung-uk Kim  * use this to update CPU accounting in case it got a lower estimate at boot.
800dd7d207dSJung-uk Kim  */
801dd7d207dSJung-uk Kim static void
802dd7d207dSJung-uk Kim tsc_levels_changed(void *arg, int unit)
803dd7d207dSJung-uk Kim {
804dd7d207dSJung-uk Kim 	device_t cf_dev;
805dd7d207dSJung-uk Kim 	struct cf_level *levels;
806dd7d207dSJung-uk Kim 	int count, error;
807dd7d207dSJung-uk Kim 	uint64_t max_freq;
808dd7d207dSJung-uk Kim 
809dd7d207dSJung-uk Kim 	/* Only use values from the first CPU, assuming all are equal. */
810dd7d207dSJung-uk Kim 	if (unit != 0)
811dd7d207dSJung-uk Kim 		return;
812dd7d207dSJung-uk Kim 
813dd7d207dSJung-uk Kim 	/* Find the appropriate cpufreq device instance. */
814dd7d207dSJung-uk Kim 	cf_dev = devclass_get_device(devclass_find("cpufreq"), unit);
815dd7d207dSJung-uk Kim 	if (cf_dev == NULL) {
816dd7d207dSJung-uk Kim 		printf("tsc_levels_changed() called but no cpufreq device?\n");
817dd7d207dSJung-uk Kim 		return;
818dd7d207dSJung-uk Kim 	}
819dd7d207dSJung-uk Kim 
820dd7d207dSJung-uk Kim 	/* Get settings from the device and find the max frequency. */
821dd7d207dSJung-uk Kim 	count = 64;
822dd7d207dSJung-uk Kim 	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
823dd7d207dSJung-uk Kim 	if (levels == NULL)
824dd7d207dSJung-uk Kim 		return;
825dd7d207dSJung-uk Kim 	error = CPUFREQ_LEVELS(cf_dev, levels, &count);
826dd7d207dSJung-uk Kim 	if (error == 0 && count != 0) {
827dd7d207dSJung-uk Kim 		max_freq = (uint64_t)levels[0].total_set.freq * 1000000;
828dd7d207dSJung-uk Kim 		set_cputicker(rdtsc, max_freq, 1);
829dd7d207dSJung-uk Kim 	} else
830dd7d207dSJung-uk Kim 		printf("tsc_levels_changed: no max freq found\n");
831dd7d207dSJung-uk Kim 	free(levels, M_TEMP);
832dd7d207dSJung-uk Kim }
833dd7d207dSJung-uk Kim 
834dd7d207dSJung-uk Kim /*
835dd7d207dSJung-uk Kim  * If the TSC timecounter is in use, veto the pending change.  It may be
836dd7d207dSJung-uk Kim  * possible in the future to handle a dynamically-changing timecounter rate.
837dd7d207dSJung-uk Kim  */
838dd7d207dSJung-uk Kim static void
839dd7d207dSJung-uk Kim tsc_freq_changing(void *arg, const struct cf_level *level, int *status)
840dd7d207dSJung-uk Kim {
841dd7d207dSJung-uk Kim 
842dd7d207dSJung-uk Kim 	if (*status != 0 || timecounter != &tsc_timecounter)
843dd7d207dSJung-uk Kim 		return;
844dd7d207dSJung-uk Kim 
845dd7d207dSJung-uk Kim 	printf("timecounter TSC must not be in use when "
846dd7d207dSJung-uk Kim 	    "changing frequencies; change denied\n");
847dd7d207dSJung-uk Kim 	*status = EBUSY;
848dd7d207dSJung-uk Kim }
849dd7d207dSJung-uk Kim 
850dd7d207dSJung-uk Kim /* Update TSC freq with the value indicated by the caller. */
851dd7d207dSJung-uk Kim static void
852dd7d207dSJung-uk Kim tsc_freq_changed(void *arg, const struct cf_level *level, int status)
853dd7d207dSJung-uk Kim {
8543453537fSJung-uk Kim 	uint64_t freq;
855dd7d207dSJung-uk Kim 
856dd7d207dSJung-uk Kim 	/* If there was an error during the transition, don't do anything. */
85779422085SJung-uk Kim 	if (tsc_disabled || status != 0)
858dd7d207dSJung-uk Kim 		return;
859dd7d207dSJung-uk Kim 
860dd7d207dSJung-uk Kim 	/* Total setting for this level gives the new frequency in MHz. */
8613453537fSJung-uk Kim 	freq = (uint64_t)level->total_set.freq * 1000000;
86222875f88SMark Johnston 	tsc_update_freq(freq);
863dd7d207dSJung-uk Kim }
864dd7d207dSJung-uk Kim 
865dd7d207dSJung-uk Kim static int
866dd7d207dSJung-uk Kim sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
867dd7d207dSJung-uk Kim {
868dd7d207dSJung-uk Kim 	int error;
869dd7d207dSJung-uk Kim 	uint64_t freq;
870dd7d207dSJung-uk Kim 
8713453537fSJung-uk Kim 	freq = atomic_load_acq_64(&tsc_freq);
8723453537fSJung-uk Kim 	if (freq == 0)
873dd7d207dSJung-uk Kim 		return (EOPNOTSUPP);
874cbc134adSMatthew D Fleming 	error = sysctl_handle_64(oidp, &freq, 0, req);
87522875f88SMark Johnston 	if (error == 0 && req->newptr != NULL)
87622875f88SMark Johnston 		tsc_update_freq(freq);
877dd7d207dSJung-uk Kim 	return (error);
878dd7d207dSJung-uk Kim }
8797029da5cSPawel Biernacki SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq,
8801d6fb900SAlexander Motin     CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
8817029da5cSPawel Biernacki     0, 0, sysctl_machdep_tsc_freq, "QU",
8827029da5cSPawel Biernacki     "Time Stamp Counter frequency");
883dd7d207dSJung-uk Kim 
884727c7b2dSJung-uk Kim static u_int
88595f2f098SJung-uk Kim tsc_get_timecount(struct timecounter *tc __unused)
886dd7d207dSJung-uk Kim {
887727c7b2dSJung-uk Kim 
888727c7b2dSJung-uk Kim 	return (rdtsc32());
889dd7d207dSJung-uk Kim }
89095f2f098SJung-uk Kim 
8919e680e40SKonstantin Belousov static u_int
8929e680e40SKonstantin Belousov tscp_get_timecount(struct timecounter *tc __unused)
8939e680e40SKonstantin Belousov {
8949e680e40SKonstantin Belousov 
8959e680e40SKonstantin Belousov 	return (rdtscp32());
8969e680e40SKonstantin Belousov }
8979e680e40SKonstantin Belousov 
898814124c3SKonstantin Belousov static inline u_int
899bc8e4ad2SJung-uk Kim tsc_get_timecount_low(struct timecounter *tc)
90095f2f098SJung-uk Kim {
9015df88f46SJung-uk Kim 	uint32_t rv;
90295f2f098SJung-uk Kim 
9035df88f46SJung-uk Kim 	__asm __volatile("rdtsc; shrd %%cl, %%edx, %0"
9045df88f46SJung-uk Kim 	    : "=a" (rv) : "c" ((int)(intptr_t)tc->tc_priv) : "edx");
9055df88f46SJung-uk Kim 	return (rv);
90695f2f098SJung-uk Kim }
907aea81038SKonstantin Belousov 
908814124c3SKonstantin Belousov static u_int
9099e680e40SKonstantin Belousov tscp_get_timecount_low(struct timecounter *tc)
9109e680e40SKonstantin Belousov {
9119e680e40SKonstantin Belousov 	uint32_t rv;
9129e680e40SKonstantin Belousov 
9139e680e40SKonstantin Belousov 	__asm __volatile("rdtscp; movl %1, %%ecx; shrd %%cl, %%edx, %0"
914a013e285SKonstantin Belousov 	    : "=&a" (rv) : "m" (tc->tc_priv) : "ecx", "edx");
9159e680e40SKonstantin Belousov 	return (rv);
9169e680e40SKonstantin Belousov }
9179e680e40SKonstantin Belousov 
9189e680e40SKonstantin Belousov static u_int
919814124c3SKonstantin Belousov tsc_get_timecount_lfence(struct timecounter *tc __unused)
920814124c3SKonstantin Belousov {
921814124c3SKonstantin Belousov 
922814124c3SKonstantin Belousov 	lfence();
923814124c3SKonstantin Belousov 	return (rdtsc32());
924814124c3SKonstantin Belousov }
925814124c3SKonstantin Belousov 
926814124c3SKonstantin Belousov static u_int
927814124c3SKonstantin Belousov tsc_get_timecount_low_lfence(struct timecounter *tc)
928814124c3SKonstantin Belousov {
929814124c3SKonstantin Belousov 
930814124c3SKonstantin Belousov 	lfence();
931814124c3SKonstantin Belousov 	return (tsc_get_timecount_low(tc));
932814124c3SKonstantin Belousov }
933814124c3SKonstantin Belousov 
934814124c3SKonstantin Belousov static u_int
935814124c3SKonstantin Belousov tsc_get_timecount_mfence(struct timecounter *tc __unused)
936814124c3SKonstantin Belousov {
937814124c3SKonstantin Belousov 
938814124c3SKonstantin Belousov 	mfence();
939814124c3SKonstantin Belousov 	return (rdtsc32());
940814124c3SKonstantin Belousov }
941814124c3SKonstantin Belousov 
942814124c3SKonstantin Belousov static u_int
943814124c3SKonstantin Belousov tsc_get_timecount_low_mfence(struct timecounter *tc)
944814124c3SKonstantin Belousov {
945814124c3SKonstantin Belousov 
946814124c3SKonstantin Belousov 	mfence();
947814124c3SKonstantin Belousov 	return (tsc_get_timecount_low(tc));
948814124c3SKonstantin Belousov }
949814124c3SKonstantin Belousov 
95016808549SKonstantin Belousov static uint32_t
95116808549SKonstantin Belousov x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th, struct timecounter *tc)
952aea81038SKonstantin Belousov {
953aea81038SKonstantin Belousov 
95416808549SKonstantin Belousov 	vdso_th->th_algo = VDSO_TH_ALGO_X86_TSC;
955d1b1b600SNeel Natu 	vdso_th->th_x86_shift = (int)(intptr_t)tc->tc_priv;
95616808549SKonstantin Belousov 	vdso_th->th_x86_hpet_idx = 0xffffffff;
957d4b2d303SAdam Fenn 	vdso_th->th_x86_pvc_last_systime = 0;
958d4b2d303SAdam Fenn 	vdso_th->th_x86_pvc_stable_mask = 0;
959aea81038SKonstantin Belousov 	bzero(vdso_th->th_res, sizeof(vdso_th->th_res));
96016808549SKonstantin Belousov 	return (1);
961aea81038SKonstantin Belousov }
962aea81038SKonstantin Belousov 
963aea81038SKonstantin Belousov #ifdef COMPAT_FREEBSD32
96416808549SKonstantin Belousov static uint32_t
96516808549SKonstantin Belousov x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
966d1b1b600SNeel Natu     struct timecounter *tc)
967aea81038SKonstantin Belousov {
968aea81038SKonstantin Belousov 
96916808549SKonstantin Belousov 	vdso_th32->th_algo = VDSO_TH_ALGO_X86_TSC;
970d1b1b600SNeel Natu 	vdso_th32->th_x86_shift = (int)(intptr_t)tc->tc_priv;
97116808549SKonstantin Belousov 	vdso_th32->th_x86_hpet_idx = 0xffffffff;
972d4b2d303SAdam Fenn 	vdso_th32->th_x86_pvc_last_systime = 0;
973d4b2d303SAdam Fenn 	vdso_th32->th_x86_pvc_stable_mask = 0;
974aea81038SKonstantin Belousov 	bzero(vdso_th32->th_res, sizeof(vdso_th32->th_res));
97516808549SKonstantin Belousov 	return (1);
976aea81038SKonstantin Belousov }
977aea81038SKonstantin Belousov #endif
978