Skip to contentSkip to conversation

Add AMD Secure Nested Paging (SEV-SNP) Hypervisor Support

RFC PATCH Superseded Michael Roth 17 participants 148 messages Feb 20, 2023 – Aug 4, 2023 Page 2 of 2

Subsystems (12)

v8 of 15 Superseded Latest is v15 →

lore
Share & tools
lore
#94 lore raw

Re: [PATCH RFC v8 35/56] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_UPDATE command

In reply to Michael Roth
Quoted 94 lines · On Mon, 20 Feb 2023 12:38:26 -0600 Michael Roth <[email protected]> wrote:

From: Brijesh Singh <[email protected]>

The KVM_SEV_SNP_LAUNCH_UPDATE command can be used to insert data into the guest's memory. The data is encrypted with the cryptographic context created with the KVM_SEV_SNP_LAUNCH_START.

In addition to the inserting data, it can insert a two special pages into the guests memory: the secrets page and the CPUID page.

While terminating the guest, reclaim the guest pages added in the RMP table. If the reclaim fails, then the page is no longer safe to be released back to the system and leak them.

For more information see the SEV-SNP specification.

---
 .../virt/kvm/x86/amd-memory-encryption.rst    |  29 +++
 arch/x86/kvm/svm/sev.c                        | 190 ++++++++++++++++++
 include/uapi/linux/kvm.h                      |  19 ++
 3 files changed, 238 insertions(+)
Documentation/virt/kvm/x86/amd-memory-encryption.rst +29 -0
index 58971fc02a15..c94be8e6d657 100644
@@ -485,6 +485,35 @@ Returns: 0 on success, -negative on error
 
 See the SEV-SNP specification for further detail on the launch input.
 
+20. KVM_SNP_LAUNCH_UPDATE
+-------------------------
+
+The KVM_SNP_LAUNCH_UPDATE is used for encrypting a memory region. It also
+calculates a measurement of the memory contents. The measurement is a signature
+of the memory contents that can be sent to the guest owner as an attestation
+that the memory was encrypted correctly by the firmware.
+
+Parameters (in): struct  kvm_snp_launch_update
+
+Returns: 0 on success, -negative on error
+
+::
+
+        struct kvm_sev_snp_launch_update {
+                __u64 start_gfn;        /* Guest page number to start from. */
+                __u64 uaddr;            /* userspace address need to be encrypted */
+                __u32 len;              /* length of memory region */
+                __u8 imi_page;          /* 1 if memory is part of the IMI */
+                __u8 page_type;         /* page type */
+                __u8 vmpl3_perms;       /* VMPL3 permission mask */
+                __u8 vmpl2_perms;       /* VMPL2 permission mask */
+                __u8 vmpl1_perms;       /* VMPL1 permission mask */
+        };
+
+See the SEV-SNP spec for further details on how to build the VMPL permission
+mask and page type.
+
+
 References
 ==========
 
arch/x86/kvm/svm/sev.c +21 -0
index 097bb2138360..03dd227f6090 100644
@@ -234,6 +234,37 @@ static void sev_decommission(unsigned int handle)
 	sev_guest_decommission(&decommission, NULL);
 }
 
+static int snp_page_reclaim(u64 pfn)
+{
+	struct sev_data_snp_page_reclaim data = {0};
+	int err, rc;
+
+	data.paddr = __sme_set(pfn << PAGE_SHIFT);
+	rc = sev_do_cmd(SEV_CMD_SNP_PAGE_RECLAIM, &data, &err);
+	if (rc) {
+		/*
+		 * If the reclaim failed, then page is no longer safe
+		 * to use.
+		 */
+		snp_mark_pages_offline(pfn,
+				       page_level_size(PG_LEVEL_4K) >> PAGE_SHIFT);
+	}
+
+	return rc;
+}
+
+static int host_rmp_make_shared(u64 pfn, enum pg_level level, bool leak)
+{

arch/x86/kvm/svm/sev.c static void sev_decommission(unsigned int handle) · line 267

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+	int rc;
+
+	rc = rmp_make_shared(pfn, level);
+	if (rc && leak)
+		snp_mark_pages_offline(pfn,
+				       page_level_size(level) >> PAGE_SHIFT);
+
+	return rc;
+}
+

PATCH 24 has similar functions. It would be better to expose them.

Quoted 213 lines
arch/x86/kvm/svm/sev.c +159 -0
 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
 {
 	struct sev_data_deactivate deactivate;
@@ -2093,6 +2124,162 @@ static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
 	return rc;
 }
 
+static int snp_launch_update_gfn_handler(struct kvm *kvm,
+					 struct kvm_gfn_range *range,
+					 void *opaque)
+{
+	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
+	struct kvm_memory_slot *memslot = range->slot;
+	struct sev_data_snp_launch_update data = {0};
+	struct kvm_sev_snp_launch_update params;
+	struct kvm_sev_cmd *argp = opaque;
+	int *error = &argp->error;
+	int i, n = 0, ret = 0;
+	unsigned long npages;
+	kvm_pfn_t *pfns;
+	gfn_t gfn;
+
+	if (!kvm_slot_can_be_private(memslot)) {
+		pr_err("SEV-SNP requires restricted memory.\n");
+		return -EINVAL;
+	}
+
+	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params))) {
+		pr_err("Failed to copy user parameters for SEV-SNP launch.\n");
+		return -EFAULT;
+	}
+
+	data.gctx_paddr = __psp_pa(sev->snp_context);
+
+	npages = range->end - range->start;
+	pfns = kvmalloc_array(npages, sizeof(*pfns), GFP_KERNEL_ACCOUNT);
+	if (!pfns)
+		return -ENOMEM;
+
+	pr_debug("%s: GFN range 0x%llx-0x%llx, type %d\n", __func__,
+		 range->start, range->end, params.page_type);
+
+	for (gfn = range->start, i = 0; gfn < range->end; gfn++, i++) {
+		int order, level;
+		void *kvaddr;
+
+		ret = kvm_restrictedmem_get_pfn(memslot, gfn, &pfns[i], &order);
+		if (ret)
+			goto e_release;
+
+		n++;
+		ret = snp_lookup_rmpentry((u64)pfns[i], &level);
+		if (ret) {
+			pr_err("Failed to ensure GFN 0x%llx is in initial shared state, ret: %d\n",
+			       gfn, ret);
+			return -EFAULT;
+		}
+
+		kvaddr = pfn_to_kaddr(pfns[i]);
+		if (!virt_addr_valid(kvaddr)) {
+			pr_err("Invalid HVA 0x%llx for GFN 0x%llx\n", (uint64_t)kvaddr, gfn);
+			ret = -EINVAL;
+			goto e_release;
+		}
+
+		ret = kvm_read_guest_page(kvm, gfn, kvaddr, 0, PAGE_SIZE);
+		if (ret) {
+			pr_err("Guest read failed, ret: 0x%x\n", ret);
+			goto e_release;
+		}
+
+		ret = rmp_make_private(pfns[i], gfn << PAGE_SHIFT, PG_LEVEL_4K,
+				       sev_get_asid(kvm), true);
+		if (ret) {
+			ret = -EFAULT;
+			goto e_release;
+		}
+
+		data.address = __sme_set(pfns[i] << PAGE_SHIFT);
+		data.page_size = X86_TO_RMP_PG_LEVEL(PG_LEVEL_4K);
+		data.page_type = params.page_type;
+		data.vmpl3_perms = params.vmpl3_perms;
+		data.vmpl2_perms = params.vmpl2_perms;
+		data.vmpl1_perms = params.vmpl1_perms;
+		ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_LAUNCH_UPDATE,
+				      &data, error);
+		if (ret) {
+			pr_err("SEV-SNP launch update failed, ret: 0x%x, fw_error: 0x%x\n",
+			       ret, *error);
+			snp_page_reclaim(pfns[i]);
+
+			/*
+			 * When invalid CPUID function entries are detected, the firmware
+			 * corrects these entries for debugging purpose and leaves the
+			 * page unencrypted so it can be provided users for debugging
+			 * and error-reporting.
+			 *
+			 * Copy the corrected CPUID page back to shared memory so
+			 * userpsace can retrieve this information.
+			 */
+			if (params.page_type == SNP_PAGE_TYPE_CPUID &&
+			    *error == SEV_RET_INVALID_PARAM) {
+				int ret;
+
+				host_rmp_make_shared(pfns[i], PG_LEVEL_4K, true);
+
+				ret = kvm_write_guest_page(kvm, gfn, kvaddr, 0, PAGE_SIZE);
+				if (ret)
+					pr_err("Failed to write CPUID page back to userspace, ret: 0x%x\n",
+					       ret);
+			}
+
+
+			goto e_release;
+		}
+	}
+
+	/*
+	 * Memory attribute updates via KVM_SET_MEMORY_ATTRIBUTES are serialized
+	 * via kvm->slots_lock, so use the same protocol for updating them here.
+	 */
+	mutex_lock(&kvm->slots_lock);
+	kvm_vm_set_region_attr(kvm, range->start, range->end, KVM_MEMORY_ATTRIBUTE_PRIVATE);
+	mutex_unlock(&kvm->slots_lock);
+
+e_release:
+	/* Content of memory is updated, mark pages dirty */
+	for (i = 0; i < n; i++) {
+		set_page_dirty(pfn_to_page(pfns[i]));
+		mark_page_accessed(pfn_to_page(pfns[i]));
+
+		/*
+		 * If its an error, then update RMP entry to change page ownership
+		 * to the hypervisor.
+		 */
+		if (ret)
+			host_rmp_make_shared(pfns[i], PG_LEVEL_4K, true);
+
+		put_page(pfn_to_page(pfns[i]));
+	}
+
+	kvfree(pfns);
+	return ret;
+}
+
+static int snp_launch_update(struct kvm *kvm, struct kvm_sev_cmd *argp)
+{
+	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
+	struct kvm_sev_snp_launch_update params;
+
+	if (!sev_snp_guest(kvm))
+		return -ENOTTY;
+
+	if (!sev->snp_context)
+		return -EINVAL;
+
+	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
+		return -EFAULT;
+
+	return kvm_vm_do_hva_range_op(kvm, params.uaddr, params.uaddr + params.len,
+				      snp_launch_update_gfn_handler, argp);
+}
+
 int sev_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 {
 	struct kvm_sev_cmd sev_cmd;
@@ -2186,6 +2373,9 @@ int sev_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 	case KVM_SEV_SNP_LAUNCH_START:
 		r = snp_launch_start(kvm, &sev_cmd);
 		break;
+	case KVM_SEV_SNP_LAUNCH_UPDATE:
+		r = snp_launch_update(kvm, &sev_cmd);
+		break;
 	default:
 		r = -EINVAL;
 		goto out;
include/uapi/linux/kvm.h +19 -0
index cf19799ca5ce..4098bba17aa4 100644
@@ -1920,6 +1920,7 @@ enum sev_cmd_id {
 	/* SNP specific commands */
 	KVM_SEV_SNP_INIT,
 	KVM_SEV_SNP_LAUNCH_START,
+	KVM_SEV_SNP_LAUNCH_UPDATE,
 
 	KVM_SEV_NR_MAX,
 };
@@ -2036,6 +2037,24 @@ struct kvm_sev_snp_launch_start {
 	__u8 pad[6];
 };
 
+#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
+#define KVM_SEV_SNP_PAGE_TYPE_CPUID		0x6
+
+struct kvm_sev_snp_launch_update {
+	__u64 start_gfn;
+	__u64 uaddr;
+	__u32 len;
+	__u8 imi_page;
+	__u8 page_type;
+	__u8 vmpl3_perms;
+	__u8 vmpl2_perms;
+	__u8 vmpl1_perms;
+};
+
 #define KVM_DEV_ASSIGN_ENABLE_IOMMU	(1 << 0)
 #define KVM_DEV_ASSIGN_PCI_2_3		(1 << 1)
 #define KVM_DEV_ASSIGN_MASK_INTX	(1 << 2)
#95 lore raw

RFC PATCH v8 36/56 KVM: SVM: Add KVM_SEV_SNP_LAUNCH_FINISH command

In reply to Michael Roth

From: Brijesh Singh <[email protected]>

The KVM_SEV_SNP_LAUNCH_FINISH finalize the cryptographic digest and stores it as the measurement of the guest at launch.

While finalizing the launch flow, it also issues the LAUNCH_UPDATE command to encrypt the VMSA pages.

If its an SNP guest, then VMSA was added in the RMP entry as a guest owned page and also removed from the kernel direct map so flush it later after it is transitioned back to hypervisor state and restored in the direct map.

---
 .../virt/kvm/x86/amd-memory-encryption.rst    |  23 ++++
 arch/x86/kvm/svm/sev.c                        | 122 ++++++++++++++++++
 include/uapi/linux/kvm.h                      |  14 ++
 3 files changed, 159 insertions(+)
Documentation/virt/kvm/x86/amd-memory-encryption.rst +23 -0
index c94be8e6d657..dafb0c9984f1 100644
@@ -513,6 +513,29 @@ Returns: 0 on success, -negative on error
 See the SEV-SNP spec for further details on how to build the VMPL permission
 mask and page type.
 
+21. KVM_SNP_LAUNCH_FINISH
+-------------------------
+
+After completion of the SNP guest launch flow, the KVM_SNP_LAUNCH_FINISH command can be
+issued to make the guest ready for the execution.
+
+Parameters (in): struct kvm_sev_snp_launch_finish
+
+Returns: 0 on success, -negative on error
+
+::
+
+        struct kvm_sev_snp_launch_finish {
+                __u64 id_block_uaddr;
+                __u64 id_auth_uaddr;
+                __u8 id_block_en;
+                __u8 auth_key_en;
+                __u8 host_data[32];
+                __u8 pad[6];
+        };
+
+
+See SEV-SNP specification for further details on launch finish input parameters.
 
 References
 ==========
arch/x86/kvm/svm/sev.c +122 -0

145 lines not on this page · raw message

include/uapi/linux/kvm.h +14 -0
index 4098bba17aa4..2bab08a5b5d7 100644
@@ -1921,6 +1921,7 @@ enum sev_cmd_id {
 	KVM_SEV_SNP_INIT,
 	KVM_SEV_SNP_LAUNCH_START,
 	KVM_SEV_SNP_LAUNCH_UPDATE,
+	KVM_SEV_SNP_LAUNCH_FINISH,
 
 	KVM_SEV_NR_MAX,
 };
@@ -2055,6 +2056,19 @@ struct kvm_sev_snp_launch_update {
 	__u8 vmpl1_perms;
 };
 
+#define KVM_SEV_SNP_ID_BLOCK_SIZE	96
+#define KVM_SEV_SNP_ID_AUTH_SIZE	4096
+#define KVM_SEV_SNP_FINISH_DATA_SIZE	32
+
+struct kvm_sev_snp_launch_finish {
+	__u64 id_block_uaddr;
+	__u64 id_auth_uaddr;
+	__u8 id_block_en;
+	__u8 auth_key_en;
+	__u8 host_data[KVM_SEV_SNP_FINISH_DATA_SIZE];
+	__u8 pad[6];
+};
+
 #define KVM_DEV_ASSIGN_ENABLE_IOMMU	(1 << 0)
 #define KVM_DEV_ASSIGN_PCI_2_3		(1 << 1)
 #define KVM_DEV_ASSIGN_MASK_INTX	(1 << 2)
Signature · 1 line
2.25.1
#96 lore raw

Re: [PATCH RFC v8 36/56] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_FINISH command

Quoted 23 lines · Michael Roth

From: Brijesh Singh <[email protected]>

The KVM_SEV_SNP_LAUNCH_FINISH finalize the cryptographic digest and stores it as the measurement of the guest at launch.

While finalizing the launch flow, it also issues the LAUNCH_UPDATE command to encrypt the VMSA pages.

If its an SNP guest, then VMSA was added in the RMP entry as a guest owned page and also removed from the kernel direct map so flush it later after it is transitioned back to hypervisor state and restored in the direct map.

---
  .../virt/kvm/x86/amd-memory-encryption.rst    |  23 ++++
  arch/x86/kvm/svm/sev.c                        | 122 ++++++++++++++++++
  include/uapi/linux/kvm.h                      |  14 ++
  3 files changed, 159 insertions(+)

[...]

Quoted 27 lines
arch/x86/kvm/svm/sev.c +19 -0
index 03dd227f6090..515e22d0dc30 100644
@@ -2280,6 +2280,109 @@ static int snp_launch_update(struct kvm *kvm, struct kvm_sev_cmd *argp)
                                       snp_launch_update_gfn_handler, argp);
  }
 
+static int snp_launch_update_vmsa(struct kvm *kvm, struct kvm_sev_cmd *argp)
+{
+       struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
+       struct sev_data_snp_launch_update data = {};
+       struct kvm_vcpu *vcpu;
+       unsigned long i;
+       int ret;
+
+       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;
+
+               /* Perform some pre-encryption checks against the VMSA */
+               ret = sev_es_sync_vmsa(svm);
+               if (ret)
+                       return ret;

arch/x86/kvm/svm/sev.c static int snp_launch_update(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 2311

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+
+               /* Transition the VMSA page to a firmware state. */
+               ret = rmp_make_private(pfn, -1, PG_LEVEL_4K, sev->asid, true);
+               if (ret)
+                       return ret;
+
+               /* Issue the SNP command to encrypt the VMSA */
+               data.address = __sme_pa(svm->sev_es.vmsa);
+               ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_LAUNCH_UPDATE,
+                                     &data, &argp->error);

There is no contract in KVM that dictates that the first entry in the vcpu list needs to be vcpu_id==0 (BSP). That means if you use a user space that spawns vCPUs in parallel on init, you will end up with the BSP behind APs in the LAUNCH_UPDATE order.

This is a problem because for LAUNCH_UPDATE, the order matters. BSP and AP vCPUs have different initial state and so if you want to reconstruct the launch digest, you need to ensure that the guest knows the order.

The easiest way I can think of to fix this is to call snp_launch_update_vmsa twice: Once filtering for vcpu_id == 0 and once for vcpu_id != 0.

Thanks,

Alex

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879

#97 lore raw

Re: [PATCH RFC v8 36/56] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_FINISH command

In reply to Michael Roth
Quoted 23 lines · Michael Roth

From: Brijesh Singh<[email protected]>

The KVM_SEV_SNP_LAUNCH_FINISH finalize the cryptographic digest and stores it as the measurement of the guest at launch.

While finalizing the launch flow, it also issues the LAUNCH_UPDATE command to encrypt the VMSA pages.

If its an SNP guest, then VMSA was added in the RMP entry as a guest owned page and also removed from the kernel direct map so flush it later after it is transitioned back to hypervisor state and restored in the direct map.

---
  .../virt/kvm/x86/amd-memory-encryption.rst    |  23 ++++
  arch/x86/kvm/svm/sev.c                        | 122 ++++++++++++++++++
  include/uapi/linux/kvm.h                      |  14 ++
  3 files changed, 159 insertions(+)

[...]

include/uapi/linux/kvm.h struct kvm_sev_snp_launch_update { · line 2069

Quoted 12 lines
include/uapi/linux/kvm.h +11 -0
+#define KVM_SEV_SNP_ID_BLOCK_SIZE      96
+#define KVM_SEV_SNP_ID_AUTH_SIZE       4096
+#define KVM_SEV_SNP_FINISH_DATA_SIZE   32
+
+struct kvm_sev_snp_launch_finish {
+       __u64 id_block_uaddr;
+       __u64 id_auth_uaddr;
+       __u8 id_block_en;
+       __u8 auth_key_en;
+       __u8 host_data[KVM_SEV_SNP_FINISH_DATA_SIZE];
+       __u8 pad[6];

The LAUNCH_FINISH command received a new argument to disable VCEK (VCEK_DIS). Shouldn't we add that in this patch already?

Alex

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879

#98 lore raw

RFC PATCH v8 37/56 KVM: X86: Keep the NPT and RMP page level in sync

In reply to Michael Roth

From: Brijesh Singh <[email protected]>

When running an SEV-SNP VM, the sPA used to index the RMP entry is obtained through the NPT translation (gva->gpa->spa). The NPT page level is checked against the page level programmed in the RMP entry. If the page level does not match, then it will cause a nested page fault with the RMP bit set to indicate the RMP violation.

---
 arch/x86/include/asm/kvm-x86-ops.h |  1 +
 arch/x86/include/asm/kvm_host.h    |  2 ++
 arch/x86/kvm/mmu/mmu.c             |  9 ++++++
 arch/x86/kvm/svm/sev.c             | 51 ++++++++++++++++++++++++++++++
 arch/x86/kvm/svm/svm.c             |  2 ++
 arch/x86/kvm/svm/svm.h             |  1 +
 6 files changed, 66 insertions(+)
arch/x86/include/asm/kvm-x86-ops.h +1 -0
index e116405cbb5f..87a087ec3277 100644
@@ -135,6 +135,7 @@ KVM_X86_OP_OPTIONAL(alloc_apic_backing_page)
 KVM_X86_OP_OPTIONAL_RET0(fault_is_private);
 KVM_X86_OP_OPTIONAL_RET0(update_mem_attr)
 KVM_X86_OP_OPTIONAL(invalidate_restricted_mem)
+KVM_X86_OP_OPTIONAL(adjust_mapping_level)
 
 #undef KVM_X86_OP
 #undef KVM_X86_OP_OPTIONAL
arch/x86/include/asm/kvm_host.h +2 -0
index a9363a6f779d..456b42cb167b 100644
@@ -1731,6 +1731,8 @@ struct kvm_x86_ops {
 	unsigned long (*vcpu_get_apicv_inhibit_reasons)(struct kvm_vcpu *vcpu);
 
 	void *(*alloc_apic_backing_page)(struct kvm_vcpu *vcpu);
+
+	void (*adjust_mapping_level)(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int *level);
 };
 
 struct kvm_x86_nested_ops {
arch/x86/kvm/mmu/mmu.c +9 -0
index 360af0c9997e..d8e5254f314d 100644
@@ -3081,6 +3081,7 @@ static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn,
 
 out:
 	local_irq_restore(flags);
+
 	return level;
 }
 
@@ -3141,6 +3142,14 @@ void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault
 	fault->req_level = __kvm_mmu_max_mapping_level(vcpu->kvm, slot,
 						       fault->gfn, fault->max_level,
 						       fault->is_private);
+	if (kvm_slot_can_be_private(slot)) {
+		int req_level = fault->req_level;
+
+		static_call_cond(kvm_x86_adjust_mapping_level)(vcpu->kvm, fault->gfn, fault->pfn,
+							       &req_level);
+		fault->req_level = req_level;
+	}
+
 	if (fault->req_level == PG_LEVEL_4K || fault->huge_page_disallowed)
 		return;
 
arch/x86/kvm/svm/sev.c +51 -0

54 lines not on this page · raw message

arch/x86/kvm/svm/svm.c +2 -0
index 1061aaf66f0a..9eb750c8b04c 100644
@@ -4835,6 +4835,8 @@ static struct kvm_x86_ops svm_x86_ops __initdata = {
 	.vcpu_deliver_sipi_vector = svm_vcpu_deliver_sipi_vector,
 	.vcpu_get_apicv_inhibit_reasons = avic_vcpu_get_apicv_inhibit_reasons,
 	.alloc_apic_backing_page = svm_alloc_apic_backing_page,
+
+	.adjust_mapping_level = sev_adjust_mapping_level,
 };
 
 /*
arch/x86/kvm/svm/svm.h +1 -0
index 740969b57425..cbd4594f1cca 100644
@@ -706,6 +706,7 @@ void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector);
 void sev_es_prepare_switch_to_guest(struct sev_es_save_area *hostsa);
 void sev_es_unmap_ghcb(struct vcpu_svm *svm);
 struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu);
+void sev_adjust_mapping_level(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int *level);
 
 /* vmenter.S */
 
Signature · 1 line
2.25.1
#99 lore raw

RFC PATCH v8 38/56 KVM: x86: Define RMP page fault error bits for #NPF

In reply to Michael Roth

From: Brijesh Singh <[email protected]>

When SEV-SNP is enabled globally, the hardware places restrictions on all memory accesses based on the RMP entry, whether the hypervisor or a VM, performs the accesses. When hardware encounters an RMP access violation during a guest access, it will cause a #VMEXIT(NPF).

See APM2 section 16.36.10 for more details.

---
 arch/x86/include/asm/kvm_host.h | 8 ++++++++
 1 file changed, 8 insertions(+)
arch/x86/include/asm/kvm_host.h +8 -0
index 456b42cb167b..d2e1c109dde5 100644
@@ -253,9 +253,13 @@ enum x86_intercept_stage;
 #define PFERR_FETCH_BIT 4
 #define PFERR_PK_BIT 5
 #define PFERR_SGX_BIT 15
+#define PFERR_GUEST_RMP_BIT 31
 #define PFERR_GUEST_FINAL_BIT 32
 #define PFERR_GUEST_PAGE_BIT 33
 #define PFERR_IMPLICIT_ACCESS_BIT 48
+#define PFERR_GUEST_ENC_BIT 34
+#define PFERR_GUEST_SIZEM_BIT 35
+#define PFERR_GUEST_VMPL_BIT 36
 
 #define PFERR_PRESENT_MASK	BIT(PFERR_PRESENT_BIT)
 #define PFERR_WRITE_MASK	BIT(PFERR_WRITE_BIT)
@@ -267,6 +271,10 @@ enum x86_intercept_stage;
 #define PFERR_GUEST_FINAL_MASK	BIT_ULL(PFERR_GUEST_FINAL_BIT)
 #define PFERR_GUEST_PAGE_MASK	BIT_ULL(PFERR_GUEST_PAGE_BIT)
 #define PFERR_IMPLICIT_ACCESS	BIT_ULL(PFERR_IMPLICIT_ACCESS_BIT)
+#define PFERR_GUEST_RMP_MASK	BIT_ULL(PFERR_GUEST_RMP_BIT)
+#define PFERR_GUEST_ENC_MASK	BIT_ULL(PFERR_GUEST_ENC_BIT)
+#define PFERR_GUEST_SIZEM_MASK	BIT_ULL(PFERR_GUEST_SIZEM_BIT)
+#define PFERR_GUEST_VMPL_MASK	BIT_ULL(PFERR_GUEST_VMPL_BIT)
 
 #define PFERR_NESTED_GUEST_PAGE (PFERR_GUEST_PAGE_MASK |	\
 				 PFERR_WRITE_MASK |		\
Signature · 1 line
2.25.1
#100 lore raw

RFC PATCH v8 39/56 KVM: SVM: Add support to handle GHCB GPA register VMGEXIT

In reply to Michael Roth

From: Brijesh Singh <[email protected]>

SEV-SNP guests are required to perform a GHCB GPA registration. Before using a GHCB GPA for a vCPU the first time, a guest must register the vCPU GHCB GPA. If hypervisor can work with the guest requested GPA then it must respond back with the same GPA otherwise return -1.

On VMEXIT, Verify that GHCB GPA matches with the registered value. If a mismatch is detected then abort the guest.

---
 arch/x86/include/asm/sev-common.h |  8 ++++++++
 arch/x86/kvm/svm/sev.c            | 27 +++++++++++++++++++++++++++
 arch/x86/kvm/svm/svm.h            |  7 +++++++
 3 files changed, 42 insertions(+)
arch/x86/include/asm/sev-common.h +8 -0
index 539de6b93420..0a9055cdfae2 100644
@@ -59,6 +59,14 @@
 #define GHCB_MSR_AP_RESET_HOLD_RESULT_POS	12
 #define GHCB_MSR_AP_RESET_HOLD_RESULT_MASK	GENMASK_ULL(51, 0)
 
+/* Preferred GHCB GPA Request */
+#define GHCB_MSR_PREF_GPA_REQ		0x010
+#define GHCB_MSR_GPA_VALUE_POS		12
+#define GHCB_MSR_GPA_VALUE_MASK		GENMASK_ULL(51, 0)
+
+#define GHCB_MSR_PREF_GPA_RESP		0x011
+#define GHCB_MSR_PREF_GPA_NONE		0xfffffffffffff
+
 /* GHCB GPA Register */
 #define GHCB_MSR_REG_GPA_REQ		0x012
 #define GHCB_MSR_REG_GPA_REQ_VAL(v)			\
arch/x86/kvm/svm/sev.c +27 -0
index e8740c35be39..2613311f4fcc 100644
@@ -3424,6 +3424,27 @@ static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
 				  GHCB_MSR_INFO_MASK, GHCB_MSR_INFO_POS);
 		break;
 	}
+	case GHCB_MSR_PREF_GPA_REQ: {
+		set_ghcb_msr_bits(svm, GHCB_MSR_PREF_GPA_NONE, GHCB_MSR_GPA_VALUE_MASK,
+				  GHCB_MSR_GPA_VALUE_POS);
+		set_ghcb_msr_bits(svm, GHCB_MSR_PREF_GPA_RESP, GHCB_MSR_INFO_MASK,
+				  GHCB_MSR_INFO_POS);
+		break;
+	}
+	case GHCB_MSR_REG_GPA_REQ: {
+		u64 gfn;
+
+		gfn = get_ghcb_msr_bits(svm, GHCB_MSR_GPA_VALUE_MASK,
+					GHCB_MSR_GPA_VALUE_POS);
+
+		svm->sev_es.ghcb_registered_gpa = gfn_to_gpa(gfn);
+
+		set_ghcb_msr_bits(svm, gfn, GHCB_MSR_GPA_VALUE_MASK,
+				  GHCB_MSR_GPA_VALUE_POS);
+		set_ghcb_msr_bits(svm, GHCB_MSR_REG_GPA_RESP, GHCB_MSR_INFO_MASK,
+				  GHCB_MSR_INFO_POS);
+		break;
+	}
 	case GHCB_MSR_TERM_REQ: {
 		u64 reason_set, reason_code;
 
@@ -3490,6 +3511,12 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
 
 	exit_code = ghcb_get_sw_exit_code(ghcb);
 
+	/* SEV-SNP guest requires that the GHCB GPA must be registered */
+	if (sev_snp_guest(svm->vcpu.kvm) && !ghcb_gpa_is_registered(svm, ghcb_gpa)) {
+		vcpu_unimpl(&svm->vcpu, "vmgexit: GHCB GPA [%#llx] is not registered.\n", ghcb_gpa);
+		return -EINVAL;
+	}
+
 	ret = sev_es_validate_vmgexit(svm);
 	if (ret)
 		return ret;
arch/x86/kvm/svm/svm.h +7 -0
index cbd4594f1cca..0c655a4d32d5 100644
@@ -204,6 +204,8 @@ struct vcpu_sev_es_state {
 	u32 ghcb_sa_len;
 	bool ghcb_sa_sync;
 	bool ghcb_sa_free;
+
+	u64 ghcb_registered_gpa;
 };
 
 struct vcpu_svm {
@@ -336,6 +338,11 @@ static inline bool sev_snp_guest(struct kvm *kvm)
 	return sev_es_guest(kvm) && sev->snp_active;
 }
 
+static inline bool ghcb_gpa_is_registered(struct vcpu_svm *svm, u64 val)
+{
+	return svm->sev_es.ghcb_registered_gpa == val;
+}
+
 static inline void vmcb_mark_all_dirty(struct vmcb *vmcb)
 {
 	vmcb->control.clean = 0;
Signature · 1 line
2.25.1
#101 lore raw

RFC PATCH v8 40/56 KVM: SVM: Add KVM_EXIT_VMGEXIT

In reply to Michael Roth

For private memslots, GHCB page state change requests will be forwarded to userspace for processing. Define a new KVM_EXIT_VMGEXIT for exits of this type.

---
 include/uapi/linux/kvm.h | 6 ++++++
 1 file changed, 6 insertions(+)
include/uapi/linux/kvm.h +6 -0
index 2bab08a5b5d7..6e684bf5f723 100644
@@ -279,6 +279,7 @@ struct kvm_xen_exit {
 #define KVM_EXIT_RISCV_CSR        36
 #define KVM_EXIT_NOTIFY           37
 #define KVM_EXIT_MEMORY_FAULT     38
+#define KVM_EXIT_VMGEXIT          50
 
 /* For KVM_EXIT_INTERNAL_ERROR */
 /* Emulate instruction failed. */
@@ -527,6 +528,11 @@ struct kvm_run {
 			__u64 gpa;
 			__u64 size;
 		} memory;
+		/* KVM_EXIT_VMGEXIT */
+		struct {
+			__u64 ghcb_msr; /* GHCB MSR contents */
+			__u8 error; /* user -> kernel */
+		} vmgexit;
 		/* Fix the size of the union. */
 		char padding[256];
 	};
Signature · 1 line
2.25.1
#102 lore raw

RFC PATCH v8 41/56 KVM: SVM: Add support to handle MSR based Page State Change VMGEXIT

In reply to Michael Roth

From: Brijesh Singh <[email protected]>

SEV-SNP VMs can ask the hypervisor to change the page state in the RMP table to be private or shared using the Page State Change MSR protocol as defined in the GHCB specification.

Forward these requests to userspace via KVM_EXIT_VMGEXIT so the VMM can issue the KVM ioctls to update the page state accordingly.

---
 arch/x86/include/asm/sev-common.h |  9 ++++++++
 arch/x86/kvm/svm/sev.c            | 25 +++++++++++++++++++++++
 arch/x86/kvm/trace.h              | 34 +++++++++++++++++++++++++++++++
 arch/x86/kvm/x86.c                |  1 +
 4 files changed, 69 insertions(+)
arch/x86/include/asm/sev-common.h +9 -0
index 0a9055cdfae2..ee38f7408470 100644
@@ -93,6 +93,10 @@ enum psc_op {
 };
 
 #define GHCB_MSR_PSC_REQ		0x014
+#define GHCB_MSR_PSC_GFN_POS		12
+#define GHCB_MSR_PSC_GFN_MASK		GENMASK_ULL(39, 0)
+#define GHCB_MSR_PSC_OP_POS		52
+#define GHCB_MSR_PSC_OP_MASK		0xf
 #define GHCB_MSR_PSC_REQ_GFN(gfn, op)			\
 	/* GHCBData[55:52] */				\
 	(((u64)((op) & 0xf) << 52) |			\
@@ -102,6 +106,11 @@ enum psc_op {
 	GHCB_MSR_PSC_REQ)
 
 #define GHCB_MSR_PSC_RESP		0x015
+#define GHCB_MSR_PSC_ERROR_POS		32
+#define GHCB_MSR_PSC_ERROR_MASK		GENMASK_ULL(31, 0)
+#define GHCB_MSR_PSC_ERROR		GENMASK_ULL(31, 0)
+#define GHCB_MSR_PSC_RSVD_POS		12
+#define GHCB_MSR_PSC_RSVD_MASK		GENMASK_ULL(19, 0)
 #define GHCB_MSR_PSC_RESP_VAL(val)			\
 	/* GHCBData[63:32] */				\
 	(((u64)(val) & GENMASK_ULL(63, 32)) >> 32)
arch/x86/kvm/svm/sev.c +25 -0
index 2613311f4fcc..a1a2686dde7b 100644
@@ -30,6 +30,7 @@
 #include "svm_ops.h"
 #include "cpuid.h"
 #include "trace.h"
+#include "mmu.h"
 
 #ifndef CONFIG_KVM_AMD_SEV
 /*
@@ -3345,6 +3346,23 @@ static void set_ghcb_msr(struct vcpu_svm *svm, u64 value)
 	svm->vmcb->control.ghcb_gpa = value;
 }
 
+/*
+ * TODO: need to get the value set by userspace in vcpu->run->vmgexit.ghcb_msr
+ * and process that here accordingly.
+ */
+static int snp_complete_psc_msr_protocol(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_svm *svm = to_svm(vcpu);
+
+	set_ghcb_msr_bits(svm, 0,
+			  GHCB_MSR_PSC_ERROR_MASK, GHCB_MSR_PSC_ERROR_POS);
+
+	set_ghcb_msr_bits(svm, 0, GHCB_MSR_PSC_RSVD_MASK, GHCB_MSR_PSC_RSVD_POS);
+	set_ghcb_msr_bits(svm, GHCB_MSR_PSC_RESP, GHCB_MSR_INFO_MASK, GHCB_MSR_INFO_POS);
+
+	return 1; /* resume */
+}
+
 static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
 {
 	struct vmcb_control_area *control = &svm->vmcb->control;
@@ -3445,6 +3463,13 @@ static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
 				  GHCB_MSR_INFO_POS);
 		break;
 	}
+	case GHCB_MSR_PSC_REQ:
+		vcpu->run->exit_reason = KVM_EXIT_VMGEXIT;
+		vcpu->run->vmgexit.ghcb_msr = control->ghcb_gpa;
+		vcpu->arch.complete_userspace_io = snp_complete_psc_msr_protocol;
+
+		ret = -1;
+		break;
 	case GHCB_MSR_TERM_REQ: {
 		u64 reason_set, reason_code;
 
arch/x86/kvm/trace.h +34 -0
index 83843379813e..65861d2d086c 100644
@@ -7,6 +7,7 @@
 #include <asm/svm.h>
 #include <asm/clocksource.h>
 #include <asm/pvclock-abi.h>
+#include <asm/sev-common.h>
 
 #undef TRACE_SYSTEM
 #define TRACE_SYSTEM kvm
@@ -1831,6 +1832,39 @@ TRACE_EVENT(kvm_vmgexit_msr_protocol_exit,
 		  __entry->vcpu_id, __entry->ghcb_gpa, __entry->result)
 );
 
+/*
+ * Tracepoint for the SEV-SNP page state change processing
+ */
+#define psc_operation					\
+	{SNP_PAGE_STATE_PRIVATE, "private"},		\
+	{SNP_PAGE_STATE_SHARED,  "shared"}		\
+
+TRACE_EVENT(kvm_snp_psc,
+	TP_PROTO(unsigned int vcpu_id, u64 pfn, u64 gpa, u8 op, int level),
+	TP_ARGS(vcpu_id, pfn, gpa, op, level),
+
+	TP_STRUCT__entry(
+		__field(int, vcpu_id)
+		__field(u64, pfn)
+		__field(u64, gpa)
+		__field(u8, op)
+		__field(int, level)
+	),
+
+	TP_fast_assign(
+		__entry->vcpu_id = vcpu_id;
+		__entry->pfn = pfn;
+		__entry->gpa = gpa;
+		__entry->op = op;
+		__entry->level = level;
+	),
+
+	TP_printk("vcpu %u, pfn %llx, gpa %llx, op %s, level %d",
+		  __entry->vcpu_id, __entry->pfn, __entry->gpa,
+		  __print_symbolic(__entry->op, psc_operation),
+		  __entry->level)
+);
+
 #endif /* _TRACE_KVM_H */
 
 #undef TRACE_INCLUDE_PATH
arch/x86/kvm/x86.c +1 -0
index 268c3d16894d..0154fc7a28c1 100644
@@ -13515,6 +13515,7 @@ EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
+EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_snp_psc);
 
 static int __init kvm_x86_init(void)
 {
Signature · 1 line
2.25.1
#103 lore raw

Re: [PATCH RFC v8 41/56] KVM: SVM: Add support to handle MSR based Page State Change VMGEXIT

Quoted 9 lines · On Mon, 20 Feb 2023 12:38:32 -0600 Michael Roth <[email protected]> wrote:

From: Brijesh Singh <[email protected]>

SEV-SNP VMs can ask the hypervisor to change the page state in the RMP table to be private or shared using the Page State Change MSR protocol as defined in the GHCB specification.

Forward these requests to userspace via KVM_EXIT_VMGEXIT so the VMM can issue the KVM ioctls to update the page state accordingly.

It would be better to describe the design purpose. Like, why should the page state change VMGEIXT be forwarded to the userspace instead of being handled in the kernel.

Quoted 152 lines
---
 arch/x86/include/asm/sev-common.h |  9 ++++++++
 arch/x86/kvm/svm/sev.c            | 25 +++++++++++++++++++++++
 arch/x86/kvm/trace.h              | 34 +++++++++++++++++++++++++++++++
 arch/x86/kvm/x86.c                |  1 +
 4 files changed, 69 insertions(+)
arch/x86/include/asm/sev-common.h +9 -0
index 0a9055cdfae2..ee38f7408470 100644
@@ -93,6 +93,10 @@ enum psc_op {
 };
 
 #define GHCB_MSR_PSC_REQ		0x014
+#define GHCB_MSR_PSC_GFN_POS		12
+#define GHCB_MSR_PSC_GFN_MASK		GENMASK_ULL(39, 0)
+#define GHCB_MSR_PSC_OP_POS		52
+#define GHCB_MSR_PSC_OP_MASK		0xf
 #define GHCB_MSR_PSC_REQ_GFN(gfn, op)			\
 	/* GHCBData[55:52] */				\
 	(((u64)((op) & 0xf) << 52) |			\
@@ -102,6 +106,11 @@ enum psc_op {
 	GHCB_MSR_PSC_REQ)
 
 #define GHCB_MSR_PSC_RESP		0x015
+#define GHCB_MSR_PSC_ERROR_POS		32
+#define GHCB_MSR_PSC_ERROR_MASK		GENMASK_ULL(31, 0)
+#define GHCB_MSR_PSC_ERROR		GENMASK_ULL(31, 0)
+#define GHCB_MSR_PSC_RSVD_POS		12
+#define GHCB_MSR_PSC_RSVD_MASK		GENMASK_ULL(19, 0)
 #define GHCB_MSR_PSC_RESP_VAL(val)			\
 	/* GHCBData[63:32] */				\
 	(((u64)(val) & GENMASK_ULL(63, 32)) >> 32)
arch/x86/kvm/svm/sev.c +25 -0
index 2613311f4fcc..a1a2686dde7b 100644
@@ -30,6 +30,7 @@
 #include "svm_ops.h"
 #include "cpuid.h"
 #include "trace.h"
+#include "mmu.h"
 
 #ifndef CONFIG_KVM_AMD_SEV
 /*
@@ -3345,6 +3346,23 @@ static void set_ghcb_msr(struct vcpu_svm *svm, u64 value)
 	svm->vmcb->control.ghcb_gpa = value;
 }
 
+/*
+ * TODO: need to get the value set by userspace in vcpu->run->vmgexit.ghcb_msr
+ * and process that here accordingly.
+ */
+static int snp_complete_psc_msr_protocol(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_svm *svm = to_svm(vcpu);
+
+	set_ghcb_msr_bits(svm, 0,
+			  GHCB_MSR_PSC_ERROR_MASK, GHCB_MSR_PSC_ERROR_POS);
+
+	set_ghcb_msr_bits(svm, 0, GHCB_MSR_PSC_RSVD_MASK, GHCB_MSR_PSC_RSVD_POS);
+	set_ghcb_msr_bits(svm, GHCB_MSR_PSC_RESP, GHCB_MSR_INFO_MASK, GHCB_MSR_INFO_POS);
+
+	return 1; /* resume */
+}
+
 static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
 {
 	struct vmcb_control_area *control = &svm->vmcb->control;
@@ -3445,6 +3463,13 @@ static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
 				  GHCB_MSR_INFO_POS);
 		break;
 	}
+	case GHCB_MSR_PSC_REQ:
+		vcpu->run->exit_reason = KVM_EXIT_VMGEXIT;
+		vcpu->run->vmgexit.ghcb_msr = control->ghcb_gpa;
+		vcpu->arch.complete_userspace_io = snp_complete_psc_msr_protocol;
+
+		ret = -1;
+		break;
 	case GHCB_MSR_TERM_REQ: {
 		u64 reason_set, reason_code;
 
arch/x86/kvm/trace.h +34 -0
index 83843379813e..65861d2d086c 100644
@@ -7,6 +7,7 @@
 #include <asm/svm.h>
 #include <asm/clocksource.h>
 #include <asm/pvclock-abi.h>
+#include <asm/sev-common.h>
 
 #undef TRACE_SYSTEM
 #define TRACE_SYSTEM kvm
@@ -1831,6 +1832,39 @@ TRACE_EVENT(kvm_vmgexit_msr_protocol_exit,
 		  __entry->vcpu_id, __entry->ghcb_gpa, __entry->result)
 );
 
+/*
+ * Tracepoint for the SEV-SNP page state change processing
+ */
+#define psc_operation					\
+	{SNP_PAGE_STATE_PRIVATE, "private"},		\
+	{SNP_PAGE_STATE_SHARED,  "shared"}		\
+
+TRACE_EVENT(kvm_snp_psc,
+	TP_PROTO(unsigned int vcpu_id, u64 pfn, u64 gpa, u8 op, int level),
+	TP_ARGS(vcpu_id, pfn, gpa, op, level),
+
+	TP_STRUCT__entry(
+		__field(int, vcpu_id)
+		__field(u64, pfn)
+		__field(u64, gpa)
+		__field(u8, op)
+		__field(int, level)
+	),
+
+	TP_fast_assign(
+		__entry->vcpu_id = vcpu_id;
+		__entry->pfn = pfn;
+		__entry->gpa = gpa;
+		__entry->op = op;
+		__entry->level = level;
+	),
+
+	TP_printk("vcpu %u, pfn %llx, gpa %llx, op %s, level %d",
+		  __entry->vcpu_id, __entry->pfn, __entry->gpa,
+		  __print_symbolic(__entry->op, psc_operation),
+		  __entry->level)
+);
+
 #endif /* _TRACE_KVM_H */
 
 #undef TRACE_INCLUDE_PATH
arch/x86/kvm/x86.c +1 -0
index 268c3d16894d..0154fc7a28c1 100644
@@ -13515,6 +13515,7 @@ EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
+EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_snp_psc);
 
 static int __init kvm_x86_init(void)
 {
#104 lore raw

RFC PATCH v8 42/56 KVM: SVM: Add support to handle Page State Change VMGEXIT

In reply to Michael Roth

From: Brijesh Singh <[email protected]>

SEV-SNP VMs can ask the hypervisor to change the page state in the RMP table to be private or shared using the Page State Change NAE event as defined in the GHCB specification version 2.

Forward these requests to userspace as KVM_EXIT_VMGEXITs, similar to how it is done for requests that don't use a GHCB page.

---
 arch/x86/include/asm/sev-common.h |  7 +++++++
 arch/x86/kvm/svm/sev.c            | 20 ++++++++++++++++++++
 2 files changed, 27 insertions(+)
arch/x86/include/asm/sev-common.h +7 -0
index ee38f7408470..1b111cde8c82 100644
@@ -130,6 +130,13 @@ enum psc_op {
 /* SNP Page State Change NAE event */
 #define VMGEXIT_PSC_MAX_ENTRY		253
 
+/* The page state change hdr structure in not valid */
+#define PSC_INVALID_HDR			1
+/* The hdr.cur_entry or hdr.end_entry is not valid */
+#define PSC_INVALID_ENTRY		2
+/* Page state change encountered undefined error */
+#define PSC_UNDEF_ERR			3
+
 struct psc_hdr {
 	u16 cur_entry;
 	u16 end_entry;
arch/x86/kvm/svm/sev.c +20 -0
index a1a2686dde7b..102966c43e28 100644
@@ -3152,6 +3152,7 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm)
 	case SVM_VMGEXIT_AP_JUMP_TABLE:
 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
 	case SVM_VMGEXIT_HV_FEATURES:
+	case SVM_VMGEXIT_PSC:
 		break;
 	default:
 		reason = GHCB_ERR_INVALID_EVENT;
@@ -3363,6 +3364,19 @@ static int snp_complete_psc_msr_protocol(struct kvm_vcpu *vcpu)
 	return 1; /* resume */
 }
 
+/*
+ * TODO: need to process the GHCB contents and report the proper error code
+ * instead of assuming success.
+ */
+static int snp_complete_psc(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_svm *svm = to_svm(vcpu);
+
+	ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, 0);
+
+	return 1;
+}
+
 static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
 {
 	struct vmcb_control_area *control = &svm->vmcb->control;
@@ -3606,6 +3620,12 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
 		ret = 1;
 		break;
 	}
+	case SVM_VMGEXIT_PSC:
+		/* Let userspace handling allocating/deallocating backing pages. */
+		vcpu->run->exit_reason = KVM_EXIT_VMGEXIT;
+		vcpu->run->vmgexit.ghcb_msr = ghcb_gpa;
+		vcpu->arch.complete_userspace_io = snp_complete_psc;
+		break;
 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
 		vcpu_unimpl(vcpu,
 			    "vmgexit: unsupported event - exit_info_1=%#llx, exit_info_2=%#llx\n",
Signature · 1 line
2.25.1
#105 lore raw

RFC PATCH v8 43/56 KVM: x86: Export the kvm_zap_gfn_range() for the SNP use

In reply to Michael Roth

From: Brijesh Singh <[email protected]>

While resolving the RMP page fault, there may be cases where the page level between the RMP entry and TDP does not match and the 2M RMP entry must be split into 4K RMP entries. Or a 2M TDP page need to be broken into multiple of 4K pages.

To keep the RMP and TDP page level in sync, zap the gfn range after splitting the pages in the RMP entry. The zap should force the TDP to gets rebuilt with the new page level.

---
 arch/x86/include/asm/kvm_host.h | 2 ++
 arch/x86/kvm/mmu.h              | 2 --
 arch/x86/kvm/mmu/mmu.c          | 1 +
 3 files changed, 3 insertions(+), 2 deletions(-)
arch/x86/include/asm/kvm_host.h +2 -0
index d2e1c109dde5..28b01cc7f64d 100644
@@ -1845,6 +1845,8 @@ void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
 void kvm_mmu_zap_all(struct kvm *kvm);
 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen);
 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long kvm_nr_mmu_pages);
+void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end);
+
 
 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3);
 
arch/x86/kvm/mmu.h +0 -2
index 168c46fd8dd1..0afaf8ff2bb8 100644
@@ -211,8 +211,6 @@ static inline u8 permission_fault(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
 	return -(u32)fault & errcode;
 }
 
-void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end);
-
 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu);
 
 int kvm_mmu_post_init_vm(struct kvm *kvm);
arch/x86/kvm/mmu/mmu.c +1 -0
index d8e5254f314d..d7847af3e177 100644
@@ -6615,6 +6615,7 @@ static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
 
 	return need_tlb_flush;
 }
+EXPORT_SYMBOL_GPL(kvm_zap_gfn_range);
 
 static void kvm_rmap_zap_collapsible_sptes(struct kvm *kvm,
 					   const struct kvm_memory_slot *slot)
Signature · 1 line
2.25.1
#106 lore raw

RFC PATCH v8 44/56 KVM: SVM: Add support to handle the RMP nested page fault

In reply to Michael Roth

From: Brijesh Singh <[email protected]>

When SEV-SNP is enabled in the guest, the hardware places restrictions on all memory accesses based on the contents of the RMP table. When hardware encounters RMP check failure caused by the guest memory access it raises the #NPF. The error code contains additional information on the access type. See the APM volume 2 for additional information.

Page state changes are handled by userspace, so if an RMP fault is triggered as a result of an RMP NPT fault, exit to userspace just like with explicit page-state change requests.

RMP NPT faults can also occur if the guest pvalidates a 2M page as 4K, in which case the RMP entries need to be PSMASH'd. Handle this case immediately in the kernel.

---
 arch/x86/kvm/svm/sev.c | 84 ++++++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/svm/svm.c | 21 +++++++++--
 arch/x86/kvm/svm/svm.h |  1 +
 3 files changed, 102 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/sev.c +84 -0
index 102966c43e28..197b1f904567 100644
@@ -3347,6 +3347,13 @@ static void set_ghcb_msr(struct vcpu_svm *svm, u64 value)
 	svm->vmcb->control.ghcb_gpa = value;
 }
 
+static int snp_rmptable_psmash(struct kvm *kvm, kvm_pfn_t pfn)
+{
+	pfn = pfn & ~(KVM_PAGES_PER_HPAGE(PG_LEVEL_2M) - 1);
+
+	return psmash(pfn);
+}
+
 /*
  * TODO: need to get the value set by userspace in vcpu->run->vmgexit.ghcb_msr
  * and process that here accordingly.
@@ -3872,3 +3879,80 @@ void sev_adjust_mapping_level(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int *le
 	pr_debug("%s: GFN: 0x%llx, PFN: 0x%llx, level: %d, rmp_level: %d, level_orig: %d, assigned: %d\n",
 		 __func__, gfn, pfn, *level, rmp_level, level_orig, assigned);
 }
+
+void handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code)
+{
+	int order, rmp_level, assigned, ret;
+	struct kvm_memory_slot *slot;
+	struct kvm *kvm = vcpu->kvm;
+	kvm_pfn_t pfn;
+	gfn_t gfn;
+
+	/*
+	 * Private memslots punt handling of implicit page state changes to
+	 * userspace, so the only RMP faults expected here for
+	 * PFERR_GUEST_SIZEM_MASK. Anything else suggests that the RMP table has
+	 * gotten out of sync with the private memslot.
+	 *
+	 * TODO: However, this case has also been noticed when an access occurs
+	 * to an NPT mapping that has just been split/PSMASHED, in which case
+	 * PFERR_GUEST_SIZEM_MASK might not be set. In those cases it should be
+	 * safe to ignore and let the guest retry, but log these just in case
+	 * for now.
+	 */
+	if (!(error_code & PFERR_GUEST_SIZEM_MASK)) {
+		pr_warn_ratelimited("Unexpected RMP fault for GPA 0x%llx, error_code 0x%llx",
+				    gpa, error_code);
+		return;
+	}
+
+	gfn = gpa >> PAGE_SHIFT;
+
+	/*
+	 * Only RMPADJUST/PVALIDATE should cause PFERR_GUEST_SIZEM.
+	 *
+	 * For PVALIDATE, this should only happen if a guest PVALIDATEs a 4K GFN
+	 * that is backed by a huge page in the host whose RMP entry has the
+	 * hugepage/assigned bits set. With UPM, that should only ever happen
+	 * for private pages.
+	 *
+	 * For RMPADJUST, this assumption might not hold, in which case handling
+	 * for obtaining the PFN from HVA-backed memory may be needed. For now,
+	 * just print warnings.
+	 */
+	if (!kvm_mem_is_private(kvm, gfn)) {
+		pr_warn_ratelimited("Unexpected RMP fault, size-mismatch for non-private GPA 0x%llx\n",
+				    gpa);
+		return;
+	}
+
+	slot = gfn_to_memslot(kvm, gfn);
+	if (!kvm_slot_can_be_private(slot)) {
+		pr_warn_ratelimited("Unexpected RMP fault, non-private slot for GPA 0x%llx\n",
+				    gpa);
+		return;
+	}
+
+	ret = kvm_restrictedmem_get_pfn(slot, gfn, &pfn, &order);
+	if (ret) {
+		pr_warn_ratelimited("Unexpected RMP fault, no private backing page for GPA 0x%llx\n",
+				    gpa);
+		return;
+	}
+
+	assigned = snp_lookup_rmpentry(pfn, &rmp_level);
+	if (assigned != 1) {
+		pr_warn_ratelimited("Unexpected RMP fault, no assigned RMP entry for GPA 0x%llx\n",
+				    gpa);
+		goto out;
+	}
+
+	ret = snp_rmptable_psmash(kvm, pfn);
+	if (ret)
+		pr_err_ratelimited("Unable to split RMP entries for GPA 0x%llx PFN 0x%llx ret %d\n",
+				   gpa, pfn, ret);
+
+out:
+	kvm_zap_gfn_range(kvm, gfn, gfn + PTRS_PER_PMD);
+	put_page(pfn_to_page(pfn));
+}
arch/x86/kvm/svm/svm.c +17 -4
index 9eb750c8b04c..f9ab4bf6d245 100644
@@ -1976,15 +1976,28 @@ static int pf_interception(struct kvm_vcpu *vcpu)
 static int npf_interception(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_svm *svm = to_svm(vcpu);
+	int rc;
 
 	u64 fault_address = svm->vmcb->control.exit_info_2;
 	u64 error_code = svm->vmcb->control.exit_info_1;
 
 	trace_kvm_page_fault(vcpu, fault_address, error_code);
-	return kvm_mmu_page_fault(vcpu, fault_address, error_code,
-			static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
-			svm->vmcb->control.insn_bytes : NULL,
-			svm->vmcb->control.insn_len);
+	rc = kvm_mmu_page_fault(vcpu, fault_address, error_code,
+				static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
+				svm->vmcb->control.insn_bytes : NULL,
+				svm->vmcb->control.insn_len);
+
+	/*
+	 * rc == 0 indicates a userspace exit is needed to handle page
+	 * transitions, so do that first before updating the RMP table.
+	 */
+	if (error_code & PFERR_GUEST_RMP_MASK) {
+		if (rc == 0)
+			return rc;
+		handle_rmp_page_fault(vcpu, fault_address, error_code);
+	}
+
+	return rc;
 }
 
 static int db_interception(struct kvm_vcpu *vcpu)
arch/x86/kvm/svm/svm.h +1 -0
index 0c655a4d32d5..13b00233b315 100644
@@ -714,6 +714,7 @@ void sev_es_prepare_switch_to_guest(struct sev_es_save_area *hostsa);
 void sev_es_unmap_ghcb(struct vcpu_svm *svm);
 struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu);
 void sev_adjust_mapping_level(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int *level);
+void handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code);
 
 /* vmenter.S */
 
Signature · 1 line
2.25.1
#107 lore raw

Re: [PATCH RFC v8 44/56] KVM: SVM: Add support to handle the RMP nested page fault

Quoted 49 lines · On Mon, 20 Feb 2023 12:38:35 -0600 Michael Roth <[email protected]> wrote:

From: Brijesh Singh <[email protected]>

When SEV-SNP is enabled in the guest, the hardware places restrictions on all memory accesses based on the contents of the RMP table. When hardware encounters RMP check failure caused by the guest memory access it raises the #NPF. The error code contains additional information on the access type. See the APM volume 2 for additional information.

Page state changes are handled by userspace, so if an RMP fault is triggered as a result of an RMP NPT fault, exit to userspace just like with explicit page-state change requests.

RMP NPT faults can also occur if the guest pvalidates a 2M page as 4K, in which case the RMP entries need to be PSMASH'd. Handle this case immediately in the kernel.

---
 arch/x86/kvm/svm/sev.c | 84 ++++++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/svm/svm.c | 21 +++++++++--
 arch/x86/kvm/svm/svm.h |  1 +
 3 files changed, 102 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/sev.c +8 -0
index 102966c43e28..197b1f904567 100644
@@ -3347,6 +3347,13 @@ static void set_ghcb_msr(struct vcpu_svm *svm, u64 value)
 	svm->vmcb->control.ghcb_gpa = value;
 }
 
+static int snp_rmptable_psmash(struct kvm *kvm, kvm_pfn_t pfn)
+{
+	pfn = pfn & ~(KVM_PAGES_PER_HPAGE(PG_LEVEL_2M) - 1);
+
+	return psmash(pfn);
+}
+
 /*
  * TODO: need to get the value set by userspace in vcpu->run->vmgexit.ghcb_msr
  * and process that here accordingly.
@@ -3872,3 +3879,80 @@ void sev_adjust_mapping_level(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int *le
 	pr_debug("%s: GFN: 0x%llx, PFN: 0x%llx, level: %d, rmp_level: %d, level_orig: %d, assigned: %d\n",
 		 __func__, gfn, pfn, *level, rmp_level, level_orig, assigned);
 }
+

arch/x86/kvm/svm/sev.c void sev_adjust_mapping_level(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int *le · line 3892

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+void handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code)
+{
+	int order, rmp_level, assigned, ret;
+	struct kvm_memory_slot *slot;
+	struct kvm *kvm = vcpu->kvm;
+	kvm_pfn_t pfn;
+	gfn_t gfn;
+
+	/*
+	 * Private memslots punt handling of implicit page state changes to

^put

Quoted 115 lines
arch/x86/kvm/svm/sev.c +66 -0
+	 * userspace, so the only RMP faults expected here for
+	 * PFERR_GUEST_SIZEM_MASK. Anything else suggests that the RMP table has
+	 * gotten out of sync with the private memslot.
+	 *
+	 * TODO: However, this case has also been noticed when an access occurs
+	 * to an NPT mapping that has just been split/PSMASHED, in which case
+	 * PFERR_GUEST_SIZEM_MASK might not be set. In those cases it should be
+	 * safe to ignore and let the guest retry, but log these just in case
+	 * for now.
+	 */
+	if (!(error_code & PFERR_GUEST_SIZEM_MASK)) {
+		pr_warn_ratelimited("Unexpected RMP fault for GPA 0x%llx, error_code 0x%llx",
+				    gpa, error_code);
+		return;
+	}
+
+	gfn = gpa >> PAGE_SHIFT;
+
+	/*
+	 * Only RMPADJUST/PVALIDATE should cause PFERR_GUEST_SIZEM.
+	 *
+	 * For PVALIDATE, this should only happen if a guest PVALIDATEs a 4K GFN
+	 * that is backed by a huge page in the host whose RMP entry has the
+	 * hugepage/assigned bits set. With UPM, that should only ever happen
+	 * for private pages.
+	 *
+	 * For RMPADJUST, this assumption might not hold, in which case handling
+	 * for obtaining the PFN from HVA-backed memory may be needed. For now,
+	 * just print warnings.
+	 */
+	if (!kvm_mem_is_private(kvm, gfn)) {
+		pr_warn_ratelimited("Unexpected RMP fault, size-mismatch for non-private GPA 0x%llx\n",
+				    gpa);
+		return;
+	}
+
+	slot = gfn_to_memslot(kvm, gfn);
+	if (!kvm_slot_can_be_private(slot)) {
+		pr_warn_ratelimited("Unexpected RMP fault, non-private slot for GPA 0x%llx\n",
+				    gpa);
+		return;
+	}
+
+	ret = kvm_restrictedmem_get_pfn(slot, gfn, &pfn, &order);
+	if (ret) {
+		pr_warn_ratelimited("Unexpected RMP fault, no private backing page for GPA 0x%llx\n",
+				    gpa);
+		return;
+	}
+
+	assigned = snp_lookup_rmpentry(pfn, &rmp_level);
+	if (assigned != 1) {
+		pr_warn_ratelimited("Unexpected RMP fault, no assigned RMP entry for GPA 0x%llx\n",
+				    gpa);
+		goto out;
+	}
+
+	ret = snp_rmptable_psmash(kvm, pfn);
+	if (ret)
+		pr_err_ratelimited("Unable to split RMP entries for GPA 0x%llx PFN 0x%llx ret %d\n",
+				   gpa, pfn, ret);
+
+out:
+	kvm_zap_gfn_range(kvm, gfn, gfn + PTRS_PER_PMD);
+	put_page(pfn_to_page(pfn));
+}
arch/x86/kvm/svm/svm.c +17 -4
index 9eb750c8b04c..f9ab4bf6d245 100644
@@ -1976,15 +1976,28 @@ static int pf_interception(struct kvm_vcpu *vcpu)
 static int npf_interception(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_svm *svm = to_svm(vcpu);
+	int rc;
 
 	u64 fault_address = svm->vmcb->control.exit_info_2;
 	u64 error_code = svm->vmcb->control.exit_info_1;
 
 	trace_kvm_page_fault(vcpu, fault_address, error_code);
-	return kvm_mmu_page_fault(vcpu, fault_address, error_code,
-			static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
-			svm->vmcb->control.insn_bytes : NULL,
-			svm->vmcb->control.insn_len);
+	rc = kvm_mmu_page_fault(vcpu, fault_address, error_code,
+				static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
+				svm->vmcb->control.insn_bytes : NULL,
+				svm->vmcb->control.insn_len);
+
+	/*
+	 * rc == 0 indicates a userspace exit is needed to handle page
+	 * transitions, so do that first before updating the RMP table.
+	 */
+	if (error_code & PFERR_GUEST_RMP_MASK) {
+		if (rc == 0)
+			return rc;
+		handle_rmp_page_fault(vcpu, fault_address, error_code);
+	}
+
+	return rc;
 }
 
 static int db_interception(struct kvm_vcpu *vcpu)
arch/x86/kvm/svm/svm.h +1 -0
index 0c655a4d32d5..13b00233b315 100644
@@ -714,6 +714,7 @@ void sev_es_prepare_switch_to_guest(struct sev_es_save_area *hostsa);
 void sev_es_unmap_ghcb(struct vcpu_svm *svm);
 struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu);
 void sev_adjust_mapping_level(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int *level);
+void handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code);
 
 /* vmenter.S */
 
#108 lore raw

RFC PATCH v8 45/56 KVM: SVM: Provide support for SNP_GUEST_REQUEST NAE event

In reply to Michael Roth

From: Brijesh Singh <[email protected]>

Version 2 of GHCB specification added the support for two SNP Guest Request Message NAE events. The events allows for an SEV-SNP guest to make request to the SEV-SNP firmware through hypervisor using the SNP_GUEST_REQUEST API define in the SEV-SNP firmware specification.

The SNP_EXT_GUEST_REQUEST is similar to SNP_GUEST_REQUEST with the difference of an additional certificate blob that can be passed through the SNP_SET_CONFIG ioctl defined in the CCP driver. The CCP driver provides snp_guest_ext_guest_request() that is used by the KVM to get both the report and certificate data at once.

---
 arch/x86/kvm/svm/sev.c | 185 +++++++++++++++++++++++++++++++++++++++--
 arch/x86/kvm/svm/svm.h |   2 +
 2 files changed, 181 insertions(+), 6 deletions(-)
arch/x86/kvm/svm/sev.c +179 -6
index 197b1f904567..92179614102e 100644
@@ -327,6 +327,7 @@ static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
 		if (ret)
 			goto e_free;
 
+		mutex_init(&sev->guest_req_lock);
 		ret = sev_snp_init(&argp->error, false);
 	} else {
 		ret = sev_platform_init(&argp->error);
@@ -2059,23 +2060,34 @@ int sev_vm_move_enc_context_from(struct kvm *kvm, unsigned int source_fd)
  */
 static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp)
 {
+	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
 	struct sev_data_snp_addr data = {};
-	void *context;
+	void *context, *certs_data;
 	int rc;
 
+	/* Allocate memory used for the certs data in SNP guest request */
+	certs_data = kzalloc(SEV_FW_BLOB_MAX_SIZE, GFP_KERNEL_ACCOUNT);
+	if (!certs_data)
+		return NULL;
+
 	/* Allocate memory for context page */
 	context = snp_alloc_firmware_page(GFP_KERNEL_ACCOUNT);
 	if (!context)
-		return NULL;
+		goto e_free;
 
 	data.gctx_paddr = __psp_pa(context);
 	rc = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_GCTX_CREATE, &data, &argp->error);
-	if (rc) {
-		snp_free_firmware_page(context);
-		return NULL;
-	}
+	if (rc)
+		goto e_free;
+
+	sev->snp_certs_data = certs_data;
 
 	return context;
+
+e_free:
+	snp_free_firmware_page(context);
+	kfree(certs_data);
+	return NULL;
 }
 
 static int snp_bind_asid(struct kvm *kvm, int *error)
@@ -2693,6 +2705,8 @@ static int snp_decommission_context(struct kvm *kvm)
 	snp_free_firmware_page(sev->snp_context);
 	sev->snp_context = NULL;
 
+	kfree(sev->snp_certs_data);
+
 	return 0;
 }
 
@@ -3153,6 +3167,8 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm)
 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
 	case SVM_VMGEXIT_HV_FEATURES:
 	case SVM_VMGEXIT_PSC:
+	case SVM_VMGEXIT_GUEST_REQUEST:
+	case SVM_VMGEXIT_EXT_GUEST_REQUEST:
 		break;
 	default:
 		reason = GHCB_ERR_INVALID_EVENT;
@@ -3384,6 +3400,149 @@ static int snp_complete_psc(struct kvm_vcpu *vcpu)
 	return 1;
 }
 
+static unsigned long snp_setup_guest_buf(struct vcpu_svm *svm,
+					 struct sev_data_snp_guest_request *data,
+					 gpa_t req_gpa, gpa_t resp_gpa)
+{
+	struct kvm_vcpu *vcpu = &svm->vcpu;
+	struct kvm *kvm = vcpu->kvm;
+	kvm_pfn_t req_pfn, resp_pfn;
+	struct kvm_sev_info *sev;
+
+	sev = &to_kvm_svm(kvm)->sev_info;
+
+	if (!IS_ALIGNED(req_gpa, PAGE_SIZE) || !IS_ALIGNED(resp_gpa, PAGE_SIZE))
+		return SEV_RET_INVALID_PARAM;
+
+	req_pfn = gfn_to_pfn(kvm, gpa_to_gfn(req_gpa));
+	if (is_error_noslot_pfn(req_pfn))
+		return SEV_RET_INVALID_ADDRESS;
+
+	resp_pfn = gfn_to_pfn(kvm, gpa_to_gfn(resp_gpa));
+	if (is_error_noslot_pfn(resp_pfn))
+		return SEV_RET_INVALID_ADDRESS;
+
+	if (rmp_make_private(resp_pfn, 0, PG_LEVEL_4K, 0, true))
+		return SEV_RET_INVALID_ADDRESS;
+
+	data->gctx_paddr = __psp_pa(sev->snp_context);
+	data->req_paddr = __sme_set(req_pfn << PAGE_SHIFT);
+	data->res_paddr = __sme_set(resp_pfn << PAGE_SHIFT);
+
+	return 0;
+}
+
+static void snp_cleanup_guest_buf(struct sev_data_snp_guest_request *data, unsigned long *rc)
+{
+	u64 pfn = __sme_clr(data->res_paddr) >> PAGE_SHIFT;
+	int ret;
+
+	ret = snp_page_reclaim(pfn);
+	if (ret)
+		*rc = SEV_RET_INVALID_ADDRESS;
+
+	ret = rmp_make_shared(pfn, PG_LEVEL_4K);
+	if (ret)
+		*rc = SEV_RET_INVALID_ADDRESS;
+}
+
+static void snp_handle_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gpa_t resp_gpa)
+{
+	struct sev_data_snp_guest_request data = {0};
+	struct kvm_vcpu *vcpu = &svm->vcpu;
+	struct kvm *kvm = vcpu->kvm;
+	struct kvm_sev_info *sev;
+	unsigned long rc;
+	int err;
+
+	if (!sev_snp_guest(vcpu->kvm)) {
+		rc = SEV_RET_INVALID_GUEST;
+		goto e_fail;
+	}
+
+	sev = &to_kvm_svm(kvm)->sev_info;
+
+	mutex_lock(&sev->guest_req_lock);
+
+	rc = snp_setup_guest_buf(svm, &data, req_gpa, resp_gpa);
+	if (rc)
+		goto unlock;
+
+	rc = sev_issue_cmd(kvm, SEV_CMD_SNP_GUEST_REQUEST, &data, &err);
+	if (rc)
+		/* use the firmware error code */
+		rc = err;
+
+	snp_cleanup_guest_buf(&data, &rc);
+
+unlock:
+	mutex_unlock(&sev->guest_req_lock);
+
+e_fail:
+	ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, rc);
+}
+
+static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gpa_t resp_gpa)
+{
+	struct sev_data_snp_guest_request req = {0};
+	struct kvm_vcpu *vcpu = &svm->vcpu;
+	struct kvm *kvm = vcpu->kvm;
+	unsigned long data_npages;
+	struct kvm_sev_info *sev;
+	unsigned long rc, err;
+	u64 data_gpa;
+
+	if (!sev_snp_guest(vcpu->kvm)) {
+		rc = SEV_RET_INVALID_GUEST;
+		goto e_fail;
+	}
+
+	sev = &to_kvm_svm(kvm)->sev_info;
+
+	data_gpa = vcpu->arch.regs[VCPU_REGS_RAX];
+	data_npages = vcpu->arch.regs[VCPU_REGS_RBX];
+
+	if (!IS_ALIGNED(data_gpa, PAGE_SIZE)) {
+		rc = SEV_RET_INVALID_ADDRESS;
+		goto e_fail;
+	}
+
+	mutex_lock(&sev->guest_req_lock);
+
+	rc = snp_setup_guest_buf(svm, &req, req_gpa, resp_gpa);
+	if (rc)
+		goto unlock;
+
+	rc = snp_guest_ext_guest_request(&req, (unsigned long)sev->snp_certs_data,
+					 &data_npages, &err);
+	if (rc) {
+		/*
+		 * If buffer length is small then return the expected
+		 * length in rbx.
+		 */
+		if (err == SNP_GUEST_REQ_INVALID_LEN)
+			vcpu->arch.regs[VCPU_REGS_RBX] = data_npages;
+
+		/* pass the firmware error code */
+		rc = err;
+		goto cleanup;
+	}
+
+	/* Copy the certificate blob in the guest memory */
+	if (data_npages &&
+	    kvm_write_guest(kvm, data_gpa, sev->snp_certs_data, data_npages << PAGE_SHIFT))
+		rc = SEV_RET_INVALID_ADDRESS;
+
+cleanup:
+	snp_cleanup_guest_buf(&req, &rc);
+
+unlock:
+	mutex_unlock(&sev->guest_req_lock);
+
+e_fail:
+	ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, rc);
+}
+
 static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
 {
 	struct vmcb_control_area *control = &svm->vmcb->control;
@@ -3633,6 +3792,20 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
 		vcpu->run->vmgexit.ghcb_msr = ghcb_gpa;
 		vcpu->arch.complete_userspace_io = snp_complete_psc;
 		break;
+	case SVM_VMGEXIT_GUEST_REQUEST: {
+		snp_handle_guest_request(svm, control->exit_info_1, control->exit_info_2);
+
+		ret = 1;
+		break;
+	}
+	case SVM_VMGEXIT_EXT_GUEST_REQUEST: {
+		snp_handle_ext_guest_request(svm,
+					     control->exit_info_1,
+					     control->exit_info_2);
+
+		ret = 1;
+		break;
+	}
 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
 		vcpu_unimpl(vcpu,
 			    "vmgexit: unsupported event - exit_info_1=%#llx, exit_info_2=%#llx\n",
arch/x86/kvm/svm/svm.h +2 -0
index 13b00233b315..4a9ffb7e5139 100644
@@ -93,6 +93,8 @@ struct kvm_sev_info {
 	atomic_t migration_in_progress;
 	u64 snp_init_flags;
 	void *snp_context;      /* SNP guest context page */
+	void *snp_certs_data;
+	struct mutex guest_req_lock; /* Lock for guest request handling */
 };
 
 struct kvm_svm {
Signature · 1 line
2.25.1
#109 lore raw

Re: [PATCH RFC v8 45/56] KVM: SVM: Provide support for SNP_GUEST_REQUEST NAE event

Quoted 37 lines · Michael Roth

From: Brijesh Singh <[email protected]>

Version 2 of GHCB specification added the support for two SNP Guest Request Message NAE events. The events allows for an SEV-SNP guest to make request to the SEV-SNP firmware through hypervisor using the SNP_GUEST_REQUEST API define in the SEV-SNP firmware specification.

The SNP_EXT_GUEST_REQUEST is similar to SNP_GUEST_REQUEST with the difference of an additional certificate blob that can be passed through the SNP_SET_CONFIG ioctl defined in the CCP driver. The CCP driver provides snp_guest_ext_guest_request() that is used by the KVM to get both the report and certificate data at once.

---
  arch/x86/kvm/svm/sev.c | 185 +++++++++++++++++++++++++++++++++++++++--
  arch/x86/kvm/svm/svm.h |   2 +
  2 files changed, 181 insertions(+), 6 deletions(-)
arch/x86/kvm/svm/sev.c +1 -0
index 197b1f904567..92179614102e 100644
@@ -327,6 +327,7 @@ static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
                 if (ret)
                         goto e_free;
 
+               mutex_init(&sev->guest_req_lock);
                 ret = sev_snp_init(&argp->error, false);
         } else {
                 ret = sev_platform_init(&argp->error);
@@ -2059,23 +2060,34 @@ int sev_vm_move_enc_context_from(struct kvm *kvm, unsigned int source_fd)
   */
  static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp)
  {

arch/x86/kvm/svm/sev.c int sev_vm_move_enc_context_from(struct kvm *kvm, unsigned int source_fd) · line 2071

Quoted 10 lines
arch/x86/kvm/svm/sev.c +6 -1
+       struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
         struct sev_data_snp_addr data = {};
-       void *context;
+       void *context, *certs_data;
         int rc;
 
+       /* Allocate memory used for the certs data in SNP guest request */
+       certs_data = kzalloc(SEV_FW_BLOB_MAX_SIZE, GFP_KERNEL_ACCOUNT);
+       if (!certs_data)
+               return NULL;

I don't understand why this is part of the context creation, which again is part of the KVM_SEV_SNP_LAUNCH_START op. Would you mind to create a separate op for this and then check later on while you use the buffer whether it was ever allocated?

Alex

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879

#110 lore raw

Re: [PATCH RFC v8 45/56] KVM: SVM: Provide support for SNP_GUEST_REQUEST NAE event

In reply to Michael Roth
Quoted 161 lines · On Mon, 20 Feb 2023 12:38:36 -0600 Michael Roth <[email protected]> wrote:

From: Brijesh Singh <[email protected]>

Version 2 of GHCB specification added the support for two SNP Guest Request Message NAE events. The events allows for an SEV-SNP guest to make request to the SEV-SNP firmware through hypervisor using the SNP_GUEST_REQUEST API define in the SEV-SNP firmware specification.

The SNP_EXT_GUEST_REQUEST is similar to SNP_GUEST_REQUEST with the difference of an additional certificate blob that can be passed through the SNP_SET_CONFIG ioctl defined in the CCP driver. The CCP driver provides snp_guest_ext_guest_request() that is used by the KVM to get both the report and certificate data at once.

---
 arch/x86/kvm/svm/sev.c | 185 +++++++++++++++++++++++++++++++++++++++--
 arch/x86/kvm/svm/svm.h |   2 +
 2 files changed, 181 insertions(+), 6 deletions(-)
arch/x86/kvm/svm/sev.c +87 -6
index 197b1f904567..92179614102e 100644
@@ -327,6 +327,7 @@ static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
 		if (ret)
 			goto e_free;
 
+		mutex_init(&sev->guest_req_lock);
 		ret = sev_snp_init(&argp->error, false);
 	} else {
 		ret = sev_platform_init(&argp->error);
@@ -2059,23 +2060,34 @@ int sev_vm_move_enc_context_from(struct kvm *kvm, unsigned int source_fd)
  */
 static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp)
 {
+	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
 	struct sev_data_snp_addr data = {};
-	void *context;
+	void *context, *certs_data;
 	int rc;
 
+	/* Allocate memory used for the certs data in SNP guest request */
+	certs_data = kzalloc(SEV_FW_BLOB_MAX_SIZE, GFP_KERNEL_ACCOUNT);
+	if (!certs_data)
+		return NULL;
+
 	/* Allocate memory for context page */
 	context = snp_alloc_firmware_page(GFP_KERNEL_ACCOUNT);
 	if (!context)
-		return NULL;
+		goto e_free;
 
 	data.gctx_paddr = __psp_pa(context);
 	rc = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_GCTX_CREATE, &data, &argp->error);
-	if (rc) {
-		snp_free_firmware_page(context);
-		return NULL;
-	}
+	if (rc)
+		goto e_free;
+
+	sev->snp_certs_data = certs_data;
 
 	return context;
+
+e_free:
+	snp_free_firmware_page(context);
+	kfree(certs_data);
+	return NULL;
 }
 
 static int snp_bind_asid(struct kvm *kvm, int *error)
@@ -2693,6 +2705,8 @@ static int snp_decommission_context(struct kvm *kvm)
 	snp_free_firmware_page(sev->snp_context);
 	sev->snp_context = NULL;
 
+	kfree(sev->snp_certs_data);
+
 	return 0;
 }
 
@@ -3153,6 +3167,8 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm)
 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
 	case SVM_VMGEXIT_HV_FEATURES:
 	case SVM_VMGEXIT_PSC:
+	case SVM_VMGEXIT_GUEST_REQUEST:
+	case SVM_VMGEXIT_EXT_GUEST_REQUEST:
 		break;
 	default:
 		reason = GHCB_ERR_INVALID_EVENT;
@@ -3384,6 +3400,149 @@ static int snp_complete_psc(struct kvm_vcpu *vcpu)
 	return 1;
 }
 
+static unsigned long snp_setup_guest_buf(struct vcpu_svm *svm,
+					 struct sev_data_snp_guest_request *data,
+					 gpa_t req_gpa, gpa_t resp_gpa)
+{
+	struct kvm_vcpu *vcpu = &svm->vcpu;
+	struct kvm *kvm = vcpu->kvm;
+	kvm_pfn_t req_pfn, resp_pfn;
+	struct kvm_sev_info *sev;
+
+	sev = &to_kvm_svm(kvm)->sev_info;
+
+	if (!IS_ALIGNED(req_gpa, PAGE_SIZE) || !IS_ALIGNED(resp_gpa, PAGE_SIZE))
+		return SEV_RET_INVALID_PARAM;
+
+	req_pfn = gfn_to_pfn(kvm, gpa_to_gfn(req_gpa));
+	if (is_error_noslot_pfn(req_pfn))
+		return SEV_RET_INVALID_ADDRESS;
+
+	resp_pfn = gfn_to_pfn(kvm, gpa_to_gfn(resp_gpa));
+	if (is_error_noslot_pfn(resp_pfn))
+		return SEV_RET_INVALID_ADDRESS;
+
+	if (rmp_make_private(resp_pfn, 0, PG_LEVEL_4K, 0, true))
+		return SEV_RET_INVALID_ADDRESS;
+
+	data->gctx_paddr = __psp_pa(sev->snp_context);
+	data->req_paddr = __sme_set(req_pfn << PAGE_SHIFT);
+	data->res_paddr = __sme_set(resp_pfn << PAGE_SHIFT);
+
+	return 0;
+}
+
+static void snp_cleanup_guest_buf(struct sev_data_snp_guest_request *data, unsigned long *rc)
+{
+	u64 pfn = __sme_clr(data->res_paddr) >> PAGE_SHIFT;
+	int ret;
+
+	ret = snp_page_reclaim(pfn);
+	if (ret)
+		*rc = SEV_RET_INVALID_ADDRESS;
+
+	ret = rmp_make_shared(pfn, PG_LEVEL_4K);
+	if (ret)
+		*rc = SEV_RET_INVALID_ADDRESS;
+}
+
+static void snp_handle_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gpa_t resp_gpa)
+{
+	struct sev_data_snp_guest_request data = {0};
+	struct kvm_vcpu *vcpu = &svm->vcpu;
+	struct kvm *kvm = vcpu->kvm;
+	struct kvm_sev_info *sev;
+	unsigned long rc;
+	int err;
+
+	if (!sev_snp_guest(vcpu->kvm)) {
+		rc = SEV_RET_INVALID_GUEST;
+		goto e_fail;
+	}
+
+	sev = &to_kvm_svm(kvm)->sev_info;
+
+	mutex_lock(&sev->guest_req_lock);
+
+	rc = snp_setup_guest_buf(svm, &data, req_gpa, resp_gpa);

arch/x86/kvm/svm/sev.c static int snp_complete_psc(struct kvm_vcpu *vcpu) · line 3477

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+	if (rc)
+		goto unlock;
+
+	rc = sev_issue_cmd(kvm, SEV_CMD_SNP_GUEST_REQUEST, &data, &err);
+	if (rc)
+		/* use the firmware error code */
+		rc = err;
+
+	snp_cleanup_guest_buf(&data, &rc);
+

I am curious about the reason of having a shared-private and private-shared conversion before and after issuing the command to firmware.

Is it because the firmware requires the resp page has to be a private page? while the req page is not. (I understand that the req/resp page should be shared before returnning to guest due to GHCB spec)

Quoted 105 lines
arch/x86/kvm/svm/sev.c +82 -0
+unlock:
+	mutex_unlock(&sev->guest_req_lock);
+
+e_fail:
+	ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, rc);
+}
+
+static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gpa_t resp_gpa)
+{
+	struct sev_data_snp_guest_request req = {0};
+	struct kvm_vcpu *vcpu = &svm->vcpu;
+	struct kvm *kvm = vcpu->kvm;
+	unsigned long data_npages;
+	struct kvm_sev_info *sev;
+	unsigned long rc, err;
+	u64 data_gpa;
+
+	if (!sev_snp_guest(vcpu->kvm)) {
+		rc = SEV_RET_INVALID_GUEST;
+		goto e_fail;
+	}
+
+	sev = &to_kvm_svm(kvm)->sev_info;
+
+	data_gpa = vcpu->arch.regs[VCPU_REGS_RAX];
+	data_npages = vcpu->arch.regs[VCPU_REGS_RBX];
+
+	if (!IS_ALIGNED(data_gpa, PAGE_SIZE)) {
+		rc = SEV_RET_INVALID_ADDRESS;
+		goto e_fail;
+	}
+
+	mutex_lock(&sev->guest_req_lock);
+
+	rc = snp_setup_guest_buf(svm, &req, req_gpa, resp_gpa);
+	if (rc)
+		goto unlock;
+
+	rc = snp_guest_ext_guest_request(&req, (unsigned long)sev->snp_certs_data,
+					 &data_npages, &err);
+	if (rc) {
+		/*
+		 * If buffer length is small then return the expected
+		 * length in rbx.
+		 */
+		if (err == SNP_GUEST_REQ_INVALID_LEN)
+			vcpu->arch.regs[VCPU_REGS_RBX] = data_npages;
+
+		/* pass the firmware error code */
+		rc = err;
+		goto cleanup;
+	}
+
+	/* Copy the certificate blob in the guest memory */
+	if (data_npages &&
+	    kvm_write_guest(kvm, data_gpa, sev->snp_certs_data, data_npages << PAGE_SHIFT))
+		rc = SEV_RET_INVALID_ADDRESS;
+
+cleanup:
+	snp_cleanup_guest_buf(&req, &rc);
+
+unlock:
+	mutex_unlock(&sev->guest_req_lock);
+
+e_fail:
+	ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, rc);
+}
+
 static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
 {
 	struct vmcb_control_area *control = &svm->vmcb->control;
@@ -3633,6 +3792,20 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
 		vcpu->run->vmgexit.ghcb_msr = ghcb_gpa;
 		vcpu->arch.complete_userspace_io = snp_complete_psc;
 		break;
+	case SVM_VMGEXIT_GUEST_REQUEST: {
+		snp_handle_guest_request(svm, control->exit_info_1, control->exit_info_2);
+
+		ret = 1;
+		break;
+	}
+	case SVM_VMGEXIT_EXT_GUEST_REQUEST: {
+		snp_handle_ext_guest_request(svm,
+					     control->exit_info_1,
+					     control->exit_info_2);
+
+		ret = 1;
+		break;
+	}
 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
 		vcpu_unimpl(vcpu,
 			    "vmgexit: unsupported event - exit_info_1=%#llx, exit_info_2=%#llx\n",
arch/x86/kvm/svm/svm.h +2 -0
index 13b00233b315..4a9ffb7e5139 100644
@@ -93,6 +93,8 @@ struct kvm_sev_info {
 	atomic_t migration_in_progress;
 	u64 snp_init_flags;
 	void *snp_context;      /* SNP guest context page */
+	void *snp_certs_data;
+	struct mutex guest_req_lock; /* Lock for guest request handling */
 };
 
 struct kvm_svm {
#111 lore raw

Re: [PATCH RFC v8 45/56] KVM: SVM: Provide support for SNP_GUEST_REQUEST NAE event

In reply to Michael Roth
Quoted 158 lines · Michael Roth

From: Brijesh Singh <[email protected]>

Version 2 of GHCB specification added the support for two SNP Guest Request Message NAE events. The events allows for an SEV-SNP guest to make request to the SEV-SNP firmware through hypervisor using the SNP_GUEST_REQUEST API define in the SEV-SNP firmware specification.

The SNP_EXT_GUEST_REQUEST is similar to SNP_GUEST_REQUEST with the difference of an additional certificate blob that can be passed through the SNP_SET_CONFIG ioctl defined in the CCP driver. The CCP driver provides snp_guest_ext_guest_request() that is used by the KVM to get both the report and certificate data at once.

---
  arch/x86/kvm/svm/sev.c | 185 +++++++++++++++++++++++++++++++++++++++--
  arch/x86/kvm/svm/svm.h |   2 +
  2 files changed, 181 insertions(+), 6 deletions(-)
arch/x86/kvm/svm/sev.c +84 -6
index 197b1f904567..92179614102e 100644
@@ -327,6 +327,7 @@ static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
                 if (ret)
                         goto e_free;
 
+               mutex_init(&sev->guest_req_lock);
                 ret = sev_snp_init(&argp->error, false);
         } else {
                 ret = sev_platform_init(&argp->error);
@@ -2059,23 +2060,34 @@ int sev_vm_move_enc_context_from(struct kvm *kvm, unsigned int source_fd)
   */
  static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp)
  {
+       struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
         struct sev_data_snp_addr data = {};
-       void *context;
+       void *context, *certs_data;
         int rc;
 
+       /* Allocate memory used for the certs data in SNP guest request */
+       certs_data = kzalloc(SEV_FW_BLOB_MAX_SIZE, GFP_KERNEL_ACCOUNT);
+       if (!certs_data)
+               return NULL;
+
         /* Allocate memory for context page */
         context = snp_alloc_firmware_page(GFP_KERNEL_ACCOUNT);
         if (!context)
-               return NULL;
+               goto e_free;
 
         data.gctx_paddr = __psp_pa(context);
         rc = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_GCTX_CREATE, &data, &argp->error);
-       if (rc) {
-               snp_free_firmware_page(context);
-               return NULL;
-       }
+       if (rc)
+               goto e_free;
+
+       sev->snp_certs_data = certs_data;
 
         return context;
+
+e_free:
+       snp_free_firmware_page(context);
+       kfree(certs_data);
+       return NULL;
  }
 
  static int snp_bind_asid(struct kvm *kvm, int *error)
@@ -2693,6 +2705,8 @@ static int snp_decommission_context(struct kvm *kvm)
         snp_free_firmware_page(sev->snp_context);
         sev->snp_context = NULL;
 
+       kfree(sev->snp_certs_data);
+
         return 0;
  }
 
@@ -3153,6 +3167,8 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm)
         case SVM_VMGEXIT_UNSUPPORTED_EVENT:
         case SVM_VMGEXIT_HV_FEATURES:
         case SVM_VMGEXIT_PSC:
+       case SVM_VMGEXIT_GUEST_REQUEST:
+       case SVM_VMGEXIT_EXT_GUEST_REQUEST:
                 break;
         default:
                 reason = GHCB_ERR_INVALID_EVENT;
@@ -3384,6 +3400,149 @@ static int snp_complete_psc(struct kvm_vcpu *vcpu)
         return 1;
  }
 
+static unsigned long snp_setup_guest_buf(struct vcpu_svm *svm,
+                                        struct sev_data_snp_guest_request *data,
+                                        gpa_t req_gpa, gpa_t resp_gpa)
+{
+       struct kvm_vcpu *vcpu = &svm->vcpu;
+       struct kvm *kvm = vcpu->kvm;
+       kvm_pfn_t req_pfn, resp_pfn;
+       struct kvm_sev_info *sev;
+
+       sev = &to_kvm_svm(kvm)->sev_info;
+
+       if (!IS_ALIGNED(req_gpa, PAGE_SIZE) || !IS_ALIGNED(resp_gpa, PAGE_SIZE))
+               return SEV_RET_INVALID_PARAM;
+
+       req_pfn = gfn_to_pfn(kvm, gpa_to_gfn(req_gpa));
+       if (is_error_noslot_pfn(req_pfn))
+               return SEV_RET_INVALID_ADDRESS;
+
+       resp_pfn = gfn_to_pfn(kvm, gpa_to_gfn(resp_gpa));
+       if (is_error_noslot_pfn(resp_pfn))
+               return SEV_RET_INVALID_ADDRESS;
+
+       if (rmp_make_private(resp_pfn, 0, PG_LEVEL_4K, 0, true))
+               return SEV_RET_INVALID_ADDRESS;
+
+       data->gctx_paddr = __psp_pa(sev->snp_context);
+       data->req_paddr = __sme_set(req_pfn << PAGE_SHIFT);
+       data->res_paddr = __sme_set(resp_pfn << PAGE_SHIFT);
+
+       return 0;
+}
+
+static void snp_cleanup_guest_buf(struct sev_data_snp_guest_request *data, unsigned long *rc)
+{
+       u64 pfn = __sme_clr(data->res_paddr) >> PAGE_SHIFT;
+       int ret;
+
+       ret = snp_page_reclaim(pfn);
+       if (ret)
+               *rc = SEV_RET_INVALID_ADDRESS;
+
+       ret = rmp_make_shared(pfn, PG_LEVEL_4K);
+       if (ret)
+               *rc = SEV_RET_INVALID_ADDRESS;
+}
+
+static void snp_handle_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gpa_t resp_gpa)
+{
+       struct sev_data_snp_guest_request data = {0};
+       struct kvm_vcpu *vcpu = &svm->vcpu;
+       struct kvm *kvm = vcpu->kvm;
+       struct kvm_sev_info *sev;
+       unsigned long rc;
+       int err;
+
+       if (!sev_snp_guest(vcpu->kvm)) {
+               rc = SEV_RET_INVALID_GUEST;
+               goto e_fail;
+       }
+
+       sev = &to_kvm_svm(kvm)->sev_info;
+

arch/x86/kvm/svm/sev.c static int snp_complete_psc(struct kvm_vcpu *vcpu) · line 3474

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+       mutex_lock(&sev->guest_req_lock);
+
+       rc = snp_setup_guest_buf(svm, &data, req_gpa, resp_gpa);
+       if (rc)
+               goto unlock;
+
+       rc = sev_issue_cmd(kvm, SEV_CMD_SNP_GUEST_REQUEST, &data, &err);
+       if (rc)
+               /* use the firmware error code */
+               rc = err;

There are cases where sev_issue_cmd can fail, but not set err. For example, when the file descriptor is incorrect. In that case, this code path leaks uninitialized state from the host stack (err) all the way into a guest.

Alex

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879

#112 lore raw

RFC PATCH v8 46/56 KVM: SVM: Use a VMSA physical address variable for populating VMCB

In reply to Michael Roth

From: Tom Lendacky <[email protected]>

In preparation to support SEV-SNP AP Creation, use a variable that holds the VMSA physical address rather than converting the virtual address. This will allow SEV-SNP AP Creation to set the new physical address that will be used should the vCPU reset path be taken.

---
 arch/x86/kvm/svm/sev.c | 5 ++---
 arch/x86/kvm/svm/svm.c | 9 ++++++++-
 arch/x86/kvm/svm/svm.h | 1 +
 3 files changed, 11 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/sev.c +2 -3
index 92179614102e..6bec2712ecc6 100644
@@ -3849,10 +3849,9 @@ static void sev_es_init_vmcb(struct vcpu_svm *svm)
 
 	/*
 	 * An SEV-ES guest requires a VMSA area that is a separate from the
-	 * VMCB page. Do not include the encryption mask on the VMSA physical
-	 * address since hardware will access it using the guest key.
+	 * VMCB page.
 	 */
-	svm->vmcb->control.vmsa_pa = __pa(svm->sev_es.vmsa);
+	svm->vmcb->control.vmsa_pa = svm->sev_es.vmsa_pa;
 
 	/* Can't intercept CR register access, HV can't modify CR registers */
 	svm_clr_intercept(svm, INTERCEPT_CR0_READ);
arch/x86/kvm/svm/svm.c +8 -1
index f9ab4bf6d245..745f736d9c98 100644
@@ -1410,9 +1410,16 @@ static int svm_vcpu_create(struct kvm_vcpu *vcpu)
 	svm->vmcb01.pa = __sme_set(page_to_pfn(vmcb01_page) << PAGE_SHIFT);
 	svm_switch_vmcb(svm, &svm->vmcb01);
 
-	if (vmsa_page)
+	if (vmsa_page) {
 		svm->sev_es.vmsa = page_address(vmsa_page);
 
+		/*
+		 * Do not include the encryption mask on the VMSA physical
+		 * address since hardware will access it using the guest key.
+		 */
+		svm->sev_es.vmsa_pa = __pa(svm->sev_es.vmsa);
+	}
+
 	svm->guest_state_loaded = false;
 
 	return 0;
arch/x86/kvm/svm/svm.h +1 -0
index 4a9ffb7e5139..b6ca6657aa6c 100644
@@ -198,6 +198,7 @@ struct vcpu_sev_es_state {
 	struct sev_es_save_area *vmsa;
 	struct ghcb *ghcb;
 	struct kvm_host_map ghcb_map;
+	hpa_t vmsa_pa;
 	bool received_first_sipi;
 	unsigned int ap_reset_hold_type;
 
Signature · 1 line
2.25.1
#113 lore raw

RFC PATCH v8 47/56 KVM: SVM: Support SEV-SNP AP Creation NAE event

In reply to Michael Roth

From: Tom Lendacky <[email protected]>

Add support for the SEV-SNP AP Creation NAE event. This allows SEV-SNP guests to alter the register state of the APs on their own. This allows the guest a way of simulating INIT-SIPI.

A new event, KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, is created and used so as to avoid updating the VMSA pointer while the vCPU is running.

For CREATE
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID. The GPA is saved in the svm struct of the target vCPU, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to the vCPU and then the vCPU is kicked.

For CREATE_ON_INIT:
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID the next time an INIT is performed. The GPA is saved in the svm struct of the target vCPU.

For DESTROY:
The guest indicates it wishes to stop the vCPU. The GPA is cleared from the svm struct, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to vCPU and then the vCPU is kicked.

The KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event handler will be invoked as a result of the event or as a result of an INIT. The handler sets the vCPU to the KVM_MP_STATE_UNINITIALIZED state, so that any errors will leave the vCPU as not runnable. Any previous VMSA pages that were installed as part of an SEV-SNP AP Creation NAE event are un-pinned. If a new VMSA is to be installed, the VMSA guest page is pinned and set as the VMSA in the vCPU VMCB and the vCPU state is set to KVM_MP_STATE_RUNNABLE. If a new VMSA is not to be installed, the VMSA is cleared in the vCPU VMCB and the vCPU state is left as KVM_MP_STATE_UNINITIALIZED to prevent it from being run.

[mdr: add handling for restrictedmem]
---
 arch/x86/include/asm/kvm_host.h |   1 +
 arch/x86/include/asm/svm.h      |   7 +-
 arch/x86/kvm/svm/sev.c          | 245 ++++++++++++++++++++++++++++++++
 arch/x86/kvm/svm/svm.c          |   3 +
 arch/x86/kvm/svm/svm.h          |   7 +
 arch/x86/kvm/x86.c              |   9 ++
 6 files changed, 271 insertions(+), 1 deletion(-)
arch/x86/include/asm/kvm_host.h +1 -0
index 28b01cc7f64d..09b36462582c 100644
@@ -113,6 +113,7 @@
 	KVM_ARCH_REQ_FLAGS(31, KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP)
 #define KVM_REQ_HV_TLB_FLUSH \
 	KVM_ARCH_REQ_FLAGS(32, KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP)
+#define KVM_REQ_UPDATE_PROTECTED_GUEST_STATE	KVM_ARCH_REQ(34)
 
 #define CR0_RESERVED_BITS                                               \
 	(~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
arch/x86/include/asm/svm.h +6 -1
index c18d78d5e505..e76ad26ba64f 100644
@@ -278,7 +278,12 @@ enum avic_ipi_failure_cause {
 #define AVIC_HPA_MASK	~((0xFFFULL << 52) | 0xFFF)
 #define VMCB_AVIC_APIC_BAR_MASK		0xFFFFFFFFFF000ULL
 
-#define SVM_SEV_FEAT_SNP_ACTIVE		BIT(0)
+#define SVM_SEV_FEAT_SNP_ACTIVE			BIT(0)
+#define SVM_SEV_FEAT_RESTRICTED_INJECTION	BIT(3)
+#define SVM_SEV_FEAT_ALTERNATE_INJECTION	BIT(4)
+#define SVM_SEV_FEAT_INT_INJ_MODES		\
+	(SVM_SEV_FEAT_RESTRICTED_INJECTION |	\
+	 SVM_SEV_FEAT_ALTERNATE_INJECTION)
 
 struct vmcb_seg {
 	u16 selector;
arch/x86/kvm/svm/sev.c +245 -0

281 lines not on this page · raw message

arch/x86/kvm/svm/svm.c +3 -0
index 745f736d9c98..539926b07ee5 100644
@@ -1349,6 +1349,9 @@ static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
 	svm->spec_ctrl = 0;
 	svm->virt_spec_ctrl = 0;
 
+	if (init_event)
+		sev_snp_init_protected_guest_state(vcpu);
+
 	init_vmcb(vcpu);
 
 	if (!init_event)
arch/x86/kvm/svm/svm.h +7 -0
index b6ca6657aa6c..37bd7b728d52 100644
@@ -95,6 +95,8 @@ struct kvm_sev_info {
 	void *snp_context;      /* SNP guest context page */
 	void *snp_certs_data;
 	struct mutex guest_req_lock; /* Lock for guest request handling */
+
+	u64 sev_features;	/* Features set at VMSA creation */
 };
 
 struct kvm_svm {
@@ -209,6 +211,10 @@ struct vcpu_sev_es_state {
 	bool ghcb_sa_free;
 
 	u64 ghcb_registered_gpa;
+
+	struct mutex snp_vmsa_mutex;
+	gpa_t snp_vmsa_gpa;
+	bool snp_ap_create;
 };
 
 struct vcpu_svm {
@@ -718,6 +724,7 @@ void sev_es_unmap_ghcb(struct vcpu_svm *svm);
 struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu);
 void sev_adjust_mapping_level(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int *level);
 void handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code);
+void sev_snp_init_protected_guest_state(struct kvm_vcpu *vcpu);
 
 /* vmenter.S */
 
arch/x86/kvm/x86.c +9 -0
index 0154fc7a28c1..9872217e3a06 100644
@@ -10501,6 +10501,12 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 
 		if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
 			static_call(kvm_x86_update_cpu_dirty_logging)(vcpu);
+
+		if (kvm_check_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu)) {
+			kvm_vcpu_reset(vcpu, true);
+			if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE)
+				goto out;
+		}
 	}
 
 	if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
@@ -12698,6 +12704,9 @@ static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
 		return true;
 #endif
 
+	if (kvm_test_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu))
+		return true;
+
 	if (kvm_arch_interrupt_allowed(vcpu) &&
 	    (kvm_cpu_has_interrupt(vcpu) ||
 	    kvm_guest_apic_has_interrupt(vcpu)))
Signature · 1 line
2.25.1
#114 lore raw

Re: [PATCH RFC v8 47/56] KVM: SVM: Support SEV-SNP AP Creation NAE event

Quoted 36 lines · Michael Roth

From: Tom Lendacky <[email protected]>

Add support for the SEV-SNP AP Creation NAE event. This allows SEV-SNP guests to alter the register state of the APs on their own. This allows the guest a way of simulating INIT-SIPI.

A new event, KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, is created and used so as to avoid updating the VMSA pointer while the vCPU is running.

For CREATE
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID. The GPA is saved in the svm struct of the target vCPU, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to the vCPU and then the vCPU is kicked.

For CREATE_ON_INIT:
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID the next time an INIT is performed. The GPA is saved in the svm struct of the target vCPU.

For DESTROY:
The guest indicates it wishes to stop the vCPU. The GPA is cleared from the svm struct, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to vCPU and then the vCPU is kicked.

The KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event handler will be invoked as a result of the event or as a result of an INIT. The handler sets the vCPU to the KVM_MP_STATE_UNINITIALIZED state, so that any errors will leave the vCPU as not runnable. Any previous VMSA pages that were installed as part of an SEV-SNP AP Creation NAE event are un-pinned. If a new VMSA is to be installed, the VMSA guest page is pinned and set as the VMSA in the vCPU VMCB and the vCPU state is set to KVM_MP_STATE_RUNNABLE. If a new VMSA is not to be installed, the VMSA is cleared in the vCPU VMCB and the vCPU state is left as KVM_MP_STATE_UNINITIALIZED to prevent it from being run.

Quoted 5 lines
[mdr: add handling for restrictedmem]

What is the intended boot sequence for SEV-SNP guests? FWIW with this interface in place, guests will typically use in-guest VMSA pages to hold secondary vcpu state. But that means we're now allocating 4kb of memory for every vcpu that we create that will be for most of the guest's lifetime superfluous.

Wouldn't it make more sense to have a model where we only allocate the VMSA for the boot CPU and leave secondary allocation to the guest? We already need firmware changes for SEV-SNP - may as well make this one more.

[...]

Quoted 7 lines
arch/x86/kvm/svm/sev.c +7 -0
+
+static int sev_snp_ap_creation(struct vcpu_svm *svm)
+{
+       struct kvm_sev_info *sev = &to_kvm_svm(svm->vcpu.kvm)->sev_info;
+       struct kvm_vcpu *vcpu = &svm->vcpu;
+       struct kvm_vcpu *target_vcpu;
+       struct vcpu_svm *target_svm;

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3688

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+       unsigned int request;
+       unsigned int apic_id;
+       bool kick;
+       int ret;
+
+       request = lower_32_bits(svm->vmcb->control.exit_info_1);
+       apic_id = upper_32_bits(svm->vmcb->control.exit_info_1);
+
+       /* Validate the APIC ID */
+       target_vcpu = kvm_get_vcpu_by_id(vcpu->kvm, apic_id);

Out of curiosity: The target CPU can be my own vCPU, right?

Quoted 44 lines
arch/x86/kvm/svm/sev.c +44 -0
+       if (!target_vcpu) {
+               vcpu_unimpl(vcpu, "vmgexit: invalid AP APIC ID [%#x] from guest\n",
+                           apic_id);
+               return -EINVAL;
+       }
+
+       ret = 0;
+
+       target_svm = to_svm(target_vcpu);
+
+       /*
+        * The target vCPU is valid, so the vCPU will be kicked unless the
+        * request is for CREATE_ON_INIT. For any errors at this stage, the
+        * kick will place the vCPU in an non-runnable state.
+        */
+       kick = true;
+
+       mutex_lock(&target_svm->sev_es.snp_vmsa_mutex);
+
+       target_svm->sev_es.snp_vmsa_gpa = INVALID_PAGE;
+       target_svm->sev_es.snp_ap_create = true;
+
+       /* Interrupt injection mode shouldn't change for AP creation */
+       if (request < SVM_VMGEXIT_AP_DESTROY) {
+               u64 sev_features;
+
+               sev_features = vcpu->arch.regs[VCPU_REGS_RAX];
+               sev_features ^= sev->sev_features;
+               if (sev_features & SVM_SEV_FEAT_INT_INJ_MODES) {
+                       vcpu_unimpl(vcpu, "vmgexit: invalid AP injection mode [%#lx] from guest\n",
+                                   vcpu->arch.regs[VCPU_REGS_RAX]);
+                       ret = -EINVAL;
+                       goto out;
+               }
+       }
+
+       switch (request) {
+       case SVM_VMGEXIT_AP_CREATE_ON_INIT:
+               kick = false;
+               fallthrough;
+       case SVM_VMGEXIT_AP_CREATE:
+               if (!page_address_valid(vcpu, svm->vmcb->control.exit_info_2)) {
+                       vcpu_unimpl(vcpu, "vmgexit: invalid AP VMSA address [%#llx] from guest\n",
+                                   svm->vmcb->control.exit_info_2);

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3742

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+                       ret = -EINVAL;
+                       goto out;
+               }
+
+               /*
+                * Malicious guest can RMPADJUST a large page into VMSA which
+                * will hit the SNP erratum where the CPU will incorrectly signal
+                * an RMP violation #PF if a hugepage collides with the RMP entry
+                * of VMSA page, reject the AP CREATE request if VMSA address from
+                * guest is 2M aligned.

This will break genuine current Linux kernels that just happen to allocate a guest page, no? In fact, given enough vCPUs you're almost guaranteed to hit an aligned structure somewhere. What is the guest supposed to do in that situation?

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3754

Quoted 12 lines
arch/x86/kvm/svm/sev.c +12 -0
+                */
+               if (IS_ALIGNED(svm->vmcb->control.exit_info_2, PMD_SIZE)) {
+                       vcpu_unimpl(vcpu,
+                                   "vmgexit: AP VMSA address [%llx] from guest is unsafe as it is 2M aligned\n",
+                                   svm->vmcb->control.exit_info_2);
+                       ret = -EINVAL;
+                       goto out;
+               }
+
+               target_svm->sev_es.snp_vmsa_gpa = svm->vmcb->control.exit_info_2;
+               break;
+       case SVM_VMGEXIT_AP_DESTROY:

I don't understand the destroy path. Why does this case destroy anything?

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3766

Quoted 12 lines
arch/x86/kvm/svm/sev.c +12 -0
+               break;
+       default:
+               vcpu_unimpl(vcpu, "vmgexit: invalid AP creation request [%#x] from guest\n",
+                           request);
+               ret = -EINVAL;
+               break;
+       }
+
+out:
+       if (kick) {
+               if (target_vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)
+                       target_vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;

What if the guest AP goes through a create -> destroy -> create cycle? Will it stay runnable while destroyed?

Alex

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3779

Quoted 13 lines
arch/x86/kvm/svm/sev.c +10 -0
+
+               kvm_make_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, target_vcpu);
+               kvm_vcpu_kick(target_vcpu);
+       }
+
+       mutex_unlock(&target_svm->sev_es.snp_vmsa_mutex);
+
+       return ret;
+}
+
  static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
  {
         struct vmcb_control_area *control = &svm->vmcb->control;

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879

#115 lore raw

Re: [PATCH RFC v8 47/56] KVM: SVM: Support SEV-SNP AP Creation NAE event

Quoted 158 lines · On Fri, 24 Feb 2023 13:37:48 +0100 Alexander Graf <[email protected]> wrote:
Quoted 36 lines · Michael Roth

From: Tom Lendacky <[email protected]>

Add support for the SEV-SNP AP Creation NAE event. This allows SEV-SNP guests to alter the register state of the APs on their own. This allows the guest a way of simulating INIT-SIPI.

A new event, KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, is created and used so as to avoid updating the VMSA pointer while the vCPU is running.

For CREATE
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID. The GPA is saved in the svm struct of the target vCPU, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to the vCPU and then the vCPU is kicked.

For CREATE_ON_INIT:
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID the next time an INIT is performed. The GPA is saved in the svm struct of the target vCPU.

For DESTROY:
The guest indicates it wishes to stop the vCPU. The GPA is cleared from the svm struct, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to vCPU and then the vCPU is kicked.

The KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event handler will be invoked as a result of the event or as a result of an INIT. The handler sets the vCPU to the KVM_MP_STATE_UNINITIALIZED state, so that any errors will leave the vCPU as not runnable. Any previous VMSA pages that were installed as part of an SEV-SNP AP Creation NAE event are un-pinned. If a new VMSA is to be installed, the VMSA guest page is pinned and set as the VMSA in the vCPU VMCB and the vCPU state is set to KVM_MP_STATE_RUNNABLE. If a new VMSA is not to be installed, the VMSA is cleared in the vCPU VMCB and the vCPU state is left as KVM_MP_STATE_UNINITIALIZED to prevent it from being run.

Quoted 5 lines
[mdr: add handling for restrictedmem]

What is the intended boot sequence for SEV-SNP guests? FWIW with this interface in place, guests will typically use in-guest VMSA pages to hold secondary vcpu state. But that means we're now allocating 4kb of memory for every vcpu that we create that will be for most of the guest's lifetime superfluous.

Wouldn't it make more sense to have a model where we only allocate the VMSA for the boot CPU and leave secondary allocation to the guest? We already need firmware changes for SEV-SNP - may as well make this one more.

[...]

Quoted 7 lines
arch/x86/kvm/svm/sev.c +7 -0
+
+static int sev_snp_ap_creation(struct vcpu_svm *svm)
+{
+       struct kvm_sev_info *sev = &to_kvm_svm(svm->vcpu.kvm)->sev_info;
+       struct kvm_vcpu *vcpu = &svm->vcpu;
+       struct kvm_vcpu *target_vcpu;
+       struct vcpu_svm *target_svm;

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3688

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+       unsigned int request;
+       unsigned int apic_id;
+       bool kick;
+       int ret;
+
+       request = lower_32_bits(svm->vmcb->control.exit_info_1);
+       apic_id = upper_32_bits(svm->vmcb->control.exit_info_1);
+
+       /* Validate the APIC ID */
+       target_vcpu = kvm_get_vcpu_by_id(vcpu->kvm, apic_id);

Out of curiosity: The target CPU can be my own vCPU, right?

Quoted 44 lines
arch/x86/kvm/svm/sev.c +44 -0
+       if (!target_vcpu) {
+               vcpu_unimpl(vcpu, "vmgexit: invalid AP APIC ID [%#x] from guest\n",
+                           apic_id);
+               return -EINVAL;
+       }
+
+       ret = 0;
+
+       target_svm = to_svm(target_vcpu);
+
+       /*
+        * The target vCPU is valid, so the vCPU will be kicked unless the
+        * request is for CREATE_ON_INIT. For any errors at this stage, the
+        * kick will place the vCPU in an non-runnable state.
+        */
+       kick = true;
+
+       mutex_lock(&target_svm->sev_es.snp_vmsa_mutex);
+
+       target_svm->sev_es.snp_vmsa_gpa = INVALID_PAGE;
+       target_svm->sev_es.snp_ap_create = true;
+
+       /* Interrupt injection mode shouldn't change for AP creation */
+       if (request < SVM_VMGEXIT_AP_DESTROY) {
+               u64 sev_features;
+
+               sev_features = vcpu->arch.regs[VCPU_REGS_RAX];
+               sev_features ^= sev->sev_features;
+               if (sev_features & SVM_SEV_FEAT_INT_INJ_MODES) {
+                       vcpu_unimpl(vcpu, "vmgexit: invalid AP injection mode [%#lx] from guest\n",
+                                   vcpu->arch.regs[VCPU_REGS_RAX]);
+                       ret = -EINVAL;
+                       goto out;
+               }
+       }
+
+       switch (request) {
+       case SVM_VMGEXIT_AP_CREATE_ON_INIT:
+               kick = false;
+               fallthrough;
+       case SVM_VMGEXIT_AP_CREATE:
+               if (!page_address_valid(vcpu, svm->vmcb->control.exit_info_2)) {
+                       vcpu_unimpl(vcpu, "vmgexit: invalid AP VMSA address [%#llx] from guest\n",
+                                   svm->vmcb->control.exit_info_2);

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3742

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+                       ret = -EINVAL;
+                       goto out;
+               }
+
+               /*
+                * Malicious guest can RMPADJUST a large page into VMSA which
+                * will hit the SNP erratum where the CPU will incorrectly signal
+                * an RMP violation #PF if a hugepage collides with the RMP entry
+                * of VMSA page, reject the AP CREATE request if VMSA address from
+                * guest is 2M aligned.

This will break genuine current Linux kernels that just happen to allocate a guest page, no? In fact, given enough vCPUs you're almost guaranteed to hit an aligned structure somewhere. What is the guest supposed to do in that situation?

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3754

Quoted 12 lines
arch/x86/kvm/svm/sev.c +12 -0
+                */
+               if (IS_ALIGNED(svm->vmcb->control.exit_info_2, PMD_SIZE)) {
+                       vcpu_unimpl(vcpu,
+                                   "vmgexit: AP VMSA address [%llx] from guest is unsafe as it is 2M aligned\n",
+                                   svm->vmcb->control.exit_info_2);
+                       ret = -EINVAL;
+                       goto out;
+               }
+
+               target_svm->sev_es.snp_vmsa_gpa = svm->vmcb->control.exit_info_2;
+               break;
+       case SVM_VMGEXIT_AP_DESTROY:

I don't understand the destroy path. Why does this case destroy anything?

Quoted 16 lines

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3766

Quoted 12 lines
arch/x86/kvm/svm/sev.c +12 -0
+               break;
+       default:
+               vcpu_unimpl(vcpu, "vmgexit: invalid AP creation request [%#x] from guest\n",
+                           request);
+               ret = -EINVAL;
+               break;
+       }
+
+out:
+       if (kick) {
+               if (target_vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)
+                       target_vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;

What if the guest AP goes through a create -> destroy -> create cycle? Will it stay runnable while destroyed?

The code is not very straightforward.

1) target_svm->sev_es.snp_vmsa_gpa is set as INVALID_PAGE in the beginning of this function.

2) If a DESTROY is hit in this function, target_svm->sev_es.snp_vmsa_gpa will be left as INVALID_PAGE.

3) At the end of this function, it calls kvm_make_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE).

4) In the vcpu_enter_guest(), the kvm_vcpu_reset()->sev_snp_init_protected_guest_state() ->__sev_snp_init_protected_guest_state() is called.

5) The mp_state is set to KVM_MP_STATE_STOPPED by default and the runtime VMSA is cleared. Then the it will be initialized according to the guest's configuration.

6) As the snp_vmsa_gpa is set as INVALID_PAGE in 1, the mp_state will be left as KVM_MP_STATE_STOPPED.

7) With this code piece:

+ kvm_vcpu_reset(vcpu, true);
+ if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE)
+ goto out;

vcpu_enter_guest() bails out.

Quoted 29 lines

Alex

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3779

Quoted 13 lines
arch/x86/kvm/svm/sev.c +10 -0
+
+               kvm_make_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, target_vcpu);
+               kvm_vcpu_kick(target_vcpu);
+       }
+
+       mutex_unlock(&target_svm->sev_es.snp_vmsa_mutex);
+
+       return ret;
+}
+
  static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
  {
         struct vmcb_control_area *control = &svm->vmcb->control;

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879

#116 lore raw

Re: [PATCH RFC v8 47/56] KVM: SVM: Support SEV-SNP AP Creation NAE event

Quoted 196 lines · Zhi Wang
Quoted 153 lines · On Fri, 24 Feb 2023 13:37:48 +0100 Alexander Graf <[email protected]> wrote:
Quoted 36 lines · Michael Roth

From: Tom Lendacky <[email protected]>

Add support for the SEV-SNP AP Creation NAE event. This allows SEV-SNP guests to alter the register state of the APs on their own. This allows the guest a way of simulating INIT-SIPI.

A new event, KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, is created and used so as to avoid updating the VMSA pointer while the vCPU is running.

For CREATE
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID. The GPA is saved in the svm struct of the target vCPU, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to the vCPU and then the vCPU is kicked.

For CREATE_ON_INIT:
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID the next time an INIT is performed. The GPA is saved in the svm struct of the target vCPU.

For DESTROY:
The guest indicates it wishes to stop the vCPU. The GPA is cleared from the svm struct, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to vCPU and then the vCPU is kicked.

The KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event handler will be invoked as a result of the event or as a result of an INIT. The handler sets the vCPU to the KVM_MP_STATE_UNINITIALIZED state, so that any errors will leave the vCPU as not runnable. Any previous VMSA pages that were installed as part of an SEV-SNP AP Creation NAE event are un-pinned. If a new VMSA is to be installed, the VMSA guest page is pinned and set as the VMSA in the vCPU VMCB and the vCPU state is set to KVM_MP_STATE_RUNNABLE. If a new VMSA is not to be installed, the VMSA is cleared in the vCPU VMCB and the vCPU state is left as KVM_MP_STATE_UNINITIALIZED to prevent it from being run.

Quoted 5 lines
[mdr: add handling for restrictedmem]

What is the intended boot sequence for SEV-SNP guests? FWIW with this interface in place, guests will typically use in-guest VMSA pages to hold secondary vcpu state. But that means we're now allocating 4kb of memory for every vcpu that we create that will be for most of the guest's lifetime superfluous.

Wouldn't it make more sense to have a model where we only allocate the VMSA for the boot CPU and leave secondary allocation to the guest? We already need firmware changes for SEV-SNP - may as well make this one more.

[...]

Quoted 7 lines
arch/x86/kvm/svm/sev.c +7 -0
+
+static int sev_snp_ap_creation(struct vcpu_svm *svm)
+{
+       struct kvm_sev_info *sev = &to_kvm_svm(svm->vcpu.kvm)->sev_info;
+       struct kvm_vcpu *vcpu = &svm->vcpu;
+       struct kvm_vcpu *target_vcpu;
+       struct vcpu_svm *target_svm;

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3688

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+       unsigned int request;
+       unsigned int apic_id;
+       bool kick;
+       int ret;
+
+       request = lower_32_bits(svm->vmcb->control.exit_info_1);
+       apic_id = upper_32_bits(svm->vmcb->control.exit_info_1);
+
+       /* Validate the APIC ID */
+       target_vcpu = kvm_get_vcpu_by_id(vcpu->kvm, apic_id);

Out of curiosity: The target CPU can be my own vCPU, right?

Quoted 44 lines
arch/x86/kvm/svm/sev.c +44 -0
+       if (!target_vcpu) {
+               vcpu_unimpl(vcpu, "vmgexit: invalid AP APIC ID [%#x] from guest\n",
+                           apic_id);
+               return -EINVAL;
+       }
+
+       ret = 0;
+
+       target_svm = to_svm(target_vcpu);
+
+       /*
+        * The target vCPU is valid, so the vCPU will be kicked unless the
+        * request is for CREATE_ON_INIT. For any errors at this stage, the
+        * kick will place the vCPU in an non-runnable state.
+        */
+       kick = true;
+
+       mutex_lock(&target_svm->sev_es.snp_vmsa_mutex);
+
+       target_svm->sev_es.snp_vmsa_gpa = INVALID_PAGE;
+       target_svm->sev_es.snp_ap_create = true;
+
+       /* Interrupt injection mode shouldn't change for AP creation */
+       if (request < SVM_VMGEXIT_AP_DESTROY) {
+               u64 sev_features;
+
+               sev_features = vcpu->arch.regs[VCPU_REGS_RAX];
+               sev_features ^= sev->sev_features;
+               if (sev_features & SVM_SEV_FEAT_INT_INJ_MODES) {
+                       vcpu_unimpl(vcpu, "vmgexit: invalid AP injection mode [%#lx] from guest\n",
+                                   vcpu->arch.regs[VCPU_REGS_RAX]);
+                       ret = -EINVAL;
+                       goto out;
+               }
+       }
+
+       switch (request) {
+       case SVM_VMGEXIT_AP_CREATE_ON_INIT:
+               kick = false;
+               fallthrough;
+       case SVM_VMGEXIT_AP_CREATE:
+               if (!page_address_valid(vcpu, svm->vmcb->control.exit_info_2)) {
+                       vcpu_unimpl(vcpu, "vmgexit: invalid AP VMSA address [%#llx] from guest\n",
+                                   svm->vmcb->control.exit_info_2);

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3742

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+                       ret = -EINVAL;
+                       goto out;
+               }
+
+               /*
+                * Malicious guest can RMPADJUST a large page into VMSA which
+                * will hit the SNP erratum where the CPU will incorrectly signal
+                * an RMP violation #PF if a hugepage collides with the RMP entry
+                * of VMSA page, reject the AP CREATE request if VMSA address from
+                * guest is 2M aligned.

This will break genuine current Linux kernels that just happen to allocate a guest page, no? In fact, given enough vCPUs you're almost guaranteed to hit an aligned structure somewhere. What is the guest supposed to do in that situation?

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3754

Quoted 12 lines
arch/x86/kvm/svm/sev.c +12 -0
+                */
+               if (IS_ALIGNED(svm->vmcb->control.exit_info_2, PMD_SIZE)) {
+                       vcpu_unimpl(vcpu,
+                                   "vmgexit: AP VMSA address [%llx] from guest is unsafe as it is 2M aligned\n",
+                                   svm->vmcb->control.exit_info_2);
+                       ret = -EINVAL;
+                       goto out;
+               }
+
+               target_svm->sev_es.snp_vmsa_gpa = svm->vmcb->control.exit_info_2;
+               break;
+       case SVM_VMGEXIT_AP_DESTROY:

I don't understand the destroy path. Why does this case destroy anything?

Quoted 15 lines

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3766

Quoted 12 lines
arch/x86/kvm/svm/sev.c +12 -0
+               break;
+       default:
+               vcpu_unimpl(vcpu, "vmgexit: invalid AP creation request [%#x] from guest\n",
+                           request);
+               ret = -EINVAL;
+               break;
+       }
+
+out:
+       if (kick) {
+               if (target_vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)
+                       target_vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;

What if the guest AP goes through a create -> destroy -> create cycle? Will it stay runnable while destroyed?

The code is not very straightforward.

1) target_svm->sev_es.snp_vmsa_gpa is set as INVALID_PAGE in the beginning of this function.

2) If a DESTROY is hit in this function, target_svm->sev_es.snp_vmsa_gpa will be left as INVALID_PAGE.

3) At the end of this function, it calls kvm_make_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE).

4) In the vcpu_enter_guest(), the kvm_vcpu_reset()->sev_snp_init_protected_guest_state() ->__sev_snp_init_protected_guest_state() is called.

5) The mp_state is set to KVM_MP_STATE_STOPPED by default and the runtime VMSA is cleared. Then the it will be initialized according to the guest's configuration.

6) As the snp_vmsa_gpa is set as INVALID_PAGE in 1, the mp_state will be left as KVM_MP_STATE_STOPPED.

7) With this code piece:

arch/x86/kvm/x86.c +3 -0
+                       kvm_vcpu_reset(vcpu, true);
+                       if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE)
+                               goto out;
Quoted 1 line

vcpu_enter_guest() bails out.

Thanks a lot Zhi for the detailed explanation! I think this code flow wants to become slightly more obvious. For example, if we just said

  case SVM_VMGEXIT_AP_DESTROY:
    /* This will tell __sev_snp_update_protected_guest_state to unmap the VMSA */ target_svm->sev_es.snp_vmsa_gpa = INVALID_PAGE;
    break;

We'd get a big win in readability with little effort. It makes it immediately obvious where to look for the destroy operation.

Alex

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879

#117 lore raw

Re: [PATCH RFC v8 47/56] KVM: SVM: Support SEV-SNP AP Creation NAE event

Quoted 11 lines · Alexander Graf
Quoted 9 lines · Zhi Wang
Quoted 6 lines · On Fri, 24 Feb 2023 13:37:48 +0100 Alexander Graf <[email protected]> wrote:
Quoted 5 lines · Michael Roth

From: Tom Lendacky <[email protected]>

Add support for the SEV-SNP AP Creation NAE event. This allows SEV-SNP guests to alter the register state of the APs on their own. This allows the guest a way of simulating INIT-SIPI.

<snip>

Quoted 62 lines
Quoted 56 lines
Quoted 16 lines

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3754

Quoted 12 lines
arch/x86/kvm/svm/sev.c +12 -0
+                */
+               if (IS_ALIGNED(svm->vmcb->control.exit_info_2, PMD_SIZE)) {
+                       vcpu_unimpl(vcpu,
+                                   "vmgexit: AP VMSA address [%llx] from guest is unsafe as it is 2M aligned\n",
+                                   svm->vmcb->control.exit_info_2);
+                       ret = -EINVAL;
+                       goto out;
+               }
+
+               target_svm->sev_es.snp_vmsa_gpa = svm->vmcb->control.exit_info_2;
+               break;
+       case SVM_VMGEXIT_AP_DESTROY:

I don't understand the destroy path. Why does this case destroy anything?

Quoted 15 lines

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3766

Quoted 12 lines
arch/x86/kvm/svm/sev.c +12 -0
+               break;
+       default:
+               vcpu_unimpl(vcpu, "vmgexit: invalid AP creation request [%#x] from guest\n",
+                           request);
+               ret = -EINVAL;
+               break;
+       }
+
+out:
+       if (kick) {
+               if (target_vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)
+                       target_vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;

What if the guest AP goes through a create -> destroy -> create cycle? Will it stay runnable while destroyed?

The code is not very straightforward.

1) target_svm->sev_es.snp_vmsa_gpa is set as INVALID_PAGE in the beginning of this function.

2) If a DESTROY is hit in this function, target_svm->sev_es.snp_vmsa_gpa will be left as INVALID_PAGE.

3) At the end of this function, it calls kvm_make_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE).

4) In the vcpu_enter_guest(), the kvm_vcpu_reset()->sev_snp_init_protected_guest_state() ->__sev_snp_init_protected_guest_state() is called.

5) The mp_state is set to KVM_MP_STATE_STOPPED by default and the runtime VMSA is cleared. Then the it will be initialized according to the guest's configuration.

6) As the snp_vmsa_gpa is set as INVALID_PAGE in 1, the mp_state will be left as KVM_MP_STATE_STOPPED.

7) With this code piece:

arch/x86/kvm/x86.c +3 -0
+                       kvm_vcpu_reset(vcpu, true);
+                       if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE)
+                               goto out;
Quoted 1 line

vcpu_enter_guest() bails out.

Thanks a lot Zhi for the detailed explanation! I think this code flow wants to become slightly more obvious. For example, if we just said

Quoted 8 lines

  case SVM_VMGEXIT_AP_DESTROY:
    /* This will tell __sev_snp_update_protected_guest_state to unmap the VMSA */
    target_svm->sev_es.snp_vmsa_gpa = INVALID_PAGE;
    break;

We'd get a big win in readability with little effort. It makes it immediately obvious where to look for the destroy operation.

The target->snp_vmsa_gpa value mainly serves to cache the GPA of the new VMSA up until the point where KVM points the target vCPU's VMCB over to using it as part of sev_snp_init_protected_guest_state(). We want to make sure it is either INVALID_PAGE, or whatever GPA the guest want us to set it to.

Once sev_snp_init_protected_guest_state() processes the update, it will set it back to INVALID_PAGE. So if we initialized it once during VM creation it wouldn't be necessary to keep setting it to INVALID_PAGE at all, except for one case ...

There is a window where the guest could do an AP_CREATE with new GPA, followed immediately by AP_DESTROY. If that AP_DESTROY got processed before the vCPU re-enters the guest, it might instead restart the vCPU (due to taking VALID_PAGE(snp_vmsa_gpa) branch in __sev_snp_update_protected_guest_state()). So for that reason it makes sense to always initialize it to INVALID_PAGE when an AP_CREATION request comes in, to essentially clear any pending updates from a previous pending AP_CREATION for the same vCPU. If we move it to the AP_DESTROY case, but hit a failure elsewhere in sev_snp_ap_creation(), then the calling vCPU will get a #GP, but the target vCPU might get set up with the VMSA for the previous pending request. That might be appropriate though, just because calling vCPU hosed itself doesn't mean a previous valid AP_CREATION request shouldn't go through for target. Hmm...

And having said all that... yes, I guess that basically boils down to INVALID_PAGE being used as an indicator of whether or not to unmap VMSA. I'll try to come up with some wording to better convey all this a bit more clearly.

Thanks,

-Mike

Quoted 17 lines

Alex

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879

#118 lore raw

Re: [PATCH RFC v8 47/56] KVM: SVM: Support SEV-SNP AP Creation NAE event

In reply to Alexander Graf
Quoted 51 lines · Alexander Graf
Quoted 36 lines · Michael Roth

From: Tom Lendacky <[email protected]>

Add support for the SEV-SNP AP Creation NAE event. This allows SEV-SNP guests to alter the register state of the APs on their own. This allows the guest a way of simulating INIT-SIPI.

A new event, KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, is created and used so as to avoid updating the VMSA pointer while the vCPU is running.

For CREATE
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID. The GPA is saved in the svm struct of the target vCPU, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to the vCPU and then the vCPU is kicked.

For CREATE_ON_INIT:
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID the next time an INIT is performed. The GPA is saved in the svm struct of the target vCPU.

For DESTROY:
The guest indicates it wishes to stop the vCPU. The GPA is cleared from the svm struct, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to vCPU and then the vCPU is kicked.

The KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event handler will be invoked as a result of the event or as a result of an INIT. The handler sets the vCPU to the KVM_MP_STATE_UNINITIALIZED state, so that any errors will leave the vCPU as not runnable. Any previous VMSA pages that were installed as part of an SEV-SNP AP Creation NAE event are un-pinned. If a new VMSA is to be installed, the VMSA guest page is pinned and set as the VMSA in the vCPU VMCB and the vCPU state is set to KVM_MP_STATE_RUNNABLE. If a new VMSA is not to be installed, the VMSA is cleared in the vCPU VMCB and the vCPU state is left as KVM_MP_STATE_UNINITIALIZED to prevent it from being run.

Quoted 5 lines
[mdr: add handling for restrictedmem]

What is the intended boot sequence for SEV-SNP guests? FWIW with this interface in place, guests will typically use in-guest VMSA pages to hold secondary vcpu state. But that means we're now allocating 4kb of memory for every vcpu that we create that will be for most of the guest's lifetime superfluous.

Quoted 3 lines

Wouldn't it make more sense to have a model where we only allocate the VMSA for the boot CPU and leave secondary allocation to the guest? We already need firmware changes for SEV-SNP - may as well make this one more.

I don't think we'd necessarily need a firmware change. We could just free original VMSA back to the hypervisor as soon as those APs come online. The down-side to that versus deferring cleaning till guest shutdown is there is some flushing activity (see:
sev_flush_encrypted_page()) that would now likely be occuring during guest boot up where the overhead might be more noticeable. But for SNP the host likely supports X86_FEATURE_SME_COHERENT so the overhead probably isn't that bad.

Quoted 15 lines

[...]

Quoted 12 lines
arch/x86/kvm/svm/sev.c +12 -0
+
+static int sev_snp_ap_creation(struct vcpu_svm *svm)
+{
+       struct kvm_sev_info *sev = &to_kvm_svm(svm->vcpu.kvm)->sev_info;
+       struct kvm_vcpu *vcpu = &svm->vcpu;
+       struct kvm_vcpu *target_vcpu;
+       struct vcpu_svm *target_svm;
+       unsigned int request;
+       unsigned int apic_id;
+       bool kick;
+       int ret;
+
Quoted 8 lines

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3688

Quoted 5 lines
arch/x86/kvm/svm/sev.c +5 -0
+       request = lower_32_bits(svm->vmcb->control.exit_info_1);
+       apic_id = upper_32_bits(svm->vmcb->control.exit_info_1);
+
+       /* Validate the APIC ID */
+       target_vcpu = kvm_get_vcpu_by_id(vcpu->kvm, apic_id);

Out of curiosity: The target CPU can be my own vCPU, right?

I don't think that would be the normal behavior, but maybe with some care it's possible for a guest to do things that way. I haven't seen anything strictly prohibiting this in the relevant specs.

Quoted 54 lines
Quoted 54 lines
arch/x86/kvm/svm/sev.c +52 -0
+       if (!target_vcpu) {
+               vcpu_unimpl(vcpu, "vmgexit: invalid AP APIC ID [%#x] from guest\n",
+                           apic_id);
+               return -EINVAL;
+       }
+
+       ret = 0;
+
+       target_svm = to_svm(target_vcpu);
+
+       /*
+        * The target vCPU is valid, so the vCPU will be kicked unless the
+        * request is for CREATE_ON_INIT. For any errors at this stage, the
+        * kick will place the vCPU in an non-runnable state.
+        */
+       kick = true;
+
+       mutex_lock(&target_svm->sev_es.snp_vmsa_mutex);
+
+       target_svm->sev_es.snp_vmsa_gpa = INVALID_PAGE;
+       target_svm->sev_es.snp_ap_create = true;
+
+       /* Interrupt injection mode shouldn't change for AP creation */
+       if (request < SVM_VMGEXIT_AP_DESTROY) {
+               u64 sev_features;
+
+               sev_features = vcpu->arch.regs[VCPU_REGS_RAX];
+               sev_features ^= sev->sev_features;
+               if (sev_features & SVM_SEV_FEAT_INT_INJ_MODES) {
+                       vcpu_unimpl(vcpu, "vmgexit: invalid AP injection mode [%#lx] from guest\n",
+                                   vcpu->arch.regs[VCPU_REGS_RAX]);
+                       ret = -EINVAL;
+                       goto out;
+               }
+       }
+
+       switch (request) {
+       case SVM_VMGEXIT_AP_CREATE_ON_INIT:
+               kick = false;
+               fallthrough;
+       case SVM_VMGEXIT_AP_CREATE:
+               if (!page_address_valid(vcpu, svm->vmcb->control.exit_info_2)) {
+                       vcpu_unimpl(vcpu, "vmgexit: invalid AP VMSA address [%#llx] from guest\n",
+                                   svm->vmcb->control.exit_info_2);
+                       ret = -EINVAL;
+                       goto out;
+               }
+
+               /*
+                * Malicious guest can RMPADJUST a large page into VMSA which
+                * will hit the SNP erratum where the CPU will incorrectly signal
+                * an RMP violation #PF if a hugepage collides with the RMP entry
Quoted 8 lines

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3742

Quoted 2 lines
arch/x86/kvm/svm/sev.c +2 -0
+                * of VMSA page, reject the AP CREATE request if VMSA address from
+                * guest is 2M aligned.

This will break genuine current Linux kernels that just happen to allocate a guest page, no? In fact, given enough vCPUs you're almost guaranteed to hit an aligned structure somewhere. What is the guest supposed to do in that situation?

The initial SNP support for guest kernels already made use of snp_alloc_vmsa_page() to do the appropriate workaround to avoid allocating 2MB-aligned VMSA pages.

-Mike

Quoted 12 lines

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879

maintainer
#119 lore raw

Re: [PATCH RFC v8 47/56] KVM: SVM: Support SEV-SNP AP Creation NAE event

Quoted 56 lines · Michael Roth
Quoted 51 lines · Alexander Graf
Quoted 36 lines · Michael Roth

From: Tom Lendacky <[email protected]>

Add support for the SEV-SNP AP Creation NAE event. This allows SEV-SNP guests to alter the register state of the APs on their own. This allows the guest a way of simulating INIT-SIPI.

A new event, KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, is created and used so as to avoid updating the VMSA pointer while the vCPU is running.

For CREATE
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID. The GPA is saved in the svm struct of the target vCPU, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to the vCPU and then the vCPU is kicked.

For CREATE_ON_INIT:
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID the next time an INIT is performed. The GPA is saved in the svm struct of the target vCPU.

For DESTROY:
The guest indicates it wishes to stop the vCPU. The GPA is cleared from the svm struct, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to vCPU and then the vCPU is kicked.

The KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event handler will be invoked as a result of the event or as a result of an INIT. The handler sets the vCPU to the KVM_MP_STATE_UNINITIALIZED state, so that any errors will leave the vCPU as not runnable. Any previous VMSA pages that were installed as part of an SEV-SNP AP Creation NAE event are un-pinned. If a new VMSA is to be installed, the VMSA guest page is pinned and set as the VMSA in the vCPU VMCB and the vCPU state is set to KVM_MP_STATE_RUNNABLE. If a new VMSA is not to be installed, the VMSA is cleared in the vCPU VMCB and the vCPU state is left as KVM_MP_STATE_UNINITIALIZED to prevent it from being run.

Quoted 5 lines
[mdr: add handling for restrictedmem]

What is the intended boot sequence for SEV-SNP guests? FWIW with this interface in place, guests will typically use in-guest VMSA pages to hold secondary vcpu state. But that means we're now allocating 4kb of memory for every vcpu that we create that will be for most of the guest's lifetime superfluous.

Quoted 3 lines

Wouldn't it make more sense to have a model where we only allocate the VMSA for the boot CPU and leave secondary allocation to the guest? We already need firmware changes for SEV-SNP - may as well make this one more.

Quoted 8 lines

I don't think we'd necessarily need a firmware change. We could just free original VMSA back to the hypervisor as soon as those APs come online. The down-side to that versus deferring cleaning till guest shutdown is there is some flushing activity (see:
sev_flush_encrypted_page()) that would now likely be occuring during guest boot up where the overhead might be more noticeable. But for SNP the host likely supports X86_FEATURE_SME_COHERENT so the overhead probably isn't that bad.

Currently, OVMF code will perform a broadcast IPI to start all the APs because it doesn't know the APIC IDs until they start for the first time. Until the APIC IDs are known, the guest BSP can't create the VMSAs.

However, a new GHCB event is in plan to retrieve the APIC IDs for the guest. Once that is in place, then you could create just a single VMSA for the BSP and then allow the guest to create the remainder (the current OVMF PoC patches to support an SVSM do this). The VMM would have to know that the hypervisor and the firmware both support that, though. That could be advertised as part of the GUID table of the firmware (in the case of OVMF) and as a capability from KVM.

Thanks,
Tom

Quoted 110 lines
Quoted 16 lines

[...]

Quoted 12 lines
arch/x86/kvm/svm/sev.c +12 -0
+
+static int sev_snp_ap_creation(struct vcpu_svm *svm)
+{
+       struct kvm_sev_info *sev = &to_kvm_svm(svm->vcpu.kvm)->sev_info;
+       struct kvm_vcpu *vcpu = &svm->vcpu;
+       struct kvm_vcpu *target_vcpu;
+       struct vcpu_svm *target_svm;
+       unsigned int request;
+       unsigned int apic_id;
+       bool kick;
+       int ret;
+
Quoted 8 lines

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3688

Quoted 5 lines
arch/x86/kvm/svm/sev.c +5 -0
+       request = lower_32_bits(svm->vmcb->control.exit_info_1);
+       apic_id = upper_32_bits(svm->vmcb->control.exit_info_1);
+
+       /* Validate the APIC ID */
+       target_vcpu = kvm_get_vcpu_by_id(vcpu->kvm, apic_id);

Out of curiosity: The target CPU can be my own vCPU, right?

I don't think that would be the normal behavior, but maybe with some care it's possible for a guest to do things that way. I haven't seen anything strictly prohibiting this in the relevant specs.

Quoted 54 lines
Quoted 54 lines
arch/x86/kvm/svm/sev.c +52 -0
+       if (!target_vcpu) {
+               vcpu_unimpl(vcpu, "vmgexit: invalid AP APIC ID [%#x] from guest\n",
+                           apic_id);
+               return -EINVAL;
+       }
+
+       ret = 0;
+
+       target_svm = to_svm(target_vcpu);
+
+       /*
+        * The target vCPU is valid, so the vCPU will be kicked unless the
+        * request is for CREATE_ON_INIT. For any errors at this stage, the
+        * kick will place the vCPU in an non-runnable state.
+        */
+       kick = true;
+
+       mutex_lock(&target_svm->sev_es.snp_vmsa_mutex);
+
+       target_svm->sev_es.snp_vmsa_gpa = INVALID_PAGE;
+       target_svm->sev_es.snp_ap_create = true;
+
+       /* Interrupt injection mode shouldn't change for AP creation */
+       if (request < SVM_VMGEXIT_AP_DESTROY) {
+               u64 sev_features;
+
+               sev_features = vcpu->arch.regs[VCPU_REGS_RAX];
+               sev_features ^= sev->sev_features;
+               if (sev_features & SVM_SEV_FEAT_INT_INJ_MODES) {
+                       vcpu_unimpl(vcpu, "vmgexit: invalid AP injection mode [%#lx] from guest\n",
+                                   vcpu->arch.regs[VCPU_REGS_RAX]);
+                       ret = -EINVAL;
+                       goto out;
+               }
+       }
+
+       switch (request) {
+       case SVM_VMGEXIT_AP_CREATE_ON_INIT:
+               kick = false;
+               fallthrough;
+       case SVM_VMGEXIT_AP_CREATE:
+               if (!page_address_valid(vcpu, svm->vmcb->control.exit_info_2)) {
+                       vcpu_unimpl(vcpu, "vmgexit: invalid AP VMSA address [%#llx] from guest\n",
+                                   svm->vmcb->control.exit_info_2);
+                       ret = -EINVAL;
+                       goto out;
+               }
+
+               /*
+                * Malicious guest can RMPADJUST a large page into VMSA which
+                * will hit the SNP erratum where the CPU will incorrectly signal
+                * an RMP violation #PF if a hugepage collides with the RMP entry
Quoted 8 lines

arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3742

Quoted 2 lines
arch/x86/kvm/svm/sev.c +2 -0
+                * of VMSA page, reject the AP CREATE request if VMSA address from
+                * guest is 2M aligned.

This will break genuine current Linux kernels that just happen to allocate a guest page, no? In fact, given enough vCPUs you're almost guaranteed to hit an aligned structure somewhere. What is the guest supposed to do in that situation?

The initial SNP support for guest kernels already made use of snp_alloc_vmsa_page() to do the appropriate workaround to avoid allocating 2MB-aligned VMSA pages.

-Mike

Quoted 12 lines

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879

#120 lore raw

RFC PATCH v8 48/56 KVM: SVM: Add SNP-specific handling for memory attribute updates

In reply to Michael Roth

This will handle RMP table updates and direct map changes needed for page state conversions requested by userspace.

---
 arch/x86/kvm/svm/sev.c | 126 +++++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/svm/svm.c |   1 +
 arch/x86/kvm/svm/svm.h |   2 +
 3 files changed, 129 insertions(+)
arch/x86/kvm/svm/sev.c +126 -0
index b2f1a12685ed..73d614c538da 100644
@@ -3381,6 +3381,31 @@ static int snp_rmptable_psmash(struct kvm *kvm, kvm_pfn_t pfn)
 	return psmash(pfn);
 }
 
+static int snp_make_page_shared(struct kvm *kvm, gpa_t gpa, kvm_pfn_t pfn, int level)
+{
+	int rc, rmp_level;
+
+	rc = snp_lookup_rmpentry(pfn, &rmp_level);
+	if (rc < 0)
+		return -EINVAL;
+
+	/* If page is not assigned then do nothing */
+	if (!rc)
+		return 0;
+
+	/*
+	 * Is the page part of an existing 2MB RMP entry ? Split the 2MB into
+	 * multiple of 4K-page before making the memory shared.
+	 */
+	if (level == PG_LEVEL_4K && rmp_level == PG_LEVEL_2M) {
+		rc = snp_rmptable_psmash(kvm, pfn);
+		if (rc)
+			return rc;
+	}
+
+	return rmp_make_shared(pfn, level);
+}
+
 /*
  * TODO: need to get the value set by userspace in vcpu->run->vmgexit.ghcb_msr
  * and process that here accordingly.
@@ -4373,3 +4398,104 @@ void handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code)
 	kvm_zap_gfn_range(kvm, gfn, gfn + PTRS_PER_PMD);
 	put_page(pfn_to_page(pfn));
 }
+
+static inline u8 order_to_level(int order)
+{
+	BUILD_BUG_ON(KVM_MAX_HUGEPAGE_LEVEL > PG_LEVEL_1G);
+
+	if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_1G))
+		return PG_LEVEL_1G;
+
+	if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_2M))
+		return PG_LEVEL_2M;
+
+	return PG_LEVEL_4K;
+}
+
+int sev_update_mem_attr(struct kvm_memory_slot *slot, unsigned int attr,
+			gfn_t start, gfn_t end)
+{
+	struct kvm_sev_info *sev = &to_kvm_svm(slot->kvm)->sev_info;
+	enum psc_op op = (attr & KVM_MEMORY_ATTRIBUTE_PRIVATE) ? SNP_PAGE_STATE_PRIVATE
+							       : SNP_PAGE_STATE_SHARED;
+	gfn_t gfn = start;
+
+	pr_debug("%s: GFN 0x%llx - 0x%llx, op: %d\n", __func__, start, end, op);
+
+	if (!sev_snp_guest(slot->kvm))
+		return 0;
+
+	if (!kvm_slot_can_be_private(slot)) {
+		pr_err_ratelimited("%s: memslot for gfn: 0x%llx is not private.\n",
+				   __func__, gfn);
+		return -EPERM;
+	}
+
+	while (gfn < end) {
+		kvm_pfn_t pfn;
+		int level = PG_LEVEL_4K; /* TODO: take actual order into account */
+		gpa_t gpa = gfn_to_gpa(gfn);
+		int npages = 1;
+		int order;
+		int rc;
+
+		/*
+		 * No work to do if there was never a page allocated from private
+		 * memory. If there was a page that was deallocated previously,
+		 * the invalidation notifier should have restored the page to
+		 * shared.
+		 */
+		rc = kvm_restrictedmem_get_pfn(slot, gfn, &pfn, &order);
+		if (rc) {
+			pr_warn_ratelimited("%s: failed to retrieve gfn 0x%llx from private FD\n",
+					    __func__, gfn);
+			gfn++;
+			continue;
+		}
+
+		/*
+		 * TODO: The RMP entry's hugepage bit is ignored for
+		 * shared/unassigned pages. Either handle looping through each
+		 * sub-page as part of snp_make_page_shared(), or remove the
+		 * level argument.
+		 */
+		if (op == SNP_PAGE_STATE_PRIVATE && order &&
+		    IS_ALIGNED(gfn, 1 << order) && (gfn + (1 << order)) <= end) {
+			level = order_to_level(order);
+			npages = 1 << order;
+		}
+
+		/*
+		 * Grab the PFN from private memslot and update the RMP entry.
+		 * It may be worthwhile to go ahead and map it into the TDP at
+		 * this point if the guest is doing lazy acceptance, but for
+		 * up-front bulk shared->private conversions it's not likely
+		 * the guest will try to access the PFN any time soon, so for
+		 * now just take the let KVM MMU handle faulting it on the next
+		 * access.
+		 */
+		switch (op) {
+		case SNP_PAGE_STATE_SHARED:
+			rc = snp_make_page_shared(slot->kvm, gpa, pfn, level);
+			break;
+		case SNP_PAGE_STATE_PRIVATE:
+			rc = rmp_make_private(pfn, gpa, level, sev->asid, false);
+			break;
+		default:
+			rc = PSC_INVALID_ENTRY;
+			break;
+		}
+
+		put_page(pfn_to_page(pfn));
+
+		if (rc) {
+			pr_err_ratelimited("%s: failed op %d gpa %llx pfn %llx level %d rc %d\n",
+					   __func__, op, gpa, pfn, level, rc);
+			return -EINVAL;
+		}
+
+		gfn += npages;
+	}
+
+	return 0;
+}
arch/x86/kvm/svm/svm.c +1 -0
index 539926b07ee5..e2edc4700e55 100644
@@ -4860,6 +4860,7 @@ static struct kvm_x86_ops svm_x86_ops __initdata = {
 	.alloc_apic_backing_page = svm_alloc_apic_backing_page,
 
 	.adjust_mapping_level = sev_adjust_mapping_level,
+	.update_mem_attr = sev_update_mem_attr,
 };
 
 /*
arch/x86/kvm/svm/svm.h +2 -0
index 37bd7b728d52..50a2bcaf3fd7 100644
@@ -725,6 +725,8 @@ struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu);
 void sev_adjust_mapping_level(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int *level);
 void handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code);
 void sev_snp_init_protected_guest_state(struct kvm_vcpu *vcpu);
+int sev_update_mem_attr(struct kvm_memory_slot *slot, unsigned int attr,
+			gfn_t start, gfn_t end);
 
 /* vmenter.S */
 
Signature · 1 line
2.25.1
#121 lore raw

Re: [PATCH RFC v8 48/56] KVM: SVM: Add SNP-specific handling for memory attribute updates

arch/x86/kvm/svm/sev.c void handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code) · line 4466

Quoted 11 lines · Michael Roth
arch/x86/kvm/svm/sev.c +11 -0
+		/*
+		 * TODO: The RMP entry's hugepage bit is ignored for
+		 * shared/unassigned pages. Either handle looping through each
+		 * sub-page as part of snp_make_page_shared(), or remove the
+		 * level argument.
+		 */
+		if (op == SNP_PAGE_STATE_PRIVATE && order &&
+		    IS_ALIGNED(gfn, 1 << order) && (gfn + (1 << order)) <= end) {
+			level = order_to_level(order);
+			npages = 1 << order;
+		}

That's a wee bit obtuse.

First of all, I assume that the 'RFC' is because of these TODOs and they won't survive to the point when you ask for this to be merged.

BTW, what keeps the restrictedmem_get_page() offset and the gfn aligned?

Let's start with this:

arch/x86/kvm/svm/sev.c void handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code) · line 4413

Quoted 12 lines
arch/x86/kvm/svm/sev.c +12 -0
+static inline u8 order_to_level(int order)
+{
+	BUILD_BUG_ON(KVM_MAX_HUGEPAGE_LEVEL > PG_LEVEL_1G);
+
+	if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_1G))
+		return PG_LEVEL_1G;
+
+	if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_2M))
+		return PG_LEVEL_2M;
+
+	return PG_LEVEL_4K;
+}

Right now, 'order' comes only from restrictedmem_get_page(), which I dug out of:

Quoted 1 line

https://github.com/mdroth/linux/commit/c6792672cd11737fd255dff10b2d5b6bccc626a8

That order is *only* filled in by THPs. That makes the PG_LEVEL_1G stuff here kinda silly. I guess it might be seen as thorough, but it's dead code. I'd probably just make this work on order==9 || order==0 and warn on anything else.

I'd also highly recommend some comments about how racy this all is. I guess it probably works, but it would be good to add some comments about page splits and collapsing.

It's also not obvious why this only cares about private pages.

Anyway, this is the exact kind of thing where I really like a well-commented helper:

bool can_install_large_rmp_entry(gfn, order)

{
	// small pages, blah blah
	if (!order)
		return false;

	// The region being updated must be aligned
	if (!IS_ALIGNED(gfn, 1 << order))
		return false;
	// ... and fit
	if (gfn + (1 << order)) > end)
		return false;

	return true;	
}

Which gets used like this:

	if (op == SNP_PAGE_STATE_PRIVATE &&
	    can_install_large_rmp_entry(gfn, order)) {
		level = ...
	}
#122 lore raw

Re: [PATCH RFC v8 48/56] KVM: SVM: Add SNP-specific handling for memory attribute updates

Quoted 15 lines · Dave Hansen

arch/x86/kvm/svm/sev.c void handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code) · line 4466

Quoted 11 lines · Michael Roth
arch/x86/kvm/svm/sev.c +11 -0
+		/*
+		 * TODO: The RMP entry's hugepage bit is ignored for
+		 * shared/unassigned pages. Either handle looping through each
+		 * sub-page as part of snp_make_page_shared(), or remove the
+		 * level argument.
+		 */
+		if (op == SNP_PAGE_STATE_PRIVATE && order &&
+		    IS_ALIGNED(gfn, 1 << order) && (gfn + (1 << order)) <= end) {
+			level = order_to_level(order);
+			npages = 1 << order;
+		}

That's a wee bit obtuse.

Quoted 2 lines

First of all, I assume that the 'RFC' is because of these TODOs and they won't survive to the point when you ask for this to be merged.

Yes, will make sure to have all the TODOs in the tree addressed before dropping the RFC tag.

Quoted 2 lines

BTW, what keeps the restrictedmem_get_page() offset and the gfn aligned?

I don't think anything enforces that currently, but there is a TODO in the UPM v10 patchset to enforce that:

https://github.com/AMDESE/linux/commit/5c86db7f98701f614c48946b733f2542c962f139#diff-e7514a224c92c2e47224f99919405a37ee7edc4612953135229cfb6e07a680d8R2131

So currently this patch relies on the following:

- the fact that the memslot alignment/sizes for a standard x86 guest's associated memory regions are 2M-aligned, so when they are bound to a restrictedmem FD they are naturally packed in at restrictedmem offsets that are also 2M-aligned. But of course we can't assume userspace will live up to this assumption and need the above TODO in KVM to enforce this when registering new memslots.

- that restrictedmem/shmem will ensure that THPs are only allocated for restrictedmem offsets that are 2M-aligned. I think this enforcement happens in shmem_alloc_hugefolio().

which both seem to hold in testing. But it's probably a good idea to add an explicit check for this, at least until KVM implements something to enforce this earlier in guest life-cycle.

Quoted 19 lines

Let's start with this:

arch/x86/kvm/svm/sev.c void handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code) · line 4413

Quoted 12 lines
arch/x86/kvm/svm/sev.c +12 -0
+static inline u8 order_to_level(int order)
+{
+	BUILD_BUG_ON(KVM_MAX_HUGEPAGE_LEVEL > PG_LEVEL_1G);
+
+	if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_1G))
+		return PG_LEVEL_1G;
+
+	if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_2M))
+		return PG_LEVEL_2M;
+
+	return PG_LEVEL_4K;
+}

Right now, 'order' comes only from restrictedmem_get_page(), which I dug out of:

Quoted 6 lines
Quoted 1 line

https://github.com/mdroth/linux/commit/c6792672cd11737fd255dff10b2d5b6bccc626a8

That order is *only* filled in by THPs. That makes the PG_LEVEL_1G stuff here kinda silly. I guess it might be seen as thorough, but it's dead code. I'd probably just make this work on order==9 || order==0 and warn on anything else.

Ok, makes sense.

Quoted 4 lines

I'd also highly recommend some comments about how racy this all is. I guess it probably works, but it would be good to add some comments about page splits and collapsing.

Collapsing while in this code path should be ok since the 4K sub-pages will just end up getting mapped as 4K in RMP table. KVM MMU will then map them into nested page table as 4K as well and we'll get non-optimal performance, but things should otherwise work.

Splitting is a similar story: if we map as 2M in RMP table, and then afterward the page gets split, then KVM MMU during fault time would map the pages in the NPT as 4K, and when the guest attempts to access private pages of this sort they'll generate a nested page fault with PFERR_GUEST_RMP_BIT and PFERR_GUEST_SIZEM_BIT set, and the code in handle_rmp_page_fault() will issue a PSMASH instruction to split the 2M RMP entry into 512 4K RMP entries.

Will add some comments around this.

Quoted 2 lines

It's also not obvious why this only cares about private pages.

Mainly because the shared memory that actually get mapped into the guest is always shared in the RMP table. It is normal VMA memory that is not allocated by UPM/restrictedmem. We will never attempt to make them private, so there is never a need to bother with switching them back to shared.

So we only need to handle RMP updates for the UPM/restrictedmem PFNs. Obviously for shared->private conversion before mapping it into the guest, but also for private->shared conversion since we will still get RMP check failures if we try to leave the PFNs as private in the RMP table and map the above-mentioned VMA memory into the guest instead.

Will add some more comments around this.

Quoted 20 lines

Anyway, this is the exact kind of thing where I really like a well-commented helper:

bool can_install_large_rmp_entry(gfn, order)

{
	// small pages, blah blah
	if (!order)
		return false;

	// The region being updated must be aligned
	if (!IS_ALIGNED(gfn, 1 << order))
		return false;
	// ... and fit
	if (gfn + (1 << order)) > end)
		return false;

	return true;	
}
Quoted 6 lines

Which gets used like this:

	if (op == SNP_PAGE_STATE_PRIVATE &&
	    can_install_large_rmp_entry(gfn, order)) {
		level = ...
	}

Makes sense, will implement something along these lines.

Thanks!

-Mike

#123 lore raw

RFC PATCH v8 49/56 KVM: SVM: Implement .fault_is_private callback for SNP

In reply to Michael Roth

KVM MMU will use this to determine whether an #NPF should be serviced with restricted memory or not.

---
 arch/x86/kvm/svm/sev.c | 10 ++++++++++
 arch/x86/kvm/svm/svm.c |  1 +
 arch/x86/kvm/svm/svm.h |  2 ++
 3 files changed, 13 insertions(+)
arch/x86/kvm/svm/sev.c +10 -0
index 73d614c538da..7a74a92cb39a 100644
@@ -4499,3 +4499,13 @@ int sev_update_mem_attr(struct kvm_memory_slot *slot, unsigned int attr,
 
 	return 0;
 }
+
+bool sev_fault_is_private(struct kvm *kvm, gpa_t gpa, u64 error_code, bool *private_fault)
+{
+	if (!sev_snp_guest(kvm))
+		return false;
+
+	*private_fault = (error_code & PFERR_GUEST_ENC_MASK) ? true : false;
+
+	return true;
+}
arch/x86/kvm/svm/svm.c +1 -0
index e2edc4700e55..18e4a6c17d11 100644
@@ -4861,6 +4861,7 @@ static struct kvm_x86_ops svm_x86_ops __initdata = {
 
 	.adjust_mapping_level = sev_adjust_mapping_level,
 	.update_mem_attr = sev_update_mem_attr,
+	.fault_is_private = sev_fault_is_private,
 };
 
 /*
arch/x86/kvm/svm/svm.h +2 -0
index 50a2bcaf3fd7..97038afa8020 100644
@@ -728,6 +728,8 @@ void sev_snp_init_protected_guest_state(struct kvm_vcpu *vcpu);
 int sev_update_mem_attr(struct kvm_memory_slot *slot, unsigned int attr,
 			gfn_t start, gfn_t end);
 
+bool sev_fault_is_private(struct kvm *kvm, gpa_t gpa, u64 error_code, bool *private_fault);
+
 /* vmenter.S */
 
 void __svm_sev_es_vcpu_run(struct vcpu_svm *svm, bool spec_ctrl_intercepted);
Signature · 1 line
2.25.1
#124 lore raw

RFC PATCH v8 50/56 KVM: SEV: Handle restricted memory invalidations for SNP

In reply to Michael Roth

Implement a platform hook to do the work of restoring the direct map entries and cleaning up RMP table entries for restricted memory that is being freed back to the host.

---
 arch/x86/kvm/svm/sev.c | 62 ++++++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/svm/svm.c |  1 +
 arch/x86/kvm/svm/svm.h |  1 +
 3 files changed, 64 insertions(+)
arch/x86/kvm/svm/sev.c +62 -0
index 7a74a92cb39a..bedec90d034f 100644
@@ -4509,3 +4509,65 @@ bool sev_fault_is_private(struct kvm *kvm, gpa_t gpa, u64 error_code, bool *priv
 
 	return true;
 }
+
+void sev_invalidate_private_range(struct kvm_memory_slot *slot, gfn_t start, gfn_t end)
+{
+	gfn_t gfn = start;
+
+	if (!sev_snp_guest(slot->kvm))
+		return;
+
+	if (!kvm_slot_can_be_private(slot)) {
+		pr_warn_ratelimited("SEV: Memslot for GFN: 0x%llx is not private.\n",
+				    gfn);
+		return;
+	}
+
+	while (gfn <= end) {
+		gpa_t gpa = gfn_to_gpa(gfn);
+		int level = PG_LEVEL_4K;
+		int order, rc;
+		kvm_pfn_t pfn;
+
+		rc = kvm_restrictedmem_get_pfn(slot, gfn, &pfn, &order);
+		if (rc) {
+			pr_warn_ratelimited("SEV: Failed to retrieve restricted PFN for GFN 0x%llx, rc: %d\n",
+					    gfn, rc);
+			gfn++;
+			continue;
+		}
+
+		if (order) {
+			int rmp_level;
+
+			if (IS_ALIGNED(gpa, page_level_size(PG_LEVEL_2M)) &&
+			    gpa + page_level_size(PG_LEVEL_2M) <= gfn_to_gpa(end))
+				level = PG_LEVEL_2M;
+			else
+				pr_debug("%s: GPA 0x%llx is not aligned to 2M, skipping 2M directmap restoration\n",
+					 __func__, gpa);
+
+			/*
+			 * TODO: It may still be possible to restore 2M mapping here,
+			 * but keep it simple for now.
+			 */
+			if (level == PG_LEVEL_2M &&
+			    (!snp_lookup_rmpentry(pfn, &rmp_level) || rmp_level == PG_LEVEL_4K)) {
+				pr_debug("%s: PFN 0x%llx is not mapped as 2M private range, skipping 2M directmap restoration\n",
+					 __func__, pfn);
+				level = PG_LEVEL_4K;
+			}
+		}
+
+		pr_debug("%s: GPA %llx PFN %llx order %d level %d\n",
+			 __func__, gpa, pfn, order, level);
+		rc = snp_make_page_shared(slot->kvm, gpa, pfn, level);
+		if (rc)
+			pr_err("SEV: Failed to restore page to shared, GPA: 0x%llx PFN: 0x%llx order: %d rc: %d\n",
+			       gpa, pfn, order, rc);
+
+		gfn += page_level_size(level) >> PAGE_SHIFT;
+		put_page(pfn_to_page(pfn));
+		cond_resched();
+	}
+}
arch/x86/kvm/svm/svm.c +1 -0
index 18e4a6c17d11..3fe5f13b5f3a 100644
@@ -4862,6 +4862,7 @@ static struct kvm_x86_ops svm_x86_ops __initdata = {
 	.adjust_mapping_level = sev_adjust_mapping_level,
 	.update_mem_attr = sev_update_mem_attr,
 	.fault_is_private = sev_fault_is_private,
+	.invalidate_restricted_mem = sev_invalidate_private_range,
 };
 
 /*
arch/x86/kvm/svm/svm.h +1 -0
index 97038afa8020..857b674e68f0 100644
@@ -727,6 +727,7 @@ void handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code);
 void sev_snp_init_protected_guest_state(struct kvm_vcpu *vcpu);
 int sev_update_mem_attr(struct kvm_memory_slot *slot, unsigned int attr,
 			gfn_t start, gfn_t end);
+void sev_invalidate_private_range(struct kvm_memory_slot *slot, gfn_t start, gfn_t end);
 
 bool sev_fault_is_private(struct kvm *kvm, gpa_t gpa, u64 error_code, bool *private_fault);
 
Signature · 1 line
2.25.1
#125 lore raw

Re: [PATCH RFC v8 50/56] KVM: SEV: Handle restricted memory invalidations for SNP

Quoted 23 lines · On Mon, 20 Feb 2023 12:38:41 -0600 Michael Roth <[email protected]> wrote:

Implement a platform hook to do the work of restoring the direct map entries and cleaning up RMP table entries for restricted memory that is being freed back to the host.

---
 arch/x86/kvm/svm/sev.c | 62 ++++++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/svm/svm.c |  1 +
 arch/x86/kvm/svm/svm.h |  1 +
 3 files changed, 64 insertions(+)
arch/x86/kvm/svm/sev.c +4 -0
index 7a74a92cb39a..bedec90d034f 100644
@@ -4509,3 +4509,65 @@ bool sev_fault_is_private(struct kvm *kvm, gpa_t gpa, u64 error_code, bool *priv
 
 	return true;
 }
+
+void sev_invalidate_private_range(struct kvm_memory_slot *slot, gfn_t start, gfn_t end)
+{
+	gfn_t gfn = start;

arch/x86/kvm/svm/sev.c bool sev_fault_is_private(struct kvm *kvm, gpa_t gpa, u64 error_code, bool *priv · line 4525

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+
+	if (!sev_snp_guest(slot->kvm))
+		return;
+
+	if (!kvm_slot_can_be_private(slot)) {
+		pr_warn_ratelimited("SEV: Memslot for GFN: 0x%llx is not private.\n",
+				    gfn);
+		return;
+	}
+

This is a generic check for both SNP and TDX, it should be moved to kvm_restrictedmem_invalidate_begin().

Quoted 72 lines
arch/x86/kvm/svm/sev.c +48 -0
+	while (gfn <= end) {
+		gpa_t gpa = gfn_to_gpa(gfn);
+		int level = PG_LEVEL_4K;
+		int order, rc;
+		kvm_pfn_t pfn;
+
+		rc = kvm_restrictedmem_get_pfn(slot, gfn, &pfn, &order);
+		if (rc) {
+			pr_warn_ratelimited("SEV: Failed to retrieve restricted PFN for GFN 0x%llx, rc: %d\n",
+					    gfn, rc);
+			gfn++;
+			continue;
+		}
+
+		if (order) {
+			int rmp_level;
+
+			if (IS_ALIGNED(gpa, page_level_size(PG_LEVEL_2M)) &&
+			    gpa + page_level_size(PG_LEVEL_2M) <= gfn_to_gpa(end))
+				level = PG_LEVEL_2M;
+			else
+				pr_debug("%s: GPA 0x%llx is not aligned to 2M, skipping 2M directmap restoration\n",
+					 __func__, gpa);
+
+			/*
+			 * TODO: It may still be possible to restore 2M mapping here,
+			 * but keep it simple for now.
+			 */
+			if (level == PG_LEVEL_2M &&
+			    (!snp_lookup_rmpentry(pfn, &rmp_level) || rmp_level == PG_LEVEL_4K)) {
+				pr_debug("%s: PFN 0x%llx is not mapped as 2M private range, skipping 2M directmap restoration\n",
+					 __func__, pfn);
+				level = PG_LEVEL_4K;
+			}
+		}
+
+		pr_debug("%s: GPA %llx PFN %llx order %d level %d\n",
+			 __func__, gpa, pfn, order, level);
+		rc = snp_make_page_shared(slot->kvm, gpa, pfn, level);
+		if (rc)
+			pr_err("SEV: Failed to restore page to shared, GPA: 0x%llx PFN: 0x%llx order: %d rc: %d\n",
+			       gpa, pfn, order, rc);
+
+		gfn += page_level_size(level) >> PAGE_SHIFT;
+		put_page(pfn_to_page(pfn));
+		cond_resched();
+	}
+}
arch/x86/kvm/svm/svm.c +1 -0
index 18e4a6c17d11..3fe5f13b5f3a 100644
@@ -4862,6 +4862,7 @@ static struct kvm_x86_ops svm_x86_ops __initdata = {
 	.adjust_mapping_level = sev_adjust_mapping_level,
 	.update_mem_attr = sev_update_mem_attr,
 	.fault_is_private = sev_fault_is_private,
+	.invalidate_restricted_mem = sev_invalidate_private_range,
 };
 
 /*
arch/x86/kvm/svm/svm.h +1 -0
index 97038afa8020..857b674e68f0 100644
@@ -727,6 +727,7 @@ void handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code);
 void sev_snp_init_protected_guest_state(struct kvm_vcpu *vcpu);
 int sev_update_mem_attr(struct kvm_memory_slot *slot, unsigned int attr,
 			gfn_t start, gfn_t end);
+void sev_invalidate_private_range(struct kvm_memory_slot *slot, gfn_t start, gfn_t end);
 
 bool sev_fault_is_private(struct kvm *kvm, gpa_t gpa, u64 error_code, bool *private_fault);
 
#126 lore raw

RFC PATCH v8 51/56 KVM: SVM: Add module parameter to enable the SEV-SNP

In reply to Michael Roth

From: Brijesh Singh <[email protected]>

Add a module parameter than can be used to enable or disable the SEV-SNP feature. Now that KVM contains the support for the SNP set the GHCB hypervisor feature flag to indicate that SNP is supported.

---
 arch/x86/kvm/svm/sev.c | 7 ++++---
 arch/x86/kvm/svm/svm.h | 2 +-
 2 files changed, 5 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/sev.c +4 -3
index bedec90d034f..70d5650d8d95 100644
@@ -55,14 +55,15 @@ module_param_named(sev, sev_enabled, bool, 0444);
 /* enable/disable SEV-ES support */
 static bool sev_es_enabled = true;
 module_param_named(sev_es, sev_es_enabled, bool, 0444);
+
+/* enable/disable SEV-SNP support */
+static bool sev_snp_enabled = true;
+module_param_named(sev_snp, sev_snp_enabled, bool, 0444);
 #else
 #define sev_enabled false
 #define sev_es_enabled false
 #endif /* CONFIG_KVM_AMD_SEV */
 
-/* enable/disable SEV-SNP support */
-static bool sev_snp_enabled;
-
 #define AP_RESET_HOLD_NONE		0
 #define AP_RESET_HOLD_NAE_EVENT		1
 #define AP_RESET_HOLD_MSR_PROTO		2
arch/x86/kvm/svm/svm.h +1 -1
index 857b674e68f0..221b38d3c845 100644
@@ -694,7 +694,7 @@ void avic_refresh_virtual_apic_mode(struct kvm_vcpu *vcpu);
 #define GHCB_VERSION_MAX	2ULL
 #define GHCB_VERSION_MIN	1ULL
 
-#define GHCB_HV_FT_SUPPORTED	0
+#define GHCB_HV_FT_SUPPORTED	(GHCB_HV_FT_SNP | GHCB_HV_FT_SNP_AP_CREATION)
 
 extern unsigned int max_sev_asid;
 
Signature · 1 line
2.25.1
#127 lore raw

Re: [PATCH RFC v8 51/56] KVM: SVM: Add module parameter to enable the SEV-SNP

Quoted 19 lines · On Mon, 20 Feb 2023 12:38:42 -0600 Michael Roth <[email protected]> wrote:

From: Brijesh Singh <[email protected]>

Add a module parameter than can be used to enable or disable the SEV-SNP feature. Now that KVM contains the support for the SNP set the GHCB hypervisor feature flag to indicate that SNP is supported.

---
 arch/x86/kvm/svm/sev.c | 7 ++++---
 arch/x86/kvm/svm/svm.h | 2 +-
 2 files changed, 5 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/sev.c +0 -0
index bedec90d034f..70d5650d8d95 100644

arch/x86/kvm/svm/sev.c module_param_named(sev, sev_enabled, bool, 0444); · line 64

Quoted 10 lines
arch/x86/kvm/svm/sev.c +4 -0
@@ -55,14 +55,15 @@ module_param_named(sev, sev_enabled, bool, 0444);
 /* enable/disable SEV-ES support */
 static bool sev_es_enabled = true;
 module_param_named(sev_es, sev_es_enabled, bool, 0444);
+
+/* enable/disable SEV-SNP support */
+static bool sev_snp_enabled = true;
+module_param_named(sev_snp, sev_snp_enabled, bool, 0444);
 #else
 #define sev_enabled false
 #define sev_es_enabled false

Guess we also need #define sev_snp_enabled false.

Quoted 13 lines
arch/x86/kvm/svm/sev.c +0 -3
 #endif /* CONFIG_KVM_AMD_SEV */
 
-/* enable/disable SEV-SNP support */
-static bool sev_snp_enabled;
-
 #define AP_RESET_HOLD_NONE		0
 #define AP_RESET_HOLD_NAE_EVENT		1
 #define AP_RESET_HOLD_MSR_PROTO		2
arch/x86/kvm/svm/svm.h +0 -0
index 857b674e68f0..221b38d3c845 100644

arch/x86/kvm/svm/svm.h void avic_refresh_virtual_apic_mode(struct kvm_vcpu *vcpu); · line 697

Quoted 5 lines
arch/x86/kvm/svm/svm.h +1 -1
@@ -694,7 +694,7 @@ void avic_refresh_virtual_apic_mode(struct kvm_vcpu *vcpu);
 #define GHCB_VERSION_MAX	2ULL
 #define GHCB_VERSION_MIN	1ULL
 
-#define GHCB_HV_FT_SUPPORTED	0
+#define GHCB_HV_FT_SUPPORTED	(GHCB_HV_FT_SNP | GHCB_HV_FT_SNP_AP_CREATION)

This is not related to the topic of this patch, should be merged into related patches.

Quoted 3 lines
arch/x86/kvm/svm/svm.h +0 -0
 extern unsigned int max_sev_asid;
 
#128 lore raw

RFC PATCH v8 52/56 ccp: Add support to decrypt the page

In reply to Michael Roth

From: Brijesh Singh <[email protected]>

Add support to decrypt guest encrypted memory. These API interfaces can be used for example to dump VMCBs on SNP guest exit.

[mdr: minor commit fixups]
---
 drivers/crypto/ccp/sev-dev.c | 32 ++++++++++++++++++++++++++++++++
 include/linux/psp-sev.h      | 22 ++++++++++++++++++++--
 2 files changed, 52 insertions(+), 2 deletions(-)
drivers/crypto/ccp/sev-dev.c +32 -0
index e65563bc8298..bf5167b2acfc 100644
@@ -2017,6 +2017,38 @@ int sev_guest_df_flush(int *error)
 }
 EXPORT_SYMBOL_GPL(sev_guest_df_flush);
 
+int snp_guest_dbg_decrypt_page(u64 gctx_pfn, u64 src_pfn, u64 dst_pfn, int *error)
+{
+	struct sev_data_snp_dbg data = {0};
+	struct sev_device *sev;
+	int ret;
+
+	if (!psp_master || !psp_master->sev_data)
+		return -ENODEV;
+
+	sev = psp_master->sev_data;
+
+	if (!sev->snp_initialized)
+		return -EINVAL;
+
+	data.gctx_paddr = sme_me_mask | (gctx_pfn << PAGE_SHIFT);
+	data.src_addr = sme_me_mask | (src_pfn << PAGE_SHIFT);
+	data.dst_addr = sme_me_mask | (dst_pfn << PAGE_SHIFT);
+
+	/* The destination page must be in the firmware state. */
+	if (rmp_mark_pages_firmware(data.dst_addr, 1, false))
+		return -EIO;
+
+	ret = sev_do_cmd(SEV_CMD_SNP_DBG_DECRYPT, &data, error);
+
+	/* Restore the page state */
+	if (snp_reclaim_pages(data.dst_addr, 1, false))
+		ret = -EIO;
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(snp_guest_dbg_decrypt_page);
+
 int snp_guest_ext_guest_request(struct sev_data_snp_guest_request *data,
 				unsigned long vaddr, unsigned long *npages, unsigned long *fw_err)
 {
include/linux/psp-sev.h +20 -2
index 81bafc049eca..92116e2b74fd 100644
@@ -710,7 +710,6 @@ struct sev_data_snp_dbg {
 	u64 gctx_paddr;				/* In */
 	u64 src_addr;				/* In */
 	u64 dst_addr;				/* In */
-	u32 len;				/* In */
 } __packed;
 
 /**
@@ -913,13 +912,27 @@ int sev_guest_decommission(struct sev_data_decommission *data, int *error);
  * @error: SEV command return code
  *
  * Returns:
+ * 0 if the sev successfully processed the command
+ * -%ENODEV    if the sev device is not available
+ * -%ENOTSUPP  if the sev does not support SEV
+ * -%ETIMEDOUT if the sev command timed out
+ * -%EIO       if the sev returned a non-zero return code
+ */
+int sev_do_cmd(int cmd, void *data, int *psp_ret);
+
+/**
+ * snp_guest_dbg_decrypt_page - perform SEV SNP_DBG_DECRYPT command
+ *
+ * @sev_ret: sev command return code
+ *
+ * Returns:
  * 0 if the SEV successfully processed the command
  * -%ENODEV    if the SEV device is not available
  * -%ENOTSUPP  if the SEV does not support SEV
  * -%ETIMEDOUT if the SEV command timed out
  * -%EIO       if the SEV returned a non-zero return code
  */
-int sev_do_cmd(int cmd, void *data, int *psp_ret);
+int snp_guest_dbg_decrypt_page(u64 gctx_pfn, u64 src_pfn, u64 dst_pfn, int *error);
 
 void *psp_copy_user_blob(u64 uaddr, u32 len);
 void *snp_alloc_firmware_page(gfp_t mask);
@@ -987,6 +1000,11 @@ static inline void *psp_copy_user_blob(u64 __user uaddr, u32 len) { return ERR_P
 
 void snp_mark_pages_offline(unsigned long pfn, unsigned int npages) {}
 
+static inline int snp_guest_dbg_decrypt_page(u64 gctx_pfn, u64 src_pfn, u64 dst_pfn, int *error)
+{
+	return -ENODEV;
+}
+
 static inline void *snp_alloc_firmware_page(gfp_t mask)
 {
 	return NULL;
Signature · 1 line
2.25.1
#129 lore raw

Re: [PATCH RFC v8 52/56] ccp: Add support to decrypt the page

Quoted 5 lines · On Mon, 20 Feb 2023 12:38:43 -0600 Michael Roth <[email protected]> wrote:

From: Brijesh Singh <[email protected]>

Add support to decrypt guest encrypted memory. These API interfaces can be used for example to dump VMCBs on SNP guest exit.

What kinds of check will be applied from firmware when VMM decrypts this page? I suppose there has to be kinda mechanism to prevent VMM to decrypt any page in the guest. It would be nice to have some introduction about it in the comments.

Quoted 105 lines
[mdr: minor commit fixups]
---
 drivers/crypto/ccp/sev-dev.c | 32 ++++++++++++++++++++++++++++++++
 include/linux/psp-sev.h      | 22 ++++++++++++++++++++--
 2 files changed, 52 insertions(+), 2 deletions(-)
drivers/crypto/ccp/sev-dev.c +32 -0
index e65563bc8298..bf5167b2acfc 100644
@@ -2017,6 +2017,38 @@ int sev_guest_df_flush(int *error)
 }
 EXPORT_SYMBOL_GPL(sev_guest_df_flush);
 
+int snp_guest_dbg_decrypt_page(u64 gctx_pfn, u64 src_pfn, u64 dst_pfn, int *error)
+{
+	struct sev_data_snp_dbg data = {0};
+	struct sev_device *sev;
+	int ret;
+
+	if (!psp_master || !psp_master->sev_data)
+		return -ENODEV;
+
+	sev = psp_master->sev_data;
+
+	if (!sev->snp_initialized)
+		return -EINVAL;
+
+	data.gctx_paddr = sme_me_mask | (gctx_pfn << PAGE_SHIFT);
+	data.src_addr = sme_me_mask | (src_pfn << PAGE_SHIFT);
+	data.dst_addr = sme_me_mask | (dst_pfn << PAGE_SHIFT);
+
+	/* The destination page must be in the firmware state. */
+	if (rmp_mark_pages_firmware(data.dst_addr, 1, false))
+		return -EIO;
+
+	ret = sev_do_cmd(SEV_CMD_SNP_DBG_DECRYPT, &data, error);
+
+	/* Restore the page state */
+	if (snp_reclaim_pages(data.dst_addr, 1, false))
+		ret = -EIO;
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(snp_guest_dbg_decrypt_page);
+
 int snp_guest_ext_guest_request(struct sev_data_snp_guest_request *data,
 				unsigned long vaddr, unsigned long *npages, unsigned long *fw_err)
 {
include/linux/psp-sev.h +20 -2
index 81bafc049eca..92116e2b74fd 100644
@@ -710,7 +710,6 @@ struct sev_data_snp_dbg {
 	u64 gctx_paddr;				/* In */
 	u64 src_addr;				/* In */
 	u64 dst_addr;				/* In */
-	u32 len;				/* In */
 } __packed;
 
 /**
@@ -913,13 +912,27 @@ int sev_guest_decommission(struct sev_data_decommission *data, int *error);
  * @error: SEV command return code
  *
  * Returns:
+ * 0 if the sev successfully processed the command
+ * -%ENODEV    if the sev device is not available
+ * -%ENOTSUPP  if the sev does not support SEV
+ * -%ETIMEDOUT if the sev command timed out
+ * -%EIO       if the sev returned a non-zero return code
+ */
+int sev_do_cmd(int cmd, void *data, int *psp_ret);
+
+/**
+ * snp_guest_dbg_decrypt_page - perform SEV SNP_DBG_DECRYPT command
+ *
+ * @sev_ret: sev command return code
+ *
+ * Returns:
  * 0 if the SEV successfully processed the command
  * -%ENODEV    if the SEV device is not available
  * -%ENOTSUPP  if the SEV does not support SEV
  * -%ETIMEDOUT if the SEV command timed out
  * -%EIO       if the SEV returned a non-zero return code
  */
-int sev_do_cmd(int cmd, void *data, int *psp_ret);
+int snp_guest_dbg_decrypt_page(u64 gctx_pfn, u64 src_pfn, u64 dst_pfn, int *error);
 
 void *psp_copy_user_blob(u64 uaddr, u32 len);
 void *snp_alloc_firmware_page(gfp_t mask);
@@ -987,6 +1000,11 @@ static inline void *psp_copy_user_blob(u64 __user uaddr, u32 len) { return ERR_P
 
 void snp_mark_pages_offline(unsigned long pfn, unsigned int npages) {}
 
+static inline int snp_guest_dbg_decrypt_page(u64 gctx_pfn, u64 src_pfn, u64 dst_pfn, int *error)
+{
+	return -ENODEV;
+}
+
 static inline void *snp_alloc_firmware_page(gfp_t mask)
 {
 	return NULL;
#130 lore raw

Re: [PATCH RFC v8 52/56] ccp: Add support to decrypt the page

Hi Mike, Zhi,

Quoted 5 lines · Zhi Wang
Quoted 2 lines · On Mon, 20 Feb 2023 12:38:43 -0600 Michael Roth <[email protected]> wrote:

From: Brijesh Singh <[email protected]>

Quoted 9 lines
Quoted 3 lines

Add support to decrypt guest encrypted memory. These API interfaces can be used for example to dump VMCBs on SNP guest exit.

What kinds of check will be applied from firmware when VMM decrypts this page? I suppose there has to be kinda mechanism to prevent VMM to decrypt any page in the guest. It would be nice to have some introduction about it in the comments.

The SNP ABI spec says (section 8.27.2 SNP_DBG_DECRYPT):

The firmware checks that the guest's policy allows debugging. If not, the firmware returns POLICY_FAILURE.

and in the Guest Policy (section 4.3):

Bit 19 - DEBUG
0: Debugging is disallowed.
1: Debugging is allowed.

In the kernel, that firmware error code is defined as SEV_RET_POLICY_FAILURE.

Quoted 26 lines
Quoted 26 lines
[mdr: minor commit fixups]
---
 drivers/crypto/ccp/sev-dev.c | 32 ++++++++++++++++++++++++++++++++
 include/linux/psp-sev.h      | 22 ++++++++++++++++++++--
 2 files changed, 52 insertions(+), 2 deletions(-)
drivers/crypto/ccp/sev-dev.c +9 -0
index e65563bc8298..bf5167b2acfc 100644
@@ -2017,6 +2017,38 @@ int sev_guest_df_flush(int *error)
 }
 EXPORT_SYMBOL_GPL(sev_guest_df_flush);
 
+int snp_guest_dbg_decrypt_page(u64 gctx_pfn, u64 src_pfn, u64 dst_pfn, int *error)
+{
+	struct sev_data_snp_dbg data = {0};
+	struct sev_device *sev;
+	int ret;
+
+	if (!psp_master || !psp_master->sev_data)
+		return -ENODEV;
+
Quoted 8 lines

drivers/crypto/ccp/sev-dev.c int sev_guest_df_flush(int *error) · line 2036

Quoted 8 lines
drivers/crypto/ccp/sev-dev.c +8 -0
+	sev = psp_master->sev_data;
+
+	if (!sev->snp_initialized)
+		return -EINVAL;
+
+	data.gctx_paddr = sme_me_mask | (gctx_pfn << PAGE_SHIFT);
+	data.src_addr = sme_me_mask | (src_pfn << PAGE_SHIFT);
+	data.dst_addr = sme_me_mask | (dst_pfn << PAGE_SHIFT);

I guess this works, but I wonder why we need to turn on sme_me_mask on teh dst_addr. I thought that the firmware decrypts the guest page (src_addr) to a plaintext page. Couldn't find this requirement in the SNP spec.

Quoted 20 lines
Quoted 20 lines
drivers/crypto/ccp/sev-dev.c +15 -0
+
+	/* The destination page must be in the firmware state. */
+	if (rmp_mark_pages_firmware(data.dst_addr, 1, false))
+		return -EIO;
+
+	ret = sev_do_cmd(SEV_CMD_SNP_DBG_DECRYPT, &data, error);
+
+	/* Restore the page state */
+	if (snp_reclaim_pages(data.dst_addr, 1, false))
+		ret = -EIO;
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(snp_guest_dbg_decrypt_page);
+
 int snp_guest_ext_guest_request(struct sev_data_snp_guest_request *data,
 				unsigned long vaddr, unsigned long *npages, unsigned long *fw_err)
 {
include/linux/psp-sev.h +0 -0
index 81bafc049eca..92116e2b74fd 100644
Quoted 8 lines

include/linux/psp-sev.h struct sev_data_snp_dbg { · line 713

Quoted 8 lines
include/linux/psp-sev.h +0 -1
@@ -710,7 +710,6 @@ struct sev_data_snp_dbg {
 	u64 gctx_paddr;				/* In */
 	u64 src_addr;				/* In */
 	u64 dst_addr;				/* In */
-	u32 len;				/* In */
 } __packed;

The comment above this ^^^ struct still lists the 'len' field, and also calls the first field 'handle' instead of 'gctx_paddr'.

Also - why is this change happening in this patch? Why was the incorrect 'len' field added in the first place in "[PATCH RFC v8 20/56] crypto:ccp: Define the SEV-SNP commands" ? (the comment fixes should probably go there too).

Quoted 12 lines

include/linux/psp-sev.h int sev_guest_decommission(struct sev_data_decommission *data, int *error); · line 920

Quoted 12 lines
include/linux/psp-sev.h +6 -0
 /**
@@ -913,13 +912,27 @@ int sev_guest_decommission(struct sev_data_decommission *data, int *error);
  * @error: SEV command return code
  *
  * Returns:
+ * 0 if the sev successfully processed the command
+ * -%ENODEV    if the sev device is not available
+ * -%ENOTSUPP  if the sev does not support SEV
+ * -%ETIMEDOUT if the sev command timed out
+ * -%EIO       if the sev returned a non-zero return code
+ */

I think that if the word 'sev' would be 'SEV' in this comment, the diff will be a bit less misleading (basically this patch should not introduce changes to sev_do_cmd).

-Dov

Quoted 32 lines
Quoted 31 lines
include/linux/psp-sev.h +14 -1
+int sev_do_cmd(int cmd, void *data, int *psp_ret);
+
+/**
+ * snp_guest_dbg_decrypt_page - perform SEV SNP_DBG_DECRYPT command
+ *
+ * @sev_ret: sev command return code
+ *
+ * Returns:
  * 0 if the SEV successfully processed the command
  * -%ENODEV    if the SEV device is not available
  * -%ENOTSUPP  if the SEV does not support SEV
  * -%ETIMEDOUT if the SEV command timed out
  * -%EIO       if the SEV returned a non-zero return code
  */
-int sev_do_cmd(int cmd, void *data, int *psp_ret);
+int snp_guest_dbg_decrypt_page(u64 gctx_pfn, u64 src_pfn, u64 dst_pfn, int *error);
 
 void *psp_copy_user_blob(u64 uaddr, u32 len);
 void *snp_alloc_firmware_page(gfp_t mask);
@@ -987,6 +1000,11 @@ static inline void *psp_copy_user_blob(u64 __user uaddr, u32 len) { return ERR_P
 
 void snp_mark_pages_offline(unsigned long pfn, unsigned int npages) {}
 
+static inline int snp_guest_dbg_decrypt_page(u64 gctx_pfn, u64 src_pfn, u64 dst_pfn, int *error)
+{
+	return -ENODEV;
+}
+
 static inline void *snp_alloc_firmware_page(gfp_t mask)
 {
 	return NULL;
maintainer
#131 lore raw

Re: [PATCH RFC v8 52/56] ccp: Add support to decrypt the page

Quoted 64 lines · Dov Murik

Hi Mike, Zhi,

Quoted 5 lines · Zhi Wang
Quoted 2 lines · On Mon, 20 Feb 2023 12:38:43 -0600 Michael Roth <[email protected]> wrote:

From: Brijesh Singh <[email protected]>

Quoted 9 lines
Quoted 3 lines

Add support to decrypt guest encrypted memory. These API interfaces can be used for example to dump VMCBs on SNP guest exit.

What kinds of check will be applied from firmware when VMM decrypts this page? I suppose there has to be kinda mechanism to prevent VMM to decrypt any page in the guest. It would be nice to have some introduction about it in the comments.

The SNP ABI spec says (section 8.27.2 SNP_DBG_DECRYPT):

The firmware checks that the guest's policy allows debugging. If not, the firmware returns POLICY_FAILURE.

and in the Guest Policy (section 4.3):

Bit 19 - DEBUG
0: Debugging is disallowed.
1: Debugging is allowed.

In the kernel, that firmware error code is defined as SEV_RET_POLICY_FAILURE.

Quoted 31 lines
Quoted 31 lines
[mdr: minor commit fixups]
---
  drivers/crypto/ccp/sev-dev.c | 32 ++++++++++++++++++++++++++++++++
  include/linux/psp-sev.h      | 22 ++++++++++++++++++++--
  2 files changed, 52 insertions(+), 2 deletions(-)
drivers/crypto/ccp/sev-dev.c +14 -0
index e65563bc8298..bf5167b2acfc 100644
@@ -2017,6 +2017,38 @@ int sev_guest_df_flush(int *error)
  }
  EXPORT_SYMBOL_GPL(sev_guest_df_flush);
 
+int snp_guest_dbg_decrypt_page(u64 gctx_pfn, u64 src_pfn, u64 dst_pfn, int *error)
+{
+	struct sev_data_snp_dbg data = {0};
+	struct sev_device *sev;
+	int ret;
+
+	if (!psp_master || !psp_master->sev_data)
+		return -ENODEV;
+
+	sev = psp_master->sev_data;
+
+	if (!sev->snp_initialized)
+		return -EINVAL;
+
Quoted 8 lines
Quoted 3 lines

drivers/crypto/ccp/sev-dev.c int sev_guest_df_flush(int *error) · line 2036

Quoted 3 lines
drivers/crypto/ccp/sev-dev.c +3 -0
+	data.gctx_paddr = sme_me_mask | (gctx_pfn << PAGE_SHIFT);
+	data.src_addr = sme_me_mask | (src_pfn << PAGE_SHIFT);
+	data.dst_addr = sme_me_mask | (dst_pfn << PAGE_SHIFT);

I guess this works, but I wonder why we need to turn on sme_me_mask on teh dst_addr. I thought that the firmware decrypts the guest page (src_addr) to a plaintext page. Couldn't find this requirement in the SNP spec.

This sme_me_mask tells the firmware how to access the host memory (similar to how DMA uses sme_me_mask when supplying addresses to devices under SME). This needs to match the pagetable mapping being used by the host, otherwise the contents will appears as ciphertext to the host if they are not in sync. Since the default pagetable mapping is encrypted, the sme_me_mask bit must be provided on the destination address. So it is not a spec requirement, but an SME implementation requirement.

Thanks,
Tom

Quoted 92 lines
Quoted 22 lines
Quoted 22 lines
drivers/crypto/ccp/sev-dev.c +15 -0
+
+	/* The destination page must be in the firmware state. */
+	if (rmp_mark_pages_firmware(data.dst_addr, 1, false))
+		return -EIO;
+
+	ret = sev_do_cmd(SEV_CMD_SNP_DBG_DECRYPT, &data, error);
+
+	/* Restore the page state */
+	if (snp_reclaim_pages(data.dst_addr, 1, false))
+		ret = -EIO;
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(snp_guest_dbg_decrypt_page);
+
  int snp_guest_ext_guest_request(struct sev_data_snp_guest_request *data,
  				unsigned long vaddr, unsigned long *npages, unsigned long *fw_err)
  {
include/linux/psp-sev.h +0 -0
index 81bafc049eca..92116e2b74fd 100644
Quoted 8 lines

include/linux/psp-sev.h struct sev_data_snp_dbg { · line 713

Quoted 8 lines
include/linux/psp-sev.h +0 -1
@@ -710,7 +710,6 @@ struct sev_data_snp_dbg {
  	u64 gctx_paddr;				/* In */
  	u64 src_addr;				/* In */
  	u64 dst_addr;				/* In */
-	u32 len;				/* In */
  } __packed;

The comment above this ^^^ struct still lists the 'len' field, and also calls the first field 'handle' instead of 'gctx_paddr'.

Also - why is this change happening in this patch? Why was the incorrect 'len' field added in the first place in "[PATCH RFC v8 20/56] crypto:ccp: Define the SEV-SNP commands" ? (the comment fixes should probably go there too).

Quoted 12 lines

include/linux/psp-sev.h int sev_guest_decommission(struct sev_data_decommission *data, int *error); · line 920

Quoted 12 lines
include/linux/psp-sev.h +6 -0
  /**
@@ -913,13 +912,27 @@ int sev_guest_decommission(struct sev_data_decommission *data, int *error);
   * @error: SEV command return code
   *
   * Returns:
+ * 0 if the sev successfully processed the command
+ * -%ENODEV    if the sev device is not available
+ * -%ENOTSUPP  if the sev does not support SEV
+ * -%ETIMEDOUT if the sev command timed out
+ * -%EIO       if the sev returned a non-zero return code
+ */

I think that if the word 'sev' would be 'SEV' in this comment, the diff will be a bit less misleading (basically this patch should not introduce changes to sev_do_cmd).

-Dov

Quoted 32 lines
Quoted 31 lines
include/linux/psp-sev.h +14 -1
+int sev_do_cmd(int cmd, void *data, int *psp_ret);
+
+/**
+ * snp_guest_dbg_decrypt_page - perform SEV SNP_DBG_DECRYPT command
+ *
+ * @sev_ret: sev command return code
+ *
+ * Returns:
   * 0 if the SEV successfully processed the command
   * -%ENODEV    if the SEV device is not available
   * -%ENOTSUPP  if the SEV does not support SEV
   * -%ETIMEDOUT if the SEV command timed out
   * -%EIO       if the SEV returned a non-zero return code
   */
-int sev_do_cmd(int cmd, void *data, int *psp_ret);
+int snp_guest_dbg_decrypt_page(u64 gctx_pfn, u64 src_pfn, u64 dst_pfn, int *error);
 
  void *psp_copy_user_blob(u64 uaddr, u32 len);
  void *snp_alloc_firmware_page(gfp_t mask);
@@ -987,6 +1000,11 @@ static inline void *psp_copy_user_blob(u64 __user uaddr, u32 len) { return ERR_P
 
  void snp_mark_pages_offline(unsigned long pfn, unsigned int npages) {}
 
+static inline int snp_guest_dbg_decrypt_page(u64 gctx_pfn, u64 src_pfn, u64 dst_pfn, int *error)
+{
+	return -ENODEV;
+}
+
  static inline void *snp_alloc_firmware_page(gfp_t mask)
  {
  	return NULL;
#132 lore raw

Re: [PATCH RFC v8 52/56] ccp: Add support to decrypt the page

Quoted 76 lines · Tom Lendacky
Quoted 66 lines · Dov Murik

Hi Mike, Zhi,

Quoted 9 lines · Zhi Wang
Quoted 5 lines · On Mon, 20 Feb 2023 12:38:43 -0600 Michael Roth <[email protected]> wrote:

From: Brijesh Singh <[email protected]>

Add support to decrypt guest encrypted memory. These API interfaces can be used for example to dump VMCBs on SNP guest exit.

Quoted 6 lines

What kinds of check will be applied from firmware when VMM decrypts this page? I suppose there has to be kinda mechanism to prevent VMM to decrypt
any page in the guest. It would be nice to have some introduction about it in the comments.

The SNP ABI spec says (section 8.27.2 SNP_DBG_DECRYPT):

   The firmware checks that the guest's policy allows debugging. If not, the firmware returns POLICY_FAILURE.

and in the Guest Policy (section 4.3):

   Bit 19 - DEBUG
   0: Debugging is disallowed.
   1: Debugging is allowed.

In the kernel, that firmware error code is defined as SEV_RET_POLICY_FAILURE.

Quoted 32 lines
Quoted 32 lines
[mdr: minor commit fixups]

---
  drivers/crypto/ccp/sev-dev.c | 32 ++++++++++++++++++++++++++++++++ include/linux/psp-sev.h      | 22 ++++++++++++++++++++--

  2 files changed, 52 insertions(+), 2 deletions(-)
drivers/crypto/ccp/sev-dev.c +0 -0
index e65563bc8298..bf5167b2acfc 100644
@@ -2017,6 +2017,38 @@ int sev_guest_df_flush(int *error)
   }
   EXPORT_SYMBOL_GPL(sev_guest_df_flush);

  +int snp_guest_dbg_decrypt_page(u64 gctx_pfn, u64 src_pfn, u64 dst_pfn, int *error)

drivers/crypto/ccp/sev-dev.c +13 -0
+{
+    struct sev_data_snp_dbg data = {0};
+    struct sev_device *sev;
+    int ret;
+
+    if (!psp_master || !psp_master->sev_data)
+        return -ENODEV;
+
+    sev = psp_master->sev_data;
+
+    if (!sev->snp_initialized)
+        return -EINVAL;
+
Quoted 8 lines
Quoted 3 lines
Quoted 3 lines

+    data.gctx_paddr = sme_me_mask | (gctx_pfn << PAGE_SHIFT); +    data.src_addr = sme_me_mask | (src_pfn << PAGE_SHIFT); +    data.dst_addr = sme_me_mask | (dst_pfn << PAGE_SHIFT);

I guess this works, but I wonder why we need to turn on sme_me_mask on teh dst_addr.  I thought that the firmware decrypts the guest page (src_addr) to a plaintext page.  Couldn't find this requirement in the SNP spec.

Quoted 8 lines

This sme_me_mask tells the firmware how to access the host memory (similar to how DMA uses sme_me_mask when supplying addresses to devices under SME). This needs to match the pagetable mapping being used by the host, otherwise the contents will appears as ciphertext to the host if they are not in sync. Since the default pagetable mapping is encrypted, the sme_me_mask bit must be provided on the destination address. So it is not a spec requirement, but an SME implementation requirement.

Ah, OK, that's clear now. Thanks Tom.

-Dov

#133 lore raw

RFC PATCH v8 53/56 KVM: SVM: Make VMSAVE target area memory allocation SNP safe

In reply to Michael Roth

From: Ashish Kalra <[email protected]>

Implement a workaround for an SNP erratum where the CPU will incorrectly signal an RMP violation #PF if a hugepage (2mb or 1gb) collides with the RMP entry of the VMSAVE target page.

When SEV-SNP is globally enabled, the CPU marks the VMSAVE target page as "InUse" while the VMSAVE instruction is executing. If another CPU writes to a different page in the same 2MB region while the VMSAVE is executing, the CPU will throw an RMP violation #PF.

Use the snp safe generic allocator for allocating the VMSA target page which will ensure that the page returned is not a hugepage, as it is already being used for the allocating the VMCB, VMSA and AVIC backing page.

---
 arch/x86/kvm/svm/svm.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/kvm/svm/svm.c +1 -1
index 3fe5f13b5f3a..8bda31a61757 100644
@@ -665,7 +665,7 @@ static int svm_cpu_init(int cpu)
 	int ret = -ENOMEM;
 
 	memset(sd, 0, sizeof(struct svm_cpu_data));
-	sd->save_area = alloc_page(GFP_KERNEL | __GFP_ZERO);
+	sd->save_area = snp_safe_alloc_page(NULL);
 	if (!sd->save_area)
 		return ret;
 
Signature · 1 line
2.25.1
#134 lore raw

Re: [PATCH RFC v8 53/56] KVM: SVM: Make VMSAVE target area memory allocation SNP safe

Quoted 11 lines · On Mon, 20 Feb 2023 12:38:44 -0600 Michael Roth <[email protected]> wrote:

From: Ashish Kalra <[email protected]>

Implement a workaround for an SNP erratum where the CPU will incorrectly signal an RMP violation #PF if a hugepage (2mb or 1gb) collides with the RMP entry of the VMSAVE target page.

When SEV-SNP is globally enabled, the CPU marks the VMSAVE target page as "InUse" while the VMSAVE instruction is executing. If another CPU writes to a different page in the same 2MB region while the VMSAVE is executing, the CPU will throw an RMP violation #PF.

Quoted 5 lines

Use the snp safe generic allocator for allocating the VMSA target page which will ensure that the page returned is not a hugepage, as it is already being used for the allocating the VMCB, VMSA and AVIC backing page.

This should be merged with patch where implements the snp_safe_alloc_page().

Quoted 22 lines
---
 arch/x86/kvm/svm/svm.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/kvm/svm/svm.c +1 -1
index 3fe5f13b5f3a..8bda31a61757 100644
@@ -665,7 +665,7 @@ static int svm_cpu_init(int cpu)
 	int ret = -ENOMEM;
 
 	memset(sd, 0, sizeof(struct svm_cpu_data));
-	sd->save_area = alloc_page(GFP_KERNEL | __GFP_ZERO);
+	sd->save_area = snp_safe_alloc_page(NULL);
 	if (!sd->save_area)
 		return ret;
 
#135 lore raw

RFC PATCH v8 54/56 x86/sev: Add KVM commands for instance certs

In reply to Michael Roth

From: Dionna Glaze <[email protected]>

The /dev/sev device has the ability to store host-wide certificates for the key used by the AMD-SP for SEV-SNP attestation report signing, but for hosts that want to specify additional certificates that are specific to the image launched in a VM, a different way is needed to communicate those certificates.

Add two new KVM ioctl to handle this: KVM_SEV_SNP_{GET,SET}_CERTS

The certificates that are set with this command are expected to follow the same format as the host certificates, but that format is opaque to the kernel.

The new behavior for custom certificates is that the extended guest request command will now return the overridden certificates if they were installed for the instance. The error condition for a too small data buffer is changed to return the overridden certificate data size if there is an overridden certificate set installed.

Setting a 0 length certificate returns the system state to only return the host certificates on an extended guest request.

Also increase the SEV_FW_BLOB_MAX_SIZE another 4K page to allow space for an extra certificate.

Cc Tom Lendacky <[email protected]>
Cc Paolo Bonzini <[email protected]>
[mdr: remove used of "we" and "this patch" in commit log]
---
 arch/x86/kvm/svm/sev.c   | 111 ++++++++++++++++++++++++++++++++++++++-
 arch/x86/kvm/svm/svm.h   |   1 +
 include/linux/psp-sev.h  |   2 +-
 include/uapi/linux/kvm.h |  12 +++++
 4 files changed, 123 insertions(+), 3 deletions(-)
arch/x86/kvm/svm/sev.c +109 -2
index 70d5650d8d95..18b64b7005e7 100644
@@ -2089,6 +2089,7 @@ static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp)
 		goto e_free;
 
 	sev->snp_certs_data = certs_data;
+	sev->snp_certs_len = 0;
 
 	return context;
 
@@ -2404,6 +2405,86 @@ static int snp_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
 	return ret;
 }
 
+static int snp_get_instance_certs(struct kvm *kvm, struct kvm_sev_cmd *argp)
+{
+	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
+	struct kvm_sev_snp_get_certs params;
+
+	if (!sev_snp_guest(kvm))
+		return -ENOTTY;
+
+	if (!sev->snp_context)
+		return -EINVAL;
+
+	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
+			   sizeof(params)))
+		return -EFAULT;
+
+	/* No instance certs set. */
+	if (!sev->snp_certs_len)
+		return -ENOENT;
+
+	if (params.certs_len < sev->snp_certs_len) {
+		/* Output buffer too small. Return the required size. */
+		params.certs_len = sev->snp_certs_len;
+
+		if (copy_to_user((void __user *)(uintptr_t)argp->data, &params,
+				 sizeof(params)))
+			return -EFAULT;
+
+		return -EINVAL;
+	}
+
+	if (copy_to_user((void __user *)(uintptr_t)params.certs_uaddr,
+			 sev->snp_certs_data, sev->snp_certs_len))
+		return -EFAULT;
+
+	return 0;
+}
+
+static int snp_set_instance_certs(struct kvm *kvm, struct kvm_sev_cmd *argp)
+{
+	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
+	unsigned long length = SEV_FW_BLOB_MAX_SIZE;
+	void *to_certs = sev->snp_certs_data;
+	struct kvm_sev_snp_set_certs params;
+
+	if (!sev_snp_guest(kvm))
+		return -ENOTTY;
+
+	if (!sev->snp_context)
+		return -EINVAL;
+
+	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
+			   sizeof(params)))
+		return -EFAULT;
+
+	if (params.certs_len > SEV_FW_BLOB_MAX_SIZE)
+		return -EINVAL;
+
+	/*
+	 * Setting a length of 0 is the same as "uninstalling" instance-
+	 * specific certificates.
+	 */
+	if (params.certs_len == 0) {
+		sev->snp_certs_len = 0;
+		return 0;
+	}
+
+	/* Page-align the length */
+	length = (params.certs_len + PAGE_SIZE - 1) & PAGE_MASK;
+
+	if (copy_from_user(to_certs,
+			   (void __user *)(uintptr_t)params.certs_uaddr,
+			   params.certs_len)) {
+		return -EFAULT;
+	}
+
+	sev->snp_certs_len = length;
+
+	return 0;
+}
+
 int sev_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 {
 	struct kvm_sev_cmd sev_cmd;
@@ -2503,6 +2584,12 @@ int sev_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 	case KVM_SEV_SNP_LAUNCH_FINISH:
 		r = snp_launch_finish(kvm, &sev_cmd);
 		break;
+	case KVM_SEV_SNP_GET_CERTS:
+		r = snp_get_instance_certs(kvm, &sev_cmd);
+		break;
+	case KVM_SEV_SNP_SET_CERTS:
+		r = snp_set_instance_certs(kvm, &sev_cmd);
+		break;
 	default:
 		r = -EINVAL;
 		goto out;
@@ -3550,8 +3637,28 @@ static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp
 	if (rc)
 		goto unlock;
 
-	rc = snp_guest_ext_guest_request(&req, (unsigned long)sev->snp_certs_data,
-					 &data_npages, &err);
+	/*
+	 * If the VMM has overridden the certs, then change the error message
+	 * if the size is inappropriate for the override. Otherwise, use a
+	 * regular guest request and copy back the instance certs.
+	 */
+	if (sev->snp_certs_len) {
+		if ((data_npages << PAGE_SHIFT) < sev->snp_certs_len) {
+			rc = -EINVAL;
+			err = SNP_GUEST_REQ_INVALID_LEN;
+			goto datalen;
+		}
+		rc = sev_issue_cmd(kvm, SEV_CMD_SNP_GUEST_REQUEST, &req,
+				   (int *)&err);
+	} else {
+		rc = snp_guest_ext_guest_request(&req,
+						 (unsigned long)sev->snp_certs_data,
+						 &data_npages, &err);
+	}
+datalen:
+	if (sev->snp_certs_len)
+		data_npages = sev->snp_certs_len >> PAGE_SHIFT;
+
 	if (rc) {
 		/*
 		 * If buffer length is small then return the expected
arch/x86/kvm/svm/svm.h +1 -0
index 221b38d3c845..dced46559508 100644
@@ -94,6 +94,7 @@ struct kvm_sev_info {
 	u64 snp_init_flags;
 	void *snp_context;      /* SNP guest context page */
 	void *snp_certs_data;
+	unsigned int snp_certs_len; /* Size of instance override for certs */
 	struct mutex guest_req_lock; /* Lock for guest request handling */
 
 	u64 sev_features;	/* Features set at VMSA creation */
include/linux/psp-sev.h +1 -1
index 92116e2b74fd..3b28b78938f6 100644
@@ -22,7 +22,7 @@
 #define __psp_pa(x)	__pa(x)
 #endif
 
-#define SEV_FW_BLOB_MAX_SIZE	0x4000	/* 16KB */
+#define SEV_FW_BLOB_MAX_SIZE	0x5000	/* 20KB */
 
 /**
  * SEV platform state
include/uapi/linux/kvm.h +12 -0
index 6e684bf5f723..ad7e24e43547 100644
@@ -1928,6 +1928,8 @@ enum sev_cmd_id {
 	KVM_SEV_SNP_LAUNCH_START,
 	KVM_SEV_SNP_LAUNCH_UPDATE,
 	KVM_SEV_SNP_LAUNCH_FINISH,
+	KVM_SEV_SNP_GET_CERTS,
+	KVM_SEV_SNP_SET_CERTS,
 
 	KVM_SEV_NR_MAX,
 };
@@ -2075,6 +2077,16 @@ struct kvm_sev_snp_launch_finish {
 	__u8 pad[6];
 };
 
+struct kvm_sev_snp_get_certs {
+	__u64 certs_uaddr;
+	__u64 certs_len;
+};
+
+struct kvm_sev_snp_set_certs {
+	__u64 certs_uaddr;
+	__u64 certs_len;
+};
+
 #define KVM_DEV_ASSIGN_ENABLE_IOMMU	(1 << 0)
 #define KVM_DEV_ASSIGN_PCI_2_3		(1 << 1)
 #define KVM_DEV_ASSIGN_MASK_INTX	(1 << 2)
Signature · 1 line
2.25.1
#136 lore raw

Re: [PATCH RFC v8 54/56] x86/sev: Add KVM commands for instance certs

Hi Mike,

Quoted 115 lines · Michael Roth

From: Dionna Glaze <[email protected]>

The /dev/sev device has the ability to store host-wide certificates for the key used by the AMD-SP for SEV-SNP attestation report signing, but for hosts that want to specify additional certificates that are specific to the image launched in a VM, a different way is needed to communicate those certificates.

Add two new KVM ioctl to handle this: KVM_SEV_SNP_{GET,SET}_CERTS

The certificates that are set with this command are expected to follow the same format as the host certificates, but that format is opaque to the kernel.

The new behavior for custom certificates is that the extended guest request command will now return the overridden certificates if they were installed for the instance. The error condition for a too small data buffer is changed to return the overridden certificate data size if there is an overridden certificate set installed.

Setting a 0 length certificate returns the system state to only return the host certificates on an extended guest request.

Also increase the SEV_FW_BLOB_MAX_SIZE another 4K page to allow space for an extra certificate.

Cc Tom Lendacky <[email protected]>
Cc Paolo Bonzini <[email protected]>
[mdr: remove used of "we" and "this patch" in commit log]
---
 arch/x86/kvm/svm/sev.c   | 111 ++++++++++++++++++++++++++++++++++++++-
 arch/x86/kvm/svm/svm.h   |   1 +
 include/linux/psp-sev.h  |   2 +-
 include/uapi/linux/kvm.h |  12 +++++
 4 files changed, 123 insertions(+), 3 deletions(-)
arch/x86/kvm/svm/sev.c +60 -0
index 70d5650d8d95..18b64b7005e7 100644
@@ -2089,6 +2089,7 @@ static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp)
 		goto e_free;
 
 	sev->snp_certs_data = certs_data;
+	sev->snp_certs_len = 0;
 
 	return context;
 
@@ -2404,6 +2405,86 @@ static int snp_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
 	return ret;
 }
 
+static int snp_get_instance_certs(struct kvm *kvm, struct kvm_sev_cmd *argp)
+{
+	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
+	struct kvm_sev_snp_get_certs params;
+
+	if (!sev_snp_guest(kvm))
+		return -ENOTTY;
+
+	if (!sev->snp_context)
+		return -EINVAL;
+
+	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
+			   sizeof(params)))
+		return -EFAULT;
+
+	/* No instance certs set. */
+	if (!sev->snp_certs_len)
+		return -ENOENT;
+
+	if (params.certs_len < sev->snp_certs_len) {
+		/* Output buffer too small. Return the required size. */
+		params.certs_len = sev->snp_certs_len;
+
+		if (copy_to_user((void __user *)(uintptr_t)argp->data, &params,
+				 sizeof(params)))
+			return -EFAULT;
+
+		return -EINVAL;
+	}
+
+	if (copy_to_user((void __user *)(uintptr_t)params.certs_uaddr,
+			 sev->snp_certs_data, sev->snp_certs_len))
+		return -EFAULT;
+
+	return 0;
+}
+
+static int snp_set_instance_certs(struct kvm *kvm, struct kvm_sev_cmd *argp)
+{
+	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
+	unsigned long length = SEV_FW_BLOB_MAX_SIZE;
+	void *to_certs = sev->snp_certs_data;
+	struct kvm_sev_snp_set_certs params;
+
+	if (!sev_snp_guest(kvm))
+		return -ENOTTY;
+
+	if (!sev->snp_context)
+		return -EINVAL;
+
+	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
+			   sizeof(params)))
+		return -EFAULT;
+
+	if (params.certs_len > SEV_FW_BLOB_MAX_SIZE)
+		return -EINVAL;
+
+	/*
+	 * Setting a length of 0 is the same as "uninstalling" instance-

arch/x86/kvm/svm/sev.c static int snp_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 2476

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+	 * specific certificates.
+	 */
+	if (params.certs_len == 0) {
+		sev->snp_certs_len = 0;
+		return 0;
+	}
+
+	/* Page-align the length */
+	length = (params.certs_len + PAGE_SIZE - 1) & PAGE_MASK;
+

In comments on v7 [1] Dionna agreed adding cleanup here:

/* The size could shrink and leave garbage at the end. */ memset(sev->snp_certs_data, 0, SEV_FW_BLOB_MAX_SIZE);

(we can use 'to_certs' in the first argument)

but it wasn't added in v8.

-Dov

[1] https://lore.kernel.org/linux-coco/CAAH4kHYOtzgqSTZQFcRiZwPLCkLAThjsCMdjUCdsBTiP=W0Vxw@mail.gmail.com/

Quoted 113 lines
arch/x86/kvm/svm/sev.c +39 -2
+	if (copy_from_user(to_certs,
+			   (void __user *)(uintptr_t)params.certs_uaddr,
+			   params.certs_len)) {
+		return -EFAULT;
+	}
+
+	sev->snp_certs_len = length;
+
+	return 0;
+}
+
 int sev_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 {
 	struct kvm_sev_cmd sev_cmd;
@@ -2503,6 +2584,12 @@ int sev_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 	case KVM_SEV_SNP_LAUNCH_FINISH:
 		r = snp_launch_finish(kvm, &sev_cmd);
 		break;
+	case KVM_SEV_SNP_GET_CERTS:
+		r = snp_get_instance_certs(kvm, &sev_cmd);
+		break;
+	case KVM_SEV_SNP_SET_CERTS:
+		r = snp_set_instance_certs(kvm, &sev_cmd);
+		break;
 	default:
 		r = -EINVAL;
 		goto out;
@@ -3550,8 +3637,28 @@ static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp
 	if (rc)
 		goto unlock;
 
-	rc = snp_guest_ext_guest_request(&req, (unsigned long)sev->snp_certs_data,
-					 &data_npages, &err);
+	/*
+	 * If the VMM has overridden the certs, then change the error message
+	 * if the size is inappropriate for the override. Otherwise, use a
+	 * regular guest request and copy back the instance certs.
+	 */
+	if (sev->snp_certs_len) {
+		if ((data_npages << PAGE_SHIFT) < sev->snp_certs_len) {
+			rc = -EINVAL;
+			err = SNP_GUEST_REQ_INVALID_LEN;
+			goto datalen;
+		}
+		rc = sev_issue_cmd(kvm, SEV_CMD_SNP_GUEST_REQUEST, &req,
+				   (int *)&err);
+	} else {
+		rc = snp_guest_ext_guest_request(&req,
+						 (unsigned long)sev->snp_certs_data,
+						 &data_npages, &err);
+	}
+datalen:
+	if (sev->snp_certs_len)
+		data_npages = sev->snp_certs_len >> PAGE_SHIFT;
+
 	if (rc) {
 		/*
 		 * If buffer length is small then return the expected
arch/x86/kvm/svm/svm.h +1 -0
index 221b38d3c845..dced46559508 100644
@@ -94,6 +94,7 @@ struct kvm_sev_info {
 	u64 snp_init_flags;
 	void *snp_context;      /* SNP guest context page */
 	void *snp_certs_data;
+	unsigned int snp_certs_len; /* Size of instance override for certs */
 	struct mutex guest_req_lock; /* Lock for guest request handling */
 
 	u64 sev_features;	/* Features set at VMSA creation */
include/linux/psp-sev.h +1 -1
index 92116e2b74fd..3b28b78938f6 100644
@@ -22,7 +22,7 @@
 #define __psp_pa(x)	__pa(x)
 #endif
 
-#define SEV_FW_BLOB_MAX_SIZE	0x4000	/* 16KB */
+#define SEV_FW_BLOB_MAX_SIZE	0x5000	/* 20KB */
 
 /**
  * SEV platform state
include/uapi/linux/kvm.h +12 -0
index 6e684bf5f723..ad7e24e43547 100644
@@ -1928,6 +1928,8 @@ enum sev_cmd_id {
 	KVM_SEV_SNP_LAUNCH_START,
 	KVM_SEV_SNP_LAUNCH_UPDATE,
 	KVM_SEV_SNP_LAUNCH_FINISH,
+	KVM_SEV_SNP_GET_CERTS,
+	KVM_SEV_SNP_SET_CERTS,
 
 	KVM_SEV_NR_MAX,
 };
@@ -2075,6 +2077,16 @@ struct kvm_sev_snp_launch_finish {
 	__u8 pad[6];
 };
 
+struct kvm_sev_snp_get_certs {
+	__u64 certs_uaddr;
+	__u64 certs_len;
+};
+
+struct kvm_sev_snp_set_certs {
+	__u64 certs_uaddr;
+	__u64 certs_len;
+};
+
 #define KVM_DEV_ASSIGN_ENABLE_IOMMU	(1 << 0)
 #define KVM_DEV_ASSIGN_PCI_2_3		(1 << 1)
 #define KVM_DEV_ASSIGN_MASK_INTX	(1 << 2)
#137 lore raw

Re: [PATCH RFC v8 54/56] x86/sev: Add KVM commands for instance certs

In reply to Michael Roth

On Mon, 20 Feb 2023 12:38:45 -0600
Michael Roth <[email protected]> wrote:

In the host-wide certificates installing/uninstalling, a lock is to prevent the racing between cert upload/download path and the handling of guest request path.

Guess we need a similar lock to prevent the racing between snp_{set,get}_instance_certs() and snp_handle_ext_guest_request().

This patch and PATCH 27 are focusing on cert from different sources. It would be better to abstract. With the functions and data structure of cert, the cert installing/uninstalling, checks, expectation of the output buffer can be unified. Then we don't need mostly duplicate routines in two different paths.

Quoted 45 lines

From: Dionna Glaze <[email protected]>

The /dev/sev device has the ability to store host-wide certificates for the key used by the AMD-SP for SEV-SNP attestation report signing, but for hosts that want to specify additional certificates that are specific to the image launched in a VM, a different way is needed to communicate those certificates.

Add two new KVM ioctl to handle this: KVM_SEV_SNP_{GET,SET}_CERTS

The certificates that are set with this command are expected to follow the same format as the host certificates, but that format is opaque to the kernel.

The new behavior for custom certificates is that the extended guest request command will now return the overridden certificates if they were installed for the instance. The error condition for a too small data buffer is changed to return the overridden certificate data size if there is an overridden certificate set installed.

Setting a 0 length certificate returns the system state to only return the host certificates on an extended guest request.

Also increase the SEV_FW_BLOB_MAX_SIZE another 4K page to allow space for an extra certificate.

Cc Tom Lendacky <[email protected]>
Cc Paolo Bonzini <[email protected]>
[mdr: remove used of "we" and "this patch" in commit log]
---
 arch/x86/kvm/svm/sev.c   | 111 ++++++++++++++++++++++++++++++++++++++-
 arch/x86/kvm/svm/svm.h   |   1 +
 include/linux/psp-sev.h  |   2 +-
 include/uapi/linux/kvm.h |  12 +++++
 4 files changed, 123 insertions(+), 3 deletions(-)
arch/x86/kvm/svm/sev.c +0 -0
index 70d5650d8d95..18b64b7005e7 100644

arch/x86/kvm/svm/sev.c static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 2095

Quoted 7 lines
arch/x86/kvm/svm/sev.c +1 -0
@@ -2089,6 +2089,7 @@ static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp)
 		goto e_free;
 
 	sev->snp_certs_data = certs_data;
+	sev->snp_certs_len = 0;
 
 	return context;
 

Better to move the fix to PATCH 45.

Quoted 186 lines
arch/x86/kvm/svm/sev.c +108 -2
@@ -2404,6 +2405,86 @@ static int snp_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
 	return ret;
 }
 
+static int snp_get_instance_certs(struct kvm *kvm, struct kvm_sev_cmd *argp)
+{
+	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
+	struct kvm_sev_snp_get_certs params;
+
+	if (!sev_snp_guest(kvm))
+		return -ENOTTY;
+
+	if (!sev->snp_context)
+		return -EINVAL;
+
+	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
+			   sizeof(params)))
+		return -EFAULT;
+
+	/* No instance certs set. */
+	if (!sev->snp_certs_len)
+		return -ENOENT;
+
+	if (params.certs_len < sev->snp_certs_len) {
+		/* Output buffer too small. Return the required size. */
+		params.certs_len = sev->snp_certs_len;
+
+		if (copy_to_user((void __user *)(uintptr_t)argp->data, &params,
+				 sizeof(params)))
+			return -EFAULT;
+
+		return -EINVAL;
+	}
+
+	if (copy_to_user((void __user *)(uintptr_t)params.certs_uaddr,
+			 sev->snp_certs_data, sev->snp_certs_len))
+		return -EFAULT;
+
+	return 0;
+}
+
+static int snp_set_instance_certs(struct kvm *kvm, struct kvm_sev_cmd *argp)
+{
+	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
+	unsigned long length = SEV_FW_BLOB_MAX_SIZE;
+	void *to_certs = sev->snp_certs_data;
+	struct kvm_sev_snp_set_certs params;
+
+	if (!sev_snp_guest(kvm))
+		return -ENOTTY;
+
+	if (!sev->snp_context)
+		return -EINVAL;
+
+	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
+			   sizeof(params)))
+		return -EFAULT;
+
+	if (params.certs_len > SEV_FW_BLOB_MAX_SIZE)
+		return -EINVAL;
+
+	/*
+	 * Setting a length of 0 is the same as "uninstalling" instance-
+	 * specific certificates.
+	 */
+	if (params.certs_len == 0) {
+		sev->snp_certs_len = 0;
+		return 0;
+	}
+
+	/* Page-align the length */
+	length = (params.certs_len + PAGE_SIZE - 1) & PAGE_MASK;
+
+	if (copy_from_user(to_certs,
+			   (void __user *)(uintptr_t)params.certs_uaddr,
+			   params.certs_len)) {
+		return -EFAULT;
+	}
+
+	sev->snp_certs_len = length;
+
+	return 0;
+}
+
 int sev_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 {
 	struct kvm_sev_cmd sev_cmd;
@@ -2503,6 +2584,12 @@ int sev_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 	case KVM_SEV_SNP_LAUNCH_FINISH:
 		r = snp_launch_finish(kvm, &sev_cmd);
 		break;
+	case KVM_SEV_SNP_GET_CERTS:
+		r = snp_get_instance_certs(kvm, &sev_cmd);
+		break;
+	case KVM_SEV_SNP_SET_CERTS:
+		r = snp_set_instance_certs(kvm, &sev_cmd);
+		break;
 	default:
 		r = -EINVAL;
 		goto out;
@@ -3550,8 +3637,28 @@ static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp
 	if (rc)
 		goto unlock;
 
-	rc = snp_guest_ext_guest_request(&req, (unsigned long)sev->snp_certs_data,
-					 &data_npages, &err);
+	/*
+	 * If the VMM has overridden the certs, then change the error message
+	 * if the size is inappropriate for the override. Otherwise, use a
+	 * regular guest request and copy back the instance certs.
+	 */
+	if (sev->snp_certs_len) {
+		if ((data_npages << PAGE_SHIFT) < sev->snp_certs_len) {
+			rc = -EINVAL;
+			err = SNP_GUEST_REQ_INVALID_LEN;
+			goto datalen;
+		}
+		rc = sev_issue_cmd(kvm, SEV_CMD_SNP_GUEST_REQUEST, &req,
+				   (int *)&err);
+	} else {
+		rc = snp_guest_ext_guest_request(&req,
+						 (unsigned long)sev->snp_certs_data,
+						 &data_npages, &err);
+	}
+datalen:
+	if (sev->snp_certs_len)
+		data_npages = sev->snp_certs_len >> PAGE_SHIFT;
+
 	if (rc) {
 		/*
 		 * If buffer length is small then return the expected
arch/x86/kvm/svm/svm.h +1 -0
index 221b38d3c845..dced46559508 100644
@@ -94,6 +94,7 @@ struct kvm_sev_info {
 	u64 snp_init_flags;
 	void *snp_context;      /* SNP guest context page */
 	void *snp_certs_data;
+	unsigned int snp_certs_len; /* Size of instance override for certs */
 	struct mutex guest_req_lock; /* Lock for guest request handling */
 
 	u64 sev_features;	/* Features set at VMSA creation */
include/linux/psp-sev.h +1 -1
index 92116e2b74fd..3b28b78938f6 100644
@@ -22,7 +22,7 @@
 #define __psp_pa(x)	__pa(x)
 #endif
 
-#define SEV_FW_BLOB_MAX_SIZE	0x4000	/* 16KB */
+#define SEV_FW_BLOB_MAX_SIZE	0x5000	/* 20KB */
 
 /**
  * SEV platform state
include/uapi/linux/kvm.h +12 -0
index 6e684bf5f723..ad7e24e43547 100644
@@ -1928,6 +1928,8 @@ enum sev_cmd_id {
 	KVM_SEV_SNP_LAUNCH_START,
 	KVM_SEV_SNP_LAUNCH_UPDATE,
 	KVM_SEV_SNP_LAUNCH_FINISH,
+	KVM_SEV_SNP_GET_CERTS,
+	KVM_SEV_SNP_SET_CERTS,
 
 	KVM_SEV_NR_MAX,
 };
@@ -2075,6 +2077,16 @@ struct kvm_sev_snp_launch_finish {
 	__u8 pad[6];
 };
 
+struct kvm_sev_snp_get_certs {
+	__u64 certs_uaddr;
+	__u64 certs_len;
+};
+
+struct kvm_sev_snp_set_certs {
+	__u64 certs_uaddr;
+	__u64 certs_len;
+};
+
 #define KVM_DEV_ASSIGN_ENABLE_IOMMU	(1 << 0)
 #define KVM_DEV_ASSIGN_PCI_2_3		(1 << 1)
 #define KVM_DEV_ASSIGN_MASK_INTX	(1 << 2)
#138 lore raw

Re: [PATCH RFC v8 54/56] x86/sev: Add KVM commands for instance certs

Quoted 11 lines

arch/x86/kvm/svm/sev.c static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 2095

Quoted 8 lines
arch/x86/kvm/svm/sev.c +1 -0
@@ -2089,6 +2089,7 @@ static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp)
              goto e_free;
 
      sev->snp_certs_data = certs_data;
+     sev->snp_certs_len = 0;
 
      return context;
 

Better to move the fix to PATCH 45.

This part isn't a fix, but part of the implementation since snp_certs_len is added in this patch here

Quoted 12 lines
Quoted 12 lines
arch/x86/kvm/svm/svm.h +1 -0
index 221b38d3c845..dced46559508 100644
@@ -94,6 +94,7 @@ struct kvm_sev_info {
      u64 snp_init_flags;
      void *snp_context;      /* SNP guest context page */
      void *snp_certs_data;
+     unsigned int snp_certs_len; /* Size of instance override for certs */
      struct mutex guest_req_lock; /* Lock for guest request handling */
 
      u64 sev_features;       /* Features set at VMSA creation */
Signature · 1 line
-Dionna Glaze, PhD (she/her)
#139 lore raw

Re: [PATCH RFC v8 54/56] x86/sev: Add KVM commands for instance certs

Quoted 6 lines · On Wed, 1 Mar 2023 17:41:11 -0800 Dionna Amalie Glaze <[email protected]>…
Quoted 6 lines
Quoted 6 lines
arch/x86/kvm/svm/sev.c +1 -0
@@ -2089,6 +2089,7 @@ static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp)
              goto e_free;
 
      sev->snp_certs_data = certs_data;
+     sev->snp_certs_len = 0;
 
Quoted 9 lines
Quoted 5 lines

arch/x86/kvm/svm/sev.c static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 2095

Quoted 2 lines
arch/x86/kvm/svm/sev.c +0 -0
      return context;
 

Better to move the fix to PATCH 45.

This part isn't a fix, but part of the implementation since snp_certs_len is added in this patch here

I see. My bad. Was thinking it was the snp_serts_len in the global sev as they has the same name.

Quoted 14 lines
Quoted 12 lines
Quoted 12 lines
arch/x86/kvm/svm/svm.h +1 -0
index 221b38d3c845..dced46559508 100644
@@ -94,6 +94,7 @@ struct kvm_sev_info {
      u64 snp_init_flags;
      void *snp_context;      /* SNP guest context page */
      void *snp_certs_data;
+     unsigned int snp_certs_len; /* Size of instance override for certs */
      struct mutex guest_req_lock; /* Lock for guest request handling */
 
      u64 sev_features;       /* Features set at VMSA creation */
#140 lore raw

Re: [PATCH RFC v8 54/56] x86/sev: Add KVM commands for instance certs

In reply to Michael Roth
Quoted 40 lines · Michael Roth

From: Dionna Glaze <[email protected]>

The /dev/sev device has the ability to store host-wide certificates for the key used by the AMD-SP for SEV-SNP attestation report signing, but for hosts that want to specify additional certificates that are specific to the image launched in a VM, a different way is needed to communicate those certificates.

Add two new KVM ioctl to handle this: KVM_SEV_SNP_{GET,SET}_CERTS

The certificates that are set with this command are expected to follow the same format as the host certificates, but that format is opaque to the kernel.

The new behavior for custom certificates is that the extended guest request command will now return the overridden certificates if they were installed for the instance. The error condition for a too small data buffer is changed to return the overridden certificate data size if there is an overridden certificate set installed.

Setting a 0 length certificate returns the system state to only return the host certificates on an extended guest request.

Also increase the SEV_FW_BLOB_MAX_SIZE another 4K page to allow space for an extra certificate.

Cc Tom Lendacky <[email protected]>
Cc Paolo Bonzini <[email protected]>
[mdr: remove used of "we" and "this patch" in commit log]
---
 arch/x86/kvm/svm/sev.c   | 111 ++++++++++++++++++++++++++++++++++++++-
 arch/x86/kvm/svm/svm.h   |   1 +
 include/linux/psp-sev.h  |   2 +-
 include/uapi/linux/kvm.h |  12 +++++
 4 files changed, 123 insertions(+), 3 deletions(-)

[...]

include/linux/psp-sev.h line 25

Quoted 10 lines
include/linux/psp-sev.h +1 -1
index 92116e2b74fd..3b28b78938f6 100644
@@ -22,7 +22,7 @@
 #define __psp_pa(x)	__pa(x)
 #endif
 
-#define SEV_FW_BLOB_MAX_SIZE	0x4000	/* 16KB */
+#define SEV_FW_BLOB_MAX_SIZE	0x5000	/* 20KB */

This change should be removed (it was also discussed in v7). If I understand correctly, 16KB is a limit of the PSP.

-Dov

Quoted 3 lines
include/linux/psp-sev.h +0 -0
 /**
  * SEV platform state
#141 lore raw

RFC PATCH v8 55/56 x86/sev: Document KVM_SEV_SNP_{G,S}ET_CERTS

In reply to Michael Roth

From: Dionna Glaze <[email protected]>

Update the KVM_MEMORY_ENCRYPT_OP documentation to include the new commands for overriding the host certificates that the guest receives from an extended guest request.

Cc Thomas Lendacky <[email protected]>
Cc Paolo Bonzini <[email protected]>
---
 .../virt/kvm/x86/amd-memory-encryption.rst    | 44 +++++++++++++++++++
 1 file changed, 44 insertions(+)
Documentation/virt/kvm/x86/amd-memory-encryption.rst +44 -0
index dafb0c9984f1..153003ff2c51 100644
@@ -537,6 +537,50 @@ Returns: 0 on success, -negative on error
 
 See SEV-SNP specification for further details on launch finish input parameters.
 
+22. KVM_SEV_SNP_GET_CERTS
+-------------------------
+
+After the SNP guest launch flow has started, the KVM_SEV_SNP_GET_CERTS command
+can be issued to request the data that has been installed with the
+KVM_SEV_SNP_SET_CERTS command.
+
+Parameters (in/out): struct kvm_sev_snp_get_certs
+
+Returns: 0 on success, -negative on error
+
+::
+
+	struct kvm_sev_snp_get_certs {
+		__u64 certs_uaddr;
+		__u64 certs_len
+	};
+
+If no certs have been installed, then the return value is -ENOENT.
+If the buffer specified in the struct is too small, the certs_len field will be
+overwritten with the required bytes to receive all the certificate bytes and the
+return value will be -EINVAL.
+
+23. KVM_SEV_SNP_SET_CERTS
+-------------------------
+
+After the SNP guest launch flow has started, the KVM_SEV_SNP_SET_CERTS command
+can be issued to override the /dev/sev certs data that is returned when a
+guest issues an extended guest request. This is useful for instance-specific
+extensions to the host certificates.
+
+Parameters (in/out): struct kvm_sev_snp_set_certs
+
+Returns: 0 on success, -negative on error
+
+::
+
+	struct kvm_sev_snp_set_certs {
+		__u64 certs_uaddr;
+		__u64 certs_len
+	};
+
+The certs_len field may not exceed SEV_FW_BLOB_MAX_SIZE.
+
 References
 ==========
 
Signature · 1 line
2.25.1
#142 lore raw

RFC PATCH v8 56/56 iommu/amd: Add IOMMU_SNP_SHUTDOWN support

In reply to Michael Roth

From: Ashish Kalra <[email protected]>

Add a new IOMMU API interface amd_iommu_snp_disable() to transition IOMMU pages to Hypervisor state from Reclaim state after SNP_SHUTDOWN_EX command. Invoke this API from the CCP driver after SNP_SHUTDOWN_EX command.

---
 drivers/crypto/ccp/sev-dev.c | 20 ++++++++++++++
 drivers/iommu/amd/init.c     | 53 ++++++++++++++++++++++++++++++++++++
 include/linux/amd-iommu.h    |  1 +
 3 files changed, 74 insertions(+)
drivers/crypto/ccp/sev-dev.c +20 -0
index bf5167b2acfc..7ded2f9111e0 100644
@@ -24,6 +24,7 @@
 #include <linux/cpufeature.h>
 #include <linux/fs.h>
 #include <linux/fs_struct.h>
+#include <linux/amd-iommu.h>
 
 #include <asm/smp.h>
 #include <asm/e820/types.h>
@@ -1503,6 +1504,25 @@ static int __sev_snp_shutdown_locked(int *error)
 		return ret;
 	}
 
+	/*
+	 * SNP_SHUTDOWN_EX with IOMMU_SNP_SHUTDOWN set to 1 disables SNP
+	 * enforcement by the IOMMU and also transitions all pages
+	 * associated with the IOMMU to the Reclaim state.
+	 * Firmware was transitioning the IOMMU pages to Hypervisor state
+	 * before version 1.53. But, accounting for the number of assigned
+	 * 4kB pages in a 2M page was done incorrectly by not transitioning
+	 * to the Reclaim state. This resulted in RMP #PF when later accessing
+	 * the 2M page containing those pages during kexec boot. Hence, the
+	 * firmware now transitions these pages to Reclaim state and hypervisor
+	 * needs to transition these pages to shared state. SNP Firmware
+	 * version 1.53 and above are needed for kexec boot.
+	 */
+	ret = amd_iommu_snp_disable();
+	if (ret) {
+		dev_err(sev->dev, "SNP IOMMU shutdown failed\n");
+		return ret;
+	}
+
 	sev->snp_initialized = false;
 	dev_dbg(sev->dev, "SEV-SNP firmware shutdown\n");
 
drivers/iommu/amd/init.c +53 -0

63 lines not on this page · raw message

include/linux/amd-iommu.h +1 -0
index 953e6f12fa1c..a1b33b838842 100644
@@ -208,6 +208,7 @@ struct amd_iommu *get_amd_iommu(unsigned int idx);
 
 #ifdef CONFIG_AMD_MEM_ENCRYPT
 int amd_iommu_snp_enable(void);
+int amd_iommu_snp_disable(void);
 #endif
 
 #endif /* _ASM_X86_AMD_IOMMU_H */
Signature · 1 line
2.25.1
#143 lore raw
In reply to Michael Roth
Quoted 7 lines · Michael Roth

The RMP check is enforced as soon as SEV-SNP is enabled. Not every memory access requires an RMP check. In particular, the read accesses from the hypervisor do not require RMP checks because the data confidentiality is already protected via memory encryption. When hardware encounters an RMP checks failure, it raises a page-fault exception. If RMP check failure is due to the page-size mismatch, then split the large page to resolve the fault.

What does this all _mean_?

When does the kernel need to care about a "page-size mismatch"?

#144 lore raw
Quoted 11 lines · On Wed, 1 Mar 2023 08:56:05 -0800 Dave Hansen <[email protected]> wrote:
Quoted 7 lines · Michael Roth

The RMP check is enforced as soon as SEV-SNP is enabled. Not every memory access requires an RMP check. In particular, the read accesses from the hypervisor do not require RMP checks because the data confidentiality is already protected via memory encryption. When hardware encounters an RMP checks failure, it raises a page-fault exception. If RMP check failure is due to the page-size mismatch, then split the large page to resolve the fault.

What does this all _mean_?

Unlike TDX which implements secure EPT to hold the restricted memory mapping, SEV-SNP is still using one NPT (similar to Intel EPT) while adding another level of HW-enforced check controlled by the "RMP" table. Similar to TDX, it has firmware calls to modify the attributes in the RMP table to achieve isolation and shared-private memory conversion.

The purpose and structure of RMP is quite similar to the PAMT table in TDX from the perspective of managing the per-page attributes. Each system page has a collection of attribute bits. But TDX only uses the PAMT as metadata as it has a separate secure EPT to achieve HW-enforced check.

The RMP memory access checks has its own schematics. E.g. data write, page table access from VMM will be checked, but data read is not, mostly I guess, due to performance consideration. More details can be found from Table 15-39. RMP Memory Access Checks in [1].

Quoted 1 line

When does the kernel need to care about a "page-size mismatch"?

The RMP table has the ability to describe a large page (similar to a large page with a description of large-page PAMT entry in TDX that can be demoted via TDX SEAMCALLs). E.g. 2MB page.

When the userspace sets the memory attribute of a GFN range through the restricted memory ioctl, the sev logic (sev_update_mem_attr() in PATCH 48, to be precise) will try to build a large page description in the RMP table if the PFNs are continuous. When kernel mm breaks the the large page due to THP, KVM updates the NPT accordingly.

Then there will be a page-size mismatch between NPT and RMP. It will be resolved by a RMP fault later. Kinda of lazy sync.

[1] https://www.amd.com/system/files/TechDocs/24593.pdf

#145 lore raw
Quoted 5 lines · Zhi Wang

When the userspace sets the memory attribute of a GFN range through the restricted memory ioctl, the sev logic (sev_update_mem_attr() in PATCH 48, to be precise) will try to build a large page description in the RMP table if the PFNs are continuous. When kernel mm breaks the the large page due to THP, KVM updates the NPT accordingly.

Gah, this really confused me.

It's *NOT* looking for contiguous PFNs. It's looking for a restrictedmem THP, which really is something different. Restrictedmem THPs have contiguous PFNs, but not all contiguous PFNs will result in trying to build a large page.

Anyway, I'll reply over to the other patch.

But, either way, I'd appreciate this kind of summary in the changelogs and probably a comment or two:

The RMP needs to be consistent with the contents of the NPT. KVM updates the NPT but will neglect to update the RMP. It is updated in response to faults when RMP and NPT get out of sync.

Right?

BTW, why doesn't KVM just update the RMP? Why bother taking the fault?

#146 lore raw
In reply to Michael Roth

We discovered that the kdump crashkernel would not work with our SEV- SNP configuration.

After reading the device table from the previour kernel we would see a lot of
AMD-Vi: Completion-Wait loop timed out
errors and finally crash:

  Kernel panic - not syncing: timer doesn't work through Interrupt-

remapped IO-APIC

We found that disabeling SNP in the outgoing (crashing) kernel would enable the crashkernel to take over the iommu config and boot from there.

We opened a PR over on github against the rfc-v9 branch to discuss the issue:
https://github.com/AMDESE/linux/pull/5

Cheers Johanna

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879

maintainer
#147 lore raw

Please look at the response on github and followup discussion.

Thanks,
Ashish

Quoted 35 lines · Johanna 'Mimoja' Amelie

We discovered that the kdump crashkernel would not work with our SEV- SNP configuration.

After reading the device table from the previour kernel we would see a lot of
AMD-Vi: Completion-Wait loop timed out
errors and finally crash:

   Kernel panic - not syncing: timer doesn't work through Interrupt-

remapped IO-APIC

We found that disabeling SNP in the outgoing (crashing) kernel would enable the crashkernel to take over the iommu config and boot from there.

We opened a PR over on github against the rfc-v9 branch to discuss the issue:
https://github.com/AMDESE/linux/pull/5

Cheers Johanna

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879