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