Skip to contentSkip to conversation

KVM: arm64: Introduce pKVM hypervisor heap allocator

PATCH Applied Vincent Donnefort 3 participants 25 messages Oct 1 – Oct 2

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

v6 cover KVM: arm64: Introduce pKVM hypervisor heap allocator

pKVM historically lacked a dynamic memory allocator: all hypervisor-side VM and VCPU structures had to be sized on the host, allocated as contiguous pages and donated to the hypervisor.

This design tightly coupled the hypervisor's memory footprint to host-side constraints, complicated memory reclaim, and severely restricted VM scalability.

This patch series introduces a dynamically-mapped custom heap allocator (hyp_allocator) to the pKVM hypervisor. The initial users are the pkvm_hyp_vm and pkvm_hyp_vcpu structs, and the hypervisor tracing metadata.

In the near future, this heap allocator is expected to be leveraged to support SVE in protected VMs and in the distant future, it will also support dynamic device assignment.

By moving to a hypervisor-managed dynamic allocator, we also allow deduplicating the donation/reclaim path of EL2-private structures.

The main building blocks for this series are:

1. pkvm_hyp_req:
----------------
When the hypervisor heap allocator goes out of memory (-ENOMEM), it suspends the hypercall, embeds a PKVM_HYP_REQ_HYP_ALLOC top-up request into the SMCCC HVC return registers, and exits back to the host.

This building block will also be useful for the future huge-mapping support in protected guests, allowing EL2 to raise requests such as block splitting back to the host.

2. hyp_allocator:
----------------
This heap allocator manages a reserved VA space range, dynamically mapping and unmapping physical pages on-demand to minimise the pKVM hypervisor footprint. As memory is reclaimed and relinquished to the host, unmapped holes are introduced within the VA space. To prevent orphan mapped regions, neighboring unused chunks cannot be merged if they are separated by an unmapped region.

The allocator chunk metadata is stored directly into the VA space range. To minimize metadata overhead, chunks only link to each other via a relative 32-bit offset.

A simple hardening of the metadata is added via a simple 32-bit hash.

3. shrinker:
------------
As the heap allocator isn't reclaimed actively on VM or tracing teardown, a shrinker is added to allow the host to reclaim unused memory from the hypervisor when the host is under heavy memory pressure.

Changelog
---------

v6:

- Rebased on kvm-arm64/hyp-type-checking-7.4
- make __pkvm_hyp_alloc_selftest pre-deprivilege only (Sashiko)
- Remove __hyp_private_va_start for __io_map_next to ease merge.
- Fix sparse NULL pointer warnings in hyp_allocator_map() and hyp_allocator_create_chunk()

v5:

- Remove unreachable !prev checks in hyp_allocator_destroy_chunk() (Fuad)
- Add kerneldoc to pkvm_call_hyp_req() (Fuad)
- Avoid duplicate handle___pkvm_hyp_alloc_selftest() definitions when !CONFIG_NVHE_EL2_DEBUG
- Chunk pkvm_hyp_reclaim() with cond_resched() to avoid blocking in EL2
- Allow shrinker to scan across all runtime topup IDs
- Reclaim chunks before draining allocator->mc in hyp_allocator_reclaim() (Fuad)
- Make is_ttbr1_addr() check in __kern_hyp_va() conditional to pKVM (Fuad)
- Rename pkvm_memcache to stage2_mc
- Rebased on 7.3-rc1

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

- Add kerneldoc to pkvm_remove_mappings
- Allow pkvm_private_va_range_pa() to work with block-level mappings (Sashiko)
- Add rollback and harden pkvm_map_private_va_range input (Sashiko)
- Add missing mc count into reclaimable memory
- Differentiate -ENOMEM from hyp_alloc in errno_to_smccc() (Sashiko)
- Collect Fuad's Tested-by

v3: https://lore.kernel.org/all/[email protected]/

- Remove unsafe WARN_ON(hyp_spin_is_locked(&pkvm_pgd_lock)) check in hyp_allocator_alloc() (Sashiko)
- Modify MIN_ALLOC_SIZE to 16-bytes to comply with FPSIMD alignment requirements (Sashiko)
- Allow hyp topup/reclaim HVCs pre-deprivilege
- Add enum symbols to pkvm_hyp_req_handle event (Fuad)
- Various clarification in commit descriptions (Fuad)
- Restore unmap_donated_memory() for PGD on error path (Fuad)
- Renamed __hyp_allocator_map -> pkvm_map_private_va_range (Fuad)
- Collected Fuad's Reviewed-by tags
- Rebased on 7.2-rc4

v2: https://lore.kernel.org/all/[email protected]/

- Rebased series on 7.2-rc2.
- Use scope-based hyp_spinlock.
- Fix best_missing/best_data_size priority in hyp_allocator_find_efficient_chunk() (Sashiko)
- Fix missing free_hyp_memcache() in pkvm_hyp_topup() (Sashiko)
- Fix unused selftest_init() warning when !CONFIG_NVHE_EL2_DEBUG (Sashiko)
- Fix missing shrinker_free() in teardown_hyp_mode() (Sashiko)

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

Vincent Donnefort (18):
KVM: arm64: Add pkvm_private_va_range_pa
KVM: arm64: Add pkvm_remove_mappings
KVM: arm64: Add pkvm_map_private_va_range
KVM: arm64: Add a heap allocator for the pKVM hyp
KVM: arm64: Allow kvm_hyp_memcache usage outside of stage-2
KVM: arm64: Add pkvm_hyp_req infrastructure
KVM: arm64: Add PKVM_HYP_REQ_HYP_ALLOC request
KVM: arm64: Add reclaim interface for the pKVM heap alloc
KVM: arm64: Add selftests for the pKVM heap allocator
KVM: arm64: Add a shrinker for pKVM
KVM: arm64: Filter out non-kernel addresses in kern_hyp_va
KVM: arm64: Move hyp_vm refcount into the structure
KVM: arm64: Alloc pkvm_hyp_vm using pKVM heap allocator
KVM: arm64: Alloc pkvm_hyp_vcpu using pKVM heap allocator
KVM: arm64: Rename vCPU pkvm_memcache to stage2_mc
KVM: arm64: Reject hyp trace descriptors with fewer CPUs than
hyp_nr_cpus
KVM: arm64: Reject hyp trace descriptors with fewer than 3 pages
KVM: arm64: Alloc simple_buffer_page using pKVM hyp allocator

 arch/arm64/include/asm/kvm_asm.h           |    4 +
 arch/arm64/include/asm/kvm_hcall.h         |   19 +-
 arch/arm64/include/asm/kvm_host.h          |   18 +-
 arch/arm64/include/asm/kvm_mmu.h           |    3 +
 arch/arm64/include/asm/kvm_pkvm.h          |  111 ++
 arch/arm64/kvm/arm.c                       |    4 +-
 arch/arm64/kvm/hyp/hyp-constants.c         |    2 -
 arch/arm64/kvm/hyp/include/nvhe/alloc.h    |   28 +
 arch/arm64/kvm/hyp/include/nvhe/mm.h       |    3 +
 arch/arm64/kvm/hyp/include/nvhe/pkvm.h     |   19 +-
 arch/arm64/kvm/hyp/include/nvhe/spinlock.h |    4 +
 arch/arm64/kvm/hyp/nvhe/Makefile           |    2 +-
 arch/arm64/kvm/hyp/nvhe/alloc.c            | 1211 ++++++++++++++++++++
 arch/arm64/kvm/hyp/nvhe/hyp-main.c         |  129 ++-
 arch/arm64/kvm/hyp/nvhe/mem_protect.c      |   10 +-
 arch/arm64/kvm/hyp/nvhe/mm.c               |   95 +-
 arch/arm64/kvm/hyp/nvhe/pkvm.c             |   79 +-
 arch/arm64/kvm/hyp/nvhe/setup.c            |    6 +
 arch/arm64/kvm/hyp/nvhe/trace.c            |   70 +-
 arch/arm64/kvm/hyp_trace.c                 |   15 +-
 arch/arm64/kvm/mmu.c                       |    6 +-
 arch/arm64/kvm/pkvm.c                      |  200 +++-
 arch/arm64/kvm/trace_pkvm.h                |   45 +
 23 files changed, 1931 insertions(+), 152 deletions(-)
 create mode 100644 arch/arm64/kvm/hyp/include/nvhe/alloc.h
 create mode 100644 arch/arm64/kvm/hyp/nvhe/alloc.c
 create mode 100644 arch/arm64/kvm/trace_pkvm.h

base-commit: 8bd0e6812a1be71d50620f00445940ded0df897c

Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#1 lore raw

PATCH v6 1/18 KVM: arm64: Add pkvm_private_va_range_pa

Mappings in the pKVM private range are not identity mapped, making the standard __hyp_pa() unsuitable for translating these addresses.

Introduce pkvm_private_va_range_pa() to resolve physical addresses for this range by walking the hypervisor page-table. This will be useful for the upcoming pKVM heap allocator.

---
 arch/arm64/kvm/hyp/include/nvhe/mm.h       |  1 +
 arch/arm64/kvm/hyp/include/nvhe/spinlock.h |  4 ++++
 arch/arm64/kvm/hyp/nvhe/mm.c               | 18 ++++++++++++++++++
 3 files changed, 23 insertions(+)
arch/arm64/kvm/hyp/include/nvhe/mm.h +1 -0
index 6e83ce35c2f2..85f1e3c711d9 100644
@@ -30,5 +30,6 @@ int __pkvm_create_private_mapping(phys_addr_t phys, size_t size,
 				  unsigned long *haddr);
 int pkvm_create_stack(phys_addr_t phys, unsigned long *haddr);
 int pkvm_alloc_private_va_range(size_t size, unsigned long *haddr);
+phys_addr_t pkvm_private_va_range_pa(void *va);
 
 #endif /* __KVM_HYP_MM_H */
arch/arm64/kvm/hyp/include/nvhe/spinlock.h +4 -0
index 7c7ea8c55405..260e14d6d200 100644
@@ -17,6 +17,8 @@
 #include <asm/lse.h>
 #include <asm/rwonce.h>
 
+#include <linux/cleanup.h>
+
 typedef union hyp_spinlock {
 	u32	__val;
 	struct {
@@ -122,4 +124,6 @@ static inline void hyp_assert_lock_held(hyp_spinlock_t *lock)
 static inline void hyp_assert_lock_held(hyp_spinlock_t *lock) { }
 #endif
 
+DEFINE_LOCK_GUARD_1(hyp_spinlock, hyp_spinlock_t, hyp_spin_lock(_T->lock),
+		    hyp_spin_unlock(_T->lock))
 #endif /* __ARM64_KVM_NVHE_SPINLOCK_H__ */
arch/arm64/kvm/hyp/nvhe/mm.c +18 -0
index 3b0bee496bff..755630c0d15e 100644
@@ -90,6 +90,24 @@ int pkvm_alloc_private_va_range(size_t size, unsigned long *haddr)
 	return ret;
 }
 
+/**
+ * pkvm_private_va_range_pa - Translate a private VA to a physical address.
+ * @va:		The private virtual address to translate.
+ *
+ * Return: The physical address corresponding to @va.
+ */
+phys_addr_t pkvm_private_va_range_pa(void *va)
+{
+	kvm_pte_t pte;
+	s8 level;
+
+	guard(hyp_spinlock)(&pkvm_pgd_lock);
+	WARN_ON(kvm_pgtable_get_leaf(&pkvm_pgtable, (u64)va, &pte, &level));
+	WARN_ON(!kvm_pte_valid(pte));
+
+	return kvm_pte_to_phys(pte) + ((u64)va & (kvm_granule_size(level) - 1));
+}
+
 int __pkvm_create_private_mapping(phys_addr_t phys, size_t size,
 				  enum kvm_pgtable_prot prot,
 				  unsigned long *haddr)
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#2 lore raw

PATCH v6 2/18 KVM: arm64: Add pkvm_remove_mappings

In reply to Vincent Donnefort

Add the counterpart to pkvm_create_mappings(), allowing previously mapped ranges to be removed. This will be useful for the upcoming pKVM heap allocator to manage its private mappings.

---
 arch/arm64/kvm/hyp/include/nvhe/mm.h |  1 +
 arch/arm64/kvm/hyp/nvhe/mm.c         | 18 ++++++++++++++++++
 2 files changed, 19 insertions(+)
arch/arm64/kvm/hyp/include/nvhe/mm.h +1 -0
index 85f1e3c711d9..00cadd13ee5d 100644
@@ -25,6 +25,7 @@ int hyp_back_vmemmap(phys_addr_t back);
 int pkvm_cpu_set_vector(enum arm64_hyp_spectre_vector slot);
 int pkvm_create_mappings(void *from, void *to, enum kvm_pgtable_prot prot);
 int pkvm_create_mappings_locked(void *from, void *to, enum kvm_pgtable_prot prot);
+void pkvm_remove_mappings(void *from, void *to);
 int __pkvm_create_private_mapping(phys_addr_t phys, size_t size,
 				  enum kvm_pgtable_prot prot,
 				  unsigned long *haddr);
arch/arm64/kvm/hyp/nvhe/mm.c +18 -0
index 755630c0d15e..9ab7f613fa36 100644
@@ -164,6 +164,24 @@ int pkvm_create_mappings(void *from, void *to, enum kvm_pgtable_prot prot)
 	return ret;
 }
 
+/**
+ * pkvm_remove_mappings - Remove mappings from the hypervisor page-table
+ * @from:	The starting virtual address of the range to remove
+ * @to:		The ending virtual address of the range to remove
+ */
+void pkvm_remove_mappings(void *from, void *to)
+{
+	u64 size;
+
+	WARN_ON(from > to);
+	to = PTR_ALIGN(to, PAGE_SIZE);
+	from = PTR_ALIGN_DOWN(from, PAGE_SIZE);
+	size = (u64)to - (u64)from;
+
+	guard(hyp_spinlock)(&pkvm_pgd_lock);
+	WARN_ON(kvm_pgtable_hyp_unmap(&pkvm_pgtable, (u64)from, size) != size);
+}
+
 int hyp_back_vmemmap(phys_addr_t back)
 {
 	unsigned long i, start, size, end = 0;
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#3 lore raw

PATCH v6 3/18 KVM: arm64: Add pkvm_map_private_va_range

In reply to Vincent Donnefort

In preparation for the pKVM heap allocator, introduce pkvm_map_private_va_range() to map a physical range into the pKVM private range.

---
 arch/arm64/kvm/hyp/include/nvhe/mm.h |  1 +
 arch/arm64/kvm/hyp/nvhe/mm.c         | 59 ++++++++++++++++++++++++----
 2 files changed, 52 insertions(+), 8 deletions(-)
arch/arm64/kvm/hyp/include/nvhe/mm.h +1 -0
index 00cadd13ee5d..ea97ea49820e 100644
@@ -31,6 +31,7 @@ int __pkvm_create_private_mapping(phys_addr_t phys, size_t size,
 				  unsigned long *haddr);
 int pkvm_create_stack(phys_addr_t phys, unsigned long *haddr);
 int pkvm_alloc_private_va_range(size_t size, unsigned long *haddr);
+int pkvm_map_private_va_range(void *haddr, phys_addr_t phys, size_t size);
 phys_addr_t pkvm_private_va_range_pa(void *va);
 
 #endif /* __KVM_HYP_MM_H */
arch/arm64/kvm/hyp/nvhe/mm.c +51 -8

130 lines not on this page · raw message

Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#4 lore raw

Re: [PATCH v6 03/18] KVM: arm64: Add pkvm_map_private_va_range

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] mm: page table memory leak on error path in pkvm_map_private_va_range() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] mm: page table memory leak on error path in pkvm_map_private_va_range() --

commit a41a8ab9fe9c147efcc9aefa4890f827e8b117a6
Author: Vincent Donnefort <[email protected]>

KVM: arm64: Add pkvm_map_private_va_range

In preparation for the pKVM heap allocator, introduce pkvm_map_private_va_range() to map a physical range into the pKVM private range.

Quoted 4 lines
arch/arm64/kvm/hyp/nvhe/mm.c +0 -0
index 9ab7f613fa360..4a22fb74182be 100644

[ ... ]

Quoted 25 lines
arch/arm64/kvm/hyp/nvhe/mm.c +21 -0
@@ -90,6 +91,41 @@ int pkvm_alloc_private_va_range(size_t size, unsigned long *haddr)
 	return ret;
 }
 
+/**
+ * pkvm_map_private_va_range() - Map a physical range into the private VA range
+ * @haddr:	The virtual address in the private range.
+ * @phys:	The physical address to map.
+ * @size:	The size of the range to map.
+ *
+ * The hypervisor VA @haddr must have been first allocated with
+ * pkvm_alloc_private_va_range(). The created mapping can later be removed
+ * with pkvm_remove_mappings().
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int pkvm_map_private_va_range(void *haddr, phys_addr_t phys, size_t size)
+{
+	unsigned long addr = (unsigned long)haddr;
+	int ret;
+
+	if (!PAGE_ALIGNED(addr | phys | size))
+		return -EINVAL;
+
+	guard(hyp_spinlock)(&pkvm_pgd_lock);

arch/arm64/kvm/hyp/nvhe/mm.c int pkvm_alloc_private_va_range(size_t size, unsigned long *haddr) · line 124

Quoted 10 lines
arch/arm64/kvm/hyp/nvhe/mm.c +10 -0
+
+	if (addr < __io_map_base || addr >= __io_map_next)
+		return -EINVAL;
+
+	if (size > __io_map_next - addr)
+		return -EINVAL;
+
+	ret = kvm_pgtable_hyp_map(&pkvm_pgtable, addr, size, phys, PAGE_HYP);
+	if (ret)
+		kvm_pgtable_hyp_unmap(&pkvm_pgtable, addr, size);

[Severity: High]
Does this error path leak hypervisor page table memory?

If kvm_pgtable_hyp_map() fails midway (for instance, due to an out-of-memory condition), pkvm_map_private_va_range() calls kvm_pgtable_hyp_unmap() to roll back the partial mapping. The unmap walker will then encounter an invalid PTE in the unmapped portion:

arch/arm64/kvm/hyp/pgtable.c:hyp_unmap_walker() {
    ...
    if (!kvm_pte_valid(ctx->old))
        return -EINVAL;
    ...
}

This causes the walker to abort. When the walk aborts, __kvm_pgtable_visit() skips the KVM_PGTABLE_WALK_TABLE_POST callbacks for all parent tables:

arch/arm64/kvm/hyp/pgtable.c:__kvm_pgtable_visit() {
    ...
    if (!kvm_pgtable_walk_continue(data->walker, ret))
        goto out;

    if (ctx.flags & KVM_PGTABLE_WALK_TABLE_POST)
        ret = kvm_pgtable_visitor_cb(data, &ctx, ...);
    ...
}

Because the post-table callback is skipped, any intermediate page tables allocated during the failed map are not freed. Since the hypervisor uses a fixed memory pool, if an untrusted host can push the allocator to its limit to trigger this error path, this leak could permanently deplete EL2 memory and prevent further VM creation.

Quoted 3 lines
arch/arm64/kvm/hyp/nvhe/mm.c +3 -0
+
+	return ret;
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#5 lore raw

PATCH v6 4/18 KVM: arm64: Add a heap allocator for the pKVM hyp

In reply to Vincent Donnefort

Currently, memory used by the hypervisor comes from donations that are embedded within HVCs. e.g. __pkvm_init_vm()'s hyp_vm.

This is cumbersome: the host needs to know the size of those struct, the memory must be page-aligned and physically contiguous which may be difficult to satisfy when host memory is highly fragmented.

Create a heap allocator to manage VA-contiguous memory. This allocator grows upward, recycles unused chunks of memory and provides a simple API to allocate and free:

hyp_alloc(size), hyp_free(addr)

This heap allocator also manages the underlying physical memory, allowing the host to top up the allocator's pool and reclaim memory.

hyp_alloc_topup(), hyp_alloc_reclaim().

Pages remain mapped in the allocator's VA-space as long as they are not reclaimed.

When the allocator runs out of memory, hyp_alloc() fails and hyp_alloc_errno() returns -ENOMEM to signal that a top-up is required.

Additionally, harden the allocator with a fast hash of the chunks meta-data. This intends to detect accidental corruptions and makes the allocator slightly more robust to potential attacks.

---
 arch/arm64/kvm/hyp/include/nvhe/alloc.h |   17 +
 arch/arm64/kvm/hyp/nvhe/Makefile        |    2 +-
 arch/arm64/kvm/hyp/nvhe/alloc.c         | 1027 +++++++++++++++++++++++
 arch/arm64/kvm/hyp/nvhe/setup.c         |    6 +
 4 files changed, 1051 insertions(+), 1 deletion(-)
 create mode 100644 arch/arm64/kvm/hyp/include/nvhe/alloc.h
 create mode 100644 arch/arm64/kvm/hyp/nvhe/alloc.c
arch/arm64/kvm/hyp/include/nvhe/alloc.h new file +17 -0
new file mode 100644
index 000000000000..8f87a63f8946
@@ -0,0 +1,17 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef __KVM_NVHE_ALLOC__
+#define __KVM_NVHE_ALLOC__
+#include <linux/types.h>
+
+#include <asm/kvm_host.h>
+
+void *hyp_alloc(size_t size);
+int hyp_alloc_errno(void);
+u32 hyp_alloc_topup_needed(void);
+void hyp_free(void *addr);
+
+int hyp_alloc_init(size_t size);
+int hyp_alloc_topup(struct kvm_hyp_memcache *host_mc);
+unsigned long hyp_alloc_reclaimable(void);
+void hyp_alloc_reclaim(struct kvm_hyp_memcache *host_mc, unsigned long target);
+#endif
arch/arm64/kvm/hyp/nvhe/Makefile +1 -1
index ccc1fe839409..ee0abb2e6af5 100644
@@ -23,7 +23,7 @@ lib-objs := $(addprefix ../../../lib/, $(lib-objs))
 CFLAGS_switch.nvhe.o += -Wno-override-init
 
 hyp-obj-y := timer-sr.o sysreg-sr.o debug-sr.o switch.o tlb.o hyp-init.o host.o \
-	 hyp-main.o hyp-smp.o psci-relay.o early_alloc.o page_alloc.o \
+	 hyp-main.o hyp-smp.o psci-relay.o alloc.o early_alloc.o page_alloc.o \
 	 cache.o setup.o mm.o mem_protect.o sys_regs.o pkvm.o stacktrace.o ffa.o
 hyp-obj-y += ../vgic-v3-sr.o ../aarch32.o ../vgic-v2-cpuif-proxy.o ../entry.o \
 	 ../hyp-entry.o ../exception.o ../pgtable.o ../vgic-v5-sr.o
arch/arm64/kvm/hyp/nvhe/alloc.c new file +1027 -0

1,027 lines not on this page · raw message

arch/arm64/kvm/hyp/nvhe/setup.c +6 -0
index 75b00c323310..9fd3dcde3557 100644
@@ -10,6 +10,7 @@
 #include <asm/kvm_pgtable.h>
 #include <asm/kvm_pkvm.h>
 
+#include <nvhe/alloc.h>
 #include <nvhe/early_alloc.h>
 #include <nvhe/ffa.h>
 #include <nvhe/gfp.h>
@@ -363,6 +364,11 @@ int __pkvm_init(phys_addr_t phys, unsigned long size, unsigned long *per_cpu_bas
 	if (ret)
 		return ret;
 
+	/* Arbitrary size, unmapped at boot and only consume VA-space */
+	ret = hyp_alloc_init(SZ_128M);
+	if (ret)
+		return ret;
+
 	update_nvhe_init_params();
 
 	/* Jump in the idmap page to switch to the new page-tables */
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#6 lore raw

PATCH v6 5/18 KVM: arm64: Allow kvm_hyp_memcache usage outside of stage-2

In reply to Vincent Donnefort

Although currently limited to guest stage-2 page-table allocations, struct kvm_hyp_memcache is a useful primitive for passing a list of discontiguous pages between host and hypervisor.

Introduce init_hyp_memcache() to initialise a generic hyp memcache, and init_hyp_stage2_memcache() for stage-2 specific memcaches. The generic initialiser will be used to top up the upcoming pKVM heap allocator.

Note that the generic kvm_hyp_memcache does not account for the allocated memory. This is expected: donations to the heap allocator are shared and recycled, they cannot be accounted for a specific VM.

---
 arch/arm64/include/asm/kvm_host.h | 13 +++++++++++++
 arch/arm64/kvm/mmu.c              |  4 +++-
 arch/arm64/kvm/pkvm.c             |  4 ++--
 3 files changed, 18 insertions(+), 3 deletions(-)
arch/arm64/include/asm/kvm_host.h +13 -0
index fc1a82777ed4..64cd6233b439 100644
@@ -92,9 +92,22 @@ struct kvm_hyp_memcache {
 	struct pkvm_mapping *mapping; /* only used from EL1 */
 
 #define	HYP_MEMCACHE_ACCOUNT_STAGE2	BIT(1)
+#define	HYP_MEMCACHE_ACCOUNT_KMEMCG	BIT(2)
 	unsigned long flags;
 };
 
+static inline void init_hyp_memcache(struct kvm_hyp_memcache *mc)
+{
+	memset(mc, 0, sizeof(*mc));
+	mc->mapping = ZERO_SIZE_PTR; /* Prevent allocation, solely useful for stage2 memcache */
+}
+
+static inline void init_hyp_stage2_memcache(struct kvm_hyp_memcache *mc)
+{
+	memset(mc, 0, sizeof(*mc));
+	mc->flags = HYP_MEMCACHE_ACCOUNT_STAGE2 | HYP_MEMCACHE_ACCOUNT_KMEMCG;
+}
+
 static inline void push_hyp_memcache(struct kvm_hyp_memcache *mc,
 				     phys_addr_t *p,
 				     phys_addr_t (*to_pa)(void *virt))
arch/arm64/kvm/mmu.c +3 -1
index 9ba86450fe4a..3163502cc7d2 100644
@@ -1160,8 +1160,10 @@ static void *hyp_mc_alloc_fn(void *mc)
 {
 	struct kvm_hyp_memcache *memcache = mc;
 	void *addr;
+	gfp_t gfp;
 
-	addr = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
+	gfp = memcache->flags & HYP_MEMCACHE_ACCOUNT_KMEMCG ? GFP_KERNEL_ACCOUNT : GFP_KERNEL;
+	addr = (void *)__get_free_page(gfp);
 	if (addr && memcache->flags & HYP_MEMCACHE_ACCOUNT_STAGE2)
 		kvm_account_pgtable_pages(addr, 1);
 
arch/arm64/kvm/pkvm.c +2 -2
index 8e4c6e4bec12..e5200731a45b 100644
@@ -111,7 +111,7 @@ static int __pkvm_create_hyp_vcpu(struct kvm_vcpu *vcpu)
 	void *hyp_vcpu;
 	int ret;
 
-	vcpu->arch.pkvm_memcache.flags |= HYP_MEMCACHE_ACCOUNT_STAGE2;
+	init_hyp_stage2_memcache(&vcpu->arch.pkvm_memcache);
 
 	hyp_vcpu = alloc_pages_exact(hyp_vcpu_sz, GFP_KERNEL_ACCOUNT);
 	if (!hyp_vcpu)
@@ -172,7 +172,7 @@ static int __pkvm_create_hyp_vm(struct kvm *kvm)
 		goto free_vm;
 
 	kvm->arch.pkvm.is_created = true;
-	kvm->arch.pkvm.stage2_teardown_mc.flags |= HYP_MEMCACHE_ACCOUNT_STAGE2;
+	init_hyp_stage2_memcache(&kvm->arch.pkvm.stage2_teardown_mc);
 	kvm_account_pgtable_pages(pgd, pgd_sz / PAGE_SIZE);
 
 	return 0;
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#7 lore raw

PATCH v6 6/18 KVM: arm64: Add pkvm_hyp_req infrastructure

In reply to Vincent Donnefort

Introduce a struct pkvm_hyp_req to enable the pKVM hypervisor to request resources from the host.

Provide serialisation helpers to transport these requests via SMCCC registers (starting from a2):

pkvm_hyp_req_to_smccc() to encode into the SMCCC args. smccc_to_pkvm_hyp_req() to decode them.

When the hypervisor raises a request, the host must handle it and retry the HVC. To automate this sequence, introduce the pkvm_call_hyp_req() macro. This intercepts pending requests, invokes the handler and retries the HVC.

Additionally, introduce a trace event to track the handling of these requests.

---
 arch/arm64/include/asm/kvm_pkvm.h | 103 ++++++++++++++++++++++++++++++
 arch/arm64/kvm/pkvm.c             |  25 ++++++++
 arch/arm64/kvm/trace_pkvm.h       |  43 +++++++++++++
 3 files changed, 171 insertions(+)
 create mode 100644 arch/arm64/kvm/trace_pkvm.h
arch/arm64/include/asm/kvm_pkvm.h +103 -0
index beea00e693a0..19bddf261c82 100644
@@ -205,6 +205,109 @@ struct pkvm_mapping {
 	u64 __subtree_last;	/* Internal member for interval tree */
 };
 
+enum pkvm_hyp_req_type {
+	PKVM_HYP_NO_REQ = 0,
+	__PKVM_HYP_REQ_TYPE_MAX,
+};
+
+#define PKVM_HYP_REQ_SMCCC_ARG_SIZE_MAX \
+	(sizeof(struct arm_smccc_res) - offsetof(struct arm_smccc_res, a2) - 1)
+
+struct pkvm_hyp_req {
+	u8 type;
+	union {
+		struct {
+			u32	nr_pages;
+		} mem;
+		struct {
+			/* Helper for SMCCC encoding/decoding */
+			u8	args[PKVM_HYP_REQ_SMCCC_ARG_SIZE_MAX];
+		} args;
+	};
+};
+
+static inline size_t pkvm_hyp_req_arg_size(u8 type)
+{
+	switch (type) {
+	case PKVM_HYP_NO_REQ:
+		return 0;
+	default:
+		WARN_ON(1);
+	}
+
+	return 0;
+}
+
+/* Encode the pending pkvm_hyp_req type into the SMCCC args */
+static inline void
+pkvm_hyp_req_to_smccc(struct kvm_cpu_context *host_ctxt, struct pkvm_hyp_req *req)
+{
+	u8 *dst, type = req->type;
+	size_t size;
+
+	if (type == PKVM_HYP_NO_REQ || type >= __PKVM_HYP_REQ_TYPE_MAX) {
+		host_ctxt->regs.regs[2] = 0;
+		return;
+	}
+
+	size = pkvm_hyp_req_arg_size(type);
+	if (WARN_ON(size > PKVM_HYP_REQ_SMCCC_ARG_SIZE_MAX))
+		return;
+
+	dst = (u8 *)&host_ctxt->regs.regs[2];
+	*dst = type;
+
+	memcpy(dst + 1, &req->args, size);
+}
+
+/* Return true if a pkvm_hyp_req has been decoded from the SMCCC args */
+static inline bool smccc_to_pkvm_hyp_req(struct pkvm_hyp_req *req, struct arm_smccc_res *res)
+{
+	u8 *src = (u8 *)res + offsetof(struct arm_smccc_res, a2);
+	u8 type = *src;
+
+	if (type == PKVM_HYP_NO_REQ || type >= __PKVM_HYP_REQ_TYPE_MAX)
+		return false;
+
+	req->type = type;
+	memcpy(&req->args, src + 1, pkvm_hyp_req_arg_size(type));
+
+	return true;
+}
+
+int __pkvm_handle_smccc_req(struct arm_smccc_res *res);
+
+/**
+ * pkvm_call_hyp_req() - Issue an HVC that can return hypervisor requests
+ * @f: Hypervisor function symbol to call.
+ * @...: Arguments to pass to the hypercall.
+ *
+ * Re-issue an HVC and process any pending hypervisor request until completion
+ * or error.
+ *
+ * Only use this helper for HVCs whose hypervisor handlers format their return
+ * registers with pkvm_hyp_req_to_smccc().
+ *
+ * Return: Result of the hypercall or a negative error if the hyp request
+ * handling failed.
+ */
+#define pkvm_call_hyp_req(f, ...)								\
+({												\
+	struct arm_smccc_res __res;								\
+	int __ret;										\
+	do {											\
+		__ret = -1;									\
+		arm_smccc_1_1_hvc(KVM_HOST_SMCCC_FUNC(f), ##__VA_ARGS__, &__res);		\
+		if (WARN_ON(__res.a0 != SMCCC_RET_SUCCESS))					\
+			break;									\
+		__ret = __res.a1;								\
+		if (!__ret)									\
+			break;									\
+		__ret = __pkvm_handle_smccc_req(&__res);					\
+	} while (!__ret);									\
+	__ret;											\
+})
+
 int pkvm_pgtable_stage2_init(struct kvm_pgtable *pgt, struct kvm_s2_mmu *mmu,
 			     struct kvm_pgtable_mm_ops *mm_ops);
 void pkvm_pgtable_stage2_destroy_range(struct kvm_pgtable *pgt,
arch/arm64/kvm/pkvm.c +25 -0
index e5200731a45b..11d9e2f70cd8 100644
@@ -16,6 +16,9 @@
 
 #include "hyp_constants.h"
 
+#define CREATE_TRACE_POINTS
+#include "trace_pkvm.h"
+
 DEFINE_STATIC_KEY_FALSE(kvm_protected_mode_initialized);
 
 static struct memblock_region *hyp_memory = kvm_nvhe_sym(hyp_memory);
@@ -594,3 +597,25 @@ bool pkvm_force_reclaim_guest_page(phys_addr_t phys)
 
 	return !ret || ret == -EAGAIN;
 }
+
+static int pkvm_handle_hyp_req(struct pkvm_hyp_req *req)
+{
+	int ret = -EINVAL;
+
+	switch (req->type) {
+	}
+
+	trace_kvm_handle_pkvm_hyp_req(req, ret);
+
+	return ret;
+}
+
+int __pkvm_handle_smccc_req(struct arm_smccc_res *res)
+{
+	struct pkvm_hyp_req req;
+
+	if (smccc_to_pkvm_hyp_req(&req, res))
+		return pkvm_handle_hyp_req(&req);
+
+	return res->a1;
+}
arch/arm64/kvm/trace_pkvm.h new file +43 -0

43 lines not on this page · raw message

Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#8 lore raw

PATCH v6 7/18 KVM: arm64: Add PKVM_HYP_REQ_HYP_ALLOC request

In reply to Vincent Donnefort

Introduce a new pkvm_hyp_request type asking the host to top up the pKVM heap allocator.

---
 arch/arm64/include/asm/kvm_asm.h   |  1 +
 arch/arm64/include/asm/kvm_hcall.h |  6 ++++++
 arch/arm64/include/asm/kvm_pkvm.h  |  5 +++++
 arch/arm64/kvm/hyp/nvhe/hyp-main.c | 26 ++++++++++++++++++++++++++
 arch/arm64/kvm/pkvm.c              | 30 ++++++++++++++++++++++++++++++
 arch/arm64/kvm/trace_pkvm.h        |  6 ++++--
 6 files changed, 72 insertions(+), 2 deletions(-)
arch/arm64/include/asm/kvm_asm.h +1 -0
index e5b92ac09e69..de59e89318fa 100644
@@ -89,6 +89,7 @@ enum __kvm_host_smccc_func {
 	__KVM_HOST_SMCCC_FUNC___vgic_v3_restore_vmcr_aprs,
 	__KVM_HOST_SMCCC_FUNC___vgic_v5_save_apr,
 	__KVM_HOST_SMCCC_FUNC___vgic_v5_restore_vmcr_apr,
+	__KVM_HOST_SMCCC_FUNC___pkvm_hyp_topup,
 
 	MARKER(__KVM_HOST_SMCCC_FUNC_PKVM_ONLY),
 
arch/arm64/include/asm/kvm_hcall.h +6 -0
index 9f06af58a4b0..6d6f12400e94 100644
@@ -22,6 +22,10 @@
 
 typedef u16 pkvm_handle_t;
 
+enum pkvm_topup_id {
+	PKVM_TOPUP_HYP_ALLOC,
+};
+
 struct kvm;
 struct kvm_s2_mmu;
 struct kvm_vcpu;
@@ -193,6 +197,8 @@ DECLARE_KVM_HOST_HCALL(void, __vgic_v5_save_apr,
 	struct vgic_v5_cpu_if __kern *, cpu_if)
 DECLARE_KVM_HOST_HCALL(void, __vgic_v5_restore_vmcr_apr,
 	struct vgic_v5_cpu_if __kern *, cpu_if)
+DECLARE_KVM_HOST_HCALL(int, __pkvm_hyp_topup,
+	enum pkvm_topup_id, id, phys_addr_t, head, unsigned long, nr_pages)
 
 /* Hypercalls that are available only when pKVM has finalised. */
 DECLARE_KVM_HOST_HCALL(int, __pkvm_host_share_hyp,
arch/arm64/include/asm/kvm_pkvm.h +5 -0
index 19bddf261c82..c338178d6bb2 100644
@@ -207,6 +207,7 @@ struct pkvm_mapping {
 
 enum pkvm_hyp_req_type {
 	PKVM_HYP_NO_REQ = 0,
+	PKVM_HYP_REQ_HYP_ALLOC,
 	__PKVM_HYP_REQ_TYPE_MAX,
 };
 
@@ -228,9 +229,13 @@ struct pkvm_hyp_req {
 
 static inline size_t pkvm_hyp_req_arg_size(u8 type)
 {
+	struct pkvm_hyp_req *req;
+
 	switch (type) {
 	case PKVM_HYP_NO_REQ:
 		return 0;
+	case PKVM_HYP_REQ_HYP_ALLOC:
+		return sizeof(req->mem);
 	default:
 		WARN_ON(1);
 	}
arch/arm64/kvm/hyp/nvhe/hyp-main.c +26 -0
index 91e74a1a334f..2b89eb274482 100644
@@ -17,6 +17,7 @@
 #include <asm/kvm_hypevents.h>
 #include <asm/kvm_mmu.h>
 
+#include <nvhe/alloc.h>
 #include <nvhe/ffa.h>
 #include <nvhe/mem_protect.h>
 #include <nvhe/mm.h>
@@ -799,6 +800,30 @@ DEFINE_KVM_HOST_HCALL(int, __pkvm_finalize_teardown_vm,
 	return __pkvm_finalize_teardown_vm(handle);
 }
 
+DEFINE_KVM_HOST_HCALL(int, __pkvm_hyp_topup,
+	enum pkvm_topup_id, id, phys_addr_t, head, unsigned long, nr_pages)
+{
+	struct kvm_cpu_context *host_ctxt = host_data_ptr(host_ctxt);
+	struct kvm_hyp_memcache host_mc = {
+		.head = head,
+		.nr_pages = nr_pages,
+	};
+	int ret;
+
+	switch (id) {
+	case PKVM_TOPUP_HYP_ALLOC:
+		ret = hyp_alloc_topup(&host_mc);
+		break;
+	default:
+		ret = -EINVAL;
+	}
+
+	cpu_reg(host_ctxt, 2) = host_mc.head;
+	cpu_reg(host_ctxt, 3) = host_mc.nr_pages;
+
+	return ret;
+}
+
 DEFINE_KVM_HOST_HCALL(int, __tracing_load,
 	void __kern *, desc_hva, size_t, desc_size)
 {
@@ -893,6 +918,7 @@ static const hcall_t host_hcall[] = {
 	HANDLE_FUNC(__vgic_v3_restore_vmcr_aprs),
 	HANDLE_FUNC(__vgic_v5_save_apr),
 	HANDLE_FUNC(__vgic_v5_restore_vmcr_apr),
+	HANDLE_FUNC(__pkvm_hyp_topup),
 
 	HANDLE_FUNC(__pkvm_host_share_hyp),
 	HANDLE_FUNC(__pkvm_host_unshare_hyp),
arch/arm64/kvm/pkvm.c +30 -0
index 11d9e2f70cd8..9cd23978481c 100644
@@ -88,6 +88,33 @@ void __init kvm_hyp_reserve(void)
 		 hyp_mem_base);
 }
 
+static int pkvm_hyp_topup(enum pkvm_topup_id id, unsigned long nr_pages)
+{
+	struct kvm_hyp_memcache mc;
+	struct arm_smccc_res res;
+	int ret;
+
+	init_hyp_memcache(&mc);
+	ret = topup_hyp_memcache(&mc, nr_pages);
+	if (ret)
+		goto err;
+
+	arm_smccc_1_1_hvc(KVM_HOST_SMCCC_FUNC(__pkvm_hyp_topup), id, mc.head,
+			  mc.nr_pages, &res);
+	if (WARN_ON_ONCE(res.a0 != SMCCC_RET_SUCCESS)) {
+		ret = -EINVAL;
+		goto err;
+	}
+
+	ret = res.a1;
+	mc.head = res.a2;
+	mc.nr_pages = res.a3;
+
+err:
+	free_hyp_memcache(&mc);
+	return ret;
+}
+
 static void __pkvm_destroy_hyp_vm(struct kvm *kvm)
 {
 	if (pkvm_hyp_vm_is_created(kvm)) {
@@ -603,6 +630,9 @@ static int pkvm_handle_hyp_req(struct pkvm_hyp_req *req)
 	int ret = -EINVAL;
 
 	switch (req->type) {
+	case PKVM_HYP_REQ_HYP_ALLOC:
+		ret = pkvm_hyp_topup(PKVM_TOPUP_HYP_ALLOC, req->mem.nr_pages);
+		break;
 	}
 
 	trace_kvm_handle_pkvm_hyp_req(req, ret);
arch/arm64/kvm/trace_pkvm.h +4 -2
index 3966c111e3ad..493225e3282d 100644
@@ -9,9 +9,11 @@
 #define TRACE_SYSTEM kvm
 
 TRACE_DEFINE_ENUM(PKVM_HYP_NO_REQ);
+TRACE_DEFINE_ENUM(PKVM_HYP_REQ_HYP_ALLOC);
 
-#define PKVM_HYP_REQ_TYPES \
-	{ PKVM_HYP_NO_REQ, "NO_REQ" }
+#define PKVM_HYP_REQ_TYPES				\
+	{ PKVM_HYP_NO_REQ, "NO_REQ" },			\
+	{ PKVM_HYP_REQ_HYP_ALLOC, "HYP_ALLOC" }
 
 TRACE_EVENT(kvm_handle_pkvm_hyp_req,
 	TP_PROTO(struct pkvm_hyp_req *req, int ret),
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#9 lore raw

PATCH v6 8/18 KVM: arm64: Add reclaim interface for the pKVM heap alloc

In reply to Vincent Donnefort

Introduce a host interface to reclaim donated memory from the pKVM heap allocator back to the host.

It specifically provides two helpers that will make it easier to create a shrinker for pKVM:

pkvm_hyp_reclaimable()
pkvm_hyp_relaim()

---
 arch/arm64/include/asm/kvm_asm.h   |  2 ++
 arch/arm64/include/asm/kvm_hcall.h |  4 +++
 arch/arm64/kvm/hyp/nvhe/hyp-main.c | 34 +++++++++++++++++++++++
 arch/arm64/kvm/pkvm.c              | 44 ++++++++++++++++++++++++++++++
 4 files changed, 84 insertions(+)
arch/arm64/include/asm/kvm_asm.h +2 -0
index de59e89318fa..fc3c52b03154 100644
@@ -90,6 +90,8 @@ enum __kvm_host_smccc_func {
 	__KVM_HOST_SMCCC_FUNC___vgic_v5_save_apr,
 	__KVM_HOST_SMCCC_FUNC___vgic_v5_restore_vmcr_apr,
 	__KVM_HOST_SMCCC_FUNC___pkvm_hyp_topup,
+	__KVM_HOST_SMCCC_FUNC___pkvm_hyp_reclaim,
+	__KVM_HOST_SMCCC_FUNC___pkvm_hyp_reclaimable,
 
 	MARKER(__KVM_HOST_SMCCC_FUNC_PKVM_ONLY),
 
arch/arm64/include/asm/kvm_hcall.h +4 -0
index 6d6f12400e94..bce6eb8b20e0 100644
@@ -199,6 +199,10 @@ DECLARE_KVM_HOST_HCALL(void, __vgic_v5_restore_vmcr_apr,
 	struct vgic_v5_cpu_if __kern *, cpu_if)
 DECLARE_KVM_HOST_HCALL(int, __pkvm_hyp_topup,
 	enum pkvm_topup_id, id, phys_addr_t, head, unsigned long, nr_pages)
+DECLARE_KVM_HOST_HCALL(int, __pkvm_hyp_reclaim,
+	enum pkvm_topup_id, id, unsigned long, target)
+DECLARE_KVM_HOST_HCALL(ulong, __pkvm_hyp_reclaimable,
+	enum pkvm_topup_id, id)
 
 /* Hypercalls that are available only when pKVM has finalised. */
 DECLARE_KVM_HOST_HCALL(int, __pkvm_host_share_hyp,
arch/arm64/kvm/hyp/nvhe/hyp-main.c +34 -0
index 2b89eb274482..fdc39f064718 100644
@@ -824,6 +824,38 @@ DEFINE_KVM_HOST_HCALL(int, __pkvm_hyp_topup,
 	return ret;
 }
 
+DEFINE_KVM_HOST_HCALL(int, __pkvm_hyp_reclaim,
+	enum pkvm_topup_id, id, unsigned long, target)
+{
+	struct kvm_cpu_context *host_ctxt = host_data_ptr(host_ctxt);
+	struct kvm_hyp_memcache host_mc = {};
+	int ret = 0;
+
+	switch (id) {
+	case PKVM_TOPUP_HYP_ALLOC:
+		hyp_alloc_reclaim(&host_mc, target);
+		break;
+	default:
+		ret = -EINVAL;
+	}
+
+	cpu_reg(host_ctxt, 2) = host_mc.head;
+	cpu_reg(host_ctxt, 3) = host_mc.nr_pages;
+
+	return ret;
+}
+
+DEFINE_KVM_HOST_HCALL(ulong, __pkvm_hyp_reclaimable,
+	enum pkvm_topup_id, id)
+{
+	switch (id) {
+	case PKVM_TOPUP_HYP_ALLOC:
+		return hyp_alloc_reclaimable();
+	default:
+		return 0;
+	}
+}
+
 DEFINE_KVM_HOST_HCALL(int, __tracing_load,
 	void __kern *, desc_hva, size_t, desc_size)
 {
@@ -919,6 +951,8 @@ static const hcall_t host_hcall[] = {
 	HANDLE_FUNC(__vgic_v5_save_apr),
 	HANDLE_FUNC(__vgic_v5_restore_vmcr_apr),
 	HANDLE_FUNC(__pkvm_hyp_topup),
+	HANDLE_FUNC(__pkvm_hyp_reclaim),
+	HANDLE_FUNC(__pkvm_hyp_reclaimable),
 
 	HANDLE_FUNC(__pkvm_host_share_hyp),
 	HANDLE_FUNC(__pkvm_host_unshare_hyp),
arch/arm64/kvm/pkvm.c +44 -0

50 lines not on this page · raw message

Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#10 lore raw

PATCH v6 9/18 KVM: arm64: Add selftests for the pKVM heap allocator

In reply to Vincent Donnefort

Introduce a comprehensive runtime selftest for the pKVM hypervisor heap allocator, executed during init when CONFIG_NVHE_EL2_DEBUG is enabled.

The selftest runs entirely at EL2 and exercises allocator's core mechanisms:

* over-sized allocations
* basic allocation and alignment
* chunk recycling, splitting, merging
* memory reclaiming
* memory topup

---
 arch/arm64/include/asm/kvm_asm.h        |   1 +
 arch/arm64/include/asm/kvm_hcall.h      |   2 +
 arch/arm64/include/asm/kvm_pkvm.h       |   3 +
 arch/arm64/kvm/arm.c                    |   2 +
 arch/arm64/kvm/hyp/include/nvhe/alloc.h |  11 ++
 arch/arm64/kvm/hyp/nvhe/alloc.c         | 186 +++++++++++++++++++++++-
 arch/arm64/kvm/hyp/nvhe/hyp-main.c      |  24 +++
 arch/arm64/kvm/pkvm.c                   |  19 +++
 8 files changed, 247 insertions(+), 1 deletion(-)
arch/arm64/include/asm/kvm_asm.h +1 -0
index fc3c52b03154..1ac1990bbd68 100644
@@ -62,6 +62,7 @@ enum __kvm_host_smccc_func {
 	__KVM_HOST_SMCCC_FUNC___kvm_enable_ssbs,
 	__KVM_HOST_SMCCC_FUNC___vgic_v3_init_lrs,
 	__KVM_HOST_SMCCC_FUNC___vgic_v3_get_gic_config,
+	__KVM_HOST_SMCCC_FUNC___pkvm_hyp_alloc_selftest,
 
 	MARKER(__KVM_HOST_SMCCC_FUNC_MIN_PKVM),
 
arch/arm64/include/asm/kvm_hcall.h +2 -0
index bce6eb8b20e0..8a6c2506fdeb 100644
@@ -24,6 +24,7 @@ typedef u16 pkvm_handle_t;
 
 enum pkvm_topup_id {
 	PKVM_TOPUP_HYP_ALLOC,
+	PKVM_TOPUP_HYP_ALLOC_SELFTEST,
 };
 
 struct kvm;
@@ -153,6 +154,7 @@ DECLARE_KVM_HOST_HCALL(int, __pkvm_cpu_set_vector,
 DECLARE_KVM_HOST_HCALL0(void, __kvm_enable_ssbs)
 DECLARE_KVM_HOST_HCALL0(void, __vgic_v3_init_lrs)
 DECLARE_KVM_HOST_HCALL0(u64, __vgic_v3_get_gic_config)
+DECLARE_KVM_HOST_HCALL0(int, __pkvm_hyp_alloc_selftest)
 
 DECLARE_KVM_HOST_HCALL0(int, __pkvm_prot_finalize)
 
arch/arm64/include/asm/kvm_pkvm.h +3 -0
index c338178d6bb2..ec8060f220f4 100644
@@ -17,6 +17,7 @@
 
 #define HYP_MEMBLOCK_REGIONS 128
 
+void pkvm_selftests(void);
 int pkvm_init_host_vm(struct kvm *kvm, unsigned long type);
 int pkvm_create_hyp_vm(struct kvm *kvm);
 bool pkvm_hyp_vm_is_created(struct kvm *kvm);
@@ -208,6 +209,7 @@ struct pkvm_mapping {
 enum pkvm_hyp_req_type {
 	PKVM_HYP_NO_REQ = 0,
 	PKVM_HYP_REQ_HYP_ALLOC,
+	PKVM_HYP_REQ_HYP_ALLOC_SELFTEST,
 	__PKVM_HYP_REQ_TYPE_MAX,
 };
 
@@ -235,6 +237,7 @@ static inline size_t pkvm_hyp_req_arg_size(u8 type)
 	case PKVM_HYP_NO_REQ:
 		return 0;
 	case PKVM_HYP_REQ_HYP_ALLOC:
+	case PKVM_HYP_REQ_HYP_ALLOC_SELFTEST:
 		return sizeof(req->mem);
 	default:
 		WARN_ON(1);
arch/arm64/kvm/arm.c +2 -0
index 8b080804bc90..09ae5431ce58 100644
@@ -2914,6 +2914,8 @@ static int __init init_hyp_mode(void)
 			kvm_err("Failed to init hyp memory protection\n");
 			goto out_err;
 		}
+
+		pkvm_selftests();
 	}
 
 	return 0;
arch/arm64/kvm/hyp/include/nvhe/alloc.h +11 -0
index 8f87a63f8946..bca0168e0046 100644
@@ -14,4 +14,15 @@ int hyp_alloc_init(size_t size);
 int hyp_alloc_topup(struct kvm_hyp_memcache *host_mc);
 unsigned long hyp_alloc_reclaimable(void);
 void hyp_alloc_reclaim(struct kvm_hyp_memcache *host_mc, unsigned long target);
+
+#ifdef CONFIG_NVHE_EL2_DEBUG
+int hyp_allocator_selftest(void);
+u32 hyp_alloc_selftest_topup_needed(void);
+int hyp_alloc_selftest_topup(struct kvm_hyp_memcache *host_mc);
+void hyp_alloc_selftest_reclaim(struct kvm_hyp_memcache *host_mc, unsigned long target);
+#else
+static inline int hyp_alloc_selftest_topup(struct kvm_hyp_memcache *host_mc) { return 0; };
+static inline void
+hyp_alloc_selftest_reclaim(struct kvm_hyp_memcache *host_mc, unsigned long target) { };
+#endif
 #endif
arch/arm64/kvm/hyp/nvhe/alloc.c +185 -1

197 lines not on this page · raw message

arch/arm64/kvm/hyp/nvhe/hyp-main.c +24 -0
index fdc39f064718..a6e6c0941428 100644
@@ -800,6 +800,23 @@ DEFINE_KVM_HOST_HCALL(int, __pkvm_finalize_teardown_vm,
 	return __pkvm_finalize_teardown_vm(handle);
 }
 
+DEFINE_KVM_HOST_HCALL0(int, __pkvm_hyp_alloc_selftest)
+{
+	struct pkvm_hyp_req req = { .type = PKVM_HYP_NO_REQ };
+	int ret = -EPERM;
+
+#ifdef CONFIG_NVHE_EL2_DEBUG
+	ret = hyp_allocator_selftest();
+	if (ret == -ENOMEM) {
+		req.type = PKVM_HYP_REQ_HYP_ALLOC_SELFTEST;
+		req.mem.nr_pages = hyp_alloc_selftest_topup_needed();
+	}
+#endif
+	pkvm_hyp_req_to_smccc(host_data_ptr(host_ctxt), &req);
+
+	return ret;
+}
+
 DEFINE_KVM_HOST_HCALL(int, __pkvm_hyp_topup,
 	enum pkvm_topup_id, id, phys_addr_t, head, unsigned long, nr_pages)
 {
@@ -814,6 +831,9 @@ DEFINE_KVM_HOST_HCALL(int, __pkvm_hyp_topup,
 	case PKVM_TOPUP_HYP_ALLOC:
 		ret = hyp_alloc_topup(&host_mc);
 		break;
+	case PKVM_TOPUP_HYP_ALLOC_SELFTEST:
+		ret = hyp_alloc_selftest_topup(&host_mc);
+		break;
 	default:
 		ret = -EINVAL;
 	}
@@ -835,6 +855,9 @@ DEFINE_KVM_HOST_HCALL(int, __pkvm_hyp_reclaim,
 	case PKVM_TOPUP_HYP_ALLOC:
 		hyp_alloc_reclaim(&host_mc, target);
 		break;
+	case PKVM_TOPUP_HYP_ALLOC_SELFTEST:
+		hyp_alloc_selftest_reclaim(&host_mc, target);
+		break;
 	default:
 		ret = -EINVAL;
 	}
@@ -927,6 +950,7 @@ static const hcall_t host_hcall[] = {
 	HANDLE_FUNC(__kvm_enable_ssbs),
 	HANDLE_FUNC(__vgic_v3_init_lrs),
 	HANDLE_FUNC(__vgic_v3_get_gic_config),
+	HANDLE_FUNC(__pkvm_hyp_alloc_selftest),
 	HANDLE_FUNC(__pkvm_prot_finalize),
 
 	HANDLE_FUNC(__kvm_adjust_pc),
arch/arm64/kvm/pkvm.c +19 -0
index fec819a9dc78..7821f2592eba 100644
@@ -344,6 +344,22 @@ static int __init pkvm_drop_host_privileges(void)
 	return ret;
 }
 
+void __init pkvm_selftests(void)
+{
+#ifdef CONFIG_NVHE_EL2_DEBUG
+	int ret = pkvm_call_hyp_req(__pkvm_hyp_alloc_selftest);
+	unsigned long reclaimed;
+
+	reclaimed = pkvm_hyp_reclaim(PKVM_TOPUP_HYP_ALLOC_SELFTEST, ULONG_MAX);
+
+	/* On failure, not all the pages may be reclaimable */
+	if (!ret)
+		WARN_ON(reclaimed != 6 /* SELFTEST_MAX_PAGES */);
+	else
+		kvm_err("pKVM hyp allocator selftest failed (%d)\n", ret);
+#endif
+}
+
 static int __init finalize_pkvm(void)
 {
 	int ret;
@@ -677,6 +693,9 @@ static int pkvm_handle_hyp_req(struct pkvm_hyp_req *req)
 	case PKVM_HYP_REQ_HYP_ALLOC:
 		ret = pkvm_hyp_topup(PKVM_TOPUP_HYP_ALLOC, req->mem.nr_pages);
 		break;
+	case PKVM_HYP_REQ_HYP_ALLOC_SELFTEST:
+		ret = pkvm_hyp_topup(PKVM_TOPUP_HYP_ALLOC_SELFTEST, req->mem.nr_pages);
+		break;
 	}
 
 	trace_kvm_handle_pkvm_hyp_req(req, ret);
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#11 lore raw

Re: [PATCH v6 09/18] KVM: arm64: Add selftests for the pKVM heap allocator

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] mm: leak of donated pages in hyp_allocator_selftest() error paths --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] mm: leak of donated pages in hyp_allocator_selftest() error paths --

commit e38e9008687b6871455e7ad734e5cd3158568487
Author: Vincent Donnefort <[email protected]>

KVM: arm64: Add selftests for the pKVM heap allocator

Introduce a comprehensive runtime selftest for the pKVM hypervisor heap allocator, executed during init when CONFIG_NVHE_EL2_DEBUG is enabled. The selftest runs entirely at EL2 and exercises allocator core mechanisms including allocation, chunk recycling, splitting, merging, and reclaiming.

Quoted 4 lines
arch/arm64/kvm/hyp/nvhe/alloc.c +0 -0
index e0104d2dd6c0e..c1881c0011c9e 100644

[ ... ]

Quoted 1 line
arch/arm64/kvm/hyp/nvhe/alloc.c +0 -0
@@ -1025,3 +1033,179 @@ u32 hyp_alloc_topup_needed(void)

[ ... ]

arch/arm64/kvm/hyp/nvhe/alloc.c u32 hyp_alloc_topup_needed(void) · line 1178

Quoted 5 lines
arch/arm64/kvm/hyp/nvhe/alloc.c +5 -0
+	/* Test reclaiming the last chunk of the list */
+	selftest_free(addr4);
+	hyp_allocator_reclaim(allocator, &host_mc, SELFTEST_MAX_PAGES);
+	if (host_mc.nr_pages != SELFTEST_MAX_PAGES - 3)
+		return -EINVAL;

[Severity: Medium]
Does this leak the reclaimed pages?

The allocator test reclaims pages into the local host_mc memcache.

If the assertion fails here (or in any of the subsequent checks before the test completes), the function returns early without passing these pages back to the host or freeing them.

This results in a permanent physical memory leak of up to 6 pages.

Quoted 16 lines
arch/arm64/kvm/hyp/nvhe/alloc.c +16 -0
+
+	/* Test punching a hole in the middle of a free chunk ... */
+	selftest_free(addr2);
+	hyp_allocator_reclaim(allocator, &host_mc, SELFTEST_MAX_PAGES);
+	if (host_mc.nr_pages != SELFTEST_MAX_PAGES - 2)
+		return -EINVAL;
+
+	if (selftest_alloc(PAGE_SIZE))
+		return -EINVAL;
+	if (selftest_errno() != -ENOMEM)
+		return -EINVAL;
+
+	/* ... and to refill this hole */
+	ret = hyp_allocator_topup(allocator, &host_mc);
+	if (ret)
+		return ret;

[ ... ]

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

PATCH v6 10/18 KVM: arm64: Add a shrinker for pKVM

In reply to Vincent Donnefort

Integrate the pKVM memory reclaim interface with the host's memory management subsystem.

This allows the host to automatically recover unused memory fom the hypervisor's heap allocator when the host is under memory pressure.

---
 arch/arm64/include/asm/kvm_hcall.h |  1 +
 arch/arm64/kvm/pkvm.c              | 50 +++++++++++++++++++++++++++---
 2 files changed, 47 insertions(+), 4 deletions(-)
arch/arm64/include/asm/kvm_hcall.h +1 -0
index 8a6c2506fdeb..9f09eb11193f 100644
@@ -24,6 +24,7 @@ typedef u16 pkvm_handle_t;
 
 enum pkvm_topup_id {
 	PKVM_TOPUP_HYP_ALLOC,
+	NR_PKVM_TOPUP_HYP_IDS,
 	PKVM_TOPUP_HYP_ALLOC_SELFTEST,
 };
 
arch/arm64/kvm/pkvm.c +46 -4

78 lines not on this page · raw message

Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#13 lore raw

PATCH v6 11/18 KVM: arm64: Filter out non-kernel addresses in kern_hyp_va

In reply to Vincent Donnefort

kern_hyp_va() is idempotent for the hypervisor linear space. This is handy for nVHE hypervisor callers handling kvm_vcpu or kvm_arch pointers. Those pointers can originate from the hypervisor space (when protected mode is enabled, we don't trust the kernel and the hypervisor uses its own copy) or from the kernel space (we do trust the kernel in "non-protected" nVHE).

This idempotence does not hold for addresses within the hypervisor private range, like the ones you get from the pKVM heap allocator (hyp_alloc()). To resolve this, filter out non-kernel addresses based on PAGE_OFFSET.

Leave the assembly version untouched as it has no current users.

---
 arch/arm64/include/asm/kvm_mmu.h | 3 +++
 1 file changed, 3 insertions(+)
arch/arm64/include/asm/kvm_mmu.h +3 -0
index 57f65257bb56..04d9f59db976 100644
@@ -128,6 +128,9 @@ static __always_inline unsigned long __kern_hyp_va(unsigned long v)
  * replace the instructions with `nop`s.
  */
 #ifndef __KVM_VHE_HYPERVISOR__
+	if (is_protected_kvm_enabled() && !is_ttbr1_addr(v))
+		return v;
+
 	asm volatile(ALTERNATIVE_CB("and %0, %0, #1\n"         /* mask with va_mask */
 				    "ror %0, %0, #1\n"         /* rotate to the first tag bit */
 				    "add %0, %0, #0\n"         /* insert the low 12 bits of the tag */
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#14 lore raw

Re: [PATCH v6 11/18] KVM: arm64: Filter out non-kernel addresses in kern_hyp_va

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Critical] mm: EL2 memory corruption via kern_hyp_va bypass for non-TTBR1 addresses --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] mm: EL2 memory corruption via kern_hyp_va bypass for non-TTBR1 addresses --

commit 8768ff7b59b5b3eb8674eb929fc20e711a216dbf
Author: Vincent Donnefort <[email protected]>

KVM: arm64: Filter out non-kernel addresses in kern_hyp_va

kern_hyp_va() is idempotent for the hypervisor linear space, which is handy for nVHE hypervisor callers. This commit adds a check based on PAGE_OFFSET to filter out non-kernel addresses, extending idempotence to the hypervisor private range.

arch/arm64/include/asm/kvm_mmu.h static __always_inline unsigned long __kern_hyp_va(unsigned long v) · line 133

Quoted 11 lines
arch/arm64/include/asm/kvm_mmu.h +3 -0
index 57f65257bb56d..04d9f59db976f 100644
@@ -128,6 +128,9 @@ static __always_inline unsigned long __kern_hyp_va(unsigned long v)
  * replace the instructions with nops.
  */
 #ifndef __KVM_VHE_HYPERVISOR__
+	if (is_protected_kvm_enabled() && !is_ttbr1_addr(v))
+		return v;
+

[Severity: Critical]
Does this bypass address translation for untrusted host-provided pointers when they are not TTBR1 addresses?

While this makes kern_hyp_va() idempotent for EL2 private addresses, kern_hyp_va_host() also uses __kern_hyp_va() on unvalidated host arguments.

For example, if the host issues a hypercall like __vgic_v5_save_apr and passes an EL2 private address:

arch/arm64/kvm/hyp/nvhe/hyp-main.c:handle___vgic_v5_save_apr() {
    ...
    __vgic_v5_save_apr(kern_hyp_va_host(cpu_if));
    ...
}

Because is_ttbr1_addr(v) is false, __kern_hyp_va() will return the EL2 private address unmodified. The handler then dereferences it:

arch/arm64/kvm/hyp/vgic-v5-sr.c:__vgic_v5_save_apr() {
    ...
    cpu_if->vgic_apr = read_sysreg_s(SYS_ICH_APR_EL2);
    ...
}

Could this regression allow an untrusted host (EL1) to execute an arbitrary write into EL2 private memory and break the pKVM trust boundary?

Quoted 3 lines
arch/arm64/include/asm/kvm_mmu.h +0 -0
 	asm volatile(ALTERNATIVE_CB("and %0, %0, #1\n"         /* mask with va_mask */
 				    "ror %0, %0, #1\n"         /* rotate to the first tag bit */
 				    "add %0, %0, #0\n"         /* insert the low 12 bits of the tag */
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
#15 lore raw

PATCH v6 12/18 KVM: arm64: Move hyp_vm refcount into the structure

In reply to Vincent Donnefort

In preparation for allocating hyp_vm using the pKVM heap allocator (hyp_alloc()), move its reference count out of the page metadata (vmemmap) and place it into the structure itself. This transition is necessary because hyp_alloc() allows multiple small objects to share the same physical page.

---
 arch/arm64/kvm/hyp/include/nvhe/pkvm.h | 13 +++++++++++++
 arch/arm64/kvm/hyp/nvhe/pkvm.c         | 10 +++++-----
 2 files changed, 18 insertions(+), 5 deletions(-)
arch/arm64/kvm/hyp/include/nvhe/pkvm.h +13 -0
index c1171451e1be..b208544141c0 100644
@@ -42,6 +42,7 @@ struct pkvm_hyp_vm {
 	struct kvm_pgtable pgt;
 	struct kvm_pgtable_mm_ops mm_ops;
 	struct hyp_pool pool;
+	unsigned short refcount;
 	hyp_spinlock_t lock;
 
 	/* Array of the hyp vCPU structures for this VM. */
@@ -66,6 +67,18 @@ static inline bool pkvm_hyp_vm_is_protected(struct pkvm_hyp_vm *hyp_vm)
 	return kvm_vm_is_protected(&hyp_vm->kvm);
 }
 
+static inline void pkvm_hyp_vm_ref_inc(struct pkvm_hyp_vm *hyp_vm)
+{
+	BUG_ON(hyp_vm->refcount == USHRT_MAX);
+	hyp_vm->refcount++;
+}
+
+static inline void pkvm_hyp_vm_ref_dec(struct pkvm_hyp_vm *hyp_vm)
+{
+	BUG_ON(!hyp_vm->refcount);
+	hyp_vm->refcount--;
+}
+
 void pkvm_hyp_vm_table_init(void *tbl);
 
 int __pkvm_reserve_vm(void);
arch/arm64/kvm/hyp/nvhe/pkvm.c +5 -5
index 5cdb0318fa7b..98db5bd28dde 100644
@@ -278,7 +278,7 @@ struct pkvm_hyp_vcpu *pkvm_load_hyp_vcpu(pkvm_handle_t handle,
 	}
 
 	hyp_vcpu->loaded_hyp_vcpu = this_cpu_ptr(&loaded_hyp_vcpu);
-	hyp_page_ref_inc(hyp_virt_to_page(hyp_vm));
+	pkvm_hyp_vm_ref_inc(hyp_vm);
 unlock:
 	hyp_spin_unlock(&vm_table_lock);
 
@@ -294,7 +294,7 @@ void pkvm_put_hyp_vcpu(struct pkvm_hyp_vcpu *hyp_vcpu)
 	hyp_spin_lock(&vm_table_lock);
 	hyp_vcpu->loaded_hyp_vcpu = NULL;
 	__this_cpu_write(loaded_hyp_vcpu, NULL);
-	hyp_page_ref_dec(hyp_virt_to_page(hyp_vm));
+	pkvm_hyp_vm_ref_dec(hyp_vm);
 	hyp_spin_unlock(&vm_table_lock);
 }
 
@@ -311,7 +311,7 @@ struct pkvm_hyp_vm *get_pkvm_hyp_vm(pkvm_handle_t handle)
 	hyp_spin_lock(&vm_table_lock);
 	hyp_vm = get_vm_by_handle(handle);
 	if (hyp_vm)
-		hyp_page_ref_inc(hyp_virt_to_page(hyp_vm));
+		pkvm_hyp_vm_ref_inc(hyp_vm);
 	hyp_spin_unlock(&vm_table_lock);
 
 	return hyp_vm;
@@ -320,7 +320,7 @@ struct pkvm_hyp_vm *get_pkvm_hyp_vm(pkvm_handle_t handle)
 void put_pkvm_hyp_vm(struct pkvm_hyp_vm *hyp_vm)
 {
 	hyp_spin_lock(&vm_table_lock);
-	hyp_page_ref_dec(hyp_virt_to_page(hyp_vm));
+	pkvm_hyp_vm_ref_dec(hyp_vm);
 	hyp_spin_unlock(&vm_table_lock);
 }
 
@@ -979,7 +979,7 @@ static struct pkvm_hyp_vm *get_pkvm_unref_hyp_vm_locked(pkvm_handle_t handle)
 	hyp_assert_lock_held(&vm_table_lock);
 
 	hyp_vm = get_vm_by_handle(handle);
-	if (!hyp_vm || hyp_page_count(hyp_vm))
+	if (!hyp_vm || hyp_vm->refcount)
 		return NULL;
 
 	return hyp_vm;
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#16 lore raw

PATCH v6 13/18 KVM: arm64: Alloc pkvm_hyp_vm using pKVM heap allocator

In reply to Vincent Donnefort

Transition the allocation of the hypervisor VM state structure (pkvm_hyp_vm) from the host to the hypervisor using the new pKVM heap allocator (hyp_alloc()).

Previously, the host was responsible for calculating the size of, allocating, and donating memory for pkvm_hyp_vm during VM creation. With the heap allocator in place, the hypervisor now allocates this structure dynamically at EL2.

Use the pkvm_call_hyp_req() wrapper in the host to invoke __pkvm_init_vm, which automatically handles any top-up requests if the hypervisor runs out of heap memory during allocation.

---
 arch/arm64/include/asm/kvm_hcall.h     |  3 +--
 arch/arm64/kvm/hyp/hyp-constants.c     |  1 -
 arch/arm64/kvm/hyp/include/nvhe/pkvm.h |  3 +--
 arch/arm64/kvm/hyp/nvhe/hyp-main.c     | 32 +++++++++++++++++++++++---
 arch/arm64/kvm/hyp/nvhe/pkvm.c         | 25 ++++++++++----------
 arch/arm64/kvm/pkvm.c                  | 21 ++++-------------
 6 files changed, 47 insertions(+), 38 deletions(-)
arch/arm64/include/asm/kvm_hcall.h +1 -2
index 9f09eb11193f..c98243e79e31 100644
@@ -230,8 +230,7 @@ DECLARE_KVM_HOST_HCALL0(int, __pkvm_reserve_vm)
 DECLARE_KVM_HOST_HCALL(void, __pkvm_unreserve_vm,
 	pkvm_handle_t, handle)
 DECLARE_KVM_HOST_HCALL(int, __pkvm_init_vm,
-	struct kvm __kern *, host_kvm, void __kern *, vm_hva,
-	void __kern *, pgd_hva)
+	struct kvm __kern *, host_kvm, void __kern *, pgd_hva)
 DECLARE_KVM_HOST_HCALL(int, __pkvm_init_vcpu,
 	pkvm_handle_t, handle, struct kvm_vcpu __kern *, host_vcpu,
 	void __kern *, vcpu_hva)
arch/arm64/kvm/hyp/hyp-constants.c +0 -1
index b257a3b4bfc5..501ab35a3840 100644
@@ -7,7 +7,6 @@
 int main(void)
 {
 	DEFINE(STRUCT_HYP_PAGE_SIZE,	sizeof(struct hyp_page));
-	DEFINE(PKVM_HYP_VM_SIZE,	sizeof(struct pkvm_hyp_vm));
 	DEFINE(PKVM_HYP_VCPU_SIZE,	sizeof(struct pkvm_hyp_vcpu));
 	return 0;
 }
arch/arm64/kvm/hyp/include/nvhe/pkvm.h +1 -2
index b208544141c0..c5fd7315c0e3 100644
@@ -83,8 +83,7 @@ void pkvm_hyp_vm_table_init(void *tbl);
 
 int __pkvm_reserve_vm(void);
 void __pkvm_unreserve_vm(pkvm_handle_t handle);
-int __pkvm_init_vm(struct kvm *host_kvm, void __kern *vm_hva,
-		   void __kern *pgd_hva);
+int __pkvm_init_vm(struct kvm *host_kvm, void __kern *pgd_hva);
 int __pkvm_init_vcpu(pkvm_handle_t handle, struct kvm_vcpu *host_vcpu,
 		     void __kern *vcpu_hva);
 
arch/arm64/kvm/hyp/nvhe/hyp-main.c +29 -3
index a6e6c0941428..7eecac7c7fbe 100644
@@ -69,6 +69,33 @@ DEFINE_PER_CPU(struct kvm_nvhe_init_params, kvm_init_params);
 	}								\
 	static ret __do_##name(void)
 
+/*
+ * Encode a hypervisor request in the host SMCCC return registers for known
+ * error numbers.
+ *
+ * Must be paired with pkvm_call_hyp_req() on the host side.
+ */
+static int errno_to_smccc(int ret)
+{
+	struct pkvm_hyp_req req = { .type = PKVM_HYP_NO_REQ };
+
+	switch (ret) {
+	case -ENOMEM: {
+		u32 nr_pages = hyp_alloc_topup_needed();
+
+		if (nr_pages) {
+			req.type = PKVM_HYP_REQ_HYP_ALLOC;
+			req.mem.nr_pages = nr_pages;
+		}
+		break;
+	}
+	}
+
+	pkvm_hyp_req_to_smccc(host_data_ptr(host_ctxt), &req);
+
+	return ret;
+}
+
 /* Number of implemented GICv3 LRs. Used by flush_hyp_vcpu(). */
 unsigned int hyp_gicv3_nr_lr;
 
@@ -756,10 +783,9 @@ DEFINE_KVM_HOST_HCALL(void, __pkvm_unreserve_vm,
 }
 
 DEFINE_KVM_HOST_HCALL(int, __pkvm_init_vm,
-	struct kvm __kern *, host_kvm, void __kern *, vm_hva,
-	void __kern *, pgd_hva)
+	struct kvm __kern *, host_kvm, void __kern *, pgd_hva)
 {
-	return __pkvm_init_vm(kern_hyp_va_host(host_kvm), vm_hva, pgd_hva);
+	return errno_to_smccc(__pkvm_init_vm(kern_hyp_va_host(host_kvm), pgd_hva));
 }
 
 DEFINE_KVM_HOST_HCALL(int, __pkvm_init_vcpu,
arch/arm64/kvm/hyp/nvhe/pkvm.c +12 -13
index 98db5bd28dde..c29a25cae8e8 100644
@@ -11,6 +11,7 @@
 
 #include <asm/kvm_emulate.h>
 
+#include <nvhe/alloc.h>
 #include <nvhe/mem_protect.h>
 #include <nvhe/memory.h>
 #include <nvhe/pkvm.h>
@@ -810,16 +811,13 @@ void teardown_selftest_vm(void)
  * Unmap the donated memory from the host at stage 2.
  *
  * host_kvm: A pointer to the host's struct kvm.
- * vm_hva: The host va of the area being donated for the VM state.
- *	   Must be page aligned.
  * pgd_hva: The host va of the area being donated for the stage-2 PGD for
  *	    the VM. Must be page aligned. Its size is implied by the VM's
  *	    VTCR.
  *
  * Return 0 success, negative error code on failure.
  */
-int __pkvm_init_vm(struct kvm *host_kvm, void __kern *vm_hva,
-		   void __kern *pgd_hva)
+int __pkvm_init_vm(struct kvm *host_kvm, void __kern *pgd_hva)
 {
 	struct pkvm_hyp_vm *hyp_vm = NULL;
 	size_t vm_size, pgd_size;
@@ -847,15 +845,17 @@ int __pkvm_init_vm(struct kvm *host_kvm, void __kern *vm_hva,
 	vm_size = pkvm_get_hyp_vm_size(nr_vcpus);
 	pgd_size = kvm_pgtable_stage2_pgd_size(host_mmu.arch.mmu.vtcr);
 
-	ret = -ENOMEM;
+	hyp_vm = hyp_alloc(vm_size);
+	if (!hyp_vm) {
+		ret = hyp_alloc_errno();
+		goto err_unpin_kvm;
+	}
 
-	hyp_vm = map_donated_memory(vm_hva, vm_size);
-	if (!hyp_vm)
-		goto err_remove_mappings;
+	ret = -ENOMEM;
 
 	pgd = map_donated_memory_noclear(pgd_hva, pgd_size);
 	if (!pgd)
-		goto err_remove_mappings;
+		goto err_free_hyp_vm;
 
 	init_pkvm_hyp_vm(host_kvm, hyp_vm, nr_vcpus, handle);
 
@@ -873,8 +873,9 @@ int __pkvm_init_vm(struct kvm *host_kvm, void __kern *vm_hva,
 err_destroy_stage2:
 	kvm_guest_destroy_stage2(hyp_vm);
 err_remove_mappings:
-	unmap_donated_memory(hyp_vm, vm_size);
 	unmap_donated_memory(pgd, pgd_size);
+err_free_hyp_vm:
+	hyp_free(hyp_vm);
 err_unpin_kvm:
 	hyp_unpin_shared_mem(host_kvm, host_kvm + 1);
 	return ret;
@@ -1010,7 +1011,6 @@ int __pkvm_finalize_teardown_vm(pkvm_handle_t handle)
 	struct pkvm_hyp_vm *hyp_vm;
 	struct kvm *host_kvm;
 	unsigned int idx;
-	size_t vm_size;
 	int err;
 
 	hyp_spin_lock(&vm_table_lock);
@@ -1053,8 +1053,7 @@ int __pkvm_finalize_teardown_vm(pkvm_handle_t handle)
 		teardown_donated_memory(mc, hyp_vcpu, sizeof(*hyp_vcpu));
 	}
 
-	vm_size = pkvm_get_hyp_vm_size(hyp_vm->kvm.created_vcpus);
-	teardown_donated_memory(mc, hyp_vm, vm_size);
+	hyp_free(hyp_vm);
 	hyp_unpin_shared_mem(host_kvm, host_kvm + 1);
 	return 0;
 
arch/arm64/kvm/pkvm.c +4 -17
index ea96744f41fb..8505965dbfb2 100644
@@ -212,8 +212,8 @@ static int __pkvm_create_hyp_vcpu(struct kvm_vcpu *vcpu)
  */
 static int __pkvm_create_hyp_vm(struct kvm *kvm)
 {
-	size_t pgd_sz, hyp_vm_sz;
-	void *pgd, *hyp_vm;
+	size_t pgd_sz;
+	void *pgd;
 	int ret;
 
 	if (kvm->created_vcpus < 1)
@@ -230,28 +230,15 @@ static int __pkvm_create_hyp_vm(struct kvm *kvm)
 	if (!pgd)
 		return -ENOMEM;
 
-	/* Allocate memory to donate to hyp for vm and vcpu pointers. */
-	hyp_vm_sz = PAGE_ALIGN(size_add(PKVM_HYP_VM_SIZE,
-					size_mul(sizeof(void *),
-						 kvm->created_vcpus)));
-	hyp_vm = alloc_pages_exact(hyp_vm_sz, GFP_KERNEL_ACCOUNT);
-	if (!hyp_vm) {
-		ret = -ENOMEM;
-		goto free_pgd;
-	}
-
-	/* Donate the VM memory to hyp and let hyp initialize it. */
-	ret = kvm_call_hyp_nvhe(__pkvm_init_vm, kvm, hyp_vm, pgd);
+	ret = pkvm_call_hyp_req(__pkvm_init_vm, kvm, pgd);
 	if (ret)
-		goto free_vm;
+		goto free_pgd;
 
 	kvm->arch.pkvm.is_created = true;
 	init_hyp_stage2_memcache(&kvm->arch.pkvm.stage2_teardown_mc);
 	kvm_account_pgtable_pages(pgd, pgd_sz / PAGE_SIZE);
 
 	return 0;
-free_vm:
-	free_pages_exact(hyp_vm, hyp_vm_sz);
 free_pgd:
 	free_pages_exact(pgd, pgd_sz);
 	return ret;
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#17 lore raw

Re: [PATCH v6 13/18] KVM: arm64: Alloc pkvm_hyp_vm using pKVM heap allocator

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] kvm: arm64: memcg accounting bypass in pKVM hyp allocator top-ups --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] kvm: arm64: memcg accounting bypass in pKVM hyp allocator top-ups --

commit c6ba9fe98ea9532d6a486e0ae326359e821cd9d4
Author: Vincent Donnefort <[email protected]>

KVM: arm64: Alloc pkvm_hyp_vm using pKVM heap allocator

Transition the allocation of the hypervisor VM state structure (pkvm_hyp_vm) from the host to the hypervisor using the new pKVM heap allocator. The host now uses pkvm_call_hyp_req() to invoke __pkvm_init_vm, automatically handling any top-up requests if the hypervisor runs out of heap memory.

Quoted 11 lines
arch/arm64/kvm/pkvm.c +0 -3
index ea96744f41fb0..8505965dbfb21 100644
@@ -230,28 +230,15 @@ static int __pkvm_create_hyp_vm(struct kvm *kvm)
 	if (!pgd)
 		return -ENOMEM;
 
-	/* Allocate memory to donate to hyp for vm and vcpu pointers. */
-	hyp_vm_sz = PAGE_ALIGN(size_add(PKVM_HYP_VM_SIZE,
-					size_mul(sizeof(void *),

arch/arm64/kvm/pkvm.c static int __pkvm_create_hyp_vm(struct kvm *kvm) · line 233

Quoted 10 lines
arch/arm64/kvm/pkvm.c +1 -9
-						 kvm->created_vcpus)));
-	hyp_vm = alloc_pages_exact(hyp_vm_sz, GFP_KERNEL_ACCOUNT);
-	if (!hyp_vm) {
-		ret = -ENOMEM;
-		goto free_pgd;
-	}
-
-	/* Donate the VM memory to hyp and let hyp initialize it. */
-	ret = kvm_call_hyp_nvhe(__pkvm_init_vm, kvm, hyp_vm, pgd);
+	ret = pkvm_call_hyp_req(__pkvm_init_vm, kvm, pgd);

[Severity: High]
Does this change bypass memory cgroup accounting for the VM structure?

The previous implementation explicitly used GFP_KERNEL_ACCOUNT to charge the allocation to the calling process. By migrating the allocation to the hypervisor, the memory is now satisfied by the host's unaccounted top-up path.

When the hypervisor needs more memory and returns a top-up request, the host handles this in pkvm_hyp_topup() using a temporary memcache:

arch/arm64/kvm/pkvm.c:pkvm_hyp_topup() {
    ...
    init_hyp_memcache(&mc);
    ret = topup_hyp_memcache(&mc, nr_pages);
    ...
}

Because init_hyp_memcache() clears all flags and drops HYP_MEMCACHE_ACCOUNT_KMEMCG, top-up pages are allocated with GFP_KERNEL instead of GFP_KERNEL_ACCOUNT.

Since KVM relies on memcg limits rather than static quotas to constrain VM memory, could an unprivileged userspace process bypass its container memory limits by creating numerous VMs, potentially exhausting host kernel memory and causing a denial of service?

Quoted 7 lines
arch/arm64/kvm/pkvm.c +1 -1
 	if (ret)
-		goto free_vm;
+		goto free_pgd;
 
 	kvm->arch.pkvm.is_created = true;
 	init_hyp_stage2_memcache(&kvm->arch.pkvm.stage2_teardown_mc);
 	kvm_account_pgtable_pages(pgd, pgd_sz / PAGE_SIZE);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
#18 lore raw

PATCH v6 14/18 KVM: arm64: Alloc pkvm_hyp_vcpu using pKVM heap allocator

In reply to Vincent Donnefort

Transition the allocation of the hypervisor vCPU state structure (pkvm_hyp_vcpu) from the host to the hypervisor using the new pKVM heap allocator (hyp_alloc()).

Previously, the host was responsible for calculating the size of, allocating, and donating memory for pkvm_hyp_vcpu during vCPU creation. With the heap allocator in place, the hypervisor now allocates this structure dynamically at EL2.

Use the pkvm_call_hyp_req() wrapper in the host to invoke __pkvm_create_hyp_vcpu, which automatically handles any top-up requests if the hypervisor runs out of heap memory during allocation.

---
 arch/arm64/include/asm/kvm_hcall.h     |  3 +-
 arch/arm64/include/asm/kvm_host.h      |  1 -
 arch/arm64/kvm/hyp/hyp-constants.c     |  1 -
 arch/arm64/kvm/hyp/include/nvhe/pkvm.h |  3 +-
 arch/arm64/kvm/hyp/nvhe/hyp-main.c     |  5 ++--
 arch/arm64/kvm/hyp/nvhe/pkvm.c         | 38 +++++---------------------
 arch/arm64/kvm/pkvm.c                  | 11 +-------
 7 files changed, 12 insertions(+), 50 deletions(-)
arch/arm64/include/asm/kvm_hcall.h +1 -2
index c98243e79e31..7dd176b4bea4 100644
@@ -232,8 +232,7 @@ DECLARE_KVM_HOST_HCALL(void, __pkvm_unreserve_vm,
 DECLARE_KVM_HOST_HCALL(int, __pkvm_init_vm,
 	struct kvm __kern *, host_kvm, void __kern *, pgd_hva)
 DECLARE_KVM_HOST_HCALL(int, __pkvm_init_vcpu,
-	pkvm_handle_t, handle, struct kvm_vcpu __kern *, host_vcpu,
-	void __kern *, vcpu_hva)
+	pkvm_handle_t, handle, struct kvm_vcpu __kern *, host_vcpu)
 DECLARE_KVM_HOST_HCALL0(int, __pkvm_vcpu_in_poison_fault)
 DECLARE_KVM_HOST_HCALL(int, __pkvm_force_reclaim_guest_page,
 	phys_addr_t, phys)
arch/arm64/include/asm/kvm_host.h +0 -1
index 64cd6233b439..3cca9f3b2eeb 100644
@@ -267,7 +267,6 @@ struct kvm_smccc_features {
 
 struct kvm_protected_vm {
 	pkvm_handle_t handle;
-	struct kvm_hyp_memcache teardown_mc;
 	struct kvm_hyp_memcache stage2_teardown_mc;
 	bool is_protected;
 	bool is_created;
arch/arm64/kvm/hyp/hyp-constants.c +0 -1
index 501ab35a3840..b2caae21f271 100644
@@ -7,6 +7,5 @@
 int main(void)
 {
 	DEFINE(STRUCT_HYP_PAGE_SIZE,	sizeof(struct hyp_page));
-	DEFINE(PKVM_HYP_VCPU_SIZE,	sizeof(struct pkvm_hyp_vcpu));
 	return 0;
 }
arch/arm64/kvm/hyp/include/nvhe/pkvm.h +1 -2
index c5fd7315c0e3..866961c3bacb 100644
@@ -84,8 +84,7 @@ void pkvm_hyp_vm_table_init(void *tbl);
 int __pkvm_reserve_vm(void);
 void __pkvm_unreserve_vm(pkvm_handle_t handle);
 int __pkvm_init_vm(struct kvm *host_kvm, void __kern *pgd_hva);
-int __pkvm_init_vcpu(pkvm_handle_t handle, struct kvm_vcpu *host_vcpu,
-		     void __kern *vcpu_hva);
+int __pkvm_init_vcpu(pkvm_handle_t handle, struct kvm_vcpu *host_vcpu);
 
 int __pkvm_reclaim_dying_guest_page(pkvm_handle_t handle, u64 gfn);
 int __pkvm_start_teardown_vm(pkvm_handle_t handle);
arch/arm64/kvm/hyp/nvhe/hyp-main.c +2 -3
index 7eecac7c7fbe..281d1359606a 100644
@@ -789,10 +789,9 @@ DEFINE_KVM_HOST_HCALL(int, __pkvm_init_vm,
 }
 
 DEFINE_KVM_HOST_HCALL(int, __pkvm_init_vcpu,
-	pkvm_handle_t, handle, struct kvm_vcpu __kern *, host_vcpu,
-	void __kern *, vcpu_hva)
+	pkvm_handle_t, handle, struct kvm_vcpu __kern *, host_vcpu)
 {
-	return __pkvm_init_vcpu(handle, kern_hyp_va_host(host_vcpu), vcpu_hva);
+	return errno_to_smccc(__pkvm_init_vcpu(handle, kern_hyp_va_host(host_vcpu)));
 }
 
 DEFINE_KVM_HOST_HCALL0(int, __pkvm_vcpu_in_poison_fault)
arch/arm64/kvm/hyp/nvhe/pkvm.c +7 -31
index c29a25cae8e8..5031ef9e6fe9 100644
@@ -672,16 +672,6 @@ static void *map_donated_memory_noclear(void __kern *host_va, size_t size)
 	return va;
 }
 
-static void *map_donated_memory(void __kern *host_va, size_t size)
-{
-	void *va = map_donated_memory_noclear(host_va, size);
-
-	if (va)
-		memset(va, 0, size);
-
-	return va;
-}
-
 static void __unmap_donated_memory(void *va, size_t size)
 {
 	kvm_flush_dcache_to_poc(va, size);
@@ -910,16 +900,15 @@ static int register_hyp_vcpu(struct pkvm_hyp_vm *hyp_vm,
 	return 0;
 }
 
-int __pkvm_init_vcpu(pkvm_handle_t handle, struct kvm_vcpu *host_vcpu,
-		     void __kern *vcpu_hva)
+int __pkvm_init_vcpu(pkvm_handle_t handle, struct kvm_vcpu *host_vcpu)
 {
 	struct pkvm_hyp_vcpu *hyp_vcpu;
 	struct pkvm_hyp_vm *hyp_vm;
 	int ret;
 
-	hyp_vcpu = map_donated_memory(vcpu_hva, sizeof(*hyp_vcpu));
+	hyp_vcpu = hyp_alloc(sizeof(*hyp_vcpu));
 	if (!hyp_vcpu)
-		return -ENOMEM;
+		return hyp_alloc_errno();
 
 	hyp_spin_lock(&vm_table_lock);
 
@@ -940,24 +929,12 @@ int __pkvm_init_vcpu(pkvm_handle_t handle, struct kvm_vcpu *host_vcpu,
 	}
 unlock:
 	hyp_spin_unlock(&vm_table_lock);
-
 	if (ret)
-		unmap_donated_memory(hyp_vcpu, sizeof(*hyp_vcpu));
+		hyp_free(hyp_vcpu);
+
 	return ret;
 }
 
-static void
-teardown_donated_memory(struct kvm_hyp_memcache *mc, void *addr, size_t size)
-{
-	size = PAGE_ALIGN(size);
-	memset(addr, 0, size);
-
-	for (void *start = addr; start < addr + size; start += PAGE_SIZE)
-		push_hyp_memcache(mc, start, hyp_virt_to_phys);
-
-	unmap_donated_memory_noclear(addr, size);
-}
-
 int __pkvm_reclaim_dying_guest_page(pkvm_handle_t handle, u64 gfn)
 {
 	struct pkvm_hyp_vm *hyp_vm = get_pkvm_hyp_vm(handle);
@@ -1007,7 +984,7 @@ int __pkvm_start_teardown_vm(pkvm_handle_t handle)
 
 int __pkvm_finalize_teardown_vm(pkvm_handle_t handle)
 {
-	struct kvm_hyp_memcache *mc, *stage2_mc;
+	struct kvm_hyp_memcache *stage2_mc;
 	struct pkvm_hyp_vm *hyp_vm;
 	struct kvm *host_kvm;
 	unsigned int idx;
@@ -1028,7 +1005,6 @@ int __pkvm_finalize_teardown_vm(pkvm_handle_t handle)
 	hyp_spin_unlock(&vm_table_lock);
 
 	/* Reclaim guest pages (including page-table pages) */
-	mc = &host_kvm->arch.pkvm.teardown_mc;
 	stage2_mc = &host_kvm->arch.pkvm.stage2_teardown_mc;
 	reclaim_pgtable_pages(hyp_vm, stage2_mc);
 	unpin_host_vcpus(hyp_vm->vcpus, hyp_vm->kvm.created_vcpus);
@@ -1050,7 +1026,7 @@ int __pkvm_finalize_teardown_vm(pkvm_handle_t handle)
 			unmap_donated_memory_noclear(addr, PAGE_SIZE);
 		}
 
-		teardown_donated_memory(mc, hyp_vcpu, sizeof(*hyp_vcpu));
+		hyp_free(hyp_vcpu);
 	}
 
 	hyp_free(hyp_vm);
arch/arm64/kvm/pkvm.c +1 -10
index 8505965dbfb2..36e677e51f7d 100644
@@ -174,28 +174,19 @@ static void __pkvm_destroy_hyp_vm(struct kvm *kvm)
 
 	kvm->arch.pkvm.handle = 0;
 	kvm->arch.pkvm.is_created = false;
-	free_hyp_memcache(&kvm->arch.pkvm.teardown_mc);
 	free_hyp_memcache(&kvm->arch.pkvm.stage2_teardown_mc);
 }
 
 static int __pkvm_create_hyp_vcpu(struct kvm_vcpu *vcpu)
 {
-	size_t hyp_vcpu_sz = PAGE_ALIGN(PKVM_HYP_VCPU_SIZE);
 	pkvm_handle_t handle = vcpu->kvm->arch.pkvm.handle;
-	void *hyp_vcpu;
 	int ret;
 
 	init_hyp_stage2_memcache(&vcpu->arch.pkvm_memcache);
 
-	hyp_vcpu = alloc_pages_exact(hyp_vcpu_sz, GFP_KERNEL_ACCOUNT);
-	if (!hyp_vcpu)
-		return -ENOMEM;
-
-	ret = kvm_call_hyp_nvhe(__pkvm_init_vcpu, handle, vcpu, hyp_vcpu);
+	ret = pkvm_call_hyp_req(__pkvm_init_vcpu, handle, vcpu);
 	if (!ret)
 		vcpu_set_flag(vcpu, VCPU_PKVM_FINALIZED);
-	else
-		free_pages_exact(hyp_vcpu, hyp_vcpu_sz);
 
 	return ret;
 }
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#19 lore raw

Re: [PATCH v6 14/18] KVM: arm64: Alloc pkvm_hyp_vcpu using pKVM heap allocator

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] mm: memcg accounting bypass for pkvm_hyp_vcpu in pKVM heap top-up --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] mm: memcg accounting bypass for pkvm_hyp_vcpu in pKVM heap top-up --

commit 21d00ea4fd8fbddce7df56c53bb28890af94ad7f
Author: Vincent Donnefort <[email protected]>

KVM: arm64: Alloc pkvm_hyp_vcpu using pKVM heap allocator

This commit transitions the allocation of the hypervisor vCPU state structure to EL2 using the new pKVM heap allocator. The host now uses pkvm_call_hyp_req() to invoke __pkvm_create_hyp_vcpu, handling any EL2 memory top-ups automatically.

Quoted 4 lines
arch/arm64/kvm/pkvm.c +0 -0
index 8505965dbfb21..36e677e51f7d6 100644

[ ... ]

Quoted 7 lines
arch/arm64/kvm/pkvm.c +0 -2
@@ -174,28 +174,19 @@ static void __pkvm_destroy_hyp_vm(struct kvm *kvm)
 
 static int __pkvm_create_hyp_vcpu(struct kvm_vcpu *vcpu)
 {
-	size_t hyp_vcpu_sz = PAGE_ALIGN(PKVM_HYP_VCPU_SIZE);
 	pkvm_handle_t handle = vcpu->kvm->arch.pkvm.handle;
-	void *hyp_vcpu;

arch/arm64/kvm/pkvm.c static void __pkvm_destroy_hyp_vm(struct kvm *kvm) · line 182

Quoted 10 lines
arch/arm64/kvm/pkvm.c +1 -5
 	int ret;
 
 	init_hyp_stage2_memcache(&vcpu->arch.pkvm_memcache);
 
-	hyp_vcpu = alloc_pages_exact(hyp_vcpu_sz, GFP_KERNEL_ACCOUNT);
-	if (!hyp_vcpu)
-		return -ENOMEM;
-
-	ret = kvm_call_hyp_nvhe(__pkvm_init_vcpu, handle, vcpu, hyp_vcpu);
+	ret = pkvm_call_hyp_req(__pkvm_init_vcpu, handle, vcpu);

[Severity: Medium]
Does this replace an accounted host allocation with an unaccounted EL2 top-up?

Previously, pkvm_hyp_vcpu was allocated directly by the host using GFP_KERNEL_ACCOUNT. Now, it triggers an EL2 allocation which, if it runs out of memory, requests a top-up via PKVM_HYP_REQ_HYP_ALLOC.

The host handles this top-up request in pkvm_hyp_topup() using:

	init_hyp_memcache(&mc);
	ret = topup_hyp_memcache(&mc, nr_pages);

Because init_hyp_memcache() initializes mc->flags to 0, it omits the HYP_MEMCACHE_ACCOUNT_KMEMCG flag. This causes the allocation in hyp_mc_alloc_fn() to use GFP_KERNEL instead of GFP_KERNEL_ACCOUNT:

	gfp = memcache->flags & HYP_MEMCACHE_ACCOUNT_KMEMCG ?
		GFP_KERNEL_ACCOUNT : GFP_KERNEL;

Can an unprivileged userspace attacker exploit this by repeatedly creating KVM virtual machines and vCPUs to bypass memory cgroup limits and exhaust host memory?

Quoted 7 lines
arch/arm64/kvm/pkvm.c +0 -2
 	if (!ret)
 		vcpu_set_flag(vcpu, VCPU_PKVM_FINALIZED);
-	else
-		free_pages_exact(hyp_vcpu, hyp_vcpu_sz);
 
 	return ret;
 }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
#20 lore raw

PATCH v6 15/18 KVM: arm64: Rename vCPU pkvm_memcache to stage2_mc

In reply to Vincent Donnefort

With the introduction of the pKVM hyp allocator, the memcache for vCPUs is now only used for carrying pages dedicated to the stage-2 page tables. Rename pkvm_memcache to stage2_mc to reflect its purpose.

---
 arch/arm64/include/asm/kvm_host.h     |  4 ++--
 arch/arm64/kvm/arm.c                  |  2 +-
 arch/arm64/kvm/hyp/nvhe/hyp-main.c    |  6 +++---
 arch/arm64/kvm/hyp/nvhe/mem_protect.c | 10 +++++-----
 arch/arm64/kvm/hyp/nvhe/pkvm.c        |  6 +++---
 arch/arm64/kvm/mmu.c                  |  2 +-
 arch/arm64/kvm/pkvm.c                 |  2 +-
 7 files changed, 16 insertions(+), 16 deletions(-)
arch/arm64/include/asm/kvm_host.h +2 -2
index 3cca9f3b2eeb..0c4498a2f30d 100644
@@ -937,8 +937,8 @@ struct kvm_vcpu_arch {
 	/* Cache some mmu pages needed inside spinlock regions */
 	struct kvm_mmu_memory_cache mmu_page_cache;
 
-	/* Pages to top-up the pKVM/EL2 guest pool */
-	struct kvm_hyp_memcache pkvm_memcache;
+	/* Pages to top-up the pKVM/EL2 guest stage-2 pool */
+	struct kvm_hyp_memcache stage2_mc;
 
 	/* Virtual SError ESR to restore when HCR_EL2.VSE is set */
 	u64 vsesr_el2;
arch/arm64/kvm/arm.c +1 -1
index 09ae5431ce58..fa77abf8cff6 100644
@@ -591,7 +591,7 @@ void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
 	if (!is_protected_kvm_enabled())
 		kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_cache);
 	else
-		free_hyp_memcache(&vcpu->arch.pkvm_memcache);
+		free_hyp_memcache(&vcpu->arch.stage2_mc);
 	kvm_timer_vcpu_terminate(vcpu);
 	kvm_pmu_vcpu_destroy(vcpu);
 	kvm_vgic_vcpu_destroy(vcpu);
arch/arm64/kvm/hyp/nvhe/hyp-main.c +3 -3
index 281d1359606a..af348e008f52 100644
@@ -464,9 +464,9 @@ static int pkvm_refill_memcache(struct pkvm_hyp_vcpu *hyp_vcpu)
 {
 	struct kvm_vcpu *host_vcpu = hyp_vcpu->host_vcpu;
 
-	return refill_memcache(&hyp_vcpu->vcpu.arch.pkvm_memcache,
-			       host_vcpu->arch.pkvm_memcache.nr_pages,
-			       &host_vcpu->arch.pkvm_memcache);
+	return refill_memcache(&hyp_vcpu->vcpu.arch.stage2_mc,
+			       host_vcpu->arch.stage2_mc.nr_pages,
+			       &host_vcpu->arch.stage2_mc);
 }
 
 DEFINE_KVM_HOST_HCALL(int, __pkvm_host_donate_guest,
arch/arm64/kvm/hyp/nvhe/mem_protect.c +5 -5
index 39aa8911f62c..dadd48431036 100644
@@ -1023,7 +1023,7 @@ int __pkvm_guest_share_host(struct pkvm_hyp_vcpu *vcpu, u64 gfn)
 	ret = 0;
 	WARN_ON(kvm_pgtable_stage2_map(&vm->pgt, ipa, PAGE_SIZE, phys,
 				       pkvm_mkstate(KVM_PGTABLE_PROT_RWX, PKVM_PAGE_SHARED_OWNED),
-				       &vcpu->vcpu.arch.pkvm_memcache, 0));
+				       &vcpu->vcpu.arch.stage2_mc, 0));
 	WARN_ON(__host_set_page_state_range(phys, PAGE_SIZE, PKVM_PAGE_SHARED_BORROWED));
 unlock:
 	guest_unlock_component(vm);
@@ -1058,7 +1058,7 @@ int __pkvm_guest_unshare_host(struct pkvm_hyp_vcpu *vcpu, u64 gfn)
 						      PKVM_ID_GUEST, meta));
 	WARN_ON(kvm_pgtable_stage2_map(&vm->pgt, ipa, PAGE_SIZE, phys,
 				       pkvm_mkstate(KVM_PGTABLE_PROT_RWX, PKVM_PAGE_OWNED),
-				       &vcpu->vcpu.arch.pkvm_memcache, 0));
+				       &vcpu->vcpu.arch.stage2_mc, 0));
 unlock:
 	guest_unlock_component(vm);
 	host_unlock_component();
@@ -1422,7 +1422,7 @@ static int __guest_check_pgtable_memcache(struct pkvm_hyp_vcpu *vcpu)
 {
 	struct pkvm_hyp_vm *vm = pkvm_hyp_vcpu_to_hyp_vm(vcpu);
 
-	if (vcpu->vcpu.arch.pkvm_memcache.nr_pages < kvm_mmu_cache_min_pages(vm->pgt.mmu))
+	if (vcpu->vcpu.arch.stage2_mc.nr_pages < kvm_mmu_cache_min_pages(vm->pgt.mmu))
 		return -ENOMEM;
 
 	return 0;
@@ -1456,7 +1456,7 @@ int __pkvm_host_donate_guest(u64 pfn, u64 gfn, struct pkvm_hyp_vcpu *vcpu)
 						      PKVM_ID_GUEST, meta));
 	WARN_ON(kvm_pgtable_stage2_map(&vm->pgt, ipa, PAGE_SIZE, phys,
 				       pkvm_mkstate(KVM_PGTABLE_PROT_RWX, PKVM_PAGE_OWNED),
-				       &vcpu->vcpu.arch.pkvm_memcache, 0));
+				       &vcpu->vcpu.arch.stage2_mc, 0));
 
 unlock:
 	guest_unlock_component(vm);
@@ -1527,7 +1527,7 @@ int __pkvm_host_share_guest(u64 pfn, u64 gfn, u64 nr_pages, struct pkvm_hyp_vcpu
 
 	WARN_ON(kvm_pgtable_stage2_map(&vm->pgt, ipa, size, phys,
 				       pkvm_mkstate(prot, PKVM_PAGE_SHARED_BORROWED),
-				       &vcpu->vcpu.arch.pkvm_memcache, 0));
+				       &vcpu->vcpu.arch.stage2_mc, 0));
 
 unlock:
 	guest_unlock_component(vm);
arch/arm64/kvm/hyp/nvhe/pkvm.c +3 -3
index 5031ef9e6fe9..599488b6d124 100644
@@ -774,7 +774,7 @@ struct pkvm_hyp_vcpu *init_selftest_vm(void *virt)
 			continue;
 		p[i].refcount = 1;
 		if (seeded < min_pages) {
-			push_hyp_memcache(&selftest_vcpu.vcpu.arch.pkvm_memcache,
+			push_hyp_memcache(&selftest_vcpu.vcpu.arch.stage2_mc,
 					  hyp_page_to_virt(&p[i]), hyp_virt_to_phys);
 			seeded++;
 		} else {
@@ -1009,7 +1009,7 @@ int __pkvm_finalize_teardown_vm(pkvm_handle_t handle)
 	reclaim_pgtable_pages(hyp_vm, stage2_mc);
 	unpin_host_vcpus(hyp_vm->vcpus, hyp_vm->kvm.created_vcpus);
 
-	/* Push the metadata pages to the teardown memcache */
+	/* Push the stage-2 pages to the teardown memcache */
 	for (idx = 0; idx < hyp_vm->kvm.created_vcpus; ++idx) {
 		struct pkvm_hyp_vcpu *hyp_vcpu = hyp_vm->vcpus[idx];
 		struct kvm_hyp_memcache *vcpu_mc;
@@ -1017,7 +1017,7 @@ int __pkvm_finalize_teardown_vm(pkvm_handle_t handle)
 		if (!hyp_vcpu)
 			continue;
 
-		vcpu_mc = &hyp_vcpu->vcpu.arch.pkvm_memcache;
+		vcpu_mc = &hyp_vcpu->vcpu.arch.stage2_mc;
 
 		while (vcpu_mc->nr_pages) {
 			void *addr = pop_hyp_memcache(vcpu_mc, hyp_phys_to_virt);
arch/arm64/kvm/mmu.c +1 -1
index 3163502cc7d2..afde0894ab15 100644
@@ -1553,7 +1553,7 @@ static void *get_mmu_memcache(struct kvm_vcpu *vcpu)
 	if (!is_protected_kvm_enabled())
 		return &vcpu->arch.mmu_page_cache;
 	else
-		return &vcpu->arch.pkvm_memcache;
+		return &vcpu->arch.stage2_mc;
 }
 
 static int topup_mmu_memcache(struct kvm_vcpu *vcpu, void *memcache)
arch/arm64/kvm/pkvm.c +1 -1
index 36e677e51f7d..83e18c0e30b5 100644
@@ -182,7 +182,7 @@ static int __pkvm_create_hyp_vcpu(struct kvm_vcpu *vcpu)
 	pkvm_handle_t handle = vcpu->kvm->arch.pkvm.handle;
 	int ret;
 
-	init_hyp_stage2_memcache(&vcpu->arch.pkvm_memcache);
+	init_hyp_stage2_memcache(&vcpu->arch.stage2_mc);
 
 	ret = pkvm_call_hyp_req(__pkvm_init_vcpu, handle, vcpu);
 	if (!ret)
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#21 lore raw

PATCH v6 16/18 KVM: arm64: Reject hyp trace descriptors with fewer CPUs than hyp_nr_cpus

In reply to Vincent Donnefort

While a trace descriptor with fewer CPUs than hyp_nr_cpus currently causes no functional issue, such a configuration is invalid and would cause the hypervisor to skip ring buffer initialization when allocating backing pages in EL2.

Enforce nr_cpus == hyp_nr_cpus during trace descriptor validation to guarantee that every possible CPU has a valid ring buffer descriptor.

---
 arch/arm64/kvm/hyp/nvhe/trace.c | 3 +++
 1 file changed, 3 insertions(+)
arch/arm64/kvm/hyp/nvhe/trace.c +3 -0
index 47680a949f61..e9e584694506 100644
@@ -181,6 +181,9 @@ static bool hyp_trace_desc_is_valid(struct hyp_trace_desc *desc, size_t desc_siz
 	desc_end = (void *)desc + desc_size;
 	nr_bpages = desc->bpages_backing_size / sizeof(struct simple_buffer_page);
 
+	if (desc->trace_buffer_desc.nr_cpus != hyp_nr_cpus)
+		return false;
+
 	for_each_ring_buffer_desc(rb_desc, cpu, &desc->trace_buffer_desc) {
 		/* Can we read nr_page_va? */
 		if ((void *)rb_desc + struct_size(rb_desc, page_va, 0) > desc_end)
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#22 lore raw

PATCH v6 17/18 KVM: arm64: Reject hyp trace descriptors with fewer than 3 pages

In reply to Vincent Donnefort

A trace descriptor with 0 nr_page_va allocates a 0-size bpages backing region, which makes the ring buffer appear unloaded. Reject descriptors with nr_page_va < 3 in hyp_trace_desc_is_valid() as this is in any case the lower-limit for simple_ring_buffer.

---
 arch/arm64/kvm/hyp/nvhe/trace.c | 4 ++++
 1 file changed, 4 insertions(+)
arch/arm64/kvm/hyp/nvhe/trace.c +4 -0
index e9e584694506..7acb81ae0e6a 100644
@@ -189,6 +189,10 @@ static bool hyp_trace_desc_is_valid(struct hyp_trace_desc *desc, size_t desc_siz
 		if ((void *)rb_desc + struct_size(rb_desc, page_va, 0) > desc_end)
 			return false;
 
+		/* simple_ring_buffer_init_mm() expects at least 3 pages */
+		if (rb_desc->nr_page_va < 3)
+			return false;
+
 		/* Overflow desc? */
 		if ((void *)rb_desc + struct_size(rb_desc, page_va, rb_desc->nr_page_va) > desc_end)
 			return false;
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#23 lore raw

PATCH v6 18/18 KVM: arm64: Alloc simple_buffer_page using pKVM hyp allocator

In reply to Vincent Donnefort

In protected mode, transition the allocation of the simple_ring_buffer structures from the host to the hypervisor using the new pKVM heap allocator.

Previously, the host allocated and donated a contiguous backing memory for these structures. In pKVM the hypervisor can now allocate them dynamically.

Use the pkvm_call_hyp_req() wrapper in the host to invoke __tracing_load, which automatically handles any top-up requests if the hypervisor runs out of heap memory during allocation.

---
 arch/arm64/kvm/hyp/nvhe/hyp-main.c |  2 +-
 arch/arm64/kvm/hyp/nvhe/trace.c    | 63 +++++++++++++++++-------------
 arch/arm64/kvm/hyp_trace.c         | 15 ++++++-
 3 files changed, 50 insertions(+), 30 deletions(-)
arch/arm64/kvm/hyp/nvhe/hyp-main.c +1 -1
index af348e008f52..7a6435725dfe 100644
@@ -907,7 +907,7 @@ DEFINE_KVM_HOST_HCALL(ulong, __pkvm_hyp_reclaimable,
 DEFINE_KVM_HOST_HCALL(int, __tracing_load,
 	void __kern *, desc_hva, size_t, desc_size)
 {
-	return __tracing_load(desc_hva, desc_size);
+	return errno_to_smccc(__tracing_load(desc_hva, desc_size));
 }
 
 DEFINE_KVM_HOST_HCALL0(void, __tracing_unload)
arch/arm64/kvm/hyp/nvhe/trace.c +36 -27

125 lines not on this page · raw message

arch/arm64/kvm/hyp_trace.c +13 -2
index 44937e257375..5bc881d6f343 100644
@@ -13,6 +13,7 @@
 #include <asm/kvm_host.h>
 #include <asm/kvm_hyptrace.h>
 #include <asm/kvm_mmu.h>
+#include <asm/kvm_pkvm.h>
 
 #include "hyp_trace.h"
 
@@ -151,11 +152,18 @@ static void __unshare_page(unsigned long va)
 
 static int hyp_trace_buffer_alloc_bpages_backing(struct hyp_trace_buffer *trace_buffer, size_t size)
 {
-	int nr_bpages = (PAGE_ALIGN(size) / PAGE_SIZE) + 1;
 	size_t backing_size;
+	int nr_bpages;
 	void *start;
 	int ret;
 
+	if (is_protected_kvm_enabled()) {
+		trace_buffer->desc->bpages_backing_start = 0;
+		trace_buffer->desc->bpages_backing_size = 0;
+		return 0;
+	}
+
+	nr_bpages = (PAGE_ALIGN(size) / PAGE_SIZE) + 1;
 	backing_size = PAGE_ALIGN(sizeof(struct simple_buffer_page) * nr_bpages *
 				  num_possible_cpus());
 
@@ -177,6 +185,9 @@ static int hyp_trace_buffer_alloc_bpages_backing(struct hyp_trace_buffer *trace_
 
 static void hyp_trace_buffer_free_bpages_backing(struct hyp_trace_buffer *trace_buffer)
 {
+	if (!trace_buffer->desc->bpages_backing_start)
+		return;
+
 	free_pages_exact((void *)trace_buffer->desc->bpages_backing_start,
 			 trace_buffer->desc->bpages_backing_size);
 }
@@ -269,7 +280,7 @@ static struct trace_buffer_desc *hyp_trace_load(unsigned long size, void *priv)
 	if (ret)
 		goto err_free_buffer;
 
-	ret = kvm_call_hyp_nvhe(__tracing_load, desc, desc_size);
+	ret = pkvm_call_hyp_req(__tracing_load, desc, desc_size);
 	if (ret)
 		goto err_unload_pages;
 
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
maintainer Applied
#24 lore raw
In reply to Vincent Donnefort
Quoted 9 lines · Vincent Donnefort

pKVM historically lacked a dynamic memory allocator: all hypervisor-side VM and VCPU structures had to be sized on the host, allocated as contiguous pages and donated to the hypervisor.

This design tightly coupled the hypervisor's memory footprint to host-side constraints, complicated memory reclaim, and severely restricted VM scalability.

[...]

Applied to next, thanks!

[01/18] KVM: arm64: Add pkvm_private_va_range_pa

        commit: 4b66a1941718ef1c945b32ab28e91330e4394de2
[02/18] KVM: arm64: Add pkvm_remove_mappings
        commit: 64a89873e0c60fd8a22ebacab6bc723415eeb4b2
[03/18] KVM: arm64: Add pkvm_map_private_va_range
        commit: 06b705e789ed1a118331bc77f477a9b46c52dcfe
[04/18] KVM: arm64: Add a heap allocator for the pKVM hyp
        commit: c8d7834c9c219a9a0e3969986e90c5c444b9d98d
[05/18] KVM: arm64: Allow kvm_hyp_memcache usage outside of stage-2
        commit: 11a59e2959e63546dd75c347d552193c38aeb37e
[06/18] KVM: arm64: Add pkvm_hyp_req infrastructure
        commit: e868b8c35268a8cb786091c63f538c960b8807e5
[07/18] KVM: arm64: Add PKVM_HYP_REQ_HYP_ALLOC request
        commit: 7bf265fe68af9e1ef3af083d444a72bd3ce3d3e3
[08/18] KVM: arm64: Add reclaim interface for the pKVM heap alloc
        commit: 43759e3c9631ffcec55e4b7396864af4a5b98f30
[09/18] KVM: arm64: Add selftests for the pKVM heap allocator
        commit: bd93068340e9d770d6282ab425b686bef2042394
[10/18] KVM: arm64: Add a shrinker for pKVM
        commit: 909e70fd13567db8247c3850f27b65aaea2c9ad0
[11/18] KVM: arm64: Filter out non-kernel addresses in kern_hyp_va
        commit: 0b27ba187dde3170a312904f18595f3ba266bcae
[12/18] KVM: arm64: Move hyp_vm refcount into the structure
        commit: 85406921dc81ea7ccfb78c92cf79b0a4bcd2439c
[13/18] KVM: arm64: Alloc pkvm_hyp_vm using pKVM heap allocator
        commit: 324397c85d1dde38e5d4805d8b79bfc549af4252
[14/18] KVM: arm64: Alloc pkvm_hyp_vcpu using pKVM heap allocator
        commit: e188a901e4bc585a170ee4235c6b55ebcf07b592
[15/18] KVM: arm64: Rename vCPU pkvm_memcache to stage2_mc
        commit: 197dac8a9060c17988414086293aa8ed4c82c185
[16/18] KVM: arm64: Reject hyp trace descriptors with fewer CPUs than hyp_nr_cpus
        commit: cf9cf059b8f30ffca78c16e6a51c905c95da47a8
[17/18] KVM: arm64: Reject hyp trace descriptors with fewer than 3 pages
        commit: 086f86286b5e060904bd372ad96edd04c366885a
[18/18] KVM: arm64: Alloc simple_buffer_page using pKVM hyp allocator
        commit: 35dc2dd00334555eb02428cff2302a1cfe60c15f

Std disclaimer: conflict-central even with the rebase, please check the result.

Cheers,

	M.
Signature · 1 line
Without deviation from the norm, progress is not possible.