Re: [PATCH 2/2] KVM: x86/pmu: Clear PERF_GLOBAL_CTRL after switching to guest LVTPC
From: Yosry Ahmed
Date: Tue Dec 01 2026 - 23:33:49 EST
On Tue, Dec 1, 2026 at 7:39 PM Mi, Dapeng <dapeng1.mi@xxxxxxxxxxxxxxx> wrote:
>
>
> On 12/2/2026 9:14 AM, Sean Christopherson wrote:
> > On Tue, Dec 01, 2026, Yosry Ahmed wrote:
> >> On Tue, Dec 1, 2026 at 3:50 PM Sean Christopherson <seanjc@xxxxxxxxxx> wrote:
> >>> On Tue, Dec 01, 2026, Yosry Ahmed wrote:
> >>>> 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()).
> >>> But disabling PERF_GLOBAL_CTRL should prevent taking any perf NMIs, no?
> >> If I am reading the code correctly, perf_event_nmi_handler() ->
> >> intel_pmu_handle_irq() -> __intel_pmu_enable_all() will be executed on
> >> an NMI even if it wasn't a perf NMI (__intel_pmu_enable_all() is
> >> called in the done label even if status is clear), but I might be
> >> mistaken.
> > That feels like a perf bug? I would expect perf_load_guest_context() to prevent
> > trying to enable perf events.
IIUC, perf not clearing PERF_GLOBAL_CTRL after
perf_load_guest_context() is the reason KVM clears PERF_GLOBAL_CTRL
here to begin with:
https://lore.kernel.org/all/aR43LoV1ti5-2WRD@xxxxxxxxxx/.
> perf_load_guest_context() schedule out all host events, and
> perf_event_nmi_handler() should early return and don't touch any PMU MSRs
> if active_events is 0. While the issue is that active_events currently
> doesn't really track the active events as what it intends. Instead, it
> seems to track the created events regardless of it's active. This is a perf
> bug.
>
> It's intended to clear GLOBAL_CTRL MSR before calling
> perf_load_guest_lvtpc(), it prevents triggering PMI from hit into
> perf_load_guest_lvtpc().
>
> It looks the better way to fix this issue is to make active_events really
> track the active events (increase/decrease active_events in
> x86_pmu_add()/x86_pmu_del()).
If active_events is always 0 while the guest LVTPC is loaded, then we
can probably drop guest_lvtpc_loaded, right?
Having perf clear GLOBAL_CTRL when no events are active (e.g. in
perf_load_guest_context() and in the NMI handler) would also let KVM
drop the MSR write completely. It seems like that's what Peter and
Sean initially expected based on the discussion linked above
Anyway, either of the above seems like it may be a more intrusive fix
for stable, but if Sean/Peter think it's fine then it works for me
too.