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