Skip to contentSkip to conversation

KVM: SVM: Support direct setting of VMSA for SEV-SNP guests

PATCH In review Jörg Rödel 2 participants 10 messages Dec 1

Subsystems (5)
Documentation x86 KVM Kselftest +1 more subsystems
lore
Share & tools
lore
#0 lore raw

v4 cover KVM: SVM: Support direct setting of VMSA for SEV-SNP guests

From: Joerg Roedel <[email protected]>

Hi,

here is the updated version of KVM-AMD changes to allow user-space to directly set the boot VMSA (direct-vmsa) for an SEV-SNP virtual machine.

The direct-vmsa support is required for stable launch measurements when loading the initial SEV-SNP guest image from an IGVM file. Without this support KVM measures a VMSA at a fixed GPA for every VCPU, which makes the launch measurement dependent on the number of VCPUs. Besides that the current KVM VMSA-allocation behavior poses challenges for live migration of SEV-SNP VMs. The current behavior is fully preserved when direct-vmsa is not used.

For a longer justification have a look at this email from the v1 thread:

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

The user-space API has slightly changes since v3 of the series and consists of three parts:

- A new KVM_CAP_SNP_DIRECT_VMSA VM-level capability which can be queried and enabled from user-space. When user-space enables the capability, KVM will no longer allocate VMSA pages when creating VCPUs. This means that the capability can only be enabled before any VCPUs are created.

- Allow VMSA pages in SNP launch updates. This was already present in the previous versions, but has different semantics since v3 of the patches. In this version all it does is adding the VMSA pages to the initial image and the launch measurement.

- A new per-VCPU MEM_ENC operation to get and set the VMSA and GHCB addresses of a VCPU. User-space will use this operation to set the GPA of the launch VMSA of the VCPUs, but can also query and set the addresses during runtime.

New in v4 is that these operatations are only allowed after SNP_LAUNCH_FINISH and only for SEV-SNP guests.

The changes are rebased to v7.4-rc5 and tested with lockdep enabled.

Changes since v3:

- Rebase onto v7.4-rc5 and update the ABI documentation.

- Gate GHCB APIC ID list discovery on KVM_CAP_SNP_DIRECT_VMSA.

- Drop the redundant SRCU lock from the guest-owned VMSA reload path.

- Validate all direct-mode vCPUs before protecting any of them, and scope the capability's mutex guard to fix the Clang build.

- Require successful SNP launch finish before GET or SET and require a protected vCPU for SET. Use the GHCB registration GPA, preserve the GHCB MSR, and report the tracked VMSA GPA across deferred reloads.

- Fix the APIC ID selftest's variadic argument type and expand coverage of feature opt-in, launch ordering, and VMSA invalidation.

Please review.

-Joerg

Joerg Roedel (7):
KVM: SEV: Document SNP direct VMSA userspace ABI
KVM: SEV: Add direct VMSA capability
KVM: SVM: Implement GET_AP_APIC_IDS NAE event
KVM: SEV: Allow VMSA pages in SNP launch updates
KVM: SEV: Add SNP vCPU state get and set commands
KVM: selftests: Test SNP vCPU state and direct VMSA launch
KVM: selftests: Test the SNP APIC-ID-list GHCB request

 .../virt/kvm/x86/amd-memory-encryption.rst    | 113 ++++-
 arch/x86/include/asm/kvm-x86-ops.h            |   1 +
 arch/x86/include/asm/kvm_host.h               |   1 +
 arch/x86/include/asm/sev-common.h             |   1 +
 arch/x86/include/uapi/asm/kvm.h               |  21 +
 arch/x86/include/uapi/asm/svm.h               |   1 +
 arch/x86/kvm/svm/sev.c                        | 371 +++++++++++++-
 arch/x86/kvm/svm/svm.c                        |  24 +
 arch/x86/kvm/svm/svm.h                        |   2 +
 arch/x86/kvm/x86.c                            |   6 +
 include/uapi/linux/kvm.h                      |   2 +
 tools/testing/selftests/kvm/Makefile.kvm      |   2 +
 tools/testing/selftests/kvm/include/x86/sev.h | 103 +++-
 tools/testing/selftests/kvm/lib/x86/sev.c     |  79 +++
 .../selftests/kvm/x86/sev_snp_apic_id_test.c  | 340 +++++++++++++
 .../kvm/x86/sev_snp_direct_vmsa_test.c        | 476 ++++++++++++++++++
 16 files changed, 1511 insertions(+), 32 deletions(-)
 create mode 100644 tools/testing/selftests/kvm/x86/sev_snp_apic_id_test.c
 create mode 100644 tools/testing/selftests/kvm/x86/sev_snp_direct_vmsa_test.c

base-commit: fe6ff8d5d675c01793b9f051d16055dd4aa75244

Signature · 1 line
2.53.0
#1 lore raw

PATCH v4 1/7 KVM: SEV: Document SNP direct VMSA userspace ABI

From: Joerg Roedel <[email protected]>

Describe how to enable direct VMSAs and the guest APIC ID list, then measure VMSA pages before launch finish and associate them with protected vCPUs after launch finish succeeds.

Document the SNP vCPU state commands, their GPA and GHCB registration rules, and how guest_memfd lookup and guest entry validate VMSA backing.

Codex assisted with comparing the ABI documentation against the preceding patches and verified the updates with the KVM documentation build and checkpatch.

---
 .../virt/kvm/x86/amd-memory-encryption.rst    | 113 ++++++++++++++++--
 1 file changed, 102 insertions(+), 11 deletions(-)
Documentation/virt/kvm/x86/amd-memory-encryption.rst +102 -11
index eeb0812cb10a..a38f5694de44 100644
@@ -49,13 +49,14 @@ defined in the CPUID 0x8000001f[ecx] field.
 The KVM_MEMORY_ENCRYPT_OP ioctl
 ===============================
 
-The main ioctl to access SEV is KVM_MEMORY_ENCRYPT_OP, which operates on
-the VM file descriptor.  If the argument to KVM_MEMORY_ENCRYPT_OP is NULL,
-the ioctl returns 0 if SEV is enabled and ``ENOTTY`` if it is disabled
-(on some older versions of Linux, the ioctl tries to run normally even
-with a NULL argument, and therefore will likely return ``EFAULT`` instead
-of zero if SEV is enabled).  If non-NULL, the argument to
-KVM_MEMORY_ENCRYPT_OP must be a struct kvm_sev_cmd::
+The main ioctl to access SEV is KVM_MEMORY_ENCRYPT_OP.  Most SEV commands
+operate on the VM file descriptor.  The SNP vCPU state commands operate on
+a vCPU file descriptor.  If the argument to KVM_MEMORY_ENCRYPT_OP on the
+VM file descriptor is NULL, the ioctl returns 0 if SEV is enabled and
+``ENOTTY`` if it is disabled (on some older versions of Linux, the ioctl
+tries to run normally even with a NULL argument, and therefore will likely
+return ``EFAULT`` instead of zero if SEV is enabled).  If non-NULL, the
+argument to KVM_MEMORY_ENCRYPT_OP must be a struct kvm_sev_cmd::
 
        struct kvm_sev_cmd {
                __u32 id;
@@ -70,8 +71,8 @@ another struct containing arguments specific to command.  The ``sev_fd``
 should point to a file descriptor that is opened on the ``/dev/sev``
 device, if needed (see individual commands).
 
-On output, ``error`` is zero on success, or an error code.  Error codes
-are defined in ``<linux/psp-dev.h>``.
+For commands that report firmware status, ``error`` is zero on success or
+contains an error code defined in ``<linux/psp-dev.h>``.
 
 KVM implements the following commands to support common lifecycle events of SEV
 guests, such as launching, running, snapshotting, migrating and decommissioning.
@@ -542,6 +543,7 @@ Returns: 0 on success, < 0 on error, -EAGAIN if caller should retry
 where the allowed values for page_type are #define'd as::
 
         KVM_SEV_SNP_PAGE_TYPE_NORMAL
+        KVM_SEV_SNP_PAGE_TYPE_VMSA
         KVM_SEV_SNP_PAGE_TYPE_ZERO
         KVM_SEV_SNP_PAGE_TYPE_UNMEASURED
         KVM_SEV_SNP_PAGE_TYPE_SECRETS
@@ -550,12 +552,101 @@ where the allowed values for page_type are #define'd as::
 See the SEV-SNP spec [snp-fw-abi]_ for further details on how each page type is
 used/measured.
 
-20. KVM_SEV_SNP_LAUNCH_FINISH
+``KVM_SEV_SNP_PAGE_TYPE_VMSA`` creates VMSA pages as part of the measured
+initial image and requires ``KVM_CAP_SNP_DIRECT_VMSA`` to be enabled.  Each
+request must contain exactly one 4 KiB VMSA page.  KVM requires VMPL 0 and a
+``sev_features`` value that matches the VM's configured VMSA features.
+Userspace can issue multiple requests before ``KVM_SEV_SNP_LAUNCH_FINISH``.
+After launch finish succeeds, use ``KVM_SEV_SNP_SET_VCPU_STATE`` on the
+intended vCPU file descriptor to associate a measured VMSA with that vCPU.
+
+20. KVM_SEV_SNP_GET_VCPU_STATE / KVM_SEV_SNP_SET_VCPU_STATE
+------------------------------------------------------------
+
+Issue ``KVM_MEMORY_ENCRYPT_OP`` on the target vCPU file descriptor and set
+``kvm_sev_cmd.data`` to point to the state structure.  Both commands are
+specific to SNP and require successful ``KVM_SEV_SNP_LAUNCH_FINISH``.  The
+``sev_fd`` and ``error`` fields of ``kvm_sev_cmd`` are unused.  Support for
+these commands is reported by ``KVM_CHECK_EXTENSION`` with
+``KVM_CAP_SNP_VCPU_STATE``.
+
+Parameters: struct kvm_sev_snp_vcpu_state (out for GET, in for SET)
+
+Returns: 0 on success, -negative on error
+
+::
+
+        #define KVM_SEV_SNP_VCPU_STATE_VMSA_VALID        _BITULL(0)
+        #define KVM_SEV_SNP_VCPU_STATE_GHCB_VALID        _BITULL(1)
+
+        struct kvm_sev_snp_vcpu_state {
+                __u64 valid_fields;
+                __u64 vmsa_gpa;
+                __u64 ghcb_gpa;
+                __u64 pad[5];           /* Must be zero */
+        };
+
+``KVM_SEV_SNP_GET_VCPU_STATE`` returns the tracked guest-owned VMSA GPA and
+the registered GHCB GPA, setting the corresponding bit in ``valid_fields``
+for each valid address.  An absent address and the reserved fields are
+returned as zero.  GET works in both direct and legacy VMSA modes.  It reports
+the tracked VMSA GPA even while its host mapping is pending reload.  SNP AP
+creation and destruction are reflected once KVM applies the request.
+
+``KVM_SEV_SNP_SET_VCPU_STATE`` sets addresses whose validity bits are set and
+clears the VMSA association or GHCB registration whose bit is clear.  SET
+requires ``KVM_CAP_SNP_DIRECT_VMSA`` to be enabled and the target vCPU to
+have been protected by launch finish.  Create the target vCPU before launch
+finish.  Reserved fields must be zero, and ``valid_fields`` may contain only
+the defined bits.
+
+A VMSA GPA must fit in the vCPU's guest physical address space, be 4 KiB
+aligned, and not be 2 MiB aligned.  SET resolves the GPA through a
+guest_memfd-backed memslot.  The lookup can fault in a backing page and
+assign it as ordinary private memory in the Reverse Map Table (RMP).  SET
+can return ``-EAGAIN`` if the backing is invalidated during the lookup.
+KVM re-resolves the tracked GPA before guest entry if the backing is later
+invalidated.
+
+To supply an initial VMSA, prepare the private page with
+``KVM_SEV_SNP_PAGE_TYPE_VMSA`` before launch finish.  Firmware marks launch
+VMSAs in the RMP, and the guest can mark runtime VMSAs with ``RMPADJUST``.
+The processor checks that the page is marked as a VMSA at guest entry.
+A successful SET can be followed by a guest-entry failure if the page is
+still ordinary data.
+
+The GHCB GPA represents the GHCB registration.  SET installs or clears the
+registration independently of the GHCB MSR, which carries reset and protocol
+values.  For the GHCB field, SET checks only that the GPA is nonzero, is
+4 KiB aligned, and fits in the vCPU's guest physical address space.
+
+``KVM_CAP_SNP_DIRECT_VMSA`` is a VM-scoped capability that selects direct-VMSA
+mode.  Userspace enables it with ``KVM_ENABLE_CAP`` on a ``KVM_X86_SNP_VM``
+before creating any vCPUs.  ``flags`` and all elements of ``args`` must be
+zero.  Enabling it also exposes the GHCB APIC ID List feature and enables
+the corresponding ``GET_AP_APIC_IDS`` event.  The list contains the IDs
+passed to ``KVM_CREATE_VCPU``, including for vCPUs without an installed VMSA.
+
+KVM creates direct-mode vCPUs without a VMSA.  Userspace supplies the initial
+VMSA pages and controls their contents, GPAs, and measurement order
+independently of the number of vCPUs created.  Only launch updates contribute
+VMSAs to the measurement in this mode.  A measured VMSA is part of the launch
+measurement regardless of whether it is later associated with a vCPU.
+
+21. KVM_SEV_SNP_LAUNCH_FINISH
 -----------------------------
 
 After completion of the SNP guest launch flow, the KVM_SEV_SNP_LAUNCH_FINISH
 command can be issued to make the guest ready for execution.
 
+In direct-VMSA mode, launch finish validates all existing vCPUs before
+protecting them and enabling LBR virtualization.  It requires unprotected
+vCPUs, with guest debugging disabled and only the fixed-one bit permitted
+in DR7.  Before a direct-VMSA vCPU can enter the guest, it needs a VMSA
+installed by userspace with ``KVM_SEV_SNP_SET_VCPU_STATE`` after successful
+launch finish or by the guest through SNP AP creation.  In legacy VMSA mode,
+launch finish generates and measures a KVM-owned VMSA for each existing vCPU.
+
 Parameters (in): struct kvm_sev_snp_launch_finish
 
 Returns: 0 on success, -negative on error
@@ -578,7 +669,7 @@ Returns: 0 on success, -negative on error
 See SNP_LAUNCH_FINISH in the SEV-SNP specification [snp-fw-abi]_ for further
 details on the input parameters in ``struct kvm_sev_snp_launch_finish``.
 
-21. KVM_SEV_SNP_ENABLE_REQ_CERTS
+22. KVM_SEV_SNP_ENABLE_REQ_CERTS
 --------------------------------
 
 The KVM_SEV_SNP_ENABLE_REQ_CERTS command will configure KVM to exit to
Signature · 1 line
2.53.0
#2 lore raw

PATCH v4 2/7 KVM: SEV: Add direct VMSA capability

In reply to Jörg Rödel

From: Joerg Roedel <[email protected]>

Add KVM_CAP_SNP_DIRECT_VMSA as a VM-scoped capability. Require userspace to enable it on an SNP VM before creating vCPUs and reject nonzero arguments.

Direct mode skips allocation and measurement of KVM-owned VMSAs. Validate the protected and debug state of every direct-mode vCPU before protecting any of them. Scope the mutex guard to its switch case so that Clang accepts the switch.

Sashiko flagged the missing validation and cleanup guard scope. The kernel test robot confirmed the Clang build failure. Codex assisted with the fixes and build verification.

---
 arch/x86/include/asm/kvm-x86-ops.h |  1 +
 arch/x86/include/asm/kvm_host.h    |  1 +
 arch/x86/kvm/svm/sev.c             | 61 ++++++++++++++++++++++--------
 arch/x86/kvm/svm/svm.c             | 23 +++++++++++
 arch/x86/kvm/svm/svm.h             |  1 +
 arch/x86/kvm/x86.c                 |  5 +++
 include/uapi/linux/kvm.h           |  1 +
 7 files changed, 78 insertions(+), 15 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -0
index 4dde4e3e608a..c853dc65fb53 100644
@@ -23,6 +23,7 @@ KVM_X86_OP(vcpu_after_set_cpuid)
 KVM_X86_OP(vm_init)
 KVM_X86_OP_OPTIONAL(vm_destroy)
 KVM_X86_OP_OPTIONAL(vm_pre_destroy)
+KVM_X86_OP_OPTIONAL(enable_vm_cap)
 KVM_X86_OP_OPTIONAL_RET0(vcpu_precreate)
 KVM_X86_OP(vcpu_create)
 KVM_X86_OP(vcpu_free)
arch/x86/include/asm/kvm_host.h +1 -0
index 1ee4b127004d..be758e0d55aa 100644
@@ -1524,6 +1524,7 @@ struct kvm_x86_ops {
 	int (*vm_init)(struct kvm *kvm);
 	void (*vm_destroy)(struct kvm *kvm);
 	void (*vm_pre_destroy)(struct kvm *kvm);
+	int (*enable_vm_cap)(struct kvm *kvm, struct kvm_enable_cap *cap);
 
 	/* Create, but do not attach this VCPU */
 	int (*vcpu_precreate)(struct kvm *kvm);
arch/x86/kvm/svm/sev.c +46 -15

123 lines not on this page · raw message

arch/x86/kvm/svm/svm.c +23 -0
index 2dd05cd6b757..4682484a7d31 100644
@@ -5485,6 +5485,28 @@ static void *svm_alloc_apic_backing_page(struct kvm_vcpu *vcpu)
 	return page_address(page);
 }
 
+static int svm_enable_vm_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
+{
+	switch (cap->cap) {
+#ifdef CONFIG_KVM_AMD_SEV
+	case KVM_CAP_SNP_DIRECT_VMSA: {
+		if (memchr_inv(cap->args, 0, sizeof(cap->args)) ||
+		    kvm->arch.vm_type != KVM_X86_SNP_VM)
+			return -EINVAL;
+
+		guard(mutex)(&kvm->lock);
+		if (kvm->created_vcpus)
+			return -EINVAL;
+
+		to_kvm_sev_info(kvm)->snp_direct_vmsa = true;
+		return 0;
+	}
+#endif
+	default:
+		return -EINVAL;
+	}
+}
+
 struct kvm_x86_ops svm_x86_ops __initdata = {
 	.name = KBUILD_MODNAME,
 
@@ -5505,6 +5527,7 @@ struct kvm_x86_ops svm_x86_ops __initdata = {
 	.vm_init = svm_vm_init,
 	.vm_pre_destroy = avic_vm_pre_destroy,
 	.vm_destroy = svm_vm_destroy,
+	.enable_vm_cap = svm_enable_vm_cap,
 
 	.prepare_switch_to_guest = svm_prepare_switch_to_guest,
 	.vcpu_load = svm_vcpu_load,
arch/x86/kvm/svm/svm.h +1 -0
index cd3242811e43..90090c3021f6 100644
@@ -122,6 +122,7 @@ struct kvm_sev_info {
 	struct mutex guest_req_mutex; /* Must acquire before using bounce buffers */
 	cpumask_var_t have_run_cpus; /* CPUs that have done VMRUN for this VM. */
 	bool snp_certs_enabled;	/* SNP certificate-fetching support. */
+	bool snp_direct_vmsa;	/* Userspace provides and measures VMSA pages. */
 };
 #endif
 
arch/x86/kvm/x86.c +5 -0
index 0549c0b48901..017612ff959f 100644
@@ -2415,6 +2415,9 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
 	case KVM_CAP_VM_TYPES:
 		r = kvm_caps.supported_vm_types;
 		break;
+	case KVM_CAP_SNP_DIRECT_VMSA:
+		r = !!(kvm_caps.supported_vm_types & BIT(KVM_X86_SNP_VM));
+		break;
 	case KVM_CAP_READONLY_MEM:
 		r = kvm ? kvm_arch_has_readonly_mem(kvm) : 1;
 		break;
@@ -4254,6 +4257,8 @@ int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
 	}
 	default:
 		r = -EINVAL;
+		if (kvm_x86_ops.enable_vm_cap)
+			r = kvm_x86_call(enable_vm_cap)(kvm, cap);
 		break;
 	}
 	return r;
include/uapi/linux/kvm.h +1 -0
index 8dff2fc1972e..005c25263030 100644
@@ -1000,6 +1000,7 @@ struct kvm_enable_cap {
 #define KVM_CAP_PPC_COMPAT_CAPS 250
 #define KVM_CAP_ARM_PMU_V3_STRICT 251
 #define KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTES 252
+#define KVM_CAP_SNP_DIRECT_VMSA 253
 
 struct kvm_irq_routing_irqchip {
 	__u32 irqchip;
Signature · 1 line
2.53.0
#3 lore raw

PATCH v4 3/7 KVM: SVM: Implement GET_AP_APIC_IDS NAE event

In reply to Jörg Rödel

From: Joerg Roedel <[email protected]>

Implement the GHCB APIC ID List event so an SNP guest can discover its vCPUs without a broadcast INIT-SIPI sequence. Use the direct VMSA capability as the userspace opt-in, as Sean suggested, to keep guest feature discovery stable for existing SNP VMs across kernel updates.

Gate both GHCB feature queries and event dispatch on the same condition. Check the entire supplied range for address overflow and shared writable backing and write the exact descriptor under the vCPU's SRCU read lock. For undersized requests, return the required page count without writing.

Codex assisted with feature gating, buffer validation and build checks.

---
 arch/x86/include/asm/sev-common.h |   1 +
 arch/x86/include/uapi/asm/svm.h   |   1 +
 arch/x86/kvm/svm/sev.c            | 102 +++++++++++++++++++++++++++++-
 3 files changed, 101 insertions(+), 3 deletions(-)
arch/x86/include/asm/sev-common.h +1 -0
index 01a6e4dbe423..c041f85dfd5c 100644
@@ -136,6 +136,7 @@ enum psc_op {
 
 #define GHCB_HV_FT_SNP			BIT_ULL(0)
 #define GHCB_HV_FT_SNP_AP_CREATION	BIT_ULL(1)
+#define GHCB_HV_FT_APIC_ID_LIST		BIT_ULL(4)
 #define GHCB_HV_FT_SNP_MULTI_VMPL	BIT_ULL(5)
 
 /*
arch/x86/include/uapi/asm/svm.h +1 -0
index e80676185092..c9c85891971a 100644
@@ -118,6 +118,7 @@
 #define SVM_VMGEXIT_AP_CREATE_ON_INIT		0
 #define SVM_VMGEXIT_AP_CREATE			1
 #define SVM_VMGEXIT_AP_DESTROY			2
+#define SVM_VMGEXIT_GET_APIC_IDS		0x80000017ull
 #define SVM_VMGEXIT_SNP_RUN_VMPL		0x80000018ull
 #define SVM_VMGEXIT_SAVIC			0x8000001aull
 #define SVM_VMGEXIT_SAVIC_REGISTER_GPA		0
arch/x86/kvm/svm/sev.c +99 -3

138 lines not on this page · raw message

Signature · 1 line
2.53.0
#6 lore raw

PATCH v4 4/7 KVM: SEV: Allow VMSA pages in SNP launch updates

In reply to Jörg Rödel

From: Joerg Roedel <[email protected]>

Pass the firmware VMSA page type through KVM_SEV_SNP_LAUNCH_UPDATE. Accept exactly one 4 KiB page per request when KVM_CAP_SNP_DIRECT_VMSA is enabled. Keep measurement independent of association with a vCPU.

Require VMPL 0 and match sev_features against the VM's configured VMSA features before submitting the page to firmware.

---
 arch/x86/include/uapi/asm/kvm.h |  1 +
 arch/x86/kvm/svm/sev.c          | 20 ++++++++++++++++++++
 2 files changed, 21 insertions(+)
arch/x86/include/uapi/asm/kvm.h +1 -0
index 00ce265391e1..f3c389d3c70e 100644
@@ -885,6 +885,7 @@ struct kvm_sev_snp_launch_start {
 /* Kept in sync with firmware values for simplicity. */
 #define KVM_SEV_PAGE_TYPE_INVALID		0x0
 #define KVM_SEV_SNP_PAGE_TYPE_NORMAL		0x1
+#define KVM_SEV_SNP_PAGE_TYPE_VMSA		0x2
 #define KVM_SEV_SNP_PAGE_TYPE_ZERO		0x3
 #define KVM_SEV_SNP_PAGE_TYPE_UNMEASURED	0x4
 #define KVM_SEV_SNP_PAGE_TYPE_SECRETS		0x5
arch/x86/kvm/svm/sev.c +20 -0
index f22490f86a4a..4d492abb233b 100644
@@ -2374,6 +2374,7 @@ struct sev_gmem_populate_args {
 	__u8 type;
 	int sev_fd;
 	int fw_error;
+	bool vmsa_invalid;
 };
 
 static int sev_gmem_post_populate(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn,
@@ -2404,6 +2405,19 @@ static int sev_gmem_post_populate(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn,
 		kunmap_local(src_vaddr);
 	}
 
+	if (sev_populate_args->type == KVM_SEV_SNP_PAGE_TYPE_VMSA) {
+		struct sev_es_save_area *vmsa = kmap_local_pfn(pfn);
+
+		if (vmsa->vmpl || vmsa->sev_features != sev->vmsa_features) {
+			sev_populate_args->vmsa_invalid = true;
+			ret = -EINVAL;
+		}
+
+		kunmap_local(vmsa);
+		if (ret)
+			goto out;
+	}
+
 	ret = rmp_make_private(pfn, gfn << PAGE_SHIFT, PG_LEVEL_4K,
 			       sev_get_asid(kvm), true);
 	if (ret)
@@ -2467,7 +2481,10 @@ static int snp_launch_update(struct kvm *kvm, struct kvm_sev_cmd *argp)
 		 params.gfn_start, params.len, params.type, params.flags, params.uaddr);
 
 	if (!params.len || !PAGE_ALIGNED(params.len) || params.flags ||
+	    (params.type == KVM_SEV_SNP_PAGE_TYPE_VMSA &&
+	     (!sev->snp_direct_vmsa || params.len != PAGE_SIZE)) ||
 	    (params.type != KVM_SEV_SNP_PAGE_TYPE_NORMAL &&
+	     params.type != KVM_SEV_SNP_PAGE_TYPE_VMSA &&
 	     params.type != KVM_SEV_SNP_PAGE_TYPE_ZERO &&
 	     params.type != KVM_SEV_SNP_PAGE_TYPE_UNMEASURED &&
 	     params.type != KVM_SEV_SNP_PAGE_TYPE_SECRETS &&
@@ -2516,6 +2533,9 @@ static int snp_launch_update(struct kvm *kvm, struct kvm_sev_cmd *argp)
 				  params.type == KVM_SEV_SNP_PAGE_TYPE_CPUID,
 				  sev_gmem_post_populate, &sev_populate_args);
 	if (count < 0) {
+		if (sev_populate_args.vmsa_invalid)
+			return -EINVAL;
+
 		argp->error = sev_populate_args.fw_error;
 		pr_debug("%s: kvm_gmem_populate failed, ret %ld (fw_error %d)\n",
 			 __func__, count, argp->error);
Signature · 1 line
2.53.0
#7 lore raw

PATCH v4 5/7 KVM: SEV: Add SNP vCPU state get and set commands

In reply to Jörg Rödel

From: Joerg Roedel <[email protected]>

Add KVM_SEV_SNP_GET_VCPU_STATE and KVM_SEV_SNP_SET_VCPU_STATE as vCPU-scoped KVM_MEMORY_ENCRYPT_OP commands and advertise KVM_CAP_SNP_VCPU_STATE. The shared, extensible argument has validity bits for the guest-owned VMSA GPA and the registered GHCB GPA.

Require successful KVM_SEV_SNP_LAUNCH_FINISH for both commands. SET also requires KVM_CAP_SNP_DIRECT_VMSA and a target vCPU with protected state.

Setting the VMSA GPA behaves like setting it with AP_CREATE, the lookup can fault in a mew private page, but further checks are deferred to VMRUN (like a set VMSA bit in the RMP).

GET reports the currently tracked VMSA GPA even while a reload is deferred. Pending AP updates are reflected once KVM applies them. GET and SET use the registered GHCB GPA. SET preserves the GHCB MSR for protocol messages, including the value installed at reset.

---
 arch/x86/include/uapi/asm/kvm.h |  20 ++++
 arch/x86/kvm/svm/sev.c          | 188 +++++++++++++++++++++++++++++++-
 arch/x86/kvm/svm/svm.c          |   1 +
 arch/x86/kvm/svm/svm.h          |   1 +
 arch/x86/kvm/x86.c              |   1 +
 include/uapi/linux/kvm.h        |   1 +
 6 files changed, 210 insertions(+), 2 deletions(-)
arch/x86/include/uapi/asm/kvm.h +20 -0
index f3c389d3c70e..546773e6d4de 100644
@@ -746,6 +746,8 @@ enum sev_cmd_id {
 	KVM_SEV_SNP_LAUNCH_UPDATE,
 	KVM_SEV_SNP_LAUNCH_FINISH,
 	KVM_SEV_SNP_ENABLE_REQ_CERTS,
+	KVM_SEV_SNP_GET_VCPU_STATE,
+	KVM_SEV_SNP_SET_VCPU_STATE,
 
 	KVM_SEV_NR_MAX,
 };
@@ -902,6 +904,24 @@ struct kvm_sev_snp_launch_update {
 	__u64 pad2[4];
 };
 
+#define KVM_SEV_SNP_VCPU_STATE_VMSA_VALID	_BITULL(0)
+#define KVM_SEV_SNP_VCPU_STATE_GHCB_VALID	_BITULL(1)
+
+/*
+ * Both commands require successful KVM_SEV_SNP_LAUNCH_FINISH. SET also
+ * requires KVM_CAP_SNP_DIRECT_VMSA and a vCPU protected by launch finish.
+ *
+ * GET reports the tracked VMSA GPA and the registered GHCB GPA. A VMSA
+ * GPA retained for a deferred reload is still reported as valid.
+ * SET clears an association when its validity bit is clear.
+ */
+struct kvm_sev_snp_vcpu_state {
+	__u64 valid_fields;
+	__u64 vmsa_gpa;
+	__u64 ghcb_gpa;
+	__u64 pad[5];
+};
+
 #define KVM_SEV_SNP_ID_BLOCK_SIZE	96
 #define KVM_SEV_SNP_ID_AUTH_SIZE	4096
 #define KVM_SEV_SNP_FINISH_DATA_SIZE	32
arch/x86/kvm/svm/sev.c +186 -2

224 lines not on this page · raw message

arch/x86/kvm/svm/svm.c +1 -0
index 4682484a7d31..6ccfca6c44ec 100644
@@ -5629,6 +5629,7 @@ struct kvm_x86_ops svm_x86_ops __initdata = {
 	.vcpu_needs_initialization = sev_vcpu_needs_initialization,
 	.dev_get_attr = sev_dev_get_attr,
 	.mem_enc_ioctl = sev_mem_enc_ioctl,
+	.vcpu_mem_enc_ioctl = sev_vcpu_mem_enc_ioctl,
 	.mem_enc_register_region = sev_mem_enc_register_region,
 	.mem_enc_unregister_region = sev_mem_enc_unregister_region,
 	.guest_memory_reclaimed = sev_guest_memory_reclaimed,
arch/x86/kvm/svm/svm.h +1 -0
index 90090c3021f6..ba03eb34b868 100644
@@ -996,6 +996,7 @@ void sev_es_unmap_ghcb(struct vcpu_svm *svm);
 #ifdef CONFIG_KVM_AMD_SEV
 bool sev_vcpu_needs_initialization(struct kvm_vcpu *vcpu);
 int sev_mem_enc_ioctl(struct kvm *kvm, void __user *argp);
+int sev_vcpu_mem_enc_ioctl(struct kvm_vcpu *vcpu, void __user *argp);
 int sev_mem_enc_register_region(struct kvm *kvm,
 				struct kvm_enc_region *range);
 int sev_mem_enc_unregister_region(struct kvm *kvm,
arch/x86/kvm/x86.c +1 -0
index 017612ff959f..57a1f3b74267 100644
@@ -2415,6 +2415,7 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
 	case KVM_CAP_VM_TYPES:
 		r = kvm_caps.supported_vm_types;
 		break;
+	case KVM_CAP_SNP_VCPU_STATE:
 	case KVM_CAP_SNP_DIRECT_VMSA:
 		r = !!(kvm_caps.supported_vm_types & BIT(KVM_X86_SNP_VM));
 		break;
include/uapi/linux/kvm.h +1 -0
index 005c25263030..00259ec260ce 100644
@@ -1001,6 +1001,7 @@ struct kvm_enable_cap {
 #define KVM_CAP_ARM_PMU_V3_STRICT 251
 #define KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTES 252
 #define KVM_CAP_SNP_DIRECT_VMSA 253
+#define KVM_CAP_SNP_VCPU_STATE 254
 
 struct kvm_irq_routing_irqchip {
 	__u32 irqchip;
Signature · 1 line
2.53.0
#8 lore raw

PATCH v4 6/7 KVM: selftests: Test SNP vCPU state and direct VMSA launch

In reply to Jörg Rödel

From: Joerg Roedel <[email protected]>

Test direct and legacy SNP launch. Validate VMSA launch updates and measure the initial VMSAs before launch finish. Check that GET and SET reject requests before successful finish, that a debug-enabled AP prevents partial protection, and that the BSP boots from the second VMSA after reassociation.

Round-trip and clear GHCB registration without changing the reset GHCB MSR. Reject invalid state requests and verify that SET accepts ordinary data backing while VMRUN rejects it. Exercise guest_memfd hole punching, memslot replacement and removal, and VMSA reload. Check that SVM reports a missing or invalid VMSA through KVM_EXIT_FAIL_ENTRY.

Codex assisted with test development, comparison with the documented ABI, compilation, and checkpatch. Runtime testing requires an SNP host with /dev/kvm.

---
 tools/testing/selftests/kvm/Makefile.kvm      |   1 +
 tools/testing/selftests/kvm/include/x86/sev.h | 101 ++++
 tools/testing/selftests/kvm/lib/x86/sev.c     |  79 +++
 .../kvm/x86/sev_snp_direct_vmsa_test.c        | 476 ++++++++++++++++++
 4 files changed, 657 insertions(+)
 create mode 100644 tools/testing/selftests/kvm/x86/sev_snp_direct_vmsa_test.c
tools/testing/selftests/kvm/Makefile.kvm +1 -0
index 283c59d7649c..2086b6e1ee25 100644
@@ -154,6 +154,7 @@ TEST_GEN_PROGS_x86 += x86/xen_vmcall_test
 TEST_GEN_PROGS_x86 += x86/sev_dbg_test
 TEST_GEN_PROGS_x86 += x86/sev_init2_tests
 TEST_GEN_PROGS_x86 += x86/sev_migrate_tests
+TEST_GEN_PROGS_x86 += x86/sev_snp_direct_vmsa_test
 TEST_GEN_PROGS_x86 += x86/sev_smoke_test
 TEST_GEN_PROGS_x86 += x86/amx_test
 TEST_GEN_PROGS_x86 += x86/max_vcpuid_cap_test
tools/testing/selftests/kvm/include/x86/sev.h +101 -0

119 lines not on this page · raw message

tools/testing/selftests/kvm/lib/x86/sev.c +79 -0

85 lines not on this page · raw message

tools/testing/selftests/kvm/x86/sev_snp_direct_vmsa_test.c new file +476 -0

476 lines not on this page · raw message

Signature · 1 line
2.53.0
#9 lore raw

PATCH v4 7/7 KVM: selftests: Test the SNP APIC-ID-list GHCB request

In reply to Jörg Rödel

From: Joerg Roedel <[email protected]>

Check feature discovery through both GHCB interfaces and verify that legacy SNP guests cannot invoke the event. Measure the BSP VMSA and associate it after launch finish succeeds, as required by the SNP vCPU state ABI.

Create vCPUs with sparse APIC IDs and check every descriptor entry and the bytes beyond the descriptor. Verify that zero-page queries and one-page requests at the 1024-vCPU boundary report the required size without writing. Cover missing RAX, invalid buffers, and a request whose first page is writable but whose second page is unmapped.

Use GHCB protocol version 2 and a VMGEXIT memory clobber so the compiler preserves access to the shared request and response. Use the standard test-data allocator to keep GFN 0 out of the private launch ranges, and pass the vCPU count as u64 to match vcpu_args_set().

Sashiko flagged the variadic type mismatch. Codex assisted with the ABI review, test coverage and build verification. The test built with GCC and Clang. Runtime testing requires an SNP host with /dev/kvm.

---
 tools/testing/selftests/kvm/Makefile.kvm      |   1 +
 tools/testing/selftests/kvm/include/x86/sev.h |   2 +-
 .../selftests/kvm/x86/sev_snp_apic_id_test.c  | 340 ++++++++++++++++++
 3 files changed, 342 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/kvm/x86/sev_snp_apic_id_test.c
tools/testing/selftests/kvm/Makefile.kvm +1 -0
index 2086b6e1ee25..3b8867f67b04 100644
@@ -154,6 +154,7 @@ TEST_GEN_PROGS_x86 += x86/xen_vmcall_test
 TEST_GEN_PROGS_x86 += x86/sev_dbg_test
 TEST_GEN_PROGS_x86 += x86/sev_init2_tests
 TEST_GEN_PROGS_x86 += x86/sev_migrate_tests
+TEST_GEN_PROGS_x86 += x86/sev_snp_apic_id_test
 TEST_GEN_PROGS_x86 += x86/sev_snp_direct_vmsa_test
 TEST_GEN_PROGS_x86 += x86/sev_smoke_test
 TEST_GEN_PROGS_x86 += x86/amx_test
tools/testing/selftests/kvm/include/x86/sev.h +1 -1
index 1def4f9b246b..0c67625d7ce1 100644
@@ -183,7 +183,7 @@ void snp_vm_init(struct kvm_vm *vm);
 
 static inline void vmgexit(void)
 {
-	__asm__ __volatile__("rep; vmmcall");
+	__asm__ __volatile__("rep; vmmcall" ::: "memory");
 }
 
 static inline void sev_register_encrypted_memory(struct kvm_vm *vm,
tools/testing/selftests/kvm/x86/sev_snp_apic_id_test.c new file +340 -0

340 lines not on this page · raw message

Signature · 1 line
2.53.0
#4 lore raw

Re: [PATCH v4 3/7] KVM: SVM: Implement GET_AP_APIC_IDS NAE event

In reply to Jörg Rödel
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] KVM: SVM: incomplete GET_APIC_IDS VMGEXIT on -EINTR in sev_snp_get_apic_ids() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] KVM: SVM: incomplete GET_APIC_IDS VMGEXIT on -EINTR in sev_snp_get_apic_ids()
--

commit bf4fda927f82a937a9bfab8fabf43d37858e2284
Author: Joerg Roedel <[email protected]>

KVM: SVM: Implement GET_AP_APIC_IDS NAE event

This commit implements the GHCB APIC ID List VMGEXIT event for SEV-SNP guests when direct VMSA support is enabled.

Quoted 4 lines
arch/x86/kvm/svm/sev.c +0 -0
index 18ccab1139895..f22490f86a4ab 100644

[ ... ]

Quoted 4 lines
arch/x86/kvm/svm/sev.c +0 -0
@@ -4261,6 +4262,93 @@ static int sev_snp_ap_creation(struct vcpu_svm *svm)
 	return 0;
 }
 

[ ... ]

Quoted 29 lines
arch/x86/kvm/svm/sev.c +29 -0
+static int sev_snp_get_apic_ids(struct vcpu_svm *svm)
+{
+	struct kvm_vcpu *vcpu = &svm->vcpu;
+	struct kvm *kvm = vcpu->kvm;
+	struct sev_apic_id_desc *desc;
+	unsigned int nr_vcpus, size;
+	unsigned int i;
+	gpa_t gpa, end_gpa;
+	gfn_t gfn;
+	u64 pages, len;
+
+	nr_vcpus = atomic_read(&kvm->online_vcpus);
+	size = sizeof(*desc) + (nr_vcpus * sizeof(desc->apic_ids[0]));
+
+	pages = vcpu->arch.regs[VCPU_REGS_RAX];
+	if (pages < PFN_UP(size)) {
+		vcpu->arch.regs[VCPU_REGS_RAX] = PFN_UP(size);
+		return 1;
+	}
+
+	gpa = svm->vmcb->control.exit_info_1;
+	if (!PAGE_ALIGNED(gpa) ||
+	    check_mul_overflow(pages, (u64)PAGE_SIZE, &len) ||
+	    check_add_overflow(gpa, len - 1, &end_gpa) ||
+	    !page_address_valid(vcpu, gpa) ||
+	    !page_address_valid(vcpu, end_gpa & PAGE_MASK))
+		goto invalid_buffer;
+
+	for (gfn = gpa_to_gfn(gpa); gfn <= gpa_to_gfn(end_gpa); gfn++) {

arch/x86/kvm/svm/sev.c static int sev_snp_ap_creation(struct vcpu_svm *svm) · line 4324

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+		struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
+
+		if (kvm_is_error_hva(gfn_to_hva_memslot(slot, gfn)) ||
+		    kvm_is_private_gfn(kvm, gfn))
+			goto invalid_buffer;
+
+		if (signal_pending(current))
+			return -EINTR;
+		cond_resched();
+	}

[Severity: High]
Does returning -EINTR here leave the SVM_VMGEXIT_GET_APIC_IDS event uncompleted while telling the guest it succeeded?

Before dispatching to sev_snp_get_apic_ids(), sev_handle_vmgexit() clears ghcb->save.valid_bitmap in sev_es_sync_from_ghcb() and presets the GHCB return code to success via svm_vmgexit_success(svm, 0). Hardware has already advanced the guest RIP past VMGEXIT, and no vcpu->arch.complete_userspace_io callback is installed when returning -EINTR. On the next KVM_RUN, svm_prepare_switch_to_guest() syncs the preset success status back to the GHCB and resumes the guest past VMGEXIT without ever writing the APIC ID descriptor to guest memory.

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

Re: [PATCH v4 3/7] KVM: SVM: Implement GET_AP_APIC_IDS NAE event

Quoted 8 lines · On Tue, Dec 01, 2026 at 10:00:56AM +0000, [email protected] wrote:

arch/x86/kvm/svm/sev.c static int sev_snp_ap_creation(struct vcpu_svm *svm) · line 4323

Quoted 3 lines
arch/x86/kvm/svm/sev.c +3 -0
+		if (signal_pending(current))
+			return -EINTR;
+		cond_resched();

[Severity: High]
Does returning -EINTR here leave the SVM_VMGEXIT_GET_APIC_IDS event uncompleted while telling the guest it succeeded?

Quoted 8 lines

Before dispatching to sev_snp_get_apic_ids(), sev_handle_vmgexit() clears ghcb->save.valid_bitmap in sev_es_sync_from_ghcb() and presets the GHCB return code to success via svm_vmgexit_success(svm, 0). Hardware has already advanced the guest RIP past VMGEXIT, and no vcpu->arch.complete_userspace_io callback is installed when returning -EINTR. On the next KVM_RUN, svm_prepare_switch_to_guest() syncs the preset success status back to the GHCB and resumes the guest past VMGEXIT without ever writing the APIC ID descriptor to guest memory.

Agreed, this hunk is over-cautious and can be trimmed down to the cond_resched().

-Joerg