xref: /freebsd/sys/x86/x86/tsc.c (revision 4a432614f68cf35879dbb4ebef089f5b8db95334)
1dd7d207dSJung-uk Kim /*-
2ebf5747bSPedro F. Giffuni  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3ebf5747bSPedro F. Giffuni  *
4dd7d207dSJung-uk Kim  * Copyright (c) 1998-2003 Poul-Henning Kamp
5dd7d207dSJung-uk Kim  * All rights reserved.
6dd7d207dSJung-uk Kim  *
7dd7d207dSJung-uk Kim  * Redistribution and use in source and binary forms, with or without
8dd7d207dSJung-uk Kim  * modification, are permitted provided that the following conditions
9dd7d207dSJung-uk Kim  * are met:
10dd7d207dSJung-uk Kim  * 1. Redistributions of source code must retain the above copyright
11dd7d207dSJung-uk Kim  *    notice, this list of conditions and the following disclaimer.
12dd7d207dSJung-uk Kim  * 2. Redistributions in binary form must reproduce the above copyright
13dd7d207dSJung-uk Kim  *    notice, this list of conditions and the following disclaimer in the
14dd7d207dSJung-uk Kim  *    documentation and/or other materials provided with the distribution.
15dd7d207dSJung-uk Kim  *
16dd7d207dSJung-uk Kim  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17dd7d207dSJung-uk Kim  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18dd7d207dSJung-uk Kim  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19dd7d207dSJung-uk Kim  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20dd7d207dSJung-uk Kim  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21dd7d207dSJung-uk Kim  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22dd7d207dSJung-uk Kim  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23dd7d207dSJung-uk Kim  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24dd7d207dSJung-uk Kim  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25dd7d207dSJung-uk Kim  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26dd7d207dSJung-uk Kim  * SUCH DAMAGE.
27dd7d207dSJung-uk Kim  */
28dd7d207dSJung-uk Kim 
29dd7d207dSJung-uk Kim #include <sys/cdefs.h>
30dd7d207dSJung-uk Kim __FBSDID("$FreeBSD$");
31dd7d207dSJung-uk Kim 
32dd7d207dSJung-uk Kim #include "opt_clock.h"
33dd7d207dSJung-uk Kim 
34dd7d207dSJung-uk Kim #include <sys/param.h>
3522875f88SMark Johnston #include <sys/systm.h>
36dd7d207dSJung-uk Kim #include <sys/bus.h>
37dd7d207dSJung-uk Kim #include <sys/cpu.h>
38e2e050c8SConrad Meyer #include <sys/eventhandler.h>
395da5812bSJung-uk Kim #include <sys/limits.h>
40dd7d207dSJung-uk Kim #include <sys/malloc.h>
4122875f88SMark Johnston #include <sys/proc.h>
4222875f88SMark Johnston #include <sys/sched.h>
43dd7d207dSJung-uk Kim #include <sys/sysctl.h>
44dd7d207dSJung-uk Kim #include <sys/time.h>
45dd7d207dSJung-uk Kim #include <sys/timetc.h>
46dd7d207dSJung-uk Kim #include <sys/kernel.h>
47dd7d207dSJung-uk Kim #include <sys/smp.h>
48aea81038SKonstantin Belousov #include <sys/vdso.h>
49dd7d207dSJung-uk Kim #include <machine/clock.h>
50dd7d207dSJung-uk Kim #include <machine/cputypes.h>
51c2705ceaSColin Percival #include <machine/fpu.h>
52dd7d207dSJung-uk Kim #include <machine/md_var.h>
53dd7d207dSJung-uk Kim #include <machine/specialreg.h>
5401e1933dSJohn Baldwin #include <x86/vmware.h>
5516808549SKonstantin Belousov #include <dev/acpica/acpi_hpet.h>
56ce3bf750SKonstantin Belousov #include <contrib/dev/acpica/include/acpi.h>
57dd7d207dSJung-uk Kim 
58dd7d207dSJung-uk Kim #include "cpufreq_if.h"
59dd7d207dSJung-uk Kim 
60dd7d207dSJung-uk Kim uint64_t	tsc_freq;
61dd7d207dSJung-uk Kim int		tsc_is_invariant;
62155094d7SJung-uk Kim int		tsc_perf_stat;
639cb32882SColin Percival static int	tsc_early_calib_exact;
64155094d7SJung-uk Kim 
65dd7d207dSJung-uk Kim static eventhandler_tag tsc_levels_tag, tsc_pre_tag, tsc_post_tag;
66dd7d207dSJung-uk Kim 
67dd7d207dSJung-uk Kim SYSCTL_INT(_kern_timecounter, OID_AUTO, invariant_tsc, CTLFLAG_RDTUN,
68dd7d207dSJung-uk Kim     &tsc_is_invariant, 0, "Indicates whether the TSC is P-state invariant");
69dd7d207dSJung-uk Kim 
70dd7d207dSJung-uk Kim #ifdef SMP
711472b87fSNeel Natu int	smp_tsc;
72dd7d207dSJung-uk Kim SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc, CTLFLAG_RDTUN, &smp_tsc, 0,
73dd7d207dSJung-uk Kim     "Indicates whether the TSC is safe to use in SMP mode");
74b2c63698SAlexander Motin 
75b2c63698SAlexander Motin int	smp_tsc_adjust = 0;
76b2c63698SAlexander Motin SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc_adjust, CTLFLAG_RDTUN,
77b2c63698SAlexander Motin     &smp_tsc_adjust, 0, "Try to adjust TSC on APs to match BSP");
78dd7d207dSJung-uk Kim #endif
79dd7d207dSJung-uk Kim 
80e7f1427dSKonstantin Belousov static int	tsc_shift = 1;
81e7f1427dSKonstantin Belousov SYSCTL_INT(_kern_timecounter, OID_AUTO, tsc_shift, CTLFLAG_RDTUN,
82e7f1427dSKonstantin Belousov     &tsc_shift, 0, "Shift to pre-apply for the maximum TSC frequency");
83e7f1427dSKonstantin Belousov 
8479422085SJung-uk Kim static int	tsc_disabled;
8579422085SJung-uk Kim SYSCTL_INT(_machdep, OID_AUTO, disable_tsc, CTLFLAG_RDTUN, &tsc_disabled, 0,
8679422085SJung-uk Kim     "Disable x86 Time Stamp Counter");
8779422085SJung-uk Kim 
88a4e4127fSJung-uk Kim static int	tsc_skip_calibration;
89ab23c278SKonstantin Belousov SYSCTL_INT(_machdep, OID_AUTO, disable_tsc_calibration, CTLFLAG_RDTUN,
90ab23c278SKonstantin Belousov     &tsc_skip_calibration, 0,
9122875f88SMark Johnston     "Disable early TSC frequency calibration");
92a4e4127fSJung-uk Kim 
93dd7d207dSJung-uk Kim static void tsc_freq_changed(void *arg, const struct cf_level *level,
94dd7d207dSJung-uk Kim     int status);
95dd7d207dSJung-uk Kim static void tsc_freq_changing(void *arg, const struct cf_level *level,
96dd7d207dSJung-uk Kim     int *status);
97826fc3ccSKonstantin Belousov static u_int tsc_get_timecount(struct timecounter *tc);
98826fc3ccSKonstantin Belousov static inline u_int tsc_get_timecount_low(struct timecounter *tc);
99826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_lfence(struct timecounter *tc);
100826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_low_lfence(struct timecounter *tc);
101826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_mfence(struct timecounter *tc);
102826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_low_mfence(struct timecounter *tc);
1039e680e40SKonstantin Belousov static u_int tscp_get_timecount(struct timecounter *tc);
1049e680e40SKonstantin Belousov static u_int tscp_get_timecount_low(struct timecounter *tc);
105dd7d207dSJung-uk Kim static void tsc_levels_changed(void *arg, int unit);
10616808549SKonstantin Belousov static uint32_t x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th,
10716808549SKonstantin Belousov     struct timecounter *tc);
10816808549SKonstantin Belousov #ifdef COMPAT_FREEBSD32
10916808549SKonstantin Belousov static uint32_t x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
11016808549SKonstantin Belousov     struct timecounter *tc);
11116808549SKonstantin Belousov #endif
112dd7d207dSJung-uk Kim 
113dd7d207dSJung-uk Kim static struct timecounter tsc_timecounter = {
11416808549SKonstantin Belousov 	.tc_get_timecount =		tsc_get_timecount,
11516808549SKonstantin Belousov 	.tc_counter_mask =		~0u,
11616808549SKonstantin Belousov 	.tc_name =			"TSC",
11716808549SKonstantin Belousov 	.tc_quality =			800,	/* adjusted in code */
11816808549SKonstantin Belousov 	.tc_fill_vdso_timehands = 	x86_tsc_vdso_timehands,
11916808549SKonstantin Belousov #ifdef COMPAT_FREEBSD32
12016808549SKonstantin Belousov 	.tc_fill_vdso_timehands32 = 	x86_tsc_vdso_timehands32,
12116808549SKonstantin Belousov #endif
122dd7d207dSJung-uk Kim };
123dd7d207dSJung-uk Kim 
124*4a432614SColin Percival static int
125*4a432614SColin Percival tsc_freq_cpuid_vm(void)
126*4a432614SColin Percival {
127*4a432614SColin Percival 	u_int regs[4];
128*4a432614SColin Percival 
129*4a432614SColin Percival 	if (vm_guest == VM_GUEST_NO)
130*4a432614SColin Percival 		return (false);
131*4a432614SColin Percival 	if (hv_high < 0x40000010)
132*4a432614SColin Percival 		return (false);
133*4a432614SColin Percival 	do_cpuid(0x40000010, regs);
134*4a432614SColin Percival 	tsc_freq = (uint64_t)(regs[0]) * 1000;
135*4a432614SColin Percival 	tsc_early_calib_exact = 1;
136*4a432614SColin Percival 	return (true);
137*4a432614SColin Percival }
138*4a432614SColin Percival 
13901e1933dSJohn Baldwin static void
1405da5812bSJung-uk Kim tsc_freq_vmware(void)
1415da5812bSJung-uk Kim {
1425da5812bSJung-uk Kim 	u_int regs[4];
1435da5812bSJung-uk Kim 
1445da5812bSJung-uk Kim 	vmware_hvcall(VMW_HVCMD_GETHZ, regs);
1455da5812bSJung-uk Kim 	if (regs[1] != UINT_MAX)
1465da5812bSJung-uk Kim 		tsc_freq = regs[0] | ((uint64_t)regs[1] << 32);
1479cb32882SColin Percival 	tsc_early_calib_exact = 1;
1485da5812bSJung-uk Kim }
1495da5812bSJung-uk Kim 
150506a906cSKonstantin Belousov /*
15122875f88SMark Johnston  * Calculate TSC frequency using information from the CPUID leaf 0x15 'Time
15222875f88SMark Johnston  * Stamp Counter and Nominal Core Crystal Clock'.  If leaf 0x15 is not
15322875f88SMark Johnston  * functional, as it is on Skylake/Kabylake, try 0x16 'Processor Frequency
15422875f88SMark Johnston  * Information'.  Leaf 0x16 is described in the SDM as informational only, but
15522875f88SMark Johnston  * we can use this value until late calibration is complete.
156506a906cSKonstantin Belousov  */
157506a906cSKonstantin Belousov static bool
158bd8a359fSKonstantin Belousov tsc_freq_cpuid(uint64_t *res)
159506a906cSKonstantin Belousov {
160506a906cSKonstantin Belousov 	u_int regs[4];
161506a906cSKonstantin Belousov 
162506a906cSKonstantin Belousov 	if (cpu_high < 0x15)
163506a906cSKonstantin Belousov 		return (false);
164506a906cSKonstantin Belousov 	do_cpuid(0x15, regs);
165a9d0e007SKonstantin Belousov 	if (regs[0] != 0 && regs[1] != 0 && regs[2] != 0) {
166bd8a359fSKonstantin Belousov 		*res = (uint64_t)regs[2] * regs[1] / regs[0];
167506a906cSKonstantin Belousov 		return (true);
168506a906cSKonstantin Belousov 	}
169506a906cSKonstantin Belousov 
170a9d0e007SKonstantin Belousov 	if (cpu_high < 0x16)
171a9d0e007SKonstantin Belousov 		return (false);
172a9d0e007SKonstantin Belousov 	do_cpuid(0x16, regs);
173a9d0e007SKonstantin Belousov 	if (regs[0] != 0) {
174bd8a359fSKonstantin Belousov 		*res = (uint64_t)regs[0] * 1000000;
175a9d0e007SKonstantin Belousov 		return (true);
176a9d0e007SKonstantin Belousov 	}
177a9d0e007SKonstantin Belousov 
178a9d0e007SKonstantin Belousov 	return (false);
179a9d0e007SKonstantin Belousov }
180a9d0e007SKonstantin Belousov 
18122875f88SMark Johnston static bool
18222875f88SMark Johnston tsc_freq_intel_brand(uint64_t *res)
183dd7d207dSJung-uk Kim {
184a4e4127fSJung-uk Kim 	char brand[48];
185a4e4127fSJung-uk Kim 	u_int regs[4];
186a4e4127fSJung-uk Kim 	uint64_t freq;
187a4e4127fSJung-uk Kim 	char *p;
188a4e4127fSJung-uk Kim 	u_int i;
189dd7d207dSJung-uk Kim 
190a4e4127fSJung-uk Kim 	/*
191a4e4127fSJung-uk Kim 	 * Intel Processor Identification and the CPUID Instruction
192a4e4127fSJung-uk Kim 	 * Application Note 485.
193a4e4127fSJung-uk Kim 	 * http://www.intel.com/assets/pdf/appnote/241618.pdf
194a4e4127fSJung-uk Kim 	 */
195a4e4127fSJung-uk Kim 	if (cpu_exthigh >= 0x80000004) {
196a4e4127fSJung-uk Kim 		p = brand;
197a4e4127fSJung-uk Kim 		for (i = 0x80000002; i < 0x80000005; i++) {
198a4e4127fSJung-uk Kim 			do_cpuid(i, regs);
199a4e4127fSJung-uk Kim 			memcpy(p, regs, sizeof(regs));
200a4e4127fSJung-uk Kim 			p += sizeof(regs);
201a4e4127fSJung-uk Kim 		}
202a4e4127fSJung-uk Kim 		p = NULL;
203a4e4127fSJung-uk Kim 		for (i = 0; i < sizeof(brand) - 1; i++)
204a4e4127fSJung-uk Kim 			if (brand[i] == 'H' && brand[i + 1] == 'z')
205a4e4127fSJung-uk Kim 				p = brand + i;
206a4e4127fSJung-uk Kim 		if (p != NULL) {
207a4e4127fSJung-uk Kim 			p -= 5;
208a4e4127fSJung-uk Kim 			switch (p[4]) {
209a4e4127fSJung-uk Kim 			case 'M':
210a4e4127fSJung-uk Kim 				i = 1;
211a4e4127fSJung-uk Kim 				break;
212a4e4127fSJung-uk Kim 			case 'G':
213a4e4127fSJung-uk Kim 				i = 1000;
214a4e4127fSJung-uk Kim 				break;
215a4e4127fSJung-uk Kim 			case 'T':
216a4e4127fSJung-uk Kim 				i = 1000000;
217a4e4127fSJung-uk Kim 				break;
218a4e4127fSJung-uk Kim 			default:
21922875f88SMark Johnston 				return (false);
220a4e4127fSJung-uk Kim 			}
221a4e4127fSJung-uk Kim #define	C2D(c)	((c) - '0')
222a4e4127fSJung-uk Kim 			if (p[1] == '.') {
223a4e4127fSJung-uk Kim 				freq = C2D(p[0]) * 1000;
224a4e4127fSJung-uk Kim 				freq += C2D(p[2]) * 100;
225a4e4127fSJung-uk Kim 				freq += C2D(p[3]) * 10;
226a4e4127fSJung-uk Kim 				freq *= i * 1000;
227a4e4127fSJung-uk Kim 			} else {
228a4e4127fSJung-uk Kim 				freq = C2D(p[0]) * 1000;
229a4e4127fSJung-uk Kim 				freq += C2D(p[1]) * 100;
230a4e4127fSJung-uk Kim 				freq += C2D(p[2]) * 10;
231a4e4127fSJung-uk Kim 				freq += C2D(p[3]);
232a4e4127fSJung-uk Kim 				freq *= i * 1000000;
233a4e4127fSJung-uk Kim 			}
234a4e4127fSJung-uk Kim #undef C2D
23522875f88SMark Johnston 			*res = freq;
23622875f88SMark Johnston 			return (true);
237a4e4127fSJung-uk Kim 		}
238a4e4127fSJung-uk Kim 	}
23922875f88SMark Johnston 	return (false);
24022875f88SMark Johnston }
24122875f88SMark Johnston 
24222875f88SMark Johnston static void
24322875f88SMark Johnston tsc_freq_8254(uint64_t *res)
24422875f88SMark Johnston {
24522875f88SMark Johnston 	uint64_t tsc1, tsc2;
24622875f88SMark Johnston 	int64_t overhead;
24722875f88SMark Johnston 	int count, i;
24822875f88SMark Johnston 
24922875f88SMark Johnston 	overhead = 0;
25022875f88SMark Johnston 	for (i = 0, count = 8; i < count; i++) {
25122875f88SMark Johnston 		tsc1 = rdtsc_ordered();
25222875f88SMark Johnston 		DELAY(0);
25322875f88SMark Johnston 		tsc2 = rdtsc_ordered();
25422875f88SMark Johnston 		if (i > 0)
25522875f88SMark Johnston 			overhead += tsc2 - tsc1;
25622875f88SMark Johnston 	}
25722875f88SMark Johnston 	overhead /= count;
25822875f88SMark Johnston 
25922875f88SMark Johnston 	tsc1 = rdtsc_ordered();
26022875f88SMark Johnston 	DELAY(100000);
26122875f88SMark Johnston 	tsc2 = rdtsc_ordered();
26222875f88SMark Johnston 	tsc_freq = (tsc2 - tsc1 - overhead) * 10;
263a4e4127fSJung-uk Kim }
264dd7d207dSJung-uk Kim 
265a4e4127fSJung-uk Kim static void
266a4e4127fSJung-uk Kim probe_tsc_freq(void)
267a4e4127fSJung-uk Kim {
268bb044eafSConrad Meyer 	if (cpu_power_ecx & CPUID_PERF_STAT) {
2695da5812bSJung-uk Kim 		/*
270bb044eafSConrad Meyer 		 * XXX Some emulators expose host CPUID without actual support
271bb044eafSConrad Meyer 		 * for these MSRs.  We must test whether they really work.
2725da5812bSJung-uk Kim 		 */
2735da5812bSJung-uk Kim 		wrmsr(MSR_MPERF, 0);
2745da5812bSJung-uk Kim 		wrmsr(MSR_APERF, 0);
2755da5812bSJung-uk Kim 		DELAY(10);
2765da5812bSJung-uk Kim 		if (rdmsr(MSR_MPERF) > 0 && rdmsr(MSR_APERF) > 0)
2775da5812bSJung-uk Kim 			tsc_perf_stat = 1;
2785da5812bSJung-uk Kim 	}
2795da5812bSJung-uk Kim 
280dd7d207dSJung-uk Kim 	switch (cpu_vendor_id) {
281dd7d207dSJung-uk Kim 	case CPU_VENDOR_AMD:
2822ee49facSKonstantin Belousov 	case CPU_VENDOR_HYGON:
283a106a27cSJung-uk Kim 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
284a106a27cSJung-uk Kim 		    (vm_guest == VM_GUEST_NO &&
285a106a27cSJung-uk Kim 		    CPUID_TO_FAMILY(cpu_id) >= 0x10))
286dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
287814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
288814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
289814124c3SKonstantin Belousov 			    tsc_get_timecount_mfence;
290814124c3SKonstantin Belousov 		}
291dd7d207dSJung-uk Kim 		break;
292dd7d207dSJung-uk Kim 	case CPU_VENDOR_INTEL:
293a106a27cSJung-uk Kim 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
294a106a27cSJung-uk Kim 		    (vm_guest == VM_GUEST_NO &&
295a106a27cSJung-uk Kim 		    ((CPUID_TO_FAMILY(cpu_id) == 0x6 &&
296dd7d207dSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0xe) ||
297dd7d207dSJung-uk Kim 		    (CPUID_TO_FAMILY(cpu_id) == 0xf &&
298a106a27cSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0x3))))
299dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
300814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
301814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
302814124c3SKonstantin Belousov 			    tsc_get_timecount_lfence;
303814124c3SKonstantin Belousov 		}
304dd7d207dSJung-uk Kim 		break;
305dd7d207dSJung-uk Kim 	case CPU_VENDOR_CENTAUR:
306a106a27cSJung-uk Kim 		if (vm_guest == VM_GUEST_NO &&
307a106a27cSJung-uk Kim 		    CPUID_TO_FAMILY(cpu_id) == 0x6 &&
308dd7d207dSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0xf &&
309dd7d207dSJung-uk Kim 		    (rdmsr(0x1203) & 0x100000000ULL) == 0)
310dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
311814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
312814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
313814124c3SKonstantin Belousov 			    tsc_get_timecount_lfence;
314814124c3SKonstantin Belousov 		}
315dd7d207dSJung-uk Kim 		break;
316dd7d207dSJung-uk Kim 	}
317dd7d207dSJung-uk Kim 
318*4a432614SColin Percival 	if (tsc_freq_cpuid_vm())
319*4a432614SColin Percival 		return;
320*4a432614SColin Percival 
321fd980febSColin Percival 	if (vm_guest == VM_GUEST_VMWARE) {
322fd980febSColin Percival 		tsc_freq_vmware();
323fd980febSColin Percival 		return;
324fd980febSColin Percival 	}
325fd980febSColin Percival 
32622875f88SMark Johnston 	if (tsc_freq_cpuid(&tsc_freq)) {
327bd8a359fSKonstantin Belousov 		/*
32822875f88SMark Johnston 		 * If possible, use the value obtained from CPUID as the initial
32922875f88SMark Johnston 		 * frequency.  This will be refined later during boot but is
33022875f88SMark Johnston 		 * good enough for now.  The 8254 PIT is not functional on some
33122875f88SMark Johnston 		 * newer platforms anyway, so don't delay our boot for what
33222875f88SMark Johnston 		 * might be a garbage result.  Late calibration is required if
33322875f88SMark Johnston 		 * the initial frequency was obtained from CPUID.16H, as the
33422875f88SMark Johnston 		 * derived value may be off by as much as 1%.
335bd8a359fSKonstantin Belousov 		 */
336a4e4127fSJung-uk Kim 		if (bootverbose)
33722875f88SMark Johnston 			printf("Early TSC frequency %juHz derived from CPUID\n",
33822875f88SMark Johnston 			    (uintmax_t)tsc_freq);
33922875f88SMark Johnston 	} else if (tsc_skip_calibration) {
34022875f88SMark Johnston 		/*
34122875f88SMark Johnston 		 * Try to parse the brand string to obtain the nominal TSC
34222875f88SMark Johnston 		 * frequency.
34322875f88SMark Johnston 		 */
34422875f88SMark Johnston 		if (cpu_vendor_id == CPU_VENDOR_INTEL &&
34522875f88SMark Johnston 		    tsc_freq_intel_brand(&tsc_freq)) {
34622875f88SMark Johnston 			if (bootverbose)
34722875f88SMark Johnston 				printf(
34822875f88SMark Johnston 		    "Early TSC frequency %juHz derived from brand string\n",
34922875f88SMark Johnston 				    (uintmax_t)tsc_freq);
35022875f88SMark Johnston 		} else {
35122875f88SMark Johnston 			tsc_disabled = 1;
35222875f88SMark Johnston 		}
35322875f88SMark Johnston 	} else {
35422875f88SMark Johnston 		/*
35522875f88SMark Johnston 		 * Calibrate against the 8254 PIT.  This estimate will be
35622875f88SMark Johnston 		 * refined later in tsc_calib().
35722875f88SMark Johnston 		 */
35822875f88SMark Johnston 		tsc_freq_8254(&tsc_freq);
35922875f88SMark Johnston 		if (bootverbose)
36022875f88SMark Johnston 			printf(
36122875f88SMark Johnston 		    "Early TSC frequency %juHz calibrated from 8254 PIT\n",
36222875f88SMark Johnston 			    (uintmax_t)tsc_freq);
36322875f88SMark Johnston 	}
364a4e4127fSJung-uk Kim }
365a4e4127fSJung-uk Kim 
366a4e4127fSJung-uk Kim void
367a4e4127fSJung-uk Kim init_TSC(void)
368a4e4127fSJung-uk Kim {
369a4e4127fSJung-uk Kim 
370a4e4127fSJung-uk Kim 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
371a4e4127fSJung-uk Kim 		return;
372a4e4127fSJung-uk Kim 
373fe760cfaSJohn Baldwin #ifdef __i386__
374fe760cfaSJohn Baldwin 	/* The TSC is known to be broken on certain CPUs. */
375fe760cfaSJohn Baldwin 	switch (cpu_vendor_id) {
376fe760cfaSJohn Baldwin 	case CPU_VENDOR_AMD:
377fe760cfaSJohn Baldwin 		switch (cpu_id & 0xFF0) {
378fe760cfaSJohn Baldwin 		case 0x500:
379fe760cfaSJohn Baldwin 			/* K5 Model 0 */
380fe760cfaSJohn Baldwin 			return;
381fe760cfaSJohn Baldwin 		}
382fe760cfaSJohn Baldwin 		break;
383fe760cfaSJohn Baldwin 	case CPU_VENDOR_CENTAUR:
384fe760cfaSJohn Baldwin 		switch (cpu_id & 0xff0) {
385fe760cfaSJohn Baldwin 		case 0x540:
386fe760cfaSJohn Baldwin 			/*
387fe760cfaSJohn Baldwin 			 * http://www.centtech.com/c6_data_sheet.pdf
388fe760cfaSJohn Baldwin 			 *
389fe760cfaSJohn Baldwin 			 * I-12 RDTSC may return incoherent values in EDX:EAX
390fe760cfaSJohn Baldwin 			 * I-13 RDTSC hangs when certain event counters are used
391fe760cfaSJohn Baldwin 			 */
392fe760cfaSJohn Baldwin 			return;
393fe760cfaSJohn Baldwin 		}
394fe760cfaSJohn Baldwin 		break;
395fe760cfaSJohn Baldwin 	case CPU_VENDOR_NSC:
396fe760cfaSJohn Baldwin 		switch (cpu_id & 0xff0) {
397fe760cfaSJohn Baldwin 		case 0x540:
398fe760cfaSJohn Baldwin 			if ((cpu_id & CPUID_STEPPING) == 0)
399fe760cfaSJohn Baldwin 				return;
400fe760cfaSJohn Baldwin 			break;
401fe760cfaSJohn Baldwin 		}
402fe760cfaSJohn Baldwin 		break;
403fe760cfaSJohn Baldwin 	}
404fe760cfaSJohn Baldwin #endif
405fe760cfaSJohn Baldwin 
406a4e4127fSJung-uk Kim 	probe_tsc_freq();
407a4e4127fSJung-uk Kim 
408dd7d207dSJung-uk Kim 	/*
409dd7d207dSJung-uk Kim 	 * Inform CPU accounting about our boot-time clock rate.  This will
410dd7d207dSJung-uk Kim 	 * be updated if someone loads a cpufreq driver after boot that
411dd7d207dSJung-uk Kim 	 * discovers a new max frequency.
41222875f88SMark Johnston 	 *
41322875f88SMark Johnston 	 * The frequency may also be updated after late calibration is complete;
41422875f88SMark Johnston 	 * however, we register the TSC as the ticker now to avoid switching
41522875f88SMark Johnston 	 * counters after much of the kernel has already booted and potentially
41622875f88SMark Johnston 	 * sampled the CPU clock.
417dd7d207dSJung-uk Kim 	 */
418a4e4127fSJung-uk Kim 	if (tsc_freq != 0)
4195ac44f72SJung-uk Kim 		set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
420dd7d207dSJung-uk Kim 
421dd7d207dSJung-uk Kim 	if (tsc_is_invariant)
422dd7d207dSJung-uk Kim 		return;
423dd7d207dSJung-uk Kim 
424dd7d207dSJung-uk Kim 	/* Register to find out about changes in CPU frequency. */
425dd7d207dSJung-uk Kim 	tsc_pre_tag = EVENTHANDLER_REGISTER(cpufreq_pre_change,
426dd7d207dSJung-uk Kim 	    tsc_freq_changing, NULL, EVENTHANDLER_PRI_FIRST);
427dd7d207dSJung-uk Kim 	tsc_post_tag = EVENTHANDLER_REGISTER(cpufreq_post_change,
428dd7d207dSJung-uk Kim 	    tsc_freq_changed, NULL, EVENTHANDLER_PRI_FIRST);
429dd7d207dSJung-uk Kim 	tsc_levels_tag = EVENTHANDLER_REGISTER(cpufreq_levels_changed,
430dd7d207dSJung-uk Kim 	    tsc_levels_changed, NULL, EVENTHANDLER_PRI_ANY);
431dd7d207dSJung-uk Kim }
432dd7d207dSJung-uk Kim 
43365e7d70bSJung-uk Kim #ifdef SMP
43465e7d70bSJung-uk Kim 
435814124c3SKonstantin Belousov /*
436814124c3SKonstantin Belousov  * RDTSC is not a serializing instruction, and does not drain
437814124c3SKonstantin Belousov  * instruction stream, so we need to drain the stream before executing
438814124c3SKonstantin Belousov  * it.  It could be fixed by use of RDTSCP, except the instruction is
439814124c3SKonstantin Belousov  * not available everywhere.
440814124c3SKonstantin Belousov  *
441814124c3SKonstantin Belousov  * Use CPUID for draining in the boot-time SMP constistency test.  The
442814124c3SKonstantin Belousov  * timecounters use MFENCE for AMD CPUs, and LFENCE for others (Intel
443814124c3SKonstantin Belousov  * and VIA) when SSE2 is present, and nothing on older machines which
444814124c3SKonstantin Belousov  * also do not issue RDTSC prematurely.  There, testing for SSE2 and
445e1a18e46SKonstantin Belousov  * vendor is too cumbersome, and we learn about TSC presence from CPUID.
446814124c3SKonstantin Belousov  *
447814124c3SKonstantin Belousov  * Do not use do_cpuid(), since we do not need CPUID results, which
448814124c3SKonstantin Belousov  * have to be written into memory with do_cpuid().
449814124c3SKonstantin Belousov  */
45065e7d70bSJung-uk Kim #define	TSC_READ(x)							\
45165e7d70bSJung-uk Kim static void								\
45265e7d70bSJung-uk Kim tsc_read_##x(void *arg)							\
45365e7d70bSJung-uk Kim {									\
4547bfcb3bbSJim Harris 	uint64_t *tsc = arg;						\
45565e7d70bSJung-uk Kim 	u_int cpu = PCPU_GET(cpuid);					\
45665e7d70bSJung-uk Kim 									\
457814124c3SKonstantin Belousov 	__asm __volatile("cpuid" : : : "eax", "ebx", "ecx", "edx");	\
4587bfcb3bbSJim Harris 	tsc[cpu * 3 + x] = rdtsc();					\
45965e7d70bSJung-uk Kim }
46065e7d70bSJung-uk Kim TSC_READ(0)
46165e7d70bSJung-uk Kim TSC_READ(1)
46265e7d70bSJung-uk Kim TSC_READ(2)
46365e7d70bSJung-uk Kim #undef TSC_READ
46465e7d70bSJung-uk Kim 
46565e7d70bSJung-uk Kim #define	N	1000
46665e7d70bSJung-uk Kim 
46765e7d70bSJung-uk Kim static void
46865e7d70bSJung-uk Kim comp_smp_tsc(void *arg)
46965e7d70bSJung-uk Kim {
4707bfcb3bbSJim Harris 	uint64_t *tsc;
4717bfcb3bbSJim Harris 	int64_t d1, d2;
47265e7d70bSJung-uk Kim 	u_int cpu = PCPU_GET(cpuid);
47365e7d70bSJung-uk Kim 	u_int i, j, size;
47465e7d70bSJung-uk Kim 
47565e7d70bSJung-uk Kim 	size = (mp_maxid + 1) * 3;
47665e7d70bSJung-uk Kim 	for (i = 0, tsc = arg; i < N; i++, tsc += size)
47765e7d70bSJung-uk Kim 		CPU_FOREACH(j) {
47865e7d70bSJung-uk Kim 			if (j == cpu)
47965e7d70bSJung-uk Kim 				continue;
48065e7d70bSJung-uk Kim 			d1 = tsc[cpu * 3 + 1] - tsc[j * 3];
48165e7d70bSJung-uk Kim 			d2 = tsc[cpu * 3 + 2] - tsc[j * 3 + 1];
48265e7d70bSJung-uk Kim 			if (d1 <= 0 || d2 <= 0) {
48365e7d70bSJung-uk Kim 				smp_tsc = 0;
48465e7d70bSJung-uk Kim 				return;
48565e7d70bSJung-uk Kim 			}
48665e7d70bSJung-uk Kim 		}
48765e7d70bSJung-uk Kim }
48865e7d70bSJung-uk Kim 
489b2c63698SAlexander Motin static void
490b2c63698SAlexander Motin adj_smp_tsc(void *arg)
491b2c63698SAlexander Motin {
492b2c63698SAlexander Motin 	uint64_t *tsc;
493b2c63698SAlexander Motin 	int64_t d, min, max;
494b2c63698SAlexander Motin 	u_int cpu = PCPU_GET(cpuid);
495b2c63698SAlexander Motin 	u_int first, i, size;
496b2c63698SAlexander Motin 
497b2c63698SAlexander Motin 	first = CPU_FIRST();
498b2c63698SAlexander Motin 	if (cpu == first)
499b2c63698SAlexander Motin 		return;
500b2c63698SAlexander Motin 	min = INT64_MIN;
501b2c63698SAlexander Motin 	max = INT64_MAX;
502b2c63698SAlexander Motin 	size = (mp_maxid + 1) * 3;
503b2c63698SAlexander Motin 	for (i = 0, tsc = arg; i < N; i++, tsc += size) {
504b2c63698SAlexander Motin 		d = tsc[first * 3] - tsc[cpu * 3 + 1];
505b2c63698SAlexander Motin 		if (d > min)
506b2c63698SAlexander Motin 			min = d;
507b2c63698SAlexander Motin 		d = tsc[first * 3 + 1] - tsc[cpu * 3 + 2];
508b2c63698SAlexander Motin 		if (d > min)
509b2c63698SAlexander Motin 			min = d;
510b2c63698SAlexander Motin 		d = tsc[first * 3 + 1] - tsc[cpu * 3];
511b2c63698SAlexander Motin 		if (d < max)
512b2c63698SAlexander Motin 			max = d;
513b2c63698SAlexander Motin 		d = tsc[first * 3 + 2] - tsc[cpu * 3 + 1];
514b2c63698SAlexander Motin 		if (d < max)
515b2c63698SAlexander Motin 			max = d;
516b2c63698SAlexander Motin 	}
517b2c63698SAlexander Motin 	if (min > max)
518b2c63698SAlexander Motin 		return;
519b2c63698SAlexander Motin 	d = min / 2 + max / 2;
520b2c63698SAlexander Motin 	__asm __volatile (
521b2c63698SAlexander Motin 		"movl $0x10, %%ecx\n\t"
522b2c63698SAlexander Motin 		"rdmsr\n\t"
523b2c63698SAlexander Motin 		"addl %%edi, %%eax\n\t"
524b2c63698SAlexander Motin 		"adcl %%esi, %%edx\n\t"
525b2c63698SAlexander Motin 		"wrmsr\n"
526b2c63698SAlexander Motin 		: /* No output */
527b2c63698SAlexander Motin 		: "D" ((uint32_t)d), "S" ((uint32_t)(d >> 32))
528b2c63698SAlexander Motin 		: "ax", "cx", "dx", "cc"
529b2c63698SAlexander Motin 	);
530b2c63698SAlexander Motin }
531b2c63698SAlexander Motin 
53265e7d70bSJung-uk Kim static int
533279be68bSAndriy Gapon test_tsc(int adj_max_count)
53465e7d70bSJung-uk Kim {
5357bfcb3bbSJim Harris 	uint64_t *data, *tsc;
536b2c63698SAlexander Motin 	u_int i, size, adj;
53765e7d70bSJung-uk Kim 
53884eaf2ccSKonstantin Belousov 	if ((!smp_tsc && !tsc_is_invariant))
53965e7d70bSJung-uk Kim 		return (-100);
5408cc15b0dSKyle Evans 	/*
5418cc15b0dSKyle Evans 	 * Misbehavior of TSC under VirtualBox has been observed.  In
5428cc15b0dSKyle Evans 	 * particular, threads doing small (~1 second) sleeps may miss their
5438cc15b0dSKyle Evans 	 * wakeup and hang around in sleep state, causing hangs on shutdown.
5448cc15b0dSKyle Evans 	 */
5458cc15b0dSKyle Evans 	if (vm_guest == VM_GUEST_VBOX)
5468cc15b0dSKyle Evans 		return (0);
5478cc15b0dSKyle Evans 
548cd165c8bSColin Percival 	TSENTER();
54965e7d70bSJung-uk Kim 	size = (mp_maxid + 1) * 3;
55065e7d70bSJung-uk Kim 	data = malloc(sizeof(*data) * size * N, M_TEMP, M_WAITOK);
551b2c63698SAlexander Motin 	adj = 0;
552b2c63698SAlexander Motin retry:
55365e7d70bSJung-uk Kim 	for (i = 0, tsc = data; i < N; i++, tsc += size)
55465e7d70bSJung-uk Kim 		smp_rendezvous(tsc_read_0, tsc_read_1, tsc_read_2, tsc);
55565e7d70bSJung-uk Kim 	smp_tsc = 1;	/* XXX */
55667d955aaSPatrick Kelsey 	smp_rendezvous(smp_no_rendezvous_barrier, comp_smp_tsc,
55767d955aaSPatrick Kelsey 	    smp_no_rendezvous_barrier, data);
558279be68bSAndriy Gapon 	if (!smp_tsc && adj < adj_max_count) {
559b2c63698SAlexander Motin 		adj++;
56067d955aaSPatrick Kelsey 		smp_rendezvous(smp_no_rendezvous_barrier, adj_smp_tsc,
56167d955aaSPatrick Kelsey 		    smp_no_rendezvous_barrier, data);
562b2c63698SAlexander Motin 		goto retry;
563b2c63698SAlexander Motin 	}
56465e7d70bSJung-uk Kim 	free(data, M_TEMP);
56565e7d70bSJung-uk Kim 	if (bootverbose)
566b2c63698SAlexander Motin 		printf("SMP: %sed TSC synchronization test%s\n",
567b2c63698SAlexander Motin 		    smp_tsc ? "pass" : "fail",
568b2c63698SAlexander Motin 		    adj > 0 ? " after adjustment" : "");
569cd165c8bSColin Percival 	TSEXIT();
57026e6537aSJung-uk Kim 	if (smp_tsc && tsc_is_invariant) {
57126e6537aSJung-uk Kim 		switch (cpu_vendor_id) {
57226e6537aSJung-uk Kim 		case CPU_VENDOR_AMD:
5732ee49facSKonstantin Belousov 		case CPU_VENDOR_HYGON:
57426e6537aSJung-uk Kim 			/*
575450d86fcSJung-uk Kim 			 * Processor Programming Reference (PPR) for AMD
576450d86fcSJung-uk Kim 			 * Family 17h states that the TSC uses a common
577450d86fcSJung-uk Kim 			 * reference for all sockets, cores and threads.
578450d86fcSJung-uk Kim 			 */
579450d86fcSJung-uk Kim 			if (CPUID_TO_FAMILY(cpu_id) >= 0x17)
580450d86fcSJung-uk Kim 				return (1000);
581450d86fcSJung-uk Kim 			/*
58226e6537aSJung-uk Kim 			 * Starting with Family 15h processors, TSC clock
58326e6537aSJung-uk Kim 			 * source is in the north bridge.  Check whether
58426e6537aSJung-uk Kim 			 * we have a single-socket/multi-core platform.
58526e6537aSJung-uk Kim 			 * XXX Need more work for complex cases.
58626e6537aSJung-uk Kim 			 */
58726e6537aSJung-uk Kim 			if (CPUID_TO_FAMILY(cpu_id) < 0x15 ||
58826e6537aSJung-uk Kim 			    (amd_feature2 & AMDID2_CMP) == 0 ||
58926e6537aSJung-uk Kim 			    smp_cpus > (cpu_procinfo2 & AMDID_CMP_CORES) + 1)
59026e6537aSJung-uk Kim 				break;
59126e6537aSJung-uk Kim 			return (1000);
59226e6537aSJung-uk Kim 		case CPU_VENDOR_INTEL:
59326e6537aSJung-uk Kim 			/*
59426e6537aSJung-uk Kim 			 * XXX Assume Intel platforms have synchronized TSCs.
59526e6537aSJung-uk Kim 			 */
59626e6537aSJung-uk Kim 			return (1000);
59726e6537aSJung-uk Kim 		}
59826e6537aSJung-uk Kim 		return (800);
59926e6537aSJung-uk Kim 	}
60026e6537aSJung-uk Kim 	return (-100);
60165e7d70bSJung-uk Kim }
60265e7d70bSJung-uk Kim 
60365e7d70bSJung-uk Kim #undef N
60465e7d70bSJung-uk Kim 
60565e7d70bSJung-uk Kim #endif /* SMP */
60665e7d70bSJung-uk Kim 
60765e7d70bSJung-uk Kim static void
608dd7d207dSJung-uk Kim init_TSC_tc(void)
609dd7d207dSJung-uk Kim {
61095f2f098SJung-uk Kim 	uint64_t max_freq;
61195f2f098SJung-uk Kim 	int shift;
612dd7d207dSJung-uk Kim 
61338b8542cSJung-uk Kim 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
614dd7d207dSJung-uk Kim 		return;
615dd7d207dSJung-uk Kim 
616dd7d207dSJung-uk Kim 	/*
61795f2f098SJung-uk Kim 	 * Limit timecounter frequency to fit in an int and prevent it from
61895f2f098SJung-uk Kim 	 * overflowing too fast.
61995f2f098SJung-uk Kim 	 */
62095f2f098SJung-uk Kim 	max_freq = UINT_MAX;
62195f2f098SJung-uk Kim 
62295f2f098SJung-uk Kim 	/*
62392597e06SJohn Baldwin 	 * Intel CPUs without a C-state invariant TSC can stop the TSC
624d1411416SJohn Baldwin 	 * in either C2 or C3.  Disable use of C2 and C3 while using
625d1411416SJohn Baldwin 	 * the TSC as the timecounter.  The timecounter can be changed
626d1411416SJohn Baldwin 	 * to enable C2 and C3.
627d1411416SJohn Baldwin 	 *
628d1411416SJohn Baldwin 	 * Note that the TSC is used as the cputicker for computing
629d1411416SJohn Baldwin 	 * thread runtime regardless of the timecounter setting, so
630d1411416SJohn Baldwin 	 * using an alternate timecounter and enabling C2 or C3 can
631d1411416SJohn Baldwin 	 * result incorrect runtimes for kernel idle threads (but not
632d1411416SJohn Baldwin 	 * for any non-idle threads).
633a49399a9SJung-uk Kim 	 */
6348cd59625SKonstantin Belousov 	if (cpu_vendor_id == CPU_VENDOR_INTEL &&
635a49399a9SJung-uk Kim 	    (amd_pminfo & AMDPM_TSC_INVARIANT) == 0) {
63692597e06SJohn Baldwin 		tsc_timecounter.tc_flags |= TC_FLAGS_C2STOP;
637a49399a9SJung-uk Kim 		if (bootverbose)
638d1411416SJohn Baldwin 			printf("TSC timecounter disables C2 and C3.\n");
639a49399a9SJung-uk Kim 	}
640a49399a9SJung-uk Kim 
641dd7d207dSJung-uk Kim 	/*
642e7f1427dSKonstantin Belousov 	 * We can not use the TSC in SMP mode unless the TSCs on all CPUs
643e7f1427dSKonstantin Belousov 	 * are synchronized.  If the user is sure that the system has
644e7f1427dSKonstantin Belousov 	 * synchronized TSCs, set kern.timecounter.smp_tsc tunable to a
645e7f1427dSKonstantin Belousov 	 * non-zero value.  The TSC seems unreliable in virtualized SMP
6465cf8ac1bSMike Silbersack 	 * environments, so it is set to a negative quality in those cases.
647dd7d207dSJung-uk Kim 	 */
648ba79ab82SAndriy Gapon #ifdef SMP
649e7f1427dSKonstantin Belousov 	if (mp_ncpus > 1)
650279be68bSAndriy Gapon 		tsc_timecounter.tc_quality = test_tsc(smp_tsc_adjust);
651ba79ab82SAndriy Gapon 	else
652ba79ab82SAndriy Gapon #endif /* SMP */
653ba79ab82SAndriy Gapon 	if (tsc_is_invariant)
65426e6537aSJung-uk Kim 		tsc_timecounter.tc_quality = 1000;
655e7f1427dSKonstantin Belousov 	max_freq >>= tsc_shift;
65626e6537aSJung-uk Kim 
657e7f1427dSKonstantin Belousov 	for (shift = 0; shift <= 31 && (tsc_freq >> shift) > max_freq; shift++)
65895f2f098SJung-uk Kim 		;
6599e680e40SKonstantin Belousov 
6609e680e40SKonstantin Belousov 	/*
6619e680e40SKonstantin Belousov 	 * Timecounter implementation selection, top to bottom:
6629e680e40SKonstantin Belousov 	 * - If RDTSCP is available, use RDTSCP.
6639e680e40SKonstantin Belousov 	 * - If fence instructions are provided (SSE2), use LFENCE;RDTSC
6649e680e40SKonstantin Belousov 	 *   on Intel, and MFENCE;RDTSC on AMD.
6659e680e40SKonstantin Belousov 	 * - For really old CPUs, just use RDTSC.
6669e680e40SKonstantin Belousov 	 */
6679f47eeffSKonstantin Belousov 	if ((amd_feature & AMDID_RDTSCP) != 0) {
6689e680e40SKonstantin Belousov 		tsc_timecounter.tc_get_timecount = shift > 0 ?
6699e680e40SKonstantin Belousov 		    tscp_get_timecount_low : tscp_get_timecount;
6709e680e40SKonstantin Belousov 	} else if ((cpu_feature & CPUID_SSE2) != 0 && mp_ncpus > 1) {
6712ee49facSKonstantin Belousov 		if (cpu_vendor_id == CPU_VENDOR_AMD ||
6722ee49facSKonstantin Belousov 		    cpu_vendor_id == CPU_VENDOR_HYGON) {
673e7f1427dSKonstantin Belousov 			tsc_timecounter.tc_get_timecount = shift > 0 ?
674e7f1427dSKonstantin Belousov 			    tsc_get_timecount_low_mfence :
675e7f1427dSKonstantin Belousov 			    tsc_get_timecount_mfence;
676814124c3SKonstantin Belousov 		} else {
677e7f1427dSKonstantin Belousov 			tsc_timecounter.tc_get_timecount = shift > 0 ?
678e7f1427dSKonstantin Belousov 			    tsc_get_timecount_low_lfence :
679e7f1427dSKonstantin Belousov 			    tsc_get_timecount_lfence;
680814124c3SKonstantin Belousov 		}
681e7f1427dSKonstantin Belousov 	} else {
682e7f1427dSKonstantin Belousov 		tsc_timecounter.tc_get_timecount = shift > 0 ?
683e7f1427dSKonstantin Belousov 		    tsc_get_timecount_low : tsc_get_timecount;
684e7f1427dSKonstantin Belousov 	}
685e7f1427dSKonstantin Belousov 	if (shift > 0) {
68695f2f098SJung-uk Kim 		tsc_timecounter.tc_name = "TSC-low";
68795f2f098SJung-uk Kim 		if (bootverbose)
688bc8e4ad2SJung-uk Kim 			printf("TSC timecounter discards lower %d bit(s)\n",
68995f2f098SJung-uk Kim 			    shift);
69095f2f098SJung-uk Kim 	}
691bc34c87eSJung-uk Kim 	if (tsc_freq != 0) {
69295f2f098SJung-uk Kim 		tsc_timecounter.tc_frequency = tsc_freq >> shift;
69395f2f098SJung-uk Kim 		tsc_timecounter.tc_priv = (void *)(intptr_t)shift;
69422875f88SMark Johnston 
69522875f88SMark Johnston 		/*
69622875f88SMark Johnston 		 * Timecounter registration is deferred until after late
69722875f88SMark Johnston 		 * calibration is finished.
69822875f88SMark Johnston 		 */
699dd7d207dSJung-uk Kim 	}
700dd7d207dSJung-uk Kim }
70165e7d70bSJung-uk Kim SYSINIT(tsc_tc, SI_SUB_SMP, SI_ORDER_ANY, init_TSC_tc, NULL);
702dd7d207dSJung-uk Kim 
70322875f88SMark Johnston static void
70422875f88SMark Johnston tsc_update_freq(uint64_t new_freq)
70522875f88SMark Johnston {
70622875f88SMark Johnston 	atomic_store_rel_64(&tsc_freq, new_freq);
70722875f88SMark Johnston 	atomic_store_rel_64(&tsc_timecounter.tc_frequency,
70822875f88SMark Johnston 	    new_freq >> (int)(intptr_t)tsc_timecounter.tc_priv);
70922875f88SMark Johnston }
71022875f88SMark Johnston 
71122875f88SMark Johnston /*
71222875f88SMark Johnston  * Perform late calibration of the TSC frequency once ACPI-based timecounters
713553af8f1SMark Johnston  * are available.  At this point timehands are not set up, so we read the
714553af8f1SMark Johnston  * highest-quality timecounter directly rather than using (s)binuptime().
71522875f88SMark Johnston  */
716553af8f1SMark Johnston void
717553af8f1SMark Johnston tsc_calibrate(void)
71822875f88SMark Johnston {
719c2705ceaSColin Percival 	uint64_t freq;
72022875f88SMark Johnston 
72122875f88SMark Johnston 	if (tsc_disabled)
72222875f88SMark Johnston 		return;
7239cb32882SColin Percival 	if (tsc_early_calib_exact)
7249cb32882SColin Percival 		goto calibrated;
72522875f88SMark Johnston 
726c2705ceaSColin Percival 	fpu_kern_enter(curthread, NULL, FPU_KERN_NOCTX);
727c2705ceaSColin Percival 	freq = clockcalib(rdtsc_ordered, "TSC");
728c2705ceaSColin Percival 	fpu_kern_leave(curthread, NULL);
729698727d6SColin Percival 	tsc_update_freq(freq);
730c2705ceaSColin Percival 
7319cb32882SColin Percival calibrated:
73222875f88SMark Johnston 	tc_init(&tsc_timecounter);
73322875f88SMark Johnston 	set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
73422875f88SMark Johnston }
73522875f88SMark Johnston 
736279be68bSAndriy Gapon void
737279be68bSAndriy Gapon resume_TSC(void)
738279be68bSAndriy Gapon {
739ba79ab82SAndriy Gapon #ifdef SMP
740279be68bSAndriy Gapon 	int quality;
741279be68bSAndriy Gapon 
742279be68bSAndriy Gapon 	/* If TSC was not good on boot, it is unlikely to become good now. */
743279be68bSAndriy Gapon 	if (tsc_timecounter.tc_quality < 0)
744279be68bSAndriy Gapon 		return;
745279be68bSAndriy Gapon 	/* Nothing to do with UP. */
746279be68bSAndriy Gapon 	if (mp_ncpus < 2)
747279be68bSAndriy Gapon 		return;
748279be68bSAndriy Gapon 
749279be68bSAndriy Gapon 	/*
750279be68bSAndriy Gapon 	 * If TSC was good, a single synchronization should be enough,
751279be68bSAndriy Gapon 	 * but honour smp_tsc_adjust if it's set.
752279be68bSAndriy Gapon 	 */
753279be68bSAndriy Gapon 	quality = test_tsc(MAX(smp_tsc_adjust, 1));
754279be68bSAndriy Gapon 	if (quality != tsc_timecounter.tc_quality) {
755279be68bSAndriy Gapon 		printf("TSC timecounter quality changed: %d -> %d\n",
756279be68bSAndriy Gapon 		    tsc_timecounter.tc_quality, quality);
757279be68bSAndriy Gapon 		tsc_timecounter.tc_quality = quality;
758279be68bSAndriy Gapon 	}
759ba79ab82SAndriy Gapon #endif /* SMP */
760279be68bSAndriy Gapon }
761279be68bSAndriy Gapon 
762dd7d207dSJung-uk Kim /*
763dd7d207dSJung-uk Kim  * When cpufreq levels change, find out about the (new) max frequency.  We
764dd7d207dSJung-uk Kim  * use this to update CPU accounting in case it got a lower estimate at boot.
765dd7d207dSJung-uk Kim  */
766dd7d207dSJung-uk Kim static void
767dd7d207dSJung-uk Kim tsc_levels_changed(void *arg, int unit)
768dd7d207dSJung-uk Kim {
769dd7d207dSJung-uk Kim 	device_t cf_dev;
770dd7d207dSJung-uk Kim 	struct cf_level *levels;
771dd7d207dSJung-uk Kim 	int count, error;
772dd7d207dSJung-uk Kim 	uint64_t max_freq;
773dd7d207dSJung-uk Kim 
774dd7d207dSJung-uk Kim 	/* Only use values from the first CPU, assuming all are equal. */
775dd7d207dSJung-uk Kim 	if (unit != 0)
776dd7d207dSJung-uk Kim 		return;
777dd7d207dSJung-uk Kim 
778dd7d207dSJung-uk Kim 	/* Find the appropriate cpufreq device instance. */
779dd7d207dSJung-uk Kim 	cf_dev = devclass_get_device(devclass_find("cpufreq"), unit);
780dd7d207dSJung-uk Kim 	if (cf_dev == NULL) {
781dd7d207dSJung-uk Kim 		printf("tsc_levels_changed() called but no cpufreq device?\n");
782dd7d207dSJung-uk Kim 		return;
783dd7d207dSJung-uk Kim 	}
784dd7d207dSJung-uk Kim 
785dd7d207dSJung-uk Kim 	/* Get settings from the device and find the max frequency. */
786dd7d207dSJung-uk Kim 	count = 64;
787dd7d207dSJung-uk Kim 	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
788dd7d207dSJung-uk Kim 	if (levels == NULL)
789dd7d207dSJung-uk Kim 		return;
790dd7d207dSJung-uk Kim 	error = CPUFREQ_LEVELS(cf_dev, levels, &count);
791dd7d207dSJung-uk Kim 	if (error == 0 && count != 0) {
792dd7d207dSJung-uk Kim 		max_freq = (uint64_t)levels[0].total_set.freq * 1000000;
793dd7d207dSJung-uk Kim 		set_cputicker(rdtsc, max_freq, 1);
794dd7d207dSJung-uk Kim 	} else
795dd7d207dSJung-uk Kim 		printf("tsc_levels_changed: no max freq found\n");
796dd7d207dSJung-uk Kim 	free(levels, M_TEMP);
797dd7d207dSJung-uk Kim }
798dd7d207dSJung-uk Kim 
799dd7d207dSJung-uk Kim /*
800dd7d207dSJung-uk Kim  * If the TSC timecounter is in use, veto the pending change.  It may be
801dd7d207dSJung-uk Kim  * possible in the future to handle a dynamically-changing timecounter rate.
802dd7d207dSJung-uk Kim  */
803dd7d207dSJung-uk Kim static void
804dd7d207dSJung-uk Kim tsc_freq_changing(void *arg, const struct cf_level *level, int *status)
805dd7d207dSJung-uk Kim {
806dd7d207dSJung-uk Kim 
807dd7d207dSJung-uk Kim 	if (*status != 0 || timecounter != &tsc_timecounter)
808dd7d207dSJung-uk Kim 		return;
809dd7d207dSJung-uk Kim 
810dd7d207dSJung-uk Kim 	printf("timecounter TSC must not be in use when "
811dd7d207dSJung-uk Kim 	    "changing frequencies; change denied\n");
812dd7d207dSJung-uk Kim 	*status = EBUSY;
813dd7d207dSJung-uk Kim }
814dd7d207dSJung-uk Kim 
815dd7d207dSJung-uk Kim /* Update TSC freq with the value indicated by the caller. */
816dd7d207dSJung-uk Kim static void
817dd7d207dSJung-uk Kim tsc_freq_changed(void *arg, const struct cf_level *level, int status)
818dd7d207dSJung-uk Kim {
8193453537fSJung-uk Kim 	uint64_t freq;
820dd7d207dSJung-uk Kim 
821dd7d207dSJung-uk Kim 	/* If there was an error during the transition, don't do anything. */
82279422085SJung-uk Kim 	if (tsc_disabled || status != 0)
823dd7d207dSJung-uk Kim 		return;
824dd7d207dSJung-uk Kim 
825dd7d207dSJung-uk Kim 	/* Total setting for this level gives the new frequency in MHz. */
8263453537fSJung-uk Kim 	freq = (uint64_t)level->total_set.freq * 1000000;
82722875f88SMark Johnston 	tsc_update_freq(freq);
828dd7d207dSJung-uk Kim }
829dd7d207dSJung-uk Kim 
830dd7d207dSJung-uk Kim static int
831dd7d207dSJung-uk Kim sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
832dd7d207dSJung-uk Kim {
833dd7d207dSJung-uk Kim 	int error;
834dd7d207dSJung-uk Kim 	uint64_t freq;
835dd7d207dSJung-uk Kim 
8363453537fSJung-uk Kim 	freq = atomic_load_acq_64(&tsc_freq);
8373453537fSJung-uk Kim 	if (freq == 0)
838dd7d207dSJung-uk Kim 		return (EOPNOTSUPP);
839cbc134adSMatthew D Fleming 	error = sysctl_handle_64(oidp, &freq, 0, req);
84022875f88SMark Johnston 	if (error == 0 && req->newptr != NULL)
84122875f88SMark Johnston 		tsc_update_freq(freq);
842dd7d207dSJung-uk Kim 	return (error);
843dd7d207dSJung-uk Kim }
8447029da5cSPawel Biernacki SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq,
8451d6fb900SAlexander Motin     CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
8467029da5cSPawel Biernacki     0, 0, sysctl_machdep_tsc_freq, "QU",
8477029da5cSPawel Biernacki     "Time Stamp Counter frequency");
848dd7d207dSJung-uk Kim 
849727c7b2dSJung-uk Kim static u_int
85095f2f098SJung-uk Kim tsc_get_timecount(struct timecounter *tc __unused)
851dd7d207dSJung-uk Kim {
852727c7b2dSJung-uk Kim 
853727c7b2dSJung-uk Kim 	return (rdtsc32());
854dd7d207dSJung-uk Kim }
85595f2f098SJung-uk Kim 
8569e680e40SKonstantin Belousov static u_int
8579e680e40SKonstantin Belousov tscp_get_timecount(struct timecounter *tc __unused)
8589e680e40SKonstantin Belousov {
8599e680e40SKonstantin Belousov 
8609e680e40SKonstantin Belousov 	return (rdtscp32());
8619e680e40SKonstantin Belousov }
8629e680e40SKonstantin Belousov 
863814124c3SKonstantin Belousov static inline u_int
864bc8e4ad2SJung-uk Kim tsc_get_timecount_low(struct timecounter *tc)
86595f2f098SJung-uk Kim {
8665df88f46SJung-uk Kim 	uint32_t rv;
86795f2f098SJung-uk Kim 
8685df88f46SJung-uk Kim 	__asm __volatile("rdtsc; shrd %%cl, %%edx, %0"
8695df88f46SJung-uk Kim 	    : "=a" (rv) : "c" ((int)(intptr_t)tc->tc_priv) : "edx");
8705df88f46SJung-uk Kim 	return (rv);
87195f2f098SJung-uk Kim }
872aea81038SKonstantin Belousov 
873814124c3SKonstantin Belousov static u_int
8749e680e40SKonstantin Belousov tscp_get_timecount_low(struct timecounter *tc)
8759e680e40SKonstantin Belousov {
8769e680e40SKonstantin Belousov 	uint32_t rv;
8779e680e40SKonstantin Belousov 
8789e680e40SKonstantin Belousov 	__asm __volatile("rdtscp; movl %1, %%ecx; shrd %%cl, %%edx, %0"
879a013e285SKonstantin Belousov 	    : "=&a" (rv) : "m" (tc->tc_priv) : "ecx", "edx");
8809e680e40SKonstantin Belousov 	return (rv);
8819e680e40SKonstantin Belousov }
8829e680e40SKonstantin Belousov 
8839e680e40SKonstantin Belousov static u_int
884814124c3SKonstantin Belousov tsc_get_timecount_lfence(struct timecounter *tc __unused)
885814124c3SKonstantin Belousov {
886814124c3SKonstantin Belousov 
887814124c3SKonstantin Belousov 	lfence();
888814124c3SKonstantin Belousov 	return (rdtsc32());
889814124c3SKonstantin Belousov }
890814124c3SKonstantin Belousov 
891814124c3SKonstantin Belousov static u_int
892814124c3SKonstantin Belousov tsc_get_timecount_low_lfence(struct timecounter *tc)
893814124c3SKonstantin Belousov {
894814124c3SKonstantin Belousov 
895814124c3SKonstantin Belousov 	lfence();
896814124c3SKonstantin Belousov 	return (tsc_get_timecount_low(tc));
897814124c3SKonstantin Belousov }
898814124c3SKonstantin Belousov 
899814124c3SKonstantin Belousov static u_int
900814124c3SKonstantin Belousov tsc_get_timecount_mfence(struct timecounter *tc __unused)
901814124c3SKonstantin Belousov {
902814124c3SKonstantin Belousov 
903814124c3SKonstantin Belousov 	mfence();
904814124c3SKonstantin Belousov 	return (rdtsc32());
905814124c3SKonstantin Belousov }
906814124c3SKonstantin Belousov 
907814124c3SKonstantin Belousov static u_int
908814124c3SKonstantin Belousov tsc_get_timecount_low_mfence(struct timecounter *tc)
909814124c3SKonstantin Belousov {
910814124c3SKonstantin Belousov 
911814124c3SKonstantin Belousov 	mfence();
912814124c3SKonstantin Belousov 	return (tsc_get_timecount_low(tc));
913814124c3SKonstantin Belousov }
914814124c3SKonstantin Belousov 
91516808549SKonstantin Belousov static uint32_t
91616808549SKonstantin Belousov x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th, struct timecounter *tc)
917aea81038SKonstantin Belousov {
918aea81038SKonstantin Belousov 
91916808549SKonstantin Belousov 	vdso_th->th_algo = VDSO_TH_ALGO_X86_TSC;
920d1b1b600SNeel Natu 	vdso_th->th_x86_shift = (int)(intptr_t)tc->tc_priv;
92116808549SKonstantin Belousov 	vdso_th->th_x86_hpet_idx = 0xffffffff;
922d4b2d303SAdam Fenn 	vdso_th->th_x86_pvc_last_systime = 0;
923d4b2d303SAdam Fenn 	vdso_th->th_x86_pvc_stable_mask = 0;
924aea81038SKonstantin Belousov 	bzero(vdso_th->th_res, sizeof(vdso_th->th_res));
92516808549SKonstantin Belousov 	return (1);
926aea81038SKonstantin Belousov }
927aea81038SKonstantin Belousov 
928aea81038SKonstantin Belousov #ifdef COMPAT_FREEBSD32
92916808549SKonstantin Belousov static uint32_t
93016808549SKonstantin Belousov x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
931d1b1b600SNeel Natu     struct timecounter *tc)
932aea81038SKonstantin Belousov {
933aea81038SKonstantin Belousov 
93416808549SKonstantin Belousov 	vdso_th32->th_algo = VDSO_TH_ALGO_X86_TSC;
935d1b1b600SNeel Natu 	vdso_th32->th_x86_shift = (int)(intptr_t)tc->tc_priv;
93616808549SKonstantin Belousov 	vdso_th32->th_x86_hpet_idx = 0xffffffff;
937d4b2d303SAdam Fenn 	vdso_th32->th_x86_pvc_last_systime = 0;
938d4b2d303SAdam Fenn 	vdso_th32->th_x86_pvc_stable_mask = 0;
939aea81038SKonstantin Belousov 	bzero(vdso_th32->th_res, sizeof(vdso_th32->th_res));
94016808549SKonstantin Belousov 	return (1);
941aea81038SKonstantin Belousov }
942aea81038SKonstantin Belousov #endif
943