xref: /openbmc/qemu/target/i386/kvm/kvm.c (revision 5f88dd43)
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 bool 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_get_default_type(MachineState *ms)
2560 {
2561     return 0;
2562 }
2563 
2564 int kvm_arch_init(MachineState *ms, KVMState *s)
2565 {
2566     uint64_t identity_base = 0xfffbc000;
2567     uint64_t shadow_mem;
2568     int ret;
2569     struct utsname utsname;
2570     Error *local_err = NULL;
2571 
2572     /*
2573      * Initialize SEV context, if required
2574      *
2575      * If no memory encryption is requested (ms->cgs == NULL) this is
2576      * a no-op.
2577      *
2578      * It's also a no-op if a non-SEV confidential guest support
2579      * mechanism is selected.  SEV is the only mechanism available to
2580      * select on x86 at present, so this doesn't arise, but if new
2581      * mechanisms are supported in future (e.g. TDX), they'll need
2582      * their own initialization either here or elsewhere.
2583      */
2584     ret = sev_kvm_init(ms->cgs, &local_err);
2585     if (ret < 0) {
2586         error_report_err(local_err);
2587         return ret;
2588     }
2589 
2590     if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
2591         error_report("kvm: KVM_CAP_IRQ_ROUTING not supported by KVM");
2592         return -ENOTSUP;
2593     }
2594 
2595     has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
2596     has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
2597     has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
2598     has_sregs2 = kvm_check_extension(s, KVM_CAP_SREGS2) > 0;
2599 
2600     hv_vpindex_settable = kvm_check_extension(s, KVM_CAP_HYPERV_VP_INDEX);
2601 
2602     has_exception_payload = kvm_check_extension(s, KVM_CAP_EXCEPTION_PAYLOAD);
2603     if (has_exception_payload) {
2604         ret = kvm_vm_enable_cap(s, KVM_CAP_EXCEPTION_PAYLOAD, 0, true);
2605         if (ret < 0) {
2606             error_report("kvm: Failed to enable exception payload cap: %s",
2607                          strerror(-ret));
2608             return ret;
2609         }
2610     }
2611 
2612     has_triple_fault_event = kvm_check_extension(s, KVM_CAP_X86_TRIPLE_FAULT_EVENT);
2613     if (has_triple_fault_event) {
2614         ret = kvm_vm_enable_cap(s, KVM_CAP_X86_TRIPLE_FAULT_EVENT, 0, true);
2615         if (ret < 0) {
2616             error_report("kvm: Failed to enable triple fault event cap: %s",
2617                          strerror(-ret));
2618             return ret;
2619         }
2620     }
2621 
2622     if (s->xen_version) {
2623 #ifdef CONFIG_XEN_EMU
2624         if (!object_dynamic_cast(OBJECT(ms), TYPE_PC_MACHINE)) {
2625             error_report("kvm: Xen support only available in PC machine");
2626             return -ENOTSUP;
2627         }
2628         /* hyperv_enabled() doesn't work yet. */
2629         uint32_t msr = XEN_HYPERCALL_MSR;
2630         ret = kvm_xen_init(s, msr);
2631         if (ret < 0) {
2632             return ret;
2633         }
2634 #else
2635         error_report("kvm: Xen support not enabled in qemu");
2636         return -ENOTSUP;
2637 #endif
2638     }
2639 
2640     ret = kvm_get_supported_msrs(s);
2641     if (ret < 0) {
2642         return ret;
2643     }
2644 
2645     kvm_get_supported_feature_msrs(s);
2646 
2647     uname(&utsname);
2648     lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
2649 
2650     /*
2651      * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
2652      * In order to use vm86 mode, an EPT identity map and a TSS  are needed.
2653      * Since these must be part of guest physical memory, we need to allocate
2654      * them, both by setting their start addresses in the kernel and by
2655      * creating a corresponding e820 entry. We need 4 pages before the BIOS.
2656      *
2657      * Older KVM versions may not support setting the identity map base. In
2658      * that case we need to stick with the default, i.e. a 256K maximum BIOS
2659      * size.
2660      */
2661     if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
2662         /* Allows up to 16M BIOSes. */
2663         identity_base = 0xfeffc000;
2664 
2665         ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
2666         if (ret < 0) {
2667             return ret;
2668         }
2669     }
2670 
2671     /* Set TSS base one page after EPT identity map. */
2672     ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
2673     if (ret < 0) {
2674         return ret;
2675     }
2676 
2677     /* Tell fw_cfg to notify the BIOS to reserve the range. */
2678     ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
2679     if (ret < 0) {
2680         fprintf(stderr, "e820_add_entry() table is full\n");
2681         return ret;
2682     }
2683 
2684     shadow_mem = object_property_get_int(OBJECT(s), "kvm-shadow-mem", &error_abort);
2685     if (shadow_mem != -1) {
2686         shadow_mem /= 4096;
2687         ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
2688         if (ret < 0) {
2689             return ret;
2690         }
2691     }
2692 
2693     if (kvm_check_extension(s, KVM_CAP_X86_SMM) &&
2694         object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE) &&
2695         x86_machine_is_smm_enabled(X86_MACHINE(ms))) {
2696         smram_machine_done.notify = register_smram_listener;
2697         qemu_add_machine_init_done_notifier(&smram_machine_done);
2698     }
2699 
2700     if (enable_cpu_pm) {
2701         int disable_exits = kvm_check_extension(s, KVM_CAP_X86_DISABLE_EXITS);
2702         int ret;
2703 
2704 /* Work around for kernel header with a typo. TODO: fix header and drop. */
2705 #if defined(KVM_X86_DISABLE_EXITS_HTL) && !defined(KVM_X86_DISABLE_EXITS_HLT)
2706 #define KVM_X86_DISABLE_EXITS_HLT KVM_X86_DISABLE_EXITS_HTL
2707 #endif
2708         if (disable_exits) {
2709             disable_exits &= (KVM_X86_DISABLE_EXITS_MWAIT |
2710                               KVM_X86_DISABLE_EXITS_HLT |
2711                               KVM_X86_DISABLE_EXITS_PAUSE |
2712                               KVM_X86_DISABLE_EXITS_CSTATE);
2713         }
2714 
2715         ret = kvm_vm_enable_cap(s, KVM_CAP_X86_DISABLE_EXITS, 0,
2716                                 disable_exits);
2717         if (ret < 0) {
2718             error_report("kvm: guest stopping CPU not supported: %s",
2719                          strerror(-ret));
2720         }
2721     }
2722 
2723     if (object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE)) {
2724         X86MachineState *x86ms = X86_MACHINE(ms);
2725 
2726         if (x86ms->bus_lock_ratelimit > 0) {
2727             ret = kvm_check_extension(s, KVM_CAP_X86_BUS_LOCK_EXIT);
2728             if (!(ret & KVM_BUS_LOCK_DETECTION_EXIT)) {
2729                 error_report("kvm: bus lock detection unsupported");
2730                 return -ENOTSUP;
2731             }
2732             ret = kvm_vm_enable_cap(s, KVM_CAP_X86_BUS_LOCK_EXIT, 0,
2733                                     KVM_BUS_LOCK_DETECTION_EXIT);
2734             if (ret < 0) {
2735                 error_report("kvm: Failed to enable bus lock detection cap: %s",
2736                              strerror(-ret));
2737                 return ret;
2738             }
2739             ratelimit_init(&bus_lock_ratelimit_ctrl);
2740             ratelimit_set_speed(&bus_lock_ratelimit_ctrl,
2741                                 x86ms->bus_lock_ratelimit, BUS_LOCK_SLICE_TIME);
2742         }
2743     }
2744 
2745     if (s->notify_vmexit != NOTIFY_VMEXIT_OPTION_DISABLE &&
2746         kvm_check_extension(s, KVM_CAP_X86_NOTIFY_VMEXIT)) {
2747             uint64_t notify_window_flags =
2748                 ((uint64_t)s->notify_window << 32) |
2749                 KVM_X86_NOTIFY_VMEXIT_ENABLED |
2750                 KVM_X86_NOTIFY_VMEXIT_USER;
2751             ret = kvm_vm_enable_cap(s, KVM_CAP_X86_NOTIFY_VMEXIT, 0,
2752                                     notify_window_flags);
2753             if (ret < 0) {
2754                 error_report("kvm: Failed to enable notify vmexit cap: %s",
2755                              strerror(-ret));
2756                 return ret;
2757             }
2758     }
2759     if (kvm_vm_check_extension(s, KVM_CAP_X86_USER_SPACE_MSR)) {
2760         bool r;
2761 
2762         ret = kvm_vm_enable_cap(s, KVM_CAP_X86_USER_SPACE_MSR, 0,
2763                                 KVM_MSR_EXIT_REASON_FILTER);
2764         if (ret) {
2765             error_report("Could not enable user space MSRs: %s",
2766                          strerror(-ret));
2767             exit(1);
2768         }
2769 
2770         r = kvm_filter_msr(s, MSR_CORE_THREAD_COUNT,
2771                            kvm_rdmsr_core_thread_count, NULL);
2772         if (!r) {
2773             error_report("Could not install MSR_CORE_THREAD_COUNT handler: %s",
2774                          strerror(-ret));
2775             exit(1);
2776         }
2777     }
2778 
2779     return 0;
2780 }
2781 
2782 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2783 {
2784     lhs->selector = rhs->selector;
2785     lhs->base = rhs->base;
2786     lhs->limit = rhs->limit;
2787     lhs->type = 3;
2788     lhs->present = 1;
2789     lhs->dpl = 3;
2790     lhs->db = 0;
2791     lhs->s = 1;
2792     lhs->l = 0;
2793     lhs->g = 0;
2794     lhs->avl = 0;
2795     lhs->unusable = 0;
2796 }
2797 
2798 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2799 {
2800     unsigned flags = rhs->flags;
2801     lhs->selector = rhs->selector;
2802     lhs->base = rhs->base;
2803     lhs->limit = rhs->limit;
2804     lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
2805     lhs->present = (flags & DESC_P_MASK) != 0;
2806     lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
2807     lhs->db = (flags >> DESC_B_SHIFT) & 1;
2808     lhs->s = (flags & DESC_S_MASK) != 0;
2809     lhs->l = (flags >> DESC_L_SHIFT) & 1;
2810     lhs->g = (flags & DESC_G_MASK) != 0;
2811     lhs->avl = (flags & DESC_AVL_MASK) != 0;
2812     lhs->unusable = !lhs->present;
2813     lhs->padding = 0;
2814 }
2815 
2816 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
2817 {
2818     lhs->selector = rhs->selector;
2819     lhs->base = rhs->base;
2820     lhs->limit = rhs->limit;
2821     lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
2822                  ((rhs->present && !rhs->unusable) * DESC_P_MASK) |
2823                  (rhs->dpl << DESC_DPL_SHIFT) |
2824                  (rhs->db << DESC_B_SHIFT) |
2825                  (rhs->s * DESC_S_MASK) |
2826                  (rhs->l << DESC_L_SHIFT) |
2827                  (rhs->g * DESC_G_MASK) |
2828                  (rhs->avl * DESC_AVL_MASK);
2829 }
2830 
2831 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
2832 {
2833     if (set) {
2834         *kvm_reg = *qemu_reg;
2835     } else {
2836         *qemu_reg = *kvm_reg;
2837     }
2838 }
2839 
2840 static int kvm_getput_regs(X86CPU *cpu, int set)
2841 {
2842     CPUX86State *env = &cpu->env;
2843     struct kvm_regs regs;
2844     int ret = 0;
2845 
2846     if (!set) {
2847         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
2848         if (ret < 0) {
2849             return ret;
2850         }
2851     }
2852 
2853     kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
2854     kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
2855     kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
2856     kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
2857     kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
2858     kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
2859     kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
2860     kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
2861 #ifdef TARGET_X86_64
2862     kvm_getput_reg(&regs.r8, &env->regs[8], set);
2863     kvm_getput_reg(&regs.r9, &env->regs[9], set);
2864     kvm_getput_reg(&regs.r10, &env->regs[10], set);
2865     kvm_getput_reg(&regs.r11, &env->regs[11], set);
2866     kvm_getput_reg(&regs.r12, &env->regs[12], set);
2867     kvm_getput_reg(&regs.r13, &env->regs[13], set);
2868     kvm_getput_reg(&regs.r14, &env->regs[14], set);
2869     kvm_getput_reg(&regs.r15, &env->regs[15], set);
2870 #endif
2871 
2872     kvm_getput_reg(&regs.rflags, &env->eflags, set);
2873     kvm_getput_reg(&regs.rip, &env->eip, set);
2874 
2875     if (set) {
2876         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
2877     }
2878 
2879     return ret;
2880 }
2881 
2882 static int kvm_put_fpu(X86CPU *cpu)
2883 {
2884     CPUX86State *env = &cpu->env;
2885     struct kvm_fpu fpu;
2886     int i;
2887 
2888     memset(&fpu, 0, sizeof fpu);
2889     fpu.fsw = env->fpus & ~(7 << 11);
2890     fpu.fsw |= (env->fpstt & 7) << 11;
2891     fpu.fcw = env->fpuc;
2892     fpu.last_opcode = env->fpop;
2893     fpu.last_ip = env->fpip;
2894     fpu.last_dp = env->fpdp;
2895     for (i = 0; i < 8; ++i) {
2896         fpu.ftwx |= (!env->fptags[i]) << i;
2897     }
2898     memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
2899     for (i = 0; i < CPU_NB_REGS; i++) {
2900         stq_p(&fpu.xmm[i][0], env->xmm_regs[i].ZMM_Q(0));
2901         stq_p(&fpu.xmm[i][8], env->xmm_regs[i].ZMM_Q(1));
2902     }
2903     fpu.mxcsr = env->mxcsr;
2904 
2905     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
2906 }
2907 
2908 static int kvm_put_xsave(X86CPU *cpu)
2909 {
2910     CPUX86State *env = &cpu->env;
2911     void *xsave = env->xsave_buf;
2912 
2913     if (!has_xsave) {
2914         return kvm_put_fpu(cpu);
2915     }
2916     x86_cpu_xsave_all_areas(cpu, xsave, env->xsave_buf_len);
2917 
2918     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
2919 }
2920 
2921 static int kvm_put_xcrs(X86CPU *cpu)
2922 {
2923     CPUX86State *env = &cpu->env;
2924     struct kvm_xcrs xcrs = {};
2925 
2926     if (!has_xcrs) {
2927         return 0;
2928     }
2929 
2930     xcrs.nr_xcrs = 1;
2931     xcrs.flags = 0;
2932     xcrs.xcrs[0].xcr = 0;
2933     xcrs.xcrs[0].value = env->xcr0;
2934     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
2935 }
2936 
2937 static int kvm_put_sregs(X86CPU *cpu)
2938 {
2939     CPUX86State *env = &cpu->env;
2940     struct kvm_sregs sregs;
2941 
2942     /*
2943      * The interrupt_bitmap is ignored because KVM_SET_SREGS is
2944      * always followed by KVM_SET_VCPU_EVENTS.
2945      */
2946     memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
2947 
2948     if ((env->eflags & VM_MASK)) {
2949         set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
2950         set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
2951         set_v8086_seg(&sregs.es, &env->segs[R_ES]);
2952         set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
2953         set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
2954         set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
2955     } else {
2956         set_seg(&sregs.cs, &env->segs[R_CS]);
2957         set_seg(&sregs.ds, &env->segs[R_DS]);
2958         set_seg(&sregs.es, &env->segs[R_ES]);
2959         set_seg(&sregs.fs, &env->segs[R_FS]);
2960         set_seg(&sregs.gs, &env->segs[R_GS]);
2961         set_seg(&sregs.ss, &env->segs[R_SS]);
2962     }
2963 
2964     set_seg(&sregs.tr, &env->tr);
2965     set_seg(&sregs.ldt, &env->ldt);
2966 
2967     sregs.idt.limit = env->idt.limit;
2968     sregs.idt.base = env->idt.base;
2969     memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
2970     sregs.gdt.limit = env->gdt.limit;
2971     sregs.gdt.base = env->gdt.base;
2972     memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
2973 
2974     sregs.cr0 = env->cr[0];
2975     sregs.cr2 = env->cr[2];
2976     sregs.cr3 = env->cr[3];
2977     sregs.cr4 = env->cr[4];
2978 
2979     sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
2980     sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
2981 
2982     sregs.efer = env->efer;
2983 
2984     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
2985 }
2986 
2987 static int kvm_put_sregs2(X86CPU *cpu)
2988 {
2989     CPUX86State *env = &cpu->env;
2990     struct kvm_sregs2 sregs;
2991     int i;
2992 
2993     sregs.flags = 0;
2994 
2995     if ((env->eflags & VM_MASK)) {
2996         set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
2997         set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
2998         set_v8086_seg(&sregs.es, &env->segs[R_ES]);
2999         set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
3000         set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
3001         set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
3002     } else {
3003         set_seg(&sregs.cs, &env->segs[R_CS]);
3004         set_seg(&sregs.ds, &env->segs[R_DS]);
3005         set_seg(&sregs.es, &env->segs[R_ES]);
3006         set_seg(&sregs.fs, &env->segs[R_FS]);
3007         set_seg(&sregs.gs, &env->segs[R_GS]);
3008         set_seg(&sregs.ss, &env->segs[R_SS]);
3009     }
3010 
3011     set_seg(&sregs.tr, &env->tr);
3012     set_seg(&sregs.ldt, &env->ldt);
3013 
3014     sregs.idt.limit = env->idt.limit;
3015     sregs.idt.base = env->idt.base;
3016     memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
3017     sregs.gdt.limit = env->gdt.limit;
3018     sregs.gdt.base = env->gdt.base;
3019     memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
3020 
3021     sregs.cr0 = env->cr[0];
3022     sregs.cr2 = env->cr[2];
3023     sregs.cr3 = env->cr[3];
3024     sregs.cr4 = env->cr[4];
3025 
3026     sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
3027     sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
3028 
3029     sregs.efer = env->efer;
3030 
3031     if (env->pdptrs_valid) {
3032         for (i = 0; i < 4; i++) {
3033             sregs.pdptrs[i] = env->pdptrs[i];
3034         }
3035         sregs.flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
3036     }
3037 
3038     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS2, &sregs);
3039 }
3040 
3041 
3042 static void kvm_msr_buf_reset(X86CPU *cpu)
3043 {
3044     memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
3045 }
3046 
3047 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
3048 {
3049     struct kvm_msrs *msrs = cpu->kvm_msr_buf;
3050     void *limit = ((void *)msrs) + MSR_BUF_SIZE;
3051     struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
3052 
3053     assert((void *)(entry + 1) <= limit);
3054 
3055     entry->index = index;
3056     entry->reserved = 0;
3057     entry->data = value;
3058     msrs->nmsrs++;
3059 }
3060 
3061 static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
3062 {
3063     kvm_msr_buf_reset(cpu);
3064     kvm_msr_entry_add(cpu, index, value);
3065 
3066     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
3067 }
3068 
3069 static int kvm_get_one_msr(X86CPU *cpu, int index, uint64_t *value)
3070 {
3071     int ret;
3072     struct {
3073         struct kvm_msrs info;
3074         struct kvm_msr_entry entries[1];
3075     } msr_data = {
3076         .info.nmsrs = 1,
3077         .entries[0].index = index,
3078     };
3079 
3080     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
3081     if (ret < 0) {
3082         return ret;
3083     }
3084     assert(ret == 1);
3085     *value = msr_data.entries[0].data;
3086     return ret;
3087 }
3088 void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
3089 {
3090     int ret;
3091 
3092     ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
3093     assert(ret == 1);
3094 }
3095 
3096 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
3097 {
3098     CPUX86State *env = &cpu->env;
3099     int ret;
3100 
3101     if (!has_msr_tsc_deadline) {
3102         return 0;
3103     }
3104 
3105     ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
3106     if (ret < 0) {
3107         return ret;
3108     }
3109 
3110     assert(ret == 1);
3111     return 0;
3112 }
3113 
3114 /*
3115  * Provide a separate write service for the feature control MSR in order to
3116  * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
3117  * before writing any other state because forcibly leaving nested mode
3118  * invalidates the VCPU state.
3119  */
3120 static int kvm_put_msr_feature_control(X86CPU *cpu)
3121 {
3122     int ret;
3123 
3124     if (!has_msr_feature_control) {
3125         return 0;
3126     }
3127 
3128     ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
3129                           cpu->env.msr_ia32_feature_control);
3130     if (ret < 0) {
3131         return ret;
3132     }
3133 
3134     assert(ret == 1);
3135     return 0;
3136 }
3137 
3138 static uint64_t make_vmx_msr_value(uint32_t index, uint32_t features)
3139 {
3140     uint32_t default1, can_be_one, can_be_zero;
3141     uint32_t must_be_one;
3142 
3143     switch (index) {
3144     case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3145         default1 = 0x00000016;
3146         break;
3147     case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3148         default1 = 0x0401e172;
3149         break;
3150     case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3151         default1 = 0x000011ff;
3152         break;
3153     case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3154         default1 = 0x00036dff;
3155         break;
3156     case MSR_IA32_VMX_PROCBASED_CTLS2:
3157         default1 = 0;
3158         break;
3159     default:
3160         abort();
3161     }
3162 
3163     /* If a feature bit is set, the control can be either set or clear.
3164      * Otherwise the value is limited to either 0 or 1 by default1.
3165      */
3166     can_be_one = features | default1;
3167     can_be_zero = features | ~default1;
3168     must_be_one = ~can_be_zero;
3169 
3170     /*
3171      * Bit 0:31 -> 0 if the control bit can be zero (i.e. 1 if it must be one).
3172      * Bit 32:63 -> 1 if the control bit can be one.
3173      */
3174     return must_be_one | (((uint64_t)can_be_one) << 32);
3175 }
3176 
3177 static void kvm_msr_entry_add_vmx(X86CPU *cpu, FeatureWordArray f)
3178 {
3179     uint64_t kvm_vmx_basic =
3180         kvm_arch_get_supported_msr_feature(kvm_state,
3181                                            MSR_IA32_VMX_BASIC);
3182 
3183     if (!kvm_vmx_basic) {
3184         /* If the kernel doesn't support VMX feature (kvm_intel.nested=0),
3185          * then kvm_vmx_basic will be 0 and KVM_SET_MSR will fail.
3186          */
3187         return;
3188     }
3189 
3190     uint64_t kvm_vmx_misc =
3191         kvm_arch_get_supported_msr_feature(kvm_state,
3192                                            MSR_IA32_VMX_MISC);
3193     uint64_t kvm_vmx_ept_vpid =
3194         kvm_arch_get_supported_msr_feature(kvm_state,
3195                                            MSR_IA32_VMX_EPT_VPID_CAP);
3196 
3197     /*
3198      * If the guest is 64-bit, a value of 1 is allowed for the host address
3199      * space size vmexit control.
3200      */
3201     uint64_t fixed_vmx_exit = f[FEAT_8000_0001_EDX] & CPUID_EXT2_LM
3202         ? (uint64_t)VMX_VM_EXIT_HOST_ADDR_SPACE_SIZE << 32 : 0;
3203 
3204     /*
3205      * Bits 0-30, 32-44 and 50-53 come from the host.  KVM should
3206      * not change them for backwards compatibility.
3207      */
3208     uint64_t fixed_vmx_basic = kvm_vmx_basic &
3209         (MSR_VMX_BASIC_VMCS_REVISION_MASK |
3210          MSR_VMX_BASIC_VMXON_REGION_SIZE_MASK |
3211          MSR_VMX_BASIC_VMCS_MEM_TYPE_MASK);
3212 
3213     /*
3214      * Same for bits 0-4 and 25-27.  Bits 16-24 (CR3 target count) can
3215      * change in the future but are always zero for now, clear them to be
3216      * future proof.  Bits 32-63 in theory could change, though KVM does
3217      * not support dual-monitor treatment and probably never will; mask
3218      * them out as well.
3219      */
3220     uint64_t fixed_vmx_misc = kvm_vmx_misc &
3221         (MSR_VMX_MISC_PREEMPTION_TIMER_SHIFT_MASK |
3222          MSR_VMX_MISC_MAX_MSR_LIST_SIZE_MASK);
3223 
3224     /*
3225      * EPT memory types should not change either, so we do not bother
3226      * adding features for them.
3227      */
3228     uint64_t fixed_vmx_ept_mask =
3229             (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_ENABLE_EPT ?
3230              MSR_VMX_EPT_UC | MSR_VMX_EPT_WB : 0);
3231     uint64_t fixed_vmx_ept_vpid = kvm_vmx_ept_vpid & fixed_vmx_ept_mask;
3232 
3233     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
3234                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
3235                                          f[FEAT_VMX_PROCBASED_CTLS]));
3236     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PINBASED_CTLS,
3237                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_PINBASED_CTLS,
3238                                          f[FEAT_VMX_PINBASED_CTLS]));
3239     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_EXIT_CTLS,
3240                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_EXIT_CTLS,
3241                                          f[FEAT_VMX_EXIT_CTLS]) | fixed_vmx_exit);
3242     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_ENTRY_CTLS,
3243                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_ENTRY_CTLS,
3244                                          f[FEAT_VMX_ENTRY_CTLS]));
3245     kvm_msr_entry_add(cpu, MSR_IA32_VMX_PROCBASED_CTLS2,
3246                       make_vmx_msr_value(MSR_IA32_VMX_PROCBASED_CTLS2,
3247                                          f[FEAT_VMX_SECONDARY_CTLS]));
3248     kvm_msr_entry_add(cpu, MSR_IA32_VMX_EPT_VPID_CAP,
3249                       f[FEAT_VMX_EPT_VPID_CAPS] | fixed_vmx_ept_vpid);
3250     kvm_msr_entry_add(cpu, MSR_IA32_VMX_BASIC,
3251                       f[FEAT_VMX_BASIC] | fixed_vmx_basic);
3252     kvm_msr_entry_add(cpu, MSR_IA32_VMX_MISC,
3253                       f[FEAT_VMX_MISC] | fixed_vmx_misc);
3254     if (has_msr_vmx_vmfunc) {
3255         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMFUNC, f[FEAT_VMX_VMFUNC]);
3256     }
3257 
3258     /*
3259      * Just to be safe, write these with constant values.  The CRn_FIXED1
3260      * MSRs are generated by KVM based on the vCPU's CPUID.
3261      */
3262     kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR0_FIXED0,
3263                       CR0_PE_MASK | CR0_PG_MASK | CR0_NE_MASK);
3264     kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR4_FIXED0,
3265                       CR4_VMXE_MASK);
3266 
3267     if (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_TSC_SCALING) {
3268         /* TSC multiplier (0x2032).  */
3269         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x32);
3270     } else {
3271         /* Preemption timer (0x482E).  */
3272         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x2E);
3273     }
3274 }
3275 
3276 static void kvm_msr_entry_add_perf(X86CPU *cpu, FeatureWordArray f)
3277 {
3278     uint64_t kvm_perf_cap =
3279         kvm_arch_get_supported_msr_feature(kvm_state,
3280                                            MSR_IA32_PERF_CAPABILITIES);
3281 
3282     if (kvm_perf_cap) {
3283         kvm_msr_entry_add(cpu, MSR_IA32_PERF_CAPABILITIES,
3284                         kvm_perf_cap & f[FEAT_PERF_CAPABILITIES]);
3285     }
3286 }
3287 
3288 static int kvm_buf_set_msrs(X86CPU *cpu)
3289 {
3290     int ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
3291     if (ret < 0) {
3292         return ret;
3293     }
3294 
3295     if (ret < cpu->kvm_msr_buf->nmsrs) {
3296         struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
3297         error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,
3298                      (uint32_t)e->index, (uint64_t)e->data);
3299     }
3300 
3301     assert(ret == cpu->kvm_msr_buf->nmsrs);
3302     return 0;
3303 }
3304 
3305 static void kvm_init_msrs(X86CPU *cpu)
3306 {
3307     CPUX86State *env = &cpu->env;
3308 
3309     kvm_msr_buf_reset(cpu);
3310     if (has_msr_arch_capabs) {
3311         kvm_msr_entry_add(cpu, MSR_IA32_ARCH_CAPABILITIES,
3312                           env->features[FEAT_ARCH_CAPABILITIES]);
3313     }
3314 
3315     if (has_msr_core_capabs) {
3316         kvm_msr_entry_add(cpu, MSR_IA32_CORE_CAPABILITY,
3317                           env->features[FEAT_CORE_CAPABILITY]);
3318     }
3319 
3320     if (has_msr_perf_capabs && cpu->enable_pmu) {
3321         kvm_msr_entry_add_perf(cpu, env->features);
3322     }
3323 
3324     if (has_msr_ucode_rev) {
3325         kvm_msr_entry_add(cpu, MSR_IA32_UCODE_REV, cpu->ucode_rev);
3326     }
3327 
3328     /*
3329      * Older kernels do not include VMX MSRs in KVM_GET_MSR_INDEX_LIST, but
3330      * all kernels with MSR features should have them.
3331      */
3332     if (kvm_feature_msrs && cpu_has_vmx(env)) {
3333         kvm_msr_entry_add_vmx(cpu, env->features);
3334     }
3335 
3336     assert(kvm_buf_set_msrs(cpu) == 0);
3337 }
3338 
3339 static int kvm_put_msrs(X86CPU *cpu, int level)
3340 {
3341     CPUX86State *env = &cpu->env;
3342     int i;
3343 
3344     kvm_msr_buf_reset(cpu);
3345 
3346     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
3347     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
3348     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
3349     kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
3350     if (has_msr_star) {
3351         kvm_msr_entry_add(cpu, MSR_STAR, env->star);
3352     }
3353     if (has_msr_hsave_pa) {
3354         kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
3355     }
3356     if (has_msr_tsc_aux) {
3357         kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
3358     }
3359     if (has_msr_tsc_adjust) {
3360         kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
3361     }
3362     if (has_msr_misc_enable) {
3363         kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
3364                           env->msr_ia32_misc_enable);
3365     }
3366     if (has_msr_smbase) {
3367         kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
3368     }
3369     if (has_msr_smi_count) {
3370         kvm_msr_entry_add(cpu, MSR_SMI_COUNT, env->msr_smi_count);
3371     }
3372     if (has_msr_pkrs) {
3373         kvm_msr_entry_add(cpu, MSR_IA32_PKRS, env->pkrs);
3374     }
3375     if (has_msr_bndcfgs) {
3376         kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
3377     }
3378     if (has_msr_xss) {
3379         kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
3380     }
3381     if (has_msr_umwait) {
3382         kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, env->umwait);
3383     }
3384     if (has_msr_spec_ctrl) {
3385         kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, env->spec_ctrl);
3386     }
3387     if (has_tsc_scale_msr) {
3388         kvm_msr_entry_add(cpu, MSR_AMD64_TSC_RATIO, env->amd_tsc_scale_msr);
3389     }
3390 
3391     if (has_msr_tsx_ctrl) {
3392         kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, env->tsx_ctrl);
3393     }
3394     if (has_msr_virt_ssbd) {
3395         kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, env->virt_ssbd);
3396     }
3397 
3398 #ifdef TARGET_X86_64
3399     if (lm_capable_kernel) {
3400         kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
3401         kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
3402         kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
3403         kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
3404     }
3405 #endif
3406 
3407     /*
3408      * The following MSRs have side effects on the guest or are too heavy
3409      * for normal writeback. Limit them to reset or full state updates.
3410      */
3411     if (level >= KVM_PUT_RESET_STATE) {
3412         kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
3413         kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
3414         kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
3415         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
3416             kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, env->async_pf_int_msr);
3417         }
3418         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
3419             kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
3420         }
3421         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
3422             kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
3423         }
3424         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
3425             kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
3426         }
3427 
3428         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
3429             kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, env->poll_control_msr);
3430         }
3431 
3432         if (has_architectural_pmu_version > 0) {
3433             if (has_architectural_pmu_version > 1) {
3434                 /* Stop the counter.  */
3435                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
3436                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
3437             }
3438 
3439             /* Set the counter values.  */
3440             for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
3441                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
3442                                   env->msr_fixed_counters[i]);
3443             }
3444             for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
3445                 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
3446                                   env->msr_gp_counters[i]);
3447                 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
3448                                   env->msr_gp_evtsel[i]);
3449             }
3450             if (has_architectural_pmu_version > 1) {
3451                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
3452                                   env->msr_global_status);
3453                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
3454                                   env->msr_global_ovf_ctrl);
3455 
3456                 /* Now start the PMU.  */
3457                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
3458                                   env->msr_fixed_ctr_ctrl);
3459                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
3460                                   env->msr_global_ctrl);
3461             }
3462         }
3463         /*
3464          * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,
3465          * only sync them to KVM on the first cpu
3466          */
3467         if (current_cpu == first_cpu) {
3468             if (has_msr_hv_hypercall) {
3469                 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
3470                                   env->msr_hv_guest_os_id);
3471                 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
3472                                   env->msr_hv_hypercall);
3473             }
3474             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
3475                 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,
3476                                   env->msr_hv_tsc);
3477             }
3478             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
3479                 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL,
3480                                   env->msr_hv_reenlightenment_control);
3481                 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL,
3482                                   env->msr_hv_tsc_emulation_control);
3483                 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS,
3484                                   env->msr_hv_tsc_emulation_status);
3485             }
3486 #ifdef CONFIG_SYNDBG
3487             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNDBG) &&
3488                 has_msr_hv_syndbg_options) {
3489                 kvm_msr_entry_add(cpu, HV_X64_MSR_SYNDBG_OPTIONS,
3490                                   hyperv_syndbg_query_options());
3491             }
3492 #endif
3493         }
3494         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3495             kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
3496                               env->msr_hv_vapic);
3497         }
3498         if (has_msr_hv_crash) {
3499             int j;
3500 
3501             for (j = 0; j < HV_CRASH_PARAMS; j++)
3502                 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
3503                                   env->msr_hv_crash_params[j]);
3504 
3505             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);
3506         }
3507         if (has_msr_hv_runtime) {
3508             kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
3509         }
3510         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)
3511             && hv_vpindex_settable) {
3512             kvm_msr_entry_add(cpu, HV_X64_MSR_VP_INDEX,
3513                               hyperv_vp_index(CPU(cpu)));
3514         }
3515         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3516             int j;
3517 
3518             kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);
3519 
3520             kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
3521                               env->msr_hv_synic_control);
3522             kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
3523                               env->msr_hv_synic_evt_page);
3524             kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
3525                               env->msr_hv_synic_msg_page);
3526 
3527             for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
3528                 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
3529                                   env->msr_hv_synic_sint[j]);
3530             }
3531         }
3532         if (has_msr_hv_stimer) {
3533             int j;
3534 
3535             for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
3536                 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
3537                                 env->msr_hv_stimer_config[j]);
3538             }
3539 
3540             for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
3541                 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
3542                                 env->msr_hv_stimer_count[j]);
3543             }
3544         }
3545         if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3546             uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
3547 
3548             kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
3549             kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
3550             kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
3551             kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
3552             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
3553             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
3554             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
3555             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
3556             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
3557             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
3558             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
3559             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
3560             for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
3561                 /* The CPU GPs if we write to a bit above the physical limit of
3562                  * the host CPU (and KVM emulates that)
3563                  */
3564                 uint64_t mask = env->mtrr_var[i].mask;
3565                 mask &= phys_mask;
3566 
3567                 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
3568                                   env->mtrr_var[i].base);
3569                 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
3570             }
3571         }
3572         if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
3573             int addr_num = kvm_arch_get_supported_cpuid(kvm_state,
3574                                                     0x14, 1, R_EAX) & 0x7;
3575 
3576             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL,
3577                             env->msr_rtit_ctrl);
3578             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS,
3579                             env->msr_rtit_status);
3580             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE,
3581                             env->msr_rtit_output_base);
3582             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK,
3583                             env->msr_rtit_output_mask);
3584             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH,
3585                             env->msr_rtit_cr3_match);
3586             for (i = 0; i < addr_num; i++) {
3587                 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i,
3588                             env->msr_rtit_addrs[i]);
3589             }
3590         }
3591 
3592         if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_SGX_LC) {
3593             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH0,
3594                               env->msr_ia32_sgxlepubkeyhash[0]);
3595             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH1,
3596                               env->msr_ia32_sgxlepubkeyhash[1]);
3597             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH2,
3598                               env->msr_ia32_sgxlepubkeyhash[2]);
3599             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH3,
3600                               env->msr_ia32_sgxlepubkeyhash[3]);
3601         }
3602 
3603         if (env->features[FEAT_XSAVE] & CPUID_D_1_EAX_XFD) {
3604             kvm_msr_entry_add(cpu, MSR_IA32_XFD,
3605                               env->msr_xfd);
3606             kvm_msr_entry_add(cpu, MSR_IA32_XFD_ERR,
3607                               env->msr_xfd_err);
3608         }
3609 
3610         if (kvm_enabled() && cpu->enable_pmu &&
3611             (env->features[FEAT_7_0_EDX] & CPUID_7_0_EDX_ARCH_LBR)) {
3612             uint64_t depth;
3613             int i, ret;
3614 
3615             /*
3616              * Only migrate Arch LBR states when the host Arch LBR depth
3617              * equals that of source guest's, this is to avoid mismatch
3618              * of guest/host config for the msr hence avoid unexpected
3619              * misbehavior.
3620              */
3621             ret = kvm_get_one_msr(cpu, MSR_ARCH_LBR_DEPTH, &depth);
3622 
3623             if (ret == 1 && !!depth && depth == env->msr_lbr_depth) {
3624                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_CTL, env->msr_lbr_ctl);
3625                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_DEPTH, env->msr_lbr_depth);
3626 
3627                 for (i = 0; i < ARCH_LBR_NR_ENTRIES; i++) {
3628                     if (!env->lbr_records[i].from) {
3629                         continue;
3630                     }
3631                     kvm_msr_entry_add(cpu, MSR_ARCH_LBR_FROM_0 + i,
3632                                       env->lbr_records[i].from);
3633                     kvm_msr_entry_add(cpu, MSR_ARCH_LBR_TO_0 + i,
3634                                       env->lbr_records[i].to);
3635                     kvm_msr_entry_add(cpu, MSR_ARCH_LBR_INFO_0 + i,
3636                                       env->lbr_records[i].info);
3637                 }
3638             }
3639         }
3640 
3641         /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
3642          *       kvm_put_msr_feature_control. */
3643     }
3644 
3645     if (env->mcg_cap) {
3646         int i;
3647 
3648         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
3649         kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
3650         if (has_msr_mcg_ext_ctl) {
3651             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
3652         }
3653         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3654             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
3655         }
3656     }
3657 
3658     return kvm_buf_set_msrs(cpu);
3659 }
3660 
3661 
3662 static int kvm_get_fpu(X86CPU *cpu)
3663 {
3664     CPUX86State *env = &cpu->env;
3665     struct kvm_fpu fpu;
3666     int i, ret;
3667 
3668     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
3669     if (ret < 0) {
3670         return ret;
3671     }
3672 
3673     env->fpstt = (fpu.fsw >> 11) & 7;
3674     env->fpus = fpu.fsw;
3675     env->fpuc = fpu.fcw;
3676     env->fpop = fpu.last_opcode;
3677     env->fpip = fpu.last_ip;
3678     env->fpdp = fpu.last_dp;
3679     for (i = 0; i < 8; ++i) {
3680         env->fptags[i] = !((fpu.ftwx >> i) & 1);
3681     }
3682     memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
3683     for (i = 0; i < CPU_NB_REGS; i++) {
3684         env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
3685         env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
3686     }
3687     env->mxcsr = fpu.mxcsr;
3688 
3689     return 0;
3690 }
3691 
3692 static int kvm_get_xsave(X86CPU *cpu)
3693 {
3694     CPUX86State *env = &cpu->env;
3695     void *xsave = env->xsave_buf;
3696     int type, ret;
3697 
3698     if (!has_xsave) {
3699         return kvm_get_fpu(cpu);
3700     }
3701 
3702     type = has_xsave2 ? KVM_GET_XSAVE2 : KVM_GET_XSAVE;
3703     ret = kvm_vcpu_ioctl(CPU(cpu), type, xsave);
3704     if (ret < 0) {
3705         return ret;
3706     }
3707     x86_cpu_xrstor_all_areas(cpu, xsave, env->xsave_buf_len);
3708 
3709     return 0;
3710 }
3711 
3712 static int kvm_get_xcrs(X86CPU *cpu)
3713 {
3714     CPUX86State *env = &cpu->env;
3715     int i, ret;
3716     struct kvm_xcrs xcrs;
3717 
3718     if (!has_xcrs) {
3719         return 0;
3720     }
3721 
3722     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
3723     if (ret < 0) {
3724         return ret;
3725     }
3726 
3727     for (i = 0; i < xcrs.nr_xcrs; i++) {
3728         /* Only support xcr0 now */
3729         if (xcrs.xcrs[i].xcr == 0) {
3730             env->xcr0 = xcrs.xcrs[i].value;
3731             break;
3732         }
3733     }
3734     return 0;
3735 }
3736 
3737 static int kvm_get_sregs(X86CPU *cpu)
3738 {
3739     CPUX86State *env = &cpu->env;
3740     struct kvm_sregs sregs;
3741     int ret;
3742 
3743     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
3744     if (ret < 0) {
3745         return ret;
3746     }
3747 
3748     /*
3749      * The interrupt_bitmap is ignored because KVM_GET_SREGS is
3750      * always preceded by KVM_GET_VCPU_EVENTS.
3751      */
3752 
3753     get_seg(&env->segs[R_CS], &sregs.cs);
3754     get_seg(&env->segs[R_DS], &sregs.ds);
3755     get_seg(&env->segs[R_ES], &sregs.es);
3756     get_seg(&env->segs[R_FS], &sregs.fs);
3757     get_seg(&env->segs[R_GS], &sregs.gs);
3758     get_seg(&env->segs[R_SS], &sregs.ss);
3759 
3760     get_seg(&env->tr, &sregs.tr);
3761     get_seg(&env->ldt, &sregs.ldt);
3762 
3763     env->idt.limit = sregs.idt.limit;
3764     env->idt.base = sregs.idt.base;
3765     env->gdt.limit = sregs.gdt.limit;
3766     env->gdt.base = sregs.gdt.base;
3767 
3768     env->cr[0] = sregs.cr0;
3769     env->cr[2] = sregs.cr2;
3770     env->cr[3] = sregs.cr3;
3771     env->cr[4] = sregs.cr4;
3772 
3773     env->efer = sregs.efer;
3774 
3775     /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
3776     x86_update_hflags(env);
3777 
3778     return 0;
3779 }
3780 
3781 static int kvm_get_sregs2(X86CPU *cpu)
3782 {
3783     CPUX86State *env = &cpu->env;
3784     struct kvm_sregs2 sregs;
3785     int i, ret;
3786 
3787     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS2, &sregs);
3788     if (ret < 0) {
3789         return ret;
3790     }
3791 
3792     get_seg(&env->segs[R_CS], &sregs.cs);
3793     get_seg(&env->segs[R_DS], &sregs.ds);
3794     get_seg(&env->segs[R_ES], &sregs.es);
3795     get_seg(&env->segs[R_FS], &sregs.fs);
3796     get_seg(&env->segs[R_GS], &sregs.gs);
3797     get_seg(&env->segs[R_SS], &sregs.ss);
3798 
3799     get_seg(&env->tr, &sregs.tr);
3800     get_seg(&env->ldt, &sregs.ldt);
3801 
3802     env->idt.limit = sregs.idt.limit;
3803     env->idt.base = sregs.idt.base;
3804     env->gdt.limit = sregs.gdt.limit;
3805     env->gdt.base = sregs.gdt.base;
3806 
3807     env->cr[0] = sregs.cr0;
3808     env->cr[2] = sregs.cr2;
3809     env->cr[3] = sregs.cr3;
3810     env->cr[4] = sregs.cr4;
3811 
3812     env->efer = sregs.efer;
3813 
3814     env->pdptrs_valid = sregs.flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
3815 
3816     if (env->pdptrs_valid) {
3817         for (i = 0; i < 4; i++) {
3818             env->pdptrs[i] = sregs.pdptrs[i];
3819         }
3820     }
3821 
3822     /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
3823     x86_update_hflags(env);
3824 
3825     return 0;
3826 }
3827 
3828 static int kvm_get_msrs(X86CPU *cpu)
3829 {
3830     CPUX86State *env = &cpu->env;
3831     struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
3832     int ret, i;
3833     uint64_t mtrr_top_bits;
3834 
3835     kvm_msr_buf_reset(cpu);
3836 
3837     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
3838     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
3839     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
3840     kvm_msr_entry_add(cpu, MSR_PAT, 0);
3841     if (has_msr_star) {
3842         kvm_msr_entry_add(cpu, MSR_STAR, 0);
3843     }
3844     if (has_msr_hsave_pa) {
3845         kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
3846     }
3847     if (has_msr_tsc_aux) {
3848         kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
3849     }
3850     if (has_msr_tsc_adjust) {
3851         kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
3852     }
3853     if (has_msr_tsc_deadline) {
3854         kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
3855     }
3856     if (has_msr_misc_enable) {
3857         kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
3858     }
3859     if (has_msr_smbase) {
3860         kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
3861     }
3862     if (has_msr_smi_count) {
3863         kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
3864     }
3865     if (has_msr_feature_control) {
3866         kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
3867     }
3868     if (has_msr_pkrs) {
3869         kvm_msr_entry_add(cpu, MSR_IA32_PKRS, 0);
3870     }
3871     if (has_msr_bndcfgs) {
3872         kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
3873     }
3874     if (has_msr_xss) {
3875         kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
3876     }
3877     if (has_msr_umwait) {
3878         kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, 0);
3879     }
3880     if (has_msr_spec_ctrl) {
3881         kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
3882     }
3883     if (has_tsc_scale_msr) {
3884         kvm_msr_entry_add(cpu, MSR_AMD64_TSC_RATIO, 0);
3885     }
3886 
3887     if (has_msr_tsx_ctrl) {
3888         kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, 0);
3889     }
3890     if (has_msr_virt_ssbd) {
3891         kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, 0);
3892     }
3893     if (!env->tsc_valid) {
3894         kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
3895         env->tsc_valid = !runstate_is_running();
3896     }
3897 
3898 #ifdef TARGET_X86_64
3899     if (lm_capable_kernel) {
3900         kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
3901         kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
3902         kvm_msr_entry_add(cpu, MSR_FMASK, 0);
3903         kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
3904     }
3905 #endif
3906     kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
3907     kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
3908     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
3909         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, 0);
3910     }
3911     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
3912         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
3913     }
3914     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
3915         kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
3916     }
3917     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
3918         kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
3919     }
3920     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
3921         kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, 1);
3922     }
3923     if (has_architectural_pmu_version > 0) {
3924         if (has_architectural_pmu_version > 1) {
3925             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
3926             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
3927             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
3928             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
3929         }
3930         for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
3931             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
3932         }
3933         for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
3934             kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
3935             kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
3936         }
3937     }
3938 
3939     if (env->mcg_cap) {
3940         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
3941         kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
3942         if (has_msr_mcg_ext_ctl) {
3943             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
3944         }
3945         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3946             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
3947         }
3948     }
3949 
3950     if (has_msr_hv_hypercall) {
3951         kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
3952         kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
3953     }
3954     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3955         kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
3956     }
3957     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
3958         kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
3959     }
3960     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
3961         kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL, 0);
3962         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL, 0);
3963         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS, 0);
3964     }
3965     if (has_msr_hv_syndbg_options) {
3966         kvm_msr_entry_add(cpu, HV_X64_MSR_SYNDBG_OPTIONS, 0);
3967     }
3968     if (has_msr_hv_crash) {
3969         int j;
3970 
3971         for (j = 0; j < HV_CRASH_PARAMS; j++) {
3972             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
3973         }
3974     }
3975     if (has_msr_hv_runtime) {
3976         kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
3977     }
3978     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3979         uint32_t msr;
3980 
3981         kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
3982         kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
3983         kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
3984         for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
3985             kvm_msr_entry_add(cpu, msr, 0);
3986         }
3987     }
3988     if (has_msr_hv_stimer) {
3989         uint32_t msr;
3990 
3991         for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
3992              msr++) {
3993             kvm_msr_entry_add(cpu, msr, 0);
3994         }
3995     }
3996     if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3997         kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
3998         kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
3999         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
4000         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
4001         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
4002         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
4003         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
4004         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
4005         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
4006         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
4007         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
4008         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
4009         for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
4010             kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
4011             kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
4012         }
4013     }
4014 
4015     if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
4016         int addr_num =
4017             kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
4018 
4019         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
4020         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
4021         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
4022         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
4023         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
4024         for (i = 0; i < addr_num; i++) {
4025             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
4026         }
4027     }
4028 
4029     if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_SGX_LC) {
4030         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH0, 0);
4031         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH1, 0);
4032         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH2, 0);
4033         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH3, 0);
4034     }
4035 
4036     if (env->features[FEAT_XSAVE] & CPUID_D_1_EAX_XFD) {
4037         kvm_msr_entry_add(cpu, MSR_IA32_XFD, 0);
4038         kvm_msr_entry_add(cpu, MSR_IA32_XFD_ERR, 0);
4039     }
4040 
4041     if (kvm_enabled() && cpu->enable_pmu &&
4042         (env->features[FEAT_7_0_EDX] & CPUID_7_0_EDX_ARCH_LBR)) {
4043         uint64_t depth;
4044         int i, ret;
4045 
4046         ret = kvm_get_one_msr(cpu, MSR_ARCH_LBR_DEPTH, &depth);
4047         if (ret == 1 && depth == ARCH_LBR_NR_ENTRIES) {
4048             kvm_msr_entry_add(cpu, MSR_ARCH_LBR_CTL, 0);
4049             kvm_msr_entry_add(cpu, MSR_ARCH_LBR_DEPTH, 0);
4050 
4051             for (i = 0; i < ARCH_LBR_NR_ENTRIES; i++) {
4052                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_FROM_0 + i, 0);
4053                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_TO_0 + i, 0);
4054                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_INFO_0 + i, 0);
4055             }
4056         }
4057     }
4058 
4059     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
4060     if (ret < 0) {
4061         return ret;
4062     }
4063 
4064     if (ret < cpu->kvm_msr_buf->nmsrs) {
4065         struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
4066         error_report("error: failed to get MSR 0x%" PRIx32,
4067                      (uint32_t)e->index);
4068     }
4069 
4070     assert(ret == cpu->kvm_msr_buf->nmsrs);
4071     /*
4072      * MTRR masks: Each mask consists of 5 parts
4073      * a  10..0: must be zero
4074      * b  11   : valid bit
4075      * c n-1.12: actual mask bits
4076      * d  51..n: reserved must be zero
4077      * e  63.52: reserved must be zero
4078      *
4079      * 'n' is the number of physical bits supported by the CPU and is
4080      * apparently always <= 52.   We know our 'n' but don't know what
4081      * the destinations 'n' is; it might be smaller, in which case
4082      * it masks (c) on loading. It might be larger, in which case
4083      * we fill 'd' so that d..c is consistent irrespetive of the 'n'
4084      * we're migrating to.
4085      */
4086 
4087     if (cpu->fill_mtrr_mask) {
4088         QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
4089         assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
4090         mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
4091     } else {
4092         mtrr_top_bits = 0;
4093     }
4094 
4095     for (i = 0; i < ret; i++) {
4096         uint32_t index = msrs[i].index;
4097         switch (index) {
4098         case MSR_IA32_SYSENTER_CS:
4099             env->sysenter_cs = msrs[i].data;
4100             break;
4101         case MSR_IA32_SYSENTER_ESP:
4102             env->sysenter_esp = msrs[i].data;
4103             break;
4104         case MSR_IA32_SYSENTER_EIP:
4105             env->sysenter_eip = msrs[i].data;
4106             break;
4107         case MSR_PAT:
4108             env->pat = msrs[i].data;
4109             break;
4110         case MSR_STAR:
4111             env->star = msrs[i].data;
4112             break;
4113 #ifdef TARGET_X86_64
4114         case MSR_CSTAR:
4115             env->cstar = msrs[i].data;
4116             break;
4117         case MSR_KERNELGSBASE:
4118             env->kernelgsbase = msrs[i].data;
4119             break;
4120         case MSR_FMASK:
4121             env->fmask = msrs[i].data;
4122             break;
4123         case MSR_LSTAR:
4124             env->lstar = msrs[i].data;
4125             break;
4126 #endif
4127         case MSR_IA32_TSC:
4128             env->tsc = msrs[i].data;
4129             break;
4130         case MSR_TSC_AUX:
4131             env->tsc_aux = msrs[i].data;
4132             break;
4133         case MSR_TSC_ADJUST:
4134             env->tsc_adjust = msrs[i].data;
4135             break;
4136         case MSR_IA32_TSCDEADLINE:
4137             env->tsc_deadline = msrs[i].data;
4138             break;
4139         case MSR_VM_HSAVE_PA:
4140             env->vm_hsave = msrs[i].data;
4141             break;
4142         case MSR_KVM_SYSTEM_TIME:
4143             env->system_time_msr = msrs[i].data;
4144             break;
4145         case MSR_KVM_WALL_CLOCK:
4146             env->wall_clock_msr = msrs[i].data;
4147             break;
4148         case MSR_MCG_STATUS:
4149             env->mcg_status = msrs[i].data;
4150             break;
4151         case MSR_MCG_CTL:
4152             env->mcg_ctl = msrs[i].data;
4153             break;
4154         case MSR_MCG_EXT_CTL:
4155             env->mcg_ext_ctl = msrs[i].data;
4156             break;
4157         case MSR_IA32_MISC_ENABLE:
4158             env->msr_ia32_misc_enable = msrs[i].data;
4159             break;
4160         case MSR_IA32_SMBASE:
4161             env->smbase = msrs[i].data;
4162             break;
4163         case MSR_SMI_COUNT:
4164             env->msr_smi_count = msrs[i].data;
4165             break;
4166         case MSR_IA32_FEATURE_CONTROL:
4167             env->msr_ia32_feature_control = msrs[i].data;
4168             break;
4169         case MSR_IA32_BNDCFGS:
4170             env->msr_bndcfgs = msrs[i].data;
4171             break;
4172         case MSR_IA32_XSS:
4173             env->xss = msrs[i].data;
4174             break;
4175         case MSR_IA32_UMWAIT_CONTROL:
4176             env->umwait = msrs[i].data;
4177             break;
4178         case MSR_IA32_PKRS:
4179             env->pkrs = msrs[i].data;
4180             break;
4181         default:
4182             if (msrs[i].index >= MSR_MC0_CTL &&
4183                 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
4184                 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
4185             }
4186             break;
4187         case MSR_KVM_ASYNC_PF_EN:
4188             env->async_pf_en_msr = msrs[i].data;
4189             break;
4190         case MSR_KVM_ASYNC_PF_INT:
4191             env->async_pf_int_msr = msrs[i].data;
4192             break;
4193         case MSR_KVM_PV_EOI_EN:
4194             env->pv_eoi_en_msr = msrs[i].data;
4195             break;
4196         case MSR_KVM_STEAL_TIME:
4197             env->steal_time_msr = msrs[i].data;
4198             break;
4199         case MSR_KVM_POLL_CONTROL: {
4200             env->poll_control_msr = msrs[i].data;
4201             break;
4202         }
4203         case MSR_CORE_PERF_FIXED_CTR_CTRL:
4204             env->msr_fixed_ctr_ctrl = msrs[i].data;
4205             break;
4206         case MSR_CORE_PERF_GLOBAL_CTRL:
4207             env->msr_global_ctrl = msrs[i].data;
4208             break;
4209         case MSR_CORE_PERF_GLOBAL_STATUS:
4210             env->msr_global_status = msrs[i].data;
4211             break;
4212         case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
4213             env->msr_global_ovf_ctrl = msrs[i].data;
4214             break;
4215         case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
4216             env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
4217             break;
4218         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
4219             env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
4220             break;
4221         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
4222             env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
4223             break;
4224         case HV_X64_MSR_HYPERCALL:
4225             env->msr_hv_hypercall = msrs[i].data;
4226             break;
4227         case HV_X64_MSR_GUEST_OS_ID:
4228             env->msr_hv_guest_os_id = msrs[i].data;
4229             break;
4230         case HV_X64_MSR_APIC_ASSIST_PAGE:
4231             env->msr_hv_vapic = msrs[i].data;
4232             break;
4233         case HV_X64_MSR_REFERENCE_TSC:
4234             env->msr_hv_tsc = msrs[i].data;
4235             break;
4236         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4237             env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
4238             break;
4239         case HV_X64_MSR_VP_RUNTIME:
4240             env->msr_hv_runtime = msrs[i].data;
4241             break;
4242         case HV_X64_MSR_SCONTROL:
4243             env->msr_hv_synic_control = msrs[i].data;
4244             break;
4245         case HV_X64_MSR_SIEFP:
4246             env->msr_hv_synic_evt_page = msrs[i].data;
4247             break;
4248         case HV_X64_MSR_SIMP:
4249             env->msr_hv_synic_msg_page = msrs[i].data;
4250             break;
4251         case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
4252             env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
4253             break;
4254         case HV_X64_MSR_STIMER0_CONFIG:
4255         case HV_X64_MSR_STIMER1_CONFIG:
4256         case HV_X64_MSR_STIMER2_CONFIG:
4257         case HV_X64_MSR_STIMER3_CONFIG:
4258             env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
4259                                 msrs[i].data;
4260             break;
4261         case HV_X64_MSR_STIMER0_COUNT:
4262         case HV_X64_MSR_STIMER1_COUNT:
4263         case HV_X64_MSR_STIMER2_COUNT:
4264         case HV_X64_MSR_STIMER3_COUNT:
4265             env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
4266                                 msrs[i].data;
4267             break;
4268         case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4269             env->msr_hv_reenlightenment_control = msrs[i].data;
4270             break;
4271         case HV_X64_MSR_TSC_EMULATION_CONTROL:
4272             env->msr_hv_tsc_emulation_control = msrs[i].data;
4273             break;
4274         case HV_X64_MSR_TSC_EMULATION_STATUS:
4275             env->msr_hv_tsc_emulation_status = msrs[i].data;
4276             break;
4277         case HV_X64_MSR_SYNDBG_OPTIONS:
4278             env->msr_hv_syndbg_options = msrs[i].data;
4279             break;
4280         case MSR_MTRRdefType:
4281             env->mtrr_deftype = msrs[i].data;
4282             break;
4283         case MSR_MTRRfix64K_00000:
4284             env->mtrr_fixed[0] = msrs[i].data;
4285             break;
4286         case MSR_MTRRfix16K_80000:
4287             env->mtrr_fixed[1] = msrs[i].data;
4288             break;
4289         case MSR_MTRRfix16K_A0000:
4290             env->mtrr_fixed[2] = msrs[i].data;
4291             break;
4292         case MSR_MTRRfix4K_C0000:
4293             env->mtrr_fixed[3] = msrs[i].data;
4294             break;
4295         case MSR_MTRRfix4K_C8000:
4296             env->mtrr_fixed[4] = msrs[i].data;
4297             break;
4298         case MSR_MTRRfix4K_D0000:
4299             env->mtrr_fixed[5] = msrs[i].data;
4300             break;
4301         case MSR_MTRRfix4K_D8000:
4302             env->mtrr_fixed[6] = msrs[i].data;
4303             break;
4304         case MSR_MTRRfix4K_E0000:
4305             env->mtrr_fixed[7] = msrs[i].data;
4306             break;
4307         case MSR_MTRRfix4K_E8000:
4308             env->mtrr_fixed[8] = msrs[i].data;
4309             break;
4310         case MSR_MTRRfix4K_F0000:
4311             env->mtrr_fixed[9] = msrs[i].data;
4312             break;
4313         case MSR_MTRRfix4K_F8000:
4314             env->mtrr_fixed[10] = msrs[i].data;
4315             break;
4316         case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
4317             if (index & 1) {
4318                 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
4319                                                                mtrr_top_bits;
4320             } else {
4321                 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
4322             }
4323             break;
4324         case MSR_IA32_SPEC_CTRL:
4325             env->spec_ctrl = msrs[i].data;
4326             break;
4327         case MSR_AMD64_TSC_RATIO:
4328             env->amd_tsc_scale_msr = msrs[i].data;
4329             break;
4330         case MSR_IA32_TSX_CTRL:
4331             env->tsx_ctrl = msrs[i].data;
4332             break;
4333         case MSR_VIRT_SSBD:
4334             env->virt_ssbd = msrs[i].data;
4335             break;
4336         case MSR_IA32_RTIT_CTL:
4337             env->msr_rtit_ctrl = msrs[i].data;
4338             break;
4339         case MSR_IA32_RTIT_STATUS:
4340             env->msr_rtit_status = msrs[i].data;
4341             break;
4342         case MSR_IA32_RTIT_OUTPUT_BASE:
4343             env->msr_rtit_output_base = msrs[i].data;
4344             break;
4345         case MSR_IA32_RTIT_OUTPUT_MASK:
4346             env->msr_rtit_output_mask = msrs[i].data;
4347             break;
4348         case MSR_IA32_RTIT_CR3_MATCH:
4349             env->msr_rtit_cr3_match = msrs[i].data;
4350             break;
4351         case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
4352             env->msr_rtit_addrs[index - MSR_IA32_RTIT_ADDR0_A] = msrs[i].data;
4353             break;
4354         case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
4355             env->msr_ia32_sgxlepubkeyhash[index - MSR_IA32_SGXLEPUBKEYHASH0] =
4356                            msrs[i].data;
4357             break;
4358         case MSR_IA32_XFD:
4359             env->msr_xfd = msrs[i].data;
4360             break;
4361         case MSR_IA32_XFD_ERR:
4362             env->msr_xfd_err = msrs[i].data;
4363             break;
4364         case MSR_ARCH_LBR_CTL:
4365             env->msr_lbr_ctl = msrs[i].data;
4366             break;
4367         case MSR_ARCH_LBR_DEPTH:
4368             env->msr_lbr_depth = msrs[i].data;
4369             break;
4370         case MSR_ARCH_LBR_FROM_0 ... MSR_ARCH_LBR_FROM_0 + 31:
4371             env->lbr_records[index - MSR_ARCH_LBR_FROM_0].from = msrs[i].data;
4372             break;
4373         case MSR_ARCH_LBR_TO_0 ... MSR_ARCH_LBR_TO_0 + 31:
4374             env->lbr_records[index - MSR_ARCH_LBR_TO_0].to = msrs[i].data;
4375             break;
4376         case MSR_ARCH_LBR_INFO_0 ... MSR_ARCH_LBR_INFO_0 + 31:
4377             env->lbr_records[index - MSR_ARCH_LBR_INFO_0].info = msrs[i].data;
4378             break;
4379         }
4380     }
4381 
4382     return 0;
4383 }
4384 
4385 static int kvm_put_mp_state(X86CPU *cpu)
4386 {
4387     struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
4388 
4389     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
4390 }
4391 
4392 static int kvm_get_mp_state(X86CPU *cpu)
4393 {
4394     CPUState *cs = CPU(cpu);
4395     CPUX86State *env = &cpu->env;
4396     struct kvm_mp_state mp_state;
4397     int ret;
4398 
4399     ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
4400     if (ret < 0) {
4401         return ret;
4402     }
4403     env->mp_state = mp_state.mp_state;
4404     if (kvm_irqchip_in_kernel()) {
4405         cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
4406     }
4407     return 0;
4408 }
4409 
4410 static int kvm_get_apic(X86CPU *cpu)
4411 {
4412     DeviceState *apic = cpu->apic_state;
4413     struct kvm_lapic_state kapic;
4414     int ret;
4415 
4416     if (apic && kvm_irqchip_in_kernel()) {
4417         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
4418         if (ret < 0) {
4419             return ret;
4420         }
4421 
4422         kvm_get_apic_state(apic, &kapic);
4423     }
4424     return 0;
4425 }
4426 
4427 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
4428 {
4429     CPUState *cs = CPU(cpu);
4430     CPUX86State *env = &cpu->env;
4431     struct kvm_vcpu_events events = {};
4432 
4433     if (!kvm_has_vcpu_events()) {
4434         return 0;
4435     }
4436 
4437     events.flags = 0;
4438 
4439     if (has_exception_payload) {
4440         events.flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
4441         events.exception.pending = env->exception_pending;
4442         events.exception_has_payload = env->exception_has_payload;
4443         events.exception_payload = env->exception_payload;
4444     }
4445     events.exception.nr = env->exception_nr;
4446     events.exception.injected = env->exception_injected;
4447     events.exception.has_error_code = env->has_error_code;
4448     events.exception.error_code = env->error_code;
4449 
4450     events.interrupt.injected = (env->interrupt_injected >= 0);
4451     events.interrupt.nr = env->interrupt_injected;
4452     events.interrupt.soft = env->soft_interrupt;
4453 
4454     events.nmi.injected = env->nmi_injected;
4455     events.nmi.pending = env->nmi_pending;
4456     events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
4457 
4458     events.sipi_vector = env->sipi_vector;
4459 
4460     if (has_msr_smbase) {
4461         events.smi.smm = !!(env->hflags & HF_SMM_MASK);
4462         events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
4463         if (kvm_irqchip_in_kernel()) {
4464             /* As soon as these are moved to the kernel, remove them
4465              * from cs->interrupt_request.
4466              */
4467             events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
4468             events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
4469             cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
4470         } else {
4471             /* Keep these in cs->interrupt_request.  */
4472             events.smi.pending = 0;
4473             events.smi.latched_init = 0;
4474         }
4475         /* Stop SMI delivery on old machine types to avoid a reboot
4476          * on an inward migration of an old VM.
4477          */
4478         if (!cpu->kvm_no_smi_migration) {
4479             events.flags |= KVM_VCPUEVENT_VALID_SMM;
4480         }
4481     }
4482 
4483     if (level >= KVM_PUT_RESET_STATE) {
4484         events.flags |= KVM_VCPUEVENT_VALID_NMI_PENDING;
4485         if (env->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
4486             events.flags |= KVM_VCPUEVENT_VALID_SIPI_VECTOR;
4487         }
4488     }
4489 
4490     if (has_triple_fault_event) {
4491         events.flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
4492         events.triple_fault.pending = env->triple_fault_pending;
4493     }
4494 
4495     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
4496 }
4497 
4498 static int kvm_get_vcpu_events(X86CPU *cpu)
4499 {
4500     CPUX86State *env = &cpu->env;
4501     struct kvm_vcpu_events events;
4502     int ret;
4503 
4504     if (!kvm_has_vcpu_events()) {
4505         return 0;
4506     }
4507 
4508     memset(&events, 0, sizeof(events));
4509     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
4510     if (ret < 0) {
4511        return ret;
4512     }
4513 
4514     if (events.flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4515         env->exception_pending = events.exception.pending;
4516         env->exception_has_payload = events.exception_has_payload;
4517         env->exception_payload = events.exception_payload;
4518     } else {
4519         env->exception_pending = 0;
4520         env->exception_has_payload = false;
4521     }
4522     env->exception_injected = events.exception.injected;
4523     env->exception_nr =
4524         (env->exception_pending || env->exception_injected) ?
4525         events.exception.nr : -1;
4526     env->has_error_code = events.exception.has_error_code;
4527     env->error_code = events.exception.error_code;
4528 
4529     env->interrupt_injected =
4530         events.interrupt.injected ? events.interrupt.nr : -1;
4531     env->soft_interrupt = events.interrupt.soft;
4532 
4533     env->nmi_injected = events.nmi.injected;
4534     env->nmi_pending = events.nmi.pending;
4535     if (events.nmi.masked) {
4536         env->hflags2 |= HF2_NMI_MASK;
4537     } else {
4538         env->hflags2 &= ~HF2_NMI_MASK;
4539     }
4540 
4541     if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
4542         if (events.smi.smm) {
4543             env->hflags |= HF_SMM_MASK;
4544         } else {
4545             env->hflags &= ~HF_SMM_MASK;
4546         }
4547         if (events.smi.pending) {
4548             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
4549         } else {
4550             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
4551         }
4552         if (events.smi.smm_inside_nmi) {
4553             env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
4554         } else {
4555             env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
4556         }
4557         if (events.smi.latched_init) {
4558             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
4559         } else {
4560             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
4561         }
4562     }
4563 
4564     if (events.flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
4565         env->triple_fault_pending = events.triple_fault.pending;
4566     }
4567 
4568     env->sipi_vector = events.sipi_vector;
4569 
4570     return 0;
4571 }
4572 
4573 static int kvm_guest_debug_workarounds(X86CPU *cpu)
4574 {
4575     CPUState *cs = CPU(cpu);
4576     CPUX86State *env = &cpu->env;
4577     int ret = 0;
4578     unsigned long reinject_trap = 0;
4579 
4580     if (!kvm_has_vcpu_events()) {
4581         if (env->exception_nr == EXCP01_DB) {
4582             reinject_trap = KVM_GUESTDBG_INJECT_DB;
4583         } else if (env->exception_injected == EXCP03_INT3) {
4584             reinject_trap = KVM_GUESTDBG_INJECT_BP;
4585         }
4586         kvm_reset_exception(env);
4587     }
4588 
4589     /*
4590      * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
4591      * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
4592      * by updating the debug state once again if single-stepping is on.
4593      * Another reason to call kvm_update_guest_debug here is a pending debug
4594      * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
4595      * reinject them via SET_GUEST_DEBUG.
4596      */
4597     if (reinject_trap ||
4598         (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
4599         ret = kvm_update_guest_debug(cs, reinject_trap);
4600     }
4601     return ret;
4602 }
4603 
4604 static int kvm_put_debugregs(X86CPU *cpu)
4605 {
4606     CPUX86State *env = &cpu->env;
4607     struct kvm_debugregs dbgregs;
4608     int i;
4609 
4610     if (!kvm_has_debugregs()) {
4611         return 0;
4612     }
4613 
4614     memset(&dbgregs, 0, sizeof(dbgregs));
4615     for (i = 0; i < 4; i++) {
4616         dbgregs.db[i] = env->dr[i];
4617     }
4618     dbgregs.dr6 = env->dr[6];
4619     dbgregs.dr7 = env->dr[7];
4620     dbgregs.flags = 0;
4621 
4622     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
4623 }
4624 
4625 static int kvm_get_debugregs(X86CPU *cpu)
4626 {
4627     CPUX86State *env = &cpu->env;
4628     struct kvm_debugregs dbgregs;
4629     int i, ret;
4630 
4631     if (!kvm_has_debugregs()) {
4632         return 0;
4633     }
4634 
4635     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
4636     if (ret < 0) {
4637         return ret;
4638     }
4639     for (i = 0; i < 4; i++) {
4640         env->dr[i] = dbgregs.db[i];
4641     }
4642     env->dr[4] = env->dr[6] = dbgregs.dr6;
4643     env->dr[5] = env->dr[7] = dbgregs.dr7;
4644 
4645     return 0;
4646 }
4647 
4648 static int kvm_put_nested_state(X86CPU *cpu)
4649 {
4650     CPUX86State *env = &cpu->env;
4651     int max_nested_state_len = kvm_max_nested_state_length();
4652 
4653     if (!env->nested_state) {
4654         return 0;
4655     }
4656 
4657     /*
4658      * Copy flags that are affected by reset from env->hflags and env->hflags2.
4659      */
4660     if (env->hflags & HF_GUEST_MASK) {
4661         env->nested_state->flags |= KVM_STATE_NESTED_GUEST_MODE;
4662     } else {
4663         env->nested_state->flags &= ~KVM_STATE_NESTED_GUEST_MODE;
4664     }
4665 
4666     /* Don't set KVM_STATE_NESTED_GIF_SET on VMX as it is illegal */
4667     if (cpu_has_svm(env) && (env->hflags2 & HF2_GIF_MASK)) {
4668         env->nested_state->flags |= KVM_STATE_NESTED_GIF_SET;
4669     } else {
4670         env->nested_state->flags &= ~KVM_STATE_NESTED_GIF_SET;
4671     }
4672 
4673     assert(env->nested_state->size <= max_nested_state_len);
4674     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_NESTED_STATE, env->nested_state);
4675 }
4676 
4677 static int kvm_get_nested_state(X86CPU *cpu)
4678 {
4679     CPUX86State *env = &cpu->env;
4680     int max_nested_state_len = kvm_max_nested_state_length();
4681     int ret;
4682 
4683     if (!env->nested_state) {
4684         return 0;
4685     }
4686 
4687     /*
4688      * It is possible that migration restored a smaller size into
4689      * nested_state->hdr.size than what our kernel support.
4690      * We preserve migration origin nested_state->hdr.size for
4691      * call to KVM_SET_NESTED_STATE but wish that our next call
4692      * to KVM_GET_NESTED_STATE will use max size our kernel support.
4693      */
4694     env->nested_state->size = max_nested_state_len;
4695 
4696     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_NESTED_STATE, env->nested_state);
4697     if (ret < 0) {
4698         return ret;
4699     }
4700 
4701     /*
4702      * Copy flags that are affected by reset to env->hflags and env->hflags2.
4703      */
4704     if (env->nested_state->flags & KVM_STATE_NESTED_GUEST_MODE) {
4705         env->hflags |= HF_GUEST_MASK;
4706     } else {
4707         env->hflags &= ~HF_GUEST_MASK;
4708     }
4709 
4710     /* Keep HF2_GIF_MASK set on !SVM as x86_cpu_pending_interrupt() needs it */
4711     if (cpu_has_svm(env)) {
4712         if (env->nested_state->flags & KVM_STATE_NESTED_GIF_SET) {
4713             env->hflags2 |= HF2_GIF_MASK;
4714         } else {
4715             env->hflags2 &= ~HF2_GIF_MASK;
4716         }
4717     }
4718 
4719     return ret;
4720 }
4721 
4722 int kvm_arch_put_registers(CPUState *cpu, int level)
4723 {
4724     X86CPU *x86_cpu = X86_CPU(cpu);
4725     int ret;
4726 
4727     assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
4728 
4729     /*
4730      * Put MSR_IA32_FEATURE_CONTROL first, this ensures the VM gets out of VMX
4731      * root operation upon vCPU reset. kvm_put_msr_feature_control() should also
4732      * preceed kvm_put_nested_state() when 'real' nested state is set.
4733      */
4734     if (level >= KVM_PUT_RESET_STATE) {
4735         ret = kvm_put_msr_feature_control(x86_cpu);
4736         if (ret < 0) {
4737             return ret;
4738         }
4739     }
4740 
4741     /* must be before kvm_put_nested_state so that EFER.SVME is set */
4742     ret = has_sregs2 ? kvm_put_sregs2(x86_cpu) : kvm_put_sregs(x86_cpu);
4743     if (ret < 0) {
4744         return ret;
4745     }
4746 
4747     if (level >= KVM_PUT_RESET_STATE) {
4748         ret = kvm_put_nested_state(x86_cpu);
4749         if (ret < 0) {
4750             return ret;
4751         }
4752     }
4753 
4754     if (level == KVM_PUT_FULL_STATE) {
4755         /* We don't check for kvm_arch_set_tsc_khz() errors here,
4756          * because TSC frequency mismatch shouldn't abort migration,
4757          * unless the user explicitly asked for a more strict TSC
4758          * setting (e.g. using an explicit "tsc-freq" option).
4759          */
4760         kvm_arch_set_tsc_khz(cpu);
4761     }
4762 
4763 #ifdef CONFIG_XEN_EMU
4764     if (xen_mode == XEN_EMULATE && level == KVM_PUT_FULL_STATE) {
4765         ret = kvm_put_xen_state(cpu);
4766         if (ret < 0) {
4767             return ret;
4768         }
4769     }
4770 #endif
4771 
4772     ret = kvm_getput_regs(x86_cpu, 1);
4773     if (ret < 0) {
4774         return ret;
4775     }
4776     ret = kvm_put_xsave(x86_cpu);
4777     if (ret < 0) {
4778         return ret;
4779     }
4780     ret = kvm_put_xcrs(x86_cpu);
4781     if (ret < 0) {
4782         return ret;
4783     }
4784     /* must be before kvm_put_msrs */
4785     ret = kvm_inject_mce_oldstyle(x86_cpu);
4786     if (ret < 0) {
4787         return ret;
4788     }
4789     ret = kvm_put_msrs(x86_cpu, level);
4790     if (ret < 0) {
4791         return ret;
4792     }
4793     ret = kvm_put_vcpu_events(x86_cpu, level);
4794     if (ret < 0) {
4795         return ret;
4796     }
4797     if (level >= KVM_PUT_RESET_STATE) {
4798         ret = kvm_put_mp_state(x86_cpu);
4799         if (ret < 0) {
4800             return ret;
4801         }
4802     }
4803 
4804     ret = kvm_put_tscdeadline_msr(x86_cpu);
4805     if (ret < 0) {
4806         return ret;
4807     }
4808     ret = kvm_put_debugregs(x86_cpu);
4809     if (ret < 0) {
4810         return ret;
4811     }
4812     /* must be last */
4813     ret = kvm_guest_debug_workarounds(x86_cpu);
4814     if (ret < 0) {
4815         return ret;
4816     }
4817     return 0;
4818 }
4819 
4820 int kvm_arch_get_registers(CPUState *cs)
4821 {
4822     X86CPU *cpu = X86_CPU(cs);
4823     int ret;
4824 
4825     assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
4826 
4827     ret = kvm_get_vcpu_events(cpu);
4828     if (ret < 0) {
4829         goto out;
4830     }
4831     /*
4832      * KVM_GET_MPSTATE can modify CS and RIP, call it before
4833      * KVM_GET_REGS and KVM_GET_SREGS.
4834      */
4835     ret = kvm_get_mp_state(cpu);
4836     if (ret < 0) {
4837         goto out;
4838     }
4839     ret = kvm_getput_regs(cpu, 0);
4840     if (ret < 0) {
4841         goto out;
4842     }
4843     ret = kvm_get_xsave(cpu);
4844     if (ret < 0) {
4845         goto out;
4846     }
4847     ret = kvm_get_xcrs(cpu);
4848     if (ret < 0) {
4849         goto out;
4850     }
4851     ret = has_sregs2 ? kvm_get_sregs2(cpu) : kvm_get_sregs(cpu);
4852     if (ret < 0) {
4853         goto out;
4854     }
4855     ret = kvm_get_msrs(cpu);
4856     if (ret < 0) {
4857         goto out;
4858     }
4859     ret = kvm_get_apic(cpu);
4860     if (ret < 0) {
4861         goto out;
4862     }
4863     ret = kvm_get_debugregs(cpu);
4864     if (ret < 0) {
4865         goto out;
4866     }
4867     ret = kvm_get_nested_state(cpu);
4868     if (ret < 0) {
4869         goto out;
4870     }
4871 #ifdef CONFIG_XEN_EMU
4872     if (xen_mode == XEN_EMULATE) {
4873         ret = kvm_get_xen_state(cs);
4874         if (ret < 0) {
4875             goto out;
4876         }
4877     }
4878 #endif
4879     ret = 0;
4880  out:
4881     cpu_sync_bndcs_hflags(&cpu->env);
4882     return ret;
4883 }
4884 
4885 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
4886 {
4887     X86CPU *x86_cpu = X86_CPU(cpu);
4888     CPUX86State *env = &x86_cpu->env;
4889     int ret;
4890 
4891     /* Inject NMI */
4892     if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
4893         if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
4894             qemu_mutex_lock_iothread();
4895             cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
4896             qemu_mutex_unlock_iothread();
4897             DPRINTF("injected NMI\n");
4898             ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
4899             if (ret < 0) {
4900                 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
4901                         strerror(-ret));
4902             }
4903         }
4904         if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
4905             qemu_mutex_lock_iothread();
4906             cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
4907             qemu_mutex_unlock_iothread();
4908             DPRINTF("injected SMI\n");
4909             ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
4910             if (ret < 0) {
4911                 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
4912                         strerror(-ret));
4913             }
4914         }
4915     }
4916 
4917     if (!kvm_pic_in_kernel()) {
4918         qemu_mutex_lock_iothread();
4919     }
4920 
4921     /* Force the VCPU out of its inner loop to process any INIT requests
4922      * or (for userspace APIC, but it is cheap to combine the checks here)
4923      * pending TPR access reports.
4924      */
4925     if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
4926         if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
4927             !(env->hflags & HF_SMM_MASK)) {
4928             cpu->exit_request = 1;
4929         }
4930         if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
4931             cpu->exit_request = 1;
4932         }
4933     }
4934 
4935     if (!kvm_pic_in_kernel()) {
4936         /* Try to inject an interrupt if the guest can accept it */
4937         if (run->ready_for_interrupt_injection &&
4938             (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
4939             (env->eflags & IF_MASK)) {
4940             int irq;
4941 
4942             cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
4943             irq = cpu_get_pic_interrupt(env);
4944             if (irq >= 0) {
4945                 struct kvm_interrupt intr;
4946 
4947                 intr.irq = irq;
4948                 DPRINTF("injected interrupt %d\n", irq);
4949                 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
4950                 if (ret < 0) {
4951                     fprintf(stderr,
4952                             "KVM: injection failed, interrupt lost (%s)\n",
4953                             strerror(-ret));
4954                 }
4955             }
4956         }
4957 
4958         /* If we have an interrupt but the guest is not ready to receive an
4959          * interrupt, request an interrupt window exit.  This will
4960          * cause a return to userspace as soon as the guest is ready to
4961          * receive interrupts. */
4962         if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
4963             run->request_interrupt_window = 1;
4964         } else {
4965             run->request_interrupt_window = 0;
4966         }
4967 
4968         DPRINTF("setting tpr\n");
4969         run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
4970 
4971         qemu_mutex_unlock_iothread();
4972     }
4973 }
4974 
4975 static void kvm_rate_limit_on_bus_lock(void)
4976 {
4977     uint64_t delay_ns = ratelimit_calculate_delay(&bus_lock_ratelimit_ctrl, 1);
4978 
4979     if (delay_ns) {
4980         g_usleep(delay_ns / SCALE_US);
4981     }
4982 }
4983 
4984 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
4985 {
4986     X86CPU *x86_cpu = X86_CPU(cpu);
4987     CPUX86State *env = &x86_cpu->env;
4988 
4989     if (run->flags & KVM_RUN_X86_SMM) {
4990         env->hflags |= HF_SMM_MASK;
4991     } else {
4992         env->hflags &= ~HF_SMM_MASK;
4993     }
4994     if (run->if_flag) {
4995         env->eflags |= IF_MASK;
4996     } else {
4997         env->eflags &= ~IF_MASK;
4998     }
4999     if (run->flags & KVM_RUN_X86_BUS_LOCK) {
5000         kvm_rate_limit_on_bus_lock();
5001     }
5002 
5003 #ifdef CONFIG_XEN_EMU
5004     /*
5005      * If the callback is asserted as a GSI (or PCI INTx) then check if
5006      * vcpu_info->evtchn_upcall_pending has been cleared, and deassert
5007      * the callback IRQ if so. Ideally we could hook into the PIC/IOAPIC
5008      * EOI and only resample then, exactly how the VFIO eventfd pairs
5009      * are designed to work for level triggered interrupts.
5010      */
5011     if (x86_cpu->env.xen_callback_asserted) {
5012         kvm_xen_maybe_deassert_callback(cpu);
5013     }
5014 #endif
5015 
5016     /* We need to protect the apic state against concurrent accesses from
5017      * different threads in case the userspace irqchip is used. */
5018     if (!kvm_irqchip_in_kernel()) {
5019         qemu_mutex_lock_iothread();
5020     }
5021     cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
5022     cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
5023     if (!kvm_irqchip_in_kernel()) {
5024         qemu_mutex_unlock_iothread();
5025     }
5026     return cpu_get_mem_attrs(env);
5027 }
5028 
5029 int kvm_arch_process_async_events(CPUState *cs)
5030 {
5031     X86CPU *cpu = X86_CPU(cs);
5032     CPUX86State *env = &cpu->env;
5033 
5034     if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
5035         /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
5036         assert(env->mcg_cap);
5037 
5038         cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
5039 
5040         kvm_cpu_synchronize_state(cs);
5041 
5042         if (env->exception_nr == EXCP08_DBLE) {
5043             /* this means triple fault */
5044             qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
5045             cs->exit_request = 1;
5046             return 0;
5047         }
5048         kvm_queue_exception(env, EXCP12_MCHK, 0, 0);
5049         env->has_error_code = 0;
5050 
5051         cs->halted = 0;
5052         if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
5053             env->mp_state = KVM_MP_STATE_RUNNABLE;
5054         }
5055     }
5056 
5057     if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
5058         !(env->hflags & HF_SMM_MASK)) {
5059         kvm_cpu_synchronize_state(cs);
5060         do_cpu_init(cpu);
5061     }
5062 
5063     if (kvm_irqchip_in_kernel()) {
5064         return 0;
5065     }
5066 
5067     if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
5068         cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
5069         apic_poll_irq(cpu->apic_state);
5070     }
5071     if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
5072          (env->eflags & IF_MASK)) ||
5073         (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
5074         cs->halted = 0;
5075     }
5076     if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
5077         kvm_cpu_synchronize_state(cs);
5078         do_cpu_sipi(cpu);
5079     }
5080     if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
5081         cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
5082         kvm_cpu_synchronize_state(cs);
5083         apic_handle_tpr_access_report(cpu->apic_state, env->eip,
5084                                       env->tpr_access_type);
5085     }
5086 
5087     return cs->halted;
5088 }
5089 
5090 static int kvm_handle_halt(X86CPU *cpu)
5091 {
5092     CPUState *cs = CPU(cpu);
5093     CPUX86State *env = &cpu->env;
5094 
5095     if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
5096           (env->eflags & IF_MASK)) &&
5097         !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
5098         cs->halted = 1;
5099         return EXCP_HLT;
5100     }
5101 
5102     return 0;
5103 }
5104 
5105 static int kvm_handle_tpr_access(X86CPU *cpu)
5106 {
5107     CPUState *cs = CPU(cpu);
5108     struct kvm_run *run = cs->kvm_run;
5109 
5110     apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
5111                                   run->tpr_access.is_write ? TPR_ACCESS_WRITE
5112                                                            : TPR_ACCESS_READ);
5113     return 1;
5114 }
5115 
5116 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
5117 {
5118     static const uint8_t int3 = 0xcc;
5119 
5120     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
5121         cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
5122         return -EINVAL;
5123     }
5124     return 0;
5125 }
5126 
5127 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
5128 {
5129     uint8_t int3;
5130 
5131     if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0)) {
5132         return -EINVAL;
5133     }
5134     if (int3 != 0xcc) {
5135         return 0;
5136     }
5137     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
5138         return -EINVAL;
5139     }
5140     return 0;
5141 }
5142 
5143 static struct {
5144     target_ulong addr;
5145     int len;
5146     int type;
5147 } hw_breakpoint[4];
5148 
5149 static int nb_hw_breakpoint;
5150 
5151 static int find_hw_breakpoint(target_ulong addr, int len, int type)
5152 {
5153     int n;
5154 
5155     for (n = 0; n < nb_hw_breakpoint; n++) {
5156         if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
5157             (hw_breakpoint[n].len == len || len == -1)) {
5158             return n;
5159         }
5160     }
5161     return -1;
5162 }
5163 
5164 int kvm_arch_insert_hw_breakpoint(vaddr addr, vaddr len, int type)
5165 {
5166     switch (type) {
5167     case GDB_BREAKPOINT_HW:
5168         len = 1;
5169         break;
5170     case GDB_WATCHPOINT_WRITE:
5171     case GDB_WATCHPOINT_ACCESS:
5172         switch (len) {
5173         case 1:
5174             break;
5175         case 2:
5176         case 4:
5177         case 8:
5178             if (addr & (len - 1)) {
5179                 return -EINVAL;
5180             }
5181             break;
5182         default:
5183             return -EINVAL;
5184         }
5185         break;
5186     default:
5187         return -ENOSYS;
5188     }
5189 
5190     if (nb_hw_breakpoint == 4) {
5191         return -ENOBUFS;
5192     }
5193     if (find_hw_breakpoint(addr, len, type) >= 0) {
5194         return -EEXIST;
5195     }
5196     hw_breakpoint[nb_hw_breakpoint].addr = addr;
5197     hw_breakpoint[nb_hw_breakpoint].len = len;
5198     hw_breakpoint[nb_hw_breakpoint].type = type;
5199     nb_hw_breakpoint++;
5200 
5201     return 0;
5202 }
5203 
5204 int kvm_arch_remove_hw_breakpoint(vaddr addr, vaddr len, int type)
5205 {
5206     int n;
5207 
5208     n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
5209     if (n < 0) {
5210         return -ENOENT;
5211     }
5212     nb_hw_breakpoint--;
5213     hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
5214 
5215     return 0;
5216 }
5217 
5218 void kvm_arch_remove_all_hw_breakpoints(void)
5219 {
5220     nb_hw_breakpoint = 0;
5221 }
5222 
5223 static CPUWatchpoint hw_watchpoint;
5224 
5225 static int kvm_handle_debug(X86CPU *cpu,
5226                             struct kvm_debug_exit_arch *arch_info)
5227 {
5228     CPUState *cs = CPU(cpu);
5229     CPUX86State *env = &cpu->env;
5230     int ret = 0;
5231     int n;
5232 
5233     if (arch_info->exception == EXCP01_DB) {
5234         if (arch_info->dr6 & DR6_BS) {
5235             if (cs->singlestep_enabled) {
5236                 ret = EXCP_DEBUG;
5237             }
5238         } else {
5239             for (n = 0; n < 4; n++) {
5240                 if (arch_info->dr6 & (1 << n)) {
5241                     switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
5242                     case 0x0:
5243                         ret = EXCP_DEBUG;
5244                         break;
5245                     case 0x1:
5246                         ret = EXCP_DEBUG;
5247                         cs->watchpoint_hit = &hw_watchpoint;
5248                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
5249                         hw_watchpoint.flags = BP_MEM_WRITE;
5250                         break;
5251                     case 0x3:
5252                         ret = EXCP_DEBUG;
5253                         cs->watchpoint_hit = &hw_watchpoint;
5254                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
5255                         hw_watchpoint.flags = BP_MEM_ACCESS;
5256                         break;
5257                     }
5258                 }
5259             }
5260         }
5261     } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
5262         ret = EXCP_DEBUG;
5263     }
5264     if (ret == 0) {
5265         cpu_synchronize_state(cs);
5266         assert(env->exception_nr == -1);
5267 
5268         /* pass to guest */
5269         kvm_queue_exception(env, arch_info->exception,
5270                             arch_info->exception == EXCP01_DB,
5271                             arch_info->dr6);
5272         env->has_error_code = 0;
5273     }
5274 
5275     return ret;
5276 }
5277 
5278 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
5279 {
5280     const uint8_t type_code[] = {
5281         [GDB_BREAKPOINT_HW] = 0x0,
5282         [GDB_WATCHPOINT_WRITE] = 0x1,
5283         [GDB_WATCHPOINT_ACCESS] = 0x3
5284     };
5285     const uint8_t len_code[] = {
5286         [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
5287     };
5288     int n;
5289 
5290     if (kvm_sw_breakpoints_active(cpu)) {
5291         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
5292     }
5293     if (nb_hw_breakpoint > 0) {
5294         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
5295         dbg->arch.debugreg[7] = 0x0600;
5296         for (n = 0; n < nb_hw_breakpoint; n++) {
5297             dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
5298             dbg->arch.debugreg[7] |= (2 << (n * 2)) |
5299                 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
5300                 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
5301         }
5302     }
5303 }
5304 
5305 static bool kvm_install_msr_filters(KVMState *s)
5306 {
5307     uint64_t zero = 0;
5308     struct kvm_msr_filter filter = {
5309         .flags = KVM_MSR_FILTER_DEFAULT_ALLOW,
5310     };
5311     int r, i, j = 0;
5312 
5313     for (i = 0; i < KVM_MSR_FILTER_MAX_RANGES; i++) {
5314         KVMMSRHandlers *handler = &msr_handlers[i];
5315         if (handler->msr) {
5316             struct kvm_msr_filter_range *range = &filter.ranges[j++];
5317 
5318             *range = (struct kvm_msr_filter_range) {
5319                 .flags = 0,
5320                 .nmsrs = 1,
5321                 .base = handler->msr,
5322                 .bitmap = (__u8 *)&zero,
5323             };
5324 
5325             if (handler->rdmsr) {
5326                 range->flags |= KVM_MSR_FILTER_READ;
5327             }
5328 
5329             if (handler->wrmsr) {
5330                 range->flags |= KVM_MSR_FILTER_WRITE;
5331             }
5332         }
5333     }
5334 
5335     r = kvm_vm_ioctl(s, KVM_X86_SET_MSR_FILTER, &filter);
5336     if (r) {
5337         return false;
5338     }
5339 
5340     return true;
5341 }
5342 
5343 bool kvm_filter_msr(KVMState *s, uint32_t msr, QEMURDMSRHandler *rdmsr,
5344                     QEMUWRMSRHandler *wrmsr)
5345 {
5346     int i;
5347 
5348     for (i = 0; i < ARRAY_SIZE(msr_handlers); i++) {
5349         if (!msr_handlers[i].msr) {
5350             msr_handlers[i] = (KVMMSRHandlers) {
5351                 .msr = msr,
5352                 .rdmsr = rdmsr,
5353                 .wrmsr = wrmsr,
5354             };
5355 
5356             if (!kvm_install_msr_filters(s)) {
5357                 msr_handlers[i] = (KVMMSRHandlers) { };
5358                 return false;
5359             }
5360 
5361             return true;
5362         }
5363     }
5364 
5365     return false;
5366 }
5367 
5368 static int kvm_handle_rdmsr(X86CPU *cpu, struct kvm_run *run)
5369 {
5370     int i;
5371     bool r;
5372 
5373     for (i = 0; i < ARRAY_SIZE(msr_handlers); i++) {
5374         KVMMSRHandlers *handler = &msr_handlers[i];
5375         if (run->msr.index == handler->msr) {
5376             if (handler->rdmsr) {
5377                 r = handler->rdmsr(cpu, handler->msr,
5378                                    (uint64_t *)&run->msr.data);
5379                 run->msr.error = r ? 0 : 1;
5380                 return 0;
5381             }
5382         }
5383     }
5384 
5385     assert(false);
5386 }
5387 
5388 static int kvm_handle_wrmsr(X86CPU *cpu, struct kvm_run *run)
5389 {
5390     int i;
5391     bool r;
5392 
5393     for (i = 0; i < ARRAY_SIZE(msr_handlers); i++) {
5394         KVMMSRHandlers *handler = &msr_handlers[i];
5395         if (run->msr.index == handler->msr) {
5396             if (handler->wrmsr) {
5397                 r = handler->wrmsr(cpu, handler->msr, run->msr.data);
5398                 run->msr.error = r ? 0 : 1;
5399                 return 0;
5400             }
5401         }
5402     }
5403 
5404     assert(false);
5405 }
5406 
5407 static bool has_sgx_provisioning;
5408 
5409 static bool __kvm_enable_sgx_provisioning(KVMState *s)
5410 {
5411     int fd, ret;
5412 
5413     if (!kvm_vm_check_extension(s, KVM_CAP_SGX_ATTRIBUTE)) {
5414         return false;
5415     }
5416 
5417     fd = qemu_open_old("/dev/sgx_provision", O_RDONLY);
5418     if (fd < 0) {
5419         return false;
5420     }
5421 
5422     ret = kvm_vm_enable_cap(s, KVM_CAP_SGX_ATTRIBUTE, 0, fd);
5423     if (ret) {
5424         error_report("Could not enable SGX PROVISIONKEY: %s", strerror(-ret));
5425         exit(1);
5426     }
5427     close(fd);
5428     return true;
5429 }
5430 
5431 bool kvm_enable_sgx_provisioning(KVMState *s)
5432 {
5433     return MEMORIZE(__kvm_enable_sgx_provisioning(s), has_sgx_provisioning);
5434 }
5435 
5436 static bool host_supports_vmx(void)
5437 {
5438     uint32_t ecx, unused;
5439 
5440     host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
5441     return ecx & CPUID_EXT_VMX;
5442 }
5443 
5444 #define VMX_INVALID_GUEST_STATE 0x80000021
5445 
5446 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
5447 {
5448     X86CPU *cpu = X86_CPU(cs);
5449     uint64_t code;
5450     int ret;
5451     bool ctx_invalid;
5452     char str[256];
5453     KVMState *state;
5454 
5455     switch (run->exit_reason) {
5456     case KVM_EXIT_HLT:
5457         DPRINTF("handle_hlt\n");
5458         qemu_mutex_lock_iothread();
5459         ret = kvm_handle_halt(cpu);
5460         qemu_mutex_unlock_iothread();
5461         break;
5462     case KVM_EXIT_SET_TPR:
5463         ret = 0;
5464         break;
5465     case KVM_EXIT_TPR_ACCESS:
5466         qemu_mutex_lock_iothread();
5467         ret = kvm_handle_tpr_access(cpu);
5468         qemu_mutex_unlock_iothread();
5469         break;
5470     case KVM_EXIT_FAIL_ENTRY:
5471         code = run->fail_entry.hardware_entry_failure_reason;
5472         fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
5473                 code);
5474         if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
5475             fprintf(stderr,
5476                     "\nIf you're running a guest on an Intel machine without "
5477                         "unrestricted mode\n"
5478                     "support, the failure can be most likely due to the guest "
5479                         "entering an invalid\n"
5480                     "state for Intel VT. For example, the guest maybe running "
5481                         "in big real mode\n"
5482                     "which is not supported on less recent Intel processors."
5483                         "\n\n");
5484         }
5485         ret = -1;
5486         break;
5487     case KVM_EXIT_EXCEPTION:
5488         fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
5489                 run->ex.exception, run->ex.error_code);
5490         ret = -1;
5491         break;
5492     case KVM_EXIT_DEBUG:
5493         DPRINTF("kvm_exit_debug\n");
5494         qemu_mutex_lock_iothread();
5495         ret = kvm_handle_debug(cpu, &run->debug.arch);
5496         qemu_mutex_unlock_iothread();
5497         break;
5498     case KVM_EXIT_HYPERV:
5499         ret = kvm_hv_handle_exit(cpu, &run->hyperv);
5500         break;
5501     case KVM_EXIT_IOAPIC_EOI:
5502         ioapic_eoi_broadcast(run->eoi.vector);
5503         ret = 0;
5504         break;
5505     case KVM_EXIT_X86_BUS_LOCK:
5506         /* already handled in kvm_arch_post_run */
5507         ret = 0;
5508         break;
5509     case KVM_EXIT_NOTIFY:
5510         ctx_invalid = !!(run->notify.flags & KVM_NOTIFY_CONTEXT_INVALID);
5511         state = KVM_STATE(current_accel());
5512         sprintf(str, "Encounter a notify exit with %svalid context in"
5513                      " guest. There can be possible misbehaves in guest."
5514                      " Please have a look.", ctx_invalid ? "in" : "");
5515         if (ctx_invalid ||
5516             state->notify_vmexit == NOTIFY_VMEXIT_OPTION_INTERNAL_ERROR) {
5517             warn_report("KVM internal error: %s", str);
5518             ret = -1;
5519         } else {
5520             warn_report_once("KVM: %s", str);
5521             ret = 0;
5522         }
5523         break;
5524     case KVM_EXIT_X86_RDMSR:
5525         /* We only enable MSR filtering, any other exit is bogus */
5526         assert(run->msr.reason == KVM_MSR_EXIT_REASON_FILTER);
5527         ret = kvm_handle_rdmsr(cpu, run);
5528         break;
5529     case KVM_EXIT_X86_WRMSR:
5530         /* We only enable MSR filtering, any other exit is bogus */
5531         assert(run->msr.reason == KVM_MSR_EXIT_REASON_FILTER);
5532         ret = kvm_handle_wrmsr(cpu, run);
5533         break;
5534 #ifdef CONFIG_XEN_EMU
5535     case KVM_EXIT_XEN:
5536         ret = kvm_xen_handle_exit(cpu, &run->xen);
5537         break;
5538 #endif
5539     default:
5540         fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
5541         ret = -1;
5542         break;
5543     }
5544 
5545     return ret;
5546 }
5547 
5548 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
5549 {
5550     X86CPU *cpu = X86_CPU(cs);
5551     CPUX86State *env = &cpu->env;
5552 
5553     kvm_cpu_synchronize_state(cs);
5554     return !(env->cr[0] & CR0_PE_MASK) ||
5555            ((env->segs[R_CS].selector  & 3) != 3);
5556 }
5557 
5558 void kvm_arch_init_irq_routing(KVMState *s)
5559 {
5560     /* We know at this point that we're using the in-kernel
5561      * irqchip, so we can use irqfds, and on x86 we know
5562      * we can use msi via irqfd and GSI routing.
5563      */
5564     kvm_msi_via_irqfd_allowed = true;
5565     kvm_gsi_routing_allowed = true;
5566 
5567     if (kvm_irqchip_is_split()) {
5568         KVMRouteChange c = kvm_irqchip_begin_route_changes(s);
5569         int i;
5570 
5571         /* If the ioapic is in QEMU and the lapics are in KVM, reserve
5572            MSI routes for signaling interrupts to the local apics. */
5573         for (i = 0; i < IOAPIC_NUM_PINS; i++) {
5574             if (kvm_irqchip_add_msi_route(&c, 0, NULL) < 0) {
5575                 error_report("Could not enable split IRQ mode.");
5576                 exit(1);
5577             }
5578         }
5579         kvm_irqchip_commit_route_changes(&c);
5580     }
5581 }
5582 
5583 int kvm_arch_irqchip_create(KVMState *s)
5584 {
5585     int ret;
5586     if (kvm_kernel_irqchip_split()) {
5587         ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
5588         if (ret) {
5589             error_report("Could not enable split irqchip mode: %s",
5590                          strerror(-ret));
5591             exit(1);
5592         } else {
5593             DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
5594             kvm_split_irqchip = true;
5595             return 1;
5596         }
5597     } else {
5598         return 0;
5599     }
5600 }
5601 
5602 uint64_t kvm_swizzle_msi_ext_dest_id(uint64_t address)
5603 {
5604     CPUX86State *env;
5605     uint64_t ext_id;
5606 
5607     if (!first_cpu) {
5608         return address;
5609     }
5610     env = &X86_CPU(first_cpu)->env;
5611     if (!(env->features[FEAT_KVM] & (1 << KVM_FEATURE_MSI_EXT_DEST_ID))) {
5612         return address;
5613     }
5614 
5615     /*
5616      * If the remappable format bit is set, or the upper bits are
5617      * already set in address_hi, or the low extended bits aren't
5618      * there anyway, do nothing.
5619      */
5620     ext_id = address & (0xff << MSI_ADDR_DEST_IDX_SHIFT);
5621     if (!ext_id || (ext_id & (1 << MSI_ADDR_DEST_IDX_SHIFT)) || (address >> 32)) {
5622         return address;
5623     }
5624 
5625     address &= ~ext_id;
5626     address |= ext_id << 35;
5627     return address;
5628 }
5629 
5630 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
5631                              uint64_t address, uint32_t data, PCIDevice *dev)
5632 {
5633     X86IOMMUState *iommu = x86_iommu_get_default();
5634 
5635     if (iommu) {
5636         X86IOMMUClass *class = X86_IOMMU_DEVICE_GET_CLASS(iommu);
5637 
5638         if (class->int_remap) {
5639             int ret;
5640             MSIMessage src, dst;
5641 
5642             src.address = route->u.msi.address_hi;
5643             src.address <<= VTD_MSI_ADDR_HI_SHIFT;
5644             src.address |= route->u.msi.address_lo;
5645             src.data = route->u.msi.data;
5646 
5647             ret = class->int_remap(iommu, &src, &dst, dev ?     \
5648                                    pci_requester_id(dev) :      \
5649                                    X86_IOMMU_SID_INVALID);
5650             if (ret) {
5651                 trace_kvm_x86_fixup_msi_error(route->gsi);
5652                 return 1;
5653             }
5654 
5655             /*
5656              * Handled untranslated compatibilty format interrupt with
5657              * extended destination ID in the low bits 11-5. */
5658             dst.address = kvm_swizzle_msi_ext_dest_id(dst.address);
5659 
5660             route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
5661             route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
5662             route->u.msi.data = dst.data;
5663             return 0;
5664         }
5665     }
5666 
5667 #ifdef CONFIG_XEN_EMU
5668     if (xen_mode == XEN_EMULATE) {
5669         int handled = xen_evtchn_translate_pirq_msi(route, address, data);
5670 
5671         /*
5672          * If it was a PIRQ and successfully routed (handled == 0) or it was
5673          * an error (handled < 0), return. If it wasn't a PIRQ, keep going.
5674          */
5675         if (handled <= 0) {
5676             return handled;
5677         }
5678     }
5679 #endif
5680 
5681     address = kvm_swizzle_msi_ext_dest_id(address);
5682     route->u.msi.address_hi = address >> VTD_MSI_ADDR_HI_SHIFT;
5683     route->u.msi.address_lo = address & VTD_MSI_ADDR_LO_MASK;
5684     return 0;
5685 }
5686 
5687 typedef struct MSIRouteEntry MSIRouteEntry;
5688 
5689 struct MSIRouteEntry {
5690     PCIDevice *dev;             /* Device pointer */
5691     int vector;                 /* MSI/MSIX vector index */
5692     int virq;                   /* Virtual IRQ index */
5693     QLIST_ENTRY(MSIRouteEntry) list;
5694 };
5695 
5696 /* List of used GSI routes */
5697 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
5698     QLIST_HEAD_INITIALIZER(msi_route_list);
5699 
5700 void kvm_update_msi_routes_all(void *private, bool global,
5701                                uint32_t index, uint32_t mask)
5702 {
5703     int cnt = 0, vector;
5704     MSIRouteEntry *entry;
5705     MSIMessage msg;
5706     PCIDevice *dev;
5707 
5708     /* TODO: explicit route update */
5709     QLIST_FOREACH(entry, &msi_route_list, list) {
5710         cnt++;
5711         vector = entry->vector;
5712         dev = entry->dev;
5713         if (msix_enabled(dev) && !msix_is_masked(dev, vector)) {
5714             msg = msix_get_message(dev, vector);
5715         } else if (msi_enabled(dev) && !msi_is_masked(dev, vector)) {
5716             msg = msi_get_message(dev, vector);
5717         } else {
5718             /*
5719              * Either MSI/MSIX is disabled for the device, or the
5720              * specific message was masked out.  Skip this one.
5721              */
5722             continue;
5723         }
5724         kvm_irqchip_update_msi_route(kvm_state, entry->virq, msg, dev);
5725     }
5726     kvm_irqchip_commit_routes(kvm_state);
5727     trace_kvm_x86_update_msi_routes(cnt);
5728 }
5729 
5730 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
5731                                 int vector, PCIDevice *dev)
5732 {
5733     static bool notify_list_inited = false;
5734     MSIRouteEntry *entry;
5735 
5736     if (!dev) {
5737         /* These are (possibly) IOAPIC routes only used for split
5738          * kernel irqchip mode, while what we are housekeeping are
5739          * PCI devices only. */
5740         return 0;
5741     }
5742 
5743     entry = g_new0(MSIRouteEntry, 1);
5744     entry->dev = dev;
5745     entry->vector = vector;
5746     entry->virq = route->gsi;
5747     QLIST_INSERT_HEAD(&msi_route_list, entry, list);
5748 
5749     trace_kvm_x86_add_msi_route(route->gsi);
5750 
5751     if (!notify_list_inited) {
5752         /* For the first time we do add route, add ourselves into
5753          * IOMMU's IEC notify list if needed. */
5754         X86IOMMUState *iommu = x86_iommu_get_default();
5755         if (iommu) {
5756             x86_iommu_iec_register_notifier(iommu,
5757                                             kvm_update_msi_routes_all,
5758                                             NULL);
5759         }
5760         notify_list_inited = true;
5761     }
5762     return 0;
5763 }
5764 
5765 int kvm_arch_release_virq_post(int virq)
5766 {
5767     MSIRouteEntry *entry, *next;
5768     QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
5769         if (entry->virq == virq) {
5770             trace_kvm_x86_remove_msi_route(virq);
5771             QLIST_REMOVE(entry, list);
5772             g_free(entry);
5773             break;
5774         }
5775     }
5776     return 0;
5777 }
5778 
5779 int kvm_arch_msi_data_to_gsi(uint32_t data)
5780 {
5781     abort();
5782 }
5783 
5784 bool kvm_has_waitpkg(void)
5785 {
5786     return has_msr_umwait;
5787 }
5788 
5789 bool kvm_arch_cpu_check_are_resettable(void)
5790 {
5791     return !sev_es_enabled();
5792 }
5793 
5794 #define ARCH_REQ_XCOMP_GUEST_PERM       0x1025
5795 
5796 void kvm_request_xsave_components(X86CPU *cpu, uint64_t mask)
5797 {
5798     KVMState *s = kvm_state;
5799     uint64_t supported;
5800 
5801     mask &= XSTATE_DYNAMIC_MASK;
5802     if (!mask) {
5803         return;
5804     }
5805     /*
5806      * Just ignore bits that are not in CPUID[EAX=0xD,ECX=0].
5807      * ARCH_REQ_XCOMP_GUEST_PERM would fail, and QEMU has warned
5808      * about them already because they are not supported features.
5809      */
5810     supported = kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EAX);
5811     supported |= (uint64_t)kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EDX) << 32;
5812     mask &= supported;
5813 
5814     while (mask) {
5815         int bit = ctz64(mask);
5816         int rc = syscall(SYS_arch_prctl, ARCH_REQ_XCOMP_GUEST_PERM, bit);
5817         if (rc) {
5818             /*
5819              * Older kernel version (<5.17) do not support
5820              * ARCH_REQ_XCOMP_GUEST_PERM, but also do not return
5821              * any dynamic feature from kvm_arch_get_supported_cpuid.
5822              */
5823             warn_report("prctl(ARCH_REQ_XCOMP_GUEST_PERM) failure "
5824                         "for feature bit %d", bit);
5825         }
5826         mask &= ~BIT_ULL(bit);
5827     }
5828 }
5829 
5830 static int kvm_arch_get_notify_vmexit(Object *obj, Error **errp)
5831 {
5832     KVMState *s = KVM_STATE(obj);
5833     return s->notify_vmexit;
5834 }
5835 
5836 static void kvm_arch_set_notify_vmexit(Object *obj, int value, Error **errp)
5837 {
5838     KVMState *s = KVM_STATE(obj);
5839 
5840     if (s->fd != -1) {
5841         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
5842         return;
5843     }
5844 
5845     s->notify_vmexit = value;
5846 }
5847 
5848 static void kvm_arch_get_notify_window(Object *obj, Visitor *v,
5849                                        const char *name, void *opaque,
5850                                        Error **errp)
5851 {
5852     KVMState *s = KVM_STATE(obj);
5853     uint32_t value = s->notify_window;
5854 
5855     visit_type_uint32(v, name, &value, errp);
5856 }
5857 
5858 static void kvm_arch_set_notify_window(Object *obj, Visitor *v,
5859                                        const char *name, void *opaque,
5860                                        Error **errp)
5861 {
5862     KVMState *s = KVM_STATE(obj);
5863     uint32_t value;
5864 
5865     if (s->fd != -1) {
5866         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
5867         return;
5868     }
5869 
5870     if (!visit_type_uint32(v, name, &value, errp)) {
5871         return;
5872     }
5873 
5874     s->notify_window = value;
5875 }
5876 
5877 static void kvm_arch_get_xen_version(Object *obj, Visitor *v,
5878                                      const char *name, void *opaque,
5879                                      Error **errp)
5880 {
5881     KVMState *s = KVM_STATE(obj);
5882     uint32_t value = s->xen_version;
5883 
5884     visit_type_uint32(v, name, &value, errp);
5885 }
5886 
5887 static void kvm_arch_set_xen_version(Object *obj, Visitor *v,
5888                                      const char *name, void *opaque,
5889                                      Error **errp)
5890 {
5891     KVMState *s = KVM_STATE(obj);
5892     Error *error = NULL;
5893     uint32_t value;
5894 
5895     visit_type_uint32(v, name, &value, &error);
5896     if (error) {
5897         error_propagate(errp, error);
5898         return;
5899     }
5900 
5901     s->xen_version = value;
5902     if (value && xen_mode == XEN_DISABLED) {
5903         xen_mode = XEN_EMULATE;
5904     }
5905 }
5906 
5907 static void kvm_arch_get_xen_gnttab_max_frames(Object *obj, Visitor *v,
5908                                                const char *name, void *opaque,
5909                                                Error **errp)
5910 {
5911     KVMState *s = KVM_STATE(obj);
5912     uint16_t value = s->xen_gnttab_max_frames;
5913 
5914     visit_type_uint16(v, name, &value, errp);
5915 }
5916 
5917 static void kvm_arch_set_xen_gnttab_max_frames(Object *obj, Visitor *v,
5918                                                const char *name, void *opaque,
5919                                                Error **errp)
5920 {
5921     KVMState *s = KVM_STATE(obj);
5922     Error *error = NULL;
5923     uint16_t value;
5924 
5925     visit_type_uint16(v, name, &value, &error);
5926     if (error) {
5927         error_propagate(errp, error);
5928         return;
5929     }
5930 
5931     s->xen_gnttab_max_frames = value;
5932 }
5933 
5934 static void kvm_arch_get_xen_evtchn_max_pirq(Object *obj, Visitor *v,
5935                                              const char *name, void *opaque,
5936                                              Error **errp)
5937 {
5938     KVMState *s = KVM_STATE(obj);
5939     uint16_t value = s->xen_evtchn_max_pirq;
5940 
5941     visit_type_uint16(v, name, &value, errp);
5942 }
5943 
5944 static void kvm_arch_set_xen_evtchn_max_pirq(Object *obj, Visitor *v,
5945                                              const char *name, void *opaque,
5946                                              Error **errp)
5947 {
5948     KVMState *s = KVM_STATE(obj);
5949     Error *error = NULL;
5950     uint16_t value;
5951 
5952     visit_type_uint16(v, name, &value, &error);
5953     if (error) {
5954         error_propagate(errp, error);
5955         return;
5956     }
5957 
5958     s->xen_evtchn_max_pirq = value;
5959 }
5960 
5961 void kvm_arch_accel_class_init(ObjectClass *oc)
5962 {
5963     object_class_property_add_enum(oc, "notify-vmexit", "NotifyVMexitOption",
5964                                    &NotifyVmexitOption_lookup,
5965                                    kvm_arch_get_notify_vmexit,
5966                                    kvm_arch_set_notify_vmexit);
5967     object_class_property_set_description(oc, "notify-vmexit",
5968                                           "Enable notify VM exit");
5969 
5970     object_class_property_add(oc, "notify-window", "uint32",
5971                               kvm_arch_get_notify_window,
5972                               kvm_arch_set_notify_window,
5973                               NULL, NULL);
5974     object_class_property_set_description(oc, "notify-window",
5975                                           "Clock cycles without an event window "
5976                                           "after which a notification VM exit occurs");
5977 
5978     object_class_property_add(oc, "xen-version", "uint32",
5979                               kvm_arch_get_xen_version,
5980                               kvm_arch_set_xen_version,
5981                               NULL, NULL);
5982     object_class_property_set_description(oc, "xen-version",
5983                                           "Xen version to be emulated "
5984                                           "(in XENVER_version form "
5985                                           "e.g. 0x4000a for 4.10)");
5986 
5987     object_class_property_add(oc, "xen-gnttab-max-frames", "uint16",
5988                               kvm_arch_get_xen_gnttab_max_frames,
5989                               kvm_arch_set_xen_gnttab_max_frames,
5990                               NULL, NULL);
5991     object_class_property_set_description(oc, "xen-gnttab-max-frames",
5992                                           "Maximum number of grant table frames");
5993 
5994     object_class_property_add(oc, "xen-evtchn-max-pirq", "uint16",
5995                               kvm_arch_get_xen_evtchn_max_pirq,
5996                               kvm_arch_set_xen_evtchn_max_pirq,
5997                               NULL, NULL);
5998     object_class_property_set_description(oc, "xen-evtchn-max-pirq",
5999                                           "Maximum number of Xen PIRQs");
6000 }
6001 
6002 void kvm_set_max_apic_id(uint32_t max_apic_id)
6003 {
6004     kvm_vm_enable_cap(kvm_state, KVM_CAP_MAX_VCPU_ID, 0, max_apic_id);
6005 }
6006