xref: /freebsd/sys/x86/x86/tsc.c (revision 758d98debec43ff83b8a1ed9a3d3a8441b83b3cc)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 1998-2003 Poul-Henning Kamp
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include "opt_clock.h"
33 
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/bus.h>
37 #include <sys/cpu.h>
38 #include <sys/eventhandler.h>
39 #include <sys/limits.h>
40 #include <sys/malloc.h>
41 #include <sys/proc.h>
42 #include <sys/sched.h>
43 #include <sys/sysctl.h>
44 #include <sys/time.h>
45 #include <sys/timetc.h>
46 #include <sys/kernel.h>
47 #include <sys/smp.h>
48 #include <sys/vdso.h>
49 #include <machine/clock.h>
50 #include <machine/cputypes.h>
51 #include <machine/fpu.h>
52 #include <machine/md_var.h>
53 #include <machine/specialreg.h>
54 #include <x86/vmware.h>
55 #include <dev/acpica/acpi_hpet.h>
56 #include <contrib/dev/acpica/include/acpi.h>
57 
58 #include "cpufreq_if.h"
59 
60 uint64_t	tsc_freq;
61 int		tsc_is_invariant;
62 int		tsc_perf_stat;
63 static int	tsc_early_calib_exact;
64 
65 static eventhandler_tag tsc_levels_tag, tsc_pre_tag, tsc_post_tag;
66 
67 SYSCTL_INT(_kern_timecounter, OID_AUTO, invariant_tsc, CTLFLAG_RDTUN,
68     &tsc_is_invariant, 0, "Indicates whether the TSC is P-state invariant");
69 
70 #ifdef SMP
71 int	smp_tsc;
72 SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc, CTLFLAG_RDTUN, &smp_tsc, 0,
73     "Indicates whether the TSC is safe to use in SMP mode");
74 
75 int	smp_tsc_adjust = 0;
76 SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc_adjust, CTLFLAG_RDTUN,
77     &smp_tsc_adjust, 0, "Try to adjust TSC on APs to match BSP");
78 #endif
79 
80 static int	tsc_shift = 1;
81 SYSCTL_INT(_kern_timecounter, OID_AUTO, tsc_shift, CTLFLAG_RDTUN,
82     &tsc_shift, 0, "Shift to pre-apply for the maximum TSC frequency");
83 
84 static int	tsc_disabled;
85 SYSCTL_INT(_machdep, OID_AUTO, disable_tsc, CTLFLAG_RDTUN, &tsc_disabled, 0,
86     "Disable x86 Time Stamp Counter");
87 
88 static int	tsc_skip_calibration;
89 SYSCTL_INT(_machdep, OID_AUTO, disable_tsc_calibration, CTLFLAG_RDTUN,
90     &tsc_skip_calibration, 0,
91     "Disable early TSC frequency calibration");
92 
93 static void tsc_freq_changed(void *arg, const struct cf_level *level,
94     int status);
95 static void tsc_freq_changing(void *arg, const struct cf_level *level,
96     int *status);
97 static u_int tsc_get_timecount(struct timecounter *tc);
98 static inline u_int tsc_get_timecount_low(struct timecounter *tc);
99 static u_int tsc_get_timecount_lfence(struct timecounter *tc);
100 static u_int tsc_get_timecount_low_lfence(struct timecounter *tc);
101 static u_int tsc_get_timecount_mfence(struct timecounter *tc);
102 static u_int tsc_get_timecount_low_mfence(struct timecounter *tc);
103 static u_int tscp_get_timecount(struct timecounter *tc);
104 static u_int tscp_get_timecount_low(struct timecounter *tc);
105 static void tsc_levels_changed(void *arg, int unit);
106 static uint32_t x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th,
107     struct timecounter *tc);
108 #ifdef COMPAT_FREEBSD32
109 static uint32_t x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
110     struct timecounter *tc);
111 #endif
112 
113 static struct timecounter tsc_timecounter = {
114 	.tc_get_timecount =		tsc_get_timecount,
115 	.tc_counter_mask =		~0u,
116 	.tc_name =			"TSC",
117 	.tc_quality =			800,	/* adjusted in code */
118 	.tc_fill_vdso_timehands = 	x86_tsc_vdso_timehands,
119 #ifdef COMPAT_FREEBSD32
120 	.tc_fill_vdso_timehands32 = 	x86_tsc_vdso_timehands32,
121 #endif
122 };
123 
124 static int
125 tsc_freq_cpuid_vm(void)
126 {
127 	u_int regs[4];
128 
129 	if (vm_guest == VM_GUEST_NO)
130 		return (false);
131 	if (hv_high < 0x40000010)
132 		return (false);
133 	do_cpuid(0x40000010, regs);
134 	tsc_freq = (uint64_t)(regs[0]) * 1000;
135 	tsc_early_calib_exact = 1;
136 	return (true);
137 }
138 
139 static void
140 tsc_freq_vmware(void)
141 {
142 	u_int regs[4];
143 
144 	vmware_hvcall(VMW_HVCMD_GETHZ, regs);
145 	if (regs[1] != UINT_MAX)
146 		tsc_freq = regs[0] | ((uint64_t)regs[1] << 32);
147 	tsc_early_calib_exact = 1;
148 }
149 
150 /*
151  * Calculate TSC frequency using information from the CPUID leaf 0x15 'Time
152  * Stamp Counter and Nominal Core Crystal Clock'.  If leaf 0x15 is not
153  * functional, as it is on Skylake/Kabylake, try 0x16 'Processor Frequency
154  * Information'.  Leaf 0x16 is described in the SDM as informational only, but
155  * we can use this value until late calibration is complete.
156  */
157 static bool
158 tsc_freq_cpuid(uint64_t *res)
159 {
160 	u_int regs[4];
161 
162 	if (cpu_high < 0x15)
163 		return (false);
164 	do_cpuid(0x15, regs);
165 	if (regs[0] != 0 && regs[1] != 0 && regs[2] != 0) {
166 		*res = (uint64_t)regs[2] * regs[1] / regs[0];
167 		return (true);
168 	}
169 
170 	if (cpu_high < 0x16)
171 		return (false);
172 	do_cpuid(0x16, regs);
173 	if (regs[0] != 0) {
174 		*res = (uint64_t)regs[0] * 1000000;
175 		return (true);
176 	}
177 
178 	return (false);
179 }
180 
181 static bool
182 tsc_freq_intel_brand(uint64_t *res)
183 {
184 	char brand[48];
185 	u_int regs[4];
186 	uint64_t freq;
187 	char *p;
188 	u_int i;
189 
190 	/*
191 	 * Intel Processor Identification and the CPUID Instruction
192 	 * Application Note 485.
193 	 * http://www.intel.com/assets/pdf/appnote/241618.pdf
194 	 */
195 	if (cpu_exthigh >= 0x80000004) {
196 		p = brand;
197 		for (i = 0x80000002; i < 0x80000005; i++) {
198 			do_cpuid(i, regs);
199 			memcpy(p, regs, sizeof(regs));
200 			p += sizeof(regs);
201 		}
202 		p = NULL;
203 		for (i = 0; i < sizeof(brand) - 1; i++)
204 			if (brand[i] == 'H' && brand[i + 1] == 'z')
205 				p = brand + i;
206 		if (p != NULL) {
207 			p -= 5;
208 			switch (p[4]) {
209 			case 'M':
210 				i = 1;
211 				break;
212 			case 'G':
213 				i = 1000;
214 				break;
215 			case 'T':
216 				i = 1000000;
217 				break;
218 			default:
219 				return (false);
220 			}
221 #define	C2D(c)	((c) - '0')
222 			if (p[1] == '.') {
223 				freq = C2D(p[0]) * 1000;
224 				freq += C2D(p[2]) * 100;
225 				freq += C2D(p[3]) * 10;
226 				freq *= i * 1000;
227 			} else {
228 				freq = C2D(p[0]) * 1000;
229 				freq += C2D(p[1]) * 100;
230 				freq += C2D(p[2]) * 10;
231 				freq += C2D(p[3]);
232 				freq *= i * 1000000;
233 			}
234 #undef C2D
235 			*res = freq;
236 			return (true);
237 		}
238 	}
239 	return (false);
240 }
241 
242 static void
243 tsc_freq_8254(uint64_t *res)
244 {
245 	uint64_t tsc1, tsc2;
246 	int64_t overhead;
247 	int count, i;
248 
249 	overhead = 0;
250 	for (i = 0, count = 8; i < count; i++) {
251 		tsc1 = rdtsc_ordered();
252 		DELAY(0);
253 		tsc2 = rdtsc_ordered();
254 		if (i > 0)
255 			overhead += tsc2 - tsc1;
256 	}
257 	overhead /= count;
258 
259 	tsc1 = rdtsc_ordered();
260 	DELAY(100000);
261 	tsc2 = rdtsc_ordered();
262 	tsc_freq = (tsc2 - tsc1 - overhead) * 10;
263 }
264 
265 static void
266 probe_tsc_freq(void)
267 {
268 	if (cpu_power_ecx & CPUID_PERF_STAT) {
269 		/*
270 		 * XXX Some emulators expose host CPUID without actual support
271 		 * for these MSRs.  We must test whether they really work.
272 		 */
273 		wrmsr(MSR_MPERF, 0);
274 		wrmsr(MSR_APERF, 0);
275 		DELAY(10);
276 		if (rdmsr(MSR_MPERF) > 0 && rdmsr(MSR_APERF) > 0)
277 			tsc_perf_stat = 1;
278 	}
279 
280 	switch (cpu_vendor_id) {
281 	case CPU_VENDOR_AMD:
282 	case CPU_VENDOR_HYGON:
283 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
284 		    (vm_guest == VM_GUEST_NO &&
285 		    CPUID_TO_FAMILY(cpu_id) >= 0x10))
286 			tsc_is_invariant = 1;
287 		if (cpu_feature & CPUID_SSE2) {
288 			tsc_timecounter.tc_get_timecount =
289 			    tsc_get_timecount_mfence;
290 		}
291 		break;
292 	case CPU_VENDOR_INTEL:
293 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
294 		    (vm_guest == VM_GUEST_NO &&
295 		    ((CPUID_TO_FAMILY(cpu_id) == 0x6 &&
296 		    CPUID_TO_MODEL(cpu_id) >= 0xe) ||
297 		    (CPUID_TO_FAMILY(cpu_id) == 0xf &&
298 		    CPUID_TO_MODEL(cpu_id) >= 0x3))))
299 			tsc_is_invariant = 1;
300 		if (cpu_feature & CPUID_SSE2) {
301 			tsc_timecounter.tc_get_timecount =
302 			    tsc_get_timecount_lfence;
303 		}
304 		break;
305 	case CPU_VENDOR_CENTAUR:
306 		if (vm_guest == VM_GUEST_NO &&
307 		    CPUID_TO_FAMILY(cpu_id) == 0x6 &&
308 		    CPUID_TO_MODEL(cpu_id) >= 0xf &&
309 		    (rdmsr(0x1203) & 0x100000000ULL) == 0)
310 			tsc_is_invariant = 1;
311 		if (cpu_feature & CPUID_SSE2) {
312 			tsc_timecounter.tc_get_timecount =
313 			    tsc_get_timecount_lfence;
314 		}
315 		break;
316 	}
317 
318 	if (tsc_freq_cpuid_vm())
319 		return;
320 
321 	if (vm_guest == VM_GUEST_VMWARE) {
322 		tsc_freq_vmware();
323 		return;
324 	}
325 
326 	if (tsc_freq_cpuid(&tsc_freq)) {
327 		/*
328 		 * If possible, use the value obtained from CPUID as the initial
329 		 * frequency.  This will be refined later during boot but is
330 		 * good enough for now.  The 8254 PIT is not functional on some
331 		 * newer platforms anyway, so don't delay our boot for what
332 		 * might be a garbage result.  Late calibration is required if
333 		 * the initial frequency was obtained from CPUID.16H, as the
334 		 * derived value may be off by as much as 1%.
335 		 */
336 		if (bootverbose)
337 			printf("Early TSC frequency %juHz derived from CPUID\n",
338 			    (uintmax_t)tsc_freq);
339 	} else if (tsc_skip_calibration) {
340 		/*
341 		 * Try to parse the brand string to obtain the nominal TSC
342 		 * frequency.
343 		 */
344 		if (cpu_vendor_id == CPU_VENDOR_INTEL &&
345 		    tsc_freq_intel_brand(&tsc_freq)) {
346 			if (bootverbose)
347 				printf(
348 		    "Early TSC frequency %juHz derived from brand string\n",
349 				    (uintmax_t)tsc_freq);
350 		} else {
351 			tsc_disabled = 1;
352 		}
353 	} else {
354 		/*
355 		 * Calibrate against the 8254 PIT.  This estimate will be
356 		 * refined later in tsc_calib().
357 		 */
358 		tsc_freq_8254(&tsc_freq);
359 		if (bootverbose)
360 			printf(
361 		    "Early TSC frequency %juHz calibrated from 8254 PIT\n",
362 			    (uintmax_t)tsc_freq);
363 	}
364 }
365 
366 void
367 init_TSC(void)
368 {
369 
370 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
371 		return;
372 
373 #ifdef __i386__
374 	/* The TSC is known to be broken on certain CPUs. */
375 	switch (cpu_vendor_id) {
376 	case CPU_VENDOR_AMD:
377 		switch (cpu_id & 0xFF0) {
378 		case 0x500:
379 			/* K5 Model 0 */
380 			return;
381 		}
382 		break;
383 	case CPU_VENDOR_CENTAUR:
384 		switch (cpu_id & 0xff0) {
385 		case 0x540:
386 			/*
387 			 * http://www.centtech.com/c6_data_sheet.pdf
388 			 *
389 			 * I-12 RDTSC may return incoherent values in EDX:EAX
390 			 * I-13 RDTSC hangs when certain event counters are used
391 			 */
392 			return;
393 		}
394 		break;
395 	case CPU_VENDOR_NSC:
396 		switch (cpu_id & 0xff0) {
397 		case 0x540:
398 			if ((cpu_id & CPUID_STEPPING) == 0)
399 				return;
400 			break;
401 		}
402 		break;
403 	}
404 #endif
405 
406 	probe_tsc_freq();
407 
408 	/*
409 	 * Inform CPU accounting about our boot-time clock rate.  This will
410 	 * be updated if someone loads a cpufreq driver after boot that
411 	 * discovers a new max frequency.
412 	 *
413 	 * The frequency may also be updated after late calibration is complete;
414 	 * however, we register the TSC as the ticker now to avoid switching
415 	 * counters after much of the kernel has already booted and potentially
416 	 * sampled the CPU clock.
417 	 */
418 	if (tsc_freq != 0)
419 		set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
420 
421 	if (tsc_is_invariant)
422 		return;
423 
424 	/* Register to find out about changes in CPU frequency. */
425 	tsc_pre_tag = EVENTHANDLER_REGISTER(cpufreq_pre_change,
426 	    tsc_freq_changing, NULL, EVENTHANDLER_PRI_FIRST);
427 	tsc_post_tag = EVENTHANDLER_REGISTER(cpufreq_post_change,
428 	    tsc_freq_changed, NULL, EVENTHANDLER_PRI_FIRST);
429 	tsc_levels_tag = EVENTHANDLER_REGISTER(cpufreq_levels_changed,
430 	    tsc_levels_changed, NULL, EVENTHANDLER_PRI_ANY);
431 }
432 
433 #ifdef SMP
434 
435 /*
436  * RDTSC is not a serializing instruction, and does not drain
437  * instruction stream, so we need to drain the stream before executing
438  * it.  It could be fixed by use of RDTSCP, except the instruction is
439  * not available everywhere.
440  *
441  * Use CPUID for draining in the boot-time SMP constistency test.  The
442  * timecounters use MFENCE for AMD CPUs, and LFENCE for others (Intel
443  * and VIA) when SSE2 is present, and nothing on older machines which
444  * also do not issue RDTSC prematurely.  There, testing for SSE2 and
445  * vendor is too cumbersome, and we learn about TSC presence from CPUID.
446  *
447  * Do not use do_cpuid(), since we do not need CPUID results, which
448  * have to be written into memory with do_cpuid().
449  */
450 #define	TSC_READ(x)							\
451 static void								\
452 tsc_read_##x(void *arg)							\
453 {									\
454 	uint64_t *tsc = arg;						\
455 	u_int cpu = PCPU_GET(cpuid);					\
456 									\
457 	__asm __volatile("cpuid" : : : "eax", "ebx", "ecx", "edx");	\
458 	tsc[cpu * 3 + x] = rdtsc();					\
459 }
460 TSC_READ(0)
461 TSC_READ(1)
462 TSC_READ(2)
463 #undef TSC_READ
464 
465 #define	N	1000
466 
467 static void
468 comp_smp_tsc(void *arg)
469 {
470 	uint64_t *tsc;
471 	int64_t d1, d2;
472 	u_int cpu = PCPU_GET(cpuid);
473 	u_int i, j, size;
474 
475 	size = (mp_maxid + 1) * 3;
476 	for (i = 0, tsc = arg; i < N; i++, tsc += size)
477 		CPU_FOREACH(j) {
478 			if (j == cpu)
479 				continue;
480 			d1 = tsc[cpu * 3 + 1] - tsc[j * 3];
481 			d2 = tsc[cpu * 3 + 2] - tsc[j * 3 + 1];
482 			if (d1 <= 0 || d2 <= 0) {
483 				smp_tsc = 0;
484 				return;
485 			}
486 		}
487 }
488 
489 static void
490 adj_smp_tsc(void *arg)
491 {
492 	uint64_t *tsc;
493 	int64_t d, min, max;
494 	u_int cpu = PCPU_GET(cpuid);
495 	u_int first, i, size;
496 
497 	first = CPU_FIRST();
498 	if (cpu == first)
499 		return;
500 	min = INT64_MIN;
501 	max = INT64_MAX;
502 	size = (mp_maxid + 1) * 3;
503 	for (i = 0, tsc = arg; i < N; i++, tsc += size) {
504 		d = tsc[first * 3] - tsc[cpu * 3 + 1];
505 		if (d > min)
506 			min = d;
507 		d = tsc[first * 3 + 1] - tsc[cpu * 3 + 2];
508 		if (d > min)
509 			min = d;
510 		d = tsc[first * 3 + 1] - tsc[cpu * 3];
511 		if (d < max)
512 			max = d;
513 		d = tsc[first * 3 + 2] - tsc[cpu * 3 + 1];
514 		if (d < max)
515 			max = d;
516 	}
517 	if (min > max)
518 		return;
519 	d = min / 2 + max / 2;
520 	__asm __volatile (
521 		"movl $0x10, %%ecx\n\t"
522 		"rdmsr\n\t"
523 		"addl %%edi, %%eax\n\t"
524 		"adcl %%esi, %%edx\n\t"
525 		"wrmsr\n"
526 		: /* No output */
527 		: "D" ((uint32_t)d), "S" ((uint32_t)(d >> 32))
528 		: "ax", "cx", "dx", "cc"
529 	);
530 }
531 
532 static int
533 test_tsc(int adj_max_count)
534 {
535 	uint64_t *data, *tsc;
536 	u_int i, size, adj;
537 
538 	if ((!smp_tsc && !tsc_is_invariant))
539 		return (-100);
540 	/*
541 	 * Misbehavior of TSC under VirtualBox has been observed.  In
542 	 * particular, threads doing small (~1 second) sleeps may miss their
543 	 * wakeup and hang around in sleep state, causing hangs on shutdown.
544 	 */
545 	if (vm_guest == VM_GUEST_VBOX)
546 		return (0);
547 
548 	TSENTER();
549 	size = (mp_maxid + 1) * 3;
550 	data = malloc(sizeof(*data) * size * N, M_TEMP, M_WAITOK);
551 	adj = 0;
552 retry:
553 	for (i = 0, tsc = data; i < N; i++, tsc += size)
554 		smp_rendezvous(tsc_read_0, tsc_read_1, tsc_read_2, tsc);
555 	smp_tsc = 1;	/* XXX */
556 	smp_rendezvous(smp_no_rendezvous_barrier, comp_smp_tsc,
557 	    smp_no_rendezvous_barrier, data);
558 	if (!smp_tsc && adj < adj_max_count) {
559 		adj++;
560 		smp_rendezvous(smp_no_rendezvous_barrier, adj_smp_tsc,
561 		    smp_no_rendezvous_barrier, data);
562 		goto retry;
563 	}
564 	free(data, M_TEMP);
565 	if (bootverbose)
566 		printf("SMP: %sed TSC synchronization test%s\n",
567 		    smp_tsc ? "pass" : "fail",
568 		    adj > 0 ? " after adjustment" : "");
569 	TSEXIT();
570 	if (smp_tsc && tsc_is_invariant) {
571 		switch (cpu_vendor_id) {
572 		case CPU_VENDOR_AMD:
573 		case CPU_VENDOR_HYGON:
574 			/*
575 			 * Processor Programming Reference (PPR) for AMD
576 			 * Family 17h states that the TSC uses a common
577 			 * reference for all sockets, cores and threads.
578 			 */
579 			if (CPUID_TO_FAMILY(cpu_id) >= 0x17)
580 				return (1000);
581 			/*
582 			 * Starting with Family 15h processors, TSC clock
583 			 * source is in the north bridge.  Check whether
584 			 * we have a single-socket/multi-core platform.
585 			 * XXX Need more work for complex cases.
586 			 */
587 			if (CPUID_TO_FAMILY(cpu_id) < 0x15 ||
588 			    (amd_feature2 & AMDID2_CMP) == 0 ||
589 			    smp_cpus > (cpu_procinfo2 & AMDID_CMP_CORES) + 1)
590 				break;
591 			return (1000);
592 		case CPU_VENDOR_INTEL:
593 			/*
594 			 * XXX Assume Intel platforms have synchronized TSCs.
595 			 */
596 			return (1000);
597 		}
598 		return (800);
599 	}
600 	return (-100);
601 }
602 
603 #undef N
604 
605 #endif /* SMP */
606 
607 static void
608 init_TSC_tc(void)
609 {
610 	uint64_t max_freq;
611 	int shift;
612 
613 	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
614 		return;
615 
616 	/*
617 	 * Limit timecounter frequency to fit in an int and prevent it from
618 	 * overflowing too fast.
619 	 */
620 	max_freq = UINT_MAX;
621 
622 	/*
623 	 * Intel CPUs without a C-state invariant TSC can stop the TSC
624 	 * in either C2 or C3.  Disable use of C2 and C3 while using
625 	 * the TSC as the timecounter.  The timecounter can be changed
626 	 * to enable C2 and C3.
627 	 *
628 	 * Note that the TSC is used as the cputicker for computing
629 	 * thread runtime regardless of the timecounter setting, so
630 	 * using an alternate timecounter and enabling C2 or C3 can
631 	 * result incorrect runtimes for kernel idle threads (but not
632 	 * for any non-idle threads).
633 	 */
634 	if (cpu_vendor_id == CPU_VENDOR_INTEL &&
635 	    (amd_pminfo & AMDPM_TSC_INVARIANT) == 0) {
636 		tsc_timecounter.tc_flags |= TC_FLAGS_C2STOP;
637 		if (bootverbose)
638 			printf("TSC timecounter disables C2 and C3.\n");
639 	}
640 
641 	/*
642 	 * We can not use the TSC in SMP mode unless the TSCs on all CPUs
643 	 * are synchronized.  If the user is sure that the system has
644 	 * synchronized TSCs, set kern.timecounter.smp_tsc tunable to a
645 	 * non-zero value.  The TSC seems unreliable in virtualized SMP
646 	 * environments, so it is set to a negative quality in those cases.
647 	 */
648 #ifdef SMP
649 	if (mp_ncpus > 1)
650 		tsc_timecounter.tc_quality = test_tsc(smp_tsc_adjust);
651 	else
652 #endif /* SMP */
653 	if (tsc_is_invariant)
654 		tsc_timecounter.tc_quality = 1000;
655 	max_freq >>= tsc_shift;
656 
657 	for (shift = 0; shift <= 31 && (tsc_freq >> shift) > max_freq; shift++)
658 		;
659 
660 	/*
661 	 * Timecounter implementation selection, top to bottom:
662 	 * - If RDTSCP is available, use RDTSCP.
663 	 * - If fence instructions are provided (SSE2), use LFENCE;RDTSC
664 	 *   on Intel, and MFENCE;RDTSC on AMD.
665 	 * - For really old CPUs, just use RDTSC.
666 	 */
667 	if ((amd_feature & AMDID_RDTSCP) != 0) {
668 		tsc_timecounter.tc_get_timecount = shift > 0 ?
669 		    tscp_get_timecount_low : tscp_get_timecount;
670 	} else if ((cpu_feature & CPUID_SSE2) != 0 && mp_ncpus > 1) {
671 		if (cpu_vendor_id == CPU_VENDOR_AMD ||
672 		    cpu_vendor_id == CPU_VENDOR_HYGON) {
673 			tsc_timecounter.tc_get_timecount = shift > 0 ?
674 			    tsc_get_timecount_low_mfence :
675 			    tsc_get_timecount_mfence;
676 		} else {
677 			tsc_timecounter.tc_get_timecount = shift > 0 ?
678 			    tsc_get_timecount_low_lfence :
679 			    tsc_get_timecount_lfence;
680 		}
681 	} else {
682 		tsc_timecounter.tc_get_timecount = shift > 0 ?
683 		    tsc_get_timecount_low : tsc_get_timecount;
684 	}
685 	if (shift > 0) {
686 		tsc_timecounter.tc_name = "TSC-low";
687 		if (bootverbose)
688 			printf("TSC timecounter discards lower %d bit(s)\n",
689 			    shift);
690 	}
691 	if (tsc_freq != 0) {
692 		tsc_timecounter.tc_frequency = tsc_freq >> shift;
693 		tsc_timecounter.tc_priv = (void *)(intptr_t)shift;
694 
695 		/*
696 		 * Timecounter registration is deferred until after late
697 		 * calibration is finished.
698 		 */
699 	}
700 }
701 SYSINIT(tsc_tc, SI_SUB_SMP, SI_ORDER_ANY, init_TSC_tc, NULL);
702 
703 static void
704 tsc_update_freq(uint64_t new_freq)
705 {
706 	atomic_store_rel_64(&tsc_freq, new_freq);
707 	atomic_store_rel_64(&tsc_timecounter.tc_frequency,
708 	    new_freq >> (int)(intptr_t)tsc_timecounter.tc_priv);
709 }
710 
711 /*
712  * Perform late calibration of the TSC frequency once ACPI-based timecounters
713  * are available.  At this point timehands are not set up, so we read the
714  * highest-quality timecounter directly rather than using (s)binuptime().
715  */
716 void
717 tsc_calibrate(void)
718 {
719 	uint64_t freq;
720 
721 	if (tsc_disabled)
722 		return;
723 	if (tsc_early_calib_exact)
724 		goto calibrated;
725 
726 	fpu_kern_enter(curthread, NULL, FPU_KERN_NOCTX);
727 	freq = clockcalib(rdtsc_ordered, "TSC");
728 	fpu_kern_leave(curthread, NULL);
729 	tsc_update_freq(freq);
730 
731 calibrated:
732 	tc_init(&tsc_timecounter);
733 	set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
734 }
735 
736 void
737 resume_TSC(void)
738 {
739 #ifdef SMP
740 	int quality;
741 
742 	/* If TSC was not good on boot, it is unlikely to become good now. */
743 	if (tsc_timecounter.tc_quality < 0)
744 		return;
745 	/* Nothing to do with UP. */
746 	if (mp_ncpus < 2)
747 		return;
748 
749 	/*
750 	 * If TSC was good, a single synchronization should be enough,
751 	 * but honour smp_tsc_adjust if it's set.
752 	 */
753 	quality = test_tsc(MAX(smp_tsc_adjust, 1));
754 	if (quality != tsc_timecounter.tc_quality) {
755 		printf("TSC timecounter quality changed: %d -> %d\n",
756 		    tsc_timecounter.tc_quality, quality);
757 		tsc_timecounter.tc_quality = quality;
758 	}
759 #endif /* SMP */
760 }
761 
762 /*
763  * When cpufreq levels change, find out about the (new) max frequency.  We
764  * use this to update CPU accounting in case it got a lower estimate at boot.
765  */
766 static void
767 tsc_levels_changed(void *arg, int unit)
768 {
769 	device_t cf_dev;
770 	struct cf_level *levels;
771 	int count, error;
772 	uint64_t max_freq;
773 
774 	/* Only use values from the first CPU, assuming all are equal. */
775 	if (unit != 0)
776 		return;
777 
778 	/* Find the appropriate cpufreq device instance. */
779 	cf_dev = devclass_get_device(devclass_find("cpufreq"), unit);
780 	if (cf_dev == NULL) {
781 		printf("tsc_levels_changed() called but no cpufreq device?\n");
782 		return;
783 	}
784 
785 	/* Get settings from the device and find the max frequency. */
786 	count = 64;
787 	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
788 	if (levels == NULL)
789 		return;
790 	error = CPUFREQ_LEVELS(cf_dev, levels, &count);
791 	if (error == 0 && count != 0) {
792 		max_freq = (uint64_t)levels[0].total_set.freq * 1000000;
793 		set_cputicker(rdtsc, max_freq, 1);
794 	} else
795 		printf("tsc_levels_changed: no max freq found\n");
796 	free(levels, M_TEMP);
797 }
798 
799 /*
800  * If the TSC timecounter is in use, veto the pending change.  It may be
801  * possible in the future to handle a dynamically-changing timecounter rate.
802  */
803 static void
804 tsc_freq_changing(void *arg, const struct cf_level *level, int *status)
805 {
806 
807 	if (*status != 0 || timecounter != &tsc_timecounter)
808 		return;
809 
810 	printf("timecounter TSC must not be in use when "
811 	    "changing frequencies; change denied\n");
812 	*status = EBUSY;
813 }
814 
815 /* Update TSC freq with the value indicated by the caller. */
816 static void
817 tsc_freq_changed(void *arg, const struct cf_level *level, int status)
818 {
819 	uint64_t freq;
820 
821 	/* If there was an error during the transition, don't do anything. */
822 	if (tsc_disabled || status != 0)
823 		return;
824 
825 	/* Total setting for this level gives the new frequency in MHz. */
826 	freq = (uint64_t)level->total_set.freq * 1000000;
827 	tsc_update_freq(freq);
828 }
829 
830 static int
831 sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
832 {
833 	int error;
834 	uint64_t freq;
835 
836 	freq = atomic_load_acq_64(&tsc_freq);
837 	if (freq == 0)
838 		return (EOPNOTSUPP);
839 	error = sysctl_handle_64(oidp, &freq, 0, req);
840 	if (error == 0 && req->newptr != NULL)
841 		tsc_update_freq(freq);
842 	return (error);
843 }
844 SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq,
845     CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
846     0, 0, sysctl_machdep_tsc_freq, "QU",
847     "Time Stamp Counter frequency");
848 
849 static u_int
850 tsc_get_timecount(struct timecounter *tc __unused)
851 {
852 
853 	return (rdtsc32());
854 }
855 
856 static u_int
857 tscp_get_timecount(struct timecounter *tc __unused)
858 {
859 
860 	return (rdtscp32());
861 }
862 
863 static inline u_int
864 tsc_get_timecount_low(struct timecounter *tc)
865 {
866 	uint32_t rv;
867 
868 	__asm __volatile("rdtsc; shrd %%cl, %%edx, %0"
869 	    : "=a" (rv) : "c" ((int)(intptr_t)tc->tc_priv) : "edx");
870 	return (rv);
871 }
872 
873 static u_int
874 tscp_get_timecount_low(struct timecounter *tc)
875 {
876 	uint32_t rv;
877 
878 	__asm __volatile("rdtscp; movl %1, %%ecx; shrd %%cl, %%edx, %0"
879 	    : "=&a" (rv) : "m" (tc->tc_priv) : "ecx", "edx");
880 	return (rv);
881 }
882 
883 static u_int
884 tsc_get_timecount_lfence(struct timecounter *tc __unused)
885 {
886 
887 	lfence();
888 	return (rdtsc32());
889 }
890 
891 static u_int
892 tsc_get_timecount_low_lfence(struct timecounter *tc)
893 {
894 
895 	lfence();
896 	return (tsc_get_timecount_low(tc));
897 }
898 
899 static u_int
900 tsc_get_timecount_mfence(struct timecounter *tc __unused)
901 {
902 
903 	mfence();
904 	return (rdtsc32());
905 }
906 
907 static u_int
908 tsc_get_timecount_low_mfence(struct timecounter *tc)
909 {
910 
911 	mfence();
912 	return (tsc_get_timecount_low(tc));
913 }
914 
915 static uint32_t
916 x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th, struct timecounter *tc)
917 {
918 
919 	vdso_th->th_algo = VDSO_TH_ALGO_X86_TSC;
920 	vdso_th->th_x86_shift = (int)(intptr_t)tc->tc_priv;
921 	vdso_th->th_x86_hpet_idx = 0xffffffff;
922 	vdso_th->th_x86_pvc_last_systime = 0;
923 	vdso_th->th_x86_pvc_stable_mask = 0;
924 	bzero(vdso_th->th_res, sizeof(vdso_th->th_res));
925 	return (1);
926 }
927 
928 #ifdef COMPAT_FREEBSD32
929 static uint32_t
930 x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
931     struct timecounter *tc)
932 {
933 
934 	vdso_th32->th_algo = VDSO_TH_ALGO_X86_TSC;
935 	vdso_th32->th_x86_shift = (int)(intptr_t)tc->tc_priv;
936 	vdso_th32->th_x86_hpet_idx = 0xffffffff;
937 	vdso_th32->th_x86_pvc_last_systime = 0;
938 	vdso_th32->th_x86_pvc_stable_mask = 0;
939 	bzero(vdso_th32->th_res, sizeof(vdso_th32->th_res));
940 	return (1);
941 }
942 #endif
943