Kernel KVM virtualization development
 help / color / mirror / Atom feed
* [PATCH v6] KVM: riscv: Allow rescheduling during G-stage unmap and teardown
@ 2026-12-03  7:35 Can Qi
  2026-12-03  8:04 ` sashiko-bot
  0 siblings, 1 reply; 2+ messages in thread
From: Can Qi @ 2026-12-03  7:35 UTC (permalink / raw)
  To: kvm-riscv
  Cc: Can Qi, Quan Zhou, Anup Patel, Atish Patra, Paul Walmsley,
	Palmer Dabbelt, Albert Ou, Alexandre Ghiti,
	open list:KERNEL VIRTUAL MACHINE FOR RISC-V (KVM/riscv),
	open list:KERNEL VIRTUAL MACHINE FOR RISC-V (KVM/riscv),
	open list

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.

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

Co-developed-by: Quan Zhou <zhouquan@iscas.ac.cn>
Signed-off-by: Quan Zhou <zhouquan@iscas.ac.cn>
Signed-off-by: Can Qi <qican5708@163.com>
---

Changes in v6

- Add the co-developer credit and sign-off trailers.

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.

v4: https://lore.kernel.org/r/20261130102644.928941-1-qican5708@163.com

 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(-)

diff --git a/arch/riscv/include/asm/kvm_gstage.h b/arch/riscv/include/asm/kvm_gstage.h
index bff1c3812..9913f6c5f 100644
--- a/arch/riscv/include/asm/kvm_gstage.h
+++ b/arch/riscv/include/asm/kvm_gstage.h
@@ -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,
diff --git a/arch/riscv/kvm/gstage.c b/arch/riscv/kvm/gstage.c
index 241f4c19c..7c3d4bc86 100644
--- a/arch/riscv/kvm/gstage.c
+++ b/arch/riscv/kvm/gstage.c
@@ -396,8 +396,9 @@ bool kvm_riscv_gstage_split_huge(struct kvm_gstage *gstage,
 	return need_flush;
 }
 
-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)
+static bool gstage_op_pte(struct kvm_gstage *gstage, gpa_t addr,
+			  pte_t *ptep, u32 ptep_level, enum kvm_riscv_gstage_op op,
+			  bool resched)
 {
 	int i, ret;
 	pte_t pte, *next_ptep;
@@ -425,10 +426,12 @@ bool kvm_riscv_gstage_op_pte(struct kvm_gstage *gstage, gpa_t addr,
 		if (op == GSTAGE_OP_CLEAR)
 			set_pte(ptep, __pte(0));
 		for (i = 0; i < PTRS_PER_PTE; i++)
-			flush |= kvm_riscv_gstage_op_pte(gstage, addr + i * next_page_size,
-							 &next_ptep[i], next_ptep_level, op);
+			flush |= gstage_op_pte(gstage, addr + i * next_page_size,
+					       &next_ptep[i], next_ptep_level, op, resched);
 		if (op == GSTAGE_OP_CLEAR)
 			gstage_free_page_table(next_ptep);
+		if (resched)
+			cond_resched();
 	} else {
 		if (op == GSTAGE_OP_CLEAR) {
 			set_pte(ptep, __pte(0));
@@ -445,68 +448,68 @@ 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)
+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)
+{
+	return gstage_op_pte(gstage, addr, ptep, ptep_level, op, false);
+}
+
+/*
+ * Walk one chunk of the range ending at @end and report the next GPA.
+ * A hole or a fully covered block mapping can extend past @chunk_end.
+ * The caller must flush any cleared mappings before releasing its lock.
+ */
+s64 kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,
+				 gpa_t addr, gpa_t end, gpa_t chunk_end, bool *flush)
 {
 	int ret;
 	pte_t *ptep;
 	u32 ptep_level;
 	bool found_leaf;
 	unsigned long page_size;
-	gpa_t addr = start, end = start + size;
-	bool flush = false;
 
-	while (addr < end) {
+	while (addr < chunk_end) {
 		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)
-			break;
+			return ret;
 
-		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 (found_leaf) {
+			if (IS_ALIGNED(addr, page_size) && end - addr >= page_size)
+				*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);
-			}
-
-			addr += page_size;
 		}
 
-		/*
-		 * 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)
-			cond_resched_rwlock_write(&gstage->kvm->mmu_lock);
+		addr = ALIGN(addr + 1, page_size);
 	}
 
-	return flush;
+	return min(addr, end);
 }
 
 /*
- * Clear every G-stage mapping and free all page tables below the PGD.
- * kvm_riscv_gstage_unmap_range() only clears leaf PTEs and leaves the
- * page tables in place, so it cannot be used to tear down a G-stage.
+ * Clear the mappings and reclaim the page tables below a detached PGD.
+ * The caller must exclude hardware walkers and release mmu_lock first.
  */
-bool kvm_riscv_gstage_unmap_all(struct kvm_gstage *gstage)
+void kvm_riscv_gstage_unmap_all(struct kvm_gstage *gstage)
 {
 	u32 level = gstage->pgd_levels - 1;
 	pte_t *pgd = (pte_t *)gstage->pgd;
 	unsigned long i, page_size;
-	bool flush = false;
 
-	if (gstage_level_to_page_size(gstage, level, &page_size))
-		return false;
+	might_sleep();
 
-	for (i = 0; i < kvm_riscv_gstage_pgd_size / sizeof(pte_t); i++)
-		flush |= kvm_riscv_gstage_op_pte(gstage, i * page_size, &pgd[i],
-						 level, GSTAGE_OP_CLEAR);
+	if (gstage_level_to_page_size(gstage, level, &page_size))
+		return;
 
-	return flush;
+	for (i = 0; i < kvm_riscv_gstage_pgd_size / sizeof(pte_t); i++) {
+		gstage_op_pte(gstage, i * page_size, &pgd[i], level,
+			      GSTAGE_OP_CLEAR, true);
+		if (IS_ALIGNED(i + 1, PTRS_PER_PTE))
+			cond_resched();
+	}
 }
 
 bool kvm_riscv_gstage_wp_range(struct kvm_gstage *gstage, gpa_t start, gpa_t end)
diff --git a/arch/riscv/kvm/mmu.c b/arch/riscv/kvm/mmu.c
index e92d564f9..29f5de42f 100644
--- a/arch/riscv/kvm/mmu.c
+++ b/arch/riscv/kvm/mmu.c
@@ -85,20 +85,56 @@ int kvm_riscv_mmu_ioremap(struct kvm *kvm, gpa_t gpa, phys_addr_t hpa,
 	return ret;
 }
 
-void kvm_riscv_mmu_iounmap(struct kvm *kvm, gpa_t gpa, unsigned long size)
+/*
+ * Process one PMD-sized span at a time, so base-page mappings cannot
+ * hold mmu_lock for an entire large memslot when rescheduling is needed.
+ * Keep one batch of invalidations for as long as the write lock is held.
+ */
+static void mmu_unmap_range(struct kvm *kvm, gpa_t addr, gpa_t end, bool may_block)
 {
-	struct kvm_gstage gstage;
-	bool flush;
+	gfn_t batch_start = addr >> PAGE_SHIFT;
+	bool flush = false;
 
-	kvm_riscv_gstage_init(&gstage, kvm);
+	lockdep_assert_held_write(&kvm->mmu_lock);
 
-	write_lock(&kvm->mmu_lock);
-	flush = kvm_riscv_gstage_unmap_range(&gstage, gpa, size, false);
-	write_unlock(&kvm->mmu_lock);
+	while (addr < end) {
+		gpa_t chunk_end = may_block ? min(end, ALIGN(addr + 1, PMD_SIZE)) : end;
+		struct kvm_gstage gstage;
+		gfn_t next_gfn;
+		s64 next;
+
+		/* Teardown can detach the root while the lock is dropped. */
+		kvm_riscv_gstage_init(&gstage, kvm);
+		if (!gstage.pgd)
+			break;
+
+		next = kvm_riscv_gstage_unmap_range(&gstage, addr, end, chunk_end, &flush);
+		if (WARN_ON_ONCE(next < 0))
+			break;
+
+		addr = next;
+		if (!may_block || addr == end ||
+		    !(need_resched() || rwlock_needbreak(&kvm->mmu_lock)))
+			continue;
+
+		/* A concurrent invalidator must not miss PTEs we have cleared. */
+		next_gfn = addr >> PAGE_SHIFT;
+		if (flush)
+			kvm_flush_remote_tlbs_range(kvm, batch_start, next_gfn - batch_start);
+		flush = false;
+		batch_start = next_gfn;
+		cond_resched_rwlock_write(&kvm->mmu_lock);
+	}
 
 	if (flush)
-		kvm_flush_remote_tlbs_range(kvm, gpa >> PAGE_SHIFT,
-					    size >> PAGE_SHIFT);
+		kvm_flush_remote_tlbs_range(kvm, batch_start, (end >> PAGE_SHIFT) - batch_start);
+}
+
+void kvm_riscv_mmu_iounmap(struct kvm *kvm, gpa_t gpa, unsigned long size)
+{
+	write_lock(&kvm->mmu_lock);
+	mmu_unmap_range(kvm, gpa, gpa + size, false);
+	write_unlock(&kvm->mmu_lock);
 }
 
 static bool need_topup_split_caches_or_resched(struct kvm *kvm, int count)
@@ -203,18 +239,11 @@ void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
 				   struct kvm_memory_slot *slot)
 {
 	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);
+	gpa_t end = (slot->base_gfn + slot->npages) << PAGE_SHIFT;
 
 	write_lock(&kvm->mmu_lock);
-	flush = kvm_riscv_gstage_unmap_range(&gstage, gpa, size, false);
+	mmu_unmap_range(kvm, gpa, end, true);
 	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)
@@ -331,21 +360,8 @@ 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;
-
-	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);
+	mmu_unmap_range(kvm, range->start << PAGE_SHIFT, range->end << PAGE_SHIFT,
+			range->may_block);
 	return false;
 }
 
@@ -830,31 +846,35 @@ static void kvm_riscv_mmu_free_pgd_rcu(struct rcu_head *head)
 	__free_pages(page, order);
 }
 
+/*
+ * This runs on VM creation rollback, after the last KVM reference is
+ * dropped, or on teardown of the owner mm. No vCPU can still run with
+ * the old G-stage root.
+ */
 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);
+	kvm_riscv_gstage_init(&gstage, kvm);
+	if (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;
+
+		/* Flush before another invalidator can observe the detached root. */
+		kvm_flush_remote_tlbs(kvm);
 	}
 	write_unlock(&kvm->mmu_lock);
 
-	if (flush)
-		kvm_flush_remote_tlbs(kvm);
+	if (!gstage.pgd)
+		return;
 
-	if (pgd)
-		call_rcu(&virt_to_page(pgd)->rcu_head, kvm_riscv_mmu_free_pgd_rcu);
+	kvm_riscv_gstage_unmap_all(&gstage);
+	call_rcu(&virt_to_page(gstage.pgd)->rcu_head, kvm_riscv_mmu_free_pgd_rcu);
 }
 
 void kvm_riscv_mmu_update_hgatp(struct kvm_vcpu *vcpu)

base-commit: ffdc855900a894034a63a46d699e0326dea3c991
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 2+ messages in thread

* Re: [PATCH v6] KVM: riscv: Allow rescheduling during G-stage unmap and teardown
  2026-12-03  7:35 [PATCH v6] KVM: riscv: Allow rescheduling during G-stage unmap and teardown Can Qi
@ 2026-12-03  8:04 ` sashiko-bot
  0 siblings, 0 replies; 2+ messages in thread
From: sashiko-bot @ 2026-12-03  8:04 UTC (permalink / raw)
  To: Can Qi; +Cc: open list:KERNEL VIRTUAL MACHINE FOR RISC-V (KVM/riscv)

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] KVM: riscv: PMD yield flushes hit hfence_queue and per-page
  loop
--

commit a9cf70d57632be8dd08b712ee49dab08ded702eb
Author: Can Qi <qican5708@163.com>

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

This commit chunks sleepable G-stage unmaps in PMD-sized spans so mmu_lock
can be dropped between batches, and detaches the G-stage root before
recursively freeing page tables outside mmu_lock.

> diff --git a/arch/riscv/kvm/mmu.c b/arch/riscv/kvm/mmu.c
> index e92d564f9c778..29f5de42fa371 100644
> --- a/arch/riscv/kvm/mmu.c
> +++ b/arch/riscv/kvm/mmu.c
> @@ -85,20 +85,56 @@ int kvm_riscv_mmu_ioremap(struct kvm *kvm, gpa_t gpa, phys_addr_t hpa,
>  	return ret;
>  }
>  
> -void kvm_riscv_mmu_iounmap(struct kvm *kvm, gpa_t gpa, unsigned long size)
> +/*
> + * Process one PMD-sized span at a time, so base-page mappings cannot
> + * hold mmu_lock for an entire large memslot when rescheduling is needed.
> + * Keep one batch of invalidations for as long as the write lock is held.
> + */
> +static void mmu_unmap_range(struct kvm *kvm, gpa_t addr, gpa_t end, bool may_block)
>  {
> -	struct kvm_gstage gstage;
> -	bool flush;
> +	gfn_t batch_start = addr >> PAGE_SHIFT;
> +	bool flush = false;
>  
> -	kvm_riscv_gstage_init(&gstage, kvm);
> +	lockdep_assert_held_write(&kvm->mmu_lock);
>  
> -	write_lock(&kvm->mmu_lock);
> -	flush = kvm_riscv_gstage_unmap_range(&gstage, gpa, size, false);
> -	write_unlock(&kvm->mmu_lock);
> +	while (addr < end) {
> +		gpa_t chunk_end = may_block ? min(end, ALIGN(addr + 1, PMD_SIZE)) : end;
> +		struct kvm_gstage gstage;
> +		gfn_t next_gfn;
> +		s64 next;
> +
> +		/* Teardown can detach the root while the lock is dropped. */
> +		kvm_riscv_gstage_init(&gstage, kvm);
> +		if (!gstage.pgd)
> +			break;
> +
> +		next = kvm_riscv_gstage_unmap_range(&gstage, addr, end, chunk_end, &flush);
> +		if (WARN_ON_ONCE(next < 0))
> +			break;
> +
> +		addr = next;
> +		if (!may_block || addr == end ||
> +		    !(need_resched() || rwlock_needbreak(&kvm->mmu_lock)))
> +			continue;
> +
> +		/* A concurrent invalidator must not miss PTEs we have cleared. */
> +		next_gfn = addr >> PAGE_SHIFT;
> +		if (flush)
> +			kvm_flush_remote_tlbs_range(kvm, batch_start, next_gfn - batch_start);
> +		flush = false;
> +		batch_start = next_gfn;
> +		cond_resched_rwlock_write(&kvm->mmu_lock);
> +	}

[Severity: Medium]
Can yielding after a single PMD chunk trigger per-page HFENCE.GVMA loops
and overflow the vCPU hfence_queue?

When kvm_arch_flush_shadow_memslot() removes a large populated memslot
under mmu_lock contention, mmu_unmap_range() can yield after one PMD_SIZE
chunk and call kvm_flush_remote_tlbs_range() for PTRS_PER_PTE pages (512
on RV64, 1024 on RV32) while holding write_lock(&kvm->mmu_lock).

kvm_riscv_local_hfence_gvma_vmid_gpa() only falls back to a full-VMID
flush when the page count exceeds PTRS_PER_PTE:

arch/riscv/kvm/tlb.c:kvm_riscv_local_hfence_gvma_vmid_gpa() {
    ...
	if (PTRS_PER_PTE < (gpsz >> order)) {
		kvm_riscv_local_hfence_gvma_vmid_all(vmid);
		return;
	}
    ...
}

Because a single PMD spans exactly PTRS_PER_PTE pages, each yield runs
512 (RV64) or 1024 (RV32) per-page HFENCE.GVMA instructions per remote
vCPU synchronously under mmu_lock, instead of one full-VMID flush.

Each yield also enqueues an entry in every vCPU's 64-entry hfence_queue.
Even after 64 yields overflow into KVM_REQ_TLB_FLUSH,
kvm_riscv_check_vcpu_requests() still drains all 64 entries after the full
flush, running 32,768 (RV64) or 65,536 (RV32) redundant HFENCE.GVMA calls.

Using kvm_flush_remote_tlbs() before yielding would coalesce into a single
KVM_REQ_TLB_FLUSH and avoid both the per-page loop and hfence_queue growth.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261203073501.17161-1-qican5708@163.com?part=1

^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2026-12-03  8:04 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-03  7:35 [PATCH v6] KVM: riscv: Allow rescheduling during G-stage unmap and teardown Can Qi
2026-12-03  8:04 ` sashiko-bot

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox