[PATCH 2/2] KVM: x86/pmu: Clear PERF_GLOBAL_CTRL after switching to guest LVTPC
From: Yosry Ahmed
Date: Tue Dec 01 2026 - 12:15:03 EST
When loading the guest PMU context, clear PERF_GLOBAL_CTRL after
switching to guest LVTPC. Otherwise, the host perf NMI handler may set
bits in PERF_GLOBAL_CTRL after KVM clears it (specifically on Intel,
through __intel_pmu_enable_all()). This results in PERF_GLOBAL_CTRL not
being cleared when the guest counters and event selectors are loaded, so
the guest counters could start counting in the host.
Switching LVTPC while PERF_GLOBAL_CTRL is non-zero should be safe as all
host events should be disabled at this point, and guest
counters/selectors are not loaded yet. Although it is worth noting that
switching LVTPC while PERF_GLOBAL_CTRL was cleared was intentional [1].
Alternatively, clearing PERF_GLOBAL_CTRL could be moved inside
perf_load_guest_lvtpc(), after setting guest_lvtpc_loaded but before
writing APIC_LVTPC. This would make sure PERF_GLOBAL_CTRL is cleared
after host NMIs can no longer set it, and that switching LVTPC happens
with PERF_GLOBAL_CTRL cleared. However, this would require more plumbing
on the perf side.
Fixes: 56bb27369750 ("KVM: x86/pmu: Load/put mediated PMU context when entering/exiting guest")
Cc: stable@xxxxxxxxxxxxxxx
Link: https://lore.kernel.org/20250818143204.GH3289052@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # [1]
Signed-off-by: Yosry Ahmed <yosry@xxxxxxxxxx>
---
arch/x86/kvm/pmu.c | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/arch/x86/kvm/pmu.c b/arch/x86/kvm/pmu.c
index eef2f792dc9e8..1a41cd4c4ecb4 100644
--- a/arch/x86/kvm/pmu.c
+++ b/arch/x86/kvm/pmu.c
@@ -1355,6 +1355,8 @@ void kvm_mediated_pmu_load(struct kvm_vcpu *vcpu)
perf_load_guest_context();
+ perf_load_guest_lvtpc(kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVTPC));
+
/*
* Explicitly clear PERF_GLOBAL_CTRL, as "loading" the guest's context
* disables all individual counters (if any were enabled), but doesn't
@@ -1367,11 +1369,13 @@ void kvm_mediated_pmu_load(struct kvm_vcpu *vcpu)
* configuring all events to be GUEST_ONLY. Clear PERF_GLOBAL_CONTROL
* even for SVM to minimize the damage if a perf event is left enabled,
* and to ensure a consistent starting state.
+ *
+ * Clear PERF_GLOBAL_CTRL after switching to the guest LVTPC, as the
+ * host perf NMI handler may set bits in PERF_GLOBAL_CTRL even if events
+ * are disabled.
*/
wrmsrq(kvm_pmu_ops.PERF_GLOBAL_CTRL, 0);
- perf_load_guest_lvtpc(kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVTPC));
-
kvm_pmu_load_guest_pmcs(vcpu);
kvm_pmu_call(mediated_load)(vcpu);
--
2.56.1.839.g22a8290db9-goog