From: Jinrong Liang <cloudliang@xxxxxxxxxxx> Add test to check if non-existent counters can be accessed in guest after determining the number of Intel generic performance counters by CPUID. Per SDM, fixed-function performance counter 'i' is supported if ECX[i] || (EDX[4:0] > i). KVM doesn't emulate more counters than it can support. Co-developed-by: Like Xu <likexu@xxxxxxxxxxx> Signed-off-by: Like Xu <likexu@xxxxxxxxxxx> Signed-off-by: Jinrong Liang <cloudliang@xxxxxxxxxxx> --- .../kvm/x86_64/pmu_basic_functionality_test.c | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/tools/testing/selftests/kvm/x86_64/pmu_basic_functionality_test.c b/tools/testing/selftests/kvm/x86_64/pmu_basic_functionality_test.c index 116437ac2095..e19f8c2774c5 100644 --- a/tools/testing/selftests/kvm/x86_64/pmu_basic_functionality_test.c +++ b/tools/testing/selftests/kvm/x86_64/pmu_basic_functionality_test.c @@ -228,10 +228,46 @@ static void test_oob_gp_counter(uint8_t eax_gp_num, uint8_t offset, kvm_vm_free(vm); } +static void intel_test_oob_fixed_ctr(uint8_t edx_fix_num, + uint32_t fixed_bitmask, uint64_t expected) +{ + struct kvm_vm *vm; + struct kvm_vcpu *vcpu; + struct kvm_cpuid_entry2 *entry; + uint8_t idx = edx_fix_num; + bool visible; + uint64_t msr_val; + + vm = pmu_vm_create_with_one_vcpu(&vcpu, guest_wr_and_rd_msrs); + + entry = vcpu_get_cpuid_entry(vcpu, 0xa); + entry->ecx = fixed_bitmask; + entry->edx = (entry->edx & ~FIXED_CTR_NUM_MASK) | edx_fix_num; + vcpu_set_cpuid(vcpu); + + /* Per Intel SDM, FxCtr[i]_is_supported := ECX[i] || (EDX[4:0] > i). */ + visible = (entry->ecx & BIT_ULL(idx) || + ((entry->edx & FIXED_CTR_NUM_MASK) > idx)); + + /* KVM doesn't emulate more fixed counters than it can support. */ + if (idx >= X86_INTEL_MAX_FIXED_CTR_NUM) + visible = false; + + vcpu_args_set(vcpu, 4, MSR_CORE_PERF_FIXED_CTR0, 0xffff, idx, 1); + if (!visible) + while (run_vcpu(vcpu, &msr_val) != UCALL_DONE) + TEST_ASSERT(msr_val == expected, + "Unexpected when testing fixed counter num."); + + kvm_vm_free(vm); +} + static void intel_test_counters_num(void) { unsigned int i; + uint32_t ecx; uint8_t kvm_gp_num = X86_INTEL_MAX_GP_CTR_NUM; + uint8_t kvm_fixed_num = X86_INTEL_MAX_FIXED_CTR_NUM; TEST_REQUIRE(kvm_gp_num > 2); @@ -254,6 +290,12 @@ static void intel_test_counters_num(void) if (perf_caps[i] == 0) test_oob_gp_counter(0, 2, perf_caps[i], 0); } + + for (ecx = 0; ecx <= X86_INTEL_FIXED_CTRS_BITMASK + 1; ecx++) { + intel_test_oob_fixed_ctr(0, ecx, GP_VECTOR); + intel_test_oob_fixed_ctr(kvm_fixed_num, ecx, GP_VECTOR); + intel_test_oob_fixed_ctr(kvm_fixed_num + 1, ecx, GP_VECTOR); + } } static void intel_test_pmu_cpuid(void) -- 2.31.1