Skip to contentSkip to conversation

KVM: arm64: CCA: Prepare Realm memory management

PATCH Superseded Steven Price 6 participants 43 messages Nov 23 – Nov 30

Subsystems (4)

v4 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#0 lore raw

v4 cover KVM: arm64: CCA: Prepare Realm memory management

This series adds the memory management plumbing for CCA, building on the basic RMM support [1]. Thanks to everyone who reviewed and tested the earlier versions.

The patches introduce internal Realm VM state, prepare Realm stage-2 setup and teardown, and provide RTT mapping and invalidation helpers. Realm memslots are restricted to the lower half of the IPA space because the protected and shared halves alias each other. The final patch connects the helpers to KVM's stage-2 MMU operations.

This is the memory management portion of the larger Realm host series. Realm descriptor creation, REC entry and exit, activation, and the new uAPI follow in the integration stack. This series alone does not enable Realm creation.

The integration branch [2] includes Realm creation, REC entry and exit, and the remaining host support on top of this series. The MM branch [3] contains just this series.

Changes since v3:
- Keep pKVM-specific protected VM handling in the nVHE path and move stage-2 destruction dispatch before basic Realm infrastructure.
- Derive the Realm RTT start level from VTCR, matching KVM's minimum two-level stage-2 layout for narrow IPAs on 64K-page hosts.
- Split Realm guest_memfd and userspace-backed faults into dedicated paths, leaving the native fault handlers unchanged.
- Unmap earlier shared mappings when a later RMI map call fails.
- Clarify the early memslot validation rationale and the arm64-wide effect of in-place guest_memfd conversion.

Changes since v2:
- Move RMM mode reservation and RMI availability and feature checks to the integration stack.
- Require mmap-capable guest_memfd backing for all arm64 VMs and route all guest_memfd faults through gmem_abort().
- Store the Realm Descriptor physical address from initial Realm setup, and improve SRO cleanup and RTT teardown error handling.
- Use a local MMU cache for RTT invalidation, handle failed splits, and validate returned RTT levels.
- Bound protected RMI mapping calls to the encoded range and tighten RTT creation, retry, and error handling.
- Split common stage-2 destruction dispatch into its own patch before registering the Realm stage-2 MMU operations.

Changes since v1:
- Add a guest_memfd prerequisite patch that checks whether the backing file supports mmap when preparing an arm64 memslot.
- Combine the RMI availability and feature checks into one patch, and move Realm vCPU feature restrictions to the integration stack.
- Correct Realm IPA sizing and RTT teardown, including teardown before activation, RTT accounting, and handling of missing or folded RTTs.
- Rework RTT mapping to respect IPA and physical alignment, handle partial RMI progress, and retry interrupted operations.
- Preserve private mappings when a Realm guest_memfd memslot deletion is rejected, and tighten Realm fault handling and stage-2 destruction.

[1] https://lore.kernel.org/all/[email protected]/
[2] https://gitlab.arm.com/linux-arm/linux-cca
branch: cca-host-mm/v4/integration
[3] https://gitlab.arm.com/linux-arm/linux-cca
branch: cca-host-mm/v4/mm

Steven Price (6):
KVM: arm64: guest_memfd: Check mmap support when preparing memslot
KVM: arm64: Dispatch stage-2 destruction by VM flavor
KVM: arm64: CCA: Add basic infrastructure for creating a realm
KVM: arm64: CCA: Destroy RTTs
KVM: arm64: CCA: Add Realm RTT mapping and invalidation helpers
KVM: arm64: CCA: Support runtime faulting of memory

Suzuki K Poulose (5):
KVM: arm64: CCA: Introduce Realms
KVM: arm64: Pass range filter to stage2_unmap_range
KVM: Allow architectures to reject memslot changes before invalidation
KVM: arm64: CCA: Prevent memslot modifications after Realm creation
KVM: arm64: CCA: Add Realm stage-2 MMU operations

 arch/arm64/include/asm/kvm_emulate.h |  29 +
 arch/arm64/include/asm/kvm_host.h    |  27 +-
 arch/arm64/include/asm/kvm_mmu.h     |   4 +-
 arch/arm64/include/asm/kvm_rmi.h     | 105 +++
 arch/arm64/kvm/Kconfig               |   1 +
 arch/arm64/kvm/Makefile              |   2 +-
 arch/arm64/kvm/arm.c                 |  13 +-
 arch/arm64/kvm/mmu.c                 | 368 +++++++++--
 arch/arm64/kvm/pkvm.c                |   4 +-
 arch/arm64/kvm/psci.c                |   3 +-
 arch/arm64/kvm/rmi.c                 | 930 +++++++++++++++++++++++++++
 drivers/firmware/arm_rmm/rmi.c       |  10 -
 include/linux/arm-rmi-cmds.h         |   8 +
 include/linux/kvm_host.h             |   5 +
 virt/kvm/guest_memfd.c               |   6 +
 virt/kvm/kvm_main.c                  |  33 +-
 16 files changed, 1471 insertions(+), 77 deletions(-)
 create mode 100644 arch/arm64/include/asm/kvm_rmi.h
 create mode 100644 arch/arm64/kvm/rmi.c
Signature · 1 line
2.43.0
#1 lore raw

PATCH v4 1/11 KVM: arm64: guest_memfd: Check mmap support when preparing memslot

Arm64 requires mmap-capable guest_memfd backing because the memslot HVA may still be used to access shared memory even when guest faults use guest_memfd.

The existing check rejects guest_memfd without mmap support based on the memslot's gmem-only flag. That stops working when arm64 defines kvm_arch_has_private_mem() for realms: in-place conversion then marks all guest_memfd memslots gmem-only, including those backed by files without GUEST_MEMFD_FLAG_MMAP. Such files would pass the existing check.

Check the backing file's mmap capability directly to keep requiring it for every arm64 VM. Expose a helper to reuse kvm_gmem_supports_mmap().

---
Changes since v3:
- Explain why in-place conversion makes checking the memslot's gmem-only flag insufficient for arm64.

Changes since v2:
- Require mmap-capable guest_memfd backing for all arm64 VMs, as shared-memory access can use the memslot HVA.

Changes since v1:
- New patch in v2. Check the guest_memfd backing file rather than the memslot flag when deciding whether arm64 can map the backing memory.

---
 arch/arm64/kvm/mmu.c     | 6 +++---
 include/linux/kvm_host.h | 1 +
 virt/kvm/guest_memfd.c   | 6 ++++++
 3 files changed, 10 insertions(+), 3 deletions(-)
arch/arm64/kvm/mmu.c +3 -3
index 1db10d8d6db7..2825fccd2a19 100644
@@ -2839,10 +2839,10 @@ int kvm_arch_prepare_memory_region(struct kvm *kvm,
 		return -EFAULT;
 
 	/*
-	 * Only support guest_memfd backed memslots with mappable memory, since
-	 * there aren't any CoCo VMs that support only private memory on arm64.
+	 * All VMs need mappable guest_memfd memory, as the memslot's HVA may be
+	 * used to access shared memory even if guest faults use guest_memfd.
 	 */
-	if (kvm_slot_has_gmem(new) && !kvm_memslot_is_gmem_only(new))
+	if (kvm_slot_has_gmem(new) && !kvm_gmem_slot_supports_mmap(new))
 		return -EINVAL;
 
 	/* guest_memfd is incompatible with MTE. */
include/linux/kvm_host.h +1 -0
index e7fc94e2910a..f65728a713ec 100644
@@ -2614,6 +2614,7 @@ static inline bool kvm_is_private_gfn(struct kvm *kvm, gfn_t gfn)
 
 #ifdef CONFIG_KVM_GUEST_MEMFD
 bool kvm_gmem_is_private_gfn(struct kvm *kvm, gfn_t gfn);
+bool kvm_gmem_slot_supports_mmap(const struct kvm_memory_slot *slot);
 bool kvm_arch_supports_gmem_init_shared(struct kvm *kvm);
 
 static inline u64 kvm_gmem_get_supported_flags(struct kvm *kvm)
virt/kvm/guest_memfd.c +6 -0
index 8c97a69b16dc..3dd8d227bebb 100644
@@ -442,6 +442,12 @@ static bool kvm_gmem_supports_mmap(struct inode *inode)
 	return GMEM_I(inode)->flags & GUEST_MEMFD_FLAG_MMAP;
 }
 
+bool kvm_gmem_slot_supports_mmap(const struct kvm_memory_slot *slot)
+{
+	/* The guest_memfd file is pinned while preparing a new memslot. */
+	return kvm_gmem_supports_mmap(file_inode(slot->gmem.file));
+}
+
 static vm_fault_t kvm_gmem_fault_user_mapping(struct vm_fault *vmf)
 {
 	struct inode *inode = file_inode(vmf->vma->vm_file);
Signature · 1 line
2.43.0
#2 lore raw

Re: [PATCH v4 01/11] KVM: arm64: guest_memfd: Check mmap support when preparing memslot

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] KVM: arm64: kvm_arch_prepare_memory_region() rejects non-mmap guest_memfd --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] KVM: arm64: kvm_arch_prepare_memory_region() rejects non-mmap guest_memfd
--

commit a0665f8dc612d05686ef019cc8462841573fe88c
Author: Steven Price <[email protected]>

KVM: arm64: guest_memfd: Check mmap support when preparing memslot

This commit introduces kvm_gmem_slot_supports_mmap() and uses it in kvm_arch_prepare_memory_region() to require that all guest_memfd-backed memslots on arm64 come from files created with GUEST_MEMFD_FLAG_MMAP.

Quoted 8 lines
arch/arm64/kvm/mmu.c +0 -0
index 1db10d8d6db73..2825fccd2a197 100644
@@ -2839,10 +2839,10 @@ int kvm_arch_prepare_memory_region(struct kvm *kvm,
 		return -EFAULT;
 
 	/*

arch/arm64/kvm/mmu.c int kvm_arch_prepare_memory_region(struct kvm *kvm, · line 2848

Quoted 10 lines
arch/arm64/kvm/mmu.c +3 -3
-	 * Only support guest_memfd backed memslots with mappable memory, since
-	 * there aren't any CoCo VMs that support only private memory on arm64.
+	 * All VMs need mappable guest_memfd memory, as the memslot's HVA may be
+	 * used to access shared memory even if guest faults use guest_memfd.
 	 */
-	if (kvm_slot_has_gmem(new) && !kvm_memslot_is_gmem_only(new))
+	if (kvm_slot_has_gmem(new) && !kvm_gmem_slot_supports_mmap(new))
 		return -EINVAL;
 
 	/* guest_memfd is incompatible with MTE. */

[Severity: Medium]
As reported by Suzuki K Poulose on v2 [1], should kvm_arch_prepare_memory_region() drop this guest_memfd check altogether rather than rejecting memslots backed by a guest_memfd created without GUEST_MEMFD_FLAG_MMAP?

Both gmem_abort() and realm_gmem_abort() fault in guest_memfd pages via kvm_gmem_get_pfn() without using new->userspace_addr, and kvm_arch_prepare_memory_region() does not verify that new->userspace_addr maps the guest_memfd or any valid VMA. Requiring GUEST_MEMFD_FLAG_MMAP here fails KVM_SET_USER_MEMORY_REGION2 with -EINVAL for VMs (such as Realms) that bind private-only guest_memfd instances without allowing host userspace mmap, and on v3 the guest_memfd maintainer noted that this check is unnecessary and should be removed rather than exposing kvm_gmem_slot_supports_mmap().

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

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

Re: [PATCH v4 01/11] KVM: arm64: guest_memfd: Check mmap support when preparing memslot

Quoted 40 lines · [email protected] writes:

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] KVM: arm64: kvm_arch_prepare_memory_region() rejects non-mmap guest_memfd
--

commit a0665f8dc612d05686ef019cc8462841573fe88c
Author: Steven Price <[email protected]>

KVM: arm64: guest_memfd: Check mmap support when preparing memslot

This commit introduces kvm_gmem_slot_supports_mmap() and uses it in kvm_arch_prepare_memory_region() to require that all guest_memfd-backed memslots on arm64 come from files created with GUEST_MEMFD_FLAG_MMAP.

Quoted 8 lines
arch/arm64/kvm/mmu.c +0 -0
index 1db10d8d6db73..2825fccd2a197 100644
@@ -2839,10 +2839,10 @@ int kvm_arch_prepare_memory_region(struct kvm *kvm,
 		return -EFAULT;
 
 	/*

arch/arm64/kvm/mmu.c int kvm_arch_prepare_memory_region(struct kvm *kvm, · line 2848

Quoted 10 lines
arch/arm64/kvm/mmu.c +3 -3
-	 * Only support guest_memfd backed memslots with mappable memory, since
-	 * there aren't any CoCo VMs that support only private memory on arm64.
+	 * All VMs need mappable guest_memfd memory, as the memslot's HVA may be
+	 * used to access shared memory even if guest faults use guest_memfd.
 	 */
-	if (kvm_slot_has_gmem(new) && !kvm_memslot_is_gmem_only(new))
+	if (kvm_slot_has_gmem(new) && !kvm_gmem_slot_supports_mmap(new))
 		return -EINVAL;
 
 	/* guest_memfd is incompatible with MTE. */

[Severity: Medium]
As reported by Suzuki K Poulose on v2 [1], should kvm_arch_prepare_memory_region() drop this guest_memfd check altogether rather than rejecting memslots backed by a guest_memfd created without GUEST_MEMFD_FLAG_MMAP?

Quoted 10 lines

Both gmem_abort() and realm_gmem_abort() fault in guest_memfd pages via kvm_gmem_get_pfn() without using new->userspace_addr, and kvm_arch_prepare_memory_region() does not verify that new->userspace_addr maps the guest_memfd or any valid VMA. Requiring GUEST_MEMFD_FLAG_MMAP here fails KVM_SET_USER_MEMORY_REGION2 with -EINVAL for VMs (such as Realms) that bind private-only guest_memfd instances without allowing host userspace mmap, and on v3 the guest_memfd maintainer noted that this check is unnecessary and should be removed rather than exposing kvm_gmem_slot_supports_mmap().

I agree with Sashiko here. I traced the history of this check:

    if (kvm_slot_has_gmem(new) && !kvm_memslot_is_gmem_only(new))
        return -EINVAL;

In [1], Arm64 guest_memfd enablement, !kvm_memslot_is_gmem_only(new) meant "this guest_memfd does not support mmap()". Arm64 had no CoCo private-memory VMs yet, so guest_memfd was only usable for shared memory where the host VMM needed mmap() to access guest RAM. Rejecting non-mappable guest_memfd slots prevented unusable private-only memslots.

In [2], pKVM support was added. The v1 of [2], [3], says pKVM uses anonymous memory. pKVM doesn't really specifically use gmem, so there's actually no change, this check doesn't really affect pKVM.

Conversions [4] made stage 2 faults (mostly on x86), always get memory from gmem. On arm, as long as it is a gmem memslot, it already always got memory from gmem.

Now that ARM CCA supports private memory, we should drop this check completely, I think David noted that right when it was added [5], and that's what Sean means too [6].

If userspace sets up gmem with a memslot and doesn't set up mmap, userspace probably won't be able to set up a running ARM CCA VM, but that's userspace's bug imo.

Imo even back in [1] perhaps the check didn't need to be added, it's just a userspace bug to try and set up a memslot with gmem that can't really be used.

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/[email protected]/
[4] https://lore.kernel.org/all/[email protected]/
[5] https://lore.kernel.org/all/[email protected]/
[6] https://lore.kernel.org/all/[email protected]/

Quoted 4 lines

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

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

#4 lore raw

Re: [PATCH v4 01/11] KVM: arm64: guest_memfd: Check mmap support when preparing memslot

Quoted 76 lines · Ackerley Tng
Quoted 40 lines · [email protected] writes:

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] KVM: arm64: kvm_arch_prepare_memory_region() rejects non-mmap guest_memfd
--

commit a0665f8dc612d05686ef019cc8462841573fe88c
Author: Steven Price <[email protected]>

KVM: arm64: guest_memfd: Check mmap support when preparing memslot

This commit introduces kvm_gmem_slot_supports_mmap() and uses it in kvm_arch_prepare_memory_region() to require that all guest_memfd-backed memslots on arm64 come from files created with GUEST_MEMFD_FLAG_MMAP.

Quoted 8 lines
arch/arm64/kvm/mmu.c +0 -0
index 1db10d8d6db73..2825fccd2a197 100644
@@ -2839,10 +2839,10 @@ int kvm_arch_prepare_memory_region(struct kvm *kvm,
 		return -EFAULT;
 
 	/*

arch/arm64/kvm/mmu.c int kvm_arch_prepare_memory_region(struct kvm *kvm, · line 2848

Quoted 10 lines
arch/arm64/kvm/mmu.c +3 -3
-	 * Only support guest_memfd backed memslots with mappable memory, since
-	 * there aren't any CoCo VMs that support only private memory on arm64.
+	 * All VMs need mappable guest_memfd memory, as the memslot's HVA may be
+	 * used to access shared memory even if guest faults use guest_memfd.
 	 */
-	if (kvm_slot_has_gmem(new) && !kvm_memslot_is_gmem_only(new))
+	if (kvm_slot_has_gmem(new) && !kvm_gmem_slot_supports_mmap(new))
 		return -EINVAL;
 
 	/* guest_memfd is incompatible with MTE. */

[Severity: Medium]
As reported by Suzuki K Poulose on v2 [1], should kvm_arch_prepare_memory_region() drop this guest_memfd check altogether rather than rejecting memslots backed by a guest_memfd created without GUEST_MEMFD_FLAG_MMAP?

Quoted 10 lines

Both gmem_abort() and realm_gmem_abort() fault in guest_memfd pages via kvm_gmem_get_pfn() without using new->userspace_addr, and kvm_arch_prepare_memory_region() does not verify that new->userspace_addr maps the guest_memfd or any valid VMA. Requiring GUEST_MEMFD_FLAG_MMAP here fails KVM_SET_USER_MEMORY_REGION2 with -EINVAL for VMs (such as Realms) that bind private-only guest_memfd instances without allowing host userspace mmap, and on v3 the guest_memfd maintainer noted that this check is unnecessary and should be removed rather than exposing kvm_gmem_slot_supports_mmap().

I agree with Sashiko here. I traced the history of this check:

    if (kvm_slot_has_gmem(new) && !kvm_memslot_is_gmem_only(new))
        return -EINVAL;

In [1], Arm64 guest_memfd enablement, !kvm_memslot_is_gmem_only(new) meant "this guest_memfd does not support mmap()". Arm64 had no CoCo private-memory VMs yet, so guest_memfd was only usable for shared memory where the host VMM needed mmap() to access guest RAM. Rejecting non-mappable guest_memfd slots prevented unusable private-only memslots.

In [2], pKVM support was added. The v1 of [2], [3], says pKVM uses anonymous memory. pKVM doesn't really specifically use gmem, so there's actually no change, this check doesn't really affect pKVM.

Conversions [4] made stage 2 faults (mostly on x86), always get memory from gmem. On arm, as long as it is a gmem memslot, it already always got memory from gmem.

Now that ARM CCA supports private memory, we should drop this check completely, I think David noted that right when it was added [5], and that's what Sean means too [6].

Quoted 7 lines

If userspace sets up gmem with a memslot and doesn't set up mmap, userspace probably won't be able to set up a running ARM CCA VM, but that's userspace's bug imo.

Imo even back in [1] perhaps the check didn't need to be added, it's just a userspace bug to try and set up a memslot with gmem that can't really be used.

Ok, thanks for digging through the history. I'm fine with just dropping the check altogether. I had been trying to avoid changing the behaviour of non-realm VMs but if we're agreed that the behaviour can be loosened to allow buggy VMMs to shoot themselves in the foot then that's clearly much easier to maintain.

Thanks,
Steve

Quoted 11 lines

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/[email protected]/
[4] https://lore.kernel.org/all/[email protected]/
[5] https://lore.kernel.org/all/[email protected]/
[6] https://lore.kernel.org/all/[email protected]/

Quoted 4 lines

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

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

#5 lore raw

PATCH v4 2/11 KVM: arm64: CCA: Introduce Realms

In reply to Steven Price

From: Suzuki K Poulose <[email protected]>

Introduce the Realm VM flavor and per-VM state tracking. Realm and protected pKVM states are mutually exclusive, so share their storage in kvm_arch. Adjust the protected VM helpers for the new flavor.

Realm VMs cannot be created yet; RMI initialization and the creation UABI follow in later patches.

---
Changes since v3:
- Keep protected-VM helper semantics specific to pKVM in nVHE, and use VM flavor checks for pKVM power-state handling.

Changes since v1:
- Move RMI initialization to the RMI checks patch and Realm vCPU feature restrictions to the follow-on integration series. Keep this patch focused on the Realm VM flavor and per-VM state.
- Limit pKVM power state handling to pKVM vCPUs.

---
 arch/arm64/include/asm/kvm_emulate.h | 16 ++++++++
 arch/arm64/include/asm/kvm_host.h    | 17 +++++---
 arch/arm64/include/asm/kvm_rmi.h     | 59 ++++++++++++++++++++++++++++
 arch/arm64/kvm/arm.c                 |  4 +-
 arch/arm64/kvm/mmu.c                 |  1 +
 arch/arm64/kvm/pkvm.c                |  2 +-
 arch/arm64/kvm/psci.c                |  3 +-
 7 files changed, 94 insertions(+), 8 deletions(-)
 create mode 100644 arch/arm64/include/asm/kvm_rmi.h
arch/arm64/include/asm/kvm_emulate.h +16 -0
index 334211b8b2ee..32021bdf2610 100644
@@ -831,4 +831,20 @@ static inline void kvm_reset_vcpu_psci(struct kvm_vcpu *vcpu,
 	vcpu_set_reg(vcpu, 0, reset_state->r0);
 }
 
+static inline enum realm_state kvm_realm_state(struct kvm *kvm)
+{
+	return READ_ONCE(kvm->arch.realm.state);
+}
+
+static inline void kvm_set_realm_state(struct kvm *kvm,
+				       enum realm_state new_state)
+{
+	WRITE_ONCE(kvm->arch.realm.state, new_state);
+}
+
+static inline bool kvm_realm_is_created(struct kvm *kvm)
+{
+	return kvm_vm_is_realm(kvm) && kvm_realm_state(kvm) != REALM_STATE_NONE;
+}
+
 #endif /* __ARM64_KVM_EMULATE_H__ */
arch/arm64/include/asm/kvm_host.h +12 -5
index 97332ffcb130..8438251e1d1b 100644
@@ -29,6 +29,7 @@
 #include <asm/kvm.h>
 #include <asm/kvm_asm.h>
 #include <asm/kvm_hcall.h>
+#include <asm/kvm_rmi.h>
 #include <asm/vncr_mapping.h>
 
 #define __KVM_HAVE_ARCH_INTC_INITIALIZED
@@ -408,6 +409,7 @@ enum kvm_arm_vm_flavor {
 	VM_PKVM,		/* Normal guests on pKVM */
 	MARKER(__VM_PROTECTED),
 	VM_PROTECTED_PKVM,	/* Protected VM */
+	VM_REALM,		/* CCA */
 	VM_FLAVOR_MAX
 };
 
@@ -501,11 +503,14 @@ struct kvm_arch {
 	/* Count the number of VNCR_EL2 TLBs */
 	atomic_t vncr_tlb_count;
 
-	/*
-	 * For an untrusted host VM, 'pkvm.handle' is used to lookup
-	 * the associated pKVM instance in the hypervisor.
-	 */
-	struct kvm_protected_vm pkvm;
+	union {
+		/*
+		 * For an untrusted host VM, 'pkvm.handle' is used to lookup
+		 * the associated pKVM instance in the hypervisor.
+		 */
+		struct kvm_protected_vm pkvm;
+		struct realm realm;
+	};
 
 #ifdef CONFIG_PTDUMP_STAGE2_DEBUGFS
 	/* Nested virtualization info */
@@ -1596,6 +1601,8 @@ struct kvm *kvm_arch_alloc_vm(void);
 
 #endif	/* __KVM_NVHE_HYPERVISOR__ */
 
+#define kvm_vm_is_realm(kvm)		((kvm)->arch.vm_flavor == VM_REALM)
+
 #define kvm_has_mte(kvm)					\
 	(system_supports_mte() &&				\
 	 test_bit(KVM_ARCH_FLAG_MTE_ENABLED, &(kvm)->arch.flags))
arch/arm64/include/asm/kvm_rmi.h new file +59 -0

59 lines not on this page · raw message

arch/arm64/kvm/arm.c +3 -1
index 157bf4b81202..d79e5451923d 100644
@@ -877,7 +877,8 @@ static void __kvm_arm_vcpu_power_off(struct kvm_vcpu *vcpu, u32 mp_state)
 /* The guest's own CPU_OFF: EL2 has already powered the vCPU off. */
 void kvm_arm_vcpu_power_off(struct kvm_vcpu *vcpu)
 {
-	u32 mp_state = vcpu_is_protected(vcpu) ? KVM_MP_STATE_UNINITIALIZED : KVM_MP_STATE_STOPPED;
+	u32 mp_state = vcpu->kvm->arch.vm_flavor == VM_PROTECTED_PKVM ?
+		       KVM_MP_STATE_UNINITIALIZED : KVM_MP_STATE_STOPPED;
 
 	spin_lock(&vcpu->arch.mp_state_lock);
 	__kvm_arm_vcpu_power_off(vcpu, mp_state);
@@ -2312,6 +2313,7 @@ static const struct kvm_vcpu_ops *arm64_vcpu_ops[] = {
 	KVM_VCPU_OPS(VM_VHE, vhe_vcpu_ops),
 	KVM_VCPU_OPS(VM_PKVM, pkvm_vcpu_ops),
 	KVM_VCPU_OPS(VM_PROTECTED_PKVM, pkvm_vcpu_ops),
+	[VM_REALM] = NULL,
 };
 
 static void kvm_init_vcpu_ops(struct kvm_vcpu *vcpu)
arch/arm64/kvm/mmu.c +1 -0
index 2825fccd2a19..09c831a49ed3 100644
@@ -3165,6 +3165,7 @@ static const struct kvm_vm_s2_ops *arm64_vm_s2_ops[] = {
 	KVM_VM_S2_OPS(VM_NVHE, kvm_default_vm_s2_ops),
 	KVM_VM_S2_OPS(VM_PKVM, pkvm_vm_s2_ops),
 	KVM_VM_S2_OPS(VM_PROTECTED_PKVM, protected_pkvm_vm_s2_ops),
+	[VM_REALM] = NULL,
 };
 
 static int kvm_vm_init_vm_s2_ops(struct kvm *kvm)
arch/arm64/kvm/pkvm.c +1 -1
index 016997288fd2..8241a05e25d1 100644
@@ -192,7 +192,7 @@ static int __pkvm_create_hyp_vcpu(struct kvm_vcpu *vcpu)
 	 * Mirror EL2's seeding of power_state from mp_state. The hyp vCPU is
 	 * published, so take mp_state_lock against kvm_psci_vcpu_on().
 	 */
-	if (vcpu_is_protected(vcpu)) {
+	if (vcpu->kvm->arch.vm_flavor == VM_PROTECTED_PKVM) {
 		spin_lock(&vcpu->arch.mp_state_lock);
 		if (kvm_arm_vcpu_stopped(vcpu))
 			WRITE_ONCE(vcpu->arch.mp_state.mp_state, KVM_MP_STATE_UNINITIALIZED);
arch/arm64/kvm/psci.c +2 -1
index b01f8d44033f..d14414d66dd5 100644
@@ -68,7 +68,8 @@ static unsigned long kvm_psci_vcpu_on(struct kvm_vcpu *source_vcpu)
 	 * STOPPED before that is the VMM's pause.
 	 */
 	if (!kvm_arm_vcpu_stopped(vcpu) ||
-	    (vcpu_is_protected(vcpu) && !kvm_pkvm_vcpu_is_powered_off(vcpu))) {
+	    (vcpu->kvm->arch.vm_flavor == VM_PROTECTED_PKVM &&
+	     !kvm_pkvm_vcpu_is_powered_off(vcpu))) {
 		if (kvm_psci_version(source_vcpu) != KVM_ARM_PSCI_0_1)
 			ret = PSCI_RET_ALREADY_ON;
 		else
Signature · 1 line
2.43.0
Reviewed-by on v4 2/11
#6 lore raw

Re: [PATCH v4 02/11] KVM: arm64: CCA: Introduce Realms

Hi Suzuki,

On Mon, 23 Nov 2026 10:42:22 +0000, Steven Price <[email protected]> wrote:
[...]

Quoted 3 lines

Introduce the Realm VM flavor and per-VM state tracking. Realm and protected pKVM states are mutually exclusive, so share their storage in kvm_arch. Adjust the protected VM helpers for the new flavor.

nit: this patch no longer changes the helpers, only their pKVM callers in arm.c, etc...

Cheers,
/fuad

#7 lore raw

PATCH v4 3/11 KVM: arm64: Pass range filter to stage2_unmap_range

In reply to Steven Price

From: Suzuki K Poulose <[email protected]>

With the introduction of private memory support, we need to handle invalidation requests with filters for a given type. Pass the range filter down to the stage-2 unmap operation.

---
 arch/arm64/include/asm/kvm_host.h |  4 +++-
 arch/arm64/kvm/mmu.c              | 31 +++++++++++++++++++++++--------
 2 files changed, 26 insertions(+), 9 deletions(-)
arch/arm64/include/asm/kvm_host.h +3 -1
index 8438251e1d1b..9d6258b213d1 100644
@@ -233,6 +233,7 @@ struct kvm_vcpu_ops {
 };
 
 struct kvm_gfn_range;
+enum kvm_gfn_range_filter;
 struct kvm_s2_fault_desc;
 
 struct kvm_vm_s2_ops {
@@ -243,7 +244,8 @@ struct kvm_vm_s2_ops {
 					  u64 nr_pages);
 	void (*vm_stage2_unmap_range)(struct kvm_s2_mmu *mmu,
 				      phys_addr_t start, u64 size,
-				      bool may_block);
+				      bool may_block,
+				      enum kvm_gfn_range_filter filter);
 	int (*vm_mem_abort)(const struct kvm_s2_fault_desc *s2fd);
 };
 
arch/arm64/kvm/mmu.c +23 -8
index 09c831a49ed3..8a9a80c7cfab 100644
@@ -324,7 +324,8 @@ static int kvm_pgtable_stage2_unmap_tracked(struct kvm_pgtable *pgt,
 
 static void kvm_vm_stage2_unmap_range(struct kvm_s2_mmu *mmu,
 				      phys_addr_t start,
-				      u64 size, bool may_block)
+				      u64 size, bool may_block,
+				      enum kvm_gfn_range_filter filter)
 {
 	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
 	int (*fn)(struct kvm_pgtable *, u64, u64);
@@ -339,14 +340,16 @@ static void kvm_vm_stage2_unmap_range(struct kvm_s2_mmu *mmu,
 
 static void pkvm_stage2_unmap_range(struct kvm_s2_mmu *mmu,
 				    phys_addr_t start,
-				    u64 size, bool may_block)
+				    u64 size, bool may_block,
+				    enum kvm_gfn_range_filter filter)
 {
 	WARN_ON(stage2_apply_range(mmu, start, start + size,
 				   pkvm_pgtable_stage2_unmap, may_block));
 }
 
 static void no_stage2_unmap_range(struct kvm_s2_mmu *mmu,
-				  phys_addr_t start, u64 size, bool may_block)
+				  phys_addr_t start, u64 size, bool may_block,
+				  enum kvm_gfn_range_filter filter)
 {
 }
 
@@ -388,25 +391,36 @@ static int kvm_pgtable_stage2_unmap_tracked(struct kvm_pgtable *pgt, u64 addr, u
 }
 
 /**
- * kvm_stage2_unmap_range -- Clear stage2 page table entries to unmap a range
+ * kvm_stage2_unmap_range_filter -- Clear stage2 page table entries to unmap a
+ * range
  * @mmu:   The KVM stage-2 MMU pointer
  * @start: The intermediate physical base address of the range to unmap
  * @size:  The size of the area to unmap
  * @may_block: Whether or not we are permitted to block
+ * @filter: Filter for the ipa range (private and/or shared)
  *
  * Clear a range of stage-2 mappings, lowering the various ref-counts.  Must
  * be called while holding mmu_lock otherwise another faulting VCPU may
  * come in and mess with things behind our backs.
  */
-void kvm_stage2_unmap_range(struct kvm_s2_mmu *mmu, phys_addr_t start,
-			    u64 size, bool may_block)
+static void kvm_stage2_unmap_range_filter(struct kvm_s2_mmu *mmu, phys_addr_t start,
+					  u64 size, bool may_block,
+					  enum kvm_gfn_range_filter filter)
 {
 	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
 
 	lockdep_assert_held_write(&kvm->mmu_lock);
 	WARN_ON(size & ~PAGE_MASK);
 
-	kvm->arch.vm_s2_ops->vm_stage2_unmap_range(mmu, start, size, may_block);
+	kvm->arch.vm_s2_ops->vm_stage2_unmap_range(mmu, start, size,
+						   may_block, filter);
+}
+
+void kvm_stage2_unmap_range(struct kvm_s2_mmu *mmu, phys_addr_t start,
+			    u64 size, bool may_block)
+{
+	kvm_stage2_unmap_range_filter(mmu, start, size, may_block,
+				      KVM_FILTER_PRIVATE | KVM_FILTER_SHARED);
 }
 
 void kvm_stage2_flush_range(struct kvm_s2_mmu *mmu, phys_addr_t addr, phys_addr_t end)
@@ -2597,7 +2611,8 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
 	if (!kvm->arch.mmu.pgt)
 		return false;
 
-	kvm_stage2_unmap_range(&kvm->arch.mmu, gpa, size, may_block);
+	kvm_stage2_unmap_range_filter(&kvm->arch.mmu, gpa, size, may_block,
+				      range->attr_filter);
 	kvm_nested_unmap_cipa_range(kvm, gpa, size, may_block);
 
 	return false;
Signature · 1 line
2.43.0
#8 lore raw

PATCH v4 4/11 KVM: arm64: Dispatch stage-2 destruction by VM flavor

In reply to Steven Price

Select the stage-2 destruction functions through the VM's stage-2 operations. This keeps the native and pKVM paths explicit and lets a Realm provide its own destruction callback when Realm stage-2 operations are registered.

The Realm callback will only free the root RTT pages, because RMI teardown destroys the non-root RTTs separately.

---
Changes since v3:
- Move before basic Realm infrastructure and declare the page-table type for the new callback.

Changes since v2:
- New patch in v3; split stage-2 destruction dispatch out of the Realm stage-2 MMU operations patch.

---
 arch/arm64/include/asm/kvm_host.h |  2 ++
 arch/arm64/kvm/mmu.c              | 30 +++++++++++++++++++++++-------
 2 files changed, 25 insertions(+), 7 deletions(-)
arch/arm64/include/asm/kvm_host.h +2 -0
index 9d6258b213d1..3ddeddfacd06 100644
@@ -234,6 +234,7 @@ struct kvm_vcpu_ops {
 
 struct kvm_gfn_range;
 enum kvm_gfn_range_filter;
+struct kvm_pgtable;
 struct kvm_s2_fault_desc;
 
 struct kvm_vm_s2_ops {
@@ -242,6 +243,7 @@ struct kvm_vm_s2_ops {
 	int (*vm_flush_remote_tlbs)(struct kvm *kvm);
 	int (*vm_flush_remote_tlbs_range)(struct kvm *kvm, gfn_t gfn,
 					  u64 nr_pages);
+	void (*vm_stage2_destroy)(struct kvm_pgtable *pgt);
 	void (*vm_stage2_unmap_range)(struct kvm_s2_mmu *mmu,
 				      phys_addr_t start, u64 size,
 				      bool may_block,
arch/arm64/kvm/mmu.c +23 -7
index 8a9a80c7cfab..fab915ddeaab 100644
@@ -1018,26 +1018,39 @@ static int kvm_init_ipa_range(struct kvm_s2_mmu *mmu, unsigned long type)
  * cond_resched() periodically to prevent hogging the CPU for a long time
  * and schedule something else, if required.
  */
-static void stage2_destroy_range(struct kvm_pgtable *pgt, phys_addr_t addr,
-				   phys_addr_t end)
+static void stage2_destroy_range(struct kvm_pgtable *pgt,
+				 void (*destroy_range)(struct kvm_pgtable *pgt,
+						       u64 addr, u64 size))
 {
+	u64 addr = 0;
+	u64 end = BIT(VTCR_EL2_IPA(pgt->mmu->vtcr));
 	u64 next;
 
 	do {
 		next = stage2_range_addr_end(addr, end);
-		KVM_PGT_FN(kvm_pgtable_stage2_destroy_range)(pgt, addr,
-							     next - addr);
+		destroy_range(pgt, addr, next - addr);
 		if (next != end)
 			cond_resched();
 	} while (addr = next, addr != end);
 }
 
+static void kvm_vm_stage2_destroy(struct kvm_pgtable *pgt)
+{
+	stage2_destroy_range(pgt, kvm_pgtable_stage2_destroy_range);
+	kvm_pgtable_stage2_destroy_pgd(pgt);
+}
+
+static void pkvm_stage2_destroy(struct kvm_pgtable *pgt)
+{
+	stage2_destroy_range(pgt, pkvm_pgtable_stage2_destroy_range);
+	pkvm_pgtable_stage2_destroy_pgd(pgt);
+}
+
 static void kvm_stage2_destroy(struct kvm_pgtable *pgt)
 {
-	unsigned int ia_bits = VTCR_EL2_IPA(pgt->mmu->vtcr);
+	struct kvm *kvm = kvm_s2_mmu_to_kvm(pgt->mmu);
 
-	stage2_destroy_range(pgt, 0, BIT(ia_bits));
-	KVM_PGT_FN(kvm_pgtable_stage2_destroy_pgd)(pgt);
+	kvm->arch.vm_s2_ops->vm_stage2_destroy(pgt);
 }
 
 /**
@@ -3146,6 +3159,7 @@ long kvm_arch_vcpu_pre_fault_memory(struct kvm_vcpu *vcpu,
 }
 
 static const struct kvm_vm_s2_ops protected_pkvm_vm_s2_ops = {
+	.vm_stage2_destroy		= pkvm_stage2_destroy,
 	.vm_flush_remote_tlbs		= pkvm_flush_remote_tlbs,
 	.vm_flush_remote_tlbs_range	= pkvm_flush_remote_tlbs_range,
 	.vm_age_gfn			= no_age_gfn,
@@ -3155,6 +3169,7 @@ static const struct kvm_vm_s2_ops protected_pkvm_vm_s2_ops = {
 };
 
 static const struct kvm_vm_s2_ops pkvm_vm_s2_ops = {
+	.vm_stage2_destroy		= pkvm_stage2_destroy,
 	.vm_flush_remote_tlbs		= pkvm_flush_remote_tlbs,
 	.vm_flush_remote_tlbs_range	= pkvm_flush_remote_tlbs_range,
 	.vm_age_gfn			= pkvm_age_gfn,
@@ -3164,6 +3179,7 @@ static const struct kvm_vm_s2_ops pkvm_vm_s2_ops = {
 };
 
 static const struct kvm_vm_s2_ops kvm_default_vm_s2_ops = {
+	.vm_stage2_destroy		= kvm_vm_stage2_destroy,
 	.vm_flush_remote_tlbs		= kvm_vm_flush_remote_tlbs,
 	.vm_flush_remote_tlbs_range	= kvm_vm_flush_remote_tlbs_range,
 	.vm_age_gfn			= kvm_vm_age_gfn,
Signature · 1 line
2.43.0
reviewer Reviewed-by on v4 4/11
#9 lore raw

Re: [PATCH v4 04/11] KVM: arm64: Dispatch stage-2 destruction by VM flavor

Quoted 8 lines · Steven Price

Select the stage-2 destruction functions through the VM's stage-2 operations. This keeps the native and pKVM paths explicit and lets a Realm provide its own destruction callback when Realm stage-2 operations are registered.

The Realm callback will only free the root RTT pages, because RMI teardown destroys the non-root RTTs separately.

minor nit: The second paragraph may be omitted as we introduce the Realm stuff in a later patch.

Quoted 1 line
Quoted 109 lines

---
Changes since v3:
- Move before basic Realm infrastructure and declare the page-table type for the new callback.

Changes since v2:
- New patch in v3; split stage-2 destruction dispatch out of the Realm stage-2 MMU operations patch.

---
  arch/arm64/include/asm/kvm_host.h |  2 ++
  arch/arm64/kvm/mmu.c              | 30 +++++++++++++++++++++++-------
  2 files changed, 25 insertions(+), 7 deletions(-)
arch/arm64/include/asm/kvm_host.h +2 -0
index 9d6258b213d1..3ddeddfacd06 100644
@@ -234,6 +234,7 @@ struct kvm_vcpu_ops {
 
  struct kvm_gfn_range;
  enum kvm_gfn_range_filter;
+struct kvm_pgtable;
  struct kvm_s2_fault_desc;
 
  struct kvm_vm_s2_ops {
@@ -242,6 +243,7 @@ struct kvm_vm_s2_ops {
  	int (*vm_flush_remote_tlbs)(struct kvm *kvm);
  	int (*vm_flush_remote_tlbs_range)(struct kvm *kvm, gfn_t gfn,
  					  u64 nr_pages);
+	void (*vm_stage2_destroy)(struct kvm_pgtable *pgt);
  	void (*vm_stage2_unmap_range)(struct kvm_s2_mmu *mmu,
  				      phys_addr_t start, u64 size,
  				      bool may_block,
arch/arm64/kvm/mmu.c +23 -7
index 8a9a80c7cfab..fab915ddeaab 100644
@@ -1018,26 +1018,39 @@ static int kvm_init_ipa_range(struct kvm_s2_mmu *mmu, unsigned long type)
   * cond_resched() periodically to prevent hogging the CPU for a long time
   * and schedule something else, if required.
   */
-static void stage2_destroy_range(struct kvm_pgtable *pgt, phys_addr_t addr,
-				   phys_addr_t end)
+static void stage2_destroy_range(struct kvm_pgtable *pgt,
+				 void (*destroy_range)(struct kvm_pgtable *pgt,
+						       u64 addr, u64 size))
  {
+	u64 addr = 0;
+	u64 end = BIT(VTCR_EL2_IPA(pgt->mmu->vtcr));
  	u64 next;
 
  	do {
  		next = stage2_range_addr_end(addr, end);
-		KVM_PGT_FN(kvm_pgtable_stage2_destroy_range)(pgt, addr,
-							     next - addr);
+		destroy_range(pgt, addr, next - addr);
  		if (next != end)
  			cond_resched();
  	} while (addr = next, addr != end);
  }
 
+static void kvm_vm_stage2_destroy(struct kvm_pgtable *pgt)
+{
+	stage2_destroy_range(pgt, kvm_pgtable_stage2_destroy_range);
+	kvm_pgtable_stage2_destroy_pgd(pgt);
+}
+
+static void pkvm_stage2_destroy(struct kvm_pgtable *pgt)
+{
+	stage2_destroy_range(pgt, pkvm_pgtable_stage2_destroy_range);
+	pkvm_pgtable_stage2_destroy_pgd(pgt);
+}
+
  static void kvm_stage2_destroy(struct kvm_pgtable *pgt)
  {
-	unsigned int ia_bits = VTCR_EL2_IPA(pgt->mmu->vtcr);
+	struct kvm *kvm = kvm_s2_mmu_to_kvm(pgt->mmu);
 
-	stage2_destroy_range(pgt, 0, BIT(ia_bits));
-	KVM_PGT_FN(kvm_pgtable_stage2_destroy_pgd)(pgt);
+	kvm->arch.vm_s2_ops->vm_stage2_destroy(pgt);
  }
 
  /**
@@ -3146,6 +3159,7 @@ long kvm_arch_vcpu_pre_fault_memory(struct kvm_vcpu *vcpu,
  }
 
  static const struct kvm_vm_s2_ops protected_pkvm_vm_s2_ops = {
+	.vm_stage2_destroy		= pkvm_stage2_destroy,
  	.vm_flush_remote_tlbs		= pkvm_flush_remote_tlbs,
  	.vm_flush_remote_tlbs_range	= pkvm_flush_remote_tlbs_range,
  	.vm_age_gfn			= no_age_gfn,
@@ -3155,6 +3169,7 @@ static const struct kvm_vm_s2_ops protected_pkvm_vm_s2_ops = {
  };
 
  static const struct kvm_vm_s2_ops pkvm_vm_s2_ops = {
+	.vm_stage2_destroy		= pkvm_stage2_destroy,
  	.vm_flush_remote_tlbs		= pkvm_flush_remote_tlbs,
  	.vm_flush_remote_tlbs_range	= pkvm_flush_remote_tlbs_range,
  	.vm_age_gfn			= pkvm_age_gfn,
@@ -3164,6 +3179,7 @@ static const struct kvm_vm_s2_ops pkvm_vm_s2_ops = {
  };
 
  static const struct kvm_vm_s2_ops kvm_default_vm_s2_ops = {
+	.vm_stage2_destroy		= kvm_vm_stage2_destroy,
  	.vm_flush_remote_tlbs		= kvm_vm_flush_remote_tlbs,
  	.vm_flush_remote_tlbs_range	= kvm_vm_flush_remote_tlbs_range,
  	.vm_age_gfn			= kvm_vm_age_gfn,
#10 lore raw

Re: [PATCH v4 04/11] KVM: arm64: Dispatch stage-2 destruction by VM flavor

Quoted 6 lines · Suzuki K Poulose
Quoted 5 lines · Steven Price

Select the stage-2 destruction functions through the VM's stage-2 operations. This keeps the native and pKVM paths explicit and lets a Realm provide its own destruction callback when Realm stage-2 operations are registered.

Quoted 6 lines
Quoted 3 lines

The Realm callback will only free the root RTT pages, because RMI teardown destroys the non-root RTTs separately.

minor nit: The second paragraph may be omitted as we introduce the Realm stuff in a later patch.

Ack

Quoted 5 lines
Quoted 2 lines

Thanks!
Steve

Quoted 109 lines
Quoted 108 lines

---
Changes since v3:
- Move before basic Realm infrastructure and declare the page-table type for the new callback.

Changes since v2:
- New patch in v3; split stage-2 destruction dispatch out of the Realm stage-2 MMU operations patch.
---
  arch/arm64/include/asm/kvm_host.h |  2 ++ arch/arm64/kvm/mmu.c              | 30 +++++++++++++++++++++++-------

  2 files changed, 25 insertions(+), 7 deletions(-)
arch/arm64/include/ renamed from arch/arm64/include/asm/kvm_host.h +0 -0

asm/kvm_host.h
index 9d6258b213d1..3ddeddfacd06 100644

arch/arm64/include/asm/kvm_host.h +2 -0
@@ -234,6 +234,7 @@ struct kvm_vcpu_ops {
     struct kvm_gfn_range;
   enum kvm_gfn_range_filter;
+struct kvm_pgtable;
   struct kvm_s2_fault_desc;
     struct kvm_vm_s2_ops {
@@ -242,6 +243,7 @@ struct kvm_vm_s2_ops {
       int (*vm_flush_remote_tlbs)(struct kvm *kvm);
       int (*vm_flush_remote_tlbs_range)(struct kvm *kvm, gfn_t gfn,
                         u64 nr_pages);
+    void (*vm_stage2_destroy)(struct kvm_pgtable *pgt);
       void (*vm_stage2_unmap_range)(struct kvm_s2_mmu *mmu,
                         phys_addr_t start, u64 size,
                         bool may_block,
arch/arm64/kvm/mmu.c +0 -0
index 8a9a80c7cfab..fab915ddeaab 100644
@@ -1018,26 +1018,39 @@ static int kvm_init_ipa_range(struct
 kvm_s2_mmu *mmu, unsigned long type)
    * cond_resched() periodically to prevent hogging the CPU for a long

time
   * and schedule something else, if required.
   */
-static void stage2_destroy_range(struct kvm_pgtable *pgt, phys_addr_t addr,
-                   phys_addr_t end)
+static void stage2_destroy_range(struct kvm_pgtable *pgt, +                 void (*destroy_range)(struct kvm_pgtable *pgt, +                               u64 addr, u64 size))
  {
+    u64 addr = 0;
+    u64 end = BIT(VTCR_EL2_IPA(pgt->mmu->vtcr));
      u64 next;
        do {
          next = stage2_range_addr_end(addr, end);
-        KVM_PGT_FN(kvm_pgtable_stage2_destroy_range)(pgt, addr, -                                 next - addr);
+        destroy_range(pgt, addr, next - addr);
          if (next != end)
              cond_resched();
      } while (addr = next, addr != end);
  }
  +static void kvm_vm_stage2_destroy(struct kvm_pgtable *pgt)

arch/arm64/kvm/mmu.c +11 -0
+{
+    stage2_destroy_range(pgt, kvm_pgtable_stage2_destroy_range);
+    kvm_pgtable_stage2_destroy_pgd(pgt);
+}
+
+static void pkvm_stage2_destroy(struct kvm_pgtable *pgt)
+{
+    stage2_destroy_range(pgt, pkvm_pgtable_stage2_destroy_range);
+    pkvm_pgtable_stage2_destroy_pgd(pgt);
+}
+

  static void kvm_stage2_destroy(struct kvm_pgtable *pgt) {
-    unsigned int ia_bits = VTCR_EL2_IPA(pgt->mmu->vtcr); +    struct kvm *kvm = kvm_s2_mmu_to_kvm(pgt->mmu); -    stage2_destroy_range(pgt, 0, BIT(ia_bits)); -    KVM_PGT_FN(kvm_pgtable_stage2_destroy_pgd)(pgt); +    kvm->arch.vm_s2_ops->vm_stage2_destroy(pgt); }
    /**

arch/arm64/kvm/mmu.c +3 -0
@@ -3146,6 +3159,7 @@ long kvm_arch_vcpu_pre_fault_memory(struct
 kvm_vcpu *vcpu,
   }
     static const struct kvm_vm_s2_ops protected_pkvm_vm_s2_ops = {
+    .vm_stage2_destroy        = pkvm_stage2_destroy,
       .vm_flush_remote_tlbs        = pkvm_flush_remote_tlbs,
       .vm_flush_remote_tlbs_range    = pkvm_flush_remote_tlbs_range,
       .vm_age_gfn            = no_age_gfn,
@@ -3155,6 +3169,7 @@ static const struct kvm_vm_s2_ops
 protected_pkvm_vm_s2_ops = {
   };
     static const struct kvm_vm_s2_ops pkvm_vm_s2_ops = {
+    .vm_stage2_destroy        = pkvm_stage2_destroy,
       .vm_flush_remote_tlbs        = pkvm_flush_remote_tlbs,
       .vm_flush_remote_tlbs_range    = pkvm_flush_remote_tlbs_range,
       .vm_age_gfn            = pkvm_age_gfn,
@@ -3164,6 +3179,7 @@ static const struct kvm_vm_s2_ops pkvm_vm_s2_ops
 = {
   };
     static const struct kvm_vm_s2_ops kvm_default_vm_s2_ops = {
+    .vm_stage2_destroy        = kvm_vm_stage2_destroy,
       .vm_flush_remote_tlbs        = kvm_vm_flush_remote_tlbs,
       .vm_flush_remote_tlbs_range    = kvm_vm_flush_remote_tlbs_range,
       .vm_age_gfn            = kvm_vm_age_gfn,
Reviewed-by on v4 4/11
#11 lore raw

Re: [PATCH v4 04/11] KVM: arm64: Dispatch stage-2 destruction by VM flavor

In reply to Steven Price

Hi Steven,

Quoted 7 lines · Steven Price

Select the stage-2 destruction functions through the VM's stage-2 operations. This keeps the native and pKVM paths explicit and lets a Realm provide its own destruction callback when Realm stage-2 operations are registered.

The Realm callback will only free the root RTT pages, because RMI teardown destroys the non-root RTTs separately.

Cheers,
/fuad

#12 lore raw

PATCH v4 5/11 KVM: arm64: CCA: Add basic infrastructure for creating a realm

In reply to Steven Price

Introduce the skeleton functions for creating and destroying a realm. The requested IPA size is checked against both the KVM and RMM limits.

The actual work of constructing the realm will be added in future patches.

---
Changes since v3:
- Use the preceding destruction dispatch instead of a temporary Realm-specific check in kvm_stage2_destroy().

Changes since v2:
- Move ARM_RMM_RMI selection and rmi.o build registration here. Store the RD physical address from the outset and free SRO state on Realm teardown errors.

Changes since v1:
- Cap the Realm IPA size at the smaller KVM and RMM limit, and record the selected IPA size when initializing Realm state.

---
 arch/arm64/include/asm/kvm_rmi.h | 23 ++++++++++++
 arch/arm64/kvm/Kconfig           |  1 +
 arch/arm64/kvm/Makefile          |  2 +-
 arch/arm64/kvm/arm.c             |  9 +++++
 arch/arm64/kvm/mmu.c             |  7 +++-
 arch/arm64/kvm/rmi.c             | 63 ++++++++++++++++++++++++++++++++
 6 files changed, 103 insertions(+), 2 deletions(-)
 create mode 100644 arch/arm64/kvm/rmi.c
arch/arm64/include/asm/kvm_rmi.h +23 -0
index 67f16793b4d0..4ac1af622872 100644
@@ -6,6 +6,9 @@
 #ifndef __ASM_KVM_RMI_H
 #define __ASM_KVM_RMI_H
 
+#include <linux/arm-smccc-rmi.h>
+#include <linux/kvm.h>
+
 /**
  * enum realm_state - State of a Realm
  *
@@ -50,10 +53,30 @@ enum realm_state {
 /**
  * struct realm - Additional per VM data for a Realm
  *
+ * @rd_phys: Physical address of the RMM-managed Realm Descriptor (RD) granule
+ * @sro: Preallocated SRO state context for Realm MMU operations
  * @state: The lifetime state machine for the realm
+ * @ia_bits: Number of valid Input Address bits in the IPA
+ * @start_level: Starting level of the Realm Translation Table
  */
 struct realm {
+	phys_addr_t rd_phys;
+	/*
+	 * Reused by RTT map/unmap SRO commands. Those commands are only
+	 * issued from Realm stage-2 map/unmap paths while kvm->mmu_lock is
+	 * held for write, including Realm fault handling where
+	 * kvm_fault_lock() takes the write side, so concurrent use is
+	 * serialized.
+	 */
+	struct rmi_sro_state *sro;
 	enum realm_state state;
+	unsigned int ia_bits;
+	int start_level;
 };
 
+u32 kvm_rmm_ipa_limit(void);
+
+int kvm_init_realm(struct kvm *kvm);
+void kvm_destroy_realm(struct kvm *kvm);
+
 #endif /* __ASM_KVM_RMI_H */
arch/arm64/kvm/Kconfig +1 -0
index cecea0820e52..d067063a3686 100644
@@ -34,6 +34,7 @@ menuconfig KVM
 	select GUEST_PERF_EVENTS if PERF_EVENTS
 	select KVM_GUEST_MEMFD
 	select KVM_GENERIC_PRE_FAULT_MEMORY
+	select ARM_RMM_RMI
 	help
 	  Support hosting virtualized guest machines.
 
arch/arm64/kvm/Makefile +1 -1
index 7aaeeb84e788..66a719ab5b6b 100644
@@ -16,7 +16,7 @@ CFLAGS_handle_exit.o += -Wno-override-init
 kvm-y += arm.o mmu.o mmio.o psci.o hypercalls.o pvtime.o \
 	 inject_fault.o va_layout.o handle_exit.o config.o \
 	 guest.o debug.o reset.o sys_regs.o stacktrace.o \
-	 vgic-sys-reg-v3.o fpsimd.o pkvm.o \
+	 vgic-sys-reg-v3.o fpsimd.o pkvm.o rmi.o \
 	 arch_timer.o trng.o vmid.o emulate-nested.o nested.o at.o \
 	 vgic/vgic.o vgic/vgic-init.o \
 	 vgic/vgic-irqfd.o vgic/vgic-v2.o \
arch/arm64/kvm/arm.c +9 -0
index d79e5451923d..7c22d9474a38 100644
@@ -300,6 +300,13 @@ int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
 
 	bitmap_zero(kvm->arch.vcpu_features, KVM_VCPU_MAX_FEATURES);
 
+	/* Initialise the realm bits after the generic bits are enabled */
+	if (kvm_vm_is_realm(kvm)) {
+		ret = kvm_init_realm(kvm);
+		if (ret)
+			goto err_uninit_mmu;
+	}
+
 	return 0;
 
 err_uninit_mmu:
@@ -364,6 +371,8 @@ void kvm_arch_destroy_vm(struct kvm *kvm)
 
 	kvm_destroy_nested(kvm);
 	kvm_arm_teardown_hypercalls(kvm);
+	if (kvm_vm_is_realm(kvm))
+		kvm_destroy_realm(kvm);
 }
 
 static bool kvm_has_full_ptr_auth(void)
arch/arm64/kvm/mmu.c +6 -1
index fab915ddeaab..84b02699f103 100644
@@ -981,10 +981,14 @@ static struct kvm_pgtable_mm_ops kvm_s2_mm_ops = {
 
 static int kvm_init_ipa_range(struct kvm_s2_mmu *mmu, unsigned long type)
 {
+	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
 	u32 kvm_ipa_limit = get_kvm_ipa_limit();
 	u64 mmfr0, mmfr1;
 	u32 phys_shift;
 
+	if (kvm_vm_is_realm(kvm))
+		kvm_ipa_limit = min(kvm_ipa_limit, kvm_rmm_ipa_limit());
+
 	phys_shift = KVM_VM_TYPE_ARM_IPA_SIZE(type);
 	if (is_protected_kvm_enabled()) {
 		phys_shift = kvm_ipa_limit;
@@ -1097,6 +1101,8 @@ int kvm_init_stage2_mmu(struct kvm *kvm, struct kvm_s2_mmu *mmu, unsigned long t
 		return -EINVAL;
 	}
 
+	mmu->arch = &kvm->arch;
+
 	err = kvm_init_ipa_range(mmu, type);
 	if (err)
 		return err;
@@ -1105,7 +1111,6 @@ int kvm_init_stage2_mmu(struct kvm *kvm, struct kvm_s2_mmu *mmu, unsigned long t
 	if (!pgt)
 		return -ENOMEM;
 
-	mmu->arch = &kvm->arch;
 	err = KVM_PGT_FN(kvm_pgtable_stage2_init)(pgt, mmu, &kvm_s2_mm_ops);
 	if (err)
 		goto out_free_pgtable;
arch/arm64/kvm/rmi.c new file +63 -0

63 lines not on this page · raw message

Signature · 1 line
2.43.0
#13 lore raw

Re: [PATCH v4 05/11] KVM: arm64: CCA: Add basic infrastructure for creating a realm

Quoted 189 lines · Steven Price

Introduce the skeleton functions for creating and destroying a realm. The requested IPA size is checked against both the KVM and RMM limits.

The actual work of constructing the realm will be added in future patches.

---
Changes since v3:
- Use the preceding destruction dispatch instead of a temporary Realm-specific check in kvm_stage2_destroy().

Changes since v2:
- Move ARM_RMM_RMI selection and rmi.o build registration here. Store the RD physical address from the outset and free SRO state on Realm teardown errors.

Changes since v1:
- Cap the Realm IPA size at the smaller KVM and RMM limit, and record the selected IPA size when initializing Realm state.

---
  arch/arm64/include/asm/kvm_rmi.h | 23 ++++++++++++
  arch/arm64/kvm/Kconfig           |  1 +
  arch/arm64/kvm/Makefile          |  2 +-
  arch/arm64/kvm/arm.c             |  9 +++++
  arch/arm64/kvm/mmu.c             |  7 +++-
  arch/arm64/kvm/rmi.c             | 63 ++++++++++++++++++++++++++++++++
  6 files changed, 103 insertions(+), 2 deletions(-)

create mode 100644 arch/arm64/kvm/rmi.c

arch/arm64/include/asm/kvm_rmi.h +23 -0
index 67f16793b4d0..4ac1af622872 100644
@@ -6,6 +6,9 @@
  #ifndef __ASM_KVM_RMI_H
  #define __ASM_KVM_RMI_H
 
+#include <linux/arm-smccc-rmi.h>
+#include <linux/kvm.h>
+
  /**
   * enum realm_state - State of a Realm
   *
@@ -50,10 +53,30 @@ enum realm_state {
  /**
   * struct realm - Additional per VM data for a Realm
   *
+ * @rd_phys: Physical address of the RMM-managed Realm Descriptor (RD) granule
+ * @sro: Preallocated SRO state context for Realm MMU operations
   * @state: The lifetime state machine for the realm
+ * @ia_bits: Number of valid Input Address bits in the IPA
+ * @start_level: Starting level of the Realm Translation Table
   */
  struct realm {
+	phys_addr_t rd_phys;
+	/*
+	 * Reused by RTT map/unmap SRO commands. Those commands are only
+	 * issued from Realm stage-2 map/unmap paths while kvm->mmu_lock is
+	 * held for write, including Realm fault handling where
+	 * kvm_fault_lock() takes the write side, so concurrent use is
+	 * serialized.
+	 */
+	struct rmi_sro_state *sro;
  	enum realm_state state;
+	unsigned int ia_bits;
+	int start_level;
  };
 
+u32 kvm_rmm_ipa_limit(void);
+
+int kvm_init_realm(struct kvm *kvm);
+void kvm_destroy_realm(struct kvm *kvm);
+
  #endif /* __ASM_KVM_RMI_H */
arch/arm64/kvm/Kconfig +1 -0
index cecea0820e52..d067063a3686 100644
@@ -34,6 +34,7 @@ menuconfig KVM
  	select GUEST_PERF_EVENTS if PERF_EVENTS
  	select KVM_GUEST_MEMFD
  	select KVM_GENERIC_PRE_FAULT_MEMORY
+	select ARM_RMM_RMI
  	help
  	  Support hosting virtualized guest machines.
 
arch/arm64/kvm/Makefile +1 -1
index 7aaeeb84e788..66a719ab5b6b 100644
@@ -16,7 +16,7 @@ CFLAGS_handle_exit.o += -Wno-override-init
  kvm-y += arm.o mmu.o mmio.o psci.o hypercalls.o pvtime.o \
  	 inject_fault.o va_layout.o handle_exit.o config.o \
  	 guest.o debug.o reset.o sys_regs.o stacktrace.o \
-	 vgic-sys-reg-v3.o fpsimd.o pkvm.o \
+	 vgic-sys-reg-v3.o fpsimd.o pkvm.o rmi.o \
  	 arch_timer.o trng.o vmid.o emulate-nested.o nested.o at.o \
  	 vgic/vgic.o vgic/vgic-init.o \
  	 vgic/vgic-irqfd.o vgic/vgic-v2.o \
arch/arm64/kvm/arm.c +9 -0
index d79e5451923d..7c22d9474a38 100644
@@ -300,6 +300,13 @@ int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
 
  	bitmap_zero(kvm->arch.vcpu_features, KVM_VCPU_MAX_FEATURES);
 
+	/* Initialise the realm bits after the generic bits are enabled */
+	if (kvm_vm_is_realm(kvm)) {
+		ret = kvm_init_realm(kvm);
+		if (ret)
+			goto err_uninit_mmu;
+	}
+
  	return 0;
 
  err_uninit_mmu:
@@ -364,6 +371,8 @@ void kvm_arch_destroy_vm(struct kvm *kvm)
 
  	kvm_destroy_nested(kvm);
  	kvm_arm_teardown_hypercalls(kvm);
+	if (kvm_vm_is_realm(kvm))
+		kvm_destroy_realm(kvm);
  }
 
  static bool kvm_has_full_ptr_auth(void)
arch/arm64/kvm/mmu.c +6 -1
index fab915ddeaab..84b02699f103 100644
@@ -981,10 +981,14 @@ static struct kvm_pgtable_mm_ops kvm_s2_mm_ops = {
 
  static int kvm_init_ipa_range(struct kvm_s2_mmu *mmu, unsigned long type)
  {
+	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
  	u32 kvm_ipa_limit = get_kvm_ipa_limit();
  	u64 mmfr0, mmfr1;
  	u32 phys_shift;
 
+	if (kvm_vm_is_realm(kvm))
+		kvm_ipa_limit = min(kvm_ipa_limit, kvm_rmm_ipa_limit());
+
  	phys_shift = KVM_VM_TYPE_ARM_IPA_SIZE(type);
  	if (is_protected_kvm_enabled()) {
  		phys_shift = kvm_ipa_limit;
@@ -1097,6 +1101,8 @@ int kvm_init_stage2_mmu(struct kvm *kvm, struct kvm_s2_mmu *mmu, unsigned long t
  		return -EINVAL;
  	}
 
+	mmu->arch = &kvm->arch;
+
  	err = kvm_init_ipa_range(mmu, type);
  	if (err)
  		return err;
@@ -1105,7 +1111,6 @@ int kvm_init_stage2_mmu(struct kvm *kvm, struct kvm_s2_mmu *mmu, unsigned long t
  	if (!pgt)
  		return -ENOMEM;
 
-	mmu->arch = &kvm->arch;
  	err = KVM_PGT_FN(kvm_pgtable_stage2_init)(pgt, mmu, &kvm_s2_mm_ops);
  	if (err)
  		goto out_free_pgtable;
arch/arm64/kvm/rmi.c new file +19 -0
new file mode 100644
index 000000000000..fafca2439c46
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) 2023-2026 ARM Ltd.
+ */
+
+#include <linux/arm-rmi-cmds.h>
+#include <linux/kvm_host.h>
+
+#include <asm/kvm_emulate.h>
+#include <asm/kvm_mmu.h>
+#include <asm/kvm_pgtable.h>
+#include <asm/virt.h>
+
+u32 kvm_rmm_ipa_limit(void)
+{
+	return u64_get_bits(rmi_feat_reg(0), RMI_FEATURE_REGISTER_0_S2SZ);
+}
+
+void kvm_destroy_realm(struct kvm *kvm)

arch/arm64/kvm/rmi.c line 29

Quoted 10 lines
arch/arm64/kvm/rmi.c new file +10 -0
+{
+	struct realm *realm = &kvm->arch.realm;
+	size_t pgd_size = kvm_pgtable_stage2_pgd_size(kvm->arch.mmu.vtcr);
+
+	if (!kvm_realm_is_created(kvm))
+		goto out_free_sro;
+
+	kvm_set_realm_state(kvm, REALM_STATE_DYING);
+
+	if (realm->rd_phys) {

Do we expect this to be otherwise ? Or do we get called twice on this function ?

Quoted 4 lines
arch/arm64/kvm/rmi.c new file +4 -0
+		phys_addr_t rd_phys = realm->rd_phys;
+
+		if (WARN_ON(rmi_realm_terminate(rd_phys, realm->sro)))
+			goto out_free_sro;

arch/arm64/kvm/rmi.c line 43

Quoted 10 lines
arch/arm64/kvm/rmi.c new file +10 -0
+
+		if (WARN_ON(rmi_realm_destroy(rd_phys, realm->sro)))
+			goto out_free_sro;
+		rmi_free_delegated_page(rd_phys);
+		realm->rd_phys = 0;
+	}
+
+	if (WARN_ON(rmi_undelegate_range(kvm->arch.mmu.pgd_phys,
+					 pgd_size)))
+		goto out_free_sro;

In the integration branch, we undelegate the Stage2 root RTTs, if the Realm create fails. Is there a particular reason why we may have the delegated S2 RTTs with realm->rd_phys = 0 ?

Suzuki

Quoted 20 lines
arch/arm64/kvm/rmi.c new file +20 -0
+
+	kvm_set_realm_state(kvm, REALM_STATE_DEAD);
+
+out_free_sro:
+	kfree(realm->sro);
+	realm->sro = NULL;
+}
+
+int kvm_init_realm(struct kvm *kvm)
+{
+	struct realm *realm = &kvm->arch.realm;
+
+	realm->ia_bits = VTCR_EL2_IPA(kvm->arch.mmu.vtcr);
+	realm->start_level = 4 - VTCR_EL2_LVLS(kvm->arch.mmu.vtcr);
+	realm->sro = kmalloc_obj(*realm->sro);
+	if (!realm->sro)
+		return -ENOMEM;
+
+	return 0;
+}
#14 lore raw

Re: [PATCH v4 05/11] KVM: arm64: CCA: Add basic infrastructure for creating a realm

Quoted 190 lines · Suzuki K Poulose
Quoted 189 lines · Steven Price

Introduce the skeleton functions for creating and destroying a realm. The requested IPA size is checked against both the KVM and RMM limits.

The actual work of constructing the realm will be added in future patches.

---
Changes since v3:
- Use the preceding destruction dispatch instead of a temporary Realm-specific check in kvm_stage2_destroy().

Changes since v2:
- Move ARM_RMM_RMI selection and rmi.o build registration here. Store the RD physical address from the outset and free SRO state on Realm teardown errors.

Changes since v1:
- Cap the Realm IPA size at the smaller KVM and RMM limit, and record the selected IPA size when initializing Realm state.
---
  arch/arm64/include/asm/kvm_rmi.h | 23 ++++++++++++ arch/arm64/kvm/Kconfig           |  1 + arch/arm64/kvm/Makefile          |  2 +-

  arch/arm64/kvm/arm.c             |  9 +++++
  arch/arm64/kvm/mmu.c             |  7 +++-
  arch/arm64/kvm/rmi.c             | 63 ++++++++++++++++++++++++++++++++
  6 files changed, 103 insertions(+), 2 deletions(-)

  create mode 100644 arch/arm64/kvm/rmi.c

arch/arm64/include/ renamed from arch/arm64/include/asm/kvm_rmi.h +0 -0

asm/kvm_rmi.h
index 67f16793b4d0..4ac1af622872 100644

arch/arm64/include/asm/kvm_rmi.h +0 -0
@@ -6,6 +6,9 @@
   #ifndef __ASM_KVM_RMI_H
   #define __ASM_KVM_RMI_H

  +#include <linux/arm-smccc-rmi.h>

arch/arm64/include/asm/kvm_rmi.h +2 -0
+#include <linux/kvm.h>
+

  /**
   * enum realm_state - State of a Realm
   *

arch/arm64/include/asm/kvm_rmi.h +1 -0
@@ -50,10 +53,30 @@ enum realm_state {
   /**
    * struct realm - Additional per VM data for a Realm
    *
+ * @rd_phys: Physical address of the RMM-managed Realm Descriptor

(RD) granule
+ * @sro: Preallocated SRO state context for Realm MMU operations
   * @state: The lifetime state machine for the realm
+ * @ia_bits: Number of valid Input Address bits in the IPA
+ * @start_level: Starting level of the Realm Translation Table */
  struct realm {
+    phys_addr_t rd_phys;
+    /*
+     * Reused by RTT map/unmap SRO commands. Those commands are only +     * issued from Realm stage-2 map/unmap paths while kvm->mmu_lock is +     * held for write, including Realm fault handling where +     * kvm_fault_lock() takes the write side, so concurrent use is +     * serialized.
+     */
+    struct rmi_sro_state *sro;
      enum realm_state state;
+    unsigned int ia_bits;
+    int start_level;
  };
  +u32 kvm_rmm_ipa_limit(void);

arch/arm64/include/asm/kvm_rmi.h +4 -0
+
+int kvm_init_realm(struct kvm *kvm);
+void kvm_destroy_realm(struct kvm *kvm);
+

  #endif /* __ASM_KVM_RMI_H */

arch/arm64/kvm/Kconfig +0 -0
index cecea0820e52..d067063a3686 100644
@@ -34,6 +34,7 @@ menuconfig KVM

      select GUEST_PERF_EVENTS if PERF_EVENTS
      select KVM_GUEST_MEMFD
      select KVM_GENERIC_PRE_FAULT_MEMORY
+    select ARM_RMM_RMI
      help
        Support hosting virtualized guest machines. diff --git a/arch/arm64/kvm/Makefile b/arch/arm64/kvm/Makefile index 7aaeeb84e788..66a719ab5b6b 100644

arch/arm64/kvm/Makefile +1 -1
@@ -16,7 +16,7 @@ CFLAGS_handle_exit.o += -Wno-override-init
   kvm-y += arm.o mmu.o mmio.o psci.o hypercalls.o pvtime.o \
        inject_fault.o va_layout.o handle_exit.o config.o \
        guest.o debug.o reset.o sys_regs.o stacktrace.o \
-     vgic-sys-reg-v3.o fpsimd.o pkvm.o \
+     vgic-sys-reg-v3.o fpsimd.o pkvm.o rmi.o \
        arch_timer.o trng.o vmid.o emulate-nested.o nested.o at.o \
        vgic/vgic.o vgic/vgic-init.o \
        vgic/vgic-irqfd.o vgic/vgic-v2.o \
arch/arm64/kvm/arm.c +0 -0
index d79e5451923d..7c22d9474a38 100644
@@ -300,6 +300,13 @@ int kvm_arch_init_vm(struct kvm *kvm, unsigned
 long type)
         bitmap_zero(kvm->arch.vcpu_features, KVM_VCPU_MAX_FEATURES);

  +    /* Initialise the realm bits after the generic bits are enabled */ +    if (kvm_vm_is_realm(kvm)) {
+        ret = kvm_init_realm(kvm);
+        if (ret)
+            goto err_uninit_mmu;
+    }
+
      return 0;
    err_uninit_mmu:

arch/arm64/kvm/arm.c +2 -0
@@ -364,6 +371,8 @@ void kvm_arch_destroy_vm(struct kvm *kvm)
         kvm_destroy_nested(kvm);
       kvm_arm_teardown_hypercalls(kvm);
+    if (kvm_vm_is_realm(kvm))
+        kvm_destroy_realm(kvm);
   }
     static bool kvm_has_full_ptr_auth(void)
arch/arm64/kvm/mmu.c +0 -0
index fab915ddeaab..84b02699f103 100644
@@ -981,10 +981,14 @@ static struct kvm_pgtable_mm_ops kvm_s2_mm_ops = {

    static int kvm_init_ipa_range(struct kvm_s2_mmu *mmu, unsigned long type)
  {
+    struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
      u32 kvm_ipa_limit = get_kvm_ipa_limit();
      u64 mmfr0, mmfr1;
      u32 phys_shift;
  +    if (kvm_vm_is_realm(kvm))
+        kvm_ipa_limit = min(kvm_ipa_limit, kvm_rmm_ipa_limit()); +
      phys_shift = KVM_VM_TYPE_ARM_IPA_SIZE(type);
      if (is_protected_kvm_enabled()) {
          phys_shift = kvm_ipa_limit;

arch/arm64/kvm/mmu.c +0 -0
@@ -1097,6 +1101,8 @@ int kvm_init_stage2_mmu(struct kvm *kvm, struct

kvm_s2_mmu *mmu, unsigned long t
          return -EINVAL;
      }
  +    mmu->arch = &kvm->arch;
+
      err = kvm_init_ipa_range(mmu, type);
      if (err)
          return err;

arch/arm64/kvm/mmu.c +0 -0
@@ -1105,7 +1111,6 @@ int kvm_init_stage2_mmu(struct kvm *kvm, struct

kvm_s2_mmu *mmu, unsigned long t
      if (!pgt)
          return -ENOMEM;
  -    mmu->arch = &kvm->arch;
      err = KVM_PGT_FN(kvm_pgtable_stage2_init)(pgt, mmu, &kvm_s2_mm_ops);
      if (err)
          goto out_free_pgtable;

arch/arm64/kvm/rmi.c new file +24 -0
new file mode 100644
index 000000000000..fafca2439c46
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) 2023-2026 ARM Ltd.
+ */
+
+#include <linux/arm-rmi-cmds.h>
+#include <linux/kvm_host.h>
+
+#include <asm/kvm_emulate.h>
+#include <asm/kvm_mmu.h>
+#include <asm/kvm_pgtable.h>
+#include <asm/virt.h>
+
+u32 kvm_rmm_ipa_limit(void)
+{
+    return u64_get_bits(rmi_feat_reg(0), RMI_FEATURE_REGISTER_0_S2SZ);
+}
+
+void kvm_destroy_realm(struct kvm *kvm)
+{
+    struct realm *realm = &kvm->arch.realm;
+    size_t pgd_size = kvm_pgtable_stage2_pgd_size(kvm->arch.mmu.vtcr);
+
+    if (!kvm_realm_is_created(kvm))
Quoted 8 lines

arch/arm64/kvm/rmi.c line 29

Quoted 5 lines
arch/arm64/kvm/rmi.c new file +5 -0
+        goto out_free_sro;
+
+    kvm_set_realm_state(kvm, REALM_STATE_DYING);
+
+    if (realm->rd_phys) {

Do we expect this to be otherwise ? Or do we get called twice on this function ?

You're right, this is redundant (and confusing). rd_phys should never be zero here. I'll drop this - thanks!

Quoted 10 lines
Quoted 10 lines
arch/arm64/kvm/rmi.c new file +10 -0
+        phys_addr_t rd_phys = realm->rd_phys;
+
+        if (WARN_ON(rmi_realm_terminate(rd_phys, realm->sro)))
+            goto out_free_sro;
+
+        if (WARN_ON(rmi_realm_destroy(rd_phys, realm->sro)))
+            goto out_free_sro;
+        rmi_free_delegated_page(rd_phys);
+        realm->rd_phys = 0;
+    }
Quoted 8 lines

arch/arm64/kvm/rmi.c line 43

Quoted 4 lines
arch/arm64/kvm/rmi.c new file +4 -0
+
+    if (WARN_ON(rmi_undelegate_range(kvm->arch.mmu.pgd_phys,
+                     pgd_size)))
+        goto out_free_sro;

In the integration branch, we undelegate the Stage2 root RTTs, if the Realm create fails. Is there a particular reason why we may have the delegated S2 RTTs with realm->rd_phys = 0 ?

As above, we don't expect to get here with realm->rd_phys == 0 (it might have been the case in a previous version of the series - I haven't check that). As you say during realm creation any undelegation required if it fails is handled in realm_create_rd().

Thanks,
Steve

Quoted 24 lines

Suzuki

Quoted 20 lines
arch/arm64/kvm/rmi.c new file +20 -0
+
+    kvm_set_realm_state(kvm, REALM_STATE_DEAD);
+
+out_free_sro:
+    kfree(realm->sro);
+    realm->sro = NULL;
+}
+
+int kvm_init_realm(struct kvm *kvm)
+{
+    struct realm *realm = &kvm->arch.realm;
+
+    realm->ia_bits = VTCR_EL2_IPA(kvm->arch.mmu.vtcr);
+    realm->start_level = 4 - VTCR_EL2_LVLS(kvm->arch.mmu.vtcr);
+    realm->sro = kmalloc_obj(*realm->sro);
+    if (!realm->sro)
+        return -ENOMEM;
+
+    return 0;
+}
#15 lore raw

PATCH v4 6/11 KVM: arm64: CCA: Destroy RTTs

In reply to Steven Price

The RMM owns the stage 2 page tables for a realm, and KVM must request that the RMM creates/destroys entries as necessary. The physical pages to store the page tables are delegated to the realm as required, and can be undelegated when no longer used.

Creating new RTTs is the easy part, destroying them is a little more tricky. The result of realm_rtt_destroy() can be used to effectively walk the tree and destroy the entries (undelegating pages that were given to the realm).

Tear down a created Realm whether it is still new or has been activated. Unmap the Realm IPA space once during stage-2 teardown. Defer destruction of non-root RTTs until final Realm destruction, after REALM_TERMINATE and before destroying the RD; root RTTs remain until the RD has gone away.

Use the same minimum of two stage-2 levels as VTCR when deriving the Realm's starting RTT level. Without this, narrow IPAs on 64K-page hosts can give the RMM a different starting level from KVM's own page tables.

---
Changes since v3:
- Match VTCR's minimum of two stage-2 levels for Realm RTTs.
- Use explicit config_lock cleanup in Realm destruction.

Changes since v2:
- Use the actual stage-2 start level and correct the RTT skip granularity. Free SRO state on final teardown errors.

Changes since v1:
- Tear down created Realms in both NEW and ACTIVE states. Fix the RTT start level, page accounting on failed undelegation, and handling of RTT granules returned by RMI.

---
 arch/arm64/include/asm/kvm_rmi.h |   3 +
 arch/arm64/kvm/mmu.c             |  17 ++-
 arch/arm64/kvm/rmi.c             | 178 +++++++++++++++++++++++++++++++
 3 files changed, 197 insertions(+), 1 deletion(-)
arch/arm64/include/asm/kvm_rmi.h +3 -0
index 4ac1af622872..01ecaabd839b 100644
@@ -58,6 +58,7 @@ enum realm_state {
  * @state: The lifetime state machine for the realm
  * @ia_bits: Number of valid Input Address bits in the IPA
  * @start_level: Starting level of the Realm Translation Table
+ * @stage2_unmapped: The Realm stage-2 mappings have been removed
  */
 struct realm {
 	phys_addr_t rd_phys;
@@ -72,11 +73,13 @@ struct realm {
 	enum realm_state state;
 	unsigned int ia_bits;
 	int start_level;
+	bool stage2_unmapped;
 };
 
 u32 kvm_rmm_ipa_limit(void);
 
 int kvm_init_realm(struct kvm *kvm);
 void kvm_destroy_realm(struct kvm *kvm);
+void kvm_realm_unmap_stage2_all(struct kvm *kvm);
 
 #endif /* __ASM_KVM_RMI_H */
arch/arm64/kvm/mmu.c +16 -1
index 84b02699f103..4a975715375c 100644
@@ -1149,9 +1149,24 @@ int kvm_init_stage2_mmu(struct kvm *kvm, struct kvm_s2_mmu *mmu, unsigned long t
 	return err;
 }
 
+static void kvm_realm_uninit_stage2(struct kvm_s2_mmu *mmu)
+{
+	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
+
+	guard(mutex)(&kvm->arch.config_lock);
+	if (kvm_realm_state(kvm) == REALM_STATE_NEW ||
+	    kvm_realm_state(kvm) == REALM_STATE_ACTIVE) {
+		kvm_set_realm_state(kvm, REALM_STATE_DYING);
+		kvm_realm_unmap_stage2_all(kvm);
+	}
+}
+
 void kvm_uninit_stage2_mmu(struct kvm *kvm)
 {
-	kvm_free_stage2_pgd(&kvm->arch.mmu);
+	if (kvm_realm_is_created(kvm))
+		kvm_realm_uninit_stage2(&kvm->arch.mmu);
+	else
+		kvm_free_stage2_pgd(&kvm->arch.mmu);
 	kvm_mmu_free_memory_cache(&kvm->arch.mmu.split_page_cache);
 }
 
arch/arm64/kvm/rmi.c +178 -0

209 lines not on this page · raw message

Signature · 1 line
2.43.0
#16 lore raw

Re: [PATCH v4 06/11] KVM: arm64: CCA: Destroy RTTs

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] KVM: arm64: CCA: commit message describes start_level change from parent commit --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] KVM: arm64: CCA: commit message describes start_level change from parent commit
--

commit 31acfdb8b4fe1e156914926f66bf5cbc470cc71b
Author: Steven Price <[email protected]>

KVM: arm64: CCA: Destroy RTTs

This commit implements Realm Translation Table (RTT) destruction and undelegation during Realm stage-2 teardown and final VM destruction.

Quoted 4 lines

Use the same minimum of two stage-2 levels as VTCR when deriving the Realm's starting RTT level. Without this, narrow IPAs on 64K-page hosts can give the RMM a different starting level from KVM's own page tables.

[Severity: Low]
Does this paragraph belong in the commit message for commit "KVM: arm64:
CCA: Add basic infrastructure for creating a realm" instead?

That earlier patch in the series introduces realm->start_level = 4 - VTCR_EL2_LVLS(kvm->arch.mmu.vtcr) in kvm_init_realm(), while this patch does not touch how start_level is derived.

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

Re: [PATCH v4 06/11] KVM: arm64: CCA: Destroy RTTs

In reply to Steven Price
Quoted 12 lines · Steven Price

The RMM owns the stage 2 page tables for a realm, and KVM must request that the RMM creates/destroys entries as necessary. The physical pages to store the page tables are delegated to the realm as required, and can be undelegated when no longer used.

Creating new RTTs is the easy part, destroying them is a little more tricky. The result of realm_rtt_destroy() can be used to effectively walk the tree and destroy the entries (undelegating pages that were given to the realm).

Quoted 5 lines

Tear down a created Realm whether it is still new or has been activated. Unmap the Realm IPA space once during stage-2 teardown. Defer destruction of non-root RTTs until final Realm destruction, after REALM_TERMINATE and before destroying the RD; root RTTs remain until the RD has gone away.

While I understand what this is trying to convey, it may be unclear to someone who is not familiar with the "Realm Liveness". How about something like :

Realm can be destroyed ONLY if all stage2 Root RTTs are not live (along with no RECs or other resources assigned to it). i.e., there are no live mappings or tables mapped from the Root tables. So, we unmap the entire stage2 and move the Realm to ZOMBIE state then destroy all the non-root level RTTs. The Root level RTTs can only be reclaimed after the RD is destroyed.

The comment in the code is actually pretty clear.

Quoted 5 lines

Use the same minimum of two stage-2 levels as VTCR when deriving the Realm's starting RTT level. Without this, narrow IPAs on 64K-page hosts can give the RMM a different starting level from KVM's own page tables.

I believe this paragraph can go as we now have start_level cached.

Quoted 205 lines

---
Changes since v3:
- Match VTCR's minimum of two stage-2 levels for Realm RTTs.
- Use explicit config_lock cleanup in Realm destruction.

Changes since v2:
- Use the actual stage-2 start level and correct the RTT skip granularity. Free SRO state on final teardown errors.

Changes since v1:
- Tear down created Realms in both NEW and ACTIVE states. Fix the RTT start level, page accounting on failed undelegation, and handling of RTT granules returned by RMI.

---
  arch/arm64/include/asm/kvm_rmi.h |   3 +
  arch/arm64/kvm/mmu.c             |  17 ++-
  arch/arm64/kvm/rmi.c             | 178 +++++++++++++++++++++++++++++++
  3 files changed, 197 insertions(+), 1 deletion(-)
arch/arm64/include/asm/kvm_rmi.h +3 -0
index 4ac1af622872..01ecaabd839b 100644
@@ -58,6 +58,7 @@ enum realm_state {
   * @state: The lifetime state machine for the realm
   * @ia_bits: Number of valid Input Address bits in the IPA
   * @start_level: Starting level of the Realm Translation Table
+ * @stage2_unmapped: The Realm stage-2 mappings have been removed
   */
  struct realm {
  	phys_addr_t rd_phys;
@@ -72,11 +73,13 @@ struct realm {
  	enum realm_state state;
  	unsigned int ia_bits;
  	int start_level;
+	bool stage2_unmapped;
  };
 
  u32 kvm_rmm_ipa_limit(void);
 
  int kvm_init_realm(struct kvm *kvm);
  void kvm_destroy_realm(struct kvm *kvm);
+void kvm_realm_unmap_stage2_all(struct kvm *kvm);
 
  #endif /* __ASM_KVM_RMI_H */
arch/arm64/kvm/mmu.c +16 -1
index 84b02699f103..4a975715375c 100644
@@ -1149,9 +1149,24 @@ int kvm_init_stage2_mmu(struct kvm *kvm, struct kvm_s2_mmu *mmu, unsigned long t
  	return err;
  }
 
+static void kvm_realm_uninit_stage2(struct kvm_s2_mmu *mmu)
+{
+	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
+
+	guard(mutex)(&kvm->arch.config_lock);
+	if (kvm_realm_state(kvm) == REALM_STATE_NEW ||
+	    kvm_realm_state(kvm) == REALM_STATE_ACTIVE) {
+		kvm_set_realm_state(kvm, REALM_STATE_DYING);
+		kvm_realm_unmap_stage2_all(kvm);
+	}
+}
+
  void kvm_uninit_stage2_mmu(struct kvm *kvm)
  {
-	kvm_free_stage2_pgd(&kvm->arch.mmu);
+	if (kvm_realm_is_created(kvm))
+		kvm_realm_uninit_stage2(&kvm->arch.mmu);
+	else
+		kvm_free_stage2_pgd(&kvm->arch.mmu);
  	kvm_mmu_free_memory_cache(&kvm->arch.mmu.split_page_cache);
  }
 
arch/arm64/kvm/rmi.c +119 -0
index fafca2439c46..435174ac3d87 100644
@@ -16,22 +16,196 @@ u32 kvm_rmm_ipa_limit(void)
  	return u64_get_bits(rmi_feat_reg(0), RMI_FEATURE_REGISTER_0_S2SZ);
  }
 
+static void free_rtt(phys_addr_t phys)
+{
+	kvm_account_pgtable_pages(phys_to_virt(phys), -1);
+	if (rmi_free_delegated_page(phys))
+		kvm_account_pgtable_pages(phys_to_virt(phys), 1);
+}
+
+/*
+ * realm_rtt_destroy - Destroy an RTT at @level for @addr.
+ *
+ * Returns - Result of the RMI_RTT_DESTROY call, and:
+ * @rtt_granule:	RTT granule, if the RTT was destroyed.
+ * @next_addr:		IPA corresponding to the next possible valid entry we
+ *			can target
+ */
+static long realm_rtt_destroy(struct realm *realm, unsigned long addr,
+			      int level, phys_addr_t *rtt_granule,
+			      unsigned long *next_addr)
+{
+	unsigned long out_rtt;
+	long ret;
+
+	ret = rmi_rtt_destroy(realm->rd_phys, addr, level,
+			      &out_rtt, next_addr);
+
+	if (ret == RMI_SUCCESS)
+		*rtt_granule = out_rtt;
+
+	return ret;
+}
+
+static int realm_destroy_rtt_level(struct realm *realm, int level,
+				   unsigned long start, unsigned long end)
+{
+	ssize_t map_size;
+	unsigned long addr, next_addr;
+
+	if (WARN_ON(level > KVM_PGTABLE_LAST_LEVEL))
+		return -EINVAL;
+
+	map_size = kvm_granule_size(level - 1);
+	if (WARN_ON(!IS_ALIGNED(start, map_size)))
+		return -EINVAL;
+
+	for (addr = start; addr < end; addr = next_addr) {
+		phys_addr_t rtt_granule;
+		long ret;
+		unsigned long align_addr = ALIGN(addr, map_size);
+
+		next_addr = ALIGN(addr + 1, map_size);
+
+		if (next_addr > end || align_addr != addr) {
+			/*
+			 * The target range is smaller than what this level
+			 * covers, recurse deeper.
+			 */
+			ret = realm_destroy_rtt_level(realm,
+						      level + 1,
+						      addr,
+						      min(next_addr, end));
+			if (ret)
+				return ret;
+			continue;
+		}
+
+		ret = realm_rtt_destroy(realm, addr, level,
+					&rtt_granule, &next_addr);
+		if (ret < 0)
+			return ret;
+
+		switch (RMI_RESULT_STATUS(ret)) {
+		case RMI_SUCCESS:
+			free_rtt(rtt_granule);
+			break;
+		case RMI_ERROR_RTT:
+			if (next_addr > addr) {
+				/* Missing RTT, skip */
+				break;
+			}
+			/*
+			 * We destroy the RTT range for the full IPA
+			 * space, after everything is unmapped. Also we
+			 * descend down only if we cannot destroy a
+			 * top level RTT. Thus RMM must be able to walk
+			 * to the requested level. e.g., a block mapping
+			 * exists at L1 or L2.
+			 */
+			if (WARN_ON(RMI_RESULT_DATA_LEVEL(ret) != level))
+				return -EBUSY;
+			if (WARN_ON(level == KVM_PGTABLE_LAST_LEVEL))
+				return -EBUSY;
+
+			/*
+			 * The table has active entries in it, recurse deeper
+			 * and destroy the RTTs.
+			 */
+			next_addr = ALIGN(addr + 1, map_size);
+			ret = realm_destroy_rtt_level(realm,
+						      level + 1,
+						      addr,
+						      next_addr);
+			if (ret)
+				return ret;
+			/*
+			 * Now that the child RTTs are destroyed,
+			 * retry at this level.
+			 */
+			next_addr = addr;
+			break;
+		default:
+			WARN_ON(1);
+			return -ENXIO;
+		}
+	}
+
+	return 0;
+}
+
+static int realm_destroy_rtt_range(struct realm *realm,

arch/arm64/kvm/rmi.c u32 kvm_rmm_ipa_limit(void) · line 147

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+				   unsigned long start, unsigned long end)
+{
+	/*
+	 * Root level RTTs can only be destroyed after the RD is destroyed. So
+	 * destroy everything below the root level
+	 */
+	return realm_destroy_rtt_level(realm, realm->start_level + 1,
+				       start, end);
+}
+

minor nit: May be we could fold the above into realm_destroy_rtts()

Quoted 27 lines
arch/arm64/kvm/rmi.c +27 -0
+static int realm_destroy_rtts(struct kvm *kvm)
+{
+	struct realm *realm = &kvm->arch.realm;
+	unsigned int ia_bits = realm->ia_bits;
+
+	lockdep_assert_held(&kvm->arch.config_lock);
+
+	return realm_destroy_rtt_range(realm, 0, (1UL << ia_bits));
+}
+
+void kvm_realm_unmap_stage2_all(struct kvm *kvm)
+{
+	struct realm *realm = &kvm->arch.realm;
+
+	lockdep_assert_held(&kvm->arch.config_lock);
+
+	if (realm->stage2_unmapped)
+		return;
+
+	write_lock(&kvm->mmu_lock);
+	kvm_stage2_unmap_range(&kvm->arch.mmu, 0,
+			       BIT(realm->ia_bits - 1), true);
+	write_unlock(&kvm->mmu_lock);
+
+	realm->stage2_unmapped = true;
+}
+

arch/arm64/kvm/rmi.c u32 kvm_rmm_ipa_limit(void) · line 184

Quoted 10 lines
arch/arm64/kvm/rmi.c +5 -0
  void kvm_destroy_realm(struct kvm *kvm)
  {
  	struct realm *realm = &kvm->arch.realm;
  	size_t pgd_size = kvm_pgtable_stage2_pgd_size(kvm->arch.mmu.vtcr);
 
+	/*
+	 * Serialize final Realm destruction with Realm creation and stage-2 unmapping,
+	 * which also access Realm state under config_lock.
+	 */
+	mutex_lock(&kvm->arch.config_lock);

minor nit: guard(mutex)() ?

Quoted 29 lines
arch/arm64/kvm/rmi.c +13 -0
+
  	if (!kvm_realm_is_created(kvm))
  		goto out_free_sro;
 
  	kvm_set_realm_state(kvm, REALM_STATE_DYING);
 
+	/*
+	 * REALM_DESTROY requires the realm to be non-live: all RECs must have
+	 * been destroyed and the root RTTs must be empty. Unmap the IPA space
+	 * and destroy any non-root RTTs before tearing down the RD. The root
+	 * RTT pages are still owned by the RMM at this point, so keep the KVM
+	 * pgtable alive until after REALM_DESTROY and undelegation.
+	 */
+	kvm_realm_unmap_stage2_all(kvm);
+
  	if (realm->rd_phys) {
  		phys_addr_t rd_phys = realm->rd_phys;
 
  		if (WARN_ON(rmi_realm_terminate(rd_phys, realm->sro)))
  			goto out_free_sro;
 
+		if (WARN_ON(realm_destroy_rtts(kvm)))
+			goto out_free_sro;
+
  		if (WARN_ON(rmi_realm_destroy(rd_phys, realm->sro)))
  			goto out_free_sro;
  		rmi_free_delegated_page(rd_phys);
@@ -44,9 +218,13 @@ void kvm_destroy_realm(struct kvm *kvm)
 

arch/arm64/kvm/rmi.c void kvm_destroy_realm(struct kvm *kvm) · line 228

Quoted 10 lines
arch/arm64/kvm/rmi.c +4 -0
  	kvm_set_realm_state(kvm, REALM_STATE_DEAD);
 
+	/* Now that the realm is destroyed, free the entry-level RTTs. */
+	kvm_free_stage2_pgd(&kvm->arch.mmu);
+
  out_free_sro:
  	kfree(realm->sro);
  	realm->sro = NULL;
+	mutex_unlock(&kvm->arch.config_lock);
  }

Suzuki

#18 lore raw

Re: [PATCH v4 06/11] KVM: arm64: CCA: Destroy RTTs

Quoted 269 lines · Suzuki K Poulose
Quoted 12 lines · Steven Price

The RMM owns the stage 2 page tables for a realm, and KVM must request that the RMM creates/destroys entries as necessary. The physical pages to store the page tables are delegated to the realm as required, and can be undelegated when no longer used.

Creating new RTTs is the easy part, destroying them is a little more tricky. The result of realm_rtt_destroy() can be used to effectively walk the tree and destroy the entries (undelegating pages that were given to the realm).

Quoted 5 lines

Tear down a created Realm whether it is still new or has been activated. Unmap the Realm IPA space once during stage-2 teardown. Defer destruction of non-root RTTs until final Realm destruction, after REALM_TERMINATE and before destroying the RD; root RTTs remain until the RD has gone away.

While I understand what this is trying to convey, it may be unclear to someone who is not familiar with the "Realm Liveness". How about something like :

Realm can be destroyed ONLY if all stage2 Root RTTs are not live (along with no RECs or other resources assigned to it). i.e., there are no live mappings or tables mapped from the Root tables. So, we unmap the entire stage2 and move the Realm to ZOMBIE state then destroy all the non-root level RTTs. The Root level RTTs can only be reclaimed after the RD is destroyed.

The comment in the code is actually pretty clear.

Quoted 5 lines

Use the same minimum of two stage-2 levels as VTCR when deriving the Realm's starting RTT level. Without this, narrow IPAs on 64K-page hosts can give the RMM a different starting level from KVM's own page tables.

I believe this paragraph can go as we now have start_level cached.

Quoted 210 lines

---
Changes since v3:
- Match VTCR's minimum of two stage-2 levels for Realm RTTs.
- Use explicit config_lock cleanup in Realm destruction.

Changes since v2:
- Use the actual stage-2 start level and correct the RTT skip granularity. Free SRO state on final teardown errors.

Changes since v1:
- Tear down created Realms in both NEW and ACTIVE states. Fix the RTT start level, page accounting on failed undelegation, and handling of RTT granules returned by RMI.
---
  arch/arm64/include/asm/kvm_rmi.h |   3 + arch/arm64/kvm/mmu.c             |  17 ++- arch/arm64/kvm/rmi.c             | 178 +++++++++++++++++++++++++++++++

  3 files changed, 197 insertions(+), 1 deletion(-)
arch/arm64/include/asm/kvm_rmi.h +3 -0
index 4ac1af622872..01ecaabd839b 100644
@@ -58,6 +58,7 @@ enum realm_state {
    * @state: The lifetime state machine for the realm
    * @ia_bits: Number of valid Input Address bits in the IPA
    * @start_level: Starting level of the Realm Translation Table
+ * @stage2_unmapped: The Realm stage-2 mappings have been removed
    */
   struct realm {
       phys_addr_t rd_phys;
@@ -72,11 +73,13 @@ struct realm {
       enum realm_state state;
       unsigned int ia_bits;
       int start_level;
+    bool stage2_unmapped;
   };
   u32 kvm_rmm_ipa_limit(void);
   int kvm_init_realm(struct kvm *kvm);
   void kvm_destroy_realm(struct kvm *kvm);
+void kvm_realm_unmap_stage2_all(struct kvm *kvm);
   #endif /* __ASM_KVM_RMI_H */
arch/arm64/kvm/mmu.c +0 -0
index 84b02699f103..4a975715375c 100644
@@ -1149,9 +1149,24 @@ int kvm_init_stage2_mmu(struct kvm *kvm, struct 

kvm_s2_mmu *mmu, unsigned long t
      return err;
  }

arch/arm64/kvm/mmu.c +12 -0
+static void kvm_realm_uninit_stage2(struct kvm_s2_mmu *mmu)
+{
+    struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
+
+    guard(mutex)(&kvm->arch.config_lock);
+    if (kvm_realm_state(kvm) == REALM_STATE_NEW ||
+        kvm_realm_state(kvm) == REALM_STATE_ACTIVE) {
+        kvm_set_realm_state(kvm, REALM_STATE_DYING);
+        kvm_realm_unmap_stage2_all(kvm);
+    }
+}
+

  void kvm_uninit_stage2_mmu(struct kvm *kvm)
  {
-    kvm_free_stage2_pgd(&kvm->arch.mmu);
+    if (kvm_realm_is_created(kvm))
+        kvm_realm_uninit_stage2(&kvm->arch.mmu);
+    else
+        kvm_free_stage2_pgd(&kvm->arch.mmu); kvm_mmu_free_memory_cache(&kvm->arch.mmu.split_page_cache); }

arch/arm64/kvm/rmi.c +13 -0
index fafca2439c46..435174ac3d87 100644
@@ -16,22 +16,196 @@ u32 kvm_rmm_ipa_limit(void)
       return u64_get_bits(rmi_feat_reg(0), RMI_FEATURE_REGISTER_0_S2SZ);
   }
+static void free_rtt(phys_addr_t phys)
+{
+    kvm_account_pgtable_pages(phys_to_virt(phys), -1);
+    if (rmi_free_delegated_page(phys))
+        kvm_account_pgtable_pages(phys_to_virt(phys), 1);
+}
+
+/*
+ * realm_rtt_destroy - Destroy an RTT at @level for @addr.
+ *
+ * Returns - Result of the RMI_RTT_DESTROY call, and:
+ * @rtt_granule:    RTT granule, if the RTT was destroyed.
+ * @next_addr:        IPA corresponding to the next possible valid 

entry we
+ *            can target
+ */

arch/arm64/kvm/rmi.c +108 -0
+static long realm_rtt_destroy(struct realm *realm, unsigned long addr,
+                  int level, phys_addr_t *rtt_granule,
+                  unsigned long *next_addr)
+{
+    unsigned long out_rtt;
+    long ret;
+
+    ret = rmi_rtt_destroy(realm->rd_phys, addr, level,
+                  &out_rtt, next_addr);
+
+    if (ret == RMI_SUCCESS)
+        *rtt_granule = out_rtt;
+
+    return ret;
+}
+
+static int realm_destroy_rtt_level(struct realm *realm, int level,
+                   unsigned long start, unsigned long end)
+{
+    ssize_t map_size;
+    unsigned long addr, next_addr;
+
+    if (WARN_ON(level > KVM_PGTABLE_LAST_LEVEL))
+        return -EINVAL;
+
+    map_size = kvm_granule_size(level - 1);
+    if (WARN_ON(!IS_ALIGNED(start, map_size)))
+        return -EINVAL;
+
+    for (addr = start; addr < end; addr = next_addr) {
+        phys_addr_t rtt_granule;
+        long ret;
+        unsigned long align_addr = ALIGN(addr, map_size);
+
+        next_addr = ALIGN(addr + 1, map_size);
+
+        if (next_addr > end || align_addr != addr) {
+            /*
+             * The target range is smaller than what this level
+             * covers, recurse deeper.
+             */
+            ret = realm_destroy_rtt_level(realm,
+                              level + 1,
+                              addr,
+                              min(next_addr, end));
+            if (ret)
+                return ret;
+            continue;
+        }
+
+        ret = realm_rtt_destroy(realm, addr, level,
+                    &rtt_granule, &next_addr);
+        if (ret < 0)
+            return ret;
+
+        switch (RMI_RESULT_STATUS(ret)) {
+        case RMI_SUCCESS:
+            free_rtt(rtt_granule);
+            break;
+        case RMI_ERROR_RTT:
+            if (next_addr > addr) {
+                /* Missing RTT, skip */
+                break;
+            }
+            /*
+             * We destroy the RTT range for the full IPA
+             * space, after everything is unmapped. Also we
+             * descend down only if we cannot destroy a
+             * top level RTT. Thus RMM must be able to walk
+             * to the requested level. e.g., a block mapping
+             * exists at L1 or L2.
+             */
+            if (WARN_ON(RMI_RESULT_DATA_LEVEL(ret) != level))
+                return -EBUSY;
+            if (WARN_ON(level == KVM_PGTABLE_LAST_LEVEL))
+                return -EBUSY;
+
+            /*
+             * The table has active entries in it, recurse deeper
+             * and destroy the RTTs.
+             */
+            next_addr = ALIGN(addr + 1, map_size);
+            ret = realm_destroy_rtt_level(realm,
+                              level + 1,
+                              addr,
+                              next_addr);
+            if (ret)
+                return ret;
+            /*
+             * Now that the child RTTs are destroyed,
+             * retry at this level.
+             */
+            next_addr = addr;
+            break;
+        default:
+            WARN_ON(1);
+            return -ENXIO;
+        }
+    }
+
+    return 0;
+}
+
+static int realm_destroy_rtt_range(struct realm *realm,
+                   unsigned long start, unsigned long end)
+{
+    /*
+     * Root level RTTs can only be destroyed after the RD is 

destroyed. So
+     * destroy everything below the root level
+     */
+    return realm_destroy_rtt_level(realm, realm->start_level + 1, +                       start, end);

arch/arm64/kvm/rmi.c

Quoted 2 lines
arch/arm64/kvm/rmi.c +2 -0
+}
+

minor nit: May be we could fold the above into realm_destroy_rtts()

Quoted 14 lines
arch/arm64/kvm/rmi.c +14 -0
+static int realm_destroy_rtts(struct kvm *kvm)
+{
+    struct realm *realm = &kvm->arch.realm;
+    unsigned int ia_bits = realm->ia_bits;
+
+    lockdep_assert_held(&kvm->arch.config_lock);
+
+    return realm_destroy_rtt_range(realm, 0, (1UL << ia_bits));
+}
+
+void kvm_realm_unmap_stage2_all(struct kvm *kvm)
+{
+    struct realm *realm = &kvm->arch.realm;
+
Quoted 8 lines

arch/arm64/kvm/rmi.c u32 kvm_rmm_ipa_limit(void) · line 169

Quoted 8 lines

+    lockdep_assert_held(&kvm->arch.config_lock);

arch/arm64/kvm/rmi.c +7 -0
+
+    if (realm->stage2_unmapped)
+        return;
+
+    write_lock(&kvm->mmu_lock);
+    kvm_stage2_unmap_range(&kvm->arch.mmu, 0,
+                   BIT(realm->ia_bits - 1), true);

Actually, the unprotected IPA mapping entries are not "live". So we could unmap only the protected IPA half and destroy the RTTs directly on the unprotected IPA.

Suzuki

#19 lore raw

Re: [PATCH v4 06/11] KVM: arm64: CCA: Destroy RTTs

In reply to Suzuki K Poulose
Quoted 23 lines · Suzuki K Poulose
Quoted 12 lines · Steven Price

The RMM owns the stage 2 page tables for a realm, and KVM must request that the RMM creates/destroys entries as necessary. The physical pages to store the page tables are delegated to the realm as required, and can be undelegated when no longer used.

Creating new RTTs is the easy part, destroying them is a little more tricky. The result of realm_rtt_destroy() can be used to effectively walk the tree and destroy the entries (undelegating pages that were given to the realm).

Quoted 5 lines

Tear down a created Realm whether it is still new or has been activated. Unmap the Realm IPA space once during stage-2 teardown. Defer destruction of non-root RTTs until final Realm destruction, after REALM_TERMINATE and before destroying the RD; root RTTs remain until the RD has gone away.

While I understand what this is trying to convey, it may be unclear to someone who is not familiar with the "Realm Liveness". How about something like :

Quoted 8 lines

Realm can be destroyed ONLY if all stage2 Root RTTs are not live (along with no RECs or other resources assigned to it). i.e., there are no live mappings or tables mapped from the Root tables. So, we unmap the entire stage2 and move the Realm to ZOMBIE state then destroy all the non-root level RTTs. The Root level RTTs can only be reclaimed after the RD is destroyed.

The comment in the code is actually pretty clear.

Thanks, I'll reword. And also update it to include your later reply that unprotected doesn't mean live.

Quoted 7 lines
Quoted 5 lines

Use the same minimum of two stage-2 levels as VTCR when deriving the Realm's starting RTT level. Without this, narrow IPAs on 64K-page hosts can give the RMM a different starting level from KVM's own page tables.

I believe this paragraph can go as we now have start_level cached.

Yep, Sashiko noticed that too ;)

Quoted 207 lines
Quoted 207 lines

---
Changes since v3:
- Match VTCR's minimum of two stage-2 levels for Realm RTTs.
- Use explicit config_lock cleanup in Realm destruction.

Changes since v2:
- Use the actual stage-2 start level and correct the RTT skip granularity. Free SRO state on final teardown errors.

Changes since v1:
- Tear down created Realms in both NEW and ACTIVE states. Fix the RTT start level, page accounting on failed undelegation, and handling of RTT granules returned by RMI.
---
  arch/arm64/include/asm/kvm_rmi.h |   3 + arch/arm64/kvm/mmu.c             |  17 ++- arch/arm64/kvm/rmi.c             | 178 +++++++++++++++++++++++++++++++

  3 files changed, 197 insertions(+), 1 deletion(-)
arch/arm64/include/ renamed from arch/arm64/include/asm/kvm_rmi.h +0 -0

asm/kvm_rmi.h
index 4ac1af622872..01ecaabd839b 100644

arch/arm64/include/asm/kvm_rmi.h +3 -0
@@ -58,6 +58,7 @@ enum realm_state {
    * @state: The lifetime state machine for the realm
    * @ia_bits: Number of valid Input Address bits in the IPA
    * @start_level: Starting level of the Realm Translation Table
+ * @stage2_unmapped: The Realm stage-2 mappings have been removed
    */
   struct realm {
       phys_addr_t rd_phys;
@@ -72,11 +73,13 @@ struct realm {
       enum realm_state state;
       unsigned int ia_bits;
       int start_level;
+    bool stage2_unmapped;
   };
     u32 kvm_rmm_ipa_limit(void);
     int kvm_init_realm(struct kvm *kvm);
   void kvm_destroy_realm(struct kvm *kvm);
+void kvm_realm_unmap_stage2_all(struct kvm *kvm);
     #endif /* __ASM_KVM_RMI_H */
arch/arm64/kvm/mmu.c +0 -0
index 84b02699f103..4a975715375c 100644
@@ -1149,9 +1149,24 @@ int kvm_init_stage2_mmu(struct kvm *kvm, struct

kvm_s2_mmu *mmu, unsigned long t
      return err;
  }
  +static void kvm_realm_uninit_stage2(struct kvm_s2_mmu *mmu)

arch/arm64/kvm/mmu.c +11 -0
+{
+    struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
+
+    guard(mutex)(&kvm->arch.config_lock);
+    if (kvm_realm_state(kvm) == REALM_STATE_NEW ||
+        kvm_realm_state(kvm) == REALM_STATE_ACTIVE) {
+        kvm_set_realm_state(kvm, REALM_STATE_DYING);
+        kvm_realm_unmap_stage2_all(kvm);
+    }
+}
+

  void kvm_uninit_stage2_mmu(struct kvm *kvm)
  {
-    kvm_free_stage2_pgd(&kvm->arch.mmu);
+    if (kvm_realm_is_created(kvm))
+        kvm_realm_uninit_stage2(&kvm->arch.mmu);
+    else
+        kvm_free_stage2_pgd(&kvm->arch.mmu); kvm_mmu_free_memory_cache(&kvm->arch.mmu.split_page_cache); }
  diff --git a/arch/arm64/kvm/rmi.c b/arch/arm64/kvm/rmi.c index fafca2439c46..435174ac3d87 100644

arch/arm64/kvm/rmi.c +12 -0
@@ -16,22 +16,196 @@ u32 kvm_rmm_ipa_limit(void)
       return u64_get_bits(rmi_feat_reg(0), RMI_FEATURE_REGISTER_0_S2SZ);
   }
   +static void free_rtt(phys_addr_t phys)
+{
+    kvm_account_pgtable_pages(phys_to_virt(phys), -1);
+    if (rmi_free_delegated_page(phys))
+        kvm_account_pgtable_pages(phys_to_virt(phys), 1);
+}
+
+/*
+ * realm_rtt_destroy - Destroy an RTT at @level for @addr.
+ *
+ * Returns - Result of the RMI_RTT_DESTROY call, and:
+ * @rtt_granule:    RTT granule, if the RTT was destroyed.
+ * @next_addr:        IPA corresponding to the next possible valid

entry we
+ *            can target
+ */

arch/arm64/kvm/rmi.c +108 -0
+static long realm_rtt_destroy(struct realm *realm, unsigned long addr,
+                  int level, phys_addr_t *rtt_granule,
+                  unsigned long *next_addr)
+{
+    unsigned long out_rtt;
+    long ret;
+
+    ret = rmi_rtt_destroy(realm->rd_phys, addr, level,
+                  &out_rtt, next_addr);
+
+    if (ret == RMI_SUCCESS)
+        *rtt_granule = out_rtt;
+
+    return ret;
+}
+
+static int realm_destroy_rtt_level(struct realm *realm, int level,
+                   unsigned long start, unsigned long end)
+{
+    ssize_t map_size;
+    unsigned long addr, next_addr;
+
+    if (WARN_ON(level > KVM_PGTABLE_LAST_LEVEL))
+        return -EINVAL;
+
+    map_size = kvm_granule_size(level - 1);
+    if (WARN_ON(!IS_ALIGNED(start, map_size)))
+        return -EINVAL;
+
+    for (addr = start; addr < end; addr = next_addr) {
+        phys_addr_t rtt_granule;
+        long ret;
+        unsigned long align_addr = ALIGN(addr, map_size);
+
+        next_addr = ALIGN(addr + 1, map_size);
+
+        if (next_addr > end || align_addr != addr) {
+            /*
+             * The target range is smaller than what this level
+             * covers, recurse deeper.
+             */
+            ret = realm_destroy_rtt_level(realm,
+                              level + 1,
+                              addr,
+                              min(next_addr, end));
+            if (ret)
+                return ret;
+            continue;
+        }
+
+        ret = realm_rtt_destroy(realm, addr, level,
+                    &rtt_granule, &next_addr);
+        if (ret < 0)
+            return ret;
+
+        switch (RMI_RESULT_STATUS(ret)) {
+        case RMI_SUCCESS:
+            free_rtt(rtt_granule);
+            break;
+        case RMI_ERROR_RTT:
+            if (next_addr > addr) {
+                /* Missing RTT, skip */
+                break;
+            }
+            /*
+             * We destroy the RTT range for the full IPA
+             * space, after everything is unmapped. Also we
+             * descend down only if we cannot destroy a
+             * top level RTT. Thus RMM must be able to walk
+             * to the requested level. e.g., a block mapping
+             * exists at L1 or L2.
+             */
+            if (WARN_ON(RMI_RESULT_DATA_LEVEL(ret) != level))
+                return -EBUSY;
+            if (WARN_ON(level == KVM_PGTABLE_LAST_LEVEL))
+                return -EBUSY;
+
+            /*
+             * The table has active entries in it, recurse deeper
+             * and destroy the RTTs.
+             */
+            next_addr = ALIGN(addr + 1, map_size);
+            ret = realm_destroy_rtt_level(realm,
+                              level + 1,
+                              addr,
+                              next_addr);
+            if (ret)
+                return ret;
+            /*
+             * Now that the child RTTs are destroyed,
+             * retry at this level.
+             */
+            next_addr = addr;
+            break;
+        default:
+            WARN_ON(1);
+            return -ENXIO;
+        }
+    }
+
+    return 0;
+}
+
+static int realm_destroy_rtt_range(struct realm *realm,
+                   unsigned long start, unsigned long end)
+{
+    /*
+     * Root level RTTs can only be destroyed after the RD is

destroyed. So

Quoted 8 lines

arch/arm64/kvm/rmi.c

Quoted 6 lines

+     * destroy everything below the root level
+     */
+    return realm_destroy_rtt_level(realm, realm->start_level + 1, +                       start, end);

arch/arm64/kvm/rmi.c +2 -0
+}
+

minor nit: May be we could fold the above into realm_destroy_rtts()

Fair point - I'll update.

Quoted 14 lines
Quoted 14 lines
arch/arm64/kvm/rmi.c +14 -0
+static int realm_destroy_rtts(struct kvm *kvm)
+{
+    struct realm *realm = &kvm->arch.realm;
+    unsigned int ia_bits = realm->ia_bits;
+
+    lockdep_assert_held(&kvm->arch.config_lock);
+
+    return realm_destroy_rtt_range(realm, 0, (1UL << ia_bits));
+}
+
+void kvm_realm_unmap_stage2_all(struct kvm *kvm)
+{
+    struct realm *realm = &kvm->arch.realm;
+
Quoted 8 lines

arch/arm64/kvm/rmi.c u32 kvm_rmm_ipa_limit(void) · line 169

Quoted 8 lines

+    lockdep_assert_held(&kvm->arch.config_lock);

arch/arm64/kvm/rmi.c +7 -0
+
+    if (realm->stage2_unmapped)
+        return;
+
+    write_lock(&kvm->mmu_lock);
+    kvm_stage2_unmap_range(&kvm->arch.mmu, 0,
+                   BIT(realm->ia_bits - 1), true);

As you menion in your follow up - this can be restricted to just protected mappings.

Quoted 9 lines
Quoted 9 lines

+    write_unlock(&kvm->mmu_lock);

arch/arm64/kvm/rmi.c +4 -0
+
+    realm->stage2_unmapped = true;
+}
+

  void kvm_destroy_realm(struct kvm *kvm)
  {
      struct realm *realm = &kvm->arch.realm;
      size_t pgd_size = kvm_pgtable_stage2_pgd_size(kvm->arch.mmu.vtcr);

Quoted 8 lines
Quoted 6 lines

  +    /*
+     * Serialize final Realm destruction with Realm creation and stage-2 unmapping,
+     * which also access Realm state under config_lock. +     */
+    mutex_lock(&kvm->arch.config_lock);

minor nit: guard(mutex)() ?

Ack.

Thanks,
Steve

Quoted 42 lines
Quoted 30 lines

+
      if (!kvm_realm_is_created(kvm))
          goto out_free_sro;
        kvm_set_realm_state(kvm, REALM_STATE_DYING);
  +    /*
+     * REALM_DESTROY requires the realm to be non-live: all RECs must have
+     * been destroyed and the root RTTs must be empty. Unmap the IPA space
+     * and destroy any non-root RTTs before tearing down the RD. The root
+     * RTT pages are still owned by the RMM at this point, so keep the KVM
+     * pgtable alive until after REALM_DESTROY and undelegation. +     */
+    kvm_realm_unmap_stage2_all(kvm);
+
      if (realm->rd_phys) {
          phys_addr_t rd_phys = realm->rd_phys;
            if (WARN_ON(rmi_realm_terminate(rd_phys, realm->sro))) goto out_free_sro;
  +        if (WARN_ON(realm_destroy_rtts(kvm)))
+            goto out_free_sro;
+
          if (WARN_ON(rmi_realm_destroy(rd_phys, realm->sro))) goto out_free_sro; rmi_free_delegated_page(rd_phys);

arch/arm64/kvm/rmi.c +0 -0
@@ -44,9 +218,13 @@ void kvm_destroy_realm(struct kvm *kvm)
         kvm_set_realm_state(kvm, REALM_STATE_DEAD);
Quoted 8 lines

  +    /* Now that the realm is destroyed, free the entry-level RTTs. */ +    kvm_free_stage2_pgd(&kvm->arch.mmu);
+
  out_free_sro:
      kfree(realm->sro);
      realm->sro = NULL;
+    mutex_unlock(&kvm->arch.config_lock);
  }

Suzuki

#20 lore raw

PATCH v4 7/11 KVM: arm64: CCA: Add Realm RTT mapping and invalidation helpers

In reply to Steven Price

Add the RMI RTT creation and unmap helpers needed by CCA Realm stage-2 memory operations. REC exit handling and guest requested RIPAS changes follow in the vCPU series.

---
Changes since v3:
- Use the VTCR-derived Realm start level for RTT operations.

Changes since v2:
- Use a local MMU cache during notifier invalidation, handle failed RTT splits, and validate RMI levels and cache state.

Changes since v1:
- Rework RTT creation and folding around missing or existing RTTs. Use a shared RMI block-size helper and handle alignment, partial progress and errors in range operations.

---
 arch/arm64/include/asm/kvm_rmi.h |   8 +
 arch/arm64/kvm/rmi.c             | 421 +++++++++++++++++++++++++++++++
 drivers/firmware/arm_rmm/rmi.c   |  10 -
 include/linux/arm-rmi-cmds.h     |   8 +
 4 files changed, 437 insertions(+), 10 deletions(-)
arch/arm64/include/asm/kvm_rmi.h +8 -0
index 01ecaabd839b..8a136fb67318 100644
@@ -82,4 +82,12 @@ int kvm_init_realm(struct kvm *kvm);
 void kvm_destroy_realm(struct kvm *kvm);
 void kvm_realm_unmap_stage2_all(struct kvm *kvm);
 
+enum kvm_gfn_range_filter;
+
+void kvm_realm_unmap_range_filter(struct kvm *kvm,
+				  unsigned long ipa,
+				  unsigned long size,
+				  bool may_block,
+				  enum kvm_gfn_range_filter attr_filter);
+
 #endif /* __ASM_KVM_RMI_H */
arch/arm64/kvm/rmi.c +421 -0

457 lines not on this page · raw message

drivers/firmware/arm_rmm/rmi.c +0 -10
index 77255a90e0a6..a9f42c9a4f79 100644
@@ -11,7 +11,6 @@
 #include <linux/slab.h>
 
 #include <asm/memory.h>
-#include <asm/pgtable-hwdef.h>
 
 /* RMM v2.0 defines RmiFeatureRegister0 to RmiFeatureRegister4. */
 static unsigned long rmi_feat_reg_cache[5] __ro_after_init;
@@ -183,15 +182,6 @@ int rmi_free_delegated_page(phys_addr_t phys)
 }
 EXPORT_SYMBOL_GPL(rmi_free_delegated_page);
 
-/*
- * Convert the RmiAddrBlockSize to actual size. This is used in RmiDonateReq
- * and RmiAddrRangeDesc*.
- */
-static unsigned long rmi_addr_block_size_to_bytes(unsigned long block_size_fld)
-{
-	return BIT(ARM64_HW_PGTABLE_LEVEL_SHIFT(3 - block_size_fld));
-}
-
 /*
  * free_addr_range: Free memory described by the address range entry, which may
  *		    be partially consumed by RMM.
include/linux/arm-rmi-cmds.h +8 -0
index a84e50ac851c..1a885f1017df 100644
@@ -13,8 +13,16 @@
 #include <linux/string.h>
 #include <linux/types.h>
 
+#include <asm/pgtable-hwdef.h>
+
 #define RMI_MAX_ADDR_LIST	256
 
+/* Convert the block size used by RmiDonateReq and RmiAddrRangeDesc. */
+static inline unsigned long rmi_addr_block_size_to_bytes(unsigned long block_size)
+{
+	return BIT(ARM64_HW_PGTABLE_LEVEL_SHIFT(3 - block_size));
+}
+
 struct rmi_sro_state {
 	struct arm_smccc_1_2_regs regs;
 	int addr_count;
Signature · 1 line
2.43.0
#21 lore raw

Re: [PATCH v4 07/11] KVM: arm64: CCA: Add Realm RTT mapping and invalidation helpers

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] KVM: arm64: cca: direct-reclaim allocation in realm_unmap_cache_topup() - [Medium] KVM: arm64…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] KVM: arm64: cca: direct-reclaim allocation in realm_unmap_cache_topup()
- [Medium] KVM: arm64: cca: stale err_level used after realm_unmap_cache_topup() failure
- [Low] KVM: arm64: cca: possible RTT creation for unmapped entry in realm_unmap_*()
--

commit 4c7e030072ac67c12f0f2603fad3d39821c47426
Author: Steven Price <[email protected]>

KVM: arm64: CCA: Add Realm RTT mapping and invalidation helpers

This commit adds RMI Realm Translation Table creation, folding, and stage-2 unmapping helpers for CCA Realms, including filtered range unmapping for shared and private memory.

Quoted 4 lines
arch/arm64/kvm/rmi.c +0 -0
index 435174ac3d87f..b34f5320b50b6 100644

[ ... ]

Quoted 9 lines
arch/arm64/kvm/rmi.c +5 -0
@@ -172,6 +391,208 @@ void kvm_realm_unmap_stage2_all(struct kvm *kvm)
 	realm->stage2_unmapped = true;
 }
 
+static bool realm_unmap_cache_topup(struct kvm *kvm,
+				    struct kvm_mmu_memory_cache *mc, int needed)
+{
+	int ret;
+

arch/arm64/kvm/rmi.c void kvm_realm_unmap_stage2_all(struct kvm *kvm) · line 408

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+	if (!mc || kvm_mmu_memory_cache_nr_free_objects(mc) >= needed)
+		return false;
+
+	lockdep_assert_held_write(&kvm->mmu_lock);
+	write_unlock(&kvm->mmu_lock);
+	ret = __kvm_mmu_topup_memory_cache(mc, KVM_PGTABLE_LAST_LEVEL, needed);
+	write_lock(&kvm->mmu_lock);
+
+	return !ret;
+}

[Severity: Medium]
When __kvm_mmu_topup_memory_cache() fails, does returning false cause realm_unmap_shared_range() and realm_unmap_private_range() to pass a stale err_level to realm_create_rtt_levels()?

Because kvm->mmu_lock was dropped and re-acquired, another thread can fold the RTT at err_level before the lock is retaken. The callers only retry from addr when realm_unmap_cache_topup() returns true; on failure they fall through to realm_create_rtt_levels(realm, addr, err_level, level, mc). alloc_rtt() can still succeed from a partially topped-up cache or via alloc_delegated_granule()'s GFP_ATOMIC fallback (which sets __GFP_HIGH and force-charges memcg), causing realm_rtt_create() at err_level + 1 to fail with RMI_ERROR_RTT at an ancestor level < err_level. That triggers the WARN() in realm_create_rtt_levels() and returns -ENXIO, hitting WARN_ON(ret != -ENOMEM) in realm_unmap_shared_range() or KVM_BUG_ON(1, kvm) in realm_unmap_private_range().

Quoted 39 lines
arch/arm64/kvm/rmi.c +39 -0
+static void realm_unmap_shared_range(struct kvm *kvm,
+				     unsigned long start,
+				     unsigned long end,
+				     bool may_block,
+				     struct kvm_mmu_memory_cache *mc)
+{
+	struct realm *realm = &kvm->arch.realm;
+	unsigned long rd = realm->rd_phys;
+	unsigned long next_addr, addr;
+	unsigned long shared_bit = BIT(realm->ia_bits - 1);
+
+	if (start >= end)
+		return;
+
+	/*
+	 * Callers may pass either an IPA range or its shared alias. Add the
+	 * shared bit only for the former. Use addition so an exclusive end at
+	 * shared_bit advances to the end of the IPA space.
+	 */
+	if (start < shared_bit) {
+		start += shared_bit;
+		end += shared_bit;
+	}
+
+	for (addr = start; addr < end; addr = next_addr) {
+		long ret;
+
+		ret = rmi_rtt_unprot_unmap(rd, addr, end, RMI_ADDR_TYPE_NONE,
+					   0, &next_addr, NULL, NULL);
+		if (WARN_ON(ret < 0))
+			return;
+
+		switch (RMI_RESULT_STATUS(ret)) {
+		case RMI_SUCCESS:
+			break;
+		case RMI_ERROR_RTT: {
+			int err_level = RMI_RESULT_DATA_LEVEL(ret);
+			int level = find_map_level(realm, addr, end);
+

arch/arm64/kvm/rmi.c void kvm_realm_unmap_stage2_all(struct kvm *kvm) · line 458

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+			if (WARN_ON(err_level < realm->start_level ||
+				    err_level > KVM_PGTABLE_LAST_LEVEL))
+				return;
+
+			if (err_level >= level) {
+				/* Nothing present, so skip */
+				next_addr = ALIGN(addr + 1,
+						  kvm_granule_size(err_level));
+				break;
+			}

[Severity: Low]
This question rests on an RMM architectural detail that could not be confirmed from the kernel source: can SMC_RMI_RTT_UNPROT_UNMAP or SMC_RMI_RTT_DATA_UNMAP return RMI_ERROR_RTT with err_level < level when the RTT walk stops at an unassigned ancestor entry (where neither a child RTT nor a block mapping is present at err_level), rather than advancing next_addr and returning RMI_SUCCESS?

If so, when unmapping a sub-block range (such as a single page, where find_map_level() returns KVM_PGTABLE_LAST_LEVEL) across an unmapped ancestor entry, both realm_unmap_shared_range() and realm_unmap_private_range() only skip when err_level >= level. For err_level < level, they treat the entry as a block mapping to split, allocating and delegating intermediate RTTs via realm_create_rtt_levels() only to fold them back at the end of the function, and if that allocation fails in realm_unmap_private_range() (for example under GFP_ATOMIC when may_block is false), it hits KVM_BUG_ON(1, kvm) even though nothing was mapped.

[ ... ]

arch/arm64/kvm/rmi.c void kvm_realm_unmap_stage2_all(struct kvm *kvm) · line 575

Quoted 9 lines
arch/arm64/kvm/rmi.c +9 -0
+void kvm_realm_unmap_range_filter(struct kvm *kvm, unsigned long start,
+				  unsigned long size, bool may_block,
+				  enum kvm_gfn_range_filter attr_filter)
+{
+	/*
+	 * MMU notifier callbacks cannot take slots_lock, which protects the
+	 * eager split cache. Use a cache owned by this invalidation instead.
+	 */
+	struct kvm_mmu_memory_cache cache = { .gfp_zero = __GFP_ZERO };

[Severity: Medium]
Can topping up this cache from an MMU notifier callback enter direct reclaim and trigger a lockdep splat on __mmu_notifier_invalidate_range_start_map?

When mmu_notifier_invalidate_range_start() invokes kvm_mmu_notifier_invalidate_range_start() -> ... -> kvm_realm_unmap_range_filter() with may_block set, it holds __mmu_notifier_invalidate_range_start_map. Because cache.gfp_custom is left at 0, realm_unmap_cache_topup() -> __kvm_mmu_topup_memory_cache() allocates with GFP_KERNEL_ACCOUNT (__GFP_DIRECT_RECLAIM | __GFP_FS), which enters fs_reclaim_acquire() and acquires __mmu_notifier_invalidate_range_start_map recursively (and risks reclaim recursion deadlock under memory pressure). Setting cache.gfp_custom to GFP_NOWAIT | __GFP_ACCOUNT avoids direct reclaim in the notifier path.

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

Re: [PATCH v4 07/11] KVM: arm64: CCA: Add Realm RTT mapping and invalidation helpers

Quoted 121 lines · On 23/11/2026 11:12, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] KVM: arm64: cca: direct-reclaim allocation in realm_unmap_cache_topup()
- [Medium] KVM: arm64: cca: stale err_level used after realm_unmap_cache_topup() failure
- [Low] KVM: arm64: cca: possible RTT creation for unmapped entry in realm_unmap_*()
--

commit 4c7e030072ac67c12f0f2603fad3d39821c47426
Author: Steven Price <[email protected]>

KVM: arm64: CCA: Add Realm RTT mapping and invalidation helpers

This commit adds RMI Realm Translation Table creation, folding, and stage-2 unmapping helpers for CCA Realms, including filtered range unmapping for shared and private memory.

Quoted 4 lines
arch/arm64/kvm/rmi.c +0 -0
index 435174ac3d87f..b34f5320b50b6 100644

[ ... ]

Quoted 9 lines
arch/arm64/kvm/rmi.c +5 -0
@@ -172,6 +391,208 @@ void kvm_realm_unmap_stage2_all(struct kvm *kvm)
  	realm->stage2_unmapped = true;
  }
 
+static bool realm_unmap_cache_topup(struct kvm *kvm,
+				    struct kvm_mmu_memory_cache *mc, int needed)
+{
+	int ret;
+

arch/arm64/kvm/rmi.c void kvm_realm_unmap_stage2_all(struct kvm *kvm) · line 408

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+	if (!mc || kvm_mmu_memory_cache_nr_free_objects(mc) >= needed)
+		return false;
+
+	lockdep_assert_held_write(&kvm->mmu_lock);
+	write_unlock(&kvm->mmu_lock);
+	ret = __kvm_mmu_topup_memory_cache(mc, KVM_PGTABLE_LAST_LEVEL, needed);
+	write_lock(&kvm->mmu_lock);
+
+	return !ret;
+}

[Severity: Medium]
When __kvm_mmu_topup_memory_cache() fails, does returning false cause realm_unmap_shared_range() and realm_unmap_private_range() to pass a stale err_level to realm_create_rtt_levels()?

Because kvm->mmu_lock was dropped and re-acquired, another thread can fold the RTT at err_level before the lock is retaken. The callers only retry from addr when realm_unmap_cache_topup() returns true; on failure they fall through to realm_create_rtt_levels(realm, addr, err_level, level, mc). alloc_rtt() can still succeed from a partially topped-up cache or via alloc_delegated_granule()'s GFP_ATOMIC fallback (which sets __GFP_HIGH and force-charges memcg), causing realm_rtt_create() at err_level + 1 to fail with RMI_ERROR_RTT at an ancestor level < err_level. That triggers the WARN() in realm_create_rtt_levels() and returns -ENXIO, hitting WARN_ON(ret != -ENOMEM) in realm_unmap_shared_range() or KVM_BUG_ON(1, kvm) in realm_unmap_private_range().

Quoted 39 lines
arch/arm64/kvm/rmi.c +39 -0
+static void realm_unmap_shared_range(struct kvm *kvm,
+				     unsigned long start,
+				     unsigned long end,
+				     bool may_block,
+				     struct kvm_mmu_memory_cache *mc)
+{
+	struct realm *realm = &kvm->arch.realm;
+	unsigned long rd = realm->rd_phys;
+	unsigned long next_addr, addr;
+	unsigned long shared_bit = BIT(realm->ia_bits - 1);
+
+	if (start >= end)
+		return;
+
+	/*
+	 * Callers may pass either an IPA range or its shared alias. Add the
+	 * shared bit only for the former. Use addition so an exclusive end at
+	 * shared_bit advances to the end of the IPA space.
+	 */
+	if (start < shared_bit) {
+		start += shared_bit;
+		end += shared_bit;
+	}
+
+	for (addr = start; addr < end; addr = next_addr) {
+		long ret;
+
+		ret = rmi_rtt_unprot_unmap(rd, addr, end, RMI_ADDR_TYPE_NONE,
+					   0, &next_addr, NULL, NULL);
+		if (WARN_ON(ret < 0))
+			return;
+
+		switch (RMI_RESULT_STATUS(ret)) {
+		case RMI_SUCCESS:
+			break;
+		case RMI_ERROR_RTT: {
+			int err_level = RMI_RESULT_DATA_LEVEL(ret);
+			int level = find_map_level(realm, addr, end);
+

arch/arm64/kvm/rmi.c void kvm_realm_unmap_stage2_all(struct kvm *kvm) · line 458

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+			if (WARN_ON(err_level < realm->start_level ||
+				    err_level > KVM_PGTABLE_LAST_LEVEL))
+				return;
+
+			if (err_level >= level) {
+				/* Nothing present, so skip */
+				next_addr = ALIGN(addr + 1,
+						  kvm_granule_size(err_level));
+				break;
+			}

[Severity: Low]
This question rests on an RMM architectural detail that could not be confirmed from the kernel source: can SMC_RMI_RTT_UNPROT_UNMAP or SMC_RMI_RTT_DATA_UNMAP return RMI_ERROR_RTT with err_level < level when the RTT walk stops at an unassigned ancestor entry (where neither a child RTT nor a block mapping is present at err_level), rather than advancing next_addr and returning RMI_SUCCESS?

Quoted 9 lines

If so, when unmapping a sub-block range (such as a single page, where find_map_level() returns KVM_PGTABLE_LAST_LEVEL) across an unmapped ancestor entry, both realm_unmap_shared_range() and realm_unmap_private_range() only skip when err_level >= level. For err_level < level, they treat the entry as a block mapping to split, allocating and delegating intermediate RTTs via realm_create_rtt_levels() only to fold them back at the end of the function, and if that allocation fails in realm_unmap_private_range() (for example under GFP_ATOMIC when may_block is false), it hits KVM_BUG_ON(1, kvm) even though nothing was mapped.

Indeed, this was observed in my testing and I have raised this with the RMM team to get this fixed. RMM must return RMI_SUCCESS if the entry at err_level is "UNASSIGNED", while also advancing the out_top to
the next possible valid entry.

Suzuki

Quoted 28 lines

[ ... ]

arch/arm64/kvm/rmi.c void kvm_realm_unmap_stage2_all(struct kvm *kvm) · line 575

Quoted 9 lines
arch/arm64/kvm/rmi.c +9 -0
+void kvm_realm_unmap_range_filter(struct kvm *kvm, unsigned long start,
+				  unsigned long size, bool may_block,
+				  enum kvm_gfn_range_filter attr_filter)
+{
+	/*
+	 * MMU notifier callbacks cannot take slots_lock, which protects the
+	 * eager split cache. Use a cache owned by this invalidation instead.
+	 */
+	struct kvm_mmu_memory_cache cache = { .gfp_zero = __GFP_ZERO };

[Severity: Medium]
Can topping up this cache from an MMU notifier callback enter direct reclaim and trigger a lockdep splat on __mmu_notifier_invalidate_range_start_map?

When mmu_notifier_invalidate_range_start() invokes kvm_mmu_notifier_invalidate_range_start() -> ... -> kvm_realm_unmap_range_filter() with may_block set, it holds __mmu_notifier_invalidate_range_start_map. Because cache.gfp_custom is left at 0, realm_unmap_cache_topup() -> __kvm_mmu_topup_memory_cache() allocates with GFP_KERNEL_ACCOUNT (__GFP_DIRECT_RECLAIM | __GFP_FS), which enters fs_reclaim_acquire() and acquires __mmu_notifier_invalidate_range_start_map recursively (and risks reclaim recursion deadlock under memory pressure). Setting cache.gfp_custom to GFP_NOWAIT | __GFP_ACCOUNT avoids direct reclaim in the notifier path.

#23 lore raw

Re: [PATCH v4 07/11] KVM: arm64: CCA: Add Realm RTT mapping and invalidation helpers

In reply to [email protected]
Quoted 147 lines · On 23/11/2026 11:12, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] KVM: arm64: cca: direct-reclaim allocation in realm_unmap_cache_topup()
- [Medium] KVM: arm64: cca: stale err_level used after realm_unmap_cache_topup() failure
- [Low] KVM: arm64: cca: possible RTT creation for unmapped entry in realm_unmap_*()
--

commit 4c7e030072ac67c12f0f2603fad3d39821c47426
Author: Steven Price <[email protected]>

KVM: arm64: CCA: Add Realm RTT mapping and invalidation helpers

This commit adds RMI Realm Translation Table creation, folding, and stage-2 unmapping helpers for CCA Realms, including filtered range unmapping for shared and private memory.

Quoted 4 lines
arch/arm64/kvm/rmi.c +0 -0
index 435174ac3d87f..b34f5320b50b6 100644

[ ... ]

Quoted 9 lines
arch/arm64/kvm/rmi.c +5 -0
@@ -172,6 +391,208 @@ void kvm_realm_unmap_stage2_all(struct kvm *kvm)
 	realm->stage2_unmapped = true;
 }
 
+static bool realm_unmap_cache_topup(struct kvm *kvm,
+				    struct kvm_mmu_memory_cache *mc, int needed)
+{
+	int ret;
+

arch/arm64/kvm/rmi.c void kvm_realm_unmap_stage2_all(struct kvm *kvm) · line 408

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+	if (!mc || kvm_mmu_memory_cache_nr_free_objects(mc) >= needed)
+		return false;
+
+	lockdep_assert_held_write(&kvm->mmu_lock);
+	write_unlock(&kvm->mmu_lock);
+	ret = __kvm_mmu_topup_memory_cache(mc, KVM_PGTABLE_LAST_LEVEL, needed);
+	write_lock(&kvm->mmu_lock);
+
+	return !ret;
+}

[Severity: Medium]
When __kvm_mmu_topup_memory_cache() fails, does returning false cause realm_unmap_shared_range() and realm_unmap_private_range() to pass a stale err_level to realm_create_rtt_levels()?

Because kvm->mmu_lock was dropped and re-acquired, another thread can fold the RTT at err_level before the lock is retaken. The callers only retry from addr when realm_unmap_cache_topup() returns true; on failure they fall through to realm_create_rtt_levels(realm, addr, err_level, level, mc). alloc_rtt() can still succeed from a partially topped-up cache or via alloc_delegated_granule()'s GFP_ATOMIC fallback (which sets __GFP_HIGH and force-charges memcg), causing realm_rtt_create() at err_level + 1 to fail with RMI_ERROR_RTT at an ancestor level < err_level. That triggers the WARN() in realm_create_rtt_levels() and returns -ENXIO, hitting WARN_ON(ret != -ENOMEM) in realm_unmap_shared_range() or KVM_BUG_ON(1, kvm) in realm_unmap_private_range().

Quoted 39 lines
arch/arm64/kvm/rmi.c +39 -0
+static void realm_unmap_shared_range(struct kvm *kvm,
+				     unsigned long start,
+				     unsigned long end,
+				     bool may_block,
+				     struct kvm_mmu_memory_cache *mc)
+{
+	struct realm *realm = &kvm->arch.realm;
+	unsigned long rd = realm->rd_phys;
+	unsigned long next_addr, addr;
+	unsigned long shared_bit = BIT(realm->ia_bits - 1);
+
+	if (start >= end)
+		return;
+
+	/*
+	 * Callers may pass either an IPA range or its shared alias. Add the
+	 * shared bit only for the former. Use addition so an exclusive end at
+	 * shared_bit advances to the end of the IPA space.
+	 */
+	if (start < shared_bit) {
+		start += shared_bit;
+		end += shared_bit;
+	}
+
+	for (addr = start; addr < end; addr = next_addr) {
+		long ret;
+
+		ret = rmi_rtt_unprot_unmap(rd, addr, end, RMI_ADDR_TYPE_NONE,
+					   0, &next_addr, NULL, NULL);
+		if (WARN_ON(ret < 0))
+			return;
+
+		switch (RMI_RESULT_STATUS(ret)) {
+		case RMI_SUCCESS:
+			break;
+		case RMI_ERROR_RTT: {
+			int err_level = RMI_RESULT_DATA_LEVEL(ret);
+			int level = find_map_level(realm, addr, end);
+

arch/arm64/kvm/rmi.c void kvm_realm_unmap_stage2_all(struct kvm *kvm) · line 458

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+			if (WARN_ON(err_level < realm->start_level ||
+				    err_level > KVM_PGTABLE_LAST_LEVEL))
+				return;
+
+			if (err_level >= level) {
+				/* Nothing present, so skip */
+				next_addr = ALIGN(addr + 1,
+						  kvm_granule_size(err_level));
+				break;
+			}

[Severity: Low]
This question rests on an RMM architectural detail that could not be confirmed from the kernel source: can SMC_RMI_RTT_UNPROT_UNMAP or SMC_RMI_RTT_DATA_UNMAP return RMI_ERROR_RTT with err_level < level when the RTT walk stops at an unassigned ancestor entry (where neither a child RTT nor a block mapping is present at err_level), rather than advancing next_addr and returning RMI_SUCCESS?

If so, when unmapping a sub-block range (such as a single page, where find_map_level() returns KVM_PGTABLE_LAST_LEVEL) across an unmapped ancestor entry, both realm_unmap_shared_range() and realm_unmap_private_range() only skip when err_level >= level. For err_level < level, they treat the entry as a block mapping to split, allocating and delegating intermediate RTTs via realm_create_rtt_levels() only to fold them back at the end of the function, and if that allocation fails in realm_unmap_private_range() (for example under GFP_ATOMIC when may_block is false), it hits KVM_BUG_ON(1, kvm) even though nothing was mapped.

[ ... ]

arch/arm64/kvm/rmi.c void kvm_realm_unmap_stage2_all(struct kvm *kvm) · line 575

Quoted 9 lines
arch/arm64/kvm/rmi.c +9 -0
+void kvm_realm_unmap_range_filter(struct kvm *kvm, unsigned long start,
+				  unsigned long size, bool may_block,
+				  enum kvm_gfn_range_filter attr_filter)
+{
+	/*
+	 * MMU notifier callbacks cannot take slots_lock, which protects the
+	 * eager split cache. Use a cache owned by this invalidation instead.
+	 */
+	struct kvm_mmu_memory_cache cache = { .gfp_zero = __GFP_ZERO };

[Severity: Medium]
Can topping up this cache from an MMU notifier callback enter direct reclaim and trigger a lockdep splat on __mmu_notifier_invalidate_range_start_map?

Quoted 11 lines

When mmu_notifier_invalidate_range_start() invokes kvm_mmu_notifier_invalidate_range_start() -> ... -> kvm_realm_unmap_range_filter() with may_block set, it holds __mmu_notifier_invalidate_range_start_map. Because cache.gfp_custom is left at 0, realm_unmap_cache_topup() -> __kvm_mmu_topup_memory_cache() allocates with GFP_KERNEL_ACCOUNT (__GFP_DIRECT_RECLAIM | __GFP_FS), which enters fs_reclaim_acquire() and acquires __mmu_notifier_invalidate_range_start_map recursively (and risks reclaim recursion deadlock under memory pressure). Setting cache.gfp_custom to GFP_NOWAIT | __GFP_ACCOUNT avoids direct reclaim in the notifier path.

Using GFP_NOWAIT doesn't sound a great idea. But this is actually only an issue for the shared mappings. Protected mappings shouldn't be triggering the mmu_notifiers because the memory is from the guest memfd. For shared memory we can always fall back on unmapping too much, so there's no real need to deal with the memcache.

I'll try to rework this for the next revision.

Thanks,
Steve

#24 lore raw

Re: [PATCH v4 07/11] KVM: arm64: CCA: Add Realm RTT mapping and invalidation helpers

In reply to Steven Price
Quoted 6 lines · Steven Price

Add the RMI RTT creation and unmap helpers needed by CCA Realm stage-2 memory operations. REC exit handling and guest requested RIPAS changes follow in the vCPU series.

...

--8>--

arch/arm64/kvm/rmi.c static int realm_destroy_rtt_range(struct realm *realm, · line 372

Quoted 8 lines
  static int realm_destroy_rtts(struct kvm *kvm)
  {
  	struct realm *realm = &kvm->arch.realm;
  	unsigned int ia_bits = realm->ia_bits;
  
  	lockdep_assert_held(&kvm->arch.config_lock);
arch/arm64/kvm/rmi.c +2 -0
+	if (WARN_ON_ONCE(!realm->stage2_unmapped))
+		return -EINVAL;

minor nit: Does this hunk belong to the previous patch ?

Suzuki

#25 lore raw

Re: [PATCH v4 07/11] KVM: arm64: CCA: Add Realm RTT mapping and invalidation helpers

Quoted 21 lines · Suzuki K Poulose
Quoted 6 lines · Steven Price

Add the RMI RTT creation and unmap helpers needed by CCA Realm stage-2 memory operations. REC exit handling and guest requested RIPAS changes follow in the vCPU series.

...

--8>--

Quoted 7 lines

  static int realm_destroy_rtts(struct kvm *kvm) {
      struct realm *realm = &kvm->arch.realm; unsigned int ia_bits = realm->ia_bits; lockdep_assert_held(&kvm->arch.config_lock); +    if (WARN_ON_ONCE(!realm->stage2_unmapped)) +        return -EINVAL;

Quoted 1 line

minor nit: Does this hunk belong to the previous patch ?

Yes, sorry about that!

Thanks,
Steve

#26 lore raw

Re: [PATCH v4 07/11] KVM: arm64: CCA: Add Realm RTT mapping and invalidation helpers

In reply to Steven Price
Quoted 26 lines · Steven Price

Add the RMI RTT creation and unmap helpers needed by CCA Realm stage-2 memory operations. REC exit handling and guest requested RIPAS changes follow in the vCPU series.

---
Changes since v3:
- Use the VTCR-derived Realm start level for RTT operations.

Changes since v2:
- Use a local MMU cache during notifier invalidation, handle failed RTT splits, and validate RMI levels and cache state.

Changes since v1:
- Rework RTT creation and folding around missing or existing RTTs. Use a shared RMI block-size helper and handle alignment, partial progress and errors in range operations.

---
  arch/arm64/include/asm/kvm_rmi.h |   8 +
  arch/arm64/kvm/rmi.c             | 421 +++++++++++++++++++++++++++++++
  drivers/firmware/arm_rmm/rmi.c   |  10 -
  include/linux/arm-rmi-cmds.h     |   8 +
  4 files changed, 437 insertions(+), 10 deletions(-)
arch/arm64/include/asm/kvm_rmi.h +0 -0

...

Quoted 29 lines
arch/arm64/include/asm/kvm_rmi.h +29 -0
+
+static void realm_unmap_shared_range(struct kvm *kvm,
+				     unsigned long start,
+				     unsigned long end,
+				     bool may_block,
+				     struct kvm_mmu_memory_cache *mc)
+{
+	struct realm *realm = &kvm->arch.realm;
+	unsigned long rd = realm->rd_phys;
+	unsigned long next_addr, addr;
+	unsigned long shared_bit = BIT(realm->ia_bits - 1);
+
+	if (start >= end)
+		return;
+
+	/*
+	 * Callers may pass either an IPA range or its shared alias. Add the
+	 * shared bit only for the former. Use addition so an exclusive end at
+	 * shared_bit advances to the end of the IPA space.
+	 */
+	if (start < shared_bit) {
+		start += shared_bit;
+		end += shared_bit;
+	}
+
+	for (addr = start; addr < end; addr = next_addr) {
+		long ret;
+
+		ret = rmi_rtt_unprot_unmap(rd, addr, end, RMI_ADDR_TYPE_NONE,

...

arch/arm64/include/asm/kvm_rmi.h

Quoted 8 lines
arch/arm64/include/asm/kvm_rmi.h +8 -0
+		}
+
+		if (may_block)
+			cond_resched_rwlock_write(&kvm->mmu_lock);
+	}
+
+	realm_fold_rtt_level(realm, realm->start_level + 1,
+			     start, end);

See below.

Quoted 19 lines
arch/arm64/include/asm/kvm_rmi.h +19 -0
+}
+
+static void realm_unmap_private_range(struct kvm *kvm,
+				      unsigned long start,
+				      unsigned long end,
+				      bool may_block,
+				      struct kvm_mmu_memory_cache *mc)
+{
+	struct realm *realm = &kvm->arch.realm;
+	unsigned long rd = realm->rd_phys;
+	unsigned long next_addr, addr;
+	long ret;
+
+	for (addr = start; addr < end; addr = next_addr) {
+		unsigned long out_range;
+		unsigned long flags = RMI_ADDR_TYPE_SINGLE;
+		/* TODO: Optimise using RMI_ADDR_TYPE_LIST */
+
+		ret = rmi_rtt_data_unmap(rd, addr, end, flags, 0,

...

arch/arm64/include/asm/kvm_rmi.h

Quoted 8 lines
arch/arm64/include/asm/kvm_rmi.h +8 -0
+		}
+
+		if (may_block)
+			cond_resched_rwlock_write(&kvm->mmu_lock);
+	}
+
+	realm_fold_rtt_level(realm, realm->start_level + 1,
+			     start, end);

If "may_block", we don't take that into account while folding the RTTs ? On a bigger range, we might spend too much time, starving the other threads.

Also, there is no point in folding the RTTs if the Realm is dying. So, I would rather skip this if the Realm is not ACTIVE.

Suzuki

#27 lore raw

Re: [PATCH v4 07/11] KVM: arm64: CCA: Add Realm RTT mapping and invalidation helpers

Quoted 110 lines · Suzuki K Poulose
Quoted 26 lines · Steven Price

Add the RMI RTT creation and unmap helpers needed by CCA Realm stage-2 memory operations. REC exit handling and guest requested RIPAS changes follow in the vCPU series.

---
Changes since v3:
- Use the VTCR-derived Realm start level for RTT operations.

Changes since v2:
- Use a local MMU cache during notifier invalidation, handle failed RTT splits, and validate RMI levels and cache state.

Changes since v1:
- Rework RTT creation and folding around missing or existing RTTs. Use a shared RMI block-size helper and handle alignment, partial progress and errors in range operations.
---
  arch/arm64/include/asm/kvm_rmi.h |   8 + arch/arm64/kvm/rmi.c             | 421 +++++++++++++++++++++++++++++++ drivers/firmware/arm_rmm/rmi.c   |  10 - include/linux/arm-rmi-cmds.h     |   8 +

  4 files changed, 437 insertions(+), 10 deletions(-)
arch/arm64/include/ asm/kvm_rmi.h renamed from arch/arm64/include/asm/kvm_rmi.h +0 -0

...

Quoted 30 lines
arch/arm64/include/ asm/kvm_rmi.h renamed from arch/arm64/include/asm/kvm_rmi.h +18 -0
+
+static void realm_unmap_shared_range(struct kvm *kvm,
+                     unsigned long start,
+                     unsigned long end,
+                     bool may_block,
+                     struct kvm_mmu_memory_cache *mc)
+{
+    struct realm *realm = &kvm->arch.realm;
+    unsigned long rd = realm->rd_phys;
+    unsigned long next_addr, addr;
+    unsigned long shared_bit = BIT(realm->ia_bits - 1);
+
+    if (start >= end)
+        return;
+
+    /*
+     * Callers may pass either an IPA range or its shared alias. Add the
+     * shared bit only for the former. Use addition so an exclusive 

end at
+     * shared_bit advances to the end of the IPA space. +     */
+    if (start < shared_bit) {
+        start += shared_bit;
+        end += shared_bit;
+    }

arch/arm64/include/ asm/kvm_rmi.h renamed from arch/arm64/include/asm/kvm_rmi.h +5 -0
+
+    for (addr = start; addr < end; addr = next_addr) {
+        long ret;
+
+        ret = rmi_rtt_unprot_unmap(rd, addr, end, RMI_ADDR_TYPE_NONE,

...

arch/arm64/include/ asm/kvm_rmi.h

Quoted 8 lines

+        }

arch/arm64/include/ asm/kvm_rmi.h renamed from arch/arm64/include/asm/kvm_rmi.h +7 -0
+
+        if (may_block)
+            cond_resched_rwlock_write(&kvm->mmu_lock);
+    }
+
+    realm_fold_rtt_level(realm, realm->start_level + 1,
+                 start, end);

See below.

Quoted 19 lines
arch/arm64/include/ asm/kvm_rmi.h renamed from arch/arm64/include/asm/kvm_rmi.h +19 -0
+}
+
+static void realm_unmap_private_range(struct kvm *kvm,
+                      unsigned long start,
+                      unsigned long end,
+                      bool may_block,
+                      struct kvm_mmu_memory_cache *mc)
+{
+    struct realm *realm = &kvm->arch.realm;
+    unsigned long rd = realm->rd_phys;
+    unsigned long next_addr, addr;
+    long ret;
+
+    for (addr = start; addr < end; addr = next_addr) {
+        unsigned long out_range;
+        unsigned long flags = RMI_ADDR_TYPE_SINGLE;
+        /* TODO: Optimise using RMI_ADDR_TYPE_LIST */
+
+        ret = rmi_rtt_data_unmap(rd, addr, end, flags, 0,

...

arch/arm64/include/ asm/kvm_rmi.h

Quoted 8 lines

+        }

arch/arm64/include/ asm/kvm_rmi.h renamed from arch/arm64/include/asm/kvm_rmi.h +7 -0
+
+        if (may_block)
+            cond_resched_rwlock_write(&kvm->mmu_lock);
+    }
+
+    realm_fold_rtt_level(realm, realm->start_level + 1,
+                 start, end);

If "may_block", we don't take that into account while folding the RTTs ? On a bigger range, we might spend too much time, starving the other threads.

Quoted 2 lines

Also, there is no point in folding the RTTs if the Realm is dying. So, I would rather skip this if the Realm is not ACTIVE.

Having a think about it, I don't think the folding of RTTs in the unmap case is a good idea. We could leave them as they are, because:

1) As mentioned above, we are holding the write_lock() and doing this within the lock is bad for contention
2) We do not check if there was any mapping at all that was actually invalidated. i.e., the tables were already folded and for a big range we go over it unnecessarily.
3) For fixing up permission faults on shared range, we end up unmapping the range and then trying to map it. Folding here means, we could end up in the dance of reclaiming the RTT and then creating it back for each L3. (This is a rare case though).

Overall, I don't see the benefit of folding outweighing the impact of it. So, could we please drop this ?

Cheers
Suzuki

Quoted 2 lines

Suzuki

#28 lore raw

Re: [PATCH v4 07/11] KVM: arm64: CCA: Add Realm RTT mapping and invalidation helpers

Quoted 131 lines · Suzuki K Poulose
Quoted 112 lines · Suzuki K Poulose
Quoted 27 lines · Steven Price

Add the RMI RTT creation and unmap helpers needed by CCA Realm stage-2 memory operations. REC exit handling and guest requested RIPAS changes follow in the vCPU series.

---
Changes since v3:
- Use the VTCR-derived Realm start level for RTT operations.

Changes since v2:
- Use a local MMU cache during notifier invalidation, handle failed RTT splits, and validate RMI levels and cache state.

Changes since v1:
- Rework RTT creation and folding around missing or existing RTTs. Use a shared RMI block-size helper and handle alignment, partial progress and errors in range operations.
---
  arch/arm64/include/asm/kvm_rmi.h |   8 + arch/arm64/kvm/rmi.c             | 421 +++++++++++++++++++++++++++++++ drivers/firmware/arm_rmm/rmi.c   |  10 - include/linux/arm-rmi-cmds.h     |   8 +

  4 files changed, 437 insertions(+), 10 deletions(-)
arch/arm64/include/ renamed from arch/arm64/include/asm/kvm_rmi.h +0 -0

asm/kvm_rmi.h

...

Quoted 31 lines
arch/arm64/include/ renamed from arch/arm64/include/asm/kvm_rmi.h +17 -0
+
+static void realm_unmap_shared_range(struct kvm *kvm,
+                     unsigned long start,
+                     unsigned long end,
+                     bool may_block,
+                     struct kvm_mmu_memory_cache *mc)
+{
+    struct realm *realm = &kvm->arch.realm;
+    unsigned long rd = realm->rd_phys;
+    unsigned long next_addr, addr;
+    unsigned long shared_bit = BIT(realm->ia_bits - 1);
+
+    if (start >= end)
+        return;
+
+    /*
+     * Callers may pass either an IPA range or its shared alias. Add

the
+     * shared bit only for the former. Use addition so an exclusive end at
+     * shared_bit advances to the end of the IPA space. +     */
+    if (start < shared_bit) {
+        start += shared_bit;
+        end += shared_bit;
+    }

arch/arm64/include/ renamed from arch/arm64/include/asm/kvm_rmi.h +5 -0
+
+    for (addr = start; addr < end; addr = next_addr) {
+        long ret;
+
+        ret = rmi_rtt_unprot_unmap(rd, addr, end, RMI_ADDR_TYPE_NONE,

...

arch/arm64/include/

Quoted 8 lines

+        }

arch/arm64/include/ renamed from arch/arm64/include/asm/kvm_rmi.h +7 -0
+
+        if (may_block)
+            cond_resched_rwlock_write(&kvm->mmu_lock);
+    }
+
+    realm_fold_rtt_level(realm, realm->start_level + 1,
+                 start, end);

See below.

Quoted 19 lines
arch/arm64/include/ renamed from arch/arm64/include/asm/kvm_rmi.h +19 -0
+}
+
+static void realm_unmap_private_range(struct kvm *kvm,
+                      unsigned long start,
+                      unsigned long end,
+                      bool may_block,
+                      struct kvm_mmu_memory_cache *mc)
+{
+    struct realm *realm = &kvm->arch.realm;
+    unsigned long rd = realm->rd_phys;
+    unsigned long next_addr, addr;
+    long ret;
+
+    for (addr = start; addr < end; addr = next_addr) {
+        unsigned long out_range;
+        unsigned long flags = RMI_ADDR_TYPE_SINGLE;
+        /* TODO: Optimise using RMI_ADDR_TYPE_LIST */
+
+        ret = rmi_rtt_data_unmap(rd, addr, end, flags, 0,

...

arch/arm64/include/

Quoted 8 lines

+        }

arch/arm64/include/ renamed from arch/arm64/include/asm/kvm_rmi.h +7 -0
+
+        if (may_block)
+            cond_resched_rwlock_write(&kvm->mmu_lock);
+    }
+
+    realm_fold_rtt_level(realm, realm->start_level + 1,
+                 start, end);

If "may_block", we don't take that into account while folding the RTTs ? On a bigger range, we might spend too much time, starving the other threads.

Quoted 2 lines

Also, there is no point in folding the RTTs if the Realm is dying. So, I would rather skip this if the Realm is not ACTIVE.

Having a think about it, I don't think the folding of RTTs in the unmap case is a good idea. We could leave them as they are, because:

1) As mentioned above, we are holding the write_lock() and doing this within the lock is bad for contention
2) We do not check if there was any mapping at all that was actually invalidated. i.e., the tables were already folded and for a big range we go over it unnecessarily.
3) For fixing up permission faults on shared range, we end up unmapping the range and then trying to map it. Folding here means, we could end up in the dance of reclaiming the RTT and then creating it back for each L3. (This is a rare case though).

Quoted 2 lines

Overall, I don't see the benefit of folding outweighing the impact of it. So, could we please drop this ?

Agreed. I don't think we have a good view (yet) on when folding makes sense. I think it ended up in here mostly so that we could exercise those paths in the RMM. But that's a terrible reason to keep it ;)

Eventually I think we'll need to figure out how to cause folding in those (probably fairly rare) situations where it will help. But for now I'll just drop this.

Thanks,
Steve

#29 lore raw

PATCH v4 8/11 KVM: Allow architectures to reject memslot changes before invalidation

In reply to Steven Price

From: Suzuki K Poulose <[email protected]>

The next patch needs to reject changes to a realm guest_memfd memslot before invalidation. KVM currently invalidates the slot and calls kvm_arch_flush_shadow_memslot() before kvm_arch_prepare_memory_region() can reject the request. For a realm, invalidation unmaps stage-2 mappings; restoring the old memslot on failure does not restore those mappings. Thus a rejected deletion or move would still have side effects.

Add kvm_arch_validate_memory_region() and invoke it before invalidating the slot, with slots_lock and slots_arch_lock held. The hook performs validation only, allowing architectures to reject a request without changing the memslot or its mappings. Provide a weak no-op implementation for architectures that do not need early validation.

Move arm64's existing pVM checks into the new hook as part of early validation. pVM invalidation uses no_stage2_unmap_range(), so the realm case motivates this hook. Keep resource preparation after invalidation, since invalidation drops slots_arch_lock and allows concurrent updates to architecture-specific memslot metadata.

---
Changes since v3:
- Clarify that Realm stage-2 invalidation motivates the early validation hook; pVM invalidation does not unmap stage-2.

---
 arch/arm64/kvm/mmu.c     | 22 ++++++++++++++++------
 arch/arm64/kvm/pkvm.c    |  2 +-
 include/linux/kvm_host.h |  4 ++++
 virt/kvm/kvm_main.c      | 33 ++++++++++++++++++++++++++-------
 4 files changed, 47 insertions(+), 14 deletions(-)
arch/arm64/kvm/mmu.c +16 -6
index 4a975715375c..800333a345cd 100644
@@ -2854,13 +2854,12 @@ void kvm_arch_commit_memory_region(struct kvm *kvm,
 	}
 }
 
-int kvm_arch_prepare_memory_region(struct kvm *kvm,
-				   const struct kvm_memory_slot *old,
-				   struct kvm_memory_slot *new,
-				   enum kvm_mr_change change)
+int kvm_arch_validate_memory_region(struct kvm *kvm,
+				    const struct kvm_memory_slot *old,
+				    const struct kvm_memory_slot *new,
+				    enum kvm_mr_change change)
 {
-	hva_t hva, reg_end;
-	int ret = 0;
+	lockdep_assert_held(&kvm->slots_lock);
 
 	if (kvm_vm_is_protected(kvm)) {
 		/* Cannot modify memslots once a pVM has run. */
@@ -2875,6 +2874,17 @@ int kvm_arch_prepare_memory_region(struct kvm *kvm,
 		}
 	}
 
+	return 0;
+}
+
+int kvm_arch_prepare_memory_region(struct kvm *kvm,
+				   const struct kvm_memory_slot *old,
+				   struct kvm_memory_slot *new,
+				   enum kvm_mr_change change)
+{
+	hva_t hva, reg_end;
+	int ret = 0;
+
 	if (change != KVM_MR_CREATE && change != KVM_MR_MOVE &&
 			change != KVM_MR_FLAGS_ONLY)
 		return 0;
arch/arm64/kvm/pkvm.c +1 -1
index 8241a05e25d1..72f98f3bd6a6 100644
@@ -262,7 +262,7 @@ int pkvm_create_hyp_vm(struct kvm *kvm)
 	int ret = 0;
 
 	/*
-	 * Synchronise with kvm_arch_prepare_memory_region(), as we
+	 * Synchronise with kvm_arch_validate_memory_region(), as we
 	 * prevent memslot modifications on a pVM that has been run.
 	 */
 	mutex_lock(&kvm->slots_lock);
include/linux/kvm_host.h +4 -0
index f65728a713ec..15848221860f 100644
@@ -1255,6 +1255,10 @@ int kvm_set_internal_memslot(struct kvm *kvm,
 			     const struct kvm_userspace_memory_region2 *mem);
 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot);
 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen);
+int kvm_arch_validate_memory_region(struct kvm *kvm,
+				    const struct kvm_memory_slot *old,
+				    const struct kvm_memory_slot *new,
+				    enum kvm_mr_change change);
 int kvm_arch_prepare_memory_region(struct kvm *kvm,
 				const struct kvm_memory_slot *old,
 				struct kvm_memory_slot *new,
virt/kvm/kvm_main.c +26 -7
index cf4cb586f140..3ef370d71818 100644
@@ -1682,6 +1682,20 @@ static void kvm_swap_active_memslots(struct kvm *kvm, int as_id)
 	slots->generation = gen;
 }
 
+/*
+ * Validate a memslot change before invalidation, which may irreversibly reclaim
+ * private guest memory. Called with slots_lock and slots_arch_lock held.
+ * Implementations must not modify memslot state or allocate resources; leave
+ * those operations to kvm_arch_prepare_memory_region().
+ */
+__weak int kvm_arch_validate_memory_region(struct kvm *kvm,
+					   const struct kvm_memory_slot *old,
+					   const struct kvm_memory_slot *new,
+					   enum kvm_mr_change change)
+{
+	return 0;
+}
+
 static int kvm_prepare_memory_region(struct kvm *kvm,
 				     const struct kvm_memory_slot *old,
 				     struct kvm_memory_slot *new,
@@ -1934,6 +1948,10 @@ static int kvm_set_memslot(struct kvm *kvm,
 	 */
 	mutex_lock(&kvm->slots_arch_lock);
 
+	r = kvm_arch_validate_memory_region(kvm, old, new, change);
+	if (r)
+		goto unlock_err;
+
 	/*
 	 * Invalidate the old slot if it's being deleted or moved.  This is
 	 * done prior to actually deleting/moving the memslot to allow vCPUs to
@@ -1950,22 +1968,22 @@ static int kvm_set_memslot(struct kvm *kvm,
 	if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
 		invalid_slot = kzalloc_obj(*invalid_slot, GFP_KERNEL_ACCOUNT);
 		if (!invalid_slot) {
-			mutex_unlock(&kvm->slots_arch_lock);
-			return -ENOMEM;
+			r = -ENOMEM;
+			goto unlock_err;
 		}
 		kvm_invalidate_memslot(kvm, old, invalid_slot);
 	}
 
 	r = kvm_prepare_memory_region(kvm, old, new, change);
 	if (r)
-		goto err;
+		goto revert_slot;
 
 	if (change == KVM_MR_CREATE && (new->flags & KVM_MEM_GUEST_MEMFD)) {
 		r = kvm_gmem_commit_memory_region(kvm, new);
 		if (r) {
 			kvm_arch_free_memslot(kvm, new);
 			kvm_destroy_dirty_bitmap(new);
-			goto err;
+			goto unlock_err;
 		}
 	}
 
@@ -2000,7 +2018,7 @@ static int kvm_set_memslot(struct kvm *kvm,
 
 	return 0;
 
-err:
+revert_slot:
 	/*
 	 * For DELETE/MOVE, revert the above INVALID change.  No modifications
 	 * required since the original slot was preserved in the inactive slots.
@@ -2009,9 +2027,10 @@ static int kvm_set_memslot(struct kvm *kvm,
 	if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
 		kvm_activate_memslot(kvm, invalid_slot, old);
 		kfree(invalid_slot);
-	} else {
-		mutex_unlock(&kvm->slots_arch_lock);
+		return r;
 	}
+unlock_err:
+	mutex_unlock(&kvm->slots_arch_lock);
 	return r;
 }
 
Signature · 1 line
2.43.0
#30 lore raw

Re: [PATCH v4 08/11] KVM: Allow architectures to reject memslot changes before invalidation

Hi Suzuki,

Quoted 4 lines · Steven Price

From: Suzuki K Poulose <[email protected]>

The next patch needs to reject changes to a realm guest_memfd memslot before invalidation. KVM currently invalidates the slot and calls

[...]

Quoted 3 lines

Move arm64's existing pVM checks into the new hook as part of early validation. pVM invalidation uses no_stage2_unmap_range(), so the realm case motivates this hook. Keep resource preparation after invalidation,

With the Realm memslot restrictions in patch 9 being dropped in the next version, is this hook still needed? pVM invalidation doesn't touch stage-2, so the pVM checks could stay in kvm_arch_prepare_memory_region().

Cheers,
/fuad

#31 lore raw

Re: [PATCH v4 08/11] KVM: Allow architectures to reject memslot changes before invalidation

Quoted 8 lines · Fuad Tabba

Hi Suzuki,

Quoted 4 lines · Steven Price

From: Suzuki K Poulose <[email protected]>

The next patch needs to reject changes to a realm guest_memfd memslot before invalidation. KVM currently invalidates the slot and calls

[...]

Quoted 8 lines
Quoted 3 lines

Move arm64's existing pVM checks into the new hook as part of early validation. pVM invalidation uses no_stage2_unmap_range(), so the realm case motivates this hook. Keep resource preparation after invalidation,

With the Realm memslot restrictions in patch 9 being dropped in the next version, is this hook still needed? pVM invalidation doesn't touch stage-2, so the pVM checks could stay in kvm_arch_prepare_memory_region().

Indeed with the memslot restrictions gone this hook isn't needed.

Thanks,
Steve

#32 lore raw

PATCH v4 9/11 KVM: arm64: CCA: Prevent memslot modifications after Realm creation

In reply to Steven Price

From: Suzuki K Poulose <[email protected]>

Once the Realm is created, prevent changes to guest_memfd backed memslots, which can provide private memory. Validate these changes before KVM invalidates the old memslot, so a rejected deletion leaves its stage-2 mappings intact. Realm stage-2 faults will also validate the private memory backing in a later commit.

Require Realm memslots to lie in the lower half of the IPA space, as the upper, shared half aliases the lower, protected half.

Define kvm_arch_has_private_mem() so generic KVM recognizes Realm VMs as supporting private memory. Defining the macro also makes gmem_in_place_conversion true for every arm64 VM, so guest_memfd memslots are marked gmem-only even for non-Realm VMs. A well-formed KVM_SET_MEMORY_ATTRIBUTES2 request on a non-Realm guest_memfd now reaches the VM check and returns -EINVAL instead of -ENOTTY.

Additionally, similar to pKVM, do not support dirty logging or read-only memslots.

---
Changes since v3:
- Explain the arm64-wide in-place conversion effect and keep the general IPA limit comment.

Changes since v1:
- Preserve private mappings if KVM invalidates a Realm guest_memfd slot before the prepare hook rejects its deletion.

---
 arch/arm64/include/asm/kvm_host.h |  2 ++
 arch/arm64/kvm/mmu.c              | 37 ++++++++++++++++++++++++-------
 2 files changed, 31 insertions(+), 8 deletions(-)
arch/arm64/include/asm/kvm_host.h +2 -0
index 3ddeddfacd06..55673d08e3eb 100644
@@ -1607,6 +1607,8 @@ struct kvm *kvm_arch_alloc_vm(void);
 
 #define kvm_vm_is_realm(kvm)		((kvm)->arch.vm_flavor == VM_REALM)
 
+#define kvm_arch_has_private_mem(kvm) kvm_vm_is_realm(kvm)
+
 #define kvm_has_mte(kvm)					\
 	(system_supports_mte() &&				\
 	 test_bit(KVM_ARCH_FLAG_MTE_ENABLED, &(kvm)->arch.flags))
arch/arm64/kvm/mmu.c +29 -8
index 800333a345cd..9af5fe6d87f0 100644
@@ -2861,17 +2861,32 @@ int kvm_arch_validate_memory_region(struct kvm *kvm,
 {
 	lockdep_assert_held(&kvm->slots_lock);
 
-	if (kvm_vm_is_protected(kvm)) {
+	if (kvm_vm_is_protected(kvm) && new &&
+	    (new->flags & (KVM_MEM_LOG_DIRTY_PAGES | KVM_MEM_READONLY)))
+		return -EPERM;
+
+	switch (kvm->arch.vm_flavor) {
+	case VM_PROTECTED_PKVM:
 		/* Cannot modify memslots once a pVM has run. */
 		if (pkvm_hyp_vm_is_created(kvm) &&
-		    (change == KVM_MR_DELETE || change == KVM_MR_MOVE)) {
+		    (change == KVM_MR_DELETE || change == KVM_MR_MOVE))
 			return -EPERM;
-		}
+		break;
+	case VM_REALM:
+		/*
+		 * Once the Realm is created, we cannot modify any slots that
+		 * could be providing private memory. i.e., guest_memfd backed
+		 * slots.
+		 * TODO: Handle trusted device private memory slots
+		 */
+		if (!kvm_realm_is_created(kvm))
+			break;
 
-		if (new &&
-		    new->flags & (KVM_MEM_LOG_DIRTY_PAGES | KVM_MEM_READONLY)) {
+		if (kvm_slot_has_gmem(old) || kvm_slot_has_gmem(new))
 			return -EPERM;
-		}
+		break;
+	default:
+		break;
 	}
 
 	return 0;
@@ -2883,6 +2898,7 @@ int kvm_arch_prepare_memory_region(struct kvm *kvm,
 				   enum kvm_mr_change change)
 {
 	hva_t hva, reg_end;
+	gfn_t ipa_limit;
 	int ret = 0;
 
 	if (change != KVM_MR_CREATE && change != KVM_MR_MOVE &&
@@ -2891,9 +2907,14 @@ int kvm_arch_prepare_memory_region(struct kvm *kvm,
 
 	/*
 	 * Prevent userspace from creating a memory region outside of the IPA
-	 * space addressable by the KVM guest IPA space.
+	 * space addressable by the KVM guest IPA space. Realm shared IPAs alias
+	 * the corresponding private IPAs, so Realm memslots must reside entirely
+	 * in the lower half of that space.
 	 */
-	if ((new->base_gfn + new->npages) > (kvm_phys_size(&kvm->arch.mmu) >> PAGE_SHIFT))
+	ipa_limit = kvm_phys_size(&kvm->arch.mmu) >> PAGE_SHIFT;
+	if (kvm_vm_is_realm(kvm))
+		ipa_limit >>= 1;
+	if (new->base_gfn + new->npages > ipa_limit)
 		return -EFAULT;
 
 	/*
Signature · 1 line
2.43.0
#33 lore raw

Re: [PATCH v4 09/11] KVM: arm64: CCA: Prevent memslot modifications after Realm creation

Quoted 18 lines · Steven Price

From: Suzuki K Poulose <[email protected]>

Once the Realm is created, prevent changes to guest_memfd backed memslots, which can provide private memory. Validate these changes before KVM invalidates the old memslot, so a rejected deletion leaves its stage-2 mappings intact. Realm stage-2 faults will also validate the private memory backing in a later commit.

Require Realm memslots to lie in the lower half of the IPA space, as the upper, shared half aliases the lower, protected half.

Define kvm_arch_has_private_mem() so generic KVM recognizes Realm VMs as supporting private memory. Defining the macro also makes gmem_in_place_conversion true for every arm64 VM, so guest_memfd memslots are marked gmem-only even for non-Realm VMs. A well-formed KVM_SET_MEMORY_ATTRIBUTES2 request on a non-Realm guest_memfd now reaches the VM check and returns -EINVAL instead of -ENOTTY.

Quoted 3 lines

Additionally, similar to pKVM, do not support dirty logging or read-only memslots.

Imo this could be split into a few patches

1. Add the constraints wrt realm memslots and being in the lower half of the IPA space
2. Defining arm's support for private mem
3. Imposing rules on memslot changes
4. Maybe some others, maybe I'm misunderstanding the patch

Quoted 34 lines

---
Changes since v3:
- Explain the arm64-wide in-place conversion effect and keep the general IPA limit comment.

Changes since v1:
- Preserve private mappings if KVM invalidates a Realm guest_memfd slot before the prepare hook rejects its deletion.

---
 arch/arm64/include/asm/kvm_host.h |  2 ++
 arch/arm64/kvm/mmu.c              | 37 ++++++++++++++++++++++++-------
 2 files changed, 31 insertions(+), 8 deletions(-)
arch/arm64/include/asm/kvm_host.h +2 -0
index 3ddeddfacd06..55673d08e3eb 100644
@@ -1607,6 +1607,8 @@ struct kvm *kvm_arch_alloc_vm(void);
 
 #define kvm_vm_is_realm(kvm)		((kvm)->arch.vm_flavor == VM_REALM)
 
+#define kvm_arch_has_private_mem(kvm) kvm_vm_is_realm(kvm)
+
 #define kvm_has_mte(kvm)					\
 	(system_supports_mte() &&				\
 	 test_bit(KVM_ARCH_FLAG_MTE_ENABLED, &(kvm)->arch.flags))
arch/arm64/kvm/mmu.c +0 -0
index 800333a345cd..9af5fe6d87f0 100644

arch/arm64/kvm/mmu.c int kvm_arch_validate_memory_region(struct kvm *kvm, · line 2866

Quoted 7 lines
arch/arm64/kvm/mmu.c +3 -1
@@ -2861,17 +2861,32 @@ int kvm_arch_validate_memory_region(struct kvm *kvm,
 {
 	lockdep_assert_held(&kvm->slots_lock);
 
-	if (kvm_vm_is_protected(kvm)) {
+	if (kvm_vm_is_protected(kvm) && new &&
+	    (new->flags & (KVM_MEM_LOG_DIRTY_PAGES | KVM_MEM_READONLY)))
+		return -EPERM;

gmem is already generically mutually exclusive with KVM_MEM_LOG_DIRTY_PAGES and KVM_MEM_READONLY, so before this change, pKVM is saying no to KVM_MEM_LOG_DIRTY_PAGES and KVM_MEM_READONLY for all memslots, gmem or not, so this check makes sense.

arch/arm64/kvm/mmu.c int kvm_arch_validate_memory_region(struct kvm *kvm, · line 2874

Quoted 10 lines
arch/arm64/kvm/mmu.c +5 -2
+
+	switch (kvm->arch.vm_flavor) {
+	case VM_PROTECTED_PKVM:
 		/* Cannot modify memslots once a pVM has run. */
 		if (pkvm_hyp_vm_is_created(kvm) &&
-		    (change == KVM_MR_DELETE || change == KVM_MR_MOVE)) {
+		    (change == KVM_MR_DELETE || change == KVM_MR_MOVE))
 			return -EPERM;
-		}
+		break;

Not sure why pKVM doesn't allow deleting a memslot after the vm is created, but this is no change from before this patch, the removal of {} here is mixed in with the other changes in this patch.

Quoted 6 lines
arch/arm64/kvm/mmu.c +6 -0
+	case VM_REALM:
+		/*
+		 * Once the Realm is created, we cannot modify any slots that
+		 * could be providing private memory. i.e., guest_memfd backed
+		 * slots.
+		 * TODO: Handle trusted device private memory slots

arch/arm64/kvm/mmu.c int kvm_arch_validate_memory_region(struct kvm *kvm, · line 2887

Quoted 10 lines
arch/arm64/kvm/mmu.c +5 -3
+		 */
+		if (!kvm_realm_is_created(kvm))
+			break;
 
-		if (new &&
-		    new->flags & (KVM_MEM_LOG_DIRTY_PAGES | KVM_MEM_READONLY)) {
+		if (kvm_slot_has_gmem(old) || kvm_slot_has_gmem(new))
 			return -EPERM;
-		}
+		break;

Imo this should be written the same way as the pKVM branch for clarity, like

if (kvm_realm_is_created() &&

    (kvm_slot_has_gmem(old) || kvm_slot_has_gmem(new)))
        return -EPERM;

but that aside,

1. Why block creating memslots after realm is created?

Does ARM CCA have no way to add pages after a VM starts? This isn't blocked for TDX and SNP so I think this constraint seems unnecessary.

2. Why block deleting memslots after realm is created?

This also seems like an artificial constraint, and it constrains the way the userspace VMM operates when stopping a VM, like the memslots can't be removed ever, the VM just has to be closed? (something like that)

Quoted 32 lines
arch/arm64/kvm/mmu.c +10 -3
+	default:
+		break;
 	}
 
 	return 0;
@@ -2883,6 +2898,7 @@ int kvm_arch_prepare_memory_region(struct kvm *kvm,
 				   enum kvm_mr_change change)
 {
 	hva_t hva, reg_end;
+	gfn_t ipa_limit;
 	int ret = 0;
 
 	if (change != KVM_MR_CREATE && change != KVM_MR_MOVE &&
@@ -2891,9 +2907,14 @@ int kvm_arch_prepare_memory_region(struct kvm *kvm,
 
 	/*
 	 * Prevent userspace from creating a memory region outside of the IPA
-	 * space addressable by the KVM guest IPA space.
+	 * space addressable by the KVM guest IPA space. Realm shared IPAs alias
+	 * the corresponding private IPAs, so Realm memslots must reside entirely
+	 * in the lower half of that space.
 	 */
-	if ((new->base_gfn + new->npages) > (kvm_phys_size(&kvm->arch.mmu) >> PAGE_SHIFT))
+	ipa_limit = kvm_phys_size(&kvm->arch.mmu) >> PAGE_SHIFT;
+	if (kvm_vm_is_realm(kvm))
+		ipa_limit >>= 1;
+	if (new->base_gfn + new->npages > ipa_limit)
 		return -EFAULT;
 
 	/*
--

2.43.0

#34 lore raw

Re: [PATCH v4 09/11] KVM: arm64: CCA: Prevent memslot modifications after Realm creation

Hi Ackerley

Quoted 24 lines · Ackerley Tng
Quoted 18 lines · Steven Price

From: Suzuki K Poulose <[email protected]>

Once the Realm is created, prevent changes to guest_memfd backed memslots, which can provide private memory. Validate these changes before KVM invalidates the old memslot, so a rejected deletion leaves its stage-2 mappings intact. Realm stage-2 faults will also validate the private memory backing in a later commit.

Require Realm memslots to lie in the lower half of the IPA space, as the upper, shared half aliases the lower, protected half.

Define kvm_arch_has_private_mem() so generic KVM recognizes Realm VMs as supporting private memory. Defining the macro also makes gmem_in_place_conversion true for every arm64 VM, so guest_memfd memslots are marked gmem-only even for non-Realm VMs. A well-formed KVM_SET_MEMORY_ATTRIBUTES2 request on a non-Realm guest_memfd now reaches the VM check and returns -EINVAL instead of -ENOTTY.

Quoted 3 lines

Additionally, similar to pKVM, do not support dirty logging or read-only memslots.

Quoted 7 lines

Imo this could be split into a few patches

1. Add the constraints wrt realm memslots and being in the lower half of the IPA space
2. Defining arm's support for private mem
3. Imposing rules on memslot changes
4. Maybe some others, maybe I'm misunderstanding the patch

Agree

Quoted 48 lines
Quoted 35 lines

---
Changes since v3:
- Explain the arm64-wide in-place conversion effect and keep the general IPA limit comment.

Changes since v1:
- Preserve private mappings if KVM invalidates a Realm guest_memfd slot before the prepare hook rejects its deletion.

---
  arch/arm64/include/asm/kvm_host.h |  2 ++
  arch/arm64/kvm/mmu.c              | 37 ++++++++++++++++++++++++-------
  2 files changed, 31 insertions(+), 8 deletions(-)
arch/arm64/include/asm/kvm_host.h +2 -0
index 3ddeddfacd06..55673d08e3eb 100644
@@ -1607,6 +1607,8 @@ struct kvm *kvm_arch_alloc_vm(void);
 
  #define kvm_vm_is_realm(kvm)		((kvm)->arch.vm_flavor == VM_REALM)
 
+#define kvm_arch_has_private_mem(kvm) kvm_vm_is_realm(kvm)
+
  #define kvm_has_mte(kvm)					\
  	(system_supports_mte() &&				\
  	 test_bit(KVM_ARCH_FLAG_MTE_ENABLED, &(kvm)->arch.flags))
arch/arm64/kvm/mmu.c +0 -0
index 800333a345cd..9af5fe6d87f0 100644

arch/arm64/kvm/mmu.c int kvm_arch_validate_memory_region(struct kvm *kvm, · line 2866

Quoted 7 lines
arch/arm64/kvm/mmu.c +3 -1
@@ -2861,17 +2861,32 @@ int kvm_arch_validate_memory_region(struct kvm *kvm,
  {
  	lockdep_assert_held(&kvm->slots_lock);
 
-	if (kvm_vm_is_protected(kvm)) {
+	if (kvm_vm_is_protected(kvm) && new &&
+	    (new->flags & (KVM_MEM_LOG_DIRTY_PAGES | KVM_MEM_READONLY)))
+		return -EPERM;

gmem is already generically mutually exclusive with KVM_MEM_LOG_DIRTY_PAGES and KVM_MEM_READONLY, so before this change, pKVM is saying no to KVM_MEM_LOG_DIRTY_PAGES and KVM_MEM_READONLY for all memslots, gmem or not, so this check makes sense.

Quoted 14 lines

arch/arm64/kvm/mmu.c int kvm_arch_validate_memory_region(struct kvm *kvm, · line 2874

Quoted 10 lines
arch/arm64/kvm/mmu.c +5 -2
+
+	switch (kvm->arch.vm_flavor) {
+	case VM_PROTECTED_PKVM:
  		/* Cannot modify memslots once a pVM has run. */
  		if (pkvm_hyp_vm_is_created(kvm) &&
-		    (change == KVM_MR_DELETE || change == KVM_MR_MOVE)) {
+		    (change == KVM_MR_DELETE || change == KVM_MR_MOVE))
  			return -EPERM;
-		}
+		break;

Not sure why pKVM doesn't allow deleting a memslot after the vm is created, but this is no change from before this patch, the removal of {} here is mixed in with the other changes in this patch.

IIRC, pKVM relies on pinning the stage2 until the teardown ? ed
from the Stage2 unless we d

Quoted 25 lines
Quoted 7 lines
arch/arm64/kvm/mmu.c +6 -0
+	case VM_REALM:
+		/*
+		 * Once the Realm is created, we cannot modify any slots that
+		 * could be providing private memory. i.e., guest_memfd backed
+		 * slots.
+		 * TODO: Handle trusted device private memory slots

arch/arm64/kvm/mmu.c int kvm_arch_validate_memory_region(struct kvm *kvm, · line 2887

Quoted 10 lines
arch/arm64/kvm/mmu.c +5 -3
+		 */
+		if (!kvm_realm_is_created(kvm))
+			break;
 
-		if (new &&
-		    new->flags & (KVM_MEM_LOG_DIRTY_PAGES | KVM_MEM_READONLY)) {
+		if (kvm_slot_has_gmem(old) || kvm_slot_has_gmem(new))
  			return -EPERM;
-		}
+		break;

Imo this should be written the same way as the pKVM branch for clarity, like

if (kvm_realm_is_created() &&

     (kvm_slot_has_gmem(old) || kvm_slot_has_gmem(new)))
         return -EPERM;
Quoted 6 lines

but that aside,

1. Why block creating memslots after realm is created?

Does ARM CCA have no way to add pages after a VM starts? This isn't blocked for TDX and SNP so I think this constraint seems unnecessary.

This and (2) was triggered by the following thread, raised by Catalin.

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

But having said that, since then, we now have :

1) All private faults must be serviced by realm_gmem_abort(), which mandates Guest memfd slot. (See Patch 11, realm_mem_abort())

2) realm_gmem_abort() matches the "private" attribute for a "protected" fault, failing which causes a memory fault exit.

So I think we can remove these memslot restrictions.

Quoted 6 lines

2. Why block deleting memslots after realm is created?

This also seems like an artificial constraint, and it constrains the way the userspace VMM operates when stopping a VM, like the memslots can't be removed ever, the VM just has to be closed? (something like that)

As mentioned above, I think we are good to remove the restrictions.

Suzuki

Quoted 33 lines
Quoted 33 lines
arch/arm64/kvm/mmu.c +10 -3
+	default:
+		break;
  	}
 
  	return 0;
@@ -2883,6 +2898,7 @@ int kvm_arch_prepare_memory_region(struct kvm *kvm,
  				   enum kvm_mr_change change)
  {
  	hva_t hva, reg_end;
+	gfn_t ipa_limit;
  	int ret = 0;
 
  	if (change != KVM_MR_CREATE && change != KVM_MR_MOVE &&
@@ -2891,9 +2907,14 @@ int kvm_arch_prepare_memory_region(struct kvm *kvm,
 
  	/*
  	 * Prevent userspace from creating a memory region outside of the IPA
-	 * space addressable by the KVM guest IPA space.
+	 * space addressable by the KVM guest IPA space. Realm shared IPAs alias
+	 * the corresponding private IPAs, so Realm memslots must reside entirely
+	 * in the lower half of that space.
  	 */
-	if ((new->base_gfn + new->npages) > (kvm_phys_size(&kvm->arch.mmu) >> PAGE_SHIFT))
+	ipa_limit = kvm_phys_size(&kvm->arch.mmu) >> PAGE_SHIFT;
+	if (kvm_vm_is_realm(kvm))
+		ipa_limit >>= 1;
+	if (new->base_gfn + new->npages > ipa_limit)
  		return -EFAULT;
 
  	/*
--

2.43.0

#35 lore raw

Re: [PATCH v4 09/11] KVM: arm64: CCA: Prevent memslot modifications after Realm creation

Quoted 29 lines · Suzuki K Poulose

Hi Ackerley

Quoted 26 lines · Ackerley Tng
Quoted 18 lines · Steven Price

From: Suzuki K Poulose <[email protected]>

Once the Realm is created, prevent changes to guest_memfd backed memslots, which can provide private memory. Validate these changes before KVM invalidates the old memslot, so a rejected deletion leaves its stage-2 mappings intact. Realm stage-2 faults will also validate the private memory backing in a later commit.

Require Realm memslots to lie in the lower half of the IPA space, as the upper, shared half aliases the lower, protected half.

Define kvm_arch_has_private_mem() so generic KVM recognizes Realm VMs as supporting private memory. Defining the macro also makes gmem_in_place_conversion true for every arm64 VM, so guest_memfd memslots are marked gmem-only even for non-Realm VMs. A well-formed KVM_SET_MEMORY_ATTRIBUTES2 request on a non-Realm guest_memfd now reaches the VM check and returns -EINVAL instead of -ENOTTY.

Quoted 3 lines

Additionally, similar to pKVM, do not support dirty logging or read-only memslots.

Imo this could be split into a few patches

Quoted 7 lines
Quoted 5 lines

1. Add the constraints wrt realm memslots and being in the lower half of the IPA space
2. Defining arm's support for private mem
3. Imposing rules on memslot changes
4. Maybe some others, maybe I'm misunderstanding the patch

Agree

Yes, although as discussed below, I think we probably don't need to have as much restriction on memslots as this currently adds.

Quoted 109 lines
Quoted 62 lines
Quoted 37 lines

---
Changes since v3:
- Explain the arm64-wide in-place conversion effect and keep the general IPA limit comment.

Changes since v1:
- Preserve private mappings if KVM invalidates a Realm guest_memfd slot before the prepare hook rejects its deletion.
---
  arch/arm64/include/asm/kvm_host.h |  2 ++ arch/arm64/kvm/mmu.c              | 37 ++++++++++++++++++++++++-------

  2 files changed, 31 insertions(+), 8 deletions(-)
arch/arm64/include/ renamed from arch/arm64/include/asm/kvm_host.h +0 -0

asm/kvm_host.h
index 3ddeddfacd06..55673d08e3eb 100644

arch/arm64/include/asm/kvm_host.h +2 -0
@@ -1607,6 +1607,8 @@ struct kvm *kvm_arch_alloc_vm(void);
 
   #define kvm_vm_is_realm(kvm)        ((kvm)->arch.vm_flavor ==
 VM_REALM)
 
+#define kvm_arch_has_private_mem(kvm) kvm_vm_is_realm(kvm)
+
   #define kvm_has_mte(kvm)                    \
       (system_supports_mte() &&                \

       test_bit(KVM_ARCH_FLAG_MTE_ENABLED, &(kvm)->arch.flags))

arch/arm64/kvm/mmu.c +0 -0
index 800333a345cd..9af5fe6d87f0 100644

arch/arm64/kvm/mmu.c int kvm_arch_validate_memory_region(struct · line 2867

Quoted 8 lines
arch/arm64/kvm/mmu.c +3 -1
@@ -2861,17 +2861,32 @@ int kvm_arch_validate_memory_region(struct
 kvm *kvm,
   {
       lockdep_assert_held(&kvm->slots_lock);
 
-    if (kvm_vm_is_protected(kvm)) {
+    if (kvm_vm_is_protected(kvm) && new &&
+        (new->flags & (KVM_MEM_LOG_DIRTY_PAGES | KVM_MEM_READONLY)))
+        return -EPERM;

gmem is already generically mutually exclusive with KVM_MEM_LOG_DIRTY_PAGES and KVM_MEM_READONLY, so before this change, pKVM is saying no to KVM_MEM_LOG_DIRTY_PAGES and KVM_MEM_READONLY for all memslots, gmem or not, so this check makes sense.

Quoted 10 lines
arch/arm64/kvm/mmu.c +3 -0
+
+    switch (kvm->arch.vm_flavor) {
+    case VM_PROTECTED_PKVM:
           /* Cannot modify memslots once a pVM has run. */

          if (pkvm_hyp_vm_is_created(kvm) &&

-            (change == KVM_MR_DELETE || change == KVM_MR_MOVE)) {
+            (change == KVM_MR_DELETE || change == KVM_MR_MOVE))

              return -EPERM;
-        }
+        break;

Quoted 3 lines

Not sure why pKVM doesn't allow deleting a memslot after the vm is created, but this is no change from before this patch, the removal of {} here is mixed in with the other changes in this patch.

IIRC, pKVM relies on pinning the stage2 until the teardown ? ed
from the Stage2 unless we d

Quoted 26 lines
Quoted 11 lines

+    case VM_REALM:
+        /*
+         * Once the Realm is created, we cannot modify any slots that +         * could be providing private memory. i.e., guest_memfd backed +         * slots.
+         * TODO: Handle trusted device private memory slots +         */
+        if (!kvm_realm_is_created(kvm))
+            break;

Quoted 7 lines

-        if (new &&
-            new->flags & (KVM_MEM_LOG_DIRTY_PAGES | KVM_MEM_READONLY)) {
+        if (kvm_slot_has_gmem(old) || kvm_slot_has_gmem(new)) return -EPERM;
-        }
+        break;

Imo this should be written the same way as the pKVM branch for clarity, like

if (kvm_realm_is_created() && (kvm_slot_has_gmem(old) || kvm_slot_has_gmem(new))) return -EPERM;

Quoted 6 lines

but that aside,

1. Why block creating memslots after realm is created?

Does ARM CCA have no way to add pages after a VM starts? This isn't blocked for TDX and SNP so I think this constraint seems unnecessary.

This and (2) was triggered by the following thread, raised by Catalin.

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

But having said that, since then, we now have :

Quoted 7 lines

1) All private faults must be serviced by realm_gmem_abort(), which mandates Guest memfd slot. (See Patch 11, realm_mem_abort())

2) realm_gmem_abort() matches the "private" attribute for a "protected" fault, failing which causes a memory fault exit.

So I think we can remove these memslot restrictions.

Agreed. We originally had memslots backed by user space memory. That meant adding or removing a memslot had to deal with all the messiness of dealing this that. As an initial step it was easier to just prevent memslot changes. guest_memfd simplifies things so I don't think this restriction is actually necessary - and I think it will actually simplify the code to not restrict it.

Quoted 8 lines
Quoted 6 lines

2. Why block deleting memslots after realm is created?

This also seems like an artificial constraint, and it constrains the way the userspace VMM operates when stopping a VM, like the memslots can't be removed ever, the VM just has to be closed? (something like that)

As mentioned above, I think we are good to remove the restrictions.

Agreed.

Thanks,
Steve

Quoted 43 lines

Suzuki

Quoted 39 lines
Quoted 39 lines

+    default:
+        break;
      }

      return 0;

arch/arm64/kvm/mmu.c +1 -0
@@ -2883,6 +2898,7 @@ int kvm_arch_prepare_memory_region(struct kvm
 *kvm,
                      enum kvm_mr_change change)
   {
       hva_t hva, reg_end;
+    gfn_t ipa_limit;
       int ret = 0;
 

      if (change != KVM_MR_CREATE && change != KVM_MR_MOVE &&

arch/arm64/kvm/mmu.c +0 -0
@@ -2891,9 +2907,14 @@ int kvm_arch_prepare_memory_region(struct kvm
 *kvm,
 
       /*
        * Prevent userspace from creating a memory region outside of

the IPA
-     * space addressable by the KVM guest IPA space.
+     * space addressable by the KVM guest IPA space. Realm shared IPAs alias
+     * the corresponding private IPAs, so Realm memslots must reside entirely
+     * in the lower half of that space.
       */
-    if ((new->base_gfn + new->npages) > (kvm_phys_size(&kvm-

Quoted 1 line

arch.mmu) >> PAGE_SHIFT))

+    ipa_limit = kvm_phys_size(&kvm->arch.mmu) >> PAGE_SHIFT; +    if (kvm_vm_is_realm(kvm))
+        ipa_limit >>= 1;
+    if (new->base_gfn + new->npages > ipa_limit) return -EFAULT;

      /*

Signature · 1 line
2.43.0
#36 lore raw

PATCH v4 10/11 KVM: arm64: CCA: Support runtime faulting of memory

In reply to Steven Price

At runtime, if the realm guest accesses an IPA without a stage-2 mapping, then KVM fixes up the stage-2 mapping for the backing memory.

For memory in the lower (protected) region of IPA, verify that the corresponding guest_memfd page is private before delegating to the RMM. The RMM then maps the delegated page into the Realm.

For memory in the upper (shared) IPA region, map the backing page as non-secure memory. Check that a guest_memfd page is shared when the fault uses guest_memfd; ordinary userspace-backed memslots can only be mapped at unprotected IPAs and follow the normal user memory fault path.

If the fault IPA and guest_memfd attributes disagree then exit to userspace with KVM_EXIT_MEMORY_FAULT so the VMM can perform the required conversion. If a shared IPA has no memslot, KVM follows the existing MMIO or abort-injection path. The latter can result in injecting a SEA to the guest.

Realm faults may need to create RTTs, including when updating a mapping after a permission fault. Take the write side of mmu_lock and top up the MMU cache for these faults. Do not pre-fault Realm memory.

The lock helpers are in a header compiled by nVHE too. Make kvm_vm_hyp_is_distrusting() available there for the lock choice.

---
Changes since v3:
- Split Realm faults into dedicated guest_memfd and userspace mapping paths, leaving the native fault paths unchanged.
- Unmap earlier shared mappings if a later RMI map call fails.
- Clarify that runtime RMI data mapping does not guarantee zeroed contents.

Changes since v2:
- Route all guest_memfd faults through gmem_abort(). Bound each protected RMI map call to its encoded range, create the required RTT levels, and tighten retry and error handling.

Changes since v1:
- Use the write side of mmu_lock and top up the MMU cache for Realm faults that may create RTTs. Skip unnecessary cache flushing, disable Realm pre-faulting, and tighten memory-fault and mapping retry handling.

---
 arch/arm64/include/asm/kvm_emulate.h |  13 ++
 arch/arm64/include/asm/kvm_host.h    |   4 +-
 arch/arm64/include/asm/kvm_mmu.h     |   4 +-
 arch/arm64/include/asm/kvm_rmi.h     |  12 ++
 arch/arm64/kvm/mmu.c                 | 174 +++++++++++++++--
 arch/arm64/kvm/rmi.c                 | 268 +++++++++++++++++++++++++++
 6 files changed, 459 insertions(+), 16 deletions(-)
arch/arm64/include/asm/kvm_emulate.h +13 -0
index 32021bdf2610..8a71fddfdb85 100644
@@ -847,4 +847,17 @@ static inline bool kvm_realm_is_created(struct kvm *kvm)
 	return kvm_vm_is_realm(kvm) && kvm_realm_state(kvm) != REALM_STATE_NONE;
 }
 
+static inline gpa_t kvm_gpa_from_fault(struct kvm *kvm, phys_addr_t ipa)
+{
+	if (!kvm_vm_is_realm(kvm))
+		return ipa;
+
+	return ipa & ~BIT(kvm->arch.realm.ia_bits - 1);
+}
+
+static inline gfn_t kvm_gfn_from_fault(struct kvm *kvm, phys_addr_t ipa)
+{
+	return gpa_to_gfn(kvm_gpa_from_fault(kvm, ipa));
+}
+
 #endif /* __ARM64_KVM_EMULATE_H__ */
arch/arm64/include/asm/kvm_host.h +2 -2
index 55673d08e3eb..505c0c5b7dbb 100644
@@ -1601,12 +1601,12 @@ struct kvm *kvm_arch_alloc_vm(void);
 #define kvm_vm_is_protected(kvm)	((kvm)->arch.vm_flavor >= __VM_PROTECTED)
 #define vcpu_is_protected(vcpu)		kvm_vm_is_protected((vcpu)->kvm)
 
-#define kvm_vm_hyp_is_distrusting(kvm)	((kvm)->arch.vm_flavor >= __VM_DISTRUSTING_HYP)
-
 #endif	/* __KVM_NVHE_HYPERVISOR__ */
 
 #define kvm_vm_is_realm(kvm)		((kvm)->arch.vm_flavor == VM_REALM)
 
+#define kvm_vm_hyp_is_distrusting(kvm)	((kvm)->arch.vm_flavor >= __VM_DISTRUSTING_HYP)
+
 #define kvm_arch_has_private_mem(kvm) kvm_vm_is_realm(kvm)
 
 #define kvm_has_mte(kvm)					\
arch/arm64/include/asm/kvm_mmu.h +2 -2
index 32392abf2e21..a70f8bd4b2b9 100644
@@ -371,7 +371,7 @@ static inline bool kvm_is_nested_s2_mmu(struct kvm *kvm, struct kvm_s2_mmu *mmu)
 
 static inline void kvm_fault_lock(struct kvm *kvm)
 {
-	if (is_protected_kvm_enabled())
+	if (kvm_vm_hyp_is_distrusting(kvm))
 		write_lock(&kvm->mmu_lock);
 	else
 		read_lock(&kvm->mmu_lock);
@@ -379,7 +379,7 @@ static inline void kvm_fault_lock(struct kvm *kvm)
 
 static inline void kvm_fault_unlock(struct kvm *kvm)
 {
-	if (is_protected_kvm_enabled())
+	if (kvm_vm_hyp_is_distrusting(kvm))
 		write_unlock(&kvm->mmu_lock);
 	else
 		read_unlock(&kvm->mmu_lock);
arch/arm64/include/asm/kvm_rmi.h +12 -0
index 8a136fb67318..697964b5b4e4 100644
@@ -6,6 +6,7 @@
 #ifndef __ASM_KVM_RMI_H
 #define __ASM_KVM_RMI_H
 
+#include <asm/kvm_pgtable.h>
 #include <linux/arm-smccc-rmi.h>
 #include <linux/kvm.h>
 
@@ -90,4 +91,15 @@ void kvm_realm_unmap_range_filter(struct kvm *kvm,
 				  bool may_block,
 				  enum kvm_gfn_range_filter attr_filter);
 
+int realm_map_ipa(struct kvm *kvm, phys_addr_t ipa,
+		  kvm_pfn_t pfn, unsigned long map_size,
+		  enum kvm_pgtable_prot prot,
+		  struct kvm_mmu_memory_cache *memcache);
+
+static inline bool kvm_realm_is_private_address(struct realm *realm,
+						unsigned long addr)
+{
+	return !(addr & BIT(realm->ia_bits - 1));
+}
+
 #endif /* __ASM_KVM_RMI_H */
arch/arm64/kvm/mmu.c +162 -12

276 lines not on this page · raw message

arch/arm64/kvm/rmi.c +268 -0

274 lines not on this page · raw message

Signature · 1 line
2.43.0
#37 lore raw

Re: [PATCH v4 10/11] KVM: arm64: CCA: Support runtime faulting of memory

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] KVM: arm64: RMI_BLOCKED and start_level mishandled in realm_map_unprotected() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] KVM: arm64: RMI_BLOCKED and start_level mishandled in realm_map_unprotected()
--

commit ad7be4b62d117614b38172987f33095d60197e1c
Author: Steven Price <[email protected]>

KVM: arm64: CCA: Support runtime faulting of memory

This commit adds stage-2 page fault handling for Arm CCA Realm guests, delegating private guest_memfd pages to the RMM and mapping shared pages at unprotected IPAs.

Quoted 5 lines
arch/arm64/kvm/rmi.c +0 -0
index b34f5320b50b6..ab606a2dc2f57 100644
@@ -593,6 +593,274 @@ void kvm_realm_unmap_range_filter(struct kvm *kvm, unsigned long start,

[ ... ]

Quoted 7 lines
arch/arm64/kvm/rmi.c +7 -0
+static int realm_map_unprotected(struct kvm *kvm,
+				 unsigned long ipa,
+				 kvm_pfn_t pfn,
+				 unsigned long size,
+				 enum kvm_pgtable_prot prot,
+				 struct kvm_mmu_memory_cache *memcache)
+{

[ ... ]

Quoted 25 lines
arch/arm64/kvm/rmi.c +25 -0
+	while (ipa < ipa_top) {
+		unsigned long range_desc = addr_range_desc(realm, ipa, phys,
+							   ipa_top - ipa,
+							   RMI_OP_MEM_UNDELEGATED);
+		unsigned long call_top = ipa + RMI_ADDR_RANGE_COUNT(range_desc) *
+			rmi_addr_block_size_to_bytes(RMI_ADDR_RANGE_BLOCK_SIZE(range_desc));
+		unsigned long out_top;
+
+		ret = rmi_rtt_unprot_map(rd, ipa, call_top, flags, range_desc,
+					 &out_top);
+		if (ret < 0)
+			goto err_unmap;
+
+		if (ret) {
+			/* Create missing RTTs and retry */
+			int level = RMI_RESULT_DATA_LEVEL(ret);
+			int req_level = KVM_PGTABLE_LAST_LEVEL -
+				RMI_ADDR_RANGE_BLOCK_SIZE(range_desc);
+
+			if (RMI_RESULT_STATUS(ret) != RMI_ERROR_RTT ||
+			    ++retries > KVM_PGTABLE_LAST_LEVEL + 2) {
+				ret = -ENXIO;
+				goto err_unmap;
+			}
+

arch/arm64/kvm/rmi.c void kvm_realm_unmap_range_filter(struct kvm *kvm, unsigned long start, · line 812

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+			/* Replace an existing mapping to update its permissions. */
+			if (level >= req_level) {
+				realm_unmap_shared_range(kvm, ipa, ipa_top, false,
+							 memcache);
+				continue;
+			}
+
+			ret = realm_create_rtt_levels(realm, ipa, level,
+						      req_level,
+						      memcache);

[Severity: Medium]
Should realm_map_unprotected() translate RMI_BLOCKED into -EAGAIN and check level < realm->start_level, matching realm_map_protected()?

When rmi_rtt_unprot_map() returns RMI_BLOCKED under RMM lock contention, RMI_RESULT_STATUS(ret) != RMI_ERROR_RTT turns it into -ENXIO, causing realm_gmem_abort() or realm_s2_fault_map() to fail KVM_RUN instead of dropping mmu_lock and retrying the fault. Also, on RMI_ERROR_RTT with level < req_level, level is not checked against realm->start_level before calling realm_create_rtt_levels().

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

Re: [PATCH v4 10/11] KVM: arm64: CCA: Support runtime faulting of memory

In reply to Steven Price
Quoted 177 lines · Steven Price

At runtime, if the realm guest accesses an IPA without a stage-2 mapping, then KVM fixes up the stage-2 mapping for the backing memory.

For memory in the lower (protected) region of IPA, verify that the corresponding guest_memfd page is private before delegating to the RMM. The RMM then maps the delegated page into the Realm.

For memory in the upper (shared) IPA region, map the backing page as non-secure memory. Check that a guest_memfd page is shared when the fault uses guest_memfd; ordinary userspace-backed memslots can only be mapped at unprotected IPAs and follow the normal user memory fault path.

If the fault IPA and guest_memfd attributes disagree then exit to userspace with KVM_EXIT_MEMORY_FAULT so the VMM can perform the required conversion. If a shared IPA has no memslot, KVM follows the existing MMIO or abort-injection path. The latter can result in injecting a SEA to the guest.

Realm faults may need to create RTTs, including when updating a mapping after a permission fault. Take the write side of mmu_lock and top up the MMU cache for these faults. Do not pre-fault Realm memory.

The lock helpers are in a header compiled by nVHE too. Make kvm_vm_hyp_is_distrusting() available there for the lock choice.

---
Changes since v3:
- Split Realm faults into dedicated guest_memfd and userspace mapping paths, leaving the native fault paths unchanged.
- Unmap earlier shared mappings if a later RMI map call fails.
- Clarify that runtime RMI data mapping does not guarantee zeroed contents.

Changes since v2:
- Route all guest_memfd faults through gmem_abort(). Bound each protected RMI map call to its encoded range, create the required RTT levels, and tighten retry and error handling.

Changes since v1:
- Use the write side of mmu_lock and top up the MMU cache for Realm faults that may create RTTs. Skip unnecessary cache flushing, disable Realm pre-faulting, and tighten memory-fault and mapping retry handling.

---
  arch/arm64/include/asm/kvm_emulate.h |  13 ++
  arch/arm64/include/asm/kvm_host.h    |   4 +-
  arch/arm64/include/asm/kvm_mmu.h     |   4 +-
  arch/arm64/include/asm/kvm_rmi.h     |  12 ++
  arch/arm64/kvm/mmu.c                 | 174 +++++++++++++++--
  arch/arm64/kvm/rmi.c                 | 268 +++++++++++++++++++++++++++
  6 files changed, 459 insertions(+), 16 deletions(-)
arch/arm64/include/asm/kvm_emulate.h +13 -0
index 32021bdf2610..8a71fddfdb85 100644
@@ -847,4 +847,17 @@ static inline bool kvm_realm_is_created(struct kvm *kvm)
  	return kvm_vm_is_realm(kvm) && kvm_realm_state(kvm) != REALM_STATE_NONE;
  }
 
+static inline gpa_t kvm_gpa_from_fault(struct kvm *kvm, phys_addr_t ipa)
+{
+	if (!kvm_vm_is_realm(kvm))
+		return ipa;
+
+	return ipa & ~BIT(kvm->arch.realm.ia_bits - 1);
+}
+
+static inline gfn_t kvm_gfn_from_fault(struct kvm *kvm, phys_addr_t ipa)
+{
+	return gpa_to_gfn(kvm_gpa_from_fault(kvm, ipa));
+}
+
  #endif /* __ARM64_KVM_EMULATE_H__ */
arch/arm64/include/asm/kvm_host.h +2 -2
index 55673d08e3eb..505c0c5b7dbb 100644
@@ -1601,12 +1601,12 @@ struct kvm *kvm_arch_alloc_vm(void);
  #define kvm_vm_is_protected(kvm)	((kvm)->arch.vm_flavor >= __VM_PROTECTED)
  #define vcpu_is_protected(vcpu)		kvm_vm_is_protected((vcpu)->kvm)
 
-#define kvm_vm_hyp_is_distrusting(kvm)	((kvm)->arch.vm_flavor >= __VM_DISTRUSTING_HYP)
-
  #endif	/* __KVM_NVHE_HYPERVISOR__ */
 
  #define kvm_vm_is_realm(kvm)		((kvm)->arch.vm_flavor == VM_REALM)
 
+#define kvm_vm_hyp_is_distrusting(kvm)	((kvm)->arch.vm_flavor >= __VM_DISTRUSTING_HYP)
+
  #define kvm_arch_has_private_mem(kvm) kvm_vm_is_realm(kvm)
 
  #define kvm_has_mte(kvm)					\
arch/arm64/include/asm/kvm_mmu.h +2 -2
index 32392abf2e21..a70f8bd4b2b9 100644
@@ -371,7 +371,7 @@ static inline bool kvm_is_nested_s2_mmu(struct kvm *kvm, struct kvm_s2_mmu *mmu)
 
  static inline void kvm_fault_lock(struct kvm *kvm)
  {
-	if (is_protected_kvm_enabled())
+	if (kvm_vm_hyp_is_distrusting(kvm))
  		write_lock(&kvm->mmu_lock);
  	else
  		read_lock(&kvm->mmu_lock);
@@ -379,7 +379,7 @@ static inline void kvm_fault_lock(struct kvm *kvm)
 
  static inline void kvm_fault_unlock(struct kvm *kvm)
  {
-	if (is_protected_kvm_enabled())
+	if (kvm_vm_hyp_is_distrusting(kvm))
  		write_unlock(&kvm->mmu_lock);
  	else
  		read_unlock(&kvm->mmu_lock);
arch/arm64/include/asm/kvm_rmi.h +12 -0
index 8a136fb67318..697964b5b4e4 100644
@@ -6,6 +6,7 @@
  #ifndef __ASM_KVM_RMI_H
  #define __ASM_KVM_RMI_H
 
+#include <asm/kvm_pgtable.h>
  #include <linux/arm-smccc-rmi.h>
  #include <linux/kvm.h>
 
@@ -90,4 +91,15 @@ void kvm_realm_unmap_range_filter(struct kvm *kvm,
  				  bool may_block,
  				  enum kvm_gfn_range_filter attr_filter);
 
+int realm_map_ipa(struct kvm *kvm, phys_addr_t ipa,
+		  kvm_pfn_t pfn, unsigned long map_size,
+		  enum kvm_pgtable_prot prot,
+		  struct kvm_mmu_memory_cache *memcache);
+
+static inline bool kvm_realm_is_private_address(struct realm *realm,
+						unsigned long addr)
+{
+	return !(addr & BIT(realm->ia_bits - 1));
+}
+
  #endif /* __ASM_KVM_RMI_H */
arch/arm64/kvm/mmu.c +8 -0
index 9af5fe6d87f0..870dc7e2699b 100644
@@ -450,6 +450,10 @@ static void stage2_flush_vm(struct kvm *kvm)
  	struct kvm_memory_slot *memslot;
  	int idx, bkt;
 
+	/* The RMM requires FWB, so Realm stage-2 mappings need no cache flush. */
+	if (kvm_vm_is_realm(kvm))
+		return;
+
  	idx = srcu_read_lock(&kvm->srcu);
  	write_lock(&kvm->mmu_lock);
 
@@ -1225,6 +1229,10 @@ void stage2_unmap_vm(struct kvm *kvm)
  	struct kvm_memory_slot *memslot;
  	int idx, bkt;
 
+	/* For realms this is handled by the RMM so nothing to do here */
+	if (kvm_vm_is_realm(kvm))
+		return;
+
  	idx = srcu_read_lock(&kvm->srcu);
  	mmap_read_lock(current->mm);
  	write_lock(&kvm->mmu_lock);

arch/arm64/kvm/mmu.c static int gmem_abort(const struct kvm_s2_fault_desc *s2fd, · line 1812

Quoted 5 lines
arch/arm64/kvm/mmu.c +2 -0
@@ -1800,6 +1808,8 @@ static int gmem_abort(const struct kvm_s2_fault_desc *s2fd,
  		ret = topup_mmu_memcache(s2fd->mmu, memcache);
  		if (ret)
  			return ret;
+	}
+	if (!perm_fault) {

Spurious change ?

arch/arm64/kvm/mmu.c static int gmem_abort(const struct kvm_s2_fault_desc *s2fd, · line 1821

Quoted 9 lines
arch/arm64/kvm/mmu.c +1 -1
  		if (kvm_is_nested_s2_mmu(kvm, pgt->mmu)) {
  			mapping = kmalloc_obj(struct kvm_guest_s2_mapping, GFP_KERNEL_ACCOUNT);
  			if (!mapping)
@@ -1808,7 +1818,7 @@ static int gmem_abort(const struct kvm_s2_fault_desc *s2fd,
  	}
 
  	s2vi.vma_pagesize = PAGE_SIZE;
-	s2vi.gfn = ALIGN_DOWN(s2fd->fault_ipa, s2vi.vma_pagesize) >> PAGE_SHIFT;
+	s2vi.gfn = gpa_to_gfn(s2fd->fault_ipa);

These looks unrelated and could be dropped from this patch

Quoted 19 lines
arch/arm64/kvm/mmu.c +12 -0
  	canonical_gfn = get_canonical_gfn(s2fd, &s2vi);
 
  	write_fault = kvm_s2_fault_is_write(s2fd);
@@ -1890,6 +1900,66 @@ static int gmem_abort(const struct kvm_s2_fault_desc *s2fd,
  	return ret;
  }
 
+static int realm_gmem_abort(const struct kvm_s2_fault_desc *s2fd)
+{
+	struct kvm *kvm = s2fd->vcpu->kvm;
+	bool write_fault = kvm_s2_fault_is_write(s2fd);
+	bool exec_fault = kvm_s2_fault_is_exec(s2fd);
+	bool is_private;
+	enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_R;
+	kvm_pfn_t pfn;
+	gfn_t gfn;
+	u64 mmu_seq;
+	void *memcache;
+	int ret;

arch/arm64/kvm/mmu.c static int gmem_abort(const struct kvm_s2_fault_desc *s2fd, · line 1924

Quoted 10 lines
arch/arm64/kvm/mmu.c +10 -0
+
+	memcache = get_mmu_memcache(s2fd->vcpu);
+	ret = topup_mmu_memcache(s2fd->mmu, memcache);
+	if (ret)
+		return ret;
+
+	gfn = kvm_gfn_from_fault(kvm, s2fd->fault_ipa);
+	is_private = kvm_realm_is_private_address(&kvm->arch.realm,
+						  s2fd->fault_ipa);
+	VM_WARN_ON_ONCE(write_fault && exec_fault);

Should we additionally do

	VM_WARN_ON_ONCE(is_private && kvm_s2_fault_is_perm(s2fd)) ?

We don't expect permission faults on private address coming to KVM.

Quoted 14 lines
arch/arm64/kvm/mmu.c +14 -0
+
+	mmu_seq = kvm->mmu_invalidate_seq;
+	/* Pairs with the smp_wmb() in kvm_mmu_invalidate_end(). */
+	smp_rmb();
+
+	if (is_private != kvm_gmem_is_private_gfn(kvm, gfn)) {
+		kvm_prepare_memory_fault_exit(s2fd->vcpu, gfn_to_gpa(gfn),
+					      PAGE_SIZE, write_fault, exec_fault,
+					      is_private);
+		return -EFAULT;
+	}
+
+	ret = kvm_gmem_get_pfn(kvm, s2fd->memslot, gfn, &pfn, NULL);
+	if (ret) {

arch/arm64/kvm/mmu.c static int gmem_abort(const struct kvm_s2_fault_desc *s2fd, · line 1946

Quoted 10 lines
arch/arm64/kvm/mmu.c +8 -0
+		kvm_prepare_memory_fault_exit(s2fd->vcpu, gfn_to_gpa(gfn),
+					      PAGE_SIZE, write_fault, exec_fault,
+					      is_private);
+		return ret;
+	}
+
 
 
+	if (!(s2fd->memslot->flags & KVM_MEM_READONLY))
+		prot |= KVM_PGTABLE_PROT_W;

We don't support READONLY memslots for Realms (and are rejected at prepare/validate slot) , so we can drop this hunk ?

arch/arm64/kvm/mmu.c static int gmem_abort(const struct kvm_s2_fault_desc *s2fd, · line 1958

Quoted 12 lines
arch/arm64/kvm/mmu.c +12 -0
+
+	kvm_fault_lock(kvm);
+	if (mmu_invalidate_retry(kvm, mmu_seq)) {
+		ret = -EAGAIN;
+	} else {
+		ret = realm_map_ipa(kvm, s2fd->fault_ipa, pfn, PAGE_SIZE,
+				    prot, memcache);
+	}
+	kvm_fault_unlock(kvm);
+
+	if ((prot & KVM_PGTABLE_PROT_W) && !ret)
+		mark_page_dirty_in_slot(kvm, s2fd->memslot, gfn);

Again, for Realms, we don't support DIRTY logging, so we can drop this.

Quoted 41 lines
arch/arm64/kvm/mmu.c +4 -0
+
+	return ret == -EAGAIN ? 0 : ret;
+}
+
  static int protected_pkvm_mem_abort(const struct kvm_s2_fault_desc *s2fd)
  {
  	unsigned int flags = FOLL_HWPOISON | FOLL_LONGTERM | FOLL_WRITE;
arch/arm64/kvm/mmu.c +22 -1
@@ -2050,7 +2120,8 @@ static int kvm_s2_fault_get_vma_info(const struct kvm_s2_fault_desc *s2fd,
  	 * mapping size to ensure we find the right PFN and lay down the
  	 * mapping in the right place.
  	 */
-	s2vi->gfn = ALIGN_DOWN(s2fd->fault_ipa, s2vi->vma_pagesize) >> PAGE_SHIFT;
+	s2vi->gfn = kvm_gfn_from_fault(kvm, ALIGN_DOWN(s2fd->fault_ipa,
+						       s2vi->vma_pagesize));
 
  	s2vi->mte_allowed = kvm_vma_mte_allowed(vma);
 
@@ -2297,8 +2368,67 @@ static int kvm_s2_fault_map(const struct kvm_s2_fault_desc *s2fd,
  	return ret;
  }
 
+static int realm_s2_fault_map(const struct kvm_s2_fault_desc *s2fd,
+			      const struct kvm_s2_fault_vma_info *s2vi,
+			      enum kvm_pgtable_prot prot,
+			      void *memcache,
+			      struct kvm_s2_fault_result *result)
+{
+	struct kvm *kvm = s2fd->vcpu->kvm;
+	bool writable = prot & KVM_PGTABLE_PROT_W;
+	phys_addr_t canonical_ipa = gfn_to_gpa(s2vi->gfn);
+	long mapping_size = s2vi->vma_pagesize;
+	kvm_pfn_t pfn = s2vi->pfn;
+	gfn_t gfn = s2vi->gfn;
+	int ret = -EAGAIN;
+
+	kvm_fault_lock(kvm);
+	if (mmu_invalidate_retry(kvm, s2vi->mmu_seq))
+		goto out_unlock;
+
+	if (mapping_size == PAGE_SIZE && s2vi->max_map_size != PAGE_SIZE) {
+		mapping_size = transparent_hugepage_adjust(s2fd, &pfn, &gfn);

arch/arm64/kvm/mmu.c static int kvm_s2_fault_map(const struct kvm_s2_fault_desc *s2fd, · line 2400

Quoted 10 lines
arch/arm64/kvm/mmu.c +10 -0
+		if (mapping_size < 0) {
+			ret = mapping_size;
+			goto out_unlock;
+		}
+		canonical_ipa = ALIGN_DOWN(canonical_ipa, mapping_size);
+	}
+
+	if (!kvm_s2_fault_is_perm(s2fd) && !s2vi->map_non_cacheable &&
+	    kvm_has_mte(kvm))
+		sanitise_mte_tags(kvm, pfn, mapping_size);

We don't support MTE for Realms, so this can be dropped too ?

arch/arm64/kvm/mmu.c static int kvm_s2_fault_map(const struct kvm_s2_fault_desc *s2fd, · line 2411

Quoted 11 lines
arch/arm64/kvm/mmu.c +11 -0
+
+	ret = realm_map_ipa(kvm, s2fd->fault_ipa, pfn, mapping_size,
+			    prot, memcache);
+
+out_unlock:
+	kvm_release_faultin_page(kvm, s2vi->page, !!ret, writable);
+	kvm_fault_unlock(kvm);
+
+	if (writable && !ret)
+		mark_page_dirty_in_slot(kvm, s2fd->memslot,
+					gpa_to_gfn(canonical_ipa));

Same as above, no dirty logging for Realms

Quoted 11 lines
arch/arm64/kvm/mmu.c +11 -0
+
+	if (ret == -EAGAIN)
+		return result ? ret : 0;
+
+	if (result && !ret)
+		result->mapping_size = mapping_size;
+
+	return ret;
+}
+
+typedef int (*kvm_s2_fault_map_fn)(const struct kvm_s2_fault_desc *s2fd,

arch/arm64/kvm/mmu.c static int kvm_s2_fault_map(const struct kvm_s2_fault_desc *s2fd, · line 2431

Quoted 10 lines
arch/arm64/kvm/mmu.c +8 -1
+				   const struct kvm_s2_fault_vma_info *s2vi,
+				   enum kvm_pgtable_prot prot,
+				   void *memcache,
+				   struct kvm_s2_fault_result *result);
+
  static int user_mem_abort(const struct kvm_s2_fault_desc *s2fd,
-			  struct kvm_s2_fault_result *result)
+			  struct kvm_s2_fault_result *result,
+			  kvm_s2_fault_map_fn fault_map,
+			  bool topup_on_perm_fault)

Do we need the flag ? We could have this deduced in the function locally ? I prefer to have that as we have all the required parameters to decide the option.

More on that below.

Quoted 9 lines
arch/arm64/kvm/mmu.c +1 -1
  {
  	bool perm_fault = kvm_s2_fault_is_perm(s2fd);
  	struct kvm_s2_fault_vma_info s2vi = {};
@@ -2309,15 +2439,16 @@ static int user_mem_abort(const struct kvm_s2_fault_desc *s2fd,
  	/*
  	 * Permission faults just need to update the existing leaf entry,
  	 * and so normally don't require allocations from the memcache. The
-	 * only exception to this is when dirty logging is enabled at runtime
+	 * exceptions are when dirty logging is enabled at runtime

arch/arm64/kvm/mmu.c static int user_mem_abort(const struct kvm_s2_fault_desc *s2fd, · line 2451

Quoted 10 lines
arch/arm64/kvm/mmu.c +2 -1
  	 * and a fault needs to collapse a block entry into a table.
+	 * Realms can also require new RTT levels when replacing a mapping.
  	 * Under pKVM a permission fault can also collapse pages into a block,
  	 * which needs a fresh mapping object, and the hypervisor requires the
  	 * min-pages memcache even when the install allocates nothing.
  	 */
  	memcache = get_mmu_memcache(s2fd->vcpu);
  	if (!perm_fault || memslot_is_logging(s2fd->memslot) ||
-	    is_protected_kvm_enabled()) {
+	    is_protected_kvm_enabled() || topup_on_perm_fault) {

See below for this. It would be good to keep the topup_on_perm_fault next to !perm_fault to make more sense.

Quoted 13 lines
arch/arm64/kvm/mmu.c +1 -1
  		ret = topup_mmu_memcache(s2fd->mmu, memcache);
  		if (ret)
  			return ret;
@@ -2340,7 +2471,7 @@ static int user_mem_abort(const struct kvm_s2_fault_desc *s2fd,
  		return ret;
  	}
 
-	return kvm_s2_fault_map(s2fd, &s2vi, prot, memcache, result);
+	return fault_map(s2fd, &s2vi, prot, memcache, result);
  }
 
  static int kvm_vm_mem_abort(const struct kvm_s2_fault_desc *s2fd)

arch/arm64/kvm/mmu.c static int kvm_vm_mem_abort(const struct kvm_s2_fault_desc *s2fd) · line 2486

Quoted 5 lines
arch/arm64/kvm/mmu.c +1 -1
@@ -2352,7 +2483,25 @@ static int kvm_vm_mem_abort(const struct kvm_s2_fault_desc *s2fd)
  	if (kvm_slot_has_gmem(s2fd->memslot))
  		return gmem_abort(s2fd, NULL);
  	else
-		return user_mem_abort(s2fd, NULL);
+		return user_mem_abort(s2fd, NULL, kvm_s2_fault_map, false);

If we are keeping the flag, should we do something like ?

return user_mem_abort(s2fd, NULL, kvm_s2_fault_map,
is_protected_kvm_enabled());

Quoted 63 lines
arch/arm64/kvm/mmu.c +23 -4
+}
+
+static int __maybe_unused realm_mem_abort(const struct kvm_s2_fault_desc *s2fd)
+{
+	struct kvm *kvm = s2fd->vcpu->kvm;
+
+	VM_WARN_ON_ONCE(kvm_s2_fault_is_perm(s2fd) &&
+			!esr_abt_is_write_fault(s2fd->esr) &&
+			!kvm_s2_fault_is_exec(s2fd));
+
+	if (kvm_realm_is_private_address(&kvm->arch.realm, s2fd->fault_ipa) &&
+	    !kvm_slot_has_gmem(s2fd->memslot))
+		return -EINVAL;
+
+	if (kvm_slot_has_gmem(s2fd->memslot))
+		return realm_gmem_abort(s2fd);
+	else
+		return user_mem_abort(s2fd, NULL, realm_s2_fault_map, true);
  }
 
  /* Resolve the access fault by making the page young again. */
@@ -2461,10 +2610,10 @@ int kvm_handle_guest_sea(struct kvm_vcpu *vcpu)
   */
  int kvm_handle_guest_abort(struct kvm_vcpu *vcpu)
  {
+	struct kvm *kvm = vcpu->kvm;
  	struct kvm_s2_trans nested_trans, *nested = NULL;
  	unsigned long esr = kvm_vcpu_get_esr(vcpu);
  	struct kvm_s2_mmu *mmu = vcpu->arch.hw_mmu;
-	struct kvm *kvm = vcpu->kvm;
  	phys_addr_t fault_ipa; /* The address we faulted on */
  	phys_addr_t ipa; /* Always the IPA in the L1 guest phys space */
  	struct kvm_memory_slot *memslot;
@@ -2557,8 +2706,9 @@ int kvm_handle_guest_abort(struct kvm_vcpu *vcpu)
  		nested = &nested_trans;
  	}
 
-	gfn = ipa >> PAGE_SHIFT;
+	gfn = kvm_gfn_from_fault(kvm, ipa);
  	memslot = gfn_to_memslot(kvm, gfn);
+
  	hva = gfn_to_hva_memslot_prot(memslot, gfn, &writable);
  	write_fault = esr_abt_is_write_fault(esr);
  	if (kvm_is_error_hva(hva) || (write_fault && !writable)) {
@@ -2601,7 +2751,7 @@ int kvm_handle_guest_abort(struct kvm_vcpu *vcpu)
  		 * of the page size.
  		 */
  		ipa |= FAR_TO_FIPA_OFFSET(kvm_vcpu_get_hfar(vcpu));
-		ret = io_mem_abort(vcpu, ipa);
+		ret = io_mem_abort(vcpu, kvm_gpa_from_fault(kvm, ipa));
  		goto out_unlock;
  	}
 
@@ -3124,7 +3274,7 @@ static long __pre_fault_s2(struct kvm_s2_mmu *mmu, struct kvm_vcpu *vcpu,
  	if (is_gmem)
  		ret = gmem_abort(&s2fd, &result);
  	else
-		ret = user_mem_abort(&s2fd, &result);
+		ret = user_mem_abort(&s2fd, &result, kvm_s2_fault_map, false);
  	if (IS_ERR_VALUE(ret))
  		return ret;
  	return result.mapping_size;

arch/arm64/kvm/mmu.c pre_fault_bytes_consumed(gpa_t gpa, unsigned long granule_size, · line 3313

Quoted 5 lines
arch/arm64/kvm/mmu.c +1 -1
@@ -3160,7 +3310,7 @@ pre_fault_bytes_consumed(gpa_t gpa, unsigned long granule_size,
 
  int kvm_arch_pre_fault_allowed(struct kvm_vcpu *vcpu)
  {
-	if (is_protected_kvm_enabled())
+	if (is_protected_kvm_enabled() || kvm_vm_is_realm(vcpu->kvm))

minor nit: kvm_vm_hyp_is_distrusting() ?

Quoted 86 lines
arch/arm64/kvm/mmu.c +0 -0
  		return -EOPNOTSUPP;
  	if (!kvm_vcpu_initialized(vcpu))
  		return -ENOEXEC;
arch/arm64/kvm/rmi.c +75 -0
index b34f5320b50b..ab606a2dc2f5 100644
@@ -593,6 +593,274 @@ void kvm_realm_unmap_range_filter(struct kvm *kvm, unsigned long start,
  	}
  }
 
+static unsigned long addr_range_desc(struct realm *realm,
+				     unsigned long ipa, unsigned long phys,
+				     unsigned long size, unsigned long state)
+{
+	unsigned long count = 1;
+	unsigned long out;
+	int rmi_size;
+
+	for (rmi_size = KVM_PGTABLE_LAST_LEVEL - realm->start_level;
+	     rmi_size >= 0; rmi_size--) {
+		unsigned long entry_size = rmi_addr_block_size_to_bytes(rmi_size);
+
+		if (size >= entry_size && IS_ALIGNED(ipa, entry_size) &&
+		    IS_ALIGNED(phys, entry_size))
+			break;
+	}
+
+	if (rmi_size == 0) {
+		/*
+		 * Stop at the next block boundary so that a later iteration can
+		 * use a larger mapping when both addresses are aligned.
+		 */
+		count = MIN(size >> PAGE_SHIFT, PTRS_PER_PTE - 1);
+		count = min(count, (PMD_SIZE - (ipa & (PMD_SIZE - 1))) >> PAGE_SHIFT);
+		count = min(count, (PMD_SIZE - (phys & (PMD_SIZE - 1))) >> PAGE_SHIFT);
+	}
+
+	WARN_ON(phys & ~PAGE_MASK);
+
+	out = FIELD_PREP(RMI_ADDR_RANGE_BLOCK_SIZE_MASK, rmi_size) |
+	      FIELD_PREP(RMI_ADDR_RANGE_COUNT_MASK, count) |
+	      FIELD_PREP(RMI_ADDR_RANGE_STATE_MASK, state);
+	out |= phys & PAGE_MASK;
+
+	return out;
+}
+
+static int realm_map_protected(struct kvm *kvm,
+			       unsigned long ipa,
+			       kvm_pfn_t pfn,
+			       unsigned long map_size,
+			       struct kvm_mmu_memory_cache *memcache)
+{
+	struct realm *realm = &kvm->arch.realm;
+	phys_addr_t phys = __pfn_to_phys(pfn);
+	phys_addr_t base_phys = phys;
+	phys_addr_t rd = realm->rd_phys;
+	phys_addr_t delegated_phys;
+	unsigned long base_ipa = ipa;
+	unsigned long ipa_top;
+	unsigned int retries = 0;
+	long ret = 0;
+
+	if (WARN_ON(!IS_ALIGNED(map_size, PAGE_SIZE) ||
+		    !IS_ALIGNED(ipa, map_size)))
+		return -EINVAL;
+
+	if (rmi_delegate_range(phys, map_size, &delegated_phys)) {
+		if (delegated_phys == phys) {
+			/*
+			 * It's likely we raced with another VCPU on the same
+			 * fault. Assume the other VCPU has handled the fault
+			 * and return to the guest.
+			 */
+			return 0;
+		}
+		/* Partial delegation - map as much as we can */
+		map_size = delegated_phys - phys;
+	}
+
+	ipa_top = ipa + map_size;
+
+	while (ipa < ipa_top) {
+		unsigned long flags = RMI_ADDR_TYPE_SINGLE;
+		unsigned long range_desc = addr_range_desc(realm, ipa, phys,

arch/arm64/kvm/rmi.c void kvm_realm_unmap_range_filter(struct kvm *kvm, unsigned long start, · line 680

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+							   ipa_top - ipa,
+							   RMI_OP_MEM_DELEGATED);
+		unsigned long call_top = ipa + RMI_ADDR_RANGE_COUNT(range_desc) *
+			rmi_addr_block_size_to_bytes(RMI_ADDR_RANGE_BLOCK_SIZE(range_desc));
+		unsigned long out_top;
+
+		ret = rmi_rtt_data_map(rd, ipa, call_top, flags, range_desc,
+				       &out_top);
+		if (ret < 0)
+			goto err_undelegate;

Should we really err_undelegate here ? This could effectively kill the Realm as unmapping the partial range would leave the IPA in RIPAS_DESTROYED and there is no coming back. I would say, just return
where we completed and come back again if needed.

Quoted 35 lines
arch/arm64/kvm/rmi.c +35 -0
+
+		if (RMI_RESULT_STATUS(ret) == RMI_ERROR_RTT) {
+			/* Create missing RTTs and retry */
+			int level = RMI_RESULT_DATA_LEVEL(ret);
+			int req_level = KVM_PGTABLE_LAST_LEVEL -
+				RMI_ADDR_RANGE_BLOCK_SIZE(range_desc);
+
+			if (++retries > KVM_PGTABLE_LAST_LEVEL + 2 ||
+			    level < realm->start_level || level >= req_level) {
+				ret = -ENXIO;
+				goto err_undelegate;
+			}
+			ret = realm_create_rtt_levels(realm, ipa, level,
+						      req_level,
+						      memcache);
+			if (ret)
+				goto err_undelegate;
+
+			continue;
+		}
+
+		if (ret) {
+			ret = RMI_RESULT_STATUS(ret) == RMI_BLOCKED ? -EAGAIN : -ENXIO;
+			goto err_undelegate;
+		}
+
+		/* An IRQ can stop the RMM before it maps the first entry. */
+		if (out_top == ipa) {
+			ret = -EAGAIN;
+			goto err_undelegate;
+		}
+		if (WARN_ON_ONCE(out_top < ipa || out_top > call_top)) {
+			ret = -ENXIO;
+			goto err_undelegate;
+		}

arch/arm64/kvm/rmi.c void kvm_realm_unmap_range_filter(struct kvm *kvm, unsigned long start, · line 725

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+
+		phys += out_top - ipa;
+		ipa = out_top;
+		retries = 0;
+	}
+
+	return 0;
+
+err_undelegate:
+	realm_unmap_private_range(kvm, base_ipa, ipa, false, memcache);

See above

Quoted 103 lines
arch/arm64/kvm/rmi.c +103 -0
+	/* A range which cannot be undelegated remains owned by the RMM. */
+	WARN_ON(rmi_undelegate_range(base_phys, map_size));
+	return ret < 0 ? ret : -ENXIO;
+}
+
+static int realm_map_unprotected(struct kvm *kvm,
+				 unsigned long ipa,
+				 kvm_pfn_t pfn,
+				 unsigned long size,
+				 enum kvm_pgtable_prot prot,
+				 struct kvm_mmu_memory_cache *memcache)
+{
+	struct realm *realm = &kvm->arch.realm;
+	unsigned long attr, flags = 0;
+	phys_addr_t rd = realm->rd_phys;
+	phys_addr_t phys = __pfn_to_phys(pfn);
+	unsigned long base_ipa = ipa;
+	unsigned long ipa_top = ipa + size;
+	unsigned int retries = 0;
+	long ret;
+
+	if (WARN_ON(!IS_ALIGNED(size, PAGE_SIZE)))
+		return -EINVAL;
+
+	switch (prot & (KVM_PGTABLE_PROT_DEVICE | KVM_PGTABLE_PROT_NORMAL_NC)) {
+	case KVM_PGTABLE_PROT_DEVICE | KVM_PGTABLE_PROT_NORMAL_NC:
+		return -EINVAL;
+	case KVM_PGTABLE_PROT_DEVICE:
+		attr = MT_S2_FWB_DEVICE_nGnRE;
+		break;
+	case KVM_PGTABLE_PROT_NORMAL_NC:
+		attr = MT_S2_FWB_NORMAL_NC;
+		break;
+	default:
+		attr = MT_S2_FWB_NORMAL;
+	}
+
+	flags |= FIELD_PREP(RMI_RTT_UNPROT_MAP_FLAGS_MEMATTR_MASK, attr);
+
+	/*
+	 * An instruction fetch from an unprotected IPA takes a Synchronous
+	 * External Abort in the Realm. KVM never handles an execute permission
+	 * fault for an unprotected mapping.
+	 */
+	if (prot & KVM_PGTABLE_PROT_R)
+		flags |= FIELD_PREP(RMI_RTT_UNPROT_MAP_FLAGS_S2AP_MASK, RMI_S2AP_DIRECT_READ);
+	if (prot & KVM_PGTABLE_PROT_W)
+		flags |= FIELD_PREP(RMI_RTT_UNPROT_MAP_FLAGS_S2AP_MASK, RMI_S2AP_DIRECT_WRITE);
+
+	/* TODO: Batch mappings with RMI_ADDR_TYPE_LIST. */
+	flags |= RMI_ADDR_TYPE_SINGLE;
+
+	while (ipa < ipa_top) {
+		unsigned long range_desc = addr_range_desc(realm, ipa, phys,
+							   ipa_top - ipa,
+							   RMI_OP_MEM_UNDELEGATED);
+		unsigned long call_top = ipa + RMI_ADDR_RANGE_COUNT(range_desc) *
+			rmi_addr_block_size_to_bytes(RMI_ADDR_RANGE_BLOCK_SIZE(range_desc));
+		unsigned long out_top;
+
+		ret = rmi_rtt_unprot_map(rd, ipa, call_top, flags, range_desc,
+					 &out_top);
+		if (ret < 0)
+			goto err_unmap;
+
+		if (ret) {
+			/* Create missing RTTs and retry */
+			int level = RMI_RESULT_DATA_LEVEL(ret);
+			int req_level = KVM_PGTABLE_LAST_LEVEL -
+				RMI_ADDR_RANGE_BLOCK_SIZE(range_desc);
+
+			if (RMI_RESULT_STATUS(ret) != RMI_ERROR_RTT ||
+			    ++retries > KVM_PGTABLE_LAST_LEVEL + 2) {
+				ret = -ENXIO;
+				goto err_unmap;
+			}
+
+			/* Replace an existing mapping to update its permissions. */
+			if (level >= req_level) {
+				realm_unmap_shared_range(kvm, ipa, ipa_top, false,
+							 memcache);
+				continue;
+			}
+
+			ret = realm_create_rtt_levels(realm, ipa, level,
+						      req_level,
+						      memcache);
+			if (ret)
+				goto err_unmap;
+
+			continue;
+		}
+
+		/* Retry the fault after releasing mmu_lock to service the IRQ. */
+		if (out_top == ipa) {
+			ret = -EAGAIN;
+			goto err_unmap;
+		}
+		if (WARN_ON_ONCE(out_top < ipa || out_top > call_top)) {
+			ret = -ENXIO;
+			goto err_unmap;
+		}
+

arch/arm64/kvm/rmi.c void kvm_realm_unmap_range_filter(struct kvm *kvm, unsigned long start, · line 838

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+		phys += out_top - ipa;
+		ipa = out_top;
+		retries = 0;
+	}
+
+	return 0;
+
+err_unmap:
+	/* Earlier iterations may have installed a writable mapping. */
+	realm_unmap_shared_range(kvm, base_ipa, ipa, false, memcache);

Similar to the protected case (though not as fatal), I think we should simply return where we finished, leaving the partial mappings in.

arch/arm64/kvm/rmi.c void kvm_realm_unmap_range_filter(struct kvm *kvm, unsigned long start, · line 850

Quoted 12 lines
arch/arm64/kvm/rmi.c +12 -0
+	return ret;
+}
+
+int realm_map_ipa(struct kvm *kvm, phys_addr_t ipa,
+		  kvm_pfn_t pfn, unsigned long map_size,
+		  enum kvm_pgtable_prot prot,
+		  struct kvm_mmu_memory_cache *memcache)
+{
+	struct realm *realm = &kvm->arch.realm;
+
+	if (kvm_realm_state(kvm) != REALM_STATE_ACTIVE)
+		return -EBUSY;

Nice, we don't want to map anything in when the Realm is not active.

arch/arm64/kvm/rmi.c void kvm_realm_unmap_range_filter(struct kvm *kvm, unsigned long start, · line 861

Quoted 11 lines
arch/arm64/kvm/rmi.c +11 -0
+
+	ipa = ALIGN_DOWN(ipa, map_size);
+	if (!kvm_realm_is_private_address(realm, ipa)) {
+		return realm_map_unprotected(kvm, ipa, pfn, map_size, prot,
+					    memcache);
+	}
+
+	/* It's impossible to map protected pages read-only. */
+	if (WARN_ON(!(prot & KVM_PGTABLE_PROT_W)))
+		return -EFAULT;
+	return realm_map_protected(kvm, ipa, pfn, map_size, memcache);

Suzuki

Quoted 5 lines
arch/arm64/kvm/rmi.c +2 -0
+}
+
  void kvm_destroy_realm(struct kvm *kvm)
  {
  	struct realm *realm = &kvm->arch.realm;
#39 lore raw

Re: [PATCH v4 10/11] KVM: arm64: CCA: Support runtime faulting of memory

Quoted 177 lines · Suzuki K Poulose
Quoted 174 lines · Steven Price

At runtime, if the realm guest accesses an IPA without a stage-2 mapping, then KVM fixes up the stage-2 mapping for the backing memory.

For memory in the lower (protected) region of IPA, verify that the corresponding guest_memfd page is private before delegating to the RMM. The RMM then maps the delegated page into the Realm.

For memory in the upper (shared) IPA region, map the backing page as non-secure memory. Check that a guest_memfd page is shared when the fault uses guest_memfd; ordinary userspace-backed memslots can only be mapped at unprotected IPAs and follow the normal user memory fault path.

If the fault IPA and guest_memfd attributes disagree then exit to userspace with KVM_EXIT_MEMORY_FAULT so the VMM can perform the required conversion. If a shared IPA has no memslot, KVM follows the existing MMIO or abort-injection path. The latter can result in injecting a SEA to the guest.

Realm faults may need to create RTTs, including when updating a mapping after a permission fault. Take the write side of mmu_lock and top up the MMU cache for these faults. Do not pre-fault Realm memory.

The lock helpers are in a header compiled by nVHE too. Make kvm_vm_hyp_is_distrusting() available there for the lock choice.

---
Changes since v3:
- Split Realm faults into dedicated guest_memfd and userspace mapping paths, leaving the native fault paths unchanged.
- Unmap earlier shared mappings if a later RMI map call fails.
- Clarify that runtime RMI data mapping does not guarantee zeroed contents.

Changes since v2:
- Route all guest_memfd faults through gmem_abort(). Bound each protected RMI map call to its encoded range, create the required RTT levels, and tighten retry and error handling.

Changes since v1:
- Use the write side of mmu_lock and top up the MMU cache for Realm faults that may create RTTs. Skip unnecessary cache flushing, disable Realm pre-faulting, and tighten memory-fault and mapping retry handling.
---
  arch/arm64/include/asm/kvm_emulate.h |  13 ++ arch/arm64/include/asm/kvm_host.h    |   4 +- arch/arm64/include/asm/kvm_mmu.h     |   4 +- arch/arm64/include/asm/kvm_rmi.h     |  12 ++ arch/arm64/kvm/mmu.c                 | 174 +++++++++++++++-- arch/arm64/kvm/rmi.c                 | 268 +++++++++++++++++++++++++++

  6 files changed, 459 insertions(+), 16 deletions(-)
arch/arm64/ renamed from arch/arm64/include/asm/kvm_emulate.h +0 -0

include/asm/kvm_emulate.h
index 32021bdf2610..8a71fddfdb85 100644

arch/arm64/include/asm/kvm_emulate.h +0 -0
@@ -847,4 +847,17 @@ static inline bool kvm_realm_is_created(struct
 kvm *kvm)

      return kvm_vm_is_realm(kvm) && kvm_realm_state(kvm) != REALM_STATE_NONE;
  }
  +static inline gpa_t kvm_gpa_from_fault(struct kvm *kvm, phys_addr_t ipa)

arch/arm64/include/asm/kvm_emulate.h +12 -0
+{
+    if (!kvm_vm_is_realm(kvm))
+        return ipa;
+
+    return ipa & ~BIT(kvm->arch.realm.ia_bits - 1);
+}
+
+static inline gfn_t kvm_gfn_from_fault(struct kvm *kvm, phys_addr_t ipa)
+{
+    return gpa_to_gfn(kvm_gpa_from_fault(kvm, ipa));
+}
+

  #endif /* __ARM64_KVM_EMULATE_H__ */

arch/arm64/include/ renamed from arch/arm64/include/asm/kvm_host.h +0 -0

asm/kvm_host.h
index 55673d08e3eb..505c0c5b7dbb 100644

arch/arm64/include/asm/kvm_host.h +0 -0
@@ -1601,12 +1601,12 @@ struct kvm *kvm_arch_alloc_vm(void);
   #define kvm_vm_is_protected(kvm)    ((kvm)->arch.vm_flavor >=
 __VM_PROTECTED)
   #define vcpu_is_protected(vcpu)        kvm_vm_is_protected((vcpu)->kvm)

  -#define kvm_vm_hyp_is_distrusting(kvm)    ((kvm)->arch.vm_flavor >= __VM_DISTRUSTING_HYP)
-
  #endif    /* __KVM_NVHE_HYPERVISOR__ */
    #define kvm_vm_is_realm(kvm)        ((kvm)->arch.vm_flavor == VM_REALM)
  +#define kvm_vm_hyp_is_distrusting(kvm)    ((kvm)->arch.vm_flavor >= __VM_DISTRUSTING_HYP)
+
  #define kvm_arch_has_private_mem(kvm) kvm_vm_is_realm(kvm) #define kvm_has_mte(kvm)                    \

arch/arm64/include/ renamed from arch/arm64/include/asm/kvm_mmu.h +0 -0

asm/kvm_mmu.h
index 32392abf2e21..a70f8bd4b2b9 100644

arch/arm64/include/asm/kvm_mmu.h +1 -1
@@ -371,7 +371,7 @@ static inline bool kvm_is_nested_s2_mmu(struct kvm
 *kvm, struct kvm_s2_mmu *mmu)
     static inline void kvm_fault_lock(struct kvm *kvm)
   {
-    if (is_protected_kvm_enabled())
+    if (kvm_vm_hyp_is_distrusting(kvm))
           write_lock(&kvm->mmu_lock);

      else
          read_lock(&kvm->mmu_lock);

arch/arm64/include/asm/kvm_mmu.h +1 -1
@@ -379,7 +379,7 @@ static inline void kvm_fault_lock(struct kvm *kvm)
     static inline void kvm_fault_unlock(struct kvm *kvm)
   {
-    if (is_protected_kvm_enabled())
+    if (kvm_vm_hyp_is_distrusting(kvm))
           write_unlock(&kvm->mmu_lock);

      else
          read_unlock(&kvm->mmu_lock);

arch/arm64/include/ renamed from arch/arm64/include/asm/kvm_rmi.h +0 -0

asm/kvm_rmi.h
index 8a136fb67318..697964b5b4e4 100644

arch/arm64/include/asm/kvm_rmi.h +0 -0
@@ -6,6 +6,7 @@
   #ifndef __ASM_KVM_RMI_H
   #define __ASM_KVM_RMI_H

  +#include <asm/kvm_pgtable.h>
  #include <linux/arm-smccc-rmi.h>
  #include <linux/kvm.h>
  @@ -90,4 +91,15 @@ void kvm_realm_unmap_range_filter(struct kvm *kvm, bool may_block,
                    enum kvm_gfn_range_filter attr_filter); +int realm_map_ipa(struct kvm *kvm, phys_addr_t ipa,
+          kvm_pfn_t pfn, unsigned long map_size,
+          enum kvm_pgtable_prot prot,
+          struct kvm_mmu_memory_cache *memcache);

arch/arm64/include/asm/kvm_rmi.h +7 -0
+
+static inline bool kvm_realm_is_private_address(struct realm *realm,
+                        unsigned long addr)
+{
+    return !(addr & BIT(realm->ia_bits - 1));
+}
+

  #endif /* __ASM_KVM_RMI_H */

arch/arm64/kvm/mmu.c +0 -0
index 9af5fe6d87f0..870dc7e2699b 100644
@@ -450,6 +450,10 @@ static void stage2_flush_vm(struct kvm *kvm)
       struct kvm_memory_slot *memslot;
       int idx, bkt;

  +    /* The RMM requires FWB, so Realm stage-2 mappings need no cache flush. */
+    if (kvm_vm_is_realm(kvm))
+        return;
+
      idx = srcu_read_lock(&kvm->srcu); write_lock(&kvm->mmu_lock);
  @@ -1225,6 +1229,10 @@ void stage2_unmap_vm(struct kvm *kvm) struct kvm_memory_slot *memslot;
      int idx, bkt;
  +    /* For realms this is handled by the RMM so nothing to do here */ +    if (kvm_vm_is_realm(kvm))
+        return;
+
      idx = srcu_read_lock(&kvm->srcu); mmap_read_lock(current->mm); write_lock(&kvm->mmu_lock);

Quoted 9 lines

arch/arm64/kvm/mmu.c static int gmem_abort(const struct · line 1813

Quoted 7 lines
arch/arm64/kvm/mmu.c +2 -0
@@ -1800,6 +1808,8 @@ static int gmem_abort(const struct
 kvm_s2_fault_desc *s2fd,
           ret = topup_mmu_memcache(s2fd->mmu, memcache);
           if (ret)
               return ret;
+    }
+    if (!perm_fault) {

Spurious change ?

Yes - sorry about that.

Quoted 5 lines
Quoted 5 lines
arch/arm64/kvm/mmu.c +0 -0
           if (kvm_is_nested_s2_mmu(kvm, pgt->mmu)) {
               mapping = kmalloc_obj(struct kvm_guest_s2_mapping,

GFP_KERNEL_ACCOUNT);
              if (!mapping)

arch/arm64/kvm/mmu.c +0 -0
@@ -1808,7 +1818,7 @@ static int gmem_abort(const struct
Quoted 8 lines

arch/arm64/kvm/mmu.c static int gmem_abort(const struct kvm_s2_fault_desc *s2fd, · line 1821

Quoted 6 lines
arch/arm64/kvm/mmu.c +1 -1
 kvm_s2_fault_desc *s2fd,
       }
         s2vi.vma_pagesize = PAGE_SIZE;
-    s2vi.gfn = ALIGN_DOWN(s2fd->fault_ipa, s2vi.vma_pagesize) >>
 PAGE_SHIFT;
+    s2vi.gfn = gpa_to_gfn(s2fd->fault_ipa);

These looks unrelated and could be dropped from this patch

Yep, looks like I screwed up the rebase when moving to a separate realm_gmem_abort().

Quoted 31 lines
Quoted 18 lines
arch/arm64/kvm/mmu.c +11 -0
       canonical_gfn = get_canonical_gfn(s2fd, &s2vi);
         write_fault = kvm_s2_fault_is_write(s2fd);
@@ -1890,6 +1900,66 @@ static int gmem_abort(const struct
 kvm_s2_fault_desc *s2fd,
       return ret;
   }
   +static int realm_gmem_abort(const struct kvm_s2_fault_desc *s2fd)
+{
+    struct kvm *kvm = s2fd->vcpu->kvm;
+    bool write_fault = kvm_s2_fault_is_write(s2fd);
+    bool exec_fault = kvm_s2_fault_is_exec(s2fd);
+    bool is_private;
+    enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_R;
+    kvm_pfn_t pfn;
+    gfn_t gfn;
+    u64 mmu_seq;
+    void *memcache;
+    int ret;

arch/arm64/kvm/mmu.c static int gmem_abort(const struct · line 1924

Quoted 10 lines
arch/arm64/kvm/mmu.c +10 -0
+
+    memcache = get_mmu_memcache(s2fd->vcpu);
+    ret = topup_mmu_memcache(s2fd->mmu, memcache);
+    if (ret)
+        return ret;
+
+    gfn = kvm_gfn_from_fault(kvm, s2fd->fault_ipa);
+    is_private = kvm_realm_is_private_address(&kvm->arch.realm,
+                          s2fd->fault_ipa);
+    VM_WARN_ON_ONCE(write_fault && exec_fault);

Should we additionally do

Quoted 3 lines

    VM_WARN_ON_ONCE(is_private && kvm_s2_fault_is_perm(s2fd)) ?

We don't expect permission faults on private address coming to KVM.

Ack.

Quoted 22 lines
Quoted 21 lines
arch/arm64/kvm/mmu.c +20 -0
+
+    mmu_seq = kvm->mmu_invalidate_seq;
+    /* Pairs with the smp_wmb() in kvm_mmu_invalidate_end(). */
+    smp_rmb();
+
+    if (is_private != kvm_gmem_is_private_gfn(kvm, gfn)) {
+        kvm_prepare_memory_fault_exit(s2fd->vcpu, gfn_to_gpa(gfn),
+                          PAGE_SIZE, write_fault, exec_fault,
+                          is_private);
+        return -EFAULT;
+    }
+
+    ret = kvm_gmem_get_pfn(kvm, s2fd->memslot, gfn, &pfn, NULL);
+    if (ret) {
+        kvm_prepare_memory_fault_exit(s2fd->vcpu, gfn_to_gpa(gfn),
+                          PAGE_SIZE, write_fault, exec_fault,
+                          is_private);
+        return ret;
+    }
+
 
Quoted 5 lines

arch/arm64/kvm/mmu.c static int gmem_abort(const struct kvm_s2_fault_desc *s2fd, · line 1946

Quoted 2 lines
arch/arm64/kvm/mmu.c +2 -0
+    if (!(s2fd->memslot->flags & KVM_MEM_READONLY))
+        prot |= KVM_PGTABLE_PROT_W;

We don't support READONLY memslots for Realms (and are rejected at prepare/validate slot) , so we can drop this hunk ?

Good point.

Quoted 6 lines
Quoted 6 lines
arch/arm64/kvm/mmu.c +6 -0
+
+    kvm_fault_lock(kvm);
+    if (mmu_invalidate_retry(kvm, mmu_seq)) {
+        ret = -EAGAIN;
+    } else {
+        ret = realm_map_ipa(kvm, s2fd->fault_ipa, pfn, PAGE_SIZE,
Quoted 8 lines

arch/arm64/kvm/mmu.c static int gmem_abort(const struct kvm_s2_fault_desc *s2fd, · line 1958

Quoted 6 lines
arch/arm64/kvm/mmu.c +6 -0
+                    prot, memcache);
+    }
+    kvm_fault_unlock(kvm);
+
+    if ((prot & KVM_PGTABLE_PROT_W) && !ret)
+        mark_page_dirty_in_slot(kvm, s2fd->memslot, gfn);

Again, for Realms, we don't support DIRTY logging, so we can drop this.

Ack.

Quoted 46 lines
Quoted 46 lines
arch/arm64/kvm/mmu.c +4 -0
+
+    return ret == -EAGAIN ? 0 : ret;
+}
+

  static int protected_pkvm_mem_abort(const struct kvm_s2_fault_desc *s2fd)
  {
      unsigned int flags = FOLL_HWPOISON | FOLL_LONGTERM | FOLL_WRITE;

arch/arm64/kvm/mmu.c +2 -1
@@ -2050,7 +2120,8 @@ static int kvm_s2_fault_get_vma_info(const
 struct kvm_s2_fault_desc *s2fd,
        * mapping size to ensure we find the right PFN and lay down the
        * mapping in the right place.
        */
-    s2vi->gfn = ALIGN_DOWN(s2fd->fault_ipa, s2vi->vma_pagesize) >>
 PAGE_SHIFT;
+    s2vi->gfn = kvm_gfn_from_fault(kvm, ALIGN_DOWN(s2fd->fault_ipa,
+                               s2vi->vma_pagesize));
         s2vi->mte_allowed = kvm_vma_mte_allowed(vma);

  @@ -2297,8 +2368,67 @@ static int kvm_s2_fault_map(const struct kvm_s2_fault_desc *s2fd,
      return ret;
  }
  +static int realm_s2_fault_map(const struct kvm_s2_fault_desc *s2fd, +                  const struct kvm_s2_fault_vma_info *s2vi, +                  enum kvm_pgtable_prot prot,
+                  void *memcache,
+                  struct kvm_s2_fault_result *result)

arch/arm64/kvm/mmu.c +19 -0
+{
+    struct kvm *kvm = s2fd->vcpu->kvm;
+    bool writable = prot & KVM_PGTABLE_PROT_W;
+    phys_addr_t canonical_ipa = gfn_to_gpa(s2vi->gfn);
+    long mapping_size = s2vi->vma_pagesize;
+    kvm_pfn_t pfn = s2vi->pfn;
+    gfn_t gfn = s2vi->gfn;
+    int ret = -EAGAIN;
+
+    kvm_fault_lock(kvm);
+    if (mmu_invalidate_retry(kvm, s2vi->mmu_seq))
+        goto out_unlock;
+
+    if (mapping_size == PAGE_SIZE && s2vi->max_map_size != PAGE_SIZE) {
+        mapping_size = transparent_hugepage_adjust(s2fd, &pfn, &gfn);
+        if (mapping_size < 0) {
+            ret = mapping_size;
+            goto out_unlock;
+        }
Quoted 8 lines
Quoted 6 lines

+        canonical_ipa = ALIGN_DOWN(canonical_ipa, mapping_size); +    }
+
+    if (!kvm_s2_fault_is_perm(s2fd) && !s2vi->map_non_cacheable && +        kvm_has_mte(kvm))
+        sanitise_mte_tags(kvm, pfn, mapping_size);

We don't support MTE for Realms, so this can be dropped too ?

Ack.

Quoted 5 lines
Quoted 5 lines
arch/arm64/kvm/mmu.c +5 -0
+
+    ret = realm_map_ipa(kvm, s2fd->fault_ipa, pfn, mapping_size,
+                prot, memcache);
+
+out_unlock:
Quoted 8 lines
Quoted 6 lines

+    kvm_release_faultin_page(kvm, s2vi->page, !!ret, writable); +    kvm_fault_unlock(kvm);
+
+    if (writable && !ret)
+        mark_page_dirty_in_slot(kvm, s2fd->memslot,
+                    gpa_to_gfn(canonical_ipa));

Same as above, no dirty logging for Realms

Ack.

Quoted 17 lines
Quoted 17 lines
arch/arm64/kvm/mmu.c +16 -0
+
+    if (ret == -EAGAIN)
+        return result ? ret : 0;
+
+    if (result && !ret)
+        result->mapping_size = mapping_size;
+
+    return ret;
+}
+
+typedef int (*kvm_s2_fault_map_fn)(const struct kvm_s2_fault_desc *s2fd,
+                   const struct kvm_s2_fault_vma_info *s2vi,
+                   enum kvm_pgtable_prot prot,
+                   void *memcache,
+                   struct kvm_s2_fault_result *result);
+

  static int user_mem_abort(const struct kvm_s2_fault_desc *s2fd,

Quoted 8 lines
Quoted 4 lines

-              struct kvm_s2_fault_result *result) +              struct kvm_s2_fault_result *result, +              kvm_s2_fault_map_fn fault_map, +              bool topup_on_perm_fault)

Do we need the flag ? We could have this deduced in the function locally ? I prefer to have that as we have all the required parameters to decide the option.

Good point, I think we can get rid of that.

Quoted 20 lines

More on that below.

Quoted 18 lines

  {
      bool perm_fault = kvm_s2_fault_is_perm(s2fd); struct kvm_s2_fault_vma_info s2vi = {};

arch/arm64/kvm/mmu.c +0 -1
@@ -2309,15 +2439,16 @@ static int user_mem_abort(const struct
 kvm_s2_fault_desc *s2fd,
       /*
        * Permission faults just need to update the existing leaf entry,
        * and so normally don't require allocations from the memcache. The
-     * only exception to this is when dirty logging is enabled at

runtime
+     * exceptions are when dirty logging is enabled at runtime
       * and a fault needs to collapse a block entry into a table. +     * Realms can also require new RTT levels when replacing a mapping.
       * Under pKVM a permission fault can also collapse pages into a block,
       * which needs a fresh mapping object, and the hypervisor requires the
       * min-pages memcache even when the install allocates nothing.

Quoted 8 lines
Quoted 5 lines

       */
      memcache = get_mmu_memcache(s2fd->vcpu);
      if (!perm_fault || memslot_is_logging(s2fd->memslot) || -        is_protected_kvm_enabled()) {
+        is_protected_kvm_enabled() || topup_on_perm_fault) {

See below for this. It would be good to keep the topup_on_perm_fault next to !perm_fault to make more sense.

If we're dropping the flag then this can be replaced with kvm_vm_hyp_is_distrusting().

Quoted 87 lines
Quoted 15 lines

          ret = topup_mmu_memcache(s2fd->mmu, memcache); if (ret)
              return ret;

arch/arm64/kvm/mmu.c +1 -0
@@ -2340,7 +2471,7 @@ static int user_mem_abort(const struct
 kvm_s2_fault_desc *s2fd,
           return ret;
       }
   -    return kvm_s2_fault_map(s2fd, &s2vi, prot, memcache, result);
+    return fault_map(s2fd, &s2vi, prot, memcache, result);
   }
     static int kvm_vm_mem_abort(const struct kvm_s2_fault_desc *s2fd)
@@ -2352,7 +2483,25 @@ static int kvm_vm_mem_abort(const struct
 kvm_s2_fault_desc *s2fd)
       if (kvm_slot_has_gmem(s2fd->memslot))
           return gmem_abort(s2fd, NULL);
Quoted 3 lines

      else
-        return user_mem_abort(s2fd, NULL);
+        return user_mem_abort(s2fd, NULL, kvm_s2_fault_map, false);

If we are keeping the flag, should we do something like ?

 return user_mem_abort(s2fd, NULL, kvm_s2_fault_map, is_protected_kvm_enabled());

Quoted 62 lines
arch/arm64/kvm/mmu.c +3 -0
+}
+
+static int __maybe_unused realm_mem_abort(const struct

kvm_s2_fault_desc *s2fd)

arch/arm64/kvm/mmu.c +8 -0
+{
+    struct kvm *kvm = s2fd->vcpu->kvm;
+
+    VM_WARN_ON_ONCE(kvm_s2_fault_is_perm(s2fd) &&
+            !esr_abt_is_write_fault(s2fd->esr) &&
+            !kvm_s2_fault_is_exec(s2fd));
+
+    if (kvm_realm_is_private_address(&kvm->arch.realm, s2fd-
Quoted 1 line

fault_ipa) &&

+        !kvm_slot_has_gmem(s2fd->memslot))
+        return -EINVAL;
+
+    if (kvm_slot_has_gmem(s2fd->memslot))
+        return realm_gmem_abort(s2fd);
+    else
+        return user_mem_abort(s2fd, NULL, realm_s2_fault_map, true); }
    /* Resolve the access fault by making the page young again. */

arch/arm64/kvm/mmu.c +1 -1
@@ -2461,10 +2610,10 @@ int kvm_handle_guest_sea(struct kvm_vcpu *vcpu)
    */
   int kvm_handle_guest_abort(struct kvm_vcpu *vcpu)
   {
+    struct kvm *kvm = vcpu->kvm;
       struct kvm_s2_trans nested_trans, *nested = NULL;
       unsigned long esr = kvm_vcpu_get_esr(vcpu);
       struct kvm_s2_mmu *mmu = vcpu->arch.hw_mmu;
-    struct kvm *kvm = vcpu->kvm;

      phys_addr_t fault_ipa; /* The address we faulted on */ phys_addr_t ipa; /* Always the IPA in the L1 guest phys space */ struct kvm_memory_slot *memslot;

arch/arm64/kvm/mmu.c +3 -1
@@ -2557,8 +2706,9 @@ int kvm_handle_guest_abort(struct kvm_vcpu *vcpu)
           nested = &nested_trans;
       }
   -    gfn = ipa >> PAGE_SHIFT;
+    gfn = kvm_gfn_from_fault(kvm, ipa);
       memslot = gfn_to_memslot(kvm, gfn);
+
       hva = gfn_to_hva_memslot_prot(memslot, gfn, &writable);
       write_fault = esr_abt_is_write_fault(esr);
       if (kvm_is_error_hva(hva) || (write_fault && !writable)) {
@@ -2601,7 +2751,7 @@ int kvm_handle_guest_abort(struct kvm_vcpu *vcpu)
            * of the page size.
            */
           ipa |= FAR_TO_FIPA_OFFSET(kvm_vcpu_get_hfar(vcpu));
-        ret = io_mem_abort(vcpu, ipa);
+        ret = io_mem_abort(vcpu, kvm_gpa_from_fault(kvm, ipa));
           goto out_unlock;
       }

  @@ -3124,7 +3274,7 @@ static long __pre_fault_s2(struct kvm_s2_mmu *mmu, struct kvm_vcpu *vcpu,
      if (is_gmem)
          ret = gmem_abort(&s2fd, &result);
      else
-        ret = user_mem_abort(&s2fd, &result);
+        ret = user_mem_abort(&s2fd, &result, kvm_s2_fault_map, false); if (IS_ERR_VALUE(ret))
          return ret;
      return result.mapping_size;

Quoted 8 lines

arch/arm64/kvm/mmu.c pre_fault_bytes_consumed(gpa_t gpa, unsigned · line 3313

Quoted 6 lines
arch/arm64/kvm/mmu.c +1 -1
@@ -3160,7 +3310,7 @@ pre_fault_bytes_consumed(gpa_t gpa, unsigned
 long granule_size,
     int kvm_arch_pre_fault_allowed(struct kvm_vcpu *vcpu)
   {
-    if (is_protected_kvm_enabled())
+    if (is_protected_kvm_enabled() || kvm_vm_is_realm(vcpu->kvm))

minor nit: kvm_vm_hyp_is_distrusting() ?

Indeed.

Quoted 98 lines
Quoted 98 lines
arch/arm64/kvm/mmu.c +0 -0
           return -EOPNOTSUPP;
       if (!kvm_vcpu_initialized(vcpu))
           return -ENOEXEC;
arch/arm64/kvm/rmi.c +24 -0
index b34f5320b50b..ab606a2dc2f5 100644
@@ -593,6 +593,274 @@ void kvm_realm_unmap_range_filter(struct kvm
 *kvm, unsigned long start,
       }
   }
   +static unsigned long addr_range_desc(struct realm *realm,
+                     unsigned long ipa, unsigned long phys,
+                     unsigned long size, unsigned long state)
+{
+    unsigned long count = 1;
+    unsigned long out;
+    int rmi_size;
+
+    for (rmi_size = KVM_PGTABLE_LAST_LEVEL - realm->start_level;
+         rmi_size >= 0; rmi_size--) {
+        unsigned long entry_size =
 rmi_addr_block_size_to_bytes(rmi_size);
+
+        if (size >= entry_size && IS_ALIGNED(ipa, entry_size) &&
+            IS_ALIGNED(phys, entry_size))
+            break;
+    }
+
+    if (rmi_size == 0) {
+        /*
+         * Stop at the next block boundary so that a later iteration can
+         * use a larger mapping when both addresses are aligned.
+         */
+        count = MIN(size >> PAGE_SHIFT, PTRS_PER_PTE - 1);
+        count = min(count, (PMD_SIZE - (ipa & (PMD_SIZE - 1))) >>
 PAGE_SHIFT);
+        count = min(count, (PMD_SIZE - (phys & (PMD_SIZE - 1))) >>

PAGE_SHIFT);
+    }

arch/arm64/kvm/rmi.c +52 -0
+
+    WARN_ON(phys & ~PAGE_MASK);
+
+    out = FIELD_PREP(RMI_ADDR_RANGE_BLOCK_SIZE_MASK, rmi_size) |
+          FIELD_PREP(RMI_ADDR_RANGE_COUNT_MASK, count) |
+          FIELD_PREP(RMI_ADDR_RANGE_STATE_MASK, state);
+    out |= phys & PAGE_MASK;
+
+    return out;
+}
+
+static int realm_map_protected(struct kvm *kvm,
+                   unsigned long ipa,
+                   kvm_pfn_t pfn,
+                   unsigned long map_size,
+                   struct kvm_mmu_memory_cache *memcache)
+{
+    struct realm *realm = &kvm->arch.realm;
+    phys_addr_t phys = __pfn_to_phys(pfn);
+    phys_addr_t base_phys = phys;
+    phys_addr_t rd = realm->rd_phys;
+    phys_addr_t delegated_phys;
+    unsigned long base_ipa = ipa;
+    unsigned long ipa_top;
+    unsigned int retries = 0;
+    long ret = 0;
+
+    if (WARN_ON(!IS_ALIGNED(map_size, PAGE_SIZE) ||
+            !IS_ALIGNED(ipa, map_size)))
+        return -EINVAL;
+
+    if (rmi_delegate_range(phys, map_size, &delegated_phys)) {
+        if (delegated_phys == phys) {
+            /*
+             * It's likely we raced with another VCPU on the same
+             * fault. Assume the other VCPU has handled the fault
+             * and return to the guest.
+             */
+            return 0;
+        }
+        /* Partial delegation - map as much as we can */
+        map_size = delegated_phys - phys;
+    }
+
+    ipa_top = ipa + map_size;
+
+    while (ipa < ipa_top) {
+        unsigned long flags = RMI_ADDR_TYPE_SINGLE;
+        unsigned long range_desc = addr_range_desc(realm, ipa, phys,
+                               ipa_top - ipa,
+                               RMI_OP_MEM_DELEGATED);
+        unsigned long call_top = ipa +

RMI_ADDR_RANGE_COUNT(range_desc) *
+ rmi_addr_block_size_to_bytes(RMI_ADDR_RANGE_BLOCK_SIZE(range_desc)); +        unsigned long out_top;
+
+        ret = rmi_rtt_data_map(rd, ipa, call_top, flags, range_desc,

Quoted 8 lines
Quoted 3 lines

+                       &out_top);
+        if (ret < 0)
+            goto err_undelegate;

Should we really err_undelegate here ? This could effectively kill the Realm as unmapping the partial range would leave the IPA in RIPAS_DESTROYED and there is no coming back. I would say, just return where we completed and come back again if needed.

The undelegate is correct, the unmap below is the issue.

Quoted 40 lines
Quoted 40 lines
arch/arm64/kvm/rmi.c +23 -0
+
+        if (RMI_RESULT_STATUS(ret) == RMI_ERROR_RTT) {
+            /* Create missing RTTs and retry */
+            int level = RMI_RESULT_DATA_LEVEL(ret);
+            int req_level = KVM_PGTABLE_LAST_LEVEL -
+                RMI_ADDR_RANGE_BLOCK_SIZE(range_desc);
+
+            if (++retries > KVM_PGTABLE_LAST_LEVEL + 2 ||
+                level < realm->start_level || level >= req_level) {
+                ret = -ENXIO;
+                goto err_undelegate;
+            }
+            ret = realm_create_rtt_levels(realm, ipa, level,
+                              req_level,
+                              memcache);
+            if (ret)
+                goto err_undelegate;
+
+            continue;
+        }
+
+        if (ret) {
+            ret = RMI_RESULT_STATUS(ret) == RMI_BLOCKED ? -EAGAIN : -

ENXIO;
+            goto err_undelegate;
+        }

arch/arm64/kvm/rmi.c +14 -0
+
+        /* An IRQ can stop the RMM before it maps the first entry. */
+        if (out_top == ipa) {
+            ret = -EAGAIN;
+            goto err_undelegate;
+        }
+        if (WARN_ON_ONCE(out_top < ipa || out_top > call_top)) {
+            ret = -ENXIO;
+            goto err_undelegate;
+        }
+
+        phys += out_top - ipa;
+        ipa = out_top;
+        retries = 0;
Quoted 8 lines

arch/arm64/kvm/rmi.c void kvm_realm_unmap_range_filter(struct kvm *kvm, unsigned long start, · line 725

Quoted 6 lines

+    }

arch/arm64/kvm/rmi.c +5 -0
+
+    return 0;
+
+err_undelegate:
+    realm_unmap_private_range(kvm, base_ipa, ipa, false, memcache);

See above

Yes I agree there's not much point trying to roll back - obviously the below undelegate also needs fixing up to only undelegate the failed part.

Quoted 115 lines
Quoted 115 lines

+    /* A range which cannot be undelegated remains owned by the RMM. */ +    WARN_ON(rmi_undelegate_range(base_phys, map_size));
+    return ret < 0 ? ret : -ENXIO;

arch/arm64/kvm/rmi.c +22 -0
+}
+
+static int realm_map_unprotected(struct kvm *kvm,
+                 unsigned long ipa,
+                 kvm_pfn_t pfn,
+                 unsigned long size,
+                 enum kvm_pgtable_prot prot,
+                 struct kvm_mmu_memory_cache *memcache)
+{
+    struct realm *realm = &kvm->arch.realm;
+    unsigned long attr, flags = 0;
+    phys_addr_t rd = realm->rd_phys;
+    phys_addr_t phys = __pfn_to_phys(pfn);
+    unsigned long base_ipa = ipa;
+    unsigned long ipa_top = ipa + size;
+    unsigned int retries = 0;
+    long ret;
+
+    if (WARN_ON(!IS_ALIGNED(size, PAGE_SIZE)))
+        return -EINVAL;
+
+    switch (prot & (KVM_PGTABLE_PROT_DEVICE |

KVM_PGTABLE_PROT_NORMAL_NC)) {
+    case KVM_PGTABLE_PROT_DEVICE | KVM_PGTABLE_PROT_NORMAL_NC:
+        return -EINVAL;
+    case KVM_PGTABLE_PROT_DEVICE:
+        attr = MT_S2_FWB_DEVICE_nGnRE;
+        break;
+    case KVM_PGTABLE_PROT_NORMAL_NC:
+        attr = MT_S2_FWB_NORMAL_NC;
+        break;
+    default:
+        attr = MT_S2_FWB_NORMAL;
+    }

arch/arm64/kvm/rmi.c +6 -0
+
+    flags |= FIELD_PREP(RMI_RTT_UNPROT_MAP_FLAGS_MEMATTR_MASK, attr);
+
+    /*
+     * An instruction fetch from an unprotected IPA takes a Synchronous
+     * External Abort in the Realm. KVM never handles an execute

permission
+     * fault for an unprotected mapping.
+     */
+    if (prot & KVM_PGTABLE_PROT_R)
+        flags |= FIELD_PREP(RMI_RTT_UNPROT_MAP_FLAGS_S2AP_MASK, RMI_S2AP_DIRECT_READ);
+    if (prot & KVM_PGTABLE_PROT_W)
+        flags |= FIELD_PREP(RMI_RTT_UNPROT_MAP_FLAGS_S2AP_MASK, RMI_S2AP_DIRECT_WRITE);

arch/arm64/kvm/rmi.c +9 -0
+
+    /* TODO: Batch mappings with RMI_ADDR_TYPE_LIST. */
+    flags |= RMI_ADDR_TYPE_SINGLE;
+
+    while (ipa < ipa_top) {
+        unsigned long range_desc = addr_range_desc(realm, ipa, phys,
+                               ipa_top - ipa,
+                               RMI_OP_MEM_UNDELEGATED);
+        unsigned long call_top = ipa +

RMI_ADDR_RANGE_COUNT(range_desc) *
+ rmi_addr_block_size_to_bytes(RMI_ADDR_RANGE_BLOCK_SIZE(range_desc)); +        unsigned long out_top;

arch/arm64/kvm/rmi.c +35 -0
+
+        ret = rmi_rtt_unprot_map(rd, ipa, call_top, flags, range_desc,
+                     &out_top);
+        if (ret < 0)
+            goto err_unmap;
+
+        if (ret) {
+            /* Create missing RTTs and retry */
+            int level = RMI_RESULT_DATA_LEVEL(ret);
+            int req_level = KVM_PGTABLE_LAST_LEVEL -
+                RMI_ADDR_RANGE_BLOCK_SIZE(range_desc);
+
+            if (RMI_RESULT_STATUS(ret) != RMI_ERROR_RTT ||
+                ++retries > KVM_PGTABLE_LAST_LEVEL + 2) {
+                ret = -ENXIO;
+                goto err_unmap;
+            }
+
+            /* Replace an existing mapping to update its permissions. */
+            if (level >= req_level) {
+                realm_unmap_shared_range(kvm, ipa, ipa_top, false,
+                             memcache);
+                continue;
+            }
+
+            ret = realm_create_rtt_levels(realm, ipa, level,
+                              req_level,
+                              memcache);
+            if (ret)
+                goto err_unmap;
+
+            continue;
+        }
+
+        /* Retry the fault after releasing mmu_lock to service the

IRQ. */
+        if (out_top == ipa) {
+            ret = -EAGAIN;
+            goto err_unmap;
+        }
+        if (WARN_ON_ONCE(out_top < ipa || out_top > call_top)) { +            ret = -ENXIO;
+            goto err_unmap;
+        }

arch/arm64/kvm/rmi.c +6 -0
+
+        phys += out_top - ipa;
+        ipa = out_top;
+        retries = 0;
+    }
+
Quoted 8 lines

arch/arm64/kvm/rmi.c void kvm_realm_unmap_range_filter(struct kvm *kvm, unsigned long start, · line 838

Quoted 5 lines

+    return 0;

arch/arm64/kvm/rmi.c +4 -0
+
+err_unmap:
+    /* Earlier iterations may have installed a writable mapping. */
+    realm_unmap_shared_range(kvm, base_ipa, ipa, false, memcache);

Similar to the protected case (though not as fatal), I think we should simply return where we finished, leaving the partial mappings in.

Yep. This also cleans up the error paths as we no longer need the gotos
- nice!

Thanks,
Steve

Quoted 36 lines

arch/arm64/kvm/rmi.c void kvm_realm_unmap_range_filter(struct kvm *kvm, unsigned long start, · line 850

Quoted 12 lines

+    return ret;

arch/arm64/kvm/rmi.c +11 -0
+}
+
+int realm_map_ipa(struct kvm *kvm, phys_addr_t ipa,
+          kvm_pfn_t pfn, unsigned long map_size,
+          enum kvm_pgtable_prot prot,
+          struct kvm_mmu_memory_cache *memcache)
+{
+    struct realm *realm = &kvm->arch.realm;
+
+    if (kvm_realm_state(kvm) != REALM_STATE_ACTIVE)
+        return -EBUSY;

Nice, we don't want to map anything in when the Realm is not active.

arch/arm64/kvm/rmi.c void kvm_realm_unmap_range_filter(struct kvm *kvm, unsigned long start, · line 861

Quoted 11 lines
arch/arm64/kvm/rmi.c +11 -0
+
+    ipa = ALIGN_DOWN(ipa, map_size);
+    if (!kvm_realm_is_private_address(realm, ipa)) {
+        return realm_map_unprotected(kvm, ipa, pfn, map_size, prot,
+                        memcache);
+    }
+
+    /* It's impossible to map protected pages read-only. */
+    if (WARN_ON(!(prot & KVM_PGTABLE_PROT_W)))
+        return -EFAULT;
+    return realm_map_protected(kvm, ipa, pfn, map_size, memcache);

Suzuki

Quoted 5 lines
arch/arm64/kvm/rmi.c +2 -0
+}
+

  void kvm_destroy_realm(struct kvm *kvm)
  {
      struct realm *realm = &kvm->arch.realm;

#40 lore raw

PATCH v4 11/11 KVM: arm64: CCA: Add Realm stage-2 MMU operations

In reply to Steven Price

From: Suzuki K Poulose <[email protected]>

Register the Realm stage-2 MMU operations now that the RMM mapping and unmapping helpers are available. Route unmapping through the RMM, and use the Realm-specific fault handler for Realm memory faults.

The RMM handles TLB invalidation when stage-2 mappings change, so the host has no separate TLB flush to perform. Realm stage-2 does not support access flags, including for shared IPAs.

Realm teardown destroys non-root RTTs through RMI, so the Realm stage-2 destruction callback frees only the root RTT pages.

---
Changes since v3:
- Register realm_mem_abort() as the Realm stage-2 fault handler.

Changes since v2:
- Move common stage-2 destruction dispatch to a separate patch; retain the Realm-specific destruction callback here.

---
 arch/arm64/kvm/mmu.c | 47 ++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 45 insertions(+), 2 deletions(-)
arch/arm64/kvm/mmu.c +45 -2
index 870dc7e2699b..274dfe8ea364 100644
@@ -191,6 +191,12 @@ static int kvm_vm_flush_remote_tlbs(struct kvm *kvm)
 	return 0;
 }
 
+static int realm_flush_remote_tlbs(struct kvm *kvm)
+{
+	/* Nothing to do here, RMM does the job */
+	return 0;
+}
+
 /**
  * kvm_arch_flush_remote_tlbs() - flush all VM TLB entries for v7/8
  * @kvm:	pointer to kvm structure.
@@ -218,6 +224,13 @@ static int kvm_vm_flush_remote_tlbs_range(struct kvm *kvm,
 	return 0;
 }
 
+static int realm_flush_remote_tlbs_range(struct kvm *kvm,
+					 gfn_t gfn, u64 nr_pages)
+{
+	/* Nothing to do here, RMM does the job */
+	return 0;
+}
+
 int kvm_arch_flush_remote_tlbs_range(struct kvm *kvm,
 				     gfn_t gfn, u64 nr_pages)
 {
@@ -353,6 +366,15 @@ static void no_stage2_unmap_range(struct kvm_s2_mmu *mmu,
 {
 }
 
+static void realm_stage2_unmap_range(struct kvm_s2_mmu *mmu,
+				     phys_addr_t start, u64 size, bool may_block,
+				     enum kvm_gfn_range_filter filter)
+{
+	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
+
+	kvm_realm_unmap_range_filter(kvm, start, size, may_block, filter);
+}
+
 /*
  * Unmapping vs dcache management:
  *
@@ -1054,6 +1076,17 @@ static void pkvm_stage2_destroy(struct kvm_pgtable *pgt)
 	pkvm_pgtable_stage2_destroy_pgd(pgt);
 }
 
+static void realm_stage2_destroy(struct kvm_pgtable *pgt)
+{
+	/*
+	 * Realm RTTs are inaccessible to the host and may contain stale data
+	 * after the RMM has released them. The non-root RTTs are explicitly
+	 * destroyed through RMI before the RD is destroyed; only the root PGD
+	 * pages remain to be freed here.
+	 */
+	kvm_pgtable_stage2_destroy_pgd(pgt);
+}
+
 static void kvm_stage2_destroy(struct kvm_pgtable *pgt)
 {
 	struct kvm *kvm = kvm_s2_mmu_to_kvm(pgt->mmu);
@@ -2486,7 +2519,7 @@ static int kvm_vm_mem_abort(const struct kvm_s2_fault_desc *s2fd)
 		return user_mem_abort(s2fd, NULL, kvm_s2_fault_map, false);
 }
 
-static int __maybe_unused realm_mem_abort(const struct kvm_s2_fault_desc *s2fd)
+static int realm_mem_abort(const struct kvm_s2_fault_desc *s2fd)
 {
 	struct kvm *kvm = s2fd->vcpu->kvm;
 
@@ -3389,6 +3422,16 @@ static const struct kvm_vm_s2_ops kvm_default_vm_s2_ops = {
 	.vm_mem_abort			= kvm_vm_mem_abort,
 };
 
+static const struct kvm_vm_s2_ops realm_vm_s2_ops = {
+	.vm_stage2_destroy		= realm_stage2_destroy,
+	.vm_flush_remote_tlbs		= realm_flush_remote_tlbs,
+	.vm_flush_remote_tlbs_range	= realm_flush_remote_tlbs_range,
+	.vm_age_gfn			= no_age_gfn,
+	.vm_test_age_gfn		= no_age_gfn,
+	.vm_stage2_unmap_range		= realm_stage2_unmap_range,
+	.vm_mem_abort			= realm_mem_abort,
+};
+
 #define KVM_VM_S2_OPS(flavor, ops)		\
 		[(flavor)] = &(ops)
 
@@ -3397,7 +3440,7 @@ static const struct kvm_vm_s2_ops *arm64_vm_s2_ops[] = {
 	KVM_VM_S2_OPS(VM_NVHE, kvm_default_vm_s2_ops),
 	KVM_VM_S2_OPS(VM_PKVM, pkvm_vm_s2_ops),
 	KVM_VM_S2_OPS(VM_PROTECTED_PKVM, protected_pkvm_vm_s2_ops),
-	[VM_REALM] = NULL,
+	KVM_VM_S2_OPS(VM_REALM, realm_vm_s2_ops),
 };
 
 static int kvm_vm_init_vm_s2_ops(struct kvm *kvm)
Signature · 1 line
2.43.0
Tested-by on the v4 series
#41 lore raw
In reply to Steven Price
Quoted 10 lines · Steven Price

This series adds the memory management plumbing for CCA, building on the basic RMM support [1]. Thanks to everyone who reviewed and tested the earlier versions.

The patches introduce internal Realm VM state, prepare Realm stage-2 setup and teardown, and provide RTT mapping and invalidation helpers. Realm memslots are restricted to the lower half of the IPA space because the protected and shared halves alias each other. The final patch connects the helpers to KVM's stage-2 MMU operations.

Quoted 8 lines

This is the memory management portion of the larger Realm host series. Realm descriptor creation, REC entry and exit, activation, and the new uAPI follow in the integration stack. This series alone does not enable Realm creation.

The integration branch [2] includes Realm creation, REC entry and exit, and the remaining host support on top of this series. The MM branch [3] contains just this series.

Hi Steve,

I tested the v4 integration branch in the same way as described in the following thread, and I haven't seen any issues so far:
https://lore.kernel.org/all/[email protected]/

For the series:

Thanks,
Kohei

#42 lore raw
Quoted 16 lines · Kohei Enju
Quoted 15 lines · Steven Price

This series adds the memory management plumbing for CCA, building on the basic RMM support [1]. Thanks to everyone who reviewed and tested the earlier versions.

The patches introduce internal Realm VM state, prepare Realm stage-2 setup and teardown, and provide RTT mapping and invalidation helpers. Realm memslots are restricted to the lower half of the IPA space because the protected and shared halves alias each other. The final patch connects the helpers to KVM's stage-2 MMU operations.

This is the memory management portion of the larger Realm host series. Realm descriptor creation, REC entry and exit, activation, and the new uAPI follow in the integration stack. This series alone does not enable Realm creation.

Quoted 5 lines
Quoted 3 lines

The integration branch [2] includes Realm creation, REC entry and exit, and the remaining host support on top of this series. The MM branch [3] contains just this series.

Hi Steve,

Hi Kohei,

Quoted 6 lines

I tested the v4 integration branch in the same way as described in the following thread, and I haven't seen any issues so far:
https://lore.kernel.org/all/[email protected]/

For the series:

Thanks as always for the testing!

Regards,
Steve

Quoted 2 lines

Thanks,
Kohei