[RFC PATCH 20/26] KVM: x86/pmu: Check for a mediated PMU before loading/putting its context

From: Yosry Ahmed

Date: Mon Nov 23 2026 - 19:24:38 EST


Move the checks for whether the vCPU has a mediated PMU from
kvm_mediated_pmu_load() and kvm_mediated_pmu_put() to their callers, in
preparation for putting the guest context from more places, and
conditionally on whether perf has events conflicting with the mediated
PMU. The new callers need to check for a mediated PMU first anyway,
e.g. to avoid querying perf or disabling IRQs for vCPUs without a
mediated PMU.

No functional change intended.

Signed-off-by: Yosry Ahmed <yosry@xxxxxxxxxx>
---
arch/x86/kvm/pmu.c | 6 ++----
arch/x86/kvm/x86.c | 6 ++++--
2 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/arch/x86/kvm/pmu.c b/arch/x86/kvm/pmu.c
index cee3c4719dd14..e92a7a1f20a89 100644
--- a/arch/x86/kvm/pmu.c
+++ b/arch/x86/kvm/pmu.c
@@ -1420,8 +1420,7 @@ void kvm_pmu_sync_lvtpc(struct kvm_vcpu *vcpu, u32 lvtpc)

void kvm_mediated_pmu_load(struct kvm_vcpu *vcpu)
{
- if (!kvm_vcpu_has_mediated_pmu(vcpu) ||
- KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
+ if (KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
return;

lockdep_assert_irqs_disabled();
@@ -1481,8 +1480,7 @@ static void kvm_pmu_put_guest_pmcs(struct kvm_vcpu *vcpu)

void kvm_mediated_pmu_put(struct kvm_vcpu *vcpu)
{
- if (!kvm_vcpu_has_mediated_pmu(vcpu) ||
- KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
+ if (KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
return;

lockdep_assert_irqs_disabled();
diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index 2cd9ee316aada..8370ccceadb82 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -8392,7 +8392,8 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
run_flags |= KVM_RUN_LOAD_DEBUGCTL;
vcpu->arch.host_debugctl = debug_ctl;

- kvm_mediated_pmu_load(vcpu);
+ if (kvm_vcpu_has_mediated_pmu(vcpu))
+ kvm_mediated_pmu_load(vcpu);

guest_timing_enter_irqoff();

@@ -8432,7 +8433,8 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)

kvm_load_host_pkru(vcpu);

- kvm_mediated_pmu_put(vcpu);
+ if (kvm_vcpu_has_mediated_pmu(vcpu))
+ kvm_mediated_pmu_put(vcpu);

/*
* Do this here before restoring debug registers on the host. And
--
2.56.1.809.ga0b61035b5-goog