xref: /freebsd/sys/x86/x86/tsc.c (revision c2705ceaeb09d8579661097fd358ffb5defb5624)
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>
51*c2705ceaSColin Percival #include <machine/fpu.h>
52dd7d207dSJung-uk Kim #include <machine/md_var.h>
53dd7d207dSJung-uk Kim #include <machine/specialreg.h>
5401e1933dSJohn Baldwin #include <x86/vmware.h>
5516808549SKonstantin Belousov #include <dev/acpica/acpi_hpet.h>
56ce3bf750SKonstantin Belousov #include <contrib/dev/acpica/include/acpi.h>
57dd7d207dSJung-uk Kim 
58dd7d207dSJung-uk Kim #include "cpufreq_if.h"
59dd7d207dSJung-uk Kim 
60dd7d207dSJung-uk Kim uint64_t	tsc_freq;
61dd7d207dSJung-uk Kim int		tsc_is_invariant;
62155094d7SJung-uk Kim int		tsc_perf_stat;
639cb32882SColin Percival static int	tsc_early_calib_exact;
64155094d7SJung-uk Kim 
65dd7d207dSJung-uk Kim static eventhandler_tag tsc_levels_tag, tsc_pre_tag, tsc_post_tag;
66dd7d207dSJung-uk Kim 
67dd7d207dSJung-uk Kim SYSCTL_INT(_kern_timecounter, OID_AUTO, invariant_tsc, CTLFLAG_RDTUN,
68dd7d207dSJung-uk Kim     &tsc_is_invariant, 0, "Indicates whether the TSC is P-state invariant");
69dd7d207dSJung-uk Kim 
70dd7d207dSJung-uk Kim #ifdef SMP
711472b87fSNeel Natu int	smp_tsc;
72dd7d207dSJung-uk Kim SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc, CTLFLAG_RDTUN, &smp_tsc, 0,
73dd7d207dSJung-uk Kim     "Indicates whether the TSC is safe to use in SMP mode");
74b2c63698SAlexander Motin 
75b2c63698SAlexander Motin int	smp_tsc_adjust = 0;
76b2c63698SAlexander Motin SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc_adjust, CTLFLAG_RDTUN,
77b2c63698SAlexander Motin     &smp_tsc_adjust, 0, "Try to adjust TSC on APs to match BSP");
78dd7d207dSJung-uk Kim #endif
79dd7d207dSJung-uk Kim 
80e7f1427dSKonstantin Belousov static int	tsc_shift = 1;
81e7f1427dSKonstantin Belousov SYSCTL_INT(_kern_timecounter, OID_AUTO, tsc_shift, CTLFLAG_RDTUN,
82e7f1427dSKonstantin Belousov     &tsc_shift, 0, "Shift to pre-apply for the maximum TSC frequency");
83e7f1427dSKonstantin Belousov 
8479422085SJung-uk Kim static int	tsc_disabled;
8579422085SJung-uk Kim SYSCTL_INT(_machdep, OID_AUTO, disable_tsc, CTLFLAG_RDTUN, &tsc_disabled, 0,
8679422085SJung-uk Kim     "Disable x86 Time Stamp Counter");
8779422085SJung-uk Kim 
88a4e4127fSJung-uk Kim static int	tsc_skip_calibration;
89ab23c278SKonstantin Belousov SYSCTL_INT(_machdep, OID_AUTO, disable_tsc_calibration, CTLFLAG_RDTUN,
90ab23c278SKonstantin Belousov     &tsc_skip_calibration, 0,
9122875f88SMark Johnston     "Disable early TSC frequency calibration");
92a4e4127fSJung-uk Kim 
93dd7d207dSJung-uk Kim static void tsc_freq_changed(void *arg, const struct cf_level *level,
94dd7d207dSJung-uk Kim     int status);
95dd7d207dSJung-uk Kim static void tsc_freq_changing(void *arg, const struct cf_level *level,
96dd7d207dSJung-uk Kim     int *status);
97826fc3ccSKonstantin Belousov static u_int tsc_get_timecount(struct timecounter *tc);
98826fc3ccSKonstantin Belousov static inline u_int tsc_get_timecount_low(struct timecounter *tc);
99826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_lfence(struct timecounter *tc);
100826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_low_lfence(struct timecounter *tc);
101826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_mfence(struct timecounter *tc);
102826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_low_mfence(struct timecounter *tc);
1039e680e40SKonstantin Belousov static u_int tscp_get_timecount(struct timecounter *tc);
1049e680e40SKonstantin Belousov static u_int tscp_get_timecount_low(struct timecounter *tc);
105dd7d207dSJung-uk Kim static void tsc_levels_changed(void *arg, int unit);
10616808549SKonstantin Belousov static uint32_t x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th,
10716808549SKonstantin Belousov     struct timecounter *tc);
10816808549SKonstantin Belousov #ifdef COMPAT_FREEBSD32
10916808549SKonstantin Belousov static uint32_t x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
11016808549SKonstantin Belousov     struct timecounter *tc);
11116808549SKonstantin Belousov #endif
112dd7d207dSJung-uk Kim 
113dd7d207dSJung-uk Kim static struct timecounter tsc_timecounter = {
11416808549SKonstantin Belousov 	.tc_get_timecount =		tsc_get_timecount,
11516808549SKonstantin Belousov 	.tc_counter_mask =		~0u,
11616808549SKonstantin Belousov 	.tc_name =			"TSC",
11716808549SKonstantin Belousov 	.tc_quality =			800,	/* adjusted in code */
11816808549SKonstantin Belousov 	.tc_fill_vdso_timehands = 	x86_tsc_vdso_timehands,
11916808549SKonstantin Belousov #ifdef COMPAT_FREEBSD32
12016808549SKonstantin Belousov 	.tc_fill_vdso_timehands32 = 	x86_tsc_vdso_timehands32,
12116808549SKonstantin Belousov #endif
122dd7d207dSJung-uk Kim };
123dd7d207dSJung-uk Kim 
12401e1933dSJohn Baldwin static void
1255da5812bSJung-uk Kim tsc_freq_vmware(void)
1265da5812bSJung-uk Kim {
1275da5812bSJung-uk Kim 	u_int regs[4];
1285da5812bSJung-uk Kim 
1295da5812bSJung-uk Kim 	if (hv_high >= 0x40000010) {
1305da5812bSJung-uk Kim 		do_cpuid(0x40000010, regs);
1315da5812bSJung-uk Kim 		tsc_freq = regs[0] * 1000;
1325da5812bSJung-uk Kim 	} else {
1335da5812bSJung-uk Kim 		vmware_hvcall(VMW_HVCMD_GETHZ, regs);
1345da5812bSJung-uk Kim 		if (regs[1] != UINT_MAX)
1355da5812bSJung-uk Kim 			tsc_freq = regs[0] | ((uint64_t)regs[1] << 32);
1365da5812bSJung-uk Kim 	}
1375da5812bSJung-uk Kim 	tsc_is_invariant = 1;
1389cb32882SColin Percival 	tsc_early_calib_exact = 1;
1395da5812bSJung-uk Kim }
1405da5812bSJung-uk Kim 
141506a906cSKonstantin Belousov /*
14222875f88SMark Johnston  * Calculate TSC frequency using information from the CPUID leaf 0x15 'Time
14322875f88SMark Johnston  * Stamp Counter and Nominal Core Crystal Clock'.  If leaf 0x15 is not
14422875f88SMark Johnston  * functional, as it is on Skylake/Kabylake, try 0x16 'Processor Frequency
14522875f88SMark Johnston  * Information'.  Leaf 0x16 is described in the SDM as informational only, but
14622875f88SMark Johnston  * we can use this value until late calibration is complete.
147506a906cSKonstantin Belousov  */
148506a906cSKonstantin Belousov static bool
149bd8a359fSKonstantin Belousov tsc_freq_cpuid(uint64_t *res)
150506a906cSKonstantin Belousov {
151506a906cSKonstantin Belousov 	u_int regs[4];
152506a906cSKonstantin Belousov 
153506a906cSKonstantin Belousov 	if (cpu_high < 0x15)
154506a906cSKonstantin Belousov 		return (false);
155506a906cSKonstantin Belousov 	do_cpuid(0x15, regs);
156a9d0e007SKonstantin Belousov 	if (regs[0] != 0 && regs[1] != 0 && regs[2] != 0) {
157bd8a359fSKonstantin Belousov 		*res = (uint64_t)regs[2] * regs[1] / regs[0];
158506a906cSKonstantin Belousov 		return (true);
159506a906cSKonstantin Belousov 	}
160506a906cSKonstantin Belousov 
161a9d0e007SKonstantin Belousov 	if (cpu_high < 0x16)
162a9d0e007SKonstantin Belousov 		return (false);
163a9d0e007SKonstantin Belousov 	do_cpuid(0x16, regs);
164a9d0e007SKonstantin Belousov 	if (regs[0] != 0) {
165bd8a359fSKonstantin Belousov 		*res = (uint64_t)regs[0] * 1000000;
166a9d0e007SKonstantin Belousov 		return (true);
167a9d0e007SKonstantin Belousov 	}
168a9d0e007SKonstantin Belousov 
169a9d0e007SKonstantin Belousov 	return (false);
170a9d0e007SKonstantin Belousov }
171a9d0e007SKonstantin Belousov 
17222875f88SMark Johnston static bool
17322875f88SMark Johnston tsc_freq_intel_brand(uint64_t *res)
174dd7d207dSJung-uk Kim {
175a4e4127fSJung-uk Kim 	char brand[48];
176a4e4127fSJung-uk Kim 	u_int regs[4];
177a4e4127fSJung-uk Kim 	uint64_t freq;
178a4e4127fSJung-uk Kim 	char *p;
179a4e4127fSJung-uk Kim 	u_int i;
180dd7d207dSJung-uk Kim 
181a4e4127fSJung-uk Kim 	/*
182a4e4127fSJung-uk Kim 	 * Intel Processor Identification and the CPUID Instruction
183a4e4127fSJung-uk Kim 	 * Application Note 485.
184a4e4127fSJung-uk Kim 	 * http://www.intel.com/assets/pdf/appnote/241618.pdf
185a4e4127fSJung-uk Kim 	 */
186a4e4127fSJung-uk Kim 	if (cpu_exthigh >= 0x80000004) {
187a4e4127fSJung-uk Kim 		p = brand;
188a4e4127fSJung-uk Kim 		for (i = 0x80000002; i < 0x80000005; i++) {
189a4e4127fSJung-uk Kim 			do_cpuid(i, regs);
190a4e4127fSJung-uk Kim 			memcpy(p, regs, sizeof(regs));
191a4e4127fSJung-uk Kim 			p += sizeof(regs);
192a4e4127fSJung-uk Kim 		}
193a4e4127fSJung-uk Kim 		p = NULL;
194a4e4127fSJung-uk Kim 		for (i = 0; i < sizeof(brand) - 1; i++)
195a4e4127fSJung-uk Kim 			if (brand[i] == 'H' && brand[i + 1] == 'z')
196a4e4127fSJung-uk Kim 				p = brand + i;
197a4e4127fSJung-uk Kim 		if (p != NULL) {
198a4e4127fSJung-uk Kim 			p -= 5;
199a4e4127fSJung-uk Kim 			switch (p[4]) {
200a4e4127fSJung-uk Kim 			case 'M':
201a4e4127fSJung-uk Kim 				i = 1;
202a4e4127fSJung-uk Kim 				break;
203a4e4127fSJung-uk Kim 			case 'G':
204a4e4127fSJung-uk Kim 				i = 1000;
205a4e4127fSJung-uk Kim 				break;
206a4e4127fSJung-uk Kim 			case 'T':
207a4e4127fSJung-uk Kim 				i = 1000000;
208a4e4127fSJung-uk Kim 				break;
209a4e4127fSJung-uk Kim 			default:
21022875f88SMark Johnston 				return (false);
211a4e4127fSJung-uk Kim 			}
212a4e4127fSJung-uk Kim #define	C2D(c)	((c) - '0')
213a4e4127fSJung-uk Kim 			if (p[1] == '.') {
214a4e4127fSJung-uk Kim 				freq = C2D(p[0]) * 1000;
215a4e4127fSJung-uk Kim 				freq += C2D(p[2]) * 100;
216a4e4127fSJung-uk Kim 				freq += C2D(p[3]) * 10;
217a4e4127fSJung-uk Kim 				freq *= i * 1000;
218a4e4127fSJung-uk Kim 			} else {
219a4e4127fSJung-uk Kim 				freq = C2D(p[0]) * 1000;
220a4e4127fSJung-uk Kim 				freq += C2D(p[1]) * 100;
221a4e4127fSJung-uk Kim 				freq += C2D(p[2]) * 10;
222a4e4127fSJung-uk Kim 				freq += C2D(p[3]);
223a4e4127fSJung-uk Kim 				freq *= i * 1000000;
224a4e4127fSJung-uk Kim 			}
225a4e4127fSJung-uk Kim #undef C2D
22622875f88SMark Johnston 			*res = freq;
22722875f88SMark Johnston 			return (true);
228a4e4127fSJung-uk Kim 		}
229a4e4127fSJung-uk Kim 	}
23022875f88SMark Johnston 	return (false);
23122875f88SMark Johnston }
23222875f88SMark Johnston 
23322875f88SMark Johnston static void
23422875f88SMark Johnston tsc_freq_8254(uint64_t *res)
23522875f88SMark Johnston {
23622875f88SMark Johnston 	uint64_t tsc1, tsc2;
23722875f88SMark Johnston 	int64_t overhead;
23822875f88SMark Johnston 	int count, i;
23922875f88SMark Johnston 
24022875f88SMark Johnston 	overhead = 0;
24122875f88SMark Johnston 	for (i = 0, count = 8; i < count; i++) {
24222875f88SMark Johnston 		tsc1 = rdtsc_ordered();
24322875f88SMark Johnston 		DELAY(0);
24422875f88SMark Johnston 		tsc2 = rdtsc_ordered();
24522875f88SMark Johnston 		if (i > 0)
24622875f88SMark Johnston 			overhead += tsc2 - tsc1;
24722875f88SMark Johnston 	}
24822875f88SMark Johnston 	overhead /= count;
24922875f88SMark Johnston 
25022875f88SMark Johnston 	tsc1 = rdtsc_ordered();
25122875f88SMark Johnston 	DELAY(100000);
25222875f88SMark Johnston 	tsc2 = rdtsc_ordered();
25322875f88SMark Johnston 	tsc_freq = (tsc2 - tsc1 - overhead) * 10;
254a4e4127fSJung-uk Kim }
255dd7d207dSJung-uk Kim 
256a4e4127fSJung-uk Kim static void
257a4e4127fSJung-uk Kim probe_tsc_freq(void)
258a4e4127fSJung-uk Kim {
259bb044eafSConrad Meyer 	if (cpu_power_ecx & CPUID_PERF_STAT) {
2605da5812bSJung-uk Kim 		/*
261bb044eafSConrad Meyer 		 * XXX Some emulators expose host CPUID without actual support
262bb044eafSConrad Meyer 		 * for these MSRs.  We must test whether they really work.
2635da5812bSJung-uk Kim 		 */
2645da5812bSJung-uk Kim 		wrmsr(MSR_MPERF, 0);
2655da5812bSJung-uk Kim 		wrmsr(MSR_APERF, 0);
2665da5812bSJung-uk Kim 		DELAY(10);
2675da5812bSJung-uk Kim 		if (rdmsr(MSR_MPERF) > 0 && rdmsr(MSR_APERF) > 0)
2685da5812bSJung-uk Kim 			tsc_perf_stat = 1;
2695da5812bSJung-uk Kim 	}
2705da5812bSJung-uk Kim 
27101e1933dSJohn Baldwin 	if (vm_guest == VM_GUEST_VMWARE) {
27201e1933dSJohn Baldwin 		tsc_freq_vmware();
2735da5812bSJung-uk Kim 		return;
27401e1933dSJohn Baldwin 	}
2755da5812bSJung-uk Kim 
276dd7d207dSJung-uk Kim 	switch (cpu_vendor_id) {
277dd7d207dSJung-uk Kim 	case CPU_VENDOR_AMD:
2782ee49facSKonstantin Belousov 	case CPU_VENDOR_HYGON:
279a106a27cSJung-uk Kim 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
280a106a27cSJung-uk Kim 		    (vm_guest == VM_GUEST_NO &&
281a106a27cSJung-uk Kim 		    CPUID_TO_FAMILY(cpu_id) >= 0x10))
282dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
283814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
284814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
285814124c3SKonstantin Belousov 			    tsc_get_timecount_mfence;
286814124c3SKonstantin Belousov 		}
287dd7d207dSJung-uk Kim 		break;
288dd7d207dSJung-uk Kim 	case CPU_VENDOR_INTEL:
289a106a27cSJung-uk Kim 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
290a106a27cSJung-uk Kim 		    (vm_guest == VM_GUEST_NO &&
291a106a27cSJung-uk Kim 		    ((CPUID_TO_FAMILY(cpu_id) == 0x6 &&
292dd7d207dSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0xe) ||
293dd7d207dSJung-uk Kim 		    (CPUID_TO_FAMILY(cpu_id) == 0xf &&
294a106a27cSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0x3))))
295dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
296814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
297814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
298814124c3SKonstantin Belousov 			    tsc_get_timecount_lfence;
299814124c3SKonstantin Belousov 		}
300dd7d207dSJung-uk Kim 		break;
301dd7d207dSJung-uk Kim 	case CPU_VENDOR_CENTAUR:
302a106a27cSJung-uk Kim 		if (vm_guest == VM_GUEST_NO &&
303a106a27cSJung-uk Kim 		    CPUID_TO_FAMILY(cpu_id) == 0x6 &&
304dd7d207dSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0xf &&
305dd7d207dSJung-uk Kim 		    (rdmsr(0x1203) & 0x100000000ULL) == 0)
306dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
307814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
308814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
309814124c3SKonstantin Belousov 			    tsc_get_timecount_lfence;
310814124c3SKonstantin Belousov 		}
311dd7d207dSJung-uk Kim 		break;
312dd7d207dSJung-uk Kim 	}
313dd7d207dSJung-uk Kim 
31422875f88SMark Johnston 	if (tsc_freq_cpuid(&tsc_freq)) {
315bd8a359fSKonstantin Belousov 		/*
31622875f88SMark Johnston 		 * If possible, use the value obtained from CPUID as the initial
31722875f88SMark Johnston 		 * frequency.  This will be refined later during boot but is
31822875f88SMark Johnston 		 * good enough for now.  The 8254 PIT is not functional on some
31922875f88SMark Johnston 		 * newer platforms anyway, so don't delay our boot for what
32022875f88SMark Johnston 		 * might be a garbage result.  Late calibration is required if
32122875f88SMark Johnston 		 * the initial frequency was obtained from CPUID.16H, as the
32222875f88SMark Johnston 		 * derived value may be off by as much as 1%.
323bd8a359fSKonstantin Belousov 		 */
324a4e4127fSJung-uk Kim 		if (bootverbose)
32522875f88SMark Johnston 			printf("Early TSC frequency %juHz derived from CPUID\n",
32622875f88SMark Johnston 			    (uintmax_t)tsc_freq);
32722875f88SMark Johnston 	} else if (tsc_skip_calibration) {
32822875f88SMark Johnston 		/*
32922875f88SMark Johnston 		 * Try to parse the brand string to obtain the nominal TSC
33022875f88SMark Johnston 		 * frequency.
33122875f88SMark Johnston 		 */
33222875f88SMark Johnston 		if (cpu_vendor_id == CPU_VENDOR_INTEL &&
33322875f88SMark Johnston 		    tsc_freq_intel_brand(&tsc_freq)) {
33422875f88SMark Johnston 			if (bootverbose)
33522875f88SMark Johnston 				printf(
33622875f88SMark Johnston 		    "Early TSC frequency %juHz derived from brand string\n",
33722875f88SMark Johnston 				    (uintmax_t)tsc_freq);
33822875f88SMark Johnston 		} else {
33922875f88SMark Johnston 			tsc_disabled = 1;
34022875f88SMark Johnston 		}
34122875f88SMark Johnston 	} else {
34222875f88SMark Johnston 		/*
34322875f88SMark Johnston 		 * Calibrate against the 8254 PIT.  This estimate will be
34422875f88SMark Johnston 		 * refined later in tsc_calib().
34522875f88SMark Johnston 		 */
34622875f88SMark Johnston 		tsc_freq_8254(&tsc_freq);
34722875f88SMark Johnston 		if (bootverbose)
34822875f88SMark Johnston 			printf(
34922875f88SMark Johnston 		    "Early TSC frequency %juHz calibrated from 8254 PIT\n",
35022875f88SMark Johnston 			    (uintmax_t)tsc_freq);
35122875f88SMark Johnston 	}
352a4e4127fSJung-uk Kim }
353a4e4127fSJung-uk Kim 
354a4e4127fSJung-uk Kim void
355a4e4127fSJung-uk Kim init_TSC(void)
356a4e4127fSJung-uk Kim {
357a4e4127fSJung-uk Kim 
358a4e4127fSJung-uk Kim 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
359a4e4127fSJung-uk Kim 		return;
360a4e4127fSJung-uk Kim 
361fe760cfaSJohn Baldwin #ifdef __i386__
362fe760cfaSJohn Baldwin 	/* The TSC is known to be broken on certain CPUs. */
363fe760cfaSJohn Baldwin 	switch (cpu_vendor_id) {
364fe760cfaSJohn Baldwin 	case CPU_VENDOR_AMD:
365fe760cfaSJohn Baldwin 		switch (cpu_id & 0xFF0) {
366fe760cfaSJohn Baldwin 		case 0x500:
367fe760cfaSJohn Baldwin 			/* K5 Model 0 */
368fe760cfaSJohn Baldwin 			return;
369fe760cfaSJohn Baldwin 		}
370fe760cfaSJohn Baldwin 		break;
371fe760cfaSJohn Baldwin 	case CPU_VENDOR_CENTAUR:
372fe760cfaSJohn Baldwin 		switch (cpu_id & 0xff0) {
373fe760cfaSJohn Baldwin 		case 0x540:
374fe760cfaSJohn Baldwin 			/*
375fe760cfaSJohn Baldwin 			 * http://www.centtech.com/c6_data_sheet.pdf
376fe760cfaSJohn Baldwin 			 *
377fe760cfaSJohn Baldwin 			 * I-12 RDTSC may return incoherent values in EDX:EAX
378fe760cfaSJohn Baldwin 			 * I-13 RDTSC hangs when certain event counters are used
379fe760cfaSJohn Baldwin 			 */
380fe760cfaSJohn Baldwin 			return;
381fe760cfaSJohn Baldwin 		}
382fe760cfaSJohn Baldwin 		break;
383fe760cfaSJohn Baldwin 	case CPU_VENDOR_NSC:
384fe760cfaSJohn Baldwin 		switch (cpu_id & 0xff0) {
385fe760cfaSJohn Baldwin 		case 0x540:
386fe760cfaSJohn Baldwin 			if ((cpu_id & CPUID_STEPPING) == 0)
387fe760cfaSJohn Baldwin 				return;
388fe760cfaSJohn Baldwin 			break;
389fe760cfaSJohn Baldwin 		}
390fe760cfaSJohn Baldwin 		break;
391fe760cfaSJohn Baldwin 	}
392fe760cfaSJohn Baldwin #endif
393fe760cfaSJohn Baldwin 
394a4e4127fSJung-uk Kim 	probe_tsc_freq();
395a4e4127fSJung-uk Kim 
396dd7d207dSJung-uk Kim 	/*
397dd7d207dSJung-uk Kim 	 * Inform CPU accounting about our boot-time clock rate.  This will
398dd7d207dSJung-uk Kim 	 * be updated if someone loads a cpufreq driver after boot that
399dd7d207dSJung-uk Kim 	 * discovers a new max frequency.
40022875f88SMark Johnston 	 *
40122875f88SMark Johnston 	 * The frequency may also be updated after late calibration is complete;
40222875f88SMark Johnston 	 * however, we register the TSC as the ticker now to avoid switching
40322875f88SMark Johnston 	 * counters after much of the kernel has already booted and potentially
40422875f88SMark Johnston 	 * sampled the CPU clock.
405dd7d207dSJung-uk Kim 	 */
406a4e4127fSJung-uk Kim 	if (tsc_freq != 0)
4075ac44f72SJung-uk Kim 		set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
408dd7d207dSJung-uk Kim 
409dd7d207dSJung-uk Kim 	if (tsc_is_invariant)
410dd7d207dSJung-uk Kim 		return;
411dd7d207dSJung-uk Kim 
412dd7d207dSJung-uk Kim 	/* Register to find out about changes in CPU frequency. */
413dd7d207dSJung-uk Kim 	tsc_pre_tag = EVENTHANDLER_REGISTER(cpufreq_pre_change,
414dd7d207dSJung-uk Kim 	    tsc_freq_changing, NULL, EVENTHANDLER_PRI_FIRST);
415dd7d207dSJung-uk Kim 	tsc_post_tag = EVENTHANDLER_REGISTER(cpufreq_post_change,
416dd7d207dSJung-uk Kim 	    tsc_freq_changed, NULL, EVENTHANDLER_PRI_FIRST);
417dd7d207dSJung-uk Kim 	tsc_levels_tag = EVENTHANDLER_REGISTER(cpufreq_levels_changed,
418dd7d207dSJung-uk Kim 	    tsc_levels_changed, NULL, EVENTHANDLER_PRI_ANY);
419dd7d207dSJung-uk Kim }
420dd7d207dSJung-uk Kim 
42165e7d70bSJung-uk Kim #ifdef SMP
42265e7d70bSJung-uk Kim 
423814124c3SKonstantin Belousov /*
424814124c3SKonstantin Belousov  * RDTSC is not a serializing instruction, and does not drain
425814124c3SKonstantin Belousov  * instruction stream, so we need to drain the stream before executing
426814124c3SKonstantin Belousov  * it.  It could be fixed by use of RDTSCP, except the instruction is
427814124c3SKonstantin Belousov  * not available everywhere.
428814124c3SKonstantin Belousov  *
429814124c3SKonstantin Belousov  * Use CPUID for draining in the boot-time SMP constistency test.  The
430814124c3SKonstantin Belousov  * timecounters use MFENCE for AMD CPUs, and LFENCE for others (Intel
431814124c3SKonstantin Belousov  * and VIA) when SSE2 is present, and nothing on older machines which
432814124c3SKonstantin Belousov  * also do not issue RDTSC prematurely.  There, testing for SSE2 and
433e1a18e46SKonstantin Belousov  * vendor is too cumbersome, and we learn about TSC presence from CPUID.
434814124c3SKonstantin Belousov  *
435814124c3SKonstantin Belousov  * Do not use do_cpuid(), since we do not need CPUID results, which
436814124c3SKonstantin Belousov  * have to be written into memory with do_cpuid().
437814124c3SKonstantin Belousov  */
43865e7d70bSJung-uk Kim #define	TSC_READ(x)							\
43965e7d70bSJung-uk Kim static void								\
44065e7d70bSJung-uk Kim tsc_read_##x(void *arg)							\
44165e7d70bSJung-uk Kim {									\
4427bfcb3bbSJim Harris 	uint64_t *tsc = arg;						\
44365e7d70bSJung-uk Kim 	u_int cpu = PCPU_GET(cpuid);					\
44465e7d70bSJung-uk Kim 									\
445814124c3SKonstantin Belousov 	__asm __volatile("cpuid" : : : "eax", "ebx", "ecx", "edx");	\
4467bfcb3bbSJim Harris 	tsc[cpu * 3 + x] = rdtsc();					\
44765e7d70bSJung-uk Kim }
44865e7d70bSJung-uk Kim TSC_READ(0)
44965e7d70bSJung-uk Kim TSC_READ(1)
45065e7d70bSJung-uk Kim TSC_READ(2)
45165e7d70bSJung-uk Kim #undef TSC_READ
45265e7d70bSJung-uk Kim 
45365e7d70bSJung-uk Kim #define	N	1000
45465e7d70bSJung-uk Kim 
45565e7d70bSJung-uk Kim static void
45665e7d70bSJung-uk Kim comp_smp_tsc(void *arg)
45765e7d70bSJung-uk Kim {
4587bfcb3bbSJim Harris 	uint64_t *tsc;
4597bfcb3bbSJim Harris 	int64_t d1, d2;
46065e7d70bSJung-uk Kim 	u_int cpu = PCPU_GET(cpuid);
46165e7d70bSJung-uk Kim 	u_int i, j, size;
46265e7d70bSJung-uk Kim 
46365e7d70bSJung-uk Kim 	size = (mp_maxid + 1) * 3;
46465e7d70bSJung-uk Kim 	for (i = 0, tsc = arg; i < N; i++, tsc += size)
46565e7d70bSJung-uk Kim 		CPU_FOREACH(j) {
46665e7d70bSJung-uk Kim 			if (j == cpu)
46765e7d70bSJung-uk Kim 				continue;
46865e7d70bSJung-uk Kim 			d1 = tsc[cpu * 3 + 1] - tsc[j * 3];
46965e7d70bSJung-uk Kim 			d2 = tsc[cpu * 3 + 2] - tsc[j * 3 + 1];
47065e7d70bSJung-uk Kim 			if (d1 <= 0 || d2 <= 0) {
47165e7d70bSJung-uk Kim 				smp_tsc = 0;
47265e7d70bSJung-uk Kim 				return;
47365e7d70bSJung-uk Kim 			}
47465e7d70bSJung-uk Kim 		}
47565e7d70bSJung-uk Kim }
47665e7d70bSJung-uk Kim 
477b2c63698SAlexander Motin static void
478b2c63698SAlexander Motin adj_smp_tsc(void *arg)
479b2c63698SAlexander Motin {
480b2c63698SAlexander Motin 	uint64_t *tsc;
481b2c63698SAlexander Motin 	int64_t d, min, max;
482b2c63698SAlexander Motin 	u_int cpu = PCPU_GET(cpuid);
483b2c63698SAlexander Motin 	u_int first, i, size;
484b2c63698SAlexander Motin 
485b2c63698SAlexander Motin 	first = CPU_FIRST();
486b2c63698SAlexander Motin 	if (cpu == first)
487b2c63698SAlexander Motin 		return;
488b2c63698SAlexander Motin 	min = INT64_MIN;
489b2c63698SAlexander Motin 	max = INT64_MAX;
490b2c63698SAlexander Motin 	size = (mp_maxid + 1) * 3;
491b2c63698SAlexander Motin 	for (i = 0, tsc = arg; i < N; i++, tsc += size) {
492b2c63698SAlexander Motin 		d = tsc[first * 3] - tsc[cpu * 3 + 1];
493b2c63698SAlexander Motin 		if (d > min)
494b2c63698SAlexander Motin 			min = d;
495b2c63698SAlexander Motin 		d = tsc[first * 3 + 1] - tsc[cpu * 3 + 2];
496b2c63698SAlexander Motin 		if (d > min)
497b2c63698SAlexander Motin 			min = d;
498b2c63698SAlexander Motin 		d = tsc[first * 3 + 1] - tsc[cpu * 3];
499b2c63698SAlexander Motin 		if (d < max)
500b2c63698SAlexander Motin 			max = d;
501b2c63698SAlexander Motin 		d = tsc[first * 3 + 2] - tsc[cpu * 3 + 1];
502b2c63698SAlexander Motin 		if (d < max)
503b2c63698SAlexander Motin 			max = d;
504b2c63698SAlexander Motin 	}
505b2c63698SAlexander Motin 	if (min > max)
506b2c63698SAlexander Motin 		return;
507b2c63698SAlexander Motin 	d = min / 2 + max / 2;
508b2c63698SAlexander Motin 	__asm __volatile (
509b2c63698SAlexander Motin 		"movl $0x10, %%ecx\n\t"
510b2c63698SAlexander Motin 		"rdmsr\n\t"
511b2c63698SAlexander Motin 		"addl %%edi, %%eax\n\t"
512b2c63698SAlexander Motin 		"adcl %%esi, %%edx\n\t"
513b2c63698SAlexander Motin 		"wrmsr\n"
514b2c63698SAlexander Motin 		: /* No output */
515b2c63698SAlexander Motin 		: "D" ((uint32_t)d), "S" ((uint32_t)(d >> 32))
516b2c63698SAlexander Motin 		: "ax", "cx", "dx", "cc"
517b2c63698SAlexander Motin 	);
518b2c63698SAlexander Motin }
519b2c63698SAlexander Motin 
52065e7d70bSJung-uk Kim static int
521279be68bSAndriy Gapon test_tsc(int adj_max_count)
52265e7d70bSJung-uk Kim {
5237bfcb3bbSJim Harris 	uint64_t *data, *tsc;
524b2c63698SAlexander Motin 	u_int i, size, adj;
52565e7d70bSJung-uk Kim 
52684eaf2ccSKonstantin Belousov 	if ((!smp_tsc && !tsc_is_invariant))
52765e7d70bSJung-uk Kim 		return (-100);
5288cc15b0dSKyle Evans 	/*
5298cc15b0dSKyle Evans 	 * Misbehavior of TSC under VirtualBox has been observed.  In
5308cc15b0dSKyle Evans 	 * particular, threads doing small (~1 second) sleeps may miss their
5318cc15b0dSKyle Evans 	 * wakeup and hang around in sleep state, causing hangs on shutdown.
5328cc15b0dSKyle Evans 	 */
5338cc15b0dSKyle Evans 	if (vm_guest == VM_GUEST_VBOX)
5348cc15b0dSKyle Evans 		return (0);
5358cc15b0dSKyle Evans 
536cd165c8bSColin Percival 	TSENTER();
53765e7d70bSJung-uk Kim 	size = (mp_maxid + 1) * 3;
53865e7d70bSJung-uk Kim 	data = malloc(sizeof(*data) * size * N, M_TEMP, M_WAITOK);
539b2c63698SAlexander Motin 	adj = 0;
540b2c63698SAlexander Motin retry:
54165e7d70bSJung-uk Kim 	for (i = 0, tsc = data; i < N; i++, tsc += size)
54265e7d70bSJung-uk Kim 		smp_rendezvous(tsc_read_0, tsc_read_1, tsc_read_2, tsc);
54365e7d70bSJung-uk Kim 	smp_tsc = 1;	/* XXX */
54467d955aaSPatrick Kelsey 	smp_rendezvous(smp_no_rendezvous_barrier, comp_smp_tsc,
54567d955aaSPatrick Kelsey 	    smp_no_rendezvous_barrier, data);
546279be68bSAndriy Gapon 	if (!smp_tsc && adj < adj_max_count) {
547b2c63698SAlexander Motin 		adj++;
54867d955aaSPatrick Kelsey 		smp_rendezvous(smp_no_rendezvous_barrier, adj_smp_tsc,
54967d955aaSPatrick Kelsey 		    smp_no_rendezvous_barrier, data);
550b2c63698SAlexander Motin 		goto retry;
551b2c63698SAlexander Motin 	}
55265e7d70bSJung-uk Kim 	free(data, M_TEMP);
55365e7d70bSJung-uk Kim 	if (bootverbose)
554b2c63698SAlexander Motin 		printf("SMP: %sed TSC synchronization test%s\n",
555b2c63698SAlexander Motin 		    smp_tsc ? "pass" : "fail",
556b2c63698SAlexander Motin 		    adj > 0 ? " after adjustment" : "");
557cd165c8bSColin Percival 	TSEXIT();
55826e6537aSJung-uk Kim 	if (smp_tsc && tsc_is_invariant) {
55926e6537aSJung-uk Kim 		switch (cpu_vendor_id) {
56026e6537aSJung-uk Kim 		case CPU_VENDOR_AMD:
5612ee49facSKonstantin Belousov 		case CPU_VENDOR_HYGON:
56226e6537aSJung-uk Kim 			/*
563450d86fcSJung-uk Kim 			 * Processor Programming Reference (PPR) for AMD
564450d86fcSJung-uk Kim 			 * Family 17h states that the TSC uses a common
565450d86fcSJung-uk Kim 			 * reference for all sockets, cores and threads.
566450d86fcSJung-uk Kim 			 */
567450d86fcSJung-uk Kim 			if (CPUID_TO_FAMILY(cpu_id) >= 0x17)
568450d86fcSJung-uk Kim 				return (1000);
569450d86fcSJung-uk Kim 			/*
57026e6537aSJung-uk Kim 			 * Starting with Family 15h processors, TSC clock
57126e6537aSJung-uk Kim 			 * source is in the north bridge.  Check whether
57226e6537aSJung-uk Kim 			 * we have a single-socket/multi-core platform.
57326e6537aSJung-uk Kim 			 * XXX Need more work for complex cases.
57426e6537aSJung-uk Kim 			 */
57526e6537aSJung-uk Kim 			if (CPUID_TO_FAMILY(cpu_id) < 0x15 ||
57626e6537aSJung-uk Kim 			    (amd_feature2 & AMDID2_CMP) == 0 ||
57726e6537aSJung-uk Kim 			    smp_cpus > (cpu_procinfo2 & AMDID_CMP_CORES) + 1)
57826e6537aSJung-uk Kim 				break;
57926e6537aSJung-uk Kim 			return (1000);
58026e6537aSJung-uk Kim 		case CPU_VENDOR_INTEL:
58126e6537aSJung-uk Kim 			/*
58226e6537aSJung-uk Kim 			 * XXX Assume Intel platforms have synchronized TSCs.
58326e6537aSJung-uk Kim 			 */
58426e6537aSJung-uk Kim 			return (1000);
58526e6537aSJung-uk Kim 		}
58626e6537aSJung-uk Kim 		return (800);
58726e6537aSJung-uk Kim 	}
58826e6537aSJung-uk Kim 	return (-100);
58965e7d70bSJung-uk Kim }
59065e7d70bSJung-uk Kim 
59165e7d70bSJung-uk Kim #undef N
59265e7d70bSJung-uk Kim 
59365e7d70bSJung-uk Kim #endif /* SMP */
59465e7d70bSJung-uk Kim 
59565e7d70bSJung-uk Kim static void
596dd7d207dSJung-uk Kim init_TSC_tc(void)
597dd7d207dSJung-uk Kim {
59895f2f098SJung-uk Kim 	uint64_t max_freq;
59995f2f098SJung-uk Kim 	int shift;
600dd7d207dSJung-uk Kim 
60138b8542cSJung-uk Kim 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
602dd7d207dSJung-uk Kim 		return;
603dd7d207dSJung-uk Kim 
604dd7d207dSJung-uk Kim 	/*
60595f2f098SJung-uk Kim 	 * Limit timecounter frequency to fit in an int and prevent it from
60695f2f098SJung-uk Kim 	 * overflowing too fast.
60795f2f098SJung-uk Kim 	 */
60895f2f098SJung-uk Kim 	max_freq = UINT_MAX;
60995f2f098SJung-uk Kim 
61095f2f098SJung-uk Kim 	/*
61192597e06SJohn Baldwin 	 * Intel CPUs without a C-state invariant TSC can stop the TSC
612d1411416SJohn Baldwin 	 * in either C2 or C3.  Disable use of C2 and C3 while using
613d1411416SJohn Baldwin 	 * the TSC as the timecounter.  The timecounter can be changed
614d1411416SJohn Baldwin 	 * to enable C2 and C3.
615d1411416SJohn Baldwin 	 *
616d1411416SJohn Baldwin 	 * Note that the TSC is used as the cputicker for computing
617d1411416SJohn Baldwin 	 * thread runtime regardless of the timecounter setting, so
618d1411416SJohn Baldwin 	 * using an alternate timecounter and enabling C2 or C3 can
619d1411416SJohn Baldwin 	 * result incorrect runtimes for kernel idle threads (but not
620d1411416SJohn Baldwin 	 * for any non-idle threads).
621a49399a9SJung-uk Kim 	 */
6228cd59625SKonstantin Belousov 	if (cpu_vendor_id == CPU_VENDOR_INTEL &&
623a49399a9SJung-uk Kim 	    (amd_pminfo & AMDPM_TSC_INVARIANT) == 0) {
62492597e06SJohn Baldwin 		tsc_timecounter.tc_flags |= TC_FLAGS_C2STOP;
625a49399a9SJung-uk Kim 		if (bootverbose)
626d1411416SJohn Baldwin 			printf("TSC timecounter disables C2 and C3.\n");
627a49399a9SJung-uk Kim 	}
628a49399a9SJung-uk Kim 
629dd7d207dSJung-uk Kim 	/*
630e7f1427dSKonstantin Belousov 	 * We can not use the TSC in SMP mode unless the TSCs on all CPUs
631e7f1427dSKonstantin Belousov 	 * are synchronized.  If the user is sure that the system has
632e7f1427dSKonstantin Belousov 	 * synchronized TSCs, set kern.timecounter.smp_tsc tunable to a
633e7f1427dSKonstantin Belousov 	 * non-zero value.  The TSC seems unreliable in virtualized SMP
6345cf8ac1bSMike Silbersack 	 * environments, so it is set to a negative quality in those cases.
635dd7d207dSJung-uk Kim 	 */
636ba79ab82SAndriy Gapon #ifdef SMP
637e7f1427dSKonstantin Belousov 	if (mp_ncpus > 1)
638279be68bSAndriy Gapon 		tsc_timecounter.tc_quality = test_tsc(smp_tsc_adjust);
639ba79ab82SAndriy Gapon 	else
640ba79ab82SAndriy Gapon #endif /* SMP */
641ba79ab82SAndriy Gapon 	if (tsc_is_invariant)
64226e6537aSJung-uk Kim 		tsc_timecounter.tc_quality = 1000;
643e7f1427dSKonstantin Belousov 	max_freq >>= tsc_shift;
64426e6537aSJung-uk Kim 
645e7f1427dSKonstantin Belousov 	for (shift = 0; shift <= 31 && (tsc_freq >> shift) > max_freq; shift++)
64695f2f098SJung-uk Kim 		;
6479e680e40SKonstantin Belousov 
6489e680e40SKonstantin Belousov 	/*
6499e680e40SKonstantin Belousov 	 * Timecounter implementation selection, top to bottom:
6509e680e40SKonstantin Belousov 	 * - If RDTSCP is available, use RDTSCP.
6519e680e40SKonstantin Belousov 	 * - If fence instructions are provided (SSE2), use LFENCE;RDTSC
6529e680e40SKonstantin Belousov 	 *   on Intel, and MFENCE;RDTSC on AMD.
6539e680e40SKonstantin Belousov 	 * - For really old CPUs, just use RDTSC.
6549e680e40SKonstantin Belousov 	 */
6559f47eeffSKonstantin Belousov 	if ((amd_feature & AMDID_RDTSCP) != 0) {
6569e680e40SKonstantin Belousov 		tsc_timecounter.tc_get_timecount = shift > 0 ?
6579e680e40SKonstantin Belousov 		    tscp_get_timecount_low : tscp_get_timecount;
6589e680e40SKonstantin Belousov 	} else if ((cpu_feature & CPUID_SSE2) != 0 && mp_ncpus > 1) {
6592ee49facSKonstantin Belousov 		if (cpu_vendor_id == CPU_VENDOR_AMD ||
6602ee49facSKonstantin Belousov 		    cpu_vendor_id == CPU_VENDOR_HYGON) {
661e7f1427dSKonstantin Belousov 			tsc_timecounter.tc_get_timecount = shift > 0 ?
662e7f1427dSKonstantin Belousov 			    tsc_get_timecount_low_mfence :
663e7f1427dSKonstantin Belousov 			    tsc_get_timecount_mfence;
664814124c3SKonstantin Belousov 		} else {
665e7f1427dSKonstantin Belousov 			tsc_timecounter.tc_get_timecount = shift > 0 ?
666e7f1427dSKonstantin Belousov 			    tsc_get_timecount_low_lfence :
667e7f1427dSKonstantin Belousov 			    tsc_get_timecount_lfence;
668814124c3SKonstantin Belousov 		}
669e7f1427dSKonstantin Belousov 	} else {
670e7f1427dSKonstantin Belousov 		tsc_timecounter.tc_get_timecount = shift > 0 ?
671e7f1427dSKonstantin Belousov 		    tsc_get_timecount_low : tsc_get_timecount;
672e7f1427dSKonstantin Belousov 	}
673e7f1427dSKonstantin Belousov 	if (shift > 0) {
67495f2f098SJung-uk Kim 		tsc_timecounter.tc_name = "TSC-low";
67595f2f098SJung-uk Kim 		if (bootverbose)
676bc8e4ad2SJung-uk Kim 			printf("TSC timecounter discards lower %d bit(s)\n",
67795f2f098SJung-uk Kim 			    shift);
67895f2f098SJung-uk Kim 	}
679bc34c87eSJung-uk Kim 	if (tsc_freq != 0) {
68095f2f098SJung-uk Kim 		tsc_timecounter.tc_frequency = tsc_freq >> shift;
68195f2f098SJung-uk Kim 		tsc_timecounter.tc_priv = (void *)(intptr_t)shift;
68222875f88SMark Johnston 
68322875f88SMark Johnston 		/*
68422875f88SMark Johnston 		 * Timecounter registration is deferred until after late
68522875f88SMark Johnston 		 * calibration is finished.
68622875f88SMark Johnston 		 */
687dd7d207dSJung-uk Kim 	}
688dd7d207dSJung-uk Kim }
68965e7d70bSJung-uk Kim SYSINIT(tsc_tc, SI_SUB_SMP, SI_ORDER_ANY, init_TSC_tc, NULL);
690dd7d207dSJung-uk Kim 
69122875f88SMark Johnston static void
69222875f88SMark Johnston tsc_update_freq(uint64_t new_freq)
69322875f88SMark Johnston {
69422875f88SMark Johnston 	atomic_store_rel_64(&tsc_freq, new_freq);
69522875f88SMark Johnston 	atomic_store_rel_64(&tsc_timecounter.tc_frequency,
69622875f88SMark Johnston 	    new_freq >> (int)(intptr_t)tsc_timecounter.tc_priv);
69722875f88SMark Johnston }
69822875f88SMark Johnston 
69922875f88SMark Johnston /*
70022875f88SMark Johnston  * Perform late calibration of the TSC frequency once ACPI-based timecounters
701553af8f1SMark Johnston  * are available.  At this point timehands are not set up, so we read the
702553af8f1SMark Johnston  * highest-quality timecounter directly rather than using (s)binuptime().
70322875f88SMark Johnston  */
704553af8f1SMark Johnston void
705553af8f1SMark Johnston tsc_calibrate(void)
70622875f88SMark Johnston {
707*c2705ceaSColin Percival 	uint64_t freq;
70822875f88SMark Johnston 
70922875f88SMark Johnston 	if (tsc_disabled)
71022875f88SMark Johnston 		return;
7119cb32882SColin Percival 	if (tsc_early_calib_exact)
7129cb32882SColin Percival 		goto calibrated;
71322875f88SMark Johnston 
714*c2705ceaSColin Percival 	fpu_kern_enter(curthread, NULL, FPU_KERN_NOCTX);
715*c2705ceaSColin Percival 	freq = clockcalib(rdtsc_ordered, "TSC");
716*c2705ceaSColin Percival 	fpu_kern_leave(curthread, NULL);
717698727d6SColin Percival 	tsc_update_freq(freq);
718*c2705ceaSColin Percival 
7199cb32882SColin Percival calibrated:
72022875f88SMark Johnston 	tc_init(&tsc_timecounter);
72122875f88SMark Johnston 	set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
72222875f88SMark Johnston }
72322875f88SMark Johnston 
724279be68bSAndriy Gapon void
725279be68bSAndriy Gapon resume_TSC(void)
726279be68bSAndriy Gapon {
727ba79ab82SAndriy Gapon #ifdef SMP
728279be68bSAndriy Gapon 	int quality;
729279be68bSAndriy Gapon 
730279be68bSAndriy Gapon 	/* If TSC was not good on boot, it is unlikely to become good now. */
731279be68bSAndriy Gapon 	if (tsc_timecounter.tc_quality < 0)
732279be68bSAndriy Gapon 		return;
733279be68bSAndriy Gapon 	/* Nothing to do with UP. */
734279be68bSAndriy Gapon 	if (mp_ncpus < 2)
735279be68bSAndriy Gapon 		return;
736279be68bSAndriy Gapon 
737279be68bSAndriy Gapon 	/*
738279be68bSAndriy Gapon 	 * If TSC was good, a single synchronization should be enough,
739279be68bSAndriy Gapon 	 * but honour smp_tsc_adjust if it's set.
740279be68bSAndriy Gapon 	 */
741279be68bSAndriy Gapon 	quality = test_tsc(MAX(smp_tsc_adjust, 1));
742279be68bSAndriy Gapon 	if (quality != tsc_timecounter.tc_quality) {
743279be68bSAndriy Gapon 		printf("TSC timecounter quality changed: %d -> %d\n",
744279be68bSAndriy Gapon 		    tsc_timecounter.tc_quality, quality);
745279be68bSAndriy Gapon 		tsc_timecounter.tc_quality = quality;
746279be68bSAndriy Gapon 	}
747ba79ab82SAndriy Gapon #endif /* SMP */
748279be68bSAndriy Gapon }
749279be68bSAndriy Gapon 
750dd7d207dSJung-uk Kim /*
751dd7d207dSJung-uk Kim  * When cpufreq levels change, find out about the (new) max frequency.  We
752dd7d207dSJung-uk Kim  * use this to update CPU accounting in case it got a lower estimate at boot.
753dd7d207dSJung-uk Kim  */
754dd7d207dSJung-uk Kim static void
755dd7d207dSJung-uk Kim tsc_levels_changed(void *arg, int unit)
756dd7d207dSJung-uk Kim {
757dd7d207dSJung-uk Kim 	device_t cf_dev;
758dd7d207dSJung-uk Kim 	struct cf_level *levels;
759dd7d207dSJung-uk Kim 	int count, error;
760dd7d207dSJung-uk Kim 	uint64_t max_freq;
761dd7d207dSJung-uk Kim 
762dd7d207dSJung-uk Kim 	/* Only use values from the first CPU, assuming all are equal. */
763dd7d207dSJung-uk Kim 	if (unit != 0)
764dd7d207dSJung-uk Kim 		return;
765dd7d207dSJung-uk Kim 
766dd7d207dSJung-uk Kim 	/* Find the appropriate cpufreq device instance. */
767dd7d207dSJung-uk Kim 	cf_dev = devclass_get_device(devclass_find("cpufreq"), unit);
768dd7d207dSJung-uk Kim 	if (cf_dev == NULL) {
769dd7d207dSJung-uk Kim 		printf("tsc_levels_changed() called but no cpufreq device?\n");
770dd7d207dSJung-uk Kim 		return;
771dd7d207dSJung-uk Kim 	}
772dd7d207dSJung-uk Kim 
773dd7d207dSJung-uk Kim 	/* Get settings from the device and find the max frequency. */
774dd7d207dSJung-uk Kim 	count = 64;
775dd7d207dSJung-uk Kim 	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
776dd7d207dSJung-uk Kim 	if (levels == NULL)
777dd7d207dSJung-uk Kim 		return;
778dd7d207dSJung-uk Kim 	error = CPUFREQ_LEVELS(cf_dev, levels, &count);
779dd7d207dSJung-uk Kim 	if (error == 0 && count != 0) {
780dd7d207dSJung-uk Kim 		max_freq = (uint64_t)levels[0].total_set.freq * 1000000;
781dd7d207dSJung-uk Kim 		set_cputicker(rdtsc, max_freq, 1);
782dd7d207dSJung-uk Kim 	} else
783dd7d207dSJung-uk Kim 		printf("tsc_levels_changed: no max freq found\n");
784dd7d207dSJung-uk Kim 	free(levels, M_TEMP);
785dd7d207dSJung-uk Kim }
786dd7d207dSJung-uk Kim 
787dd7d207dSJung-uk Kim /*
788dd7d207dSJung-uk Kim  * If the TSC timecounter is in use, veto the pending change.  It may be
789dd7d207dSJung-uk Kim  * possible in the future to handle a dynamically-changing timecounter rate.
790dd7d207dSJung-uk Kim  */
791dd7d207dSJung-uk Kim static void
792dd7d207dSJung-uk Kim tsc_freq_changing(void *arg, const struct cf_level *level, int *status)
793dd7d207dSJung-uk Kim {
794dd7d207dSJung-uk Kim 
795dd7d207dSJung-uk Kim 	if (*status != 0 || timecounter != &tsc_timecounter)
796dd7d207dSJung-uk Kim 		return;
797dd7d207dSJung-uk Kim 
798dd7d207dSJung-uk Kim 	printf("timecounter TSC must not be in use when "
799dd7d207dSJung-uk Kim 	    "changing frequencies; change denied\n");
800dd7d207dSJung-uk Kim 	*status = EBUSY;
801dd7d207dSJung-uk Kim }
802dd7d207dSJung-uk Kim 
803dd7d207dSJung-uk Kim /* Update TSC freq with the value indicated by the caller. */
804dd7d207dSJung-uk Kim static void
805dd7d207dSJung-uk Kim tsc_freq_changed(void *arg, const struct cf_level *level, int status)
806dd7d207dSJung-uk Kim {
8073453537fSJung-uk Kim 	uint64_t freq;
808dd7d207dSJung-uk Kim 
809dd7d207dSJung-uk Kim 	/* If there was an error during the transition, don't do anything. */
81079422085SJung-uk Kim 	if (tsc_disabled || status != 0)
811dd7d207dSJung-uk Kim 		return;
812dd7d207dSJung-uk Kim 
813dd7d207dSJung-uk Kim 	/* Total setting for this level gives the new frequency in MHz. */
8143453537fSJung-uk Kim 	freq = (uint64_t)level->total_set.freq * 1000000;
81522875f88SMark Johnston 	tsc_update_freq(freq);
816dd7d207dSJung-uk Kim }
817dd7d207dSJung-uk Kim 
818dd7d207dSJung-uk Kim static int
819dd7d207dSJung-uk Kim sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
820dd7d207dSJung-uk Kim {
821dd7d207dSJung-uk Kim 	int error;
822dd7d207dSJung-uk Kim 	uint64_t freq;
823dd7d207dSJung-uk Kim 
8243453537fSJung-uk Kim 	freq = atomic_load_acq_64(&tsc_freq);
8253453537fSJung-uk Kim 	if (freq == 0)
826dd7d207dSJung-uk Kim 		return (EOPNOTSUPP);
827cbc134adSMatthew D Fleming 	error = sysctl_handle_64(oidp, &freq, 0, req);
82822875f88SMark Johnston 	if (error == 0 && req->newptr != NULL)
82922875f88SMark Johnston 		tsc_update_freq(freq);
830dd7d207dSJung-uk Kim 	return (error);
831dd7d207dSJung-uk Kim }
8327029da5cSPawel Biernacki SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq,
8331d6fb900SAlexander Motin     CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
8347029da5cSPawel Biernacki     0, 0, sysctl_machdep_tsc_freq, "QU",
8357029da5cSPawel Biernacki     "Time Stamp Counter frequency");
836dd7d207dSJung-uk Kim 
837727c7b2dSJung-uk Kim static u_int
83895f2f098SJung-uk Kim tsc_get_timecount(struct timecounter *tc __unused)
839dd7d207dSJung-uk Kim {
840727c7b2dSJung-uk Kim 
841727c7b2dSJung-uk Kim 	return (rdtsc32());
842dd7d207dSJung-uk Kim }
84395f2f098SJung-uk Kim 
8449e680e40SKonstantin Belousov static u_int
8459e680e40SKonstantin Belousov tscp_get_timecount(struct timecounter *tc __unused)
8469e680e40SKonstantin Belousov {
8479e680e40SKonstantin Belousov 
8489e680e40SKonstantin Belousov 	return (rdtscp32());
8499e680e40SKonstantin Belousov }
8509e680e40SKonstantin Belousov 
851814124c3SKonstantin Belousov static inline u_int
852bc8e4ad2SJung-uk Kim tsc_get_timecount_low(struct timecounter *tc)
85395f2f098SJung-uk Kim {
8545df88f46SJung-uk Kim 	uint32_t rv;
85595f2f098SJung-uk Kim 
8565df88f46SJung-uk Kim 	__asm __volatile("rdtsc; shrd %%cl, %%edx, %0"
8575df88f46SJung-uk Kim 	    : "=a" (rv) : "c" ((int)(intptr_t)tc->tc_priv) : "edx");
8585df88f46SJung-uk Kim 	return (rv);
85995f2f098SJung-uk Kim }
860aea81038SKonstantin Belousov 
861814124c3SKonstantin Belousov static u_int
8629e680e40SKonstantin Belousov tscp_get_timecount_low(struct timecounter *tc)
8639e680e40SKonstantin Belousov {
8649e680e40SKonstantin Belousov 	uint32_t rv;
8659e680e40SKonstantin Belousov 
8669e680e40SKonstantin Belousov 	__asm __volatile("rdtscp; movl %1, %%ecx; shrd %%cl, %%edx, %0"
867a013e285SKonstantin Belousov 	    : "=&a" (rv) : "m" (tc->tc_priv) : "ecx", "edx");
8689e680e40SKonstantin Belousov 	return (rv);
8699e680e40SKonstantin Belousov }
8709e680e40SKonstantin Belousov 
8719e680e40SKonstantin Belousov static u_int
872814124c3SKonstantin Belousov tsc_get_timecount_lfence(struct timecounter *tc __unused)
873814124c3SKonstantin Belousov {
874814124c3SKonstantin Belousov 
875814124c3SKonstantin Belousov 	lfence();
876814124c3SKonstantin Belousov 	return (rdtsc32());
877814124c3SKonstantin Belousov }
878814124c3SKonstantin Belousov 
879814124c3SKonstantin Belousov static u_int
880814124c3SKonstantin Belousov tsc_get_timecount_low_lfence(struct timecounter *tc)
881814124c3SKonstantin Belousov {
882814124c3SKonstantin Belousov 
883814124c3SKonstantin Belousov 	lfence();
884814124c3SKonstantin Belousov 	return (tsc_get_timecount_low(tc));
885814124c3SKonstantin Belousov }
886814124c3SKonstantin Belousov 
887814124c3SKonstantin Belousov static u_int
888814124c3SKonstantin Belousov tsc_get_timecount_mfence(struct timecounter *tc __unused)
889814124c3SKonstantin Belousov {
890814124c3SKonstantin Belousov 
891814124c3SKonstantin Belousov 	mfence();
892814124c3SKonstantin Belousov 	return (rdtsc32());
893814124c3SKonstantin Belousov }
894814124c3SKonstantin Belousov 
895814124c3SKonstantin Belousov static u_int
896814124c3SKonstantin Belousov tsc_get_timecount_low_mfence(struct timecounter *tc)
897814124c3SKonstantin Belousov {
898814124c3SKonstantin Belousov 
899814124c3SKonstantin Belousov 	mfence();
900814124c3SKonstantin Belousov 	return (tsc_get_timecount_low(tc));
901814124c3SKonstantin Belousov }
902814124c3SKonstantin Belousov 
90316808549SKonstantin Belousov static uint32_t
90416808549SKonstantin Belousov x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th, struct timecounter *tc)
905aea81038SKonstantin Belousov {
906aea81038SKonstantin Belousov 
90716808549SKonstantin Belousov 	vdso_th->th_algo = VDSO_TH_ALGO_X86_TSC;
908d1b1b600SNeel Natu 	vdso_th->th_x86_shift = (int)(intptr_t)tc->tc_priv;
90916808549SKonstantin Belousov 	vdso_th->th_x86_hpet_idx = 0xffffffff;
910d4b2d303SAdam Fenn 	vdso_th->th_x86_pvc_last_systime = 0;
911d4b2d303SAdam Fenn 	vdso_th->th_x86_pvc_stable_mask = 0;
912aea81038SKonstantin Belousov 	bzero(vdso_th->th_res, sizeof(vdso_th->th_res));
91316808549SKonstantin Belousov 	return (1);
914aea81038SKonstantin Belousov }
915aea81038SKonstantin Belousov 
916aea81038SKonstantin Belousov #ifdef COMPAT_FREEBSD32
91716808549SKonstantin Belousov static uint32_t
91816808549SKonstantin Belousov x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
919d1b1b600SNeel Natu     struct timecounter *tc)
920aea81038SKonstantin Belousov {
921aea81038SKonstantin Belousov 
92216808549SKonstantin Belousov 	vdso_th32->th_algo = VDSO_TH_ALGO_X86_TSC;
923d1b1b600SNeel Natu 	vdso_th32->th_x86_shift = (int)(intptr_t)tc->tc_priv;
92416808549SKonstantin Belousov 	vdso_th32->th_x86_hpet_idx = 0xffffffff;
925d4b2d303SAdam Fenn 	vdso_th32->th_x86_pvc_last_systime = 0;
926d4b2d303SAdam Fenn 	vdso_th32->th_x86_pvc_stable_mask = 0;
927aea81038SKonstantin Belousov 	bzero(vdso_th32->th_res, sizeof(vdso_th32->th_res));
92816808549SKonstantin Belousov 	return (1);
929aea81038SKonstantin Belousov }
930aea81038SKonstantin Belousov #endif
931