[RFC PATCH 21/26] KVM: x86/pmu: Make loading/putting the mediated PMU context idempotent
From: Yosry Ahmed
Date: Mon Nov 23 2026 - 19:24:39 EST
Make kvm_mediated_pmu_load() and kvm_mediated_pmu_put() bail if the
guest context is already loaded or put, respectively, in preparation for
leaving the guest context loaded across slowpath VM-Exits.
kvm_mediated_pmu_load() will still be called on every vcpu_enter_guest(),
even if the guest context is still loaded, and kvm_mediated_pmu_put()
will be called from multiple paths, e.g. on slowpath VM-Exits, on
vcpu_put(), and when perf reclaims the mediated PMU, any of which may
find the guest context already put.
Checking the per-CPU state is sufficient, as only the running vCPU's
guest context can be loaded on a CPU: it is put on vcpu_put() before
another vCPU can run.
Move lockdep_assert_irqs_disabled() before the checks, so that callers
are verified to have IRQs disabled even if loading/putting is skipped.
Signed-off-by: Yosry Ahmed <yosry@xxxxxxxxxx>
---
arch/x86/kvm/pmu.c | 14 ++++++++------
1 file changed, 8 insertions(+), 6 deletions(-)
diff --git a/arch/x86/kvm/pmu.c b/arch/x86/kvm/pmu.c
index e92a7a1f20a89..d56cd0fa817d7 100644
--- a/arch/x86/kvm/pmu.c
+++ b/arch/x86/kvm/pmu.c
@@ -1420,11 +1420,12 @@ void kvm_pmu_sync_lvtpc(struct kvm_vcpu *vcpu, u32 lvtpc)
void kvm_mediated_pmu_load(struct kvm_vcpu *vcpu)
{
- if (KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
- return;
-
lockdep_assert_irqs_disabled();
+ if (is_guest_mediated_pmu_loaded() ||
+ KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
+ return;
+
perf_load_guest_context();
/*
@@ -1480,11 +1481,12 @@ static void kvm_pmu_put_guest_pmcs(struct kvm_vcpu *vcpu)
void kvm_mediated_pmu_put(struct kvm_vcpu *vcpu)
{
- if (KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
- return;
-
lockdep_assert_irqs_disabled();
+ if (!is_guest_mediated_pmu_loaded() ||
+ KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
+ return;
+
/*
* Defer handling of PERF_GLOBAL_CTRL to vendor code. On Intel, it's
* atomically cleared on VM-Exit, i.e. doesn't need to be clear here.
--
2.56.1.809.ga0b61035b5-goog