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