Re: [PATCH] KVM: x86/pmu: Avoid ternary operator by directly referring to counters->type

From: Sean Christopherson
Date: Tue Dec 06 2022 - 12:19:55 EST


On Tue, Dec 06, 2022, Like Xu wrote:
> > > diff --git a/arch/x86/kvm/vmx/pmu_intel.c b/arch/x86/kvm/vmx/pmu_intel.c
> > > index e5cec07ca8d9..28b0a784f6e9 100644
> > > --- a/arch/x86/kvm/vmx/pmu_intel.c
> > > +++ b/arch/x86/kvm/vmx/pmu_intel.c
> > > @@ -142,7 +142,7 @@ static struct kvm_pmc *intel_rdpmc_ecx_to_pmc(struct kvm_vcpu *vcpu,
> > > }
> > > if (idx >= num_counters)
> > > return NULL;
> > > - *mask &= pmu->counter_bitmask[fixed ? KVM_PMC_FIXED : KVM_PMC_GP];
> > > + *mask &= pmu->counter_bitmask[counters->type];
> >
> > In terms of readability, I have a slight preference for the current code as I
> > don't have to look at counters->type to understand its possible values.
> When someone tries to add a new type of pmc type, the code bugs up.

Are there new types coming along? If so, I definitely would not object to refactoring
this code in the context of a series that adds a new type(s). But "fixing" this one
case is not sufficient to support a new type, e.g. intel_is_valid_rdpmc_ecx() also
needs to be updated. Actually, even this function would need additional updates
to perform a similar sanity check.

if (fixed) {
counters = pmu->fixed_counters;
num_counters = pmu->nr_arch_fixed_counters;
} else {
counters = pmu->gp_counters;
num_counters = pmu->nr_arch_gp_counters;
}
if (idx >= num_counters)
return NULL;

> And, this one will make all usage of pmu->counter_bitmask[] more consistent.

How's that? There's literally one instance of using ->type

static inline u64 pmc_bitmask(struct kvm_pmc *pmc)
{
struct kvm_pmu *pmu = pmc_to_pmu(pmc);

return pmu->counter_bitmask[pmc->type];
}

everything else is hardcoded. And using pmc->type there make perfect sense in
that case. But in intel_rdpmc_ecx_to_pmc(), there is already usage of "fixed",
so IMO switching to ->type makes that function somewhat inconsistent with itself.