xref: /openbmc/qemu/target/i386/kvm/kvm.c (revision 888788dd)
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         if (env->features[FEAT_7_1_EAX] & CPUID_7_1_EAX_FRED) {
3380             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP0, env->fred_rsp0);
3381             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP1, env->fred_rsp1);
3382             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP2, env->fred_rsp2);
3383             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP3, env->fred_rsp3);
3384             kvm_msr_entry_add(cpu, MSR_IA32_FRED_STKLVLS, env->fred_stklvls);
3385             kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP1, env->fred_ssp1);
3386             kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP2, env->fred_ssp2);
3387             kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP3, env->fred_ssp3);
3388             kvm_msr_entry_add(cpu, MSR_IA32_FRED_CONFIG, env->fred_config);
3389         }
3390     }
3391 #endif
3392 
3393     /*
3394      * The following MSRs have side effects on the guest or are too heavy
3395      * for normal writeback. Limit them to reset or full state updates.
3396      */
3397     if (level >= KVM_PUT_RESET_STATE) {
3398         kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
3399         kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
3400         kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
3401         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
3402             kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, env->async_pf_int_msr);
3403         }
3404         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
3405             kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
3406         }
3407         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
3408             kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
3409         }
3410         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
3411             kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
3412         }
3413 
3414         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
3415             kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, env->poll_control_msr);
3416         }
3417 
3418         if (has_architectural_pmu_version > 0) {
3419             if (has_architectural_pmu_version > 1) {
3420                 /* Stop the counter.  */
3421                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
3422                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
3423             }
3424 
3425             /* Set the counter values.  */
3426             for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
3427                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
3428                                   env->msr_fixed_counters[i]);
3429             }
3430             for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
3431                 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
3432                                   env->msr_gp_counters[i]);
3433                 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
3434                                   env->msr_gp_evtsel[i]);
3435             }
3436             if (has_architectural_pmu_version > 1) {
3437                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
3438                                   env->msr_global_status);
3439                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
3440                                   env->msr_global_ovf_ctrl);
3441 
3442                 /* Now start the PMU.  */
3443                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
3444                                   env->msr_fixed_ctr_ctrl);
3445                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
3446                                   env->msr_global_ctrl);
3447             }
3448         }
3449         /*
3450          * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,
3451          * only sync them to KVM on the first cpu
3452          */
3453         if (current_cpu == first_cpu) {
3454             if (has_msr_hv_hypercall) {
3455                 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
3456                                   env->msr_hv_guest_os_id);
3457                 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
3458                                   env->msr_hv_hypercall);
3459             }
3460             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
3461                 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,
3462                                   env->msr_hv_tsc);
3463             }
3464             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
3465                 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL,
3466                                   env->msr_hv_reenlightenment_control);
3467                 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL,
3468                                   env->msr_hv_tsc_emulation_control);
3469                 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS,
3470                                   env->msr_hv_tsc_emulation_status);
3471             }
3472 #ifdef CONFIG_SYNDBG
3473             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNDBG) &&
3474                 has_msr_hv_syndbg_options) {
3475                 kvm_msr_entry_add(cpu, HV_X64_MSR_SYNDBG_OPTIONS,
3476                                   hyperv_syndbg_query_options());
3477             }
3478 #endif
3479         }
3480         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3481             kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
3482                               env->msr_hv_vapic);
3483         }
3484         if (has_msr_hv_crash) {
3485             int j;
3486 
3487             for (j = 0; j < HV_CRASH_PARAMS; j++)
3488                 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
3489                                   env->msr_hv_crash_params[j]);
3490 
3491             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);
3492         }
3493         if (has_msr_hv_runtime) {
3494             kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
3495         }
3496         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)
3497             && hv_vpindex_settable) {
3498             kvm_msr_entry_add(cpu, HV_X64_MSR_VP_INDEX,
3499                               hyperv_vp_index(CPU(cpu)));
3500         }
3501         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3502             int j;
3503 
3504             kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);
3505 
3506             kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
3507                               env->msr_hv_synic_control);
3508             kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
3509                               env->msr_hv_synic_evt_page);
3510             kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
3511                               env->msr_hv_synic_msg_page);
3512 
3513             for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
3514                 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
3515                                   env->msr_hv_synic_sint[j]);
3516             }
3517         }
3518         if (has_msr_hv_stimer) {
3519             int j;
3520 
3521             for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
3522                 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
3523                                 env->msr_hv_stimer_config[j]);
3524             }
3525 
3526             for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
3527                 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
3528                                 env->msr_hv_stimer_count[j]);
3529             }
3530         }
3531         if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3532             uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
3533 
3534             kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
3535             kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
3536             kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
3537             kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
3538             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
3539             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
3540             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
3541             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
3542             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
3543             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
3544             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
3545             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
3546             for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
3547                 /* The CPU GPs if we write to a bit above the physical limit of
3548                  * the host CPU (and KVM emulates that)
3549                  */
3550                 uint64_t mask = env->mtrr_var[i].mask;
3551                 mask &= phys_mask;
3552 
3553                 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
3554                                   env->mtrr_var[i].base);
3555                 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
3556             }
3557         }
3558         if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
3559             int addr_num = kvm_arch_get_supported_cpuid(kvm_state,
3560                                                     0x14, 1, R_EAX) & 0x7;
3561 
3562             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL,
3563                             env->msr_rtit_ctrl);
3564             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS,
3565                             env->msr_rtit_status);
3566             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE,
3567                             env->msr_rtit_output_base);
3568             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK,
3569                             env->msr_rtit_output_mask);
3570             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH,
3571                             env->msr_rtit_cr3_match);
3572             for (i = 0; i < addr_num; i++) {
3573                 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i,
3574                             env->msr_rtit_addrs[i]);
3575             }
3576         }
3577 
3578         if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_SGX_LC) {
3579             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH0,
3580                               env->msr_ia32_sgxlepubkeyhash[0]);
3581             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH1,
3582                               env->msr_ia32_sgxlepubkeyhash[1]);
3583             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH2,
3584                               env->msr_ia32_sgxlepubkeyhash[2]);
3585             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH3,
3586                               env->msr_ia32_sgxlepubkeyhash[3]);
3587         }
3588 
3589         if (env->features[FEAT_XSAVE] & CPUID_D_1_EAX_XFD) {
3590             kvm_msr_entry_add(cpu, MSR_IA32_XFD,
3591                               env->msr_xfd);
3592             kvm_msr_entry_add(cpu, MSR_IA32_XFD_ERR,
3593                               env->msr_xfd_err);
3594         }
3595 
3596         if (kvm_enabled() && cpu->enable_pmu &&
3597             (env->features[FEAT_7_0_EDX] & CPUID_7_0_EDX_ARCH_LBR)) {
3598             uint64_t depth;
3599             int ret;
3600 
3601             /*
3602              * Only migrate Arch LBR states when the host Arch LBR depth
3603              * equals that of source guest's, this is to avoid mismatch
3604              * of guest/host config for the msr hence avoid unexpected
3605              * misbehavior.
3606              */
3607             ret = kvm_get_one_msr(cpu, MSR_ARCH_LBR_DEPTH, &depth);
3608 
3609             if (ret == 1 && !!depth && depth == env->msr_lbr_depth) {
3610                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_CTL, env->msr_lbr_ctl);
3611                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_DEPTH, env->msr_lbr_depth);
3612 
3613                 for (i = 0; i < ARCH_LBR_NR_ENTRIES; i++) {
3614                     if (!env->lbr_records[i].from) {
3615                         continue;
3616                     }
3617                     kvm_msr_entry_add(cpu, MSR_ARCH_LBR_FROM_0 + i,
3618                                       env->lbr_records[i].from);
3619                     kvm_msr_entry_add(cpu, MSR_ARCH_LBR_TO_0 + i,
3620                                       env->lbr_records[i].to);
3621                     kvm_msr_entry_add(cpu, MSR_ARCH_LBR_INFO_0 + i,
3622                                       env->lbr_records[i].info);
3623                 }
3624             }
3625         }
3626 
3627         /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
3628          *       kvm_put_msr_feature_control. */
3629     }
3630 
3631     if (env->mcg_cap) {
3632         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
3633         kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
3634         if (has_msr_mcg_ext_ctl) {
3635             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
3636         }
3637         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3638             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
3639         }
3640     }
3641 
3642     return kvm_buf_set_msrs(cpu);
3643 }
3644 
3645 
3646 static int kvm_get_xsave(X86CPU *cpu)
3647 {
3648     CPUX86State *env = &cpu->env;
3649     void *xsave = env->xsave_buf;
3650     int type, ret;
3651 
3652     type = has_xsave2 ? KVM_GET_XSAVE2 : KVM_GET_XSAVE;
3653     ret = kvm_vcpu_ioctl(CPU(cpu), type, xsave);
3654     if (ret < 0) {
3655         return ret;
3656     }
3657     x86_cpu_xrstor_all_areas(cpu, xsave, env->xsave_buf_len);
3658 
3659     return 0;
3660 }
3661 
3662 static int kvm_get_xcrs(X86CPU *cpu)
3663 {
3664     CPUX86State *env = &cpu->env;
3665     int i, ret;
3666     struct kvm_xcrs xcrs;
3667 
3668     if (!has_xcrs) {
3669         return 0;
3670     }
3671 
3672     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
3673     if (ret < 0) {
3674         return ret;
3675     }
3676 
3677     for (i = 0; i < xcrs.nr_xcrs; i++) {
3678         /* Only support xcr0 now */
3679         if (xcrs.xcrs[i].xcr == 0) {
3680             env->xcr0 = xcrs.xcrs[i].value;
3681             break;
3682         }
3683     }
3684     return 0;
3685 }
3686 
3687 static int kvm_get_sregs(X86CPU *cpu)
3688 {
3689     CPUX86State *env = &cpu->env;
3690     struct kvm_sregs sregs;
3691     int ret;
3692 
3693     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
3694     if (ret < 0) {
3695         return ret;
3696     }
3697 
3698     /*
3699      * The interrupt_bitmap is ignored because KVM_GET_SREGS is
3700      * always preceded by KVM_GET_VCPU_EVENTS.
3701      */
3702 
3703     get_seg(&env->segs[R_CS], &sregs.cs);
3704     get_seg(&env->segs[R_DS], &sregs.ds);
3705     get_seg(&env->segs[R_ES], &sregs.es);
3706     get_seg(&env->segs[R_FS], &sregs.fs);
3707     get_seg(&env->segs[R_GS], &sregs.gs);
3708     get_seg(&env->segs[R_SS], &sregs.ss);
3709 
3710     get_seg(&env->tr, &sregs.tr);
3711     get_seg(&env->ldt, &sregs.ldt);
3712 
3713     env->idt.limit = sregs.idt.limit;
3714     env->idt.base = sregs.idt.base;
3715     env->gdt.limit = sregs.gdt.limit;
3716     env->gdt.base = sregs.gdt.base;
3717 
3718     env->cr[0] = sregs.cr0;
3719     env->cr[2] = sregs.cr2;
3720     env->cr[3] = sregs.cr3;
3721     env->cr[4] = sregs.cr4;
3722 
3723     env->efer = sregs.efer;
3724     if (sev_es_enabled() && env->efer & MSR_EFER_LME &&
3725         env->cr[0] & CR0_PG_MASK) {
3726         env->efer |= MSR_EFER_LMA;
3727     }
3728 
3729     /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
3730     x86_update_hflags(env);
3731 
3732     return 0;
3733 }
3734 
3735 static int kvm_get_sregs2(X86CPU *cpu)
3736 {
3737     CPUX86State *env = &cpu->env;
3738     struct kvm_sregs2 sregs;
3739     int i, ret;
3740 
3741     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS2, &sregs);
3742     if (ret < 0) {
3743         return ret;
3744     }
3745 
3746     get_seg(&env->segs[R_CS], &sregs.cs);
3747     get_seg(&env->segs[R_DS], &sregs.ds);
3748     get_seg(&env->segs[R_ES], &sregs.es);
3749     get_seg(&env->segs[R_FS], &sregs.fs);
3750     get_seg(&env->segs[R_GS], &sregs.gs);
3751     get_seg(&env->segs[R_SS], &sregs.ss);
3752 
3753     get_seg(&env->tr, &sregs.tr);
3754     get_seg(&env->ldt, &sregs.ldt);
3755 
3756     env->idt.limit = sregs.idt.limit;
3757     env->idt.base = sregs.idt.base;
3758     env->gdt.limit = sregs.gdt.limit;
3759     env->gdt.base = sregs.gdt.base;
3760 
3761     env->cr[0] = sregs.cr0;
3762     env->cr[2] = sregs.cr2;
3763     env->cr[3] = sregs.cr3;
3764     env->cr[4] = sregs.cr4;
3765 
3766     env->efer = sregs.efer;
3767     if (sev_es_enabled() && env->efer & MSR_EFER_LME &&
3768         env->cr[0] & CR0_PG_MASK) {
3769         env->efer |= MSR_EFER_LMA;
3770     }
3771 
3772     env->pdptrs_valid = sregs.flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
3773 
3774     if (env->pdptrs_valid) {
3775         for (i = 0; i < 4; i++) {
3776             env->pdptrs[i] = sregs.pdptrs[i];
3777         }
3778     }
3779 
3780     /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
3781     x86_update_hflags(env);
3782 
3783     return 0;
3784 }
3785 
3786 static int kvm_get_msrs(X86CPU *cpu)
3787 {
3788     CPUX86State *env = &cpu->env;
3789     struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
3790     int ret, i;
3791     uint64_t mtrr_top_bits;
3792 
3793     kvm_msr_buf_reset(cpu);
3794 
3795     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
3796     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
3797     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
3798     kvm_msr_entry_add(cpu, MSR_PAT, 0);
3799     if (has_msr_star) {
3800         kvm_msr_entry_add(cpu, MSR_STAR, 0);
3801     }
3802     if (has_msr_hsave_pa) {
3803         kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
3804     }
3805     if (has_msr_tsc_aux) {
3806         kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
3807     }
3808     if (has_msr_tsc_adjust) {
3809         kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
3810     }
3811     if (has_msr_tsc_deadline) {
3812         kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
3813     }
3814     if (has_msr_misc_enable) {
3815         kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
3816     }
3817     if (has_msr_smbase) {
3818         kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
3819     }
3820     if (has_msr_smi_count) {
3821         kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
3822     }
3823     if (has_msr_feature_control) {
3824         kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
3825     }
3826     if (has_msr_pkrs) {
3827         kvm_msr_entry_add(cpu, MSR_IA32_PKRS, 0);
3828     }
3829     if (has_msr_bndcfgs) {
3830         kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
3831     }
3832     if (has_msr_xss) {
3833         kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
3834     }
3835     if (has_msr_umwait) {
3836         kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, 0);
3837     }
3838     if (has_msr_spec_ctrl) {
3839         kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
3840     }
3841     if (has_tsc_scale_msr) {
3842         kvm_msr_entry_add(cpu, MSR_AMD64_TSC_RATIO, 0);
3843     }
3844 
3845     if (has_msr_tsx_ctrl) {
3846         kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, 0);
3847     }
3848     if (has_msr_virt_ssbd) {
3849         kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, 0);
3850     }
3851     if (!env->tsc_valid) {
3852         kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
3853         env->tsc_valid = !runstate_is_running();
3854     }
3855 
3856 #ifdef TARGET_X86_64
3857     if (lm_capable_kernel) {
3858         kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
3859         kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
3860         kvm_msr_entry_add(cpu, MSR_FMASK, 0);
3861         kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
3862         if (env->features[FEAT_7_1_EAX] & CPUID_7_1_EAX_FRED) {
3863             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP0, 0);
3864             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP1, 0);
3865             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP2, 0);
3866             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP3, 0);
3867             kvm_msr_entry_add(cpu, MSR_IA32_FRED_STKLVLS, 0);
3868             kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP1, 0);
3869             kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP2, 0);
3870             kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP3, 0);
3871             kvm_msr_entry_add(cpu, MSR_IA32_FRED_CONFIG, 0);
3872         }
3873     }
3874 #endif
3875     kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
3876     kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
3877     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
3878         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, 0);
3879     }
3880     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
3881         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
3882     }
3883     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
3884         kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
3885     }
3886     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
3887         kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
3888     }
3889     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
3890         kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, 1);
3891     }
3892     if (has_architectural_pmu_version > 0) {
3893         if (has_architectural_pmu_version > 1) {
3894             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
3895             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
3896             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
3897             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
3898         }
3899         for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
3900             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
3901         }
3902         for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
3903             kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
3904             kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
3905         }
3906     }
3907 
3908     if (env->mcg_cap) {
3909         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
3910         kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
3911         if (has_msr_mcg_ext_ctl) {
3912             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
3913         }
3914         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3915             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
3916         }
3917     }
3918 
3919     if (has_msr_hv_hypercall) {
3920         kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
3921         kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
3922     }
3923     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3924         kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
3925     }
3926     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
3927         kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
3928     }
3929     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
3930         kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL, 0);
3931         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL, 0);
3932         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS, 0);
3933     }
3934     if (has_msr_hv_syndbg_options) {
3935         kvm_msr_entry_add(cpu, HV_X64_MSR_SYNDBG_OPTIONS, 0);
3936     }
3937     if (has_msr_hv_crash) {
3938         int j;
3939 
3940         for (j = 0; j < HV_CRASH_PARAMS; j++) {
3941             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
3942         }
3943     }
3944     if (has_msr_hv_runtime) {
3945         kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
3946     }
3947     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3948         uint32_t msr;
3949 
3950         kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
3951         kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
3952         kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
3953         for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
3954             kvm_msr_entry_add(cpu, msr, 0);
3955         }
3956     }
3957     if (has_msr_hv_stimer) {
3958         uint32_t msr;
3959 
3960         for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
3961              msr++) {
3962             kvm_msr_entry_add(cpu, msr, 0);
3963         }
3964     }
3965     if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3966         kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
3967         kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
3968         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
3969         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
3970         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
3971         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
3972         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
3973         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
3974         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
3975         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
3976         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
3977         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
3978         for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
3979             kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
3980             kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
3981         }
3982     }
3983 
3984     if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
3985         int addr_num =
3986             kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
3987 
3988         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
3989         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
3990         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
3991         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
3992         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
3993         for (i = 0; i < addr_num; i++) {
3994             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
3995         }
3996     }
3997 
3998     if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_SGX_LC) {
3999         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH0, 0);
4000         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH1, 0);
4001         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH2, 0);
4002         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH3, 0);
4003     }
4004 
4005     if (env->features[FEAT_XSAVE] & CPUID_D_1_EAX_XFD) {
4006         kvm_msr_entry_add(cpu, MSR_IA32_XFD, 0);
4007         kvm_msr_entry_add(cpu, MSR_IA32_XFD_ERR, 0);
4008     }
4009 
4010     if (kvm_enabled() && cpu->enable_pmu &&
4011         (env->features[FEAT_7_0_EDX] & CPUID_7_0_EDX_ARCH_LBR)) {
4012         uint64_t depth;
4013 
4014         ret = kvm_get_one_msr(cpu, MSR_ARCH_LBR_DEPTH, &depth);
4015         if (ret == 1 && depth == ARCH_LBR_NR_ENTRIES) {
4016             kvm_msr_entry_add(cpu, MSR_ARCH_LBR_CTL, 0);
4017             kvm_msr_entry_add(cpu, MSR_ARCH_LBR_DEPTH, 0);
4018 
4019             for (i = 0; i < ARCH_LBR_NR_ENTRIES; i++) {
4020                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_FROM_0 + i, 0);
4021                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_TO_0 + i, 0);
4022                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_INFO_0 + i, 0);
4023             }
4024         }
4025     }
4026 
4027     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
4028     if (ret < 0) {
4029         return ret;
4030     }
4031 
4032     if (ret < cpu->kvm_msr_buf->nmsrs) {
4033         struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
4034         error_report("error: failed to get MSR 0x%" PRIx32,
4035                      (uint32_t)e->index);
4036     }
4037 
4038     assert(ret == cpu->kvm_msr_buf->nmsrs);
4039     /*
4040      * MTRR masks: Each mask consists of 5 parts
4041      * a  10..0: must be zero
4042      * b  11   : valid bit
4043      * c n-1.12: actual mask bits
4044      * d  51..n: reserved must be zero
4045      * e  63.52: reserved must be zero
4046      *
4047      * 'n' is the number of physical bits supported by the CPU and is
4048      * apparently always <= 52.   We know our 'n' but don't know what
4049      * the destinations 'n' is; it might be smaller, in which case
4050      * it masks (c) on loading. It might be larger, in which case
4051      * we fill 'd' so that d..c is consistent irrespetive of the 'n'
4052      * we're migrating to.
4053      */
4054 
4055     if (cpu->fill_mtrr_mask) {
4056         QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
4057         assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
4058         mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
4059     } else {
4060         mtrr_top_bits = 0;
4061     }
4062 
4063     for (i = 0; i < ret; i++) {
4064         uint32_t index = msrs[i].index;
4065         switch (index) {
4066         case MSR_IA32_SYSENTER_CS:
4067             env->sysenter_cs = msrs[i].data;
4068             break;
4069         case MSR_IA32_SYSENTER_ESP:
4070             env->sysenter_esp = msrs[i].data;
4071             break;
4072         case MSR_IA32_SYSENTER_EIP:
4073             env->sysenter_eip = msrs[i].data;
4074             break;
4075         case MSR_PAT:
4076             env->pat = msrs[i].data;
4077             break;
4078         case MSR_STAR:
4079             env->star = msrs[i].data;
4080             break;
4081 #ifdef TARGET_X86_64
4082         case MSR_CSTAR:
4083             env->cstar = msrs[i].data;
4084             break;
4085         case MSR_KERNELGSBASE:
4086             env->kernelgsbase = msrs[i].data;
4087             break;
4088         case MSR_FMASK:
4089             env->fmask = msrs[i].data;
4090             break;
4091         case MSR_LSTAR:
4092             env->lstar = msrs[i].data;
4093             break;
4094         case MSR_IA32_FRED_RSP0:
4095             env->fred_rsp0 = msrs[i].data;
4096             break;
4097         case MSR_IA32_FRED_RSP1:
4098             env->fred_rsp1 = msrs[i].data;
4099             break;
4100         case MSR_IA32_FRED_RSP2:
4101             env->fred_rsp2 = msrs[i].data;
4102             break;
4103         case MSR_IA32_FRED_RSP3:
4104             env->fred_rsp3 = msrs[i].data;
4105             break;
4106         case MSR_IA32_FRED_STKLVLS:
4107             env->fred_stklvls = msrs[i].data;
4108             break;
4109         case MSR_IA32_FRED_SSP1:
4110             env->fred_ssp1 = msrs[i].data;
4111             break;
4112         case MSR_IA32_FRED_SSP2:
4113             env->fred_ssp2 = msrs[i].data;
4114             break;
4115         case MSR_IA32_FRED_SSP3:
4116             env->fred_ssp3 = msrs[i].data;
4117             break;
4118         case MSR_IA32_FRED_CONFIG:
4119             env->fred_config = msrs[i].data;
4120             break;
4121 #endif
4122         case MSR_IA32_TSC:
4123             env->tsc = msrs[i].data;
4124             break;
4125         case MSR_TSC_AUX:
4126             env->tsc_aux = msrs[i].data;
4127             break;
4128         case MSR_TSC_ADJUST:
4129             env->tsc_adjust = msrs[i].data;
4130             break;
4131         case MSR_IA32_TSCDEADLINE:
4132             env->tsc_deadline = msrs[i].data;
4133             break;
4134         case MSR_VM_HSAVE_PA:
4135             env->vm_hsave = msrs[i].data;
4136             break;
4137         case MSR_KVM_SYSTEM_TIME:
4138             env->system_time_msr = msrs[i].data;
4139             break;
4140         case MSR_KVM_WALL_CLOCK:
4141             env->wall_clock_msr = msrs[i].data;
4142             break;
4143         case MSR_MCG_STATUS:
4144             env->mcg_status = msrs[i].data;
4145             break;
4146         case MSR_MCG_CTL:
4147             env->mcg_ctl = msrs[i].data;
4148             break;
4149         case MSR_MCG_EXT_CTL:
4150             env->mcg_ext_ctl = msrs[i].data;
4151             break;
4152         case MSR_IA32_MISC_ENABLE:
4153             env->msr_ia32_misc_enable = msrs[i].data;
4154             break;
4155         case MSR_IA32_SMBASE:
4156             env->smbase = msrs[i].data;
4157             break;
4158         case MSR_SMI_COUNT:
4159             env->msr_smi_count = msrs[i].data;
4160             break;
4161         case MSR_IA32_FEATURE_CONTROL:
4162             env->msr_ia32_feature_control = msrs[i].data;
4163             break;
4164         case MSR_IA32_BNDCFGS:
4165             env->msr_bndcfgs = msrs[i].data;
4166             break;
4167         case MSR_IA32_XSS:
4168             env->xss = msrs[i].data;
4169             break;
4170         case MSR_IA32_UMWAIT_CONTROL:
4171             env->umwait = msrs[i].data;
4172             break;
4173         case MSR_IA32_PKRS:
4174             env->pkrs = msrs[i].data;
4175             break;
4176         default:
4177             if (msrs[i].index >= MSR_MC0_CTL &&
4178                 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
4179                 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
4180             }
4181             break;
4182         case MSR_KVM_ASYNC_PF_EN:
4183             env->async_pf_en_msr = msrs[i].data;
4184             break;
4185         case MSR_KVM_ASYNC_PF_INT:
4186             env->async_pf_int_msr = msrs[i].data;
4187             break;
4188         case MSR_KVM_PV_EOI_EN:
4189             env->pv_eoi_en_msr = msrs[i].data;
4190             break;
4191         case MSR_KVM_STEAL_TIME:
4192             env->steal_time_msr = msrs[i].data;
4193             break;
4194         case MSR_KVM_POLL_CONTROL: {
4195             env->poll_control_msr = msrs[i].data;
4196             break;
4197         }
4198         case MSR_CORE_PERF_FIXED_CTR_CTRL:
4199             env->msr_fixed_ctr_ctrl = msrs[i].data;
4200             break;
4201         case MSR_CORE_PERF_GLOBAL_CTRL:
4202             env->msr_global_ctrl = msrs[i].data;
4203             break;
4204         case MSR_CORE_PERF_GLOBAL_STATUS:
4205             env->msr_global_status = msrs[i].data;
4206             break;
4207         case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
4208             env->msr_global_ovf_ctrl = msrs[i].data;
4209             break;
4210         case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
4211             env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
4212             break;
4213         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
4214             env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
4215             break;
4216         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
4217             env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
4218             break;
4219         case HV_X64_MSR_HYPERCALL:
4220             env->msr_hv_hypercall = msrs[i].data;
4221             break;
4222         case HV_X64_MSR_GUEST_OS_ID:
4223             env->msr_hv_guest_os_id = msrs[i].data;
4224             break;
4225         case HV_X64_MSR_APIC_ASSIST_PAGE:
4226             env->msr_hv_vapic = msrs[i].data;
4227             break;
4228         case HV_X64_MSR_REFERENCE_TSC:
4229             env->msr_hv_tsc = msrs[i].data;
4230             break;
4231         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4232             env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
4233             break;
4234         case HV_X64_MSR_VP_RUNTIME:
4235             env->msr_hv_runtime = msrs[i].data;
4236             break;
4237         case HV_X64_MSR_SCONTROL:
4238             env->msr_hv_synic_control = msrs[i].data;
4239             break;
4240         case HV_X64_MSR_SIEFP:
4241             env->msr_hv_synic_evt_page = msrs[i].data;
4242             break;
4243         case HV_X64_MSR_SIMP:
4244             env->msr_hv_synic_msg_page = msrs[i].data;
4245             break;
4246         case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
4247             env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
4248             break;
4249         case HV_X64_MSR_STIMER0_CONFIG:
4250         case HV_X64_MSR_STIMER1_CONFIG:
4251         case HV_X64_MSR_STIMER2_CONFIG:
4252         case HV_X64_MSR_STIMER3_CONFIG:
4253             env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
4254                                 msrs[i].data;
4255             break;
4256         case HV_X64_MSR_STIMER0_COUNT:
4257         case HV_X64_MSR_STIMER1_COUNT:
4258         case HV_X64_MSR_STIMER2_COUNT:
4259         case HV_X64_MSR_STIMER3_COUNT:
4260             env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
4261                                 msrs[i].data;
4262             break;
4263         case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4264             env->msr_hv_reenlightenment_control = msrs[i].data;
4265             break;
4266         case HV_X64_MSR_TSC_EMULATION_CONTROL:
4267             env->msr_hv_tsc_emulation_control = msrs[i].data;
4268             break;
4269         case HV_X64_MSR_TSC_EMULATION_STATUS:
4270             env->msr_hv_tsc_emulation_status = msrs[i].data;
4271             break;
4272         case HV_X64_MSR_SYNDBG_OPTIONS:
4273             env->msr_hv_syndbg_options = msrs[i].data;
4274             break;
4275         case MSR_MTRRdefType:
4276             env->mtrr_deftype = msrs[i].data;
4277             break;
4278         case MSR_MTRRfix64K_00000:
4279             env->mtrr_fixed[0] = msrs[i].data;
4280             break;
4281         case MSR_MTRRfix16K_80000:
4282             env->mtrr_fixed[1] = msrs[i].data;
4283             break;
4284         case MSR_MTRRfix16K_A0000:
4285             env->mtrr_fixed[2] = msrs[i].data;
4286             break;
4287         case MSR_MTRRfix4K_C0000:
4288             env->mtrr_fixed[3] = msrs[i].data;
4289             break;
4290         case MSR_MTRRfix4K_C8000:
4291             env->mtrr_fixed[4] = msrs[i].data;
4292             break;
4293         case MSR_MTRRfix4K_D0000:
4294             env->mtrr_fixed[5] = msrs[i].data;
4295             break;
4296         case MSR_MTRRfix4K_D8000:
4297             env->mtrr_fixed[6] = msrs[i].data;
4298             break;
4299         case MSR_MTRRfix4K_E0000:
4300             env->mtrr_fixed[7] = msrs[i].data;
4301             break;
4302         case MSR_MTRRfix4K_E8000:
4303             env->mtrr_fixed[8] = msrs[i].data;
4304             break;
4305         case MSR_MTRRfix4K_F0000:
4306             env->mtrr_fixed[9] = msrs[i].data;
4307             break;
4308         case MSR_MTRRfix4K_F8000:
4309             env->mtrr_fixed[10] = msrs[i].data;
4310             break;
4311         case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
4312             if (index & 1) {
4313                 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
4314                                                                mtrr_top_bits;
4315             } else {
4316                 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
4317             }
4318             break;
4319         case MSR_IA32_SPEC_CTRL:
4320             env->spec_ctrl = msrs[i].data;
4321             break;
4322         case MSR_AMD64_TSC_RATIO:
4323             env->amd_tsc_scale_msr = msrs[i].data;
4324             break;
4325         case MSR_IA32_TSX_CTRL:
4326             env->tsx_ctrl = msrs[i].data;
4327             break;
4328         case MSR_VIRT_SSBD:
4329             env->virt_ssbd = msrs[i].data;
4330             break;
4331         case MSR_IA32_RTIT_CTL:
4332             env->msr_rtit_ctrl = msrs[i].data;
4333             break;
4334         case MSR_IA32_RTIT_STATUS:
4335             env->msr_rtit_status = msrs[i].data;
4336             break;
4337         case MSR_IA32_RTIT_OUTPUT_BASE:
4338             env->msr_rtit_output_base = msrs[i].data;
4339             break;
4340         case MSR_IA32_RTIT_OUTPUT_MASK:
4341             env->msr_rtit_output_mask = msrs[i].data;
4342             break;
4343         case MSR_IA32_RTIT_CR3_MATCH:
4344             env->msr_rtit_cr3_match = msrs[i].data;
4345             break;
4346         case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
4347             env->msr_rtit_addrs[index - MSR_IA32_RTIT_ADDR0_A] = msrs[i].data;
4348             break;
4349         case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
4350             env->msr_ia32_sgxlepubkeyhash[index - MSR_IA32_SGXLEPUBKEYHASH0] =
4351                            msrs[i].data;
4352             break;
4353         case MSR_IA32_XFD:
4354             env->msr_xfd = msrs[i].data;
4355             break;
4356         case MSR_IA32_XFD_ERR:
4357             env->msr_xfd_err = msrs[i].data;
4358             break;
4359         case MSR_ARCH_LBR_CTL:
4360             env->msr_lbr_ctl = msrs[i].data;
4361             break;
4362         case MSR_ARCH_LBR_DEPTH:
4363             env->msr_lbr_depth = msrs[i].data;
4364             break;
4365         case MSR_ARCH_LBR_FROM_0 ... MSR_ARCH_LBR_FROM_0 + 31:
4366             env->lbr_records[index - MSR_ARCH_LBR_FROM_0].from = msrs[i].data;
4367             break;
4368         case MSR_ARCH_LBR_TO_0 ... MSR_ARCH_LBR_TO_0 + 31:
4369             env->lbr_records[index - MSR_ARCH_LBR_TO_0].to = msrs[i].data;
4370             break;
4371         case MSR_ARCH_LBR_INFO_0 ... MSR_ARCH_LBR_INFO_0 + 31:
4372             env->lbr_records[index - MSR_ARCH_LBR_INFO_0].info = msrs[i].data;
4373             break;
4374         }
4375     }
4376 
4377     return 0;
4378 }
4379 
4380 static int kvm_put_mp_state(X86CPU *cpu)
4381 {
4382     struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
4383 
4384     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
4385 }
4386 
4387 static int kvm_get_mp_state(X86CPU *cpu)
4388 {
4389     CPUState *cs = CPU(cpu);
4390     CPUX86State *env = &cpu->env;
4391     struct kvm_mp_state mp_state;
4392     int ret;
4393 
4394     ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
4395     if (ret < 0) {
4396         return ret;
4397     }
4398     env->mp_state = mp_state.mp_state;
4399     if (kvm_irqchip_in_kernel()) {
4400         cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
4401     }
4402     return 0;
4403 }
4404 
4405 static int kvm_get_apic(X86CPU *cpu)
4406 {
4407     DeviceState *apic = cpu->apic_state;
4408     struct kvm_lapic_state kapic;
4409     int ret;
4410 
4411     if (apic && kvm_irqchip_in_kernel()) {
4412         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
4413         if (ret < 0) {
4414             return ret;
4415         }
4416 
4417         kvm_get_apic_state(apic, &kapic);
4418     }
4419     return 0;
4420 }
4421 
4422 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
4423 {
4424     CPUState *cs = CPU(cpu);
4425     CPUX86State *env = &cpu->env;
4426     struct kvm_vcpu_events events = {};
4427 
4428     events.flags = 0;
4429 
4430     if (has_exception_payload) {
4431         events.flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
4432         events.exception.pending = env->exception_pending;
4433         events.exception_has_payload = env->exception_has_payload;
4434         events.exception_payload = env->exception_payload;
4435     }
4436     events.exception.nr = env->exception_nr;
4437     events.exception.injected = env->exception_injected;
4438     events.exception.has_error_code = env->has_error_code;
4439     events.exception.error_code = env->error_code;
4440 
4441     events.interrupt.injected = (env->interrupt_injected >= 0);
4442     events.interrupt.nr = env->interrupt_injected;
4443     events.interrupt.soft = env->soft_interrupt;
4444 
4445     events.nmi.injected = env->nmi_injected;
4446     events.nmi.pending = env->nmi_pending;
4447     events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
4448 
4449     events.sipi_vector = env->sipi_vector;
4450 
4451     if (has_msr_smbase) {
4452         events.smi.smm = !!(env->hflags & HF_SMM_MASK);
4453         events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
4454         if (kvm_irqchip_in_kernel()) {
4455             /* As soon as these are moved to the kernel, remove them
4456              * from cs->interrupt_request.
4457              */
4458             events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
4459             events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
4460             cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
4461         } else {
4462             /* Keep these in cs->interrupt_request.  */
4463             events.smi.pending = 0;
4464             events.smi.latched_init = 0;
4465         }
4466         /* Stop SMI delivery on old machine types to avoid a reboot
4467          * on an inward migration of an old VM.
4468          */
4469         if (!cpu->kvm_no_smi_migration) {
4470             events.flags |= KVM_VCPUEVENT_VALID_SMM;
4471         }
4472     }
4473 
4474     if (level >= KVM_PUT_RESET_STATE) {
4475         events.flags |= KVM_VCPUEVENT_VALID_NMI_PENDING;
4476         if (env->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
4477             events.flags |= KVM_VCPUEVENT_VALID_SIPI_VECTOR;
4478         }
4479     }
4480 
4481     if (has_triple_fault_event) {
4482         events.flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
4483         events.triple_fault.pending = env->triple_fault_pending;
4484     }
4485 
4486     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
4487 }
4488 
4489 static int kvm_get_vcpu_events(X86CPU *cpu)
4490 {
4491     CPUX86State *env = &cpu->env;
4492     struct kvm_vcpu_events events;
4493     int ret;
4494 
4495     memset(&events, 0, sizeof(events));
4496     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
4497     if (ret < 0) {
4498        return ret;
4499     }
4500 
4501     if (events.flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4502         env->exception_pending = events.exception.pending;
4503         env->exception_has_payload = events.exception_has_payload;
4504         env->exception_payload = events.exception_payload;
4505     } else {
4506         env->exception_pending = 0;
4507         env->exception_has_payload = false;
4508     }
4509     env->exception_injected = events.exception.injected;
4510     env->exception_nr =
4511         (env->exception_pending || env->exception_injected) ?
4512         events.exception.nr : -1;
4513     env->has_error_code = events.exception.has_error_code;
4514     env->error_code = events.exception.error_code;
4515 
4516     env->interrupt_injected =
4517         events.interrupt.injected ? events.interrupt.nr : -1;
4518     env->soft_interrupt = events.interrupt.soft;
4519 
4520     env->nmi_injected = events.nmi.injected;
4521     env->nmi_pending = events.nmi.pending;
4522     if (events.nmi.masked) {
4523         env->hflags2 |= HF2_NMI_MASK;
4524     } else {
4525         env->hflags2 &= ~HF2_NMI_MASK;
4526     }
4527 
4528     if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
4529         if (events.smi.smm) {
4530             env->hflags |= HF_SMM_MASK;
4531         } else {
4532             env->hflags &= ~HF_SMM_MASK;
4533         }
4534         if (events.smi.pending) {
4535             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
4536         } else {
4537             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
4538         }
4539         if (events.smi.smm_inside_nmi) {
4540             env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
4541         } else {
4542             env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
4543         }
4544         if (events.smi.latched_init) {
4545             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
4546         } else {
4547             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
4548         }
4549     }
4550 
4551     if (events.flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
4552         env->triple_fault_pending = events.triple_fault.pending;
4553     }
4554 
4555     env->sipi_vector = events.sipi_vector;
4556 
4557     return 0;
4558 }
4559 
4560 static int kvm_put_debugregs(X86CPU *cpu)
4561 {
4562     CPUX86State *env = &cpu->env;
4563     struct kvm_debugregs dbgregs;
4564     int i;
4565 
4566     memset(&dbgregs, 0, sizeof(dbgregs));
4567     for (i = 0; i < 4; i++) {
4568         dbgregs.db[i] = env->dr[i];
4569     }
4570     dbgregs.dr6 = env->dr[6];
4571     dbgregs.dr7 = env->dr[7];
4572     dbgregs.flags = 0;
4573 
4574     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
4575 }
4576 
4577 static int kvm_get_debugregs(X86CPU *cpu)
4578 {
4579     CPUX86State *env = &cpu->env;
4580     struct kvm_debugregs dbgregs;
4581     int i, ret;
4582 
4583     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
4584     if (ret < 0) {
4585         return ret;
4586     }
4587     for (i = 0; i < 4; i++) {
4588         env->dr[i] = dbgregs.db[i];
4589     }
4590     env->dr[4] = env->dr[6] = dbgregs.dr6;
4591     env->dr[5] = env->dr[7] = dbgregs.dr7;
4592 
4593     return 0;
4594 }
4595 
4596 static int kvm_put_nested_state(X86CPU *cpu)
4597 {
4598     CPUX86State *env = &cpu->env;
4599     int max_nested_state_len = kvm_max_nested_state_length();
4600 
4601     if (!env->nested_state) {
4602         return 0;
4603     }
4604 
4605     /*
4606      * Copy flags that are affected by reset from env->hflags and env->hflags2.
4607      */
4608     if (env->hflags & HF_GUEST_MASK) {
4609         env->nested_state->flags |= KVM_STATE_NESTED_GUEST_MODE;
4610     } else {
4611         env->nested_state->flags &= ~KVM_STATE_NESTED_GUEST_MODE;
4612     }
4613 
4614     /* Don't set KVM_STATE_NESTED_GIF_SET on VMX as it is illegal */
4615     if (cpu_has_svm(env) && (env->hflags2 & HF2_GIF_MASK)) {
4616         env->nested_state->flags |= KVM_STATE_NESTED_GIF_SET;
4617     } else {
4618         env->nested_state->flags &= ~KVM_STATE_NESTED_GIF_SET;
4619     }
4620 
4621     assert(env->nested_state->size <= max_nested_state_len);
4622     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_NESTED_STATE, env->nested_state);
4623 }
4624 
4625 static int kvm_get_nested_state(X86CPU *cpu)
4626 {
4627     CPUX86State *env = &cpu->env;
4628     int max_nested_state_len = kvm_max_nested_state_length();
4629     int ret;
4630 
4631     if (!env->nested_state) {
4632         return 0;
4633     }
4634 
4635     /*
4636      * It is possible that migration restored a smaller size into
4637      * nested_state->hdr.size than what our kernel support.
4638      * We preserve migration origin nested_state->hdr.size for
4639      * call to KVM_SET_NESTED_STATE but wish that our next call
4640      * to KVM_GET_NESTED_STATE will use max size our kernel support.
4641      */
4642     env->nested_state->size = max_nested_state_len;
4643 
4644     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_NESTED_STATE, env->nested_state);
4645     if (ret < 0) {
4646         return ret;
4647     }
4648 
4649     /*
4650      * Copy flags that are affected by reset to env->hflags and env->hflags2.
4651      */
4652     if (env->nested_state->flags & KVM_STATE_NESTED_GUEST_MODE) {
4653         env->hflags |= HF_GUEST_MASK;
4654     } else {
4655         env->hflags &= ~HF_GUEST_MASK;
4656     }
4657 
4658     /* Keep HF2_GIF_MASK set on !SVM as x86_cpu_pending_interrupt() needs it */
4659     if (cpu_has_svm(env)) {
4660         if (env->nested_state->flags & KVM_STATE_NESTED_GIF_SET) {
4661             env->hflags2 |= HF2_GIF_MASK;
4662         } else {
4663             env->hflags2 &= ~HF2_GIF_MASK;
4664         }
4665     }
4666 
4667     return ret;
4668 }
4669 
4670 int kvm_arch_put_registers(CPUState *cpu, int level)
4671 {
4672     X86CPU *x86_cpu = X86_CPU(cpu);
4673     int ret;
4674 
4675     assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
4676 
4677     /*
4678      * Put MSR_IA32_FEATURE_CONTROL first, this ensures the VM gets out of VMX
4679      * root operation upon vCPU reset. kvm_put_msr_feature_control() should also
4680      * precede kvm_put_nested_state() when 'real' nested state is set.
4681      */
4682     if (level >= KVM_PUT_RESET_STATE) {
4683         ret = kvm_put_msr_feature_control(x86_cpu);
4684         if (ret < 0) {
4685             return ret;
4686         }
4687     }
4688 
4689     /* must be before kvm_put_nested_state so that EFER.SVME is set */
4690     ret = has_sregs2 ? kvm_put_sregs2(x86_cpu) : kvm_put_sregs(x86_cpu);
4691     if (ret < 0) {
4692         return ret;
4693     }
4694 
4695     if (level >= KVM_PUT_RESET_STATE) {
4696         ret = kvm_put_nested_state(x86_cpu);
4697         if (ret < 0) {
4698             return ret;
4699         }
4700     }
4701 
4702     if (level == KVM_PUT_FULL_STATE) {
4703         /* We don't check for kvm_arch_set_tsc_khz() errors here,
4704          * because TSC frequency mismatch shouldn't abort migration,
4705          * unless the user explicitly asked for a more strict TSC
4706          * setting (e.g. using an explicit "tsc-freq" option).
4707          */
4708         kvm_arch_set_tsc_khz(cpu);
4709     }
4710 
4711 #ifdef CONFIG_XEN_EMU
4712     if (xen_mode == XEN_EMULATE && level == KVM_PUT_FULL_STATE) {
4713         ret = kvm_put_xen_state(cpu);
4714         if (ret < 0) {
4715             return ret;
4716         }
4717     }
4718 #endif
4719 
4720     ret = kvm_getput_regs(x86_cpu, 1);
4721     if (ret < 0) {
4722         return ret;
4723     }
4724     ret = kvm_put_xsave(x86_cpu);
4725     if (ret < 0) {
4726         return ret;
4727     }
4728     ret = kvm_put_xcrs(x86_cpu);
4729     if (ret < 0) {
4730         return ret;
4731     }
4732     ret = kvm_put_msrs(x86_cpu, level);
4733     if (ret < 0) {
4734         return ret;
4735     }
4736     ret = kvm_put_vcpu_events(x86_cpu, level);
4737     if (ret < 0) {
4738         return ret;
4739     }
4740     if (level >= KVM_PUT_RESET_STATE) {
4741         ret = kvm_put_mp_state(x86_cpu);
4742         if (ret < 0) {
4743             return ret;
4744         }
4745     }
4746 
4747     ret = kvm_put_tscdeadline_msr(x86_cpu);
4748     if (ret < 0) {
4749         return ret;
4750     }
4751     ret = kvm_put_debugregs(x86_cpu);
4752     if (ret < 0) {
4753         return ret;
4754     }
4755     return 0;
4756 }
4757 
4758 int kvm_arch_get_registers(CPUState *cs)
4759 {
4760     X86CPU *cpu = X86_CPU(cs);
4761     int ret;
4762 
4763     assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
4764 
4765     ret = kvm_get_vcpu_events(cpu);
4766     if (ret < 0) {
4767         goto out;
4768     }
4769     /*
4770      * KVM_GET_MPSTATE can modify CS and RIP, call it before
4771      * KVM_GET_REGS and KVM_GET_SREGS.
4772      */
4773     ret = kvm_get_mp_state(cpu);
4774     if (ret < 0) {
4775         goto out;
4776     }
4777     ret = kvm_getput_regs(cpu, 0);
4778     if (ret < 0) {
4779         goto out;
4780     }
4781     ret = kvm_get_xsave(cpu);
4782     if (ret < 0) {
4783         goto out;
4784     }
4785     ret = kvm_get_xcrs(cpu);
4786     if (ret < 0) {
4787         goto out;
4788     }
4789     ret = has_sregs2 ? kvm_get_sregs2(cpu) : kvm_get_sregs(cpu);
4790     if (ret < 0) {
4791         goto out;
4792     }
4793     ret = kvm_get_msrs(cpu);
4794     if (ret < 0) {
4795         goto out;
4796     }
4797     ret = kvm_get_apic(cpu);
4798     if (ret < 0) {
4799         goto out;
4800     }
4801     ret = kvm_get_debugregs(cpu);
4802     if (ret < 0) {
4803         goto out;
4804     }
4805     ret = kvm_get_nested_state(cpu);
4806     if (ret < 0) {
4807         goto out;
4808     }
4809 #ifdef CONFIG_XEN_EMU
4810     if (xen_mode == XEN_EMULATE) {
4811         ret = kvm_get_xen_state(cs);
4812         if (ret < 0) {
4813             goto out;
4814         }
4815     }
4816 #endif
4817     ret = 0;
4818  out:
4819     cpu_sync_bndcs_hflags(&cpu->env);
4820     return ret;
4821 }
4822 
4823 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
4824 {
4825     X86CPU *x86_cpu = X86_CPU(cpu);
4826     CPUX86State *env = &x86_cpu->env;
4827     int ret;
4828 
4829     /* Inject NMI */
4830     if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
4831         if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
4832             bql_lock();
4833             cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
4834             bql_unlock();
4835             DPRINTF("injected NMI\n");
4836             ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
4837             if (ret < 0) {
4838                 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
4839                         strerror(-ret));
4840             }
4841         }
4842         if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
4843             bql_lock();
4844             cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
4845             bql_unlock();
4846             DPRINTF("injected SMI\n");
4847             ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
4848             if (ret < 0) {
4849                 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
4850                         strerror(-ret));
4851             }
4852         }
4853     }
4854 
4855     if (!kvm_pic_in_kernel()) {
4856         bql_lock();
4857     }
4858 
4859     /* Force the VCPU out of its inner loop to process any INIT requests
4860      * or (for userspace APIC, but it is cheap to combine the checks here)
4861      * pending TPR access reports.
4862      */
4863     if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
4864         if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
4865             !(env->hflags & HF_SMM_MASK)) {
4866             cpu->exit_request = 1;
4867         }
4868         if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
4869             cpu->exit_request = 1;
4870         }
4871     }
4872 
4873     if (!kvm_pic_in_kernel()) {
4874         /* Try to inject an interrupt if the guest can accept it */
4875         if (run->ready_for_interrupt_injection &&
4876             (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
4877             (env->eflags & IF_MASK)) {
4878             int irq;
4879 
4880             cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
4881             irq = cpu_get_pic_interrupt(env);
4882             if (irq >= 0) {
4883                 struct kvm_interrupt intr;
4884 
4885                 intr.irq = irq;
4886                 DPRINTF("injected interrupt %d\n", irq);
4887                 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
4888                 if (ret < 0) {
4889                     fprintf(stderr,
4890                             "KVM: injection failed, interrupt lost (%s)\n",
4891                             strerror(-ret));
4892                 }
4893             }
4894         }
4895 
4896         /* If we have an interrupt but the guest is not ready to receive an
4897          * interrupt, request an interrupt window exit.  This will
4898          * cause a return to userspace as soon as the guest is ready to
4899          * receive interrupts. */
4900         if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
4901             run->request_interrupt_window = 1;
4902         } else {
4903             run->request_interrupt_window = 0;
4904         }
4905 
4906         DPRINTF("setting tpr\n");
4907         run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
4908 
4909         bql_unlock();
4910     }
4911 }
4912 
4913 static void kvm_rate_limit_on_bus_lock(void)
4914 {
4915     uint64_t delay_ns = ratelimit_calculate_delay(&bus_lock_ratelimit_ctrl, 1);
4916 
4917     if (delay_ns) {
4918         g_usleep(delay_ns / SCALE_US);
4919     }
4920 }
4921 
4922 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
4923 {
4924     X86CPU *x86_cpu = X86_CPU(cpu);
4925     CPUX86State *env = &x86_cpu->env;
4926 
4927     if (run->flags & KVM_RUN_X86_SMM) {
4928         env->hflags |= HF_SMM_MASK;
4929     } else {
4930         env->hflags &= ~HF_SMM_MASK;
4931     }
4932     if (run->if_flag) {
4933         env->eflags |= IF_MASK;
4934     } else {
4935         env->eflags &= ~IF_MASK;
4936     }
4937     if (run->flags & KVM_RUN_X86_BUS_LOCK) {
4938         kvm_rate_limit_on_bus_lock();
4939     }
4940 
4941 #ifdef CONFIG_XEN_EMU
4942     /*
4943      * If the callback is asserted as a GSI (or PCI INTx) then check if
4944      * vcpu_info->evtchn_upcall_pending has been cleared, and deassert
4945      * the callback IRQ if so. Ideally we could hook into the PIC/IOAPIC
4946      * EOI and only resample then, exactly how the VFIO eventfd pairs
4947      * are designed to work for level triggered interrupts.
4948      */
4949     if (x86_cpu->env.xen_callback_asserted) {
4950         kvm_xen_maybe_deassert_callback(cpu);
4951     }
4952 #endif
4953 
4954     /* We need to protect the apic state against concurrent accesses from
4955      * different threads in case the userspace irqchip is used. */
4956     if (!kvm_irqchip_in_kernel()) {
4957         bql_lock();
4958     }
4959     cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
4960     cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
4961     if (!kvm_irqchip_in_kernel()) {
4962         bql_unlock();
4963     }
4964     return cpu_get_mem_attrs(env);
4965 }
4966 
4967 int kvm_arch_process_async_events(CPUState *cs)
4968 {
4969     X86CPU *cpu = X86_CPU(cs);
4970     CPUX86State *env = &cpu->env;
4971 
4972     if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
4973         /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
4974         assert(env->mcg_cap);
4975 
4976         cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
4977 
4978         kvm_cpu_synchronize_state(cs);
4979 
4980         if (env->exception_nr == EXCP08_DBLE) {
4981             /* this means triple fault */
4982             qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
4983             cs->exit_request = 1;
4984             return 0;
4985         }
4986         kvm_queue_exception(env, EXCP12_MCHK, 0, 0);
4987         env->has_error_code = 0;
4988 
4989         cs->halted = 0;
4990         if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
4991             env->mp_state = KVM_MP_STATE_RUNNABLE;
4992         }
4993     }
4994 
4995     if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
4996         !(env->hflags & HF_SMM_MASK)) {
4997         kvm_cpu_synchronize_state(cs);
4998         do_cpu_init(cpu);
4999     }
5000 
5001     if (kvm_irqchip_in_kernel()) {
5002         return 0;
5003     }
5004 
5005     if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
5006         cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
5007         apic_poll_irq(cpu->apic_state);
5008     }
5009     if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
5010          (env->eflags & IF_MASK)) ||
5011         (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
5012         cs->halted = 0;
5013     }
5014     if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
5015         kvm_cpu_synchronize_state(cs);
5016         do_cpu_sipi(cpu);
5017     }
5018     if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
5019         cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
5020         kvm_cpu_synchronize_state(cs);
5021         apic_handle_tpr_access_report(cpu->apic_state, env->eip,
5022                                       env->tpr_access_type);
5023     }
5024 
5025     return cs->halted;
5026 }
5027 
5028 static int kvm_handle_halt(X86CPU *cpu)
5029 {
5030     CPUState *cs = CPU(cpu);
5031     CPUX86State *env = &cpu->env;
5032 
5033     if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
5034           (env->eflags & IF_MASK)) &&
5035         !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
5036         cs->halted = 1;
5037         return EXCP_HLT;
5038     }
5039 
5040     return 0;
5041 }
5042 
5043 static int kvm_handle_tpr_access(X86CPU *cpu)
5044 {
5045     CPUState *cs = CPU(cpu);
5046     struct kvm_run *run = cs->kvm_run;
5047 
5048     apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
5049                                   run->tpr_access.is_write ? TPR_ACCESS_WRITE
5050                                                            : TPR_ACCESS_READ);
5051     return 1;
5052 }
5053 
5054 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
5055 {
5056     static const uint8_t int3 = 0xcc;
5057 
5058     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
5059         cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
5060         return -EINVAL;
5061     }
5062     return 0;
5063 }
5064 
5065 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
5066 {
5067     uint8_t int3;
5068 
5069     if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0)) {
5070         return -EINVAL;
5071     }
5072     if (int3 != 0xcc) {
5073         return 0;
5074     }
5075     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
5076         return -EINVAL;
5077     }
5078     return 0;
5079 }
5080 
5081 static struct {
5082     target_ulong addr;
5083     int len;
5084     int type;
5085 } hw_breakpoint[4];
5086 
5087 static int nb_hw_breakpoint;
5088 
5089 static int find_hw_breakpoint(target_ulong addr, int len, int type)
5090 {
5091     int n;
5092 
5093     for (n = 0; n < nb_hw_breakpoint; n++) {
5094         if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
5095             (hw_breakpoint[n].len == len || len == -1)) {
5096             return n;
5097         }
5098     }
5099     return -1;
5100 }
5101 
5102 int kvm_arch_insert_hw_breakpoint(vaddr addr, vaddr len, int type)
5103 {
5104     switch (type) {
5105     case GDB_BREAKPOINT_HW:
5106         len = 1;
5107         break;
5108     case GDB_WATCHPOINT_WRITE:
5109     case GDB_WATCHPOINT_ACCESS:
5110         switch (len) {
5111         case 1:
5112             break;
5113         case 2:
5114         case 4:
5115         case 8:
5116             if (addr & (len - 1)) {
5117                 return -EINVAL;
5118             }
5119             break;
5120         default:
5121             return -EINVAL;
5122         }
5123         break;
5124     default:
5125         return -ENOSYS;
5126     }
5127 
5128     if (nb_hw_breakpoint == 4) {
5129         return -ENOBUFS;
5130     }
5131     if (find_hw_breakpoint(addr, len, type) >= 0) {
5132         return -EEXIST;
5133     }
5134     hw_breakpoint[nb_hw_breakpoint].addr = addr;
5135     hw_breakpoint[nb_hw_breakpoint].len = len;
5136     hw_breakpoint[nb_hw_breakpoint].type = type;
5137     nb_hw_breakpoint++;
5138 
5139     return 0;
5140 }
5141 
5142 int kvm_arch_remove_hw_breakpoint(vaddr addr, vaddr len, int type)
5143 {
5144     int n;
5145 
5146     n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
5147     if (n < 0) {
5148         return -ENOENT;
5149     }
5150     nb_hw_breakpoint--;
5151     hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
5152 
5153     return 0;
5154 }
5155 
5156 void kvm_arch_remove_all_hw_breakpoints(void)
5157 {
5158     nb_hw_breakpoint = 0;
5159 }
5160 
5161 static CPUWatchpoint hw_watchpoint;
5162 
5163 static int kvm_handle_debug(X86CPU *cpu,
5164                             struct kvm_debug_exit_arch *arch_info)
5165 {
5166     CPUState *cs = CPU(cpu);
5167     CPUX86State *env = &cpu->env;
5168     int ret = 0;
5169     int n;
5170 
5171     if (arch_info->exception == EXCP01_DB) {
5172         if (arch_info->dr6 & DR6_BS) {
5173             if (cs->singlestep_enabled) {
5174                 ret = EXCP_DEBUG;
5175             }
5176         } else {
5177             for (n = 0; n < 4; n++) {
5178                 if (arch_info->dr6 & (1 << n)) {
5179                     switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
5180                     case 0x0:
5181                         ret = EXCP_DEBUG;
5182                         break;
5183                     case 0x1:
5184                         ret = EXCP_DEBUG;
5185                         cs->watchpoint_hit = &hw_watchpoint;
5186                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
5187                         hw_watchpoint.flags = BP_MEM_WRITE;
5188                         break;
5189                     case 0x3:
5190                         ret = EXCP_DEBUG;
5191                         cs->watchpoint_hit = &hw_watchpoint;
5192                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
5193                         hw_watchpoint.flags = BP_MEM_ACCESS;
5194                         break;
5195                     }
5196                 }
5197             }
5198         }
5199     } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
5200         ret = EXCP_DEBUG;
5201     }
5202     if (ret == 0) {
5203         cpu_synchronize_state(cs);
5204         assert(env->exception_nr == -1);
5205 
5206         /* pass to guest */
5207         kvm_queue_exception(env, arch_info->exception,
5208                             arch_info->exception == EXCP01_DB,
5209                             arch_info->dr6);
5210         env->has_error_code = 0;
5211     }
5212 
5213     return ret;
5214 }
5215 
5216 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
5217 {
5218     const uint8_t type_code[] = {
5219         [GDB_BREAKPOINT_HW] = 0x0,
5220         [GDB_WATCHPOINT_WRITE] = 0x1,
5221         [GDB_WATCHPOINT_ACCESS] = 0x3
5222     };
5223     const uint8_t len_code[] = {
5224         [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
5225     };
5226     int n;
5227 
5228     if (kvm_sw_breakpoints_active(cpu)) {
5229         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
5230     }
5231     if (nb_hw_breakpoint > 0) {
5232         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
5233         dbg->arch.debugreg[7] = 0x0600;
5234         for (n = 0; n < nb_hw_breakpoint; n++) {
5235             dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
5236             dbg->arch.debugreg[7] |= (2 << (n * 2)) |
5237                 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
5238                 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
5239         }
5240     }
5241 }
5242 
5243 static bool kvm_install_msr_filters(KVMState *s)
5244 {
5245     uint64_t zero = 0;
5246     struct kvm_msr_filter filter = {
5247         .flags = KVM_MSR_FILTER_DEFAULT_ALLOW,
5248     };
5249     int r, i, j = 0;
5250 
5251     for (i = 0; i < KVM_MSR_FILTER_MAX_RANGES; i++) {
5252         KVMMSRHandlers *handler = &msr_handlers[i];
5253         if (handler->msr) {
5254             struct kvm_msr_filter_range *range = &filter.ranges[j++];
5255 
5256             *range = (struct kvm_msr_filter_range) {
5257                 .flags = 0,
5258                 .nmsrs = 1,
5259                 .base = handler->msr,
5260                 .bitmap = (__u8 *)&zero,
5261             };
5262 
5263             if (handler->rdmsr) {
5264                 range->flags |= KVM_MSR_FILTER_READ;
5265             }
5266 
5267             if (handler->wrmsr) {
5268                 range->flags |= KVM_MSR_FILTER_WRITE;
5269             }
5270         }
5271     }
5272 
5273     r = kvm_vm_ioctl(s, KVM_X86_SET_MSR_FILTER, &filter);
5274     if (r) {
5275         return false;
5276     }
5277 
5278     return true;
5279 }
5280 
5281 bool kvm_filter_msr(KVMState *s, uint32_t msr, QEMURDMSRHandler *rdmsr,
5282                     QEMUWRMSRHandler *wrmsr)
5283 {
5284     int i;
5285 
5286     for (i = 0; i < ARRAY_SIZE(msr_handlers); i++) {
5287         if (!msr_handlers[i].msr) {
5288             msr_handlers[i] = (KVMMSRHandlers) {
5289                 .msr = msr,
5290                 .rdmsr = rdmsr,
5291                 .wrmsr = wrmsr,
5292             };
5293 
5294             if (!kvm_install_msr_filters(s)) {
5295                 msr_handlers[i] = (KVMMSRHandlers) { };
5296                 return false;
5297             }
5298 
5299             return true;
5300         }
5301     }
5302 
5303     return false;
5304 }
5305 
5306 static int kvm_handle_rdmsr(X86CPU *cpu, struct kvm_run *run)
5307 {
5308     int i;
5309     bool r;
5310 
5311     for (i = 0; i < ARRAY_SIZE(msr_handlers); i++) {
5312         KVMMSRHandlers *handler = &msr_handlers[i];
5313         if (run->msr.index == handler->msr) {
5314             if (handler->rdmsr) {
5315                 r = handler->rdmsr(cpu, handler->msr,
5316                                    (uint64_t *)&run->msr.data);
5317                 run->msr.error = r ? 0 : 1;
5318                 return 0;
5319             }
5320         }
5321     }
5322 
5323     assert(false);
5324 }
5325 
5326 static int kvm_handle_wrmsr(X86CPU *cpu, struct kvm_run *run)
5327 {
5328     int i;
5329     bool r;
5330 
5331     for (i = 0; i < ARRAY_SIZE(msr_handlers); i++) {
5332         KVMMSRHandlers *handler = &msr_handlers[i];
5333         if (run->msr.index == handler->msr) {
5334             if (handler->wrmsr) {
5335                 r = handler->wrmsr(cpu, handler->msr, run->msr.data);
5336                 run->msr.error = r ? 0 : 1;
5337                 return 0;
5338             }
5339         }
5340     }
5341 
5342     assert(false);
5343 }
5344 
5345 static bool has_sgx_provisioning;
5346 
5347 static bool __kvm_enable_sgx_provisioning(KVMState *s)
5348 {
5349     int fd, ret;
5350 
5351     if (!kvm_vm_check_extension(s, KVM_CAP_SGX_ATTRIBUTE)) {
5352         return false;
5353     }
5354 
5355     fd = qemu_open_old("/dev/sgx_provision", O_RDONLY);
5356     if (fd < 0) {
5357         return false;
5358     }
5359 
5360     ret = kvm_vm_enable_cap(s, KVM_CAP_SGX_ATTRIBUTE, 0, fd);
5361     if (ret) {
5362         error_report("Could not enable SGX PROVISIONKEY: %s", strerror(-ret));
5363         exit(1);
5364     }
5365     close(fd);
5366     return true;
5367 }
5368 
5369 bool kvm_enable_sgx_provisioning(KVMState *s)
5370 {
5371     return MEMORIZE(__kvm_enable_sgx_provisioning(s), has_sgx_provisioning);
5372 }
5373 
5374 static bool host_supports_vmx(void)
5375 {
5376     uint32_t ecx, unused;
5377 
5378     host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
5379     return ecx & CPUID_EXT_VMX;
5380 }
5381 
5382 /*
5383  * Currently the handling here only supports use of KVM_HC_MAP_GPA_RANGE
5384  * to service guest-initiated memory attribute update requests so that
5385  * KVM_SET_MEMORY_ATTRIBUTES can update whether or not a page should be
5386  * backed by the private memory pool provided by guest_memfd, and as such
5387  * is only applicable to guest_memfd-backed guests (e.g. SNP/TDX).
5388  *
5389  * Other other use-cases for KVM_HC_MAP_GPA_RANGE, such as for SEV live
5390  * migration, are not implemented here currently.
5391  *
5392  * For the guest_memfd use-case, these exits will generally be synthesized
5393  * by KVM based on platform-specific hypercalls, like GHCB requests in the
5394  * case of SEV-SNP, and not issued directly within the guest though the
5395  * KVM_HC_MAP_GPA_RANGE hypercall. So in this case, KVM_HC_MAP_GPA_RANGE is
5396  * not actually advertised to guests via the KVM CPUID feature bit, as
5397  * opposed to SEV live migration where it would be. Since it is unlikely the
5398  * SEV live migration use-case would be useful for guest-memfd backed guests,
5399  * because private/shared page tracking is already provided through other
5400  * means, these 2 use-cases should be treated as being mutually-exclusive.
5401  */
5402 static int kvm_handle_hc_map_gpa_range(struct kvm_run *run)
5403 {
5404     uint64_t gpa, size, attributes;
5405 
5406     if (!machine_require_guest_memfd(current_machine))
5407         return -EINVAL;
5408 
5409     gpa = run->hypercall.args[0];
5410     size = run->hypercall.args[1] * TARGET_PAGE_SIZE;
5411     attributes = run->hypercall.args[2];
5412 
5413     trace_kvm_hc_map_gpa_range(gpa, size, attributes, run->hypercall.flags);
5414 
5415     return kvm_convert_memory(gpa, size, attributes & KVM_MAP_GPA_RANGE_ENCRYPTED);
5416 }
5417 
5418 static int kvm_handle_hypercall(struct kvm_run *run)
5419 {
5420     if (run->hypercall.nr == KVM_HC_MAP_GPA_RANGE)
5421         return kvm_handle_hc_map_gpa_range(run);
5422 
5423     return -EINVAL;
5424 }
5425 
5426 #define VMX_INVALID_GUEST_STATE 0x80000021
5427 
5428 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
5429 {
5430     X86CPU *cpu = X86_CPU(cs);
5431     uint64_t code;
5432     int ret;
5433     bool ctx_invalid;
5434     KVMState *state;
5435 
5436     switch (run->exit_reason) {
5437     case KVM_EXIT_HLT:
5438         DPRINTF("handle_hlt\n");
5439         bql_lock();
5440         ret = kvm_handle_halt(cpu);
5441         bql_unlock();
5442         break;
5443     case KVM_EXIT_SET_TPR:
5444         ret = 0;
5445         break;
5446     case KVM_EXIT_TPR_ACCESS:
5447         bql_lock();
5448         ret = kvm_handle_tpr_access(cpu);
5449         bql_unlock();
5450         break;
5451     case KVM_EXIT_FAIL_ENTRY:
5452         code = run->fail_entry.hardware_entry_failure_reason;
5453         fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
5454                 code);
5455         if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
5456             fprintf(stderr,
5457                     "\nIf you're running a guest on an Intel machine without "
5458                         "unrestricted mode\n"
5459                     "support, the failure can be most likely due to the guest "
5460                         "entering an invalid\n"
5461                     "state for Intel VT. For example, the guest maybe running "
5462                         "in big real mode\n"
5463                     "which is not supported on less recent Intel processors."
5464                         "\n\n");
5465         }
5466         ret = -1;
5467         break;
5468     case KVM_EXIT_EXCEPTION:
5469         fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
5470                 run->ex.exception, run->ex.error_code);
5471         ret = -1;
5472         break;
5473     case KVM_EXIT_DEBUG:
5474         DPRINTF("kvm_exit_debug\n");
5475         bql_lock();
5476         ret = kvm_handle_debug(cpu, &run->debug.arch);
5477         bql_unlock();
5478         break;
5479     case KVM_EXIT_HYPERV:
5480         ret = kvm_hv_handle_exit(cpu, &run->hyperv);
5481         break;
5482     case KVM_EXIT_IOAPIC_EOI:
5483         ioapic_eoi_broadcast(run->eoi.vector);
5484         ret = 0;
5485         break;
5486     case KVM_EXIT_X86_BUS_LOCK:
5487         /* already handled in kvm_arch_post_run */
5488         ret = 0;
5489         break;
5490     case KVM_EXIT_NOTIFY:
5491         ctx_invalid = !!(run->notify.flags & KVM_NOTIFY_CONTEXT_INVALID);
5492         state = KVM_STATE(current_accel());
5493         if (ctx_invalid ||
5494             state->notify_vmexit == NOTIFY_VMEXIT_OPTION_INTERNAL_ERROR) {
5495             warn_report("KVM internal error: Encountered a notify exit "
5496                         "with invalid context in guest.");
5497             ret = -1;
5498         } else {
5499             warn_report_once("KVM: Encountered a notify exit with valid "
5500                              "context in guest. "
5501                              "The guest could be misbehaving.");
5502             ret = 0;
5503         }
5504         break;
5505     case KVM_EXIT_X86_RDMSR:
5506         /* We only enable MSR filtering, any other exit is bogus */
5507         assert(run->msr.reason == KVM_MSR_EXIT_REASON_FILTER);
5508         ret = kvm_handle_rdmsr(cpu, run);
5509         break;
5510     case KVM_EXIT_X86_WRMSR:
5511         /* We only enable MSR filtering, any other exit is bogus */
5512         assert(run->msr.reason == KVM_MSR_EXIT_REASON_FILTER);
5513         ret = kvm_handle_wrmsr(cpu, run);
5514         break;
5515 #ifdef CONFIG_XEN_EMU
5516     case KVM_EXIT_XEN:
5517         ret = kvm_xen_handle_exit(cpu, &run->xen);
5518         break;
5519 #endif
5520     case KVM_EXIT_HYPERCALL:
5521         ret = kvm_handle_hypercall(run);
5522         break;
5523     default:
5524         fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
5525         ret = -1;
5526         break;
5527     }
5528 
5529     return ret;
5530 }
5531 
5532 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
5533 {
5534     X86CPU *cpu = X86_CPU(cs);
5535     CPUX86State *env = &cpu->env;
5536 
5537     kvm_cpu_synchronize_state(cs);
5538     return !(env->cr[0] & CR0_PE_MASK) ||
5539            ((env->segs[R_CS].selector  & 3) != 3);
5540 }
5541 
5542 void kvm_arch_init_irq_routing(KVMState *s)
5543 {
5544     /* We know at this point that we're using the in-kernel
5545      * irqchip, so we can use irqfds, and on x86 we know
5546      * we can use msi via irqfd and GSI routing.
5547      */
5548     kvm_msi_via_irqfd_allowed = true;
5549     kvm_gsi_routing_allowed = true;
5550 
5551     if (kvm_irqchip_is_split()) {
5552         KVMRouteChange c = kvm_irqchip_begin_route_changes(s);
5553         int i;
5554 
5555         /* If the ioapic is in QEMU and the lapics are in KVM, reserve
5556            MSI routes for signaling interrupts to the local apics. */
5557         for (i = 0; i < IOAPIC_NUM_PINS; i++) {
5558             if (kvm_irqchip_add_msi_route(&c, 0, NULL) < 0) {
5559                 error_report("Could not enable split IRQ mode.");
5560                 exit(1);
5561             }
5562         }
5563         kvm_irqchip_commit_route_changes(&c);
5564     }
5565 }
5566 
5567 int kvm_arch_irqchip_create(KVMState *s)
5568 {
5569     int ret;
5570     if (kvm_kernel_irqchip_split()) {
5571         ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
5572         if (ret) {
5573             error_report("Could not enable split irqchip mode: %s",
5574                          strerror(-ret));
5575             exit(1);
5576         } else {
5577             DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
5578             kvm_split_irqchip = true;
5579             return 1;
5580         }
5581     } else {
5582         return 0;
5583     }
5584 }
5585 
5586 uint64_t kvm_swizzle_msi_ext_dest_id(uint64_t address)
5587 {
5588     CPUX86State *env;
5589     uint64_t ext_id;
5590 
5591     if (!first_cpu) {
5592         return address;
5593     }
5594     env = &X86_CPU(first_cpu)->env;
5595     if (!(env->features[FEAT_KVM] & (1 << KVM_FEATURE_MSI_EXT_DEST_ID))) {
5596         return address;
5597     }
5598 
5599     /*
5600      * If the remappable format bit is set, or the upper bits are
5601      * already set in address_hi, or the low extended bits aren't
5602      * there anyway, do nothing.
5603      */
5604     ext_id = address & (0xff << MSI_ADDR_DEST_IDX_SHIFT);
5605     if (!ext_id || (ext_id & (1 << MSI_ADDR_DEST_IDX_SHIFT)) || (address >> 32)) {
5606         return address;
5607     }
5608 
5609     address &= ~ext_id;
5610     address |= ext_id << 35;
5611     return address;
5612 }
5613 
5614 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
5615                              uint64_t address, uint32_t data, PCIDevice *dev)
5616 {
5617     X86IOMMUState *iommu = x86_iommu_get_default();
5618 
5619     if (iommu) {
5620         X86IOMMUClass *class = X86_IOMMU_DEVICE_GET_CLASS(iommu);
5621 
5622         if (class->int_remap) {
5623             int ret;
5624             MSIMessage src, dst;
5625 
5626             src.address = route->u.msi.address_hi;
5627             src.address <<= VTD_MSI_ADDR_HI_SHIFT;
5628             src.address |= route->u.msi.address_lo;
5629             src.data = route->u.msi.data;
5630 
5631             ret = class->int_remap(iommu, &src, &dst, dev ?     \
5632                                    pci_requester_id(dev) :      \
5633                                    X86_IOMMU_SID_INVALID);
5634             if (ret) {
5635                 trace_kvm_x86_fixup_msi_error(route->gsi);
5636                 return 1;
5637             }
5638 
5639             /*
5640              * Handled untranslated compatibility format interrupt with
5641              * extended destination ID in the low bits 11-5. */
5642             dst.address = kvm_swizzle_msi_ext_dest_id(dst.address);
5643 
5644             route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
5645             route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
5646             route->u.msi.data = dst.data;
5647             return 0;
5648         }
5649     }
5650 
5651 #ifdef CONFIG_XEN_EMU
5652     if (xen_mode == XEN_EMULATE) {
5653         int handled = xen_evtchn_translate_pirq_msi(route, address, data);
5654 
5655         /*
5656          * If it was a PIRQ and successfully routed (handled == 0) or it was
5657          * an error (handled < 0), return. If it wasn't a PIRQ, keep going.
5658          */
5659         if (handled <= 0) {
5660             return handled;
5661         }
5662     }
5663 #endif
5664 
5665     address = kvm_swizzle_msi_ext_dest_id(address);
5666     route->u.msi.address_hi = address >> VTD_MSI_ADDR_HI_SHIFT;
5667     route->u.msi.address_lo = address & VTD_MSI_ADDR_LO_MASK;
5668     return 0;
5669 }
5670 
5671 typedef struct MSIRouteEntry MSIRouteEntry;
5672 
5673 struct MSIRouteEntry {
5674     PCIDevice *dev;             /* Device pointer */
5675     int vector;                 /* MSI/MSIX vector index */
5676     int virq;                   /* Virtual IRQ index */
5677     QLIST_ENTRY(MSIRouteEntry) list;
5678 };
5679 
5680 /* List of used GSI routes */
5681 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
5682     QLIST_HEAD_INITIALIZER(msi_route_list);
5683 
5684 void kvm_update_msi_routes_all(void *private, bool global,
5685                                uint32_t index, uint32_t mask)
5686 {
5687     int cnt = 0, vector;
5688     MSIRouteEntry *entry;
5689     MSIMessage msg;
5690     PCIDevice *dev;
5691 
5692     /* TODO: explicit route update */
5693     QLIST_FOREACH(entry, &msi_route_list, list) {
5694         cnt++;
5695         vector = entry->vector;
5696         dev = entry->dev;
5697         if (msix_enabled(dev) && !msix_is_masked(dev, vector)) {
5698             msg = msix_get_message(dev, vector);
5699         } else if (msi_enabled(dev) && !msi_is_masked(dev, vector)) {
5700             msg = msi_get_message(dev, vector);
5701         } else {
5702             /*
5703              * Either MSI/MSIX is disabled for the device, or the
5704              * specific message was masked out.  Skip this one.
5705              */
5706             continue;
5707         }
5708         kvm_irqchip_update_msi_route(kvm_state, entry->virq, msg, dev);
5709     }
5710     kvm_irqchip_commit_routes(kvm_state);
5711     trace_kvm_x86_update_msi_routes(cnt);
5712 }
5713 
5714 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
5715                                 int vector, PCIDevice *dev)
5716 {
5717     static bool notify_list_inited = false;
5718     MSIRouteEntry *entry;
5719 
5720     if (!dev) {
5721         /* These are (possibly) IOAPIC routes only used for split
5722          * kernel irqchip mode, while what we are housekeeping are
5723          * PCI devices only. */
5724         return 0;
5725     }
5726 
5727     entry = g_new0(MSIRouteEntry, 1);
5728     entry->dev = dev;
5729     entry->vector = vector;
5730     entry->virq = route->gsi;
5731     QLIST_INSERT_HEAD(&msi_route_list, entry, list);
5732 
5733     trace_kvm_x86_add_msi_route(route->gsi);
5734 
5735     if (!notify_list_inited) {
5736         /* For the first time we do add route, add ourselves into
5737          * IOMMU's IEC notify list if needed. */
5738         X86IOMMUState *iommu = x86_iommu_get_default();
5739         if (iommu) {
5740             x86_iommu_iec_register_notifier(iommu,
5741                                             kvm_update_msi_routes_all,
5742                                             NULL);
5743         }
5744         notify_list_inited = true;
5745     }
5746     return 0;
5747 }
5748 
5749 int kvm_arch_release_virq_post(int virq)
5750 {
5751     MSIRouteEntry *entry, *next;
5752     QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
5753         if (entry->virq == virq) {
5754             trace_kvm_x86_remove_msi_route(virq);
5755             QLIST_REMOVE(entry, list);
5756             g_free(entry);
5757             break;
5758         }
5759     }
5760     return 0;
5761 }
5762 
5763 int kvm_arch_msi_data_to_gsi(uint32_t data)
5764 {
5765     abort();
5766 }
5767 
5768 bool kvm_has_waitpkg(void)
5769 {
5770     return has_msr_umwait;
5771 }
5772 
5773 #define ARCH_REQ_XCOMP_GUEST_PERM       0x1025
5774 
5775 void kvm_request_xsave_components(X86CPU *cpu, uint64_t mask)
5776 {
5777     KVMState *s = kvm_state;
5778     uint64_t supported;
5779 
5780     mask &= XSTATE_DYNAMIC_MASK;
5781     if (!mask) {
5782         return;
5783     }
5784     /*
5785      * Just ignore bits that are not in CPUID[EAX=0xD,ECX=0].
5786      * ARCH_REQ_XCOMP_GUEST_PERM would fail, and QEMU has warned
5787      * about them already because they are not supported features.
5788      */
5789     supported = kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EAX);
5790     supported |= (uint64_t)kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EDX) << 32;
5791     mask &= supported;
5792 
5793     while (mask) {
5794         int bit = ctz64(mask);
5795         int rc = syscall(SYS_arch_prctl, ARCH_REQ_XCOMP_GUEST_PERM, bit);
5796         if (rc) {
5797             /*
5798              * Older kernel version (<5.17) do not support
5799              * ARCH_REQ_XCOMP_GUEST_PERM, but also do not return
5800              * any dynamic feature from kvm_arch_get_supported_cpuid.
5801              */
5802             warn_report("prctl(ARCH_REQ_XCOMP_GUEST_PERM) failure "
5803                         "for feature bit %d", bit);
5804         }
5805         mask &= ~BIT_ULL(bit);
5806     }
5807 }
5808 
5809 static int kvm_arch_get_notify_vmexit(Object *obj, Error **errp)
5810 {
5811     KVMState *s = KVM_STATE(obj);
5812     return s->notify_vmexit;
5813 }
5814 
5815 static void kvm_arch_set_notify_vmexit(Object *obj, int value, Error **errp)
5816 {
5817     KVMState *s = KVM_STATE(obj);
5818 
5819     if (s->fd != -1) {
5820         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
5821         return;
5822     }
5823 
5824     s->notify_vmexit = value;
5825 }
5826 
5827 static void kvm_arch_get_notify_window(Object *obj, Visitor *v,
5828                                        const char *name, void *opaque,
5829                                        Error **errp)
5830 {
5831     KVMState *s = KVM_STATE(obj);
5832     uint32_t value = s->notify_window;
5833 
5834     visit_type_uint32(v, name, &value, errp);
5835 }
5836 
5837 static void kvm_arch_set_notify_window(Object *obj, Visitor *v,
5838                                        const char *name, void *opaque,
5839                                        Error **errp)
5840 {
5841     KVMState *s = KVM_STATE(obj);
5842     uint32_t value;
5843 
5844     if (s->fd != -1) {
5845         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
5846         return;
5847     }
5848 
5849     if (!visit_type_uint32(v, name, &value, errp)) {
5850         return;
5851     }
5852 
5853     s->notify_window = value;
5854 }
5855 
5856 static void kvm_arch_get_xen_version(Object *obj, Visitor *v,
5857                                      const char *name, void *opaque,
5858                                      Error **errp)
5859 {
5860     KVMState *s = KVM_STATE(obj);
5861     uint32_t value = s->xen_version;
5862 
5863     visit_type_uint32(v, name, &value, errp);
5864 }
5865 
5866 static void kvm_arch_set_xen_version(Object *obj, Visitor *v,
5867                                      const char *name, void *opaque,
5868                                      Error **errp)
5869 {
5870     KVMState *s = KVM_STATE(obj);
5871     Error *error = NULL;
5872     uint32_t value;
5873 
5874     visit_type_uint32(v, name, &value, &error);
5875     if (error) {
5876         error_propagate(errp, error);
5877         return;
5878     }
5879 
5880     s->xen_version = value;
5881     if (value && xen_mode == XEN_DISABLED) {
5882         xen_mode = XEN_EMULATE;
5883     }
5884 }
5885 
5886 static void kvm_arch_get_xen_gnttab_max_frames(Object *obj, Visitor *v,
5887                                                const char *name, void *opaque,
5888                                                Error **errp)
5889 {
5890     KVMState *s = KVM_STATE(obj);
5891     uint16_t value = s->xen_gnttab_max_frames;
5892 
5893     visit_type_uint16(v, name, &value, errp);
5894 }
5895 
5896 static void kvm_arch_set_xen_gnttab_max_frames(Object *obj, Visitor *v,
5897                                                const char *name, void *opaque,
5898                                                Error **errp)
5899 {
5900     KVMState *s = KVM_STATE(obj);
5901     Error *error = NULL;
5902     uint16_t value;
5903 
5904     visit_type_uint16(v, name, &value, &error);
5905     if (error) {
5906         error_propagate(errp, error);
5907         return;
5908     }
5909 
5910     s->xen_gnttab_max_frames = value;
5911 }
5912 
5913 static void kvm_arch_get_xen_evtchn_max_pirq(Object *obj, Visitor *v,
5914                                              const char *name, void *opaque,
5915                                              Error **errp)
5916 {
5917     KVMState *s = KVM_STATE(obj);
5918     uint16_t value = s->xen_evtchn_max_pirq;
5919 
5920     visit_type_uint16(v, name, &value, errp);
5921 }
5922 
5923 static void kvm_arch_set_xen_evtchn_max_pirq(Object *obj, Visitor *v,
5924                                              const char *name, void *opaque,
5925                                              Error **errp)
5926 {
5927     KVMState *s = KVM_STATE(obj);
5928     Error *error = NULL;
5929     uint16_t value;
5930 
5931     visit_type_uint16(v, name, &value, &error);
5932     if (error) {
5933         error_propagate(errp, error);
5934         return;
5935     }
5936 
5937     s->xen_evtchn_max_pirq = value;
5938 }
5939 
5940 void kvm_arch_accel_class_init(ObjectClass *oc)
5941 {
5942     object_class_property_add_enum(oc, "notify-vmexit", "NotifyVMexitOption",
5943                                    &NotifyVmexitOption_lookup,
5944                                    kvm_arch_get_notify_vmexit,
5945                                    kvm_arch_set_notify_vmexit);
5946     object_class_property_set_description(oc, "notify-vmexit",
5947                                           "Enable notify VM exit");
5948 
5949     object_class_property_add(oc, "notify-window", "uint32",
5950                               kvm_arch_get_notify_window,
5951                               kvm_arch_set_notify_window,
5952                               NULL, NULL);
5953     object_class_property_set_description(oc, "notify-window",
5954                                           "Clock cycles without an event window "
5955                                           "after which a notification VM exit occurs");
5956 
5957     object_class_property_add(oc, "xen-version", "uint32",
5958                               kvm_arch_get_xen_version,
5959                               kvm_arch_set_xen_version,
5960                               NULL, NULL);
5961     object_class_property_set_description(oc, "xen-version",
5962                                           "Xen version to be emulated "
5963                                           "(in XENVER_version form "
5964                                           "e.g. 0x4000a for 4.10)");
5965 
5966     object_class_property_add(oc, "xen-gnttab-max-frames", "uint16",
5967                               kvm_arch_get_xen_gnttab_max_frames,
5968                               kvm_arch_set_xen_gnttab_max_frames,
5969                               NULL, NULL);
5970     object_class_property_set_description(oc, "xen-gnttab-max-frames",
5971                                           "Maximum number of grant table frames");
5972 
5973     object_class_property_add(oc, "xen-evtchn-max-pirq", "uint16",
5974                               kvm_arch_get_xen_evtchn_max_pirq,
5975                               kvm_arch_set_xen_evtchn_max_pirq,
5976                               NULL, NULL);
5977     object_class_property_set_description(oc, "xen-evtchn-max-pirq",
5978                                           "Maximum number of Xen PIRQs");
5979 }
5980 
5981 void kvm_set_max_apic_id(uint32_t max_apic_id)
5982 {
5983     kvm_vm_enable_cap(kvm_state, KVM_CAP_MAX_VCPU_ID, 0, max_apic_id);
5984 }
5985