xref: /openbmc/qemu/target/i386/sev.c (revision b2580720)
1 /*
2  * QEMU SEV support
3  *
4  * Copyright Advanced Micro Devices 2016-2018
5  *
6  * Author:
7  *      Brijesh Singh <brijesh.singh@amd.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2 or later.
10  * See the COPYING file in the top-level directory.
11  *
12  */
13 
14 #include "qemu/osdep.h"
15 
16 #include <linux/kvm.h>
17 #include <linux/kvm_para.h>
18 #include <linux/psp-sev.h>
19 
20 #include <sys/ioctl.h>
21 
22 #include "qapi/error.h"
23 #include "qom/object_interfaces.h"
24 #include "qemu/base64.h"
25 #include "qemu/module.h"
26 #include "qemu/uuid.h"
27 #include "qemu/error-report.h"
28 #include "crypto/hash.h"
29 #include "sysemu/kvm.h"
30 #include "kvm/kvm_i386.h"
31 #include "sev.h"
32 #include "sysemu/sysemu.h"
33 #include "sysemu/runstate.h"
34 #include "trace.h"
35 #include "migration/blocker.h"
36 #include "qom/object.h"
37 #include "monitor/monitor.h"
38 #include "monitor/hmp-target.h"
39 #include "qapi/qapi-commands-misc-target.h"
40 #include "confidential-guest.h"
41 #include "hw/i386/pc.h"
42 #include "exec/address-spaces.h"
43 #include "qemu/queue.h"
44 
45 OBJECT_DECLARE_TYPE(SevCommonState, SevCommonStateClass, SEV_COMMON)
46 OBJECT_DECLARE_TYPE(SevGuestState, SevCommonStateClass, SEV_GUEST)
47 OBJECT_DECLARE_TYPE(SevSnpGuestState, SevCommonStateClass, SEV_SNP_GUEST)
48 
49 /* hard code sha256 digest size */
50 #define HASH_SIZE 32
51 
52 typedef struct QEMU_PACKED SevHashTableEntry {
53     QemuUUID guid;
54     uint16_t len;
55     uint8_t hash[HASH_SIZE];
56 } SevHashTableEntry;
57 
58 typedef struct QEMU_PACKED SevHashTable {
59     QemuUUID guid;
60     uint16_t len;
61     SevHashTableEntry cmdline;
62     SevHashTableEntry initrd;
63     SevHashTableEntry kernel;
64 } SevHashTable;
65 
66 /*
67  * Data encrypted by sev_encrypt_flash() must be padded to a multiple of
68  * 16 bytes.
69  */
70 typedef struct QEMU_PACKED PaddedSevHashTable {
71     SevHashTable ht;
72     uint8_t padding[ROUND_UP(sizeof(SevHashTable), 16) - sizeof(SevHashTable)];
73 } PaddedSevHashTable;
74 
75 QEMU_BUILD_BUG_ON(sizeof(PaddedSevHashTable) % 16 != 0);
76 
77 #define SEV_INFO_BLOCK_GUID     "00f771de-1a7e-4fcb-890e-68c77e2fb44e"
78 typedef struct __attribute__((__packed__)) SevInfoBlock {
79     /* SEV-ES Reset Vector Address */
80     uint32_t reset_addr;
81 } SevInfoBlock;
82 
83 #define SEV_HASH_TABLE_RV_GUID  "7255371f-3a3b-4b04-927b-1da6efa8d454"
84 typedef struct QEMU_PACKED SevHashTableDescriptor {
85     /* SEV hash table area guest address */
86     uint32_t base;
87     /* SEV hash table area size (in bytes) */
88     uint32_t size;
89 } SevHashTableDescriptor;
90 
91 struct SevCommonState {
92     X86ConfidentialGuest parent_obj;
93 
94     int kvm_type;
95 
96     /* configuration parameters */
97     char *sev_device;
98     uint32_t cbitpos;
99     uint32_t reduced_phys_bits;
100     bool kernel_hashes;
101 
102     /* runtime state */
103     uint8_t api_major;
104     uint8_t api_minor;
105     uint8_t build_id;
106     int sev_fd;
107     SevState state;
108 
109     uint32_t reset_cs;
110     uint32_t reset_ip;
111     bool reset_data_valid;
112 };
113 
114 struct SevCommonStateClass {
115     X86ConfidentialGuestClass parent_class;
116 
117     /* public */
118     bool (*build_kernel_loader_hashes)(SevCommonState *sev_common,
119                                        SevHashTableDescriptor *area,
120                                        SevKernelLoaderContext *ctx,
121                                        Error **errp);
122     int (*launch_start)(SevCommonState *sev_common);
123     void (*launch_finish)(SevCommonState *sev_common);
124     int (*launch_update_data)(SevCommonState *sev_common, hwaddr gpa, uint8_t *ptr, uint64_t len);
125     int (*kvm_init)(ConfidentialGuestSupport *cgs, Error **errp);
126 };
127 
128 /**
129  * SevGuestState:
130  *
131  * The SevGuestState object is used for creating and managing a SEV
132  * guest.
133  *
134  * # $QEMU \
135  *         -object sev-guest,id=sev0 \
136  *         -machine ...,memory-encryption=sev0
137  */
138 struct SevGuestState {
139     SevCommonState parent_obj;
140     gchar *measurement;
141 
142     /* configuration parameters */
143     uint32_t handle;
144     uint32_t policy;
145     char *dh_cert_file;
146     char *session_file;
147     bool legacy_vm_type;
148 };
149 
150 struct SevSnpGuestState {
151     SevCommonState parent_obj;
152 
153     /* configuration parameters */
154     char *guest_visible_workarounds;
155     char *id_block;
156     char *id_auth;
157     char *host_data;
158 
159     struct kvm_sev_snp_launch_start kvm_start_conf;
160     struct kvm_sev_snp_launch_finish kvm_finish_conf;
161 
162     uint32_t kernel_hashes_offset;
163     PaddedSevHashTable *kernel_hashes_data;
164 };
165 
166 #define DEFAULT_GUEST_POLICY    0x1 /* disable debug */
167 #define DEFAULT_SEV_DEVICE      "/dev/sev"
168 #define DEFAULT_SEV_SNP_POLICY  0x30000
169 
170 typedef struct SevLaunchUpdateData {
171     QTAILQ_ENTRY(SevLaunchUpdateData) next;
172     hwaddr gpa;
173     void *hva;
174     uint64_t len;
175     int type;
176 } SevLaunchUpdateData;
177 
178 static QTAILQ_HEAD(, SevLaunchUpdateData) launch_update;
179 
180 static Error *sev_mig_blocker;
181 
182 static const char *const sev_fw_errlist[] = {
183     [SEV_RET_SUCCESS]                = "",
184     [SEV_RET_INVALID_PLATFORM_STATE] = "Platform state is invalid",
185     [SEV_RET_INVALID_GUEST_STATE]    = "Guest state is invalid",
186     [SEV_RET_INAVLID_CONFIG]         = "Platform configuration is invalid",
187     [SEV_RET_INVALID_LEN]            = "Buffer too small",
188     [SEV_RET_ALREADY_OWNED]          = "Platform is already owned",
189     [SEV_RET_INVALID_CERTIFICATE]    = "Certificate is invalid",
190     [SEV_RET_POLICY_FAILURE]         = "Policy is not allowed",
191     [SEV_RET_INACTIVE]               = "Guest is not active",
192     [SEV_RET_INVALID_ADDRESS]        = "Invalid address",
193     [SEV_RET_BAD_SIGNATURE]          = "Bad signature",
194     [SEV_RET_BAD_MEASUREMENT]        = "Bad measurement",
195     [SEV_RET_ASID_OWNED]             = "ASID is already owned",
196     [SEV_RET_INVALID_ASID]           = "Invalid ASID",
197     [SEV_RET_WBINVD_REQUIRED]        = "WBINVD is required",
198     [SEV_RET_DFFLUSH_REQUIRED]       = "DF_FLUSH is required",
199     [SEV_RET_INVALID_GUEST]          = "Guest handle is invalid",
200     [SEV_RET_INVALID_COMMAND]        = "Invalid command",
201     [SEV_RET_ACTIVE]                 = "Guest is active",
202     [SEV_RET_HWSEV_RET_PLATFORM]     = "Hardware error",
203     [SEV_RET_HWSEV_RET_UNSAFE]       = "Hardware unsafe",
204     [SEV_RET_UNSUPPORTED]            = "Feature not supported",
205     [SEV_RET_INVALID_PARAM]          = "Invalid parameter",
206     [SEV_RET_RESOURCE_LIMIT]         = "Required firmware resource depleted",
207     [SEV_RET_SECURE_DATA_INVALID]    = "Part-specific integrity check failure",
208 };
209 
210 #define SEV_FW_MAX_ERROR      ARRAY_SIZE(sev_fw_errlist)
211 
212 /* <linux/kvm.h> doesn't expose this, so re-use the max from kvm.c */
213 #define KVM_MAX_CPUID_ENTRIES 100
214 
215 typedef struct KvmCpuidInfo {
216     struct kvm_cpuid2 cpuid;
217     struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
218 } KvmCpuidInfo;
219 
220 #define SNP_CPUID_FUNCTION_MAXCOUNT 64
221 #define SNP_CPUID_FUNCTION_UNKNOWN 0xFFFFFFFF
222 
223 typedef struct {
224     uint32_t eax_in;
225     uint32_t ecx_in;
226     uint64_t xcr0_in;
227     uint64_t xss_in;
228     uint32_t eax;
229     uint32_t ebx;
230     uint32_t ecx;
231     uint32_t edx;
232     uint64_t reserved;
233 } __attribute__((packed)) SnpCpuidFunc;
234 
235 typedef struct {
236     uint32_t count;
237     uint32_t reserved1;
238     uint64_t reserved2;
239     SnpCpuidFunc entries[SNP_CPUID_FUNCTION_MAXCOUNT];
240 } __attribute__((packed)) SnpCpuidInfo;
241 
242 static int
243 sev_ioctl(int fd, int cmd, void *data, int *error)
244 {
245     int r;
246     struct kvm_sev_cmd input;
247 
248     memset(&input, 0x0, sizeof(input));
249 
250     input.id = cmd;
251     input.sev_fd = fd;
252     input.data = (uintptr_t)data;
253 
254     r = kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_OP, &input);
255 
256     if (error) {
257         *error = input.error;
258     }
259 
260     return r;
261 }
262 
263 static int
264 sev_platform_ioctl(int fd, int cmd, void *data, int *error)
265 {
266     int r;
267     struct sev_issue_cmd arg;
268 
269     arg.cmd = cmd;
270     arg.data = (unsigned long)data;
271     r = ioctl(fd, SEV_ISSUE_CMD, &arg);
272     if (error) {
273         *error = arg.error;
274     }
275 
276     return r;
277 }
278 
279 static const char *
280 fw_error_to_str(int code)
281 {
282     if (code < 0 || code >= SEV_FW_MAX_ERROR) {
283         return "unknown error";
284     }
285 
286     return sev_fw_errlist[code];
287 }
288 
289 static bool
290 sev_check_state(const SevCommonState *sev_common, SevState state)
291 {
292     assert(sev_common);
293     return sev_common->state == state ? true : false;
294 }
295 
296 static void
297 sev_set_guest_state(SevCommonState *sev_common, SevState new_state)
298 {
299     assert(new_state < SEV_STATE__MAX);
300     assert(sev_common);
301 
302     trace_kvm_sev_change_state(SevState_str(sev_common->state),
303                                SevState_str(new_state));
304     sev_common->state = new_state;
305 }
306 
307 static void
308 sev_ram_block_added(RAMBlockNotifier *n, void *host, size_t size,
309                     size_t max_size)
310 {
311     int r;
312     struct kvm_enc_region range;
313     ram_addr_t offset;
314     MemoryRegion *mr;
315 
316     /*
317      * The RAM device presents a memory region that should be treated
318      * as IO region and should not be pinned.
319      */
320     mr = memory_region_from_host(host, &offset);
321     if (mr && memory_region_is_ram_device(mr)) {
322         return;
323     }
324 
325     range.addr = (uintptr_t)host;
326     range.size = max_size;
327 
328     trace_kvm_memcrypt_register_region(host, max_size);
329     r = kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_REG_REGION, &range);
330     if (r) {
331         error_report("%s: failed to register region (%p+%#zx) error '%s'",
332                      __func__, host, max_size, strerror(errno));
333         exit(1);
334     }
335 }
336 
337 static void
338 sev_ram_block_removed(RAMBlockNotifier *n, void *host, size_t size,
339                       size_t max_size)
340 {
341     int r;
342     struct kvm_enc_region range;
343     ram_addr_t offset;
344     MemoryRegion *mr;
345 
346     /*
347      * The RAM device presents a memory region that should be treated
348      * as IO region and should not have been pinned.
349      */
350     mr = memory_region_from_host(host, &offset);
351     if (mr && memory_region_is_ram_device(mr)) {
352         return;
353     }
354 
355     range.addr = (uintptr_t)host;
356     range.size = max_size;
357 
358     trace_kvm_memcrypt_unregister_region(host, max_size);
359     r = kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_UNREG_REGION, &range);
360     if (r) {
361         error_report("%s: failed to unregister region (%p+%#zx)",
362                      __func__, host, max_size);
363     }
364 }
365 
366 static struct RAMBlockNotifier sev_ram_notifier = {
367     .ram_block_added = sev_ram_block_added,
368     .ram_block_removed = sev_ram_block_removed,
369 };
370 
371 bool
372 sev_enabled(void)
373 {
374     ConfidentialGuestSupport *cgs = MACHINE(qdev_get_machine())->cgs;
375 
376     return !!object_dynamic_cast(OBJECT(cgs), TYPE_SEV_COMMON);
377 }
378 
379 bool
380 sev_snp_enabled(void)
381 {
382     ConfidentialGuestSupport *cgs = MACHINE(qdev_get_machine())->cgs;
383 
384     return !!object_dynamic_cast(OBJECT(cgs), TYPE_SEV_SNP_GUEST);
385 }
386 
387 bool
388 sev_es_enabled(void)
389 {
390     ConfidentialGuestSupport *cgs = MACHINE(qdev_get_machine())->cgs;
391 
392     return sev_snp_enabled() ||
393             (sev_enabled() && SEV_GUEST(cgs)->policy & SEV_POLICY_ES);
394 }
395 
396 uint32_t
397 sev_get_cbit_position(void)
398 {
399     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
400 
401     return sev_common ? sev_common->cbitpos : 0;
402 }
403 
404 uint32_t
405 sev_get_reduced_phys_bits(void)
406 {
407     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
408 
409     return sev_common ? sev_common->reduced_phys_bits : 0;
410 }
411 
412 static SevInfo *sev_get_info(void)
413 {
414     SevInfo *info;
415     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
416 
417     info = g_new0(SevInfo, 1);
418     info->enabled = sev_enabled();
419 
420     if (info->enabled) {
421         info->api_major = sev_common->api_major;
422         info->api_minor = sev_common->api_minor;
423         info->build_id = sev_common->build_id;
424         info->state = sev_common->state;
425 
426         if (sev_snp_enabled()) {
427             info->sev_type = SEV_GUEST_TYPE_SEV_SNP;
428             info->u.sev_snp.snp_policy =
429                 object_property_get_uint(OBJECT(sev_common), "policy", NULL);
430         } else {
431             info->sev_type = SEV_GUEST_TYPE_SEV;
432             info->u.sev.handle = SEV_GUEST(sev_common)->handle;
433             info->u.sev.policy =
434                 (uint32_t)object_property_get_uint(OBJECT(sev_common),
435                                                    "policy", NULL);
436         }
437     }
438 
439     return info;
440 }
441 
442 SevInfo *qmp_query_sev(Error **errp)
443 {
444     SevInfo *info;
445 
446     info = sev_get_info();
447     if (!info) {
448         error_setg(errp, "SEV feature is not available");
449         return NULL;
450     }
451 
452     return info;
453 }
454 
455 void hmp_info_sev(Monitor *mon, const QDict *qdict)
456 {
457     SevInfo *info = sev_get_info();
458 
459     if (!info || !info->enabled) {
460         monitor_printf(mon, "SEV is not enabled\n");
461         goto out;
462     }
463 
464     monitor_printf(mon, "SEV type: %s\n", SevGuestType_str(info->sev_type));
465     monitor_printf(mon, "state: %s\n", SevState_str(info->state));
466     monitor_printf(mon, "build: %d\n", info->build_id);
467     monitor_printf(mon, "api version: %d.%d\n", info->api_major,
468                    info->api_minor);
469 
470     if (sev_snp_enabled()) {
471         monitor_printf(mon, "debug: %s\n",
472                        info->u.sev_snp.snp_policy & SEV_SNP_POLICY_DBG ? "on"
473                                                                        : "off");
474         monitor_printf(mon, "SMT allowed: %s\n",
475                        info->u.sev_snp.snp_policy & SEV_SNP_POLICY_SMT ? "on"
476                                                                        : "off");
477     } else {
478         monitor_printf(mon, "handle: %d\n", info->u.sev.handle);
479         monitor_printf(mon, "debug: %s\n",
480                        info->u.sev.policy & SEV_POLICY_NODBG ? "off" : "on");
481         monitor_printf(mon, "key-sharing: %s\n",
482                        info->u.sev.policy & SEV_POLICY_NOKS ? "off" : "on");
483     }
484 
485 out:
486     qapi_free_SevInfo(info);
487 }
488 
489 static int
490 sev_get_pdh_info(int fd, guchar **pdh, size_t *pdh_len, guchar **cert_chain,
491                  size_t *cert_chain_len, Error **errp)
492 {
493     guchar *pdh_data = NULL;
494     guchar *cert_chain_data = NULL;
495     struct sev_user_data_pdh_cert_export export = {};
496     int err, r;
497 
498     /* query the certificate length */
499     r = sev_platform_ioctl(fd, SEV_PDH_CERT_EXPORT, &export, &err);
500     if (r < 0) {
501         if (err != SEV_RET_INVALID_LEN) {
502             error_setg(errp, "SEV: Failed to export PDH cert"
503                              " ret=%d fw_err=%d (%s)",
504                        r, err, fw_error_to_str(err));
505             return 1;
506         }
507     }
508 
509     pdh_data = g_new(guchar, export.pdh_cert_len);
510     cert_chain_data = g_new(guchar, export.cert_chain_len);
511     export.pdh_cert_address = (unsigned long)pdh_data;
512     export.cert_chain_address = (unsigned long)cert_chain_data;
513 
514     r = sev_platform_ioctl(fd, SEV_PDH_CERT_EXPORT, &export, &err);
515     if (r < 0) {
516         error_setg(errp, "SEV: Failed to export PDH cert ret=%d fw_err=%d (%s)",
517                    r, err, fw_error_to_str(err));
518         goto e_free;
519     }
520 
521     *pdh = pdh_data;
522     *pdh_len = export.pdh_cert_len;
523     *cert_chain = cert_chain_data;
524     *cert_chain_len = export.cert_chain_len;
525     return 0;
526 
527 e_free:
528     g_free(pdh_data);
529     g_free(cert_chain_data);
530     return 1;
531 }
532 
533 static int sev_get_cpu0_id(int fd, guchar **id, size_t *id_len, Error **errp)
534 {
535     guchar *id_data;
536     struct sev_user_data_get_id2 get_id2 = {};
537     int err, r;
538 
539     /* query the ID length */
540     r = sev_platform_ioctl(fd, SEV_GET_ID2, &get_id2, &err);
541     if (r < 0 && err != SEV_RET_INVALID_LEN) {
542         error_setg(errp, "SEV: Failed to get ID ret=%d fw_err=%d (%s)",
543                    r, err, fw_error_to_str(err));
544         return 1;
545     }
546 
547     id_data = g_new(guchar, get_id2.length);
548     get_id2.address = (unsigned long)id_data;
549 
550     r = sev_platform_ioctl(fd, SEV_GET_ID2, &get_id2, &err);
551     if (r < 0) {
552         error_setg(errp, "SEV: Failed to get ID ret=%d fw_err=%d (%s)",
553                    r, err, fw_error_to_str(err));
554         goto err;
555     }
556 
557     *id = id_data;
558     *id_len = get_id2.length;
559     return 0;
560 
561 err:
562     g_free(id_data);
563     return 1;
564 }
565 
566 static SevCapability *sev_get_capabilities(Error **errp)
567 {
568     SevCapability *cap = NULL;
569     guchar *pdh_data = NULL;
570     guchar *cert_chain_data = NULL;
571     guchar *cpu0_id_data = NULL;
572     size_t pdh_len = 0, cert_chain_len = 0, cpu0_id_len = 0;
573     uint32_t ebx;
574     int fd;
575     SevCommonState *sev_common;
576     char *sev_device;
577 
578     if (!kvm_enabled()) {
579         error_setg(errp, "KVM not enabled");
580         return NULL;
581     }
582     if (kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_OP, NULL) < 0) {
583         error_setg(errp, "SEV is not enabled in KVM");
584         return NULL;
585     }
586 
587     sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
588     if (!sev_common) {
589         error_setg(errp, "SEV is not configured");
590         return NULL;
591     }
592 
593     sev_device = object_property_get_str(OBJECT(sev_common), "sev-device",
594                                          &error_abort);
595     fd = open(sev_device, O_RDWR);
596     if (fd < 0) {
597         error_setg_errno(errp, errno, "SEV: Failed to open %s",
598                          DEFAULT_SEV_DEVICE);
599         g_free(sev_device);
600         return NULL;
601     }
602     g_free(sev_device);
603 
604     if (sev_get_pdh_info(fd, &pdh_data, &pdh_len,
605                          &cert_chain_data, &cert_chain_len, errp)) {
606         goto out;
607     }
608 
609     if (sev_get_cpu0_id(fd, &cpu0_id_data, &cpu0_id_len, errp)) {
610         goto out;
611     }
612 
613     cap = g_new0(SevCapability, 1);
614     cap->pdh = g_base64_encode(pdh_data, pdh_len);
615     cap->cert_chain = g_base64_encode(cert_chain_data, cert_chain_len);
616     cap->cpu0_id = g_base64_encode(cpu0_id_data, cpu0_id_len);
617 
618     host_cpuid(0x8000001F, 0, NULL, &ebx, NULL, NULL);
619     cap->cbitpos = ebx & 0x3f;
620 
621     /*
622      * When SEV feature is enabled, we loose one bit in guest physical
623      * addressing.
624      */
625     cap->reduced_phys_bits = 1;
626 
627 out:
628     g_free(cpu0_id_data);
629     g_free(pdh_data);
630     g_free(cert_chain_data);
631     close(fd);
632     return cap;
633 }
634 
635 SevCapability *qmp_query_sev_capabilities(Error **errp)
636 {
637     return sev_get_capabilities(errp);
638 }
639 
640 static OvmfSevMetadata *ovmf_sev_metadata_table;
641 
642 #define OVMF_SEV_META_DATA_GUID "dc886566-984a-4798-A75e-5585a7bf67cc"
643 typedef struct __attribute__((__packed__)) OvmfSevMetadataOffset {
644     uint32_t offset;
645 } OvmfSevMetadataOffset;
646 
647 OvmfSevMetadata *pc_system_get_ovmf_sev_metadata_ptr(void)
648 {
649     return ovmf_sev_metadata_table;
650 }
651 
652 void pc_system_parse_sev_metadata(uint8_t *flash_ptr, size_t flash_size)
653 {
654     OvmfSevMetadata     *metadata;
655     OvmfSevMetadataOffset  *data;
656 
657     if (!pc_system_ovmf_table_find(OVMF_SEV_META_DATA_GUID, (uint8_t **)&data,
658                                    NULL)) {
659         return;
660     }
661 
662     metadata = (OvmfSevMetadata *)(flash_ptr + flash_size - data->offset);
663     if (memcmp(metadata->signature, "ASEV", 4) != 0 ||
664         metadata->len < sizeof(OvmfSevMetadata) ||
665         metadata->len > flash_size - data->offset) {
666         return;
667     }
668 
669     ovmf_sev_metadata_table = g_memdup2(metadata, metadata->len);
670 }
671 
672 static SevAttestationReport *sev_get_attestation_report(const char *mnonce,
673                                                         Error **errp)
674 {
675     struct kvm_sev_attestation_report input = {};
676     SevAttestationReport *report = NULL;
677     SevCommonState *sev_common;
678     g_autofree guchar *data = NULL;
679     g_autofree guchar *buf = NULL;
680     gsize len;
681     int err = 0, ret;
682 
683     if (!sev_enabled()) {
684         error_setg(errp, "SEV is not enabled");
685         return NULL;
686     }
687 
688     /* lets decode the mnonce string */
689     buf = g_base64_decode(mnonce, &len);
690     if (!buf) {
691         error_setg(errp, "SEV: failed to decode mnonce input");
692         return NULL;
693     }
694 
695     /* verify the input mnonce length */
696     if (len != sizeof(input.mnonce)) {
697         error_setg(errp, "SEV: mnonce must be %zu bytes (got %" G_GSIZE_FORMAT ")",
698                 sizeof(input.mnonce), len);
699         return NULL;
700     }
701 
702     sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
703 
704     /* Query the report length */
705     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_GET_ATTESTATION_REPORT,
706             &input, &err);
707     if (ret < 0) {
708         if (err != SEV_RET_INVALID_LEN) {
709             error_setg(errp, "SEV: Failed to query the attestation report"
710                              " length ret=%d fw_err=%d (%s)",
711                        ret, err, fw_error_to_str(err));
712             return NULL;
713         }
714     }
715 
716     data = g_malloc(input.len);
717     input.uaddr = (unsigned long)data;
718     memcpy(input.mnonce, buf, sizeof(input.mnonce));
719 
720     /* Query the report */
721     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_GET_ATTESTATION_REPORT,
722             &input, &err);
723     if (ret) {
724         error_setg_errno(errp, errno, "SEV: Failed to get attestation report"
725                 " ret=%d fw_err=%d (%s)", ret, err, fw_error_to_str(err));
726         return NULL;
727     }
728 
729     report = g_new0(SevAttestationReport, 1);
730     report->data = g_base64_encode(data, input.len);
731 
732     trace_kvm_sev_attestation_report(mnonce, report->data);
733 
734     return report;
735 }
736 
737 SevAttestationReport *qmp_query_sev_attestation_report(const char *mnonce,
738                                                        Error **errp)
739 {
740     return sev_get_attestation_report(mnonce, errp);
741 }
742 
743 static int
744 sev_read_file_base64(const char *filename, guchar **data, gsize *len)
745 {
746     gsize sz;
747     g_autofree gchar *base64 = NULL;
748     GError *error = NULL;
749 
750     if (!g_file_get_contents(filename, &base64, &sz, &error)) {
751         error_report("SEV: Failed to read '%s' (%s)", filename, error->message);
752         g_error_free(error);
753         return -1;
754     }
755 
756     *data = g_base64_decode(base64, len);
757     return 0;
758 }
759 
760 static int
761 sev_snp_launch_start(SevCommonState *sev_common)
762 {
763     int fw_error, rc;
764     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(sev_common);
765     struct kvm_sev_snp_launch_start *start = &sev_snp_guest->kvm_start_conf;
766 
767     trace_kvm_sev_snp_launch_start(start->policy,
768                                    sev_snp_guest->guest_visible_workarounds);
769 
770     if (!kvm_enable_hypercall(BIT_ULL(KVM_HC_MAP_GPA_RANGE))) {
771             return 1;
772     }
773 
774     rc = sev_ioctl(sev_common->sev_fd, KVM_SEV_SNP_LAUNCH_START,
775                    start, &fw_error);
776     if (rc < 0) {
777         error_report("%s: SNP_LAUNCH_START ret=%d fw_error=%d '%s'",
778                 __func__, rc, fw_error, fw_error_to_str(fw_error));
779         return 1;
780     }
781 
782     QTAILQ_INIT(&launch_update);
783 
784     sev_set_guest_state(sev_common, SEV_STATE_LAUNCH_UPDATE);
785 
786     return 0;
787 }
788 
789 static int
790 sev_launch_start(SevCommonState *sev_common)
791 {
792     gsize sz;
793     int ret = 1;
794     int fw_error, rc;
795     SevGuestState *sev_guest = SEV_GUEST(sev_common);
796     struct kvm_sev_launch_start start = {
797         .handle = sev_guest->handle, .policy = sev_guest->policy
798     };
799     guchar *session = NULL, *dh_cert = NULL;
800 
801     if (sev_guest->session_file) {
802         if (sev_read_file_base64(sev_guest->session_file, &session, &sz) < 0) {
803             goto out;
804         }
805         start.session_uaddr = (unsigned long)session;
806         start.session_len = sz;
807     }
808 
809     if (sev_guest->dh_cert_file) {
810         if (sev_read_file_base64(sev_guest->dh_cert_file, &dh_cert, &sz) < 0) {
811             goto out;
812         }
813         start.dh_uaddr = (unsigned long)dh_cert;
814         start.dh_len = sz;
815     }
816 
817     trace_kvm_sev_launch_start(start.policy, session, dh_cert);
818     rc = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_START, &start, &fw_error);
819     if (rc < 0) {
820         error_report("%s: LAUNCH_START ret=%d fw_error=%d '%s'",
821                 __func__, ret, fw_error, fw_error_to_str(fw_error));
822         goto out;
823     }
824 
825     sev_set_guest_state(sev_common, SEV_STATE_LAUNCH_UPDATE);
826     sev_guest->handle = start.handle;
827     ret = 0;
828 
829 out:
830     g_free(session);
831     g_free(dh_cert);
832     return ret;
833 }
834 
835 static void
836 sev_snp_cpuid_report_mismatches(SnpCpuidInfo *old,
837                                 SnpCpuidInfo *new)
838 {
839     size_t i;
840 
841     if (old->count != new->count) {
842         error_report("SEV-SNP: CPUID validation failed due to count mismatch,"
843                      "provided: %d, expected: %d", old->count, new->count);
844         return;
845     }
846 
847     for (i = 0; i < old->count; i++) {
848         SnpCpuidFunc *old_func, *new_func;
849 
850         old_func = &old->entries[i];
851         new_func = &new->entries[i];
852 
853         if (memcmp(old_func, new_func, sizeof(SnpCpuidFunc))) {
854             error_report("SEV-SNP: CPUID validation failed for function 0x%x, index: 0x%x"
855                          "provided: eax:0x%08x, ebx: 0x%08x, ecx: 0x%08x, edx: 0x%08x"
856                          "expected: eax:0x%08x, ebx: 0x%08x, ecx: 0x%08x, edx: 0x%08x",
857                          old_func->eax_in, old_func->ecx_in,
858                          old_func->eax, old_func->ebx, old_func->ecx, old_func->edx,
859                          new_func->eax, new_func->ebx, new_func->ecx, new_func->edx);
860         }
861     }
862 }
863 
864 static const char *
865 snp_page_type_to_str(int type)
866 {
867     switch (type) {
868     case KVM_SEV_SNP_PAGE_TYPE_NORMAL: return "Normal";
869     case KVM_SEV_SNP_PAGE_TYPE_ZERO: return "Zero";
870     case KVM_SEV_SNP_PAGE_TYPE_UNMEASURED: return "Unmeasured";
871     case KVM_SEV_SNP_PAGE_TYPE_SECRETS: return "Secrets";
872     case KVM_SEV_SNP_PAGE_TYPE_CPUID: return "Cpuid";
873     default: return "unknown";
874     }
875 }
876 
877 static int
878 sev_snp_launch_update(SevSnpGuestState *sev_snp_guest,
879                       SevLaunchUpdateData *data)
880 {
881     int ret, fw_error;
882     SnpCpuidInfo snp_cpuid_info;
883     struct kvm_sev_snp_launch_update update = {0};
884 
885     if (!data->hva || !data->len) {
886         error_report("SNP_LAUNCH_UPDATE called with invalid address"
887                      "/ length: %p / %lx",
888                      data->hva, data->len);
889         return 1;
890     }
891 
892     if (data->type == KVM_SEV_SNP_PAGE_TYPE_CPUID) {
893         /* Save a copy for comparison in case the LAUNCH_UPDATE fails */
894         memcpy(&snp_cpuid_info, data->hva, sizeof(snp_cpuid_info));
895     }
896 
897     update.uaddr = (__u64)(unsigned long)data->hva;
898     update.gfn_start = data->gpa >> TARGET_PAGE_BITS;
899     update.len = data->len;
900     update.type = data->type;
901 
902     /*
903      * KVM_SEV_SNP_LAUNCH_UPDATE requires that GPA ranges have the private
904      * memory attribute set in advance.
905      */
906     ret = kvm_set_memory_attributes_private(data->gpa, data->len);
907     if (ret) {
908         error_report("SEV-SNP: failed to configure initial"
909                      "private guest memory");
910         goto out;
911     }
912 
913     while (update.len || ret == -EAGAIN) {
914         trace_kvm_sev_snp_launch_update(update.uaddr, update.gfn_start <<
915                                         TARGET_PAGE_BITS, update.len,
916                                         snp_page_type_to_str(update.type));
917 
918         ret = sev_ioctl(SEV_COMMON(sev_snp_guest)->sev_fd,
919                         KVM_SEV_SNP_LAUNCH_UPDATE,
920                         &update, &fw_error);
921         if (ret && ret != -EAGAIN) {
922             error_report("SNP_LAUNCH_UPDATE ret=%d fw_error=%d '%s'",
923                          ret, fw_error, fw_error_to_str(fw_error));
924 
925             if (data->type == KVM_SEV_SNP_PAGE_TYPE_CPUID) {
926                 sev_snp_cpuid_report_mismatches(&snp_cpuid_info, data->hva);
927                 error_report("SEV-SNP: failed update CPUID page");
928             }
929             break;
930         }
931     }
932 
933 out:
934     if (!ret && update.gfn_start << TARGET_PAGE_BITS != data->gpa + data->len) {
935         error_report("SEV-SNP: expected update of GPA range %lx-%lx,"
936                      "got GPA range %lx-%llx",
937                      data->gpa, data->gpa + data->len, data->gpa,
938                      update.gfn_start << TARGET_PAGE_BITS);
939         ret = -EIO;
940     }
941 
942     return ret;
943 }
944 
945 static int
946 sev_launch_update_data(SevCommonState *sev_common, hwaddr gpa, uint8_t *addr, uint64_t len)
947 {
948     int ret, fw_error;
949     struct kvm_sev_launch_update_data update;
950 
951     if (!addr || !len) {
952         return 1;
953     }
954 
955     update.uaddr = (uintptr_t)addr;
956     update.len = len;
957     trace_kvm_sev_launch_update_data(addr, len);
958     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_UPDATE_DATA,
959                     &update, &fw_error);
960     if (ret) {
961         error_report("%s: LAUNCH_UPDATE ret=%d fw_error=%d '%s'",
962                 __func__, ret, fw_error, fw_error_to_str(fw_error));
963     }
964 
965     return ret;
966 }
967 
968 static int
969 sev_launch_update_vmsa(SevGuestState *sev_guest)
970 {
971     int ret, fw_error;
972 
973     ret = sev_ioctl(SEV_COMMON(sev_guest)->sev_fd, KVM_SEV_LAUNCH_UPDATE_VMSA,
974                     NULL, &fw_error);
975     if (ret) {
976         error_report("%s: LAUNCH_UPDATE_VMSA ret=%d fw_error=%d '%s'",
977                 __func__, ret, fw_error, fw_error_to_str(fw_error));
978     }
979 
980     return ret;
981 }
982 
983 static void
984 sev_launch_get_measure(Notifier *notifier, void *unused)
985 {
986     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
987     SevGuestState *sev_guest = SEV_GUEST(sev_common);
988     int ret, error;
989     g_autofree guchar *data = NULL;
990     struct kvm_sev_launch_measure measurement = {};
991 
992     if (!sev_check_state(sev_common, SEV_STATE_LAUNCH_UPDATE)) {
993         return;
994     }
995 
996     if (sev_es_enabled()) {
997         /* measure all the VM save areas before getting launch_measure */
998         ret = sev_launch_update_vmsa(sev_guest);
999         if (ret) {
1000             exit(1);
1001         }
1002         kvm_mark_guest_state_protected();
1003     }
1004 
1005     /* query the measurement blob length */
1006     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_MEASURE,
1007                     &measurement, &error);
1008     if (!measurement.len) {
1009         error_report("%s: LAUNCH_MEASURE ret=%d fw_error=%d '%s'",
1010                      __func__, ret, error, fw_error_to_str(errno));
1011         return;
1012     }
1013 
1014     data = g_new0(guchar, measurement.len);
1015     measurement.uaddr = (unsigned long)data;
1016 
1017     /* get the measurement blob */
1018     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_MEASURE,
1019                     &measurement, &error);
1020     if (ret) {
1021         error_report("%s: LAUNCH_MEASURE ret=%d fw_error=%d '%s'",
1022                      __func__, ret, error, fw_error_to_str(errno));
1023         return;
1024     }
1025 
1026     sev_set_guest_state(sev_common, SEV_STATE_LAUNCH_SECRET);
1027 
1028     /* encode the measurement value and emit the event */
1029     sev_guest->measurement = g_base64_encode(data, measurement.len);
1030     trace_kvm_sev_launch_measurement(sev_guest->measurement);
1031 }
1032 
1033 static char *sev_get_launch_measurement(void)
1034 {
1035     ConfidentialGuestSupport *cgs = MACHINE(qdev_get_machine())->cgs;
1036     SevGuestState *sev_guest =
1037         (SevGuestState *)object_dynamic_cast(OBJECT(cgs), TYPE_SEV_GUEST);
1038 
1039     if (sev_guest &&
1040         SEV_COMMON(sev_guest)->state >= SEV_STATE_LAUNCH_SECRET) {
1041         return g_strdup(sev_guest->measurement);
1042     }
1043 
1044     return NULL;
1045 }
1046 
1047 SevLaunchMeasureInfo *qmp_query_sev_launch_measure(Error **errp)
1048 {
1049     char *data;
1050     SevLaunchMeasureInfo *info;
1051 
1052     data = sev_get_launch_measurement();
1053     if (!data) {
1054         error_setg(errp, "SEV launch measurement is not available");
1055         return NULL;
1056     }
1057 
1058     info = g_malloc0(sizeof(*info));
1059     info->data = data;
1060 
1061     return info;
1062 }
1063 
1064 static Notifier sev_machine_done_notify = {
1065     .notify = sev_launch_get_measure,
1066 };
1067 
1068 static void
1069 sev_launch_finish(SevCommonState *sev_common)
1070 {
1071     int ret, error;
1072 
1073     trace_kvm_sev_launch_finish();
1074     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_FINISH, 0,
1075                     &error);
1076     if (ret) {
1077         error_report("%s: LAUNCH_FINISH ret=%d fw_error=%d '%s'",
1078                      __func__, ret, error, fw_error_to_str(error));
1079         exit(1);
1080     }
1081 
1082     sev_set_guest_state(sev_common, SEV_STATE_RUNNING);
1083 
1084     /* add migration blocker */
1085     error_setg(&sev_mig_blocker,
1086                "SEV: Migration is not implemented");
1087     migrate_add_blocker(&sev_mig_blocker, &error_fatal);
1088 }
1089 
1090 static int
1091 snp_launch_update_data(uint64_t gpa, void *hva,
1092                        uint32_t len, int type)
1093 {
1094     SevLaunchUpdateData *data;
1095 
1096     data = g_new0(SevLaunchUpdateData, 1);
1097     data->gpa = gpa;
1098     data->hva = hva;
1099     data->len = len;
1100     data->type = type;
1101 
1102     QTAILQ_INSERT_TAIL(&launch_update, data, next);
1103 
1104     return 0;
1105 }
1106 
1107 static int
1108 sev_snp_launch_update_data(SevCommonState *sev_common, hwaddr gpa,
1109                            uint8_t *ptr, uint64_t len)
1110 {
1111        int ret = snp_launch_update_data(gpa, ptr, len,
1112                                          KVM_SEV_SNP_PAGE_TYPE_NORMAL);
1113        return ret;
1114 }
1115 
1116 static int
1117 sev_snp_cpuid_info_fill(SnpCpuidInfo *snp_cpuid_info,
1118                         const KvmCpuidInfo *kvm_cpuid_info)
1119 {
1120     size_t i;
1121 
1122     if (kvm_cpuid_info->cpuid.nent > SNP_CPUID_FUNCTION_MAXCOUNT) {
1123         error_report("SEV-SNP: CPUID entry count (%d) exceeds max (%d)",
1124                      kvm_cpuid_info->cpuid.nent, SNP_CPUID_FUNCTION_MAXCOUNT);
1125         return -1;
1126     }
1127 
1128     memset(snp_cpuid_info, 0, sizeof(*snp_cpuid_info));
1129 
1130     for (i = 0; i < kvm_cpuid_info->cpuid.nent; i++) {
1131         const struct kvm_cpuid_entry2 *kvm_cpuid_entry;
1132         SnpCpuidFunc *snp_cpuid_entry;
1133 
1134         kvm_cpuid_entry = &kvm_cpuid_info->entries[i];
1135         snp_cpuid_entry = &snp_cpuid_info->entries[i];
1136 
1137         snp_cpuid_entry->eax_in = kvm_cpuid_entry->function;
1138         if (kvm_cpuid_entry->flags == KVM_CPUID_FLAG_SIGNIFCANT_INDEX) {
1139             snp_cpuid_entry->ecx_in = kvm_cpuid_entry->index;
1140         }
1141         snp_cpuid_entry->eax = kvm_cpuid_entry->eax;
1142         snp_cpuid_entry->ebx = kvm_cpuid_entry->ebx;
1143         snp_cpuid_entry->ecx = kvm_cpuid_entry->ecx;
1144         snp_cpuid_entry->edx = kvm_cpuid_entry->edx;
1145 
1146         /*
1147          * Guest kernels will calculate EBX themselves using the 0xD
1148          * subfunctions corresponding to the individual XSAVE areas, so only
1149          * encode the base XSAVE size in the initial leaves, corresponding
1150          * to the initial XCR0=1 state.
1151          */
1152         if (snp_cpuid_entry->eax_in == 0xD &&
1153             (snp_cpuid_entry->ecx_in == 0x0 || snp_cpuid_entry->ecx_in == 0x1)) {
1154             snp_cpuid_entry->ebx = 0x240;
1155             snp_cpuid_entry->xcr0_in = 1;
1156             snp_cpuid_entry->xss_in = 0;
1157         }
1158     }
1159 
1160     snp_cpuid_info->count = i;
1161 
1162     return 0;
1163 }
1164 
1165 static int
1166 snp_launch_update_cpuid(uint32_t cpuid_addr, void *hva, uint32_t cpuid_len)
1167 {
1168     KvmCpuidInfo kvm_cpuid_info = {0};
1169     SnpCpuidInfo snp_cpuid_info;
1170     CPUState *cs = first_cpu;
1171     int ret;
1172     uint32_t i = 0;
1173 
1174     assert(sizeof(snp_cpuid_info) <= cpuid_len);
1175 
1176     /* get the cpuid list from KVM */
1177     do {
1178         kvm_cpuid_info.cpuid.nent = ++i;
1179         ret = kvm_vcpu_ioctl(cs, KVM_GET_CPUID2, &kvm_cpuid_info);
1180     } while (ret == -E2BIG);
1181 
1182     if (ret) {
1183         error_report("SEV-SNP: unable to query CPUID values for CPU: '%s'",
1184                      strerror(-ret));
1185         return 1;
1186     }
1187 
1188     ret = sev_snp_cpuid_info_fill(&snp_cpuid_info, &kvm_cpuid_info);
1189     if (ret) {
1190         error_report("SEV-SNP: failed to generate CPUID table information");
1191         return 1;
1192     }
1193 
1194     memcpy(hva, &snp_cpuid_info, sizeof(snp_cpuid_info));
1195 
1196     return snp_launch_update_data(cpuid_addr, hva, cpuid_len,
1197                                   KVM_SEV_SNP_PAGE_TYPE_CPUID);
1198 }
1199 
1200 static int
1201 snp_launch_update_kernel_hashes(SevSnpGuestState *sev_snp, uint32_t addr,
1202                                 void *hva, uint32_t len)
1203 {
1204     int type = KVM_SEV_SNP_PAGE_TYPE_ZERO;
1205     if (sev_snp->parent_obj.kernel_hashes) {
1206         assert(sev_snp->kernel_hashes_data);
1207         assert((sev_snp->kernel_hashes_offset +
1208                 sizeof(*sev_snp->kernel_hashes_data)) <= len);
1209         memset(hva, 0, len);
1210         memcpy(hva + sev_snp->kernel_hashes_offset, sev_snp->kernel_hashes_data,
1211                sizeof(*sev_snp->kernel_hashes_data));
1212         type = KVM_SEV_SNP_PAGE_TYPE_NORMAL;
1213     }
1214     return snp_launch_update_data(addr, hva, len, type);
1215 }
1216 
1217 static int
1218 snp_metadata_desc_to_page_type(int desc_type)
1219 {
1220     switch (desc_type) {
1221     /* Add the umeasured prevalidated pages as a zero page */
1222     case SEV_DESC_TYPE_SNP_SEC_MEM: return KVM_SEV_SNP_PAGE_TYPE_ZERO;
1223     case SEV_DESC_TYPE_SNP_SECRETS: return KVM_SEV_SNP_PAGE_TYPE_SECRETS;
1224     case SEV_DESC_TYPE_CPUID: return KVM_SEV_SNP_PAGE_TYPE_CPUID;
1225     default:
1226          return KVM_SEV_SNP_PAGE_TYPE_ZERO;
1227     }
1228 }
1229 
1230 static void
1231 snp_populate_metadata_pages(SevSnpGuestState *sev_snp,
1232                             OvmfSevMetadata *metadata)
1233 {
1234     OvmfSevMetadataDesc *desc;
1235     int type, ret, i;
1236     void *hva;
1237     MemoryRegion *mr = NULL;
1238 
1239     for (i = 0; i < metadata->num_desc; i++) {
1240         desc = &metadata->descs[i];
1241 
1242         type = snp_metadata_desc_to_page_type(desc->type);
1243 
1244         hva = gpa2hva(&mr, desc->base, desc->len, NULL);
1245         if (!hva) {
1246             error_report("%s: Failed to get HVA for GPA 0x%x sz 0x%x",
1247                          __func__, desc->base, desc->len);
1248             exit(1);
1249         }
1250 
1251         if (type == KVM_SEV_SNP_PAGE_TYPE_CPUID) {
1252             ret = snp_launch_update_cpuid(desc->base, hva, desc->len);
1253         } else if (desc->type == SEV_DESC_TYPE_SNP_KERNEL_HASHES) {
1254             ret = snp_launch_update_kernel_hashes(sev_snp, desc->base, hva,
1255                                                   desc->len);
1256         } else {
1257             ret = snp_launch_update_data(desc->base, hva, desc->len, type);
1258         }
1259 
1260         if (ret) {
1261             error_report("%s: Failed to add metadata page gpa 0x%x+%x type %d",
1262                          __func__, desc->base, desc->len, desc->type);
1263             exit(1);
1264         }
1265     }
1266 }
1267 
1268 static void
1269 sev_snp_launch_finish(SevCommonState *sev_common)
1270 {
1271     int ret, error;
1272     Error *local_err = NULL;
1273     OvmfSevMetadata *metadata;
1274     SevLaunchUpdateData *data;
1275     SevSnpGuestState *sev_snp = SEV_SNP_GUEST(sev_common);
1276     struct kvm_sev_snp_launch_finish *finish = &sev_snp->kvm_finish_conf;
1277 
1278     /*
1279      * To boot the SNP guest, the hypervisor is required to populate the CPUID
1280      * and Secrets page before finalizing the launch flow. The location of
1281      * the secrets and CPUID page is available through the OVMF metadata GUID.
1282      */
1283     metadata = pc_system_get_ovmf_sev_metadata_ptr();
1284     if (metadata == NULL) {
1285         error_report("%s: Failed to locate SEV metadata header", __func__);
1286         exit(1);
1287     }
1288 
1289     /* Populate all the metadata pages */
1290     snp_populate_metadata_pages(sev_snp, metadata);
1291 
1292     QTAILQ_FOREACH(data, &launch_update, next) {
1293         ret = sev_snp_launch_update(sev_snp, data);
1294         if (ret) {
1295             exit(1);
1296         }
1297     }
1298 
1299     trace_kvm_sev_snp_launch_finish(sev_snp->id_block, sev_snp->id_auth,
1300                                     sev_snp->host_data);
1301     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_SNP_LAUNCH_FINISH,
1302                     finish, &error);
1303     if (ret) {
1304         error_report("SNP_LAUNCH_FINISH ret=%d fw_error=%d '%s'",
1305                      ret, error, fw_error_to_str(error));
1306         exit(1);
1307     }
1308 
1309     kvm_mark_guest_state_protected();
1310     sev_set_guest_state(sev_common, SEV_STATE_RUNNING);
1311 
1312     /* add migration blocker */
1313     error_setg(&sev_mig_blocker,
1314                "SEV-SNP: Migration is not implemented");
1315     ret = migrate_add_blocker(&sev_mig_blocker, &local_err);
1316     if (local_err) {
1317         error_report_err(local_err);
1318         error_free(sev_mig_blocker);
1319         exit(1);
1320     }
1321 }
1322 
1323 
1324 static void
1325 sev_vm_state_change(void *opaque, bool running, RunState state)
1326 {
1327     SevCommonState *sev_common = opaque;
1328     SevCommonStateClass *klass = SEV_COMMON_GET_CLASS(opaque);
1329 
1330     if (running) {
1331         if (!sev_check_state(sev_common, SEV_STATE_RUNNING)) {
1332             klass->launch_finish(sev_common);
1333         }
1334     }
1335 }
1336 
1337 static int sev_kvm_type(X86ConfidentialGuest *cg)
1338 {
1339     SevCommonState *sev_common = SEV_COMMON(cg);
1340     SevGuestState *sev_guest = SEV_GUEST(sev_common);
1341     int kvm_type;
1342 
1343     if (sev_common->kvm_type != -1) {
1344         goto out;
1345     }
1346 
1347     kvm_type = (sev_guest->policy & SEV_POLICY_ES) ?
1348                 KVM_X86_SEV_ES_VM : KVM_X86_SEV_VM;
1349     if (kvm_is_vm_type_supported(kvm_type) && !sev_guest->legacy_vm_type) {
1350         sev_common->kvm_type = kvm_type;
1351     } else {
1352         sev_common->kvm_type = KVM_X86_DEFAULT_VM;
1353     }
1354 
1355 out:
1356     return sev_common->kvm_type;
1357 }
1358 
1359 static int sev_snp_kvm_type(X86ConfidentialGuest *cg)
1360 {
1361     return KVM_X86_SNP_VM;
1362 }
1363 
1364 static int sev_common_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
1365 {
1366     char *devname;
1367     int ret, fw_error, cmd;
1368     uint32_t ebx;
1369     uint32_t host_cbitpos;
1370     struct sev_user_data_status status = {};
1371     SevCommonState *sev_common = SEV_COMMON(cgs);
1372     SevCommonStateClass *klass = SEV_COMMON_GET_CLASS(cgs);
1373     X86ConfidentialGuestClass *x86_klass =
1374                                X86_CONFIDENTIAL_GUEST_GET_CLASS(cgs);
1375 
1376     sev_common->state = SEV_STATE_UNINIT;
1377 
1378     host_cpuid(0x8000001F, 0, NULL, &ebx, NULL, NULL);
1379     host_cbitpos = ebx & 0x3f;
1380 
1381     /*
1382      * The cbitpos value will be placed in bit positions 5:0 of the EBX
1383      * register of CPUID 0x8000001F. No need to verify the range as the
1384      * comparison against the host value accomplishes that.
1385      */
1386     if (host_cbitpos != sev_common->cbitpos) {
1387         error_setg(errp, "%s: cbitpos check failed, host '%d' requested '%d'",
1388                    __func__, host_cbitpos, sev_common->cbitpos);
1389         return -1;
1390     }
1391 
1392     /*
1393      * The reduced-phys-bits value will be placed in bit positions 11:6 of
1394      * the EBX register of CPUID 0x8000001F, so verify the supplied value
1395      * is in the range of 1 to 63.
1396      */
1397     if (sev_common->reduced_phys_bits < 1 ||
1398         sev_common->reduced_phys_bits > 63) {
1399         error_setg(errp, "%s: reduced_phys_bits check failed,"
1400                    " it should be in the range of 1 to 63, requested '%d'",
1401                    __func__, sev_common->reduced_phys_bits);
1402         return -1;
1403     }
1404 
1405     devname = object_property_get_str(OBJECT(sev_common), "sev-device", NULL);
1406     sev_common->sev_fd = open(devname, O_RDWR);
1407     if (sev_common->sev_fd < 0) {
1408         error_setg(errp, "%s: Failed to open %s '%s'", __func__,
1409                    devname, strerror(errno));
1410         g_free(devname);
1411         return -1;
1412     }
1413     g_free(devname);
1414 
1415     ret = sev_platform_ioctl(sev_common->sev_fd, SEV_PLATFORM_STATUS, &status,
1416                              &fw_error);
1417     if (ret) {
1418         error_setg(errp, "%s: failed to get platform status ret=%d "
1419                    "fw_error='%d: %s'", __func__, ret, fw_error,
1420                    fw_error_to_str(fw_error));
1421         return -1;
1422     }
1423     sev_common->build_id = status.build;
1424     sev_common->api_major = status.api_major;
1425     sev_common->api_minor = status.api_minor;
1426 
1427     if (sev_es_enabled()) {
1428         if (!kvm_kernel_irqchip_allowed()) {
1429             error_setg(errp, "%s: SEV-ES guests require in-kernel irqchip"
1430                        "support", __func__);
1431             return -1;
1432         }
1433     }
1434 
1435     if (sev_es_enabled() && !sev_snp_enabled()) {
1436         if (!(status.flags & SEV_STATUS_FLAGS_CONFIG_ES)) {
1437             error_setg(errp, "%s: guest policy requires SEV-ES, but "
1438                          "host SEV-ES support unavailable",
1439                          __func__);
1440             return -1;
1441         }
1442     }
1443 
1444     trace_kvm_sev_init();
1445     if (x86_klass->kvm_type(X86_CONFIDENTIAL_GUEST(sev_common)) == KVM_X86_DEFAULT_VM) {
1446         cmd = sev_es_enabled() ? KVM_SEV_ES_INIT : KVM_SEV_INIT;
1447 
1448         ret = sev_ioctl(sev_common->sev_fd, cmd, NULL, &fw_error);
1449     } else {
1450         struct kvm_sev_init args = { 0 };
1451 
1452         ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_INIT2, &args, &fw_error);
1453     }
1454 
1455     if (ret) {
1456         error_setg(errp, "%s: failed to initialize ret=%d fw_error=%d '%s'",
1457                    __func__, ret, fw_error, fw_error_to_str(fw_error));
1458         return -1;
1459     }
1460 
1461     ret = klass->launch_start(sev_common);
1462 
1463     if (ret) {
1464         error_setg(errp, "%s: failed to create encryption context", __func__);
1465         return -1;
1466     }
1467 
1468     if (klass->kvm_init && klass->kvm_init(cgs, errp)) {
1469         return -1;
1470     }
1471 
1472     qemu_add_vm_change_state_handler(sev_vm_state_change, sev_common);
1473 
1474     cgs->ready = true;
1475 
1476     return 0;
1477 }
1478 
1479 static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
1480 {
1481      int ret;
1482 
1483     /*
1484      * SEV/SEV-ES rely on pinned memory to back guest RAM so discarding
1485      * isn't actually possible. With SNP, only guest_memfd pages are used
1486      * for private guest memory, so discarding of shared memory is still
1487      * possible..
1488      */
1489     ret = ram_block_discard_disable(true);
1490     if (ret) {
1491         error_setg(errp, "%s: cannot disable RAM discard", __func__);
1492         return -1;
1493     }
1494 
1495     /*
1496      * SEV uses these notifiers to register/pin pages prior to guest use,
1497      * but SNP relies on guest_memfd for private pages, which has its
1498      * own internal mechanisms for registering/pinning private memory.
1499      */
1500     ram_block_notifier_add(&sev_ram_notifier);
1501 
1502     /*
1503      * The machine done notify event is used for SEV guests to get the
1504      * measurement of the encrypted images. When SEV-SNP is enabled, the
1505      * measurement is part of the guest attestation process where it can
1506      * be collected without any reliance on the VMM. So skip registering
1507      * the notifier for SNP in favor of using guest attestation instead.
1508      */
1509     qemu_add_machine_init_done_notifier(&sev_machine_done_notify);
1510 
1511     return 0;
1512 }
1513 
1514 static int sev_snp_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
1515 {
1516     MachineState *ms = MACHINE(qdev_get_machine());
1517     X86MachineState *x86ms = X86_MACHINE(ms);
1518 
1519     if (x86ms->smm == ON_OFF_AUTO_AUTO) {
1520         x86ms->smm = ON_OFF_AUTO_OFF;
1521     } else if (x86ms->smm == ON_OFF_AUTO_ON) {
1522         error_setg(errp, "SEV-SNP does not support SMM.");
1523         return -1;
1524     }
1525 
1526     return 0;
1527 }
1528 
1529 int
1530 sev_encrypt_flash(hwaddr gpa, uint8_t *ptr, uint64_t len, Error **errp)
1531 {
1532     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1533     SevCommonStateClass *klass;
1534 
1535     if (!sev_common) {
1536         return 0;
1537     }
1538     klass = SEV_COMMON_GET_CLASS(sev_common);
1539 
1540     /* if SEV is in update state then encrypt the data else do nothing */
1541     if (sev_check_state(sev_common, SEV_STATE_LAUNCH_UPDATE)) {
1542         int ret;
1543 
1544         ret = klass->launch_update_data(sev_common, gpa, ptr, len);
1545         if (ret < 0) {
1546             error_setg(errp, "SEV: Failed to encrypt pflash rom");
1547             return ret;
1548         }
1549     }
1550 
1551     return 0;
1552 }
1553 
1554 int sev_inject_launch_secret(const char *packet_hdr, const char *secret,
1555                              uint64_t gpa, Error **errp)
1556 {
1557     ERRP_GUARD();
1558     struct kvm_sev_launch_secret input;
1559     g_autofree guchar *data = NULL, *hdr = NULL;
1560     int error, ret = 1;
1561     void *hva;
1562     gsize hdr_sz = 0, data_sz = 0;
1563     MemoryRegion *mr = NULL;
1564     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1565 
1566     if (!sev_common) {
1567         error_setg(errp, "SEV not enabled for guest");
1568         return 1;
1569     }
1570 
1571     /* secret can be injected only in this state */
1572     if (!sev_check_state(sev_common, SEV_STATE_LAUNCH_SECRET)) {
1573         error_setg(errp, "SEV: Not in correct state. (LSECRET) %x",
1574                    sev_common->state);
1575         return 1;
1576     }
1577 
1578     hdr = g_base64_decode(packet_hdr, &hdr_sz);
1579     if (!hdr || !hdr_sz) {
1580         error_setg(errp, "SEV: Failed to decode sequence header");
1581         return 1;
1582     }
1583 
1584     data = g_base64_decode(secret, &data_sz);
1585     if (!data || !data_sz) {
1586         error_setg(errp, "SEV: Failed to decode data");
1587         return 1;
1588     }
1589 
1590     hva = gpa2hva(&mr, gpa, data_sz, errp);
1591     if (!hva) {
1592         error_prepend(errp, "SEV: Failed to calculate guest address: ");
1593         return 1;
1594     }
1595 
1596     input.hdr_uaddr = (uint64_t)(unsigned long)hdr;
1597     input.hdr_len = hdr_sz;
1598 
1599     input.trans_uaddr = (uint64_t)(unsigned long)data;
1600     input.trans_len = data_sz;
1601 
1602     input.guest_uaddr = (uint64_t)(unsigned long)hva;
1603     input.guest_len = data_sz;
1604 
1605     trace_kvm_sev_launch_secret(gpa, input.guest_uaddr,
1606                                 input.trans_uaddr, input.trans_len);
1607 
1608     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_SECRET,
1609                     &input, &error);
1610     if (ret) {
1611         error_setg(errp, "SEV: failed to inject secret ret=%d fw_error=%d '%s'",
1612                      ret, error, fw_error_to_str(error));
1613         return ret;
1614     }
1615 
1616     return 0;
1617 }
1618 
1619 #define SEV_SECRET_GUID "4c2eb361-7d9b-4cc3-8081-127c90d3d294"
1620 struct sev_secret_area {
1621     uint32_t base;
1622     uint32_t size;
1623 };
1624 
1625 void qmp_sev_inject_launch_secret(const char *packet_hdr,
1626                                   const char *secret,
1627                                   bool has_gpa, uint64_t gpa,
1628                                   Error **errp)
1629 {
1630     if (!sev_enabled()) {
1631         error_setg(errp, "SEV not enabled for guest");
1632         return;
1633     }
1634     if (!has_gpa) {
1635         uint8_t *data;
1636         struct sev_secret_area *area;
1637 
1638         if (!pc_system_ovmf_table_find(SEV_SECRET_GUID, &data, NULL)) {
1639             error_setg(errp, "SEV: no secret area found in OVMF,"
1640                        " gpa must be specified.");
1641             return;
1642         }
1643         area = (struct sev_secret_area *)data;
1644         gpa = area->base;
1645     }
1646 
1647     sev_inject_launch_secret(packet_hdr, secret, gpa, errp);
1648 }
1649 
1650 static int
1651 sev_es_parse_reset_block(SevInfoBlock *info, uint32_t *addr)
1652 {
1653     if (!info->reset_addr) {
1654         error_report("SEV-ES reset address is zero");
1655         return 1;
1656     }
1657 
1658     *addr = info->reset_addr;
1659 
1660     return 0;
1661 }
1662 
1663 static int
1664 sev_es_find_reset_vector(void *flash_ptr, uint64_t flash_size,
1665                          uint32_t *addr)
1666 {
1667     QemuUUID info_guid, *guid;
1668     SevInfoBlock *info;
1669     uint8_t *data;
1670     uint16_t *len;
1671 
1672     /*
1673      * Initialize the address to zero. An address of zero with a successful
1674      * return code indicates that SEV-ES is not active.
1675      */
1676     *addr = 0;
1677 
1678     /*
1679      * Extract the AP reset vector for SEV-ES guests by locating the SEV GUID.
1680      * The SEV GUID is located on its own (original implementation) or within
1681      * the Firmware GUID Table (new implementation), either of which are
1682      * located 32 bytes from the end of the flash.
1683      *
1684      * Check the Firmware GUID Table first.
1685      */
1686     if (pc_system_ovmf_table_find(SEV_INFO_BLOCK_GUID, &data, NULL)) {
1687         return sev_es_parse_reset_block((SevInfoBlock *)data, addr);
1688     }
1689 
1690     /*
1691      * SEV info block not found in the Firmware GUID Table (or there isn't
1692      * a Firmware GUID Table), fall back to the original implementation.
1693      */
1694     data = flash_ptr + flash_size - 0x20;
1695 
1696     qemu_uuid_parse(SEV_INFO_BLOCK_GUID, &info_guid);
1697     info_guid = qemu_uuid_bswap(info_guid); /* GUIDs are LE */
1698 
1699     guid = (QemuUUID *)(data - sizeof(info_guid));
1700     if (!qemu_uuid_is_equal(guid, &info_guid)) {
1701         error_report("SEV information block/Firmware GUID Table block not found in pflash rom");
1702         return 1;
1703     }
1704 
1705     len = (uint16_t *)((uint8_t *)guid - sizeof(*len));
1706     info = (SevInfoBlock *)(data - le16_to_cpu(*len));
1707 
1708     return sev_es_parse_reset_block(info, addr);
1709 }
1710 
1711 void sev_es_set_reset_vector(CPUState *cpu)
1712 {
1713     X86CPU *x86;
1714     CPUX86State *env;
1715     ConfidentialGuestSupport *cgs = MACHINE(qdev_get_machine())->cgs;
1716     SevCommonState *sev_common = SEV_COMMON(
1717         object_dynamic_cast(OBJECT(cgs), TYPE_SEV_COMMON));
1718 
1719     /* Only update if we have valid reset information */
1720     if (!sev_common || !sev_common->reset_data_valid) {
1721         return;
1722     }
1723 
1724     /* Do not update the BSP reset state */
1725     if (cpu->cpu_index == 0) {
1726         return;
1727     }
1728 
1729     x86 = X86_CPU(cpu);
1730     env = &x86->env;
1731 
1732     cpu_x86_load_seg_cache(env, R_CS, 0xf000, sev_common->reset_cs, 0xffff,
1733                            DESC_P_MASK | DESC_S_MASK | DESC_CS_MASK |
1734                            DESC_R_MASK | DESC_A_MASK);
1735 
1736     env->eip = sev_common->reset_ip;
1737 }
1738 
1739 int sev_es_save_reset_vector(void *flash_ptr, uint64_t flash_size)
1740 {
1741     CPUState *cpu;
1742     uint32_t addr;
1743     int ret;
1744     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1745 
1746     if (!sev_es_enabled()) {
1747         return 0;
1748     }
1749 
1750     addr = 0;
1751     ret = sev_es_find_reset_vector(flash_ptr, flash_size,
1752                                    &addr);
1753     if (ret) {
1754         return ret;
1755     }
1756 
1757     if (addr) {
1758         sev_common->reset_cs = addr & 0xffff0000;
1759         sev_common->reset_ip = addr & 0x0000ffff;
1760         sev_common->reset_data_valid = true;
1761 
1762         CPU_FOREACH(cpu) {
1763             sev_es_set_reset_vector(cpu);
1764         }
1765     }
1766 
1767     return 0;
1768 }
1769 
1770 static const QemuUUID sev_hash_table_header_guid = {
1771     .data = UUID_LE(0x9438d606, 0x4f22, 0x4cc9, 0xb4, 0x79, 0xa7, 0x93,
1772                     0xd4, 0x11, 0xfd, 0x21)
1773 };
1774 
1775 static const QemuUUID sev_kernel_entry_guid = {
1776     .data = UUID_LE(0x4de79437, 0xabd2, 0x427f, 0xb8, 0x35, 0xd5, 0xb1,
1777                     0x72, 0xd2, 0x04, 0x5b)
1778 };
1779 static const QemuUUID sev_initrd_entry_guid = {
1780     .data = UUID_LE(0x44baf731, 0x3a2f, 0x4bd7, 0x9a, 0xf1, 0x41, 0xe2,
1781                     0x91, 0x69, 0x78, 0x1d)
1782 };
1783 static const QemuUUID sev_cmdline_entry_guid = {
1784     .data = UUID_LE(0x97d02dd8, 0xbd20, 0x4c94, 0xaa, 0x78, 0xe7, 0x71,
1785                     0x4d, 0x36, 0xab, 0x2a)
1786 };
1787 
1788 static bool build_kernel_loader_hashes(PaddedSevHashTable *padded_ht,
1789                                        SevKernelLoaderContext *ctx,
1790                                        Error **errp)
1791 {
1792     SevHashTable *ht;
1793     uint8_t cmdline_hash[HASH_SIZE];
1794     uint8_t initrd_hash[HASH_SIZE];
1795     uint8_t kernel_hash[HASH_SIZE];
1796     uint8_t *hashp;
1797     size_t hash_len = HASH_SIZE;
1798 
1799     /*
1800      * Calculate hash of kernel command-line with the terminating null byte. If
1801      * the user doesn't supply a command-line via -append, the 1-byte "\0" will
1802      * be used.
1803      */
1804     hashp = cmdline_hash;
1805     if (qcrypto_hash_bytes(QCRYPTO_HASH_ALG_SHA256, ctx->cmdline_data,
1806                            ctx->cmdline_size, &hashp, &hash_len, errp) < 0) {
1807         return false;
1808     }
1809     assert(hash_len == HASH_SIZE);
1810 
1811     /*
1812      * Calculate hash of initrd. If the user doesn't supply an initrd via
1813      * -initrd, an empty buffer will be used (ctx->initrd_size == 0).
1814      */
1815     hashp = initrd_hash;
1816     if (qcrypto_hash_bytes(QCRYPTO_HASH_ALG_SHA256, ctx->initrd_data,
1817                            ctx->initrd_size, &hashp, &hash_len, errp) < 0) {
1818         return false;
1819     }
1820     assert(hash_len == HASH_SIZE);
1821 
1822     /* Calculate hash of the kernel */
1823     hashp = kernel_hash;
1824     struct iovec iov[2] = {
1825         { .iov_base = ctx->setup_data, .iov_len = ctx->setup_size },
1826         { .iov_base = ctx->kernel_data, .iov_len = ctx->kernel_size }
1827     };
1828     if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA256, iov, ARRAY_SIZE(iov),
1829                             &hashp, &hash_len, errp) < 0) {
1830         return false;
1831     }
1832     assert(hash_len == HASH_SIZE);
1833 
1834     ht = &padded_ht->ht;
1835 
1836     ht->guid = sev_hash_table_header_guid;
1837     ht->len = sizeof(*ht);
1838 
1839     ht->cmdline.guid = sev_cmdline_entry_guid;
1840     ht->cmdline.len = sizeof(ht->cmdline);
1841     memcpy(ht->cmdline.hash, cmdline_hash, sizeof(ht->cmdline.hash));
1842 
1843     ht->initrd.guid = sev_initrd_entry_guid;
1844     ht->initrd.len = sizeof(ht->initrd);
1845     memcpy(ht->initrd.hash, initrd_hash, sizeof(ht->initrd.hash));
1846 
1847     ht->kernel.guid = sev_kernel_entry_guid;
1848     ht->kernel.len = sizeof(ht->kernel);
1849     memcpy(ht->kernel.hash, kernel_hash, sizeof(ht->kernel.hash));
1850 
1851     /* zero the excess data so the measurement can be reliably calculated */
1852     memset(padded_ht->padding, 0, sizeof(padded_ht->padding));
1853 
1854     return true;
1855 }
1856 
1857 static bool sev_snp_build_kernel_loader_hashes(SevCommonState *sev_common,
1858                                                SevHashTableDescriptor *area,
1859                                                SevKernelLoaderContext *ctx,
1860                                                Error **errp)
1861 {
1862     /*
1863      * SNP: Populate the hashes table in an area that later in
1864      * snp_launch_update_kernel_hashes() will be copied to the guest memory
1865      * and encrypted.
1866      */
1867     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(sev_common);
1868     sev_snp_guest->kernel_hashes_offset = area->base & ~TARGET_PAGE_MASK;
1869     sev_snp_guest->kernel_hashes_data = g_new0(PaddedSevHashTable, 1);
1870     return build_kernel_loader_hashes(sev_snp_guest->kernel_hashes_data, ctx, errp);
1871 }
1872 
1873 static bool sev_build_kernel_loader_hashes(SevCommonState *sev_common,
1874                                            SevHashTableDescriptor *area,
1875                                            SevKernelLoaderContext *ctx,
1876                                            Error **errp)
1877 {
1878     PaddedSevHashTable *padded_ht;
1879     hwaddr mapped_len = sizeof(*padded_ht);
1880     MemTxAttrs attrs = { 0 };
1881     bool ret = true;
1882 
1883     /*
1884      * Populate the hashes table in the guest's memory at the OVMF-designated
1885      * area for the SEV hashes table
1886      */
1887     padded_ht = address_space_map(&address_space_memory, area->base,
1888                                   &mapped_len, true, attrs);
1889     if (!padded_ht || mapped_len != sizeof(*padded_ht)) {
1890         error_setg(errp, "SEV: cannot map hashes table guest memory area");
1891         return false;
1892     }
1893 
1894     if (build_kernel_loader_hashes(padded_ht, ctx, errp)) {
1895         if (sev_encrypt_flash(area->base, (uint8_t *)padded_ht,
1896                               sizeof(*padded_ht), errp) < 0) {
1897             ret = false;
1898         }
1899     } else {
1900         ret = false;
1901     }
1902 
1903     address_space_unmap(&address_space_memory, padded_ht,
1904                         mapped_len, true, mapped_len);
1905 
1906     return ret;
1907 }
1908 
1909 /*
1910  * Add the hashes of the linux kernel/initrd/cmdline to an encrypted guest page
1911  * which is included in SEV's initial memory measurement.
1912  */
1913 bool sev_add_kernel_loader_hashes(SevKernelLoaderContext *ctx, Error **errp)
1914 {
1915     uint8_t *data;
1916     SevHashTableDescriptor *area;
1917     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1918     SevCommonStateClass *klass = SEV_COMMON_GET_CLASS(sev_common);
1919 
1920     /*
1921      * Only add the kernel hashes if the sev-guest configuration explicitly
1922      * stated kernel-hashes=on.
1923      */
1924     if (!sev_common->kernel_hashes) {
1925         return false;
1926     }
1927 
1928     if (!pc_system_ovmf_table_find(SEV_HASH_TABLE_RV_GUID, &data, NULL)) {
1929         error_setg(errp, "SEV: kernel specified but guest firmware "
1930                          "has no hashes table GUID");
1931         return false;
1932     }
1933 
1934     area = (SevHashTableDescriptor *)data;
1935     if (!area->base || area->size < sizeof(PaddedSevHashTable)) {
1936         error_setg(errp, "SEV: guest firmware hashes table area is invalid "
1937                          "(base=0x%x size=0x%x)", area->base, area->size);
1938         return false;
1939     }
1940 
1941     return klass->build_kernel_loader_hashes(sev_common, area, ctx, errp);
1942 }
1943 
1944 static char *
1945 sev_common_get_sev_device(Object *obj, Error **errp)
1946 {
1947     return g_strdup(SEV_COMMON(obj)->sev_device);
1948 }
1949 
1950 static void
1951 sev_common_set_sev_device(Object *obj, const char *value, Error **errp)
1952 {
1953     SEV_COMMON(obj)->sev_device = g_strdup(value);
1954 }
1955 
1956 static bool sev_common_get_kernel_hashes(Object *obj, Error **errp)
1957 {
1958     return SEV_COMMON(obj)->kernel_hashes;
1959 }
1960 
1961 static void sev_common_set_kernel_hashes(Object *obj, bool value, Error **errp)
1962 {
1963     SEV_COMMON(obj)->kernel_hashes = value;
1964 }
1965 
1966 static void
1967 sev_common_class_init(ObjectClass *oc, void *data)
1968 {
1969     ConfidentialGuestSupportClass *klass = CONFIDENTIAL_GUEST_SUPPORT_CLASS(oc);
1970 
1971     klass->kvm_init = sev_common_kvm_init;
1972 
1973     object_class_property_add_str(oc, "sev-device",
1974                                   sev_common_get_sev_device,
1975                                   sev_common_set_sev_device);
1976     object_class_property_set_description(oc, "sev-device",
1977             "SEV device to use");
1978     object_class_property_add_bool(oc, "kernel-hashes",
1979                                    sev_common_get_kernel_hashes,
1980                                    sev_common_set_kernel_hashes);
1981     object_class_property_set_description(oc, "kernel-hashes",
1982             "add kernel hashes to guest firmware for measured Linux boot");
1983 }
1984 
1985 static void
1986 sev_common_instance_init(Object *obj)
1987 {
1988     SevCommonState *sev_common = SEV_COMMON(obj);
1989 
1990     sev_common->kvm_type = -1;
1991 
1992     sev_common->sev_device = g_strdup(DEFAULT_SEV_DEVICE);
1993 
1994     object_property_add_uint32_ptr(obj, "cbitpos", &sev_common->cbitpos,
1995                                    OBJ_PROP_FLAG_READWRITE);
1996     object_property_add_uint32_ptr(obj, "reduced-phys-bits",
1997                                    &sev_common->reduced_phys_bits,
1998                                    OBJ_PROP_FLAG_READWRITE);
1999 }
2000 
2001 /* sev guest info common to sev/sev-es/sev-snp */
2002 static const TypeInfo sev_common_info = {
2003     .parent = TYPE_X86_CONFIDENTIAL_GUEST,
2004     .name = TYPE_SEV_COMMON,
2005     .instance_size = sizeof(SevCommonState),
2006     .instance_init = sev_common_instance_init,
2007     .class_size = sizeof(SevCommonStateClass),
2008     .class_init = sev_common_class_init,
2009     .abstract = true,
2010     .interfaces = (InterfaceInfo[]) {
2011         { TYPE_USER_CREATABLE },
2012         { }
2013     }
2014 };
2015 
2016 static char *
2017 sev_guest_get_dh_cert_file(Object *obj, Error **errp)
2018 {
2019     return g_strdup(SEV_GUEST(obj)->dh_cert_file);
2020 }
2021 
2022 static void
2023 sev_guest_set_dh_cert_file(Object *obj, const char *value, Error **errp)
2024 {
2025     SEV_GUEST(obj)->dh_cert_file = g_strdup(value);
2026 }
2027 
2028 static char *
2029 sev_guest_get_session_file(Object *obj, Error **errp)
2030 {
2031     SevGuestState *sev_guest = SEV_GUEST(obj);
2032 
2033     return sev_guest->session_file ? g_strdup(sev_guest->session_file) : NULL;
2034 }
2035 
2036 static void
2037 sev_guest_set_session_file(Object *obj, const char *value, Error **errp)
2038 {
2039     SEV_GUEST(obj)->session_file = g_strdup(value);
2040 }
2041 
2042 static bool sev_guest_get_legacy_vm_type(Object *obj, Error **errp)
2043 {
2044     return SEV_GUEST(obj)->legacy_vm_type;
2045 }
2046 
2047 static void sev_guest_set_legacy_vm_type(Object *obj, bool value, Error **errp)
2048 {
2049     SEV_GUEST(obj)->legacy_vm_type = value;
2050 }
2051 
2052 static void
2053 sev_guest_class_init(ObjectClass *oc, void *data)
2054 {
2055     SevCommonStateClass *klass = SEV_COMMON_CLASS(oc);
2056     X86ConfidentialGuestClass *x86_klass = X86_CONFIDENTIAL_GUEST_CLASS(oc);
2057 
2058     klass->build_kernel_loader_hashes = sev_build_kernel_loader_hashes;
2059     klass->launch_start = sev_launch_start;
2060     klass->launch_finish = sev_launch_finish;
2061     klass->launch_update_data = sev_launch_update_data;
2062     klass->kvm_init = sev_kvm_init;
2063     x86_klass->kvm_type = sev_kvm_type;
2064 
2065     object_class_property_add_str(oc, "dh-cert-file",
2066                                   sev_guest_get_dh_cert_file,
2067                                   sev_guest_set_dh_cert_file);
2068     object_class_property_set_description(oc, "dh-cert-file",
2069             "guest owners DH certificate (encoded with base64)");
2070     object_class_property_add_str(oc, "session-file",
2071                                   sev_guest_get_session_file,
2072                                   sev_guest_set_session_file);
2073     object_class_property_set_description(oc, "session-file",
2074             "guest owners session parameters (encoded with base64)");
2075     object_class_property_add_bool(oc, "legacy-vm-type",
2076                                    sev_guest_get_legacy_vm_type,
2077                                    sev_guest_set_legacy_vm_type);
2078     object_class_property_set_description(oc, "legacy-vm-type",
2079             "use legacy VM type to maintain measurement compatibility with older QEMU or kernel versions.");
2080 }
2081 
2082 static void
2083 sev_guest_instance_init(Object *obj)
2084 {
2085     SevGuestState *sev_guest = SEV_GUEST(obj);
2086 
2087     sev_guest->policy = DEFAULT_GUEST_POLICY;
2088     object_property_add_uint32_ptr(obj, "handle", &sev_guest->handle,
2089                                    OBJ_PROP_FLAG_READWRITE);
2090     object_property_add_uint32_ptr(obj, "policy", &sev_guest->policy,
2091                                    OBJ_PROP_FLAG_READWRITE);
2092     object_apply_compat_props(obj);
2093 }
2094 
2095 /* guest info specific sev/sev-es */
2096 static const TypeInfo sev_guest_info = {
2097     .parent = TYPE_SEV_COMMON,
2098     .name = TYPE_SEV_GUEST,
2099     .instance_size = sizeof(SevGuestState),
2100     .instance_init = sev_guest_instance_init,
2101     .class_init = sev_guest_class_init,
2102 };
2103 
2104 static void
2105 sev_snp_guest_get_policy(Object *obj, Visitor *v, const char *name,
2106                          void *opaque, Error **errp)
2107 {
2108     visit_type_uint64(v, name,
2109                       (uint64_t *)&SEV_SNP_GUEST(obj)->kvm_start_conf.policy,
2110                       errp);
2111 }
2112 
2113 static void
2114 sev_snp_guest_set_policy(Object *obj, Visitor *v, const char *name,
2115                          void *opaque, Error **errp)
2116 {
2117     visit_type_uint64(v, name,
2118                       (uint64_t *)&SEV_SNP_GUEST(obj)->kvm_start_conf.policy,
2119                       errp);
2120 }
2121 
2122 static char *
2123 sev_snp_guest_get_guest_visible_workarounds(Object *obj, Error **errp)
2124 {
2125     return g_strdup(SEV_SNP_GUEST(obj)->guest_visible_workarounds);
2126 }
2127 
2128 static void
2129 sev_snp_guest_set_guest_visible_workarounds(Object *obj, const char *value,
2130                                             Error **errp)
2131 {
2132     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2133     struct kvm_sev_snp_launch_start *start = &sev_snp_guest->kvm_start_conf;
2134     g_autofree guchar *blob;
2135     gsize len;
2136 
2137     g_free(sev_snp_guest->guest_visible_workarounds);
2138 
2139     /* store the base64 str so we don't need to re-encode in getter */
2140     sev_snp_guest->guest_visible_workarounds = g_strdup(value);
2141 
2142     blob = qbase64_decode(sev_snp_guest->guest_visible_workarounds,
2143                           -1, &len, errp);
2144     if (!blob) {
2145         return;
2146     }
2147 
2148     if (len != sizeof(start->gosvw)) {
2149         error_setg(errp, "parameter length of %lu exceeds max of %lu",
2150                    len, sizeof(start->gosvw));
2151         return;
2152     }
2153 
2154     memcpy(start->gosvw, blob, len);
2155 }
2156 
2157 static char *
2158 sev_snp_guest_get_id_block(Object *obj, Error **errp)
2159 {
2160     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2161 
2162     return g_strdup(sev_snp_guest->id_block);
2163 }
2164 
2165 static void
2166 sev_snp_guest_set_id_block(Object *obj, const char *value, Error **errp)
2167 {
2168     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2169     struct kvm_sev_snp_launch_finish *finish = &sev_snp_guest->kvm_finish_conf;
2170     gsize len;
2171 
2172     finish->id_block_en = 0;
2173     g_free(sev_snp_guest->id_block);
2174     g_free((guchar *)finish->id_block_uaddr);
2175 
2176     /* store the base64 str so we don't need to re-encode in getter */
2177     sev_snp_guest->id_block = g_strdup(value);
2178 
2179     finish->id_block_uaddr =
2180         (uint64_t)qbase64_decode(sev_snp_guest->id_block, -1, &len, errp);
2181 
2182     if (!finish->id_block_uaddr) {
2183         return;
2184     }
2185 
2186     if (len != KVM_SEV_SNP_ID_BLOCK_SIZE) {
2187         error_setg(errp, "parameter length of %lu not equal to %u",
2188                    len, KVM_SEV_SNP_ID_BLOCK_SIZE);
2189         return;
2190     }
2191 
2192     finish->id_block_en = 1;
2193 }
2194 
2195 static char *
2196 sev_snp_guest_get_id_auth(Object *obj, Error **errp)
2197 {
2198     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2199 
2200     return g_strdup(sev_snp_guest->id_auth);
2201 }
2202 
2203 static void
2204 sev_snp_guest_set_id_auth(Object *obj, const char *value, Error **errp)
2205 {
2206     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2207     struct kvm_sev_snp_launch_finish *finish = &sev_snp_guest->kvm_finish_conf;
2208     gsize len;
2209 
2210     g_free(sev_snp_guest->id_auth);
2211     g_free((guchar *)finish->id_auth_uaddr);
2212 
2213     /* store the base64 str so we don't need to re-encode in getter */
2214     sev_snp_guest->id_auth = g_strdup(value);
2215 
2216     finish->id_auth_uaddr =
2217         (uint64_t)qbase64_decode(sev_snp_guest->id_auth, -1, &len, errp);
2218 
2219     if (!finish->id_auth_uaddr) {
2220         return;
2221     }
2222 
2223     if (len > KVM_SEV_SNP_ID_AUTH_SIZE) {
2224         error_setg(errp, "parameter length:ID_AUTH %lu exceeds max of %u",
2225                    len, KVM_SEV_SNP_ID_AUTH_SIZE);
2226         return;
2227     }
2228 }
2229 
2230 static bool
2231 sev_snp_guest_get_author_key_enabled(Object *obj, Error **errp)
2232 {
2233     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2234 
2235     return !!sev_snp_guest->kvm_finish_conf.auth_key_en;
2236 }
2237 
2238 static void
2239 sev_snp_guest_set_author_key_enabled(Object *obj, bool value, Error **errp)
2240 {
2241     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2242 
2243     sev_snp_guest->kvm_finish_conf.auth_key_en = value;
2244 }
2245 
2246 static bool
2247 sev_snp_guest_get_vcek_disabled(Object *obj, Error **errp)
2248 {
2249     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2250 
2251     return !!sev_snp_guest->kvm_finish_conf.vcek_disabled;
2252 }
2253 
2254 static void
2255 sev_snp_guest_set_vcek_disabled(Object *obj, bool value, Error **errp)
2256 {
2257     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2258 
2259     sev_snp_guest->kvm_finish_conf.vcek_disabled = value;
2260 }
2261 
2262 static char *
2263 sev_snp_guest_get_host_data(Object *obj, Error **errp)
2264 {
2265     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2266 
2267     return g_strdup(sev_snp_guest->host_data);
2268 }
2269 
2270 static void
2271 sev_snp_guest_set_host_data(Object *obj, const char *value, Error **errp)
2272 {
2273     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2274     struct kvm_sev_snp_launch_finish *finish = &sev_snp_guest->kvm_finish_conf;
2275     g_autofree guchar *blob;
2276     gsize len;
2277 
2278     g_free(sev_snp_guest->host_data);
2279 
2280     /* store the base64 str so we don't need to re-encode in getter */
2281     sev_snp_guest->host_data = g_strdup(value);
2282 
2283     blob = qbase64_decode(sev_snp_guest->host_data, -1, &len, errp);
2284 
2285     if (!blob) {
2286         return;
2287     }
2288 
2289     if (len != sizeof(finish->host_data)) {
2290         error_setg(errp, "parameter length of %lu not equal to %lu",
2291                    len, sizeof(finish->host_data));
2292         return;
2293     }
2294 
2295     memcpy(finish->host_data, blob, len);
2296 }
2297 
2298 static void
2299 sev_snp_guest_class_init(ObjectClass *oc, void *data)
2300 {
2301     SevCommonStateClass *klass = SEV_COMMON_CLASS(oc);
2302     X86ConfidentialGuestClass *x86_klass = X86_CONFIDENTIAL_GUEST_CLASS(oc);
2303 
2304     klass->build_kernel_loader_hashes = sev_snp_build_kernel_loader_hashes;
2305     klass->launch_start = sev_snp_launch_start;
2306     klass->launch_finish = sev_snp_launch_finish;
2307     klass->launch_update_data = sev_snp_launch_update_data;
2308     klass->kvm_init = sev_snp_kvm_init;
2309     x86_klass->kvm_type = sev_snp_kvm_type;
2310 
2311     object_class_property_add(oc, "policy", "uint64",
2312                               sev_snp_guest_get_policy,
2313                               sev_snp_guest_set_policy, NULL, NULL);
2314     object_class_property_add_str(oc, "guest-visible-workarounds",
2315                                   sev_snp_guest_get_guest_visible_workarounds,
2316                                   sev_snp_guest_set_guest_visible_workarounds);
2317     object_class_property_add_str(oc, "id-block",
2318                                   sev_snp_guest_get_id_block,
2319                                   sev_snp_guest_set_id_block);
2320     object_class_property_add_str(oc, "id-auth",
2321                                   sev_snp_guest_get_id_auth,
2322                                   sev_snp_guest_set_id_auth);
2323     object_class_property_add_bool(oc, "author-key-enabled",
2324                                    sev_snp_guest_get_author_key_enabled,
2325                                    sev_snp_guest_set_author_key_enabled);
2326     object_class_property_add_bool(oc, "vcek-required",
2327                                    sev_snp_guest_get_vcek_disabled,
2328                                    sev_snp_guest_set_vcek_disabled);
2329     object_class_property_add_str(oc, "host-data",
2330                                   sev_snp_guest_get_host_data,
2331                                   sev_snp_guest_set_host_data);
2332 }
2333 
2334 static void
2335 sev_snp_guest_instance_init(Object *obj)
2336 {
2337     ConfidentialGuestSupport *cgs = CONFIDENTIAL_GUEST_SUPPORT(obj);
2338     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2339 
2340     cgs->require_guest_memfd = true;
2341 
2342     /* default init/start/finish params for kvm */
2343     sev_snp_guest->kvm_start_conf.policy = DEFAULT_SEV_SNP_POLICY;
2344 }
2345 
2346 /* guest info specific to sev-snp */
2347 static const TypeInfo sev_snp_guest_info = {
2348     .parent = TYPE_SEV_COMMON,
2349     .name = TYPE_SEV_SNP_GUEST,
2350     .instance_size = sizeof(SevSnpGuestState),
2351     .class_init = sev_snp_guest_class_init,
2352     .instance_init = sev_snp_guest_instance_init,
2353 };
2354 
2355 static void
2356 sev_register_types(void)
2357 {
2358     type_register_static(&sev_common_info);
2359     type_register_static(&sev_guest_info);
2360     type_register_static(&sev_snp_guest_info);
2361 }
2362 
2363 type_init(sev_register_types);
2364