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