Skip to contentSkip to conversation

arm64: Support for Arm CCA in KVM

PATCH Superseded Steven Price 5 participants 89 messages Jul 15 – Aug 4

Subsystems (4)

v15 of 16 Superseded Latest is v16 →

lore
Share & tools
lore
#0 lore raw

v15 cover arm64: Support for Arm CCA in KVM

This series adds support for running protected VMs using KVM under the Arm Confidential Compute Architecture (CCA).

It is the second part of the Arm CCA host support that was previously posted as a single 44-patch series. The generic firmware/RMM support has now been split into a separate 6-patch base series[0] so that it can also be used by other work (and hopefully make reviewing a little easier). This series applies on top of that base.

This is rebased on v7.2-rc1 and targets RMM v2.0-bet2[1].

The main changes since v14 are:

* The RMI definitions and wrappers have been updated for RMM v2.0-bet2. One bet2 change, which moves metadata out of the individual address range descriptors, has intentionally not been implemented because that part of the spec is expected to be reverted.

* The generic RMI code has been split out into the preceding firmware/RMM series. Common definitions and helpers are in include/linux/arm-smccc-rmi.h and include/linux/arm-rmi-cmds.h, with the KVM-specific wrappers left under arch/arm64.

* SRO handling has been reworked to match the new layout. Wrappers for SRO-based RMI commands live with the SRO infrastructure, range delegate/undelegate use the stateful command infrastructure, BUSY and BLOCKED polling now calls cpu_relax(), and realm creation uses the SRO flow.

* PSCI completion has been updated for the RMM v2.0-bet2 flow, which no longer requires the host to pass the target REC to RMI_PSCI_COMPLETE.

* Realm creation has been adapted to the v2.0-bet2 realm parameter layout, including explicit SHA-256 selection and SRO-based realm creation.

* RTT teardown is now serialized under config_lock and is idempotent.

* KVM_ARM_RMI_POPULATE now takes slots_lock and config_lock higher in the call path, adds lockdep assertions in the lower helpers, and checks for overflow in the userspace-provided range.

* RMI_EXIT_RIPAS_CHANGE handling now uses addition rather than bitwise OR when adding the shared bit, so ranges ending at the last address are handled correctly.

* The RMI feature checks now support selecting the feature register to query and validate that the default SHA-256 hash algorithm is available.

* Patch subjects have been renamed to use firmware: arm_rmm for the generic RMI layer and KVM: arm64: CCA for the KVM realm support.

There are also the usual rebase updates and smaller fixes.

The RMM v2.0 spec introduces Stateful RMI Operations (SROs), which allow the RMM to complete an operation over several SMC calls while requesting or returning memory to the host. This allows interrupts to be handled in the middle of an operation and lets the RMM dynamically allocate memory for internal tracking purposes. For example, RMI_REC_CREATE no longer needs auxiliary granules to be provided up front, and can instead request memory during the operation.

The SRO infrastructure itself is provided by the prerequisite firmware/RMM series. This KVM series uses that infrastructure for the RMI operations which can complete statefully, including realm creation, RMM activation, GPT creation and range delegate/undelegate.

This series is based on v7.2-rc1 and Ackerley's guest_memfd in-place series. It is also available as a git repository:

https://gitlab.arm.com/linux-arm/linux-cca cca-host/v15

Work in progress changes for kvmtool are available from the git repository below:

https://gitlab.arm.com/linux-arm/kvmtool-cca cca/v13

The TF-RMM has now merged most of the RMM v2.0 support needed by this series. The remaining PSCI changes have not yet merged; for testing those changes are available in the following TF-RMM branch:

https://git.trustedfirmware.org/TF-RMM/tf-rmm.git topics/rmm-v2.0-poc_3

There is a kvm-unit-test branch which has been updated to support the attestation used in RMM v2.0 available here:

https://gitlab.arm.com/linux-arm/kvm-unit-tests-cca cca/v4

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

[1] https://developer.arm.com/documentation/den0137/2-0bet2/
Note that one bet2 change, which moves metadata out of the individual address range descriptors, has intentionally not been implemented because that part of the spec is expected to be reverted.

Jean-Philippe Brucker (6):
KVM: arm64: CCA: Propagate breakpoint and watchpoint counts to
userspace
KVM: arm64: CCA: Set breakpoint parameters through SET_ONE_REG
KVM: arm64: CCA: Propagate max SVE vector length from the RMM
KVM: arm64: CCA: Configure max SVE vector length for a Realm
KVM: arm64: CCA: Provide register list for unfinalized RECs
KVM: arm64: CCA: Provide an accurate register list

Joey Gouly (2):
KVM: arm64: CCA: Allow userspace to inject aborts
KVM: arm64: CCA: Support RSI_HOST_CALL

Steven Price (26):
KVM: arm64: Avoid including linux/kvm_host.h in kvm_pgtable.h
arm64: mm: Handle Granule Protection Faults (GPFs)
KVM: arm64: CCA: Check for RMI support at KVM init
KVM: arm64: CCA: Check for LPA2 support
KVM: arm64: CCA: Define the user ABI
KVM: arm64: CCA: Add basic infrastructure for creating a realm
KVM: arm64: CCA: Allow passing the machine type in KVM creation
KVM: arm64: CCA: Tear down RTTs
KVM: arm64: CCA: Allocate and free RECs to match vCPUs
KVM: arm64: CCA: Support the VGIC in realms
KVM: arm64: CCA: Support timers in realm RECs
KVM: arm64: CCA: Handle realm enter/exit
KVM: arm64: CCA: Handle RMI_EXIT_RIPAS_CHANGE
KVM: arm64: CCA: Handle realm MMIO emulation
KVM: arm64: Expose support for private memory
KVM: arm64: CCA: Create the realm descriptor
KVM: arm64: CCA: Activate realms on first vCPU run
KVM: arm64: CCA: Allow populating initial contents
KVM: arm64: CCA: Set RIPAS of initial memslots
KVM: arm64: CCA: Support runtime faulting of memory
KVM: arm64: CCA: Handle realm vCPU load
KVM: arm64: CCA: Validate register access for Realm VMs
KVM: arm64: CCA: Handle Realm PSCI requests
KVM: arm64: WARN on injected undef exceptions
KVM: arm64: CCA: Prevent Device mappings for realms
KVM: arm64: CCA: Enable realms to be created

Suzuki K Poulose (3):
KVM: arm64: Include kvm_emulate.h in kvm/arm_psci.h
KVM: arm64: CCA: Don't expose unsupported capabilities for realm
guests
KVM: arm64: CCA: Allow checking SVE on VM instance

 Documentation/virt/kvm/api.rst       |   61 +-
 arch/arm64/include/asm/kvm_emulate.h |   37 +
 arch/arm64/include/asm/kvm_host.h    |   11 +-
 arch/arm64/include/asm/kvm_pgtable.h |    6 +-
 arch/arm64/include/asm/kvm_pkvm.h    |    2 +-
 arch/arm64/include/asm/kvm_rmi.h     |  136 +++
 arch/arm64/include/asm/virt.h        |    1 +
 arch/arm64/kvm/Kconfig               |    2 +
 arch/arm64/kvm/Makefile              |    2 +-
 arch/arm64/kvm/arch_timer.c          |   38 +-
 arch/arm64/kvm/arm.c                 |  140 ++-
 arch/arm64/kvm/guest.c               |   93 +-
 arch/arm64/kvm/hyp/pgtable.c         |    1 +
 arch/arm64/kvm/hypercalls.c          |    4 +-
 arch/arm64/kvm/inject_fault.c        |    5 +-
 arch/arm64/kvm/mmio.c                |   16 +-
 arch/arm64/kvm/mmu.c                 |  144 ++-
 arch/arm64/kvm/psci.c                |   14 +
 arch/arm64/kvm/reset.c               |   13 +-
 arch/arm64/kvm/rmi-exit.c            |  212 ++++
 arch/arm64/kvm/rmi.c                 | 1523 ++++++++++++++++++++++++++
 arch/arm64/kvm/sys_regs.c            |   47 +-
 arch/arm64/kvm/vgic/vgic-init.c      |    2 +-
 arch/arm64/mm/fault.c                |   28 +-
 include/kvm/arm_arch_timer.h         |    2 +
 include/kvm/arm_psci.h               |    2 +
 include/uapi/linux/kvm.h             |   20 +-
 27 files changed, 2466 insertions(+), 96 deletions(-)
 create mode 100644 arch/arm64/include/asm/kvm_rmi.h
 create mode 100644 arch/arm64/kvm/rmi-exit.c
 create mode 100644 arch/arm64/kvm/rmi.c
Signature · 1 line
2.43.0
#1 lore raw

PATCH v15 1/37 KVM: arm64: Include kvm_emulate.h in kvm/arm_psci.h

From: Suzuki K Poulose <[email protected]>

Fix a potential build error (like below, when asm/kvm_emulate.h gets included after the kvm/arm_psci.h) by including the missing header file in kvm/arm_psci.h:

./include/kvm/arm_psci.h: In function ‘kvm_psci_version’:
./include/kvm/arm_psci.h:29:13: error: implicit declaration of function
‘vcpu_has_feature’; did you mean ‘cpu_have_feature’? [-Werror=implicit-function-declaration]

   29 |         if (vcpu_has_feature(vcpu, KVM_ARM_VCPU_PSCI_0_2)) {
	         |             ^~~~~~~~~~~~~~~~
			       |             cpu_have_feature
---
 include/kvm/arm_psci.h | 2 ++
 1 file changed, 2 insertions(+)
include/kvm/arm_psci.h +2 -0
index cbaec804eb83..38dab7add79b 100644
@@ -10,6 +10,8 @@
 #include <linux/kvm_host.h>
 #include <uapi/linux/psci.h>
 
+#include <asm/kvm_emulate.h>
+
 #define KVM_ARM_PSCI_0_1	PSCI_VERSION(0, 1)
 #define KVM_ARM_PSCI_0_2	PSCI_VERSION(0, 2)
 #define KVM_ARM_PSCI_1_0	PSCI_VERSION(1, 0)
Signature · 1 line
2.43.0
#2 lore raw

PATCH v15 2/37 KVM: arm64: Avoid including linux/kvm_host.h in kvm_pgtable.h

In reply to Steven Price

To avoid future include cycles, drop the linux/kvm_host.h include in kvm_pgtable.h and include the lightweight headers required for the types and inline helpers used there. Additionally provide a forward declaration for struct kvm_s2_mmu as it's only used as a pointer in this file.

Both pgtable.c and kvm_pkvm.h relied on the indirect inclusion of kvm_host.h, so make that explicit.

---
New patch in v13

---
 arch/arm64/include/asm/kvm_pgtable.h | 6 +++++-
 arch/arm64/include/asm/kvm_pkvm.h    | 2 +-
 arch/arm64/kvm/hyp/pgtable.c         | 1 +
 3 files changed, 7 insertions(+), 2 deletions(-)
arch/arm64/include/asm/kvm_pgtable.h +5 -1
index 41a8687938eb..c2e4b29e605f 100644
@@ -8,9 +8,13 @@
 #define __ARM64_KVM_PGTABLE_H__
 
 #include <linux/bits.h>
-#include <linux/kvm_host.h>
+#include <linux/kvm_types.h>
+#include <linux/rbtree_types.h>
+#include <linux/rcupdate.h>
 #include <linux/types.h>
 
+struct kvm_s2_mmu;
+
 #define KVM_PGTABLE_FIRST_LEVEL		-1
 #define KVM_PGTABLE_LAST_LEVEL		3
 
arch/arm64/include/asm/kvm_pkvm.h +1 -1
index 74fedd9c5ff0..a0f7a699d690 100644
@@ -9,7 +9,7 @@
 #include <linux/arm_ffa.h>
 #include <linux/memblock.h>
 #include <linux/scatterlist.h>
-#include <asm/kvm_host.h>
+#include <linux/kvm_host.h>
 #include <asm/kvm_pgtable.h>
 
 /* Maximum number of VMs that can co-exist under pKVM. */
arch/arm64/kvm/hyp/pgtable.c +1 -0
index 91a7dfad6686..3d608b7e0cf0 100644
@@ -8,6 +8,7 @@
  */
 
 #include <linux/bitfield.h>
+#include <linux/kvm_host.h>
 #include <asm/kvm_pgtable.h>
 #include <asm/stage2_pgtable.h>
 
Signature · 1 line
2.43.0
maintainer
#3 lore raw

Re: [PATCH v15 02/37] KVM: arm64: Avoid including linux/kvm_host.h in kvm_pgtable.h

Quoted 42 lines · Steven Price

To avoid future include cycles, drop the linux/kvm_host.h include in kvm_pgtable.h and include the lightweight headers required for the types and inline helpers used there. Additionally provide a forward declaration for struct kvm_s2_mmu as it's only used as a pointer in this file.

Both pgtable.c and kvm_pkvm.h relied on the indirect inclusion of kvm_host.h, so make that explicit.

---
New patch in v13

---
 arch/arm64/include/asm/kvm_pgtable.h | 6 +++++-
 arch/arm64/include/asm/kvm_pkvm.h    | 2 +-
 arch/arm64/kvm/hyp/pgtable.c         | 1 +
 3 files changed, 7 insertions(+), 2 deletions(-)
arch/arm64/include/asm/kvm_pgtable.h +5 -1
index 41a8687938eb..c2e4b29e605f 100644
@@ -8,9 +8,13 @@
 #define __ARM64_KVM_PGTABLE_H__
 
 #include <linux/bits.h>
-#include <linux/kvm_host.h>
+#include <linux/kvm_types.h>
+#include <linux/rbtree_types.h>
+#include <linux/rcupdate.h>
 #include <linux/types.h>
 
+struct kvm_s2_mmu;
+
 #define KVM_PGTABLE_FIRST_LEVEL		-1
 #define KVM_PGTABLE_LAST_LEVEL		3
 
arch/arm64/include/asm/kvm_pkvm.h +0 -0
index 74fedd9c5ff0..a0f7a699d690 100644

arch/arm64/include/asm/kvm_pkvm.h line 12

Quoted 5 lines
arch/arm64/include/asm/kvm_pkvm.h +1 -1
@@ -9,7 +9,7 @@
 #include <linux/arm_ffa.h>
 #include <linux/memblock.h>
 #include <linux/scatterlist.h>
-#include <asm/kvm_host.h>
+#include <linux/kvm_host.h>

nit: please keep the include directives in alphabetical order.

	M.
Signature · 1 line
Jazz isn't dead. It just smells funny.
#4 lore raw

Re: [PATCH v15 02/37] KVM: arm64: Avoid including linux/kvm_host.h in kvm_pgtable.h

Quoted 39 lines · Marc Zyngier
Quoted 37 lines · Steven Price

To avoid future include cycles, drop the linux/kvm_host.h include in kvm_pgtable.h and include the lightweight headers required for the types and inline helpers used there. Additionally provide a forward declaration for struct kvm_s2_mmu as it's only used as a pointer in this file.

Both pgtable.c and kvm_pkvm.h relied on the indirect inclusion of kvm_host.h, so make that explicit.

---
New patch in v13

---
 arch/arm64/include/asm/kvm_pgtable.h | 6 +++++-
 arch/arm64/include/asm/kvm_pkvm.h    | 2 +-
 arch/arm64/kvm/hyp/pgtable.c         | 1 +
 3 files changed, 7 insertions(+), 2 deletions(-)
arch/arm64/include/asm/kvm_pgtable.h +5 -1
index 41a8687938eb..c2e4b29e605f 100644
@@ -8,9 +8,13 @@
 #define __ARM64_KVM_PGTABLE_H__
 
 #include <linux/bits.h>
-#include <linux/kvm_host.h>
+#include <linux/kvm_types.h>
+#include <linux/rbtree_types.h>
+#include <linux/rcupdate.h>
 #include <linux/types.h>
 
+struct kvm_s2_mmu;
+
 #define KVM_PGTABLE_FIRST_LEVEL		-1
 #define KVM_PGTABLE_LAST_LEVEL		3
 
Quoted 12 lines

arch/arm64/include/asm/kvm_pkvm.h line 12

Quoted 10 lines
arch/arm64/include/asm/kvm_pkvm.h +1 -1
index 74fedd9c5ff0..a0f7a699d690 100644
@@ -9,7 +9,7 @@
 #include <linux/arm_ffa.h>
 #include <linux/memblock.h>
 #include <linux/scatterlist.h>
-#include <asm/kvm_host.h>
+#include <linux/kvm_host.h>

nit: please keep the include directives in alphabetical order.

Ack.

Thanks,
Steve

Quoted 2 lines
	M.
#5 lore raw

PATCH v15 3/37 arm64: mm: Handle Granule Protection Faults (GPFs)

In reply to Steven Price

If the host attempts to access granules that have been delegated for use in a realm these accesses will be caught and will trigger a Granule Protection Fault (GPF).

A fault during a page walk signals a bug in the kernel and is handled by oopsing the kernel. A non-page walk fault could be caused by user space having access to a page which has been delegated to the kernel and will trigger a SIGBUS to allow debugging why user space is trying to access a delegated page.

---
Changes since v10:
* Don't call arm64_notify_die() in do_gpf() but simply return 1.
Changes since v2:
* Include missing "Granule Protection Fault at level -1"

---
 arch/arm64/mm/fault.c | 28 ++++++++++++++++++++++------
 1 file changed, 22 insertions(+), 6 deletions(-)
arch/arm64/mm/fault.c +22 -6
index 85e23388f9bb..ea3ae0ca7dba 100644
@@ -909,6 +909,22 @@ static int do_tag_check_fault(unsigned long far, unsigned long esr,
 	return 0;
 }
 
+static int do_gpf_ptw(unsigned long far, unsigned long esr, struct pt_regs *regs)
+{
+	const struct fault_info *inf = esr_to_fault_info(esr);
+
+	die_kernel_fault(inf->name, far, esr, regs);
+	return 0;
+}
+
+static int do_gpf(unsigned long far, unsigned long esr, struct pt_regs *regs)
+{
+	if (!is_el1_instruction_abort(esr) && fixup_exception(regs, esr))
+		return 0;
+
+	return 1;
+}
+
 static const struct fault_info fault_info[] = {
 	{ do_bad,		SIGKILL, SI_KERNEL,	"ttbr address size fault"	},
 	{ do_bad,		SIGKILL, SI_KERNEL,	"level 1 address size fault"	},
@@ -945,12 +961,12 @@ static const struct fault_info fault_info[] = {
 	{ do_bad,		SIGKILL, SI_KERNEL,	"unknown 32"			},
 	{ do_alignment_fault,	SIGBUS,  BUS_ADRALN,	"alignment fault"		},
 	{ do_bad,		SIGKILL, SI_KERNEL,	"unknown 34"			},
-	{ do_bad,		SIGKILL, SI_KERNEL,	"unknown 35"			},
-	{ do_bad,		SIGKILL, SI_KERNEL,	"unknown 36"			},
-	{ do_bad,		SIGKILL, SI_KERNEL,	"unknown 37"			},
-	{ do_bad,		SIGKILL, SI_KERNEL,	"unknown 38"			},
-	{ do_bad,		SIGKILL, SI_KERNEL,	"unknown 39"			},
-	{ do_bad,		SIGKILL, SI_KERNEL,	"unknown 40"			},
+	{ do_gpf_ptw,		SIGKILL, SI_KERNEL,	"level -1 granule protection fault (translation table walk)" },
+	{ do_gpf_ptw,		SIGKILL, SI_KERNEL,	"level 0 granule protection fault (translation table walk)" },
+	{ do_gpf_ptw,		SIGKILL, SI_KERNEL,	"level 1 granule protection fault (translation table walk)" },
+	{ do_gpf_ptw,		SIGKILL, SI_KERNEL,	"level 2 granule protection fault (translation table walk)" },
+	{ do_gpf_ptw,		SIGKILL, SI_KERNEL,	"level 3 granule protection fault (translation table walk)" },
+	{ do_gpf,		SIGBUS,  SI_KERNEL,	"granule protection fault" },
 	{ do_bad,		SIGKILL, SI_KERNEL,	"level -1 address size fault"	},
 	{ do_bad,		SIGKILL, SI_KERNEL,	"unknown 42"			},
 	{ do_translation_fault,	SIGSEGV, SEGV_MAPERR,	"level -1 translation fault"	},
Signature · 1 line
2.43.0
#6 lore raw

PATCH v15 4/37 KVM: arm64: CCA: Check for RMI support at KVM init

In reply to Steven Price

Check if the RMI support is sufficient for using in KVM. Specifically, we currently only support creating realm VMs when KVM is running in VHE mode.

---
Changes since v13:
* Most of the init has been moved out of the 'kvm' directory so this is much more basic now.
Changes since v12:
* Drop check for 4k page size.
Changes since v11:
* Reword slightly the comments on the realm states.
Changes since v10:
* kvm_is_realm() no longer has a NULL check.
* Rename from "rme" to "rmi" when referring to the RMM interface.
* Check for RME (hardware) support before probing for RMI support.
Changes since v8:
* No need to guard kvm_init_rme() behind 'in_hyp_mode'.
Changes since v6:
* Improved message for an unsupported RMI ABI version.
Changes since v5:
* Reword "unsupported" message from "host supports" to "we want" to clarify that 'we' are the 'host'.
Changes since v2:
* Drop return value from kvm_init_rme(), it was always 0.
* Rely on the RMM return value to identify whether the RSI ABI is compatible.

---
 arch/arm64/include/asm/kvm_host.h |  4 ++++
 arch/arm64/include/asm/kvm_rmi.h  | 17 +++++++++++++++++
 arch/arm64/include/asm/virt.h     |  1 +
 arch/arm64/kvm/Kconfig            |  1 +
 arch/arm64/kvm/Makefile           |  2 +-
 arch/arm64/kvm/arm.c              |  5 +++++
 arch/arm64/kvm/rmi.c              | 24 ++++++++++++++++++++++++
 7 files changed, 53 insertions(+), 1 deletion(-)
 create mode 100644 arch/arm64/include/asm/kvm_rmi.h
 create mode 100644 arch/arm64/kvm/rmi.c
arch/arm64/include/asm/kvm_host.h +4 -0
index bae2c4f92ef5..1a5e15040111 100644
@@ -27,6 +27,7 @@
 #include <asm/fpsimd.h>
 #include <asm/kvm.h>
 #include <asm/kvm_asm.h>
+#include <asm/kvm_rmi.h>
 #include <asm/vncr_mapping.h>
 
 #define __KVM_HAVE_ARCH_INTC_INITIALIZED
@@ -424,6 +425,9 @@ struct kvm_arch {
 	/* Nested virtualization info */
 	struct dentry *debugfs_nv_dentry;
 #endif
+
+	bool is_realm;
+	struct realm realm;
 };
 
 struct kvm_vcpu_fault_info {
arch/arm64/include/asm/kvm_rmi.h new file +17 -0
new file mode 100644
index 000000000000..57d24b244c95
@@ -0,0 +1,17 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Copyright (C) 2023-2026 ARM Ltd.
+ */
+
+#ifndef __ASM_KVM_RMI_H
+#define __ASM_KVM_RMI_H
+
+/**
+ * struct realm - Additional per VM data for a Realm
+ */
+struct realm {
+};
+
+void kvm_init_rmi(void);
+
+#endif /* __ASM_KVM_RMI_H */
arch/arm64/include/asm/virt.h +1 -0
index b546703c3ab9..92cec42952f4 100644
@@ -87,6 +87,7 @@ void __hyp_reset_vectors(void);
 bool is_kvm_arm_initialised(void);
 
 DECLARE_STATIC_KEY_FALSE(kvm_protected_mode_initialized);
+DECLARE_STATIC_KEY_FALSE(kvm_rmi_is_available);
 
 static inline bool is_pkvm_initialized(void)
 {
arch/arm64/kvm/Kconfig +1 -0
index 449154f9a485..189e8ad78b22 100644
@@ -37,6 +37,7 @@ menuconfig KVM
 	select SCHED_INFO
 	select GUEST_PERF_EVENTS if PERF_EVENTS
 	select KVM_GUEST_MEMFD
+	select ARM_RMM
 	help
 	  Support hosting virtualized guest machines.
 
arch/arm64/kvm/Makefile +1 -1
index 59612d2f277c..ed3cf30eb06e 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 +5 -0
index 50adfff75be8..b961c22fce3d 100644
@@ -42,6 +42,7 @@
 #include <asm/kvm_nested.h>
 #include <asm/kvm_pkvm.h>
 #include <asm/kvm_ptrauth.h>
+#include <asm/kvm_rmi.h>
 #include <asm/sections.h>
 #include <asm/stacktrace/nvhe.h>
 
@@ -111,6 +112,8 @@ long kvm_get_cap_for_kvm_ioctl(unsigned int ioctl, long *ext)
 	return -EINVAL;
 }
 
+DEFINE_STATIC_KEY_FALSE(kvm_rmi_is_available);
+
 DECLARE_KVM_HYP_PER_CPU(unsigned long, kvm_hyp_vector);
 
 DEFINE_PER_CPU(unsigned long, kvm_arm_hyp_stack_base);
@@ -3019,6 +3022,8 @@ static __init int kvm_arm_init(void)
 
 	in_hyp_mode = is_kernel_in_hyp_mode();
 
+	kvm_init_rmi();
+
 	if (cpus_have_final_cap(ARM64_WORKAROUND_DEVICE_LOAD_ACQUIRE) ||
 	    cpus_have_final_cap(ARM64_WORKAROUND_1508412))
 		kvm_info("Guests without required CPU erratum workarounds can deadlock system!\n" \
arch/arm64/kvm/rmi.c new file +24 -0
new file mode 100644
index 000000000000..384991d69f78
@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) 2023-2026 ARM Ltd.
+ */
+
+#include <linux/kvm_host.h>
+
+#include <asm/rmi_cmds.h>
+#include <asm/virt.h>
+
+void kvm_init_rmi(void)
+{
+	/*
+	 * TODO: Support Realm guests in nVHE mode, this will require adding
+	 * EL2 stub(s) for REC entry and possibly other things.
+	 */
+	if (!is_kernel_in_hyp_mode())
+		return;
+
+	if (!is_rmi_available())
+		return;
+
+	/* Future patch will enable static branch kvm_rmi_is_available */
+}
Signature · 1 line
2.43.0
#7 lore raw

PATCH v15 5/37 KVM: arm64: CCA: Check for LPA2 support

In reply to Steven Price

If KVM has enabled LPA2 support then check that the RMM also supports it. If there is a mismatch then disable support for realm guests as the VMM may attempt to create a guest which is incompatible with the RMM.

---
v15:
* Extend rmi_has_feature() to take the register number and check the presence of SHA-256 support which is default.
v13:
* New patch

---
 arch/arm64/kvm/rmi.c | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
arch/arm64/kvm/rmi.c +25 -0
index 384991d69f78..247c4f033945 100644
@@ -5,9 +5,31 @@
 
 #include <linux/kvm_host.h>
 
+#include <asm/kvm_pgtable.h>
 #include <asm/rmi_cmds.h>
 #include <asm/virt.h>
 
+static bool rmi_has_feature(int reg, unsigned long feature)
+{
+	return !!u64_get_bits(rmi_feat_reg(reg), feature);
+}
+
+static int rmm_check_features(void)
+{
+	if (kvm_lpa2_is_enabled() &&
+	    !rmi_has_feature(0, RMI_FEATURE_REGISTER_0_LPA2)) {
+		kvm_err("RMM doesn't support LPA2\n");
+		return -ENXIO;
+	}
+
+	if (!rmi_has_feature(1, RMI_FEATURE_REGISTER_1_HASH_SHA_256)) {
+		kvm_err("RMM doesn't support SHA-256 measurements\n");
+		return -ENXIO;
+	}
+
+	return 0;
+}
+
 void kvm_init_rmi(void)
 {
 	/*
@@ -20,5 +42,8 @@ void kvm_init_rmi(void)
 	if (!is_rmi_available())
 		return;
 
+	if (rmm_check_features())
+		return;
+
 	/* Future patch will enable static branch kvm_rmi_is_available */
 }
Signature · 1 line
2.43.0
reviewer Reviewed-by on v15 5/37
#8 lore raw

Re: [PATCH v15 05/37] KVM: arm64: CCA: Check for LPA2 support

Quoted 4 lines · Steven Price

If KVM has enabled LPA2 support then check that the RMM also supports it. If there is a mismatch then disable support for realm guests as the VMM may attempt to create a guest which is incompatible with the RMM.

We may be able to relax this in the future with the UNPROT MAP/UNMAP RMI ABIs now accepting the OutputAddress and Attributes separately and gracefully handle cases where the requested IPA size exceeds the RMM limit.

But practically I don't see why we should support it. So :

Quoted 1 line
Quoted 55 lines

---
v15:
* Extend rmi_has_feature() to take the register number and check the presence of SHA-256 support which is default.
v13:
* New patch

---
  arch/arm64/kvm/rmi.c | 25 +++++++++++++++++++++++++
  1 file changed, 25 insertions(+)
arch/arm64/kvm/rmi.c +25 -0
index 384991d69f78..247c4f033945 100644
@@ -5,9 +5,31 @@
 
  #include <linux/kvm_host.h>
 
+#include <asm/kvm_pgtable.h>
  #include <asm/rmi_cmds.h>
  #include <asm/virt.h>
 
+static bool rmi_has_feature(int reg, unsigned long feature)
+{
+	return !!u64_get_bits(rmi_feat_reg(reg), feature);
+}
+
+static int rmm_check_features(void)
+{
+	if (kvm_lpa2_is_enabled() &&
+	    !rmi_has_feature(0, RMI_FEATURE_REGISTER_0_LPA2)) {
+		kvm_err("RMM doesn't support LPA2\n");
+		return -ENXIO;
+	}
+
+	if (!rmi_has_feature(1, RMI_FEATURE_REGISTER_1_HASH_SHA_256)) {
+		kvm_err("RMM doesn't support SHA-256 measurements\n");
+		return -ENXIO;
+	}
+
+	return 0;
+}
+
  void kvm_init_rmi(void)
  {
  	/*
@@ -20,5 +42,8 @@ void kvm_init_rmi(void)
  	if (!is_rmi_available())
  		return;
 
+	if (rmm_check_features())
+		return;
+
  	/* Future patch will enable static branch kvm_rmi_is_available */
  }
#9 lore raw

PATCH v15 6/37 KVM: arm64: CCA: Define the user ABI

In reply to Steven Price

There is one CAP (KVM_CAP_ARM_RMI) which identifies the presence of CCA, and one ioctl. The ioctl (KVM_ARM_RMI_POPULATE) is used to populate memory during creation of the realm as this requires the RMM to copy data from an unprotected address to the protected memory - CCA does not support shared <-> private memory conversion where the memory contents is preserved as this is incompatible with memory encryption.

---
Changes since v13:
* KVM_ARM_VCPU_RMI_PSCI_COMPLETE removed.
* KVM_ARM_RMI_POPULATE documentation updated to reflect that the structure is written by the kernel.
* CAP number bumped.
Changes since v12:
* Change KVM_ARM_RMI_POPULATE to update the structure with the amount that has been progressed rather than return the number of bytes populated.
* Describe the flag KVM_ARM_RMI_POPULATE_FLAGS_MEASURE.
* CAP number is bumped.
* NOTE: The PSCI ioctl may be removed in a future spec release.
Changes since v11:
* Completely reworked to be more implicit. Rather than having explicit CAP operations to progress the realm construction these operations are done when needed (on populating and on first vCPU run).
* Populate and PSCI complete are promoted to proper ioctls.
Changes since v10:
* Rename symbols from RME to RMI.
Changes since v9:
* Improvements to documentation.
* Bump the magic number for KVM_CAP_ARM_RME to avoid conflicts.
Changes since v8:
* Minor improvements to documentation following review.
* Bump the magic numbers to avoid conflicts.
Changes since v7:
* Add documentation of new ioctls
* Bump the magic numbers to avoid conflicts
Changes since v6:
* Rename some of the symbols to make their usage clearer and avoid repetition.
Changes from v5:
* Actually expose the new VCPU capability (KVM_ARM_VCPU_REC) by bumping KVM_VCPU_MAX_FEATURES - note this also exposes KVM_ARM_VCPU_HAS_EL2!

---
 Documentation/virt/kvm/api.rst | 41 ++++++++++++++++++++++++++++++++++
 include/uapi/linux/kvm.h       | 13 +++++++++++
 2 files changed, 54 insertions(+)
Documentation/virt/kvm/api.rst +41 -0
index 304b9c3209ae..b38e090ad95d 100644
@@ -6642,6 +6642,38 @@ if the guest_memfd memory was pinned in IOMMU page tables.
 
 See also: :ref: `KVM_SET_MEMORY_ATTRIBUTES`.
 
+4.146 KVM_ARM_RMI_POPULATE
+--------------------------
+
+:Capability: KVM_CAP_ARM_RMI
+:Architectures: arm64
+:Type: vm ioctl
+:Parameters: struct kvm_arm_rmi_populate (in/out)
+:Returns: 0 on success, < 0 on error
+
+::
+
+  struct kvm_arm_rmi_populate {
+	__u64 base;
+	__u64 size;
+	__u64 source_uaddr;
+	__u32 flags;
+	__u32 reserved;
+  };
+
+Populate a region of protected address space by copying the data from the
+(non-protected) user space pointer provided into a protected region (backed by
+guestmem_fd). It implicitly sets the destination region to RIPAS RAM. This is
+only valid before any VCPUs have been run. The ioctl might not populate the
+entire region and in this case the kernel updates the fields `base`, `size` and
+`source_uaddr`. User space may have to repeatedly call it until `size` is 0 to
+populate the entire region.
+
+`flags` can be set to `KVM_ARM_RMI_POPULATE_FLAGS_MEASURE` to request that the
+populated data is hashed and added to the guest's Realm Initial Measurement
+(RIM) stored by the RMM. This can then be retrieved by the guest (using the RSI
+interface) to present to an attestation server.
+
 .. _kvm_run:
 
 5. The kvm_run structure
@@ -9025,6 +9057,15 @@ enabled, cmma can't be enabled anymore and pfmfi and the storage key
 interpretation are disabled. If cmma has already been enabled or the
 hpage_2g module parameter is not set to 1, -EINVAL is returned.
 
+7.48 KVM_CAP_ARM_RMI
+--------------------
+
+:Architectures: arm64
+:Target: VM
+:Parameters: None
+
+This capability indicates that support for CCA realms is available.
+
 8. Other capabilities.
 ======================
 
include/uapi/linux/kvm.h +13 -0
index 129d6f630325..0231ff174a50 100644
@@ -998,6 +998,7 @@ struct kvm_enable_cap {
 #define KVM_CAP_S390_VSIE_ESAMODE 248
 #define KVM_CAP_S390_HPAGE_2G 249
 #define KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTES 250
+#define KVM_CAP_ARM_RMI 251
 
 struct kvm_irq_routing_irqchip {
 	__u32 irqchip;
@@ -1686,4 +1687,16 @@ struct kvm_pre_fault_memory {
 	__u64 padding[5];
 };
 
+/* Available with KVM_CAP_ARM_RMI, only for VMs with KVM_VM_TYPE_ARM_REALM */
+#define KVM_ARM_RMI_POPULATE	_IOWR(KVMIO, 0xd7, struct kvm_arm_rmi_populate)
+#define KVM_ARM_RMI_POPULATE_FLAGS_MEASURE	(1 << 0)
+
+struct kvm_arm_rmi_populate {
+	__u64 base;
+	__u64 size;
+	__u64 source_uaddr;
+	__u32 flags;
+	__u32 reserved;
+};
+
 #endif /* __LINUX_KVM_H */
Signature · 1 line
2.43.0
#10 lore raw

Re: [PATCH v15 06/37] KVM: arm64: CCA: Define the user ABI

Quoted 6 lines · Steven Price

There is one CAP (KVM_CAP_ARM_RMI) which identifies the presence of CCA, and one ioctl. The ioctl (KVM_ARM_RMI_POPULATE) is used to populate memory during creation of the realm as this requires the RMM to copy data from an unprotected address to the protected memory - CCA does not support shared <-> private memory conversion where the memory contents is preserved as this is incompatible with memory encryption.

May be we could add the above constraint to the Documentation to make it clear from the source. The code later adds this restriction and it would be good to reflect in the Documentation, given other CC architectures seem to provide it.

Please see below.

Quoted 62 lines

---
Changes since v13:
* KVM_ARM_VCPU_RMI_PSCI_COMPLETE removed.
* KVM_ARM_RMI_POPULATE documentation updated to reflect that the structure is written by the kernel.
* CAP number bumped.
Changes since v12:
* Change KVM_ARM_RMI_POPULATE to update the structure with the amount that has been progressed rather than return the number of bytes populated.
* Describe the flag KVM_ARM_RMI_POPULATE_FLAGS_MEASURE.
* CAP number is bumped.
* NOTE: The PSCI ioctl may be removed in a future spec release.
Changes since v11:
* Completely reworked to be more implicit. Rather than having explicit CAP operations to progress the realm construction these operations are done when needed (on populating and on first vCPU run).
* Populate and PSCI complete are promoted to proper ioctls.
Changes since v10:
* Rename symbols from RME to RMI.
Changes since v9:
* Improvements to documentation.
* Bump the magic number for KVM_CAP_ARM_RME to avoid conflicts.
Changes since v8:
* Minor improvements to documentation following review.
* Bump the magic numbers to avoid conflicts.
Changes since v7:
* Add documentation of new ioctls
* Bump the magic numbers to avoid conflicts
Changes since v6:
* Rename some of the symbols to make their usage clearer and avoid repetition.
Changes from v5:
* Actually expose the new VCPU capability (KVM_ARM_VCPU_REC) by bumping KVM_VCPU_MAX_FEATURES - note this also exposes KVM_ARM_VCPU_HAS_EL2!

---
  Documentation/virt/kvm/api.rst | 41 ++++++++++++++++++++++++++++++++++
  include/uapi/linux/kvm.h       | 13 +++++++++++
  2 files changed, 54 insertions(+)
Documentation/virt/kvm/api.rst +12 -0
index 304b9c3209ae..b38e090ad95d 100644
@@ -6642,6 +6642,38 @@ if the guest_memfd memory was pinned in IOMMU page tables.
 
  See also: :ref: `KVM_SET_MEMORY_ATTRIBUTES`.
 
+4.146 KVM_ARM_RMI_POPULATE
+--------------------------
+
+:Capability: KVM_CAP_ARM_RMI
+:Architectures: arm64
+:Type: vm ioctl
+:Parameters: struct kvm_arm_rmi_populate (in/out)
+:Returns: 0 on success, < 0 on error
+
+::
+
+  struct kvm_arm_rmi_populate {

Documentation/virt/kvm/api.rst if the guest_memfd memory was pinned in IOMMU page tables. · line 6666

Quoted 10 lines
Documentation/virt/kvm/api.rst +10 -0
+	__u64 base;
+	__u64 size;
+	__u64 source_uaddr;
+	__u32 flags;
+	__u32 reserved;
+  };
+
+Populate a region of protected address space by copying the data from the
+(non-protected) user space pointer provided into a protected region (backed by
+guestmem_fd). It implicitly sets the destination region to RIPAS RAM. This is

minor nit: RIPAS_RAM for the sake of completeness. Also, I am wondering if this could confuse the reader to imply that the UABI implicitly converts the region in guest_memfd to "PRIVATE". May be we could rewrite
this to make all the preconditions explicit ? Something like:

"
Populate the guest address region described by @base and @size, with the data pointed to by the userspace pointer @source_uaddr. The guest_memfd region backing the memory region must be PRIVATE. Arm CCA cannot do in-place conversion, preserving the contents. Thus @source_uaddr must be a valid pointer. This operation maps to RMI_RTT_DATA_INIT which also converts the region to RIPAS_RAM.

"

Suzuki

Quoted 61 lines
Documentation/virt/kvm/api.rst +10 -0
+only valid before any VCPUs have been run. The ioctl might not populate the
+entire region and in this case the kernel updates the fields `base`, `size` and
+`source_uaddr`. User space may have to repeatedly call it until `size` is 0 to
+populate the entire region.
 
 
 
+
+`flags` can be set to `KVM_ARM_RMI_POPULATE_FLAGS_MEASURE` to request that the
+populated data is hashed and added to the guest's Realm Initial Measurement
+(RIM) stored by the RMM. This can then be retrieved by the guest (using the RSI
+interface) to present to an attestation server.
+

.. _kvm_run:

5. The kvm_run structure

Documentation/virt/kvm/api.rst +9 -0
@@ -9025,6 +9057,15 @@ enabled, cmma can't be enabled anymore and pfmfi and the storage key
  interpretation are disabled. If cmma has already been enabled or the
  hpage_2g module parameter is not set to 1, -EINVAL is returned.
 
+7.48 KVM_CAP_ARM_RMI
+--------------------
+
+:Architectures: arm64
+:Target: VM
+:Parameters: None
+
+This capability indicates that support for CCA realms is available.
+
  8. Other capabilities.
  ======================
 
include/uapi/linux/kvm.h +13 -0
index 129d6f630325..0231ff174a50 100644
@@ -998,6 +998,7 @@ struct kvm_enable_cap {
  #define KVM_CAP_S390_VSIE_ESAMODE 248
  #define KVM_CAP_S390_HPAGE_2G 249
  #define KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTES 250
+#define KVM_CAP_ARM_RMI 251
 
  struct kvm_irq_routing_irqchip {
  	__u32 irqchip;
@@ -1686,4 +1687,16 @@ struct kvm_pre_fault_memory {
  	__u64 padding[5];
  };
 
+/* Available with KVM_CAP_ARM_RMI, only for VMs with KVM_VM_TYPE_ARM_REALM */
+#define KVM_ARM_RMI_POPULATE	_IOWR(KVMIO, 0xd7, struct kvm_arm_rmi_populate)
+#define KVM_ARM_RMI_POPULATE_FLAGS_MEASURE	(1 << 0)
+
+struct kvm_arm_rmi_populate {
+	__u64 base;
+	__u64 size;
+	__u64 source_uaddr;
+	__u32 flags;
+	__u32 reserved;
+};
+
  #endif /* __LINUX_KVM_H */
#11 lore raw

PATCH v15 7/37 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 IPA size requested is checked against what the RMM supports.

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

---
Changes since v14:
* Adapt to the RMM v2.0-bet2 realm parameter layout and SRO-based realm creation.
Changes since v13:
* Rebased and updated to RMM-v2.0-bet1.
* Auxiliary granules have been removed in RMM-v2.0-bet1
Changes since v12:
* Drop the RMM_PAGE_{SHIFT,SIZE} defines - the RMM is now configured to be the same as the host's page size.
* Rework delegate/undelegate functions to use the new RMI range based operations.
Changes since v11:
* Major rework to drop the realm configuration and make the construction of realms implicit rather than driven by the VMM directly.
* The code to create RDs, handle VMIDs etc is moved to later patches.
Changes since v10:
* Rename from RME to RMI.
* Move the stage2 cleanup to a later patch.
Changes since v9:
* Avoid walking the stage 2 page tables when destroying the realm - the real ones are not accessible to the non-secure world, and the RMM may leave junk in the physical pages when returning them.
* Fix an error path in realm_create_rd() to actually return an error value.
Changes since v8:
* Fix free_delegated_granule() to not call kvm_account_pgtable_pages(); a separate wrapper will be introduced in a later patch to deal with RTTs.
* Minor code cleanups following review.
Changes since v7:
* Minor code cleanup following Gavin's review.
Changes since v6:
* Separate RMM RTT calculations from host PAGE_SIZE. This allows the host page size to be larger than 4k while still communicating with an RMM which uses 4k granules.
Changes since v5:
* Introduce free_delegated_granule() to replace many undelegate/free_page() instances and centralise the comment on leaking when the undelegate fails.
* Several other minor improvements suggested by reviews - thanks for the feedback!
Changes since v2:
* Improved commit description.
* Improved return failures for rmi_check_version().
* Clear contents of PGD after it has been undelegated in case the RMM left stale data.
* Minor changes to reflect changes in previous patches.

---
 arch/arm64/include/asm/kvm_emulate.h | 24 ++++++++++
 arch/arm64/include/asm/kvm_rmi.h     | 65 +++++++++++++++++++++++++++
 arch/arm64/kvm/arm.c                 | 12 +++++
 arch/arm64/kvm/mmu.c                 | 18 +++++++-
 arch/arm64/kvm/rmi.c                 | 67 ++++++++++++++++++++++++++++
 5 files changed, 184 insertions(+), 2 deletions(-)
arch/arm64/include/asm/kvm_emulate.h +24 -0
index 5bf3d7e1d92c..e26d6755279f 100644
@@ -688,4 +688,28 @@ static inline void vcpu_set_hcrx(struct kvm_vcpu *vcpu)
 			vcpu->arch.hcrx_el2 |= HCRX_EL2_EnASR;
 	}
 }
+
+static inline bool kvm_is_realm(struct kvm *kvm)
+{
+	if (static_branch_unlikely(&kvm_rmi_is_available))
+		return kvm->arch.is_realm;
+	return false;
+}
+
+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_is_realm(kvm) && kvm_realm_state(kvm) != REALM_STATE_NONE;
+}
+
 #endif /* __ARM64_KVM_EMULATE_H__ */
arch/arm64/include/asm/kvm_rmi.h +65 -0

77 lines not on this page · raw message

arch/arm64/kvm/arm.c +12 -0
index b961c22fce3d..c4d906861736 100644
@@ -266,6 +266,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_is_realm(kvm)) {
+		ret = kvm_init_realm(kvm);
+		if (ret)
+			goto err_uninit_mmu;
+	}
+
 	return 0;
 
 err_uninit_mmu:
@@ -328,6 +335,8 @@ void kvm_arch_destroy_vm(struct kvm *kvm)
 	kvm_unshare_hyp(kvm, kvm + 1);
 
 	kvm_arm_teardown_hypercalls(kvm);
+	if (kvm_is_realm(kvm))
+		kvm_destroy_realm(kvm);
 }
 
 static bool kvm_has_full_ptr_auth(void)
@@ -488,6 +497,9 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
 		else
 			r = kvm_supports_cacheable_pfnmap();
 		break;
+	case KVM_CAP_ARM_RMI:
+		r = static_key_enabled(&kvm_rmi_is_available);
+		break;
 
 	default:
 		r = 0;
arch/arm64/kvm/mmu.c +16 -2
index 6c941aaa10c6..8b9efa8a3539 100644
@@ -904,10 +904,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_is_realm(kvm))
+		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;
@@ -957,9 +961,18 @@ static void stage2_destroy_range(struct kvm_pgtable *pgt, phys_addr_t addr,
 
 static void kvm_stage2_destroy(struct kvm_pgtable *pgt)
 {
+	struct kvm *kvm = kvm_s2_mmu_to_kvm(pgt->mmu);
 	unsigned int ia_bits = VTCR_EL2_IPA(pgt->mmu->vtcr);
 
-	stage2_destroy_range(pgt, 0, BIT(ia_bits));
+	/*
+	 * 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.
+	 */
+	if (!kvm_is_realm(kvm))
+		stage2_destroy_range(pgt, 0, BIT(ia_bits));
+
 	KVM_PGT_FN(kvm_pgtable_stage2_destroy_pgd)(pgt);
 }
 
@@ -1001,6 +1014,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;
@@ -1009,7 +1024,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 +67 -0

79 lines not on this page · raw message

Signature · 1 line
2.43.0
#12 lore raw

PATCH v15 8/37 KVM: arm64: CCA: Don't expose unsupported capabilities for realm guests

In reply to Steven Price

From: Suzuki K Poulose <[email protected]>

RMM v2.0 provides no mechanism for the host to perform debug operations on the guest. So limit the extensions that are visible to an allowlist so that only those capabilities we can support are advertised.

---
Changes since v13:
* Add missing check in kvm_vm_ioctl_enable_cap().
Changes since v10:
* Add a kvm_realm_ext_allowed() function which limits which extensions are exposed to an allowlist. This removes the need for special casing various extensions.
Changes since v7:
* Remove the helper functions and inline the kvm_is_realm() check with a ternary operator.
* Rewrite the commit message to explain this patch.

---
 arch/arm64/kvm/arm.c | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)
arch/arm64/kvm/arm.c +26 -0
index c4d906861736..6f39831dcf5d 100644
@@ -135,6 +135,26 @@ int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
 	return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
 }
 
+static bool kvm_realm_ext_allowed(long ext)
+{
+	switch (ext) {
+	case KVM_CAP_IRQCHIP:
+	case KVM_CAP_ARM_PSCI:
+	case KVM_CAP_ARM_PSCI_0_2:
+	case KVM_CAP_NR_VCPUS:
+	case KVM_CAP_MAX_VCPUS:
+	case KVM_CAP_MAX_VCPU_ID:
+	case KVM_CAP_MSI_DEVID:
+	case KVM_CAP_ARM_VM_IPA_SIZE:
+	case KVM_CAP_ARM_PTRAUTH_ADDRESS:
+	case KVM_CAP_ARM_PTRAUTH_GENERIC:
+	case KVM_CAP_ARM_RMI:
+	case KVM_CAP_SYNC_MMU:
+		return true;
+	}
+	return false;
+}
+
 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
 			    struct kvm_enable_cap *cap)
 {
@@ -146,6 +166,9 @@ int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
 	if (is_protected_kvm_enabled() && !kvm_pkvm_ext_allowed(kvm, cap->cap))
 		return -EINVAL;
 
+	if (kvm && kvm_is_realm(kvm) && !kvm_realm_ext_allowed(cap->cap))
+		return -EINVAL;
+
 	switch (cap->cap) {
 	case KVM_CAP_ARM_NISV_TO_USER:
 		r = 0;
@@ -380,6 +403,9 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
 	if (is_protected_kvm_enabled() && !kvm_pkvm_ext_allowed(kvm, ext))
 		return 0;
 
+	if (kvm && kvm_is_realm(kvm) && !kvm_realm_ext_allowed(ext))
+		return 0;
+
 	switch (ext) {
 	case KVM_CAP_IRQCHIP:
 		r = vgic_present;
Signature · 1 line
2.43.0
#13 lore raw

PATCH v15 9/37 KVM: arm64: CCA: Allow passing the machine type in KVM creation

In reply to Steven Price

Previously machine type was used purely for specifying the physical address size of the guest. Reserve the higher bits to specify an ARM specific machine type and declare a new type 'KVM_VM_TYPE_ARM_REALM' used to create a realm guest.

---
Changes since v13:
* Rework to use the two top bits for the machine type now that pKVM has merged and used the top bit for KVM_VM_TYPE_ARM_PROTECTED.
* Update the documentation to include KVM_VM_TYPE_ARM_PROTECTED as well.
Changes since v9:
* Explictly set realm.state to REALM_STATE_NONE rather than rely on the zeroing of the structure.
Changes since v7:
* Add some documentation explaining the new machine type.
Changes since v6:
* Make the check for kvm_rme_is_available more visible and report an error code of -EPERM (instead of -EINVAL) to make it explicit that the kernel supports RME, but the platform doesn't.

---
 Documentation/virt/kvm/api.rst | 18 ++++++++++++++++--
 arch/arm64/kvm/arm.c           | 11 +++++++++++
 include/uapi/linux/kvm.h       |  7 ++++++-
 3 files changed, 33 insertions(+), 3 deletions(-)
Documentation/virt/kvm/api.rst +16 -2
index b38e090ad95d..e39d146b34a3 100644
@@ -181,8 +181,22 @@ flag KVM_VM_MIPS_VZ.
 ARM64:
 ^^^^^^
 
-On arm64, the physical address size for a VM (IPA Size limit) is limited
-to 40bits by default. The limit can be configured if the host supports the
+On arm64, the machine type identifier is used to encode a type and the
+physical address size for the VM. The lower byte (bits[7-0]) encode the
+address size and the upper bits[30-31] encode a machine type. The machine
+types that might be available are:
+
+ =========================   ============================================
+ KVM_VM_TYPE_ARM_NORMAL      A standard VM
+ KVM_VM_TYPE_ARM_REALM       A "Realm" VM using the Arm Confidential
+                             Compute extensions, the VM's memory is
+                             protected from the host.
+ KVM_VM_TYPE_ARM_PROTECTED   A "protected" VM using pKVM to isolate the
+                             VM from the host.
+ =========================   ============================================
+
+The physical address size for a VM (IPA Size limit) is limited to 40bits
+by default. The limit can be configured if the host supports the
 extension KVM_CAP_ARM_VM_IPA_SIZE. When supported, use
 KVM_VM_TYPE_ARM_IPA_SIZE(IPA_Bits) to set the size in the machine type
 identifier, where IPA_Bits is the maximum width of any physical
arch/arm64/kvm/arm.c +11 -0
index 6f39831dcf5d..9881fd6c511c 100644
@@ -249,6 +249,17 @@ int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
 	mutex_unlock(&kvm->lock);
 #endif
 
+	if ((type & KVM_VM_TYPE_ARM_PROTECTED) &&
+	    (type & KVM_VM_TYPE_ARM_REALM))
+		return -EINVAL;
+
+	if (type & KVM_VM_TYPE_ARM_REALM) {
+		if (!static_branch_unlikely(&kvm_rmi_is_available))
+			return -EINVAL;
+		kvm_set_realm_state(kvm, REALM_STATE_NONE);
+		kvm->arch.is_realm = true;
+	}
+
 	kvm_init_nested(kvm);
 
 	ret = kvm_share_hyp(kvm, kvm + 1);
include/uapi/linux/kvm.h +6 -1
index 0231ff174a50..adee3936d6ae 100644
@@ -700,14 +700,19 @@ struct kvm_enable_cap {
  * address size for the VM. Bits[7-0] are reserved for the guest
  * PA size shift (i.e, log2(PA_Size)). For backward compatibility,
  * value 0 implies the default IPA size, 40bits.
+ *
+ * Bits[30-31] are reserved for the VM type
  */
 #define KVM_VM_TYPE_ARM_IPA_SIZE_MASK	0xffULL
 #define KVM_VM_TYPE_ARM_IPA_SIZE(x)		\
 	((x) & KVM_VM_TYPE_ARM_IPA_SIZE_MASK)
 
+#define KVM_VM_TYPE_ARM_NORMAL		0
+#define KVM_VM_TYPE_ARM_REALM		(1UL << 30)
 #define KVM_VM_TYPE_ARM_PROTECTED	(1UL << 31)
 #define KVM_VM_TYPE_ARM_MASK		(KVM_VM_TYPE_ARM_IPA_SIZE_MASK | \
-					 KVM_VM_TYPE_ARM_PROTECTED)
+					 KVM_VM_TYPE_ARM_PROTECTED | \
+					 KVM_VM_TYPE_ARM_REALM)
 
 /*
  * ioctls for /dev/kvm fds:
Signature · 1 line
2.43.0
maintainer
#14 lore raw

Re: [PATCH v15 09/37] KVM: arm64: CCA: Allow passing the machine type in KVM creation

Quoted 42 lines · Steven Price

Previously machine type was used purely for specifying the physical address size of the guest. Reserve the higher bits to specify an ARM specific machine type and declare a new type 'KVM_VM_TYPE_ARM_REALM' used to create a realm guest.

---
Changes since v13:
* Rework to use the two top bits for the machine type now that pKVM has merged and used the top bit for KVM_VM_TYPE_ARM_PROTECTED.
* Update the documentation to include KVM_VM_TYPE_ARM_PROTECTED as well.
Changes since v9:
* Explictly set realm.state to REALM_STATE_NONE rather than rely on the zeroing of the structure.
Changes since v7:
* Add some documentation explaining the new machine type.
Changes since v6:
* Make the check for kvm_rme_is_available more visible and report an error code of -EPERM (instead of -EINVAL) to make it explicit that the kernel supports RME, but the platform doesn't.

---
 Documentation/virt/kvm/api.rst | 18 ++++++++++++++++--
 arch/arm64/kvm/arm.c           | 11 +++++++++++
 include/uapi/linux/kvm.h       |  7 ++++++-
 3 files changed, 33 insertions(+), 3 deletions(-)
Documentation/virt/kvm/api.rst +4 -2
index b38e090ad95d..e39d146b34a3 100644
@@ -181,8 +181,22 @@ flag KVM_VM_MIPS_VZ.
 ARM64:
 ^^^^^^
 
-On arm64, the physical address size for a VM (IPA Size limit) is limited
-to 40bits by default. The limit can be configured if the host supports the
+On arm64, the machine type identifier is used to encode a type and the
+physical address size for the VM. The lower byte (bits[7-0]) encode the
+address size and the upper bits[30-31] encode a machine type. The machine
+types that might be available are:

Documentation/virt/kvm/api.rst flag KVM_VM_MIPS_VZ. · line 197

Quoted 10 lines
Documentation/virt/kvm/api.rst +10 -0
+
+ =========================   ============================================
+ KVM_VM_TYPE_ARM_NORMAL      A standard VM
+ KVM_VM_TYPE_ARM_REALM       A "Realm" VM using the Arm Confidential
+                             Compute extensions, the VM's memory is
+                             protected from the host.
+ KVM_VM_TYPE_ARM_PROTECTED   A "protected" VM using pKVM to isolate the
+                             VM from the host.
+ =========================   ============================================
+

Probably worth mentioning that REALM+PROTECTED is an illegal combination.

	M.
Signature · 1 line
Jazz isn't dead. It just smells funny.
#15 lore raw

Re: [PATCH v15 09/37] KVM: arm64: CCA: Allow passing the machine type in KVM creation

Quoted 49 lines · Marc Zyngier
Quoted 47 lines · Steven Price

Previously machine type was used purely for specifying the physical address size of the guest. Reserve the higher bits to specify an ARM specific machine type and declare a new type 'KVM_VM_TYPE_ARM_REALM' used to create a realm guest.

---
Changes since v13:
* Rework to use the two top bits for the machine type now that pKVM has merged and used the top bit for KVM_VM_TYPE_ARM_PROTECTED.
* Update the documentation to include KVM_VM_TYPE_ARM_PROTECTED as well.
Changes since v9:
* Explictly set realm.state to REALM_STATE_NONE rather than rely on the zeroing of the structure.
Changes since v7:
* Add some documentation explaining the new machine type.
Changes since v6:
* Make the check for kvm_rme_is_available more visible and report an error code of -EPERM (instead of -EINVAL) to make it explicit that the kernel supports RME, but the platform doesn't.

---
 Documentation/virt/kvm/api.rst | 18 ++++++++++++++++--
 arch/arm64/kvm/arm.c           | 11 +++++++++++
 include/uapi/linux/kvm.h       |  7 ++++++-
 3 files changed, 33 insertions(+), 3 deletions(-)
Documentation/virt/kvm/api.rst +9 -2
index b38e090ad95d..e39d146b34a3 100644
@@ -181,8 +181,22 @@ flag KVM_VM_MIPS_VZ.
 ARM64:
 ^^^^^^
 
-On arm64, the physical address size for a VM (IPA Size limit) is limited
-to 40bits by default. The limit can be configured if the host supports the
+On arm64, the machine type identifier is used to encode a type and the
+physical address size for the VM. The lower byte (bits[7-0]) encode the
+address size and the upper bits[30-31] encode a machine type. The machine
+types that might be available are:
+
+ =========================   ============================================
+ KVM_VM_TYPE_ARM_NORMAL      A standard VM
+ KVM_VM_TYPE_ARM_REALM       A "Realm" VM using the Arm Confidential
+                             Compute extensions, the VM's memory is
Quoted 8 lines

Documentation/virt/kvm/api.rst flag KVM_VM_MIPS_VZ. · line 197

Quoted 5 lines
Documentation/virt/kvm/api.rst +5 -0
+                             protected from the host.
+ KVM_VM_TYPE_ARM_PROTECTED   A "protected" VM using pKVM to isolate the
+                             VM from the host.
+ =========================   ============================================
+

Probably worth mentioning that REALM+PROTECTED is an illegal combination.

The original intention was that these were enum values not separate bit fields. Having to adapt to the pKVM changes when they were merged has somewhat messed this up. I'll add a clarification, but hopefully we haven't actually burnt the combination in case we have a 4th type in the future.

Thanks,
Steve

maintainer
#16 lore raw

Re: [PATCH v15 09/37] KVM: arm64: CCA: Allow passing the machine type in KVM creation

Quoted 60 lines · Steven Price
Quoted 49 lines · Marc Zyngier
Quoted 47 lines · Steven Price

Previously machine type was used purely for specifying the physical address size of the guest. Reserve the higher bits to specify an ARM specific machine type and declare a new type 'KVM_VM_TYPE_ARM_REALM' used to create a realm guest.

---
Changes since v13:
* Rework to use the two top bits for the machine type now that pKVM has merged and used the top bit for KVM_VM_TYPE_ARM_PROTECTED.
* Update the documentation to include KVM_VM_TYPE_ARM_PROTECTED as well.
Changes since v9:
* Explictly set realm.state to REALM_STATE_NONE rather than rely on the zeroing of the structure.
Changes since v7:
* Add some documentation explaining the new machine type.
Changes since v6:
* Make the check for kvm_rme_is_available more visible and report an error code of -EPERM (instead of -EINVAL) to make it explicit that the kernel supports RME, but the platform doesn't.

---
 Documentation/virt/kvm/api.rst | 18 ++++++++++++++++--
 arch/arm64/kvm/arm.c           | 11 +++++++++++
 include/uapi/linux/kvm.h       |  7 ++++++-
 3 files changed, 33 insertions(+), 3 deletions(-)
Documentation/virt/kvm/api.rst +9 -2
index b38e090ad95d..e39d146b34a3 100644
@@ -181,8 +181,22 @@ flag KVM_VM_MIPS_VZ.
 ARM64:
 ^^^^^^
 
-On arm64, the physical address size for a VM (IPA Size limit) is limited
-to 40bits by default. The limit can be configured if the host supports the
+On arm64, the machine type identifier is used to encode a type and the
+physical address size for the VM. The lower byte (bits[7-0]) encode the
+address size and the upper bits[30-31] encode a machine type. The machine
+types that might be available are:
+
+ =========================   ============================================
+ KVM_VM_TYPE_ARM_NORMAL      A standard VM
+ KVM_VM_TYPE_ARM_REALM       A "Realm" VM using the Arm Confidential
+                             Compute extensions, the VM's memory is
Quoted 8 lines

Documentation/virt/kvm/api.rst flag KVM_VM_MIPS_VZ. · line 197

Quoted 5 lines
Documentation/virt/kvm/api.rst +5 -0
+                             protected from the host.
+ KVM_VM_TYPE_ARM_PROTECTED   A "protected" VM using pKVM to isolate the
+                             VM from the host.
+ =========================   ============================================
+

Probably worth mentioning that REALM+PROTECTED is an illegal combination.

Quoted 5 lines

The original intention was that these were enum values not separate bit fields. Having to adapt to the pKVM changes when they were merged has somewhat messed this up. I'll add a clarification, but hopefully we haven't actually burnt the combination in case we have a 4th type in the future.

A good way to avoid ambiguity would be to list the actual values for the [31:30] field (0b00, 0b01, 0b10).

Thanks,

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

PATCH v15 10/37 KVM: arm64: CCA: Tear down 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, tearing down 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).

---
Changes since v14:
* Teardown is now serialized under config_lock and idempotent.
Changes since v13:
* Avoid the double call of kvm_free_stage2_pgd() by splitting the work across that and a new function kvm_realm_uninit_stage2() which is only called for realm guests.
Changes since v12:
* Simplify some functions now we know RMM page size is the same as the host's.
Changes since v11:
* Moved some code from earlier in the series to this one so that it's added when it's first used.
Changes since v10:
* RME->RMI rename.
* Some code to handle freeing stage 2 PGD moved into this patch where it belongs.
Changes since v9:
* Add a comment clarifying that root level RTTs are not destroyed until after the RD is destroyed.
Changes since v8:
* Introduce free_rtt() wrapper which calls free_delegated_granule() followed by kvm_account_pgtable_pages(). This makes it clear where an RTT is being freed rather than just a delegated granule.
Changes since v6:
* Move rme_rtt_level_mapsize() and supporting defines from kvm_rme.h into rme.c as they are only used in that file.
Changes since v5:
* Rename some RME_xxx defines to do with page sizes as RMM_xxx - they are a property of the RMM specification not the RME architecture.
Changes since v2:
* Moved {alloc,free}_delegated_page() and ensure_spare_page() to a later patch when they are actually used.
* Some simplifications now rmi_xxx() functions allow NULL as an output parameter.
* Improved comments and code layout.

---
 arch/arm64/include/asm/kvm_rmi.h |  11 ++
 arch/arm64/kvm/mmu.c             |  17 ++-
 arch/arm64/kvm/rmi.c             | 196 +++++++++++++++++++++++++++++++
 3 files changed, 223 insertions(+), 1 deletion(-)
arch/arm64/include/asm/kvm_rmi.h +11 -0
index 5c40616aa1a1..31ec856561c6 100644
@@ -57,6 +57,8 @@ enum realm_state {
  * @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
+ * @stage2_unmapped: The Realm stage-2 mappings have been removed
+ * @rtts_destroyed: The non-root RTTs have been torn down
  */
 struct realm {
 	void *rd;
@@ -71,6 +73,8 @@ struct realm {
 	struct rmi_sro_state *sro;
 	enum realm_state state;
 	unsigned int ia_bits;
+	bool stage2_unmapped;
+	bool rtts_destroyed;
 };
 
 void kvm_init_rmi(void);
@@ -78,5 +82,12 @@ u32 kvm_rmm_ipa_limit(void);
 
 int kvm_init_realm(struct kvm *kvm);
 void kvm_destroy_realm(struct kvm *kvm);
+int kvm_realm_teardown_stage2(struct kvm *kvm);
+
+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 +16 -1
index 8b9efa8a3539..cd06881c1497 100644
@@ -1060,9 +1060,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);
+
+	mutex_lock(&kvm->arch.config_lock);
+	if (kvm_realm_state(kvm) == REALM_STATE_ACTIVE) {
+		kvm_set_realm_state(kvm, REALM_STATE_DYING);
+		WARN_ON(kvm_realm_teardown_stage2(kvm));
+	}
+	mutex_unlock(&kvm->arch.config_lock);
+}
+
 void kvm_uninit_stage2_mmu(struct kvm *kvm)
 {
-	kvm_free_stage2_pgd(&kvm->arch.mmu);
+	if (kvm_is_realm(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 +196 -0

225 lines not on this page · raw message

Signature · 1 line
2.43.0
#18 lore raw

PATCH v15 11/37 KVM: arm64: CCA: Allocate and free RECs to match vCPUs

In reply to Steven Price

The RMM maintains a data structure known as the Realm Execution Context (or REC). It is similar to struct kvm_vcpu and tracks the state of the virtual CPUs. KVM must delegate memory and request the structures are created when vCPUs are created, and suitably tear down on destruction.

RECs may require additional pages (e.g. for storing larger register state for SVE). The RMM can request extra pages for this purpose using the Stateful RMI Operations (SRO) functionality to request pages during REC creation. These pages are then passed back to the host from the RMM ('reclaimed') when the REC is destroyed. The kernel tracking object (struct rmi_sro_state) is stored in the realm_rec structure to avoid memory allocation during the destruction path.

Note that only some of register state for the REC can be set by KVM, the rest is defined by the RMM (zeroed). The register state then cannot be changed by KVM after the REC is created (except when the guest explicitly requests this e.g. by performing a PSCI call).

Note that the function kvm_create_rec() is unused at this point, a future patch will add the call and remove the __maybe_unused attribute.

---
Changes since v14:
* Handle partial REC creation better by NULLing rec->run, rec->rec_page and rec->sro when freeing.
Changes since v13:
* Support SRO for REC creation/destruction instead of auxiliary granules.
Changes since v12:
* Use the new range-based delegation RMI.
Changes since v11:
* Remove the KVM_ARM_VCPU_REC feature. User space no longer needs to configure each VCPU separately, RECs are created on the first VCPU run of the guest.
Changes since v9:
* Size the aux_pages array according to the PAGE_SIZE of the host.
Changes since v7:
* Add comment explaining the aux_pages array.
* Rename "undeleted_failed" variable to "should_free" to avoid a confusing double negative.
Changes since v6:
* Avoid reporting the KVM_ARM_VCPU_REC feature if the guest isn't a realm guest.
* Support host page size being larger than RMM's granule size when allocating/freeing aux granules.
Changes since v5:
* Separate the concept of vcpu_is_rec() and kvm_arm_vcpu_rec_finalized() by using the KVM_ARM_VCPU_REC feature as the indication that the VCPU is a REC.
Changes since v2:
* Free rec->run earlier in kvm_destroy_realm() and adapt to previous patches.

---
 arch/arm64/include/asm/kvm_emulate.h |   5 ++
 arch/arm64/include/asm/kvm_host.h    |   3 +
 arch/arm64/include/asm/kvm_rmi.h     |  16 +++++
 arch/arm64/kvm/arm.c                 |   6 ++
 arch/arm64/kvm/reset.c               |   1 +
 arch/arm64/kvm/rmi.c                 | 100 +++++++++++++++++++++++++++
 6 files changed, 131 insertions(+)
arch/arm64/include/asm/kvm_emulate.h +5 -0
index e26d6755279f..2e69fe494716 100644
@@ -712,4 +712,9 @@ static inline bool kvm_realm_is_created(struct kvm *kvm)
 	return kvm_is_realm(kvm) && kvm_realm_state(kvm) != REALM_STATE_NONE;
 }
 
+static inline bool vcpu_is_rec(const struct kvm_vcpu *vcpu)
+{
+	return kvm_is_realm(vcpu->kvm);
+}
+
 #endif /* __ARM64_KVM_EMULATE_H__ */
arch/arm64/include/asm/kvm_host.h +3 -0
index 1a5e15040111..9b46b39ed11e 100644
@@ -949,6 +949,9 @@ struct kvm_vcpu_arch {
 
 	/* Hyp-readable copy of kvm_vcpu::pid */
 	pid_t pid;
+
+	/* Realm meta data */
+	struct realm_rec rec;
 };
 
 /*
arch/arm64/include/asm/kvm_rmi.h +16 -0
index 31ec856561c6..ccd09d55c69f 100644
@@ -77,12 +77,28 @@ struct realm {
 	bool rtts_destroyed;
 };
 
+/**
+ * struct realm_rec - Additional per VCPU data for a Realm
+ *
+ * @mpidr: MPIDR (Multiprocessor Affinity Register) value to identify this VCPU
+ * @rec_page: Kernel VA of the RMM's private page for this REC
+ * @run: Kernel VA of the RmiRecRun structure shared with the RMM
+ * @sro: A preallocated SRO state context
+ */
+struct realm_rec {
+	unsigned long mpidr;
+	void *rec_page;
+	struct rec_run *run;
+	struct rmi_sro_state *sro;
+};
+
 void kvm_init_rmi(void);
 u32 kvm_rmm_ipa_limit(void);
 
 int kvm_init_realm(struct kvm *kvm);
 void kvm_destroy_realm(struct kvm *kvm);
 int kvm_realm_teardown_stage2(struct kvm *kvm);
+void kvm_destroy_rec(struct kvm_vcpu *vcpu);
 
 static inline bool kvm_realm_is_private_address(struct realm *realm,
 						unsigned long addr)
arch/arm64/kvm/arm.c +6 -0
index 9881fd6c511c..38fac98cd6a4 100644
@@ -589,6 +589,8 @@ int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
 	/* Force users to call KVM_ARM_VCPU_INIT */
 	vcpu_clear_flag(vcpu, VCPU_INITIALIZED);
 
+	vcpu->arch.rec.mpidr = INVALID_HWID;
+
 	vcpu->arch.mmu_page_cache.gfp_zero = __GFP_ZERO;
 
 	/* Set up the timer */
@@ -1668,6 +1670,10 @@ static int kvm_vcpu_init_check_features(struct kvm_vcpu *vcpu,
 	if (test_bit(KVM_ARM_VCPU_HAS_EL2, &features))
 		return -EINVAL;
 
+	/* Realms are incompatible with AArch32 */
+	if (vcpu_is_rec(vcpu))
+		return -EINVAL;
+
 	return 0;
 }
 
arch/arm64/kvm/reset.c +1 -0
index b963fd975aac..c18cdca7d125 100644
@@ -161,6 +161,7 @@ void kvm_arm_vcpu_destroy(struct kvm_vcpu *vcpu)
 	free_page((unsigned long)vcpu->arch.ctxt.vncr_array);
 	kfree(vcpu->arch.vncr_tlb);
 	kfree(vcpu->arch.ccsidr);
+	kvm_destroy_rec(vcpu);
 }
 
 static void kvm_vcpu_reset_sve(struct kvm_vcpu *vcpu)
arch/arm64/kvm/rmi.c +100 -0

106 lines not on this page · raw message

Signature · 1 line
2.43.0
#19 lore raw

PATCH v15 12/37 KVM: arm64: CCA: Support the VGIC in realms

In reply to Steven Price

The RMM provides emulation of a VGIC to the realm guest. With RMM v2.0 the registers are passed in the system registers so this works similar to a normal guest, but kvm_arch_vcpu_put() need reordering to early out, and realm guests don't support GICv2 even if the host does.

---
Changes from v12:
* GIC registers are now passed in the system registers rather than via rec_entry/rec_exit which removes most of the changes.
Changes from v11:
* Minor changes to align with the previous patches. Note that the VGIC handling will change with RMM v2.0.
Changes from v10:
* Make sure we sync the VGIC v4 state, and only populate valid lrs from the list.
Changes from v9:
* Copy gicv3_vmcr from the RMM at the same time as gicv3_hcr rather than having to handle that as a special case.
Changes from v8:
* Propagate gicv3_hcr to from the RMM.
Changes from v5:
* Handle RMM providing fewer GIC LRs than the hardware supports.

---
 arch/arm64/kvm/arm.c            | 11 ++++++++---
 arch/arm64/kvm/vgic/vgic-init.c |  2 +-
 2 files changed, 9 insertions(+), 4 deletions(-)
arch/arm64/kvm/arm.c +8 -3
index 38fac98cd6a4..2959a1451232 100644
@@ -791,19 +791,24 @@ void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
 		kvm_call_hyp_nvhe(__pkvm_vcpu_put);
 	}
 
+	kvm_timer_vcpu_put(vcpu);
+	kvm_vgic_put(vcpu);
 	kvm_vcpu_put_debug(vcpu);
+
+	vcpu->cpu = -1;
+
+	if (vcpu_is_rec(vcpu))
+		return;
+
 	kvm_arch_vcpu_put_fp(vcpu);
 	if (has_vhe())
 		kvm_vcpu_put_vhe(vcpu);
-	kvm_timer_vcpu_put(vcpu);
-	kvm_vgic_put(vcpu);
 	kvm_vcpu_pmu_restore_host(vcpu);
 	if (vcpu_has_nv(vcpu))
 		kvm_vcpu_put_hw_mmu(vcpu);
 	kvm_arm_vmid_clear_active();
 
 	vcpu_clear_on_unsupported_cpu(vcpu);
-	vcpu->cpu = -1;
 }
 
 static void __kvm_arm_vcpu_power_off(struct kvm_vcpu *vcpu)
arch/arm64/kvm/vgic/vgic-init.c +1 -1
index 907057881b26..fd77db35ef02 100644
@@ -81,7 +81,7 @@ int kvm_vgic_create(struct kvm *kvm, u32 type)
 	 * the proper checks already.
 	 */
 	if (type == KVM_DEV_TYPE_ARM_VGIC_V2 &&
-		!kvm_vgic_global_state.can_emulate_gicv2)
+	    (!kvm_vgic_global_state.can_emulate_gicv2 || kvm_is_realm(kvm)))
 		return -ENODEV;
 
 	/*
Signature · 1 line
2.43.0
#20 lore raw

Re: [PATCH v15 12/37] KVM: arm64: CCA: Support the VGIC in realms

Quoted 6 lines · Steven Price

The RMM provides emulation of a VGIC to the realm guest. With RMM v2.0 the registers are passed in the system registers so this works similar to a normal guest, but kvm_arch_vcpu_put() need reordering to early out, and realm guests don't support GICv2 even if the host does.

Hi Steven,

I've been testing this series and found that when the host CPU doesn't have ARM64_HAS_ICH_HCR_EL2_TDIR this series doesn't work as expected.

Since commit 2a28810cbb8b ("KVM: arm64: GICv3: Detect and work around the lack of ICV_DIR_EL1 trapping"), when the host CPU doesn't support this feature, KVM traps all GIC sysreg accesses in the common group. However, currently trap handlers for ICC_{PMR,RPR,CTLR}_EL1 registers are missing [0]. So when Realm guests try to access those registers, KVM traps them but just emits the warning shown in [1], and Realm guests fail to boot.

As far as I can tell, the CCA requirements don't require the ARM64_HAS_ICH_HCR_EL2_TDIR feature. If that's the case, this seems to be a problem. Is there any workaround for this issue, or should we implement trap handlers for those registers?

Thanks,
Kohei

[0]

static const struct sys_reg_desc sys_reg_descs[] = {
    ...
	{ SYS_DESC(SYS_ICC_PMR_EL1), undef_access },
	{ SYS_DESC(SYS_ICC_RPR_EL1), undef_access },
	{ SYS_DESC(SYS_ICC_CTLR_EL1), undef_access },
};

[1]

------------[ cut here ]------------
Unexpected undefined exception injection to REC
WARNING: arch/arm64/kvm/inject_fault.c:330 at kvm_inject_undefined+0x100/0x148, CPU#1: kvm-vcpu-0/370
Modules linked in:
CPU: 1 UID: 0 PID: 370 Comm: kvm-vcpu-0 Not tainted 7.2.0-rc1-00096-gd6d40e6a3103 #161 PREEMPT(lazy)
[...]
Call trace:
 kvm_inject_undefined+0x100/0x148 (P)
 undef_access+0x18/0x30
 perform_access+0x54/0x1d0
 kvm_handle_sys_reg+0xfc/0x308
 rec_exit_sys_reg+0x34/0x168
 handle_rec_exit+0x12c/0x4c8
 kvm_arch_vcpu_ioctl_run+0x7a0/0x9a8
 kvm_vcpu_ioctl+0x180/0xb50
 __arm64_sys_ioctl+0xb4/0x118
 invoke_syscall.constprop.0+0xb8/0x120
 do_el0_svc+0x48/0xc8
 el0_svc+0x44/0x248
 el0t_64_sync_handler+0xa0/0xe8
 el0t_64_sync+0x198/0x1a0
---[ end trace 0000000000000000 ]---
 [...]
Quoted 71 lines

---
Changes from v12:
* GIC registers are now passed in the system registers rather than via rec_entry/rec_exit which removes most of the changes.
Changes from v11:
* Minor changes to align with the previous patches. Note that the VGIC handling will change with RMM v2.0.
Changes from v10:
* Make sure we sync the VGIC v4 state, and only populate valid lrs from the list.
Changes from v9:
* Copy gicv3_vmcr from the RMM at the same time as gicv3_hcr rather than having to handle that as a special case.
Changes from v8:
* Propagate gicv3_hcr to from the RMM.
Changes from v5:
* Handle RMM providing fewer GIC LRs than the hardware supports.

---
 arch/arm64/kvm/arm.c            | 11 ++++++++---
 arch/arm64/kvm/vgic/vgic-init.c |  2 +-
 2 files changed, 9 insertions(+), 4 deletions(-)
arch/arm64/kvm/arm.c +8 -3
index 38fac98cd6a4..2959a1451232 100644
@@ -791,19 +791,24 @@ void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
 		kvm_call_hyp_nvhe(__pkvm_vcpu_put);
 	}
 
+	kvm_timer_vcpu_put(vcpu);
+	kvm_vgic_put(vcpu);
 	kvm_vcpu_put_debug(vcpu);
+
+	vcpu->cpu = -1;
+
+	if (vcpu_is_rec(vcpu))
+		return;
+
 	kvm_arch_vcpu_put_fp(vcpu);
 	if (has_vhe())
 		kvm_vcpu_put_vhe(vcpu);
-	kvm_timer_vcpu_put(vcpu);
-	kvm_vgic_put(vcpu);
 	kvm_vcpu_pmu_restore_host(vcpu);
 	if (vcpu_has_nv(vcpu))
 		kvm_vcpu_put_hw_mmu(vcpu);
 	kvm_arm_vmid_clear_active();
 
 	vcpu_clear_on_unsupported_cpu(vcpu);
-	vcpu->cpu = -1;
 }
 
 static void __kvm_arm_vcpu_power_off(struct kvm_vcpu *vcpu)
arch/arm64/kvm/vgic/vgic-init.c +1 -1
index 907057881b26..fd77db35ef02 100644
@@ -81,7 +81,7 @@ int kvm_vgic_create(struct kvm *kvm, u32 type)
 	 * the proper checks already.
 	 */
 	if (type == KVM_DEV_TYPE_ARM_VGIC_V2 &&
-		!kvm_vgic_global_state.can_emulate_gicv2)
+	    (!kvm_vgic_global_state.can_emulate_gicv2 || kvm_is_realm(kvm)))
 		return -ENODEV;
 
 	/*
Signature · 1 line
2.43.0
maintainer
#21 lore raw

Re: [PATCH v15 12/37] KVM: arm64: CCA: Support the VGIC in realms

Quoted 7 lines · Kohei Enju
Quoted 5 lines · Steven Price

The RMM provides emulation of a VGIC to the realm guest. With RMM v2.0 the registers are passed in the system registers so this works similar to a normal guest, but kvm_arch_vcpu_put() need reordering to early out, and realm guests don't support GICv2 even if the host does.

Quoted 6 lines
Quoted 1 line

Hi Steven,

I've been testing this series and found that when the host CPU doesn't have ARM64_HAS_ICH_HCR_EL2_TDIR this series doesn't work as expected.

What modern CPU doesn't support TDIR? The only CPUs I know of that are stuck in this mode are old ARMv8.0 CPUs, and anything else was fixed.

Quoted 7 lines

Since commit 2a28810cbb8b ("KVM: arm64: GICv3: Detect and work around the lack of ICV_DIR_EL1 trapping"), when the host CPU doesn't support this feature, KVM traps all GIC sysreg accesses in the common group. However, currently trap handlers for ICC_{PMR,RPR,CTLR}_EL1 registers are missing [0]. So when Realm guests try to access those registers, KVM traps them but just emits the warning shown in [1], and Realm guests fail to boot.

This isn't missing. This is handled by the early emulation in vgic-v3-sr.c, which of course CCA completely bypasses. Too bad.

Quoted 5 lines

As far as I can tell, the CCA requirements don't require the ARM64_HAS_ICH_HCR_EL2_TDIR feature. If that's the case, this seems to be a problem. Is there any workaround for this issue, or should we implement trap handlers for those registers?

No. Either you support TDIR, like any modern CPU, or you don't run CCA. I'm not adding yet another level of emulation for this.

Thanks,

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

Re: [PATCH v15 12/37] KVM: arm64: CCA: Support the VGIC in realms

Quoted 11 lines · Marc Zyngier
Quoted 9 lines · Kohei Enju
Quoted 6 lines · Steven Price

The RMM provides emulation of a VGIC to the realm guest. With RMM v2.0 the registers are passed in the system registers so this works similar to a normal guest, but kvm_arch_vcpu_put() need reordering to early out, and realm guests don't support GICv2 even if the host does.

Quoted 7 lines
Quoted 4 lines

Hi Steven,

I've been testing this series and found that when the host CPU doesn't have ARM64_HAS_ICH_HCR_EL2_TDIR this series doesn't work as expected.

What modern CPU doesn't support TDIR? The only CPUs I know of that are stuck in this mode are old ARMv8.0 CPUs, and anything else was fixed.

Hi Marc, thank you for the response.

I'm afraid I can't share the details due to my company's policy, but at least I happen to be testing on such a system.

Quoted 11 lines
Quoted 8 lines

Since commit 2a28810cbb8b ("KVM: arm64: GICv3: Detect and work around the lack of ICV_DIR_EL1 trapping"), when the host CPU doesn't support this feature, KVM traps all GIC sysreg accesses in the common group. However, currently trap handlers for ICC_{PMR,RPR,CTLR}_EL1 registers are missing [0]. So when Realm guests try to access those registers, KVM traps them but just emits the warning shown in [1], and Realm guests fail to boot.

This isn't missing. This is handled by the early emulation in vgic-v3-sr.c, which of course CCA completely bypasses. Too bad.

That makes sense.

Quoted 9 lines
Quoted 6 lines

As far as I can tell, the CCA requirements don't require the ARM64_HAS_ICH_HCR_EL2_TDIR feature. If that's the case, this seems to be a problem. Is there any workaround for this issue, or should we implement trap handlers for those registers?

No. Either you support TDIR, like any modern CPU, or you don't run CCA. I'm not adding yet another level of emulation for this.

However, I'm still not aware of any requirement in the CCA architecture, or in Armv8-A/Armv9-A, that mandates TDIR support.

When you say "you don't run CCA", is that because the architecture requires it, or because that's the current KVM policy? If it's the latter, we'd be interested in adding the required emulation to make it work.

Thanks,
Kohei

Quoted 8 lines

Thanks,

	M.
Signature · 1 line
Without deviation from the norm, progress is not possible.
maintainer
#23 lore raw

Re: [PATCH v15 12/37] KVM: arm64: CCA: Support the VGIC in realms

Quoted 8 lines · Kohei Enju
Quoted 6 lines · Marc Zyngier
Quoted 5 lines

As far as I can tell, the CCA requirements don't require the ARM64_HAS_ICH_HCR_EL2_TDIR feature. If that's the case, this seems to be a problem. Is there any workaround for this issue, or should we implement trap handlers for those registers?

Quoted 5 lines
Quoted 2 lines

No. Either you support TDIR, like any modern CPU, or you don't run CCA. I'm not adding yet another level of emulation for this.

However, I'm still not aware of any requirement in the CCA architecture, or in Armv8-A/Armv9-A, that mandates TDIR support.

The GICv3 architecture has deprecated the lack of TDIR support since the very first release of the specification in 2015, because it was quickly identified as an architecture bug. CCA mandates GICv3 support as written in the spec, and relying on deprecated features 11 years later is not acceptable.

By any definition, this is buggy hardware, and I don't feel a strong urge to support it.

Quoted 3 lines

When you say "you don't run CCA", is that because the architecture requires it,

See above.

Quoted 3 lines

or because that's the current KVM policy? If it's the latter, we'd be interested in adding the required emulation to make it work.

And I say no to this. Enough. This isn't a "policy*. This is a hard red line. "Do Not Cross".

We already have the most complicated interrupt architecture ever, and I have zero desire to add even more complexity to it. Because I'm the idiot who ends-up maintaining this horror, and not you.

So no, no more emulation code. CCA in KVM won't handle systems that do not support TDIR, unless you rewrite the CCA support so that it can use the *existing* emulation code without any change.

Thanks,

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

Re: [PATCH v15 12/37] KVM: arm64: CCA: Support the VGIC in realms

Quoted 38 lines · Marc Zyngier
Quoted 8 lines · Kohei Enju
Quoted 6 lines · Marc Zyngier
Quoted 5 lines

As far as I can tell, the CCA requirements don't require the ARM64_HAS_ICH_HCR_EL2_TDIR feature. If that's the case, this seems to be a problem. Is there any workaround for this issue, or should we implement trap handlers for those registers?

Quoted 5 lines
Quoted 2 lines

No. Either you support TDIR, like any modern CPU, or you don't run CCA. I'm not adding yet another level of emulation for this.

However, I'm still not aware of any requirement in the CCA architecture, or in Armv8-A/Armv9-A, that mandates TDIR support.

The GICv3 architecture has deprecated the lack of TDIR support since the very first release of the specification in 2015, because it was quickly identified as an architecture bug. CCA mandates GICv3 support as written in the spec, and relying on deprecated features 11 years later is not acceptable.

By any definition, this is buggy hardware, and I don't feel a strong urge to support it.

Quoted 3 lines

When you say "you don't run CCA", is that because the architecture requires it,

See above.

Quoted 3 lines

or because that's the current KVM policy? If it's the latter, we'd be interested in adding the required emulation to make it work.

And I say no to this. Enough. This isn't a "policy*. This is a hard red line. "Do Not Cross".

Quoted 7 lines

We already have the most complicated interrupt architecture ever, and I have zero desire to add even more complexity to it. Because I'm the idiot who ends-up maintaining this horror, and not you.

So no, no more emulation code. CCA in KVM won't handle systems that do not support TDIR, unless you rewrite the CCA support so that it can use the *existing* emulation code without any change.

Understood. Thanks for the clarification.

Thanks,
Kohei

Quoted 8 lines

Thanks,

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

Re: [PATCH v15 12/37] KVM: arm64: CCA: Support the VGIC in realms

In reply to Kohei Enju
Quoted 9 lines · Kohei Enju
Quoted 6 lines · Steven Price

The RMM provides emulation of a VGIC to the realm guest. With RMM v2.0 the registers are passed in the system registers so this works similar to a normal guest, but kvm_arch_vcpu_put() need reordering to early out, and realm guests don't support GICv2 even if the host does.

Hi Steven,

Hi Kohei,

Quoted 2 lines

I've been testing this series and found that when the host CPU doesn't have ARM64_HAS_ICH_HCR_EL2_TDIR this series doesn't work as expected.

Thanks for testing!

Quoted 11 lines

Since commit 2a28810cbb8b ("KVM: arm64: GICv3: Detect and work around the lack of ICV_DIR_EL1 trapping"), when the host CPU doesn't support this feature, KVM traps all GIC sysreg accesses in the common group. However, currently trap handlers for ICC_{PMR,RPR,CTLR}_EL1 registers are missing [0]. So when Realm guests try to access those registers, KVM traps them but just emits the warning shown in [1], and Realm guests fail to boot.

As far as I can tell, the CCA requirements don't require the ARM64_HAS_ICH_HCR_EL2_TDIR feature. If that's the case, this seems to be a problem. Is there any workaround for this issue, or should we implement trap handlers for those registers?

As Marc has already said in his reply, I'm really surprised you have a CPU which implements CCA but doesn't have ARM64_HAS_ICH_HCR_EL2_TDIR. Can you give some more details about the platform you are testing on?

Ultimately there are two options here - either don't support CCA (so detect the lack of ARM64_HAS_ICH_HCR_EL2_TDIR and bail out early), or plumb in the trap handlers - as commit 2a28810cbb8b points out this isn't something we really want to support if we can avoid it.

Hence I'm interested to know where this sits between "hacked up test system" and "production hardware". E.g. if this is an emulator it might be possible to just enable the CPU feature.

Thanks,
Steve

Quoted 107 lines

Thanks,
Kohei

[0]

static const struct sys_reg_desc sys_reg_descs[] = {
    ...
	{ SYS_DESC(SYS_ICC_PMR_EL1), undef_access },
	{ SYS_DESC(SYS_ICC_RPR_EL1), undef_access },
	{ SYS_DESC(SYS_ICC_CTLR_EL1), undef_access },
};

[1]

------------[ cut here ]------------
Unexpected undefined exception injection to REC
WARNING: arch/arm64/kvm/inject_fault.c:330 at kvm_inject_undefined+0x100/0x148, CPU#1: kvm-vcpu-0/370
Modules linked in:
CPU: 1 UID: 0 PID: 370 Comm: kvm-vcpu-0 Not tainted 7.2.0-rc1-00096-gd6d40e6a3103 #161 PREEMPT(lazy)
[...]
Call trace:
 kvm_inject_undefined+0x100/0x148 (P)
 undef_access+0x18/0x30
 perform_access+0x54/0x1d0
 kvm_handle_sys_reg+0xfc/0x308
 rec_exit_sys_reg+0x34/0x168
 handle_rec_exit+0x12c/0x4c8
 kvm_arch_vcpu_ioctl_run+0x7a0/0x9a8
 kvm_vcpu_ioctl+0x180/0xb50
 __arm64_sys_ioctl+0xb4/0x118
 invoke_syscall.constprop.0+0xb8/0x120
 do_el0_svc+0x48/0xc8
 el0_svc+0x44/0x248
 el0t_64_sync_handler+0xa0/0xe8
 el0t_64_sync+0x198/0x1a0
---[ end trace 0000000000000000 ]---
 [...]
Quoted 71 lines

---
Changes from v12:
* GIC registers are now passed in the system registers rather than via rec_entry/rec_exit which removes most of the changes.
Changes from v11:
* Minor changes to align with the previous patches. Note that the VGIC handling will change with RMM v2.0.
Changes from v10:
* Make sure we sync the VGIC v4 state, and only populate valid lrs from the list.
Changes from v9:
* Copy gicv3_vmcr from the RMM at the same time as gicv3_hcr rather than having to handle that as a special case.
Changes from v8:
* Propagate gicv3_hcr to from the RMM.
Changes from v5:
* Handle RMM providing fewer GIC LRs than the hardware supports.

---
 arch/arm64/kvm/arm.c            | 11 ++++++++---
 arch/arm64/kvm/vgic/vgic-init.c |  2 +-
 2 files changed, 9 insertions(+), 4 deletions(-)
arch/arm64/kvm/arm.c +8 -3
index 38fac98cd6a4..2959a1451232 100644
@@ -791,19 +791,24 @@ void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
 		kvm_call_hyp_nvhe(__pkvm_vcpu_put);
 	}
 
+	kvm_timer_vcpu_put(vcpu);
+	kvm_vgic_put(vcpu);
 	kvm_vcpu_put_debug(vcpu);
+
+	vcpu->cpu = -1;
+
+	if (vcpu_is_rec(vcpu))
+		return;
+
 	kvm_arch_vcpu_put_fp(vcpu);
 	if (has_vhe())
 		kvm_vcpu_put_vhe(vcpu);
-	kvm_timer_vcpu_put(vcpu);
-	kvm_vgic_put(vcpu);
 	kvm_vcpu_pmu_restore_host(vcpu);
 	if (vcpu_has_nv(vcpu))
 		kvm_vcpu_put_hw_mmu(vcpu);
 	kvm_arm_vmid_clear_active();
 
 	vcpu_clear_on_unsupported_cpu(vcpu);
-	vcpu->cpu = -1;
 }
 
 static void __kvm_arm_vcpu_power_off(struct kvm_vcpu *vcpu)
arch/arm64/kvm/vgic/vgic-init.c +1 -1
index 907057881b26..fd77db35ef02 100644
@@ -81,7 +81,7 @@ int kvm_vgic_create(struct kvm *kvm, u32 type)
 	 * the proper checks already.
 	 */
 	if (type == KVM_DEV_TYPE_ARM_VGIC_V2 &&
-		!kvm_vgic_global_state.can_emulate_gicv2)
+	    (!kvm_vgic_global_state.can_emulate_gicv2 || kvm_is_realm(kvm)))
 		return -ENODEV;
 
 	/*
Signature · 1 line
2.43.0
#26 lore raw

Re: [PATCH v15 12/37] KVM: arm64: CCA: Support the VGIC in realms

Quoted 25 lines · Steven Price
Quoted 9 lines · Kohei Enju
Quoted 6 lines · Steven Price

The RMM provides emulation of a VGIC to the realm guest. With RMM v2.0 the registers are passed in the system registers so this works similar to a normal guest, but kvm_arch_vcpu_put() need reordering to early out, and realm guests don't support GICv2 even if the host does.

Hi Steven,

Hi Kohei,

Quoted 2 lines

I've been testing this series and found that when the host CPU doesn't have ARM64_HAS_ICH_HCR_EL2_TDIR this series doesn't work as expected.

Thanks for testing!

Quoted 7 lines

Since commit 2a28810cbb8b ("KVM: arm64: GICv3: Detect and work around the lack of ICV_DIR_EL1 trapping"), when the host CPU doesn't support this feature, KVM traps all GIC sysreg accesses in the common group. However, currently trap handlers for ICC_{PMR,RPR,CTLR}_EL1 registers are missing [0]. So when Realm guests try to access those registers, KVM traps them but just emits the warning shown in [1], and Realm guests fail to boot.

Quoted 8 lines
Quoted 4 lines

As far as I can tell, the CCA requirements don't require the ARM64_HAS_ICH_HCR_EL2_TDIR feature. If that's the case, this seems to be a problem. Is there any workaround for this issue, or should we implement trap handlers for those registers?

As Marc has already said in his reply, I'm really surprised you have a CPU which implements CCA but doesn't have ARM64_HAS_ICH_HCR_EL2_TDIR. Can you give some more details about the platform you are testing on?

Thank you for taking a look, Steve.

Unfortunately, due to the company's policy, I can't share any details about the platform I'm currently testing on. When the time is right, I'll be happy to do so.

Quoted 5 lines

Ultimately there are two options here - either don't support CCA (so detect the lack of ARM64_HAS_ICH_HCR_EL2_TDIR and bail out early), or plumb in the trap handlers - as commit 2a28810cbb8b points out this isn't something we really want to support if we can avoid it.

Yes, the former makes perfect sense if there would be no systems that supports CCA without TDIR. However, if such systems do exist, I'd be interested in exploring the latter approach.

Quoted 4 lines

Hence I'm interested to know where this sits between "hacked up test system" and "production hardware". E.g. if this is an emulator it might be possible to just enable the CPU feature.

Again, I can't share that right now, but I'd like to share more when the time comes.

Thanks,
Kohei

Quoted 4 lines

Thanks,
Steve

#27 lore raw

Re: [PATCH v15 12/37] KVM: arm64: CCA: Support the VGIC in realms

Quoted 52 lines · Kohei Enju
Quoted 25 lines · Steven Price
Quoted 9 lines · Kohei Enju
Quoted 6 lines · Steven Price

The RMM provides emulation of a VGIC to the realm guest. With RMM v2.0 the registers are passed in the system registers so this works similar to a normal guest, but kvm_arch_vcpu_put() need reordering to early out, and realm guests don't support GICv2 even if the host does.

Hi Steven,

Hi Kohei,

Quoted 2 lines

I've been testing this series and found that when the host CPU doesn't have ARM64_HAS_ICH_HCR_EL2_TDIR this series doesn't work as expected.

Thanks for testing!

Quoted 7 lines

Since commit 2a28810cbb8b ("KVM: arm64: GICv3: Detect and work around the lack of ICV_DIR_EL1 trapping"), when the host CPU doesn't support this feature, KVM traps all GIC sysreg accesses in the common group. However, currently trap handlers for ICC_{PMR,RPR,CTLR}_EL1 registers are missing [0]. So when Realm guests try to access those registers, KVM traps them but just emits the warning shown in [1], and Realm guests fail to boot.

Quoted 8 lines
Quoted 4 lines

As far as I can tell, the CCA requirements don't require the ARM64_HAS_ICH_HCR_EL2_TDIR feature. If that's the case, this seems to be a problem. Is there any workaround for this issue, or should we implement trap handlers for those registers?

As Marc has already said in his reply, I'm really surprised you have a CPU which implements CCA but doesn't have ARM64_HAS_ICH_HCR_EL2_TDIR. Can you give some more details about the platform you are testing on?

Thank you for taking a look, Steve.

Unfortunately, due to the company's policy, I can't share any details about the platform I'm currently testing on. When the time is right, I'll be happy to do so.

Quoted 5 lines

Ultimately there are two options here - either don't support CCA (so detect the lack of ARM64_HAS_ICH_HCR_EL2_TDIR and bail out early), or plumb in the trap handlers - as commit 2a28810cbb8b points out this isn't something we really want to support if we can avoid it.

Yes, the former makes perfect sense if there would be no systems that supports CCA without TDIR. However, if such systems do exist, I'd be interested in exploring the latter approach.

Quoted 1 line
Quoted 6 lines
Quoted 3 lines

Hence I'm interested to know where this sits between "hacked up test system" and "production hardware". E.g. if this is an emulator it might be possible to just enable the CPU feature.

Again, I can't share that right now, but I'd like to share more when the time comes.

Given Marc's response for now I'm not going to add support for this. "When the time comes" we can revisit whether it makes sense to have upstream support and what that might look like.

However, I did ask an AI tool to have a go at implementing this, and it came up with the (very lightly tested) patch below. That might at least give you something you can test. It doesn't meet Marc's request that it reuses the existing implementation, and it took the AI a few goes at getting something that "works" so I suspect it might have bugs - I haven't reviewed the code myself.

Thanks,
Steve

----8<----
From 7aaaa5089c05f19bf00df2b651fa4bd7d738384c Mon Sep 17 00:00:00 2001
From: Steven Price <[email protected]>
Date: Thu, 23 Jul 2026 11:49:36 +0100
Subject: [PATCH] KVM: arm64: CCA: Handle GICv3 CPU interface traps for realms

On CPUs that lack ICH_HCR_EL2.TDIR, KVM works around the missing DIR trap by setting ICH_HCR_EL2.TC and trapping the GICv3 common CPU interface registers. Normal guests handle these traps in hyp via the VGIC CPU interface emulation, but realm guests exit through the RMM and reach KVM's host-side sysreg emulation instead.

That path only handles ICC_DIR_EL1 and treats the rest of the trapped common group as undefined. A realm guest can therefore take an unexpected UNDEF when accessing registers such as ICC_PMR_EL1 or ICC_CTLR_EL1 on systems that require the TC workaround.

Handle the GICv3 common CPU interface registers directly from the realm sysreg exit path. Reads are satisfied from the saved VGIC state and writes update the VGIC shadow state. For PMR and CTLR writes, also restore the VMCR/APR state to the live GIC CPU interface before re-entering the REC, matching the effect a direct guest sysreg write would have had.

---
 arch/arm64/kvm/rmi-exit.c | 119 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 119 insertions(+)
arch/arm64/kvm/rmi-exit.c +119 -0
index 78d9189fd5ca..0fad8e68d920 100644
@@ -3,17 +3,25 @@
  * Copyright (C) 2023-2026 ARM Ltd.
  */
 
+#include <linux/bitfield.h>
+#include <linux/irqchip/arm-gic-v3.h>
 #include <linux/kvm_host.h>
 #include <kvm/arm_hypercalls.h>
 #include <kvm/arm_psci.h>
 
 #include <linux/arm-smccc-rmi.h>
 #include <asm/kvm_emulate.h>
+#include <asm/kvm_hyp.h>
 #include <asm/kvm_rmi.h>
 #include <asm/kvm_mmu.h>
+#include <asm/sysreg.h>
+
+#include "vgic/vgic.h"
 
 typedef int (*exit_handler_fn)(struct kvm_vcpu *vcpu);
 
+#define GICV3_IDLE_PRIORITY	0xff
+
 static int rec_exit_reason_notimpl(struct kvm_vcpu *vcpu)
 {
 	vcpu_err(vcpu, "Unhandled exit reason from realm (ESR: %#llx)\n",
@@ -48,6 +56,114 @@ static int rec_exit_sync_iabt(struct kvm_vcpu *vcpu)
 	return -ENXIO;
 }
 
+static int rec_get_gicv3_bpr_min(void)
+{
+	return 8 - (FIELD_GET(ICH_VTR_EL2_PREbits,
+			      kvm_vgic_global_state.ich_vtr_el2) + 1);
+}
+
+static u8 rec_get_gicv3_active_priority(struct kvm_vcpu *vcpu)
+{
+	struct vgic_v3_cpu_if *cpuif = &vcpu->arch.vgic_cpu.vgic_v3;
+	u8 prio = 0;
+
+	for (int i = 0; i <= vgic_v3_max_apr_idx(vcpu); i++) {
+		u32 val = cpuif->vgic_ap0r[i] | cpuif->vgic_ap1r[i];
+
+		if (!val) {
+			prio += 32;
+			continue;
+		}
+
+		return (prio + __ffs(val)) << rec_get_gicv3_bpr_min();
+	}
+
+	return GICV3_IDLE_PRIORITY;
+}
+
+static void rec_restore_gicv3_vmcr_aprs(struct kvm_vcpu *vcpu)
+{
+	preempt_disable();
+	kvm_call_hyp(__vgic_v3_restore_vmcr_aprs,
+		     &vcpu->arch.vgic_cpu.vgic_v3);
+	preempt_enable();
+}
+
+/*
+ * Realm exits are handled after the RMM has returned to the host, so use the
+ * saved VGIC shadow state instead of the hyp-side live sysreg helpers.
+ */
+static bool rec_exit_gicv3_sys_reg(struct kvm_vcpu *vcpu, bool is_write)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+	struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
+	struct vgic_vmcr vmcr;
+	unsigned long esr = kvm_vcpu_get_esr(vcpu);
+	int rt = kvm_vcpu_sys_get_rt(vcpu);
+	u32 sysreg = esr_sys64_to_sysreg(esr);
+	u64 val;
+
+	if (!kvm_has_gicv3(vcpu->kvm))
+		return false;
+
+	vgic_get_vmcr(vcpu, &vmcr);
+
+	switch (sysreg) {
+	case SYS_ICC_DIR_EL1:
+		if (!is_write)
+			return false;
+
+		vgic_v3_deactivate(vcpu, rec->run->exit.gprs[rt]);
+		return true;
+	case SYS_ICC_PMR_EL1:
+		if (is_write) {
+			vmcr.pmr = FIELD_GET(ICC_PMR_EL1_MASK,
+					     rec->run->exit.gprs[rt]);
+			vgic_set_vmcr(vcpu, &vmcr);
+			rec_restore_gicv3_vmcr_aprs(vcpu);
+		} else {
+			rec->run->enter.gprs[rt] = FIELD_PREP(ICC_PMR_EL1_MASK,
+							      vmcr.pmr);
+		}
+
+		return true;
+	case SYS_ICC_CTLR_EL1:
+		if (is_write) {
+			val = rec->run->exit.gprs[rt];
+			vmcr.cbpr = FIELD_GET(ICC_CTLR_EL1_CBPR_MASK, val);
+			vmcr.eoim = FIELD_GET(ICC_CTLR_EL1_EOImode_MASK, val);
+			vgic_set_vmcr(vcpu, &vmcr);
+			rec_restore_gicv3_vmcr_aprs(vcpu);
+		} else {
+			val  = FIELD_PREP(ICC_CTLR_EL1_PRI_BITS_MASK,
+					  vgic_cpu->num_pri_bits - 1);
+			val |= FIELD_PREP(ICC_CTLR_EL1_ID_BITS_MASK,
+					  vgic_cpu->num_id_bits);
+			val |= FIELD_PREP(ICC_CTLR_EL1_SEIS_MASK,
+					  FIELD_GET(ICH_VTR_EL2_SEIS,
+						    kvm_vgic_global_state.ich_vtr_el2));
+			val |= FIELD_PREP(ICC_CTLR_EL1_A3V_MASK,
+					  FIELD_GET(ICH_VTR_EL2_A3V,
+						    kvm_vgic_global_state.ich_vtr_el2));
+			val |= FIELD_PREP(ICC_CTLR_EL1_CBPR_MASK,
+					  vmcr.cbpr);
+			val |= FIELD_PREP(ICC_CTLR_EL1_EOImode_MASK,
+					  vmcr.eoim);
+			rec->run->enter.gprs[rt] = val;
+		}
+
+		return true;
+	case SYS_ICC_RPR_EL1:
+		if (is_write)
+			return false;
+
+		rec->run->enter.gprs[rt] = rec_get_gicv3_active_priority(vcpu);
+		return true;
+	default:
+		return false;
+	}
+}
+
 static int rec_exit_sys_reg(struct kvm_vcpu *vcpu)
 {
 	struct realm_rec *rec = &vcpu->arch.rec;
@@ -59,6 +175,9 @@ static int rec_exit_sys_reg(struct kvm_vcpu *vcpu)
 	if (is_write)
 		vcpu_set_reg(vcpu, rt, rec->run->exit.gprs[rt]);
 
+	if (rec_exit_gicv3_sys_reg(vcpu, is_write))
+		return 1;
+
 	ret = kvm_handle_sys_reg(vcpu);
 	if (!is_write)
 		rec->run->enter.gprs[rt] = vcpu_get_reg(vcpu, rt);
Signature · 1 line
2.43.0
#28 lore raw

Re: [PATCH v15 12/37] KVM: arm64: CCA: Support the VGIC in realms

Quoted 57 lines · Steven Price
Quoted 56 lines · Kohei Enju
Quoted 25 lines · Steven Price
Quoted 9 lines · Kohei Enju
Quoted 6 lines · Steven Price

The RMM provides emulation of a VGIC to the realm guest. With RMM v2.0 the registers are passed in the system registers so this works similar to a normal guest, but kvm_arch_vcpu_put() need reordering to early out, and realm guests don't support GICv2 even if the host does.

Hi Steven,

Hi Kohei,

Quoted 2 lines

I've been testing this series and found that when the host CPU doesn't have ARM64_HAS_ICH_HCR_EL2_TDIR this series doesn't work as expected.

Thanks for testing!

Quoted 7 lines

Since commit 2a28810cbb8b ("KVM: arm64: GICv3: Detect and work around the lack of ICV_DIR_EL1 trapping"), when the host CPU doesn't support this feature, KVM traps all GIC sysreg accesses in the common group. However, currently trap handlers for ICC_{PMR,RPR,CTLR}_EL1 registers are missing [0]. So when Realm guests try to access those registers, KVM traps them but just emits the warning shown in [1], and Realm guests fail to boot.

Quoted 8 lines
Quoted 4 lines

As far as I can tell, the CCA requirements don't require the ARM64_HAS_ICH_HCR_EL2_TDIR feature. If that's the case, this seems to be a problem. Is there any workaround for this issue, or should we implement trap handlers for those registers?

As Marc has already said in his reply, I'm really surprised you have a CPU which implements CCA but doesn't have ARM64_HAS_ICH_HCR_EL2_TDIR. Can you give some more details about the platform you are testing on?

Thank you for taking a look, Steve.

Unfortunately, due to the company's policy, I can't share any details about the platform I'm currently testing on. When the time is right, I'll be happy to do so.

Quoted 5 lines

Ultimately there are two options here - either don't support CCA (so detect the lack of ARM64_HAS_ICH_HCR_EL2_TDIR and bail out early), or plumb in the trap handlers - as commit 2a28810cbb8b points out this isn't something we really want to support if we can avoid it.

Yes, the former makes perfect sense if there would be no systems that supports CCA without TDIR. However, if such systems do exist, I'd be interested in exploring the latter approach.

Quoted 4 lines

Hence I'm interested to know where this sits between "hacked up test system" and "production hardware". E.g. if this is an emulator it might be possible to just enable the CPU feature.

Quoted 6 lines
Quoted 2 lines

Again, I can't share that right now, but I'd like to share more when the time comes.

Given Marc's response for now I'm not going to add support for this. "When the time comes" we can revisit whether it makes sense to have upstream support and what that might look like.

I understand. Thank you for clarifying the current stance.

Quoted 7 lines

However, I did ask an AI tool to have a go at implementing this, and it came up with the (very lightly tested) patch below. That might at least give you something you can test. It doesn't meet Marc's request that it reuses the existing implementation, and it took the AI a few goes at getting something that "works" so I suspect it might have bugs - I haven't reviewed the code myself.

Thanks for the patch. That's very helpful, and I'll look into it.

Thanks,
Kohei

Quoted 193 lines

Thanks,
Steve

----8<----
From 7aaaa5089c05f19bf00df2b651fa4bd7d738384c Mon Sep 17 00:00:00 2001
From: Steven Price <[email protected]>
Date: Thu, 23 Jul 2026 11:49:36 +0100
Subject: [PATCH] KVM: arm64: CCA: Handle GICv3 CPU interface traps for realms

On CPUs that lack ICH_HCR_EL2.TDIR, KVM works around the missing DIR trap by setting ICH_HCR_EL2.TC and trapping the GICv3 common CPU interface registers. Normal guests handle these traps in hyp via the VGIC CPU interface emulation, but realm guests exit through the RMM and reach KVM's host-side sysreg emulation instead.

That path only handles ICC_DIR_EL1 and treats the rest of the trapped common group as undefined. A realm guest can therefore take an unexpected UNDEF when accessing registers such as ICC_PMR_EL1 or ICC_CTLR_EL1 on systems that require the TC workaround.

Handle the GICv3 common CPU interface registers directly from the realm sysreg exit path. Reads are satisfied from the saved VGIC state and writes update the VGIC shadow state. For PMR and CTLR writes, also restore the VMCR/APR state to the live GIC CPU interface before re-entering the REC, matching the effect a direct guest sysreg write would have had.

---
 arch/arm64/kvm/rmi-exit.c | 119 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 119 insertions(+)
arch/arm64/kvm/rmi-exit.c +119 -0
index 78d9189fd5ca..0fad8e68d920 100644
@@ -3,17 +3,25 @@
  * Copyright (C) 2023-2026 ARM Ltd.
  */
 
+#include <linux/bitfield.h>
+#include <linux/irqchip/arm-gic-v3.h>
 #include <linux/kvm_host.h>
 #include <kvm/arm_hypercalls.h>
 #include <kvm/arm_psci.h>
 
 #include <linux/arm-smccc-rmi.h>
 #include <asm/kvm_emulate.h>
+#include <asm/kvm_hyp.h>
 #include <asm/kvm_rmi.h>
 #include <asm/kvm_mmu.h>
+#include <asm/sysreg.h>
+
+#include "vgic/vgic.h"
 
 typedef int (*exit_handler_fn)(struct kvm_vcpu *vcpu);
 
+#define GICV3_IDLE_PRIORITY	0xff
+
 static int rec_exit_reason_notimpl(struct kvm_vcpu *vcpu)
 {
 	vcpu_err(vcpu, "Unhandled exit reason from realm (ESR: %#llx)\n",
@@ -48,6 +56,114 @@ static int rec_exit_sync_iabt(struct kvm_vcpu *vcpu)
 	return -ENXIO;
 }
 
+static int rec_get_gicv3_bpr_min(void)
+{
+	return 8 - (FIELD_GET(ICH_VTR_EL2_PREbits,
+			      kvm_vgic_global_state.ich_vtr_el2) + 1);
+}
+
+static u8 rec_get_gicv3_active_priority(struct kvm_vcpu *vcpu)
+{
+	struct vgic_v3_cpu_if *cpuif = &vcpu->arch.vgic_cpu.vgic_v3;
+	u8 prio = 0;
+
+	for (int i = 0; i <= vgic_v3_max_apr_idx(vcpu); i++) {
+		u32 val = cpuif->vgic_ap0r[i] | cpuif->vgic_ap1r[i];
+
+		if (!val) {
+			prio += 32;
+			continue;
+		}
+
+		return (prio + __ffs(val)) << rec_get_gicv3_bpr_min();
+	}
+
+	return GICV3_IDLE_PRIORITY;
+}
+
+static void rec_restore_gicv3_vmcr_aprs(struct kvm_vcpu *vcpu)
+{
+	preempt_disable();
+	kvm_call_hyp(__vgic_v3_restore_vmcr_aprs,
+		     &vcpu->arch.vgic_cpu.vgic_v3);
+	preempt_enable();
+}
+
+/*
+ * Realm exits are handled after the RMM has returned to the host, so use the
+ * saved VGIC shadow state instead of the hyp-side live sysreg helpers.
+ */
+static bool rec_exit_gicv3_sys_reg(struct kvm_vcpu *vcpu, bool is_write)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+	struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
+	struct vgic_vmcr vmcr;
+	unsigned long esr = kvm_vcpu_get_esr(vcpu);
+	int rt = kvm_vcpu_sys_get_rt(vcpu);
+	u32 sysreg = esr_sys64_to_sysreg(esr);
+	u64 val;
+
+	if (!kvm_has_gicv3(vcpu->kvm))
+		return false;
+
+	vgic_get_vmcr(vcpu, &vmcr);
+
+	switch (sysreg) {
+	case SYS_ICC_DIR_EL1:
+		if (!is_write)
+			return false;
+
+		vgic_v3_deactivate(vcpu, rec->run->exit.gprs[rt]);
+		return true;
+	case SYS_ICC_PMR_EL1:
+		if (is_write) {
+			vmcr.pmr = FIELD_GET(ICC_PMR_EL1_MASK,
+					     rec->run->exit.gprs[rt]);
+			vgic_set_vmcr(vcpu, &vmcr);
+			rec_restore_gicv3_vmcr_aprs(vcpu);
+		} else {
+			rec->run->enter.gprs[rt] = FIELD_PREP(ICC_PMR_EL1_MASK,
+							      vmcr.pmr);
+		}
+
+		return true;
+	case SYS_ICC_CTLR_EL1:
+		if (is_write) {
+			val = rec->run->exit.gprs[rt];
+			vmcr.cbpr = FIELD_GET(ICC_CTLR_EL1_CBPR_MASK, val);
+			vmcr.eoim = FIELD_GET(ICC_CTLR_EL1_EOImode_MASK, val);
+			vgic_set_vmcr(vcpu, &vmcr);
+			rec_restore_gicv3_vmcr_aprs(vcpu);
+		} else {
+			val  = FIELD_PREP(ICC_CTLR_EL1_PRI_BITS_MASK,
+					  vgic_cpu->num_pri_bits - 1);
+			val |= FIELD_PREP(ICC_CTLR_EL1_ID_BITS_MASK,
+					  vgic_cpu->num_id_bits);
+			val |= FIELD_PREP(ICC_CTLR_EL1_SEIS_MASK,
+					  FIELD_GET(ICH_VTR_EL2_SEIS,
+						    kvm_vgic_global_state.ich_vtr_el2));
+			val |= FIELD_PREP(ICC_CTLR_EL1_A3V_MASK,
+					  FIELD_GET(ICH_VTR_EL2_A3V,
+						    kvm_vgic_global_state.ich_vtr_el2));
+			val |= FIELD_PREP(ICC_CTLR_EL1_CBPR_MASK,
+					  vmcr.cbpr);
+			val |= FIELD_PREP(ICC_CTLR_EL1_EOImode_MASK,
+					  vmcr.eoim);
+			rec->run->enter.gprs[rt] = val;
+		}
+
+		return true;
+	case SYS_ICC_RPR_EL1:
+		if (is_write)
+			return false;
+
+		rec->run->enter.gprs[rt] = rec_get_gicv3_active_priority(vcpu);
+		return true;
+	default:
+		return false;
+	}
+}
+
 static int rec_exit_sys_reg(struct kvm_vcpu *vcpu)
 {
 	struct realm_rec *rec = &vcpu->arch.rec;
@@ -59,6 +175,9 @@ static int rec_exit_sys_reg(struct kvm_vcpu *vcpu)
 	if (is_write)
 		vcpu_set_reg(vcpu, rt, rec->run->exit.gprs[rt]);
 
+	if (rec_exit_gicv3_sys_reg(vcpu, is_write))
+		return 1;
+
 	ret = kvm_handle_sys_reg(vcpu);
 	if (!is_write)
 		rec->run->enter.gprs[rt] = vcpu_get_reg(vcpu, rt);
Signature · 1 line
2.43.0
#29 lore raw

PATCH v15 13/37 KVM: arm64: CCA: Support timers in realm RECs

In reply to Steven Price

The RMM keeps track of the timer while the realm REC is running, but on exit to the normal world KVM is responsible for handling the timers.

A later patch adds the support for propagating the timer values from the exit data structure and calling kvm_realm_timers_update().

---
Changes since v14:
* Special case in kvm_timer_vcpu_load()/kvm_timer_vcpu_put() the timer handling.
Changes since v12:
* Adapt to upstream changes.
Changes since v11:
* Drop the kvm_is_realm() check from timer_set_offset(). We already ensure that the offset is 0 when calling the function.
Changes since v10:
* KVM_CAP_COUNTER_OFFSET is now already hidden by a previous patch.
Changes since v9:
* No need to move the call to kvm_timer_unblocking() in kvm_timer_vcpu_load().
Changes since v7:
* Hide KVM_CAP_COUNTER_OFFSET for realm guests.

---
 arch/arm64/kvm/arch_timer.c  | 38 +++++++++++++++++++++++++++++++++---
 include/kvm/arm_arch_timer.h |  2 ++
 2 files changed, 37 insertions(+), 3 deletions(-)
arch/arm64/kvm/arch_timer.c +35 -3
index 4155fe89b58a..fdd68f1f5b7b 100644
@@ -482,6 +482,20 @@ static void kvm_timer_update_irq(struct kvm_vcpu *vcpu, bool new_level,
 			    timer_ctx);
 }
 
+void kvm_realm_timers_update(struct kvm_vcpu *vcpu)
+{
+	struct arch_timer_cpu *arch_timer = &vcpu->arch.timer_cpu;
+	int i;
+
+	for (i = 0; i < NR_KVM_EL0_TIMERS; i++) {
+		struct arch_timer_context *timer = &arch_timer->timers[i];
+		bool status = timer_get_ctl(timer) & ARCH_TIMER_CTRL_IT_STAT;
+		bool level = kvm_timer_enabled(timer) && status;
+
+		kvm_timer_update_irq(vcpu, level, timer);
+	}
+}
+
 /* Only called for a fully emulated timer */
 static void timer_emulate(struct arch_timer_context *ctx)
 {
@@ -888,6 +902,11 @@ void kvm_timer_vcpu_load(struct kvm_vcpu *vcpu)
 	if (unlikely(!timer->enabled))
 		return;
 
+	if (vcpu_is_rec(vcpu)) {
+		kvm_timer_unblocking(vcpu);
+		return;
+	}
+
 	get_timer_map(vcpu, &map);
 
 	if (static_branch_likely(&has_gic_active_state)) {
@@ -923,6 +942,12 @@ void kvm_timer_vcpu_put(struct kvm_vcpu *vcpu)
 	if (unlikely(!timer->enabled))
 		return;
 
+	if (vcpu_is_rec(vcpu)) {
+		if (kvm_vcpu_is_blocking(vcpu))
+			kvm_timer_blocking(vcpu);
+		return;
+	}
+
 	get_timer_map(vcpu, &map);
 
 	timer_save_state(map.direct_vtimer);
@@ -1073,7 +1098,7 @@ static void timer_context_init(struct kvm_vcpu *vcpu, int timerid)
 
 	ctxt->timer_id = timerid;
 
-	if (!kvm_vm_is_protected(vcpu->kvm)) {
+	if (!kvm_vm_is_protected(vcpu->kvm) && !vcpu_is_rec(vcpu)) {
 		if (timerid == TIMER_VTIMER)
 			ctxt->offset.vm_offset = &kvm->arch.timer_data.voffset;
 		else
@@ -1104,7 +1129,7 @@ void kvm_timer_vcpu_init(struct kvm_vcpu *vcpu)
 		timer_context_init(vcpu, i);
 
 	/* Synchronize offsets across timers of a VM if not already provided */
-	if (!vcpu_is_protected(vcpu) &&
+	if (!vcpu_is_protected(vcpu) && !vcpu_is_rec(vcpu) &&
 	    !test_bit(KVM_ARCH_FLAG_VM_COUNTER_OFFSET, &vcpu->kvm->arch.flags)) {
 		timer_set_offset(vcpu_vtimer(vcpu), kvm_phys_timer_read());
 		timer_set_offset(vcpu_ptimer(vcpu), 0);
@@ -1600,6 +1625,13 @@ int kvm_timer_enable(struct kvm_vcpu *vcpu)
 		return -EINVAL;
 	}
 
+	/*
+	 * We don't use mapped IRQs for Realms because the RMI doesn't allow
+	 * us setting the LR.HW bit in the VGIC.
+	 */
+	if (vcpu_is_rec(vcpu))
+		return 0;
+
 	get_timer_map(vcpu, &map);
 
 	ops = vgic_is_v5(vcpu->kvm) ? &arch_timer_irq_ops_vgic_v5 :
@@ -1729,7 +1761,7 @@ int kvm_vm_ioctl_set_counter_offset(struct kvm *kvm,
 	if (offset->reserved)
 		return -EINVAL;
 
-	if (kvm_vm_is_protected(kvm))
+	if (kvm_vm_is_protected(kvm) || kvm_is_realm(kvm))
 		return -EINVAL;
 
 	mutex_lock(&kvm->lock);
include/kvm/arm_arch_timer.h +2 -0
index 15a4f97f8105..31e48d5dbc31 100644
@@ -108,6 +108,8 @@ int kvm_arm_timer_set_attr(struct kvm_vcpu *vcpu, struct kvm_device_attr *attr);
 int kvm_arm_timer_get_attr(struct kvm_vcpu *vcpu, struct kvm_device_attr *attr);
 int kvm_arm_timer_has_attr(struct kvm_vcpu *vcpu, struct kvm_device_attr *attr);
 
+void kvm_realm_timers_update(struct kvm_vcpu *vcpu);
+
 u64 kvm_phys_timer_read(void);
 
 void kvm_timer_vcpu_load(struct kvm_vcpu *vcpu);
Signature · 1 line
2.43.0
maintainer
#30 lore raw

Re: [PATCH v15 13/37] KVM: arm64: CCA: Support timers in realm RECs

Quoted 41 lines · Steven Price

The RMM keeps track of the timer while the realm REC is running, but on exit to the normal world KVM is responsible for handling the timers.

A later patch adds the support for propagating the timer values from the exit data structure and calling kvm_realm_timers_update().

---
Changes since v14:
* Special case in kvm_timer_vcpu_load()/kvm_timer_vcpu_put() the timer handling.
Changes since v12:
* Adapt to upstream changes.
Changes since v11:
* Drop the kvm_is_realm() check from timer_set_offset(). We already ensure that the offset is 0 when calling the function.
Changes since v10:
* KVM_CAP_COUNTER_OFFSET is now already hidden by a previous patch.
Changes since v9:
* No need to move the call to kvm_timer_unblocking() in kvm_timer_vcpu_load().
Changes since v7:
* Hide KVM_CAP_COUNTER_OFFSET for realm guests.

---
 arch/arm64/kvm/arch_timer.c  | 38 +++++++++++++++++++++++++++++++++---
 include/kvm/arm_arch_timer.h |  2 ++
 2 files changed, 37 insertions(+), 3 deletions(-)
arch/arm64/kvm/arch_timer.c +4 -0
index 4155fe89b58a..fdd68f1f5b7b 100644
@@ -482,6 +482,20 @@ static void kvm_timer_update_irq(struct kvm_vcpu *vcpu, bool new_level,
 			    timer_ctx);
 }
 
+void kvm_realm_timers_update(struct kvm_vcpu *vcpu)
+{
+	struct arch_timer_cpu *arch_timer = &vcpu->arch.timer_cpu;
+	int i;

arch/arm64/kvm/arch_timer.c static void kvm_timer_update_irq(struct kvm_vcpu *vcpu, bool new_level, · line 498

Quoted 10 lines
arch/arm64/kvm/arch_timer.c +10 -0
+
+	for (i = 0; i < NR_KVM_EL0_TIMERS; i++) {
+		struct arch_timer_context *timer = &arch_timer->timers[i];
+		bool status = timer_get_ctl(timer) & ARCH_TIMER_CTRL_IT_STAT;
+		bool level = kvm_timer_enabled(timer) && status;
+
+		kvm_timer_update_irq(vcpu, level, timer);
+	}
+}
+

Why do we need this? What is so special about CCA that it cannot use the existing timer flow?

Quoted 47 lines
arch/arm64/kvm/arch_timer.c +13 -2
 /* Only called for a fully emulated timer */
 static void timer_emulate(struct arch_timer_context *ctx)
 {
@@ -888,6 +902,11 @@ void kvm_timer_vcpu_load(struct kvm_vcpu *vcpu)
 	if (unlikely(!timer->enabled))
 		return;
 
+	if (vcpu_is_rec(vcpu)) {
+		kvm_timer_unblocking(vcpu);
+		return;
+	}
+
 	get_timer_map(vcpu, &map);
 
 	if (static_branch_likely(&has_gic_active_state)) {
@@ -923,6 +942,12 @@ void kvm_timer_vcpu_put(struct kvm_vcpu *vcpu)
 	if (unlikely(!timer->enabled))
 		return;
 
+	if (vcpu_is_rec(vcpu)) {
+		if (kvm_vcpu_is_blocking(vcpu))
+			kvm_timer_blocking(vcpu);
+		return;
+	}
+
 	get_timer_map(vcpu, &map);
 
 	timer_save_state(map.direct_vtimer);
@@ -1073,7 +1098,7 @@ static void timer_context_init(struct kvm_vcpu *vcpu, int timerid)
 
 	ctxt->timer_id = timerid;
 
-	if (!kvm_vm_is_protected(vcpu->kvm)) {
+	if (!kvm_vm_is_protected(vcpu->kvm) && !vcpu_is_rec(vcpu)) {
 		if (timerid == TIMER_VTIMER)
 			ctxt->offset.vm_offset = &kvm->arch.timer_data.voffset;
 		else
@@ -1104,7 +1129,7 @@ void kvm_timer_vcpu_init(struct kvm_vcpu *vcpu)
 		timer_context_init(vcpu, i);
 
 	/* Synchronize offsets across timers of a VM if not already provided */
-	if (!vcpu_is_protected(vcpu) &&
+	if (!vcpu_is_protected(vcpu) && !vcpu_is_rec(vcpu) &&
 	    !test_bit(KVM_ARCH_FLAG_VM_COUNTER_OFFSET, &vcpu->kvm->arch.flags)) {
 		timer_set_offset(vcpu_vtimer(vcpu), kvm_phys_timer_read());
 		timer_set_offset(vcpu_ptimer(vcpu), 0);

arch/arm64/kvm/arch_timer.c int kvm_timer_enable(struct kvm_vcpu *vcpu) · line 1634

Quoted 10 lines
arch/arm64/kvm/arch_timer.c +7 -0
@@ -1600,6 +1625,13 @@ int kvm_timer_enable(struct kvm_vcpu *vcpu)
 		return -EINVAL;
 	}
 
+	/*
+	 * We don't use mapped IRQs for Realms because the RMI doesn't allow
+	 * us setting the LR.HW bit in the VGIC.
+	 */
+	if (vcpu_is_rec(vcpu))
+		return 0;
+

If you can't set the HW bit, then use the existing infrastructure for similarly challenged systems. But I find this restriction hard to swallow. What is so special about the HW bit?

As it stands, I don't think this is acceptable, and I really want to know why you need to special-case the timer code.

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

Re: [PATCH v15 13/37] KVM: arm64: CCA: Support timers in realm RECs

Quoted 48 lines · Marc Zyngier
Quoted 46 lines · Steven Price

The RMM keeps track of the timer while the realm REC is running, but on exit to the normal world KVM is responsible for handling the timers.

A later patch adds the support for propagating the timer values from the exit data structure and calling kvm_realm_timers_update().

---
Changes since v14:
* Special case in kvm_timer_vcpu_load()/kvm_timer_vcpu_put() the timer handling.
Changes since v12:
* Adapt to upstream changes.
Changes since v11:
* Drop the kvm_is_realm() check from timer_set_offset(). We already ensure that the offset is 0 when calling the function.
Changes since v10:
* KVM_CAP_COUNTER_OFFSET is now already hidden by a previous patch.
Changes since v9:
* No need to move the call to kvm_timer_unblocking() in kvm_timer_vcpu_load().
Changes since v7:
* Hide KVM_CAP_COUNTER_OFFSET for realm guests.

---
 arch/arm64/kvm/arch_timer.c  | 38 +++++++++++++++++++++++++++++++++---
 include/kvm/arm_arch_timer.h |  2 ++
 2 files changed, 37 insertions(+), 3 deletions(-)
arch/arm64/kvm/arch_timer.c +9 -0
index 4155fe89b58a..fdd68f1f5b7b 100644
@@ -482,6 +482,20 @@ static void kvm_timer_update_irq(struct kvm_vcpu *vcpu, bool new_level,
 			    timer_ctx);
 }
 
+void kvm_realm_timers_update(struct kvm_vcpu *vcpu)
+{
+	struct arch_timer_cpu *arch_timer = &vcpu->arch.timer_cpu;
+	int i;
+
+	for (i = 0; i < NR_KVM_EL0_TIMERS; i++) {
+		struct arch_timer_context *timer = &arch_timer->timers[i];
+		bool status = timer_get_ctl(timer) & ARCH_TIMER_CTRL_IT_STAT;
+		bool level = kvm_timer_enabled(timer) && status;
Quoted 8 lines

arch/arm64/kvm/arch_timer.c static void kvm_timer_update_irq(struct kvm_vcpu *vcpu, bool new_level, · line 498

Quoted 5 lines
arch/arm64/kvm/arch_timer.c +5 -0
+
+		kvm_timer_update_irq(vcpu, level, timer);
+	}
+}
+

Why do we need this? What is so special about CCA that it cannot use the existing timer flow?

CCA is a little special because the timer context is owned by the RMM while the realm is executing. It's the RMM which actually loads/saves the timer registers not KVM.

The RMM returns some of the timer state on every exit, and the host is responsible for updating the interrupt status (as the host controls the GIC emulation).

Quoted 50 lines
Quoted 50 lines
arch/arm64/kvm/arch_timer.c +13 -2
 /* Only called for a fully emulated timer */
 static void timer_emulate(struct arch_timer_context *ctx)
 {
@@ -888,6 +902,11 @@ void kvm_timer_vcpu_load(struct kvm_vcpu *vcpu)
 	if (unlikely(!timer->enabled))
 		return;
 
+	if (vcpu_is_rec(vcpu)) {
+		kvm_timer_unblocking(vcpu);
+		return;
+	}
+
 	get_timer_map(vcpu, &map);
 
 	if (static_branch_likely(&has_gic_active_state)) {
@@ -923,6 +942,12 @@ void kvm_timer_vcpu_put(struct kvm_vcpu *vcpu)
 	if (unlikely(!timer->enabled))
 		return;
 
+	if (vcpu_is_rec(vcpu)) {
+		if (kvm_vcpu_is_blocking(vcpu))
+			kvm_timer_blocking(vcpu);
+		return;
+	}
+
 	get_timer_map(vcpu, &map);
 
 	timer_save_state(map.direct_vtimer);
@@ -1073,7 +1098,7 @@ static void timer_context_init(struct kvm_vcpu *vcpu, int timerid)
 
 	ctxt->timer_id = timerid;
 
-	if (!kvm_vm_is_protected(vcpu->kvm)) {
+	if (!kvm_vm_is_protected(vcpu->kvm) && !vcpu_is_rec(vcpu)) {
 		if (timerid == TIMER_VTIMER)
 			ctxt->offset.vm_offset = &kvm->arch.timer_data.voffset;
 		else
@@ -1104,7 +1129,7 @@ void kvm_timer_vcpu_init(struct kvm_vcpu *vcpu)
 		timer_context_init(vcpu, i);
 
 	/* Synchronize offsets across timers of a VM if not already provided */
-	if (!vcpu_is_protected(vcpu) &&
+	if (!vcpu_is_protected(vcpu) && !vcpu_is_rec(vcpu) &&
 	    !test_bit(KVM_ARCH_FLAG_VM_COUNTER_OFFSET, &vcpu->kvm->arch.flags)) {
 		timer_set_offset(vcpu_vtimer(vcpu), kvm_phys_timer_read());
 		timer_set_offset(vcpu_ptimer(vcpu), 0);
@@ -1600,6 +1625,13 @@ int kvm_timer_enable(struct kvm_vcpu *vcpu)
 		return -EINVAL;
 	}
 
Quoted 11 lines

arch/arm64/kvm/arch_timer.c int kvm_timer_enable(struct kvm_vcpu *vcpu) · line 1634

Quoted 7 lines
arch/arm64/kvm/arch_timer.c +7 -0
+	/*
+	 * We don't use mapped IRQs for Realms because the RMI doesn't allow
+	 * us setting the LR.HW bit in the VGIC.
+	 */
+	if (vcpu_is_rec(vcpu))
+		return 0;
+

If you can't set the HW bit, then use the existing infrastructure for similarly challenged systems. But I find this restriction hard to swallow. What is so special about the HW bit?

The spec provides this justification for not being able to set the bit:

XDMSDZ: The GICv3 architecture states that, if HW == '1' then the virtual interrupt must be linked to a physical interrupt whose state is Active, otherwise behavior is undefined. The RMM is unable to validate that invariant, so it imposes the constraint that HW == '0'.

Quoted 2 lines

As it stands, I don't think this is acceptable, and I really want to know why you need to special-case the timer code.

You're right, there's no need for this early return. Instead I should be able to implement an 'ops' for the realm guests which returns the VGIC_IRQ_SW_RESAMPLE flag.

Thanks,
Steve

maintainer
#32 lore raw

Re: [PATCH v15 13/37] KVM: arm64: CCA: Support timers in realm RECs

Quoted 59 lines · Steven Price
Quoted 48 lines · Marc Zyngier
Quoted 46 lines · Steven Price

The RMM keeps track of the timer while the realm REC is running, but on exit to the normal world KVM is responsible for handling the timers.

A later patch adds the support for propagating the timer values from the exit data structure and calling kvm_realm_timers_update().

---
Changes since v14:
* Special case in kvm_timer_vcpu_load()/kvm_timer_vcpu_put() the timer handling.
Changes since v12:
* Adapt to upstream changes.
Changes since v11:
* Drop the kvm_is_realm() check from timer_set_offset(). We already ensure that the offset is 0 when calling the function.
Changes since v10:
* KVM_CAP_COUNTER_OFFSET is now already hidden by a previous patch.
Changes since v9:
* No need to move the call to kvm_timer_unblocking() in kvm_timer_vcpu_load().
Changes since v7:
* Hide KVM_CAP_COUNTER_OFFSET for realm guests.

---
 arch/arm64/kvm/arch_timer.c  | 38 +++++++++++++++++++++++++++++++++---
 include/kvm/arm_arch_timer.h |  2 ++
 2 files changed, 37 insertions(+), 3 deletions(-)
arch/arm64/kvm/arch_timer.c +9 -0
index 4155fe89b58a..fdd68f1f5b7b 100644
@@ -482,6 +482,20 @@ static void kvm_timer_update_irq(struct kvm_vcpu *vcpu, bool new_level,
 			    timer_ctx);
 }
 
+void kvm_realm_timers_update(struct kvm_vcpu *vcpu)
+{
+	struct arch_timer_cpu *arch_timer = &vcpu->arch.timer_cpu;
+	int i;
+
+	for (i = 0; i < NR_KVM_EL0_TIMERS; i++) {
+		struct arch_timer_context *timer = &arch_timer->timers[i];
+		bool status = timer_get_ctl(timer) & ARCH_TIMER_CTRL_IT_STAT;
+		bool level = kvm_timer_enabled(timer) && status;
Quoted 8 lines

arch/arm64/kvm/arch_timer.c static void kvm_timer_update_irq(struct kvm_vcpu *vcpu, bool new_level, · line 498

Quoted 5 lines
arch/arm64/kvm/arch_timer.c +5 -0
+
+		kvm_timer_update_irq(vcpu, level, timer);
+	}
+}
+

Why do we need this? What is so special about CCA that it cannot use the existing timer flow?

Quoted 7 lines

CCA is a little special because the timer context is owned by the RMM while the realm is executing. It's the RMM which actually loads/saves the timer registers not KVM.

The RMM returns some of the timer state on every exit, and the host is responsible for updating the interrupt status (as the host controls the GIC emulation).

But KVM relies on the timers being live when the vcpu is loaded. So the first port of call should be for CCA to adapt to KVM, and not the other way around.

You can always make sure that the timers are in the registers at the point where you reach the KVM code.

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

Re: [PATCH v15 13/37] KVM: arm64: CCA: Support timers in realm RECs

Quoted 69 lines · Marc Zyngier
Quoted 59 lines · Steven Price
Quoted 48 lines · Marc Zyngier
Quoted 46 lines · Steven Price

The RMM keeps track of the timer while the realm REC is running, but on exit to the normal world KVM is responsible for handling the timers.

A later patch adds the support for propagating the timer values from the exit data structure and calling kvm_realm_timers_update().

---
Changes since v14:
* Special case in kvm_timer_vcpu_load()/kvm_timer_vcpu_put() the timer handling.
Changes since v12:
* Adapt to upstream changes.
Changes since v11:
* Drop the kvm_is_realm() check from timer_set_offset(). We already ensure that the offset is 0 when calling the function.
Changes since v10:
* KVM_CAP_COUNTER_OFFSET is now already hidden by a previous patch.
Changes since v9:
* No need to move the call to kvm_timer_unblocking() in kvm_timer_vcpu_load().
Changes since v7:
* Hide KVM_CAP_COUNTER_OFFSET for realm guests.

---
 arch/arm64/kvm/arch_timer.c  | 38 +++++++++++++++++++++++++++++++++---
 include/kvm/arm_arch_timer.h |  2 ++
 2 files changed, 37 insertions(+), 3 deletions(-)
arch/arm64/kvm/arch_timer.c +9 -0
index 4155fe89b58a..fdd68f1f5b7b 100644
@@ -482,6 +482,20 @@ static void kvm_timer_update_irq(struct kvm_vcpu *vcpu, bool new_level,
 			    timer_ctx);
 }
 
+void kvm_realm_timers_update(struct kvm_vcpu *vcpu)
+{
+	struct arch_timer_cpu *arch_timer = &vcpu->arch.timer_cpu;
+	int i;
+
+	for (i = 0; i < NR_KVM_EL0_TIMERS; i++) {
+		struct arch_timer_context *timer = &arch_timer->timers[i];
+		bool status = timer_get_ctl(timer) & ARCH_TIMER_CTRL_IT_STAT;
+		bool level = kvm_timer_enabled(timer) && status;
Quoted 8 lines

arch/arm64/kvm/arch_timer.c static void kvm_timer_update_irq(struct kvm_vcpu *vcpu, bool new_level, · line 498

Quoted 5 lines
arch/arm64/kvm/arch_timer.c +5 -0
+
+		kvm_timer_update_irq(vcpu, level, timer);
+	}
+}
+

Why do we need this? What is so special about CCA that it cannot use the existing timer flow?

Quoted 7 lines

CCA is a little special because the timer context is owned by the RMM while the realm is executing. It's the RMM which actually loads/saves the timer registers not KVM.

The RMM returns some of the timer state on every exit, and the host is responsible for updating the interrupt status (as the host controls the GIC emulation).

Quoted 6 lines

But KVM relies on the timers being live when the vcpu is loaded. So the first port of call should be for CCA to adapt to KVM, and not the other way around.

You can always make sure that the timers are in the registers at the point where you reach the KVM code.

Indeed if you'd prefer that I can modify the code to load the timer state into the registers in the Linux CCA code before reaching the generic KVM code. It's a little weird from an overall point of view (the RMM saves the state into memory, and then Linux reloads it just to save it again), but I don't see any implementation issues.

But a quick go at implementing this does indeed seem to save us a bit of code, so I'll include this in the next posting.

Thanks,
Steve

#34 lore raw

PATCH v15 14/37 KVM: arm64: CCA: Handle realm enter/exit

In reply to Steven Price

Entering a realm is done using a SMC call to the RMM. On exit the exit-codes need to be handled slightly differently to the normal KVM path so define our own functions for realm enter/exit and hook them in if the guest is a realm guest.

---
Changes since v13:
* The RMM is now required to provide an ESR value with the correct information to emulate MMIO, so we no longer need to hardcode 0s in rec_exit_sys_reg().
* The PSCI changes mean that there is a potential race when turning on a VCPU which can cause a RMI_ERROR_REC return. Exit to user space with -EAGAIN in this case.
Changes since v12:
* Call guest_state_{enter,exit}_irqoff() around rmi_rec_enter().
* Add handling of the IRQ exception case where IRQs need to be briefly enabled before exiting guest timing.
Changes since v8:
* Introduce kvm_rec_pre_enter() called before entering an atomic section to handle operations that might require memory allocation (specifically completing a RIPAS change introduced in a later patch).
* Updates to align with upstream changes to hpfar_el2 which now (ab)uses HPFAR_EL2_NS as a valid flag.
* Fix exit reason when racing with PSCI shutdown to return KVM_EXIT_SHUTDOWN rather than KVM_EXIT_UNKNOWN.
Changes since v7:
* A return of 0 from kvm_handle_sys_reg() doesn't mean the register has been read (although that can never happen in the current code). Tidy up the condition to handle any future refactoring.
Changes since v6:
* Use vcpu_err() rather than pr_err/kvm_err when there is an associated vcpu to the error.
* Return -EFAULT for KVM_EXIT_MEMORY_FAULT as per the documentation for this exit type.
* Split code handling a RIPAS change triggered by the guest to the following patch.
Changes since v5:
* For a RIPAS_CHANGE request from the guest perform the actual RIPAS change on next entry rather than immediately on the exit. This allows the VMM to 'reject' a RIPAS change by refusing to continue scheduling.
Changes since v4:
* Rename handle_rme_exit() to handle_rec_exit()
* Move the loop to copy registers into the REC enter structure from the to rec_exit_handlers callbacks to kvm_rec_enter(). This fixes a bug where the handler exits to user space and user space wants to modify the GPRS.
* Some code rearrangement in rec_exit_ripas_change().
Changes since v2:
* realm_set_ipa_state() now provides an output parameter for the top_iap that was changed. Use this to signal the VMM with the correct range that has been transitioned.
* Adapt to previous patch changes.

---
 arch/arm64/include/asm/kvm_rmi.h |   4 +
 arch/arm64/kvm/Makefile          |   2 +-
 arch/arm64/kvm/arm.c             |  25 ++++-
 arch/arm64/kvm/rmi-exit.c        | 182 +++++++++++++++++++++++++++++++
 arch/arm64/kvm/rmi.c             |  42 +++++++
 5 files changed, 249 insertions(+), 6 deletions(-)
 create mode 100644 arch/arm64/kvm/rmi-exit.c
arch/arm64/include/asm/kvm_rmi.h +4 -0
index ccd09d55c69f..b1e4cf0f6803 100644
@@ -100,6 +100,10 @@ void kvm_destroy_realm(struct kvm *kvm);
 int kvm_realm_teardown_stage2(struct kvm *kvm);
 void kvm_destroy_rec(struct kvm_vcpu *vcpu);
 
+int kvm_rec_enter(struct kvm_vcpu *vcpu);
+int kvm_rec_pre_enter(struct kvm_vcpu *vcpu);
+int handle_rec_exit(struct kvm_vcpu *vcpu, int rec_run_status);
+
 static inline bool kvm_realm_is_private_address(struct realm *realm,
 						unsigned long addr)
 {
arch/arm64/kvm/Makefile +1 -1
index ed3cf30eb06e..4a2d52fdb6a2 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 rmi.o \
+	 vgic-sys-reg-v3.o fpsimd.o pkvm.o rmi.o rmi-exit.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 +20 -5
index 2959a1451232..534d33b7c67a 100644
@@ -1341,6 +1341,9 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 		if (ret > 0)
 			ret = check_vcpu_requests(vcpu);
 
+		if (ret > 0 && vcpu_is_rec(vcpu))
+			ret = kvm_rec_pre_enter(vcpu);
+
 		/*
 		 * Preparing the interrupts to be injected also
 		 * involves poking the GIC, which must be done in a
@@ -1388,7 +1391,10 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 		trace_kvm_entry(*vcpu_pc(vcpu));
 		guest_timing_enter_irqoff();
 
-		ret = kvm_arm_vcpu_enter_exit(vcpu);
+		if (vcpu_is_rec(vcpu))
+			ret = kvm_rec_enter(vcpu);
+		else
+			ret = kvm_arm_vcpu_enter_exit(vcpu);
 
 		vcpu->mode = OUTSIDE_GUEST_MODE;
 		vcpu->stat.exits++;
@@ -1434,7 +1440,8 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 		 * context synchronization event) is necessary to ensure that
 		 * pending interrupts are taken.
 		 */
-		if (ARM_EXCEPTION_CODE(ret) == ARM_EXCEPTION_IRQ) {
+		if ((!vcpu_is_rec(vcpu) && ARM_EXCEPTION_CODE(ret) == ARM_EXCEPTION_IRQ) ||
+		    (vcpu_is_rec(vcpu) && vcpu->arch.rec.run->exit.exit_reason == RMI_EXIT_IRQ)) {
 			local_irq_enable();
 			isb();
 			local_irq_disable();
@@ -1446,8 +1453,13 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 
 		trace_kvm_exit(ret, kvm_vcpu_trap_get_class(vcpu), *vcpu_pc(vcpu));
 
-		/* Exit types that need handling before we can be preempted */
-		handle_exit_early(vcpu, ret);
+		if (!vcpu_is_rec(vcpu)) {
+			/*
+			 * Exit types that need handling before we can be
+			 * preempted
+			 */
+			handle_exit_early(vcpu, ret);
+		}
 
 		kvm_nested_sync_hwstate(vcpu);
 
@@ -1472,7 +1484,10 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 			ret = ARM_EXCEPTION_IL;
 		}
 
-		ret = handle_exit(vcpu, ret);
+		if (vcpu_is_rec(vcpu))
+			ret = handle_rec_exit(vcpu, ret);
+		else
+			ret = handle_exit(vcpu, ret);
 	}
 
 	if (unlikely(!irqchip_in_kernel(vcpu->kvm)))
arch/arm64/kvm/rmi-exit.c new file +182 -0

182 lines not on this page · raw message

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

48 lines not on this page · raw message

Signature · 1 line
2.43.0
#35 lore raw

Re: [PATCH v15 14/37] KVM: arm64: CCA: Handle realm enter/exit

Hi Steven, I have a comment about rec_exit_sys_reg() below.

Quoted 59 lines · Steven Price

Entering a realm is done using a SMC call to the RMM. On exit the exit-codes need to be handled slightly differently to the normal KVM path so define our own functions for realm enter/exit and hook them in if the guest is a realm guest.

---
Changes since v13:
* The RMM is now required to provide an ESR value with the correct information to emulate MMIO, so we no longer need to hardcode 0s in rec_exit_sys_reg().
* The PSCI changes mean that there is a potential race when turning on a VCPU which can cause a RMI_ERROR_REC return. Exit to user space with -EAGAIN in this case.
Changes since v12:
* Call guest_state_{enter,exit}_irqoff() around rmi_rec_enter().
* Add handling of the IRQ exception case where IRQs need to be briefly enabled before exiting guest timing.
Changes since v8:
* Introduce kvm_rec_pre_enter() called before entering an atomic section to handle operations that might require memory allocation (specifically completing a RIPAS change introduced in a later patch).
* Updates to align with upstream changes to hpfar_el2 which now (ab)uses HPFAR_EL2_NS as a valid flag.
* Fix exit reason when racing with PSCI shutdown to return KVM_EXIT_SHUTDOWN rather than KVM_EXIT_UNKNOWN.
Changes since v7:
* A return of 0 from kvm_handle_sys_reg() doesn't mean the register has been read (although that can never happen in the current code). Tidy up the condition to handle any future refactoring.
Changes since v6:
* Use vcpu_err() rather than pr_err/kvm_err when there is an associated vcpu to the error.
* Return -EFAULT for KVM_EXIT_MEMORY_FAULT as per the documentation for this exit type.
* Split code handling a RIPAS change triggered by the guest to the following patch.
Changes since v5:
* For a RIPAS_CHANGE request from the guest perform the actual RIPAS change on next entry rather than immediately on the exit. This allows the VMM to 'reject' a RIPAS change by refusing to continue scheduling.
Changes since v4:
* Rename handle_rme_exit() to handle_rec_exit()
* Move the loop to copy registers into the REC enter structure from the to rec_exit_handlers callbacks to kvm_rec_enter(). This fixes a bug where the handler exits to user space and user space wants to modify the GPRS.
* Some code rearrangement in rec_exit_ripas_change().
Changes since v2:
* realm_set_ipa_state() now provides an output parameter for the top_iap that was changed. Use this to signal the VMM with the correct range that has been transitioned.
* Adapt to previous patch changes.
---

[...]

arch/arm64/kvm/rmi-exit.c line 45

Quoted 10 lines
arch/arm64/kvm/rmi-exit.c new file +10 -0
+static int rec_exit_sys_reg(struct kvm_vcpu *vcpu)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+	unsigned long esr = kvm_vcpu_get_esr(vcpu);
+	int rt = kvm_vcpu_sys_get_rt(vcpu);
+	bool is_write = (esr & ESR_ELx_SYS64_ISS_DIR_MASK) == ESR_ELx_SYS64_ISS_DIR_WRITE;
+	int ret;
+
+	if (is_write)
+		vcpu_set_reg(vcpu, rt, rec->run->exit.gprs[rt]);

When rt is 31 (XZR), does exit.gprs[rt] trigger an out-of-bounds read since REC_RUN_GPRS is 31? Although the padding after the gprs means this OOB may not cause any practical issue, would it make sense to skip the access when rt is 31?

if (is_write && rt != 31)

    vcpu_set_reg(vcpu, rt, rec->run->exit.gprs[rt]);

arch/arm64/kvm/rmi-exit.c line 49

Quoted 4 lines
arch/arm64/kvm/rmi-exit.c new file +4 -0
+
+	ret = kvm_handle_sys_reg(vcpu);
+	if (!is_write)
+		rec->run->enter.gprs[rt] = vcpu_get_reg(vcpu, rt);

The same applies here:

if (!is_write && rt != 31)

    rec->run->enter.gprs[rt] = vcpu_get_reg(vcpu, rt);
Quoted 3 lines
arch/arm64/kvm/rmi-exit.c new file +3 -0
+
+	return ret;
+}
#36 lore raw

Re: [PATCH v15 14/37] KVM: arm64: CCA: Handle realm enter/exit

Quoted 78 lines · Kohei Enju

Hi Steven, I have a comment about rec_exit_sys_reg() below.

Quoted 59 lines · Steven Price

Entering a realm is done using a SMC call to the RMM. On exit the exit-codes need to be handled slightly differently to the normal KVM path so define our own functions for realm enter/exit and hook them in if the guest is a realm guest.

---
Changes since v13:
* The RMM is now required to provide an ESR value with the correct information to emulate MMIO, so we no longer need to hardcode 0s in rec_exit_sys_reg().
* The PSCI changes mean that there is a potential race when turning on a VCPU which can cause a RMI_ERROR_REC return. Exit to user space with -EAGAIN in this case.
Changes since v12:
* Call guest_state_{enter,exit}_irqoff() around rmi_rec_enter().
* Add handling of the IRQ exception case where IRQs need to be briefly enabled before exiting guest timing.
Changes since v8:
* Introduce kvm_rec_pre_enter() called before entering an atomic section to handle operations that might require memory allocation (specifically completing a RIPAS change introduced in a later patch).
* Updates to align with upstream changes to hpfar_el2 which now (ab)uses HPFAR_EL2_NS as a valid flag.
* Fix exit reason when racing with PSCI shutdown to return KVM_EXIT_SHUTDOWN rather than KVM_EXIT_UNKNOWN.
Changes since v7:
* A return of 0 from kvm_handle_sys_reg() doesn't mean the register has been read (although that can never happen in the current code). Tidy up the condition to handle any future refactoring.
Changes since v6:
* Use vcpu_err() rather than pr_err/kvm_err when there is an associated vcpu to the error.
* Return -EFAULT for KVM_EXIT_MEMORY_FAULT as per the documentation for this exit type.
* Split code handling a RIPAS change triggered by the guest to the following patch.
Changes since v5:
* For a RIPAS_CHANGE request from the guest perform the actual RIPAS change on next entry rather than immediately on the exit. This allows the VMM to 'reject' a RIPAS change by refusing to continue scheduling.
Changes since v4:
* Rename handle_rme_exit() to handle_rec_exit()
* Move the loop to copy registers into the REC enter structure from the to rec_exit_handlers callbacks to kvm_rec_enter(). This fixes a bug where the handler exits to user space and user space wants to modify the GPRS.
* Some code rearrangement in rec_exit_ripas_change().
Changes since v2:
* realm_set_ipa_state() now provides an output parameter for the top_iap that was changed. Use this to signal the VMM with the correct range that has been transitioned.
* Adapt to previous patch changes.
---

[...]

arch/arm64/kvm/rmi-exit.c line 45

Quoted 10 lines
arch/arm64/kvm/rmi-exit.c new file +10 -0
+static int rec_exit_sys_reg(struct kvm_vcpu *vcpu)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+	unsigned long esr = kvm_vcpu_get_esr(vcpu);
+	int rt = kvm_vcpu_sys_get_rt(vcpu);
+	bool is_write = (esr & ESR_ELx_SYS64_ISS_DIR_MASK) == ESR_ELx_SYS64_ISS_DIR_WRITE;
+	int ret;
+
+	if (is_write)
+		vcpu_set_reg(vcpu, rt, rec->run->exit.gprs[rt]);

When rt is 31 (XZR), does exit.gprs[rt] trigger an out-of-bounds read since REC_RUN_GPRS is 31? Although the padding after the gprs means this OOB may not cause any practical issue, would it make sense to skip the access when rt is 31?

Quoted 2 lines

if (is_write && rt != 31)

    vcpu_set_reg(vcpu, rt, rec->run->exit.gprs[rt]);

Very true - as you say in practise this isn't a big issue because vcpu_set_reg() is a no-op, so it's just a read of padding. But definitely worth fixing.

Quoted 9 lines

arch/arm64/kvm/rmi-exit.c line 49

Quoted 4 lines
arch/arm64/kvm/rmi-exit.c new file +4 -0
+
+	ret = kvm_handle_sys_reg(vcpu);
+	if (!is_write)
+		rec->run->enter.gprs[rt] = vcpu_get_reg(vcpu, rt);

The same applies here:

if (!is_write && rt != 31)

    rec->run->enter.gprs[rt] = vcpu_get_reg(vcpu, rt);

And the same here - a zero written into the padding.

Thanks for the review!

Steve

Quoted 3 lines
Quoted 3 lines
arch/arm64/kvm/rmi-exit.c new file +3 -0
+
+	return ret;
+}
#37 lore raw

Re: [PATCH v15 14/37] KVM: arm64: CCA: Handle realm enter/exit

Quoted 63 lines · Steven Price
Quoted 62 lines · Kohei Enju

Hi Steven, I have a comment about rec_exit_sys_reg() below.

Quoted 59 lines · Steven Price

Entering a realm is done using a SMC call to the RMM. On exit the exit-codes need to be handled slightly differently to the normal KVM path so define our own functions for realm enter/exit and hook them in if the guest is a realm guest.

---
Changes since v13:
* The RMM is now required to provide an ESR value with the correct information to emulate MMIO, so we no longer need to hardcode 0s in rec_exit_sys_reg().
* The PSCI changes mean that there is a potential race when turning on a VCPU which can cause a RMI_ERROR_REC return. Exit to user space with -EAGAIN in this case.
Changes since v12:
* Call guest_state_{enter,exit}_irqoff() around rmi_rec_enter().
* Add handling of the IRQ exception case where IRQs need to be briefly enabled before exiting guest timing.
Changes since v8:
* Introduce kvm_rec_pre_enter() called before entering an atomic section to handle operations that might require memory allocation (specifically completing a RIPAS change introduced in a later patch).
* Updates to align with upstream changes to hpfar_el2 which now (ab)uses HPFAR_EL2_NS as a valid flag.
* Fix exit reason when racing with PSCI shutdown to return KVM_EXIT_SHUTDOWN rather than KVM_EXIT_UNKNOWN.
Changes since v7:
* A return of 0 from kvm_handle_sys_reg() doesn't mean the register has been read (although that can never happen in the current code). Tidy up the condition to handle any future refactoring.
Changes since v6:
* Use vcpu_err() rather than pr_err/kvm_err when there is an associated vcpu to the error.
* Return -EFAULT for KVM_EXIT_MEMORY_FAULT as per the documentation for this exit type.
* Split code handling a RIPAS change triggered by the guest to the following patch.
Changes since v5:
* For a RIPAS_CHANGE request from the guest perform the actual RIPAS change on next entry rather than immediately on the exit. This allows the VMM to 'reject' a RIPAS change by refusing to continue scheduling.
Changes since v4:
* Rename handle_rme_exit() to handle_rec_exit()
* Move the loop to copy registers into the REC enter structure from the to rec_exit_handlers callbacks to kvm_rec_enter(). This fixes a bug where the handler exits to user space and user space wants to modify the GPRS.
* Some code rearrangement in rec_exit_ripas_change().
Changes since v2:
* realm_set_ipa_state() now provides an output parameter for the top_iap that was changed. Use this to signal the VMM with the correct range that has been transitioned.
* Adapt to previous patch changes.
---

[...]

Quoted 16 lines
Quoted 7 lines
Quoted 7 lines
arch/arm64/kvm/rmi-exit.c new file +7 -0
+static int rec_exit_sys_reg(struct kvm_vcpu *vcpu)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+	unsigned long esr = kvm_vcpu_get_esr(vcpu);
+	int rt = kvm_vcpu_sys_get_rt(vcpu);
+	bool is_write = (esr & ESR_ELx_SYS64_ISS_DIR_MASK) == ESR_ELx_SYS64_ISS_DIR_WRITE;
+	int ret;
Quoted 9 lines

arch/arm64/kvm/rmi-exit.c line 45

Quoted 3 lines
arch/arm64/kvm/rmi-exit.c new file +3 -0
+
+	if (is_write)
+		vcpu_set_reg(vcpu, rt, rec->run->exit.gprs[rt]);

When rt is 31 (XZR), does exit.gprs[rt] trigger an out-of-bounds read since REC_RUN_GPRS is 31? Although the padding after the gprs means this OOB may not cause any practical issue, would it make sense to skip the access when rt is 31?

RMM mandates that the ESR_ELx.ISS.RT == 0 on an exit due to System register access. See "A4.3.4.4 REC exit due to System register access"

So this shouldn't be a problem, but doesn't hurt to defend the host against a malicious RMM ?

Suzuki

Quoted 27 lines
Quoted 2 lines

if (is_write && rt != 31)

     vcpu_set_reg(vcpu, rt, rec->run->exit.gprs[rt]);

Very true - as you say in practise this isn't a big issue because vcpu_set_reg() is a no-op, so it's just a read of padding. But definitely worth fixing.

Quoted 9 lines

arch/arm64/kvm/rmi-exit.c line 49

Quoted 4 lines
arch/arm64/kvm/rmi-exit.c new file +4 -0
+
+	ret = kvm_handle_sys_reg(vcpu);
+	if (!is_write)
+		rec->run->enter.gprs[rt] = vcpu_get_reg(vcpu, rt);

The same applies here:

if (!is_write && rt != 31)

     rec->run->enter.gprs[rt] = vcpu_get_reg(vcpu, rt);

And the same here - a zero written into the padding.

Thanks for the review!

Steve

Quoted 3 lines
Quoted 3 lines
arch/arm64/kvm/rmi-exit.c new file +3 -0
+
+	return ret;
+}
#38 lore raw

Re: [PATCH v15 14/37] KVM: arm64: CCA: Handle realm enter/exit

Quoted 81 lines · Suzuki K Poulose
Quoted 63 lines · Steven Price
Quoted 62 lines · Kohei Enju

Hi Steven, I have a comment about rec_exit_sys_reg() below.

Quoted 59 lines · Steven Price

Entering a realm is done using a SMC call to the RMM. On exit the exit-codes need to be handled slightly differently to the normal KVM path so define our own functions for realm enter/exit and hook them in if the guest is a realm guest.

---
Changes since v13:
* The RMM is now required to provide an ESR value with the correct information to emulate MMIO, so we no longer need to hardcode 0s in rec_exit_sys_reg().
* The PSCI changes mean that there is a potential race when turning on a VCPU which can cause a RMI_ERROR_REC return. Exit to user space with -EAGAIN in this case.
Changes since v12:
* Call guest_state_{enter,exit}_irqoff() around rmi_rec_enter().
* Add handling of the IRQ exception case where IRQs need to be briefly enabled before exiting guest timing.
Changes since v8:
* Introduce kvm_rec_pre_enter() called before entering an atomic section to handle operations that might require memory allocation (specifically completing a RIPAS change introduced in a later patch).
* Updates to align with upstream changes to hpfar_el2 which now (ab)uses HPFAR_EL2_NS as a valid flag.
* Fix exit reason when racing with PSCI shutdown to return KVM_EXIT_SHUTDOWN rather than KVM_EXIT_UNKNOWN.
Changes since v7:
* A return of 0 from kvm_handle_sys_reg() doesn't mean the register has been read (although that can never happen in the current code). Tidy up the condition to handle any future refactoring.
Changes since v6:
* Use vcpu_err() rather than pr_err/kvm_err when there is an associated vcpu to the error.
* Return -EFAULT for KVM_EXIT_MEMORY_FAULT as per the documentation for this exit type.
* Split code handling a RIPAS change triggered by the guest to the following patch.
Changes since v5:
* For a RIPAS_CHANGE request from the guest perform the actual RIPAS change on next entry rather than immediately on the exit. This allows the VMM to 'reject' a RIPAS change by refusing to continue scheduling.
Changes since v4:
* Rename handle_rme_exit() to handle_rec_exit()
* Move the loop to copy registers into the REC enter structure from the to rec_exit_handlers callbacks to kvm_rec_enter(). This fixes a bug where the handler exits to user space and user space wants to modify the GPRS.
* Some code rearrangement in rec_exit_ripas_change().
Changes since v2:
* realm_set_ipa_state() now provides an output parameter for the top_iap that was changed. Use this to signal the VMM with the correct range that has been transitioned.
* Adapt to previous patch changes.
---

[...]

Quoted 16 lines
Quoted 7 lines
Quoted 7 lines
arch/arm64/kvm/rmi-exit.c new file +7 -0
+static int rec_exit_sys_reg(struct kvm_vcpu *vcpu)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+	unsigned long esr = kvm_vcpu_get_esr(vcpu);
+	int rt = kvm_vcpu_sys_get_rt(vcpu);
+	bool is_write = (esr & ESR_ELx_SYS64_ISS_DIR_MASK) == ESR_ELx_SYS64_ISS_DIR_WRITE;
+	int ret;
Quoted 9 lines

arch/arm64/kvm/rmi-exit.c line 45

Quoted 3 lines
arch/arm64/kvm/rmi-exit.c new file +3 -0
+
+	if (is_write)
+		vcpu_set_reg(vcpu, rt, rec->run->exit.gprs[rt]);

When rt is 31 (XZR), does exit.gprs[rt] trigger an out-of-bounds read since REC_RUN_GPRS is 31? Although the padding after the gprs means this OOB may not cause any practical issue, would it make sense to skip the access when rt is 31?

Quoted 5 lines

RMM mandates that the ESR_ELx.ISS.RT == 0 on an exit due to System register access. See "A4.3.4.4 REC exit due to System register access"

So this shouldn't be a problem, but doesn't hurt to defend the host against a malicious RMM ?

Ah, I missed that requirement. The changelog and the old RMM implementation led me to mistakenly assume tat Rt could be non-zero.

Then special-casing Rt == 31 doesn't really make sense. So keeping the code as it is seems fine to me:)

Thanks,
Kohei

Quoted 33 lines

Suzuki

Quoted 27 lines
Quoted 2 lines

if (is_write && rt != 31)

     vcpu_set_reg(vcpu, rt, rec->run->exit.gprs[rt]);

Very true - as you say in practise this isn't a big issue because vcpu_set_reg() is a no-op, so it's just a read of padding. But definitely worth fixing.

Quoted 9 lines

arch/arm64/kvm/rmi-exit.c line 49

Quoted 4 lines
arch/arm64/kvm/rmi-exit.c new file +4 -0
+
+	ret = kvm_handle_sys_reg(vcpu);
+	if (!is_write)
+		rec->run->enter.gprs[rt] = vcpu_get_reg(vcpu, rt);

The same applies here:

if (!is_write && rt != 31)

     rec->run->enter.gprs[rt] = vcpu_get_reg(vcpu, rt);

And the same here - a zero written into the padding.

Thanks for the review!

Steve

Quoted 3 lines
Quoted 3 lines
arch/arm64/kvm/rmi-exit.c new file +3 -0
+
+	return ret;
+}
maintainer
#39 lore raw

Re: [PATCH v15 14/37] KVM: arm64: CCA: Handle realm enter/exit

In reply to Steven Price
Quoted 5 lines · Steven Price

Entering a realm is done using a SMC call to the RMM. On exit the exit-codes need to be handled slightly differently to the normal KVM path so define our own functions for realm enter/exit and hook them in if the guest is a realm guest.

What is so different that you need to reinvent the wheel?

Quoted 93 lines

---
Changes since v13:
* The RMM is now required to provide an ESR value with the correct information to emulate MMIO, so we no longer need to hardcode 0s in rec_exit_sys_reg().
* The PSCI changes mean that there is a potential race when turning on a VCPU which can cause a RMI_ERROR_REC return. Exit to user space with -EAGAIN in this case.
Changes since v12:
* Call guest_state_{enter,exit}_irqoff() around rmi_rec_enter().
* Add handling of the IRQ exception case where IRQs need to be briefly enabled before exiting guest timing.
Changes since v8:
* Introduce kvm_rec_pre_enter() called before entering an atomic section to handle operations that might require memory allocation (specifically completing a RIPAS change introduced in a later patch).
* Updates to align with upstream changes to hpfar_el2 which now (ab)uses HPFAR_EL2_NS as a valid flag.
* Fix exit reason when racing with PSCI shutdown to return KVM_EXIT_SHUTDOWN rather than KVM_EXIT_UNKNOWN.
Changes since v7:
* A return of 0 from kvm_handle_sys_reg() doesn't mean the register has been read (although that can never happen in the current code). Tidy up the condition to handle any future refactoring.
Changes since v6:
* Use vcpu_err() rather than pr_err/kvm_err when there is an associated vcpu to the error.
* Return -EFAULT for KVM_EXIT_MEMORY_FAULT as per the documentation for this exit type.
* Split code handling a RIPAS change triggered by the guest to the following patch.
Changes since v5:
* For a RIPAS_CHANGE request from the guest perform the actual RIPAS change on next entry rather than immediately on the exit. This allows the VMM to 'reject' a RIPAS change by refusing to continue scheduling.
Changes since v4:
* Rename handle_rme_exit() to handle_rec_exit()
* Move the loop to copy registers into the REC enter structure from the to rec_exit_handlers callbacks to kvm_rec_enter(). This fixes a bug where the handler exits to user space and user space wants to modify the GPRS.
* Some code rearrangement in rec_exit_ripas_change().
Changes since v2:
* realm_set_ipa_state() now provides an output parameter for the top_iap that was changed. Use this to signal the VMM with the correct range that has been transitioned.
* Adapt to previous patch changes.

---
 arch/arm64/include/asm/kvm_rmi.h |   4 +
 arch/arm64/kvm/Makefile          |   2 +-
 arch/arm64/kvm/arm.c             |  25 ++++-
 arch/arm64/kvm/rmi-exit.c        | 182 +++++++++++++++++++++++++++++++
 arch/arm64/kvm/rmi.c             |  42 +++++++
 5 files changed, 249 insertions(+), 6 deletions(-)
 create mode 100644 arch/arm64/kvm/rmi-exit.c
arch/arm64/include/asm/kvm_rmi.h +4 -0
index ccd09d55c69f..b1e4cf0f6803 100644
@@ -100,6 +100,10 @@ void kvm_destroy_realm(struct kvm *kvm);
 int kvm_realm_teardown_stage2(struct kvm *kvm);
 void kvm_destroy_rec(struct kvm_vcpu *vcpu);
 
+int kvm_rec_enter(struct kvm_vcpu *vcpu);
+int kvm_rec_pre_enter(struct kvm_vcpu *vcpu);
+int handle_rec_exit(struct kvm_vcpu *vcpu, int rec_run_status);
+
 static inline bool kvm_realm_is_private_address(struct realm *realm,
 						unsigned long addr)
 {
arch/arm64/kvm/Makefile +1 -1
index ed3cf30eb06e..4a2d52fdb6a2 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 rmi.o \
+	 vgic-sys-reg-v3.o fpsimd.o pkvm.o rmi.o rmi-exit.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 2959a1451232..534d33b7c67a 100644

arch/arm64/kvm/arm.c int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu) · line 1346

Quoted 6 lines
arch/arm64/kvm/arm.c +3 -0
@@ -1341,6 +1341,9 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 		if (ret > 0)
 			ret = check_vcpu_requests(vcpu);
 
+		if (ret > 0 && vcpu_is_rec(vcpu))
+			ret = kvm_rec_pre_enter(vcpu);
+

What needs to be done at this stage? Why isn't this handled as a request? Or similarly to an MMIO return?

arch/arm64/kvm/arm.c int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu) · line 1397

Quoted 12 lines
arch/arm64/kvm/arm.c +4 -1
 		/*
 		 * Preparing the interrupts to be injected also
 		 * involves poking the GIC, which must be done in a
@@ -1388,7 +1391,10 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 		trace_kvm_entry(*vcpu_pc(vcpu));
 		guest_timing_enter_irqoff();
 
-		ret = kvm_arm_vcpu_enter_exit(vcpu);
+		if (vcpu_is_rec(vcpu))
+			ret = kvm_rec_enter(vcpu);
+		else
+			ret = kvm_arm_vcpu_enter_exit(vcpu);

This either sidesteps all the RCU EQS, context management and co, or duplicates it. Either way, that's no good.

arch/arm64/kvm/arm.c int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu) · line 1444

Quoted 10 lines
arch/arm64/kvm/arm.c +2 -1
 		vcpu->mode = OUTSIDE_GUEST_MODE;
 		vcpu->stat.exits++;
@@ -1434,7 +1440,8 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 		 * context synchronization event) is necessary to ensure that
 		 * pending interrupts are taken.
 		 */
-		if (ARM_EXCEPTION_CODE(ret) == ARM_EXCEPTION_IRQ) {
+		if ((!vcpu_is_rec(vcpu) && ARM_EXCEPTION_CODE(ret) == ARM_EXCEPTION_IRQ) ||
+		    (vcpu_is_rec(vcpu) && vcpu->arch.rec.run->exit.exit_reason == RMI_EXIT_IRQ)) {

No. Please adapt the CCA code so that what it returns has the exact same format as the non-CCA code, having the vcpu state placed where it matters.

Quoted 6 lines
arch/arm64/kvm/arm.c +0 -0
 			local_irq_enable();
 			isb();
 			local_irq_disable();
@@ -1446,8 +1453,13 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 
 		trace_kvm_exit(ret, kvm_vcpu_trap_get_class(vcpu), *vcpu_pc(vcpu));

arch/arm64/kvm/arm.c int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu) · line 1462

Quoted 10 lines
arch/arm64/kvm/arm.c +7 -2
 
-		/* Exit types that need handling before we can be preempted */
-		handle_exit_early(vcpu, ret);
+		if (!vcpu_is_rec(vcpu)) {
+			/*
+			 * Exit types that need handling before we can be
+			 * preempted
+			 */
+			handle_exit_early(vcpu, ret);
+		}

Same thing.

arch/arm64/kvm/arm.c int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu) · line 1490

Quoted 12 lines
arch/arm64/kvm/arm.c +4 -1
 		kvm_nested_sync_hwstate(vcpu);
 
@@ -1472,7 +1484,10 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 			ret = ARM_EXCEPTION_IL;
 		}
 
-		ret = handle_exit(vcpu, ret);
+		if (vcpu_is_rec(vcpu))
+			ret = handle_rec_exit(vcpu, ret);
+		else
+			ret = handle_exit(vcpu, ret);

And same thing here as well.

Quoted 21 lines
arch/arm64/kvm/arm.c +0 -0
 	}
 
 	if (unlikely(!irqchip_in_kernel(vcpu->kvm)))
arch/arm64/kvm/rmi-exit.c new file +12 -0
new file mode 100644
index 000000000000..973250563d7b
@@ -0,0 +1,182 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (C) 2023-2026 ARM Ltd.
+ */
+
+#include <linux/kvm_host.h>
+#include <kvm/arm_hypercalls.h>
+#include <kvm/arm_psci.h>
+
+#include <linux/arm-smccc-rmi.h>
+#include <asm/kvm_emulate.h>
+#include <asm/kvm_rmi.h>

arch/arm64/kvm/rmi-exit.c line 22

Quoted 10 lines
arch/arm64/kvm/rmi-exit.c new file +10 -0
+#include <asm/kvm_mmu.h>
+
+typedef int (*exit_handler_fn)(struct kvm_vcpu *vcpu);
+
+static int rec_exit_reason_notimpl(struct kvm_vcpu *vcpu)
+{
+	vcpu_err(vcpu, "Unhandled exit reason from realm (ESR: %#llx)\n",
+		 kvm_vcpu_get_esr(vcpu));
+	return -ENXIO;
+}

This should mark the VM dead.

arch/arm64/kvm/rmi-exit.c line 34

Quoted 12 lines
arch/arm64/kvm/rmi-exit.c new file +12 -0
+
+static int rec_exit_sync_dabt(struct kvm_vcpu *vcpu)
+{
+	return kvm_handle_guest_abort(vcpu);
+}
+
+static int rec_exit_sync_iabt(struct kvm_vcpu *vcpu)
+{
+	vcpu_err(vcpu, "Unhandled instruction abort (ESR: %#llx).\n",
+		 kvm_vcpu_get_esr(vcpu));
+	return -ENXIO;
+}

If you can't handle it, why do you specify a handler? isn't the default handler enough?

Quoted 15 lines
arch/arm64/kvm/rmi-exit.c new file +15 -0
+
+static int rec_exit_sys_reg(struct kvm_vcpu *vcpu)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+	unsigned long esr = kvm_vcpu_get_esr(vcpu);
+	int rt = kvm_vcpu_sys_get_rt(vcpu);
+	bool is_write = (esr & ESR_ELx_SYS64_ISS_DIR_MASK) == ESR_ELx_SYS64_ISS_DIR_WRITE;
+	int ret;
+
+	if (is_write)
+		vcpu_set_reg(vcpu, rt, rec->run->exit.gprs[rt]);
+
+	ret = kvm_handle_sys_reg(vcpu);
+	if (!is_write)
+		rec->run->enter.gprs[rt] = vcpu_get_reg(vcpu, rt);

arch/arm64/kvm/rmi-exit.c line 59

Quoted 10 lines
arch/arm64/kvm/rmi-exit.c new file +10 -0
+
+	return ret;
+}
+
+static exit_handler_fn rec_exit_handlers[] = {
+	[0 ... ESR_ELx_EC_MAX]	= rec_exit_reason_notimpl,
+	[ESR_ELx_EC_SYS64]	= rec_exit_sys_reg,
+	[ESR_ELx_EC_DABT_LOW]	= rec_exit_sync_dabt,
+	[ESR_ELx_EC_IABT_LOW]	= rec_exit_sync_iabt
+};

Frankly, none of that should exist. You should simply populate the state in the vcpu, and let the normal handlers run.

Quoted 41 lines
arch/arm64/kvm/rmi-exit.c new file +41 -0
+
+static int rec_exit_psci(struct kvm_vcpu *vcpu)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+	int i;
+
+	for (i = 0; i < REC_RUN_GPRS; i++)
+		vcpu_set_reg(vcpu, i, rec->run->exit.gprs[i]);
+
+	return kvm_smccc_call_handler(vcpu);
+}
+
+static int rec_exit_ripas_change(struct kvm_vcpu *vcpu)
+{
+	struct kvm *kvm = vcpu->kvm;
+	struct realm *realm = &kvm->arch.realm;
+	struct realm_rec *rec = &vcpu->arch.rec;
+	unsigned long base = rec->run->exit.ripas_base;
+	unsigned long top = rec->run->exit.ripas_top;
+	unsigned long ripas = rec->run->exit.ripas_value;
+
+	if (!kvm_realm_is_private_address(realm, base) ||
+	    !kvm_realm_is_private_address(realm, top - 1)) {
+		vcpu_err(vcpu, "Invalid RIPAS_CHANGE for %#lx - %#lx, ripas: %#lx\n",
+			 base, top, ripas);
+		/* Set RMI_REJECT bit */
+		rec->run->enter.flags = REC_ENTER_FLAG_RIPAS_RESPONSE;
+		return -EINVAL;
+	}
+
+	/* Exit to VMM, the actual RIPAS change is done on next entry */
+	kvm_prepare_memory_fault_exit(vcpu, base, top - base, false, false,
+				      ripas == RMI_RAM);
+
+	/*
+	 * KVM_EXIT_MEMORY_FAULT requires an return code of -EFAULT, see the
+	 * API documentation
+	 */
+	return -EFAULT;
+}
+

arch/arm64/kvm/rmi-exit.c line 110

Quoted 10 lines
arch/arm64/kvm/rmi-exit.c new file +10 -0
+static void update_arch_timer_irq_lines(struct kvm_vcpu *vcpu)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+
+	__vcpu_assign_sys_reg(vcpu, CNTV_CTL_EL0, rec->run->exit.cntv_ctl);
+	__vcpu_assign_sys_reg(vcpu, CNTV_CVAL_EL0, rec->run->exit.cntv_cval);
+	__vcpu_assign_sys_reg(vcpu, CNTP_CTL_EL0, rec->run->exit.cntp_ctl);
+	__vcpu_assign_sys_reg(vcpu, CNTP_CVAL_EL0, rec->run->exit.cntp_cval);
+
+	kvm_realm_timers_update(vcpu);

Why is that saved to memory? The expectations are that the HW timers are live when the guest state is loaded.

Quoted 62 lines
arch/arm64/kvm/rmi-exit.c new file +62 -0
+}
+
+/*
+ * Return > 0 to return to guest, < 0 on error, 0 (and set exit_reason) on
+ * proper exit to userspace.
+ */
+int handle_rec_exit(struct kvm_vcpu *vcpu, int rec_run_ret)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+	u8 esr_ec = ESR_ELx_EC(rec->run->exit.esr);
+	unsigned long status, index;
+
+	status = RMI_RETURN_STATUS(rec_run_ret);
+	index = RMI_RETURN_INDEX(rec_run_ret);
+
+	/*
+	 * If a PSCI_SYSTEM_OFF request raced with a vcpu executing, we might
+	 * see the following status code and index indicating an attempt to run
+	 * a REC when the RD state is SYSTEM_OFF.  In this case, we just need to
+	 * return to user space which can deal with the system event or will try
+	 * to run the KVM VCPU again, at which point we will no longer attempt
+	 * to enter the Realm because we will have a sleep request pending on
+	 * the VCPU as a result of KVM's PSCI handling.
+	 */
+	if (status == RMI_ERROR_REALM) {
+		vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
+		return 0;
+	}
+
+	/*
+	 * If a VCPU has been turned on, but the REC state hasn't been updated
+	 * we may experience RMI_ERROR_REC. Exit to the userspace with -EAGAIN
+	 * for a retry.
+	 */
+	if (status == RMI_ERROR_REC)
+		return -EAGAIN;
+	if (rec_run_ret)
+		return -ENXIO;
+
+	vcpu->arch.fault.esr_el2 = rec->run->exit.esr;
+	vcpu->arch.fault.far_el2 = rec->run->exit.far;
+	/* HPFAR_EL2 is only valid for RMI_EXIT_SYNC */
+	vcpu->arch.fault.hpfar_el2 = 0;
+
+	update_arch_timer_irq_lines(vcpu);
+
+	/* Reset the emulation flags for the next run of the REC */
+	rec->run->enter.flags = 0;
+
+	switch (rec->run->exit.exit_reason) {
+	case RMI_EXIT_SYNC:
+		/*
+		 * HPFAR_EL2_NS is hijacked to indicate a valid HPFAR value,
+		 * see __get_fault_info()
+		 */
+		vcpu->arch.fault.hpfar_el2 = rec->run->exit.hpfar | HPFAR_EL2_NS;
+		return rec_exit_handlers[esr_ec](vcpu);
+	case RMI_EXIT_IRQ:
+	case RMI_EXIT_FIQ:
+	case RMI_EXIT_SERROR:
+		return 1;
+	case RMI_EXIT_PSCI:

arch/arm64/kvm/rmi-exit.c line 182

Quoted 10 lines
arch/arm64/kvm/rmi-exit.c new file +10 -0
+		return rec_exit_psci(vcpu);
+	case RMI_EXIT_RIPAS_CHANGE:
+		return rec_exit_ripas_change(vcpu);
+	}
+
+	kvm_pr_unimpl("Unsupported exit reason: %u\n",
+		      rec->run->exit.exit_reason);
+	vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
+	return 0;
+}

-ETOOMUCHCODE. Please rework this so that this is modelled after the
existing KVM code. Extra handling (such as the other RMI_EXIT* reasons) can be treated as if they were an HVC call from the guest.

Quoted 16 lines
arch/arm64/kvm/rmi.c +8 -0
index aa97ad5fd7e9..430b82c02d15 100644
@@ -203,6 +203,48 @@ int kvm_realm_teardown_stage2(struct kvm *kvm)
 	return realm_destroy_rtts(kvm);
 }
 
+/*
+ * kvm_rec_pre_enter - Complete operations before entering a REC
+ *
+ * Some operations require work to be completed before entering a realm. That
+ * work may require memory allocation so cannot be done in the kvm_rec_enter()
+ * call.
+ *
+ * Return: 1 if we should enter the guest

arch/arm64/kvm/rmi.c int kvm_realm_teardown_stage2(struct kvm *kvm) · line 223

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+ *	   0 if we should exit to userspace
+ *	   < 0 if we should exit to userspace, where the return value indicates
+ *	   an error
+ */
+int kvm_rec_pre_enter(struct kvm_vcpu *vcpu)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+
+	if (kvm_realm_state(vcpu->kvm) != REALM_STATE_ACTIVE)
+		return -EINVAL;

Do you really need to check for this in the run loop?

arch/arm64/kvm/rmi.c int kvm_realm_teardown_stage2(struct kvm *kvm) · line 229

Quoted 6 lines
arch/arm64/kvm/rmi.c +6 -0
+
+	switch (rec->run->exit.exit_reason) {
+	case RMI_EXIT_HOST_CALL:
+		for (int i = 0; i < REC_RUN_GPRS; i++)
+			rec->run->enter.gprs[i] = vcpu_get_reg(vcpu, i);
+		break;

If this only happens on returning to the guest from a host call, this definitely can be done as a request.

arch/arm64/kvm/rmi.c int kvm_realm_teardown_stage2(struct kvm *kvm) · line 242

Quoted 13 lines
arch/arm64/kvm/rmi.c +13 -0
+	}
+
+	return 1;
+}
+
+int noinstr kvm_rec_enter(struct kvm_vcpu *vcpu)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+	int ret;
+
+	guest_state_enter_irqoff();
+	ret = rmi_rec_enter(virt_to_phys(rec->rec_page),
+			    virt_to_phys(rec->run));

Why don't you keep the PAs around instead? This should be merged into kvm_arm_vcpu_enter_exit().

arch/arm64/kvm/rmi.c int kvm_realm_teardown_stage2(struct kvm *kvm) · line 250

Quoted 8 lines
arch/arm64/kvm/rmi.c +5 -0
+	guest_state_exit_irqoff();
+
+	return ret;
+}
+
 static int __maybe_unused kvm_create_rec(struct kvm_vcpu *vcpu)
 {
 	struct user_pt_regs *vcpu_regs = vcpu_gp_regs(vcpu);

Thanks,

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

Re: [PATCH v15 14/37] KVM: arm64: CCA: Handle realm enter/exit

Hi Marc,

Thanks for the detailed review, comments below.

Quoted 9 lines · Marc Zyngier
Quoted 5 lines · Steven Price

Entering a realm is done using a SMC call to the RMM. On exit the exit-codes need to be handled slightly differently to the normal KVM path so define our own functions for realm enter/exit and hook them in if the guest is a realm guest.

What is so different that you need to reinvent the wheel?

Fair point - there's a bunch of differences, but CCA could definitely fit in better.

Quoted 96 lines
Quoted 96 lines

---
Changes since v13:
* The RMM is now required to provide an ESR value with the correct information to emulate MMIO, so we no longer need to hardcode 0s in rec_exit_sys_reg().
* The PSCI changes mean that there is a potential race when turning on a VCPU which can cause a RMI_ERROR_REC return. Exit to user space with -EAGAIN in this case.
Changes since v12:
* Call guest_state_{enter,exit}_irqoff() around rmi_rec_enter().
* Add handling of the IRQ exception case where IRQs need to be briefly enabled before exiting guest timing.
Changes since v8:
* Introduce kvm_rec_pre_enter() called before entering an atomic section to handle operations that might require memory allocation (specifically completing a RIPAS change introduced in a later patch).
* Updates to align with upstream changes to hpfar_el2 which now (ab)uses HPFAR_EL2_NS as a valid flag.
* Fix exit reason when racing with PSCI shutdown to return KVM_EXIT_SHUTDOWN rather than KVM_EXIT_UNKNOWN.
Changes since v7:
* A return of 0 from kvm_handle_sys_reg() doesn't mean the register has been read (although that can never happen in the current code). Tidy up the condition to handle any future refactoring.
Changes since v6:
* Use vcpu_err() rather than pr_err/kvm_err when there is an associated vcpu to the error.
* Return -EFAULT for KVM_EXIT_MEMORY_FAULT as per the documentation for this exit type.
* Split code handling a RIPAS change triggered by the guest to the following patch.
Changes since v5:
* For a RIPAS_CHANGE request from the guest perform the actual RIPAS change on next entry rather than immediately on the exit. This allows the VMM to 'reject' a RIPAS change by refusing to continue scheduling.
Changes since v4:
* Rename handle_rme_exit() to handle_rec_exit()
* Move the loop to copy registers into the REC enter structure from the to rec_exit_handlers callbacks to kvm_rec_enter(). This fixes a bug where the handler exits to user space and user space wants to modify the GPRS.
* Some code rearrangement in rec_exit_ripas_change().
Changes since v2:
* realm_set_ipa_state() now provides an output parameter for the top_iap that was changed. Use this to signal the VMM with the correct range that has been transitioned.
* Adapt to previous patch changes.

---
 arch/arm64/include/asm/kvm_rmi.h |   4 +
 arch/arm64/kvm/Makefile          |   2 +-
 arch/arm64/kvm/arm.c             |  25 ++++-
 arch/arm64/kvm/rmi-exit.c        | 182 +++++++++++++++++++++++++++++++
 arch/arm64/kvm/rmi.c             |  42 +++++++
 5 files changed, 249 insertions(+), 6 deletions(-)
 create mode 100644 arch/arm64/kvm/rmi-exit.c
arch/arm64/include/asm/kvm_rmi.h +4 -0
index ccd09d55c69f..b1e4cf0f6803 100644
@@ -100,6 +100,10 @@ void kvm_destroy_realm(struct kvm *kvm);
 int kvm_realm_teardown_stage2(struct kvm *kvm);
 void kvm_destroy_rec(struct kvm_vcpu *vcpu);
 
+int kvm_rec_enter(struct kvm_vcpu *vcpu);
+int kvm_rec_pre_enter(struct kvm_vcpu *vcpu);
+int handle_rec_exit(struct kvm_vcpu *vcpu, int rec_run_status);
+
 static inline bool kvm_realm_is_private_address(struct realm *realm,
 						unsigned long addr)
 {
arch/arm64/kvm/Makefile +1 -1
index ed3cf30eb06e..4a2d52fdb6a2 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 rmi.o \
+	 vgic-sys-reg-v3.o fpsimd.o pkvm.o rmi.o rmi-exit.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 2959a1451232..534d33b7c67a 100644
@@ -1341,6 +1341,9 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 		if (ret > 0)
 			ret = check_vcpu_requests(vcpu);
 
Quoted 6 lines

arch/arm64/kvm/arm.c int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu) · line 1346

Quoted 3 lines
arch/arm64/kvm/arm.c +3 -0
+		if (ret > 0 && vcpu_is_rec(vcpu))
+			ret = kvm_rec_pre_enter(vcpu);
+

What needs to be done at this stage? Why isn't this handled as a request? Or similarly to an MMIO return?

Good point - a request looks like a better solution. I'll have a go converting this to a new request.

Quoted 7 lines
Quoted 7 lines
arch/arm64/kvm/arm.c +0 -0
 		/*
 		 * Preparing the interrupts to be injected also
 		 * involves poking the GIC, which must be done in a
@@ -1388,7 +1391,10 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 		trace_kvm_entry(*vcpu_pc(vcpu));
 		guest_timing_enter_irqoff();
 
Quoted 8 lines

arch/arm64/kvm/arm.c int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu) · line 1397

Quoted 5 lines
arch/arm64/kvm/arm.c +4 -1
-		ret = kvm_arm_vcpu_enter_exit(vcpu);
+		if (vcpu_is_rec(vcpu))
+			ret = kvm_rec_enter(vcpu);
+		else
+			ret = kvm_arm_vcpu_enter_exit(vcpu);

This either sidesteps all the RCU EQS, context management and co, or duplicates it. Either way, that's no good.

Yeah, this isn't great - there's an issue here where we want to use the same infrastructure but we need to handle the different return codes from the RMM. I'll have a go at fixing this by moving this down into kvm_rec_enter() and mapping RMM result codes into KVM ones.

Quoted 5 lines
Quoted 5 lines
arch/arm64/kvm/arm.c +0 -0
 		vcpu->mode = OUTSIDE_GUEST_MODE;
 		vcpu->stat.exits++;
@@ -1434,7 +1440,8 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 		 * context synchronization event) is necessary to ensure that
 		 * pending interrupts are taken.
Quoted 8 lines

arch/arm64/kvm/arm.c int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu) · line 1444

Quoted 4 lines
arch/arm64/kvm/arm.c +2 -1
 		 */
-		if (ARM_EXCEPTION_CODE(ret) == ARM_EXCEPTION_IRQ) {
+		if ((!vcpu_is_rec(vcpu) && ARM_EXCEPTION_CODE(ret) == ARM_EXCEPTION_IRQ) ||
+		    (vcpu_is_rec(vcpu) && vcpu->arch.rec.run->exit.exit_reason == RMI_EXIT_IRQ)) {

No. Please adapt the CCA code so that what it returns has the exact same format as the non-CCA code, having the vcpu state placed where it matters.

Agreed - this is horrid, sorry. As above I'll fix this to map the result codes.

Quoted 26 lines
Quoted 6 lines
arch/arm64/kvm/arm.c +0 -0
 			local_irq_enable();
 			isb();
 			local_irq_disable();
@@ -1446,8 +1453,13 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 
 		trace_kvm_exit(ret, kvm_vcpu_trap_get_class(vcpu), *vcpu_pc(vcpu));

arch/arm64/kvm/arm.c int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu) · line 1462

Quoted 10 lines
arch/arm64/kvm/arm.c +7 -2
 
-		/* Exit types that need handling before we can be preempted */
-		handle_exit_early(vcpu, ret);
+		if (!vcpu_is_rec(vcpu)) {
+			/*
+			 * Exit types that need handling before we can be
+			 * preempted
+			 */
+			handle_exit_early(vcpu, ret);
+		}

Same thing.

Quoted 7 lines
arch/arm64/kvm/arm.c +0 -0
 		kvm_nested_sync_hwstate(vcpu);
 
@@ -1472,7 +1484,10 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 			ret = ARM_EXCEPTION_IL;
 		}
 
Quoted 7 lines

arch/arm64/kvm/arm.c int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu) · line 1490

Quoted 5 lines
arch/arm64/kvm/arm.c +4 -1
-		ret = handle_exit(vcpu, ret);
+		if (vcpu_is_rec(vcpu))
+			ret = handle_rec_exit(vcpu, ret);
+		else
+			ret = handle_exit(vcpu, ret);

And same thing here as well.

Agreed.

Quoted 25 lines
Quoted 25 lines
arch/arm64/kvm/arm.c +0 -0
 	}
 
 	if (unlikely(!irqchip_in_kernel(vcpu->kvm)))
arch/arm64/kvm/rmi-exit.c new file +16 -0
new file mode 100644
index 000000000000..973250563d7b
@@ -0,0 +1,182 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (C) 2023-2026 ARM Ltd.
+ */
+
+#include <linux/kvm_host.h>
+#include <kvm/arm_hypercalls.h>
+#include <kvm/arm_psci.h>
+
+#include <linux/arm-smccc-rmi.h>
+#include <asm/kvm_emulate.h>
+#include <asm/kvm_rmi.h>
+#include <asm/kvm_mmu.h>
+
+typedef int (*exit_handler_fn)(struct kvm_vcpu *vcpu);
+
Quoted 8 lines

arch/arm64/kvm/rmi-exit.c line 22

Quoted 6 lines
arch/arm64/kvm/rmi-exit.c new file +6 -0
+static int rec_exit_reason_notimpl(struct kvm_vcpu *vcpu)
+{
+	vcpu_err(vcpu, "Unhandled exit reason from realm (ESR: %#llx)\n",
+		 kvm_vcpu_get_esr(vcpu));
+	return -ENXIO;
+}

This should mark the VM dead.

Good point, thanks for pointing it out.

Quoted 7 lines
Quoted 7 lines
arch/arm64/kvm/rmi-exit.c new file +7 -0
+
+static int rec_exit_sync_dabt(struct kvm_vcpu *vcpu)
+{
+	return kvm_handle_guest_abort(vcpu);
+}
+
+static int rec_exit_sync_iabt(struct kvm_vcpu *vcpu)
Quoted 8 lines

arch/arm64/kvm/rmi-exit.c line 34

Quoted 5 lines
arch/arm64/kvm/rmi-exit.c new file +5 -0
+{
+	vcpu_err(vcpu, "Unhandled instruction abort (ESR: %#llx).\n",
+		 kvm_vcpu_get_esr(vcpu));
+	return -ENXIO;
+}

If you can't handle it, why do you specify a handler? isn't the default handler enough?

I think I can ditch the whole handler table as you mention below.

Quoted 20 lines
Quoted 20 lines
arch/arm64/kvm/rmi-exit.c new file +20 -0
+
+static int rec_exit_sys_reg(struct kvm_vcpu *vcpu)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+	unsigned long esr = kvm_vcpu_get_esr(vcpu);
+	int rt = kvm_vcpu_sys_get_rt(vcpu);
+	bool is_write = (esr & ESR_ELx_SYS64_ISS_DIR_MASK) == ESR_ELx_SYS64_ISS_DIR_WRITE;
+	int ret;
+
+	if (is_write)
+		vcpu_set_reg(vcpu, rt, rec->run->exit.gprs[rt]);
+
+	ret = kvm_handle_sys_reg(vcpu);
+	if (!is_write)
+		rec->run->enter.gprs[rt] = vcpu_get_reg(vcpu, rt);
+
+	return ret;
+}
+
+static exit_handler_fn rec_exit_handlers[] = {
Quoted 8 lines

arch/arm64/kvm/rmi-exit.c line 59

Quoted 5 lines
arch/arm64/kvm/rmi-exit.c new file +5 -0
+	[0 ... ESR_ELx_EC_MAX]	= rec_exit_reason_notimpl,
+	[ESR_ELx_EC_SYS64]	= rec_exit_sys_reg,
+	[ESR_ELx_EC_DABT_LOW]	= rec_exit_sync_dabt,
+	[ESR_ELx_EC_IABT_LOW]	= rec_exit_sync_iabt
+};

Frankly, none of that should exist. You should simply populate the state in the vcpu, and let the normal handlers run.

I'll have a go at doing that - I think it should be possible.

Quoted 46 lines
Quoted 46 lines
arch/arm64/kvm/rmi-exit.c new file +46 -0
+
+static int rec_exit_psci(struct kvm_vcpu *vcpu)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+	int i;
+
+	for (i = 0; i < REC_RUN_GPRS; i++)
+		vcpu_set_reg(vcpu, i, rec->run->exit.gprs[i]);
+
+	return kvm_smccc_call_handler(vcpu);
+}
+
+static int rec_exit_ripas_change(struct kvm_vcpu *vcpu)
+{
+	struct kvm *kvm = vcpu->kvm;
+	struct realm *realm = &kvm->arch.realm;
+	struct realm_rec *rec = &vcpu->arch.rec;
+	unsigned long base = rec->run->exit.ripas_base;
+	unsigned long top = rec->run->exit.ripas_top;
+	unsigned long ripas = rec->run->exit.ripas_value;
+
+	if (!kvm_realm_is_private_address(realm, base) ||
+	    !kvm_realm_is_private_address(realm, top - 1)) {
+		vcpu_err(vcpu, "Invalid RIPAS_CHANGE for %#lx - %#lx, ripas: %#lx\n",
+			 base, top, ripas);
+		/* Set RMI_REJECT bit */
+		rec->run->enter.flags = REC_ENTER_FLAG_RIPAS_RESPONSE;
+		return -EINVAL;
+	}
+
+	/* Exit to VMM, the actual RIPAS change is done on next entry */
+	kvm_prepare_memory_fault_exit(vcpu, base, top - base, false, false,
+				      ripas == RMI_RAM);
+
+	/*
+	 * KVM_EXIT_MEMORY_FAULT requires an return code of -EFAULT, see the
+	 * API documentation
+	 */
+	return -EFAULT;
+}
+
+static void update_arch_timer_irq_lines(struct kvm_vcpu *vcpu)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+
+	__vcpu_assign_sys_reg(vcpu, CNTV_CTL_EL0, rec->run->exit.cntv_ctl);
Quoted 8 lines

arch/arm64/kvm/rmi-exit.c line 110

Quoted 5 lines
arch/arm64/kvm/rmi-exit.c new file +5 -0
+	__vcpu_assign_sys_reg(vcpu, CNTV_CVAL_EL0, rec->run->exit.cntv_cval);
+	__vcpu_assign_sys_reg(vcpu, CNTP_CTL_EL0, rec->run->exit.cntp_ctl);
+	__vcpu_assign_sys_reg(vcpu, CNTP_CVAL_EL0, rec->run->exit.cntp_cval);
+
+	kvm_realm_timers_update(vcpu);

Why is that saved to memory? The expectations are that the HW timers are live when the guest state is loaded.

You mentioned this in the previous patch - I'm moving these to the hardware registers as you requested, so this will go.

Quoted 68 lines
Quoted 68 lines
arch/arm64/kvm/rmi-exit.c new file +68 -0
+}
+
+/*
+ * Return > 0 to return to guest, < 0 on error, 0 (and set exit_reason) on
+ * proper exit to userspace.
+ */
+int handle_rec_exit(struct kvm_vcpu *vcpu, int rec_run_ret)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+	u8 esr_ec = ESR_ELx_EC(rec->run->exit.esr);
+	unsigned long status, index;
+
+	status = RMI_RETURN_STATUS(rec_run_ret);
+	index = RMI_RETURN_INDEX(rec_run_ret);
+
+	/*
+	 * If a PSCI_SYSTEM_OFF request raced with a vcpu executing, we might
+	 * see the following status code and index indicating an attempt to run
+	 * a REC when the RD state is SYSTEM_OFF.  In this case, we just need to
+	 * return to user space which can deal with the system event or will try
+	 * to run the KVM VCPU again, at which point we will no longer attempt
+	 * to enter the Realm because we will have a sleep request pending on
+	 * the VCPU as a result of KVM's PSCI handling.
+	 */
+	if (status == RMI_ERROR_REALM) {
+		vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
+		return 0;
+	}
+
+	/*
+	 * If a VCPU has been turned on, but the REC state hasn't been updated
+	 * we may experience RMI_ERROR_REC. Exit to the userspace with -EAGAIN
+	 * for a retry.
+	 */
+	if (status == RMI_ERROR_REC)
+		return -EAGAIN;
+	if (rec_run_ret)
+		return -ENXIO;
+
+	vcpu->arch.fault.esr_el2 = rec->run->exit.esr;
+	vcpu->arch.fault.far_el2 = rec->run->exit.far;
+	/* HPFAR_EL2 is only valid for RMI_EXIT_SYNC */
+	vcpu->arch.fault.hpfar_el2 = 0;
+
+	update_arch_timer_irq_lines(vcpu);
+
+	/* Reset the emulation flags for the next run of the REC */
+	rec->run->enter.flags = 0;
+
+	switch (rec->run->exit.exit_reason) {
+	case RMI_EXIT_SYNC:
+		/*
+		 * HPFAR_EL2_NS is hijacked to indicate a valid HPFAR value,
+		 * see __get_fault_info()
+		 */
+		vcpu->arch.fault.hpfar_el2 = rec->run->exit.hpfar | HPFAR_EL2_NS;
+		return rec_exit_handlers[esr_ec](vcpu);
+	case RMI_EXIT_IRQ:
+	case RMI_EXIT_FIQ:
+	case RMI_EXIT_SERROR:
+		return 1;
+	case RMI_EXIT_PSCI:
+		return rec_exit_psci(vcpu);
+	case RMI_EXIT_RIPAS_CHANGE:
+		return rec_exit_ripas_change(vcpu);
+	}
+
+	kvm_pr_unimpl("Unsupported exit reason: %u\n",
Quoted 8 lines

arch/arm64/kvm/rmi-exit.c line 182

Quoted 4 lines
arch/arm64/kvm/rmi-exit.c new file +4 -0
+		      rec->run->exit.exit_reason);
+	vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
+	return 0;
+}

-ETOOMUCHCODE. Please rework this so that this is modelled after the
existing KVM code. Extra handling (such as the other RMI_EXIT* reasons) can be treated as if they were an HVC call from the guest.

Ok - treating it as an HVC call looks like it should work. Thanks for the suggestion.

Quoted 20 lines
Quoted 20 lines
arch/arm64/kvm/rmi.c +12 -0
index aa97ad5fd7e9..430b82c02d15 100644
@@ -203,6 +203,48 @@ int kvm_realm_teardown_stage2(struct kvm *kvm)
 	return realm_destroy_rtts(kvm);
 }
 
+/*
+ * kvm_rec_pre_enter - Complete operations before entering a REC
+ *
+ * Some operations require work to be completed before entering a realm. That
+ * work may require memory allocation so cannot be done in the kvm_rec_enter()
+ * call.
+ *
+ * Return: 1 if we should enter the guest
+ *	   0 if we should exit to userspace
+ *	   < 0 if we should exit to userspace, where the return value indicates
+ *	   an error
+ */
Quoted 8 lines

arch/arm64/kvm/rmi.c int kvm_realm_teardown_stage2(struct kvm *kvm) · line 223

Quoted 6 lines
arch/arm64/kvm/rmi.c +6 -0
+int kvm_rec_pre_enter(struct kvm_vcpu *vcpu)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
+
+	if (kvm_realm_state(vcpu->kvm) != REALM_STATE_ACTIVE)
+		return -EINVAL;

Do you really need to check for this in the run loop?

With the suggestion to use requests then I think this whole pre_enter concept can be removed. But agreed this is a bit of a silly check for every loop.

Quoted 9 lines

arch/arm64/kvm/rmi.c int kvm_realm_teardown_stage2(struct kvm *kvm) · line 229

Quoted 6 lines
arch/arm64/kvm/rmi.c +6 -0
+
+	switch (rec->run->exit.exit_reason) {
+	case RMI_EXIT_HOST_CALL:
+		for (int i = 0; i < REC_RUN_GPRS; i++)
+			rec->run->enter.gprs[i] = vcpu_get_reg(vcpu, i);
+		break;

If this only happens on returning to the guest from a host call, this definitely can be done as a request.

Ack.

Quoted 8 lines
Quoted 8 lines
arch/arm64/kvm/rmi.c +8 -0
+	}
+
+	return 1;
+}
+
+int noinstr kvm_rec_enter(struct kvm_vcpu *vcpu)
+{
+	struct realm_rec *rec = &vcpu->arch.rec;
Quoted 8 lines

arch/arm64/kvm/rmi.c int kvm_realm_teardown_stage2(struct kvm *kvm) · line 242

Quoted 5 lines
arch/arm64/kvm/rmi.c +5 -0
+	int ret;
+
+	guest_state_enter_irqoff();
+	ret = rmi_rec_enter(virt_to_phys(rec->rec_page),
+			    virt_to_phys(rec->run));

Why don't you keep the PAs around instead? This should be merged into kvm_arm_vcpu_enter_exit().

Ack

Quoted 12 lines

arch/arm64/kvm/rmi.c int kvm_realm_teardown_stage2(struct kvm *kvm) · line 250

Quoted 9 lines
arch/arm64/kvm/rmi.c +5 -0
+	guest_state_exit_irqoff();
+
+	return ret;
+}
+
 static int __maybe_unused kvm_create_rec(struct kvm_vcpu *vcpu)
 {
 	struct user_pt_regs *vcpu_regs = vcpu_gp_regs(vcpu);

Thanks,

Quoted 2 lines
	M.

Thanks for the review and suggestions!

Steve

#41 lore raw

PATCH v15 15/37 KVM: arm64: CCA: Handle RMI_EXIT_RIPAS_CHANGE

In reply to Steven Price

The guest can request that a region of its protected address space is switched between RIPAS_RAM and RIPAS_EMPTY (and back) using RSI_IPA_STATE_SET. This causes a guest exit with the RMI_EXIT_RIPAS_CHANGE code. We treat this as a request to convert a protected region to unprotected (or back), exiting to the VMM to make the necessary changes to the guest_memfd and memslot mappings. On the next entry the RIPAS changes are committed by making RMI_RTT_SET_RIPAS calls.

The VMM may wish to reject the RIPAS change requested by the guest. For now it can only do this by no longer scheduling the VCPU as we don't currently have a usecase for returning that rejection to the guest, but by postponing the RMI_RTT_SET_RIPAS changes to entry we leave the door open for adding a new ioctl in the future for this purpose.

---
Changes since v14:
* Use addition rather than bitwise OR for adding the shared_bit in realm_unmap_shared_range(), this handles the case where the region includes the last address (which means 'end' already has the bit set).
Changes since v13:
* Switch to the new RMI_RTT_UNPROT_UNMAP range-based API.
* Drop ugly hack for RMM bug which errored when the RIPAS was already set to the desired value.
Changes since v12:
* Switch to the new RMM v2.0 RMI_RTT_DATA_UNMAP which can unmap an address range.
Changes since v11:
* Combine the "Allow VMM to set RIPAS" patch into this one to avoid adding functions before they are used.
* Drop the CAP for setting RIPAS and adapt to changes from previous patches.
Changes since v10:
* Add comment explaining the assignment of rec->run->exit.ripas_base in kvm_complete_ripas_change().
Changes since v8:
* Make use of ripas_change() from a previous patch to implement realm_set_ipa_state().
* Update exit.ripas_base after a RIPAS change so that, if instead of entering the guest we exit to user space, we don't attempt to repeat the RIPAS change (triggering an error from the RMM).
Changes since v7:
* Rework the loop in realm_set_ipa_state() to make it clear when the 'next' output value of rmi_rtt_set_ripas() is used.
New patch for v7: The code was previously split awkwardly between two other patches.

---
 arch/arm64/include/asm/kvm_rmi.h |   6 +
 arch/arm64/kvm/mmu.c             |   8 +-
 arch/arm64/kvm/rmi.c             | 457 +++++++++++++++++++++++++++++++
 3 files changed, 468 insertions(+), 3 deletions(-)
arch/arm64/include/asm/kvm_rmi.h +6 -0
index b1e4cf0f6803..5461c49bea4d 100644
@@ -104,6 +104,12 @@ int kvm_rec_enter(struct kvm_vcpu *vcpu);
 int kvm_rec_pre_enter(struct kvm_vcpu *vcpu);
 int handle_rec_exit(struct kvm_vcpu *vcpu, int rec_run_status);
 
+void kvm_realm_unmap_range(struct kvm *kvm,
+			   unsigned long ipa,
+			   unsigned long size,
+			   bool unmap_private,
+			   bool may_block);
+
 static inline bool kvm_realm_is_private_address(struct realm *realm,
 						unsigned long addr)
 {
arch/arm64/kvm/mmu.c +5 -3
index cd06881c1497..dcc2ab08d0e4 100644
@@ -319,6 +319,7 @@ static void invalidate_icache_guest_page(void *va, size_t size)
  * @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
+ * @only_shared: If true then protected mappings should not be unmapped
  *
  * Clear a range of stage-2 mappings, lowering the various ref-counts.  Must
  * be called while holding mmu_lock (unless for freeing the stage2 pgd before
@@ -326,7 +327,7 @@ static void invalidate_icache_guest_page(void *va, size_t size)
  * with things behind our backs.
  */
 static void __unmap_stage2_range(struct kvm_s2_mmu *mmu, phys_addr_t start, u64 size,
-				 bool may_block)
+				 bool may_block, bool only_shared)
 {
 	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
 	phys_addr_t end = start + size;
@@ -343,7 +344,7 @@ void kvm_stage2_unmap_range(struct kvm_s2_mmu *mmu, phys_addr_t start,
 	if (kvm_vm_is_protected(kvm_s2_mmu_to_kvm(mmu)))
 		return;
 
-	__unmap_stage2_range(mmu, start, size, may_block);
+	__unmap_stage2_range(mmu, start, size, may_block, false);
 }
 
 void kvm_stage2_flush_range(struct kvm_s2_mmu *mmu, phys_addr_t addr, phys_addr_t end)
@@ -2467,7 +2468,8 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
 
 	__unmap_stage2_range(&kvm->arch.mmu, range->start << PAGE_SHIFT,
 			     (range->end - range->start) << PAGE_SHIFT,
-			     range->may_block);
+			     range->may_block,
+			     !(range->attr_filter & KVM_FILTER_PRIVATE));
 
 	kvm_nested_s2_unmap(kvm, range->may_block);
 	return false;
arch/arm64/kvm/rmi.c +457 -0

493 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer
#42 lore raw

Re: [PATCH v15 15/37] KVM: arm64: CCA: Handle RMI_EXIT_RIPAS_CHANGE

Quoted 77 lines · Steven Price

The guest can request that a region of its protected address space is switched between RIPAS_RAM and RIPAS_EMPTY (and back) using RSI_IPA_STATE_SET. This causes a guest exit with the RMI_EXIT_RIPAS_CHANGE code. We treat this as a request to convert a protected region to unprotected (or back), exiting to the VMM to make the necessary changes to the guest_memfd and memslot mappings. On the next entry the RIPAS changes are committed by making RMI_RTT_SET_RIPAS calls.

The VMM may wish to reject the RIPAS change requested by the guest. For now it can only do this by no longer scheduling the VCPU as we don't currently have a usecase for returning that rejection to the guest, but by postponing the RMI_RTT_SET_RIPAS changes to entry we leave the door open for adding a new ioctl in the future for this purpose.

---
Changes since v14:
* Use addition rather than bitwise OR for adding the shared_bit in realm_unmap_shared_range(), this handles the case where the region includes the last address (which means 'end' already has the bit set).
Changes since v13:
* Switch to the new RMI_RTT_UNPROT_UNMAP range-based API.
* Drop ugly hack for RMM bug which errored when the RIPAS was already set to the desired value.
Changes since v12:
* Switch to the new RMM v2.0 RMI_RTT_DATA_UNMAP which can unmap an address range.
Changes since v11:
* Combine the "Allow VMM to set RIPAS" patch into this one to avoid adding functions before they are used.
* Drop the CAP for setting RIPAS and adapt to changes from previous patches.
Changes since v10:
* Add comment explaining the assignment of rec->run->exit.ripas_base in kvm_complete_ripas_change().
Changes since v8:
* Make use of ripas_change() from a previous patch to implement realm_set_ipa_state().
* Update exit.ripas_base after a RIPAS change so that, if instead of entering the guest we exit to user space, we don't attempt to repeat the RIPAS change (triggering an error from the RMM).
Changes since v7:
* Rework the loop in realm_set_ipa_state() to make it clear when the 'next' output value of rmi_rtt_set_ripas() is used.
New patch for v7: The code was previously split awkwardly between two other patches.

---
 arch/arm64/include/asm/kvm_rmi.h |   6 +
 arch/arm64/kvm/mmu.c             |   8 +-
 arch/arm64/kvm/rmi.c             | 457 +++++++++++++++++++++++++++++++
 3 files changed, 468 insertions(+), 3 deletions(-)
arch/arm64/include/asm/kvm_rmi.h +6 -0
index b1e4cf0f6803..5461c49bea4d 100644
@@ -104,6 +104,12 @@ int kvm_rec_enter(struct kvm_vcpu *vcpu);
 int kvm_rec_pre_enter(struct kvm_vcpu *vcpu);
 int handle_rec_exit(struct kvm_vcpu *vcpu, int rec_run_status);
 
+void kvm_realm_unmap_range(struct kvm *kvm,
+			   unsigned long ipa,
+			   unsigned long size,
+			   bool unmap_private,
+			   bool may_block);
+
 static inline bool kvm_realm_is_private_address(struct realm *realm,
 						unsigned long addr)
 {
arch/arm64/kvm/mmu.c +0 -0
index cd06881c1497..dcc2ab08d0e4 100644

arch/arm64/kvm/mmu.c static void invalidate_icache_guest_page(void *va, size_t size) · line 323

Quoted 5 lines
arch/arm64/kvm/mmu.c +1 -0
@@ -319,6 +319,7 @@ static void invalidate_icache_guest_page(void *va, size_t size)
  * @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
+ * @only_shared: If true then protected mappings should not be unmapped
  *

I don't understand the need for this additional argument. Given that CCA imposes that shared and private are in non-overlapping ranges, why is it necessary to introduce this at the core of the S2 management code?

I'd expect that the CCA code could simply work out what range it needs to run on and keep the API intact.

arch/arm64/kvm/mmu.c static void invalidate_icache_guest_page(void *va, size_t size) · line 333

Quoted 11 lines
arch/arm64/kvm/mmu.c +1 -1
  * Clear a range of stage-2 mappings, lowering the various ref-counts.  Must
  * be called while holding mmu_lock (unless for freeing the stage2 pgd before
@@ -326,7 +327,7 @@ static void invalidate_icache_guest_page(void *va, size_t size)
  * with things behind our backs.
  */
 static void __unmap_stage2_range(struct kvm_s2_mmu *mmu, phys_addr_t start, u64 size,
-				 bool may_block)
+				 bool may_block, bool only_shared)
 {
 	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
 	phys_addr_t end = start + size;

So what is the *actual* change?

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

Re: [PATCH v15 15/37] KVM: arm64: CCA: Handle RMI_EXIT_RIPAS_CHANGE

Hi Marc,

I've just posted v16 before looking at these - I didn't want to delay posting before responding as I'm going to be on holiday for a week after today. Apologies that I haven't addressed these comments in v16.

Quoted 93 lines · Marc Zyngier
Quoted 77 lines · Steven Price

The guest can request that a region of its protected address space is switched between RIPAS_RAM and RIPAS_EMPTY (and back) using RSI_IPA_STATE_SET. This causes a guest exit with the RMI_EXIT_RIPAS_CHANGE code. We treat this as a request to convert a protected region to unprotected (or back), exiting to the VMM to make the necessary changes to the guest_memfd and memslot mappings. On the next entry the RIPAS changes are committed by making RMI_RTT_SET_RIPAS calls.

The VMM may wish to reject the RIPAS change requested by the guest. For now it can only do this by no longer scheduling the VCPU as we don't currently have a usecase for returning that rejection to the guest, but by postponing the RMI_RTT_SET_RIPAS changes to entry we leave the door open for adding a new ioctl in the future for this purpose.

---
Changes since v14:
* Use addition rather than bitwise OR for adding the shared_bit in realm_unmap_shared_range(), this handles the case where the region includes the last address (which means 'end' already has the bit set).
Changes since v13:
* Switch to the new RMI_RTT_UNPROT_UNMAP range-based API.
* Drop ugly hack for RMM bug which errored when the RIPAS was already set to the desired value.
Changes since v12:
* Switch to the new RMM v2.0 RMI_RTT_DATA_UNMAP which can unmap an address range.
Changes since v11:
* Combine the "Allow VMM to set RIPAS" patch into this one to avoid adding functions before they are used.
* Drop the CAP for setting RIPAS and adapt to changes from previous patches.
Changes since v10:
* Add comment explaining the assignment of rec->run->exit.ripas_base in kvm_complete_ripas_change().
Changes since v8:
* Make use of ripas_change() from a previous patch to implement realm_set_ipa_state().
* Update exit.ripas_base after a RIPAS change so that, if instead of entering the guest we exit to user space, we don't attempt to repeat the RIPAS change (triggering an error from the RMM).
Changes since v7:
* Rework the loop in realm_set_ipa_state() to make it clear when the 'next' output value of rmi_rtt_set_ripas() is used.
New patch for v7: The code was previously split awkwardly between two other patches.

---
 arch/arm64/include/asm/kvm_rmi.h |   6 +
 arch/arm64/kvm/mmu.c             |   8 +-
 arch/arm64/kvm/rmi.c             | 457 +++++++++++++++++++++++++++++++
 3 files changed, 468 insertions(+), 3 deletions(-)
arch/arm64/include/asm/kvm_rmi.h +6 -0
index b1e4cf0f6803..5461c49bea4d 100644
@@ -104,6 +104,12 @@ int kvm_rec_enter(struct kvm_vcpu *vcpu);
 int kvm_rec_pre_enter(struct kvm_vcpu *vcpu);
 int handle_rec_exit(struct kvm_vcpu *vcpu, int rec_run_status);
 
+void kvm_realm_unmap_range(struct kvm *kvm,
+			   unsigned long ipa,
+			   unsigned long size,
+			   bool unmap_private,
+			   bool may_block);
+
 static inline bool kvm_realm_is_private_address(struct realm *realm,
 						unsigned long addr)
 {
arch/arm64/kvm/mmu.c +0 -0
index cd06881c1497..dcc2ab08d0e4 100644

arch/arm64/kvm/mmu.c static void invalidate_icache_guest_page(void *va, size_t size) · line 323

Quoted 5 lines
arch/arm64/kvm/mmu.c +1 -0
@@ -319,6 +319,7 @@ static void invalidate_icache_guest_page(void *va, size_t size)
  * @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
+ * @only_shared: If true then protected mappings should not be unmapped
  *

I don't understand the need for this additional argument. Given that CCA imposes that shared and private are in non-overlapping ranges, why is it necessary to introduce this at the core of the S2 management code?

I'd expect that the CCA code could simply work out what range it needs to run on and keep the API intact.

Quoted 13 lines

arch/arm64/kvm/mmu.c static void invalidate_icache_guest_page(void *va, size_t size) · line 333

Quoted 11 lines
arch/arm64/kvm/mmu.c +1 -1
  * Clear a range of stage-2 mappings, lowering the various ref-counts.  Must
  * be called while holding mmu_lock (unless for freeing the stage2 pgd before
@@ -326,7 +327,7 @@ static void invalidate_icache_guest_page(void *va, size_t size)
  * with things behind our backs.
  */
 static void __unmap_stage2_range(struct kvm_s2_mmu *mmu, phys_addr_t start, u64 size,
-				 bool may_block)
+				 bool may_block, bool only_shared)
 {
 	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
 	phys_addr_t end = start + size;

So what is the *actual* change?

It looks like I've screwed up what goes in which patch. The real change is in patch 22 where this 'only_shared' property gets passed down to kvm_realm_unmap_range(). There it's used to decide whether the private range should be unmapped or not.

The reason for this is kvm_unmap_gfn_range() which has a 'attr_filter' member of 'kvm_gfn_range' which can specify KVM_FILTER_PRIVATE. Which is used in __kvm_gmem_set_attributes() so choose whether to invalidate the private or shared part of a gmem range.

The issue on CCA is that invalidating the private mapping is destructive
- if the guest doesn't agree to it then the guest will not be able to continue executing. For the shared part this isn't a problem (we can refault the address).

Clearly I've screwed up the patch ordering here, but I'm not sure quite how to structure the APIs better to avoid adding this argument.

Thanks,
Steve

maintainer
#44 lore raw

Re: [PATCH v15 15/37] KVM: arm64: CCA: Handle RMI_EXIT_RIPAS_CHANGE

On Mon, 03 Aug 2026 15:04:32 +0100,
Steven Price <[email protected]> wrote:

[...]

Quoted 38 lines
Quoted 19 lines

arch/arm64/kvm/mmu.c static void invalidate_icache_guest_page(void *va, size_t size) · line 323

Quoted 10 lines
arch/arm64/kvm/mmu.c +1 -0
index cd06881c1497..dcc2ab08d0e4 100644
@@ -319,6 +319,7 @@ static void invalidate_icache_guest_page(void *va, size_t size)
  * @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
+ * @only_shared: If true then protected mappings should not be unmapped
  *

I don't understand the need for this additional argument. Given that CCA imposes that shared and private are in non-overlapping ranges, why is it necessary to introduce this at the core of the S2 management code?

I'd expect that the CCA code could simply work out what range it needs to run on and keep the API intact.

Quoted 13 lines

arch/arm64/kvm/mmu.c static void invalidate_icache_guest_page(void *va, size_t size) · line 333

Quoted 11 lines
arch/arm64/kvm/mmu.c +1 -1
  * Clear a range of stage-2 mappings, lowering the various ref-counts.  Must
  * be called while holding mmu_lock (unless for freeing the stage2 pgd before
@@ -326,7 +327,7 @@ static void invalidate_icache_guest_page(void *va, size_t size)
  * with things behind our backs.
  */
 static void __unmap_stage2_range(struct kvm_s2_mmu *mmu, phys_addr_t start, u64 size,
-				 bool may_block)
+				 bool may_block, bool only_shared)
 {
 	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
 	phys_addr_t end = start + size;

So what is the *actual* change?

It looks like I've screwed up what goes in which patch. The real change is in patch 22 where this 'only_shared' property gets passed down to kvm_realm_unmap_range(). There it's used to decide whether the private range should be unmapped or not.

Quoted 4 lines

The reason for this is kvm_unmap_gfn_range() which has a 'attr_filter' member of 'kvm_gfn_range' which can specify KVM_FILTER_PRIVATE. Which is used in __kvm_gmem_set_attributes() so choose whether to invalidate the private or shared part of a gmem range.

But you can readily distinguish the private/shared part of the address range by looking at the top IPA bit, right? And from there, you should be in a position to decide whether to call __unmap_stage2_range() on a per IPA range, rather than making this information trickle all over the place.

I.e don't hack into the API. Use the information you already have to decide whether you need to use the existing API at all.

If that cannot be done for whatever reason, then you need to indirect the call with a set of operations that leave the existing code untouched.

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

Re: [PATCH v15 15/37] KVM: arm64: CCA: Handle RMI_EXIT_RIPAS_CHANGE

Quoted 48 lines · Marc Zyngier

On Mon, 03 Aug 2026 15:04:32 +0100,
Steven Price <[email protected]> wrote:

[...]

Quoted 38 lines
Quoted 19 lines

arch/arm64/kvm/mmu.c static void invalidate_icache_guest_page(void *va, size_t size) · line 323

Quoted 10 lines
arch/arm64/kvm/mmu.c +1 -0
index cd06881c1497..dcc2ab08d0e4 100644
@@ -319,6 +319,7 @@ static void invalidate_icache_guest_page(void *va, size_t size)
   * @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
+ * @only_shared: If true then protected mappings should not be unmapped
   *

I don't understand the need for this additional argument. Given that CCA imposes that shared and private are in non-overlapping ranges, why is it necessary to introduce this at the core of the S2 management code?

I'd expect that the CCA code could simply work out what range it needs to run on and keep the API intact.

Quoted 13 lines

arch/arm64/kvm/mmu.c static void invalidate_icache_guest_page(void *va, size_t size) · line 333

Quoted 11 lines
arch/arm64/kvm/mmu.c +1 -1
   * Clear a range of stage-2 mappings, lowering the various ref-counts.  Must
   * be called while holding mmu_lock (unless for freeing the stage2 pgd before
@@ -326,7 +327,7 @@ static void invalidate_icache_guest_page(void *va, size_t size)
   * with things behind our backs.
   */
  static void __unmap_stage2_range(struct kvm_s2_mmu *mmu, phys_addr_t start, u64 size,
-				 bool may_block)
+				 bool may_block, bool only_shared)
  {
  	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
  	phys_addr_t end = start + size;

So what is the *actual* change?

It looks like I've screwed up what goes in which patch. The real change is in patch 22 where this 'only_shared' property gets passed down to kvm_realm_unmap_range(). There it's used to decide whether the private range should be unmapped or not.

Quoted 4 lines

The reason for this is kvm_unmap_gfn_range() which has a 'attr_filter' member of 'kvm_gfn_range' which can specify KVM_FILTER_PRIVATE. Which is used in __kvm_gmem_set_attributes() so choose whether to invalidate the private or shared part of a gmem range.

Quoted 5 lines

But you can readily distinguish the private/shared part of the address range by looking at the top IPA bit, right? And from there, you should be in a position to decide whether to call __unmap_stage2_range() on a per IPA range, rather than making this information trickle all over the place.

Yes, we can for an "IPA". However there are two different things at play here. There is KVM generic "GPA" (as manitained by the slot) and where the backend maps it in stage2 "IPA". For Arm CCA, for shared GPAs, the "IPA" is an alias of the GPA. But, here we get the GPA from the core layer.

There is a shared/private state associated with each "GPA" (GFN) as maintained by the Guest_memfd for each GPA in a memslot backed by it. When a change occurs in the backing store (e.g. set GPA to private, punch a hole in GPA, destroy a given range of GPAs), an invalidation needs to be triggered in the Stage2. Now, given different architectures have different ways to deal with private vs shared GPAs, (e.g., on CCA, shared GPAs are mapped in an aliased IPA) and the private GPAs are special, Guest_memfd tells you which ones need invalidation, using the filter. This filter then gets handled by the backends (CCA unmaps aliased address for Shared filter). Ideally this filter should be passed down to the core routine, so that it can be handled by the backends appropriately (similar to the range->mayblock).

Quoted 7 lines

I.e don't hack into the API. Use the information you already have to decide whether you need to use the existing API at all.

If that cannot be done for whatever reason, then you need to indirect the call with a set of operations that leave the existing code untouched.

Please let us know if you think we need to explore this ^ ?

Cheers
Suzuki

Quoted 3 lines
	M.
reviewer
#46 lore raw

Re: [PATCH v15 15/37] KVM: arm64: CCA: Handle RMI_EXIT_RIPAS_CHANGE

Hi Suzuki,

+ Quentin (who's on leave, but for when he gets back)

On Mon, 3 Aug 2026 at 16:30, Suzuki K Poulose <[email protected]> wrote:
...

Quoted 8 lines
Quoted 6 lines

I.e don't hack into the API. Use the information you already have to decide whether you need to use the existing API at all.

If that cannot be done for whatever reason, then you need to indirect the call with a set of operations that leave the existing code untouched.

Please let us know if you think we need to explore this ^ ?

FWIW, pKVM already has this kind of indirection: in protected mode, the kvm_pgtable_stage2_* calls in mmu.c dispatch to the pkvm_pgtable_stage2_* wrappers through KVM_PGT_FN(), and the callers don't branch. It is global today because pKVM owns the whole host, but a per-VM version would let the CCA backend handle the filter and the IPA aliasing internally, keeping __unmap_stage2_range()'s signature intact. That should work for pKVM as well.

Cheers,
/fuad

#47 lore raw

Re: [PATCH v15 15/37] KVM: arm64: CCA: Handle RMI_EXIT_RIPAS_CHANGE

Hi Fuad

Thanks for your feedback.

Quoted 15 lines · Fuad Tabba

Hi Suzuki,

+ Quentin (who's on leave, but for when he gets back)

On Mon, 3 Aug 2026 at 16:30, Suzuki K Poulose <[email protected]> wrote:
...

Quoted 8 lines
Quoted 6 lines

I.e don't hack into the API. Use the information you already have to decide whether you need to use the existing API at all.

If that cannot be done for whatever reason, then you need to indirect the call with a set of operations that leave the existing code untouched.

Please let us know if you think we need to explore this ^ ?

Quoted 7 lines

FWIW, pKVM already has this kind of indirection: in protected mode, the kvm_pgtable_stage2_* calls in mmu.c dispatch to the pkvm_pgtable_stage2_* wrappers through KVM_PGT_FN(), and the callers don't branch. It is global today because pKVM owns the whole host, but a per-VM version would let the CCA backend handle the filter and the IPA aliasing internally, keeping __unmap_stage2_range()'s signature intact. That should work for pKVM as well.

Sure, will explore this option. For the record, the patch here only passes down the "filter" parameter to __unmap_stage2_range() [ though in a different name, only_shared ] and we still handle the aliasing inside the CCA code. Let me explore on this front.

Suzuki

Quoted 3 lines

Cheers,
/fuad

#48 lore raw

PATCH v15 16/37 KVM: arm64: CCA: Handle realm MMIO emulation

In reply to Steven Price

MMIO emulation for a realm cannot be done directly with the VM's registers as they are protected from the host. However, for emulatable data aborts, the RMM uses GPRS[0] to provide the read/written value. We can transfer this from/to the equivalent VCPU's register entry and then depend on the generic MMIO handling code in KVM.

For a MMIO read, the value is placed in the shared RecExit structure during kvm_handle_mmio_return() rather than in the VCPU's register entry.

---
Changes since v7:
* New comment for rec_exit_sync_dabt() explaining the call to vcpu_set_reg().
Changes since v5:
* Inject SEA to the guest is an emulatable MMIO access triggers a data abort.
* kvm_handle_mmio_return() - disable kvm_incr_pc() for a REC (as the PC isn't under the host's control) and move the REC_ENTER_EMULATED_MMIO flag setting to this location (as that tells the RMM to skip the instruction).

---
 arch/arm64/kvm/inject_fault.c |  4 +++-
 arch/arm64/kvm/mmio.c         | 16 ++++++++++++----
 arch/arm64/kvm/rmi-exit.c     | 15 +++++++++++++++
 3 files changed, 30 insertions(+), 5 deletions(-)
arch/arm64/kvm/inject_fault.c +3 -1
index 89982bd3345f..6492397b73d7 100644
@@ -228,7 +228,9 @@ static void inject_abt32(struct kvm_vcpu *vcpu, bool is_pabt, u32 addr)
 
 static void __kvm_inject_sea(struct kvm_vcpu *vcpu, bool iabt, u64 addr)
 {
-	if (vcpu_el1_is_32bit(vcpu))
+	if (unlikely(vcpu_is_rec(vcpu)))
+		vcpu->arch.rec.run->enter.flags |= REC_ENTER_FLAG_INJECT_SEA;
+	else if (vcpu_el1_is_32bit(vcpu))
 		inject_abt32(vcpu, iabt, addr);
 	else
 		inject_abt64(vcpu, iabt, addr);
arch/arm64/kvm/mmio.c +12 -4
index e2285ed8c91d..a8c125205695 100644
@@ -6,6 +6,7 @@
 
 #include <linux/kvm_host.h>
 #include <asm/kvm_emulate.h>
+#include <linux/arm-smccc-rmi.h>
 #include <trace/events/kvm.h>
 
 #include "trace.h"
@@ -138,14 +139,21 @@ int kvm_handle_mmio_return(struct kvm_vcpu *vcpu)
 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, len, run->mmio.phys_addr,
 			       &data);
 		data = vcpu_data_host_to_guest(vcpu, data, len);
-		vcpu_set_reg(vcpu, kvm_vcpu_dabt_get_rd(vcpu), data);
+
+		if (vcpu_is_rec(vcpu))
+			vcpu->arch.rec.run->enter.gprs[0] = data;
+		else
+			vcpu_set_reg(vcpu, kvm_vcpu_dabt_get_rd(vcpu), data);
 	}
 
 	/*
 	 * The MMIO instruction is emulated and should not be re-executed
 	 * in the guest.
 	 */
-	kvm_incr_pc(vcpu);
+	if (vcpu_is_rec(vcpu))
+		vcpu->arch.rec.run->enter.flags |= REC_ENTER_FLAG_EMULATED_MMIO;
+	else
+		kvm_incr_pc(vcpu);
 
 	return 1;
 }
@@ -167,14 +175,14 @@ int io_mem_abort(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa)
 	 * No valid syndrome? Ask userspace for help if it has
 	 * volunteered to do so, and bail out otherwise.
 	 *
-	 * In the protected VM case, there isn't much userspace can do
+	 * In the protected/realm VM case, there isn't much userspace can do
 	 * though, so directly deliver an exception to the guest.
 	 */
 	if (!kvm_vcpu_dabt_isvalid(vcpu)) {
 		trace_kvm_mmio_nisv(*vcpu_pc(vcpu), esr,
 				    kvm_vcpu_get_hfar(vcpu), fault_ipa);
 
-		if (vcpu_is_protected(vcpu))
+		if (vcpu_is_protected(vcpu) || vcpu_is_rec(vcpu))
 			return kvm_inject_sea_dabt(vcpu, kvm_vcpu_get_hfar(vcpu));
 
 		if (test_bit(KVM_ARCH_FLAG_RETURN_NISV_IO_ABORT_TO_USER,
arch/arm64/kvm/rmi-exit.c +15 -0
index 973250563d7b..c668cbfa971a 100644
@@ -23,6 +23,21 @@ static int rec_exit_reason_notimpl(struct kvm_vcpu *vcpu)
 
 static int rec_exit_sync_dabt(struct kvm_vcpu *vcpu)
 {
+	struct realm_rec *rec = &vcpu->arch.rec;
+
+	/*
+	 * In the case of a write, copy over gprs[0] to the target GPR,
+	 * preparing to handle MMIO write fault. The content to be written has
+	 * been saved to gprs[0] by the RMM (even if another register was used
+	 * by the guest). In the case of normal memory access this is redundant
+	 * (the guest will replay the instruction), but the overhead is
+	 * minimal.
+	 */
+	if (kvm_vcpu_dabt_iswrite(vcpu) && kvm_vcpu_dabt_isvalid(vcpu)) {
+		vcpu_set_reg(vcpu, kvm_vcpu_dabt_get_rd(vcpu),
+			     rec->run->exit.gprs[0]);
+	}
+
 	return kvm_handle_guest_abort(vcpu);
 }
 
Signature · 1 line
2.43.0
maintainer
#49 lore raw

Re: [PATCH v15 16/37] KVM: arm64: CCA: Handle realm MMIO emulation

Quoted 36 lines · Steven Price

MMIO emulation for a realm cannot be done directly with the VM's registers as they are protected from the host. However, for emulatable data aborts, the RMM uses GPRS[0] to provide the read/written value. We can transfer this from/to the equivalent VCPU's register entry and then depend on the generic MMIO handling code in KVM.

For a MMIO read, the value is placed in the shared RecExit structure during kvm_handle_mmio_return() rather than in the VCPU's register entry.

---
Changes since v7:
* New comment for rec_exit_sync_dabt() explaining the call to vcpu_set_reg().
Changes since v5:
* Inject SEA to the guest is an emulatable MMIO access triggers a data abort.
* kvm_handle_mmio_return() - disable kvm_incr_pc() for a REC (as the PC isn't under the host's control) and move the REC_ENTER_EMULATED_MMIO flag setting to this location (as that tells the RMM to skip the instruction).

---
 arch/arm64/kvm/inject_fault.c |  4 +++-
 arch/arm64/kvm/mmio.c         | 16 ++++++++++++----
 arch/arm64/kvm/rmi-exit.c     | 15 +++++++++++++++
 3 files changed, 30 insertions(+), 5 deletions(-)
arch/arm64/kvm/inject_fault.c +0 -0
index 89982bd3345f..6492397b73d7 100644

arch/arm64/kvm/inject_fault.c static void inject_abt32(struct kvm_vcpu *vcpu, bool is_pabt, u32 addr) · line 236

Quoted 10 lines
arch/arm64/kvm/inject_fault.c +3 -1
@@ -228,7 +228,9 @@ static void inject_abt32(struct kvm_vcpu *vcpu, bool is_pabt, u32 addr)
 
 static void __kvm_inject_sea(struct kvm_vcpu *vcpu, bool iabt, u64 addr)
 {
-	if (vcpu_el1_is_32bit(vcpu))
+	if (unlikely(vcpu_is_rec(vcpu)))
+		vcpu->arch.rec.run->enter.flags |= REC_ENTER_FLAG_INJECT_SEA;
+	else if (vcpu_el1_is_32bit(vcpu))
 		inject_abt32(vcpu, iabt, addr);
 	else
 		inject_abt64(vcpu, iabt, addr);

Why don't you let inject_dabt64() do its job and reconcile the REC stuff at run time?

Quoted 13 lines
arch/arm64/kvm/mmio.c +1 -0
index e2285ed8c91d..a8c125205695 100644
@@ -6,6 +6,7 @@
 
 #include <linux/kvm_host.h>
 #include <asm/kvm_emulate.h>
+#include <linux/arm-smccc-rmi.h>
 #include <trace/events/kvm.h>
 
 #include "trace.h"

arch/arm64/kvm/mmio.c int kvm_handle_mmio_return(struct kvm_vcpu *vcpu) · line 146

Quoted 9 lines
arch/arm64/kvm/mmio.c +5 -1
@@ -138,14 +139,21 @@ int kvm_handle_mmio_return(struct kvm_vcpu *vcpu)
 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, len, run->mmio.phys_addr,
 			       &data);
 		data = vcpu_data_host_to_guest(vcpu, data, len);
-		vcpu_set_reg(vcpu, kvm_vcpu_dabt_get_rd(vcpu), data);
+
+		if (vcpu_is_rec(vcpu))
+			vcpu->arch.rec.run->enter.gprs[0] = data;
+		else
+			vcpu_set_reg(vcpu, kvm_vcpu_dabt_get_rd(vcpu), data);

This is yet another example of things I do not want to see. KVM works on the GPRs described in the vcpu structure. And that's it.

So let the ESR information be correct for CCA, the data being written back to x0, and once you're ready to enter the guest again, copy whatever you need into the CCA data structure.

But not any of this stuff.

arch/arm64/kvm/mmio.c int kvm_handle_mmio_return(struct kvm_vcpu *vcpu) · line 156

Quoted 11 lines
arch/arm64/kvm/mmio.c +4 -1
 	}
 
 	/*
 	 * The MMIO instruction is emulated and should not be re-executed
 	 * in the guest.
 	 */
-	kvm_incr_pc(vcpu);
+	if (vcpu_is_rec(vcpu))
+		vcpu->arch.rec.run->enter.flags |= REC_ENTER_FLAG_EMULATED_MMIO;
+	else
+		kvm_incr_pc(vcpu);

Same thing. kvm_incr_pc() sets a flag. Use that to reconcile the state with CCA.

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

Re: [PATCH v15 16/37] KVM: arm64: CCA: Handle realm MMIO emulation

Quoted 39 lines · Marc Zyngier
Quoted 37 lines · Steven Price

MMIO emulation for a realm cannot be done directly with the VM's registers as they are protected from the host. However, for emulatable data aborts, the RMM uses GPRS[0] to provide the read/written value. We can transfer this from/to the equivalent VCPU's register entry and then depend on the generic MMIO handling code in KVM.

For a MMIO read, the value is placed in the shared RecExit structure during kvm_handle_mmio_return() rather than in the VCPU's register entry.

---
Changes since v7:
* New comment for rec_exit_sync_dabt() explaining the call to vcpu_set_reg().
Changes since v5:
* Inject SEA to the guest is an emulatable MMIO access triggers a data abort.
* kvm_handle_mmio_return() - disable kvm_incr_pc() for a REC (as the PC isn't under the host's control) and move the REC_ENTER_EMULATED_MMIO flag setting to this location (as that tells the RMM to skip the instruction).

---
 arch/arm64/kvm/inject_fault.c |  4 +++-
 arch/arm64/kvm/mmio.c         | 16 ++++++++++++----
 arch/arm64/kvm/rmi-exit.c     | 15 +++++++++++++++
 3 files changed, 30 insertions(+), 5 deletions(-)
arch/arm64/kvm/inject_fault.c +0 -0
index 89982bd3345f..6492397b73d7 100644
@@ -228,7 +228,9 @@ static void inject_abt32(struct kvm_vcpu *vcpu, bool is_pabt, u32 addr)
 
Quoted 12 lines

arch/arm64/kvm/inject_fault.c static void inject_abt32(struct kvm_vcpu *vcpu, bool is_pabt, u32 addr) · line 236

Quoted 9 lines
arch/arm64/kvm/inject_fault.c +3 -1
 static void __kvm_inject_sea(struct kvm_vcpu *vcpu, bool iabt, u64 addr)
 {
-	if (vcpu_el1_is_32bit(vcpu))
+	if (unlikely(vcpu_is_rec(vcpu)))
+		vcpu->arch.rec.run->enter.flags |= REC_ENTER_FLAG_INJECT_SEA;
+	else if (vcpu_el1_is_32bit(vcpu))
 		inject_abt32(vcpu, iabt, addr);
 	else
 		inject_abt64(vcpu, iabt, addr);

Why don't you let inject_dabt64() do its job and reconcile the REC stuff at run time?

Ok, one wrinkle is the __kvm_adjust_pc() path. But I can skip that and leave the PENDING_EXCEPTION flag set on return to user space. That way the flag is still set for the next entry and we can handle the RMM specific parts there.

Quoted 26 lines
Quoted 13 lines
arch/arm64/kvm/mmio.c +1 -0
index e2285ed8c91d..a8c125205695 100644
@@ -6,6 +6,7 @@
 
 #include <linux/kvm_host.h>
 #include <asm/kvm_emulate.h>
+#include <linux/arm-smccc-rmi.h>
 #include <trace/events/kvm.h>
 
 #include "trace.h"

arch/arm64/kvm/mmio.c int kvm_handle_mmio_return(struct kvm_vcpu *vcpu) · line 146

Quoted 9 lines
arch/arm64/kvm/mmio.c +5 -1
@@ -138,14 +139,21 @@ int kvm_handle_mmio_return(struct kvm_vcpu *vcpu)
 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, len, run->mmio.phys_addr,
 			       &data);
 		data = vcpu_data_host_to_guest(vcpu, data, len);
-		vcpu_set_reg(vcpu, kvm_vcpu_dabt_get_rd(vcpu), data);
+
+		if (vcpu_is_rec(vcpu))
+			vcpu->arch.rec.run->enter.gprs[0] = data;
+		else
+			vcpu_set_reg(vcpu, kvm_vcpu_dabt_get_rd(vcpu), data);

This is yet another example of things I do not want to see. KVM works on the GPRs described in the vcpu structure. And that's it.

Quoted 5 lines

So let the ESR information be correct for CCA, the data being written back to x0, and once you're ready to enter the guest again, copy whatever you need into the CCA data structure.

But not any of this stuff.

Yes this is a bit silly. A while ago the RMM wasn't populating the ESR information correctly which is where all these gprs[0] hacks came from. That's been fixed and it should be possible to do this on entry.

Quoted 14 lines

arch/arm64/kvm/mmio.c int kvm_handle_mmio_return(struct kvm_vcpu *vcpu) · line 156

Quoted 11 lines
arch/arm64/kvm/mmio.c +4 -1
 	}
 
 	/*
 	 * The MMIO instruction is emulated and should not be re-executed
 	 * in the guest.
 	 */
-	kvm_incr_pc(vcpu);
+	if (vcpu_is_rec(vcpu))
+		vcpu->arch.rec.run->enter.flags |= REC_ENTER_FLAG_EMULATED_MMIO;
+	else
+		kvm_incr_pc(vcpu);

Same thing. kvm_incr_pc() sets a flag. Use that to reconcile the state with CCA.

It's not an ideal flag for this use (it's set in other places). But I think it should be sufficient along with checking other state to identify this condition.

Thanks,
Steve

#51 lore raw

PATCH v15 17/37 KVM: arm64: Expose support for private memory

In reply to Steven Price

Select KVM_GENERIC_MEMORY_ATTRIBUTES and provide the necessary support functions.

---
Changes since v13:
* Also update documentation to show that KVM_CAP_MEMORY_ATTRIBUTES is used on arm64.
Changes since v12:
* Only define kvm_arch_has_private_mem() when CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES is set to avoid build issues when KVM is disabled.
Changes since v10:
* KVM_GENERIC_PRIVATE_MEM replacd with KVM_GENERIC_MEMORY_ATTRIBUTES.
Changes since v9:
* Drop the #ifdef CONFIG_KVM_PRIVATE_MEM guard from the definition of kvm_arch_has_private_mem()
Changes since v2:
* Switch kvm_arch_has_private_mem() to a macro to avoid overhead of a function call.
* Guard definitions of kvm_arch_{pre,post}_set_memory_attributes() with #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES.
* Early out in kvm_arch_post_set_memory_attributes() if the WARN_ON should trigger.

---
 arch/arm64/include/asm/kvm_host.h | 2 ++
 1 file changed, 2 insertions(+)
arch/arm64/include/asm/kvm_host.h +2 -0
index 9b46b39ed11e..993ead6e6449 100644
@@ -1509,6 +1509,8 @@ struct kvm *kvm_arch_alloc_vm(void);
 
 #define vcpu_is_protected(vcpu)		kvm_vm_is_protected((vcpu)->kvm)
 
+#define kvm_arch_has_private_mem(kvm) ((kvm)->arch.is_realm)
+
 int kvm_arm_vcpu_finalize(struct kvm_vcpu *vcpu, int feature);
 bool kvm_arm_vcpu_is_finalized(struct kvm_vcpu *vcpu);
 
Signature · 1 line
2.43.0
reviewer Reviewed-by on v15 17/37
#52 lore raw

Re: [PATCH v15 17/37] KVM: arm64: Expose support for private memory

Quoted 5 lines · Steven Price

Select KVM_GENERIC_MEMORY_ATTRIBUTES and provide the necessary support functions.

---

minor nit:

Changes since v14:
* Switch to guest_memfd in-place memory conversion and drop support for KVM_VM_MEMORY_ATTRIBUTES.

Quoted 36 lines

Changes since v13:
* Also update documentation to show that KVM_CAP_MEMORY_ATTRIBUTES is used on arm64.
Changes since v12:
* Only define kvm_arch_has_private_mem() when CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES is set to avoid build issues when KVM is disabled.
Changes since v10:
* KVM_GENERIC_PRIVATE_MEM replacd with KVM_GENERIC_MEMORY_ATTRIBUTES.
Changes since v9:
* Drop the #ifdef CONFIG_KVM_PRIVATE_MEM guard from the definition of kvm_arch_has_private_mem()
Changes since v2:
* Switch kvm_arch_has_private_mem() to a macro to avoid overhead of a function call.
* Guard definitions of kvm_arch_{pre,post}_set_memory_attributes() with

    #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES.
  * Early out in kvm_arch_post_set_memory_attributes() if the WARN_ON
    should trigger.
---
  arch/arm64/include/asm/kvm_host.h | 2 ++
  1 file changed, 2 insertions(+)
arch/arm64/include/asm/kvm_host.h +2 -0
index 9b46b39ed11e..993ead6e6449 100644
@@ -1509,6 +1509,8 @@ struct kvm *kvm_arch_alloc_vm(void);
 
  #define vcpu_is_protected(vcpu)		kvm_vm_is_protected((vcpu)->kvm)
 
+#define kvm_arch_has_private_mem(kvm) ((kvm)->arch.is_realm)
+
  int kvm_arm_vcpu_finalize(struct kvm_vcpu *vcpu, int feature);
  bool kvm_arm_vcpu_is_finalized(struct kvm_vcpu *vcpu);
 
#53 lore raw

PATCH v15 18/37 KVM: arm64: CCA: Create the realm descriptor

In reply to Steven Price

Creating a realm involves first creating a realm descriptor (RD). This involves passing the configuration information to the RMM. Do this as part of realm_ensure_created() so that the realm is created when it is first needed. The call to realm_ensure_created() will be added in a later patch.

---
Changes since v14:
* Explicitly set hash_algo = RMI_HASH_SHA_256 (which is the default).
* Support SRO flow during realm creation.
Changes since v13:
* The RMM no longer uses AUX granules, so no need to ask it how many it needs.
* Adapted to other changes.
Changes since v12:
* Since RMM page size is now equal to the host's page size various calculations are simplified.
* Switch to using range based APIs to delegate/undelegate.
* VMID handling is now handled entirely by the RMM.

---
 arch/arm64/kvm/rmi.c | 91 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 91 insertions(+)
arch/arm64/kvm/rmi.c +91 -0
index 1ef676eed172..94776a9262c9 100644
@@ -449,6 +449,79 @@ static void realm_unmap_shared_range(struct kvm *kvm,
 			     start, end);
 }
 
+static int realm_create_rd(struct kvm *kvm)
+{
+	struct realm *realm = &kvm->arch.realm;
+	struct realm_params *params = realm->params;
+	void *rd = NULL;
+	phys_addr_t rd_phys, params_phys, top_delegated;
+	size_t pgd_size = kvm_pgtable_stage2_pgd_size(kvm->arch.mmu.vtcr);
+	int r;
+
+	realm->ia_bits = VTCR_EL2_IPA(kvm->arch.mmu.vtcr);
+
+	if (WARN_ON(realm->rd || !realm->params))
+		return -EEXIST;
+
+	rd = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
+	if (!rd)
+		return -ENOMEM;
+
+	rd_phys = virt_to_phys(rd);
+	if (rmi_delegate_page(rd_phys)) {
+		r = -ENXIO;
+		goto free_rd;
+	}
+
+	if (rmi_delegate_range(kvm->arch.mmu.pgd_phys, pgd_size,
+			       &top_delegated)) {
+		r = -ENXIO;
+		goto out_undelegate_tables;
+	}
+
+	params->s2sz = VTCR_EL2_IPA(kvm->arch.mmu.vtcr);
+	params->rtt_level_start = get_start_level(realm);
+	params->rtt_num_start = pgd_size / PAGE_SIZE;
+	params->rtt_base = kvm->arch.mmu.pgd_phys;
+	params->hash_algo = RMI_HASH_SHA_256;
+
+	if (kvm->arch.arm_pmu) {
+		params->pmu_num_ctrs = kvm->arch.nr_pmu_counters;
+		params->flags0 |= RMI_REALM_PARAM_FLAG_PMU;
+	}
+
+	if (kvm_lpa2_is_enabled())
+		params->flags0 |= RMI_REALM_PARAM_FLAG_LPA2;
+
+	params_phys = virt_to_phys(params);
+
+	if (rmi_realm_create(rd_phys, params_phys, realm->sro)) {
+		r = -ENXIO;
+		goto out_undelegate_tables;
+	}
+
+	realm->rd = rd;
+	kvm_set_realm_state(kvm, REALM_STATE_NEW);
+	/* The realm is up, free the parameters.  */
+	free_page((unsigned long)realm->params);
+	realm->params = NULL;
+
+	return 0;
+
+out_undelegate_tables:
+	if (WARN_ON(rmi_undelegate_range(kvm->arch.mmu.pgd_phys, top_delegated - kvm->arch.mmu.pgd_phys))) {
+		/* Leak the pages if they cannot be returned */
+		kvm->arch.mmu.pgt = NULL;
+	}
+	if (WARN_ON(rmi_undelegate_page(rd_phys))) {
+		/* Leak the page if it isn't returned */
+		return r;
+	}
+free_rd:
+	free_page((unsigned long)rd);
+	return r;
+}
+
 static void realm_unmap_private_range(struct kvm *kvm,
 				      unsigned long start,
 				      unsigned long end,
@@ -614,6 +687,24 @@ static int realm_set_ipa_state(struct kvm_vcpu *vcpu,
 	return ret;
 }
 
+static int __maybe_unused realm_ensure_created(struct kvm *kvm)
+{
+	lockdep_assert_held(&kvm->arch.config_lock);
+
+	switch (kvm_realm_state(kvm)) {
+	case REALM_STATE_NONE:
+		break;
+	case REALM_STATE_NEW:
+		return 0;
+	case REALM_STATE_DEAD:
+		return -ENXIO;
+	default:
+		return -EBUSY;
+	}
+
+	return realm_create_rd(kvm);
+}
+
 static void kvm_complete_ripas_change(struct kvm_vcpu *vcpu)
 {
 	struct kvm *kvm = vcpu->kvm;
Signature · 1 line
2.43.0
#54 lore raw

PATCH v15 19/37 KVM: arm64: CCA: Activate realms on first vCPU run

In reply to Steven Price

Use kvm_arch_vcpu_run_pid_change() to check if this is the first time the realm guest has run. If this is the first run then activate the realm.

---
Changes since v12:
* Fix commit message
* Change realm_state checks to be >= REALM_STATE_ACTIVE to avoid a dead guest being revived by kvm_activate_realm().

---
 arch/arm64/include/asm/kvm_rmi.h |  1 +
 arch/arm64/kvm/arm.c             |  6 +++++
 arch/arm64/kvm/rmi.c             | 45 ++++++++++++++++++++++++++++++--
 3 files changed, 50 insertions(+), 2 deletions(-)
arch/arm64/include/asm/kvm_rmi.h +1 -0
index 5461c49bea4d..5cb99c187202 100644
@@ -96,6 +96,7 @@ void kvm_init_rmi(void);
 u32 kvm_rmm_ipa_limit(void);
 
 int kvm_init_realm(struct kvm *kvm);
+int kvm_activate_realm(struct kvm *kvm);
 void kvm_destroy_realm(struct kvm *kvm);
 int kvm_realm_teardown_stage2(struct kvm *kvm);
 void kvm_destroy_rec(struct kvm_vcpu *vcpu);
arch/arm64/kvm/arm.c +6 -0
index 534d33b7c67a..df33322b8fea 100644
@@ -1034,6 +1034,12 @@ int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu)
 			return ret;
 	}
 
+	if (kvm_is_realm(vcpu->kvm)) {
+		ret = kvm_activate_realm(kvm);
+		if (ret)
+			return ret;
+	}
+
 	mutex_lock(&kvm->arch.config_lock);
 	set_bit(KVM_ARCH_FLAG_HAS_RAN_ONCE, &kvm->arch.flags);
 	mutex_unlock(&kvm->arch.config_lock);
arch/arm64/kvm/rmi.c +43 -2

63 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer
#55 lore raw

Re: [PATCH v15 19/37] KVM: arm64: CCA: Activate realms on first vCPU run

Quoted 77 lines · Steven Price

Use kvm_arch_vcpu_run_pid_change() to check if this is the first time the realm guest has run. If this is the first run then activate the realm.

---
Changes since v12:
* Fix commit message
* Change realm_state checks to be >= REALM_STATE_ACTIVE to avoid a dead guest being revived by kvm_activate_realm().

---
 arch/arm64/include/asm/kvm_rmi.h |  1 +
 arch/arm64/kvm/arm.c             |  6 +++++
 arch/arm64/kvm/rmi.c             | 45 ++++++++++++++++++++++++++++++--
 3 files changed, 50 insertions(+), 2 deletions(-)
arch/arm64/include/asm/kvm_rmi.h +1 -0
index 5461c49bea4d..5cb99c187202 100644
@@ -96,6 +96,7 @@ void kvm_init_rmi(void);
 u32 kvm_rmm_ipa_limit(void);
 
 int kvm_init_realm(struct kvm *kvm);
+int kvm_activate_realm(struct kvm *kvm);
 void kvm_destroy_realm(struct kvm *kvm);
 int kvm_realm_teardown_stage2(struct kvm *kvm);
 void kvm_destroy_rec(struct kvm_vcpu *vcpu);
arch/arm64/kvm/arm.c +6 -0
index 534d33b7c67a..df33322b8fea 100644
@@ -1034,6 +1034,12 @@ int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu)
 			return ret;
 	}
 
+	if (kvm_is_realm(vcpu->kvm)) {
+		ret = kvm_activate_realm(kvm);
+		if (ret)
+			return ret;
+	}
+
 	mutex_lock(&kvm->arch.config_lock);
 	set_bit(KVM_ARCH_FLAG_HAS_RAN_ONCE, &kvm->arch.flags);
 	mutex_unlock(&kvm->arch.config_lock);
arch/arm64/kvm/rmi.c +6 -2
index 94776a9262c9..53b5b18f2275 100644
@@ -687,7 +687,7 @@ static int realm_set_ipa_state(struct kvm_vcpu *vcpu,
 	return ret;
 }
 
-static int __maybe_unused realm_ensure_created(struct kvm *kvm)
+static int realm_ensure_created(struct kvm *kvm)
 {
 	lockdep_assert_held(&kvm->arch.config_lock);
 
@@ -793,7 +793,7 @@ int noinstr kvm_rec_enter(struct kvm_vcpu *vcpu)
 	return ret;
 }
 
-static int __maybe_unused kvm_create_rec(struct kvm_vcpu *vcpu)
+static int kvm_create_rec(struct kvm_vcpu *vcpu)
 {
 	struct user_pt_regs *vcpu_regs = vcpu_gp_regs(vcpu);
 	unsigned long mpidr = kvm_vcpu_get_mpidr_aff(vcpu);
@@ -893,6 +893,47 @@ void kvm_destroy_rec(struct kvm_vcpu *vcpu)
 	rec->rec_page = NULL;
 }
 
+int kvm_activate_realm(struct kvm *kvm)
+{
+	struct realm *realm = &kvm->arch.realm;
+	struct kvm_vcpu *vcpu;

arch/arm64/kvm/rmi.c void kvm_destroy_rec(struct kvm_vcpu *vcpu) · line 909

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+	unsigned long i;
+	int ret;
+
+	if (kvm_realm_state(kvm) >= REALM_STATE_ACTIVE)
+		return 0;
+
+	if (!irqchip_in_kernel(kvm)) {
+		/* Userspace irqchip not yet supported with realms */
+		return -EOPNOTSUPP;
+	}

This could race with the irqchip being created on another CPU. Also, an irqchip being in kernel doesn't mean it is ready, and I suspect you also need to check that it has been initialised.

Quoted 8 lines
arch/arm64/kvm/rmi.c +8 -0
+
+	guard(mutex)(&kvm->arch.config_lock);
+	/* Check again with the lock held */
+	if (kvm_realm_state(kvm) >= REALM_STATE_ACTIVE)
+		return 0;
+
+	ret = realm_ensure_created(kvm);
+	if (ret)

arch/arm64/kvm/rmi.c void kvm_destroy_rec(struct kvm_vcpu *vcpu) · line 927

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+		return ret;
+
+	/* Mark state as dead in case we fail */
+	kvm_set_realm_state(kvm, REALM_STATE_DEAD);
+
+	kvm_for_each_vcpu(i, vcpu, kvm) {
+		ret = kvm_create_rec(vcpu);
+		if (ret)
+			return ret;
+	}

If the realm is dead, shouldn't the KVM view of death apply as well?

arch/arm64/kvm/rmi.c void kvm_destroy_rec(struct kvm_vcpu *vcpu) · line 939

Quoted 12 lines
arch/arm64/kvm/rmi.c +9 -0
+
+	ret = rmi_realm_activate(virt_to_phys(realm->rd));
+	if (ret)
+		return -ENXIO;
+
+	kvm_set_realm_state(kvm, REALM_STATE_ACTIVE);
+	return 0;
+}
+
 void kvm_destroy_realm(struct kvm *kvm)
 {
 	struct realm *realm = &kvm->arch.realm;

Thanks,

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

Re: [PATCH v15 19/37] KVM: arm64: CCA: Activate realms on first vCPU run

Quoted 85 lines · Marc Zyngier
Quoted 83 lines · Steven Price

Use kvm_arch_vcpu_run_pid_change() to check if this is the first time the realm guest has run. If this is the first run then activate the realm.

---
Changes since v12:
* Fix commit message
* Change realm_state checks to be >= REALM_STATE_ACTIVE to avoid a dead guest being revived by kvm_activate_realm().

---
 arch/arm64/include/asm/kvm_rmi.h |  1 +
 arch/arm64/kvm/arm.c             |  6 +++++
 arch/arm64/kvm/rmi.c             | 45 ++++++++++++++++++++++++++++++--
 3 files changed, 50 insertions(+), 2 deletions(-)
arch/arm64/include/asm/kvm_rmi.h +1 -0
index 5461c49bea4d..5cb99c187202 100644
@@ -96,6 +96,7 @@ void kvm_init_rmi(void);
 u32 kvm_rmm_ipa_limit(void);
 
 int kvm_init_realm(struct kvm *kvm);
+int kvm_activate_realm(struct kvm *kvm);
 void kvm_destroy_realm(struct kvm *kvm);
 int kvm_realm_teardown_stage2(struct kvm *kvm);
 void kvm_destroy_rec(struct kvm_vcpu *vcpu);
arch/arm64/kvm/arm.c +6 -0
index 534d33b7c67a..df33322b8fea 100644
@@ -1034,6 +1034,12 @@ int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu)
 			return ret;
 	}
 
+	if (kvm_is_realm(vcpu->kvm)) {
+		ret = kvm_activate_realm(kvm);
+		if (ret)
+			return ret;
+	}
+
 	mutex_lock(&kvm->arch.config_lock);
 	set_bit(KVM_ARCH_FLAG_HAS_RAN_ONCE, &kvm->arch.flags);
 	mutex_unlock(&kvm->arch.config_lock);
arch/arm64/kvm/rmi.c +12 -2
index 94776a9262c9..53b5b18f2275 100644
@@ -687,7 +687,7 @@ static int realm_set_ipa_state(struct kvm_vcpu *vcpu,
 	return ret;
 }
 
-static int __maybe_unused realm_ensure_created(struct kvm *kvm)
+static int realm_ensure_created(struct kvm *kvm)
 {
 	lockdep_assert_held(&kvm->arch.config_lock);
 
@@ -793,7 +793,7 @@ int noinstr kvm_rec_enter(struct kvm_vcpu *vcpu)
 	return ret;
 }
 
-static int __maybe_unused kvm_create_rec(struct kvm_vcpu *vcpu)
+static int kvm_create_rec(struct kvm_vcpu *vcpu)
 {
 	struct user_pt_regs *vcpu_regs = vcpu_gp_regs(vcpu);
 	unsigned long mpidr = kvm_vcpu_get_mpidr_aff(vcpu);
@@ -893,6 +893,47 @@ void kvm_destroy_rec(struct kvm_vcpu *vcpu)
 	rec->rec_page = NULL;
 }
 
+int kvm_activate_realm(struct kvm *kvm)
+{
+	struct realm *realm = &kvm->arch.realm;
+	struct kvm_vcpu *vcpu;
+	unsigned long i;
+	int ret;
+
+	if (kvm_realm_state(kvm) >= REALM_STATE_ACTIVE)
+		return 0;
+
Quoted 8 lines

arch/arm64/kvm/rmi.c void kvm_destroy_rec(struct kvm_vcpu *vcpu) · line 909

Quoted 4 lines
arch/arm64/kvm/rmi.c +4 -0
+	if (!irqchip_in_kernel(kvm)) {
+		/* Userspace irqchip not yet supported with realms */
+		return -EOPNOTSUPP;
+	}

This could race with the irqchip being created on another CPU. Also, an irqchip being in kernel doesn't mean it is ready, and I suspect you also need to check that it has been initialised.

Good point - moving the config_lock up and checking vgic_initialized() makes sense.

Quoted 12 lines
Quoted 12 lines
arch/arm64/kvm/rmi.c +12 -0
+
+	guard(mutex)(&kvm->arch.config_lock);
+	/* Check again with the lock held */
+	if (kvm_realm_state(kvm) >= REALM_STATE_ACTIVE)
+		return 0;
+
+	ret = realm_ensure_created(kvm);
+	if (ret)
+		return ret;
+
+	/* Mark state as dead in case we fail */
+	kvm_set_realm_state(kvm, REALM_STATE_DEAD);
Quoted 8 lines

arch/arm64/kvm/rmi.c void kvm_destroy_rec(struct kvm_vcpu *vcpu) · line 927

Quoted 6 lines
arch/arm64/kvm/rmi.c +6 -0
+
+	kvm_for_each_vcpu(i, vcpu, kvm) {
+		ret = kvm_create_rec(vcpu);
+		if (ret)
+			return ret;
+	}

If the realm is dead, shouldn't the KVM view of death apply as well?

Indeed that would be a good improvement. I'll change these error paths to include a kvm_vm_dead() call.

Thanks,
Steve

Quoted 17 lines

arch/arm64/kvm/rmi.c void kvm_destroy_rec(struct kvm_vcpu *vcpu) · line 939

Quoted 12 lines
arch/arm64/kvm/rmi.c +9 -0
+
+	ret = rmi_realm_activate(virt_to_phys(realm->rd));
+	if (ret)
+		return -ENXIO;
+
+	kvm_set_realm_state(kvm, REALM_STATE_ACTIVE);
+	return 0;
+}
+
 void kvm_destroy_realm(struct kvm *kvm)
 {
 	struct realm *realm = &kvm->arch.realm;

Thanks,

	M.
#57 lore raw

PATCH v15 20/37 KVM: arm64: CCA: Allow populating initial contents

In reply to Steven Price

The VMM needs to populate the realm with some data before starting (e.g. a kernel and initrd). This is measured by the RMM and used as part of the attestation later on.

---
Changes since v14:
* Holding of locks slots_lock and config_lock have been moved up the callstack with lockdesp assertions placed in the lower functions.
* Add overflow check into kvm_arm_rmi_populate().
Changes since v13:
* Rename realm_create_protected_data_page() to realm_data_map_init().
Changes since v12:
* The ioctl now updates the structure with the amount populated rather than returning this through the ioctl return code.
* Use the new RMM v2.0 range based RMI calls.
* Adapt to upstream changes in kvm_gmem_populate().
Changes since v11:
* The multiplex CAP is gone and there's a new ioctl which makes use of the generic kvm_gmem_populate() functionality.
Changes since v7:
* Improve the error codes.
* Other minor changes from review.
Changes since v6:
* Handle host potentially having a larger page size than the RMM granule.
* Drop historic "par" (protected address range) from populate_par_region() - it doesn't exist within the current architecture.
* Add a cond_resched() call in kvm_populate_realm().
Changes since v5:
* Refactor to use PFNs rather than tracking struct page in realm_create_protected_data_page().
* Pull changes from a later patch (in the v5 series) for accessing pages from a guest memfd.
* Do the populate in chunks to avoid holding locks for too long and triggering RCU stall warnings.

---
 arch/arm64/include/asm/kvm_rmi.h |   4 ++
 arch/arm64/kvm/Kconfig           |   1 +
 arch/arm64/kvm/arm.c             |  13 ++++
 arch/arm64/kvm/rmi.c             | 119 +++++++++++++++++++++++++++++++
 4 files changed, 137 insertions(+)
arch/arm64/include/asm/kvm_rmi.h +4 -0
index 5cb99c187202..fd0c57594a22 100644
@@ -105,6 +105,10 @@ int kvm_rec_enter(struct kvm_vcpu *vcpu);
 int kvm_rec_pre_enter(struct kvm_vcpu *vcpu);
 int handle_rec_exit(struct kvm_vcpu *vcpu, int rec_run_status);
 
+struct kvm_arm_rmi_populate;
+
+int kvm_arm_rmi_populate(struct kvm *kvm,
+			 struct kvm_arm_rmi_populate *arg);
 void kvm_realm_unmap_range(struct kvm *kvm,
 			   unsigned long ipa,
 			   unsigned long size,
arch/arm64/kvm/Kconfig +1 -0
index 189e8ad78b22..83b95e836b4d 100644
@@ -37,6 +37,7 @@ menuconfig KVM
 	select SCHED_INFO
 	select GUEST_PERF_EVENTS if PERF_EVENTS
 	select KVM_GUEST_MEMFD
+	select HAVE_KVM_ARCH_GMEM_POPULATE
 	select ARM_RMM
 	help
 	  Support hosting virtualized guest machines.
arch/arm64/kvm/arm.c +13 -0
index df33322b8fea..1558bb12b1b1 100644
@@ -2153,6 +2153,19 @@ int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
 			return -EFAULT;
 		return kvm_vm_ioctl_get_reg_writable_masks(kvm, &range);
 	}
+	case KVM_ARM_RMI_POPULATE: {
+		struct kvm_arm_rmi_populate req;
+		int ret;
+
+		if (!kvm_is_realm(kvm))
+			return -ENXIO;
+		if (copy_from_user(&req, argp, sizeof(req)))
+			return -EFAULT;
+		ret = kvm_arm_rmi_populate(kvm, &req);
+		if (copy_to_user(argp, &req, sizeof(req)))
+			return -EFAULT;
+		return ret;
+	}
 	default:
 		return -EINVAL;
 	}
arch/arm64/kvm/rmi.c +119 -0

131 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer
#58 lore raw

Re: [PATCH v15 20/37] KVM: arm64: CCA: Allow populating initial contents

Quoted 119 lines · Steven Price

The VMM needs to populate the realm with some data before starting (e.g. a kernel and initrd). This is measured by the RMM and used as part of the attestation later on.

---
Changes since v14:
* Holding of locks slots_lock and config_lock have been moved up the callstack with lockdesp assertions placed in the lower functions.
* Add overflow check into kvm_arm_rmi_populate().
Changes since v13:
* Rename realm_create_protected_data_page() to realm_data_map_init().
Changes since v12:
* The ioctl now updates the structure with the amount populated rather than returning this through the ioctl return code.
* Use the new RMM v2.0 range based RMI calls.
* Adapt to upstream changes in kvm_gmem_populate().
Changes since v11:
* The multiplex CAP is gone and there's a new ioctl which makes use of the generic kvm_gmem_populate() functionality.
Changes since v7:
* Improve the error codes.
* Other minor changes from review.
Changes since v6:
* Handle host potentially having a larger page size than the RMM granule.
* Drop historic "par" (protected address range) from populate_par_region() - it doesn't exist within the current architecture.
* Add a cond_resched() call in kvm_populate_realm().
Changes since v5:
* Refactor to use PFNs rather than tracking struct page in realm_create_protected_data_page().
* Pull changes from a later patch (in the v5 series) for accessing pages from a guest memfd.
* Do the populate in chunks to avoid holding locks for too long and triggering RCU stall warnings.

---
 arch/arm64/include/asm/kvm_rmi.h |   4 ++
 arch/arm64/kvm/Kconfig           |   1 +
 arch/arm64/kvm/arm.c             |  13 ++++
 arch/arm64/kvm/rmi.c             | 119 +++++++++++++++++++++++++++++++
 4 files changed, 137 insertions(+)
arch/arm64/include/asm/kvm_rmi.h +4 -0
index 5cb99c187202..fd0c57594a22 100644
@@ -105,6 +105,10 @@ int kvm_rec_enter(struct kvm_vcpu *vcpu);
 int kvm_rec_pre_enter(struct kvm_vcpu *vcpu);
 int handle_rec_exit(struct kvm_vcpu *vcpu, int rec_run_status);
 
+struct kvm_arm_rmi_populate;
+
+int kvm_arm_rmi_populate(struct kvm *kvm,
+			 struct kvm_arm_rmi_populate *arg);
 void kvm_realm_unmap_range(struct kvm *kvm,
 			   unsigned long ipa,
 			   unsigned long size,
arch/arm64/kvm/Kconfig +1 -0
index 189e8ad78b22..83b95e836b4d 100644
@@ -37,6 +37,7 @@ menuconfig KVM
 	select SCHED_INFO
 	select GUEST_PERF_EVENTS if PERF_EVENTS
 	select KVM_GUEST_MEMFD
+	select HAVE_KVM_ARCH_GMEM_POPULATE
 	select ARM_RMM
 	help
 	  Support hosting virtualized guest machines.
arch/arm64/kvm/arm.c +13 -0
index df33322b8fea..1558bb12b1b1 100644
@@ -2153,6 +2153,19 @@ int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
 			return -EFAULT;
 		return kvm_vm_ioctl_get_reg_writable_masks(kvm, &range);
 	}
+	case KVM_ARM_RMI_POPULATE: {
+		struct kvm_arm_rmi_populate req;
+		int ret;
+
+		if (!kvm_is_realm(kvm))
+			return -ENXIO;
+		if (copy_from_user(&req, argp, sizeof(req)))
+			return -EFAULT;
+		ret = kvm_arm_rmi_populate(kvm, &req);
+		if (copy_to_user(argp, &req, sizeof(req)))
+			return -EFAULT;
+		return ret;
+	}
 	default:
 		return -EINVAL;
 	}
arch/arm64/kvm/rmi.c +15 -0
index 53b5b18f2275..e2b4c64e982d 100644
@@ -590,6 +590,76 @@ void kvm_realm_unmap_range(struct kvm *kvm, unsigned long start,
 		realm_unmap_private_range(kvm, start, end, may_block);
 }
 
+static int realm_data_map_init(struct kvm *kvm, unsigned long ipa,
+			       kvm_pfn_t dst_pfn, kvm_pfn_t src_pfn,
+			       unsigned long flags)
+{
+	struct realm *realm = &kvm->arch.realm;
+	phys_addr_t rd = virt_to_phys(realm->rd);
+	phys_addr_t dst_phys, src_phys;
+	int ret;
+
+	lockdep_assert_held(&kvm->slots_lock);
+	lockdep_assert_held(&kvm->arch.config_lock);
+
+	dst_phys = __pfn_to_phys(dst_pfn);
+	src_phys = __pfn_to_phys(src_pfn);
+

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

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+	if (rmi_delegate_page(dst_phys))
+		return -ENXIO;
+
+retry:
+	ret = rmi_rtt_data_map_init(rd, dst_phys, ipa, src_phys, flags);
+	if (RMI_RETURN_STATUS(ret) == RMI_ERROR_RTT) {
+		/* Create missing RTTs and retry */
+		int level = RMI_RETURN_INDEX(ret);
+
+		KVM_BUG_ON(level >= KVM_PGTABLE_LAST_LEVEL, kvm);

Surely you should break here and make it stop, right? The VM is bugged anyway, so what's the point in continuing?

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

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+
+		ret = realm_create_rtt_levels(realm, ipa, level,
+					      level + 1, NULL);
+		if (!ret)
+			goto retry;
+	}
+
+	if (ret && WARN_ON(rmi_undelegate_page(dst_phys))) {
+		/* Leak the page if the undelegate fails */
+		get_page(pfn_to_page(dst_pfn));

Same here. The VM should be dead.

Quoted 44 lines
arch/arm64/kvm/rmi.c +37 -0
+	}
+
+	return ret <= 0 ? ret : -ENXIO;
+}
+
+static int populate_region_cb(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn,
+			      struct page *src_page, void *opaque)
+{
+	unsigned long data_flags = *(unsigned long *)opaque;
+	phys_addr_t ipa = gfn_to_gpa(gfn);
+
+	return realm_data_map_init(kvm, ipa, pfn, page_to_pfn(src_page),
+				   data_flags);
+}
+
+static long populate_region(struct kvm *kvm,
+			    gfn_t base_gfn,
+			    unsigned long pages,
+			    u64 uaddr,
+			    unsigned long data_flags)
+{
+	long ret = 0;
+
+	lockdep_assert_held(&kvm->slots_lock);
+	lockdep_assert_held(&kvm->arch.config_lock);
+
+	if (!uaddr)
+		return -EINVAL;
+
+	ret = kvm_gmem_populate(kvm, base_gfn, u64_to_user_ptr(uaddr), pages,
+				false, populate_region_cb, &data_flags);
+
+	return ret;
+}
+
 enum ripas_action {
 	RIPAS_INIT,
 	RIPAS_SET,
@@ -705,6 +775,55 @@ static int realm_ensure_created(struct kvm *kvm)
 	return realm_create_rd(kvm);
 }
 
+int kvm_arm_rmi_populate(struct kvm *kvm,
+			 struct kvm_arm_rmi_populate *args)

arch/arm64/kvm/rmi.c static int realm_ensure_created(struct kvm *kvm) · line 789

Quoted 10 lines
arch/arm64/kvm/rmi.c +10 -0
+{
+	unsigned long data_flags = 0;
+	unsigned long ipa_start = args->base;
+	unsigned long ipa_end = ipa_start + args->size;
+	long pages_populated;
+	int ret;
+
+	if (args->reserved ||
+	    (args->flags & ~KVM_ARM_RMI_POPULATE_FLAGS_MEASURE) ||
+	    args->base + args->size < args->base ||

More importantly, what checks that this is within the IPA range?

Quoted 30 lines
arch/arm64/kvm/rmi.c +30 -0
+	    !IS_ALIGNED(ipa_start, PAGE_SIZE) ||
+	    !IS_ALIGNED(ipa_end, PAGE_SIZE) ||
+	    !IS_ALIGNED(args->source_uaddr, PAGE_SIZE))
+		return -EINVAL;
+
+	if (args->flags & KVM_ARM_RMI_POPULATE_FLAGS_MEASURE)
+		data_flags |= RMI_MEASURE_CONTENT;
+
+	mutex_lock(&kvm->slots_lock);
+	mutex_lock(&kvm->arch.config_lock);
+
+	ret = realm_ensure_created(kvm);
+	if (ret)
+		goto out_unlock;
+
+	if (args->size == 0)
+		goto out_unlock;
+
+	pages_populated = populate_region(kvm, gpa_to_gfn(ipa_start),
+					  args->size >> PAGE_SHIFT,
+					  args->source_uaddr, data_flags);
+
+	if (pages_populated < 0) {
+		ret = pages_populated;
+		goto out_unlock;
+	}
+
+	args->size -= pages_populated << PAGE_SHIFT;
+	args->source_uaddr += pages_populated << PAGE_SHIFT;
+	args->base += pages_populated << PAGE_SHIFT;

arch/arm64/kvm/rmi.c static int realm_ensure_created(struct kvm *kvm) · line 829

Quoted 10 lines
arch/arm64/kvm/rmi.c +7 -0
+
+out_unlock:
+	mutex_unlock(&kvm->arch.config_lock);
+	mutex_unlock(&kvm->slots_lock);
+	return ret;
+}
+
 static void kvm_complete_ripas_change(struct kvm_vcpu *vcpu)
 {
 	struct kvm *kvm = vcpu->kvm;
	M.
Signature · 1 line
Without deviation from the norm, progress is not possible.
#59 lore raw

Re: [PATCH v15 20/37] KVM: arm64: CCA: Allow populating initial contents

Quoted 126 lines · Marc Zyngier
Quoted 124 lines · Steven Price

The VMM needs to populate the realm with some data before starting (e.g. a kernel and initrd). This is measured by the RMM and used as part of the attestation later on.

---
Changes since v14:
* Holding of locks slots_lock and config_lock have been moved up the callstack with lockdesp assertions placed in the lower functions.
* Add overflow check into kvm_arm_rmi_populate().
Changes since v13:
* Rename realm_create_protected_data_page() to realm_data_map_init().
Changes since v12:
* The ioctl now updates the structure with the amount populated rather than returning this through the ioctl return code.
* Use the new RMM v2.0 range based RMI calls.
* Adapt to upstream changes in kvm_gmem_populate().
Changes since v11:
* The multiplex CAP is gone and there's a new ioctl which makes use of the generic kvm_gmem_populate() functionality.
Changes since v7:
* Improve the error codes.
* Other minor changes from review.
Changes since v6:
* Handle host potentially having a larger page size than the RMM granule.
* Drop historic "par" (protected address range) from populate_par_region() - it doesn't exist within the current architecture.
* Add a cond_resched() call in kvm_populate_realm().
Changes since v5:
* Refactor to use PFNs rather than tracking struct page in realm_create_protected_data_page().
* Pull changes from a later patch (in the v5 series) for accessing pages from a guest memfd.
* Do the populate in chunks to avoid holding locks for too long and triggering RCU stall warnings.

---
 arch/arm64/include/asm/kvm_rmi.h |   4 ++
 arch/arm64/kvm/Kconfig           |   1 +
 arch/arm64/kvm/arm.c             |  13 ++++
 arch/arm64/kvm/rmi.c             | 119 +++++++++++++++++++++++++++++++
 4 files changed, 137 insertions(+)
arch/arm64/include/asm/kvm_rmi.h +4 -0
index 5cb99c187202..fd0c57594a22 100644
@@ -105,6 +105,10 @@ int kvm_rec_enter(struct kvm_vcpu *vcpu);
 int kvm_rec_pre_enter(struct kvm_vcpu *vcpu);
 int handle_rec_exit(struct kvm_vcpu *vcpu, int rec_run_status);
 
+struct kvm_arm_rmi_populate;
+
+int kvm_arm_rmi_populate(struct kvm *kvm,
+			 struct kvm_arm_rmi_populate *arg);
 void kvm_realm_unmap_range(struct kvm *kvm,
 			   unsigned long ipa,
 			   unsigned long size,
arch/arm64/kvm/Kconfig +1 -0
index 189e8ad78b22..83b95e836b4d 100644
@@ -37,6 +37,7 @@ menuconfig KVM
 	select SCHED_INFO
 	select GUEST_PERF_EVENTS if PERF_EVENTS
 	select KVM_GUEST_MEMFD
+	select HAVE_KVM_ARCH_GMEM_POPULATE
 	select ARM_RMM
 	help
 	  Support hosting virtualized guest machines.
arch/arm64/kvm/arm.c +13 -0
index df33322b8fea..1558bb12b1b1 100644
@@ -2153,6 +2153,19 @@ int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
 			return -EFAULT;
 		return kvm_vm_ioctl_get_reg_writable_masks(kvm, &range);
 	}
+	case KVM_ARM_RMI_POPULATE: {
+		struct kvm_arm_rmi_populate req;
+		int ret;
+
+		if (!kvm_is_realm(kvm))
+			return -ENXIO;
+		if (copy_from_user(&req, argp, sizeof(req)))
+			return -EFAULT;
+		ret = kvm_arm_rmi_populate(kvm, &req);
+		if (copy_to_user(argp, &req, sizeof(req)))
+			return -EFAULT;
+		return ret;
+	}
 	default:
 		return -EINVAL;
 	}
arch/arm64/kvm/rmi.c +20 -0
index 53b5b18f2275..e2b4c64e982d 100644
@@ -590,6 +590,76 @@ void kvm_realm_unmap_range(struct kvm *kvm, unsigned long start,
 		realm_unmap_private_range(kvm, start, end, may_block);
 }
 
+static int realm_data_map_init(struct kvm *kvm, unsigned long ipa,
+			       kvm_pfn_t dst_pfn, kvm_pfn_t src_pfn,
+			       unsigned long flags)
+{
+	struct realm *realm = &kvm->arch.realm;
+	phys_addr_t rd = virt_to_phys(realm->rd);
+	phys_addr_t dst_phys, src_phys;
+	int ret;
+
+	lockdep_assert_held(&kvm->slots_lock);
+	lockdep_assert_held(&kvm->arch.config_lock);
+
+	dst_phys = __pfn_to_phys(dst_pfn);
+	src_phys = __pfn_to_phys(src_pfn);
+
+	if (rmi_delegate_page(dst_phys))
+		return -ENXIO;
+
+retry:
+	ret = rmi_rtt_data_map_init(rd, dst_phys, ipa, src_phys, flags);
Quoted 8 lines

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

Quoted 5 lines
arch/arm64/kvm/rmi.c +5 -0
+	if (RMI_RETURN_STATUS(ret) == RMI_ERROR_RTT) {
+		/* Create missing RTTs and retry */
+		int level = RMI_RETURN_INDEX(ret);
+
+		KVM_BUG_ON(level >= KVM_PGTABLE_LAST_LEVEL, kvm);

Surely you should break here and make it stop, right? The VM is bugged anyway, so what's the point in continuing?

True, this should have an early error return.

Quoted 4 lines
Quoted 4 lines
arch/arm64/kvm/rmi.c +4 -0
+
+		ret = realm_create_rtt_levels(realm, ipa, level,
+					      level + 1, NULL);
+		if (!ret)
Quoted 8 lines

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

Quoted 6 lines
arch/arm64/kvm/rmi.c +6 -0
+			goto retry;
+	}
+
+	if (ret && WARN_ON(rmi_undelegate_page(dst_phys))) {
+		/* Leak the page if the undelegate fails */
+		get_page(pfn_to_page(dst_pfn));

Same here. The VM should be dead.

Ack.

Quoted 42 lines
Quoted 42 lines
arch/arm64/kvm/rmi.c +35 -0
+	}
+
+	return ret <= 0 ? ret : -ENXIO;
+}
+
+static int populate_region_cb(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn,
+			      struct page *src_page, void *opaque)
+{
+	unsigned long data_flags = *(unsigned long *)opaque;
+	phys_addr_t ipa = gfn_to_gpa(gfn);
+
+	return realm_data_map_init(kvm, ipa, pfn, page_to_pfn(src_page),
+				   data_flags);
+}
+
+static long populate_region(struct kvm *kvm,
+			    gfn_t base_gfn,
+			    unsigned long pages,
+			    u64 uaddr,
+			    unsigned long data_flags)
+{
+	long ret = 0;
+
+	lockdep_assert_held(&kvm->slots_lock);
+	lockdep_assert_held(&kvm->arch.config_lock);
+
+	if (!uaddr)
+		return -EINVAL;
+
+	ret = kvm_gmem_populate(kvm, base_gfn, u64_to_user_ptr(uaddr), pages,
+				false, populate_region_cb, &data_flags);
+
+	return ret;
+}
+
 enum ripas_action {
 	RIPAS_INIT,
 	RIPAS_SET,
@@ -705,6 +775,55 @@ static int realm_ensure_created(struct kvm *kvm)
 	return realm_create_rd(kvm);
 }
 
Quoted 14 lines

arch/arm64/kvm/rmi.c static int realm_ensure_created(struct kvm *kvm) · line 789

Quoted 12 lines
arch/arm64/kvm/rmi.c +12 -0
+int kvm_arm_rmi_populate(struct kvm *kvm,
+			 struct kvm_arm_rmi_populate *args)
+{
+	unsigned long data_flags = 0;
+	unsigned long ipa_start = args->base;
+	unsigned long ipa_end = ipa_start + args->size;
+	long pages_populated;
+	int ret;
+
+	if (args->reserved ||
+	    (args->flags & ~KVM_ARM_RMI_POPULATE_FLAGS_MEASURE) ||
+	    args->base + args->size < args->base ||

More importantly, what checks that this is within the IPA range?

So I think this should fail gracefully when we fail to find the memslot. But I agree an explicit check here would be easier to reason about.

Thanks,
Steve

Quoted 43 lines
Quoted 30 lines
arch/arm64/kvm/rmi.c +30 -0
+	    !IS_ALIGNED(ipa_start, PAGE_SIZE) ||
+	    !IS_ALIGNED(ipa_end, PAGE_SIZE) ||
+	    !IS_ALIGNED(args->source_uaddr, PAGE_SIZE))
+		return -EINVAL;
+
+	if (args->flags & KVM_ARM_RMI_POPULATE_FLAGS_MEASURE)
+		data_flags |= RMI_MEASURE_CONTENT;
+
+	mutex_lock(&kvm->slots_lock);
+	mutex_lock(&kvm->arch.config_lock);
+
+	ret = realm_ensure_created(kvm);
+	if (ret)
+		goto out_unlock;
+
+	if (args->size == 0)
+		goto out_unlock;
+
+	pages_populated = populate_region(kvm, gpa_to_gfn(ipa_start),
+					  args->size >> PAGE_SHIFT,
+					  args->source_uaddr, data_flags);
+
+	if (pages_populated < 0) {
+		ret = pages_populated;
+		goto out_unlock;
+	}
+
+	args->size -= pages_populated << PAGE_SHIFT;
+	args->source_uaddr += pages_populated << PAGE_SHIFT;
+	args->base += pages_populated << PAGE_SHIFT;

arch/arm64/kvm/rmi.c static int realm_ensure_created(struct kvm *kvm) · line 829

Quoted 10 lines
arch/arm64/kvm/rmi.c +7 -0
+
+out_unlock:
+	mutex_unlock(&kvm->arch.config_lock);
+	mutex_unlock(&kvm->slots_lock);
+	return ret;
+}
+
 static void kvm_complete_ripas_change(struct kvm_vcpu *vcpu)
 {
 	struct kvm *kvm = vcpu->kvm;
	M.
#60 lore raw

PATCH v15 21/37 KVM: arm64: CCA: Set RIPAS of initial memslots

In reply to Steven Price

The memory which the realm guest accesses must be set to RIPAS_RAM. Iterate over the memslots and set all gmem memslots to RIPAS_RAM.

---
New patch for v12.

---
 arch/arm64/kvm/rmi.c | 38 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 38 insertions(+)
arch/arm64/kvm/rmi.c +38 -0
index e2b4c64e982d..1e6c04145f6c 100644
@@ -757,6 +757,14 @@ static int realm_set_ipa_state(struct kvm_vcpu *vcpu,
 	return ret;
 }
 
+static int realm_init_ipa_state(struct kvm *kvm,
+				unsigned long gfn,
+				unsigned long pages)
+{
+	return ripas_change(kvm, NULL, gfn_to_gpa(gfn), gfn_to_gpa(gfn + pages),
+			    RIPAS_INIT, NULL);
+}
+
 static int realm_ensure_created(struct kvm *kvm)
 {
 	lockdep_assert_held(&kvm->arch.config_lock);
@@ -775,6 +783,32 @@ static int realm_ensure_created(struct kvm *kvm)
 	return realm_create_rd(kvm);
 }
 
+static int set_ripas_of_protected_regions(struct kvm *kvm)
+{
+	struct kvm_memslots *slots;
+	struct kvm_memory_slot *memslot;
+	int idx, bkt;
+	int ret = 0;
+
+	lockdep_assert_held(&kvm->arch.config_lock);
+
+	idx = srcu_read_lock(&kvm->srcu);
+
+	slots = kvm_memslots(kvm);
+	kvm_for_each_memslot(memslot, bkt, slots) {
+		if (!kvm_slot_has_gmem(memslot))
+			continue;
+
+		ret = realm_init_ipa_state(kvm, memslot->base_gfn,
+					   memslot->npages);
+		if (ret)
+			break;
+	}
+	srcu_read_unlock(&kvm->srcu, idx);
+
+	return ret;
+}
+
 int kvm_arm_rmi_populate(struct kvm *kvm,
 			 struct kvm_arm_rmi_populate *args)
 {
@@ -1045,6 +1079,10 @@ int kvm_activate_realm(struct kvm *kvm)
 			return ret;
 	}
 
+	ret = set_ripas_of_protected_regions(kvm);
+	if (ret)
+		return ret;
+
 	ret = rmi_realm_activate(virt_to_phys(realm->rd));
 	if (ret)
 		return -ENXIO;
Signature · 1 line
2.43.0
#61 lore raw

PATCH v15 22/37 KVM: arm64: CCA: Support runtime faulting of memory

In reply to Steven Price

At runtime if the realm guest accesses memory which hasn't yet been mapped then KVM needs to either populate the region or fault the guest.

For memory in the lower (protected) region of IPA a fresh page is provided to the RMM which will zero the contents. For memory in the upper (shared) region of IPA, the memory from the memslot is mapped into the realm VM non secure.

---
Changes since v13:
* Numerous changes due to rebasing.
* Fix addr_range_desc() to encode the correct block size.
Changes since v12:
* Switch to RMM v2.0 range based APIs.
Changes since v11:
* Adapt to upstream changes.
Changes since v10:
* RME->RMI renaming.
* Adapt to upstream gmem changes.
Changes since v9:
* Fix call to kvm_stage2_unmap_range() in kvm_free_stage2_pgd() to set may_block to avoid stall warnings.
* Minor coding style fixes.
Changes since v8:
* Propagate the may_block flag.
* Minor comments and coding style changes.
Changes since v7:
* Remove redundant WARN_ONs for realm_create_rtt_levels() - it will internally WARN when necessary.
Changes since v6:
* Handle PAGE_SIZE being larger than RMM granule size.
* Some minor renaming following review comments.
Changes since v5:
* Reduce use of struct page in preparation for supporting the RMM having a different page size to the host.
* Handle a race when delegating a page where another CPU has faulted on a the same page (and already delegated the physical page) but not yet mapped it. In this case simply return to the guest to either use the mapping from the other CPU (or refault if the race is lost).
* The changes to populate_par_region() are moved into the previous patch where they belong.
Changes since v4:
* Code cleanup following review feedback.
* Drop the PTE_SHARED bit when creating unprotected page table entries. This is now set by the RMM and the host has no control of it and the spec requires the bit to be set to zero.
Changes since v2:
* Avoid leaking memory if failing to map it in the realm.
* Correctly mask RTT based on LPA2 flag (see rtt_get_phys()).
* Adapt to changes in previous patches.

---
 arch/arm64/include/asm/kvm_emulate.h |   8 +
 arch/arm64/include/asm/kvm_rmi.h     |   5 +
 arch/arm64/kvm/mmu.c                 |  97 ++++++++----
 arch/arm64/kvm/rmi.c                 | 214 +++++++++++++++++++++++++++
 4 files changed, 298 insertions(+), 26 deletions(-)
arch/arm64/include/asm/kvm_emulate.h +8 -0
index 2e69fe494716..8b6f9d26b5d8 100644
@@ -712,6 +712,14 @@ static inline bool kvm_realm_is_created(struct kvm *kvm)
 	return kvm_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_is_realm(kvm))
+		return ipa;
+
+	return ipa & ~BIT(kvm->arch.realm.ia_bits - 1);
+}
+
 static inline bool vcpu_is_rec(const struct kvm_vcpu *vcpu)
 {
 	return kvm_is_realm(vcpu->kvm);
arch/arm64/include/asm/kvm_rmi.h +5 -0
index fd0c57594a22..718c7128a3c3 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>
 
 /**
@@ -114,6 +115,10 @@ void kvm_realm_unmap_range(struct kvm *kvm,
 			   unsigned long size,
 			   bool unmap_private,
 			   bool may_block);
+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)
arch/arm64/kvm/mmu.c +71 -26

210 lines not on this page · raw message

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

220 lines not on this page · raw message

Signature · 1 line
2.43.0
#62 lore raw

PATCH v15 23/37 KVM: arm64: CCA: Handle realm vCPU load

In reply to Steven Price

When loading a realm VCPU much of the work is handled by the RMM so only some of the actions are required. Rearrange kvm_arch_vcpu_load() slightly so we can bail out early for a realm guest.

---
 arch/arm64/kvm/arm.c | 19 ++++++++++++-------
 1 file changed, 12 insertions(+), 7 deletions(-)
arch/arm64/kvm/arm.c +12 -7
index 1558bb12b1b1..4ad9462e9d47 100644
@@ -707,7 +707,7 @@ void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
 	struct kvm_s2_mmu *mmu;
 	int *last_ran;
 
-	if (is_protected_kvm_enabled())
+	if (is_protected_kvm_enabled() || kvm_is_realm(vcpu->kvm))
 		goto nommu;
 
 	if (vcpu_has_nv(vcpu))
@@ -751,12 +751,6 @@ void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
 	kvm_vgic_load(vcpu);
 	kvm_vcpu_load_debug(vcpu);
 	kvm_vcpu_load_fgt(vcpu);
-	if (has_vhe())
-		kvm_vcpu_load_vhe(vcpu);
-	kvm_arch_vcpu_load_fp(vcpu);
-	kvm_vcpu_pmu_restore_guest(vcpu);
-	if (kvm_arm_is_pvtime_enabled(&vcpu->arch))
-		kvm_make_request(KVM_REQ_RECORD_STEAL, vcpu);
 
 	if (kvm_vcpu_should_clear_twe(vcpu))
 		vcpu->arch.hcr_el2 &= ~HCR_TWE;
@@ -778,6 +772,17 @@ void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
 			     &vcpu->arch.vgic_cpu.vgic_v3);
 	}
 
+	/* No additional state needs to be loaded on Realmed VMs */
+	if (vcpu_is_rec(vcpu))
+		return;
+
+	if (has_vhe())
+		kvm_vcpu_load_vhe(vcpu);
+	kvm_arch_vcpu_load_fp(vcpu);
+	kvm_vcpu_pmu_restore_guest(vcpu);
+	if (kvm_arm_is_pvtime_enabled(&vcpu->arch))
+		kvm_make_request(KVM_REQ_RECORD_STEAL, vcpu);
+
 	if (!cpumask_test_cpu(cpu, vcpu->kvm->arch.supported_cpus))
 		vcpu_set_on_unsupported_cpu(vcpu);
 
Signature · 1 line
2.43.0
#63 lore raw

PATCH v15 24/37 KVM: arm64: CCA: Validate register access for Realm VMs

In reply to Steven Price

The RMM only allows setting the GPRS (x0-x30) and PC for a realm guest. Check this in kvm_arm_set_reg() so that the VMM can receive a suitable error return if other registers are written to.

The RMM makes similar restrictions for reading of the guest's registers (this is *confidential* compute after all), however we don't impose the restriction here. This allows the VMM to read (stale) values from the registers which might be useful to read back the initial values even if the RMM doesn't provide the latest version. For migration of a realm VM, a new interface will be needed so that the VMM can receive an (encrypted) blob of the VM's state.

---
Changes since v5:
* Upper GPRS can be set as part of a HOST_CALL return, so fix up the test to allow them.

---
 arch/arm64/kvm/guest.c | 41 +++++++++++++++++++++++++++++++++++++++++
 1 file changed, 41 insertions(+)
arch/arm64/kvm/guest.c +41 -0
index b01d6622b872..3e970c4f6214 100644
@@ -73,6 +73,25 @@ static u64 core_reg_offset_from_id(u64 id)
 	return id & ~(KVM_REG_ARCH_MASK | KVM_REG_SIZE_MASK | KVM_REG_ARM_CORE);
 }
 
+static bool kvm_realm_validate_core_reg(u64 off)
+{
+	/*
+	 * Note that GPRs can only sometimes be controlled by the VMM.
+	 * For PSCI only X0-X6 are used, higher registers are ignored (restored
+	 * from the REC).
+	 * For HOST_CALL all of X0-X30 are copied to the RsiHostCall structure.
+	 * For emulated MMIO X0 is always used.
+	 * PC can only be set before the realm is activated.
+	 */
+	switch (off) {
+	case KVM_REG_ARM_CORE_REG(regs.regs[0]) ...
+	     KVM_REG_ARM_CORE_REG(regs.regs[30]):
+	case KVM_REG_ARM_CORE_REG(regs.pc):
+		return true;
+	}
+	return false;
+}
+
 static int core_reg_size_from_offset(const struct kvm_vcpu *vcpu, u64 off)
 {
 	int size;
@@ -716,12 +735,34 @@ int kvm_arm_get_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
 	return kvm_arm_sys_reg_get_reg(vcpu, reg);
 }
 
+/*
+ * The RMI ABI only enables setting some GPRs and PC. The selection of GPRs
+ * that are available depends on the Realm state and the reason for the last
+ * exit.  All other registers are reset to architectural or otherwise defined
+ * reset values by the RMM, except for a few configuration fields that
+ * correspond to Realm parameters.
+ */
+static bool validate_realm_set_reg(struct kvm_vcpu *vcpu,
+				   const struct kvm_one_reg *reg)
+{
+	if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_CORE) {
+		u64 off = core_reg_offset_from_id(reg->id);
+
+		return kvm_realm_validate_core_reg(off);
+	}
+
+	return false;
+}
+
 int kvm_arm_set_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
 {
 	/* We currently use nothing arch-specific in upper 32 bits */
 	if ((reg->id & ~KVM_REG_SIZE_MASK) >> 32 != KVM_REG_ARM64 >> 32)
 		return -EINVAL;
 
+	if (kvm_is_realm(vcpu->kvm) && !validate_realm_set_reg(vcpu, reg))
+		return -EINVAL;
+
 	switch (reg->id & KVM_REG_ARM_COPROC_MASK) {
 	case KVM_REG_ARM_CORE:	return set_core_reg(vcpu, reg);
 	case KVM_REG_ARM_FW:
Signature · 1 line
2.43.0
#64 lore raw

PATCH v15 25/37 KVM: arm64: CCA: Handle Realm PSCI requests

In reply to Steven Price

Some PSCI commands cause a REC exit and the host has to call RMI_PSCI_COMPLETE to provide the status value to return to the guest.

---
Changes since v14:
* Dropped the support for providing the target REC for a PSCI call (as per v2.0-bet2 spec).
Changes since v13:
* The ioctl KVM_ARM_VCPU_RMI_PSCI_COMPLETE has gone. The RMI call is made automatically just before entering the REC again.
Changes since v12:
* Change return code for non-realms to -ENXIO to better represent that the ioctl is invalid for non-realms (checkpatch is insistent that "ENOSYS means 'invalid syscall nr' and nothing else").
Changes since v11:
* RMM->RMI renaming.
Changes since v6:
* Use vcpu_is_rec() rather than kvm_is_realm(vcpu->kvm).
* Minor renaming/formatting fixes.

---
 arch/arm64/include/asm/kvm_rmi.h |  2 ++
 arch/arm64/kvm/psci.c            | 14 ++++++++++++
 arch/arm64/kvm/rmi.c             | 38 ++++++++++++++++++++++++++++++++
 3 files changed, 54 insertions(+)
arch/arm64/include/asm/kvm_rmi.h +2 -0
index 718c7128a3c3..a9bb9aabee5d 100644
@@ -120,6 +120,8 @@ int realm_map_ipa(struct kvm *kvm, phys_addr_t ipa,
 		  enum kvm_pgtable_prot prot,
 		  struct kvm_mmu_memory_cache *memcache);
 
+int realm_psci_complete(struct kvm_vcpu *source, unsigned long status);
+
 static inline bool kvm_realm_is_private_address(struct realm *realm,
 						unsigned long addr)
 {
arch/arm64/kvm/psci.c +14 -0
index 3b5dbe9a0a0e..b0983ee416a2 100644
@@ -142,6 +142,20 @@ static unsigned long kvm_psci_vcpu_affinity_info(struct kvm_vcpu *vcpu)
 	/* Ignore other bits of target affinity */
 	target_affinity &= target_affinity_mask;
 
+	if (vcpu_is_rec(vcpu)) {
+		struct kvm_vcpu *target_vcpu;
+
+		/* RMM supports only zero affinity level */
+		if (lowest_affinity_level != 0)
+			return PSCI_RET_INVALID_PARAMS;
+
+		target_vcpu = kvm_mpidr_to_vcpu(kvm, target_affinity);
+		if (!target_vcpu)
+			return PSCI_RET_INVALID_PARAMS;
+
+		return PSCI_RET_SUCCESS;
+	}
+
 	/*
 	 * If one or more VCPU matching target affinity are running
 	 * then ON else OFF
arch/arm64/kvm/rmi.c +38 -0
index 31effae067c8..8fb6403893e8 100644
@@ -3,6 +3,7 @@
  * Copyright (C) 2023-2026 ARM Ltd.
  */
 
+#include <uapi/linux/psci.h>
 #include <linux/kvm_host.h>
 
 #include <asm/kvm_emulate.h>
@@ -119,6 +120,18 @@ static void free_rtt(phys_addr_t phys)
 	kvm_account_pgtable_pages(phys_to_virt(phys), -1);
 }
 
+int realm_psci_complete(struct kvm_vcpu *source, unsigned long status)
+{
+	int ret;
+
+	ret = rmi_psci_complete(virt_to_phys(source->arch.rec.rec_page),
+				status);
+	if (ret)
+		return -ENXIO;
+
+	return 0;
+}
+
 static int realm_rtt_create(struct realm *realm,
 			    unsigned long addr,
 			    int level,
@@ -1115,6 +1128,28 @@ static void kvm_complete_ripas_change(struct kvm_vcpu *vcpu)
 	rec->run->exit.ripas_base = base;
 }
 
+static void kvm_rec_complete_psci(struct kvm_vcpu *vcpu)
+{
+	struct rec_run *run = vcpu->arch.rec.run;
+	unsigned long status = PSCI_RET_DENIED;
+	unsigned long ret = vcpu_get_reg(vcpu, 0);
+
+	switch (run->exit.gprs[0]) {
+	case PSCI_0_2_FN64_CPU_ON: {
+		if (ret != PSCI_RET_SUCCESS &&
+		    ret != PSCI_RET_ALREADY_ON)
+			status = PSCI_RET_DENIED;
+		else
+			status = PSCI_RET_SUCCESS;
+		break;
+	}
+	default:
+		return;
+	}
+
+	realm_psci_complete(vcpu, status);
+}
+
 /*
  * kvm_rec_pre_enter - Complete operations before entering a REC
  *
@@ -1139,6 +1174,9 @@ int kvm_rec_pre_enter(struct kvm_vcpu *vcpu)
 		for (int i = 0; i < REC_RUN_GPRS; i++)
 			rec->run->enter.gprs[i] = vcpu_get_reg(vcpu, i);
 		break;
+	case RMI_EXIT_PSCI:
+		kvm_rec_complete_psci(vcpu);
+		break;
 	case RMI_EXIT_RIPAS_CHANGE:
 		kvm_complete_ripas_change(vcpu);
 		break;
Signature · 1 line
2.43.0
#65 lore raw

Re: [PATCH v15 25/37] KVM: arm64: CCA: Handle Realm PSCI requests

Quoted 53 lines · Steven Price

Some PSCI commands cause a REC exit and the host has to call RMI_PSCI_COMPLETE to provide the status value to return to the guest.

---
Changes since v14:
* Dropped the support for providing the target REC for a PSCI call (as

    per v2.0-bet2 spec).

Changes since v13:
* The ioctl KVM_ARM_VCPU_RMI_PSCI_COMPLETE has gone. The RMI call is made automatically just before entering the REC again.
Changes since v12:
* Change return code for non-realms to -ENXIO to better represent that the ioctl is invalid for non-realms (checkpatch is insistent that "ENOSYS means 'invalid syscall nr' and nothing else").
Changes since v11:
* RMM->RMI renaming.
Changes since v6:
* Use vcpu_is_rec() rather than kvm_is_realm(vcpu->kvm).
* Minor renaming/formatting fixes.

---
  arch/arm64/include/asm/kvm_rmi.h |  2 ++
  arch/arm64/kvm/psci.c            | 14 ++++++++++++
  arch/arm64/kvm/rmi.c             | 38 ++++++++++++++++++++++++++++++++
  3 files changed, 54 insertions(+)
arch/arm64/include/asm/kvm_rmi.h +2 -0
index 718c7128a3c3..a9bb9aabee5d 100644
@@ -120,6 +120,8 @@ int realm_map_ipa(struct kvm *kvm, phys_addr_t ipa,
  		  enum kvm_pgtable_prot prot,
  		  struct kvm_mmu_memory_cache *memcache);
 
+int realm_psci_complete(struct kvm_vcpu *source, unsigned long status);
+
  static inline bool kvm_realm_is_private_address(struct realm *realm,
  						unsigned long addr)
  {
arch/arm64/kvm/psci.c +4 -0
index 3b5dbe9a0a0e..b0983ee416a2 100644
@@ -142,6 +142,20 @@ static unsigned long kvm_psci_vcpu_affinity_info(struct kvm_vcpu *vcpu)
  	/* Ignore other bits of target affinity */
  	target_affinity &= target_affinity_mask;
 
+	if (vcpu_is_rec(vcpu)) {
+		struct kvm_vcpu *target_vcpu;
+
+		/* RMM supports only zero affinity level */

arch/arm64/kvm/psci.c static unsigned long kvm_psci_vcpu_affinity_info(struct kvm_vcpu *vcpu) · line 158

Quoted 10 lines
arch/arm64/kvm/psci.c +10 -0
+		if (lowest_affinity_level != 0)
+			return PSCI_RET_INVALID_PARAMS;
+
+		target_vcpu = kvm_mpidr_to_vcpu(kvm, target_affinity);
+		if (!target_vcpu)
+			return PSCI_RET_INVALID_PARAMS;
+
+		return PSCI_RET_SUCCESS;
+	}
+

We don't have to deal with AFFINITY_INFO anymore with the RMM maintaining the MPIDR to REC mapping. This can be removed.

Otherwise looks good to me.

Suzuki

Quoted 73 lines
arch/arm64/kvm/psci.c +0 -0
  	/*
  	 * If one or more VCPU matching target affinity are running
  	 * then ON else OFF
arch/arm64/kvm/rmi.c +38 -0
index 31effae067c8..8fb6403893e8 100644
@@ -3,6 +3,7 @@
   * Copyright (C) 2023-2026 ARM Ltd.
   */
 
+#include <uapi/linux/psci.h>
  #include <linux/kvm_host.h>
 
  #include <asm/kvm_emulate.h>
@@ -119,6 +120,18 @@ static void free_rtt(phys_addr_t phys)
  	kvm_account_pgtable_pages(phys_to_virt(phys), -1);
  }
 
+int realm_psci_complete(struct kvm_vcpu *source, unsigned long status)
+{
+	int ret;
+
+	ret = rmi_psci_complete(virt_to_phys(source->arch.rec.rec_page),
+				status);
+	if (ret)
+		return -ENXIO;
+
+	return 0;
+}
+
  static int realm_rtt_create(struct realm *realm,
  			    unsigned long addr,
  			    int level,
@@ -1115,6 +1128,28 @@ static void kvm_complete_ripas_change(struct kvm_vcpu *vcpu)
  	rec->run->exit.ripas_base = base;
  }
 
+static void kvm_rec_complete_psci(struct kvm_vcpu *vcpu)
+{
+	struct rec_run *run = vcpu->arch.rec.run;
+	unsigned long status = PSCI_RET_DENIED;
+	unsigned long ret = vcpu_get_reg(vcpu, 0);
+
+	switch (run->exit.gprs[0]) {
+	case PSCI_0_2_FN64_CPU_ON: {
+		if (ret != PSCI_RET_SUCCESS &&
+		    ret != PSCI_RET_ALREADY_ON)
+			status = PSCI_RET_DENIED;
+		else
+			status = PSCI_RET_SUCCESS;
+		break;
+	}
+	default:
+		return;
+	}
+
+	realm_psci_complete(vcpu, status);
+}
+
  /*
   * kvm_rec_pre_enter - Complete operations before entering a REC
   *
@@ -1139,6 +1174,9 @@ int kvm_rec_pre_enter(struct kvm_vcpu *vcpu)
  		for (int i = 0; i < REC_RUN_GPRS; i++)
  			rec->run->enter.gprs[i] = vcpu_get_reg(vcpu, i);
  		break;
+	case RMI_EXIT_PSCI:
+		kvm_rec_complete_psci(vcpu);
+		break;
  	case RMI_EXIT_RIPAS_CHANGE:
  		kvm_complete_ripas_change(vcpu);
  		break;
#66 lore raw

PATCH v15 26/37 KVM: arm64: WARN on injected undef exceptions

In reply to Steven Price

The RMM doesn't allow injection of a undefined exception into a realm guest. Add a WARN to catch if this ever happens.

---
Changes since v6:
* if (x) WARN(1, ...) makes no sense, just WARN(x, ...)!

---
 arch/arm64/kvm/inject_fault.c | 1 +
 1 file changed, 1 insertion(+)
arch/arm64/kvm/inject_fault.c +1 -0
index 6492397b73d7..613f223bc7a3 100644
@@ -327,6 +327,7 @@ void kvm_inject_size_fault(struct kvm_vcpu *vcpu)
  */
 void kvm_inject_undefined(struct kvm_vcpu *vcpu)
 {
+	WARN(vcpu_is_rec(vcpu), "Unexpected undefined exception injection to REC");
 	if (vcpu_el1_is_32bit(vcpu))
 		inject_undef32(vcpu);
 	else
Signature · 1 line
2.43.0
maintainer
#67 lore raw

Re: [PATCH v15 26/37] KVM: arm64: WARN on injected undef exceptions

Quoted 19 lines · Steven Price

The RMM doesn't allow injection of a undefined exception into a realm guest. Add a WARN to catch if this ever happens.

---
Changes since v6:
* if (x) WARN(1, ...) makes no sense, just WARN(x, ...)!

---
 arch/arm64/kvm/inject_fault.c | 1 +
 1 file changed, 1 insertion(+)
arch/arm64/kvm/inject_fault.c +0 -0
index 6492397b73d7..613f223bc7a3 100644

arch/arm64/kvm/inject_fault.c void kvm_inject_size_fault(struct kvm_vcpu *vcpu) · line 333

Quoted 7 lines
arch/arm64/kvm/inject_fault.c +1 -0
@@ -327,6 +327,7 @@ void kvm_inject_size_fault(struct kvm_vcpu *vcpu)
  */
 void kvm_inject_undefined(struct kvm_vcpu *vcpu)
 {
+	WARN(vcpu_is_rec(vcpu), "Unexpected undefined exception injection to REC");
 	if (vcpu_el1_is_32bit(vcpu))
 		inject_undef32(vcpu);
 	else

No. WARN_ONCE at a push, but even then, this looks dodgy.

Exceptions must be injectable. Otherwise, how do you respond to, for example, a sysreg access for a feature that is hidden from the guest?

Will the RMM perform this in KVM's stead?

	M.
Signature · 1 line
Jazz isn't dead. It just smells funny.
#68 lore raw

Re: [PATCH v15 26/37] KVM: arm64: WARN on injected undef exceptions

Quoted 16 lines · Marc Zyngier
Quoted 14 lines · Steven Price

The RMM doesn't allow injection of a undefined exception into a realm guest. Add a WARN to catch if this ever happens.

---
Changes since v6:
* if (x) WARN(1, ...) makes no sense, just WARN(x, ...)!

---
 arch/arm64/kvm/inject_fault.c | 1 +
 1 file changed, 1 insertion(+)
Quoted 14 lines

arch/arm64/kvm/inject_fault.c void kvm_inject_size_fault(struct kvm_vcpu *vcpu) · line 333

Quoted 12 lines
arch/arm64/kvm/inject_fault.c +1 -0
index 6492397b73d7..613f223bc7a3 100644
@@ -327,6 +327,7 @@ void kvm_inject_size_fault(struct kvm_vcpu *vcpu)
  */
 void kvm_inject_undefined(struct kvm_vcpu *vcpu)
 {
+	WARN(vcpu_is_rec(vcpu), "Unexpected undefined exception injection to REC");
 	if (vcpu_el1_is_32bit(vcpu))
 		inject_undef32(vcpu);
 	else

No. WARN_ONCE at a push, but even then, this looks dodgy.

Yep WARN_ONCE() would be better. This function should never be called for a realm guest.

Quoted 2 lines

Exceptions must be injectable. Otherwise, how do you respond to, for example, a sysreg access for a feature that is hidden from the guest?

The RMM doesn't allow the host to inject exceptions - with the exception of SEA after a host-emulated MMIO.

Quoted 1 line

Will the RMM perform this in KVM's stead?

Yes the RMM would have to handle this for the likes of sysreg accesses. The host doesn't control the trapping of sysreg accesses. There are a few GIC-related registers which are forwarded to the host ("REC exit due to system register access") but generally the handling of sysregs is entirely internal to the RMM.

Thanks,
Steve

maintainer
#69 lore raw

Re: [PATCH v15 26/37] KVM: arm64: WARN on injected undef exceptions

Quoted 42 lines · Steven Price
Quoted 16 lines · Marc Zyngier
Quoted 14 lines · Steven Price

The RMM doesn't allow injection of a undefined exception into a realm guest. Add a WARN to catch if this ever happens.

---
Changes since v6:
* if (x) WARN(1, ...) makes no sense, just WARN(x, ...)!

---
 arch/arm64/kvm/inject_fault.c | 1 +
 1 file changed, 1 insertion(+)
Quoted 14 lines

arch/arm64/kvm/inject_fault.c void kvm_inject_size_fault(struct kvm_vcpu *vcpu) · line 333

Quoted 12 lines
arch/arm64/kvm/inject_fault.c +1 -0
index 6492397b73d7..613f223bc7a3 100644
@@ -327,6 +327,7 @@ void kvm_inject_size_fault(struct kvm_vcpu *vcpu)
  */
 void kvm_inject_undefined(struct kvm_vcpu *vcpu)
 {
+	WARN(vcpu_is_rec(vcpu), "Unexpected undefined exception injection to REC");
 	if (vcpu_el1_is_32bit(vcpu))
 		inject_undef32(vcpu);
 	else

No. WARN_ONCE at a push, but even then, this looks dodgy.

Yep WARN_ONCE() would be better. This function should never be called for a realm guest.

Quoted 2 lines

Exceptions must be injectable. Otherwise, how do you respond to, for example, a sysreg access for a feature that is hidden from the guest?

The RMM doesn't allow the host to inject exceptions - with the exception of SEA after a host-emulated MMIO.

Quoted 7 lines
Quoted 1 line

Will the RMM perform this in KVM's stead?

Yes the RMM would have to handle this for the likes of sysreg accesses. The host doesn't control the trapping of sysreg accesses. There are a few GIC-related registers which are forwarded to the host ("REC exit due to system register access") but generally the handling of sysregs is entirely internal to the RMM.

Then the only option is not to just warn, but to mark all realms as dead and refuse to run them any further. If we can't inject an exception and that the RMM isn't doing its job, I can't see how we can continue at all.

	M.
Signature · 1 line
Jazz isn't dead. It just smells funny.
#70 lore raw

Re: [PATCH v15 26/37] KVM: arm64: WARN on injected undef exceptions

Quoted 52 lines · Marc Zyngier
Quoted 42 lines · Steven Price
Quoted 16 lines · Marc Zyngier
Quoted 14 lines · Steven Price

The RMM doesn't allow injection of a undefined exception into a realm guest. Add a WARN to catch if this ever happens.

---
Changes since v6:
* if (x) WARN(1, ...) makes no sense, just WARN(x, ...)!

---
 arch/arm64/kvm/inject_fault.c | 1 +
 1 file changed, 1 insertion(+)
Quoted 14 lines

arch/arm64/kvm/inject_fault.c void kvm_inject_size_fault(struct kvm_vcpu *vcpu) · line 333

Quoted 12 lines
arch/arm64/kvm/inject_fault.c +1 -0
index 6492397b73d7..613f223bc7a3 100644
@@ -327,6 +327,7 @@ void kvm_inject_size_fault(struct kvm_vcpu *vcpu)
  */
 void kvm_inject_undefined(struct kvm_vcpu *vcpu)
 {
+	WARN(vcpu_is_rec(vcpu), "Unexpected undefined exception injection to REC");
 	if (vcpu_el1_is_32bit(vcpu))
 		inject_undef32(vcpu);
 	else

No. WARN_ONCE at a push, but even then, this looks dodgy.

Yep WARN_ONCE() would be better. This function should never be called for a realm guest.

Quoted 2 lines

Exceptions must be injectable. Otherwise, how do you respond to, for example, a sysreg access for a feature that is hidden from the guest?

The RMM doesn't allow the host to inject exceptions - with the exception of SEA after a host-emulated MMIO.

Quoted 7 lines
Quoted 1 line

Will the RMM perform this in KVM's stead?

Yes the RMM would have to handle this for the likes of sysreg accesses. The host doesn't control the trapping of sysreg accesses. There are a few GIC-related registers which are forwarded to the host ("REC exit due to system register access") but generally the handling of sysregs is entirely internal to the RMM.

Quoted 4 lines

Then the only option is not to just warn, but to mark all realms as dead and refuse to run them any further. If we can't inject an exception and that the RMM isn't doing its job, I can't see how we can continue at all.

You've got a point - I'm not sure whether it's entirely reasonable to refuse to run any realm, but it certainly would be sensible to mark the guest which triggers this as dead. Would a KVM_BUG() be more appropriate here?

Thanks,
Steve

maintainer
#71 lore raw

Re: [PATCH v15 26/37] KVM: arm64: WARN on injected undef exceptions

Quoted 54 lines · Steven Price
Quoted 52 lines · Marc Zyngier
Quoted 49 lines · Steven Price
Quoted 16 lines · Marc Zyngier
Quoted 14 lines · Steven Price

The RMM doesn't allow injection of a undefined exception into a realm guest. Add a WARN to catch if this ever happens.

---
Changes since v6:
* if (x) WARN(1, ...) makes no sense, just WARN(x, ...)!

---
 arch/arm64/kvm/inject_fault.c | 1 +
 1 file changed, 1 insertion(+)
Quoted 14 lines

arch/arm64/kvm/inject_fault.c void kvm_inject_size_fault(struct kvm_vcpu *vcpu) · line 333

Quoted 12 lines
arch/arm64/kvm/inject_fault.c +1 -0
index 6492397b73d7..613f223bc7a3 100644
@@ -327,6 +327,7 @@ void kvm_inject_size_fault(struct kvm_vcpu *vcpu)
  */
 void kvm_inject_undefined(struct kvm_vcpu *vcpu)
 {
+	WARN(vcpu_is_rec(vcpu), "Unexpected undefined exception injection to REC");
 	if (vcpu_el1_is_32bit(vcpu))
 		inject_undef32(vcpu);
 	else

No. WARN_ONCE at a push, but even then, this looks dodgy.

Yep WARN_ONCE() would be better. This function should never be called for a realm guest.

Quoted 2 lines

Exceptions must be injectable. Otherwise, how do you respond to, for example, a sysreg access for a feature that is hidden from the guest?

The RMM doesn't allow the host to inject exceptions - with the exception of SEA after a host-emulated MMIO.

Quoted 1 line

Will the RMM perform this in KVM's stead?

Yes the RMM would have to handle this for the likes of sysreg accesses. The host doesn't control the trapping of sysreg accesses. There are a few GIC-related registers which are forwarded to the host ("REC exit due to system register access") but generally the handling of sysregs is entirely internal to the RMM.

Quoted 7 lines
Quoted 4 lines

Then the only option is not to just warn, but to mark all realms as dead and refuse to run them any further. If we can't inject an exception and that the RMM isn't doing its job, I can't see how we can continue at all.

You've got a point - I'm not sure whether it's entirely reasonable to refuse to run any realm, but it certainly would be sensible to mark the

If the RMM is not playing ball by not doing its part of the bargain, the only sane option is stop talking to it immediately. Who knows what else the implementation got wrong?

Quoted 2 lines

guest which triggers this as dead. Would a KVM_BUG() be more appropriate here?

That's the absolutely minimal option. Not necessarily the safe one.

	M.
Signature · 1 line
Jazz isn't dead. It just smells funny.
#72 lore raw

Re: [PATCH v15 26/37] KVM: arm64: WARN on injected undef exceptions

Quoted 61 lines · Marc Zyngier
Quoted 59 lines · Steven Price
Quoted 56 lines · Marc Zyngier
Quoted 42 lines · Steven Price
Quoted 16 lines · Marc Zyngier
Quoted 14 lines · Steven Price

The RMM doesn't allow injection of a undefined exception into a realm guest. Add a WARN to catch if this ever happens.

---
Changes since v6:
* if (x) WARN(1, ...) makes no sense, just WARN(x, ...)!

---
 arch/arm64/kvm/inject_fault.c | 1 +
 1 file changed, 1 insertion(+)
Quoted 14 lines

arch/arm64/kvm/inject_fault.c void kvm_inject_size_fault(struct kvm_vcpu *vcpu) · line 333

Quoted 12 lines
arch/arm64/kvm/inject_fault.c +1 -0
index 6492397b73d7..613f223bc7a3 100644
@@ -327,6 +327,7 @@ void kvm_inject_size_fault(struct kvm_vcpu *vcpu)
  */
 void kvm_inject_undefined(struct kvm_vcpu *vcpu)
 {
+	WARN(vcpu_is_rec(vcpu), "Unexpected undefined exception injection to REC");
 	if (vcpu_el1_is_32bit(vcpu))
 		inject_undef32(vcpu);
 	else

No. WARN_ONCE at a push, but even then, this looks dodgy.

Yep WARN_ONCE() would be better. This function should never be called for a realm guest.

Quoted 2 lines

Exceptions must be injectable. Otherwise, how do you respond to, for example, a sysreg access for a feature that is hidden from the guest?

The RMM doesn't allow the host to inject exceptions - with the exception of SEA after a host-emulated MMIO.

Quoted 7 lines
Quoted 1 line

Will the RMM perform this in KVM's stead?

Yes the RMM would have to handle this for the likes of sysreg accesses. The host doesn't control the trapping of sysreg accesses. There are a few GIC-related registers which are forwarded to the host ("REC exit due to system register access") but generally the handling of sysregs is entirely internal to the RMM.

Then the only option is not to just warn, but to mark all realms as dead and refuse to run them any further. If we can't inject an exception and that the RMM isn't doing its job, I can't see how we can continue at all.

Quoted 6 lines
Quoted 2 lines

You've got a point - I'm not sure whether it's entirely reasonable to refuse to run any realm, but it certainly would be sensible to mark the

If the RMM is not playing ball by not doing its part of the bargain, the only sane option is stop talking to it immediately. Who knows what else the implementation got wrong?

If the RMM isn't playing ball then we're in trouble whatever. Refusing to talk to the RMM ensures that we wouldn't be able to reclaim any of the memory that has been donated to the guest (or related RMM metadata). It also doesn't rule out that a faulty RMM has left a minefield of "delegated" memory which could cause a GPF at any moment. In reality the only "safe" option is to BUG() the kernel and completely give up.

But the chances are that the RMM hasn't suddenly become malicious, and in most likely the situation is that we've hit a corner case which in the RMM which is highly likely to only affect the one guest. "panic_on_warn" is available for those who would prefer the system to stop in these situations.

And of course it's entirely possible that the bug is in Linux and the RMM is playing ball it's just that I've screwed something up. In which case the realm VM is probably screwed, but the rest of the system (including other guests) should be absolutely fine.

I can of course code up a "rmm_is_bugged" flag and litter the code with paths to handle that - but I can't imagine that's actually what you want. Although please do let me know if I'm wrong, I seem to have misplaced my mind reading hat ;)

Quoted 4 lines
Quoted 2 lines

guest which triggers this as dead. Would a KVM_BUG() be more appropriate here?

That's the absolutely minimal option. Not necessarily the safe one.

I'm not sure how to make it "safer" - I don't think there is a completely "safe" option for this "should never happen" case.

Thanks,
Steve

#73 lore raw

PATCH v15 27/37 KVM: arm64: CCA: Allow userspace to inject aborts

In reply to Steven Price

From: Joey Gouly <[email protected]>

Extend KVM_SET_VCPU_EVENTS to support realms, where KVM cannot set the system registers, and the RMM must perform it on next REC entry.

---
 Documentation/virt/kvm/api.rst |  2 ++
 arch/arm64/kvm/guest.c         | 24 ++++++++++++++++++++++++
 2 files changed, 26 insertions(+)
Documentation/virt/kvm/api.rst +2 -0
index e39d146b34a3..85bec9b4f021 100644
@@ -1314,6 +1314,8 @@ User space may need to inject several types of events to the guest.
 Set the pending SError exception state for this VCPU. It is not possible to
 'cancel' an Serror that has been made pending.
 
+User space cannot inject SErrors into Realms.
+
 If the guest performed an access to I/O memory which could not be handled by
 userspace, for example because of missing instruction syndrome decode
 information or because there is no device mapped at the accessed IPA, then
arch/arm64/kvm/guest.c +24 -0
index 3e970c4f6214..5469c9a97fad 100644
@@ -827,6 +827,30 @@ int __kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu,
 	u64 esr = events->exception.serror_esr;
 	int ret = 0;
 
+	if (vcpu_is_rec(vcpu)) {
+		/* Cannot inject SError into a Realm. */
+		if (serror_pending)
+			return -EINVAL;
+
+		/*
+		 * If a data abort is pending, set the flag and let the RMM
+		 * inject an SEA when the REC is scheduled to be run.
+		 */
+		if (ext_dabt_pending) {
+			/*
+			 * Can only inject SEA into a Realm if the previous exit
+			 * was due to a data abort of an Unprotected IPA.
+			 */
+			if (!(vcpu->arch.rec.run->enter.flags & REC_ENTER_FLAG_EMULATED_MMIO))
+				return -EINVAL;
+
+			vcpu->arch.rec.run->enter.flags &= ~REC_ENTER_FLAG_EMULATED_MMIO;
+			vcpu->arch.rec.run->enter.flags |= REC_ENTER_FLAG_INJECT_SEA;
+		}
+
+		return 0;
+	}
+
 	/*
 	 * Immediately commit the pending SEA to the vCPU's architectural
 	 * state which is necessary since we do not return a pending SEA
Signature · 1 line
2.43.0
reviewer Reviewed-by on v15 27/37
#74 lore raw

Re: [PATCH v15 27/37] KVM: arm64: CCA: Allow userspace to inject aborts

Quoted 9 lines · Steven Price

From: Joey Gouly <[email protected]>

Extend KVM_SET_VCPU_EVENTS to support realms, where KVM cannot set the system registers, and the RMM must perform it on next REC entry.

---

Quoted 52 lines
  Documentation/virt/kvm/api.rst |  2 ++
  arch/arm64/kvm/guest.c         | 24 ++++++++++++++++++++++++
  2 files changed, 26 insertions(+)
Documentation/virt/kvm/api.rst +2 -0
index e39d146b34a3..85bec9b4f021 100644
@@ -1314,6 +1314,8 @@ User space may need to inject several types of events to the guest.
  Set the pending SError exception state for this VCPU. It is not possible to
  'cancel' an Serror that has been made pending.
 
+User space cannot inject SErrors into Realms.
+
  If the guest performed an access to I/O memory which could not be handled by
  userspace, for example because of missing instruction syndrome decode
  information or because there is no device mapped at the accessed IPA, then
arch/arm64/kvm/guest.c +24 -0
index 3e970c4f6214..5469c9a97fad 100644
@@ -827,6 +827,30 @@ int __kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu,
  	u64 esr = events->exception.serror_esr;
  	int ret = 0;
 
+	if (vcpu_is_rec(vcpu)) {
+		/* Cannot inject SError into a Realm. */
+		if (serror_pending)
+			return -EINVAL;
+
+		/*
+		 * If a data abort is pending, set the flag and let the RMM
+		 * inject an SEA when the REC is scheduled to be run.
+		 */
+		if (ext_dabt_pending) {
+			/*
+			 * Can only inject SEA into a Realm if the previous exit
+			 * was due to a data abort of an Unprotected IPA.
+			 */
+			if (!(vcpu->arch.rec.run->enter.flags & REC_ENTER_FLAG_EMULATED_MMIO))
+				return -EINVAL;
+
+			vcpu->arch.rec.run->enter.flags &= ~REC_ENTER_FLAG_EMULATED_MMIO;
+			vcpu->arch.rec.run->enter.flags |= REC_ENTER_FLAG_INJECT_SEA;
+		}
+
+		return 0;
+	}
+
  	/*
  	 * Immediately commit the pending SEA to the vCPU's architectural
  	 * state which is necessary since we do not return a pending SEA
#75 lore raw

PATCH v15 28/37 KVM: arm64: CCA: Support RSI_HOST_CALL

In reply to Steven Price

From: Joey Gouly <[email protected]>

Realm VMs can talk to the hypervisor using the RSI_HOST_CALL SMC. The RMM forwards this to the host and KVM handles them as regular hypercalls.

---
Changes since v7:
* Avoid turning a negative return from kvm_smccc_call_handler() into a error response to the guest. Instead propagate the error back to user space.
Changes since v4:
* Setting GPRS is now done by kvm_rec_enter() rather than rec_exit_host_call() (see previous patch - arm64: RME: Handle realm enter/exit). This fixes a bug where the registers set by user space were being ignored.

---
 arch/arm64/kvm/rmi-exit.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
arch/arm64/kvm/rmi-exit.c +15 -0
index c668cbfa971a..78d9189fd5ca 100644
@@ -113,6 +113,19 @@ static int rec_exit_ripas_change(struct kvm_vcpu *vcpu)
 	return -EFAULT;
 }
 
+static int rec_exit_host_call(struct kvm_vcpu *vcpu)
+{
+	int i;
+	struct realm_rec *rec = &vcpu->arch.rec;
+
+	vcpu->stat.hvc_exit_stat++;
+
+	for (i = 0; i < REC_RUN_GPRS; i++)
+		vcpu_set_reg(vcpu, i, rec->run->exit.gprs[i]);
+
+	return kvm_smccc_call_handler(vcpu);
+}
+
 static void update_arch_timer_irq_lines(struct kvm_vcpu *vcpu)
 {
 	struct realm_rec *rec = &vcpu->arch.rec;
@@ -188,6 +201,8 @@ int handle_rec_exit(struct kvm_vcpu *vcpu, int rec_run_ret)
 		return rec_exit_psci(vcpu);
 	case RMI_EXIT_RIPAS_CHANGE:
 		return rec_exit_ripas_change(vcpu);
+	case RMI_EXIT_HOST_CALL:
+		return rec_exit_host_call(vcpu);
 	}
 
 	kvm_pr_unimpl("Unsupported exit reason: %u\n",
Signature · 1 line
2.43.0
reviewer Reviewed-by on v15 28/37
#76 lore raw

Re: [PATCH v15 28/37] KVM: arm64: CCA: Support RSI_HOST_CALL

Quoted 10 lines · Steven Price

From: Joey Gouly <[email protected]>

Realm VMs can talk to the hypervisor using the RSI_HOST_CALL SMC. The RMM forwards this to the host and KVM handles them as regular hypercalls.

---

minor nit: Populating the results back to the Realm is added in the Patch 14: KVM: arm64: CCA: Handle realm enter/exit

May be a good idea to move to this one here ?

Either ways:

Quoted 46 lines

Changes since v7:
* Avoid turning a negative return from kvm_smccc_call_handler() into a error response to the guest. Instead propagate the error back to user space.
Changes since v4:
* Setting GPRS is now done by kvm_rec_enter() rather than rec_exit_host_call() (see previous patch - arm64: RME: Handle realm enter/exit). This fixes a bug where the registers set by user space were being ignored.

---
  arch/arm64/kvm/rmi-exit.c | 15 +++++++++++++++
  1 file changed, 15 insertions(+)
arch/arm64/kvm/rmi-exit.c +15 -0
index c668cbfa971a..78d9189fd5ca 100644
@@ -113,6 +113,19 @@ static int rec_exit_ripas_change(struct kvm_vcpu *vcpu)
  	return -EFAULT;
  }
 
+static int rec_exit_host_call(struct kvm_vcpu *vcpu)
+{
+	int i;
+	struct realm_rec *rec = &vcpu->arch.rec;
+
+	vcpu->stat.hvc_exit_stat++;
+
+	for (i = 0; i < REC_RUN_GPRS; i++)
+		vcpu_set_reg(vcpu, i, rec->run->exit.gprs[i]);
+
+	return kvm_smccc_call_handler(vcpu);
+}
+
  static void update_arch_timer_irq_lines(struct kvm_vcpu *vcpu)
  {
  	struct realm_rec *rec = &vcpu->arch.rec;
@@ -188,6 +201,8 @@ int handle_rec_exit(struct kvm_vcpu *vcpu, int rec_run_ret)
  		return rec_exit_psci(vcpu);
  	case RMI_EXIT_RIPAS_CHANGE:
  		return rec_exit_ripas_change(vcpu);
+	case RMI_EXIT_HOST_CALL:
+		return rec_exit_host_call(vcpu);
  	}
 
  	kvm_pr_unimpl("Unsupported exit reason: %u\n",
#77 lore raw

PATCH v15 29/37 KVM: arm64: CCA: Allow checking SVE on VM instance

In reply to Steven Price

From: Suzuki K Poulose <[email protected]>

Given we have different types of VMs supported, check the support for SVE for the given instance of the VM to accurately report the status.

---
Changes since v10:
* RME->RMI renaming.
* Adapt to move CAP check to kvm_realm_ext_allowed().

---
 arch/arm64/include/asm/kvm_rmi.h | 2 ++
 arch/arm64/kvm/arm.c             | 2 ++
 arch/arm64/kvm/rmi.c             | 5 +++++
 3 files changed, 9 insertions(+)
arch/arm64/include/asm/kvm_rmi.h +2 -0
index a9bb9aabee5d..7f0c059ac7cf 100644
@@ -96,6 +96,8 @@ struct realm_rec {
 void kvm_init_rmi(void);
 u32 kvm_rmm_ipa_limit(void);
 
+bool kvm_rmi_supports_sve(void);
+
 int kvm_init_realm(struct kvm *kvm);
 int kvm_activate_realm(struct kvm *kvm);
 void kvm_destroy_realm(struct kvm *kvm);
arch/arm64/kvm/arm.c +2 -0
index 4ad9462e9d47..aa7617e72e22 100644
@@ -151,6 +151,8 @@ static bool kvm_realm_ext_allowed(long ext)
 	case KVM_CAP_ARM_RMI:
 	case KVM_CAP_SYNC_MMU:
 		return true;
+	case KVM_CAP_ARM_SVE:
+		return kvm_rmi_supports_sve();
 	}
 	return false;
 }
arch/arm64/kvm/rmi.c +5 -0
index 8fb6403893e8..2310f2b608a7 100644
@@ -25,6 +25,11 @@ static bool rmi_has_feature(int reg, unsigned long feature)
 	return !!u64_get_bits(rmi_feat_reg(reg), feature);
 }
 
+bool kvm_rmi_supports_sve(void)
+{
+	return rmi_has_feature(0, RMI_FEATURE_REGISTER_0_SVE);
+}
+
 u32 kvm_rmm_ipa_limit(void)
 {
 	return u64_get_bits(rmi_feat_reg(0), RMI_FEATURE_REGISTER_0_S2SZ);
Signature · 1 line
2.43.0
#78 lore raw

PATCH v15 30/37 KVM: arm64: CCA: Prevent Device mappings for realms

In reply to Steven Price

Physical device assignment is not yet supported. RMM v2.0 does add the relevant APIs, but device assignment is a big topic so will be handled in a future patch series. For now prevent device mappings when the guest is a realm.

---
Changes from v6:
* Fix the check in user_mem_abort() to prevent all pages that are not guest_memfd() from being mapped into the protected half of the IPA.
Changes from v5:
* Also prevent accesses in user_mem_abort()

---
 arch/arm64/kvm/mmu.c | 4 ++++
 1 file changed, 4 insertions(+)
arch/arm64/kvm/mmu.c +4 -0
index 79119cb136b0..dc27f3dfb337 100644
@@ -1261,6 +1261,10 @@ int kvm_phys_addr_ioremap(struct kvm *kvm, phys_addr_t guest_ipa,
 	if (is_protected_kvm_enabled())
 		return -EPERM;
 
+	/* We don't support mapping special pages into a Realm */
+	if (kvm_is_realm(kvm))
+		return -EPERM;
+
 	size += offset_in_page(guest_ipa);
 	guest_ipa &= PAGE_MASK;
 
Signature · 1 line
2.43.0
#79 lore raw

PATCH v15 31/37 KVM: arm64: CCA: Propagate breakpoint and watchpoint counts to userspace

In reply to Steven Price

From: Jean-Philippe Brucker <[email protected]>

The RMM describes the maximum number of BPs/WPs available to the guest in the Feature Register 0. Propagate those numbers into ID_AA64DFR0_EL1, which is visible to userspace. A VMM needs this information in order to set up realm parameters.

---
 arch/arm64/include/asm/kvm_rmi.h |  2 ++
 arch/arm64/kvm/rmi.c             | 19 +++++++++++++++++++
 arch/arm64/kvm/sys_regs.c        |  3 +++
 3 files changed, 24 insertions(+)
arch/arm64/include/asm/kvm_rmi.h +2 -0
index 7f0c059ac7cf..3ec6525ae95f 100644
@@ -96,6 +96,8 @@ struct realm_rec {
 void kvm_init_rmi(void);
 u32 kvm_rmm_ipa_limit(void);
 
+u64 kvm_realm_reset_id_aa64dfr0_el1(const struct kvm_vcpu *vcpu, u64 val);
+
 bool kvm_rmi_supports_sve(void);
 
 int kvm_init_realm(struct kvm *kvm);
arch/arm64/kvm/rmi.c +19 -0
index 2310f2b608a7..491097a57328 100644
@@ -35,6 +35,25 @@ u32 kvm_rmm_ipa_limit(void)
 	return u64_get_bits(rmi_feat_reg(0), RMI_FEATURE_REGISTER_0_S2SZ);
 }
 
+u64 kvm_realm_reset_id_aa64dfr0_el1(const struct kvm_vcpu *vcpu, u64 val)
+{
+	u32 bps = u64_get_bits(rmi_feat_reg(0), RMI_FEATURE_REGISTER_0_NUM_BPS);
+	u32 wps = u64_get_bits(rmi_feat_reg(0), RMI_FEATURE_REGISTER_0_NUM_WPS);
+	u32 ctx_cmps;
+
+	/* Ensure CTX_CMPs is still valid */
+	ctx_cmps = FIELD_GET(ID_AA64DFR0_EL1_CTX_CMPs, val);
+	ctx_cmps = min(bps, ctx_cmps);
+
+	val &= ~(ID_AA64DFR0_EL1_BRPs_MASK | ID_AA64DFR0_EL1_WRPs_MASK |
+		 ID_AA64DFR0_EL1_CTX_CMPs);
+	val |= FIELD_PREP(ID_AA64DFR0_EL1_BRPs_MASK, bps) |
+	       FIELD_PREP(ID_AA64DFR0_EL1_WRPs_MASK, wps) |
+	       FIELD_PREP(ID_AA64DFR0_EL1_CTX_CMPs, ctx_cmps);
+
+	return val;
+}
+
 static int get_start_level(struct realm *realm)
 {
 	return 4 - stage2_pgtable_levels(realm->ia_bits);
arch/arm64/kvm/sys_regs.c +3 -0
index 5d5c579d4579..e0fe9f2562bc 100644
@@ -2142,6 +2142,9 @@ static u64 sanitise_id_aa64dfr0_el1(const struct kvm_vcpu *vcpu, u64 val)
 	/* Hide BRBE from guests */
 	val &= ~ID_AA64DFR0_EL1_BRBE_MASK;
 
+	if (vcpu_is_rec(vcpu))
+		return kvm_realm_reset_id_aa64dfr0_el1(vcpu, val);
+
 	return val;
 }
 
Signature · 1 line
2.43.0
#80 lore raw

PATCH v15 32/37 KVM: arm64: CCA: Set breakpoint parameters through SET_ONE_REG

In reply to Steven Price

From: Jean-Philippe Brucker <[email protected]>

Allow userspace to configure the number of breakpoints and watchpoints of a Realm VM through KVM_SET_ONE_REG ID_AA64DFR0_EL1.

The KVM sys_reg handler checks the user value against the maximum value given by RMM (arm64_check_features() gets it from the read_sanitised_id_aa64dfr0_el1() reset handler).

Userspace discovers that it can write these fields by issuing a KVM_ARM_GET_REG_WRITABLE_MASKS ioctl.

---
 arch/arm64/kvm/guest.c    |  7 +++++++
 arch/arm64/kvm/rmi.c      |  3 +++
 arch/arm64/kvm/sys_regs.c | 17 +++++++++++------
 3 files changed, 21 insertions(+), 6 deletions(-)
arch/arm64/kvm/guest.c +7 -0
index 5469c9a97fad..3ed563e85572 100644
@@ -735,6 +735,8 @@ int kvm_arm_get_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
 	return kvm_arm_sys_reg_get_reg(vcpu, reg);
 }
 
+#define KVM_REG_ARM_ID_AA64DFR0_EL1	ARM64_SYS_REG(3, 0, 0, 5, 0)
+
 /*
  * The RMI ABI only enables setting some GPRs and PC. The selection of GPRs
  * that are available depends on the Realm state and the reason for the last
@@ -749,6 +751,11 @@ static bool validate_realm_set_reg(struct kvm_vcpu *vcpu,
 		u64 off = core_reg_offset_from_id(reg->id);
 
 		return kvm_realm_validate_core_reg(off);
+	} else {
+		switch (reg->id) {
+		case KVM_REG_ARM_ID_AA64DFR0_EL1:
+			return true;
+		}
 	}
 
 	return false;
arch/arm64/kvm/rmi.c +3 -0
index 491097a57328..6850338e2f19 100644
@@ -493,6 +493,7 @@ static int realm_create_rd(struct kvm *kvm)
 	void *rd = NULL;
 	phys_addr_t rd_phys, params_phys, top_delegated;
 	size_t pgd_size = kvm_pgtable_stage2_pgd_size(kvm->arch.mmu.vtcr);
+	u64 dfr0 = kvm_read_vm_id_reg(kvm, SYS_ID_AA64DFR0_EL1);
 	int r;
 
 	realm->ia_bits = VTCR_EL2_IPA(kvm->arch.mmu.vtcr);
@@ -520,6 +521,8 @@ static int realm_create_rd(struct kvm *kvm)
 	params->rtt_level_start = get_start_level(realm);
 	params->rtt_num_start = pgd_size / PAGE_SIZE;
 	params->rtt_base = kvm->arch.mmu.pgd_phys;
+	params->num_bps = SYS_FIELD_GET(ID_AA64DFR0_EL1, BRPs, dfr0);
+	params->num_wps = SYS_FIELD_GET(ID_AA64DFR0_EL1, WRPs, dfr0);
 	params->hash_algo = RMI_HASH_SHA_256;
 
 	if (kvm->arch.arm_pmu) {
arch/arm64/kvm/sys_regs.c +11 -6
index e0fe9f2562bc..e47be8f8d259 100644
@@ -2174,6 +2174,9 @@ static int set_id_aa64dfr0_el1(struct kvm_vcpu *vcpu,
 {
 	u8 debugver = SYS_FIELD_GET(ID_AA64DFR0_EL1, DebugVer, val);
 	u8 pmuver = SYS_FIELD_GET(ID_AA64DFR0_EL1, PMUVer, val);
+	u8 bps = SYS_FIELD_GET(ID_AA64DFR0_EL1, BRPs, val);
+	u8 wps = SYS_FIELD_GET(ID_AA64DFR0_EL1, WRPs, val);
+	u8 ctx_cmps = SYS_FIELD_GET(ID_AA64DFR0_EL1, CTX_CMPs, val);
 
 	/*
 	 * Prior to commit 3d0dba5764b9 ("KVM: arm64: PMU: Move the
@@ -2193,10 +2196,11 @@ static int set_id_aa64dfr0_el1(struct kvm_vcpu *vcpu,
 		val &= ~ID_AA64DFR0_EL1_PMUVer_MASK;
 
 	/*
-	 * ID_AA64DFR0_EL1.DebugVer is one of those awkward fields with a
-	 * nonzero minimum safe value.
+	 * ID_AA64DFR0_EL1.DebugVer, BRPs and WRPs all have to be greater than
+	 * zero. CTX_CMPs is never greater than BRPs.
 	 */
-	if (debugver < ID_AA64DFR0_EL1_DebugVer_IMP)
+	if (debugver < ID_AA64DFR0_EL1_DebugVer_IMP || !bps || !wps ||
+	    ctx_cmps > bps)
 		return -EINVAL;
 
 	if (ignore_feat_doublelock(vcpu, val)) {
@@ -2429,10 +2433,11 @@ static int set_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
 	mutex_lock(&vcpu->kvm->arch.config_lock);
 
 	/*
-	 * Once the VM has started the ID registers are immutable. Reject any
-	 * write that does not match the final register value.
+	 * Once the VM has started or the Realm descriptor is created, the ID
+	 * registers are immutable. Reject any write that does not match the
+	 * final register value.
 	 */
-	if (kvm_vm_has_ran_once(vcpu->kvm)) {
+	if (kvm_vm_has_ran_once(vcpu->kvm) || kvm_realm_is_created(vcpu->kvm)) {
 		if (val != read_id_reg(vcpu, rd))
 			ret = -EBUSY;
 		else
Signature · 1 line
2.43.0
#81 lore raw

PATCH v15 33/37 KVM: arm64: CCA: Propagate max SVE vector length from the RMM

In reply to Steven Price

From: Jean-Philippe Brucker <[email protected]>

RMM provides the maximum vector length it supports for a guest in its feature register. Make it visible to the rest of KVM and to userspace via KVM_REG_ARM64_SVE_VLS.

---
 arch/arm64/include/asm/kvm_host.h |  2 +-
 arch/arm64/include/asm/kvm_rmi.h  |  1 +
 arch/arm64/kvm/guest.c            |  2 +-
 arch/arm64/kvm/reset.c            | 12 ++++++++++--
 arch/arm64/kvm/rmi.c              |  6 ++++++
 5 files changed, 19 insertions(+), 4 deletions(-)
arch/arm64/include/asm/kvm_host.h +1 -1
index 993ead6e6449..3542b32433b7 100644
@@ -78,9 +78,9 @@ enum kvm_mode kvm_get_mode(void);
 static inline enum kvm_mode kvm_get_mode(void) { return KVM_MODE_NONE; };
 #endif
 
-extern unsigned int __ro_after_init kvm_sve_max_vl;
 extern unsigned int __ro_after_init kvm_host_sve_max_vl;
 int __init kvm_arm_init_sve(void);
+unsigned int kvm_sve_get_max_vl(struct kvm *kvm);
 
 u32 __attribute_const__ kvm_target_cpu(void);
 void kvm_reset_vcpu(struct kvm_vcpu *vcpu);
arch/arm64/include/asm/kvm_rmi.h +1 -0
index 3ec6525ae95f..420e99fca07e 100644
@@ -95,6 +95,7 @@ struct realm_rec {
 
 void kvm_init_rmi(void);
 u32 kvm_rmm_ipa_limit(void);
+unsigned int kvm_realm_sve_max_vl(void);
 
 u64 kvm_realm_reset_id_aa64dfr0_el1(const struct kvm_vcpu *vcpu, u64 val);
 
arch/arm64/kvm/guest.c +1 -1
index 3ed563e85572..f48fc0d5a249 100644
@@ -375,7 +375,7 @@ static int set_sve_vls(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
 		if (vq_present(vqs, vq))
 			max_vq = vq;
 
-	if (max_vq > sve_vq_from_vl(kvm_sve_max_vl))
+	if (max_vq > sve_vq_from_vl(kvm_sve_get_max_vl(vcpu->kvm)))
 		return -EINVAL;
 
 	/*
arch/arm64/kvm/reset.c +10 -2
index c18cdca7d125..7b8681a602d4 100644
@@ -46,7 +46,7 @@ unsigned int __ro_after_init kvm_host_sve_max_vl;
 #define VCPU_RESET_PSTATE_SVC	(PSR_AA32_MODE_SVC | PSR_AA32_A_BIT | \
 				 PSR_AA32_I_BIT | PSR_AA32_F_BIT)
 
-unsigned int __ro_after_init kvm_sve_max_vl;
+static unsigned int __ro_after_init kvm_sve_max_vl;
 
 int __init kvm_arm_init_sve(void)
 {
@@ -76,9 +76,17 @@ int __init kvm_arm_init_sve(void)
 	return 0;
 }
 
+unsigned int kvm_sve_get_max_vl(struct kvm *kvm)
+{
+	if (kvm_is_realm(kvm))
+		return kvm_realm_sve_max_vl();
+	else
+		return kvm_sve_max_vl;
+}
+
 static void kvm_vcpu_enable_sve(struct kvm_vcpu *vcpu)
 {
-	vcpu->arch.sve_max_vl = kvm_sve_max_vl;
+	vcpu->arch.sve_max_vl = kvm_sve_get_max_vl(vcpu->kvm);
 
 	/*
 	 * Userspace can still customize the vector lengths by writing
arch/arm64/kvm/rmi.c +6 -0
index 6850338e2f19..cc618608f128 100644
@@ -35,6 +35,12 @@ u32 kvm_rmm_ipa_limit(void)
 	return u64_get_bits(rmi_feat_reg(0), RMI_FEATURE_REGISTER_0_S2SZ);
 }
 
+unsigned int kvm_realm_sve_max_vl(void)
+{
+	return sve_vl_from_vq(u64_get_bits(rmi_feat_reg(0),
+					   RMI_FEATURE_REGISTER_0_SVE_VL) + 1);
+}
+
 u64 kvm_realm_reset_id_aa64dfr0_el1(const struct kvm_vcpu *vcpu, u64 val)
 {
 	u32 bps = u64_get_bits(rmi_feat_reg(0), RMI_FEATURE_REGISTER_0_NUM_BPS);
Signature · 1 line
2.43.0
#82 lore raw

PATCH v15 34/37 KVM: arm64: CCA: Configure max SVE vector length for a Realm

In reply to Steven Price

From: Jean-Philippe Brucker <[email protected]>

Obtain the max vector length configured by userspace on the vCPUs, and write it into the Realm parameters. By default the vCPU is configured with the max vector length reported by RMM, and userspace can reduce it with a write to KVM_REG_ARM64_SVE_VLS.

---
Changes since v6:
* Rename max_vl/realm_max_vl to vl/last_vl - there is nothing "maximum" about them, we're just checking that all realms have the same vector length

---
 arch/arm64/kvm/guest.c |  3 ++-
 arch/arm64/kvm/rmi.c   | 37 +++++++++++++++++++++++++++++++++++++
 2 files changed, 39 insertions(+), 1 deletion(-)
arch/arm64/kvm/guest.c +2 -1
index f48fc0d5a249..452cf5d3152e 100644
@@ -361,7 +361,7 @@ static int set_sve_vls(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
 	if (!vcpu_has_sve(vcpu))
 		return -ENOENT;
 
-	if (kvm_arm_vcpu_sve_finalized(vcpu))
+	if (kvm_arm_vcpu_sve_finalized(vcpu) || kvm_realm_is_created(vcpu->kvm))
 		return -EPERM; /* too late! */
 
 	if (WARN_ON(vcpu->arch.sve_state))
@@ -754,6 +754,7 @@ static bool validate_realm_set_reg(struct kvm_vcpu *vcpu,
 	} else {
 		switch (reg->id) {
 		case KVM_REG_ARM_ID_AA64DFR0_EL1:
+		case KVM_REG_ARM64_SVE_VLS:
 			return true;
 		}
 	}
arch/arm64/kvm/rmi.c +37 -0
index cc618608f128..3f1c6351b71a 100644
@@ -492,6 +492,39 @@ static void realm_unmap_shared_range(struct kvm *kvm,
 			     start, end);
 }
 
+static int realm_init_sve_param(struct kvm *kvm, struct realm_params *params)
+{
+	unsigned long i;
+	struct kvm_vcpu *vcpu;
+	int vl, last_vl = -1;
+
+	if (!kvm_has_sve(kvm))
+		return 0;
+
+	/*
+	 * Get the preferred SVE configuration, set by userspace with the
+	 * KVM_ARM_VCPU_SVE feature and KVM_REG_ARM64_SVE_VLS pseudo-register.
+	 */
+	kvm_for_each_vcpu(i, vcpu, kvm) {
+		if (!kvm_arm_vcpu_sve_finalized(vcpu))
+			return -EINVAL;
+
+		vl = vcpu->arch.sve_max_vl;
+
+		/* We need all vCPUs to have the same SVE config */
+		if (last_vl >= 0 && last_vl != vl)
+			return -EINVAL;
+
+		last_vl = vl;
+	}
+
+	if (last_vl > 0) {
+		params->sve_vl = sve_vq_from_vl(last_vl) - 1;
+		params->flags0 |= RMI_REALM_PARAM_FLAG_SVE;
+	}
+	return 0;
+}
+
 static int realm_create_rd(struct kvm *kvm)
 {
 	struct realm *realm = &kvm->arch.realm;
@@ -539,6 +572,10 @@ static int realm_create_rd(struct kvm *kvm)
 	if (kvm_lpa2_is_enabled())
 		params->flags0 |= RMI_REALM_PARAM_FLAG_LPA2;
 
+	r = realm_init_sve_param(kvm, params);
+	if (r)
+		goto out_undelegate_tables;
+
 	params_phys = virt_to_phys(params);
 
 	if (rmi_realm_create(rd_phys, params_phys, realm->sro)) {
Signature · 1 line
2.43.0
#83 lore raw

PATCH v15 35/37 KVM: arm64: CCA: Provide register list for unfinalized RECs

In reply to Steven Price

From: Jean-Philippe Brucker <[email protected]>

KVM_GET_REG_LIST should not be called before SVE is finalized. The ioctl handler currently returns -EPERM in this case. But because it uses kvm_arm_vcpu_is_finalized(), it now also rejects the call for unfinalized REC even though finalizing the REC can only be done late, after Realm descriptor creation.

Move the check to copy_sve_reg_indices(). One adverse side effect of this change is that a KVM_GET_REG_LIST call that only probes for the array size will now succeed even if SVE is not finalized, but that seems harmless since the following KVM_GET_REG_LIST with the full array will fail.

---
 arch/arm64/kvm/arm.c   |  4 ----
 arch/arm64/kvm/guest.c | 10 +++++-----
 2 files changed, 5 insertions(+), 9 deletions(-)
arch/arm64/kvm/arm.c +0 -4
index aa7617e72e22..3862db30779f 100644
@@ -1966,10 +1966,6 @@ long kvm_arch_vcpu_ioctl(struct file *filp,
 		if (unlikely(!kvm_vcpu_initialized(vcpu)))
 			break;
 
-		r = -EPERM;
-		if (!kvm_arm_vcpu_is_finalized(vcpu))
-			break;
-
 		r = -EFAULT;
 		if (copy_from_user(&reg_list, user_list, sizeof(reg_list)))
 			break;
arch/arm64/kvm/guest.c +5 -5
index 452cf5d3152e..128fec56993a 100644
@@ -617,8 +617,8 @@ static unsigned long num_sve_regs(const struct kvm_vcpu *vcpu)
 	if (!vcpu_has_sve(vcpu))
 		return 0;
 
-	/* Policed by KVM_GET_REG_LIST: */
-	WARN_ON(!kvm_arm_vcpu_sve_finalized(vcpu));
+	if (!kvm_arm_vcpu_sve_finalized(vcpu))
+		return 1; /* KVM_REG_ARM64_SVE_VLS */
 
 	return slices * (SVE_NUM_PREGS + SVE_NUM_ZREGS + 1 /* FFR */)
 		+ 1; /* KVM_REG_ARM64_SVE_VLS */
@@ -635,9 +635,6 @@ static int copy_sve_reg_indices(const struct kvm_vcpu *vcpu,
 	if (!vcpu_has_sve(vcpu))
 		return 0;
 
-	/* Policed by KVM_GET_REG_LIST: */
-	WARN_ON(!kvm_arm_vcpu_sve_finalized(vcpu));
-
 	/*
 	 * Enumerate this first, so that userspace can save/restore in
 	 * the order reported by KVM_GET_REG_LIST:
@@ -647,6 +644,9 @@ static int copy_sve_reg_indices(const struct kvm_vcpu *vcpu,
 		return -EFAULT;
 	++num_regs;
 
+	if (!kvm_arm_vcpu_sve_finalized(vcpu))
+		return num_regs;
+
 	for (i = 0; i < slices; i++) {
 		for (n = 0; n < SVE_NUM_ZREGS; n++) {
 			reg = KVM_REG_ARM64_SVE_ZREG(n, i);
Signature · 1 line
2.43.0
#84 lore raw

PATCH v15 36/37 KVM: arm64: CCA: Provide an accurate register list

In reply to Steven Price

From: Jean-Philippe Brucker <[email protected]>

Userspace can set a few registers with KVM_SET_ONE_REG (9 GP registers at runtime, and 3 system registers during initialization). Update the register list returned by KVM_GET_REG_LIST.

---
Changes since v11:
* Reworked due to upstream changes.
Changes since v8:
* Minor type changes following review.
Changes since v7:
* Reworked on upstream changes.

---
 arch/arm64/kvm/guest.c      |  6 ++++++
 arch/arm64/kvm/hypercalls.c |  4 ++--
 arch/arm64/kvm/sys_regs.c   | 27 +++++++++++++++++++++------
 3 files changed, 29 insertions(+), 8 deletions(-)
arch/arm64/kvm/guest.c +6 -0
index 128fec56993a..5e495dd39e39 100644
@@ -620,6 +620,9 @@ static unsigned long num_sve_regs(const struct kvm_vcpu *vcpu)
 	if (!kvm_arm_vcpu_sve_finalized(vcpu))
 		return 1; /* KVM_REG_ARM64_SVE_VLS */
 
+	if (kvm_is_realm(vcpu->kvm))
+		return 1; /* KVM_REG_ARM64_SVE_VLS */
+
 	return slices * (SVE_NUM_PREGS + SVE_NUM_ZREGS + 1 /* FFR */)
 		+ 1; /* KVM_REG_ARM64_SVE_VLS */
 }
@@ -647,6 +650,9 @@ static int copy_sve_reg_indices(const struct kvm_vcpu *vcpu,
 	if (!kvm_arm_vcpu_sve_finalized(vcpu))
 		return num_regs;
 
+	if (kvm_is_realm(vcpu->kvm))
+		return num_regs;
+
 	for (i = 0; i < slices; i++) {
 		for (n = 0; n < SVE_NUM_ZREGS; n++) {
 			reg = KVM_REG_ARM64_SVE_ZREG(n, i);
arch/arm64/kvm/hypercalls.c +2 -2
index b11b8821c9fb..82278ccb19ae 100644
@@ -414,14 +414,14 @@ void kvm_arm_teardown_hypercalls(struct kvm *kvm)
 
 int kvm_arm_get_fw_num_regs(struct kvm_vcpu *vcpu)
 {
-	return ARRAY_SIZE(kvm_arm_fw_reg_ids);
+	return kvm_is_realm(vcpu->kvm) ? 0 : ARRAY_SIZE(kvm_arm_fw_reg_ids);
 }
 
 int kvm_arm_copy_fw_reg_indices(struct kvm_vcpu *vcpu, u64 __user *uindices)
 {
 	int i;
 
-	for (i = 0; i < ARRAY_SIZE(kvm_arm_fw_reg_ids); i++) {
+	for (i = 0; i < kvm_arm_get_fw_num_regs(vcpu); i++) {
 		if (put_user(kvm_arm_fw_reg_ids[i], uindices++))
 			return -EFAULT;
 	}
arch/arm64/kvm/sys_regs.c +21 -6
index e47be8f8d259..6d805160d70e 100644
@@ -5540,18 +5540,18 @@ int kvm_arm_sys_reg_set_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg
 				    sys_reg_descs, ARRAY_SIZE(sys_reg_descs));
 }
 
-static unsigned int num_demux_regs(void)
+static inline unsigned int num_demux_regs(struct kvm_vcpu *vcpu)
 {
-	return CSSELR_MAX;
+	return kvm_is_realm(vcpu->kvm) ? 0 : CSSELR_MAX;
 }
 
-static int write_demux_regids(u64 __user *uindices)
+static int write_demux_regids(struct kvm_vcpu *vcpu, u64 __user *uindices)
 {
 	u64 val = KVM_REG_ARM64 | KVM_REG_SIZE_U32 | KVM_REG_ARM_DEMUX;
 	unsigned int i;
 
 	val |= KVM_REG_ARM_DEMUX_ID_CCSIDR;
-	for (i = 0; i < CSSELR_MAX; i++) {
+	for (i = 0; i < num_demux_regs(vcpu); i++) {
 		if (put_user(val | i, uindices))
 			return -EFAULT;
 		uindices++;
@@ -5595,11 +5595,26 @@ static bool copy_reg_to_user(const struct sys_reg_desc *reg, u64 __user **uind)
 	return true;
 }
 
+static inline bool kvm_realm_sys_reg_hidden_user(const struct kvm_vcpu *vcpu,
+						 u64 reg)
+{
+	switch (reg) {
+	case SYS_ID_AA64DFR0_EL1:
+	case SYS_PMCR_EL0:
+		return false;
+	}
+	return true;
+}
+
 static int walk_one_sys_reg(const struct kvm_vcpu *vcpu,
 			    const struct sys_reg_desc *rd,
 			    u64 __user **uind,
 			    unsigned int *total)
 {
+	if (vcpu_is_rec(vcpu) &&
+	    kvm_realm_sys_reg_hidden_user(vcpu, reg_to_encoding(rd)))
+		return 0;
+
 	/*
 	 * Ignore registers we trap but don't save,
 	 * and for which no custom user accessor is provided.
@@ -5637,7 +5652,7 @@ static int walk_sys_regs(struct kvm_vcpu *vcpu, u64 __user *uind)
 
 unsigned long kvm_arm_num_sys_reg_descs(struct kvm_vcpu *vcpu)
 {
-	return num_demux_regs()
+	return num_demux_regs(vcpu)
 		+ walk_sys_regs(vcpu, (u64 __user *)NULL);
 }
 
@@ -5650,7 +5665,7 @@ int kvm_arm_copy_sys_reg_indices(struct kvm_vcpu *vcpu, u64 __user *uindices)
 		return err;
 	uindices += err;
 
-	return write_demux_regids(uindices);
+	return write_demux_regids(vcpu, uindices);
 }
 
 #define KVM_ARM_FEATURE_ID_RANGE_INDEX(r)			\
Signature · 1 line
2.43.0
#85 lore raw

PATCH v15 37/37 KVM: arm64: CCA: Enable realms to be created

In reply to Steven Price

All the pieces are now in place, so enable kvm_rmi_is_available when the RMM is detected.

---
 arch/arm64/kvm/rmi.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
arch/arm64/kvm/rmi.c +2 -1
index 3f1c6351b71a..06cc85fb5092 100644
@@ -1518,5 +1518,6 @@ void kvm_init_rmi(void)
 	if (rmm_check_features())
 		return;
 
-	/* Future patch will enable static branch kvm_rmi_is_available */
+	kvm_info("Realm guests supported\n");
+	static_branch_enable(&kvm_rmi_is_available);
 }
Signature · 1 line
2.43.0
maintainer
#86 lore raw
In reply to Steven Price
Quoted 9 lines · Steven Price

This series adds support for running protected VMs using KVM under the Arm Confidential Compute Architecture (CCA).

It is the second part of the Arm CCA host support that was previously posted as a single 44-patch series. The generic firmware/RMM support has now been split into a separate 6-patch base series[0] so that it can also be used by other work (and hopefully make reviewing a little easier). This series applies on top of that base.

Splitting the series this way means that no Sashiko review can occur, as nothing applies on its own:

https://sashiko.dev/#/patchset/20260715142841.80544-1-steven.price%40arm.com

In the future, please post this with the relevant patches as an integral prefix, so that we can make use of the tooling.

Thanks,

	M.
Signature · 1 line
Without deviation from the norm, progress is not possible.
#87 lore raw
Quoted 12 lines · Marc Zyngier
Quoted 9 lines · Steven Price

This series adds support for running protected VMs using KVM under the Arm Confidential Compute Architecture (CCA).

It is the second part of the Arm CCA host support that was previously posted as a single 44-patch series. The generic firmware/RMM support has now been split into a separate 6-patch base series[0] so that it can also be used by other work (and hopefully make reviewing a little easier). This series applies on top of that base.

Quoted 7 lines

Splitting the series this way means that no Sashiko review can occur, as nothing applies on its own:

https://sashiko.dev/#/patchset/20260715142841.80544-1-steven.price%40arm.com

In the future, please post this with the relevant patches as an integral prefix, so that we can make use of the tooling.

Ah, I wonder if there's a way to teach Sashiko to deal with dependencies like this? Anyway if you're happy with everything in one series and (hopefully) merging a prefix earlier then I'll go back to that - it's easier for me too.

Thanks,
Steve

maintainer
#88 lore raw
Quoted 19 lines · Steven Price
Quoted 17 lines · Marc Zyngier
Quoted 9 lines · Steven Price

This series adds support for running protected VMs using KVM under the Arm Confidential Compute Architecture (CCA).

It is the second part of the Arm CCA host support that was previously posted as a single 44-patch series. The generic firmware/RMM support has now been split into a separate 6-patch base series[0] so that it can also be used by other work (and hopefully make reviewing a little easier). This series applies on top of that base.

Splitting the series this way means that no Sashiko review can occur, as nothing applies on its own:

https://sashiko.dev/#/patchset/20260715142841.80544-1-steven.price%40arm.com

Quoted 7 lines
Quoted 2 lines

In the future, please post this with the relevant patches as an integral prefix, so that we can make use of the tooling.

Ah, I wonder if there's a way to teach Sashiko to deal with dependencies like this? Anyway if you're happy with everything in one series and (hopefully) merging a prefix earlier then I'll go back to that - it's easier for me too.

Sashiko had plenty to say about the first series, and you've been Cc'd on the reports. I'd expect responses to the reports explaining why this isn't a problem, or how you are planning to address it.

Thanks,

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