[PATCH 2/2] VMX: nSVM: enter protected mode prior to returning to nested guest from SMM

From: Maxim Levitsky
Date: Thu Aug 26 2021 - 05:58:12 EST


SMM return code switches CPU to real mode, and
then the nested_vmx_enter_non_root_mode first switches to vmcs02,
and then restores CR0 in the KVM register cache.

Unfortunately when it restores the CR0, this enables the protection mode
which leads us to "restore" the segment registers from
"real mode segment cache", which is not up to date vs L2 and trips
'vmx_guest_state_valid check' later, when the
unrestricted guest mode is not enabled.

This happens to work otherwise, because after we enter the nested guest,
we restore its register state again from SMRAM with correct values
and that includes the segment values.

As a workaround to this if we enter protected mode first,
then setting CR0 won't cause this damage.

Signed-off-by: Maxim Levitsky <mlevitsk@xxxxxxxxxx>
---
arch/x86/kvm/vmx/vmx.c | 7 +++++++
1 file changed, 7 insertions(+)

diff --git a/arch/x86/kvm/vmx/vmx.c b/arch/x86/kvm/vmx/vmx.c
index 0c2c0d5ae873..805c415494cf 100644
--- a/arch/x86/kvm/vmx/vmx.c
+++ b/arch/x86/kvm/vmx/vmx.c
@@ -7507,6 +7507,13 @@ static int vmx_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
}

if (vmx->nested.smm.guest_mode) {
+
+ /*
+ * Enter protected mode to avoid clobbering L2's segment
+ * registers during nested guest entry
+ */
+ vmx_set_cr0(vcpu, vcpu->arch.cr0 | X86_CR0_PE);
+
ret = nested_vmx_enter_non_root_mode(vcpu, false);
if (ret)
return ret;
--
2.26.3