Re: [PATCH] perf/x86: Don't enforce minimum period for KVM guest-only events

From: Sean Christopherson
Date: Tue Nov 28 2023 - 20:35:06 EST


On Fri, Nov 17, 2023, Peter Zijlstra wrote:
> On Tue, Nov 07, 2023 at 10:36:05AM -0800, Sean Christopherson wrote:
> > diff --git a/arch/x86/events/core.c b/arch/x86/events/core.c
> > index 40ad1425ffa2..f8a8a4ea4d47 100644
> > --- a/arch/x86/events/core.c
> > +++ b/arch/x86/events/core.c
> > @@ -1388,16 +1388,25 @@ int x86_perf_event_set_period(struct perf_event *event)
> > hwc->last_period = period;
> > ret = 1;
> > }
> > - /*
> > - * Quirk: certain CPUs dont like it if just 1 hw_event is left:
> > - */
> > - if (unlikely(left < 2))
> > - left = 2;
> >
> > if (left > x86_pmu.max_period)
> > left = x86_pmu.max_period;
> >
> > - static_call_cond(x86_pmu_limit_period)(event, &left);
> > + /*
> > + * Exempt KVM guest events from the minimum period requirements. It's
> > + * the guest's responsibility to ensure it can make forward progress,
> > + * and it's KVM's responsibility to configure an appropriate "period"
> > + * to correctly virtualize overflow for the guest's PMCs.
> > + */
> > + if (!event->attr.exclude_host) {
> > + /*
> > + * Quirk: certain CPUs dont like it if just 1 event is left:
> > + */
> > + if (unlikely(left < 2))
> > + left = 2;
> > +
> > + static_call_cond(x86_pmu_limit_period)(event, &left);
> > + }
>
> Hmm, IIRC we can disable that left < 2 thing for anything that doesn't
> have x86_pmu.pebs_no_isolation IIRC.
>
> I'm not sure about taking out the limit_period call, why does it make
> sense to allow the guest to program obviously invalid settings?

I don't see how the guest behavior is obviously invalid. Architecturally, writing
-1 to a counter should result in overflow after a single event. Underlying uarch
goofiness shouldn't enter into that equation.

Honoring the guest's programming *might* cause oddness for the guest, whereas
not honoring the architecture is guaranteed to cause visible issues.

If programming a "period" of 1 puts the host at risk in some way, then I agree
that this is unsafe and we need a different solution. But if the worst case
scenario is non-determinstic or odd behavior from the guest's perspective, then
that's the guest's problem (with the caveat that the guest might not have accurate
Family/Model/Stepping data to make informed decisions).

> That is, would something like the below work for you?

No, because the fix ideally wouldn't require fancy hardware, i.e. would work for
all CPUs for which KVM supports a virtual PMU.