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