Re: [PATCH 3/7] KVM: selftests: Test consistency of CPUID with num of GP counters

From: Sean Christopherson
Date: Wed May 24 2023 - 18:44:30 EST


On Thu, Mar 23, 2023, Like Xu wrote:
> diff --git a/tools/testing/selftests/kvm/x86_64/pmu_cpuid_test.c b/tools/testing/selftests/kvm/x86_64/pmu_cpuid_test.c
> index 75434aa2a0ec..50902187d2c9 100644
> --- a/tools/testing/selftests/kvm/x86_64/pmu_cpuid_test.c
> +++ b/tools/testing/selftests/kvm/x86_64/pmu_cpuid_test.c
> @@ -49,11 +49,31 @@ static const uint64_t arch_events[] = {
> /* Association of Fixed Counters with Architectural Performance Events */
> static int fixed_events[] = {1, 0, 7};
>
> +static const uint64_t perf_caps[] = {
> + 0,
> + PMU_CAP_FW_WRITES,
> +};
> +
> +/*
> + * KVM implements the first two non-existent counters (MSR_P6_PERFCTRx)
> + * via kvm_pr_unimpl_wrmsr() instead of #GP. It is acceptable here to test
> + * the third counter as there are usually more than 3 available gp counters.

Don't hedge, i.e. don't say things like "usually". And why not test that KVM
drops writes to the first two counters? Unlike KVM-Unit_tests, selftests can
test arbitrary KVM behavior without concern for breaking other use cases.

> +#define MSR_INTEL_ARCH_PMU_GPCTR (MSR_IA32_PERFCTR0 + 2)
> +
> static uint64_t evt_code_for_fixed_ctr(uint8_t idx)
> {
> return arch_events[fixed_events[idx]];
> }
>
> +static uint8_t kvm_gp_ctrs_num(void)
> +{
> + const struct kvm_cpuid_entry2 *kvm_entry;
> +
> + kvm_entry = get_cpuid_entry(kvm_get_supported_cpuid(), 0xa, 0);
> + return (kvm_entry->eax & GP_CTR_NUM_MASK) >> GP_CTR_NUM_OFS_BIT;

This definitely can be defined as a KVM_X86_CPU_PROPERTY(). Ditto for most of
the helpers that are added in future patches.

> static struct kvm_vcpu *new_vcpu(void *guest_code)
> {
> struct kvm_vm *vm;
> @@ -98,6 +118,30 @@ static bool first_uc_arg_non_zero(struct ucall *uc, void *data)
> return uc->args[1];
> }
>
> +static bool first_uc_arg_equals(struct ucall *uc, void *data)
> +{
> + return uc->args[1] == (uint64_t)data;
> +}
> +
> +static void guest_gp_handler(struct ex_regs *regs)
> +{
> + GUEST_SYNC(GP_VECTOR);
> + GUEST_DONE();
> +}
> +
> +static void guest_wr_and_rd_msrs(uint32_t base, uint64_t value,
> + uint8_t begin, uint8_t offset)
> +{
> + unsigned int i;
> +
> + for (i = begin; i < begin + offset; i++) {
> + wrmsr(base + i, value);
> + GUEST_SYNC(rdmsr(base + i));

Unless it won't work for something, use rdmsr_safe() and/oror wrmsr_safe() instead
of installing a dedicated handler. And if I'm reading the code correctly, that will
fix a bug in the test where only the first MSR is tested in the #GP case since the
#GP handler goes straight to GUEST_DONE(), i.e. doesn't skip and continue the rest
of the guest code. Maybe that isn't a bug in practice, e.g. each negative test only
tests a single MSR, but (a) that's not obvious and (b) it's an unnecessary limitation.


> + }
> +
> + GUEST_DONE();
> +}