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