Re: [PATCH v4 29/38] KVM: x86/pmu: Switch host/guest PMU context at vm-exit/vm-entry

From: Sean Christopherson
Date: Fri May 16 2025 - 09:27:04 EST


On Mon, Mar 24, 2025, Mingwei Zhang wrote:
> + /*
> + * Clear hardware selector MSR content and its counter to avoid
> + * leakage and also avoid this guest GP counter get accidentally
> + * enabled during host running when host enable global ctrl.
> + */
> + for (i = 0; i < pmu->nr_arch_gp_counters; i++) {
> + pmc = &pmu->gp_counters[i];
> + eventsel_msr = pmc_msr_addr(pmu, pmu->gp_eventsel_base, i);
> + counter_msr = pmc_msr_addr(pmu, pmu->gp_counter_base, i);
> +
> + rdpmcl(i, pmc->counter);
> + rdmsrl(eventsel_msr, pmc->eventsel_hw);

As pointed out by Dapeng offlist, this RDMSR is unnecessary since event selector
MSRs are always intercepted.

> + if (pmc->counter)
> + wrmsrl(counter_msr, 0);
> + if (pmc->eventsel_hw)
> + wrmsrl(eventsel_msr, 0);
> + }
> +
> + for (i = 0; i < pmu->nr_arch_fixed_counters; i++) {
> + pmc = &pmu->fixed_counters[i];
> + counter_msr = pmc_msr_addr(pmu, pmu->fixed_base, i);
> +
> + rdpmcl(INTEL_PMC_FIXED_RDPMC_BASE | i, pmc->counter);
> + if (pmc->counter)
> + wrmsrl(counter_msr, 0);
> + }
> +
> +}
> +static void intel_put_guest_context(struct kvm_vcpu *vcpu)
> +{
> + struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
> +
> + /* Global ctrl register is already saved at VM-exit. */
> + rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, pmu->global_status);
> +
> + /* Clear hardware MSR_CORE_PERF_GLOBAL_STATUS MSR, if non-zero. */
> + if (pmu->global_status)
> + wrmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, pmu->global_status);
> +
> + rdmsrl(MSR_CORE_PERF_FIXED_CTR_CTRL, pmu->fixed_ctr_ctrl_hw);

And same thing here. Though I'm confused as to why KVM always intercept
FIXED_CTR_CTRL.

/me rummages around the SDM

Ahh, because there are Any Thread bits in there. That absolutely needs to be
called out, probably in the interception logic in pmu_intel.c. I'll add a comment.