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