Skip to contentSkip to conversation

Add AMD Secure Nested Paging (SEV-SNP) support

PATCH In review Pankaj Gupta 9 participants 73 messages May 30, 2024 – Jul 4, 2024

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

v4 cover Add AMD Secure Nested Paging (SEV-SNP) support

These patches implement SEV-SNP base support along with CPUID enforcement support for QEMU, and are also available at:

https://github.com/pagupta/qemu/tree/snp_v4

Latest version of kvm changes are posted here [2] and also queued in kvm/next.

Patch Layout
------------
01-03: 'error_setg' independent fix, kvm/next header sync & patch from
Xiaoyao's TDX v5 patchset.
04-29: Introduction of sev-snp-guest object and various configuration
requirements for SNP. Support for creating a cryptographic "launch" context and populating various OVMF metadata pages, BIOS regions, and vCPU/VMSA pages with the initial encrypted/measured/validated launch data prior to launching the SNP guest.
30-31: Handling for KVM_HC_MAP_GPA_RANGE hypercall for userspace VMEXIT.

Testing
-------
This series has been tested against the kvm/next tree and the AMDSEV tree [1].

[1] https://github.com/AMDESE/linux/commits/snp-host-latest/

Below version of OVMF is used to test the changes.

https://github.com/mdroth/edk2/commits/apic-mmio-fix1d/

A basic command-line invocation for SNP would be:

qemu-system-x86_64 -smp 32,maxcpus=255 -cpu EPYC-Milan-v2
-machine q35,confidential-guest-support=sev0,memory-backend=ram1 -object memory-backend-memfd,id=ram1,size=4G,share=true,reserve=false -object sev-snp-guest,id=sev0,cbitpos=51,reduced-phys-bits=1,id-auth= -bios OVMF_CODE-upstream-20240410-apic-mmio-fix1d-AmdSevX64.fd

With kernel-hashing and certificate data supplied:

qemu-system-x86_64 -smp 32,maxcpus=255 -cpu EPYC-Milan-v2
-machine q35,confidential-guest-support=sev0,memory-backend=ram1
-object memory-backend-memfd,id=ram1,size=4G,share=true,reserve=false -object sev-snp-guest,id=sev0,cbitpos=51,reduced-phys-bits=1,id-auth=,kernel-hashes=on -bios OVMF_CODE-upstream-20240410-apic-mmio-fix1d-AmdSevX64.fd
-kernel /boot/vmlinuz-$ver
-initrd /boot/initrd.img-$ver
-append "root=UUID=d72a6d1c-06cf-4b79-af43-f1bac4f620f9 ro console=ttyS0,115200n8"

With standard X64 OVMF package with separate image for persistent NVRAM:

qemu-system-x86_64 -smp 32,maxcpus=255 -cpu EPYC-Milan-v2
-machine q35,confidential-guest-support=sev0,memory-backend=ram1
-object memory-backend-memfd,id=ram1,size=4G,share=true,reserve=false
-object sev-snp-guest,id=sev0,cbitpos=51,reduced-phys-bits=1,id-auth=
-bios OVMF_CODE-upstream-20240410-apic-mmio-fix1d.fd
-drive if=pflash,format=raw,unit=0,file=OVMF_VARS-upstream-20240410-apic-mmio-fix1d.fd,readonly=off:

Any comments/feedback would be very much appreciated.

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

Changes since rfc3:

- added class methods (SEV & SNP) for functions changes suggested in RFC v3:
launch_start(), launch_update_data(), launch_finish(), kvm_init(), kvm_type() (Paolo)
- improved qom.json, query-sev QAPI text suggestions (Daniel & Markus).
- moved 'pc_system_parse_sev_metadata' to 'target/i386/sev.c' (Isaku).
- moved SNP specific methods (set guest_mem_fd, no smm check, no disable block discard) to sev_snp_kvm_init().
- squashed qapi changes for SecCommonProperties into 'sev-guest-common' patch (Daniel, Markus)
- made legacy bios support to SNP only.
- switch to using KVM_HC_MAP_GPA_RANGE to handle page-state change
requests rather than directly processing GHCB page-state change buffer
- drop attestation certificate support, will revisit once the KVM_EXIT_*
event mechanism is finalized
- sync headers with kvm/next, which now contains base KVM SNP support
- some more fixes including missing 'return', length checks,
monitor logs improvements. (Daniel, Markus)

Changes since rfc2:

- reworked on top of guest_memfd support
- added handling for various KVM_EXIT_VMGEXIT events
- various changes/considerations for PCI passthrough support
- general bugfixes/hardening/cleanups
- qapi cmdline doc fixes/rework (Dov, Markus)
- switch to qbase64_decode, more error-checking for cmdline opts (Dov)
- unset id_block_en for 0 input (Dov)
- use error_setg in snp init (Dov)
- report more info in trace_kvm_sev_init (Dov)
- rework bounds-checking for kvm_cpuid_info, rework existing checks for readability, add additional checks (Dov)
- fixups for validated_ranges handling (Dov)
- rename 'policy' field to 'snp-policy' in query-sev when sev-type is SNP

Changes since rfc1:

- rebased onto latest master
- drop SNP config file in favor of a new 'sev-snp-guest' object where all SNP-related params are passed as strings/integers via command-line
- report specific error if BIOS reports invalid address/len for reserved/pre-validated regions (Connor)
- use Range helpers for handling validated region overlaps (Dave)
- simplify error handling in sev_snp_launch_start, and report the correct return code when handling LAUNCH_START failures (Dov)
- add SEV-SNP bit to CPUID 0x8000001f when SNP enabled
- updated query-sev to handle differences between SEV and SEV-SNP
- updated to work against v5 of SEV-SNP host kernel / hypervisor patches

Brijesh Singh (6):
i386/sev: Introduce 'sev-snp-guest' object
i386/sev: Add the SNP launch start context
i386/sev: Add handling to encrypt/finalize guest launch data hw/i386/sev: Add function to get SEV metadata from OVMF header i386/sev: Add support for populating OVMF metadata pages hw/i386/sev: Add support to encrypt BIOS when SEV-SNP is enabled

Dov Murik (3):
i386/sev: Extract build_kernel_loader_hashes i386/sev: Reorder struct declarations i386/sev: Allow measured direct kernel boot on SNP

Michael Roth (12):
i386/sev: Introduce "sev-common" type to encapsulate common SEV state i386/sev: Add a sev_snp_enabled() helper
i386/cpu: Set SEV-SNP CPUID bit when SNP enabled
i386/sev: Don't return launch measurements for SEV-SNP guests i386/sev: Update query-sev QAPI format to handle SEV-SNP i386/sev: Set CPU state to protected once SNP guest payload is
finalized
i386/sev: Add support for SNP CPUID validation hw/i386/sev: Use guest_memfd for legacy ROMs
hw/i386: Add support for loading BIOS using guest_memfd hw/i386/sev: Allow use of pflash in conjunction with -bios i386/kvm: Add KVM_EXIT_HYPERCALL handling for KVM_HC_MAP_GPA_RANGE i386/sev: Enable KVM_HC_MAP_GPA_RANGE hcall for SNP guests

Pankaj Gupta (9):
i386/sev: Replace error_report with error_setg
linux-headers: Update to current kvm/next
i386/sev: Move sev_launch_update to separate class method i386/sev: Move sev_launch_finish to separate class method i386/sev: Add sev_kvm_init() override for SEV class i386/sev: Add snp_kvm_init() override for SNP class i386/sev: Add a class method to determine KVM VM type for SNP guests i386/sev: Invoke launch_updata_data() for SEV class i386/sev: Invoke launch_updata_data() for SNP class

Xiaoyao Li (1):
memory: Introduce memory_region_init_ram_guest_memfd()

 docs/system/i386/amd-memory-encryption.rst |   70 +-
 hw/i386/pc.c                               |   14 +-
 hw/i386/pc_sysfw.c                         |   76 +-
 hw/i386/x86-common.c                       |   24 +-
 include/exec/memory.h                      |    6 +
 include/hw/i386/pc.h                       |   28 +
 include/hw/i386/x86.h                      |    2 +-
 linux-headers/asm-loongarch/bitsperlong.h  |   23 +
 linux-headers/asm-loongarch/kvm.h          |    4 +
 linux-headers/asm-loongarch/mman.h         |    9 +
 linux-headers/asm-riscv/kvm.h              |    1 +
 linux-headers/asm-riscv/mman.h             |   36 +-
 linux-headers/asm-s390/mman.h              |   36 +-
 linux-headers/asm-x86/kvm.h                |   52 +-
 linux-headers/linux/vhost.h                |   15 +-
 qapi/misc-target.json                      |   72 +-
 qapi/qom.json                              |   97 +-
 system/memory.c                            |   24 +
 target/i386/cpu.c                          |    1 +
 target/i386/kvm/kvm.c                      |   55 +
 target/i386/kvm/kvm_i386.h                 |    1 +
 target/i386/kvm/trace-events               |    1 +
 target/i386/sev-sysemu-stub.c              |    2 +-
 target/i386/sev.c                          | 1588 +++++++++++++++-----
 target/i386/sev.h                          |   13 +-
 target/i386/trace-events                   |    3 +
 26 files changed, 1833 insertions(+), 420 deletions(-)
Signature · 1 line
2.34.1
#1 lore raw

PATCH v4 1/31 i386/sev: Replace error_report with error_setg

---
 target/i386/sev.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
target/i386/sev.c +3 -3
index d30b68c11e..67ed32e5ea 100644
@@ -952,13 +952,13 @@ static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
 
     if (sev_es_enabled()) {
         if (!kvm_kernel_irqchip_allowed()) {
-            error_report("%s: SEV-ES guests require in-kernel irqchip support",
-                         __func__);
+            error_setg(errp, "%s: SEV-ES guests require in-kernel irqchip"
+                       "support", __func__);
             goto err;
         }
 
         if (!(status.flags & SEV_STATUS_FLAGS_CONFIG_ES)) {
-            error_report("%s: guest policy requires SEV-ES, but "
+            error_setg(errp, "%s: guest policy requires SEV-ES, but "
                          "host SEV-ES support unavailable",
                          __func__);
             goto err;
Signature · 1 line
2.34.1
#2 lore raw

Re: [PATCH v4 01/31] i386/sev: Replace error_report with error_setg

Quoted 16 lines · Pankaj Gupta
---
 target/i386/sev.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
target/i386/sev.c +1 -2
index d30b68c11e..67ed32e5ea 100644
@@ -952,13 +952,13 @@ static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
 
     if (sev_es_enabled()) {
         if (!kvm_kernel_irqchip_allowed()) {
-            error_report("%s: SEV-ES guests require in-kernel irqchip support",
-                         __func__);
+            error_setg(errp, "%s: SEV-ES guests require in-kernel irqchip"

target/i386/sev.c static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp) · line 964

Quoted 10 lines
target/i386/sev.c +2 -1
+                       "support", __func__);
             goto err;
         }
 
         if (!(status.flags & SEV_STATUS_FLAGS_CONFIG_ES)) {
-            error_report("%s: guest policy requires SEV-ES, but "
+            error_setg(errp, "%s: guest policy requires SEV-ES, but "
                          "host SEV-ES support unavailable",
                          __func__);
             goto err;

While changing this, I'd suggest removing '__func__' frmo this - including internal function names in an error message is not useful to the end user, as this is a private impl detail, and the text message is sufficiently clear of the problem already.

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#3 lore raw

PATCH v4 2/31 linux-headers: Update to current kvm/next

In reply to Pankaj Gupta
---
 linux-headers/asm-loongarch/bitsperlong.h | 23 ++++++++++
 linux-headers/asm-loongarch/kvm.h         |  4 ++
 linux-headers/asm-loongarch/mman.h        |  9 ++++
 linux-headers/asm-riscv/kvm.h             |  1 +
 linux-headers/asm-riscv/mman.h            | 36 +++++++++++++++-
 linux-headers/asm-s390/mman.h             | 36 +++++++++++++++-
 linux-headers/asm-x86/kvm.h               | 52 ++++++++++++++++++++++-
 linux-headers/linux/vhost.h               | 15 ++++---
 8 files changed, 166 insertions(+), 10 deletions(-)
linux-headers/asm-loongarch/bitsperlong.h +23 -0
index 6dc0bb0c13..485d60bee2 100644
@@ -1 +1,24 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+/*
+ * Copyright (C) 2012 ARM Ltd.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+#ifndef __ASM_BITSPERLONG_H
+#define __ASM_BITSPERLONG_H
+
+#define __BITS_PER_LONG 64
+
 #include <asm-generic/bitsperlong.h>
+
+#endif	/* __ASM_BITSPERLONG_H */
linux-headers/asm-loongarch/kvm.h +4 -0
index 109785922c..f9abef3823 100644
@@ -17,6 +17,8 @@
 #define KVM_COALESCED_MMIO_PAGE_OFFSET	1
 #define KVM_DIRTY_LOG_PAGE_OFFSET	64
 
+#define KVM_GUESTDBG_USE_SW_BP		0x00010000
+
 /*
  * for KVM_GET_REGS and KVM_SET_REGS
  */
@@ -72,6 +74,8 @@ struct kvm_fpu {
 
 #define KVM_REG_LOONGARCH_COUNTER	(KVM_REG_LOONGARCH_KVM | KVM_REG_SIZE_U64 | 1)
 #define KVM_REG_LOONGARCH_VCPU_RESET	(KVM_REG_LOONGARCH_KVM | KVM_REG_SIZE_U64 | 2)
+/* Debugging: Special instruction for software breakpoint */
+#define KVM_REG_LOONGARCH_DEBUG_INST	(KVM_REG_LOONGARCH_KVM | KVM_REG_SIZE_U64 | 3)
 
 #define LOONGARCH_REG_SHIFT		3
 #define LOONGARCH_REG_64(TYPE, REG)	(TYPE | KVM_REG_SIZE_U64 | (REG << LOONGARCH_REG_SHIFT))
linux-headers/asm-loongarch/mman.h +9 -0
index 8eebf89f5a..d0dbfe9587 100644
@@ -1 +1,10 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+#ifndef __ASM_MMAN_H
+#define __ASM_MMAN_H
+
 #include <asm-generic/mman.h>
+
+#define PROT_BTI	0x10		/* BTI guarded page */
+#define PROT_MTE	0x20		/* Normal Tagged mapping */
+
+#endif /* ! _UAPI__ASM_MMAN_H */
linux-headers/asm-riscv/kvm.h +1 -0
index b1c503c295..e878e7cc39 100644
@@ -167,6 +167,7 @@ enum KVM_RISCV_ISA_EXT_ID {
 	KVM_RISCV_ISA_EXT_ZFA,
 	KVM_RISCV_ISA_EXT_ZTSO,
 	KVM_RISCV_ISA_EXT_ZACAS,
+	KVM_RISCV_ISA_EXT_SSCOFPMF,
 	KVM_RISCV_ISA_EXT_MAX,
 };
 
linux-headers/asm-riscv/mman.h +35 -1
index 8eebf89f5a..8db7c2a3be 100644
@@ -1 +1,35 @@
-#include <asm-generic/mman.h>
+/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */
+/*
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version
+ * 2 of the License, or (at your option) any later version.
+ */
+#ifndef _ASM_POWERPC_MMAN_H
+#define _ASM_POWERPC_MMAN_H
+
+#include <asm-generic/mman-common.h>
+
+
+#define PROT_SAO	0x10		/* Strong Access Ordering */
+
+#define MAP_RENAME      MAP_ANONYMOUS   /* In SunOS terminology */
+#define MAP_NORESERVE   0x40            /* don't reserve swap pages */
+#define MAP_LOCKED	0x80
+
+#define MAP_GROWSDOWN	0x0100		/* stack-like segment */
+#define MAP_DENYWRITE	0x0800		/* ETXTBSY */
+#define MAP_EXECUTABLE	0x1000		/* mark it as an executable */
+
+
+#define MCL_CURRENT     0x2000          /* lock all currently mapped pages */
+#define MCL_FUTURE      0x4000          /* lock all additions to address space */
+#define MCL_ONFAULT	0x8000		/* lock all pages that are faulted in */
+
+/* Override any generic PKEY permission defines */
+#define PKEY_DISABLE_EXECUTE   0x4
+#undef PKEY_ACCESS_MASK
+#define PKEY_ACCESS_MASK       (PKEY_DISABLE_ACCESS |\
+				PKEY_DISABLE_WRITE  |\
+				PKEY_DISABLE_EXECUTE)
+#endif /* _ASM_POWERPC_MMAN_H */
linux-headers/asm-s390/mman.h +35 -1
index 8eebf89f5a..8db7c2a3be 100644
@@ -1 +1,35 @@
-#include <asm-generic/mman.h>
+/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */
+/*
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version
+ * 2 of the License, or (at your option) any later version.
+ */
+#ifndef _ASM_POWERPC_MMAN_H
+#define _ASM_POWERPC_MMAN_H
+
+#include <asm-generic/mman-common.h>
+
+
+#define PROT_SAO	0x10		/* Strong Access Ordering */
+
+#define MAP_RENAME      MAP_ANONYMOUS   /* In SunOS terminology */
+#define MAP_NORESERVE   0x40            /* don't reserve swap pages */
+#define MAP_LOCKED	0x80
+
+#define MAP_GROWSDOWN	0x0100		/* stack-like segment */
+#define MAP_DENYWRITE	0x0800		/* ETXTBSY */
+#define MAP_EXECUTABLE	0x1000		/* mark it as an executable */
+
+
+#define MCL_CURRENT     0x2000          /* lock all currently mapped pages */
+#define MCL_FUTURE      0x4000          /* lock all additions to address space */
+#define MCL_ONFAULT	0x8000		/* lock all pages that are faulted in */
+
+/* Override any generic PKEY permission defines */
+#define PKEY_DISABLE_EXECUTE   0x4
+#undef PKEY_ACCESS_MASK
+#define PKEY_ACCESS_MASK       (PKEY_DISABLE_ACCESS |\
+				PKEY_DISABLE_WRITE  |\
+				PKEY_DISABLE_EXECUTE)
+#endif /* _ASM_POWERPC_MMAN_H */
linux-headers/asm-x86/kvm.h +51 -1

75 lines not on this page · raw message

linux-headers/linux/vhost.h +8 -7
index bea6973906..b95dd84eef 100644
@@ -179,12 +179,6 @@
 /* Get the config size */
 #define VHOST_VDPA_GET_CONFIG_SIZE	_IOR(VHOST_VIRTIO, 0x79, __u32)
 
-/* Get the count of all virtqueues */
-#define VHOST_VDPA_GET_VQS_COUNT	_IOR(VHOST_VIRTIO, 0x80, __u32)
-
-/* Get the number of virtqueue groups. */
-#define VHOST_VDPA_GET_GROUP_NUM	_IOR(VHOST_VIRTIO, 0x81, __u32)
-
 /* Get the number of address spaces. */
 #define VHOST_VDPA_GET_AS_NUM		_IOR(VHOST_VIRTIO, 0x7A, unsigned int)
 
@@ -228,10 +222,17 @@
 #define VHOST_VDPA_GET_VRING_DESC_GROUP	_IOWR(VHOST_VIRTIO, 0x7F,	\
 					      struct vhost_vring_state)
 
+
+/* Get the count of all virtqueues */
+#define VHOST_VDPA_GET_VQS_COUNT	_IOR(VHOST_VIRTIO, 0x80, __u32)
+
+/* Get the number of virtqueue groups. */
+#define VHOST_VDPA_GET_GROUP_NUM	_IOR(VHOST_VIRTIO, 0x81, __u32)
+
 /* Get the queue size of a specific virtqueue.
  * userspace set the vring index in vhost_vring_state.index
  * kernel set the queue size in vhost_vring_state.num
  */
-#define VHOST_VDPA_GET_VRING_SIZE	_IOWR(VHOST_VIRTIO, 0x80,	\
+#define VHOST_VDPA_GET_VRING_SIZE	_IOWR(VHOST_VIRTIO, 0x82,	\
 					      struct vhost_vring_state)
 #endif
Signature · 1 line
2.34.1
#4 lore raw

Re: [PATCH v4 02/31] linux-headers: Update to current kvm/next

Quoted 19 lines · Pankaj Gupta
---
  linux-headers/asm-loongarch/bitsperlong.h | 23 ++++++++++
  linux-headers/asm-loongarch/kvm.h         |  4 ++
  linux-headers/asm-loongarch/mman.h        |  9 ++++
  linux-headers/asm-riscv/kvm.h             |  1 +
  linux-headers/asm-riscv/mman.h            | 36 +++++++++++++++-
  linux-headers/asm-s390/mman.h             | 36 +++++++++++++++-
  linux-headers/asm-x86/kvm.h               | 52 ++++++++++++++++++++++-
  linux-headers/linux/vhost.h               | 15 ++++---
  8 files changed, 166 insertions(+), 10 deletions(-)

linux-headers/asm-x86/kvm.h struct kvm_hyperv_eventfd { · line 922

Quoted 4 lines
linux-headers/asm-x86/kvm.h +1 -0
@@ -870,5 +919,6 @@ struct kvm_hyperv_eventfd {
  #define KVM_X86_SW_PROTECTED_VM     1
  #define KVM_X86_SEV_VM              2
  #define KVM_X86_SEV_ES_VM   3
+#define KVM_X86_SNP_VM               4

I'm not sure which is the best patch, but there needs to be an array entry added for vm_type_name[KVM_X86_SNP_VM] in target/i386/kvm/kvm.c

Regards,
Liam

maintainer
#5 lore raw

Re: [PATCH v4 02/31] linux-headers: Update to current kvm/next

Quoted 10 lines · Liam Merwick

linux-headers/asm-x86/kvm.h struct kvm_hyperv_eventfd { · line 922

Quoted 7 lines
linux-headers/asm-x86/kvm.h +1 -0
@@ -870,5 +919,6 @@ struct kvm_hyperv_eventfd {
  #define KVM_X86_SW_PROTECTED_VM     1
  #define KVM_X86_SEV_VM              2
  #define KVM_X86_SEV_ES_VM   3
+#define KVM_X86_SNP_VM               4

I'm not sure which is the best patch, but there needs to be an array entry added for vm_type_name[KVM_X86_SNP_VM] in target/i386/kvm/kvm.c

Probably "i386/sev: Add a class method to determine KVM VM type for SNP guests", which is where KVM_X86_SNP_VM appears in the code.

Paolo

#6 lore raw

PATCH v4 3/31 memory: Introduce memory_region_init_ram_guest_memfd()

In reply to Pankaj Gupta

From: Xiaoyao Li <[email protected]>

Introduce memory_region_init_ram_guest_memfd() to allocate private guset memfd on the MemoryRegion initialization. It's for the use case of TDVF, which must be private on TDX case.

---
 include/exec/memory.h |  6 ++++++
 system/memory.c       | 24 ++++++++++++++++++++++++
 2 files changed, 30 insertions(+)
include/exec/memory.h +6 -0
index 9cdd64e9c6..1be58f694c 100644
@@ -1638,6 +1638,12 @@ bool memory_region_init_ram(MemoryRegion *mr,
                             uint64_t size,
                             Error **errp);
 
+bool memory_region_init_ram_guest_memfd(MemoryRegion *mr,
+                                        Object *owner,
+                                        const char *name,
+                                        uint64_t size,
+                                        Error **errp);
+
 /**
  * memory_region_init_rom: Initialize a ROM memory region.
  *
system/memory.c +24 -0
index 9540caa8a1..74cd73ebc7 100644
@@ -3649,6 +3649,30 @@ bool memory_region_init_ram(MemoryRegion *mr,
     return true;
 }
 
+bool memory_region_init_ram_guest_memfd(MemoryRegion *mr,
+                                        Object *owner,
+                                        const char *name,
+                                        uint64_t size,
+                                        Error **errp)
+{
+    DeviceState *owner_dev;
+
+    if (!memory_region_init_ram_flags_nomigrate(mr, owner, name, size,
+                                                RAM_GUEST_MEMFD, errp)) {
+        return false;
+    }
+    /* This will assert if owner is neither NULL nor a DeviceState.
+     * We only want the owner here for the purposes of defining a
+     * unique name for migration. TODO: Ideally we should implement
+     * a naming scheme for Objects which are not DeviceStates, in
+     * which case we can relax this restriction.
+     */
+    owner_dev = DEVICE(owner);
+    vmstate_register_ram(mr, owner_dev);
+
+    return true;
+}
+
 bool memory_region_init_rom(MemoryRegion *mr,
                             Object *owner,
                             const char *name,
Signature · 1 line
2.34.1
#7 lore raw

PATCH v4 4/31 i386/sev: Introduce "sev-common" type to encapsulate common SEV state

In reply to Pankaj Gupta

From: Michael Roth <[email protected]>

Currently all SEV/SEV-ES functionality is managed through a single 'sev-guest' QOM type. With upcoming support for SEV-SNP, taking this same approach won't work well since some of the properties/state managed by 'sev-guest' is not applicable to SEV-SNP, which will instead rely on a new QOM type with its own set of properties/state.

To prepare for this, this patch moves common state into an abstract 'sev-common' parent type to encapsulate properties/state that are common to both SEV/SEV-ES and SEV-SNP, leaving only SEV/SEV-ES-specific properties/state in the current 'sev-guest' type. This should not affect current behavior or command-line options.

As part of this patch, some related changes are also made:

- a static 'sev_guest' variable is currently used to keep track of the 'sev-guest' instance. SEV-SNP would similarly introduce an 'sev_snp_guest' static variable. But these instances are now available via qdev_get_machine()->cgs, so switch to using that instead and drop the static variable.

- 'sev_guest' is currently used as the name for the static variable holding a pointer to the 'sev-guest' instance. Re-purpose the name as a local variable referring the 'sev-guest' instance, and use that consistently throughout the code so it can be easily distinguished from sev-common/sev-snp-guest instances.

- 'sev' is generally used as the name for local variables holding a pointer to the 'sev-guest' instance. In cases where that now points to common state, use the name 'sev_common'; in cases where that now points to state specific to 'sev-guest' instance, use the name 'sev_guest'

In order to enable kernel-hashes for SNP, pull it from SevGuestProperties to its parent SevCommonProperties so it will be available for both SEV and SNP.

---
 qapi/qom.json     |  40 ++--
 target/i386/sev.c | 494 ++++++++++++++++++++++++++--------------------
 target/i386/sev.h |   3 +
 3 files changed, 306 insertions(+), 231 deletions(-)
qapi/qom.json +25 -15
index 38dde6d785..056b38f491 100644
@@ -875,20 +875,12 @@
   'data': { '*filename': 'str' } }
 
 ##
-# @SevGuestProperties:
+# @SevCommonProperties:
 #
-# Properties for sev-guest objects.
+# Properties common to objects that are derivatives of sev-common.
 #
 # @sev-device: SEV device to use (default: "/dev/sev")
 #
-# @dh-cert-file: guest owners DH certificate (encoded with base64)
-#
-# @session-file: guest owners session parameters (encoded with base64)
-#
-# @policy: SEV policy value (default: 0x1)
-#
-# @handle: SEV firmware handle (default: 0)
-#
 # @cbitpos: C-bit location in page table entry (default: 0)
 #
 # @reduced-phys-bits: number of bits in physical addresses that become
@@ -898,6 +890,27 @@
 #     designated guest firmware page for measured boot with -kernel
 #     (default: false) (since 6.2)
 #
+# Since: 9.1
+##
+{ 'struct': 'SevCommonProperties',
+  'data': { '*sev-device': 'str',
+            '*cbitpos': 'uint32',
+            'reduced-phys-bits': 'uint32',
+            '*kernel-hashes': 'bool' } }
+
+##
+# @SevGuestProperties:
+#
+# Properties for sev-guest objects.
+#
+# @dh-cert-file: guest owners DH certificate (encoded with base64)
+#
+# @session-file: guest owners session parameters (encoded with base64)
+#
+# @policy: SEV policy value (default: 0x1)
+#
+# @handle: SEV firmware handle (default: 0)
+#
 # @legacy-vm-type: Use legacy KVM_SEV_INIT KVM interface for creating the VM.
 #                  The newer KVM_SEV_INIT2 interface syncs additional vCPU
 #                  state when initializing the VMSA structures, which will
@@ -909,14 +922,11 @@
 # Since: 2.12
 ##
 { 'struct': 'SevGuestProperties',
-  'data': { '*sev-device': 'str',
-            '*dh-cert-file': 'str',
+  'base': 'SevCommonProperties',
+  'data': { '*dh-cert-file': 'str',
             '*session-file': 'str',
             '*policy': 'uint32',
             '*handle': 'uint32',
-            '*cbitpos': 'uint32',
-            'reduced-phys-bits': 'uint32',
-            '*kernel-hashes': 'bool',
             '*legacy-vm-type': 'bool' } }
 
 ##
target/i386/sev.c +278 -216

924 lines not on this page · raw message

target/i386/sev.h +3 -0
index 9e10d09539..668374eef3 100644
@@ -20,6 +20,9 @@
 
 #include "exec/confidential-guest-support.h"
 
+#define TYPE_SEV_COMMON "sev-common"
+#define TYPE_SEV_GUEST "sev-guest"
+
 #define SEV_POLICY_NODBG        0x1
 #define SEV_POLICY_NOKS         0x2
 #define SEV_POLICY_ES           0x4
Signature · 1 line
2.34.1
maintainer
#8 lore raw

Re: [PATCH v4 04/31] i386/sev: Introduce "sev-common" type to encapsulate common SEV state

target/i386/sev.c

Quoted 6 lines · Pankaj Gupta
target/i386/sev.c +2 -2
-#define TYPE_SEV_GUEST "sev-guest"
-OBJECT_DECLARE_SIMPLE_TYPE(SevGuestState, SEV_GUEST)
 
+OBJECT_DECLARE_TYPE(SevCommonState, SevCommonStateClass, SEV_COMMON)
+OBJECT_DECLARE_TYPE(SevGuestState, SevGuestStateClass, SEV_GUEST)

A separate SevGuestStateClass is not necessary.

target/i386/sev.c sev_guest_class_init(ObjectClass *oc, void *data) · line 1494

Quoted 5 lines
target/i386/sev.c +1 -4
-    .interfaces = (InterfaceInfo[]) {
-        { TYPE_USER_CREATABLE },
-        { }
-    }
+    .class_size = sizeof(SevGuestStateClass),

Declaring .class_size is not needed either because it's the same as the superclass.

Paolo

#9 lore raw

PATCH v4 5/31 i386/sev: Move sev_launch_update to separate class method

In reply to Pankaj Gupta

When sev-snp-guest objects are introduced there will be a number of differences in how the launch data is handled compared to the existing sev-guest object. Move sev_launch_start() to a class method to make it easier to implement SNP-specific launch update functionality later.

---
 target/i386/sev.c | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)
target/i386/sev.c +10 -3
index 79eb21c7d0..3bdb88f2ed 100644
@@ -69,6 +69,8 @@ struct SevCommonState {
 struct SevCommonStateClass {
     X86ConfidentialGuestClass parent_class;
 
+    /* public */
+    int (*launch_start)(SevCommonState *sev_common);
 };
 
 /**
@@ -636,16 +638,16 @@ sev_read_file_base64(const char *filename, guchar **data, gsize *len)
 }
 
 static int
-sev_launch_start(SevGuestState *sev_guest)
+sev_launch_start(SevCommonState *sev_common)
 {
     gsize sz;
     int ret = 1;
     int fw_error, rc;
+    SevGuestState *sev_guest = SEV_GUEST(sev_common);
     struct kvm_sev_launch_start start = {
         .handle = sev_guest->handle, .policy = sev_guest->policy
     };
     guchar *session = NULL, *dh_cert = NULL;
-    SevCommonState *sev_common = SEV_COMMON(sev_guest);
 
     if (sev_guest->session_file) {
         if (sev_read_file_base64(sev_guest->session_file, &session, &sz) < 0) {
@@ -866,6 +868,7 @@ static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
     uint32_t ebx;
     uint32_t host_cbitpos;
     struct sev_user_data_status status = {};
+    SevCommonStateClass *klass = SEV_COMMON_GET_CLASS(cgs);
 
     ret = ram_block_discard_disable(true);
     if (ret) {
@@ -956,7 +959,7 @@ static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
         goto err;
     }
 
-    sev_launch_start(SEV_GUEST(sev_common));
+    ret = klass->launch_start(sev_common);
     if (ret) {
         error_setg(errp, "%s: failed to create encryption context", __func__);
         goto err;
@@ -1455,6 +1458,10 @@ static void sev_guest_set_legacy_vm_type(Object *obj, bool value, Error **errp)
 static void
 sev_guest_class_init(ObjectClass *oc, void *data)
 {
+    SevCommonStateClass *klass = SEV_COMMON_CLASS(oc);
+
+    klass->launch_start = sev_launch_start;
+
     object_class_property_add_str(oc, "dh-cert-file",
                                   sev_guest_get_dh_cert_file,
                                   sev_guest_set_dh_cert_file);
Signature · 1 line
2.34.1
#10 lore raw

PATCH v4 6/31 i386/sev: Move sev_launch_finish to separate class method

In reply to Pankaj Gupta

When sev-snp-guest objects are introduced there will be a number of differences in how the launch finish is handled compared to the existing sev-guest object. Move sev_launch_finish() to a class method to make it easier to implement SNP-specific launch update functionality later.

---
 target/i386/sev.c | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)
target/i386/sev.c +7 -4
index 3bdb88f2ed..c141f4fed4 100644
@@ -71,6 +71,7 @@ struct SevCommonStateClass {
 
     /* public */
     int (*launch_start)(SevCommonState *sev_common);
+    void (*launch_finish)(SevCommonState *sev_common);
 };
 
 /**
@@ -805,12 +806,12 @@ static Notifier sev_machine_done_notify = {
 };
 
 static void
-sev_launch_finish(SevGuestState *sev_guest)
+sev_launch_finish(SevCommonState *sev_common)
 {
     int ret, error;
 
     trace_kvm_sev_launch_finish();
-    ret = sev_ioctl(SEV_COMMON(sev_guest)->sev_fd, KVM_SEV_LAUNCH_FINISH, 0,
+    ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_FINISH, 0,
                     &error);
     if (ret) {
         error_report("%s: LAUNCH_FINISH ret=%d fw_error=%d '%s'",
@@ -818,7 +819,7 @@ sev_launch_finish(SevGuestState *sev_guest)
         exit(1);
     }
 
-    sev_set_guest_state(SEV_COMMON(sev_guest), SEV_STATE_RUNNING);
+    sev_set_guest_state(sev_common, SEV_STATE_RUNNING);
 
     /* add migration blocker */
     error_setg(&sev_mig_blocker,
@@ -830,10 +831,11 @@ static void
 sev_vm_state_change(void *opaque, bool running, RunState state)
 {
     SevCommonState *sev_common = opaque;
+    SevCommonStateClass *klass = SEV_COMMON_GET_CLASS(opaque);
 
     if (running) {
         if (!sev_check_state(sev_common, SEV_STATE_RUNNING)) {
-            sev_launch_finish(SEV_GUEST(sev_common));
+            klass->launch_finish(sev_common);
         }
     }
 }
@@ -1461,6 +1463,7 @@ sev_guest_class_init(ObjectClass *oc, void *data)
     SevCommonStateClass *klass = SEV_COMMON_CLASS(oc);
 
     klass->launch_start = sev_launch_start;
+    klass->launch_finish = sev_launch_finish;
 
     object_class_property_add_str(oc, "dh-cert-file",
                                   sev_guest_get_dh_cert_file,
Signature · 1 line
2.34.1
#11 lore raw

PATCH v4 7/31 i386/sev: Introduce 'sev-snp-guest' object

In reply to Pankaj Gupta

From: Brijesh Singh <[email protected]>

SEV-SNP support relies on a different set of properties/state than the existing 'sev-guest' object. This patch introduces the 'sev-snp-guest' object, which can be used to configure an SEV-SNP guest. For example, a default-configured SEV-SNP guest with no additional information passed in for use with attestation:

-object sev-snp-guest,id=sev0

or a fully-specified SEV-SNP guest where all spec-defined binary blobs are passed in as base64-encoded strings:

  -object sev-snp-guest,id=sev0, \
    policy=0x30000, \
    init-flags=0, \
    id-block=YWFhYWFhYWFhYWFhYWFhCg==, \
    id-auth=CxHK/OKLkXGn/KpAC7Wl1FSiisWDbGTEKz..., \
    auth-key-enabled=on, \
    host-data=LNkCWBRC5CcdGXirbNUV1OrsR28s..., \
    guest-visible-workarounds=AA==, \

See the QAPI schema updates included in this patch for more usage details.

In some cases these blobs may be up to 4096 characters, but this is generally well below the default limit for linux hosts where command-line sizes are defined by the sysconf-configurable ARG_MAX value, which defaults to 2097152 characters for Ubuntu hosts, for example.

---
 docs/system/i386/amd-memory-encryption.rst |  70 +++++-
 qapi/qom.json                              |  57 +++++
 target/i386/sev.c                          | 257 +++++++++++++++++++++
 target/i386/sev.h                          |   1 +
 4 files changed, 383 insertions(+), 2 deletions(-)
docs/system/i386/amd-memory-encryption.rst +68 -2
index e9bc142bc1..5849ec8972 100644
@@ -25,8 +25,8 @@ support for notifying a guest's operating system when certain types of VMEXITs
 are about to occur. This allows the guest to selectively share information with
 the hypervisor to satisfy the requested function.
 
-Launching
----------
+Launching (SEV and SEV-ES)
+--------------------------
 
 Boot images (such as bios) must be encrypted before a guest can be booted. The
 ``MEMORY_ENCRYPT_OP`` ioctl provides commands to encrypt the images: ``LAUNCH_START``,
@@ -161,6 +161,72 @@ The value of GCTX.LD is
 If kernel hashes are not used, or SEV-ES is disabled, use empty blobs for
 ``kernel_hashes_blob`` and ``vmsas_blob`` as needed.
 
+Launching (SEV-SNP)
+-------------------
+Boot images (such as bios) must be encrypted before a guest can be booted. The
+``MEMORY_ENCRYPT_OP`` ioctl provides commands to encrypt the images:
+``SNP_LAUNCH_START``, ``SNP_LAUNCH_UPDATE``, and ``SNP_LAUNCH_FINISH``. These
+three commands communicate with SEV-SNP firmware to generate a fresh memory
+encryption key for the VM, encrypt the boot images for a successful launch. For
+more details on the SEV-SNP firmware interfaces used by these commands please
+see the SEV-SNP Firmware ABI.
+
+``SNP_LAUNCH_START`` is called first to create a cryptographic launch context
+within the firmware. To create this context, the guest owner must provide a
+guest policy and other parameters as described in the SEV-SNP firmware
+specification. The launch parameters should be specified as described in the
+QAPI schema for the sev-snp-guest object.
+
+The ``SNP_LAUNCH_START`` uses the following parameters, which can be configured
+by the corresponding parameters documented in the QAPI schema for the
+'sev-snp-guest' object.
+
++--------+-------+----------+-------------------------------------------------+
+| key                       | type  | default  | meaning                      |
++---------------------------+-------------------------------------------------+
+| policy                    | hex   | 0x30000  | a 64-bit guest policy        |
++---------------------------+-------------------------------------------------+
+| guest-visible-workarounds | string| 0        | 16-byte base64 encoded string|
+|                           |       |          | for guest OS visible         |
+|                           |       |          | workarounds.                 |
++---------------------------+-------------------------------------------------+
+
+``SNP_LAUNCH_UPDATE`` encrypts the memory region using the cryptographic context
+created via the ``SNP_LAUNCH_START`` command. If required, this command can be
+called multiple times to encrypt different memory regions. The command also
+calculates the measurement of the memory contents as it encrypts.
+
+``SNP_LAUNCH_FINISH`` finalizes the guest launch flow. Optionally, while
+finalizing the launch the firmware can perform checks on the launch digest
+computing through the ``SNP_LAUNCH_UPDATE``. To perform the check the user must
+supply the id block, authentication blob and host data that should be included
+in the attestation report. See the SEV-SNP spec for further details.
+
+The ``SNP_LAUNCH_FINISH`` uses the following parameters, which can be configured
+by the corresponding parameters documented in the QAPI schema for the
+'sev-snp-guest' object.
+
++--------------------+-------+----------+-------------------------------------+
+| key                | type  | default  | meaning                             |
++--------------------+-------+----------+-------------------------------------+
+| id-block           | string| none     | base64 encoded ID block             |
++--------------------+-------+----------+-------------------------------------+
+| id-auth            | string| none     | base64 encoded authentication       |
+|                    |       |          | information                         |
++--------------------+-------+----------+-------------------------------------+
+| auth-key-enabled   | bool  | 0        | auth block contains author key      |
++--------------------+-------+----------+-------------------------------------+
+| host_data          | string| none     | host provided data                  |
++--------------------+-------+----------+-------------------------------------+
+
+To launch a SEV-SNP guest (additional parameters are documented in the QAPI
+schema for the 'sev-snp-guest' object)::
+
+  # ${QEMU} \
+    -machine ...,confidential-guest-support=sev0 \
+    -object sev-snp-guest,id=sev0,cbitpos=51,reduced-phys-bits=1
+
+
 Debugging
 ---------
 
qapi/qom.json +57 -0

75 lines not on this page · raw message

target/i386/sev.c +257 -0

282 lines not on this page · raw message

target/i386/sev.h +1 -0
index 668374eef3..bedc667eeb 100644
@@ -22,6 +22,7 @@
 
 #define TYPE_SEV_COMMON "sev-common"
 #define TYPE_SEV_GUEST "sev-guest"
+#define TYPE_SEV_SNP_GUEST "sev-snp-guest"
 
 #define SEV_POLICY_NODBG        0x1
 #define SEV_POLICY_NOKS         0x2
Signature · 1 line
2.34.1
maintainer
#12 lore raw

Re: [PATCH v4 07/31] i386/sev: Introduce 'sev-snp-guest' object

qapi/qom.json line 930

Quoted 5 lines · Pankaj Gupta

+++ b/qapi/qom.json

qapi/qom.json +0 -0
@@ -928,6 +928,61 @@
             '*policy': 'uint32',
             '*handle': 'uint32',
             '*legacy-vm-type': 'bool' } }

Nit, missing empty line here.

Quoted 3 lines
qapi/qom.json +3 -0
+##
+# @SevSnpGuestProperties:
+#

[...]

target/i386/sev.c line 45

Quoted 9 lines
target/i386/sev.c +1 -0
index c141f4fed4..841b45f59b 100644
@@ -42,6 +42,7 @@
 
 OBJECT_DECLARE_TYPE(SevCommonState, SevCommonStateClass, SEV_COMMON)
 OBJECT_DECLARE_TYPE(SevGuestState, SevGuestStateClass, SEV_GUEST)
+OBJECT_DECLARE_TYPE(SevSnpGuestState, SevSnpGuestStateClass, SEV_SNP_GUEST)

This separate struct is also unnecessary.

Paolo

#13 lore raw

Re: [PATCH v4 07/31] i386/sev: Introduce 'sev-snp-guest' object

In reply to Pankaj Gupta
Quoted 8 lines · Pankaj Gupta
qapi/qom.json +8 -0
+# @policy: the 'POLICY' parameter to the SNP_LAUNCH_START command, as
+#     defined in the SEV-SNP firmware ABI (default: 0x30000)
+#
+# @guest-visible-workarounds: 16-byte, base64-encoded blob to report
+#     hypervisor-defined workarounds, corresponding to the 'GOSVW'
+#     parameter of the SNP_LAUNCH_START command defined in the SEV-SNP
+#     firmware ABI (default: all-zero)
+#

qapi/qom.json line 961

Quoted 10 lines
qapi/qom.json +10 -0
+# @id-block: 96-byte, base64-encoded blob to provide the 'ID Block'
+#     structure for the SNP_LAUNCH_FINISH command defined in the
+#     SEV-SNP firmware ABI (default: all-zero)
+#
+# @id-auth: 4096-byte, base64-encoded blob to provide the 'ID
+#     Authentication Information Structure' for the SNP_LAUNCH_FINISH
+#     command defined in the SEV-SNP firmware ABI (default: all-zero)
+#
+# @auth-key-enabled: true if 'id-auth' blob contains the 'AUTHOR_KEY'
+#     field defined SEV-SNP firmware ABI (default: false)

In 'id-auth', 'auth' is short for 'authentication'

In 'auth-key-enabled', 'auth' is short for 'author'.

Shortening 'authentication' is a compelling win. Shorting 'author' is not much of a win.

So to make it less ambiguous, how about '@author-key-enabled' for the field ?

Quoted 347 lines
qapi/qom.json +26 -0
+#
+# @host-data: 32-byte, base64-encoded, user-defined blob to provide to
+#     the guest, as documented for the 'HOST_DATA' parameter of the
+#     SNP_LAUNCH_FINISH command in the SEV-SNP firmware ABI (default:
+#     all-zero)
+#
+# @vcek-disabled: Guests are by default allowed to choose between VLEK
+#     (Versioned Loaded Endorsement Key) or VCEK (Versioned Chip
+#     Endorsement Key) when requesting attestation reports from
+#     firmware. Set this to true to disable the use of VCEK.
+#     (default: false) (since: 9.1)
+#
+# Since: 9.1
+##
+{ 'struct': 'SevSnpGuestProperties',
+  'base': 'SevCommonProperties',
+  'data': {
+            '*policy': 'uint64',
+            '*guest-visible-workarounds': 'str',
+            '*id-block': 'str',
+            '*id-auth': 'str',
+            '*auth-key-enabled': 'bool',
+            '*host-data': 'str',
+            '*vcek-disabled': 'bool' } }
 
 ##
 # @ThreadContextProperties:
@@ -1007,6 +1062,7 @@
     { 'name': 'secret_keyring',
       'if': 'CONFIG_SECRET_KEYRING' },
     'sev-guest',
+    'sev-snp-guest',
     'thread-context',
     's390-pv-guest',
     'throttle-group',
@@ -1077,6 +1133,7 @@
       'secret_keyring':             { 'type': 'SecretKeyringProperties',
                                       'if': 'CONFIG_SECRET_KEYRING' },
       'sev-guest':                  'SevGuestProperties',
+      'sev-snp-guest':              'SevSnpGuestProperties',
       'thread-context':             'ThreadContextProperties',
       'throttle-group':             'ThrottleGroupProperties',
       'tls-creds-anon':             'TlsCredsAnonProperties',
target/i386/sev.c +257 -0
index c141f4fed4..841b45f59b 100644
@@ -42,6 +42,7 @@
 
 OBJECT_DECLARE_TYPE(SevCommonState, SevCommonStateClass, SEV_COMMON)
 OBJECT_DECLARE_TYPE(SevGuestState, SevGuestStateClass, SEV_GUEST)
+OBJECT_DECLARE_TYPE(SevSnpGuestState, SevSnpGuestStateClass, SEV_SNP_GUEST)
 
 struct SevCommonState {
     X86ConfidentialGuest parent_obj;
@@ -100,8 +101,26 @@ struct SevGuestStateClass {
     SevCommonStateClass parent_class;
 };
 
+struct SevSnpGuestState {
+    SevCommonState parent_obj;
+
+    /* configuration parameters */
+    char *guest_visible_workarounds;
+    char *id_block;
+    char *id_auth;
+    char *host_data;
+
+    struct kvm_sev_snp_launch_start kvm_start_conf;
+    struct kvm_sev_snp_launch_finish kvm_finish_conf;
+};
+
+struct SevSnpGuestStateClass {
+    SevCommonStateClass parent_class;
+};
+
 #define DEFAULT_GUEST_POLICY    0x1 /* disable debug */
 #define DEFAULT_SEV_DEVICE      "/dev/sev"
+#define DEFAULT_SEV_SNP_POLICY  0x30000
 
 #define SEV_INFO_BLOCK_GUID     "00f771de-1a7e-4fcb-890e-68c77e2fb44e"
 typedef struct __attribute__((__packed__)) SevInfoBlock {
@@ -1505,11 +1524,249 @@ static const TypeInfo sev_guest_info = {
     .class_init = sev_guest_class_init,
 };
 
+static void
+sev_snp_guest_get_policy(Object *obj, Visitor *v, const char *name,
+                         void *opaque, Error **errp)
+{
+    visit_type_uint64(v, name,
+                      (uint64_t *)&SEV_SNP_GUEST(obj)->kvm_start_conf.policy,
+                      errp);
+}
+
+static void
+sev_snp_guest_set_policy(Object *obj, Visitor *v, const char *name,
+                         void *opaque, Error **errp)
+{
+    visit_type_uint64(v, name,
+                      (uint64_t *)&SEV_SNP_GUEST(obj)->kvm_start_conf.policy,
+                      errp);
+}
+
+static char *
+sev_snp_guest_get_guest_visible_workarounds(Object *obj, Error **errp)
+{
+    return g_strdup(SEV_SNP_GUEST(obj)->guest_visible_workarounds);
+}
+
+static void
+sev_snp_guest_set_guest_visible_workarounds(Object *obj, const char *value,
+                                            Error **errp)
+{
+    SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
+    struct kvm_sev_snp_launch_start *start = &sev_snp_guest->kvm_start_conf;
+    g_autofree guchar *blob;
+    gsize len;
+
+    g_free(sev_snp_guest->guest_visible_workarounds);
+
+    /* store the base64 str so we don't need to re-encode in getter */
+    sev_snp_guest->guest_visible_workarounds = g_strdup(value);
+
+    blob = qbase64_decode(sev_snp_guest->guest_visible_workarounds,
+                          -1, &len, errp);
+    if (!blob) {
+        return;
+    }
+
+    if (len != sizeof(start->gosvw)) {
+        error_setg(errp, "parameter length of %lu exceeds max of %lu",
+                   len, sizeof(start->gosvw));
+        return;
+    }
+
+    memcpy(start->gosvw, blob, len);
+}
+
+static char *
+sev_snp_guest_get_id_block(Object *obj, Error **errp)
+{
+    SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
+
+    return g_strdup(sev_snp_guest->id_block);
+}
+
+static void
+sev_snp_guest_set_id_block(Object *obj, const char *value, Error **errp)
+{
+    SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
+    struct kvm_sev_snp_launch_finish *finish = &sev_snp_guest->kvm_finish_conf;
+    gsize len;
+
+    g_free(sev_snp_guest->id_block);
+    g_free((guchar *)finish->id_block_uaddr);
+
+    /* store the base64 str so we don't need to re-encode in getter */
+    sev_snp_guest->id_block = g_strdup(value);
+
+    finish->id_block_uaddr =
+        (uint64_t)qbase64_decode(sev_snp_guest->id_block, -1, &len, errp);
+
+    if (!finish->id_block_uaddr) {
+        return;
+    }
+
+    if (len != KVM_SEV_SNP_ID_BLOCK_SIZE) {
+        error_setg(errp, "parameter length of %lu not equal to %u",
+                   len, KVM_SEV_SNP_ID_BLOCK_SIZE);
+        return;
+    }
+
+    finish->id_block_en = (len) ? 1 : 0;
+}
+
+static char *
+sev_snp_guest_get_id_auth(Object *obj, Error **errp)
+{
+    SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
+
+    return g_strdup(sev_snp_guest->id_auth);
+}
+
+static void
+sev_snp_guest_set_id_auth(Object *obj, const char *value, Error **errp)
+{
+    SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
+    struct kvm_sev_snp_launch_finish *finish = &sev_snp_guest->kvm_finish_conf;
+    gsize len;
+
+    g_free(sev_snp_guest->id_auth);
+    g_free((guchar *)finish->id_auth_uaddr);
+
+    /* store the base64 str so we don't need to re-encode in getter */
+    sev_snp_guest->id_auth = g_strdup(value);
+
+    finish->id_auth_uaddr =
+        (uint64_t)qbase64_decode(sev_snp_guest->id_auth, -1, &len, errp);
+
+    if (!finish->id_auth_uaddr) {
+        return;
+    }
+
+    if (len > KVM_SEV_SNP_ID_AUTH_SIZE) {
+        error_setg(errp, "parameter length:ID_AUTH %lu exceeds max of %u",
+                   len, KVM_SEV_SNP_ID_AUTH_SIZE);
+        return;
+    }
+}
+
+static bool
+sev_snp_guest_get_auth_key_en(Object *obj, Error **errp)
+{
+    SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
+
+    return !!sev_snp_guest->kvm_finish_conf.auth_key_en;
+}
+
+static void
+sev_snp_guest_set_auth_key_en(Object *obj, bool value, Error **errp)
+{
+    SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
+
+    sev_snp_guest->kvm_finish_conf.auth_key_en = value;
+}
+
+static bool
+sev_snp_guest_get_vcek_disabled(Object *obj, Error **errp)
+{
+    SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
+
+    return !!sev_snp_guest->kvm_finish_conf.vcek_disabled;
+}
+
+static void
+sev_snp_guest_set_vcek_disabled(Object *obj, bool value, Error **errp)
+{
+    SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
+
+    sev_snp_guest->kvm_finish_conf.vcek_disabled = value;
+}
+
+static char *
+sev_snp_guest_get_host_data(Object *obj, Error **errp)
+{
+    SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
+
+    return g_strdup(sev_snp_guest->host_data);
+}
+
+static void
+sev_snp_guest_set_host_data(Object *obj, const char *value, Error **errp)
+{
+    SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
+    struct kvm_sev_snp_launch_finish *finish = &sev_snp_guest->kvm_finish_conf;
+    g_autofree guchar *blob;
+    gsize len;
+
+    g_free(sev_snp_guest->host_data);
+
+    /* store the base64 str so we don't need to re-encode in getter */
+    sev_snp_guest->host_data = g_strdup(value);
+
+    blob = qbase64_decode(sev_snp_guest->host_data, -1, &len, errp);
+
+    if (!blob) {
+        return;
+    }
+
+    if (len != sizeof(finish->host_data)) {
+        error_setg(errp, "parameter length of %lu not equal to %lu",
+                   len, sizeof(finish->host_data));
+        return;
+    }
+
+    memcpy(finish->host_data, blob, len);
+}
+
+static void
+sev_snp_guest_class_init(ObjectClass *oc, void *data)
+{
+    object_class_property_add(oc, "policy", "uint64",
+                              sev_snp_guest_get_policy,
+                              sev_snp_guest_set_policy, NULL, NULL);
+    object_class_property_add_str(oc, "guest-visible-workarounds",
+                                  sev_snp_guest_get_guest_visible_workarounds,
+                                  sev_snp_guest_set_guest_visible_workarounds);
+    object_class_property_add_str(oc, "id-block",
+                                  sev_snp_guest_get_id_block,
+                                  sev_snp_guest_set_id_block);
+    object_class_property_add_str(oc, "id-auth",
+                                  sev_snp_guest_get_id_auth,
+                                  sev_snp_guest_set_id_auth);
+    object_class_property_add_bool(oc, "auth-key-enabled",
+                                   sev_snp_guest_get_auth_key_en,
+                                   sev_snp_guest_set_auth_key_en);
+    object_class_property_add_bool(oc, "vcek-required",
+                                   sev_snp_guest_get_vcek_disabled,
+                                   sev_snp_guest_set_vcek_disabled);
+    object_class_property_add_str(oc, "host-data",
+                                  sev_snp_guest_get_host_data,
+                                  sev_snp_guest_set_host_data);
+}
+
+static void
+sev_snp_guest_instance_init(Object *obj)
+{
+    SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
+
+    /* default init/start/finish params for kvm */
+    sev_snp_guest->kvm_start_conf.policy = DEFAULT_SEV_SNP_POLICY;
+}
+
+/* guest info specific to sev-snp */
+static const TypeInfo sev_snp_guest_info = {
+    .parent = TYPE_SEV_COMMON,
+    .name = TYPE_SEV_SNP_GUEST,
+    .instance_size = sizeof(SevSnpGuestState),
+    .class_init = sev_snp_guest_class_init,
+    .instance_init = sev_snp_guest_instance_init,
+};
+
 static void
 sev_register_types(void)
 {
     type_register_static(&sev_common_info);
     type_register_static(&sev_guest_info);
+    type_register_static(&sev_snp_guest_info);
 }
 
 type_init(sev_register_types);
target/i386/sev.h +1 -0
index 668374eef3..bedc667eeb 100644
@@ -22,6 +22,7 @@
 
 #define TYPE_SEV_COMMON "sev-common"
 #define TYPE_SEV_GUEST "sev-guest"
+#define TYPE_SEV_SNP_GUEST "sev-snp-guest"
 
 #define SEV_POLICY_NODBG        0x1
 #define SEV_POLICY_NOKS         0x2
Signature · 1 line
2.34.1

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
maintainer
#14 lore raw

Re: [PATCH v4 07/31] i386/sev: Introduce 'sev-snp-guest' object

Quoted 24 lines · Daniel P. Berrangé
Quoted 8 lines · Pankaj Gupta
qapi/qom.json +8 -0
+# @policy: the 'POLICY' parameter to the SNP_LAUNCH_START command, as
+#     defined in the SEV-SNP firmware ABI (default: 0x30000)
+#
+# @guest-visible-workarounds: 16-byte, base64-encoded blob to report
+#     hypervisor-defined workarounds, corresponding to the 'GOSVW'
+#     parameter of the SNP_LAUNCH_START command defined in the SEV-SNP
+#     firmware ABI (default: all-zero)
+#

qapi/qom.json line 961

Quoted 10 lines
qapi/qom.json +10 -0
+# @id-block: 96-byte, base64-encoded blob to provide the 'ID Block'
+#     structure for the SNP_LAUNCH_FINISH command defined in the
+#     SEV-SNP firmware ABI (default: all-zero)
+#
+# @id-auth: 4096-byte, base64-encoded blob to provide the 'ID
+#     Authentication Information Structure' for the SNP_LAUNCH_FINISH
+#     command defined in the SEV-SNP firmware ABI (default: all-zero)
+#
+# @auth-key-enabled: true if 'id-auth' blob contains the 'AUTHOR_KEY'
+#     field defined SEV-SNP firmware ABI (default: false)

In 'id-auth', 'auth' is short for 'authentication'

Quoted 7 lines

In 'auth-key-enabled', 'auth' is short for 'author'.

Shortening 'authentication' is a compelling win. Shorting 'author' is not much of a win.

So to make it less ambiguous, how about '@author-key-enabled' for the field ?

Good idea.

Paolo

#15 lore raw

PATCH v4 8/31 i386/sev: Add a sev_snp_enabled() helper

In reply to Pankaj Gupta

From: Michael Roth <[email protected]>

Add a simple helper to check if the current guest type is SNP. Also have SNP-enabled imply that SEV-ES is enabled as well, and fix up any places where the sev_es_enabled() check is expecting a pure/non-SNP guest.

---
 target/i386/sev.c | 13 ++++++++++++-
 target/i386/sev.h |  2 ++
 2 files changed, 14 insertions(+), 1 deletion(-)
target/i386/sev.c +12 -1
index 841b45f59b..f4f1971202 100644
@@ -333,12 +333,21 @@ sev_enabled(void)
     return !!object_dynamic_cast(OBJECT(cgs), TYPE_SEV_COMMON);
 }
 
+bool
+sev_snp_enabled(void)
+{
+    ConfidentialGuestSupport *cgs = MACHINE(qdev_get_machine())->cgs;
+
+    return !!object_dynamic_cast(OBJECT(cgs), TYPE_SEV_SNP_GUEST);
+}
+
 bool
 sev_es_enabled(void)
 {
     ConfidentialGuestSupport *cgs = MACHINE(qdev_get_machine())->cgs;
 
-    return sev_enabled() && (SEV_GUEST(cgs)->policy & SEV_POLICY_ES);
+    return sev_snp_enabled() ||
+            (sev_enabled() && SEV_GUEST(cgs)->policy & SEV_POLICY_ES);
 }
 
 uint32_t
@@ -954,7 +963,9 @@ static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
                        "support", __func__);
             goto err;
         }
+    }
 
+    if (sev_es_enabled() && !sev_snp_enabled()) {
         if (!(status.flags & SEV_STATUS_FLAGS_CONFIG_ES)) {
             error_setg(errp, "%s: guest policy requires SEV-ES, but "
                          "host SEV-ES support unavailable",
target/i386/sev.h +2 -0
index bedc667eeb..94295ee74f 100644
@@ -45,9 +45,11 @@ typedef struct SevKernelLoaderContext {
 #ifdef CONFIG_SEV
 bool sev_enabled(void);
 bool sev_es_enabled(void);
+bool sev_snp_enabled(void);
 #else
 #define sev_enabled() 0
 #define sev_es_enabled() 0
+#define sev_snp_enabled() 0
 #endif
 
 uint32_t sev_get_cbit_position(void);
Signature · 1 line
2.34.1
#16 lore raw

PATCH v4 9/31 i386/sev: Add sev_kvm_init() override for SEV class

In reply to Pankaj Gupta

Some aspects of the init routine SEV are specific to SEV and not applicable for SNP guests, so move the SEV-specific bits into separate class method and retain only the common functionality.

---
 target/i386/sev.c | 72 +++++++++++++++++++++++++++++++++--------------
 1 file changed, 51 insertions(+), 21 deletions(-)
target/i386/sev.c +51 -21
index f4f1971202..2a9a77a2d9 100644
@@ -73,6 +73,7 @@ struct SevCommonStateClass {
     /* public */
     int (*launch_start)(SevCommonState *sev_common);
     void (*launch_finish)(SevCommonState *sev_common);
+    int (*kvm_init)(ConfidentialGuestSupport *cgs, Error **errp);
 };
 
 /**
@@ -890,7 +891,7 @@ out:
     return sev_common->kvm_type;
 }
 
-static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
+static int sev_common_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
 {
     SevCommonState *sev_common = SEV_COMMON(cgs);
     char *devname;
@@ -900,12 +901,6 @@ static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
     struct sev_user_data_status status = {};
     SevCommonStateClass *klass = SEV_COMMON_GET_CLASS(cgs);
 
-    ret = ram_block_discard_disable(true);
-    if (ret) {
-        error_report("%s: cannot disable RAM discard", __func__);
-        return -1;
-    }
-
     sev_common->state = SEV_STATE_UNINIT;
 
     host_cpuid(0x8000001F, 0, NULL, &ebx, NULL, NULL);
@@ -919,7 +914,7 @@ static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
     if (host_cbitpos != sev_common->cbitpos) {
         error_setg(errp, "%s: cbitpos check failed, host '%d' requested '%d'",
                    __func__, host_cbitpos, sev_common->cbitpos);
-        goto err;
+        return -1;
     }
 
     /*
@@ -932,7 +927,7 @@ static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
         error_setg(errp, "%s: reduced_phys_bits check failed,"
                    " it should be in the range of 1 to 63, requested '%d'",
                    __func__, sev_common->reduced_phys_bits);
-        goto err;
+        return -1;
     }
 
     devname = object_property_get_str(OBJECT(sev_common), "sev-device", NULL);
@@ -941,7 +936,7 @@ static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
         error_setg(errp, "%s: Failed to open %s '%s'", __func__,
                    devname, strerror(errno));
         g_free(devname);
-        goto err;
+        return -1;
     }
     g_free(devname);
 
@@ -951,7 +946,7 @@ static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
         error_setg(errp, "%s: failed to get platform status ret=%d "
                    "fw_error='%d: %s'", __func__, ret, fw_error,
                    fw_error_to_str(fw_error));
-        goto err;
+        return -1;
     }
     sev_common->build_id = status.build;
     sev_common->api_major = status.api_major;
@@ -961,7 +956,7 @@ static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
         if (!kvm_kernel_irqchip_allowed()) {
             error_setg(errp, "%s: SEV-ES guests require in-kernel irqchip"
                        "support", __func__);
-            goto err;
+            return -1;
         }
     }
 
@@ -970,7 +965,7 @@ static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
             error_setg(errp, "%s: guest policy requires SEV-ES, but "
                          "host SEV-ES support unavailable",
                          __func__);
-            goto err;
+            return -1;
         }
     }
 
@@ -988,25 +983,59 @@ static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
     if (ret) {
         error_setg(errp, "%s: failed to initialize ret=%d fw_error=%d '%s'",
                    __func__, ret, fw_error, fw_error_to_str(fw_error));
-        goto err;
+        return -1;
     }
 
     ret = klass->launch_start(sev_common);
     if (ret) {
         error_setg(errp, "%s: failed to create encryption context", __func__);
-        goto err;
+        return -1;
+    }
+
+    if (klass->kvm_init && klass->kvm_init(cgs, errp)) {
+        return -1;
     }
 
-    ram_block_notifier_add(&sev_ram_notifier);
-    qemu_add_machine_init_done_notifier(&sev_machine_done_notify);
     qemu_add_vm_change_state_handler(sev_vm_state_change, sev_common);
 
     cgs->ready = true;
 
     return 0;
-err:
-    ram_block_discard_disable(false);
-    return -1;
+}
+
+static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
+{
+     int ret;
+
+    /*
+     * SEV/SEV-ES rely on pinned memory to back guest RAM so discarding
+     * isn't actually possible. With SNP, only guest_memfd pages are used
+     * for private guest memory, so discarding of shared memory is still
+     * possible..
+     */
+    ret = ram_block_discard_disable(true);
+    if (ret) {
+        error_setg(errp, "%s: cannot disable RAM discard", __func__);
+        return -1;
+    }
+
+    /*
+     * SEV uses these notifiers to register/pin pages prior to guest use,
+     * but SNP relies on guest_memfd for private pages, which has it's
+     * own internal mechanisms for registering/pinning private memory.
+     */
+    ram_block_notifier_add(&sev_ram_notifier);
+
+    /*
+     * The machine done notify event is used for SEV guests to get the
+     * measurement of the encrypted images. When SEV-SNP is enabled, the
+     * measurement is part of the guest attestation process where it can
+     * be collected without any reliance on the VMM. So skip registering
+     * the notifier for SNP in favor of using guest attestation instead.
+     */
+    qemu_add_machine_init_done_notifier(&sev_machine_done_notify);
+
+    return 0;
 }
 
 int
@@ -1405,7 +1434,7 @@ sev_common_class_init(ObjectClass *oc, void *data)
     ConfidentialGuestSupportClass *klass = CONFIDENTIAL_GUEST_SUPPORT_CLASS(oc);
     X86ConfidentialGuestClass *x86_klass = X86_CONFIDENTIAL_GUEST_CLASS(oc);
 
-    klass->kvm_init = sev_kvm_init;
+    klass->kvm_init = sev_common_kvm_init;
     x86_klass->kvm_type = sev_kvm_type;
 
     object_class_property_add_str(oc, "sev-device",
@@ -1494,6 +1523,7 @@ sev_guest_class_init(ObjectClass *oc, void *data)
 
     klass->launch_start = sev_launch_start;
     klass->launch_finish = sev_launch_finish;
+    klass->kvm_init = sev_kvm_init;
 
     object_class_property_add_str(oc, "dh-cert-file",
                                   sev_guest_get_dh_cert_file,
Signature · 1 line
2.34.1
maintainer
#17 lore raw

Re: [PATCH v4 09/31] i386/sev: Add sev_kvm_init() override for SEV class

target/i386/sev.c static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp) · line 1027

Quoted 6 lines · Pankaj Gupta
target/i386/sev.c +6 -0
+    /*
+     * SEV uses these notifiers to register/pin pages prior to guest use,
+     * but SNP relies on guest_memfd for private pages, which has it's
+     * own internal mechanisms for registering/pinning private memory.
+     */
+    ram_block_notifier_add(&sev_ram_notifier);

"it's" should be "its".

Paolo

#18 lore raw

PATCH v4 10/31 i386/sev: Add snp_kvm_init() override for SNP class

In reply to Pankaj Gupta

SNP does not support SMM and requires guest_memfd for private guest memory, so add SNP specific kvm_init() functionality in snp_kvm_init() class method.

---
 target/i386/sev.c | 23 ++++++++++++++++++++++-
 1 file changed, 22 insertions(+), 1 deletion(-)
target/i386/sev.c +22 -1
index 2a9a77a2d9..56c1cce8e7 100644
@@ -893,12 +893,12 @@ out:
 
 static int sev_common_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
 {
-    SevCommonState *sev_common = SEV_COMMON(cgs);
     char *devname;
     int ret, fw_error, cmd;
     uint32_t ebx;
     uint32_t host_cbitpos;
     struct sev_user_data_status status = {};
+    SevCommonState *sev_common = SEV_COMMON(cgs);
     SevCommonStateClass *klass = SEV_COMMON_GET_CLASS(cgs);
 
     sev_common->state = SEV_STATE_UNINIT;
@@ -1038,6 +1038,23 @@ static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
     return 0;
 }
 
+static int sev_snp_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
+{
+    MachineState *ms = MACHINE(qdev_get_machine());
+    X86MachineState *x86ms = X86_MACHINE(ms);
+
+    if (x86ms->smm == ON_OFF_AUTO_AUTO) {
+        x86ms->smm = ON_OFF_AUTO_OFF;
+    } else if (x86ms->smm == ON_OFF_AUTO_ON) {
+        error_setg(errp, "SEV-SNP does not support SMM.");
+        ram_block_discard_disable(false);
+        return -1;
+    }
+    ms->require_guest_memfd = true;
+
+    return 0;
+}
+
 int
 sev_encrypt_flash(uint8_t *ptr, uint64_t len, Error **errp)
 {
@@ -1761,6 +1778,10 @@ sev_snp_guest_set_host_data(Object *obj, const char *value, Error **errp)
 static void
 sev_snp_guest_class_init(ObjectClass *oc, void *data)
 {
+    SevCommonStateClass *klass = SEV_COMMON_CLASS(oc);
+
+    klass->kvm_init = sev_snp_kvm_init;
+
     object_class_property_add(oc, "policy", "uint64",
                               sev_snp_guest_get_policy,
                               sev_snp_guest_set_policy, NULL, NULL);
Signature · 1 line
2.34.1
maintainer
#19 lore raw

Re: [PATCH v4 10/31] i386/sev: Add snp_kvm_init() override for SNP class

target/i386/sev.c static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp) · line 1050

Quoted 3 lines · Pankaj Gupta
target/i386/sev.c +3 -0
+    } else if (x86ms->smm == ON_OFF_AUTO_ON) {
+        error_setg(errp, "SEV-SNP does not support SMM.");
+        ram_block_discard_disable(false);

Unnecessary line, there is no matching ram_block_discard_disable(true).

Paolo

#20 lore raw

PATCH v4 11/31 i386/cpu: Set SEV-SNP CPUID bit when SNP enabled

In reply to Pankaj Gupta

From: Michael Roth <[email protected]>

SNP guests will rely on this bit to determine certain feature support.

---
 target/i386/cpu.c | 1 +
 1 file changed, 1 insertion(+)
target/i386/cpu.c +1 -0
index bc2dceb647..914bef442c 100644
@@ -6979,6 +6979,7 @@ void cpu_x86_cpuid(CPUX86State *env, uint32_t index, uint32_t count,
         if (sev_enabled()) {
             *eax = 0x2;
             *eax |= sev_es_enabled() ? 0x8 : 0;
+            *eax |= sev_snp_enabled() ? 0x10 : 0;
             *ebx = sev_get_cbit_position() & 0x3f; /* EBX[5:0] */
             *ebx |= (sev_get_reduced_phys_bits() & 0x3f) << 6; /* EBX[11:6] */
         }
Signature · 1 line
2.34.1
#21 lore raw

PATCH v4 12/31 i386/sev: Don't return launch measurements for SEV-SNP guests

In reply to Pankaj Gupta

From: Michael Roth <[email protected]>

For SEV-SNP guests, launch measurement is queried from within the guest during attestation, so don't attempt to return it as part of query-sev-launch-measure.

---
 target/i386/sev.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
target/i386/sev.c +3 -1
index 56c1cce8e7..458ff5040d 100644
@@ -803,7 +803,9 @@ sev_launch_get_measure(Notifier *notifier, void *unused)
 
 static char *sev_get_launch_measurement(void)
 {
-    SevGuestState *sev_guest = SEV_GUEST(MACHINE(qdev_get_machine())->cgs);
+    ConfidentialGuestSupport *cgs = MACHINE(qdev_get_machine())->cgs;
+    SevGuestState *sev_guest =
+        (SevGuestState *)object_dynamic_cast(OBJECT(cgs), TYPE_SEV_GUEST);
 
     if (sev_guest &&
         SEV_COMMON(sev_guest)->state >= SEV_STATE_LAUNCH_SECRET) {
Signature · 1 line
2.34.1
#22 lore raw

PATCH v4 13/31 i386/sev: Add a class method to determine KVM VM type for SNP guests

In reply to Pankaj Gupta

SEV guests can use either KVM_X86_DEFAULT_VM, KVM_X86_SEV_VM, or KVM_X86_SEV_ES_VM depending on the configuration and what the host kernel supports. SNP guests on the other hand can only ever use KVM_X86_SNP_VM, so split determination of VM type out into a separate class method that can be set accordingly for sev-guest vs. sev-snp-guest objects and add handling for SNP.

---
 target/i386/sev.c | 21 ++++++++++++++++++---
 1 file changed, 18 insertions(+), 3 deletions(-)
target/i386/sev.c +18 -3
index 458ff5040d..8ca486f5d2 100644
@@ -100,6 +100,9 @@ struct SevGuestState {
 
 struct SevGuestStateClass {
     SevCommonStateClass parent_class;
+
+    /* public */
+    int (*kvm_type)(X86ConfidentialGuest *cg);
 };
 
 struct SevSnpGuestState {
@@ -117,6 +120,9 @@ struct SevSnpGuestState {
 
 struct SevSnpGuestStateClass {
     SevCommonStateClass parent_class;
+
+    /* public */
+    int (*kvm_type)(X86ConfidentialGuest *cg);
 };
 
 #define DEFAULT_GUEST_POLICY    0x1 /* disable debug */
@@ -893,6 +899,11 @@ out:
     return sev_common->kvm_type;
 }
 
+static int sev_snp_kvm_type(X86ConfidentialGuest *cg)
+{
+    return KVM_X86_SNP_VM;
+}
+
 static int sev_common_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
 {
     char *devname;
@@ -902,6 +913,8 @@ static int sev_common_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
     struct sev_user_data_status status = {};
     SevCommonState *sev_common = SEV_COMMON(cgs);
     SevCommonStateClass *klass = SEV_COMMON_GET_CLASS(cgs);
+    X86ConfidentialGuestClass *x86_klass =
+                               X86_CONFIDENTIAL_GUEST_GET_CLASS(cgs);
 
     sev_common->state = SEV_STATE_UNINIT;
 
@@ -972,7 +985,7 @@ static int sev_common_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
     }
 
     trace_kvm_sev_init();
-    if (sev_kvm_type(X86_CONFIDENTIAL_GUEST(sev_common)) == KVM_X86_DEFAULT_VM) {
+    if (x86_klass->kvm_type(X86_CONFIDENTIAL_GUEST(sev_common)) == KVM_X86_DEFAULT_VM) {
         cmd = sev_es_enabled() ? KVM_SEV_ES_INIT : KVM_SEV_INIT;
 
         ret = sev_ioctl(sev_common->sev_fd, cmd, NULL, &fw_error);
@@ -1451,10 +1464,8 @@ static void
 sev_common_class_init(ObjectClass *oc, void *data)
 {
     ConfidentialGuestSupportClass *klass = CONFIDENTIAL_GUEST_SUPPORT_CLASS(oc);
-    X86ConfidentialGuestClass *x86_klass = X86_CONFIDENTIAL_GUEST_CLASS(oc);
 
     klass->kvm_init = sev_common_kvm_init;
-    x86_klass->kvm_type = sev_kvm_type;
 
     object_class_property_add_str(oc, "sev-device",
                                   sev_common_get_sev_device,
@@ -1539,10 +1550,12 @@ static void
 sev_guest_class_init(ObjectClass *oc, void *data)
 {
     SevCommonStateClass *klass = SEV_COMMON_CLASS(oc);
+    X86ConfidentialGuestClass *x86_klass = X86_CONFIDENTIAL_GUEST_CLASS(oc);
 
     klass->launch_start = sev_launch_start;
     klass->launch_finish = sev_launch_finish;
     klass->kvm_init = sev_kvm_init;
+    x86_klass->kvm_type = sev_kvm_type;
 
     object_class_property_add_str(oc, "dh-cert-file",
                                   sev_guest_get_dh_cert_file,
@@ -1781,8 +1794,10 @@ static void
 sev_snp_guest_class_init(ObjectClass *oc, void *data)
 {
     SevCommonStateClass *klass = SEV_COMMON_CLASS(oc);
+    X86ConfidentialGuestClass *x86_klass = X86_CONFIDENTIAL_GUEST_CLASS(oc);
 
     klass->kvm_init = sev_snp_kvm_init;
+    x86_klass->kvm_type = sev_snp_kvm_type;
 
     object_class_property_add(oc, "policy", "uint64",
                               sev_snp_guest_get_policy,
Signature · 1 line
2.34.1
#23 lore raw

PATCH v4 14/31 i386/sev: Update query-sev QAPI format to handle SEV-SNP

In reply to Pankaj Gupta

From: Michael Roth <[email protected]>

Most of the current 'query-sev' command is relevant to both legacy SEV/SEV-ES guests and SEV-SNP guests, with 2 exceptions:

- 'policy' is a 64-bit field for SEV-SNP, not 32-bit, and the meaning of the bit positions has changed
- 'handle' is not relevant to SEV-SNP

To address this, this patch adds a new 'sev-type' field that can be used as a discriminator to select between SEV and SEV-SNP-specific fields/formats without breaking compatibility for existing management tools (so long as management tools that add support for launching SEV-SNP guest update their handling of query-sev appropriately).

The corresponding HMP command has also been fixed up similarly.

---
 qapi/misc-target.json | 72 ++++++++++++++++++++++++++++++++++---------
 target/i386/sev.c     | 55 +++++++++++++++++++++------------
 target/i386/sev.h     |  3 ++
 3 files changed, 96 insertions(+), 34 deletions(-)
qapi/misc-target.json +58 -14
index 4e0a6492a9..2d7d4d89bd 100644
@@ -47,6 +47,50 @@
            'send-update', 'receive-update' ],
   'if': 'TARGET_I386' }
 
+##
+# @SevGuestType:
+#
+# An enumeration indicating the type of SEV guest being run.
+#
+# @sev: The guest is a legacy SEV or SEV-ES guest.
+#
+# @sev-snp: The guest is an SEV-SNP guest.
+#
+# Since: 6.2
+##
+{ 'enum': 'SevGuestType',
+  'data': [ 'sev', 'sev-snp' ],
+  'if': 'TARGET_I386' }
+
+##
+# @SevGuestInfo:
+#
+# Information specific to legacy SEV/SEV-ES guests.
+#
+# @policy: SEV policy value
+#
+# @handle: SEV firmware handle
+#
+# Since: 2.12
+##
+{ 'struct': 'SevGuestInfo',
+  'data': { 'policy': 'uint32',
+            'handle': 'uint32' },
+  'if': 'TARGET_I386' }
+
+##
+# @SevSnpGuestInfo:
+#
+# Information specific to SEV-SNP guests.
+#
+# @snp-policy: SEV-SNP policy value
+#
+# Since: 9.1
+##
+{ 'struct': 'SevSnpGuestInfo',
+  'data': { 'snp-policy': 'uint64' },
+  'if': 'TARGET_I386' }
+
 ##
 # @SevInfo:
 #
@@ -60,25 +104,25 @@
 #
 # @build-id: SEV FW build id
 #
-# @policy: SEV policy value
-#
 # @state: SEV guest state
 #
-# @handle: SEV firmware handle
+# @sev-type: Type of SEV guest being run
 #
 # Since: 2.12
 ##
-{ 'struct': 'SevInfo',
-    'data': { 'enabled': 'bool',
-              'api-major': 'uint8',
-              'api-minor' : 'uint8',
-              'build-id' : 'uint8',
-              'policy' : 'uint32',
-              'state' : 'SevState',
-              'handle' : 'uint32'
-            },
-  'if': 'TARGET_I386'
-}
+{ 'union': 'SevInfo',
+  'base': { 'enabled': 'bool',
+            'api-major': 'uint8',
+            'api-minor' : 'uint8',
+            'build-id' : 'uint8',
+            'state' : 'SevState',
+            'sev-type' : 'SevGuestType' },
+  'discriminator': 'sev-type',
+  'data': {
+      'sev': 'SevGuestInfo',
+      'sev-snp': 'SevSnpGuestInfo' },
+  'if': 'TARGET_I386' }
+
 
 ##
 # @query-sev:
target/i386/sev.c +35 -20

80 lines not on this page · raw message

target/i386/sev.h +3 -0
index 94295ee74f..5dc4767b1e 100644
@@ -31,6 +31,9 @@
 #define SEV_POLICY_DOMAIN       0x10
 #define SEV_POLICY_SEV          0x20
 
+#define SEV_SNP_POLICY_SMT      0x10000
+#define SEV_SNP_POLICY_DBG      0x80000
+
 typedef struct SevKernelLoaderContext {
     char *setup_data;
     size_t setup_size;
Signature · 1 line
2.34.1
#24 lore raw

PATCH v4 15/31 i386/sev: Add the SNP launch start context

In reply to Pankaj Gupta

From: Brijesh Singh <[email protected]>

The SNP_LAUNCH_START is called first to create a cryptographic launch context within the firmware.

---
 target/i386/sev.c        | 39 +++++++++++++++++++++++++++++++++++++++
 target/i386/trace-events |  1 +
 2 files changed, 40 insertions(+)
target/i386/sev.c +39 -0
index 101661bf71..acbb22ff15 100644
@@ -39,6 +39,7 @@
 #include "confidential-guest.h"
 #include "hw/i386/pc.h"
 #include "exec/address-spaces.h"
+#include "qemu/queue.h"
 
 OBJECT_DECLARE_TYPE(SevCommonState, SevCommonStateClass, SEV_COMMON)
 OBJECT_DECLARE_TYPE(SevGuestState, SevGuestStateClass, SEV_GUEST)
@@ -129,6 +130,16 @@ struct SevSnpGuestStateClass {
 #define DEFAULT_SEV_DEVICE      "/dev/sev"
 #define DEFAULT_SEV_SNP_POLICY  0x30000
 
+typedef struct SevLaunchUpdateData {
+    QTAILQ_ENTRY(SevLaunchUpdateData) next;
+    hwaddr gpa;
+    void *hva;
+    uint64_t len;
+    int type;
+} SevLaunchUpdateData;
+
+static QTAILQ_HEAD(, SevLaunchUpdateData) launch_update;
+
 #define SEV_INFO_BLOCK_GUID     "00f771de-1a7e-4fcb-890e-68c77e2fb44e"
 typedef struct __attribute__((__packed__)) SevInfoBlock {
     /* SEV-ES Reset Vector Address */
@@ -688,6 +699,31 @@ sev_read_file_base64(const char *filename, guchar **data, gsize *len)
     return 0;
 }
 
+static int
+sev_snp_launch_start(SevCommonState *sev_common)
+{
+    int fw_error, rc;
+    SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(sev_common);
+    struct kvm_sev_snp_launch_start *start = &sev_snp_guest->kvm_start_conf;
+
+    trace_kvm_sev_snp_launch_start(start->policy,
+                                   sev_snp_guest->guest_visible_workarounds);
+
+    rc = sev_ioctl(sev_common->sev_fd, KVM_SEV_SNP_LAUNCH_START,
+                   start, &fw_error);
+    if (rc < 0) {
+        error_report("%s: SNP_LAUNCH_START ret=%d fw_error=%d '%s'",
+                __func__, rc, fw_error, fw_error_to_str(fw_error));
+        return 1;
+    }
+
+    QTAILQ_INIT(&launch_update);
+
+    sev_set_guest_state(sev_common, SEV_STATE_LAUNCH_UPDATE);
+
+    return 0;
+}
+
 static int
 sev_launch_start(SevCommonState *sev_common)
 {
@@ -1017,6 +1053,7 @@ static int sev_common_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
     }
 
     ret = klass->launch_start(sev_common);
+
     if (ret) {
         error_setg(errp, "%s: failed to create encryption context", __func__);
         return -1;
@@ -1811,9 +1848,11 @@ sev_snp_guest_class_init(ObjectClass *oc, void *data)
     SevCommonStateClass *klass = SEV_COMMON_CLASS(oc);
     X86ConfidentialGuestClass *x86_klass = X86_CONFIDENTIAL_GUEST_CLASS(oc);
 
+    klass->launch_start = sev_snp_launch_start;
     klass->kvm_init = sev_snp_kvm_init;
     x86_klass->kvm_type = sev_snp_kvm_type;
 
+
     object_class_property_add(oc, "policy", "uint64",
                               sev_snp_guest_get_policy,
                               sev_snp_guest_set_policy, NULL, NULL);
target/i386/trace-events +1 -0
index 2cd8726eeb..cb26d8a925 100644
@@ -11,3 +11,4 @@ kvm_sev_launch_measurement(const char *value) "data %s"
 kvm_sev_launch_finish(void) ""
 kvm_sev_launch_secret(uint64_t hpa, uint64_t hva, uint64_t secret, int len) "hpa 0x%" PRIx64 " hva 0x%" PRIx64 " data 0x%" PRIx64 " len %d"
 kvm_sev_attestation_report(const char *mnonce, const char *data) "mnonce %s data %s"
+kvm_sev_snp_launch_start(uint64_t policy, char *gosvw) "policy 0x%" PRIx64 " gosvw %s"
Signature · 1 line
2.34.1
#25 lore raw

PATCH v4 16/31 i386/sev: Add handling to encrypt/finalize guest launch data

In reply to Pankaj Gupta

From: Brijesh Singh <[email protected]>

Process any queued up launch data and encrypt/measure it into the SNP guest instance prior to initial guest launch.

This also updates the KVM_SEV_SNP_LAUNCH_UPDATE call to handle partial update responses.

---
 target/i386/sev.c        | 112 ++++++++++++++++++++++++++++++++++++++-
 target/i386/trace-events |   2 +
 2 files changed, 113 insertions(+), 1 deletion(-)
target/i386/sev.c +111 -1
index acbb22ff15..cd47c195cd 100644
@@ -770,6 +770,76 @@ out:
     return ret;
 }
 
+static const char *
+snp_page_type_to_str(int type)
+{
+    switch (type) {
+    case KVM_SEV_SNP_PAGE_TYPE_NORMAL: return "Normal";
+    case KVM_SEV_SNP_PAGE_TYPE_ZERO: return "Zero";
+    case KVM_SEV_SNP_PAGE_TYPE_UNMEASURED: return "Unmeasured";
+    case KVM_SEV_SNP_PAGE_TYPE_SECRETS: return "Secrets";
+    case KVM_SEV_SNP_PAGE_TYPE_CPUID: return "Cpuid";
+    default: return "unknown";
+    }
+}
+
+static int
+sev_snp_launch_update(SevSnpGuestState *sev_snp_guest,
+                      SevLaunchUpdateData *data)
+{
+    int ret, fw_error;
+    struct kvm_sev_snp_launch_update update = {0};
+
+    if (!data->hva || !data->len) {
+        error_report("SNP_LAUNCH_UPDATE called with invalid address"
+                     "/ length: %p / %lx",
+                     data->hva, data->len);
+        return 1;
+    }
+
+    update.uaddr = (__u64)(unsigned long)data->hva;
+    update.gfn_start = data->gpa >> TARGET_PAGE_BITS;
+    update.len = data->len;
+    update.type = data->type;
+
+    /*
+     * KVM_SEV_SNP_LAUNCH_UPDATE requires that GPA ranges have the private
+     * memory attribute set in advance.
+     */
+    ret = kvm_set_memory_attributes_private(data->gpa, data->len);
+    if (ret) {
+        error_report("SEV-SNP: failed to configure initial"
+                     "private guest memory");
+        goto out;
+    }
+
+    while (update.len || ret == -EAGAIN) {
+        trace_kvm_sev_snp_launch_update(update.uaddr, update.gfn_start <<
+                                        TARGET_PAGE_BITS, update.len,
+                                        snp_page_type_to_str(update.type));
+
+        ret = sev_ioctl(SEV_COMMON(sev_snp_guest)->sev_fd,
+                        KVM_SEV_SNP_LAUNCH_UPDATE,
+                        &update, &fw_error);
+        if (ret && ret != -EAGAIN) {
+            error_report("SNP_LAUNCH_UPDATE ret=%d fw_error=%d '%s'",
+                         ret, fw_error, fw_error_to_str(fw_error));
+            break;
+        }
+    }
+
+out:
+    if (!ret && update.gfn_start << TARGET_PAGE_BITS != data->gpa + data->len) {
+        error_report("SEV-SNP: expected update of GPA range %lx-%lx,"
+                     "got GPA range %lx-%llx",
+                     data->gpa, data->gpa + data->len, data->gpa,
+                     update.gfn_start << TARGET_PAGE_BITS);
+        ret = -EIO;
+    }
+
+    return ret;
+}
+
 static int
 sev_launch_update_data(SevGuestState *sev_guest, uint8_t *addr, uint64_t len)
 {
@@ -915,6 +985,46 @@ sev_launch_finish(SevCommonState *sev_common)
     migrate_add_blocker(&sev_mig_blocker, &error_fatal);
 }
 
+static void
+sev_snp_launch_finish(SevCommonState *sev_common)
+{
+    int ret, error;
+    Error *local_err = NULL;
+    SevLaunchUpdateData *data;
+    SevSnpGuestState *sev_snp = SEV_SNP_GUEST(sev_common);
+    struct kvm_sev_snp_launch_finish *finish = &sev_snp->kvm_finish_conf;
+
+    QTAILQ_FOREACH(data, &launch_update, next) {
+        ret = sev_snp_launch_update(sev_snp, data);
+        if (ret) {
+            exit(1);
+        }
+    }
+
+    trace_kvm_sev_snp_launch_finish(sev_snp->id_block, sev_snp->id_auth,
+                                    sev_snp->host_data);
+    ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_SNP_LAUNCH_FINISH,
+                    finish, &error);
+    if (ret) {
+        error_report("SNP_LAUNCH_FINISH ret=%d fw_error=%d '%s'",
+                     ret, error, fw_error_to_str(error));
+        exit(1);
+    }
+
+    sev_set_guest_state(sev_common, SEV_STATE_RUNNING);
+
+    /* add migration blocker */
+    error_setg(&sev_mig_blocker,
+               "SEV-SNP: Migration is not implemented");
+    ret = migrate_add_blocker(&sev_mig_blocker, &local_err);
+    if (local_err) {
+        error_report_err(local_err);
+        error_free(sev_mig_blocker);
+        exit(1);
+    }
+}
+
+
 static void
 sev_vm_state_change(void *opaque, bool running, RunState state)
 {
@@ -1849,10 +1959,10 @@ sev_snp_guest_class_init(ObjectClass *oc, void *data)
     X86ConfidentialGuestClass *x86_klass = X86_CONFIDENTIAL_GUEST_CLASS(oc);
 
     klass->launch_start = sev_snp_launch_start;
+    klass->launch_finish = sev_snp_launch_finish;
     klass->kvm_init = sev_snp_kvm_init;
     x86_klass->kvm_type = sev_snp_kvm_type;
 
-
     object_class_property_add(oc, "policy", "uint64",
                               sev_snp_guest_get_policy,
                               sev_snp_guest_set_policy, NULL, NULL);
target/i386/trace-events +2 -0
index cb26d8a925..06b44ead2e 100644
@@ -12,3 +12,5 @@ kvm_sev_launch_finish(void) ""
 kvm_sev_launch_secret(uint64_t hpa, uint64_t hva, uint64_t secret, int len) "hpa 0x%" PRIx64 " hva 0x%" PRIx64 " data 0x%" PRIx64 " len %d"
 kvm_sev_attestation_report(const char *mnonce, const char *data) "mnonce %s data %s"
 kvm_sev_snp_launch_start(uint64_t policy, char *gosvw) "policy 0x%" PRIx64 " gosvw %s"
+kvm_sev_snp_launch_update(uint64_t src, uint64_t gpa, uint64_t len, const char *type) "src 0x%" PRIx64 " gpa 0x%" PRIx64 " len 0x%" PRIx64 " (%s page)"
+kvm_sev_snp_launch_finish(char *id_block, char *id_auth, char *host_data) "id_block %s id_auth %s host_data %s"
Signature · 1 line
2.34.1
#26 lore raw

PATCH v4 17/31 i386/sev: Set CPU state to protected once SNP guest payload is finalized

In reply to Pankaj Gupta

From: Michael Roth <[email protected]>

Once KVM_SNP_LAUNCH_FINISH is called the vCPU state is copied into the vCPU's VMSA page and measured/encrypted. Any attempt to read/write CPU state afterward will only be acting on the initial data and so are effectively no-ops.

Set the vCPU state to protected at this point so that QEMU don't continue trying to re-sync vCPU data during guest runtime.

---
 target/i386/sev.c | 1 +
 1 file changed, 1 insertion(+)
target/i386/sev.c +1 -0
index cd47c195cd..2ca9a86bf3 100644
@@ -1011,6 +1011,7 @@ sev_snp_launch_finish(SevCommonState *sev_common)
         exit(1);
     }
 
+    kvm_mark_guest_state_protected();
     sev_set_guest_state(sev_common, SEV_STATE_RUNNING);
 
     /* add migration blocker */
Signature · 1 line
2.34.1
#27 lore raw

PATCH v4 18/31 hw/i386/sev: Add function to get SEV metadata from OVMF header

In reply to Pankaj Gupta

From: Brijesh Singh <[email protected]>

A recent version of OVMF expanded the reset vector GUID list to add SEV-specific metadata GUID. The SEV metadata describes the reserved memory regions such as the secrets and CPUID page used during the SEV-SNP guest launch.

The pc_system_get_ovmf_sev_metadata_ptr() is used to retieve the SEV metadata pointer from the OVMF GUID list.

---
 hw/i386/pc_sysfw.c   |  4 ++++
 include/hw/i386/pc.h | 26 ++++++++++++++++++++++++++
 target/i386/sev.c    | 31 +++++++++++++++++++++++++++++++
 target/i386/sev.h    |  2 ++
 4 files changed, 63 insertions(+)
hw/i386/pc_sysfw.c +4 -0
index ac88ad4eb9..048d0919c1 100644
@@ -260,6 +260,10 @@ void x86_firmware_configure(void *ptr, int size)
     pc_system_parse_ovmf_flash(ptr, size);
 
     if (sev_enabled()) {
+
+        /* Copy the SEV metadata table (if exist) */
+        pc_system_parse_sev_metadata(ptr, size);
+
         ret = sev_es_save_reset_vector(ptr, size);
         if (ret) {
             error_report("failed to locate and/or save reset vector");
include/hw/i386/pc.h +26 -0
index ad9c3d9ba8..c653b8eeb2 100644
@@ -164,6 +164,32 @@ void pc_acpi_smi_interrupt(void *opaque, int irq, int level);
 #define PCI_HOST_ABOVE_4G_MEM_SIZE     "above-4g-mem-size"
 #define PCI_HOST_PROP_SMM_RANGES       "smm-ranges"
 
+typedef enum {
+    SEV_DESC_TYPE_UNDEF,
+    /* The section contains the region that must be validated by the VMM. */
+    SEV_DESC_TYPE_SNP_SEC_MEM,
+    /* The section contains the SNP secrets page */
+    SEV_DESC_TYPE_SNP_SECRETS,
+    /* The section contains address that can be used as a CPUID page */
+    SEV_DESC_TYPE_CPUID,
+
+} ovmf_sev_metadata_desc_type;
+
+typedef struct __attribute__((__packed__)) OvmfSevMetadataDesc {
+    uint32_t base;
+    uint32_t len;
+    ovmf_sev_metadata_desc_type type;
+} OvmfSevMetadataDesc;
+
+typedef struct __attribute__((__packed__)) OvmfSevMetadata {
+    uint8_t signature[4];
+    uint32_t len;
+    uint32_t version;
+    uint32_t num_desc;
+    OvmfSevMetadataDesc descs[];
+} OvmfSevMetadata;
+
+OvmfSevMetadata *pc_system_get_ovmf_sev_metadata_ptr(void);
 
 void pc_pci_as_mapping_init(MemoryRegion *system_memory,
                             MemoryRegion *pci_address_space);
target/i386/sev.c +31 -0
index 2ca9a86bf3..d9d1d97f0c 100644
@@ -611,6 +611,37 @@ SevCapability *qmp_query_sev_capabilities(Error **errp)
     return sev_get_capabilities(errp);
 }
 
+static OvmfSevMetadata *ovmf_sev_metadata_table;
+
+#define OVMF_SEV_META_DATA_GUID "dc886566-984a-4798-A75e-5585a7bf67cc"
+typedef struct __attribute__((__packed__)) OvmfSevMetadataOffset {
+    uint32_t offset;
+} OvmfSevMetadataOffset;
+
+OvmfSevMetadata *pc_system_get_ovmf_sev_metadata_ptr(void)
+{
+    return ovmf_sev_metadata_table;
+}
+
+void pc_system_parse_sev_metadata(uint8_t *flash_ptr, size_t flash_size)
+{
+    OvmfSevMetadata     *metadata;
+    OvmfSevMetadataOffset  *data;
+
+    if (!pc_system_ovmf_table_find(OVMF_SEV_META_DATA_GUID, (uint8_t **)&data,
+                                   NULL)) {
+        return;
+    }
+
+    metadata = (OvmfSevMetadata *)(flash_ptr + flash_size - data->offset);
+    if (memcmp(metadata->signature, "ASEV", 4) != 0) {
+        return;
+    }
+
+    ovmf_sev_metadata_table = g_malloc(metadata->len);
+    memcpy(ovmf_sev_metadata_table, metadata, metadata->len);
+}
+
 static SevAttestationReport *sev_get_attestation_report(const char *mnonce,
                                                         Error **errp)
 {
target/i386/sev.h +2 -0
index 5dc4767b1e..cc12824dd6 100644
@@ -66,4 +66,6 @@ int sev_inject_launch_secret(const char *hdr, const char *secret,
 int sev_es_save_reset_vector(void *flash_ptr, uint64_t flash_size);
 void sev_es_set_reset_vector(CPUState *cpu);
 
+void pc_system_parse_sev_metadata(uint8_t *flash_ptr, size_t flash_size);
+
 #endif
Signature · 1 line
2.34.1
#28 lore raw

Re: [PATCH v4 18/31] hw/i386/sev: Add function to get SEV metadata from OVMF header

Quoted 8 lines · Pankaj Gupta

From: Brijesh Singh <[email protected]>

A recent version of OVMF expanded the reset vector GUID list to add SEV-specific metadata GUID. The SEV metadata describes the reserved memory regions such as the secrets and CPUID page used during the SEV-SNP guest launch.

The pc_system_get_ovmf_sev_metadata_ptr() is used to retieve the SEV

typo: retieve

Quoted 17 lines

metadata pointer from the OVMF GUID list.

---
  hw/i386/pc_sysfw.c   |  4 ++++
  include/hw/i386/pc.h | 26 ++++++++++++++++++++++++++
  target/i386/sev.c    | 31 +++++++++++++++++++++++++++++++
  target/i386/sev.h    |  2 ++
  4 files changed, 63 insertions(+)
hw/i386/pc_sysfw.c +0 -0
index ac88ad4eb9..048d0919c1 100644

hw/i386/pc_sysfw.c void x86_firmware_configure(void *ptr, int size) · line 264

Quoted 5 lines
hw/i386/pc_sysfw.c +2 -0
@@ -260,6 +260,10 @@ void x86_firmware_configure(void *ptr, int size)
      pc_system_parse_ovmf_flash(ptr, size);
 
      if (sev_enabled()) {
+
+        /* Copy the SEV metadata table (if exist) */

Maybe s/exist/it exists/

Quoted 68 lines
hw/i386/pc_sysfw.c +2 -0
+        pc_system_parse_sev_metadata(ptr, size);
+
          ret = sev_es_save_reset_vector(ptr, size);
          if (ret) {
              error_report("failed to locate and/or save reset vector");
include/hw/i386/pc.h +26 -0
index ad9c3d9ba8..c653b8eeb2 100644
@@ -164,6 +164,32 @@ void pc_acpi_smi_interrupt(void *opaque, int irq, int level);
  #define PCI_HOST_ABOVE_4G_MEM_SIZE     "above-4g-mem-size"
  #define PCI_HOST_PROP_SMM_RANGES       "smm-ranges"
 
+typedef enum {
+    SEV_DESC_TYPE_UNDEF,
+    /* The section contains the region that must be validated by the VMM. */
+    SEV_DESC_TYPE_SNP_SEC_MEM,
+    /* The section contains the SNP secrets page */
+    SEV_DESC_TYPE_SNP_SECRETS,
+    /* The section contains address that can be used as a CPUID page */
+    SEV_DESC_TYPE_CPUID,
+
+} ovmf_sev_metadata_desc_type;
+
+typedef struct __attribute__((__packed__)) OvmfSevMetadataDesc {
+    uint32_t base;
+    uint32_t len;
+    ovmf_sev_metadata_desc_type type;
+} OvmfSevMetadataDesc;
+
+typedef struct __attribute__((__packed__)) OvmfSevMetadata {
+    uint8_t signature[4];
+    uint32_t len;
+    uint32_t version;
+    uint32_t num_desc;
+    OvmfSevMetadataDesc descs[];
+} OvmfSevMetadata;
+
+OvmfSevMetadata *pc_system_get_ovmf_sev_metadata_ptr(void);
 
  void pc_pci_as_mapping_init(MemoryRegion *system_memory,
                              MemoryRegion *pci_address_space);
target/i386/sev.c +18 -0
index 2ca9a86bf3..d9d1d97f0c 100644
@@ -611,6 +611,37 @@ SevCapability *qmp_query_sev_capabilities(Error **errp)
      return sev_get_capabilities(errp);
  }
 
+static OvmfSevMetadata *ovmf_sev_metadata_table;
+
+#define OVMF_SEV_META_DATA_GUID "dc886566-984a-4798-A75e-5585a7bf67cc"
+typedef struct __attribute__((__packed__)) OvmfSevMetadataOffset {
+    uint32_t offset;
+} OvmfSevMetadataOffset;
+
+OvmfSevMetadata *pc_system_get_ovmf_sev_metadata_ptr(void)
+{
+    return ovmf_sev_metadata_table;
+}
+
+void pc_system_parse_sev_metadata(uint8_t *flash_ptr, size_t flash_size)
+{
+    OvmfSevMetadata     *metadata;
+    OvmfSevMetadataOffset  *data;
+
+    if (!pc_system_ovmf_table_find(OVMF_SEV_META_DATA_GUID, (uint8_t **)&data,

target/i386/sev.c SevCapability *qmp_query_sev_capabilities(Error **errp) · line 641

Quoted 10 lines
target/i386/sev.c +10 -0
+                                   NULL)) {
+        return;
+    }
+
+    metadata = (OvmfSevMetadata *)(flash_ptr + flash_size - data->offset);
+    if (memcmp(metadata->signature, "ASEV", 4) != 0) {
+        return;
+    }
+
+    ovmf_sev_metadata_table = g_malloc(metadata->len);

There should be a bounds check on metadata->len before using it.

Quoted 17 lines
target/i386/sev.c +3 -0
+    memcpy(ovmf_sev_metadata_table, metadata, metadata->len);
+}
+
  static SevAttestationReport *sev_get_attestation_report(const char *mnonce,
                                                          Error **errp)
  {
target/i386/sev.h +2 -0
index 5dc4767b1e..cc12824dd6 100644
@@ -66,4 +66,6 @@ int sev_inject_launch_secret(const char *hdr, const char *secret,
  int sev_es_save_reset_vector(void *flash_ptr, uint64_t flash_size);
  void sev_es_set_reset_vector(CPUState *cpu);
 
+void pc_system_parse_sev_metadata(uint8_t *flash_ptr, size_t flash_size);
+
  #endif
maintainer
#29 lore raw

Re: [PATCH v4 18/31] hw/i386/sev: Add function to get SEV metadata from OVMF header

Quoted 8 lines · Liam Merwick

target/i386/sev.c SevCapability *qmp_query_sev_capabilities(Error **errp) · line 641

Quoted 6 lines
target/i386/sev.c +6 -0
+    metadata = (OvmfSevMetadata *)(flash_ptr + flash_size - data->offset);
+    if (memcmp(metadata->signature, "ASEV", 4) != 0) {
+        return;
+    }
+
+    ovmf_sev_metadata_table = g_malloc(metadata->len);

There should be a bounds check on metadata->len before using it.

You mean like:

    if (metadata->len <= flash_size - data->offset) {
        ovmf_sev_metadata_table = g_memdup2(metadata, metadata->len);
    }

?

Paolo

#30 lore raw

Re: [PATCH v4 18/31] hw/i386/sev: Add function to get SEV metadata from OVMF header

Quoted 8 lines · Paolo Bonzini
Quoted 7 lines · Liam Merwick
Quoted 6 lines
target/i386/sev.c +6 -0
+    metadata = (OvmfSevMetadata *)(flash_ptr + flash_size - data->offset);
+    if (memcmp(metadata->signature, "ASEV", 4) != 0) {
+        return;
+    }
+
+    ovmf_sev_metadata_table = g_malloc(metadata->len);
Quoted 8 lines
Quoted 1 line

There should be a bounds check on metadata->len before using it.

You mean like:

     if (metadata->len <= flash_size - data->offset) {
         ovmf_sev_metadata_table = g_memdup2(metadata, metadata->len);
     }

Yeah, and maybe before that

if (metadata->len < sizeof(OvmfSevMetadata))
return

But the main thing would be checking the upper bound to avoid allocating a huge amount of memory

Regards,
Liam

#31 lore raw

PATCH v4 19/31 i386/sev: Add support for populating OVMF metadata pages

In reply to Pankaj Gupta

From: Brijesh Singh <[email protected]>

OVMF reserves various pages so they can be pre-initialized/validated prior to launching the guest. Add support for populating these pages with the expected content.

---
 target/i386/sev.c | 74 +++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 74 insertions(+)
target/i386/sev.c +74 -0
index d9d1d97f0c..504f641038 100644
@@ -1016,15 +1016,89 @@ sev_launch_finish(SevCommonState *sev_common)
     migrate_add_blocker(&sev_mig_blocker, &error_fatal);
 }
 
+static int
+snp_launch_update_data(uint64_t gpa, void *hva, uint32_t len, int type)
+{
+    SevLaunchUpdateData *data;
+
+    data = g_new0(SevLaunchUpdateData, 1);
+    data->gpa = gpa;
+    data->hva = hva;
+    data->len = len;
+    data->type = type;
+
+    QTAILQ_INSERT_TAIL(&launch_update, data, next);
+
+    return 0;
+}
+
+static int
+snp_metadata_desc_to_page_type(int desc_type)
+{
+    switch (desc_type) {
+    /* Add the umeasured prevalidated pages as a zero page */
+    case SEV_DESC_TYPE_SNP_SEC_MEM: return KVM_SEV_SNP_PAGE_TYPE_ZERO;
+    case SEV_DESC_TYPE_SNP_SECRETS: return KVM_SEV_SNP_PAGE_TYPE_SECRETS;
+    case SEV_DESC_TYPE_CPUID: return KVM_SEV_SNP_PAGE_TYPE_CPUID;
+    default:
+         return KVM_SEV_SNP_PAGE_TYPE_ZERO;
+    }
+}
+
+static void
+snp_populate_metadata_pages(SevSnpGuestState *sev_snp,
+                            OvmfSevMetadata *metadata)
+{
+    OvmfSevMetadataDesc *desc;
+    int type, ret, i;
+    void *hva;
+    MemoryRegion *mr = NULL;
+
+    for (i = 0; i < metadata->num_desc; i++) {
+        desc = &metadata->descs[i];
+
+        type = snp_metadata_desc_to_page_type(desc->type);
+
+        hva = gpa2hva(&mr, desc->base, desc->len, NULL);
+        if (!hva) {
+            error_report("%s: Failed to get HVA for GPA 0x%x sz 0x%x",
+                         __func__, desc->base, desc->len);
+            exit(1);
+        }
+
+        ret = snp_launch_update_data(desc->base, hva, desc->len, type);
+        if (ret) {
+            error_report("%s: Failed to add metadata page gpa 0x%x+%x type %d",
+                         __func__, desc->base, desc->len, desc->type);
+            exit(1);
+        }
+    }
+}
+
 static void
 sev_snp_launch_finish(SevCommonState *sev_common)
 {
     int ret, error;
     Error *local_err = NULL;
+    OvmfSevMetadata *metadata;
     SevLaunchUpdateData *data;
     SevSnpGuestState *sev_snp = SEV_SNP_GUEST(sev_common);
     struct kvm_sev_snp_launch_finish *finish = &sev_snp->kvm_finish_conf;
 
+    /*
+     * To boot the SNP guest, the hypervisor is required to populate the CPUID
+     * and Secrets page before finalizing the launch flow. The location of
+     * the secrets and CPUID page is available through the OVMF metadata GUID.
+     */
+    metadata = pc_system_get_ovmf_sev_metadata_ptr();
+    if (metadata == NULL) {
+        error_report("%s: Failed to locate SEV metadata header", __func__);
+        exit(1);
+    }
+
+    /* Populate all the metadata pages */
+    snp_populate_metadata_pages(sev_snp, metadata);
+
     QTAILQ_FOREACH(data, &launch_update, next) {
         ret = sev_snp_launch_update(sev_snp, data);
         if (ret) {
Signature · 1 line
2.34.1
#32 lore raw

PATCH v4 20/31 i386/sev: Add support for SNP CPUID validation

In reply to Pankaj Gupta

From: Michael Roth <[email protected]>

SEV-SNP firmware allows a special guest page to be populated with a table of guest CPUID values so that they can be validated through firmware before being loaded into encrypted guest memory where they can be used in place of hypervisor-provided values[1].

As part of SEV-SNP guest initialization, use this interface to validate the CPUID entries reported by KVM_GET_CPUID2 prior to initial guest start and populate the CPUID page reserved by OVMF with the resulting encrypted data.

[1] SEV SNP Firmware ABI Specification, Rev. 0.8, 8.13.2.6

---
 target/i386/sev.c | 164 +++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 162 insertions(+), 2 deletions(-)
target/i386/sev.c +162 -2
index 504f641038..4388ffe867 100644
@@ -214,6 +214,36 @@ static const char *const sev_fw_errlist[] = {
 
 #define SEV_FW_MAX_ERROR      ARRAY_SIZE(sev_fw_errlist)
 
+/* <linux/kvm.h> doesn't expose this, so re-use the max from kvm.c */
+#define KVM_MAX_CPUID_ENTRIES 100
+
+typedef struct KvmCpuidInfo {
+    struct kvm_cpuid2 cpuid;
+    struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
+} KvmCpuidInfo;
+
+#define SNP_CPUID_FUNCTION_MAXCOUNT 64
+#define SNP_CPUID_FUNCTION_UNKNOWN 0xFFFFFFFF
+
+typedef struct {
+    uint32_t eax_in;
+    uint32_t ecx_in;
+    uint64_t xcr0_in;
+    uint64_t xss_in;
+    uint32_t eax;
+    uint32_t ebx;
+    uint32_t ecx;
+    uint32_t edx;
+    uint64_t reserved;
+} __attribute__((packed)) SnpCpuidFunc;
+
+typedef struct {
+    uint32_t count;
+    uint32_t reserved1;
+    uint64_t reserved2;
+    SnpCpuidFunc entries[SNP_CPUID_FUNCTION_MAXCOUNT];
+} __attribute__((packed)) SnpCpuidInfo;
+
 static int
 sev_ioctl(int fd, int cmd, void *data, int *error)
 {
@@ -801,6 +831,35 @@ out:
     return ret;
 }
 
+static void
+sev_snp_cpuid_report_mismatches(SnpCpuidInfo *old,
+                                SnpCpuidInfo *new)
+{
+    size_t i;
+
+    if (old->count != new->count) {
+        error_report("SEV-SNP: CPUID validation failed due to count mismatch,"
+                     "provided: %d, expected: %d", old->count, new->count);
+        return;
+    }
+
+    for (i = 0; i < old->count; i++) {
+        SnpCpuidFunc *old_func, *new_func;
+
+        old_func = &old->entries[i];
+        new_func = &new->entries[i];
+
+        if (memcmp(old_func, new_func, sizeof(SnpCpuidFunc))) {
+            error_report("SEV-SNP: CPUID validation failed for function 0x%x, index: 0x%x"
+                         "provided: eax:0x%08x, ebx: 0x%08x, ecx: 0x%08x, edx: 0x%08x"
+                         "expected: eax:0x%08x, ebx: 0x%08x, ecx: 0x%08x, edx: 0x%08x",
+                         old_func->eax_in, old_func->ecx_in,
+                         old_func->eax, old_func->ebx, old_func->ecx, old_func->edx,
+                         new_func->eax, new_func->ebx, new_func->ecx, new_func->edx);
+        }
+    }
+}
+
 static const char *
 snp_page_type_to_str(int type)
 {
@@ -819,6 +878,7 @@ sev_snp_launch_update(SevSnpGuestState *sev_snp_guest,
                       SevLaunchUpdateData *data)
 {
     int ret, fw_error;
+    SnpCpuidInfo snp_cpuid_info;
     struct kvm_sev_snp_launch_update update = {0};
 
     if (!data->hva || !data->len) {
@@ -828,6 +888,11 @@ sev_snp_launch_update(SevSnpGuestState *sev_snp_guest,
         return 1;
     }
 
+    if (data->type == KVM_SEV_SNP_PAGE_TYPE_CPUID) {
+        /* Save a copy for comparison in case the LAUNCH_UPDATE fails */
+        memcpy(&snp_cpuid_info, data->hva, sizeof(snp_cpuid_info));
+    }
+
     update.uaddr = (__u64)(unsigned long)data->hva;
     update.gfn_start = data->gpa >> TARGET_PAGE_BITS;
     update.len = data->len;
@@ -855,6 +920,11 @@ sev_snp_launch_update(SevSnpGuestState *sev_snp_guest,
         if (ret && ret != -EAGAIN) {
             error_report("SNP_LAUNCH_UPDATE ret=%d fw_error=%d '%s'",
                          ret, fw_error, fw_error_to_str(fw_error));
+
+            if (data->type == KVM_SEV_SNP_PAGE_TYPE_CPUID) {
+                sev_snp_cpuid_report_mismatches(&snp_cpuid_info, data->hva);
+                error_report("SEV-SNP: failed update CPUID page");
+            }
             break;
         }
     }
@@ -1017,7 +1087,8 @@ sev_launch_finish(SevCommonState *sev_common)
 }
 
 static int
-snp_launch_update_data(uint64_t gpa, void *hva, uint32_t len, int type)
+snp_launch_update_data(uint64_t gpa, void *hva,
+                       uint32_t len, int type)
 {
     SevLaunchUpdateData *data;
 
@@ -1032,6 +1103,90 @@ snp_launch_update_data(uint64_t gpa, void *hva, uint32_t len, int type)
     return 0;
 }
 
+static int
+sev_snp_cpuid_info_fill(SnpCpuidInfo *snp_cpuid_info,
+                        const KvmCpuidInfo *kvm_cpuid_info)
+{
+    size_t i;
+
+    if (kvm_cpuid_info->cpuid.nent > SNP_CPUID_FUNCTION_MAXCOUNT) {
+        error_report("SEV-SNP: CPUID entry count (%d) exceeds max (%d)",
+                     kvm_cpuid_info->cpuid.nent, SNP_CPUID_FUNCTION_MAXCOUNT);
+        return -1;
+    }
+
+    memset(snp_cpuid_info, 0, sizeof(*snp_cpuid_info));
+
+    for (i = 0; i < kvm_cpuid_info->cpuid.nent; i++) {
+        const struct kvm_cpuid_entry2 *kvm_cpuid_entry;
+        SnpCpuidFunc *snp_cpuid_entry;
+
+        kvm_cpuid_entry = &kvm_cpuid_info->entries[i];
+        snp_cpuid_entry = &snp_cpuid_info->entries[i];
+
+        snp_cpuid_entry->eax_in = kvm_cpuid_entry->function;
+        if (kvm_cpuid_entry->flags == KVM_CPUID_FLAG_SIGNIFCANT_INDEX) {
+            snp_cpuid_entry->ecx_in = kvm_cpuid_entry->index;
+        }
+        snp_cpuid_entry->eax = kvm_cpuid_entry->eax;
+        snp_cpuid_entry->ebx = kvm_cpuid_entry->ebx;
+        snp_cpuid_entry->ecx = kvm_cpuid_entry->ecx;
+        snp_cpuid_entry->edx = kvm_cpuid_entry->edx;
+
+        /*
+         * Guest kernels will calculate EBX themselves using the 0xD
+         * subfunctions corresponding to the individual XSAVE areas, so only
+         * encode the base XSAVE size in the initial leaves, corresponding
+         * to the initial XCR0=1 state.
+         */
+        if (snp_cpuid_entry->eax_in == 0xD &&
+            (snp_cpuid_entry->ecx_in == 0x0 || snp_cpuid_entry->ecx_in == 0x1)) {
+            snp_cpuid_entry->ebx = 0x240;
+            snp_cpuid_entry->xcr0_in = 1;
+            snp_cpuid_entry->xss_in = 0;
+        }
+    }
+
+    snp_cpuid_info->count = i;
+
+    return 0;
+}
+
+static int
+snp_launch_update_cpuid(uint32_t cpuid_addr, void *hva, uint32_t cpuid_len)
+{
+    KvmCpuidInfo kvm_cpuid_info = {0};
+    SnpCpuidInfo snp_cpuid_info;
+    CPUState *cs = first_cpu;
+    int ret;
+    uint32_t i = 0;
+
+    assert(sizeof(snp_cpuid_info) <= cpuid_len);
+
+    /* get the cpuid list from KVM */
+    do {
+        kvm_cpuid_info.cpuid.nent = ++i;
+        ret = kvm_vcpu_ioctl(cs, KVM_GET_CPUID2, &kvm_cpuid_info);
+    } while (ret == -E2BIG);
+
+    if (ret) {
+        error_report("SEV-SNP: unable to query CPUID values for CPU: '%s'",
+                     strerror(-ret));
+        return 1;
+    }
+
+    ret = sev_snp_cpuid_info_fill(&snp_cpuid_info, &kvm_cpuid_info);
+    if (ret) {
+        error_report("SEV-SNP: failed to generate CPUID table information");
+        return 1;
+    }
+
+    memcpy(hva, &snp_cpuid_info, sizeof(snp_cpuid_info));
+
+    return snp_launch_update_data(cpuid_addr, hva, cpuid_len,
+                                  KVM_SEV_SNP_PAGE_TYPE_CPUID);
+}
+
 static int
 snp_metadata_desc_to_page_type(int desc_type)
 {
@@ -1066,7 +1221,12 @@ snp_populate_metadata_pages(SevSnpGuestState *sev_snp,
             exit(1);
         }
 
-        ret = snp_launch_update_data(desc->base, hva, desc->len, type);
+        if (type == KVM_SEV_SNP_PAGE_TYPE_CPUID) {
+            ret = snp_launch_update_cpuid(desc->base, hva, desc->len);
+        } else {
+            ret = snp_launch_update_data(desc->base, hva, desc->len, type);
+        }
+
         if (ret) {
             error_report("%s: Failed to add metadata page gpa 0x%x+%x type %d",
                          __func__, desc->base, desc->len, desc->type);
Signature · 1 line
2.34.1
#33 lore raw

Re: [PATCH v4 20/31] i386/sev: Add support for SNP CPUID validation

Quoted 11 lines · Pankaj Gupta

From: Michael Roth <[email protected]>

SEV-SNP firmware allows a special guest page to be populated with a table of guest CPUID values so that they can be validated through firmware before being loaded into encrypted guest memory where they can be used in place of hypervisor-provided values[1].

As part of SEV-SNP guest initialization, use this interface to validate the CPUID entries reported by KVM_GET_CPUID2 prior to initial guest start and populate the CPUID page reserved by OVMF with the resulting encrypted data.

How is KVM CPUIDs (leaf 0x40000001) validated?

I suppose not all KVM_FEATURE_XXX are supported for SNP guest. And SNP firmware doesn't validate such CPUID range. So how does them get validated?

Quoted 2 lines

[1] SEV SNP Firmware ABI Specification, Rev. 0.8, 8.13.2.6

#34 lore raw

Re: [PATCH v4 20/31] i386/sev: Add support for SNP CPUID validation

Quoted 13 lines · Xiaoyao Li
Quoted 11 lines · Pankaj Gupta

From: Michael Roth <[email protected]>

SEV-SNP firmware allows a special guest page to be populated with a table of guest CPUID values so that they can be validated through firmware before being loaded into encrypted guest memory where they can be used in place of hypervisor-provided values[1].

As part of SEV-SNP guest initialization, use this interface to validate the CPUID entries reported by KVM_GET_CPUID2 prior to initial guest start and populate the CPUID page reserved by OVMF with the resulting encrypted data.

Quoted 4 lines

How is KVM CPUIDs (leaf 0x40000001) validated?

I suppose not all KVM_FEATURE_XXX are supported for SNP guest. And SNP firmware doesn't validate such CPUID range. So how does them get validated?

This rules for CPUID enforcement are documented in the PPR for each AMD CPU model in Chapter 2, section "CPUID Policy Enforcement". For the situation you mentioned, it's stated there that:

The PSP enforces the following policy:
- If the CPUID function is not in the standard range (Fn00000000 through Fn0000FFFF) or the extended range
(Fn8000_0000 through Fn8000_FFFF), the function output check is UnChecked.
- If the CPUID function is in the standard or extended range and the function is not listed in SEV-SNP CPUID
Policy table, then the output check is Strict and required to be 0. Note that if the CPUID function does not depend
on ECX and/or XCR0, then the PSP policy ignores those inputs, respectively.
- Otherwise, the check is defined according to the values listed in SEV-SNP CPUID Policy table.

So there are specific ranges that are checked, mainly ones where there is potential for guests to misbehave if they are being lied to. But hypervisor-ranges are paravirtual in a sense so there's no assumptions being made about what the underlying hardware is doing, so the checks are needed as much in those cases.

-Mike

Quoted 4 lines
Quoted 3 lines

[1] SEV SNP Firmware ABI Specification, Rev. 0.8, 8.13.2.6

#35 lore raw

Re: [PATCH v4 20/31] i386/sev: Add support for SNP CPUID validation

Quoted 37 lines · Michael Roth
Quoted 13 lines · Xiaoyao Li
Quoted 11 lines · Pankaj Gupta

From: Michael Roth <[email protected]>

SEV-SNP firmware allows a special guest page to be populated with a table of guest CPUID values so that they can be validated through firmware before being loaded into encrypted guest memory where they can be used in place of hypervisor-provided values[1].

As part of SEV-SNP guest initialization, use this interface to validate the CPUID entries reported by KVM_GET_CPUID2 prior to initial guest start and populate the CPUID page reserved by OVMF with the resulting encrypted data.

Quoted 4 lines

How is KVM CPUIDs (leaf 0x40000001) validated?

I suppose not all KVM_FEATURE_XXX are supported for SNP guest. And SNP firmware doesn't validate such CPUID range. So how does them get validated?

This rules for CPUID enforcement are documented in the PPR for each AMD CPU model in Chapter 2, section "CPUID Policy Enforcement". For the situation you mentioned, it's stated there that:

The PSP enforces the following policy:
- If the CPUID function is not in the standard range (Fn00000000 through Fn0000FFFF) or the extended range
(Fn8000_0000 through Fn8000_FFFF), the function output check is UnChecked.
- If the CPUID function is in the standard or extended range and the function is not listed in SEV-SNP CPUID
Policy table, then the output check is Strict and required to be 0. Note that if the CPUID function does not depend
on ECX and/or XCR0, then the PSP policy ignores those inputs, respectively.
- Otherwise, the check is defined according to the values listed in SEV-SNP CPUID Policy table.

Quoted 5 lines

So there are specific ranges that are checked, mainly ones where there is potential for guests to misbehave if they are being lied to. But hypervisor-ranges are paravirtual in a sense so there's no assumptions being made about what the underlying hardware is doing, so the checks are needed as much in those cases.

I'm a little confused. Per your reference above, hypervisor-ranges is unchecked because it's not in the standard range nor the extended range.

And your last sentence said "so the checks are needed as much in those cases". So how does hypervisor-ranges get checked?

Quoted 6 lines

-Mike

Quoted 4 lines
Quoted 3 lines

[1] SEV SNP Firmware ABI Specification, Rev. 0.8, 8.13.2.6

maintainer
#36 lore raw

Re: [PATCH v4 20/31] i386/sev: Add support for SNP CPUID validation

Quoted 11 lines · Xiaoyao Li
Quoted 5 lines

So there are specific ranges that are checked, mainly ones where there is potential for guests to misbehave if they are being lied to. But hypervisor-ranges are paravirtual in a sense so there's no assumptions being made about what the underlying hardware is doing, so the checks are needed as much in those cases.

I'm a little confused. Per your reference above, hypervisor-ranges is unchecked because it's not in the standard range nor the extended range.

And your last sentence said "so the checks are needed as much in those cases". So how does hypervisor-ranges get checked?

I think "not" is missing in the sentence.

Paolo

#37 lore raw

PATCH v4 21/31 i386/sev: Extract build_kernel_loader_hashes

In reply to Pankaj Gupta

From: Dov Murik <[email protected]>

Extract the building of the kernel hashes table out from sev_add_kernel_loader_hashes() to allow building it in other memory areas (for SNP support).

No functional change intended.

---
 target/i386/sev.c | 101 ++++++++++++++++++++++++++--------------------
 1 file changed, 58 insertions(+), 43 deletions(-)
target/i386/sev.c +58 -43
index 4388ffe867..831745c02a 100644
@@ -1751,45 +1751,16 @@ static const QemuUUID sev_cmdline_entry_guid = {
                     0x4d, 0x36, 0xab, 0x2a)
 };
 
-/*
- * Add the hashes of the linux kernel/initrd/cmdline to an encrypted guest page
- * which is included in SEV's initial memory measurement.
- */
-bool sev_add_kernel_loader_hashes(SevKernelLoaderContext *ctx, Error **errp)
+static bool build_kernel_loader_hashes(PaddedSevHashTable *padded_ht,
+                                       SevKernelLoaderContext *ctx,
+                                       Error **errp)
 {
-    uint8_t *data;
-    SevHashTableDescriptor *area;
     SevHashTable *ht;
-    PaddedSevHashTable *padded_ht;
     uint8_t cmdline_hash[HASH_SIZE];
     uint8_t initrd_hash[HASH_SIZE];
     uint8_t kernel_hash[HASH_SIZE];
     uint8_t *hashp;
     size_t hash_len = HASH_SIZE;
-    hwaddr mapped_len = sizeof(*padded_ht);
-    MemTxAttrs attrs = { 0 };
-    bool ret = true;
-    SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
-
-    /*
-     * Only add the kernel hashes if the sev-guest configuration explicitly
-     * stated kernel-hashes=on.
-     */
-    if (!sev_common->kernel_hashes) {
-        return false;
-    }
-
-    if (!pc_system_ovmf_table_find(SEV_HASH_TABLE_RV_GUID, &data, NULL)) {
-        error_setg(errp, "SEV: kernel specified but guest firmware "
-                         "has no hashes table GUID");
-        return false;
-    }
-    area = (SevHashTableDescriptor *)data;
-    if (!area->base || area->size < sizeof(PaddedSevHashTable)) {
-        error_setg(errp, "SEV: guest firmware hashes table area is invalid "
-                         "(base=0x%x size=0x%x)", area->base, area->size);
-        return false;
-    }
 
     /*
      * Calculate hash of kernel command-line with the terminating null byte. If
@@ -1826,16 +1797,6 @@ bool sev_add_kernel_loader_hashes(SevKernelLoaderContext *ctx, Error **errp)
     }
     assert(hash_len == HASH_SIZE);
 
-    /*
-     * Populate the hashes table in the guest's memory at the OVMF-designated
-     * area for the SEV hashes table
-     */
-    padded_ht = address_space_map(&address_space_memory, area->base,
-                                  &mapped_len, true, attrs);
-    if (!padded_ht || mapped_len != sizeof(*padded_ht)) {
-        error_setg(errp, "SEV: cannot map hashes table guest memory area");
-        return false;
-    }
     ht = &padded_ht->ht;
 
     ht->guid = sev_hash_table_header_guid;
@@ -1856,7 +1817,61 @@ bool sev_add_kernel_loader_hashes(SevKernelLoaderContext *ctx, Error **errp)
     /* zero the excess data so the measurement can be reliably calculated */
     memset(padded_ht->padding, 0, sizeof(padded_ht->padding));
 
-    if (sev_encrypt_flash((uint8_t *)padded_ht, sizeof(*padded_ht), errp) < 0) {
+    return true;
+}
+
+/*
+ * Add the hashes of the linux kernel/initrd/cmdline to an encrypted guest page
+ * which is included in SEV's initial memory measurement.
+ */
+bool sev_add_kernel_loader_hashes(SevKernelLoaderContext *ctx, Error **errp)
+{
+    uint8_t *data;
+    SevHashTableDescriptor *area;
+    PaddedSevHashTable *padded_ht;
+    hwaddr mapped_len = sizeof(*padded_ht);
+    MemTxAttrs attrs = { 0 };
+    bool ret = true;
+    SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
+
+    /*
+     * Only add the kernel hashes if the sev-guest configuration explicitly
+     * stated kernel-hashes=on.
+     */
+    if (!sev_common->kernel_hashes) {
+        return false;
+    }
+
+    if (!pc_system_ovmf_table_find(SEV_HASH_TABLE_RV_GUID, &data, NULL)) {
+        error_setg(errp, "SEV: kernel specified but guest firmware "
+                         "has no hashes table GUID");
+        return false;
+    }
+
+    area = (SevHashTableDescriptor *)data;
+    if (!area->base || area->size < sizeof(PaddedSevHashTable)) {
+        error_setg(errp, "SEV: guest firmware hashes table area is invalid "
+                         "(base=0x%x size=0x%x)", area->base, area->size);
+        return false;
+    }
+
+    /*
+     * Populate the hashes table in the guest's memory at the OVMF-designated
+     * area for the SEV hashes table
+     */
+    padded_ht = address_space_map(&address_space_memory, area->base,
+                                  &mapped_len, true, attrs);
+    if (!padded_ht || mapped_len != sizeof(*padded_ht)) {
+        error_setg(errp, "SEV: cannot map hashes table guest memory area");
+        return false;
+    }
+
+    if (build_kernel_loader_hashes(padded_ht, ctx, errp)) {
+        if (sev_encrypt_flash((uint8_t *)padded_ht, sizeof(*padded_ht),
+                              errp) < 0) {
+            ret = false;
+        }
+    } else {
         ret = false;
     }
 
Signature · 1 line
2.34.1
#38 lore raw

PATCH v4 22/31 i386/sev: Reorder struct declarations

In reply to Pankaj Gupta

From: Dov Murik <[email protected]>

Move the declaration of PaddedSevHashTable before SevSnpGuest so we can add a new such field to the latter.

No functional change intended.

---
 target/i386/sev.c | 56 +++++++++++++++++++++++------------------------
 1 file changed, 28 insertions(+), 28 deletions(-)
target/i386/sev.c +28 -28
index 831745c02a..1b29fdbc9a 100644
@@ -45,6 +45,34 @@ OBJECT_DECLARE_TYPE(SevCommonState, SevCommonStateClass, SEV_COMMON)
 OBJECT_DECLARE_TYPE(SevGuestState, SevGuestStateClass, SEV_GUEST)
 OBJECT_DECLARE_TYPE(SevSnpGuestState, SevSnpGuestStateClass, SEV_SNP_GUEST)
 
+/* hard code sha256 digest size */
+#define HASH_SIZE 32
+
+typedef struct QEMU_PACKED SevHashTableEntry {
+    QemuUUID guid;
+    uint16_t len;
+    uint8_t hash[HASH_SIZE];
+} SevHashTableEntry;
+
+typedef struct QEMU_PACKED SevHashTable {
+    QemuUUID guid;
+    uint16_t len;
+    SevHashTableEntry cmdline;
+    SevHashTableEntry initrd;
+    SevHashTableEntry kernel;
+} SevHashTable;
+
+/*
+ * Data encrypted by sev_encrypt_flash() must be padded to a multiple of
+ * 16 bytes.
+ */
+typedef struct QEMU_PACKED PaddedSevHashTable {
+    SevHashTable ht;
+    uint8_t padding[ROUND_UP(sizeof(SevHashTable), 16) - sizeof(SevHashTable)];
+} PaddedSevHashTable;
+
+QEMU_BUILD_BUG_ON(sizeof(PaddedSevHashTable) % 16 != 0);
+
 struct SevCommonState {
     X86ConfidentialGuest parent_obj;
 
@@ -154,34 +182,6 @@ typedef struct QEMU_PACKED SevHashTableDescriptor {
     uint32_t size;
 } SevHashTableDescriptor;
 
-/* hard code sha256 digest size */
-#define HASH_SIZE 32
-
-typedef struct QEMU_PACKED SevHashTableEntry {
-    QemuUUID guid;
-    uint16_t len;
-    uint8_t hash[HASH_SIZE];
-} SevHashTableEntry;
-
-typedef struct QEMU_PACKED SevHashTable {
-    QemuUUID guid;
-    uint16_t len;
-    SevHashTableEntry cmdline;
-    SevHashTableEntry initrd;
-    SevHashTableEntry kernel;
-} SevHashTable;
-
-/*
- * Data encrypted by sev_encrypt_flash() must be padded to a multiple of
- * 16 bytes.
- */
-typedef struct QEMU_PACKED PaddedSevHashTable {
-    SevHashTable ht;
-    uint8_t padding[ROUND_UP(sizeof(SevHashTable), 16) - sizeof(SevHashTable)];
-} PaddedSevHashTable;
-
-QEMU_BUILD_BUG_ON(sizeof(PaddedSevHashTable) % 16 != 0);
-
 static Error *sev_mig_blocker;
 
 static const char *const sev_fw_errlist[] = {
Signature · 1 line
2.34.1
maintainer
#39 lore raw

Re: [PATCH v4 22/31] i386/sev: Reorder struct declarations

Quoted 40 lines · Pankaj Gupta

From: Dov Murik <[email protected]>

Move the declaration of PaddedSevHashTable before SevSnpGuest so we can add a new such field to the latter.

No functional change intended.

---
 target/i386/sev.c | 56 +++++++++++++++++++++++------------------------
 1 file changed, 28 insertions(+), 28 deletions(-)
target/i386/sev.c +17 -0
index 831745c02a..1b29fdbc9a 100644
@@ -45,6 +45,34 @@ OBJECT_DECLARE_TYPE(SevCommonState, SevCommonStateClass, SEV_COMMON)
 OBJECT_DECLARE_TYPE(SevGuestState, SevGuestStateClass, SEV_GUEST)
 OBJECT_DECLARE_TYPE(SevSnpGuestState, SevSnpGuestStateClass, SEV_SNP_GUEST)
 
+/* hard code sha256 digest size */
+#define HASH_SIZE 32
+
+typedef struct QEMU_PACKED SevHashTableEntry {
+    QemuUUID guid;
+    uint16_t len;
+    uint8_t hash[HASH_SIZE];
+} SevHashTableEntry;
+
+typedef struct QEMU_PACKED SevHashTable {
+    QemuUUID guid;
+    uint16_t len;
+    SevHashTableEntry cmdline;
+    SevHashTableEntry initrd;
+    SevHashTableEntry kernel;
+} SevHashTable;
+

target/i386/sev.c OBJECT_DECLARE_TYPE(SevCommonState, SevCommonStateClass, SEV_COMMON) · line 74

Quoted 10 lines
target/i386/sev.c +10 -0
+/*
+ * Data encrypted by sev_encrypt_flash() must be padded to a multiple of
+ * 16 bytes.
+ */
+typedef struct QEMU_PACKED PaddedSevHashTable {
+    SevHashTable ht;
+    uint8_t padding[ROUND_UP(sizeof(SevHashTable), 16) - sizeof(SevHashTable)];
+} PaddedSevHashTable;
+
+QEMU_BUILD_BUG_ON(sizeof(PaddedSevHashTable) % 16 != 0);

Please move also the following lines (SevInfoBlock, SevHashTableDescriptor and the GUIDs) as they are related.

Paolo

#40 lore raw

PATCH v4 23/31 i386/sev: Allow measured direct kernel boot on SNP

In reply to Pankaj Gupta

From: Dov Murik <[email protected]>

In SNP, the hashes page designated with a specific metadata entry published in AmdSev OVMF.

Therefore, if the user enabled kernel hashes (for measured direct boot), QEMU should prepare the content of hashes table, and during the processing of the metadata entry it copy the content into the designated page and encrypt it.

Note that in SNP (unlike SEV and SEV-ES) the measurements is done in whole 4KB pages. Therefore QEMU zeros the whole page that includes the hashes table, and fills in the kernel hashes area in that page, and then encrypts the whole page. The rest of the page is reserved for SEV launch secrets which are not usable anyway on SNP.

If the user disabled kernel hashes, QEMU pre-validates the kernel hashes page as a zero page.

---
 include/hw/i386/pc.h |  2 ++
 target/i386/sev.c    | 35 +++++++++++++++++++++++++++++++++++
 2 files changed, 37 insertions(+)
include/hw/i386/pc.h +2 -0
index c653b8eeb2..ca7904ac2c 100644
@@ -172,6 +172,8 @@ typedef enum {
     SEV_DESC_TYPE_SNP_SECRETS,
     /* The section contains address that can be used as a CPUID page */
     SEV_DESC_TYPE_CPUID,
+    /* The section contains the region for kernel hashes for measured direct boot */
+    SEV_DESC_TYPE_SNP_KERNEL_HASHES = 0x10,
 
 } ovmf_sev_metadata_desc_type;
 
target/i386/sev.c +35 -0
index 1b29fdbc9a..1a78e98751 100644
@@ -145,6 +145,9 @@ struct SevSnpGuestState {
 
     struct kvm_sev_snp_launch_start kvm_start_conf;
     struct kvm_sev_snp_launch_finish kvm_finish_conf;
+
+    uint32_t kernel_hashes_offset;
+    PaddedSevHashTable *kernel_hashes_data;
 };
 
 struct SevSnpGuestStateClass {
@@ -1187,6 +1190,23 @@ snp_launch_update_cpuid(uint32_t cpuid_addr, void *hva, uint32_t cpuid_len)
                                   KVM_SEV_SNP_PAGE_TYPE_CPUID);
 }
 
+static int
+snp_launch_update_kernel_hashes(SevSnpGuestState *sev_snp, uint32_t addr,
+                                void *hva, uint32_t len)
+{
+    int type = KVM_SEV_SNP_PAGE_TYPE_ZERO;
+    if (sev_snp->parent_obj.kernel_hashes) {
+        assert(sev_snp->kernel_hashes_data);
+        assert((sev_snp->kernel_hashes_offset +
+                sizeof(*sev_snp->kernel_hashes_data)) <= len);
+        memset(hva, 0, len);
+        memcpy(hva + sev_snp->kernel_hashes_offset, sev_snp->kernel_hashes_data,
+               sizeof(*sev_snp->kernel_hashes_data));
+        type = KVM_SEV_SNP_PAGE_TYPE_NORMAL;
+    }
+    return snp_launch_update_data(addr, hva, len, type);
+}
+
 static int
 snp_metadata_desc_to_page_type(int desc_type)
 {
@@ -1223,6 +1243,9 @@ snp_populate_metadata_pages(SevSnpGuestState *sev_snp,
 
         if (type == KVM_SEV_SNP_PAGE_TYPE_CPUID) {
             ret = snp_launch_update_cpuid(desc->base, hva, desc->len);
+        } else if (desc->type == SEV_DESC_TYPE_SNP_KERNEL_HASHES) {
+            ret = snp_launch_update_kernel_hashes(sev_snp, desc->base, hva,
+                                                  desc->len);
         } else {
             ret = snp_launch_update_data(desc->base, hva, desc->len, type);
         }
@@ -1855,6 +1878,18 @@ bool sev_add_kernel_loader_hashes(SevKernelLoaderContext *ctx, Error **errp)
         return false;
     }
 
+    if (sev_snp_enabled()) {
+        /*
+         * SNP: Populate the hashes table in an area that later in
+         * snp_launch_update_kernel_hashes() will be copied to the guest memory
+         * and encrypted.
+         */
+        SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(sev_common);
+        sev_snp_guest->kernel_hashes_offset = area->base & ~TARGET_PAGE_MASK;
+        sev_snp_guest->kernel_hashes_data = g_new0(PaddedSevHashTable, 1);
+        return build_kernel_loader_hashes(sev_snp_guest->kernel_hashes_data, ctx, errp);
+    }
+
     /*
      * Populate the hashes table in the guest's memory at the OVMF-designated
      * area for the SEV hashes table
Signature · 1 line
2.34.1
maintainer
#41 lore raw

Re: [PATCH v4 23/31] i386/sev: Allow measured direct kernel boot on SNP

Quoted 94 lines · Pankaj Gupta

From: Dov Murik <[email protected]>

In SNP, the hashes page designated with a specific metadata entry published in AmdSev OVMF.

Therefore, if the user enabled kernel hashes (for measured direct boot), QEMU should prepare the content of hashes table, and during the processing of the metadata entry it copy the content into the designated page and encrypt it.

Note that in SNP (unlike SEV and SEV-ES) the measurements is done in whole 4KB pages. Therefore QEMU zeros the whole page that includes the hashes table, and fills in the kernel hashes area in that page, and then encrypts the whole page. The rest of the page is reserved for SEV launch secrets which are not usable anyway on SNP.

If the user disabled kernel hashes, QEMU pre-validates the kernel hashes page as a zero page.

---
 include/hw/i386/pc.h |  2 ++
 target/i386/sev.c    | 35 +++++++++++++++++++++++++++++++++++
 2 files changed, 37 insertions(+)
include/hw/i386/pc.h +2 -0
index c653b8eeb2..ca7904ac2c 100644
@@ -172,6 +172,8 @@ typedef enum {
     SEV_DESC_TYPE_SNP_SECRETS,
     /* The section contains address that can be used as a CPUID page */
     SEV_DESC_TYPE_CPUID,
+    /* The section contains the region for kernel hashes for measured direct boot */
+    SEV_DESC_TYPE_SNP_KERNEL_HASHES = 0x10,
 
 } ovmf_sev_metadata_desc_type;
 
target/i386/sev.c +24 -0
index 1b29fdbc9a..1a78e98751 100644
@@ -145,6 +145,9 @@ struct SevSnpGuestState {
 
     struct kvm_sev_snp_launch_start kvm_start_conf;
     struct kvm_sev_snp_launch_finish kvm_finish_conf;
+
+    uint32_t kernel_hashes_offset;
+    PaddedSevHashTable *kernel_hashes_data;
 };
 
 struct SevSnpGuestStateClass {
@@ -1187,6 +1190,23 @@ snp_launch_update_cpuid(uint32_t cpuid_addr, void *hva, uint32_t cpuid_len)
                                   KVM_SEV_SNP_PAGE_TYPE_CPUID);
 }
 
+static int
+snp_launch_update_kernel_hashes(SevSnpGuestState *sev_snp, uint32_t addr,
+                                void *hva, uint32_t len)
+{
+    int type = KVM_SEV_SNP_PAGE_TYPE_ZERO;
+    if (sev_snp->parent_obj.kernel_hashes) {
+        assert(sev_snp->kernel_hashes_data);
+        assert((sev_snp->kernel_hashes_offset +
+                sizeof(*sev_snp->kernel_hashes_data)) <= len);
+        memset(hva, 0, len);
+        memcpy(hva + sev_snp->kernel_hashes_offset, sev_snp->kernel_hashes_data,
+               sizeof(*sev_snp->kernel_hashes_data));
+        type = KVM_SEV_SNP_PAGE_TYPE_NORMAL;
+    }
+    return snp_launch_update_data(addr, hva, len, type);
+}
+
 static int
 snp_metadata_desc_to_page_type(int desc_type)
 {
@@ -1223,6 +1243,9 @@ snp_populate_metadata_pages(SevSnpGuestState *sev_snp,
 
         if (type == KVM_SEV_SNP_PAGE_TYPE_CPUID) {
             ret = snp_launch_update_cpuid(desc->base, hva, desc->len);
+        } else if (desc->type == SEV_DESC_TYPE_SNP_KERNEL_HASHES) {
+            ret = snp_launch_update_kernel_hashes(sev_snp, desc->base, hva,
+                                                  desc->len);
         } else {
             ret = snp_launch_update_data(desc->base, hva, desc->len, type);
         }
@@ -1855,6 +1878,18 @@ bool sev_add_kernel_loader_hashes(SevKernelLoaderContext *ctx, Error **errp)
         return false;
     }
 
+    if (sev_snp_enabled()) {

target/i386/sev.c bool sev_add_kernel_loader_hashes(SevKernelLoaderContext *ctx, Error **errp) · line 1891

Quoted 10 lines
target/i386/sev.c +10 -0
+        /*
+         * SNP: Populate the hashes table in an area that later in
+         * snp_launch_update_kernel_hashes() will be copied to the guest memory
+         * and encrypted.
+         */
+        SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(sev_common);
+        sev_snp_guest->kernel_hashes_offset = area->base & ~TARGET_PAGE_MASK;
+        sev_snp_guest->kernel_hashes_data = g_new0(PaddedSevHashTable, 1);
+        return build_kernel_loader_hashes(sev_snp_guest->kernel_hashes_data, ctx, errp);
+    }

This is effectively a new method:

bool (*build_kernel_loader_hashes)(SevCommonState *sev_common,
SevHashTableDescriptor *area, SevKernelLoaderContext *ctx, Error **errp);

where the four lines above are the implementation for SNP and the code below is the implementation for sev-guest.

Paolo

Quoted 6 lines
target/i386/sev.c +0 -1
     /*
      * Populate the hashes table in the guest's memory at the OVMF-designated
      * area for the SEV hashes table
--

2.34.1

#42 lore raw

PATCH v4 24/31 hw/i386/sev: Add support to encrypt BIOS when SEV-SNP is enabled

In reply to Pankaj Gupta

From: Brijesh Singh <[email protected]>

As with SEV, an SNP guest requires that the BIOS be part of the initial encrypted/measured guest payload. Extend sev_encrypt_flash() to handle the SNP case and plumb through the GPA of the BIOS location since this is needed for SNP.

---
 hw/i386/pc_sysfw.c            | 12 +++++++-----
 hw/i386/x86-common.c          |  2 +-
 include/hw/i386/x86.h         |  2 +-
 target/i386/sev-sysemu-stub.c |  2 +-
 target/i386/sev.c             | 15 +++++++++++----
 target/i386/sev.h             |  2 +-
 6 files changed, 22 insertions(+), 13 deletions(-)
hw/i386/pc_sysfw.c +7 -5
index 048d0919c1..00464afcb4 100644
@@ -148,6 +148,8 @@ static void pc_system_flash_map(PCMachineState *pcms,
     assert(PC_MACHINE_GET_CLASS(pcms)->pci_enabled);
 
     for (i = 0; i < ARRAY_SIZE(pcms->flash); i++) {
+        hwaddr gpa;
+
         system_flash = pcms->flash[i];
         blk = pflash_cfi01_get_blk(system_flash);
         if (!blk) {
@@ -177,11 +179,11 @@ static void pc_system_flash_map(PCMachineState *pcms,
         }
 
         total_size += size;
+        gpa = 0x100000000ULL - total_size; /* where the flash is mapped */
         qdev_prop_set_uint32(DEVICE(system_flash), "num-blocks",
                              size / FLASH_SECTOR_SIZE);
         sysbus_realize_and_unref(SYS_BUS_DEVICE(system_flash), &error_fatal);
-        sysbus_mmio_map(SYS_BUS_DEVICE(system_flash), 0,
-                        0x100000000ULL - total_size);
+        sysbus_mmio_map(SYS_BUS_DEVICE(system_flash), 0, gpa);
 
         if (i == 0) {
             flash_mem = pflash_cfi01_get_memory(system_flash);
@@ -196,7 +198,7 @@ static void pc_system_flash_map(PCMachineState *pcms,
             if (sev_enabled()) {
                 flash_ptr = memory_region_get_ram_ptr(flash_mem);
                 flash_size = memory_region_size(flash_mem);
-                x86_firmware_configure(flash_ptr, flash_size);
+                x86_firmware_configure(gpa, flash_ptr, flash_size);
             }
         }
     }
@@ -249,7 +251,7 @@ void pc_system_firmware_init(PCMachineState *pcms,
     pc_system_flash_cleanup_unused(pcms);
 }
 
-void x86_firmware_configure(void *ptr, int size)
+void x86_firmware_configure(hwaddr gpa, void *ptr, int size)
 {
     int ret;
 
@@ -270,6 +272,6 @@ void x86_firmware_configure(void *ptr, int size)
             exit(1);
         }
 
-        sev_encrypt_flash(ptr, size, &error_fatal);
+        sev_encrypt_flash(gpa, ptr, size, &error_fatal);
     }
 }
hw/i386/x86-common.c +1 -1
index ee9046d9a8..f41cb0a6a8 100644
@@ -1013,7 +1013,7 @@ void x86_bios_rom_init(X86MachineState *x86ms, const char *default_firmware,
          */
         void *ptr = memory_region_get_ram_ptr(&x86ms->bios);
         load_image_size(filename, ptr, bios_size);
-        x86_firmware_configure(ptr, bios_size);
+        x86_firmware_configure(0x100000000ULL - bios_size, ptr, bios_size);
     } else {
         memory_region_set_readonly(&x86ms->bios, !isapc_ram_fw);
         ret = rom_add_file_fixed(bios_name, (uint32_t)(-bios_size), -1);
include/hw/i386/x86.h +1 -1
index b006f16b8d..d43cb3908e 100644
@@ -154,6 +154,6 @@ void ioapic_init_gsi(GSIState *gsi_state, Object *parent);
 DeviceState *ioapic_init_secondary(GSIState *gsi_state);
 
 /* pc_sysfw.c */
-void x86_firmware_configure(void *ptr, int size);
+void x86_firmware_configure(hwaddr gpa, void *ptr, int size);
 
 #endif
target/i386/sev-sysemu-stub.c +1 -1
index 96e1c15cc3..6af643e3a1 100644
@@ -42,7 +42,7 @@ void qmp_sev_inject_launch_secret(const char *packet_header, const char *secret,
     error_setg(errp, "SEV is not available in this QEMU");
 }
 
-int sev_encrypt_flash(uint8_t *ptr, uint64_t len, Error **errp)
+int sev_encrypt_flash(hwaddr gpa, uint8_t *ptr, uint64_t len, Error **errp)
 {
     g_assert_not_reached();
 }
target/i386/sev.c +11 -4
index 1a78e98751..c5c703bc8d 100644
@@ -1522,7 +1522,7 @@ static int sev_snp_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
 }
 
 int
-sev_encrypt_flash(uint8_t *ptr, uint64_t len, Error **errp)
+sev_encrypt_flash(hwaddr gpa, uint8_t *ptr, uint64_t len, Error **errp)
 {
     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
 
@@ -1532,7 +1532,14 @@ sev_encrypt_flash(uint8_t *ptr, uint64_t len, Error **errp)
 
     /* if SEV is in update state then encrypt the data else do nothing */
     if (sev_check_state(sev_common, SEV_STATE_LAUNCH_UPDATE)) {
-        int ret = sev_launch_update_data(SEV_GUEST(sev_common), ptr, len);
+        int ret;
+
+        if (sev_snp_enabled()) {
+            ret = snp_launch_update_data(gpa, ptr, len,
+                                         KVM_SEV_SNP_PAGE_TYPE_NORMAL);
+        } else {
+            ret = sev_launch_update_data(SEV_GUEST(sev_common), ptr, len);
+        }
         if (ret < 0) {
             error_setg(errp, "SEV: Failed to encrypt pflash rom");
             return ret;
@@ -1902,8 +1909,8 @@ bool sev_add_kernel_loader_hashes(SevKernelLoaderContext *ctx, Error **errp)
     }
 
     if (build_kernel_loader_hashes(padded_ht, ctx, errp)) {
-        if (sev_encrypt_flash((uint8_t *)padded_ht, sizeof(*padded_ht),
-                              errp) < 0) {
+        if (sev_encrypt_flash(area->base, (uint8_t *)padded_ht,
+                              sizeof(*padded_ht), errp) < 0) {
             ret = false;
         }
     } else {
target/i386/sev.h +1 -1
index cc12824dd6..858005a119 100644
@@ -59,7 +59,7 @@ uint32_t sev_get_cbit_position(void);
 uint32_t sev_get_reduced_phys_bits(void);
 bool sev_add_kernel_loader_hashes(SevKernelLoaderContext *ctx, Error **errp);
 
-int sev_encrypt_flash(uint8_t *ptr, uint64_t len, Error **errp);
+int sev_encrypt_flash(hwaddr gpa, uint8_t *ptr, uint64_t len, Error **errp);
 int sev_inject_launch_secret(const char *hdr, const char *secret,
                              uint64_t gpa, Error **errp);
 
Signature · 1 line
2.34.1
#43 lore raw

PATCH v4 25/31 i386/sev: Invoke launch_updata_data() for SEV class

In reply to Pankaj Gupta

Add launch_update_data() in SevCommonStateClass and invoke as sev_launch_update_data() for SEV object.

---
 target/i386/sev.c | 15 +++++++--------
 1 file changed, 7 insertions(+), 8 deletions(-)
target/i386/sev.c +7 -8
index c5c703bc8d..7a0c2ee10f 100644
@@ -102,6 +102,7 @@ struct SevCommonStateClass {
     /* public */
     int (*launch_start)(SevCommonState *sev_common);
     void (*launch_finish)(SevCommonState *sev_common);
+    int (*launch_update_data)(hwaddr gpa, uint8_t *ptr, uint64_t len);
     int (*kvm_init)(ConfidentialGuestSupport *cgs, Error **errp);
 };
 
@@ -945,10 +946,11 @@ out:
 }
 
 static int
-sev_launch_update_data(SevGuestState *sev_guest, uint8_t *addr, uint64_t len)
+sev_launch_update_data(hwaddr gpa, uint8_t *addr, uint64_t len)
 {
     int ret, fw_error;
     struct kvm_sev_launch_update_data update;
+    SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
 
     if (!addr || !len) {
         return 1;
@@ -957,7 +959,7 @@ sev_launch_update_data(SevGuestState *sev_guest, uint8_t *addr, uint64_t len)
     update.uaddr = (uintptr_t)addr;
     update.len = len;
     trace_kvm_sev_launch_update_data(addr, len);
-    ret = sev_ioctl(SEV_COMMON(sev_guest)->sev_fd, KVM_SEV_LAUNCH_UPDATE_DATA,
+    ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_UPDATE_DATA,
                     &update, &fw_error);
     if (ret) {
         error_report("%s: LAUNCH_UPDATE ret=%d fw_error=%d '%s'",
@@ -1525,6 +1527,7 @@ int
 sev_encrypt_flash(hwaddr gpa, uint8_t *ptr, uint64_t len, Error **errp)
 {
     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
+    SevCommonStateClass *klass = SEV_COMMON_GET_CLASS(sev_common);
 
     if (!sev_common) {
         return 0;
@@ -1534,12 +1537,7 @@ sev_encrypt_flash(hwaddr gpa, uint8_t *ptr, uint64_t len, Error **errp)
     if (sev_check_state(sev_common, SEV_STATE_LAUNCH_UPDATE)) {
         int ret;
 
-        if (sev_snp_enabled()) {
-            ret = snp_launch_update_data(gpa, ptr, len,
-                                         KVM_SEV_SNP_PAGE_TYPE_NORMAL);
-        } else {
-            ret = sev_launch_update_data(SEV_GUEST(sev_common), ptr, len);
-        }
+        ret = klass->launch_update_data(gpa, ptr, len);
         if (ret < 0) {
             error_setg(errp, "SEV: Failed to encrypt pflash rom");
             return ret;
@@ -2039,6 +2037,7 @@ sev_guest_class_init(ObjectClass *oc, void *data)
 
     klass->launch_start = sev_launch_start;
     klass->launch_finish = sev_launch_finish;
+    klass->launch_update_data = sev_launch_update_data;
     klass->kvm_init = sev_kvm_init;
     x86_klass->kvm_type = sev_kvm_type;
 
Signature · 1 line
2.34.1
maintainer
#44 lore raw

Re: [PATCH v4 25/31] i386/sev: Invoke launch_updata_data() for SEV class

Quoted 14 lines · Pankaj Gupta

Add launch_update_data() in SevCommonStateClass and invoke as sev_launch_update_data() for SEV object.

---
 target/i386/sev.c | 15 +++++++--------
 1 file changed, 7 insertions(+), 8 deletions(-)
target/i386/sev.c +0 -0
index c5c703bc8d..7a0c2ee10f 100644

target/i386/sev.c struct SevCommonStateClass { · line 105

Quoted 4 lines
target/i386/sev.c +1 -0
@@ -102,6 +102,7 @@ struct SevCommonStateClass {
     /* public */
     int (*launch_start)(SevCommonState *sev_common);
     void (*launch_finish)(SevCommonState *sev_common);
+    int (*launch_update_data)(hwaddr gpa, uint8_t *ptr, uint64_t len);

This should receive the SevCommonState, so that sev_launch_update_data() does not have to grab it from the MachineState.

Also,

target/i386/sev.c sev_encrypt_flash(hwaddr gpa, uint8_t *ptr, uint64_t len, Error **errp) · line 1540

Quoted 7 lines
target/i386/sev.c +1 -6
-        if (sev_snp_enabled()) {
-            ret = snp_launch_update_data(gpa, ptr, len,
-                                         KVM_SEV_SNP_PAGE_TYPE_NORMAL);
-        } else {
-            ret = sev_launch_update_data(SEV_GUEST(sev_common), ptr, len);
-        }
+        ret = klass->launch_update_data(gpa, ptr, len);

this patch should be placed earlier in the series, so that this change is done before snp_launch_data() is introduced..

That is, the hunk should be just:

     /* if SEV is in update state then encrypt the data else do nothing */
     if (sev_check_state(sev_common, SEV_STATE_LAUNCH_UPDATE)) {
-        int ret = sev_launch_update_data(SEV_GUEST(sev_common), ptr, len);
+        int ret;
+
+        ret = klass->launch_update_data(SEV_GUEST(sev_common), gpa, ptr, len);
         if (ret < 0) {
             error_setg(errp, "SEV: Failed to encrypt pflash rom");
             return ret;

Paolo

#45 lore raw

PATCH v4 26/31 i386/sev: Invoke launch_updata_data() for SNP class

In reply to Pankaj Gupta

Invoke as sev_snp_launch_update_data() for SNP object.

---
 target/i386/sev.c | 9 +++++++++
 1 file changed, 9 insertions(+)
target/i386/sev.c +9 -0
index 7a0c2ee10f..7d2f67e2f3 100644
@@ -1108,6 +1108,14 @@ snp_launch_update_data(uint64_t gpa, void *hva,
     return 0;
 }
 
+static int
+sev_snp_launch_update_data(hwaddr gpa, uint8_t *ptr, uint64_t len)
+{
+       int ret = snp_launch_update_data(gpa, ptr, len,
+                                         KVM_SEV_SNP_PAGE_TYPE_NORMAL);
+       return ret;
+}
+
 static int
 sev_snp_cpuid_info_fill(SnpCpuidInfo *snp_cpuid_info,
                         const KvmCpuidInfo *kvm_cpuid_info)
@@ -2282,6 +2290,7 @@ sev_snp_guest_class_init(ObjectClass *oc, void *data)
 
     klass->launch_start = sev_snp_launch_start;
     klass->launch_finish = sev_snp_launch_finish;
+    klass->launch_update_data = sev_snp_launch_update_data;
     klass->kvm_init = sev_snp_kvm_init;
     x86_klass->kvm_type = sev_snp_kvm_type;
 
Signature · 1 line
2.34.1
#46 lore raw

PATCH v4 27/31 hw/i386/sev: Use guest_memfd for legacy ROMs

In reply to Pankaj Gupta

From: Michael Roth <[email protected]>

Current SNP guest kernels will attempt to access these regions with with C-bit set, so guest_memfd is needed to handle that. Otherwise, kvm_convert_memory() will fail when the guest kernel tries to access it and QEMU attempts to call KVM_SET_MEMORY_ATTRIBUTES to set these ranges to private.

Whether guests should actually try to access ROM regions in this way (or need to deal with legacy ROM regions at all), is a separate issue to be addressed on kernel side, but current SNP guest kernels will exhibit this behavior and so this handling is needed to allow QEMU to continue running existing SNP guest kernels.

[pankaj: Added sev_snp_enabled() check]
---
 hw/i386/pc.c       | 14 ++++++++++----
 hw/i386/pc_sysfw.c | 13 ++++++++++---
 2 files changed, 20 insertions(+), 7 deletions(-)
hw/i386/pc.c +10 -4
index 7b638da7aa..62c25ea1e9 100644
@@ -62,6 +62,7 @@
 #include "hw/mem/memory-device.h"
 #include "e820_memory_layout.h"
 #include "trace.h"
+#include "sev.h"
 #include CONFIG_DEVICES
 
 #ifdef CONFIG_XEN_EMU
@@ -1022,10 +1023,15 @@ void pc_memory_init(PCMachineState *pcms,
     pc_system_firmware_init(pcms, rom_memory);
 
     option_rom_mr = g_malloc(sizeof(*option_rom_mr));
-    memory_region_init_ram(option_rom_mr, NULL, "pc.rom", PC_ROM_SIZE,
-                           &error_fatal);
-    if (pcmc->pci_enabled) {
-        memory_region_set_readonly(option_rom_mr, true);
+    if (sev_snp_enabled()) {
+        memory_region_init_ram_guest_memfd(option_rom_mr, NULL, "pc.rom",
+                                           PC_ROM_SIZE, &error_fatal);
+    } else {
+        memory_region_init_ram(option_rom_mr, NULL, "pc.rom", PC_ROM_SIZE,
+                               &error_fatal);
+        if (pcmc->pci_enabled) {
+            memory_region_set_readonly(option_rom_mr, true);
+        }
     }
     memory_region_add_subregion_overlap(rom_memory,
                                         PC_ROM_MIN_VGA,
hw/i386/pc_sysfw.c +10 -3
index 00464afcb4..def77a442d 100644
@@ -51,8 +51,13 @@ static void pc_isa_bios_init(MemoryRegion *isa_bios, MemoryRegion *rom_memory,
 
     /* map the last 128KB of the BIOS in ISA space */
     isa_bios_size = MIN(flash_size, 128 * KiB);
-    memory_region_init_ram(isa_bios, NULL, "isa-bios", isa_bios_size,
-                           &error_fatal);
+    if (sev_snp_enabled()) {
+        memory_region_init_ram_guest_memfd(isa_bios, NULL, "isa-bios",
+                                           isa_bios_size, &error_fatal);
+    } else {
+        memory_region_init_ram(isa_bios, NULL, "isa-bios", isa_bios_size,
+                               &error_fatal);
+    }
     memory_region_add_subregion_overlap(rom_memory,
                                         0x100000 - isa_bios_size,
                                         isa_bios,
@@ -65,7 +70,9 @@ static void pc_isa_bios_init(MemoryRegion *isa_bios, MemoryRegion *rom_memory,
            ((uint8_t*)flash_ptr) + (flash_size - isa_bios_size),
            isa_bios_size);
 
-    memory_region_set_readonly(isa_bios, true);
+    if (!machine_require_guest_memfd(current_machine)) {
+        memory_region_set_readonly(isa_bios, true);
+    }
 }
 
 static PFlashCFI01 *pc_pflash_create(PCMachineState *pcms,
Signature · 1 line
2.34.1
maintainer
#47 lore raw

Re: [PATCH v4 27/31] hw/i386/sev: Use guest_memfd for legacy ROMs

Quoted 14 lines · Pankaj Gupta

From: Michael Roth <[email protected]>

Current SNP guest kernels will attempt to access these regions with with C-bit set, so guest_memfd is needed to handle that. Otherwise, kvm_convert_memory() will fail when the guest kernel tries to access it and QEMU attempts to call KVM_SET_MEMORY_ATTRIBUTES to set these ranges to private.

Whether guests should actually try to access ROM regions in this way (or need to deal with legacy ROM regions at all), is a separate issue to be addressed on kernel side, but current SNP guest kernels will exhibit this behavior and so this handling is needed to allow QEMU to continue running existing SNP guest kernels.

[...]

Review void pc_memory_init(PCMachineState *pcms, · line 1026

Quoted 10 lines

#ifdef CONFIG_XEN_EMU

(quoted diff) +1 -4
@@ -1022,10 +1023,15 @@ void pc_memory_init(PCMachineState *pcms,
     pc_system_firmware_init(pcms, rom_memory);
 
     option_rom_mr = g_malloc(sizeof(*option_rom_mr));
-    memory_region_init_ram(option_rom_mr, NULL, "pc.rom", PC_ROM_SIZE,
-                           &error_fatal);
-    if (pcmc->pci_enabled) {
-        memory_region_set_readonly(option_rom_mr, true);
+    if (sev_snp_enabled()) {

Using sev_snp_enabled() here however is pretty ugly...

Fortunately we can fix machine_require_guest_memfd(), which I think is initialized later (?), so that it is usable here too (and the code is cleaner). To do so, just delegate machine_require_guest_memfd() to the ConfidentialGuestSupport object (see patch at
https://patchew.org/QEMU/[email protected]/)
and then initialize the new field in SevSnpGuest's instance_init function:

target/i386/sev.c +3 -0
index 1c5e2e7a1f9..a7574d1c707 100644
@@ -2328,8 +2328,11 @@ sev_snp_guest_class_init(ObjectClass *oc, void *data)
 static void
 sev_snp_guest_instance_init(Object *obj)
 {
+    ConfidentialGuestSupport *cgs = CONFIDENTIAL_GUEST_SUPPORT(obj);
     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
 
+    cgs->require_guest_memfd = true;
+
     /* default init/start/finish params for kvm */
     sev_snp_guest->kvm_start_conf.policy = DEFAULT_SEV_SNP_POLICY;
 }

Paolo

#48 lore raw

Re: [PATCH v4 27/31] hw/i386/sev: Use guest_memfd for legacy ROMs

In reply to Pankaj Gupta
Quoted 75 lines · Pankaj Gupta

From: Michael Roth <[email protected]>

Current SNP guest kernels will attempt to access these regions with with C-bit set, so guest_memfd is needed to handle that. Otherwise, kvm_convert_memory() will fail when the guest kernel tries to access it and QEMU attempts to call KVM_SET_MEMORY_ATTRIBUTES to set these ranges to private.

Whether guests should actually try to access ROM regions in this way (or need to deal with legacy ROM regions at all), is a separate issue to be addressed on kernel side, but current SNP guest kernels will exhibit this behavior and so this handling is needed to allow QEMU to continue running existing SNP guest kernels.

[pankaj: Added sev_snp_enabled() check]
---
  hw/i386/pc.c       | 14 ++++++++++----
  hw/i386/pc_sysfw.c | 13 ++++++++++---
  2 files changed, 20 insertions(+), 7 deletions(-)
hw/i386/pc.c +10 -4
index 7b638da7aa..62c25ea1e9 100644
@@ -62,6 +62,7 @@
  #include "hw/mem/memory-device.h"
  #include "e820_memory_layout.h"
  #include "trace.h"
+#include "sev.h"
  #include CONFIG_DEVICES
 
  #ifdef CONFIG_XEN_EMU
@@ -1022,10 +1023,15 @@ void pc_memory_init(PCMachineState *pcms,
      pc_system_firmware_init(pcms, rom_memory);
 
      option_rom_mr = g_malloc(sizeof(*option_rom_mr));
-    memory_region_init_ram(option_rom_mr, NULL, "pc.rom", PC_ROM_SIZE,
-                           &error_fatal);
-    if (pcmc->pci_enabled) {
-        memory_region_set_readonly(option_rom_mr, true);
+    if (sev_snp_enabled()) {
+        memory_region_init_ram_guest_memfd(option_rom_mr, NULL, "pc.rom",
+                                           PC_ROM_SIZE, &error_fatal);
+    } else {
+        memory_region_init_ram(option_rom_mr, NULL, "pc.rom", PC_ROM_SIZE,
+                               &error_fatal);
+        if (pcmc->pci_enabled) {
+            memory_region_set_readonly(option_rom_mr, true);
+        }
      }
      memory_region_add_subregion_overlap(rom_memory,
                                          PC_ROM_MIN_VGA,
hw/i386/pc_sysfw.c +7 -2
index 00464afcb4..def77a442d 100644
@@ -51,8 +51,13 @@ static void pc_isa_bios_init(MemoryRegion *isa_bios, MemoryRegion *rom_memory,
 
      /* map the last 128KB of the BIOS in ISA space */
      isa_bios_size = MIN(flash_size, 128 * KiB);
-    memory_region_init_ram(isa_bios, NULL, "isa-bios", isa_bios_size,
-                           &error_fatal);
+    if (sev_snp_enabled()) {
+        memory_region_init_ram_guest_memfd(isa_bios, NULL, "isa-bios",
+                                           isa_bios_size, &error_fatal);
+    } else {
+        memory_region_init_ram(isa_bios, NULL, "isa-bios", isa_bios_size,
+                               &error_fatal);
+    }
      memory_region_add_subregion_overlap(rom_memory,
                                          0x100000 - isa_bios_size,
                                          isa_bios,

hw/i386/pc_sysfw.c static void pc_isa_bios_init(MemoryRegion *isa_bios, MemoryRegion *rom_memory, · line 75

Quoted 7 lines
hw/i386/pc_sysfw.c +3 -1
@@ -65,7 +70,9 @@ static void pc_isa_bios_init(MemoryRegion *isa_bios, MemoryRegion *rom_memory,
             ((uint8_t*)flash_ptr) + (flash_size - isa_bios_size),
             isa_bios_size);
 
-    memory_region_set_readonly(isa_bios, true);
+    if (!machine_require_guest_memfd(current_machine)) {
+        memory_region_set_readonly(isa_bios, true);
+    }

This patch takes different approach than next patch that this patch chooses to not set readonly when require guest memfd while next patch skips the whole isa_bios setup for -bios case. Why make different handling for the two cases?

More importantly, with commit a44ea3fa7f2a,
pcmc->isa_bios_alias is default true for all new machine after 9.0, then pc_isa_bios_init() would be hit even on plash case. It will call x86_isa_bios_init() in pc_system_flash_map().

So with -bios case, the call site is

pc_system_firmware_init()

     -> x86_bios_rom_init()
	-> x86_isa_bios_init()

because require_guest_memfd is true for snp, x86_isa_bios_init() is
not called.

However, with pflash case, the call site is

pc_system_firmware_init()

     -> pc_system_flash_map()
	 -> if (pcmc->isa_bios_alias) {
                x86_isa_bios_init();
            } else {
                pc_isa_bios_init();
            }

As I said above, pcmc->isa_bios_alias is true for machine after 9.0, so it will goes x86_isa_bios_init().

So please anyone explain to me why x86_isa_bios_init() is ok for pflash case but not for -bios case?

Quoted 3 lines
hw/i386/pc_sysfw.c +0 -0
  }
 
  static PFlashCFI01 *pc_pflash_create(PCMachineState *pcms,
#49 lore raw

Re: [PATCH v4 27/31] hw/i386/sev: Use guest_memfd for legacy ROMs

Quoted 92 lines · Xiaoyao Li
Quoted 76 lines · Pankaj Gupta

From: Michael Roth <[email protected]>

Current SNP guest kernels will attempt to access these regions with with C-bit set, so guest_memfd is needed to handle that. Otherwise, kvm_convert_memory() will fail when the guest kernel tries to access it and QEMU attempts to call KVM_SET_MEMORY_ATTRIBUTES to set these ranges to private.

Whether guests should actually try to access ROM regions in this way (or need to deal with legacy ROM regions at all), is a separate issue to be addressed on kernel side, but current SNP guest kernels will exhibit this behavior and so this handling is needed to allow QEMU to continue running existing SNP guest kernels.

[pankaj: Added sev_snp_enabled() check]

---
  hw/i386/pc.c       | 14 ++++++++++----
  hw/i386/pc_sysfw.c | 13 ++++++++++---

  2 files changed, 20 insertions(+), 7 deletions(-)
hw/i386/pc.c +10 -4
index 7b638da7aa..62c25ea1e9 100644
@@ -62,6 +62,7 @@
   #include "hw/mem/memory-device.h"
   #include "e820_memory_layout.h"
   #include "trace.h"
+#include "sev.h"
   #include CONFIG_DEVICES
   #ifdef CONFIG_XEN_EMU
@@ -1022,10 +1023,15 @@ void pc_memory_init(PCMachineState *pcms,
       pc_system_firmware_init(pcms, rom_memory);
       option_rom_mr = g_malloc(sizeof(*option_rom_mr));
-    memory_region_init_ram(option_rom_mr, NULL, "pc.rom", PC_ROM_SIZE,
-                           &error_fatal);
-    if (pcmc->pci_enabled) {
-        memory_region_set_readonly(option_rom_mr, true);
+    if (sev_snp_enabled()) {
+        memory_region_init_ram_guest_memfd(option_rom_mr, NULL, 
 "pc.rom",
+                                           PC_ROM_SIZE, &error_fatal);
+    } else {
+        memory_region_init_ram(option_rom_mr, NULL, "pc.rom", 
 PC_ROM_SIZE,
+                               &error_fatal);
+        if (pcmc->pci_enabled) {
+            memory_region_set_readonly(option_rom_mr, true);
+        }
       }
       memory_region_add_subregion_overlap(rom_memory,

                                          PC_ROM_MIN_VGA,

hw/i386/pc_sysfw.c +7 -2
index 00464afcb4..def77a442d 100644
@@ -51,8 +51,13 @@ static void pc_isa_bios_init(MemoryRegion 
 *isa_bios, MemoryRegion *rom_memory,
       /* map the last 128KB of the BIOS in ISA space */
       isa_bios_size = MIN(flash_size, 128 * KiB);
-    memory_region_init_ram(isa_bios, NULL, "isa-bios", isa_bios_size,
-                           &error_fatal);
+    if (sev_snp_enabled()) {
+        memory_region_init_ram_guest_memfd(isa_bios, NULL, "isa-bios",
+                                           isa_bios_size, &error_fatal);
+    } else {
+        memory_region_init_ram(isa_bios, NULL, "isa-bios", 
 isa_bios_size,
+                               &error_fatal);
+    }
       memory_region_add_subregion_overlap(rom_memory,
                                           0x100000 - isa_bios_size,

                                          isa_bios,

hw/i386/pc_sysfw.c static void pc_isa_bios_init(MemoryRegion *isa_bios, · line 75

Quoted 7 lines
hw/i386/pc_sysfw.c +3 -1
@@ -65,7 +70,9 @@ static void pc_isa_bios_init(MemoryRegion *isa_bios, 
 MemoryRegion *rom_memory,
              ((uint8_t*)flash_ptr) + (flash_size - isa_bios_size),
              isa_bios_size);
-    memory_region_set_readonly(isa_bios, true);
+    if (!machine_require_guest_memfd(current_machine)) {
+        memory_region_set_readonly(isa_bios, true);
+    }

This patch takes different approach than next patch that this patch chooses to not set readonly when require guest memfd while next patch skips the whole isa_bios setup for -bios case. Why make different handling for the two cases?

More importantly, with commit a44ea3fa7f2a,
pcmc->isa_bios_alias is default true for all new machine after 9.0, then pc_isa_bios_init() would be hit even on plash case. It will call x86_isa_bios_init() in pc_system_flash_map().

So with -bios case, the call site is

Quoted 8 lines

  pc_system_firmware_init()
     -> x86_bios_rom_init()
    -> x86_isa_bios_init()

  because require_guest_memfd is true for snp, x86_isa_bios_init() is
not called.

However, with pflash case, the call site is

btw, right now we don't support 'pflash' case with SNP. Please see the discussion [1]. So, this seems to be pre-enablement for 'bios' with 'pflash' case, which we proposed in PATCH 29 and could not make it to Upstream (reasons mentioned in the thread). But this does not impact the other functionality.

Thanks,
Pankaj

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

Quoted 16 lines

  pc_system_firmware_init()
     -> pc_system_flash_map()
     -> if (pcmc->isa_bios_alias) {
                x86_isa_bios_init();
            } else {
                pc_isa_bios_init();
            }

As I said above, pcmc->isa_bios_alias is true for machine after 9.0, so it will goes x86_isa_bios_init().

So please anyone explain to me why x86_isa_bios_init() is ok for pflash case but not for -bios case?

Quoted 2 lines
hw/i386/pc_sysfw.c +0 -0
   }
   static PFlashCFI01 *pc_pflash_create(PCMachineState *pcms,
#50 lore raw

PATCH v4 28/31 hw/i386: Add support for loading BIOS using guest_memfd

In reply to Pankaj Gupta

From: Michael Roth <[email protected]>

When guest_memfd is enabled, the BIOS is generally part of the initial encrypted guest image and will be accessed as private guest memory. Add the necessary changes to set up the associated RAM region with a guest_memfd backend to allow for this.

Current support centers around using -bios to load the BIOS data. Support for loading the BIOS via pflash requires additional enablement since those interfaces rely on the use of ROM memory regions which make use of the KVM_MEM_READONLY memslot flag, which is not supported for guest_memfd-backed memslots.

---
 hw/i386/x86-common.c | 22 ++++++++++++++++------
 1 file changed, 16 insertions(+), 6 deletions(-)
hw/i386/x86-common.c +16 -6
index f41cb0a6a8..059de65f36 100644
@@ -999,10 +999,18 @@ void x86_bios_rom_init(X86MachineState *x86ms, const char *default_firmware,
     }
     if (bios_size <= 0 ||
         (bios_size % 65536) != 0) {
-        goto bios_error;
+        if (!machine_require_guest_memfd(MACHINE(x86ms))) {
+                g_warning("%s: Unaligned BIOS size %d", __func__, bios_size);
+                goto bios_error;
+        }
+    }
+    if (machine_require_guest_memfd(MACHINE(x86ms))) {
+        memory_region_init_ram_guest_memfd(&x86ms->bios, NULL, "pc.bios",
+                                           bios_size, &error_fatal);
+    } else {
+        memory_region_init_ram(&x86ms->bios, NULL, "pc.bios",
+                               bios_size, &error_fatal);
     }
-    memory_region_init_ram(&x86ms->bios, NULL, "pc.bios", bios_size,
-                           &error_fatal);
     if (sev_enabled()) {
         /*
          * The concept of a "reset" simply doesn't exist for
@@ -1023,9 +1031,11 @@ void x86_bios_rom_init(X86MachineState *x86ms, const char *default_firmware,
     }
     g_free(filename);
 
-    /* map the last 128KB of the BIOS in ISA space */
-    x86_isa_bios_init(&x86ms->isa_bios, rom_memory, &x86ms->bios,
-                      !isapc_ram_fw);
+    if (!machine_require_guest_memfd(MACHINE(x86ms))) {
+        /* map the last 128KB of the BIOS in ISA space */
+        x86_isa_bios_init(&x86ms->isa_bios, rom_memory, &x86ms->bios,
+                          !isapc_ram_fw);
+    }
 
     /* map all the bios at the top of memory */
     memory_region_add_subregion(rom_memory,
Signature · 1 line
2.34.1
maintainer
#51 lore raw

Re: [PATCH v4 28/31] hw/i386: Add support for loading BIOS using guest_memfd

hw/i386/x86-common.c void x86_bios_rom_init(X86MachineState *x86ms, const char *default_firmware, · line 1005

Quoted 7 lines · Pankaj Gupta
     if (bios_size <= 0 ||
         (bios_size % 65536) != 0) {
hw/i386/x86-common.c +4 -1
-        goto bios_error;
+        if (!machine_require_guest_memfd(MACHINE(x86ms))) {
+                g_warning("%s: Unaligned BIOS size %d", __func__, bios_size);
+                goto bios_error;
+        }

Why is this not needed for SEV-SNP? (The bios_size <= 0 case definitely should be an error).

I'll just drop this change.

Quoted 32 lines
hw/i386/x86-common.c +12 -5
+    }
+    if (machine_require_guest_memfd(MACHINE(x86ms))) {
+        memory_region_init_ram_guest_memfd(&x86ms->bios, NULL, "pc.bios",
+                                           bios_size, &error_fatal);
+    } else {
+        memory_region_init_ram(&x86ms->bios, NULL, "pc.bios",
+                               bios_size, &error_fatal);
     }
-    memory_region_init_ram(&x86ms->bios, NULL, "pc.bios", bios_size,
-                           &error_fatal);
     if (sev_enabled()) {
         /*
          * The concept of a "reset" simply doesn't exist for
@@ -1023,9 +1031,11 @@ void x86_bios_rom_init(X86MachineState *x86ms, const char *default_firmware,
     }
     g_free(filename);
 
-    /* map the last 128KB of the BIOS in ISA space */
-    x86_isa_bios_init(&x86ms->isa_bios, rom_memory, &x86ms->bios,
-                      !isapc_ram_fw);
 
+    if (!machine_require_guest_memfd(MACHINE(x86ms))) {
+        /* map the last 128KB of the BIOS in ISA space */
+        x86_isa_bios_init(&x86ms->isa_bios, rom_memory, &x86ms->bios,
+                          !isapc_ram_fw);
+    }
 
     /* map all the bios at the top of memory */

memory_region_add_subregion(rom_memory,
--
2.34.1

Quoted 64 lines · Pankaj Gupta

From: Michael Roth <[email protected]>

When guest_memfd is enabled, the BIOS is generally part of the initial encrypted guest image and will be accessed as private guest memory. Add the necessary changes to set up the associated RAM region with a guest_memfd backend to allow for this.

Current support centers around using -bios to load the BIOS data. Support for loading the BIOS via pflash requires additional enablement since those interfaces rely on the use of ROM memory regions which make use of the KVM_MEM_READONLY memslot flag, which is not supported for guest_memfd-backed memslots.

---
 hw/i386/x86-common.c | 22 ++++++++++++++++------
 1 file changed, 16 insertions(+), 6 deletions(-)
hw/i386/x86-common.c +16 -7
index f41cb0a6a8..059de65f36 100644
@@ -999,10 +999,18 @@ void x86_bios_rom_init(X86MachineState *x86ms, const char *default_firmware,
     }
     if (bios_size <= 0 ||
         (bios_size % 65536) != 0) {
-        goto bios_error;
+        if (!machine_require_guest_memfd(MACHINE(x86ms))) {
+                g_warning("%s: Unaligned BIOS size %d", __func__, bios_size);
+                goto bios_error;
+        }
+    }
+    if (machine_require_guest_memfd(MACHINE(x86ms))) {
+        memory_region_init_ram_guest_memfd(&x86ms->bios, NULL, "pc.bios",
+                                           bios_size, &error_fatal);
+    } else {
+        memory_region_init_ram(&x86ms->bios, NULL, "pc.bios",
+                               bios_size, &error_fatal);
     }
-    memory_region_init_ram(&x86ms->bios, NULL, "pc.bios", bios_size,
-                           &error_fatal);
     if (sev_enabled()) {
         /*
          * The concept of a "reset" simply doesn't exist for
@@ -1023,9 +1031,11 @@ void x86_bios_rom_init(X86MachineState *x86ms, const char *default_firmware,
     }
     g_free(filename);
 
-    /* map the last 128KB of the BIOS in ISA space */
-    x86_isa_bios_init(&x86ms->isa_bios, rom_memory, &x86ms->bios,
-                      !isapc_ram_fw);
+    if (!machine_require_guest_memfd(MACHINE(x86ms))) {
+        /* map the last 128KB of the BIOS in ISA space */
+        x86_isa_bios_init(&x86ms->isa_bios, rom_memory, &x86ms->bios,
+                          !isapc_ram_fw);
+    }
 
     /* map all the bios at the top of memory */
     memory_region_add_subregion(rom_memory,
--

2.34.1

#52 lore raw

Re: [PATCH v4 28/31] hw/i386: Add support for loading BIOS using guest_memfd

In reply to Pankaj Gupta
Quoted 47 lines · Pankaj Gupta

From: Michael Roth <[email protected]>

When guest_memfd is enabled, the BIOS is generally part of the initial encrypted guest image and will be accessed as private guest memory. Add the necessary changes to set up the associated RAM region with a guest_memfd backend to allow for this.

Current support centers around using -bios to load the BIOS data. Support for loading the BIOS via pflash requires additional enablement since those interfaces rely on the use of ROM memory regions which make use of the KVM_MEM_READONLY memslot flag, which is not supported for guest_memfd-backed memslots.

---
  hw/i386/x86-common.c | 22 ++++++++++++++++------
  1 file changed, 16 insertions(+), 6 deletions(-)
hw/i386/x86-common.c +11 -3
index f41cb0a6a8..059de65f36 100644
@@ -999,10 +999,18 @@ void x86_bios_rom_init(X86MachineState *x86ms, const char *default_firmware,
      }
      if (bios_size <= 0 ||
          (bios_size % 65536) != 0) {
-        goto bios_error;
+        if (!machine_require_guest_memfd(MACHINE(x86ms))) {
+                g_warning("%s: Unaligned BIOS size %d", __func__, bios_size);
+                goto bios_error;
+        }
+    }
+    if (machine_require_guest_memfd(MACHINE(x86ms))) {
+        memory_region_init_ram_guest_memfd(&x86ms->bios, NULL, "pc.bios",
+                                           bios_size, &error_fatal);
+    } else {
+        memory_region_init_ram(&x86ms->bios, NULL, "pc.bios",
+                               bios_size, &error_fatal);
      }
-    memory_region_init_ram(&x86ms->bios, NULL, "pc.bios", bios_size,
-                           &error_fatal);
      if (sev_enabled()) {
          /*
           * The concept of a "reset" simply doesn't exist for
@@ -1023,9 +1031,11 @@ void x86_bios_rom_init(X86MachineState *x86ms, const char *default_firmware,
      }

hw/i386/x86-common.c void x86_bios_rom_init(X86MachineState *x86ms, const char *default_firmware, · line 1038

Quoted 10 lines
hw/i386/x86-common.c +5 -3
      g_free(filename);
 
-    /* map the last 128KB of the BIOS in ISA space */
-    x86_isa_bios_init(&x86ms->isa_bios, rom_memory, &x86ms->bios,
-                      !isapc_ram_fw);
+    if (!machine_require_guest_memfd(MACHINE(x86ms))) {
+        /* map the last 128KB of the BIOS in ISA space */
+        x86_isa_bios_init(&x86ms->isa_bios, rom_memory, &x86ms->bios,
+                          !isapc_ram_fw);
+    }

Could anyone explain to me why above change is related to this patch and why need it?

because inside x86_isa_bios_init(), the alias isa_bios is set to read_only while guest_memfd doesn't support readonly?

Quoted 2 lines
hw/i386/x86-common.c +0 -0
      /* map all the bios at the top of memory */
      memory_region_add_subregion(rom_memory,
#53 lore raw

Re: [PATCH v4 28/31] hw/i386: Add support for loading BIOS using guest_memfd

Quoted 64 lines · Xiaoyao Li
Quoted 50 lines · Pankaj Gupta

From: Michael Roth <[email protected]>

When guest_memfd is enabled, the BIOS is generally part of the initial encrypted guest image and will be accessed as private guest memory. Add the necessary changes to set up the associated RAM region with a guest_memfd backend to allow for this.

Current support centers around using -bios to load the BIOS data. Support for loading the BIOS via pflash requires additional enablement since those interfaces rely on the use of ROM memory regions which make use of the KVM_MEM_READONLY memslot flag, which is not supported for guest_memfd-backed memslots.

---
  hw/i386/x86-common.c | 22 ++++++++++++++++------

  1 file changed, 16 insertions(+), 6 deletions(-)
hw/i386/x86-common.c +0 -0
index f41cb0a6a8..059de65f36 100644
@@ -999,10 +999,18 @@ void x86_bios_rom_init(X86MachineState *x86ms, 
 const char *default_firmware,
       }

      if (bios_size <= 0 ||
          (bios_size % 65536) != 0) {
-        goto bios_error;
+        if (!machine_require_guest_memfd(MACHINE(x86ms))) { +                g_warning("%s: Unaligned BIOS size %d", __func__, bios_size);
+                goto bios_error;
+        }
+    }
+    if (machine_require_guest_memfd(MACHINE(x86ms))) {
+        memory_region_init_ram_guest_memfd(&x86ms->bios, NULL, "pc.bios",
+                                           bios_size, &error_fatal); +    } else {
+        memory_region_init_ram(&x86ms->bios, NULL, "pc.bios", +                               bios_size, &error_fatal); }
-    memory_region_init_ram(&x86ms->bios, NULL, "pc.bios", bios_size, -                           &error_fatal);
      if (sev_enabled()) {
          /*
           * The concept of a "reset" simply doesn't exist for

hw/i386/x86-common.c +0 -0
@@ -1023,9 +1031,11 @@ void x86_bios_rom_init(X86MachineState *x86ms, 
 const char *default_firmware,

hw/i386/x86-common.c void x86_bios_rom_init(X86MachineState *x86ms, · line 1038

Quoted 10 lines
hw/i386/x86-common.c +5 -3
       }
       g_free(filename);
-    /* map the last 128KB of the BIOS in ISA space */
-    x86_isa_bios_init(&x86ms->isa_bios, rom_memory, &x86ms->bios,
-                      !isapc_ram_fw);
+    if (!machine_require_guest_memfd(MACHINE(x86ms))) {
+        /* map the last 128KB of the BIOS in ISA space */
+        x86_isa_bios_init(&x86ms->isa_bios, rom_memory, &x86ms->bios,
+                          !isapc_ram_fw);
+    }

Could anyone explain to me why above change is related to this patch and why need it?

Quoted 1 line

because inside x86_isa_bios_init(), the alias isa_bios is set to read_only while guest_memfd doesn't support readonly?

I could not understand your comment entirely. This condition is for non guest_memfd case? You expect something else?

Thanks,
Pankaj

Quoted 4 lines
Quoted 3 lines
hw/i386/x86-common.c +0 -0
       /* map all the bios at the top of memory */
       memory_region_add_subregion(rom_memory,
#54 lore raw

Re: [PATCH v4 28/31] hw/i386: Add support for loading BIOS using guest_memfd

Quoted 65 lines · Pankaj
Quoted 64 lines · Xiaoyao Li
Quoted 50 lines · Pankaj Gupta

From: Michael Roth <[email protected]>

When guest_memfd is enabled, the BIOS is generally part of the initial encrypted guest image and will be accessed as private guest memory. Add the necessary changes to set up the associated RAM region with a guest_memfd backend to allow for this.

Current support centers around using -bios to load the BIOS data. Support for loading the BIOS via pflash requires additional enablement since those interfaces rely on the use of ROM memory regions which make use of the KVM_MEM_READONLY memslot flag, which is not supported for guest_memfd-backed memslots.

---
  hw/i386/x86-common.c | 22 ++++++++++++++++------

  1 file changed, 16 insertions(+), 6 deletions(-)
hw/i386/x86-common.c +0 -0
index f41cb0a6a8..059de65f36 100644
@@ -999,10 +999,18 @@ void x86_bios_rom_init(X86MachineState *x86ms, 
 const char *default_firmware,
       }

      if (bios_size <= 0 ||
          (bios_size % 65536) != 0) {
-        goto bios_error;
+        if (!machine_require_guest_memfd(MACHINE(x86ms))) { +                g_warning("%s: Unaligned BIOS size %d", __func__, bios_size);
+                goto bios_error;
+        }
+    }
+    if (machine_require_guest_memfd(MACHINE(x86ms))) {
+        memory_region_init_ram_guest_memfd(&x86ms->bios, NULL, "pc.bios",
+                                           bios_size, &error_fatal); +    } else {
+        memory_region_init_ram(&x86ms->bios, NULL, "pc.bios", +                               bios_size, &error_fatal); }
-    memory_region_init_ram(&x86ms->bios, NULL, "pc.bios", bios_size, -                           &error_fatal);
      if (sev_enabled()) {
          /*
           * The concept of a "reset" simply doesn't exist for

hw/i386/x86-common.c +0 -0
@@ -1023,9 +1031,11 @@ void x86_bios_rom_init(X86MachineState *x86ms, 
 const char *default_firmware,

hw/i386/x86-common.c void x86_bios_rom_init(X86MachineState *x86ms, · line 1038

Quoted 10 lines
hw/i386/x86-common.c +5 -3
       }
       g_free(filename);
-    /* map the last 128KB of the BIOS in ISA space */
-    x86_isa_bios_init(&x86ms->isa_bios, rom_memory, &x86ms->bios,
-                      !isapc_ram_fw);
+    if (!machine_require_guest_memfd(MACHINE(x86ms))) {
+        /* map the last 128KB of the BIOS in ISA space */
+        x86_isa_bios_init(&x86ms->isa_bios, rom_memory, &x86ms->bios,
+                          !isapc_ram_fw);
+    }

Could anyone explain to me why above change is related to this patch and why need it?

Quoted 3 lines
Quoted 1 line

because inside x86_isa_bios_init(), the alias isa_bios is set to read_only while guest_memfd doesn't support readonly?

I could not understand your comment entirely. This condition is for non guest_memfd case? You expect something else?

I'm asking why x86_isa_bios_init() cannot be called when machine requires guest memfd.

Please see my comment[1] to previous patch, patch 27, the two patches conflict with each other. The two patches did lack the clarification on the changes it made. sigh...

[1] https://lore.kernel.org/qemu-devel/[email protected]/

Quoted 7 lines

Thanks,
Pankaj

Quoted 4 lines
Quoted 3 lines
hw/i386/x86-common.c +0 -0
       /* map all the bios at the top of memory */
       memory_region_add_subregion(rom_memory,
#55 lore raw

PATCH v4 29/31 hw/i386/sev: Allow use of pflash in conjunction with -bios

In reply to Pankaj Gupta

From: Michael Roth <[email protected]>

SEV-ES and SEV-SNP support OVMF images with non-volatile storage in cases where the storage area is generated as a separate image as part of the OVMF build process.

Currently these are exposed with unit=0 corresponding to the actual BIOS image, and unit=1 corresponding to the storage image. However, pflash images are mapped guest memory using read-only memslots, which are not allowed in conjunction with guest_memfd-backed ranges. This makes that approach unusable for SEV-SNP, where the BIOS range will be encrypted and mapped as private guest_memfd-backed memory. For this reason, SEV-SNP will instead rely on -bios to handle loading the BIOS image.

To allow for pflash to still be used for the storage image, rework the existing logic to remove assumptions that unit=0 contains the BIOS image when SEV-SNP, so that it can instead be used to handle only the storage image.

---
 hw/i386/pc_sysfw.c | 47 +++++++++++++++++++++++++++++-----------------
 1 file changed, 30 insertions(+), 17 deletions(-)
hw/i386/pc_sysfw.c +30 -17
index def77a442d..7f97e62b16 100644
@@ -125,21 +125,10 @@ void pc_system_flash_cleanup_unused(PCMachineState *pcms)
     }
 }
 
-/*
- * Map the pcms->flash[] from 4GiB downward, and realize.
- * Map them in descending order, i.e. pcms->flash[0] at the top,
- * without gaps.
- * Stop at the first pcms->flash[0] lacking a block backend.
- * Set each flash's size from its block backend.  Fatal error if the
- * size isn't a non-zero multiple of 4KiB, or the total size exceeds
- * pcms->max_fw_size.
- *
- * If pcms->flash[0] has a block backend, its memory is passed to
- * pc_isa_bios_init().  Merging several flash devices for isa-bios is
- * not supported.
- */
-static void pc_system_flash_map(PCMachineState *pcms,
-                                MemoryRegion *rom_memory)
+static void pc_system_flash_map_partial(PCMachineState *pcms,
+                                        MemoryRegion *rom_memory,
+                                        hwaddr offset,
+                                        bool storage_only)
 {
     X86MachineState *x86ms = X86_MACHINE(pcms);
     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
@@ -154,6 +143,8 @@ static void pc_system_flash_map(PCMachineState *pcms,
 
     assert(PC_MACHINE_GET_CLASS(pcms)->pci_enabled);
 
+    total_size = offset;
+
     for (i = 0; i < ARRAY_SIZE(pcms->flash); i++) {
         hwaddr gpa;
 
@@ -192,7 +183,7 @@ static void pc_system_flash_map(PCMachineState *pcms,
         sysbus_realize_and_unref(SYS_BUS_DEVICE(system_flash), &error_fatal);
         sysbus_mmio_map(SYS_BUS_DEVICE(system_flash), 0, gpa);
 
-        if (i == 0) {
+        if (i == 0 && !storage_only) {
             flash_mem = pflash_cfi01_get_memory(system_flash);
             if (pcmc->isa_bios_alias) {
                 x86_isa_bios_init(&x86ms->isa_bios, rom_memory, flash_mem,
@@ -211,6 +202,25 @@ static void pc_system_flash_map(PCMachineState *pcms,
     }
 }
 
+/*
+ * Map the pcms->flash[] from 4GiB downward, and realize.
+ * Map them in descending order, i.e. pcms->flash[0] at the top,
+ * without gaps.
+ * Stop at the first pcms->flash[0] lacking a block backend.
+ * Set each flash's size from its block backend.  Fatal error if the
+ * size isn't a non-zero multiple of 4KiB, or the total size exceeds
+ * pcms->max_fw_size.
+ *
+ * If pcms->flash[0] has a block backend, its memory is passed to
+ * pc_isa_bios_init().  Merging several flash devices for isa-bios is
+ * not supported.
+ */
+static void pc_system_flash_map(PCMachineState *pcms,
+                                MemoryRegion *rom_memory)
+{
+    pc_system_flash_map_partial(pcms, rom_memory, 0, false);
+}
+
 void pc_system_firmware_init(PCMachineState *pcms,
                              MemoryRegion *rom_memory)
 {
@@ -238,9 +248,12 @@ void pc_system_firmware_init(PCMachineState *pcms,
         }
     }
 
-    if (!pflash_blk[0]) {
+    if (!pflash_blk[0] || sev_snp_enabled()) {
         /* Machine property pflash0 not set, use ROM mode */
         x86_bios_rom_init(X86_MACHINE(pcms), "bios.bin", rom_memory, false);
+        if (sev_snp_enabled()) {
+            pc_system_flash_map_partial(pcms, rom_memory, 3653632, true);
+        }
     } else {
         if (kvm_enabled() && !kvm_readonly_mem_enabled()) {
             /*
Signature · 1 line
2.34.1
maintainer
#56 lore raw

Re: [PATCH v4 29/31] hw/i386/sev: Allow use of pflash in conjunction with -bios

Quoted 12 lines · Pankaj Gupta
hw/i386/pc_sysfw.c +6 -0
index def77a4429fb24e62748
+static void pc_system_flash_map(PCMachineState *pcms,
+                                MemoryRegion *rom_memory)
+{
+    pc_system_flash_map_partial(pcms, rom_memory, 0, false);
+}
+
 void pc_system_firmware_init(PCMachineState *pcms,
                              MemoryRegion *rom_memory)
 {

hw/i386/pc_sysfw.c void pc_system_firmware_init(PCMachineState *pcms, · line 256

Quoted 10 lines
hw/i386/pc_sysfw.c +4 -1
@@ -238,9 +248,12 @@ void pc_system_firmware_init(PCMachineState *pcms,
         }
     }
 
-    if (!pflash_blk[0]) {
+    if (!pflash_blk[0] || sev_snp_enabled()) {
         /* Machine property pflash0 not set, use ROM mode */
         x86_bios_rom_init(X86_MACHINE(pcms), "bios.bin", rom_memory, false);
+        if (sev_snp_enabled()) {
+            pc_system_flash_map_partial(pcms, rom_memory, 3653632, true);
+        }

This number is a bit too specific. :)

The main issue here is that we want to have both a ROM and a non-executable pflash device.

I think in this case (which should be gated by machine_require_guest_memfd(MACHINE(pcms)), just like in earlier patches), we need to:

1) give an error if pflash_blk[1] is specified, i.e. support only one flash device

2) possibly, give a warning if -bios is _not_ specified.

3) map pflash_blk[0] below the BIOS ROM and expect it to be just the variables

The need to use -bios for code and pflash0 (if desired) for variables also needs to be documented of course.

Some parts of this patch can be salvaged, others are not needed anymore... I'll let you figure it out. :)

Paolo

#57 lore raw

Re: [PATCH v4 29/31] hw/i386/sev: Allow use of pflash in conjunction with -bios

In reply to Pankaj Gupta
Quoted 5 lines · Pankaj Gupta

From: Michael Roth <[email protected]>

SEV-ES and SEV-SNP support OVMF images with non-volatile storage in cases where the storage area is generated as a separate image as part of the OVMF build process.

IIUC, right now all OVMF builds for SEV/-ES/-SNP should be done as so called "stateless" image. ie *without* any separate NVRAM image, because that image will not be covered by the VM boot measurement and thus the NVRAM state is liable to undermine trust of the VM.

Using NVRAM for SNP is theoretically possible in future but would be reliant on SVSM providing a secure encryption mechanism on the storage.

Quoted 9 lines

Currently these are exposed with unit=0 corresponding to the actual BIOS image, and unit=1 corresponding to the storage image. However, pflash images are mapped guest memory using read-only memslots, which are not allowed in conjunction with guest_memfd-backed ranges. This makes that approach unusable for SEV-SNP, where the BIOS range will be encrypted and mapped as private guest_memfd-backed memory. For this reason, SEV-SNP will instead rely on -bios to handle loading the BIOS image.

Quoted 4 lines

To allow for pflash to still be used for the storage image, rework the existing logic to remove assumptions that unit=0 contains the BIOS image when SEV-SNP, so that it can instead be used to handle only the storage image.

Mixing both BIOS and pflash is pretty undesirable, not least because that setup cannot be currently represented by the firmware descriptor format described by docs/interop/firmware.json.

So at the very least this patch is incomplete, as it would need to propose changes to the firmware.json to allow this setup to be expressed.

I really wish we didn't have to introduce this though - is there really no way to make it possible to use pflash for both CODE & VARS with SNP, as is done with traditional VMs, so we don't diverge in setup, needing yet more changes up the mgmt stack ?

Quoted 98 lines
---
 hw/i386/pc_sysfw.c | 47 +++++++++++++++++++++++++++++-----------------
 1 file changed, 30 insertions(+), 17 deletions(-)
hw/i386/pc_sysfw.c +30 -17
index def77a442d..7f97e62b16 100644
@@ -125,21 +125,10 @@ void pc_system_flash_cleanup_unused(PCMachineState *pcms)
     }
 }
 
-/*
- * Map the pcms->flash[] from 4GiB downward, and realize.
- * Map them in descending order, i.e. pcms->flash[0] at the top,
- * without gaps.
- * Stop at the first pcms->flash[0] lacking a block backend.
- * Set each flash's size from its block backend.  Fatal error if the
- * size isn't a non-zero multiple of 4KiB, or the total size exceeds
- * pcms->max_fw_size.
- *
- * If pcms->flash[0] has a block backend, its memory is passed to
- * pc_isa_bios_init().  Merging several flash devices for isa-bios is
- * not supported.
- */
-static void pc_system_flash_map(PCMachineState *pcms,
-                                MemoryRegion *rom_memory)
+static void pc_system_flash_map_partial(PCMachineState *pcms,
+                                        MemoryRegion *rom_memory,
+                                        hwaddr offset,
+                                        bool storage_only)
 {
     X86MachineState *x86ms = X86_MACHINE(pcms);
     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
@@ -154,6 +143,8 @@ static void pc_system_flash_map(PCMachineState *pcms,
 
     assert(PC_MACHINE_GET_CLASS(pcms)->pci_enabled);
 
+    total_size = offset;
+
     for (i = 0; i < ARRAY_SIZE(pcms->flash); i++) {
         hwaddr gpa;
 
@@ -192,7 +183,7 @@ static void pc_system_flash_map(PCMachineState *pcms,
         sysbus_realize_and_unref(SYS_BUS_DEVICE(system_flash), &error_fatal);
         sysbus_mmio_map(SYS_BUS_DEVICE(system_flash), 0, gpa);
 
-        if (i == 0) {
+        if (i == 0 && !storage_only) {
             flash_mem = pflash_cfi01_get_memory(system_flash);
             if (pcmc->isa_bios_alias) {
                 x86_isa_bios_init(&x86ms->isa_bios, rom_memory, flash_mem,
@@ -211,6 +202,25 @@ static void pc_system_flash_map(PCMachineState *pcms,
     }
 }
 
+/*
+ * Map the pcms->flash[] from 4GiB downward, and realize.
+ * Map them in descending order, i.e. pcms->flash[0] at the top,
+ * without gaps.
+ * Stop at the first pcms->flash[0] lacking a block backend.
+ * Set each flash's size from its block backend.  Fatal error if the
+ * size isn't a non-zero multiple of 4KiB, or the total size exceeds
+ * pcms->max_fw_size.
+ *
+ * If pcms->flash[0] has a block backend, its memory is passed to
+ * pc_isa_bios_init().  Merging several flash devices for isa-bios is
+ * not supported.
+ */
+static void pc_system_flash_map(PCMachineState *pcms,
+                                MemoryRegion *rom_memory)
+{
+    pc_system_flash_map_partial(pcms, rom_memory, 0, false);
+}
+
 void pc_system_firmware_init(PCMachineState *pcms,
                              MemoryRegion *rom_memory)
 {
@@ -238,9 +248,12 @@ void pc_system_firmware_init(PCMachineState *pcms,
         }
     }
 
-    if (!pflash_blk[0]) {
+    if (!pflash_blk[0] || sev_snp_enabled()) {
         /* Machine property pflash0 not set, use ROM mode */
         x86_bios_rom_init(X86_MACHINE(pcms), "bios.bin", rom_memory, false);
+        if (sev_snp_enabled()) {
+            pc_system_flash_map_partial(pcms, rom_memory, 3653632, true);
+        }
     } else {
         if (kvm_enabled() && !kvm_readonly_mem_enabled()) {
             /*
Signature · 1 line
2.34.1

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
maintainer
#58 lore raw

Re: [PATCH v4 29/31] hw/i386/sev: Allow use of pflash in conjunction with -bios

Quoted 4 lines · Daniel P. Berrangé

I really wish we didn't have to introduce this though - is there really no way to make it possible to use pflash for both CODE & VARS with SNP, as is done with traditional VMs, so we don't diverge in setup, needing yet more changes up the mgmt stack ?

No, you cannot use pflash for CODE in either SNP or TDX. The hardware does not support it.

One possibility is to only support non-pflash-based variable store. This is not yet in QEMU, but it is how both AWS and Google implemented UEFI variables and I think Gerd was going to work on it for QEMU.

Paolo

#59 lore raw

Re: [PATCH v4 29/31] hw/i386/sev: Allow use of pflash in conjunction with -bios

Quoted 6 lines · Paolo Bonzini
Quoted 4 lines · Daniel P. Berrangé

I really wish we didn't have to introduce this though - is there really no way to make it possible to use pflash for both CODE & VARS with SNP, as is done with traditional VMs, so we don't diverge in setup, needing yet more changes up the mgmt stack ?

Quoted 6 lines

No, you cannot use pflash for CODE in either SNP or TDX. The hardware does not support it.

One possibility is to only support non-pflash-based variable store. This is not yet in QEMU, but it is how both AWS and Google implemented UEFI variables and I think Gerd was going to work on it for QEMU.

Yes, working on and off on it. Progress is slower that I wish it would be due to getting side tracked into other important edk2 things ...

But, yes, the longer-term plan is that edk2 wouldn't manage the variable store itself. It will be either qemu (non-confidential setups), or the svsm (confidential setups).

Where we are going to store svsm state (vtpm, efi vars, ...) is not fully clear yet. pflash is one option, but we are also checking out alternatives like virtio-blk (via virtio-mmio).

take care,
Gerd

#60 lore raw

Re: [PATCH v4 29/31] hw/i386/sev: Allow use of pflash in conjunction with -bios

In reply to Daniel P. Berrangé
Quoted 11 lines · Daniel P. Berrangé
Quoted 5 lines · Pankaj Gupta

From: Michael Roth <[email protected]>

SEV-ES and SEV-SNP support OVMF images with non-volatile storage in cases where the storage area is generated as a separate image as part of the OVMF build process.

IIUC, right now all OVMF builds for SEV/-ES/-SNP should be done as so called "stateless" image. ie *without* any separate NVRAM image, because that image will not be covered by the VM boot measurement and thus the NVRAM state is liable to undermine trust of the VM.

Technically both stateless and stateful are supported for SEV-ES, so this is mainly to provide similar support for SNP. Unfortunately we can't re-use the existing QEMU topology because of the limitations are using read-only ROMs.

But I'm not sure it's something we have a hard requirement for, and even then maybe there are other alternatives to consider that would offer better security.

In any case, I think it makes total sense to decouple this from the series and re-submit this as a separate patchset if we determine that it's truly necessary (and if so, address Paolo's comments, and handle the 64K-alignment thing in the context of that work).

So for now maybe we should plan to drop it from qemu-coco-queue and focus on the stateless builds for the initial code merge.

-Mike

Quoted 138 lines

Using NVRAM for SNP is theoretically possible in future but would be reliant on SVSM providing a secure encryption mechanism on the storage.

Quoted 9 lines

Currently these are exposed with unit=0 corresponding to the actual BIOS image, and unit=1 corresponding to the storage image. However, pflash images are mapped guest memory using read-only memslots, which are not allowed in conjunction with guest_memfd-backed ranges. This makes that approach unusable for SEV-SNP, where the BIOS range will be encrypted and mapped as private guest_memfd-backed memory. For this reason, SEV-SNP will instead rely on -bios to handle loading the BIOS image.

Quoted 4 lines

To allow for pflash to still be used for the storage image, rework the existing logic to remove assumptions that unit=0 contains the BIOS image when SEV-SNP, so that it can instead be used to handle only the storage image.

Mixing both BIOS and pflash is pretty undesirable, not least because that setup cannot be currently represented by the firmware descriptor format described by docs/interop/firmware.json.

So at the very least this patch is incomplete, as it would need to propose changes to the firmware.json to allow this setup to be expressed.

I really wish we didn't have to introduce this though - is there really no way to make it possible to use pflash for both CODE & VARS with SNP, as is done with traditional VMs, so we don't diverge in setup, needing yet more changes up the mgmt stack ?

Quoted 98 lines
---
 hw/i386/pc_sysfw.c | 47 +++++++++++++++++++++++++++++-----------------
 1 file changed, 30 insertions(+), 17 deletions(-)
hw/i386/pc_sysfw.c +30 -17
index def77a442d..7f97e62b16 100644
@@ -125,21 +125,10 @@ void pc_system_flash_cleanup_unused(PCMachineState *pcms)
     }
 }
 
-/*
- * Map the pcms->flash[] from 4GiB downward, and realize.
- * Map them in descending order, i.e. pcms->flash[0] at the top,
- * without gaps.
- * Stop at the first pcms->flash[0] lacking a block backend.
- * Set each flash's size from its block backend.  Fatal error if the
- * size isn't a non-zero multiple of 4KiB, or the total size exceeds
- * pcms->max_fw_size.
- *
- * If pcms->flash[0] has a block backend, its memory is passed to
- * pc_isa_bios_init().  Merging several flash devices for isa-bios is
- * not supported.
- */
-static void pc_system_flash_map(PCMachineState *pcms,
-                                MemoryRegion *rom_memory)
+static void pc_system_flash_map_partial(PCMachineState *pcms,
+                                        MemoryRegion *rom_memory,
+                                        hwaddr offset,
+                                        bool storage_only)
 {
     X86MachineState *x86ms = X86_MACHINE(pcms);
     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
@@ -154,6 +143,8 @@ static void pc_system_flash_map(PCMachineState *pcms,
 
     assert(PC_MACHINE_GET_CLASS(pcms)->pci_enabled);
 
+    total_size = offset;
+
     for (i = 0; i < ARRAY_SIZE(pcms->flash); i++) {
         hwaddr gpa;
 
@@ -192,7 +183,7 @@ static void pc_system_flash_map(PCMachineState *pcms,
         sysbus_realize_and_unref(SYS_BUS_DEVICE(system_flash), &error_fatal);
         sysbus_mmio_map(SYS_BUS_DEVICE(system_flash), 0, gpa);
 
-        if (i == 0) {
+        if (i == 0 && !storage_only) {
             flash_mem = pflash_cfi01_get_memory(system_flash);
             if (pcmc->isa_bios_alias) {
                 x86_isa_bios_init(&x86ms->isa_bios, rom_memory, flash_mem,
@@ -211,6 +202,25 @@ static void pc_system_flash_map(PCMachineState *pcms,
     }
 }
 
+/*
+ * Map the pcms->flash[] from 4GiB downward, and realize.
+ * Map them in descending order, i.e. pcms->flash[0] at the top,
+ * without gaps.
+ * Stop at the first pcms->flash[0] lacking a block backend.
+ * Set each flash's size from its block backend.  Fatal error if the
+ * size isn't a non-zero multiple of 4KiB, or the total size exceeds
+ * pcms->max_fw_size.
+ *
+ * If pcms->flash[0] has a block backend, its memory is passed to
+ * pc_isa_bios_init().  Merging several flash devices for isa-bios is
+ * not supported.
+ */
+static void pc_system_flash_map(PCMachineState *pcms,
+                                MemoryRegion *rom_memory)
+{
+    pc_system_flash_map_partial(pcms, rom_memory, 0, false);
+}
+
 void pc_system_firmware_init(PCMachineState *pcms,
                              MemoryRegion *rom_memory)
 {
@@ -238,9 +248,12 @@ void pc_system_firmware_init(PCMachineState *pcms,
         }
     }
 
-    if (!pflash_blk[0]) {
+    if (!pflash_blk[0] || sev_snp_enabled()) {
         /* Machine property pflash0 not set, use ROM mode */
         x86_bios_rom_init(X86_MACHINE(pcms), "bios.bin", rom_memory, false);
+        if (sev_snp_enabled()) {
+            pc_system_flash_map_partial(pcms, rom_memory, 3653632, true);
+        }
     } else {
         if (kvm_enabled() && !kvm_readonly_mem_enabled()) {
             /*
Signature · 1 line
2.34.1

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
maintainer
#61 lore raw

Re: [PATCH v4 29/31] hw/i386/sev: Allow use of pflash in conjunction with -bios

Quoted 2 lines · Michael Roth

So for now maybe we should plan to drop it from qemu-coco-queue and focus on the stateless builds for the initial code merge.

Yes, I included it in qemu-coco-queue to ensure that other things didn't break split firmware (or they were properly identified), but basically everything else in qemu-coco-queue is ready for merge.

Please double check "i386/sev: Allow measured direct kernel boot on SNP" as well, as I did some reorganization of the code into a new class method for sev-guest and sev-snp-guest objects.

Paolo

#62 lore raw

Re: [PATCH v4 29/31] hw/i386/sev: Allow use of pflash in conjunction with -bios

Quoted 11 lines · Paolo Bonzini
Quoted 2 lines · Michael Roth

So for now maybe we should plan to drop it from qemu-coco-queue and focus on the stateless builds for the initial code merge.

Yes, I included it in qemu-coco-queue to ensure that other things didn't break split firmware (or they were properly identified), but basically everything else in qemu-coco-queue is ready for merge.

Please double check "i386/sev: Allow measured direct kernel boot on SNP" as well, as I did some reorganization of the code into a new class method for sev-guest and sev-snp-guest objects.

The patch changes look sensible to me, and I re-tested the following permutations of split/unsplit OVMF with/without kernel hashing and everything looks good (this is with PATCH 29/31 reverted):

         |split     |split      |unsplit   |unsplit    |
         |hashing=on|hashing=off|hashing=on|hashing=off|
         |----------|-----------|----------|-----------|
  svm    |      n/a |      PASS |      n/a |      PASS |
  sev    |      n/a |      PASS |     PASS |      PASS |
  sev-es |      n/a |      PASS |     PASS |      PASS |
  snp    |      n/a |      n/a  |     PASS |      PASS | 

(split + hashing=on is not possible because hashing requires AmdSevX64 OVMF package which is built unsplit-only by design. split tests done using OvmfPkgX64)

-Mike

Quoted 3 lines

Paolo

#63 lore raw

PATCH v4 30/31 i386/kvm: Add KVM_EXIT_HYPERCALL handling for KVM_HC_MAP_GPA_RANGE

In reply to Pankaj Gupta

From: Michael Roth <[email protected]>

KVM_HC_MAP_GPA_RANGE will be used to send requests to userspace for private/shared memory attribute updates requested by the guest. Implement handling for that use-case along with some basic infrastructure for enabling specific hypercall events.

---
 target/i386/kvm/kvm.c        | 55 ++++++++++++++++++++++++++++++++++++
 target/i386/kvm/kvm_i386.h   |  1 +
 target/i386/kvm/trace-events |  1 +
 3 files changed, 57 insertions(+)
target/i386/kvm/kvm.c +55 -0
index 6c864e4611..e72c295f77 100644
@@ -21,6 +21,7 @@
 #include <sys/syscall.h>
 
 #include <linux/kvm.h>
+#include <linux/kvm_para.h>
 #include "standard-headers/asm-x86/kvm_para.h"
 #include "hw/xen/interface/arch-x86/cpuid.h"
 
@@ -208,6 +209,13 @@ int kvm_get_vm_type(MachineState *ms)
     return kvm_type;
 }
 
+bool kvm_enable_hypercall(uint64_t enable_mask)
+{
+    KVMState *s = KVM_STATE(current_accel());
+
+    return !kvm_vm_enable_cap(s, KVM_CAP_EXIT_HYPERCALL, 0, enable_mask);
+}
+
 bool kvm_has_smm(void)
 {
     return kvm_vm_check_extension(kvm_state, KVM_CAP_X86_SMM);
@@ -5321,6 +5329,50 @@ static bool host_supports_vmx(void)
     return ecx & CPUID_EXT_VMX;
 }
 
+/*
+ * Currently the handling here only supports use of KVM_HC_MAP_GPA_RANGE
+ * to service guest-initiated memory attribute update requests so that
+ * KVM_SET_MEMORY_ATTRIBUTES can update whether or not a page should be
+ * backed by the private memory pool provided by guest_memfd, and as such
+ * is only applicable to guest_memfd-backed guests (e.g. SNP/TDX).
+ *
+ * Other other use-cases for KVM_HC_MAP_GPA_RANGE, such as for SEV live
+ * migration, are not implemented here currently.
+ *
+ * For the guest_memfd use-case, these exits will generally be synthesized
+ * by KVM based on platform-specific hypercalls, like GHCB requests in the
+ * case of SEV-SNP, and not issued directly within the guest though the
+ * KVM_HC_MAP_GPA_RANGE hypercall. So in this case, KVM_HC_MAP_GPA_RANGE is
+ * not actually advertised to guests via the KVM CPUID feature bit, as
+ * opposed to SEV live migration where it would be. Since it is unlikely the
+ * SEV live migration use-case would be useful for guest-memfd backed guests,
+ * because private/shared page tracking is already provided through other
+ * means, these 2 use-cases should be treated as being mutually-exclusive.
+ */
+static int kvm_handle_hc_map_gpa_range(struct kvm_run *run)
+{
+    uint64_t gpa, size, attributes;
+
+    if (!machine_require_guest_memfd(current_machine))
+        return -EINVAL;
+
+    gpa = run->hypercall.args[0];
+    size = run->hypercall.args[1] * TARGET_PAGE_SIZE;
+    attributes = run->hypercall.args[2];
+
+    trace_kvm_hc_map_gpa_range(gpa, size, attributes, run->hypercall.flags);
+
+    return kvm_convert_memory(gpa, size, attributes & KVM_MAP_GPA_RANGE_ENCRYPTED);
+}
+
+static int kvm_handle_hypercall(struct kvm_run *run)
+{
+    if (run->hypercall.nr == KVM_HC_MAP_GPA_RANGE)
+        return kvm_handle_hc_map_gpa_range(run);
+
+    return -EINVAL;
+}
+
 #define VMX_INVALID_GUEST_STATE 0x80000021
 
 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
@@ -5416,6 +5468,9 @@ int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
         ret = kvm_xen_handle_exit(cpu, &run->xen);
         break;
 #endif
+    case KVM_EXIT_HYPERCALL:
+        ret = kvm_handle_hypercall(run);
+        break;
     default:
         fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
         ret = -1;
target/i386/kvm/kvm_i386.h +1 -0
index 6b44844d95..34fc60774b 100644
@@ -33,6 +33,7 @@
 bool kvm_has_smm(void);
 bool kvm_enable_x2apic(void);
 bool kvm_hv_vpindex_settable(void);
+bool kvm_enable_hypercall(uint64_t enable_mask);
 
 bool kvm_enable_sgx_provisioning(KVMState *s);
 bool kvm_hyperv_expand_features(X86CPU *cpu, Error **errp);
target/i386/kvm/trace-events +1 -0
index b365a8e8e2..74a6234ff7 100644
@@ -5,6 +5,7 @@ kvm_x86_fixup_msi_error(uint32_t gsi) "VT-d failed to remap interrupt for GSI %"
 kvm_x86_add_msi_route(int virq) "Adding route entry for virq %d"
 kvm_x86_remove_msi_route(int virq) "Removing route entry for virq %d"
 kvm_x86_update_msi_routes(int num) "Updated %d MSI routes"
+kvm_hc_map_gpa_range(uint64_t gpa, uint64_t size, uint64_t attributes, uint64_t flags) "gpa 0x%" PRIx64 " size 0x%" PRIx64 " attributes 0x%" PRIx64 " flags 0x%" PRIx64
 
 # xen-emu.c
 kvm_xen_hypercall(int cpu, uint8_t cpl, uint64_t input, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t ret) "xen_hypercall: cpu %d cpl %d input %" PRIu64 " a0 0x%" PRIx64 " a1 0x%" PRIx64 " a2 0x%" PRIx64" ret 0x%" PRIx64
Signature · 1 line
2.34.1
#64 lore raw

Re: [PATCH v4 30/31] i386/kvm: Add KVM_EXIT_HYPERCALL handling for KVM_HC_MAP_GPA_RANGE

On 5/30/2024 7:16 PM, Pankaj Gupta wrote:

[...]

Quoted 8 lines

+/*
+ * Currently the handling here only supports use of KVM_HC_MAP_GPA_RANGE
+ * to service guest-initiated memory attribute update requests so that
+ * KVM_SET_MEMORY_ATTRIBUTES can update whether or not a page should be
+ * backed by the private memory pool provided by guest_memfd, and as such
+ * is only applicable to guest_memfd-backed guests (e.g. SNP/TDX).
+ *
+ * Other other use-cases for KVM_HC_MAP_GPA_RANGE, such as for SEV live

           ^
           extra "other"?

Quoted 16 lines

+ * migration, are not implemented here currently.
+ *
+ * For the guest_memfd use-case, these exits will generally be synthesized
+ * by KVM based on platform-specific hypercalls, like GHCB requests in the
+ * case of SEV-SNP, and not issued directly within the guest though the
+ * KVM_HC_MAP_GPA_RANGE hypercall. So in this case, KVM_HC_MAP_GPA_RANGE is
+ * not actually advertised to guests via the KVM CPUID feature bit, as
+ * opposed to SEV live migration where it would be. Since it is unlikely the
+ * SEV live migration use-case would be useful for guest-memfd backed guests,
+ * because private/shared page tracking is already provided through other
+ * means, these 2 use-cases should be treated as being mutually-exclusive.
+ */

target/i386/kvm/kvm.c +4 -0
+static int kvm_handle_hc_map_gpa_range(struct kvm_run *run)
+{
+    uint64_t gpa, size, attributes;
+

target/i386/kvm/kvm.c static bool host_supports_vmx(void) · line 5365

Quoted 10 lines
target/i386/kvm/kvm.c +10 -0
+    if (!machine_require_guest_memfd(current_machine))
+        return -EINVAL;
+
+    gpa = run->hypercall.args[0];
+    size = run->hypercall.args[1] * TARGET_PAGE_SIZE;
+    attributes = run->hypercall.args[2];
+
+    trace_kvm_hc_map_gpa_range(gpa, size, attributes, run->hypercall.flags);
+
+    return kvm_convert_memory(gpa, size, attributes & KVM_MAP_GPA_RANGE_ENCRYPTED);

run->hypercall.ret should be updated accordingly.
At least for successful case.
For failure case, QEMU will shutdown the VM, is it the expected behavior?

Quoted 11 lines
target/i386/kvm/kvm.c +10 -0
+}
+
+static int kvm_handle_hypercall(struct kvm_run *run)
+{
+    if (run->hypercall.nr == KVM_HC_MAP_GPA_RANGE)
+        return kvm_handle_hc_map_gpa_range(run);
+
+    return -EINVAL;
+}
+

[...]

#65 lore raw

PATCH v4 31/31 i386/sev: Enable KVM_HC_MAP_GPA_RANGE hcall for SNP guests

In reply to Pankaj Gupta

From: Michael Roth <[email protected]>

KVM will forward GHCB page-state change requests to userspace in the form of KVM_HC_MAP_GPA_RANGE, so make sure the hypercall handling is enabled for SNP guests.

---
 target/i386/sev.c | 5 +++++
 1 file changed, 5 insertions(+)
target/i386/sev.c +5 -0
index 7d2f67e2f3..c1872ce3a4 100644
@@ -14,6 +14,7 @@
 #include "qemu/osdep.h"
 
 #include <linux/kvm.h>
+#include <linux/kvm_para.h>
 #include <linux/psp-sev.h>
 
 #include <sys/ioctl.h>
@@ -774,6 +775,10 @@ sev_snp_launch_start(SevCommonState *sev_common)
     trace_kvm_sev_snp_launch_start(start->policy,
                                    sev_snp_guest->guest_visible_workarounds);
 
+    if (!kvm_enable_hypercall(BIT_ULL(KVM_HC_MAP_GPA_RANGE))) {
+            return 1;
+    }
+
     rc = sev_ioctl(sev_common->sev_fd, KVM_SEV_SNP_LAUNCH_START,
                    start, &fw_error);
     if (rc < 0) {
Signature · 1 line
2.34.1
maintainer
#66 lore raw
In reply to Pankaj Gupta
Quoted 8 lines · Pankaj Gupta

These patches implement SEV-SNP base support along with CPUID enforcement support for QEMU, and are also available at:

https://github.com/pagupta/qemu/tree/snp_v4

Latest version of kvm changes are posted here [2] and also queued in kvm/next.

Quoted 10 lines

Patch Layout
------------
01-03: 'error_setg' independent fix, kvm/next header sync & patch from
Xiaoyao's TDX v5 patchset.
04-29: Introduction of sev-snp-guest object and various configuration
requirements for SNP. Support for creating a cryptographic "launch" context and populating various OVMF metadata pages, BIOS regions, and vCPU/VMSA pages with the initial encrypted/measured/validated launch data prior to launching the SNP guest.
30-31: Handling for KVM_HC_MAP_GPA_RANGE hypercall for userspace VMEXIT.

These patches are more or less okay, with only a few nits, and I can queue them already:

i386/sev: Replace error_report with error_setg
linux-headers: Update to current kvm/next
i386/sev: Introduce "sev-common" type to encapsulate common SEV state i386/sev: Move sev_launch_update to separate class method i386/sev: Move sev_launch_finish to separate class method i386/sev: Introduce 'sev-snp-guest' object
i386/sev: Add a sev_snp_enabled() helper
i386/sev: Add sev_kvm_init() override for SEV class i386/sev: Add snp_kvm_init() override for SNP class i386/cpu: Set SEV-SNP CPUID bit when SNP enabled
i386/sev: Don't return launch measurements for SEV-SNP guests i386/sev: Add a class method to determine KVM VM type for SNP guests i386/sev: Update query-sev QAPI format to handle SEV-SNP i386/sev: Add the SNP launch start context
i386/sev: Add handling to encrypt/finalize guest launch data i386/sev: Set CPU state to protected once SNP guest payload is finalized hw/i386/sev: Add function to get SEV metadata from OVMF header i386/sev: Add support for populating OVMF metadata pages i386/sev: Add support for SNP CPUID validation
i386/sev: Invoke launch_updata_data() for SEV class i386/sev: Invoke launch_updata_data() for SNP class i386/kvm: Add KVM_EXIT_HYPERCALL handling for KVM_HC_MAP_GPA_RANGE i386/sev: Enable KVM_HC_MAP_GPA_RANGE hcall for SNP guests i386/sev: Extract build_kernel_loader_hashes
i386/sev: Reorder struct declarations
i386/sev: Allow measured direct kernel boot on SNP hw/i386/sev: Add support to encrypt BIOS when SEV-SNP is enabled
memory: Introduce memory_region_init_ram_guest_memfd()

These patches need a small prerequisite that I'll post soon:

hw/i386/sev: Use guest_memfd for legacy ROMs hw/i386: Add support for loading BIOS using guest_memfd

This one definitely requires more work:

hw/i386/sev: Allow use of pflash in conjunction with -bios

Paolo

maintainer
#67 lore raw
Quoted 21 lines · Paolo Bonzini
Quoted 8 lines · Pankaj Gupta

These patches implement SEV-SNP base support along with CPUID enforcement support for QEMU, and are also available at:

https://github.com/pagupta/qemu/tree/snp_v4

Latest version of kvm changes are posted here [2] and also queued in kvm/next.

Quoted 10 lines

Patch Layout
------------
01-03: 'error_setg' independent fix, kvm/next header sync & patch from
Xiaoyao's TDX v5 patchset.
04-29: Introduction of sev-snp-guest object and various configuration
requirements for SNP. Support for creating a cryptographic "launch" context and populating various OVMF metadata pages, BIOS regions, and vCPU/VMSA pages with the initial encrypted/measured/validated launch data prior to launching the SNP guest.
30-31: Handling for KVM_HC_MAP_GPA_RANGE hypercall for userspace VMEXIT.

Quoted 2 lines

These patches are more or less okay, with only a few nits, and I can queue them already:

Hey,

please check if branch qemu-coco-queue of
https://gitlab.com/bonzini/qemu works for you!

I tested it successfully on CentOS 9 Stream with kernel from kvm/next and firmware from edk2-ovmf-20240524-1.fc41.noarch.

Paolo

Quoted 40 lines

i386/sev: Replace error_report with error_setg
linux-headers: Update to current kvm/next
i386/sev: Introduce "sev-common" type to encapsulate common SEV state i386/sev: Move sev_launch_update to separate class method i386/sev: Move sev_launch_finish to separate class method i386/sev: Introduce 'sev-snp-guest' object
i386/sev: Add a sev_snp_enabled() helper
i386/sev: Add sev_kvm_init() override for SEV class i386/sev: Add snp_kvm_init() override for SNP class i386/cpu: Set SEV-SNP CPUID bit when SNP enabled
i386/sev: Don't return launch measurements for SEV-SNP guests i386/sev: Add a class method to determine KVM VM type for SNP guests i386/sev: Update query-sev QAPI format to handle SEV-SNP i386/sev: Add the SNP launch start context
i386/sev: Add handling to encrypt/finalize guest launch data i386/sev: Set CPU state to protected once SNP guest payload is finalized hw/i386/sev: Add function to get SEV metadata from OVMF header i386/sev: Add support for populating OVMF metadata pages i386/sev: Add support for SNP CPUID validation
i386/sev: Invoke launch_updata_data() for SEV class i386/sev: Invoke launch_updata_data() for SNP class i386/kvm: Add KVM_EXIT_HYPERCALL handling for KVM_HC_MAP_GPA_RANGE i386/sev: Enable KVM_HC_MAP_GPA_RANGE hcall for SNP guests i386/sev: Extract build_kernel_loader_hashes
i386/sev: Reorder struct declarations
i386/sev: Allow measured direct kernel boot on SNP hw/i386/sev: Add support to encrypt BIOS when SEV-SNP is enabled
memory: Introduce memory_region_init_ram_guest_memfd()

These patches need a small prerequisite that I'll post soon:

hw/i386/sev: Use guest_memfd for legacy ROMs hw/i386: Add support for loading BIOS using guest_memfd

This one definitely requires more work:

hw/i386/sev: Allow use of pflash in conjunction with -bios

Paolo

#68 lore raw
Quoted 19 lines
Quoted 19 lines
Quoted 18 lines

These patches implement SEV-SNP base support along with CPUID enforcement support for QEMU, and are also available at:

https://github.com/pagupta/qemu/tree/snp_v4

Latest version of kvm changes are posted here [2] and also queued in kvm/next.

Patch Layout
------------
01-03: 'error_setg' independent fix, kvm/next header sync & patch from
Xiaoyao's TDX v5 patchset.
04-29: Introduction of sev-snp-guest object and various configuration
requirements for SNP. Support for creating a cryptographic "launch" context and populating various OVMF metadata pages, BIOS regions, and vCPU/VMSA pages with the initial encrypted/measured/validated launch data prior to launching the SNP guest.
30-31: Handling for KVM_HC_MAP_GPA_RANGE hypercall for userspace VMEXIT.

Quoted 7 lines
Quoted 2 lines

These patches are more or less okay, with only a few nits, and I can queue them already:

Hey,

please check if branch qemu-coco-queue of
https://gitlab.com/bonzini/qemu works for you!

Getting compilation error here: Hope I am looking at correct branch.

softmmu.fa.p/target_i386_kvm_kvm.c.o.d -o libqemu-x86_64-softmmu.fa.p/target_i386_kvm_kvm.c.o -c ../target/i386/kvm/kvm.c ../target/i386/kvm/kvm.c:171:6: error: ‘KVM_X86_SEV_SNP_VM’ undeclared here (not in a function); did you mean ‘KVM_X86_SEV_ES_VM’?

  171 |     [KVM_X86_SEV_SNP_VM] = "SEV-SNP",
      |      ^~~~~~~~~~~~~~~~~~
      |      KVM_X86_SEV_ES_VM

Thanks,
Pankaj

Quoted 47 lines

I tested it successfully on CentOS 9 Stream with kernel from kvm/next and firmware from edk2-ovmf-20240524-1.fc41.noarch.

Paolo

Quoted 40 lines

i386/sev: Replace error_report with error_setg
linux-headers: Update to current kvm/next
i386/sev: Introduce "sev-common" type to encapsulate common SEV state i386/sev: Move sev_launch_update to separate class method i386/sev: Move sev_launch_finish to separate class method i386/sev: Introduce 'sev-snp-guest' object
i386/sev: Add a sev_snp_enabled() helper
i386/sev: Add sev_kvm_init() override for SEV class i386/sev: Add snp_kvm_init() override for SNP class i386/cpu: Set SEV-SNP CPUID bit when SNP enabled
i386/sev: Don't return launch measurements for SEV-SNP guests i386/sev: Add a class method to determine KVM VM type for SNP guests i386/sev: Update query-sev QAPI format to handle SEV-SNP i386/sev: Add the SNP launch start context
i386/sev: Add handling to encrypt/finalize guest launch data i386/sev: Set CPU state to protected once SNP guest payload is finalized hw/i386/sev: Add function to get SEV metadata from OVMF header i386/sev: Add support for populating OVMF metadata pages i386/sev: Add support for SNP CPUID validation
i386/sev: Invoke launch_updata_data() for SEV class i386/sev: Invoke launch_updata_data() for SNP class i386/kvm: Add KVM_EXIT_HYPERCALL handling for KVM_HC_MAP_GPA_RANGE i386/sev: Enable KVM_HC_MAP_GPA_RANGE hcall for SNP guests i386/sev: Extract build_kernel_loader_hashes
i386/sev: Reorder struct declarations
i386/sev: Allow measured direct kernel boot on SNP hw/i386/sev: Add support to encrypt BIOS when SEV-SNP is enabled
memory: Introduce memory_region_init_ram_guest_memfd()

These patches need a small prerequisite that I'll post soon:

hw/i386/sev: Use guest_memfd for legacy ROMs hw/i386: Add support for loading BIOS using guest_memfd

This one definitely requires more work:

hw/i386/sev: Allow use of pflash in conjunction with -bios

Paolo

maintainer
#69 lore raw
Quoted 4 lines · Pankaj
Quoted 2 lines

please check if branch qemu-coco-queue of
https://gitlab.com/bonzini/qemu works for you!

Getting compilation error here: Hope I am looking at correct branch.

Oops, sorry:

target/i386/kvm/kvm.c +1 -1
index 96dc41d355c..ede3ef1225f 100644
@@ -168,7 +168,7 @@ static const char *vm_type_name[] = {
     [KVM_X86_DEFAULT_VM] = "default",
     [KVM_X86_SEV_VM] = "SEV",
     [KVM_X86_SEV_ES_VM] = "SEV-ES",
-    [KVM_X86_SEV_SNP_VM] = "SEV-SNP",
+    [KVM_X86_SNP_VM] = "SEV-SNP",
 };
 
 bool kvm_is_vm_type_supported(int type)

Tested the above builds, and pushed!

Paolo

Quoted 60 lines

softmmu.fa.p/target_i386_kvm_kvm.c.o.d -o libqemu-x86_64-softmmu.fa.p/target_i386_kvm_kvm.c.o -c ../target/i386/kvm/kvm.c
../target/i386/kvm/kvm.c:171:6: error: ‘KVM_X86_SEV_SNP_VM’ undeclared here (not in a function); did you mean ‘KVM_X86_SEV_ES_VM’?

   171 |     [KVM_X86_SEV_SNP_VM] = "SEV-SNP",
       |      ^~~~~~~~~~~~~~~~~~
       |      KVM_X86_SEV_ES_VM

Thanks,
Pankaj

Quoted 47 lines

I tested it successfully on CentOS 9 Stream with kernel from kvm/next and firmware from edk2-ovmf-20240524-1.fc41.noarch.

Paolo

Quoted 40 lines

i386/sev: Replace error_report with error_setg
linux-headers: Update to current kvm/next
i386/sev: Introduce "sev-common" type to encapsulate common SEV state i386/sev: Move sev_launch_update to separate class method i386/sev: Move sev_launch_finish to separate class method i386/sev: Introduce 'sev-snp-guest' object
i386/sev: Add a sev_snp_enabled() helper
i386/sev: Add sev_kvm_init() override for SEV class i386/sev: Add snp_kvm_init() override for SNP class i386/cpu: Set SEV-SNP CPUID bit when SNP enabled
i386/sev: Don't return launch measurements for SEV-SNP guests i386/sev: Add a class method to determine KVM VM type for SNP guests i386/sev: Update query-sev QAPI format to handle SEV-SNP i386/sev: Add the SNP launch start context
i386/sev: Add handling to encrypt/finalize guest launch data i386/sev: Set CPU state to protected once SNP guest payload is finalized hw/i386/sev: Add function to get SEV metadata from OVMF header i386/sev: Add support for populating OVMF metadata pages i386/sev: Add support for SNP CPUID validation
i386/sev: Invoke launch_updata_data() for SEV class i386/sev: Invoke launch_updata_data() for SNP class i386/kvm: Add KVM_EXIT_HYPERCALL handling for KVM_HC_MAP_GPA_RANGE i386/sev: Enable KVM_HC_MAP_GPA_RANGE hcall for SNP guests i386/sev: Extract build_kernel_loader_hashes
i386/sev: Reorder struct declarations
i386/sev: Allow measured direct kernel boot on SNP hw/i386/sev: Add support to encrypt BIOS when SEV-SNP is enabled
memory: Introduce memory_region_init_ram_guest_memfd()

These patches need a small prerequisite that I'll post soon:

hw/i386/sev: Use guest_memfd for legacy ROMs hw/i386: Add support for loading BIOS using guest_memfd

This one definitely requires more work:

hw/i386/sev: Allow use of pflash in conjunction with -bios

Paolo

#70 lore raw

Hi Paolo,

Quoted 21 lines
Quoted 4 lines
Quoted 2 lines

please check if branch qemu-coco-queue of
https://gitlab.com/bonzini/qemu works for you!

Getting compilation error here: Hope I am looking at correct branch.

Oops, sorry:

target/i386/kvm/kvm.c +1 -1
index 96dc41d355c..ede3ef1225f 100644
@@ -168,7 +168,7 @@ static const char *vm_type_name[] = {
      [KVM_X86_DEFAULT_VM] = "default",
      [KVM_X86_SEV_VM] = "SEV",
      [KVM_X86_SEV_ES_VM] = "SEV-ES",
-    [KVM_X86_SEV_SNP_VM] = "SEV-SNP",
+    [KVM_X86_SNP_VM] = "SEV-SNP",
  };
 
  bool kvm_is_vm_type_supported(int type)
Quoted 1 line

Tested the above builds, and pushed!

Thank you for your work! I tested (quick tests) the updated branch and OVMF [1], it works well for single bios option[2] & direct kernel boot [3]. For some reason separate 'pflash' & 'bios' option, facing issue (maybe some other bug in my code, will try to figure it out and get back on this). Also, will check your comment on mailing list on patch [4], maybe they are related.

For now I think we are good with the 'qemu-coco-queue' & single bios binary configuration using 'AmdSevX64'.

[1] https://github.com/mdroth/edk2/commits/apic-mmio-fix1d/

[2] -bios /home/amd/AMDSEV/OVMF_CODE-upstream-20240228-apicfix-1c-AmdSevX64.fd

[3] Direct kernel loading with '-bios /home/amd/AMDSEV/ovmf/OVMF_CODE-apic-mmio-fix1d-AmdSevX64.fd'

[4] "hw/i386/sev: Allow use of pflash in conjunction with -bios"

Thanks,
Pankaj

Quoted 64 lines

Paolo

Quoted 60 lines

softmmu.fa.p/target_i386_kvm_kvm.c.o.d -o libqemu-x86_64-softmmu.fa.p/target_i386_kvm_kvm.c.o -c ../target/i386/kvm/kvm.c
../target/i386/kvm/kvm.c:171:6: error: ‘KVM_X86_SEV_SNP_VM’ undeclared here (not in a function); did you mean ‘KVM_X86_SEV_ES_VM’?

    171 |     [KVM_X86_SEV_SNP_VM] = "SEV-SNP",
        |      ^~~~~~~~~~~~~~~~~~
        |      KVM_X86_SEV_ES_VM

Thanks,
Pankaj

Quoted 47 lines

I tested it successfully on CentOS 9 Stream with kernel from kvm/next and firmware from edk2-ovmf-20240524-1.fc41.noarch.

Paolo

Quoted 40 lines

i386/sev: Replace error_report with error_setg
linux-headers: Update to current kvm/next
i386/sev: Introduce "sev-common" type to encapsulate common SEV state i386/sev: Move sev_launch_update to separate class method i386/sev: Move sev_launch_finish to separate class method i386/sev: Introduce 'sev-snp-guest' object
i386/sev: Add a sev_snp_enabled() helper
i386/sev: Add sev_kvm_init() override for SEV class i386/sev: Add snp_kvm_init() override for SNP class i386/cpu: Set SEV-SNP CPUID bit when SNP enabled
i386/sev: Don't return launch measurements for SEV-SNP guests i386/sev: Add a class method to determine KVM VM type for SNP guests i386/sev: Update query-sev QAPI format to handle SEV-SNP i386/sev: Add the SNP launch start context
i386/sev: Add handling to encrypt/finalize guest launch data i386/sev: Set CPU state to protected once SNP guest payload is finalized hw/i386/sev: Add function to get SEV metadata from OVMF header i386/sev: Add support for populating OVMF metadata pages i386/sev: Add support for SNP CPUID validation
i386/sev: Invoke launch_updata_data() for SEV class i386/sev: Invoke launch_updata_data() for SNP class i386/kvm: Add KVM_EXIT_HYPERCALL handling for KVM_HC_MAP_GPA_RANGE i386/sev: Enable KVM_HC_MAP_GPA_RANGE hcall for SNP guests i386/sev: Extract build_kernel_loader_hashes
i386/sev: Reorder struct declarations
i386/sev: Allow measured direct kernel boot on SNP hw/i386/sev: Add support to encrypt BIOS when SEV-SNP is enabled
memory: Introduce memory_region_init_ram_guest_memfd()

These patches need a small prerequisite that I'll post soon:

hw/i386/sev: Use guest_memfd for legacy ROMs hw/i386: Add support for loading BIOS using guest_memfd

This one definitely requires more work:

hw/i386/sev: Allow use of pflash in conjunction with -bios

Paolo

#71 lore raw
Quoted 21 lines · Pankaj

Hi Paolo,

Quoted 19 lines
Quoted 4 lines
Quoted 2 lines

please check if branch qemu-coco-queue of
https://gitlab.com/bonzini/qemu works for you!

Getting compilation error here: Hope I am looking at correct branch.

Oops, sorry:

target/i386/kvm/kvm.c +1 -1
index 96dc41d355c..ede3ef1225f 100644
@@ -168,7 +168,7 @@ static const char *vm_type_name[] = {
      [KVM_X86_DEFAULT_VM] = "default",
      [KVM_X86_SEV_VM] = "SEV",
      [KVM_X86_SEV_ES_VM] = "SEV-ES",
-    [KVM_X86_SEV_SNP_VM] = "SEV-SNP",
+    [KVM_X86_SNP_VM] = "SEV-SNP",
  };
 
Quoted 8 lines
Quoted 3 lines
target/i386/kvm/kvm.c +0 -0
  bool kvm_is_vm_type_supported(int type)

Tested the above builds, and pushed!

Thank you for your work! I tested (quick tests) the updated branch and OVMF [1], it works well for single bios option[2] & direct kernel boot [3]. For some reason separate 'pflash' & 'bios' option, facing issue (maybe some other bug in my code, will try to figure it out and get back on this). Also,

Paolo mentioned he dropped the this hunk from:

hw/i386: Add support for loading BIOS using guest_memfd

diff --git a/hw/i386/x86.c b/hw/i386/x86.c
index de606369b0..d076b30ccb 100644
--- a/hw/i386/x86.c
+++ b/hw/i386/x86.c
@@ -1147,10 +1147,18 @@ void x86_bios_rom_init(MachineState *ms, const char *default_firmware,

       }
       if (bios_size <= 0 ||
           (bios_size % 65536) != 0) {

- goto bios_error;
+ if (!machine_require_guest_memfd(ms)) {
+ g_warning("%s: Unaligned BIOS size %d", __func__, bios_size);
+ goto bios_error;
+ }

without that, OVMF with split CODE/VARS won't work because the CODE portion is not 64KB aligned.

If I add that back the split builds work for qemu-coco-queue as well.

We need to understand why the 64KB alignment exists in the first place, why it's not necessary for SNP, and then resubmit the above change with proper explanation.

Quoted 2 lines

will check your comment on mailing list on patch [4], maybe they are related.

However, if based on Daniel's comments we decide not to support split CODE/VARS for SNP, then the above change won't be needed. But if we do, then it goes make sense that the above change is grouped with (or submitted as a fix-up for):

hw/i386/sev: Allow use of pflash in conjunction with -bios

and untangled from "hw/i386: Add support for loading BIOS using guest_memfd", since that's the patch where we actually start dealing with non-64K-aligned OVMF CODE images.

-Mike

Quoted 81 lines

For now I think we are good with the 'qemu-coco-queue' & single bios binary configuration using 'AmdSevX64'.

[1] https://github.com/mdroth/edk2/commits/apic-mmio-fix1d/

[2] -bios /home/amd/AMDSEV/OVMF_CODE-upstream-20240228-apicfix-1c-AmdSevX64.fd

[3] Direct kernel loading with '-bios /home/amd/AMDSEV/ovmf/OVMF_CODE-apic-mmio-fix1d-AmdSevX64.fd'

[4] "hw/i386/sev: Allow use of pflash in conjunction with -bios"

Thanks,
Pankaj

Quoted 64 lines

Paolo

Quoted 60 lines

softmmu.fa.p/target_i386_kvm_kvm.c.o.d -o libqemu-x86_64-softmmu.fa.p/target_i386_kvm_kvm.c.o -c ../target/i386/kvm/kvm.c
../target/i386/kvm/kvm.c:171:6: error: ‘KVM_X86_SEV_SNP_VM’ undeclared here (not in a function); did you mean ‘KVM_X86_SEV_ES_VM’?

    171 |     [KVM_X86_SEV_SNP_VM] = "SEV-SNP",
        |      ^~~~~~~~~~~~~~~~~~
        |      KVM_X86_SEV_ES_VM

Thanks,
Pankaj

Quoted 47 lines

I tested it successfully on CentOS 9 Stream with kernel from kvm/next and firmware from edk2-ovmf-20240524-1.fc41.noarch.

Paolo

Quoted 40 lines

i386/sev: Replace error_report with error_setg
linux-headers: Update to current kvm/next
i386/sev: Introduce "sev-common" type to encapsulate common SEV state i386/sev: Move sev_launch_update to separate class method i386/sev: Move sev_launch_finish to separate class method i386/sev: Introduce 'sev-snp-guest' object
i386/sev: Add a sev_snp_enabled() helper
i386/sev: Add sev_kvm_init() override for SEV class i386/sev: Add snp_kvm_init() override for SNP class i386/cpu: Set SEV-SNP CPUID bit when SNP enabled
i386/sev: Don't return launch measurements for SEV-SNP guests i386/sev: Add a class method to determine KVM VM type for SNP guests i386/sev: Update query-sev QAPI format to handle SEV-SNP i386/sev: Add the SNP launch start context
i386/sev: Add handling to encrypt/finalize guest launch data i386/sev: Set CPU state to protected once SNP guest payload is finalized hw/i386/sev: Add function to get SEV metadata from OVMF header i386/sev: Add support for populating OVMF metadata pages i386/sev: Add support for SNP CPUID validation
i386/sev: Invoke launch_updata_data() for SEV class i386/sev: Invoke launch_updata_data() for SNP class i386/kvm: Add KVM_EXIT_HYPERCALL handling for KVM_HC_MAP_GPA_RANGE i386/sev: Enable KVM_HC_MAP_GPA_RANGE hcall for SNP guests i386/sev: Extract build_kernel_loader_hashes
i386/sev: Reorder struct declarations
i386/sev: Allow measured direct kernel boot on SNP hw/i386/sev: Add support to encrypt BIOS when SEV-SNP is enabled
memory: Introduce memory_region_init_ram_guest_memfd()

These patches need a small prerequisite that I'll post soon:

hw/i386/sev: Use guest_memfd for legacy ROMs hw/i386: Add support for loading BIOS using guest_memfd

This one definitely requires more work:

hw/i386/sev: Allow use of pflash in conjunction with -bios

Paolo

maintainer
#72 lore raw
Quoted 18 lines · Michael Roth

Paolo mentioned he dropped the this hunk from:

hw/i386: Add support for loading BIOS using guest_memfd

diff --git a/hw/i386/x86.c b/hw/i386/x86.c
index de606369b0..d076b30ccb 100644
--- a/hw/i386/x86.c
+++ b/hw/i386/x86.c
@@ -1147,10 +1147,18 @@ void x86_bios_rom_init(MachineState *ms, const char *default_firmware,

       }
       if (bios_size <= 0 ||
           (bios_size % 65536) != 0) {

- goto bios_error;
+ if (!machine_require_guest_memfd(ms)) {
+ g_warning("%s: Unaligned BIOS size %d", __func__, bios_size);
+ goto bios_error;
+ }

Quoted 8 lines

without that, OVMF with split CODE/VARS won't work because the CODE portion is not 64KB aligned.

If I add that back the split builds work for qemu-coco-queue as well.

We need to understand why the 64KB alignment exists in the first place, why it's not necessary for SNP, and then resubmit the above change with proper explanation.

I think it was only needed to make sure that people weren't using "unpadded" BIOS (not OVMF) binaries. I think we can delete it altogether, and it can be submitted separately from this series.

Quoted 4 lines

However, if based on Daniel's comments we decide not to support split CODE/VARS for SNP, then the above change won't be needed. But if we do, then it goes make sense that the above change is grouped with (or submitted as a fix-up for):

Yes, I think we want to go for a variable store that is not "right below BIOS". The advantage of something that isn't pflash-based is that it can be used by any code-only firmware binary.

Paolo