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