[PATCH 6.1.y 13/24] KVM: x86/mmu: Flush TLBs in kvm_unmap_gfn_range() if the unmap may block/yield
From: Paolo Bonzini
Date: Fri Dec 04 2026 - 13:10:08 EST
From: Sean Christopherson <seanjc@xxxxxxxxxx>
[ Upstream commit 27e2443f180a769a6e58a8f3821cacd01325bfc4 ]
Immediately flush TLBs if a flush is pending after unmapping a GFN range,
*before* returning to the caller, if the overall unmap operation may block,
i.e. if a *future* call to kvm_unmap_gfn_range() may yield and drop
mmu_lock. Because kvm_unmap_gfn_range() starts with "flush = false", KVM
incorrectly loses track of the pending flush if an overall unmap operation
straddles multiple memslots. KVM will still service the TLB flush before
the *caller* completes, but KVM relies on its mappings being completely
unreachable prior to dropping mmu_lock.
E.g. if a MMU notifier invalidation event runs after mmu_lock is dropped,
but before TLBs are flushed, then the MMU notifier task can observe the
missing PTE and return without issuing its own TLB flush, resulting in a
use-after-free (if the to-be-invalidated page was freed or moved).
Hack a fix into x86, but leave a TODO behind to undo the hack, or at least
make it less awful. By dumb luck, x86 is the only arch that conditionally
yields *and* utilizes the common TLB flushing mechanism.
Fixes: e1eed5847b09 ("KVM: x86/mmu: Allow yielding during MMU notifier unmap/zap, if possible")
Cc: stable@xxxxxxxxxxxxxxx
Reported-by: Kevin Liu <kevin.liu@xxxxxxxxxx>
Reported-by: Chris Mason <mason@xxxxxxxxxx>
Cc: Kyle Zeng <kylebot@xxxxxxxxxx>
Signed-off-by: Sean Christopherson <seanjc@xxxxxxxxxx>
Link: https://patch.msgid.link/20261119172647.64295-5-seanjc@xxxxxxxxxx
Signed-off-by: Paolo Bonzini <pbonzini@xxxxxxxxxx>
Signed-off-by: Paolo Bonzini <pbonzini@xxxxxxxxxx>
---
arch/x86/kvm/mmu/mmu.c | 15 +++++++++++++++
1 file changed, 15 insertions(+)
diff --git a/arch/x86/kvm/mmu/mmu.c b/arch/x86/kvm/mmu/mmu.c
index d6c83b7611d6..0ece6fe15fd3 100644
--- a/arch/x86/kvm/mmu/mmu.c
+++ b/arch/x86/kvm/mmu/mmu.c
@@ -1555,6 +1555,21 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
if (range->slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT)
kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
+ /*
+ * Immediately flush TLBs if a *future* invocation of the current unmap
+ * operation may block, in which case the pending flush will be dropped
+ * due to starting with "flush = false" above.
+ *
+ * TODO: Plumb @flush around common KVM so that pending flushes can be
+ * processed if and only if KVM actually yields, and so that this
+ * code doesn't rely on may_block being constant for the entirety
+ * of an unmap operation.
+ */
+ if (flush && range->may_block) {
+ kvm_flush_remote_tlbs(kvm);
+ return false;
+ }
+
return flush;
}
--
2.56.1