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

From: Mingwei Zhang
Date: Tue Nov 07 2023 - 18:48:00 EST


On Tue, Nov 7, 2023 at 3:02 PM Sean Christopherson <seanjc@xxxxxxxxxx> wrote:
>
> On Tue, Nov 07, 2023, Mingwei Zhang wrote:
> > On Tue, Nov 07, 2023, Sean Christopherson wrote:
> > > arch/x86/events/core.c | 21 +++++++++++++++------
> > > 1 file changed, 15 insertions(+), 6 deletions(-)
> > >
> > > 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);
> > > + }
> > >
> > > this_cpu_write(pmc_prev_left[idx], left);
> > >
> >
> > Nice one. I am curious how you tested this one? I would like to
> > reproduce that one on my side.
>
> The check_emulated_instr() sub-test in KVM-Unit-Tests's x86/pmu.c fails when run
> with "my" (which is really yours) fix for the KVM's handling of emulated PMC
> events[*]. If KVM synthesizes an "instructions retired" event that bumps the
> PMC to all ones, i.e. -1 for all intents and purposes, the test fails because
> KVM creates a sample_period of '1', but perf programs a period of '2'.
>
> I suspect a very simple test of writing -1 to a PMC from the guest would exhibit
> the same behavior.
>
> [*] https://lkml.kernel.org/r/ZUWAg3WP2XESCAR4%40google.com

Nice, I will try that and see if I can reproduce. Will give
Reviewed-by after testing it on my side.

Thanks.
-Mingwei