xref: /openbmc/qemu/target/i386/sev.c (revision ba379542)
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     }
591 
592     sev_device = object_property_get_str(OBJECT(sev_common), "sev-device",
593                                          &error_abort);
594     fd = open(sev_device, O_RDWR);
595     if (fd < 0) {
596         error_setg_errno(errp, errno, "SEV: Failed to open %s",
597                          DEFAULT_SEV_DEVICE);
598         g_free(sev_device);
599         return NULL;
600     }
601     g_free(sev_device);
602 
603     if (sev_get_pdh_info(fd, &pdh_data, &pdh_len,
604                          &cert_chain_data, &cert_chain_len, errp)) {
605         goto out;
606     }
607 
608     if (sev_get_cpu0_id(fd, &cpu0_id_data, &cpu0_id_len, errp)) {
609         goto out;
610     }
611 
612     cap = g_new0(SevCapability, 1);
613     cap->pdh = g_base64_encode(pdh_data, pdh_len);
614     cap->cert_chain = g_base64_encode(cert_chain_data, cert_chain_len);
615     cap->cpu0_id = g_base64_encode(cpu0_id_data, cpu0_id_len);
616 
617     host_cpuid(0x8000001F, 0, NULL, &ebx, NULL, NULL);
618     cap->cbitpos = ebx & 0x3f;
619 
620     /*
621      * When SEV feature is enabled, we loose one bit in guest physical
622      * addressing.
623      */
624     cap->reduced_phys_bits = 1;
625 
626 out:
627     g_free(cpu0_id_data);
628     g_free(pdh_data);
629     g_free(cert_chain_data);
630     close(fd);
631     return cap;
632 }
633 
634 SevCapability *qmp_query_sev_capabilities(Error **errp)
635 {
636     return sev_get_capabilities(errp);
637 }
638 
639 static OvmfSevMetadata *ovmf_sev_metadata_table;
640 
641 #define OVMF_SEV_META_DATA_GUID "dc886566-984a-4798-A75e-5585a7bf67cc"
642 typedef struct __attribute__((__packed__)) OvmfSevMetadataOffset {
643     uint32_t offset;
644 } OvmfSevMetadataOffset;
645 
646 OvmfSevMetadata *pc_system_get_ovmf_sev_metadata_ptr(void)
647 {
648     return ovmf_sev_metadata_table;
649 }
650 
651 void pc_system_parse_sev_metadata(uint8_t *flash_ptr, size_t flash_size)
652 {
653     OvmfSevMetadata     *metadata;
654     OvmfSevMetadataOffset  *data;
655 
656     if (!pc_system_ovmf_table_find(OVMF_SEV_META_DATA_GUID, (uint8_t **)&data,
657                                    NULL)) {
658         return;
659     }
660 
661     metadata = (OvmfSevMetadata *)(flash_ptr + flash_size - data->offset);
662     if (memcmp(metadata->signature, "ASEV", 4) != 0 ||
663         metadata->len < sizeof(OvmfSevMetadata) ||
664         metadata->len > flash_size - data->offset) {
665         return;
666     }
667 
668     ovmf_sev_metadata_table = g_memdup2(metadata, metadata->len);
669 }
670 
671 static SevAttestationReport *sev_get_attestation_report(const char *mnonce,
672                                                         Error **errp)
673 {
674     struct kvm_sev_attestation_report input = {};
675     SevAttestationReport *report = NULL;
676     SevCommonState *sev_common;
677     g_autofree guchar *data = NULL;
678     g_autofree guchar *buf = NULL;
679     gsize len;
680     int err = 0, ret;
681 
682     if (!sev_enabled()) {
683         error_setg(errp, "SEV is not enabled");
684         return NULL;
685     }
686 
687     /* lets decode the mnonce string */
688     buf = g_base64_decode(mnonce, &len);
689     if (!buf) {
690         error_setg(errp, "SEV: failed to decode mnonce input");
691         return NULL;
692     }
693 
694     /* verify the input mnonce length */
695     if (len != sizeof(input.mnonce)) {
696         error_setg(errp, "SEV: mnonce must be %zu bytes (got %" G_GSIZE_FORMAT ")",
697                 sizeof(input.mnonce), len);
698         return NULL;
699     }
700 
701     sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
702 
703     /* Query the report length */
704     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_GET_ATTESTATION_REPORT,
705             &input, &err);
706     if (ret < 0) {
707         if (err != SEV_RET_INVALID_LEN) {
708             error_setg(errp, "SEV: Failed to query the attestation report"
709                              " length ret=%d fw_err=%d (%s)",
710                        ret, err, fw_error_to_str(err));
711             return NULL;
712         }
713     }
714 
715     data = g_malloc(input.len);
716     input.uaddr = (unsigned long)data;
717     memcpy(input.mnonce, buf, sizeof(input.mnonce));
718 
719     /* Query the report */
720     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_GET_ATTESTATION_REPORT,
721             &input, &err);
722     if (ret) {
723         error_setg_errno(errp, errno, "SEV: Failed to get attestation report"
724                 " ret=%d fw_err=%d (%s)", ret, err, fw_error_to_str(err));
725         return NULL;
726     }
727 
728     report = g_new0(SevAttestationReport, 1);
729     report->data = g_base64_encode(data, input.len);
730 
731     trace_kvm_sev_attestation_report(mnonce, report->data);
732 
733     return report;
734 }
735 
736 SevAttestationReport *qmp_query_sev_attestation_report(const char *mnonce,
737                                                        Error **errp)
738 {
739     return sev_get_attestation_report(mnonce, errp);
740 }
741 
742 static int
743 sev_read_file_base64(const char *filename, guchar **data, gsize *len)
744 {
745     gsize sz;
746     g_autofree gchar *base64 = NULL;
747     GError *error = NULL;
748 
749     if (!g_file_get_contents(filename, &base64, &sz, &error)) {
750         error_report("SEV: Failed to read '%s' (%s)", filename, error->message);
751         g_error_free(error);
752         return -1;
753     }
754 
755     *data = g_base64_decode(base64, len);
756     return 0;
757 }
758 
759 static int
760 sev_snp_launch_start(SevCommonState *sev_common)
761 {
762     int fw_error, rc;
763     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(sev_common);
764     struct kvm_sev_snp_launch_start *start = &sev_snp_guest->kvm_start_conf;
765 
766     trace_kvm_sev_snp_launch_start(start->policy,
767                                    sev_snp_guest->guest_visible_workarounds);
768 
769     if (!kvm_enable_hypercall(BIT_ULL(KVM_HC_MAP_GPA_RANGE))) {
770             return 1;
771     }
772 
773     rc = sev_ioctl(sev_common->sev_fd, KVM_SEV_SNP_LAUNCH_START,
774                    start, &fw_error);
775     if (rc < 0) {
776         error_report("%s: SNP_LAUNCH_START ret=%d fw_error=%d '%s'",
777                 __func__, rc, fw_error, fw_error_to_str(fw_error));
778         return 1;
779     }
780 
781     QTAILQ_INIT(&launch_update);
782 
783     sev_set_guest_state(sev_common, SEV_STATE_LAUNCH_UPDATE);
784 
785     return 0;
786 }
787 
788 static int
789 sev_launch_start(SevCommonState *sev_common)
790 {
791     gsize sz;
792     int ret = 1;
793     int fw_error, rc;
794     SevGuestState *sev_guest = SEV_GUEST(sev_common);
795     struct kvm_sev_launch_start start = {
796         .handle = sev_guest->handle, .policy = sev_guest->policy
797     };
798     guchar *session = NULL, *dh_cert = NULL;
799 
800     if (sev_guest->session_file) {
801         if (sev_read_file_base64(sev_guest->session_file, &session, &sz) < 0) {
802             goto out;
803         }
804         start.session_uaddr = (unsigned long)session;
805         start.session_len = sz;
806     }
807 
808     if (sev_guest->dh_cert_file) {
809         if (sev_read_file_base64(sev_guest->dh_cert_file, &dh_cert, &sz) < 0) {
810             goto out;
811         }
812         start.dh_uaddr = (unsigned long)dh_cert;
813         start.dh_len = sz;
814     }
815 
816     trace_kvm_sev_launch_start(start.policy, session, dh_cert);
817     rc = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_START, &start, &fw_error);
818     if (rc < 0) {
819         error_report("%s: LAUNCH_START ret=%d fw_error=%d '%s'",
820                 __func__, ret, fw_error, fw_error_to_str(fw_error));
821         goto out;
822     }
823 
824     sev_set_guest_state(sev_common, SEV_STATE_LAUNCH_UPDATE);
825     sev_guest->handle = start.handle;
826     ret = 0;
827 
828 out:
829     g_free(session);
830     g_free(dh_cert);
831     return ret;
832 }
833 
834 static void
835 sev_snp_cpuid_report_mismatches(SnpCpuidInfo *old,
836                                 SnpCpuidInfo *new)
837 {
838     size_t i;
839 
840     if (old->count != new->count) {
841         error_report("SEV-SNP: CPUID validation failed due to count mismatch,"
842                      "provided: %d, expected: %d", old->count, new->count);
843         return;
844     }
845 
846     for (i = 0; i < old->count; i++) {
847         SnpCpuidFunc *old_func, *new_func;
848 
849         old_func = &old->entries[i];
850         new_func = &new->entries[i];
851 
852         if (memcmp(old_func, new_func, sizeof(SnpCpuidFunc))) {
853             error_report("SEV-SNP: CPUID validation failed for function 0x%x, index: 0x%x"
854                          "provided: eax:0x%08x, ebx: 0x%08x, ecx: 0x%08x, edx: 0x%08x"
855                          "expected: eax:0x%08x, ebx: 0x%08x, ecx: 0x%08x, edx: 0x%08x",
856                          old_func->eax_in, old_func->ecx_in,
857                          old_func->eax, old_func->ebx, old_func->ecx, old_func->edx,
858                          new_func->eax, new_func->ebx, new_func->ecx, new_func->edx);
859         }
860     }
861 }
862 
863 static const char *
864 snp_page_type_to_str(int type)
865 {
866     switch (type) {
867     case KVM_SEV_SNP_PAGE_TYPE_NORMAL: return "Normal";
868     case KVM_SEV_SNP_PAGE_TYPE_ZERO: return "Zero";
869     case KVM_SEV_SNP_PAGE_TYPE_UNMEASURED: return "Unmeasured";
870     case KVM_SEV_SNP_PAGE_TYPE_SECRETS: return "Secrets";
871     case KVM_SEV_SNP_PAGE_TYPE_CPUID: return "Cpuid";
872     default: return "unknown";
873     }
874 }
875 
876 static int
877 sev_snp_launch_update(SevSnpGuestState *sev_snp_guest,
878                       SevLaunchUpdateData *data)
879 {
880     int ret, fw_error;
881     SnpCpuidInfo snp_cpuid_info;
882     struct kvm_sev_snp_launch_update update = {0};
883 
884     if (!data->hva || !data->len) {
885         error_report("SNP_LAUNCH_UPDATE called with invalid address"
886                      "/ length: %p / %lx",
887                      data->hva, data->len);
888         return 1;
889     }
890 
891     if (data->type == KVM_SEV_SNP_PAGE_TYPE_CPUID) {
892         /* Save a copy for comparison in case the LAUNCH_UPDATE fails */
893         memcpy(&snp_cpuid_info, data->hva, sizeof(snp_cpuid_info));
894     }
895 
896     update.uaddr = (__u64)(unsigned long)data->hva;
897     update.gfn_start = data->gpa >> TARGET_PAGE_BITS;
898     update.len = data->len;
899     update.type = data->type;
900 
901     /*
902      * KVM_SEV_SNP_LAUNCH_UPDATE requires that GPA ranges have the private
903      * memory attribute set in advance.
904      */
905     ret = kvm_set_memory_attributes_private(data->gpa, data->len);
906     if (ret) {
907         error_report("SEV-SNP: failed to configure initial"
908                      "private guest memory");
909         goto out;
910     }
911 
912     while (update.len || ret == -EAGAIN) {
913         trace_kvm_sev_snp_launch_update(update.uaddr, update.gfn_start <<
914                                         TARGET_PAGE_BITS, update.len,
915                                         snp_page_type_to_str(update.type));
916 
917         ret = sev_ioctl(SEV_COMMON(sev_snp_guest)->sev_fd,
918                         KVM_SEV_SNP_LAUNCH_UPDATE,
919                         &update, &fw_error);
920         if (ret && ret != -EAGAIN) {
921             error_report("SNP_LAUNCH_UPDATE ret=%d fw_error=%d '%s'",
922                          ret, fw_error, fw_error_to_str(fw_error));
923 
924             if (data->type == KVM_SEV_SNP_PAGE_TYPE_CPUID) {
925                 sev_snp_cpuid_report_mismatches(&snp_cpuid_info, data->hva);
926                 error_report("SEV-SNP: failed update CPUID page");
927             }
928             break;
929         }
930     }
931 
932 out:
933     if (!ret && update.gfn_start << TARGET_PAGE_BITS != data->gpa + data->len) {
934         error_report("SEV-SNP: expected update of GPA range %lx-%lx,"
935                      "got GPA range %lx-%llx",
936                      data->gpa, data->gpa + data->len, data->gpa,
937                      update.gfn_start << TARGET_PAGE_BITS);
938         ret = -EIO;
939     }
940 
941     return ret;
942 }
943 
944 static int
945 sev_launch_update_data(SevCommonState *sev_common, hwaddr gpa, uint8_t *addr, uint64_t len)
946 {
947     int ret, fw_error;
948     struct kvm_sev_launch_update_data update;
949 
950     if (!addr || !len) {
951         return 1;
952     }
953 
954     update.uaddr = (uintptr_t)addr;
955     update.len = len;
956     trace_kvm_sev_launch_update_data(addr, len);
957     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_UPDATE_DATA,
958                     &update, &fw_error);
959     if (ret) {
960         error_report("%s: LAUNCH_UPDATE ret=%d fw_error=%d '%s'",
961                 __func__, ret, fw_error, fw_error_to_str(fw_error));
962     }
963 
964     return ret;
965 }
966 
967 static int
968 sev_launch_update_vmsa(SevGuestState *sev_guest)
969 {
970     int ret, fw_error;
971 
972     ret = sev_ioctl(SEV_COMMON(sev_guest)->sev_fd, KVM_SEV_LAUNCH_UPDATE_VMSA,
973                     NULL, &fw_error);
974     if (ret) {
975         error_report("%s: LAUNCH_UPDATE_VMSA ret=%d fw_error=%d '%s'",
976                 __func__, ret, fw_error, fw_error_to_str(fw_error));
977     }
978 
979     return ret;
980 }
981 
982 static void
983 sev_launch_get_measure(Notifier *notifier, void *unused)
984 {
985     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
986     SevGuestState *sev_guest = SEV_GUEST(sev_common);
987     int ret, error;
988     g_autofree guchar *data = NULL;
989     struct kvm_sev_launch_measure measurement = {};
990 
991     if (!sev_check_state(sev_common, SEV_STATE_LAUNCH_UPDATE)) {
992         return;
993     }
994 
995     if (sev_es_enabled()) {
996         /* measure all the VM save areas before getting launch_measure */
997         ret = sev_launch_update_vmsa(sev_guest);
998         if (ret) {
999             exit(1);
1000         }
1001         kvm_mark_guest_state_protected();
1002     }
1003 
1004     /* query the measurement blob length */
1005     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_MEASURE,
1006                     &measurement, &error);
1007     if (!measurement.len) {
1008         error_report("%s: LAUNCH_MEASURE ret=%d fw_error=%d '%s'",
1009                      __func__, ret, error, fw_error_to_str(errno));
1010         return;
1011     }
1012 
1013     data = g_new0(guchar, measurement.len);
1014     measurement.uaddr = (unsigned long)data;
1015 
1016     /* get the measurement blob */
1017     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_MEASURE,
1018                     &measurement, &error);
1019     if (ret) {
1020         error_report("%s: LAUNCH_MEASURE ret=%d fw_error=%d '%s'",
1021                      __func__, ret, error, fw_error_to_str(errno));
1022         return;
1023     }
1024 
1025     sev_set_guest_state(sev_common, SEV_STATE_LAUNCH_SECRET);
1026 
1027     /* encode the measurement value and emit the event */
1028     sev_guest->measurement = g_base64_encode(data, measurement.len);
1029     trace_kvm_sev_launch_measurement(sev_guest->measurement);
1030 }
1031 
1032 static char *sev_get_launch_measurement(void)
1033 {
1034     ConfidentialGuestSupport *cgs = MACHINE(qdev_get_machine())->cgs;
1035     SevGuestState *sev_guest =
1036         (SevGuestState *)object_dynamic_cast(OBJECT(cgs), TYPE_SEV_GUEST);
1037 
1038     if (sev_guest &&
1039         SEV_COMMON(sev_guest)->state >= SEV_STATE_LAUNCH_SECRET) {
1040         return g_strdup(sev_guest->measurement);
1041     }
1042 
1043     return NULL;
1044 }
1045 
1046 SevLaunchMeasureInfo *qmp_query_sev_launch_measure(Error **errp)
1047 {
1048     char *data;
1049     SevLaunchMeasureInfo *info;
1050 
1051     data = sev_get_launch_measurement();
1052     if (!data) {
1053         error_setg(errp, "SEV launch measurement is not available");
1054         return NULL;
1055     }
1056 
1057     info = g_malloc0(sizeof(*info));
1058     info->data = data;
1059 
1060     return info;
1061 }
1062 
1063 static Notifier sev_machine_done_notify = {
1064     .notify = sev_launch_get_measure,
1065 };
1066 
1067 static void
1068 sev_launch_finish(SevCommonState *sev_common)
1069 {
1070     int ret, error;
1071 
1072     trace_kvm_sev_launch_finish();
1073     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_FINISH, 0,
1074                     &error);
1075     if (ret) {
1076         error_report("%s: LAUNCH_FINISH ret=%d fw_error=%d '%s'",
1077                      __func__, ret, error, fw_error_to_str(error));
1078         exit(1);
1079     }
1080 
1081     sev_set_guest_state(sev_common, SEV_STATE_RUNNING);
1082 
1083     /* add migration blocker */
1084     error_setg(&sev_mig_blocker,
1085                "SEV: Migration is not implemented");
1086     migrate_add_blocker(&sev_mig_blocker, &error_fatal);
1087 }
1088 
1089 static int
1090 snp_launch_update_data(uint64_t gpa, void *hva,
1091                        uint32_t len, int type)
1092 {
1093     SevLaunchUpdateData *data;
1094 
1095     data = g_new0(SevLaunchUpdateData, 1);
1096     data->gpa = gpa;
1097     data->hva = hva;
1098     data->len = len;
1099     data->type = type;
1100 
1101     QTAILQ_INSERT_TAIL(&launch_update, data, next);
1102 
1103     return 0;
1104 }
1105 
1106 static int
1107 sev_snp_launch_update_data(SevCommonState *sev_common, hwaddr gpa,
1108                            uint8_t *ptr, uint64_t len)
1109 {
1110        int ret = snp_launch_update_data(gpa, ptr, len,
1111                                          KVM_SEV_SNP_PAGE_TYPE_NORMAL);
1112        return ret;
1113 }
1114 
1115 static int
1116 sev_snp_cpuid_info_fill(SnpCpuidInfo *snp_cpuid_info,
1117                         const KvmCpuidInfo *kvm_cpuid_info)
1118 {
1119     size_t i;
1120 
1121     if (kvm_cpuid_info->cpuid.nent > SNP_CPUID_FUNCTION_MAXCOUNT) {
1122         error_report("SEV-SNP: CPUID entry count (%d) exceeds max (%d)",
1123                      kvm_cpuid_info->cpuid.nent, SNP_CPUID_FUNCTION_MAXCOUNT);
1124         return -1;
1125     }
1126 
1127     memset(snp_cpuid_info, 0, sizeof(*snp_cpuid_info));
1128 
1129     for (i = 0; i < kvm_cpuid_info->cpuid.nent; i++) {
1130         const struct kvm_cpuid_entry2 *kvm_cpuid_entry;
1131         SnpCpuidFunc *snp_cpuid_entry;
1132 
1133         kvm_cpuid_entry = &kvm_cpuid_info->entries[i];
1134         snp_cpuid_entry = &snp_cpuid_info->entries[i];
1135 
1136         snp_cpuid_entry->eax_in = kvm_cpuid_entry->function;
1137         if (kvm_cpuid_entry->flags == KVM_CPUID_FLAG_SIGNIFCANT_INDEX) {
1138             snp_cpuid_entry->ecx_in = kvm_cpuid_entry->index;
1139         }
1140         snp_cpuid_entry->eax = kvm_cpuid_entry->eax;
1141         snp_cpuid_entry->ebx = kvm_cpuid_entry->ebx;
1142         snp_cpuid_entry->ecx = kvm_cpuid_entry->ecx;
1143         snp_cpuid_entry->edx = kvm_cpuid_entry->edx;
1144 
1145         /*
1146          * Guest kernels will calculate EBX themselves using the 0xD
1147          * subfunctions corresponding to the individual XSAVE areas, so only
1148          * encode the base XSAVE size in the initial leaves, corresponding
1149          * to the initial XCR0=1 state.
1150          */
1151         if (snp_cpuid_entry->eax_in == 0xD &&
1152             (snp_cpuid_entry->ecx_in == 0x0 || snp_cpuid_entry->ecx_in == 0x1)) {
1153             snp_cpuid_entry->ebx = 0x240;
1154             snp_cpuid_entry->xcr0_in = 1;
1155             snp_cpuid_entry->xss_in = 0;
1156         }
1157     }
1158 
1159     snp_cpuid_info->count = i;
1160 
1161     return 0;
1162 }
1163 
1164 static int
1165 snp_launch_update_cpuid(uint32_t cpuid_addr, void *hva, uint32_t cpuid_len)
1166 {
1167     KvmCpuidInfo kvm_cpuid_info = {0};
1168     SnpCpuidInfo snp_cpuid_info;
1169     CPUState *cs = first_cpu;
1170     int ret;
1171     uint32_t i = 0;
1172 
1173     assert(sizeof(snp_cpuid_info) <= cpuid_len);
1174 
1175     /* get the cpuid list from KVM */
1176     do {
1177         kvm_cpuid_info.cpuid.nent = ++i;
1178         ret = kvm_vcpu_ioctl(cs, KVM_GET_CPUID2, &kvm_cpuid_info);
1179     } while (ret == -E2BIG);
1180 
1181     if (ret) {
1182         error_report("SEV-SNP: unable to query CPUID values for CPU: '%s'",
1183                      strerror(-ret));
1184         return 1;
1185     }
1186 
1187     ret = sev_snp_cpuid_info_fill(&snp_cpuid_info, &kvm_cpuid_info);
1188     if (ret) {
1189         error_report("SEV-SNP: failed to generate CPUID table information");
1190         return 1;
1191     }
1192 
1193     memcpy(hva, &snp_cpuid_info, sizeof(snp_cpuid_info));
1194 
1195     return snp_launch_update_data(cpuid_addr, hva, cpuid_len,
1196                                   KVM_SEV_SNP_PAGE_TYPE_CPUID);
1197 }
1198 
1199 static int
1200 snp_launch_update_kernel_hashes(SevSnpGuestState *sev_snp, uint32_t addr,
1201                                 void *hva, uint32_t len)
1202 {
1203     int type = KVM_SEV_SNP_PAGE_TYPE_ZERO;
1204     if (sev_snp->parent_obj.kernel_hashes) {
1205         assert(sev_snp->kernel_hashes_data);
1206         assert((sev_snp->kernel_hashes_offset +
1207                 sizeof(*sev_snp->kernel_hashes_data)) <= len);
1208         memset(hva, 0, len);
1209         memcpy(hva + sev_snp->kernel_hashes_offset, sev_snp->kernel_hashes_data,
1210                sizeof(*sev_snp->kernel_hashes_data));
1211         type = KVM_SEV_SNP_PAGE_TYPE_NORMAL;
1212     }
1213     return snp_launch_update_data(addr, hva, len, type);
1214 }
1215 
1216 static int
1217 snp_metadata_desc_to_page_type(int desc_type)
1218 {
1219     switch (desc_type) {
1220     /* Add the umeasured prevalidated pages as a zero page */
1221     case SEV_DESC_TYPE_SNP_SEC_MEM: return KVM_SEV_SNP_PAGE_TYPE_ZERO;
1222     case SEV_DESC_TYPE_SNP_SECRETS: return KVM_SEV_SNP_PAGE_TYPE_SECRETS;
1223     case SEV_DESC_TYPE_CPUID: return KVM_SEV_SNP_PAGE_TYPE_CPUID;
1224     default:
1225          return KVM_SEV_SNP_PAGE_TYPE_ZERO;
1226     }
1227 }
1228 
1229 static void
1230 snp_populate_metadata_pages(SevSnpGuestState *sev_snp,
1231                             OvmfSevMetadata *metadata)
1232 {
1233     OvmfSevMetadataDesc *desc;
1234     int type, ret, i;
1235     void *hva;
1236     MemoryRegion *mr = NULL;
1237 
1238     for (i = 0; i < metadata->num_desc; i++) {
1239         desc = &metadata->descs[i];
1240 
1241         type = snp_metadata_desc_to_page_type(desc->type);
1242 
1243         hva = gpa2hva(&mr, desc->base, desc->len, NULL);
1244         if (!hva) {
1245             error_report("%s: Failed to get HVA for GPA 0x%x sz 0x%x",
1246                          __func__, desc->base, desc->len);
1247             exit(1);
1248         }
1249 
1250         if (type == KVM_SEV_SNP_PAGE_TYPE_CPUID) {
1251             ret = snp_launch_update_cpuid(desc->base, hva, desc->len);
1252         } else if (desc->type == SEV_DESC_TYPE_SNP_KERNEL_HASHES) {
1253             ret = snp_launch_update_kernel_hashes(sev_snp, desc->base, hva,
1254                                                   desc->len);
1255         } else {
1256             ret = snp_launch_update_data(desc->base, hva, desc->len, type);
1257         }
1258 
1259         if (ret) {
1260             error_report("%s: Failed to add metadata page gpa 0x%x+%x type %d",
1261                          __func__, desc->base, desc->len, desc->type);
1262             exit(1);
1263         }
1264     }
1265 }
1266 
1267 static void
1268 sev_snp_launch_finish(SevCommonState *sev_common)
1269 {
1270     int ret, error;
1271     Error *local_err = NULL;
1272     OvmfSevMetadata *metadata;
1273     SevLaunchUpdateData *data;
1274     SevSnpGuestState *sev_snp = SEV_SNP_GUEST(sev_common);
1275     struct kvm_sev_snp_launch_finish *finish = &sev_snp->kvm_finish_conf;
1276 
1277     /*
1278      * To boot the SNP guest, the hypervisor is required to populate the CPUID
1279      * and Secrets page before finalizing the launch flow. The location of
1280      * the secrets and CPUID page is available through the OVMF metadata GUID.
1281      */
1282     metadata = pc_system_get_ovmf_sev_metadata_ptr();
1283     if (metadata == NULL) {
1284         error_report("%s: Failed to locate SEV metadata header", __func__);
1285         exit(1);
1286     }
1287 
1288     /* Populate all the metadata pages */
1289     snp_populate_metadata_pages(sev_snp, metadata);
1290 
1291     QTAILQ_FOREACH(data, &launch_update, next) {
1292         ret = sev_snp_launch_update(sev_snp, data);
1293         if (ret) {
1294             exit(1);
1295         }
1296     }
1297 
1298     trace_kvm_sev_snp_launch_finish(sev_snp->id_block, sev_snp->id_auth,
1299                                     sev_snp->host_data);
1300     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_SNP_LAUNCH_FINISH,
1301                     finish, &error);
1302     if (ret) {
1303         error_report("SNP_LAUNCH_FINISH ret=%d fw_error=%d '%s'",
1304                      ret, error, fw_error_to_str(error));
1305         exit(1);
1306     }
1307 
1308     kvm_mark_guest_state_protected();
1309     sev_set_guest_state(sev_common, SEV_STATE_RUNNING);
1310 
1311     /* add migration blocker */
1312     error_setg(&sev_mig_blocker,
1313                "SEV-SNP: Migration is not implemented");
1314     ret = migrate_add_blocker(&sev_mig_blocker, &local_err);
1315     if (local_err) {
1316         error_report_err(local_err);
1317         error_free(sev_mig_blocker);
1318         exit(1);
1319     }
1320 }
1321 
1322 
1323 static void
1324 sev_vm_state_change(void *opaque, bool running, RunState state)
1325 {
1326     SevCommonState *sev_common = opaque;
1327     SevCommonStateClass *klass = SEV_COMMON_GET_CLASS(opaque);
1328 
1329     if (running) {
1330         if (!sev_check_state(sev_common, SEV_STATE_RUNNING)) {
1331             klass->launch_finish(sev_common);
1332         }
1333     }
1334 }
1335 
1336 static int sev_kvm_type(X86ConfidentialGuest *cg)
1337 {
1338     SevCommonState *sev_common = SEV_COMMON(cg);
1339     SevGuestState *sev_guest = SEV_GUEST(sev_common);
1340     int kvm_type;
1341 
1342     if (sev_common->kvm_type != -1) {
1343         goto out;
1344     }
1345 
1346     kvm_type = (sev_guest->policy & SEV_POLICY_ES) ?
1347                 KVM_X86_SEV_ES_VM : KVM_X86_SEV_VM;
1348     if (kvm_is_vm_type_supported(kvm_type) && !sev_guest->legacy_vm_type) {
1349         sev_common->kvm_type = kvm_type;
1350     } else {
1351         sev_common->kvm_type = KVM_X86_DEFAULT_VM;
1352     }
1353 
1354 out:
1355     return sev_common->kvm_type;
1356 }
1357 
1358 static int sev_snp_kvm_type(X86ConfidentialGuest *cg)
1359 {
1360     return KVM_X86_SNP_VM;
1361 }
1362 
1363 static int sev_common_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
1364 {
1365     char *devname;
1366     int ret, fw_error, cmd;
1367     uint32_t ebx;
1368     uint32_t host_cbitpos;
1369     struct sev_user_data_status status = {};
1370     SevCommonState *sev_common = SEV_COMMON(cgs);
1371     SevCommonStateClass *klass = SEV_COMMON_GET_CLASS(cgs);
1372     X86ConfidentialGuestClass *x86_klass =
1373                                X86_CONFIDENTIAL_GUEST_GET_CLASS(cgs);
1374 
1375     sev_common->state = SEV_STATE_UNINIT;
1376 
1377     host_cpuid(0x8000001F, 0, NULL, &ebx, NULL, NULL);
1378     host_cbitpos = ebx & 0x3f;
1379 
1380     /*
1381      * The cbitpos value will be placed in bit positions 5:0 of the EBX
1382      * register of CPUID 0x8000001F. No need to verify the range as the
1383      * comparison against the host value accomplishes that.
1384      */
1385     if (host_cbitpos != sev_common->cbitpos) {
1386         error_setg(errp, "%s: cbitpos check failed, host '%d' requested '%d'",
1387                    __func__, host_cbitpos, sev_common->cbitpos);
1388         return -1;
1389     }
1390 
1391     /*
1392      * The reduced-phys-bits value will be placed in bit positions 11:6 of
1393      * the EBX register of CPUID 0x8000001F, so verify the supplied value
1394      * is in the range of 1 to 63.
1395      */
1396     if (sev_common->reduced_phys_bits < 1 ||
1397         sev_common->reduced_phys_bits > 63) {
1398         error_setg(errp, "%s: reduced_phys_bits check failed,"
1399                    " it should be in the range of 1 to 63, requested '%d'",
1400                    __func__, sev_common->reduced_phys_bits);
1401         return -1;
1402     }
1403 
1404     devname = object_property_get_str(OBJECT(sev_common), "sev-device", NULL);
1405     sev_common->sev_fd = open(devname, O_RDWR);
1406     if (sev_common->sev_fd < 0) {
1407         error_setg(errp, "%s: Failed to open %s '%s'", __func__,
1408                    devname, strerror(errno));
1409         g_free(devname);
1410         return -1;
1411     }
1412     g_free(devname);
1413 
1414     ret = sev_platform_ioctl(sev_common->sev_fd, SEV_PLATFORM_STATUS, &status,
1415                              &fw_error);
1416     if (ret) {
1417         error_setg(errp, "%s: failed to get platform status ret=%d "
1418                    "fw_error='%d: %s'", __func__, ret, fw_error,
1419                    fw_error_to_str(fw_error));
1420         return -1;
1421     }
1422     sev_common->build_id = status.build;
1423     sev_common->api_major = status.api_major;
1424     sev_common->api_minor = status.api_minor;
1425 
1426     if (sev_es_enabled()) {
1427         if (!kvm_kernel_irqchip_allowed()) {
1428             error_setg(errp, "%s: SEV-ES guests require in-kernel irqchip"
1429                        "support", __func__);
1430             return -1;
1431         }
1432     }
1433 
1434     if (sev_es_enabled() && !sev_snp_enabled()) {
1435         if (!(status.flags & SEV_STATUS_FLAGS_CONFIG_ES)) {
1436             error_setg(errp, "%s: guest policy requires SEV-ES, but "
1437                          "host SEV-ES support unavailable",
1438                          __func__);
1439             return -1;
1440         }
1441     }
1442 
1443     trace_kvm_sev_init();
1444     if (x86_klass->kvm_type(X86_CONFIDENTIAL_GUEST(sev_common)) == KVM_X86_DEFAULT_VM) {
1445         cmd = sev_es_enabled() ? KVM_SEV_ES_INIT : KVM_SEV_INIT;
1446 
1447         ret = sev_ioctl(sev_common->sev_fd, cmd, NULL, &fw_error);
1448     } else {
1449         struct kvm_sev_init args = { 0 };
1450 
1451         ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_INIT2, &args, &fw_error);
1452     }
1453 
1454     if (ret) {
1455         error_setg(errp, "%s: failed to initialize ret=%d fw_error=%d '%s'",
1456                    __func__, ret, fw_error, fw_error_to_str(fw_error));
1457         return -1;
1458     }
1459 
1460     ret = klass->launch_start(sev_common);
1461 
1462     if (ret) {
1463         error_setg(errp, "%s: failed to create encryption context", __func__);
1464         return -1;
1465     }
1466 
1467     if (klass->kvm_init && klass->kvm_init(cgs, errp)) {
1468         return -1;
1469     }
1470 
1471     qemu_add_vm_change_state_handler(sev_vm_state_change, sev_common);
1472 
1473     cgs->ready = true;
1474 
1475     return 0;
1476 }
1477 
1478 static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
1479 {
1480      int ret;
1481 
1482     /*
1483      * SEV/SEV-ES rely on pinned memory to back guest RAM so discarding
1484      * isn't actually possible. With SNP, only guest_memfd pages are used
1485      * for private guest memory, so discarding of shared memory is still
1486      * possible..
1487      */
1488     ret = ram_block_discard_disable(true);
1489     if (ret) {
1490         error_setg(errp, "%s: cannot disable RAM discard", __func__);
1491         return -1;
1492     }
1493 
1494     /*
1495      * SEV uses these notifiers to register/pin pages prior to guest use,
1496      * but SNP relies on guest_memfd for private pages, which has its
1497      * own internal mechanisms for registering/pinning private memory.
1498      */
1499     ram_block_notifier_add(&sev_ram_notifier);
1500 
1501     /*
1502      * The machine done notify event is used for SEV guests to get the
1503      * measurement of the encrypted images. When SEV-SNP is enabled, the
1504      * measurement is part of the guest attestation process where it can
1505      * be collected without any reliance on the VMM. So skip registering
1506      * the notifier for SNP in favor of using guest attestation instead.
1507      */
1508     qemu_add_machine_init_done_notifier(&sev_machine_done_notify);
1509 
1510     return 0;
1511 }
1512 
1513 static int sev_snp_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
1514 {
1515     MachineState *ms = MACHINE(qdev_get_machine());
1516     X86MachineState *x86ms = X86_MACHINE(ms);
1517 
1518     if (x86ms->smm == ON_OFF_AUTO_AUTO) {
1519         x86ms->smm = ON_OFF_AUTO_OFF;
1520     } else if (x86ms->smm == ON_OFF_AUTO_ON) {
1521         error_setg(errp, "SEV-SNP does not support SMM.");
1522         return -1;
1523     }
1524 
1525     return 0;
1526 }
1527 
1528 int
1529 sev_encrypt_flash(hwaddr gpa, uint8_t *ptr, uint64_t len, Error **errp)
1530 {
1531     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1532     SevCommonStateClass *klass = SEV_COMMON_GET_CLASS(sev_common);
1533 
1534     if (!sev_common) {
1535         return 0;
1536     }
1537 
1538     /* if SEV is in update state then encrypt the data else do nothing */
1539     if (sev_check_state(sev_common, SEV_STATE_LAUNCH_UPDATE)) {
1540         int ret;
1541 
1542         ret = klass->launch_update_data(sev_common, gpa, ptr, len);
1543         if (ret < 0) {
1544             error_setg(errp, "SEV: Failed to encrypt pflash rom");
1545             return ret;
1546         }
1547     }
1548 
1549     return 0;
1550 }
1551 
1552 int sev_inject_launch_secret(const char *packet_hdr, const char *secret,
1553                              uint64_t gpa, Error **errp)
1554 {
1555     ERRP_GUARD();
1556     struct kvm_sev_launch_secret input;
1557     g_autofree guchar *data = NULL, *hdr = NULL;
1558     int error, ret = 1;
1559     void *hva;
1560     gsize hdr_sz = 0, data_sz = 0;
1561     MemoryRegion *mr = NULL;
1562     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1563 
1564     if (!sev_common) {
1565         error_setg(errp, "SEV not enabled for guest");
1566         return 1;
1567     }
1568 
1569     /* secret can be injected only in this state */
1570     if (!sev_check_state(sev_common, SEV_STATE_LAUNCH_SECRET)) {
1571         error_setg(errp, "SEV: Not in correct state. (LSECRET) %x",
1572                    sev_common->state);
1573         return 1;
1574     }
1575 
1576     hdr = g_base64_decode(packet_hdr, &hdr_sz);
1577     if (!hdr || !hdr_sz) {
1578         error_setg(errp, "SEV: Failed to decode sequence header");
1579         return 1;
1580     }
1581 
1582     data = g_base64_decode(secret, &data_sz);
1583     if (!data || !data_sz) {
1584         error_setg(errp, "SEV: Failed to decode data");
1585         return 1;
1586     }
1587 
1588     hva = gpa2hva(&mr, gpa, data_sz, errp);
1589     if (!hva) {
1590         error_prepend(errp, "SEV: Failed to calculate guest address: ");
1591         return 1;
1592     }
1593 
1594     input.hdr_uaddr = (uint64_t)(unsigned long)hdr;
1595     input.hdr_len = hdr_sz;
1596 
1597     input.trans_uaddr = (uint64_t)(unsigned long)data;
1598     input.trans_len = data_sz;
1599 
1600     input.guest_uaddr = (uint64_t)(unsigned long)hva;
1601     input.guest_len = data_sz;
1602 
1603     trace_kvm_sev_launch_secret(gpa, input.guest_uaddr,
1604                                 input.trans_uaddr, input.trans_len);
1605 
1606     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_SECRET,
1607                     &input, &error);
1608     if (ret) {
1609         error_setg(errp, "SEV: failed to inject secret ret=%d fw_error=%d '%s'",
1610                      ret, error, fw_error_to_str(error));
1611         return ret;
1612     }
1613 
1614     return 0;
1615 }
1616 
1617 #define SEV_SECRET_GUID "4c2eb361-7d9b-4cc3-8081-127c90d3d294"
1618 struct sev_secret_area {
1619     uint32_t base;
1620     uint32_t size;
1621 };
1622 
1623 void qmp_sev_inject_launch_secret(const char *packet_hdr,
1624                                   const char *secret,
1625                                   bool has_gpa, uint64_t gpa,
1626                                   Error **errp)
1627 {
1628     if (!sev_enabled()) {
1629         error_setg(errp, "SEV not enabled for guest");
1630         return;
1631     }
1632     if (!has_gpa) {
1633         uint8_t *data;
1634         struct sev_secret_area *area;
1635 
1636         if (!pc_system_ovmf_table_find(SEV_SECRET_GUID, &data, NULL)) {
1637             error_setg(errp, "SEV: no secret area found in OVMF,"
1638                        " gpa must be specified.");
1639             return;
1640         }
1641         area = (struct sev_secret_area *)data;
1642         gpa = area->base;
1643     }
1644 
1645     sev_inject_launch_secret(packet_hdr, secret, gpa, errp);
1646 }
1647 
1648 static int
1649 sev_es_parse_reset_block(SevInfoBlock *info, uint32_t *addr)
1650 {
1651     if (!info->reset_addr) {
1652         error_report("SEV-ES reset address is zero");
1653         return 1;
1654     }
1655 
1656     *addr = info->reset_addr;
1657 
1658     return 0;
1659 }
1660 
1661 static int
1662 sev_es_find_reset_vector(void *flash_ptr, uint64_t flash_size,
1663                          uint32_t *addr)
1664 {
1665     QemuUUID info_guid, *guid;
1666     SevInfoBlock *info;
1667     uint8_t *data;
1668     uint16_t *len;
1669 
1670     /*
1671      * Initialize the address to zero. An address of zero with a successful
1672      * return code indicates that SEV-ES is not active.
1673      */
1674     *addr = 0;
1675 
1676     /*
1677      * Extract the AP reset vector for SEV-ES guests by locating the SEV GUID.
1678      * The SEV GUID is located on its own (original implementation) or within
1679      * the Firmware GUID Table (new implementation), either of which are
1680      * located 32 bytes from the end of the flash.
1681      *
1682      * Check the Firmware GUID Table first.
1683      */
1684     if (pc_system_ovmf_table_find(SEV_INFO_BLOCK_GUID, &data, NULL)) {
1685         return sev_es_parse_reset_block((SevInfoBlock *)data, addr);
1686     }
1687 
1688     /*
1689      * SEV info block not found in the Firmware GUID Table (or there isn't
1690      * a Firmware GUID Table), fall back to the original implementation.
1691      */
1692     data = flash_ptr + flash_size - 0x20;
1693 
1694     qemu_uuid_parse(SEV_INFO_BLOCK_GUID, &info_guid);
1695     info_guid = qemu_uuid_bswap(info_guid); /* GUIDs are LE */
1696 
1697     guid = (QemuUUID *)(data - sizeof(info_guid));
1698     if (!qemu_uuid_is_equal(guid, &info_guid)) {
1699         error_report("SEV information block/Firmware GUID Table block not found in pflash rom");
1700         return 1;
1701     }
1702 
1703     len = (uint16_t *)((uint8_t *)guid - sizeof(*len));
1704     info = (SevInfoBlock *)(data - le16_to_cpu(*len));
1705 
1706     return sev_es_parse_reset_block(info, addr);
1707 }
1708 
1709 void sev_es_set_reset_vector(CPUState *cpu)
1710 {
1711     X86CPU *x86;
1712     CPUX86State *env;
1713     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1714 
1715     /* Only update if we have valid reset information */
1716     if (!sev_common || !sev_common->reset_data_valid) {
1717         return;
1718     }
1719 
1720     /* Do not update the BSP reset state */
1721     if (cpu->cpu_index == 0) {
1722         return;
1723     }
1724 
1725     x86 = X86_CPU(cpu);
1726     env = &x86->env;
1727 
1728     cpu_x86_load_seg_cache(env, R_CS, 0xf000, sev_common->reset_cs, 0xffff,
1729                            DESC_P_MASK | DESC_S_MASK | DESC_CS_MASK |
1730                            DESC_R_MASK | DESC_A_MASK);
1731 
1732     env->eip = sev_common->reset_ip;
1733 }
1734 
1735 int sev_es_save_reset_vector(void *flash_ptr, uint64_t flash_size)
1736 {
1737     CPUState *cpu;
1738     uint32_t addr;
1739     int ret;
1740     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1741 
1742     if (!sev_es_enabled()) {
1743         return 0;
1744     }
1745 
1746     addr = 0;
1747     ret = sev_es_find_reset_vector(flash_ptr, flash_size,
1748                                    &addr);
1749     if (ret) {
1750         return ret;
1751     }
1752 
1753     if (addr) {
1754         sev_common->reset_cs = addr & 0xffff0000;
1755         sev_common->reset_ip = addr & 0x0000ffff;
1756         sev_common->reset_data_valid = true;
1757 
1758         CPU_FOREACH(cpu) {
1759             sev_es_set_reset_vector(cpu);
1760         }
1761     }
1762 
1763     return 0;
1764 }
1765 
1766 static const QemuUUID sev_hash_table_header_guid = {
1767     .data = UUID_LE(0x9438d606, 0x4f22, 0x4cc9, 0xb4, 0x79, 0xa7, 0x93,
1768                     0xd4, 0x11, 0xfd, 0x21)
1769 };
1770 
1771 static const QemuUUID sev_kernel_entry_guid = {
1772     .data = UUID_LE(0x4de79437, 0xabd2, 0x427f, 0xb8, 0x35, 0xd5, 0xb1,
1773                     0x72, 0xd2, 0x04, 0x5b)
1774 };
1775 static const QemuUUID sev_initrd_entry_guid = {
1776     .data = UUID_LE(0x44baf731, 0x3a2f, 0x4bd7, 0x9a, 0xf1, 0x41, 0xe2,
1777                     0x91, 0x69, 0x78, 0x1d)
1778 };
1779 static const QemuUUID sev_cmdline_entry_guid = {
1780     .data = UUID_LE(0x97d02dd8, 0xbd20, 0x4c94, 0xaa, 0x78, 0xe7, 0x71,
1781                     0x4d, 0x36, 0xab, 0x2a)
1782 };
1783 
1784 static bool build_kernel_loader_hashes(PaddedSevHashTable *padded_ht,
1785                                        SevKernelLoaderContext *ctx,
1786                                        Error **errp)
1787 {
1788     SevHashTable *ht;
1789     uint8_t cmdline_hash[HASH_SIZE];
1790     uint8_t initrd_hash[HASH_SIZE];
1791     uint8_t kernel_hash[HASH_SIZE];
1792     uint8_t *hashp;
1793     size_t hash_len = HASH_SIZE;
1794 
1795     /*
1796      * Calculate hash of kernel command-line with the terminating null byte. If
1797      * the user doesn't supply a command-line via -append, the 1-byte "\0" will
1798      * be used.
1799      */
1800     hashp = cmdline_hash;
1801     if (qcrypto_hash_bytes(QCRYPTO_HASH_ALG_SHA256, ctx->cmdline_data,
1802                            ctx->cmdline_size, &hashp, &hash_len, errp) < 0) {
1803         return false;
1804     }
1805     assert(hash_len == HASH_SIZE);
1806 
1807     /*
1808      * Calculate hash of initrd. If the user doesn't supply an initrd via
1809      * -initrd, an empty buffer will be used (ctx->initrd_size == 0).
1810      */
1811     hashp = initrd_hash;
1812     if (qcrypto_hash_bytes(QCRYPTO_HASH_ALG_SHA256, ctx->initrd_data,
1813                            ctx->initrd_size, &hashp, &hash_len, errp) < 0) {
1814         return false;
1815     }
1816     assert(hash_len == HASH_SIZE);
1817 
1818     /* Calculate hash of the kernel */
1819     hashp = kernel_hash;
1820     struct iovec iov[2] = {
1821         { .iov_base = ctx->setup_data, .iov_len = ctx->setup_size },
1822         { .iov_base = ctx->kernel_data, .iov_len = ctx->kernel_size }
1823     };
1824     if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA256, iov, ARRAY_SIZE(iov),
1825                             &hashp, &hash_len, errp) < 0) {
1826         return false;
1827     }
1828     assert(hash_len == HASH_SIZE);
1829 
1830     ht = &padded_ht->ht;
1831 
1832     ht->guid = sev_hash_table_header_guid;
1833     ht->len = sizeof(*ht);
1834 
1835     ht->cmdline.guid = sev_cmdline_entry_guid;
1836     ht->cmdline.len = sizeof(ht->cmdline);
1837     memcpy(ht->cmdline.hash, cmdline_hash, sizeof(ht->cmdline.hash));
1838 
1839     ht->initrd.guid = sev_initrd_entry_guid;
1840     ht->initrd.len = sizeof(ht->initrd);
1841     memcpy(ht->initrd.hash, initrd_hash, sizeof(ht->initrd.hash));
1842 
1843     ht->kernel.guid = sev_kernel_entry_guid;
1844     ht->kernel.len = sizeof(ht->kernel);
1845     memcpy(ht->kernel.hash, kernel_hash, sizeof(ht->kernel.hash));
1846 
1847     /* zero the excess data so the measurement can be reliably calculated */
1848     memset(padded_ht->padding, 0, sizeof(padded_ht->padding));
1849 
1850     return true;
1851 }
1852 
1853 static bool sev_snp_build_kernel_loader_hashes(SevCommonState *sev_common,
1854                                                SevHashTableDescriptor *area,
1855                                                SevKernelLoaderContext *ctx,
1856                                                Error **errp)
1857 {
1858     /*
1859      * SNP: Populate the hashes table in an area that later in
1860      * snp_launch_update_kernel_hashes() will be copied to the guest memory
1861      * and encrypted.
1862      */
1863     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(sev_common);
1864     sev_snp_guest->kernel_hashes_offset = area->base & ~TARGET_PAGE_MASK;
1865     sev_snp_guest->kernel_hashes_data = g_new0(PaddedSevHashTable, 1);
1866     return build_kernel_loader_hashes(sev_snp_guest->kernel_hashes_data, ctx, errp);
1867 }
1868 
1869 static bool sev_build_kernel_loader_hashes(SevCommonState *sev_common,
1870                                            SevHashTableDescriptor *area,
1871                                            SevKernelLoaderContext *ctx,
1872                                            Error **errp)
1873 {
1874     PaddedSevHashTable *padded_ht;
1875     hwaddr mapped_len = sizeof(*padded_ht);
1876     MemTxAttrs attrs = { 0 };
1877     bool ret = true;
1878 
1879     /*
1880      * Populate the hashes table in the guest's memory at the OVMF-designated
1881      * area for the SEV hashes table
1882      */
1883     padded_ht = address_space_map(&address_space_memory, area->base,
1884                                   &mapped_len, true, attrs);
1885     if (!padded_ht || mapped_len != sizeof(*padded_ht)) {
1886         error_setg(errp, "SEV: cannot map hashes table guest memory area");
1887         return false;
1888     }
1889 
1890     if (build_kernel_loader_hashes(padded_ht, ctx, errp)) {
1891         if (sev_encrypt_flash(area->base, (uint8_t *)padded_ht,
1892                               sizeof(*padded_ht), errp) < 0) {
1893             ret = false;
1894         }
1895     } else {
1896         ret = false;
1897     }
1898 
1899     address_space_unmap(&address_space_memory, padded_ht,
1900                         mapped_len, true, mapped_len);
1901 
1902     return ret;
1903 }
1904 
1905 /*
1906  * Add the hashes of the linux kernel/initrd/cmdline to an encrypted guest page
1907  * which is included in SEV's initial memory measurement.
1908  */
1909 bool sev_add_kernel_loader_hashes(SevKernelLoaderContext *ctx, Error **errp)
1910 {
1911     uint8_t *data;
1912     SevHashTableDescriptor *area;
1913     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1914     SevCommonStateClass *klass = SEV_COMMON_GET_CLASS(sev_common);
1915 
1916     /*
1917      * Only add the kernel hashes if the sev-guest configuration explicitly
1918      * stated kernel-hashes=on.
1919      */
1920     if (!sev_common->kernel_hashes) {
1921         return false;
1922     }
1923 
1924     if (!pc_system_ovmf_table_find(SEV_HASH_TABLE_RV_GUID, &data, NULL)) {
1925         error_setg(errp, "SEV: kernel specified but guest firmware "
1926                          "has no hashes table GUID");
1927         return false;
1928     }
1929 
1930     area = (SevHashTableDescriptor *)data;
1931     if (!area->base || area->size < sizeof(PaddedSevHashTable)) {
1932         error_setg(errp, "SEV: guest firmware hashes table area is invalid "
1933                          "(base=0x%x size=0x%x)", area->base, area->size);
1934         return false;
1935     }
1936 
1937     return klass->build_kernel_loader_hashes(sev_common, area, ctx, errp);
1938 }
1939 
1940 static char *
1941 sev_common_get_sev_device(Object *obj, Error **errp)
1942 {
1943     return g_strdup(SEV_COMMON(obj)->sev_device);
1944 }
1945 
1946 static void
1947 sev_common_set_sev_device(Object *obj, const char *value, Error **errp)
1948 {
1949     SEV_COMMON(obj)->sev_device = g_strdup(value);
1950 }
1951 
1952 static bool sev_common_get_kernel_hashes(Object *obj, Error **errp)
1953 {
1954     return SEV_COMMON(obj)->kernel_hashes;
1955 }
1956 
1957 static void sev_common_set_kernel_hashes(Object *obj, bool value, Error **errp)
1958 {
1959     SEV_COMMON(obj)->kernel_hashes = value;
1960 }
1961 
1962 static void
1963 sev_common_class_init(ObjectClass *oc, void *data)
1964 {
1965     ConfidentialGuestSupportClass *klass = CONFIDENTIAL_GUEST_SUPPORT_CLASS(oc);
1966 
1967     klass->kvm_init = sev_common_kvm_init;
1968 
1969     object_class_property_add_str(oc, "sev-device",
1970                                   sev_common_get_sev_device,
1971                                   sev_common_set_sev_device);
1972     object_class_property_set_description(oc, "sev-device",
1973             "SEV device to use");
1974     object_class_property_add_bool(oc, "kernel-hashes",
1975                                    sev_common_get_kernel_hashes,
1976                                    sev_common_set_kernel_hashes);
1977     object_class_property_set_description(oc, "kernel-hashes",
1978             "add kernel hashes to guest firmware for measured Linux boot");
1979 }
1980 
1981 static void
1982 sev_common_instance_init(Object *obj)
1983 {
1984     SevCommonState *sev_common = SEV_COMMON(obj);
1985 
1986     sev_common->kvm_type = -1;
1987 
1988     sev_common->sev_device = g_strdup(DEFAULT_SEV_DEVICE);
1989 
1990     object_property_add_uint32_ptr(obj, "cbitpos", &sev_common->cbitpos,
1991                                    OBJ_PROP_FLAG_READWRITE);
1992     object_property_add_uint32_ptr(obj, "reduced-phys-bits",
1993                                    &sev_common->reduced_phys_bits,
1994                                    OBJ_PROP_FLAG_READWRITE);
1995 }
1996 
1997 /* sev guest info common to sev/sev-es/sev-snp */
1998 static const TypeInfo sev_common_info = {
1999     .parent = TYPE_X86_CONFIDENTIAL_GUEST,
2000     .name = TYPE_SEV_COMMON,
2001     .instance_size = sizeof(SevCommonState),
2002     .instance_init = sev_common_instance_init,
2003     .class_size = sizeof(SevCommonStateClass),
2004     .class_init = sev_common_class_init,
2005     .abstract = true,
2006     .interfaces = (InterfaceInfo[]) {
2007         { TYPE_USER_CREATABLE },
2008         { }
2009     }
2010 };
2011 
2012 static char *
2013 sev_guest_get_dh_cert_file(Object *obj, Error **errp)
2014 {
2015     return g_strdup(SEV_GUEST(obj)->dh_cert_file);
2016 }
2017 
2018 static void
2019 sev_guest_set_dh_cert_file(Object *obj, const char *value, Error **errp)
2020 {
2021     SEV_GUEST(obj)->dh_cert_file = g_strdup(value);
2022 }
2023 
2024 static char *
2025 sev_guest_get_session_file(Object *obj, Error **errp)
2026 {
2027     SevGuestState *sev_guest = SEV_GUEST(obj);
2028 
2029     return sev_guest->session_file ? g_strdup(sev_guest->session_file) : NULL;
2030 }
2031 
2032 static void
2033 sev_guest_set_session_file(Object *obj, const char *value, Error **errp)
2034 {
2035     SEV_GUEST(obj)->session_file = g_strdup(value);
2036 }
2037 
2038 static bool sev_guest_get_legacy_vm_type(Object *obj, Error **errp)
2039 {
2040     return SEV_GUEST(obj)->legacy_vm_type;
2041 }
2042 
2043 static void sev_guest_set_legacy_vm_type(Object *obj, bool value, Error **errp)
2044 {
2045     SEV_GUEST(obj)->legacy_vm_type = value;
2046 }
2047 
2048 static void
2049 sev_guest_class_init(ObjectClass *oc, void *data)
2050 {
2051     SevCommonStateClass *klass = SEV_COMMON_CLASS(oc);
2052     X86ConfidentialGuestClass *x86_klass = X86_CONFIDENTIAL_GUEST_CLASS(oc);
2053 
2054     klass->build_kernel_loader_hashes = sev_build_kernel_loader_hashes;
2055     klass->launch_start = sev_launch_start;
2056     klass->launch_finish = sev_launch_finish;
2057     klass->launch_update_data = sev_launch_update_data;
2058     klass->kvm_init = sev_kvm_init;
2059     x86_klass->kvm_type = sev_kvm_type;
2060 
2061     object_class_property_add_str(oc, "dh-cert-file",
2062                                   sev_guest_get_dh_cert_file,
2063                                   sev_guest_set_dh_cert_file);
2064     object_class_property_set_description(oc, "dh-cert-file",
2065             "guest owners DH certificate (encoded with base64)");
2066     object_class_property_add_str(oc, "session-file",
2067                                   sev_guest_get_session_file,
2068                                   sev_guest_set_session_file);
2069     object_class_property_set_description(oc, "session-file",
2070             "guest owners session parameters (encoded with base64)");
2071     object_class_property_add_bool(oc, "legacy-vm-type",
2072                                    sev_guest_get_legacy_vm_type,
2073                                    sev_guest_set_legacy_vm_type);
2074     object_class_property_set_description(oc, "legacy-vm-type",
2075             "use legacy VM type to maintain measurement compatibility with older QEMU or kernel versions.");
2076 }
2077 
2078 static void
2079 sev_guest_instance_init(Object *obj)
2080 {
2081     SevGuestState *sev_guest = SEV_GUEST(obj);
2082 
2083     sev_guest->policy = DEFAULT_GUEST_POLICY;
2084     object_property_add_uint32_ptr(obj, "handle", &sev_guest->handle,
2085                                    OBJ_PROP_FLAG_READWRITE);
2086     object_property_add_uint32_ptr(obj, "policy", &sev_guest->policy,
2087                                    OBJ_PROP_FLAG_READWRITE);
2088     object_apply_compat_props(obj);
2089 }
2090 
2091 /* guest info specific sev/sev-es */
2092 static const TypeInfo sev_guest_info = {
2093     .parent = TYPE_SEV_COMMON,
2094     .name = TYPE_SEV_GUEST,
2095     .instance_size = sizeof(SevGuestState),
2096     .instance_init = sev_guest_instance_init,
2097     .class_init = sev_guest_class_init,
2098 };
2099 
2100 static void
2101 sev_snp_guest_get_policy(Object *obj, Visitor *v, const char *name,
2102                          void *opaque, Error **errp)
2103 {
2104     visit_type_uint64(v, name,
2105                       (uint64_t *)&SEV_SNP_GUEST(obj)->kvm_start_conf.policy,
2106                       errp);
2107 }
2108 
2109 static void
2110 sev_snp_guest_set_policy(Object *obj, Visitor *v, const char *name,
2111                          void *opaque, Error **errp)
2112 {
2113     visit_type_uint64(v, name,
2114                       (uint64_t *)&SEV_SNP_GUEST(obj)->kvm_start_conf.policy,
2115                       errp);
2116 }
2117 
2118 static char *
2119 sev_snp_guest_get_guest_visible_workarounds(Object *obj, Error **errp)
2120 {
2121     return g_strdup(SEV_SNP_GUEST(obj)->guest_visible_workarounds);
2122 }
2123 
2124 static void
2125 sev_snp_guest_set_guest_visible_workarounds(Object *obj, const char *value,
2126                                             Error **errp)
2127 {
2128     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2129     struct kvm_sev_snp_launch_start *start = &sev_snp_guest->kvm_start_conf;
2130     g_autofree guchar *blob;
2131     gsize len;
2132 
2133     g_free(sev_snp_guest->guest_visible_workarounds);
2134 
2135     /* store the base64 str so we don't need to re-encode in getter */
2136     sev_snp_guest->guest_visible_workarounds = g_strdup(value);
2137 
2138     blob = qbase64_decode(sev_snp_guest->guest_visible_workarounds,
2139                           -1, &len, errp);
2140     if (!blob) {
2141         return;
2142     }
2143 
2144     if (len != sizeof(start->gosvw)) {
2145         error_setg(errp, "parameter length of %lu exceeds max of %lu",
2146                    len, sizeof(start->gosvw));
2147         return;
2148     }
2149 
2150     memcpy(start->gosvw, blob, len);
2151 }
2152 
2153 static char *
2154 sev_snp_guest_get_id_block(Object *obj, Error **errp)
2155 {
2156     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2157 
2158     return g_strdup(sev_snp_guest->id_block);
2159 }
2160 
2161 static void
2162 sev_snp_guest_set_id_block(Object *obj, const char *value, Error **errp)
2163 {
2164     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2165     struct kvm_sev_snp_launch_finish *finish = &sev_snp_guest->kvm_finish_conf;
2166     gsize len;
2167 
2168     g_free(sev_snp_guest->id_block);
2169     g_free((guchar *)finish->id_block_uaddr);
2170 
2171     /* store the base64 str so we don't need to re-encode in getter */
2172     sev_snp_guest->id_block = g_strdup(value);
2173 
2174     finish->id_block_uaddr =
2175         (uint64_t)qbase64_decode(sev_snp_guest->id_block, -1, &len, errp);
2176 
2177     if (!finish->id_block_uaddr) {
2178         return;
2179     }
2180 
2181     if (len != KVM_SEV_SNP_ID_BLOCK_SIZE) {
2182         error_setg(errp, "parameter length of %lu not equal to %u",
2183                    len, KVM_SEV_SNP_ID_BLOCK_SIZE);
2184         return;
2185     }
2186 
2187     finish->id_block_en = (len) ? 1 : 0;
2188 }
2189 
2190 static char *
2191 sev_snp_guest_get_id_auth(Object *obj, Error **errp)
2192 {
2193     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2194 
2195     return g_strdup(sev_snp_guest->id_auth);
2196 }
2197 
2198 static void
2199 sev_snp_guest_set_id_auth(Object *obj, const char *value, Error **errp)
2200 {
2201     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2202     struct kvm_sev_snp_launch_finish *finish = &sev_snp_guest->kvm_finish_conf;
2203     gsize len;
2204 
2205     g_free(sev_snp_guest->id_auth);
2206     g_free((guchar *)finish->id_auth_uaddr);
2207 
2208     /* store the base64 str so we don't need to re-encode in getter */
2209     sev_snp_guest->id_auth = g_strdup(value);
2210 
2211     finish->id_auth_uaddr =
2212         (uint64_t)qbase64_decode(sev_snp_guest->id_auth, -1, &len, errp);
2213 
2214     if (!finish->id_auth_uaddr) {
2215         return;
2216     }
2217 
2218     if (len > KVM_SEV_SNP_ID_AUTH_SIZE) {
2219         error_setg(errp, "parameter length:ID_AUTH %lu exceeds max of %u",
2220                    len, KVM_SEV_SNP_ID_AUTH_SIZE);
2221         return;
2222     }
2223 }
2224 
2225 static bool
2226 sev_snp_guest_get_author_key_enabled(Object *obj, Error **errp)
2227 {
2228     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2229 
2230     return !!sev_snp_guest->kvm_finish_conf.auth_key_en;
2231 }
2232 
2233 static void
2234 sev_snp_guest_set_author_key_enabled(Object *obj, bool value, Error **errp)
2235 {
2236     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2237 
2238     sev_snp_guest->kvm_finish_conf.auth_key_en = value;
2239 }
2240 
2241 static bool
2242 sev_snp_guest_get_vcek_disabled(Object *obj, Error **errp)
2243 {
2244     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2245 
2246     return !!sev_snp_guest->kvm_finish_conf.vcek_disabled;
2247 }
2248 
2249 static void
2250 sev_snp_guest_set_vcek_disabled(Object *obj, bool value, Error **errp)
2251 {
2252     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2253 
2254     sev_snp_guest->kvm_finish_conf.vcek_disabled = value;
2255 }
2256 
2257 static char *
2258 sev_snp_guest_get_host_data(Object *obj, Error **errp)
2259 {
2260     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2261 
2262     return g_strdup(sev_snp_guest->host_data);
2263 }
2264 
2265 static void
2266 sev_snp_guest_set_host_data(Object *obj, const char *value, Error **errp)
2267 {
2268     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2269     struct kvm_sev_snp_launch_finish *finish = &sev_snp_guest->kvm_finish_conf;
2270     g_autofree guchar *blob;
2271     gsize len;
2272 
2273     g_free(sev_snp_guest->host_data);
2274 
2275     /* store the base64 str so we don't need to re-encode in getter */
2276     sev_snp_guest->host_data = g_strdup(value);
2277 
2278     blob = qbase64_decode(sev_snp_guest->host_data, -1, &len, errp);
2279 
2280     if (!blob) {
2281         return;
2282     }
2283 
2284     if (len != sizeof(finish->host_data)) {
2285         error_setg(errp, "parameter length of %lu not equal to %lu",
2286                    len, sizeof(finish->host_data));
2287         return;
2288     }
2289 
2290     memcpy(finish->host_data, blob, len);
2291 }
2292 
2293 static void
2294 sev_snp_guest_class_init(ObjectClass *oc, void *data)
2295 {
2296     SevCommonStateClass *klass = SEV_COMMON_CLASS(oc);
2297     X86ConfidentialGuestClass *x86_klass = X86_CONFIDENTIAL_GUEST_CLASS(oc);
2298 
2299     klass->build_kernel_loader_hashes = sev_snp_build_kernel_loader_hashes;
2300     klass->launch_start = sev_snp_launch_start;
2301     klass->launch_finish = sev_snp_launch_finish;
2302     klass->launch_update_data = sev_snp_launch_update_data;
2303     klass->kvm_init = sev_snp_kvm_init;
2304     x86_klass->kvm_type = sev_snp_kvm_type;
2305 
2306     object_class_property_add(oc, "policy", "uint64",
2307                               sev_snp_guest_get_policy,
2308                               sev_snp_guest_set_policy, NULL, NULL);
2309     object_class_property_add_str(oc, "guest-visible-workarounds",
2310                                   sev_snp_guest_get_guest_visible_workarounds,
2311                                   sev_snp_guest_set_guest_visible_workarounds);
2312     object_class_property_add_str(oc, "id-block",
2313                                   sev_snp_guest_get_id_block,
2314                                   sev_snp_guest_set_id_block);
2315     object_class_property_add_str(oc, "id-auth",
2316                                   sev_snp_guest_get_id_auth,
2317                                   sev_snp_guest_set_id_auth);
2318     object_class_property_add_bool(oc, "author-key-enabled",
2319                                    sev_snp_guest_get_author_key_enabled,
2320                                    sev_snp_guest_set_author_key_enabled);
2321     object_class_property_add_bool(oc, "vcek-required",
2322                                    sev_snp_guest_get_vcek_disabled,
2323                                    sev_snp_guest_set_vcek_disabled);
2324     object_class_property_add_str(oc, "host-data",
2325                                   sev_snp_guest_get_host_data,
2326                                   sev_snp_guest_set_host_data);
2327 }
2328 
2329 static void
2330 sev_snp_guest_instance_init(Object *obj)
2331 {
2332     ConfidentialGuestSupport *cgs = CONFIDENTIAL_GUEST_SUPPORT(obj);
2333     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
2334 
2335     cgs->require_guest_memfd = true;
2336 
2337     /* default init/start/finish params for kvm */
2338     sev_snp_guest->kvm_start_conf.policy = DEFAULT_SEV_SNP_POLICY;
2339 }
2340 
2341 /* guest info specific to sev-snp */
2342 static const TypeInfo sev_snp_guest_info = {
2343     .parent = TYPE_SEV_COMMON,
2344     .name = TYPE_SEV_SNP_GUEST,
2345     .instance_size = sizeof(SevSnpGuestState),
2346     .class_init = sev_snp_guest_class_init,
2347     .instance_init = sev_snp_guest_instance_init,
2348 };
2349 
2350 static void
2351 sev_register_types(void)
2352 {
2353     type_register_static(&sev_common_info);
2354     type_register_static(&sev_guest_info);
2355     type_register_static(&sev_snp_guest_info);
2356 }
2357 
2358 type_init(sev_register_types);
2359