Kernel KVM virtualization development
 help / color / mirror / Atom feed
* [PATCH v4 0/7] KVM: SVM: Support direct setting of VMSA for SEV-SNP guests
@ 2026-12-01  9:45 Jörg Rödel
  2026-12-01  9:45 ` [PATCH v4 1/7] KVM: SEV: Document SNP direct VMSA userspace ABI Jörg Rödel
                   ` (6 more replies)
  0 siblings, 7 replies; 10+ messages in thread
From: Jörg Rödel @ 2026-12-01  9:45 UTC (permalink / raw)
  To: Paolo Bonzini, Sean Christopherson
  Cc: Michael Roth, Liam Merwick, Vishal Annapurve, Ninad Naik,
	Joerg Roedel, Tom Lendacky, James Bottomley, kvm, linux-doc,
	linux-kernel, linux-kselftest, coconut-svsm, joro

From: Joerg Roedel <joerg.roedel@amd.com>

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/aiqwjn2DVOumfr3T@8bytes.org/

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
-- 
2.53.0


^ permalink raw reply	[flat|nested] 10+ messages in thread

* [PATCH v4 1/7] KVM: SEV: Document SNP direct VMSA userspace ABI
  2026-12-01  9:45 [PATCH v4 0/7] KVM: SVM: Support direct setting of VMSA for SEV-SNP guests Jörg Rödel
@ 2026-12-01  9:45 ` Jörg Rödel
  2026-12-01  9:45 ` [PATCH v4 2/7] KVM: SEV: Add direct VMSA capability Jörg Rödel
                   ` (5 subsequent siblings)
  6 siblings, 0 replies; 10+ messages in thread
From: Jörg Rödel @ 2026-12-01  9:45 UTC (permalink / raw)
  To: Paolo Bonzini, Sean Christopherson
  Cc: Michael Roth, Liam Merwick, Vishal Annapurve, Ninad Naik,
	Joerg Roedel, Tom Lendacky, James Bottomley, kvm, linux-doc,
	linux-kernel, linux-kselftest, coconut-svsm, joro

From: Joerg Roedel <joerg.roedel@amd.com>

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.

Signed-off-by: Joerg Roedel <joerg.roedel@amd.com>
---
 .../virt/kvm/x86/amd-memory-encryption.rst    | 113 ++++++++++++++++--
 1 file changed, 102 insertions(+), 11 deletions(-)

diff --git a/Documentation/virt/kvm/x86/amd-memory-encryption.rst b/Documentation/virt/kvm/x86/amd-memory-encryption.rst
index eeb0812cb10a..a38f5694de44 100644
--- a/Documentation/virt/kvm/x86/amd-memory-encryption.rst
+++ b/Documentation/virt/kvm/x86/amd-memory-encryption.rst
@@ -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
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH v4 2/7] KVM: SEV: Add direct VMSA capability
  2026-12-01  9:45 [PATCH v4 0/7] KVM: SVM: Support direct setting of VMSA for SEV-SNP guests Jörg Rödel
  2026-12-01  9:45 ` [PATCH v4 1/7] KVM: SEV: Document SNP direct VMSA userspace ABI Jörg Rödel
@ 2026-12-01  9:45 ` Jörg Rödel
  2026-12-01  9:45 ` [PATCH v4 3/7] KVM: SVM: Implement GET_AP_APIC_IDS NAE event Jörg Rödel
                   ` (4 subsequent siblings)
  6 siblings, 0 replies; 10+ messages in thread
From: Jörg Rödel @ 2026-12-01  9:45 UTC (permalink / raw)
  To: Paolo Bonzini, Sean Christopherson
  Cc: Michael Roth, Liam Merwick, Vishal Annapurve, Ninad Naik,
	Joerg Roedel, Tom Lendacky, James Bottomley, kvm, linux-doc,
	linux-kernel, linux-kselftest, coconut-svsm, joro

From: Joerg Roedel <joerg.roedel@amd.com>

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.

Signed-off-by: Joerg Roedel <joerg.roedel@amd.com>
---
 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(-)

diff --git a/arch/x86/include/asm/kvm-x86-ops.h b/arch/x86/include/asm/kvm-x86-ops.h
index 4dde4e3e608a..c853dc65fb53 100644
--- a/arch/x86/include/asm/kvm-x86-ops.h
+++ b/arch/x86/include/asm/kvm-x86-ops.h
@@ -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)
diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h
index 1ee4b127004d..be758e0d55aa 100644
--- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h
@@ -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);
diff --git a/arch/x86/kvm/svm/sev.c b/arch/x86/kvm/svm/sev.c
index b90c5f14c1ac..18ccab113989 100644
--- a/arch/x86/kvm/svm/sev.c
+++ b/arch/x86/kvm/svm/sev.c
@@ -979,15 +979,9 @@ static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
 	return ret;
 }
 
-static int sev_es_sync_vmsa(struct vcpu_svm *svm)
+static int sev_es_validate_vmsa(struct vcpu_svm *svm)
 {
 	struct kvm_vcpu *vcpu = &svm->vcpu;
-	struct kvm_sev_info *sev = to_kvm_sev_info(vcpu->kvm);
-	struct sev_es_save_area *save = svm->sev_es.vmsa;
-	struct xregs_state *xsave;
-	const u8 *s;
-	u8 *d;
-	int i;
 
 	lockdep_assert_held(&vcpu->mutex);
 
@@ -998,6 +992,23 @@ static int sev_es_sync_vmsa(struct vcpu_svm *svm)
 	if (svm->vcpu.guest_debug || (svm->vmcb->save.dr7 & ~DR7_FIXED_1))
 		return -EINVAL;
 
+	return 0;
+}
+
+static int sev_es_sync_vmsa(struct vcpu_svm *svm)
+{
+	struct kvm_vcpu *vcpu = &svm->vcpu;
+	struct kvm_sev_info *sev = to_kvm_sev_info(vcpu->kvm);
+	struct sev_es_save_area *save = svm->sev_es.vmsa;
+	struct xregs_state *xsave;
+	const u8 *s;
+	u8 *d;
+	int i, ret;
+
+	ret = sev_es_validate_vmsa(svm);
+	if (ret)
+		return ret;
+
 	/*
 	 * SEV-ES will use a VMSA that is pointed to by the VMCB, not
 	 * the traditional VMSA that is part of the VMCB. Copy the
@@ -2534,13 +2545,28 @@ static int snp_launch_update_vmsa(struct kvm *kvm, struct kvm_sev_cmd *argp)
 	if (ret)
 		return ret;
 
+	if (sev->snp_direct_vmsa) {
+		kvm_for_each_vcpu(i, vcpu, kvm) {
+			ret = sev_es_validate_vmsa(to_svm(vcpu));
+			if (ret)
+				goto out;
+		}
+	}
+
 	data.gctx_paddr = __psp_pa(sev->snp_context);
 	data.page_type = SNP_PAGE_TYPE_VMSA;
 
 	kvm_for_each_vcpu(i, vcpu, kvm) {
 		struct vcpu_svm *svm = to_svm(vcpu);
-		u64 pfn = __pa(svm->sev_es.vmsa) >> PAGE_SHIFT;
+		u64 pfn;
+
+		if (sev->snp_direct_vmsa) {
+			if (!svm->sev_es.snp_has_guest_vmsa)
+				svm->vmcb->control.vmsa_pa = INVALID_PAGE;
+			goto protect_vcpu;
+		}
 
+		pfn = __pa(svm->sev_es.vmsa) >> PAGE_SHIFT;
 		ret = sev_es_sync_vmsa(svm);
 		if (ret)
 			goto out;
@@ -2560,6 +2586,7 @@ static int snp_launch_update_vmsa(struct kvm *kvm, struct kvm_sev_cmd *argp)
 			goto out;
 		}
 
+protect_vcpu:
 		svm->vcpu.arch.guest_state_protected = true;
 		/*
 		 * SEV-ES (and thus SNP) guest mandates LBR Virtualization to
@@ -3580,6 +3607,9 @@ void sev_free_vcpu(struct kvm_vcpu *vcpu)
 	 * a guest-owned page. Transition the page to hypervisor state before
 	 * releasing it back to the system.
 	 */
+	if (!svm->sev_es.vmsa)
+		goto skip_vmsa_free;
+
 	if (is_sev_snp_guest(vcpu)) {
 		u64 pfn = __pa(svm->sev_es.vmsa) >> PAGE_SHIFT;
 
@@ -4074,13 +4104,9 @@ static void __sev_snp_reload_vmsa(struct kvm_vcpu *vcpu, gpa_t gpa)
 	vmcb_mark_all_dirty(svm->vmcb);
 
 	/*
-	 * From this point forward, the VMSA will always be a guest-mapped page
-	 * rather than the initial one allocated by KVM in svm->sev_es.vmsa. In
-	 * theory, svm->sev_es.vmsa could be free'd and cleaned up here, but
-	 * that involves cleanups like flushing caches, which would ideally be
-	 * handled during teardown rather than guest boot.  Deferring that also
-	 * allows the existing logic for SEV-ES VMSAs to be re-used with
-	 * minimal SNP-specific changes.
+	 * From this point forward, the VMSA will always be a guest-mapped page.
+	 * If KVM allocated an initial VMSA, keep it until teardown to defer
+	 * cache flushing and other cleanup out of the guest boot path.
 	 */
 	svm->sev_es.snp_has_guest_vmsa = true;
 
@@ -4907,12 +4933,15 @@ void sev_init_vmcb(struct vcpu_svm *svm, bool init_event)
 int sev_vcpu_create(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_svm *svm = to_svm(vcpu);
+	struct kvm_sev_info *sev = to_kvm_sev_info(vcpu->kvm);
 	struct page *vmsa_page;
 
 	mutex_init(&svm->sev_es.snp_vmsa_mutex);
 
 	if (!is_sev_es_guest(vcpu))
 		return 0;
+	if (is_sev_snp_guest(vcpu) && sev->snp_direct_vmsa)
+		goto init_vmsa_state;
 
 	/*
 	 * SEV-ES guests require a separate (from the VMCB) VMSA page used to
@@ -4923,6 +4952,8 @@ int sev_vcpu_create(struct kvm_vcpu *vcpu)
 		return -ENOMEM;
 
 	svm->sev_es.vmsa = page_address(vmsa_page);
+
+init_vmsa_state:
 	svm->sev_es.snp_pending_vmsa_gpa = INVALID_PAGE;
 	svm->sev_es.snp_guest_vmsa_gpa = INVALID_PAGE;
 
diff --git a/arch/x86/kvm/svm/svm.c b/arch/x86/kvm/svm/svm.c
index 2dd05cd6b757..4682484a7d31 100644
--- a/arch/x86/kvm/svm/svm.c
+++ b/arch/x86/kvm/svm/svm.c
@@ -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,
diff --git a/arch/x86/kvm/svm/svm.h b/arch/x86/kvm/svm/svm.h
index cd3242811e43..90090c3021f6 100644
--- a/arch/x86/kvm/svm/svm.h
+++ b/arch/x86/kvm/svm/svm.h
@@ -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
 
diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index 0549c0b48901..017612ff959f 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -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;
diff --git a/include/uapi/linux/kvm.h b/include/uapi/linux/kvm.h
index 8dff2fc1972e..005c25263030 100644
--- a/include/uapi/linux/kvm.h
+++ b/include/uapi/linux/kvm.h
@@ -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;
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH v4 3/7] KVM: SVM: Implement GET_AP_APIC_IDS NAE event
  2026-12-01  9:45 [PATCH v4 0/7] KVM: SVM: Support direct setting of VMSA for SEV-SNP guests Jörg Rödel
  2026-12-01  9:45 ` [PATCH v4 1/7] KVM: SEV: Document SNP direct VMSA userspace ABI Jörg Rödel
  2026-12-01  9:45 ` [PATCH v4 2/7] KVM: SEV: Add direct VMSA capability Jörg Rödel
@ 2026-12-01  9:45 ` Jörg Rödel
  2026-12-01 10:00   ` sashiko-bot
  2026-12-01  9:45 ` [PATCH v4 4/7] KVM: SEV: Allow VMSA pages in SNP launch updates Jörg Rödel
                   ` (3 subsequent siblings)
  6 siblings, 1 reply; 10+ messages in thread
From: Jörg Rödel @ 2026-12-01  9:45 UTC (permalink / raw)
  To: Paolo Bonzini, Sean Christopherson
  Cc: Michael Roth, Liam Merwick, Vishal Annapurve, Ninad Naik,
	Joerg Roedel, Tom Lendacky, James Bottomley, kvm, linux-doc,
	linux-kernel, linux-kselftest, coconut-svsm, joro

From: Joerg Roedel <joerg.roedel@amd.com>

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.

Signed-off-by: Joerg Roedel <joerg.roedel@amd.com>
---
 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(-)

diff --git a/arch/x86/include/asm/sev-common.h b/arch/x86/include/asm/sev-common.h
index 01a6e4dbe423..c041f85dfd5c 100644
--- a/arch/x86/include/asm/sev-common.h
+++ b/arch/x86/include/asm/sev-common.h
@@ -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)
 
 /*
diff --git a/arch/x86/include/uapi/asm/svm.h b/arch/x86/include/uapi/asm/svm.h
index e80676185092..c9c85891971a 100644
--- a/arch/x86/include/uapi/asm/svm.h
+++ b/arch/x86/include/uapi/asm/svm.h
@@ -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
diff --git a/arch/x86/kvm/svm/sev.c b/arch/x86/kvm/svm/sev.c
index 18ccab113989..f22490f86a4a 100644
--- a/arch/x86/kvm/svm/sev.c
+++ b/arch/x86/kvm/svm/sev.c
@@ -3544,7 +3544,8 @@ static bool sev_es_are_required_ghcb_fields_valid(struct vcpu_svm *svm)
 	case SVM_VMGEXIT_AP_CREATION:
 		return kvm_ghcb_rax_is_valid(svm) ||
 		       lower_32_bits(control->exit_info_1) == SVM_VMGEXIT_AP_DESTROY;
-		break;
+	case SVM_VMGEXIT_GET_APIC_IDS:
+		return kvm_ghcb_rax_is_valid(svm);
 	case SVM_VMGEXIT_MMIO_READ:
 	case SVM_VMGEXIT_MMIO_WRITE:
 	case SVM_VMGEXIT_PSC:
@@ -4261,6 +4262,93 @@ static int sev_snp_ap_creation(struct vcpu_svm *svm)
 	return 0;
 }
 
+struct sev_apic_id_desc {
+	u32 num_entries;
+	u32 apic_ids[];
+};
+
+static bool sev_snp_apic_id_list_enabled(struct kvm_vcpu *vcpu)
+{
+	return is_sev_snp_guest(vcpu) &&
+	       to_kvm_sev_info(vcpu->kvm)->snp_direct_vmsa;
+}
+
+static u64 sev_ghcb_hv_features(struct kvm_vcpu *vcpu)
+{
+	u64 features = GHCB_HV_FT_SUPPORTED;
+
+	if (sev_snp_apic_id_list_enabled(vcpu))
+		features |= GHCB_HV_FT_APIC_ID_LIST;
+
+	return features;
+}
+
+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++) {
+		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();
+	}
+
+	desc = kvzalloc(size, GFP_KERNEL_ACCOUNT);
+	if (!desc)
+		return -ENOMEM;
+
+	desc->num_entries = nr_vcpus;
+	for (i = 0; i < nr_vcpus; i++) {
+		struct kvm_vcpu *listed_vcpu = kvm_get_vcpu(kvm, i);
+
+		if (WARN_ON_ONCE(!listed_vcpu))
+			goto invalid_buffer_free;
+		desc->apic_ids[i] = listed_vcpu->vcpu_id;
+	}
+
+	if (kvm_write_guest(kvm, gpa, desc, size))
+		goto invalid_buffer_free;
+
+	kvfree(desc);
+	return 1;
+
+invalid_buffer_free:
+	kvfree(desc);
+invalid_buffer:
+	svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_INPUT);
+	return 1;
+}
+
 static int snp_handle_guest_req(struct vcpu_svm *svm, gpa_t req_gpa, gpa_t resp_gpa)
 {
 	struct sev_data_snp_guest_request data = {0};
@@ -4491,7 +4579,7 @@ static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
 				  GHCB_MSR_INFO_POS);
 		break;
 	case GHCB_MSR_HV_FT_REQ:
-		set_ghcb_msr_bits(svm, GHCB_HV_FT_SUPPORTED,
+		set_ghcb_msr_bits(svm, sev_ghcb_hv_features(&svm->vcpu),
 				  GHCB_MSR_HV_FT_MASK, GHCB_MSR_HV_FT_POS);
 		set_ghcb_msr_bits(svm, GHCB_MSR_HV_FT_RESP,
 				  GHCB_MSR_INFO_MASK, GHCB_MSR_INFO_POS);
@@ -4631,6 +4719,12 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
 		return 1;
 	}
 
+	if (control->exit_code == SVM_VMGEXIT_GET_APIC_IDS &&
+	    !sev_snp_apic_id_list_enabled(vcpu)) {
+		svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_EVENT);
+		return 1;
+	}
+
 	if (!sev_es_are_required_ghcb_fields_valid(svm)) {
 		/*
 		 * Print the exit code even though it may not be marked valid
@@ -4713,7 +4807,7 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
 		return 1;
 	}
 	case SVM_VMGEXIT_HV_FEATURES:
-		svm_vmgexit_success(svm, GHCB_HV_FT_SUPPORTED);
+		svm_vmgexit_success(svm, sev_ghcb_hv_features(vcpu));
 		return 1;
 	case SVM_VMGEXIT_TERM_REQUEST:
 		pr_info("SEV-ES guest requested termination: reason %#llx info %#llx\n",
@@ -4736,6 +4830,8 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
 		if (sev_snp_ap_creation(svm))
 			svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_INPUT);
 		return 1;
+	case SVM_VMGEXIT_GET_APIC_IDS:
+		return sev_snp_get_apic_ids(svm);
 	case SVM_VMGEXIT_GUEST_REQUEST:
 	case SVM_VMGEXIT_EXT_GUEST_REQUEST:
 		if (!PAGE_ALIGNED(control->exit_info_1) ||
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH v4 4/7] KVM: SEV: Allow VMSA pages in SNP launch updates
  2026-12-01  9:45 [PATCH v4 0/7] KVM: SVM: Support direct setting of VMSA for SEV-SNP guests Jörg Rödel
                   ` (2 preceding siblings ...)
  2026-12-01  9:45 ` [PATCH v4 3/7] KVM: SVM: Implement GET_AP_APIC_IDS NAE event Jörg Rödel
@ 2026-12-01  9:45 ` Jörg Rödel
  2026-12-01  9:45 ` [PATCH v4 5/7] KVM: SEV: Add SNP vCPU state get and set commands Jörg Rödel
                   ` (2 subsequent siblings)
  6 siblings, 0 replies; 10+ messages in thread
From: Jörg Rödel @ 2026-12-01  9:45 UTC (permalink / raw)
  To: Paolo Bonzini, Sean Christopherson
  Cc: Michael Roth, Liam Merwick, Vishal Annapurve, Ninad Naik,
	Joerg Roedel, Tom Lendacky, James Bottomley, kvm, linux-doc,
	linux-kernel, linux-kselftest, coconut-svsm, joro

From: Joerg Roedel <joerg.roedel@amd.com>

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.

Signed-off-by: Joerg Roedel <joerg.roedel@amd.com>
---
 arch/x86/include/uapi/asm/kvm.h |  1 +
 arch/x86/kvm/svm/sev.c          | 20 ++++++++++++++++++++
 2 files changed, 21 insertions(+)

diff --git a/arch/x86/include/uapi/asm/kvm.h b/arch/x86/include/uapi/asm/kvm.h
index 00ce265391e1..f3c389d3c70e 100644
--- a/arch/x86/include/uapi/asm/kvm.h
+++ b/arch/x86/include/uapi/asm/kvm.h
@@ -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
diff --git a/arch/x86/kvm/svm/sev.c b/arch/x86/kvm/svm/sev.c
index f22490f86a4a..4d492abb233b 100644
--- a/arch/x86/kvm/svm/sev.c
+++ b/arch/x86/kvm/svm/sev.c
@@ -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);
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH v4 5/7] KVM: SEV: Add SNP vCPU state get and set commands
  2026-12-01  9:45 [PATCH v4 0/7] KVM: SVM: Support direct setting of VMSA for SEV-SNP guests Jörg Rödel
                   ` (3 preceding siblings ...)
  2026-12-01  9:45 ` [PATCH v4 4/7] KVM: SEV: Allow VMSA pages in SNP launch updates Jörg Rödel
@ 2026-12-01  9:45 ` Jörg Rödel
  2026-12-01  9:45 ` [PATCH v4 6/7] KVM: selftests: Test SNP vCPU state and direct VMSA launch Jörg Rödel
  2026-12-01  9:45 ` [PATCH v4 7/7] KVM: selftests: Test the SNP APIC-ID-list GHCB request Jörg Rödel
  6 siblings, 0 replies; 10+ messages in thread
From: Jörg Rödel @ 2026-12-01  9:45 UTC (permalink / raw)
  To: Paolo Bonzini, Sean Christopherson
  Cc: Michael Roth, Liam Merwick, Vishal Annapurve, Ninad Naik,
	Joerg Roedel, Tom Lendacky, James Bottomley, kvm, linux-doc,
	linux-kernel, linux-kselftest, coconut-svsm, joro

From: Joerg Roedel <joerg.roedel@amd.com>

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.

Signed-off-by: Joerg Roedel <joerg.roedel@amd.com>
---
 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(-)

diff --git a/arch/x86/include/uapi/asm/kvm.h b/arch/x86/include/uapi/asm/kvm.h
index f3c389d3c70e..546773e6d4de 100644
--- a/arch/x86/include/uapi/asm/kvm.h
+++ b/arch/x86/include/uapi/asm/kvm.h
@@ -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
diff --git a/arch/x86/kvm/svm/sev.c b/arch/x86/kvm/svm/sev.c
index 4d492abb233b..fae6a596c7ab 100644
--- a/arch/x86/kvm/svm/sev.c
+++ b/arch/x86/kvm/svm/sev.c
@@ -2553,6 +2553,8 @@ static int snp_launch_update(struct kvm *kvm, struct kvm_sev_cmd *argp)
 	return 0;
 }
 
+static int sev_snp_install_guest_vmsa(struct vcpu_svm *svm, gpa_t gpa);
+
 static int snp_launch_update_vmsa(struct kvm *kvm, struct kvm_sev_cmd *argp)
 {
 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
@@ -2623,6 +2625,102 @@ static int snp_launch_update_vmsa(struct kvm *kvm, struct kvm_sev_cmd *argp)
 	return ret;
 }
 
+static bool snp_launch_finished(struct kvm *kvm)
+{
+	/* Pairs with the release in snp_launch_finish(). */
+	return smp_load_acquire(&kvm->arch.pre_fault_allowed);
+}
+
+static int snp_get_vcpu_state(struct kvm_vcpu *vcpu,
+			      struct kvm_sev_cmd *argp)
+{
+	struct vcpu_svm *svm = to_svm(vcpu);
+	struct kvm *kvm = vcpu->kvm;
+	struct kvm_sev_snp_vcpu_state state = {};
+
+	if (!is_sev_snp_guest(vcpu))
+		return -ENOTTY;
+	if (!snp_launch_finished(kvm))
+		return -EINVAL;
+
+	guard(mutex)(&svm->sev_es.snp_vmsa_mutex);
+
+	/* A deferred reload can retain the GPA with vmsa_pa invalid. */
+	if (VALID_PAGE(svm->sev_es.snp_guest_vmsa_gpa)) {
+		state.vmsa_gpa = svm->sev_es.snp_guest_vmsa_gpa;
+		state.valid_fields |= KVM_SEV_SNP_VCPU_STATE_VMSA_VALID;
+	}
+
+	if (svm->sev_es.ghcb_registered_gpa) {
+		state.ghcb_gpa = svm->sev_es.ghcb_registered_gpa;
+		state.valid_fields |= KVM_SEV_SNP_VCPU_STATE_GHCB_VALID;
+	}
+
+	if (copy_to_user(u64_to_user_ptr(argp->data), &state, sizeof(state)))
+		return -EFAULT;
+
+	return 0;
+}
+
+static int snp_set_vcpu_state(struct kvm_vcpu *vcpu,
+			      struct kvm_sev_cmd *argp)
+{
+	struct vcpu_svm *svm = to_svm(vcpu);
+	struct kvm *kvm = vcpu->kvm;
+	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
+	struct kvm_sev_snp_vcpu_state state;
+	int ret;
+
+	if (!is_sev_snp_guest(vcpu))
+		return -ENOTTY;
+	if (!sev->snp_direct_vmsa)
+		return -EINVAL;
+	/* vCPUs created after launch finish did not get protected. */
+	if (!snp_launch_finished(kvm) || !vcpu->arch.guest_state_protected)
+		return -EINVAL;
+
+	if (copy_from_user(&state, u64_to_user_ptr(argp->data), sizeof(state)))
+		return -EFAULT;
+
+	if (memchr_inv(state.pad, 0, sizeof(state.pad)) ||
+	    state.valid_fields & ~(KVM_SEV_SNP_VCPU_STATE_VMSA_VALID |
+				   KVM_SEV_SNP_VCPU_STATE_GHCB_VALID))
+		return -EINVAL;
+
+	if ((state.valid_fields & KVM_SEV_SNP_VCPU_STATE_GHCB_VALID) &&
+	    (!state.ghcb_gpa || !page_address_valid(vcpu, state.ghcb_gpa)))
+		return -EINVAL;
+
+	if (state.valid_fields & KVM_SEV_SNP_VCPU_STATE_VMSA_VALID) {
+		if (!PAGE_ALIGNED(state.vmsa_gpa) ||
+		    !page_address_valid(vcpu, state.vmsa_gpa) ||
+		    IS_ALIGNED(state.vmsa_gpa, PMD_SIZE))
+			return -EINVAL;
+	}
+
+	guard(mutex)(&svm->sev_es.snp_vmsa_mutex);
+
+	if (state.valid_fields & KVM_SEV_SNP_VCPU_STATE_VMSA_VALID) {
+		ret = sev_snp_install_guest_vmsa(svm, state.vmsa_gpa);
+		if (ret)
+			return ret;
+	} else {
+		svm->sev_es.snp_has_guest_vmsa = true;
+		/* Pairs with READ_ONCE() in sev_gmem_invalidate_range(). */
+		WRITE_ONCE(svm->sev_es.snp_guest_vmsa_gpa, INVALID_PAGE);
+		svm->vmcb->control.vmsa_pa = INVALID_PAGE;
+	}
+
+	/* Preserve the GHCB MSR, which also carries protocol messages. */
+	if (state.valid_fields & KVM_SEV_SNP_VCPU_STATE_GHCB_VALID)
+		svm->sev_es.ghcb_registered_gpa = state.ghcb_gpa;
+	else
+		svm->sev_es.ghcb_registered_gpa = 0;
+
+	vmcb_mark_all_dirty(svm->vmcb);
+	return 0;
+}
+
 static int snp_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
 {
 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
@@ -2643,7 +2741,7 @@ static int snp_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
 	if (params.flags)
 		return -EINVAL;
 
-	/* Measure all vCPUs using LAUNCH_UPDATE before finalizing the launch flow. */
+	/* Protect all existing vCPUs, measuring KVM-owned VMSAs. */
 	ret = snp_launch_update_vmsa(kvm, argp);
 	if (ret)
 		return ret;
@@ -2686,7 +2784,8 @@ static int snp_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
 	 * This can happen on first access and also with KVM_PRE_FAULT_MEMORY.
 	 */
 	if (!ret)
-		kvm->arch.pre_fault_allowed = true;
+		/* Publish launch completion to snp_launch_finished(). */
+		smp_store_release(&kvm->arch.pre_fault_allowed, true);
 
 	kfree(id_auth);
 
@@ -2819,6 +2918,35 @@ int sev_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 	return r;
 }
 
+int sev_vcpu_mem_enc_ioctl(struct kvm_vcpu *vcpu, void __user *argp)
+{
+	struct kvm_sev_cmd sev_cmd;
+	int ret;
+
+	if (!sev_enabled)
+		return -ENOTTY;
+	if (!argp)
+		return -EINVAL;
+	if (copy_from_user(&sev_cmd, argp, sizeof(sev_cmd)))
+		return -EFAULT;
+
+	switch (sev_cmd.id) {
+	case KVM_SEV_SNP_GET_VCPU_STATE:
+		ret = snp_get_vcpu_state(vcpu, &sev_cmd);
+		break;
+	case KVM_SEV_SNP_SET_VCPU_STATE:
+		ret = snp_set_vcpu_state(vcpu, &sev_cmd);
+		break;
+	default:
+		return -EINVAL;
+	}
+
+	if (copy_to_user(argp, &sev_cmd, sizeof(sev_cmd)))
+		return -EFAULT;
+
+	return ret;
+}
+
 int sev_mem_enc_register_region(struct kvm *kvm,
 				struct kvm_enc_region *range)
 {
@@ -4099,6 +4227,62 @@ static int snp_begin_psc(struct vcpu_svm *svm)
 	return snp_do_psc(svm);
 }
 
+/*
+ * Install a guest-owned VMSA.  The caller must serialize against AP creation
+ * and destruction with snp_vmsa_mutex.
+ */
+static int sev_snp_install_guest_vmsa(struct vcpu_svm *svm, gpa_t gpa)
+{
+	struct kvm *kvm = svm->vcpu.kvm;
+	struct kvm_memory_slot *slot;
+	unsigned long mmu_seq;
+	kvm_pfn_t pfn;
+	gfn_t gfn;
+	int idx;
+	int ret;
+
+	lockdep_assert_held(&svm->sev_es.snp_vmsa_mutex);
+
+	gfn = gpa_to_gfn(gpa);
+	idx = srcu_read_lock(&kvm->srcu);
+	slot = gfn_to_memslot(kvm, gfn);
+	if (!slot) {
+		ret = -EINVAL;
+		goto out_unlock;
+	}
+
+	mmu_seq = kvm->mmu_invalidate_seq;
+	/* Pairs with the smp_wmb() in kvm_mmu_invalidate_end(). */
+	smp_rmb();
+
+	/*
+	 * As with AP_CREATE, this lookup can fault in a page and assign it
+	 * in the RMP as ordinary private memory. SET runs after launch
+	 * finish, when launch measurement is complete.
+	 *
+	 * Firmware (SNP_LAUNCH_UPDATE) or the guest (RMPADJUST) must mark
+	 * the page as a VMSA. snp_lookup_rmpentry() exposes only assignment
+	 * and page size, so rely on VMRUN to check the VMSA bit at entry.
+	 */
+	ret = kvm_gmem_get_pfn(kvm, slot, gfn, &pfn, NULL);
+	if (ret)
+		goto out_unlock;
+
+	read_lock(&kvm->mmu_lock);
+	if (mmu_invalidate_retry_gfn(kvm, mmu_seq, gfn)) {
+		ret = -EAGAIN;
+	} else {
+		svm->sev_es.snp_has_guest_vmsa = true;
+		WRITE_ONCE(svm->sev_es.snp_guest_vmsa_gpa, gpa);
+		svm->vmcb->control.vmsa_pa = pfn_to_hpa(pfn);
+	}
+	read_unlock(&kvm->mmu_lock);
+
+out_unlock:
+	srcu_read_unlock(&kvm->srcu, idx);
+	return ret;
+}
+
 static void __sev_snp_reload_vmsa(struct kvm_vcpu *vcpu, gpa_t gpa)
 {
 	struct vcpu_svm *svm = to_svm(vcpu);
diff --git a/arch/x86/kvm/svm/svm.c b/arch/x86/kvm/svm/svm.c
index 4682484a7d31..6ccfca6c44ec 100644
--- a/arch/x86/kvm/svm/svm.c
+++ b/arch/x86/kvm/svm/svm.c
@@ -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,
diff --git a/arch/x86/kvm/svm/svm.h b/arch/x86/kvm/svm/svm.h
index 90090c3021f6..ba03eb34b868 100644
--- a/arch/x86/kvm/svm/svm.h
+++ b/arch/x86/kvm/svm/svm.h
@@ -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,
diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index 017612ff959f..57a1f3b74267 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -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;
diff --git a/include/uapi/linux/kvm.h b/include/uapi/linux/kvm.h
index 005c25263030..00259ec260ce 100644
--- a/include/uapi/linux/kvm.h
+++ b/include/uapi/linux/kvm.h
@@ -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;
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH v4 6/7] KVM: selftests: Test SNP vCPU state and direct VMSA launch
  2026-12-01  9:45 [PATCH v4 0/7] KVM: SVM: Support direct setting of VMSA for SEV-SNP guests Jörg Rödel
                   ` (4 preceding siblings ...)
  2026-12-01  9:45 ` [PATCH v4 5/7] KVM: SEV: Add SNP vCPU state get and set commands Jörg Rödel
@ 2026-12-01  9:45 ` Jörg Rödel
  2026-12-01  9:45 ` [PATCH v4 7/7] KVM: selftests: Test the SNP APIC-ID-list GHCB request Jörg Rödel
  6 siblings, 0 replies; 10+ messages in thread
From: Jörg Rödel @ 2026-12-01  9:45 UTC (permalink / raw)
  To: Paolo Bonzini, Sean Christopherson
  Cc: Michael Roth, Liam Merwick, Vishal Annapurve, Ninad Naik,
	Joerg Roedel, Tom Lendacky, James Bottomley, kvm, linux-doc,
	linux-kernel, linux-kselftest, coconut-svsm, joro

From: Joerg Roedel <joerg.roedel@amd.com>

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.

Signed-off-by: Joerg Roedel <joerg.roedel@amd.com>
---
 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

diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selftests/kvm/Makefile.kvm
index 283c59d7649c..2086b6e1ee25 100644
--- a/tools/testing/selftests/kvm/Makefile.kvm
+++ b/tools/testing/selftests/kvm/Makefile.kvm
@@ -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
diff --git a/tools/testing/selftests/kvm/include/x86/sev.h b/tools/testing/selftests/kvm/include/x86/sev.h
index dec383e59a47..1def4f9b246b 100644
--- a/tools/testing/selftests/kvm/include/x86/sev.h
+++ b/tools/testing/selftests/kvm/include/x86/sev.h
@@ -31,6 +31,59 @@ enum sev_guest_state {
 
 #define GHCB_MSR_TERM_REQ	0x100
 
+#define SNP_ACTIVE_SEV_FEATURE	BIT_ULL(0)
+#define VMSA_PMD_SIZE		BIT_ULL(21)
+#define VMSA_MIN_GPA		(VMSA_PMD_SIZE + PAGE_SIZE)
+
+struct snp_test_vmsa {
+	struct vmcb_seg es, cs, ss, ds, fs, gs;
+	struct vmcb_seg gdtr, ldtr, idtr, tr;
+	u64 pl0_ssp, pl1_ssp, pl2_ssp, pl3_ssp;
+	u64 u_cet;
+	u8 reserved_0xc8[2];
+	u8 vmpl;
+	u8 cpl;
+	u8 reserved_0xcc[4];
+	u64 efer;
+	u8 reserved_0xd8[104];
+	u64 xss;
+	u64 cr4, cr3, cr0, dr7, dr6, rflags, rip;
+	u64 dr0, dr1, dr2, dr3;
+	u64 dr0_addr_mask, dr1_addr_mask, dr2_addr_mask, dr3_addr_mask;
+	u8 reserved_0x1c0[24];
+	u64 rsp, s_cet, ssp, isst_addr, rax;
+	u64 star, lstar, cstar, sfmask, kernel_gs_base;
+	u64 sysenter_cs, sysenter_esp, sysenter_eip, cr2;
+	u8 reserved_0x248[32];
+	u64 g_pat, dbgctl, br_from, br_to, last_excp_from, last_excp_to;
+	u8 reserved_0x298[80];
+	u32 pkru, tsc_aux;
+	u64 tsc_scale, tsc_offset;
+	u8 reserved_0x300[8];
+	u64 rcx, rdx, rbx, reserved_0x320, rbp, rsi, rdi;
+	u64 r8, r9, r10, r11, r12, r13, r14, r15;
+	u8 reserved_0x380[16];
+	u64 guest_exit_info_1, guest_exit_info_2, guest_exit_int_info, guest_nrip;
+	u64 sev_features, vintr_ctrl, guest_exit_code, virtual_tom, tlb_id, pcpu_id;
+	u64 event_inj, xcr0;
+	u8 reserved_0x3f0[16];
+	u64 x87_dp;
+	u32 mxcsr;
+	u16 x87_ftw, x87_fsw, x87_fcw, x87_fop, x87_ds, x87_cs;
+	u64 x87_rip;
+	u8 fpreg_x87[80];
+	u8 fpreg_xmm[256];
+	u8 fpreg_ymm[256];
+} __packed;
+
+static_assert(offsetof(struct snp_test_vmsa, vmpl) == 0xca, "VMSA VMPL offset");
+static_assert(offsetof(struct snp_test_vmsa, rip) == 0x178, "VMSA RIP offset");
+static_assert(offsetof(struct snp_test_vmsa, sev_features) == 0x3b0, "VMSA SEV features offset");
+static_assert(offsetof(struct snp_test_vmsa, xcr0) == 0x3e8, "VMSA XCR0 offset");
+
+void snp_prepare_vmsa(struct kvm_vcpu *vcpu, struct snp_test_vmsa *vmsa,
+		      void *entry);
+
 static inline bool is_sev_snp_vm(struct kvm_vm *vm)
 {
 	return vm->type == KVM_X86_SNP_VM;
@@ -100,6 +153,30 @@ static inline u64 snp_default_policy(void)
 	__TEST_ASSERT_VM_VCPU_IOCTL(!ret, #cmd,	ret, vm);		\
 })
 
+static inline int __vcpu_sev_ioctl(struct kvm_vcpu *vcpu, u32 cmd, void *arg)
+{
+	union {
+		struct kvm_sev_cmd c;
+		unsigned long raw;
+	} sev_cmd = { .c = {
+		.id = cmd,
+		.data = (u64)arg,
+		.sev_fd = vcpu->vm->arch.sev_fd,
+	} };
+	int ret;
+
+	ret = __vcpu_ioctl(vcpu, KVM_MEMORY_ENCRYPT_OP, &sev_cmd.raw);
+	return ret ?: sev_cmd.c.error;
+}
+
+#define vcpu_sev_ioctl(vcpu, cmd, arg)				\
+({								\
+	struct kvm_vcpu *__vcpu = (vcpu);				\
+	int ret = __vcpu_sev_ioctl(__vcpu, cmd, arg);		\
+								\
+	__TEST_ASSERT_VM_VCPU_IOCTL(!ret, #cmd, ret, __vcpu->vm);	\
+})
+
 void sev_vm_init(struct kvm_vm *vm);
 void sev_es_vm_init(struct kvm_vm *vm);
 void snp_vm_init(struct kvm_vm *vm);
@@ -144,6 +221,30 @@ static inline void snp_launch_update_data(struct kvm_vm *vm, gpa_t gpa,
 	vm_sev_ioctl(vm, KVM_SEV_SNP_LAUNCH_UPDATE, &update_data);
 }
 
+static inline void snp_launch_update_vmsa(struct kvm_vm *vm, gpa_t gpa,
+					  void *vmsa)
+{
+	vm_mem_set_private(vm, gpa, PAGE_SIZE);
+	snp_launch_update_data(vm, gpa, (u64)vmsa, PAGE_SIZE,
+			       KVM_SEV_SNP_PAGE_TYPE_VMSA);
+}
+
+static inline void snp_get_vcpu_state(struct kvm_vcpu *vcpu,
+				      struct kvm_sev_snp_vcpu_state *state)
+{
+	vcpu_sev_ioctl(vcpu, KVM_SEV_SNP_GET_VCPU_STATE, state);
+}
+
+static inline void snp_set_vcpu_state(struct kvm_vcpu *vcpu, gpa_t vmsa_gpa)
+{
+	struct kvm_sev_snp_vcpu_state state = {
+		.vmsa_gpa = vmsa_gpa,
+		.valid_fields = KVM_SEV_SNP_VCPU_STATE_VMSA_VALID,
+	};
+
+	vcpu_sev_ioctl(vcpu, KVM_SEV_SNP_SET_VCPU_STATE, &state);
+}
+
 static inline void sev_dbg_crypt_memory(struct kvm_vm *vm, unsigned int cmd,
 					void *dst, void *src, unsigned int len)
 {
diff --git a/tools/testing/selftests/kvm/lib/x86/sev.c b/tools/testing/selftests/kvm/lib/x86/sev.c
index 93f916903461..b9fbed4cd7ea 100644
--- a/tools/testing/selftests/kvm/lib/x86/sev.c
+++ b/tools/testing/selftests/kvm/lib/x86/sev.c
@@ -71,6 +71,85 @@ void sev_es_vm_init(struct kvm_vm *vm)
 	}
 }
 
+static void copy_segment(struct vmcb_seg *dst, const struct kvm_segment *src)
+{
+	dst->selector = src->selector;
+	dst->base = src->base;
+	dst->limit = src->limit;
+	dst->attrib = src->type |
+		(src->s << SVM_SELECTOR_S_SHIFT) |
+		(src->dpl << SVM_SELECTOR_DPL_SHIFT) |
+		((src->present && !src->unusable) << SVM_SELECTOR_P_SHIFT) |
+		(src->avl << SVM_SELECTOR_AVL_SHIFT) |
+		(src->l << SVM_SELECTOR_L_SHIFT) |
+		(src->db << SVM_SELECTOR_DB_SHIFT) |
+		(src->g << SVM_SELECTOR_G_SHIFT);
+}
+
+static void copy_dtable(struct vmcb_seg *dst, const struct kvm_dtable *src)
+{
+	dst->base = src->base;
+	dst->limit = src->limit;
+}
+
+void snp_prepare_vmsa(struct kvm_vcpu *vcpu, struct snp_test_vmsa *vmsa,
+		      void *entry)
+{
+	struct kvm_sregs sregs;
+	struct kvm_regs regs;
+
+	memset(vmsa, 0, PAGE_SIZE);
+	vcpu_sregs_get(vcpu, &sregs);
+	vcpu_regs_get(vcpu, &regs);
+
+	copy_segment(&vmsa->es, &sregs.es);
+	copy_segment(&vmsa->cs, &sregs.cs);
+	copy_segment(&vmsa->ss, &sregs.ss);
+	copy_segment(&vmsa->ds, &sregs.ds);
+	copy_segment(&vmsa->fs, &sregs.fs);
+	copy_segment(&vmsa->gs, &sregs.gs);
+	copy_dtable(&vmsa->gdtr, &sregs.gdt);
+	copy_segment(&vmsa->ldtr, &sregs.ldt);
+	copy_dtable(&vmsa->idtr, &sregs.idt);
+	copy_segment(&vmsa->tr, &sregs.tr);
+
+	vmsa->cpl = sregs.cs.dpl;
+	/*
+	 * KVM_GET_SREGS exposes the guest-visible EFER and therefore omits
+	 * SVME, which KVM normally adds to the hardware VMSA itself.
+	 */
+	vmsa->efer = sregs.efer | EFER_SVME;
+	vmsa->cr4 = sregs.cr4;
+	vmsa->cr3 = sregs.cr3;
+	vmsa->cr0 = sregs.cr0;
+	vmsa->dr7 = 0x400;
+	vmsa->dr6 = 0xffff0ff0;
+	vmsa->rflags = regs.rflags;
+	vmsa->rip = (u64)entry;
+	vmsa->rsp = regs.rsp;
+	vmsa->rax = regs.rax;
+	vmsa->rcx = regs.rcx;
+	vmsa->rdx = regs.rdx;
+	vmsa->rbx = regs.rbx;
+	vmsa->rbp = regs.rbp;
+	vmsa->rsi = regs.rsi;
+	vmsa->rdi = regs.rdi;
+	vmsa->r8 = regs.r8;
+	vmsa->r9 = regs.r9;
+	vmsa->r10 = regs.r10;
+	vmsa->r11 = regs.r11;
+	vmsa->r12 = regs.r12;
+	vmsa->r13 = regs.r13;
+	vmsa->r14 = regs.r14;
+	vmsa->r15 = regs.r15;
+	vmsa->g_pat = 0x0007040600070406ULL;
+	vmsa->sev_features = SNP_ACTIVE_SEV_FEATURE;
+	/* The selftest compiler and string helpers can use SSE instructions. */
+	vmsa->xcr0 = XFEATURE_MASK_FP | XFEATURE_MASK_SSE;
+	vmsa->mxcsr = 0x1f80;
+	vmsa->x87_fcw = 0x37f;
+}
+
 void snp_vm_init(struct kvm_vm *vm)
 {
 	struct kvm_sev_init init = { 0 };
diff --git a/tools/testing/selftests/kvm/x86/sev_snp_direct_vmsa_test.c b/tools/testing/selftests/kvm/x86/sev_snp_direct_vmsa_test.c
new file mode 100644
index 000000000000..be15b43f85cb
--- /dev/null
+++ b/tools/testing/selftests/kvm/x86/sev_snp_direct_vmsa_test.c
@@ -0,0 +1,476 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <errno.h>
+#include <stdlib.h>
+
+#include "kvm_util.h"
+#include "processor.h"
+#include "sev.h"
+#include "svm_util.h"
+
+#define DIRECT_MARKER	0x444952454354564dULL
+#define LEGACY_MARKER	0x4c4547414359564dULL
+#define GHCB_MSR_INFO_MASK	GENMASK_ULL(11, 0)
+#define GHCB_MSR_SEV_INFO_RESP	0x001
+
+struct direct_results {
+	u64 marker;
+	u64 initial_ghcb_msr;
+};
+
+static void guest_direct_entry(struct direct_results *results)
+{
+	results->initial_ghcb_msr = rdmsr(MSR_AMD64_SEV_ES_GHCB);
+	results->marker = DIRECT_MARKER;
+	wrmsr(MSR_AMD64_SEV_ES_GHCB, GHCB_MSR_TERM_REQ);
+	vmgexit();
+}
+
+static void guest_legacy_entry(u64 *marker)
+{
+	*marker = LEGACY_MARKER;
+	wrmsr(MSR_AMD64_SEV_ES_GHCB, GHCB_MSR_TERM_REQ);
+	vmgexit();
+}
+
+static void expect_launch_update_vmsa_error(struct kvm_vm *vm, gpa_t gpa,
+					    void *vmsa, u64 size)
+{
+	struct kvm_sev_snp_launch_update update = {
+		.gfn_start = gpa >> PAGE_SHIFT,
+		.uaddr = (u64)vmsa,
+		.len = size,
+		.type = KVM_SEV_SNP_PAGE_TYPE_VMSA,
+	};
+
+	errno = 0;
+	TEST_ASSERT_EQ(__vm_sev_ioctl(vm, KVM_SEV_SNP_LAUNCH_UPDATE, &update), -1);
+	TEST_ASSERT_EQ(errno, EINVAL);
+}
+
+static void exclude_from_normal_launch(struct kvm_vm *vm, gpa_t gpa,
+				       unsigned int npages)
+{
+	struct userspace_mem_region *region;
+
+	region = memslot2region(vm, vm->memslots[MEM_REGION_TEST_DATA]);
+	sparsebit_clear_num(region->protected_phy_pages, gpa >> PAGE_SHIFT, npages);
+}
+
+static void assert_vcpu_terminated(struct kvm_vcpu *vcpu)
+{
+	vcpu_run(vcpu);
+	TEST_ASSERT_EQ(vcpu->run->exit_reason, KVM_EXIT_SYSTEM_EVENT);
+	TEST_ASSERT_EQ(vcpu->run->system_event.type, KVM_SYSTEM_EVENT_SEV_TERM);
+}
+
+static void assert_vcpu_entry_failed(struct kvm_vcpu *vcpu)
+{
+	vcpu_run(vcpu);
+	TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_FAIL_ENTRY);
+	TEST_ASSERT_EQ(vcpu->run->fail_entry.hardware_entry_failure_reason,
+		       SVM_EXIT_ERR);
+}
+
+static struct kvm_vm *create_direct_vmsa_vm(unsigned int nr_vcpus,
+					    void *guest_code,
+					    struct kvm_vcpu **vcpus)
+{
+	struct vm_shape shape = {
+		.mode = VM_MODE_DEFAULT,
+		.type = KVM_X86_SNP_VM,
+	};
+	struct kvm_vm *vm;
+	unsigned int i;
+
+	vm = __vm_create(shape, nr_vcpus, 0);
+	vm_enable_cap(vm, KVM_CAP_SNP_DIRECT_VMSA, 0);
+	for (i = 0; i < nr_vcpus; i++)
+		vcpus[i] = vm_vcpu_add(vm, i, guest_code);
+	kvm_arch_vm_finalize_vcpus(vm);
+
+	return vm;
+}
+
+static void expect_set_vcpu_state_error(struct kvm_vcpu *vcpu,
+					struct kvm_sev_snp_vcpu_state *state,
+					int expected_errno)
+{
+	errno = 0;
+	TEST_ASSERT_EQ(__vcpu_sev_ioctl(vcpu, KVM_SEV_SNP_SET_VCPU_STATE, state), -1);
+	TEST_ASSERT_EQ(errno, expected_errno);
+}
+
+static void expect_vcpu_state_unavailable(struct kvm_vcpu *vcpu,
+					  struct kvm_sev_snp_vcpu_state *state,
+					  int expected_errno)
+{
+	errno = 0;
+	TEST_ASSERT_EQ(__vcpu_sev_ioctl(vcpu, KVM_SEV_SNP_GET_VCPU_STATE, state), -1);
+	TEST_ASSERT_EQ(errno, expected_errno);
+	expect_set_vcpu_state_error(vcpu, state, expected_errno);
+}
+
+static void test_direct_vmsa(void)
+{
+	struct snp_test_vmsa *vmsas, *selected_vmsa;
+	struct kvm_sev_snp_vcpu_state state = {};
+	struct kvm_mp_state mp_state = {
+		.mp_state = KVM_MP_STATE_UNINITIALIZED,
+	};
+	struct kvm_guest_debug debug = {
+		.control = KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP,
+	};
+	struct kvm_sev_snp_launch_finish finish = {};
+	struct kvm_vcpu *vcpus[2];
+	struct kvm_vcpu *vcpu, *ap;
+	struct kvm_vm *vm;
+	struct direct_results *results;
+	gva_t marker_gva;
+	gpa_t vmsa_gpa;
+
+	vm = create_direct_vmsa_vm(ARRAY_SIZE(vcpus), guest_legacy_entry, vcpus);
+	vcpu = vcpus[0];
+	ap = vcpus[1];
+	/* Restore normal AP state after vm_vcpu_add() makes it runnable. */
+	vcpu_mp_state_set(ap, &mp_state);
+	marker_gva = vm_alloc_shared(vm, PAGE_SIZE, KVM_UTIL_MIN_VADDR,
+				     MEM_REGION_TEST_DATA);
+	results = addr_gva2hva(vm, marker_gva);
+	vcpu_args_set(vcpu, 1, marker_gva);
+
+	vmsa_gpa = ____vm_phy_pages_alloc(vm, 2, VMSA_MIN_GPA,
+					vm->memslots[MEM_REGION_TEST_DATA], true, false);
+	TEST_ASSERT(vmsa_gpa & (VMSA_PMD_SIZE - 1), "unsafe VMSA GPA");
+	vmsas = aligned_alloc(PAGE_SIZE, 2 * PAGE_SIZE);
+	TEST_ASSERT(vmsas, "Failed to allocate VMSA source pages");
+	selected_vmsa = (void *)vmsas + PAGE_SIZE;
+	snp_prepare_vmsa(vcpu, &vmsas[0], guest_legacy_entry);
+	snp_prepare_vmsa(vcpu, selected_vmsa, guest_direct_entry);
+
+	snp_vm_launch_start(vm, snp_default_policy());
+	vm_mem_set_private(vm, vmsa_gpa, 2 * PAGE_SIZE);
+	expect_launch_update_vmsa_error(vm, vmsa_gpa, vmsas, 2 * PAGE_SIZE);
+
+	vmsas[0].vmpl = 1;
+	expect_launch_update_vmsa_error(vm, vmsa_gpa, vmsas, PAGE_SIZE);
+	vmsas[0].vmpl = 0;
+	vmsas[0].sev_features = 0;
+	expect_launch_update_vmsa_error(vm, vmsa_gpa, vmsas, PAGE_SIZE);
+	vmsas[0].sev_features = SNP_ACTIVE_SEV_FEATURE;
+
+	snp_launch_update_vmsa(vm, vmsa_gpa, vmsas);
+	snp_launch_update_vmsa(vm, vmsa_gpa + PAGE_SIZE, selected_vmsa);
+	exclude_from_normal_launch(vm, vmsa_gpa, 2);
+	snp_vm_launch_update(vm);
+
+	state.valid_fields = KVM_SEV_SNP_VCPU_STATE_VMSA_VALID;
+	state.vmsa_gpa = vmsa_gpa;
+	expect_vcpu_state_unavailable(vcpu, &state, EINVAL);
+	memset(results, 0, sizeof(*results));
+	assert_vcpu_entry_failed(vcpu);
+	TEST_ASSERT_EQ(results->marker, 0);
+
+	/* A debug-enabled AP must not cause partial protection of the BSP. */
+	vcpu_ioctl(ap, KVM_SET_GUEST_DEBUG, &debug);
+	TEST_ASSERT_EQ(__vm_sev_ioctl(vm, KVM_SEV_SNP_LAUNCH_FINISH, &finish), -1);
+	TEST_ASSERT_EQ(errno, EINVAL);
+	debug.control = 0;
+	vcpu_ioctl(ap, KVM_SET_GUEST_DEBUG, &debug);
+	snp_vm_launch_finish(vm);
+
+	/* Rebind to the second VMSA and register a GHCB in the same request. */
+	snp_set_vcpu_state(vcpu, vmsa_gpa);
+	snp_get_vcpu_state(vcpu, &state);
+	TEST_ASSERT_EQ(state.valid_fields, KVM_SEV_SNP_VCPU_STATE_VMSA_VALID);
+	TEST_ASSERT_EQ(state.vmsa_gpa, vmsa_gpa);
+	TEST_ASSERT_EQ(state.ghcb_gpa, 0);
+
+	state.valid_fields |= KVM_SEV_SNP_VCPU_STATE_GHCB_VALID;
+	state.vmsa_gpa = vmsa_gpa + PAGE_SIZE;
+	state.ghcb_gpa = PAGE_SIZE;
+	vcpu_sev_ioctl(vcpu, KVM_SEV_SNP_SET_VCPU_STATE, &state);
+	snp_get_vcpu_state(vcpu, &state);
+	TEST_ASSERT_EQ(state.valid_fields, KVM_SEV_SNP_VCPU_STATE_VMSA_VALID |
+		       KVM_SEV_SNP_VCPU_STATE_GHCB_VALID);
+	TEST_ASSERT_EQ(state.vmsa_gpa, vmsa_gpa + PAGE_SIZE);
+	TEST_ASSERT_EQ(state.ghcb_gpa, PAGE_SIZE);
+
+	vcpu_mp_state_get(ap, &mp_state);
+	TEST_ASSERT_EQ(mp_state.mp_state, KVM_MP_STATE_UNINITIALIZED);
+	assert_vcpu_terminated(vcpu);
+	TEST_ASSERT_EQ(results->marker, DIRECT_MARKER);
+	TEST_ASSERT_EQ(results->initial_ghcb_msr & GHCB_MSR_INFO_MASK,
+		       GHCB_MSR_SEV_INFO_RESP);
+
+	state.valid_fields = KVM_SEV_SNP_VCPU_STATE_GHCB_VALID;
+	vcpu_sev_ioctl(vcpu, KVM_SEV_SNP_SET_VCPU_STATE, &state);
+	snp_get_vcpu_state(vcpu, &state);
+	TEST_ASSERT_EQ(state.valid_fields, KVM_SEV_SNP_VCPU_STATE_GHCB_VALID);
+	TEST_ASSERT_EQ(state.vmsa_gpa, 0);
+	TEST_ASSERT_EQ(state.ghcb_gpa, PAGE_SIZE);
+
+	free(vmsas);
+	kvm_vm_free(vm);
+}
+
+static void test_ghcb_registration(void)
+{
+	struct kvm_sev_snp_vcpu_state state = {};
+	struct kvm_vcpu *vcpu;
+	struct kvm_vm *vm;
+
+	vm = create_direct_vmsa_vm(1, guest_legacy_entry, &vcpu);
+	snp_vm_launch_start(vm, snp_default_policy());
+	snp_vm_launch_update(vm);
+	snp_vm_launch_finish(vm);
+	snp_get_vcpu_state(vcpu, &state);
+	TEST_ASSERT_EQ(state.valid_fields, 0);
+
+	state.valid_fields = KVM_SEV_SNP_VCPU_STATE_GHCB_VALID;
+	state.ghcb_gpa = PAGE_SIZE;
+	vcpu_sev_ioctl(vcpu, KVM_SEV_SNP_SET_VCPU_STATE, &state);
+	memset(&state, 0, sizeof(state));
+	snp_get_vcpu_state(vcpu, &state);
+	TEST_ASSERT_EQ(state.valid_fields, KVM_SEV_SNP_VCPU_STATE_GHCB_VALID);
+	TEST_ASSERT_EQ(state.ghcb_gpa, PAGE_SIZE);
+
+	state.ghcb_gpa = 0;
+	expect_set_vcpu_state_error(vcpu, &state, EINVAL);
+	state.ghcb_gpa = GHCB_MSR_TERM_REQ;
+	expect_set_vcpu_state_error(vcpu, &state, EINVAL);
+	state.ghcb_gpa = BIT_ULL(63);
+	expect_set_vcpu_state_error(vcpu, &state, EINVAL);
+	snp_get_vcpu_state(vcpu, &state);
+	TEST_ASSERT_EQ(state.valid_fields, KVM_SEV_SNP_VCPU_STATE_GHCB_VALID);
+	TEST_ASSERT_EQ(state.ghcb_gpa, PAGE_SIZE);
+
+	state.valid_fields = 0;
+	vcpu_sev_ioctl(vcpu, KVM_SEV_SNP_SET_VCPU_STATE, &state);
+	snp_get_vcpu_state(vcpu, &state);
+	TEST_ASSERT_EQ(state.valid_fields, 0);
+	TEST_ASSERT_EQ(state.ghcb_gpa, 0);
+	kvm_vm_free(vm);
+}
+
+static void test_failed_launch_finish(void)
+{
+	struct kvm_sev_snp_vcpu_state state = {
+		.valid_fields = KVM_SEV_SNP_VCPU_STATE_GHCB_VALID,
+		.ghcb_gpa = PAGE_SIZE,
+	};
+	struct kvm_sev_snp_launch_finish finish = {
+		.id_block_en = 1,
+		.id_block_uaddr = -1ULL,
+	};
+	struct kvm_vcpu *vcpu;
+	struct kvm_vm *vm;
+
+	vm = create_direct_vmsa_vm(1, guest_legacy_entry, &vcpu);
+	snp_vm_launch_start(vm, snp_default_policy());
+	snp_vm_launch_update(vm);
+
+	/* Bad ID data fails after the vCPU has already been protected. */
+	errno = 0;
+	TEST_ASSERT_EQ(__vm_sev_ioctl(vm, KVM_SEV_SNP_LAUNCH_FINISH, &finish), -1);
+	TEST_ASSERT_EQ(errno, EFAULT);
+	expect_vcpu_state_unavailable(vcpu, &state, EINVAL);
+	assert_vcpu_entry_failed(vcpu);
+	kvm_vm_free(vm);
+}
+
+static void test_vmsa_memslot_replacement(void)
+{
+	const gpa_t gpa = BIT_ULL(32) + PAGE_SIZE;
+	const u32 slot = 10;
+	struct kvm_sev_snp_vcpu_state state;
+	struct snp_test_vmsa *vmsa;
+	struct kvm_vcpu *vcpu;
+	struct kvm_vm *vm;
+
+	vm = create_direct_vmsa_vm(1, guest_legacy_entry, &vcpu);
+	vmsa = aligned_alloc(PAGE_SIZE, PAGE_SIZE);
+	TEST_ASSERT(vmsa, "Failed to allocate a VMSA source page");
+	snp_prepare_vmsa(vcpu, vmsa, guest_legacy_entry);
+	snp_vm_launch_start(vm, snp_default_policy());
+
+	vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS, gpa, slot, 1,
+				    KVM_MEM_GUEST_MEMFD);
+	snp_launch_update_vmsa(vm, gpa, vmsa);
+	snp_vm_launch_update(vm);
+	snp_vm_launch_finish(vm);
+	snp_set_vcpu_state(vcpu, gpa);
+
+	/* SET can fault in a new page after hole punching. */
+	vm_guest_mem_punch_hole(vm, gpa, PAGE_SIZE);
+	snp_set_vcpu_state(vcpu, gpa);
+	assert_vcpu_entry_failed(vcpu);
+	snp_get_vcpu_state(vcpu, &state);
+	TEST_ASSERT_EQ(state.valid_fields, KVM_SEV_SNP_VCPU_STATE_VMSA_VALID);
+	TEST_ASSERT_EQ(state.vmsa_gpa, gpa);
+
+	vm_mem_region_delete(vm, slot);
+	vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS, gpa, slot, 1,
+				    KVM_MEM_GUEST_MEMFD);
+	vm_mem_set_private(vm, gpa, PAGE_SIZE);
+	/* GET still reports the association while reload is pending. */
+	snp_get_vcpu_state(vcpu, &state);
+	TEST_ASSERT_EQ(state.valid_fields, KVM_SEV_SNP_VCPU_STATE_VMSA_VALID);
+	TEST_ASSERT_EQ(state.vmsa_gpa, gpa);
+
+	/* The replacement page is ordinary data and fails guest entry. */
+	assert_vcpu_entry_failed(vcpu);
+	snp_get_vcpu_state(vcpu, &state);
+	TEST_ASSERT_EQ(state.valid_fields, KVM_SEV_SNP_VCPU_STATE_VMSA_VALID);
+	TEST_ASSERT_EQ(state.vmsa_gpa, gpa);
+
+	vm_mem_region_delete(vm, slot);
+	expect_set_vcpu_state_error(vcpu, &state, EINVAL);
+	/* With no slot to resolve, reload clears the tracked GPA. */
+	assert_vcpu_entry_failed(vcpu);
+	snp_get_vcpu_state(vcpu, &state);
+	TEST_ASSERT_EQ(state.valid_fields, 0);
+	TEST_ASSERT_EQ(state.vmsa_gpa, 0);
+
+	free(vmsa);
+	kvm_vm_free(vm);
+}
+
+static void test_invalid_requests(void)
+{
+	const gpa_t shared_gpa = BIT_ULL(32) + PAGE_SIZE;
+	struct kvm_sev_snp_vcpu_state state = {
+		.valid_fields = KVM_SEV_SNP_VCPU_STATE_VMSA_VALID,
+	};
+	struct kvm_sev_snp_launch_update update = {
+		.len = PAGE_SIZE,
+		.type = KVM_SEV_SNP_PAGE_TYPE_ZERO,
+	};
+	struct kvm_vcpu *vcpu;
+	struct kvm_vm *vm;
+	gpa_t private_gpa;
+
+	vm = vm_create_with_one_vcpu(&vcpu, guest_legacy_entry);
+	expect_vcpu_state_unavailable(vcpu, &state, ENOTTY);
+	kvm_vm_free(vm);
+
+	vm = create_direct_vmsa_vm(1, guest_legacy_entry, &vcpu);
+	snp_vm_launch_start(vm, snp_default_policy());
+	private_gpa = ____vm_phy_pages_alloc(vm, 1, VMSA_MIN_GPA,
+					    vm->memslots[MEM_REGION_TEST_DATA], true, false);
+	TEST_ASSERT(private_gpa & (VMSA_PMD_SIZE - 1), "unsafe VMSA GPA");
+	vm_mem_set_private(vm, private_gpa, PAGE_SIZE);
+	update.gfn_start = private_gpa >> PAGE_SHIFT;
+	vm_sev_ioctl(vm, KVM_SEV_SNP_LAUNCH_UPDATE, &update);
+	exclude_from_normal_launch(vm, private_gpa, 1);
+	snp_vm_launch_update(vm);
+	snp_vm_launch_finish(vm);
+
+	vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS, shared_gpa, 10, 1, 0);
+
+	state.vmsa_gpa = private_gpa;
+	state.pad[4] = 1;
+	expect_set_vcpu_state_error(vcpu, &state, EINVAL);
+	state.pad[4] = 0;
+	state.valid_fields |= BIT_ULL(2);
+	expect_set_vcpu_state_error(vcpu, &state, EINVAL);
+	state.valid_fields &= ~BIT_ULL(2);
+	state.vmsa_gpa = private_gpa + 1;
+	expect_set_vcpu_state_error(vcpu, &state, EINVAL);
+	state.vmsa_gpa = VMSA_PMD_SIZE;
+	expect_set_vcpu_state_error(vcpu, &state, EINVAL);
+	state.vmsa_gpa = BIT_ULL(63) + PAGE_SIZE;
+	expect_set_vcpu_state_error(vcpu, &state, EINVAL);
+
+	/* Failed VMSA lookup must leave the GHCB registration unchanged. */
+	state.vmsa_gpa = shared_gpa;
+	state.ghcb_gpa = PAGE_SIZE;
+	state.valid_fields |= KVM_SEV_SNP_VCPU_STATE_GHCB_VALID;
+	expect_set_vcpu_state_error(vcpu, &state, EFAULT);
+
+	snp_get_vcpu_state(vcpu, &state);
+	TEST_ASSERT_EQ(state.valid_fields, 0);
+	TEST_ASSERT_EQ(state.ghcb_gpa, 0);
+
+	/* SET accepts existing data backing.  VMRUN checks the RMP VMSA bit. */
+	snp_set_vcpu_state(vcpu, private_gpa);
+	snp_get_vcpu_state(vcpu, &state);
+	TEST_ASSERT_EQ(state.valid_fields, KVM_SEV_SNP_VCPU_STATE_VMSA_VALID);
+	TEST_ASSERT_EQ(state.vmsa_gpa, private_gpa);
+	assert_vcpu_entry_failed(vcpu);
+
+	kvm_vm_free(vm);
+}
+
+static void test_direct_vmsa_capability(void)
+{
+	struct kvm_enable_cap cap = {
+		.cap = KVM_CAP_SNP_DIRECT_VMSA,
+	};
+	struct vm_shape shape = {
+		.mode = VM_MODE_DEFAULT,
+		.type = KVM_X86_SNP_VM,
+	};
+	struct kvm_vm *vm;
+
+	vm = vm_create_barebones();
+	TEST_ASSERT_EQ(__vm_enable_cap(vm, KVM_CAP_SNP_DIRECT_VMSA, 0), -1);
+	TEST_ASSERT_EQ(errno, EINVAL);
+	kvm_vm_free(vm);
+
+	vm = __vm_create(shape, 1, 0);
+	TEST_ASSERT_EQ(__vm_enable_cap(vm, KVM_CAP_SNP_DIRECT_VMSA, 1), -1);
+	TEST_ASSERT_EQ(errno, EINVAL);
+	cap.args[3] = 1;
+	TEST_ASSERT_EQ(__vm_ioctl(vm, KVM_ENABLE_CAP, &cap), -1);
+	TEST_ASSERT_EQ(errno, EINVAL);
+	cap.args[3] = 0;
+	cap.flags = 1;
+	TEST_ASSERT_EQ(__vm_ioctl(vm, KVM_ENABLE_CAP, &cap), -1);
+	TEST_ASSERT_EQ(errno, EINVAL);
+	vm_enable_cap(vm, KVM_CAP_SNP_DIRECT_VMSA, 0);
+	vm_vcpu_add(vm, 0, guest_legacy_entry);
+	TEST_ASSERT_EQ(__vm_enable_cap(vm, KVM_CAP_SNP_DIRECT_VMSA, 0), -1);
+	TEST_ASSERT_EQ(errno, EINVAL);
+	kvm_vm_free(vm);
+}
+
+static void test_legacy_launch(void)
+{
+	struct kvm_sev_snp_vcpu_state state;
+	struct kvm_vcpu *vcpu;
+	struct kvm_vm *vm;
+	gva_t marker_gva;
+	u64 *marker;
+
+	vm = vm_sev_create_with_one_vcpu(KVM_X86_SNP_VM, guest_legacy_entry, &vcpu);
+	marker_gva = vm_alloc_shared(vm, PAGE_SIZE, KVM_UTIL_MIN_VADDR,
+				     MEM_REGION_TEST_DATA);
+	marker = addr_gva2hva(vm, marker_gva);
+	vcpu_args_set(vcpu, 1, marker_gva);
+	vm_sev_launch(vm, snp_default_policy(), NULL);
+	snp_get_vcpu_state(vcpu, &state);
+	TEST_ASSERT_EQ(state.valid_fields, 0);
+	TEST_ASSERT_EQ(state.vmsa_gpa, 0);
+	expect_set_vcpu_state_error(vcpu, &state, EINVAL);
+
+	*marker = 0;
+	assert_vcpu_terminated(vcpu);
+	TEST_ASSERT_EQ(*marker, LEGACY_MARKER);
+	kvm_vm_free(vm);
+}
+
+int main(int argc, char *argv[])
+{
+	TEST_REQUIRE(kvm_check_cap(KVM_CAP_SNP_VCPU_STATE));
+	TEST_REQUIRE(kvm_check_cap(KVM_CAP_SNP_DIRECT_VMSA));
+	TEST_ASSERT(sizeof(struct snp_test_vmsa) <= PAGE_SIZE, "VMSA structure is too large");
+
+	test_direct_vmsa_capability();
+	test_ghcb_registration();
+	test_failed_launch_finish();
+	test_vmsa_memslot_replacement();
+	test_invalid_requests();
+	test_direct_vmsa();
+	test_legacy_launch();
+	return 0;
+}
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH v4 7/7] KVM: selftests: Test the SNP APIC-ID-list GHCB request
  2026-12-01  9:45 [PATCH v4 0/7] KVM: SVM: Support direct setting of VMSA for SEV-SNP guests Jörg Rödel
                   ` (5 preceding siblings ...)
  2026-12-01  9:45 ` [PATCH v4 6/7] KVM: selftests: Test SNP vCPU state and direct VMSA launch Jörg Rödel
@ 2026-12-01  9:45 ` Jörg Rödel
  6 siblings, 0 replies; 10+ messages in thread
From: Jörg Rödel @ 2026-12-01  9:45 UTC (permalink / raw)
  To: Paolo Bonzini, Sean Christopherson
  Cc: Michael Roth, Liam Merwick, Vishal Annapurve, Ninad Naik,
	Joerg Roedel, Tom Lendacky, James Bottomley, kvm, linux-doc,
	linux-kernel, linux-kselftest, coconut-svsm, joro

From: Joerg Roedel <joerg.roedel@amd.com>

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.

Signed-off-by: Joerg Roedel <joerg.roedel@amd.com>
---
 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

diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selftests/kvm/Makefile.kvm
index 2086b6e1ee25..3b8867f67b04 100644
--- a/tools/testing/selftests/kvm/Makefile.kvm
+++ b/tools/testing/selftests/kvm/Makefile.kvm
@@ -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
diff --git a/tools/testing/selftests/kvm/include/x86/sev.h b/tools/testing/selftests/kvm/include/x86/sev.h
index 1def4f9b246b..0c67625d7ce1 100644
--- a/tools/testing/selftests/kvm/include/x86/sev.h
+++ b/tools/testing/selftests/kvm/include/x86/sev.h
@@ -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,
diff --git a/tools/testing/selftests/kvm/x86/sev_snp_apic_id_test.c b/tools/testing/selftests/kvm/x86/sev_snp_apic_id_test.c
new file mode 100644
index 000000000000..8f69fb1c45c7
--- /dev/null
+++ b/tools/testing/selftests/kvm/x86/sev_snp_apic_id_test.c
@@ -0,0 +1,340 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <stddef.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#include "kvm_util.h"
+#include "processor.h"
+#include "sev.h"
+#include "svm_util.h"
+
+#define GHCB_SAVE_RAX_OFFSET		0x1f8
+#define GHCB_SAVE_SW_EXIT_CODE_OFFSET	0x390
+#define GHCB_SAVE_SW_EXIT_INFO_1_OFFSET	0x398
+#define GHCB_SAVE_SW_EXIT_INFO_2_OFFSET	0x3a0
+#define GHCB_SAVE_VALID_BITMAP_OFFSET	0x3f0
+#define GHCB_PROTOCOL_VERSION_OFFSET	0xffa
+#define GHCB_PROTOCOL_VERSION		2
+
+#define GHCB_MSR_REG_GPA_REQ		0x012
+#define GHCB_MSR_REG_GPA_RESP		0x013
+#define GHCB_MSR_HV_FT_REQ		0x080
+#define GHCB_MSR_HV_FT_RESP		0x081
+#define GHCB_MSR_HV_FT_POS		12
+#define GHCB_MSR_INFO_MASK		GENMASK_ULL(11, 0)
+#define GHCB_HV_FT_APIC_ID_LIST		BIT_ULL(4)
+
+#define GHCB_HV_RESP_MALFORMED_INPUT	2
+#define GHCB_ERR_MISSING_INPUT		4
+#define GHCB_ERR_INVALID_INPUT		5
+#define GHCB_ERR_INVALID_EVENT		6
+
+#define APIC_ID_BOUNDARY		(PAGE_SIZE / sizeof(u32))
+#define APIC_ID_STRIDE		2
+#define BUFFER_PATTERN		0xa5
+
+struct apic_id_desc {
+	u32 nr_entries;
+	u32 apic_ids[];
+};
+
+struct apic_id_response {
+	u64 info1;
+	u64 info2;
+	u64 pages;
+};
+
+struct apic_id_results {
+	gpa_t private_gpa;
+	gpa_t one_page_gpa;
+	u64 features_msr;
+	u64 features_nae;
+	u64 features_nae_status;
+	struct apic_id_response missing;
+	struct apic_id_response zero;
+	struct apic_id_response undersized;
+	struct apic_id_response misaligned;
+	struct apic_id_response out_of_range;
+	struct apic_id_response private;
+	struct apic_id_response unmapped;
+	struct apic_id_response partial;
+	struct apic_id_response valid;
+	bool list_unchanged;
+};
+
+static bool buffer_has_pattern(const void *buffer, size_t size)
+{
+	const u8 *bytes = buffer;
+	size_t i;
+
+	for (i = 0; i < size; i++) {
+		if (bytes[i] != BUFFER_PATTERN)
+			return false;
+	}
+	return true;
+}
+
+static void ghcb_init(void *ghcb)
+{
+	memset(ghcb, 0, PAGE_SIZE);
+	*(u16 *)(ghcb + GHCB_PROTOCOL_VERSION_OFFSET) = GHCB_PROTOCOL_VERSION;
+}
+
+static void ghcb_set_field(void *ghcb, size_t offset, u64 value, bool valid)
+{
+	u8 *valid_bitmap = ghcb + GHCB_SAVE_VALID_BITMAP_OFFSET;
+
+	*(u64 *)(ghcb + offset) = value;
+	if (valid)
+		valid_bitmap[(offset / sizeof(u64)) / 8] |=
+			BIT((offset / sizeof(u64)) % 8);
+}
+
+static u64 ghcb_get_field(void *ghcb, size_t offset)
+{
+	return *(u64 *)(ghcb + offset);
+}
+
+static struct apic_id_response get_apic_ids(void *ghcb, gpa_t buffer_gpa,
+					   u64 pages, bool rax_valid)
+{
+	ghcb_init(ghcb);
+	ghcb_set_field(ghcb, GHCB_SAVE_SW_EXIT_CODE_OFFSET,
+		       SVM_VMGEXIT_GET_APIC_IDS, true);
+	ghcb_set_field(ghcb, GHCB_SAVE_SW_EXIT_INFO_1_OFFSET, buffer_gpa, true);
+	ghcb_set_field(ghcb, GHCB_SAVE_SW_EXIT_INFO_2_OFFSET, 0, true);
+	ghcb_set_field(ghcb, GHCB_SAVE_RAX_OFFSET, pages, rax_valid);
+	vmgexit();
+
+	return (struct apic_id_response) {
+		.info1 = ghcb_get_field(ghcb, GHCB_SAVE_SW_EXIT_INFO_1_OFFSET),
+		.info2 = ghcb_get_field(ghcb, GHCB_SAVE_SW_EXIT_INFO_2_OFFSET),
+		.pages = ghcb_get_field(ghcb, GHCB_SAVE_RAX_OFFSET),
+	};
+}
+
+static void guest_code(void *ghcb, gpa_t ghcb_gpa, void *list,
+		       gpa_t list_gpa, struct apic_id_results *results,
+		       u64 expected_vcpus)
+{
+	u64 msr;
+
+	wrmsr(MSR_AMD64_SEV_ES_GHCB, GHCB_MSR_HV_FT_REQ);
+	vmgexit();
+	msr = rdmsr(MSR_AMD64_SEV_ES_GHCB);
+	if ((msr & GHCB_MSR_INFO_MASK) != GHCB_MSR_HV_FT_RESP)
+		goto terminate;
+	results->features_msr = msr >> GHCB_MSR_HV_FT_POS;
+
+	wrmsr(MSR_AMD64_SEV_ES_GHCB, ghcb_gpa | GHCB_MSR_REG_GPA_REQ);
+	vmgexit();
+	msr = rdmsr(MSR_AMD64_SEV_ES_GHCB);
+	if (msr != (ghcb_gpa | GHCB_MSR_REG_GPA_RESP))
+		goto terminate;
+
+	wrmsr(MSR_AMD64_SEV_ES_GHCB, ghcb_gpa);
+
+	ghcb_init(ghcb);
+	ghcb_set_field(ghcb, GHCB_SAVE_SW_EXIT_CODE_OFFSET, SVM_VMGEXIT_HV_FEATURES, true);
+	ghcb_set_field(ghcb, GHCB_SAVE_SW_EXIT_INFO_1_OFFSET, 0, true);
+	ghcb_set_field(ghcb, GHCB_SAVE_SW_EXIT_INFO_2_OFFSET, 0, true);
+	vmgexit();
+	results->features_nae_status = ghcb_get_field(ghcb, GHCB_SAVE_SW_EXIT_INFO_1_OFFSET);
+	results->features_nae = ghcb_get_field(ghcb, GHCB_SAVE_SW_EXIT_INFO_2_OFFSET);
+
+	if (!expected_vcpus) {
+		results->valid = get_apic_ids(ghcb, list_gpa, 2, true);
+		goto terminate;
+	}
+
+	results->missing = get_apic_ids(ghcb, list_gpa, 1, false);
+	results->zero = get_apic_ids(ghcb, list_gpa, 0, true);
+	if (expected_vcpus == APIC_ID_BOUNDARY)
+		results->undersized = get_apic_ids(ghcb, list_gpa, 1, true);
+	results->misaligned = get_apic_ids(ghcb, list_gpa + 1, 2, true);
+	results->out_of_range = get_apic_ids(ghcb, BIT_ULL(63), 2, true);
+	results->private = get_apic_ids(ghcb, results->private_gpa, 2, true);
+	results->unmapped = get_apic_ids(ghcb, results->one_page_gpa + PAGE_SIZE, 2, true);
+	results->partial = get_apic_ids(ghcb, results->one_page_gpa, 2, true);
+	results->list_unchanged = buffer_has_pattern(list, 2 * PAGE_SIZE);
+	results->valid = get_apic_ids(ghcb, list_gpa, 2, true);
+
+terminate:
+	wrmsr(MSR_AMD64_SEV_ES_GHCB, GHCB_MSR_TERM_REQ);
+	vmgexit();
+}
+
+static void launch_direct_bsp(struct kvm_vcpu *vcpu)
+{
+	struct kvm_vm *vm = vcpu->vm;
+	u32 slot = vm->memslots[MEM_REGION_TEST_DATA];
+	struct userspace_mem_region *region;
+	struct snp_test_vmsa *vmsa;
+	gpa_t gpa;
+
+	gpa = ____vm_phy_pages_alloc(vm, 1, VMSA_MIN_GPA, slot, true, false);
+	TEST_ASSERT(gpa & (VMSA_PMD_SIZE - 1), "unsafe VMSA GPA");
+	vmsa = aligned_alloc(PAGE_SIZE, PAGE_SIZE);
+	TEST_ASSERT(vmsa, "Failed to allocate a VMSA source page");
+	snp_prepare_vmsa(vcpu, vmsa, guest_code);
+
+	snp_vm_launch_start(vm, snp_default_policy());
+	snp_launch_update_vmsa(vm, gpa, vmsa);
+	region = memslot2region(vm, slot);
+	sparsebit_clear(region->protected_phy_pages, gpa >> PAGE_SHIFT);
+	snp_vm_launch_update(vm);
+	snp_vm_launch_finish(vm);
+	snp_set_vcpu_state(vcpu, gpa);
+	free(vmsa);
+}
+
+static void assert_invalid_input(const struct apic_id_response *response)
+{
+	TEST_ASSERT_EQ(response->info1, GHCB_HV_RESP_MALFORMED_INPUT);
+	TEST_ASSERT_EQ(response->info2, GHCB_ERR_INVALID_INPUT);
+}
+
+static void assert_apic_id_list(const struct apic_id_desc *desc,
+				unsigned int nr_vcpus)
+{
+	bool seen[APIC_ID_BOUNDARY] = {};
+	size_t size = sizeof(*desc) + nr_vcpus * sizeof(desc->apic_ids[0]);
+	unsigned int i;
+
+	TEST_ASSERT_EQ(desc->nr_entries, nr_vcpus);
+	for (i = 0; i < nr_vcpus; i++) {
+		u32 id = desc->apic_ids[i];
+		u32 index = id / APIC_ID_STRIDE;
+
+		TEST_ASSERT(id % APIC_ID_STRIDE == 0 && index < nr_vcpus,
+			    "Unexpected APIC ID %u at entry %u", id, i);
+		TEST_ASSERT(!seen[index], "Duplicate APIC ID %u", id);
+		seen[index] = true;
+	}
+
+	TEST_ASSERT(buffer_has_pattern((const u8 *)desc + size, 2 * PAGE_SIZE - size),
+		    "GET_APIC_IDS wrote past the end of the descriptor");
+}
+
+static void run_apic_id_test(unsigned int nr_vcpus, bool direct)
+{
+	const gpa_t one_page_gpa = BIT_ULL(32);
+	struct vm_shape shape = {
+		.mode = VM_MODE_DEFAULT,
+		.type = KVM_X86_SNP_VM,
+	};
+	struct apic_id_results *results;
+	struct kvm_vcpu *vcpu;
+	struct kvm_vm *vm;
+	void *list;
+	gva_t ghcb_gva, list_gva, results_gva;
+	gpa_t ghcb_gpa, list_gpa;
+	unsigned int i;
+	int ret;
+
+	kvm_set_files_rlimit(nr_vcpus);
+	vm = __vm_create(shape, 1, 0);
+	if (direct)
+		vm_enable_cap(vm, KVM_CAP_SNP_DIRECT_VMSA, 0);
+	vcpu = vm_vcpu_add(vm, 0, guest_code);
+	for (i = 1; i < nr_vcpus; i++)
+		__vm_vcpu_add(vm, i * APIC_ID_STRIDE);
+	kvm_arch_vm_finalize_vcpus(vm);
+
+	ghcb_gva = vm_alloc_shared(vm, PAGE_SIZE, KVM_UTIL_MIN_VADDR,
+				   MEM_REGION_TEST_DATA);
+	list_gva = vm_alloc_shared(vm, 2 * PAGE_SIZE, KVM_UTIL_MIN_VADDR,
+				   MEM_REGION_TEST_DATA);
+	results_gva = vm_alloc_shared(vm, PAGE_SIZE, KVM_UTIL_MIN_VADDR,
+				      MEM_REGION_TEST_DATA);
+	ghcb_gpa = addr_gva2gpa(vm, ghcb_gva);
+	list_gpa = addr_gva2gpa(vm, list_gva);
+	list = addr_gva2hva(vm, list_gva);
+	results = addr_gva2hva(vm, results_gva);
+
+	vcpu_args_set(vcpu, 6, ghcb_gva, ghcb_gpa, list_gva, list_gpa,
+		      results_gva, direct ? (u64)nr_vcpus : 0);
+	memset(list, BUFFER_PATTERN, 2 * PAGE_SIZE);
+	memset(results, 0, PAGE_SIZE);
+	if (direct) {
+		/* The launch range iterator uses GFN 0 as its end sentinel. */
+		results->private_gpa = vm_phy_pages_alloc(vm, 2, MEM_REGION_TEST_DATA);
+		/* A writable first page followed by an unmapped page. */
+		vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS, one_page_gpa, 10, 1, 0);
+		memset(addr_gpa2hva(vm, one_page_gpa), BUFFER_PATTERN, PAGE_SIZE);
+		results->one_page_gpa = one_page_gpa;
+		launch_direct_bsp(vcpu);
+	} else {
+		vm_sev_launch(vm, snp_default_policy(), NULL);
+	}
+
+	ret = _vcpu_run(vcpu);
+	if (ret && vcpu->run->exit_reason == KVM_EXIT_MEMORY_FAULT)
+		TEST_FAIL("KVM_RUN %s/%u vCPUs: errno=%d GPA=%#llx size=%#llx flags=%#llx",
+			  direct ? "direct" : "legacy", nr_vcpus, errno,
+			  vcpu->run->memory_fault.gpa, vcpu->run->memory_fault.size,
+			  vcpu->run->memory_fault.flags);
+	TEST_ASSERT(!ret, KVM_IOCTL_ERROR(KVM_RUN, ret));
+	TEST_ASSERT_EQ(vcpu->run->exit_reason, KVM_EXIT_SYSTEM_EVENT);
+	TEST_ASSERT_EQ(vcpu->run->system_event.type, KVM_SYSTEM_EVENT_SEV_TERM);
+
+	TEST_ASSERT_EQ(results->features_nae_status, 0);
+	TEST_ASSERT_EQ(results->features_msr, results->features_nae);
+	TEST_ASSERT_EQ(!!(results->features_msr & GHCB_HV_FT_APIC_ID_LIST), direct);
+	if (!direct) {
+		TEST_ASSERT_EQ(results->valid.info1, GHCB_HV_RESP_MALFORMED_INPUT);
+		TEST_ASSERT_EQ(results->valid.info2, GHCB_ERR_INVALID_EVENT);
+		TEST_ASSERT(buffer_has_pattern(list, 2 * PAGE_SIZE),
+			    "GET_APIC_IDS modified the legacy guest's buffer");
+		kvm_vm_free(vm);
+		return;
+	}
+
+	TEST_ASSERT_EQ(results->missing.info1, GHCB_HV_RESP_MALFORMED_INPUT);
+	TEST_ASSERT_EQ(results->missing.info2, GHCB_ERR_MISSING_INPUT);
+	TEST_ASSERT_EQ(results->zero.info1, 0);
+	TEST_ASSERT_EQ(results->zero.info2, 0);
+	TEST_ASSERT_EQ(results->zero.pages,
+		       DIV_ROUND_UP(sizeof(struct apic_id_desc) + nr_vcpus * sizeof(u32),
+				    PAGE_SIZE));
+	if (nr_vcpus == APIC_ID_BOUNDARY) {
+		TEST_ASSERT_EQ(results->undersized.info1, 0);
+		TEST_ASSERT_EQ(results->undersized.info2, 0);
+		TEST_ASSERT_EQ(results->undersized.pages, 2);
+	}
+	assert_invalid_input(&results->misaligned);
+	assert_invalid_input(&results->out_of_range);
+	assert_invalid_input(&results->private);
+	assert_invalid_input(&results->unmapped);
+	assert_invalid_input(&results->partial);
+	TEST_ASSERT(results->list_unchanged,
+		    "GET_APIC_IDS modified an invalid or undersized buffer");
+	TEST_ASSERT(buffer_has_pattern(addr_gpa2hva(vm, one_page_gpa), PAGE_SIZE),
+		    "GET_APIC_IDS modified the mapped part of an invalid buffer");
+	TEST_ASSERT_EQ(results->valid.info1, 0);
+	TEST_ASSERT_EQ(results->valid.info2, 0);
+	TEST_ASSERT_EQ(results->valid.pages, 2);
+	assert_apic_id_list(list, nr_vcpus);
+
+	kvm_vm_free(vm);
+}
+
+int main(int argc, char *argv[])
+{
+	unsigned int max_vcpus;
+
+	TEST_REQUIRE(kvm_check_cap(KVM_CAP_VM_TYPES) & BIT(KVM_X86_SNP_VM));
+	TEST_REQUIRE(kvm_check_cap(KVM_CAP_SNP_DIRECT_VMSA));
+	TEST_REQUIRE(kvm_check_cap(KVM_CAP_SNP_VCPU_STATE));
+	run_apic_id_test(2, false);
+	run_apic_id_test(2, true);
+
+	/* 1024 IDs cross the one-page descriptor boundary. */
+	max_vcpus = kvm_check_cap(KVM_CAP_MAX_VCPUS);
+	if (max_vcpus >= APIC_ID_BOUNDARY)
+		run_apic_id_test(APIC_ID_BOUNDARY, true);
+	else
+		pr_info("Skipping vCPU-count boundary test (max vCPUs: %u)\n", max_vcpus);
+
+	return 0;
+}
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* Re: [PATCH v4 3/7] KVM: SVM: Implement GET_AP_APIC_IDS NAE event
  2026-12-01  9:45 ` [PATCH v4 3/7] KVM: SVM: Implement GET_AP_APIC_IDS NAE event Jörg Rödel
@ 2026-12-01 10:00   ` sashiko-bot
  2026-12-01 10:23     ` Jörg Rödel
  0 siblings, 1 reply; 10+ messages in thread
From: sashiko-bot @ 2026-12-01 10:00 UTC (permalink / raw)
  To: Jörg Rödel; +Cc: kvm

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 <joerg.roedel@amd.com>

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.

> diff --git a/arch/x86/kvm/svm/sev.c b/arch/x86/kvm/svm/sev.c
> index 18ccab1139895..f22490f86a4ab 100644
> --- a/arch/x86/kvm/svm/sev.c
> +++ b/arch/x86/kvm/svm/sev.c
[ ... ]
> @@ -4261,6 +4262,93 @@ static int sev_snp_ap_creation(struct vcpu_svm *svm)
>  	return 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++) {
> +		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.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261201094525.1240736-1-joro@8bytes.org?part=3

^ permalink raw reply	[flat|nested] 10+ messages in thread

* Re: [PATCH v4 3/7] KVM: SVM: Implement GET_AP_APIC_IDS NAE event
  2026-12-01 10:00   ` sashiko-bot
@ 2026-12-01 10:23     ` Jörg Rödel
  0 siblings, 0 replies; 10+ messages in thread
From: Jörg Rödel @ 2026-12-01 10:23 UTC (permalink / raw)
  To: sashiko-reviews; +Cc: kvm

On Tue, Dec 01, 2026 at 10:00:56AM +0000, sashiko-bot@kernel.org wrote:
> > +		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.

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

-Joerg

^ permalink raw reply	[flat|nested] 10+ messages in thread

end of thread, other threads:[~2026-12-01 10:23 UTC | newest]

Thread overview: 10+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-01  9:45 [PATCH v4 0/7] KVM: SVM: Support direct setting of VMSA for SEV-SNP guests Jörg Rödel
2026-12-01  9:45 ` [PATCH v4 1/7] KVM: SEV: Document SNP direct VMSA userspace ABI Jörg Rödel
2026-12-01  9:45 ` [PATCH v4 2/7] KVM: SEV: Add direct VMSA capability Jörg Rödel
2026-12-01  9:45 ` [PATCH v4 3/7] KVM: SVM: Implement GET_AP_APIC_IDS NAE event Jörg Rödel
2026-12-01 10:00   ` sashiko-bot
2026-12-01 10:23     ` Jörg Rödel
2026-12-01  9:45 ` [PATCH v4 4/7] KVM: SEV: Allow VMSA pages in SNP launch updates Jörg Rödel
2026-12-01  9:45 ` [PATCH v4 5/7] KVM: SEV: Add SNP vCPU state get and set commands Jörg Rödel
2026-12-01  9:45 ` [PATCH v4 6/7] KVM: selftests: Test SNP vCPU state and direct VMSA launch Jörg Rödel
2026-12-01  9:45 ` [PATCH v4 7/7] KVM: selftests: Test the SNP APIC-ID-list GHCB request Jörg Rödel

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox