xref: /freebsd/sys/x86/x86/tsc.c (revision 698727d6)
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>
51dd7d207dSJung-uk Kim #include <machine/md_var.h>
52dd7d207dSJung-uk Kim #include <machine/specialreg.h>
5301e1933dSJohn Baldwin #include <x86/vmware.h>
5416808549SKonstantin Belousov #include <dev/acpica/acpi_hpet.h>
55ce3bf750SKonstantin Belousov #include <contrib/dev/acpica/include/acpi.h>
56dd7d207dSJung-uk Kim 
57dd7d207dSJung-uk Kim #include "cpufreq_if.h"
58dd7d207dSJung-uk Kim 
59dd7d207dSJung-uk Kim uint64_t	tsc_freq;
60dd7d207dSJung-uk Kim int		tsc_is_invariant;
61155094d7SJung-uk Kim int		tsc_perf_stat;
629cb32882SColin Percival static int	tsc_early_calib_exact;
63155094d7SJung-uk Kim 
64dd7d207dSJung-uk Kim static eventhandler_tag tsc_levels_tag, tsc_pre_tag, tsc_post_tag;
65dd7d207dSJung-uk Kim 
66dd7d207dSJung-uk Kim SYSCTL_INT(_kern_timecounter, OID_AUTO, invariant_tsc, CTLFLAG_RDTUN,
67dd7d207dSJung-uk Kim     &tsc_is_invariant, 0, "Indicates whether the TSC is P-state invariant");
68dd7d207dSJung-uk Kim 
69dd7d207dSJung-uk Kim #ifdef SMP
701472b87fSNeel Natu int	smp_tsc;
71dd7d207dSJung-uk Kim SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc, CTLFLAG_RDTUN, &smp_tsc, 0,
72dd7d207dSJung-uk Kim     "Indicates whether the TSC is safe to use in SMP mode");
73b2c63698SAlexander Motin 
74b2c63698SAlexander Motin int	smp_tsc_adjust = 0;
75b2c63698SAlexander Motin SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc_adjust, CTLFLAG_RDTUN,
76b2c63698SAlexander Motin     &smp_tsc_adjust, 0, "Try to adjust TSC on APs to match BSP");
77dd7d207dSJung-uk Kim #endif
78dd7d207dSJung-uk Kim 
79e7f1427dSKonstantin Belousov static int	tsc_shift = 1;
80e7f1427dSKonstantin Belousov SYSCTL_INT(_kern_timecounter, OID_AUTO, tsc_shift, CTLFLAG_RDTUN,
81e7f1427dSKonstantin Belousov     &tsc_shift, 0, "Shift to pre-apply for the maximum TSC frequency");
82e7f1427dSKonstantin Belousov 
8379422085SJung-uk Kim static int	tsc_disabled;
8479422085SJung-uk Kim SYSCTL_INT(_machdep, OID_AUTO, disable_tsc, CTLFLAG_RDTUN, &tsc_disabled, 0,
8579422085SJung-uk Kim     "Disable x86 Time Stamp Counter");
8679422085SJung-uk Kim 
87a4e4127fSJung-uk Kim static int	tsc_skip_calibration;
88ab23c278SKonstantin Belousov SYSCTL_INT(_machdep, OID_AUTO, disable_tsc_calibration, CTLFLAG_RDTUN,
89ab23c278SKonstantin Belousov     &tsc_skip_calibration, 0,
9022875f88SMark Johnston     "Disable early TSC frequency calibration");
91a4e4127fSJung-uk Kim 
92dd7d207dSJung-uk Kim static void tsc_freq_changed(void *arg, const struct cf_level *level,
93dd7d207dSJung-uk Kim     int status);
94dd7d207dSJung-uk Kim static void tsc_freq_changing(void *arg, const struct cf_level *level,
95dd7d207dSJung-uk Kim     int *status);
96826fc3ccSKonstantin Belousov static u_int tsc_get_timecount(struct timecounter *tc);
97826fc3ccSKonstantin Belousov static inline u_int tsc_get_timecount_low(struct timecounter *tc);
98826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_lfence(struct timecounter *tc);
99826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_low_lfence(struct timecounter *tc);
100826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_mfence(struct timecounter *tc);
101826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_low_mfence(struct timecounter *tc);
1029e680e40SKonstantin Belousov static u_int tscp_get_timecount(struct timecounter *tc);
1039e680e40SKonstantin Belousov static u_int tscp_get_timecount_low(struct timecounter *tc);
104dd7d207dSJung-uk Kim static void tsc_levels_changed(void *arg, int unit);
10516808549SKonstantin Belousov static uint32_t x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th,
10616808549SKonstantin Belousov     struct timecounter *tc);
10716808549SKonstantin Belousov #ifdef COMPAT_FREEBSD32
10816808549SKonstantin Belousov static uint32_t x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
10916808549SKonstantin Belousov     struct timecounter *tc);
11016808549SKonstantin Belousov #endif
111dd7d207dSJung-uk Kim 
112dd7d207dSJung-uk Kim static struct timecounter tsc_timecounter = {
11316808549SKonstantin Belousov 	.tc_get_timecount =		tsc_get_timecount,
11416808549SKonstantin Belousov 	.tc_counter_mask =		~0u,
11516808549SKonstantin Belousov 	.tc_name =			"TSC",
11616808549SKonstantin Belousov 	.tc_quality =			800,	/* adjusted in code */
11716808549SKonstantin Belousov 	.tc_fill_vdso_timehands = 	x86_tsc_vdso_timehands,
11816808549SKonstantin Belousov #ifdef COMPAT_FREEBSD32
11916808549SKonstantin Belousov 	.tc_fill_vdso_timehands32 = 	x86_tsc_vdso_timehands32,
12016808549SKonstantin Belousov #endif
121dd7d207dSJung-uk Kim };
122dd7d207dSJung-uk Kim 
12301e1933dSJohn Baldwin static void
1245da5812bSJung-uk Kim tsc_freq_vmware(void)
1255da5812bSJung-uk Kim {
1265da5812bSJung-uk Kim 	u_int regs[4];
1275da5812bSJung-uk Kim 
1285da5812bSJung-uk Kim 	if (hv_high >= 0x40000010) {
1295da5812bSJung-uk Kim 		do_cpuid(0x40000010, regs);
1305da5812bSJung-uk Kim 		tsc_freq = regs[0] * 1000;
1315da5812bSJung-uk Kim 	} else {
1325da5812bSJung-uk Kim 		vmware_hvcall(VMW_HVCMD_GETHZ, regs);
1335da5812bSJung-uk Kim 		if (regs[1] != UINT_MAX)
1345da5812bSJung-uk Kim 			tsc_freq = regs[0] | ((uint64_t)regs[1] << 32);
1355da5812bSJung-uk Kim 	}
1365da5812bSJung-uk Kim 	tsc_is_invariant = 1;
1379cb32882SColin Percival 	tsc_early_calib_exact = 1;
1385da5812bSJung-uk Kim }
1395da5812bSJung-uk Kim 
140506a906cSKonstantin Belousov /*
14122875f88SMark Johnston  * Calculate TSC frequency using information from the CPUID leaf 0x15 'Time
14222875f88SMark Johnston  * Stamp Counter and Nominal Core Crystal Clock'.  If leaf 0x15 is not
14322875f88SMark Johnston  * functional, as it is on Skylake/Kabylake, try 0x16 'Processor Frequency
14422875f88SMark Johnston  * Information'.  Leaf 0x16 is described in the SDM as informational only, but
14522875f88SMark Johnston  * we can use this value until late calibration is complete.
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 
17122875f88SMark Johnston static bool
17222875f88SMark Johnston tsc_freq_intel_brand(uint64_t *res)
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:
20922875f88SMark Johnston 				return (false);
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
22522875f88SMark Johnston 			*res = freq;
22622875f88SMark Johnston 			return (true);
227a4e4127fSJung-uk Kim 		}
228a4e4127fSJung-uk Kim 	}
22922875f88SMark Johnston 	return (false);
23022875f88SMark Johnston }
23122875f88SMark Johnston 
23222875f88SMark Johnston static void
23322875f88SMark Johnston tsc_freq_8254(uint64_t *res)
23422875f88SMark Johnston {
23522875f88SMark Johnston 	uint64_t tsc1, tsc2;
23622875f88SMark Johnston 	int64_t overhead;
23722875f88SMark Johnston 	int count, i;
23822875f88SMark Johnston 
23922875f88SMark Johnston 	overhead = 0;
24022875f88SMark Johnston 	for (i = 0, count = 8; i < count; i++) {
24122875f88SMark Johnston 		tsc1 = rdtsc_ordered();
24222875f88SMark Johnston 		DELAY(0);
24322875f88SMark Johnston 		tsc2 = rdtsc_ordered();
24422875f88SMark Johnston 		if (i > 0)
24522875f88SMark Johnston 			overhead += tsc2 - tsc1;
24622875f88SMark Johnston 	}
24722875f88SMark Johnston 	overhead /= count;
24822875f88SMark Johnston 
24922875f88SMark Johnston 	tsc1 = rdtsc_ordered();
25022875f88SMark Johnston 	DELAY(100000);
25122875f88SMark Johnston 	tsc2 = rdtsc_ordered();
25222875f88SMark Johnston 	tsc_freq = (tsc2 - tsc1 - overhead) * 10;
253a4e4127fSJung-uk Kim }
254dd7d207dSJung-uk Kim 
255a4e4127fSJung-uk Kim static void
256a4e4127fSJung-uk Kim probe_tsc_freq(void)
257a4e4127fSJung-uk Kim {
258bb044eafSConrad Meyer 	if (cpu_power_ecx & CPUID_PERF_STAT) {
2595da5812bSJung-uk Kim 		/*
260bb044eafSConrad Meyer 		 * XXX Some emulators expose host CPUID without actual support
261bb044eafSConrad Meyer 		 * for these MSRs.  We must test whether they really work.
2625da5812bSJung-uk Kim 		 */
2635da5812bSJung-uk Kim 		wrmsr(MSR_MPERF, 0);
2645da5812bSJung-uk Kim 		wrmsr(MSR_APERF, 0);
2655da5812bSJung-uk Kim 		DELAY(10);
2665da5812bSJung-uk Kim 		if (rdmsr(MSR_MPERF) > 0 && rdmsr(MSR_APERF) > 0)
2675da5812bSJung-uk Kim 			tsc_perf_stat = 1;
2685da5812bSJung-uk Kim 	}
2695da5812bSJung-uk Kim 
27001e1933dSJohn Baldwin 	if (vm_guest == VM_GUEST_VMWARE) {
27101e1933dSJohn Baldwin 		tsc_freq_vmware();
2725da5812bSJung-uk Kim 		return;
27301e1933dSJohn Baldwin 	}
2745da5812bSJung-uk Kim 
275dd7d207dSJung-uk Kim 	switch (cpu_vendor_id) {
276dd7d207dSJung-uk Kim 	case CPU_VENDOR_AMD:
2772ee49facSKonstantin Belousov 	case CPU_VENDOR_HYGON:
278a106a27cSJung-uk Kim 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
279a106a27cSJung-uk Kim 		    (vm_guest == VM_GUEST_NO &&
280a106a27cSJung-uk Kim 		    CPUID_TO_FAMILY(cpu_id) >= 0x10))
281dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
282814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
283814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
284814124c3SKonstantin Belousov 			    tsc_get_timecount_mfence;
285814124c3SKonstantin Belousov 		}
286dd7d207dSJung-uk Kim 		break;
287dd7d207dSJung-uk Kim 	case CPU_VENDOR_INTEL:
288a106a27cSJung-uk Kim 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
289a106a27cSJung-uk Kim 		    (vm_guest == VM_GUEST_NO &&
290a106a27cSJung-uk Kim 		    ((CPUID_TO_FAMILY(cpu_id) == 0x6 &&
291dd7d207dSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0xe) ||
292dd7d207dSJung-uk Kim 		    (CPUID_TO_FAMILY(cpu_id) == 0xf &&
293a106a27cSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0x3))))
294dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
295814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
296814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
297814124c3SKonstantin Belousov 			    tsc_get_timecount_lfence;
298814124c3SKonstantin Belousov 		}
299dd7d207dSJung-uk Kim 		break;
300dd7d207dSJung-uk Kim 	case CPU_VENDOR_CENTAUR:
301a106a27cSJung-uk Kim 		if (vm_guest == VM_GUEST_NO &&
302a106a27cSJung-uk Kim 		    CPUID_TO_FAMILY(cpu_id) == 0x6 &&
303dd7d207dSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0xf &&
304dd7d207dSJung-uk Kim 		    (rdmsr(0x1203) & 0x100000000ULL) == 0)
305dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
306814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
307814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
308814124c3SKonstantin Belousov 			    tsc_get_timecount_lfence;
309814124c3SKonstantin Belousov 		}
310dd7d207dSJung-uk Kim 		break;
311dd7d207dSJung-uk Kim 	}
312dd7d207dSJung-uk Kim 
31322875f88SMark Johnston 	if (tsc_freq_cpuid(&tsc_freq)) {
314bd8a359fSKonstantin Belousov 		/*
31522875f88SMark Johnston 		 * If possible, use the value obtained from CPUID as the initial
31622875f88SMark Johnston 		 * frequency.  This will be refined later during boot but is
31722875f88SMark Johnston 		 * good enough for now.  The 8254 PIT is not functional on some
31822875f88SMark Johnston 		 * newer platforms anyway, so don't delay our boot for what
31922875f88SMark Johnston 		 * might be a garbage result.  Late calibration is required if
32022875f88SMark Johnston 		 * the initial frequency was obtained from CPUID.16H, as the
32122875f88SMark Johnston 		 * derived value may be off by as much as 1%.
322bd8a359fSKonstantin Belousov 		 */
323a4e4127fSJung-uk Kim 		if (bootverbose)
32422875f88SMark Johnston 			printf("Early TSC frequency %juHz derived from CPUID\n",
32522875f88SMark Johnston 			    (uintmax_t)tsc_freq);
32622875f88SMark Johnston 	} else if (tsc_skip_calibration) {
32722875f88SMark Johnston 		/*
32822875f88SMark Johnston 		 * Try to parse the brand string to obtain the nominal TSC
32922875f88SMark Johnston 		 * frequency.
33022875f88SMark Johnston 		 */
33122875f88SMark Johnston 		if (cpu_vendor_id == CPU_VENDOR_INTEL &&
33222875f88SMark Johnston 		    tsc_freq_intel_brand(&tsc_freq)) {
33322875f88SMark Johnston 			if (bootverbose)
33422875f88SMark Johnston 				printf(
33522875f88SMark Johnston 		    "Early TSC frequency %juHz derived from brand string\n",
33622875f88SMark Johnston 				    (uintmax_t)tsc_freq);
33722875f88SMark Johnston 		} else {
33822875f88SMark Johnston 			tsc_disabled = 1;
33922875f88SMark Johnston 		}
34022875f88SMark Johnston 	} else {
34122875f88SMark Johnston 		/*
34222875f88SMark Johnston 		 * Calibrate against the 8254 PIT.  This estimate will be
34322875f88SMark Johnston 		 * refined later in tsc_calib().
34422875f88SMark Johnston 		 */
34522875f88SMark Johnston 		tsc_freq_8254(&tsc_freq);
34622875f88SMark Johnston 		if (bootverbose)
34722875f88SMark Johnston 			printf(
34822875f88SMark Johnston 		    "Early TSC frequency %juHz calibrated from 8254 PIT\n",
34922875f88SMark Johnston 			    (uintmax_t)tsc_freq);
35022875f88SMark Johnston 	}
351a4e4127fSJung-uk Kim }
352a4e4127fSJung-uk Kim 
353a4e4127fSJung-uk Kim void
354a4e4127fSJung-uk Kim init_TSC(void)
355a4e4127fSJung-uk Kim {
356a4e4127fSJung-uk Kim 
357a4e4127fSJung-uk Kim 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
358a4e4127fSJung-uk Kim 		return;
359a4e4127fSJung-uk Kim 
360fe760cfaSJohn Baldwin #ifdef __i386__
361fe760cfaSJohn Baldwin 	/* The TSC is known to be broken on certain CPUs. */
362fe760cfaSJohn Baldwin 	switch (cpu_vendor_id) {
363fe760cfaSJohn Baldwin 	case CPU_VENDOR_AMD:
364fe760cfaSJohn Baldwin 		switch (cpu_id & 0xFF0) {
365fe760cfaSJohn Baldwin 		case 0x500:
366fe760cfaSJohn Baldwin 			/* K5 Model 0 */
367fe760cfaSJohn Baldwin 			return;
368fe760cfaSJohn Baldwin 		}
369fe760cfaSJohn Baldwin 		break;
370fe760cfaSJohn Baldwin 	case CPU_VENDOR_CENTAUR:
371fe760cfaSJohn Baldwin 		switch (cpu_id & 0xff0) {
372fe760cfaSJohn Baldwin 		case 0x540:
373fe760cfaSJohn Baldwin 			/*
374fe760cfaSJohn Baldwin 			 * http://www.centtech.com/c6_data_sheet.pdf
375fe760cfaSJohn Baldwin 			 *
376fe760cfaSJohn Baldwin 			 * I-12 RDTSC may return incoherent values in EDX:EAX
377fe760cfaSJohn Baldwin 			 * I-13 RDTSC hangs when certain event counters are used
378fe760cfaSJohn Baldwin 			 */
379fe760cfaSJohn Baldwin 			return;
380fe760cfaSJohn Baldwin 		}
381fe760cfaSJohn Baldwin 		break;
382fe760cfaSJohn Baldwin 	case CPU_VENDOR_NSC:
383fe760cfaSJohn Baldwin 		switch (cpu_id & 0xff0) {
384fe760cfaSJohn Baldwin 		case 0x540:
385fe760cfaSJohn Baldwin 			if ((cpu_id & CPUID_STEPPING) == 0)
386fe760cfaSJohn Baldwin 				return;
387fe760cfaSJohn Baldwin 			break;
388fe760cfaSJohn Baldwin 		}
389fe760cfaSJohn Baldwin 		break;
390fe760cfaSJohn Baldwin 	}
391fe760cfaSJohn Baldwin #endif
392fe760cfaSJohn Baldwin 
393a4e4127fSJung-uk Kim 	probe_tsc_freq();
394a4e4127fSJung-uk Kim 
395dd7d207dSJung-uk Kim 	/*
396dd7d207dSJung-uk Kim 	 * Inform CPU accounting about our boot-time clock rate.  This will
397dd7d207dSJung-uk Kim 	 * be updated if someone loads a cpufreq driver after boot that
398dd7d207dSJung-uk Kim 	 * discovers a new max frequency.
39922875f88SMark Johnston 	 *
40022875f88SMark Johnston 	 * The frequency may also be updated after late calibration is complete;
40122875f88SMark Johnston 	 * however, we register the TSC as the ticker now to avoid switching
40222875f88SMark Johnston 	 * counters after much of the kernel has already booted and potentially
40322875f88SMark Johnston 	 * sampled the CPU clock.
404dd7d207dSJung-uk Kim 	 */
405a4e4127fSJung-uk Kim 	if (tsc_freq != 0)
4065ac44f72SJung-uk Kim 		set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
407dd7d207dSJung-uk Kim 
408dd7d207dSJung-uk Kim 	if (tsc_is_invariant)
409dd7d207dSJung-uk Kim 		return;
410dd7d207dSJung-uk Kim 
411dd7d207dSJung-uk Kim 	/* Register to find out about changes in CPU frequency. */
412dd7d207dSJung-uk Kim 	tsc_pre_tag = EVENTHANDLER_REGISTER(cpufreq_pre_change,
413dd7d207dSJung-uk Kim 	    tsc_freq_changing, NULL, EVENTHANDLER_PRI_FIRST);
414dd7d207dSJung-uk Kim 	tsc_post_tag = EVENTHANDLER_REGISTER(cpufreq_post_change,
415dd7d207dSJung-uk Kim 	    tsc_freq_changed, NULL, EVENTHANDLER_PRI_FIRST);
416dd7d207dSJung-uk Kim 	tsc_levels_tag = EVENTHANDLER_REGISTER(cpufreq_levels_changed,
417dd7d207dSJung-uk Kim 	    tsc_levels_changed, NULL, EVENTHANDLER_PRI_ANY);
418dd7d207dSJung-uk Kim }
419dd7d207dSJung-uk Kim 
42065e7d70bSJung-uk Kim #ifdef SMP
42165e7d70bSJung-uk Kim 
422814124c3SKonstantin Belousov /*
423814124c3SKonstantin Belousov  * RDTSC is not a serializing instruction, and does not drain
424814124c3SKonstantin Belousov  * instruction stream, so we need to drain the stream before executing
425814124c3SKonstantin Belousov  * it.  It could be fixed by use of RDTSCP, except the instruction is
426814124c3SKonstantin Belousov  * not available everywhere.
427814124c3SKonstantin Belousov  *
428814124c3SKonstantin Belousov  * Use CPUID for draining in the boot-time SMP constistency test.  The
429814124c3SKonstantin Belousov  * timecounters use MFENCE for AMD CPUs, and LFENCE for others (Intel
430814124c3SKonstantin Belousov  * and VIA) when SSE2 is present, and nothing on older machines which
431814124c3SKonstantin Belousov  * also do not issue RDTSC prematurely.  There, testing for SSE2 and
432e1a18e46SKonstantin Belousov  * vendor is too cumbersome, and we learn about TSC presence from CPUID.
433814124c3SKonstantin Belousov  *
434814124c3SKonstantin Belousov  * Do not use do_cpuid(), since we do not need CPUID results, which
435814124c3SKonstantin Belousov  * have to be written into memory with do_cpuid().
436814124c3SKonstantin Belousov  */
43765e7d70bSJung-uk Kim #define	TSC_READ(x)							\
43865e7d70bSJung-uk Kim static void								\
43965e7d70bSJung-uk Kim tsc_read_##x(void *arg)							\
44065e7d70bSJung-uk Kim {									\
4417bfcb3bbSJim Harris 	uint64_t *tsc = arg;						\
44265e7d70bSJung-uk Kim 	u_int cpu = PCPU_GET(cpuid);					\
44365e7d70bSJung-uk Kim 									\
444814124c3SKonstantin Belousov 	__asm __volatile("cpuid" : : : "eax", "ebx", "ecx", "edx");	\
4457bfcb3bbSJim Harris 	tsc[cpu * 3 + x] = rdtsc();					\
44665e7d70bSJung-uk Kim }
44765e7d70bSJung-uk Kim TSC_READ(0)
44865e7d70bSJung-uk Kim TSC_READ(1)
44965e7d70bSJung-uk Kim TSC_READ(2)
45065e7d70bSJung-uk Kim #undef TSC_READ
45165e7d70bSJung-uk Kim 
45265e7d70bSJung-uk Kim #define	N	1000
45365e7d70bSJung-uk Kim 
45465e7d70bSJung-uk Kim static void
45565e7d70bSJung-uk Kim comp_smp_tsc(void *arg)
45665e7d70bSJung-uk Kim {
4577bfcb3bbSJim Harris 	uint64_t *tsc;
4587bfcb3bbSJim Harris 	int64_t d1, d2;
45965e7d70bSJung-uk Kim 	u_int cpu = PCPU_GET(cpuid);
46065e7d70bSJung-uk Kim 	u_int i, j, size;
46165e7d70bSJung-uk Kim 
46265e7d70bSJung-uk Kim 	size = (mp_maxid + 1) * 3;
46365e7d70bSJung-uk Kim 	for (i = 0, tsc = arg; i < N; i++, tsc += size)
46465e7d70bSJung-uk Kim 		CPU_FOREACH(j) {
46565e7d70bSJung-uk Kim 			if (j == cpu)
46665e7d70bSJung-uk Kim 				continue;
46765e7d70bSJung-uk Kim 			d1 = tsc[cpu * 3 + 1] - tsc[j * 3];
46865e7d70bSJung-uk Kim 			d2 = tsc[cpu * 3 + 2] - tsc[j * 3 + 1];
46965e7d70bSJung-uk Kim 			if (d1 <= 0 || d2 <= 0) {
47065e7d70bSJung-uk Kim 				smp_tsc = 0;
47165e7d70bSJung-uk Kim 				return;
47265e7d70bSJung-uk Kim 			}
47365e7d70bSJung-uk Kim 		}
47465e7d70bSJung-uk Kim }
47565e7d70bSJung-uk Kim 
476b2c63698SAlexander Motin static void
477b2c63698SAlexander Motin adj_smp_tsc(void *arg)
478b2c63698SAlexander Motin {
479b2c63698SAlexander Motin 	uint64_t *tsc;
480b2c63698SAlexander Motin 	int64_t d, min, max;
481b2c63698SAlexander Motin 	u_int cpu = PCPU_GET(cpuid);
482b2c63698SAlexander Motin 	u_int first, i, size;
483b2c63698SAlexander Motin 
484b2c63698SAlexander Motin 	first = CPU_FIRST();
485b2c63698SAlexander Motin 	if (cpu == first)
486b2c63698SAlexander Motin 		return;
487b2c63698SAlexander Motin 	min = INT64_MIN;
488b2c63698SAlexander Motin 	max = INT64_MAX;
489b2c63698SAlexander Motin 	size = (mp_maxid + 1) * 3;
490b2c63698SAlexander Motin 	for (i = 0, tsc = arg; i < N; i++, tsc += size) {
491b2c63698SAlexander Motin 		d = tsc[first * 3] - tsc[cpu * 3 + 1];
492b2c63698SAlexander Motin 		if (d > min)
493b2c63698SAlexander Motin 			min = d;
494b2c63698SAlexander Motin 		d = tsc[first * 3 + 1] - tsc[cpu * 3 + 2];
495b2c63698SAlexander Motin 		if (d > min)
496b2c63698SAlexander Motin 			min = d;
497b2c63698SAlexander Motin 		d = tsc[first * 3 + 1] - tsc[cpu * 3];
498b2c63698SAlexander Motin 		if (d < max)
499b2c63698SAlexander Motin 			max = d;
500b2c63698SAlexander Motin 		d = tsc[first * 3 + 2] - tsc[cpu * 3 + 1];
501b2c63698SAlexander Motin 		if (d < max)
502b2c63698SAlexander Motin 			max = d;
503b2c63698SAlexander Motin 	}
504b2c63698SAlexander Motin 	if (min > max)
505b2c63698SAlexander Motin 		return;
506b2c63698SAlexander Motin 	d = min / 2 + max / 2;
507b2c63698SAlexander Motin 	__asm __volatile (
508b2c63698SAlexander Motin 		"movl $0x10, %%ecx\n\t"
509b2c63698SAlexander Motin 		"rdmsr\n\t"
510b2c63698SAlexander Motin 		"addl %%edi, %%eax\n\t"
511b2c63698SAlexander Motin 		"adcl %%esi, %%edx\n\t"
512b2c63698SAlexander Motin 		"wrmsr\n"
513b2c63698SAlexander Motin 		: /* No output */
514b2c63698SAlexander Motin 		: "D" ((uint32_t)d), "S" ((uint32_t)(d >> 32))
515b2c63698SAlexander Motin 		: "ax", "cx", "dx", "cc"
516b2c63698SAlexander Motin 	);
517b2c63698SAlexander Motin }
518b2c63698SAlexander Motin 
51965e7d70bSJung-uk Kim static int
520279be68bSAndriy Gapon test_tsc(int adj_max_count)
52165e7d70bSJung-uk Kim {
5227bfcb3bbSJim Harris 	uint64_t *data, *tsc;
523b2c63698SAlexander Motin 	u_int i, size, adj;
52465e7d70bSJung-uk Kim 
52584eaf2ccSKonstantin Belousov 	if ((!smp_tsc && !tsc_is_invariant))
52665e7d70bSJung-uk Kim 		return (-100);
5278cc15b0dSKyle Evans 	/*
5288cc15b0dSKyle Evans 	 * Misbehavior of TSC under VirtualBox has been observed.  In
5298cc15b0dSKyle Evans 	 * particular, threads doing small (~1 second) sleeps may miss their
5308cc15b0dSKyle Evans 	 * wakeup and hang around in sleep state, causing hangs on shutdown.
5318cc15b0dSKyle Evans 	 */
5328cc15b0dSKyle Evans 	if (vm_guest == VM_GUEST_VBOX)
5338cc15b0dSKyle Evans 		return (0);
5348cc15b0dSKyle Evans 
535cd165c8bSColin Percival 	TSENTER();
53665e7d70bSJung-uk Kim 	size = (mp_maxid + 1) * 3;
53765e7d70bSJung-uk Kim 	data = malloc(sizeof(*data) * size * N, M_TEMP, M_WAITOK);
538b2c63698SAlexander Motin 	adj = 0;
539b2c63698SAlexander Motin retry:
54065e7d70bSJung-uk Kim 	for (i = 0, tsc = data; i < N; i++, tsc += size)
54165e7d70bSJung-uk Kim 		smp_rendezvous(tsc_read_0, tsc_read_1, tsc_read_2, tsc);
54265e7d70bSJung-uk Kim 	smp_tsc = 1;	/* XXX */
54367d955aaSPatrick Kelsey 	smp_rendezvous(smp_no_rendezvous_barrier, comp_smp_tsc,
54467d955aaSPatrick Kelsey 	    smp_no_rendezvous_barrier, data);
545279be68bSAndriy Gapon 	if (!smp_tsc && adj < adj_max_count) {
546b2c63698SAlexander Motin 		adj++;
54767d955aaSPatrick Kelsey 		smp_rendezvous(smp_no_rendezvous_barrier, adj_smp_tsc,
54867d955aaSPatrick Kelsey 		    smp_no_rendezvous_barrier, data);
549b2c63698SAlexander Motin 		goto retry;
550b2c63698SAlexander Motin 	}
55165e7d70bSJung-uk Kim 	free(data, M_TEMP);
55265e7d70bSJung-uk Kim 	if (bootverbose)
553b2c63698SAlexander Motin 		printf("SMP: %sed TSC synchronization test%s\n",
554b2c63698SAlexander Motin 		    smp_tsc ? "pass" : "fail",
555b2c63698SAlexander Motin 		    adj > 0 ? " after adjustment" : "");
556cd165c8bSColin Percival 	TSEXIT();
55726e6537aSJung-uk Kim 	if (smp_tsc && tsc_is_invariant) {
55826e6537aSJung-uk Kim 		switch (cpu_vendor_id) {
55926e6537aSJung-uk Kim 		case CPU_VENDOR_AMD:
5602ee49facSKonstantin Belousov 		case CPU_VENDOR_HYGON:
56126e6537aSJung-uk Kim 			/*
562450d86fcSJung-uk Kim 			 * Processor Programming Reference (PPR) for AMD
563450d86fcSJung-uk Kim 			 * Family 17h states that the TSC uses a common
564450d86fcSJung-uk Kim 			 * reference for all sockets, cores and threads.
565450d86fcSJung-uk Kim 			 */
566450d86fcSJung-uk Kim 			if (CPUID_TO_FAMILY(cpu_id) >= 0x17)
567450d86fcSJung-uk Kim 				return (1000);
568450d86fcSJung-uk Kim 			/*
56926e6537aSJung-uk Kim 			 * Starting with Family 15h processors, TSC clock
57026e6537aSJung-uk Kim 			 * source is in the north bridge.  Check whether
57126e6537aSJung-uk Kim 			 * we have a single-socket/multi-core platform.
57226e6537aSJung-uk Kim 			 * XXX Need more work for complex cases.
57326e6537aSJung-uk Kim 			 */
57426e6537aSJung-uk Kim 			if (CPUID_TO_FAMILY(cpu_id) < 0x15 ||
57526e6537aSJung-uk Kim 			    (amd_feature2 & AMDID2_CMP) == 0 ||
57626e6537aSJung-uk Kim 			    smp_cpus > (cpu_procinfo2 & AMDID_CMP_CORES) + 1)
57726e6537aSJung-uk Kim 				break;
57826e6537aSJung-uk Kim 			return (1000);
57926e6537aSJung-uk Kim 		case CPU_VENDOR_INTEL:
58026e6537aSJung-uk Kim 			/*
58126e6537aSJung-uk Kim 			 * XXX Assume Intel platforms have synchronized TSCs.
58226e6537aSJung-uk Kim 			 */
58326e6537aSJung-uk Kim 			return (1000);
58426e6537aSJung-uk Kim 		}
58526e6537aSJung-uk Kim 		return (800);
58626e6537aSJung-uk Kim 	}
58726e6537aSJung-uk Kim 	return (-100);
58865e7d70bSJung-uk Kim }
58965e7d70bSJung-uk Kim 
59065e7d70bSJung-uk Kim #undef N
59165e7d70bSJung-uk Kim 
59265e7d70bSJung-uk Kim #endif /* SMP */
59365e7d70bSJung-uk Kim 
59465e7d70bSJung-uk Kim static void
595dd7d207dSJung-uk Kim init_TSC_tc(void)
596dd7d207dSJung-uk Kim {
59795f2f098SJung-uk Kim 	uint64_t max_freq;
59895f2f098SJung-uk Kim 	int shift;
599dd7d207dSJung-uk Kim 
60038b8542cSJung-uk Kim 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
601dd7d207dSJung-uk Kim 		return;
602dd7d207dSJung-uk Kim 
603dd7d207dSJung-uk Kim 	/*
60495f2f098SJung-uk Kim 	 * Limit timecounter frequency to fit in an int and prevent it from
60595f2f098SJung-uk Kim 	 * overflowing too fast.
60695f2f098SJung-uk Kim 	 */
60795f2f098SJung-uk Kim 	max_freq = UINT_MAX;
60895f2f098SJung-uk Kim 
60995f2f098SJung-uk Kim 	/*
61092597e06SJohn Baldwin 	 * Intel CPUs without a C-state invariant TSC can stop the TSC
611d1411416SJohn Baldwin 	 * in either C2 or C3.  Disable use of C2 and C3 while using
612d1411416SJohn Baldwin 	 * the TSC as the timecounter.  The timecounter can be changed
613d1411416SJohn Baldwin 	 * to enable C2 and C3.
614d1411416SJohn Baldwin 	 *
615d1411416SJohn Baldwin 	 * Note that the TSC is used as the cputicker for computing
616d1411416SJohn Baldwin 	 * thread runtime regardless of the timecounter setting, so
617d1411416SJohn Baldwin 	 * using an alternate timecounter and enabling C2 or C3 can
618d1411416SJohn Baldwin 	 * result incorrect runtimes for kernel idle threads (but not
619d1411416SJohn Baldwin 	 * for any non-idle threads).
620a49399a9SJung-uk Kim 	 */
6218cd59625SKonstantin Belousov 	if (cpu_vendor_id == CPU_VENDOR_INTEL &&
622a49399a9SJung-uk Kim 	    (amd_pminfo & AMDPM_TSC_INVARIANT) == 0) {
62392597e06SJohn Baldwin 		tsc_timecounter.tc_flags |= TC_FLAGS_C2STOP;
624a49399a9SJung-uk Kim 		if (bootverbose)
625d1411416SJohn Baldwin 			printf("TSC timecounter disables C2 and C3.\n");
626a49399a9SJung-uk Kim 	}
627a49399a9SJung-uk Kim 
628dd7d207dSJung-uk Kim 	/*
629e7f1427dSKonstantin Belousov 	 * We can not use the TSC in SMP mode unless the TSCs on all CPUs
630e7f1427dSKonstantin Belousov 	 * are synchronized.  If the user is sure that the system has
631e7f1427dSKonstantin Belousov 	 * synchronized TSCs, set kern.timecounter.smp_tsc tunable to a
632e7f1427dSKonstantin Belousov 	 * non-zero value.  The TSC seems unreliable in virtualized SMP
6335cf8ac1bSMike Silbersack 	 * environments, so it is set to a negative quality in those cases.
634dd7d207dSJung-uk Kim 	 */
635ba79ab82SAndriy Gapon #ifdef SMP
636e7f1427dSKonstantin Belousov 	if (mp_ncpus > 1)
637279be68bSAndriy Gapon 		tsc_timecounter.tc_quality = test_tsc(smp_tsc_adjust);
638ba79ab82SAndriy Gapon 	else
639ba79ab82SAndriy Gapon #endif /* SMP */
640ba79ab82SAndriy Gapon 	if (tsc_is_invariant)
64126e6537aSJung-uk Kim 		tsc_timecounter.tc_quality = 1000;
642e7f1427dSKonstantin Belousov 	max_freq >>= tsc_shift;
64326e6537aSJung-uk Kim 
644e7f1427dSKonstantin Belousov 	for (shift = 0; shift <= 31 && (tsc_freq >> shift) > max_freq; shift++)
64595f2f098SJung-uk Kim 		;
6469e680e40SKonstantin Belousov 
6479e680e40SKonstantin Belousov 	/*
6489e680e40SKonstantin Belousov 	 * Timecounter implementation selection, top to bottom:
6499e680e40SKonstantin Belousov 	 * - If RDTSCP is available, use RDTSCP.
6509e680e40SKonstantin Belousov 	 * - If fence instructions are provided (SSE2), use LFENCE;RDTSC
6519e680e40SKonstantin Belousov 	 *   on Intel, and MFENCE;RDTSC on AMD.
6529e680e40SKonstantin Belousov 	 * - For really old CPUs, just use RDTSC.
6539e680e40SKonstantin Belousov 	 */
6549f47eeffSKonstantin Belousov 	if ((amd_feature & AMDID_RDTSCP) != 0) {
6559e680e40SKonstantin Belousov 		tsc_timecounter.tc_get_timecount = shift > 0 ?
6569e680e40SKonstantin Belousov 		    tscp_get_timecount_low : tscp_get_timecount;
6579e680e40SKonstantin Belousov 	} else if ((cpu_feature & CPUID_SSE2) != 0 && mp_ncpus > 1) {
6582ee49facSKonstantin Belousov 		if (cpu_vendor_id == CPU_VENDOR_AMD ||
6592ee49facSKonstantin Belousov 		    cpu_vendor_id == CPU_VENDOR_HYGON) {
660e7f1427dSKonstantin Belousov 			tsc_timecounter.tc_get_timecount = shift > 0 ?
661e7f1427dSKonstantin Belousov 			    tsc_get_timecount_low_mfence :
662e7f1427dSKonstantin Belousov 			    tsc_get_timecount_mfence;
663814124c3SKonstantin Belousov 		} else {
664e7f1427dSKonstantin Belousov 			tsc_timecounter.tc_get_timecount = shift > 0 ?
665e7f1427dSKonstantin Belousov 			    tsc_get_timecount_low_lfence :
666e7f1427dSKonstantin Belousov 			    tsc_get_timecount_lfence;
667814124c3SKonstantin Belousov 		}
668e7f1427dSKonstantin Belousov 	} else {
669e7f1427dSKonstantin Belousov 		tsc_timecounter.tc_get_timecount = shift > 0 ?
670e7f1427dSKonstantin Belousov 		    tsc_get_timecount_low : tsc_get_timecount;
671e7f1427dSKonstantin Belousov 	}
672e7f1427dSKonstantin Belousov 	if (shift > 0) {
67395f2f098SJung-uk Kim 		tsc_timecounter.tc_name = "TSC-low";
67495f2f098SJung-uk Kim 		if (bootverbose)
675bc8e4ad2SJung-uk Kim 			printf("TSC timecounter discards lower %d bit(s)\n",
67695f2f098SJung-uk Kim 			    shift);
67795f2f098SJung-uk Kim 	}
678bc34c87eSJung-uk Kim 	if (tsc_freq != 0) {
67995f2f098SJung-uk Kim 		tsc_timecounter.tc_frequency = tsc_freq >> shift;
68095f2f098SJung-uk Kim 		tsc_timecounter.tc_priv = (void *)(intptr_t)shift;
68122875f88SMark Johnston 
68222875f88SMark Johnston 		/*
68322875f88SMark Johnston 		 * Timecounter registration is deferred until after late
68422875f88SMark Johnston 		 * calibration is finished.
68522875f88SMark Johnston 		 */
686dd7d207dSJung-uk Kim 	}
687dd7d207dSJung-uk Kim }
68865e7d70bSJung-uk Kim SYSINIT(tsc_tc, SI_SUB_SMP, SI_ORDER_ANY, init_TSC_tc, NULL);
689dd7d207dSJung-uk Kim 
69022875f88SMark Johnston static void
69122875f88SMark Johnston tsc_update_freq(uint64_t new_freq)
69222875f88SMark Johnston {
69322875f88SMark Johnston 	atomic_store_rel_64(&tsc_freq, new_freq);
69422875f88SMark Johnston 	atomic_store_rel_64(&tsc_timecounter.tc_frequency,
69522875f88SMark Johnston 	    new_freq >> (int)(intptr_t)tsc_timecounter.tc_priv);
69622875f88SMark Johnston }
69722875f88SMark Johnston 
69822875f88SMark Johnston /*
69922875f88SMark Johnston  * Perform late calibration of the TSC frequency once ACPI-based timecounters
700553af8f1SMark Johnston  * are available.  At this point timehands are not set up, so we read the
701553af8f1SMark Johnston  * highest-quality timecounter directly rather than using (s)binuptime().
70222875f88SMark Johnston  */
703553af8f1SMark Johnston void
704553af8f1SMark Johnston tsc_calibrate(void)
70522875f88SMark Johnston {
706553af8f1SMark Johnston 	struct timecounter *tc;
707698727d6SColin Percival 	uint64_t freq, tsc_start, tsc_end;
708553af8f1SMark Johnston 	u_int t_start, t_end;
70922875f88SMark Johnston 	register_t flags;
71022875f88SMark Johnston 	int cpu;
71122875f88SMark Johnston 
71222875f88SMark Johnston 	if (tsc_disabled)
71322875f88SMark Johnston 		return;
7149cb32882SColin Percival 	if (tsc_early_calib_exact)
7159cb32882SColin Percival 		goto calibrated;
71622875f88SMark Johnston 
717553af8f1SMark Johnston 	tc = atomic_load_ptr(&timecounter);
718553af8f1SMark Johnston 
71922875f88SMark Johnston 	flags = intr_disable();
72022875f88SMark Johnston 	cpu = curcpu;
72122875f88SMark Johnston 	tsc_start = rdtsc_ordered();
722553af8f1SMark Johnston 	t_start = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
72322875f88SMark Johnston 	intr_restore(flags);
72422875f88SMark Johnston 
72522875f88SMark Johnston 	DELAY(1000000);
72622875f88SMark Johnston 
72722875f88SMark Johnston 	thread_lock(curthread);
72822875f88SMark Johnston 	sched_bind(curthread, cpu);
72922875f88SMark Johnston 
73022875f88SMark Johnston 	flags = intr_disable();
73122875f88SMark Johnston 	tsc_end = rdtsc_ordered();
732553af8f1SMark Johnston 	t_end = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
73322875f88SMark Johnston 	intr_restore(flags);
73422875f88SMark Johnston 
73522875f88SMark Johnston 	sched_unbind(curthread);
73622875f88SMark Johnston 	thread_unlock(curthread);
73722875f88SMark Johnston 
738553af8f1SMark Johnston 	if (t_end <= t_start) {
739553af8f1SMark Johnston 		/* Assume that the counter has wrapped around at most once. */
740553af8f1SMark Johnston 		t_end += (uint64_t)tc->tc_counter_mask + 1;
741553af8f1SMark Johnston 	}
74222875f88SMark Johnston 
743698727d6SColin Percival 	freq = tc->tc_frequency * (tsc_end - tsc_start) / (t_end - t_start);
744553af8f1SMark Johnston 
745698727d6SColin Percival 	tsc_update_freq(freq);
7469cb32882SColin Percival calibrated:
74722875f88SMark Johnston 	tc_init(&tsc_timecounter);
74822875f88SMark Johnston 	set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
74922875f88SMark Johnston }
75022875f88SMark Johnston 
751279be68bSAndriy Gapon void
752279be68bSAndriy Gapon resume_TSC(void)
753279be68bSAndriy Gapon {
754ba79ab82SAndriy Gapon #ifdef SMP
755279be68bSAndriy Gapon 	int quality;
756279be68bSAndriy Gapon 
757279be68bSAndriy Gapon 	/* If TSC was not good on boot, it is unlikely to become good now. */
758279be68bSAndriy Gapon 	if (tsc_timecounter.tc_quality < 0)
759279be68bSAndriy Gapon 		return;
760279be68bSAndriy Gapon 	/* Nothing to do with UP. */
761279be68bSAndriy Gapon 	if (mp_ncpus < 2)
762279be68bSAndriy Gapon 		return;
763279be68bSAndriy Gapon 
764279be68bSAndriy Gapon 	/*
765279be68bSAndriy Gapon 	 * If TSC was good, a single synchronization should be enough,
766279be68bSAndriy Gapon 	 * but honour smp_tsc_adjust if it's set.
767279be68bSAndriy Gapon 	 */
768279be68bSAndriy Gapon 	quality = test_tsc(MAX(smp_tsc_adjust, 1));
769279be68bSAndriy Gapon 	if (quality != tsc_timecounter.tc_quality) {
770279be68bSAndriy Gapon 		printf("TSC timecounter quality changed: %d -> %d\n",
771279be68bSAndriy Gapon 		    tsc_timecounter.tc_quality, quality);
772279be68bSAndriy Gapon 		tsc_timecounter.tc_quality = quality;
773279be68bSAndriy Gapon 	}
774ba79ab82SAndriy Gapon #endif /* SMP */
775279be68bSAndriy Gapon }
776279be68bSAndriy Gapon 
777dd7d207dSJung-uk Kim /*
778dd7d207dSJung-uk Kim  * When cpufreq levels change, find out about the (new) max frequency.  We
779dd7d207dSJung-uk Kim  * use this to update CPU accounting in case it got a lower estimate at boot.
780dd7d207dSJung-uk Kim  */
781dd7d207dSJung-uk Kim static void
782dd7d207dSJung-uk Kim tsc_levels_changed(void *arg, int unit)
783dd7d207dSJung-uk Kim {
784dd7d207dSJung-uk Kim 	device_t cf_dev;
785dd7d207dSJung-uk Kim 	struct cf_level *levels;
786dd7d207dSJung-uk Kim 	int count, error;
787dd7d207dSJung-uk Kim 	uint64_t max_freq;
788dd7d207dSJung-uk Kim 
789dd7d207dSJung-uk Kim 	/* Only use values from the first CPU, assuming all are equal. */
790dd7d207dSJung-uk Kim 	if (unit != 0)
791dd7d207dSJung-uk Kim 		return;
792dd7d207dSJung-uk Kim 
793dd7d207dSJung-uk Kim 	/* Find the appropriate cpufreq device instance. */
794dd7d207dSJung-uk Kim 	cf_dev = devclass_get_device(devclass_find("cpufreq"), unit);
795dd7d207dSJung-uk Kim 	if (cf_dev == NULL) {
796dd7d207dSJung-uk Kim 		printf("tsc_levels_changed() called but no cpufreq device?\n");
797dd7d207dSJung-uk Kim 		return;
798dd7d207dSJung-uk Kim 	}
799dd7d207dSJung-uk Kim 
800dd7d207dSJung-uk Kim 	/* Get settings from the device and find the max frequency. */
801dd7d207dSJung-uk Kim 	count = 64;
802dd7d207dSJung-uk Kim 	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
803dd7d207dSJung-uk Kim 	if (levels == NULL)
804dd7d207dSJung-uk Kim 		return;
805dd7d207dSJung-uk Kim 	error = CPUFREQ_LEVELS(cf_dev, levels, &count);
806dd7d207dSJung-uk Kim 	if (error == 0 && count != 0) {
807dd7d207dSJung-uk Kim 		max_freq = (uint64_t)levels[0].total_set.freq * 1000000;
808dd7d207dSJung-uk Kim 		set_cputicker(rdtsc, max_freq, 1);
809dd7d207dSJung-uk Kim 	} else
810dd7d207dSJung-uk Kim 		printf("tsc_levels_changed: no max freq found\n");
811dd7d207dSJung-uk Kim 	free(levels, M_TEMP);
812dd7d207dSJung-uk Kim }
813dd7d207dSJung-uk Kim 
814dd7d207dSJung-uk Kim /*
815dd7d207dSJung-uk Kim  * If the TSC timecounter is in use, veto the pending change.  It may be
816dd7d207dSJung-uk Kim  * possible in the future to handle a dynamically-changing timecounter rate.
817dd7d207dSJung-uk Kim  */
818dd7d207dSJung-uk Kim static void
819dd7d207dSJung-uk Kim tsc_freq_changing(void *arg, const struct cf_level *level, int *status)
820dd7d207dSJung-uk Kim {
821dd7d207dSJung-uk Kim 
822dd7d207dSJung-uk Kim 	if (*status != 0 || timecounter != &tsc_timecounter)
823dd7d207dSJung-uk Kim 		return;
824dd7d207dSJung-uk Kim 
825dd7d207dSJung-uk Kim 	printf("timecounter TSC must not be in use when "
826dd7d207dSJung-uk Kim 	    "changing frequencies; change denied\n");
827dd7d207dSJung-uk Kim 	*status = EBUSY;
828dd7d207dSJung-uk Kim }
829dd7d207dSJung-uk Kim 
830dd7d207dSJung-uk Kim /* Update TSC freq with the value indicated by the caller. */
831dd7d207dSJung-uk Kim static void
832dd7d207dSJung-uk Kim tsc_freq_changed(void *arg, const struct cf_level *level, int status)
833dd7d207dSJung-uk Kim {
8343453537fSJung-uk Kim 	uint64_t freq;
835dd7d207dSJung-uk Kim 
836dd7d207dSJung-uk Kim 	/* If there was an error during the transition, don't do anything. */
83779422085SJung-uk Kim 	if (tsc_disabled || status != 0)
838dd7d207dSJung-uk Kim 		return;
839dd7d207dSJung-uk Kim 
840dd7d207dSJung-uk Kim 	/* Total setting for this level gives the new frequency in MHz. */
8413453537fSJung-uk Kim 	freq = (uint64_t)level->total_set.freq * 1000000;
84222875f88SMark Johnston 	tsc_update_freq(freq);
843dd7d207dSJung-uk Kim }
844dd7d207dSJung-uk Kim 
845dd7d207dSJung-uk Kim static int
846dd7d207dSJung-uk Kim sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
847dd7d207dSJung-uk Kim {
848dd7d207dSJung-uk Kim 	int error;
849dd7d207dSJung-uk Kim 	uint64_t freq;
850dd7d207dSJung-uk Kim 
8513453537fSJung-uk Kim 	freq = atomic_load_acq_64(&tsc_freq);
8523453537fSJung-uk Kim 	if (freq == 0)
853dd7d207dSJung-uk Kim 		return (EOPNOTSUPP);
854cbc134adSMatthew D Fleming 	error = sysctl_handle_64(oidp, &freq, 0, req);
85522875f88SMark Johnston 	if (error == 0 && req->newptr != NULL)
85622875f88SMark Johnston 		tsc_update_freq(freq);
857dd7d207dSJung-uk Kim 	return (error);
858dd7d207dSJung-uk Kim }
8597029da5cSPawel Biernacki SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq,
8601d6fb900SAlexander Motin     CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
8617029da5cSPawel Biernacki     0, 0, sysctl_machdep_tsc_freq, "QU",
8627029da5cSPawel Biernacki     "Time Stamp Counter frequency");
863dd7d207dSJung-uk Kim 
864727c7b2dSJung-uk Kim static u_int
86595f2f098SJung-uk Kim tsc_get_timecount(struct timecounter *tc __unused)
866dd7d207dSJung-uk Kim {
867727c7b2dSJung-uk Kim 
868727c7b2dSJung-uk Kim 	return (rdtsc32());
869dd7d207dSJung-uk Kim }
87095f2f098SJung-uk Kim 
8719e680e40SKonstantin Belousov static u_int
8729e680e40SKonstantin Belousov tscp_get_timecount(struct timecounter *tc __unused)
8739e680e40SKonstantin Belousov {
8749e680e40SKonstantin Belousov 
8759e680e40SKonstantin Belousov 	return (rdtscp32());
8769e680e40SKonstantin Belousov }
8779e680e40SKonstantin Belousov 
878814124c3SKonstantin Belousov static inline u_int
879bc8e4ad2SJung-uk Kim tsc_get_timecount_low(struct timecounter *tc)
88095f2f098SJung-uk Kim {
8815df88f46SJung-uk Kim 	uint32_t rv;
88295f2f098SJung-uk Kim 
8835df88f46SJung-uk Kim 	__asm __volatile("rdtsc; shrd %%cl, %%edx, %0"
8845df88f46SJung-uk Kim 	    : "=a" (rv) : "c" ((int)(intptr_t)tc->tc_priv) : "edx");
8855df88f46SJung-uk Kim 	return (rv);
88695f2f098SJung-uk Kim }
887aea81038SKonstantin Belousov 
888814124c3SKonstantin Belousov static u_int
8899e680e40SKonstantin Belousov tscp_get_timecount_low(struct timecounter *tc)
8909e680e40SKonstantin Belousov {
8919e680e40SKonstantin Belousov 	uint32_t rv;
8929e680e40SKonstantin Belousov 
8939e680e40SKonstantin Belousov 	__asm __volatile("rdtscp; movl %1, %%ecx; shrd %%cl, %%edx, %0"
894a013e285SKonstantin Belousov 	    : "=&a" (rv) : "m" (tc->tc_priv) : "ecx", "edx");
8959e680e40SKonstantin Belousov 	return (rv);
8969e680e40SKonstantin Belousov }
8979e680e40SKonstantin Belousov 
8989e680e40SKonstantin Belousov static u_int
899814124c3SKonstantin Belousov tsc_get_timecount_lfence(struct timecounter *tc __unused)
900814124c3SKonstantin Belousov {
901814124c3SKonstantin Belousov 
902814124c3SKonstantin Belousov 	lfence();
903814124c3SKonstantin Belousov 	return (rdtsc32());
904814124c3SKonstantin Belousov }
905814124c3SKonstantin Belousov 
906814124c3SKonstantin Belousov static u_int
907814124c3SKonstantin Belousov tsc_get_timecount_low_lfence(struct timecounter *tc)
908814124c3SKonstantin Belousov {
909814124c3SKonstantin Belousov 
910814124c3SKonstantin Belousov 	lfence();
911814124c3SKonstantin Belousov 	return (tsc_get_timecount_low(tc));
912814124c3SKonstantin Belousov }
913814124c3SKonstantin Belousov 
914814124c3SKonstantin Belousov static u_int
915814124c3SKonstantin Belousov tsc_get_timecount_mfence(struct timecounter *tc __unused)
916814124c3SKonstantin Belousov {
917814124c3SKonstantin Belousov 
918814124c3SKonstantin Belousov 	mfence();
919814124c3SKonstantin Belousov 	return (rdtsc32());
920814124c3SKonstantin Belousov }
921814124c3SKonstantin Belousov 
922814124c3SKonstantin Belousov static u_int
923814124c3SKonstantin Belousov tsc_get_timecount_low_mfence(struct timecounter *tc)
924814124c3SKonstantin Belousov {
925814124c3SKonstantin Belousov 
926814124c3SKonstantin Belousov 	mfence();
927814124c3SKonstantin Belousov 	return (tsc_get_timecount_low(tc));
928814124c3SKonstantin Belousov }
929814124c3SKonstantin Belousov 
93016808549SKonstantin Belousov static uint32_t
93116808549SKonstantin Belousov x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th, struct timecounter *tc)
932aea81038SKonstantin Belousov {
933aea81038SKonstantin Belousov 
93416808549SKonstantin Belousov 	vdso_th->th_algo = VDSO_TH_ALGO_X86_TSC;
935d1b1b600SNeel Natu 	vdso_th->th_x86_shift = (int)(intptr_t)tc->tc_priv;
93616808549SKonstantin Belousov 	vdso_th->th_x86_hpet_idx = 0xffffffff;
937d4b2d303SAdam Fenn 	vdso_th->th_x86_pvc_last_systime = 0;
938d4b2d303SAdam Fenn 	vdso_th->th_x86_pvc_stable_mask = 0;
939aea81038SKonstantin Belousov 	bzero(vdso_th->th_res, sizeof(vdso_th->th_res));
94016808549SKonstantin Belousov 	return (1);
941aea81038SKonstantin Belousov }
942aea81038SKonstantin Belousov 
943aea81038SKonstantin Belousov #ifdef COMPAT_FREEBSD32
94416808549SKonstantin Belousov static uint32_t
94516808549SKonstantin Belousov x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
946d1b1b600SNeel Natu     struct timecounter *tc)
947aea81038SKonstantin Belousov {
948aea81038SKonstantin Belousov 
94916808549SKonstantin Belousov 	vdso_th32->th_algo = VDSO_TH_ALGO_X86_TSC;
950d1b1b600SNeel Natu 	vdso_th32->th_x86_shift = (int)(intptr_t)tc->tc_priv;
95116808549SKonstantin Belousov 	vdso_th32->th_x86_hpet_idx = 0xffffffff;
952d4b2d303SAdam Fenn 	vdso_th32->th_x86_pvc_last_systime = 0;
953d4b2d303SAdam Fenn 	vdso_th32->th_x86_pvc_stable_mask = 0;
954aea81038SKonstantin Belousov 	bzero(vdso_th32->th_res, sizeof(vdso_th32->th_res));
95516808549SKonstantin Belousov 	return (1);
956aea81038SKonstantin Belousov }
957aea81038SKonstantin Belousov #endif
958