[PATCH 1/3] KVM: x86/pmu: Recalc PMC emulation when deferring counter reprogramming

From: Yosry Ahmed

Date: Wed Nov 25 2026 - 13:27:20 EST


In preparation for always deferring counter reprogramming, recalculate
PMC emulation for each counter first. On AMD, this would make sure that
mode changes (e.g. via VMRUN or toggling EFER.SVME) are immediately
propagated before instruction emulation completes, such that
instructions are counted in the mode they retire in as hardware does.

This gives kvm_pmu_request_counters_reprogram() similar treatment to
kvm_pmu_request_counter_reprogram(), as done in commit 5dfd498bad5f
("KVM: x86/pmu: Calculate set of to-be-emulated PMCs at time of
WRMSRs").

Now that kvm_pmu_request_counter_reprogram() is just a single-counter
version of kvm_pmu_request_counters_reprogram(), just call the latter
from the former.

No functional change intended, as all architectural mode-changing paths
on AMD do not currently defer counter reprogramming.

Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Yosry Ahmed <yosry@xxxxxxxxxx>
---
arch/x86/kvm/pmu.h | 26 ++++++++++++++++----------
1 file changed, 16 insertions(+), 10 deletions(-)

diff --git a/arch/x86/kvm/pmu.h b/arch/x86/kvm/pmu.h
index 090c9bbb74f48..8aa9db1569167 100644
--- a/arch/x86/kvm/pmu.h
+++ b/arch/x86/kvm/pmu.h
@@ -218,26 +218,27 @@ void kvm_init_pmu_capability(struct kvm_pmu_ops *pmu_ops);
void kvm_pmu_recalc_pmc_emulation(struct kvm_pmu *pmu, struct kvm_pmc *pmc);
void kvm_pmu_handle_event(struct kvm_vcpu *vcpu);

-static inline void kvm_pmu_request_counter_reprogram(struct kvm_pmc *pmc)
-{
- kvm_pmu_recalc_pmc_emulation(pmc_to_pmu(pmc), pmc);
-
- set_bit(pmc->idx, pmc_to_pmu(pmc)->reprogram_pmi);
- kvm_make_request(KVM_REQ_PMU, pmc->vcpu);
-}
-
static inline void __kvm_pmu_reprogram_counters(struct kvm_pmu *pmu,
u64 counters,
bool defer)
{
+ DECLARE_BITMAP(bitmap, X86_PMC_IDX_MAX);
+ struct kvm_pmc *pmc;
+ int bit;
+
if (!counters)
return;

atomic64_or(counters, &pmu->__reprogram_pmi);
- if (defer)
+ if (defer) {
+ BUILD_BUG_ON(sizeof(bitmap) != sizeof(counters));
+ bitmap_from_u64(bitmap, counters);
+ kvm_for_each_pmc(pmu, pmc, bit, bitmap)
+ kvm_pmu_recalc_pmc_emulation(pmu, pmc);
kvm_make_request(KVM_REQ_PMU, pmu_to_vcpu(pmu));
- else
+ } else {
kvm_pmu_handle_event(pmu_to_vcpu(pmu));
+ }
}

static inline void kvm_pmu_request_counters_reprogram(struct kvm_pmu *pmu,
@@ -246,6 +247,11 @@ static inline void kvm_pmu_request_counters_reprogram(struct kvm_pmu *pmu,
__kvm_pmu_reprogram_counters(pmu, counters, true);
}

+static inline void kvm_pmu_request_counter_reprogram(struct kvm_pmc *pmc)
+{
+ kvm_pmu_request_counters_reprogram(pmc_to_pmu(pmc), BIT_ULL(pmc->idx));
+}
+
/*
* Check if a PMC is enabled by comparing it against global_ctrl bits.
*
--
2.56.1.839.g22a8290db9-goog