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