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