xref: /openbmc/qemu/target/i386/kvm/kvm.c (revision 34aee9c9)
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     return 0;
1654 }
1655 
1656 static Error *invtsc_mig_blocker;
1657 
1658 #define KVM_MAX_CPUID_ENTRIES  100
1659 
1660 static void kvm_init_xsave(CPUX86State *env)
1661 {
1662     if (has_xsave2) {
1663         env->xsave_buf_len = QEMU_ALIGN_UP(has_xsave2, 4096);
1664     } else {
1665         env->xsave_buf_len = sizeof(struct kvm_xsave);
1666     }
1667 
1668     env->xsave_buf = qemu_memalign(4096, env->xsave_buf_len);
1669     memset(env->xsave_buf, 0, env->xsave_buf_len);
1670     /*
1671      * The allocated storage must be large enough for all of the
1672      * possible XSAVE state components.
1673      */
1674     assert(kvm_arch_get_supported_cpuid(kvm_state, 0xd, 0, R_ECX) <=
1675            env->xsave_buf_len);
1676 }
1677 
1678 static void kvm_init_nested_state(CPUX86State *env)
1679 {
1680     struct kvm_vmx_nested_state_hdr *vmx_hdr;
1681     uint32_t size;
1682 
1683     if (!env->nested_state) {
1684         return;
1685     }
1686 
1687     size = env->nested_state->size;
1688 
1689     memset(env->nested_state, 0, size);
1690     env->nested_state->size = size;
1691 
1692     if (cpu_has_vmx(env)) {
1693         env->nested_state->format = KVM_STATE_NESTED_FORMAT_VMX;
1694         vmx_hdr = &env->nested_state->hdr.vmx;
1695         vmx_hdr->vmxon_pa = -1ull;
1696         vmx_hdr->vmcs12_pa = -1ull;
1697     } else if (cpu_has_svm(env)) {
1698         env->nested_state->format = KVM_STATE_NESTED_FORMAT_SVM;
1699     }
1700 }
1701 
1702 int kvm_arch_init_vcpu(CPUState *cs)
1703 {
1704     struct {
1705         struct kvm_cpuid2 cpuid;
1706         struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
1707     } cpuid_data;
1708     /*
1709      * The kernel defines these structs with padding fields so there
1710      * should be no extra padding in our cpuid_data struct.
1711      */
1712     QEMU_BUILD_BUG_ON(sizeof(cpuid_data) !=
1713                       sizeof(struct kvm_cpuid2) +
1714                       sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES);
1715 
1716     X86CPU *cpu = X86_CPU(cs);
1717     CPUX86State *env = &cpu->env;
1718     uint32_t limit, i, j, cpuid_i;
1719     uint32_t unused;
1720     struct kvm_cpuid_entry2 *c;
1721     uint32_t signature[3];
1722     int kvm_base = KVM_CPUID_SIGNATURE;
1723     int max_nested_state_len;
1724     int r;
1725     Error *local_err = NULL;
1726 
1727     memset(&cpuid_data, 0, sizeof(cpuid_data));
1728 
1729     cpuid_i = 0;
1730 
1731     has_xsave2 = kvm_check_extension(cs->kvm_state, KVM_CAP_XSAVE2);
1732 
1733     r = kvm_arch_set_tsc_khz(cs);
1734     if (r < 0) {
1735         return r;
1736     }
1737 
1738     /* vcpu's TSC frequency is either specified by user, or following
1739      * the value used by KVM if the former is not present. In the
1740      * latter case, we query it from KVM and record in env->tsc_khz,
1741      * so that vcpu's TSC frequency can be migrated later via this field.
1742      */
1743     if (!env->tsc_khz) {
1744         r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
1745             kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
1746             -ENOTSUP;
1747         if (r > 0) {
1748             env->tsc_khz = r;
1749         }
1750     }
1751 
1752     env->apic_bus_freq = KVM_APIC_BUS_FREQUENCY;
1753 
1754     /*
1755      * kvm_hyperv_expand_features() is called here for the second time in case
1756      * KVM_CAP_SYS_HYPERV_CPUID is not supported. While we can't possibly handle
1757      * 'query-cpu-model-expansion' in this case as we don't have a KVM vCPU to
1758      * check which Hyper-V enlightenments are supported and which are not, we
1759      * can still proceed and check/expand Hyper-V enlightenments here so legacy
1760      * behavior is preserved.
1761      */
1762     if (!kvm_hyperv_expand_features(cpu, &local_err)) {
1763         error_report_err(local_err);
1764         return -ENOSYS;
1765     }
1766 
1767     if (hyperv_enabled(cpu)) {
1768         r = hyperv_init_vcpu(cpu);
1769         if (r) {
1770             return r;
1771         }
1772 
1773         cpuid_i = hyperv_fill_cpuids(cs, cpuid_data.entries);
1774         kvm_base = KVM_CPUID_SIGNATURE_NEXT;
1775         has_msr_hv_hypercall = true;
1776     }
1777 
1778     if (cs->kvm_state->xen_version) {
1779 #ifdef CONFIG_XEN_EMU
1780         struct kvm_cpuid_entry2 *xen_max_leaf;
1781 
1782         memcpy(signature, "XenVMMXenVMM", 12);
1783 
1784         xen_max_leaf = c = &cpuid_data.entries[cpuid_i++];
1785         c->function = kvm_base + XEN_CPUID_SIGNATURE;
1786         c->eax = kvm_base + XEN_CPUID_TIME;
1787         c->ebx = signature[0];
1788         c->ecx = signature[1];
1789         c->edx = signature[2];
1790 
1791         c = &cpuid_data.entries[cpuid_i++];
1792         c->function = kvm_base + XEN_CPUID_VENDOR;
1793         c->eax = cs->kvm_state->xen_version;
1794         c->ebx = 0;
1795         c->ecx = 0;
1796         c->edx = 0;
1797 
1798         c = &cpuid_data.entries[cpuid_i++];
1799         c->function = kvm_base + XEN_CPUID_HVM_MSR;
1800         /* Number of hypercall-transfer pages */
1801         c->eax = 1;
1802         /* Hypercall MSR base address */
1803         if (hyperv_enabled(cpu)) {
1804             c->ebx = XEN_HYPERCALL_MSR_HYPERV;
1805             kvm_xen_init(cs->kvm_state, c->ebx);
1806         } else {
1807             c->ebx = XEN_HYPERCALL_MSR;
1808         }
1809         c->ecx = 0;
1810         c->edx = 0;
1811 
1812         c = &cpuid_data.entries[cpuid_i++];
1813         c->function = kvm_base + XEN_CPUID_TIME;
1814         c->eax = ((!!tsc_is_stable_and_known(env) << 1) |
1815             (!!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP) << 2));
1816         /* default=0 (emulate if necessary) */
1817         c->ebx = 0;
1818         /* guest tsc frequency */
1819         c->ecx = env->user_tsc_khz;
1820         /* guest tsc incarnation (migration count) */
1821         c->edx = 0;
1822 
1823         c = &cpuid_data.entries[cpuid_i++];
1824         c->function = kvm_base + XEN_CPUID_HVM;
1825         xen_max_leaf->eax = kvm_base + XEN_CPUID_HVM;
1826         if (cs->kvm_state->xen_version >= XEN_VERSION(4, 5)) {
1827             c->function = kvm_base + XEN_CPUID_HVM;
1828 
1829             if (cpu->xen_vapic) {
1830                 c->eax |= XEN_HVM_CPUID_APIC_ACCESS_VIRT;
1831                 c->eax |= XEN_HVM_CPUID_X2APIC_VIRT;
1832             }
1833 
1834             c->eax |= XEN_HVM_CPUID_IOMMU_MAPPINGS;
1835 
1836             if (cs->kvm_state->xen_version >= XEN_VERSION(4, 6)) {
1837                 c->eax |= XEN_HVM_CPUID_VCPU_ID_PRESENT;
1838                 c->ebx = cs->cpu_index;
1839             }
1840 
1841             if (cs->kvm_state->xen_version >= XEN_VERSION(4, 17)) {
1842                 c->eax |= XEN_HVM_CPUID_UPCALL_VECTOR;
1843             }
1844         }
1845 
1846         r = kvm_xen_init_vcpu(cs);
1847         if (r) {
1848             return r;
1849         }
1850 
1851         kvm_base += 0x100;
1852 #else /* CONFIG_XEN_EMU */
1853         /* This should never happen as kvm_arch_init() would have died first. */
1854         fprintf(stderr, "Cannot enable Xen CPUID without Xen support\n");
1855         abort();
1856 #endif
1857     } else if (cpu->expose_kvm) {
1858         memcpy(signature, "KVMKVMKVM\0\0\0", 12);
1859         c = &cpuid_data.entries[cpuid_i++];
1860         c->function = KVM_CPUID_SIGNATURE | kvm_base;
1861         c->eax = KVM_CPUID_FEATURES | kvm_base;
1862         c->ebx = signature[0];
1863         c->ecx = signature[1];
1864         c->edx = signature[2];
1865 
1866         c = &cpuid_data.entries[cpuid_i++];
1867         c->function = KVM_CPUID_FEATURES | kvm_base;
1868         c->eax = env->features[FEAT_KVM];
1869         c->edx = env->features[FEAT_KVM_HINTS];
1870     }
1871 
1872     cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
1873 
1874     if (cpu->kvm_pv_enforce_cpuid) {
1875         r = kvm_vcpu_enable_cap(cs, KVM_CAP_ENFORCE_PV_FEATURE_CPUID, 0, 1);
1876         if (r < 0) {
1877             fprintf(stderr,
1878                     "failed to enable KVM_CAP_ENFORCE_PV_FEATURE_CPUID: %s",
1879                     strerror(-r));
1880             abort();
1881         }
1882     }
1883 
1884     for (i = 0; i <= limit; i++) {
1885         if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1886             fprintf(stderr, "unsupported level value: 0x%x\n", limit);
1887             abort();
1888         }
1889         c = &cpuid_data.entries[cpuid_i++];
1890 
1891         switch (i) {
1892         case 2: {
1893             /* Keep reading function 2 till all the input is received */
1894             int times;
1895 
1896             c->function = i;
1897             c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
1898                        KVM_CPUID_FLAG_STATE_READ_NEXT;
1899             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1900             times = c->eax & 0xff;
1901 
1902             for (j = 1; j < times; ++j) {
1903                 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1904                     fprintf(stderr, "cpuid_data is full, no space for "
1905                             "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
1906                     abort();
1907                 }
1908                 c = &cpuid_data.entries[cpuid_i++];
1909                 c->function = i;
1910                 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
1911                 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1912             }
1913             break;
1914         }
1915         case 0x1f:
1916             if (env->nr_dies < 2) {
1917                 break;
1918             }
1919             /* fallthrough */
1920         case 4:
1921         case 0xb:
1922         case 0xd:
1923             for (j = 0; ; j++) {
1924                 if (i == 0xd && j == 64) {
1925                     break;
1926                 }
1927 
1928                 if (i == 0x1f && j == 64) {
1929                     break;
1930                 }
1931 
1932                 c->function = i;
1933                 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1934                 c->index = j;
1935                 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1936 
1937                 if (i == 4 && c->eax == 0) {
1938                     break;
1939                 }
1940                 if (i == 0xb && !(c->ecx & 0xff00)) {
1941                     break;
1942                 }
1943                 if (i == 0x1f && !(c->ecx & 0xff00)) {
1944                     break;
1945                 }
1946                 if (i == 0xd && c->eax == 0) {
1947                     continue;
1948                 }
1949                 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1950                     fprintf(stderr, "cpuid_data is full, no space for "
1951                             "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1952                     abort();
1953                 }
1954                 c = &cpuid_data.entries[cpuid_i++];
1955             }
1956             break;
1957         case 0x7:
1958         case 0x12:
1959             for (j = 0; ; j++) {
1960                 c->function = i;
1961                 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1962                 c->index = j;
1963                 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1964 
1965                 if (j > 1 && (c->eax & 0xf) != 1) {
1966                     break;
1967                 }
1968 
1969                 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1970                     fprintf(stderr, "cpuid_data is full, no space for "
1971                                 "cpuid(eax:0x12,ecx:0x%x)\n", j);
1972                     abort();
1973                 }
1974                 c = &cpuid_data.entries[cpuid_i++];
1975             }
1976             break;
1977         case 0x14:
1978         case 0x1d:
1979         case 0x1e: {
1980             uint32_t times;
1981 
1982             c->function = i;
1983             c->index = 0;
1984             c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1985             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1986             times = c->eax;
1987 
1988             for (j = 1; j <= times; ++j) {
1989                 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1990                     fprintf(stderr, "cpuid_data is full, no space for "
1991                                 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1992                     abort();
1993                 }
1994                 c = &cpuid_data.entries[cpuid_i++];
1995                 c->function = i;
1996                 c->index = j;
1997                 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1998                 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1999             }
2000             break;
2001         }
2002         default:
2003             c->function = i;
2004             c->flags = 0;
2005             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
2006             if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
2007                 /*
2008                  * KVM already returns all zeroes if a CPUID entry is missing,
2009                  * so we can omit it and avoid hitting KVM's 80-entry limit.
2010                  */
2011                 cpuid_i--;
2012             }
2013             break;
2014         }
2015     }
2016 
2017     if (limit >= 0x0a) {
2018         uint32_t eax, edx;
2019 
2020         cpu_x86_cpuid(env, 0x0a, 0, &eax, &unused, &unused, &edx);
2021 
2022         has_architectural_pmu_version = eax & 0xff;
2023         if (has_architectural_pmu_version > 0) {
2024             num_architectural_pmu_gp_counters = (eax & 0xff00) >> 8;
2025 
2026             /* Shouldn't be more than 32, since that's the number of bits
2027              * available in EBX to tell us _which_ counters are available.
2028              * Play it safe.
2029              */
2030             if (num_architectural_pmu_gp_counters > MAX_GP_COUNTERS) {
2031                 num_architectural_pmu_gp_counters = MAX_GP_COUNTERS;
2032             }
2033 
2034             if (has_architectural_pmu_version > 1) {
2035                 num_architectural_pmu_fixed_counters = edx & 0x1f;
2036 
2037                 if (num_architectural_pmu_fixed_counters > MAX_FIXED_COUNTERS) {
2038                     num_architectural_pmu_fixed_counters = MAX_FIXED_COUNTERS;
2039                 }
2040             }
2041         }
2042     }
2043 
2044     cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
2045 
2046     for (i = 0x80000000; i <= limit; i++) {
2047         if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
2048             fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
2049             abort();
2050         }
2051         c = &cpuid_data.entries[cpuid_i++];
2052 
2053         switch (i) {
2054         case 0x8000001d:
2055             /* Query for all AMD cache information leaves */
2056             for (j = 0; ; j++) {
2057                 c->function = i;
2058                 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2059                 c->index = j;
2060                 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
2061 
2062                 if (c->eax == 0) {
2063                     break;
2064                 }
2065                 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
2066                     fprintf(stderr, "cpuid_data is full, no space for "
2067                             "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
2068                     abort();
2069                 }
2070                 c = &cpuid_data.entries[cpuid_i++];
2071             }
2072             break;
2073         default:
2074             c->function = i;
2075             c->flags = 0;
2076             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
2077             if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
2078                 /*
2079                  * KVM already returns all zeroes if a CPUID entry is missing,
2080                  * so we can omit it and avoid hitting KVM's 80-entry limit.
2081                  */
2082                 cpuid_i--;
2083             }
2084             break;
2085         }
2086     }
2087 
2088     /* Call Centaur's CPUID instructions they are supported. */
2089     if (env->cpuid_xlevel2 > 0) {
2090         cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
2091 
2092         for (i = 0xC0000000; i <= limit; i++) {
2093             if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
2094                 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
2095                 abort();
2096             }
2097             c = &cpuid_data.entries[cpuid_i++];
2098 
2099             c->function = i;
2100             c->flags = 0;
2101             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
2102         }
2103     }
2104 
2105     cpuid_data.cpuid.nent = cpuid_i;
2106 
2107     if (((env->cpuid_version >> 8)&0xF) >= 6
2108         && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
2109            (CPUID_MCE | CPUID_MCA)) {
2110         uint64_t mcg_cap, unsupported_caps;
2111         int banks;
2112         int ret;
2113 
2114         ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
2115         if (ret < 0) {
2116             fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
2117             return ret;
2118         }
2119 
2120         if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
2121             error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
2122                          (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
2123             return -ENOTSUP;
2124         }
2125 
2126         unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
2127         if (unsupported_caps) {
2128             if (unsupported_caps & MCG_LMCE_P) {
2129                 error_report("kvm: LMCE not supported");
2130                 return -ENOTSUP;
2131             }
2132             warn_report("Unsupported MCG_CAP bits: 0x%" PRIx64,
2133                         unsupported_caps);
2134         }
2135 
2136         env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
2137         ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
2138         if (ret < 0) {
2139             fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
2140             return ret;
2141         }
2142     }
2143 
2144     cpu->vmsentry = qemu_add_vm_change_state_handler(cpu_update_state, env);
2145 
2146     c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
2147     if (c) {
2148         has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
2149                                   !!(c->ecx & CPUID_EXT_SMX);
2150     }
2151 
2152     c = cpuid_find_entry(&cpuid_data.cpuid, 7, 0);
2153     if (c && (c->ebx & CPUID_7_0_EBX_SGX)) {
2154         has_msr_feature_control = true;
2155     }
2156 
2157     if (env->mcg_cap & MCG_LMCE_P) {
2158         has_msr_mcg_ext_ctl = has_msr_feature_control = true;
2159     }
2160 
2161     if (!env->user_tsc_khz) {
2162         if ((env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC) &&
2163             invtsc_mig_blocker == NULL) {
2164             error_setg(&invtsc_mig_blocker,
2165                        "State blocked by non-migratable CPU device"
2166                        " (invtsc flag)");
2167             r = migrate_add_blocker(&invtsc_mig_blocker, &local_err);
2168             if (r < 0) {
2169                 error_report_err(local_err);
2170                 return r;
2171             }
2172         }
2173     }
2174 
2175     if (cpu->vmware_cpuid_freq
2176         /* Guests depend on 0x40000000 to detect this feature, so only expose
2177          * it if KVM exposes leaf 0x40000000. (Conflicts with Hyper-V) */
2178         && cpu->expose_kvm
2179         && kvm_base == KVM_CPUID_SIGNATURE
2180         /* TSC clock must be stable and known for this feature. */
2181         && tsc_is_stable_and_known(env)) {
2182 
2183         c = &cpuid_data.entries[cpuid_i++];
2184         c->function = KVM_CPUID_SIGNATURE | 0x10;
2185         c->eax = env->tsc_khz;
2186         c->ebx = env->apic_bus_freq / 1000; /* Hz to KHz */
2187         c->ecx = c->edx = 0;
2188 
2189         c = cpuid_find_entry(&cpuid_data.cpuid, kvm_base, 0);
2190         c->eax = MAX(c->eax, KVM_CPUID_SIGNATURE | 0x10);
2191     }
2192 
2193     cpuid_data.cpuid.nent = cpuid_i;
2194 
2195     cpuid_data.cpuid.padding = 0;
2196     r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
2197     if (r) {
2198         goto fail;
2199     }
2200     kvm_init_xsave(env);
2201 
2202     max_nested_state_len = kvm_max_nested_state_length();
2203     if (max_nested_state_len > 0) {
2204         assert(max_nested_state_len >= offsetof(struct kvm_nested_state, data));
2205 
2206         if (cpu_has_vmx(env) || cpu_has_svm(env)) {
2207             env->nested_state = g_malloc0(max_nested_state_len);
2208             env->nested_state->size = max_nested_state_len;
2209 
2210             kvm_init_nested_state(env);
2211         }
2212     }
2213 
2214     cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
2215 
2216     if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
2217         has_msr_tsc_aux = false;
2218     }
2219 
2220     kvm_init_msrs(cpu);
2221 
2222     return 0;
2223 
2224  fail:
2225     migrate_del_blocker(&invtsc_mig_blocker);
2226 
2227     return r;
2228 }
2229 
2230 int kvm_arch_destroy_vcpu(CPUState *cs)
2231 {
2232     X86CPU *cpu = X86_CPU(cs);
2233     CPUX86State *env = &cpu->env;
2234 
2235     g_free(env->xsave_buf);
2236 
2237     g_free(cpu->kvm_msr_buf);
2238     cpu->kvm_msr_buf = NULL;
2239 
2240     g_free(env->nested_state);
2241     env->nested_state = NULL;
2242 
2243     qemu_del_vm_change_state_handler(cpu->vmsentry);
2244 
2245     return 0;
2246 }
2247 
2248 void kvm_arch_reset_vcpu(X86CPU *cpu)
2249 {
2250     CPUX86State *env = &cpu->env;
2251 
2252     env->xcr0 = 1;
2253     if (kvm_irqchip_in_kernel()) {
2254         env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
2255                                           KVM_MP_STATE_UNINITIALIZED;
2256     } else {
2257         env->mp_state = KVM_MP_STATE_RUNNABLE;
2258     }
2259 
2260     /* enabled by default */
2261     env->poll_control_msr = 1;
2262 
2263     kvm_init_nested_state(env);
2264 
2265     sev_es_set_reset_vector(CPU(cpu));
2266 }
2267 
2268 void kvm_arch_after_reset_vcpu(X86CPU *cpu)
2269 {
2270     CPUX86State *env = &cpu->env;
2271     int i;
2272 
2273     /*
2274      * Reset SynIC after all other devices have been reset to let them remove
2275      * their SINT routes first.
2276      */
2277     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
2278         for (i = 0; i < ARRAY_SIZE(env->msr_hv_synic_sint); i++) {
2279             env->msr_hv_synic_sint[i] = HV_SINT_MASKED;
2280         }
2281 
2282         hyperv_x86_synic_reset(cpu);
2283     }
2284 }
2285 
2286 void kvm_arch_do_init_vcpu(X86CPU *cpu)
2287 {
2288     CPUX86State *env = &cpu->env;
2289 
2290     /* APs get directly into wait-for-SIPI state.  */
2291     if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
2292         env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
2293     }
2294 }
2295 
2296 static int kvm_get_supported_feature_msrs(KVMState *s)
2297 {
2298     int ret = 0;
2299 
2300     if (kvm_feature_msrs != NULL) {
2301         return 0;
2302     }
2303 
2304     if (!kvm_check_extension(s, KVM_CAP_GET_MSR_FEATURES)) {
2305         return 0;
2306     }
2307 
2308     struct kvm_msr_list msr_list;
2309 
2310     msr_list.nmsrs = 0;
2311     ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, &msr_list);
2312     if (ret < 0 && ret != -E2BIG) {
2313         error_report("Fetch KVM feature MSR list failed: %s",
2314             strerror(-ret));
2315         return ret;
2316     }
2317 
2318     assert(msr_list.nmsrs > 0);
2319     kvm_feature_msrs = g_malloc0(sizeof(msr_list) +
2320                  msr_list.nmsrs * sizeof(msr_list.indices[0]));
2321 
2322     kvm_feature_msrs->nmsrs = msr_list.nmsrs;
2323     ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, kvm_feature_msrs);
2324 
2325     if (ret < 0) {
2326         error_report("Fetch KVM feature MSR list failed: %s",
2327             strerror(-ret));
2328         g_free(kvm_feature_msrs);
2329         kvm_feature_msrs = NULL;
2330         return ret;
2331     }
2332 
2333     return 0;
2334 }
2335 
2336 static int kvm_get_supported_msrs(KVMState *s)
2337 {
2338     int ret = 0;
2339     struct kvm_msr_list msr_list, *kvm_msr_list;
2340 
2341     /*
2342      *  Obtain MSR list from KVM.  These are the MSRs that we must
2343      *  save/restore.
2344      */
2345     msr_list.nmsrs = 0;
2346     ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
2347     if (ret < 0 && ret != -E2BIG) {
2348         return ret;
2349     }
2350     /*
2351      * Old kernel modules had a bug and could write beyond the provided
2352      * memory. Allocate at least a safe amount of 1K.
2353      */
2354     kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
2355                                           msr_list.nmsrs *
2356                                           sizeof(msr_list.indices[0])));
2357 
2358     kvm_msr_list->nmsrs = msr_list.nmsrs;
2359     ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
2360     if (ret >= 0) {
2361         int i;
2362 
2363         for (i = 0; i < kvm_msr_list->nmsrs; i++) {
2364             switch (kvm_msr_list->indices[i]) {
2365             case MSR_STAR:
2366                 has_msr_star = true;
2367                 break;
2368             case MSR_VM_HSAVE_PA:
2369                 has_msr_hsave_pa = true;
2370                 break;
2371             case MSR_TSC_AUX:
2372                 has_msr_tsc_aux = true;
2373                 break;
2374             case MSR_TSC_ADJUST:
2375                 has_msr_tsc_adjust = true;
2376                 break;
2377             case MSR_IA32_TSCDEADLINE:
2378                 has_msr_tsc_deadline = true;
2379                 break;
2380             case MSR_IA32_SMBASE:
2381                 has_msr_smbase = true;
2382                 break;
2383             case MSR_SMI_COUNT:
2384                 has_msr_smi_count = true;
2385                 break;
2386             case MSR_IA32_MISC_ENABLE:
2387                 has_msr_misc_enable = true;
2388                 break;
2389             case MSR_IA32_BNDCFGS:
2390                 has_msr_bndcfgs = true;
2391                 break;
2392             case MSR_IA32_XSS:
2393                 has_msr_xss = true;
2394                 break;
2395             case MSR_IA32_UMWAIT_CONTROL:
2396                 has_msr_umwait = true;
2397                 break;
2398             case HV_X64_MSR_CRASH_CTL:
2399                 has_msr_hv_crash = true;
2400                 break;
2401             case HV_X64_MSR_RESET:
2402                 has_msr_hv_reset = true;
2403                 break;
2404             case HV_X64_MSR_VP_INDEX:
2405                 has_msr_hv_vpindex = true;
2406                 break;
2407             case HV_X64_MSR_VP_RUNTIME:
2408                 has_msr_hv_runtime = true;
2409                 break;
2410             case HV_X64_MSR_SCONTROL:
2411                 has_msr_hv_synic = true;
2412                 break;
2413             case HV_X64_MSR_STIMER0_CONFIG:
2414                 has_msr_hv_stimer = true;
2415                 break;
2416             case HV_X64_MSR_TSC_FREQUENCY:
2417                 has_msr_hv_frequencies = true;
2418                 break;
2419             case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2420                 has_msr_hv_reenlightenment = true;
2421                 break;
2422             case HV_X64_MSR_SYNDBG_OPTIONS:
2423                 has_msr_hv_syndbg_options = true;
2424                 break;
2425             case MSR_IA32_SPEC_CTRL:
2426                 has_msr_spec_ctrl = true;
2427                 break;
2428             case MSR_AMD64_TSC_RATIO:
2429                 has_tsc_scale_msr = true;
2430                 break;
2431             case MSR_IA32_TSX_CTRL:
2432                 has_msr_tsx_ctrl = true;
2433                 break;
2434             case MSR_VIRT_SSBD:
2435                 has_msr_virt_ssbd = true;
2436                 break;
2437             case MSR_IA32_ARCH_CAPABILITIES:
2438                 has_msr_arch_capabs = true;
2439                 break;
2440             case MSR_IA32_CORE_CAPABILITY:
2441                 has_msr_core_capabs = true;
2442                 break;
2443             case MSR_IA32_PERF_CAPABILITIES:
2444                 has_msr_perf_capabs = true;
2445                 break;
2446             case MSR_IA32_VMX_VMFUNC:
2447                 has_msr_vmx_vmfunc = true;
2448                 break;
2449             case MSR_IA32_UCODE_REV:
2450                 has_msr_ucode_rev = true;
2451                 break;
2452             case MSR_IA32_VMX_PROCBASED_CTLS2:
2453                 has_msr_vmx_procbased_ctls2 = true;
2454                 break;
2455             case MSR_IA32_PKRS:
2456                 has_msr_pkrs = true;
2457                 break;
2458             }
2459         }
2460     }
2461 
2462     g_free(kvm_msr_list);
2463 
2464     return ret;
2465 }
2466 
2467 static bool kvm_rdmsr_core_thread_count(X86CPU *cpu, uint32_t msr,
2468                                         uint64_t *val)
2469 {
2470     CPUState *cs = CPU(cpu);
2471 
2472     *val = cs->nr_threads * cs->nr_cores; /* thread count, bits 15..0 */
2473     *val |= ((uint32_t)cs->nr_cores << 16); /* core count, bits 31..16 */
2474 
2475     return true;
2476 }
2477 
2478 static Notifier smram_machine_done;
2479 static KVMMemoryListener smram_listener;
2480 static AddressSpace smram_address_space;
2481 static MemoryRegion smram_as_root;
2482 static MemoryRegion smram_as_mem;
2483 
2484 static void register_smram_listener(Notifier *n, void *unused)
2485 {
2486     MemoryRegion *smram =
2487         (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
2488 
2489     /* Outer container... */
2490     memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
2491     memory_region_set_enabled(&smram_as_root, true);
2492 
2493     /* ... with two regions inside: normal system memory with low
2494      * priority, and...
2495      */
2496     memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
2497                              get_system_memory(), 0, ~0ull);
2498     memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
2499     memory_region_set_enabled(&smram_as_mem, true);
2500 
2501     if (smram) {
2502         /* ... SMRAM with higher priority */
2503         memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
2504         memory_region_set_enabled(smram, true);
2505     }
2506 
2507     address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
2508     kvm_memory_listener_register(kvm_state, &smram_listener,
2509                                  &smram_address_space, 1, "kvm-smram");
2510 }
2511 
2512 int kvm_arch_get_default_type(MachineState *ms)
2513 {
2514     return 0;
2515 }
2516 
2517 int kvm_arch_init(MachineState *ms, KVMState *s)
2518 {
2519     uint64_t identity_base = 0xfffbc000;
2520     uint64_t shadow_mem;
2521     int ret;
2522     struct utsname utsname;
2523     Error *local_err = NULL;
2524 
2525     /*
2526      * Initialize SEV context, if required
2527      *
2528      * If no memory encryption is requested (ms->cgs == NULL) this is
2529      * a no-op.
2530      *
2531      * It's also a no-op if a non-SEV confidential guest support
2532      * mechanism is selected.  SEV is the only mechanism available to
2533      * select on x86 at present, so this doesn't arise, but if new
2534      * mechanisms are supported in future (e.g. TDX), they'll need
2535      * their own initialization either here or elsewhere.
2536      */
2537     ret = sev_kvm_init(ms->cgs, &local_err);
2538     if (ret < 0) {
2539         error_report_err(local_err);
2540         return ret;
2541     }
2542 
2543     has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
2544     has_sregs2 = kvm_check_extension(s, KVM_CAP_SREGS2) > 0;
2545 
2546     hv_vpindex_settable = kvm_check_extension(s, KVM_CAP_HYPERV_VP_INDEX);
2547 
2548     has_exception_payload = kvm_check_extension(s, KVM_CAP_EXCEPTION_PAYLOAD);
2549     if (has_exception_payload) {
2550         ret = kvm_vm_enable_cap(s, KVM_CAP_EXCEPTION_PAYLOAD, 0, true);
2551         if (ret < 0) {
2552             error_report("kvm: Failed to enable exception payload cap: %s",
2553                          strerror(-ret));
2554             return ret;
2555         }
2556     }
2557 
2558     has_triple_fault_event = kvm_check_extension(s, KVM_CAP_X86_TRIPLE_FAULT_EVENT);
2559     if (has_triple_fault_event) {
2560         ret = kvm_vm_enable_cap(s, KVM_CAP_X86_TRIPLE_FAULT_EVENT, 0, true);
2561         if (ret < 0) {
2562             error_report("kvm: Failed to enable triple fault event cap: %s",
2563                          strerror(-ret));
2564             return ret;
2565         }
2566     }
2567 
2568     if (s->xen_version) {
2569 #ifdef CONFIG_XEN_EMU
2570         if (!object_dynamic_cast(OBJECT(ms), TYPE_PC_MACHINE)) {
2571             error_report("kvm: Xen support only available in PC machine");
2572             return -ENOTSUP;
2573         }
2574         /* hyperv_enabled() doesn't work yet. */
2575         uint32_t msr = XEN_HYPERCALL_MSR;
2576         ret = kvm_xen_init(s, msr);
2577         if (ret < 0) {
2578             return ret;
2579         }
2580 #else
2581         error_report("kvm: Xen support not enabled in qemu");
2582         return -ENOTSUP;
2583 #endif
2584     }
2585 
2586     ret = kvm_get_supported_msrs(s);
2587     if (ret < 0) {
2588         return ret;
2589     }
2590 
2591     kvm_get_supported_feature_msrs(s);
2592 
2593     uname(&utsname);
2594     lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
2595 
2596     /*
2597      * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
2598      * In order to use vm86 mode, an EPT identity map and a TSS  are needed.
2599      * Since these must be part of guest physical memory, we need to allocate
2600      * them, both by setting their start addresses in the kernel and by
2601      * creating a corresponding e820 entry. We need 4 pages before the BIOS,
2602      * so this value allows up to 16M BIOSes.
2603      */
2604     identity_base = 0xfeffc000;
2605     ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
2606     if (ret < 0) {
2607         return ret;
2608     }
2609 
2610     /* Set TSS base one page after EPT identity map. */
2611     ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
2612     if (ret < 0) {
2613         return ret;
2614     }
2615 
2616     /* Tell fw_cfg to notify the BIOS to reserve the range. */
2617     ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
2618     if (ret < 0) {
2619         fprintf(stderr, "e820_add_entry() table is full\n");
2620         return ret;
2621     }
2622 
2623     shadow_mem = object_property_get_int(OBJECT(s), "kvm-shadow-mem", &error_abort);
2624     if (shadow_mem != -1) {
2625         shadow_mem /= 4096;
2626         ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
2627         if (ret < 0) {
2628             return ret;
2629         }
2630     }
2631 
2632     if (kvm_check_extension(s, KVM_CAP_X86_SMM) &&
2633         object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE) &&
2634         x86_machine_is_smm_enabled(X86_MACHINE(ms))) {
2635         smram_machine_done.notify = register_smram_listener;
2636         qemu_add_machine_init_done_notifier(&smram_machine_done);
2637     }
2638 
2639     if (enable_cpu_pm) {
2640         int disable_exits = kvm_check_extension(s, KVM_CAP_X86_DISABLE_EXITS);
2641 /* Work around for kernel header with a typo. TODO: fix header and drop. */
2642 #if defined(KVM_X86_DISABLE_EXITS_HTL) && !defined(KVM_X86_DISABLE_EXITS_HLT)
2643 #define KVM_X86_DISABLE_EXITS_HLT KVM_X86_DISABLE_EXITS_HTL
2644 #endif
2645         if (disable_exits) {
2646             disable_exits &= (KVM_X86_DISABLE_EXITS_MWAIT |
2647                               KVM_X86_DISABLE_EXITS_HLT |
2648                               KVM_X86_DISABLE_EXITS_PAUSE |
2649                               KVM_X86_DISABLE_EXITS_CSTATE);
2650         }
2651 
2652         ret = kvm_vm_enable_cap(s, KVM_CAP_X86_DISABLE_EXITS, 0,
2653                                 disable_exits);
2654         if (ret < 0) {
2655             error_report("kvm: guest stopping CPU not supported: %s",
2656                          strerror(-ret));
2657         }
2658     }
2659 
2660     if (object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE)) {
2661         X86MachineState *x86ms = X86_MACHINE(ms);
2662 
2663         if (x86ms->bus_lock_ratelimit > 0) {
2664             ret = kvm_check_extension(s, KVM_CAP_X86_BUS_LOCK_EXIT);
2665             if (!(ret & KVM_BUS_LOCK_DETECTION_EXIT)) {
2666                 error_report("kvm: bus lock detection unsupported");
2667                 return -ENOTSUP;
2668             }
2669             ret = kvm_vm_enable_cap(s, KVM_CAP_X86_BUS_LOCK_EXIT, 0,
2670                                     KVM_BUS_LOCK_DETECTION_EXIT);
2671             if (ret < 0) {
2672                 error_report("kvm: Failed to enable bus lock detection cap: %s",
2673                              strerror(-ret));
2674                 return ret;
2675             }
2676             ratelimit_init(&bus_lock_ratelimit_ctrl);
2677             ratelimit_set_speed(&bus_lock_ratelimit_ctrl,
2678                                 x86ms->bus_lock_ratelimit, BUS_LOCK_SLICE_TIME);
2679         }
2680     }
2681 
2682     if (s->notify_vmexit != NOTIFY_VMEXIT_OPTION_DISABLE &&
2683         kvm_check_extension(s, KVM_CAP_X86_NOTIFY_VMEXIT)) {
2684             uint64_t notify_window_flags =
2685                 ((uint64_t)s->notify_window << 32) |
2686                 KVM_X86_NOTIFY_VMEXIT_ENABLED |
2687                 KVM_X86_NOTIFY_VMEXIT_USER;
2688             ret = kvm_vm_enable_cap(s, KVM_CAP_X86_NOTIFY_VMEXIT, 0,
2689                                     notify_window_flags);
2690             if (ret < 0) {
2691                 error_report("kvm: Failed to enable notify vmexit cap: %s",
2692                              strerror(-ret));
2693                 return ret;
2694             }
2695     }
2696     if (kvm_vm_check_extension(s, KVM_CAP_X86_USER_SPACE_MSR)) {
2697         bool r;
2698 
2699         ret = kvm_vm_enable_cap(s, KVM_CAP_X86_USER_SPACE_MSR, 0,
2700                                 KVM_MSR_EXIT_REASON_FILTER);
2701         if (ret) {
2702             error_report("Could not enable user space MSRs: %s",
2703                          strerror(-ret));
2704             exit(1);
2705         }
2706 
2707         r = kvm_filter_msr(s, MSR_CORE_THREAD_COUNT,
2708                            kvm_rdmsr_core_thread_count, NULL);
2709         if (!r) {
2710             error_report("Could not install MSR_CORE_THREAD_COUNT handler: %s",
2711                          strerror(-ret));
2712             exit(1);
2713         }
2714     }
2715 
2716     return 0;
2717 }
2718 
2719 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2720 {
2721     lhs->selector = rhs->selector;
2722     lhs->base = rhs->base;
2723     lhs->limit = rhs->limit;
2724     lhs->type = 3;
2725     lhs->present = 1;
2726     lhs->dpl = 3;
2727     lhs->db = 0;
2728     lhs->s = 1;
2729     lhs->l = 0;
2730     lhs->g = 0;
2731     lhs->avl = 0;
2732     lhs->unusable = 0;
2733 }
2734 
2735 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2736 {
2737     unsigned flags = rhs->flags;
2738     lhs->selector = rhs->selector;
2739     lhs->base = rhs->base;
2740     lhs->limit = rhs->limit;
2741     lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
2742     lhs->present = (flags & DESC_P_MASK) != 0;
2743     lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
2744     lhs->db = (flags >> DESC_B_SHIFT) & 1;
2745     lhs->s = (flags & DESC_S_MASK) != 0;
2746     lhs->l = (flags >> DESC_L_SHIFT) & 1;
2747     lhs->g = (flags & DESC_G_MASK) != 0;
2748     lhs->avl = (flags & DESC_AVL_MASK) != 0;
2749     lhs->unusable = !lhs->present;
2750     lhs->padding = 0;
2751 }
2752 
2753 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
2754 {
2755     lhs->selector = rhs->selector;
2756     lhs->base = rhs->base;
2757     lhs->limit = rhs->limit;
2758     lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
2759                  ((rhs->present && !rhs->unusable) * DESC_P_MASK) |
2760                  (rhs->dpl << DESC_DPL_SHIFT) |
2761                  (rhs->db << DESC_B_SHIFT) |
2762                  (rhs->s * DESC_S_MASK) |
2763                  (rhs->l << DESC_L_SHIFT) |
2764                  (rhs->g * DESC_G_MASK) |
2765                  (rhs->avl * DESC_AVL_MASK);
2766 }
2767 
2768 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
2769 {
2770     if (set) {
2771         *kvm_reg = *qemu_reg;
2772     } else {
2773         *qemu_reg = *kvm_reg;
2774     }
2775 }
2776 
2777 static int kvm_getput_regs(X86CPU *cpu, int set)
2778 {
2779     CPUX86State *env = &cpu->env;
2780     struct kvm_regs regs;
2781     int ret = 0;
2782 
2783     if (!set) {
2784         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
2785         if (ret < 0) {
2786             return ret;
2787         }
2788     }
2789 
2790     kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
2791     kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
2792     kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
2793     kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
2794     kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
2795     kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
2796     kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
2797     kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
2798 #ifdef TARGET_X86_64
2799     kvm_getput_reg(&regs.r8, &env->regs[8], set);
2800     kvm_getput_reg(&regs.r9, &env->regs[9], set);
2801     kvm_getput_reg(&regs.r10, &env->regs[10], set);
2802     kvm_getput_reg(&regs.r11, &env->regs[11], set);
2803     kvm_getput_reg(&regs.r12, &env->regs[12], set);
2804     kvm_getput_reg(&regs.r13, &env->regs[13], set);
2805     kvm_getput_reg(&regs.r14, &env->regs[14], set);
2806     kvm_getput_reg(&regs.r15, &env->regs[15], set);
2807 #endif
2808 
2809     kvm_getput_reg(&regs.rflags, &env->eflags, set);
2810     kvm_getput_reg(&regs.rip, &env->eip, set);
2811 
2812     if (set) {
2813         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
2814     }
2815 
2816     return ret;
2817 }
2818 
2819 static int kvm_put_xsave(X86CPU *cpu)
2820 {
2821     CPUX86State *env = &cpu->env;
2822     void *xsave = env->xsave_buf;
2823 
2824     x86_cpu_xsave_all_areas(cpu, xsave, env->xsave_buf_len);
2825 
2826     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
2827 }
2828 
2829 static int kvm_put_xcrs(X86CPU *cpu)
2830 {
2831     CPUX86State *env = &cpu->env;
2832     struct kvm_xcrs xcrs = {};
2833 
2834     if (!has_xcrs) {
2835         return 0;
2836     }
2837 
2838     xcrs.nr_xcrs = 1;
2839     xcrs.flags = 0;
2840     xcrs.xcrs[0].xcr = 0;
2841     xcrs.xcrs[0].value = env->xcr0;
2842     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
2843 }
2844 
2845 static int kvm_put_sregs(X86CPU *cpu)
2846 {
2847     CPUX86State *env = &cpu->env;
2848     struct kvm_sregs sregs;
2849 
2850     /*
2851      * The interrupt_bitmap is ignored because KVM_SET_SREGS is
2852      * always followed by KVM_SET_VCPU_EVENTS.
2853      */
2854     memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
2855 
2856     if ((env->eflags & VM_MASK)) {
2857         set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
2858         set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
2859         set_v8086_seg(&sregs.es, &env->segs[R_ES]);
2860         set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
2861         set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
2862         set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
2863     } else {
2864         set_seg(&sregs.cs, &env->segs[R_CS]);
2865         set_seg(&sregs.ds, &env->segs[R_DS]);
2866         set_seg(&sregs.es, &env->segs[R_ES]);
2867         set_seg(&sregs.fs, &env->segs[R_FS]);
2868         set_seg(&sregs.gs, &env->segs[R_GS]);
2869         set_seg(&sregs.ss, &env->segs[R_SS]);
2870     }
2871 
2872     set_seg(&sregs.tr, &env->tr);
2873     set_seg(&sregs.ldt, &env->ldt);
2874 
2875     sregs.idt.limit = env->idt.limit;
2876     sregs.idt.base = env->idt.base;
2877     memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
2878     sregs.gdt.limit = env->gdt.limit;
2879     sregs.gdt.base = env->gdt.base;
2880     memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
2881 
2882     sregs.cr0 = env->cr[0];
2883     sregs.cr2 = env->cr[2];
2884     sregs.cr3 = env->cr[3];
2885     sregs.cr4 = env->cr[4];
2886 
2887     sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
2888     sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
2889 
2890     sregs.efer = env->efer;
2891 
2892     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
2893 }
2894 
2895 static int kvm_put_sregs2(X86CPU *cpu)
2896 {
2897     CPUX86State *env = &cpu->env;
2898     struct kvm_sregs2 sregs;
2899     int i;
2900 
2901     sregs.flags = 0;
2902 
2903     if ((env->eflags & VM_MASK)) {
2904         set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
2905         set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
2906         set_v8086_seg(&sregs.es, &env->segs[R_ES]);
2907         set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
2908         set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
2909         set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
2910     } else {
2911         set_seg(&sregs.cs, &env->segs[R_CS]);
2912         set_seg(&sregs.ds, &env->segs[R_DS]);
2913         set_seg(&sregs.es, &env->segs[R_ES]);
2914         set_seg(&sregs.fs, &env->segs[R_FS]);
2915         set_seg(&sregs.gs, &env->segs[R_GS]);
2916         set_seg(&sregs.ss, &env->segs[R_SS]);
2917     }
2918 
2919     set_seg(&sregs.tr, &env->tr);
2920     set_seg(&sregs.ldt, &env->ldt);
2921 
2922     sregs.idt.limit = env->idt.limit;
2923     sregs.idt.base = env->idt.base;
2924     memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
2925     sregs.gdt.limit = env->gdt.limit;
2926     sregs.gdt.base = env->gdt.base;
2927     memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
2928 
2929     sregs.cr0 = env->cr[0];
2930     sregs.cr2 = env->cr[2];
2931     sregs.cr3 = env->cr[3];
2932     sregs.cr4 = env->cr[4];
2933 
2934     sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
2935     sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
2936 
2937     sregs.efer = env->efer;
2938 
2939     if (env->pdptrs_valid) {
2940         for (i = 0; i < 4; i++) {
2941             sregs.pdptrs[i] = env->pdptrs[i];
2942         }
2943         sregs.flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
2944     }
2945 
2946     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS2, &sregs);
2947 }
2948 
2949 
2950 static void kvm_msr_buf_reset(X86CPU *cpu)
2951 {
2952     memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
2953 }
2954 
2955 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
2956 {
2957     struct kvm_msrs *msrs = cpu->kvm_msr_buf;
2958     void *limit = ((void *)msrs) + MSR_BUF_SIZE;
2959     struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
2960 
2961     assert((void *)(entry + 1) <= limit);
2962 
2963     entry->index = index;
2964     entry->reserved = 0;
2965     entry->data = value;
2966     msrs->nmsrs++;
2967 }
2968 
2969 static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
2970 {
2971     kvm_msr_buf_reset(cpu);
2972     kvm_msr_entry_add(cpu, index, value);
2973 
2974     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
2975 }
2976 
2977 static int kvm_get_one_msr(X86CPU *cpu, int index, uint64_t *value)
2978 {
2979     int ret;
2980     struct {
2981         struct kvm_msrs info;
2982         struct kvm_msr_entry entries[1];
2983     } msr_data = {
2984         .info.nmsrs = 1,
2985         .entries[0].index = index,
2986     };
2987 
2988     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
2989     if (ret < 0) {
2990         return ret;
2991     }
2992     assert(ret == 1);
2993     *value = msr_data.entries[0].data;
2994     return ret;
2995 }
2996 void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
2997 {
2998     int ret;
2999 
3000     ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
3001     assert(ret == 1);
3002 }
3003 
3004 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
3005 {
3006     CPUX86State *env = &cpu->env;
3007     int ret;
3008 
3009     if (!has_msr_tsc_deadline) {
3010         return 0;
3011     }
3012 
3013     ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
3014     if (ret < 0) {
3015         return ret;
3016     }
3017 
3018     assert(ret == 1);
3019     return 0;
3020 }
3021 
3022 /*
3023  * Provide a separate write service for the feature control MSR in order to
3024  * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
3025  * before writing any other state because forcibly leaving nested mode
3026  * invalidates the VCPU state.
3027  */
3028 static int kvm_put_msr_feature_control(X86CPU *cpu)
3029 {
3030     int ret;
3031 
3032     if (!has_msr_feature_control) {
3033         return 0;
3034     }
3035 
3036     ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
3037                           cpu->env.msr_ia32_feature_control);
3038     if (ret < 0) {
3039         return ret;
3040     }
3041 
3042     assert(ret == 1);
3043     return 0;
3044 }
3045 
3046 static uint64_t make_vmx_msr_value(uint32_t index, uint32_t features)
3047 {
3048     uint32_t default1, can_be_one, can_be_zero;
3049     uint32_t must_be_one;
3050 
3051     switch (index) {
3052     case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3053         default1 = 0x00000016;
3054         break;
3055     case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3056         default1 = 0x0401e172;
3057         break;
3058     case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3059         default1 = 0x000011ff;
3060         break;
3061     case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3062         default1 = 0x00036dff;
3063         break;
3064     case MSR_IA32_VMX_PROCBASED_CTLS2:
3065         default1 = 0;
3066         break;
3067     default:
3068         abort();
3069     }
3070 
3071     /* If a feature bit is set, the control can be either set or clear.
3072      * Otherwise the value is limited to either 0 or 1 by default1.
3073      */
3074     can_be_one = features | default1;
3075     can_be_zero = features | ~default1;
3076     must_be_one = ~can_be_zero;
3077 
3078     /*
3079      * Bit 0:31 -> 0 if the control bit can be zero (i.e. 1 if it must be one).
3080      * Bit 32:63 -> 1 if the control bit can be one.
3081      */
3082     return must_be_one | (((uint64_t)can_be_one) << 32);
3083 }
3084 
3085 static void kvm_msr_entry_add_vmx(X86CPU *cpu, FeatureWordArray f)
3086 {
3087     uint64_t kvm_vmx_basic =
3088         kvm_arch_get_supported_msr_feature(kvm_state,
3089                                            MSR_IA32_VMX_BASIC);
3090 
3091     if (!kvm_vmx_basic) {
3092         /* If the kernel doesn't support VMX feature (kvm_intel.nested=0),
3093          * then kvm_vmx_basic will be 0 and KVM_SET_MSR will fail.
3094          */
3095         return;
3096     }
3097 
3098     uint64_t kvm_vmx_misc =
3099         kvm_arch_get_supported_msr_feature(kvm_state,
3100                                            MSR_IA32_VMX_MISC);
3101     uint64_t kvm_vmx_ept_vpid =
3102         kvm_arch_get_supported_msr_feature(kvm_state,
3103                                            MSR_IA32_VMX_EPT_VPID_CAP);
3104 
3105     /*
3106      * If the guest is 64-bit, a value of 1 is allowed for the host address
3107      * space size vmexit control.
3108      */
3109     uint64_t fixed_vmx_exit = f[FEAT_8000_0001_EDX] & CPUID_EXT2_LM
3110         ? (uint64_t)VMX_VM_EXIT_HOST_ADDR_SPACE_SIZE << 32 : 0;
3111 
3112     /*
3113      * Bits 0-30, 32-44 and 50-53 come from the host.  KVM should
3114      * not change them for backwards compatibility.
3115      */
3116     uint64_t fixed_vmx_basic = kvm_vmx_basic &
3117         (MSR_VMX_BASIC_VMCS_REVISION_MASK |
3118          MSR_VMX_BASIC_VMXON_REGION_SIZE_MASK |
3119          MSR_VMX_BASIC_VMCS_MEM_TYPE_MASK);
3120 
3121     /*
3122      * Same for bits 0-4 and 25-27.  Bits 16-24 (CR3 target count) can
3123      * change in the future but are always zero for now, clear them to be
3124      * future proof.  Bits 32-63 in theory could change, though KVM does
3125      * not support dual-monitor treatment and probably never will; mask
3126      * them out as well.
3127      */
3128     uint64_t fixed_vmx_misc = kvm_vmx_misc &
3129         (MSR_VMX_MISC_PREEMPTION_TIMER_SHIFT_MASK |
3130          MSR_VMX_MISC_MAX_MSR_LIST_SIZE_MASK);
3131 
3132     /*
3133      * EPT memory types should not change either, so we do not bother
3134      * adding features for them.
3135      */
3136     uint64_t fixed_vmx_ept_mask =
3137             (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_ENABLE_EPT ?
3138              MSR_VMX_EPT_UC | MSR_VMX_EPT_WB : 0);
3139     uint64_t fixed_vmx_ept_vpid = kvm_vmx_ept_vpid & fixed_vmx_ept_mask;
3140 
3141     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
3142                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
3143                                          f[FEAT_VMX_PROCBASED_CTLS]));
3144     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PINBASED_CTLS,
3145                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_PINBASED_CTLS,
3146                                          f[FEAT_VMX_PINBASED_CTLS]));
3147     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_EXIT_CTLS,
3148                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_EXIT_CTLS,
3149                                          f[FEAT_VMX_EXIT_CTLS]) | fixed_vmx_exit);
3150     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_ENTRY_CTLS,
3151                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_ENTRY_CTLS,
3152                                          f[FEAT_VMX_ENTRY_CTLS]));
3153     kvm_msr_entry_add(cpu, MSR_IA32_VMX_PROCBASED_CTLS2,
3154                       make_vmx_msr_value(MSR_IA32_VMX_PROCBASED_CTLS2,
3155                                          f[FEAT_VMX_SECONDARY_CTLS]));
3156     kvm_msr_entry_add(cpu, MSR_IA32_VMX_EPT_VPID_CAP,
3157                       f[FEAT_VMX_EPT_VPID_CAPS] | fixed_vmx_ept_vpid);
3158     kvm_msr_entry_add(cpu, MSR_IA32_VMX_BASIC,
3159                       f[FEAT_VMX_BASIC] | fixed_vmx_basic);
3160     kvm_msr_entry_add(cpu, MSR_IA32_VMX_MISC,
3161                       f[FEAT_VMX_MISC] | fixed_vmx_misc);
3162     if (has_msr_vmx_vmfunc) {
3163         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMFUNC, f[FEAT_VMX_VMFUNC]);
3164     }
3165 
3166     /*
3167      * Just to be safe, write these with constant values.  The CRn_FIXED1
3168      * MSRs are generated by KVM based on the vCPU's CPUID.
3169      */
3170     kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR0_FIXED0,
3171                       CR0_PE_MASK | CR0_PG_MASK | CR0_NE_MASK);
3172     kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR4_FIXED0,
3173                       CR4_VMXE_MASK);
3174 
3175     if (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_TSC_SCALING) {
3176         /* TSC multiplier (0x2032).  */
3177         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x32);
3178     } else {
3179         /* Preemption timer (0x482E).  */
3180         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x2E);
3181     }
3182 }
3183 
3184 static void kvm_msr_entry_add_perf(X86CPU *cpu, FeatureWordArray f)
3185 {
3186     uint64_t kvm_perf_cap =
3187         kvm_arch_get_supported_msr_feature(kvm_state,
3188                                            MSR_IA32_PERF_CAPABILITIES);
3189 
3190     if (kvm_perf_cap) {
3191         kvm_msr_entry_add(cpu, MSR_IA32_PERF_CAPABILITIES,
3192                         kvm_perf_cap & f[FEAT_PERF_CAPABILITIES]);
3193     }
3194 }
3195 
3196 static int kvm_buf_set_msrs(X86CPU *cpu)
3197 {
3198     int ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
3199     if (ret < 0) {
3200         return ret;
3201     }
3202 
3203     if (ret < cpu->kvm_msr_buf->nmsrs) {
3204         struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
3205         error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,
3206                      (uint32_t)e->index, (uint64_t)e->data);
3207     }
3208 
3209     assert(ret == cpu->kvm_msr_buf->nmsrs);
3210     return 0;
3211 }
3212 
3213 static void kvm_init_msrs(X86CPU *cpu)
3214 {
3215     CPUX86State *env = &cpu->env;
3216 
3217     kvm_msr_buf_reset(cpu);
3218     if (has_msr_arch_capabs) {
3219         kvm_msr_entry_add(cpu, MSR_IA32_ARCH_CAPABILITIES,
3220                           env->features[FEAT_ARCH_CAPABILITIES]);
3221     }
3222 
3223     if (has_msr_core_capabs) {
3224         kvm_msr_entry_add(cpu, MSR_IA32_CORE_CAPABILITY,
3225                           env->features[FEAT_CORE_CAPABILITY]);
3226     }
3227 
3228     if (has_msr_perf_capabs && cpu->enable_pmu) {
3229         kvm_msr_entry_add_perf(cpu, env->features);
3230     }
3231 
3232     if (has_msr_ucode_rev) {
3233         kvm_msr_entry_add(cpu, MSR_IA32_UCODE_REV, cpu->ucode_rev);
3234     }
3235 
3236     /*
3237      * Older kernels do not include VMX MSRs in KVM_GET_MSR_INDEX_LIST, but
3238      * all kernels with MSR features should have them.
3239      */
3240     if (kvm_feature_msrs && cpu_has_vmx(env)) {
3241         kvm_msr_entry_add_vmx(cpu, env->features);
3242     }
3243 
3244     assert(kvm_buf_set_msrs(cpu) == 0);
3245 }
3246 
3247 static int kvm_put_msrs(X86CPU *cpu, int level)
3248 {
3249     CPUX86State *env = &cpu->env;
3250     int i;
3251 
3252     kvm_msr_buf_reset(cpu);
3253 
3254     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
3255     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
3256     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
3257     kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
3258     if (has_msr_star) {
3259         kvm_msr_entry_add(cpu, MSR_STAR, env->star);
3260     }
3261     if (has_msr_hsave_pa) {
3262         kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
3263     }
3264     if (has_msr_tsc_aux) {
3265         kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
3266     }
3267     if (has_msr_tsc_adjust) {
3268         kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
3269     }
3270     if (has_msr_misc_enable) {
3271         kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
3272                           env->msr_ia32_misc_enable);
3273     }
3274     if (has_msr_smbase) {
3275         kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
3276     }
3277     if (has_msr_smi_count) {
3278         kvm_msr_entry_add(cpu, MSR_SMI_COUNT, env->msr_smi_count);
3279     }
3280     if (has_msr_pkrs) {
3281         kvm_msr_entry_add(cpu, MSR_IA32_PKRS, env->pkrs);
3282     }
3283     if (has_msr_bndcfgs) {
3284         kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
3285     }
3286     if (has_msr_xss) {
3287         kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
3288     }
3289     if (has_msr_umwait) {
3290         kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, env->umwait);
3291     }
3292     if (has_msr_spec_ctrl) {
3293         kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, env->spec_ctrl);
3294     }
3295     if (has_tsc_scale_msr) {
3296         kvm_msr_entry_add(cpu, MSR_AMD64_TSC_RATIO, env->amd_tsc_scale_msr);
3297     }
3298 
3299     if (has_msr_tsx_ctrl) {
3300         kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, env->tsx_ctrl);
3301     }
3302     if (has_msr_virt_ssbd) {
3303         kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, env->virt_ssbd);
3304     }
3305 
3306 #ifdef TARGET_X86_64
3307     if (lm_capable_kernel) {
3308         kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
3309         kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
3310         kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
3311         kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
3312     }
3313 #endif
3314 
3315     /*
3316      * The following MSRs have side effects on the guest or are too heavy
3317      * for normal writeback. Limit them to reset or full state updates.
3318      */
3319     if (level >= KVM_PUT_RESET_STATE) {
3320         kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
3321         kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
3322         kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
3323         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
3324             kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, env->async_pf_int_msr);
3325         }
3326         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
3327             kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
3328         }
3329         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
3330             kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
3331         }
3332         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
3333             kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
3334         }
3335 
3336         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
3337             kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, env->poll_control_msr);
3338         }
3339 
3340         if (has_architectural_pmu_version > 0) {
3341             if (has_architectural_pmu_version > 1) {
3342                 /* Stop the counter.  */
3343                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
3344                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
3345             }
3346 
3347             /* Set the counter values.  */
3348             for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
3349                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
3350                                   env->msr_fixed_counters[i]);
3351             }
3352             for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
3353                 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
3354                                   env->msr_gp_counters[i]);
3355                 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
3356                                   env->msr_gp_evtsel[i]);
3357             }
3358             if (has_architectural_pmu_version > 1) {
3359                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
3360                                   env->msr_global_status);
3361                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
3362                                   env->msr_global_ovf_ctrl);
3363 
3364                 /* Now start the PMU.  */
3365                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
3366                                   env->msr_fixed_ctr_ctrl);
3367                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
3368                                   env->msr_global_ctrl);
3369             }
3370         }
3371         /*
3372          * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,
3373          * only sync them to KVM on the first cpu
3374          */
3375         if (current_cpu == first_cpu) {
3376             if (has_msr_hv_hypercall) {
3377                 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
3378                                   env->msr_hv_guest_os_id);
3379                 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
3380                                   env->msr_hv_hypercall);
3381             }
3382             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
3383                 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,
3384                                   env->msr_hv_tsc);
3385             }
3386             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
3387                 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL,
3388                                   env->msr_hv_reenlightenment_control);
3389                 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL,
3390                                   env->msr_hv_tsc_emulation_control);
3391                 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS,
3392                                   env->msr_hv_tsc_emulation_status);
3393             }
3394 #ifdef CONFIG_SYNDBG
3395             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNDBG) &&
3396                 has_msr_hv_syndbg_options) {
3397                 kvm_msr_entry_add(cpu, HV_X64_MSR_SYNDBG_OPTIONS,
3398                                   hyperv_syndbg_query_options());
3399             }
3400 #endif
3401         }
3402         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3403             kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
3404                               env->msr_hv_vapic);
3405         }
3406         if (has_msr_hv_crash) {
3407             int j;
3408 
3409             for (j = 0; j < HV_CRASH_PARAMS; j++)
3410                 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
3411                                   env->msr_hv_crash_params[j]);
3412 
3413             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);
3414         }
3415         if (has_msr_hv_runtime) {
3416             kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
3417         }
3418         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)
3419             && hv_vpindex_settable) {
3420             kvm_msr_entry_add(cpu, HV_X64_MSR_VP_INDEX,
3421                               hyperv_vp_index(CPU(cpu)));
3422         }
3423         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3424             int j;
3425 
3426             kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);
3427 
3428             kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
3429                               env->msr_hv_synic_control);
3430             kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
3431                               env->msr_hv_synic_evt_page);
3432             kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
3433                               env->msr_hv_synic_msg_page);
3434 
3435             for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
3436                 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
3437                                   env->msr_hv_synic_sint[j]);
3438             }
3439         }
3440         if (has_msr_hv_stimer) {
3441             int j;
3442 
3443             for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
3444                 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
3445                                 env->msr_hv_stimer_config[j]);
3446             }
3447 
3448             for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
3449                 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
3450                                 env->msr_hv_stimer_count[j]);
3451             }
3452         }
3453         if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3454             uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
3455 
3456             kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
3457             kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
3458             kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
3459             kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
3460             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
3461             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
3462             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
3463             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
3464             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
3465             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
3466             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
3467             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
3468             for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
3469                 /* The CPU GPs if we write to a bit above the physical limit of
3470                  * the host CPU (and KVM emulates that)
3471                  */
3472                 uint64_t mask = env->mtrr_var[i].mask;
3473                 mask &= phys_mask;
3474 
3475                 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
3476                                   env->mtrr_var[i].base);
3477                 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
3478             }
3479         }
3480         if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
3481             int addr_num = kvm_arch_get_supported_cpuid(kvm_state,
3482                                                     0x14, 1, R_EAX) & 0x7;
3483 
3484             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL,
3485                             env->msr_rtit_ctrl);
3486             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS,
3487                             env->msr_rtit_status);
3488             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE,
3489                             env->msr_rtit_output_base);
3490             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK,
3491                             env->msr_rtit_output_mask);
3492             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH,
3493                             env->msr_rtit_cr3_match);
3494             for (i = 0; i < addr_num; i++) {
3495                 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i,
3496                             env->msr_rtit_addrs[i]);
3497             }
3498         }
3499 
3500         if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_SGX_LC) {
3501             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH0,
3502                               env->msr_ia32_sgxlepubkeyhash[0]);
3503             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH1,
3504                               env->msr_ia32_sgxlepubkeyhash[1]);
3505             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH2,
3506                               env->msr_ia32_sgxlepubkeyhash[2]);
3507             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH3,
3508                               env->msr_ia32_sgxlepubkeyhash[3]);
3509         }
3510 
3511         if (env->features[FEAT_XSAVE] & CPUID_D_1_EAX_XFD) {
3512             kvm_msr_entry_add(cpu, MSR_IA32_XFD,
3513                               env->msr_xfd);
3514             kvm_msr_entry_add(cpu, MSR_IA32_XFD_ERR,
3515                               env->msr_xfd_err);
3516         }
3517 
3518         if (kvm_enabled() && cpu->enable_pmu &&
3519             (env->features[FEAT_7_0_EDX] & CPUID_7_0_EDX_ARCH_LBR)) {
3520             uint64_t depth;
3521             int ret;
3522 
3523             /*
3524              * Only migrate Arch LBR states when the host Arch LBR depth
3525              * equals that of source guest's, this is to avoid mismatch
3526              * of guest/host config for the msr hence avoid unexpected
3527              * misbehavior.
3528              */
3529             ret = kvm_get_one_msr(cpu, MSR_ARCH_LBR_DEPTH, &depth);
3530 
3531             if (ret == 1 && !!depth && depth == env->msr_lbr_depth) {
3532                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_CTL, env->msr_lbr_ctl);
3533                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_DEPTH, env->msr_lbr_depth);
3534 
3535                 for (i = 0; i < ARCH_LBR_NR_ENTRIES; i++) {
3536                     if (!env->lbr_records[i].from) {
3537                         continue;
3538                     }
3539                     kvm_msr_entry_add(cpu, MSR_ARCH_LBR_FROM_0 + i,
3540                                       env->lbr_records[i].from);
3541                     kvm_msr_entry_add(cpu, MSR_ARCH_LBR_TO_0 + i,
3542                                       env->lbr_records[i].to);
3543                     kvm_msr_entry_add(cpu, MSR_ARCH_LBR_INFO_0 + i,
3544                                       env->lbr_records[i].info);
3545                 }
3546             }
3547         }
3548 
3549         /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
3550          *       kvm_put_msr_feature_control. */
3551     }
3552 
3553     if (env->mcg_cap) {
3554         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
3555         kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
3556         if (has_msr_mcg_ext_ctl) {
3557             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
3558         }
3559         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3560             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
3561         }
3562     }
3563 
3564     return kvm_buf_set_msrs(cpu);
3565 }
3566 
3567 
3568 static int kvm_get_xsave(X86CPU *cpu)
3569 {
3570     CPUX86State *env = &cpu->env;
3571     void *xsave = env->xsave_buf;
3572     int type, ret;
3573 
3574     type = has_xsave2 ? KVM_GET_XSAVE2 : KVM_GET_XSAVE;
3575     ret = kvm_vcpu_ioctl(CPU(cpu), type, xsave);
3576     if (ret < 0) {
3577         return ret;
3578     }
3579     x86_cpu_xrstor_all_areas(cpu, xsave, env->xsave_buf_len);
3580 
3581     return 0;
3582 }
3583 
3584 static int kvm_get_xcrs(X86CPU *cpu)
3585 {
3586     CPUX86State *env = &cpu->env;
3587     int i, ret;
3588     struct kvm_xcrs xcrs;
3589 
3590     if (!has_xcrs) {
3591         return 0;
3592     }
3593 
3594     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
3595     if (ret < 0) {
3596         return ret;
3597     }
3598 
3599     for (i = 0; i < xcrs.nr_xcrs; i++) {
3600         /* Only support xcr0 now */
3601         if (xcrs.xcrs[i].xcr == 0) {
3602             env->xcr0 = xcrs.xcrs[i].value;
3603             break;
3604         }
3605     }
3606     return 0;
3607 }
3608 
3609 static int kvm_get_sregs(X86CPU *cpu)
3610 {
3611     CPUX86State *env = &cpu->env;
3612     struct kvm_sregs sregs;
3613     int ret;
3614 
3615     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
3616     if (ret < 0) {
3617         return ret;
3618     }
3619 
3620     /*
3621      * The interrupt_bitmap is ignored because KVM_GET_SREGS is
3622      * always preceded by KVM_GET_VCPU_EVENTS.
3623      */
3624 
3625     get_seg(&env->segs[R_CS], &sregs.cs);
3626     get_seg(&env->segs[R_DS], &sregs.ds);
3627     get_seg(&env->segs[R_ES], &sregs.es);
3628     get_seg(&env->segs[R_FS], &sregs.fs);
3629     get_seg(&env->segs[R_GS], &sregs.gs);
3630     get_seg(&env->segs[R_SS], &sregs.ss);
3631 
3632     get_seg(&env->tr, &sregs.tr);
3633     get_seg(&env->ldt, &sregs.ldt);
3634 
3635     env->idt.limit = sregs.idt.limit;
3636     env->idt.base = sregs.idt.base;
3637     env->gdt.limit = sregs.gdt.limit;
3638     env->gdt.base = sregs.gdt.base;
3639 
3640     env->cr[0] = sregs.cr0;
3641     env->cr[2] = sregs.cr2;
3642     env->cr[3] = sregs.cr3;
3643     env->cr[4] = sregs.cr4;
3644 
3645     env->efer = sregs.efer;
3646 
3647     /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
3648     x86_update_hflags(env);
3649 
3650     return 0;
3651 }
3652 
3653 static int kvm_get_sregs2(X86CPU *cpu)
3654 {
3655     CPUX86State *env = &cpu->env;
3656     struct kvm_sregs2 sregs;
3657     int i, ret;
3658 
3659     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS2, &sregs);
3660     if (ret < 0) {
3661         return ret;
3662     }
3663 
3664     get_seg(&env->segs[R_CS], &sregs.cs);
3665     get_seg(&env->segs[R_DS], &sregs.ds);
3666     get_seg(&env->segs[R_ES], &sregs.es);
3667     get_seg(&env->segs[R_FS], &sregs.fs);
3668     get_seg(&env->segs[R_GS], &sregs.gs);
3669     get_seg(&env->segs[R_SS], &sregs.ss);
3670 
3671     get_seg(&env->tr, &sregs.tr);
3672     get_seg(&env->ldt, &sregs.ldt);
3673 
3674     env->idt.limit = sregs.idt.limit;
3675     env->idt.base = sregs.idt.base;
3676     env->gdt.limit = sregs.gdt.limit;
3677     env->gdt.base = sregs.gdt.base;
3678 
3679     env->cr[0] = sregs.cr0;
3680     env->cr[2] = sregs.cr2;
3681     env->cr[3] = sregs.cr3;
3682     env->cr[4] = sregs.cr4;
3683 
3684     env->efer = sregs.efer;
3685 
3686     env->pdptrs_valid = sregs.flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
3687 
3688     if (env->pdptrs_valid) {
3689         for (i = 0; i < 4; i++) {
3690             env->pdptrs[i] = sregs.pdptrs[i];
3691         }
3692     }
3693 
3694     /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
3695     x86_update_hflags(env);
3696 
3697     return 0;
3698 }
3699 
3700 static int kvm_get_msrs(X86CPU *cpu)
3701 {
3702     CPUX86State *env = &cpu->env;
3703     struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
3704     int ret, i;
3705     uint64_t mtrr_top_bits;
3706 
3707     kvm_msr_buf_reset(cpu);
3708 
3709     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
3710     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
3711     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
3712     kvm_msr_entry_add(cpu, MSR_PAT, 0);
3713     if (has_msr_star) {
3714         kvm_msr_entry_add(cpu, MSR_STAR, 0);
3715     }
3716     if (has_msr_hsave_pa) {
3717         kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
3718     }
3719     if (has_msr_tsc_aux) {
3720         kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
3721     }
3722     if (has_msr_tsc_adjust) {
3723         kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
3724     }
3725     if (has_msr_tsc_deadline) {
3726         kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
3727     }
3728     if (has_msr_misc_enable) {
3729         kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
3730     }
3731     if (has_msr_smbase) {
3732         kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
3733     }
3734     if (has_msr_smi_count) {
3735         kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
3736     }
3737     if (has_msr_feature_control) {
3738         kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
3739     }
3740     if (has_msr_pkrs) {
3741         kvm_msr_entry_add(cpu, MSR_IA32_PKRS, 0);
3742     }
3743     if (has_msr_bndcfgs) {
3744         kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
3745     }
3746     if (has_msr_xss) {
3747         kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
3748     }
3749     if (has_msr_umwait) {
3750         kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, 0);
3751     }
3752     if (has_msr_spec_ctrl) {
3753         kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
3754     }
3755     if (has_tsc_scale_msr) {
3756         kvm_msr_entry_add(cpu, MSR_AMD64_TSC_RATIO, 0);
3757     }
3758 
3759     if (has_msr_tsx_ctrl) {
3760         kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, 0);
3761     }
3762     if (has_msr_virt_ssbd) {
3763         kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, 0);
3764     }
3765     if (!env->tsc_valid) {
3766         kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
3767         env->tsc_valid = !runstate_is_running();
3768     }
3769 
3770 #ifdef TARGET_X86_64
3771     if (lm_capable_kernel) {
3772         kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
3773         kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
3774         kvm_msr_entry_add(cpu, MSR_FMASK, 0);
3775         kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
3776     }
3777 #endif
3778     kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
3779     kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
3780     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
3781         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, 0);
3782     }
3783     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
3784         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
3785     }
3786     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
3787         kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
3788     }
3789     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
3790         kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
3791     }
3792     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
3793         kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, 1);
3794     }
3795     if (has_architectural_pmu_version > 0) {
3796         if (has_architectural_pmu_version > 1) {
3797             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
3798             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
3799             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
3800             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
3801         }
3802         for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
3803             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
3804         }
3805         for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
3806             kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
3807             kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
3808         }
3809     }
3810 
3811     if (env->mcg_cap) {
3812         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
3813         kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
3814         if (has_msr_mcg_ext_ctl) {
3815             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
3816         }
3817         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3818             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
3819         }
3820     }
3821 
3822     if (has_msr_hv_hypercall) {
3823         kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
3824         kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
3825     }
3826     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3827         kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
3828     }
3829     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
3830         kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
3831     }
3832     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
3833         kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL, 0);
3834         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL, 0);
3835         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS, 0);
3836     }
3837     if (has_msr_hv_syndbg_options) {
3838         kvm_msr_entry_add(cpu, HV_X64_MSR_SYNDBG_OPTIONS, 0);
3839     }
3840     if (has_msr_hv_crash) {
3841         int j;
3842 
3843         for (j = 0; j < HV_CRASH_PARAMS; j++) {
3844             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
3845         }
3846     }
3847     if (has_msr_hv_runtime) {
3848         kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
3849     }
3850     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3851         uint32_t msr;
3852 
3853         kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
3854         kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
3855         kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
3856         for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
3857             kvm_msr_entry_add(cpu, msr, 0);
3858         }
3859     }
3860     if (has_msr_hv_stimer) {
3861         uint32_t msr;
3862 
3863         for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
3864              msr++) {
3865             kvm_msr_entry_add(cpu, msr, 0);
3866         }
3867     }
3868     if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3869         kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
3870         kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
3871         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
3872         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
3873         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
3874         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
3875         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
3876         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
3877         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
3878         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
3879         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
3880         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
3881         for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
3882             kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
3883             kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
3884         }
3885     }
3886 
3887     if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
3888         int addr_num =
3889             kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
3890 
3891         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
3892         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
3893         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
3894         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
3895         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
3896         for (i = 0; i < addr_num; i++) {
3897             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
3898         }
3899     }
3900 
3901     if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_SGX_LC) {
3902         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH0, 0);
3903         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH1, 0);
3904         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH2, 0);
3905         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH3, 0);
3906     }
3907 
3908     if (env->features[FEAT_XSAVE] & CPUID_D_1_EAX_XFD) {
3909         kvm_msr_entry_add(cpu, MSR_IA32_XFD, 0);
3910         kvm_msr_entry_add(cpu, MSR_IA32_XFD_ERR, 0);
3911     }
3912 
3913     if (kvm_enabled() && cpu->enable_pmu &&
3914         (env->features[FEAT_7_0_EDX] & CPUID_7_0_EDX_ARCH_LBR)) {
3915         uint64_t depth;
3916 
3917         ret = kvm_get_one_msr(cpu, MSR_ARCH_LBR_DEPTH, &depth);
3918         if (ret == 1 && depth == ARCH_LBR_NR_ENTRIES) {
3919             kvm_msr_entry_add(cpu, MSR_ARCH_LBR_CTL, 0);
3920             kvm_msr_entry_add(cpu, MSR_ARCH_LBR_DEPTH, 0);
3921 
3922             for (i = 0; i < ARCH_LBR_NR_ENTRIES; i++) {
3923                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_FROM_0 + i, 0);
3924                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_TO_0 + i, 0);
3925                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_INFO_0 + i, 0);
3926             }
3927         }
3928     }
3929 
3930     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
3931     if (ret < 0) {
3932         return ret;
3933     }
3934 
3935     if (ret < cpu->kvm_msr_buf->nmsrs) {
3936         struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
3937         error_report("error: failed to get MSR 0x%" PRIx32,
3938                      (uint32_t)e->index);
3939     }
3940 
3941     assert(ret == cpu->kvm_msr_buf->nmsrs);
3942     /*
3943      * MTRR masks: Each mask consists of 5 parts
3944      * a  10..0: must be zero
3945      * b  11   : valid bit
3946      * c n-1.12: actual mask bits
3947      * d  51..n: reserved must be zero
3948      * e  63.52: reserved must be zero
3949      *
3950      * 'n' is the number of physical bits supported by the CPU and is
3951      * apparently always <= 52.   We know our 'n' but don't know what
3952      * the destinations 'n' is; it might be smaller, in which case
3953      * it masks (c) on loading. It might be larger, in which case
3954      * we fill 'd' so that d..c is consistent irrespetive of the 'n'
3955      * we're migrating to.
3956      */
3957 
3958     if (cpu->fill_mtrr_mask) {
3959         QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
3960         assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
3961         mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
3962     } else {
3963         mtrr_top_bits = 0;
3964     }
3965 
3966     for (i = 0; i < ret; i++) {
3967         uint32_t index = msrs[i].index;
3968         switch (index) {
3969         case MSR_IA32_SYSENTER_CS:
3970             env->sysenter_cs = msrs[i].data;
3971             break;
3972         case MSR_IA32_SYSENTER_ESP:
3973             env->sysenter_esp = msrs[i].data;
3974             break;
3975         case MSR_IA32_SYSENTER_EIP:
3976             env->sysenter_eip = msrs[i].data;
3977             break;
3978         case MSR_PAT:
3979             env->pat = msrs[i].data;
3980             break;
3981         case MSR_STAR:
3982             env->star = msrs[i].data;
3983             break;
3984 #ifdef TARGET_X86_64
3985         case MSR_CSTAR:
3986             env->cstar = msrs[i].data;
3987             break;
3988         case MSR_KERNELGSBASE:
3989             env->kernelgsbase = msrs[i].data;
3990             break;
3991         case MSR_FMASK:
3992             env->fmask = msrs[i].data;
3993             break;
3994         case MSR_LSTAR:
3995             env->lstar = msrs[i].data;
3996             break;
3997 #endif
3998         case MSR_IA32_TSC:
3999             env->tsc = msrs[i].data;
4000             break;
4001         case MSR_TSC_AUX:
4002             env->tsc_aux = msrs[i].data;
4003             break;
4004         case MSR_TSC_ADJUST:
4005             env->tsc_adjust = msrs[i].data;
4006             break;
4007         case MSR_IA32_TSCDEADLINE:
4008             env->tsc_deadline = msrs[i].data;
4009             break;
4010         case MSR_VM_HSAVE_PA:
4011             env->vm_hsave = msrs[i].data;
4012             break;
4013         case MSR_KVM_SYSTEM_TIME:
4014             env->system_time_msr = msrs[i].data;
4015             break;
4016         case MSR_KVM_WALL_CLOCK:
4017             env->wall_clock_msr = msrs[i].data;
4018             break;
4019         case MSR_MCG_STATUS:
4020             env->mcg_status = msrs[i].data;
4021             break;
4022         case MSR_MCG_CTL:
4023             env->mcg_ctl = msrs[i].data;
4024             break;
4025         case MSR_MCG_EXT_CTL:
4026             env->mcg_ext_ctl = msrs[i].data;
4027             break;
4028         case MSR_IA32_MISC_ENABLE:
4029             env->msr_ia32_misc_enable = msrs[i].data;
4030             break;
4031         case MSR_IA32_SMBASE:
4032             env->smbase = msrs[i].data;
4033             break;
4034         case MSR_SMI_COUNT:
4035             env->msr_smi_count = msrs[i].data;
4036             break;
4037         case MSR_IA32_FEATURE_CONTROL:
4038             env->msr_ia32_feature_control = msrs[i].data;
4039             break;
4040         case MSR_IA32_BNDCFGS:
4041             env->msr_bndcfgs = msrs[i].data;
4042             break;
4043         case MSR_IA32_XSS:
4044             env->xss = msrs[i].data;
4045             break;
4046         case MSR_IA32_UMWAIT_CONTROL:
4047             env->umwait = msrs[i].data;
4048             break;
4049         case MSR_IA32_PKRS:
4050             env->pkrs = msrs[i].data;
4051             break;
4052         default:
4053             if (msrs[i].index >= MSR_MC0_CTL &&
4054                 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
4055                 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
4056             }
4057             break;
4058         case MSR_KVM_ASYNC_PF_EN:
4059             env->async_pf_en_msr = msrs[i].data;
4060             break;
4061         case MSR_KVM_ASYNC_PF_INT:
4062             env->async_pf_int_msr = msrs[i].data;
4063             break;
4064         case MSR_KVM_PV_EOI_EN:
4065             env->pv_eoi_en_msr = msrs[i].data;
4066             break;
4067         case MSR_KVM_STEAL_TIME:
4068             env->steal_time_msr = msrs[i].data;
4069             break;
4070         case MSR_KVM_POLL_CONTROL: {
4071             env->poll_control_msr = msrs[i].data;
4072             break;
4073         }
4074         case MSR_CORE_PERF_FIXED_CTR_CTRL:
4075             env->msr_fixed_ctr_ctrl = msrs[i].data;
4076             break;
4077         case MSR_CORE_PERF_GLOBAL_CTRL:
4078             env->msr_global_ctrl = msrs[i].data;
4079             break;
4080         case MSR_CORE_PERF_GLOBAL_STATUS:
4081             env->msr_global_status = msrs[i].data;
4082             break;
4083         case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
4084             env->msr_global_ovf_ctrl = msrs[i].data;
4085             break;
4086         case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
4087             env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
4088             break;
4089         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
4090             env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
4091             break;
4092         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
4093             env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
4094             break;
4095         case HV_X64_MSR_HYPERCALL:
4096             env->msr_hv_hypercall = msrs[i].data;
4097             break;
4098         case HV_X64_MSR_GUEST_OS_ID:
4099             env->msr_hv_guest_os_id = msrs[i].data;
4100             break;
4101         case HV_X64_MSR_APIC_ASSIST_PAGE:
4102             env->msr_hv_vapic = msrs[i].data;
4103             break;
4104         case HV_X64_MSR_REFERENCE_TSC:
4105             env->msr_hv_tsc = msrs[i].data;
4106             break;
4107         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4108             env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
4109             break;
4110         case HV_X64_MSR_VP_RUNTIME:
4111             env->msr_hv_runtime = msrs[i].data;
4112             break;
4113         case HV_X64_MSR_SCONTROL:
4114             env->msr_hv_synic_control = msrs[i].data;
4115             break;
4116         case HV_X64_MSR_SIEFP:
4117             env->msr_hv_synic_evt_page = msrs[i].data;
4118             break;
4119         case HV_X64_MSR_SIMP:
4120             env->msr_hv_synic_msg_page = msrs[i].data;
4121             break;
4122         case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
4123             env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
4124             break;
4125         case HV_X64_MSR_STIMER0_CONFIG:
4126         case HV_X64_MSR_STIMER1_CONFIG:
4127         case HV_X64_MSR_STIMER2_CONFIG:
4128         case HV_X64_MSR_STIMER3_CONFIG:
4129             env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
4130                                 msrs[i].data;
4131             break;
4132         case HV_X64_MSR_STIMER0_COUNT:
4133         case HV_X64_MSR_STIMER1_COUNT:
4134         case HV_X64_MSR_STIMER2_COUNT:
4135         case HV_X64_MSR_STIMER3_COUNT:
4136             env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
4137                                 msrs[i].data;
4138             break;
4139         case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4140             env->msr_hv_reenlightenment_control = msrs[i].data;
4141             break;
4142         case HV_X64_MSR_TSC_EMULATION_CONTROL:
4143             env->msr_hv_tsc_emulation_control = msrs[i].data;
4144             break;
4145         case HV_X64_MSR_TSC_EMULATION_STATUS:
4146             env->msr_hv_tsc_emulation_status = msrs[i].data;
4147             break;
4148         case HV_X64_MSR_SYNDBG_OPTIONS:
4149             env->msr_hv_syndbg_options = msrs[i].data;
4150             break;
4151         case MSR_MTRRdefType:
4152             env->mtrr_deftype = msrs[i].data;
4153             break;
4154         case MSR_MTRRfix64K_00000:
4155             env->mtrr_fixed[0] = msrs[i].data;
4156             break;
4157         case MSR_MTRRfix16K_80000:
4158             env->mtrr_fixed[1] = msrs[i].data;
4159             break;
4160         case MSR_MTRRfix16K_A0000:
4161             env->mtrr_fixed[2] = msrs[i].data;
4162             break;
4163         case MSR_MTRRfix4K_C0000:
4164             env->mtrr_fixed[3] = msrs[i].data;
4165             break;
4166         case MSR_MTRRfix4K_C8000:
4167             env->mtrr_fixed[4] = msrs[i].data;
4168             break;
4169         case MSR_MTRRfix4K_D0000:
4170             env->mtrr_fixed[5] = msrs[i].data;
4171             break;
4172         case MSR_MTRRfix4K_D8000:
4173             env->mtrr_fixed[6] = msrs[i].data;
4174             break;
4175         case MSR_MTRRfix4K_E0000:
4176             env->mtrr_fixed[7] = msrs[i].data;
4177             break;
4178         case MSR_MTRRfix4K_E8000:
4179             env->mtrr_fixed[8] = msrs[i].data;
4180             break;
4181         case MSR_MTRRfix4K_F0000:
4182             env->mtrr_fixed[9] = msrs[i].data;
4183             break;
4184         case MSR_MTRRfix4K_F8000:
4185             env->mtrr_fixed[10] = msrs[i].data;
4186             break;
4187         case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
4188             if (index & 1) {
4189                 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
4190                                                                mtrr_top_bits;
4191             } else {
4192                 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
4193             }
4194             break;
4195         case MSR_IA32_SPEC_CTRL:
4196             env->spec_ctrl = msrs[i].data;
4197             break;
4198         case MSR_AMD64_TSC_RATIO:
4199             env->amd_tsc_scale_msr = msrs[i].data;
4200             break;
4201         case MSR_IA32_TSX_CTRL:
4202             env->tsx_ctrl = msrs[i].data;
4203             break;
4204         case MSR_VIRT_SSBD:
4205             env->virt_ssbd = msrs[i].data;
4206             break;
4207         case MSR_IA32_RTIT_CTL:
4208             env->msr_rtit_ctrl = msrs[i].data;
4209             break;
4210         case MSR_IA32_RTIT_STATUS:
4211             env->msr_rtit_status = msrs[i].data;
4212             break;
4213         case MSR_IA32_RTIT_OUTPUT_BASE:
4214             env->msr_rtit_output_base = msrs[i].data;
4215             break;
4216         case MSR_IA32_RTIT_OUTPUT_MASK:
4217             env->msr_rtit_output_mask = msrs[i].data;
4218             break;
4219         case MSR_IA32_RTIT_CR3_MATCH:
4220             env->msr_rtit_cr3_match = msrs[i].data;
4221             break;
4222         case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
4223             env->msr_rtit_addrs[index - MSR_IA32_RTIT_ADDR0_A] = msrs[i].data;
4224             break;
4225         case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
4226             env->msr_ia32_sgxlepubkeyhash[index - MSR_IA32_SGXLEPUBKEYHASH0] =
4227                            msrs[i].data;
4228             break;
4229         case MSR_IA32_XFD:
4230             env->msr_xfd = msrs[i].data;
4231             break;
4232         case MSR_IA32_XFD_ERR:
4233             env->msr_xfd_err = msrs[i].data;
4234             break;
4235         case MSR_ARCH_LBR_CTL:
4236             env->msr_lbr_ctl = msrs[i].data;
4237             break;
4238         case MSR_ARCH_LBR_DEPTH:
4239             env->msr_lbr_depth = msrs[i].data;
4240             break;
4241         case MSR_ARCH_LBR_FROM_0 ... MSR_ARCH_LBR_FROM_0 + 31:
4242             env->lbr_records[index - MSR_ARCH_LBR_FROM_0].from = msrs[i].data;
4243             break;
4244         case MSR_ARCH_LBR_TO_0 ... MSR_ARCH_LBR_TO_0 + 31:
4245             env->lbr_records[index - MSR_ARCH_LBR_TO_0].to = msrs[i].data;
4246             break;
4247         case MSR_ARCH_LBR_INFO_0 ... MSR_ARCH_LBR_INFO_0 + 31:
4248             env->lbr_records[index - MSR_ARCH_LBR_INFO_0].info = msrs[i].data;
4249             break;
4250         }
4251     }
4252 
4253     return 0;
4254 }
4255 
4256 static int kvm_put_mp_state(X86CPU *cpu)
4257 {
4258     struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
4259 
4260     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
4261 }
4262 
4263 static int kvm_get_mp_state(X86CPU *cpu)
4264 {
4265     CPUState *cs = CPU(cpu);
4266     CPUX86State *env = &cpu->env;
4267     struct kvm_mp_state mp_state;
4268     int ret;
4269 
4270     ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
4271     if (ret < 0) {
4272         return ret;
4273     }
4274     env->mp_state = mp_state.mp_state;
4275     if (kvm_irqchip_in_kernel()) {
4276         cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
4277     }
4278     return 0;
4279 }
4280 
4281 static int kvm_get_apic(X86CPU *cpu)
4282 {
4283     DeviceState *apic = cpu->apic_state;
4284     struct kvm_lapic_state kapic;
4285     int ret;
4286 
4287     if (apic && kvm_irqchip_in_kernel()) {
4288         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
4289         if (ret < 0) {
4290             return ret;
4291         }
4292 
4293         kvm_get_apic_state(apic, &kapic);
4294     }
4295     return 0;
4296 }
4297 
4298 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
4299 {
4300     CPUState *cs = CPU(cpu);
4301     CPUX86State *env = &cpu->env;
4302     struct kvm_vcpu_events events = {};
4303 
4304     events.flags = 0;
4305 
4306     if (has_exception_payload) {
4307         events.flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
4308         events.exception.pending = env->exception_pending;
4309         events.exception_has_payload = env->exception_has_payload;
4310         events.exception_payload = env->exception_payload;
4311     }
4312     events.exception.nr = env->exception_nr;
4313     events.exception.injected = env->exception_injected;
4314     events.exception.has_error_code = env->has_error_code;
4315     events.exception.error_code = env->error_code;
4316 
4317     events.interrupt.injected = (env->interrupt_injected >= 0);
4318     events.interrupt.nr = env->interrupt_injected;
4319     events.interrupt.soft = env->soft_interrupt;
4320 
4321     events.nmi.injected = env->nmi_injected;
4322     events.nmi.pending = env->nmi_pending;
4323     events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
4324 
4325     events.sipi_vector = env->sipi_vector;
4326 
4327     if (has_msr_smbase) {
4328         events.smi.smm = !!(env->hflags & HF_SMM_MASK);
4329         events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
4330         if (kvm_irqchip_in_kernel()) {
4331             /* As soon as these are moved to the kernel, remove them
4332              * from cs->interrupt_request.
4333              */
4334             events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
4335             events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
4336             cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
4337         } else {
4338             /* Keep these in cs->interrupt_request.  */
4339             events.smi.pending = 0;
4340             events.smi.latched_init = 0;
4341         }
4342         /* Stop SMI delivery on old machine types to avoid a reboot
4343          * on an inward migration of an old VM.
4344          */
4345         if (!cpu->kvm_no_smi_migration) {
4346             events.flags |= KVM_VCPUEVENT_VALID_SMM;
4347         }
4348     }
4349 
4350     if (level >= KVM_PUT_RESET_STATE) {
4351         events.flags |= KVM_VCPUEVENT_VALID_NMI_PENDING;
4352         if (env->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
4353             events.flags |= KVM_VCPUEVENT_VALID_SIPI_VECTOR;
4354         }
4355     }
4356 
4357     if (has_triple_fault_event) {
4358         events.flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
4359         events.triple_fault.pending = env->triple_fault_pending;
4360     }
4361 
4362     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
4363 }
4364 
4365 static int kvm_get_vcpu_events(X86CPU *cpu)
4366 {
4367     CPUX86State *env = &cpu->env;
4368     struct kvm_vcpu_events events;
4369     int ret;
4370 
4371     memset(&events, 0, sizeof(events));
4372     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
4373     if (ret < 0) {
4374        return ret;
4375     }
4376 
4377     if (events.flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4378         env->exception_pending = events.exception.pending;
4379         env->exception_has_payload = events.exception_has_payload;
4380         env->exception_payload = events.exception_payload;
4381     } else {
4382         env->exception_pending = 0;
4383         env->exception_has_payload = false;
4384     }
4385     env->exception_injected = events.exception.injected;
4386     env->exception_nr =
4387         (env->exception_pending || env->exception_injected) ?
4388         events.exception.nr : -1;
4389     env->has_error_code = events.exception.has_error_code;
4390     env->error_code = events.exception.error_code;
4391 
4392     env->interrupt_injected =
4393         events.interrupt.injected ? events.interrupt.nr : -1;
4394     env->soft_interrupt = events.interrupt.soft;
4395 
4396     env->nmi_injected = events.nmi.injected;
4397     env->nmi_pending = events.nmi.pending;
4398     if (events.nmi.masked) {
4399         env->hflags2 |= HF2_NMI_MASK;
4400     } else {
4401         env->hflags2 &= ~HF2_NMI_MASK;
4402     }
4403 
4404     if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
4405         if (events.smi.smm) {
4406             env->hflags |= HF_SMM_MASK;
4407         } else {
4408             env->hflags &= ~HF_SMM_MASK;
4409         }
4410         if (events.smi.pending) {
4411             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
4412         } else {
4413             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
4414         }
4415         if (events.smi.smm_inside_nmi) {
4416             env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
4417         } else {
4418             env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
4419         }
4420         if (events.smi.latched_init) {
4421             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
4422         } else {
4423             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
4424         }
4425     }
4426 
4427     if (events.flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
4428         env->triple_fault_pending = events.triple_fault.pending;
4429     }
4430 
4431     env->sipi_vector = events.sipi_vector;
4432 
4433     return 0;
4434 }
4435 
4436 static int kvm_put_debugregs(X86CPU *cpu)
4437 {
4438     CPUX86State *env = &cpu->env;
4439     struct kvm_debugregs dbgregs;
4440     int i;
4441 
4442     memset(&dbgregs, 0, sizeof(dbgregs));
4443     for (i = 0; i < 4; i++) {
4444         dbgregs.db[i] = env->dr[i];
4445     }
4446     dbgregs.dr6 = env->dr[6];
4447     dbgregs.dr7 = env->dr[7];
4448     dbgregs.flags = 0;
4449 
4450     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
4451 }
4452 
4453 static int kvm_get_debugregs(X86CPU *cpu)
4454 {
4455     CPUX86State *env = &cpu->env;
4456     struct kvm_debugregs dbgregs;
4457     int i, ret;
4458 
4459     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
4460     if (ret < 0) {
4461         return ret;
4462     }
4463     for (i = 0; i < 4; i++) {
4464         env->dr[i] = dbgregs.db[i];
4465     }
4466     env->dr[4] = env->dr[6] = dbgregs.dr6;
4467     env->dr[5] = env->dr[7] = dbgregs.dr7;
4468 
4469     return 0;
4470 }
4471 
4472 static int kvm_put_nested_state(X86CPU *cpu)
4473 {
4474     CPUX86State *env = &cpu->env;
4475     int max_nested_state_len = kvm_max_nested_state_length();
4476 
4477     if (!env->nested_state) {
4478         return 0;
4479     }
4480 
4481     /*
4482      * Copy flags that are affected by reset from env->hflags and env->hflags2.
4483      */
4484     if (env->hflags & HF_GUEST_MASK) {
4485         env->nested_state->flags |= KVM_STATE_NESTED_GUEST_MODE;
4486     } else {
4487         env->nested_state->flags &= ~KVM_STATE_NESTED_GUEST_MODE;
4488     }
4489 
4490     /* Don't set KVM_STATE_NESTED_GIF_SET on VMX as it is illegal */
4491     if (cpu_has_svm(env) && (env->hflags2 & HF2_GIF_MASK)) {
4492         env->nested_state->flags |= KVM_STATE_NESTED_GIF_SET;
4493     } else {
4494         env->nested_state->flags &= ~KVM_STATE_NESTED_GIF_SET;
4495     }
4496 
4497     assert(env->nested_state->size <= max_nested_state_len);
4498     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_NESTED_STATE, env->nested_state);
4499 }
4500 
4501 static int kvm_get_nested_state(X86CPU *cpu)
4502 {
4503     CPUX86State *env = &cpu->env;
4504     int max_nested_state_len = kvm_max_nested_state_length();
4505     int ret;
4506 
4507     if (!env->nested_state) {
4508         return 0;
4509     }
4510 
4511     /*
4512      * It is possible that migration restored a smaller size into
4513      * nested_state->hdr.size than what our kernel support.
4514      * We preserve migration origin nested_state->hdr.size for
4515      * call to KVM_SET_NESTED_STATE but wish that our next call
4516      * to KVM_GET_NESTED_STATE will use max size our kernel support.
4517      */
4518     env->nested_state->size = max_nested_state_len;
4519 
4520     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_NESTED_STATE, env->nested_state);
4521     if (ret < 0) {
4522         return ret;
4523     }
4524 
4525     /*
4526      * Copy flags that are affected by reset to env->hflags and env->hflags2.
4527      */
4528     if (env->nested_state->flags & KVM_STATE_NESTED_GUEST_MODE) {
4529         env->hflags |= HF_GUEST_MASK;
4530     } else {
4531         env->hflags &= ~HF_GUEST_MASK;
4532     }
4533 
4534     /* Keep HF2_GIF_MASK set on !SVM as x86_cpu_pending_interrupt() needs it */
4535     if (cpu_has_svm(env)) {
4536         if (env->nested_state->flags & KVM_STATE_NESTED_GIF_SET) {
4537             env->hflags2 |= HF2_GIF_MASK;
4538         } else {
4539             env->hflags2 &= ~HF2_GIF_MASK;
4540         }
4541     }
4542 
4543     return ret;
4544 }
4545 
4546 int kvm_arch_put_registers(CPUState *cpu, int level)
4547 {
4548     X86CPU *x86_cpu = X86_CPU(cpu);
4549     int ret;
4550 
4551     assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
4552 
4553     /*
4554      * Put MSR_IA32_FEATURE_CONTROL first, this ensures the VM gets out of VMX
4555      * root operation upon vCPU reset. kvm_put_msr_feature_control() should also
4556      * precede kvm_put_nested_state() when 'real' nested state is set.
4557      */
4558     if (level >= KVM_PUT_RESET_STATE) {
4559         ret = kvm_put_msr_feature_control(x86_cpu);
4560         if (ret < 0) {
4561             return ret;
4562         }
4563     }
4564 
4565     /* must be before kvm_put_nested_state so that EFER.SVME is set */
4566     ret = has_sregs2 ? kvm_put_sregs2(x86_cpu) : kvm_put_sregs(x86_cpu);
4567     if (ret < 0) {
4568         return ret;
4569     }
4570 
4571     if (level >= KVM_PUT_RESET_STATE) {
4572         ret = kvm_put_nested_state(x86_cpu);
4573         if (ret < 0) {
4574             return ret;
4575         }
4576     }
4577 
4578     if (level == KVM_PUT_FULL_STATE) {
4579         /* We don't check for kvm_arch_set_tsc_khz() errors here,
4580          * because TSC frequency mismatch shouldn't abort migration,
4581          * unless the user explicitly asked for a more strict TSC
4582          * setting (e.g. using an explicit "tsc-freq" option).
4583          */
4584         kvm_arch_set_tsc_khz(cpu);
4585     }
4586 
4587 #ifdef CONFIG_XEN_EMU
4588     if (xen_mode == XEN_EMULATE && level == KVM_PUT_FULL_STATE) {
4589         ret = kvm_put_xen_state(cpu);
4590         if (ret < 0) {
4591             return ret;
4592         }
4593     }
4594 #endif
4595 
4596     ret = kvm_getput_regs(x86_cpu, 1);
4597     if (ret < 0) {
4598         return ret;
4599     }
4600     ret = kvm_put_xsave(x86_cpu);
4601     if (ret < 0) {
4602         return ret;
4603     }
4604     ret = kvm_put_xcrs(x86_cpu);
4605     if (ret < 0) {
4606         return ret;
4607     }
4608     ret = kvm_put_msrs(x86_cpu, level);
4609     if (ret < 0) {
4610         return ret;
4611     }
4612     ret = kvm_put_vcpu_events(x86_cpu, level);
4613     if (ret < 0) {
4614         return ret;
4615     }
4616     if (level >= KVM_PUT_RESET_STATE) {
4617         ret = kvm_put_mp_state(x86_cpu);
4618         if (ret < 0) {
4619             return ret;
4620         }
4621     }
4622 
4623     ret = kvm_put_tscdeadline_msr(x86_cpu);
4624     if (ret < 0) {
4625         return ret;
4626     }
4627     ret = kvm_put_debugregs(x86_cpu);
4628     if (ret < 0) {
4629         return ret;
4630     }
4631     return 0;
4632 }
4633 
4634 int kvm_arch_get_registers(CPUState *cs)
4635 {
4636     X86CPU *cpu = X86_CPU(cs);
4637     int ret;
4638 
4639     assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
4640 
4641     ret = kvm_get_vcpu_events(cpu);
4642     if (ret < 0) {
4643         goto out;
4644     }
4645     /*
4646      * KVM_GET_MPSTATE can modify CS and RIP, call it before
4647      * KVM_GET_REGS and KVM_GET_SREGS.
4648      */
4649     ret = kvm_get_mp_state(cpu);
4650     if (ret < 0) {
4651         goto out;
4652     }
4653     ret = kvm_getput_regs(cpu, 0);
4654     if (ret < 0) {
4655         goto out;
4656     }
4657     ret = kvm_get_xsave(cpu);
4658     if (ret < 0) {
4659         goto out;
4660     }
4661     ret = kvm_get_xcrs(cpu);
4662     if (ret < 0) {
4663         goto out;
4664     }
4665     ret = has_sregs2 ? kvm_get_sregs2(cpu) : kvm_get_sregs(cpu);
4666     if (ret < 0) {
4667         goto out;
4668     }
4669     ret = kvm_get_msrs(cpu);
4670     if (ret < 0) {
4671         goto out;
4672     }
4673     ret = kvm_get_apic(cpu);
4674     if (ret < 0) {
4675         goto out;
4676     }
4677     ret = kvm_get_debugregs(cpu);
4678     if (ret < 0) {
4679         goto out;
4680     }
4681     ret = kvm_get_nested_state(cpu);
4682     if (ret < 0) {
4683         goto out;
4684     }
4685 #ifdef CONFIG_XEN_EMU
4686     if (xen_mode == XEN_EMULATE) {
4687         ret = kvm_get_xen_state(cs);
4688         if (ret < 0) {
4689             goto out;
4690         }
4691     }
4692 #endif
4693     ret = 0;
4694  out:
4695     cpu_sync_bndcs_hflags(&cpu->env);
4696     return ret;
4697 }
4698 
4699 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
4700 {
4701     X86CPU *x86_cpu = X86_CPU(cpu);
4702     CPUX86State *env = &x86_cpu->env;
4703     int ret;
4704 
4705     /* Inject NMI */
4706     if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
4707         if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
4708             qemu_mutex_lock_iothread();
4709             cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
4710             qemu_mutex_unlock_iothread();
4711             DPRINTF("injected NMI\n");
4712             ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
4713             if (ret < 0) {
4714                 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
4715                         strerror(-ret));
4716             }
4717         }
4718         if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
4719             qemu_mutex_lock_iothread();
4720             cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
4721             qemu_mutex_unlock_iothread();
4722             DPRINTF("injected SMI\n");
4723             ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
4724             if (ret < 0) {
4725                 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
4726                         strerror(-ret));
4727             }
4728         }
4729     }
4730 
4731     if (!kvm_pic_in_kernel()) {
4732         qemu_mutex_lock_iothread();
4733     }
4734 
4735     /* Force the VCPU out of its inner loop to process any INIT requests
4736      * or (for userspace APIC, but it is cheap to combine the checks here)
4737      * pending TPR access reports.
4738      */
4739     if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
4740         if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
4741             !(env->hflags & HF_SMM_MASK)) {
4742             cpu->exit_request = 1;
4743         }
4744         if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
4745             cpu->exit_request = 1;
4746         }
4747     }
4748 
4749     if (!kvm_pic_in_kernel()) {
4750         /* Try to inject an interrupt if the guest can accept it */
4751         if (run->ready_for_interrupt_injection &&
4752             (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
4753             (env->eflags & IF_MASK)) {
4754             int irq;
4755 
4756             cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
4757             irq = cpu_get_pic_interrupt(env);
4758             if (irq >= 0) {
4759                 struct kvm_interrupt intr;
4760 
4761                 intr.irq = irq;
4762                 DPRINTF("injected interrupt %d\n", irq);
4763                 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
4764                 if (ret < 0) {
4765                     fprintf(stderr,
4766                             "KVM: injection failed, interrupt lost (%s)\n",
4767                             strerror(-ret));
4768                 }
4769             }
4770         }
4771 
4772         /* If we have an interrupt but the guest is not ready to receive an
4773          * interrupt, request an interrupt window exit.  This will
4774          * cause a return to userspace as soon as the guest is ready to
4775          * receive interrupts. */
4776         if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
4777             run->request_interrupt_window = 1;
4778         } else {
4779             run->request_interrupt_window = 0;
4780         }
4781 
4782         DPRINTF("setting tpr\n");
4783         run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
4784 
4785         qemu_mutex_unlock_iothread();
4786     }
4787 }
4788 
4789 static void kvm_rate_limit_on_bus_lock(void)
4790 {
4791     uint64_t delay_ns = ratelimit_calculate_delay(&bus_lock_ratelimit_ctrl, 1);
4792 
4793     if (delay_ns) {
4794         g_usleep(delay_ns / SCALE_US);
4795     }
4796 }
4797 
4798 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
4799 {
4800     X86CPU *x86_cpu = X86_CPU(cpu);
4801     CPUX86State *env = &x86_cpu->env;
4802 
4803     if (run->flags & KVM_RUN_X86_SMM) {
4804         env->hflags |= HF_SMM_MASK;
4805     } else {
4806         env->hflags &= ~HF_SMM_MASK;
4807     }
4808     if (run->if_flag) {
4809         env->eflags |= IF_MASK;
4810     } else {
4811         env->eflags &= ~IF_MASK;
4812     }
4813     if (run->flags & KVM_RUN_X86_BUS_LOCK) {
4814         kvm_rate_limit_on_bus_lock();
4815     }
4816 
4817 #ifdef CONFIG_XEN_EMU
4818     /*
4819      * If the callback is asserted as a GSI (or PCI INTx) then check if
4820      * vcpu_info->evtchn_upcall_pending has been cleared, and deassert
4821      * the callback IRQ if so. Ideally we could hook into the PIC/IOAPIC
4822      * EOI and only resample then, exactly how the VFIO eventfd pairs
4823      * are designed to work for level triggered interrupts.
4824      */
4825     if (x86_cpu->env.xen_callback_asserted) {
4826         kvm_xen_maybe_deassert_callback(cpu);
4827     }
4828 #endif
4829 
4830     /* We need to protect the apic state against concurrent accesses from
4831      * different threads in case the userspace irqchip is used. */
4832     if (!kvm_irqchip_in_kernel()) {
4833         qemu_mutex_lock_iothread();
4834     }
4835     cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
4836     cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
4837     if (!kvm_irqchip_in_kernel()) {
4838         qemu_mutex_unlock_iothread();
4839     }
4840     return cpu_get_mem_attrs(env);
4841 }
4842 
4843 int kvm_arch_process_async_events(CPUState *cs)
4844 {
4845     X86CPU *cpu = X86_CPU(cs);
4846     CPUX86State *env = &cpu->env;
4847 
4848     if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
4849         /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
4850         assert(env->mcg_cap);
4851 
4852         cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
4853 
4854         kvm_cpu_synchronize_state(cs);
4855 
4856         if (env->exception_nr == EXCP08_DBLE) {
4857             /* this means triple fault */
4858             qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
4859             cs->exit_request = 1;
4860             return 0;
4861         }
4862         kvm_queue_exception(env, EXCP12_MCHK, 0, 0);
4863         env->has_error_code = 0;
4864 
4865         cs->halted = 0;
4866         if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
4867             env->mp_state = KVM_MP_STATE_RUNNABLE;
4868         }
4869     }
4870 
4871     if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
4872         !(env->hflags & HF_SMM_MASK)) {
4873         kvm_cpu_synchronize_state(cs);
4874         do_cpu_init(cpu);
4875     }
4876 
4877     if (kvm_irqchip_in_kernel()) {
4878         return 0;
4879     }
4880 
4881     if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
4882         cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
4883         apic_poll_irq(cpu->apic_state);
4884     }
4885     if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
4886          (env->eflags & IF_MASK)) ||
4887         (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
4888         cs->halted = 0;
4889     }
4890     if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
4891         kvm_cpu_synchronize_state(cs);
4892         do_cpu_sipi(cpu);
4893     }
4894     if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
4895         cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
4896         kvm_cpu_synchronize_state(cs);
4897         apic_handle_tpr_access_report(cpu->apic_state, env->eip,
4898                                       env->tpr_access_type);
4899     }
4900 
4901     return cs->halted;
4902 }
4903 
4904 static int kvm_handle_halt(X86CPU *cpu)
4905 {
4906     CPUState *cs = CPU(cpu);
4907     CPUX86State *env = &cpu->env;
4908 
4909     if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
4910           (env->eflags & IF_MASK)) &&
4911         !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
4912         cs->halted = 1;
4913         return EXCP_HLT;
4914     }
4915 
4916     return 0;
4917 }
4918 
4919 static int kvm_handle_tpr_access(X86CPU *cpu)
4920 {
4921     CPUState *cs = CPU(cpu);
4922     struct kvm_run *run = cs->kvm_run;
4923 
4924     apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
4925                                   run->tpr_access.is_write ? TPR_ACCESS_WRITE
4926                                                            : TPR_ACCESS_READ);
4927     return 1;
4928 }
4929 
4930 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
4931 {
4932     static const uint8_t int3 = 0xcc;
4933 
4934     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
4935         cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
4936         return -EINVAL;
4937     }
4938     return 0;
4939 }
4940 
4941 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
4942 {
4943     uint8_t int3;
4944 
4945     if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0)) {
4946         return -EINVAL;
4947     }
4948     if (int3 != 0xcc) {
4949         return 0;
4950     }
4951     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
4952         return -EINVAL;
4953     }
4954     return 0;
4955 }
4956 
4957 static struct {
4958     target_ulong addr;
4959     int len;
4960     int type;
4961 } hw_breakpoint[4];
4962 
4963 static int nb_hw_breakpoint;
4964 
4965 static int find_hw_breakpoint(target_ulong addr, int len, int type)
4966 {
4967     int n;
4968 
4969     for (n = 0; n < nb_hw_breakpoint; n++) {
4970         if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
4971             (hw_breakpoint[n].len == len || len == -1)) {
4972             return n;
4973         }
4974     }
4975     return -1;
4976 }
4977 
4978 int kvm_arch_insert_hw_breakpoint(vaddr addr, vaddr len, int type)
4979 {
4980     switch (type) {
4981     case GDB_BREAKPOINT_HW:
4982         len = 1;
4983         break;
4984     case GDB_WATCHPOINT_WRITE:
4985     case GDB_WATCHPOINT_ACCESS:
4986         switch (len) {
4987         case 1:
4988             break;
4989         case 2:
4990         case 4:
4991         case 8:
4992             if (addr & (len - 1)) {
4993                 return -EINVAL;
4994             }
4995             break;
4996         default:
4997             return -EINVAL;
4998         }
4999         break;
5000     default:
5001         return -ENOSYS;
5002     }
5003 
5004     if (nb_hw_breakpoint == 4) {
5005         return -ENOBUFS;
5006     }
5007     if (find_hw_breakpoint(addr, len, type) >= 0) {
5008         return -EEXIST;
5009     }
5010     hw_breakpoint[nb_hw_breakpoint].addr = addr;
5011     hw_breakpoint[nb_hw_breakpoint].len = len;
5012     hw_breakpoint[nb_hw_breakpoint].type = type;
5013     nb_hw_breakpoint++;
5014 
5015     return 0;
5016 }
5017 
5018 int kvm_arch_remove_hw_breakpoint(vaddr addr, vaddr len, int type)
5019 {
5020     int n;
5021 
5022     n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
5023     if (n < 0) {
5024         return -ENOENT;
5025     }
5026     nb_hw_breakpoint--;
5027     hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
5028 
5029     return 0;
5030 }
5031 
5032 void kvm_arch_remove_all_hw_breakpoints(void)
5033 {
5034     nb_hw_breakpoint = 0;
5035 }
5036 
5037 static CPUWatchpoint hw_watchpoint;
5038 
5039 static int kvm_handle_debug(X86CPU *cpu,
5040                             struct kvm_debug_exit_arch *arch_info)
5041 {
5042     CPUState *cs = CPU(cpu);
5043     CPUX86State *env = &cpu->env;
5044     int ret = 0;
5045     int n;
5046 
5047     if (arch_info->exception == EXCP01_DB) {
5048         if (arch_info->dr6 & DR6_BS) {
5049             if (cs->singlestep_enabled) {
5050                 ret = EXCP_DEBUG;
5051             }
5052         } else {
5053             for (n = 0; n < 4; n++) {
5054                 if (arch_info->dr6 & (1 << n)) {
5055                     switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
5056                     case 0x0:
5057                         ret = EXCP_DEBUG;
5058                         break;
5059                     case 0x1:
5060                         ret = EXCP_DEBUG;
5061                         cs->watchpoint_hit = &hw_watchpoint;
5062                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
5063                         hw_watchpoint.flags = BP_MEM_WRITE;
5064                         break;
5065                     case 0x3:
5066                         ret = EXCP_DEBUG;
5067                         cs->watchpoint_hit = &hw_watchpoint;
5068                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
5069                         hw_watchpoint.flags = BP_MEM_ACCESS;
5070                         break;
5071                     }
5072                 }
5073             }
5074         }
5075     } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
5076         ret = EXCP_DEBUG;
5077     }
5078     if (ret == 0) {
5079         cpu_synchronize_state(cs);
5080         assert(env->exception_nr == -1);
5081 
5082         /* pass to guest */
5083         kvm_queue_exception(env, arch_info->exception,
5084                             arch_info->exception == EXCP01_DB,
5085                             arch_info->dr6);
5086         env->has_error_code = 0;
5087     }
5088 
5089     return ret;
5090 }
5091 
5092 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
5093 {
5094     const uint8_t type_code[] = {
5095         [GDB_BREAKPOINT_HW] = 0x0,
5096         [GDB_WATCHPOINT_WRITE] = 0x1,
5097         [GDB_WATCHPOINT_ACCESS] = 0x3
5098     };
5099     const uint8_t len_code[] = {
5100         [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
5101     };
5102     int n;
5103 
5104     if (kvm_sw_breakpoints_active(cpu)) {
5105         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
5106     }
5107     if (nb_hw_breakpoint > 0) {
5108         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
5109         dbg->arch.debugreg[7] = 0x0600;
5110         for (n = 0; n < nb_hw_breakpoint; n++) {
5111             dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
5112             dbg->arch.debugreg[7] |= (2 << (n * 2)) |
5113                 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
5114                 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
5115         }
5116     }
5117 }
5118 
5119 static bool kvm_install_msr_filters(KVMState *s)
5120 {
5121     uint64_t zero = 0;
5122     struct kvm_msr_filter filter = {
5123         .flags = KVM_MSR_FILTER_DEFAULT_ALLOW,
5124     };
5125     int r, i, j = 0;
5126 
5127     for (i = 0; i < KVM_MSR_FILTER_MAX_RANGES; i++) {
5128         KVMMSRHandlers *handler = &msr_handlers[i];
5129         if (handler->msr) {
5130             struct kvm_msr_filter_range *range = &filter.ranges[j++];
5131 
5132             *range = (struct kvm_msr_filter_range) {
5133                 .flags = 0,
5134                 .nmsrs = 1,
5135                 .base = handler->msr,
5136                 .bitmap = (__u8 *)&zero,
5137             };
5138 
5139             if (handler->rdmsr) {
5140                 range->flags |= KVM_MSR_FILTER_READ;
5141             }
5142 
5143             if (handler->wrmsr) {
5144                 range->flags |= KVM_MSR_FILTER_WRITE;
5145             }
5146         }
5147     }
5148 
5149     r = kvm_vm_ioctl(s, KVM_X86_SET_MSR_FILTER, &filter);
5150     if (r) {
5151         return false;
5152     }
5153 
5154     return true;
5155 }
5156 
5157 bool kvm_filter_msr(KVMState *s, uint32_t msr, QEMURDMSRHandler *rdmsr,
5158                     QEMUWRMSRHandler *wrmsr)
5159 {
5160     int i;
5161 
5162     for (i = 0; i < ARRAY_SIZE(msr_handlers); i++) {
5163         if (!msr_handlers[i].msr) {
5164             msr_handlers[i] = (KVMMSRHandlers) {
5165                 .msr = msr,
5166                 .rdmsr = rdmsr,
5167                 .wrmsr = wrmsr,
5168             };
5169 
5170             if (!kvm_install_msr_filters(s)) {
5171                 msr_handlers[i] = (KVMMSRHandlers) { };
5172                 return false;
5173             }
5174 
5175             return true;
5176         }
5177     }
5178 
5179     return false;
5180 }
5181 
5182 static int kvm_handle_rdmsr(X86CPU *cpu, struct kvm_run *run)
5183 {
5184     int i;
5185     bool r;
5186 
5187     for (i = 0; i < ARRAY_SIZE(msr_handlers); i++) {
5188         KVMMSRHandlers *handler = &msr_handlers[i];
5189         if (run->msr.index == handler->msr) {
5190             if (handler->rdmsr) {
5191                 r = handler->rdmsr(cpu, handler->msr,
5192                                    (uint64_t *)&run->msr.data);
5193                 run->msr.error = r ? 0 : 1;
5194                 return 0;
5195             }
5196         }
5197     }
5198 
5199     assert(false);
5200 }
5201 
5202 static int kvm_handle_wrmsr(X86CPU *cpu, struct kvm_run *run)
5203 {
5204     int i;
5205     bool r;
5206 
5207     for (i = 0; i < ARRAY_SIZE(msr_handlers); i++) {
5208         KVMMSRHandlers *handler = &msr_handlers[i];
5209         if (run->msr.index == handler->msr) {
5210             if (handler->wrmsr) {
5211                 r = handler->wrmsr(cpu, handler->msr, run->msr.data);
5212                 run->msr.error = r ? 0 : 1;
5213                 return 0;
5214             }
5215         }
5216     }
5217 
5218     assert(false);
5219 }
5220 
5221 static bool has_sgx_provisioning;
5222 
5223 static bool __kvm_enable_sgx_provisioning(KVMState *s)
5224 {
5225     int fd, ret;
5226 
5227     if (!kvm_vm_check_extension(s, KVM_CAP_SGX_ATTRIBUTE)) {
5228         return false;
5229     }
5230 
5231     fd = qemu_open_old("/dev/sgx_provision", O_RDONLY);
5232     if (fd < 0) {
5233         return false;
5234     }
5235 
5236     ret = kvm_vm_enable_cap(s, KVM_CAP_SGX_ATTRIBUTE, 0, fd);
5237     if (ret) {
5238         error_report("Could not enable SGX PROVISIONKEY: %s", strerror(-ret));
5239         exit(1);
5240     }
5241     close(fd);
5242     return true;
5243 }
5244 
5245 bool kvm_enable_sgx_provisioning(KVMState *s)
5246 {
5247     return MEMORIZE(__kvm_enable_sgx_provisioning(s), has_sgx_provisioning);
5248 }
5249 
5250 static bool host_supports_vmx(void)
5251 {
5252     uint32_t ecx, unused;
5253 
5254     host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
5255     return ecx & CPUID_EXT_VMX;
5256 }
5257 
5258 #define VMX_INVALID_GUEST_STATE 0x80000021
5259 
5260 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
5261 {
5262     X86CPU *cpu = X86_CPU(cs);
5263     uint64_t code;
5264     int ret;
5265     bool ctx_invalid;
5266     char str[256];
5267     KVMState *state;
5268 
5269     switch (run->exit_reason) {
5270     case KVM_EXIT_HLT:
5271         DPRINTF("handle_hlt\n");
5272         qemu_mutex_lock_iothread();
5273         ret = kvm_handle_halt(cpu);
5274         qemu_mutex_unlock_iothread();
5275         break;
5276     case KVM_EXIT_SET_TPR:
5277         ret = 0;
5278         break;
5279     case KVM_EXIT_TPR_ACCESS:
5280         qemu_mutex_lock_iothread();
5281         ret = kvm_handle_tpr_access(cpu);
5282         qemu_mutex_unlock_iothread();
5283         break;
5284     case KVM_EXIT_FAIL_ENTRY:
5285         code = run->fail_entry.hardware_entry_failure_reason;
5286         fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
5287                 code);
5288         if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
5289             fprintf(stderr,
5290                     "\nIf you're running a guest on an Intel machine without "
5291                         "unrestricted mode\n"
5292                     "support, the failure can be most likely due to the guest "
5293                         "entering an invalid\n"
5294                     "state for Intel VT. For example, the guest maybe running "
5295                         "in big real mode\n"
5296                     "which is not supported on less recent Intel processors."
5297                         "\n\n");
5298         }
5299         ret = -1;
5300         break;
5301     case KVM_EXIT_EXCEPTION:
5302         fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
5303                 run->ex.exception, run->ex.error_code);
5304         ret = -1;
5305         break;
5306     case KVM_EXIT_DEBUG:
5307         DPRINTF("kvm_exit_debug\n");
5308         qemu_mutex_lock_iothread();
5309         ret = kvm_handle_debug(cpu, &run->debug.arch);
5310         qemu_mutex_unlock_iothread();
5311         break;
5312     case KVM_EXIT_HYPERV:
5313         ret = kvm_hv_handle_exit(cpu, &run->hyperv);
5314         break;
5315     case KVM_EXIT_IOAPIC_EOI:
5316         ioapic_eoi_broadcast(run->eoi.vector);
5317         ret = 0;
5318         break;
5319     case KVM_EXIT_X86_BUS_LOCK:
5320         /* already handled in kvm_arch_post_run */
5321         ret = 0;
5322         break;
5323     case KVM_EXIT_NOTIFY:
5324         ctx_invalid = !!(run->notify.flags & KVM_NOTIFY_CONTEXT_INVALID);
5325         state = KVM_STATE(current_accel());
5326         sprintf(str, "Encounter a notify exit with %svalid context in"
5327                      " guest. There can be possible misbehaves in guest."
5328                      " Please have a look.", ctx_invalid ? "in" : "");
5329         if (ctx_invalid ||
5330             state->notify_vmexit == NOTIFY_VMEXIT_OPTION_INTERNAL_ERROR) {
5331             warn_report("KVM internal error: %s", str);
5332             ret = -1;
5333         } else {
5334             warn_report_once("KVM: %s", str);
5335             ret = 0;
5336         }
5337         break;
5338     case KVM_EXIT_X86_RDMSR:
5339         /* We only enable MSR filtering, any other exit is bogus */
5340         assert(run->msr.reason == KVM_MSR_EXIT_REASON_FILTER);
5341         ret = kvm_handle_rdmsr(cpu, run);
5342         break;
5343     case KVM_EXIT_X86_WRMSR:
5344         /* We only enable MSR filtering, any other exit is bogus */
5345         assert(run->msr.reason == KVM_MSR_EXIT_REASON_FILTER);
5346         ret = kvm_handle_wrmsr(cpu, run);
5347         break;
5348 #ifdef CONFIG_XEN_EMU
5349     case KVM_EXIT_XEN:
5350         ret = kvm_xen_handle_exit(cpu, &run->xen);
5351         break;
5352 #endif
5353     default:
5354         fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
5355         ret = -1;
5356         break;
5357     }
5358 
5359     return ret;
5360 }
5361 
5362 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
5363 {
5364     X86CPU *cpu = X86_CPU(cs);
5365     CPUX86State *env = &cpu->env;
5366 
5367     kvm_cpu_synchronize_state(cs);
5368     return !(env->cr[0] & CR0_PE_MASK) ||
5369            ((env->segs[R_CS].selector  & 3) != 3);
5370 }
5371 
5372 void kvm_arch_init_irq_routing(KVMState *s)
5373 {
5374     /* We know at this point that we're using the in-kernel
5375      * irqchip, so we can use irqfds, and on x86 we know
5376      * we can use msi via irqfd and GSI routing.
5377      */
5378     kvm_msi_via_irqfd_allowed = true;
5379     kvm_gsi_routing_allowed = true;
5380 
5381     if (kvm_irqchip_is_split()) {
5382         KVMRouteChange c = kvm_irqchip_begin_route_changes(s);
5383         int i;
5384 
5385         /* If the ioapic is in QEMU and the lapics are in KVM, reserve
5386            MSI routes for signaling interrupts to the local apics. */
5387         for (i = 0; i < IOAPIC_NUM_PINS; i++) {
5388             if (kvm_irqchip_add_msi_route(&c, 0, NULL) < 0) {
5389                 error_report("Could not enable split IRQ mode.");
5390                 exit(1);
5391             }
5392         }
5393         kvm_irqchip_commit_route_changes(&c);
5394     }
5395 }
5396 
5397 int kvm_arch_irqchip_create(KVMState *s)
5398 {
5399     int ret;
5400     if (kvm_kernel_irqchip_split()) {
5401         ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
5402         if (ret) {
5403             error_report("Could not enable split irqchip mode: %s",
5404                          strerror(-ret));
5405             exit(1);
5406         } else {
5407             DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
5408             kvm_split_irqchip = true;
5409             return 1;
5410         }
5411     } else {
5412         return 0;
5413     }
5414 }
5415 
5416 uint64_t kvm_swizzle_msi_ext_dest_id(uint64_t address)
5417 {
5418     CPUX86State *env;
5419     uint64_t ext_id;
5420 
5421     if (!first_cpu) {
5422         return address;
5423     }
5424     env = &X86_CPU(first_cpu)->env;
5425     if (!(env->features[FEAT_KVM] & (1 << KVM_FEATURE_MSI_EXT_DEST_ID))) {
5426         return address;
5427     }
5428 
5429     /*
5430      * If the remappable format bit is set, or the upper bits are
5431      * already set in address_hi, or the low extended bits aren't
5432      * there anyway, do nothing.
5433      */
5434     ext_id = address & (0xff << MSI_ADDR_DEST_IDX_SHIFT);
5435     if (!ext_id || (ext_id & (1 << MSI_ADDR_DEST_IDX_SHIFT)) || (address >> 32)) {
5436         return address;
5437     }
5438 
5439     address &= ~ext_id;
5440     address |= ext_id << 35;
5441     return address;
5442 }
5443 
5444 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
5445                              uint64_t address, uint32_t data, PCIDevice *dev)
5446 {
5447     X86IOMMUState *iommu = x86_iommu_get_default();
5448 
5449     if (iommu) {
5450         X86IOMMUClass *class = X86_IOMMU_DEVICE_GET_CLASS(iommu);
5451 
5452         if (class->int_remap) {
5453             int ret;
5454             MSIMessage src, dst;
5455 
5456             src.address = route->u.msi.address_hi;
5457             src.address <<= VTD_MSI_ADDR_HI_SHIFT;
5458             src.address |= route->u.msi.address_lo;
5459             src.data = route->u.msi.data;
5460 
5461             ret = class->int_remap(iommu, &src, &dst, dev ?     \
5462                                    pci_requester_id(dev) :      \
5463                                    X86_IOMMU_SID_INVALID);
5464             if (ret) {
5465                 trace_kvm_x86_fixup_msi_error(route->gsi);
5466                 return 1;
5467             }
5468 
5469             /*
5470              * Handled untranslated compatibility format interrupt with
5471              * extended destination ID in the low bits 11-5. */
5472             dst.address = kvm_swizzle_msi_ext_dest_id(dst.address);
5473 
5474             route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
5475             route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
5476             route->u.msi.data = dst.data;
5477             return 0;
5478         }
5479     }
5480 
5481 #ifdef CONFIG_XEN_EMU
5482     if (xen_mode == XEN_EMULATE) {
5483         int handled = xen_evtchn_translate_pirq_msi(route, address, data);
5484 
5485         /*
5486          * If it was a PIRQ and successfully routed (handled == 0) or it was
5487          * an error (handled < 0), return. If it wasn't a PIRQ, keep going.
5488          */
5489         if (handled <= 0) {
5490             return handled;
5491         }
5492     }
5493 #endif
5494 
5495     address = kvm_swizzle_msi_ext_dest_id(address);
5496     route->u.msi.address_hi = address >> VTD_MSI_ADDR_HI_SHIFT;
5497     route->u.msi.address_lo = address & VTD_MSI_ADDR_LO_MASK;
5498     return 0;
5499 }
5500 
5501 typedef struct MSIRouteEntry MSIRouteEntry;
5502 
5503 struct MSIRouteEntry {
5504     PCIDevice *dev;             /* Device pointer */
5505     int vector;                 /* MSI/MSIX vector index */
5506     int virq;                   /* Virtual IRQ index */
5507     QLIST_ENTRY(MSIRouteEntry) list;
5508 };
5509 
5510 /* List of used GSI routes */
5511 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
5512     QLIST_HEAD_INITIALIZER(msi_route_list);
5513 
5514 void kvm_update_msi_routes_all(void *private, bool global,
5515                                uint32_t index, uint32_t mask)
5516 {
5517     int cnt = 0, vector;
5518     MSIRouteEntry *entry;
5519     MSIMessage msg;
5520     PCIDevice *dev;
5521 
5522     /* TODO: explicit route update */
5523     QLIST_FOREACH(entry, &msi_route_list, list) {
5524         cnt++;
5525         vector = entry->vector;
5526         dev = entry->dev;
5527         if (msix_enabled(dev) && !msix_is_masked(dev, vector)) {
5528             msg = msix_get_message(dev, vector);
5529         } else if (msi_enabled(dev) && !msi_is_masked(dev, vector)) {
5530             msg = msi_get_message(dev, vector);
5531         } else {
5532             /*
5533              * Either MSI/MSIX is disabled for the device, or the
5534              * specific message was masked out.  Skip this one.
5535              */
5536             continue;
5537         }
5538         kvm_irqchip_update_msi_route(kvm_state, entry->virq, msg, dev);
5539     }
5540     kvm_irqchip_commit_routes(kvm_state);
5541     trace_kvm_x86_update_msi_routes(cnt);
5542 }
5543 
5544 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
5545                                 int vector, PCIDevice *dev)
5546 {
5547     static bool notify_list_inited = false;
5548     MSIRouteEntry *entry;
5549 
5550     if (!dev) {
5551         /* These are (possibly) IOAPIC routes only used for split
5552          * kernel irqchip mode, while what we are housekeeping are
5553          * PCI devices only. */
5554         return 0;
5555     }
5556 
5557     entry = g_new0(MSIRouteEntry, 1);
5558     entry->dev = dev;
5559     entry->vector = vector;
5560     entry->virq = route->gsi;
5561     QLIST_INSERT_HEAD(&msi_route_list, entry, list);
5562 
5563     trace_kvm_x86_add_msi_route(route->gsi);
5564 
5565     if (!notify_list_inited) {
5566         /* For the first time we do add route, add ourselves into
5567          * IOMMU's IEC notify list if needed. */
5568         X86IOMMUState *iommu = x86_iommu_get_default();
5569         if (iommu) {
5570             x86_iommu_iec_register_notifier(iommu,
5571                                             kvm_update_msi_routes_all,
5572                                             NULL);
5573         }
5574         notify_list_inited = true;
5575     }
5576     return 0;
5577 }
5578 
5579 int kvm_arch_release_virq_post(int virq)
5580 {
5581     MSIRouteEntry *entry, *next;
5582     QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
5583         if (entry->virq == virq) {
5584             trace_kvm_x86_remove_msi_route(virq);
5585             QLIST_REMOVE(entry, list);
5586             g_free(entry);
5587             break;
5588         }
5589     }
5590     return 0;
5591 }
5592 
5593 int kvm_arch_msi_data_to_gsi(uint32_t data)
5594 {
5595     abort();
5596 }
5597 
5598 bool kvm_has_waitpkg(void)
5599 {
5600     return has_msr_umwait;
5601 }
5602 
5603 bool kvm_arch_cpu_check_are_resettable(void)
5604 {
5605     return !sev_es_enabled();
5606 }
5607 
5608 #define ARCH_REQ_XCOMP_GUEST_PERM       0x1025
5609 
5610 void kvm_request_xsave_components(X86CPU *cpu, uint64_t mask)
5611 {
5612     KVMState *s = kvm_state;
5613     uint64_t supported;
5614 
5615     mask &= XSTATE_DYNAMIC_MASK;
5616     if (!mask) {
5617         return;
5618     }
5619     /*
5620      * Just ignore bits that are not in CPUID[EAX=0xD,ECX=0].
5621      * ARCH_REQ_XCOMP_GUEST_PERM would fail, and QEMU has warned
5622      * about them already because they are not supported features.
5623      */
5624     supported = kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EAX);
5625     supported |= (uint64_t)kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EDX) << 32;
5626     mask &= supported;
5627 
5628     while (mask) {
5629         int bit = ctz64(mask);
5630         int rc = syscall(SYS_arch_prctl, ARCH_REQ_XCOMP_GUEST_PERM, bit);
5631         if (rc) {
5632             /*
5633              * Older kernel version (<5.17) do not support
5634              * ARCH_REQ_XCOMP_GUEST_PERM, but also do not return
5635              * any dynamic feature from kvm_arch_get_supported_cpuid.
5636              */
5637             warn_report("prctl(ARCH_REQ_XCOMP_GUEST_PERM) failure "
5638                         "for feature bit %d", bit);
5639         }
5640         mask &= ~BIT_ULL(bit);
5641     }
5642 }
5643 
5644 static int kvm_arch_get_notify_vmexit(Object *obj, Error **errp)
5645 {
5646     KVMState *s = KVM_STATE(obj);
5647     return s->notify_vmexit;
5648 }
5649 
5650 static void kvm_arch_set_notify_vmexit(Object *obj, int value, Error **errp)
5651 {
5652     KVMState *s = KVM_STATE(obj);
5653 
5654     if (s->fd != -1) {
5655         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
5656         return;
5657     }
5658 
5659     s->notify_vmexit = value;
5660 }
5661 
5662 static void kvm_arch_get_notify_window(Object *obj, Visitor *v,
5663                                        const char *name, void *opaque,
5664                                        Error **errp)
5665 {
5666     KVMState *s = KVM_STATE(obj);
5667     uint32_t value = s->notify_window;
5668 
5669     visit_type_uint32(v, name, &value, errp);
5670 }
5671 
5672 static void kvm_arch_set_notify_window(Object *obj, Visitor *v,
5673                                        const char *name, void *opaque,
5674                                        Error **errp)
5675 {
5676     KVMState *s = KVM_STATE(obj);
5677     uint32_t value;
5678 
5679     if (s->fd != -1) {
5680         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
5681         return;
5682     }
5683 
5684     if (!visit_type_uint32(v, name, &value, errp)) {
5685         return;
5686     }
5687 
5688     s->notify_window = value;
5689 }
5690 
5691 static void kvm_arch_get_xen_version(Object *obj, Visitor *v,
5692                                      const char *name, void *opaque,
5693                                      Error **errp)
5694 {
5695     KVMState *s = KVM_STATE(obj);
5696     uint32_t value = s->xen_version;
5697 
5698     visit_type_uint32(v, name, &value, errp);
5699 }
5700 
5701 static void kvm_arch_set_xen_version(Object *obj, Visitor *v,
5702                                      const char *name, void *opaque,
5703                                      Error **errp)
5704 {
5705     KVMState *s = KVM_STATE(obj);
5706     Error *error = NULL;
5707     uint32_t value;
5708 
5709     visit_type_uint32(v, name, &value, &error);
5710     if (error) {
5711         error_propagate(errp, error);
5712         return;
5713     }
5714 
5715     s->xen_version = value;
5716     if (value && xen_mode == XEN_DISABLED) {
5717         xen_mode = XEN_EMULATE;
5718     }
5719 }
5720 
5721 static void kvm_arch_get_xen_gnttab_max_frames(Object *obj, Visitor *v,
5722                                                const char *name, void *opaque,
5723                                                Error **errp)
5724 {
5725     KVMState *s = KVM_STATE(obj);
5726     uint16_t value = s->xen_gnttab_max_frames;
5727 
5728     visit_type_uint16(v, name, &value, errp);
5729 }
5730 
5731 static void kvm_arch_set_xen_gnttab_max_frames(Object *obj, Visitor *v,
5732                                                const char *name, void *opaque,
5733                                                Error **errp)
5734 {
5735     KVMState *s = KVM_STATE(obj);
5736     Error *error = NULL;
5737     uint16_t value;
5738 
5739     visit_type_uint16(v, name, &value, &error);
5740     if (error) {
5741         error_propagate(errp, error);
5742         return;
5743     }
5744 
5745     s->xen_gnttab_max_frames = value;
5746 }
5747 
5748 static void kvm_arch_get_xen_evtchn_max_pirq(Object *obj, Visitor *v,
5749                                              const char *name, void *opaque,
5750                                              Error **errp)
5751 {
5752     KVMState *s = KVM_STATE(obj);
5753     uint16_t value = s->xen_evtchn_max_pirq;
5754 
5755     visit_type_uint16(v, name, &value, errp);
5756 }
5757 
5758 static void kvm_arch_set_xen_evtchn_max_pirq(Object *obj, Visitor *v,
5759                                              const char *name, void *opaque,
5760                                              Error **errp)
5761 {
5762     KVMState *s = KVM_STATE(obj);
5763     Error *error = NULL;
5764     uint16_t value;
5765 
5766     visit_type_uint16(v, name, &value, &error);
5767     if (error) {
5768         error_propagate(errp, error);
5769         return;
5770     }
5771 
5772     s->xen_evtchn_max_pirq = value;
5773 }
5774 
5775 void kvm_arch_accel_class_init(ObjectClass *oc)
5776 {
5777     object_class_property_add_enum(oc, "notify-vmexit", "NotifyVMexitOption",
5778                                    &NotifyVmexitOption_lookup,
5779                                    kvm_arch_get_notify_vmexit,
5780                                    kvm_arch_set_notify_vmexit);
5781     object_class_property_set_description(oc, "notify-vmexit",
5782                                           "Enable notify VM exit");
5783 
5784     object_class_property_add(oc, "notify-window", "uint32",
5785                               kvm_arch_get_notify_window,
5786                               kvm_arch_set_notify_window,
5787                               NULL, NULL);
5788     object_class_property_set_description(oc, "notify-window",
5789                                           "Clock cycles without an event window "
5790                                           "after which a notification VM exit occurs");
5791 
5792     object_class_property_add(oc, "xen-version", "uint32",
5793                               kvm_arch_get_xen_version,
5794                               kvm_arch_set_xen_version,
5795                               NULL, NULL);
5796     object_class_property_set_description(oc, "xen-version",
5797                                           "Xen version to be emulated "
5798                                           "(in XENVER_version form "
5799                                           "e.g. 0x4000a for 4.10)");
5800 
5801     object_class_property_add(oc, "xen-gnttab-max-frames", "uint16",
5802                               kvm_arch_get_xen_gnttab_max_frames,
5803                               kvm_arch_set_xen_gnttab_max_frames,
5804                               NULL, NULL);
5805     object_class_property_set_description(oc, "xen-gnttab-max-frames",
5806                                           "Maximum number of grant table frames");
5807 
5808     object_class_property_add(oc, "xen-evtchn-max-pirq", "uint16",
5809                               kvm_arch_get_xen_evtchn_max_pirq,
5810                               kvm_arch_set_xen_evtchn_max_pirq,
5811                               NULL, NULL);
5812     object_class_property_set_description(oc, "xen-evtchn-max-pirq",
5813                                           "Maximum number of Xen PIRQs");
5814 }
5815 
5816 void kvm_set_max_apic_id(uint32_t max_apic_id)
5817 {
5818     kvm_vm_enable_cap(kvm_state, KVM_CAP_MAX_VCPU_ID, 0, max_apic_id);
5819 }
5820