Skip to contentSkip to conversation

KVM: arm64: nv: Grow the shadow S2 MMU pool on demand

RFC PATCH In review Nathan Chen 3 participants 11 messages Nov 24

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

cover KVM: arm64: nv: Grow the shadow S2 MMU pool on demand

A nested-capable VM gets 2 shadow stage-2 MMUs per vcpu. Once the guest hypervisor runs more nested VMs than that, nearly every nested context switch recycles a live MMU and spikes host CPU usage.

This series lets KVM grow the shadow MMU pool on demand when the pool is too small, up to a host-wide VMID budget. It also parks grown MMUs on a guest TLBI ALLE1 and when a guest range invalidation leaves them empty, in order to return unused capacity.

Testing on a 16-bit VMID, 4K pages host with 64-vCPU L1 and idle 2-vCPU Firecracker L2s:

- Ramping to 300 L2s grew the pool 128 -> 192 -> 256 -> 320, with no host CPU usage spike observed and no VMID TLB flushes.

- Dropping to 20 L2s and forcing an ALLE1 (an L1 VMID rollover from churning ~66K VMs) parked all grown MMUs and returned the budget. Ramping back to 300 reactivated them without allocating, with no host CPU usage spike observed.

- VM teardown returned the budget, with no warnings in dmesg.

Testing with 14 L2s on a 4-vCPU L1 with 6 L2 guests powered off or rebooted:

- Firecracker unmaps guest memory before exiting, and L1 issues a TLBI RIPAS2E1IS over all of the L2's memory, leaving its shadow MMU empty. Patch 6 parked 5 of the 6 MMUs, and the remaining L2 had an MMU from the initial pool which should never be parked. This is reclaim on range invalidation, not on L2 shutdown, as a range invalidation doesn't necessarily mean the nested VM is gone.

Known limitations:

- ALLE1 parking can't tell live idle nested VMs from dead ones. After an ALLE1, the remaining L2s found their MMUs parked, and each of their vcpus recycled an initial MMU that was empty but still valid, doing a whole-IPA unmap. Serialised on mmu_lock, these made L1 spike host CPU usage for a brief period. Skipping the unmap of an already empty victim would avoid this, but changes the recycle path and is left out of this RFC.

- On SIGTERM or SIGKILL, L1 issues no TLBI naming the L2's VMID, while it runs or as it is torn down. The leftover MMUs are then only parked on an ALLE1, which a Linux guest hypervisor only issues on its own VMID rollover.

For SIGTERM and SIGKILL, an alternative I prototyped is a periodic scan that parks grown MMUs no vcpu used since the previous scan. With a 10s period, it returned a dead nested VM's budget without taking MMUs from live idle ones.
However, the scan has to unmap what it parks: after dropping from 300 to 20 L2s, MMU mapping took some time and could delay the vcpus of a busy L1.

Is parking on ALLE1 and range invalidation good enough to start with, or would you prefer a periodic scan or another signal for nested VMs whose VMM is killed?

This series was developed with AI assistance (Anthropic Claude, through Cursor). It was used for design trade-offs, testing, and adversarial review of feedback received. I ran the tests on hardware, have reviewed every change, and take full DCO responsibility for the series.

A branch can be found here with the series applied:
https://github.com/NathanChenNVIDIA/linux/tree/rfc_alle1_nested_s2_mmu_pool_dynamic_budgeted_kvmarmnext

Nathan Chen (6):
KVM: arm64: nv: Allocate shadow S2 MMUs in blocks
KVM: arm64: nv: Pick the shadow S2 MMU to recycle with a clock
KVM: arm64: Add kvm_arm_vmid_nr_usable()
KVM: arm64: nv: Grow the shadow S2 MMU pool on demand
KVM: arm64: nv: Park grown MMUs on ALLE1 and reactivate them on demand
KVM: arm64: nv: Park shadow S2 MMUs emptied by a guest range
invalidation

 arch/arm64/include/asm/kvm_host.h   |  25 +-
 arch/arm64/include/asm/kvm_nested.h |   2 +
 arch/arm64/kvm/nested.c             | 350 ++++++++++++++++++++++++----
 arch/arm64/kvm/sys_regs.c           |   9 +
 arch/arm64/kvm/vmid.c               |  12 +
 5 files changed, 356 insertions(+), 42 deletions(-)

base-commit: 263a8db21f7321d74a9258d17151b295290b5dea

Signature · 1 line
2.43.0
#1 lore raw

RFC PATCH 1/6 KVM: arm64: nv: Allocate shadow S2 MMUs in blocks

Shadow S2 MMUs are allocated S2_MMU_PER_VCPU at a time at vcpu init, and kvm_destroy_nested() frees them by walking the pointer table with that stride, as it assumes every allocation has the same size.

Allocate them through a helper that adds a block of any size to the pool, and track the blocks on a list that kvm_destroy_nested() frees, so that the pool can later grow by blocks of a different size.

The ptdump files of the new MMUs are created once they are published in the table, rather than before.

No functional change otherwise.

---
 arch/arm64/include/asm/kvm_host.h |  4 +-
 arch/arm64/kvm/nested.c           | 84 ++++++++++++++++++++-----------
 2 files changed, 57 insertions(+), 31 deletions(-)
arch/arm64/include/asm/kvm_host.h +3 -1
index 97332ffcb130..ff5073b13338 100644
@@ -430,10 +430,12 @@ struct kvm_arch {
 
 	/*
 	 * Stage 2 paging state for VMs with nested S2 using a virtual
-	 * VMID.
+	 * VMID. The MMUs are allocated in blocks tracked on
+	 * nested_mmu_blocks.
 	 */
 	struct kvm_s2_mmu **nested_mmus;
 	size_t nested_mmus_size;
+	struct list_head nested_mmu_blocks;
 	int nested_mmus_next;
 
 	/*
arch/arm64/kvm/nested.c +54 -30

116 lines not on this page · raw message

Signature · 1 line
2.43.0
#2 lore raw

RFC PATCH 2/6 KVM: arm64: nv: Pick the shadow S2 MMU to recycle with a clock

In reply to Nathan Chen

On a lookup miss, get_s2_mmu_nested() recycles the first free MMU after the last one it picked. That MMU may hold the shadow stage-2 of a nested VM that is still running and about to be loaded again, while the pool has MMUs nobody has used in a long time, such as those of torn down nested VMs. Recycling a live MMU throws away its shadow tables and makes its nested VM fault them all back in.

Track use with an 'accessed' flag, set whenever a vcpu takes a reference on the MMU, and pick the victim with a clock (second chance):

- A free MMU that is invalid, or wasn't used since the search last went past it, is recycled straight away.

- Other free MMUs have their flag cleared as the search goes past them.

- If every free MMU was used since the last pass, the first one found is recycled, as before.

---
 arch/arm64/include/asm/kvm_host.h |  3 +++
 arch/arm64/kvm/nested.c           | 30 +++++++++++++++++++++++++-----
 2 files changed, 28 insertions(+), 5 deletions(-)
arch/arm64/include/asm/kvm_host.h +3 -0
index ff5073b13338..c7133999296f 100644
@@ -325,6 +325,9 @@ struct kvm_s2_mmu {
 	/* Index in the S2 MMU array, only valid for a shadow S2 */
 	u16	s2_mmu_idx;
 
+	/* Used since the victim search last went past it, under mmu_lock */
+	bool	accessed;
+
 	/*
 	 *  0: Nobody is currently using this, check vttbr for validity
 	 * >0: Somebody is actively using this.
arch/arm64/kvm/nested.c +25 -5
index 7d78efee5296..44dc6780fe6f 100644
@@ -842,7 +842,7 @@ static struct kvm_s2_mmu *get_s2_mmu_nested(struct kvm_vcpu *vcpu)
 {
 	struct kvm *kvm = vcpu->kvm;
 	struct kvm_s2_mmu *s2_mmu;
-	int i;
+	int i, victim = -1;
 
 	lockdep_assert_held_write(&vcpu->kvm->mmu_lock);
 
@@ -854,19 +854,38 @@ static struct kvm_s2_mmu *get_s2_mmu_nested(struct kvm_vcpu *vcpu)
 	 * Make sure we don't always search from the same point, or we
 	 * will always reuse a potentially active context, leaving
 	 * free contexts unused.
+	 *
+	 * Pick the victim with a clock: a free MMU that is invalid, or
+	 * hasn't been used since the search last went past it (such as
+	 * one left behind by a torn down guest), is recycled straight
+	 * away. Other free MMUs lose their accessed bit and get a second
+	 * chance. If every free MMU was used since the last pass, the
+	 * first one found is recycled.
 	 */
 	for (i = kvm->arch.nested_mmus_next;
 	     i < (kvm->arch.nested_mmus_size + kvm->arch.nested_mmus_next);
 	     i++) {
-		s2_mmu = kvm->arch.nested_mmus[i % kvm->arch.nested_mmus_size];
+		struct kvm_s2_mmu *mmu;
+
+		mmu = kvm->arch.nested_mmus[i % kvm->arch.nested_mmus_size];
+		if (atomic_read(&mmu->refcnt))
+			continue;
 
-		if (atomic_read(&s2_mmu->refcnt) == 0)
+		if (!kvm_s2_mmu_valid(mmu) || !mmu->accessed) {
+			victim = i;
 			break;
+		}
+
+		if (victim < 0)
+			victim = i;
+
+		mmu->accessed = false;
 	}
-	BUG_ON(atomic_read(&s2_mmu->refcnt)); /* We have struct MMUs to spare */
+	BUG_ON(victim < 0); /* We have struct MMUs to spare */
+	s2_mmu = kvm->arch.nested_mmus[victim % kvm->arch.nested_mmus_size];
 
 	/* Set the scene for the next search */
-	kvm->arch.nested_mmus_next = (i + 1) % kvm->arch.nested_mmus_size;
+	kvm->arch.nested_mmus_next = (victim + 1) % kvm->arch.nested_mmus_size;
 
 	/* Make sure we don't forget to do the laundry */
 	if (kvm_s2_mmu_valid(s2_mmu))
@@ -886,6 +905,7 @@ static struct kvm_s2_mmu *get_s2_mmu_nested(struct kvm_vcpu *vcpu)
 
 out:
 	atomic_inc(&s2_mmu->refcnt);
+	s2_mmu->accessed = true;
 
 	/*
 	 * Set the vCPU request to perform an unmap, even if the pending unmap
Signature · 1 line
2.43.0
#3 lore raw

RFC PATCH 3/6 KVM: arm64: Add kvm_arm_vmid_nr_usable()

In reply to Nathan Chen

Growing the shadow stage-2 MMU pool of nested VMs needs a host-wide limit derived from how many VMIDs the allocator can hand out within a generation, before a rollover.

That is fewer than NUM_USER_VMIDS: VMID #0 is never allocated, and a rollover can keep one VMID reserved per CPU for the VMID active on it. Add kvm_arm_vmid_nr_usable() to return that number, so that the limit is computed next to the allocator that sets it.

---
 arch/arm64/include/asm/kvm_host.h |  1 +
 arch/arm64/kvm/vmid.c             | 12 ++++++++++++
 2 files changed, 13 insertions(+)
arch/arm64/include/asm/kvm_host.h +1 -0
index c7133999296f..6ae86bc96600 100644
@@ -1431,6 +1431,7 @@ int __init kvm_arm_vmid_alloc_init(void);
 void __init kvm_arm_vmid_alloc_free(void);
 void kvm_arm_vmid_update(struct kvm_vmid *kvm_vmid);
 void kvm_arm_vmid_clear_active(void);
+unsigned int kvm_arm_vmid_nr_usable(void);
 
 static inline void kvm_arm_pvtime_vcpu_init(struct kvm_vcpu_arch *vcpu_arch)
 {
arch/arm64/kvm/vmid.c +12 -0
index 7fe8ba1a2851..cf044f434531 100644
@@ -129,6 +129,18 @@ static u64 new_vmid(struct kvm_vmid *kvm_vmid)
 	return vmid;
 }
 
+/*
+ * Number of VMIDs that can be handed out within a generation: VMID #0
+ * is never allocated, and a rollover can keep one VMID reserved per CPU.
+ */
+unsigned int kvm_arm_vmid_nr_usable(void)
+{
+	if (NUM_USER_VMIDS - 1 <= num_possible_cpus())
+		return 0;
+
+	return NUM_USER_VMIDS - 1 - num_possible_cpus();
+}
+
 /* Called from vCPU sched out with preemption disabled */
 void kvm_arm_vmid_clear_active(void)
 {
Signature · 1 line
2.43.0
#4 lore raw

RFC PATCH 4/6 KVM: arm64: nv: Grow the shadow S2 MMU pool on demand

In reply to Nathan Chen

A nested-capable VM gets online_vcpus * S2_MMU_PER_VCPU shadow stage-2 MMUs, with S2_MMU_PER_VCPU currently hardcoded to 2. When the guest hypervisor runs more than that number of concurrent nested VMs, get_s2_mmu_nested() recycles live MMUs on nearly every nested context switch, tearing down and rebuilding shadow stage-2 tables and issuing VMID TLB invalidations each time. This causes a sharp spike in host CPU usage.

Keep S2_MMU_PER_VCPU as the initial allocation, and grow the VM's pool when the guest's working set outgrows it. To keep growth from exhausting the VMID space, grown MMUs are counted across all VMs on the host and limited to half of what kvm_arm_vmid_nr_usable() returns.

If an allocation fails, growth stops for good, so that a VM at its memory limit doesn't retry on every recycle.

The nested_mmus pointer table is reallocated when full. Only the table moves, not the MMUs, so cached hw_mmu pointers stay valid.

---
 arch/arm64/include/asm/kvm_host.h |   8 +-
 arch/arm64/kvm/nested.c           | 153 +++++++++++++++++++++++++++---
 2 files changed, 148 insertions(+), 13 deletions(-)
arch/arm64/include/asm/kvm_host.h +7 -1
index 6ae86bc96600..9307b86285a5 100644
@@ -62,6 +62,7 @@
 #define KVM_REQ_MAP_L1_VNCR_EL2		KVM_ARCH_REQ(10)
 #define KVM_REQ_VGIC_PROCESS_UPDATE	KVM_ARCH_REQ(11)
 #define KVM_REQ_RELOAD_GICv5		KVM_ARCH_REQ(12)
+#define KVM_REQ_NESTED_S2_GROW		KVM_ARCH_REQ(13)
 
 /* Bit indices for kvm_arch::flags */
 enum {
@@ -434,12 +435,17 @@ struct kvm_arch {
 	/*
 	 * Stage 2 paging state for VMs with nested S2 using a virtual
 	 * VMID. The MMUs are allocated in blocks tracked on
-	 * nested_mmu_blocks.
+	 * nested_mmu_blocks, and the pool grows on demand.
 	 */
 	struct kvm_s2_mmu **nested_mmus;
 	size_t nested_mmus_size;
+	size_t nested_mmus_capacity;
 	struct list_head nested_mmu_blocks;
+	/* Grown MMUs, counted in the host budget, under mmu_lock */
+	unsigned int nested_mmus_grown;
 	int nested_mmus_next;
+	bool nested_mmus_grow;
+	bool nested_mmus_no_grow;
 
 	/*
 	 * Serializes guest s2 tracking trees access when the mmu_lock
arch/arm64/kvm/nested.c +141 -12

253 lines not on this page · raw message

Signature · 1 line
2.43.0
#5 lore raw
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] KVM: arm64: nv: premature pool growth in get_s2_mmu_nested() clock sweep - [Medium] KVM: arm64…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] KVM: arm64: nv: premature pool growth in get_s2_mmu_nested() clock sweep
- [Medium] KVM: arm64: nv: missing __GFP_NORETRY in init_nested_s2_mmu() on pool grow
- [Medium] KVM: arm64: nv: skipped baseline MMU allocation in kvm_vcpu_init_nested()
--

commit ed87347a8e1063feec4d2776535ef6edc4da64e2
Author: Nathan Chen <[email protected]>

KVM: arm64: nv: Grow the shadow S2 MMU pool on demand

This commit grows a nested-capable VM's shadow stage-2 MMU pool on demand when all free MMUs in the pool have been accessed since the last victim sweep, bounded by a per-VM limit and a host-wide VMID budget.

Quoted 4 lines
arch/arm64/kvm/nested.c +0 -0
index 44dc6780fe6fe..d530a37716be6 100644

[ ... ]

Quoted 29 lines
arch/arm64/kvm/nested.c +12 -3
@@ -91,16 +139,25 @@ static int init_nested_s2_mmu(struct kvm *kvm, struct kvm_s2_mmu *mmu)
 	return kvm_init_stage2_mmu(kvm, mmu, kvm_get_pa_bits(kvm));
 }
 
-/* Add a block of @nr shadow S2 MMUs to the pool */
-static int kvm_nested_add_s2_mmus(struct kvm *kvm, int nr)
+/*
+ * Add a block of @nr shadow S2 MMUs to the pool, reallocating the
+ * pointer table if it is full. Only the table moves, never the MMUs, so
+ * cached hw_mmu pointers stay valid. Runtime walkers of the table hold
+ * mmu_lock, and kvm_arch_flush_shadow_all() only runs once no vcpu can
+ * enter the guest, so it can't race with a grow.
+ */
+static int kvm_nested_add_s2_mmus(struct kvm *kvm, int nr, bool grow)
 {
+	gfp_t gfp = GFP_KERNEL_ACCOUNT | (grow ? __GFP_NORETRY : 0);
 	size_t size = kvm->arch.nested_mmus_size;
+	size_t cap = kvm->arch.nested_mmus_capacity;
+	struct kvm_s2_mmu **table = NULL;
 	struct nested_s2_mmu_block *blk;
 	int i, ret = 0;
 
 	lockdep_assert_held(&kvm->arch.config_lock);
 
-	blk = kvzalloc_flex(*blk, mmus, nr, GFP_KERNEL_ACCOUNT);
+	blk = kvzalloc_flex(*blk, mmus, nr, gfp);
 	if (!blk)
 		return -ENOMEM;
 

arch/arm64/kvm/nested.c

Quoted 4 lines
arch/arm64/kvm/nested.c +0 -0
 	for (i = 0; i < nr; i++) {
 		ret = init_nested_s2_mmu(kvm, &blk->mmus[i]);
 		if (ret)
 			goto out_free;

[Severity: Medium]
Should init_nested_s2_mmu() -> kvm_init_stage2_mmu() also receive @gfp so that its allocations carry __GFP_NORETRY when @grow is true?

kvzalloc_flex() and kvmalloc_objs() use __GFP_NORETRY on grow, but kvm_init_stage2_mmu() still allocates each struct kvm_pgtable and stage-2 PGD (up to 16 contiguous pages per MMU in kvm_host_zalloc_pages_exact()) with hardcoded GFP_KERNEL_ACCOUNT. When a VM near its memcg limit triggers kvm_nested_s2_grow(), the small block allocation can succeed while the PGD allocations enter full reclaim and trigger the memcg OOM killer instead of failing fast and setting nested_mmus_no_grow.

[ ... ]

arch/arm64/kvm/nested.c int kvm_vcpu_init_nested(struct kvm_vcpu *vcpu) · line 273

Quoted 6 lines
arch/arm64/kvm/nested.c +1 -1
@@ -155,7 +270,7 @@ int kvm_vcpu_init_nested(struct kvm_vcpu *vcpu)
 	num_mmus = atomic_read(&kvm->online_vcpus) * S2_MMU_PER_VCPU;
 
 	if (num_mmus > kvm->arch.nested_mmus_size) {
-		int ret = kvm_nested_add_s2_mmus(kvm, S2_MMU_PER_VCPU);
+		int ret = kvm_nested_add_s2_mmus(kvm, S2_MMU_PER_VCPU, false);

[Severity: Medium]
Should kvm_vcpu_init_nested() compare num_mmus against the baseline MMU count (nested_mmus_size - nested_mmus_grown) rather than nested_mmus_size?

If an already-initialized vcpu runs and triggers kvm_nested_s2_grow() before the remaining vcpus run KVM_ARM_VCPU_INIT, nested_mmus_size already includes nested_mmus_grown. Later kvm_vcpu_init_nested() calls then see num_mmus <= nested_mmus_size and skip allocating those vcpus' baseline S2_MMU_PER_VCPU MMUs, leaving the pool smaller by S2_MMU_PER_VCPU per late-initialized vcpu and keeping their baseline MMUs charged against the global nested_s2_mmus_grown budget.

[ ... ]

Quoted 28 lines
arch/arm64/kvm/nested.c +4 -2
@@ -842,6 +957,7 @@ static struct kvm_s2_mmu *get_s2_mmu_nested(struct kvm_vcpu *vcpu)
 {
 	struct kvm *kvm = vcpu->kvm;
 	struct kvm_s2_mmu *s2_mmu;
+	bool in_use = true;
 	int i, victim = -1;
 
 	lockdep_assert_held_write(&vcpu->kvm->mmu_lock);
@@ -859,8 +975,8 @@ static struct kvm_s2_mmu *get_s2_mmu_nested(struct kvm_vcpu *vcpu)
 	 * hasn't been used since the search last went past it (such as
 	 * one left behind by a torn down guest), is recycled straight
 	 * away. Other free MMUs lose their accessed bit and get a second
-	 * chance. If every free MMU was used since the last pass, the
-	 * first one found is recycled.
+	 * chance. If every free MMU was used since the last pass, they
+	 * are all in concurrent use and the pool is too small.
 	 */
 	for (i = kvm->arch.nested_mmus_next;
 	     i < (kvm->arch.nested_mmus_size + kvm->arch.nested_mmus_next);
@@ -873,6 +989,7 @@ static struct kvm_s2_mmu *get_s2_mmu_nested(struct kvm_vcpu *vcpu)
 
 		if (!kvm_s2_mmu_valid(mmu) || !mmu->accessed) {
 			victim = i;
+			in_use = false;
 			break;
 		}
 

arch/arm64/kvm/nested.c static struct kvm_s2_mmu *get_s2_mmu_nested(struct kvm_vcpu *vcpu) · line 1017

Quoted 10 lines
arch/arm64/kvm/nested.c +7 -0
@@ -891,6 +1008,14 @@ static struct kvm_s2_mmu *get_s2_mmu_nested(struct kvm_vcpu *vcpu)
 	if (kvm_s2_mmu_valid(s2_mmu))
 		s2_mmu->pending_unmap = true;
 
+	/* Every free MMU is in concurrent use: the pool is too small */
+	if (in_use && !READ_ONCE(kvm->arch.nested_mmus_no_grow) &&
+	    kvm->arch.nested_mmus_size < S2_MMU_MAX_PER_VM &&
+	    nested_s2_mmus_budget_left()) {
+		WRITE_ONCE(kvm->arch.nested_mmus_grow, true);
+		kvm_make_request(KVM_REQ_NESTED_S2_GROW, vcpu);
+	}

[Severity: Medium]
Does setting s2_mmu->accessed = true on a lookup miss cause get_s2_mmu_nested() to grow the pool even when old MMUs are never reused?

When the loop picks an invalid or unaccessed slot at nested_mmus_next, it breaks on the first iteration, advances nested_mmus_next to victim + 1 without sweeping other slots, and sets s2_mmu->accessed = true at the out label:

arch/arm64/kvm/nested.c:get_s2_mmu_nested() {
    ...
out:
	atomic_inc(&s2_mmu->refcnt);
	s2_mmu->accessed = true;
    ...
}

Each newly allocated MMU therefore sits right behind the clock hand with accessed == true before any lookup_s2_mmu() hit has occurred. After the initial 2 * online_vcpus misses fill the invalid slots, the very first recycle sees accessed == true on every slot and triggers KVM_REQ_NESTED_S2_GROW even if the guest only ran one nested VM at a time. After a grow resets nested_mmus_next = size, consuming the new invalid slots and stepping one by one through the unaccessed slots leaves at least size + online_vcpus - 1 slots with accessed == true from allocation misses alone, so a single active reference or lookup hit on the remaining slot triggers another grow cycle, inflating the pool toward S2_MMU_MAX_PER_VM (4096) and slowing linear scans over nested_mmus under mmu_lock.

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

RFC PATCH 5/6 KVM: arm64: nv: Park grown MMUs on ALLE1 and reactivate them on demand

In reply to Nathan Chen

Grown shadow S2 MMUs only return to the host budget when their VM is destroyed, so a guest hypervisor that once ran many nested VMs keeps holding the budget after they are gone.

Park the grown MMUs that are unreferenced and still empty after a guest TLBI ALLE1, returning them to the budget. A later grow reactivates parked MMUs before allocating new ones.

---
 arch/arm64/include/asm/kvm_host.h   |  13 +++-
 arch/arm64/include/asm/kvm_nested.h |   1 +
 arch/arm64/kvm/nested.c             | 113 +++++++++++++++++++++++++---
 arch/arm64/kvm/sys_regs.c           |   1 +
 4 files changed, 118 insertions(+), 10 deletions(-)
arch/arm64/include/asm/kvm_host.h +12 -1
index 9307b86285a5..c0b9cd60dbe6 100644
@@ -329,6 +329,15 @@ struct kvm_s2_mmu {
 	/* Used since the victim search last went past it, under mmu_lock */
 	bool	accessed;
 
+	/*
+	 * Added by growing the pool, and returned to the host budget by
+	 * parking it (invalid and unmapped) once unused. A parked MMU is
+	 * never picked by the victim search until a grow reactivates it.
+	 * Both under mmu_lock.
+	 */
+	bool	grown;
+	bool	parked;
+
 	/*
 	 *  0: Nobody is currently using this, check vttbr for validity
 	 * >0: Somebody is actively using this.
@@ -441,8 +450,10 @@ struct kvm_arch {
 	size_t nested_mmus_size;
 	size_t nested_mmus_capacity;
 	struct list_head nested_mmu_blocks;
-	/* Grown MMUs, counted in the host budget, under mmu_lock */
+	/* Grown MMUs not parked, counted in the host budget, under mmu_lock */
 	unsigned int nested_mmus_grown;
+	/* Parked MMUs, under mmu_lock */
+	unsigned int nested_mmus_parked;
 	int nested_mmus_next;
 	bool nested_mmus_grow;
 	bool nested_mmus_no_grow;
arch/arm64/include/asm/kvm_nested.h +1 -0
index 0f899addafa8..952853ab245a 100644
@@ -174,6 +174,7 @@ extern void kvm_nested_s2_wp(struct kvm *kvm);
 extern void kvm_nested_unmap_cipa_range(struct kvm *kvm, gpa_t cipa,
 					size_t unmap_size, bool may_block);
 extern void kvm_nested_s2_unmap(struct kvm *kvm, bool may_block);
+extern void kvm_nested_s2_shrink(struct kvm *kvm);
 extern void kvm_nested_s2_flush(struct kvm *kvm);
 
 unsigned long compute_tlb_inval_range(struct kvm_s2_mmu *mmu, u64 val);
arch/arm64/kvm/nested.c +104 -9

166 lines not on this page · raw message

arch/arm64/kvm/sys_regs.c +1 -0
index c7d91138a6d4..df81adf96259 100644
@@ -4047,6 +4047,7 @@ static bool handle_alle1is(struct kvm_vcpu *vcpu, struct sys_reg_params *p,
 	 * corresponding VMIDs.
 	 */
 	kvm_nested_s2_unmap(vcpu->kvm, true);
+	kvm_nested_s2_shrink(vcpu->kvm);
 
 	write_unlock(&vcpu->kvm->mmu_lock);
 
Signature · 1 line
2.43.0
#7 lore raw

Re: [RFC PATCH 5/6] KVM: arm64: nv: Park grown MMUs on ALLE1 and reactivate them on demand

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [High] KVM: arm64: nv: kvm_vcpu_init_nested() counts grown and parked MMUs as base - [Medium] KVM: arm64…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [High] KVM: arm64: nv: kvm_vcpu_init_nested() counts grown and parked MMUs as base
- [Medium] KVM: arm64: nv: nested_mmus_no_grow blocks reactivating parked MMUs
- [Medium] KVM: arm64: nv: kvm_nested_add_s2_mmus() clobbers reactivated clock hand
- [Medium] KVM: arm64: nv: stale guest_s2_mappings left behind by kvm_nested_s2_park()
--

commit 9c4a135b779b29bdcbc1e942f3c2d4d37849957b
Author: Nathan Chen <[email protected]>

KVM: arm64: nv: Park grown MMUs on ALLE1 and reactivate them on demand

This commit parks unreferenced and empty grown shadow stage-2 MMUs on a guest TLBI ALLE1 to return them to the host budget, and reactivates parked MMUs before allocating new ones when growing the pool.

Quoted 40 lines
arch/arm64/kvm/nested.c +32 -0
index d530a37716be6..9251f3fd48405 100644
@@ -96,6 +96,55 @@ struct nested_s2_mmu_block {
 	struct kvm_s2_mmu	mmus[];
 };
 
+static int s2_mmu_nonempty_walker(const struct kvm_pgtable_visit_ctx *ctx,
+				  enum kvm_pgtable_walk_flags visit)
+{
+	return ctx->old ? -EEXIST : 0;
+}
+
+/* Only looks at the stage-2 root unless it finds an entry in use */
+static bool kvm_s2_mmu_empty(struct kvm_s2_mmu *mmu)
+{
+	struct kvm_pgtable_walker walker = {
+		.cb	= s2_mmu_nonempty_walker,
+		.flags	= KVM_PGTABLE_WALK_LEAF | KVM_PGTABLE_WALK_TABLE_PRE,
+	};
+
+	return !kvm_pgtable_walk(mmu->pgt, 0, kvm_phys_size(mmu), &walker);
+}
+
+/*
+ * Park @mmu if it is grown, unreferenced and empty, returning it to the
+ * budget. It is invalidated, so no lookup can hand it out, and skipped
+ * by the victim search. It keeps its slot, its struct and its stage-2
+ * root until the VM is destroyed, so walkers of the table that drop
+ * mmu_lock never see it go away. Parking always leaves S2_MMU_PER_VCPU
+ * unparked MMUs per vcpu, so the victim search always has a candidate.
+ */
+static bool kvm_nested_s2_park(struct kvm *kvm, struct kvm_s2_mmu *mmu)
+{
+	unsigned int keep = atomic_read(&kvm->online_vcpus) * S2_MMU_PER_VCPU;
+
+	lockdep_assert_held_write(&kvm->mmu_lock);
+
+	if (kvm->arch.nested_mmus_size - kvm->arch.nested_mmus_parked <= keep)

arch/arm64/kvm/nested.c struct nested_s2_mmu_block { · line 140

Quoted 10 lines
arch/arm64/kvm/nested.c +10 -0
+		return false;
+
+	if (!mmu->grown || mmu->parked || atomic_read(&mmu->refcnt) ||
+	    !mmu->pgt || !kvm_s2_mmu_empty(mmu))
+		return false;
+
+	if (kvm_s2_mmu_valid(mmu))
+		kvm_init_nested_s2_mmu(mmu);
+	mmu->parked = true;
+	mmu->pending_unmap = false;

[Severity: Medium]
Can kvm_nested_s2_park() leave stale entries in mmu->guest_s2_mappings when parking an MMU?

kvm_s2_mmu_empty() only checks mmu->pgt, which can be empty while mmu->guest_s2_mappings still holds nodes (for example, if a guest stage-2 TLBI unmapped a subrange of a block mapping: stage2_unmap_walker() breaks the entire block PTE in mmu->pgt, while kvm_remove_guest_s2_mappings() keeps nodes larger than the unmap range).

Because kvm_nested_s2_park() marks the MMU invalid via kvm_init_nested_s2_mmu() and clears mmu->pending_unmap, a later reactivation and reuse in get_s2_mmu_nested() will not request KVM_REQ_NESTED_S2_UNMAP, leaving the old tracking nodes attached to the new nested context until a full unmap or VM teardown. Calling kvm_remove_guest_s2_mappings(mmu, 0, kvm_phys_size(mmu)) before parking would clear any remaining tracking entries.

[ ... ]

Quoted 29 lines
arch/arm64/kvm/nested.c +17 -2
@@ -216,14 +266,15 @@ static int kvm_nested_add_s2_mmus(struct kvm *kvm, int nr, bool grow)
 static void kvm_nested_s2_grow(struct kvm *kvm)
 {
-	int nr, add;
+	int nr, add = 0, reactivated = 0, first = -1;
 
 	guard(mutex)(&kvm->arch.config_lock);
 
@@ -238,15 +289,57 @@ static void kvm_nested_s2_grow(struct kvm *kvm)
 		return;
 	}
 
-	add = min_t(int, nr, S2_MMU_MAX_PER_VM - kvm->arch.nested_mmus_size);
+	scoped_guard(write_lock, &kvm->mmu_lock) {
+		for (int i = 0; i < kvm->arch.nested_mmus_size; i++) {
+			struct kvm_s2_mmu *mmu = kvm->arch.nested_mmus[i];
+
+			if (reactivated == nr)
+				break;
+			if (!mmu->parked)
+				continue;
+
+			mmu->parked = false;
+			reactivated++;
+			if (first < 0)
+				first = i;
+		}
+
+		if (reactivated) {

arch/arm64/kvm/nested.c static void kvm_nested_s2_grow(struct kvm *kvm) · line 317

Quoted 10 lines
arch/arm64/kvm/nested.c +9 -0
+			kvm->arch.nested_mmus_grown += reactivated;
+			kvm->arch.nested_mmus_parked -= reactivated;
+			kvm->arch.nested_mmus_next = first;
+		}
+
+		add = min_t(int, nr - reactivated,
+			    S2_MMU_MAX_PER_VM - kvm->arch.nested_mmus_size);
+	}
+
 	if (add && kvm_nested_add_s2_mmus(kvm, add, true)) {

[Severity: Medium]
When kvm_nested_s2_grow() both reactivates parked MMUs (0 < reactivated < nr) and allocates new ones (add > 0), does kvm_nested_add_s2_mmus() clobber kvm->arch.nested_mmus_next = first?

kvm_nested_add_s2_mmus() unconditionally sets kvm->arch.nested_mmus_next to the old nested_mmus_size. After get_s2_mmu_nested() hands out the new MMUs at the tail, the clock hand wraps to index 0 and recycles live MMUs in [0, first) whose accessed bits were just cleared by the pass that triggered the grow, before reaching the empty reactivated MMUs at [first, size).

[ ... ]

arch/arm64/kvm/nested.c static struct kvm_s2_mmu *get_s2_mmu_nested(struct kvm_vcpu *vcpu) · line 1082

Quoted 7 lines
arch/arm64/kvm/nested.c +1 -1
@@ -984,7 +1078,7 @@ static struct kvm_s2_mmu *get_s2_mmu_nested(struct kvm_vcpu *vcpu)
 		struct kvm_s2_mmu *mmu;
 
 		mmu = kvm->arch.nested_mmus[i % kvm->arch.nested_mmus_size];
-		if (atomic_read(&mmu->refcnt))
+		if (atomic_read(&mmu->refcnt) || mmu->parked)
 			continue;

[Severity: High]
Can skipping parked MMUs here trigger BUG_ON(victim < 0) in get_s2_mmu_nested() when vCPUs are initialized after the pool has grown?

arch/arm64/kvm/nested.c:kvm_vcpu_init_nested() {
    ...
	num_mmus = atomic_read(&kvm->online_vcpus) * S2_MMU_PER_VCPU;

	if (num_mmus > kvm->arch.nested_mmus_size) {
		int ret = kvm_nested_add_s2_mmus(kvm, S2_MMU_PER_VCPU, false);
    ...
}

kvm_vcpu_init_nested() compares num_mmus against nested_mmus_size, which includes grown and parked MMUs rather than just the base non-grown pool (nested_mmus_size - nested_mmus_grown - nested_mmus_parked).

If vCPU 0 is created, initialized (nested_mmus_size == 2), and runs in nested mode to grow the pool (for example by 4 MMUs to nested_mmus_size == 6), and then executes TLBI ALLE1, kvm_nested_s2_park() parks all 4 grown MMUs (keep == 2, leaving 2 unparked MMUs). If userspace then creates and initializes vCPU 1 and vCPU 2 (allowed before VGIC init or when !irqchip_in_kernel(kvm)), num_mmus > kvm->arch.nested_mmus_size is false, so no base MMUs are added and the 4 grown MMUs remain parked. The VM now has 3 online vCPUs and only 2 unparked MMUs; when 2 vCPUs hold references to those 2 MMUs and the 3rd calls get_s2_mmu_nested(), every entry is either referenced or parked and the host hits BUG_ON(victim < 0).

Even when all vCPUs are created upfront, if vCPU 0 grows the pool before the remaining vCPUs call KVM_ARM_VCPU_INIT, kvm_vcpu_init_nested() skips allocating their base MMUs, and kvm_nested_s2_park() permanently retains grown MMUs against the host budget to satisfy keep.

arch/arm64/kvm/nested.c static struct kvm_s2_mmu *get_s2_mmu_nested(struct kvm_vcpu *vcpu) · line 1111

Quoted 10 lines
arch/arm64/kvm/nested.c +2 -1
@@ -1010,7 +1104,8 @@ static struct kvm_s2_mmu *get_s2_mmu_nested(struct kvm_vcpu *vcpu)
 
 	/* Every free MMU is in concurrent use: the pool is too small */
 	if (in_use && !READ_ONCE(kvm->arch.nested_mmus_no_grow) &&
-	    kvm->arch.nested_mmus_size < S2_MMU_MAX_PER_VM &&
+	    (kvm->arch.nested_mmus_size < S2_MMU_MAX_PER_VM ||
+	     kvm->arch.nested_mmus_parked) &&
 	    nested_s2_mmus_budget_left()) {
 		WRITE_ONCE(kvm->arch.nested_mmus_grow, true);
 		kvm_make_request(KVM_REQ_NESTED_S2_GROW, vcpu);

[Severity: Medium]
Does nested_mmus_no_grow prevent reactivating already-allocated parked MMUs?

If a grow allocation in kvm_nested_add_s2_mmus() fails after the VM has already accumulated grown MMUs, kvm_nested_s2_grow() sets nested_mmus_no_grow = true. Once a later guest TLBI parks those earlier grown MMUs, checking !READ_ONCE(kvm->arch.nested_mmus_no_grow) here and at the start of kvm_nested_s2_grow() blocks reactivating them even though reactivation needs no memory allocation, leaving their memory and stage-2 PGDs allocated but unusable until VM teardown.

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

RFC PATCH 6/6 KVM: arm64: nv: Park shadow S2 MMUs emptied by a guest range invalidation

In reply to Nathan Chen

If a guest TLBI RIPAS2E1IS or VMALLS12E1IS leaves a grown, unreferenced MMU empty, park it there rather than leave it valid until a recycle unmaps the whole IPA space of an already empty MMU.

---
 arch/arm64/include/asm/kvm_nested.h | 1 +
 arch/arm64/kvm/nested.c             | 2 +-
 arch/arm64/kvm/sys_regs.c           | 8 ++++++++
 3 files changed, 10 insertions(+), 1 deletion(-)
arch/arm64/include/asm/kvm_nested.h +1 -0
index 952853ab245a..164e42376296 100644
@@ -175,6 +175,7 @@ extern void kvm_nested_unmap_cipa_range(struct kvm *kvm, gpa_t cipa,
 					size_t unmap_size, bool may_block);
 extern void kvm_nested_s2_unmap(struct kvm *kvm, bool may_block);
 extern void kvm_nested_s2_shrink(struct kvm *kvm);
+extern bool kvm_nested_s2_park(struct kvm *kvm, struct kvm_s2_mmu *mmu);
 extern void kvm_nested_s2_flush(struct kvm *kvm);
 
 unsigned long compute_tlb_inval_range(struct kvm_s2_mmu *mmu, u64 val);
arch/arm64/kvm/nested.c +1 -1
index 9251f3fd4840..e9a2eaef9eda 100644
@@ -121,7 +121,7 @@ static bool kvm_s2_mmu_empty(struct kvm_s2_mmu *mmu)
  * mmu_lock never see it go away. Parking always leaves S2_MMU_PER_VCPU
  * unparked MMUs per vcpu, so the victim search always has a candidate.
  */
-static bool kvm_nested_s2_park(struct kvm *kvm, struct kvm_s2_mmu *mmu)
+bool kvm_nested_s2_park(struct kvm *kvm, struct kvm_s2_mmu *mmu)
 {
 	unsigned int keep = atomic_read(&kvm->online_vcpus) * S2_MMU_PER_VCPU;
 
arch/arm64/kvm/sys_regs.c +8 -0
index df81adf96259..99dcd2549b08 100644
@@ -4123,6 +4123,14 @@ static void s2_mmu_unmap_range(struct kvm_s2_mmu *mmu,
 	 * the TLBI.
 	 */
 	kvm_stage2_unmap_range(mmu, info->range.start, info->range.size, true);
+
+	/*
+	 * The guest hypervisor may have unmapped everything this MMU held,
+	 * e.g. all memory of a nested VM being torn down. If it is grown and
+	 * now empty, return it to the budget rather than leave it for a
+	 * recycle to unmap again.
+	 */
+	kvm_nested_s2_park(kvm_s2_mmu_to_kvm(mmu), mmu);
 }
 
 static bool handle_vmalls12e1is(struct kvm_vcpu *vcpu, struct sys_reg_params *p,
Signature · 1 line
2.43.0
#9 lore raw

Re: [RFC PATCH 6/6] KVM: arm64: nv: Park shadow S2 MMUs emptied by a guest range invalidation

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] KVM: arm64: nv: stale guest_s2_mappings left by s2_mmu_unmap_range() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] KVM: arm64: nv: stale guest_s2_mappings left by s2_mmu_unmap_range()
--

commit f58fa33431acb8934a7b0dc10a9031b3bb889b94
Author: Nathan Chen <[email protected]>

KVM: arm64: nv: Park shadow S2 MMUs emptied by a guest range invalidation

This commit exports kvm_nested_s2_park() and calls it from s2_mmu_unmap_range() so that grown, unreferenced shadow stage-2 MMUs emptied by a guest TLBI range invalidation are immediately parked.

Quoted 7 lines
arch/arm64/kvm/sys_regs.c +0 -0
index df81adf962599..99dcd2549b08a 100644
@@ -4123,6 +4123,14 @@ static void s2_mmu_unmap_range(struct kvm_s2_mmu *mmu,
 	 * the TLBI.
 	 */

arch/arm64/kvm/sys_regs.c static void s2_mmu_unmap_range(struct kvm_s2_mmu *mmu, · line 4134

Quoted 10 lines
arch/arm64/kvm/sys_regs.c +8 -0
 	kvm_stage2_unmap_range(mmu, info->range.start, info->range.size, true);
+
+	/*
+	 * The guest hypervisor may have unmapped everything this MMU held,
+	 * e.g. all memory of a nested VM being torn down. If it is grown and
+	 * now empty, return it to the budget rather than leave it for a
+	 * recycle to unmap again.
+	 */
+	kvm_nested_s2_park(kvm_s2_mmu_to_kvm(mmu), mmu);
 }

[Severity: High]
Can calling kvm_nested_s2_park() after a partial range invalidation (TLBI RIPAS2E1IS) leave stale kvm_guest_s2_mapping entries in mmu->guest_s2_mappings and kvm->arch.mmu.guest_s2_mappings?

When a guest TLBI RIPAS2E1IS unmaps a range smaller than a recorded block mapping (or unmaps a block across multiple sub-block ranges), stage2_unmap_walker() unmaps the entire overlapping block PTE and can leave mmu->pgt empty, while kvm_remove_guest_s2_mappings() only frees mappings completely enclosed within that single unmap range:

arch/arm64/kvm/nested.c:kvm_remove_guest_s2_mappings() {
    ...
		nested_start = s2_mapping_to_nested_start(mapping);
		if (nipa <= nested_start && nipa_end >= mapping->nested.last) {
			interval_tree_remove(&mapping->nested, &mmu->guest_s2_mappings);
			interval_tree_remove(&mapping->canonical,
					     &kvm->arch.mmu.guest_s2_mappings);
			kfree(mapping);
		}
    ...
}

Because kvm_nested_s2_park() only checks kvm_s2_mmu_empty(mmu) (which walks mmu->pgt), it marks the MMU invalid via kvm_init_nested_s2_mmu() and clears pending_unmap without draining mmu->guest_s2_mappings. Later full-VMID invalidations skip the invalidated MMU, and reactivating it in get_s2_mmu_nested() sees !kvm_s2_mmu_valid(s2_mmu) and skips setting pending_unmap. The leftover mappings leak across park/grow cycles and let kvm_nested_unmap_cipa_range() unmap unrelated nested IPAs after the MMU is reused for a new nested context.

Should kvm_nested_s2_park() call kvm_remove_guest_s2_mappings(mmu, 0, kvm_phys_size(mmu)) before parking the MMU?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
maintainer
#10 lore raw
In reply to Nathan Chen

Hi Nathan,

Quoted 8 lines · Nathan Chen

A nested-capable VM gets 2 shadow stage-2 MMUs per vcpu. Once the guest hypervisor runs more nested VMs than that, nearly every nested context switch recycles a live MMU and spikes host CPU usage.

This series lets KVM grow the shadow MMU pool on demand when the pool is too small, up to a host-wide VMID budget. It also parks grown MMUs on a guest TLBI ALLE1 and when a guest range invalidation leaves them empty, in order to return unused capacity.

Thanks for taking a look at the problem. There's no argument that we need to do something, the existing MMU allocation policy was good enough for doing nested development and would get replaced eventually.

With that said, I feel rather strongly that we should not invest further in the MMU array because it is quite inflexible. On top of that we need an actual eviction policy that selects cold MMUs as victims instead of the current round robin approach. I don't think you need to do anything special on the invalidation side with a good eviction policy.

I think this is what we need:

- A VM-wide hashtable for storing stage-2 MMUs, keyed off of {VTCR_EL2, VTTBR_EL2, HCR_EL2.VM} to align with how we handle TLB match at stage-2. The hashtable can be dimensioned based on a configurable VM limit for shadow stage-2 MMUs.

- A state tracking mechanism for victim selection. An LRU list seems like a reasonable starting point.

- RCU replacement of the evicted MMU. I need to think about it a bit more but you should be able to reuse the PGD in the new MMU context as well since we know that no vCPU holds a reference on the victim. That ought to be the goal anyway.

That should allow us to dynamically allocate MMUs while also improving upon the current behavior for constrained MMU allocations.

Thanks,
Oliver