[PATCH 26/31] KVM: x86/mmu: Issue memory fault exit if walk failed due to memory attribute

From: Paolo Bonzini

Date: Fri Sep 18 2026 - 11:24:47 EST


From: Nicolas Saenz Julienne <nsaenz@xxxxxxxxxx>

During execution, page table entries are subject to memory protection
simply because their GPA is obtained with an EPT walk. During emulation,
the checks need to be done by hand and result in an -EFAULT userspace
exit.

However, if a guest PTE is read-only, do not go all the way out to
userspace and just stomp out the write. This is consistent with the way
KVM handles read-only memory slots during emulation, though admittedly
inconsistent with everything else: NPT for example always wants nested
page table entries for the guest page tables to be writable, and will
fault.

Signed-off-by: Nicolas Saenz Julienne <nsaenz@xxxxxxxxxx>
Signed-off-by: Paolo Bonzini <pbonzini@xxxxxxxxxx>
---
arch/x86/kvm/mmu/paging_tmpl.h | 17 +++++++++++++++++
1 file changed, 17 insertions(+)

diff --git a/arch/x86/kvm/mmu/paging_tmpl.h b/arch/x86/kvm/mmu/paging_tmpl.h
index b031123fcb36..cd055bfb1eb6 100644
--- a/arch/x86/kvm/mmu/paging_tmpl.h
+++ b/arch/x86/kvm/mmu/paging_tmpl.h
@@ -89,6 +89,7 @@ struct guest_walker {
unsigned int pt_access[PT_MAX_FULL_LEVELS];
unsigned int pte_access;
gfn_t gfn;
+ bool memory_attributes_fault;
struct x86_exception fault;
};

@@ -342,6 +343,7 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker,

trace_kvm_mmu_pagetable_walk(addr, access);
retry_walk:
+ walker->memory_attributes_fault = false;
walker->level = w->cpu_role.base.level;
pte = kvm_mmu_get_guest_pgd(vcpu, w);
have_ad = PT_HAVE_ACCESSED_DIRTY(w);
@@ -411,6 +413,15 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker,
if (unlikely(kvm_is_error_hva(host_addr)))
goto error;

+ if (!kvm_mem_attributes_may_read_gfn(vcpu->kvm, gpa_to_gfn(real_gpa))) {
+ walker->memory_attributes_fault = true;
+ walker->gfn = gpa_to_gfn(real_gpa);
+ goto error;
+ }
+
+ if (!kvm_mem_attributes_may_write_gfn(vcpu->kvm, gpa_to_gfn(real_gpa)))
+ walker->pte_writable[walker->level - 1] = false;
+
ptep_user = (pt_element_t __user *)((void *)host_addr + offset);
if (unlikely(get_user(pte, ptep_user)))
goto error;
@@ -820,6 +831,12 @@ static int FNAME(page_fault)(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault
* The page is not mapped by the guest. Let the guest handle it.
*/
if (!r) {
+ if (walker.memory_attributes_fault) {
+ kvm_prepare_memory_fault_exit(vcpu, walker.gfn << PAGE_SHIFT,
+ PAGE_SIZE, false, false, false);
+ return -EFAULT;
+ }
+
if (!fault->prefetch)
__kvm_inject_emulated_page_fault(vcpu, &walker.fault, true);

--
2.52.0