xref: /openbmc/qemu/target/i386/kvm/kvm.c (revision 2e1cacfb)
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             uint32_t times;
1928 
1929             c->function = i;
1930             c->index = 0;
1931             c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1932             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1933             times = c->eax;
1934 
1935             for (j = 1; j <= times; ++j) {
1936                 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1937                     goto full;
1938                 }
1939                 c = &entries[cpuid_i++];
1940                 c->function = i;
1941                 c->index = j;
1942                 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1943                 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1944             }
1945             break;
1946         }
1947         default:
1948             c->function = i;
1949             c->flags = 0;
1950             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1951             if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
1952                 /*
1953                  * KVM already returns all zeroes if a CPUID entry is missing,
1954                  * so we can omit it and avoid hitting KVM's 80-entry limit.
1955                  */
1956                 cpuid_i--;
1957             }
1958             break;
1959         }
1960     }
1961 
1962     if (limit >= 0x0a) {
1963         uint32_t eax, edx;
1964 
1965         cpu_x86_cpuid(env, 0x0a, 0, &eax, &unused, &unused, &edx);
1966 
1967         has_architectural_pmu_version = eax & 0xff;
1968         if (has_architectural_pmu_version > 0) {
1969             num_architectural_pmu_gp_counters = (eax & 0xff00) >> 8;
1970 
1971             /* Shouldn't be more than 32, since that's the number of bits
1972              * available in EBX to tell us _which_ counters are available.
1973              * Play it safe.
1974              */
1975             if (num_architectural_pmu_gp_counters > MAX_GP_COUNTERS) {
1976                 num_architectural_pmu_gp_counters = MAX_GP_COUNTERS;
1977             }
1978 
1979             if (has_architectural_pmu_version > 1) {
1980                 num_architectural_pmu_fixed_counters = edx & 0x1f;
1981 
1982                 if (num_architectural_pmu_fixed_counters > MAX_FIXED_COUNTERS) {
1983                     num_architectural_pmu_fixed_counters = MAX_FIXED_COUNTERS;
1984                 }
1985             }
1986         }
1987     }
1988 
1989     cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
1990 
1991     for (i = 0x80000000; i <= limit; i++) {
1992         j = 0;
1993         if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1994             goto full;
1995         }
1996         c = &entries[cpuid_i++];
1997 
1998         switch (i) {
1999         case 0x8000001d:
2000             /* Query for all AMD cache information leaves */
2001             for (j = 0; ; j++) {
2002                 c->function = i;
2003                 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2004                 c->index = j;
2005                 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
2006 
2007                 if (c->eax == 0) {
2008                     break;
2009                 }
2010                 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
2011                     goto full;
2012                 }
2013                 c = &entries[cpuid_i++];
2014             }
2015             break;
2016         default:
2017             c->function = i;
2018             c->flags = 0;
2019             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
2020             if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
2021                 /*
2022                  * KVM already returns all zeroes if a CPUID entry is missing,
2023                  * so we can omit it and avoid hitting KVM's 80-entry limit.
2024                  */
2025                 cpuid_i--;
2026             }
2027             break;
2028         }
2029     }
2030 
2031     /* Call Centaur's CPUID instructions they are supported. */
2032     if (env->cpuid_xlevel2 > 0) {
2033         cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
2034 
2035         for (i = 0xC0000000; i <= limit; i++) {
2036             j = 0;
2037             if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
2038                 goto full;
2039             }
2040             c = &entries[cpuid_i++];
2041 
2042             c->function = i;
2043             c->flags = 0;
2044             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
2045         }
2046     }
2047 
2048     return cpuid_i;
2049 
2050 full:
2051     fprintf(stderr, "cpuid_data is full, no space for "
2052             "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
2053     abort();
2054 }
2055 
2056 int kvm_arch_init_vcpu(CPUState *cs)
2057 {
2058     struct {
2059         struct kvm_cpuid2 cpuid;
2060         struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
2061     } cpuid_data;
2062     /*
2063      * The kernel defines these structs with padding fields so there
2064      * should be no extra padding in our cpuid_data struct.
2065      */
2066     QEMU_BUILD_BUG_ON(sizeof(cpuid_data) !=
2067                       sizeof(struct kvm_cpuid2) +
2068                       sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES);
2069 
2070     X86CPU *cpu = X86_CPU(cs);
2071     CPUX86State *env = &cpu->env;
2072     uint32_t cpuid_i;
2073     struct kvm_cpuid_entry2 *c;
2074     uint32_t signature[3];
2075     int kvm_base = KVM_CPUID_SIGNATURE;
2076     int max_nested_state_len;
2077     int r;
2078     Error *local_err = NULL;
2079 
2080     memset(&cpuid_data, 0, sizeof(cpuid_data));
2081 
2082     cpuid_i = 0;
2083 
2084     has_xsave2 = kvm_check_extension(cs->kvm_state, KVM_CAP_XSAVE2);
2085 
2086     r = kvm_arch_set_tsc_khz(cs);
2087     if (r < 0) {
2088         return r;
2089     }
2090 
2091     /* vcpu's TSC frequency is either specified by user, or following
2092      * the value used by KVM if the former is not present. In the
2093      * latter case, we query it from KVM and record in env->tsc_khz,
2094      * so that vcpu's TSC frequency can be migrated later via this field.
2095      */
2096     if (!env->tsc_khz) {
2097         r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
2098             kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
2099             -ENOTSUP;
2100         if (r > 0) {
2101             env->tsc_khz = r;
2102         }
2103     }
2104 
2105     env->apic_bus_freq = KVM_APIC_BUS_FREQUENCY;
2106 
2107     /*
2108      * kvm_hyperv_expand_features() is called here for the second time in case
2109      * KVM_CAP_SYS_HYPERV_CPUID is not supported. While we can't possibly handle
2110      * 'query-cpu-model-expansion' in this case as we don't have a KVM vCPU to
2111      * check which Hyper-V enlightenments are supported and which are not, we
2112      * can still proceed and check/expand Hyper-V enlightenments here so legacy
2113      * behavior is preserved.
2114      */
2115     if (!kvm_hyperv_expand_features(cpu, &local_err)) {
2116         error_report_err(local_err);
2117         return -ENOSYS;
2118     }
2119 
2120     if (hyperv_enabled(cpu)) {
2121         r = hyperv_init_vcpu(cpu);
2122         if (r) {
2123             return r;
2124         }
2125 
2126         cpuid_i = hyperv_fill_cpuids(cs, cpuid_data.entries);
2127         kvm_base = KVM_CPUID_SIGNATURE_NEXT;
2128         has_msr_hv_hypercall = true;
2129     }
2130 
2131     if (cs->kvm_state->xen_version) {
2132 #ifdef CONFIG_XEN_EMU
2133         struct kvm_cpuid_entry2 *xen_max_leaf;
2134 
2135         memcpy(signature, "XenVMMXenVMM", 12);
2136 
2137         xen_max_leaf = c = &cpuid_data.entries[cpuid_i++];
2138         c->function = kvm_base + XEN_CPUID_SIGNATURE;
2139         c->eax = kvm_base + XEN_CPUID_TIME;
2140         c->ebx = signature[0];
2141         c->ecx = signature[1];
2142         c->edx = signature[2];
2143 
2144         c = &cpuid_data.entries[cpuid_i++];
2145         c->function = kvm_base + XEN_CPUID_VENDOR;
2146         c->eax = cs->kvm_state->xen_version;
2147         c->ebx = 0;
2148         c->ecx = 0;
2149         c->edx = 0;
2150 
2151         c = &cpuid_data.entries[cpuid_i++];
2152         c->function = kvm_base + XEN_CPUID_HVM_MSR;
2153         /* Number of hypercall-transfer pages */
2154         c->eax = 1;
2155         /* Hypercall MSR base address */
2156         if (hyperv_enabled(cpu)) {
2157             c->ebx = XEN_HYPERCALL_MSR_HYPERV;
2158             kvm_xen_init(cs->kvm_state, c->ebx);
2159         } else {
2160             c->ebx = XEN_HYPERCALL_MSR;
2161         }
2162         c->ecx = 0;
2163         c->edx = 0;
2164 
2165         c = &cpuid_data.entries[cpuid_i++];
2166         c->function = kvm_base + XEN_CPUID_TIME;
2167         c->eax = ((!!tsc_is_stable_and_known(env) << 1) |
2168             (!!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP) << 2));
2169         /* default=0 (emulate if necessary) */
2170         c->ebx = 0;
2171         /* guest tsc frequency */
2172         c->ecx = env->user_tsc_khz;
2173         /* guest tsc incarnation (migration count) */
2174         c->edx = 0;
2175 
2176         c = &cpuid_data.entries[cpuid_i++];
2177         c->function = kvm_base + XEN_CPUID_HVM;
2178         xen_max_leaf->eax = kvm_base + XEN_CPUID_HVM;
2179         if (cs->kvm_state->xen_version >= XEN_VERSION(4, 5)) {
2180             c->function = kvm_base + XEN_CPUID_HVM;
2181 
2182             if (cpu->xen_vapic) {
2183                 c->eax |= XEN_HVM_CPUID_APIC_ACCESS_VIRT;
2184                 c->eax |= XEN_HVM_CPUID_X2APIC_VIRT;
2185             }
2186 
2187             c->eax |= XEN_HVM_CPUID_IOMMU_MAPPINGS;
2188 
2189             if (cs->kvm_state->xen_version >= XEN_VERSION(4, 6)) {
2190                 c->eax |= XEN_HVM_CPUID_VCPU_ID_PRESENT;
2191                 c->ebx = cs->cpu_index;
2192             }
2193 
2194             if (cs->kvm_state->xen_version >= XEN_VERSION(4, 17)) {
2195                 c->eax |= XEN_HVM_CPUID_UPCALL_VECTOR;
2196             }
2197         }
2198 
2199         r = kvm_xen_init_vcpu(cs);
2200         if (r) {
2201             return r;
2202         }
2203 
2204         kvm_base += 0x100;
2205 #else /* CONFIG_XEN_EMU */
2206         /* This should never happen as kvm_arch_init() would have died first. */
2207         fprintf(stderr, "Cannot enable Xen CPUID without Xen support\n");
2208         abort();
2209 #endif
2210     } else if (cpu->expose_kvm) {
2211         memcpy(signature, "KVMKVMKVM\0\0\0", 12);
2212         c = &cpuid_data.entries[cpuid_i++];
2213         c->function = KVM_CPUID_SIGNATURE | kvm_base;
2214         c->eax = KVM_CPUID_FEATURES | kvm_base;
2215         c->ebx = signature[0];
2216         c->ecx = signature[1];
2217         c->edx = signature[2];
2218 
2219         c = &cpuid_data.entries[cpuid_i++];
2220         c->function = KVM_CPUID_FEATURES | kvm_base;
2221         c->eax = env->features[FEAT_KVM];
2222         c->edx = env->features[FEAT_KVM_HINTS];
2223     }
2224 
2225     if (cpu->kvm_pv_enforce_cpuid) {
2226         r = kvm_vcpu_enable_cap(cs, KVM_CAP_ENFORCE_PV_FEATURE_CPUID, 0, 1);
2227         if (r < 0) {
2228             fprintf(stderr,
2229                     "failed to enable KVM_CAP_ENFORCE_PV_FEATURE_CPUID: %s",
2230                     strerror(-r));
2231             abort();
2232         }
2233     }
2234 
2235     cpuid_i = kvm_x86_build_cpuid(env, cpuid_data.entries, cpuid_i);
2236     cpuid_data.cpuid.nent = cpuid_i;
2237 
2238     if (((env->cpuid_version >> 8)&0xF) >= 6
2239         && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
2240            (CPUID_MCE | CPUID_MCA)) {
2241         uint64_t mcg_cap, unsupported_caps;
2242         int banks;
2243         int ret;
2244 
2245         ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
2246         if (ret < 0) {
2247             fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
2248             return ret;
2249         }
2250 
2251         if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
2252             error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
2253                          (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
2254             return -ENOTSUP;
2255         }
2256 
2257         unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
2258         if (unsupported_caps) {
2259             if (unsupported_caps & MCG_LMCE_P) {
2260                 error_report("kvm: LMCE not supported");
2261                 return -ENOTSUP;
2262             }
2263             warn_report("Unsupported MCG_CAP bits: 0x%" PRIx64,
2264                         unsupported_caps);
2265         }
2266 
2267         env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
2268         ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
2269         if (ret < 0) {
2270             fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
2271             return ret;
2272         }
2273     }
2274 
2275     cpu->vmsentry = qemu_add_vm_change_state_handler(cpu_update_state, env);
2276 
2277     c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
2278     if (c) {
2279         has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
2280                                   !!(c->ecx & CPUID_EXT_SMX);
2281     }
2282 
2283     c = cpuid_find_entry(&cpuid_data.cpuid, 7, 0);
2284     if (c && (c->ebx & CPUID_7_0_EBX_SGX)) {
2285         has_msr_feature_control = true;
2286     }
2287 
2288     if (env->mcg_cap & MCG_LMCE_P) {
2289         has_msr_mcg_ext_ctl = has_msr_feature_control = true;
2290     }
2291 
2292     if (!env->user_tsc_khz) {
2293         if ((env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC) &&
2294             invtsc_mig_blocker == NULL) {
2295             error_setg(&invtsc_mig_blocker,
2296                        "State blocked by non-migratable CPU device"
2297                        " (invtsc flag)");
2298             r = migrate_add_blocker(&invtsc_mig_blocker, &local_err);
2299             if (r < 0) {
2300                 error_report_err(local_err);
2301                 return r;
2302             }
2303         }
2304     }
2305 
2306     if (cpu->vmware_cpuid_freq
2307         /* Guests depend on 0x40000000 to detect this feature, so only expose
2308          * it if KVM exposes leaf 0x40000000. (Conflicts with Hyper-V) */
2309         && cpu->expose_kvm
2310         && kvm_base == KVM_CPUID_SIGNATURE
2311         /* TSC clock must be stable and known for this feature. */
2312         && tsc_is_stable_and_known(env)) {
2313 
2314         c = &cpuid_data.entries[cpuid_i++];
2315         c->function = KVM_CPUID_SIGNATURE | 0x10;
2316         c->eax = env->tsc_khz;
2317         c->ebx = env->apic_bus_freq / 1000; /* Hz to KHz */
2318         c->ecx = c->edx = 0;
2319 
2320         c = cpuid_find_entry(&cpuid_data.cpuid, kvm_base, 0);
2321         c->eax = MAX(c->eax, KVM_CPUID_SIGNATURE | 0x10);
2322     }
2323 
2324     cpuid_data.cpuid.nent = cpuid_i;
2325 
2326     cpuid_data.cpuid.padding = 0;
2327     r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
2328     if (r) {
2329         goto fail;
2330     }
2331     kvm_init_xsave(env);
2332 
2333     max_nested_state_len = kvm_max_nested_state_length();
2334     if (max_nested_state_len > 0) {
2335         assert(max_nested_state_len >= offsetof(struct kvm_nested_state, data));
2336 
2337         if (cpu_has_vmx(env) || cpu_has_svm(env)) {
2338             env->nested_state = g_malloc0(max_nested_state_len);
2339             env->nested_state->size = max_nested_state_len;
2340 
2341             kvm_init_nested_state(env);
2342         }
2343     }
2344 
2345     cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
2346 
2347     if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
2348         has_msr_tsc_aux = false;
2349     }
2350 
2351     kvm_init_msrs(cpu);
2352 
2353     return 0;
2354 
2355  fail:
2356     migrate_del_blocker(&invtsc_mig_blocker);
2357 
2358     return r;
2359 }
2360 
2361 int kvm_arch_destroy_vcpu(CPUState *cs)
2362 {
2363     X86CPU *cpu = X86_CPU(cs);
2364     CPUX86State *env = &cpu->env;
2365 
2366     g_free(env->xsave_buf);
2367 
2368     g_free(cpu->kvm_msr_buf);
2369     cpu->kvm_msr_buf = NULL;
2370 
2371     g_free(env->nested_state);
2372     env->nested_state = NULL;
2373 
2374     qemu_del_vm_change_state_handler(cpu->vmsentry);
2375 
2376     return 0;
2377 }
2378 
2379 void kvm_arch_reset_vcpu(X86CPU *cpu)
2380 {
2381     CPUX86State *env = &cpu->env;
2382 
2383     env->xcr0 = 1;
2384     if (kvm_irqchip_in_kernel()) {
2385         env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
2386                                           KVM_MP_STATE_UNINITIALIZED;
2387     } else {
2388         env->mp_state = KVM_MP_STATE_RUNNABLE;
2389     }
2390 
2391     /* enabled by default */
2392     env->poll_control_msr = 1;
2393 
2394     kvm_init_nested_state(env);
2395 
2396     sev_es_set_reset_vector(CPU(cpu));
2397 }
2398 
2399 void kvm_arch_after_reset_vcpu(X86CPU *cpu)
2400 {
2401     CPUX86State *env = &cpu->env;
2402     int i;
2403 
2404     /*
2405      * Reset SynIC after all other devices have been reset to let them remove
2406      * their SINT routes first.
2407      */
2408     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
2409         for (i = 0; i < ARRAY_SIZE(env->msr_hv_synic_sint); i++) {
2410             env->msr_hv_synic_sint[i] = HV_SINT_MASKED;
2411         }
2412 
2413         hyperv_x86_synic_reset(cpu);
2414     }
2415 }
2416 
2417 void kvm_arch_do_init_vcpu(X86CPU *cpu)
2418 {
2419     CPUX86State *env = &cpu->env;
2420 
2421     /* APs get directly into wait-for-SIPI state.  */
2422     if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
2423         env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
2424     }
2425 }
2426 
2427 static int kvm_get_supported_feature_msrs(KVMState *s)
2428 {
2429     int ret = 0;
2430 
2431     if (kvm_feature_msrs != NULL) {
2432         return 0;
2433     }
2434 
2435     if (!kvm_check_extension(s, KVM_CAP_GET_MSR_FEATURES)) {
2436         return 0;
2437     }
2438 
2439     struct kvm_msr_list msr_list;
2440 
2441     msr_list.nmsrs = 0;
2442     ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, &msr_list);
2443     if (ret < 0 && ret != -E2BIG) {
2444         error_report("Fetch KVM feature MSR list failed: %s",
2445             strerror(-ret));
2446         return ret;
2447     }
2448 
2449     assert(msr_list.nmsrs > 0);
2450     kvm_feature_msrs = g_malloc0(sizeof(msr_list) +
2451                  msr_list.nmsrs * sizeof(msr_list.indices[0]));
2452 
2453     kvm_feature_msrs->nmsrs = msr_list.nmsrs;
2454     ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, kvm_feature_msrs);
2455 
2456     if (ret < 0) {
2457         error_report("Fetch KVM feature MSR list failed: %s",
2458             strerror(-ret));
2459         g_free(kvm_feature_msrs);
2460         kvm_feature_msrs = NULL;
2461         return ret;
2462     }
2463 
2464     return 0;
2465 }
2466 
2467 static int kvm_get_supported_msrs(KVMState *s)
2468 {
2469     int ret = 0;
2470     struct kvm_msr_list msr_list, *kvm_msr_list;
2471 
2472     /*
2473      *  Obtain MSR list from KVM.  These are the MSRs that we must
2474      *  save/restore.
2475      */
2476     msr_list.nmsrs = 0;
2477     ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
2478     if (ret < 0 && ret != -E2BIG) {
2479         return ret;
2480     }
2481     /*
2482      * Old kernel modules had a bug and could write beyond the provided
2483      * memory. Allocate at least a safe amount of 1K.
2484      */
2485     kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
2486                                           msr_list.nmsrs *
2487                                           sizeof(msr_list.indices[0])));
2488 
2489     kvm_msr_list->nmsrs = msr_list.nmsrs;
2490     ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
2491     if (ret >= 0) {
2492         int i;
2493 
2494         for (i = 0; i < kvm_msr_list->nmsrs; i++) {
2495             switch (kvm_msr_list->indices[i]) {
2496             case MSR_STAR:
2497                 has_msr_star = true;
2498                 break;
2499             case MSR_VM_HSAVE_PA:
2500                 has_msr_hsave_pa = true;
2501                 break;
2502             case MSR_TSC_AUX:
2503                 has_msr_tsc_aux = true;
2504                 break;
2505             case MSR_TSC_ADJUST:
2506                 has_msr_tsc_adjust = true;
2507                 break;
2508             case MSR_IA32_TSCDEADLINE:
2509                 has_msr_tsc_deadline = true;
2510                 break;
2511             case MSR_IA32_SMBASE:
2512                 has_msr_smbase = true;
2513                 break;
2514             case MSR_SMI_COUNT:
2515                 has_msr_smi_count = true;
2516                 break;
2517             case MSR_IA32_MISC_ENABLE:
2518                 has_msr_misc_enable = true;
2519                 break;
2520             case MSR_IA32_BNDCFGS:
2521                 has_msr_bndcfgs = true;
2522                 break;
2523             case MSR_IA32_XSS:
2524                 has_msr_xss = true;
2525                 break;
2526             case MSR_IA32_UMWAIT_CONTROL:
2527                 has_msr_umwait = true;
2528                 break;
2529             case HV_X64_MSR_CRASH_CTL:
2530                 has_msr_hv_crash = true;
2531                 break;
2532             case HV_X64_MSR_RESET:
2533                 has_msr_hv_reset = true;
2534                 break;
2535             case HV_X64_MSR_VP_INDEX:
2536                 has_msr_hv_vpindex = true;
2537                 break;
2538             case HV_X64_MSR_VP_RUNTIME:
2539                 has_msr_hv_runtime = true;
2540                 break;
2541             case HV_X64_MSR_SCONTROL:
2542                 has_msr_hv_synic = true;
2543                 break;
2544             case HV_X64_MSR_STIMER0_CONFIG:
2545                 has_msr_hv_stimer = true;
2546                 break;
2547             case HV_X64_MSR_TSC_FREQUENCY:
2548                 has_msr_hv_frequencies = true;
2549                 break;
2550             case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2551                 has_msr_hv_reenlightenment = true;
2552                 break;
2553             case HV_X64_MSR_SYNDBG_OPTIONS:
2554                 has_msr_hv_syndbg_options = true;
2555                 break;
2556             case MSR_IA32_SPEC_CTRL:
2557                 has_msr_spec_ctrl = true;
2558                 break;
2559             case MSR_AMD64_TSC_RATIO:
2560                 has_tsc_scale_msr = true;
2561                 break;
2562             case MSR_IA32_TSX_CTRL:
2563                 has_msr_tsx_ctrl = true;
2564                 break;
2565             case MSR_VIRT_SSBD:
2566                 has_msr_virt_ssbd = true;
2567                 break;
2568             case MSR_IA32_ARCH_CAPABILITIES:
2569                 has_msr_arch_capabs = true;
2570                 break;
2571             case MSR_IA32_CORE_CAPABILITY:
2572                 has_msr_core_capabs = true;
2573                 break;
2574             case MSR_IA32_PERF_CAPABILITIES:
2575                 has_msr_perf_capabs = true;
2576                 break;
2577             case MSR_IA32_VMX_VMFUNC:
2578                 has_msr_vmx_vmfunc = true;
2579                 break;
2580             case MSR_IA32_UCODE_REV:
2581                 has_msr_ucode_rev = true;
2582                 break;
2583             case MSR_IA32_VMX_PROCBASED_CTLS2:
2584                 has_msr_vmx_procbased_ctls2 = true;
2585                 break;
2586             case MSR_IA32_PKRS:
2587                 has_msr_pkrs = true;
2588                 break;
2589             case MSR_K7_HWCR:
2590                 has_msr_hwcr = true;
2591             }
2592         }
2593     }
2594 
2595     g_free(kvm_msr_list);
2596 
2597     return ret;
2598 }
2599 
2600 static bool kvm_rdmsr_core_thread_count(X86CPU *cpu,
2601                                         uint32_t msr,
2602                                         uint64_t *val)
2603 {
2604     CPUState *cs = CPU(cpu);
2605 
2606     *val = cs->nr_threads * cs->nr_cores; /* thread count, bits 15..0 */
2607     *val |= ((uint32_t)cs->nr_cores << 16); /* core count, bits 31..16 */
2608 
2609     return true;
2610 }
2611 
2612 static bool kvm_rdmsr_rapl_power_unit(X86CPU *cpu,
2613                                       uint32_t msr,
2614                                       uint64_t *val)
2615 {
2616 
2617     CPUState *cs = CPU(cpu);
2618 
2619     *val = cs->kvm_state->msr_energy.msr_unit;
2620 
2621     return true;
2622 }
2623 
2624 static bool kvm_rdmsr_pkg_power_limit(X86CPU *cpu,
2625                                       uint32_t msr,
2626                                       uint64_t *val)
2627 {
2628 
2629     CPUState *cs = CPU(cpu);
2630 
2631     *val = cs->kvm_state->msr_energy.msr_limit;
2632 
2633     return true;
2634 }
2635 
2636 static bool kvm_rdmsr_pkg_power_info(X86CPU *cpu,
2637                                      uint32_t msr,
2638                                      uint64_t *val)
2639 {
2640 
2641     CPUState *cs = CPU(cpu);
2642 
2643     *val = cs->kvm_state->msr_energy.msr_info;
2644 
2645     return true;
2646 }
2647 
2648 static bool kvm_rdmsr_pkg_energy_status(X86CPU *cpu,
2649                                         uint32_t msr,
2650                                         uint64_t *val)
2651 {
2652 
2653     CPUState *cs = CPU(cpu);
2654     *val = cs->kvm_state->msr_energy.msr_value[cs->cpu_index];
2655 
2656     return true;
2657 }
2658 
2659 static Notifier smram_machine_done;
2660 static KVMMemoryListener smram_listener;
2661 static AddressSpace smram_address_space;
2662 static MemoryRegion smram_as_root;
2663 static MemoryRegion smram_as_mem;
2664 
2665 static void register_smram_listener(Notifier *n, void *unused)
2666 {
2667     MemoryRegion *smram =
2668         (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
2669 
2670     /* Outer container... */
2671     memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
2672     memory_region_set_enabled(&smram_as_root, true);
2673 
2674     /* ... with two regions inside: normal system memory with low
2675      * priority, and...
2676      */
2677     memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
2678                              get_system_memory(), 0, ~0ull);
2679     memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
2680     memory_region_set_enabled(&smram_as_mem, true);
2681 
2682     if (smram) {
2683         /* ... SMRAM with higher priority */
2684         memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
2685         memory_region_set_enabled(smram, true);
2686     }
2687 
2688     address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
2689     kvm_memory_listener_register(kvm_state, &smram_listener,
2690                                  &smram_address_space, 1, "kvm-smram");
2691 }
2692 
2693 static void *kvm_msr_energy_thread(void *data)
2694 {
2695     KVMState *s = data;
2696     struct KVMMsrEnergy *vmsr = &s->msr_energy;
2697 
2698     g_autofree vmsr_package_energy_stat *pkg_stat = NULL;
2699     g_autofree vmsr_thread_stat *thd_stat = NULL;
2700     g_autofree CPUState *cpu = NULL;
2701     g_autofree unsigned int *vpkgs_energy_stat = NULL;
2702     unsigned int num_threads = 0;
2703 
2704     X86CPUTopoIDs topo_ids;
2705 
2706     rcu_register_thread();
2707 
2708     /* Allocate memory for each package energy status */
2709     pkg_stat = g_new0(vmsr_package_energy_stat, vmsr->host_topo.maxpkgs);
2710 
2711     /* Allocate memory for thread stats */
2712     thd_stat = g_new0(vmsr_thread_stat, 1);
2713 
2714     /* Allocate memory for holding virtual package energy counter */
2715     vpkgs_energy_stat = g_new0(unsigned int, vmsr->guest_vsockets);
2716 
2717     /* Populate the max tick of each packages */
2718     for (int i = 0; i < vmsr->host_topo.maxpkgs; i++) {
2719         /*
2720          * Max numbers of ticks per package
2721          * Time in second * Number of ticks/second * Number of cores/package
2722          * ex: 100 ticks/second/CPU, 12 CPUs per Package gives 1200 ticks max
2723          */
2724         vmsr->host_topo.maxticks[i] = (MSR_ENERGY_THREAD_SLEEP_US / 1000000)
2725                         * sysconf(_SC_CLK_TCK)
2726                         * vmsr->host_topo.pkg_cpu_count[i];
2727     }
2728 
2729     while (true) {
2730         /* Get all qemu threads id */
2731         g_autofree pid_t *thread_ids
2732             = vmsr_get_thread_ids(vmsr->pid, &num_threads);
2733 
2734         if (thread_ids == NULL) {
2735             goto clean;
2736         }
2737 
2738         thd_stat = g_renew(vmsr_thread_stat, thd_stat, num_threads);
2739         /* Unlike g_new0, g_renew0 function doesn't exist yet... */
2740         memset(thd_stat, 0, num_threads * sizeof(vmsr_thread_stat));
2741 
2742         /* Populate all the thread stats */
2743         for (int i = 0; i < num_threads; i++) {
2744             thd_stat[i].utime = g_new0(unsigned long long, 2);
2745             thd_stat[i].stime = g_new0(unsigned long long, 2);
2746             thd_stat[i].thread_id = thread_ids[i];
2747             vmsr_read_thread_stat(vmsr->pid,
2748                                   thd_stat[i].thread_id,
2749                                   &thd_stat[i].utime[0],
2750                                   &thd_stat[i].stime[0],
2751                                   &thd_stat[i].cpu_id);
2752             thd_stat[i].pkg_id =
2753                 vmsr_get_physical_package_id(thd_stat[i].cpu_id);
2754         }
2755 
2756         /* Retrieve all packages power plane energy counter */
2757         for (int i = 0; i < vmsr->host_topo.maxpkgs; i++) {
2758             for (int j = 0; j < num_threads; j++) {
2759                 /*
2760                  * Use the first thread we found that ran on the CPU
2761                  * of the package to read the packages energy counter
2762                  */
2763                 if (thd_stat[j].pkg_id == i) {
2764                     pkg_stat[i].e_start =
2765                     vmsr_read_msr(MSR_PKG_ENERGY_STATUS,
2766                                   thd_stat[j].cpu_id,
2767                                   thd_stat[j].thread_id,
2768                                   s->msr_energy.sioc);
2769                     break;
2770                 }
2771             }
2772         }
2773 
2774         /* Sleep a short period while the other threads are working */
2775         usleep(MSR_ENERGY_THREAD_SLEEP_US);
2776 
2777         /*
2778          * Retrieve all packages power plane energy counter
2779          * Calculate the delta of all packages
2780          */
2781         for (int i = 0; i < vmsr->host_topo.maxpkgs; i++) {
2782             for (int j = 0; j < num_threads; j++) {
2783                 /*
2784                  * Use the first thread we found that ran on the CPU
2785                  * of the package to read the packages energy counter
2786                  */
2787                 if (thd_stat[j].pkg_id == i) {
2788                     pkg_stat[i].e_end =
2789                     vmsr_read_msr(MSR_PKG_ENERGY_STATUS,
2790                                   thd_stat[j].cpu_id,
2791                                   thd_stat[j].thread_id,
2792                                   s->msr_energy.sioc);
2793                     /*
2794                      * Prevent the case we have migrate the VM
2795                      * during the sleep period or any other cases
2796                      * were energy counter might be lower after
2797                      * the sleep period.
2798                      */
2799                     if (pkg_stat[i].e_end > pkg_stat[i].e_start) {
2800                         pkg_stat[i].e_delta =
2801                             pkg_stat[i].e_end - pkg_stat[i].e_start;
2802                     } else {
2803                         pkg_stat[i].e_delta = 0;
2804                     }
2805                     break;
2806                 }
2807             }
2808         }
2809 
2810         /* Delta of ticks spend by each thread between the sample */
2811         for (int i = 0; i < num_threads; i++) {
2812             vmsr_read_thread_stat(vmsr->pid,
2813                                   thd_stat[i].thread_id,
2814                                   &thd_stat[i].utime[1],
2815                                   &thd_stat[i].stime[1],
2816                                   &thd_stat[i].cpu_id);
2817 
2818             if (vmsr->pid < 0) {
2819                 /*
2820                  * We don't count the dead thread
2821                  * i.e threads that existed before the sleep
2822                  * and not anymore
2823                  */
2824                 thd_stat[i].delta_ticks = 0;
2825             } else {
2826                 vmsr_delta_ticks(thd_stat, i);
2827             }
2828         }
2829 
2830         /*
2831          * Identify the vcpu threads
2832          * Calculate the number of vcpu per package
2833          */
2834         CPU_FOREACH(cpu) {
2835             for (int i = 0; i < num_threads; i++) {
2836                 if (cpu->thread_id == thd_stat[i].thread_id) {
2837                     thd_stat[i].is_vcpu = true;
2838                     thd_stat[i].vcpu_id = cpu->cpu_index;
2839                     pkg_stat[thd_stat[i].pkg_id].nb_vcpu++;
2840                     thd_stat[i].acpi_id = kvm_arch_vcpu_id(cpu);
2841                     break;
2842                 }
2843             }
2844         }
2845 
2846         /* Retrieve the virtual package number of each vCPU */
2847         for (int i = 0; i < vmsr->guest_cpu_list->len; i++) {
2848             for (int j = 0; j < num_threads; j++) {
2849                 if ((thd_stat[j].acpi_id ==
2850                         vmsr->guest_cpu_list->cpus[i].arch_id)
2851                     && (thd_stat[j].is_vcpu == true)) {
2852                     x86_topo_ids_from_apicid(thd_stat[j].acpi_id,
2853                         &vmsr->guest_topo_info, &topo_ids);
2854                     thd_stat[j].vpkg_id = topo_ids.pkg_id;
2855                 }
2856             }
2857         }
2858 
2859         /* Calculate the total energy of all non-vCPU thread */
2860         for (int i = 0; i < num_threads; i++) {
2861             if ((thd_stat[i].is_vcpu != true) &&
2862                 (thd_stat[i].delta_ticks > 0)) {
2863                 double temp;
2864                 temp = vmsr_get_ratio(pkg_stat[thd_stat[i].pkg_id].e_delta,
2865                     thd_stat[i].delta_ticks,
2866                     vmsr->host_topo.maxticks[thd_stat[i].pkg_id]);
2867                 pkg_stat[thd_stat[i].pkg_id].e_ratio
2868                     += (uint64_t)lround(temp);
2869             }
2870         }
2871 
2872         /* Calculate the ratio per non-vCPU thread of each package */
2873         for (int i = 0; i < vmsr->host_topo.maxpkgs; i++) {
2874             if (pkg_stat[i].nb_vcpu > 0) {
2875                 pkg_stat[i].e_ratio = pkg_stat[i].e_ratio / pkg_stat[i].nb_vcpu;
2876             }
2877         }
2878 
2879         /*
2880          * Calculate the energy for each Package:
2881          * Energy Package = sum of each vCPU energy that belongs to the package
2882          */
2883         for (int i = 0; i < num_threads; i++) {
2884             if ((thd_stat[i].is_vcpu == true) && \
2885                     (thd_stat[i].delta_ticks > 0)) {
2886                 double temp;
2887                 temp = vmsr_get_ratio(pkg_stat[thd_stat[i].pkg_id].e_delta,
2888                     thd_stat[i].delta_ticks,
2889                     vmsr->host_topo.maxticks[thd_stat[i].pkg_id]);
2890                 vpkgs_energy_stat[thd_stat[i].vpkg_id] +=
2891                     (uint64_t)lround(temp);
2892                 vpkgs_energy_stat[thd_stat[i].vpkg_id] +=
2893                     pkg_stat[thd_stat[i].pkg_id].e_ratio;
2894             }
2895         }
2896 
2897         /*
2898          * Finally populate the vmsr register of each vCPU with the total
2899          * package value to emulate the real hardware where each CPU return the
2900          * value of the package it belongs.
2901          */
2902         for (int i = 0; i < num_threads; i++) {
2903             if ((thd_stat[i].is_vcpu == true) && \
2904                     (thd_stat[i].delta_ticks > 0)) {
2905                 vmsr->msr_value[thd_stat[i].vcpu_id] = \
2906                                         vpkgs_energy_stat[thd_stat[i].vpkg_id];
2907           }
2908         }
2909 
2910         /* Freeing memory before zeroing the pointer */
2911         for (int i = 0; i < num_threads; i++) {
2912             g_free(thd_stat[i].utime);
2913             g_free(thd_stat[i].stime);
2914         }
2915    }
2916 
2917 clean:
2918     rcu_unregister_thread();
2919     return NULL;
2920 }
2921 
2922 static int kvm_msr_energy_thread_init(KVMState *s, MachineState *ms)
2923 {
2924     MachineClass *mc = MACHINE_GET_CLASS(ms);
2925     struct KVMMsrEnergy *r = &s->msr_energy;
2926     int ret = 0;
2927 
2928     /*
2929      * Sanity check
2930      * 1. Host cpu must be Intel cpu
2931      * 2. RAPL must be enabled on the Host
2932      */
2933     if (!is_host_cpu_intel()) {
2934         error_report("The RAPL feature can only be enabled on hosts "
2935                      "with Intel CPU models");
2936         ret = 1;
2937         goto out;
2938     }
2939 
2940     if (!is_rapl_enabled()) {
2941         ret = 1;
2942         goto out;
2943     }
2944 
2945     /* Retrieve the virtual topology */
2946     vmsr_init_topo_info(&r->guest_topo_info, ms);
2947 
2948     /* Retrieve the number of vcpu */
2949     r->guest_vcpus = ms->smp.cpus;
2950 
2951     /* Retrieve the number of virtual sockets */
2952     r->guest_vsockets = ms->smp.sockets;
2953 
2954     /* Allocate register memory (MSR_PKG_STATUS) for each vcpu */
2955     r->msr_value = g_new0(uint64_t, r->guest_vcpus);
2956 
2957     /* Retrieve the CPUArchIDlist */
2958     r->guest_cpu_list = mc->possible_cpu_arch_ids(ms);
2959 
2960     /* Max number of cpus on the Host */
2961     r->host_topo.maxcpus = vmsr_get_maxcpus();
2962     if (r->host_topo.maxcpus == 0) {
2963         error_report("host max cpus = 0");
2964         ret = 1;
2965         goto out;
2966     }
2967 
2968     /* Max number of packages on the host */
2969     r->host_topo.maxpkgs = vmsr_get_max_physical_package(r->host_topo.maxcpus);
2970     if (r->host_topo.maxpkgs == 0) {
2971         error_report("host max pkgs = 0");
2972         ret = 1;
2973         goto out;
2974     }
2975 
2976     /* Allocate memory for each package on the host */
2977     r->host_topo.pkg_cpu_count = g_new0(unsigned int, r->host_topo.maxpkgs);
2978     r->host_topo.maxticks = g_new0(unsigned int, r->host_topo.maxpkgs);
2979 
2980     vmsr_count_cpus_per_package(r->host_topo.pkg_cpu_count,
2981                                 r->host_topo.maxpkgs);
2982     for (int i = 0; i < r->host_topo.maxpkgs; i++) {
2983         if (r->host_topo.pkg_cpu_count[i] == 0) {
2984             error_report("cpu per packages = 0 on package_%d", i);
2985             ret = 1;
2986             goto out;
2987         }
2988     }
2989 
2990     /* Get QEMU PID*/
2991     r->pid = getpid();
2992 
2993     /* Compute the socket path if necessary */
2994     if (s->msr_energy.socket_path == NULL) {
2995         s->msr_energy.socket_path = vmsr_compute_default_paths();
2996     }
2997 
2998     /* Open socket with vmsr helper */
2999     s->msr_energy.sioc = vmsr_open_socket(s->msr_energy.socket_path);
3000 
3001     if (s->msr_energy.sioc == NULL) {
3002         error_report("vmsr socket opening failed");
3003         ret = 1;
3004         goto out;
3005     }
3006 
3007     /* Those MSR values should not change */
3008     r->msr_unit  = vmsr_read_msr(MSR_RAPL_POWER_UNIT, 0, r->pid,
3009                                     s->msr_energy.sioc);
3010     r->msr_limit = vmsr_read_msr(MSR_PKG_POWER_LIMIT, 0, r->pid,
3011                                     s->msr_energy.sioc);
3012     r->msr_info  = vmsr_read_msr(MSR_PKG_POWER_INFO, 0, r->pid,
3013                                     s->msr_energy.sioc);
3014     if (r->msr_unit == 0 || r->msr_limit == 0 || r->msr_info == 0) {
3015         error_report("can't read any virtual msr");
3016         ret = 1;
3017         goto out;
3018     }
3019 
3020     qemu_thread_create(&r->msr_thr, "kvm-msr",
3021                        kvm_msr_energy_thread,
3022                        s, QEMU_THREAD_JOINABLE);
3023 out:
3024     return ret;
3025 }
3026 
3027 int kvm_arch_get_default_type(MachineState *ms)
3028 {
3029     return 0;
3030 }
3031 
3032 static int kvm_vm_enable_exception_payload(KVMState *s)
3033 {
3034     int ret = 0;
3035     has_exception_payload = kvm_check_extension(s, KVM_CAP_EXCEPTION_PAYLOAD);
3036     if (has_exception_payload) {
3037         ret = kvm_vm_enable_cap(s, KVM_CAP_EXCEPTION_PAYLOAD, 0, true);
3038         if (ret < 0) {
3039             error_report("kvm: Failed to enable exception payload cap: %s",
3040                          strerror(-ret));
3041         }
3042     }
3043 
3044     return ret;
3045 }
3046 
3047 static int kvm_vm_enable_triple_fault_event(KVMState *s)
3048 {
3049     int ret = 0;
3050     has_triple_fault_event = \
3051         kvm_check_extension(s,
3052                             KVM_CAP_X86_TRIPLE_FAULT_EVENT);
3053     if (has_triple_fault_event) {
3054         ret = kvm_vm_enable_cap(s, KVM_CAP_X86_TRIPLE_FAULT_EVENT, 0, true);
3055         if (ret < 0) {
3056             error_report("kvm: Failed to enable triple fault event cap: %s",
3057                          strerror(-ret));
3058         }
3059     }
3060     return ret;
3061 }
3062 
3063 static int kvm_vm_set_identity_map_addr(KVMState *s, uint64_t identity_base)
3064 {
3065     return kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
3066 }
3067 
3068 static int kvm_vm_set_nr_mmu_pages(KVMState *s)
3069 {
3070     uint64_t shadow_mem;
3071     int ret = 0;
3072     shadow_mem = object_property_get_int(OBJECT(s),
3073                                          "kvm-shadow-mem",
3074                                          &error_abort);
3075     if (shadow_mem != -1) {
3076         shadow_mem /= 4096;
3077         ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
3078     }
3079     return ret;
3080 }
3081 
3082 static int kvm_vm_set_tss_addr(KVMState *s, uint64_t tss_base)
3083 {
3084     return kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, tss_base);
3085 }
3086 
3087 static int kvm_vm_enable_disable_exits(KVMState *s)
3088 {
3089     int disable_exits = kvm_check_extension(s, KVM_CAP_X86_DISABLE_EXITS);
3090 /* Work around for kernel header with a typo. TODO: fix header and drop. */
3091 #if defined(KVM_X86_DISABLE_EXITS_HTL) && !defined(KVM_X86_DISABLE_EXITS_HLT)
3092 #define KVM_X86_DISABLE_EXITS_HLT KVM_X86_DISABLE_EXITS_HTL
3093 #endif
3094     if (disable_exits) {
3095         disable_exits &= (KVM_X86_DISABLE_EXITS_MWAIT |
3096                           KVM_X86_DISABLE_EXITS_HLT |
3097                           KVM_X86_DISABLE_EXITS_PAUSE |
3098                           KVM_X86_DISABLE_EXITS_CSTATE);
3099     }
3100 
3101     return kvm_vm_enable_cap(s, KVM_CAP_X86_DISABLE_EXITS, 0,
3102                              disable_exits);
3103 }
3104 
3105 static int kvm_vm_enable_bus_lock_exit(KVMState *s)
3106 {
3107     int ret = 0;
3108     ret = kvm_check_extension(s, KVM_CAP_X86_BUS_LOCK_EXIT);
3109     if (!(ret & KVM_BUS_LOCK_DETECTION_EXIT)) {
3110         error_report("kvm: bus lock detection unsupported");
3111         return -ENOTSUP;
3112     }
3113     ret = kvm_vm_enable_cap(s, KVM_CAP_X86_BUS_LOCK_EXIT, 0,
3114                             KVM_BUS_LOCK_DETECTION_EXIT);
3115     if (ret < 0) {
3116         error_report("kvm: Failed to enable bus lock detection cap: %s",
3117                      strerror(-ret));
3118     }
3119 
3120     return ret;
3121 }
3122 
3123 static int kvm_vm_enable_notify_vmexit(KVMState *s)
3124 {
3125     int ret = 0;
3126     if (s->notify_vmexit != NOTIFY_VMEXIT_OPTION_DISABLE) {
3127         uint64_t notify_window_flags =
3128             ((uint64_t)s->notify_window << 32) |
3129             KVM_X86_NOTIFY_VMEXIT_ENABLED |
3130             KVM_X86_NOTIFY_VMEXIT_USER;
3131         ret = kvm_vm_enable_cap(s, KVM_CAP_X86_NOTIFY_VMEXIT, 0,
3132                                 notify_window_flags);
3133         if (ret < 0) {
3134             error_report("kvm: Failed to enable notify vmexit cap: %s",
3135                          strerror(-ret));
3136         }
3137     }
3138     return ret;
3139 }
3140 
3141 static int kvm_vm_enable_userspace_msr(KVMState *s)
3142 {
3143     int ret = kvm_vm_enable_cap(s, KVM_CAP_X86_USER_SPACE_MSR, 0,
3144                                 KVM_MSR_EXIT_REASON_FILTER);
3145     if (ret < 0) {
3146         error_report("Could not enable user space MSRs: %s",
3147                      strerror(-ret));
3148         exit(1);
3149     }
3150 
3151     if (!kvm_filter_msr(s, MSR_CORE_THREAD_COUNT,
3152                         kvm_rdmsr_core_thread_count, NULL)) {
3153         error_report("Could not install MSR_CORE_THREAD_COUNT handler!");
3154         exit(1);
3155     }
3156 
3157     return 0;
3158 }
3159 
3160 static void kvm_vm_enable_energy_msrs(KVMState *s)
3161 {
3162     bool r;
3163     if (s->msr_energy.enable == true) {
3164         r = kvm_filter_msr(s, MSR_RAPL_POWER_UNIT,
3165                            kvm_rdmsr_rapl_power_unit, NULL);
3166         if (!r) {
3167             error_report("Could not install MSR_RAPL_POWER_UNIT \
3168                                 handler");
3169             exit(1);
3170         }
3171 
3172         r = kvm_filter_msr(s, MSR_PKG_POWER_LIMIT,
3173                            kvm_rdmsr_pkg_power_limit, NULL);
3174         if (!r) {
3175             error_report("Could not install MSR_PKG_POWER_LIMIT \
3176                                 handler");
3177             exit(1);
3178         }
3179 
3180         r = kvm_filter_msr(s, MSR_PKG_POWER_INFO,
3181                            kvm_rdmsr_pkg_power_info, NULL);
3182         if (!r) {
3183             error_report("Could not install MSR_PKG_POWER_INFO \
3184                                 handler");
3185             exit(1);
3186         }
3187         r = kvm_filter_msr(s, MSR_PKG_ENERGY_STATUS,
3188                            kvm_rdmsr_pkg_energy_status, NULL);
3189         if (!r) {
3190             error_report("Could not install MSR_PKG_ENERGY_STATUS \
3191                                 handler");
3192             exit(1);
3193         }
3194     }
3195     return;
3196 }
3197 
3198 int kvm_arch_init(MachineState *ms, KVMState *s)
3199 {
3200     int ret;
3201     struct utsname utsname;
3202     Error *local_err = NULL;
3203 
3204     /*
3205      * Initialize SEV context, if required
3206      *
3207      * If no memory encryption is requested (ms->cgs == NULL) this is
3208      * a no-op.
3209      *
3210      * It's also a no-op if a non-SEV confidential guest support
3211      * mechanism is selected.  SEV is the only mechanism available to
3212      * select on x86 at present, so this doesn't arise, but if new
3213      * mechanisms are supported in future (e.g. TDX), they'll need
3214      * their own initialization either here or elsewhere.
3215      */
3216     if (ms->cgs) {
3217         ret = confidential_guest_kvm_init(ms->cgs, &local_err);
3218         if (ret < 0) {
3219             error_report_err(local_err);
3220             return ret;
3221         }
3222     }
3223 
3224     has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
3225     has_sregs2 = kvm_check_extension(s, KVM_CAP_SREGS2) > 0;
3226 
3227     hv_vpindex_settable = kvm_check_extension(s, KVM_CAP_HYPERV_VP_INDEX);
3228 
3229     ret = kvm_vm_enable_exception_payload(s);
3230     if (ret < 0) {
3231         return ret;
3232     }
3233 
3234     ret = kvm_vm_enable_triple_fault_event(s);
3235     if (ret < 0) {
3236         return ret;
3237     }
3238 
3239     if (s->xen_version) {
3240 #ifdef CONFIG_XEN_EMU
3241         if (!object_dynamic_cast(OBJECT(ms), TYPE_PC_MACHINE)) {
3242             error_report("kvm: Xen support only available in PC machine");
3243             return -ENOTSUP;
3244         }
3245         /* hyperv_enabled() doesn't work yet. */
3246         uint32_t msr = XEN_HYPERCALL_MSR;
3247         ret = kvm_xen_init(s, msr);
3248         if (ret < 0) {
3249             return ret;
3250         }
3251 #else
3252         error_report("kvm: Xen support not enabled in qemu");
3253         return -ENOTSUP;
3254 #endif
3255     }
3256 
3257     ret = kvm_get_supported_msrs(s);
3258     if (ret < 0) {
3259         return ret;
3260     }
3261 
3262     kvm_get_supported_feature_msrs(s);
3263 
3264     uname(&utsname);
3265     lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
3266 
3267     ret = kvm_vm_set_identity_map_addr(s, KVM_IDENTITY_BASE);
3268     if (ret < 0) {
3269         return ret;
3270     }
3271 
3272     /* Set TSS base one page after EPT identity map. */
3273     ret = kvm_vm_set_tss_addr(s, KVM_IDENTITY_BASE + 0x1000);
3274     if (ret < 0) {
3275         return ret;
3276     }
3277 
3278     /* Tell fw_cfg to notify the BIOS to reserve the range. */
3279     e820_add_entry(KVM_IDENTITY_BASE, 0x4000, E820_RESERVED);
3280 
3281     ret = kvm_vm_set_nr_mmu_pages(s);
3282     if (ret < 0) {
3283         return ret;
3284     }
3285 
3286     if (kvm_check_extension(s, KVM_CAP_X86_SMM) &&
3287         object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE) &&
3288         x86_machine_is_smm_enabled(X86_MACHINE(ms))) {
3289         smram_machine_done.notify = register_smram_listener;
3290         qemu_add_machine_init_done_notifier(&smram_machine_done);
3291     }
3292 
3293     if (enable_cpu_pm) {
3294         ret = kvm_vm_enable_disable_exits(s);
3295         if (ret < 0) {
3296             error_report("kvm: guest stopping CPU not supported: %s",
3297                          strerror(-ret));
3298         }
3299     }
3300 
3301     if (object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE)) {
3302         X86MachineState *x86ms = X86_MACHINE(ms);
3303 
3304         if (x86ms->bus_lock_ratelimit > 0) {
3305             ret = kvm_vm_enable_bus_lock_exit(s);
3306             if (ret < 0) {
3307                 return ret;
3308             }
3309             ratelimit_init(&bus_lock_ratelimit_ctrl);
3310             ratelimit_set_speed(&bus_lock_ratelimit_ctrl,
3311                                 x86ms->bus_lock_ratelimit, BUS_LOCK_SLICE_TIME);
3312         }
3313     }
3314 
3315     if (kvm_check_extension(s, KVM_CAP_X86_NOTIFY_VMEXIT)) {
3316         ret = kvm_vm_enable_notify_vmexit(s);
3317         if (ret < 0) {
3318             return ret;
3319         }
3320     }
3321 
3322     if (kvm_vm_check_extension(s, KVM_CAP_X86_USER_SPACE_MSR)) {
3323         ret = kvm_vm_enable_userspace_msr(s);
3324         if (ret < 0) {
3325             return ret;
3326         }
3327 
3328         if (s->msr_energy.enable == true) {
3329             kvm_vm_enable_energy_msrs(s);
3330             if (kvm_msr_energy_thread_init(s, ms)) {
3331                 error_report("kvm : error RAPL feature requirement not met");
3332                 exit(1);
3333             }
3334         }
3335     }
3336 
3337     return 0;
3338 }
3339 
3340 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
3341 {
3342     lhs->selector = rhs->selector;
3343     lhs->base = rhs->base;
3344     lhs->limit = rhs->limit;
3345     lhs->type = 3;
3346     lhs->present = 1;
3347     lhs->dpl = 3;
3348     lhs->db = 0;
3349     lhs->s = 1;
3350     lhs->l = 0;
3351     lhs->g = 0;
3352     lhs->avl = 0;
3353     lhs->unusable = 0;
3354 }
3355 
3356 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
3357 {
3358     unsigned flags = rhs->flags;
3359     lhs->selector = rhs->selector;
3360     lhs->base = rhs->base;
3361     lhs->limit = rhs->limit;
3362     lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
3363     lhs->present = (flags & DESC_P_MASK) != 0;
3364     lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
3365     lhs->db = (flags >> DESC_B_SHIFT) & 1;
3366     lhs->s = (flags & DESC_S_MASK) != 0;
3367     lhs->l = (flags >> DESC_L_SHIFT) & 1;
3368     lhs->g = (flags & DESC_G_MASK) != 0;
3369     lhs->avl = (flags & DESC_AVL_MASK) != 0;
3370     lhs->unusable = !lhs->present;
3371     lhs->padding = 0;
3372 }
3373 
3374 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
3375 {
3376     lhs->selector = rhs->selector;
3377     lhs->base = rhs->base;
3378     lhs->limit = rhs->limit;
3379     lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
3380                  ((rhs->present && !rhs->unusable) * DESC_P_MASK) |
3381                  (rhs->dpl << DESC_DPL_SHIFT) |
3382                  (rhs->db << DESC_B_SHIFT) |
3383                  (rhs->s * DESC_S_MASK) |
3384                  (rhs->l << DESC_L_SHIFT) |
3385                  (rhs->g * DESC_G_MASK) |
3386                  (rhs->avl * DESC_AVL_MASK);
3387 }
3388 
3389 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
3390 {
3391     if (set) {
3392         *kvm_reg = *qemu_reg;
3393     } else {
3394         *qemu_reg = *kvm_reg;
3395     }
3396 }
3397 
3398 static int kvm_getput_regs(X86CPU *cpu, int set)
3399 {
3400     CPUX86State *env = &cpu->env;
3401     struct kvm_regs regs;
3402     int ret = 0;
3403 
3404     if (!set) {
3405         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
3406         if (ret < 0) {
3407             return ret;
3408         }
3409     }
3410 
3411     kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
3412     kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
3413     kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
3414     kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
3415     kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
3416     kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
3417     kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
3418     kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
3419 #ifdef TARGET_X86_64
3420     kvm_getput_reg(&regs.r8, &env->regs[8], set);
3421     kvm_getput_reg(&regs.r9, &env->regs[9], set);
3422     kvm_getput_reg(&regs.r10, &env->regs[10], set);
3423     kvm_getput_reg(&regs.r11, &env->regs[11], set);
3424     kvm_getput_reg(&regs.r12, &env->regs[12], set);
3425     kvm_getput_reg(&regs.r13, &env->regs[13], set);
3426     kvm_getput_reg(&regs.r14, &env->regs[14], set);
3427     kvm_getput_reg(&regs.r15, &env->regs[15], set);
3428 #endif
3429 
3430     kvm_getput_reg(&regs.rflags, &env->eflags, set);
3431     kvm_getput_reg(&regs.rip, &env->eip, set);
3432 
3433     if (set) {
3434         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
3435     }
3436 
3437     return ret;
3438 }
3439 
3440 static int kvm_put_xsave(X86CPU *cpu)
3441 {
3442     CPUX86State *env = &cpu->env;
3443     void *xsave = env->xsave_buf;
3444 
3445     x86_cpu_xsave_all_areas(cpu, xsave, env->xsave_buf_len);
3446 
3447     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
3448 }
3449 
3450 static int kvm_put_xcrs(X86CPU *cpu)
3451 {
3452     CPUX86State *env = &cpu->env;
3453     struct kvm_xcrs xcrs = {};
3454 
3455     if (!has_xcrs) {
3456         return 0;
3457     }
3458 
3459     xcrs.nr_xcrs = 1;
3460     xcrs.flags = 0;
3461     xcrs.xcrs[0].xcr = 0;
3462     xcrs.xcrs[0].value = env->xcr0;
3463     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
3464 }
3465 
3466 static int kvm_put_sregs(X86CPU *cpu)
3467 {
3468     CPUX86State *env = &cpu->env;
3469     struct kvm_sregs sregs;
3470 
3471     /*
3472      * The interrupt_bitmap is ignored because KVM_SET_SREGS is
3473      * always followed by KVM_SET_VCPU_EVENTS.
3474      */
3475     memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
3476 
3477     if ((env->eflags & VM_MASK)) {
3478         set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
3479         set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
3480         set_v8086_seg(&sregs.es, &env->segs[R_ES]);
3481         set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
3482         set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
3483         set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
3484     } else {
3485         set_seg(&sregs.cs, &env->segs[R_CS]);
3486         set_seg(&sregs.ds, &env->segs[R_DS]);
3487         set_seg(&sregs.es, &env->segs[R_ES]);
3488         set_seg(&sregs.fs, &env->segs[R_FS]);
3489         set_seg(&sregs.gs, &env->segs[R_GS]);
3490         set_seg(&sregs.ss, &env->segs[R_SS]);
3491     }
3492 
3493     set_seg(&sregs.tr, &env->tr);
3494     set_seg(&sregs.ldt, &env->ldt);
3495 
3496     sregs.idt.limit = env->idt.limit;
3497     sregs.idt.base = env->idt.base;
3498     memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
3499     sregs.gdt.limit = env->gdt.limit;
3500     sregs.gdt.base = env->gdt.base;
3501     memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
3502 
3503     sregs.cr0 = env->cr[0];
3504     sregs.cr2 = env->cr[2];
3505     sregs.cr3 = env->cr[3];
3506     sregs.cr4 = env->cr[4];
3507 
3508     sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
3509     sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
3510 
3511     sregs.efer = env->efer;
3512 
3513     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
3514 }
3515 
3516 static int kvm_put_sregs2(X86CPU *cpu)
3517 {
3518     CPUX86State *env = &cpu->env;
3519     struct kvm_sregs2 sregs;
3520     int i;
3521 
3522     sregs.flags = 0;
3523 
3524     if ((env->eflags & VM_MASK)) {
3525         set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
3526         set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
3527         set_v8086_seg(&sregs.es, &env->segs[R_ES]);
3528         set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
3529         set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
3530         set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
3531     } else {
3532         set_seg(&sregs.cs, &env->segs[R_CS]);
3533         set_seg(&sregs.ds, &env->segs[R_DS]);
3534         set_seg(&sregs.es, &env->segs[R_ES]);
3535         set_seg(&sregs.fs, &env->segs[R_FS]);
3536         set_seg(&sregs.gs, &env->segs[R_GS]);
3537         set_seg(&sregs.ss, &env->segs[R_SS]);
3538     }
3539 
3540     set_seg(&sregs.tr, &env->tr);
3541     set_seg(&sregs.ldt, &env->ldt);
3542 
3543     sregs.idt.limit = env->idt.limit;
3544     sregs.idt.base = env->idt.base;
3545     memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
3546     sregs.gdt.limit = env->gdt.limit;
3547     sregs.gdt.base = env->gdt.base;
3548     memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
3549 
3550     sregs.cr0 = env->cr[0];
3551     sregs.cr2 = env->cr[2];
3552     sregs.cr3 = env->cr[3];
3553     sregs.cr4 = env->cr[4];
3554 
3555     sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
3556     sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
3557 
3558     sregs.efer = env->efer;
3559 
3560     if (env->pdptrs_valid) {
3561         for (i = 0; i < 4; i++) {
3562             sregs.pdptrs[i] = env->pdptrs[i];
3563         }
3564         sregs.flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
3565     }
3566 
3567     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS2, &sregs);
3568 }
3569 
3570 
3571 static void kvm_msr_buf_reset(X86CPU *cpu)
3572 {
3573     memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
3574 }
3575 
3576 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
3577 {
3578     struct kvm_msrs *msrs = cpu->kvm_msr_buf;
3579     void *limit = ((void *)msrs) + MSR_BUF_SIZE;
3580     struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
3581 
3582     assert((void *)(entry + 1) <= limit);
3583 
3584     entry->index = index;
3585     entry->reserved = 0;
3586     entry->data = value;
3587     msrs->nmsrs++;
3588 }
3589 
3590 static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
3591 {
3592     kvm_msr_buf_reset(cpu);
3593     kvm_msr_entry_add(cpu, index, value);
3594 
3595     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
3596 }
3597 
3598 static int kvm_get_one_msr(X86CPU *cpu, int index, uint64_t *value)
3599 {
3600     int ret;
3601     struct {
3602         struct kvm_msrs info;
3603         struct kvm_msr_entry entries[1];
3604     } msr_data = {
3605         .info.nmsrs = 1,
3606         .entries[0].index = index,
3607     };
3608 
3609     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
3610     if (ret < 0) {
3611         return ret;
3612     }
3613     assert(ret == 1);
3614     *value = msr_data.entries[0].data;
3615     return ret;
3616 }
3617 void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
3618 {
3619     int ret;
3620 
3621     ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
3622     assert(ret == 1);
3623 }
3624 
3625 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
3626 {
3627     CPUX86State *env = &cpu->env;
3628     int ret;
3629 
3630     if (!has_msr_tsc_deadline) {
3631         return 0;
3632     }
3633 
3634     ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
3635     if (ret < 0) {
3636         return ret;
3637     }
3638 
3639     assert(ret == 1);
3640     return 0;
3641 }
3642 
3643 /*
3644  * Provide a separate write service for the feature control MSR in order to
3645  * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
3646  * before writing any other state because forcibly leaving nested mode
3647  * invalidates the VCPU state.
3648  */
3649 static int kvm_put_msr_feature_control(X86CPU *cpu)
3650 {
3651     int ret;
3652 
3653     if (!has_msr_feature_control) {
3654         return 0;
3655     }
3656 
3657     ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
3658                           cpu->env.msr_ia32_feature_control);
3659     if (ret < 0) {
3660         return ret;
3661     }
3662 
3663     assert(ret == 1);
3664     return 0;
3665 }
3666 
3667 static uint64_t make_vmx_msr_value(uint32_t index, uint32_t features)
3668 {
3669     uint32_t default1, can_be_one, can_be_zero;
3670     uint32_t must_be_one;
3671 
3672     switch (index) {
3673     case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3674         default1 = 0x00000016;
3675         break;
3676     case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3677         default1 = 0x0401e172;
3678         break;
3679     case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3680         default1 = 0x000011ff;
3681         break;
3682     case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3683         default1 = 0x00036dff;
3684         break;
3685     case MSR_IA32_VMX_PROCBASED_CTLS2:
3686         default1 = 0;
3687         break;
3688     default:
3689         abort();
3690     }
3691 
3692     /* If a feature bit is set, the control can be either set or clear.
3693      * Otherwise the value is limited to either 0 or 1 by default1.
3694      */
3695     can_be_one = features | default1;
3696     can_be_zero = features | ~default1;
3697     must_be_one = ~can_be_zero;
3698 
3699     /*
3700      * Bit 0:31 -> 0 if the control bit can be zero (i.e. 1 if it must be one).
3701      * Bit 32:63 -> 1 if the control bit can be one.
3702      */
3703     return must_be_one | (((uint64_t)can_be_one) << 32);
3704 }
3705 
3706 static void kvm_msr_entry_add_vmx(X86CPU *cpu, FeatureWordArray f)
3707 {
3708     uint64_t kvm_vmx_basic =
3709         kvm_arch_get_supported_msr_feature(kvm_state,
3710                                            MSR_IA32_VMX_BASIC);
3711 
3712     if (!kvm_vmx_basic) {
3713         /* If the kernel doesn't support VMX feature (kvm_intel.nested=0),
3714          * then kvm_vmx_basic will be 0 and KVM_SET_MSR will fail.
3715          */
3716         return;
3717     }
3718 
3719     uint64_t kvm_vmx_misc =
3720         kvm_arch_get_supported_msr_feature(kvm_state,
3721                                            MSR_IA32_VMX_MISC);
3722     uint64_t kvm_vmx_ept_vpid =
3723         kvm_arch_get_supported_msr_feature(kvm_state,
3724                                            MSR_IA32_VMX_EPT_VPID_CAP);
3725 
3726     /*
3727      * If the guest is 64-bit, a value of 1 is allowed for the host address
3728      * space size vmexit control.
3729      */
3730     uint64_t fixed_vmx_exit = f[FEAT_8000_0001_EDX] & CPUID_EXT2_LM
3731         ? (uint64_t)VMX_VM_EXIT_HOST_ADDR_SPACE_SIZE << 32 : 0;
3732 
3733     /*
3734      * Bits 0-30, 32-44 and 50-53 come from the host.  KVM should
3735      * not change them for backwards compatibility.
3736      */
3737     uint64_t fixed_vmx_basic = kvm_vmx_basic &
3738         (MSR_VMX_BASIC_VMCS_REVISION_MASK |
3739          MSR_VMX_BASIC_VMXON_REGION_SIZE_MASK |
3740          MSR_VMX_BASIC_VMCS_MEM_TYPE_MASK);
3741 
3742     /*
3743      * Same for bits 0-4 and 25-27.  Bits 16-24 (CR3 target count) can
3744      * change in the future but are always zero for now, clear them to be
3745      * future proof.  Bits 32-63 in theory could change, though KVM does
3746      * not support dual-monitor treatment and probably never will; mask
3747      * them out as well.
3748      */
3749     uint64_t fixed_vmx_misc = kvm_vmx_misc &
3750         (MSR_VMX_MISC_PREEMPTION_TIMER_SHIFT_MASK |
3751          MSR_VMX_MISC_MAX_MSR_LIST_SIZE_MASK);
3752 
3753     /*
3754      * EPT memory types should not change either, so we do not bother
3755      * adding features for them.
3756      */
3757     uint64_t fixed_vmx_ept_mask =
3758             (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_ENABLE_EPT ?
3759              MSR_VMX_EPT_UC | MSR_VMX_EPT_WB : 0);
3760     uint64_t fixed_vmx_ept_vpid = kvm_vmx_ept_vpid & fixed_vmx_ept_mask;
3761 
3762     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
3763                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
3764                                          f[FEAT_VMX_PROCBASED_CTLS]));
3765     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PINBASED_CTLS,
3766                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_PINBASED_CTLS,
3767                                          f[FEAT_VMX_PINBASED_CTLS]));
3768     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_EXIT_CTLS,
3769                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_EXIT_CTLS,
3770                                          f[FEAT_VMX_EXIT_CTLS]) | fixed_vmx_exit);
3771     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_ENTRY_CTLS,
3772                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_ENTRY_CTLS,
3773                                          f[FEAT_VMX_ENTRY_CTLS]));
3774     kvm_msr_entry_add(cpu, MSR_IA32_VMX_PROCBASED_CTLS2,
3775                       make_vmx_msr_value(MSR_IA32_VMX_PROCBASED_CTLS2,
3776                                          f[FEAT_VMX_SECONDARY_CTLS]));
3777     kvm_msr_entry_add(cpu, MSR_IA32_VMX_EPT_VPID_CAP,
3778                       f[FEAT_VMX_EPT_VPID_CAPS] | fixed_vmx_ept_vpid);
3779     kvm_msr_entry_add(cpu, MSR_IA32_VMX_BASIC,
3780                       f[FEAT_VMX_BASIC] | fixed_vmx_basic);
3781     kvm_msr_entry_add(cpu, MSR_IA32_VMX_MISC,
3782                       f[FEAT_VMX_MISC] | fixed_vmx_misc);
3783     if (has_msr_vmx_vmfunc) {
3784         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMFUNC, f[FEAT_VMX_VMFUNC]);
3785     }
3786 
3787     /*
3788      * Just to be safe, write these with constant values.  The CRn_FIXED1
3789      * MSRs are generated by KVM based on the vCPU's CPUID.
3790      */
3791     kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR0_FIXED0,
3792                       CR0_PE_MASK | CR0_PG_MASK | CR0_NE_MASK);
3793     kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR4_FIXED0,
3794                       CR4_VMXE_MASK);
3795 
3796     if (f[FEAT_7_1_EAX] & CPUID_7_1_EAX_FRED) {
3797         /* FRED injected-event data (0x2052).  */
3798         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x52);
3799     } else if (f[FEAT_VMX_EXIT_CTLS] &
3800                VMX_VM_EXIT_ACTIVATE_SECONDARY_CONTROLS) {
3801         /* Secondary VM-exit controls (0x2044).  */
3802         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x44);
3803     } else if (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_TSC_SCALING) {
3804         /* TSC multiplier (0x2032).  */
3805         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x32);
3806     } else {
3807         /* Preemption timer (0x482E).  */
3808         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x2E);
3809     }
3810 }
3811 
3812 static void kvm_msr_entry_add_perf(X86CPU *cpu, FeatureWordArray f)
3813 {
3814     uint64_t kvm_perf_cap =
3815         kvm_arch_get_supported_msr_feature(kvm_state,
3816                                            MSR_IA32_PERF_CAPABILITIES);
3817 
3818     if (kvm_perf_cap) {
3819         kvm_msr_entry_add(cpu, MSR_IA32_PERF_CAPABILITIES,
3820                         kvm_perf_cap & f[FEAT_PERF_CAPABILITIES]);
3821     }
3822 }
3823 
3824 static int kvm_buf_set_msrs(X86CPU *cpu)
3825 {
3826     int ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
3827     if (ret < 0) {
3828         return ret;
3829     }
3830 
3831     if (ret < cpu->kvm_msr_buf->nmsrs) {
3832         struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
3833         error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,
3834                      (uint32_t)e->index, (uint64_t)e->data);
3835     }
3836 
3837     assert(ret == cpu->kvm_msr_buf->nmsrs);
3838     return 0;
3839 }
3840 
3841 static void kvm_init_msrs(X86CPU *cpu)
3842 {
3843     CPUX86State *env = &cpu->env;
3844 
3845     kvm_msr_buf_reset(cpu);
3846     if (has_msr_arch_capabs) {
3847         kvm_msr_entry_add(cpu, MSR_IA32_ARCH_CAPABILITIES,
3848                           env->features[FEAT_ARCH_CAPABILITIES]);
3849     }
3850 
3851     if (has_msr_core_capabs) {
3852         kvm_msr_entry_add(cpu, MSR_IA32_CORE_CAPABILITY,
3853                           env->features[FEAT_CORE_CAPABILITY]);
3854     }
3855 
3856     if (has_msr_perf_capabs && cpu->enable_pmu) {
3857         kvm_msr_entry_add_perf(cpu, env->features);
3858     }
3859 
3860     if (has_msr_ucode_rev) {
3861         kvm_msr_entry_add(cpu, MSR_IA32_UCODE_REV, cpu->ucode_rev);
3862     }
3863 
3864     /*
3865      * Older kernels do not include VMX MSRs in KVM_GET_MSR_INDEX_LIST, but
3866      * all kernels with MSR features should have them.
3867      */
3868     if (kvm_feature_msrs && cpu_has_vmx(env)) {
3869         kvm_msr_entry_add_vmx(cpu, env->features);
3870     }
3871 
3872     assert(kvm_buf_set_msrs(cpu) == 0);
3873 }
3874 
3875 static int kvm_put_msrs(X86CPU *cpu, int level)
3876 {
3877     CPUX86State *env = &cpu->env;
3878     int i;
3879 
3880     kvm_msr_buf_reset(cpu);
3881 
3882     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
3883     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
3884     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
3885     kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
3886     if (has_msr_star) {
3887         kvm_msr_entry_add(cpu, MSR_STAR, env->star);
3888     }
3889     if (has_msr_hsave_pa) {
3890         kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
3891     }
3892     if (has_msr_tsc_aux) {
3893         kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
3894     }
3895     if (has_msr_tsc_adjust) {
3896         kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
3897     }
3898     if (has_msr_misc_enable) {
3899         kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
3900                           env->msr_ia32_misc_enable);
3901     }
3902     if (has_msr_smbase) {
3903         kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
3904     }
3905     if (has_msr_smi_count) {
3906         kvm_msr_entry_add(cpu, MSR_SMI_COUNT, env->msr_smi_count);
3907     }
3908     if (has_msr_pkrs) {
3909         kvm_msr_entry_add(cpu, MSR_IA32_PKRS, env->pkrs);
3910     }
3911     if (has_msr_bndcfgs) {
3912         kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
3913     }
3914     if (has_msr_xss) {
3915         kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
3916     }
3917     if (has_msr_umwait) {
3918         kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, env->umwait);
3919     }
3920     if (has_msr_spec_ctrl) {
3921         kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, env->spec_ctrl);
3922     }
3923     if (has_tsc_scale_msr) {
3924         kvm_msr_entry_add(cpu, MSR_AMD64_TSC_RATIO, env->amd_tsc_scale_msr);
3925     }
3926 
3927     if (has_msr_tsx_ctrl) {
3928         kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, env->tsx_ctrl);
3929     }
3930     if (has_msr_virt_ssbd) {
3931         kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, env->virt_ssbd);
3932     }
3933     if (has_msr_hwcr) {
3934         kvm_msr_entry_add(cpu, MSR_K7_HWCR, env->msr_hwcr);
3935     }
3936 
3937 #ifdef TARGET_X86_64
3938     if (lm_capable_kernel) {
3939         kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
3940         kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
3941         kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
3942         kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
3943         if (env->features[FEAT_7_1_EAX] & CPUID_7_1_EAX_FRED) {
3944             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP0, env->fred_rsp0);
3945             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP1, env->fred_rsp1);
3946             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP2, env->fred_rsp2);
3947             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP3, env->fred_rsp3);
3948             kvm_msr_entry_add(cpu, MSR_IA32_FRED_STKLVLS, env->fred_stklvls);
3949             kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP1, env->fred_ssp1);
3950             kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP2, env->fred_ssp2);
3951             kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP3, env->fred_ssp3);
3952             kvm_msr_entry_add(cpu, MSR_IA32_FRED_CONFIG, env->fred_config);
3953         }
3954     }
3955 #endif
3956 
3957     /*
3958      * The following MSRs have side effects on the guest or are too heavy
3959      * for normal writeback. Limit them to reset or full state updates.
3960      */
3961     if (level >= KVM_PUT_RESET_STATE) {
3962         kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
3963         kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
3964         kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
3965         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
3966             kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, env->async_pf_int_msr);
3967         }
3968         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
3969             kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
3970         }
3971         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
3972             kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
3973         }
3974         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
3975             kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
3976         }
3977 
3978         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
3979             kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, env->poll_control_msr);
3980         }
3981 
3982         if (has_architectural_pmu_version > 0) {
3983             if (has_architectural_pmu_version > 1) {
3984                 /* Stop the counter.  */
3985                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
3986                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
3987             }
3988 
3989             /* Set the counter values.  */
3990             for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
3991                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
3992                                   env->msr_fixed_counters[i]);
3993             }
3994             for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
3995                 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
3996                                   env->msr_gp_counters[i]);
3997                 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
3998                                   env->msr_gp_evtsel[i]);
3999             }
4000             if (has_architectural_pmu_version > 1) {
4001                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
4002                                   env->msr_global_status);
4003                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
4004                                   env->msr_global_ovf_ctrl);
4005 
4006                 /* Now start the PMU.  */
4007                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
4008                                   env->msr_fixed_ctr_ctrl);
4009                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
4010                                   env->msr_global_ctrl);
4011             }
4012         }
4013         /*
4014          * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,
4015          * only sync them to KVM on the first cpu
4016          */
4017         if (current_cpu == first_cpu) {
4018             if (has_msr_hv_hypercall) {
4019                 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
4020                                   env->msr_hv_guest_os_id);
4021                 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
4022                                   env->msr_hv_hypercall);
4023             }
4024             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
4025                 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,
4026                                   env->msr_hv_tsc);
4027             }
4028             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
4029                 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL,
4030                                   env->msr_hv_reenlightenment_control);
4031                 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL,
4032                                   env->msr_hv_tsc_emulation_control);
4033                 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS,
4034                                   env->msr_hv_tsc_emulation_status);
4035             }
4036             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNDBG) &&
4037                 has_msr_hv_syndbg_options) {
4038                 kvm_msr_entry_add(cpu, HV_X64_MSR_SYNDBG_OPTIONS,
4039                                   hyperv_syndbg_query_options());
4040             }
4041         }
4042         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
4043             kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
4044                               env->msr_hv_vapic);
4045         }
4046         if (has_msr_hv_crash) {
4047             int j;
4048 
4049             for (j = 0; j < HV_CRASH_PARAMS; j++)
4050                 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
4051                                   env->msr_hv_crash_params[j]);
4052 
4053             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);
4054         }
4055         if (has_msr_hv_runtime) {
4056             kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
4057         }
4058         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)
4059             && hv_vpindex_settable) {
4060             kvm_msr_entry_add(cpu, HV_X64_MSR_VP_INDEX,
4061                               hyperv_vp_index(CPU(cpu)));
4062         }
4063         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
4064             int j;
4065 
4066             kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);
4067 
4068             kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
4069                               env->msr_hv_synic_control);
4070             kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
4071                               env->msr_hv_synic_evt_page);
4072             kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
4073                               env->msr_hv_synic_msg_page);
4074 
4075             for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
4076                 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
4077                                   env->msr_hv_synic_sint[j]);
4078             }
4079         }
4080         if (has_msr_hv_stimer) {
4081             int j;
4082 
4083             for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
4084                 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
4085                                 env->msr_hv_stimer_config[j]);
4086             }
4087 
4088             for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
4089                 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
4090                                 env->msr_hv_stimer_count[j]);
4091             }
4092         }
4093         if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
4094             uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
4095 
4096             kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
4097             kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
4098             kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
4099             kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
4100             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
4101             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
4102             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
4103             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
4104             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
4105             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
4106             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
4107             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
4108             for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
4109                 /* The CPU GPs if we write to a bit above the physical limit of
4110                  * the host CPU (and KVM emulates that)
4111                  */
4112                 uint64_t mask = env->mtrr_var[i].mask;
4113                 mask &= phys_mask;
4114 
4115                 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
4116                                   env->mtrr_var[i].base);
4117                 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
4118             }
4119         }
4120         if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
4121             int addr_num = kvm_arch_get_supported_cpuid(kvm_state,
4122                                                     0x14, 1, R_EAX) & 0x7;
4123 
4124             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL,
4125                             env->msr_rtit_ctrl);
4126             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS,
4127                             env->msr_rtit_status);
4128             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE,
4129                             env->msr_rtit_output_base);
4130             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK,
4131                             env->msr_rtit_output_mask);
4132             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH,
4133                             env->msr_rtit_cr3_match);
4134             for (i = 0; i < addr_num; i++) {
4135                 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i,
4136                             env->msr_rtit_addrs[i]);
4137             }
4138         }
4139 
4140         if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_SGX_LC) {
4141             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH0,
4142                               env->msr_ia32_sgxlepubkeyhash[0]);
4143             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH1,
4144                               env->msr_ia32_sgxlepubkeyhash[1]);
4145             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH2,
4146                               env->msr_ia32_sgxlepubkeyhash[2]);
4147             kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH3,
4148                               env->msr_ia32_sgxlepubkeyhash[3]);
4149         }
4150 
4151         if (env->features[FEAT_XSAVE] & CPUID_D_1_EAX_XFD) {
4152             kvm_msr_entry_add(cpu, MSR_IA32_XFD,
4153                               env->msr_xfd);
4154             kvm_msr_entry_add(cpu, MSR_IA32_XFD_ERR,
4155                               env->msr_xfd_err);
4156         }
4157 
4158         if (kvm_enabled() && cpu->enable_pmu &&
4159             (env->features[FEAT_7_0_EDX] & CPUID_7_0_EDX_ARCH_LBR)) {
4160             uint64_t depth;
4161             int ret;
4162 
4163             /*
4164              * Only migrate Arch LBR states when the host Arch LBR depth
4165              * equals that of source guest's, this is to avoid mismatch
4166              * of guest/host config for the msr hence avoid unexpected
4167              * misbehavior.
4168              */
4169             ret = kvm_get_one_msr(cpu, MSR_ARCH_LBR_DEPTH, &depth);
4170 
4171             if (ret == 1 && !!depth && depth == env->msr_lbr_depth) {
4172                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_CTL, env->msr_lbr_ctl);
4173                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_DEPTH, env->msr_lbr_depth);
4174 
4175                 for (i = 0; i < ARCH_LBR_NR_ENTRIES; i++) {
4176                     if (!env->lbr_records[i].from) {
4177                         continue;
4178                     }
4179                     kvm_msr_entry_add(cpu, MSR_ARCH_LBR_FROM_0 + i,
4180                                       env->lbr_records[i].from);
4181                     kvm_msr_entry_add(cpu, MSR_ARCH_LBR_TO_0 + i,
4182                                       env->lbr_records[i].to);
4183                     kvm_msr_entry_add(cpu, MSR_ARCH_LBR_INFO_0 + i,
4184                                       env->lbr_records[i].info);
4185                 }
4186             }
4187         }
4188 
4189         /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
4190          *       kvm_put_msr_feature_control. */
4191     }
4192 
4193     if (env->mcg_cap) {
4194         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
4195         kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
4196         if (has_msr_mcg_ext_ctl) {
4197             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
4198         }
4199         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
4200             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
4201         }
4202     }
4203 
4204     return kvm_buf_set_msrs(cpu);
4205 }
4206 
4207 
4208 static int kvm_get_xsave(X86CPU *cpu)
4209 {
4210     CPUX86State *env = &cpu->env;
4211     void *xsave = env->xsave_buf;
4212     unsigned long type;
4213     int ret;
4214 
4215     type = has_xsave2 ? KVM_GET_XSAVE2 : KVM_GET_XSAVE;
4216     ret = kvm_vcpu_ioctl(CPU(cpu), type, xsave);
4217     if (ret < 0) {
4218         return ret;
4219     }
4220     x86_cpu_xrstor_all_areas(cpu, xsave, env->xsave_buf_len);
4221 
4222     return 0;
4223 }
4224 
4225 static int kvm_get_xcrs(X86CPU *cpu)
4226 {
4227     CPUX86State *env = &cpu->env;
4228     int i, ret;
4229     struct kvm_xcrs xcrs;
4230 
4231     if (!has_xcrs) {
4232         return 0;
4233     }
4234 
4235     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
4236     if (ret < 0) {
4237         return ret;
4238     }
4239 
4240     for (i = 0; i < xcrs.nr_xcrs; i++) {
4241         /* Only support xcr0 now */
4242         if (xcrs.xcrs[i].xcr == 0) {
4243             env->xcr0 = xcrs.xcrs[i].value;
4244             break;
4245         }
4246     }
4247     return 0;
4248 }
4249 
4250 static int kvm_get_sregs(X86CPU *cpu)
4251 {
4252     CPUX86State *env = &cpu->env;
4253     struct kvm_sregs sregs;
4254     int ret;
4255 
4256     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
4257     if (ret < 0) {
4258         return ret;
4259     }
4260 
4261     /*
4262      * The interrupt_bitmap is ignored because KVM_GET_SREGS is
4263      * always preceded by KVM_GET_VCPU_EVENTS.
4264      */
4265 
4266     get_seg(&env->segs[R_CS], &sregs.cs);
4267     get_seg(&env->segs[R_DS], &sregs.ds);
4268     get_seg(&env->segs[R_ES], &sregs.es);
4269     get_seg(&env->segs[R_FS], &sregs.fs);
4270     get_seg(&env->segs[R_GS], &sregs.gs);
4271     get_seg(&env->segs[R_SS], &sregs.ss);
4272 
4273     get_seg(&env->tr, &sregs.tr);
4274     get_seg(&env->ldt, &sregs.ldt);
4275 
4276     env->idt.limit = sregs.idt.limit;
4277     env->idt.base = sregs.idt.base;
4278     env->gdt.limit = sregs.gdt.limit;
4279     env->gdt.base = sregs.gdt.base;
4280 
4281     env->cr[0] = sregs.cr0;
4282     env->cr[2] = sregs.cr2;
4283     env->cr[3] = sregs.cr3;
4284     env->cr[4] = sregs.cr4;
4285 
4286     env->efer = sregs.efer;
4287     if (sev_es_enabled() && env->efer & MSR_EFER_LME &&
4288         env->cr[0] & CR0_PG_MASK) {
4289         env->efer |= MSR_EFER_LMA;
4290     }
4291 
4292     /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
4293     x86_update_hflags(env);
4294 
4295     return 0;
4296 }
4297 
4298 static int kvm_get_sregs2(X86CPU *cpu)
4299 {
4300     CPUX86State *env = &cpu->env;
4301     struct kvm_sregs2 sregs;
4302     int i, ret;
4303 
4304     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS2, &sregs);
4305     if (ret < 0) {
4306         return ret;
4307     }
4308 
4309     get_seg(&env->segs[R_CS], &sregs.cs);
4310     get_seg(&env->segs[R_DS], &sregs.ds);
4311     get_seg(&env->segs[R_ES], &sregs.es);
4312     get_seg(&env->segs[R_FS], &sregs.fs);
4313     get_seg(&env->segs[R_GS], &sregs.gs);
4314     get_seg(&env->segs[R_SS], &sregs.ss);
4315 
4316     get_seg(&env->tr, &sregs.tr);
4317     get_seg(&env->ldt, &sregs.ldt);
4318 
4319     env->idt.limit = sregs.idt.limit;
4320     env->idt.base = sregs.idt.base;
4321     env->gdt.limit = sregs.gdt.limit;
4322     env->gdt.base = sregs.gdt.base;
4323 
4324     env->cr[0] = sregs.cr0;
4325     env->cr[2] = sregs.cr2;
4326     env->cr[3] = sregs.cr3;
4327     env->cr[4] = sregs.cr4;
4328 
4329     env->efer = sregs.efer;
4330     if (sev_es_enabled() && env->efer & MSR_EFER_LME &&
4331         env->cr[0] & CR0_PG_MASK) {
4332         env->efer |= MSR_EFER_LMA;
4333     }
4334 
4335     env->pdptrs_valid = sregs.flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
4336 
4337     if (env->pdptrs_valid) {
4338         for (i = 0; i < 4; i++) {
4339             env->pdptrs[i] = sregs.pdptrs[i];
4340         }
4341     }
4342 
4343     /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
4344     x86_update_hflags(env);
4345 
4346     return 0;
4347 }
4348 
4349 static int kvm_get_msrs(X86CPU *cpu)
4350 {
4351     CPUX86State *env = &cpu->env;
4352     struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
4353     int ret, i;
4354     uint64_t mtrr_top_bits;
4355 
4356     kvm_msr_buf_reset(cpu);
4357 
4358     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
4359     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
4360     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
4361     kvm_msr_entry_add(cpu, MSR_PAT, 0);
4362     if (has_msr_star) {
4363         kvm_msr_entry_add(cpu, MSR_STAR, 0);
4364     }
4365     if (has_msr_hsave_pa) {
4366         kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
4367     }
4368     if (has_msr_tsc_aux) {
4369         kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
4370     }
4371     if (has_msr_tsc_adjust) {
4372         kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
4373     }
4374     if (has_msr_tsc_deadline) {
4375         kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
4376     }
4377     if (has_msr_misc_enable) {
4378         kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
4379     }
4380     if (has_msr_smbase) {
4381         kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
4382     }
4383     if (has_msr_smi_count) {
4384         kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
4385     }
4386     if (has_msr_feature_control) {
4387         kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
4388     }
4389     if (has_msr_pkrs) {
4390         kvm_msr_entry_add(cpu, MSR_IA32_PKRS, 0);
4391     }
4392     if (has_msr_bndcfgs) {
4393         kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
4394     }
4395     if (has_msr_xss) {
4396         kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
4397     }
4398     if (has_msr_umwait) {
4399         kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, 0);
4400     }
4401     if (has_msr_spec_ctrl) {
4402         kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
4403     }
4404     if (has_tsc_scale_msr) {
4405         kvm_msr_entry_add(cpu, MSR_AMD64_TSC_RATIO, 0);
4406     }
4407 
4408     if (has_msr_tsx_ctrl) {
4409         kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, 0);
4410     }
4411     if (has_msr_virt_ssbd) {
4412         kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, 0);
4413     }
4414     if (!env->tsc_valid) {
4415         kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
4416         env->tsc_valid = !runstate_is_running();
4417     }
4418     if (has_msr_hwcr) {
4419         kvm_msr_entry_add(cpu, MSR_K7_HWCR, 0);
4420     }
4421 
4422 #ifdef TARGET_X86_64
4423     if (lm_capable_kernel) {
4424         kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
4425         kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
4426         kvm_msr_entry_add(cpu, MSR_FMASK, 0);
4427         kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
4428         if (env->features[FEAT_7_1_EAX] & CPUID_7_1_EAX_FRED) {
4429             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP0, 0);
4430             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP1, 0);
4431             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP2, 0);
4432             kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP3, 0);
4433             kvm_msr_entry_add(cpu, MSR_IA32_FRED_STKLVLS, 0);
4434             kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP1, 0);
4435             kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP2, 0);
4436             kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP3, 0);
4437             kvm_msr_entry_add(cpu, MSR_IA32_FRED_CONFIG, 0);
4438         }
4439     }
4440 #endif
4441     kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
4442     kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
4443     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
4444         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, 0);
4445     }
4446     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
4447         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
4448     }
4449     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
4450         kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
4451     }
4452     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
4453         kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
4454     }
4455     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
4456         kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, 1);
4457     }
4458     if (has_architectural_pmu_version > 0) {
4459         if (has_architectural_pmu_version > 1) {
4460             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
4461             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
4462             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
4463             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
4464         }
4465         for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
4466             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
4467         }
4468         for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
4469             kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
4470             kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
4471         }
4472     }
4473 
4474     if (env->mcg_cap) {
4475         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
4476         kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
4477         if (has_msr_mcg_ext_ctl) {
4478             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
4479         }
4480         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
4481             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
4482         }
4483     }
4484 
4485     if (has_msr_hv_hypercall) {
4486         kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
4487         kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
4488     }
4489     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
4490         kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
4491     }
4492     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
4493         kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
4494     }
4495     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
4496         kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL, 0);
4497         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL, 0);
4498         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS, 0);
4499     }
4500     if (has_msr_hv_syndbg_options) {
4501         kvm_msr_entry_add(cpu, HV_X64_MSR_SYNDBG_OPTIONS, 0);
4502     }
4503     if (has_msr_hv_crash) {
4504         int j;
4505 
4506         for (j = 0; j < HV_CRASH_PARAMS; j++) {
4507             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
4508         }
4509     }
4510     if (has_msr_hv_runtime) {
4511         kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
4512     }
4513     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
4514         uint32_t msr;
4515 
4516         kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
4517         kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
4518         kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
4519         for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
4520             kvm_msr_entry_add(cpu, msr, 0);
4521         }
4522     }
4523     if (has_msr_hv_stimer) {
4524         uint32_t msr;
4525 
4526         for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
4527              msr++) {
4528             kvm_msr_entry_add(cpu, msr, 0);
4529         }
4530     }
4531     if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
4532         kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
4533         kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
4534         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
4535         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
4536         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
4537         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
4538         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
4539         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
4540         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
4541         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
4542         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
4543         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
4544         for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
4545             kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
4546             kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
4547         }
4548     }
4549 
4550     if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
4551         int addr_num =
4552             kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
4553 
4554         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
4555         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
4556         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
4557         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
4558         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
4559         for (i = 0; i < addr_num; i++) {
4560             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
4561         }
4562     }
4563 
4564     if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_SGX_LC) {
4565         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH0, 0);
4566         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH1, 0);
4567         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH2, 0);
4568         kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH3, 0);
4569     }
4570 
4571     if (env->features[FEAT_XSAVE] & CPUID_D_1_EAX_XFD) {
4572         kvm_msr_entry_add(cpu, MSR_IA32_XFD, 0);
4573         kvm_msr_entry_add(cpu, MSR_IA32_XFD_ERR, 0);
4574     }
4575 
4576     if (kvm_enabled() && cpu->enable_pmu &&
4577         (env->features[FEAT_7_0_EDX] & CPUID_7_0_EDX_ARCH_LBR)) {
4578         uint64_t depth;
4579 
4580         ret = kvm_get_one_msr(cpu, MSR_ARCH_LBR_DEPTH, &depth);
4581         if (ret == 1 && depth == ARCH_LBR_NR_ENTRIES) {
4582             kvm_msr_entry_add(cpu, MSR_ARCH_LBR_CTL, 0);
4583             kvm_msr_entry_add(cpu, MSR_ARCH_LBR_DEPTH, 0);
4584 
4585             for (i = 0; i < ARCH_LBR_NR_ENTRIES; i++) {
4586                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_FROM_0 + i, 0);
4587                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_TO_0 + i, 0);
4588                 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_INFO_0 + i, 0);
4589             }
4590         }
4591     }
4592 
4593     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
4594     if (ret < 0) {
4595         return ret;
4596     }
4597 
4598     if (ret < cpu->kvm_msr_buf->nmsrs) {
4599         struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
4600         error_report("error: failed to get MSR 0x%" PRIx32,
4601                      (uint32_t)e->index);
4602     }
4603 
4604     assert(ret == cpu->kvm_msr_buf->nmsrs);
4605     /*
4606      * MTRR masks: Each mask consists of 5 parts
4607      * a  10..0: must be zero
4608      * b  11   : valid bit
4609      * c n-1.12: actual mask bits
4610      * d  51..n: reserved must be zero
4611      * e  63.52: reserved must be zero
4612      *
4613      * 'n' is the number of physical bits supported by the CPU and is
4614      * apparently always <= 52.   We know our 'n' but don't know what
4615      * the destinations 'n' is; it might be smaller, in which case
4616      * it masks (c) on loading. It might be larger, in which case
4617      * we fill 'd' so that d..c is consistent irrespetive of the 'n'
4618      * we're migrating to.
4619      */
4620 
4621     if (cpu->fill_mtrr_mask) {
4622         QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
4623         assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
4624         mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
4625     } else {
4626         mtrr_top_bits = 0;
4627     }
4628 
4629     for (i = 0; i < ret; i++) {
4630         uint32_t index = msrs[i].index;
4631         switch (index) {
4632         case MSR_IA32_SYSENTER_CS:
4633             env->sysenter_cs = msrs[i].data;
4634             break;
4635         case MSR_IA32_SYSENTER_ESP:
4636             env->sysenter_esp = msrs[i].data;
4637             break;
4638         case MSR_IA32_SYSENTER_EIP:
4639             env->sysenter_eip = msrs[i].data;
4640             break;
4641         case MSR_PAT:
4642             env->pat = msrs[i].data;
4643             break;
4644         case MSR_STAR:
4645             env->star = msrs[i].data;
4646             break;
4647 #ifdef TARGET_X86_64
4648         case MSR_CSTAR:
4649             env->cstar = msrs[i].data;
4650             break;
4651         case MSR_KERNELGSBASE:
4652             env->kernelgsbase = msrs[i].data;
4653             break;
4654         case MSR_FMASK:
4655             env->fmask = msrs[i].data;
4656             break;
4657         case MSR_LSTAR:
4658             env->lstar = msrs[i].data;
4659             break;
4660         case MSR_IA32_FRED_RSP0:
4661             env->fred_rsp0 = msrs[i].data;
4662             break;
4663         case MSR_IA32_FRED_RSP1:
4664             env->fred_rsp1 = msrs[i].data;
4665             break;
4666         case MSR_IA32_FRED_RSP2:
4667             env->fred_rsp2 = msrs[i].data;
4668             break;
4669         case MSR_IA32_FRED_RSP3:
4670             env->fred_rsp3 = msrs[i].data;
4671             break;
4672         case MSR_IA32_FRED_STKLVLS:
4673             env->fred_stklvls = msrs[i].data;
4674             break;
4675         case MSR_IA32_FRED_SSP1:
4676             env->fred_ssp1 = msrs[i].data;
4677             break;
4678         case MSR_IA32_FRED_SSP2:
4679             env->fred_ssp2 = msrs[i].data;
4680             break;
4681         case MSR_IA32_FRED_SSP3:
4682             env->fred_ssp3 = msrs[i].data;
4683             break;
4684         case MSR_IA32_FRED_CONFIG:
4685             env->fred_config = msrs[i].data;
4686             break;
4687 #endif
4688         case MSR_IA32_TSC:
4689             env->tsc = msrs[i].data;
4690             break;
4691         case MSR_TSC_AUX:
4692             env->tsc_aux = msrs[i].data;
4693             break;
4694         case MSR_TSC_ADJUST:
4695             env->tsc_adjust = msrs[i].data;
4696             break;
4697         case MSR_IA32_TSCDEADLINE:
4698             env->tsc_deadline = msrs[i].data;
4699             break;
4700         case MSR_VM_HSAVE_PA:
4701             env->vm_hsave = msrs[i].data;
4702             break;
4703         case MSR_KVM_SYSTEM_TIME:
4704             env->system_time_msr = msrs[i].data;
4705             break;
4706         case MSR_KVM_WALL_CLOCK:
4707             env->wall_clock_msr = msrs[i].data;
4708             break;
4709         case MSR_MCG_STATUS:
4710             env->mcg_status = msrs[i].data;
4711             break;
4712         case MSR_MCG_CTL:
4713             env->mcg_ctl = msrs[i].data;
4714             break;
4715         case MSR_MCG_EXT_CTL:
4716             env->mcg_ext_ctl = msrs[i].data;
4717             break;
4718         case MSR_IA32_MISC_ENABLE:
4719             env->msr_ia32_misc_enable = msrs[i].data;
4720             break;
4721         case MSR_IA32_SMBASE:
4722             env->smbase = msrs[i].data;
4723             break;
4724         case MSR_SMI_COUNT:
4725             env->msr_smi_count = msrs[i].data;
4726             break;
4727         case MSR_IA32_FEATURE_CONTROL:
4728             env->msr_ia32_feature_control = msrs[i].data;
4729             break;
4730         case MSR_IA32_BNDCFGS:
4731             env->msr_bndcfgs = msrs[i].data;
4732             break;
4733         case MSR_IA32_XSS:
4734             env->xss = msrs[i].data;
4735             break;
4736         case MSR_IA32_UMWAIT_CONTROL:
4737             env->umwait = msrs[i].data;
4738             break;
4739         case MSR_IA32_PKRS:
4740             env->pkrs = msrs[i].data;
4741             break;
4742         default:
4743             if (msrs[i].index >= MSR_MC0_CTL &&
4744                 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
4745                 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
4746             }
4747             break;
4748         case MSR_KVM_ASYNC_PF_EN:
4749             env->async_pf_en_msr = msrs[i].data;
4750             break;
4751         case MSR_KVM_ASYNC_PF_INT:
4752             env->async_pf_int_msr = msrs[i].data;
4753             break;
4754         case MSR_KVM_PV_EOI_EN:
4755             env->pv_eoi_en_msr = msrs[i].data;
4756             break;
4757         case MSR_KVM_STEAL_TIME:
4758             env->steal_time_msr = msrs[i].data;
4759             break;
4760         case MSR_KVM_POLL_CONTROL: {
4761             env->poll_control_msr = msrs[i].data;
4762             break;
4763         }
4764         case MSR_CORE_PERF_FIXED_CTR_CTRL:
4765             env->msr_fixed_ctr_ctrl = msrs[i].data;
4766             break;
4767         case MSR_CORE_PERF_GLOBAL_CTRL:
4768             env->msr_global_ctrl = msrs[i].data;
4769             break;
4770         case MSR_CORE_PERF_GLOBAL_STATUS:
4771             env->msr_global_status = msrs[i].data;
4772             break;
4773         case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
4774             env->msr_global_ovf_ctrl = msrs[i].data;
4775             break;
4776         case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
4777             env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
4778             break;
4779         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
4780             env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
4781             break;
4782         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
4783             env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
4784             break;
4785         case HV_X64_MSR_HYPERCALL:
4786             env->msr_hv_hypercall = msrs[i].data;
4787             break;
4788         case HV_X64_MSR_GUEST_OS_ID:
4789             env->msr_hv_guest_os_id = msrs[i].data;
4790             break;
4791         case HV_X64_MSR_APIC_ASSIST_PAGE:
4792             env->msr_hv_vapic = msrs[i].data;
4793             break;
4794         case HV_X64_MSR_REFERENCE_TSC:
4795             env->msr_hv_tsc = msrs[i].data;
4796             break;
4797         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4798             env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
4799             break;
4800         case HV_X64_MSR_VP_RUNTIME:
4801             env->msr_hv_runtime = msrs[i].data;
4802             break;
4803         case HV_X64_MSR_SCONTROL:
4804             env->msr_hv_synic_control = msrs[i].data;
4805             break;
4806         case HV_X64_MSR_SIEFP:
4807             env->msr_hv_synic_evt_page = msrs[i].data;
4808             break;
4809         case HV_X64_MSR_SIMP:
4810             env->msr_hv_synic_msg_page = msrs[i].data;
4811             break;
4812         case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
4813             env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
4814             break;
4815         case HV_X64_MSR_STIMER0_CONFIG:
4816         case HV_X64_MSR_STIMER1_CONFIG:
4817         case HV_X64_MSR_STIMER2_CONFIG:
4818         case HV_X64_MSR_STIMER3_CONFIG:
4819             env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
4820                                 msrs[i].data;
4821             break;
4822         case HV_X64_MSR_STIMER0_COUNT:
4823         case HV_X64_MSR_STIMER1_COUNT:
4824         case HV_X64_MSR_STIMER2_COUNT:
4825         case HV_X64_MSR_STIMER3_COUNT:
4826             env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
4827                                 msrs[i].data;
4828             break;
4829         case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4830             env->msr_hv_reenlightenment_control = msrs[i].data;
4831             break;
4832         case HV_X64_MSR_TSC_EMULATION_CONTROL:
4833             env->msr_hv_tsc_emulation_control = msrs[i].data;
4834             break;
4835         case HV_X64_MSR_TSC_EMULATION_STATUS:
4836             env->msr_hv_tsc_emulation_status = msrs[i].data;
4837             break;
4838         case HV_X64_MSR_SYNDBG_OPTIONS:
4839             env->msr_hv_syndbg_options = msrs[i].data;
4840             break;
4841         case MSR_MTRRdefType:
4842             env->mtrr_deftype = msrs[i].data;
4843             break;
4844         case MSR_MTRRfix64K_00000:
4845             env->mtrr_fixed[0] = msrs[i].data;
4846             break;
4847         case MSR_MTRRfix16K_80000:
4848             env->mtrr_fixed[1] = msrs[i].data;
4849             break;
4850         case MSR_MTRRfix16K_A0000:
4851             env->mtrr_fixed[2] = msrs[i].data;
4852             break;
4853         case MSR_MTRRfix4K_C0000:
4854             env->mtrr_fixed[3] = msrs[i].data;
4855             break;
4856         case MSR_MTRRfix4K_C8000:
4857             env->mtrr_fixed[4] = msrs[i].data;
4858             break;
4859         case MSR_MTRRfix4K_D0000:
4860             env->mtrr_fixed[5] = msrs[i].data;
4861             break;
4862         case MSR_MTRRfix4K_D8000:
4863             env->mtrr_fixed[6] = msrs[i].data;
4864             break;
4865         case MSR_MTRRfix4K_E0000:
4866             env->mtrr_fixed[7] = msrs[i].data;
4867             break;
4868         case MSR_MTRRfix4K_E8000:
4869             env->mtrr_fixed[8] = msrs[i].data;
4870             break;
4871         case MSR_MTRRfix4K_F0000:
4872             env->mtrr_fixed[9] = msrs[i].data;
4873             break;
4874         case MSR_MTRRfix4K_F8000:
4875             env->mtrr_fixed[10] = msrs[i].data;
4876             break;
4877         case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
4878             if (index & 1) {
4879                 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
4880                                                                mtrr_top_bits;
4881             } else {
4882                 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
4883             }
4884             break;
4885         case MSR_IA32_SPEC_CTRL:
4886             env->spec_ctrl = msrs[i].data;
4887             break;
4888         case MSR_AMD64_TSC_RATIO:
4889             env->amd_tsc_scale_msr = msrs[i].data;
4890             break;
4891         case MSR_IA32_TSX_CTRL:
4892             env->tsx_ctrl = msrs[i].data;
4893             break;
4894         case MSR_VIRT_SSBD:
4895             env->virt_ssbd = msrs[i].data;
4896             break;
4897         case MSR_IA32_RTIT_CTL:
4898             env->msr_rtit_ctrl = msrs[i].data;
4899             break;
4900         case MSR_IA32_RTIT_STATUS:
4901             env->msr_rtit_status = msrs[i].data;
4902             break;
4903         case MSR_IA32_RTIT_OUTPUT_BASE:
4904             env->msr_rtit_output_base = msrs[i].data;
4905             break;
4906         case MSR_IA32_RTIT_OUTPUT_MASK:
4907             env->msr_rtit_output_mask = msrs[i].data;
4908             break;
4909         case MSR_IA32_RTIT_CR3_MATCH:
4910             env->msr_rtit_cr3_match = msrs[i].data;
4911             break;
4912         case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
4913             env->msr_rtit_addrs[index - MSR_IA32_RTIT_ADDR0_A] = msrs[i].data;
4914             break;
4915         case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
4916             env->msr_ia32_sgxlepubkeyhash[index - MSR_IA32_SGXLEPUBKEYHASH0] =
4917                            msrs[i].data;
4918             break;
4919         case MSR_IA32_XFD:
4920             env->msr_xfd = msrs[i].data;
4921             break;
4922         case MSR_IA32_XFD_ERR:
4923             env->msr_xfd_err = msrs[i].data;
4924             break;
4925         case MSR_ARCH_LBR_CTL:
4926             env->msr_lbr_ctl = msrs[i].data;
4927             break;
4928         case MSR_ARCH_LBR_DEPTH:
4929             env->msr_lbr_depth = msrs[i].data;
4930             break;
4931         case MSR_ARCH_LBR_FROM_0 ... MSR_ARCH_LBR_FROM_0 + 31:
4932             env->lbr_records[index - MSR_ARCH_LBR_FROM_0].from = msrs[i].data;
4933             break;
4934         case MSR_ARCH_LBR_TO_0 ... MSR_ARCH_LBR_TO_0 + 31:
4935             env->lbr_records[index - MSR_ARCH_LBR_TO_0].to = msrs[i].data;
4936             break;
4937         case MSR_ARCH_LBR_INFO_0 ... MSR_ARCH_LBR_INFO_0 + 31:
4938             env->lbr_records[index - MSR_ARCH_LBR_INFO_0].info = msrs[i].data;
4939             break;
4940         case MSR_K7_HWCR:
4941             env->msr_hwcr = msrs[i].data;
4942             break;
4943         }
4944     }
4945 
4946     return 0;
4947 }
4948 
4949 static int kvm_put_mp_state(X86CPU *cpu)
4950 {
4951     struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
4952 
4953     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
4954 }
4955 
4956 static int kvm_get_mp_state(X86CPU *cpu)
4957 {
4958     CPUState *cs = CPU(cpu);
4959     CPUX86State *env = &cpu->env;
4960     struct kvm_mp_state mp_state;
4961     int ret;
4962 
4963     ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
4964     if (ret < 0) {
4965         return ret;
4966     }
4967     env->mp_state = mp_state.mp_state;
4968     if (kvm_irqchip_in_kernel()) {
4969         cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
4970     }
4971     return 0;
4972 }
4973 
4974 static int kvm_get_apic(X86CPU *cpu)
4975 {
4976     DeviceState *apic = cpu->apic_state;
4977     struct kvm_lapic_state kapic;
4978     int ret;
4979 
4980     if (apic && kvm_irqchip_in_kernel()) {
4981         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
4982         if (ret < 0) {
4983             return ret;
4984         }
4985 
4986         kvm_get_apic_state(apic, &kapic);
4987     }
4988     return 0;
4989 }
4990 
4991 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
4992 {
4993     CPUState *cs = CPU(cpu);
4994     CPUX86State *env = &cpu->env;
4995     struct kvm_vcpu_events events = {};
4996 
4997     events.flags = 0;
4998 
4999     if (has_exception_payload) {
5000         events.flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
5001         events.exception.pending = env->exception_pending;
5002         events.exception_has_payload = env->exception_has_payload;
5003         events.exception_payload = env->exception_payload;
5004     }
5005     events.exception.nr = env->exception_nr;
5006     events.exception.injected = env->exception_injected;
5007     events.exception.has_error_code = env->has_error_code;
5008     events.exception.error_code = env->error_code;
5009 
5010     events.interrupt.injected = (env->interrupt_injected >= 0);
5011     events.interrupt.nr = env->interrupt_injected;
5012     events.interrupt.soft = env->soft_interrupt;
5013 
5014     events.nmi.injected = env->nmi_injected;
5015     events.nmi.pending = env->nmi_pending;
5016     events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
5017 
5018     events.sipi_vector = env->sipi_vector;
5019 
5020     if (has_msr_smbase) {
5021         events.flags |= KVM_VCPUEVENT_VALID_SMM;
5022         events.smi.smm = !!(env->hflags & HF_SMM_MASK);
5023         events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
5024         if (kvm_irqchip_in_kernel()) {
5025             /* As soon as these are moved to the kernel, remove them
5026              * from cs->interrupt_request.
5027              */
5028             events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
5029             events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
5030             cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
5031         } else {
5032             /* Keep these in cs->interrupt_request.  */
5033             events.smi.pending = 0;
5034             events.smi.latched_init = 0;
5035         }
5036     }
5037 
5038     if (level >= KVM_PUT_RESET_STATE) {
5039         events.flags |= KVM_VCPUEVENT_VALID_NMI_PENDING;
5040         if (env->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
5041             events.flags |= KVM_VCPUEVENT_VALID_SIPI_VECTOR;
5042         }
5043     }
5044 
5045     if (has_triple_fault_event) {
5046         events.flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
5047         events.triple_fault.pending = env->triple_fault_pending;
5048     }
5049 
5050     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
5051 }
5052 
5053 static int kvm_get_vcpu_events(X86CPU *cpu)
5054 {
5055     CPUX86State *env = &cpu->env;
5056     struct kvm_vcpu_events events;
5057     int ret;
5058 
5059     memset(&events, 0, sizeof(events));
5060     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
5061     if (ret < 0) {
5062        return ret;
5063     }
5064 
5065     if (events.flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
5066         env->exception_pending = events.exception.pending;
5067         env->exception_has_payload = events.exception_has_payload;
5068         env->exception_payload = events.exception_payload;
5069     } else {
5070         env->exception_pending = 0;
5071         env->exception_has_payload = false;
5072     }
5073     env->exception_injected = events.exception.injected;
5074     env->exception_nr =
5075         (env->exception_pending || env->exception_injected) ?
5076         events.exception.nr : -1;
5077     env->has_error_code = events.exception.has_error_code;
5078     env->error_code = events.exception.error_code;
5079 
5080     env->interrupt_injected =
5081         events.interrupt.injected ? events.interrupt.nr : -1;
5082     env->soft_interrupt = events.interrupt.soft;
5083 
5084     env->nmi_injected = events.nmi.injected;
5085     env->nmi_pending = events.nmi.pending;
5086     if (events.nmi.masked) {
5087         env->hflags2 |= HF2_NMI_MASK;
5088     } else {
5089         env->hflags2 &= ~HF2_NMI_MASK;
5090     }
5091 
5092     if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
5093         if (events.smi.smm) {
5094             env->hflags |= HF_SMM_MASK;
5095         } else {
5096             env->hflags &= ~HF_SMM_MASK;
5097         }
5098         if (events.smi.pending) {
5099             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
5100         } else {
5101             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
5102         }
5103         if (events.smi.smm_inside_nmi) {
5104             env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
5105         } else {
5106             env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
5107         }
5108         if (events.smi.latched_init) {
5109             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
5110         } else {
5111             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
5112         }
5113     }
5114 
5115     if (events.flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
5116         env->triple_fault_pending = events.triple_fault.pending;
5117     }
5118 
5119     env->sipi_vector = events.sipi_vector;
5120 
5121     return 0;
5122 }
5123 
5124 static int kvm_put_debugregs(X86CPU *cpu)
5125 {
5126     CPUX86State *env = &cpu->env;
5127     struct kvm_debugregs dbgregs;
5128     int i;
5129 
5130     memset(&dbgregs, 0, sizeof(dbgregs));
5131     for (i = 0; i < 4; i++) {
5132         dbgregs.db[i] = env->dr[i];
5133     }
5134     dbgregs.dr6 = env->dr[6];
5135     dbgregs.dr7 = env->dr[7];
5136     dbgregs.flags = 0;
5137 
5138     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
5139 }
5140 
5141 static int kvm_get_debugregs(X86CPU *cpu)
5142 {
5143     CPUX86State *env = &cpu->env;
5144     struct kvm_debugregs dbgregs;
5145     int i, ret;
5146 
5147     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
5148     if (ret < 0) {
5149         return ret;
5150     }
5151     for (i = 0; i < 4; i++) {
5152         env->dr[i] = dbgregs.db[i];
5153     }
5154     env->dr[4] = env->dr[6] = dbgregs.dr6;
5155     env->dr[5] = env->dr[7] = dbgregs.dr7;
5156 
5157     return 0;
5158 }
5159 
5160 static int kvm_put_nested_state(X86CPU *cpu)
5161 {
5162     CPUX86State *env = &cpu->env;
5163     int max_nested_state_len = kvm_max_nested_state_length();
5164 
5165     if (!env->nested_state) {
5166         return 0;
5167     }
5168 
5169     /*
5170      * Copy flags that are affected by reset from env->hflags and env->hflags2.
5171      */
5172     if (env->hflags & HF_GUEST_MASK) {
5173         env->nested_state->flags |= KVM_STATE_NESTED_GUEST_MODE;
5174     } else {
5175         env->nested_state->flags &= ~KVM_STATE_NESTED_GUEST_MODE;
5176     }
5177 
5178     /* Don't set KVM_STATE_NESTED_GIF_SET on VMX as it is illegal */
5179     if (cpu_has_svm(env) && (env->hflags2 & HF2_GIF_MASK)) {
5180         env->nested_state->flags |= KVM_STATE_NESTED_GIF_SET;
5181     } else {
5182         env->nested_state->flags &= ~KVM_STATE_NESTED_GIF_SET;
5183     }
5184 
5185     assert(env->nested_state->size <= max_nested_state_len);
5186     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_NESTED_STATE, env->nested_state);
5187 }
5188 
5189 static int kvm_get_nested_state(X86CPU *cpu)
5190 {
5191     CPUX86State *env = &cpu->env;
5192     int max_nested_state_len = kvm_max_nested_state_length();
5193     int ret;
5194 
5195     if (!env->nested_state) {
5196         return 0;
5197     }
5198 
5199     /*
5200      * It is possible that migration restored a smaller size into
5201      * nested_state->hdr.size than what our kernel support.
5202      * We preserve migration origin nested_state->hdr.size for
5203      * call to KVM_SET_NESTED_STATE but wish that our next call
5204      * to KVM_GET_NESTED_STATE will use max size our kernel support.
5205      */
5206     env->nested_state->size = max_nested_state_len;
5207 
5208     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_NESTED_STATE, env->nested_state);
5209     if (ret < 0) {
5210         return ret;
5211     }
5212 
5213     /*
5214      * Copy flags that are affected by reset to env->hflags and env->hflags2.
5215      */
5216     if (env->nested_state->flags & KVM_STATE_NESTED_GUEST_MODE) {
5217         env->hflags |= HF_GUEST_MASK;
5218     } else {
5219         env->hflags &= ~HF_GUEST_MASK;
5220     }
5221 
5222     /* Keep HF2_GIF_MASK set on !SVM as x86_cpu_pending_interrupt() needs it */
5223     if (cpu_has_svm(env)) {
5224         if (env->nested_state->flags & KVM_STATE_NESTED_GIF_SET) {
5225             env->hflags2 |= HF2_GIF_MASK;
5226         } else {
5227             env->hflags2 &= ~HF2_GIF_MASK;
5228         }
5229     }
5230 
5231     return ret;
5232 }
5233 
5234 int kvm_arch_put_registers(CPUState *cpu, int level, Error **errp)
5235 {
5236     X86CPU *x86_cpu = X86_CPU(cpu);
5237     int ret;
5238 
5239     assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
5240 
5241     /*
5242      * Put MSR_IA32_FEATURE_CONTROL first, this ensures the VM gets out of VMX
5243      * root operation upon vCPU reset. kvm_put_msr_feature_control() should also
5244      * precede kvm_put_nested_state() when 'real' nested state is set.
5245      */
5246     if (level >= KVM_PUT_RESET_STATE) {
5247         ret = kvm_put_msr_feature_control(x86_cpu);
5248         if (ret < 0) {
5249             error_setg_errno(errp, -ret, "Failed to set feature control MSR");
5250             return ret;
5251         }
5252     }
5253 
5254     /* must be before kvm_put_nested_state so that EFER.SVME is set */
5255     ret = has_sregs2 ? kvm_put_sregs2(x86_cpu) : kvm_put_sregs(x86_cpu);
5256     if (ret < 0) {
5257         error_setg_errno(errp, -ret, "Failed to set special registers");
5258         return ret;
5259     }
5260 
5261     if (level >= KVM_PUT_RESET_STATE) {
5262         ret = kvm_put_nested_state(x86_cpu);
5263         if (ret < 0) {
5264             error_setg_errno(errp, -ret, "Failed to set nested state");
5265             return ret;
5266         }
5267     }
5268 
5269     if (level == KVM_PUT_FULL_STATE) {
5270         /* We don't check for kvm_arch_set_tsc_khz() errors here,
5271          * because TSC frequency mismatch shouldn't abort migration,
5272          * unless the user explicitly asked for a more strict TSC
5273          * setting (e.g. using an explicit "tsc-freq" option).
5274          */
5275         kvm_arch_set_tsc_khz(cpu);
5276     }
5277 
5278 #ifdef CONFIG_XEN_EMU
5279     if (xen_mode == XEN_EMULATE && level == KVM_PUT_FULL_STATE) {
5280         ret = kvm_put_xen_state(cpu);
5281         if (ret < 0) {
5282             error_setg_errno(errp, -ret, "Failed to set Xen state");
5283             return ret;
5284         }
5285     }
5286 #endif
5287 
5288     ret = kvm_getput_regs(x86_cpu, 1);
5289     if (ret < 0) {
5290         error_setg_errno(errp, -ret, "Failed to set general purpose registers");
5291         return ret;
5292     }
5293     ret = kvm_put_xsave(x86_cpu);
5294     if (ret < 0) {
5295         error_setg_errno(errp, -ret, "Failed to set XSAVE");
5296         return ret;
5297     }
5298     ret = kvm_put_xcrs(x86_cpu);
5299     if (ret < 0) {
5300         error_setg_errno(errp, -ret, "Failed to set XCRs");
5301         return ret;
5302     }
5303     ret = kvm_put_msrs(x86_cpu, level);
5304     if (ret < 0) {
5305         error_setg_errno(errp, -ret, "Failed to set MSRs");
5306         return ret;
5307     }
5308     ret = kvm_put_vcpu_events(x86_cpu, level);
5309     if (ret < 0) {
5310         error_setg_errno(errp, -ret, "Failed to set vCPU events");
5311         return ret;
5312     }
5313     if (level >= KVM_PUT_RESET_STATE) {
5314         ret = kvm_put_mp_state(x86_cpu);
5315         if (ret < 0) {
5316             error_setg_errno(errp, -ret, "Failed to set MP state");
5317             return ret;
5318         }
5319     }
5320 
5321     ret = kvm_put_tscdeadline_msr(x86_cpu);
5322     if (ret < 0) {
5323         error_setg_errno(errp, -ret, "Failed to set TSC deadline MSR");
5324         return ret;
5325     }
5326     ret = kvm_put_debugregs(x86_cpu);
5327     if (ret < 0) {
5328         error_setg_errno(errp, -ret, "Failed to set debug registers");
5329         return ret;
5330     }
5331     return 0;
5332 }
5333 
5334 int kvm_arch_get_registers(CPUState *cs, Error **errp)
5335 {
5336     X86CPU *cpu = X86_CPU(cs);
5337     int ret;
5338 
5339     assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
5340 
5341     ret = kvm_get_vcpu_events(cpu);
5342     if (ret < 0) {
5343         error_setg_errno(errp, -ret, "Failed to get vCPU events");
5344         goto out;
5345     }
5346     /*
5347      * KVM_GET_MPSTATE can modify CS and RIP, call it before
5348      * KVM_GET_REGS and KVM_GET_SREGS.
5349      */
5350     ret = kvm_get_mp_state(cpu);
5351     if (ret < 0) {
5352         error_setg_errno(errp, -ret, "Failed to get MP state");
5353         goto out;
5354     }
5355     ret = kvm_getput_regs(cpu, 0);
5356     if (ret < 0) {
5357         error_setg_errno(errp, -ret, "Failed to get general purpose registers");
5358         goto out;
5359     }
5360     ret = kvm_get_xsave(cpu);
5361     if (ret < 0) {
5362         error_setg_errno(errp, -ret, "Failed to get XSAVE");
5363         goto out;
5364     }
5365     ret = kvm_get_xcrs(cpu);
5366     if (ret < 0) {
5367         error_setg_errno(errp, -ret, "Failed to get XCRs");
5368         goto out;
5369     }
5370     ret = has_sregs2 ? kvm_get_sregs2(cpu) : kvm_get_sregs(cpu);
5371     if (ret < 0) {
5372         error_setg_errno(errp, -ret, "Failed to get special registers");
5373         goto out;
5374     }
5375     ret = kvm_get_msrs(cpu);
5376     if (ret < 0) {
5377         error_setg_errno(errp, -ret, "Failed to get MSRs");
5378         goto out;
5379     }
5380     ret = kvm_get_apic(cpu);
5381     if (ret < 0) {
5382         error_setg_errno(errp, -ret, "Failed to get APIC");
5383         goto out;
5384     }
5385     ret = kvm_get_debugregs(cpu);
5386     if (ret < 0) {
5387         error_setg_errno(errp, -ret, "Failed to get debug registers");
5388         goto out;
5389     }
5390     ret = kvm_get_nested_state(cpu);
5391     if (ret < 0) {
5392         error_setg_errno(errp, -ret, "Failed to get nested state");
5393         goto out;
5394     }
5395 #ifdef CONFIG_XEN_EMU
5396     if (xen_mode == XEN_EMULATE) {
5397         ret = kvm_get_xen_state(cs);
5398         if (ret < 0) {
5399             error_setg_errno(errp, -ret, "Failed to get Xen state");
5400             goto out;
5401         }
5402     }
5403 #endif
5404     ret = 0;
5405  out:
5406     cpu_sync_bndcs_hflags(&cpu->env);
5407     return ret;
5408 }
5409 
5410 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
5411 {
5412     X86CPU *x86_cpu = X86_CPU(cpu);
5413     CPUX86State *env = &x86_cpu->env;
5414     int ret;
5415 
5416     /* Inject NMI */
5417     if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
5418         if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
5419             bql_lock();
5420             cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
5421             bql_unlock();
5422             DPRINTF("injected NMI\n");
5423             ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
5424             if (ret < 0) {
5425                 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
5426                         strerror(-ret));
5427             }
5428         }
5429         if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
5430             bql_lock();
5431             cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
5432             bql_unlock();
5433             DPRINTF("injected SMI\n");
5434             ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
5435             if (ret < 0) {
5436                 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
5437                         strerror(-ret));
5438             }
5439         }
5440     }
5441 
5442     if (!kvm_pic_in_kernel()) {
5443         bql_lock();
5444     }
5445 
5446     /* Force the VCPU out of its inner loop to process any INIT requests
5447      * or (for userspace APIC, but it is cheap to combine the checks here)
5448      * pending TPR access reports.
5449      */
5450     if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
5451         if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
5452             !(env->hflags & HF_SMM_MASK)) {
5453             cpu->exit_request = 1;
5454         }
5455         if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
5456             cpu->exit_request = 1;
5457         }
5458     }
5459 
5460     if (!kvm_pic_in_kernel()) {
5461         /* Try to inject an interrupt if the guest can accept it */
5462         if (run->ready_for_interrupt_injection &&
5463             (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
5464             (env->eflags & IF_MASK)) {
5465             int irq;
5466 
5467             cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
5468             irq = cpu_get_pic_interrupt(env);
5469             if (irq >= 0) {
5470                 struct kvm_interrupt intr;
5471 
5472                 intr.irq = irq;
5473                 DPRINTF("injected interrupt %d\n", irq);
5474                 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
5475                 if (ret < 0) {
5476                     fprintf(stderr,
5477                             "KVM: injection failed, interrupt lost (%s)\n",
5478                             strerror(-ret));
5479                 }
5480             }
5481         }
5482 
5483         /* If we have an interrupt but the guest is not ready to receive an
5484          * interrupt, request an interrupt window exit.  This will
5485          * cause a return to userspace as soon as the guest is ready to
5486          * receive interrupts. */
5487         if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
5488             run->request_interrupt_window = 1;
5489         } else {
5490             run->request_interrupt_window = 0;
5491         }
5492 
5493         DPRINTF("setting tpr\n");
5494         run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
5495 
5496         bql_unlock();
5497     }
5498 }
5499 
5500 static void kvm_rate_limit_on_bus_lock(void)
5501 {
5502     uint64_t delay_ns = ratelimit_calculate_delay(&bus_lock_ratelimit_ctrl, 1);
5503 
5504     if (delay_ns) {
5505         g_usleep(delay_ns / SCALE_US);
5506     }
5507 }
5508 
5509 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
5510 {
5511     X86CPU *x86_cpu = X86_CPU(cpu);
5512     CPUX86State *env = &x86_cpu->env;
5513 
5514     if (run->flags & KVM_RUN_X86_SMM) {
5515         env->hflags |= HF_SMM_MASK;
5516     } else {
5517         env->hflags &= ~HF_SMM_MASK;
5518     }
5519     if (run->if_flag) {
5520         env->eflags |= IF_MASK;
5521     } else {
5522         env->eflags &= ~IF_MASK;
5523     }
5524     if (run->flags & KVM_RUN_X86_BUS_LOCK) {
5525         kvm_rate_limit_on_bus_lock();
5526     }
5527 
5528 #ifdef CONFIG_XEN_EMU
5529     /*
5530      * If the callback is asserted as a GSI (or PCI INTx) then check if
5531      * vcpu_info->evtchn_upcall_pending has been cleared, and deassert
5532      * the callback IRQ if so. Ideally we could hook into the PIC/IOAPIC
5533      * EOI and only resample then, exactly how the VFIO eventfd pairs
5534      * are designed to work for level triggered interrupts.
5535      */
5536     if (x86_cpu->env.xen_callback_asserted) {
5537         kvm_xen_maybe_deassert_callback(cpu);
5538     }
5539 #endif
5540 
5541     /* We need to protect the apic state against concurrent accesses from
5542      * different threads in case the userspace irqchip is used. */
5543     if (!kvm_irqchip_in_kernel()) {
5544         bql_lock();
5545     }
5546     cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
5547     cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
5548     if (!kvm_irqchip_in_kernel()) {
5549         bql_unlock();
5550     }
5551     return cpu_get_mem_attrs(env);
5552 }
5553 
5554 int kvm_arch_process_async_events(CPUState *cs)
5555 {
5556     X86CPU *cpu = X86_CPU(cs);
5557     CPUX86State *env = &cpu->env;
5558 
5559     if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
5560         /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
5561         assert(env->mcg_cap);
5562 
5563         cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
5564 
5565         kvm_cpu_synchronize_state(cs);
5566 
5567         if (env->exception_nr == EXCP08_DBLE) {
5568             /* this means triple fault */
5569             qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
5570             cs->exit_request = 1;
5571             return 0;
5572         }
5573         kvm_queue_exception(env, EXCP12_MCHK, 0, 0);
5574         env->has_error_code = 0;
5575 
5576         cs->halted = 0;
5577         if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
5578             env->mp_state = KVM_MP_STATE_RUNNABLE;
5579         }
5580     }
5581 
5582     if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
5583         !(env->hflags & HF_SMM_MASK)) {
5584         kvm_cpu_synchronize_state(cs);
5585         do_cpu_init(cpu);
5586     }
5587 
5588     if (kvm_irqchip_in_kernel()) {
5589         return 0;
5590     }
5591 
5592     if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
5593         cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
5594         apic_poll_irq(cpu->apic_state);
5595     }
5596     if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
5597          (env->eflags & IF_MASK)) ||
5598         (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
5599         cs->halted = 0;
5600     }
5601     if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
5602         kvm_cpu_synchronize_state(cs);
5603         do_cpu_sipi(cpu);
5604     }
5605     if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
5606         cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
5607         kvm_cpu_synchronize_state(cs);
5608         apic_handle_tpr_access_report(cpu->apic_state, env->eip,
5609                                       env->tpr_access_type);
5610     }
5611 
5612     return cs->halted;
5613 }
5614 
5615 static int kvm_handle_halt(X86CPU *cpu)
5616 {
5617     CPUState *cs = CPU(cpu);
5618     CPUX86State *env = &cpu->env;
5619 
5620     if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
5621           (env->eflags & IF_MASK)) &&
5622         !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
5623         cs->halted = 1;
5624         return EXCP_HLT;
5625     }
5626 
5627     return 0;
5628 }
5629 
5630 static int kvm_handle_tpr_access(X86CPU *cpu)
5631 {
5632     CPUState *cs = CPU(cpu);
5633     struct kvm_run *run = cs->kvm_run;
5634 
5635     apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
5636                                   run->tpr_access.is_write ? TPR_ACCESS_WRITE
5637                                                            : TPR_ACCESS_READ);
5638     return 1;
5639 }
5640 
5641 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
5642 {
5643     static const uint8_t int3 = 0xcc;
5644 
5645     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
5646         cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
5647         return -EINVAL;
5648     }
5649     return 0;
5650 }
5651 
5652 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
5653 {
5654     uint8_t int3;
5655 
5656     if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0)) {
5657         return -EINVAL;
5658     }
5659     if (int3 != 0xcc) {
5660         return 0;
5661     }
5662     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
5663         return -EINVAL;
5664     }
5665     return 0;
5666 }
5667 
5668 static struct {
5669     target_ulong addr;
5670     int len;
5671     int type;
5672 } hw_breakpoint[4];
5673 
5674 static int nb_hw_breakpoint;
5675 
5676 static int find_hw_breakpoint(target_ulong addr, int len, int type)
5677 {
5678     int n;
5679 
5680     for (n = 0; n < nb_hw_breakpoint; n++) {
5681         if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
5682             (hw_breakpoint[n].len == len || len == -1)) {
5683             return n;
5684         }
5685     }
5686     return -1;
5687 }
5688 
5689 int kvm_arch_insert_hw_breakpoint(vaddr addr, vaddr len, int type)
5690 {
5691     switch (type) {
5692     case GDB_BREAKPOINT_HW:
5693         len = 1;
5694         break;
5695     case GDB_WATCHPOINT_WRITE:
5696     case GDB_WATCHPOINT_ACCESS:
5697         switch (len) {
5698         case 1:
5699             break;
5700         case 2:
5701         case 4:
5702         case 8:
5703             if (addr & (len - 1)) {
5704                 return -EINVAL;
5705             }
5706             break;
5707         default:
5708             return -EINVAL;
5709         }
5710         break;
5711     default:
5712         return -ENOSYS;
5713     }
5714 
5715     if (nb_hw_breakpoint == 4) {
5716         return -ENOBUFS;
5717     }
5718     if (find_hw_breakpoint(addr, len, type) >= 0) {
5719         return -EEXIST;
5720     }
5721     hw_breakpoint[nb_hw_breakpoint].addr = addr;
5722     hw_breakpoint[nb_hw_breakpoint].len = len;
5723     hw_breakpoint[nb_hw_breakpoint].type = type;
5724     nb_hw_breakpoint++;
5725 
5726     return 0;
5727 }
5728 
5729 int kvm_arch_remove_hw_breakpoint(vaddr addr, vaddr len, int type)
5730 {
5731     int n;
5732 
5733     n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
5734     if (n < 0) {
5735         return -ENOENT;
5736     }
5737     nb_hw_breakpoint--;
5738     hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
5739 
5740     return 0;
5741 }
5742 
5743 void kvm_arch_remove_all_hw_breakpoints(void)
5744 {
5745     nb_hw_breakpoint = 0;
5746 }
5747 
5748 static CPUWatchpoint hw_watchpoint;
5749 
5750 static int kvm_handle_debug(X86CPU *cpu,
5751                             struct kvm_debug_exit_arch *arch_info)
5752 {
5753     CPUState *cs = CPU(cpu);
5754     CPUX86State *env = &cpu->env;
5755     int ret = 0;
5756     int n;
5757 
5758     if (arch_info->exception == EXCP01_DB) {
5759         if (arch_info->dr6 & DR6_BS) {
5760             if (cs->singlestep_enabled) {
5761                 ret = EXCP_DEBUG;
5762             }
5763         } else {
5764             for (n = 0; n < 4; n++) {
5765                 if (arch_info->dr6 & (1 << n)) {
5766                     switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
5767                     case 0x0:
5768                         ret = EXCP_DEBUG;
5769                         break;
5770                     case 0x1:
5771                         ret = EXCP_DEBUG;
5772                         cs->watchpoint_hit = &hw_watchpoint;
5773                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
5774                         hw_watchpoint.flags = BP_MEM_WRITE;
5775                         break;
5776                     case 0x3:
5777                         ret = EXCP_DEBUG;
5778                         cs->watchpoint_hit = &hw_watchpoint;
5779                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
5780                         hw_watchpoint.flags = BP_MEM_ACCESS;
5781                         break;
5782                     }
5783                 }
5784             }
5785         }
5786     } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
5787         ret = EXCP_DEBUG;
5788     }
5789     if (ret == 0) {
5790         cpu_synchronize_state(cs);
5791         assert(env->exception_nr == -1);
5792 
5793         /* pass to guest */
5794         kvm_queue_exception(env, arch_info->exception,
5795                             arch_info->exception == EXCP01_DB,
5796                             arch_info->dr6);
5797         env->has_error_code = 0;
5798     }
5799 
5800     return ret;
5801 }
5802 
5803 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
5804 {
5805     const uint8_t type_code[] = {
5806         [GDB_BREAKPOINT_HW] = 0x0,
5807         [GDB_WATCHPOINT_WRITE] = 0x1,
5808         [GDB_WATCHPOINT_ACCESS] = 0x3
5809     };
5810     const uint8_t len_code[] = {
5811         [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
5812     };
5813     int n;
5814 
5815     if (kvm_sw_breakpoints_active(cpu)) {
5816         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
5817     }
5818     if (nb_hw_breakpoint > 0) {
5819         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
5820         dbg->arch.debugreg[7] = 0x0600;
5821         for (n = 0; n < nb_hw_breakpoint; n++) {
5822             dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
5823             dbg->arch.debugreg[7] |= (2 << (n * 2)) |
5824                 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
5825                 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
5826         }
5827     }
5828 }
5829 
5830 static bool kvm_install_msr_filters(KVMState *s)
5831 {
5832     uint64_t zero = 0;
5833     struct kvm_msr_filter filter = {
5834         .flags = KVM_MSR_FILTER_DEFAULT_ALLOW,
5835     };
5836     int r, i, j = 0;
5837 
5838     for (i = 0; i < KVM_MSR_FILTER_MAX_RANGES; i++) {
5839         KVMMSRHandlers *handler = &msr_handlers[i];
5840         if (handler->msr) {
5841             struct kvm_msr_filter_range *range = &filter.ranges[j++];
5842 
5843             *range = (struct kvm_msr_filter_range) {
5844                 .flags = 0,
5845                 .nmsrs = 1,
5846                 .base = handler->msr,
5847                 .bitmap = (__u8 *)&zero,
5848             };
5849 
5850             if (handler->rdmsr) {
5851                 range->flags |= KVM_MSR_FILTER_READ;
5852             }
5853 
5854             if (handler->wrmsr) {
5855                 range->flags |= KVM_MSR_FILTER_WRITE;
5856             }
5857         }
5858     }
5859 
5860     r = kvm_vm_ioctl(s, KVM_X86_SET_MSR_FILTER, &filter);
5861     if (r) {
5862         return false;
5863     }
5864 
5865     return true;
5866 }
5867 
5868 static bool kvm_filter_msr(KVMState *s, uint32_t msr, QEMURDMSRHandler *rdmsr,
5869                     QEMUWRMSRHandler *wrmsr)
5870 {
5871     int i;
5872 
5873     for (i = 0; i < ARRAY_SIZE(msr_handlers); i++) {
5874         if (!msr_handlers[i].msr) {
5875             msr_handlers[i] = (KVMMSRHandlers) {
5876                 .msr = msr,
5877                 .rdmsr = rdmsr,
5878                 .wrmsr = wrmsr,
5879             };
5880 
5881             if (!kvm_install_msr_filters(s)) {
5882                 msr_handlers[i] = (KVMMSRHandlers) { };
5883                 return false;
5884             }
5885 
5886             return true;
5887         }
5888     }
5889 
5890     return false;
5891 }
5892 
5893 static int kvm_handle_rdmsr(X86CPU *cpu, struct kvm_run *run)
5894 {
5895     int i;
5896     bool r;
5897 
5898     for (i = 0; i < ARRAY_SIZE(msr_handlers); i++) {
5899         KVMMSRHandlers *handler = &msr_handlers[i];
5900         if (run->msr.index == handler->msr) {
5901             if (handler->rdmsr) {
5902                 r = handler->rdmsr(cpu, handler->msr,
5903                                    (uint64_t *)&run->msr.data);
5904                 run->msr.error = r ? 0 : 1;
5905                 return 0;
5906             }
5907         }
5908     }
5909 
5910     g_assert_not_reached();
5911 }
5912 
5913 static int kvm_handle_wrmsr(X86CPU *cpu, struct kvm_run *run)
5914 {
5915     int i;
5916     bool r;
5917 
5918     for (i = 0; i < ARRAY_SIZE(msr_handlers); i++) {
5919         KVMMSRHandlers *handler = &msr_handlers[i];
5920         if (run->msr.index == handler->msr) {
5921             if (handler->wrmsr) {
5922                 r = handler->wrmsr(cpu, handler->msr, run->msr.data);
5923                 run->msr.error = r ? 0 : 1;
5924                 return 0;
5925             }
5926         }
5927     }
5928 
5929     g_assert_not_reached();
5930 }
5931 
5932 static bool has_sgx_provisioning;
5933 
5934 static bool __kvm_enable_sgx_provisioning(KVMState *s)
5935 {
5936     int fd, ret;
5937 
5938     if (!kvm_vm_check_extension(s, KVM_CAP_SGX_ATTRIBUTE)) {
5939         return false;
5940     }
5941 
5942     fd = qemu_open_old("/dev/sgx_provision", O_RDONLY);
5943     if (fd < 0) {
5944         return false;
5945     }
5946 
5947     ret = kvm_vm_enable_cap(s, KVM_CAP_SGX_ATTRIBUTE, 0, fd);
5948     if (ret) {
5949         error_report("Could not enable SGX PROVISIONKEY: %s", strerror(-ret));
5950         exit(1);
5951     }
5952     close(fd);
5953     return true;
5954 }
5955 
5956 bool kvm_enable_sgx_provisioning(KVMState *s)
5957 {
5958     return MEMORIZE(__kvm_enable_sgx_provisioning(s), has_sgx_provisioning);
5959 }
5960 
5961 static bool host_supports_vmx(void)
5962 {
5963     uint32_t ecx, unused;
5964 
5965     host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
5966     return ecx & CPUID_EXT_VMX;
5967 }
5968 
5969 /*
5970  * Currently the handling here only supports use of KVM_HC_MAP_GPA_RANGE
5971  * to service guest-initiated memory attribute update requests so that
5972  * KVM_SET_MEMORY_ATTRIBUTES can update whether or not a page should be
5973  * backed by the private memory pool provided by guest_memfd, and as such
5974  * is only applicable to guest_memfd-backed guests (e.g. SNP/TDX).
5975  *
5976  * Other other use-cases for KVM_HC_MAP_GPA_RANGE, such as for SEV live
5977  * migration, are not implemented here currently.
5978  *
5979  * For the guest_memfd use-case, these exits will generally be synthesized
5980  * by KVM based on platform-specific hypercalls, like GHCB requests in the
5981  * case of SEV-SNP, and not issued directly within the guest though the
5982  * KVM_HC_MAP_GPA_RANGE hypercall. So in this case, KVM_HC_MAP_GPA_RANGE is
5983  * not actually advertised to guests via the KVM CPUID feature bit, as
5984  * opposed to SEV live migration where it would be. Since it is unlikely the
5985  * SEV live migration use-case would be useful for guest-memfd backed guests,
5986  * because private/shared page tracking is already provided through other
5987  * means, these 2 use-cases should be treated as being mutually-exclusive.
5988  */
5989 static int kvm_handle_hc_map_gpa_range(struct kvm_run *run)
5990 {
5991     uint64_t gpa, size, attributes;
5992 
5993     if (!machine_require_guest_memfd(current_machine))
5994         return -EINVAL;
5995 
5996     gpa = run->hypercall.args[0];
5997     size = run->hypercall.args[1] * TARGET_PAGE_SIZE;
5998     attributes = run->hypercall.args[2];
5999 
6000     trace_kvm_hc_map_gpa_range(gpa, size, attributes, run->hypercall.flags);
6001 
6002     return kvm_convert_memory(gpa, size, attributes & KVM_MAP_GPA_RANGE_ENCRYPTED);
6003 }
6004 
6005 static int kvm_handle_hypercall(struct kvm_run *run)
6006 {
6007     if (run->hypercall.nr == KVM_HC_MAP_GPA_RANGE)
6008         return kvm_handle_hc_map_gpa_range(run);
6009 
6010     return -EINVAL;
6011 }
6012 
6013 #define VMX_INVALID_GUEST_STATE 0x80000021
6014 
6015 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
6016 {
6017     X86CPU *cpu = X86_CPU(cs);
6018     uint64_t code;
6019     int ret;
6020     bool ctx_invalid;
6021     KVMState *state;
6022 
6023     switch (run->exit_reason) {
6024     case KVM_EXIT_HLT:
6025         DPRINTF("handle_hlt\n");
6026         bql_lock();
6027         ret = kvm_handle_halt(cpu);
6028         bql_unlock();
6029         break;
6030     case KVM_EXIT_SET_TPR:
6031         ret = 0;
6032         break;
6033     case KVM_EXIT_TPR_ACCESS:
6034         bql_lock();
6035         ret = kvm_handle_tpr_access(cpu);
6036         bql_unlock();
6037         break;
6038     case KVM_EXIT_FAIL_ENTRY:
6039         code = run->fail_entry.hardware_entry_failure_reason;
6040         fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
6041                 code);
6042         if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
6043             fprintf(stderr,
6044                     "\nIf you're running a guest on an Intel machine without "
6045                         "unrestricted mode\n"
6046                     "support, the failure can be most likely due to the guest "
6047                         "entering an invalid\n"
6048                     "state for Intel VT. For example, the guest maybe running "
6049                         "in big real mode\n"
6050                     "which is not supported on less recent Intel processors."
6051                         "\n\n");
6052         }
6053         ret = -1;
6054         break;
6055     case KVM_EXIT_EXCEPTION:
6056         fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
6057                 run->ex.exception, run->ex.error_code);
6058         ret = -1;
6059         break;
6060     case KVM_EXIT_DEBUG:
6061         DPRINTF("kvm_exit_debug\n");
6062         bql_lock();
6063         ret = kvm_handle_debug(cpu, &run->debug.arch);
6064         bql_unlock();
6065         break;
6066     case KVM_EXIT_HYPERV:
6067         ret = kvm_hv_handle_exit(cpu, &run->hyperv);
6068         break;
6069     case KVM_EXIT_IOAPIC_EOI:
6070         ioapic_eoi_broadcast(run->eoi.vector);
6071         ret = 0;
6072         break;
6073     case KVM_EXIT_X86_BUS_LOCK:
6074         /* already handled in kvm_arch_post_run */
6075         ret = 0;
6076         break;
6077     case KVM_EXIT_NOTIFY:
6078         ctx_invalid = !!(run->notify.flags & KVM_NOTIFY_CONTEXT_INVALID);
6079         state = KVM_STATE(current_accel());
6080         if (ctx_invalid ||
6081             state->notify_vmexit == NOTIFY_VMEXIT_OPTION_INTERNAL_ERROR) {
6082             warn_report("KVM internal error: Encountered a notify exit "
6083                         "with invalid context in guest.");
6084             ret = -1;
6085         } else {
6086             warn_report_once("KVM: Encountered a notify exit with valid "
6087                              "context in guest. "
6088                              "The guest could be misbehaving.");
6089             ret = 0;
6090         }
6091         break;
6092     case KVM_EXIT_X86_RDMSR:
6093         /* We only enable MSR filtering, any other exit is bogus */
6094         assert(run->msr.reason == KVM_MSR_EXIT_REASON_FILTER);
6095         ret = kvm_handle_rdmsr(cpu, run);
6096         break;
6097     case KVM_EXIT_X86_WRMSR:
6098         /* We only enable MSR filtering, any other exit is bogus */
6099         assert(run->msr.reason == KVM_MSR_EXIT_REASON_FILTER);
6100         ret = kvm_handle_wrmsr(cpu, run);
6101         break;
6102 #ifdef CONFIG_XEN_EMU
6103     case KVM_EXIT_XEN:
6104         ret = kvm_xen_handle_exit(cpu, &run->xen);
6105         break;
6106 #endif
6107     case KVM_EXIT_HYPERCALL:
6108         ret = kvm_handle_hypercall(run);
6109         break;
6110     default:
6111         fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
6112         ret = -1;
6113         break;
6114     }
6115 
6116     return ret;
6117 }
6118 
6119 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
6120 {
6121     X86CPU *cpu = X86_CPU(cs);
6122     CPUX86State *env = &cpu->env;
6123 
6124     kvm_cpu_synchronize_state(cs);
6125     return !(env->cr[0] & CR0_PE_MASK) ||
6126            ((env->segs[R_CS].selector  & 3) != 3);
6127 }
6128 
6129 void kvm_arch_init_irq_routing(KVMState *s)
6130 {
6131     /* We know at this point that we're using the in-kernel
6132      * irqchip, so we can use irqfds, and on x86 we know
6133      * we can use msi via irqfd and GSI routing.
6134      */
6135     kvm_msi_via_irqfd_allowed = true;
6136     kvm_gsi_routing_allowed = true;
6137 
6138     if (kvm_irqchip_is_split()) {
6139         KVMRouteChange c = kvm_irqchip_begin_route_changes(s);
6140         int i;
6141 
6142         /* If the ioapic is in QEMU and the lapics are in KVM, reserve
6143            MSI routes for signaling interrupts to the local apics. */
6144         for (i = 0; i < IOAPIC_NUM_PINS; i++) {
6145             if (kvm_irqchip_add_msi_route(&c, 0, NULL) < 0) {
6146                 error_report("Could not enable split IRQ mode.");
6147                 exit(1);
6148             }
6149         }
6150         kvm_irqchip_commit_route_changes(&c);
6151     }
6152 }
6153 
6154 int kvm_arch_irqchip_create(KVMState *s)
6155 {
6156     int ret;
6157     if (kvm_kernel_irqchip_split()) {
6158         ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
6159         if (ret) {
6160             error_report("Could not enable split irqchip mode: %s",
6161                          strerror(-ret));
6162             exit(1);
6163         } else {
6164             DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
6165             kvm_split_irqchip = true;
6166             return 1;
6167         }
6168     } else {
6169         return 0;
6170     }
6171 }
6172 
6173 uint64_t kvm_swizzle_msi_ext_dest_id(uint64_t address)
6174 {
6175     CPUX86State *env;
6176     uint64_t ext_id;
6177 
6178     if (!first_cpu) {
6179         return address;
6180     }
6181     env = &X86_CPU(first_cpu)->env;
6182     if (!(env->features[FEAT_KVM] & (1 << KVM_FEATURE_MSI_EXT_DEST_ID))) {
6183         return address;
6184     }
6185 
6186     /*
6187      * If the remappable format bit is set, or the upper bits are
6188      * already set in address_hi, or the low extended bits aren't
6189      * there anyway, do nothing.
6190      */
6191     ext_id = address & (0xff << MSI_ADDR_DEST_IDX_SHIFT);
6192     if (!ext_id || (ext_id & (1 << MSI_ADDR_DEST_IDX_SHIFT)) || (address >> 32)) {
6193         return address;
6194     }
6195 
6196     address &= ~ext_id;
6197     address |= ext_id << 35;
6198     return address;
6199 }
6200 
6201 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
6202                              uint64_t address, uint32_t data, PCIDevice *dev)
6203 {
6204     X86IOMMUState *iommu = x86_iommu_get_default();
6205 
6206     if (iommu) {
6207         X86IOMMUClass *class = X86_IOMMU_DEVICE_GET_CLASS(iommu);
6208 
6209         if (class->int_remap) {
6210             int ret;
6211             MSIMessage src, dst;
6212 
6213             src.address = route->u.msi.address_hi;
6214             src.address <<= VTD_MSI_ADDR_HI_SHIFT;
6215             src.address |= route->u.msi.address_lo;
6216             src.data = route->u.msi.data;
6217 
6218             ret = class->int_remap(iommu, &src, &dst, dev ?     \
6219                                    pci_requester_id(dev) :      \
6220                                    X86_IOMMU_SID_INVALID);
6221             if (ret) {
6222                 trace_kvm_x86_fixup_msi_error(route->gsi);
6223                 return 1;
6224             }
6225 
6226             /*
6227              * Handled untranslated compatibility format interrupt with
6228              * extended destination ID in the low bits 11-5. */
6229             dst.address = kvm_swizzle_msi_ext_dest_id(dst.address);
6230 
6231             route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
6232             route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
6233             route->u.msi.data = dst.data;
6234             return 0;
6235         }
6236     }
6237 
6238 #ifdef CONFIG_XEN_EMU
6239     if (xen_mode == XEN_EMULATE) {
6240         int handled = xen_evtchn_translate_pirq_msi(route, address, data);
6241 
6242         /*
6243          * If it was a PIRQ and successfully routed (handled == 0) or it was
6244          * an error (handled < 0), return. If it wasn't a PIRQ, keep going.
6245          */
6246         if (handled <= 0) {
6247             return handled;
6248         }
6249     }
6250 #endif
6251 
6252     address = kvm_swizzle_msi_ext_dest_id(address);
6253     route->u.msi.address_hi = address >> VTD_MSI_ADDR_HI_SHIFT;
6254     route->u.msi.address_lo = address & VTD_MSI_ADDR_LO_MASK;
6255     return 0;
6256 }
6257 
6258 typedef struct MSIRouteEntry MSIRouteEntry;
6259 
6260 struct MSIRouteEntry {
6261     PCIDevice *dev;             /* Device pointer */
6262     int vector;                 /* MSI/MSIX vector index */
6263     int virq;                   /* Virtual IRQ index */
6264     QLIST_ENTRY(MSIRouteEntry) list;
6265 };
6266 
6267 /* List of used GSI routes */
6268 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
6269     QLIST_HEAD_INITIALIZER(msi_route_list);
6270 
6271 void kvm_update_msi_routes_all(void *private, bool global,
6272                                uint32_t index, uint32_t mask)
6273 {
6274     int cnt = 0, vector;
6275     MSIRouteEntry *entry;
6276     MSIMessage msg;
6277     PCIDevice *dev;
6278 
6279     /* TODO: explicit route update */
6280     QLIST_FOREACH(entry, &msi_route_list, list) {
6281         cnt++;
6282         vector = entry->vector;
6283         dev = entry->dev;
6284         if (msix_enabled(dev) && !msix_is_masked(dev, vector)) {
6285             msg = msix_get_message(dev, vector);
6286         } else if (msi_enabled(dev) && !msi_is_masked(dev, vector)) {
6287             msg = msi_get_message(dev, vector);
6288         } else {
6289             /*
6290              * Either MSI/MSIX is disabled for the device, or the
6291              * specific message was masked out.  Skip this one.
6292              */
6293             continue;
6294         }
6295         kvm_irqchip_update_msi_route(kvm_state, entry->virq, msg, dev);
6296     }
6297     kvm_irqchip_commit_routes(kvm_state);
6298     trace_kvm_x86_update_msi_routes(cnt);
6299 }
6300 
6301 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
6302                                 int vector, PCIDevice *dev)
6303 {
6304     static bool notify_list_inited = false;
6305     MSIRouteEntry *entry;
6306 
6307     if (!dev) {
6308         /* These are (possibly) IOAPIC routes only used for split
6309          * kernel irqchip mode, while what we are housekeeping are
6310          * PCI devices only. */
6311         return 0;
6312     }
6313 
6314     entry = g_new0(MSIRouteEntry, 1);
6315     entry->dev = dev;
6316     entry->vector = vector;
6317     entry->virq = route->gsi;
6318     QLIST_INSERT_HEAD(&msi_route_list, entry, list);
6319 
6320     trace_kvm_x86_add_msi_route(route->gsi);
6321 
6322     if (!notify_list_inited) {
6323         /* For the first time we do add route, add ourselves into
6324          * IOMMU's IEC notify list if needed. */
6325         X86IOMMUState *iommu = x86_iommu_get_default();
6326         if (iommu) {
6327             x86_iommu_iec_register_notifier(iommu,
6328                                             kvm_update_msi_routes_all,
6329                                             NULL);
6330         }
6331         notify_list_inited = true;
6332     }
6333     return 0;
6334 }
6335 
6336 int kvm_arch_release_virq_post(int virq)
6337 {
6338     MSIRouteEntry *entry, *next;
6339     QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
6340         if (entry->virq == virq) {
6341             trace_kvm_x86_remove_msi_route(virq);
6342             QLIST_REMOVE(entry, list);
6343             g_free(entry);
6344             break;
6345         }
6346     }
6347     return 0;
6348 }
6349 
6350 int kvm_arch_msi_data_to_gsi(uint32_t data)
6351 {
6352     abort();
6353 }
6354 
6355 bool kvm_has_waitpkg(void)
6356 {
6357     return has_msr_umwait;
6358 }
6359 
6360 #define ARCH_REQ_XCOMP_GUEST_PERM       0x1025
6361 
6362 void kvm_request_xsave_components(X86CPU *cpu, uint64_t mask)
6363 {
6364     KVMState *s = kvm_state;
6365     uint64_t supported;
6366 
6367     mask &= XSTATE_DYNAMIC_MASK;
6368     if (!mask) {
6369         return;
6370     }
6371     /*
6372      * Just ignore bits that are not in CPUID[EAX=0xD,ECX=0].
6373      * ARCH_REQ_XCOMP_GUEST_PERM would fail, and QEMU has warned
6374      * about them already because they are not supported features.
6375      */
6376     supported = kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EAX);
6377     supported |= (uint64_t)kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EDX) << 32;
6378     mask &= supported;
6379 
6380     while (mask) {
6381         int bit = ctz64(mask);
6382         int rc = syscall(SYS_arch_prctl, ARCH_REQ_XCOMP_GUEST_PERM, bit);
6383         if (rc) {
6384             /*
6385              * Older kernel version (<5.17) do not support
6386              * ARCH_REQ_XCOMP_GUEST_PERM, but also do not return
6387              * any dynamic feature from kvm_arch_get_supported_cpuid.
6388              */
6389             warn_report("prctl(ARCH_REQ_XCOMP_GUEST_PERM) failure "
6390                         "for feature bit %d", bit);
6391         }
6392         mask &= ~BIT_ULL(bit);
6393     }
6394 }
6395 
6396 static int kvm_arch_get_notify_vmexit(Object *obj, Error **errp)
6397 {
6398     KVMState *s = KVM_STATE(obj);
6399     return s->notify_vmexit;
6400 }
6401 
6402 static void kvm_arch_set_notify_vmexit(Object *obj, int value, Error **errp)
6403 {
6404     KVMState *s = KVM_STATE(obj);
6405 
6406     if (s->fd != -1) {
6407         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
6408         return;
6409     }
6410 
6411     s->notify_vmexit = value;
6412 }
6413 
6414 static void kvm_arch_get_notify_window(Object *obj, Visitor *v,
6415                                        const char *name, void *opaque,
6416                                        Error **errp)
6417 {
6418     KVMState *s = KVM_STATE(obj);
6419     uint32_t value = s->notify_window;
6420 
6421     visit_type_uint32(v, name, &value, errp);
6422 }
6423 
6424 static void kvm_arch_set_notify_window(Object *obj, Visitor *v,
6425                                        const char *name, void *opaque,
6426                                        Error **errp)
6427 {
6428     KVMState *s = KVM_STATE(obj);
6429     uint32_t value;
6430 
6431     if (s->fd != -1) {
6432         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
6433         return;
6434     }
6435 
6436     if (!visit_type_uint32(v, name, &value, errp)) {
6437         return;
6438     }
6439 
6440     s->notify_window = value;
6441 }
6442 
6443 static void kvm_arch_get_xen_version(Object *obj, Visitor *v,
6444                                      const char *name, void *opaque,
6445                                      Error **errp)
6446 {
6447     KVMState *s = KVM_STATE(obj);
6448     uint32_t value = s->xen_version;
6449 
6450     visit_type_uint32(v, name, &value, errp);
6451 }
6452 
6453 static void kvm_arch_set_xen_version(Object *obj, Visitor *v,
6454                                      const char *name, void *opaque,
6455                                      Error **errp)
6456 {
6457     KVMState *s = KVM_STATE(obj);
6458     Error *error = NULL;
6459     uint32_t value;
6460 
6461     visit_type_uint32(v, name, &value, &error);
6462     if (error) {
6463         error_propagate(errp, error);
6464         return;
6465     }
6466 
6467     s->xen_version = value;
6468     if (value && xen_mode == XEN_DISABLED) {
6469         xen_mode = XEN_EMULATE;
6470     }
6471 }
6472 
6473 static void kvm_arch_get_xen_gnttab_max_frames(Object *obj, Visitor *v,
6474                                                const char *name, void *opaque,
6475                                                Error **errp)
6476 {
6477     KVMState *s = KVM_STATE(obj);
6478     uint16_t value = s->xen_gnttab_max_frames;
6479 
6480     visit_type_uint16(v, name, &value, errp);
6481 }
6482 
6483 static void kvm_arch_set_xen_gnttab_max_frames(Object *obj, Visitor *v,
6484                                                const char *name, void *opaque,
6485                                                Error **errp)
6486 {
6487     KVMState *s = KVM_STATE(obj);
6488     Error *error = NULL;
6489     uint16_t value;
6490 
6491     visit_type_uint16(v, name, &value, &error);
6492     if (error) {
6493         error_propagate(errp, error);
6494         return;
6495     }
6496 
6497     s->xen_gnttab_max_frames = value;
6498 }
6499 
6500 static void kvm_arch_get_xen_evtchn_max_pirq(Object *obj, Visitor *v,
6501                                              const char *name, void *opaque,
6502                                              Error **errp)
6503 {
6504     KVMState *s = KVM_STATE(obj);
6505     uint16_t value = s->xen_evtchn_max_pirq;
6506 
6507     visit_type_uint16(v, name, &value, errp);
6508 }
6509 
6510 static void kvm_arch_set_xen_evtchn_max_pirq(Object *obj, Visitor *v,
6511                                              const char *name, void *opaque,
6512                                              Error **errp)
6513 {
6514     KVMState *s = KVM_STATE(obj);
6515     Error *error = NULL;
6516     uint16_t value;
6517 
6518     visit_type_uint16(v, name, &value, &error);
6519     if (error) {
6520         error_propagate(errp, error);
6521         return;
6522     }
6523 
6524     s->xen_evtchn_max_pirq = value;
6525 }
6526 
6527 void kvm_arch_accel_class_init(ObjectClass *oc)
6528 {
6529     object_class_property_add_enum(oc, "notify-vmexit", "NotifyVMexitOption",
6530                                    &NotifyVmexitOption_lookup,
6531                                    kvm_arch_get_notify_vmexit,
6532                                    kvm_arch_set_notify_vmexit);
6533     object_class_property_set_description(oc, "notify-vmexit",
6534                                           "Enable notify VM exit");
6535 
6536     object_class_property_add(oc, "notify-window", "uint32",
6537                               kvm_arch_get_notify_window,
6538                               kvm_arch_set_notify_window,
6539                               NULL, NULL);
6540     object_class_property_set_description(oc, "notify-window",
6541                                           "Clock cycles without an event window "
6542                                           "after which a notification VM exit occurs");
6543 
6544     object_class_property_add(oc, "xen-version", "uint32",
6545                               kvm_arch_get_xen_version,
6546                               kvm_arch_set_xen_version,
6547                               NULL, NULL);
6548     object_class_property_set_description(oc, "xen-version",
6549                                           "Xen version to be emulated "
6550                                           "(in XENVER_version form "
6551                                           "e.g. 0x4000a for 4.10)");
6552 
6553     object_class_property_add(oc, "xen-gnttab-max-frames", "uint16",
6554                               kvm_arch_get_xen_gnttab_max_frames,
6555                               kvm_arch_set_xen_gnttab_max_frames,
6556                               NULL, NULL);
6557     object_class_property_set_description(oc, "xen-gnttab-max-frames",
6558                                           "Maximum number of grant table frames");
6559 
6560     object_class_property_add(oc, "xen-evtchn-max-pirq", "uint16",
6561                               kvm_arch_get_xen_evtchn_max_pirq,
6562                               kvm_arch_set_xen_evtchn_max_pirq,
6563                               NULL, NULL);
6564     object_class_property_set_description(oc, "xen-evtchn-max-pirq",
6565                                           "Maximum number of Xen PIRQs");
6566 }
6567 
6568 void kvm_set_max_apic_id(uint32_t max_apic_id)
6569 {
6570     kvm_vm_enable_cap(kvm_state, KVM_CAP_MAX_VCPU_ID, 0, max_apic_id);
6571 }
6572