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