xref: /openbmc/qemu/target/i386/sev.c (revision 16dcf200)
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/psp-sev.h>
18 
19 #include <sys/ioctl.h>
20 
21 #include "qapi/error.h"
22 #include "qom/object_interfaces.h"
23 #include "qemu/base64.h"
24 #include "qemu/module.h"
25 #include "qemu/uuid.h"
26 #include "qemu/error-report.h"
27 #include "crypto/hash.h"
28 #include "sysemu/kvm.h"
29 #include "kvm/kvm_i386.h"
30 #include "sev.h"
31 #include "sysemu/sysemu.h"
32 #include "sysemu/runstate.h"
33 #include "trace.h"
34 #include "migration/blocker.h"
35 #include "qom/object.h"
36 #include "monitor/monitor.h"
37 #include "monitor/hmp-target.h"
38 #include "qapi/qapi-commands-misc-target.h"
39 #include "confidential-guest.h"
40 #include "hw/i386/pc.h"
41 #include "exec/address-spaces.h"
42 
43 OBJECT_DECLARE_TYPE(SevCommonState, SevCommonStateClass, SEV_COMMON)
44 OBJECT_DECLARE_TYPE(SevGuestState, SevCommonStateClass, SEV_GUEST)
45 
46 struct SevCommonState {
47     X86ConfidentialGuest parent_obj;
48 
49     int kvm_type;
50 
51     /* configuration parameters */
52     char *sev_device;
53     uint32_t cbitpos;
54     uint32_t reduced_phys_bits;
55     bool kernel_hashes;
56 
57     /* runtime state */
58     uint8_t api_major;
59     uint8_t api_minor;
60     uint8_t build_id;
61     int sev_fd;
62     SevState state;
63 
64     uint32_t reset_cs;
65     uint32_t reset_ip;
66     bool reset_data_valid;
67 };
68 
69 struct SevCommonStateClass {
70     X86ConfidentialGuestClass parent_class;
71 
72 };
73 
74 /**
75  * SevGuestState:
76  *
77  * The SevGuestState object is used for creating and managing a SEV
78  * guest.
79  *
80  * # $QEMU \
81  *         -object sev-guest,id=sev0 \
82  *         -machine ...,memory-encryption=sev0
83  */
84 struct SevGuestState {
85     SevCommonState parent_obj;
86     gchar *measurement;
87 
88     /* configuration parameters */
89     uint32_t handle;
90     uint32_t policy;
91     char *dh_cert_file;
92     char *session_file;
93     bool legacy_vm_type;
94 };
95 
96 #define DEFAULT_GUEST_POLICY    0x1 /* disable debug */
97 #define DEFAULT_SEV_DEVICE      "/dev/sev"
98 
99 #define SEV_INFO_BLOCK_GUID     "00f771de-1a7e-4fcb-890e-68c77e2fb44e"
100 typedef struct __attribute__((__packed__)) SevInfoBlock {
101     /* SEV-ES Reset Vector Address */
102     uint32_t reset_addr;
103 } SevInfoBlock;
104 
105 #define SEV_HASH_TABLE_RV_GUID  "7255371f-3a3b-4b04-927b-1da6efa8d454"
106 typedef struct QEMU_PACKED SevHashTableDescriptor {
107     /* SEV hash table area guest address */
108     uint32_t base;
109     /* SEV hash table area size (in bytes) */
110     uint32_t size;
111 } SevHashTableDescriptor;
112 
113 /* hard code sha256 digest size */
114 #define HASH_SIZE 32
115 
116 typedef struct QEMU_PACKED SevHashTableEntry {
117     QemuUUID guid;
118     uint16_t len;
119     uint8_t hash[HASH_SIZE];
120 } SevHashTableEntry;
121 
122 typedef struct QEMU_PACKED SevHashTable {
123     QemuUUID guid;
124     uint16_t len;
125     SevHashTableEntry cmdline;
126     SevHashTableEntry initrd;
127     SevHashTableEntry kernel;
128 } SevHashTable;
129 
130 /*
131  * Data encrypted by sev_encrypt_flash() must be padded to a multiple of
132  * 16 bytes.
133  */
134 typedef struct QEMU_PACKED PaddedSevHashTable {
135     SevHashTable ht;
136     uint8_t padding[ROUND_UP(sizeof(SevHashTable), 16) - sizeof(SevHashTable)];
137 } PaddedSevHashTable;
138 
139 QEMU_BUILD_BUG_ON(sizeof(PaddedSevHashTable) % 16 != 0);
140 
141 static Error *sev_mig_blocker;
142 
143 static const char *const sev_fw_errlist[] = {
144     [SEV_RET_SUCCESS]                = "",
145     [SEV_RET_INVALID_PLATFORM_STATE] = "Platform state is invalid",
146     [SEV_RET_INVALID_GUEST_STATE]    = "Guest state is invalid",
147     [SEV_RET_INAVLID_CONFIG]         = "Platform configuration is invalid",
148     [SEV_RET_INVALID_LEN]            = "Buffer too small",
149     [SEV_RET_ALREADY_OWNED]          = "Platform is already owned",
150     [SEV_RET_INVALID_CERTIFICATE]    = "Certificate is invalid",
151     [SEV_RET_POLICY_FAILURE]         = "Policy is not allowed",
152     [SEV_RET_INACTIVE]               = "Guest is not active",
153     [SEV_RET_INVALID_ADDRESS]        = "Invalid address",
154     [SEV_RET_BAD_SIGNATURE]          = "Bad signature",
155     [SEV_RET_BAD_MEASUREMENT]        = "Bad measurement",
156     [SEV_RET_ASID_OWNED]             = "ASID is already owned",
157     [SEV_RET_INVALID_ASID]           = "Invalid ASID",
158     [SEV_RET_WBINVD_REQUIRED]        = "WBINVD is required",
159     [SEV_RET_DFFLUSH_REQUIRED]       = "DF_FLUSH is required",
160     [SEV_RET_INVALID_GUEST]          = "Guest handle is invalid",
161     [SEV_RET_INVALID_COMMAND]        = "Invalid command",
162     [SEV_RET_ACTIVE]                 = "Guest is active",
163     [SEV_RET_HWSEV_RET_PLATFORM]     = "Hardware error",
164     [SEV_RET_HWSEV_RET_UNSAFE]       = "Hardware unsafe",
165     [SEV_RET_UNSUPPORTED]            = "Feature not supported",
166     [SEV_RET_INVALID_PARAM]          = "Invalid parameter",
167     [SEV_RET_RESOURCE_LIMIT]         = "Required firmware resource depleted",
168     [SEV_RET_SECURE_DATA_INVALID]    = "Part-specific integrity check failure",
169 };
170 
171 #define SEV_FW_MAX_ERROR      ARRAY_SIZE(sev_fw_errlist)
172 
173 static int
174 sev_ioctl(int fd, int cmd, void *data, int *error)
175 {
176     int r;
177     struct kvm_sev_cmd input;
178 
179     memset(&input, 0x0, sizeof(input));
180 
181     input.id = cmd;
182     input.sev_fd = fd;
183     input.data = (uintptr_t)data;
184 
185     r = kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_OP, &input);
186 
187     if (error) {
188         *error = input.error;
189     }
190 
191     return r;
192 }
193 
194 static int
195 sev_platform_ioctl(int fd, int cmd, void *data, int *error)
196 {
197     int r;
198     struct sev_issue_cmd arg;
199 
200     arg.cmd = cmd;
201     arg.data = (unsigned long)data;
202     r = ioctl(fd, SEV_ISSUE_CMD, &arg);
203     if (error) {
204         *error = arg.error;
205     }
206 
207     return r;
208 }
209 
210 static const char *
211 fw_error_to_str(int code)
212 {
213     if (code < 0 || code >= SEV_FW_MAX_ERROR) {
214         return "unknown error";
215     }
216 
217     return sev_fw_errlist[code];
218 }
219 
220 static bool
221 sev_check_state(const SevCommonState *sev_common, SevState state)
222 {
223     assert(sev_common);
224     return sev_common->state == state ? true : false;
225 }
226 
227 static void
228 sev_set_guest_state(SevCommonState *sev_common, SevState new_state)
229 {
230     assert(new_state < SEV_STATE__MAX);
231     assert(sev_common);
232 
233     trace_kvm_sev_change_state(SevState_str(sev_common->state),
234                                SevState_str(new_state));
235     sev_common->state = new_state;
236 }
237 
238 static void
239 sev_ram_block_added(RAMBlockNotifier *n, void *host, size_t size,
240                     size_t max_size)
241 {
242     int r;
243     struct kvm_enc_region range;
244     ram_addr_t offset;
245     MemoryRegion *mr;
246 
247     /*
248      * The RAM device presents a memory region that should be treated
249      * as IO region and should not be pinned.
250      */
251     mr = memory_region_from_host(host, &offset);
252     if (mr && memory_region_is_ram_device(mr)) {
253         return;
254     }
255 
256     range.addr = (uintptr_t)host;
257     range.size = max_size;
258 
259     trace_kvm_memcrypt_register_region(host, max_size);
260     r = kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_REG_REGION, &range);
261     if (r) {
262         error_report("%s: failed to register region (%p+%#zx) error '%s'",
263                      __func__, host, max_size, strerror(errno));
264         exit(1);
265     }
266 }
267 
268 static void
269 sev_ram_block_removed(RAMBlockNotifier *n, void *host, size_t size,
270                       size_t max_size)
271 {
272     int r;
273     struct kvm_enc_region range;
274     ram_addr_t offset;
275     MemoryRegion *mr;
276 
277     /*
278      * The RAM device presents a memory region that should be treated
279      * as IO region and should not have been pinned.
280      */
281     mr = memory_region_from_host(host, &offset);
282     if (mr && memory_region_is_ram_device(mr)) {
283         return;
284     }
285 
286     range.addr = (uintptr_t)host;
287     range.size = max_size;
288 
289     trace_kvm_memcrypt_unregister_region(host, max_size);
290     r = kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_UNREG_REGION, &range);
291     if (r) {
292         error_report("%s: failed to unregister region (%p+%#zx)",
293                      __func__, host, max_size);
294     }
295 }
296 
297 static struct RAMBlockNotifier sev_ram_notifier = {
298     .ram_block_added = sev_ram_block_added,
299     .ram_block_removed = sev_ram_block_removed,
300 };
301 
302 bool
303 sev_enabled(void)
304 {
305     ConfidentialGuestSupport *cgs = MACHINE(qdev_get_machine())->cgs;
306 
307     return !!object_dynamic_cast(OBJECT(cgs), TYPE_SEV_COMMON);
308 }
309 
310 bool
311 sev_es_enabled(void)
312 {
313     ConfidentialGuestSupport *cgs = MACHINE(qdev_get_machine())->cgs;
314 
315     return sev_enabled() && (SEV_GUEST(cgs)->policy & SEV_POLICY_ES);
316 }
317 
318 uint32_t
319 sev_get_cbit_position(void)
320 {
321     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
322 
323     return sev_common ? sev_common->cbitpos : 0;
324 }
325 
326 uint32_t
327 sev_get_reduced_phys_bits(void)
328 {
329     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
330 
331     return sev_common ? sev_common->reduced_phys_bits : 0;
332 }
333 
334 static SevInfo *sev_get_info(void)
335 {
336     SevInfo *info;
337     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
338     SevGuestState *sev_guest =
339         (SevGuestState *)object_dynamic_cast(OBJECT(sev_common),
340                                              TYPE_SEV_GUEST);
341 
342     info = g_new0(SevInfo, 1);
343     info->enabled = sev_enabled();
344 
345     if (info->enabled) {
346         if (sev_guest) {
347             info->handle = sev_guest->handle;
348         }
349         info->api_major = sev_common->api_major;
350         info->api_minor = sev_common->api_minor;
351         info->build_id = sev_common->build_id;
352         info->state = sev_common->state;
353         /* we only report the lower 32-bits of policy for SNP, ok for now... */
354         info->policy =
355             (uint32_t)object_property_get_uint(OBJECT(sev_common),
356                                                "policy", NULL);
357     }
358 
359     return info;
360 }
361 
362 SevInfo *qmp_query_sev(Error **errp)
363 {
364     SevInfo *info;
365 
366     info = sev_get_info();
367     if (!info) {
368         error_setg(errp, "SEV feature is not available");
369         return NULL;
370     }
371 
372     return info;
373 }
374 
375 void hmp_info_sev(Monitor *mon, const QDict *qdict)
376 {
377     SevInfo *info = sev_get_info();
378 
379     if (info && info->enabled) {
380         monitor_printf(mon, "handle: %d\n", info->handle);
381         monitor_printf(mon, "state: %s\n", SevState_str(info->state));
382         monitor_printf(mon, "build: %d\n", info->build_id);
383         monitor_printf(mon, "api version: %d.%d\n",
384                        info->api_major, info->api_minor);
385         monitor_printf(mon, "debug: %s\n",
386                        info->policy & SEV_POLICY_NODBG ? "off" : "on");
387         monitor_printf(mon, "key-sharing: %s\n",
388                        info->policy & SEV_POLICY_NOKS ? "off" : "on");
389     } else {
390         monitor_printf(mon, "SEV is not enabled\n");
391     }
392 
393     qapi_free_SevInfo(info);
394 }
395 
396 static int
397 sev_get_pdh_info(int fd, guchar **pdh, size_t *pdh_len, guchar **cert_chain,
398                  size_t *cert_chain_len, Error **errp)
399 {
400     guchar *pdh_data = NULL;
401     guchar *cert_chain_data = NULL;
402     struct sev_user_data_pdh_cert_export export = {};
403     int err, r;
404 
405     /* query the certificate length */
406     r = sev_platform_ioctl(fd, SEV_PDH_CERT_EXPORT, &export, &err);
407     if (r < 0) {
408         if (err != SEV_RET_INVALID_LEN) {
409             error_setg(errp, "SEV: Failed to export PDH cert"
410                              " ret=%d fw_err=%d (%s)",
411                        r, err, fw_error_to_str(err));
412             return 1;
413         }
414     }
415 
416     pdh_data = g_new(guchar, export.pdh_cert_len);
417     cert_chain_data = g_new(guchar, export.cert_chain_len);
418     export.pdh_cert_address = (unsigned long)pdh_data;
419     export.cert_chain_address = (unsigned long)cert_chain_data;
420 
421     r = sev_platform_ioctl(fd, SEV_PDH_CERT_EXPORT, &export, &err);
422     if (r < 0) {
423         error_setg(errp, "SEV: Failed to export PDH cert ret=%d fw_err=%d (%s)",
424                    r, err, fw_error_to_str(err));
425         goto e_free;
426     }
427 
428     *pdh = pdh_data;
429     *pdh_len = export.pdh_cert_len;
430     *cert_chain = cert_chain_data;
431     *cert_chain_len = export.cert_chain_len;
432     return 0;
433 
434 e_free:
435     g_free(pdh_data);
436     g_free(cert_chain_data);
437     return 1;
438 }
439 
440 static int sev_get_cpu0_id(int fd, guchar **id, size_t *id_len, Error **errp)
441 {
442     guchar *id_data;
443     struct sev_user_data_get_id2 get_id2 = {};
444     int err, r;
445 
446     /* query the ID length */
447     r = sev_platform_ioctl(fd, SEV_GET_ID2, &get_id2, &err);
448     if (r < 0 && err != SEV_RET_INVALID_LEN) {
449         error_setg(errp, "SEV: Failed to get ID ret=%d fw_err=%d (%s)",
450                    r, err, fw_error_to_str(err));
451         return 1;
452     }
453 
454     id_data = g_new(guchar, get_id2.length);
455     get_id2.address = (unsigned long)id_data;
456 
457     r = sev_platform_ioctl(fd, SEV_GET_ID2, &get_id2, &err);
458     if (r < 0) {
459         error_setg(errp, "SEV: Failed to get ID ret=%d fw_err=%d (%s)",
460                    r, err, fw_error_to_str(err));
461         goto err;
462     }
463 
464     *id = id_data;
465     *id_len = get_id2.length;
466     return 0;
467 
468 err:
469     g_free(id_data);
470     return 1;
471 }
472 
473 static SevCapability *sev_get_capabilities(Error **errp)
474 {
475     SevCapability *cap = NULL;
476     guchar *pdh_data = NULL;
477     guchar *cert_chain_data = NULL;
478     guchar *cpu0_id_data = NULL;
479     size_t pdh_len = 0, cert_chain_len = 0, cpu0_id_len = 0;
480     uint32_t ebx;
481     int fd;
482     SevCommonState *sev_common;
483     char *sev_device;
484 
485     if (!kvm_enabled()) {
486         error_setg(errp, "KVM not enabled");
487         return NULL;
488     }
489     if (kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_OP, NULL) < 0) {
490         error_setg(errp, "SEV is not enabled in KVM");
491         return NULL;
492     }
493 
494     sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
495     if (!sev_common) {
496         error_setg(errp, "SEV is not configured");
497     }
498 
499     sev_device = object_property_get_str(OBJECT(sev_common), "sev-device",
500                                          &error_abort);
501     fd = open(sev_device, O_RDWR);
502     if (fd < 0) {
503         error_setg_errno(errp, errno, "SEV: Failed to open %s",
504                          DEFAULT_SEV_DEVICE);
505         g_free(sev_device);
506         return NULL;
507     }
508     g_free(sev_device);
509 
510     if (sev_get_pdh_info(fd, &pdh_data, &pdh_len,
511                          &cert_chain_data, &cert_chain_len, errp)) {
512         goto out;
513     }
514 
515     if (sev_get_cpu0_id(fd, &cpu0_id_data, &cpu0_id_len, errp)) {
516         goto out;
517     }
518 
519     cap = g_new0(SevCapability, 1);
520     cap->pdh = g_base64_encode(pdh_data, pdh_len);
521     cap->cert_chain = g_base64_encode(cert_chain_data, cert_chain_len);
522     cap->cpu0_id = g_base64_encode(cpu0_id_data, cpu0_id_len);
523 
524     host_cpuid(0x8000001F, 0, NULL, &ebx, NULL, NULL);
525     cap->cbitpos = ebx & 0x3f;
526 
527     /*
528      * When SEV feature is enabled, we loose one bit in guest physical
529      * addressing.
530      */
531     cap->reduced_phys_bits = 1;
532 
533 out:
534     g_free(cpu0_id_data);
535     g_free(pdh_data);
536     g_free(cert_chain_data);
537     close(fd);
538     return cap;
539 }
540 
541 SevCapability *qmp_query_sev_capabilities(Error **errp)
542 {
543     return sev_get_capabilities(errp);
544 }
545 
546 static SevAttestationReport *sev_get_attestation_report(const char *mnonce,
547                                                         Error **errp)
548 {
549     struct kvm_sev_attestation_report input = {};
550     SevAttestationReport *report = NULL;
551     SevCommonState *sev_common;
552     g_autofree guchar *data = NULL;
553     g_autofree guchar *buf = NULL;
554     gsize len;
555     int err = 0, ret;
556 
557     if (!sev_enabled()) {
558         error_setg(errp, "SEV is not enabled");
559         return NULL;
560     }
561 
562     /* lets decode the mnonce string */
563     buf = g_base64_decode(mnonce, &len);
564     if (!buf) {
565         error_setg(errp, "SEV: failed to decode mnonce input");
566         return NULL;
567     }
568 
569     /* verify the input mnonce length */
570     if (len != sizeof(input.mnonce)) {
571         error_setg(errp, "SEV: mnonce must be %zu bytes (got %" G_GSIZE_FORMAT ")",
572                 sizeof(input.mnonce), len);
573         return NULL;
574     }
575 
576     sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
577 
578     /* Query the report length */
579     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_GET_ATTESTATION_REPORT,
580             &input, &err);
581     if (ret < 0) {
582         if (err != SEV_RET_INVALID_LEN) {
583             error_setg(errp, "SEV: Failed to query the attestation report"
584                              " length ret=%d fw_err=%d (%s)",
585                        ret, err, fw_error_to_str(err));
586             return NULL;
587         }
588     }
589 
590     data = g_malloc(input.len);
591     input.uaddr = (unsigned long)data;
592     memcpy(input.mnonce, buf, sizeof(input.mnonce));
593 
594     /* Query the report */
595     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_GET_ATTESTATION_REPORT,
596             &input, &err);
597     if (ret) {
598         error_setg_errno(errp, errno, "SEV: Failed to get attestation report"
599                 " ret=%d fw_err=%d (%s)", ret, err, fw_error_to_str(err));
600         return NULL;
601     }
602 
603     report = g_new0(SevAttestationReport, 1);
604     report->data = g_base64_encode(data, input.len);
605 
606     trace_kvm_sev_attestation_report(mnonce, report->data);
607 
608     return report;
609 }
610 
611 SevAttestationReport *qmp_query_sev_attestation_report(const char *mnonce,
612                                                        Error **errp)
613 {
614     return sev_get_attestation_report(mnonce, errp);
615 }
616 
617 static int
618 sev_read_file_base64(const char *filename, guchar **data, gsize *len)
619 {
620     gsize sz;
621     g_autofree gchar *base64 = NULL;
622     GError *error = NULL;
623 
624     if (!g_file_get_contents(filename, &base64, &sz, &error)) {
625         error_report("SEV: Failed to read '%s' (%s)", filename, error->message);
626         g_error_free(error);
627         return -1;
628     }
629 
630     *data = g_base64_decode(base64, len);
631     return 0;
632 }
633 
634 static int
635 sev_launch_start(SevGuestState *sev_guest)
636 {
637     gsize sz;
638     int ret = 1;
639     int fw_error, rc;
640     struct kvm_sev_launch_start start = {
641         .handle = sev_guest->handle, .policy = sev_guest->policy
642     };
643     guchar *session = NULL, *dh_cert = NULL;
644     SevCommonState *sev_common = SEV_COMMON(sev_guest);
645 
646     if (sev_guest->session_file) {
647         if (sev_read_file_base64(sev_guest->session_file, &session, &sz) < 0) {
648             goto out;
649         }
650         start.session_uaddr = (unsigned long)session;
651         start.session_len = sz;
652     }
653 
654     if (sev_guest->dh_cert_file) {
655         if (sev_read_file_base64(sev_guest->dh_cert_file, &dh_cert, &sz) < 0) {
656             goto out;
657         }
658         start.dh_uaddr = (unsigned long)dh_cert;
659         start.dh_len = sz;
660     }
661 
662     trace_kvm_sev_launch_start(start.policy, session, dh_cert);
663     rc = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_START, &start, &fw_error);
664     if (rc < 0) {
665         error_report("%s: LAUNCH_START ret=%d fw_error=%d '%s'",
666                 __func__, ret, fw_error, fw_error_to_str(fw_error));
667         goto out;
668     }
669 
670     sev_set_guest_state(sev_common, SEV_STATE_LAUNCH_UPDATE);
671     sev_guest->handle = start.handle;
672     ret = 0;
673 
674 out:
675     g_free(session);
676     g_free(dh_cert);
677     return ret;
678 }
679 
680 static int
681 sev_launch_update_data(SevGuestState *sev_guest, uint8_t *addr, uint64_t len)
682 {
683     int ret, fw_error;
684     struct kvm_sev_launch_update_data update;
685 
686     if (!addr || !len) {
687         return 1;
688     }
689 
690     update.uaddr = (uintptr_t)addr;
691     update.len = len;
692     trace_kvm_sev_launch_update_data(addr, len);
693     ret = sev_ioctl(SEV_COMMON(sev_guest)->sev_fd, KVM_SEV_LAUNCH_UPDATE_DATA,
694                     &update, &fw_error);
695     if (ret) {
696         error_report("%s: LAUNCH_UPDATE ret=%d fw_error=%d '%s'",
697                 __func__, ret, fw_error, fw_error_to_str(fw_error));
698     }
699 
700     return ret;
701 }
702 
703 static int
704 sev_launch_update_vmsa(SevGuestState *sev_guest)
705 {
706     int ret, fw_error;
707 
708     ret = sev_ioctl(SEV_COMMON(sev_guest)->sev_fd, KVM_SEV_LAUNCH_UPDATE_VMSA,
709                     NULL, &fw_error);
710     if (ret) {
711         error_report("%s: LAUNCH_UPDATE_VMSA ret=%d fw_error=%d '%s'",
712                 __func__, ret, fw_error, fw_error_to_str(fw_error));
713     }
714 
715     return ret;
716 }
717 
718 static void
719 sev_launch_get_measure(Notifier *notifier, void *unused)
720 {
721     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
722     SevGuestState *sev_guest = SEV_GUEST(sev_common);
723     int ret, error;
724     g_autofree guchar *data = NULL;
725     struct kvm_sev_launch_measure measurement = {};
726 
727     if (!sev_check_state(sev_common, SEV_STATE_LAUNCH_UPDATE)) {
728         return;
729     }
730 
731     if (sev_es_enabled()) {
732         /* measure all the VM save areas before getting launch_measure */
733         ret = sev_launch_update_vmsa(sev_guest);
734         if (ret) {
735             exit(1);
736         }
737         kvm_mark_guest_state_protected();
738     }
739 
740     /* query the measurement blob length */
741     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_MEASURE,
742                     &measurement, &error);
743     if (!measurement.len) {
744         error_report("%s: LAUNCH_MEASURE ret=%d fw_error=%d '%s'",
745                      __func__, ret, error, fw_error_to_str(errno));
746         return;
747     }
748 
749     data = g_new0(guchar, measurement.len);
750     measurement.uaddr = (unsigned long)data;
751 
752     /* get the measurement blob */
753     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_MEASURE,
754                     &measurement, &error);
755     if (ret) {
756         error_report("%s: LAUNCH_MEASURE ret=%d fw_error=%d '%s'",
757                      __func__, ret, error, fw_error_to_str(errno));
758         return;
759     }
760 
761     sev_set_guest_state(sev_common, SEV_STATE_LAUNCH_SECRET);
762 
763     /* encode the measurement value and emit the event */
764     sev_guest->measurement = g_base64_encode(data, measurement.len);
765     trace_kvm_sev_launch_measurement(sev_guest->measurement);
766 }
767 
768 static char *sev_get_launch_measurement(void)
769 {
770     SevGuestState *sev_guest = SEV_GUEST(MACHINE(qdev_get_machine())->cgs);
771 
772     if (sev_guest &&
773         SEV_COMMON(sev_guest)->state >= SEV_STATE_LAUNCH_SECRET) {
774         return g_strdup(sev_guest->measurement);
775     }
776 
777     return NULL;
778 }
779 
780 SevLaunchMeasureInfo *qmp_query_sev_launch_measure(Error **errp)
781 {
782     char *data;
783     SevLaunchMeasureInfo *info;
784 
785     data = sev_get_launch_measurement();
786     if (!data) {
787         error_setg(errp, "SEV launch measurement is not available");
788         return NULL;
789     }
790 
791     info = g_malloc0(sizeof(*info));
792     info->data = data;
793 
794     return info;
795 }
796 
797 static Notifier sev_machine_done_notify = {
798     .notify = sev_launch_get_measure,
799 };
800 
801 static void
802 sev_launch_finish(SevGuestState *sev_guest)
803 {
804     int ret, error;
805 
806     trace_kvm_sev_launch_finish();
807     ret = sev_ioctl(SEV_COMMON(sev_guest)->sev_fd, KVM_SEV_LAUNCH_FINISH, 0,
808                     &error);
809     if (ret) {
810         error_report("%s: LAUNCH_FINISH ret=%d fw_error=%d '%s'",
811                      __func__, ret, error, fw_error_to_str(error));
812         exit(1);
813     }
814 
815     sev_set_guest_state(SEV_COMMON(sev_guest), SEV_STATE_RUNNING);
816 
817     /* add migration blocker */
818     error_setg(&sev_mig_blocker,
819                "SEV: Migration is not implemented");
820     migrate_add_blocker(&sev_mig_blocker, &error_fatal);
821 }
822 
823 static void
824 sev_vm_state_change(void *opaque, bool running, RunState state)
825 {
826     SevCommonState *sev_common = opaque;
827 
828     if (running) {
829         if (!sev_check_state(sev_common, SEV_STATE_RUNNING)) {
830             sev_launch_finish(SEV_GUEST(sev_common));
831         }
832     }
833 }
834 
835 static int sev_kvm_type(X86ConfidentialGuest *cg)
836 {
837     SevCommonState *sev_common = SEV_COMMON(cg);
838     SevGuestState *sev_guest = SEV_GUEST(sev_common);
839     int kvm_type;
840 
841     if (sev_common->kvm_type != -1) {
842         goto out;
843     }
844 
845     kvm_type = (sev_guest->policy & SEV_POLICY_ES) ?
846                 KVM_X86_SEV_ES_VM : KVM_X86_SEV_VM;
847     if (kvm_is_vm_type_supported(kvm_type) && !sev_guest->legacy_vm_type) {
848         sev_common->kvm_type = kvm_type;
849     } else {
850         sev_common->kvm_type = KVM_X86_DEFAULT_VM;
851     }
852 
853 out:
854     return sev_common->kvm_type;
855 }
856 
857 static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
858 {
859     SevCommonState *sev_common = SEV_COMMON(cgs);
860     char *devname;
861     int ret, fw_error, cmd;
862     uint32_t ebx;
863     uint32_t host_cbitpos;
864     struct sev_user_data_status status = {};
865 
866     ret = ram_block_discard_disable(true);
867     if (ret) {
868         error_report("%s: cannot disable RAM discard", __func__);
869         return -1;
870     }
871 
872     sev_common->state = SEV_STATE_UNINIT;
873 
874     host_cpuid(0x8000001F, 0, NULL, &ebx, NULL, NULL);
875     host_cbitpos = ebx & 0x3f;
876 
877     /*
878      * The cbitpos value will be placed in bit positions 5:0 of the EBX
879      * register of CPUID 0x8000001F. No need to verify the range as the
880      * comparison against the host value accomplishes that.
881      */
882     if (host_cbitpos != sev_common->cbitpos) {
883         error_setg(errp, "%s: cbitpos check failed, host '%d' requested '%d'",
884                    __func__, host_cbitpos, sev_common->cbitpos);
885         goto err;
886     }
887 
888     /*
889      * The reduced-phys-bits value will be placed in bit positions 11:6 of
890      * the EBX register of CPUID 0x8000001F, so verify the supplied value
891      * is in the range of 1 to 63.
892      */
893     if (sev_common->reduced_phys_bits < 1 ||
894         sev_common->reduced_phys_bits > 63) {
895         error_setg(errp, "%s: reduced_phys_bits check failed,"
896                    " it should be in the range of 1 to 63, requested '%d'",
897                    __func__, sev_common->reduced_phys_bits);
898         goto err;
899     }
900 
901     devname = object_property_get_str(OBJECT(sev_common), "sev-device", NULL);
902     sev_common->sev_fd = open(devname, O_RDWR);
903     if (sev_common->sev_fd < 0) {
904         error_setg(errp, "%s: Failed to open %s '%s'", __func__,
905                    devname, strerror(errno));
906         g_free(devname);
907         goto err;
908     }
909     g_free(devname);
910 
911     ret = sev_platform_ioctl(sev_common->sev_fd, SEV_PLATFORM_STATUS, &status,
912                              &fw_error);
913     if (ret) {
914         error_setg(errp, "%s: failed to get platform status ret=%d "
915                    "fw_error='%d: %s'", __func__, ret, fw_error,
916                    fw_error_to_str(fw_error));
917         goto err;
918     }
919     sev_common->build_id = status.build;
920     sev_common->api_major = status.api_major;
921     sev_common->api_minor = status.api_minor;
922 
923     if (sev_es_enabled()) {
924         if (!kvm_kernel_irqchip_allowed()) {
925             error_setg(errp, "%s: SEV-ES guests require in-kernel irqchip"
926                        "support", __func__);
927             goto err;
928         }
929 
930         if (!(status.flags & SEV_STATUS_FLAGS_CONFIG_ES)) {
931             error_setg(errp, "%s: guest policy requires SEV-ES, but "
932                          "host SEV-ES support unavailable",
933                          __func__);
934             goto err;
935         }
936     }
937 
938     trace_kvm_sev_init();
939     if (sev_kvm_type(X86_CONFIDENTIAL_GUEST(sev_common)) == KVM_X86_DEFAULT_VM) {
940         cmd = sev_es_enabled() ? KVM_SEV_ES_INIT : KVM_SEV_INIT;
941 
942         ret = sev_ioctl(sev_common->sev_fd, cmd, NULL, &fw_error);
943     } else {
944         struct kvm_sev_init args = { 0 };
945 
946         ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_INIT2, &args, &fw_error);
947     }
948 
949     if (ret) {
950         error_setg(errp, "%s: failed to initialize ret=%d fw_error=%d '%s'",
951                    __func__, ret, fw_error, fw_error_to_str(fw_error));
952         goto err;
953     }
954 
955     sev_launch_start(SEV_GUEST(sev_common));
956     if (ret) {
957         error_setg(errp, "%s: failed to create encryption context", __func__);
958         goto err;
959     }
960 
961     ram_block_notifier_add(&sev_ram_notifier);
962     qemu_add_machine_init_done_notifier(&sev_machine_done_notify);
963     qemu_add_vm_change_state_handler(sev_vm_state_change, sev_common);
964 
965     cgs->ready = true;
966 
967     return 0;
968 err:
969     ram_block_discard_disable(false);
970     return -1;
971 }
972 
973 int
974 sev_encrypt_flash(uint8_t *ptr, uint64_t len, Error **errp)
975 {
976     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
977 
978     if (!sev_common) {
979         return 0;
980     }
981 
982     /* if SEV is in update state then encrypt the data else do nothing */
983     if (sev_check_state(sev_common, SEV_STATE_LAUNCH_UPDATE)) {
984         int ret = sev_launch_update_data(SEV_GUEST(sev_common), ptr, len);
985         if (ret < 0) {
986             error_setg(errp, "SEV: Failed to encrypt pflash rom");
987             return ret;
988         }
989     }
990 
991     return 0;
992 }
993 
994 int sev_inject_launch_secret(const char *packet_hdr, const char *secret,
995                              uint64_t gpa, Error **errp)
996 {
997     ERRP_GUARD();
998     struct kvm_sev_launch_secret input;
999     g_autofree guchar *data = NULL, *hdr = NULL;
1000     int error, ret = 1;
1001     void *hva;
1002     gsize hdr_sz = 0, data_sz = 0;
1003     MemoryRegion *mr = NULL;
1004     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1005 
1006     if (!sev_common) {
1007         error_setg(errp, "SEV not enabled for guest");
1008         return 1;
1009     }
1010 
1011     /* secret can be injected only in this state */
1012     if (!sev_check_state(sev_common, SEV_STATE_LAUNCH_SECRET)) {
1013         error_setg(errp, "SEV: Not in correct state. (LSECRET) %x",
1014                    sev_common->state);
1015         return 1;
1016     }
1017 
1018     hdr = g_base64_decode(packet_hdr, &hdr_sz);
1019     if (!hdr || !hdr_sz) {
1020         error_setg(errp, "SEV: Failed to decode sequence header");
1021         return 1;
1022     }
1023 
1024     data = g_base64_decode(secret, &data_sz);
1025     if (!data || !data_sz) {
1026         error_setg(errp, "SEV: Failed to decode data");
1027         return 1;
1028     }
1029 
1030     hva = gpa2hva(&mr, gpa, data_sz, errp);
1031     if (!hva) {
1032         error_prepend(errp, "SEV: Failed to calculate guest address: ");
1033         return 1;
1034     }
1035 
1036     input.hdr_uaddr = (uint64_t)(unsigned long)hdr;
1037     input.hdr_len = hdr_sz;
1038 
1039     input.trans_uaddr = (uint64_t)(unsigned long)data;
1040     input.trans_len = data_sz;
1041 
1042     input.guest_uaddr = (uint64_t)(unsigned long)hva;
1043     input.guest_len = data_sz;
1044 
1045     trace_kvm_sev_launch_secret(gpa, input.guest_uaddr,
1046                                 input.trans_uaddr, input.trans_len);
1047 
1048     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_SECRET,
1049                     &input, &error);
1050     if (ret) {
1051         error_setg(errp, "SEV: failed to inject secret ret=%d fw_error=%d '%s'",
1052                      ret, error, fw_error_to_str(error));
1053         return ret;
1054     }
1055 
1056     return 0;
1057 }
1058 
1059 #define SEV_SECRET_GUID "4c2eb361-7d9b-4cc3-8081-127c90d3d294"
1060 struct sev_secret_area {
1061     uint32_t base;
1062     uint32_t size;
1063 };
1064 
1065 void qmp_sev_inject_launch_secret(const char *packet_hdr,
1066                                   const char *secret,
1067                                   bool has_gpa, uint64_t gpa,
1068                                   Error **errp)
1069 {
1070     if (!sev_enabled()) {
1071         error_setg(errp, "SEV not enabled for guest");
1072         return;
1073     }
1074     if (!has_gpa) {
1075         uint8_t *data;
1076         struct sev_secret_area *area;
1077 
1078         if (!pc_system_ovmf_table_find(SEV_SECRET_GUID, &data, NULL)) {
1079             error_setg(errp, "SEV: no secret area found in OVMF,"
1080                        " gpa must be specified.");
1081             return;
1082         }
1083         area = (struct sev_secret_area *)data;
1084         gpa = area->base;
1085     }
1086 
1087     sev_inject_launch_secret(packet_hdr, secret, gpa, errp);
1088 }
1089 
1090 static int
1091 sev_es_parse_reset_block(SevInfoBlock *info, uint32_t *addr)
1092 {
1093     if (!info->reset_addr) {
1094         error_report("SEV-ES reset address is zero");
1095         return 1;
1096     }
1097 
1098     *addr = info->reset_addr;
1099 
1100     return 0;
1101 }
1102 
1103 static int
1104 sev_es_find_reset_vector(void *flash_ptr, uint64_t flash_size,
1105                          uint32_t *addr)
1106 {
1107     QemuUUID info_guid, *guid;
1108     SevInfoBlock *info;
1109     uint8_t *data;
1110     uint16_t *len;
1111 
1112     /*
1113      * Initialize the address to zero. An address of zero with a successful
1114      * return code indicates that SEV-ES is not active.
1115      */
1116     *addr = 0;
1117 
1118     /*
1119      * Extract the AP reset vector for SEV-ES guests by locating the SEV GUID.
1120      * The SEV GUID is located on its own (original implementation) or within
1121      * the Firmware GUID Table (new implementation), either of which are
1122      * located 32 bytes from the end of the flash.
1123      *
1124      * Check the Firmware GUID Table first.
1125      */
1126     if (pc_system_ovmf_table_find(SEV_INFO_BLOCK_GUID, &data, NULL)) {
1127         return sev_es_parse_reset_block((SevInfoBlock *)data, addr);
1128     }
1129 
1130     /*
1131      * SEV info block not found in the Firmware GUID Table (or there isn't
1132      * a Firmware GUID Table), fall back to the original implementation.
1133      */
1134     data = flash_ptr + flash_size - 0x20;
1135 
1136     qemu_uuid_parse(SEV_INFO_BLOCK_GUID, &info_guid);
1137     info_guid = qemu_uuid_bswap(info_guid); /* GUIDs are LE */
1138 
1139     guid = (QemuUUID *)(data - sizeof(info_guid));
1140     if (!qemu_uuid_is_equal(guid, &info_guid)) {
1141         error_report("SEV information block/Firmware GUID Table block not found in pflash rom");
1142         return 1;
1143     }
1144 
1145     len = (uint16_t *)((uint8_t *)guid - sizeof(*len));
1146     info = (SevInfoBlock *)(data - le16_to_cpu(*len));
1147 
1148     return sev_es_parse_reset_block(info, addr);
1149 }
1150 
1151 void sev_es_set_reset_vector(CPUState *cpu)
1152 {
1153     X86CPU *x86;
1154     CPUX86State *env;
1155     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1156 
1157     /* Only update if we have valid reset information */
1158     if (!sev_common || !sev_common->reset_data_valid) {
1159         return;
1160     }
1161 
1162     /* Do not update the BSP reset state */
1163     if (cpu->cpu_index == 0) {
1164         return;
1165     }
1166 
1167     x86 = X86_CPU(cpu);
1168     env = &x86->env;
1169 
1170     cpu_x86_load_seg_cache(env, R_CS, 0xf000, sev_common->reset_cs, 0xffff,
1171                            DESC_P_MASK | DESC_S_MASK | DESC_CS_MASK |
1172                            DESC_R_MASK | DESC_A_MASK);
1173 
1174     env->eip = sev_common->reset_ip;
1175 }
1176 
1177 int sev_es_save_reset_vector(void *flash_ptr, uint64_t flash_size)
1178 {
1179     CPUState *cpu;
1180     uint32_t addr;
1181     int ret;
1182     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1183 
1184     if (!sev_es_enabled()) {
1185         return 0;
1186     }
1187 
1188     addr = 0;
1189     ret = sev_es_find_reset_vector(flash_ptr, flash_size,
1190                                    &addr);
1191     if (ret) {
1192         return ret;
1193     }
1194 
1195     if (addr) {
1196         sev_common->reset_cs = addr & 0xffff0000;
1197         sev_common->reset_ip = addr & 0x0000ffff;
1198         sev_common->reset_data_valid = true;
1199 
1200         CPU_FOREACH(cpu) {
1201             sev_es_set_reset_vector(cpu);
1202         }
1203     }
1204 
1205     return 0;
1206 }
1207 
1208 static const QemuUUID sev_hash_table_header_guid = {
1209     .data = UUID_LE(0x9438d606, 0x4f22, 0x4cc9, 0xb4, 0x79, 0xa7, 0x93,
1210                     0xd4, 0x11, 0xfd, 0x21)
1211 };
1212 
1213 static const QemuUUID sev_kernel_entry_guid = {
1214     .data = UUID_LE(0x4de79437, 0xabd2, 0x427f, 0xb8, 0x35, 0xd5, 0xb1,
1215                     0x72, 0xd2, 0x04, 0x5b)
1216 };
1217 static const QemuUUID sev_initrd_entry_guid = {
1218     .data = UUID_LE(0x44baf731, 0x3a2f, 0x4bd7, 0x9a, 0xf1, 0x41, 0xe2,
1219                     0x91, 0x69, 0x78, 0x1d)
1220 };
1221 static const QemuUUID sev_cmdline_entry_guid = {
1222     .data = UUID_LE(0x97d02dd8, 0xbd20, 0x4c94, 0xaa, 0x78, 0xe7, 0x71,
1223                     0x4d, 0x36, 0xab, 0x2a)
1224 };
1225 
1226 /*
1227  * Add the hashes of the linux kernel/initrd/cmdline to an encrypted guest page
1228  * which is included in SEV's initial memory measurement.
1229  */
1230 bool sev_add_kernel_loader_hashes(SevKernelLoaderContext *ctx, Error **errp)
1231 {
1232     uint8_t *data;
1233     SevHashTableDescriptor *area;
1234     SevHashTable *ht;
1235     PaddedSevHashTable *padded_ht;
1236     uint8_t cmdline_hash[HASH_SIZE];
1237     uint8_t initrd_hash[HASH_SIZE];
1238     uint8_t kernel_hash[HASH_SIZE];
1239     uint8_t *hashp;
1240     size_t hash_len = HASH_SIZE;
1241     hwaddr mapped_len = sizeof(*padded_ht);
1242     MemTxAttrs attrs = { 0 };
1243     bool ret = true;
1244     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1245 
1246     /*
1247      * Only add the kernel hashes if the sev-guest configuration explicitly
1248      * stated kernel-hashes=on.
1249      */
1250     if (!sev_common->kernel_hashes) {
1251         return false;
1252     }
1253 
1254     if (!pc_system_ovmf_table_find(SEV_HASH_TABLE_RV_GUID, &data, NULL)) {
1255         error_setg(errp, "SEV: kernel specified but guest firmware "
1256                          "has no hashes table GUID");
1257         return false;
1258     }
1259     area = (SevHashTableDescriptor *)data;
1260     if (!area->base || area->size < sizeof(PaddedSevHashTable)) {
1261         error_setg(errp, "SEV: guest firmware hashes table area is invalid "
1262                          "(base=0x%x size=0x%x)", area->base, area->size);
1263         return false;
1264     }
1265 
1266     /*
1267      * Calculate hash of kernel command-line with the terminating null byte. If
1268      * the user doesn't supply a command-line via -append, the 1-byte "\0" will
1269      * be used.
1270      */
1271     hashp = cmdline_hash;
1272     if (qcrypto_hash_bytes(QCRYPTO_HASH_ALG_SHA256, ctx->cmdline_data,
1273                            ctx->cmdline_size, &hashp, &hash_len, errp) < 0) {
1274         return false;
1275     }
1276     assert(hash_len == HASH_SIZE);
1277 
1278     /*
1279      * Calculate hash of initrd. If the user doesn't supply an initrd via
1280      * -initrd, an empty buffer will be used (ctx->initrd_size == 0).
1281      */
1282     hashp = initrd_hash;
1283     if (qcrypto_hash_bytes(QCRYPTO_HASH_ALG_SHA256, ctx->initrd_data,
1284                            ctx->initrd_size, &hashp, &hash_len, errp) < 0) {
1285         return false;
1286     }
1287     assert(hash_len == HASH_SIZE);
1288 
1289     /* Calculate hash of the kernel */
1290     hashp = kernel_hash;
1291     struct iovec iov[2] = {
1292         { .iov_base = ctx->setup_data, .iov_len = ctx->setup_size },
1293         { .iov_base = ctx->kernel_data, .iov_len = ctx->kernel_size }
1294     };
1295     if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA256, iov, ARRAY_SIZE(iov),
1296                             &hashp, &hash_len, errp) < 0) {
1297         return false;
1298     }
1299     assert(hash_len == HASH_SIZE);
1300 
1301     /*
1302      * Populate the hashes table in the guest's memory at the OVMF-designated
1303      * area for the SEV hashes table
1304      */
1305     padded_ht = address_space_map(&address_space_memory, area->base,
1306                                   &mapped_len, true, attrs);
1307     if (!padded_ht || mapped_len != sizeof(*padded_ht)) {
1308         error_setg(errp, "SEV: cannot map hashes table guest memory area");
1309         return false;
1310     }
1311     ht = &padded_ht->ht;
1312 
1313     ht->guid = sev_hash_table_header_guid;
1314     ht->len = sizeof(*ht);
1315 
1316     ht->cmdline.guid = sev_cmdline_entry_guid;
1317     ht->cmdline.len = sizeof(ht->cmdline);
1318     memcpy(ht->cmdline.hash, cmdline_hash, sizeof(ht->cmdline.hash));
1319 
1320     ht->initrd.guid = sev_initrd_entry_guid;
1321     ht->initrd.len = sizeof(ht->initrd);
1322     memcpy(ht->initrd.hash, initrd_hash, sizeof(ht->initrd.hash));
1323 
1324     ht->kernel.guid = sev_kernel_entry_guid;
1325     ht->kernel.len = sizeof(ht->kernel);
1326     memcpy(ht->kernel.hash, kernel_hash, sizeof(ht->kernel.hash));
1327 
1328     /* zero the excess data so the measurement can be reliably calculated */
1329     memset(padded_ht->padding, 0, sizeof(padded_ht->padding));
1330 
1331     if (sev_encrypt_flash((uint8_t *)padded_ht, sizeof(*padded_ht), errp) < 0) {
1332         ret = false;
1333     }
1334 
1335     address_space_unmap(&address_space_memory, padded_ht,
1336                         mapped_len, true, mapped_len);
1337 
1338     return ret;
1339 }
1340 
1341 static char *
1342 sev_common_get_sev_device(Object *obj, Error **errp)
1343 {
1344     return g_strdup(SEV_COMMON(obj)->sev_device);
1345 }
1346 
1347 static void
1348 sev_common_set_sev_device(Object *obj, const char *value, Error **errp)
1349 {
1350     SEV_COMMON(obj)->sev_device = g_strdup(value);
1351 }
1352 
1353 static bool sev_common_get_kernel_hashes(Object *obj, Error **errp)
1354 {
1355     return SEV_COMMON(obj)->kernel_hashes;
1356 }
1357 
1358 static void sev_common_set_kernel_hashes(Object *obj, bool value, Error **errp)
1359 {
1360     SEV_COMMON(obj)->kernel_hashes = value;
1361 }
1362 
1363 static void
1364 sev_common_class_init(ObjectClass *oc, void *data)
1365 {
1366     ConfidentialGuestSupportClass *klass = CONFIDENTIAL_GUEST_SUPPORT_CLASS(oc);
1367     X86ConfidentialGuestClass *x86_klass = X86_CONFIDENTIAL_GUEST_CLASS(oc);
1368 
1369     klass->kvm_init = sev_kvm_init;
1370     x86_klass->kvm_type = sev_kvm_type;
1371 
1372     object_class_property_add_str(oc, "sev-device",
1373                                   sev_common_get_sev_device,
1374                                   sev_common_set_sev_device);
1375     object_class_property_set_description(oc, "sev-device",
1376             "SEV device to use");
1377     object_class_property_add_bool(oc, "kernel-hashes",
1378                                    sev_common_get_kernel_hashes,
1379                                    sev_common_set_kernel_hashes);
1380     object_class_property_set_description(oc, "kernel-hashes",
1381             "add kernel hashes to guest firmware for measured Linux boot");
1382 }
1383 
1384 static void
1385 sev_common_instance_init(Object *obj)
1386 {
1387     SevCommonState *sev_common = SEV_COMMON(obj);
1388 
1389     sev_common->kvm_type = -1;
1390 
1391     sev_common->sev_device = g_strdup(DEFAULT_SEV_DEVICE);
1392 
1393     object_property_add_uint32_ptr(obj, "cbitpos", &sev_common->cbitpos,
1394                                    OBJ_PROP_FLAG_READWRITE);
1395     object_property_add_uint32_ptr(obj, "reduced-phys-bits",
1396                                    &sev_common->reduced_phys_bits,
1397                                    OBJ_PROP_FLAG_READWRITE);
1398 }
1399 
1400 /* sev guest info common to sev/sev-es/sev-snp */
1401 static const TypeInfo sev_common_info = {
1402     .parent = TYPE_X86_CONFIDENTIAL_GUEST,
1403     .name = TYPE_SEV_COMMON,
1404     .instance_size = sizeof(SevCommonState),
1405     .instance_init = sev_common_instance_init,
1406     .class_size = sizeof(SevCommonStateClass),
1407     .class_init = sev_common_class_init,
1408     .abstract = true,
1409     .interfaces = (InterfaceInfo[]) {
1410         { TYPE_USER_CREATABLE },
1411         { }
1412     }
1413 };
1414 
1415 static char *
1416 sev_guest_get_dh_cert_file(Object *obj, Error **errp)
1417 {
1418     return g_strdup(SEV_GUEST(obj)->dh_cert_file);
1419 }
1420 
1421 static void
1422 sev_guest_set_dh_cert_file(Object *obj, const char *value, Error **errp)
1423 {
1424     SEV_GUEST(obj)->dh_cert_file = g_strdup(value);
1425 }
1426 
1427 static char *
1428 sev_guest_get_session_file(Object *obj, Error **errp)
1429 {
1430     SevGuestState *sev_guest = SEV_GUEST(obj);
1431 
1432     return sev_guest->session_file ? g_strdup(sev_guest->session_file) : NULL;
1433 }
1434 
1435 static void
1436 sev_guest_set_session_file(Object *obj, const char *value, Error **errp)
1437 {
1438     SEV_GUEST(obj)->session_file = g_strdup(value);
1439 }
1440 
1441 static bool sev_guest_get_legacy_vm_type(Object *obj, Error **errp)
1442 {
1443     return SEV_GUEST(obj)->legacy_vm_type;
1444 }
1445 
1446 static void sev_guest_set_legacy_vm_type(Object *obj, bool value, Error **errp)
1447 {
1448     SEV_GUEST(obj)->legacy_vm_type = value;
1449 }
1450 
1451 static void
1452 sev_guest_class_init(ObjectClass *oc, void *data)
1453 {
1454     object_class_property_add_str(oc, "dh-cert-file",
1455                                   sev_guest_get_dh_cert_file,
1456                                   sev_guest_set_dh_cert_file);
1457     object_class_property_set_description(oc, "dh-cert-file",
1458             "guest owners DH certificate (encoded with base64)");
1459     object_class_property_add_str(oc, "session-file",
1460                                   sev_guest_get_session_file,
1461                                   sev_guest_set_session_file);
1462     object_class_property_set_description(oc, "session-file",
1463             "guest owners session parameters (encoded with base64)");
1464     object_class_property_add_bool(oc, "legacy-vm-type",
1465                                    sev_guest_get_legacy_vm_type,
1466                                    sev_guest_set_legacy_vm_type);
1467     object_class_property_set_description(oc, "legacy-vm-type",
1468             "use legacy VM type to maintain measurement compatibility with older QEMU or kernel versions.");
1469 }
1470 
1471 static void
1472 sev_guest_instance_init(Object *obj)
1473 {
1474     SevGuestState *sev_guest = SEV_GUEST(obj);
1475 
1476     sev_guest->policy = DEFAULT_GUEST_POLICY;
1477     object_property_add_uint32_ptr(obj, "handle", &sev_guest->handle,
1478                                    OBJ_PROP_FLAG_READWRITE);
1479     object_property_add_uint32_ptr(obj, "policy", &sev_guest->policy,
1480                                    OBJ_PROP_FLAG_READWRITE);
1481     object_apply_compat_props(obj);
1482 }
1483 
1484 /* guest info specific sev/sev-es */
1485 static const TypeInfo sev_guest_info = {
1486     .parent = TYPE_SEV_COMMON,
1487     .name = TYPE_SEV_GUEST,
1488     .instance_size = sizeof(SevGuestState),
1489     .instance_init = sev_guest_instance_init,
1490     .class_init = sev_guest_class_init,
1491 };
1492 
1493 static void
1494 sev_register_types(void)
1495 {
1496     type_register_static(&sev_common_info);
1497     type_register_static(&sev_guest_info);
1498 }
1499 
1500 type_init(sev_register_types);
1501