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