Re: [PATCH 01/12] KVM: x86: Add a framework for enabling KVM-governed x86 features

From: Sean Christopherson
Date: Fri Jun 30 2023 - 11:32:55 EST


On Fri, Jun 30, 2023, Chao Gao wrote:
> On Fri, Feb 17, 2023 at 03:10:11PM -0800, Sean Christopherson wrote:
> >+static __always_inline void kvm_governed_feature_set(struct kvm_vcpu *vcpu,
> >+ unsigned int x86_feature)
> >+{
> >+ BUILD_BUG_ON(KVM_NR_GOVERNED_FEATURES >
> >+ sizeof(vcpu->arch.governed_features.enabled) * BITS_PER_BYTE);
> >+
> >+ vcpu->arch.governed_features.enabled |= kvm_governed_feature_bit(x86_feature);
> >+}
> >+
> >+static __always_inline void kvm_governed_feature_check_and_set(struct kvm_vcpu *vcpu,
> >+ unsigned int x86_feature)
> >+{
> >+ if (guest_cpuid_has(vcpu, x86_feature))
>
> Most callers in this series are conditional on either boot_cpu_has() or some
> local variables. Can we convert them to kvm_cpu_cap_has() and incorporate them
> within this function? i.e.,
>
> if (kvm_cpu_cap_has(x86_feature) && guest_cpuid_has(vcpu, x86_feature))

Hmm, I was going to say "no", as most callers don't check kvm_cpu_cap_has() verbatim,
but it doesn't have to be that way. The majority of SVM features factor in module
params, but KVM should set the kvm_cpu capability if and only if a feature is supported
in hardware *and* enabled by its module param.

And arguably that's kinda sorta a bug fix, because this

if (lbrv)
kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_LBRV);

technically should be

if (lbrv && nested)
kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_LBRV);

Heh, and it's kinda sorta a bug fix for XSAVES on VMX, because this

if (cpu_has_vmx_xsaves() && boot_cpu_has(X86_FEATURE_XSAVE) &&
guest_cpuid_has(vcpu, X86_FEATURE_XSAVE))
kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_XSAVES);

should technically be

if (kvm_cpu_cap_has(X86_FEATURE_XSAVES) &&
boot_cpu_has(X86_FEATURE_XSAVE) &&
guest_cpuid_has(vcpu, X86_FEATURE_XSAVE))
kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_XSAVES);

> The benefits of doing so are
> 1. callers needn't repeat
>
> if (kvm_cpu_cap_has(x86_feature))
> kvm_governed_feature_check_and_set(x86_feature)
>
> 2. this fits the idea better that guests can use a governed feature only if host
> supports it _and_ QEMU exposes it to the guest.

Agreed, especially since we'll still have kvm_governed_feature_set() for the
extra special cases.

Thanks for the input!