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