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