[PATCH] KVM: x86: Fix the #GP(0) and #UD conditions for XSETBV emulation

From: Like Xu
Date: Mon Jan 17 2022 - 02:25:10 EST


From: Like Xu <likexu@xxxxxxxxxxx>

According to Intel SDM "XSETBV—Set Extended Control Register",
the #UD exception is raised if CPUID.01H:ECX.XSAVE[bit 26] = 0
or if CR4.OSXSAVE[bit 18] = 0, and the #GP(0) exception for the
reason "if the current privilege level is not 0" is only valid
in the protected mode. Translate them into KVM terms.

Fixes: 92f9895c146d ("Move XSETBV emulation to common code")
Signed-off-by: Like Xu <likexu@xxxxxxxxxxx>
---
arch/x86/kvm/x86.c | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index 76b4803dd3bd..7d8622e592bb 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -1024,7 +1024,11 @@ static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)

int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
{
- if (static_call(kvm_x86_get_cpl)(vcpu) != 0 ||
+ if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) ||
+ !kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE))
+ return kvm_handle_invalid_op(vcpu);
+
+ if ((is_protmode(vcpu) && static_call(kvm_x86_get_cpl)(vcpu) != 0) ||
__kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
kvm_inject_gp(vcpu, 0);
return 1;
--
2.33.1