[PATCH 05/17] RISC-V: KVM: Flush TLBs *before* dropping mmu_lock, e.g. when yielding
From: Paolo Bonzini
Date: Fri Dec 04 2026 - 13:00:26 EST
From: Kyle Zeng <kylebot@xxxxxxxxxx>
When unmapping a GPA range, flush TLBs for the processed GPA range *before*
dropping mmu_lock. The ENTIRE point of holding mmu_lock is to ensure other
MMU operations will either see the present stage-2 PTEs, or can rely on any
references to the old PTEs being fully zapped.
E.g. if a MMU notifier invalidation event runs while the zapping task has
dropped mmu_lock and yielded, then the MMU notifier task 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).
Fixes: 60aa6734f542 ("RISC-V: KVM: Batch stage-2 TLB flushes")
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Kyle Zeng <kylebot@xxxxxxxxxx>
[sean: rewrite changelog and drop the comment]
Signed-off-by: Sean Christopherson <seanjc@xxxxxxxxxx>
Link: https://patch.msgid.link/20261119172647.64295-2-seanjc@xxxxxxxxxx
Signed-off-by: Paolo Bonzini <pbonzini@xxxxxxxxxx>
---
arch/riscv/kvm/gstage.c | 9 ++++++++-
arch/riscv/kvm/mmu.c | 2 +-
2 files changed, 9 insertions(+), 2 deletions(-)
diff --git a/arch/riscv/kvm/gstage.c b/arch/riscv/kvm/gstage.c
index 0aace3215d3e..ee9bf5ff3ee8 100644
--- a/arch/riscv/kvm/gstage.c
+++ b/arch/riscv/kvm/gstage.c
@@ -449,8 +449,15 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
* If the range is too large, release the kvm->mmu_lock
* to prevent starvation and lockup detector warnings.
*/
- if (!(gstage->flags & KVM_GSTAGE_FLAGS_LOCAL) && may_block && addr < end)
+ if (!(gstage->flags & KVM_GSTAGE_FLAGS_LOCAL) && may_block && addr < end &&
+ (need_resched() || rwlock_needbreak(&gstage->kvm->mmu_lock))) {
+ if (flush) {
+ kvm_flush_remote_tlbs_range(gstage->kvm, start >> PAGE_SHIFT,
+ (addr - start) >> PAGE_SHIFT);
+ flush = false;
+ }
cond_resched_rwlock_write(&gstage->kvm->mmu_lock);
+ }
}
return flush;
diff --git a/arch/riscv/kvm/mmu.c b/arch/riscv/kvm/mmu.c
index 6861c0e2728d..f8abd3281a75 100644
--- a/arch/riscv/kvm/mmu.c
+++ b/arch/riscv/kvm/mmu.c
@@ -211,10 +211,10 @@ void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
write_lock(&kvm->mmu_lock);
flush = kvm_riscv_gstage_unmap_range(&gstage, gpa, size, false);
- write_unlock(&kvm->mmu_lock);
if (flush)
kvm_flush_remote_tlbs_range(kvm, gpa >> PAGE_SHIFT,
size >> PAGE_SHIFT);
+ write_unlock(&kvm->mmu_lock);
}
static void mmu_split_memory_region(struct kvm *kvm, int slot)
--
2.56.1