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