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