xref: /freebsd/sys/x86/x86/tsc.c (revision 1d6fb900ed90d1fd6547e2d79da9d0259f450c2c)
1dd7d207dSJung-uk Kim /*-
2ebf5747bSPedro F. Giffuni  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3ebf5747bSPedro F. Giffuni  *
4dd7d207dSJung-uk Kim  * Copyright (c) 1998-2003 Poul-Henning Kamp
5dd7d207dSJung-uk Kim  * All rights reserved.
6dd7d207dSJung-uk Kim  *
7dd7d207dSJung-uk Kim  * Redistribution and use in source and binary forms, with or without
8dd7d207dSJung-uk Kim  * modification, are permitted provided that the following conditions
9dd7d207dSJung-uk Kim  * are met:
10dd7d207dSJung-uk Kim  * 1. Redistributions of source code must retain the above copyright
11dd7d207dSJung-uk Kim  *    notice, this list of conditions and the following disclaimer.
12dd7d207dSJung-uk Kim  * 2. Redistributions in binary form must reproduce the above copyright
13dd7d207dSJung-uk Kim  *    notice, this list of conditions and the following disclaimer in the
14dd7d207dSJung-uk Kim  *    documentation and/or other materials provided with the distribution.
15dd7d207dSJung-uk Kim  *
16dd7d207dSJung-uk Kim  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17dd7d207dSJung-uk Kim  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18dd7d207dSJung-uk Kim  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19dd7d207dSJung-uk Kim  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20dd7d207dSJung-uk Kim  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21dd7d207dSJung-uk Kim  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22dd7d207dSJung-uk Kim  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23dd7d207dSJung-uk Kim  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24dd7d207dSJung-uk Kim  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25dd7d207dSJung-uk Kim  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26dd7d207dSJung-uk Kim  * SUCH DAMAGE.
27dd7d207dSJung-uk Kim  */
28dd7d207dSJung-uk Kim 
29dd7d207dSJung-uk Kim #include <sys/cdefs.h>
30dd7d207dSJung-uk Kim __FBSDID("$FreeBSD$");
31dd7d207dSJung-uk Kim 
32dd7d207dSJung-uk Kim #include "opt_clock.h"
33dd7d207dSJung-uk Kim 
34dd7d207dSJung-uk Kim #include <sys/param.h>
3522875f88SMark Johnston #include <sys/systm.h>
36dd7d207dSJung-uk Kim #include <sys/bus.h>
37dd7d207dSJung-uk Kim #include <sys/cpu.h>
38e2e050c8SConrad Meyer #include <sys/eventhandler.h>
395da5812bSJung-uk Kim #include <sys/limits.h>
40dd7d207dSJung-uk Kim #include <sys/malloc.h>
4122875f88SMark Johnston #include <sys/proc.h>
4222875f88SMark Johnston #include <sys/sched.h>
43dd7d207dSJung-uk Kim #include <sys/sysctl.h>
44dd7d207dSJung-uk Kim #include <sys/time.h>
45dd7d207dSJung-uk Kim #include <sys/timetc.h>
46dd7d207dSJung-uk Kim #include <sys/kernel.h>
47dd7d207dSJung-uk Kim #include <sys/smp.h>
48aea81038SKonstantin Belousov #include <sys/vdso.h>
49dd7d207dSJung-uk Kim #include <machine/clock.h>
50dd7d207dSJung-uk Kim #include <machine/cputypes.h>
51dd7d207dSJung-uk Kim #include <machine/md_var.h>
52dd7d207dSJung-uk Kim #include <machine/specialreg.h>
5301e1933dSJohn Baldwin #include <x86/vmware.h>
5416808549SKonstantin Belousov #include <dev/acpica/acpi_hpet.h>
55ce3bf750SKonstantin Belousov #include <contrib/dev/acpica/include/acpi.h>
56dd7d207dSJung-uk Kim 
57dd7d207dSJung-uk Kim #include "cpufreq_if.h"
58dd7d207dSJung-uk Kim 
59dd7d207dSJung-uk Kim uint64_t	tsc_freq;
60dd7d207dSJung-uk Kim int		tsc_is_invariant;
61155094d7SJung-uk Kim int		tsc_perf_stat;
62155094d7SJung-uk Kim 
63dd7d207dSJung-uk Kim static eventhandler_tag tsc_levels_tag, tsc_pre_tag, tsc_post_tag;
64dd7d207dSJung-uk Kim 
65dd7d207dSJung-uk Kim SYSCTL_INT(_kern_timecounter, OID_AUTO, invariant_tsc, CTLFLAG_RDTUN,
66dd7d207dSJung-uk Kim     &tsc_is_invariant, 0, "Indicates whether the TSC is P-state invariant");
67dd7d207dSJung-uk Kim 
68dd7d207dSJung-uk Kim #ifdef SMP
691472b87fSNeel Natu int	smp_tsc;
70dd7d207dSJung-uk Kim SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc, CTLFLAG_RDTUN, &smp_tsc, 0,
71dd7d207dSJung-uk Kim     "Indicates whether the TSC is safe to use in SMP mode");
72b2c63698SAlexander Motin 
73b2c63698SAlexander Motin int	smp_tsc_adjust = 0;
74b2c63698SAlexander Motin SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc_adjust, CTLFLAG_RDTUN,
75b2c63698SAlexander Motin     &smp_tsc_adjust, 0, "Try to adjust TSC on APs to match BSP");
76dd7d207dSJung-uk Kim #endif
77dd7d207dSJung-uk Kim 
78e7f1427dSKonstantin Belousov static int	tsc_shift = 1;
79e7f1427dSKonstantin Belousov SYSCTL_INT(_kern_timecounter, OID_AUTO, tsc_shift, CTLFLAG_RDTUN,
80e7f1427dSKonstantin Belousov     &tsc_shift, 0, "Shift to pre-apply for the maximum TSC frequency");
81e7f1427dSKonstantin Belousov 
8279422085SJung-uk Kim static int	tsc_disabled;
8379422085SJung-uk Kim SYSCTL_INT(_machdep, OID_AUTO, disable_tsc, CTLFLAG_RDTUN, &tsc_disabled, 0,
8479422085SJung-uk Kim     "Disable x86 Time Stamp Counter");
8579422085SJung-uk Kim 
86a4e4127fSJung-uk Kim static int	tsc_skip_calibration;
87ab23c278SKonstantin Belousov SYSCTL_INT(_machdep, OID_AUTO, disable_tsc_calibration, CTLFLAG_RDTUN,
88ab23c278SKonstantin Belousov     &tsc_skip_calibration, 0,
8922875f88SMark Johnston     "Disable early TSC frequency calibration");
90a4e4127fSJung-uk Kim 
91dd7d207dSJung-uk Kim static void tsc_freq_changed(void *arg, const struct cf_level *level,
92dd7d207dSJung-uk Kim     int status);
93dd7d207dSJung-uk Kim static void tsc_freq_changing(void *arg, const struct cf_level *level,
94dd7d207dSJung-uk Kim     int *status);
95826fc3ccSKonstantin Belousov static u_int tsc_get_timecount(struct timecounter *tc);
96826fc3ccSKonstantin Belousov static inline u_int tsc_get_timecount_low(struct timecounter *tc);
97826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_lfence(struct timecounter *tc);
98826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_low_lfence(struct timecounter *tc);
99826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_mfence(struct timecounter *tc);
100826fc3ccSKonstantin Belousov static u_int tsc_get_timecount_low_mfence(struct timecounter *tc);
1019e680e40SKonstantin Belousov static u_int tscp_get_timecount(struct timecounter *tc);
1029e680e40SKonstantin Belousov static u_int tscp_get_timecount_low(struct timecounter *tc);
103dd7d207dSJung-uk Kim static void tsc_levels_changed(void *arg, int unit);
10416808549SKonstantin Belousov static uint32_t x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th,
10516808549SKonstantin Belousov     struct timecounter *tc);
10616808549SKonstantin Belousov #ifdef COMPAT_FREEBSD32
10716808549SKonstantin Belousov static uint32_t x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
10816808549SKonstantin Belousov     struct timecounter *tc);
10916808549SKonstantin Belousov #endif
110dd7d207dSJung-uk Kim 
111dd7d207dSJung-uk Kim static struct timecounter tsc_timecounter = {
11216808549SKonstantin Belousov 	.tc_get_timecount =		tsc_get_timecount,
11316808549SKonstantin Belousov 	.tc_counter_mask =		~0u,
11416808549SKonstantin Belousov 	.tc_name =			"TSC",
11516808549SKonstantin Belousov 	.tc_quality =			800,	/* adjusted in code */
11616808549SKonstantin Belousov 	.tc_fill_vdso_timehands = 	x86_tsc_vdso_timehands,
11716808549SKonstantin Belousov #ifdef COMPAT_FREEBSD32
11816808549SKonstantin Belousov 	.tc_fill_vdso_timehands32 = 	x86_tsc_vdso_timehands32,
11916808549SKonstantin Belousov #endif
120dd7d207dSJung-uk Kim };
121dd7d207dSJung-uk Kim 
12201e1933dSJohn Baldwin static void
1235da5812bSJung-uk Kim tsc_freq_vmware(void)
1245da5812bSJung-uk Kim {
1255da5812bSJung-uk Kim 	u_int regs[4];
1265da5812bSJung-uk Kim 
1275da5812bSJung-uk Kim 	if (hv_high >= 0x40000010) {
1285da5812bSJung-uk Kim 		do_cpuid(0x40000010, regs);
1295da5812bSJung-uk Kim 		tsc_freq = regs[0] * 1000;
1305da5812bSJung-uk Kim 	} else {
1315da5812bSJung-uk Kim 		vmware_hvcall(VMW_HVCMD_GETHZ, regs);
1325da5812bSJung-uk Kim 		if (regs[1] != UINT_MAX)
1335da5812bSJung-uk Kim 			tsc_freq = regs[0] | ((uint64_t)regs[1] << 32);
1345da5812bSJung-uk Kim 	}
1355da5812bSJung-uk Kim 	tsc_is_invariant = 1;
1365da5812bSJung-uk Kim }
1375da5812bSJung-uk Kim 
138506a906cSKonstantin Belousov /*
13922875f88SMark Johnston  * Calculate TSC frequency using information from the CPUID leaf 0x15 'Time
14022875f88SMark Johnston  * Stamp Counter and Nominal Core Crystal Clock'.  If leaf 0x15 is not
14122875f88SMark Johnston  * functional, as it is on Skylake/Kabylake, try 0x16 'Processor Frequency
14222875f88SMark Johnston  * Information'.  Leaf 0x16 is described in the SDM as informational only, but
14322875f88SMark Johnston  * we can use this value until late calibration is complete.
144506a906cSKonstantin Belousov  */
145506a906cSKonstantin Belousov static bool
146bd8a359fSKonstantin Belousov tsc_freq_cpuid(uint64_t *res)
147506a906cSKonstantin Belousov {
148506a906cSKonstantin Belousov 	u_int regs[4];
149506a906cSKonstantin Belousov 
150506a906cSKonstantin Belousov 	if (cpu_high < 0x15)
151506a906cSKonstantin Belousov 		return (false);
152506a906cSKonstantin Belousov 	do_cpuid(0x15, regs);
153a9d0e007SKonstantin Belousov 	if (regs[0] != 0 && regs[1] != 0 && regs[2] != 0) {
154bd8a359fSKonstantin Belousov 		*res = (uint64_t)regs[2] * regs[1] / regs[0];
155506a906cSKonstantin Belousov 		return (true);
156506a906cSKonstantin Belousov 	}
157506a906cSKonstantin Belousov 
158a9d0e007SKonstantin Belousov 	if (cpu_high < 0x16)
159a9d0e007SKonstantin Belousov 		return (false);
160a9d0e007SKonstantin Belousov 	do_cpuid(0x16, regs);
161a9d0e007SKonstantin Belousov 	if (regs[0] != 0) {
162bd8a359fSKonstantin Belousov 		*res = (uint64_t)regs[0] * 1000000;
163a9d0e007SKonstantin Belousov 		return (true);
164a9d0e007SKonstantin Belousov 	}
165a9d0e007SKonstantin Belousov 
166a9d0e007SKonstantin Belousov 	return (false);
167a9d0e007SKonstantin Belousov }
168a9d0e007SKonstantin Belousov 
16922875f88SMark Johnston static bool
17022875f88SMark Johnston tsc_freq_intel_brand(uint64_t *res)
171dd7d207dSJung-uk Kim {
172a4e4127fSJung-uk Kim 	char brand[48];
173a4e4127fSJung-uk Kim 	u_int regs[4];
174a4e4127fSJung-uk Kim 	uint64_t freq;
175a4e4127fSJung-uk Kim 	char *p;
176a4e4127fSJung-uk Kim 	u_int i;
177dd7d207dSJung-uk Kim 
178a4e4127fSJung-uk Kim 	/*
179a4e4127fSJung-uk Kim 	 * Intel Processor Identification and the CPUID Instruction
180a4e4127fSJung-uk Kim 	 * Application Note 485.
181a4e4127fSJung-uk Kim 	 * http://www.intel.com/assets/pdf/appnote/241618.pdf
182a4e4127fSJung-uk Kim 	 */
183a4e4127fSJung-uk Kim 	if (cpu_exthigh >= 0x80000004) {
184a4e4127fSJung-uk Kim 		p = brand;
185a4e4127fSJung-uk Kim 		for (i = 0x80000002; i < 0x80000005; i++) {
186a4e4127fSJung-uk Kim 			do_cpuid(i, regs);
187a4e4127fSJung-uk Kim 			memcpy(p, regs, sizeof(regs));
188a4e4127fSJung-uk Kim 			p += sizeof(regs);
189a4e4127fSJung-uk Kim 		}
190a4e4127fSJung-uk Kim 		p = NULL;
191a4e4127fSJung-uk Kim 		for (i = 0; i < sizeof(brand) - 1; i++)
192a4e4127fSJung-uk Kim 			if (brand[i] == 'H' && brand[i + 1] == 'z')
193a4e4127fSJung-uk Kim 				p = brand + i;
194a4e4127fSJung-uk Kim 		if (p != NULL) {
195a4e4127fSJung-uk Kim 			p -= 5;
196a4e4127fSJung-uk Kim 			switch (p[4]) {
197a4e4127fSJung-uk Kim 			case 'M':
198a4e4127fSJung-uk Kim 				i = 1;
199a4e4127fSJung-uk Kim 				break;
200a4e4127fSJung-uk Kim 			case 'G':
201a4e4127fSJung-uk Kim 				i = 1000;
202a4e4127fSJung-uk Kim 				break;
203a4e4127fSJung-uk Kim 			case 'T':
204a4e4127fSJung-uk Kim 				i = 1000000;
205a4e4127fSJung-uk Kim 				break;
206a4e4127fSJung-uk Kim 			default:
20722875f88SMark Johnston 				return (false);
208a4e4127fSJung-uk Kim 			}
209a4e4127fSJung-uk Kim #define	C2D(c)	((c) - '0')
210a4e4127fSJung-uk Kim 			if (p[1] == '.') {
211a4e4127fSJung-uk Kim 				freq = C2D(p[0]) * 1000;
212a4e4127fSJung-uk Kim 				freq += C2D(p[2]) * 100;
213a4e4127fSJung-uk Kim 				freq += C2D(p[3]) * 10;
214a4e4127fSJung-uk Kim 				freq *= i * 1000;
215a4e4127fSJung-uk Kim 			} else {
216a4e4127fSJung-uk Kim 				freq = C2D(p[0]) * 1000;
217a4e4127fSJung-uk Kim 				freq += C2D(p[1]) * 100;
218a4e4127fSJung-uk Kim 				freq += C2D(p[2]) * 10;
219a4e4127fSJung-uk Kim 				freq += C2D(p[3]);
220a4e4127fSJung-uk Kim 				freq *= i * 1000000;
221a4e4127fSJung-uk Kim 			}
222a4e4127fSJung-uk Kim #undef C2D
22322875f88SMark Johnston 			*res = freq;
22422875f88SMark Johnston 			return (true);
225a4e4127fSJung-uk Kim 		}
226a4e4127fSJung-uk Kim 	}
22722875f88SMark Johnston 	return (false);
22822875f88SMark Johnston }
22922875f88SMark Johnston 
23022875f88SMark Johnston static void
23122875f88SMark Johnston tsc_freq_8254(uint64_t *res)
23222875f88SMark Johnston {
23322875f88SMark Johnston 	uint64_t tsc1, tsc2;
23422875f88SMark Johnston 	int64_t overhead;
23522875f88SMark Johnston 	int count, i;
23622875f88SMark Johnston 
23722875f88SMark Johnston 	overhead = 0;
23822875f88SMark Johnston 	for (i = 0, count = 8; i < count; i++) {
23922875f88SMark Johnston 		tsc1 = rdtsc_ordered();
24022875f88SMark Johnston 		DELAY(0);
24122875f88SMark Johnston 		tsc2 = rdtsc_ordered();
24222875f88SMark Johnston 		if (i > 0)
24322875f88SMark Johnston 			overhead += tsc2 - tsc1;
24422875f88SMark Johnston 	}
24522875f88SMark Johnston 	overhead /= count;
24622875f88SMark Johnston 
24722875f88SMark Johnston 	tsc1 = rdtsc_ordered();
24822875f88SMark Johnston 	DELAY(100000);
24922875f88SMark Johnston 	tsc2 = rdtsc_ordered();
25022875f88SMark Johnston 	tsc_freq = (tsc2 - tsc1 - overhead) * 10;
251a4e4127fSJung-uk Kim }
252dd7d207dSJung-uk Kim 
253a4e4127fSJung-uk Kim static void
254a4e4127fSJung-uk Kim probe_tsc_freq(void)
255a4e4127fSJung-uk Kim {
256bb044eafSConrad Meyer 	if (cpu_power_ecx & CPUID_PERF_STAT) {
2575da5812bSJung-uk Kim 		/*
258bb044eafSConrad Meyer 		 * XXX Some emulators expose host CPUID without actual support
259bb044eafSConrad Meyer 		 * for these MSRs.  We must test whether they really work.
2605da5812bSJung-uk Kim 		 */
2615da5812bSJung-uk Kim 		wrmsr(MSR_MPERF, 0);
2625da5812bSJung-uk Kim 		wrmsr(MSR_APERF, 0);
2635da5812bSJung-uk Kim 		DELAY(10);
2645da5812bSJung-uk Kim 		if (rdmsr(MSR_MPERF) > 0 && rdmsr(MSR_APERF) > 0)
2655da5812bSJung-uk Kim 			tsc_perf_stat = 1;
2665da5812bSJung-uk Kim 	}
2675da5812bSJung-uk Kim 
26801e1933dSJohn Baldwin 	if (vm_guest == VM_GUEST_VMWARE) {
26901e1933dSJohn Baldwin 		tsc_freq_vmware();
2705da5812bSJung-uk Kim 		return;
27101e1933dSJohn Baldwin 	}
2725da5812bSJung-uk Kim 
273dd7d207dSJung-uk Kim 	switch (cpu_vendor_id) {
274dd7d207dSJung-uk Kim 	case CPU_VENDOR_AMD:
2752ee49facSKonstantin Belousov 	case CPU_VENDOR_HYGON:
276a106a27cSJung-uk Kim 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
277a106a27cSJung-uk Kim 		    (vm_guest == VM_GUEST_NO &&
278a106a27cSJung-uk Kim 		    CPUID_TO_FAMILY(cpu_id) >= 0x10))
279dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
280814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
281814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
282814124c3SKonstantin Belousov 			    tsc_get_timecount_mfence;
283814124c3SKonstantin Belousov 		}
284dd7d207dSJung-uk Kim 		break;
285dd7d207dSJung-uk Kim 	case CPU_VENDOR_INTEL:
286a106a27cSJung-uk Kim 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
287a106a27cSJung-uk Kim 		    (vm_guest == VM_GUEST_NO &&
288a106a27cSJung-uk Kim 		    ((CPUID_TO_FAMILY(cpu_id) == 0x6 &&
289dd7d207dSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0xe) ||
290dd7d207dSJung-uk Kim 		    (CPUID_TO_FAMILY(cpu_id) == 0xf &&
291a106a27cSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0x3))))
292dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
293814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
294814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
295814124c3SKonstantin Belousov 			    tsc_get_timecount_lfence;
296814124c3SKonstantin Belousov 		}
297dd7d207dSJung-uk Kim 		break;
298dd7d207dSJung-uk Kim 	case CPU_VENDOR_CENTAUR:
299a106a27cSJung-uk Kim 		if (vm_guest == VM_GUEST_NO &&
300a106a27cSJung-uk Kim 		    CPUID_TO_FAMILY(cpu_id) == 0x6 &&
301dd7d207dSJung-uk Kim 		    CPUID_TO_MODEL(cpu_id) >= 0xf &&
302dd7d207dSJung-uk Kim 		    (rdmsr(0x1203) & 0x100000000ULL) == 0)
303dd7d207dSJung-uk Kim 			tsc_is_invariant = 1;
304814124c3SKonstantin Belousov 		if (cpu_feature & CPUID_SSE2) {
305814124c3SKonstantin Belousov 			tsc_timecounter.tc_get_timecount =
306814124c3SKonstantin Belousov 			    tsc_get_timecount_lfence;
307814124c3SKonstantin Belousov 		}
308dd7d207dSJung-uk Kim 		break;
309dd7d207dSJung-uk Kim 	}
310dd7d207dSJung-uk Kim 
31122875f88SMark Johnston 	if (tsc_freq_cpuid(&tsc_freq)) {
312bd8a359fSKonstantin Belousov 		/*
31322875f88SMark Johnston 		 * If possible, use the value obtained from CPUID as the initial
31422875f88SMark Johnston 		 * frequency.  This will be refined later during boot but is
31522875f88SMark Johnston 		 * good enough for now.  The 8254 PIT is not functional on some
31622875f88SMark Johnston 		 * newer platforms anyway, so don't delay our boot for what
31722875f88SMark Johnston 		 * might be a garbage result.  Late calibration is required if
31822875f88SMark Johnston 		 * the initial frequency was obtained from CPUID.16H, as the
31922875f88SMark Johnston 		 * derived value may be off by as much as 1%.
320bd8a359fSKonstantin Belousov 		 */
321a4e4127fSJung-uk Kim 		if (bootverbose)
32222875f88SMark Johnston 			printf("Early TSC frequency %juHz derived from CPUID\n",
32322875f88SMark Johnston 			    (uintmax_t)tsc_freq);
32422875f88SMark Johnston 	} else if (tsc_skip_calibration) {
32522875f88SMark Johnston 		/*
32622875f88SMark Johnston 		 * Try to parse the brand string to obtain the nominal TSC
32722875f88SMark Johnston 		 * frequency.
32822875f88SMark Johnston 		 */
32922875f88SMark Johnston 		if (cpu_vendor_id == CPU_VENDOR_INTEL &&
33022875f88SMark Johnston 		    tsc_freq_intel_brand(&tsc_freq)) {
33122875f88SMark Johnston 			if (bootverbose)
33222875f88SMark Johnston 				printf(
33322875f88SMark Johnston 		    "Early TSC frequency %juHz derived from brand string\n",
33422875f88SMark Johnston 				    (uintmax_t)tsc_freq);
33522875f88SMark Johnston 		} else {
33622875f88SMark Johnston 			tsc_disabled = 1;
33722875f88SMark Johnston 		}
33822875f88SMark Johnston 	} else {
33922875f88SMark Johnston 		/*
34022875f88SMark Johnston 		 * Calibrate against the 8254 PIT.  This estimate will be
34122875f88SMark Johnston 		 * refined later in tsc_calib().
34222875f88SMark Johnston 		 */
34322875f88SMark Johnston 		tsc_freq_8254(&tsc_freq);
34422875f88SMark Johnston 		if (bootverbose)
34522875f88SMark Johnston 			printf(
34622875f88SMark Johnston 		    "Early TSC frequency %juHz calibrated from 8254 PIT\n",
34722875f88SMark Johnston 			    (uintmax_t)tsc_freq);
34822875f88SMark Johnston 	}
349a4e4127fSJung-uk Kim }
350a4e4127fSJung-uk Kim 
351a4e4127fSJung-uk Kim void
352a4e4127fSJung-uk Kim init_TSC(void)
353a4e4127fSJung-uk Kim {
354a4e4127fSJung-uk Kim 
355a4e4127fSJung-uk Kim 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
356a4e4127fSJung-uk Kim 		return;
357a4e4127fSJung-uk Kim 
358fe760cfaSJohn Baldwin #ifdef __i386__
359fe760cfaSJohn Baldwin 	/* The TSC is known to be broken on certain CPUs. */
360fe760cfaSJohn Baldwin 	switch (cpu_vendor_id) {
361fe760cfaSJohn Baldwin 	case CPU_VENDOR_AMD:
362fe760cfaSJohn Baldwin 		switch (cpu_id & 0xFF0) {
363fe760cfaSJohn Baldwin 		case 0x500:
364fe760cfaSJohn Baldwin 			/* K5 Model 0 */
365fe760cfaSJohn Baldwin 			return;
366fe760cfaSJohn Baldwin 		}
367fe760cfaSJohn Baldwin 		break;
368fe760cfaSJohn Baldwin 	case CPU_VENDOR_CENTAUR:
369fe760cfaSJohn Baldwin 		switch (cpu_id & 0xff0) {
370fe760cfaSJohn Baldwin 		case 0x540:
371fe760cfaSJohn Baldwin 			/*
372fe760cfaSJohn Baldwin 			 * http://www.centtech.com/c6_data_sheet.pdf
373fe760cfaSJohn Baldwin 			 *
374fe760cfaSJohn Baldwin 			 * I-12 RDTSC may return incoherent values in EDX:EAX
375fe760cfaSJohn Baldwin 			 * I-13 RDTSC hangs when certain event counters are used
376fe760cfaSJohn Baldwin 			 */
377fe760cfaSJohn Baldwin 			return;
378fe760cfaSJohn Baldwin 		}
379fe760cfaSJohn Baldwin 		break;
380fe760cfaSJohn Baldwin 	case CPU_VENDOR_NSC:
381fe760cfaSJohn Baldwin 		switch (cpu_id & 0xff0) {
382fe760cfaSJohn Baldwin 		case 0x540:
383fe760cfaSJohn Baldwin 			if ((cpu_id & CPUID_STEPPING) == 0)
384fe760cfaSJohn Baldwin 				return;
385fe760cfaSJohn Baldwin 			break;
386fe760cfaSJohn Baldwin 		}
387fe760cfaSJohn Baldwin 		break;
388fe760cfaSJohn Baldwin 	}
389fe760cfaSJohn Baldwin #endif
390fe760cfaSJohn Baldwin 
391a4e4127fSJung-uk Kim 	probe_tsc_freq();
392a4e4127fSJung-uk Kim 
393dd7d207dSJung-uk Kim 	/*
394dd7d207dSJung-uk Kim 	 * Inform CPU accounting about our boot-time clock rate.  This will
395dd7d207dSJung-uk Kim 	 * be updated if someone loads a cpufreq driver after boot that
396dd7d207dSJung-uk Kim 	 * discovers a new max frequency.
39722875f88SMark Johnston 	 *
39822875f88SMark Johnston 	 * The frequency may also be updated after late calibration is complete;
39922875f88SMark Johnston 	 * however, we register the TSC as the ticker now to avoid switching
40022875f88SMark Johnston 	 * counters after much of the kernel has already booted and potentially
40122875f88SMark Johnston 	 * sampled the CPU clock.
402dd7d207dSJung-uk Kim 	 */
403a4e4127fSJung-uk Kim 	if (tsc_freq != 0)
4045ac44f72SJung-uk Kim 		set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
405dd7d207dSJung-uk Kim 
406dd7d207dSJung-uk Kim 	if (tsc_is_invariant)
407dd7d207dSJung-uk Kim 		return;
408dd7d207dSJung-uk Kim 
409dd7d207dSJung-uk Kim 	/* Register to find out about changes in CPU frequency. */
410dd7d207dSJung-uk Kim 	tsc_pre_tag = EVENTHANDLER_REGISTER(cpufreq_pre_change,
411dd7d207dSJung-uk Kim 	    tsc_freq_changing, NULL, EVENTHANDLER_PRI_FIRST);
412dd7d207dSJung-uk Kim 	tsc_post_tag = EVENTHANDLER_REGISTER(cpufreq_post_change,
413dd7d207dSJung-uk Kim 	    tsc_freq_changed, NULL, EVENTHANDLER_PRI_FIRST);
414dd7d207dSJung-uk Kim 	tsc_levels_tag = EVENTHANDLER_REGISTER(cpufreq_levels_changed,
415dd7d207dSJung-uk Kim 	    tsc_levels_changed, NULL, EVENTHANDLER_PRI_ANY);
416dd7d207dSJung-uk Kim }
417dd7d207dSJung-uk Kim 
41865e7d70bSJung-uk Kim #ifdef SMP
41965e7d70bSJung-uk Kim 
420814124c3SKonstantin Belousov /*
421814124c3SKonstantin Belousov  * RDTSC is not a serializing instruction, and does not drain
422814124c3SKonstantin Belousov  * instruction stream, so we need to drain the stream before executing
423814124c3SKonstantin Belousov  * it.  It could be fixed by use of RDTSCP, except the instruction is
424814124c3SKonstantin Belousov  * not available everywhere.
425814124c3SKonstantin Belousov  *
426814124c3SKonstantin Belousov  * Use CPUID for draining in the boot-time SMP constistency test.  The
427814124c3SKonstantin Belousov  * timecounters use MFENCE for AMD CPUs, and LFENCE for others (Intel
428814124c3SKonstantin Belousov  * and VIA) when SSE2 is present, and nothing on older machines which
429814124c3SKonstantin Belousov  * also do not issue RDTSC prematurely.  There, testing for SSE2 and
430e1a18e46SKonstantin Belousov  * vendor is too cumbersome, and we learn about TSC presence from CPUID.
431814124c3SKonstantin Belousov  *
432814124c3SKonstantin Belousov  * Do not use do_cpuid(), since we do not need CPUID results, which
433814124c3SKonstantin Belousov  * have to be written into memory with do_cpuid().
434814124c3SKonstantin Belousov  */
43565e7d70bSJung-uk Kim #define	TSC_READ(x)							\
43665e7d70bSJung-uk Kim static void								\
43765e7d70bSJung-uk Kim tsc_read_##x(void *arg)							\
43865e7d70bSJung-uk Kim {									\
4397bfcb3bbSJim Harris 	uint64_t *tsc = arg;						\
44065e7d70bSJung-uk Kim 	u_int cpu = PCPU_GET(cpuid);					\
44165e7d70bSJung-uk Kim 									\
442814124c3SKonstantin Belousov 	__asm __volatile("cpuid" : : : "eax", "ebx", "ecx", "edx");	\
4437bfcb3bbSJim Harris 	tsc[cpu * 3 + x] = rdtsc();					\
44465e7d70bSJung-uk Kim }
44565e7d70bSJung-uk Kim TSC_READ(0)
44665e7d70bSJung-uk Kim TSC_READ(1)
44765e7d70bSJung-uk Kim TSC_READ(2)
44865e7d70bSJung-uk Kim #undef TSC_READ
44965e7d70bSJung-uk Kim 
45065e7d70bSJung-uk Kim #define	N	1000
45165e7d70bSJung-uk Kim 
45265e7d70bSJung-uk Kim static void
45365e7d70bSJung-uk Kim comp_smp_tsc(void *arg)
45465e7d70bSJung-uk Kim {
4557bfcb3bbSJim Harris 	uint64_t *tsc;
4567bfcb3bbSJim Harris 	int64_t d1, d2;
45765e7d70bSJung-uk Kim 	u_int cpu = PCPU_GET(cpuid);
45865e7d70bSJung-uk Kim 	u_int i, j, size;
45965e7d70bSJung-uk Kim 
46065e7d70bSJung-uk Kim 	size = (mp_maxid + 1) * 3;
46165e7d70bSJung-uk Kim 	for (i = 0, tsc = arg; i < N; i++, tsc += size)
46265e7d70bSJung-uk Kim 		CPU_FOREACH(j) {
46365e7d70bSJung-uk Kim 			if (j == cpu)
46465e7d70bSJung-uk Kim 				continue;
46565e7d70bSJung-uk Kim 			d1 = tsc[cpu * 3 + 1] - tsc[j * 3];
46665e7d70bSJung-uk Kim 			d2 = tsc[cpu * 3 + 2] - tsc[j * 3 + 1];
46765e7d70bSJung-uk Kim 			if (d1 <= 0 || d2 <= 0) {
46865e7d70bSJung-uk Kim 				smp_tsc = 0;
46965e7d70bSJung-uk Kim 				return;
47065e7d70bSJung-uk Kim 			}
47165e7d70bSJung-uk Kim 		}
47265e7d70bSJung-uk Kim }
47365e7d70bSJung-uk Kim 
474b2c63698SAlexander Motin static void
475b2c63698SAlexander Motin adj_smp_tsc(void *arg)
476b2c63698SAlexander Motin {
477b2c63698SAlexander Motin 	uint64_t *tsc;
478b2c63698SAlexander Motin 	int64_t d, min, max;
479b2c63698SAlexander Motin 	u_int cpu = PCPU_GET(cpuid);
480b2c63698SAlexander Motin 	u_int first, i, size;
481b2c63698SAlexander Motin 
482b2c63698SAlexander Motin 	first = CPU_FIRST();
483b2c63698SAlexander Motin 	if (cpu == first)
484b2c63698SAlexander Motin 		return;
485b2c63698SAlexander Motin 	min = INT64_MIN;
486b2c63698SAlexander Motin 	max = INT64_MAX;
487b2c63698SAlexander Motin 	size = (mp_maxid + 1) * 3;
488b2c63698SAlexander Motin 	for (i = 0, tsc = arg; i < N; i++, tsc += size) {
489b2c63698SAlexander Motin 		d = tsc[first * 3] - tsc[cpu * 3 + 1];
490b2c63698SAlexander Motin 		if (d > min)
491b2c63698SAlexander Motin 			min = d;
492b2c63698SAlexander Motin 		d = tsc[first * 3 + 1] - tsc[cpu * 3 + 2];
493b2c63698SAlexander Motin 		if (d > min)
494b2c63698SAlexander Motin 			min = d;
495b2c63698SAlexander Motin 		d = tsc[first * 3 + 1] - tsc[cpu * 3];
496b2c63698SAlexander Motin 		if (d < max)
497b2c63698SAlexander Motin 			max = d;
498b2c63698SAlexander Motin 		d = tsc[first * 3 + 2] - tsc[cpu * 3 + 1];
499b2c63698SAlexander Motin 		if (d < max)
500b2c63698SAlexander Motin 			max = d;
501b2c63698SAlexander Motin 	}
502b2c63698SAlexander Motin 	if (min > max)
503b2c63698SAlexander Motin 		return;
504b2c63698SAlexander Motin 	d = min / 2 + max / 2;
505b2c63698SAlexander Motin 	__asm __volatile (
506b2c63698SAlexander Motin 		"movl $0x10, %%ecx\n\t"
507b2c63698SAlexander Motin 		"rdmsr\n\t"
508b2c63698SAlexander Motin 		"addl %%edi, %%eax\n\t"
509b2c63698SAlexander Motin 		"adcl %%esi, %%edx\n\t"
510b2c63698SAlexander Motin 		"wrmsr\n"
511b2c63698SAlexander Motin 		: /* No output */
512b2c63698SAlexander Motin 		: "D" ((uint32_t)d), "S" ((uint32_t)(d >> 32))
513b2c63698SAlexander Motin 		: "ax", "cx", "dx", "cc"
514b2c63698SAlexander Motin 	);
515b2c63698SAlexander Motin }
516b2c63698SAlexander Motin 
51765e7d70bSJung-uk Kim static int
518279be68bSAndriy Gapon test_tsc(int adj_max_count)
51965e7d70bSJung-uk Kim {
5207bfcb3bbSJim Harris 	uint64_t *data, *tsc;
521b2c63698SAlexander Motin 	u_int i, size, adj;
52265e7d70bSJung-uk Kim 
52384eaf2ccSKonstantin Belousov 	if ((!smp_tsc && !tsc_is_invariant))
52465e7d70bSJung-uk Kim 		return (-100);
5258cc15b0dSKyle Evans 	/*
5268cc15b0dSKyle Evans 	 * Misbehavior of TSC under VirtualBox has been observed.  In
5278cc15b0dSKyle Evans 	 * particular, threads doing small (~1 second) sleeps may miss their
5288cc15b0dSKyle Evans 	 * wakeup and hang around in sleep state, causing hangs on shutdown.
5298cc15b0dSKyle Evans 	 */
5308cc15b0dSKyle Evans 	if (vm_guest == VM_GUEST_VBOX)
5318cc15b0dSKyle Evans 		return (0);
5328cc15b0dSKyle Evans 
533cd165c8bSColin Percival 	TSENTER();
53465e7d70bSJung-uk Kim 	size = (mp_maxid + 1) * 3;
53565e7d70bSJung-uk Kim 	data = malloc(sizeof(*data) * size * N, M_TEMP, M_WAITOK);
536b2c63698SAlexander Motin 	adj = 0;
537b2c63698SAlexander Motin retry:
53865e7d70bSJung-uk Kim 	for (i = 0, tsc = data; i < N; i++, tsc += size)
53965e7d70bSJung-uk Kim 		smp_rendezvous(tsc_read_0, tsc_read_1, tsc_read_2, tsc);
54065e7d70bSJung-uk Kim 	smp_tsc = 1;	/* XXX */
54167d955aaSPatrick Kelsey 	smp_rendezvous(smp_no_rendezvous_barrier, comp_smp_tsc,
54267d955aaSPatrick Kelsey 	    smp_no_rendezvous_barrier, data);
543279be68bSAndriy Gapon 	if (!smp_tsc && adj < adj_max_count) {
544b2c63698SAlexander Motin 		adj++;
54567d955aaSPatrick Kelsey 		smp_rendezvous(smp_no_rendezvous_barrier, adj_smp_tsc,
54667d955aaSPatrick Kelsey 		    smp_no_rendezvous_barrier, data);
547b2c63698SAlexander Motin 		goto retry;
548b2c63698SAlexander Motin 	}
54965e7d70bSJung-uk Kim 	free(data, M_TEMP);
55065e7d70bSJung-uk Kim 	if (bootverbose)
551b2c63698SAlexander Motin 		printf("SMP: %sed TSC synchronization test%s\n",
552b2c63698SAlexander Motin 		    smp_tsc ? "pass" : "fail",
553b2c63698SAlexander Motin 		    adj > 0 ? " after adjustment" : "");
554cd165c8bSColin Percival 	TSEXIT();
55526e6537aSJung-uk Kim 	if (smp_tsc && tsc_is_invariant) {
55626e6537aSJung-uk Kim 		switch (cpu_vendor_id) {
55726e6537aSJung-uk Kim 		case CPU_VENDOR_AMD:
5582ee49facSKonstantin Belousov 		case CPU_VENDOR_HYGON:
55926e6537aSJung-uk Kim 			/*
560450d86fcSJung-uk Kim 			 * Processor Programming Reference (PPR) for AMD
561450d86fcSJung-uk Kim 			 * Family 17h states that the TSC uses a common
562450d86fcSJung-uk Kim 			 * reference for all sockets, cores and threads.
563450d86fcSJung-uk Kim 			 */
564450d86fcSJung-uk Kim 			if (CPUID_TO_FAMILY(cpu_id) >= 0x17)
565450d86fcSJung-uk Kim 				return (1000);
566450d86fcSJung-uk Kim 			/*
56726e6537aSJung-uk Kim 			 * Starting with Family 15h processors, TSC clock
56826e6537aSJung-uk Kim 			 * source is in the north bridge.  Check whether
56926e6537aSJung-uk Kim 			 * we have a single-socket/multi-core platform.
57026e6537aSJung-uk Kim 			 * XXX Need more work for complex cases.
57126e6537aSJung-uk Kim 			 */
57226e6537aSJung-uk Kim 			if (CPUID_TO_FAMILY(cpu_id) < 0x15 ||
57326e6537aSJung-uk Kim 			    (amd_feature2 & AMDID2_CMP) == 0 ||
57426e6537aSJung-uk Kim 			    smp_cpus > (cpu_procinfo2 & AMDID_CMP_CORES) + 1)
57526e6537aSJung-uk Kim 				break;
57626e6537aSJung-uk Kim 			return (1000);
57726e6537aSJung-uk Kim 		case CPU_VENDOR_INTEL:
57826e6537aSJung-uk Kim 			/*
57926e6537aSJung-uk Kim 			 * XXX Assume Intel platforms have synchronized TSCs.
58026e6537aSJung-uk Kim 			 */
58126e6537aSJung-uk Kim 			return (1000);
58226e6537aSJung-uk Kim 		}
58326e6537aSJung-uk Kim 		return (800);
58426e6537aSJung-uk Kim 	}
58526e6537aSJung-uk Kim 	return (-100);
58665e7d70bSJung-uk Kim }
58765e7d70bSJung-uk Kim 
58865e7d70bSJung-uk Kim #undef N
58965e7d70bSJung-uk Kim 
59065e7d70bSJung-uk Kim #endif /* SMP */
59165e7d70bSJung-uk Kim 
59265e7d70bSJung-uk Kim static void
593dd7d207dSJung-uk Kim init_TSC_tc(void)
594dd7d207dSJung-uk Kim {
59595f2f098SJung-uk Kim 	uint64_t max_freq;
59695f2f098SJung-uk Kim 	int shift;
597dd7d207dSJung-uk Kim 
59838b8542cSJung-uk Kim 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
599dd7d207dSJung-uk Kim 		return;
600dd7d207dSJung-uk Kim 
601dd7d207dSJung-uk Kim 	/*
60295f2f098SJung-uk Kim 	 * Limit timecounter frequency to fit in an int and prevent it from
60395f2f098SJung-uk Kim 	 * overflowing too fast.
60495f2f098SJung-uk Kim 	 */
60595f2f098SJung-uk Kim 	max_freq = UINT_MAX;
60695f2f098SJung-uk Kim 
60795f2f098SJung-uk Kim 	/*
60892597e06SJohn Baldwin 	 * Intel CPUs without a C-state invariant TSC can stop the TSC
609d1411416SJohn Baldwin 	 * in either C2 or C3.  Disable use of C2 and C3 while using
610d1411416SJohn Baldwin 	 * the TSC as the timecounter.  The timecounter can be changed
611d1411416SJohn Baldwin 	 * to enable C2 and C3.
612d1411416SJohn Baldwin 	 *
613d1411416SJohn Baldwin 	 * Note that the TSC is used as the cputicker for computing
614d1411416SJohn Baldwin 	 * thread runtime regardless of the timecounter setting, so
615d1411416SJohn Baldwin 	 * using an alternate timecounter and enabling C2 or C3 can
616d1411416SJohn Baldwin 	 * result incorrect runtimes for kernel idle threads (but not
617d1411416SJohn Baldwin 	 * for any non-idle threads).
618a49399a9SJung-uk Kim 	 */
6198cd59625SKonstantin Belousov 	if (cpu_vendor_id == CPU_VENDOR_INTEL &&
620a49399a9SJung-uk Kim 	    (amd_pminfo & AMDPM_TSC_INVARIANT) == 0) {
62192597e06SJohn Baldwin 		tsc_timecounter.tc_flags |= TC_FLAGS_C2STOP;
622a49399a9SJung-uk Kim 		if (bootverbose)
623d1411416SJohn Baldwin 			printf("TSC timecounter disables C2 and C3.\n");
624a49399a9SJung-uk Kim 	}
625a49399a9SJung-uk Kim 
626dd7d207dSJung-uk Kim 	/*
627e7f1427dSKonstantin Belousov 	 * We can not use the TSC in SMP mode unless the TSCs on all CPUs
628e7f1427dSKonstantin Belousov 	 * are synchronized.  If the user is sure that the system has
629e7f1427dSKonstantin Belousov 	 * synchronized TSCs, set kern.timecounter.smp_tsc tunable to a
630e7f1427dSKonstantin Belousov 	 * non-zero value.  The TSC seems unreliable in virtualized SMP
6315cf8ac1bSMike Silbersack 	 * environments, so it is set to a negative quality in those cases.
632dd7d207dSJung-uk Kim 	 */
633ba79ab82SAndriy Gapon #ifdef SMP
634e7f1427dSKonstantin Belousov 	if (mp_ncpus > 1)
635279be68bSAndriy Gapon 		tsc_timecounter.tc_quality = test_tsc(smp_tsc_adjust);
636ba79ab82SAndriy Gapon 	else
637ba79ab82SAndriy Gapon #endif /* SMP */
638ba79ab82SAndriy Gapon 	if (tsc_is_invariant)
63926e6537aSJung-uk Kim 		tsc_timecounter.tc_quality = 1000;
640e7f1427dSKonstantin Belousov 	max_freq >>= tsc_shift;
64126e6537aSJung-uk Kim 
642e7f1427dSKonstantin Belousov 	for (shift = 0; shift <= 31 && (tsc_freq >> shift) > max_freq; shift++)
64395f2f098SJung-uk Kim 		;
6449e680e40SKonstantin Belousov 
6459e680e40SKonstantin Belousov 	/*
6469e680e40SKonstantin Belousov 	 * Timecounter implementation selection, top to bottom:
6479e680e40SKonstantin Belousov 	 * - If RDTSCP is available, use RDTSCP.
6489e680e40SKonstantin Belousov 	 * - If fence instructions are provided (SSE2), use LFENCE;RDTSC
6499e680e40SKonstantin Belousov 	 *   on Intel, and MFENCE;RDTSC on AMD.
6509e680e40SKonstantin Belousov 	 * - For really old CPUs, just use RDTSC.
6519e680e40SKonstantin Belousov 	 */
6529f47eeffSKonstantin Belousov 	if ((amd_feature & AMDID_RDTSCP) != 0) {
6539e680e40SKonstantin Belousov 		tsc_timecounter.tc_get_timecount = shift > 0 ?
6549e680e40SKonstantin Belousov 		    tscp_get_timecount_low : tscp_get_timecount;
6559e680e40SKonstantin Belousov 	} else if ((cpu_feature & CPUID_SSE2) != 0 && mp_ncpus > 1) {
6562ee49facSKonstantin Belousov 		if (cpu_vendor_id == CPU_VENDOR_AMD ||
6572ee49facSKonstantin Belousov 		    cpu_vendor_id == CPU_VENDOR_HYGON) {
658e7f1427dSKonstantin Belousov 			tsc_timecounter.tc_get_timecount = shift > 0 ?
659e7f1427dSKonstantin Belousov 			    tsc_get_timecount_low_mfence :
660e7f1427dSKonstantin Belousov 			    tsc_get_timecount_mfence;
661814124c3SKonstantin Belousov 		} else {
662e7f1427dSKonstantin Belousov 			tsc_timecounter.tc_get_timecount = shift > 0 ?
663e7f1427dSKonstantin Belousov 			    tsc_get_timecount_low_lfence :
664e7f1427dSKonstantin Belousov 			    tsc_get_timecount_lfence;
665814124c3SKonstantin Belousov 		}
666e7f1427dSKonstantin Belousov 	} else {
667e7f1427dSKonstantin Belousov 		tsc_timecounter.tc_get_timecount = shift > 0 ?
668e7f1427dSKonstantin Belousov 		    tsc_get_timecount_low : tsc_get_timecount;
669e7f1427dSKonstantin Belousov 	}
670e7f1427dSKonstantin Belousov 	if (shift > 0) {
67195f2f098SJung-uk Kim 		tsc_timecounter.tc_name = "TSC-low";
67295f2f098SJung-uk Kim 		if (bootverbose)
673bc8e4ad2SJung-uk Kim 			printf("TSC timecounter discards lower %d bit(s)\n",
67495f2f098SJung-uk Kim 			    shift);
67595f2f098SJung-uk Kim 	}
676bc34c87eSJung-uk Kim 	if (tsc_freq != 0) {
67795f2f098SJung-uk Kim 		tsc_timecounter.tc_frequency = tsc_freq >> shift;
67895f2f098SJung-uk Kim 		tsc_timecounter.tc_priv = (void *)(intptr_t)shift;
67922875f88SMark Johnston 
68022875f88SMark Johnston 		/*
68122875f88SMark Johnston 		 * Timecounter registration is deferred until after late
68222875f88SMark Johnston 		 * calibration is finished.
68322875f88SMark Johnston 		 */
684dd7d207dSJung-uk Kim 	}
685dd7d207dSJung-uk Kim }
68665e7d70bSJung-uk Kim SYSINIT(tsc_tc, SI_SUB_SMP, SI_ORDER_ANY, init_TSC_tc, NULL);
687dd7d207dSJung-uk Kim 
68822875f88SMark Johnston static void
68922875f88SMark Johnston tsc_update_freq(uint64_t new_freq)
69022875f88SMark Johnston {
69122875f88SMark Johnston 	atomic_store_rel_64(&tsc_freq, new_freq);
69222875f88SMark Johnston 	atomic_store_rel_64(&tsc_timecounter.tc_frequency,
69322875f88SMark Johnston 	    new_freq >> (int)(intptr_t)tsc_timecounter.tc_priv);
69422875f88SMark Johnston }
69522875f88SMark Johnston 
69622875f88SMark Johnston /*
69722875f88SMark Johnston  * Perform late calibration of the TSC frequency once ACPI-based timecounters
698553af8f1SMark Johnston  * are available.  At this point timehands are not set up, so we read the
699553af8f1SMark Johnston  * highest-quality timecounter directly rather than using (s)binuptime().
70022875f88SMark Johnston  */
701553af8f1SMark Johnston void
702553af8f1SMark Johnston tsc_calibrate(void)
70322875f88SMark Johnston {
704553af8f1SMark Johnston 	struct timecounter *tc;
70522875f88SMark Johnston 	uint64_t freq_khz, tsc_start, tsc_end;
706553af8f1SMark Johnston 	u_int t_start, t_end;
70722875f88SMark Johnston 	register_t flags;
70822875f88SMark Johnston 	int cpu;
70922875f88SMark Johnston 
71022875f88SMark Johnston 	if (tsc_disabled)
71122875f88SMark Johnston 		return;
71222875f88SMark Johnston 
713553af8f1SMark Johnston 	tc = atomic_load_ptr(&timecounter);
714553af8f1SMark Johnston 
71522875f88SMark Johnston 	flags = intr_disable();
71622875f88SMark Johnston 	cpu = curcpu;
71722875f88SMark Johnston 	tsc_start = rdtsc_ordered();
718553af8f1SMark Johnston 	t_start = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
71922875f88SMark Johnston 	intr_restore(flags);
72022875f88SMark Johnston 
72122875f88SMark Johnston 	DELAY(1000000);
72222875f88SMark Johnston 
72322875f88SMark Johnston 	thread_lock(curthread);
72422875f88SMark Johnston 	sched_bind(curthread, cpu);
72522875f88SMark Johnston 
72622875f88SMark Johnston 	flags = intr_disable();
72722875f88SMark Johnston 	tsc_end = rdtsc_ordered();
728553af8f1SMark Johnston 	t_end = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
72922875f88SMark Johnston 	intr_restore(flags);
73022875f88SMark Johnston 
73122875f88SMark Johnston 	sched_unbind(curthread);
73222875f88SMark Johnston 	thread_unlock(curthread);
73322875f88SMark Johnston 
734553af8f1SMark Johnston 	if (t_end <= t_start) {
735553af8f1SMark Johnston 		/* Assume that the counter has wrapped around at most once. */
736553af8f1SMark Johnston 		t_end += (uint64_t)tc->tc_counter_mask + 1;
737553af8f1SMark Johnston 	}
73822875f88SMark Johnston 
739553af8f1SMark Johnston 	freq_khz = tc->tc_frequency * (tsc_end - tsc_start) / (t_end - t_start);
740553af8f1SMark Johnston 
741553af8f1SMark Johnston 	tsc_update_freq(freq_khz);
74222875f88SMark Johnston 	tc_init(&tsc_timecounter);
74322875f88SMark Johnston 	set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
74422875f88SMark Johnston }
74522875f88SMark Johnston 
746279be68bSAndriy Gapon void
747279be68bSAndriy Gapon resume_TSC(void)
748279be68bSAndriy Gapon {
749ba79ab82SAndriy Gapon #ifdef SMP
750279be68bSAndriy Gapon 	int quality;
751279be68bSAndriy Gapon 
752279be68bSAndriy Gapon 	/* If TSC was not good on boot, it is unlikely to become good now. */
753279be68bSAndriy Gapon 	if (tsc_timecounter.tc_quality < 0)
754279be68bSAndriy Gapon 		return;
755279be68bSAndriy Gapon 	/* Nothing to do with UP. */
756279be68bSAndriy Gapon 	if (mp_ncpus < 2)
757279be68bSAndriy Gapon 		return;
758279be68bSAndriy Gapon 
759279be68bSAndriy Gapon 	/*
760279be68bSAndriy Gapon 	 * If TSC was good, a single synchronization should be enough,
761279be68bSAndriy Gapon 	 * but honour smp_tsc_adjust if it's set.
762279be68bSAndriy Gapon 	 */
763279be68bSAndriy Gapon 	quality = test_tsc(MAX(smp_tsc_adjust, 1));
764279be68bSAndriy Gapon 	if (quality != tsc_timecounter.tc_quality) {
765279be68bSAndriy Gapon 		printf("TSC timecounter quality changed: %d -> %d\n",
766279be68bSAndriy Gapon 		    tsc_timecounter.tc_quality, quality);
767279be68bSAndriy Gapon 		tsc_timecounter.tc_quality = quality;
768279be68bSAndriy Gapon 	}
769ba79ab82SAndriy Gapon #endif /* SMP */
770279be68bSAndriy Gapon }
771279be68bSAndriy Gapon 
772dd7d207dSJung-uk Kim /*
773dd7d207dSJung-uk Kim  * When cpufreq levels change, find out about the (new) max frequency.  We
774dd7d207dSJung-uk Kim  * use this to update CPU accounting in case it got a lower estimate at boot.
775dd7d207dSJung-uk Kim  */
776dd7d207dSJung-uk Kim static void
777dd7d207dSJung-uk Kim tsc_levels_changed(void *arg, int unit)
778dd7d207dSJung-uk Kim {
779dd7d207dSJung-uk Kim 	device_t cf_dev;
780dd7d207dSJung-uk Kim 	struct cf_level *levels;
781dd7d207dSJung-uk Kim 	int count, error;
782dd7d207dSJung-uk Kim 	uint64_t max_freq;
783dd7d207dSJung-uk Kim 
784dd7d207dSJung-uk Kim 	/* Only use values from the first CPU, assuming all are equal. */
785dd7d207dSJung-uk Kim 	if (unit != 0)
786dd7d207dSJung-uk Kim 		return;
787dd7d207dSJung-uk Kim 
788dd7d207dSJung-uk Kim 	/* Find the appropriate cpufreq device instance. */
789dd7d207dSJung-uk Kim 	cf_dev = devclass_get_device(devclass_find("cpufreq"), unit);
790dd7d207dSJung-uk Kim 	if (cf_dev == NULL) {
791dd7d207dSJung-uk Kim 		printf("tsc_levels_changed() called but no cpufreq device?\n");
792dd7d207dSJung-uk Kim 		return;
793dd7d207dSJung-uk Kim 	}
794dd7d207dSJung-uk Kim 
795dd7d207dSJung-uk Kim 	/* Get settings from the device and find the max frequency. */
796dd7d207dSJung-uk Kim 	count = 64;
797dd7d207dSJung-uk Kim 	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
798dd7d207dSJung-uk Kim 	if (levels == NULL)
799dd7d207dSJung-uk Kim 		return;
800dd7d207dSJung-uk Kim 	error = CPUFREQ_LEVELS(cf_dev, levels, &count);
801dd7d207dSJung-uk Kim 	if (error == 0 && count != 0) {
802dd7d207dSJung-uk Kim 		max_freq = (uint64_t)levels[0].total_set.freq * 1000000;
803dd7d207dSJung-uk Kim 		set_cputicker(rdtsc, max_freq, 1);
804dd7d207dSJung-uk Kim 	} else
805dd7d207dSJung-uk Kim 		printf("tsc_levels_changed: no max freq found\n");
806dd7d207dSJung-uk Kim 	free(levels, M_TEMP);
807dd7d207dSJung-uk Kim }
808dd7d207dSJung-uk Kim 
809dd7d207dSJung-uk Kim /*
810dd7d207dSJung-uk Kim  * If the TSC timecounter is in use, veto the pending change.  It may be
811dd7d207dSJung-uk Kim  * possible in the future to handle a dynamically-changing timecounter rate.
812dd7d207dSJung-uk Kim  */
813dd7d207dSJung-uk Kim static void
814dd7d207dSJung-uk Kim tsc_freq_changing(void *arg, const struct cf_level *level, int *status)
815dd7d207dSJung-uk Kim {
816dd7d207dSJung-uk Kim 
817dd7d207dSJung-uk Kim 	if (*status != 0 || timecounter != &tsc_timecounter)
818dd7d207dSJung-uk Kim 		return;
819dd7d207dSJung-uk Kim 
820dd7d207dSJung-uk Kim 	printf("timecounter TSC must not be in use when "
821dd7d207dSJung-uk Kim 	    "changing frequencies; change denied\n");
822dd7d207dSJung-uk Kim 	*status = EBUSY;
823dd7d207dSJung-uk Kim }
824dd7d207dSJung-uk Kim 
825dd7d207dSJung-uk Kim /* Update TSC freq with the value indicated by the caller. */
826dd7d207dSJung-uk Kim static void
827dd7d207dSJung-uk Kim tsc_freq_changed(void *arg, const struct cf_level *level, int status)
828dd7d207dSJung-uk Kim {
8293453537fSJung-uk Kim 	uint64_t freq;
830dd7d207dSJung-uk Kim 
831dd7d207dSJung-uk Kim 	/* If there was an error during the transition, don't do anything. */
83279422085SJung-uk Kim 	if (tsc_disabled || status != 0)
833dd7d207dSJung-uk Kim 		return;
834dd7d207dSJung-uk Kim 
835dd7d207dSJung-uk Kim 	/* Total setting for this level gives the new frequency in MHz. */
8363453537fSJung-uk Kim 	freq = (uint64_t)level->total_set.freq * 1000000;
83722875f88SMark Johnston 	tsc_update_freq(freq);
838dd7d207dSJung-uk Kim }
839dd7d207dSJung-uk Kim 
840dd7d207dSJung-uk Kim static int
841dd7d207dSJung-uk Kim sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
842dd7d207dSJung-uk Kim {
843dd7d207dSJung-uk Kim 	int error;
844dd7d207dSJung-uk Kim 	uint64_t freq;
845dd7d207dSJung-uk Kim 
8463453537fSJung-uk Kim 	freq = atomic_load_acq_64(&tsc_freq);
8473453537fSJung-uk Kim 	if (freq == 0)
848dd7d207dSJung-uk Kim 		return (EOPNOTSUPP);
849cbc134adSMatthew D Fleming 	error = sysctl_handle_64(oidp, &freq, 0, req);
85022875f88SMark Johnston 	if (error == 0 && req->newptr != NULL)
85122875f88SMark Johnston 		tsc_update_freq(freq);
852dd7d207dSJung-uk Kim 	return (error);
853dd7d207dSJung-uk Kim }
8547029da5cSPawel Biernacki SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq,
855*1d6fb900SAlexander Motin     CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
8567029da5cSPawel Biernacki     0, 0, sysctl_machdep_tsc_freq, "QU",
8577029da5cSPawel Biernacki     "Time Stamp Counter frequency");
858dd7d207dSJung-uk Kim 
859727c7b2dSJung-uk Kim static u_int
86095f2f098SJung-uk Kim tsc_get_timecount(struct timecounter *tc __unused)
861dd7d207dSJung-uk Kim {
862727c7b2dSJung-uk Kim 
863727c7b2dSJung-uk Kim 	return (rdtsc32());
864dd7d207dSJung-uk Kim }
86595f2f098SJung-uk Kim 
8669e680e40SKonstantin Belousov static u_int
8679e680e40SKonstantin Belousov tscp_get_timecount(struct timecounter *tc __unused)
8689e680e40SKonstantin Belousov {
8699e680e40SKonstantin Belousov 
8709e680e40SKonstantin Belousov 	return (rdtscp32());
8719e680e40SKonstantin Belousov }
8729e680e40SKonstantin Belousov 
873814124c3SKonstantin Belousov static inline u_int
874bc8e4ad2SJung-uk Kim tsc_get_timecount_low(struct timecounter *tc)
87595f2f098SJung-uk Kim {
8765df88f46SJung-uk Kim 	uint32_t rv;
87795f2f098SJung-uk Kim 
8785df88f46SJung-uk Kim 	__asm __volatile("rdtsc; shrd %%cl, %%edx, %0"
8795df88f46SJung-uk Kim 	    : "=a" (rv) : "c" ((int)(intptr_t)tc->tc_priv) : "edx");
8805df88f46SJung-uk Kim 	return (rv);
88195f2f098SJung-uk Kim }
882aea81038SKonstantin Belousov 
883814124c3SKonstantin Belousov static u_int
8849e680e40SKonstantin Belousov tscp_get_timecount_low(struct timecounter *tc)
8859e680e40SKonstantin Belousov {
8869e680e40SKonstantin Belousov 	uint32_t rv;
8879e680e40SKonstantin Belousov 
8889e680e40SKonstantin Belousov 	__asm __volatile("rdtscp; movl %1, %%ecx; shrd %%cl, %%edx, %0"
889a013e285SKonstantin Belousov 	    : "=&a" (rv) : "m" (tc->tc_priv) : "ecx", "edx");
8909e680e40SKonstantin Belousov 	return (rv);
8919e680e40SKonstantin Belousov }
8929e680e40SKonstantin Belousov 
8939e680e40SKonstantin Belousov static u_int
894814124c3SKonstantin Belousov tsc_get_timecount_lfence(struct timecounter *tc __unused)
895814124c3SKonstantin Belousov {
896814124c3SKonstantin Belousov 
897814124c3SKonstantin Belousov 	lfence();
898814124c3SKonstantin Belousov 	return (rdtsc32());
899814124c3SKonstantin Belousov }
900814124c3SKonstantin Belousov 
901814124c3SKonstantin Belousov static u_int
902814124c3SKonstantin Belousov tsc_get_timecount_low_lfence(struct timecounter *tc)
903814124c3SKonstantin Belousov {
904814124c3SKonstantin Belousov 
905814124c3SKonstantin Belousov 	lfence();
906814124c3SKonstantin Belousov 	return (tsc_get_timecount_low(tc));
907814124c3SKonstantin Belousov }
908814124c3SKonstantin Belousov 
909814124c3SKonstantin Belousov static u_int
910814124c3SKonstantin Belousov tsc_get_timecount_mfence(struct timecounter *tc __unused)
911814124c3SKonstantin Belousov {
912814124c3SKonstantin Belousov 
913814124c3SKonstantin Belousov 	mfence();
914814124c3SKonstantin Belousov 	return (rdtsc32());
915814124c3SKonstantin Belousov }
916814124c3SKonstantin Belousov 
917814124c3SKonstantin Belousov static u_int
918814124c3SKonstantin Belousov tsc_get_timecount_low_mfence(struct timecounter *tc)
919814124c3SKonstantin Belousov {
920814124c3SKonstantin Belousov 
921814124c3SKonstantin Belousov 	mfence();
922814124c3SKonstantin Belousov 	return (tsc_get_timecount_low(tc));
923814124c3SKonstantin Belousov }
924814124c3SKonstantin Belousov 
92516808549SKonstantin Belousov static uint32_t
92616808549SKonstantin Belousov x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th, struct timecounter *tc)
927aea81038SKonstantin Belousov {
928aea81038SKonstantin Belousov 
92916808549SKonstantin Belousov 	vdso_th->th_algo = VDSO_TH_ALGO_X86_TSC;
930d1b1b600SNeel Natu 	vdso_th->th_x86_shift = (int)(intptr_t)tc->tc_priv;
93116808549SKonstantin Belousov 	vdso_th->th_x86_hpet_idx = 0xffffffff;
932d4b2d303SAdam Fenn 	vdso_th->th_x86_pvc_last_systime = 0;
933d4b2d303SAdam Fenn 	vdso_th->th_x86_pvc_stable_mask = 0;
934aea81038SKonstantin Belousov 	bzero(vdso_th->th_res, sizeof(vdso_th->th_res));
93516808549SKonstantin Belousov 	return (1);
936aea81038SKonstantin Belousov }
937aea81038SKonstantin Belousov 
938aea81038SKonstantin Belousov #ifdef COMPAT_FREEBSD32
93916808549SKonstantin Belousov static uint32_t
94016808549SKonstantin Belousov x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
941d1b1b600SNeel Natu     struct timecounter *tc)
942aea81038SKonstantin Belousov {
943aea81038SKonstantin Belousov 
94416808549SKonstantin Belousov 	vdso_th32->th_algo = VDSO_TH_ALGO_X86_TSC;
945d1b1b600SNeel Natu 	vdso_th32->th_x86_shift = (int)(intptr_t)tc->tc_priv;
94616808549SKonstantin Belousov 	vdso_th32->th_x86_hpet_idx = 0xffffffff;
947d4b2d303SAdam Fenn 	vdso_th32->th_x86_pvc_last_systime = 0;
948d4b2d303SAdam Fenn 	vdso_th32->th_x86_pvc_stable_mask = 0;
949aea81038SKonstantin Belousov 	bzero(vdso_th32->th_res, sizeof(vdso_th32->th_res));
95016808549SKonstantin Belousov 	return (1);
951aea81038SKonstantin Belousov }
952aea81038SKonstantin Belousov #endif
953