xref: /openbmc/qemu/target/i386/kvm/kvm.c (revision b14df228)
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     if (cpu->kvm_msr_buf) {
2180         g_free(cpu->kvm_msr_buf);
2181         cpu->kvm_msr_buf = NULL;
2182     }
2183 
2184     if (env->nested_state) {
2185         g_free(env->nested_state);
2186         env->nested_state = NULL;
2187     }
2188 
2189     qemu_del_vm_change_state_handler(cpu->vmsentry);
2190 
2191     return 0;
2192 }
2193 
2194 void kvm_arch_reset_vcpu(X86CPU *cpu)
2195 {
2196     CPUX86State *env = &cpu->env;
2197 
2198     env->xcr0 = 1;
2199     if (kvm_irqchip_in_kernel()) {
2200         env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
2201                                           KVM_MP_STATE_UNINITIALIZED;
2202     } else {
2203         env->mp_state = KVM_MP_STATE_RUNNABLE;
2204     }
2205 
2206     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
2207         int i;
2208         for (i = 0; i < ARRAY_SIZE(env->msr_hv_synic_sint); i++) {
2209             env->msr_hv_synic_sint[i] = HV_SINT_MASKED;
2210         }
2211 
2212         hyperv_x86_synic_reset(cpu);
2213     }
2214     /* enabled by default */
2215     env->poll_control_msr = 1;
2216 
2217     kvm_init_nested_state(env);
2218 
2219     sev_es_set_reset_vector(CPU(cpu));
2220 }
2221 
2222 void kvm_arch_do_init_vcpu(X86CPU *cpu)
2223 {
2224     CPUX86State *env = &cpu->env;
2225 
2226     /* APs get directly into wait-for-SIPI state.  */
2227     if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
2228         env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
2229     }
2230 }
2231 
2232 static int kvm_get_supported_feature_msrs(KVMState *s)
2233 {
2234     int ret = 0;
2235 
2236     if (kvm_feature_msrs != NULL) {
2237         return 0;
2238     }
2239 
2240     if (!kvm_check_extension(s, KVM_CAP_GET_MSR_FEATURES)) {
2241         return 0;
2242     }
2243 
2244     struct kvm_msr_list msr_list;
2245 
2246     msr_list.nmsrs = 0;
2247     ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, &msr_list);
2248     if (ret < 0 && ret != -E2BIG) {
2249         error_report("Fetch KVM feature MSR list failed: %s",
2250             strerror(-ret));
2251         return ret;
2252     }
2253 
2254     assert(msr_list.nmsrs > 0);
2255     kvm_feature_msrs = (struct kvm_msr_list *) \
2256         g_malloc0(sizeof(msr_list) +
2257                  msr_list.nmsrs * sizeof(msr_list.indices[0]));
2258 
2259     kvm_feature_msrs->nmsrs = msr_list.nmsrs;
2260     ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, kvm_feature_msrs);
2261 
2262     if (ret < 0) {
2263         error_report("Fetch KVM feature MSR list failed: %s",
2264             strerror(-ret));
2265         g_free(kvm_feature_msrs);
2266         kvm_feature_msrs = NULL;
2267         return ret;
2268     }
2269 
2270     return 0;
2271 }
2272 
2273 static int kvm_get_supported_msrs(KVMState *s)
2274 {
2275     int ret = 0;
2276     struct kvm_msr_list msr_list, *kvm_msr_list;
2277 
2278     /*
2279      *  Obtain MSR list from KVM.  These are the MSRs that we must
2280      *  save/restore.
2281      */
2282     msr_list.nmsrs = 0;
2283     ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
2284     if (ret < 0 && ret != -E2BIG) {
2285         return ret;
2286     }
2287     /*
2288      * Old kernel modules had a bug and could write beyond the provided
2289      * memory. Allocate at least a safe amount of 1K.
2290      */
2291     kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
2292                                           msr_list.nmsrs *
2293                                           sizeof(msr_list.indices[0])));
2294 
2295     kvm_msr_list->nmsrs = msr_list.nmsrs;
2296     ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
2297     if (ret >= 0) {
2298         int i;
2299 
2300         for (i = 0; i < kvm_msr_list->nmsrs; i++) {
2301             switch (kvm_msr_list->indices[i]) {
2302             case MSR_STAR:
2303                 has_msr_star = true;
2304                 break;
2305             case MSR_VM_HSAVE_PA:
2306                 has_msr_hsave_pa = true;
2307                 break;
2308             case MSR_TSC_AUX:
2309                 has_msr_tsc_aux = true;
2310                 break;
2311             case MSR_TSC_ADJUST:
2312                 has_msr_tsc_adjust = true;
2313                 break;
2314             case MSR_IA32_TSCDEADLINE:
2315                 has_msr_tsc_deadline = true;
2316                 break;
2317             case MSR_IA32_SMBASE:
2318                 has_msr_smbase = true;
2319                 break;
2320             case MSR_SMI_COUNT:
2321                 has_msr_smi_count = true;
2322                 break;
2323             case MSR_IA32_MISC_ENABLE:
2324                 has_msr_misc_enable = true;
2325                 break;
2326             case MSR_IA32_BNDCFGS:
2327                 has_msr_bndcfgs = true;
2328                 break;
2329             case MSR_IA32_XSS:
2330                 has_msr_xss = true;
2331                 break;
2332             case MSR_IA32_UMWAIT_CONTROL:
2333                 has_msr_umwait = true;
2334                 break;
2335             case HV_X64_MSR_CRASH_CTL:
2336                 has_msr_hv_crash = true;
2337                 break;
2338             case HV_X64_MSR_RESET:
2339                 has_msr_hv_reset = true;
2340                 break;
2341             case HV_X64_MSR_VP_INDEX:
2342                 has_msr_hv_vpindex = true;
2343                 break;
2344             case HV_X64_MSR_VP_RUNTIME:
2345                 has_msr_hv_runtime = true;
2346                 break;
2347             case HV_X64_MSR_SCONTROL:
2348                 has_msr_hv_synic = true;
2349                 break;
2350             case HV_X64_MSR_STIMER0_CONFIG:
2351                 has_msr_hv_stimer = true;
2352                 break;
2353             case HV_X64_MSR_TSC_FREQUENCY:
2354                 has_msr_hv_frequencies = true;
2355                 break;
2356             case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2357                 has_msr_hv_reenlightenment = true;
2358                 break;
2359             case HV_X64_MSR_SYNDBG_OPTIONS:
2360                 has_msr_hv_syndbg_options = true;
2361                 break;
2362             case MSR_IA32_SPEC_CTRL:
2363                 has_msr_spec_ctrl = true;
2364                 break;
2365             case MSR_AMD64_TSC_RATIO:
2366                 has_tsc_scale_msr = true;
2367                 break;
2368             case MSR_IA32_TSX_CTRL:
2369                 has_msr_tsx_ctrl = true;
2370                 break;
2371             case MSR_VIRT_SSBD:
2372                 has_msr_virt_ssbd = true;
2373                 break;
2374             case MSR_IA32_ARCH_CAPABILITIES:
2375                 has_msr_arch_capabs = true;
2376                 break;
2377             case MSR_IA32_CORE_CAPABILITY:
2378                 has_msr_core_capabs = true;
2379                 break;
2380             case MSR_IA32_PERF_CAPABILITIES:
2381                 has_msr_perf_capabs = true;
2382                 break;
2383             case MSR_IA32_VMX_VMFUNC:
2384                 has_msr_vmx_vmfunc = true;
2385                 break;
2386             case MSR_IA32_UCODE_REV:
2387                 has_msr_ucode_rev = true;
2388                 break;
2389             case MSR_IA32_VMX_PROCBASED_CTLS2:
2390                 has_msr_vmx_procbased_ctls2 = true;
2391                 break;
2392             case MSR_IA32_PKRS:
2393                 has_msr_pkrs = true;
2394                 break;
2395             }
2396         }
2397     }
2398 
2399     g_free(kvm_msr_list);
2400 
2401     return ret;
2402 }
2403 
2404 static Notifier smram_machine_done;
2405 static KVMMemoryListener smram_listener;
2406 static AddressSpace smram_address_space;
2407 static MemoryRegion smram_as_root;
2408 static MemoryRegion smram_as_mem;
2409 
2410 static void register_smram_listener(Notifier *n, void *unused)
2411 {
2412     MemoryRegion *smram =
2413         (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
2414 
2415     /* Outer container... */
2416     memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
2417     memory_region_set_enabled(&smram_as_root, true);
2418 
2419     /* ... with two regions inside: normal system memory with low
2420      * priority, and...
2421      */
2422     memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
2423                              get_system_memory(), 0, ~0ull);
2424     memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
2425     memory_region_set_enabled(&smram_as_mem, true);
2426 
2427     if (smram) {
2428         /* ... SMRAM with higher priority */
2429         memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
2430         memory_region_set_enabled(smram, true);
2431     }
2432 
2433     address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
2434     kvm_memory_listener_register(kvm_state, &smram_listener,
2435                                  &smram_address_space, 1, "kvm-smram");
2436 }
2437 
2438 int kvm_arch_init(MachineState *ms, KVMState *s)
2439 {
2440     uint64_t identity_base = 0xfffbc000;
2441     uint64_t shadow_mem;
2442     int ret;
2443     struct utsname utsname;
2444     Error *local_err = NULL;
2445 
2446     /*
2447      * Initialize SEV context, if required
2448      *
2449      * If no memory encryption is requested (ms->cgs == NULL) this is
2450      * a no-op.
2451      *
2452      * It's also a no-op if a non-SEV confidential guest support
2453      * mechanism is selected.  SEV is the only mechanism available to
2454      * select on x86 at present, so this doesn't arise, but if new
2455      * mechanisms are supported in future (e.g. TDX), they'll need
2456      * their own initialization either here or elsewhere.
2457      */
2458     ret = sev_kvm_init(ms->cgs, &local_err);
2459     if (ret < 0) {
2460         error_report_err(local_err);
2461         return ret;
2462     }
2463 
2464     if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
2465         error_report("kvm: KVM_CAP_IRQ_ROUTING not supported by KVM");
2466         return -ENOTSUP;
2467     }
2468 
2469     has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
2470     has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
2471     has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
2472     has_sregs2 = kvm_check_extension(s, KVM_CAP_SREGS2) > 0;
2473 
2474     hv_vpindex_settable = kvm_check_extension(s, KVM_CAP_HYPERV_VP_INDEX);
2475 
2476     has_exception_payload = kvm_check_extension(s, KVM_CAP_EXCEPTION_PAYLOAD);
2477     if (has_exception_payload) {
2478         ret = kvm_vm_enable_cap(s, KVM_CAP_EXCEPTION_PAYLOAD, 0, true);
2479         if (ret < 0) {
2480             error_report("kvm: Failed to enable exception payload cap: %s",
2481                          strerror(-ret));
2482             return ret;
2483         }
2484     }
2485 
2486     ret = kvm_get_supported_msrs(s);
2487     if (ret < 0) {
2488         return ret;
2489     }
2490 
2491     kvm_get_supported_feature_msrs(s);
2492 
2493     uname(&utsname);
2494     lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
2495 
2496     /*
2497      * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
2498      * In order to use vm86 mode, an EPT identity map and a TSS  are needed.
2499      * Since these must be part of guest physical memory, we need to allocate
2500      * them, both by setting their start addresses in the kernel and by
2501      * creating a corresponding e820 entry. We need 4 pages before the BIOS.
2502      *
2503      * Older KVM versions may not support setting the identity map base. In
2504      * that case we need to stick with the default, i.e. a 256K maximum BIOS
2505      * size.
2506      */
2507     if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
2508         /* Allows up to 16M BIOSes. */
2509         identity_base = 0xfeffc000;
2510 
2511         ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
2512         if (ret < 0) {
2513             return ret;
2514         }
2515     }
2516 
2517     /* Set TSS base one page after EPT identity map. */
2518     ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
2519     if (ret < 0) {
2520         return ret;
2521     }
2522 
2523     /* Tell fw_cfg to notify the BIOS to reserve the range. */
2524     ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
2525     if (ret < 0) {
2526         fprintf(stderr, "e820_add_entry() table is full\n");
2527         return ret;
2528     }
2529 
2530     shadow_mem = object_property_get_int(OBJECT(s), "kvm-shadow-mem", &error_abort);
2531     if (shadow_mem != -1) {
2532         shadow_mem /= 4096;
2533         ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
2534         if (ret < 0) {
2535             return ret;
2536         }
2537     }
2538 
2539     if (kvm_check_extension(s, KVM_CAP_X86_SMM) &&
2540         object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE) &&
2541         x86_machine_is_smm_enabled(X86_MACHINE(ms))) {
2542         smram_machine_done.notify = register_smram_listener;
2543         qemu_add_machine_init_done_notifier(&smram_machine_done);
2544     }
2545 
2546     if (enable_cpu_pm) {
2547         int disable_exits = kvm_check_extension(s, KVM_CAP_X86_DISABLE_EXITS);
2548         int ret;
2549 
2550 /* Work around for kernel header with a typo. TODO: fix header and drop. */
2551 #if defined(KVM_X86_DISABLE_EXITS_HTL) && !defined(KVM_X86_DISABLE_EXITS_HLT)
2552 #define KVM_X86_DISABLE_EXITS_HLT KVM_X86_DISABLE_EXITS_HTL
2553 #endif
2554         if (disable_exits) {
2555             disable_exits &= (KVM_X86_DISABLE_EXITS_MWAIT |
2556                               KVM_X86_DISABLE_EXITS_HLT |
2557                               KVM_X86_DISABLE_EXITS_PAUSE |
2558                               KVM_X86_DISABLE_EXITS_CSTATE);
2559         }
2560 
2561         ret = kvm_vm_enable_cap(s, KVM_CAP_X86_DISABLE_EXITS, 0,
2562                                 disable_exits);
2563         if (ret < 0) {
2564             error_report("kvm: guest stopping CPU not supported: %s",
2565                          strerror(-ret));
2566         }
2567     }
2568 
2569     if (object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE)) {
2570         X86MachineState *x86ms = X86_MACHINE(ms);
2571 
2572         if (x86ms->bus_lock_ratelimit > 0) {
2573             ret = kvm_check_extension(s, KVM_CAP_X86_BUS_LOCK_EXIT);
2574             if (!(ret & KVM_BUS_LOCK_DETECTION_EXIT)) {
2575                 error_report("kvm: bus lock detection unsupported");
2576                 return -ENOTSUP;
2577             }
2578             ret = kvm_vm_enable_cap(s, KVM_CAP_X86_BUS_LOCK_EXIT, 0,
2579                                     KVM_BUS_LOCK_DETECTION_EXIT);
2580             if (ret < 0) {
2581                 error_report("kvm: Failed to enable bus lock detection cap: %s",
2582                              strerror(-ret));
2583                 return ret;
2584             }
2585             ratelimit_init(&bus_lock_ratelimit_ctrl);
2586             ratelimit_set_speed(&bus_lock_ratelimit_ctrl,
2587                                 x86ms->bus_lock_ratelimit, BUS_LOCK_SLICE_TIME);
2588         }
2589     }
2590 
2591     return 0;
2592 }
2593 
2594 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2595 {
2596     lhs->selector = rhs->selector;
2597     lhs->base = rhs->base;
2598     lhs->limit = rhs->limit;
2599     lhs->type = 3;
2600     lhs->present = 1;
2601     lhs->dpl = 3;
2602     lhs->db = 0;
2603     lhs->s = 1;
2604     lhs->l = 0;
2605     lhs->g = 0;
2606     lhs->avl = 0;
2607     lhs->unusable = 0;
2608 }
2609 
2610 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2611 {
2612     unsigned flags = rhs->flags;
2613     lhs->selector = rhs->selector;
2614     lhs->base = rhs->base;
2615     lhs->limit = rhs->limit;
2616     lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
2617     lhs->present = (flags & DESC_P_MASK) != 0;
2618     lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
2619     lhs->db = (flags >> DESC_B_SHIFT) & 1;
2620     lhs->s = (flags & DESC_S_MASK) != 0;
2621     lhs->l = (flags >> DESC_L_SHIFT) & 1;
2622     lhs->g = (flags & DESC_G_MASK) != 0;
2623     lhs->avl = (flags & DESC_AVL_MASK) != 0;
2624     lhs->unusable = !lhs->present;
2625     lhs->padding = 0;
2626 }
2627 
2628 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
2629 {
2630     lhs->selector = rhs->selector;
2631     lhs->base = rhs->base;
2632     lhs->limit = rhs->limit;
2633     lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
2634                  ((rhs->present && !rhs->unusable) * DESC_P_MASK) |
2635                  (rhs->dpl << DESC_DPL_SHIFT) |
2636                  (rhs->db << DESC_B_SHIFT) |
2637                  (rhs->s * DESC_S_MASK) |
2638                  (rhs->l << DESC_L_SHIFT) |
2639                  (rhs->g * DESC_G_MASK) |
2640                  (rhs->avl * DESC_AVL_MASK);
2641 }
2642 
2643 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
2644 {
2645     if (set) {
2646         *kvm_reg = *qemu_reg;
2647     } else {
2648         *qemu_reg = *kvm_reg;
2649     }
2650 }
2651 
2652 static int kvm_getput_regs(X86CPU *cpu, int set)
2653 {
2654     CPUX86State *env = &cpu->env;
2655     struct kvm_regs regs;
2656     int ret = 0;
2657 
2658     if (!set) {
2659         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
2660         if (ret < 0) {
2661             return ret;
2662         }
2663     }
2664 
2665     kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
2666     kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
2667     kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
2668     kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
2669     kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
2670     kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
2671     kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
2672     kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
2673 #ifdef TARGET_X86_64
2674     kvm_getput_reg(&regs.r8, &env->regs[8], set);
2675     kvm_getput_reg(&regs.r9, &env->regs[9], set);
2676     kvm_getput_reg(&regs.r10, &env->regs[10], set);
2677     kvm_getput_reg(&regs.r11, &env->regs[11], set);
2678     kvm_getput_reg(&regs.r12, &env->regs[12], set);
2679     kvm_getput_reg(&regs.r13, &env->regs[13], set);
2680     kvm_getput_reg(&regs.r14, &env->regs[14], set);
2681     kvm_getput_reg(&regs.r15, &env->regs[15], set);
2682 #endif
2683 
2684     kvm_getput_reg(&regs.rflags, &env->eflags, set);
2685     kvm_getput_reg(&regs.rip, &env->eip, set);
2686 
2687     if (set) {
2688         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
2689     }
2690 
2691     return ret;
2692 }
2693 
2694 static int kvm_put_fpu(X86CPU *cpu)
2695 {
2696     CPUX86State *env = &cpu->env;
2697     struct kvm_fpu fpu;
2698     int i;
2699 
2700     memset(&fpu, 0, sizeof fpu);
2701     fpu.fsw = env->fpus & ~(7 << 11);
2702     fpu.fsw |= (env->fpstt & 7) << 11;
2703     fpu.fcw = env->fpuc;
2704     fpu.last_opcode = env->fpop;
2705     fpu.last_ip = env->fpip;
2706     fpu.last_dp = env->fpdp;
2707     for (i = 0; i < 8; ++i) {
2708         fpu.ftwx |= (!env->fptags[i]) << i;
2709     }
2710     memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
2711     for (i = 0; i < CPU_NB_REGS; i++) {
2712         stq_p(&fpu.xmm[i][0], env->xmm_regs[i].ZMM_Q(0));
2713         stq_p(&fpu.xmm[i][8], env->xmm_regs[i].ZMM_Q(1));
2714     }
2715     fpu.mxcsr = env->mxcsr;
2716 
2717     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
2718 }
2719 
2720 static int kvm_put_xsave(X86CPU *cpu)
2721 {
2722     CPUX86State *env = &cpu->env;
2723     void *xsave = env->xsave_buf;
2724 
2725     if (!has_xsave) {
2726         return kvm_put_fpu(cpu);
2727     }
2728     x86_cpu_xsave_all_areas(cpu, xsave, env->xsave_buf_len);
2729 
2730     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
2731 }
2732 
2733 static int kvm_put_xcrs(X86CPU *cpu)
2734 {
2735     CPUX86State *env = &cpu->env;
2736     struct kvm_xcrs xcrs = {};
2737 
2738     if (!has_xcrs) {
2739         return 0;
2740     }
2741 
2742     xcrs.nr_xcrs = 1;
2743     xcrs.flags = 0;
2744     xcrs.xcrs[0].xcr = 0;
2745     xcrs.xcrs[0].value = env->xcr0;
2746     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
2747 }
2748 
2749 static int kvm_put_sregs(X86CPU *cpu)
2750 {
2751     CPUX86State *env = &cpu->env;
2752     struct kvm_sregs sregs;
2753 
2754     /*
2755      * The interrupt_bitmap is ignored because KVM_SET_SREGS is
2756      * always followed by KVM_SET_VCPU_EVENTS.
2757      */
2758     memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
2759 
2760     if ((env->eflags & VM_MASK)) {
2761         set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
2762         set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
2763         set_v8086_seg(&sregs.es, &env->segs[R_ES]);
2764         set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
2765         set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
2766         set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
2767     } else {
2768         set_seg(&sregs.cs, &env->segs[R_CS]);
2769         set_seg(&sregs.ds, &env->segs[R_DS]);
2770         set_seg(&sregs.es, &env->segs[R_ES]);
2771         set_seg(&sregs.fs, &env->segs[R_FS]);
2772         set_seg(&sregs.gs, &env->segs[R_GS]);
2773         set_seg(&sregs.ss, &env->segs[R_SS]);
2774     }
2775 
2776     set_seg(&sregs.tr, &env->tr);
2777     set_seg(&sregs.ldt, &env->ldt);
2778 
2779     sregs.idt.limit = env->idt.limit;
2780     sregs.idt.base = env->idt.base;
2781     memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
2782     sregs.gdt.limit = env->gdt.limit;
2783     sregs.gdt.base = env->gdt.base;
2784     memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
2785 
2786     sregs.cr0 = env->cr[0];
2787     sregs.cr2 = env->cr[2];
2788     sregs.cr3 = env->cr[3];
2789     sregs.cr4 = env->cr[4];
2790 
2791     sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
2792     sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
2793 
2794     sregs.efer = env->efer;
2795 
2796     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
2797 }
2798 
2799 static int kvm_put_sregs2(X86CPU *cpu)
2800 {
2801     CPUX86State *env = &cpu->env;
2802     struct kvm_sregs2 sregs;
2803     int i;
2804 
2805     sregs.flags = 0;
2806 
2807     if ((env->eflags & VM_MASK)) {
2808         set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
2809         set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
2810         set_v8086_seg(&sregs.es, &env->segs[R_ES]);
2811         set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
2812         set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
2813         set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
2814     } else {
2815         set_seg(&sregs.cs, &env->segs[R_CS]);
2816         set_seg(&sregs.ds, &env->segs[R_DS]);
2817         set_seg(&sregs.es, &env->segs[R_ES]);
2818         set_seg(&sregs.fs, &env->segs[R_FS]);
2819         set_seg(&sregs.gs, &env->segs[R_GS]);
2820         set_seg(&sregs.ss, &env->segs[R_SS]);
2821     }
2822 
2823     set_seg(&sregs.tr, &env->tr);
2824     set_seg(&sregs.ldt, &env->ldt);
2825 
2826     sregs.idt.limit = env->idt.limit;
2827     sregs.idt.base = env->idt.base;
2828     memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
2829     sregs.gdt.limit = env->gdt.limit;
2830     sregs.gdt.base = env->gdt.base;
2831     memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
2832 
2833     sregs.cr0 = env->cr[0];
2834     sregs.cr2 = env->cr[2];
2835     sregs.cr3 = env->cr[3];
2836     sregs.cr4 = env->cr[4];
2837 
2838     sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
2839     sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
2840 
2841     sregs.efer = env->efer;
2842 
2843     if (env->pdptrs_valid) {
2844         for (i = 0; i < 4; i++) {
2845             sregs.pdptrs[i] = env->pdptrs[i];
2846         }
2847         sregs.flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
2848     }
2849 
2850     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS2, &sregs);
2851 }
2852 
2853 
2854 static void kvm_msr_buf_reset(X86CPU *cpu)
2855 {
2856     memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
2857 }
2858 
2859 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
2860 {
2861     struct kvm_msrs *msrs = cpu->kvm_msr_buf;
2862     void *limit = ((void *)msrs) + MSR_BUF_SIZE;
2863     struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
2864 
2865     assert((void *)(entry + 1) <= limit);
2866 
2867     entry->index = index;
2868     entry->reserved = 0;
2869     entry->data = value;
2870     msrs->nmsrs++;
2871 }
2872 
2873 static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
2874 {
2875     kvm_msr_buf_reset(cpu);
2876     kvm_msr_entry_add(cpu, index, value);
2877 
2878     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
2879 }
2880 
2881 static int kvm_get_one_msr(X86CPU *cpu, int index, uint64_t *value)
2882 {
2883     int ret;
2884     struct {
2885         struct kvm_msrs info;
2886         struct kvm_msr_entry entries[1];
2887     } msr_data = {
2888         .info.nmsrs = 1,
2889         .entries[0].index = index,
2890     };
2891 
2892     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
2893     if (ret < 0) {
2894         return ret;
2895     }
2896     assert(ret == 1);
2897     *value = msr_data.entries[0].data;
2898     return ret;
2899 }
2900 void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
2901 {
2902     int ret;
2903 
2904     ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
2905     assert(ret == 1);
2906 }
2907 
2908 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
2909 {
2910     CPUX86State *env = &cpu->env;
2911     int ret;
2912 
2913     if (!has_msr_tsc_deadline) {
2914         return 0;
2915     }
2916 
2917     ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
2918     if (ret < 0) {
2919         return ret;
2920     }
2921 
2922     assert(ret == 1);
2923     return 0;
2924 }
2925 
2926 /*
2927  * Provide a separate write service for the feature control MSR in order to
2928  * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
2929  * before writing any other state because forcibly leaving nested mode
2930  * invalidates the VCPU state.
2931  */
2932 static int kvm_put_msr_feature_control(X86CPU *cpu)
2933 {
2934     int ret;
2935 
2936     if (!has_msr_feature_control) {
2937         return 0;
2938     }
2939 
2940     ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
2941                           cpu->env.msr_ia32_feature_control);
2942     if (ret < 0) {
2943         return ret;
2944     }
2945 
2946     assert(ret == 1);
2947     return 0;
2948 }
2949 
2950 static uint64_t make_vmx_msr_value(uint32_t index, uint32_t features)
2951 {
2952     uint32_t default1, can_be_one, can_be_zero;
2953     uint32_t must_be_one;
2954 
2955     switch (index) {
2956     case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2957         default1 = 0x00000016;
2958         break;
2959     case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2960         default1 = 0x0401e172;
2961         break;
2962     case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
2963         default1 = 0x000011ff;
2964         break;
2965     case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2966         default1 = 0x00036dff;
2967         break;
2968     case MSR_IA32_VMX_PROCBASED_CTLS2:
2969         default1 = 0;
2970         break;
2971     default:
2972         abort();
2973     }
2974 
2975     /* If a feature bit is set, the control can be either set or clear.
2976      * Otherwise the value is limited to either 0 or 1 by default1.
2977      */
2978     can_be_one = features | default1;
2979     can_be_zero = features | ~default1;
2980     must_be_one = ~can_be_zero;
2981 
2982     /*
2983      * Bit 0:31 -> 0 if the control bit can be zero (i.e. 1 if it must be one).
2984      * Bit 32:63 -> 1 if the control bit can be one.
2985      */
2986     return must_be_one | (((uint64_t)can_be_one) << 32);
2987 }
2988 
2989 static void kvm_msr_entry_add_vmx(X86CPU *cpu, FeatureWordArray f)
2990 {
2991     uint64_t kvm_vmx_basic =
2992         kvm_arch_get_supported_msr_feature(kvm_state,
2993                                            MSR_IA32_VMX_BASIC);
2994 
2995     if (!kvm_vmx_basic) {
2996         /* If the kernel doesn't support VMX feature (kvm_intel.nested=0),
2997          * then kvm_vmx_basic will be 0 and KVM_SET_MSR will fail.
2998          */
2999         return;
3000     }
3001 
3002     uint64_t kvm_vmx_misc =
3003         kvm_arch_get_supported_msr_feature(kvm_state,
3004                                            MSR_IA32_VMX_MISC);
3005     uint64_t kvm_vmx_ept_vpid =
3006         kvm_arch_get_supported_msr_feature(kvm_state,
3007                                            MSR_IA32_VMX_EPT_VPID_CAP);
3008 
3009     /*
3010      * If the guest is 64-bit, a value of 1 is allowed for the host address
3011      * space size vmexit control.
3012      */
3013     uint64_t fixed_vmx_exit = f[FEAT_8000_0001_EDX] & CPUID_EXT2_LM
3014         ? (uint64_t)VMX_VM_EXIT_HOST_ADDR_SPACE_SIZE << 32 : 0;
3015 
3016     /*
3017      * Bits 0-30, 32-44 and 50-53 come from the host.  KVM should
3018      * not change them for backwards compatibility.
3019      */
3020     uint64_t fixed_vmx_basic = kvm_vmx_basic &
3021         (MSR_VMX_BASIC_VMCS_REVISION_MASK |
3022          MSR_VMX_BASIC_VMXON_REGION_SIZE_MASK |
3023          MSR_VMX_BASIC_VMCS_MEM_TYPE_MASK);
3024 
3025     /*
3026      * Same for bits 0-4 and 25-27.  Bits 16-24 (CR3 target count) can
3027      * change in the future but are always zero for now, clear them to be
3028      * future proof.  Bits 32-63 in theory could change, though KVM does
3029      * not support dual-monitor treatment and probably never will; mask
3030      * them out as well.
3031      */
3032     uint64_t fixed_vmx_misc = kvm_vmx_misc &
3033         (MSR_VMX_MISC_PREEMPTION_TIMER_SHIFT_MASK |
3034          MSR_VMX_MISC_MAX_MSR_LIST_SIZE_MASK);
3035 
3036     /*
3037      * EPT memory types should not change either, so we do not bother
3038      * adding features for them.
3039      */
3040     uint64_t fixed_vmx_ept_mask =
3041             (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_ENABLE_EPT ?
3042              MSR_VMX_EPT_UC | MSR_VMX_EPT_WB : 0);
3043     uint64_t fixed_vmx_ept_vpid = kvm_vmx_ept_vpid & fixed_vmx_ept_mask;
3044 
3045     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
3046                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
3047                                          f[FEAT_VMX_PROCBASED_CTLS]));
3048     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PINBASED_CTLS,
3049                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_PINBASED_CTLS,
3050                                          f[FEAT_VMX_PINBASED_CTLS]));
3051     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_EXIT_CTLS,
3052                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_EXIT_CTLS,
3053                                          f[FEAT_VMX_EXIT_CTLS]) | fixed_vmx_exit);
3054     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_ENTRY_CTLS,
3055                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_ENTRY_CTLS,
3056                                          f[FEAT_VMX_ENTRY_CTLS]));
3057     kvm_msr_entry_add(cpu, MSR_IA32_VMX_PROCBASED_CTLS2,
3058                       make_vmx_msr_value(MSR_IA32_VMX_PROCBASED_CTLS2,
3059                                          f[FEAT_VMX_SECONDARY_CTLS]));
3060     kvm_msr_entry_add(cpu, MSR_IA32_VMX_EPT_VPID_CAP,
3061                       f[FEAT_VMX_EPT_VPID_CAPS] | fixed_vmx_ept_vpid);
3062     kvm_msr_entry_add(cpu, MSR_IA32_VMX_BASIC,
3063                       f[FEAT_VMX_BASIC] | fixed_vmx_basic);
3064     kvm_msr_entry_add(cpu, MSR_IA32_VMX_MISC,
3065                       f[FEAT_VMX_MISC] | fixed_vmx_misc);
3066     if (has_msr_vmx_vmfunc) {
3067         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMFUNC, f[FEAT_VMX_VMFUNC]);
3068     }
3069 
3070     /*
3071      * Just to be safe, write these with constant values.  The CRn_FIXED1
3072      * MSRs are generated by KVM based on the vCPU's CPUID.
3073      */
3074     kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR0_FIXED0,
3075                       CR0_PE_MASK | CR0_PG_MASK | CR0_NE_MASK);
3076     kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR4_FIXED0,
3077                       CR4_VMXE_MASK);
3078 
3079     if (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_TSC_SCALING) {
3080         /* TSC multiplier (0x2032).  */
3081         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x32);
3082     } else {
3083         /* Preemption timer (0x482E).  */
3084         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x2E);
3085     }
3086 }
3087 
3088 static void kvm_msr_entry_add_perf(X86CPU *cpu, FeatureWordArray f)
3089 {
3090     uint64_t kvm_perf_cap =
3091         kvm_arch_get_supported_msr_feature(kvm_state,
3092                                            MSR_IA32_PERF_CAPABILITIES);
3093 
3094     if (kvm_perf_cap) {
3095         kvm_msr_entry_add(cpu, MSR_IA32_PERF_CAPABILITIES,
3096                         kvm_perf_cap & f[FEAT_PERF_CAPABILITIES]);
3097     }
3098 }
3099 
3100 static int kvm_buf_set_msrs(X86CPU *cpu)
3101 {
3102     int ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
3103     if (ret < 0) {
3104         return ret;
3105     }
3106 
3107     if (ret < cpu->kvm_msr_buf->nmsrs) {
3108         struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
3109         error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,
3110                      (uint32_t)e->index, (uint64_t)e->data);
3111     }
3112 
3113     assert(ret == cpu->kvm_msr_buf->nmsrs);
3114     return 0;
3115 }
3116 
3117 static void kvm_init_msrs(X86CPU *cpu)
3118 {
3119     CPUX86State *env = &cpu->env;
3120 
3121     kvm_msr_buf_reset(cpu);
3122     if (has_msr_arch_capabs) {
3123         kvm_msr_entry_add(cpu, MSR_IA32_ARCH_CAPABILITIES,
3124                           env->features[FEAT_ARCH_CAPABILITIES]);
3125     }
3126 
3127     if (has_msr_core_capabs) {
3128         kvm_msr_entry_add(cpu, MSR_IA32_CORE_CAPABILITY,
3129                           env->features[FEAT_CORE_CAPABILITY]);
3130     }
3131 
3132     if (has_msr_perf_capabs && cpu->enable_pmu) {
3133         kvm_msr_entry_add_perf(cpu, env->features);
3134     }
3135 
3136     if (has_msr_ucode_rev) {
3137         kvm_msr_entry_add(cpu, MSR_IA32_UCODE_REV, cpu->ucode_rev);
3138     }
3139 
3140     /*
3141      * Older kernels do not include VMX MSRs in KVM_GET_MSR_INDEX_LIST, but
3142      * all kernels with MSR features should have them.
3143      */
3144     if (kvm_feature_msrs && cpu_has_vmx(env)) {
3145         kvm_msr_entry_add_vmx(cpu, env->features);
3146     }
3147 
3148     assert(kvm_buf_set_msrs(cpu) == 0);
3149 }
3150 
3151 static int kvm_put_msrs(X86CPU *cpu, int level)
3152 {
3153     CPUX86State *env = &cpu->env;
3154     int i;
3155 
3156     kvm_msr_buf_reset(cpu);
3157 
3158     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
3159     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
3160     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
3161     kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
3162     if (has_msr_star) {
3163         kvm_msr_entry_add(cpu, MSR_STAR, env->star);
3164     }
3165     if (has_msr_hsave_pa) {
3166         kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
3167     }
3168     if (has_msr_tsc_aux) {
3169         kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
3170     }
3171     if (has_msr_tsc_adjust) {
3172         kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
3173     }
3174     if (has_msr_misc_enable) {
3175         kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
3176                           env->msr_ia32_misc_enable);
3177     }
3178     if (has_msr_smbase) {
3179         kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
3180     }
3181     if (has_msr_smi_count) {
3182         kvm_msr_entry_add(cpu, MSR_SMI_COUNT, env->msr_smi_count);
3183     }
3184     if (has_msr_pkrs) {
3185         kvm_msr_entry_add(cpu, MSR_IA32_PKRS, env->pkrs);
3186     }
3187     if (has_msr_bndcfgs) {
3188         kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
3189     }
3190     if (has_msr_xss) {
3191         kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
3192     }
3193     if (has_msr_umwait) {
3194         kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, env->umwait);
3195     }
3196     if (has_msr_spec_ctrl) {
3197         kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, env->spec_ctrl);
3198     }
3199     if (has_tsc_scale_msr) {
3200         kvm_msr_entry_add(cpu, MSR_AMD64_TSC_RATIO, env->amd_tsc_scale_msr);
3201     }
3202 
3203     if (has_msr_tsx_ctrl) {
3204         kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, env->tsx_ctrl);
3205     }
3206     if (has_msr_virt_ssbd) {
3207         kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, env->virt_ssbd);
3208     }
3209 
3210 #ifdef TARGET_X86_64
3211     if (lm_capable_kernel) {
3212         kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
3213         kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
3214         kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
3215         kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
3216     }
3217 #endif
3218 
3219     /*
3220      * The following MSRs have side effects on the guest or are too heavy
3221      * for normal writeback. Limit them to reset or full state updates.
3222      */
3223     if (level >= KVM_PUT_RESET_STATE) {
3224         kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
3225         kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
3226         kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
3227         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
3228             kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, env->async_pf_int_msr);
3229         }
3230         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
3231             kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
3232         }
3233         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
3234             kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
3235         }
3236         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
3237             kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
3238         }
3239 
3240         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
3241             kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, env->poll_control_msr);
3242         }
3243 
3244         if (has_architectural_pmu_version > 0) {
3245             if (has_architectural_pmu_version > 1) {
3246                 /* Stop the counter.  */
3247                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
3248                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
3249             }
3250 
3251             /* Set the counter values.  */
3252             for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
3253                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
3254                                   env->msr_fixed_counters[i]);
3255             }
3256             for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
3257                 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
3258                                   env->msr_gp_counters[i]);
3259                 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
3260                                   env->msr_gp_evtsel[i]);
3261             }
3262             if (has_architectural_pmu_version > 1) {
3263                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
3264                                   env->msr_global_status);
3265                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
3266                                   env->msr_global_ovf_ctrl);
3267 
3268                 /* Now start the PMU.  */
3269                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
3270                                   env->msr_fixed_ctr_ctrl);
3271                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
3272                                   env->msr_global_ctrl);
3273             }
3274         }
3275         /*
3276          * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,
3277          * only sync them to KVM on the first cpu
3278          */
3279         if (current_cpu == first_cpu) {
3280             if (has_msr_hv_hypercall) {
3281                 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
3282                                   env->msr_hv_guest_os_id);
3283                 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
3284                                   env->msr_hv_hypercall);
3285             }
3286             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
3287                 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,
3288                                   env->msr_hv_tsc);
3289             }
3290             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
3291                 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL,
3292                                   env->msr_hv_reenlightenment_control);
3293                 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL,
3294                                   env->msr_hv_tsc_emulation_control);
3295                 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS,
3296                                   env->msr_hv_tsc_emulation_status);
3297             }
3298 #ifdef CONFIG_SYNDBG
3299             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNDBG) &&
3300                 has_msr_hv_syndbg_options) {
3301                 kvm_msr_entry_add(cpu, HV_X64_MSR_SYNDBG_OPTIONS,
3302                                   hyperv_syndbg_query_options());
3303             }
3304 #endif
3305         }
3306         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3307             kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
3308                               env->msr_hv_vapic);
3309         }
3310         if (has_msr_hv_crash) {
3311             int j;
3312 
3313             for (j = 0; j < HV_CRASH_PARAMS; j++)
3314                 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
3315                                   env->msr_hv_crash_params[j]);
3316 
3317             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);
3318         }
3319         if (has_msr_hv_runtime) {
3320             kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
3321         }
3322         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)
3323             && hv_vpindex_settable) {
3324             kvm_msr_entry_add(cpu, HV_X64_MSR_VP_INDEX,
3325                               hyperv_vp_index(CPU(cpu)));
3326         }
3327         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3328             int j;
3329 
3330             kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);
3331 
3332             kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
3333                               env->msr_hv_synic_control);
3334             kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
3335                               env->msr_hv_synic_evt_page);
3336             kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
3337                               env->msr_hv_synic_msg_page);
3338 
3339             for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
3340                 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
3341                                   env->msr_hv_synic_sint[j]);
3342             }
3343         }
3344         if (has_msr_hv_stimer) {
3345             int j;
3346 
3347             for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
3348                 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
3349                                 env->msr_hv_stimer_config[j]);
3350             }
3351 
3352             for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
3353                 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
3354                                 env->msr_hv_stimer_count[j]);
3355             }
3356         }
3357         if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3358             uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
3359 
3360             kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
3361             kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
3362             kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
3363             kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
3364             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
3365             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
3366             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
3367             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
3368             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
3369             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
3370             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
3371             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
3372             for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
3373                 /* The CPU GPs if we write to a bit above the physical limit of
3374                  * the host CPU (and KVM emulates that)
3375                  */
3376                 uint64_t mask = env->mtrr_var[i].mask;
3377                 mask &= phys_mask;
3378 
3379                 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
3380                                   env->mtrr_var[i].base);
3381                 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
3382             }
3383         }
3384         if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
3385             int addr_num = kvm_arch_get_supported_cpuid(kvm_state,
3386                                                     0x14, 1, R_EAX) & 0x7;
3387 
3388             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL,
3389                             env->msr_rtit_ctrl);
3390             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS,
3391                             env->msr_rtit_status);
3392             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE,
3393                             env->msr_rtit_output_base);
3394             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK,
3395                             env->msr_rtit_output_mask);
3396             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH,
3397                             env->msr_rtit_cr3_match);
3398             for (i = 0; i < addr_num; i++) {
3399                 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i,
3400                             env->msr_rtit_addrs[i]);
3401             }
3402         }
3403 
3404         if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_SGX_LC) {
3405             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH0,
3406                               env->msr_ia32_sgxlepubkeyhash[0]);
3407             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH1,
3408                               env->msr_ia32_sgxlepubkeyhash[1]);
3409             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH2,
3410                               env->msr_ia32_sgxlepubkeyhash[2]);
3411             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH3,
3412                               env->msr_ia32_sgxlepubkeyhash[3]);
3413         }
3414 
3415         if (env->features[FEAT_XSAVE] & CPUID_D_1_EAX_XFD) {
3416             kvm_msr_entry_add(cpu, MSR_IA32_XFD,
3417                               env->msr_xfd);
3418             kvm_msr_entry_add(cpu, MSR_IA32_XFD_ERR,
3419                               env->msr_xfd_err);
3420         }
3421 
3422         if (kvm_enabled() && cpu->enable_pmu &&
3423             (env->features[FEAT_7_0_EDX] & CPUID_7_0_EDX_ARCH_LBR)) {
3424             uint64_t depth;
3425             int i, ret;
3426 
3427             /*
3428              * Only migrate Arch LBR states when the host Arch LBR depth
3429              * equals that of source guest's, this is to avoid mismatch
3430              * of guest/host config for the msr hence avoid unexpected
3431              * misbehavior.
3432              */
3433             ret = kvm_get_one_msr(cpu, MSR_ARCH_LBR_DEPTH, &depth);
3434 
3435             if (ret == 1 && !!depth && depth == env->msr_lbr_depth) {
3436                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_CTL, env->msr_lbr_ctl);
3437                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_DEPTH, env->msr_lbr_depth);
3438 
3439                 for (i = 0; i < ARCH_LBR_NR_ENTRIES; i++) {
3440                     if (!env->lbr_records[i].from) {
3441                         continue;
3442                     }
3443                     kvm_msr_entry_add(cpu, MSR_ARCH_LBR_FROM_0 + i,
3444                                       env->lbr_records[i].from);
3445                     kvm_msr_entry_add(cpu, MSR_ARCH_LBR_TO_0 + i,
3446                                       env->lbr_records[i].to);
3447                     kvm_msr_entry_add(cpu, MSR_ARCH_LBR_INFO_0 + i,
3448                                       env->lbr_records[i].info);
3449                 }
3450             }
3451         }
3452 
3453         /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
3454          *       kvm_put_msr_feature_control. */
3455     }
3456 
3457     if (env->mcg_cap) {
3458         int i;
3459 
3460         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
3461         kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
3462         if (has_msr_mcg_ext_ctl) {
3463             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
3464         }
3465         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3466             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
3467         }
3468     }
3469 
3470     return kvm_buf_set_msrs(cpu);
3471 }
3472 
3473 
3474 static int kvm_get_fpu(X86CPU *cpu)
3475 {
3476     CPUX86State *env = &cpu->env;
3477     struct kvm_fpu fpu;
3478     int i, ret;
3479 
3480     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
3481     if (ret < 0) {
3482         return ret;
3483     }
3484 
3485     env->fpstt = (fpu.fsw >> 11) & 7;
3486     env->fpus = fpu.fsw;
3487     env->fpuc = fpu.fcw;
3488     env->fpop = fpu.last_opcode;
3489     env->fpip = fpu.last_ip;
3490     env->fpdp = fpu.last_dp;
3491     for (i = 0; i < 8; ++i) {
3492         env->fptags[i] = !((fpu.ftwx >> i) & 1);
3493     }
3494     memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
3495     for (i = 0; i < CPU_NB_REGS; i++) {
3496         env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
3497         env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
3498     }
3499     env->mxcsr = fpu.mxcsr;
3500 
3501     return 0;
3502 }
3503 
3504 static int kvm_get_xsave(X86CPU *cpu)
3505 {
3506     CPUX86State *env = &cpu->env;
3507     void *xsave = env->xsave_buf;
3508     int type, ret;
3509 
3510     if (!has_xsave) {
3511         return kvm_get_fpu(cpu);
3512     }
3513 
3514     type = has_xsave2 ? KVM_GET_XSAVE2 : KVM_GET_XSAVE;
3515     ret = kvm_vcpu_ioctl(CPU(cpu), type, xsave);
3516     if (ret < 0) {
3517         return ret;
3518     }
3519     x86_cpu_xrstor_all_areas(cpu, xsave, env->xsave_buf_len);
3520 
3521     return 0;
3522 }
3523 
3524 static int kvm_get_xcrs(X86CPU *cpu)
3525 {
3526     CPUX86State *env = &cpu->env;
3527     int i, ret;
3528     struct kvm_xcrs xcrs;
3529 
3530     if (!has_xcrs) {
3531         return 0;
3532     }
3533 
3534     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
3535     if (ret < 0) {
3536         return ret;
3537     }
3538 
3539     for (i = 0; i < xcrs.nr_xcrs; i++) {
3540         /* Only support xcr0 now */
3541         if (xcrs.xcrs[i].xcr == 0) {
3542             env->xcr0 = xcrs.xcrs[i].value;
3543             break;
3544         }
3545     }
3546     return 0;
3547 }
3548 
3549 static int kvm_get_sregs(X86CPU *cpu)
3550 {
3551     CPUX86State *env = &cpu->env;
3552     struct kvm_sregs sregs;
3553     int ret;
3554 
3555     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
3556     if (ret < 0) {
3557         return ret;
3558     }
3559 
3560     /*
3561      * The interrupt_bitmap is ignored because KVM_GET_SREGS is
3562      * always preceded by KVM_GET_VCPU_EVENTS.
3563      */
3564 
3565     get_seg(&env->segs[R_CS], &sregs.cs);
3566     get_seg(&env->segs[R_DS], &sregs.ds);
3567     get_seg(&env->segs[R_ES], &sregs.es);
3568     get_seg(&env->segs[R_FS], &sregs.fs);
3569     get_seg(&env->segs[R_GS], &sregs.gs);
3570     get_seg(&env->segs[R_SS], &sregs.ss);
3571 
3572     get_seg(&env->tr, &sregs.tr);
3573     get_seg(&env->ldt, &sregs.ldt);
3574 
3575     env->idt.limit = sregs.idt.limit;
3576     env->idt.base = sregs.idt.base;
3577     env->gdt.limit = sregs.gdt.limit;
3578     env->gdt.base = sregs.gdt.base;
3579 
3580     env->cr[0] = sregs.cr0;
3581     env->cr[2] = sregs.cr2;
3582     env->cr[3] = sregs.cr3;
3583     env->cr[4] = sregs.cr4;
3584 
3585     env->efer = sregs.efer;
3586 
3587     /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
3588     x86_update_hflags(env);
3589 
3590     return 0;
3591 }
3592 
3593 static int kvm_get_sregs2(X86CPU *cpu)
3594 {
3595     CPUX86State *env = &cpu->env;
3596     struct kvm_sregs2 sregs;
3597     int i, ret;
3598 
3599     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS2, &sregs);
3600     if (ret < 0) {
3601         return ret;
3602     }
3603 
3604     get_seg(&env->segs[R_CS], &sregs.cs);
3605     get_seg(&env->segs[R_DS], &sregs.ds);
3606     get_seg(&env->segs[R_ES], &sregs.es);
3607     get_seg(&env->segs[R_FS], &sregs.fs);
3608     get_seg(&env->segs[R_GS], &sregs.gs);
3609     get_seg(&env->segs[R_SS], &sregs.ss);
3610 
3611     get_seg(&env->tr, &sregs.tr);
3612     get_seg(&env->ldt, &sregs.ldt);
3613 
3614     env->idt.limit = sregs.idt.limit;
3615     env->idt.base = sregs.idt.base;
3616     env->gdt.limit = sregs.gdt.limit;
3617     env->gdt.base = sregs.gdt.base;
3618 
3619     env->cr[0] = sregs.cr0;
3620     env->cr[2] = sregs.cr2;
3621     env->cr[3] = sregs.cr3;
3622     env->cr[4] = sregs.cr4;
3623 
3624     env->efer = sregs.efer;
3625 
3626     env->pdptrs_valid = sregs.flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
3627 
3628     if (env->pdptrs_valid) {
3629         for (i = 0; i < 4; i++) {
3630             env->pdptrs[i] = sregs.pdptrs[i];
3631         }
3632     }
3633 
3634     /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
3635     x86_update_hflags(env);
3636 
3637     return 0;
3638 }
3639 
3640 static int kvm_get_msrs(X86CPU *cpu)
3641 {
3642     CPUX86State *env = &cpu->env;
3643     struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
3644     int ret, i;
3645     uint64_t mtrr_top_bits;
3646 
3647     kvm_msr_buf_reset(cpu);
3648 
3649     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
3650     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
3651     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
3652     kvm_msr_entry_add(cpu, MSR_PAT, 0);
3653     if (has_msr_star) {
3654         kvm_msr_entry_add(cpu, MSR_STAR, 0);
3655     }
3656     if (has_msr_hsave_pa) {
3657         kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
3658     }
3659     if (has_msr_tsc_aux) {
3660         kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
3661     }
3662     if (has_msr_tsc_adjust) {
3663         kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
3664     }
3665     if (has_msr_tsc_deadline) {
3666         kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
3667     }
3668     if (has_msr_misc_enable) {
3669         kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
3670     }
3671     if (has_msr_smbase) {
3672         kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
3673     }
3674     if (has_msr_smi_count) {
3675         kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
3676     }
3677     if (has_msr_feature_control) {
3678         kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
3679     }
3680     if (has_msr_pkrs) {
3681         kvm_msr_entry_add(cpu, MSR_IA32_PKRS, 0);
3682     }
3683     if (has_msr_bndcfgs) {
3684         kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
3685     }
3686     if (has_msr_xss) {
3687         kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
3688     }
3689     if (has_msr_umwait) {
3690         kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, 0);
3691     }
3692     if (has_msr_spec_ctrl) {
3693         kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
3694     }
3695     if (has_tsc_scale_msr) {
3696         kvm_msr_entry_add(cpu, MSR_AMD64_TSC_RATIO, 0);
3697     }
3698 
3699     if (has_msr_tsx_ctrl) {
3700         kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, 0);
3701     }
3702     if (has_msr_virt_ssbd) {
3703         kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, 0);
3704     }
3705     if (!env->tsc_valid) {
3706         kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
3707         env->tsc_valid = !runstate_is_running();
3708     }
3709 
3710 #ifdef TARGET_X86_64
3711     if (lm_capable_kernel) {
3712         kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
3713         kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
3714         kvm_msr_entry_add(cpu, MSR_FMASK, 0);
3715         kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
3716     }
3717 #endif
3718     kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
3719     kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
3720     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
3721         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, 0);
3722     }
3723     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
3724         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
3725     }
3726     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
3727         kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
3728     }
3729     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
3730         kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
3731     }
3732     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
3733         kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, 1);
3734     }
3735     if (has_architectural_pmu_version > 0) {
3736         if (has_architectural_pmu_version > 1) {
3737             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
3738             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
3739             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
3740             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
3741         }
3742         for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
3743             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
3744         }
3745         for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
3746             kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
3747             kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
3748         }
3749     }
3750 
3751     if (env->mcg_cap) {
3752         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
3753         kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
3754         if (has_msr_mcg_ext_ctl) {
3755             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
3756         }
3757         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3758             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
3759         }
3760     }
3761 
3762     if (has_msr_hv_hypercall) {
3763         kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
3764         kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
3765     }
3766     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3767         kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
3768     }
3769     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
3770         kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
3771     }
3772     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
3773         kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL, 0);
3774         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL, 0);
3775         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS, 0);
3776     }
3777     if (has_msr_hv_syndbg_options) {
3778         kvm_msr_entry_add(cpu, HV_X64_MSR_SYNDBG_OPTIONS, 0);
3779     }
3780     if (has_msr_hv_crash) {
3781         int j;
3782 
3783         for (j = 0; j < HV_CRASH_PARAMS; j++) {
3784             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
3785         }
3786     }
3787     if (has_msr_hv_runtime) {
3788         kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
3789     }
3790     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3791         uint32_t msr;
3792 
3793         kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
3794         kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
3795         kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
3796         for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
3797             kvm_msr_entry_add(cpu, msr, 0);
3798         }
3799     }
3800     if (has_msr_hv_stimer) {
3801         uint32_t msr;
3802 
3803         for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
3804              msr++) {
3805             kvm_msr_entry_add(cpu, msr, 0);
3806         }
3807     }
3808     if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3809         kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
3810         kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
3811         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
3812         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
3813         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
3814         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
3815         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
3816         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
3817         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
3818         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
3819         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
3820         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
3821         for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
3822             kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
3823             kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
3824         }
3825     }
3826 
3827     if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
3828         int addr_num =
3829             kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
3830 
3831         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
3832         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
3833         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
3834         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
3835         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
3836         for (i = 0; i < addr_num; i++) {
3837             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
3838         }
3839     }
3840 
3841     if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_SGX_LC) {
3842         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH0, 0);
3843         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH1, 0);
3844         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH2, 0);
3845         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH3, 0);
3846     }
3847 
3848     if (env->features[FEAT_XSAVE] & CPUID_D_1_EAX_XFD) {
3849         kvm_msr_entry_add(cpu, MSR_IA32_XFD, 0);
3850         kvm_msr_entry_add(cpu, MSR_IA32_XFD_ERR, 0);
3851     }
3852 
3853     if (kvm_enabled() && cpu->enable_pmu &&
3854         (env->features[FEAT_7_0_EDX] & CPUID_7_0_EDX_ARCH_LBR)) {
3855         uint64_t depth;
3856         int i, ret;
3857 
3858         ret = kvm_get_one_msr(cpu, MSR_ARCH_LBR_DEPTH, &depth);
3859         if (ret == 1 && depth == ARCH_LBR_NR_ENTRIES) {
3860             kvm_msr_entry_add(cpu, MSR_ARCH_LBR_CTL, 0);
3861             kvm_msr_entry_add(cpu, MSR_ARCH_LBR_DEPTH, 0);
3862 
3863             for (i = 0; i < ARCH_LBR_NR_ENTRIES; i++) {
3864                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_FROM_0 + i, 0);
3865                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_TO_0 + i, 0);
3866                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_INFO_0 + i, 0);
3867             }
3868         }
3869     }
3870 
3871     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
3872     if (ret < 0) {
3873         return ret;
3874     }
3875 
3876     if (ret < cpu->kvm_msr_buf->nmsrs) {
3877         struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
3878         error_report("error: failed to get MSR 0x%" PRIx32,
3879                      (uint32_t)e->index);
3880     }
3881 
3882     assert(ret == cpu->kvm_msr_buf->nmsrs);
3883     /*
3884      * MTRR masks: Each mask consists of 5 parts
3885      * a  10..0: must be zero
3886      * b  11   : valid bit
3887      * c n-1.12: actual mask bits
3888      * d  51..n: reserved must be zero
3889      * e  63.52: reserved must be zero
3890      *
3891      * 'n' is the number of physical bits supported by the CPU and is
3892      * apparently always <= 52.   We know our 'n' but don't know what
3893      * the destinations 'n' is; it might be smaller, in which case
3894      * it masks (c) on loading. It might be larger, in which case
3895      * we fill 'd' so that d..c is consistent irrespetive of the 'n'
3896      * we're migrating to.
3897      */
3898 
3899     if (cpu->fill_mtrr_mask) {
3900         QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
3901         assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
3902         mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
3903     } else {
3904         mtrr_top_bits = 0;
3905     }
3906 
3907     for (i = 0; i < ret; i++) {
3908         uint32_t index = msrs[i].index;
3909         switch (index) {
3910         case MSR_IA32_SYSENTER_CS:
3911             env->sysenter_cs = msrs[i].data;
3912             break;
3913         case MSR_IA32_SYSENTER_ESP:
3914             env->sysenter_esp = msrs[i].data;
3915             break;
3916         case MSR_IA32_SYSENTER_EIP:
3917             env->sysenter_eip = msrs[i].data;
3918             break;
3919         case MSR_PAT:
3920             env->pat = msrs[i].data;
3921             break;
3922         case MSR_STAR:
3923             env->star = msrs[i].data;
3924             break;
3925 #ifdef TARGET_X86_64
3926         case MSR_CSTAR:
3927             env->cstar = msrs[i].data;
3928             break;
3929         case MSR_KERNELGSBASE:
3930             env->kernelgsbase = msrs[i].data;
3931             break;
3932         case MSR_FMASK:
3933             env->fmask = msrs[i].data;
3934             break;
3935         case MSR_LSTAR:
3936             env->lstar = msrs[i].data;
3937             break;
3938 #endif
3939         case MSR_IA32_TSC:
3940             env->tsc = msrs[i].data;
3941             break;
3942         case MSR_TSC_AUX:
3943             env->tsc_aux = msrs[i].data;
3944             break;
3945         case MSR_TSC_ADJUST:
3946             env->tsc_adjust = msrs[i].data;
3947             break;
3948         case MSR_IA32_TSCDEADLINE:
3949             env->tsc_deadline = msrs[i].data;
3950             break;
3951         case MSR_VM_HSAVE_PA:
3952             env->vm_hsave = msrs[i].data;
3953             break;
3954         case MSR_KVM_SYSTEM_TIME:
3955             env->system_time_msr = msrs[i].data;
3956             break;
3957         case MSR_KVM_WALL_CLOCK:
3958             env->wall_clock_msr = msrs[i].data;
3959             break;
3960         case MSR_MCG_STATUS:
3961             env->mcg_status = msrs[i].data;
3962             break;
3963         case MSR_MCG_CTL:
3964             env->mcg_ctl = msrs[i].data;
3965             break;
3966         case MSR_MCG_EXT_CTL:
3967             env->mcg_ext_ctl = msrs[i].data;
3968             break;
3969         case MSR_IA32_MISC_ENABLE:
3970             env->msr_ia32_misc_enable = msrs[i].data;
3971             break;
3972         case MSR_IA32_SMBASE:
3973             env->smbase = msrs[i].data;
3974             break;
3975         case MSR_SMI_COUNT:
3976             env->msr_smi_count = msrs[i].data;
3977             break;
3978         case MSR_IA32_FEATURE_CONTROL:
3979             env->msr_ia32_feature_control = msrs[i].data;
3980             break;
3981         case MSR_IA32_BNDCFGS:
3982             env->msr_bndcfgs = msrs[i].data;
3983             break;
3984         case MSR_IA32_XSS:
3985             env->xss = msrs[i].data;
3986             break;
3987         case MSR_IA32_UMWAIT_CONTROL:
3988             env->umwait = msrs[i].data;
3989             break;
3990         case MSR_IA32_PKRS:
3991             env->pkrs = msrs[i].data;
3992             break;
3993         default:
3994             if (msrs[i].index >= MSR_MC0_CTL &&
3995                 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
3996                 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
3997             }
3998             break;
3999         case MSR_KVM_ASYNC_PF_EN:
4000             env->async_pf_en_msr = msrs[i].data;
4001             break;
4002         case MSR_KVM_ASYNC_PF_INT:
4003             env->async_pf_int_msr = msrs[i].data;
4004             break;
4005         case MSR_KVM_PV_EOI_EN:
4006             env->pv_eoi_en_msr = msrs[i].data;
4007             break;
4008         case MSR_KVM_STEAL_TIME:
4009             env->steal_time_msr = msrs[i].data;
4010             break;
4011         case MSR_KVM_POLL_CONTROL: {
4012             env->poll_control_msr = msrs[i].data;
4013             break;
4014         }
4015         case MSR_CORE_PERF_FIXED_CTR_CTRL:
4016             env->msr_fixed_ctr_ctrl = msrs[i].data;
4017             break;
4018         case MSR_CORE_PERF_GLOBAL_CTRL:
4019             env->msr_global_ctrl = msrs[i].data;
4020             break;
4021         case MSR_CORE_PERF_GLOBAL_STATUS:
4022             env->msr_global_status = msrs[i].data;
4023             break;
4024         case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
4025             env->msr_global_ovf_ctrl = msrs[i].data;
4026             break;
4027         case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
4028             env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
4029             break;
4030         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
4031             env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
4032             break;
4033         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
4034             env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
4035             break;
4036         case HV_X64_MSR_HYPERCALL:
4037             env->msr_hv_hypercall = msrs[i].data;
4038             break;
4039         case HV_X64_MSR_GUEST_OS_ID:
4040             env->msr_hv_guest_os_id = msrs[i].data;
4041             break;
4042         case HV_X64_MSR_APIC_ASSIST_PAGE:
4043             env->msr_hv_vapic = msrs[i].data;
4044             break;
4045         case HV_X64_MSR_REFERENCE_TSC:
4046             env->msr_hv_tsc = msrs[i].data;
4047             break;
4048         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4049             env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
4050             break;
4051         case HV_X64_MSR_VP_RUNTIME:
4052             env->msr_hv_runtime = msrs[i].data;
4053             break;
4054         case HV_X64_MSR_SCONTROL:
4055             env->msr_hv_synic_control = msrs[i].data;
4056             break;
4057         case HV_X64_MSR_SIEFP:
4058             env->msr_hv_synic_evt_page = msrs[i].data;
4059             break;
4060         case HV_X64_MSR_SIMP:
4061             env->msr_hv_synic_msg_page = msrs[i].data;
4062             break;
4063         case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
4064             env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
4065             break;
4066         case HV_X64_MSR_STIMER0_CONFIG:
4067         case HV_X64_MSR_STIMER1_CONFIG:
4068         case HV_X64_MSR_STIMER2_CONFIG:
4069         case HV_X64_MSR_STIMER3_CONFIG:
4070             env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
4071                                 msrs[i].data;
4072             break;
4073         case HV_X64_MSR_STIMER0_COUNT:
4074         case HV_X64_MSR_STIMER1_COUNT:
4075         case HV_X64_MSR_STIMER2_COUNT:
4076         case HV_X64_MSR_STIMER3_COUNT:
4077             env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
4078                                 msrs[i].data;
4079             break;
4080         case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4081             env->msr_hv_reenlightenment_control = msrs[i].data;
4082             break;
4083         case HV_X64_MSR_TSC_EMULATION_CONTROL:
4084             env->msr_hv_tsc_emulation_control = msrs[i].data;
4085             break;
4086         case HV_X64_MSR_TSC_EMULATION_STATUS:
4087             env->msr_hv_tsc_emulation_status = msrs[i].data;
4088             break;
4089         case HV_X64_MSR_SYNDBG_OPTIONS:
4090             env->msr_hv_syndbg_options = msrs[i].data;
4091             break;
4092         case MSR_MTRRdefType:
4093             env->mtrr_deftype = msrs[i].data;
4094             break;
4095         case MSR_MTRRfix64K_00000:
4096             env->mtrr_fixed[0] = msrs[i].data;
4097             break;
4098         case MSR_MTRRfix16K_80000:
4099             env->mtrr_fixed[1] = msrs[i].data;
4100             break;
4101         case MSR_MTRRfix16K_A0000:
4102             env->mtrr_fixed[2] = msrs[i].data;
4103             break;
4104         case MSR_MTRRfix4K_C0000:
4105             env->mtrr_fixed[3] = msrs[i].data;
4106             break;
4107         case MSR_MTRRfix4K_C8000:
4108             env->mtrr_fixed[4] = msrs[i].data;
4109             break;
4110         case MSR_MTRRfix4K_D0000:
4111             env->mtrr_fixed[5] = msrs[i].data;
4112             break;
4113         case MSR_MTRRfix4K_D8000:
4114             env->mtrr_fixed[6] = msrs[i].data;
4115             break;
4116         case MSR_MTRRfix4K_E0000:
4117             env->mtrr_fixed[7] = msrs[i].data;
4118             break;
4119         case MSR_MTRRfix4K_E8000:
4120             env->mtrr_fixed[8] = msrs[i].data;
4121             break;
4122         case MSR_MTRRfix4K_F0000:
4123             env->mtrr_fixed[9] = msrs[i].data;
4124             break;
4125         case MSR_MTRRfix4K_F8000:
4126             env->mtrr_fixed[10] = msrs[i].data;
4127             break;
4128         case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
4129             if (index & 1) {
4130                 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
4131                                                                mtrr_top_bits;
4132             } else {
4133                 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
4134             }
4135             break;
4136         case MSR_IA32_SPEC_CTRL:
4137             env->spec_ctrl = msrs[i].data;
4138             break;
4139         case MSR_AMD64_TSC_RATIO:
4140             env->amd_tsc_scale_msr = msrs[i].data;
4141             break;
4142         case MSR_IA32_TSX_CTRL:
4143             env->tsx_ctrl = msrs[i].data;
4144             break;
4145         case MSR_VIRT_SSBD:
4146             env->virt_ssbd = msrs[i].data;
4147             break;
4148         case MSR_IA32_RTIT_CTL:
4149             env->msr_rtit_ctrl = msrs[i].data;
4150             break;
4151         case MSR_IA32_RTIT_STATUS:
4152             env->msr_rtit_status = msrs[i].data;
4153             break;
4154         case MSR_IA32_RTIT_OUTPUT_BASE:
4155             env->msr_rtit_output_base = msrs[i].data;
4156             break;
4157         case MSR_IA32_RTIT_OUTPUT_MASK:
4158             env->msr_rtit_output_mask = msrs[i].data;
4159             break;
4160         case MSR_IA32_RTIT_CR3_MATCH:
4161             env->msr_rtit_cr3_match = msrs[i].data;
4162             break;
4163         case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
4164             env->msr_rtit_addrs[index - MSR_IA32_RTIT_ADDR0_A] = msrs[i].data;
4165             break;
4166         case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
4167             env->msr_ia32_sgxlepubkeyhash[index - MSR_IA32_SGXLEPUBKEYHASH0] =
4168                            msrs[i].data;
4169             break;
4170         case MSR_IA32_XFD:
4171             env->msr_xfd = msrs[i].data;
4172             break;
4173         case MSR_IA32_XFD_ERR:
4174             env->msr_xfd_err = msrs[i].data;
4175             break;
4176         case MSR_ARCH_LBR_CTL:
4177             env->msr_lbr_ctl = msrs[i].data;
4178             break;
4179         case MSR_ARCH_LBR_DEPTH:
4180             env->msr_lbr_depth = msrs[i].data;
4181             break;
4182         case MSR_ARCH_LBR_FROM_0 ... MSR_ARCH_LBR_FROM_0 + 31:
4183             env->lbr_records[index - MSR_ARCH_LBR_FROM_0].from = msrs[i].data;
4184             break;
4185         case MSR_ARCH_LBR_TO_0 ... MSR_ARCH_LBR_TO_0 + 31:
4186             env->lbr_records[index - MSR_ARCH_LBR_TO_0].to = msrs[i].data;
4187             break;
4188         case MSR_ARCH_LBR_INFO_0 ... MSR_ARCH_LBR_INFO_0 + 31:
4189             env->lbr_records[index - MSR_ARCH_LBR_INFO_0].info = msrs[i].data;
4190             break;
4191         }
4192     }
4193 
4194     return 0;
4195 }
4196 
4197 static int kvm_put_mp_state(X86CPU *cpu)
4198 {
4199     struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
4200 
4201     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
4202 }
4203 
4204 static int kvm_get_mp_state(X86CPU *cpu)
4205 {
4206     CPUState *cs = CPU(cpu);
4207     CPUX86State *env = &cpu->env;
4208     struct kvm_mp_state mp_state;
4209     int ret;
4210 
4211     ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
4212     if (ret < 0) {
4213         return ret;
4214     }
4215     env->mp_state = mp_state.mp_state;
4216     if (kvm_irqchip_in_kernel()) {
4217         cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
4218     }
4219     return 0;
4220 }
4221 
4222 static int kvm_get_apic(X86CPU *cpu)
4223 {
4224     DeviceState *apic = cpu->apic_state;
4225     struct kvm_lapic_state kapic;
4226     int ret;
4227 
4228     if (apic && kvm_irqchip_in_kernel()) {
4229         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
4230         if (ret < 0) {
4231             return ret;
4232         }
4233 
4234         kvm_get_apic_state(apic, &kapic);
4235     }
4236     return 0;
4237 }
4238 
4239 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
4240 {
4241     CPUState *cs = CPU(cpu);
4242     CPUX86State *env = &cpu->env;
4243     struct kvm_vcpu_events events = {};
4244 
4245     if (!kvm_has_vcpu_events()) {
4246         return 0;
4247     }
4248 
4249     events.flags = 0;
4250 
4251     if (has_exception_payload) {
4252         events.flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
4253         events.exception.pending = env->exception_pending;
4254         events.exception_has_payload = env->exception_has_payload;
4255         events.exception_payload = env->exception_payload;
4256     }
4257     events.exception.nr = env->exception_nr;
4258     events.exception.injected = env->exception_injected;
4259     events.exception.has_error_code = env->has_error_code;
4260     events.exception.error_code = env->error_code;
4261 
4262     events.interrupt.injected = (env->interrupt_injected >= 0);
4263     events.interrupt.nr = env->interrupt_injected;
4264     events.interrupt.soft = env->soft_interrupt;
4265 
4266     events.nmi.injected = env->nmi_injected;
4267     events.nmi.pending = env->nmi_pending;
4268     events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
4269 
4270     events.sipi_vector = env->sipi_vector;
4271 
4272     if (has_msr_smbase) {
4273         events.smi.smm = !!(env->hflags & HF_SMM_MASK);
4274         events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
4275         if (kvm_irqchip_in_kernel()) {
4276             /* As soon as these are moved to the kernel, remove them
4277              * from cs->interrupt_request.
4278              */
4279             events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
4280             events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
4281             cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
4282         } else {
4283             /* Keep these in cs->interrupt_request.  */
4284             events.smi.pending = 0;
4285             events.smi.latched_init = 0;
4286         }
4287         /* Stop SMI delivery on old machine types to avoid a reboot
4288          * on an inward migration of an old VM.
4289          */
4290         if (!cpu->kvm_no_smi_migration) {
4291             events.flags |= KVM_VCPUEVENT_VALID_SMM;
4292         }
4293     }
4294 
4295     if (level >= KVM_PUT_RESET_STATE) {
4296         events.flags |= KVM_VCPUEVENT_VALID_NMI_PENDING;
4297         if (env->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
4298             events.flags |= KVM_VCPUEVENT_VALID_SIPI_VECTOR;
4299         }
4300     }
4301 
4302     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
4303 }
4304 
4305 static int kvm_get_vcpu_events(X86CPU *cpu)
4306 {
4307     CPUX86State *env = &cpu->env;
4308     struct kvm_vcpu_events events;
4309     int ret;
4310 
4311     if (!kvm_has_vcpu_events()) {
4312         return 0;
4313     }
4314 
4315     memset(&events, 0, sizeof(events));
4316     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
4317     if (ret < 0) {
4318        return ret;
4319     }
4320 
4321     if (events.flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4322         env->exception_pending = events.exception.pending;
4323         env->exception_has_payload = events.exception_has_payload;
4324         env->exception_payload = events.exception_payload;
4325     } else {
4326         env->exception_pending = 0;
4327         env->exception_has_payload = false;
4328     }
4329     env->exception_injected = events.exception.injected;
4330     env->exception_nr =
4331         (env->exception_pending || env->exception_injected) ?
4332         events.exception.nr : -1;
4333     env->has_error_code = events.exception.has_error_code;
4334     env->error_code = events.exception.error_code;
4335 
4336     env->interrupt_injected =
4337         events.interrupt.injected ? events.interrupt.nr : -1;
4338     env->soft_interrupt = events.interrupt.soft;
4339 
4340     env->nmi_injected = events.nmi.injected;
4341     env->nmi_pending = events.nmi.pending;
4342     if (events.nmi.masked) {
4343         env->hflags2 |= HF2_NMI_MASK;
4344     } else {
4345         env->hflags2 &= ~HF2_NMI_MASK;
4346     }
4347 
4348     if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
4349         if (events.smi.smm) {
4350             env->hflags |= HF_SMM_MASK;
4351         } else {
4352             env->hflags &= ~HF_SMM_MASK;
4353         }
4354         if (events.smi.pending) {
4355             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
4356         } else {
4357             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
4358         }
4359         if (events.smi.smm_inside_nmi) {
4360             env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
4361         } else {
4362             env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
4363         }
4364         if (events.smi.latched_init) {
4365             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
4366         } else {
4367             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
4368         }
4369     }
4370 
4371     env->sipi_vector = events.sipi_vector;
4372 
4373     return 0;
4374 }
4375 
4376 static int kvm_guest_debug_workarounds(X86CPU *cpu)
4377 {
4378     CPUState *cs = CPU(cpu);
4379     CPUX86State *env = &cpu->env;
4380     int ret = 0;
4381     unsigned long reinject_trap = 0;
4382 
4383     if (!kvm_has_vcpu_events()) {
4384         if (env->exception_nr == EXCP01_DB) {
4385             reinject_trap = KVM_GUESTDBG_INJECT_DB;
4386         } else if (env->exception_injected == EXCP03_INT3) {
4387             reinject_trap = KVM_GUESTDBG_INJECT_BP;
4388         }
4389         kvm_reset_exception(env);
4390     }
4391 
4392     /*
4393      * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
4394      * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
4395      * by updating the debug state once again if single-stepping is on.
4396      * Another reason to call kvm_update_guest_debug here is a pending debug
4397      * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
4398      * reinject them via SET_GUEST_DEBUG.
4399      */
4400     if (reinject_trap ||
4401         (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
4402         ret = kvm_update_guest_debug(cs, reinject_trap);
4403     }
4404     return ret;
4405 }
4406 
4407 static int kvm_put_debugregs(X86CPU *cpu)
4408 {
4409     CPUX86State *env = &cpu->env;
4410     struct kvm_debugregs dbgregs;
4411     int i;
4412 
4413     if (!kvm_has_debugregs()) {
4414         return 0;
4415     }
4416 
4417     memset(&dbgregs, 0, sizeof(dbgregs));
4418     for (i = 0; i < 4; i++) {
4419         dbgregs.db[i] = env->dr[i];
4420     }
4421     dbgregs.dr6 = env->dr[6];
4422     dbgregs.dr7 = env->dr[7];
4423     dbgregs.flags = 0;
4424 
4425     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
4426 }
4427 
4428 static int kvm_get_debugregs(X86CPU *cpu)
4429 {
4430     CPUX86State *env = &cpu->env;
4431     struct kvm_debugregs dbgregs;
4432     int i, ret;
4433 
4434     if (!kvm_has_debugregs()) {
4435         return 0;
4436     }
4437 
4438     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
4439     if (ret < 0) {
4440         return ret;
4441     }
4442     for (i = 0; i < 4; i++) {
4443         env->dr[i] = dbgregs.db[i];
4444     }
4445     env->dr[4] = env->dr[6] = dbgregs.dr6;
4446     env->dr[5] = env->dr[7] = dbgregs.dr7;
4447 
4448     return 0;
4449 }
4450 
4451 static int kvm_put_nested_state(X86CPU *cpu)
4452 {
4453     CPUX86State *env = &cpu->env;
4454     int max_nested_state_len = kvm_max_nested_state_length();
4455 
4456     if (!env->nested_state) {
4457         return 0;
4458     }
4459 
4460     /*
4461      * Copy flags that are affected by reset from env->hflags and env->hflags2.
4462      */
4463     if (env->hflags & HF_GUEST_MASK) {
4464         env->nested_state->flags |= KVM_STATE_NESTED_GUEST_MODE;
4465     } else {
4466         env->nested_state->flags &= ~KVM_STATE_NESTED_GUEST_MODE;
4467     }
4468 
4469     /* Don't set KVM_STATE_NESTED_GIF_SET on VMX as it is illegal */
4470     if (cpu_has_svm(env) && (env->hflags2 & HF2_GIF_MASK)) {
4471         env->nested_state->flags |= KVM_STATE_NESTED_GIF_SET;
4472     } else {
4473         env->nested_state->flags &= ~KVM_STATE_NESTED_GIF_SET;
4474     }
4475 
4476     assert(env->nested_state->size <= max_nested_state_len);
4477     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_NESTED_STATE, env->nested_state);
4478 }
4479 
4480 static int kvm_get_nested_state(X86CPU *cpu)
4481 {
4482     CPUX86State *env = &cpu->env;
4483     int max_nested_state_len = kvm_max_nested_state_length();
4484     int ret;
4485 
4486     if (!env->nested_state) {
4487         return 0;
4488     }
4489 
4490     /*
4491      * It is possible that migration restored a smaller size into
4492      * nested_state->hdr.size than what our kernel support.
4493      * We preserve migration origin nested_state->hdr.size for
4494      * call to KVM_SET_NESTED_STATE but wish that our next call
4495      * to KVM_GET_NESTED_STATE will use max size our kernel support.
4496      */
4497     env->nested_state->size = max_nested_state_len;
4498 
4499     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_NESTED_STATE, env->nested_state);
4500     if (ret < 0) {
4501         return ret;
4502     }
4503 
4504     /*
4505      * Copy flags that are affected by reset to env->hflags and env->hflags2.
4506      */
4507     if (env->nested_state->flags & KVM_STATE_NESTED_GUEST_MODE) {
4508         env->hflags |= HF_GUEST_MASK;
4509     } else {
4510         env->hflags &= ~HF_GUEST_MASK;
4511     }
4512 
4513     /* Keep HF2_GIF_MASK set on !SVM as x86_cpu_pending_interrupt() needs it */
4514     if (cpu_has_svm(env)) {
4515         if (env->nested_state->flags & KVM_STATE_NESTED_GIF_SET) {
4516             env->hflags2 |= HF2_GIF_MASK;
4517         } else {
4518             env->hflags2 &= ~HF2_GIF_MASK;
4519         }
4520     }
4521 
4522     return ret;
4523 }
4524 
4525 int kvm_arch_put_registers(CPUState *cpu, int level)
4526 {
4527     X86CPU *x86_cpu = X86_CPU(cpu);
4528     int ret;
4529 
4530     assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
4531 
4532     /*
4533      * Put MSR_IA32_FEATURE_CONTROL first, this ensures the VM gets out of VMX
4534      * root operation upon vCPU reset. kvm_put_msr_feature_control() should also
4535      * preceed kvm_put_nested_state() when 'real' nested state is set.
4536      */
4537     if (level >= KVM_PUT_RESET_STATE) {
4538         ret = kvm_put_msr_feature_control(x86_cpu);
4539         if (ret < 0) {
4540             return ret;
4541         }
4542     }
4543 
4544     /* must be before kvm_put_nested_state so that EFER.SVME is set */
4545     ret = has_sregs2 ? kvm_put_sregs2(x86_cpu) : kvm_put_sregs(x86_cpu);
4546     if (ret < 0) {
4547         return ret;
4548     }
4549 
4550     if (level >= KVM_PUT_RESET_STATE) {
4551         ret = kvm_put_nested_state(x86_cpu);
4552         if (ret < 0) {
4553             return ret;
4554         }
4555     }
4556 
4557     if (level == KVM_PUT_FULL_STATE) {
4558         /* We don't check for kvm_arch_set_tsc_khz() errors here,
4559          * because TSC frequency mismatch shouldn't abort migration,
4560          * unless the user explicitly asked for a more strict TSC
4561          * setting (e.g. using an explicit "tsc-freq" option).
4562          */
4563         kvm_arch_set_tsc_khz(cpu);
4564     }
4565 
4566     ret = kvm_getput_regs(x86_cpu, 1);
4567     if (ret < 0) {
4568         return ret;
4569     }
4570     ret = kvm_put_xsave(x86_cpu);
4571     if (ret < 0) {
4572         return ret;
4573     }
4574     ret = kvm_put_xcrs(x86_cpu);
4575     if (ret < 0) {
4576         return ret;
4577     }
4578     /* must be before kvm_put_msrs */
4579     ret = kvm_inject_mce_oldstyle(x86_cpu);
4580     if (ret < 0) {
4581         return ret;
4582     }
4583     ret = kvm_put_msrs(x86_cpu, level);
4584     if (ret < 0) {
4585         return ret;
4586     }
4587     ret = kvm_put_vcpu_events(x86_cpu, level);
4588     if (ret < 0) {
4589         return ret;
4590     }
4591     if (level >= KVM_PUT_RESET_STATE) {
4592         ret = kvm_put_mp_state(x86_cpu);
4593         if (ret < 0) {
4594             return ret;
4595         }
4596     }
4597 
4598     ret = kvm_put_tscdeadline_msr(x86_cpu);
4599     if (ret < 0) {
4600         return ret;
4601     }
4602     ret = kvm_put_debugregs(x86_cpu);
4603     if (ret < 0) {
4604         return ret;
4605     }
4606     /* must be last */
4607     ret = kvm_guest_debug_workarounds(x86_cpu);
4608     if (ret < 0) {
4609         return ret;
4610     }
4611     return 0;
4612 }
4613 
4614 int kvm_arch_get_registers(CPUState *cs)
4615 {
4616     X86CPU *cpu = X86_CPU(cs);
4617     int ret;
4618 
4619     assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
4620 
4621     ret = kvm_get_vcpu_events(cpu);
4622     if (ret < 0) {
4623         goto out;
4624     }
4625     /*
4626      * KVM_GET_MPSTATE can modify CS and RIP, call it before
4627      * KVM_GET_REGS and KVM_GET_SREGS.
4628      */
4629     ret = kvm_get_mp_state(cpu);
4630     if (ret < 0) {
4631         goto out;
4632     }
4633     ret = kvm_getput_regs(cpu, 0);
4634     if (ret < 0) {
4635         goto out;
4636     }
4637     ret = kvm_get_xsave(cpu);
4638     if (ret < 0) {
4639         goto out;
4640     }
4641     ret = kvm_get_xcrs(cpu);
4642     if (ret < 0) {
4643         goto out;
4644     }
4645     ret = has_sregs2 ? kvm_get_sregs2(cpu) : kvm_get_sregs(cpu);
4646     if (ret < 0) {
4647         goto out;
4648     }
4649     ret = kvm_get_msrs(cpu);
4650     if (ret < 0) {
4651         goto out;
4652     }
4653     ret = kvm_get_apic(cpu);
4654     if (ret < 0) {
4655         goto out;
4656     }
4657     ret = kvm_get_debugregs(cpu);
4658     if (ret < 0) {
4659         goto out;
4660     }
4661     ret = kvm_get_nested_state(cpu);
4662     if (ret < 0) {
4663         goto out;
4664     }
4665     ret = 0;
4666  out:
4667     cpu_sync_bndcs_hflags(&cpu->env);
4668     return ret;
4669 }
4670 
4671 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
4672 {
4673     X86CPU *x86_cpu = X86_CPU(cpu);
4674     CPUX86State *env = &x86_cpu->env;
4675     int ret;
4676 
4677     /* Inject NMI */
4678     if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
4679         if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
4680             qemu_mutex_lock_iothread();
4681             cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
4682             qemu_mutex_unlock_iothread();
4683             DPRINTF("injected NMI\n");
4684             ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
4685             if (ret < 0) {
4686                 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
4687                         strerror(-ret));
4688             }
4689         }
4690         if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
4691             qemu_mutex_lock_iothread();
4692             cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
4693             qemu_mutex_unlock_iothread();
4694             DPRINTF("injected SMI\n");
4695             ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
4696             if (ret < 0) {
4697                 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
4698                         strerror(-ret));
4699             }
4700         }
4701     }
4702 
4703     if (!kvm_pic_in_kernel()) {
4704         qemu_mutex_lock_iothread();
4705     }
4706 
4707     /* Force the VCPU out of its inner loop to process any INIT requests
4708      * or (for userspace APIC, but it is cheap to combine the checks here)
4709      * pending TPR access reports.
4710      */
4711     if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
4712         if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
4713             !(env->hflags & HF_SMM_MASK)) {
4714             cpu->exit_request = 1;
4715         }
4716         if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
4717             cpu->exit_request = 1;
4718         }
4719     }
4720 
4721     if (!kvm_pic_in_kernel()) {
4722         /* Try to inject an interrupt if the guest can accept it */
4723         if (run->ready_for_interrupt_injection &&
4724             (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
4725             (env->eflags & IF_MASK)) {
4726             int irq;
4727 
4728             cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
4729             irq = cpu_get_pic_interrupt(env);
4730             if (irq >= 0) {
4731                 struct kvm_interrupt intr;
4732 
4733                 intr.irq = irq;
4734                 DPRINTF("injected interrupt %d\n", irq);
4735                 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
4736                 if (ret < 0) {
4737                     fprintf(stderr,
4738                             "KVM: injection failed, interrupt lost (%s)\n",
4739                             strerror(-ret));
4740                 }
4741             }
4742         }
4743 
4744         /* If we have an interrupt but the guest is not ready to receive an
4745          * interrupt, request an interrupt window exit.  This will
4746          * cause a return to userspace as soon as the guest is ready to
4747          * receive interrupts. */
4748         if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
4749             run->request_interrupt_window = 1;
4750         } else {
4751             run->request_interrupt_window = 0;
4752         }
4753 
4754         DPRINTF("setting tpr\n");
4755         run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
4756 
4757         qemu_mutex_unlock_iothread();
4758     }
4759 }
4760 
4761 static void kvm_rate_limit_on_bus_lock(void)
4762 {
4763     uint64_t delay_ns = ratelimit_calculate_delay(&bus_lock_ratelimit_ctrl, 1);
4764 
4765     if (delay_ns) {
4766         g_usleep(delay_ns / SCALE_US);
4767     }
4768 }
4769 
4770 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
4771 {
4772     X86CPU *x86_cpu = X86_CPU(cpu);
4773     CPUX86State *env = &x86_cpu->env;
4774 
4775     if (run->flags & KVM_RUN_X86_SMM) {
4776         env->hflags |= HF_SMM_MASK;
4777     } else {
4778         env->hflags &= ~HF_SMM_MASK;
4779     }
4780     if (run->if_flag) {
4781         env->eflags |= IF_MASK;
4782     } else {
4783         env->eflags &= ~IF_MASK;
4784     }
4785     if (run->flags & KVM_RUN_X86_BUS_LOCK) {
4786         kvm_rate_limit_on_bus_lock();
4787     }
4788 
4789     /* We need to protect the apic state against concurrent accesses from
4790      * different threads in case the userspace irqchip is used. */
4791     if (!kvm_irqchip_in_kernel()) {
4792         qemu_mutex_lock_iothread();
4793     }
4794     cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
4795     cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
4796     if (!kvm_irqchip_in_kernel()) {
4797         qemu_mutex_unlock_iothread();
4798     }
4799     return cpu_get_mem_attrs(env);
4800 }
4801 
4802 int kvm_arch_process_async_events(CPUState *cs)
4803 {
4804     X86CPU *cpu = X86_CPU(cs);
4805     CPUX86State *env = &cpu->env;
4806 
4807     if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
4808         /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
4809         assert(env->mcg_cap);
4810 
4811         cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
4812 
4813         kvm_cpu_synchronize_state(cs);
4814 
4815         if (env->exception_nr == EXCP08_DBLE) {
4816             /* this means triple fault */
4817             qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
4818             cs->exit_request = 1;
4819             return 0;
4820         }
4821         kvm_queue_exception(env, EXCP12_MCHK, 0, 0);
4822         env->has_error_code = 0;
4823 
4824         cs->halted = 0;
4825         if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
4826             env->mp_state = KVM_MP_STATE_RUNNABLE;
4827         }
4828     }
4829 
4830     if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
4831         !(env->hflags & HF_SMM_MASK)) {
4832         kvm_cpu_synchronize_state(cs);
4833         do_cpu_init(cpu);
4834     }
4835 
4836     if (kvm_irqchip_in_kernel()) {
4837         return 0;
4838     }
4839 
4840     if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
4841         cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
4842         apic_poll_irq(cpu->apic_state);
4843     }
4844     if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
4845          (env->eflags & IF_MASK)) ||
4846         (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
4847         cs->halted = 0;
4848     }
4849     if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
4850         kvm_cpu_synchronize_state(cs);
4851         do_cpu_sipi(cpu);
4852     }
4853     if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
4854         cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
4855         kvm_cpu_synchronize_state(cs);
4856         apic_handle_tpr_access_report(cpu->apic_state, env->eip,
4857                                       env->tpr_access_type);
4858     }
4859 
4860     return cs->halted;
4861 }
4862 
4863 static int kvm_handle_halt(X86CPU *cpu)
4864 {
4865     CPUState *cs = CPU(cpu);
4866     CPUX86State *env = &cpu->env;
4867 
4868     if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
4869           (env->eflags & IF_MASK)) &&
4870         !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
4871         cs->halted = 1;
4872         return EXCP_HLT;
4873     }
4874 
4875     return 0;
4876 }
4877 
4878 static int kvm_handle_tpr_access(X86CPU *cpu)
4879 {
4880     CPUState *cs = CPU(cpu);
4881     struct kvm_run *run = cs->kvm_run;
4882 
4883     apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
4884                                   run->tpr_access.is_write ? TPR_ACCESS_WRITE
4885                                                            : TPR_ACCESS_READ);
4886     return 1;
4887 }
4888 
4889 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
4890 {
4891     static const uint8_t int3 = 0xcc;
4892 
4893     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
4894         cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
4895         return -EINVAL;
4896     }
4897     return 0;
4898 }
4899 
4900 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
4901 {
4902     uint8_t int3;
4903 
4904     if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0)) {
4905         return -EINVAL;
4906     }
4907     if (int3 != 0xcc) {
4908         return 0;
4909     }
4910     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
4911         return -EINVAL;
4912     }
4913     return 0;
4914 }
4915 
4916 static struct {
4917     target_ulong addr;
4918     int len;
4919     int type;
4920 } hw_breakpoint[4];
4921 
4922 static int nb_hw_breakpoint;
4923 
4924 static int find_hw_breakpoint(target_ulong addr, int len, int type)
4925 {
4926     int n;
4927 
4928     for (n = 0; n < nb_hw_breakpoint; n++) {
4929         if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
4930             (hw_breakpoint[n].len == len || len == -1)) {
4931             return n;
4932         }
4933     }
4934     return -1;
4935 }
4936 
4937 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
4938                                   target_ulong len, int type)
4939 {
4940     switch (type) {
4941     case GDB_BREAKPOINT_HW:
4942         len = 1;
4943         break;
4944     case GDB_WATCHPOINT_WRITE:
4945     case GDB_WATCHPOINT_ACCESS:
4946         switch (len) {
4947         case 1:
4948             break;
4949         case 2:
4950         case 4:
4951         case 8:
4952             if (addr & (len - 1)) {
4953                 return -EINVAL;
4954             }
4955             break;
4956         default:
4957             return -EINVAL;
4958         }
4959         break;
4960     default:
4961         return -ENOSYS;
4962     }
4963 
4964     if (nb_hw_breakpoint == 4) {
4965         return -ENOBUFS;
4966     }
4967     if (find_hw_breakpoint(addr, len, type) >= 0) {
4968         return -EEXIST;
4969     }
4970     hw_breakpoint[nb_hw_breakpoint].addr = addr;
4971     hw_breakpoint[nb_hw_breakpoint].len = len;
4972     hw_breakpoint[nb_hw_breakpoint].type = type;
4973     nb_hw_breakpoint++;
4974 
4975     return 0;
4976 }
4977 
4978 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
4979                                   target_ulong len, int type)
4980 {
4981     int n;
4982 
4983     n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
4984     if (n < 0) {
4985         return -ENOENT;
4986     }
4987     nb_hw_breakpoint--;
4988     hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
4989 
4990     return 0;
4991 }
4992 
4993 void kvm_arch_remove_all_hw_breakpoints(void)
4994 {
4995     nb_hw_breakpoint = 0;
4996 }
4997 
4998 static CPUWatchpoint hw_watchpoint;
4999 
5000 static int kvm_handle_debug(X86CPU *cpu,
5001                             struct kvm_debug_exit_arch *arch_info)
5002 {
5003     CPUState *cs = CPU(cpu);
5004     CPUX86State *env = &cpu->env;
5005     int ret = 0;
5006     int n;
5007 
5008     if (arch_info->exception == EXCP01_DB) {
5009         if (arch_info->dr6 & DR6_BS) {
5010             if (cs->singlestep_enabled) {
5011                 ret = EXCP_DEBUG;
5012             }
5013         } else {
5014             for (n = 0; n < 4; n++) {
5015                 if (arch_info->dr6 & (1 << n)) {
5016                     switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
5017                     case 0x0:
5018                         ret = EXCP_DEBUG;
5019                         break;
5020                     case 0x1:
5021                         ret = EXCP_DEBUG;
5022                         cs->watchpoint_hit = &hw_watchpoint;
5023                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
5024                         hw_watchpoint.flags = BP_MEM_WRITE;
5025                         break;
5026                     case 0x3:
5027                         ret = EXCP_DEBUG;
5028                         cs->watchpoint_hit = &hw_watchpoint;
5029                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
5030                         hw_watchpoint.flags = BP_MEM_ACCESS;
5031                         break;
5032                     }
5033                 }
5034             }
5035         }
5036     } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
5037         ret = EXCP_DEBUG;
5038     }
5039     if (ret == 0) {
5040         cpu_synchronize_state(cs);
5041         assert(env->exception_nr == -1);
5042 
5043         /* pass to guest */
5044         kvm_queue_exception(env, arch_info->exception,
5045                             arch_info->exception == EXCP01_DB,
5046                             arch_info->dr6);
5047         env->has_error_code = 0;
5048     }
5049 
5050     return ret;
5051 }
5052 
5053 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
5054 {
5055     const uint8_t type_code[] = {
5056         [GDB_BREAKPOINT_HW] = 0x0,
5057         [GDB_WATCHPOINT_WRITE] = 0x1,
5058         [GDB_WATCHPOINT_ACCESS] = 0x3
5059     };
5060     const uint8_t len_code[] = {
5061         [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
5062     };
5063     int n;
5064 
5065     if (kvm_sw_breakpoints_active(cpu)) {
5066         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
5067     }
5068     if (nb_hw_breakpoint > 0) {
5069         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
5070         dbg->arch.debugreg[7] = 0x0600;
5071         for (n = 0; n < nb_hw_breakpoint; n++) {
5072             dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
5073             dbg->arch.debugreg[7] |= (2 << (n * 2)) |
5074                 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
5075                 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
5076         }
5077     }
5078 }
5079 
5080 static bool has_sgx_provisioning;
5081 
5082 static bool __kvm_enable_sgx_provisioning(KVMState *s)
5083 {
5084     int fd, ret;
5085 
5086     if (!kvm_vm_check_extension(s, KVM_CAP_SGX_ATTRIBUTE)) {
5087         return false;
5088     }
5089 
5090     fd = qemu_open_old("/dev/sgx_provision", O_RDONLY);
5091     if (fd < 0) {
5092         return false;
5093     }
5094 
5095     ret = kvm_vm_enable_cap(s, KVM_CAP_SGX_ATTRIBUTE, 0, fd);
5096     if (ret) {
5097         error_report("Could not enable SGX PROVISIONKEY: %s", strerror(-ret));
5098         exit(1);
5099     }
5100     close(fd);
5101     return true;
5102 }
5103 
5104 bool kvm_enable_sgx_provisioning(KVMState *s)
5105 {
5106     return MEMORIZE(__kvm_enable_sgx_provisioning(s), has_sgx_provisioning);
5107 }
5108 
5109 static bool host_supports_vmx(void)
5110 {
5111     uint32_t ecx, unused;
5112 
5113     host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
5114     return ecx & CPUID_EXT_VMX;
5115 }
5116 
5117 #define VMX_INVALID_GUEST_STATE 0x80000021
5118 
5119 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
5120 {
5121     X86CPU *cpu = X86_CPU(cs);
5122     uint64_t code;
5123     int ret;
5124 
5125     switch (run->exit_reason) {
5126     case KVM_EXIT_HLT:
5127         DPRINTF("handle_hlt\n");
5128         qemu_mutex_lock_iothread();
5129         ret = kvm_handle_halt(cpu);
5130         qemu_mutex_unlock_iothread();
5131         break;
5132     case KVM_EXIT_SET_TPR:
5133         ret = 0;
5134         break;
5135     case KVM_EXIT_TPR_ACCESS:
5136         qemu_mutex_lock_iothread();
5137         ret = kvm_handle_tpr_access(cpu);
5138         qemu_mutex_unlock_iothread();
5139         break;
5140     case KVM_EXIT_FAIL_ENTRY:
5141         code = run->fail_entry.hardware_entry_failure_reason;
5142         fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
5143                 code);
5144         if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
5145             fprintf(stderr,
5146                     "\nIf you're running a guest on an Intel machine without "
5147                         "unrestricted mode\n"
5148                     "support, the failure can be most likely due to the guest "
5149                         "entering an invalid\n"
5150                     "state for Intel VT. For example, the guest maybe running "
5151                         "in big real mode\n"
5152                     "which is not supported on less recent Intel processors."
5153                         "\n\n");
5154         }
5155         ret = -1;
5156         break;
5157     case KVM_EXIT_EXCEPTION:
5158         fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
5159                 run->ex.exception, run->ex.error_code);
5160         ret = -1;
5161         break;
5162     case KVM_EXIT_DEBUG:
5163         DPRINTF("kvm_exit_debug\n");
5164         qemu_mutex_lock_iothread();
5165         ret = kvm_handle_debug(cpu, &run->debug.arch);
5166         qemu_mutex_unlock_iothread();
5167         break;
5168     case KVM_EXIT_HYPERV:
5169         ret = kvm_hv_handle_exit(cpu, &run->hyperv);
5170         break;
5171     case KVM_EXIT_IOAPIC_EOI:
5172         ioapic_eoi_broadcast(run->eoi.vector);
5173         ret = 0;
5174         break;
5175     case KVM_EXIT_X86_BUS_LOCK:
5176         /* already handled in kvm_arch_post_run */
5177         ret = 0;
5178         break;
5179     default:
5180         fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
5181         ret = -1;
5182         break;
5183     }
5184 
5185     return ret;
5186 }
5187 
5188 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
5189 {
5190     X86CPU *cpu = X86_CPU(cs);
5191     CPUX86State *env = &cpu->env;
5192 
5193     kvm_cpu_synchronize_state(cs);
5194     return !(env->cr[0] & CR0_PE_MASK) ||
5195            ((env->segs[R_CS].selector  & 3) != 3);
5196 }
5197 
5198 void kvm_arch_init_irq_routing(KVMState *s)
5199 {
5200     /* We know at this point that we're using the in-kernel
5201      * irqchip, so we can use irqfds, and on x86 we know
5202      * we can use msi via irqfd and GSI routing.
5203      */
5204     kvm_msi_via_irqfd_allowed = true;
5205     kvm_gsi_routing_allowed = true;
5206 
5207     if (kvm_irqchip_is_split()) {
5208         KVMRouteChange c = kvm_irqchip_begin_route_changes(s);
5209         int i;
5210 
5211         /* If the ioapic is in QEMU and the lapics are in KVM, reserve
5212            MSI routes for signaling interrupts to the local apics. */
5213         for (i = 0; i < IOAPIC_NUM_PINS; i++) {
5214             if (kvm_irqchip_add_msi_route(&c, 0, NULL) < 0) {
5215                 error_report("Could not enable split IRQ mode.");
5216                 exit(1);
5217             }
5218         }
5219         kvm_irqchip_commit_route_changes(&c);
5220     }
5221 }
5222 
5223 int kvm_arch_irqchip_create(KVMState *s)
5224 {
5225     int ret;
5226     if (kvm_kernel_irqchip_split()) {
5227         ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
5228         if (ret) {
5229             error_report("Could not enable split irqchip mode: %s",
5230                          strerror(-ret));
5231             exit(1);
5232         } else {
5233             DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
5234             kvm_split_irqchip = true;
5235             return 1;
5236         }
5237     } else {
5238         return 0;
5239     }
5240 }
5241 
5242 uint64_t kvm_swizzle_msi_ext_dest_id(uint64_t address)
5243 {
5244     CPUX86State *env;
5245     uint64_t ext_id;
5246 
5247     if (!first_cpu) {
5248         return address;
5249     }
5250     env = &X86_CPU(first_cpu)->env;
5251     if (!(env->features[FEAT_KVM] & (1 << KVM_FEATURE_MSI_EXT_DEST_ID))) {
5252         return address;
5253     }
5254 
5255     /*
5256      * If the remappable format bit is set, or the upper bits are
5257      * already set in address_hi, or the low extended bits aren't
5258      * there anyway, do nothing.
5259      */
5260     ext_id = address & (0xff << MSI_ADDR_DEST_IDX_SHIFT);
5261     if (!ext_id || (ext_id & (1 << MSI_ADDR_DEST_IDX_SHIFT)) || (address >> 32)) {
5262         return address;
5263     }
5264 
5265     address &= ~ext_id;
5266     address |= ext_id << 35;
5267     return address;
5268 }
5269 
5270 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
5271                              uint64_t address, uint32_t data, PCIDevice *dev)
5272 {
5273     X86IOMMUState *iommu = x86_iommu_get_default();
5274 
5275     if (iommu) {
5276         X86IOMMUClass *class = X86_IOMMU_DEVICE_GET_CLASS(iommu);
5277 
5278         if (class->int_remap) {
5279             int ret;
5280             MSIMessage src, dst;
5281 
5282             src.address = route->u.msi.address_hi;
5283             src.address <<= VTD_MSI_ADDR_HI_SHIFT;
5284             src.address |= route->u.msi.address_lo;
5285             src.data = route->u.msi.data;
5286 
5287             ret = class->int_remap(iommu, &src, &dst, dev ?     \
5288                                    pci_requester_id(dev) :      \
5289                                    X86_IOMMU_SID_INVALID);
5290             if (ret) {
5291                 trace_kvm_x86_fixup_msi_error(route->gsi);
5292                 return 1;
5293             }
5294 
5295             /*
5296              * Handled untranslated compatibilty format interrupt with
5297              * extended destination ID in the low bits 11-5. */
5298             dst.address = kvm_swizzle_msi_ext_dest_id(dst.address);
5299 
5300             route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
5301             route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
5302             route->u.msi.data = dst.data;
5303             return 0;
5304         }
5305     }
5306 
5307     address = kvm_swizzle_msi_ext_dest_id(address);
5308     route->u.msi.address_hi = address >> VTD_MSI_ADDR_HI_SHIFT;
5309     route->u.msi.address_lo = address & VTD_MSI_ADDR_LO_MASK;
5310     return 0;
5311 }
5312 
5313 typedef struct MSIRouteEntry MSIRouteEntry;
5314 
5315 struct MSIRouteEntry {
5316     PCIDevice *dev;             /* Device pointer */
5317     int vector;                 /* MSI/MSIX vector index */
5318     int virq;                   /* Virtual IRQ index */
5319     QLIST_ENTRY(MSIRouteEntry) list;
5320 };
5321 
5322 /* List of used GSI routes */
5323 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
5324     QLIST_HEAD_INITIALIZER(msi_route_list);
5325 
5326 static void kvm_update_msi_routes_all(void *private, bool global,
5327                                       uint32_t index, uint32_t mask)
5328 {
5329     int cnt = 0, vector;
5330     MSIRouteEntry *entry;
5331     MSIMessage msg;
5332     PCIDevice *dev;
5333 
5334     /* TODO: explicit route update */
5335     QLIST_FOREACH(entry, &msi_route_list, list) {
5336         cnt++;
5337         vector = entry->vector;
5338         dev = entry->dev;
5339         if (msix_enabled(dev) && !msix_is_masked(dev, vector)) {
5340             msg = msix_get_message(dev, vector);
5341         } else if (msi_enabled(dev) && !msi_is_masked(dev, vector)) {
5342             msg = msi_get_message(dev, vector);
5343         } else {
5344             /*
5345              * Either MSI/MSIX is disabled for the device, or the
5346              * specific message was masked out.  Skip this one.
5347              */
5348             continue;
5349         }
5350         kvm_irqchip_update_msi_route(kvm_state, entry->virq, msg, dev);
5351     }
5352     kvm_irqchip_commit_routes(kvm_state);
5353     trace_kvm_x86_update_msi_routes(cnt);
5354 }
5355 
5356 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
5357                                 int vector, PCIDevice *dev)
5358 {
5359     static bool notify_list_inited = false;
5360     MSIRouteEntry *entry;
5361 
5362     if (!dev) {
5363         /* These are (possibly) IOAPIC routes only used for split
5364          * kernel irqchip mode, while what we are housekeeping are
5365          * PCI devices only. */
5366         return 0;
5367     }
5368 
5369     entry = g_new0(MSIRouteEntry, 1);
5370     entry->dev = dev;
5371     entry->vector = vector;
5372     entry->virq = route->gsi;
5373     QLIST_INSERT_HEAD(&msi_route_list, entry, list);
5374 
5375     trace_kvm_x86_add_msi_route(route->gsi);
5376 
5377     if (!notify_list_inited) {
5378         /* For the first time we do add route, add ourselves into
5379          * IOMMU's IEC notify list if needed. */
5380         X86IOMMUState *iommu = x86_iommu_get_default();
5381         if (iommu) {
5382             x86_iommu_iec_register_notifier(iommu,
5383                                             kvm_update_msi_routes_all,
5384                                             NULL);
5385         }
5386         notify_list_inited = true;
5387     }
5388     return 0;
5389 }
5390 
5391 int kvm_arch_release_virq_post(int virq)
5392 {
5393     MSIRouteEntry *entry, *next;
5394     QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
5395         if (entry->virq == virq) {
5396             trace_kvm_x86_remove_msi_route(virq);
5397             QLIST_REMOVE(entry, list);
5398             g_free(entry);
5399             break;
5400         }
5401     }
5402     return 0;
5403 }
5404 
5405 int kvm_arch_msi_data_to_gsi(uint32_t data)
5406 {
5407     abort();
5408 }
5409 
5410 bool kvm_has_waitpkg(void)
5411 {
5412     return has_msr_umwait;
5413 }
5414 
5415 bool kvm_arch_cpu_check_are_resettable(void)
5416 {
5417     return !sev_es_enabled();
5418 }
5419 
5420 #define ARCH_REQ_XCOMP_GUEST_PERM       0x1025
5421 
5422 void kvm_request_xsave_components(X86CPU *cpu, uint64_t mask)
5423 {
5424     KVMState *s = kvm_state;
5425     uint64_t supported;
5426 
5427     mask &= XSTATE_DYNAMIC_MASK;
5428     if (!mask) {
5429         return;
5430     }
5431     /*
5432      * Just ignore bits that are not in CPUID[EAX=0xD,ECX=0].
5433      * ARCH_REQ_XCOMP_GUEST_PERM would fail, and QEMU has warned
5434      * about them already because they are not supported features.
5435      */
5436     supported = kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EAX);
5437     supported |= (uint64_t)kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EDX) << 32;
5438     mask &= supported;
5439 
5440     while (mask) {
5441         int bit = ctz64(mask);
5442         int rc = syscall(SYS_arch_prctl, ARCH_REQ_XCOMP_GUEST_PERM, bit);
5443         if (rc) {
5444             /*
5445              * Older kernel version (<5.17) do not support
5446              * ARCH_REQ_XCOMP_GUEST_PERM, but also do not return
5447              * any dynamic feature from kvm_arch_get_supported_cpuid.
5448              */
5449             warn_report("prctl(ARCH_REQ_XCOMP_GUEST_PERM) failure "
5450                         "for feature bit %d", bit);
5451         }
5452         mask &= ~BIT_ULL(bit);
5453     }
5454 }
5455