[PATCH v4 5/9] KVM: selftests: Test Intel PMU architectural events on fixed counters

From: Jinrong Liang
Date: Mon Sep 11 2023 - 17:04:18 EST


From: Jinrong Liang <cloudliang@xxxxxxxxxxx>

Update test to cover Intel PMU architectural events on fixed counters.
Per Intel SDM, PMU users can also count architecture performance events
on fixed counters (specifically, FIXED_CTR0 for the retired instructions
and FIXED_CTR1 for cpu core cycles event). Therefore, if guest's CPUID
indicates that an architecture event is not available, the corresponding
fixed counter will also not count that event.

Co-developed-by: Like Xu <likexu@xxxxxxxxxxx>
Signed-off-by: Like Xu <likexu@xxxxxxxxxxx>
Signed-off-by: Jinrong Liang <cloudliang@xxxxxxxxxxx>
---
.../selftests/kvm/x86_64/pmu_counters_test.c | 22 +++++++++++++++++++
1 file changed, 22 insertions(+)

diff --git a/tools/testing/selftests/kvm/x86_64/pmu_counters_test.c b/tools/testing/selftests/kvm/x86_64/pmu_counters_test.c
index f47853f3ab84..fe9f38a3557e 100644
--- a/tools/testing/selftests/kvm/x86_64/pmu_counters_test.c
+++ b/tools/testing/selftests/kvm/x86_64/pmu_counters_test.c
@@ -106,6 +106,28 @@ static void guest_measure_loop(uint8_t idx)
GUEST_ASSERT_EQ(expect, !!_rdpmc(i));
}

+ if (this_cpu_property(X86_PROPERTY_PMU_NR_FIXED_COUNTERS) < 1)
+ goto done;
+
+ if (idx == INTEL_ARCH_INSTRUCTIONS_RETIRED)
+ i = 0;
+ else if (idx == INTEL_ARCH_CPU_CYCLES)
+ i = 1;
+ else if (idx == PSEUDO_ARCH_REFERENCE_CYCLES)
+ i = 2;
+ else
+ goto done;
+
+ wrmsr(MSR_CORE_PERF_FIXED_CTR0 + i, 0);
+ wrmsr(MSR_CORE_PERF_FIXED_CTR_CTRL, BIT_ULL(4 * i));
+
+ wrmsr(MSR_CORE_PERF_GLOBAL_CTRL, BIT_ULL(PMC_IDX_FIXED + i));
+ __asm__ __volatile__("loop ." : "+c"((int){NUM_BRANCHES}));
+ wrmsr(MSR_CORE_PERF_GLOBAL_CTRL, 0);
+
+ GUEST_ASSERT_EQ(expect, !!_rdpmc(PMC_FIXED_RDPMC_BASE | i));
+
+done:
GUEST_DONE();
}

--
2.39.3