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