2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 1998-2003 Poul-Henning Kamp
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include "opt_clock.h"
34 #include <sys/param.h>
37 #include <sys/eventhandler.h>
38 #include <sys/limits.h>
39 #include <sys/malloc.h>
40 #include <sys/systm.h>
41 #include <sys/sysctl.h>
43 #include <sys/timetc.h>
44 #include <sys/kernel.h>
45 #include <sys/power.h>
48 #include <machine/clock.h>
49 #include <machine/cputypes.h>
50 #include <machine/md_var.h>
51 #include <machine/specialreg.h>
52 #include <x86/vmware.h>
53 #include <dev/acpica/acpi_hpet.h>
54 #include <contrib/dev/acpica/include/acpi.h>
56 #include "cpufreq_if.h"
62 static eventhandler_tag tsc_levels_tag, tsc_pre_tag, tsc_post_tag;
64 SYSCTL_INT(_kern_timecounter, OID_AUTO, invariant_tsc, CTLFLAG_RDTUN,
65 &tsc_is_invariant, 0, "Indicates whether the TSC is P-state invariant");
69 SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc, CTLFLAG_RDTUN, &smp_tsc, 0,
70 "Indicates whether the TSC is safe to use in SMP mode");
72 int smp_tsc_adjust = 0;
73 SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc_adjust, CTLFLAG_RDTUN,
74 &smp_tsc_adjust, 0, "Try to adjust TSC on APs to match BSP");
77 static int tsc_shift = 1;
78 SYSCTL_INT(_kern_timecounter, OID_AUTO, tsc_shift, CTLFLAG_RDTUN,
79 &tsc_shift, 0, "Shift to pre-apply for the maximum TSC frequency");
81 static int tsc_disabled;
82 SYSCTL_INT(_machdep, OID_AUTO, disable_tsc, CTLFLAG_RDTUN, &tsc_disabled, 0,
83 "Disable x86 Time Stamp Counter");
85 static int tsc_skip_calibration;
86 SYSCTL_INT(_machdep, OID_AUTO, disable_tsc_calibration, CTLFLAG_RDTUN |
87 CTLFLAG_NOFETCH, &tsc_skip_calibration, 0,
88 "Disable TSC frequency calibration");
90 static void tsc_freq_changed(void *arg, const struct cf_level *level,
92 static void tsc_freq_changing(void *arg, const struct cf_level *level,
94 static unsigned tsc_get_timecount(struct timecounter *tc);
95 static inline unsigned tsc_get_timecount_low(struct timecounter *tc);
96 static unsigned tsc_get_timecount_lfence(struct timecounter *tc);
97 static unsigned tsc_get_timecount_low_lfence(struct timecounter *tc);
98 static unsigned tsc_get_timecount_mfence(struct timecounter *tc);
99 static unsigned tsc_get_timecount_low_mfence(struct timecounter *tc);
100 static void tsc_levels_changed(void *arg, int unit);
101 static uint32_t x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th,
102 struct timecounter *tc);
103 #ifdef COMPAT_FREEBSD32
104 static uint32_t x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
105 struct timecounter *tc);
108 static struct timecounter tsc_timecounter = {
109 .tc_get_timecount = tsc_get_timecount,
110 .tc_counter_mask = ~0u,
112 .tc_quality = 800, /* adjusted in code */
113 .tc_fill_vdso_timehands = x86_tsc_vdso_timehands,
114 #ifdef COMPAT_FREEBSD32
115 .tc_fill_vdso_timehands32 = x86_tsc_vdso_timehands32,
120 tsc_freq_vmware(void)
124 if (hv_high >= 0x40000010) {
125 do_cpuid(0x40000010, regs);
126 tsc_freq = regs[0] * 1000;
128 vmware_hvcall(VMW_HVCMD_GETHZ, regs);
129 if (regs[1] != UINT_MAX)
130 tsc_freq = regs[0] | ((uint64_t)regs[1] << 32);
132 tsc_is_invariant = 1;
136 * Calculate TSC frequency using information from the CPUID leaf 0x15
137 * 'Time Stamp Counter and Nominal Core Crystal Clock'. If leaf 0x15
138 * is not functional, as it is on Skylake/Kabylake, try 0x16 'Processor
139 * Frequency Information'. Leaf 0x16 is described in the SDM as
140 * informational only, but if 0x15 did not work, and TSC calibration
141 * is disabled, it is the best we can get at all. It should still be
142 * an improvement over the parsing of the CPU model name in
143 * tsc_freq_intel(), when available.
152 do_cpuid(0x15, regs);
153 if (regs[0] != 0 && regs[1] != 0 && regs[2] != 0) {
154 tsc_freq = (uint64_t)regs[2] * regs[1] / regs[0];
160 do_cpuid(0x16, regs);
162 tsc_freq = (uint64_t)regs[0] * 1000000;
179 * Intel Processor Identification and the CPUID Instruction
180 * Application Note 485.
181 * http://www.intel.com/assets/pdf/appnote/241618.pdf
183 if (cpu_exthigh >= 0x80000004) {
185 for (i = 0x80000002; i < 0x80000005; i++) {
187 memcpy(p, regs, sizeof(regs));
191 for (i = 0; i < sizeof(brand) - 1; i++)
192 if (brand[i] == 'H' && brand[i + 1] == 'z')
209 #define C2D(c) ((c) - '0')
211 freq = C2D(p[0]) * 1000;
212 freq += C2D(p[2]) * 100;
213 freq += C2D(p[3]) * 10;
216 freq = C2D(p[0]) * 1000;
217 freq += C2D(p[1]) * 100;
218 freq += C2D(p[2]) * 10;
234 if (cpu_power_ecx & CPUID_PERF_STAT) {
236 * XXX Some emulators expose host CPUID without actual support
237 * for these MSRs. We must test whether they really work.
242 if (rdmsr(MSR_MPERF) > 0 && rdmsr(MSR_APERF) > 0)
246 if (vm_guest == VM_GUEST_VMWARE) {
251 switch (cpu_vendor_id) {
253 case CPU_VENDOR_HYGON:
254 if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
255 (vm_guest == VM_GUEST_NO &&
256 CPUID_TO_FAMILY(cpu_id) >= 0x10))
257 tsc_is_invariant = 1;
258 if (cpu_feature & CPUID_SSE2) {
259 tsc_timecounter.tc_get_timecount =
260 tsc_get_timecount_mfence;
263 case CPU_VENDOR_INTEL:
264 if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
265 (vm_guest == VM_GUEST_NO &&
266 ((CPUID_TO_FAMILY(cpu_id) == 0x6 &&
267 CPUID_TO_MODEL(cpu_id) >= 0xe) ||
268 (CPUID_TO_FAMILY(cpu_id) == 0xf &&
269 CPUID_TO_MODEL(cpu_id) >= 0x3))))
270 tsc_is_invariant = 1;
271 if (cpu_feature & CPUID_SSE2) {
272 tsc_timecounter.tc_get_timecount =
273 tsc_get_timecount_lfence;
276 case CPU_VENDOR_CENTAUR:
277 if (vm_guest == VM_GUEST_NO &&
278 CPUID_TO_FAMILY(cpu_id) == 0x6 &&
279 CPUID_TO_MODEL(cpu_id) >= 0xf &&
280 (rdmsr(0x1203) & 0x100000000ULL) == 0)
281 tsc_is_invariant = 1;
282 if (cpu_feature & CPUID_SSE2) {
283 tsc_timecounter.tc_get_timecount =
284 tsc_get_timecount_lfence;
289 if (!TUNABLE_INT_FETCH("machdep.disable_tsc_calibration",
290 &tsc_skip_calibration)) {
292 * User did not give the order about calibration.
293 * If he did, we do not try to guess.
295 * Otherwise, if ACPI FADT reports that the platform
296 * is legacy-free and CPUID provides TSC frequency,
297 * use it. The calibration could fail anyway since
298 * ISA timer can be absent or power gated.
300 if (acpi_get_fadt_bootflags(&bootflags) &&
301 (bootflags & ACPI_FADT_LEGACY_DEVICES) == 0 &&
303 printf("Skipping TSC calibration since no legacy "
304 "devices reported by FADT and CPUID works\n");
305 tsc_skip_calibration = 1;
308 if (tsc_skip_calibration) {
309 if (tsc_freq_cpuid())
311 else if (cpu_vendor_id == CPU_VENDOR_INTEL)
315 printf("Calibrating TSC clock ... ");
319 tsc_freq = tsc2 - tsc1;
322 printf("TSC clock: %ju Hz\n", (intmax_t)tsc_freq);
329 if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
333 /* The TSC is known to be broken on certain CPUs. */
334 switch (cpu_vendor_id) {
336 switch (cpu_id & 0xFF0) {
342 case CPU_VENDOR_CENTAUR:
343 switch (cpu_id & 0xff0) {
346 * http://www.centtech.com/c6_data_sheet.pdf
348 * I-12 RDTSC may return incoherent values in EDX:EAX
349 * I-13 RDTSC hangs when certain event counters are used
355 switch (cpu_id & 0xff0) {
357 if ((cpu_id & CPUID_STEPPING) == 0)
368 * Inform CPU accounting about our boot-time clock rate. This will
369 * be updated if someone loads a cpufreq driver after boot that
370 * discovers a new max frequency.
373 set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
375 if (tsc_is_invariant)
378 /* Register to find out about changes in CPU frequency. */
379 tsc_pre_tag = EVENTHANDLER_REGISTER(cpufreq_pre_change,
380 tsc_freq_changing, NULL, EVENTHANDLER_PRI_FIRST);
381 tsc_post_tag = EVENTHANDLER_REGISTER(cpufreq_post_change,
382 tsc_freq_changed, NULL, EVENTHANDLER_PRI_FIRST);
383 tsc_levels_tag = EVENTHANDLER_REGISTER(cpufreq_levels_changed,
384 tsc_levels_changed, NULL, EVENTHANDLER_PRI_ANY);
390 * RDTSC is not a serializing instruction, and does not drain
391 * instruction stream, so we need to drain the stream before executing
392 * it. It could be fixed by use of RDTSCP, except the instruction is
393 * not available everywhere.
395 * Use CPUID for draining in the boot-time SMP constistency test. The
396 * timecounters use MFENCE for AMD CPUs, and LFENCE for others (Intel
397 * and VIA) when SSE2 is present, and nothing on older machines which
398 * also do not issue RDTSC prematurely. There, testing for SSE2 and
399 * vendor is too cumbersome, and we learn about TSC presence from CPUID.
401 * Do not use do_cpuid(), since we do not need CPUID results, which
402 * have to be written into memory with do_cpuid().
404 #define TSC_READ(x) \
406 tsc_read_##x(void *arg) \
408 uint64_t *tsc = arg; \
409 u_int cpu = PCPU_GET(cpuid); \
411 __asm __volatile("cpuid" : : : "eax", "ebx", "ecx", "edx"); \
412 tsc[cpu * 3 + x] = rdtsc(); \
422 comp_smp_tsc(void *arg)
426 u_int cpu = PCPU_GET(cpuid);
429 size = (mp_maxid + 1) * 3;
430 for (i = 0, tsc = arg; i < N; i++, tsc += size)
434 d1 = tsc[cpu * 3 + 1] - tsc[j * 3];
435 d2 = tsc[cpu * 3 + 2] - tsc[j * 3 + 1];
436 if (d1 <= 0 || d2 <= 0) {
444 adj_smp_tsc(void *arg)
448 u_int cpu = PCPU_GET(cpuid);
449 u_int first, i, size;
456 size = (mp_maxid + 1) * 3;
457 for (i = 0, tsc = arg; i < N; i++, tsc += size) {
458 d = tsc[first * 3] - tsc[cpu * 3 + 1];
461 d = tsc[first * 3 + 1] - tsc[cpu * 3 + 2];
464 d = tsc[first * 3 + 1] - tsc[cpu * 3];
467 d = tsc[first * 3 + 2] - tsc[cpu * 3 + 1];
473 d = min / 2 + max / 2;
475 "movl $0x10, %%ecx\n\t"
477 "addl %%edi, %%eax\n\t"
478 "adcl %%esi, %%edx\n\t"
481 : "D" ((uint32_t)d), "S" ((uint32_t)(d >> 32))
482 : "ax", "cx", "dx", "cc"
487 test_tsc(int adj_max_count)
489 uint64_t *data, *tsc;
492 if ((!smp_tsc && !tsc_is_invariant) || vm_guest)
494 size = (mp_maxid + 1) * 3;
495 data = malloc(sizeof(*data) * size * N, M_TEMP, M_WAITOK);
498 for (i = 0, tsc = data; i < N; i++, tsc += size)
499 smp_rendezvous(tsc_read_0, tsc_read_1, tsc_read_2, tsc);
500 smp_tsc = 1; /* XXX */
501 smp_rendezvous(smp_no_rendezvous_barrier, comp_smp_tsc,
502 smp_no_rendezvous_barrier, data);
503 if (!smp_tsc && adj < adj_max_count) {
505 smp_rendezvous(smp_no_rendezvous_barrier, adj_smp_tsc,
506 smp_no_rendezvous_barrier, data);
511 printf("SMP: %sed TSC synchronization test%s\n",
512 smp_tsc ? "pass" : "fail",
513 adj > 0 ? " after adjustment" : "");
514 if (smp_tsc && tsc_is_invariant) {
515 switch (cpu_vendor_id) {
517 case CPU_VENDOR_HYGON:
519 * Starting with Family 15h processors, TSC clock
520 * source is in the north bridge. Check whether
521 * we have a single-socket/multi-core platform.
522 * XXX Need more work for complex cases.
524 if (CPUID_TO_FAMILY(cpu_id) < 0x15 ||
525 (amd_feature2 & AMDID2_CMP) == 0 ||
526 smp_cpus > (cpu_procinfo2 & AMDID_CMP_CORES) + 1)
529 case CPU_VENDOR_INTEL:
531 * XXX Assume Intel platforms have synchronized TSCs.
550 if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
554 * Limit timecounter frequency to fit in an int and prevent it from
555 * overflowing too fast.
560 * We can not use the TSC if we support APM. Precise timekeeping
561 * on an APM'ed machine is at best a fools pursuit, since
562 * any and all of the time spent in various SMM code can't
563 * be reliably accounted for. Reading the RTC is your only
564 * source of reliable time info. The i8254 loses too, of course,
565 * but we need to have some kind of time...
566 * We don't know at this point whether APM is going to be used
567 * or not, nor when it might be activated. Play it safe.
569 if (power_pm_get_type() == POWER_PM_TYPE_APM) {
570 tsc_timecounter.tc_quality = -1000;
572 printf("TSC timecounter disabled: APM enabled.\n");
577 * Intel CPUs without a C-state invariant TSC can stop the TSC
578 * in either C2 or C3. Disable use of C2 and C3 while using
579 * the TSC as the timecounter. The timecounter can be changed
580 * to enable C2 and C3.
582 * Note that the TSC is used as the cputicker for computing
583 * thread runtime regardless of the timecounter setting, so
584 * using an alternate timecounter and enabling C2 or C3 can
585 * result incorrect runtimes for kernel idle threads (but not
586 * for any non-idle threads).
588 if (cpu_vendor_id == CPU_VENDOR_INTEL &&
589 (amd_pminfo & AMDPM_TSC_INVARIANT) == 0) {
590 tsc_timecounter.tc_flags |= TC_FLAGS_C2STOP;
592 printf("TSC timecounter disables C2 and C3.\n");
596 * We can not use the TSC in SMP mode unless the TSCs on all CPUs
597 * are synchronized. If the user is sure that the system has
598 * synchronized TSCs, set kern.timecounter.smp_tsc tunable to a
599 * non-zero value. The TSC seems unreliable in virtualized SMP
600 * environments, so it is set to a negative quality in those cases.
604 tsc_timecounter.tc_quality = test_tsc(smp_tsc_adjust);
607 if (tsc_is_invariant)
608 tsc_timecounter.tc_quality = 1000;
609 max_freq >>= tsc_shift;
612 for (shift = 0; shift <= 31 && (tsc_freq >> shift) > max_freq; shift++)
614 if ((cpu_feature & CPUID_SSE2) != 0 && mp_ncpus > 1) {
615 if (cpu_vendor_id == CPU_VENDOR_AMD ||
616 cpu_vendor_id == CPU_VENDOR_HYGON) {
617 tsc_timecounter.tc_get_timecount = shift > 0 ?
618 tsc_get_timecount_low_mfence :
619 tsc_get_timecount_mfence;
621 tsc_timecounter.tc_get_timecount = shift > 0 ?
622 tsc_get_timecount_low_lfence :
623 tsc_get_timecount_lfence;
626 tsc_timecounter.tc_get_timecount = shift > 0 ?
627 tsc_get_timecount_low : tsc_get_timecount;
630 tsc_timecounter.tc_name = "TSC-low";
632 printf("TSC timecounter discards lower %d bit(s)\n",
636 tsc_timecounter.tc_frequency = tsc_freq >> shift;
637 tsc_timecounter.tc_priv = (void *)(intptr_t)shift;
638 tc_init(&tsc_timecounter);
641 SYSINIT(tsc_tc, SI_SUB_SMP, SI_ORDER_ANY, init_TSC_tc, NULL);
649 /* If TSC was not good on boot, it is unlikely to become good now. */
650 if (tsc_timecounter.tc_quality < 0)
652 /* Nothing to do with UP. */
657 * If TSC was good, a single synchronization should be enough,
658 * but honour smp_tsc_adjust if it's set.
660 quality = test_tsc(MAX(smp_tsc_adjust, 1));
661 if (quality != tsc_timecounter.tc_quality) {
662 printf("TSC timecounter quality changed: %d -> %d\n",
663 tsc_timecounter.tc_quality, quality);
664 tsc_timecounter.tc_quality = quality;
670 * When cpufreq levels change, find out about the (new) max frequency. We
671 * use this to update CPU accounting in case it got a lower estimate at boot.
674 tsc_levels_changed(void *arg, int unit)
677 struct cf_level *levels;
681 /* Only use values from the first CPU, assuming all are equal. */
685 /* Find the appropriate cpufreq device instance. */
686 cf_dev = devclass_get_device(devclass_find("cpufreq"), unit);
687 if (cf_dev == NULL) {
688 printf("tsc_levels_changed() called but no cpufreq device?\n");
692 /* Get settings from the device and find the max frequency. */
694 levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
697 error = CPUFREQ_LEVELS(cf_dev, levels, &count);
698 if (error == 0 && count != 0) {
699 max_freq = (uint64_t)levels[0].total_set.freq * 1000000;
700 set_cputicker(rdtsc, max_freq, 1);
702 printf("tsc_levels_changed: no max freq found\n");
703 free(levels, M_TEMP);
707 * If the TSC timecounter is in use, veto the pending change. It may be
708 * possible in the future to handle a dynamically-changing timecounter rate.
711 tsc_freq_changing(void *arg, const struct cf_level *level, int *status)
714 if (*status != 0 || timecounter != &tsc_timecounter)
717 printf("timecounter TSC must not be in use when "
718 "changing frequencies; change denied\n");
722 /* Update TSC freq with the value indicated by the caller. */
724 tsc_freq_changed(void *arg, const struct cf_level *level, int status)
728 /* If there was an error during the transition, don't do anything. */
729 if (tsc_disabled || status != 0)
732 /* Total setting for this level gives the new frequency in MHz. */
733 freq = (uint64_t)level->total_set.freq * 1000000;
734 atomic_store_rel_64(&tsc_freq, freq);
735 tsc_timecounter.tc_frequency =
736 freq >> (int)(intptr_t)tsc_timecounter.tc_priv;
740 sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
745 freq = atomic_load_acq_64(&tsc_freq);
748 error = sysctl_handle_64(oidp, &freq, 0, req);
749 if (error == 0 && req->newptr != NULL) {
750 atomic_store_rel_64(&tsc_freq, freq);
751 atomic_store_rel_64(&tsc_timecounter.tc_frequency,
752 freq >> (int)(intptr_t)tsc_timecounter.tc_priv);
757 SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq, CTLTYPE_U64 | CTLFLAG_RW,
758 0, 0, sysctl_machdep_tsc_freq, "QU", "Time Stamp Counter frequency");
761 tsc_get_timecount(struct timecounter *tc __unused)
768 tsc_get_timecount_low(struct timecounter *tc)
772 __asm __volatile("rdtsc; shrd %%cl, %%edx, %0"
773 : "=a" (rv) : "c" ((int)(intptr_t)tc->tc_priv) : "edx");
778 tsc_get_timecount_lfence(struct timecounter *tc __unused)
786 tsc_get_timecount_low_lfence(struct timecounter *tc)
790 return (tsc_get_timecount_low(tc));
794 tsc_get_timecount_mfence(struct timecounter *tc __unused)
802 tsc_get_timecount_low_mfence(struct timecounter *tc)
806 return (tsc_get_timecount_low(tc));
810 x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th, struct timecounter *tc)
813 vdso_th->th_algo = VDSO_TH_ALGO_X86_TSC;
814 vdso_th->th_x86_shift = (int)(intptr_t)tc->tc_priv;
815 vdso_th->th_x86_hpet_idx = 0xffffffff;
816 bzero(vdso_th->th_res, sizeof(vdso_th->th_res));
820 #ifdef COMPAT_FREEBSD32
822 x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
823 struct timecounter *tc)
826 vdso_th32->th_algo = VDSO_TH_ALGO_X86_TSC;
827 vdso_th32->th_x86_shift = (int)(intptr_t)tc->tc_priv;
828 vdso_th32->th_x86_hpet_idx = 0xffffffff;
829 bzero(vdso_th32->th_res, sizeof(vdso_th32->th_res));