Re: [PATCH v3 3/4] x86/kvm: add max number of vcpus for hyperv emulation

From: Sean Christopherson
Date: Thu Nov 18 2021 - 11:12:23 EST


On Thu, Nov 18, 2021, Juergen Gross wrote:
> On 18.11.21 15:49, Sean Christopherson wrote:
> > On Thu, Nov 18, 2021, Juergen Gross wrote:
> > > On 17.11.21 21:50, Sean Christopherson wrote:
> > > > > @@ -166,7 +166,7 @@ static struct kvm_vcpu *get_vcpu_by_vpidx(struct kvm *kvm, u32 vpidx)
> > > > > struct kvm_vcpu *vcpu = NULL;
> > > > > int i;
> > > > > - if (vpidx >= KVM_MAX_VCPUS)
> > > > > + if (vpidx >= min(KVM_MAX_VCPUS, KVM_MAX_HYPERV_VCPUS))
> > > >
> > > > IMO, this is conceptually wrong. KVM should refuse to allow Hyper-V to be enabled
> > > > if the max number of vCPUs exceeds what can be supported, or should refuse to create
> > >
> > > TBH, I wasn't sure where to put this test. Is there a guaranteed
> > > sequence of ioctl()s regarding vcpu creation (or setting the max
> > > number of vcpus) and the Hyper-V enabling?
> >
> > For better or worse (mostly worse), like all other things CPUID, Hyper-V is a per-vCPU
> > knob. If KVM can't detect the impossible condition at compile time, kvm_check_cpuid()
> > is probably the right place to prevent enabling Hyper-V on an unreachable vCPU.
>
> With HYPERV_CPUID_IMPLEMENT_LIMITS already returning the
> supported number of vcpus for the Hyper-V case I'm not sure
> there is really more needed.

Yep, that'll do nicely.

> The problem I'm seeing is that the only thing I can do is to
> let kvm_get_hv_cpuid() not adding the Hyper-V cpuid leaves for
> vcpus > 64. I can't return a failure, because that would
> probably let vcpu creation fail. And this is something we don't
> want, as kvm_get_hv_cpuid() is called even in the case the guest
> doesn't plan to use Hyper-V extensions.

Argh, that thing is annoying.

My vote is still to reject KVM_SET_CPUID{2} if userspace attempts to enable Hyper-V
for a vCPU when the max number of vCPUs exceeds HYPERV_CPUID_IMPLEMENT_LIMITS. If
userspace parrots back KVM_GET_SUPPORTED_CPUID, it will specify KVM as the hypervisor,
i.e. enabling Hyper-V requires deliberate action from userspace.

The non-vCPU version of KVM_GET_SUPPORTED_HV_CPUID is not an issue, e.g. the generic
KVM_GET_SUPPORTED_CPUID also reports features that become unsupported if dependent
CPUID features are not enabled by userspace.

The discrepancy with the per-vCPU variant of kvm_get_hv_cpuid() would be unfortunate,
but IMO that ship sailed when the per-vCPU variant was added by commit 2bc39970e932
("x86/kvm/hyper-v: Introduce KVM_GET_SUPPORTED_HV_CPUID"). We can't retroactively
yank that code out, but I don't think we should be overly concerned with keeping it
100% accurate. IMO it's perfectly fine for KVM to define the output of
KVM_GET_SUPPORTED_HV_CPUID as being garbage if the vCPU cannot possibly support
Hyper-V enlightments. That situation isn't possible today, so there's no backwards
compatibility to worry about.