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