[PATCH v19 018/130] KVM: x86/mmu: Assume guest MMIOs are shared

From: isaku . yamahata
Date: Mon Feb 26 2024 - 03:34:04 EST


From: Chao Gao <chao.gao@xxxxxxxxx>

TODO: Drop this patch once the common patch is merged.

When memory slot isn't found for kvm page fault, handle it as MMIO.

The guest of TDX_VM, SNP_VM, or SW_PROTECTED_VM don't necessarily convert
the virtual MMIO range to shared before accessing it. When the guest tries
to access the virtual device's MMIO without any private/shared conversion,
An NPT fault or EPT violation is raised first to find private-shared
mismatch. Don't raise KVM_EXIT_MEMORY_FAULT, fall back to KVM_PFN_NOLSLOT.

Signed-off-by: Chao Gao <chao.gao@xxxxxxxxx>
Signed-off-by: Isaku Yamahata <isaku.yamahata@xxxxxxxxx>
---
v19:
- Added slot check before kvm_faultin_private_pfn()
- updated comment
- rewrite the commit message
---
arch/x86/kvm/mmu/mmu.c | 14 ++++++++++++--
1 file changed, 12 insertions(+), 2 deletions(-)

diff --git a/arch/x86/kvm/mmu/mmu.c b/arch/x86/kvm/mmu/mmu.c
index ca0c91f14063..c45252ed2ffd 100644
--- a/arch/x86/kvm/mmu/mmu.c
+++ b/arch/x86/kvm/mmu/mmu.c
@@ -4342,6 +4342,7 @@ static int kvm_faultin_pfn_private(struct kvm_vcpu *vcpu,
static int __kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
{
struct kvm_memory_slot *slot = fault->slot;
+ bool force_mmio;
bool async;

/*
@@ -4371,12 +4372,21 @@ static int __kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault
return RET_PF_EMULATE;
}

- if (fault->is_private != kvm_mem_is_private(vcpu->kvm, fault->gfn)) {
+ /*
+ * !fault->slot means MMIO for SNP and TDX. Don't require explicit GPA
+ * conversion for MMIO because MMIO is assigned at the boot time. Fall
+ * to !is_private case to get pfn = KVM_PFN_NOSLOT.
+ */
+ force_mmio = !slot &&
+ vcpu->kvm->arch.vm_type != KVM_X86_DEFAULT_VM &&
+ vcpu->kvm->arch.vm_type != KVM_X86_SW_PROTECTED_VM;
+ if (!force_mmio &&
+ fault->is_private != kvm_mem_is_private(vcpu->kvm, fault->gfn)) {
kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
return -EFAULT;
}

- if (fault->is_private)
+ if (!force_mmio && fault->is_private)
return kvm_faultin_pfn_private(vcpu, fault);

async = false;
--
2.25.1