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