xref: /freebsd/sys/x86/x86/tsc.c (revision 9f47eeff)
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>
35dd7d207dSJung-uk Kim #include <sys/bus.h>
36dd7d207dSJung-uk Kim #include <sys/cpu.h>
37e2e050c8SConrad Meyer #include <sys/eventhandler.h>
385da5812bSJung-uk Kim #include <sys/limits.h>
39dd7d207dSJung-uk Kim #include <sys/malloc.h>
40dd7d207dSJung-uk Kim #include <sys/systm.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/power.h>
46dd7d207dSJung-uk Kim #include <sys/smp.h>
47aea81038SKonstantin Belousov #include <sys/vdso.h>
48dd7d207dSJung-uk Kim #include <machine/clock.h>
49dd7d207dSJung-uk Kim #include <machine/cputypes.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;
61155094d7SJung-uk Kim 
62dd7d207dSJung-uk Kim static eventhandler_tag tsc_levels_tag, tsc_pre_tag, tsc_post_tag;
63dd7d207dSJung-uk Kim 
64dd7d207dSJung-uk Kim SYSCTL_INT(_kern_timecounter, OID_AUTO, invariant_tsc, CTLFLAG_RDTUN,
65dd7d207dSJung-uk Kim     &tsc_is_invariant, 0, "Indicates whether the TSC is P-state invariant");
66dd7d207dSJung-uk Kim 
67dd7d207dSJung-uk Kim #ifdef SMP
681472b87fSNeel Natu int	smp_tsc;
69dd7d207dSJung-uk Kim SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc, CTLFLAG_RDTUN, &smp_tsc, 0,
70dd7d207dSJung-uk Kim     "Indicates whether the TSC is safe to use in SMP mode");
71b2c63698SAlexander Motin 
72b2c63698SAlexander Motin int	smp_tsc_adjust = 0;
73b2c63698SAlexander Motin SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc_adjust, CTLFLAG_RDTUN,
74b2c63698SAlexander Motin     &smp_tsc_adjust, 0, "Try to adjust TSC on APs to match BSP");
75dd7d207dSJung-uk Kim #endif
76dd7d207dSJung-uk Kim 
77e7f1427dSKonstantin Belousov static int	tsc_shift = 1;
78e7f1427dSKonstantin Belousov SYSCTL_INT(_kern_timecounter, OID_AUTO, tsc_shift, CTLFLAG_RDTUN,
79e7f1427dSKonstantin Belousov     &tsc_shift, 0, "Shift to pre-apply for the maximum TSC frequency");
80e7f1427dSKonstantin Belousov 
8179422085SJung-uk Kim static int	tsc_disabled;
8279422085SJung-uk Kim SYSCTL_INT(_machdep, OID_AUTO, disable_tsc, CTLFLAG_RDTUN, &tsc_disabled, 0,
8379422085SJung-uk Kim     "Disable x86 Time Stamp Counter");
8479422085SJung-uk Kim 
85a4e4127fSJung-uk Kim static int	tsc_skip_calibration;
86ab23c278SKonstantin Belousov SYSCTL_INT(_machdep, OID_AUTO, disable_tsc_calibration, CTLFLAG_RDTUN,
87ab23c278SKonstantin Belousov     &tsc_skip_calibration, 0,
88ce3bf750SKonstantin Belousov     "Disable TSC frequency calibration");
89a4e4127fSJung-uk Kim 
90dd7d207dSJung-uk Kim static void tsc_freq_changed(void *arg, const struct cf_level *level,
91dd7d207dSJung-uk Kim     int status);
92dd7d207dSJung-uk Kim static void tsc_freq_changing(void *arg, const struct cf_level *level,
93dd7d207dSJung-uk Kim     int *status);
94826fc3ccSKonstantin Belousov static u_int tsc_get_timecount(struct timecounter *tc);
95826fc3ccSKonstantin Belousov static inline u_int tsc_get_timecount_low(struct timecounter *tc);
96826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_lfence(struct timecounter *tc);
97826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_low_lfence(struct timecounter *tc);
98826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_mfence(struct timecounter *tc);
99826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_low_mfence(struct timecounter *tc);
1009e680e40SKonstantin Belousov static u_int tscp_get_timecount(struct timecounter *tc);
1019e680e40SKonstantin Belousov static u_int tscp_get_timecount_low(struct timecounter *tc);
102dd7d207dSJung-uk Kim static void tsc_levels_changed(void *arg, int unit);
10316808549SKonstantin Belousov static uint32_t x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th,
10416808549SKonstantin Belousov     struct timecounter *tc);
10516808549SKonstantin Belousov #ifdef COMPAT_FREEBSD32
10616808549SKonstantin Belousov static uint32_t x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
10716808549SKonstantin Belousov     struct timecounter *tc);
10816808549SKonstantin Belousov #endif
109dd7d207dSJung-uk Kim 
110dd7d207dSJung-uk Kim static struct timecounter tsc_timecounter = {
11116808549SKonstantin Belousov 	.tc_get_timecount =		tsc_get_timecount,
11216808549SKonstantin Belousov 	.tc_counter_mask =		~0u,
11316808549SKonstantin Belousov 	.tc_name =			"TSC",
11416808549SKonstantin Belousov 	.tc_quality =			800,	/* adjusted in code */
11516808549SKonstantin Belousov 	.tc_fill_vdso_timehands = 	x86_tsc_vdso_timehands,
11616808549SKonstantin Belousov #ifdef COMPAT_FREEBSD32
11716808549SKonstantin Belousov 	.tc_fill_vdso_timehands32 = 	x86_tsc_vdso_timehands32,
11816808549SKonstantin Belousov #endif
119dd7d207dSJung-uk Kim };
120dd7d207dSJung-uk Kim 
12101e1933dSJohn Baldwin static void
1225da5812bSJung-uk Kim tsc_freq_vmware(void)
1235da5812bSJung-uk Kim {
1245da5812bSJung-uk Kim 	u_int regs[4];
1255da5812bSJung-uk Kim 
1265da5812bSJung-uk Kim 	if (hv_high >= 0x40000010) {
1275da5812bSJung-uk Kim 		do_cpuid(0x40000010, regs);
1285da5812bSJung-uk Kim 		tsc_freq = regs[0] * 1000;
1295da5812bSJung-uk Kim 	} else {
1305da5812bSJung-uk Kim 		vmware_hvcall(VMW_HVCMD_GETHZ, regs);
1315da5812bSJung-uk Kim 		if (regs[1] != UINT_MAX)
1325da5812bSJung-uk Kim 			tsc_freq = regs[0] | ((uint64_t)regs[1] << 32);
1335da5812bSJung-uk Kim 	}
1345da5812bSJung-uk Kim 	tsc_is_invariant = 1;
1355da5812bSJung-uk Kim }
1365da5812bSJung-uk Kim 
137506a906cSKonstantin Belousov /*
138506a906cSKonstantin Belousov  * Calculate TSC frequency using information from the CPUID leaf 0x15
139a9d0e007SKonstantin Belousov  * 'Time Stamp Counter and Nominal Core Crystal Clock'.  If leaf 0x15
140a9d0e007SKonstantin Belousov  * is not functional, as it is on Skylake/Kabylake, try 0x16 'Processor
141a9d0e007SKonstantin Belousov  * Frequency Information'.  Leaf 0x16 is described in the SDM as
142a9d0e007SKonstantin Belousov  * informational only, but if 0x15 did not work, and TSC calibration
143a9d0e007SKonstantin Belousov  * is disabled, it is the best we can get at all.  It should still be
144506a906cSKonstantin Belousov  * an improvement over the parsing of the CPU model name in
145506a906cSKonstantin Belousov  * tsc_freq_intel(), when available.
146506a906cSKonstantin Belousov  */
147506a906cSKonstantin Belousov static bool
148bd8a359fSKonstantin Belousov tsc_freq_cpuid(uint64_t *res)
149506a906cSKonstantin Belousov {
150506a906cSKonstantin Belousov 	u_int regs[4];
151506a906cSKonstantin Belousov 
152506a906cSKonstantin Belousov 	if (cpu_high < 0x15)
153506a906cSKonstantin Belousov 		return (false);
154506a906cSKonstantin Belousov 	do_cpuid(0x15, regs);
155a9d0e007SKonstantin Belousov 	if (regs[0] != 0 && regs[1] != 0 && regs[2] != 0) {
156bd8a359fSKonstantin Belousov 		*res = (uint64_t)regs[2] * regs[1] / regs[0];
157506a906cSKonstantin Belousov 		return (true);
158506a906cSKonstantin Belousov 	}
159506a906cSKonstantin Belousov 
160a9d0e007SKonstantin Belousov 	if (cpu_high < 0x16)
161a9d0e007SKonstantin Belousov 		return (false);
162a9d0e007SKonstantin Belousov 	do_cpuid(0x16, regs);
163a9d0e007SKonstantin Belousov 	if (regs[0] != 0) {
164bd8a359fSKonstantin Belousov 		*res = (uint64_t)regs[0] * 1000000;
165a9d0e007SKonstantin Belousov 		return (true);
166a9d0e007SKonstantin Belousov 	}
167a9d0e007SKonstantin Belousov 
168a9d0e007SKonstantin Belousov 	return (false);
169a9d0e007SKonstantin Belousov }
170a9d0e007SKonstantin Belousov 
171a4e4127fSJung-uk Kim static void
172a4e4127fSJung-uk Kim tsc_freq_intel(void)
173dd7d207dSJung-uk Kim {
174a4e4127fSJung-uk Kim 	char brand[48];
175a4e4127fSJung-uk Kim 	u_int regs[4];
176a4e4127fSJung-uk Kim 	uint64_t freq;
177a4e4127fSJung-uk Kim 	char *p;
178a4e4127fSJung-uk Kim 	u_int i;
179dd7d207dSJung-uk Kim 
180a4e4127fSJung-uk Kim 	/*
181a4e4127fSJung-uk Kim 	 * Intel Processor Identification and the CPUID Instruction
182a4e4127fSJung-uk Kim 	 * Application Note 485.
183a4e4127fSJung-uk Kim 	 * http://www.intel.com/assets/pdf/appnote/241618.pdf
184a4e4127fSJung-uk Kim 	 */
185a4e4127fSJung-uk Kim 	if (cpu_exthigh >= 0x80000004) {
186a4e4127fSJung-uk Kim 		p = brand;
187a4e4127fSJung-uk Kim 		for (i = 0x80000002; i < 0x80000005; i++) {
188a4e4127fSJung-uk Kim 			do_cpuid(i, regs);
189a4e4127fSJung-uk Kim 			memcpy(p, regs, sizeof(regs));
190a4e4127fSJung-uk Kim 			p += sizeof(regs);
191a4e4127fSJung-uk Kim 		}
192a4e4127fSJung-uk Kim 		p = NULL;
193a4e4127fSJung-uk Kim 		for (i = 0; i < sizeof(brand) - 1; i++)
194a4e4127fSJung-uk Kim 			if (brand[i] == 'H' && brand[i + 1] == 'z')
195a4e4127fSJung-uk Kim 				p = brand + i;
196a4e4127fSJung-uk Kim 		if (p != NULL) {
197a4e4127fSJung-uk Kim 			p -= 5;
198a4e4127fSJung-uk Kim 			switch (p[4]) {
199a4e4127fSJung-uk Kim 			case 'M':
200a4e4127fSJung-uk Kim 				i = 1;
201a4e4127fSJung-uk Kim 				break;
202a4e4127fSJung-uk Kim 			case 'G':
203a4e4127fSJung-uk Kim 				i = 1000;
204a4e4127fSJung-uk Kim 				break;
205a4e4127fSJung-uk Kim 			case 'T':
206a4e4127fSJung-uk Kim 				i = 1000000;
207a4e4127fSJung-uk Kim 				break;
208a4e4127fSJung-uk Kim 			default:
209dd7d207dSJung-uk Kim 				return;
210a4e4127fSJung-uk Kim 			}
211a4e4127fSJung-uk Kim #define	C2D(c)	((c) - '0')
212a4e4127fSJung-uk Kim 			if (p[1] == '.') {
213a4e4127fSJung-uk Kim 				freq = C2D(p[0]) * 1000;
214a4e4127fSJung-uk Kim 				freq += C2D(p[2]) * 100;
215a4e4127fSJung-uk Kim 				freq += C2D(p[3]) * 10;
216a4e4127fSJung-uk Kim 				freq *= i * 1000;
217a4e4127fSJung-uk Kim 			} else {
218a4e4127fSJung-uk Kim 				freq = C2D(p[0]) * 1000;
219a4e4127fSJung-uk Kim 				freq += C2D(p[1]) * 100;
220a4e4127fSJung-uk Kim 				freq += C2D(p[2]) * 10;
221a4e4127fSJung-uk Kim 				freq += C2D(p[3]);
222a4e4127fSJung-uk Kim 				freq *= i * 1000000;
223a4e4127fSJung-uk Kim 			}
224a4e4127fSJung-uk Kim #undef C2D
225a4e4127fSJung-uk Kim 			tsc_freq = freq;
226a4e4127fSJung-uk Kim 		}
227a4e4127fSJung-uk Kim 	}
228a4e4127fSJung-uk Kim }
229dd7d207dSJung-uk Kim 
230a4e4127fSJung-uk Kim static void
231a4e4127fSJung-uk Kim probe_tsc_freq(void)
232a4e4127fSJung-uk Kim {
233bd8a359fSKonstantin Belousov 	uint64_t tmp_freq, tsc1, tsc2;
234bd8a359fSKonstantin Belousov 	int no_cpuid_override;
235dd7d207dSJung-uk Kim 
236bb044eafSConrad Meyer 	if (cpu_power_ecx & CPUID_PERF_STAT) {
2375da5812bSJung-uk Kim 		/*
238bb044eafSConrad Meyer 		 * XXX Some emulators expose host CPUID without actual support
239bb044eafSConrad Meyer 		 * for these MSRs.  We must test whether they really work.
2405da5812bSJung-uk Kim 		 */
2415da5812bSJung-uk Kim 		wrmsr(MSR_MPERF, 0);
2425da5812bSJung-uk Kim 		wrmsr(MSR_APERF, 0);
2435da5812bSJung-uk Kim 		DELAY(10);
2445da5812bSJung-uk Kim 		if (rdmsr(MSR_MPERF) > 0 && rdmsr(MSR_APERF) > 0)
2455da5812bSJung-uk Kim 			tsc_perf_stat = 1;
2465da5812bSJung-uk Kim 	}
2475da5812bSJung-uk Kim 
24801e1933dSJohn Baldwin 	if (vm_guest == VM_GUEST_VMWARE) {
24901e1933dSJohn Baldwin 		tsc_freq_vmware();
2505da5812bSJung-uk Kim 		return;
25101e1933dSJohn Baldwin 	}
2525da5812bSJung-uk Kim 
253dd7d207dSJung-uk Kim 	switch (cpu_vendor_id) {
254dd7d207dSJung-uk Kim 	case CPU_VENDOR_AMD:
2552ee49facSKonstantin Belousov 	case CPU_VENDOR_HYGON:
256a106a27cSJung-uk Kim 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
257a106a27cSJung-uk Kim 		    (vm_guest == VM_GUEST_NO &&
258a106a27cSJung-uk Kim 		    CPUID_TO_FAMILY(cpu_id) >= 0x10))
259dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
260814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
261814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
262814124c3SKonstantin Belousov 			    tsc_get_timecount_mfence;
263814124c3SKonstantin Belousov 		}
264dd7d207dSJung-uk Kim 		break;
265dd7d207dSJung-uk Kim 	case CPU_VENDOR_INTEL:
266a106a27cSJung-uk Kim 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
267a106a27cSJung-uk Kim 		    (vm_guest == VM_GUEST_NO &&
268a106a27cSJung-uk Kim 		    ((CPUID_TO_FAMILY(cpu_id) == 0x6 &&
269dd7d207dSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0xe) ||
270dd7d207dSJung-uk Kim 		    (CPUID_TO_FAMILY(cpu_id) == 0xf &&
271a106a27cSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0x3))))
272dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
273814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
274814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
275814124c3SKonstantin Belousov 			    tsc_get_timecount_lfence;
276814124c3SKonstantin Belousov 		}
277dd7d207dSJung-uk Kim 		break;
278dd7d207dSJung-uk Kim 	case CPU_VENDOR_CENTAUR:
279a106a27cSJung-uk Kim 		if (vm_guest == VM_GUEST_NO &&
280a106a27cSJung-uk Kim 		    CPUID_TO_FAMILY(cpu_id) == 0x6 &&
281dd7d207dSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0xf &&
282dd7d207dSJung-uk Kim 		    (rdmsr(0x1203) & 0x100000000ULL) == 0)
283dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
284814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
285814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
286814124c3SKonstantin Belousov 			    tsc_get_timecount_lfence;
287814124c3SKonstantin Belousov 		}
288dd7d207dSJung-uk Kim 		break;
289dd7d207dSJung-uk Kim 	}
290dd7d207dSJung-uk Kim 
291a4e4127fSJung-uk Kim 	if (tsc_skip_calibration) {
292bd8a359fSKonstantin Belousov 		if (tsc_freq_cpuid(&tmp_freq))
293bd8a359fSKonstantin Belousov 			tsc_freq = tmp_freq;
294506a906cSKonstantin Belousov 		else if (cpu_vendor_id == CPU_VENDOR_INTEL)
295a4e4127fSJung-uk Kim 			tsc_freq_intel();
296ab23c278SKonstantin Belousov 		if (tsc_freq == 0)
297ab23c278SKonstantin Belousov 			tsc_disabled = 1;
298506a906cSKonstantin Belousov 	} else {
299a4e4127fSJung-uk Kim 		if (bootverbose)
300a4e4127fSJung-uk Kim 			printf("Calibrating TSC clock ... ");
301a4e4127fSJung-uk Kim 		tsc1 = rdtsc();
302a4e4127fSJung-uk Kim 		DELAY(1000000);
303a4e4127fSJung-uk Kim 		tsc2 = rdtsc();
304a4e4127fSJung-uk Kim 		tsc_freq = tsc2 - tsc1;
305bd8a359fSKonstantin Belousov 
306bd8a359fSKonstantin Belousov 		/*
307bd8a359fSKonstantin Belousov 		 * If the difference between calibrated frequency and
308bd8a359fSKonstantin Belousov 		 * the frequency reported by CPUID 0x15/0x16 leafs
309bd8a359fSKonstantin Belousov 		 * differ significantly, this probably means that
310bd8a359fSKonstantin Belousov 		 * calibration is bogus.  It happens on machines
311ab23c278SKonstantin Belousov 		 * without 8254 timer.  The BIOS rarely properly
312ab23c278SKonstantin Belousov 		 * reports it in FADT boot flags, so just compare the
313ab23c278SKonstantin Belousov 		 * frequencies directly.
314bd8a359fSKonstantin Belousov 		 */
315bd8a359fSKonstantin Belousov 		if (tsc_freq_cpuid(&tmp_freq) && qabs(tsc_freq - tmp_freq) >
316bd8a359fSKonstantin Belousov 		    uqmin(tsc_freq, tmp_freq)) {
317bd8a359fSKonstantin Belousov 			no_cpuid_override = 0;
318bd8a359fSKonstantin Belousov 			TUNABLE_INT_FETCH("machdep.disable_tsc_cpuid_override",
319bd8a359fSKonstantin Belousov 			    &no_cpuid_override);
320bd8a359fSKonstantin Belousov 			if (!no_cpuid_override) {
321bd8a359fSKonstantin Belousov 				if (bootverbose) {
322bd8a359fSKonstantin Belousov 					printf(
323bd8a359fSKonstantin Belousov 	"TSC clock: calibration freq %ju Hz, CPUID freq %ju Hz%s\n",
324bd8a359fSKonstantin Belousov 					    (uintmax_t)tsc_freq,
325bd8a359fSKonstantin Belousov 					    (uintmax_t)tmp_freq,
326bd8a359fSKonstantin Belousov 					    no_cpuid_override ? "" :
327bd8a359fSKonstantin Belousov 					    ", doing CPUID override");
328bd8a359fSKonstantin Belousov 				}
329bd8a359fSKonstantin Belousov 				tsc_freq = tmp_freq;
330bd8a359fSKonstantin Belousov 			}
331bd8a359fSKonstantin Belousov 		}
332506a906cSKonstantin Belousov 	}
333a4e4127fSJung-uk Kim 	if (bootverbose)
334a4e4127fSJung-uk Kim 		printf("TSC clock: %ju Hz\n", (intmax_t)tsc_freq);
335a4e4127fSJung-uk Kim }
336a4e4127fSJung-uk Kim 
337a4e4127fSJung-uk Kim void
338a4e4127fSJung-uk Kim init_TSC(void)
339a4e4127fSJung-uk Kim {
340a4e4127fSJung-uk Kim 
341a4e4127fSJung-uk Kim 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
342a4e4127fSJung-uk Kim 		return;
343a4e4127fSJung-uk Kim 
344fe760cfaSJohn Baldwin #ifdef __i386__
345fe760cfaSJohn Baldwin 	/* The TSC is known to be broken on certain CPUs. */
346fe760cfaSJohn Baldwin 	switch (cpu_vendor_id) {
347fe760cfaSJohn Baldwin 	case CPU_VENDOR_AMD:
348fe760cfaSJohn Baldwin 		switch (cpu_id & 0xFF0) {
349fe760cfaSJohn Baldwin 		case 0x500:
350fe760cfaSJohn Baldwin 			/* K5 Model 0 */
351fe760cfaSJohn Baldwin 			return;
352fe760cfaSJohn Baldwin 		}
353fe760cfaSJohn Baldwin 		break;
354fe760cfaSJohn Baldwin 	case CPU_VENDOR_CENTAUR:
355fe760cfaSJohn Baldwin 		switch (cpu_id & 0xff0) {
356fe760cfaSJohn Baldwin 		case 0x540:
357fe760cfaSJohn Baldwin 			/*
358fe760cfaSJohn Baldwin 			 * http://www.centtech.com/c6_data_sheet.pdf
359fe760cfaSJohn Baldwin 			 *
360fe760cfaSJohn Baldwin 			 * I-12 RDTSC may return incoherent values in EDX:EAX
361fe760cfaSJohn Baldwin 			 * I-13 RDTSC hangs when certain event counters are used
362fe760cfaSJohn Baldwin 			 */
363fe760cfaSJohn Baldwin 			return;
364fe760cfaSJohn Baldwin 		}
365fe760cfaSJohn Baldwin 		break;
366fe760cfaSJohn Baldwin 	case CPU_VENDOR_NSC:
367fe760cfaSJohn Baldwin 		switch (cpu_id & 0xff0) {
368fe760cfaSJohn Baldwin 		case 0x540:
369fe760cfaSJohn Baldwin 			if ((cpu_id & CPUID_STEPPING) == 0)
370fe760cfaSJohn Baldwin 				return;
371fe760cfaSJohn Baldwin 			break;
372fe760cfaSJohn Baldwin 		}
373fe760cfaSJohn Baldwin 		break;
374fe760cfaSJohn Baldwin 	}
375fe760cfaSJohn Baldwin #endif
376fe760cfaSJohn Baldwin 
377a4e4127fSJung-uk Kim 	probe_tsc_freq();
378a4e4127fSJung-uk Kim 
379dd7d207dSJung-uk Kim 	/*
380dd7d207dSJung-uk Kim 	 * Inform CPU accounting about our boot-time clock rate.  This will
381dd7d207dSJung-uk Kim 	 * be updated if someone loads a cpufreq driver after boot that
382dd7d207dSJung-uk Kim 	 * discovers a new max frequency.
383dd7d207dSJung-uk Kim 	 */
384a4e4127fSJung-uk Kim 	if (tsc_freq != 0)
3855ac44f72SJung-uk Kim 		set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
386dd7d207dSJung-uk Kim 
387dd7d207dSJung-uk Kim 	if (tsc_is_invariant)
388dd7d207dSJung-uk Kim 		return;
389dd7d207dSJung-uk Kim 
390dd7d207dSJung-uk Kim 	/* Register to find out about changes in CPU frequency. */
391dd7d207dSJung-uk Kim 	tsc_pre_tag = EVENTHANDLER_REGISTER(cpufreq_pre_change,
392dd7d207dSJung-uk Kim 	    tsc_freq_changing, NULL, EVENTHANDLER_PRI_FIRST);
393dd7d207dSJung-uk Kim 	tsc_post_tag = EVENTHANDLER_REGISTER(cpufreq_post_change,
394dd7d207dSJung-uk Kim 	    tsc_freq_changed, NULL, EVENTHANDLER_PRI_FIRST);
395dd7d207dSJung-uk Kim 	tsc_levels_tag = EVENTHANDLER_REGISTER(cpufreq_levels_changed,
396dd7d207dSJung-uk Kim 	    tsc_levels_changed, NULL, EVENTHANDLER_PRI_ANY);
397dd7d207dSJung-uk Kim }
398dd7d207dSJung-uk Kim 
39965e7d70bSJung-uk Kim #ifdef SMP
40065e7d70bSJung-uk Kim 
401814124c3SKonstantin Belousov /*
402814124c3SKonstantin Belousov  * RDTSC is not a serializing instruction, and does not drain
403814124c3SKonstantin Belousov  * instruction stream, so we need to drain the stream before executing
404814124c3SKonstantin Belousov  * it.  It could be fixed by use of RDTSCP, except the instruction is
405814124c3SKonstantin Belousov  * not available everywhere.
406814124c3SKonstantin Belousov  *
407814124c3SKonstantin Belousov  * Use CPUID for draining in the boot-time SMP constistency test.  The
408814124c3SKonstantin Belousov  * timecounters use MFENCE for AMD CPUs, and LFENCE for others (Intel
409814124c3SKonstantin Belousov  * and VIA) when SSE2 is present, and nothing on older machines which
410814124c3SKonstantin Belousov  * also do not issue RDTSC prematurely.  There, testing for SSE2 and
411e1a18e46SKonstantin Belousov  * vendor is too cumbersome, and we learn about TSC presence from CPUID.
412814124c3SKonstantin Belousov  *
413814124c3SKonstantin Belousov  * Do not use do_cpuid(), since we do not need CPUID results, which
414814124c3SKonstantin Belousov  * have to be written into memory with do_cpuid().
415814124c3SKonstantin Belousov  */
41665e7d70bSJung-uk Kim #define	TSC_READ(x)							\
41765e7d70bSJung-uk Kim static void								\
41865e7d70bSJung-uk Kim tsc_read_##x(void *arg)							\
41965e7d70bSJung-uk Kim {									\
4207bfcb3bbSJim Harris 	uint64_t *tsc = arg;						\
42165e7d70bSJung-uk Kim 	u_int cpu = PCPU_GET(cpuid);					\
42265e7d70bSJung-uk Kim 									\
423814124c3SKonstantin Belousov 	__asm __volatile("cpuid" : : : "eax", "ebx", "ecx", "edx");	\
4247bfcb3bbSJim Harris 	tsc[cpu * 3 + x] = rdtsc();					\
42565e7d70bSJung-uk Kim }
42665e7d70bSJung-uk Kim TSC_READ(0)
42765e7d70bSJung-uk Kim TSC_READ(1)
42865e7d70bSJung-uk Kim TSC_READ(2)
42965e7d70bSJung-uk Kim #undef TSC_READ
43065e7d70bSJung-uk Kim 
43165e7d70bSJung-uk Kim #define	N	1000
43265e7d70bSJung-uk Kim 
43365e7d70bSJung-uk Kim static void
43465e7d70bSJung-uk Kim comp_smp_tsc(void *arg)
43565e7d70bSJung-uk Kim {
4367bfcb3bbSJim Harris 	uint64_t *tsc;
4377bfcb3bbSJim Harris 	int64_t d1, d2;
43865e7d70bSJung-uk Kim 	u_int cpu = PCPU_GET(cpuid);
43965e7d70bSJung-uk Kim 	u_int i, j, size;
44065e7d70bSJung-uk Kim 
44165e7d70bSJung-uk Kim 	size = (mp_maxid + 1) * 3;
44265e7d70bSJung-uk Kim 	for (i = 0, tsc = arg; i < N; i++, tsc += size)
44365e7d70bSJung-uk Kim 		CPU_FOREACH(j) {
44465e7d70bSJung-uk Kim 			if (j == cpu)
44565e7d70bSJung-uk Kim 				continue;
44665e7d70bSJung-uk Kim 			d1 = tsc[cpu * 3 + 1] - tsc[j * 3];
44765e7d70bSJung-uk Kim 			d2 = tsc[cpu * 3 + 2] - tsc[j * 3 + 1];
44865e7d70bSJung-uk Kim 			if (d1 <= 0 || d2 <= 0) {
44965e7d70bSJung-uk Kim 				smp_tsc = 0;
45065e7d70bSJung-uk Kim 				return;
45165e7d70bSJung-uk Kim 			}
45265e7d70bSJung-uk Kim 		}
45365e7d70bSJung-uk Kim }
45465e7d70bSJung-uk Kim 
455b2c63698SAlexander Motin static void
456b2c63698SAlexander Motin adj_smp_tsc(void *arg)
457b2c63698SAlexander Motin {
458b2c63698SAlexander Motin 	uint64_t *tsc;
459b2c63698SAlexander Motin 	int64_t d, min, max;
460b2c63698SAlexander Motin 	u_int cpu = PCPU_GET(cpuid);
461b2c63698SAlexander Motin 	u_int first, i, size;
462b2c63698SAlexander Motin 
463b2c63698SAlexander Motin 	first = CPU_FIRST();
464b2c63698SAlexander Motin 	if (cpu == first)
465b2c63698SAlexander Motin 		return;
466b2c63698SAlexander Motin 	min = INT64_MIN;
467b2c63698SAlexander Motin 	max = INT64_MAX;
468b2c63698SAlexander Motin 	size = (mp_maxid + 1) * 3;
469b2c63698SAlexander Motin 	for (i = 0, tsc = arg; i < N; i++, tsc += size) {
470b2c63698SAlexander Motin 		d = tsc[first * 3] - tsc[cpu * 3 + 1];
471b2c63698SAlexander Motin 		if (d > min)
472b2c63698SAlexander Motin 			min = d;
473b2c63698SAlexander Motin 		d = tsc[first * 3 + 1] - tsc[cpu * 3 + 2];
474b2c63698SAlexander Motin 		if (d > min)
475b2c63698SAlexander Motin 			min = d;
476b2c63698SAlexander Motin 		d = tsc[first * 3 + 1] - tsc[cpu * 3];
477b2c63698SAlexander Motin 		if (d < max)
478b2c63698SAlexander Motin 			max = d;
479b2c63698SAlexander Motin 		d = tsc[first * 3 + 2] - tsc[cpu * 3 + 1];
480b2c63698SAlexander Motin 		if (d < max)
481b2c63698SAlexander Motin 			max = d;
482b2c63698SAlexander Motin 	}
483b2c63698SAlexander Motin 	if (min > max)
484b2c63698SAlexander Motin 		return;
485b2c63698SAlexander Motin 	d = min / 2 + max / 2;
486b2c63698SAlexander Motin 	__asm __volatile (
487b2c63698SAlexander Motin 		"movl $0x10, %%ecx\n\t"
488b2c63698SAlexander Motin 		"rdmsr\n\t"
489b2c63698SAlexander Motin 		"addl %%edi, %%eax\n\t"
490b2c63698SAlexander Motin 		"adcl %%esi, %%edx\n\t"
491b2c63698SAlexander Motin 		"wrmsr\n"
492b2c63698SAlexander Motin 		: /* No output */
493b2c63698SAlexander Motin 		: "D" ((uint32_t)d), "S" ((uint32_t)(d >> 32))
494b2c63698SAlexander Motin 		: "ax", "cx", "dx", "cc"
495b2c63698SAlexander Motin 	);
496b2c63698SAlexander Motin }
497b2c63698SAlexander Motin 
49865e7d70bSJung-uk Kim static int
499279be68bSAndriy Gapon test_tsc(int adj_max_count)
50065e7d70bSJung-uk Kim {
5017bfcb3bbSJim Harris 	uint64_t *data, *tsc;
502b2c63698SAlexander Motin 	u_int i, size, adj;
50365e7d70bSJung-uk Kim 
50484eaf2ccSKonstantin Belousov 	if ((!smp_tsc && !tsc_is_invariant))
50565e7d70bSJung-uk Kim 		return (-100);
50665e7d70bSJung-uk Kim 	size = (mp_maxid + 1) * 3;
50765e7d70bSJung-uk Kim 	data = malloc(sizeof(*data) * size * N, M_TEMP, M_WAITOK);
508b2c63698SAlexander Motin 	adj = 0;
509b2c63698SAlexander Motin retry:
51065e7d70bSJung-uk Kim 	for (i = 0, tsc = data; i < N; i++, tsc += size)
51165e7d70bSJung-uk Kim 		smp_rendezvous(tsc_read_0, tsc_read_1, tsc_read_2, tsc);
51265e7d70bSJung-uk Kim 	smp_tsc = 1;	/* XXX */
51367d955aaSPatrick Kelsey 	smp_rendezvous(smp_no_rendezvous_barrier, comp_smp_tsc,
51467d955aaSPatrick Kelsey 	    smp_no_rendezvous_barrier, data);
515279be68bSAndriy Gapon 	if (!smp_tsc && adj < adj_max_count) {
516b2c63698SAlexander Motin 		adj++;
51767d955aaSPatrick Kelsey 		smp_rendezvous(smp_no_rendezvous_barrier, adj_smp_tsc,
51867d955aaSPatrick Kelsey 		    smp_no_rendezvous_barrier, data);
519b2c63698SAlexander Motin 		goto retry;
520b2c63698SAlexander Motin 	}
52165e7d70bSJung-uk Kim 	free(data, M_TEMP);
52265e7d70bSJung-uk Kim 	if (bootverbose)
523b2c63698SAlexander Motin 		printf("SMP: %sed TSC synchronization test%s\n",
524b2c63698SAlexander Motin 		    smp_tsc ? "pass" : "fail",
525b2c63698SAlexander Motin 		    adj > 0 ? " after adjustment" : "");
52626e6537aSJung-uk Kim 	if (smp_tsc && tsc_is_invariant) {
52726e6537aSJung-uk Kim 		switch (cpu_vendor_id) {
52826e6537aSJung-uk Kim 		case CPU_VENDOR_AMD:
5292ee49facSKonstantin Belousov 		case CPU_VENDOR_HYGON:
53026e6537aSJung-uk Kim 			/*
531450d86fcSJung-uk Kim 			 * Processor Programming Reference (PPR) for AMD
532450d86fcSJung-uk Kim 			 * Family 17h states that the TSC uses a common
533450d86fcSJung-uk Kim 			 * reference for all sockets, cores and threads.
534450d86fcSJung-uk Kim 			 */
535450d86fcSJung-uk Kim 			if (CPUID_TO_FAMILY(cpu_id) >= 0x17)
536450d86fcSJung-uk Kim 				return (1000);
537450d86fcSJung-uk Kim 			/*
53826e6537aSJung-uk Kim 			 * Starting with Family 15h processors, TSC clock
53926e6537aSJung-uk Kim 			 * source is in the north bridge.  Check whether
54026e6537aSJung-uk Kim 			 * we have a single-socket/multi-core platform.
54126e6537aSJung-uk Kim 			 * XXX Need more work for complex cases.
54226e6537aSJung-uk Kim 			 */
54326e6537aSJung-uk Kim 			if (CPUID_TO_FAMILY(cpu_id) < 0x15 ||
54426e6537aSJung-uk Kim 			    (amd_feature2 & AMDID2_CMP) == 0 ||
54526e6537aSJung-uk Kim 			    smp_cpus > (cpu_procinfo2 & AMDID_CMP_CORES) + 1)
54626e6537aSJung-uk Kim 				break;
54726e6537aSJung-uk Kim 			return (1000);
54826e6537aSJung-uk Kim 		case CPU_VENDOR_INTEL:
54926e6537aSJung-uk Kim 			/*
55026e6537aSJung-uk Kim 			 * XXX Assume Intel platforms have synchronized TSCs.
55126e6537aSJung-uk Kim 			 */
55226e6537aSJung-uk Kim 			return (1000);
55326e6537aSJung-uk Kim 		}
55426e6537aSJung-uk Kim 		return (800);
55526e6537aSJung-uk Kim 	}
55626e6537aSJung-uk Kim 	return (-100);
55765e7d70bSJung-uk Kim }
55865e7d70bSJung-uk Kim 
55965e7d70bSJung-uk Kim #undef N
56065e7d70bSJung-uk Kim 
56165e7d70bSJung-uk Kim #endif /* SMP */
56265e7d70bSJung-uk Kim 
56365e7d70bSJung-uk Kim static void
564dd7d207dSJung-uk Kim init_TSC_tc(void)
565dd7d207dSJung-uk Kim {
56695f2f098SJung-uk Kim 	uint64_t max_freq;
56795f2f098SJung-uk Kim 	int shift;
568dd7d207dSJung-uk Kim 
56938b8542cSJung-uk Kim 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
570dd7d207dSJung-uk Kim 		return;
571dd7d207dSJung-uk Kim 
572dd7d207dSJung-uk Kim 	/*
57395f2f098SJung-uk Kim 	 * Limit timecounter frequency to fit in an int and prevent it from
57495f2f098SJung-uk Kim 	 * overflowing too fast.
57595f2f098SJung-uk Kim 	 */
57695f2f098SJung-uk Kim 	max_freq = UINT_MAX;
57795f2f098SJung-uk Kim 
57895f2f098SJung-uk Kim 	/*
579dd7d207dSJung-uk Kim 	 * We can not use the TSC if we support APM.  Precise timekeeping
580dd7d207dSJung-uk Kim 	 * on an APM'ed machine is at best a fools pursuit, since
581dd7d207dSJung-uk Kim 	 * any and all of the time spent in various SMM code can't
582dd7d207dSJung-uk Kim 	 * be reliably accounted for.  Reading the RTC is your only
583dd7d207dSJung-uk Kim 	 * source of reliable time info.  The i8254 loses too, of course,
584dd7d207dSJung-uk Kim 	 * but we need to have some kind of time...
585dd7d207dSJung-uk Kim 	 * We don't know at this point whether APM is going to be used
586dd7d207dSJung-uk Kim 	 * or not, nor when it might be activated.  Play it safe.
587dd7d207dSJung-uk Kim 	 */
588dd7d207dSJung-uk Kim 	if (power_pm_get_type() == POWER_PM_TYPE_APM) {
589dd7d207dSJung-uk Kim 		tsc_timecounter.tc_quality = -1000;
590dd7d207dSJung-uk Kim 		if (bootverbose)
591dd7d207dSJung-uk Kim 			printf("TSC timecounter disabled: APM enabled.\n");
59265e7d70bSJung-uk Kim 		goto init;
593dd7d207dSJung-uk Kim 	}
594dd7d207dSJung-uk Kim 
595a49399a9SJung-uk Kim 	/*
59692597e06SJohn Baldwin 	 * Intel CPUs without a C-state invariant TSC can stop the TSC
597d1411416SJohn Baldwin 	 * in either C2 or C3.  Disable use of C2 and C3 while using
598d1411416SJohn Baldwin 	 * the TSC as the timecounter.  The timecounter can be changed
599d1411416SJohn Baldwin 	 * to enable C2 and C3.
600d1411416SJohn Baldwin 	 *
601d1411416SJohn Baldwin 	 * Note that the TSC is used as the cputicker for computing
602d1411416SJohn Baldwin 	 * thread runtime regardless of the timecounter setting, so
603d1411416SJohn Baldwin 	 * using an alternate timecounter and enabling C2 or C3 can
604d1411416SJohn Baldwin 	 * result incorrect runtimes for kernel idle threads (but not
605d1411416SJohn Baldwin 	 * for any non-idle threads).
606a49399a9SJung-uk Kim 	 */
6078cd59625SKonstantin Belousov 	if (cpu_vendor_id == CPU_VENDOR_INTEL &&
608a49399a9SJung-uk Kim 	    (amd_pminfo & AMDPM_TSC_INVARIANT) == 0) {
60992597e06SJohn Baldwin 		tsc_timecounter.tc_flags |= TC_FLAGS_C2STOP;
610a49399a9SJung-uk Kim 		if (bootverbose)
611d1411416SJohn Baldwin 			printf("TSC timecounter disables C2 and C3.\n");
612a49399a9SJung-uk Kim 	}
613a49399a9SJung-uk Kim 
614dd7d207dSJung-uk Kim 	/*
615e7f1427dSKonstantin Belousov 	 * We can not use the TSC in SMP mode unless the TSCs on all CPUs
616e7f1427dSKonstantin Belousov 	 * are synchronized.  If the user is sure that the system has
617e7f1427dSKonstantin Belousov 	 * synchronized TSCs, set kern.timecounter.smp_tsc tunable to a
618e7f1427dSKonstantin Belousov 	 * non-zero value.  The TSC seems unreliable in virtualized SMP
6195cf8ac1bSMike Silbersack 	 * environments, so it is set to a negative quality in those cases.
620dd7d207dSJung-uk Kim 	 */
621ba79ab82SAndriy Gapon #ifdef SMP
622e7f1427dSKonstantin Belousov 	if (mp_ncpus > 1)
623279be68bSAndriy Gapon 		tsc_timecounter.tc_quality = test_tsc(smp_tsc_adjust);
624ba79ab82SAndriy Gapon 	else
625ba79ab82SAndriy Gapon #endif /* SMP */
626ba79ab82SAndriy Gapon 	if (tsc_is_invariant)
62726e6537aSJung-uk Kim 		tsc_timecounter.tc_quality = 1000;
628e7f1427dSKonstantin Belousov 	max_freq >>= tsc_shift;
62926e6537aSJung-uk Kim 
63065e7d70bSJung-uk Kim init:
631e7f1427dSKonstantin Belousov 	for (shift = 0; shift <= 31 && (tsc_freq >> shift) > max_freq; shift++)
63295f2f098SJung-uk Kim 		;
6339e680e40SKonstantin Belousov 
6349e680e40SKonstantin Belousov 	/*
6359e680e40SKonstantin Belousov 	 * Timecounter implementation selection, top to bottom:
6369e680e40SKonstantin Belousov 	 * - If RDTSCP is available, use RDTSCP.
6379e680e40SKonstantin Belousov 	 * - If fence instructions are provided (SSE2), use LFENCE;RDTSC
6389e680e40SKonstantin Belousov 	 *   on Intel, and MFENCE;RDTSC on AMD.
6399e680e40SKonstantin Belousov 	 * - For really old CPUs, just use RDTSC.
6409e680e40SKonstantin Belousov 	 */
6419f47eeffSKonstantin Belousov 	if ((amd_feature & AMDID_RDTSCP) != 0) {
6429e680e40SKonstantin Belousov 		tsc_timecounter.tc_get_timecount = shift > 0 ?
6439e680e40SKonstantin Belousov 		    tscp_get_timecount_low : tscp_get_timecount;
6449e680e40SKonstantin Belousov 	} else if ((cpu_feature & CPUID_SSE2) != 0 && mp_ncpus > 1) {
6452ee49facSKonstantin Belousov 		if (cpu_vendor_id == CPU_VENDOR_AMD ||
6462ee49facSKonstantin Belousov 		    cpu_vendor_id == CPU_VENDOR_HYGON) {
647e7f1427dSKonstantin Belousov 			tsc_timecounter.tc_get_timecount = shift > 0 ?
648e7f1427dSKonstantin Belousov 			    tsc_get_timecount_low_mfence :
649e7f1427dSKonstantin Belousov 			    tsc_get_timecount_mfence;
650814124c3SKonstantin Belousov 		} else {
651e7f1427dSKonstantin Belousov 			tsc_timecounter.tc_get_timecount = shift > 0 ?
652e7f1427dSKonstantin Belousov 			    tsc_get_timecount_low_lfence :
653e7f1427dSKonstantin Belousov 			    tsc_get_timecount_lfence;
654814124c3SKonstantin Belousov 		}
655e7f1427dSKonstantin Belousov 	} else {
656e7f1427dSKonstantin Belousov 		tsc_timecounter.tc_get_timecount = shift > 0 ?
657e7f1427dSKonstantin Belousov 		    tsc_get_timecount_low : tsc_get_timecount;
658e7f1427dSKonstantin Belousov 	}
659e7f1427dSKonstantin Belousov 	if (shift > 0) {
66095f2f098SJung-uk Kim 		tsc_timecounter.tc_name = "TSC-low";
66195f2f098SJung-uk Kim 		if (bootverbose)
662bc8e4ad2SJung-uk Kim 			printf("TSC timecounter discards lower %d bit(s)\n",
66395f2f098SJung-uk Kim 			    shift);
66495f2f098SJung-uk Kim 	}
665bc34c87eSJung-uk Kim 	if (tsc_freq != 0) {
66695f2f098SJung-uk Kim 		tsc_timecounter.tc_frequency = tsc_freq >> shift;
66795f2f098SJung-uk Kim 		tsc_timecounter.tc_priv = (void *)(intptr_t)shift;
668dd7d207dSJung-uk Kim 		tc_init(&tsc_timecounter);
669dd7d207dSJung-uk Kim 	}
670dd7d207dSJung-uk Kim }
67165e7d70bSJung-uk Kim SYSINIT(tsc_tc, SI_SUB_SMP, SI_ORDER_ANY, init_TSC_tc, NULL);
672dd7d207dSJung-uk Kim 
673279be68bSAndriy Gapon void
674279be68bSAndriy Gapon resume_TSC(void)
675279be68bSAndriy Gapon {
676ba79ab82SAndriy Gapon #ifdef SMP
677279be68bSAndriy Gapon 	int quality;
678279be68bSAndriy Gapon 
679279be68bSAndriy Gapon 	/* If TSC was not good on boot, it is unlikely to become good now. */
680279be68bSAndriy Gapon 	if (tsc_timecounter.tc_quality < 0)
681279be68bSAndriy Gapon 		return;
682279be68bSAndriy Gapon 	/* Nothing to do with UP. */
683279be68bSAndriy Gapon 	if (mp_ncpus < 2)
684279be68bSAndriy Gapon 		return;
685279be68bSAndriy Gapon 
686279be68bSAndriy Gapon 	/*
687279be68bSAndriy Gapon 	 * If TSC was good, a single synchronization should be enough,
688279be68bSAndriy Gapon 	 * but honour smp_tsc_adjust if it's set.
689279be68bSAndriy Gapon 	 */
690279be68bSAndriy Gapon 	quality = test_tsc(MAX(smp_tsc_adjust, 1));
691279be68bSAndriy Gapon 	if (quality != tsc_timecounter.tc_quality) {
692279be68bSAndriy Gapon 		printf("TSC timecounter quality changed: %d -> %d\n",
693279be68bSAndriy Gapon 		    tsc_timecounter.tc_quality, quality);
694279be68bSAndriy Gapon 		tsc_timecounter.tc_quality = quality;
695279be68bSAndriy Gapon 	}
696ba79ab82SAndriy Gapon #endif /* SMP */
697279be68bSAndriy Gapon }
698279be68bSAndriy Gapon 
699dd7d207dSJung-uk Kim /*
700dd7d207dSJung-uk Kim  * When cpufreq levels change, find out about the (new) max frequency.  We
701dd7d207dSJung-uk Kim  * use this to update CPU accounting in case it got a lower estimate at boot.
702dd7d207dSJung-uk Kim  */
703dd7d207dSJung-uk Kim static void
704dd7d207dSJung-uk Kim tsc_levels_changed(void *arg, int unit)
705dd7d207dSJung-uk Kim {
706dd7d207dSJung-uk Kim 	device_t cf_dev;
707dd7d207dSJung-uk Kim 	struct cf_level *levels;
708dd7d207dSJung-uk Kim 	int count, error;
709dd7d207dSJung-uk Kim 	uint64_t max_freq;
710dd7d207dSJung-uk Kim 
711dd7d207dSJung-uk Kim 	/* Only use values from the first CPU, assuming all are equal. */
712dd7d207dSJung-uk Kim 	if (unit != 0)
713dd7d207dSJung-uk Kim 		return;
714dd7d207dSJung-uk Kim 
715dd7d207dSJung-uk Kim 	/* Find the appropriate cpufreq device instance. */
716dd7d207dSJung-uk Kim 	cf_dev = devclass_get_device(devclass_find("cpufreq"), unit);
717dd7d207dSJung-uk Kim 	if (cf_dev == NULL) {
718dd7d207dSJung-uk Kim 		printf("tsc_levels_changed() called but no cpufreq device?\n");
719dd7d207dSJung-uk Kim 		return;
720dd7d207dSJung-uk Kim 	}
721dd7d207dSJung-uk Kim 
722dd7d207dSJung-uk Kim 	/* Get settings from the device and find the max frequency. */
723dd7d207dSJung-uk Kim 	count = 64;
724dd7d207dSJung-uk Kim 	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
725dd7d207dSJung-uk Kim 	if (levels == NULL)
726dd7d207dSJung-uk Kim 		return;
727dd7d207dSJung-uk Kim 	error = CPUFREQ_LEVELS(cf_dev, levels, &count);
728dd7d207dSJung-uk Kim 	if (error == 0 && count != 0) {
729dd7d207dSJung-uk Kim 		max_freq = (uint64_t)levels[0].total_set.freq * 1000000;
730dd7d207dSJung-uk Kim 		set_cputicker(rdtsc, max_freq, 1);
731dd7d207dSJung-uk Kim 	} else
732dd7d207dSJung-uk Kim 		printf("tsc_levels_changed: no max freq found\n");
733dd7d207dSJung-uk Kim 	free(levels, M_TEMP);
734dd7d207dSJung-uk Kim }
735dd7d207dSJung-uk Kim 
736dd7d207dSJung-uk Kim /*
737dd7d207dSJung-uk Kim  * If the TSC timecounter is in use, veto the pending change.  It may be
738dd7d207dSJung-uk Kim  * possible in the future to handle a dynamically-changing timecounter rate.
739dd7d207dSJung-uk Kim  */
740dd7d207dSJung-uk Kim static void
741dd7d207dSJung-uk Kim tsc_freq_changing(void *arg, const struct cf_level *level, int *status)
742dd7d207dSJung-uk Kim {
743dd7d207dSJung-uk Kim 
744dd7d207dSJung-uk Kim 	if (*status != 0 || timecounter != &tsc_timecounter)
745dd7d207dSJung-uk Kim 		return;
746dd7d207dSJung-uk Kim 
747dd7d207dSJung-uk Kim 	printf("timecounter TSC must not be in use when "
748dd7d207dSJung-uk Kim 	    "changing frequencies; change denied\n");
749dd7d207dSJung-uk Kim 	*status = EBUSY;
750dd7d207dSJung-uk Kim }
751dd7d207dSJung-uk Kim 
752dd7d207dSJung-uk Kim /* Update TSC freq with the value indicated by the caller. */
753dd7d207dSJung-uk Kim static void
754dd7d207dSJung-uk Kim tsc_freq_changed(void *arg, const struct cf_level *level, int status)
755dd7d207dSJung-uk Kim {
7563453537fSJung-uk Kim 	uint64_t freq;
757dd7d207dSJung-uk Kim 
758dd7d207dSJung-uk Kim 	/* If there was an error during the transition, don't do anything. */
75979422085SJung-uk Kim 	if (tsc_disabled || status != 0)
760dd7d207dSJung-uk Kim 		return;
761dd7d207dSJung-uk Kim 
762dd7d207dSJung-uk Kim 	/* Total setting for this level gives the new frequency in MHz. */
7633453537fSJung-uk Kim 	freq = (uint64_t)level->total_set.freq * 1000000;
7643453537fSJung-uk Kim 	atomic_store_rel_64(&tsc_freq, freq);
76595f2f098SJung-uk Kim 	tsc_timecounter.tc_frequency =
76695f2f098SJung-uk Kim 	    freq >> (int)(intptr_t)tsc_timecounter.tc_priv;
767dd7d207dSJung-uk Kim }
768dd7d207dSJung-uk Kim 
769dd7d207dSJung-uk Kim static int
770dd7d207dSJung-uk Kim sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
771dd7d207dSJung-uk Kim {
772dd7d207dSJung-uk Kim 	int error;
773dd7d207dSJung-uk Kim 	uint64_t freq;
774dd7d207dSJung-uk Kim 
7753453537fSJung-uk Kim 	freq = atomic_load_acq_64(&tsc_freq);
7763453537fSJung-uk Kim 	if (freq == 0)
777dd7d207dSJung-uk Kim 		return (EOPNOTSUPP);
778cbc134adSMatthew D Fleming 	error = sysctl_handle_64(oidp, &freq, 0, req);
7797ebbcb21SJung-uk Kim 	if (error == 0 && req->newptr != NULL) {
7803453537fSJung-uk Kim 		atomic_store_rel_64(&tsc_freq, freq);
781bc8e4ad2SJung-uk Kim 		atomic_store_rel_64(&tsc_timecounter.tc_frequency,
782bc8e4ad2SJung-uk Kim 		    freq >> (int)(intptr_t)tsc_timecounter.tc_priv);
7837ebbcb21SJung-uk Kim 	}
784dd7d207dSJung-uk Kim 	return (error);
785dd7d207dSJung-uk Kim }
786dd7d207dSJung-uk Kim 
7877029da5cSPawel Biernacki SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq,
7887029da5cSPawel Biernacki     CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
7897029da5cSPawel Biernacki     0, 0, sysctl_machdep_tsc_freq, "QU",
7907029da5cSPawel Biernacki     "Time Stamp Counter frequency");
791dd7d207dSJung-uk Kim 
792727c7b2dSJung-uk Kim static u_int
79395f2f098SJung-uk Kim tsc_get_timecount(struct timecounter *tc __unused)
794dd7d207dSJung-uk Kim {
795727c7b2dSJung-uk Kim 
796727c7b2dSJung-uk Kim 	return (rdtsc32());
797dd7d207dSJung-uk Kim }
79895f2f098SJung-uk Kim 
7999e680e40SKonstantin Belousov static u_int
8009e680e40SKonstantin Belousov tscp_get_timecount(struct timecounter *tc __unused)
8019e680e40SKonstantin Belousov {
8029e680e40SKonstantin Belousov 
8039e680e40SKonstantin Belousov 	return (rdtscp32());
8049e680e40SKonstantin Belousov }
8059e680e40SKonstantin Belousov 
806814124c3SKonstantin Belousov static inline u_int
807bc8e4ad2SJung-uk Kim tsc_get_timecount_low(struct timecounter *tc)
80895f2f098SJung-uk Kim {
8095df88f46SJung-uk Kim 	uint32_t rv;
81095f2f098SJung-uk Kim 
8115df88f46SJung-uk Kim 	__asm __volatile("rdtsc; shrd %%cl, %%edx, %0"
8125df88f46SJung-uk Kim 	    : "=a" (rv) : "c" ((int)(intptr_t)tc->tc_priv) : "edx");
8135df88f46SJung-uk Kim 	return (rv);
81495f2f098SJung-uk Kim }
815aea81038SKonstantin Belousov 
816814124c3SKonstantin Belousov static u_int
8179e680e40SKonstantin Belousov tscp_get_timecount_low(struct timecounter *tc)
8189e680e40SKonstantin Belousov {
8199e680e40SKonstantin Belousov 	uint32_t rv;
8209e680e40SKonstantin Belousov 
8219e680e40SKonstantin Belousov 	__asm __volatile("rdtscp; movl %1, %%ecx; shrd %%cl, %%edx, %0"
822a013e285SKonstantin Belousov 	    : "=&a" (rv) : "m" (tc->tc_priv) : "ecx", "edx");
8239e680e40SKonstantin Belousov 	return (rv);
8249e680e40SKonstantin Belousov }
8259e680e40SKonstantin Belousov 
8269e680e40SKonstantin Belousov static u_int
827814124c3SKonstantin Belousov tsc_get_timecount_lfence(struct timecounter *tc __unused)
828814124c3SKonstantin Belousov {
829814124c3SKonstantin Belousov 
830814124c3SKonstantin Belousov 	lfence();
831814124c3SKonstantin Belousov 	return (rdtsc32());
832814124c3SKonstantin Belousov }
833814124c3SKonstantin Belousov 
834814124c3SKonstantin Belousov static u_int
835814124c3SKonstantin Belousov tsc_get_timecount_low_lfence(struct timecounter *tc)
836814124c3SKonstantin Belousov {
837814124c3SKonstantin Belousov 
838814124c3SKonstantin Belousov 	lfence();
839814124c3SKonstantin Belousov 	return (tsc_get_timecount_low(tc));
840814124c3SKonstantin Belousov }
841814124c3SKonstantin Belousov 
842814124c3SKonstantin Belousov static u_int
843814124c3SKonstantin Belousov tsc_get_timecount_mfence(struct timecounter *tc __unused)
844814124c3SKonstantin Belousov {
845814124c3SKonstantin Belousov 
846814124c3SKonstantin Belousov 	mfence();
847814124c3SKonstantin Belousov 	return (rdtsc32());
848814124c3SKonstantin Belousov }
849814124c3SKonstantin Belousov 
850814124c3SKonstantin Belousov static u_int
851814124c3SKonstantin Belousov tsc_get_timecount_low_mfence(struct timecounter *tc)
852814124c3SKonstantin Belousov {
853814124c3SKonstantin Belousov 
854814124c3SKonstantin Belousov 	mfence();
855814124c3SKonstantin Belousov 	return (tsc_get_timecount_low(tc));
856814124c3SKonstantin Belousov }
857814124c3SKonstantin Belousov 
85816808549SKonstantin Belousov static uint32_t
85916808549SKonstantin Belousov x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th, struct timecounter *tc)
860aea81038SKonstantin Belousov {
861aea81038SKonstantin Belousov 
86216808549SKonstantin Belousov 	vdso_th->th_algo = VDSO_TH_ALGO_X86_TSC;
863d1b1b600SNeel Natu 	vdso_th->th_x86_shift = (int)(intptr_t)tc->tc_priv;
86416808549SKonstantin Belousov 	vdso_th->th_x86_hpet_idx = 0xffffffff;
865aea81038SKonstantin Belousov 	bzero(vdso_th->th_res, sizeof(vdso_th->th_res));
86616808549SKonstantin Belousov 	return (1);
867aea81038SKonstantin Belousov }
868aea81038SKonstantin Belousov 
869aea81038SKonstantin Belousov #ifdef COMPAT_FREEBSD32
87016808549SKonstantin Belousov static uint32_t
87116808549SKonstantin Belousov x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
872d1b1b600SNeel Natu     struct timecounter *tc)
873aea81038SKonstantin Belousov {
874aea81038SKonstantin Belousov 
87516808549SKonstantin Belousov 	vdso_th32->th_algo = VDSO_TH_ALGO_X86_TSC;
876d1b1b600SNeel Natu 	vdso_th32->th_x86_shift = (int)(intptr_t)tc->tc_priv;
87716808549SKonstantin Belousov 	vdso_th32->th_x86_hpet_idx = 0xffffffff;
878aea81038SKonstantin Belousov 	bzero(vdso_th32->th_res, sizeof(vdso_th32->th_res));
87916808549SKonstantin Belousov 	return (1);
880aea81038SKonstantin Belousov }
881aea81038SKonstantin Belousov #endif
882