xref: /openbmc/qemu/target/i386/kvm/kvm.c (revision 55d71e0b)
1 /*
2  * QEMU KVM support
3  *
4  * Copyright (C) 2006-2008 Qumranet Technologies
5  * Copyright IBM, Corp. 2008
6  *
7  * Authors:
8  *  Anthony Liguori   <aliguori@us.ibm.com>
9  *
10  * This work is licensed under the terms of the GNU GPL, version 2 or later.
11  * See the COPYING file in the top-level directory.
12  *
13  */
14 
15 #include "qemu/osdep.h"
16 #include "qapi/qapi-events-run-state.h"
17 #include "qapi/error.h"
18 #include <sys/ioctl.h>
19 #include <sys/utsname.h>
20 #include <sys/syscall.h>
21 
22 #include <linux/kvm.h>
23 #include "standard-headers/asm-x86/kvm_para.h"
24 
25 #include "cpu.h"
26 #include "host-cpu.h"
27 #include "sysemu/sysemu.h"
28 #include "sysemu/hw_accel.h"
29 #include "sysemu/kvm_int.h"
30 #include "sysemu/runstate.h"
31 #include "kvm_i386.h"
32 #include "sev.h"
33 #include "hyperv.h"
34 #include "hyperv-proto.h"
35 
36 #include "exec/gdbstub.h"
37 #include "qemu/host-utils.h"
38 #include "qemu/main-loop.h"
39 #include "qemu/config-file.h"
40 #include "qemu/error-report.h"
41 #include "qemu/memalign.h"
42 #include "hw/i386/x86.h"
43 #include "hw/i386/apic.h"
44 #include "hw/i386/apic_internal.h"
45 #include "hw/i386/apic-msidef.h"
46 #include "hw/i386/intel_iommu.h"
47 #include "hw/i386/x86-iommu.h"
48 #include "hw/i386/e820_memory_layout.h"
49 
50 #include "hw/pci/pci.h"
51 #include "hw/pci/msi.h"
52 #include "hw/pci/msix.h"
53 #include "migration/blocker.h"
54 #include "exec/memattrs.h"
55 #include "trace.h"
56 
57 #include CONFIG_DEVICES
58 
59 //#define DEBUG_KVM
60 
61 #ifdef DEBUG_KVM
62 #define DPRINTF(fmt, ...) \
63     do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
64 #else
65 #define DPRINTF(fmt, ...) \
66     do { } while (0)
67 #endif
68 
69 /* From arch/x86/kvm/lapic.h */
70 #define KVM_APIC_BUS_CYCLE_NS       1
71 #define KVM_APIC_BUS_FREQUENCY      (1000000000ULL / KVM_APIC_BUS_CYCLE_NS)
72 
73 #define MSR_KVM_WALL_CLOCK  0x11
74 #define MSR_KVM_SYSTEM_TIME 0x12
75 
76 /* A 4096-byte buffer can hold the 8-byte kvm_msrs header, plus
77  * 255 kvm_msr_entry structs */
78 #define MSR_BUF_SIZE 4096
79 
80 static void kvm_init_msrs(X86CPU *cpu);
81 
82 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
83     KVM_CAP_INFO(SET_TSS_ADDR),
84     KVM_CAP_INFO(EXT_CPUID),
85     KVM_CAP_INFO(MP_STATE),
86     KVM_CAP_LAST_INFO
87 };
88 
89 static bool has_msr_star;
90 static bool has_msr_hsave_pa;
91 static bool has_msr_tsc_aux;
92 static bool has_msr_tsc_adjust;
93 static bool has_msr_tsc_deadline;
94 static bool has_msr_feature_control;
95 static bool has_msr_misc_enable;
96 static bool has_msr_smbase;
97 static bool has_msr_bndcfgs;
98 static int lm_capable_kernel;
99 static bool has_msr_hv_hypercall;
100 static bool has_msr_hv_crash;
101 static bool has_msr_hv_reset;
102 static bool has_msr_hv_vpindex;
103 static bool hv_vpindex_settable;
104 static bool has_msr_hv_runtime;
105 static bool has_msr_hv_synic;
106 static bool has_msr_hv_stimer;
107 static bool has_msr_hv_frequencies;
108 static bool has_msr_hv_reenlightenment;
109 static bool has_msr_hv_syndbg_options;
110 static bool has_msr_xss;
111 static bool has_msr_umwait;
112 static bool has_msr_spec_ctrl;
113 static bool has_tsc_scale_msr;
114 static bool has_msr_tsx_ctrl;
115 static bool has_msr_virt_ssbd;
116 static bool has_msr_smi_count;
117 static bool has_msr_arch_capabs;
118 static bool has_msr_core_capabs;
119 static bool has_msr_vmx_vmfunc;
120 static bool has_msr_ucode_rev;
121 static bool has_msr_vmx_procbased_ctls2;
122 static bool has_msr_perf_capabs;
123 static bool has_msr_pkrs;
124 
125 static uint32_t has_architectural_pmu_version;
126 static uint32_t num_architectural_pmu_gp_counters;
127 static uint32_t num_architectural_pmu_fixed_counters;
128 
129 static int has_xsave;
130 static int has_xsave2;
131 static int has_xcrs;
132 static int has_pit_state2;
133 static int has_sregs2;
134 static int has_exception_payload;
135 
136 static bool has_msr_mcg_ext_ctl;
137 
138 static struct kvm_cpuid2 *cpuid_cache;
139 static struct kvm_cpuid2 *hv_cpuid_cache;
140 static struct kvm_msr_list *kvm_feature_msrs;
141 
142 #define BUS_LOCK_SLICE_TIME 1000000000ULL /* ns */
143 static RateLimit bus_lock_ratelimit_ctrl;
144 
145 int kvm_has_pit_state2(void)
146 {
147     return has_pit_state2;
148 }
149 
150 bool kvm_has_smm(void)
151 {
152     return kvm_vm_check_extension(kvm_state, KVM_CAP_X86_SMM);
153 }
154 
155 bool kvm_has_adjust_clock_stable(void)
156 {
157     int ret = kvm_check_extension(kvm_state, KVM_CAP_ADJUST_CLOCK);
158 
159     return (ret == KVM_CLOCK_TSC_STABLE);
160 }
161 
162 bool kvm_has_adjust_clock(void)
163 {
164     return kvm_check_extension(kvm_state, KVM_CAP_ADJUST_CLOCK);
165 }
166 
167 bool kvm_has_exception_payload(void)
168 {
169     return has_exception_payload;
170 }
171 
172 static bool kvm_x2apic_api_set_flags(uint64_t flags)
173 {
174     KVMState *s = KVM_STATE(current_accel());
175 
176     return !kvm_vm_enable_cap(s, KVM_CAP_X2APIC_API, 0, flags);
177 }
178 
179 #define MEMORIZE(fn, _result) \
180     ({ \
181         static bool _memorized; \
182         \
183         if (_memorized) { \
184             return _result; \
185         } \
186         _memorized = true; \
187         _result = fn; \
188     })
189 
190 static bool has_x2apic_api;
191 
192 bool kvm_has_x2apic_api(void)
193 {
194     return has_x2apic_api;
195 }
196 
197 bool kvm_enable_x2apic(void)
198 {
199     return MEMORIZE(
200              kvm_x2apic_api_set_flags(KVM_X2APIC_API_USE_32BIT_IDS |
201                                       KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK),
202              has_x2apic_api);
203 }
204 
205 bool kvm_hv_vpindex_settable(void)
206 {
207     return hv_vpindex_settable;
208 }
209 
210 static int kvm_get_tsc(CPUState *cs)
211 {
212     X86CPU *cpu = X86_CPU(cs);
213     CPUX86State *env = &cpu->env;
214     struct {
215         struct kvm_msrs info;
216         struct kvm_msr_entry entries[1];
217     } msr_data = {};
218     int ret;
219 
220     if (env->tsc_valid) {
221         return 0;
222     }
223 
224     memset(&msr_data, 0, sizeof(msr_data));
225     msr_data.info.nmsrs = 1;
226     msr_data.entries[0].index = MSR_IA32_TSC;
227     env->tsc_valid = !runstate_is_running();
228 
229     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
230     if (ret < 0) {
231         return ret;
232     }
233 
234     assert(ret == 1);
235     env->tsc = msr_data.entries[0].data;
236     return 0;
237 }
238 
239 static inline void do_kvm_synchronize_tsc(CPUState *cpu, run_on_cpu_data arg)
240 {
241     kvm_get_tsc(cpu);
242 }
243 
244 void kvm_synchronize_all_tsc(void)
245 {
246     CPUState *cpu;
247 
248     if (kvm_enabled()) {
249         CPU_FOREACH(cpu) {
250             run_on_cpu(cpu, do_kvm_synchronize_tsc, RUN_ON_CPU_NULL);
251         }
252     }
253 }
254 
255 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
256 {
257     struct kvm_cpuid2 *cpuid;
258     int r, size;
259 
260     size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
261     cpuid = g_malloc0(size);
262     cpuid->nent = max;
263     r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
264     if (r == 0 && cpuid->nent >= max) {
265         r = -E2BIG;
266     }
267     if (r < 0) {
268         if (r == -E2BIG) {
269             g_free(cpuid);
270             return NULL;
271         } else {
272             fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
273                     strerror(-r));
274             exit(1);
275         }
276     }
277     return cpuid;
278 }
279 
280 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
281  * for all entries.
282  */
283 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
284 {
285     struct kvm_cpuid2 *cpuid;
286     int max = 1;
287 
288     if (cpuid_cache != NULL) {
289         return cpuid_cache;
290     }
291     while ((cpuid = try_get_cpuid(s, max)) == NULL) {
292         max *= 2;
293     }
294     cpuid_cache = cpuid;
295     return cpuid;
296 }
297 
298 static bool host_tsx_broken(void)
299 {
300     int family, model, stepping;\
301     char vendor[CPUID_VENDOR_SZ + 1];
302 
303     host_cpu_vendor_fms(vendor, &family, &model, &stepping);
304 
305     /* Check if we are running on a Haswell host known to have broken TSX */
306     return !strcmp(vendor, CPUID_VENDOR_INTEL) &&
307            (family == 6) &&
308            ((model == 63 && stepping < 4) ||
309             model == 60 || model == 69 || model == 70);
310 }
311 
312 /* Returns the value for a specific register on the cpuid entry
313  */
314 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
315 {
316     uint32_t ret = 0;
317     switch (reg) {
318     case R_EAX:
319         ret = entry->eax;
320         break;
321     case R_EBX:
322         ret = entry->ebx;
323         break;
324     case R_ECX:
325         ret = entry->ecx;
326         break;
327     case R_EDX:
328         ret = entry->edx;
329         break;
330     }
331     return ret;
332 }
333 
334 /* Find matching entry for function/index on kvm_cpuid2 struct
335  */
336 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
337                                                  uint32_t function,
338                                                  uint32_t index)
339 {
340     int i;
341     for (i = 0; i < cpuid->nent; ++i) {
342         if (cpuid->entries[i].function == function &&
343             cpuid->entries[i].index == index) {
344             return &cpuid->entries[i];
345         }
346     }
347     /* not found: */
348     return NULL;
349 }
350 
351 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
352                                       uint32_t index, int reg)
353 {
354     struct kvm_cpuid2 *cpuid;
355     uint32_t ret = 0;
356     uint32_t cpuid_1_edx;
357     uint64_t bitmask;
358 
359     cpuid = get_supported_cpuid(s);
360 
361     struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
362     if (entry) {
363         ret = cpuid_entry_get_reg(entry, reg);
364     }
365 
366     /* Fixups for the data returned by KVM, below */
367 
368     if (function == 1 && reg == R_EDX) {
369         /* KVM before 2.6.30 misreports the following features */
370         ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
371     } else if (function == 1 && reg == R_ECX) {
372         /* We can set the hypervisor flag, even if KVM does not return it on
373          * GET_SUPPORTED_CPUID
374          */
375         ret |= CPUID_EXT_HYPERVISOR;
376         /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
377          * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
378          * and the irqchip is in the kernel.
379          */
380         if (kvm_irqchip_in_kernel() &&
381                 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
382             ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
383         }
384 
385         /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
386          * without the in-kernel irqchip
387          */
388         if (!kvm_irqchip_in_kernel()) {
389             ret &= ~CPUID_EXT_X2APIC;
390         }
391 
392         if (enable_cpu_pm) {
393             int disable_exits = kvm_check_extension(s,
394                                                     KVM_CAP_X86_DISABLE_EXITS);
395 
396             if (disable_exits & KVM_X86_DISABLE_EXITS_MWAIT) {
397                 ret |= CPUID_EXT_MONITOR;
398             }
399         }
400     } else if (function == 6 && reg == R_EAX) {
401         ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
402     } else if (function == 7 && index == 0 && reg == R_EBX) {
403         if (host_tsx_broken()) {
404             ret &= ~(CPUID_7_0_EBX_RTM | CPUID_7_0_EBX_HLE);
405         }
406     } else if (function == 7 && index == 0 && reg == R_EDX) {
407         /*
408          * Linux v4.17-v4.20 incorrectly return ARCH_CAPABILITIES on SVM hosts.
409          * We can detect the bug by checking if MSR_IA32_ARCH_CAPABILITIES is
410          * returned by KVM_GET_MSR_INDEX_LIST.
411          */
412         if (!has_msr_arch_capabs) {
413             ret &= ~CPUID_7_0_EDX_ARCH_CAPABILITIES;
414         }
415     } else if (function == 0xd && index == 0 &&
416                (reg == R_EAX || reg == R_EDX)) {
417         /*
418          * The value returned by KVM_GET_SUPPORTED_CPUID does not include
419          * features that still have to be enabled with the arch_prctl
420          * system call.  QEMU needs the full value, which is retrieved
421          * with KVM_GET_DEVICE_ATTR.
422          */
423         struct kvm_device_attr attr = {
424             .group = 0,
425             .attr = KVM_X86_XCOMP_GUEST_SUPP,
426             .addr = (unsigned long) &bitmask
427         };
428 
429         bool sys_attr = kvm_check_extension(s, KVM_CAP_SYS_ATTRIBUTES);
430         if (!sys_attr) {
431             return ret;
432         }
433 
434         int rc = kvm_ioctl(s, KVM_GET_DEVICE_ATTR, &attr);
435         if (rc < 0) {
436             if (rc != -ENXIO) {
437                 warn_report("KVM_GET_DEVICE_ATTR(0, KVM_X86_XCOMP_GUEST_SUPP) "
438                             "error: %d", rc);
439             }
440             return ret;
441         }
442         ret = (reg == R_EAX) ? bitmask : bitmask >> 32;
443     } else if (function == 0x80000001 && reg == R_ECX) {
444         /*
445          * It's safe to enable TOPOEXT even if it's not returned by
446          * GET_SUPPORTED_CPUID.  Unconditionally enabling TOPOEXT here allows
447          * us to keep CPU models including TOPOEXT runnable on older kernels.
448          */
449         ret |= CPUID_EXT3_TOPOEXT;
450     } else if (function == 0x80000001 && reg == R_EDX) {
451         /* On Intel, kvm returns cpuid according to the Intel spec,
452          * so add missing bits according to the AMD spec:
453          */
454         cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
455         ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
456     } else if (function == KVM_CPUID_FEATURES && reg == R_EAX) {
457         /* kvm_pv_unhalt is reported by GET_SUPPORTED_CPUID, but it can't
458          * be enabled without the in-kernel irqchip
459          */
460         if (!kvm_irqchip_in_kernel()) {
461             ret &= ~(1U << KVM_FEATURE_PV_UNHALT);
462         }
463         if (kvm_irqchip_is_split()) {
464             ret |= 1U << KVM_FEATURE_MSI_EXT_DEST_ID;
465         }
466     } else if (function == KVM_CPUID_FEATURES && reg == R_EDX) {
467         ret |= 1U << KVM_HINTS_REALTIME;
468     }
469 
470     return ret;
471 }
472 
473 uint64_t kvm_arch_get_supported_msr_feature(KVMState *s, uint32_t index)
474 {
475     struct {
476         struct kvm_msrs info;
477         struct kvm_msr_entry entries[1];
478     } msr_data = {};
479     uint64_t value;
480     uint32_t ret, can_be_one, must_be_one;
481 
482     if (kvm_feature_msrs == NULL) { /* Host doesn't support feature MSRs */
483         return 0;
484     }
485 
486     /* Check if requested MSR is supported feature MSR */
487     int i;
488     for (i = 0; i < kvm_feature_msrs->nmsrs; i++)
489         if (kvm_feature_msrs->indices[i] == index) {
490             break;
491         }
492     if (i == kvm_feature_msrs->nmsrs) {
493         return 0; /* if the feature MSR is not supported, simply return 0 */
494     }
495 
496     msr_data.info.nmsrs = 1;
497     msr_data.entries[0].index = index;
498 
499     ret = kvm_ioctl(s, KVM_GET_MSRS, &msr_data);
500     if (ret != 1) {
501         error_report("KVM get MSR (index=0x%x) feature failed, %s",
502             index, strerror(-ret));
503         exit(1);
504     }
505 
506     value = msr_data.entries[0].data;
507     switch (index) {
508     case MSR_IA32_VMX_PROCBASED_CTLS2:
509         if (!has_msr_vmx_procbased_ctls2) {
510             /* KVM forgot to add these bits for some time, do this ourselves. */
511             if (kvm_arch_get_supported_cpuid(s, 0xD, 1, R_ECX) &
512                 CPUID_XSAVE_XSAVES) {
513                 value |= (uint64_t)VMX_SECONDARY_EXEC_XSAVES << 32;
514             }
515             if (kvm_arch_get_supported_cpuid(s, 1, 0, R_ECX) &
516                 CPUID_EXT_RDRAND) {
517                 value |= (uint64_t)VMX_SECONDARY_EXEC_RDRAND_EXITING << 32;
518             }
519             if (kvm_arch_get_supported_cpuid(s, 7, 0, R_EBX) &
520                 CPUID_7_0_EBX_INVPCID) {
521                 value |= (uint64_t)VMX_SECONDARY_EXEC_ENABLE_INVPCID << 32;
522             }
523             if (kvm_arch_get_supported_cpuid(s, 7, 0, R_EBX) &
524                 CPUID_7_0_EBX_RDSEED) {
525                 value |= (uint64_t)VMX_SECONDARY_EXEC_RDSEED_EXITING << 32;
526             }
527             if (kvm_arch_get_supported_cpuid(s, 0x80000001, 0, R_EDX) &
528                 CPUID_EXT2_RDTSCP) {
529                 value |= (uint64_t)VMX_SECONDARY_EXEC_RDTSCP << 32;
530             }
531         }
532         /* fall through */
533     case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
534     case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
535     case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
536     case MSR_IA32_VMX_TRUE_EXIT_CTLS:
537         /*
538          * Return true for bits that can be one, but do not have to be one.
539          * The SDM tells us which bits could have a "must be one" setting,
540          * so we can do the opposite transformation in make_vmx_msr_value.
541          */
542         must_be_one = (uint32_t)value;
543         can_be_one = (uint32_t)(value >> 32);
544         return can_be_one & ~must_be_one;
545 
546     default:
547         return value;
548     }
549 }
550 
551 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
552                                      int *max_banks)
553 {
554     int r;
555 
556     r = kvm_check_extension(s, KVM_CAP_MCE);
557     if (r > 0) {
558         *max_banks = r;
559         return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
560     }
561     return -ENOSYS;
562 }
563 
564 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
565 {
566     CPUState *cs = CPU(cpu);
567     CPUX86State *env = &cpu->env;
568     uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
569                       MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
570     uint64_t mcg_status = MCG_STATUS_MCIP;
571     int flags = 0;
572 
573     if (code == BUS_MCEERR_AR) {
574         status |= MCI_STATUS_AR | 0x134;
575         mcg_status |= MCG_STATUS_RIPV | MCG_STATUS_EIPV;
576     } else {
577         status |= 0xc0;
578         mcg_status |= MCG_STATUS_RIPV;
579     }
580 
581     flags = cpu_x86_support_mca_broadcast(env) ? MCE_INJECT_BROADCAST : 0;
582     /* We need to read back the value of MSR_EXT_MCG_CTL that was set by the
583      * guest kernel back into env->mcg_ext_ctl.
584      */
585     cpu_synchronize_state(cs);
586     if (env->mcg_ext_ctl & MCG_EXT_CTL_LMCE_EN) {
587         mcg_status |= MCG_STATUS_LMCE;
588         flags = 0;
589     }
590 
591     cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
592                        (MCM_ADDR_PHYS << 6) | 0xc, flags);
593 }
594 
595 static void emit_hypervisor_memory_failure(MemoryFailureAction action, bool ar)
596 {
597     MemoryFailureFlags mff = {.action_required = ar, .recursive = false};
598 
599     qapi_event_send_memory_failure(MEMORY_FAILURE_RECIPIENT_HYPERVISOR, action,
600                                    &mff);
601 }
602 
603 static void hardware_memory_error(void *host_addr)
604 {
605     emit_hypervisor_memory_failure(MEMORY_FAILURE_ACTION_FATAL, true);
606     error_report("QEMU got Hardware memory error at addr %p", host_addr);
607     exit(1);
608 }
609 
610 void kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
611 {
612     X86CPU *cpu = X86_CPU(c);
613     CPUX86State *env = &cpu->env;
614     ram_addr_t ram_addr;
615     hwaddr paddr;
616 
617     /* If we get an action required MCE, it has been injected by KVM
618      * while the VM was running.  An action optional MCE instead should
619      * be coming from the main thread, which qemu_init_sigbus identifies
620      * as the "early kill" thread.
621      */
622     assert(code == BUS_MCEERR_AR || code == BUS_MCEERR_AO);
623 
624     if ((env->mcg_cap & MCG_SER_P) && addr) {
625         ram_addr = qemu_ram_addr_from_host(addr);
626         if (ram_addr != RAM_ADDR_INVALID &&
627             kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
628             kvm_hwpoison_page_add(ram_addr);
629             kvm_mce_inject(cpu, paddr, code);
630 
631             /*
632              * Use different logging severity based on error type.
633              * If there is additional MCE reporting on the hypervisor, QEMU VA
634              * could be another source to identify the PA and MCE details.
635              */
636             if (code == BUS_MCEERR_AR) {
637                 error_report("Guest MCE Memory Error at QEMU addr %p and "
638                     "GUEST addr 0x%" HWADDR_PRIx " of type %s injected",
639                     addr, paddr, "BUS_MCEERR_AR");
640             } else {
641                  warn_report("Guest MCE Memory Error at QEMU addr %p and "
642                      "GUEST addr 0x%" HWADDR_PRIx " of type %s injected",
643                      addr, paddr, "BUS_MCEERR_AO");
644             }
645 
646             return;
647         }
648 
649         if (code == BUS_MCEERR_AO) {
650             warn_report("Hardware memory error at addr %p of type %s "
651                 "for memory used by QEMU itself instead of guest system!",
652                  addr, "BUS_MCEERR_AO");
653         }
654     }
655 
656     if (code == BUS_MCEERR_AR) {
657         hardware_memory_error(addr);
658     }
659 
660     /* Hope we are lucky for AO MCE, just notify a event */
661     emit_hypervisor_memory_failure(MEMORY_FAILURE_ACTION_IGNORE, false);
662 }
663 
664 static void kvm_reset_exception(CPUX86State *env)
665 {
666     env->exception_nr = -1;
667     env->exception_pending = 0;
668     env->exception_injected = 0;
669     env->exception_has_payload = false;
670     env->exception_payload = 0;
671 }
672 
673 static void kvm_queue_exception(CPUX86State *env,
674                                 int32_t exception_nr,
675                                 uint8_t exception_has_payload,
676                                 uint64_t exception_payload)
677 {
678     assert(env->exception_nr == -1);
679     assert(!env->exception_pending);
680     assert(!env->exception_injected);
681     assert(!env->exception_has_payload);
682 
683     env->exception_nr = exception_nr;
684 
685     if (has_exception_payload) {
686         env->exception_pending = 1;
687 
688         env->exception_has_payload = exception_has_payload;
689         env->exception_payload = exception_payload;
690     } else {
691         env->exception_injected = 1;
692 
693         if (exception_nr == EXCP01_DB) {
694             assert(exception_has_payload);
695             env->dr[6] = exception_payload;
696         } else if (exception_nr == EXCP0E_PAGE) {
697             assert(exception_has_payload);
698             env->cr[2] = exception_payload;
699         } else {
700             assert(!exception_has_payload);
701         }
702     }
703 }
704 
705 static int kvm_inject_mce_oldstyle(X86CPU *cpu)
706 {
707     CPUX86State *env = &cpu->env;
708 
709     if (!kvm_has_vcpu_events() && env->exception_nr == EXCP12_MCHK) {
710         unsigned int bank, bank_num = env->mcg_cap & 0xff;
711         struct kvm_x86_mce mce;
712 
713         kvm_reset_exception(env);
714 
715         /*
716          * There must be at least one bank in use if an MCE is pending.
717          * Find it and use its values for the event injection.
718          */
719         for (bank = 0; bank < bank_num; bank++) {
720             if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
721                 break;
722             }
723         }
724         assert(bank < bank_num);
725 
726         mce.bank = bank;
727         mce.status = env->mce_banks[bank * 4 + 1];
728         mce.mcg_status = env->mcg_status;
729         mce.addr = env->mce_banks[bank * 4 + 2];
730         mce.misc = env->mce_banks[bank * 4 + 3];
731 
732         return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
733     }
734     return 0;
735 }
736 
737 static void cpu_update_state(void *opaque, bool running, RunState state)
738 {
739     CPUX86State *env = opaque;
740 
741     if (running) {
742         env->tsc_valid = false;
743     }
744 }
745 
746 unsigned long kvm_arch_vcpu_id(CPUState *cs)
747 {
748     X86CPU *cpu = X86_CPU(cs);
749     return cpu->apic_id;
750 }
751 
752 #ifndef KVM_CPUID_SIGNATURE_NEXT
753 #define KVM_CPUID_SIGNATURE_NEXT                0x40000100
754 #endif
755 
756 static bool hyperv_enabled(X86CPU *cpu)
757 {
758     return kvm_check_extension(kvm_state, KVM_CAP_HYPERV) > 0 &&
759         ((cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_NOTIFY) ||
760          cpu->hyperv_features || cpu->hyperv_passthrough);
761 }
762 
763 /*
764  * Check whether target_freq is within conservative
765  * ntp correctable bounds (250ppm) of freq
766  */
767 static inline bool freq_within_bounds(int freq, int target_freq)
768 {
769         int max_freq = freq + (freq * 250 / 1000000);
770         int min_freq = freq - (freq * 250 / 1000000);
771 
772         if (target_freq >= min_freq && target_freq <= max_freq) {
773                 return true;
774         }
775 
776         return false;
777 }
778 
779 static int kvm_arch_set_tsc_khz(CPUState *cs)
780 {
781     X86CPU *cpu = X86_CPU(cs);
782     CPUX86State *env = &cpu->env;
783     int r, cur_freq;
784     bool set_ioctl = false;
785 
786     if (!env->tsc_khz) {
787         return 0;
788     }
789 
790     cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
791                kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) : -ENOTSUP;
792 
793     /*
794      * If TSC scaling is supported, attempt to set TSC frequency.
795      */
796     if (kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL)) {
797         set_ioctl = true;
798     }
799 
800     /*
801      * If desired TSC frequency is within bounds of NTP correction,
802      * attempt to set TSC frequency.
803      */
804     if (cur_freq != -ENOTSUP && freq_within_bounds(cur_freq, env->tsc_khz)) {
805         set_ioctl = true;
806     }
807 
808     r = set_ioctl ?
809         kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) :
810         -ENOTSUP;
811 
812     if (r < 0) {
813         /* When KVM_SET_TSC_KHZ fails, it's an error only if the current
814          * TSC frequency doesn't match the one we want.
815          */
816         cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
817                    kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
818                    -ENOTSUP;
819         if (cur_freq <= 0 || cur_freq != env->tsc_khz) {
820             warn_report("TSC frequency mismatch between "
821                         "VM (%" PRId64 " kHz) and host (%d kHz), "
822                         "and TSC scaling unavailable",
823                         env->tsc_khz, cur_freq);
824             return r;
825         }
826     }
827 
828     return 0;
829 }
830 
831 static bool tsc_is_stable_and_known(CPUX86State *env)
832 {
833     if (!env->tsc_khz) {
834         return false;
835     }
836     return (env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC)
837         || env->user_tsc_khz;
838 }
839 
840 static struct {
841     const char *desc;
842     struct {
843         uint32_t func;
844         int reg;
845         uint32_t bits;
846     } flags[2];
847     uint64_t dependencies;
848 } kvm_hyperv_properties[] = {
849     [HYPERV_FEAT_RELAXED] = {
850         .desc = "relaxed timing (hv-relaxed)",
851         .flags = {
852             {.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
853              .bits = HV_RELAXED_TIMING_RECOMMENDED}
854         }
855     },
856     [HYPERV_FEAT_VAPIC] = {
857         .desc = "virtual APIC (hv-vapic)",
858         .flags = {
859             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
860              .bits = HV_APIC_ACCESS_AVAILABLE}
861         }
862     },
863     [HYPERV_FEAT_TIME] = {
864         .desc = "clocksources (hv-time)",
865         .flags = {
866             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
867              .bits = HV_TIME_REF_COUNT_AVAILABLE | HV_REFERENCE_TSC_AVAILABLE}
868         }
869     },
870     [HYPERV_FEAT_CRASH] = {
871         .desc = "crash MSRs (hv-crash)",
872         .flags = {
873             {.func = HV_CPUID_FEATURES, .reg = R_EDX,
874              .bits = HV_GUEST_CRASH_MSR_AVAILABLE}
875         }
876     },
877     [HYPERV_FEAT_RESET] = {
878         .desc = "reset MSR (hv-reset)",
879         .flags = {
880             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
881              .bits = HV_RESET_AVAILABLE}
882         }
883     },
884     [HYPERV_FEAT_VPINDEX] = {
885         .desc = "VP_INDEX MSR (hv-vpindex)",
886         .flags = {
887             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
888              .bits = HV_VP_INDEX_AVAILABLE}
889         }
890     },
891     [HYPERV_FEAT_RUNTIME] = {
892         .desc = "VP_RUNTIME MSR (hv-runtime)",
893         .flags = {
894             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
895              .bits = HV_VP_RUNTIME_AVAILABLE}
896         }
897     },
898     [HYPERV_FEAT_SYNIC] = {
899         .desc = "synthetic interrupt controller (hv-synic)",
900         .flags = {
901             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
902              .bits = HV_SYNIC_AVAILABLE}
903         }
904     },
905     [HYPERV_FEAT_STIMER] = {
906         .desc = "synthetic timers (hv-stimer)",
907         .flags = {
908             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
909              .bits = HV_SYNTIMERS_AVAILABLE}
910         },
911         .dependencies = BIT(HYPERV_FEAT_SYNIC) | BIT(HYPERV_FEAT_TIME)
912     },
913     [HYPERV_FEAT_FREQUENCIES] = {
914         .desc = "frequency MSRs (hv-frequencies)",
915         .flags = {
916             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
917              .bits = HV_ACCESS_FREQUENCY_MSRS},
918             {.func = HV_CPUID_FEATURES, .reg = R_EDX,
919              .bits = HV_FREQUENCY_MSRS_AVAILABLE}
920         }
921     },
922     [HYPERV_FEAT_REENLIGHTENMENT] = {
923         .desc = "reenlightenment MSRs (hv-reenlightenment)",
924         .flags = {
925             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
926              .bits = HV_ACCESS_REENLIGHTENMENTS_CONTROL}
927         }
928     },
929     [HYPERV_FEAT_TLBFLUSH] = {
930         .desc = "paravirtualized TLB flush (hv-tlbflush)",
931         .flags = {
932             {.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
933              .bits = HV_REMOTE_TLB_FLUSH_RECOMMENDED |
934              HV_EX_PROCESSOR_MASKS_RECOMMENDED}
935         },
936         .dependencies = BIT(HYPERV_FEAT_VPINDEX)
937     },
938     [HYPERV_FEAT_EVMCS] = {
939         .desc = "enlightened VMCS (hv-evmcs)",
940         .flags = {
941             {.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
942              .bits = HV_ENLIGHTENED_VMCS_RECOMMENDED}
943         },
944         .dependencies = BIT(HYPERV_FEAT_VAPIC)
945     },
946     [HYPERV_FEAT_IPI] = {
947         .desc = "paravirtualized IPI (hv-ipi)",
948         .flags = {
949             {.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
950              .bits = HV_CLUSTER_IPI_RECOMMENDED |
951              HV_EX_PROCESSOR_MASKS_RECOMMENDED}
952         },
953         .dependencies = BIT(HYPERV_FEAT_VPINDEX)
954     },
955     [HYPERV_FEAT_STIMER_DIRECT] = {
956         .desc = "direct mode synthetic timers (hv-stimer-direct)",
957         .flags = {
958             {.func = HV_CPUID_FEATURES, .reg = R_EDX,
959              .bits = HV_STIMER_DIRECT_MODE_AVAILABLE}
960         },
961         .dependencies = BIT(HYPERV_FEAT_STIMER)
962     },
963     [HYPERV_FEAT_AVIC] = {
964         .desc = "AVIC/APICv support (hv-avic/hv-apicv)",
965         .flags = {
966             {.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
967              .bits = HV_DEPRECATING_AEOI_RECOMMENDED}
968         }
969     },
970 #ifdef CONFIG_SYNDBG
971     [HYPERV_FEAT_SYNDBG] = {
972         .desc = "Enable synthetic kernel debugger channel (hv-syndbg)",
973         .flags = {
974             {.func = HV_CPUID_FEATURES, .reg = R_EDX,
975              .bits = HV_FEATURE_DEBUG_MSRS_AVAILABLE}
976         },
977         .dependencies = BIT(HYPERV_FEAT_SYNIC) | BIT(HYPERV_FEAT_RELAXED)
978     },
979 #endif
980 };
981 
982 static struct kvm_cpuid2 *try_get_hv_cpuid(CPUState *cs, int max,
983                                            bool do_sys_ioctl)
984 {
985     struct kvm_cpuid2 *cpuid;
986     int r, size;
987 
988     size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
989     cpuid = g_malloc0(size);
990     cpuid->nent = max;
991 
992     if (do_sys_ioctl) {
993         r = kvm_ioctl(kvm_state, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
994     } else {
995         r = kvm_vcpu_ioctl(cs, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
996     }
997     if (r == 0 && cpuid->nent >= max) {
998         r = -E2BIG;
999     }
1000     if (r < 0) {
1001         if (r == -E2BIG) {
1002             g_free(cpuid);
1003             return NULL;
1004         } else {
1005             fprintf(stderr, "KVM_GET_SUPPORTED_HV_CPUID failed: %s\n",
1006                     strerror(-r));
1007             exit(1);
1008         }
1009     }
1010     return cpuid;
1011 }
1012 
1013 /*
1014  * Run KVM_GET_SUPPORTED_HV_CPUID ioctl(), allocating a buffer large enough
1015  * for all entries.
1016  */
1017 static struct kvm_cpuid2 *get_supported_hv_cpuid(CPUState *cs)
1018 {
1019     struct kvm_cpuid2 *cpuid;
1020     /* 0x40000000..0x40000005, 0x4000000A, 0x40000080..0x40000082 leaves */
1021     int max = 11;
1022     int i;
1023     bool do_sys_ioctl;
1024 
1025     do_sys_ioctl =
1026         kvm_check_extension(kvm_state, KVM_CAP_SYS_HYPERV_CPUID) > 0;
1027 
1028     /*
1029      * Non-empty KVM context is needed when KVM_CAP_SYS_HYPERV_CPUID is
1030      * unsupported, kvm_hyperv_expand_features() checks for that.
1031      */
1032     assert(do_sys_ioctl || cs->kvm_state);
1033 
1034     /*
1035      * When the buffer is too small, KVM_GET_SUPPORTED_HV_CPUID fails with
1036      * -E2BIG, however, it doesn't report back the right size. Keep increasing
1037      * it and re-trying until we succeed.
1038      */
1039     while ((cpuid = try_get_hv_cpuid(cs, max, do_sys_ioctl)) == NULL) {
1040         max++;
1041     }
1042 
1043     /*
1044      * KVM_GET_SUPPORTED_HV_CPUID does not set EVMCS CPUID bit before
1045      * KVM_CAP_HYPERV_ENLIGHTENED_VMCS is enabled but we want to get the
1046      * information early, just check for the capability and set the bit
1047      * manually.
1048      */
1049     if (!do_sys_ioctl && kvm_check_extension(cs->kvm_state,
1050                             KVM_CAP_HYPERV_ENLIGHTENED_VMCS) > 0) {
1051         for (i = 0; i < cpuid->nent; i++) {
1052             if (cpuid->entries[i].function == HV_CPUID_ENLIGHTMENT_INFO) {
1053                 cpuid->entries[i].eax |= HV_ENLIGHTENED_VMCS_RECOMMENDED;
1054             }
1055         }
1056     }
1057 
1058     return cpuid;
1059 }
1060 
1061 /*
1062  * When KVM_GET_SUPPORTED_HV_CPUID is not supported we fill CPUID feature
1063  * leaves from KVM_CAP_HYPERV* and present MSRs data.
1064  */
1065 static struct kvm_cpuid2 *get_supported_hv_cpuid_legacy(CPUState *cs)
1066 {
1067     X86CPU *cpu = X86_CPU(cs);
1068     struct kvm_cpuid2 *cpuid;
1069     struct kvm_cpuid_entry2 *entry_feat, *entry_recomm;
1070 
1071     /* HV_CPUID_FEATURES, HV_CPUID_ENLIGHTMENT_INFO */
1072     cpuid = g_malloc0(sizeof(*cpuid) + 2 * sizeof(*cpuid->entries));
1073     cpuid->nent = 2;
1074 
1075     /* HV_CPUID_VENDOR_AND_MAX_FUNCTIONS */
1076     entry_feat = &cpuid->entries[0];
1077     entry_feat->function = HV_CPUID_FEATURES;
1078 
1079     entry_recomm = &cpuid->entries[1];
1080     entry_recomm->function = HV_CPUID_ENLIGHTMENT_INFO;
1081     entry_recomm->ebx = cpu->hyperv_spinlock_attempts;
1082 
1083     if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0) {
1084         entry_feat->eax |= HV_HYPERCALL_AVAILABLE;
1085         entry_feat->eax |= HV_APIC_ACCESS_AVAILABLE;
1086         entry_feat->edx |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
1087         entry_recomm->eax |= HV_RELAXED_TIMING_RECOMMENDED;
1088         entry_recomm->eax |= HV_APIC_ACCESS_RECOMMENDED;
1089     }
1090 
1091     if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) > 0) {
1092         entry_feat->eax |= HV_TIME_REF_COUNT_AVAILABLE;
1093         entry_feat->eax |= HV_REFERENCE_TSC_AVAILABLE;
1094     }
1095 
1096     if (has_msr_hv_frequencies) {
1097         entry_feat->eax |= HV_ACCESS_FREQUENCY_MSRS;
1098         entry_feat->edx |= HV_FREQUENCY_MSRS_AVAILABLE;
1099     }
1100 
1101     if (has_msr_hv_crash) {
1102         entry_feat->edx |= HV_GUEST_CRASH_MSR_AVAILABLE;
1103     }
1104 
1105     if (has_msr_hv_reenlightenment) {
1106         entry_feat->eax |= HV_ACCESS_REENLIGHTENMENTS_CONTROL;
1107     }
1108 
1109     if (has_msr_hv_reset) {
1110         entry_feat->eax |= HV_RESET_AVAILABLE;
1111     }
1112 
1113     if (has_msr_hv_vpindex) {
1114         entry_feat->eax |= HV_VP_INDEX_AVAILABLE;
1115     }
1116 
1117     if (has_msr_hv_runtime) {
1118         entry_feat->eax |= HV_VP_RUNTIME_AVAILABLE;
1119     }
1120 
1121     if (has_msr_hv_synic) {
1122         unsigned int cap = cpu->hyperv_synic_kvm_only ?
1123             KVM_CAP_HYPERV_SYNIC : KVM_CAP_HYPERV_SYNIC2;
1124 
1125         if (kvm_check_extension(cs->kvm_state, cap) > 0) {
1126             entry_feat->eax |= HV_SYNIC_AVAILABLE;
1127         }
1128     }
1129 
1130     if (has_msr_hv_stimer) {
1131         entry_feat->eax |= HV_SYNTIMERS_AVAILABLE;
1132     }
1133 
1134     if (has_msr_hv_syndbg_options) {
1135         entry_feat->edx |= HV_GUEST_DEBUGGING_AVAILABLE;
1136         entry_feat->edx |= HV_FEATURE_DEBUG_MSRS_AVAILABLE;
1137         entry_feat->ebx |= HV_PARTITION_DEBUGGING_ALLOWED;
1138     }
1139 
1140     if (kvm_check_extension(cs->kvm_state,
1141                             KVM_CAP_HYPERV_TLBFLUSH) > 0) {
1142         entry_recomm->eax |= HV_REMOTE_TLB_FLUSH_RECOMMENDED;
1143         entry_recomm->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
1144     }
1145 
1146     if (kvm_check_extension(cs->kvm_state,
1147                             KVM_CAP_HYPERV_ENLIGHTENED_VMCS) > 0) {
1148         entry_recomm->eax |= HV_ENLIGHTENED_VMCS_RECOMMENDED;
1149     }
1150 
1151     if (kvm_check_extension(cs->kvm_state,
1152                             KVM_CAP_HYPERV_SEND_IPI) > 0) {
1153         entry_recomm->eax |= HV_CLUSTER_IPI_RECOMMENDED;
1154         entry_recomm->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
1155     }
1156 
1157     return cpuid;
1158 }
1159 
1160 static uint32_t hv_cpuid_get_host(CPUState *cs, uint32_t func, int reg)
1161 {
1162     struct kvm_cpuid_entry2 *entry;
1163     struct kvm_cpuid2 *cpuid;
1164 
1165     if (hv_cpuid_cache) {
1166         cpuid = hv_cpuid_cache;
1167     } else {
1168         if (kvm_check_extension(kvm_state, KVM_CAP_HYPERV_CPUID) > 0) {
1169             cpuid = get_supported_hv_cpuid(cs);
1170         } else {
1171             /*
1172              * 'cs->kvm_state' may be NULL when Hyper-V features are expanded
1173              * before KVM context is created but this is only done when
1174              * KVM_CAP_SYS_HYPERV_CPUID is supported and it implies
1175              * KVM_CAP_HYPERV_CPUID.
1176              */
1177             assert(cs->kvm_state);
1178 
1179             cpuid = get_supported_hv_cpuid_legacy(cs);
1180         }
1181         hv_cpuid_cache = cpuid;
1182     }
1183 
1184     if (!cpuid) {
1185         return 0;
1186     }
1187 
1188     entry = cpuid_find_entry(cpuid, func, 0);
1189     if (!entry) {
1190         return 0;
1191     }
1192 
1193     return cpuid_entry_get_reg(entry, reg);
1194 }
1195 
1196 static bool hyperv_feature_supported(CPUState *cs, int feature)
1197 {
1198     uint32_t func, bits;
1199     int i, reg;
1200 
1201     for (i = 0; i < ARRAY_SIZE(kvm_hyperv_properties[feature].flags); i++) {
1202 
1203         func = kvm_hyperv_properties[feature].flags[i].func;
1204         reg = kvm_hyperv_properties[feature].flags[i].reg;
1205         bits = kvm_hyperv_properties[feature].flags[i].bits;
1206 
1207         if (!func) {
1208             continue;
1209         }
1210 
1211         if ((hv_cpuid_get_host(cs, func, reg) & bits) != bits) {
1212             return false;
1213         }
1214     }
1215 
1216     return true;
1217 }
1218 
1219 /* Checks that all feature dependencies are enabled */
1220 static bool hv_feature_check_deps(X86CPU *cpu, int feature, Error **errp)
1221 {
1222     uint64_t deps;
1223     int dep_feat;
1224 
1225     deps = kvm_hyperv_properties[feature].dependencies;
1226     while (deps) {
1227         dep_feat = ctz64(deps);
1228         if (!(hyperv_feat_enabled(cpu, dep_feat))) {
1229             error_setg(errp, "Hyper-V %s requires Hyper-V %s",
1230                        kvm_hyperv_properties[feature].desc,
1231                        kvm_hyperv_properties[dep_feat].desc);
1232             return false;
1233         }
1234         deps &= ~(1ull << dep_feat);
1235     }
1236 
1237     return true;
1238 }
1239 
1240 static uint32_t hv_build_cpuid_leaf(CPUState *cs, uint32_t func, int reg)
1241 {
1242     X86CPU *cpu = X86_CPU(cs);
1243     uint32_t r = 0;
1244     int i, j;
1245 
1246     for (i = 0; i < ARRAY_SIZE(kvm_hyperv_properties); i++) {
1247         if (!hyperv_feat_enabled(cpu, i)) {
1248             continue;
1249         }
1250 
1251         for (j = 0; j < ARRAY_SIZE(kvm_hyperv_properties[i].flags); j++) {
1252             if (kvm_hyperv_properties[i].flags[j].func != func) {
1253                 continue;
1254             }
1255             if (kvm_hyperv_properties[i].flags[j].reg != reg) {
1256                 continue;
1257             }
1258 
1259             r |= kvm_hyperv_properties[i].flags[j].bits;
1260         }
1261     }
1262 
1263     return r;
1264 }
1265 
1266 /*
1267  * Expand Hyper-V CPU features. In partucular, check that all the requested
1268  * features are supported by the host and the sanity of the configuration
1269  * (that all the required dependencies are included). Also, this takes care
1270  * of 'hv_passthrough' mode and fills the environment with all supported
1271  * Hyper-V features.
1272  */
1273 bool kvm_hyperv_expand_features(X86CPU *cpu, Error **errp)
1274 {
1275     CPUState *cs = CPU(cpu);
1276     Error *local_err = NULL;
1277     int feat;
1278 
1279     if (!hyperv_enabled(cpu))
1280         return true;
1281 
1282     /*
1283      * When kvm_hyperv_expand_features is called at CPU feature expansion
1284      * time per-CPU kvm_state is not available yet so we can only proceed
1285      * when KVM_CAP_SYS_HYPERV_CPUID is supported.
1286      */
1287     if (!cs->kvm_state &&
1288         !kvm_check_extension(kvm_state, KVM_CAP_SYS_HYPERV_CPUID))
1289         return true;
1290 
1291     if (cpu->hyperv_passthrough) {
1292         cpu->hyperv_vendor_id[0] =
1293             hv_cpuid_get_host(cs, HV_CPUID_VENDOR_AND_MAX_FUNCTIONS, R_EBX);
1294         cpu->hyperv_vendor_id[1] =
1295             hv_cpuid_get_host(cs, HV_CPUID_VENDOR_AND_MAX_FUNCTIONS, R_ECX);
1296         cpu->hyperv_vendor_id[2] =
1297             hv_cpuid_get_host(cs, HV_CPUID_VENDOR_AND_MAX_FUNCTIONS, R_EDX);
1298         cpu->hyperv_vendor = g_realloc(cpu->hyperv_vendor,
1299                                        sizeof(cpu->hyperv_vendor_id) + 1);
1300         memcpy(cpu->hyperv_vendor, cpu->hyperv_vendor_id,
1301                sizeof(cpu->hyperv_vendor_id));
1302         cpu->hyperv_vendor[sizeof(cpu->hyperv_vendor_id)] = 0;
1303 
1304         cpu->hyperv_interface_id[0] =
1305             hv_cpuid_get_host(cs, HV_CPUID_INTERFACE, R_EAX);
1306         cpu->hyperv_interface_id[1] =
1307             hv_cpuid_get_host(cs, HV_CPUID_INTERFACE, R_EBX);
1308         cpu->hyperv_interface_id[2] =
1309             hv_cpuid_get_host(cs, HV_CPUID_INTERFACE, R_ECX);
1310         cpu->hyperv_interface_id[3] =
1311             hv_cpuid_get_host(cs, HV_CPUID_INTERFACE, R_EDX);
1312 
1313         cpu->hyperv_ver_id_build =
1314             hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EAX);
1315         cpu->hyperv_ver_id_major =
1316             hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EBX) >> 16;
1317         cpu->hyperv_ver_id_minor =
1318             hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EBX) & 0xffff;
1319         cpu->hyperv_ver_id_sp =
1320             hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_ECX);
1321         cpu->hyperv_ver_id_sb =
1322             hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EDX) >> 24;
1323         cpu->hyperv_ver_id_sn =
1324             hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EDX) & 0xffffff;
1325 
1326         cpu->hv_max_vps = hv_cpuid_get_host(cs, HV_CPUID_IMPLEMENT_LIMITS,
1327                                             R_EAX);
1328         cpu->hyperv_limits[0] =
1329             hv_cpuid_get_host(cs, HV_CPUID_IMPLEMENT_LIMITS, R_EBX);
1330         cpu->hyperv_limits[1] =
1331             hv_cpuid_get_host(cs, HV_CPUID_IMPLEMENT_LIMITS, R_ECX);
1332         cpu->hyperv_limits[2] =
1333             hv_cpuid_get_host(cs, HV_CPUID_IMPLEMENT_LIMITS, R_EDX);
1334 
1335         cpu->hyperv_spinlock_attempts =
1336             hv_cpuid_get_host(cs, HV_CPUID_ENLIGHTMENT_INFO, R_EBX);
1337 
1338         /*
1339          * Mark feature as enabled in 'cpu->hyperv_features' as
1340          * hv_build_cpuid_leaf() uses this info to build guest CPUIDs.
1341          */
1342         for (feat = 0; feat < ARRAY_SIZE(kvm_hyperv_properties); feat++) {
1343             if (hyperv_feature_supported(cs, feat)) {
1344                 cpu->hyperv_features |= BIT(feat);
1345             }
1346         }
1347     } else {
1348         /* Check features availability and dependencies */
1349         for (feat = 0; feat < ARRAY_SIZE(kvm_hyperv_properties); feat++) {
1350             /* If the feature was not requested skip it. */
1351             if (!hyperv_feat_enabled(cpu, feat)) {
1352                 continue;
1353             }
1354 
1355             /* Check if the feature is supported by KVM */
1356             if (!hyperv_feature_supported(cs, feat)) {
1357                 error_setg(errp, "Hyper-V %s is not supported by kernel",
1358                            kvm_hyperv_properties[feat].desc);
1359                 return false;
1360             }
1361 
1362             /* Check dependencies */
1363             if (!hv_feature_check_deps(cpu, feat, &local_err)) {
1364                 error_propagate(errp, local_err);
1365                 return false;
1366             }
1367         }
1368     }
1369 
1370     /* Additional dependencies not covered by kvm_hyperv_properties[] */
1371     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC) &&
1372         !cpu->hyperv_synic_kvm_only &&
1373         !hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)) {
1374         error_setg(errp, "Hyper-V %s requires Hyper-V %s",
1375                    kvm_hyperv_properties[HYPERV_FEAT_SYNIC].desc,
1376                    kvm_hyperv_properties[HYPERV_FEAT_VPINDEX].desc);
1377         return false;
1378     }
1379 
1380     return true;
1381 }
1382 
1383 /*
1384  * Fill in Hyper-V CPUIDs. Returns the number of entries filled in cpuid_ent.
1385  */
1386 static int hyperv_fill_cpuids(CPUState *cs,
1387                               struct kvm_cpuid_entry2 *cpuid_ent)
1388 {
1389     X86CPU *cpu = X86_CPU(cs);
1390     struct kvm_cpuid_entry2 *c;
1391     uint32_t signature[3];
1392     uint32_t cpuid_i = 0, max_cpuid_leaf = 0;
1393 
1394     max_cpuid_leaf = HV_CPUID_IMPLEMENT_LIMITS;
1395     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS)) {
1396         max_cpuid_leaf = MAX(max_cpuid_leaf, HV_CPUID_NESTED_FEATURES);
1397     }
1398 
1399     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNDBG)) {
1400         max_cpuid_leaf =
1401             MAX(max_cpuid_leaf, HV_CPUID_SYNDBG_PLATFORM_CAPABILITIES);
1402     }
1403 
1404     c = &cpuid_ent[cpuid_i++];
1405     c->function = HV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
1406     c->eax = max_cpuid_leaf;
1407     c->ebx = cpu->hyperv_vendor_id[0];
1408     c->ecx = cpu->hyperv_vendor_id[1];
1409     c->edx = cpu->hyperv_vendor_id[2];
1410 
1411     c = &cpuid_ent[cpuid_i++];
1412     c->function = HV_CPUID_INTERFACE;
1413     c->eax = cpu->hyperv_interface_id[0];
1414     c->ebx = cpu->hyperv_interface_id[1];
1415     c->ecx = cpu->hyperv_interface_id[2];
1416     c->edx = cpu->hyperv_interface_id[3];
1417 
1418     c = &cpuid_ent[cpuid_i++];
1419     c->function = HV_CPUID_VERSION;
1420     c->eax = cpu->hyperv_ver_id_build;
1421     c->ebx = (uint32_t)cpu->hyperv_ver_id_major << 16 |
1422         cpu->hyperv_ver_id_minor;
1423     c->ecx = cpu->hyperv_ver_id_sp;
1424     c->edx = (uint32_t)cpu->hyperv_ver_id_sb << 24 |
1425         (cpu->hyperv_ver_id_sn & 0xffffff);
1426 
1427     c = &cpuid_ent[cpuid_i++];
1428     c->function = HV_CPUID_FEATURES;
1429     c->eax = hv_build_cpuid_leaf(cs, HV_CPUID_FEATURES, R_EAX);
1430     c->ebx = hv_build_cpuid_leaf(cs, HV_CPUID_FEATURES, R_EBX);
1431     c->edx = hv_build_cpuid_leaf(cs, HV_CPUID_FEATURES, R_EDX);
1432 
1433     /* Unconditionally required with any Hyper-V enlightenment */
1434     c->eax |= HV_HYPERCALL_AVAILABLE;
1435 
1436     /* SynIC and Vmbus devices require messages/signals hypercalls */
1437     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC) &&
1438         !cpu->hyperv_synic_kvm_only) {
1439         c->ebx |= HV_POST_MESSAGES | HV_SIGNAL_EVENTS;
1440     }
1441 
1442 
1443     /* Not exposed by KVM but needed to make CPU hotplug in Windows work */
1444     c->edx |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
1445 
1446     c = &cpuid_ent[cpuid_i++];
1447     c->function = HV_CPUID_ENLIGHTMENT_INFO;
1448     c->eax = hv_build_cpuid_leaf(cs, HV_CPUID_ENLIGHTMENT_INFO, R_EAX);
1449     c->ebx = cpu->hyperv_spinlock_attempts;
1450 
1451     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC) &&
1452         !hyperv_feat_enabled(cpu, HYPERV_FEAT_AVIC)) {
1453         c->eax |= HV_APIC_ACCESS_RECOMMENDED;
1454     }
1455 
1456     if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_ON) {
1457         c->eax |= HV_NO_NONARCH_CORESHARING;
1458     } else if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_AUTO) {
1459         c->eax |= hv_cpuid_get_host(cs, HV_CPUID_ENLIGHTMENT_INFO, R_EAX) &
1460             HV_NO_NONARCH_CORESHARING;
1461     }
1462 
1463     c = &cpuid_ent[cpuid_i++];
1464     c->function = HV_CPUID_IMPLEMENT_LIMITS;
1465     c->eax = cpu->hv_max_vps;
1466     c->ebx = cpu->hyperv_limits[0];
1467     c->ecx = cpu->hyperv_limits[1];
1468     c->edx = cpu->hyperv_limits[2];
1469 
1470     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS)) {
1471         uint32_t function;
1472 
1473         /* Create zeroed 0x40000006..0x40000009 leaves */
1474         for (function = HV_CPUID_IMPLEMENT_LIMITS + 1;
1475              function < HV_CPUID_NESTED_FEATURES; function++) {
1476             c = &cpuid_ent[cpuid_i++];
1477             c->function = function;
1478         }
1479 
1480         c = &cpuid_ent[cpuid_i++];
1481         c->function = HV_CPUID_NESTED_FEATURES;
1482         c->eax = cpu->hyperv_nested[0];
1483     }
1484 
1485     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNDBG)) {
1486         c = &cpuid_ent[cpuid_i++];
1487         c->function = HV_CPUID_SYNDBG_VENDOR_AND_MAX_FUNCTIONS;
1488         c->eax = hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS) ?
1489             HV_CPUID_NESTED_FEATURES : HV_CPUID_IMPLEMENT_LIMITS;
1490         memcpy(signature, "Microsoft VS", 12);
1491         c->eax = 0;
1492         c->ebx = signature[0];
1493         c->ecx = signature[1];
1494         c->edx = signature[2];
1495 
1496         c = &cpuid_ent[cpuid_i++];
1497         c->function = HV_CPUID_SYNDBG_INTERFACE;
1498         memcpy(signature, "VS#1\0\0\0\0\0\0\0\0", 12);
1499         c->eax = signature[0];
1500         c->ebx = 0;
1501         c->ecx = 0;
1502         c->edx = 0;
1503 
1504         c = &cpuid_ent[cpuid_i++];
1505         c->function = HV_CPUID_SYNDBG_PLATFORM_CAPABILITIES;
1506         c->eax = HV_SYNDBG_CAP_ALLOW_KERNEL_DEBUGGING;
1507         c->ebx = 0;
1508         c->ecx = 0;
1509         c->edx = 0;
1510     }
1511 
1512     return cpuid_i;
1513 }
1514 
1515 static Error *hv_passthrough_mig_blocker;
1516 static Error *hv_no_nonarch_cs_mig_blocker;
1517 
1518 /* Checks that the exposed eVMCS version range is supported by KVM */
1519 static bool evmcs_version_supported(uint16_t evmcs_version,
1520                                     uint16_t supported_evmcs_version)
1521 {
1522     uint8_t min_version = evmcs_version & 0xff;
1523     uint8_t max_version = evmcs_version >> 8;
1524     uint8_t min_supported_version = supported_evmcs_version & 0xff;
1525     uint8_t max_supported_version = supported_evmcs_version >> 8;
1526 
1527     return (min_version >= min_supported_version) &&
1528         (max_version <= max_supported_version);
1529 }
1530 
1531 #define DEFAULT_EVMCS_VERSION ((1 << 8) | 1)
1532 
1533 static int hyperv_init_vcpu(X86CPU *cpu)
1534 {
1535     CPUState *cs = CPU(cpu);
1536     Error *local_err = NULL;
1537     int ret;
1538 
1539     if (cpu->hyperv_passthrough && hv_passthrough_mig_blocker == NULL) {
1540         error_setg(&hv_passthrough_mig_blocker,
1541                    "'hv-passthrough' CPU flag prevents migration, use explicit"
1542                    " set of hv-* flags instead");
1543         ret = migrate_add_blocker(hv_passthrough_mig_blocker, &local_err);
1544         if (ret < 0) {
1545             error_report_err(local_err);
1546             return ret;
1547         }
1548     }
1549 
1550     if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_AUTO &&
1551         hv_no_nonarch_cs_mig_blocker == NULL) {
1552         error_setg(&hv_no_nonarch_cs_mig_blocker,
1553                    "'hv-no-nonarch-coresharing=auto' CPU flag prevents migration"
1554                    " use explicit 'hv-no-nonarch-coresharing=on' instead (but"
1555                    " make sure SMT is disabled and/or that vCPUs are properly"
1556                    " pinned)");
1557         ret = migrate_add_blocker(hv_no_nonarch_cs_mig_blocker, &local_err);
1558         if (ret < 0) {
1559             error_report_err(local_err);
1560             return ret;
1561         }
1562     }
1563 
1564     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX) && !hv_vpindex_settable) {
1565         /*
1566          * the kernel doesn't support setting vp_index; assert that its value
1567          * is in sync
1568          */
1569         struct {
1570             struct kvm_msrs info;
1571             struct kvm_msr_entry entries[1];
1572         } msr_data = {
1573             .info.nmsrs = 1,
1574             .entries[0].index = HV_X64_MSR_VP_INDEX,
1575         };
1576 
1577         ret = kvm_vcpu_ioctl(cs, KVM_GET_MSRS, &msr_data);
1578         if (ret < 0) {
1579             return ret;
1580         }
1581         assert(ret == 1);
1582 
1583         if (msr_data.entries[0].data != hyperv_vp_index(CPU(cpu))) {
1584             error_report("kernel's vp_index != QEMU's vp_index");
1585             return -ENXIO;
1586         }
1587     }
1588 
1589     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
1590         uint32_t synic_cap = cpu->hyperv_synic_kvm_only ?
1591             KVM_CAP_HYPERV_SYNIC : KVM_CAP_HYPERV_SYNIC2;
1592         ret = kvm_vcpu_enable_cap(cs, synic_cap, 0);
1593         if (ret < 0) {
1594             error_report("failed to turn on HyperV SynIC in KVM: %s",
1595                          strerror(-ret));
1596             return ret;
1597         }
1598 
1599         if (!cpu->hyperv_synic_kvm_only) {
1600             ret = hyperv_x86_synic_add(cpu);
1601             if (ret < 0) {
1602                 error_report("failed to create HyperV SynIC: %s",
1603                              strerror(-ret));
1604                 return ret;
1605             }
1606         }
1607     }
1608 
1609     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS)) {
1610         uint16_t evmcs_version = DEFAULT_EVMCS_VERSION;
1611         uint16_t supported_evmcs_version;
1612 
1613         ret = kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_ENLIGHTENED_VMCS, 0,
1614                                   (uintptr_t)&supported_evmcs_version);
1615 
1616         /*
1617          * KVM is required to support EVMCS ver.1. as that's what 'hv-evmcs'
1618          * option sets. Note: we hardcode the maximum supported eVMCS version
1619          * to '1' as well so 'hv-evmcs' feature is migratable even when (and if)
1620          * ver.2 is implemented. A new option (e.g. 'hv-evmcs=2') will then have
1621          * to be added.
1622          */
1623         if (ret < 0) {
1624             error_report("Hyper-V %s is not supported by kernel",
1625                          kvm_hyperv_properties[HYPERV_FEAT_EVMCS].desc);
1626             return ret;
1627         }
1628 
1629         if (!evmcs_version_supported(evmcs_version, supported_evmcs_version)) {
1630             error_report("eVMCS version range [%d..%d] is not supported by "
1631                          "kernel (supported: [%d..%d])", evmcs_version & 0xff,
1632                          evmcs_version >> 8, supported_evmcs_version & 0xff,
1633                          supported_evmcs_version >> 8);
1634             return -ENOTSUP;
1635         }
1636 
1637         cpu->hyperv_nested[0] = evmcs_version;
1638     }
1639 
1640     if (cpu->hyperv_enforce_cpuid) {
1641         ret = kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_ENFORCE_CPUID, 0, 1);
1642         if (ret < 0) {
1643             error_report("failed to enable KVM_CAP_HYPERV_ENFORCE_CPUID: %s",
1644                          strerror(-ret));
1645             return ret;
1646         }
1647     }
1648 
1649     return 0;
1650 }
1651 
1652 static Error *invtsc_mig_blocker;
1653 
1654 #define KVM_MAX_CPUID_ENTRIES  100
1655 
1656 static void kvm_init_xsave(CPUX86State *env)
1657 {
1658     if (has_xsave2) {
1659         env->xsave_buf_len = QEMU_ALIGN_UP(has_xsave2, 4096);
1660     } else if (has_xsave) {
1661         env->xsave_buf_len = sizeof(struct kvm_xsave);
1662     } else {
1663         return;
1664     }
1665 
1666     env->xsave_buf = qemu_memalign(4096, env->xsave_buf_len);
1667     memset(env->xsave_buf, 0, env->xsave_buf_len);
1668     /*
1669      * The allocated storage must be large enough for all of the
1670      * possible XSAVE state components.
1671      */
1672     assert(kvm_arch_get_supported_cpuid(kvm_state, 0xd, 0, R_ECX) <=
1673            env->xsave_buf_len);
1674 }
1675 
1676 int kvm_arch_init_vcpu(CPUState *cs)
1677 {
1678     struct {
1679         struct kvm_cpuid2 cpuid;
1680         struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
1681     } cpuid_data;
1682     /*
1683      * The kernel defines these structs with padding fields so there
1684      * should be no extra padding in our cpuid_data struct.
1685      */
1686     QEMU_BUILD_BUG_ON(sizeof(cpuid_data) !=
1687                       sizeof(struct kvm_cpuid2) +
1688                       sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES);
1689 
1690     X86CPU *cpu = X86_CPU(cs);
1691     CPUX86State *env = &cpu->env;
1692     uint32_t limit, i, j, cpuid_i;
1693     uint32_t unused;
1694     struct kvm_cpuid_entry2 *c;
1695     uint32_t signature[3];
1696     int kvm_base = KVM_CPUID_SIGNATURE;
1697     int max_nested_state_len;
1698     int r;
1699     Error *local_err = NULL;
1700 
1701     memset(&cpuid_data, 0, sizeof(cpuid_data));
1702 
1703     cpuid_i = 0;
1704 
1705     has_xsave2 = kvm_check_extension(cs->kvm_state, KVM_CAP_XSAVE2);
1706 
1707     r = kvm_arch_set_tsc_khz(cs);
1708     if (r < 0) {
1709         return r;
1710     }
1711 
1712     /* vcpu's TSC frequency is either specified by user, or following
1713      * the value used by KVM if the former is not present. In the
1714      * latter case, we query it from KVM and record in env->tsc_khz,
1715      * so that vcpu's TSC frequency can be migrated later via this field.
1716      */
1717     if (!env->tsc_khz) {
1718         r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
1719             kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
1720             -ENOTSUP;
1721         if (r > 0) {
1722             env->tsc_khz = r;
1723         }
1724     }
1725 
1726     env->apic_bus_freq = KVM_APIC_BUS_FREQUENCY;
1727 
1728     /*
1729      * kvm_hyperv_expand_features() is called here for the second time in case
1730      * KVM_CAP_SYS_HYPERV_CPUID is not supported. While we can't possibly handle
1731      * 'query-cpu-model-expansion' in this case as we don't have a KVM vCPU to
1732      * check which Hyper-V enlightenments are supported and which are not, we
1733      * can still proceed and check/expand Hyper-V enlightenments here so legacy
1734      * behavior is preserved.
1735      */
1736     if (!kvm_hyperv_expand_features(cpu, &local_err)) {
1737         error_report_err(local_err);
1738         return -ENOSYS;
1739     }
1740 
1741     if (hyperv_enabled(cpu)) {
1742         r = hyperv_init_vcpu(cpu);
1743         if (r) {
1744             return r;
1745         }
1746 
1747         cpuid_i = hyperv_fill_cpuids(cs, cpuid_data.entries);
1748         kvm_base = KVM_CPUID_SIGNATURE_NEXT;
1749         has_msr_hv_hypercall = true;
1750     }
1751 
1752     if (cpu->expose_kvm) {
1753         memcpy(signature, "KVMKVMKVM\0\0\0", 12);
1754         c = &cpuid_data.entries[cpuid_i++];
1755         c->function = KVM_CPUID_SIGNATURE | kvm_base;
1756         c->eax = KVM_CPUID_FEATURES | kvm_base;
1757         c->ebx = signature[0];
1758         c->ecx = signature[1];
1759         c->edx = signature[2];
1760 
1761         c = &cpuid_data.entries[cpuid_i++];
1762         c->function = KVM_CPUID_FEATURES | kvm_base;
1763         c->eax = env->features[FEAT_KVM];
1764         c->edx = env->features[FEAT_KVM_HINTS];
1765     }
1766 
1767     cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
1768 
1769     if (cpu->kvm_pv_enforce_cpuid) {
1770         r = kvm_vcpu_enable_cap(cs, KVM_CAP_ENFORCE_PV_FEATURE_CPUID, 0, 1);
1771         if (r < 0) {
1772             fprintf(stderr,
1773                     "failed to enable KVM_CAP_ENFORCE_PV_FEATURE_CPUID: %s",
1774                     strerror(-r));
1775             abort();
1776         }
1777     }
1778 
1779     for (i = 0; i <= limit; i++) {
1780         if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1781             fprintf(stderr, "unsupported level value: 0x%x\n", limit);
1782             abort();
1783         }
1784         c = &cpuid_data.entries[cpuid_i++];
1785 
1786         switch (i) {
1787         case 2: {
1788             /* Keep reading function 2 till all the input is received */
1789             int times;
1790 
1791             c->function = i;
1792             c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
1793                        KVM_CPUID_FLAG_STATE_READ_NEXT;
1794             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1795             times = c->eax & 0xff;
1796 
1797             for (j = 1; j < times; ++j) {
1798                 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1799                     fprintf(stderr, "cpuid_data is full, no space for "
1800                             "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
1801                     abort();
1802                 }
1803                 c = &cpuid_data.entries[cpuid_i++];
1804                 c->function = i;
1805                 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
1806                 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1807             }
1808             break;
1809         }
1810         case 0x1f:
1811             if (env->nr_dies < 2) {
1812                 break;
1813             }
1814             /* fallthrough */
1815         case 4:
1816         case 0xb:
1817         case 0xd:
1818             for (j = 0; ; j++) {
1819                 if (i == 0xd && j == 64) {
1820                     break;
1821                 }
1822 
1823                 if (i == 0x1f && j == 64) {
1824                     break;
1825                 }
1826 
1827                 c->function = i;
1828                 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1829                 c->index = j;
1830                 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1831 
1832                 if (i == 4 && c->eax == 0) {
1833                     break;
1834                 }
1835                 if (i == 0xb && !(c->ecx & 0xff00)) {
1836                     break;
1837                 }
1838                 if (i == 0x1f && !(c->ecx & 0xff00)) {
1839                     break;
1840                 }
1841                 if (i == 0xd && c->eax == 0) {
1842                     continue;
1843                 }
1844                 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1845                     fprintf(stderr, "cpuid_data is full, no space for "
1846                             "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1847                     abort();
1848                 }
1849                 c = &cpuid_data.entries[cpuid_i++];
1850             }
1851             break;
1852         case 0x7:
1853         case 0x12:
1854             for (j = 0; ; j++) {
1855                 c->function = i;
1856                 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1857                 c->index = j;
1858                 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1859 
1860                 if (j > 1 && (c->eax & 0xf) != 1) {
1861                     break;
1862                 }
1863 
1864                 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1865                     fprintf(stderr, "cpuid_data is full, no space for "
1866                                 "cpuid(eax:0x12,ecx:0x%x)\n", j);
1867                     abort();
1868                 }
1869                 c = &cpuid_data.entries[cpuid_i++];
1870             }
1871             break;
1872         case 0x14:
1873         case 0x1d:
1874         case 0x1e: {
1875             uint32_t times;
1876 
1877             c->function = i;
1878             c->index = 0;
1879             c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1880             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1881             times = c->eax;
1882 
1883             for (j = 1; j <= times; ++j) {
1884                 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1885                     fprintf(stderr, "cpuid_data is full, no space for "
1886                                 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1887                     abort();
1888                 }
1889                 c = &cpuid_data.entries[cpuid_i++];
1890                 c->function = i;
1891                 c->index = j;
1892                 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1893                 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1894             }
1895             break;
1896         }
1897         default:
1898             c->function = i;
1899             c->flags = 0;
1900             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1901             if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
1902                 /*
1903                  * KVM already returns all zeroes if a CPUID entry is missing,
1904                  * so we can omit it and avoid hitting KVM's 80-entry limit.
1905                  */
1906                 cpuid_i--;
1907             }
1908             break;
1909         }
1910     }
1911 
1912     if (limit >= 0x0a) {
1913         uint32_t eax, edx;
1914 
1915         cpu_x86_cpuid(env, 0x0a, 0, &eax, &unused, &unused, &edx);
1916 
1917         has_architectural_pmu_version = eax & 0xff;
1918         if (has_architectural_pmu_version > 0) {
1919             num_architectural_pmu_gp_counters = (eax & 0xff00) >> 8;
1920 
1921             /* Shouldn't be more than 32, since that's the number of bits
1922              * available in EBX to tell us _which_ counters are available.
1923              * Play it safe.
1924              */
1925             if (num_architectural_pmu_gp_counters > MAX_GP_COUNTERS) {
1926                 num_architectural_pmu_gp_counters = MAX_GP_COUNTERS;
1927             }
1928 
1929             if (has_architectural_pmu_version > 1) {
1930                 num_architectural_pmu_fixed_counters = edx & 0x1f;
1931 
1932                 if (num_architectural_pmu_fixed_counters > MAX_FIXED_COUNTERS) {
1933                     num_architectural_pmu_fixed_counters = MAX_FIXED_COUNTERS;
1934                 }
1935             }
1936         }
1937     }
1938 
1939     cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
1940 
1941     for (i = 0x80000000; i <= limit; i++) {
1942         if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1943             fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
1944             abort();
1945         }
1946         c = &cpuid_data.entries[cpuid_i++];
1947 
1948         switch (i) {
1949         case 0x8000001d:
1950             /* Query for all AMD cache information leaves */
1951             for (j = 0; ; j++) {
1952                 c->function = i;
1953                 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1954                 c->index = j;
1955                 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1956 
1957                 if (c->eax == 0) {
1958                     break;
1959                 }
1960                 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1961                     fprintf(stderr, "cpuid_data is full, no space for "
1962                             "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1963                     abort();
1964                 }
1965                 c = &cpuid_data.entries[cpuid_i++];
1966             }
1967             break;
1968         default:
1969             c->function = i;
1970             c->flags = 0;
1971             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1972             if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
1973                 /*
1974                  * KVM already returns all zeroes if a CPUID entry is missing,
1975                  * so we can omit it and avoid hitting KVM's 80-entry limit.
1976                  */
1977                 cpuid_i--;
1978             }
1979             break;
1980         }
1981     }
1982 
1983     /* Call Centaur's CPUID instructions they are supported. */
1984     if (env->cpuid_xlevel2 > 0) {
1985         cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
1986 
1987         for (i = 0xC0000000; i <= limit; i++) {
1988             if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1989                 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
1990                 abort();
1991             }
1992             c = &cpuid_data.entries[cpuid_i++];
1993 
1994             c->function = i;
1995             c->flags = 0;
1996             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1997         }
1998     }
1999 
2000     cpuid_data.cpuid.nent = cpuid_i;
2001 
2002     if (((env->cpuid_version >> 8)&0xF) >= 6
2003         && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
2004            (CPUID_MCE | CPUID_MCA)
2005         && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
2006         uint64_t mcg_cap, unsupported_caps;
2007         int banks;
2008         int ret;
2009 
2010         ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
2011         if (ret < 0) {
2012             fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
2013             return ret;
2014         }
2015 
2016         if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
2017             error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
2018                          (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
2019             return -ENOTSUP;
2020         }
2021 
2022         unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
2023         if (unsupported_caps) {
2024             if (unsupported_caps & MCG_LMCE_P) {
2025                 error_report("kvm: LMCE not supported");
2026                 return -ENOTSUP;
2027             }
2028             warn_report("Unsupported MCG_CAP bits: 0x%" PRIx64,
2029                         unsupported_caps);
2030         }
2031 
2032         env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
2033         ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
2034         if (ret < 0) {
2035             fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
2036             return ret;
2037         }
2038     }
2039 
2040     cpu->vmsentry = qemu_add_vm_change_state_handler(cpu_update_state, env);
2041 
2042     c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
2043     if (c) {
2044         has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
2045                                   !!(c->ecx & CPUID_EXT_SMX);
2046     }
2047 
2048     c = cpuid_find_entry(&cpuid_data.cpuid, 7, 0);
2049     if (c && (c->ebx & CPUID_7_0_EBX_SGX)) {
2050         has_msr_feature_control = true;
2051     }
2052 
2053     if (env->mcg_cap & MCG_LMCE_P) {
2054         has_msr_mcg_ext_ctl = has_msr_feature_control = true;
2055     }
2056 
2057     if (!env->user_tsc_khz) {
2058         if ((env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC) &&
2059             invtsc_mig_blocker == NULL) {
2060             error_setg(&invtsc_mig_blocker,
2061                        "State blocked by non-migratable CPU device"
2062                        " (invtsc flag)");
2063             r = migrate_add_blocker(invtsc_mig_blocker, &local_err);
2064             if (r < 0) {
2065                 error_report_err(local_err);
2066                 return r;
2067             }
2068         }
2069     }
2070 
2071     if (cpu->vmware_cpuid_freq
2072         /* Guests depend on 0x40000000 to detect this feature, so only expose
2073          * it if KVM exposes leaf 0x40000000. (Conflicts with Hyper-V) */
2074         && cpu->expose_kvm
2075         && kvm_base == KVM_CPUID_SIGNATURE
2076         /* TSC clock must be stable and known for this feature. */
2077         && tsc_is_stable_and_known(env)) {
2078 
2079         c = &cpuid_data.entries[cpuid_i++];
2080         c->function = KVM_CPUID_SIGNATURE | 0x10;
2081         c->eax = env->tsc_khz;
2082         c->ebx = env->apic_bus_freq / 1000; /* Hz to KHz */
2083         c->ecx = c->edx = 0;
2084 
2085         c = cpuid_find_entry(&cpuid_data.cpuid, kvm_base, 0);
2086         c->eax = MAX(c->eax, KVM_CPUID_SIGNATURE | 0x10);
2087     }
2088 
2089     cpuid_data.cpuid.nent = cpuid_i;
2090 
2091     cpuid_data.cpuid.padding = 0;
2092     r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
2093     if (r) {
2094         goto fail;
2095     }
2096     kvm_init_xsave(env);
2097 
2098     max_nested_state_len = kvm_max_nested_state_length();
2099     if (max_nested_state_len > 0) {
2100         assert(max_nested_state_len >= offsetof(struct kvm_nested_state, data));
2101 
2102         if (cpu_has_vmx(env) || cpu_has_svm(env)) {
2103             struct kvm_vmx_nested_state_hdr *vmx_hdr;
2104 
2105             env->nested_state = g_malloc0(max_nested_state_len);
2106             env->nested_state->size = max_nested_state_len;
2107 
2108             if (cpu_has_vmx(env)) {
2109                 env->nested_state->format = KVM_STATE_NESTED_FORMAT_VMX;
2110                 vmx_hdr = &env->nested_state->hdr.vmx;
2111                 vmx_hdr->vmxon_pa = -1ull;
2112                 vmx_hdr->vmcs12_pa = -1ull;
2113             } else {
2114                 env->nested_state->format = KVM_STATE_NESTED_FORMAT_SVM;
2115             }
2116         }
2117     }
2118 
2119     cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
2120 
2121     if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
2122         has_msr_tsc_aux = false;
2123     }
2124 
2125     kvm_init_msrs(cpu);
2126 
2127     return 0;
2128 
2129  fail:
2130     migrate_del_blocker(invtsc_mig_blocker);
2131 
2132     return r;
2133 }
2134 
2135 int kvm_arch_destroy_vcpu(CPUState *cs)
2136 {
2137     X86CPU *cpu = X86_CPU(cs);
2138     CPUX86State *env = &cpu->env;
2139 
2140     g_free(env->xsave_buf);
2141 
2142     if (cpu->kvm_msr_buf) {
2143         g_free(cpu->kvm_msr_buf);
2144         cpu->kvm_msr_buf = NULL;
2145     }
2146 
2147     if (env->nested_state) {
2148         g_free(env->nested_state);
2149         env->nested_state = NULL;
2150     }
2151 
2152     qemu_del_vm_change_state_handler(cpu->vmsentry);
2153 
2154     return 0;
2155 }
2156 
2157 void kvm_arch_reset_vcpu(X86CPU *cpu)
2158 {
2159     CPUX86State *env = &cpu->env;
2160 
2161     env->xcr0 = 1;
2162     if (kvm_irqchip_in_kernel()) {
2163         env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
2164                                           KVM_MP_STATE_UNINITIALIZED;
2165     } else {
2166         env->mp_state = KVM_MP_STATE_RUNNABLE;
2167     }
2168 
2169     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
2170         int i;
2171         for (i = 0; i < ARRAY_SIZE(env->msr_hv_synic_sint); i++) {
2172             env->msr_hv_synic_sint[i] = HV_SINT_MASKED;
2173         }
2174 
2175         hyperv_x86_synic_reset(cpu);
2176     }
2177     /* enabled by default */
2178     env->poll_control_msr = 1;
2179 
2180     sev_es_set_reset_vector(CPU(cpu));
2181 }
2182 
2183 void kvm_arch_do_init_vcpu(X86CPU *cpu)
2184 {
2185     CPUX86State *env = &cpu->env;
2186 
2187     /* APs get directly into wait-for-SIPI state.  */
2188     if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
2189         env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
2190     }
2191 }
2192 
2193 static int kvm_get_supported_feature_msrs(KVMState *s)
2194 {
2195     int ret = 0;
2196 
2197     if (kvm_feature_msrs != NULL) {
2198         return 0;
2199     }
2200 
2201     if (!kvm_check_extension(s, KVM_CAP_GET_MSR_FEATURES)) {
2202         return 0;
2203     }
2204 
2205     struct kvm_msr_list msr_list;
2206 
2207     msr_list.nmsrs = 0;
2208     ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, &msr_list);
2209     if (ret < 0 && ret != -E2BIG) {
2210         error_report("Fetch KVM feature MSR list failed: %s",
2211             strerror(-ret));
2212         return ret;
2213     }
2214 
2215     assert(msr_list.nmsrs > 0);
2216     kvm_feature_msrs = (struct kvm_msr_list *) \
2217         g_malloc0(sizeof(msr_list) +
2218                  msr_list.nmsrs * sizeof(msr_list.indices[0]));
2219 
2220     kvm_feature_msrs->nmsrs = msr_list.nmsrs;
2221     ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, kvm_feature_msrs);
2222 
2223     if (ret < 0) {
2224         error_report("Fetch KVM feature MSR list failed: %s",
2225             strerror(-ret));
2226         g_free(kvm_feature_msrs);
2227         kvm_feature_msrs = NULL;
2228         return ret;
2229     }
2230 
2231     return 0;
2232 }
2233 
2234 static int kvm_get_supported_msrs(KVMState *s)
2235 {
2236     int ret = 0;
2237     struct kvm_msr_list msr_list, *kvm_msr_list;
2238 
2239     /*
2240      *  Obtain MSR list from KVM.  These are the MSRs that we must
2241      *  save/restore.
2242      */
2243     msr_list.nmsrs = 0;
2244     ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
2245     if (ret < 0 && ret != -E2BIG) {
2246         return ret;
2247     }
2248     /*
2249      * Old kernel modules had a bug and could write beyond the provided
2250      * memory. Allocate at least a safe amount of 1K.
2251      */
2252     kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
2253                                           msr_list.nmsrs *
2254                                           sizeof(msr_list.indices[0])));
2255 
2256     kvm_msr_list->nmsrs = msr_list.nmsrs;
2257     ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
2258     if (ret >= 0) {
2259         int i;
2260 
2261         for (i = 0; i < kvm_msr_list->nmsrs; i++) {
2262             switch (kvm_msr_list->indices[i]) {
2263             case MSR_STAR:
2264                 has_msr_star = true;
2265                 break;
2266             case MSR_VM_HSAVE_PA:
2267                 has_msr_hsave_pa = true;
2268                 break;
2269             case MSR_TSC_AUX:
2270                 has_msr_tsc_aux = true;
2271                 break;
2272             case MSR_TSC_ADJUST:
2273                 has_msr_tsc_adjust = true;
2274                 break;
2275             case MSR_IA32_TSCDEADLINE:
2276                 has_msr_tsc_deadline = true;
2277                 break;
2278             case MSR_IA32_SMBASE:
2279                 has_msr_smbase = true;
2280                 break;
2281             case MSR_SMI_COUNT:
2282                 has_msr_smi_count = true;
2283                 break;
2284             case MSR_IA32_MISC_ENABLE:
2285                 has_msr_misc_enable = true;
2286                 break;
2287             case MSR_IA32_BNDCFGS:
2288                 has_msr_bndcfgs = true;
2289                 break;
2290             case MSR_IA32_XSS:
2291                 has_msr_xss = true;
2292                 break;
2293             case MSR_IA32_UMWAIT_CONTROL:
2294                 has_msr_umwait = true;
2295                 break;
2296             case HV_X64_MSR_CRASH_CTL:
2297                 has_msr_hv_crash = true;
2298                 break;
2299             case HV_X64_MSR_RESET:
2300                 has_msr_hv_reset = true;
2301                 break;
2302             case HV_X64_MSR_VP_INDEX:
2303                 has_msr_hv_vpindex = true;
2304                 break;
2305             case HV_X64_MSR_VP_RUNTIME:
2306                 has_msr_hv_runtime = true;
2307                 break;
2308             case HV_X64_MSR_SCONTROL:
2309                 has_msr_hv_synic = true;
2310                 break;
2311             case HV_X64_MSR_STIMER0_CONFIG:
2312                 has_msr_hv_stimer = true;
2313                 break;
2314             case HV_X64_MSR_TSC_FREQUENCY:
2315                 has_msr_hv_frequencies = true;
2316                 break;
2317             case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2318                 has_msr_hv_reenlightenment = true;
2319                 break;
2320             case HV_X64_MSR_SYNDBG_OPTIONS:
2321                 has_msr_hv_syndbg_options = true;
2322                 break;
2323             case MSR_IA32_SPEC_CTRL:
2324                 has_msr_spec_ctrl = true;
2325                 break;
2326             case MSR_AMD64_TSC_RATIO:
2327                 has_tsc_scale_msr = true;
2328                 break;
2329             case MSR_IA32_TSX_CTRL:
2330                 has_msr_tsx_ctrl = true;
2331                 break;
2332             case MSR_VIRT_SSBD:
2333                 has_msr_virt_ssbd = true;
2334                 break;
2335             case MSR_IA32_ARCH_CAPABILITIES:
2336                 has_msr_arch_capabs = true;
2337                 break;
2338             case MSR_IA32_CORE_CAPABILITY:
2339                 has_msr_core_capabs = true;
2340                 break;
2341             case MSR_IA32_PERF_CAPABILITIES:
2342                 has_msr_perf_capabs = true;
2343                 break;
2344             case MSR_IA32_VMX_VMFUNC:
2345                 has_msr_vmx_vmfunc = true;
2346                 break;
2347             case MSR_IA32_UCODE_REV:
2348                 has_msr_ucode_rev = true;
2349                 break;
2350             case MSR_IA32_VMX_PROCBASED_CTLS2:
2351                 has_msr_vmx_procbased_ctls2 = true;
2352                 break;
2353             case MSR_IA32_PKRS:
2354                 has_msr_pkrs = true;
2355                 break;
2356             }
2357         }
2358     }
2359 
2360     g_free(kvm_msr_list);
2361 
2362     return ret;
2363 }
2364 
2365 static Notifier smram_machine_done;
2366 static KVMMemoryListener smram_listener;
2367 static AddressSpace smram_address_space;
2368 static MemoryRegion smram_as_root;
2369 static MemoryRegion smram_as_mem;
2370 
2371 static void register_smram_listener(Notifier *n, void *unused)
2372 {
2373     MemoryRegion *smram =
2374         (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
2375 
2376     /* Outer container... */
2377     memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
2378     memory_region_set_enabled(&smram_as_root, true);
2379 
2380     /* ... with two regions inside: normal system memory with low
2381      * priority, and...
2382      */
2383     memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
2384                              get_system_memory(), 0, ~0ull);
2385     memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
2386     memory_region_set_enabled(&smram_as_mem, true);
2387 
2388     if (smram) {
2389         /* ... SMRAM with higher priority */
2390         memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
2391         memory_region_set_enabled(smram, true);
2392     }
2393 
2394     address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
2395     kvm_memory_listener_register(kvm_state, &smram_listener,
2396                                  &smram_address_space, 1, "kvm-smram");
2397 }
2398 
2399 int kvm_arch_init(MachineState *ms, KVMState *s)
2400 {
2401     uint64_t identity_base = 0xfffbc000;
2402     uint64_t shadow_mem;
2403     int ret;
2404     struct utsname utsname;
2405     Error *local_err = NULL;
2406 
2407     /*
2408      * Initialize SEV context, if required
2409      *
2410      * If no memory encryption is requested (ms->cgs == NULL) this is
2411      * a no-op.
2412      *
2413      * It's also a no-op if a non-SEV confidential guest support
2414      * mechanism is selected.  SEV is the only mechanism available to
2415      * select on x86 at present, so this doesn't arise, but if new
2416      * mechanisms are supported in future (e.g. TDX), they'll need
2417      * their own initialization either here or elsewhere.
2418      */
2419     ret = sev_kvm_init(ms->cgs, &local_err);
2420     if (ret < 0) {
2421         error_report_err(local_err);
2422         return ret;
2423     }
2424 
2425     if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
2426         error_report("kvm: KVM_CAP_IRQ_ROUTING not supported by KVM");
2427         return -ENOTSUP;
2428     }
2429 
2430     has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
2431     has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
2432     has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
2433     has_sregs2 = kvm_check_extension(s, KVM_CAP_SREGS2) > 0;
2434 
2435     hv_vpindex_settable = kvm_check_extension(s, KVM_CAP_HYPERV_VP_INDEX);
2436 
2437     has_exception_payload = kvm_check_extension(s, KVM_CAP_EXCEPTION_PAYLOAD);
2438     if (has_exception_payload) {
2439         ret = kvm_vm_enable_cap(s, KVM_CAP_EXCEPTION_PAYLOAD, 0, true);
2440         if (ret < 0) {
2441             error_report("kvm: Failed to enable exception payload cap: %s",
2442                          strerror(-ret));
2443             return ret;
2444         }
2445     }
2446 
2447     ret = kvm_get_supported_msrs(s);
2448     if (ret < 0) {
2449         return ret;
2450     }
2451 
2452     kvm_get_supported_feature_msrs(s);
2453 
2454     uname(&utsname);
2455     lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
2456 
2457     /*
2458      * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
2459      * In order to use vm86 mode, an EPT identity map and a TSS  are needed.
2460      * Since these must be part of guest physical memory, we need to allocate
2461      * them, both by setting their start addresses in the kernel and by
2462      * creating a corresponding e820 entry. We need 4 pages before the BIOS.
2463      *
2464      * Older KVM versions may not support setting the identity map base. In
2465      * that case we need to stick with the default, i.e. a 256K maximum BIOS
2466      * size.
2467      */
2468     if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
2469         /* Allows up to 16M BIOSes. */
2470         identity_base = 0xfeffc000;
2471 
2472         ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
2473         if (ret < 0) {
2474             return ret;
2475         }
2476     }
2477 
2478     /* Set TSS base one page after EPT identity map. */
2479     ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
2480     if (ret < 0) {
2481         return ret;
2482     }
2483 
2484     /* Tell fw_cfg to notify the BIOS to reserve the range. */
2485     ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
2486     if (ret < 0) {
2487         fprintf(stderr, "e820_add_entry() table is full\n");
2488         return ret;
2489     }
2490 
2491     shadow_mem = object_property_get_int(OBJECT(s), "kvm-shadow-mem", &error_abort);
2492     if (shadow_mem != -1) {
2493         shadow_mem /= 4096;
2494         ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
2495         if (ret < 0) {
2496             return ret;
2497         }
2498     }
2499 
2500     if (kvm_check_extension(s, KVM_CAP_X86_SMM) &&
2501         object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE) &&
2502         x86_machine_is_smm_enabled(X86_MACHINE(ms))) {
2503         smram_machine_done.notify = register_smram_listener;
2504         qemu_add_machine_init_done_notifier(&smram_machine_done);
2505     }
2506 
2507     if (enable_cpu_pm) {
2508         int disable_exits = kvm_check_extension(s, KVM_CAP_X86_DISABLE_EXITS);
2509         int ret;
2510 
2511 /* Work around for kernel header with a typo. TODO: fix header and drop. */
2512 #if defined(KVM_X86_DISABLE_EXITS_HTL) && !defined(KVM_X86_DISABLE_EXITS_HLT)
2513 #define KVM_X86_DISABLE_EXITS_HLT KVM_X86_DISABLE_EXITS_HTL
2514 #endif
2515         if (disable_exits) {
2516             disable_exits &= (KVM_X86_DISABLE_EXITS_MWAIT |
2517                               KVM_X86_DISABLE_EXITS_HLT |
2518                               KVM_X86_DISABLE_EXITS_PAUSE |
2519                               KVM_X86_DISABLE_EXITS_CSTATE);
2520         }
2521 
2522         ret = kvm_vm_enable_cap(s, KVM_CAP_X86_DISABLE_EXITS, 0,
2523                                 disable_exits);
2524         if (ret < 0) {
2525             error_report("kvm: guest stopping CPU not supported: %s",
2526                          strerror(-ret));
2527         }
2528     }
2529 
2530     if (object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE)) {
2531         X86MachineState *x86ms = X86_MACHINE(ms);
2532 
2533         if (x86ms->bus_lock_ratelimit > 0) {
2534             ret = kvm_check_extension(s, KVM_CAP_X86_BUS_LOCK_EXIT);
2535             if (!(ret & KVM_BUS_LOCK_DETECTION_EXIT)) {
2536                 error_report("kvm: bus lock detection unsupported");
2537                 return -ENOTSUP;
2538             }
2539             ret = kvm_vm_enable_cap(s, KVM_CAP_X86_BUS_LOCK_EXIT, 0,
2540                                     KVM_BUS_LOCK_DETECTION_EXIT);
2541             if (ret < 0) {
2542                 error_report("kvm: Failed to enable bus lock detection cap: %s",
2543                              strerror(-ret));
2544                 return ret;
2545             }
2546             ratelimit_init(&bus_lock_ratelimit_ctrl);
2547             ratelimit_set_speed(&bus_lock_ratelimit_ctrl,
2548                                 x86ms->bus_lock_ratelimit, BUS_LOCK_SLICE_TIME);
2549         }
2550     }
2551 
2552     return 0;
2553 }
2554 
2555 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2556 {
2557     lhs->selector = rhs->selector;
2558     lhs->base = rhs->base;
2559     lhs->limit = rhs->limit;
2560     lhs->type = 3;
2561     lhs->present = 1;
2562     lhs->dpl = 3;
2563     lhs->db = 0;
2564     lhs->s = 1;
2565     lhs->l = 0;
2566     lhs->g = 0;
2567     lhs->avl = 0;
2568     lhs->unusable = 0;
2569 }
2570 
2571 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2572 {
2573     unsigned flags = rhs->flags;
2574     lhs->selector = rhs->selector;
2575     lhs->base = rhs->base;
2576     lhs->limit = rhs->limit;
2577     lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
2578     lhs->present = (flags & DESC_P_MASK) != 0;
2579     lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
2580     lhs->db = (flags >> DESC_B_SHIFT) & 1;
2581     lhs->s = (flags & DESC_S_MASK) != 0;
2582     lhs->l = (flags >> DESC_L_SHIFT) & 1;
2583     lhs->g = (flags & DESC_G_MASK) != 0;
2584     lhs->avl = (flags & DESC_AVL_MASK) != 0;
2585     lhs->unusable = !lhs->present;
2586     lhs->padding = 0;
2587 }
2588 
2589 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
2590 {
2591     lhs->selector = rhs->selector;
2592     lhs->base = rhs->base;
2593     lhs->limit = rhs->limit;
2594     lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
2595                  ((rhs->present && !rhs->unusable) * DESC_P_MASK) |
2596                  (rhs->dpl << DESC_DPL_SHIFT) |
2597                  (rhs->db << DESC_B_SHIFT) |
2598                  (rhs->s * DESC_S_MASK) |
2599                  (rhs->l << DESC_L_SHIFT) |
2600                  (rhs->g * DESC_G_MASK) |
2601                  (rhs->avl * DESC_AVL_MASK);
2602 }
2603 
2604 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
2605 {
2606     if (set) {
2607         *kvm_reg = *qemu_reg;
2608     } else {
2609         *qemu_reg = *kvm_reg;
2610     }
2611 }
2612 
2613 static int kvm_getput_regs(X86CPU *cpu, int set)
2614 {
2615     CPUX86State *env = &cpu->env;
2616     struct kvm_regs regs;
2617     int ret = 0;
2618 
2619     if (!set) {
2620         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
2621         if (ret < 0) {
2622             return ret;
2623         }
2624     }
2625 
2626     kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
2627     kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
2628     kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
2629     kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
2630     kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
2631     kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
2632     kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
2633     kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
2634 #ifdef TARGET_X86_64
2635     kvm_getput_reg(&regs.r8, &env->regs[8], set);
2636     kvm_getput_reg(&regs.r9, &env->regs[9], set);
2637     kvm_getput_reg(&regs.r10, &env->regs[10], set);
2638     kvm_getput_reg(&regs.r11, &env->regs[11], set);
2639     kvm_getput_reg(&regs.r12, &env->regs[12], set);
2640     kvm_getput_reg(&regs.r13, &env->regs[13], set);
2641     kvm_getput_reg(&regs.r14, &env->regs[14], set);
2642     kvm_getput_reg(&regs.r15, &env->regs[15], set);
2643 #endif
2644 
2645     kvm_getput_reg(&regs.rflags, &env->eflags, set);
2646     kvm_getput_reg(&regs.rip, &env->eip, set);
2647 
2648     if (set) {
2649         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
2650     }
2651 
2652     return ret;
2653 }
2654 
2655 static int kvm_put_fpu(X86CPU *cpu)
2656 {
2657     CPUX86State *env = &cpu->env;
2658     struct kvm_fpu fpu;
2659     int i;
2660 
2661     memset(&fpu, 0, sizeof fpu);
2662     fpu.fsw = env->fpus & ~(7 << 11);
2663     fpu.fsw |= (env->fpstt & 7) << 11;
2664     fpu.fcw = env->fpuc;
2665     fpu.last_opcode = env->fpop;
2666     fpu.last_ip = env->fpip;
2667     fpu.last_dp = env->fpdp;
2668     for (i = 0; i < 8; ++i) {
2669         fpu.ftwx |= (!env->fptags[i]) << i;
2670     }
2671     memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
2672     for (i = 0; i < CPU_NB_REGS; i++) {
2673         stq_p(&fpu.xmm[i][0], env->xmm_regs[i].ZMM_Q(0));
2674         stq_p(&fpu.xmm[i][8], env->xmm_regs[i].ZMM_Q(1));
2675     }
2676     fpu.mxcsr = env->mxcsr;
2677 
2678     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
2679 }
2680 
2681 static int kvm_put_xsave(X86CPU *cpu)
2682 {
2683     CPUX86State *env = &cpu->env;
2684     void *xsave = env->xsave_buf;
2685 
2686     if (!has_xsave) {
2687         return kvm_put_fpu(cpu);
2688     }
2689     x86_cpu_xsave_all_areas(cpu, xsave, env->xsave_buf_len);
2690 
2691     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
2692 }
2693 
2694 static int kvm_put_xcrs(X86CPU *cpu)
2695 {
2696     CPUX86State *env = &cpu->env;
2697     struct kvm_xcrs xcrs = {};
2698 
2699     if (!has_xcrs) {
2700         return 0;
2701     }
2702 
2703     xcrs.nr_xcrs = 1;
2704     xcrs.flags = 0;
2705     xcrs.xcrs[0].xcr = 0;
2706     xcrs.xcrs[0].value = env->xcr0;
2707     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
2708 }
2709 
2710 static int kvm_put_sregs(X86CPU *cpu)
2711 {
2712     CPUX86State *env = &cpu->env;
2713     struct kvm_sregs sregs;
2714 
2715     /*
2716      * The interrupt_bitmap is ignored because KVM_SET_SREGS is
2717      * always followed by KVM_SET_VCPU_EVENTS.
2718      */
2719     memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
2720 
2721     if ((env->eflags & VM_MASK)) {
2722         set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
2723         set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
2724         set_v8086_seg(&sregs.es, &env->segs[R_ES]);
2725         set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
2726         set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
2727         set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
2728     } else {
2729         set_seg(&sregs.cs, &env->segs[R_CS]);
2730         set_seg(&sregs.ds, &env->segs[R_DS]);
2731         set_seg(&sregs.es, &env->segs[R_ES]);
2732         set_seg(&sregs.fs, &env->segs[R_FS]);
2733         set_seg(&sregs.gs, &env->segs[R_GS]);
2734         set_seg(&sregs.ss, &env->segs[R_SS]);
2735     }
2736 
2737     set_seg(&sregs.tr, &env->tr);
2738     set_seg(&sregs.ldt, &env->ldt);
2739 
2740     sregs.idt.limit = env->idt.limit;
2741     sregs.idt.base = env->idt.base;
2742     memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
2743     sregs.gdt.limit = env->gdt.limit;
2744     sregs.gdt.base = env->gdt.base;
2745     memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
2746 
2747     sregs.cr0 = env->cr[0];
2748     sregs.cr2 = env->cr[2];
2749     sregs.cr3 = env->cr[3];
2750     sregs.cr4 = env->cr[4];
2751 
2752     sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
2753     sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
2754 
2755     sregs.efer = env->efer;
2756 
2757     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
2758 }
2759 
2760 static int kvm_put_sregs2(X86CPU *cpu)
2761 {
2762     CPUX86State *env = &cpu->env;
2763     struct kvm_sregs2 sregs;
2764     int i;
2765 
2766     sregs.flags = 0;
2767 
2768     if ((env->eflags & VM_MASK)) {
2769         set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
2770         set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
2771         set_v8086_seg(&sregs.es, &env->segs[R_ES]);
2772         set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
2773         set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
2774         set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
2775     } else {
2776         set_seg(&sregs.cs, &env->segs[R_CS]);
2777         set_seg(&sregs.ds, &env->segs[R_DS]);
2778         set_seg(&sregs.es, &env->segs[R_ES]);
2779         set_seg(&sregs.fs, &env->segs[R_FS]);
2780         set_seg(&sregs.gs, &env->segs[R_GS]);
2781         set_seg(&sregs.ss, &env->segs[R_SS]);
2782     }
2783 
2784     set_seg(&sregs.tr, &env->tr);
2785     set_seg(&sregs.ldt, &env->ldt);
2786 
2787     sregs.idt.limit = env->idt.limit;
2788     sregs.idt.base = env->idt.base;
2789     memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
2790     sregs.gdt.limit = env->gdt.limit;
2791     sregs.gdt.base = env->gdt.base;
2792     memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
2793 
2794     sregs.cr0 = env->cr[0];
2795     sregs.cr2 = env->cr[2];
2796     sregs.cr3 = env->cr[3];
2797     sregs.cr4 = env->cr[4];
2798 
2799     sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
2800     sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
2801 
2802     sregs.efer = env->efer;
2803 
2804     if (env->pdptrs_valid) {
2805         for (i = 0; i < 4; i++) {
2806             sregs.pdptrs[i] = env->pdptrs[i];
2807         }
2808         sregs.flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
2809     }
2810 
2811     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS2, &sregs);
2812 }
2813 
2814 
2815 static void kvm_msr_buf_reset(X86CPU *cpu)
2816 {
2817     memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
2818 }
2819 
2820 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
2821 {
2822     struct kvm_msrs *msrs = cpu->kvm_msr_buf;
2823     void *limit = ((void *)msrs) + MSR_BUF_SIZE;
2824     struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
2825 
2826     assert((void *)(entry + 1) <= limit);
2827 
2828     entry->index = index;
2829     entry->reserved = 0;
2830     entry->data = value;
2831     msrs->nmsrs++;
2832 }
2833 
2834 static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
2835 {
2836     kvm_msr_buf_reset(cpu);
2837     kvm_msr_entry_add(cpu, index, value);
2838 
2839     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
2840 }
2841 
2842 void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
2843 {
2844     int ret;
2845 
2846     ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
2847     assert(ret == 1);
2848 }
2849 
2850 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
2851 {
2852     CPUX86State *env = &cpu->env;
2853     int ret;
2854 
2855     if (!has_msr_tsc_deadline) {
2856         return 0;
2857     }
2858 
2859     ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
2860     if (ret < 0) {
2861         return ret;
2862     }
2863 
2864     assert(ret == 1);
2865     return 0;
2866 }
2867 
2868 /*
2869  * Provide a separate write service for the feature control MSR in order to
2870  * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
2871  * before writing any other state because forcibly leaving nested mode
2872  * invalidates the VCPU state.
2873  */
2874 static int kvm_put_msr_feature_control(X86CPU *cpu)
2875 {
2876     int ret;
2877 
2878     if (!has_msr_feature_control) {
2879         return 0;
2880     }
2881 
2882     ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
2883                           cpu->env.msr_ia32_feature_control);
2884     if (ret < 0) {
2885         return ret;
2886     }
2887 
2888     assert(ret == 1);
2889     return 0;
2890 }
2891 
2892 static uint64_t make_vmx_msr_value(uint32_t index, uint32_t features)
2893 {
2894     uint32_t default1, can_be_one, can_be_zero;
2895     uint32_t must_be_one;
2896 
2897     switch (index) {
2898     case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2899         default1 = 0x00000016;
2900         break;
2901     case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2902         default1 = 0x0401e172;
2903         break;
2904     case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
2905         default1 = 0x000011ff;
2906         break;
2907     case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2908         default1 = 0x00036dff;
2909         break;
2910     case MSR_IA32_VMX_PROCBASED_CTLS2:
2911         default1 = 0;
2912         break;
2913     default:
2914         abort();
2915     }
2916 
2917     /* If a feature bit is set, the control can be either set or clear.
2918      * Otherwise the value is limited to either 0 or 1 by default1.
2919      */
2920     can_be_one = features | default1;
2921     can_be_zero = features | ~default1;
2922     must_be_one = ~can_be_zero;
2923 
2924     /*
2925      * Bit 0:31 -> 0 if the control bit can be zero (i.e. 1 if it must be one).
2926      * Bit 32:63 -> 1 if the control bit can be one.
2927      */
2928     return must_be_one | (((uint64_t)can_be_one) << 32);
2929 }
2930 
2931 static void kvm_msr_entry_add_vmx(X86CPU *cpu, FeatureWordArray f)
2932 {
2933     uint64_t kvm_vmx_basic =
2934         kvm_arch_get_supported_msr_feature(kvm_state,
2935                                            MSR_IA32_VMX_BASIC);
2936 
2937     if (!kvm_vmx_basic) {
2938         /* If the kernel doesn't support VMX feature (kvm_intel.nested=0),
2939          * then kvm_vmx_basic will be 0 and KVM_SET_MSR will fail.
2940          */
2941         return;
2942     }
2943 
2944     uint64_t kvm_vmx_misc =
2945         kvm_arch_get_supported_msr_feature(kvm_state,
2946                                            MSR_IA32_VMX_MISC);
2947     uint64_t kvm_vmx_ept_vpid =
2948         kvm_arch_get_supported_msr_feature(kvm_state,
2949                                            MSR_IA32_VMX_EPT_VPID_CAP);
2950 
2951     /*
2952      * If the guest is 64-bit, a value of 1 is allowed for the host address
2953      * space size vmexit control.
2954      */
2955     uint64_t fixed_vmx_exit = f[FEAT_8000_0001_EDX] & CPUID_EXT2_LM
2956         ? (uint64_t)VMX_VM_EXIT_HOST_ADDR_SPACE_SIZE << 32 : 0;
2957 
2958     /*
2959      * Bits 0-30, 32-44 and 50-53 come from the host.  KVM should
2960      * not change them for backwards compatibility.
2961      */
2962     uint64_t fixed_vmx_basic = kvm_vmx_basic &
2963         (MSR_VMX_BASIC_VMCS_REVISION_MASK |
2964          MSR_VMX_BASIC_VMXON_REGION_SIZE_MASK |
2965          MSR_VMX_BASIC_VMCS_MEM_TYPE_MASK);
2966 
2967     /*
2968      * Same for bits 0-4 and 25-27.  Bits 16-24 (CR3 target count) can
2969      * change in the future but are always zero for now, clear them to be
2970      * future proof.  Bits 32-63 in theory could change, though KVM does
2971      * not support dual-monitor treatment and probably never will; mask
2972      * them out as well.
2973      */
2974     uint64_t fixed_vmx_misc = kvm_vmx_misc &
2975         (MSR_VMX_MISC_PREEMPTION_TIMER_SHIFT_MASK |
2976          MSR_VMX_MISC_MAX_MSR_LIST_SIZE_MASK);
2977 
2978     /*
2979      * EPT memory types should not change either, so we do not bother
2980      * adding features for them.
2981      */
2982     uint64_t fixed_vmx_ept_mask =
2983             (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_ENABLE_EPT ?
2984              MSR_VMX_EPT_UC | MSR_VMX_EPT_WB : 0);
2985     uint64_t fixed_vmx_ept_vpid = kvm_vmx_ept_vpid & fixed_vmx_ept_mask;
2986 
2987     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
2988                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
2989                                          f[FEAT_VMX_PROCBASED_CTLS]));
2990     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PINBASED_CTLS,
2991                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_PINBASED_CTLS,
2992                                          f[FEAT_VMX_PINBASED_CTLS]));
2993     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_EXIT_CTLS,
2994                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_EXIT_CTLS,
2995                                          f[FEAT_VMX_EXIT_CTLS]) | fixed_vmx_exit);
2996     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_ENTRY_CTLS,
2997                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_ENTRY_CTLS,
2998                                          f[FEAT_VMX_ENTRY_CTLS]));
2999     kvm_msr_entry_add(cpu, MSR_IA32_VMX_PROCBASED_CTLS2,
3000                       make_vmx_msr_value(MSR_IA32_VMX_PROCBASED_CTLS2,
3001                                          f[FEAT_VMX_SECONDARY_CTLS]));
3002     kvm_msr_entry_add(cpu, MSR_IA32_VMX_EPT_VPID_CAP,
3003                       f[FEAT_VMX_EPT_VPID_CAPS] | fixed_vmx_ept_vpid);
3004     kvm_msr_entry_add(cpu, MSR_IA32_VMX_BASIC,
3005                       f[FEAT_VMX_BASIC] | fixed_vmx_basic);
3006     kvm_msr_entry_add(cpu, MSR_IA32_VMX_MISC,
3007                       f[FEAT_VMX_MISC] | fixed_vmx_misc);
3008     if (has_msr_vmx_vmfunc) {
3009         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMFUNC, f[FEAT_VMX_VMFUNC]);
3010     }
3011 
3012     /*
3013      * Just to be safe, write these with constant values.  The CRn_FIXED1
3014      * MSRs are generated by KVM based on the vCPU's CPUID.
3015      */
3016     kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR0_FIXED0,
3017                       CR0_PE_MASK | CR0_PG_MASK | CR0_NE_MASK);
3018     kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR4_FIXED0,
3019                       CR4_VMXE_MASK);
3020 
3021     if (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_TSC_SCALING) {
3022         /* TSC multiplier (0x2032).  */
3023         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x32);
3024     } else {
3025         /* Preemption timer (0x482E).  */
3026         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x2E);
3027     }
3028 }
3029 
3030 static void kvm_msr_entry_add_perf(X86CPU *cpu, FeatureWordArray f)
3031 {
3032     uint64_t kvm_perf_cap =
3033         kvm_arch_get_supported_msr_feature(kvm_state,
3034                                            MSR_IA32_PERF_CAPABILITIES);
3035 
3036     if (kvm_perf_cap) {
3037         kvm_msr_entry_add(cpu, MSR_IA32_PERF_CAPABILITIES,
3038                         kvm_perf_cap & f[FEAT_PERF_CAPABILITIES]);
3039     }
3040 }
3041 
3042 static int kvm_buf_set_msrs(X86CPU *cpu)
3043 {
3044     int ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
3045     if (ret < 0) {
3046         return ret;
3047     }
3048 
3049     if (ret < cpu->kvm_msr_buf->nmsrs) {
3050         struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
3051         error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,
3052                      (uint32_t)e->index, (uint64_t)e->data);
3053     }
3054 
3055     assert(ret == cpu->kvm_msr_buf->nmsrs);
3056     return 0;
3057 }
3058 
3059 static void kvm_init_msrs(X86CPU *cpu)
3060 {
3061     CPUX86State *env = &cpu->env;
3062 
3063     kvm_msr_buf_reset(cpu);
3064     if (has_msr_arch_capabs) {
3065         kvm_msr_entry_add(cpu, MSR_IA32_ARCH_CAPABILITIES,
3066                           env->features[FEAT_ARCH_CAPABILITIES]);
3067     }
3068 
3069     if (has_msr_core_capabs) {
3070         kvm_msr_entry_add(cpu, MSR_IA32_CORE_CAPABILITY,
3071                           env->features[FEAT_CORE_CAPABILITY]);
3072     }
3073 
3074     if (has_msr_perf_capabs && cpu->enable_pmu) {
3075         kvm_msr_entry_add_perf(cpu, env->features);
3076     }
3077 
3078     if (has_msr_ucode_rev) {
3079         kvm_msr_entry_add(cpu, MSR_IA32_UCODE_REV, cpu->ucode_rev);
3080     }
3081 
3082     /*
3083      * Older kernels do not include VMX MSRs in KVM_GET_MSR_INDEX_LIST, but
3084      * all kernels with MSR features should have them.
3085      */
3086     if (kvm_feature_msrs && cpu_has_vmx(env)) {
3087         kvm_msr_entry_add_vmx(cpu, env->features);
3088     }
3089 
3090     assert(kvm_buf_set_msrs(cpu) == 0);
3091 }
3092 
3093 static int kvm_put_msrs(X86CPU *cpu, int level)
3094 {
3095     CPUX86State *env = &cpu->env;
3096     int i;
3097 
3098     kvm_msr_buf_reset(cpu);
3099 
3100     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
3101     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
3102     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
3103     kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
3104     if (has_msr_star) {
3105         kvm_msr_entry_add(cpu, MSR_STAR, env->star);
3106     }
3107     if (has_msr_hsave_pa) {
3108         kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
3109     }
3110     if (has_msr_tsc_aux) {
3111         kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
3112     }
3113     if (has_msr_tsc_adjust) {
3114         kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
3115     }
3116     if (has_msr_misc_enable) {
3117         kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
3118                           env->msr_ia32_misc_enable);
3119     }
3120     if (has_msr_smbase) {
3121         kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
3122     }
3123     if (has_msr_smi_count) {
3124         kvm_msr_entry_add(cpu, MSR_SMI_COUNT, env->msr_smi_count);
3125     }
3126     if (has_msr_pkrs) {
3127         kvm_msr_entry_add(cpu, MSR_IA32_PKRS, env->pkrs);
3128     }
3129     if (has_msr_bndcfgs) {
3130         kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
3131     }
3132     if (has_msr_xss) {
3133         kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
3134     }
3135     if (has_msr_umwait) {
3136         kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, env->umwait);
3137     }
3138     if (has_msr_spec_ctrl) {
3139         kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, env->spec_ctrl);
3140     }
3141     if (has_tsc_scale_msr) {
3142         kvm_msr_entry_add(cpu, MSR_AMD64_TSC_RATIO, env->amd_tsc_scale_msr);
3143     }
3144 
3145     if (has_msr_tsx_ctrl) {
3146         kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, env->tsx_ctrl);
3147     }
3148     if (has_msr_virt_ssbd) {
3149         kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, env->virt_ssbd);
3150     }
3151 
3152 #ifdef TARGET_X86_64
3153     if (lm_capable_kernel) {
3154         kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
3155         kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
3156         kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
3157         kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
3158     }
3159 #endif
3160 
3161     /*
3162      * The following MSRs have side effects on the guest or are too heavy
3163      * for normal writeback. Limit them to reset or full state updates.
3164      */
3165     if (level >= KVM_PUT_RESET_STATE) {
3166         kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
3167         kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
3168         kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
3169         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
3170             kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, env->async_pf_int_msr);
3171         }
3172         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
3173             kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
3174         }
3175         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
3176             kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
3177         }
3178         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
3179             kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
3180         }
3181 
3182         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
3183             kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, env->poll_control_msr);
3184         }
3185 
3186         if (has_architectural_pmu_version > 0) {
3187             if (has_architectural_pmu_version > 1) {
3188                 /* Stop the counter.  */
3189                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
3190                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
3191             }
3192 
3193             /* Set the counter values.  */
3194             for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
3195                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
3196                                   env->msr_fixed_counters[i]);
3197             }
3198             for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
3199                 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
3200                                   env->msr_gp_counters[i]);
3201                 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
3202                                   env->msr_gp_evtsel[i]);
3203             }
3204             if (has_architectural_pmu_version > 1) {
3205                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
3206                                   env->msr_global_status);
3207                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
3208                                   env->msr_global_ovf_ctrl);
3209 
3210                 /* Now start the PMU.  */
3211                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
3212                                   env->msr_fixed_ctr_ctrl);
3213                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
3214                                   env->msr_global_ctrl);
3215             }
3216         }
3217         /*
3218          * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,
3219          * only sync them to KVM on the first cpu
3220          */
3221         if (current_cpu == first_cpu) {
3222             if (has_msr_hv_hypercall) {
3223                 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
3224                                   env->msr_hv_guest_os_id);
3225                 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
3226                                   env->msr_hv_hypercall);
3227             }
3228             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
3229                 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,
3230                                   env->msr_hv_tsc);
3231             }
3232             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
3233                 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL,
3234                                   env->msr_hv_reenlightenment_control);
3235                 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL,
3236                                   env->msr_hv_tsc_emulation_control);
3237                 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS,
3238                                   env->msr_hv_tsc_emulation_status);
3239             }
3240 #ifdef CONFIG_SYNDBG
3241             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNDBG) &&
3242                 has_msr_hv_syndbg_options) {
3243                 kvm_msr_entry_add(cpu, HV_X64_MSR_SYNDBG_OPTIONS,
3244                                   hyperv_syndbg_query_options());
3245             }
3246 #endif
3247         }
3248         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3249             kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
3250                               env->msr_hv_vapic);
3251         }
3252         if (has_msr_hv_crash) {
3253             int j;
3254 
3255             for (j = 0; j < HV_CRASH_PARAMS; j++)
3256                 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
3257                                   env->msr_hv_crash_params[j]);
3258 
3259             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);
3260         }
3261         if (has_msr_hv_runtime) {
3262             kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
3263         }
3264         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)
3265             && hv_vpindex_settable) {
3266             kvm_msr_entry_add(cpu, HV_X64_MSR_VP_INDEX,
3267                               hyperv_vp_index(CPU(cpu)));
3268         }
3269         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3270             int j;
3271 
3272             kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);
3273 
3274             kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
3275                               env->msr_hv_synic_control);
3276             kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
3277                               env->msr_hv_synic_evt_page);
3278             kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
3279                               env->msr_hv_synic_msg_page);
3280 
3281             for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
3282                 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
3283                                   env->msr_hv_synic_sint[j]);
3284             }
3285         }
3286         if (has_msr_hv_stimer) {
3287             int j;
3288 
3289             for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
3290                 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
3291                                 env->msr_hv_stimer_config[j]);
3292             }
3293 
3294             for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
3295                 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
3296                                 env->msr_hv_stimer_count[j]);
3297             }
3298         }
3299         if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3300             uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
3301 
3302             kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
3303             kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
3304             kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
3305             kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
3306             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
3307             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
3308             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
3309             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
3310             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
3311             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
3312             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
3313             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
3314             for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
3315                 /* The CPU GPs if we write to a bit above the physical limit of
3316                  * the host CPU (and KVM emulates that)
3317                  */
3318                 uint64_t mask = env->mtrr_var[i].mask;
3319                 mask &= phys_mask;
3320 
3321                 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
3322                                   env->mtrr_var[i].base);
3323                 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
3324             }
3325         }
3326         if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
3327             int addr_num = kvm_arch_get_supported_cpuid(kvm_state,
3328                                                     0x14, 1, R_EAX) & 0x7;
3329 
3330             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL,
3331                             env->msr_rtit_ctrl);
3332             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS,
3333                             env->msr_rtit_status);
3334             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE,
3335                             env->msr_rtit_output_base);
3336             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK,
3337                             env->msr_rtit_output_mask);
3338             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH,
3339                             env->msr_rtit_cr3_match);
3340             for (i = 0; i < addr_num; i++) {
3341                 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i,
3342                             env->msr_rtit_addrs[i]);
3343             }
3344         }
3345 
3346         if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_SGX_LC) {
3347             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH0,
3348                               env->msr_ia32_sgxlepubkeyhash[0]);
3349             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH1,
3350                               env->msr_ia32_sgxlepubkeyhash[1]);
3351             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH2,
3352                               env->msr_ia32_sgxlepubkeyhash[2]);
3353             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH3,
3354                               env->msr_ia32_sgxlepubkeyhash[3]);
3355         }
3356 
3357         if (env->features[FEAT_XSAVE] & CPUID_D_1_EAX_XFD) {
3358             kvm_msr_entry_add(cpu, MSR_IA32_XFD,
3359                               env->msr_xfd);
3360             kvm_msr_entry_add(cpu, MSR_IA32_XFD_ERR,
3361                               env->msr_xfd_err);
3362         }
3363 
3364         /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
3365          *       kvm_put_msr_feature_control. */
3366     }
3367 
3368     if (env->mcg_cap) {
3369         int i;
3370 
3371         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
3372         kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
3373         if (has_msr_mcg_ext_ctl) {
3374             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
3375         }
3376         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3377             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
3378         }
3379     }
3380 
3381     return kvm_buf_set_msrs(cpu);
3382 }
3383 
3384 
3385 static int kvm_get_fpu(X86CPU *cpu)
3386 {
3387     CPUX86State *env = &cpu->env;
3388     struct kvm_fpu fpu;
3389     int i, ret;
3390 
3391     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
3392     if (ret < 0) {
3393         return ret;
3394     }
3395 
3396     env->fpstt = (fpu.fsw >> 11) & 7;
3397     env->fpus = fpu.fsw;
3398     env->fpuc = fpu.fcw;
3399     env->fpop = fpu.last_opcode;
3400     env->fpip = fpu.last_ip;
3401     env->fpdp = fpu.last_dp;
3402     for (i = 0; i < 8; ++i) {
3403         env->fptags[i] = !((fpu.ftwx >> i) & 1);
3404     }
3405     memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
3406     for (i = 0; i < CPU_NB_REGS; i++) {
3407         env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
3408         env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
3409     }
3410     env->mxcsr = fpu.mxcsr;
3411 
3412     return 0;
3413 }
3414 
3415 static int kvm_get_xsave(X86CPU *cpu)
3416 {
3417     CPUX86State *env = &cpu->env;
3418     void *xsave = env->xsave_buf;
3419     int type, ret;
3420 
3421     if (!has_xsave) {
3422         return kvm_get_fpu(cpu);
3423     }
3424 
3425     type = has_xsave2 ? KVM_GET_XSAVE2 : KVM_GET_XSAVE;
3426     ret = kvm_vcpu_ioctl(CPU(cpu), type, xsave);
3427     if (ret < 0) {
3428         return ret;
3429     }
3430     x86_cpu_xrstor_all_areas(cpu, xsave, env->xsave_buf_len);
3431 
3432     return 0;
3433 }
3434 
3435 static int kvm_get_xcrs(X86CPU *cpu)
3436 {
3437     CPUX86State *env = &cpu->env;
3438     int i, ret;
3439     struct kvm_xcrs xcrs;
3440 
3441     if (!has_xcrs) {
3442         return 0;
3443     }
3444 
3445     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
3446     if (ret < 0) {
3447         return ret;
3448     }
3449 
3450     for (i = 0; i < xcrs.nr_xcrs; i++) {
3451         /* Only support xcr0 now */
3452         if (xcrs.xcrs[i].xcr == 0) {
3453             env->xcr0 = xcrs.xcrs[i].value;
3454             break;
3455         }
3456     }
3457     return 0;
3458 }
3459 
3460 static int kvm_get_sregs(X86CPU *cpu)
3461 {
3462     CPUX86State *env = &cpu->env;
3463     struct kvm_sregs sregs;
3464     int ret;
3465 
3466     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
3467     if (ret < 0) {
3468         return ret;
3469     }
3470 
3471     /*
3472      * The interrupt_bitmap is ignored because KVM_GET_SREGS is
3473      * always preceded by KVM_GET_VCPU_EVENTS.
3474      */
3475 
3476     get_seg(&env->segs[R_CS], &sregs.cs);
3477     get_seg(&env->segs[R_DS], &sregs.ds);
3478     get_seg(&env->segs[R_ES], &sregs.es);
3479     get_seg(&env->segs[R_FS], &sregs.fs);
3480     get_seg(&env->segs[R_GS], &sregs.gs);
3481     get_seg(&env->segs[R_SS], &sregs.ss);
3482 
3483     get_seg(&env->tr, &sregs.tr);
3484     get_seg(&env->ldt, &sregs.ldt);
3485 
3486     env->idt.limit = sregs.idt.limit;
3487     env->idt.base = sregs.idt.base;
3488     env->gdt.limit = sregs.gdt.limit;
3489     env->gdt.base = sregs.gdt.base;
3490 
3491     env->cr[0] = sregs.cr0;
3492     env->cr[2] = sregs.cr2;
3493     env->cr[3] = sregs.cr3;
3494     env->cr[4] = sregs.cr4;
3495 
3496     env->efer = sregs.efer;
3497 
3498     /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
3499     x86_update_hflags(env);
3500 
3501     return 0;
3502 }
3503 
3504 static int kvm_get_sregs2(X86CPU *cpu)
3505 {
3506     CPUX86State *env = &cpu->env;
3507     struct kvm_sregs2 sregs;
3508     int i, ret;
3509 
3510     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS2, &sregs);
3511     if (ret < 0) {
3512         return ret;
3513     }
3514 
3515     get_seg(&env->segs[R_CS], &sregs.cs);
3516     get_seg(&env->segs[R_DS], &sregs.ds);
3517     get_seg(&env->segs[R_ES], &sregs.es);
3518     get_seg(&env->segs[R_FS], &sregs.fs);
3519     get_seg(&env->segs[R_GS], &sregs.gs);
3520     get_seg(&env->segs[R_SS], &sregs.ss);
3521 
3522     get_seg(&env->tr, &sregs.tr);
3523     get_seg(&env->ldt, &sregs.ldt);
3524 
3525     env->idt.limit = sregs.idt.limit;
3526     env->idt.base = sregs.idt.base;
3527     env->gdt.limit = sregs.gdt.limit;
3528     env->gdt.base = sregs.gdt.base;
3529 
3530     env->cr[0] = sregs.cr0;
3531     env->cr[2] = sregs.cr2;
3532     env->cr[3] = sregs.cr3;
3533     env->cr[4] = sregs.cr4;
3534 
3535     env->efer = sregs.efer;
3536 
3537     env->pdptrs_valid = sregs.flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
3538 
3539     if (env->pdptrs_valid) {
3540         for (i = 0; i < 4; i++) {
3541             env->pdptrs[i] = sregs.pdptrs[i];
3542         }
3543     }
3544 
3545     /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
3546     x86_update_hflags(env);
3547 
3548     return 0;
3549 }
3550 
3551 static int kvm_get_msrs(X86CPU *cpu)
3552 {
3553     CPUX86State *env = &cpu->env;
3554     struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
3555     int ret, i;
3556     uint64_t mtrr_top_bits;
3557 
3558     kvm_msr_buf_reset(cpu);
3559 
3560     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
3561     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
3562     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
3563     kvm_msr_entry_add(cpu, MSR_PAT, 0);
3564     if (has_msr_star) {
3565         kvm_msr_entry_add(cpu, MSR_STAR, 0);
3566     }
3567     if (has_msr_hsave_pa) {
3568         kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
3569     }
3570     if (has_msr_tsc_aux) {
3571         kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
3572     }
3573     if (has_msr_tsc_adjust) {
3574         kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
3575     }
3576     if (has_msr_tsc_deadline) {
3577         kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
3578     }
3579     if (has_msr_misc_enable) {
3580         kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
3581     }
3582     if (has_msr_smbase) {
3583         kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
3584     }
3585     if (has_msr_smi_count) {
3586         kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
3587     }
3588     if (has_msr_feature_control) {
3589         kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
3590     }
3591     if (has_msr_pkrs) {
3592         kvm_msr_entry_add(cpu, MSR_IA32_PKRS, 0);
3593     }
3594     if (has_msr_bndcfgs) {
3595         kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
3596     }
3597     if (has_msr_xss) {
3598         kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
3599     }
3600     if (has_msr_umwait) {
3601         kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, 0);
3602     }
3603     if (has_msr_spec_ctrl) {
3604         kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
3605     }
3606     if (has_tsc_scale_msr) {
3607         kvm_msr_entry_add(cpu, MSR_AMD64_TSC_RATIO, 0);
3608     }
3609 
3610     if (has_msr_tsx_ctrl) {
3611         kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, 0);
3612     }
3613     if (has_msr_virt_ssbd) {
3614         kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, 0);
3615     }
3616     if (!env->tsc_valid) {
3617         kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
3618         env->tsc_valid = !runstate_is_running();
3619     }
3620 
3621 #ifdef TARGET_X86_64
3622     if (lm_capable_kernel) {
3623         kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
3624         kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
3625         kvm_msr_entry_add(cpu, MSR_FMASK, 0);
3626         kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
3627     }
3628 #endif
3629     kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
3630     kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
3631     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
3632         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, 0);
3633     }
3634     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
3635         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
3636     }
3637     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
3638         kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
3639     }
3640     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
3641         kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
3642     }
3643     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
3644         kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, 1);
3645     }
3646     if (has_architectural_pmu_version > 0) {
3647         if (has_architectural_pmu_version > 1) {
3648             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
3649             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
3650             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
3651             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
3652         }
3653         for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
3654             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
3655         }
3656         for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
3657             kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
3658             kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
3659         }
3660     }
3661 
3662     if (env->mcg_cap) {
3663         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
3664         kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
3665         if (has_msr_mcg_ext_ctl) {
3666             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
3667         }
3668         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3669             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
3670         }
3671     }
3672 
3673     if (has_msr_hv_hypercall) {
3674         kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
3675         kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
3676     }
3677     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3678         kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
3679     }
3680     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
3681         kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
3682     }
3683     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
3684         kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL, 0);
3685         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL, 0);
3686         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS, 0);
3687     }
3688     if (has_msr_hv_syndbg_options) {
3689         kvm_msr_entry_add(cpu, HV_X64_MSR_SYNDBG_OPTIONS, 0);
3690     }
3691     if (has_msr_hv_crash) {
3692         int j;
3693 
3694         for (j = 0; j < HV_CRASH_PARAMS; j++) {
3695             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
3696         }
3697     }
3698     if (has_msr_hv_runtime) {
3699         kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
3700     }
3701     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3702         uint32_t msr;
3703 
3704         kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
3705         kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
3706         kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
3707         for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
3708             kvm_msr_entry_add(cpu, msr, 0);
3709         }
3710     }
3711     if (has_msr_hv_stimer) {
3712         uint32_t msr;
3713 
3714         for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
3715              msr++) {
3716             kvm_msr_entry_add(cpu, msr, 0);
3717         }
3718     }
3719     if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3720         kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
3721         kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
3722         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
3723         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
3724         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
3725         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
3726         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
3727         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
3728         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
3729         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
3730         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
3731         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
3732         for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
3733             kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
3734             kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
3735         }
3736     }
3737 
3738     if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
3739         int addr_num =
3740             kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
3741 
3742         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
3743         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
3744         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
3745         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
3746         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
3747         for (i = 0; i < addr_num; i++) {
3748             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
3749         }
3750     }
3751 
3752     if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_SGX_LC) {
3753         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH0, 0);
3754         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH1, 0);
3755         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH2, 0);
3756         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH3, 0);
3757     }
3758 
3759     if (env->features[FEAT_XSAVE] & CPUID_D_1_EAX_XFD) {
3760         kvm_msr_entry_add(cpu, MSR_IA32_XFD, 0);
3761         kvm_msr_entry_add(cpu, MSR_IA32_XFD_ERR, 0);
3762     }
3763 
3764     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
3765     if (ret < 0) {
3766         return ret;
3767     }
3768 
3769     if (ret < cpu->kvm_msr_buf->nmsrs) {
3770         struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
3771         error_report("error: failed to get MSR 0x%" PRIx32,
3772                      (uint32_t)e->index);
3773     }
3774 
3775     assert(ret == cpu->kvm_msr_buf->nmsrs);
3776     /*
3777      * MTRR masks: Each mask consists of 5 parts
3778      * a  10..0: must be zero
3779      * b  11   : valid bit
3780      * c n-1.12: actual mask bits
3781      * d  51..n: reserved must be zero
3782      * e  63.52: reserved must be zero
3783      *
3784      * 'n' is the number of physical bits supported by the CPU and is
3785      * apparently always <= 52.   We know our 'n' but don't know what
3786      * the destinations 'n' is; it might be smaller, in which case
3787      * it masks (c) on loading. It might be larger, in which case
3788      * we fill 'd' so that d..c is consistent irrespetive of the 'n'
3789      * we're migrating to.
3790      */
3791 
3792     if (cpu->fill_mtrr_mask) {
3793         QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
3794         assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
3795         mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
3796     } else {
3797         mtrr_top_bits = 0;
3798     }
3799 
3800     for (i = 0; i < ret; i++) {
3801         uint32_t index = msrs[i].index;
3802         switch (index) {
3803         case MSR_IA32_SYSENTER_CS:
3804             env->sysenter_cs = msrs[i].data;
3805             break;
3806         case MSR_IA32_SYSENTER_ESP:
3807             env->sysenter_esp = msrs[i].data;
3808             break;
3809         case MSR_IA32_SYSENTER_EIP:
3810             env->sysenter_eip = msrs[i].data;
3811             break;
3812         case MSR_PAT:
3813             env->pat = msrs[i].data;
3814             break;
3815         case MSR_STAR:
3816             env->star = msrs[i].data;
3817             break;
3818 #ifdef TARGET_X86_64
3819         case MSR_CSTAR:
3820             env->cstar = msrs[i].data;
3821             break;
3822         case MSR_KERNELGSBASE:
3823             env->kernelgsbase = msrs[i].data;
3824             break;
3825         case MSR_FMASK:
3826             env->fmask = msrs[i].data;
3827             break;
3828         case MSR_LSTAR:
3829             env->lstar = msrs[i].data;
3830             break;
3831 #endif
3832         case MSR_IA32_TSC:
3833             env->tsc = msrs[i].data;
3834             break;
3835         case MSR_TSC_AUX:
3836             env->tsc_aux = msrs[i].data;
3837             break;
3838         case MSR_TSC_ADJUST:
3839             env->tsc_adjust = msrs[i].data;
3840             break;
3841         case MSR_IA32_TSCDEADLINE:
3842             env->tsc_deadline = msrs[i].data;
3843             break;
3844         case MSR_VM_HSAVE_PA:
3845             env->vm_hsave = msrs[i].data;
3846             break;
3847         case MSR_KVM_SYSTEM_TIME:
3848             env->system_time_msr = msrs[i].data;
3849             break;
3850         case MSR_KVM_WALL_CLOCK:
3851             env->wall_clock_msr = msrs[i].data;
3852             break;
3853         case MSR_MCG_STATUS:
3854             env->mcg_status = msrs[i].data;
3855             break;
3856         case MSR_MCG_CTL:
3857             env->mcg_ctl = msrs[i].data;
3858             break;
3859         case MSR_MCG_EXT_CTL:
3860             env->mcg_ext_ctl = msrs[i].data;
3861             break;
3862         case MSR_IA32_MISC_ENABLE:
3863             env->msr_ia32_misc_enable = msrs[i].data;
3864             break;
3865         case MSR_IA32_SMBASE:
3866             env->smbase = msrs[i].data;
3867             break;
3868         case MSR_SMI_COUNT:
3869             env->msr_smi_count = msrs[i].data;
3870             break;
3871         case MSR_IA32_FEATURE_CONTROL:
3872             env->msr_ia32_feature_control = msrs[i].data;
3873             break;
3874         case MSR_IA32_BNDCFGS:
3875             env->msr_bndcfgs = msrs[i].data;
3876             break;
3877         case MSR_IA32_XSS:
3878             env->xss = msrs[i].data;
3879             break;
3880         case MSR_IA32_UMWAIT_CONTROL:
3881             env->umwait = msrs[i].data;
3882             break;
3883         case MSR_IA32_PKRS:
3884             env->pkrs = msrs[i].data;
3885             break;
3886         default:
3887             if (msrs[i].index >= MSR_MC0_CTL &&
3888                 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
3889                 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
3890             }
3891             break;
3892         case MSR_KVM_ASYNC_PF_EN:
3893             env->async_pf_en_msr = msrs[i].data;
3894             break;
3895         case MSR_KVM_ASYNC_PF_INT:
3896             env->async_pf_int_msr = msrs[i].data;
3897             break;
3898         case MSR_KVM_PV_EOI_EN:
3899             env->pv_eoi_en_msr = msrs[i].data;
3900             break;
3901         case MSR_KVM_STEAL_TIME:
3902             env->steal_time_msr = msrs[i].data;
3903             break;
3904         case MSR_KVM_POLL_CONTROL: {
3905             env->poll_control_msr = msrs[i].data;
3906             break;
3907         }
3908         case MSR_CORE_PERF_FIXED_CTR_CTRL:
3909             env->msr_fixed_ctr_ctrl = msrs[i].data;
3910             break;
3911         case MSR_CORE_PERF_GLOBAL_CTRL:
3912             env->msr_global_ctrl = msrs[i].data;
3913             break;
3914         case MSR_CORE_PERF_GLOBAL_STATUS:
3915             env->msr_global_status = msrs[i].data;
3916             break;
3917         case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
3918             env->msr_global_ovf_ctrl = msrs[i].data;
3919             break;
3920         case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
3921             env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
3922             break;
3923         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
3924             env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
3925             break;
3926         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
3927             env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
3928             break;
3929         case HV_X64_MSR_HYPERCALL:
3930             env->msr_hv_hypercall = msrs[i].data;
3931             break;
3932         case HV_X64_MSR_GUEST_OS_ID:
3933             env->msr_hv_guest_os_id = msrs[i].data;
3934             break;
3935         case HV_X64_MSR_APIC_ASSIST_PAGE:
3936             env->msr_hv_vapic = msrs[i].data;
3937             break;
3938         case HV_X64_MSR_REFERENCE_TSC:
3939             env->msr_hv_tsc = msrs[i].data;
3940             break;
3941         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3942             env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
3943             break;
3944         case HV_X64_MSR_VP_RUNTIME:
3945             env->msr_hv_runtime = msrs[i].data;
3946             break;
3947         case HV_X64_MSR_SCONTROL:
3948             env->msr_hv_synic_control = msrs[i].data;
3949             break;
3950         case HV_X64_MSR_SIEFP:
3951             env->msr_hv_synic_evt_page = msrs[i].data;
3952             break;
3953         case HV_X64_MSR_SIMP:
3954             env->msr_hv_synic_msg_page = msrs[i].data;
3955             break;
3956         case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
3957             env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
3958             break;
3959         case HV_X64_MSR_STIMER0_CONFIG:
3960         case HV_X64_MSR_STIMER1_CONFIG:
3961         case HV_X64_MSR_STIMER2_CONFIG:
3962         case HV_X64_MSR_STIMER3_CONFIG:
3963             env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
3964                                 msrs[i].data;
3965             break;
3966         case HV_X64_MSR_STIMER0_COUNT:
3967         case HV_X64_MSR_STIMER1_COUNT:
3968         case HV_X64_MSR_STIMER2_COUNT:
3969         case HV_X64_MSR_STIMER3_COUNT:
3970             env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
3971                                 msrs[i].data;
3972             break;
3973         case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3974             env->msr_hv_reenlightenment_control = msrs[i].data;
3975             break;
3976         case HV_X64_MSR_TSC_EMULATION_CONTROL:
3977             env->msr_hv_tsc_emulation_control = msrs[i].data;
3978             break;
3979         case HV_X64_MSR_TSC_EMULATION_STATUS:
3980             env->msr_hv_tsc_emulation_status = msrs[i].data;
3981             break;
3982         case HV_X64_MSR_SYNDBG_OPTIONS:
3983             env->msr_hv_syndbg_options = msrs[i].data;
3984             break;
3985         case MSR_MTRRdefType:
3986             env->mtrr_deftype = msrs[i].data;
3987             break;
3988         case MSR_MTRRfix64K_00000:
3989             env->mtrr_fixed[0] = msrs[i].data;
3990             break;
3991         case MSR_MTRRfix16K_80000:
3992             env->mtrr_fixed[1] = msrs[i].data;
3993             break;
3994         case MSR_MTRRfix16K_A0000:
3995             env->mtrr_fixed[2] = msrs[i].data;
3996             break;
3997         case MSR_MTRRfix4K_C0000:
3998             env->mtrr_fixed[3] = msrs[i].data;
3999             break;
4000         case MSR_MTRRfix4K_C8000:
4001             env->mtrr_fixed[4] = msrs[i].data;
4002             break;
4003         case MSR_MTRRfix4K_D0000:
4004             env->mtrr_fixed[5] = msrs[i].data;
4005             break;
4006         case MSR_MTRRfix4K_D8000:
4007             env->mtrr_fixed[6] = msrs[i].data;
4008             break;
4009         case MSR_MTRRfix4K_E0000:
4010             env->mtrr_fixed[7] = msrs[i].data;
4011             break;
4012         case MSR_MTRRfix4K_E8000:
4013             env->mtrr_fixed[8] = msrs[i].data;
4014             break;
4015         case MSR_MTRRfix4K_F0000:
4016             env->mtrr_fixed[9] = msrs[i].data;
4017             break;
4018         case MSR_MTRRfix4K_F8000:
4019             env->mtrr_fixed[10] = msrs[i].data;
4020             break;
4021         case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
4022             if (index & 1) {
4023                 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
4024                                                                mtrr_top_bits;
4025             } else {
4026                 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
4027             }
4028             break;
4029         case MSR_IA32_SPEC_CTRL:
4030             env->spec_ctrl = msrs[i].data;
4031             break;
4032         case MSR_AMD64_TSC_RATIO:
4033             env->amd_tsc_scale_msr = msrs[i].data;
4034             break;
4035         case MSR_IA32_TSX_CTRL:
4036             env->tsx_ctrl = msrs[i].data;
4037             break;
4038         case MSR_VIRT_SSBD:
4039             env->virt_ssbd = msrs[i].data;
4040             break;
4041         case MSR_IA32_RTIT_CTL:
4042             env->msr_rtit_ctrl = msrs[i].data;
4043             break;
4044         case MSR_IA32_RTIT_STATUS:
4045             env->msr_rtit_status = msrs[i].data;
4046             break;
4047         case MSR_IA32_RTIT_OUTPUT_BASE:
4048             env->msr_rtit_output_base = msrs[i].data;
4049             break;
4050         case MSR_IA32_RTIT_OUTPUT_MASK:
4051             env->msr_rtit_output_mask = msrs[i].data;
4052             break;
4053         case MSR_IA32_RTIT_CR3_MATCH:
4054             env->msr_rtit_cr3_match = msrs[i].data;
4055             break;
4056         case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
4057             env->msr_rtit_addrs[index - MSR_IA32_RTIT_ADDR0_A] = msrs[i].data;
4058             break;
4059         case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
4060             env->msr_ia32_sgxlepubkeyhash[index - MSR_IA32_SGXLEPUBKEYHASH0] =
4061                            msrs[i].data;
4062             break;
4063         case MSR_IA32_XFD:
4064             env->msr_xfd = msrs[i].data;
4065             break;
4066         case MSR_IA32_XFD_ERR:
4067             env->msr_xfd_err = msrs[i].data;
4068             break;
4069         }
4070     }
4071 
4072     return 0;
4073 }
4074 
4075 static int kvm_put_mp_state(X86CPU *cpu)
4076 {
4077     struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
4078 
4079     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
4080 }
4081 
4082 static int kvm_get_mp_state(X86CPU *cpu)
4083 {
4084     CPUState *cs = CPU(cpu);
4085     CPUX86State *env = &cpu->env;
4086     struct kvm_mp_state mp_state;
4087     int ret;
4088 
4089     ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
4090     if (ret < 0) {
4091         return ret;
4092     }
4093     env->mp_state = mp_state.mp_state;
4094     if (kvm_irqchip_in_kernel()) {
4095         cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
4096     }
4097     return 0;
4098 }
4099 
4100 static int kvm_get_apic(X86CPU *cpu)
4101 {
4102     DeviceState *apic = cpu->apic_state;
4103     struct kvm_lapic_state kapic;
4104     int ret;
4105 
4106     if (apic && kvm_irqchip_in_kernel()) {
4107         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
4108         if (ret < 0) {
4109             return ret;
4110         }
4111 
4112         kvm_get_apic_state(apic, &kapic);
4113     }
4114     return 0;
4115 }
4116 
4117 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
4118 {
4119     CPUState *cs = CPU(cpu);
4120     CPUX86State *env = &cpu->env;
4121     struct kvm_vcpu_events events = {};
4122 
4123     if (!kvm_has_vcpu_events()) {
4124         return 0;
4125     }
4126 
4127     events.flags = 0;
4128 
4129     if (has_exception_payload) {
4130         events.flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
4131         events.exception.pending = env->exception_pending;
4132         events.exception_has_payload = env->exception_has_payload;
4133         events.exception_payload = env->exception_payload;
4134     }
4135     events.exception.nr = env->exception_nr;
4136     events.exception.injected = env->exception_injected;
4137     events.exception.has_error_code = env->has_error_code;
4138     events.exception.error_code = env->error_code;
4139 
4140     events.interrupt.injected = (env->interrupt_injected >= 0);
4141     events.interrupt.nr = env->interrupt_injected;
4142     events.interrupt.soft = env->soft_interrupt;
4143 
4144     events.nmi.injected = env->nmi_injected;
4145     events.nmi.pending = env->nmi_pending;
4146     events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
4147 
4148     events.sipi_vector = env->sipi_vector;
4149 
4150     if (has_msr_smbase) {
4151         events.smi.smm = !!(env->hflags & HF_SMM_MASK);
4152         events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
4153         if (kvm_irqchip_in_kernel()) {
4154             /* As soon as these are moved to the kernel, remove them
4155              * from cs->interrupt_request.
4156              */
4157             events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
4158             events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
4159             cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
4160         } else {
4161             /* Keep these in cs->interrupt_request.  */
4162             events.smi.pending = 0;
4163             events.smi.latched_init = 0;
4164         }
4165         /* Stop SMI delivery on old machine types to avoid a reboot
4166          * on an inward migration of an old VM.
4167          */
4168         if (!cpu->kvm_no_smi_migration) {
4169             events.flags |= KVM_VCPUEVENT_VALID_SMM;
4170         }
4171     }
4172 
4173     if (level >= KVM_PUT_RESET_STATE) {
4174         events.flags |= KVM_VCPUEVENT_VALID_NMI_PENDING;
4175         if (env->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
4176             events.flags |= KVM_VCPUEVENT_VALID_SIPI_VECTOR;
4177         }
4178     }
4179 
4180     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
4181 }
4182 
4183 static int kvm_get_vcpu_events(X86CPU *cpu)
4184 {
4185     CPUX86State *env = &cpu->env;
4186     struct kvm_vcpu_events events;
4187     int ret;
4188 
4189     if (!kvm_has_vcpu_events()) {
4190         return 0;
4191     }
4192 
4193     memset(&events, 0, sizeof(events));
4194     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
4195     if (ret < 0) {
4196        return ret;
4197     }
4198 
4199     if (events.flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4200         env->exception_pending = events.exception.pending;
4201         env->exception_has_payload = events.exception_has_payload;
4202         env->exception_payload = events.exception_payload;
4203     } else {
4204         env->exception_pending = 0;
4205         env->exception_has_payload = false;
4206     }
4207     env->exception_injected = events.exception.injected;
4208     env->exception_nr =
4209         (env->exception_pending || env->exception_injected) ?
4210         events.exception.nr : -1;
4211     env->has_error_code = events.exception.has_error_code;
4212     env->error_code = events.exception.error_code;
4213 
4214     env->interrupt_injected =
4215         events.interrupt.injected ? events.interrupt.nr : -1;
4216     env->soft_interrupt = events.interrupt.soft;
4217 
4218     env->nmi_injected = events.nmi.injected;
4219     env->nmi_pending = events.nmi.pending;
4220     if (events.nmi.masked) {
4221         env->hflags2 |= HF2_NMI_MASK;
4222     } else {
4223         env->hflags2 &= ~HF2_NMI_MASK;
4224     }
4225 
4226     if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
4227         if (events.smi.smm) {
4228             env->hflags |= HF_SMM_MASK;
4229         } else {
4230             env->hflags &= ~HF_SMM_MASK;
4231         }
4232         if (events.smi.pending) {
4233             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
4234         } else {
4235             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
4236         }
4237         if (events.smi.smm_inside_nmi) {
4238             env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
4239         } else {
4240             env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
4241         }
4242         if (events.smi.latched_init) {
4243             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
4244         } else {
4245             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
4246         }
4247     }
4248 
4249     env->sipi_vector = events.sipi_vector;
4250 
4251     return 0;
4252 }
4253 
4254 static int kvm_guest_debug_workarounds(X86CPU *cpu)
4255 {
4256     CPUState *cs = CPU(cpu);
4257     CPUX86State *env = &cpu->env;
4258     int ret = 0;
4259     unsigned long reinject_trap = 0;
4260 
4261     if (!kvm_has_vcpu_events()) {
4262         if (env->exception_nr == EXCP01_DB) {
4263             reinject_trap = KVM_GUESTDBG_INJECT_DB;
4264         } else if (env->exception_injected == EXCP03_INT3) {
4265             reinject_trap = KVM_GUESTDBG_INJECT_BP;
4266         }
4267         kvm_reset_exception(env);
4268     }
4269 
4270     /*
4271      * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
4272      * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
4273      * by updating the debug state once again if single-stepping is on.
4274      * Another reason to call kvm_update_guest_debug here is a pending debug
4275      * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
4276      * reinject them via SET_GUEST_DEBUG.
4277      */
4278     if (reinject_trap ||
4279         (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
4280         ret = kvm_update_guest_debug(cs, reinject_trap);
4281     }
4282     return ret;
4283 }
4284 
4285 static int kvm_put_debugregs(X86CPU *cpu)
4286 {
4287     CPUX86State *env = &cpu->env;
4288     struct kvm_debugregs dbgregs;
4289     int i;
4290 
4291     if (!kvm_has_debugregs()) {
4292         return 0;
4293     }
4294 
4295     memset(&dbgregs, 0, sizeof(dbgregs));
4296     for (i = 0; i < 4; i++) {
4297         dbgregs.db[i] = env->dr[i];
4298     }
4299     dbgregs.dr6 = env->dr[6];
4300     dbgregs.dr7 = env->dr[7];
4301     dbgregs.flags = 0;
4302 
4303     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
4304 }
4305 
4306 static int kvm_get_debugregs(X86CPU *cpu)
4307 {
4308     CPUX86State *env = &cpu->env;
4309     struct kvm_debugregs dbgregs;
4310     int i, ret;
4311 
4312     if (!kvm_has_debugregs()) {
4313         return 0;
4314     }
4315 
4316     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
4317     if (ret < 0) {
4318         return ret;
4319     }
4320     for (i = 0; i < 4; i++) {
4321         env->dr[i] = dbgregs.db[i];
4322     }
4323     env->dr[4] = env->dr[6] = dbgregs.dr6;
4324     env->dr[5] = env->dr[7] = dbgregs.dr7;
4325 
4326     return 0;
4327 }
4328 
4329 static int kvm_put_nested_state(X86CPU *cpu)
4330 {
4331     CPUX86State *env = &cpu->env;
4332     int max_nested_state_len = kvm_max_nested_state_length();
4333 
4334     if (!env->nested_state) {
4335         return 0;
4336     }
4337 
4338     /*
4339      * Copy flags that are affected by reset from env->hflags and env->hflags2.
4340      */
4341     if (env->hflags & HF_GUEST_MASK) {
4342         env->nested_state->flags |= KVM_STATE_NESTED_GUEST_MODE;
4343     } else {
4344         env->nested_state->flags &= ~KVM_STATE_NESTED_GUEST_MODE;
4345     }
4346 
4347     /* Don't set KVM_STATE_NESTED_GIF_SET on VMX as it is illegal */
4348     if (cpu_has_svm(env) && (env->hflags2 & HF2_GIF_MASK)) {
4349         env->nested_state->flags |= KVM_STATE_NESTED_GIF_SET;
4350     } else {
4351         env->nested_state->flags &= ~KVM_STATE_NESTED_GIF_SET;
4352     }
4353 
4354     assert(env->nested_state->size <= max_nested_state_len);
4355     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_NESTED_STATE, env->nested_state);
4356 }
4357 
4358 static int kvm_get_nested_state(X86CPU *cpu)
4359 {
4360     CPUX86State *env = &cpu->env;
4361     int max_nested_state_len = kvm_max_nested_state_length();
4362     int ret;
4363 
4364     if (!env->nested_state) {
4365         return 0;
4366     }
4367 
4368     /*
4369      * It is possible that migration restored a smaller size into
4370      * nested_state->hdr.size than what our kernel support.
4371      * We preserve migration origin nested_state->hdr.size for
4372      * call to KVM_SET_NESTED_STATE but wish that our next call
4373      * to KVM_GET_NESTED_STATE will use max size our kernel support.
4374      */
4375     env->nested_state->size = max_nested_state_len;
4376 
4377     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_NESTED_STATE, env->nested_state);
4378     if (ret < 0) {
4379         return ret;
4380     }
4381 
4382     /*
4383      * Copy flags that are affected by reset to env->hflags and env->hflags2.
4384      */
4385     if (env->nested_state->flags & KVM_STATE_NESTED_GUEST_MODE) {
4386         env->hflags |= HF_GUEST_MASK;
4387     } else {
4388         env->hflags &= ~HF_GUEST_MASK;
4389     }
4390 
4391     /* Keep HF2_GIF_MASK set on !SVM as x86_cpu_pending_interrupt() needs it */
4392     if (cpu_has_svm(env)) {
4393         if (env->nested_state->flags & KVM_STATE_NESTED_GIF_SET) {
4394             env->hflags2 |= HF2_GIF_MASK;
4395         } else {
4396             env->hflags2 &= ~HF2_GIF_MASK;
4397         }
4398     }
4399 
4400     return ret;
4401 }
4402 
4403 int kvm_arch_put_registers(CPUState *cpu, int level)
4404 {
4405     X86CPU *x86_cpu = X86_CPU(cpu);
4406     int ret;
4407 
4408     assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
4409 
4410     /* must be before kvm_put_nested_state so that EFER.SVME is set */
4411     ret = has_sregs2 ? kvm_put_sregs2(x86_cpu) : kvm_put_sregs(x86_cpu);
4412     if (ret < 0) {
4413         return ret;
4414     }
4415 
4416     if (level >= KVM_PUT_RESET_STATE) {
4417         ret = kvm_put_nested_state(x86_cpu);
4418         if (ret < 0) {
4419             return ret;
4420         }
4421 
4422         ret = kvm_put_msr_feature_control(x86_cpu);
4423         if (ret < 0) {
4424             return ret;
4425         }
4426     }
4427 
4428     if (level == KVM_PUT_FULL_STATE) {
4429         /* We don't check for kvm_arch_set_tsc_khz() errors here,
4430          * because TSC frequency mismatch shouldn't abort migration,
4431          * unless the user explicitly asked for a more strict TSC
4432          * setting (e.g. using an explicit "tsc-freq" option).
4433          */
4434         kvm_arch_set_tsc_khz(cpu);
4435     }
4436 
4437     ret = kvm_getput_regs(x86_cpu, 1);
4438     if (ret < 0) {
4439         return ret;
4440     }
4441     ret = kvm_put_xsave(x86_cpu);
4442     if (ret < 0) {
4443         return ret;
4444     }
4445     ret = kvm_put_xcrs(x86_cpu);
4446     if (ret < 0) {
4447         return ret;
4448     }
4449     /* must be before kvm_put_msrs */
4450     ret = kvm_inject_mce_oldstyle(x86_cpu);
4451     if (ret < 0) {
4452         return ret;
4453     }
4454     ret = kvm_put_msrs(x86_cpu, level);
4455     if (ret < 0) {
4456         return ret;
4457     }
4458     ret = kvm_put_vcpu_events(x86_cpu, level);
4459     if (ret < 0) {
4460         return ret;
4461     }
4462     if (level >= KVM_PUT_RESET_STATE) {
4463         ret = kvm_put_mp_state(x86_cpu);
4464         if (ret < 0) {
4465             return ret;
4466         }
4467     }
4468 
4469     ret = kvm_put_tscdeadline_msr(x86_cpu);
4470     if (ret < 0) {
4471         return ret;
4472     }
4473     ret = kvm_put_debugregs(x86_cpu);
4474     if (ret < 0) {
4475         return ret;
4476     }
4477     /* must be last */
4478     ret = kvm_guest_debug_workarounds(x86_cpu);
4479     if (ret < 0) {
4480         return ret;
4481     }
4482     return 0;
4483 }
4484 
4485 int kvm_arch_get_registers(CPUState *cs)
4486 {
4487     X86CPU *cpu = X86_CPU(cs);
4488     int ret;
4489 
4490     assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
4491 
4492     ret = kvm_get_vcpu_events(cpu);
4493     if (ret < 0) {
4494         goto out;
4495     }
4496     /*
4497      * KVM_GET_MPSTATE can modify CS and RIP, call it before
4498      * KVM_GET_REGS and KVM_GET_SREGS.
4499      */
4500     ret = kvm_get_mp_state(cpu);
4501     if (ret < 0) {
4502         goto out;
4503     }
4504     ret = kvm_getput_regs(cpu, 0);
4505     if (ret < 0) {
4506         goto out;
4507     }
4508     ret = kvm_get_xsave(cpu);
4509     if (ret < 0) {
4510         goto out;
4511     }
4512     ret = kvm_get_xcrs(cpu);
4513     if (ret < 0) {
4514         goto out;
4515     }
4516     ret = has_sregs2 ? kvm_get_sregs2(cpu) : kvm_get_sregs(cpu);
4517     if (ret < 0) {
4518         goto out;
4519     }
4520     ret = kvm_get_msrs(cpu);
4521     if (ret < 0) {
4522         goto out;
4523     }
4524     ret = kvm_get_apic(cpu);
4525     if (ret < 0) {
4526         goto out;
4527     }
4528     ret = kvm_get_debugregs(cpu);
4529     if (ret < 0) {
4530         goto out;
4531     }
4532     ret = kvm_get_nested_state(cpu);
4533     if (ret < 0) {
4534         goto out;
4535     }
4536     ret = 0;
4537  out:
4538     cpu_sync_bndcs_hflags(&cpu->env);
4539     return ret;
4540 }
4541 
4542 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
4543 {
4544     X86CPU *x86_cpu = X86_CPU(cpu);
4545     CPUX86State *env = &x86_cpu->env;
4546     int ret;
4547 
4548     /* Inject NMI */
4549     if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
4550         if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
4551             qemu_mutex_lock_iothread();
4552             cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
4553             qemu_mutex_unlock_iothread();
4554             DPRINTF("injected NMI\n");
4555             ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
4556             if (ret < 0) {
4557                 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
4558                         strerror(-ret));
4559             }
4560         }
4561         if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
4562             qemu_mutex_lock_iothread();
4563             cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
4564             qemu_mutex_unlock_iothread();
4565             DPRINTF("injected SMI\n");
4566             ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
4567             if (ret < 0) {
4568                 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
4569                         strerror(-ret));
4570             }
4571         }
4572     }
4573 
4574     if (!kvm_pic_in_kernel()) {
4575         qemu_mutex_lock_iothread();
4576     }
4577 
4578     /* Force the VCPU out of its inner loop to process any INIT requests
4579      * or (for userspace APIC, but it is cheap to combine the checks here)
4580      * pending TPR access reports.
4581      */
4582     if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
4583         if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
4584             !(env->hflags & HF_SMM_MASK)) {
4585             cpu->exit_request = 1;
4586         }
4587         if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
4588             cpu->exit_request = 1;
4589         }
4590     }
4591 
4592     if (!kvm_pic_in_kernel()) {
4593         /* Try to inject an interrupt if the guest can accept it */
4594         if (run->ready_for_interrupt_injection &&
4595             (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
4596             (env->eflags & IF_MASK)) {
4597             int irq;
4598 
4599             cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
4600             irq = cpu_get_pic_interrupt(env);
4601             if (irq >= 0) {
4602                 struct kvm_interrupt intr;
4603 
4604                 intr.irq = irq;
4605                 DPRINTF("injected interrupt %d\n", irq);
4606                 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
4607                 if (ret < 0) {
4608                     fprintf(stderr,
4609                             "KVM: injection failed, interrupt lost (%s)\n",
4610                             strerror(-ret));
4611                 }
4612             }
4613         }
4614 
4615         /* If we have an interrupt but the guest is not ready to receive an
4616          * interrupt, request an interrupt window exit.  This will
4617          * cause a return to userspace as soon as the guest is ready to
4618          * receive interrupts. */
4619         if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
4620             run->request_interrupt_window = 1;
4621         } else {
4622             run->request_interrupt_window = 0;
4623         }
4624 
4625         DPRINTF("setting tpr\n");
4626         run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
4627 
4628         qemu_mutex_unlock_iothread();
4629     }
4630 }
4631 
4632 static void kvm_rate_limit_on_bus_lock(void)
4633 {
4634     uint64_t delay_ns = ratelimit_calculate_delay(&bus_lock_ratelimit_ctrl, 1);
4635 
4636     if (delay_ns) {
4637         g_usleep(delay_ns / SCALE_US);
4638     }
4639 }
4640 
4641 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
4642 {
4643     X86CPU *x86_cpu = X86_CPU(cpu);
4644     CPUX86State *env = &x86_cpu->env;
4645 
4646     if (run->flags & KVM_RUN_X86_SMM) {
4647         env->hflags |= HF_SMM_MASK;
4648     } else {
4649         env->hflags &= ~HF_SMM_MASK;
4650     }
4651     if (run->if_flag) {
4652         env->eflags |= IF_MASK;
4653     } else {
4654         env->eflags &= ~IF_MASK;
4655     }
4656     if (run->flags & KVM_RUN_X86_BUS_LOCK) {
4657         kvm_rate_limit_on_bus_lock();
4658     }
4659 
4660     /* We need to protect the apic state against concurrent accesses from
4661      * different threads in case the userspace irqchip is used. */
4662     if (!kvm_irqchip_in_kernel()) {
4663         qemu_mutex_lock_iothread();
4664     }
4665     cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
4666     cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
4667     if (!kvm_irqchip_in_kernel()) {
4668         qemu_mutex_unlock_iothread();
4669     }
4670     return cpu_get_mem_attrs(env);
4671 }
4672 
4673 int kvm_arch_process_async_events(CPUState *cs)
4674 {
4675     X86CPU *cpu = X86_CPU(cs);
4676     CPUX86State *env = &cpu->env;
4677 
4678     if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
4679         /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
4680         assert(env->mcg_cap);
4681 
4682         cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
4683 
4684         kvm_cpu_synchronize_state(cs);
4685 
4686         if (env->exception_nr == EXCP08_DBLE) {
4687             /* this means triple fault */
4688             qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
4689             cs->exit_request = 1;
4690             return 0;
4691         }
4692         kvm_queue_exception(env, EXCP12_MCHK, 0, 0);
4693         env->has_error_code = 0;
4694 
4695         cs->halted = 0;
4696         if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
4697             env->mp_state = KVM_MP_STATE_RUNNABLE;
4698         }
4699     }
4700 
4701     if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
4702         !(env->hflags & HF_SMM_MASK)) {
4703         kvm_cpu_synchronize_state(cs);
4704         do_cpu_init(cpu);
4705     }
4706 
4707     if (kvm_irqchip_in_kernel()) {
4708         return 0;
4709     }
4710 
4711     if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
4712         cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
4713         apic_poll_irq(cpu->apic_state);
4714     }
4715     if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
4716          (env->eflags & IF_MASK)) ||
4717         (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
4718         cs->halted = 0;
4719     }
4720     if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
4721         kvm_cpu_synchronize_state(cs);
4722         do_cpu_sipi(cpu);
4723     }
4724     if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
4725         cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
4726         kvm_cpu_synchronize_state(cs);
4727         apic_handle_tpr_access_report(cpu->apic_state, env->eip,
4728                                       env->tpr_access_type);
4729     }
4730 
4731     return cs->halted;
4732 }
4733 
4734 static int kvm_handle_halt(X86CPU *cpu)
4735 {
4736     CPUState *cs = CPU(cpu);
4737     CPUX86State *env = &cpu->env;
4738 
4739     if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
4740           (env->eflags & IF_MASK)) &&
4741         !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
4742         cs->halted = 1;
4743         return EXCP_HLT;
4744     }
4745 
4746     return 0;
4747 }
4748 
4749 static int kvm_handle_tpr_access(X86CPU *cpu)
4750 {
4751     CPUState *cs = CPU(cpu);
4752     struct kvm_run *run = cs->kvm_run;
4753 
4754     apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
4755                                   run->tpr_access.is_write ? TPR_ACCESS_WRITE
4756                                                            : TPR_ACCESS_READ);
4757     return 1;
4758 }
4759 
4760 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
4761 {
4762     static const uint8_t int3 = 0xcc;
4763 
4764     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
4765         cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
4766         return -EINVAL;
4767     }
4768     return 0;
4769 }
4770 
4771 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
4772 {
4773     uint8_t int3;
4774 
4775     if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0)) {
4776         return -EINVAL;
4777     }
4778     if (int3 != 0xcc) {
4779         return 0;
4780     }
4781     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
4782         return -EINVAL;
4783     }
4784     return 0;
4785 }
4786 
4787 static struct {
4788     target_ulong addr;
4789     int len;
4790     int type;
4791 } hw_breakpoint[4];
4792 
4793 static int nb_hw_breakpoint;
4794 
4795 static int find_hw_breakpoint(target_ulong addr, int len, int type)
4796 {
4797     int n;
4798 
4799     for (n = 0; n < nb_hw_breakpoint; n++) {
4800         if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
4801             (hw_breakpoint[n].len == len || len == -1)) {
4802             return n;
4803         }
4804     }
4805     return -1;
4806 }
4807 
4808 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
4809                                   target_ulong len, int type)
4810 {
4811     switch (type) {
4812     case GDB_BREAKPOINT_HW:
4813         len = 1;
4814         break;
4815     case GDB_WATCHPOINT_WRITE:
4816     case GDB_WATCHPOINT_ACCESS:
4817         switch (len) {
4818         case 1:
4819             break;
4820         case 2:
4821         case 4:
4822         case 8:
4823             if (addr & (len - 1)) {
4824                 return -EINVAL;
4825             }
4826             break;
4827         default:
4828             return -EINVAL;
4829         }
4830         break;
4831     default:
4832         return -ENOSYS;
4833     }
4834 
4835     if (nb_hw_breakpoint == 4) {
4836         return -ENOBUFS;
4837     }
4838     if (find_hw_breakpoint(addr, len, type) >= 0) {
4839         return -EEXIST;
4840     }
4841     hw_breakpoint[nb_hw_breakpoint].addr = addr;
4842     hw_breakpoint[nb_hw_breakpoint].len = len;
4843     hw_breakpoint[nb_hw_breakpoint].type = type;
4844     nb_hw_breakpoint++;
4845 
4846     return 0;
4847 }
4848 
4849 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
4850                                   target_ulong len, int type)
4851 {
4852     int n;
4853 
4854     n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
4855     if (n < 0) {
4856         return -ENOENT;
4857     }
4858     nb_hw_breakpoint--;
4859     hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
4860 
4861     return 0;
4862 }
4863 
4864 void kvm_arch_remove_all_hw_breakpoints(void)
4865 {
4866     nb_hw_breakpoint = 0;
4867 }
4868 
4869 static CPUWatchpoint hw_watchpoint;
4870 
4871 static int kvm_handle_debug(X86CPU *cpu,
4872                             struct kvm_debug_exit_arch *arch_info)
4873 {
4874     CPUState *cs = CPU(cpu);
4875     CPUX86State *env = &cpu->env;
4876     int ret = 0;
4877     int n;
4878 
4879     if (arch_info->exception == EXCP01_DB) {
4880         if (arch_info->dr6 & DR6_BS) {
4881             if (cs->singlestep_enabled) {
4882                 ret = EXCP_DEBUG;
4883             }
4884         } else {
4885             for (n = 0; n < 4; n++) {
4886                 if (arch_info->dr6 & (1 << n)) {
4887                     switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
4888                     case 0x0:
4889                         ret = EXCP_DEBUG;
4890                         break;
4891                     case 0x1:
4892                         ret = EXCP_DEBUG;
4893                         cs->watchpoint_hit = &hw_watchpoint;
4894                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
4895                         hw_watchpoint.flags = BP_MEM_WRITE;
4896                         break;
4897                     case 0x3:
4898                         ret = EXCP_DEBUG;
4899                         cs->watchpoint_hit = &hw_watchpoint;
4900                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
4901                         hw_watchpoint.flags = BP_MEM_ACCESS;
4902                         break;
4903                     }
4904                 }
4905             }
4906         }
4907     } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
4908         ret = EXCP_DEBUG;
4909     }
4910     if (ret == 0) {
4911         cpu_synchronize_state(cs);
4912         assert(env->exception_nr == -1);
4913 
4914         /* pass to guest */
4915         kvm_queue_exception(env, arch_info->exception,
4916                             arch_info->exception == EXCP01_DB,
4917                             arch_info->dr6);
4918         env->has_error_code = 0;
4919     }
4920 
4921     return ret;
4922 }
4923 
4924 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
4925 {
4926     const uint8_t type_code[] = {
4927         [GDB_BREAKPOINT_HW] = 0x0,
4928         [GDB_WATCHPOINT_WRITE] = 0x1,
4929         [GDB_WATCHPOINT_ACCESS] = 0x3
4930     };
4931     const uint8_t len_code[] = {
4932         [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
4933     };
4934     int n;
4935 
4936     if (kvm_sw_breakpoints_active(cpu)) {
4937         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
4938     }
4939     if (nb_hw_breakpoint > 0) {
4940         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
4941         dbg->arch.debugreg[7] = 0x0600;
4942         for (n = 0; n < nb_hw_breakpoint; n++) {
4943             dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
4944             dbg->arch.debugreg[7] |= (2 << (n * 2)) |
4945                 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
4946                 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
4947         }
4948     }
4949 }
4950 
4951 static bool has_sgx_provisioning;
4952 
4953 static bool __kvm_enable_sgx_provisioning(KVMState *s)
4954 {
4955     int fd, ret;
4956 
4957     if (!kvm_vm_check_extension(s, KVM_CAP_SGX_ATTRIBUTE)) {
4958         return false;
4959     }
4960 
4961     fd = qemu_open_old("/dev/sgx_provision", O_RDONLY);
4962     if (fd < 0) {
4963         return false;
4964     }
4965 
4966     ret = kvm_vm_enable_cap(s, KVM_CAP_SGX_ATTRIBUTE, 0, fd);
4967     if (ret) {
4968         error_report("Could not enable SGX PROVISIONKEY: %s", strerror(-ret));
4969         exit(1);
4970     }
4971     close(fd);
4972     return true;
4973 }
4974 
4975 bool kvm_enable_sgx_provisioning(KVMState *s)
4976 {
4977     return MEMORIZE(__kvm_enable_sgx_provisioning(s), has_sgx_provisioning);
4978 }
4979 
4980 static bool host_supports_vmx(void)
4981 {
4982     uint32_t ecx, unused;
4983 
4984     host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
4985     return ecx & CPUID_EXT_VMX;
4986 }
4987 
4988 #define VMX_INVALID_GUEST_STATE 0x80000021
4989 
4990 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
4991 {
4992     X86CPU *cpu = X86_CPU(cs);
4993     uint64_t code;
4994     int ret;
4995 
4996     switch (run->exit_reason) {
4997     case KVM_EXIT_HLT:
4998         DPRINTF("handle_hlt\n");
4999         qemu_mutex_lock_iothread();
5000         ret = kvm_handle_halt(cpu);
5001         qemu_mutex_unlock_iothread();
5002         break;
5003     case KVM_EXIT_SET_TPR:
5004         ret = 0;
5005         break;
5006     case KVM_EXIT_TPR_ACCESS:
5007         qemu_mutex_lock_iothread();
5008         ret = kvm_handle_tpr_access(cpu);
5009         qemu_mutex_unlock_iothread();
5010         break;
5011     case KVM_EXIT_FAIL_ENTRY:
5012         code = run->fail_entry.hardware_entry_failure_reason;
5013         fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
5014                 code);
5015         if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
5016             fprintf(stderr,
5017                     "\nIf you're running a guest on an Intel machine without "
5018                         "unrestricted mode\n"
5019                     "support, the failure can be most likely due to the guest "
5020                         "entering an invalid\n"
5021                     "state for Intel VT. For example, the guest maybe running "
5022                         "in big real mode\n"
5023                     "which is not supported on less recent Intel processors."
5024                         "\n\n");
5025         }
5026         ret = -1;
5027         break;
5028     case KVM_EXIT_EXCEPTION:
5029         fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
5030                 run->ex.exception, run->ex.error_code);
5031         ret = -1;
5032         break;
5033     case KVM_EXIT_DEBUG:
5034         DPRINTF("kvm_exit_debug\n");
5035         qemu_mutex_lock_iothread();
5036         ret = kvm_handle_debug(cpu, &run->debug.arch);
5037         qemu_mutex_unlock_iothread();
5038         break;
5039     case KVM_EXIT_HYPERV:
5040         ret = kvm_hv_handle_exit(cpu, &run->hyperv);
5041         break;
5042     case KVM_EXIT_IOAPIC_EOI:
5043         ioapic_eoi_broadcast(run->eoi.vector);
5044         ret = 0;
5045         break;
5046     case KVM_EXIT_X86_BUS_LOCK:
5047         /* already handled in kvm_arch_post_run */
5048         ret = 0;
5049         break;
5050     default:
5051         fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
5052         ret = -1;
5053         break;
5054     }
5055 
5056     return ret;
5057 }
5058 
5059 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
5060 {
5061     X86CPU *cpu = X86_CPU(cs);
5062     CPUX86State *env = &cpu->env;
5063 
5064     kvm_cpu_synchronize_state(cs);
5065     return !(env->cr[0] & CR0_PE_MASK) ||
5066            ((env->segs[R_CS].selector  & 3) != 3);
5067 }
5068 
5069 void kvm_arch_init_irq_routing(KVMState *s)
5070 {
5071     /* We know at this point that we're using the in-kernel
5072      * irqchip, so we can use irqfds, and on x86 we know
5073      * we can use msi via irqfd and GSI routing.
5074      */
5075     kvm_msi_via_irqfd_allowed = true;
5076     kvm_gsi_routing_allowed = true;
5077 
5078     if (kvm_irqchip_is_split()) {
5079         KVMRouteChange c = kvm_irqchip_begin_route_changes(s);
5080         int i;
5081 
5082         /* If the ioapic is in QEMU and the lapics are in KVM, reserve
5083            MSI routes for signaling interrupts to the local apics. */
5084         for (i = 0; i < IOAPIC_NUM_PINS; i++) {
5085             if (kvm_irqchip_add_msi_route(&c, 0, NULL) < 0) {
5086                 error_report("Could not enable split IRQ mode.");
5087                 exit(1);
5088             }
5089         }
5090         kvm_irqchip_commit_route_changes(&c);
5091     }
5092 }
5093 
5094 int kvm_arch_irqchip_create(KVMState *s)
5095 {
5096     int ret;
5097     if (kvm_kernel_irqchip_split()) {
5098         ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
5099         if (ret) {
5100             error_report("Could not enable split irqchip mode: %s",
5101                          strerror(-ret));
5102             exit(1);
5103         } else {
5104             DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
5105             kvm_split_irqchip = true;
5106             return 1;
5107         }
5108     } else {
5109         return 0;
5110     }
5111 }
5112 
5113 uint64_t kvm_swizzle_msi_ext_dest_id(uint64_t address)
5114 {
5115     CPUX86State *env;
5116     uint64_t ext_id;
5117 
5118     if (!first_cpu) {
5119         return address;
5120     }
5121     env = &X86_CPU(first_cpu)->env;
5122     if (!(env->features[FEAT_KVM] & (1 << KVM_FEATURE_MSI_EXT_DEST_ID))) {
5123         return address;
5124     }
5125 
5126     /*
5127      * If the remappable format bit is set, or the upper bits are
5128      * already set in address_hi, or the low extended bits aren't
5129      * there anyway, do nothing.
5130      */
5131     ext_id = address & (0xff << MSI_ADDR_DEST_IDX_SHIFT);
5132     if (!ext_id || (ext_id & (1 << MSI_ADDR_DEST_IDX_SHIFT)) || (address >> 32)) {
5133         return address;
5134     }
5135 
5136     address &= ~ext_id;
5137     address |= ext_id << 35;
5138     return address;
5139 }
5140 
5141 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
5142                              uint64_t address, uint32_t data, PCIDevice *dev)
5143 {
5144     X86IOMMUState *iommu = x86_iommu_get_default();
5145 
5146     if (iommu) {
5147         X86IOMMUClass *class = X86_IOMMU_DEVICE_GET_CLASS(iommu);
5148 
5149         if (class->int_remap) {
5150             int ret;
5151             MSIMessage src, dst;
5152 
5153             src.address = route->u.msi.address_hi;
5154             src.address <<= VTD_MSI_ADDR_HI_SHIFT;
5155             src.address |= route->u.msi.address_lo;
5156             src.data = route->u.msi.data;
5157 
5158             ret = class->int_remap(iommu, &src, &dst, dev ?     \
5159                                    pci_requester_id(dev) :      \
5160                                    X86_IOMMU_SID_INVALID);
5161             if (ret) {
5162                 trace_kvm_x86_fixup_msi_error(route->gsi);
5163                 return 1;
5164             }
5165 
5166             /*
5167              * Handled untranslated compatibilty format interrupt with
5168              * extended destination ID in the low bits 11-5. */
5169             dst.address = kvm_swizzle_msi_ext_dest_id(dst.address);
5170 
5171             route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
5172             route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
5173             route->u.msi.data = dst.data;
5174             return 0;
5175         }
5176     }
5177 
5178     address = kvm_swizzle_msi_ext_dest_id(address);
5179     route->u.msi.address_hi = address >> VTD_MSI_ADDR_HI_SHIFT;
5180     route->u.msi.address_lo = address & VTD_MSI_ADDR_LO_MASK;
5181     return 0;
5182 }
5183 
5184 typedef struct MSIRouteEntry MSIRouteEntry;
5185 
5186 struct MSIRouteEntry {
5187     PCIDevice *dev;             /* Device pointer */
5188     int vector;                 /* MSI/MSIX vector index */
5189     int virq;                   /* Virtual IRQ index */
5190     QLIST_ENTRY(MSIRouteEntry) list;
5191 };
5192 
5193 /* List of used GSI routes */
5194 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
5195     QLIST_HEAD_INITIALIZER(msi_route_list);
5196 
5197 static void kvm_update_msi_routes_all(void *private, bool global,
5198                                       uint32_t index, uint32_t mask)
5199 {
5200     int cnt = 0, vector;
5201     MSIRouteEntry *entry;
5202     MSIMessage msg;
5203     PCIDevice *dev;
5204 
5205     /* TODO: explicit route update */
5206     QLIST_FOREACH(entry, &msi_route_list, list) {
5207         cnt++;
5208         vector = entry->vector;
5209         dev = entry->dev;
5210         if (msix_enabled(dev) && !msix_is_masked(dev, vector)) {
5211             msg = msix_get_message(dev, vector);
5212         } else if (msi_enabled(dev) && !msi_is_masked(dev, vector)) {
5213             msg = msi_get_message(dev, vector);
5214         } else {
5215             /*
5216              * Either MSI/MSIX is disabled for the device, or the
5217              * specific message was masked out.  Skip this one.
5218              */
5219             continue;
5220         }
5221         kvm_irqchip_update_msi_route(kvm_state, entry->virq, msg, dev);
5222     }
5223     kvm_irqchip_commit_routes(kvm_state);
5224     trace_kvm_x86_update_msi_routes(cnt);
5225 }
5226 
5227 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
5228                                 int vector, PCIDevice *dev)
5229 {
5230     static bool notify_list_inited = false;
5231     MSIRouteEntry *entry;
5232 
5233     if (!dev) {
5234         /* These are (possibly) IOAPIC routes only used for split
5235          * kernel irqchip mode, while what we are housekeeping are
5236          * PCI devices only. */
5237         return 0;
5238     }
5239 
5240     entry = g_new0(MSIRouteEntry, 1);
5241     entry->dev = dev;
5242     entry->vector = vector;
5243     entry->virq = route->gsi;
5244     QLIST_INSERT_HEAD(&msi_route_list, entry, list);
5245 
5246     trace_kvm_x86_add_msi_route(route->gsi);
5247 
5248     if (!notify_list_inited) {
5249         /* For the first time we do add route, add ourselves into
5250          * IOMMU's IEC notify list if needed. */
5251         X86IOMMUState *iommu = x86_iommu_get_default();
5252         if (iommu) {
5253             x86_iommu_iec_register_notifier(iommu,
5254                                             kvm_update_msi_routes_all,
5255                                             NULL);
5256         }
5257         notify_list_inited = true;
5258     }
5259     return 0;
5260 }
5261 
5262 int kvm_arch_release_virq_post(int virq)
5263 {
5264     MSIRouteEntry *entry, *next;
5265     QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
5266         if (entry->virq == virq) {
5267             trace_kvm_x86_remove_msi_route(virq);
5268             QLIST_REMOVE(entry, list);
5269             g_free(entry);
5270             break;
5271         }
5272     }
5273     return 0;
5274 }
5275 
5276 int kvm_arch_msi_data_to_gsi(uint32_t data)
5277 {
5278     abort();
5279 }
5280 
5281 bool kvm_has_waitpkg(void)
5282 {
5283     return has_msr_umwait;
5284 }
5285 
5286 bool kvm_arch_cpu_check_are_resettable(void)
5287 {
5288     return !sev_es_enabled();
5289 }
5290 
5291 #define ARCH_REQ_XCOMP_GUEST_PERM       0x1025
5292 
5293 void kvm_request_xsave_components(X86CPU *cpu, uint64_t mask)
5294 {
5295     KVMState *s = kvm_state;
5296     uint64_t supported;
5297 
5298     mask &= XSTATE_DYNAMIC_MASK;
5299     if (!mask) {
5300         return;
5301     }
5302     /*
5303      * Just ignore bits that are not in CPUID[EAX=0xD,ECX=0].
5304      * ARCH_REQ_XCOMP_GUEST_PERM would fail, and QEMU has warned
5305      * about them already because they are not supported features.
5306      */
5307     supported = kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EAX);
5308     supported |= (uint64_t)kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EDX) << 32;
5309     mask &= supported;
5310 
5311     while (mask) {
5312         int bit = ctz64(mask);
5313         int rc = syscall(SYS_arch_prctl, ARCH_REQ_XCOMP_GUEST_PERM, bit);
5314         if (rc) {
5315             /*
5316              * Older kernel version (<5.17) do not support
5317              * ARCH_REQ_XCOMP_GUEST_PERM, but also do not return
5318              * any dynamic feature from kvm_arch_get_supported_cpuid.
5319              */
5320             warn_report("prctl(ARCH_REQ_XCOMP_GUEST_PERM) failure "
5321                         "for feature bit %d", bit);
5322         }
5323         mask &= ~BIT_ULL(bit);
5324     }
5325 }
5326