Skip to contentSkip to conversation

KVM: riscv: Allow rescheduling during G-stage unmap

PATCH Superseded Can Qi 3 participants 10 messages Nov 23 – Dec 3

Subsystems (3)

v1 of 7 Superseded Latest is v7 →

lore
Share & tools
lore

Can Qi

author
#0 lore raw

PATCH 1/1 KVM: riscv: Allow rescheduling during G-stage unmap

Removing a populated memslot or destroying a VM can require walking a large G-stage range while holding mmu_lock. Let these callers use the existing write-lock reschedule helper to bound the time spent holding the lock continuously.

Snapshot the shared root under mmu_lock and stop the walk if the root has been detached while the lock was dropped. Flush pending batches before yielding so a concurrent invalidation cannot miss PTEs cleared by the current walker. Finish memslot invalidation under the write lock and synchronize the VM before releasing a detached root.

Free the VM-owned split-page cache in kvm_arch_destroy_vm(), after notifier callbacks have completed. Notifier release can be invoked by both address-space teardown and notifier unregister.

Validated with RISC-V KVM selftests in QEMU TCG, including MMU stress with two vCPUs, KASAN and lockdep runs, and traces of rescheduling and remote TLB request handling.

Codex assisted with implementation and validation. Sashiko identified the pending-flush ordering concern in an earlier revision.

---
 arch/riscv/include/asm/kvm_gstage.h | 10 ++-
 arch/riscv/kvm/gstage.c             | 29 +++++++--
 arch/riscv/kvm/mmu.c                | 95 ++++++++++++++---------------
 arch/riscv/kvm/vm.c                 |  3 +
 4 files changed, 83 insertions(+), 54 deletions(-)
arch/riscv/include/asm/kvm_gstage.h +9 -1
index aaf080ba1..0df2c2a54 100644
@@ -104,13 +104,21 @@ static inline unsigned long kvm_riscv_gstage_mode(unsigned long pgd_levels)
 	}
 }
 
-static inline void kvm_riscv_gstage_init(struct kvm_gstage *gstage, struct kvm *kvm)
+/* The caller must hold mmu_lock while accessing the shared page tables. */
+static inline bool kvm_riscv_gstage_init(struct kvm_gstage *gstage, struct kvm *kvm)
 {
+	lockdep_assert_held(&kvm->mmu_lock);
+
+	if (!kvm->arch.pgd)
+		return false;
+
 	gstage->kvm = kvm;
 	gstage->flags = 0;
 	gstage->vmid = READ_ONCE(kvm->arch.vmid.vmid);
 	gstage->pgd = kvm->arch.pgd;
 	gstage->pgd_levels = kvm->arch.pgd_levels;
+
+	return true;
 }
 
 #endif
arch/riscv/kvm/gstage.c +25 -4
index be70607a3..ea7a156ec 100644
@@ -423,9 +423,20 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
 	bool found_leaf;
 	unsigned long page_size;
 	gpa_t addr = start, end = start + size;
+	gfn_t last_flush_gfn = start >> PAGE_SHIFT;
 	bool flush = false;
+	bool pending_flush = false;
+
+	if (!(gstage->flags & KVM_GSTAGE_FLAGS_LOCAL))
+		lockdep_assert_held_write(&gstage->kvm->mmu_lock);
 
 	while (addr < end) {
+		/* A concurrent teardown may have freed the root while unlocked. */
+		if (!(gstage->flags & KVM_GSTAGE_FLAGS_LOCAL) &&
+		    (!gstage->kvm->arch.pgd ||
+		     gstage->pgd != gstage->kvm->arch.pgd))
+			break;
+
 		found_leaf = kvm_riscv_gstage_get_leaf(gstage, addr, &ptep, &ptep_level);
 		ret = gstage_level_to_page_size(gstage, ptep_level, &page_size);
 		if (ret)
@@ -434,10 +445,11 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
 		if (!found_leaf) {
 			addr = ALIGN(addr + 1, page_size);
 		} else {
-			if (!(addr & (page_size - 1)) && ((end - addr) >= page_size))
-				flush |= kvm_riscv_gstage_op_pte(gstage, addr, ptep,
+			if (!(addr & (page_size - 1)) && ((end - addr) >= page_size)) {
+				pending_flush |= kvm_riscv_gstage_op_pte(gstage, addr, ptep,
 								 ptep_level, GSTAGE_OP_CLEAR);
-			else {
+				flush |= pending_flush;
+			} else {
 				WARN_ONCE(1, "Skip unmap range addr: %#llx, end: %#llx, page_size: %#lx\n",
 						addr, end, page_size);
 			}
@@ -448,9 +460,18 @@ 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.
+		 * Flush first so another invalidator cannot miss cleared PTEs.
 		 */
-		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 (pending_flush) {
+				kvm_flush_remote_tlbs_range(gstage->kvm, last_flush_gfn,
+							    (addr >> PAGE_SHIFT) - last_flush_gfn);
+				pending_flush = false;
+			}
+			last_flush_gfn = addr >> PAGE_SHIFT;
 			cond_resched_rwlock_write(&gstage->kvm->mmu_lock);
+		}
 	}
 
 	return flush;
arch/riscv/kvm/mmu.c +46 -49

228 lines not on this page · raw message

arch/riscv/kvm/vm.c +3 -0
index 58500a19b..7d467b0c5 100644
@@ -54,6 +54,9 @@ void kvm_arch_destroy_vm(struct kvm *kvm)
 	kvm_destroy_vcpus(kvm);
 
 	kvm_riscv_aia_destroy_vm(kvm);
+
+	/* MMU notifier callbacks have finished before VM destruction. */
+	kvm_mmu_free_memory_cache(&kvm->arch.pgd_split_page_cache);
 }
 
 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irql,

base-commit: aebb7274476403040d582c61478df8f4a7bf9cd3

Signature · 7 lines
2.34.1


-- 
kvm-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/kvm-riscv
#1 lore raw
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] KVM: riscv: redundant TLB flush after kvm_riscv_gstage_unmap_range() yield --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] KVM: riscv: redundant TLB flush after kvm_riscv_gstage_unmap_range() yield
--

commit 08865a8ca16cac26d3da38f3cc5232bb2fb890ba
Author: Can Qi <[email protected]>

KVM: riscv: Allow rescheduling during G-stage unmap

This commit allows G-stage unmap walks to flush pending TLB invalidations and yield mmu_lock when rescheduling is needed, and moves freeing of the VM-owned split-page cache to kvm_arch_destroy_vm().

Quoted 50 lines
arch/riscv/kvm/gstage.c +19 -4
index be70607a33ea0..ea7a156ec4f3f 100644
@@ -423,9 +423,20 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
 	bool found_leaf;
 	unsigned long page_size;
 	gpa_t addr = start, end = start + size;
+	gfn_t last_flush_gfn = start >> PAGE_SHIFT;
 	bool flush = false;
+	bool pending_flush = false;
+
+	if (!(gstage->flags & KVM_GSTAGE_FLAGS_LOCAL))
+		lockdep_assert_held_write(&gstage->kvm->mmu_lock);
 
 	while (addr < end) {
+		/* A concurrent teardown may have freed the root while unlocked. */
+		if (!(gstage->flags & KVM_GSTAGE_FLAGS_LOCAL) &&
+		    (!gstage->kvm->arch.pgd ||
+		     gstage->pgd != gstage->kvm->arch.pgd))
+			break;
+
 		found_leaf = kvm_riscv_gstage_get_leaf(gstage, addr, &ptep, &ptep_level);
 		ret = gstage_level_to_page_size(gstage, ptep_level, &page_size);
 		if (ret)
@@ -434,10 +445,11 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
 		if (!found_leaf) {
 			addr = ALIGN(addr + 1, page_size);
 		} else {
-			if (!(addr & (page_size - 1)) && ((end - addr) >= page_size))
-				flush |= kvm_riscv_gstage_op_pte(gstage, addr, ptep,
+			if (!(addr & (page_size - 1)) && ((end - addr) >= page_size)) {
+				pending_flush |= kvm_riscv_gstage_op_pte(gstage, addr, ptep,
 								 ptep_level, GSTAGE_OP_CLEAR);
-			else {
+				flush |= pending_flush;
+			} else {
 				WARN_ONCE(1, "Skip unmap range addr: %#llx, end: %#llx, page_size: %#lx\n",
 						addr, end, page_size);
 			}
@@ -448,9 +460,18 @@ 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.
+		 * Flush first so another invalidator cannot miss cleared PTEs.
 		 */
-		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 (pending_flush) {

arch/riscv/kvm/gstage.c bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage, · line 477

Quoted 10 lines
arch/riscv/kvm/gstage.c +6 -0
+				kvm_flush_remote_tlbs_range(gstage->kvm, last_flush_gfn,
+							    (addr >> PAGE_SHIFT) - last_flush_gfn);
+				pending_flush = false;
+			}
+			last_flush_gfn = addr >> PAGE_SHIFT;
 			cond_resched_rwlock_write(&gstage->kvm->mmu_lock);
+		}
 	}
 
 	return flush;

[Severity: Medium]
Should kvm_riscv_gstage_unmap_range() return pending_flush instead of flush?

When the walk yields mmu_lock, it flushes the cleared PTEs in [last_flush_gfn, addr >> PAGE_SHIFT) and resets pending_flush to false, but flush stays latched to true. Callers such as kvm_arch_flush_shadow_memslot() and kvm_unmap_gfn_range() check the return value to decide whether a post-walk TLB flush is needed, so they will issue a redundant remote TLB shootdown across the entire range even when all cleared PTEs were already flushed before yielding.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author
#2 lore raw

PATCH v2 1/1 KVM: riscv: Allow rescheduling during G-stage unmap

In reply to Can Qi

Removing a populated memslot or destroying a VM can require walking a large G-stage range while holding mmu_lock. Let these callers use the existing write-lock reschedule helper to bound the time spent holding the lock continuously.

Snapshot the shared root under mmu_lock and stop the walk if the root has been detached while the lock was dropped. Flush pending batches before yielding so a concurrent invalidation cannot miss PTEs cleared by the current walker. Finish memslot invalidation under the write lock and synchronize the VM before releasing a detached root. Return whether any cleared PTEs still need a flush at the end of the walk, so callers can skip a second flush when the batches have already been synchronized.

Free the VM-owned split-page cache in kvm_arch_destroy_vm(), after notifier callbacks have completed. Notifier release can be invoked by both address-space teardown and notifier unregister.

The first revision passed the QEMU KVM selftests, KASAN and lockdep runs, and tracing of rescheduling and remote TLB request handling. For v2, rebuild the kernel and modules and rerun the two-vCPU MMU stress selftest. Tracing confirms the full flush still runs on root detach even when the walker returns with no pending invalidations.

Codex assisted with implementation and validation. Sashiko identified the pending-flush ordering concern in an earlier revision.

---
Changes in v2

- Return only pending TLB work from kvm_riscv_gstage_unmap_range(), so callers can skip the final range flush if earlier batches already synchronized all cleared PTEs. Keep the full flush on root detach.

 arch/riscv/include/asm/kvm_gstage.h | 11 ++++-
 arch/riscv/kvm/gstage.c             | 31 +++++++++---
 arch/riscv/kvm/mmu.c                | 95 ++++++++++++++++++-------------------
 arch/riscv/kvm/vm.c                 |  3 ++
 4 files changed, 84 insertions(+), 56 deletions(-)
arch/riscv/include/asm/kvm_gstage.h +10 -1
index aaf080ba1..ea57df965 100644
@@ -77,6 +77,7 @@ enum kvm_riscv_gstage_op {
 bool kvm_riscv_gstage_op_pte(struct kvm_gstage *gstage, gpa_t addr,
 			     pte_t *ptep, u32 ptep_level, enum kvm_riscv_gstage_op op);
 
+/* Returns true if cleared PTEs still need a TLB flush. */
 bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
 				  gpa_t start, gpa_t size, bool may_block);
 
@@ -104,13 +105,21 @@ static inline unsigned long kvm_riscv_gstage_mode(unsigned long pgd_levels)
 	}
 }
 
-static inline void kvm_riscv_gstage_init(struct kvm_gstage *gstage, struct kvm *kvm)
+/* The caller must hold mmu_lock while accessing the shared page tables. */
+static inline bool kvm_riscv_gstage_init(struct kvm_gstage *gstage, struct kvm *kvm)
 {
+	lockdep_assert_held(&kvm->mmu_lock);
+
+	if (!kvm->arch.pgd)
+		return false;
+
 	gstage->kvm = kvm;
 	gstage->flags = 0;
 	gstage->vmid = READ_ONCE(kvm->arch.vmid.vmid);
 	gstage->pgd = kvm->arch.pgd;
 	gstage->pgd_levels = kvm->arch.pgd_levels;
+
+	return true;
 }
 
 #endif
arch/riscv/kvm/gstage.c +25 -6
index be70607a3..47b906769 100644
@@ -423,9 +423,19 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
 	bool found_leaf;
 	unsigned long page_size;
 	gpa_t addr = start, end = start + size;
-	bool flush = false;
+	gfn_t last_flush_gfn = start >> PAGE_SHIFT;
+	bool pending_flush = false;
+
+	if (!(gstage->flags & KVM_GSTAGE_FLAGS_LOCAL))
+		lockdep_assert_held_write(&gstage->kvm->mmu_lock);
 
 	while (addr < end) {
+		/* A concurrent teardown may have freed the root while unlocked. */
+		if (!(gstage->flags & KVM_GSTAGE_FLAGS_LOCAL) &&
+		    (!gstage->kvm->arch.pgd ||
+		     gstage->pgd != gstage->kvm->arch.pgd))
+			break;
+
 		found_leaf = kvm_riscv_gstage_get_leaf(gstage, addr, &ptep, &ptep_level);
 		ret = gstage_level_to_page_size(gstage, ptep_level, &page_size);
 		if (ret)
@@ -434,10 +444,10 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
 		if (!found_leaf) {
 			addr = ALIGN(addr + 1, page_size);
 		} else {
-			if (!(addr & (page_size - 1)) && ((end - addr) >= page_size))
-				flush |= kvm_riscv_gstage_op_pte(gstage, addr, ptep,
+			if (!(addr & (page_size - 1)) && ((end - addr) >= page_size)) {
+				pending_flush |= kvm_riscv_gstage_op_pte(gstage, addr, ptep,
 								 ptep_level, GSTAGE_OP_CLEAR);
-			else {
+			} else {
 				WARN_ONCE(1, "Skip unmap range addr: %#llx, end: %#llx, page_size: %#lx\n",
 						addr, end, page_size);
 			}
@@ -448,12 +458,21 @@ 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.
+		 * Flush first so another invalidator cannot miss cleared PTEs.
 		 */
-		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 (pending_flush) {
+				kvm_flush_remote_tlbs_range(gstage->kvm, last_flush_gfn,
+							    (addr >> PAGE_SHIFT) - last_flush_gfn);
+				pending_flush = false;
+			}
+			last_flush_gfn = addr >> PAGE_SHIFT;
 			cond_resched_rwlock_write(&gstage->kvm->mmu_lock);
+		}
 	}
 
-	return flush;
+	return pending_flush;
 }
 
 bool kvm_riscv_gstage_wp_range(struct kvm_gstage *gstage, gpa_t start, gpa_t end)
arch/riscv/kvm/mmu.c +46 -49

228 lines not on this page · raw message

arch/riscv/kvm/vm.c +3 -0
index 58500a19b..7d467b0c5 100644
@@ -54,6 +54,9 @@ void kvm_arch_destroy_vm(struct kvm *kvm)
 	kvm_destroy_vcpus(kvm);
 
 	kvm_riscv_aia_destroy_vm(kvm);
+
+	/* MMU notifier callbacks have finished before VM destruction. */
+	kvm_mmu_free_memory_cache(&kvm->arch.pgd_split_page_cache);
 }
 
 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irql,

base-commit: aebb7274476403040d582c61478df8f4a7bf9cd3

Signature · 1 line
2.34.1
#3 lore raw
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] KVM: riscv: callers re-flush full range after batched unmap yields --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] KVM: riscv: callers re-flush full range after batched unmap yields
--

commit 98e1340ab679b1cafbeb059326e3045e4ca36e66
Author: Can Qi <[email protected]>

KVM: riscv: Allow rescheduling during G-stage unmap

This commit allows G-stage unmap walks to yield mmu_lock, flushing pending TLB batches before rescheduling and stopping if the root page table is detached concurrently.

Quoted 11 lines
arch/riscv/kvm/gstage.c +2 -1
index be70607a33ea0..47b906769f497 100644
@@ -423,9 +423,19 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
 	bool found_leaf;
 	unsigned long page_size;
 	gpa_t addr = start, end = start + size;
-	bool flush = false;
+	gfn_t last_flush_gfn = start >> PAGE_SHIFT;
+	bool pending_flush = false;

[ ... ]

Quoted 12 lines
arch/riscv/kvm/gstage.c +6 -1
@@ -448,12 +458,21 @@ 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.
+		 * Flush first so another invalidator cannot miss cleared PTEs.
 		 */
-		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 (pending_flush) {
+				kvm_flush_remote_tlbs_range(gstage->kvm, last_flush_gfn,
+							    (addr >> PAGE_SHIFT) - last_flush_gfn);

arch/riscv/kvm/gstage.c bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage, · line 476

Quoted 10 lines
arch/riscv/kvm/gstage.c +5 -1
+				pending_flush = false;
+			}
+			last_flush_gfn = addr >> PAGE_SHIFT;
 			cond_resched_rwlock_write(&gstage->kvm->mmu_lock);
+		}
 	}
 
-	return flush;
+	return pending_flush;
 }

[Severity: Medium]
Does returning only pending_flush discard last_flush_gfn and cause callers to re-flush the entire original range whenever a PTE is cleared after the last yield?

When kvm_riscv_gstage_unmap_range() yields and then clears a PTE in the remaining tail, kvm_arch_flush_shadow_memslot() and kvm_unmap_gfn_range() call kvm_flush_remote_tlbs_range() from the start of the full range instead of from last_flush_gfn. Because kvm_riscv_local_hfence_gvma_vmid_gpa() falls back to a full-VMID TLB flush when the range exceeds PTRS_PER_PTE (512 pages), any unmap of a range larger than 2 MiB that yields and clears a tail PTE still triggers a full-VMID flush across all vCPUs in addition to the intermediate batch flushes.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author
#4 lore raw

PATCH v3 1/1 KVM: riscv: Allow rescheduling during G-stage unmap

In reply to Can Qi

Removing a populated memslot or destroying a VM can require walking a large G-stage range under mmu_lock. Allow these paths to drop the write lock and reschedule during the walk.

Snapshot the shared root under mmu_lock and verify it before walking again after a yield. Flush each pending batch before dropping the lock so another invalidator cannot miss PTEs that the walker cleared.

Return the number of pages in the trailing range that still needs a flush. The memslot and MMU notifier paths can then flush just that range while holding mmu_lock. Detaching the root still requires a full VM flush before freeing it, even when the last batch was empty.

Free the VM-owned split-page cache in kvm_arch_destroy_vm(), after MMU notifier callbacks have completed. Both address-space teardown and notifier unregister can invoke the release callback.

Codex assisted with implementation and validation. Sashiko identified the redundant final range flush during review.

---
Changes in v3

- Carry the unflushed tail length back to the memslot and MMU notifier callers. A v2 trace showed a final request for all 262144 pages of a memslot when only 255 pages remained after the last batch.

Changes in v2

- Skip the final range flush when the walk has already synchronized every cleared PTE. Keep the full flush when detaching the root.

Testing

- Built the RV64 kernel image and modules and ran mmu_stress_test -c 2 -m 2 -s 1 under QEMU. The trace showed a final memslot flush of 154 of 262144 pages and a notifier flush of 506 of 262144 pages. Root teardown still requested a full flush with an empty tail.

 arch/riscv/include/asm/kvm_gstage.h |  15 +++-
 arch/riscv/kvm/gstage.c             |  35 +++++++--
 arch/riscv/kvm/mmu.c                | 112 ++++++++++++++--------------
 arch/riscv/kvm/vm.c                 |   3 +
 4 files changed, 96 insertions(+), 69 deletions(-)
arch/riscv/include/asm/kvm_gstage.h +12 -3
index aaf080ba1..a576940f3 100644
@@ -77,8 +77,9 @@ enum kvm_riscv_gstage_op {
 bool kvm_riscv_gstage_op_pte(struct kvm_gstage *gstage, gpa_t addr,
 			     pte_t *ptep, u32 ptep_level, enum kvm_riscv_gstage_op op);
 
-bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
-				  gpa_t start, gpa_t size, bool may_block);
+/* Return the number of trailing pages to flush, or zero if none remain. */
+u64 kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
+				 gpa_t start, gpa_t size, bool may_block);
 
 bool kvm_riscv_gstage_wp_range(struct kvm_gstage *gstage, gpa_t start, gpa_t end);
 
@@ -104,13 +105,21 @@ static inline unsigned long kvm_riscv_gstage_mode(unsigned long pgd_levels)
 	}
 }
 
-static inline void kvm_riscv_gstage_init(struct kvm_gstage *gstage, struct kvm *kvm)
+/* The caller must hold mmu_lock while accessing the shared page tables. */
+static inline bool kvm_riscv_gstage_init(struct kvm_gstage *gstage, struct kvm *kvm)
 {
+	lockdep_assert_held(&kvm->mmu_lock);
+
+	if (!kvm->arch.pgd)
+		return false;
+
 	gstage->kvm = kvm;
 	gstage->flags = 0;
 	gstage->vmid = READ_ONCE(kvm->arch.vmid.vmid);
 	gstage->pgd = kvm->arch.pgd;
 	gstage->pgd_levels = kvm->arch.pgd_levels;
+
+	return true;
 }
 
 #endif
arch/riscv/kvm/gstage.c +27 -8
index be70607a3..76a2f7c78 100644
@@ -414,8 +414,8 @@ bool kvm_riscv_gstage_op_pte(struct kvm_gstage *gstage, gpa_t addr,
 	return flush;
 }
 
-bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
-				  gpa_t start, gpa_t size, bool may_block)
+u64 kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
+				 gpa_t start, gpa_t size, bool may_block)
 {
 	int ret;
 	pte_t *ptep;
@@ -423,9 +423,19 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
 	bool found_leaf;
 	unsigned long page_size;
 	gpa_t addr = start, end = start + size;
-	bool flush = false;
+	gfn_t last_flush_gfn = start >> PAGE_SHIFT;
+	bool pending_flush = false;
+
+	if (!(gstage->flags & KVM_GSTAGE_FLAGS_LOCAL))
+		lockdep_assert_held_write(&gstage->kvm->mmu_lock);
 
 	while (addr < end) {
+		/* A concurrent teardown may have freed the root while unlocked. */
+		if (!(gstage->flags & KVM_GSTAGE_FLAGS_LOCAL) &&
+		    (!gstage->kvm->arch.pgd ||
+		     gstage->pgd != gstage->kvm->arch.pgd))
+			break;
+
 		found_leaf = kvm_riscv_gstage_get_leaf(gstage, addr, &ptep, &ptep_level);
 		ret = gstage_level_to_page_size(gstage, ptep_level, &page_size);
 		if (ret)
@@ -434,10 +444,10 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
 		if (!found_leaf) {
 			addr = ALIGN(addr + 1, page_size);
 		} else {
-			if (!(addr & (page_size - 1)) && ((end - addr) >= page_size))
-				flush |= kvm_riscv_gstage_op_pte(gstage, addr, ptep,
+			if (!(addr & (page_size - 1)) && ((end - addr) >= page_size)) {
+				pending_flush |= kvm_riscv_gstage_op_pte(gstage, addr, ptep,
 								 ptep_level, GSTAGE_OP_CLEAR);
-			else {
+			} else {
 				WARN_ONCE(1, "Skip unmap range addr: %#llx, end: %#llx, page_size: %#lx\n",
 						addr, end, page_size);
 			}
@@ -448,12 +458,21 @@ 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.
+		 * Flush first so another invalidator cannot miss cleared PTEs.
 		 */
-		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 (pending_flush) {
+				kvm_flush_remote_tlbs_range(gstage->kvm, last_flush_gfn,
+							    (addr >> PAGE_SHIFT) - last_flush_gfn);
+				pending_flush = false;
+			}
+			last_flush_gfn = addr >> PAGE_SHIFT;
 			cond_resched_rwlock_write(&gstage->kvm->mmu_lock);
+		}
 	}
 
-	return flush;
+	return pending_flush ? (end >> PAGE_SHIFT) - last_flush_gfn : 0;
 }
 
 bool kvm_riscv_gstage_wp_range(struct kvm_gstage *gstage, gpa_t start, gpa_t end)
arch/riscv/kvm/mmu.c +54 -58

244 lines not on this page · raw message

arch/riscv/kvm/vm.c +3 -0
index 58500a19b..7d467b0c5 100644
@@ -54,6 +54,9 @@ void kvm_arch_destroy_vm(struct kvm *kvm)
 	kvm_destroy_vcpus(kvm);
 
 	kvm_riscv_aia_destroy_vm(kvm);
+
+	/* MMU notifier callbacks have finished before VM destruction. */
+	kvm_mmu_free_memory_cache(&kvm->arch.pgd_split_page_cache);
 }
 
 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irql,

base-commit: aebb7274476403040d582c61478df8f4a7bf9cd3

Signature · 7 lines
2.34.1


-- 
kvm-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/kvm-riscv
maintainer
#5 lore raw
Quoted 18 lines · Can Qi

Removing a populated memslot or destroying a VM can require walking a large G-stage range under mmu_lock. Allow these paths to drop the write lock and reschedule during the walk.

Snapshot the shared root under mmu_lock and verify it before walking again after a yield. Flush each pending batch before dropping the lock so another invalidator cannot miss PTEs that the walker cleared.

Return the number of pages in the trailing range that still needs a flush. The memslot and MMU notifier paths can then flush just that range while holding mmu_lock. Detaching the root still requires a full VM flush before freeing it, even when the last batch was empty.

Free the VM-owned split-page cache in kvm_arch_destroy_vm(), after MMU notifier callbacks have completed. Both address-space teardown and notifier unregister can invoke the release callback.

Quoted 6 lines

Codex assisted with implementation and validation. Sashiko identified the redundant final range flush during review.

This needs to be rebased on latest riscv_kvm_queue branch at
https://github.com/kvm-riscv/linux.git

Regards,
Anup

Quoted 422 lines

---
Changes in v3

- Carry the unflushed tail length back to the memslot and MMU notifier callers. A v2 trace showed a final request for all 262144 pages of a memslot when only 255 pages remained after the last batch.

Changes in v2

- Skip the final range flush when the walk has already synchronized every cleared PTE. Keep the full flush when detaching the root.

Testing

- Built the RV64 kernel image and modules and ran mmu_stress_test -c 2 -m 2 -s 1 under QEMU. The trace showed a final memslot flush of 154 of 262144 pages and a notifier flush of 506 of 262144 pages. Root teardown still requested a full flush with an empty tail.

 arch/riscv/include/asm/kvm_gstage.h |  15 +++-
 arch/riscv/kvm/gstage.c             |  35 +++++++--
 arch/riscv/kvm/mmu.c                | 112 ++++++++++++++--------------
 arch/riscv/kvm/vm.c                 |   3 +
 4 files changed, 96 insertions(+), 69 deletions(-)
arch/riscv/include/asm/kvm_gstage.h +12 -3
index aaf080ba1..a576940f3 100644
@@ -77,8 +77,9 @@ enum kvm_riscv_gstage_op {
 bool kvm_riscv_gstage_op_pte(struct kvm_gstage *gstage, gpa_t addr,
                             pte_t *ptep, u32 ptep_level, enum kvm_riscv_gstage_op op);
 
-bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
-                                 gpa_t start, gpa_t size, bool may_block);
+/* Return the number of trailing pages to flush, or zero if none remain. */
+u64 kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
+                                gpa_t start, gpa_t size, bool may_block);
 
 bool kvm_riscv_gstage_wp_range(struct kvm_gstage *gstage, gpa_t start, gpa_t end);
 
@@ -104,13 +105,21 @@ static inline unsigned long kvm_riscv_gstage_mode(unsigned long pgd_levels)
        }
 }
 
-static inline void kvm_riscv_gstage_init(struct kvm_gstage *gstage, struct kvm *kvm)
+/* The caller must hold mmu_lock while accessing the shared page tables. */
+static inline bool kvm_riscv_gstage_init(struct kvm_gstage *gstage, struct kvm *kvm)
 {
+       lockdep_assert_held(&kvm->mmu_lock);
+
+       if (!kvm->arch.pgd)
+               return false;
+
        gstage->kvm = kvm;
        gstage->flags = 0;
        gstage->vmid = READ_ONCE(kvm->arch.vmid.vmid);
        gstage->pgd = kvm->arch.pgd;
        gstage->pgd_levels = kvm->arch.pgd_levels;
+
+       return true;
 }
 
 #endif
arch/riscv/kvm/gstage.c +27 -8
index be70607a3..76a2f7c78 100644
@@ -414,8 +414,8 @@ bool kvm_riscv_gstage_op_pte(struct kvm_gstage *gstage, gpa_t addr,
        return flush;
 }
 
-bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
-                                 gpa_t start, gpa_t size, bool may_block)
+u64 kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
+                                gpa_t start, gpa_t size, bool may_block)
 {
        int ret;
        pte_t *ptep;
@@ -423,9 +423,19 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
        bool found_leaf;
        unsigned long page_size;
        gpa_t addr = start, end = start + size;
-       bool flush = false;
+       gfn_t last_flush_gfn = start >> PAGE_SHIFT;
+       bool pending_flush = false;
+
+       if (!(gstage->flags & KVM_GSTAGE_FLAGS_LOCAL))
+               lockdep_assert_held_write(&gstage->kvm->mmu_lock);
 
        while (addr < end) {
+               /* A concurrent teardown may have freed the root while unlocked. */
+               if (!(gstage->flags & KVM_GSTAGE_FLAGS_LOCAL) &&
+                   (!gstage->kvm->arch.pgd ||
+                    gstage->pgd != gstage->kvm->arch.pgd))
+                       break;
+
                found_leaf = kvm_riscv_gstage_get_leaf(gstage, addr, &ptep, &ptep_level);
                ret = gstage_level_to_page_size(gstage, ptep_level, &page_size);
                if (ret)
@@ -434,10 +444,10 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
                if (!found_leaf) {
                        addr = ALIGN(addr + 1, page_size);
                } else {
-                       if (!(addr & (page_size - 1)) && ((end - addr) >= page_size))
-                               flush |= kvm_riscv_gstage_op_pte(gstage, addr, ptep,
+                       if (!(addr & (page_size - 1)) && ((end - addr) >= page_size)) {
+                               pending_flush |= kvm_riscv_gstage_op_pte(gstage, addr, ptep,
                                                                 ptep_level, GSTAGE_OP_CLEAR);
-                       else {
+                       } else {
                                WARN_ONCE(1, "Skip unmap range addr: %#llx, end: %#llx, page_size: %#lx\n",
                                                addr, end, page_size);
                        }
@@ -448,12 +458,21 @@ 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.
+                * Flush first so another invalidator cannot miss cleared PTEs.
                 */
-               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 (pending_flush) {
+                               kvm_flush_remote_tlbs_range(gstage->kvm, last_flush_gfn,
+                                                           (addr >> PAGE_SHIFT) - last_flush_gfn);
+                               pending_flush = false;
+                       }
+                       last_flush_gfn = addr >> PAGE_SHIFT;
                        cond_resched_rwlock_write(&gstage->kvm->mmu_lock);
+               }
        }
 
-       return flush;
+       return pending_flush ? (end >> PAGE_SHIFT) - last_flush_gfn : 0;
 }
 
 bool kvm_riscv_gstage_wp_range(struct kvm_gstage *gstage, gpa_t start, gpa_t end)
arch/riscv/kvm/mmu.c +54 -58
index 738d9ee1e..092376a94 100644
@@ -26,12 +26,11 @@ static void mmu_wp_memory_region(struct kvm *kvm, int slot)
        phys_addr_t start = memslot->base_gfn << PAGE_SHIFT;
        phys_addr_t end = (memslot->base_gfn + memslot->npages) << PAGE_SHIFT;
        struct kvm_gstage gstage;
-       bool flush;
-
-       kvm_riscv_gstage_init(&gstage, kvm);
+       bool flush = false;
 
        write_lock(&kvm->mmu_lock);
-       flush = kvm_riscv_gstage_wp_range(&gstage, start, end);
+       if (kvm_riscv_gstage_init(&gstage, kvm))
+               flush = kvm_riscv_gstage_wp_range(&gstage, start, end);
        write_unlock(&kvm->mmu_lock);
        if (flush)
                kvm_flush_remote_tlbs_memslot(kvm, memslot);
@@ -44,7 +43,7 @@ int kvm_riscv_mmu_ioremap(struct kvm *kvm, gpa_t gpa, phys_addr_t hpa,
        pgprot_t prot;
        unsigned long pfn;
        phys_addr_t addr, end;
-       unsigned long pgd_levels = kvm->arch.pgd_levels;
+       unsigned long pgd_levels = kvm_riscv_gstage_max_pgd_levels;
        struct kvm_mmu_memory_cache pcache = {
                .gfp_custom = (in_atomic) ? GFP_ATOMIC | __GFP_ACCOUNT : 0,
                .gfp_zero = __GFP_ZERO,
@@ -52,8 +51,6 @@ int kvm_riscv_mmu_ioremap(struct kvm *kvm, gpa_t gpa, phys_addr_t hpa,
        struct kvm_gstage_mapping map;
        struct kvm_gstage gstage;
 
-       kvm_riscv_gstage_init(&gstage, kvm);
-
        end = (gpa + size + PAGE_SIZE - 1) & PAGE_MASK;
        pfn = __phys_to_pfn(hpa);
        prot = pgprot_noncached(PAGE_WRITE);
@@ -72,7 +69,10 @@ int kvm_riscv_mmu_ioremap(struct kvm *kvm, gpa_t gpa, phys_addr_t hpa,
                        goto out;
 
                write_lock(&kvm->mmu_lock);
-               ret = kvm_riscv_gstage_set_pte(&gstage, &pcache, &map);
+               if (kvm_riscv_gstage_init(&gstage, kvm))
+                       ret = kvm_riscv_gstage_set_pte(&gstage, &pcache, &map);
+               else
+                       ret = -EFAULT;
                write_unlock(&kvm->mmu_lock);
                if (ret)
                        goto out;
@@ -88,12 +88,11 @@ out:
 void kvm_riscv_mmu_iounmap(struct kvm *kvm, gpa_t gpa, unsigned long size)
 {
        struct kvm_gstage gstage;
-       bool flush;
-
-       kvm_riscv_gstage_init(&gstage, kvm);
+       bool flush = false;
 
        write_lock(&kvm->mmu_lock);
-       flush = kvm_riscv_gstage_unmap_range(&gstage, gpa, size, false);
+       if (kvm_riscv_gstage_init(&gstage, kvm))
+               flush = kvm_riscv_gstage_unmap_range(&gstage, gpa, size, false);
        write_unlock(&kvm->mmu_lock);
 
        if (flush)
@@ -146,7 +145,7 @@ static bool mmu_split_huge_pages(struct kvm_gstage *gstage,
                        write_lock(&kvm->mmu_lock);
                }
 
-               if (!kvm->arch.pgd)
+               if (!kvm->arch.pgd || gstage->pgd != kvm->arch.pgd)
                        return flush;
 
                flush |= kvm_riscv_gstage_split_huge(gstage, pcache, addr, 0, false);
@@ -167,7 +166,8 @@ void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
        phys_addr_t end = (base_gfn + __fls(mask) + 1) << PAGE_SHIFT;
        struct kvm_gstage gstage;
 
-       kvm_riscv_gstage_init(&gstage, kvm);
+       if (!kvm_riscv_gstage_init(&gstage, kvm))
+               return;
 
        kvm_riscv_gstage_wp_pt_masked(&gstage, base_gfn, mask);
 
@@ -205,16 +205,15 @@ void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
        gpa_t gpa = slot->base_gfn << PAGE_SHIFT;
        phys_addr_t size = slot->npages << PAGE_SHIFT;
        struct kvm_gstage gstage;
-       bool flush;
-
-       kvm_riscv_gstage_init(&gstage, kvm);
+       u64 nr_pages = 0;
 
        write_lock(&kvm->mmu_lock);
-       flush = kvm_riscv_gstage_unmap_range(&gstage, gpa, size, false);
+       if (kvm_riscv_gstage_init(&gstage, kvm))
+               nr_pages = kvm_riscv_gstage_unmap_range(&gstage, gpa, size, true);
+       if (nr_pages)
+               kvm_flush_remote_tlbs_range(kvm, slot->base_gfn + slot->npages - nr_pages,
+                                           nr_pages);
        write_unlock(&kvm->mmu_lock);
-       if (flush)
-               kvm_flush_remote_tlbs_range(kvm, gpa >> PAGE_SHIFT,
-                                           size >> PAGE_SHIFT);
 }
 
 static void mmu_split_memory_region(struct kvm *kvm, int slot)
@@ -224,12 +223,11 @@ static void mmu_split_memory_region(struct kvm *kvm, int slot)
        phys_addr_t start = memslot->base_gfn << PAGE_SHIFT;
        phys_addr_t end = (memslot->base_gfn + memslot->npages) << PAGE_SHIFT;
        struct kvm_gstage gstage;
-       bool flush;
-
-       kvm_riscv_gstage_init(&gstage, kvm);
+       bool flush = false;
 
        write_lock(&kvm->mmu_lock);
-       flush = mmu_split_huge_pages(&gstage, start, end);
+       if (kvm_riscv_gstage_init(&gstage, kvm))
+               flush = mmu_split_huge_pages(&gstage, start, end);
        write_unlock(&kvm->mmu_lock);
 
        if (flush)
@@ -332,20 +330,17 @@ out:
 bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
 {
        struct kvm_gstage gstage;
-       bool flush;
-
-       if (!kvm->arch.pgd)
-               return false;
+       u64 nr_pages;
 
        lockdep_assert_held_write(&kvm->mmu_lock);
 
-       kvm_riscv_gstage_init(&gstage, kvm);
-       flush = kvm_riscv_gstage_unmap_range(&gstage, range->start << PAGE_SHIFT,
-                                            (range->end - range->start) << PAGE_SHIFT,
-                                            range->may_block);
-       if (flush)
-               kvm_flush_remote_tlbs_range(kvm, range->start,
-                                           range->end - range->start);
+       if (!kvm_riscv_gstage_init(&gstage, kvm))
+               return false;
+       nr_pages = kvm_riscv_gstage_unmap_range(&gstage, range->start << PAGE_SHIFT,
+                                               (range->end - range->start) << PAGE_SHIFT,
+                                               range->may_block);
+       if (nr_pages)
+               kvm_flush_remote_tlbs_range(kvm, range->end - nr_pages, nr_pages);
        return false;
 }
 
@@ -356,12 +351,11 @@ bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
        u64 size = (range->end - range->start) << PAGE_SHIFT;
        struct kvm_gstage gstage;
 
-       if (!kvm->arch.pgd)
+       if (!kvm_riscv_gstage_init(&gstage, kvm))
                return false;
 
        WARN_ON(size != PAGE_SIZE && size != PMD_SIZE && size != PUD_SIZE);
 
-       kvm_riscv_gstage_init(&gstage, kvm);
        if (!kvm_riscv_gstage_get_leaf(&gstage, range->start << PAGE_SHIFT,
                                       &ptep, &ptep_level))
                return false;
@@ -376,12 +370,11 @@ bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
        u64 size = (range->end - range->start) << PAGE_SHIFT;
        struct kvm_gstage gstage;
 
-       if (!kvm->arch.pgd)
+       if (!kvm_riscv_gstage_init(&gstage, kvm))
                return false;
 
        WARN_ON(size != PAGE_SIZE && size != PMD_SIZE && size != PUD_SIZE);
 
-       kvm_riscv_gstage_init(&gstage, kvm);
        if (!kvm_riscv_gstage_get_leaf(&gstage, range->start << PAGE_SHIFT,
                                       &ptep, &ptep_level))
                return false;
@@ -563,12 +556,12 @@ static bool kvm_riscv_mmu_dirty_log_write_fault_fast(struct kvm *kvm,
        bool dirty_marked = false;
        bool ret;
 
-       kvm_riscv_gstage_init(&gstage, kvm);
        mmu_seq = kvm->mmu_invalidate_seq;
 
        read_lock(&kvm->mmu_lock);
 
-       if (mmu_invalidate_retry_gfn(kvm, mmu_seq, gfn)) {
+       if (!kvm_riscv_gstage_init(&gstage, kvm) ||
+           mmu_invalidate_retry_gfn(kvm, mmu_seq, gfn)) {
                ret = false;
                goto out_unlock;
        }
@@ -640,8 +633,6 @@ int kvm_riscv_mmu_map(struct kvm_vcpu *vcpu, struct kvm_memory_slot *memslot,
        struct kvm_gstage gstage;
        struct page *page;
 
-       kvm_riscv_gstage_init(&gstage, kvm);
-
        /* Setup initial state of output mapping */
        memset(out_map, 0, sizeof(*out_map));
 
@@ -649,8 +640,8 @@ int kvm_riscv_mmu_map(struct kvm_vcpu *vcpu, struct kvm_memory_slot *memslot,
            kvm_riscv_mmu_dirty_log_write_fault_fast(kvm, memslot, gpa, out_map))
                return 0;
 
-       /* We need minimum second+third level pages */
-       ret = kvm_mmu_topup_memory_cache(pcache, kvm->arch.pgd_levels);
+       /* Size the cache before acquiring the shared root under mmu_lock. */
+       ret = kvm_mmu_topup_memory_cache(pcache, kvm_riscv_gstage_max_pgd_levels);
        if (ret) {
                kvm_err("Failed to topup G-stage cache\n");
                return ret;
@@ -722,6 +713,11 @@ int kvm_riscv_mmu_map(struct kvm_vcpu *vcpu, struct kvm_memory_slot *memslot,
 
        write_lock(&kvm->mmu_lock);
 
+       if (!kvm_riscv_gstage_init(&gstage, kvm)) {
+               ret = -EFAULT;
+               goto out_unlock;
+       }
+
        if (mmu_invalidate_retry(kvm, mmu_seq)) {
                unused = true;
                goto out_unlock;
@@ -829,24 +825,24 @@ void kvm_riscv_mmu_free_pgd(struct kvm *kvm)
        bool flush = false;
 
        write_lock(&kvm->mmu_lock);
-       if (kvm->arch.pgd) {
-               kvm_riscv_gstage_init(&gstage, kvm);
+       if (kvm_riscv_gstage_init(&gstage, kvm)) {
                flush = kvm_riscv_gstage_unmap_range(&gstage, 0UL,
-                       kvm_riscv_gstage_gpa_size(kvm->arch.pgd_levels), false);
-               pgd = READ_ONCE(kvm->arch.pgd);
-               kvm->arch.pgd = NULL;
-               kvm->arch.pgd_phys = 0;
-               kvm->arch.pgd_levels = 0;
+                       kvm_riscv_gstage_gpa_size(gstage.pgd_levels), true);
+               /* Only the caller that still owns the root may detach it. */
+               if (gstage.pgd == kvm->arch.pgd) {
+                       pgd = kvm->arch.pgd;
+                       kvm->arch.pgd = NULL;
+                       kvm->arch.pgd_phys = 0;
+                       kvm->arch.pgd_levels = 0;
+               }
        }
-       write_unlock(&kvm->mmu_lock);
-
-       if (flush)
+       /* Synchronize before another invalidator can observe the detached root. */
+       if (flush || pgd)
                kvm_flush_remote_tlbs(kvm);
+       write_unlock(&kvm->mmu_lock);
 
        if (pgd)
                free_pages((unsigned long)pgd, get_order(kvm_riscv_gstage_pgd_size));
-
-       kvm_mmu_free_memory_cache(&kvm->arch.pgd_split_page_cache);
 }
 
 void kvm_riscv_mmu_update_hgatp(struct kvm_vcpu *vcpu)
arch/riscv/kvm/vm.c +3 -0
index 58500a19b..7d467b0c5 100644
@@ -54,6 +54,9 @@ void kvm_arch_destroy_vm(struct kvm *kvm)
        kvm_destroy_vcpus(kvm);
 
        kvm_riscv_aia_destroy_vm(kvm);
+
+       /* MMU notifier callbacks have finished before VM destruction. */
+       kvm_mmu_free_memory_cache(&kvm->arch.pgd_split_page_cache);
 }
 
 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irql,

base-commit: aebb7274476403040d582c61478df8f4a7bf9cd3 --
2.34.1

author
#6 lore raw

PATCH v4 1/1 KVM: riscv: Allow rescheduling during G-stage range unmap

Removing a populated memslot can require walking a large G-stage range while holding mmu_lock. Allow this path to use the existing write-lock reschedule helper.

Take the shared root snapshot under mmu_lock for lock-based walkers. Lockless aging continues to take its snapshot under RCU. Verify the root before walking again after dropping the lock.

Flush pending invalidations before yielding so that a concurrent invalidator cannot miss PTEs cleared by the current walker. Return the length of the remaining range that needs a flush so the memslot and MMU notifier paths flush only that range under mmu_lock.

Keep the recursive teardown and RCU freeing of page tables. Request the full VM flush before dropping mmu_lock on root detach so another invalidator cannot return early after observing a detached root.

Codex assisted with implementation and validation. Sashiko identified the redundant final range flush during review.

---
Changes in v4

- Rebase onto the RISC-V KVM queue at Anup's request.
- Keep lockless aging under RCU and preserve recursive G-stage teardown and deferred page-table freeing. Limit the new rescheduling to memslot range unmap. The existing MMU notifier reschedule path now flushes pending invalidations before yielding.
- Drop the split page cache change because the queue already frees the cache in kvm_arch_destroy_vm().

Changes in v3

- Flush only the unflushed tail in the memslot and MMU notifier paths.

Changes in v2

- Skip a final range flush when there are no pending invalidations.

Testing

- Cross-built RV64 vmlinux, Image and modules.
- QEMU 10.0.0 with two CPUs passed guest_print_test, memslot_modification_stress_test and dirty_log_test, also with lockdep enabled. An MMU stress run with lockdep and a competing CPU-bound task timed out.
- mmu_stress_test -c 2 -m 2 -s 1 passed with lockdep disabled and without the competing task.
- The trace showed a final memslot flush of 185558 pages out of 262144 after yielding.
- The trace showed a final MMU notifier flush of 68495 pages out of 131072 after yielding.

 arch/riscv/include/asm/kvm_gstage.h | 18 ++++--
 arch/riscv/kvm/gstage.c             | 35 +++++++---
 arch/riscv/kvm/mmu.c                | 99 ++++++++++++++---------------
 3 files changed, 88 insertions(+), 64 deletions(-)
arch/riscv/include/asm/kvm_gstage.h +14 -4
index bff1c3812..07e3a8c86 100644
@@ -80,8 +80,9 @@ enum kvm_riscv_gstage_op {
 bool kvm_riscv_gstage_op_pte(struct kvm_gstage *gstage, gpa_t addr,
 			     pte_t *ptep, u32 ptep_level, enum kvm_riscv_gstage_op op);
 
-bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
-				  gpa_t start, gpa_t size, bool may_block);
+/* Return the number of trailing pages to flush, or zero if none remain. */
+u64 kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
+				 gpa_t start, gpa_t size, bool may_block);
 
 bool kvm_riscv_gstage_unmap_all(struct kvm_gstage *gstage);
 
@@ -111,13 +112,22 @@ static inline unsigned long kvm_riscv_gstage_mode(unsigned long pgd_levels)
 	}
 }
 
-static inline void kvm_riscv_gstage_init(struct kvm_gstage *gstage, struct kvm *kvm)
+/* Protect the shared page tables with mmu_lock or RCU for lockless aging. */
+static inline bool kvm_riscv_gstage_init(struct kvm_gstage *gstage, struct kvm *kvm)
 {
+	RCU_LOCKDEP_WARN(!lockdep_is_held(&kvm->mmu_lock) && !rcu_read_lock_held(),
+			 "G-stage walk without mmu_lock or RCU");
+
+	gstage->pgd = READ_ONCE(kvm->arch.pgd);
+	if (!gstage->pgd)
+		return false;
+
 	gstage->kvm = kvm;
 	gstage->flags = 0;
 	gstage->vmid = READ_ONCE(kvm->arch.vmid.vmid);
-	gstage->pgd = READ_ONCE(kvm->arch.pgd);
 	gstage->pgd_levels = kvm->arch.pgd_levels;
+
+	return true;
 }
 
 #endif
arch/riscv/kvm/gstage.c +27 -8
index 66e25b6b4..d200eacda 100644
@@ -440,8 +440,8 @@ bool kvm_riscv_gstage_op_pte(struct kvm_gstage *gstage, gpa_t addr,
 	return flush;
 }
 
-bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
-				  gpa_t start, gpa_t size, bool may_block)
+u64 kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
+				 gpa_t start, gpa_t size, bool may_block)
 {
 	int ret;
 	pte_t *ptep;
@@ -449,9 +449,19 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
 	bool found_leaf;
 	unsigned long page_size;
 	gpa_t addr = start, end = start + size;
-	bool flush = false;
+	gfn_t last_flush_gfn = start >> PAGE_SHIFT;
+	bool pending_flush = false;
+
+	if (!(gstage->flags & KVM_GSTAGE_FLAGS_LOCAL))
+		lockdep_assert_held_write(&gstage->kvm->mmu_lock);
 
 	while (addr < end) {
+		/* A concurrent teardown may have freed the root while unlocked. */
+		if (!(gstage->flags & KVM_GSTAGE_FLAGS_LOCAL) &&
+		    (!gstage->kvm->arch.pgd ||
+		     gstage->pgd != gstage->kvm->arch.pgd))
+			break;
+
 		found_leaf = kvm_riscv_gstage_get_leaf(gstage, addr, &ptep, &ptep_level);
 		ret = gstage_level_to_page_size(gstage, ptep_level, &page_size);
 		if (ret)
@@ -460,10 +470,10 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
 		if (!found_leaf) {
 			addr = ALIGN(addr + 1, page_size);
 		} else {
-			if (!(addr & (page_size - 1)) && ((end - addr) >= page_size))
-				flush |= kvm_riscv_gstage_op_pte(gstage, addr, ptep,
+			if (!(addr & (page_size - 1)) && ((end - addr) >= page_size)) {
+				pending_flush |= kvm_riscv_gstage_op_pte(gstage, addr, ptep,
 								 ptep_level, GSTAGE_OP_CLEAR);
-			else {
+			} else {
 				WARN_ONCE(1, "Skip unmap range addr: %#llx, end: %#llx, page_size: %#lx\n",
 						addr, end, page_size);
 			}
@@ -474,12 +484,21 @@ 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.
+		 * Flush first so another invalidator cannot miss cleared PTEs.
 		 */
-		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 (pending_flush) {
+				kvm_flush_remote_tlbs_range(gstage->kvm, last_flush_gfn,
+							    (addr >> PAGE_SHIFT) - last_flush_gfn);
+				pending_flush = false;
+			}
+			last_flush_gfn = addr >> PAGE_SHIFT;
 			cond_resched_rwlock_write(&gstage->kvm->mmu_lock);
+		}
 	}
 
-	return flush;
+	return pending_flush ? (end >> PAGE_SHIFT) - last_flush_gfn : 0;
 }
 
 /*
arch/riscv/kvm/mmu.c +47 -52

221 lines not on this page · raw message

base-commit: bd68956997dddcc3b1a7dd2fadadf584529027a1

Signature · 7 lines
2.56.1


-- 
kvm-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/kvm-riscv
maintainer
#7 lore raw

Re: [PATCH v4] KVM: riscv: Allow rescheduling during G-stage range unmap

Quoted 83 lines · Can Qi

Removing a populated memslot can require walking a large G-stage range while holding mmu_lock. Allow this path to use the existing write-lock reschedule helper.

Take the shared root snapshot under mmu_lock for lock-based walkers. Lockless aging continues to take its snapshot under RCU. Verify the root before walking again after dropping the lock.

Flush pending invalidations before yielding so that a concurrent invalidator cannot miss PTEs cleared by the current walker. Return the length of the remaining range that needs a flush so the memslot and MMU notifier paths flush only that range under mmu_lock.

Keep the recursive teardown and RCU freeing of page tables. Request the full VM flush before dropping mmu_lock on root detach so another invalidator cannot return early after observing a detached root.

Codex assisted with implementation and validation. Sashiko identified the redundant final range flush during review.

---
Changes in v4

- Rebase onto the RISC-V KVM queue at Anup's request.
- Keep lockless aging under RCU and preserve recursive G-stage teardown and deferred page-table freeing. Limit the new rescheduling to memslot range unmap. The existing MMU notifier reschedule path now flushes pending invalidations before yielding.
- Drop the split page cache change because the queue already frees the cache in kvm_arch_destroy_vm().

Changes in v3

- Flush only the unflushed tail in the memslot and MMU notifier paths.

Changes in v2

- Skip a final range flush when there are no pending invalidations.

Testing

- Cross-built RV64 vmlinux, Image and modules.
- QEMU 10.0.0 with two CPUs passed guest_print_test, memslot_modification_stress_test and dirty_log_test, also with lockdep enabled. An MMU stress run with lockdep and a competing CPU-bound task timed out.
- mmu_stress_test -c 2 -m 2 -s 1 passed with lockdep disabled and without the competing task.
- The trace showed a final memslot flush of 185558 pages out of 262144 after yielding.
- The trace showed a final MMU notifier flush of 68495 pages out of 131072 after yielding.

 arch/riscv/include/asm/kvm_gstage.h | 18 ++++--
 arch/riscv/kvm/gstage.c             | 35 +++++++---
 arch/riscv/kvm/mmu.c                | 99 ++++++++++++++---------------
 3 files changed, 88 insertions(+), 64 deletions(-)
arch/riscv/include/asm/kvm_gstage.h +3 -3
index bff1c3812..07e3a8c86 100644
@@ -80,8 +80,9 @@ enum kvm_riscv_gstage_op {
 bool kvm_riscv_gstage_op_pte(struct kvm_gstage *gstage, gpa_t addr,
                             pte_t *ptep, u32 ptep_level, enum kvm_riscv_gstage_op op);
 
-bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
-                                 gpa_t start, gpa_t size, bool may_block);
+/* Return the number of trailing pages to flush, or zero if none remain. */
+u64 kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
+                                gpa_t start, gpa_t size, bool may_block);
 
 bool kvm_riscv_gstage_unmap_all(struct kvm_gstage *gstage);
 
@@ -111,13 +112,22 @@ static inline unsigned long kvm_riscv_gstage_mode(unsigned long pgd_levels)
        }
 }
 
-static inline void kvm_riscv_gstage_init(struct kvm_gstage *gstage, struct kvm *kvm)

arch/riscv/include/asm/kvm_gstage.h static inline unsigned long kvm_riscv_gstage_mode(unsigned long pgd_levels) · line 124

Quoted 10 lines
arch/riscv/include/asm/kvm_gstage.h +9 -0
+/* Protect the shared page tables with mmu_lock or RCU for lockless aging. */
+static inline bool kvm_riscv_gstage_init(struct kvm_gstage *gstage, struct kvm *kvm)
 {
+       RCU_LOCKDEP_WARN(!lockdep_is_held(&kvm->mmu_lock) && !rcu_read_lock_held(),
+                        "G-stage walk without mmu_lock or RCU");
+
+       gstage->pgd = READ_ONCE(kvm->arch.pgd);
+       if (!gstage->pgd)
+               return false;
+

The kvm_riscv_gstage_init() is going to be used nested virtualization where we have separate per-VCPU shadown page table so these changes will break that.

Drop these changes in kvm_riscv_gstage_init().

Quoted 238 lines
arch/riscv/include/asm/kvm_gstage.h +2 -1
        gstage->kvm = kvm;
        gstage->flags = 0;
        gstage->vmid = READ_ONCE(kvm->arch.vmid.vmid);
-       gstage->pgd = READ_ONCE(kvm->arch.pgd);
        gstage->pgd_levels = kvm->arch.pgd_levels;
+
+       return true;
 }
 
 #endif
arch/riscv/kvm/gstage.c +27 -8
index 66e25b6b4..d200eacda 100644
@@ -440,8 +440,8 @@ bool kvm_riscv_gstage_op_pte(struct kvm_gstage *gstage, gpa_t addr,
        return flush;
 }
 
-bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
-                                 gpa_t start, gpa_t size, bool may_block)
+u64 kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
+                                gpa_t start, gpa_t size, bool may_block)
 {
        int ret;
        pte_t *ptep;
@@ -449,9 +449,19 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
        bool found_leaf;
        unsigned long page_size;
        gpa_t addr = start, end = start + size;
-       bool flush = false;
+       gfn_t last_flush_gfn = start >> PAGE_SHIFT;
+       bool pending_flush = false;
+
+       if (!(gstage->flags & KVM_GSTAGE_FLAGS_LOCAL))
+               lockdep_assert_held_write(&gstage->kvm->mmu_lock);
 
        while (addr < end) {
+               /* A concurrent teardown may have freed the root while unlocked. */
+               if (!(gstage->flags & KVM_GSTAGE_FLAGS_LOCAL) &&
+                   (!gstage->kvm->arch.pgd ||
+                    gstage->pgd != gstage->kvm->arch.pgd))
+                       break;
+
                found_leaf = kvm_riscv_gstage_get_leaf(gstage, addr, &ptep, &ptep_level);
                ret = gstage_level_to_page_size(gstage, ptep_level, &page_size);
                if (ret)
@@ -460,10 +470,10 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
                if (!found_leaf) {
                        addr = ALIGN(addr + 1, page_size);
                } else {
-                       if (!(addr & (page_size - 1)) && ((end - addr) >= page_size))
-                               flush |= kvm_riscv_gstage_op_pte(gstage, addr, ptep,
+                       if (!(addr & (page_size - 1)) && ((end - addr) >= page_size)) {
+                               pending_flush |= kvm_riscv_gstage_op_pte(gstage, addr, ptep,
                                                                 ptep_level, GSTAGE_OP_CLEAR);
-                       else {
+                       } else {
                                WARN_ONCE(1, "Skip unmap range addr: %#llx, end: %#llx, page_size: %#lx\n",
                                                addr, end, page_size);
                        }
@@ -474,12 +484,21 @@ 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.
+                * Flush first so another invalidator cannot miss cleared PTEs.
                 */
-               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 (pending_flush) {
+                               kvm_flush_remote_tlbs_range(gstage->kvm, last_flush_gfn,
+                                                           (addr >> PAGE_SHIFT) - last_flush_gfn);
+                               pending_flush = false;
+                       }
+                       last_flush_gfn = addr >> PAGE_SHIFT;
                        cond_resched_rwlock_write(&gstage->kvm->mmu_lock);
+               }
        }
 
-       return flush;
+       return pending_flush ? (end >> PAGE_SHIFT) - last_flush_gfn : 0;
 }
 
 /*
arch/riscv/kvm/mmu.c +31 -36
index dee36dc77..31eb667ea 100644
@@ -26,12 +26,11 @@ static void mmu_wp_memory_region(struct kvm *kvm, int slot)
        phys_addr_t start = memslot->base_gfn << PAGE_SHIFT;
        phys_addr_t end = (memslot->base_gfn + memslot->npages) << PAGE_SHIFT;
        struct kvm_gstage gstage;
-       bool flush;
-
-       kvm_riscv_gstage_init(&gstage, kvm);
+       bool flush = false;
 
        write_lock(&kvm->mmu_lock);
-       flush = kvm_riscv_gstage_wp_range(&gstage, start, end);
+       if (kvm_riscv_gstage_init(&gstage, kvm))
+               flush = kvm_riscv_gstage_wp_range(&gstage, start, end);
        write_unlock(&kvm->mmu_lock);
        if (flush)
                kvm_flush_remote_tlbs_memslot(kvm, memslot);
@@ -44,7 +43,7 @@ int kvm_riscv_mmu_ioremap(struct kvm *kvm, gpa_t gpa, phys_addr_t hpa,
        pgprot_t prot;
        unsigned long pfn;
        phys_addr_t addr, end;
-       unsigned long pgd_levels = kvm->arch.pgd_levels;
+       unsigned long pgd_levels = kvm_riscv_gstage_max_pgd_levels;
        struct kvm_mmu_memory_cache pcache = {
                .gfp_custom = (in_atomic) ? GFP_ATOMIC | __GFP_ACCOUNT : 0,
                .gfp_zero = __GFP_ZERO,
@@ -52,8 +51,6 @@ int kvm_riscv_mmu_ioremap(struct kvm *kvm, gpa_t gpa, phys_addr_t hpa,
        struct kvm_gstage_mapping map;
        struct kvm_gstage gstage;
 
-       kvm_riscv_gstage_init(&gstage, kvm);
-
        end = (gpa + size + PAGE_SIZE - 1) & PAGE_MASK;
        pfn = __phys_to_pfn(hpa);
        prot = pgprot_noncached(PAGE_WRITE);
@@ -72,7 +69,10 @@ int kvm_riscv_mmu_ioremap(struct kvm *kvm, gpa_t gpa, phys_addr_t hpa,
                        goto out;
 
                write_lock(&kvm->mmu_lock);
-               ret = kvm_riscv_gstage_set_pte(&gstage, &pcache, &map);
+               if (kvm_riscv_gstage_init(&gstage, kvm))
+                       ret = kvm_riscv_gstage_set_pte(&gstage, &pcache, &map);
+               else
+                       ret = -EFAULT;
                write_unlock(&kvm->mmu_lock);
                if (ret)
                        goto out;
@@ -88,12 +88,11 @@ int kvm_riscv_mmu_ioremap(struct kvm *kvm, gpa_t gpa, phys_addr_t hpa,
 void kvm_riscv_mmu_iounmap(struct kvm *kvm, gpa_t gpa, unsigned long size)
 {
        struct kvm_gstage gstage;
-       bool flush;
-
-       kvm_riscv_gstage_init(&gstage, kvm);
+       bool flush = false;
 
        write_lock(&kvm->mmu_lock);
-       flush = kvm_riscv_gstage_unmap_range(&gstage, gpa, size, false);
+       if (kvm_riscv_gstage_init(&gstage, kvm))
+               flush = kvm_riscv_gstage_unmap_range(&gstage, gpa, size, false);
        write_unlock(&kvm->mmu_lock);
 
        if (flush)
@@ -146,7 +145,7 @@ static bool mmu_split_huge_pages(struct kvm_gstage *gstage,
                        write_lock(&kvm->mmu_lock);
                }
 
-               if (!kvm->arch.pgd)
+               if (!kvm->arch.pgd || gstage->pgd != kvm->arch.pgd)
                        return flush;
 
                flush |= kvm_riscv_gstage_split_huge(gstage, pcache, addr, 0, false);
@@ -167,7 +166,8 @@ void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
        phys_addr_t end = (base_gfn + __fls(mask) + 1) << PAGE_SHIFT;
        struct kvm_gstage gstage;
 
-       kvm_riscv_gstage_init(&gstage, kvm);
+       if (!kvm_riscv_gstage_init(&gstage, kvm))
+               return;
 
        kvm_riscv_gstage_wp_pt_masked(&gstage, base_gfn, mask);
 
@@ -205,16 +205,15 @@ void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
        gpa_t gpa = slot->base_gfn << PAGE_SHIFT;
        phys_addr_t size = slot->npages << PAGE_SHIFT;
        struct kvm_gstage gstage;
-       bool flush;
-
-       kvm_riscv_gstage_init(&gstage, kvm);
+       u64 nr_pages = 0;
 
        write_lock(&kvm->mmu_lock);
-       flush = kvm_riscv_gstage_unmap_range(&gstage, gpa, size, false);
+       if (kvm_riscv_gstage_init(&gstage, kvm))
+               nr_pages = kvm_riscv_gstage_unmap_range(&gstage, gpa, size, true);
+       if (nr_pages)
+               kvm_flush_remote_tlbs_range(kvm, slot->base_gfn + slot->npages - nr_pages,
+                                           nr_pages);
        write_unlock(&kvm->mmu_lock);
-       if (flush)
-               kvm_flush_remote_tlbs_range(kvm, gpa >> PAGE_SHIFT,
-                                           size >> PAGE_SHIFT);
 }
 
 static void mmu_split_memory_region(struct kvm *kvm, int slot)
@@ -224,12 +223,11 @@ static void mmu_split_memory_region(struct kvm *kvm, int slot)
        phys_addr_t start = memslot->base_gfn << PAGE_SHIFT;
        phys_addr_t end = (memslot->base_gfn + memslot->npages) << PAGE_SHIFT;
        struct kvm_gstage gstage;
-       bool flush;
-
-       kvm_riscv_gstage_init(&gstage, kvm);
+       bool flush = false;
 
        write_lock(&kvm->mmu_lock);
-       flush = mmu_split_huge_pages(&gstage, start, end);
+       if (kvm_riscv_gstage_init(&gstage, kvm))
+               flush = mmu_split_huge_pages(&gstage, start, end);
        write_unlock(&kvm->mmu_lock);
 
        if (flush)
@@ -332,20 +330,17 @@ int kvm_arch_prepare_memory_region(struct kvm *kvm,
 bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
 {
        struct kvm_gstage gstage;
-       bool flush;
-
-       if (!kvm->arch.pgd)
-               return false;
+       u64 nr_pages;
 
        lockdep_assert_held_write(&kvm->mmu_lock);
 
-       kvm_riscv_gstage_init(&gstage, kvm);
-       flush = kvm_riscv_gstage_unmap_range(&gstage, range->start << PAGE_SHIFT,
-                                            (range->end - range->start) << PAGE_SHIFT,
-                                            range->may_block);
-       if (flush)
-               kvm_flush_remote_tlbs_range(kvm, range->start,
-                                           range->end - range->start);
+       if (!kvm_riscv_gstage_init(&gstage, kvm))
+               return false;
+       nr_pages = kvm_riscv_gstage_unmap_range(&gstage, range->start << PAGE_SHIFT,
+                                               (range->end - range->start) << PAGE_SHIFT,
+                                               range->may_block);
+       if (nr_pages)
+               kvm_flush_remote_tlbs_range(kvm, range->end - nr_pages, nr_pages);
        return false;
 }
 

arch/riscv/kvm/mmu.c static bool kvm_riscv_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range, · line 360

Quoted 4 lines
arch/riscv/kvm/mmu.c +0 -1
@@ -357,8 +352,7 @@ static bool kvm_riscv_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range,
        guard(rcu)();
        lockdep_assert_not_held(&kvm->mmu_lock);
 
-       kvm_riscv_gstage_init(&gstage, kvm);

Drop all these kvm_riscv_gstage_init() related changes.

Quoted 84 lines
arch/riscv/kvm/mmu.c +16 -15
-       if (!gstage.pgd)
+       if (!kvm_riscv_gstage_init(&gstage, kvm))
                return false;
 
        return kvm_riscv_gstage_age_range(&gstage, range->start << PAGE_SHIFT,
@@ -549,12 +543,12 @@ static bool kvm_riscv_mmu_dirty_log_write_fault_fast(struct kvm *kvm,
        bool dirty_marked = false;
        bool ret;
 
-       kvm_riscv_gstage_init(&gstage, kvm);
        mmu_seq = kvm->mmu_invalidate_seq;
 
        read_lock(&kvm->mmu_lock);
 
-       if (mmu_invalidate_retry_gfn(kvm, mmu_seq, gfn)) {
+       if (!kvm_riscv_gstage_init(&gstage, kvm) ||
+           mmu_invalidate_retry_gfn(kvm, mmu_seq, gfn)) {
                ret = false;
                goto out_unlock;
        }
@@ -634,8 +628,6 @@ int kvm_riscv_mmu_map(struct kvm_vcpu *vcpu, struct kvm_memory_slot *memslot,
        struct kvm_gstage gstage;
        struct page *page;
 
-       kvm_riscv_gstage_init(&gstage, kvm);
-
        /* Setup initial state of output mapping */
        memset(out_map, 0, sizeof(*out_map));
 
@@ -643,8 +635,8 @@ int kvm_riscv_mmu_map(struct kvm_vcpu *vcpu, struct kvm_memory_slot *memslot,
            kvm_riscv_mmu_dirty_log_write_fault_fast(kvm, memslot, gpa, out_map))
                return 0;
 
-       /* We need minimum second+third level pages */
-       ret = kvm_mmu_topup_memory_cache(pcache, kvm->arch.pgd_levels);
+       /* Size the cache before acquiring the shared root under mmu_lock. */
+       ret = kvm_mmu_topup_memory_cache(pcache, kvm_riscv_gstage_max_pgd_levels);
        if (ret) {
                kvm_err("Failed to topup G-stage cache\n");
                return ret;
@@ -718,6 +710,11 @@ int kvm_riscv_mmu_map(struct kvm_vcpu *vcpu, struct kvm_memory_slot *memslot,
 
        write_lock(&kvm->mmu_lock);
 
+       if (!kvm_riscv_gstage_init(&gstage, kvm)) {
+               ret = -EFAULT;
+               goto out_unlock;
+       }
+
        if (mmu_invalidate_retry(kvm, mmu_seq)) {
                unused = true;
                goto out_unlock;
@@ -831,24 +828,22 @@ void kvm_riscv_mmu_free_pgd(struct kvm *kvm)
 {
        struct kvm_gstage gstage;
        void *pgd = NULL;
-       bool flush = false;
 
        write_lock(&kvm->mmu_lock);
-       if (kvm->arch.pgd) {
-               kvm_riscv_gstage_init(&gstage, kvm);
-               flush = kvm_riscv_gstage_unmap_all(&gstage);
-               pgd = READ_ONCE(kvm->arch.pgd);
+       if (kvm_riscv_gstage_init(&gstage, kvm)) {
+               kvm_riscv_gstage_unmap_all(&gstage);
+               pgd = gstage.pgd;
                /*
                 * Keep pgd_levels unchanged for lockless walkers that already
                 * observed the old root.
                 */
                WRITE_ONCE(kvm->arch.pgd, NULL);
                kvm->arch.pgd_phys = 0;
-       }
-       write_unlock(&kvm->mmu_lock);
 
-       if (flush)
+               /* Synchronize before another invalidator can see the detached root. */
                kvm_flush_remote_tlbs(kvm);
+       }
+       write_unlock(&kvm->mmu_lock);
 
        if (pgd)
                call_rcu(&virt_to_page(pgd)->rcu_head, kvm_riscv_mmu_free_pgd_rcu);
Quoted 4 lines

base-commit: bd68956997dddcc3b1a7dd2fadadf584529027a1 --
2.56.1

Regards,
Anup

author
#8 lore raw

PATCH v5 1/1 KVM: riscv: Allow rescheduling during G-stage unmap and teardown

Removing a populated memslot or destroying a VM can walk a large G-stage range while holding mmu_lock. Limit the time spent holding the lock continuously and let other tasks run while tearing down a VM.

Process sleepable memslot and MMU notifier unmaps in PMD-sized chunks. Advance past holes and fully covered block mappings, even when they extend past a chunk. Finish any pending remote TLB invalidations before yielding the lock, and read the current root under the lock before walking the next chunk. Flush the remaining batch before returning.

Detach the root and request the full VM TLB flush under mmu_lock before starting teardown. The VM is being rolled back during setup, its owner mm is exiting, or the last KVM reference has been dropped. No vCPU can still run with the detached root in these cases.

Recursively clear the old tree outside mmu_lock and check for rescheduling as page tables are removed. Keep RCU-delayed freeing for the root and its descendants so lockless aging walkers can finish.

Earlier revisions were co-developed with Quan Zhou. Codex assisted with implementation and QEMU validation. Sashiko identified the redundant final range flush during review.

---

Changes in v5

- Rebase on the RISC-V KVM queue at ffdc855900a8.
- Keep the existing G-stage initializer and lockless aging path.
- Use an outer PMD-sized walk for memslot and notifier unmaps. Batch invalidations until a possible lock drop or the end of the walk.
- Detach the G-stage root before the recursive VM teardown and allow rescheduling while reclaiming the old page tables.

Testing

- Built RV64 Image and RV32 KVM objects.
- On QEMU 10.0.0 TCG with two CPUs, guest_print_test, memslot_modification_stress_test, dirty_log_test, pre_fault_memory_test and mmu_stress_test -c 2 -m 2 -s 1 passed on the base and with the patch.
- Trace confirmed that both memslot and notifier unmaps issued pending invalidations before dropping mmu_lock. In seven contended 1 GiB memslot removals per kernel, median wakeup latency fell from 18.55 ms to 52 us with removal time around 20 ms on both kernels.
- Abrupt VMM exit with 16 GiB of dense 4 KiB G-stage mappings over repeated 1 GiB backing reduced the longest uninterrupted interval within the recursive walk from 132.86-134.05 ms to 1.06-1.09 ms in two paired TCG runs. Each run reclaimed 8210 descendant tables and one PGD.
- In 16 runs racing owner mm exit against close of the final VM fd, both teardown entries ran and only one walked and reclaimed the tree. Two 128 MiB exit tests also passed with lockdep enabled.

v4: https://lore.kernel.org/r/[email protected]

 arch/riscv/include/asm/kvm_gstage.h |   6 +-
 arch/riscv/kvm/gstage.c             |  77 ++++++++++----------
 arch/riscv/kvm/mmu.c                | 106 +++++++++++++++++-----------
 3 files changed, 106 insertions(+), 83 deletions(-)
arch/riscv/include/asm/kvm_gstage.h +3 -3
index bff1c3812..9913f6c5f 100644
@@ -80,10 +80,10 @@ enum kvm_riscv_gstage_op {
 bool kvm_riscv_gstage_op_pte(struct kvm_gstage *gstage, gpa_t addr,
 			     pte_t *ptep, u32 ptep_level, enum kvm_riscv_gstage_op op);
 
-bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
-				  gpa_t start, gpa_t size, bool may_block);
+s64 kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
+				 gpa_t addr, gpa_t end, gpa_t chunk_end, bool *flush);
 
-bool kvm_riscv_gstage_unmap_all(struct kvm_gstage *gstage);
+void kvm_riscv_gstage_unmap_all(struct kvm_gstage *gstage);
 
 bool kvm_riscv_gstage_wp_range(struct kvm_gstage *gstage, gpa_t start, gpa_t end);
 bool kvm_riscv_gstage_age_range(struct kvm_gstage *gstage, gpa_t start,
arch/riscv/kvm/gstage.c +40 -37

126 lines not on this page · raw message

arch/riscv/kvm/mmu.c +63 -43

153 lines not on this page · raw message

base-commit: ffdc855900a894034a63a46d699e0326dea3c991

Signature · 7 lines
2.56.1


-- 
kvm-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/kvm-riscv
#9 lore raw

Re: [PATCH v5] KVM: riscv: Allow rescheduling during G-stage unmap and teardown

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] KVM: riscv: commit message is missing a Signed-off-by trailer --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] KVM: riscv: commit message is missing a Signed-off-by trailer --

commit 5d0031b037717ca6a07783729d4f105732d072a9
Author: Can Qi <[email protected]>

Quoted 21 lines

KVM: riscv: Allow rescheduling during G-stage unmap and teardown

Removing a populated memslot or destroying a VM can walk a large G-stage range while holding mmu_lock. Limit the time spent holding the lock continuously and let other tasks run while tearing down a VM.

Process sleepable memslot and MMU notifier unmaps in PMD-sized chunks. Advance past holes and fully covered block mappings, even when they extend past a chunk. Finish any pending remote TLB invalidations before yielding the lock, and read the current root under the lock before walking the next chunk. Flush the remaining batch before returning.

Detach the root and request the full VM TLB flush under mmu_lock before starting teardown. The VM is being rolled back during setup, its owner mm is exiting, or the last KVM reference has been dropped. No vCPU can still run with the detached root in these cases.

Recursively clear the old tree outside mmu_lock and check for rescheduling as page tables are removed. Keep RCU-delayed freeing for the root and its descendants so lockless aging walkers can finish.

Quoted 5 lines

Earlier revisions were co-developed with Quan Zhou. Codex assisted with implementation and QEMU validation. Sashiko identified the redundant final range flush during review.

[Severity: High]
The commit message is missing a Signed-off-by trailer. A valid Signed-off-by line certifying the Developer Certificate of Origin is required per Documentation/process/submitting-patches.rst before this patch can be merged.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1