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