xref: /openbmc/qemu/target/i386/kvm/kvm.c (revision a6e65975)
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     int type, ret;
4106 
4107     type = has_xsave2 ? KVM_GET_XSAVE2 : KVM_GET_XSAVE;
4108     ret = kvm_vcpu_ioctl(CPU(cpu), type, xsave);
4109     if (ret < 0) {
4110         return ret;
4111     }
4112     x86_cpu_xrstor_all_areas(cpu, xsave, env->xsave_buf_len);
4113 
4114     return 0;
4115 }
4116 
4117 static int kvm_get_xcrs(X86CPU *cpu)
4118 {
4119     CPUX86State *env = &cpu->env;
4120     int i, ret;
4121     struct kvm_xcrs xcrs;
4122 
4123     if (!has_xcrs) {
4124         return 0;
4125     }
4126 
4127     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
4128     if (ret < 0) {
4129         return ret;
4130     }
4131 
4132     for (i = 0; i < xcrs.nr_xcrs; i++) {
4133         /* Only support xcr0 now */
4134         if (xcrs.xcrs[i].xcr == 0) {
4135             env->xcr0 = xcrs.xcrs[i].value;
4136             break;
4137         }
4138     }
4139     return 0;
4140 }
4141 
4142 static int kvm_get_sregs(X86CPU *cpu)
4143 {
4144     CPUX86State *env = &cpu->env;
4145     struct kvm_sregs sregs;
4146     int ret;
4147 
4148     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
4149     if (ret < 0) {
4150         return ret;
4151     }
4152 
4153     /*
4154      * The interrupt_bitmap is ignored because KVM_GET_SREGS is
4155      * always preceded by KVM_GET_VCPU_EVENTS.
4156      */
4157 
4158     get_seg(&env->segs[R_CS], &sregs.cs);
4159     get_seg(&env->segs[R_DS], &sregs.ds);
4160     get_seg(&env->segs[R_ES], &sregs.es);
4161     get_seg(&env->segs[R_FS], &sregs.fs);
4162     get_seg(&env->segs[R_GS], &sregs.gs);
4163     get_seg(&env->segs[R_SS], &sregs.ss);
4164 
4165     get_seg(&env->tr, &sregs.tr);
4166     get_seg(&env->ldt, &sregs.ldt);
4167 
4168     env->idt.limit = sregs.idt.limit;
4169     env->idt.base = sregs.idt.base;
4170     env->gdt.limit = sregs.gdt.limit;
4171     env->gdt.base = sregs.gdt.base;
4172 
4173     env->cr[0] = sregs.cr0;
4174     env->cr[2] = sregs.cr2;
4175     env->cr[3] = sregs.cr3;
4176     env->cr[4] = sregs.cr4;
4177 
4178     env->efer = sregs.efer;
4179     if (sev_es_enabled() && env->efer & MSR_EFER_LME &&
4180         env->cr[0] & CR0_PG_MASK) {
4181         env->efer |= MSR_EFER_LMA;
4182     }
4183 
4184     /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
4185     x86_update_hflags(env);
4186 
4187     return 0;
4188 }
4189 
4190 static int kvm_get_sregs2(X86CPU *cpu)
4191 {
4192     CPUX86State *env = &cpu->env;
4193     struct kvm_sregs2 sregs;
4194     int i, ret;
4195 
4196     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS2, &sregs);
4197     if (ret < 0) {
4198         return ret;
4199     }
4200 
4201     get_seg(&env->segs[R_CS], &sregs.cs);
4202     get_seg(&env->segs[R_DS], &sregs.ds);
4203     get_seg(&env->segs[R_ES], &sregs.es);
4204     get_seg(&env->segs[R_FS], &sregs.fs);
4205     get_seg(&env->segs[R_GS], &sregs.gs);
4206     get_seg(&env->segs[R_SS], &sregs.ss);
4207 
4208     get_seg(&env->tr, &sregs.tr);
4209     get_seg(&env->ldt, &sregs.ldt);
4210 
4211     env->idt.limit = sregs.idt.limit;
4212     env->idt.base = sregs.idt.base;
4213     env->gdt.limit = sregs.gdt.limit;
4214     env->gdt.base = sregs.gdt.base;
4215 
4216     env->cr[0] = sregs.cr0;
4217     env->cr[2] = sregs.cr2;
4218     env->cr[3] = sregs.cr3;
4219     env->cr[4] = sregs.cr4;
4220 
4221     env->efer = sregs.efer;
4222     if (sev_es_enabled() && env->efer & MSR_EFER_LME &&
4223         env->cr[0] & CR0_PG_MASK) {
4224         env->efer |= MSR_EFER_LMA;
4225     }
4226 
4227     env->pdptrs_valid = sregs.flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
4228 
4229     if (env->pdptrs_valid) {
4230         for (i = 0; i < 4; i++) {
4231             env->pdptrs[i] = sregs.pdptrs[i];
4232         }
4233     }
4234 
4235     /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
4236     x86_update_hflags(env);
4237 
4238     return 0;
4239 }
4240 
4241 static int kvm_get_msrs(X86CPU *cpu)
4242 {
4243     CPUX86State *env = &cpu->env;
4244     struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
4245     int ret, i;
4246     uint64_t mtrr_top_bits;
4247 
4248     kvm_msr_buf_reset(cpu);
4249 
4250     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
4251     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
4252     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
4253     kvm_msr_entry_add(cpu, MSR_PAT, 0);
4254     if (has_msr_star) {
4255         kvm_msr_entry_add(cpu, MSR_STAR, 0);
4256     }
4257     if (has_msr_hsave_pa) {
4258         kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
4259     }
4260     if (has_msr_tsc_aux) {
4261         kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
4262     }
4263     if (has_msr_tsc_adjust) {
4264         kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
4265     }
4266     if (has_msr_tsc_deadline) {
4267         kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
4268     }
4269     if (has_msr_misc_enable) {
4270         kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
4271     }
4272     if (has_msr_smbase) {
4273         kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
4274     }
4275     if (has_msr_smi_count) {
4276         kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
4277     }
4278     if (has_msr_feature_control) {
4279         kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
4280     }
4281     if (has_msr_pkrs) {
4282         kvm_msr_entry_add(cpu, MSR_IA32_PKRS, 0);
4283     }
4284     if (has_msr_bndcfgs) {
4285         kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
4286     }
4287     if (has_msr_xss) {
4288         kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
4289     }
4290     if (has_msr_umwait) {
4291         kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, 0);
4292     }
4293     if (has_msr_spec_ctrl) {
4294         kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
4295     }
4296     if (has_tsc_scale_msr) {
4297         kvm_msr_entry_add(cpu, MSR_AMD64_TSC_RATIO, 0);
4298     }
4299 
4300     if (has_msr_tsx_ctrl) {
4301         kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, 0);
4302     }
4303     if (has_msr_virt_ssbd) {
4304         kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, 0);
4305     }
4306     if (!env->tsc_valid) {
4307         kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
4308         env->tsc_valid = !runstate_is_running();
4309     }
4310 
4311 #ifdef TARGET_X86_64
4312     if (lm_capable_kernel) {
4313         kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
4314         kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
4315         kvm_msr_entry_add(cpu, MSR_FMASK, 0);
4316         kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
4317         if (env->features[FEAT_7_1_EAX] & CPUID_7_1_EAX_FRED) {
4318             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP0, 0);
4319             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP1, 0);
4320             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP2, 0);
4321             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP3, 0);
4322             kvm_msr_entry_add(cpu, MSR_IA32_FRED_STKLVLS, 0);
4323             kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP1, 0);
4324             kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP2, 0);
4325             kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP3, 0);
4326             kvm_msr_entry_add(cpu, MSR_IA32_FRED_CONFIG, 0);
4327         }
4328     }
4329 #endif
4330     kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
4331     kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
4332     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
4333         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, 0);
4334     }
4335     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
4336         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
4337     }
4338     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
4339         kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
4340     }
4341     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
4342         kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
4343     }
4344     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
4345         kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, 1);
4346     }
4347     if (has_architectural_pmu_version > 0) {
4348         if (has_architectural_pmu_version > 1) {
4349             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
4350             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
4351             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
4352             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
4353         }
4354         for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
4355             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
4356         }
4357         for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
4358             kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
4359             kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
4360         }
4361     }
4362 
4363     if (env->mcg_cap) {
4364         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
4365         kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
4366         if (has_msr_mcg_ext_ctl) {
4367             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
4368         }
4369         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
4370             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
4371         }
4372     }
4373 
4374     if (has_msr_hv_hypercall) {
4375         kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
4376         kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
4377     }
4378     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
4379         kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
4380     }
4381     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
4382         kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
4383     }
4384     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
4385         kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL, 0);
4386         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL, 0);
4387         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS, 0);
4388     }
4389     if (has_msr_hv_syndbg_options) {
4390         kvm_msr_entry_add(cpu, HV_X64_MSR_SYNDBG_OPTIONS, 0);
4391     }
4392     if (has_msr_hv_crash) {
4393         int j;
4394 
4395         for (j = 0; j < HV_CRASH_PARAMS; j++) {
4396             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
4397         }
4398     }
4399     if (has_msr_hv_runtime) {
4400         kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
4401     }
4402     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
4403         uint32_t msr;
4404 
4405         kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
4406         kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
4407         kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
4408         for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
4409             kvm_msr_entry_add(cpu, msr, 0);
4410         }
4411     }
4412     if (has_msr_hv_stimer) {
4413         uint32_t msr;
4414 
4415         for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
4416              msr++) {
4417             kvm_msr_entry_add(cpu, msr, 0);
4418         }
4419     }
4420     if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
4421         kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
4422         kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
4423         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
4424         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
4425         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
4426         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
4427         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
4428         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
4429         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
4430         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
4431         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
4432         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
4433         for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
4434             kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
4435             kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
4436         }
4437     }
4438 
4439     if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
4440         int addr_num =
4441             kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
4442 
4443         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
4444         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
4445         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
4446         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
4447         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
4448         for (i = 0; i < addr_num; i++) {
4449             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
4450         }
4451     }
4452 
4453     if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_SGX_LC) {
4454         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH0, 0);
4455         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH1, 0);
4456         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH2, 0);
4457         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH3, 0);
4458     }
4459 
4460     if (env->features[FEAT_XSAVE] & CPUID_D_1_EAX_XFD) {
4461         kvm_msr_entry_add(cpu, MSR_IA32_XFD, 0);
4462         kvm_msr_entry_add(cpu, MSR_IA32_XFD_ERR, 0);
4463     }
4464 
4465     if (kvm_enabled() && cpu->enable_pmu &&
4466         (env->features[FEAT_7_0_EDX] & CPUID_7_0_EDX_ARCH_LBR)) {
4467         uint64_t depth;
4468 
4469         ret = kvm_get_one_msr(cpu, MSR_ARCH_LBR_DEPTH, &depth);
4470         if (ret == 1 && depth == ARCH_LBR_NR_ENTRIES) {
4471             kvm_msr_entry_add(cpu, MSR_ARCH_LBR_CTL, 0);
4472             kvm_msr_entry_add(cpu, MSR_ARCH_LBR_DEPTH, 0);
4473 
4474             for (i = 0; i < ARCH_LBR_NR_ENTRIES; i++) {
4475                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_FROM_0 + i, 0);
4476                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_TO_0 + i, 0);
4477                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_INFO_0 + i, 0);
4478             }
4479         }
4480     }
4481 
4482     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
4483     if (ret < 0) {
4484         return ret;
4485     }
4486 
4487     if (ret < cpu->kvm_msr_buf->nmsrs) {
4488         struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
4489         error_report("error: failed to get MSR 0x%" PRIx32,
4490                      (uint32_t)e->index);
4491     }
4492 
4493     assert(ret == cpu->kvm_msr_buf->nmsrs);
4494     /*
4495      * MTRR masks: Each mask consists of 5 parts
4496      * a  10..0: must be zero
4497      * b  11   : valid bit
4498      * c n-1.12: actual mask bits
4499      * d  51..n: reserved must be zero
4500      * e  63.52: reserved must be zero
4501      *
4502      * 'n' is the number of physical bits supported by the CPU and is
4503      * apparently always <= 52.   We know our 'n' but don't know what
4504      * the destinations 'n' is; it might be smaller, in which case
4505      * it masks (c) on loading. It might be larger, in which case
4506      * we fill 'd' so that d..c is consistent irrespetive of the 'n'
4507      * we're migrating to.
4508      */
4509 
4510     if (cpu->fill_mtrr_mask) {
4511         QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
4512         assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
4513         mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
4514     } else {
4515         mtrr_top_bits = 0;
4516     }
4517 
4518     for (i = 0; i < ret; i++) {
4519         uint32_t index = msrs[i].index;
4520         switch (index) {
4521         case MSR_IA32_SYSENTER_CS:
4522             env->sysenter_cs = msrs[i].data;
4523             break;
4524         case MSR_IA32_SYSENTER_ESP:
4525             env->sysenter_esp = msrs[i].data;
4526             break;
4527         case MSR_IA32_SYSENTER_EIP:
4528             env->sysenter_eip = msrs[i].data;
4529             break;
4530         case MSR_PAT:
4531             env->pat = msrs[i].data;
4532             break;
4533         case MSR_STAR:
4534             env->star = msrs[i].data;
4535             break;
4536 #ifdef TARGET_X86_64
4537         case MSR_CSTAR:
4538             env->cstar = msrs[i].data;
4539             break;
4540         case MSR_KERNELGSBASE:
4541             env->kernelgsbase = msrs[i].data;
4542             break;
4543         case MSR_FMASK:
4544             env->fmask = msrs[i].data;
4545             break;
4546         case MSR_LSTAR:
4547             env->lstar = msrs[i].data;
4548             break;
4549         case MSR_IA32_FRED_RSP0:
4550             env->fred_rsp0 = msrs[i].data;
4551             break;
4552         case MSR_IA32_FRED_RSP1:
4553             env->fred_rsp1 = msrs[i].data;
4554             break;
4555         case MSR_IA32_FRED_RSP2:
4556             env->fred_rsp2 = msrs[i].data;
4557             break;
4558         case MSR_IA32_FRED_RSP3:
4559             env->fred_rsp3 = msrs[i].data;
4560             break;
4561         case MSR_IA32_FRED_STKLVLS:
4562             env->fred_stklvls = msrs[i].data;
4563             break;
4564         case MSR_IA32_FRED_SSP1:
4565             env->fred_ssp1 = msrs[i].data;
4566             break;
4567         case MSR_IA32_FRED_SSP2:
4568             env->fred_ssp2 = msrs[i].data;
4569             break;
4570         case MSR_IA32_FRED_SSP3:
4571             env->fred_ssp3 = msrs[i].data;
4572             break;
4573         case MSR_IA32_FRED_CONFIG:
4574             env->fred_config = msrs[i].data;
4575             break;
4576 #endif
4577         case MSR_IA32_TSC:
4578             env->tsc = msrs[i].data;
4579             break;
4580         case MSR_TSC_AUX:
4581             env->tsc_aux = msrs[i].data;
4582             break;
4583         case MSR_TSC_ADJUST:
4584             env->tsc_adjust = msrs[i].data;
4585             break;
4586         case MSR_IA32_TSCDEADLINE:
4587             env->tsc_deadline = msrs[i].data;
4588             break;
4589         case MSR_VM_HSAVE_PA:
4590             env->vm_hsave = msrs[i].data;
4591             break;
4592         case MSR_KVM_SYSTEM_TIME:
4593             env->system_time_msr = msrs[i].data;
4594             break;
4595         case MSR_KVM_WALL_CLOCK:
4596             env->wall_clock_msr = msrs[i].data;
4597             break;
4598         case MSR_MCG_STATUS:
4599             env->mcg_status = msrs[i].data;
4600             break;
4601         case MSR_MCG_CTL:
4602             env->mcg_ctl = msrs[i].data;
4603             break;
4604         case MSR_MCG_EXT_CTL:
4605             env->mcg_ext_ctl = msrs[i].data;
4606             break;
4607         case MSR_IA32_MISC_ENABLE:
4608             env->msr_ia32_misc_enable = msrs[i].data;
4609             break;
4610         case MSR_IA32_SMBASE:
4611             env->smbase = msrs[i].data;
4612             break;
4613         case MSR_SMI_COUNT:
4614             env->msr_smi_count = msrs[i].data;
4615             break;
4616         case MSR_IA32_FEATURE_CONTROL:
4617             env->msr_ia32_feature_control = msrs[i].data;
4618             break;
4619         case MSR_IA32_BNDCFGS:
4620             env->msr_bndcfgs = msrs[i].data;
4621             break;
4622         case MSR_IA32_XSS:
4623             env->xss = msrs[i].data;
4624             break;
4625         case MSR_IA32_UMWAIT_CONTROL:
4626             env->umwait = msrs[i].data;
4627             break;
4628         case MSR_IA32_PKRS:
4629             env->pkrs = msrs[i].data;
4630             break;
4631         default:
4632             if (msrs[i].index >= MSR_MC0_CTL &&
4633                 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
4634                 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
4635             }
4636             break;
4637         case MSR_KVM_ASYNC_PF_EN:
4638             env->async_pf_en_msr = msrs[i].data;
4639             break;
4640         case MSR_KVM_ASYNC_PF_INT:
4641             env->async_pf_int_msr = msrs[i].data;
4642             break;
4643         case MSR_KVM_PV_EOI_EN:
4644             env->pv_eoi_en_msr = msrs[i].data;
4645             break;
4646         case MSR_KVM_STEAL_TIME:
4647             env->steal_time_msr = msrs[i].data;
4648             break;
4649         case MSR_KVM_POLL_CONTROL: {
4650             env->poll_control_msr = msrs[i].data;
4651             break;
4652         }
4653         case MSR_CORE_PERF_FIXED_CTR_CTRL:
4654             env->msr_fixed_ctr_ctrl = msrs[i].data;
4655             break;
4656         case MSR_CORE_PERF_GLOBAL_CTRL:
4657             env->msr_global_ctrl = msrs[i].data;
4658             break;
4659         case MSR_CORE_PERF_GLOBAL_STATUS:
4660             env->msr_global_status = msrs[i].data;
4661             break;
4662         case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
4663             env->msr_global_ovf_ctrl = msrs[i].data;
4664             break;
4665         case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
4666             env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
4667             break;
4668         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
4669             env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
4670             break;
4671         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
4672             env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
4673             break;
4674         case HV_X64_MSR_HYPERCALL:
4675             env->msr_hv_hypercall = msrs[i].data;
4676             break;
4677         case HV_X64_MSR_GUEST_OS_ID:
4678             env->msr_hv_guest_os_id = msrs[i].data;
4679             break;
4680         case HV_X64_MSR_APIC_ASSIST_PAGE:
4681             env->msr_hv_vapic = msrs[i].data;
4682             break;
4683         case HV_X64_MSR_REFERENCE_TSC:
4684             env->msr_hv_tsc = msrs[i].data;
4685             break;
4686         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4687             env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
4688             break;
4689         case HV_X64_MSR_VP_RUNTIME:
4690             env->msr_hv_runtime = msrs[i].data;
4691             break;
4692         case HV_X64_MSR_SCONTROL:
4693             env->msr_hv_synic_control = msrs[i].data;
4694             break;
4695         case HV_X64_MSR_SIEFP:
4696             env->msr_hv_synic_evt_page = msrs[i].data;
4697             break;
4698         case HV_X64_MSR_SIMP:
4699             env->msr_hv_synic_msg_page = msrs[i].data;
4700             break;
4701         case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
4702             env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
4703             break;
4704         case HV_X64_MSR_STIMER0_CONFIG:
4705         case HV_X64_MSR_STIMER1_CONFIG:
4706         case HV_X64_MSR_STIMER2_CONFIG:
4707         case HV_X64_MSR_STIMER3_CONFIG:
4708             env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
4709                                 msrs[i].data;
4710             break;
4711         case HV_X64_MSR_STIMER0_COUNT:
4712         case HV_X64_MSR_STIMER1_COUNT:
4713         case HV_X64_MSR_STIMER2_COUNT:
4714         case HV_X64_MSR_STIMER3_COUNT:
4715             env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
4716                                 msrs[i].data;
4717             break;
4718         case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4719             env->msr_hv_reenlightenment_control = msrs[i].data;
4720             break;
4721         case HV_X64_MSR_TSC_EMULATION_CONTROL:
4722             env->msr_hv_tsc_emulation_control = msrs[i].data;
4723             break;
4724         case HV_X64_MSR_TSC_EMULATION_STATUS:
4725             env->msr_hv_tsc_emulation_status = msrs[i].data;
4726             break;
4727         case HV_X64_MSR_SYNDBG_OPTIONS:
4728             env->msr_hv_syndbg_options = msrs[i].data;
4729             break;
4730         case MSR_MTRRdefType:
4731             env->mtrr_deftype = msrs[i].data;
4732             break;
4733         case MSR_MTRRfix64K_00000:
4734             env->mtrr_fixed[0] = msrs[i].data;
4735             break;
4736         case MSR_MTRRfix16K_80000:
4737             env->mtrr_fixed[1] = msrs[i].data;
4738             break;
4739         case MSR_MTRRfix16K_A0000:
4740             env->mtrr_fixed[2] = msrs[i].data;
4741             break;
4742         case MSR_MTRRfix4K_C0000:
4743             env->mtrr_fixed[3] = msrs[i].data;
4744             break;
4745         case MSR_MTRRfix4K_C8000:
4746             env->mtrr_fixed[4] = msrs[i].data;
4747             break;
4748         case MSR_MTRRfix4K_D0000:
4749             env->mtrr_fixed[5] = msrs[i].data;
4750             break;
4751         case MSR_MTRRfix4K_D8000:
4752             env->mtrr_fixed[6] = msrs[i].data;
4753             break;
4754         case MSR_MTRRfix4K_E0000:
4755             env->mtrr_fixed[7] = msrs[i].data;
4756             break;
4757         case MSR_MTRRfix4K_E8000:
4758             env->mtrr_fixed[8] = msrs[i].data;
4759             break;
4760         case MSR_MTRRfix4K_F0000:
4761             env->mtrr_fixed[9] = msrs[i].data;
4762             break;
4763         case MSR_MTRRfix4K_F8000:
4764             env->mtrr_fixed[10] = msrs[i].data;
4765             break;
4766         case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
4767             if (index & 1) {
4768                 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
4769                                                                mtrr_top_bits;
4770             } else {
4771                 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
4772             }
4773             break;
4774         case MSR_IA32_SPEC_CTRL:
4775             env->spec_ctrl = msrs[i].data;
4776             break;
4777         case MSR_AMD64_TSC_RATIO:
4778             env->amd_tsc_scale_msr = msrs[i].data;
4779             break;
4780         case MSR_IA32_TSX_CTRL:
4781             env->tsx_ctrl = msrs[i].data;
4782             break;
4783         case MSR_VIRT_SSBD:
4784             env->virt_ssbd = msrs[i].data;
4785             break;
4786         case MSR_IA32_RTIT_CTL:
4787             env->msr_rtit_ctrl = msrs[i].data;
4788             break;
4789         case MSR_IA32_RTIT_STATUS:
4790             env->msr_rtit_status = msrs[i].data;
4791             break;
4792         case MSR_IA32_RTIT_OUTPUT_BASE:
4793             env->msr_rtit_output_base = msrs[i].data;
4794             break;
4795         case MSR_IA32_RTIT_OUTPUT_MASK:
4796             env->msr_rtit_output_mask = msrs[i].data;
4797             break;
4798         case MSR_IA32_RTIT_CR3_MATCH:
4799             env->msr_rtit_cr3_match = msrs[i].data;
4800             break;
4801         case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
4802             env->msr_rtit_addrs[index - MSR_IA32_RTIT_ADDR0_A] = msrs[i].data;
4803             break;
4804         case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
4805             env->msr_ia32_sgxlepubkeyhash[index - MSR_IA32_SGXLEPUBKEYHASH0] =
4806                            msrs[i].data;
4807             break;
4808         case MSR_IA32_XFD:
4809             env->msr_xfd = msrs[i].data;
4810             break;
4811         case MSR_IA32_XFD_ERR:
4812             env->msr_xfd_err = msrs[i].data;
4813             break;
4814         case MSR_ARCH_LBR_CTL:
4815             env->msr_lbr_ctl = msrs[i].data;
4816             break;
4817         case MSR_ARCH_LBR_DEPTH:
4818             env->msr_lbr_depth = msrs[i].data;
4819             break;
4820         case MSR_ARCH_LBR_FROM_0 ... MSR_ARCH_LBR_FROM_0 + 31:
4821             env->lbr_records[index - MSR_ARCH_LBR_FROM_0].from = msrs[i].data;
4822             break;
4823         case MSR_ARCH_LBR_TO_0 ... MSR_ARCH_LBR_TO_0 + 31:
4824             env->lbr_records[index - MSR_ARCH_LBR_TO_0].to = msrs[i].data;
4825             break;
4826         case MSR_ARCH_LBR_INFO_0 ... MSR_ARCH_LBR_INFO_0 + 31:
4827             env->lbr_records[index - MSR_ARCH_LBR_INFO_0].info = msrs[i].data;
4828             break;
4829         }
4830     }
4831 
4832     return 0;
4833 }
4834 
4835 static int kvm_put_mp_state(X86CPU *cpu)
4836 {
4837     struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
4838 
4839     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
4840 }
4841 
4842 static int kvm_get_mp_state(X86CPU *cpu)
4843 {
4844     CPUState *cs = CPU(cpu);
4845     CPUX86State *env = &cpu->env;
4846     struct kvm_mp_state mp_state;
4847     int ret;
4848 
4849     ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
4850     if (ret < 0) {
4851         return ret;
4852     }
4853     env->mp_state = mp_state.mp_state;
4854     if (kvm_irqchip_in_kernel()) {
4855         cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
4856     }
4857     return 0;
4858 }
4859 
4860 static int kvm_get_apic(X86CPU *cpu)
4861 {
4862     DeviceState *apic = cpu->apic_state;
4863     struct kvm_lapic_state kapic;
4864     int ret;
4865 
4866     if (apic && kvm_irqchip_in_kernel()) {
4867         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
4868         if (ret < 0) {
4869             return ret;
4870         }
4871 
4872         kvm_get_apic_state(apic, &kapic);
4873     }
4874     return 0;
4875 }
4876 
4877 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
4878 {
4879     CPUState *cs = CPU(cpu);
4880     CPUX86State *env = &cpu->env;
4881     struct kvm_vcpu_events events = {};
4882 
4883     events.flags = 0;
4884 
4885     if (has_exception_payload) {
4886         events.flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
4887         events.exception.pending = env->exception_pending;
4888         events.exception_has_payload = env->exception_has_payload;
4889         events.exception_payload = env->exception_payload;
4890     }
4891     events.exception.nr = env->exception_nr;
4892     events.exception.injected = env->exception_injected;
4893     events.exception.has_error_code = env->has_error_code;
4894     events.exception.error_code = env->error_code;
4895 
4896     events.interrupt.injected = (env->interrupt_injected >= 0);
4897     events.interrupt.nr = env->interrupt_injected;
4898     events.interrupt.soft = env->soft_interrupt;
4899 
4900     events.nmi.injected = env->nmi_injected;
4901     events.nmi.pending = env->nmi_pending;
4902     events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
4903 
4904     events.sipi_vector = env->sipi_vector;
4905 
4906     if (has_msr_smbase) {
4907         events.flags |= KVM_VCPUEVENT_VALID_SMM;
4908         events.smi.smm = !!(env->hflags & HF_SMM_MASK);
4909         events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
4910         if (kvm_irqchip_in_kernel()) {
4911             /* As soon as these are moved to the kernel, remove them
4912              * from cs->interrupt_request.
4913              */
4914             events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
4915             events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
4916             cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
4917         } else {
4918             /* Keep these in cs->interrupt_request.  */
4919             events.smi.pending = 0;
4920             events.smi.latched_init = 0;
4921         }
4922     }
4923 
4924     if (level >= KVM_PUT_RESET_STATE) {
4925         events.flags |= KVM_VCPUEVENT_VALID_NMI_PENDING;
4926         if (env->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
4927             events.flags |= KVM_VCPUEVENT_VALID_SIPI_VECTOR;
4928         }
4929     }
4930 
4931     if (has_triple_fault_event) {
4932         events.flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
4933         events.triple_fault.pending = env->triple_fault_pending;
4934     }
4935 
4936     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
4937 }
4938 
4939 static int kvm_get_vcpu_events(X86CPU *cpu)
4940 {
4941     CPUX86State *env = &cpu->env;
4942     struct kvm_vcpu_events events;
4943     int ret;
4944 
4945     memset(&events, 0, sizeof(events));
4946     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
4947     if (ret < 0) {
4948        return ret;
4949     }
4950 
4951     if (events.flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4952         env->exception_pending = events.exception.pending;
4953         env->exception_has_payload = events.exception_has_payload;
4954         env->exception_payload = events.exception_payload;
4955     } else {
4956         env->exception_pending = 0;
4957         env->exception_has_payload = false;
4958     }
4959     env->exception_injected = events.exception.injected;
4960     env->exception_nr =
4961         (env->exception_pending || env->exception_injected) ?
4962         events.exception.nr : -1;
4963     env->has_error_code = events.exception.has_error_code;
4964     env->error_code = events.exception.error_code;
4965 
4966     env->interrupt_injected =
4967         events.interrupt.injected ? events.interrupt.nr : -1;
4968     env->soft_interrupt = events.interrupt.soft;
4969 
4970     env->nmi_injected = events.nmi.injected;
4971     env->nmi_pending = events.nmi.pending;
4972     if (events.nmi.masked) {
4973         env->hflags2 |= HF2_NMI_MASK;
4974     } else {
4975         env->hflags2 &= ~HF2_NMI_MASK;
4976     }
4977 
4978     if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
4979         if (events.smi.smm) {
4980             env->hflags |= HF_SMM_MASK;
4981         } else {
4982             env->hflags &= ~HF_SMM_MASK;
4983         }
4984         if (events.smi.pending) {
4985             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
4986         } else {
4987             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
4988         }
4989         if (events.smi.smm_inside_nmi) {
4990             env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
4991         } else {
4992             env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
4993         }
4994         if (events.smi.latched_init) {
4995             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
4996         } else {
4997             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
4998         }
4999     }
5000 
5001     if (events.flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
5002         env->triple_fault_pending = events.triple_fault.pending;
5003     }
5004 
5005     env->sipi_vector = events.sipi_vector;
5006 
5007     return 0;
5008 }
5009 
5010 static int kvm_put_debugregs(X86CPU *cpu)
5011 {
5012     CPUX86State *env = &cpu->env;
5013     struct kvm_debugregs dbgregs;
5014     int i;
5015 
5016     memset(&dbgregs, 0, sizeof(dbgregs));
5017     for (i = 0; i < 4; i++) {
5018         dbgregs.db[i] = env->dr[i];
5019     }
5020     dbgregs.dr6 = env->dr[6];
5021     dbgregs.dr7 = env->dr[7];
5022     dbgregs.flags = 0;
5023 
5024     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
5025 }
5026 
5027 static int kvm_get_debugregs(X86CPU *cpu)
5028 {
5029     CPUX86State *env = &cpu->env;
5030     struct kvm_debugregs dbgregs;
5031     int i, ret;
5032 
5033     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
5034     if (ret < 0) {
5035         return ret;
5036     }
5037     for (i = 0; i < 4; i++) {
5038         env->dr[i] = dbgregs.db[i];
5039     }
5040     env->dr[4] = env->dr[6] = dbgregs.dr6;
5041     env->dr[5] = env->dr[7] = dbgregs.dr7;
5042 
5043     return 0;
5044 }
5045 
5046 static int kvm_put_nested_state(X86CPU *cpu)
5047 {
5048     CPUX86State *env = &cpu->env;
5049     int max_nested_state_len = kvm_max_nested_state_length();
5050 
5051     if (!env->nested_state) {
5052         return 0;
5053     }
5054 
5055     /*
5056      * Copy flags that are affected by reset from env->hflags and env->hflags2.
5057      */
5058     if (env->hflags & HF_GUEST_MASK) {
5059         env->nested_state->flags |= KVM_STATE_NESTED_GUEST_MODE;
5060     } else {
5061         env->nested_state->flags &= ~KVM_STATE_NESTED_GUEST_MODE;
5062     }
5063 
5064     /* Don't set KVM_STATE_NESTED_GIF_SET on VMX as it is illegal */
5065     if (cpu_has_svm(env) && (env->hflags2 & HF2_GIF_MASK)) {
5066         env->nested_state->flags |= KVM_STATE_NESTED_GIF_SET;
5067     } else {
5068         env->nested_state->flags &= ~KVM_STATE_NESTED_GIF_SET;
5069     }
5070 
5071     assert(env->nested_state->size <= max_nested_state_len);
5072     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_NESTED_STATE, env->nested_state);
5073 }
5074 
5075 static int kvm_get_nested_state(X86CPU *cpu)
5076 {
5077     CPUX86State *env = &cpu->env;
5078     int max_nested_state_len = kvm_max_nested_state_length();
5079     int ret;
5080 
5081     if (!env->nested_state) {
5082         return 0;
5083     }
5084 
5085     /*
5086      * It is possible that migration restored a smaller size into
5087      * nested_state->hdr.size than what our kernel support.
5088      * We preserve migration origin nested_state->hdr.size for
5089      * call to KVM_SET_NESTED_STATE but wish that our next call
5090      * to KVM_GET_NESTED_STATE will use max size our kernel support.
5091      */
5092     env->nested_state->size = max_nested_state_len;
5093 
5094     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_NESTED_STATE, env->nested_state);
5095     if (ret < 0) {
5096         return ret;
5097     }
5098 
5099     /*
5100      * Copy flags that are affected by reset to env->hflags and env->hflags2.
5101      */
5102     if (env->nested_state->flags & KVM_STATE_NESTED_GUEST_MODE) {
5103         env->hflags |= HF_GUEST_MASK;
5104     } else {
5105         env->hflags &= ~HF_GUEST_MASK;
5106     }
5107 
5108     /* Keep HF2_GIF_MASK set on !SVM as x86_cpu_pending_interrupt() needs it */
5109     if (cpu_has_svm(env)) {
5110         if (env->nested_state->flags & KVM_STATE_NESTED_GIF_SET) {
5111             env->hflags2 |= HF2_GIF_MASK;
5112         } else {
5113             env->hflags2 &= ~HF2_GIF_MASK;
5114         }
5115     }
5116 
5117     return ret;
5118 }
5119 
5120 int kvm_arch_put_registers(CPUState *cpu, int level)
5121 {
5122     X86CPU *x86_cpu = X86_CPU(cpu);
5123     int ret;
5124 
5125     assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
5126 
5127     /*
5128      * Put MSR_IA32_FEATURE_CONTROL first, this ensures the VM gets out of VMX
5129      * root operation upon vCPU reset. kvm_put_msr_feature_control() should also
5130      * precede kvm_put_nested_state() when 'real' nested state is set.
5131      */
5132     if (level >= KVM_PUT_RESET_STATE) {
5133         ret = kvm_put_msr_feature_control(x86_cpu);
5134         if (ret < 0) {
5135             return ret;
5136         }
5137     }
5138 
5139     /* must be before kvm_put_nested_state so that EFER.SVME is set */
5140     ret = has_sregs2 ? kvm_put_sregs2(x86_cpu) : kvm_put_sregs(x86_cpu);
5141     if (ret < 0) {
5142         return ret;
5143     }
5144 
5145     if (level >= KVM_PUT_RESET_STATE) {
5146         ret = kvm_put_nested_state(x86_cpu);
5147         if (ret < 0) {
5148             return ret;
5149         }
5150     }
5151 
5152     if (level == KVM_PUT_FULL_STATE) {
5153         /* We don't check for kvm_arch_set_tsc_khz() errors here,
5154          * because TSC frequency mismatch shouldn't abort migration,
5155          * unless the user explicitly asked for a more strict TSC
5156          * setting (e.g. using an explicit "tsc-freq" option).
5157          */
5158         kvm_arch_set_tsc_khz(cpu);
5159     }
5160 
5161 #ifdef CONFIG_XEN_EMU
5162     if (xen_mode == XEN_EMULATE && level == KVM_PUT_FULL_STATE) {
5163         ret = kvm_put_xen_state(cpu);
5164         if (ret < 0) {
5165             return ret;
5166         }
5167     }
5168 #endif
5169 
5170     ret = kvm_getput_regs(x86_cpu, 1);
5171     if (ret < 0) {
5172         return ret;
5173     }
5174     ret = kvm_put_xsave(x86_cpu);
5175     if (ret < 0) {
5176         return ret;
5177     }
5178     ret = kvm_put_xcrs(x86_cpu);
5179     if (ret < 0) {
5180         return ret;
5181     }
5182     ret = kvm_put_msrs(x86_cpu, level);
5183     if (ret < 0) {
5184         return ret;
5185     }
5186     ret = kvm_put_vcpu_events(x86_cpu, level);
5187     if (ret < 0) {
5188         return ret;
5189     }
5190     if (level >= KVM_PUT_RESET_STATE) {
5191         ret = kvm_put_mp_state(x86_cpu);
5192         if (ret < 0) {
5193             return ret;
5194         }
5195     }
5196 
5197     ret = kvm_put_tscdeadline_msr(x86_cpu);
5198     if (ret < 0) {
5199         return ret;
5200     }
5201     ret = kvm_put_debugregs(x86_cpu);
5202     if (ret < 0) {
5203         return ret;
5204     }
5205     return 0;
5206 }
5207 
5208 int kvm_arch_get_registers(CPUState *cs)
5209 {
5210     X86CPU *cpu = X86_CPU(cs);
5211     int ret;
5212 
5213     assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
5214 
5215     ret = kvm_get_vcpu_events(cpu);
5216     if (ret < 0) {
5217         goto out;
5218     }
5219     /*
5220      * KVM_GET_MPSTATE can modify CS and RIP, call it before
5221      * KVM_GET_REGS and KVM_GET_SREGS.
5222      */
5223     ret = kvm_get_mp_state(cpu);
5224     if (ret < 0) {
5225         goto out;
5226     }
5227     ret = kvm_getput_regs(cpu, 0);
5228     if (ret < 0) {
5229         goto out;
5230     }
5231     ret = kvm_get_xsave(cpu);
5232     if (ret < 0) {
5233         goto out;
5234     }
5235     ret = kvm_get_xcrs(cpu);
5236     if (ret < 0) {
5237         goto out;
5238     }
5239     ret = has_sregs2 ? kvm_get_sregs2(cpu) : kvm_get_sregs(cpu);
5240     if (ret < 0) {
5241         goto out;
5242     }
5243     ret = kvm_get_msrs(cpu);
5244     if (ret < 0) {
5245         goto out;
5246     }
5247     ret = kvm_get_apic(cpu);
5248     if (ret < 0) {
5249         goto out;
5250     }
5251     ret = kvm_get_debugregs(cpu);
5252     if (ret < 0) {
5253         goto out;
5254     }
5255     ret = kvm_get_nested_state(cpu);
5256     if (ret < 0) {
5257         goto out;
5258     }
5259 #ifdef CONFIG_XEN_EMU
5260     if (xen_mode == XEN_EMULATE) {
5261         ret = kvm_get_xen_state(cs);
5262         if (ret < 0) {
5263             goto out;
5264         }
5265     }
5266 #endif
5267     ret = 0;
5268  out:
5269     cpu_sync_bndcs_hflags(&cpu->env);
5270     return ret;
5271 }
5272 
5273 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
5274 {
5275     X86CPU *x86_cpu = X86_CPU(cpu);
5276     CPUX86State *env = &x86_cpu->env;
5277     int ret;
5278 
5279     /* Inject NMI */
5280     if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
5281         if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
5282             bql_lock();
5283             cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
5284             bql_unlock();
5285             DPRINTF("injected NMI\n");
5286             ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
5287             if (ret < 0) {
5288                 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
5289                         strerror(-ret));
5290             }
5291         }
5292         if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
5293             bql_lock();
5294             cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
5295             bql_unlock();
5296             DPRINTF("injected SMI\n");
5297             ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
5298             if (ret < 0) {
5299                 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
5300                         strerror(-ret));
5301             }
5302         }
5303     }
5304 
5305     if (!kvm_pic_in_kernel()) {
5306         bql_lock();
5307     }
5308 
5309     /* Force the VCPU out of its inner loop to process any INIT requests
5310      * or (for userspace APIC, but it is cheap to combine the checks here)
5311      * pending TPR access reports.
5312      */
5313     if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
5314         if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
5315             !(env->hflags & HF_SMM_MASK)) {
5316             cpu->exit_request = 1;
5317         }
5318         if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
5319             cpu->exit_request = 1;
5320         }
5321     }
5322 
5323     if (!kvm_pic_in_kernel()) {
5324         /* Try to inject an interrupt if the guest can accept it */
5325         if (run->ready_for_interrupt_injection &&
5326             (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
5327             (env->eflags & IF_MASK)) {
5328             int irq;
5329 
5330             cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
5331             irq = cpu_get_pic_interrupt(env);
5332             if (irq >= 0) {
5333                 struct kvm_interrupt intr;
5334 
5335                 intr.irq = irq;
5336                 DPRINTF("injected interrupt %d\n", irq);
5337                 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
5338                 if (ret < 0) {
5339                     fprintf(stderr,
5340                             "KVM: injection failed, interrupt lost (%s)\n",
5341                             strerror(-ret));
5342                 }
5343             }
5344         }
5345 
5346         /* If we have an interrupt but the guest is not ready to receive an
5347          * interrupt, request an interrupt window exit.  This will
5348          * cause a return to userspace as soon as the guest is ready to
5349          * receive interrupts. */
5350         if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
5351             run->request_interrupt_window = 1;
5352         } else {
5353             run->request_interrupt_window = 0;
5354         }
5355 
5356         DPRINTF("setting tpr\n");
5357         run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
5358 
5359         bql_unlock();
5360     }
5361 }
5362 
5363 static void kvm_rate_limit_on_bus_lock(void)
5364 {
5365     uint64_t delay_ns = ratelimit_calculate_delay(&bus_lock_ratelimit_ctrl, 1);
5366 
5367     if (delay_ns) {
5368         g_usleep(delay_ns / SCALE_US);
5369     }
5370 }
5371 
5372 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
5373 {
5374     X86CPU *x86_cpu = X86_CPU(cpu);
5375     CPUX86State *env = &x86_cpu->env;
5376 
5377     if (run->flags & KVM_RUN_X86_SMM) {
5378         env->hflags |= HF_SMM_MASK;
5379     } else {
5380         env->hflags &= ~HF_SMM_MASK;
5381     }
5382     if (run->if_flag) {
5383         env->eflags |= IF_MASK;
5384     } else {
5385         env->eflags &= ~IF_MASK;
5386     }
5387     if (run->flags & KVM_RUN_X86_BUS_LOCK) {
5388         kvm_rate_limit_on_bus_lock();
5389     }
5390 
5391 #ifdef CONFIG_XEN_EMU
5392     /*
5393      * If the callback is asserted as a GSI (or PCI INTx) then check if
5394      * vcpu_info->evtchn_upcall_pending has been cleared, and deassert
5395      * the callback IRQ if so. Ideally we could hook into the PIC/IOAPIC
5396      * EOI and only resample then, exactly how the VFIO eventfd pairs
5397      * are designed to work for level triggered interrupts.
5398      */
5399     if (x86_cpu->env.xen_callback_asserted) {
5400         kvm_xen_maybe_deassert_callback(cpu);
5401     }
5402 #endif
5403 
5404     /* We need to protect the apic state against concurrent accesses from
5405      * different threads in case the userspace irqchip is used. */
5406     if (!kvm_irqchip_in_kernel()) {
5407         bql_lock();
5408     }
5409     cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
5410     cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
5411     if (!kvm_irqchip_in_kernel()) {
5412         bql_unlock();
5413     }
5414     return cpu_get_mem_attrs(env);
5415 }
5416 
5417 int kvm_arch_process_async_events(CPUState *cs)
5418 {
5419     X86CPU *cpu = X86_CPU(cs);
5420     CPUX86State *env = &cpu->env;
5421 
5422     if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
5423         /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
5424         assert(env->mcg_cap);
5425 
5426         cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
5427 
5428         kvm_cpu_synchronize_state(cs);
5429 
5430         if (env->exception_nr == EXCP08_DBLE) {
5431             /* this means triple fault */
5432             qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
5433             cs->exit_request = 1;
5434             return 0;
5435         }
5436         kvm_queue_exception(env, EXCP12_MCHK, 0, 0);
5437         env->has_error_code = 0;
5438 
5439         cs->halted = 0;
5440         if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
5441             env->mp_state = KVM_MP_STATE_RUNNABLE;
5442         }
5443     }
5444 
5445     if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
5446         !(env->hflags & HF_SMM_MASK)) {
5447         kvm_cpu_synchronize_state(cs);
5448         do_cpu_init(cpu);
5449     }
5450 
5451     if (kvm_irqchip_in_kernel()) {
5452         return 0;
5453     }
5454 
5455     if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
5456         cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
5457         apic_poll_irq(cpu->apic_state);
5458     }
5459     if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
5460          (env->eflags & IF_MASK)) ||
5461         (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
5462         cs->halted = 0;
5463     }
5464     if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
5465         kvm_cpu_synchronize_state(cs);
5466         do_cpu_sipi(cpu);
5467     }
5468     if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
5469         cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
5470         kvm_cpu_synchronize_state(cs);
5471         apic_handle_tpr_access_report(cpu->apic_state, env->eip,
5472                                       env->tpr_access_type);
5473     }
5474 
5475     return cs->halted;
5476 }
5477 
5478 static int kvm_handle_halt(X86CPU *cpu)
5479 {
5480     CPUState *cs = CPU(cpu);
5481     CPUX86State *env = &cpu->env;
5482 
5483     if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
5484           (env->eflags & IF_MASK)) &&
5485         !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
5486         cs->halted = 1;
5487         return EXCP_HLT;
5488     }
5489 
5490     return 0;
5491 }
5492 
5493 static int kvm_handle_tpr_access(X86CPU *cpu)
5494 {
5495     CPUState *cs = CPU(cpu);
5496     struct kvm_run *run = cs->kvm_run;
5497 
5498     apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
5499                                   run->tpr_access.is_write ? TPR_ACCESS_WRITE
5500                                                            : TPR_ACCESS_READ);
5501     return 1;
5502 }
5503 
5504 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
5505 {
5506     static const uint8_t int3 = 0xcc;
5507 
5508     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
5509         cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
5510         return -EINVAL;
5511     }
5512     return 0;
5513 }
5514 
5515 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
5516 {
5517     uint8_t int3;
5518 
5519     if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0)) {
5520         return -EINVAL;
5521     }
5522     if (int3 != 0xcc) {
5523         return 0;
5524     }
5525     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
5526         return -EINVAL;
5527     }
5528     return 0;
5529 }
5530 
5531 static struct {
5532     target_ulong addr;
5533     int len;
5534     int type;
5535 } hw_breakpoint[4];
5536 
5537 static int nb_hw_breakpoint;
5538 
5539 static int find_hw_breakpoint(target_ulong addr, int len, int type)
5540 {
5541     int n;
5542 
5543     for (n = 0; n < nb_hw_breakpoint; n++) {
5544         if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
5545             (hw_breakpoint[n].len == len || len == -1)) {
5546             return n;
5547         }
5548     }
5549     return -1;
5550 }
5551 
5552 int kvm_arch_insert_hw_breakpoint(vaddr addr, vaddr len, int type)
5553 {
5554     switch (type) {
5555     case GDB_BREAKPOINT_HW:
5556         len = 1;
5557         break;
5558     case GDB_WATCHPOINT_WRITE:
5559     case GDB_WATCHPOINT_ACCESS:
5560         switch (len) {
5561         case 1:
5562             break;
5563         case 2:
5564         case 4:
5565         case 8:
5566             if (addr & (len - 1)) {
5567                 return -EINVAL;
5568             }
5569             break;
5570         default:
5571             return -EINVAL;
5572         }
5573         break;
5574     default:
5575         return -ENOSYS;
5576     }
5577 
5578     if (nb_hw_breakpoint == 4) {
5579         return -ENOBUFS;
5580     }
5581     if (find_hw_breakpoint(addr, len, type) >= 0) {
5582         return -EEXIST;
5583     }
5584     hw_breakpoint[nb_hw_breakpoint].addr = addr;
5585     hw_breakpoint[nb_hw_breakpoint].len = len;
5586     hw_breakpoint[nb_hw_breakpoint].type = type;
5587     nb_hw_breakpoint++;
5588 
5589     return 0;
5590 }
5591 
5592 int kvm_arch_remove_hw_breakpoint(vaddr addr, vaddr len, int type)
5593 {
5594     int n;
5595 
5596     n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
5597     if (n < 0) {
5598         return -ENOENT;
5599     }
5600     nb_hw_breakpoint--;
5601     hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
5602 
5603     return 0;
5604 }
5605 
5606 void kvm_arch_remove_all_hw_breakpoints(void)
5607 {
5608     nb_hw_breakpoint = 0;
5609 }
5610 
5611 static CPUWatchpoint hw_watchpoint;
5612 
5613 static int kvm_handle_debug(X86CPU *cpu,
5614                             struct kvm_debug_exit_arch *arch_info)
5615 {
5616     CPUState *cs = CPU(cpu);
5617     CPUX86State *env = &cpu->env;
5618     int ret = 0;
5619     int n;
5620 
5621     if (arch_info->exception == EXCP01_DB) {
5622         if (arch_info->dr6 & DR6_BS) {
5623             if (cs->singlestep_enabled) {
5624                 ret = EXCP_DEBUG;
5625             }
5626         } else {
5627             for (n = 0; n < 4; n++) {
5628                 if (arch_info->dr6 & (1 << n)) {
5629                     switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
5630                     case 0x0:
5631                         ret = EXCP_DEBUG;
5632                         break;
5633                     case 0x1:
5634                         ret = EXCP_DEBUG;
5635                         cs->watchpoint_hit = &hw_watchpoint;
5636                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
5637                         hw_watchpoint.flags = BP_MEM_WRITE;
5638                         break;
5639                     case 0x3:
5640                         ret = EXCP_DEBUG;
5641                         cs->watchpoint_hit = &hw_watchpoint;
5642                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
5643                         hw_watchpoint.flags = BP_MEM_ACCESS;
5644                         break;
5645                     }
5646                 }
5647             }
5648         }
5649     } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
5650         ret = EXCP_DEBUG;
5651     }
5652     if (ret == 0) {
5653         cpu_synchronize_state(cs);
5654         assert(env->exception_nr == -1);
5655 
5656         /* pass to guest */
5657         kvm_queue_exception(env, arch_info->exception,
5658                             arch_info->exception == EXCP01_DB,
5659                             arch_info->dr6);
5660         env->has_error_code = 0;
5661     }
5662 
5663     return ret;
5664 }
5665 
5666 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
5667 {
5668     const uint8_t type_code[] = {
5669         [GDB_BREAKPOINT_HW] = 0x0,
5670         [GDB_WATCHPOINT_WRITE] = 0x1,
5671         [GDB_WATCHPOINT_ACCESS] = 0x3
5672     };
5673     const uint8_t len_code[] = {
5674         [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
5675     };
5676     int n;
5677 
5678     if (kvm_sw_breakpoints_active(cpu)) {
5679         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
5680     }
5681     if (nb_hw_breakpoint > 0) {
5682         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
5683         dbg->arch.debugreg[7] = 0x0600;
5684         for (n = 0; n < nb_hw_breakpoint; n++) {
5685             dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
5686             dbg->arch.debugreg[7] |= (2 << (n * 2)) |
5687                 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
5688                 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
5689         }
5690     }
5691 }
5692 
5693 static bool kvm_install_msr_filters(KVMState *s)
5694 {
5695     uint64_t zero = 0;
5696     struct kvm_msr_filter filter = {
5697         .flags = KVM_MSR_FILTER_DEFAULT_ALLOW,
5698     };
5699     int r, i, j = 0;
5700 
5701     for (i = 0; i < KVM_MSR_FILTER_MAX_RANGES; i++) {
5702         KVMMSRHandlers *handler = &msr_handlers[i];
5703         if (handler->msr) {
5704             struct kvm_msr_filter_range *range = &filter.ranges[j++];
5705 
5706             *range = (struct kvm_msr_filter_range) {
5707                 .flags = 0,
5708                 .nmsrs = 1,
5709                 .base = handler->msr,
5710                 .bitmap = (__u8 *)&zero,
5711             };
5712 
5713             if (handler->rdmsr) {
5714                 range->flags |= KVM_MSR_FILTER_READ;
5715             }
5716 
5717             if (handler->wrmsr) {
5718                 range->flags |= KVM_MSR_FILTER_WRITE;
5719             }
5720         }
5721     }
5722 
5723     r = kvm_vm_ioctl(s, KVM_X86_SET_MSR_FILTER, &filter);
5724     if (r) {
5725         return false;
5726     }
5727 
5728     return true;
5729 }
5730 
5731 bool kvm_filter_msr(KVMState *s, uint32_t msr, QEMURDMSRHandler *rdmsr,
5732                     QEMUWRMSRHandler *wrmsr)
5733 {
5734     int i;
5735 
5736     for (i = 0; i < ARRAY_SIZE(msr_handlers); i++) {
5737         if (!msr_handlers[i].msr) {
5738             msr_handlers[i] = (KVMMSRHandlers) {
5739                 .msr = msr,
5740                 .rdmsr = rdmsr,
5741                 .wrmsr = wrmsr,
5742             };
5743 
5744             if (!kvm_install_msr_filters(s)) {
5745                 msr_handlers[i] = (KVMMSRHandlers) { };
5746                 return false;
5747             }
5748 
5749             return true;
5750         }
5751     }
5752 
5753     return false;
5754 }
5755 
5756 static int kvm_handle_rdmsr(X86CPU *cpu, struct kvm_run *run)
5757 {
5758     int i;
5759     bool r;
5760 
5761     for (i = 0; i < ARRAY_SIZE(msr_handlers); i++) {
5762         KVMMSRHandlers *handler = &msr_handlers[i];
5763         if (run->msr.index == handler->msr) {
5764             if (handler->rdmsr) {
5765                 r = handler->rdmsr(cpu, handler->msr,
5766                                    (uint64_t *)&run->msr.data);
5767                 run->msr.error = r ? 0 : 1;
5768                 return 0;
5769             }
5770         }
5771     }
5772 
5773     assert(false);
5774 }
5775 
5776 static int kvm_handle_wrmsr(X86CPU *cpu, struct kvm_run *run)
5777 {
5778     int i;
5779     bool r;
5780 
5781     for (i = 0; i < ARRAY_SIZE(msr_handlers); i++) {
5782         KVMMSRHandlers *handler = &msr_handlers[i];
5783         if (run->msr.index == handler->msr) {
5784             if (handler->wrmsr) {
5785                 r = handler->wrmsr(cpu, handler->msr, run->msr.data);
5786                 run->msr.error = r ? 0 : 1;
5787                 return 0;
5788             }
5789         }
5790     }
5791 
5792     assert(false);
5793 }
5794 
5795 static bool has_sgx_provisioning;
5796 
5797 static bool __kvm_enable_sgx_provisioning(KVMState *s)
5798 {
5799     int fd, ret;
5800 
5801     if (!kvm_vm_check_extension(s, KVM_CAP_SGX_ATTRIBUTE)) {
5802         return false;
5803     }
5804 
5805     fd = qemu_open_old("/dev/sgx_provision", O_RDONLY);
5806     if (fd < 0) {
5807         return false;
5808     }
5809 
5810     ret = kvm_vm_enable_cap(s, KVM_CAP_SGX_ATTRIBUTE, 0, fd);
5811     if (ret) {
5812         error_report("Could not enable SGX PROVISIONKEY: %s", strerror(-ret));
5813         exit(1);
5814     }
5815     close(fd);
5816     return true;
5817 }
5818 
5819 bool kvm_enable_sgx_provisioning(KVMState *s)
5820 {
5821     return MEMORIZE(__kvm_enable_sgx_provisioning(s), has_sgx_provisioning);
5822 }
5823 
5824 static bool host_supports_vmx(void)
5825 {
5826     uint32_t ecx, unused;
5827 
5828     host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
5829     return ecx & CPUID_EXT_VMX;
5830 }
5831 
5832 /*
5833  * Currently the handling here only supports use of KVM_HC_MAP_GPA_RANGE
5834  * to service guest-initiated memory attribute update requests so that
5835  * KVM_SET_MEMORY_ATTRIBUTES can update whether or not a page should be
5836  * backed by the private memory pool provided by guest_memfd, and as such
5837  * is only applicable to guest_memfd-backed guests (e.g. SNP/TDX).
5838  *
5839  * Other other use-cases for KVM_HC_MAP_GPA_RANGE, such as for SEV live
5840  * migration, are not implemented here currently.
5841  *
5842  * For the guest_memfd use-case, these exits will generally be synthesized
5843  * by KVM based on platform-specific hypercalls, like GHCB requests in the
5844  * case of SEV-SNP, and not issued directly within the guest though the
5845  * KVM_HC_MAP_GPA_RANGE hypercall. So in this case, KVM_HC_MAP_GPA_RANGE is
5846  * not actually advertised to guests via the KVM CPUID feature bit, as
5847  * opposed to SEV live migration where it would be. Since it is unlikely the
5848  * SEV live migration use-case would be useful for guest-memfd backed guests,
5849  * because private/shared page tracking is already provided through other
5850  * means, these 2 use-cases should be treated as being mutually-exclusive.
5851  */
5852 static int kvm_handle_hc_map_gpa_range(struct kvm_run *run)
5853 {
5854     uint64_t gpa, size, attributes;
5855 
5856     if (!machine_require_guest_memfd(current_machine))
5857         return -EINVAL;
5858 
5859     gpa = run->hypercall.args[0];
5860     size = run->hypercall.args[1] * TARGET_PAGE_SIZE;
5861     attributes = run->hypercall.args[2];
5862 
5863     trace_kvm_hc_map_gpa_range(gpa, size, attributes, run->hypercall.flags);
5864 
5865     return kvm_convert_memory(gpa, size, attributes & KVM_MAP_GPA_RANGE_ENCRYPTED);
5866 }
5867 
5868 static int kvm_handle_hypercall(struct kvm_run *run)
5869 {
5870     if (run->hypercall.nr == KVM_HC_MAP_GPA_RANGE)
5871         return kvm_handle_hc_map_gpa_range(run);
5872 
5873     return -EINVAL;
5874 }
5875 
5876 #define VMX_INVALID_GUEST_STATE 0x80000021
5877 
5878 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
5879 {
5880     X86CPU *cpu = X86_CPU(cs);
5881     uint64_t code;
5882     int ret;
5883     bool ctx_invalid;
5884     KVMState *state;
5885 
5886     switch (run->exit_reason) {
5887     case KVM_EXIT_HLT:
5888         DPRINTF("handle_hlt\n");
5889         bql_lock();
5890         ret = kvm_handle_halt(cpu);
5891         bql_unlock();
5892         break;
5893     case KVM_EXIT_SET_TPR:
5894         ret = 0;
5895         break;
5896     case KVM_EXIT_TPR_ACCESS:
5897         bql_lock();
5898         ret = kvm_handle_tpr_access(cpu);
5899         bql_unlock();
5900         break;
5901     case KVM_EXIT_FAIL_ENTRY:
5902         code = run->fail_entry.hardware_entry_failure_reason;
5903         fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
5904                 code);
5905         if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
5906             fprintf(stderr,
5907                     "\nIf you're running a guest on an Intel machine without "
5908                         "unrestricted mode\n"
5909                     "support, the failure can be most likely due to the guest "
5910                         "entering an invalid\n"
5911                     "state for Intel VT. For example, the guest maybe running "
5912                         "in big real mode\n"
5913                     "which is not supported on less recent Intel processors."
5914                         "\n\n");
5915         }
5916         ret = -1;
5917         break;
5918     case KVM_EXIT_EXCEPTION:
5919         fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
5920                 run->ex.exception, run->ex.error_code);
5921         ret = -1;
5922         break;
5923     case KVM_EXIT_DEBUG:
5924         DPRINTF("kvm_exit_debug\n");
5925         bql_lock();
5926         ret = kvm_handle_debug(cpu, &run->debug.arch);
5927         bql_unlock();
5928         break;
5929     case KVM_EXIT_HYPERV:
5930         ret = kvm_hv_handle_exit(cpu, &run->hyperv);
5931         break;
5932     case KVM_EXIT_IOAPIC_EOI:
5933         ioapic_eoi_broadcast(run->eoi.vector);
5934         ret = 0;
5935         break;
5936     case KVM_EXIT_X86_BUS_LOCK:
5937         /* already handled in kvm_arch_post_run */
5938         ret = 0;
5939         break;
5940     case KVM_EXIT_NOTIFY:
5941         ctx_invalid = !!(run->notify.flags & KVM_NOTIFY_CONTEXT_INVALID);
5942         state = KVM_STATE(current_accel());
5943         if (ctx_invalid ||
5944             state->notify_vmexit == NOTIFY_VMEXIT_OPTION_INTERNAL_ERROR) {
5945             warn_report("KVM internal error: Encountered a notify exit "
5946                         "with invalid context in guest.");
5947             ret = -1;
5948         } else {
5949             warn_report_once("KVM: Encountered a notify exit with valid "
5950                              "context in guest. "
5951                              "The guest could be misbehaving.");
5952             ret = 0;
5953         }
5954         break;
5955     case KVM_EXIT_X86_RDMSR:
5956         /* We only enable MSR filtering, any other exit is bogus */
5957         assert(run->msr.reason == KVM_MSR_EXIT_REASON_FILTER);
5958         ret = kvm_handle_rdmsr(cpu, run);
5959         break;
5960     case KVM_EXIT_X86_WRMSR:
5961         /* We only enable MSR filtering, any other exit is bogus */
5962         assert(run->msr.reason == KVM_MSR_EXIT_REASON_FILTER);
5963         ret = kvm_handle_wrmsr(cpu, run);
5964         break;
5965 #ifdef CONFIG_XEN_EMU
5966     case KVM_EXIT_XEN:
5967         ret = kvm_xen_handle_exit(cpu, &run->xen);
5968         break;
5969 #endif
5970     case KVM_EXIT_HYPERCALL:
5971         ret = kvm_handle_hypercall(run);
5972         break;
5973     default:
5974         fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
5975         ret = -1;
5976         break;
5977     }
5978 
5979     return ret;
5980 }
5981 
5982 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
5983 {
5984     X86CPU *cpu = X86_CPU(cs);
5985     CPUX86State *env = &cpu->env;
5986 
5987     kvm_cpu_synchronize_state(cs);
5988     return !(env->cr[0] & CR0_PE_MASK) ||
5989            ((env->segs[R_CS].selector  & 3) != 3);
5990 }
5991 
5992 void kvm_arch_init_irq_routing(KVMState *s)
5993 {
5994     /* We know at this point that we're using the in-kernel
5995      * irqchip, so we can use irqfds, and on x86 we know
5996      * we can use msi via irqfd and GSI routing.
5997      */
5998     kvm_msi_via_irqfd_allowed = true;
5999     kvm_gsi_routing_allowed = true;
6000 
6001     if (kvm_irqchip_is_split()) {
6002         KVMRouteChange c = kvm_irqchip_begin_route_changes(s);
6003         int i;
6004 
6005         /* If the ioapic is in QEMU and the lapics are in KVM, reserve
6006            MSI routes for signaling interrupts to the local apics. */
6007         for (i = 0; i < IOAPIC_NUM_PINS; i++) {
6008             if (kvm_irqchip_add_msi_route(&c, 0, NULL) < 0) {
6009                 error_report("Could not enable split IRQ mode.");
6010                 exit(1);
6011             }
6012         }
6013         kvm_irqchip_commit_route_changes(&c);
6014     }
6015 }
6016 
6017 int kvm_arch_irqchip_create(KVMState *s)
6018 {
6019     int ret;
6020     if (kvm_kernel_irqchip_split()) {
6021         ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
6022         if (ret) {
6023             error_report("Could not enable split irqchip mode: %s",
6024                          strerror(-ret));
6025             exit(1);
6026         } else {
6027             DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
6028             kvm_split_irqchip = true;
6029             return 1;
6030         }
6031     } else {
6032         return 0;
6033     }
6034 }
6035 
6036 uint64_t kvm_swizzle_msi_ext_dest_id(uint64_t address)
6037 {
6038     CPUX86State *env;
6039     uint64_t ext_id;
6040 
6041     if (!first_cpu) {
6042         return address;
6043     }
6044     env = &X86_CPU(first_cpu)->env;
6045     if (!(env->features[FEAT_KVM] & (1 << KVM_FEATURE_MSI_EXT_DEST_ID))) {
6046         return address;
6047     }
6048 
6049     /*
6050      * If the remappable format bit is set, or the upper bits are
6051      * already set in address_hi, or the low extended bits aren't
6052      * there anyway, do nothing.
6053      */
6054     ext_id = address & (0xff << MSI_ADDR_DEST_IDX_SHIFT);
6055     if (!ext_id || (ext_id & (1 << MSI_ADDR_DEST_IDX_SHIFT)) || (address >> 32)) {
6056         return address;
6057     }
6058 
6059     address &= ~ext_id;
6060     address |= ext_id << 35;
6061     return address;
6062 }
6063 
6064 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
6065                              uint64_t address, uint32_t data, PCIDevice *dev)
6066 {
6067     X86IOMMUState *iommu = x86_iommu_get_default();
6068 
6069     if (iommu) {
6070         X86IOMMUClass *class = X86_IOMMU_DEVICE_GET_CLASS(iommu);
6071 
6072         if (class->int_remap) {
6073             int ret;
6074             MSIMessage src, dst;
6075 
6076             src.address = route->u.msi.address_hi;
6077             src.address <<= VTD_MSI_ADDR_HI_SHIFT;
6078             src.address |= route->u.msi.address_lo;
6079             src.data = route->u.msi.data;
6080 
6081             ret = class->int_remap(iommu, &src, &dst, dev ?     \
6082                                    pci_requester_id(dev) :      \
6083                                    X86_IOMMU_SID_INVALID);
6084             if (ret) {
6085                 trace_kvm_x86_fixup_msi_error(route->gsi);
6086                 return 1;
6087             }
6088 
6089             /*
6090              * Handled untranslated compatibility format interrupt with
6091              * extended destination ID in the low bits 11-5. */
6092             dst.address = kvm_swizzle_msi_ext_dest_id(dst.address);
6093 
6094             route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
6095             route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
6096             route->u.msi.data = dst.data;
6097             return 0;
6098         }
6099     }
6100 
6101 #ifdef CONFIG_XEN_EMU
6102     if (xen_mode == XEN_EMULATE) {
6103         int handled = xen_evtchn_translate_pirq_msi(route, address, data);
6104 
6105         /*
6106          * If it was a PIRQ and successfully routed (handled == 0) or it was
6107          * an error (handled < 0), return. If it wasn't a PIRQ, keep going.
6108          */
6109         if (handled <= 0) {
6110             return handled;
6111         }
6112     }
6113 #endif
6114 
6115     address = kvm_swizzle_msi_ext_dest_id(address);
6116     route->u.msi.address_hi = address >> VTD_MSI_ADDR_HI_SHIFT;
6117     route->u.msi.address_lo = address & VTD_MSI_ADDR_LO_MASK;
6118     return 0;
6119 }
6120 
6121 typedef struct MSIRouteEntry MSIRouteEntry;
6122 
6123 struct MSIRouteEntry {
6124     PCIDevice *dev;             /* Device pointer */
6125     int vector;                 /* MSI/MSIX vector index */
6126     int virq;                   /* Virtual IRQ index */
6127     QLIST_ENTRY(MSIRouteEntry) list;
6128 };
6129 
6130 /* List of used GSI routes */
6131 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
6132     QLIST_HEAD_INITIALIZER(msi_route_list);
6133 
6134 void kvm_update_msi_routes_all(void *private, bool global,
6135                                uint32_t index, uint32_t mask)
6136 {
6137     int cnt = 0, vector;
6138     MSIRouteEntry *entry;
6139     MSIMessage msg;
6140     PCIDevice *dev;
6141 
6142     /* TODO: explicit route update */
6143     QLIST_FOREACH(entry, &msi_route_list, list) {
6144         cnt++;
6145         vector = entry->vector;
6146         dev = entry->dev;
6147         if (msix_enabled(dev) && !msix_is_masked(dev, vector)) {
6148             msg = msix_get_message(dev, vector);
6149         } else if (msi_enabled(dev) && !msi_is_masked(dev, vector)) {
6150             msg = msi_get_message(dev, vector);
6151         } else {
6152             /*
6153              * Either MSI/MSIX is disabled for the device, or the
6154              * specific message was masked out.  Skip this one.
6155              */
6156             continue;
6157         }
6158         kvm_irqchip_update_msi_route(kvm_state, entry->virq, msg, dev);
6159     }
6160     kvm_irqchip_commit_routes(kvm_state);
6161     trace_kvm_x86_update_msi_routes(cnt);
6162 }
6163 
6164 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
6165                                 int vector, PCIDevice *dev)
6166 {
6167     static bool notify_list_inited = false;
6168     MSIRouteEntry *entry;
6169 
6170     if (!dev) {
6171         /* These are (possibly) IOAPIC routes only used for split
6172          * kernel irqchip mode, while what we are housekeeping are
6173          * PCI devices only. */
6174         return 0;
6175     }
6176 
6177     entry = g_new0(MSIRouteEntry, 1);
6178     entry->dev = dev;
6179     entry->vector = vector;
6180     entry->virq = route->gsi;
6181     QLIST_INSERT_HEAD(&msi_route_list, entry, list);
6182 
6183     trace_kvm_x86_add_msi_route(route->gsi);
6184 
6185     if (!notify_list_inited) {
6186         /* For the first time we do add route, add ourselves into
6187          * IOMMU's IEC notify list if needed. */
6188         X86IOMMUState *iommu = x86_iommu_get_default();
6189         if (iommu) {
6190             x86_iommu_iec_register_notifier(iommu,
6191                                             kvm_update_msi_routes_all,
6192                                             NULL);
6193         }
6194         notify_list_inited = true;
6195     }
6196     return 0;
6197 }
6198 
6199 int kvm_arch_release_virq_post(int virq)
6200 {
6201     MSIRouteEntry *entry, *next;
6202     QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
6203         if (entry->virq == virq) {
6204             trace_kvm_x86_remove_msi_route(virq);
6205             QLIST_REMOVE(entry, list);
6206             g_free(entry);
6207             break;
6208         }
6209     }
6210     return 0;
6211 }
6212 
6213 int kvm_arch_msi_data_to_gsi(uint32_t data)
6214 {
6215     abort();
6216 }
6217 
6218 bool kvm_has_waitpkg(void)
6219 {
6220     return has_msr_umwait;
6221 }
6222 
6223 #define ARCH_REQ_XCOMP_GUEST_PERM       0x1025
6224 
6225 void kvm_request_xsave_components(X86CPU *cpu, uint64_t mask)
6226 {
6227     KVMState *s = kvm_state;
6228     uint64_t supported;
6229 
6230     mask &= XSTATE_DYNAMIC_MASK;
6231     if (!mask) {
6232         return;
6233     }
6234     /*
6235      * Just ignore bits that are not in CPUID[EAX=0xD,ECX=0].
6236      * ARCH_REQ_XCOMP_GUEST_PERM would fail, and QEMU has warned
6237      * about them already because they are not supported features.
6238      */
6239     supported = kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EAX);
6240     supported |= (uint64_t)kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EDX) << 32;
6241     mask &= supported;
6242 
6243     while (mask) {
6244         int bit = ctz64(mask);
6245         int rc = syscall(SYS_arch_prctl, ARCH_REQ_XCOMP_GUEST_PERM, bit);
6246         if (rc) {
6247             /*
6248              * Older kernel version (<5.17) do not support
6249              * ARCH_REQ_XCOMP_GUEST_PERM, but also do not return
6250              * any dynamic feature from kvm_arch_get_supported_cpuid.
6251              */
6252             warn_report("prctl(ARCH_REQ_XCOMP_GUEST_PERM) failure "
6253                         "for feature bit %d", bit);
6254         }
6255         mask &= ~BIT_ULL(bit);
6256     }
6257 }
6258 
6259 static int kvm_arch_get_notify_vmexit(Object *obj, Error **errp)
6260 {
6261     KVMState *s = KVM_STATE(obj);
6262     return s->notify_vmexit;
6263 }
6264 
6265 static void kvm_arch_set_notify_vmexit(Object *obj, int value, Error **errp)
6266 {
6267     KVMState *s = KVM_STATE(obj);
6268 
6269     if (s->fd != -1) {
6270         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
6271         return;
6272     }
6273 
6274     s->notify_vmexit = value;
6275 }
6276 
6277 static void kvm_arch_get_notify_window(Object *obj, Visitor *v,
6278                                        const char *name, void *opaque,
6279                                        Error **errp)
6280 {
6281     KVMState *s = KVM_STATE(obj);
6282     uint32_t value = s->notify_window;
6283 
6284     visit_type_uint32(v, name, &value, errp);
6285 }
6286 
6287 static void kvm_arch_set_notify_window(Object *obj, Visitor *v,
6288                                        const char *name, void *opaque,
6289                                        Error **errp)
6290 {
6291     KVMState *s = KVM_STATE(obj);
6292     uint32_t value;
6293 
6294     if (s->fd != -1) {
6295         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
6296         return;
6297     }
6298 
6299     if (!visit_type_uint32(v, name, &value, errp)) {
6300         return;
6301     }
6302 
6303     s->notify_window = value;
6304 }
6305 
6306 static void kvm_arch_get_xen_version(Object *obj, Visitor *v,
6307                                      const char *name, void *opaque,
6308                                      Error **errp)
6309 {
6310     KVMState *s = KVM_STATE(obj);
6311     uint32_t value = s->xen_version;
6312 
6313     visit_type_uint32(v, name, &value, errp);
6314 }
6315 
6316 static void kvm_arch_set_xen_version(Object *obj, Visitor *v,
6317                                      const char *name, void *opaque,
6318                                      Error **errp)
6319 {
6320     KVMState *s = KVM_STATE(obj);
6321     Error *error = NULL;
6322     uint32_t value;
6323 
6324     visit_type_uint32(v, name, &value, &error);
6325     if (error) {
6326         error_propagate(errp, error);
6327         return;
6328     }
6329 
6330     s->xen_version = value;
6331     if (value && xen_mode == XEN_DISABLED) {
6332         xen_mode = XEN_EMULATE;
6333     }
6334 }
6335 
6336 static void kvm_arch_get_xen_gnttab_max_frames(Object *obj, Visitor *v,
6337                                                const char *name, void *opaque,
6338                                                Error **errp)
6339 {
6340     KVMState *s = KVM_STATE(obj);
6341     uint16_t value = s->xen_gnttab_max_frames;
6342 
6343     visit_type_uint16(v, name, &value, errp);
6344 }
6345 
6346 static void kvm_arch_set_xen_gnttab_max_frames(Object *obj, Visitor *v,
6347                                                const char *name, void *opaque,
6348                                                Error **errp)
6349 {
6350     KVMState *s = KVM_STATE(obj);
6351     Error *error = NULL;
6352     uint16_t value;
6353 
6354     visit_type_uint16(v, name, &value, &error);
6355     if (error) {
6356         error_propagate(errp, error);
6357         return;
6358     }
6359 
6360     s->xen_gnttab_max_frames = value;
6361 }
6362 
6363 static void kvm_arch_get_xen_evtchn_max_pirq(Object *obj, Visitor *v,
6364                                              const char *name, void *opaque,
6365                                              Error **errp)
6366 {
6367     KVMState *s = KVM_STATE(obj);
6368     uint16_t value = s->xen_evtchn_max_pirq;
6369 
6370     visit_type_uint16(v, name, &value, errp);
6371 }
6372 
6373 static void kvm_arch_set_xen_evtchn_max_pirq(Object *obj, Visitor *v,
6374                                              const char *name, void *opaque,
6375                                              Error **errp)
6376 {
6377     KVMState *s = KVM_STATE(obj);
6378     Error *error = NULL;
6379     uint16_t value;
6380 
6381     visit_type_uint16(v, name, &value, &error);
6382     if (error) {
6383         error_propagate(errp, error);
6384         return;
6385     }
6386 
6387     s->xen_evtchn_max_pirq = value;
6388 }
6389 
6390 void kvm_arch_accel_class_init(ObjectClass *oc)
6391 {
6392     object_class_property_add_enum(oc, "notify-vmexit", "NotifyVMexitOption",
6393                                    &NotifyVmexitOption_lookup,
6394                                    kvm_arch_get_notify_vmexit,
6395                                    kvm_arch_set_notify_vmexit);
6396     object_class_property_set_description(oc, "notify-vmexit",
6397                                           "Enable notify VM exit");
6398 
6399     object_class_property_add(oc, "notify-window", "uint32",
6400                               kvm_arch_get_notify_window,
6401                               kvm_arch_set_notify_window,
6402                               NULL, NULL);
6403     object_class_property_set_description(oc, "notify-window",
6404                                           "Clock cycles without an event window "
6405                                           "after which a notification VM exit occurs");
6406 
6407     object_class_property_add(oc, "xen-version", "uint32",
6408                               kvm_arch_get_xen_version,
6409                               kvm_arch_set_xen_version,
6410                               NULL, NULL);
6411     object_class_property_set_description(oc, "xen-version",
6412                                           "Xen version to be emulated "
6413                                           "(in XENVER_version form "
6414                                           "e.g. 0x4000a for 4.10)");
6415 
6416     object_class_property_add(oc, "xen-gnttab-max-frames", "uint16",
6417                               kvm_arch_get_xen_gnttab_max_frames,
6418                               kvm_arch_set_xen_gnttab_max_frames,
6419                               NULL, NULL);
6420     object_class_property_set_description(oc, "xen-gnttab-max-frames",
6421                                           "Maximum number of grant table frames");
6422 
6423     object_class_property_add(oc, "xen-evtchn-max-pirq", "uint16",
6424                               kvm_arch_get_xen_evtchn_max_pirq,
6425                               kvm_arch_set_xen_evtchn_max_pirq,
6426                               NULL, NULL);
6427     object_class_property_set_description(oc, "xen-evtchn-max-pirq",
6428                                           "Maximum number of Xen PIRQs");
6429 }
6430 
6431 void kvm_set_max_apic_id(uint32_t max_apic_id)
6432 {
6433     kvm_vm_enable_cap(kvm_state, KVM_CAP_MAX_VCPU_ID, 0, max_apic_id);
6434 }
6435