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