Re: [PATCH v4 06/21] KVM: x86/pmu: Drop nr_arch_{gp,fixed}_counters from kvm_pmu

From: Yosry Ahmed

Date: Wed Nov 18 2026 - 10:46:32 EST


On Wed, Nov 18, 2026 at 12:59:07AM +0000, Yosry Ahmed wrote:
> On Tue, Nov 17, 2026 at 02:02:08PM -0600, Chen, Zide wrote:
> >
> >
> > On 11/17/2026 11:23 AM, Yosry Ahmed wrote:
> > >> static void amd_pmu_init(struct kvm_vcpu *vcpu)
> > >> diff --git a/arch/x86/kvm/svm/svm.c b/arch/x86/kvm/svm/svm.c
> > >> index 136069dfcd44..e21abcedea70 100644
> > >> --- a/arch/x86/kvm/svm/svm.c
> > >> +++ b/arch/x86/kvm/svm/svm.c
> > >> @@ -761,24 +761,21 @@ static void svm_recalc_pmu_msr_intercepts(struct kvm_vcpu *vcpu)
> > >> {
> > >> bool intercept = !kvm_vcpu_has_mediated_pmu(vcpu);
> > >> struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
> > >> + unsigned long gp_mask = kvm_gp_pmc_mask(pmu);
> > >> int i;
> > >>
> > >> if (!enable_mediated_pmu)
> > >> return;
> > >>
> > >> /* Legacy counters are always available for AMD CPUs with a PMU. */
> > >> - for (i = 0; i < min(pmu->nr_arch_gp_counters, AMD64_NUM_COUNTERS); i++)
> > >> + for (i = 0; i < AMD64_NUM_COUNTERS; i++)
> > >> svm_set_intercept_for_msr(vcpu, MSR_K7_PERFCTR0 + i,
> > >> - MSR_TYPE_RW, intercept);
> > >> + MSR_TYPE_RW, intercept || !test_bit(i, &gp_mask));
> > >
> > > This fixes a pre-existing bug that was reported internally, that can
> > > happen if a malicious VMM reduces the number of counters after
> > > initiating KVM_RUN but before VM-entry. The current code would fail to
> > > re-enable the intercept on the counters that become unsupported.
> > >
> > > Might be worth splitting this out into a standalone fix.
> >
> > My hesitation on a separate patch was to avoid throwaway code churn.
> > A standalone patch would add:
> >
> > for ( ; i < AMD64_NUM_COUNTERS; i++)
> > svm_enable_intercept_for_msr(vcpu, MSR_K7_PERFCTR0 + i,
> > MSR_TYPE_RW);
> >
> > and then it will be immediately overwritten and collapsed into a single
> > loop in this patch.
> >
> > So basically cleaner logic vs. avoiding immediate churn. I'm happy to
> > split it out if you prefer.
>
> I think it's fine. You can also fix it by using the same loop struct we
> end up with instead of adding another loop? i.e. loop until
> AMD64_NUM_COUNTERS and intercept based on i < nr_arch_gp_counters
> instead of testing the GP mask?

Thinking about this a bit more, I think having two different loop
structures might be confusing when they are later changed/dropped. So
I'd rather do what you suggested initially and add the second loop as a
standalone fix.