xref: /openbmc/qemu/target/i386/kvm/kvm.c (revision 62fffaa6)
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 <sys/ioctl.h>
19 #include <sys/utsname.h>
20 
21 #include <linux/kvm.h>
22 #include "standard-headers/asm-x86/kvm_para.h"
23 
24 #include "cpu.h"
25 #include "host-cpu.h"
26 #include "sysemu/sysemu.h"
27 #include "sysemu/hw_accel.h"
28 #include "sysemu/kvm_int.h"
29 #include "sysemu/runstate.h"
30 #include "kvm_i386.h"
31 #include "sev_i386.h"
32 #include "hyperv.h"
33 #include "hyperv-proto.h"
34 
35 #include "exec/gdbstub.h"
36 #include "qemu/host-utils.h"
37 #include "qemu/main-loop.h"
38 #include "qemu/config-file.h"
39 #include "qemu/error-report.h"
40 #include "hw/i386/x86.h"
41 #include "hw/i386/apic.h"
42 #include "hw/i386/apic_internal.h"
43 #include "hw/i386/apic-msidef.h"
44 #include "hw/i386/intel_iommu.h"
45 #include "hw/i386/x86-iommu.h"
46 #include "hw/i386/e820_memory_layout.h"
47 #include "sysemu/sev.h"
48 
49 #include "hw/pci/pci.h"
50 #include "hw/pci/msi.h"
51 #include "hw/pci/msix.h"
52 #include "migration/blocker.h"
53 #include "exec/memattrs.h"
54 #include "trace.h"
55 
56 //#define DEBUG_KVM
57 
58 #ifdef DEBUG_KVM
59 #define DPRINTF(fmt, ...) \
60     do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
61 #else
62 #define DPRINTF(fmt, ...) \
63     do { } while (0)
64 #endif
65 
66 /* From arch/x86/kvm/lapic.h */
67 #define KVM_APIC_BUS_CYCLE_NS       1
68 #define KVM_APIC_BUS_FREQUENCY      (1000000000ULL / KVM_APIC_BUS_CYCLE_NS)
69 
70 #define MSR_KVM_WALL_CLOCK  0x11
71 #define MSR_KVM_SYSTEM_TIME 0x12
72 
73 /* A 4096-byte buffer can hold the 8-byte kvm_msrs header, plus
74  * 255 kvm_msr_entry structs */
75 #define MSR_BUF_SIZE 4096
76 
77 static void kvm_init_msrs(X86CPU *cpu);
78 
79 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
80     KVM_CAP_INFO(SET_TSS_ADDR),
81     KVM_CAP_INFO(EXT_CPUID),
82     KVM_CAP_INFO(MP_STATE),
83     KVM_CAP_LAST_INFO
84 };
85 
86 static bool has_msr_star;
87 static bool has_msr_hsave_pa;
88 static bool has_msr_tsc_aux;
89 static bool has_msr_tsc_adjust;
90 static bool has_msr_tsc_deadline;
91 static bool has_msr_feature_control;
92 static bool has_msr_misc_enable;
93 static bool has_msr_smbase;
94 static bool has_msr_bndcfgs;
95 static int lm_capable_kernel;
96 static bool has_msr_hv_hypercall;
97 static bool has_msr_hv_crash;
98 static bool has_msr_hv_reset;
99 static bool has_msr_hv_vpindex;
100 static bool hv_vpindex_settable;
101 static bool has_msr_hv_runtime;
102 static bool has_msr_hv_synic;
103 static bool has_msr_hv_stimer;
104 static bool has_msr_hv_frequencies;
105 static bool has_msr_hv_reenlightenment;
106 static bool has_msr_xss;
107 static bool has_msr_umwait;
108 static bool has_msr_spec_ctrl;
109 static bool has_msr_tsx_ctrl;
110 static bool has_msr_virt_ssbd;
111 static bool has_msr_smi_count;
112 static bool has_msr_arch_capabs;
113 static bool has_msr_core_capabs;
114 static bool has_msr_vmx_vmfunc;
115 static bool has_msr_ucode_rev;
116 static bool has_msr_vmx_procbased_ctls2;
117 static bool has_msr_perf_capabs;
118 static bool has_msr_pkrs;
119 
120 static uint32_t has_architectural_pmu_version;
121 static uint32_t num_architectural_pmu_gp_counters;
122 static uint32_t num_architectural_pmu_fixed_counters;
123 
124 static int has_xsave;
125 static int has_xcrs;
126 static int has_pit_state2;
127 static int has_exception_payload;
128 
129 static bool has_msr_mcg_ext_ctl;
130 
131 static struct kvm_cpuid2 *cpuid_cache;
132 static struct kvm_cpuid2 *hv_cpuid_cache;
133 static struct kvm_msr_list *kvm_feature_msrs;
134 
135 #define BUS_LOCK_SLICE_TIME 1000000000ULL /* ns */
136 static RateLimit bus_lock_ratelimit_ctrl;
137 
138 int kvm_has_pit_state2(void)
139 {
140     return has_pit_state2;
141 }
142 
143 bool kvm_has_smm(void)
144 {
145     return kvm_vm_check_extension(kvm_state, KVM_CAP_X86_SMM);
146 }
147 
148 bool kvm_has_adjust_clock_stable(void)
149 {
150     int ret = kvm_check_extension(kvm_state, KVM_CAP_ADJUST_CLOCK);
151 
152     return (ret == KVM_CLOCK_TSC_STABLE);
153 }
154 
155 bool kvm_has_adjust_clock(void)
156 {
157     return kvm_check_extension(kvm_state, KVM_CAP_ADJUST_CLOCK);
158 }
159 
160 bool kvm_has_exception_payload(void)
161 {
162     return has_exception_payload;
163 }
164 
165 static bool kvm_x2apic_api_set_flags(uint64_t flags)
166 {
167     KVMState *s = KVM_STATE(current_accel());
168 
169     return !kvm_vm_enable_cap(s, KVM_CAP_X2APIC_API, 0, flags);
170 }
171 
172 #define MEMORIZE(fn, _result) \
173     ({ \
174         static bool _memorized; \
175         \
176         if (_memorized) { \
177             return _result; \
178         } \
179         _memorized = true; \
180         _result = fn; \
181     })
182 
183 static bool has_x2apic_api;
184 
185 bool kvm_has_x2apic_api(void)
186 {
187     return has_x2apic_api;
188 }
189 
190 bool kvm_enable_x2apic(void)
191 {
192     return MEMORIZE(
193              kvm_x2apic_api_set_flags(KVM_X2APIC_API_USE_32BIT_IDS |
194                                       KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK),
195              has_x2apic_api);
196 }
197 
198 bool kvm_hv_vpindex_settable(void)
199 {
200     return hv_vpindex_settable;
201 }
202 
203 static int kvm_get_tsc(CPUState *cs)
204 {
205     X86CPU *cpu = X86_CPU(cs);
206     CPUX86State *env = &cpu->env;
207     struct {
208         struct kvm_msrs info;
209         struct kvm_msr_entry entries[1];
210     } msr_data = {};
211     int ret;
212 
213     if (env->tsc_valid) {
214         return 0;
215     }
216 
217     memset(&msr_data, 0, sizeof(msr_data));
218     msr_data.info.nmsrs = 1;
219     msr_data.entries[0].index = MSR_IA32_TSC;
220     env->tsc_valid = !runstate_is_running();
221 
222     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
223     if (ret < 0) {
224         return ret;
225     }
226 
227     assert(ret == 1);
228     env->tsc = msr_data.entries[0].data;
229     return 0;
230 }
231 
232 static inline void do_kvm_synchronize_tsc(CPUState *cpu, run_on_cpu_data arg)
233 {
234     kvm_get_tsc(cpu);
235 }
236 
237 void kvm_synchronize_all_tsc(void)
238 {
239     CPUState *cpu;
240 
241     if (kvm_enabled()) {
242         CPU_FOREACH(cpu) {
243             run_on_cpu(cpu, do_kvm_synchronize_tsc, RUN_ON_CPU_NULL);
244         }
245     }
246 }
247 
248 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
249 {
250     struct kvm_cpuid2 *cpuid;
251     int r, size;
252 
253     size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
254     cpuid = g_malloc0(size);
255     cpuid->nent = max;
256     r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
257     if (r == 0 && cpuid->nent >= max) {
258         r = -E2BIG;
259     }
260     if (r < 0) {
261         if (r == -E2BIG) {
262             g_free(cpuid);
263             return NULL;
264         } else {
265             fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
266                     strerror(-r));
267             exit(1);
268         }
269     }
270     return cpuid;
271 }
272 
273 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
274  * for all entries.
275  */
276 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
277 {
278     struct kvm_cpuid2 *cpuid;
279     int max = 1;
280 
281     if (cpuid_cache != NULL) {
282         return cpuid_cache;
283     }
284     while ((cpuid = try_get_cpuid(s, max)) == NULL) {
285         max *= 2;
286     }
287     cpuid_cache = cpuid;
288     return cpuid;
289 }
290 
291 static bool host_tsx_broken(void)
292 {
293     int family, model, stepping;\
294     char vendor[CPUID_VENDOR_SZ + 1];
295 
296     host_cpu_vendor_fms(vendor, &family, &model, &stepping);
297 
298     /* Check if we are running on a Haswell host known to have broken TSX */
299     return !strcmp(vendor, CPUID_VENDOR_INTEL) &&
300            (family == 6) &&
301            ((model == 63 && stepping < 4) ||
302             model == 60 || model == 69 || model == 70);
303 }
304 
305 /* Returns the value for a specific register on the cpuid entry
306  */
307 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
308 {
309     uint32_t ret = 0;
310     switch (reg) {
311     case R_EAX:
312         ret = entry->eax;
313         break;
314     case R_EBX:
315         ret = entry->ebx;
316         break;
317     case R_ECX:
318         ret = entry->ecx;
319         break;
320     case R_EDX:
321         ret = entry->edx;
322         break;
323     }
324     return ret;
325 }
326 
327 /* Find matching entry for function/index on kvm_cpuid2 struct
328  */
329 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
330                                                  uint32_t function,
331                                                  uint32_t index)
332 {
333     int i;
334     for (i = 0; i < cpuid->nent; ++i) {
335         if (cpuid->entries[i].function == function &&
336             cpuid->entries[i].index == index) {
337             return &cpuid->entries[i];
338         }
339     }
340     /* not found: */
341     return NULL;
342 }
343 
344 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
345                                       uint32_t index, int reg)
346 {
347     struct kvm_cpuid2 *cpuid;
348     uint32_t ret = 0;
349     uint32_t cpuid_1_edx;
350 
351     cpuid = get_supported_cpuid(s);
352 
353     struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
354     if (entry) {
355         ret = cpuid_entry_get_reg(entry, reg);
356     }
357 
358     /* Fixups for the data returned by KVM, below */
359 
360     if (function == 1 && reg == R_EDX) {
361         /* KVM before 2.6.30 misreports the following features */
362         ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
363     } else if (function == 1 && reg == R_ECX) {
364         /* We can set the hypervisor flag, even if KVM does not return it on
365          * GET_SUPPORTED_CPUID
366          */
367         ret |= CPUID_EXT_HYPERVISOR;
368         /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
369          * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
370          * and the irqchip is in the kernel.
371          */
372         if (kvm_irqchip_in_kernel() &&
373                 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
374             ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
375         }
376 
377         /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
378          * without the in-kernel irqchip
379          */
380         if (!kvm_irqchip_in_kernel()) {
381             ret &= ~CPUID_EXT_X2APIC;
382         }
383 
384         if (enable_cpu_pm) {
385             int disable_exits = kvm_check_extension(s,
386                                                     KVM_CAP_X86_DISABLE_EXITS);
387 
388             if (disable_exits & KVM_X86_DISABLE_EXITS_MWAIT) {
389                 ret |= CPUID_EXT_MONITOR;
390             }
391         }
392     } else if (function == 6 && reg == R_EAX) {
393         ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
394     } else if (function == 7 && index == 0 && reg == R_EBX) {
395         if (host_tsx_broken()) {
396             ret &= ~(CPUID_7_0_EBX_RTM | CPUID_7_0_EBX_HLE);
397         }
398     } else if (function == 7 && index == 0 && reg == R_EDX) {
399         /*
400          * Linux v4.17-v4.20 incorrectly return ARCH_CAPABILITIES on SVM hosts.
401          * We can detect the bug by checking if MSR_IA32_ARCH_CAPABILITIES is
402          * returned by KVM_GET_MSR_INDEX_LIST.
403          */
404         if (!has_msr_arch_capabs) {
405             ret &= ~CPUID_7_0_EDX_ARCH_CAPABILITIES;
406         }
407     } else if (function == 0x80000001 && reg == R_ECX) {
408         /*
409          * It's safe to enable TOPOEXT even if it's not returned by
410          * GET_SUPPORTED_CPUID.  Unconditionally enabling TOPOEXT here allows
411          * us to keep CPU models including TOPOEXT runnable on older kernels.
412          */
413         ret |= CPUID_EXT3_TOPOEXT;
414     } else if (function == 0x80000001 && reg == R_EDX) {
415         /* On Intel, kvm returns cpuid according to the Intel spec,
416          * so add missing bits according to the AMD spec:
417          */
418         cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
419         ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
420     } else if (function == KVM_CPUID_FEATURES && reg == R_EAX) {
421         /* kvm_pv_unhalt is reported by GET_SUPPORTED_CPUID, but it can't
422          * be enabled without the in-kernel irqchip
423          */
424         if (!kvm_irqchip_in_kernel()) {
425             ret &= ~(1U << KVM_FEATURE_PV_UNHALT);
426         }
427         if (kvm_irqchip_is_split()) {
428             ret |= 1U << KVM_FEATURE_MSI_EXT_DEST_ID;
429         }
430     } else if (function == KVM_CPUID_FEATURES && reg == R_EDX) {
431         ret |= 1U << KVM_HINTS_REALTIME;
432     }
433 
434     return ret;
435 }
436 
437 uint64_t kvm_arch_get_supported_msr_feature(KVMState *s, uint32_t index)
438 {
439     struct {
440         struct kvm_msrs info;
441         struct kvm_msr_entry entries[1];
442     } msr_data = {};
443     uint64_t value;
444     uint32_t ret, can_be_one, must_be_one;
445 
446     if (kvm_feature_msrs == NULL) { /* Host doesn't support feature MSRs */
447         return 0;
448     }
449 
450     /* Check if requested MSR is supported feature MSR */
451     int i;
452     for (i = 0; i < kvm_feature_msrs->nmsrs; i++)
453         if (kvm_feature_msrs->indices[i] == index) {
454             break;
455         }
456     if (i == kvm_feature_msrs->nmsrs) {
457         return 0; /* if the feature MSR is not supported, simply return 0 */
458     }
459 
460     msr_data.info.nmsrs = 1;
461     msr_data.entries[0].index = index;
462 
463     ret = kvm_ioctl(s, KVM_GET_MSRS, &msr_data);
464     if (ret != 1) {
465         error_report("KVM get MSR (index=0x%x) feature failed, %s",
466             index, strerror(-ret));
467         exit(1);
468     }
469 
470     value = msr_data.entries[0].data;
471     switch (index) {
472     case MSR_IA32_VMX_PROCBASED_CTLS2:
473         if (!has_msr_vmx_procbased_ctls2) {
474             /* KVM forgot to add these bits for some time, do this ourselves. */
475             if (kvm_arch_get_supported_cpuid(s, 0xD, 1, R_ECX) &
476                 CPUID_XSAVE_XSAVES) {
477                 value |= (uint64_t)VMX_SECONDARY_EXEC_XSAVES << 32;
478             }
479             if (kvm_arch_get_supported_cpuid(s, 1, 0, R_ECX) &
480                 CPUID_EXT_RDRAND) {
481                 value |= (uint64_t)VMX_SECONDARY_EXEC_RDRAND_EXITING << 32;
482             }
483             if (kvm_arch_get_supported_cpuid(s, 7, 0, R_EBX) &
484                 CPUID_7_0_EBX_INVPCID) {
485                 value |= (uint64_t)VMX_SECONDARY_EXEC_ENABLE_INVPCID << 32;
486             }
487             if (kvm_arch_get_supported_cpuid(s, 7, 0, R_EBX) &
488                 CPUID_7_0_EBX_RDSEED) {
489                 value |= (uint64_t)VMX_SECONDARY_EXEC_RDSEED_EXITING << 32;
490             }
491             if (kvm_arch_get_supported_cpuid(s, 0x80000001, 0, R_EDX) &
492                 CPUID_EXT2_RDTSCP) {
493                 value |= (uint64_t)VMX_SECONDARY_EXEC_RDTSCP << 32;
494             }
495         }
496         /* fall through */
497     case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
498     case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
499     case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
500     case MSR_IA32_VMX_TRUE_EXIT_CTLS:
501         /*
502          * Return true for bits that can be one, but do not have to be one.
503          * The SDM tells us which bits could have a "must be one" setting,
504          * so we can do the opposite transformation in make_vmx_msr_value.
505          */
506         must_be_one = (uint32_t)value;
507         can_be_one = (uint32_t)(value >> 32);
508         return can_be_one & ~must_be_one;
509 
510     default:
511         return value;
512     }
513 }
514 
515 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
516                                      int *max_banks)
517 {
518     int r;
519 
520     r = kvm_check_extension(s, KVM_CAP_MCE);
521     if (r > 0) {
522         *max_banks = r;
523         return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
524     }
525     return -ENOSYS;
526 }
527 
528 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
529 {
530     CPUState *cs = CPU(cpu);
531     CPUX86State *env = &cpu->env;
532     uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
533                       MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
534     uint64_t mcg_status = MCG_STATUS_MCIP;
535     int flags = 0;
536 
537     if (code == BUS_MCEERR_AR) {
538         status |= MCI_STATUS_AR | 0x134;
539         mcg_status |= MCG_STATUS_EIPV;
540     } else {
541         status |= 0xc0;
542         mcg_status |= MCG_STATUS_RIPV;
543     }
544 
545     flags = cpu_x86_support_mca_broadcast(env) ? MCE_INJECT_BROADCAST : 0;
546     /* We need to read back the value of MSR_EXT_MCG_CTL that was set by the
547      * guest kernel back into env->mcg_ext_ctl.
548      */
549     cpu_synchronize_state(cs);
550     if (env->mcg_ext_ctl & MCG_EXT_CTL_LMCE_EN) {
551         mcg_status |= MCG_STATUS_LMCE;
552         flags = 0;
553     }
554 
555     cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
556                        (MCM_ADDR_PHYS << 6) | 0xc, flags);
557 }
558 
559 static void emit_hypervisor_memory_failure(MemoryFailureAction action, bool ar)
560 {
561     MemoryFailureFlags mff = {.action_required = ar, .recursive = false};
562 
563     qapi_event_send_memory_failure(MEMORY_FAILURE_RECIPIENT_HYPERVISOR, action,
564                                    &mff);
565 }
566 
567 static void hardware_memory_error(void *host_addr)
568 {
569     emit_hypervisor_memory_failure(MEMORY_FAILURE_ACTION_FATAL, true);
570     error_report("QEMU got Hardware memory error at addr %p", host_addr);
571     exit(1);
572 }
573 
574 void kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
575 {
576     X86CPU *cpu = X86_CPU(c);
577     CPUX86State *env = &cpu->env;
578     ram_addr_t ram_addr;
579     hwaddr paddr;
580 
581     /* If we get an action required MCE, it has been injected by KVM
582      * while the VM was running.  An action optional MCE instead should
583      * be coming from the main thread, which qemu_init_sigbus identifies
584      * as the "early kill" thread.
585      */
586     assert(code == BUS_MCEERR_AR || code == BUS_MCEERR_AO);
587 
588     if ((env->mcg_cap & MCG_SER_P) && addr) {
589         ram_addr = qemu_ram_addr_from_host(addr);
590         if (ram_addr != RAM_ADDR_INVALID &&
591             kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
592             kvm_hwpoison_page_add(ram_addr);
593             kvm_mce_inject(cpu, paddr, code);
594 
595             /*
596              * Use different logging severity based on error type.
597              * If there is additional MCE reporting on the hypervisor, QEMU VA
598              * could be another source to identify the PA and MCE details.
599              */
600             if (code == BUS_MCEERR_AR) {
601                 error_report("Guest MCE Memory Error at QEMU addr %p and "
602                     "GUEST addr 0x%" HWADDR_PRIx " of type %s injected",
603                     addr, paddr, "BUS_MCEERR_AR");
604             } else {
605                  warn_report("Guest MCE Memory Error at QEMU addr %p and "
606                      "GUEST addr 0x%" HWADDR_PRIx " of type %s injected",
607                      addr, paddr, "BUS_MCEERR_AO");
608             }
609 
610             return;
611         }
612 
613         if (code == BUS_MCEERR_AO) {
614             warn_report("Hardware memory error at addr %p of type %s "
615                 "for memory used by QEMU itself instead of guest system!",
616                  addr, "BUS_MCEERR_AO");
617         }
618     }
619 
620     if (code == BUS_MCEERR_AR) {
621         hardware_memory_error(addr);
622     }
623 
624     /* Hope we are lucky for AO MCE, just notify a event */
625     emit_hypervisor_memory_failure(MEMORY_FAILURE_ACTION_IGNORE, false);
626 }
627 
628 static void kvm_reset_exception(CPUX86State *env)
629 {
630     env->exception_nr = -1;
631     env->exception_pending = 0;
632     env->exception_injected = 0;
633     env->exception_has_payload = false;
634     env->exception_payload = 0;
635 }
636 
637 static void kvm_queue_exception(CPUX86State *env,
638                                 int32_t exception_nr,
639                                 uint8_t exception_has_payload,
640                                 uint64_t exception_payload)
641 {
642     assert(env->exception_nr == -1);
643     assert(!env->exception_pending);
644     assert(!env->exception_injected);
645     assert(!env->exception_has_payload);
646 
647     env->exception_nr = exception_nr;
648 
649     if (has_exception_payload) {
650         env->exception_pending = 1;
651 
652         env->exception_has_payload = exception_has_payload;
653         env->exception_payload = exception_payload;
654     } else {
655         env->exception_injected = 1;
656 
657         if (exception_nr == EXCP01_DB) {
658             assert(exception_has_payload);
659             env->dr[6] = exception_payload;
660         } else if (exception_nr == EXCP0E_PAGE) {
661             assert(exception_has_payload);
662             env->cr[2] = exception_payload;
663         } else {
664             assert(!exception_has_payload);
665         }
666     }
667 }
668 
669 static int kvm_inject_mce_oldstyle(X86CPU *cpu)
670 {
671     CPUX86State *env = &cpu->env;
672 
673     if (!kvm_has_vcpu_events() && env->exception_nr == EXCP12_MCHK) {
674         unsigned int bank, bank_num = env->mcg_cap & 0xff;
675         struct kvm_x86_mce mce;
676 
677         kvm_reset_exception(env);
678 
679         /*
680          * There must be at least one bank in use if an MCE is pending.
681          * Find it and use its values for the event injection.
682          */
683         for (bank = 0; bank < bank_num; bank++) {
684             if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
685                 break;
686             }
687         }
688         assert(bank < bank_num);
689 
690         mce.bank = bank;
691         mce.status = env->mce_banks[bank * 4 + 1];
692         mce.mcg_status = env->mcg_status;
693         mce.addr = env->mce_banks[bank * 4 + 2];
694         mce.misc = env->mce_banks[bank * 4 + 3];
695 
696         return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
697     }
698     return 0;
699 }
700 
701 static void cpu_update_state(void *opaque, bool running, RunState state)
702 {
703     CPUX86State *env = opaque;
704 
705     if (running) {
706         env->tsc_valid = false;
707     }
708 }
709 
710 unsigned long kvm_arch_vcpu_id(CPUState *cs)
711 {
712     X86CPU *cpu = X86_CPU(cs);
713     return cpu->apic_id;
714 }
715 
716 #ifndef KVM_CPUID_SIGNATURE_NEXT
717 #define KVM_CPUID_SIGNATURE_NEXT                0x40000100
718 #endif
719 
720 static bool hyperv_enabled(X86CPU *cpu)
721 {
722     return kvm_check_extension(kvm_state, KVM_CAP_HYPERV) > 0 &&
723         ((cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_NOTIFY) ||
724          cpu->hyperv_features || cpu->hyperv_passthrough);
725 }
726 
727 /*
728  * Check whether target_freq is within conservative
729  * ntp correctable bounds (250ppm) of freq
730  */
731 static inline bool freq_within_bounds(int freq, int target_freq)
732 {
733         int max_freq = freq + (freq * 250 / 1000000);
734         int min_freq = freq - (freq * 250 / 1000000);
735 
736         if (target_freq >= min_freq && target_freq <= max_freq) {
737                 return true;
738         }
739 
740         return false;
741 }
742 
743 static int kvm_arch_set_tsc_khz(CPUState *cs)
744 {
745     X86CPU *cpu = X86_CPU(cs);
746     CPUX86State *env = &cpu->env;
747     int r, cur_freq;
748     bool set_ioctl = false;
749 
750     if (!env->tsc_khz) {
751         return 0;
752     }
753 
754     cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
755                kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) : -ENOTSUP;
756 
757     /*
758      * If TSC scaling is supported, attempt to set TSC frequency.
759      */
760     if (kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL)) {
761         set_ioctl = true;
762     }
763 
764     /*
765      * If desired TSC frequency is within bounds of NTP correction,
766      * attempt to set TSC frequency.
767      */
768     if (cur_freq != -ENOTSUP && freq_within_bounds(cur_freq, env->tsc_khz)) {
769         set_ioctl = true;
770     }
771 
772     r = set_ioctl ?
773         kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) :
774         -ENOTSUP;
775 
776     if (r < 0) {
777         /* When KVM_SET_TSC_KHZ fails, it's an error only if the current
778          * TSC frequency doesn't match the one we want.
779          */
780         cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
781                    kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
782                    -ENOTSUP;
783         if (cur_freq <= 0 || cur_freq != env->tsc_khz) {
784             warn_report("TSC frequency mismatch between "
785                         "VM (%" PRId64 " kHz) and host (%d kHz), "
786                         "and TSC scaling unavailable",
787                         env->tsc_khz, cur_freq);
788             return r;
789         }
790     }
791 
792     return 0;
793 }
794 
795 static bool tsc_is_stable_and_known(CPUX86State *env)
796 {
797     if (!env->tsc_khz) {
798         return false;
799     }
800     return (env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC)
801         || env->user_tsc_khz;
802 }
803 
804 static struct {
805     const char *desc;
806     struct {
807         uint32_t func;
808         int reg;
809         uint32_t bits;
810     } flags[2];
811     uint64_t dependencies;
812 } kvm_hyperv_properties[] = {
813     [HYPERV_FEAT_RELAXED] = {
814         .desc = "relaxed timing (hv-relaxed)",
815         .flags = {
816             {.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
817              .bits = HV_RELAXED_TIMING_RECOMMENDED}
818         }
819     },
820     [HYPERV_FEAT_VAPIC] = {
821         .desc = "virtual APIC (hv-vapic)",
822         .flags = {
823             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
824              .bits = HV_APIC_ACCESS_AVAILABLE},
825             {.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
826              .bits = HV_APIC_ACCESS_RECOMMENDED}
827         }
828     },
829     [HYPERV_FEAT_TIME] = {
830         .desc = "clocksources (hv-time)",
831         .flags = {
832             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
833              .bits = HV_TIME_REF_COUNT_AVAILABLE | HV_REFERENCE_TSC_AVAILABLE}
834         }
835     },
836     [HYPERV_FEAT_CRASH] = {
837         .desc = "crash MSRs (hv-crash)",
838         .flags = {
839             {.func = HV_CPUID_FEATURES, .reg = R_EDX,
840              .bits = HV_GUEST_CRASH_MSR_AVAILABLE}
841         }
842     },
843     [HYPERV_FEAT_RESET] = {
844         .desc = "reset MSR (hv-reset)",
845         .flags = {
846             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
847              .bits = HV_RESET_AVAILABLE}
848         }
849     },
850     [HYPERV_FEAT_VPINDEX] = {
851         .desc = "VP_INDEX MSR (hv-vpindex)",
852         .flags = {
853             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
854              .bits = HV_VP_INDEX_AVAILABLE}
855         }
856     },
857     [HYPERV_FEAT_RUNTIME] = {
858         .desc = "VP_RUNTIME MSR (hv-runtime)",
859         .flags = {
860             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
861              .bits = HV_VP_RUNTIME_AVAILABLE}
862         }
863     },
864     [HYPERV_FEAT_SYNIC] = {
865         .desc = "synthetic interrupt controller (hv-synic)",
866         .flags = {
867             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
868              .bits = HV_SYNIC_AVAILABLE}
869         }
870     },
871     [HYPERV_FEAT_STIMER] = {
872         .desc = "synthetic timers (hv-stimer)",
873         .flags = {
874             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
875              .bits = HV_SYNTIMERS_AVAILABLE}
876         },
877         .dependencies = BIT(HYPERV_FEAT_SYNIC) | BIT(HYPERV_FEAT_TIME)
878     },
879     [HYPERV_FEAT_FREQUENCIES] = {
880         .desc = "frequency MSRs (hv-frequencies)",
881         .flags = {
882             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
883              .bits = HV_ACCESS_FREQUENCY_MSRS},
884             {.func = HV_CPUID_FEATURES, .reg = R_EDX,
885              .bits = HV_FREQUENCY_MSRS_AVAILABLE}
886         }
887     },
888     [HYPERV_FEAT_REENLIGHTENMENT] = {
889         .desc = "reenlightenment MSRs (hv-reenlightenment)",
890         .flags = {
891             {.func = HV_CPUID_FEATURES, .reg = R_EAX,
892              .bits = HV_ACCESS_REENLIGHTENMENTS_CONTROL}
893         }
894     },
895     [HYPERV_FEAT_TLBFLUSH] = {
896         .desc = "paravirtualized TLB flush (hv-tlbflush)",
897         .flags = {
898             {.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
899              .bits = HV_REMOTE_TLB_FLUSH_RECOMMENDED |
900              HV_EX_PROCESSOR_MASKS_RECOMMENDED}
901         },
902         .dependencies = BIT(HYPERV_FEAT_VPINDEX)
903     },
904     [HYPERV_FEAT_EVMCS] = {
905         .desc = "enlightened VMCS (hv-evmcs)",
906         .flags = {
907             {.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
908              .bits = HV_ENLIGHTENED_VMCS_RECOMMENDED}
909         },
910         .dependencies = BIT(HYPERV_FEAT_VAPIC)
911     },
912     [HYPERV_FEAT_IPI] = {
913         .desc = "paravirtualized IPI (hv-ipi)",
914         .flags = {
915             {.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
916              .bits = HV_CLUSTER_IPI_RECOMMENDED |
917              HV_EX_PROCESSOR_MASKS_RECOMMENDED}
918         },
919         .dependencies = BIT(HYPERV_FEAT_VPINDEX)
920     },
921     [HYPERV_FEAT_STIMER_DIRECT] = {
922         .desc = "direct mode synthetic timers (hv-stimer-direct)",
923         .flags = {
924             {.func = HV_CPUID_FEATURES, .reg = R_EDX,
925              .bits = HV_STIMER_DIRECT_MODE_AVAILABLE}
926         },
927         .dependencies = BIT(HYPERV_FEAT_STIMER)
928     },
929 };
930 
931 static struct kvm_cpuid2 *try_get_hv_cpuid(CPUState *cs, int max,
932                                            bool do_sys_ioctl)
933 {
934     struct kvm_cpuid2 *cpuid;
935     int r, size;
936 
937     size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
938     cpuid = g_malloc0(size);
939     cpuid->nent = max;
940 
941     if (do_sys_ioctl) {
942         r = kvm_ioctl(kvm_state, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
943     } else {
944         r = kvm_vcpu_ioctl(cs, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
945     }
946     if (r == 0 && cpuid->nent >= max) {
947         r = -E2BIG;
948     }
949     if (r < 0) {
950         if (r == -E2BIG) {
951             g_free(cpuid);
952             return NULL;
953         } else {
954             fprintf(stderr, "KVM_GET_SUPPORTED_HV_CPUID failed: %s\n",
955                     strerror(-r));
956             exit(1);
957         }
958     }
959     return cpuid;
960 }
961 
962 /*
963  * Run KVM_GET_SUPPORTED_HV_CPUID ioctl(), allocating a buffer large enough
964  * for all entries.
965  */
966 static struct kvm_cpuid2 *get_supported_hv_cpuid(CPUState *cs)
967 {
968     struct kvm_cpuid2 *cpuid;
969     /* 0x40000000..0x40000005, 0x4000000A, 0x40000080..0x40000080 leaves */
970     int max = 10;
971     int i;
972     bool do_sys_ioctl;
973 
974     do_sys_ioctl =
975         kvm_check_extension(kvm_state, KVM_CAP_SYS_HYPERV_CPUID) > 0;
976 
977     /*
978      * Non-empty KVM context is needed when KVM_CAP_SYS_HYPERV_CPUID is
979      * unsupported, kvm_hyperv_expand_features() checks for that.
980      */
981     assert(do_sys_ioctl || cs->kvm_state);
982 
983     /*
984      * When the buffer is too small, KVM_GET_SUPPORTED_HV_CPUID fails with
985      * -E2BIG, however, it doesn't report back the right size. Keep increasing
986      * it and re-trying until we succeed.
987      */
988     while ((cpuid = try_get_hv_cpuid(cs, max, do_sys_ioctl)) == NULL) {
989         max++;
990     }
991 
992     /*
993      * KVM_GET_SUPPORTED_HV_CPUID does not set EVMCS CPUID bit before
994      * KVM_CAP_HYPERV_ENLIGHTENED_VMCS is enabled but we want to get the
995      * information early, just check for the capability and set the bit
996      * manually.
997      */
998     if (!do_sys_ioctl && kvm_check_extension(cs->kvm_state,
999                             KVM_CAP_HYPERV_ENLIGHTENED_VMCS) > 0) {
1000         for (i = 0; i < cpuid->nent; i++) {
1001             if (cpuid->entries[i].function == HV_CPUID_ENLIGHTMENT_INFO) {
1002                 cpuid->entries[i].eax |= HV_ENLIGHTENED_VMCS_RECOMMENDED;
1003             }
1004         }
1005     }
1006 
1007     return cpuid;
1008 }
1009 
1010 /*
1011  * When KVM_GET_SUPPORTED_HV_CPUID is not supported we fill CPUID feature
1012  * leaves from KVM_CAP_HYPERV* and present MSRs data.
1013  */
1014 static struct kvm_cpuid2 *get_supported_hv_cpuid_legacy(CPUState *cs)
1015 {
1016     X86CPU *cpu = X86_CPU(cs);
1017     struct kvm_cpuid2 *cpuid;
1018     struct kvm_cpuid_entry2 *entry_feat, *entry_recomm;
1019 
1020     /* HV_CPUID_FEATURES, HV_CPUID_ENLIGHTMENT_INFO */
1021     cpuid = g_malloc0(sizeof(*cpuid) + 2 * sizeof(*cpuid->entries));
1022     cpuid->nent = 2;
1023 
1024     /* HV_CPUID_VENDOR_AND_MAX_FUNCTIONS */
1025     entry_feat = &cpuid->entries[0];
1026     entry_feat->function = HV_CPUID_FEATURES;
1027 
1028     entry_recomm = &cpuid->entries[1];
1029     entry_recomm->function = HV_CPUID_ENLIGHTMENT_INFO;
1030     entry_recomm->ebx = cpu->hyperv_spinlock_attempts;
1031 
1032     if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0) {
1033         entry_feat->eax |= HV_HYPERCALL_AVAILABLE;
1034         entry_feat->eax |= HV_APIC_ACCESS_AVAILABLE;
1035         entry_feat->edx |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
1036         entry_recomm->eax |= HV_RELAXED_TIMING_RECOMMENDED;
1037         entry_recomm->eax |= HV_APIC_ACCESS_RECOMMENDED;
1038     }
1039 
1040     if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) > 0) {
1041         entry_feat->eax |= HV_TIME_REF_COUNT_AVAILABLE;
1042         entry_feat->eax |= HV_REFERENCE_TSC_AVAILABLE;
1043     }
1044 
1045     if (has_msr_hv_frequencies) {
1046         entry_feat->eax |= HV_ACCESS_FREQUENCY_MSRS;
1047         entry_feat->edx |= HV_FREQUENCY_MSRS_AVAILABLE;
1048     }
1049 
1050     if (has_msr_hv_crash) {
1051         entry_feat->edx |= HV_GUEST_CRASH_MSR_AVAILABLE;
1052     }
1053 
1054     if (has_msr_hv_reenlightenment) {
1055         entry_feat->eax |= HV_ACCESS_REENLIGHTENMENTS_CONTROL;
1056     }
1057 
1058     if (has_msr_hv_reset) {
1059         entry_feat->eax |= HV_RESET_AVAILABLE;
1060     }
1061 
1062     if (has_msr_hv_vpindex) {
1063         entry_feat->eax |= HV_VP_INDEX_AVAILABLE;
1064     }
1065 
1066     if (has_msr_hv_runtime) {
1067         entry_feat->eax |= HV_VP_RUNTIME_AVAILABLE;
1068     }
1069 
1070     if (has_msr_hv_synic) {
1071         unsigned int cap = cpu->hyperv_synic_kvm_only ?
1072             KVM_CAP_HYPERV_SYNIC : KVM_CAP_HYPERV_SYNIC2;
1073 
1074         if (kvm_check_extension(cs->kvm_state, cap) > 0) {
1075             entry_feat->eax |= HV_SYNIC_AVAILABLE;
1076         }
1077     }
1078 
1079     if (has_msr_hv_stimer) {
1080         entry_feat->eax |= HV_SYNTIMERS_AVAILABLE;
1081     }
1082 
1083     if (kvm_check_extension(cs->kvm_state,
1084                             KVM_CAP_HYPERV_TLBFLUSH) > 0) {
1085         entry_recomm->eax |= HV_REMOTE_TLB_FLUSH_RECOMMENDED;
1086         entry_recomm->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
1087     }
1088 
1089     if (kvm_check_extension(cs->kvm_state,
1090                             KVM_CAP_HYPERV_ENLIGHTENED_VMCS) > 0) {
1091         entry_recomm->eax |= HV_ENLIGHTENED_VMCS_RECOMMENDED;
1092     }
1093 
1094     if (kvm_check_extension(cs->kvm_state,
1095                             KVM_CAP_HYPERV_SEND_IPI) > 0) {
1096         entry_recomm->eax |= HV_CLUSTER_IPI_RECOMMENDED;
1097         entry_recomm->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
1098     }
1099 
1100     return cpuid;
1101 }
1102 
1103 static uint32_t hv_cpuid_get_host(CPUState *cs, uint32_t func, int reg)
1104 {
1105     struct kvm_cpuid_entry2 *entry;
1106     struct kvm_cpuid2 *cpuid;
1107 
1108     if (hv_cpuid_cache) {
1109         cpuid = hv_cpuid_cache;
1110     } else {
1111         if (kvm_check_extension(kvm_state, KVM_CAP_HYPERV_CPUID) > 0) {
1112             cpuid = get_supported_hv_cpuid(cs);
1113         } else {
1114             /*
1115              * 'cs->kvm_state' may be NULL when Hyper-V features are expanded
1116              * before KVM context is created but this is only done when
1117              * KVM_CAP_SYS_HYPERV_CPUID is supported and it implies
1118              * KVM_CAP_HYPERV_CPUID.
1119              */
1120             assert(cs->kvm_state);
1121 
1122             cpuid = get_supported_hv_cpuid_legacy(cs);
1123         }
1124         hv_cpuid_cache = cpuid;
1125     }
1126 
1127     if (!cpuid) {
1128         return 0;
1129     }
1130 
1131     entry = cpuid_find_entry(cpuid, func, 0);
1132     if (!entry) {
1133         return 0;
1134     }
1135 
1136     return cpuid_entry_get_reg(entry, reg);
1137 }
1138 
1139 static bool hyperv_feature_supported(CPUState *cs, int feature)
1140 {
1141     uint32_t func, bits;
1142     int i, reg;
1143 
1144     for (i = 0; i < ARRAY_SIZE(kvm_hyperv_properties[feature].flags); i++) {
1145 
1146         func = kvm_hyperv_properties[feature].flags[i].func;
1147         reg = kvm_hyperv_properties[feature].flags[i].reg;
1148         bits = kvm_hyperv_properties[feature].flags[i].bits;
1149 
1150         if (!func) {
1151             continue;
1152         }
1153 
1154         if ((hv_cpuid_get_host(cs, func, reg) & bits) != bits) {
1155             return false;
1156         }
1157     }
1158 
1159     return true;
1160 }
1161 
1162 /* Checks that all feature dependencies are enabled */
1163 static bool hv_feature_check_deps(X86CPU *cpu, int feature, Error **errp)
1164 {
1165     uint64_t deps;
1166     int dep_feat;
1167 
1168     deps = kvm_hyperv_properties[feature].dependencies;
1169     while (deps) {
1170         dep_feat = ctz64(deps);
1171         if (!(hyperv_feat_enabled(cpu, dep_feat))) {
1172             error_setg(errp, "Hyper-V %s requires Hyper-V %s",
1173                        kvm_hyperv_properties[feature].desc,
1174                        kvm_hyperv_properties[dep_feat].desc);
1175             return false;
1176         }
1177         deps &= ~(1ull << dep_feat);
1178     }
1179 
1180     return true;
1181 }
1182 
1183 static uint32_t hv_build_cpuid_leaf(CPUState *cs, uint32_t func, int reg)
1184 {
1185     X86CPU *cpu = X86_CPU(cs);
1186     uint32_t r = 0;
1187     int i, j;
1188 
1189     for (i = 0; i < ARRAY_SIZE(kvm_hyperv_properties); i++) {
1190         if (!hyperv_feat_enabled(cpu, i)) {
1191             continue;
1192         }
1193 
1194         for (j = 0; j < ARRAY_SIZE(kvm_hyperv_properties[i].flags); j++) {
1195             if (kvm_hyperv_properties[i].flags[j].func != func) {
1196                 continue;
1197             }
1198             if (kvm_hyperv_properties[i].flags[j].reg != reg) {
1199                 continue;
1200             }
1201 
1202             r |= kvm_hyperv_properties[i].flags[j].bits;
1203         }
1204     }
1205 
1206     return r;
1207 }
1208 
1209 /*
1210  * Expand Hyper-V CPU features. In partucular, check that all the requested
1211  * features are supported by the host and the sanity of the configuration
1212  * (that all the required dependencies are included). Also, this takes care
1213  * of 'hv_passthrough' mode and fills the environment with all supported
1214  * Hyper-V features.
1215  */
1216 bool kvm_hyperv_expand_features(X86CPU *cpu, Error **errp)
1217 {
1218     CPUState *cs = CPU(cpu);
1219     Error *local_err = NULL;
1220     int feat;
1221 
1222     if (!hyperv_enabled(cpu))
1223         return true;
1224 
1225     /*
1226      * When kvm_hyperv_expand_features is called at CPU feature expansion
1227      * time per-CPU kvm_state is not available yet so we can only proceed
1228      * when KVM_CAP_SYS_HYPERV_CPUID is supported.
1229      */
1230     if (!cs->kvm_state &&
1231         !kvm_check_extension(kvm_state, KVM_CAP_SYS_HYPERV_CPUID))
1232         return true;
1233 
1234     if (cpu->hyperv_passthrough) {
1235         cpu->hyperv_vendor_id[0] =
1236             hv_cpuid_get_host(cs, HV_CPUID_VENDOR_AND_MAX_FUNCTIONS, R_EBX);
1237         cpu->hyperv_vendor_id[1] =
1238             hv_cpuid_get_host(cs, HV_CPUID_VENDOR_AND_MAX_FUNCTIONS, R_ECX);
1239         cpu->hyperv_vendor_id[2] =
1240             hv_cpuid_get_host(cs, HV_CPUID_VENDOR_AND_MAX_FUNCTIONS, R_EDX);
1241         cpu->hyperv_vendor = g_realloc(cpu->hyperv_vendor,
1242                                        sizeof(cpu->hyperv_vendor_id) + 1);
1243         memcpy(cpu->hyperv_vendor, cpu->hyperv_vendor_id,
1244                sizeof(cpu->hyperv_vendor_id));
1245         cpu->hyperv_vendor[sizeof(cpu->hyperv_vendor_id)] = 0;
1246 
1247         cpu->hyperv_interface_id[0] =
1248             hv_cpuid_get_host(cs, HV_CPUID_INTERFACE, R_EAX);
1249         cpu->hyperv_interface_id[1] =
1250             hv_cpuid_get_host(cs, HV_CPUID_INTERFACE, R_EBX);
1251         cpu->hyperv_interface_id[2] =
1252             hv_cpuid_get_host(cs, HV_CPUID_INTERFACE, R_ECX);
1253         cpu->hyperv_interface_id[3] =
1254             hv_cpuid_get_host(cs, HV_CPUID_INTERFACE, R_EDX);
1255 
1256         cpu->hyperv_version_id[0] =
1257             hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EAX);
1258         cpu->hyperv_version_id[1] =
1259             hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EBX);
1260         cpu->hyperv_version_id[2] =
1261             hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_ECX);
1262         cpu->hyperv_version_id[3] =
1263             hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EDX);
1264 
1265         cpu->hv_max_vps = hv_cpuid_get_host(cs, HV_CPUID_IMPLEMENT_LIMITS,
1266                                             R_EAX);
1267         cpu->hyperv_limits[0] =
1268             hv_cpuid_get_host(cs, HV_CPUID_IMPLEMENT_LIMITS, R_EBX);
1269         cpu->hyperv_limits[1] =
1270             hv_cpuid_get_host(cs, HV_CPUID_IMPLEMENT_LIMITS, R_ECX);
1271         cpu->hyperv_limits[2] =
1272             hv_cpuid_get_host(cs, HV_CPUID_IMPLEMENT_LIMITS, R_EDX);
1273 
1274         cpu->hyperv_spinlock_attempts =
1275             hv_cpuid_get_host(cs, HV_CPUID_ENLIGHTMENT_INFO, R_EBX);
1276 
1277         /*
1278          * Mark feature as enabled in 'cpu->hyperv_features' as
1279          * hv_build_cpuid_leaf() uses this info to build guest CPUIDs.
1280          */
1281         for (feat = 0; feat < ARRAY_SIZE(kvm_hyperv_properties); feat++) {
1282             if (hyperv_feature_supported(cs, feat)) {
1283                 cpu->hyperv_features |= BIT(feat);
1284             }
1285         }
1286     } else {
1287         /* Check features availability and dependencies */
1288         for (feat = 0; feat < ARRAY_SIZE(kvm_hyperv_properties); feat++) {
1289             /* If the feature was not requested skip it. */
1290             if (!hyperv_feat_enabled(cpu, feat)) {
1291                 continue;
1292             }
1293 
1294             /* Check if the feature is supported by KVM */
1295             if (!hyperv_feature_supported(cs, feat)) {
1296                 error_setg(errp, "Hyper-V %s is not supported by kernel",
1297                            kvm_hyperv_properties[feat].desc);
1298                 return false;
1299             }
1300 
1301             /* Check dependencies */
1302             if (!hv_feature_check_deps(cpu, feat, &local_err)) {
1303                 error_propagate(errp, local_err);
1304                 return false;
1305             }
1306         }
1307     }
1308 
1309     /* Additional dependencies not covered by kvm_hyperv_properties[] */
1310     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC) &&
1311         !cpu->hyperv_synic_kvm_only &&
1312         !hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)) {
1313         error_setg(errp, "Hyper-V %s requires Hyper-V %s",
1314                    kvm_hyperv_properties[HYPERV_FEAT_SYNIC].desc,
1315                    kvm_hyperv_properties[HYPERV_FEAT_VPINDEX].desc);
1316         return false;
1317     }
1318 
1319     return true;
1320 }
1321 
1322 /*
1323  * Fill in Hyper-V CPUIDs. Returns the number of entries filled in cpuid_ent.
1324  */
1325 static int hyperv_fill_cpuids(CPUState *cs,
1326                               struct kvm_cpuid_entry2 *cpuid_ent)
1327 {
1328     X86CPU *cpu = X86_CPU(cs);
1329     struct kvm_cpuid_entry2 *c;
1330     uint32_t cpuid_i = 0;
1331 
1332     c = &cpuid_ent[cpuid_i++];
1333     c->function = HV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
1334     c->eax = hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS) ?
1335         HV_CPUID_NESTED_FEATURES : HV_CPUID_IMPLEMENT_LIMITS;
1336     c->ebx = cpu->hyperv_vendor_id[0];
1337     c->ecx = cpu->hyperv_vendor_id[1];
1338     c->edx = cpu->hyperv_vendor_id[2];
1339 
1340     c = &cpuid_ent[cpuid_i++];
1341     c->function = HV_CPUID_INTERFACE;
1342     c->eax = cpu->hyperv_interface_id[0];
1343     c->ebx = cpu->hyperv_interface_id[1];
1344     c->ecx = cpu->hyperv_interface_id[2];
1345     c->edx = cpu->hyperv_interface_id[3];
1346 
1347     c = &cpuid_ent[cpuid_i++];
1348     c->function = HV_CPUID_VERSION;
1349     c->eax = cpu->hyperv_version_id[0];
1350     c->ebx = cpu->hyperv_version_id[1];
1351     c->ecx = cpu->hyperv_version_id[2];
1352     c->edx = cpu->hyperv_version_id[3];
1353 
1354     c = &cpuid_ent[cpuid_i++];
1355     c->function = HV_CPUID_FEATURES;
1356     c->eax = hv_build_cpuid_leaf(cs, HV_CPUID_FEATURES, R_EAX);
1357     c->ebx = hv_build_cpuid_leaf(cs, HV_CPUID_FEATURES, R_EBX);
1358     c->edx = hv_build_cpuid_leaf(cs, HV_CPUID_FEATURES, R_EDX);
1359 
1360     /* Unconditionally required with any Hyper-V enlightenment */
1361     c->eax |= HV_HYPERCALL_AVAILABLE;
1362 
1363     /* SynIC and Vmbus devices require messages/signals hypercalls */
1364     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC) &&
1365         !cpu->hyperv_synic_kvm_only) {
1366         c->ebx |= HV_POST_MESSAGES | HV_SIGNAL_EVENTS;
1367     }
1368 
1369     /* Not exposed by KVM but needed to make CPU hotplug in Windows work */
1370     c->edx |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
1371 
1372     c = &cpuid_ent[cpuid_i++];
1373     c->function = HV_CPUID_ENLIGHTMENT_INFO;
1374     c->eax = hv_build_cpuid_leaf(cs, HV_CPUID_ENLIGHTMENT_INFO, R_EAX);
1375     c->ebx = cpu->hyperv_spinlock_attempts;
1376 
1377     if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_ON) {
1378         c->eax |= HV_NO_NONARCH_CORESHARING;
1379     } else if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_AUTO) {
1380         c->eax |= hv_cpuid_get_host(cs, HV_CPUID_ENLIGHTMENT_INFO, R_EAX) &
1381             HV_NO_NONARCH_CORESHARING;
1382     }
1383 
1384     c = &cpuid_ent[cpuid_i++];
1385     c->function = HV_CPUID_IMPLEMENT_LIMITS;
1386     c->eax = cpu->hv_max_vps;
1387     c->ebx = cpu->hyperv_limits[0];
1388     c->ecx = cpu->hyperv_limits[1];
1389     c->edx = cpu->hyperv_limits[2];
1390 
1391     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS)) {
1392         __u32 function;
1393 
1394         /* Create zeroed 0x40000006..0x40000009 leaves */
1395         for (function = HV_CPUID_IMPLEMENT_LIMITS + 1;
1396              function < HV_CPUID_NESTED_FEATURES; function++) {
1397             c = &cpuid_ent[cpuid_i++];
1398             c->function = function;
1399         }
1400 
1401         c = &cpuid_ent[cpuid_i++];
1402         c->function = HV_CPUID_NESTED_FEATURES;
1403         c->eax = cpu->hyperv_nested[0];
1404     }
1405 
1406     return cpuid_i;
1407 }
1408 
1409 static Error *hv_passthrough_mig_blocker;
1410 static Error *hv_no_nonarch_cs_mig_blocker;
1411 
1412 /* Checks that the exposed eVMCS version range is supported by KVM */
1413 static bool evmcs_version_supported(uint16_t evmcs_version,
1414                                     uint16_t supported_evmcs_version)
1415 {
1416     uint8_t min_version = evmcs_version & 0xff;
1417     uint8_t max_version = evmcs_version >> 8;
1418     uint8_t min_supported_version = supported_evmcs_version & 0xff;
1419     uint8_t max_supported_version = supported_evmcs_version >> 8;
1420 
1421     return (min_version >= min_supported_version) &&
1422         (max_version <= max_supported_version);
1423 }
1424 
1425 #define DEFAULT_EVMCS_VERSION ((1 << 8) | 1)
1426 
1427 static int hyperv_init_vcpu(X86CPU *cpu)
1428 {
1429     CPUState *cs = CPU(cpu);
1430     Error *local_err = NULL;
1431     int ret;
1432 
1433     if (cpu->hyperv_passthrough && hv_passthrough_mig_blocker == NULL) {
1434         error_setg(&hv_passthrough_mig_blocker,
1435                    "'hv-passthrough' CPU flag prevents migration, use explicit"
1436                    " set of hv-* flags instead");
1437         ret = migrate_add_blocker(hv_passthrough_mig_blocker, &local_err);
1438         if (local_err) {
1439             error_report_err(local_err);
1440             error_free(hv_passthrough_mig_blocker);
1441             return ret;
1442         }
1443     }
1444 
1445     if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_AUTO &&
1446         hv_no_nonarch_cs_mig_blocker == NULL) {
1447         error_setg(&hv_no_nonarch_cs_mig_blocker,
1448                    "'hv-no-nonarch-coresharing=auto' CPU flag prevents migration"
1449                    " use explicit 'hv-no-nonarch-coresharing=on' instead (but"
1450                    " make sure SMT is disabled and/or that vCPUs are properly"
1451                    " pinned)");
1452         ret = migrate_add_blocker(hv_no_nonarch_cs_mig_blocker, &local_err);
1453         if (local_err) {
1454             error_report_err(local_err);
1455             error_free(hv_no_nonarch_cs_mig_blocker);
1456             return ret;
1457         }
1458     }
1459 
1460     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX) && !hv_vpindex_settable) {
1461         /*
1462          * the kernel doesn't support setting vp_index; assert that its value
1463          * is in sync
1464          */
1465         struct {
1466             struct kvm_msrs info;
1467             struct kvm_msr_entry entries[1];
1468         } msr_data = {
1469             .info.nmsrs = 1,
1470             .entries[0].index = HV_X64_MSR_VP_INDEX,
1471         };
1472 
1473         ret = kvm_vcpu_ioctl(cs, KVM_GET_MSRS, &msr_data);
1474         if (ret < 0) {
1475             return ret;
1476         }
1477         assert(ret == 1);
1478 
1479         if (msr_data.entries[0].data != hyperv_vp_index(CPU(cpu))) {
1480             error_report("kernel's vp_index != QEMU's vp_index");
1481             return -ENXIO;
1482         }
1483     }
1484 
1485     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
1486         uint32_t synic_cap = cpu->hyperv_synic_kvm_only ?
1487             KVM_CAP_HYPERV_SYNIC : KVM_CAP_HYPERV_SYNIC2;
1488         ret = kvm_vcpu_enable_cap(cs, synic_cap, 0);
1489         if (ret < 0) {
1490             error_report("failed to turn on HyperV SynIC in KVM: %s",
1491                          strerror(-ret));
1492             return ret;
1493         }
1494 
1495         if (!cpu->hyperv_synic_kvm_only) {
1496             ret = hyperv_x86_synic_add(cpu);
1497             if (ret < 0) {
1498                 error_report("failed to create HyperV SynIC: %s",
1499                              strerror(-ret));
1500                 return ret;
1501             }
1502         }
1503     }
1504 
1505     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS)) {
1506         uint16_t evmcs_version = DEFAULT_EVMCS_VERSION;
1507         uint16_t supported_evmcs_version;
1508 
1509         ret = kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_ENLIGHTENED_VMCS, 0,
1510                                   (uintptr_t)&supported_evmcs_version);
1511 
1512         /*
1513          * KVM is required to support EVMCS ver.1. as that's what 'hv-evmcs'
1514          * option sets. Note: we hardcode the maximum supported eVMCS version
1515          * to '1' as well so 'hv-evmcs' feature is migratable even when (and if)
1516          * ver.2 is implemented. A new option (e.g. 'hv-evmcs=2') will then have
1517          * to be added.
1518          */
1519         if (ret < 0) {
1520             error_report("Hyper-V %s is not supported by kernel",
1521                          kvm_hyperv_properties[HYPERV_FEAT_EVMCS].desc);
1522             return ret;
1523         }
1524 
1525         if (!evmcs_version_supported(evmcs_version, supported_evmcs_version)) {
1526             error_report("eVMCS version range [%d..%d] is not supported by "
1527                          "kernel (supported: [%d..%d])", evmcs_version & 0xff,
1528                          evmcs_version >> 8, supported_evmcs_version & 0xff,
1529                          supported_evmcs_version >> 8);
1530             return -ENOTSUP;
1531         }
1532 
1533         cpu->hyperv_nested[0] = evmcs_version;
1534     }
1535 
1536     return 0;
1537 }
1538 
1539 static Error *invtsc_mig_blocker;
1540 
1541 #define KVM_MAX_CPUID_ENTRIES  100
1542 
1543 int kvm_arch_init_vcpu(CPUState *cs)
1544 {
1545     struct {
1546         struct kvm_cpuid2 cpuid;
1547         struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
1548     } cpuid_data;
1549     /*
1550      * The kernel defines these structs with padding fields so there
1551      * should be no extra padding in our cpuid_data struct.
1552      */
1553     QEMU_BUILD_BUG_ON(sizeof(cpuid_data) !=
1554                       sizeof(struct kvm_cpuid2) +
1555                       sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES);
1556 
1557     X86CPU *cpu = X86_CPU(cs);
1558     CPUX86State *env = &cpu->env;
1559     uint32_t limit, i, j, cpuid_i;
1560     uint32_t unused;
1561     struct kvm_cpuid_entry2 *c;
1562     uint32_t signature[3];
1563     int kvm_base = KVM_CPUID_SIGNATURE;
1564     int max_nested_state_len;
1565     int r;
1566     Error *local_err = NULL;
1567 
1568     memset(&cpuid_data, 0, sizeof(cpuid_data));
1569 
1570     cpuid_i = 0;
1571 
1572     r = kvm_arch_set_tsc_khz(cs);
1573     if (r < 0) {
1574         return r;
1575     }
1576 
1577     /* vcpu's TSC frequency is either specified by user, or following
1578      * the value used by KVM if the former is not present. In the
1579      * latter case, we query it from KVM and record in env->tsc_khz,
1580      * so that vcpu's TSC frequency can be migrated later via this field.
1581      */
1582     if (!env->tsc_khz) {
1583         r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
1584             kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
1585             -ENOTSUP;
1586         if (r > 0) {
1587             env->tsc_khz = r;
1588         }
1589     }
1590 
1591     env->apic_bus_freq = KVM_APIC_BUS_FREQUENCY;
1592 
1593     /*
1594      * kvm_hyperv_expand_features() is called here for the second time in case
1595      * KVM_CAP_SYS_HYPERV_CPUID is not supported. While we can't possibly handle
1596      * 'query-cpu-model-expansion' in this case as we don't have a KVM vCPU to
1597      * check which Hyper-V enlightenments are supported and which are not, we
1598      * can still proceed and check/expand Hyper-V enlightenments here so legacy
1599      * behavior is preserved.
1600      */
1601     if (!kvm_hyperv_expand_features(cpu, &local_err)) {
1602         error_report_err(local_err);
1603         return -ENOSYS;
1604     }
1605 
1606     if (hyperv_enabled(cpu)) {
1607         r = hyperv_init_vcpu(cpu);
1608         if (r) {
1609             return r;
1610         }
1611 
1612         cpuid_i = hyperv_fill_cpuids(cs, cpuid_data.entries);
1613         kvm_base = KVM_CPUID_SIGNATURE_NEXT;
1614         has_msr_hv_hypercall = true;
1615     }
1616 
1617     if (cpu->expose_kvm) {
1618         memcpy(signature, "KVMKVMKVM\0\0\0", 12);
1619         c = &cpuid_data.entries[cpuid_i++];
1620         c->function = KVM_CPUID_SIGNATURE | kvm_base;
1621         c->eax = KVM_CPUID_FEATURES | kvm_base;
1622         c->ebx = signature[0];
1623         c->ecx = signature[1];
1624         c->edx = signature[2];
1625 
1626         c = &cpuid_data.entries[cpuid_i++];
1627         c->function = KVM_CPUID_FEATURES | kvm_base;
1628         c->eax = env->features[FEAT_KVM];
1629         c->edx = env->features[FEAT_KVM_HINTS];
1630     }
1631 
1632     cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
1633 
1634     for (i = 0; i <= limit; i++) {
1635         if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1636             fprintf(stderr, "unsupported level value: 0x%x\n", limit);
1637             abort();
1638         }
1639         c = &cpuid_data.entries[cpuid_i++];
1640 
1641         switch (i) {
1642         case 2: {
1643             /* Keep reading function 2 till all the input is received */
1644             int times;
1645 
1646             c->function = i;
1647             c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
1648                        KVM_CPUID_FLAG_STATE_READ_NEXT;
1649             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1650             times = c->eax & 0xff;
1651 
1652             for (j = 1; j < times; ++j) {
1653                 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1654                     fprintf(stderr, "cpuid_data is full, no space for "
1655                             "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
1656                     abort();
1657                 }
1658                 c = &cpuid_data.entries[cpuid_i++];
1659                 c->function = i;
1660                 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
1661                 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1662             }
1663             break;
1664         }
1665         case 0x1f:
1666             if (env->nr_dies < 2) {
1667                 break;
1668             }
1669             /* fallthrough */
1670         case 4:
1671         case 0xb:
1672         case 0xd:
1673             for (j = 0; ; j++) {
1674                 if (i == 0xd && j == 64) {
1675                     break;
1676                 }
1677 
1678                 if (i == 0x1f && j == 64) {
1679                     break;
1680                 }
1681 
1682                 c->function = i;
1683                 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1684                 c->index = j;
1685                 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1686 
1687                 if (i == 4 && c->eax == 0) {
1688                     break;
1689                 }
1690                 if (i == 0xb && !(c->ecx & 0xff00)) {
1691                     break;
1692                 }
1693                 if (i == 0x1f && !(c->ecx & 0xff00)) {
1694                     break;
1695                 }
1696                 if (i == 0xd && c->eax == 0) {
1697                     continue;
1698                 }
1699                 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1700                     fprintf(stderr, "cpuid_data is full, no space for "
1701                             "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1702                     abort();
1703                 }
1704                 c = &cpuid_data.entries[cpuid_i++];
1705             }
1706             break;
1707         case 0x7:
1708         case 0x14: {
1709             uint32_t times;
1710 
1711             c->function = i;
1712             c->index = 0;
1713             c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1714             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1715             times = c->eax;
1716 
1717             for (j = 1; j <= times; ++j) {
1718                 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1719                     fprintf(stderr, "cpuid_data is full, no space for "
1720                                 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1721                     abort();
1722                 }
1723                 c = &cpuid_data.entries[cpuid_i++];
1724                 c->function = i;
1725                 c->index = j;
1726                 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1727                 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1728             }
1729             break;
1730         }
1731         default:
1732             c->function = i;
1733             c->flags = 0;
1734             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1735             if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
1736                 /*
1737                  * KVM already returns all zeroes if a CPUID entry is missing,
1738                  * so we can omit it and avoid hitting KVM's 80-entry limit.
1739                  */
1740                 cpuid_i--;
1741             }
1742             break;
1743         }
1744     }
1745 
1746     if (limit >= 0x0a) {
1747         uint32_t eax, edx;
1748 
1749         cpu_x86_cpuid(env, 0x0a, 0, &eax, &unused, &unused, &edx);
1750 
1751         has_architectural_pmu_version = eax & 0xff;
1752         if (has_architectural_pmu_version > 0) {
1753             num_architectural_pmu_gp_counters = (eax & 0xff00) >> 8;
1754 
1755             /* Shouldn't be more than 32, since that's the number of bits
1756              * available in EBX to tell us _which_ counters are available.
1757              * Play it safe.
1758              */
1759             if (num_architectural_pmu_gp_counters > MAX_GP_COUNTERS) {
1760                 num_architectural_pmu_gp_counters = MAX_GP_COUNTERS;
1761             }
1762 
1763             if (has_architectural_pmu_version > 1) {
1764                 num_architectural_pmu_fixed_counters = edx & 0x1f;
1765 
1766                 if (num_architectural_pmu_fixed_counters > MAX_FIXED_COUNTERS) {
1767                     num_architectural_pmu_fixed_counters = MAX_FIXED_COUNTERS;
1768                 }
1769             }
1770         }
1771     }
1772 
1773     cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
1774 
1775     for (i = 0x80000000; i <= limit; i++) {
1776         if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1777             fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
1778             abort();
1779         }
1780         c = &cpuid_data.entries[cpuid_i++];
1781 
1782         switch (i) {
1783         case 0x8000001d:
1784             /* Query for all AMD cache information leaves */
1785             for (j = 0; ; j++) {
1786                 c->function = i;
1787                 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1788                 c->index = j;
1789                 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1790 
1791                 if (c->eax == 0) {
1792                     break;
1793                 }
1794                 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1795                     fprintf(stderr, "cpuid_data is full, no space for "
1796                             "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1797                     abort();
1798                 }
1799                 c = &cpuid_data.entries[cpuid_i++];
1800             }
1801             break;
1802         default:
1803             c->function = i;
1804             c->flags = 0;
1805             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1806             if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
1807                 /*
1808                  * KVM already returns all zeroes if a CPUID entry is missing,
1809                  * so we can omit it and avoid hitting KVM's 80-entry limit.
1810                  */
1811                 cpuid_i--;
1812             }
1813             break;
1814         }
1815     }
1816 
1817     /* Call Centaur's CPUID instructions they are supported. */
1818     if (env->cpuid_xlevel2 > 0) {
1819         cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
1820 
1821         for (i = 0xC0000000; i <= limit; i++) {
1822             if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1823                 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
1824                 abort();
1825             }
1826             c = &cpuid_data.entries[cpuid_i++];
1827 
1828             c->function = i;
1829             c->flags = 0;
1830             cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1831         }
1832     }
1833 
1834     cpuid_data.cpuid.nent = cpuid_i;
1835 
1836     if (((env->cpuid_version >> 8)&0xF) >= 6
1837         && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
1838            (CPUID_MCE | CPUID_MCA)
1839         && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
1840         uint64_t mcg_cap, unsupported_caps;
1841         int banks;
1842         int ret;
1843 
1844         ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
1845         if (ret < 0) {
1846             fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
1847             return ret;
1848         }
1849 
1850         if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
1851             error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
1852                          (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
1853             return -ENOTSUP;
1854         }
1855 
1856         unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
1857         if (unsupported_caps) {
1858             if (unsupported_caps & MCG_LMCE_P) {
1859                 error_report("kvm: LMCE not supported");
1860                 return -ENOTSUP;
1861             }
1862             warn_report("Unsupported MCG_CAP bits: 0x%" PRIx64,
1863                         unsupported_caps);
1864         }
1865 
1866         env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
1867         ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
1868         if (ret < 0) {
1869             fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
1870             return ret;
1871         }
1872     }
1873 
1874     cpu->vmsentry = qemu_add_vm_change_state_handler(cpu_update_state, env);
1875 
1876     c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
1877     if (c) {
1878         has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
1879                                   !!(c->ecx & CPUID_EXT_SMX);
1880     }
1881 
1882     if (env->mcg_cap & MCG_LMCE_P) {
1883         has_msr_mcg_ext_ctl = has_msr_feature_control = true;
1884     }
1885 
1886     if (!env->user_tsc_khz) {
1887         if ((env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC) &&
1888             invtsc_mig_blocker == NULL) {
1889             error_setg(&invtsc_mig_blocker,
1890                        "State blocked by non-migratable CPU device"
1891                        " (invtsc flag)");
1892             r = migrate_add_blocker(invtsc_mig_blocker, &local_err);
1893             if (local_err) {
1894                 error_report_err(local_err);
1895                 error_free(invtsc_mig_blocker);
1896                 return r;
1897             }
1898         }
1899     }
1900 
1901     if (cpu->vmware_cpuid_freq
1902         /* Guests depend on 0x40000000 to detect this feature, so only expose
1903          * it if KVM exposes leaf 0x40000000. (Conflicts with Hyper-V) */
1904         && cpu->expose_kvm
1905         && kvm_base == KVM_CPUID_SIGNATURE
1906         /* TSC clock must be stable and known for this feature. */
1907         && tsc_is_stable_and_known(env)) {
1908 
1909         c = &cpuid_data.entries[cpuid_i++];
1910         c->function = KVM_CPUID_SIGNATURE | 0x10;
1911         c->eax = env->tsc_khz;
1912         c->ebx = env->apic_bus_freq / 1000; /* Hz to KHz */
1913         c->ecx = c->edx = 0;
1914 
1915         c = cpuid_find_entry(&cpuid_data.cpuid, kvm_base, 0);
1916         c->eax = MAX(c->eax, KVM_CPUID_SIGNATURE | 0x10);
1917     }
1918 
1919     cpuid_data.cpuid.nent = cpuid_i;
1920 
1921     cpuid_data.cpuid.padding = 0;
1922     r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
1923     if (r) {
1924         goto fail;
1925     }
1926 
1927     if (has_xsave) {
1928         env->xsave_buf_len = sizeof(struct kvm_xsave);
1929         env->xsave_buf = qemu_memalign(4096, env->xsave_buf_len);
1930         memset(env->xsave_buf, 0, env->xsave_buf_len);
1931 
1932         /*
1933          * The allocated storage must be large enough for all of the
1934          * possible XSAVE state components.
1935          */
1936         assert(kvm_arch_get_supported_cpuid(kvm_state, 0xd, 0, R_ECX)
1937                <= env->xsave_buf_len);
1938     }
1939 
1940     max_nested_state_len = kvm_max_nested_state_length();
1941     if (max_nested_state_len > 0) {
1942         assert(max_nested_state_len >= offsetof(struct kvm_nested_state, data));
1943 
1944         if (cpu_has_vmx(env) || cpu_has_svm(env)) {
1945             struct kvm_vmx_nested_state_hdr *vmx_hdr;
1946 
1947             env->nested_state = g_malloc0(max_nested_state_len);
1948             env->nested_state->size = max_nested_state_len;
1949 
1950             if (cpu_has_vmx(env)) {
1951                 env->nested_state->format = KVM_STATE_NESTED_FORMAT_VMX;
1952                 vmx_hdr = &env->nested_state->hdr.vmx;
1953                 vmx_hdr->vmxon_pa = -1ull;
1954                 vmx_hdr->vmcs12_pa = -1ull;
1955             } else {
1956                 env->nested_state->format = KVM_STATE_NESTED_FORMAT_SVM;
1957             }
1958         }
1959     }
1960 
1961     cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
1962 
1963     if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
1964         has_msr_tsc_aux = false;
1965     }
1966 
1967     kvm_init_msrs(cpu);
1968 
1969     return 0;
1970 
1971  fail:
1972     migrate_del_blocker(invtsc_mig_blocker);
1973 
1974     return r;
1975 }
1976 
1977 int kvm_arch_destroy_vcpu(CPUState *cs)
1978 {
1979     X86CPU *cpu = X86_CPU(cs);
1980     CPUX86State *env = &cpu->env;
1981 
1982     if (cpu->kvm_msr_buf) {
1983         g_free(cpu->kvm_msr_buf);
1984         cpu->kvm_msr_buf = NULL;
1985     }
1986 
1987     if (env->nested_state) {
1988         g_free(env->nested_state);
1989         env->nested_state = NULL;
1990     }
1991 
1992     qemu_del_vm_change_state_handler(cpu->vmsentry);
1993 
1994     return 0;
1995 }
1996 
1997 void kvm_arch_reset_vcpu(X86CPU *cpu)
1998 {
1999     CPUX86State *env = &cpu->env;
2000 
2001     env->xcr0 = 1;
2002     if (kvm_irqchip_in_kernel()) {
2003         env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
2004                                           KVM_MP_STATE_UNINITIALIZED;
2005     } else {
2006         env->mp_state = KVM_MP_STATE_RUNNABLE;
2007     }
2008 
2009     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
2010         int i;
2011         for (i = 0; i < ARRAY_SIZE(env->msr_hv_synic_sint); i++) {
2012             env->msr_hv_synic_sint[i] = HV_SINT_MASKED;
2013         }
2014 
2015         hyperv_x86_synic_reset(cpu);
2016     }
2017     /* enabled by default */
2018     env->poll_control_msr = 1;
2019 
2020     sev_es_set_reset_vector(CPU(cpu));
2021 }
2022 
2023 void kvm_arch_do_init_vcpu(X86CPU *cpu)
2024 {
2025     CPUX86State *env = &cpu->env;
2026 
2027     /* APs get directly into wait-for-SIPI state.  */
2028     if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
2029         env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
2030     }
2031 }
2032 
2033 static int kvm_get_supported_feature_msrs(KVMState *s)
2034 {
2035     int ret = 0;
2036 
2037     if (kvm_feature_msrs != NULL) {
2038         return 0;
2039     }
2040 
2041     if (!kvm_check_extension(s, KVM_CAP_GET_MSR_FEATURES)) {
2042         return 0;
2043     }
2044 
2045     struct kvm_msr_list msr_list;
2046 
2047     msr_list.nmsrs = 0;
2048     ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, &msr_list);
2049     if (ret < 0 && ret != -E2BIG) {
2050         error_report("Fetch KVM feature MSR list failed: %s",
2051             strerror(-ret));
2052         return ret;
2053     }
2054 
2055     assert(msr_list.nmsrs > 0);
2056     kvm_feature_msrs = (struct kvm_msr_list *) \
2057         g_malloc0(sizeof(msr_list) +
2058                  msr_list.nmsrs * sizeof(msr_list.indices[0]));
2059 
2060     kvm_feature_msrs->nmsrs = msr_list.nmsrs;
2061     ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, kvm_feature_msrs);
2062 
2063     if (ret < 0) {
2064         error_report("Fetch KVM feature MSR list failed: %s",
2065             strerror(-ret));
2066         g_free(kvm_feature_msrs);
2067         kvm_feature_msrs = NULL;
2068         return ret;
2069     }
2070 
2071     return 0;
2072 }
2073 
2074 static int kvm_get_supported_msrs(KVMState *s)
2075 {
2076     int ret = 0;
2077     struct kvm_msr_list msr_list, *kvm_msr_list;
2078 
2079     /*
2080      *  Obtain MSR list from KVM.  These are the MSRs that we must
2081      *  save/restore.
2082      */
2083     msr_list.nmsrs = 0;
2084     ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
2085     if (ret < 0 && ret != -E2BIG) {
2086         return ret;
2087     }
2088     /*
2089      * Old kernel modules had a bug and could write beyond the provided
2090      * memory. Allocate at least a safe amount of 1K.
2091      */
2092     kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
2093                                           msr_list.nmsrs *
2094                                           sizeof(msr_list.indices[0])));
2095 
2096     kvm_msr_list->nmsrs = msr_list.nmsrs;
2097     ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
2098     if (ret >= 0) {
2099         int i;
2100 
2101         for (i = 0; i < kvm_msr_list->nmsrs; i++) {
2102             switch (kvm_msr_list->indices[i]) {
2103             case MSR_STAR:
2104                 has_msr_star = true;
2105                 break;
2106             case MSR_VM_HSAVE_PA:
2107                 has_msr_hsave_pa = true;
2108                 break;
2109             case MSR_TSC_AUX:
2110                 has_msr_tsc_aux = true;
2111                 break;
2112             case MSR_TSC_ADJUST:
2113                 has_msr_tsc_adjust = true;
2114                 break;
2115             case MSR_IA32_TSCDEADLINE:
2116                 has_msr_tsc_deadline = true;
2117                 break;
2118             case MSR_IA32_SMBASE:
2119                 has_msr_smbase = true;
2120                 break;
2121             case MSR_SMI_COUNT:
2122                 has_msr_smi_count = true;
2123                 break;
2124             case MSR_IA32_MISC_ENABLE:
2125                 has_msr_misc_enable = true;
2126                 break;
2127             case MSR_IA32_BNDCFGS:
2128                 has_msr_bndcfgs = true;
2129                 break;
2130             case MSR_IA32_XSS:
2131                 has_msr_xss = true;
2132                 break;
2133             case MSR_IA32_UMWAIT_CONTROL:
2134                 has_msr_umwait = true;
2135                 break;
2136             case HV_X64_MSR_CRASH_CTL:
2137                 has_msr_hv_crash = true;
2138                 break;
2139             case HV_X64_MSR_RESET:
2140                 has_msr_hv_reset = true;
2141                 break;
2142             case HV_X64_MSR_VP_INDEX:
2143                 has_msr_hv_vpindex = true;
2144                 break;
2145             case HV_X64_MSR_VP_RUNTIME:
2146                 has_msr_hv_runtime = true;
2147                 break;
2148             case HV_X64_MSR_SCONTROL:
2149                 has_msr_hv_synic = true;
2150                 break;
2151             case HV_X64_MSR_STIMER0_CONFIG:
2152                 has_msr_hv_stimer = true;
2153                 break;
2154             case HV_X64_MSR_TSC_FREQUENCY:
2155                 has_msr_hv_frequencies = true;
2156                 break;
2157             case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2158                 has_msr_hv_reenlightenment = true;
2159                 break;
2160             case MSR_IA32_SPEC_CTRL:
2161                 has_msr_spec_ctrl = true;
2162                 break;
2163             case MSR_IA32_TSX_CTRL:
2164                 has_msr_tsx_ctrl = true;
2165                 break;
2166             case MSR_VIRT_SSBD:
2167                 has_msr_virt_ssbd = true;
2168                 break;
2169             case MSR_IA32_ARCH_CAPABILITIES:
2170                 has_msr_arch_capabs = true;
2171                 break;
2172             case MSR_IA32_CORE_CAPABILITY:
2173                 has_msr_core_capabs = true;
2174                 break;
2175             case MSR_IA32_PERF_CAPABILITIES:
2176                 has_msr_perf_capabs = true;
2177                 break;
2178             case MSR_IA32_VMX_VMFUNC:
2179                 has_msr_vmx_vmfunc = true;
2180                 break;
2181             case MSR_IA32_UCODE_REV:
2182                 has_msr_ucode_rev = true;
2183                 break;
2184             case MSR_IA32_VMX_PROCBASED_CTLS2:
2185                 has_msr_vmx_procbased_ctls2 = true;
2186                 break;
2187             case MSR_IA32_PKRS:
2188                 has_msr_pkrs = true;
2189                 break;
2190             }
2191         }
2192     }
2193 
2194     g_free(kvm_msr_list);
2195 
2196     return ret;
2197 }
2198 
2199 static Notifier smram_machine_done;
2200 static KVMMemoryListener smram_listener;
2201 static AddressSpace smram_address_space;
2202 static MemoryRegion smram_as_root;
2203 static MemoryRegion smram_as_mem;
2204 
2205 static void register_smram_listener(Notifier *n, void *unused)
2206 {
2207     MemoryRegion *smram =
2208         (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
2209 
2210     /* Outer container... */
2211     memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
2212     memory_region_set_enabled(&smram_as_root, true);
2213 
2214     /* ... with two regions inside: normal system memory with low
2215      * priority, and...
2216      */
2217     memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
2218                              get_system_memory(), 0, ~0ull);
2219     memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
2220     memory_region_set_enabled(&smram_as_mem, true);
2221 
2222     if (smram) {
2223         /* ... SMRAM with higher priority */
2224         memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
2225         memory_region_set_enabled(smram, true);
2226     }
2227 
2228     address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
2229     kvm_memory_listener_register(kvm_state, &smram_listener,
2230                                  &smram_address_space, 1);
2231 }
2232 
2233 int kvm_arch_init(MachineState *ms, KVMState *s)
2234 {
2235     uint64_t identity_base = 0xfffbc000;
2236     uint64_t shadow_mem;
2237     int ret;
2238     struct utsname utsname;
2239     Error *local_err = NULL;
2240 
2241     /*
2242      * Initialize SEV context, if required
2243      *
2244      * If no memory encryption is requested (ms->cgs == NULL) this is
2245      * a no-op.
2246      *
2247      * It's also a no-op if a non-SEV confidential guest support
2248      * mechanism is selected.  SEV is the only mechanism available to
2249      * select on x86 at present, so this doesn't arise, but if new
2250      * mechanisms are supported in future (e.g. TDX), they'll need
2251      * their own initialization either here or elsewhere.
2252      */
2253     ret = sev_kvm_init(ms->cgs, &local_err);
2254     if (ret < 0) {
2255         error_report_err(local_err);
2256         return ret;
2257     }
2258 
2259     if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
2260         error_report("kvm: KVM_CAP_IRQ_ROUTING not supported by KVM");
2261         return -ENOTSUP;
2262     }
2263 
2264     has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
2265     has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
2266     has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
2267 
2268     hv_vpindex_settable = kvm_check_extension(s, KVM_CAP_HYPERV_VP_INDEX);
2269 
2270     has_exception_payload = kvm_check_extension(s, KVM_CAP_EXCEPTION_PAYLOAD);
2271     if (has_exception_payload) {
2272         ret = kvm_vm_enable_cap(s, KVM_CAP_EXCEPTION_PAYLOAD, 0, true);
2273         if (ret < 0) {
2274             error_report("kvm: Failed to enable exception payload cap: %s",
2275                          strerror(-ret));
2276             return ret;
2277         }
2278     }
2279 
2280     ret = kvm_get_supported_msrs(s);
2281     if (ret < 0) {
2282         return ret;
2283     }
2284 
2285     kvm_get_supported_feature_msrs(s);
2286 
2287     uname(&utsname);
2288     lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
2289 
2290     /*
2291      * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
2292      * In order to use vm86 mode, an EPT identity map and a TSS  are needed.
2293      * Since these must be part of guest physical memory, we need to allocate
2294      * them, both by setting their start addresses in the kernel and by
2295      * creating a corresponding e820 entry. We need 4 pages before the BIOS.
2296      *
2297      * Older KVM versions may not support setting the identity map base. In
2298      * that case we need to stick with the default, i.e. a 256K maximum BIOS
2299      * size.
2300      */
2301     if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
2302         /* Allows up to 16M BIOSes. */
2303         identity_base = 0xfeffc000;
2304 
2305         ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
2306         if (ret < 0) {
2307             return ret;
2308         }
2309     }
2310 
2311     /* Set TSS base one page after EPT identity map. */
2312     ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
2313     if (ret < 0) {
2314         return ret;
2315     }
2316 
2317     /* Tell fw_cfg to notify the BIOS to reserve the range. */
2318     ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
2319     if (ret < 0) {
2320         fprintf(stderr, "e820_add_entry() table is full\n");
2321         return ret;
2322     }
2323 
2324     shadow_mem = object_property_get_int(OBJECT(s), "kvm-shadow-mem", &error_abort);
2325     if (shadow_mem != -1) {
2326         shadow_mem /= 4096;
2327         ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
2328         if (ret < 0) {
2329             return ret;
2330         }
2331     }
2332 
2333     if (kvm_check_extension(s, KVM_CAP_X86_SMM) &&
2334         object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE) &&
2335         x86_machine_is_smm_enabled(X86_MACHINE(ms))) {
2336         smram_machine_done.notify = register_smram_listener;
2337         qemu_add_machine_init_done_notifier(&smram_machine_done);
2338     }
2339 
2340     if (enable_cpu_pm) {
2341         int disable_exits = kvm_check_extension(s, KVM_CAP_X86_DISABLE_EXITS);
2342         int ret;
2343 
2344 /* Work around for kernel header with a typo. TODO: fix header and drop. */
2345 #if defined(KVM_X86_DISABLE_EXITS_HTL) && !defined(KVM_X86_DISABLE_EXITS_HLT)
2346 #define KVM_X86_DISABLE_EXITS_HLT KVM_X86_DISABLE_EXITS_HTL
2347 #endif
2348         if (disable_exits) {
2349             disable_exits &= (KVM_X86_DISABLE_EXITS_MWAIT |
2350                               KVM_X86_DISABLE_EXITS_HLT |
2351                               KVM_X86_DISABLE_EXITS_PAUSE |
2352                               KVM_X86_DISABLE_EXITS_CSTATE);
2353         }
2354 
2355         ret = kvm_vm_enable_cap(s, KVM_CAP_X86_DISABLE_EXITS, 0,
2356                                 disable_exits);
2357         if (ret < 0) {
2358             error_report("kvm: guest stopping CPU not supported: %s",
2359                          strerror(-ret));
2360         }
2361     }
2362 
2363     if (object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE)) {
2364         X86MachineState *x86ms = X86_MACHINE(ms);
2365 
2366         if (x86ms->bus_lock_ratelimit > 0) {
2367             ret = kvm_check_extension(s, KVM_CAP_X86_BUS_LOCK_EXIT);
2368             if (!(ret & KVM_BUS_LOCK_DETECTION_EXIT)) {
2369                 error_report("kvm: bus lock detection unsupported");
2370                 return -ENOTSUP;
2371             }
2372             ret = kvm_vm_enable_cap(s, KVM_CAP_X86_BUS_LOCK_EXIT, 0,
2373                                     KVM_BUS_LOCK_DETECTION_EXIT);
2374             if (ret < 0) {
2375                 error_report("kvm: Failed to enable bus lock detection cap: %s",
2376                              strerror(-ret));
2377                 return ret;
2378             }
2379             ratelimit_init(&bus_lock_ratelimit_ctrl);
2380             ratelimit_set_speed(&bus_lock_ratelimit_ctrl,
2381                                 x86ms->bus_lock_ratelimit, BUS_LOCK_SLICE_TIME);
2382         }
2383     }
2384 
2385     return 0;
2386 }
2387 
2388 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2389 {
2390     lhs->selector = rhs->selector;
2391     lhs->base = rhs->base;
2392     lhs->limit = rhs->limit;
2393     lhs->type = 3;
2394     lhs->present = 1;
2395     lhs->dpl = 3;
2396     lhs->db = 0;
2397     lhs->s = 1;
2398     lhs->l = 0;
2399     lhs->g = 0;
2400     lhs->avl = 0;
2401     lhs->unusable = 0;
2402 }
2403 
2404 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2405 {
2406     unsigned flags = rhs->flags;
2407     lhs->selector = rhs->selector;
2408     lhs->base = rhs->base;
2409     lhs->limit = rhs->limit;
2410     lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
2411     lhs->present = (flags & DESC_P_MASK) != 0;
2412     lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
2413     lhs->db = (flags >> DESC_B_SHIFT) & 1;
2414     lhs->s = (flags & DESC_S_MASK) != 0;
2415     lhs->l = (flags >> DESC_L_SHIFT) & 1;
2416     lhs->g = (flags & DESC_G_MASK) != 0;
2417     lhs->avl = (flags & DESC_AVL_MASK) != 0;
2418     lhs->unusable = !lhs->present;
2419     lhs->padding = 0;
2420 }
2421 
2422 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
2423 {
2424     lhs->selector = rhs->selector;
2425     lhs->base = rhs->base;
2426     lhs->limit = rhs->limit;
2427     lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
2428                  ((rhs->present && !rhs->unusable) * DESC_P_MASK) |
2429                  (rhs->dpl << DESC_DPL_SHIFT) |
2430                  (rhs->db << DESC_B_SHIFT) |
2431                  (rhs->s * DESC_S_MASK) |
2432                  (rhs->l << DESC_L_SHIFT) |
2433                  (rhs->g * DESC_G_MASK) |
2434                  (rhs->avl * DESC_AVL_MASK);
2435 }
2436 
2437 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
2438 {
2439     if (set) {
2440         *kvm_reg = *qemu_reg;
2441     } else {
2442         *qemu_reg = *kvm_reg;
2443     }
2444 }
2445 
2446 static int kvm_getput_regs(X86CPU *cpu, int set)
2447 {
2448     CPUX86State *env = &cpu->env;
2449     struct kvm_regs regs;
2450     int ret = 0;
2451 
2452     if (!set) {
2453         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
2454         if (ret < 0) {
2455             return ret;
2456         }
2457     }
2458 
2459     kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
2460     kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
2461     kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
2462     kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
2463     kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
2464     kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
2465     kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
2466     kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
2467 #ifdef TARGET_X86_64
2468     kvm_getput_reg(&regs.r8, &env->regs[8], set);
2469     kvm_getput_reg(&regs.r9, &env->regs[9], set);
2470     kvm_getput_reg(&regs.r10, &env->regs[10], set);
2471     kvm_getput_reg(&regs.r11, &env->regs[11], set);
2472     kvm_getput_reg(&regs.r12, &env->regs[12], set);
2473     kvm_getput_reg(&regs.r13, &env->regs[13], set);
2474     kvm_getput_reg(&regs.r14, &env->regs[14], set);
2475     kvm_getput_reg(&regs.r15, &env->regs[15], set);
2476 #endif
2477 
2478     kvm_getput_reg(&regs.rflags, &env->eflags, set);
2479     kvm_getput_reg(&regs.rip, &env->eip, set);
2480 
2481     if (set) {
2482         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
2483     }
2484 
2485     return ret;
2486 }
2487 
2488 static int kvm_put_fpu(X86CPU *cpu)
2489 {
2490     CPUX86State *env = &cpu->env;
2491     struct kvm_fpu fpu;
2492     int i;
2493 
2494     memset(&fpu, 0, sizeof fpu);
2495     fpu.fsw = env->fpus & ~(7 << 11);
2496     fpu.fsw |= (env->fpstt & 7) << 11;
2497     fpu.fcw = env->fpuc;
2498     fpu.last_opcode = env->fpop;
2499     fpu.last_ip = env->fpip;
2500     fpu.last_dp = env->fpdp;
2501     for (i = 0; i < 8; ++i) {
2502         fpu.ftwx |= (!env->fptags[i]) << i;
2503     }
2504     memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
2505     for (i = 0; i < CPU_NB_REGS; i++) {
2506         stq_p(&fpu.xmm[i][0], env->xmm_regs[i].ZMM_Q(0));
2507         stq_p(&fpu.xmm[i][8], env->xmm_regs[i].ZMM_Q(1));
2508     }
2509     fpu.mxcsr = env->mxcsr;
2510 
2511     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
2512 }
2513 
2514 static int kvm_put_xsave(X86CPU *cpu)
2515 {
2516     CPUX86State *env = &cpu->env;
2517     void *xsave = env->xsave_buf;
2518 
2519     if (!has_xsave) {
2520         return kvm_put_fpu(cpu);
2521     }
2522     x86_cpu_xsave_all_areas(cpu, xsave, env->xsave_buf_len);
2523 
2524     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
2525 }
2526 
2527 static int kvm_put_xcrs(X86CPU *cpu)
2528 {
2529     CPUX86State *env = &cpu->env;
2530     struct kvm_xcrs xcrs = {};
2531 
2532     if (!has_xcrs) {
2533         return 0;
2534     }
2535 
2536     xcrs.nr_xcrs = 1;
2537     xcrs.flags = 0;
2538     xcrs.xcrs[0].xcr = 0;
2539     xcrs.xcrs[0].value = env->xcr0;
2540     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
2541 }
2542 
2543 static int kvm_put_sregs(X86CPU *cpu)
2544 {
2545     CPUX86State *env = &cpu->env;
2546     struct kvm_sregs sregs;
2547 
2548     memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
2549     if (env->interrupt_injected >= 0) {
2550         sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
2551                 (uint64_t)1 << (env->interrupt_injected % 64);
2552     }
2553 
2554     if ((env->eflags & VM_MASK)) {
2555         set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
2556         set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
2557         set_v8086_seg(&sregs.es, &env->segs[R_ES]);
2558         set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
2559         set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
2560         set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
2561     } else {
2562         set_seg(&sregs.cs, &env->segs[R_CS]);
2563         set_seg(&sregs.ds, &env->segs[R_DS]);
2564         set_seg(&sregs.es, &env->segs[R_ES]);
2565         set_seg(&sregs.fs, &env->segs[R_FS]);
2566         set_seg(&sregs.gs, &env->segs[R_GS]);
2567         set_seg(&sregs.ss, &env->segs[R_SS]);
2568     }
2569 
2570     set_seg(&sregs.tr, &env->tr);
2571     set_seg(&sregs.ldt, &env->ldt);
2572 
2573     sregs.idt.limit = env->idt.limit;
2574     sregs.idt.base = env->idt.base;
2575     memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
2576     sregs.gdt.limit = env->gdt.limit;
2577     sregs.gdt.base = env->gdt.base;
2578     memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
2579 
2580     sregs.cr0 = env->cr[0];
2581     sregs.cr2 = env->cr[2];
2582     sregs.cr3 = env->cr[3];
2583     sregs.cr4 = env->cr[4];
2584 
2585     sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
2586     sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
2587 
2588     sregs.efer = env->efer;
2589 
2590     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
2591 }
2592 
2593 static void kvm_msr_buf_reset(X86CPU *cpu)
2594 {
2595     memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
2596 }
2597 
2598 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
2599 {
2600     struct kvm_msrs *msrs = cpu->kvm_msr_buf;
2601     void *limit = ((void *)msrs) + MSR_BUF_SIZE;
2602     struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
2603 
2604     assert((void *)(entry + 1) <= limit);
2605 
2606     entry->index = index;
2607     entry->reserved = 0;
2608     entry->data = value;
2609     msrs->nmsrs++;
2610 }
2611 
2612 static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
2613 {
2614     kvm_msr_buf_reset(cpu);
2615     kvm_msr_entry_add(cpu, index, value);
2616 
2617     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
2618 }
2619 
2620 void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
2621 {
2622     int ret;
2623 
2624     ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
2625     assert(ret == 1);
2626 }
2627 
2628 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
2629 {
2630     CPUX86State *env = &cpu->env;
2631     int ret;
2632 
2633     if (!has_msr_tsc_deadline) {
2634         return 0;
2635     }
2636 
2637     ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
2638     if (ret < 0) {
2639         return ret;
2640     }
2641 
2642     assert(ret == 1);
2643     return 0;
2644 }
2645 
2646 /*
2647  * Provide a separate write service for the feature control MSR in order to
2648  * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
2649  * before writing any other state because forcibly leaving nested mode
2650  * invalidates the VCPU state.
2651  */
2652 static int kvm_put_msr_feature_control(X86CPU *cpu)
2653 {
2654     int ret;
2655 
2656     if (!has_msr_feature_control) {
2657         return 0;
2658     }
2659 
2660     ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
2661                           cpu->env.msr_ia32_feature_control);
2662     if (ret < 0) {
2663         return ret;
2664     }
2665 
2666     assert(ret == 1);
2667     return 0;
2668 }
2669 
2670 static uint64_t make_vmx_msr_value(uint32_t index, uint32_t features)
2671 {
2672     uint32_t default1, can_be_one, can_be_zero;
2673     uint32_t must_be_one;
2674 
2675     switch (index) {
2676     case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2677         default1 = 0x00000016;
2678         break;
2679     case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2680         default1 = 0x0401e172;
2681         break;
2682     case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
2683         default1 = 0x000011ff;
2684         break;
2685     case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2686         default1 = 0x00036dff;
2687         break;
2688     case MSR_IA32_VMX_PROCBASED_CTLS2:
2689         default1 = 0;
2690         break;
2691     default:
2692         abort();
2693     }
2694 
2695     /* If a feature bit is set, the control can be either set or clear.
2696      * Otherwise the value is limited to either 0 or 1 by default1.
2697      */
2698     can_be_one = features | default1;
2699     can_be_zero = features | ~default1;
2700     must_be_one = ~can_be_zero;
2701 
2702     /*
2703      * Bit 0:31 -> 0 if the control bit can be zero (i.e. 1 if it must be one).
2704      * Bit 32:63 -> 1 if the control bit can be one.
2705      */
2706     return must_be_one | (((uint64_t)can_be_one) << 32);
2707 }
2708 
2709 static void kvm_msr_entry_add_vmx(X86CPU *cpu, FeatureWordArray f)
2710 {
2711     uint64_t kvm_vmx_basic =
2712         kvm_arch_get_supported_msr_feature(kvm_state,
2713                                            MSR_IA32_VMX_BASIC);
2714 
2715     if (!kvm_vmx_basic) {
2716         /* If the kernel doesn't support VMX feature (kvm_intel.nested=0),
2717          * then kvm_vmx_basic will be 0 and KVM_SET_MSR will fail.
2718          */
2719         return;
2720     }
2721 
2722     uint64_t kvm_vmx_misc =
2723         kvm_arch_get_supported_msr_feature(kvm_state,
2724                                            MSR_IA32_VMX_MISC);
2725     uint64_t kvm_vmx_ept_vpid =
2726         kvm_arch_get_supported_msr_feature(kvm_state,
2727                                            MSR_IA32_VMX_EPT_VPID_CAP);
2728 
2729     /*
2730      * If the guest is 64-bit, a value of 1 is allowed for the host address
2731      * space size vmexit control.
2732      */
2733     uint64_t fixed_vmx_exit = f[FEAT_8000_0001_EDX] & CPUID_EXT2_LM
2734         ? (uint64_t)VMX_VM_EXIT_HOST_ADDR_SPACE_SIZE << 32 : 0;
2735 
2736     /*
2737      * Bits 0-30, 32-44 and 50-53 come from the host.  KVM should
2738      * not change them for backwards compatibility.
2739      */
2740     uint64_t fixed_vmx_basic = kvm_vmx_basic &
2741         (MSR_VMX_BASIC_VMCS_REVISION_MASK |
2742          MSR_VMX_BASIC_VMXON_REGION_SIZE_MASK |
2743          MSR_VMX_BASIC_VMCS_MEM_TYPE_MASK);
2744 
2745     /*
2746      * Same for bits 0-4 and 25-27.  Bits 16-24 (CR3 target count) can
2747      * change in the future but are always zero for now, clear them to be
2748      * future proof.  Bits 32-63 in theory could change, though KVM does
2749      * not support dual-monitor treatment and probably never will; mask
2750      * them out as well.
2751      */
2752     uint64_t fixed_vmx_misc = kvm_vmx_misc &
2753         (MSR_VMX_MISC_PREEMPTION_TIMER_SHIFT_MASK |
2754          MSR_VMX_MISC_MAX_MSR_LIST_SIZE_MASK);
2755 
2756     /*
2757      * EPT memory types should not change either, so we do not bother
2758      * adding features for them.
2759      */
2760     uint64_t fixed_vmx_ept_mask =
2761             (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_ENABLE_EPT ?
2762              MSR_VMX_EPT_UC | MSR_VMX_EPT_WB : 0);
2763     uint64_t fixed_vmx_ept_vpid = kvm_vmx_ept_vpid & fixed_vmx_ept_mask;
2764 
2765     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
2766                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
2767                                          f[FEAT_VMX_PROCBASED_CTLS]));
2768     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PINBASED_CTLS,
2769                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_PINBASED_CTLS,
2770                                          f[FEAT_VMX_PINBASED_CTLS]));
2771     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_EXIT_CTLS,
2772                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_EXIT_CTLS,
2773                                          f[FEAT_VMX_EXIT_CTLS]) | fixed_vmx_exit);
2774     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_ENTRY_CTLS,
2775                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_ENTRY_CTLS,
2776                                          f[FEAT_VMX_ENTRY_CTLS]));
2777     kvm_msr_entry_add(cpu, MSR_IA32_VMX_PROCBASED_CTLS2,
2778                       make_vmx_msr_value(MSR_IA32_VMX_PROCBASED_CTLS2,
2779                                          f[FEAT_VMX_SECONDARY_CTLS]));
2780     kvm_msr_entry_add(cpu, MSR_IA32_VMX_EPT_VPID_CAP,
2781                       f[FEAT_VMX_EPT_VPID_CAPS] | fixed_vmx_ept_vpid);
2782     kvm_msr_entry_add(cpu, MSR_IA32_VMX_BASIC,
2783                       f[FEAT_VMX_BASIC] | fixed_vmx_basic);
2784     kvm_msr_entry_add(cpu, MSR_IA32_VMX_MISC,
2785                       f[FEAT_VMX_MISC] | fixed_vmx_misc);
2786     if (has_msr_vmx_vmfunc) {
2787         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMFUNC, f[FEAT_VMX_VMFUNC]);
2788     }
2789 
2790     /*
2791      * Just to be safe, write these with constant values.  The CRn_FIXED1
2792      * MSRs are generated by KVM based on the vCPU's CPUID.
2793      */
2794     kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR0_FIXED0,
2795                       CR0_PE_MASK | CR0_PG_MASK | CR0_NE_MASK);
2796     kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR4_FIXED0,
2797                       CR4_VMXE_MASK);
2798 
2799     if (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_TSC_SCALING) {
2800         /* TSC multiplier (0x2032).  */
2801         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x32);
2802     } else {
2803         /* Preemption timer (0x482E).  */
2804         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x2E);
2805     }
2806 }
2807 
2808 static void kvm_msr_entry_add_perf(X86CPU *cpu, FeatureWordArray f)
2809 {
2810     uint64_t kvm_perf_cap =
2811         kvm_arch_get_supported_msr_feature(kvm_state,
2812                                            MSR_IA32_PERF_CAPABILITIES);
2813 
2814     if (kvm_perf_cap) {
2815         kvm_msr_entry_add(cpu, MSR_IA32_PERF_CAPABILITIES,
2816                         kvm_perf_cap & f[FEAT_PERF_CAPABILITIES]);
2817     }
2818 }
2819 
2820 static int kvm_buf_set_msrs(X86CPU *cpu)
2821 {
2822     int ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
2823     if (ret < 0) {
2824         return ret;
2825     }
2826 
2827     if (ret < cpu->kvm_msr_buf->nmsrs) {
2828         struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
2829         error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,
2830                      (uint32_t)e->index, (uint64_t)e->data);
2831     }
2832 
2833     assert(ret == cpu->kvm_msr_buf->nmsrs);
2834     return 0;
2835 }
2836 
2837 static void kvm_init_msrs(X86CPU *cpu)
2838 {
2839     CPUX86State *env = &cpu->env;
2840 
2841     kvm_msr_buf_reset(cpu);
2842     if (has_msr_arch_capabs) {
2843         kvm_msr_entry_add(cpu, MSR_IA32_ARCH_CAPABILITIES,
2844                           env->features[FEAT_ARCH_CAPABILITIES]);
2845     }
2846 
2847     if (has_msr_core_capabs) {
2848         kvm_msr_entry_add(cpu, MSR_IA32_CORE_CAPABILITY,
2849                           env->features[FEAT_CORE_CAPABILITY]);
2850     }
2851 
2852     if (has_msr_perf_capabs && cpu->enable_pmu) {
2853         kvm_msr_entry_add_perf(cpu, env->features);
2854     }
2855 
2856     if (has_msr_ucode_rev) {
2857         kvm_msr_entry_add(cpu, MSR_IA32_UCODE_REV, cpu->ucode_rev);
2858     }
2859 
2860     /*
2861      * Older kernels do not include VMX MSRs in KVM_GET_MSR_INDEX_LIST, but
2862      * all kernels with MSR features should have them.
2863      */
2864     if (kvm_feature_msrs && cpu_has_vmx(env)) {
2865         kvm_msr_entry_add_vmx(cpu, env->features);
2866     }
2867 
2868     assert(kvm_buf_set_msrs(cpu) == 0);
2869 }
2870 
2871 static int kvm_put_msrs(X86CPU *cpu, int level)
2872 {
2873     CPUX86State *env = &cpu->env;
2874     int i;
2875 
2876     kvm_msr_buf_reset(cpu);
2877 
2878     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
2879     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
2880     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
2881     kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
2882     if (has_msr_star) {
2883         kvm_msr_entry_add(cpu, MSR_STAR, env->star);
2884     }
2885     if (has_msr_hsave_pa) {
2886         kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
2887     }
2888     if (has_msr_tsc_aux) {
2889         kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
2890     }
2891     if (has_msr_tsc_adjust) {
2892         kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
2893     }
2894     if (has_msr_misc_enable) {
2895         kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
2896                           env->msr_ia32_misc_enable);
2897     }
2898     if (has_msr_smbase) {
2899         kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
2900     }
2901     if (has_msr_smi_count) {
2902         kvm_msr_entry_add(cpu, MSR_SMI_COUNT, env->msr_smi_count);
2903     }
2904     if (has_msr_pkrs) {
2905         kvm_msr_entry_add(cpu, MSR_IA32_PKRS, env->pkrs);
2906     }
2907     if (has_msr_bndcfgs) {
2908         kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
2909     }
2910     if (has_msr_xss) {
2911         kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
2912     }
2913     if (has_msr_umwait) {
2914         kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, env->umwait);
2915     }
2916     if (has_msr_spec_ctrl) {
2917         kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, env->spec_ctrl);
2918     }
2919     if (has_msr_tsx_ctrl) {
2920         kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, env->tsx_ctrl);
2921     }
2922     if (has_msr_virt_ssbd) {
2923         kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, env->virt_ssbd);
2924     }
2925 
2926 #ifdef TARGET_X86_64
2927     if (lm_capable_kernel) {
2928         kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
2929         kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
2930         kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
2931         kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
2932     }
2933 #endif
2934 
2935     /*
2936      * The following MSRs have side effects on the guest or are too heavy
2937      * for normal writeback. Limit them to reset or full state updates.
2938      */
2939     if (level >= KVM_PUT_RESET_STATE) {
2940         kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
2941         kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
2942         kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
2943         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
2944             kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, env->async_pf_int_msr);
2945         }
2946         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
2947             kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
2948         }
2949         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
2950             kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
2951         }
2952         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
2953             kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
2954         }
2955 
2956         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
2957             kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, env->poll_control_msr);
2958         }
2959 
2960         if (has_architectural_pmu_version > 0) {
2961             if (has_architectural_pmu_version > 1) {
2962                 /* Stop the counter.  */
2963                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
2964                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
2965             }
2966 
2967             /* Set the counter values.  */
2968             for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
2969                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
2970                                   env->msr_fixed_counters[i]);
2971             }
2972             for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
2973                 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
2974                                   env->msr_gp_counters[i]);
2975                 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
2976                                   env->msr_gp_evtsel[i]);
2977             }
2978             if (has_architectural_pmu_version > 1) {
2979                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
2980                                   env->msr_global_status);
2981                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
2982                                   env->msr_global_ovf_ctrl);
2983 
2984                 /* Now start the PMU.  */
2985                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
2986                                   env->msr_fixed_ctr_ctrl);
2987                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
2988                                   env->msr_global_ctrl);
2989             }
2990         }
2991         /*
2992          * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,
2993          * only sync them to KVM on the first cpu
2994          */
2995         if (current_cpu == first_cpu) {
2996             if (has_msr_hv_hypercall) {
2997                 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
2998                                   env->msr_hv_guest_os_id);
2999                 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
3000                                   env->msr_hv_hypercall);
3001             }
3002             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
3003                 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,
3004                                   env->msr_hv_tsc);
3005             }
3006             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
3007                 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL,
3008                                   env->msr_hv_reenlightenment_control);
3009                 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL,
3010                                   env->msr_hv_tsc_emulation_control);
3011                 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS,
3012                                   env->msr_hv_tsc_emulation_status);
3013             }
3014         }
3015         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3016             kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
3017                               env->msr_hv_vapic);
3018         }
3019         if (has_msr_hv_crash) {
3020             int j;
3021 
3022             for (j = 0; j < HV_CRASH_PARAMS; j++)
3023                 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
3024                                   env->msr_hv_crash_params[j]);
3025 
3026             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);
3027         }
3028         if (has_msr_hv_runtime) {
3029             kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
3030         }
3031         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)
3032             && hv_vpindex_settable) {
3033             kvm_msr_entry_add(cpu, HV_X64_MSR_VP_INDEX,
3034                               hyperv_vp_index(CPU(cpu)));
3035         }
3036         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3037             int j;
3038 
3039             kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);
3040 
3041             kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
3042                               env->msr_hv_synic_control);
3043             kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
3044                               env->msr_hv_synic_evt_page);
3045             kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
3046                               env->msr_hv_synic_msg_page);
3047 
3048             for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
3049                 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
3050                                   env->msr_hv_synic_sint[j]);
3051             }
3052         }
3053         if (has_msr_hv_stimer) {
3054             int j;
3055 
3056             for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
3057                 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
3058                                 env->msr_hv_stimer_config[j]);
3059             }
3060 
3061             for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
3062                 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
3063                                 env->msr_hv_stimer_count[j]);
3064             }
3065         }
3066         if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3067             uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
3068 
3069             kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
3070             kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
3071             kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
3072             kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
3073             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
3074             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
3075             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
3076             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
3077             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
3078             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
3079             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
3080             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
3081             for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
3082                 /* The CPU GPs if we write to a bit above the physical limit of
3083                  * the host CPU (and KVM emulates that)
3084                  */
3085                 uint64_t mask = env->mtrr_var[i].mask;
3086                 mask &= phys_mask;
3087 
3088                 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
3089                                   env->mtrr_var[i].base);
3090                 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
3091             }
3092         }
3093         if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
3094             int addr_num = kvm_arch_get_supported_cpuid(kvm_state,
3095                                                     0x14, 1, R_EAX) & 0x7;
3096 
3097             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL,
3098                             env->msr_rtit_ctrl);
3099             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS,
3100                             env->msr_rtit_status);
3101             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE,
3102                             env->msr_rtit_output_base);
3103             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK,
3104                             env->msr_rtit_output_mask);
3105             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH,
3106                             env->msr_rtit_cr3_match);
3107             for (i = 0; i < addr_num; i++) {
3108                 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i,
3109                             env->msr_rtit_addrs[i]);
3110             }
3111         }
3112 
3113         /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
3114          *       kvm_put_msr_feature_control. */
3115     }
3116 
3117     if (env->mcg_cap) {
3118         int i;
3119 
3120         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
3121         kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
3122         if (has_msr_mcg_ext_ctl) {
3123             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
3124         }
3125         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3126             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
3127         }
3128     }
3129 
3130     return kvm_buf_set_msrs(cpu);
3131 }
3132 
3133 
3134 static int kvm_get_fpu(X86CPU *cpu)
3135 {
3136     CPUX86State *env = &cpu->env;
3137     struct kvm_fpu fpu;
3138     int i, ret;
3139 
3140     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
3141     if (ret < 0) {
3142         return ret;
3143     }
3144 
3145     env->fpstt = (fpu.fsw >> 11) & 7;
3146     env->fpus = fpu.fsw;
3147     env->fpuc = fpu.fcw;
3148     env->fpop = fpu.last_opcode;
3149     env->fpip = fpu.last_ip;
3150     env->fpdp = fpu.last_dp;
3151     for (i = 0; i < 8; ++i) {
3152         env->fptags[i] = !((fpu.ftwx >> i) & 1);
3153     }
3154     memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
3155     for (i = 0; i < CPU_NB_REGS; i++) {
3156         env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
3157         env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
3158     }
3159     env->mxcsr = fpu.mxcsr;
3160 
3161     return 0;
3162 }
3163 
3164 static int kvm_get_xsave(X86CPU *cpu)
3165 {
3166     CPUX86State *env = &cpu->env;
3167     void *xsave = env->xsave_buf;
3168     int ret;
3169 
3170     if (!has_xsave) {
3171         return kvm_get_fpu(cpu);
3172     }
3173 
3174     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
3175     if (ret < 0) {
3176         return ret;
3177     }
3178     x86_cpu_xrstor_all_areas(cpu, xsave, env->xsave_buf_len);
3179 
3180     return 0;
3181 }
3182 
3183 static int kvm_get_xcrs(X86CPU *cpu)
3184 {
3185     CPUX86State *env = &cpu->env;
3186     int i, ret;
3187     struct kvm_xcrs xcrs;
3188 
3189     if (!has_xcrs) {
3190         return 0;
3191     }
3192 
3193     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
3194     if (ret < 0) {
3195         return ret;
3196     }
3197 
3198     for (i = 0; i < xcrs.nr_xcrs; i++) {
3199         /* Only support xcr0 now */
3200         if (xcrs.xcrs[i].xcr == 0) {
3201             env->xcr0 = xcrs.xcrs[i].value;
3202             break;
3203         }
3204     }
3205     return 0;
3206 }
3207 
3208 static int kvm_get_sregs(X86CPU *cpu)
3209 {
3210     CPUX86State *env = &cpu->env;
3211     struct kvm_sregs sregs;
3212     int bit, i, ret;
3213 
3214     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
3215     if (ret < 0) {
3216         return ret;
3217     }
3218 
3219     /* There can only be one pending IRQ set in the bitmap at a time, so try
3220        to find it and save its number instead (-1 for none). */
3221     env->interrupt_injected = -1;
3222     for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
3223         if (sregs.interrupt_bitmap[i]) {
3224             bit = ctz64(sregs.interrupt_bitmap[i]);
3225             env->interrupt_injected = i * 64 + bit;
3226             break;
3227         }
3228     }
3229 
3230     get_seg(&env->segs[R_CS], &sregs.cs);
3231     get_seg(&env->segs[R_DS], &sregs.ds);
3232     get_seg(&env->segs[R_ES], &sregs.es);
3233     get_seg(&env->segs[R_FS], &sregs.fs);
3234     get_seg(&env->segs[R_GS], &sregs.gs);
3235     get_seg(&env->segs[R_SS], &sregs.ss);
3236 
3237     get_seg(&env->tr, &sregs.tr);
3238     get_seg(&env->ldt, &sregs.ldt);
3239 
3240     env->idt.limit = sregs.idt.limit;
3241     env->idt.base = sregs.idt.base;
3242     env->gdt.limit = sregs.gdt.limit;
3243     env->gdt.base = sregs.gdt.base;
3244 
3245     env->cr[0] = sregs.cr0;
3246     env->cr[2] = sregs.cr2;
3247     env->cr[3] = sregs.cr3;
3248     env->cr[4] = sregs.cr4;
3249 
3250     env->efer = sregs.efer;
3251 
3252     /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
3253     x86_update_hflags(env);
3254 
3255     return 0;
3256 }
3257 
3258 static int kvm_get_msrs(X86CPU *cpu)
3259 {
3260     CPUX86State *env = &cpu->env;
3261     struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
3262     int ret, i;
3263     uint64_t mtrr_top_bits;
3264 
3265     kvm_msr_buf_reset(cpu);
3266 
3267     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
3268     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
3269     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
3270     kvm_msr_entry_add(cpu, MSR_PAT, 0);
3271     if (has_msr_star) {
3272         kvm_msr_entry_add(cpu, MSR_STAR, 0);
3273     }
3274     if (has_msr_hsave_pa) {
3275         kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
3276     }
3277     if (has_msr_tsc_aux) {
3278         kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
3279     }
3280     if (has_msr_tsc_adjust) {
3281         kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
3282     }
3283     if (has_msr_tsc_deadline) {
3284         kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
3285     }
3286     if (has_msr_misc_enable) {
3287         kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
3288     }
3289     if (has_msr_smbase) {
3290         kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
3291     }
3292     if (has_msr_smi_count) {
3293         kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
3294     }
3295     if (has_msr_feature_control) {
3296         kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
3297     }
3298     if (has_msr_pkrs) {
3299         kvm_msr_entry_add(cpu, MSR_IA32_PKRS, 0);
3300     }
3301     if (has_msr_bndcfgs) {
3302         kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
3303     }
3304     if (has_msr_xss) {
3305         kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
3306     }
3307     if (has_msr_umwait) {
3308         kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, 0);
3309     }
3310     if (has_msr_spec_ctrl) {
3311         kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
3312     }
3313     if (has_msr_tsx_ctrl) {
3314         kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, 0);
3315     }
3316     if (has_msr_virt_ssbd) {
3317         kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, 0);
3318     }
3319     if (!env->tsc_valid) {
3320         kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
3321         env->tsc_valid = !runstate_is_running();
3322     }
3323 
3324 #ifdef TARGET_X86_64
3325     if (lm_capable_kernel) {
3326         kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
3327         kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
3328         kvm_msr_entry_add(cpu, MSR_FMASK, 0);
3329         kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
3330     }
3331 #endif
3332     kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
3333     kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
3334     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
3335         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, 0);
3336     }
3337     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
3338         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
3339     }
3340     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
3341         kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
3342     }
3343     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
3344         kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
3345     }
3346     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
3347         kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, 1);
3348     }
3349     if (has_architectural_pmu_version > 0) {
3350         if (has_architectural_pmu_version > 1) {
3351             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
3352             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
3353             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
3354             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
3355         }
3356         for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
3357             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
3358         }
3359         for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
3360             kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
3361             kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
3362         }
3363     }
3364 
3365     if (env->mcg_cap) {
3366         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
3367         kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
3368         if (has_msr_mcg_ext_ctl) {
3369             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
3370         }
3371         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3372             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
3373         }
3374     }
3375 
3376     if (has_msr_hv_hypercall) {
3377         kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
3378         kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
3379     }
3380     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3381         kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
3382     }
3383     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
3384         kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
3385     }
3386     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
3387         kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL, 0);
3388         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL, 0);
3389         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS, 0);
3390     }
3391     if (has_msr_hv_crash) {
3392         int j;
3393 
3394         for (j = 0; j < HV_CRASH_PARAMS; j++) {
3395             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
3396         }
3397     }
3398     if (has_msr_hv_runtime) {
3399         kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
3400     }
3401     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3402         uint32_t msr;
3403 
3404         kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
3405         kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
3406         kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
3407         for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
3408             kvm_msr_entry_add(cpu, msr, 0);
3409         }
3410     }
3411     if (has_msr_hv_stimer) {
3412         uint32_t msr;
3413 
3414         for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
3415              msr++) {
3416             kvm_msr_entry_add(cpu, msr, 0);
3417         }
3418     }
3419     if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3420         kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
3421         kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
3422         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
3423         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
3424         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
3425         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
3426         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
3427         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
3428         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
3429         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
3430         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
3431         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
3432         for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
3433             kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
3434             kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
3435         }
3436     }
3437 
3438     if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
3439         int addr_num =
3440             kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
3441 
3442         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
3443         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
3444         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
3445         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
3446         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
3447         for (i = 0; i < addr_num; i++) {
3448             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
3449         }
3450     }
3451 
3452     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
3453     if (ret < 0) {
3454         return ret;
3455     }
3456 
3457     if (ret < cpu->kvm_msr_buf->nmsrs) {
3458         struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
3459         error_report("error: failed to get MSR 0x%" PRIx32,
3460                      (uint32_t)e->index);
3461     }
3462 
3463     assert(ret == cpu->kvm_msr_buf->nmsrs);
3464     /*
3465      * MTRR masks: Each mask consists of 5 parts
3466      * a  10..0: must be zero
3467      * b  11   : valid bit
3468      * c n-1.12: actual mask bits
3469      * d  51..n: reserved must be zero
3470      * e  63.52: reserved must be zero
3471      *
3472      * 'n' is the number of physical bits supported by the CPU and is
3473      * apparently always <= 52.   We know our 'n' but don't know what
3474      * the destinations 'n' is; it might be smaller, in which case
3475      * it masks (c) on loading. It might be larger, in which case
3476      * we fill 'd' so that d..c is consistent irrespetive of the 'n'
3477      * we're migrating to.
3478      */
3479 
3480     if (cpu->fill_mtrr_mask) {
3481         QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
3482         assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
3483         mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
3484     } else {
3485         mtrr_top_bits = 0;
3486     }
3487 
3488     for (i = 0; i < ret; i++) {
3489         uint32_t index = msrs[i].index;
3490         switch (index) {
3491         case MSR_IA32_SYSENTER_CS:
3492             env->sysenter_cs = msrs[i].data;
3493             break;
3494         case MSR_IA32_SYSENTER_ESP:
3495             env->sysenter_esp = msrs[i].data;
3496             break;
3497         case MSR_IA32_SYSENTER_EIP:
3498             env->sysenter_eip = msrs[i].data;
3499             break;
3500         case MSR_PAT:
3501             env->pat = msrs[i].data;
3502             break;
3503         case MSR_STAR:
3504             env->star = msrs[i].data;
3505             break;
3506 #ifdef TARGET_X86_64
3507         case MSR_CSTAR:
3508             env->cstar = msrs[i].data;
3509             break;
3510         case MSR_KERNELGSBASE:
3511             env->kernelgsbase = msrs[i].data;
3512             break;
3513         case MSR_FMASK:
3514             env->fmask = msrs[i].data;
3515             break;
3516         case MSR_LSTAR:
3517             env->lstar = msrs[i].data;
3518             break;
3519 #endif
3520         case MSR_IA32_TSC:
3521             env->tsc = msrs[i].data;
3522             break;
3523         case MSR_TSC_AUX:
3524             env->tsc_aux = msrs[i].data;
3525             break;
3526         case MSR_TSC_ADJUST:
3527             env->tsc_adjust = msrs[i].data;
3528             break;
3529         case MSR_IA32_TSCDEADLINE:
3530             env->tsc_deadline = msrs[i].data;
3531             break;
3532         case MSR_VM_HSAVE_PA:
3533             env->vm_hsave = msrs[i].data;
3534             break;
3535         case MSR_KVM_SYSTEM_TIME:
3536             env->system_time_msr = msrs[i].data;
3537             break;
3538         case MSR_KVM_WALL_CLOCK:
3539             env->wall_clock_msr = msrs[i].data;
3540             break;
3541         case MSR_MCG_STATUS:
3542             env->mcg_status = msrs[i].data;
3543             break;
3544         case MSR_MCG_CTL:
3545             env->mcg_ctl = msrs[i].data;
3546             break;
3547         case MSR_MCG_EXT_CTL:
3548             env->mcg_ext_ctl = msrs[i].data;
3549             break;
3550         case MSR_IA32_MISC_ENABLE:
3551             env->msr_ia32_misc_enable = msrs[i].data;
3552             break;
3553         case MSR_IA32_SMBASE:
3554             env->smbase = msrs[i].data;
3555             break;
3556         case MSR_SMI_COUNT:
3557             env->msr_smi_count = msrs[i].data;
3558             break;
3559         case MSR_IA32_FEATURE_CONTROL:
3560             env->msr_ia32_feature_control = msrs[i].data;
3561             break;
3562         case MSR_IA32_BNDCFGS:
3563             env->msr_bndcfgs = msrs[i].data;
3564             break;
3565         case MSR_IA32_XSS:
3566             env->xss = msrs[i].data;
3567             break;
3568         case MSR_IA32_UMWAIT_CONTROL:
3569             env->umwait = msrs[i].data;
3570             break;
3571         case MSR_IA32_PKRS:
3572             env->pkrs = msrs[i].data;
3573             break;
3574         default:
3575             if (msrs[i].index >= MSR_MC0_CTL &&
3576                 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
3577                 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
3578             }
3579             break;
3580         case MSR_KVM_ASYNC_PF_EN:
3581             env->async_pf_en_msr = msrs[i].data;
3582             break;
3583         case MSR_KVM_ASYNC_PF_INT:
3584             env->async_pf_int_msr = msrs[i].data;
3585             break;
3586         case MSR_KVM_PV_EOI_EN:
3587             env->pv_eoi_en_msr = msrs[i].data;
3588             break;
3589         case MSR_KVM_STEAL_TIME:
3590             env->steal_time_msr = msrs[i].data;
3591             break;
3592         case MSR_KVM_POLL_CONTROL: {
3593             env->poll_control_msr = msrs[i].data;
3594             break;
3595         }
3596         case MSR_CORE_PERF_FIXED_CTR_CTRL:
3597             env->msr_fixed_ctr_ctrl = msrs[i].data;
3598             break;
3599         case MSR_CORE_PERF_GLOBAL_CTRL:
3600             env->msr_global_ctrl = msrs[i].data;
3601             break;
3602         case MSR_CORE_PERF_GLOBAL_STATUS:
3603             env->msr_global_status = msrs[i].data;
3604             break;
3605         case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
3606             env->msr_global_ovf_ctrl = msrs[i].data;
3607             break;
3608         case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
3609             env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
3610             break;
3611         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
3612             env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
3613             break;
3614         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
3615             env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
3616             break;
3617         case HV_X64_MSR_HYPERCALL:
3618             env->msr_hv_hypercall = msrs[i].data;
3619             break;
3620         case HV_X64_MSR_GUEST_OS_ID:
3621             env->msr_hv_guest_os_id = msrs[i].data;
3622             break;
3623         case HV_X64_MSR_APIC_ASSIST_PAGE:
3624             env->msr_hv_vapic = msrs[i].data;
3625             break;
3626         case HV_X64_MSR_REFERENCE_TSC:
3627             env->msr_hv_tsc = msrs[i].data;
3628             break;
3629         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3630             env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
3631             break;
3632         case HV_X64_MSR_VP_RUNTIME:
3633             env->msr_hv_runtime = msrs[i].data;
3634             break;
3635         case HV_X64_MSR_SCONTROL:
3636             env->msr_hv_synic_control = msrs[i].data;
3637             break;
3638         case HV_X64_MSR_SIEFP:
3639             env->msr_hv_synic_evt_page = msrs[i].data;
3640             break;
3641         case HV_X64_MSR_SIMP:
3642             env->msr_hv_synic_msg_page = msrs[i].data;
3643             break;
3644         case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
3645             env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
3646             break;
3647         case HV_X64_MSR_STIMER0_CONFIG:
3648         case HV_X64_MSR_STIMER1_CONFIG:
3649         case HV_X64_MSR_STIMER2_CONFIG:
3650         case HV_X64_MSR_STIMER3_CONFIG:
3651             env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
3652                                 msrs[i].data;
3653             break;
3654         case HV_X64_MSR_STIMER0_COUNT:
3655         case HV_X64_MSR_STIMER1_COUNT:
3656         case HV_X64_MSR_STIMER2_COUNT:
3657         case HV_X64_MSR_STIMER3_COUNT:
3658             env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
3659                                 msrs[i].data;
3660             break;
3661         case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3662             env->msr_hv_reenlightenment_control = msrs[i].data;
3663             break;
3664         case HV_X64_MSR_TSC_EMULATION_CONTROL:
3665             env->msr_hv_tsc_emulation_control = msrs[i].data;
3666             break;
3667         case HV_X64_MSR_TSC_EMULATION_STATUS:
3668             env->msr_hv_tsc_emulation_status = msrs[i].data;
3669             break;
3670         case MSR_MTRRdefType:
3671             env->mtrr_deftype = msrs[i].data;
3672             break;
3673         case MSR_MTRRfix64K_00000:
3674             env->mtrr_fixed[0] = msrs[i].data;
3675             break;
3676         case MSR_MTRRfix16K_80000:
3677             env->mtrr_fixed[1] = msrs[i].data;
3678             break;
3679         case MSR_MTRRfix16K_A0000:
3680             env->mtrr_fixed[2] = msrs[i].data;
3681             break;
3682         case MSR_MTRRfix4K_C0000:
3683             env->mtrr_fixed[3] = msrs[i].data;
3684             break;
3685         case MSR_MTRRfix4K_C8000:
3686             env->mtrr_fixed[4] = msrs[i].data;
3687             break;
3688         case MSR_MTRRfix4K_D0000:
3689             env->mtrr_fixed[5] = msrs[i].data;
3690             break;
3691         case MSR_MTRRfix4K_D8000:
3692             env->mtrr_fixed[6] = msrs[i].data;
3693             break;
3694         case MSR_MTRRfix4K_E0000:
3695             env->mtrr_fixed[7] = msrs[i].data;
3696             break;
3697         case MSR_MTRRfix4K_E8000:
3698             env->mtrr_fixed[8] = msrs[i].data;
3699             break;
3700         case MSR_MTRRfix4K_F0000:
3701             env->mtrr_fixed[9] = msrs[i].data;
3702             break;
3703         case MSR_MTRRfix4K_F8000:
3704             env->mtrr_fixed[10] = msrs[i].data;
3705             break;
3706         case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
3707             if (index & 1) {
3708                 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
3709                                                                mtrr_top_bits;
3710             } else {
3711                 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
3712             }
3713             break;
3714         case MSR_IA32_SPEC_CTRL:
3715             env->spec_ctrl = msrs[i].data;
3716             break;
3717         case MSR_IA32_TSX_CTRL:
3718             env->tsx_ctrl = msrs[i].data;
3719             break;
3720         case MSR_VIRT_SSBD:
3721             env->virt_ssbd = msrs[i].data;
3722             break;
3723         case MSR_IA32_RTIT_CTL:
3724             env->msr_rtit_ctrl = msrs[i].data;
3725             break;
3726         case MSR_IA32_RTIT_STATUS:
3727             env->msr_rtit_status = msrs[i].data;
3728             break;
3729         case MSR_IA32_RTIT_OUTPUT_BASE:
3730             env->msr_rtit_output_base = msrs[i].data;
3731             break;
3732         case MSR_IA32_RTIT_OUTPUT_MASK:
3733             env->msr_rtit_output_mask = msrs[i].data;
3734             break;
3735         case MSR_IA32_RTIT_CR3_MATCH:
3736             env->msr_rtit_cr3_match = msrs[i].data;
3737             break;
3738         case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
3739             env->msr_rtit_addrs[index - MSR_IA32_RTIT_ADDR0_A] = msrs[i].data;
3740             break;
3741         }
3742     }
3743 
3744     return 0;
3745 }
3746 
3747 static int kvm_put_mp_state(X86CPU *cpu)
3748 {
3749     struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
3750 
3751     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
3752 }
3753 
3754 static int kvm_get_mp_state(X86CPU *cpu)
3755 {
3756     CPUState *cs = CPU(cpu);
3757     CPUX86State *env = &cpu->env;
3758     struct kvm_mp_state mp_state;
3759     int ret;
3760 
3761     ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
3762     if (ret < 0) {
3763         return ret;
3764     }
3765     env->mp_state = mp_state.mp_state;
3766     if (kvm_irqchip_in_kernel()) {
3767         cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
3768     }
3769     return 0;
3770 }
3771 
3772 static int kvm_get_apic(X86CPU *cpu)
3773 {
3774     DeviceState *apic = cpu->apic_state;
3775     struct kvm_lapic_state kapic;
3776     int ret;
3777 
3778     if (apic && kvm_irqchip_in_kernel()) {
3779         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
3780         if (ret < 0) {
3781             return ret;
3782         }
3783 
3784         kvm_get_apic_state(apic, &kapic);
3785     }
3786     return 0;
3787 }
3788 
3789 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
3790 {
3791     CPUState *cs = CPU(cpu);
3792     CPUX86State *env = &cpu->env;
3793     struct kvm_vcpu_events events = {};
3794 
3795     if (!kvm_has_vcpu_events()) {
3796         return 0;
3797     }
3798 
3799     events.flags = 0;
3800 
3801     if (has_exception_payload) {
3802         events.flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
3803         events.exception.pending = env->exception_pending;
3804         events.exception_has_payload = env->exception_has_payload;
3805         events.exception_payload = env->exception_payload;
3806     }
3807     events.exception.nr = env->exception_nr;
3808     events.exception.injected = env->exception_injected;
3809     events.exception.has_error_code = env->has_error_code;
3810     events.exception.error_code = env->error_code;
3811 
3812     events.interrupt.injected = (env->interrupt_injected >= 0);
3813     events.interrupt.nr = env->interrupt_injected;
3814     events.interrupt.soft = env->soft_interrupt;
3815 
3816     events.nmi.injected = env->nmi_injected;
3817     events.nmi.pending = env->nmi_pending;
3818     events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
3819 
3820     events.sipi_vector = env->sipi_vector;
3821 
3822     if (has_msr_smbase) {
3823         events.smi.smm = !!(env->hflags & HF_SMM_MASK);
3824         events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
3825         if (kvm_irqchip_in_kernel()) {
3826             /* As soon as these are moved to the kernel, remove them
3827              * from cs->interrupt_request.
3828              */
3829             events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
3830             events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
3831             cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
3832         } else {
3833             /* Keep these in cs->interrupt_request.  */
3834             events.smi.pending = 0;
3835             events.smi.latched_init = 0;
3836         }
3837         /* Stop SMI delivery on old machine types to avoid a reboot
3838          * on an inward migration of an old VM.
3839          */
3840         if (!cpu->kvm_no_smi_migration) {
3841             events.flags |= KVM_VCPUEVENT_VALID_SMM;
3842         }
3843     }
3844 
3845     if (level >= KVM_PUT_RESET_STATE) {
3846         events.flags |= KVM_VCPUEVENT_VALID_NMI_PENDING;
3847         if (env->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
3848             events.flags |= KVM_VCPUEVENT_VALID_SIPI_VECTOR;
3849         }
3850     }
3851 
3852     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
3853 }
3854 
3855 static int kvm_get_vcpu_events(X86CPU *cpu)
3856 {
3857     CPUX86State *env = &cpu->env;
3858     struct kvm_vcpu_events events;
3859     int ret;
3860 
3861     if (!kvm_has_vcpu_events()) {
3862         return 0;
3863     }
3864 
3865     memset(&events, 0, sizeof(events));
3866     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
3867     if (ret < 0) {
3868        return ret;
3869     }
3870 
3871     if (events.flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
3872         env->exception_pending = events.exception.pending;
3873         env->exception_has_payload = events.exception_has_payload;
3874         env->exception_payload = events.exception_payload;
3875     } else {
3876         env->exception_pending = 0;
3877         env->exception_has_payload = false;
3878     }
3879     env->exception_injected = events.exception.injected;
3880     env->exception_nr =
3881         (env->exception_pending || env->exception_injected) ?
3882         events.exception.nr : -1;
3883     env->has_error_code = events.exception.has_error_code;
3884     env->error_code = events.exception.error_code;
3885 
3886     env->interrupt_injected =
3887         events.interrupt.injected ? events.interrupt.nr : -1;
3888     env->soft_interrupt = events.interrupt.soft;
3889 
3890     env->nmi_injected = events.nmi.injected;
3891     env->nmi_pending = events.nmi.pending;
3892     if (events.nmi.masked) {
3893         env->hflags2 |= HF2_NMI_MASK;
3894     } else {
3895         env->hflags2 &= ~HF2_NMI_MASK;
3896     }
3897 
3898     if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
3899         if (events.smi.smm) {
3900             env->hflags |= HF_SMM_MASK;
3901         } else {
3902             env->hflags &= ~HF_SMM_MASK;
3903         }
3904         if (events.smi.pending) {
3905             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
3906         } else {
3907             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
3908         }
3909         if (events.smi.smm_inside_nmi) {
3910             env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
3911         } else {
3912             env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
3913         }
3914         if (events.smi.latched_init) {
3915             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
3916         } else {
3917             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
3918         }
3919     }
3920 
3921     env->sipi_vector = events.sipi_vector;
3922 
3923     return 0;
3924 }
3925 
3926 static int kvm_guest_debug_workarounds(X86CPU *cpu)
3927 {
3928     CPUState *cs = CPU(cpu);
3929     CPUX86State *env = &cpu->env;
3930     int ret = 0;
3931     unsigned long reinject_trap = 0;
3932 
3933     if (!kvm_has_vcpu_events()) {
3934         if (env->exception_nr == EXCP01_DB) {
3935             reinject_trap = KVM_GUESTDBG_INJECT_DB;
3936         } else if (env->exception_injected == EXCP03_INT3) {
3937             reinject_trap = KVM_GUESTDBG_INJECT_BP;
3938         }
3939         kvm_reset_exception(env);
3940     }
3941 
3942     /*
3943      * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
3944      * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
3945      * by updating the debug state once again if single-stepping is on.
3946      * Another reason to call kvm_update_guest_debug here is a pending debug
3947      * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
3948      * reinject them via SET_GUEST_DEBUG.
3949      */
3950     if (reinject_trap ||
3951         (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
3952         ret = kvm_update_guest_debug(cs, reinject_trap);
3953     }
3954     return ret;
3955 }
3956 
3957 static int kvm_put_debugregs(X86CPU *cpu)
3958 {
3959     CPUX86State *env = &cpu->env;
3960     struct kvm_debugregs dbgregs;
3961     int i;
3962 
3963     if (!kvm_has_debugregs()) {
3964         return 0;
3965     }
3966 
3967     memset(&dbgregs, 0, sizeof(dbgregs));
3968     for (i = 0; i < 4; i++) {
3969         dbgregs.db[i] = env->dr[i];
3970     }
3971     dbgregs.dr6 = env->dr[6];
3972     dbgregs.dr7 = env->dr[7];
3973     dbgregs.flags = 0;
3974 
3975     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
3976 }
3977 
3978 static int kvm_get_debugregs(X86CPU *cpu)
3979 {
3980     CPUX86State *env = &cpu->env;
3981     struct kvm_debugregs dbgregs;
3982     int i, ret;
3983 
3984     if (!kvm_has_debugregs()) {
3985         return 0;
3986     }
3987 
3988     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
3989     if (ret < 0) {
3990         return ret;
3991     }
3992     for (i = 0; i < 4; i++) {
3993         env->dr[i] = dbgregs.db[i];
3994     }
3995     env->dr[4] = env->dr[6] = dbgregs.dr6;
3996     env->dr[5] = env->dr[7] = dbgregs.dr7;
3997 
3998     return 0;
3999 }
4000 
4001 static int kvm_put_nested_state(X86CPU *cpu)
4002 {
4003     CPUX86State *env = &cpu->env;
4004     int max_nested_state_len = kvm_max_nested_state_length();
4005 
4006     if (!env->nested_state) {
4007         return 0;
4008     }
4009 
4010     /*
4011      * Copy flags that are affected by reset from env->hflags and env->hflags2.
4012      */
4013     if (env->hflags & HF_GUEST_MASK) {
4014         env->nested_state->flags |= KVM_STATE_NESTED_GUEST_MODE;
4015     } else {
4016         env->nested_state->flags &= ~KVM_STATE_NESTED_GUEST_MODE;
4017     }
4018 
4019     /* Don't set KVM_STATE_NESTED_GIF_SET on VMX as it is illegal */
4020     if (cpu_has_svm(env) && (env->hflags2 & HF2_GIF_MASK)) {
4021         env->nested_state->flags |= KVM_STATE_NESTED_GIF_SET;
4022     } else {
4023         env->nested_state->flags &= ~KVM_STATE_NESTED_GIF_SET;
4024     }
4025 
4026     assert(env->nested_state->size <= max_nested_state_len);
4027     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_NESTED_STATE, env->nested_state);
4028 }
4029 
4030 static int kvm_get_nested_state(X86CPU *cpu)
4031 {
4032     CPUX86State *env = &cpu->env;
4033     int max_nested_state_len = kvm_max_nested_state_length();
4034     int ret;
4035 
4036     if (!env->nested_state) {
4037         return 0;
4038     }
4039 
4040     /*
4041      * It is possible that migration restored a smaller size into
4042      * nested_state->hdr.size than what our kernel support.
4043      * We preserve migration origin nested_state->hdr.size for
4044      * call to KVM_SET_NESTED_STATE but wish that our next call
4045      * to KVM_GET_NESTED_STATE will use max size our kernel support.
4046      */
4047     env->nested_state->size = max_nested_state_len;
4048 
4049     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_NESTED_STATE, env->nested_state);
4050     if (ret < 0) {
4051         return ret;
4052     }
4053 
4054     /*
4055      * Copy flags that are affected by reset to env->hflags and env->hflags2.
4056      */
4057     if (env->nested_state->flags & KVM_STATE_NESTED_GUEST_MODE) {
4058         env->hflags |= HF_GUEST_MASK;
4059     } else {
4060         env->hflags &= ~HF_GUEST_MASK;
4061     }
4062 
4063     /* Keep HF2_GIF_MASK set on !SVM as x86_cpu_pending_interrupt() needs it */
4064     if (cpu_has_svm(env)) {
4065         if (env->nested_state->flags & KVM_STATE_NESTED_GIF_SET) {
4066             env->hflags2 |= HF2_GIF_MASK;
4067         } else {
4068             env->hflags2 &= ~HF2_GIF_MASK;
4069         }
4070     }
4071 
4072     return ret;
4073 }
4074 
4075 int kvm_arch_put_registers(CPUState *cpu, int level)
4076 {
4077     X86CPU *x86_cpu = X86_CPU(cpu);
4078     int ret;
4079 
4080     assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
4081 
4082     /* must be before kvm_put_nested_state so that EFER.SVME is set */
4083     ret = kvm_put_sregs(x86_cpu);
4084     if (ret < 0) {
4085         return ret;
4086     }
4087 
4088     if (level >= KVM_PUT_RESET_STATE) {
4089         ret = kvm_put_nested_state(x86_cpu);
4090         if (ret < 0) {
4091             return ret;
4092         }
4093 
4094         ret = kvm_put_msr_feature_control(x86_cpu);
4095         if (ret < 0) {
4096             return ret;
4097         }
4098     }
4099 
4100     if (level == KVM_PUT_FULL_STATE) {
4101         /* We don't check for kvm_arch_set_tsc_khz() errors here,
4102          * because TSC frequency mismatch shouldn't abort migration,
4103          * unless the user explicitly asked for a more strict TSC
4104          * setting (e.g. using an explicit "tsc-freq" option).
4105          */
4106         kvm_arch_set_tsc_khz(cpu);
4107     }
4108 
4109     ret = kvm_getput_regs(x86_cpu, 1);
4110     if (ret < 0) {
4111         return ret;
4112     }
4113     ret = kvm_put_xsave(x86_cpu);
4114     if (ret < 0) {
4115         return ret;
4116     }
4117     ret = kvm_put_xcrs(x86_cpu);
4118     if (ret < 0) {
4119         return ret;
4120     }
4121     /* must be before kvm_put_msrs */
4122     ret = kvm_inject_mce_oldstyle(x86_cpu);
4123     if (ret < 0) {
4124         return ret;
4125     }
4126     ret = kvm_put_msrs(x86_cpu, level);
4127     if (ret < 0) {
4128         return ret;
4129     }
4130     ret = kvm_put_vcpu_events(x86_cpu, level);
4131     if (ret < 0) {
4132         return ret;
4133     }
4134     if (level >= KVM_PUT_RESET_STATE) {
4135         ret = kvm_put_mp_state(x86_cpu);
4136         if (ret < 0) {
4137             return ret;
4138         }
4139     }
4140 
4141     ret = kvm_put_tscdeadline_msr(x86_cpu);
4142     if (ret < 0) {
4143         return ret;
4144     }
4145     ret = kvm_put_debugregs(x86_cpu);
4146     if (ret < 0) {
4147         return ret;
4148     }
4149     /* must be last */
4150     ret = kvm_guest_debug_workarounds(x86_cpu);
4151     if (ret < 0) {
4152         return ret;
4153     }
4154     return 0;
4155 }
4156 
4157 int kvm_arch_get_registers(CPUState *cs)
4158 {
4159     X86CPU *cpu = X86_CPU(cs);
4160     int ret;
4161 
4162     assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
4163 
4164     ret = kvm_get_vcpu_events(cpu);
4165     if (ret < 0) {
4166         goto out;
4167     }
4168     /*
4169      * KVM_GET_MPSTATE can modify CS and RIP, call it before
4170      * KVM_GET_REGS and KVM_GET_SREGS.
4171      */
4172     ret = kvm_get_mp_state(cpu);
4173     if (ret < 0) {
4174         goto out;
4175     }
4176     ret = kvm_getput_regs(cpu, 0);
4177     if (ret < 0) {
4178         goto out;
4179     }
4180     ret = kvm_get_xsave(cpu);
4181     if (ret < 0) {
4182         goto out;
4183     }
4184     ret = kvm_get_xcrs(cpu);
4185     if (ret < 0) {
4186         goto out;
4187     }
4188     ret = kvm_get_sregs(cpu);
4189     if (ret < 0) {
4190         goto out;
4191     }
4192     ret = kvm_get_msrs(cpu);
4193     if (ret < 0) {
4194         goto out;
4195     }
4196     ret = kvm_get_apic(cpu);
4197     if (ret < 0) {
4198         goto out;
4199     }
4200     ret = kvm_get_debugregs(cpu);
4201     if (ret < 0) {
4202         goto out;
4203     }
4204     ret = kvm_get_nested_state(cpu);
4205     if (ret < 0) {
4206         goto out;
4207     }
4208     ret = 0;
4209  out:
4210     cpu_sync_bndcs_hflags(&cpu->env);
4211     return ret;
4212 }
4213 
4214 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
4215 {
4216     X86CPU *x86_cpu = X86_CPU(cpu);
4217     CPUX86State *env = &x86_cpu->env;
4218     int ret;
4219 
4220     /* Inject NMI */
4221     if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
4222         if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
4223             qemu_mutex_lock_iothread();
4224             cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
4225             qemu_mutex_unlock_iothread();
4226             DPRINTF("injected NMI\n");
4227             ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
4228             if (ret < 0) {
4229                 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
4230                         strerror(-ret));
4231             }
4232         }
4233         if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
4234             qemu_mutex_lock_iothread();
4235             cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
4236             qemu_mutex_unlock_iothread();
4237             DPRINTF("injected SMI\n");
4238             ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
4239             if (ret < 0) {
4240                 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
4241                         strerror(-ret));
4242             }
4243         }
4244     }
4245 
4246     if (!kvm_pic_in_kernel()) {
4247         qemu_mutex_lock_iothread();
4248     }
4249 
4250     /* Force the VCPU out of its inner loop to process any INIT requests
4251      * or (for userspace APIC, but it is cheap to combine the checks here)
4252      * pending TPR access reports.
4253      */
4254     if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
4255         if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
4256             !(env->hflags & HF_SMM_MASK)) {
4257             cpu->exit_request = 1;
4258         }
4259         if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
4260             cpu->exit_request = 1;
4261         }
4262     }
4263 
4264     if (!kvm_pic_in_kernel()) {
4265         /* Try to inject an interrupt if the guest can accept it */
4266         if (run->ready_for_interrupt_injection &&
4267             (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
4268             (env->eflags & IF_MASK)) {
4269             int irq;
4270 
4271             cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
4272             irq = cpu_get_pic_interrupt(env);
4273             if (irq >= 0) {
4274                 struct kvm_interrupt intr;
4275 
4276                 intr.irq = irq;
4277                 DPRINTF("injected interrupt %d\n", irq);
4278                 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
4279                 if (ret < 0) {
4280                     fprintf(stderr,
4281                             "KVM: injection failed, interrupt lost (%s)\n",
4282                             strerror(-ret));
4283                 }
4284             }
4285         }
4286 
4287         /* If we have an interrupt but the guest is not ready to receive an
4288          * interrupt, request an interrupt window exit.  This will
4289          * cause a return to userspace as soon as the guest is ready to
4290          * receive interrupts. */
4291         if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
4292             run->request_interrupt_window = 1;
4293         } else {
4294             run->request_interrupt_window = 0;
4295         }
4296 
4297         DPRINTF("setting tpr\n");
4298         run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
4299 
4300         qemu_mutex_unlock_iothread();
4301     }
4302 }
4303 
4304 static void kvm_rate_limit_on_bus_lock(void)
4305 {
4306     uint64_t delay_ns = ratelimit_calculate_delay(&bus_lock_ratelimit_ctrl, 1);
4307 
4308     if (delay_ns) {
4309         g_usleep(delay_ns / SCALE_US);
4310     }
4311 }
4312 
4313 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
4314 {
4315     X86CPU *x86_cpu = X86_CPU(cpu);
4316     CPUX86State *env = &x86_cpu->env;
4317 
4318     if (run->flags & KVM_RUN_X86_SMM) {
4319         env->hflags |= HF_SMM_MASK;
4320     } else {
4321         env->hflags &= ~HF_SMM_MASK;
4322     }
4323     if (run->if_flag) {
4324         env->eflags |= IF_MASK;
4325     } else {
4326         env->eflags &= ~IF_MASK;
4327     }
4328     if (run->flags & KVM_RUN_X86_BUS_LOCK) {
4329         kvm_rate_limit_on_bus_lock();
4330     }
4331 
4332     /* We need to protect the apic state against concurrent accesses from
4333      * different threads in case the userspace irqchip is used. */
4334     if (!kvm_irqchip_in_kernel()) {
4335         qemu_mutex_lock_iothread();
4336     }
4337     cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
4338     cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
4339     if (!kvm_irqchip_in_kernel()) {
4340         qemu_mutex_unlock_iothread();
4341     }
4342     return cpu_get_mem_attrs(env);
4343 }
4344 
4345 int kvm_arch_process_async_events(CPUState *cs)
4346 {
4347     X86CPU *cpu = X86_CPU(cs);
4348     CPUX86State *env = &cpu->env;
4349 
4350     if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
4351         /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
4352         assert(env->mcg_cap);
4353 
4354         cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
4355 
4356         kvm_cpu_synchronize_state(cs);
4357 
4358         if (env->exception_nr == EXCP08_DBLE) {
4359             /* this means triple fault */
4360             qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
4361             cs->exit_request = 1;
4362             return 0;
4363         }
4364         kvm_queue_exception(env, EXCP12_MCHK, 0, 0);
4365         env->has_error_code = 0;
4366 
4367         cs->halted = 0;
4368         if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
4369             env->mp_state = KVM_MP_STATE_RUNNABLE;
4370         }
4371     }
4372 
4373     if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
4374         !(env->hflags & HF_SMM_MASK)) {
4375         kvm_cpu_synchronize_state(cs);
4376         do_cpu_init(cpu);
4377     }
4378 
4379     if (kvm_irqchip_in_kernel()) {
4380         return 0;
4381     }
4382 
4383     if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
4384         cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
4385         apic_poll_irq(cpu->apic_state);
4386     }
4387     if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
4388          (env->eflags & IF_MASK)) ||
4389         (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
4390         cs->halted = 0;
4391     }
4392     if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
4393         kvm_cpu_synchronize_state(cs);
4394         do_cpu_sipi(cpu);
4395     }
4396     if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
4397         cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
4398         kvm_cpu_synchronize_state(cs);
4399         apic_handle_tpr_access_report(cpu->apic_state, env->eip,
4400                                       env->tpr_access_type);
4401     }
4402 
4403     return cs->halted;
4404 }
4405 
4406 static int kvm_handle_halt(X86CPU *cpu)
4407 {
4408     CPUState *cs = CPU(cpu);
4409     CPUX86State *env = &cpu->env;
4410 
4411     if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
4412           (env->eflags & IF_MASK)) &&
4413         !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
4414         cs->halted = 1;
4415         return EXCP_HLT;
4416     }
4417 
4418     return 0;
4419 }
4420 
4421 static int kvm_handle_tpr_access(X86CPU *cpu)
4422 {
4423     CPUState *cs = CPU(cpu);
4424     struct kvm_run *run = cs->kvm_run;
4425 
4426     apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
4427                                   run->tpr_access.is_write ? TPR_ACCESS_WRITE
4428                                                            : TPR_ACCESS_READ);
4429     return 1;
4430 }
4431 
4432 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
4433 {
4434     static const uint8_t int3 = 0xcc;
4435 
4436     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
4437         cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
4438         return -EINVAL;
4439     }
4440     return 0;
4441 }
4442 
4443 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
4444 {
4445     uint8_t int3;
4446 
4447     if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0)) {
4448         return -EINVAL;
4449     }
4450     if (int3 != 0xcc) {
4451         return 0;
4452     }
4453     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
4454         return -EINVAL;
4455     }
4456     return 0;
4457 }
4458 
4459 static struct {
4460     target_ulong addr;
4461     int len;
4462     int type;
4463 } hw_breakpoint[4];
4464 
4465 static int nb_hw_breakpoint;
4466 
4467 static int find_hw_breakpoint(target_ulong addr, int len, int type)
4468 {
4469     int n;
4470 
4471     for (n = 0; n < nb_hw_breakpoint; n++) {
4472         if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
4473             (hw_breakpoint[n].len == len || len == -1)) {
4474             return n;
4475         }
4476     }
4477     return -1;
4478 }
4479 
4480 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
4481                                   target_ulong len, int type)
4482 {
4483     switch (type) {
4484     case GDB_BREAKPOINT_HW:
4485         len = 1;
4486         break;
4487     case GDB_WATCHPOINT_WRITE:
4488     case GDB_WATCHPOINT_ACCESS:
4489         switch (len) {
4490         case 1:
4491             break;
4492         case 2:
4493         case 4:
4494         case 8:
4495             if (addr & (len - 1)) {
4496                 return -EINVAL;
4497             }
4498             break;
4499         default:
4500             return -EINVAL;
4501         }
4502         break;
4503     default:
4504         return -ENOSYS;
4505     }
4506 
4507     if (nb_hw_breakpoint == 4) {
4508         return -ENOBUFS;
4509     }
4510     if (find_hw_breakpoint(addr, len, type) >= 0) {
4511         return -EEXIST;
4512     }
4513     hw_breakpoint[nb_hw_breakpoint].addr = addr;
4514     hw_breakpoint[nb_hw_breakpoint].len = len;
4515     hw_breakpoint[nb_hw_breakpoint].type = type;
4516     nb_hw_breakpoint++;
4517 
4518     return 0;
4519 }
4520 
4521 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
4522                                   target_ulong len, int type)
4523 {
4524     int n;
4525 
4526     n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
4527     if (n < 0) {
4528         return -ENOENT;
4529     }
4530     nb_hw_breakpoint--;
4531     hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
4532 
4533     return 0;
4534 }
4535 
4536 void kvm_arch_remove_all_hw_breakpoints(void)
4537 {
4538     nb_hw_breakpoint = 0;
4539 }
4540 
4541 static CPUWatchpoint hw_watchpoint;
4542 
4543 static int kvm_handle_debug(X86CPU *cpu,
4544                             struct kvm_debug_exit_arch *arch_info)
4545 {
4546     CPUState *cs = CPU(cpu);
4547     CPUX86State *env = &cpu->env;
4548     int ret = 0;
4549     int n;
4550 
4551     if (arch_info->exception == EXCP01_DB) {
4552         if (arch_info->dr6 & DR6_BS) {
4553             if (cs->singlestep_enabled) {
4554                 ret = EXCP_DEBUG;
4555             }
4556         } else {
4557             for (n = 0; n < 4; n++) {
4558                 if (arch_info->dr6 & (1 << n)) {
4559                     switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
4560                     case 0x0:
4561                         ret = EXCP_DEBUG;
4562                         break;
4563                     case 0x1:
4564                         ret = EXCP_DEBUG;
4565                         cs->watchpoint_hit = &hw_watchpoint;
4566                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
4567                         hw_watchpoint.flags = BP_MEM_WRITE;
4568                         break;
4569                     case 0x3:
4570                         ret = EXCP_DEBUG;
4571                         cs->watchpoint_hit = &hw_watchpoint;
4572                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
4573                         hw_watchpoint.flags = BP_MEM_ACCESS;
4574                         break;
4575                     }
4576                 }
4577             }
4578         }
4579     } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
4580         ret = EXCP_DEBUG;
4581     }
4582     if (ret == 0) {
4583         cpu_synchronize_state(cs);
4584         assert(env->exception_nr == -1);
4585 
4586         /* pass to guest */
4587         kvm_queue_exception(env, arch_info->exception,
4588                             arch_info->exception == EXCP01_DB,
4589                             arch_info->dr6);
4590         env->has_error_code = 0;
4591     }
4592 
4593     return ret;
4594 }
4595 
4596 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
4597 {
4598     const uint8_t type_code[] = {
4599         [GDB_BREAKPOINT_HW] = 0x0,
4600         [GDB_WATCHPOINT_WRITE] = 0x1,
4601         [GDB_WATCHPOINT_ACCESS] = 0x3
4602     };
4603     const uint8_t len_code[] = {
4604         [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
4605     };
4606     int n;
4607 
4608     if (kvm_sw_breakpoints_active(cpu)) {
4609         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
4610     }
4611     if (nb_hw_breakpoint > 0) {
4612         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
4613         dbg->arch.debugreg[7] = 0x0600;
4614         for (n = 0; n < nb_hw_breakpoint; n++) {
4615             dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
4616             dbg->arch.debugreg[7] |= (2 << (n * 2)) |
4617                 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
4618                 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
4619         }
4620     }
4621 }
4622 
4623 static bool host_supports_vmx(void)
4624 {
4625     uint32_t ecx, unused;
4626 
4627     host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
4628     return ecx & CPUID_EXT_VMX;
4629 }
4630 
4631 #define VMX_INVALID_GUEST_STATE 0x80000021
4632 
4633 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
4634 {
4635     X86CPU *cpu = X86_CPU(cs);
4636     uint64_t code;
4637     int ret;
4638 
4639     switch (run->exit_reason) {
4640     case KVM_EXIT_HLT:
4641         DPRINTF("handle_hlt\n");
4642         qemu_mutex_lock_iothread();
4643         ret = kvm_handle_halt(cpu);
4644         qemu_mutex_unlock_iothread();
4645         break;
4646     case KVM_EXIT_SET_TPR:
4647         ret = 0;
4648         break;
4649     case KVM_EXIT_TPR_ACCESS:
4650         qemu_mutex_lock_iothread();
4651         ret = kvm_handle_tpr_access(cpu);
4652         qemu_mutex_unlock_iothread();
4653         break;
4654     case KVM_EXIT_FAIL_ENTRY:
4655         code = run->fail_entry.hardware_entry_failure_reason;
4656         fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
4657                 code);
4658         if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
4659             fprintf(stderr,
4660                     "\nIf you're running a guest on an Intel machine without "
4661                         "unrestricted mode\n"
4662                     "support, the failure can be most likely due to the guest "
4663                         "entering an invalid\n"
4664                     "state for Intel VT. For example, the guest maybe running "
4665                         "in big real mode\n"
4666                     "which is not supported on less recent Intel processors."
4667                         "\n\n");
4668         }
4669         ret = -1;
4670         break;
4671     case KVM_EXIT_EXCEPTION:
4672         fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
4673                 run->ex.exception, run->ex.error_code);
4674         ret = -1;
4675         break;
4676     case KVM_EXIT_DEBUG:
4677         DPRINTF("kvm_exit_debug\n");
4678         qemu_mutex_lock_iothread();
4679         ret = kvm_handle_debug(cpu, &run->debug.arch);
4680         qemu_mutex_unlock_iothread();
4681         break;
4682     case KVM_EXIT_HYPERV:
4683         ret = kvm_hv_handle_exit(cpu, &run->hyperv);
4684         break;
4685     case KVM_EXIT_IOAPIC_EOI:
4686         ioapic_eoi_broadcast(run->eoi.vector);
4687         ret = 0;
4688         break;
4689     case KVM_EXIT_X86_BUS_LOCK:
4690         /* already handled in kvm_arch_post_run */
4691         ret = 0;
4692         break;
4693     default:
4694         fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
4695         ret = -1;
4696         break;
4697     }
4698 
4699     return ret;
4700 }
4701 
4702 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
4703 {
4704     X86CPU *cpu = X86_CPU(cs);
4705     CPUX86State *env = &cpu->env;
4706 
4707     kvm_cpu_synchronize_state(cs);
4708     return !(env->cr[0] & CR0_PE_MASK) ||
4709            ((env->segs[R_CS].selector  & 3) != 3);
4710 }
4711 
4712 void kvm_arch_init_irq_routing(KVMState *s)
4713 {
4714     /* We know at this point that we're using the in-kernel
4715      * irqchip, so we can use irqfds, and on x86 we know
4716      * we can use msi via irqfd and GSI routing.
4717      */
4718     kvm_msi_via_irqfd_allowed = true;
4719     kvm_gsi_routing_allowed = true;
4720 
4721     if (kvm_irqchip_is_split()) {
4722         int i;
4723 
4724         /* If the ioapic is in QEMU and the lapics are in KVM, reserve
4725            MSI routes for signaling interrupts to the local apics. */
4726         for (i = 0; i < IOAPIC_NUM_PINS; i++) {
4727             if (kvm_irqchip_add_msi_route(s, 0, NULL) < 0) {
4728                 error_report("Could not enable split IRQ mode.");
4729                 exit(1);
4730             }
4731         }
4732     }
4733 }
4734 
4735 int kvm_arch_irqchip_create(KVMState *s)
4736 {
4737     int ret;
4738     if (kvm_kernel_irqchip_split()) {
4739         ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
4740         if (ret) {
4741             error_report("Could not enable split irqchip mode: %s",
4742                          strerror(-ret));
4743             exit(1);
4744         } else {
4745             DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
4746             kvm_split_irqchip = true;
4747             return 1;
4748         }
4749     } else {
4750         return 0;
4751     }
4752 }
4753 
4754 uint64_t kvm_swizzle_msi_ext_dest_id(uint64_t address)
4755 {
4756     CPUX86State *env;
4757     uint64_t ext_id;
4758 
4759     if (!first_cpu) {
4760         return address;
4761     }
4762     env = &X86_CPU(first_cpu)->env;
4763     if (!(env->features[FEAT_KVM] & (1 << KVM_FEATURE_MSI_EXT_DEST_ID))) {
4764         return address;
4765     }
4766 
4767     /*
4768      * If the remappable format bit is set, or the upper bits are
4769      * already set in address_hi, or the low extended bits aren't
4770      * there anyway, do nothing.
4771      */
4772     ext_id = address & (0xff << MSI_ADDR_DEST_IDX_SHIFT);
4773     if (!ext_id || (ext_id & (1 << MSI_ADDR_DEST_IDX_SHIFT)) || (address >> 32)) {
4774         return address;
4775     }
4776 
4777     address &= ~ext_id;
4778     address |= ext_id << 35;
4779     return address;
4780 }
4781 
4782 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
4783                              uint64_t address, uint32_t data, PCIDevice *dev)
4784 {
4785     X86IOMMUState *iommu = x86_iommu_get_default();
4786 
4787     if (iommu) {
4788         X86IOMMUClass *class = X86_IOMMU_DEVICE_GET_CLASS(iommu);
4789 
4790         if (class->int_remap) {
4791             int ret;
4792             MSIMessage src, dst;
4793 
4794             src.address = route->u.msi.address_hi;
4795             src.address <<= VTD_MSI_ADDR_HI_SHIFT;
4796             src.address |= route->u.msi.address_lo;
4797             src.data = route->u.msi.data;
4798 
4799             ret = class->int_remap(iommu, &src, &dst, dev ?     \
4800                                    pci_requester_id(dev) :      \
4801                                    X86_IOMMU_SID_INVALID);
4802             if (ret) {
4803                 trace_kvm_x86_fixup_msi_error(route->gsi);
4804                 return 1;
4805             }
4806 
4807             /*
4808              * Handled untranslated compatibilty format interrupt with
4809              * extended destination ID in the low bits 11-5. */
4810             dst.address = kvm_swizzle_msi_ext_dest_id(dst.address);
4811 
4812             route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
4813             route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
4814             route->u.msi.data = dst.data;
4815             return 0;
4816         }
4817     }
4818 
4819     address = kvm_swizzle_msi_ext_dest_id(address);
4820     route->u.msi.address_hi = address >> VTD_MSI_ADDR_HI_SHIFT;
4821     route->u.msi.address_lo = address & VTD_MSI_ADDR_LO_MASK;
4822     return 0;
4823 }
4824 
4825 typedef struct MSIRouteEntry MSIRouteEntry;
4826 
4827 struct MSIRouteEntry {
4828     PCIDevice *dev;             /* Device pointer */
4829     int vector;                 /* MSI/MSIX vector index */
4830     int virq;                   /* Virtual IRQ index */
4831     QLIST_ENTRY(MSIRouteEntry) list;
4832 };
4833 
4834 /* List of used GSI routes */
4835 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
4836     QLIST_HEAD_INITIALIZER(msi_route_list);
4837 
4838 static void kvm_update_msi_routes_all(void *private, bool global,
4839                                       uint32_t index, uint32_t mask)
4840 {
4841     int cnt = 0, vector;
4842     MSIRouteEntry *entry;
4843     MSIMessage msg;
4844     PCIDevice *dev;
4845 
4846     /* TODO: explicit route update */
4847     QLIST_FOREACH(entry, &msi_route_list, list) {
4848         cnt++;
4849         vector = entry->vector;
4850         dev = entry->dev;
4851         if (msix_enabled(dev) && !msix_is_masked(dev, vector)) {
4852             msg = msix_get_message(dev, vector);
4853         } else if (msi_enabled(dev) && !msi_is_masked(dev, vector)) {
4854             msg = msi_get_message(dev, vector);
4855         } else {
4856             /*
4857              * Either MSI/MSIX is disabled for the device, or the
4858              * specific message was masked out.  Skip this one.
4859              */
4860             continue;
4861         }
4862         kvm_irqchip_update_msi_route(kvm_state, entry->virq, msg, dev);
4863     }
4864     kvm_irqchip_commit_routes(kvm_state);
4865     trace_kvm_x86_update_msi_routes(cnt);
4866 }
4867 
4868 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
4869                                 int vector, PCIDevice *dev)
4870 {
4871     static bool notify_list_inited = false;
4872     MSIRouteEntry *entry;
4873 
4874     if (!dev) {
4875         /* These are (possibly) IOAPIC routes only used for split
4876          * kernel irqchip mode, while what we are housekeeping are
4877          * PCI devices only. */
4878         return 0;
4879     }
4880 
4881     entry = g_new0(MSIRouteEntry, 1);
4882     entry->dev = dev;
4883     entry->vector = vector;
4884     entry->virq = route->gsi;
4885     QLIST_INSERT_HEAD(&msi_route_list, entry, list);
4886 
4887     trace_kvm_x86_add_msi_route(route->gsi);
4888 
4889     if (!notify_list_inited) {
4890         /* For the first time we do add route, add ourselves into
4891          * IOMMU's IEC notify list if needed. */
4892         X86IOMMUState *iommu = x86_iommu_get_default();
4893         if (iommu) {
4894             x86_iommu_iec_register_notifier(iommu,
4895                                             kvm_update_msi_routes_all,
4896                                             NULL);
4897         }
4898         notify_list_inited = true;
4899     }
4900     return 0;
4901 }
4902 
4903 int kvm_arch_release_virq_post(int virq)
4904 {
4905     MSIRouteEntry *entry, *next;
4906     QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
4907         if (entry->virq == virq) {
4908             trace_kvm_x86_remove_msi_route(virq);
4909             QLIST_REMOVE(entry, list);
4910             g_free(entry);
4911             break;
4912         }
4913     }
4914     return 0;
4915 }
4916 
4917 int kvm_arch_msi_data_to_gsi(uint32_t data)
4918 {
4919     abort();
4920 }
4921 
4922 bool kvm_has_waitpkg(void)
4923 {
4924     return has_msr_umwait;
4925 }
4926 
4927 bool kvm_arch_cpu_check_are_resettable(void)
4928 {
4929     return !sev_es_enabled();
4930 }
4931