Re: [PATCH v4 09/21] KVM: x86/pmu: Switch to bitmask-based KVM PMU capabilities

From: Yosry Ahmed

Date: Wed Nov 18 2026 - 11:06:06 EST


On Thu, Nov 12, 2026 at 01:32:15PM -0700, Zide Chen wrote:
> From: Dapeng Mi <dapeng1.mi@xxxxxxxxxxxxxxx>
>
> Intel platforms support non-contiguous fixed counters via CPUID.0AH:ECX
> starting with PerfMon v5, and support non-contiguous GP counters
> through the Architectural PerfMon Extension (CPUID leaf 23H).
>
> struct x86_pmu_capability now exposes {,fixed_}cntr_mask64 bitmaps,
> which may contain sparse bits representing non-contiguous counters.
> Switch KVM's kvm_host_pmu and kvm_pmu_cap consumers over to the new
> bitmask fields, including iterating kvm_host_pmu bitmasks directly in
> VMX and SVM PMU MSR intercept setup.
>
> CPUID.0AH:EAX[15:8] and CPUID.0AH:EDX[4:0] enumerate only contiguous
> counters. Derive these values from kvm_pmu_cap.{,fixed_}cntr_mask64 as
> the number of consecutive counters starting at index 0.
>
> Signed-off-by: Dapeng Mi <dapeng1.mi@xxxxxxxxxxxxxxx>
> Co-developed-by: Zide Chen <zide.chen@xxxxxxxxx>
> Signed-off-by: Zide Chen <zide.chen@xxxxxxxxx>
> ---
> v4:
> - Cleanly substitute kvm_pmu_cap.num_counters_{gp,fixed} with
> find_first_zero_bit() in intel_pmu_refresh() without throwaway
> code churn.
> - Use find_first_zero_bit() instead of hweight64() for AMD CPUID
> 0x80000022 EBX[3:0] (NumCorePmc) and svm_set_cpu_caps() to enumerate
> contiguous counters. (Yosry)
> - Do not carry over Jim's Reviewed-by from v3 due to reworking counter
> clamping in intel_pmu_refresh().
>
> v3:
> - Iterate kvm_host_pmu bitmasks directly in VMX and SVM intercept loops.
> - Clamp nr_{gp,fixed}_counters to the number of contiguous counters
> supported by KVM in intel_pmu_refresh(). (Jim, Sashiko)
> - Drop redundant !enable_mediated_pmu clamp on fixed_cntr_mask64.
> (Sashiko)
> ---
> arch/x86/kvm/cpuid.c | 17 ++++++++++++++---
> arch/x86/kvm/msrs.c | 12 ++++++------
> arch/x86/kvm/pmu.c | 17 ++++++++---------
> arch/x86/kvm/svm/pmu.c | 2 +-
> arch/x86/kvm/svm/svm.c | 8 ++++----
> arch/x86/kvm/vmx/pmu_intel.c | 18 +++++++++++++++---
> arch/x86/kvm/vmx/vmx.c | 4 ++--
> 7 files changed, 50 insertions(+), 28 deletions(-)
>
> diff --git a/arch/x86/kvm/cpuid.c b/arch/x86/kvm/cpuid.c
> index adafd6fa2c54..427871ec365f 100644
> --- a/arch/x86/kvm/cpuid.c
> +++ b/arch/x86/kvm/cpuid.c
> @@ -1535,10 +1535,18 @@ static inline int __do_cpuid_func(struct kvm_cpuid_array *array, u32 function)
> }
>
> eax.split.version_id = kvm_pmu_cap.version;
> - eax.split.num_counters = kvm_pmu_cap.num_counters_gp;
> +
> + /* Contiguous GP counters only. */
> + eax.split.num_counters =
> + find_first_zero_bit(kvm_pmu_cap.cntr_mask,
> + KVM_MAX_NR_GP_COUNTERS);

Should we add helpers for the find_first_zero_bit() calls across?
Perhaps kvm_pmu_nr_contig_gp_counters() and
kvm_pmu_nr_contig_fixed_counters()?