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