xref: /openbmc/qemu/target/i386/kvm/kvm.c (revision 65d1a2bd)
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 #define VMCS12_MAX_FIELD_INDEX (0x17)
2704 
2705 static void kvm_msr_entry_add_vmx(X86CPU *cpu, FeatureWordArray f)
2706 {
2707     uint64_t kvm_vmx_basic =
2708         kvm_arch_get_supported_msr_feature(kvm_state,
2709                                            MSR_IA32_VMX_BASIC);
2710 
2711     if (!kvm_vmx_basic) {
2712         /* If the kernel doesn't support VMX feature (kvm_intel.nested=0),
2713          * then kvm_vmx_basic will be 0 and KVM_SET_MSR will fail.
2714          */
2715         return;
2716     }
2717 
2718     uint64_t kvm_vmx_misc =
2719         kvm_arch_get_supported_msr_feature(kvm_state,
2720                                            MSR_IA32_VMX_MISC);
2721     uint64_t kvm_vmx_ept_vpid =
2722         kvm_arch_get_supported_msr_feature(kvm_state,
2723                                            MSR_IA32_VMX_EPT_VPID_CAP);
2724 
2725     /*
2726      * If the guest is 64-bit, a value of 1 is allowed for the host address
2727      * space size vmexit control.
2728      */
2729     uint64_t fixed_vmx_exit = f[FEAT_8000_0001_EDX] & CPUID_EXT2_LM
2730         ? (uint64_t)VMX_VM_EXIT_HOST_ADDR_SPACE_SIZE << 32 : 0;
2731 
2732     /*
2733      * Bits 0-30, 32-44 and 50-53 come from the host.  KVM should
2734      * not change them for backwards compatibility.
2735      */
2736     uint64_t fixed_vmx_basic = kvm_vmx_basic &
2737         (MSR_VMX_BASIC_VMCS_REVISION_MASK |
2738          MSR_VMX_BASIC_VMXON_REGION_SIZE_MASK |
2739          MSR_VMX_BASIC_VMCS_MEM_TYPE_MASK);
2740 
2741     /*
2742      * Same for bits 0-4 and 25-27.  Bits 16-24 (CR3 target count) can
2743      * change in the future but are always zero for now, clear them to be
2744      * future proof.  Bits 32-63 in theory could change, though KVM does
2745      * not support dual-monitor treatment and probably never will; mask
2746      * them out as well.
2747      */
2748     uint64_t fixed_vmx_misc = kvm_vmx_misc &
2749         (MSR_VMX_MISC_PREEMPTION_TIMER_SHIFT_MASK |
2750          MSR_VMX_MISC_MAX_MSR_LIST_SIZE_MASK);
2751 
2752     /*
2753      * EPT memory types should not change either, so we do not bother
2754      * adding features for them.
2755      */
2756     uint64_t fixed_vmx_ept_mask =
2757             (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_ENABLE_EPT ?
2758              MSR_VMX_EPT_UC | MSR_VMX_EPT_WB : 0);
2759     uint64_t fixed_vmx_ept_vpid = kvm_vmx_ept_vpid & fixed_vmx_ept_mask;
2760 
2761     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
2762                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
2763                                          f[FEAT_VMX_PROCBASED_CTLS]));
2764     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PINBASED_CTLS,
2765                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_PINBASED_CTLS,
2766                                          f[FEAT_VMX_PINBASED_CTLS]));
2767     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_EXIT_CTLS,
2768                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_EXIT_CTLS,
2769                                          f[FEAT_VMX_EXIT_CTLS]) | fixed_vmx_exit);
2770     kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_ENTRY_CTLS,
2771                       make_vmx_msr_value(MSR_IA32_VMX_TRUE_ENTRY_CTLS,
2772                                          f[FEAT_VMX_ENTRY_CTLS]));
2773     kvm_msr_entry_add(cpu, MSR_IA32_VMX_PROCBASED_CTLS2,
2774                       make_vmx_msr_value(MSR_IA32_VMX_PROCBASED_CTLS2,
2775                                          f[FEAT_VMX_SECONDARY_CTLS]));
2776     kvm_msr_entry_add(cpu, MSR_IA32_VMX_EPT_VPID_CAP,
2777                       f[FEAT_VMX_EPT_VPID_CAPS] | fixed_vmx_ept_vpid);
2778     kvm_msr_entry_add(cpu, MSR_IA32_VMX_BASIC,
2779                       f[FEAT_VMX_BASIC] | fixed_vmx_basic);
2780     kvm_msr_entry_add(cpu, MSR_IA32_VMX_MISC,
2781                       f[FEAT_VMX_MISC] | fixed_vmx_misc);
2782     if (has_msr_vmx_vmfunc) {
2783         kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMFUNC, f[FEAT_VMX_VMFUNC]);
2784     }
2785 
2786     /*
2787      * Just to be safe, write these with constant values.  The CRn_FIXED1
2788      * MSRs are generated by KVM based on the vCPU's CPUID.
2789      */
2790     kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR0_FIXED0,
2791                       CR0_PE_MASK | CR0_PG_MASK | CR0_NE_MASK);
2792     kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR4_FIXED0,
2793                       CR4_VMXE_MASK);
2794     kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM,
2795                       VMCS12_MAX_FIELD_INDEX << 1);
2796 }
2797 
2798 static void kvm_msr_entry_add_perf(X86CPU *cpu, FeatureWordArray f)
2799 {
2800     uint64_t kvm_perf_cap =
2801         kvm_arch_get_supported_msr_feature(kvm_state,
2802                                            MSR_IA32_PERF_CAPABILITIES);
2803 
2804     if (kvm_perf_cap) {
2805         kvm_msr_entry_add(cpu, MSR_IA32_PERF_CAPABILITIES,
2806                         kvm_perf_cap & f[FEAT_PERF_CAPABILITIES]);
2807     }
2808 }
2809 
2810 static int kvm_buf_set_msrs(X86CPU *cpu)
2811 {
2812     int ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
2813     if (ret < 0) {
2814         return ret;
2815     }
2816 
2817     if (ret < cpu->kvm_msr_buf->nmsrs) {
2818         struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
2819         error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,
2820                      (uint32_t)e->index, (uint64_t)e->data);
2821     }
2822 
2823     assert(ret == cpu->kvm_msr_buf->nmsrs);
2824     return 0;
2825 }
2826 
2827 static void kvm_init_msrs(X86CPU *cpu)
2828 {
2829     CPUX86State *env = &cpu->env;
2830 
2831     kvm_msr_buf_reset(cpu);
2832     if (has_msr_arch_capabs) {
2833         kvm_msr_entry_add(cpu, MSR_IA32_ARCH_CAPABILITIES,
2834                           env->features[FEAT_ARCH_CAPABILITIES]);
2835     }
2836 
2837     if (has_msr_core_capabs) {
2838         kvm_msr_entry_add(cpu, MSR_IA32_CORE_CAPABILITY,
2839                           env->features[FEAT_CORE_CAPABILITY]);
2840     }
2841 
2842     if (has_msr_perf_capabs && cpu->enable_pmu) {
2843         kvm_msr_entry_add_perf(cpu, env->features);
2844     }
2845 
2846     if (has_msr_ucode_rev) {
2847         kvm_msr_entry_add(cpu, MSR_IA32_UCODE_REV, cpu->ucode_rev);
2848     }
2849 
2850     /*
2851      * Older kernels do not include VMX MSRs in KVM_GET_MSR_INDEX_LIST, but
2852      * all kernels with MSR features should have them.
2853      */
2854     if (kvm_feature_msrs && cpu_has_vmx(env)) {
2855         kvm_msr_entry_add_vmx(cpu, env->features);
2856     }
2857 
2858     assert(kvm_buf_set_msrs(cpu) == 0);
2859 }
2860 
2861 static int kvm_put_msrs(X86CPU *cpu, int level)
2862 {
2863     CPUX86State *env = &cpu->env;
2864     int i;
2865 
2866     kvm_msr_buf_reset(cpu);
2867 
2868     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
2869     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
2870     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
2871     kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
2872     if (has_msr_star) {
2873         kvm_msr_entry_add(cpu, MSR_STAR, env->star);
2874     }
2875     if (has_msr_hsave_pa) {
2876         kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
2877     }
2878     if (has_msr_tsc_aux) {
2879         kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
2880     }
2881     if (has_msr_tsc_adjust) {
2882         kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
2883     }
2884     if (has_msr_misc_enable) {
2885         kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
2886                           env->msr_ia32_misc_enable);
2887     }
2888     if (has_msr_smbase) {
2889         kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
2890     }
2891     if (has_msr_smi_count) {
2892         kvm_msr_entry_add(cpu, MSR_SMI_COUNT, env->msr_smi_count);
2893     }
2894     if (has_msr_pkrs) {
2895         kvm_msr_entry_add(cpu, MSR_IA32_PKRS, env->pkrs);
2896     }
2897     if (has_msr_bndcfgs) {
2898         kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
2899     }
2900     if (has_msr_xss) {
2901         kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
2902     }
2903     if (has_msr_umwait) {
2904         kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, env->umwait);
2905     }
2906     if (has_msr_spec_ctrl) {
2907         kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, env->spec_ctrl);
2908     }
2909     if (has_msr_tsx_ctrl) {
2910         kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, env->tsx_ctrl);
2911     }
2912     if (has_msr_virt_ssbd) {
2913         kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, env->virt_ssbd);
2914     }
2915 
2916 #ifdef TARGET_X86_64
2917     if (lm_capable_kernel) {
2918         kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
2919         kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
2920         kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
2921         kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
2922     }
2923 #endif
2924 
2925     /*
2926      * The following MSRs have side effects on the guest or are too heavy
2927      * for normal writeback. Limit them to reset or full state updates.
2928      */
2929     if (level >= KVM_PUT_RESET_STATE) {
2930         kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
2931         kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
2932         kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
2933         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
2934             kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, env->async_pf_int_msr);
2935         }
2936         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
2937             kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
2938         }
2939         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
2940             kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
2941         }
2942         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
2943             kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
2944         }
2945 
2946         if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
2947             kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, env->poll_control_msr);
2948         }
2949 
2950         if (has_architectural_pmu_version > 0) {
2951             if (has_architectural_pmu_version > 1) {
2952                 /* Stop the counter.  */
2953                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
2954                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
2955             }
2956 
2957             /* Set the counter values.  */
2958             for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
2959                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
2960                                   env->msr_fixed_counters[i]);
2961             }
2962             for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
2963                 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
2964                                   env->msr_gp_counters[i]);
2965                 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
2966                                   env->msr_gp_evtsel[i]);
2967             }
2968             if (has_architectural_pmu_version > 1) {
2969                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
2970                                   env->msr_global_status);
2971                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
2972                                   env->msr_global_ovf_ctrl);
2973 
2974                 /* Now start the PMU.  */
2975                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
2976                                   env->msr_fixed_ctr_ctrl);
2977                 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
2978                                   env->msr_global_ctrl);
2979             }
2980         }
2981         /*
2982          * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,
2983          * only sync them to KVM on the first cpu
2984          */
2985         if (current_cpu == first_cpu) {
2986             if (has_msr_hv_hypercall) {
2987                 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
2988                                   env->msr_hv_guest_os_id);
2989                 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
2990                                   env->msr_hv_hypercall);
2991             }
2992             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
2993                 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,
2994                                   env->msr_hv_tsc);
2995             }
2996             if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
2997                 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL,
2998                                   env->msr_hv_reenlightenment_control);
2999                 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL,
3000                                   env->msr_hv_tsc_emulation_control);
3001                 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS,
3002                                   env->msr_hv_tsc_emulation_status);
3003             }
3004         }
3005         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3006             kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
3007                               env->msr_hv_vapic);
3008         }
3009         if (has_msr_hv_crash) {
3010             int j;
3011 
3012             for (j = 0; j < HV_CRASH_PARAMS; j++)
3013                 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
3014                                   env->msr_hv_crash_params[j]);
3015 
3016             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);
3017         }
3018         if (has_msr_hv_runtime) {
3019             kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
3020         }
3021         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)
3022             && hv_vpindex_settable) {
3023             kvm_msr_entry_add(cpu, HV_X64_MSR_VP_INDEX,
3024                               hyperv_vp_index(CPU(cpu)));
3025         }
3026         if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3027             int j;
3028 
3029             kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);
3030 
3031             kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
3032                               env->msr_hv_synic_control);
3033             kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
3034                               env->msr_hv_synic_evt_page);
3035             kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
3036                               env->msr_hv_synic_msg_page);
3037 
3038             for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
3039                 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
3040                                   env->msr_hv_synic_sint[j]);
3041             }
3042         }
3043         if (has_msr_hv_stimer) {
3044             int j;
3045 
3046             for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
3047                 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
3048                                 env->msr_hv_stimer_config[j]);
3049             }
3050 
3051             for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
3052                 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
3053                                 env->msr_hv_stimer_count[j]);
3054             }
3055         }
3056         if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3057             uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
3058 
3059             kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
3060             kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
3061             kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
3062             kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
3063             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
3064             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
3065             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
3066             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
3067             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
3068             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
3069             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
3070             kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
3071             for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
3072                 /* The CPU GPs if we write to a bit above the physical limit of
3073                  * the host CPU (and KVM emulates that)
3074                  */
3075                 uint64_t mask = env->mtrr_var[i].mask;
3076                 mask &= phys_mask;
3077 
3078                 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
3079                                   env->mtrr_var[i].base);
3080                 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
3081             }
3082         }
3083         if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
3084             int addr_num = kvm_arch_get_supported_cpuid(kvm_state,
3085                                                     0x14, 1, R_EAX) & 0x7;
3086 
3087             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL,
3088                             env->msr_rtit_ctrl);
3089             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS,
3090                             env->msr_rtit_status);
3091             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE,
3092                             env->msr_rtit_output_base);
3093             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK,
3094                             env->msr_rtit_output_mask);
3095             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH,
3096                             env->msr_rtit_cr3_match);
3097             for (i = 0; i < addr_num; i++) {
3098                 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i,
3099                             env->msr_rtit_addrs[i]);
3100             }
3101         }
3102 
3103         /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
3104          *       kvm_put_msr_feature_control. */
3105     }
3106 
3107     if (env->mcg_cap) {
3108         int i;
3109 
3110         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
3111         kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
3112         if (has_msr_mcg_ext_ctl) {
3113             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
3114         }
3115         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3116             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
3117         }
3118     }
3119 
3120     return kvm_buf_set_msrs(cpu);
3121 }
3122 
3123 
3124 static int kvm_get_fpu(X86CPU *cpu)
3125 {
3126     CPUX86State *env = &cpu->env;
3127     struct kvm_fpu fpu;
3128     int i, ret;
3129 
3130     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
3131     if (ret < 0) {
3132         return ret;
3133     }
3134 
3135     env->fpstt = (fpu.fsw >> 11) & 7;
3136     env->fpus = fpu.fsw;
3137     env->fpuc = fpu.fcw;
3138     env->fpop = fpu.last_opcode;
3139     env->fpip = fpu.last_ip;
3140     env->fpdp = fpu.last_dp;
3141     for (i = 0; i < 8; ++i) {
3142         env->fptags[i] = !((fpu.ftwx >> i) & 1);
3143     }
3144     memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
3145     for (i = 0; i < CPU_NB_REGS; i++) {
3146         env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
3147         env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
3148     }
3149     env->mxcsr = fpu.mxcsr;
3150 
3151     return 0;
3152 }
3153 
3154 static int kvm_get_xsave(X86CPU *cpu)
3155 {
3156     CPUX86State *env = &cpu->env;
3157     X86XSaveArea *xsave = env->xsave_buf;
3158     int ret;
3159 
3160     if (!has_xsave) {
3161         return kvm_get_fpu(cpu);
3162     }
3163 
3164     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
3165     if (ret < 0) {
3166         return ret;
3167     }
3168     x86_cpu_xrstor_all_areas(cpu, xsave);
3169 
3170     return 0;
3171 }
3172 
3173 static int kvm_get_xcrs(X86CPU *cpu)
3174 {
3175     CPUX86State *env = &cpu->env;
3176     int i, ret;
3177     struct kvm_xcrs xcrs;
3178 
3179     if (!has_xcrs) {
3180         return 0;
3181     }
3182 
3183     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
3184     if (ret < 0) {
3185         return ret;
3186     }
3187 
3188     for (i = 0; i < xcrs.nr_xcrs; i++) {
3189         /* Only support xcr0 now */
3190         if (xcrs.xcrs[i].xcr == 0) {
3191             env->xcr0 = xcrs.xcrs[i].value;
3192             break;
3193         }
3194     }
3195     return 0;
3196 }
3197 
3198 static int kvm_get_sregs(X86CPU *cpu)
3199 {
3200     CPUX86State *env = &cpu->env;
3201     struct kvm_sregs sregs;
3202     int bit, i, ret;
3203 
3204     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
3205     if (ret < 0) {
3206         return ret;
3207     }
3208 
3209     /* There can only be one pending IRQ set in the bitmap at a time, so try
3210        to find it and save its number instead (-1 for none). */
3211     env->interrupt_injected = -1;
3212     for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
3213         if (sregs.interrupt_bitmap[i]) {
3214             bit = ctz64(sregs.interrupt_bitmap[i]);
3215             env->interrupt_injected = i * 64 + bit;
3216             break;
3217         }
3218     }
3219 
3220     get_seg(&env->segs[R_CS], &sregs.cs);
3221     get_seg(&env->segs[R_DS], &sregs.ds);
3222     get_seg(&env->segs[R_ES], &sregs.es);
3223     get_seg(&env->segs[R_FS], &sregs.fs);
3224     get_seg(&env->segs[R_GS], &sregs.gs);
3225     get_seg(&env->segs[R_SS], &sregs.ss);
3226 
3227     get_seg(&env->tr, &sregs.tr);
3228     get_seg(&env->ldt, &sregs.ldt);
3229 
3230     env->idt.limit = sregs.idt.limit;
3231     env->idt.base = sregs.idt.base;
3232     env->gdt.limit = sregs.gdt.limit;
3233     env->gdt.base = sregs.gdt.base;
3234 
3235     env->cr[0] = sregs.cr0;
3236     env->cr[2] = sregs.cr2;
3237     env->cr[3] = sregs.cr3;
3238     env->cr[4] = sregs.cr4;
3239 
3240     env->efer = sregs.efer;
3241 
3242     /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
3243     x86_update_hflags(env);
3244 
3245     return 0;
3246 }
3247 
3248 static int kvm_get_msrs(X86CPU *cpu)
3249 {
3250     CPUX86State *env = &cpu->env;
3251     struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
3252     int ret, i;
3253     uint64_t mtrr_top_bits;
3254 
3255     kvm_msr_buf_reset(cpu);
3256 
3257     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
3258     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
3259     kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
3260     kvm_msr_entry_add(cpu, MSR_PAT, 0);
3261     if (has_msr_star) {
3262         kvm_msr_entry_add(cpu, MSR_STAR, 0);
3263     }
3264     if (has_msr_hsave_pa) {
3265         kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
3266     }
3267     if (has_msr_tsc_aux) {
3268         kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
3269     }
3270     if (has_msr_tsc_adjust) {
3271         kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
3272     }
3273     if (has_msr_tsc_deadline) {
3274         kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
3275     }
3276     if (has_msr_misc_enable) {
3277         kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
3278     }
3279     if (has_msr_smbase) {
3280         kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
3281     }
3282     if (has_msr_smi_count) {
3283         kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
3284     }
3285     if (has_msr_feature_control) {
3286         kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
3287     }
3288     if (has_msr_pkrs) {
3289         kvm_msr_entry_add(cpu, MSR_IA32_PKRS, 0);
3290     }
3291     if (has_msr_bndcfgs) {
3292         kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
3293     }
3294     if (has_msr_xss) {
3295         kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
3296     }
3297     if (has_msr_umwait) {
3298         kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, 0);
3299     }
3300     if (has_msr_spec_ctrl) {
3301         kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
3302     }
3303     if (has_msr_tsx_ctrl) {
3304         kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, 0);
3305     }
3306     if (has_msr_virt_ssbd) {
3307         kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, 0);
3308     }
3309     if (!env->tsc_valid) {
3310         kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
3311         env->tsc_valid = !runstate_is_running();
3312     }
3313 
3314 #ifdef TARGET_X86_64
3315     if (lm_capable_kernel) {
3316         kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
3317         kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
3318         kvm_msr_entry_add(cpu, MSR_FMASK, 0);
3319         kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
3320     }
3321 #endif
3322     kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
3323     kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
3324     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
3325         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, 0);
3326     }
3327     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
3328         kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
3329     }
3330     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
3331         kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
3332     }
3333     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
3334         kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
3335     }
3336     if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
3337         kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, 1);
3338     }
3339     if (has_architectural_pmu_version > 0) {
3340         if (has_architectural_pmu_version > 1) {
3341             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
3342             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
3343             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
3344             kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
3345         }
3346         for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
3347             kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
3348         }
3349         for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
3350             kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
3351             kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
3352         }
3353     }
3354 
3355     if (env->mcg_cap) {
3356         kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
3357         kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
3358         if (has_msr_mcg_ext_ctl) {
3359             kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
3360         }
3361         for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3362             kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
3363         }
3364     }
3365 
3366     if (has_msr_hv_hypercall) {
3367         kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
3368         kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
3369     }
3370     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3371         kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
3372     }
3373     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
3374         kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
3375     }
3376     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
3377         kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL, 0);
3378         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL, 0);
3379         kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS, 0);
3380     }
3381     if (has_msr_hv_crash) {
3382         int j;
3383 
3384         for (j = 0; j < HV_CRASH_PARAMS; j++) {
3385             kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
3386         }
3387     }
3388     if (has_msr_hv_runtime) {
3389         kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
3390     }
3391     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3392         uint32_t msr;
3393 
3394         kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
3395         kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
3396         kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
3397         for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
3398             kvm_msr_entry_add(cpu, msr, 0);
3399         }
3400     }
3401     if (has_msr_hv_stimer) {
3402         uint32_t msr;
3403 
3404         for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
3405              msr++) {
3406             kvm_msr_entry_add(cpu, msr, 0);
3407         }
3408     }
3409     if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3410         kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
3411         kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
3412         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
3413         kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
3414         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
3415         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
3416         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
3417         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
3418         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
3419         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
3420         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
3421         kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
3422         for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
3423             kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
3424             kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
3425         }
3426     }
3427 
3428     if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
3429         int addr_num =
3430             kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
3431 
3432         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
3433         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
3434         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
3435         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
3436         kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
3437         for (i = 0; i < addr_num; i++) {
3438             kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
3439         }
3440     }
3441 
3442     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
3443     if (ret < 0) {
3444         return ret;
3445     }
3446 
3447     if (ret < cpu->kvm_msr_buf->nmsrs) {
3448         struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
3449         error_report("error: failed to get MSR 0x%" PRIx32,
3450                      (uint32_t)e->index);
3451     }
3452 
3453     assert(ret == cpu->kvm_msr_buf->nmsrs);
3454     /*
3455      * MTRR masks: Each mask consists of 5 parts
3456      * a  10..0: must be zero
3457      * b  11   : valid bit
3458      * c n-1.12: actual mask bits
3459      * d  51..n: reserved must be zero
3460      * e  63.52: reserved must be zero
3461      *
3462      * 'n' is the number of physical bits supported by the CPU and is
3463      * apparently always <= 52.   We know our 'n' but don't know what
3464      * the destinations 'n' is; it might be smaller, in which case
3465      * it masks (c) on loading. It might be larger, in which case
3466      * we fill 'd' so that d..c is consistent irrespetive of the 'n'
3467      * we're migrating to.
3468      */
3469 
3470     if (cpu->fill_mtrr_mask) {
3471         QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
3472         assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
3473         mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
3474     } else {
3475         mtrr_top_bits = 0;
3476     }
3477 
3478     for (i = 0; i < ret; i++) {
3479         uint32_t index = msrs[i].index;
3480         switch (index) {
3481         case MSR_IA32_SYSENTER_CS:
3482             env->sysenter_cs = msrs[i].data;
3483             break;
3484         case MSR_IA32_SYSENTER_ESP:
3485             env->sysenter_esp = msrs[i].data;
3486             break;
3487         case MSR_IA32_SYSENTER_EIP:
3488             env->sysenter_eip = msrs[i].data;
3489             break;
3490         case MSR_PAT:
3491             env->pat = msrs[i].data;
3492             break;
3493         case MSR_STAR:
3494             env->star = msrs[i].data;
3495             break;
3496 #ifdef TARGET_X86_64
3497         case MSR_CSTAR:
3498             env->cstar = msrs[i].data;
3499             break;
3500         case MSR_KERNELGSBASE:
3501             env->kernelgsbase = msrs[i].data;
3502             break;
3503         case MSR_FMASK:
3504             env->fmask = msrs[i].data;
3505             break;
3506         case MSR_LSTAR:
3507             env->lstar = msrs[i].data;
3508             break;
3509 #endif
3510         case MSR_IA32_TSC:
3511             env->tsc = msrs[i].data;
3512             break;
3513         case MSR_TSC_AUX:
3514             env->tsc_aux = msrs[i].data;
3515             break;
3516         case MSR_TSC_ADJUST:
3517             env->tsc_adjust = msrs[i].data;
3518             break;
3519         case MSR_IA32_TSCDEADLINE:
3520             env->tsc_deadline = msrs[i].data;
3521             break;
3522         case MSR_VM_HSAVE_PA:
3523             env->vm_hsave = msrs[i].data;
3524             break;
3525         case MSR_KVM_SYSTEM_TIME:
3526             env->system_time_msr = msrs[i].data;
3527             break;
3528         case MSR_KVM_WALL_CLOCK:
3529             env->wall_clock_msr = msrs[i].data;
3530             break;
3531         case MSR_MCG_STATUS:
3532             env->mcg_status = msrs[i].data;
3533             break;
3534         case MSR_MCG_CTL:
3535             env->mcg_ctl = msrs[i].data;
3536             break;
3537         case MSR_MCG_EXT_CTL:
3538             env->mcg_ext_ctl = msrs[i].data;
3539             break;
3540         case MSR_IA32_MISC_ENABLE:
3541             env->msr_ia32_misc_enable = msrs[i].data;
3542             break;
3543         case MSR_IA32_SMBASE:
3544             env->smbase = msrs[i].data;
3545             break;
3546         case MSR_SMI_COUNT:
3547             env->msr_smi_count = msrs[i].data;
3548             break;
3549         case MSR_IA32_FEATURE_CONTROL:
3550             env->msr_ia32_feature_control = msrs[i].data;
3551             break;
3552         case MSR_IA32_BNDCFGS:
3553             env->msr_bndcfgs = msrs[i].data;
3554             break;
3555         case MSR_IA32_XSS:
3556             env->xss = msrs[i].data;
3557             break;
3558         case MSR_IA32_UMWAIT_CONTROL:
3559             env->umwait = msrs[i].data;
3560             break;
3561         case MSR_IA32_PKRS:
3562             env->pkrs = msrs[i].data;
3563             break;
3564         default:
3565             if (msrs[i].index >= MSR_MC0_CTL &&
3566                 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
3567                 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
3568             }
3569             break;
3570         case MSR_KVM_ASYNC_PF_EN:
3571             env->async_pf_en_msr = msrs[i].data;
3572             break;
3573         case MSR_KVM_ASYNC_PF_INT:
3574             env->async_pf_int_msr = msrs[i].data;
3575             break;
3576         case MSR_KVM_PV_EOI_EN:
3577             env->pv_eoi_en_msr = msrs[i].data;
3578             break;
3579         case MSR_KVM_STEAL_TIME:
3580             env->steal_time_msr = msrs[i].data;
3581             break;
3582         case MSR_KVM_POLL_CONTROL: {
3583             env->poll_control_msr = msrs[i].data;
3584             break;
3585         }
3586         case MSR_CORE_PERF_FIXED_CTR_CTRL:
3587             env->msr_fixed_ctr_ctrl = msrs[i].data;
3588             break;
3589         case MSR_CORE_PERF_GLOBAL_CTRL:
3590             env->msr_global_ctrl = msrs[i].data;
3591             break;
3592         case MSR_CORE_PERF_GLOBAL_STATUS:
3593             env->msr_global_status = msrs[i].data;
3594             break;
3595         case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
3596             env->msr_global_ovf_ctrl = msrs[i].data;
3597             break;
3598         case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
3599             env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
3600             break;
3601         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
3602             env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
3603             break;
3604         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
3605             env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
3606             break;
3607         case HV_X64_MSR_HYPERCALL:
3608             env->msr_hv_hypercall = msrs[i].data;
3609             break;
3610         case HV_X64_MSR_GUEST_OS_ID:
3611             env->msr_hv_guest_os_id = msrs[i].data;
3612             break;
3613         case HV_X64_MSR_APIC_ASSIST_PAGE:
3614             env->msr_hv_vapic = msrs[i].data;
3615             break;
3616         case HV_X64_MSR_REFERENCE_TSC:
3617             env->msr_hv_tsc = msrs[i].data;
3618             break;
3619         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3620             env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
3621             break;
3622         case HV_X64_MSR_VP_RUNTIME:
3623             env->msr_hv_runtime = msrs[i].data;
3624             break;
3625         case HV_X64_MSR_SCONTROL:
3626             env->msr_hv_synic_control = msrs[i].data;
3627             break;
3628         case HV_X64_MSR_SIEFP:
3629             env->msr_hv_synic_evt_page = msrs[i].data;
3630             break;
3631         case HV_X64_MSR_SIMP:
3632             env->msr_hv_synic_msg_page = msrs[i].data;
3633             break;
3634         case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
3635             env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
3636             break;
3637         case HV_X64_MSR_STIMER0_CONFIG:
3638         case HV_X64_MSR_STIMER1_CONFIG:
3639         case HV_X64_MSR_STIMER2_CONFIG:
3640         case HV_X64_MSR_STIMER3_CONFIG:
3641             env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
3642                                 msrs[i].data;
3643             break;
3644         case HV_X64_MSR_STIMER0_COUNT:
3645         case HV_X64_MSR_STIMER1_COUNT:
3646         case HV_X64_MSR_STIMER2_COUNT:
3647         case HV_X64_MSR_STIMER3_COUNT:
3648             env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
3649                                 msrs[i].data;
3650             break;
3651         case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3652             env->msr_hv_reenlightenment_control = msrs[i].data;
3653             break;
3654         case HV_X64_MSR_TSC_EMULATION_CONTROL:
3655             env->msr_hv_tsc_emulation_control = msrs[i].data;
3656             break;
3657         case HV_X64_MSR_TSC_EMULATION_STATUS:
3658             env->msr_hv_tsc_emulation_status = msrs[i].data;
3659             break;
3660         case MSR_MTRRdefType:
3661             env->mtrr_deftype = msrs[i].data;
3662             break;
3663         case MSR_MTRRfix64K_00000:
3664             env->mtrr_fixed[0] = msrs[i].data;
3665             break;
3666         case MSR_MTRRfix16K_80000:
3667             env->mtrr_fixed[1] = msrs[i].data;
3668             break;
3669         case MSR_MTRRfix16K_A0000:
3670             env->mtrr_fixed[2] = msrs[i].data;
3671             break;
3672         case MSR_MTRRfix4K_C0000:
3673             env->mtrr_fixed[3] = msrs[i].data;
3674             break;
3675         case MSR_MTRRfix4K_C8000:
3676             env->mtrr_fixed[4] = msrs[i].data;
3677             break;
3678         case MSR_MTRRfix4K_D0000:
3679             env->mtrr_fixed[5] = msrs[i].data;
3680             break;
3681         case MSR_MTRRfix4K_D8000:
3682             env->mtrr_fixed[6] = msrs[i].data;
3683             break;
3684         case MSR_MTRRfix4K_E0000:
3685             env->mtrr_fixed[7] = msrs[i].data;
3686             break;
3687         case MSR_MTRRfix4K_E8000:
3688             env->mtrr_fixed[8] = msrs[i].data;
3689             break;
3690         case MSR_MTRRfix4K_F0000:
3691             env->mtrr_fixed[9] = msrs[i].data;
3692             break;
3693         case MSR_MTRRfix4K_F8000:
3694             env->mtrr_fixed[10] = msrs[i].data;
3695             break;
3696         case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
3697             if (index & 1) {
3698                 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
3699                                                                mtrr_top_bits;
3700             } else {
3701                 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
3702             }
3703             break;
3704         case MSR_IA32_SPEC_CTRL:
3705             env->spec_ctrl = msrs[i].data;
3706             break;
3707         case MSR_IA32_TSX_CTRL:
3708             env->tsx_ctrl = msrs[i].data;
3709             break;
3710         case MSR_VIRT_SSBD:
3711             env->virt_ssbd = msrs[i].data;
3712             break;
3713         case MSR_IA32_RTIT_CTL:
3714             env->msr_rtit_ctrl = msrs[i].data;
3715             break;
3716         case MSR_IA32_RTIT_STATUS:
3717             env->msr_rtit_status = msrs[i].data;
3718             break;
3719         case MSR_IA32_RTIT_OUTPUT_BASE:
3720             env->msr_rtit_output_base = msrs[i].data;
3721             break;
3722         case MSR_IA32_RTIT_OUTPUT_MASK:
3723             env->msr_rtit_output_mask = msrs[i].data;
3724             break;
3725         case MSR_IA32_RTIT_CR3_MATCH:
3726             env->msr_rtit_cr3_match = msrs[i].data;
3727             break;
3728         case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
3729             env->msr_rtit_addrs[index - MSR_IA32_RTIT_ADDR0_A] = msrs[i].data;
3730             break;
3731         }
3732     }
3733 
3734     return 0;
3735 }
3736 
3737 static int kvm_put_mp_state(X86CPU *cpu)
3738 {
3739     struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
3740 
3741     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
3742 }
3743 
3744 static int kvm_get_mp_state(X86CPU *cpu)
3745 {
3746     CPUState *cs = CPU(cpu);
3747     CPUX86State *env = &cpu->env;
3748     struct kvm_mp_state mp_state;
3749     int ret;
3750 
3751     ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
3752     if (ret < 0) {
3753         return ret;
3754     }
3755     env->mp_state = mp_state.mp_state;
3756     if (kvm_irqchip_in_kernel()) {
3757         cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
3758     }
3759     return 0;
3760 }
3761 
3762 static int kvm_get_apic(X86CPU *cpu)
3763 {
3764     DeviceState *apic = cpu->apic_state;
3765     struct kvm_lapic_state kapic;
3766     int ret;
3767 
3768     if (apic && kvm_irqchip_in_kernel()) {
3769         ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
3770         if (ret < 0) {
3771             return ret;
3772         }
3773 
3774         kvm_get_apic_state(apic, &kapic);
3775     }
3776     return 0;
3777 }
3778 
3779 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
3780 {
3781     CPUState *cs = CPU(cpu);
3782     CPUX86State *env = &cpu->env;
3783     struct kvm_vcpu_events events = {};
3784 
3785     if (!kvm_has_vcpu_events()) {
3786         return 0;
3787     }
3788 
3789     events.flags = 0;
3790 
3791     if (has_exception_payload) {
3792         events.flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
3793         events.exception.pending = env->exception_pending;
3794         events.exception_has_payload = env->exception_has_payload;
3795         events.exception_payload = env->exception_payload;
3796     }
3797     events.exception.nr = env->exception_nr;
3798     events.exception.injected = env->exception_injected;
3799     events.exception.has_error_code = env->has_error_code;
3800     events.exception.error_code = env->error_code;
3801 
3802     events.interrupt.injected = (env->interrupt_injected >= 0);
3803     events.interrupt.nr = env->interrupt_injected;
3804     events.interrupt.soft = env->soft_interrupt;
3805 
3806     events.nmi.injected = env->nmi_injected;
3807     events.nmi.pending = env->nmi_pending;
3808     events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
3809 
3810     events.sipi_vector = env->sipi_vector;
3811 
3812     if (has_msr_smbase) {
3813         events.smi.smm = !!(env->hflags & HF_SMM_MASK);
3814         events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
3815         if (kvm_irqchip_in_kernel()) {
3816             /* As soon as these are moved to the kernel, remove them
3817              * from cs->interrupt_request.
3818              */
3819             events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
3820             events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
3821             cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
3822         } else {
3823             /* Keep these in cs->interrupt_request.  */
3824             events.smi.pending = 0;
3825             events.smi.latched_init = 0;
3826         }
3827         /* Stop SMI delivery on old machine types to avoid a reboot
3828          * on an inward migration of an old VM.
3829          */
3830         if (!cpu->kvm_no_smi_migration) {
3831             events.flags |= KVM_VCPUEVENT_VALID_SMM;
3832         }
3833     }
3834 
3835     if (level >= KVM_PUT_RESET_STATE) {
3836         events.flags |= KVM_VCPUEVENT_VALID_NMI_PENDING;
3837         if (env->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
3838             events.flags |= KVM_VCPUEVENT_VALID_SIPI_VECTOR;
3839         }
3840     }
3841 
3842     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
3843 }
3844 
3845 static int kvm_get_vcpu_events(X86CPU *cpu)
3846 {
3847     CPUX86State *env = &cpu->env;
3848     struct kvm_vcpu_events events;
3849     int ret;
3850 
3851     if (!kvm_has_vcpu_events()) {
3852         return 0;
3853     }
3854 
3855     memset(&events, 0, sizeof(events));
3856     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
3857     if (ret < 0) {
3858        return ret;
3859     }
3860 
3861     if (events.flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
3862         env->exception_pending = events.exception.pending;
3863         env->exception_has_payload = events.exception_has_payload;
3864         env->exception_payload = events.exception_payload;
3865     } else {
3866         env->exception_pending = 0;
3867         env->exception_has_payload = false;
3868     }
3869     env->exception_injected = events.exception.injected;
3870     env->exception_nr =
3871         (env->exception_pending || env->exception_injected) ?
3872         events.exception.nr : -1;
3873     env->has_error_code = events.exception.has_error_code;
3874     env->error_code = events.exception.error_code;
3875 
3876     env->interrupt_injected =
3877         events.interrupt.injected ? events.interrupt.nr : -1;
3878     env->soft_interrupt = events.interrupt.soft;
3879 
3880     env->nmi_injected = events.nmi.injected;
3881     env->nmi_pending = events.nmi.pending;
3882     if (events.nmi.masked) {
3883         env->hflags2 |= HF2_NMI_MASK;
3884     } else {
3885         env->hflags2 &= ~HF2_NMI_MASK;
3886     }
3887 
3888     if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
3889         if (events.smi.smm) {
3890             env->hflags |= HF_SMM_MASK;
3891         } else {
3892             env->hflags &= ~HF_SMM_MASK;
3893         }
3894         if (events.smi.pending) {
3895             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
3896         } else {
3897             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
3898         }
3899         if (events.smi.smm_inside_nmi) {
3900             env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
3901         } else {
3902             env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
3903         }
3904         if (events.smi.latched_init) {
3905             cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
3906         } else {
3907             cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
3908         }
3909     }
3910 
3911     env->sipi_vector = events.sipi_vector;
3912 
3913     return 0;
3914 }
3915 
3916 static int kvm_guest_debug_workarounds(X86CPU *cpu)
3917 {
3918     CPUState *cs = CPU(cpu);
3919     CPUX86State *env = &cpu->env;
3920     int ret = 0;
3921     unsigned long reinject_trap = 0;
3922 
3923     if (!kvm_has_vcpu_events()) {
3924         if (env->exception_nr == EXCP01_DB) {
3925             reinject_trap = KVM_GUESTDBG_INJECT_DB;
3926         } else if (env->exception_injected == EXCP03_INT3) {
3927             reinject_trap = KVM_GUESTDBG_INJECT_BP;
3928         }
3929         kvm_reset_exception(env);
3930     }
3931 
3932     /*
3933      * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
3934      * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
3935      * by updating the debug state once again if single-stepping is on.
3936      * Another reason to call kvm_update_guest_debug here is a pending debug
3937      * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
3938      * reinject them via SET_GUEST_DEBUG.
3939      */
3940     if (reinject_trap ||
3941         (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
3942         ret = kvm_update_guest_debug(cs, reinject_trap);
3943     }
3944     return ret;
3945 }
3946 
3947 static int kvm_put_debugregs(X86CPU *cpu)
3948 {
3949     CPUX86State *env = &cpu->env;
3950     struct kvm_debugregs dbgregs;
3951     int i;
3952 
3953     if (!kvm_has_debugregs()) {
3954         return 0;
3955     }
3956 
3957     memset(&dbgregs, 0, sizeof(dbgregs));
3958     for (i = 0; i < 4; i++) {
3959         dbgregs.db[i] = env->dr[i];
3960     }
3961     dbgregs.dr6 = env->dr[6];
3962     dbgregs.dr7 = env->dr[7];
3963     dbgregs.flags = 0;
3964 
3965     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
3966 }
3967 
3968 static int kvm_get_debugregs(X86CPU *cpu)
3969 {
3970     CPUX86State *env = &cpu->env;
3971     struct kvm_debugregs dbgregs;
3972     int i, ret;
3973 
3974     if (!kvm_has_debugregs()) {
3975         return 0;
3976     }
3977 
3978     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
3979     if (ret < 0) {
3980         return ret;
3981     }
3982     for (i = 0; i < 4; i++) {
3983         env->dr[i] = dbgregs.db[i];
3984     }
3985     env->dr[4] = env->dr[6] = dbgregs.dr6;
3986     env->dr[5] = env->dr[7] = dbgregs.dr7;
3987 
3988     return 0;
3989 }
3990 
3991 static int kvm_put_nested_state(X86CPU *cpu)
3992 {
3993     CPUX86State *env = &cpu->env;
3994     int max_nested_state_len = kvm_max_nested_state_length();
3995 
3996     if (!env->nested_state) {
3997         return 0;
3998     }
3999 
4000     /*
4001      * Copy flags that are affected by reset from env->hflags and env->hflags2.
4002      */
4003     if (env->hflags & HF_GUEST_MASK) {
4004         env->nested_state->flags |= KVM_STATE_NESTED_GUEST_MODE;
4005     } else {
4006         env->nested_state->flags &= ~KVM_STATE_NESTED_GUEST_MODE;
4007     }
4008 
4009     /* Don't set KVM_STATE_NESTED_GIF_SET on VMX as it is illegal */
4010     if (cpu_has_svm(env) && (env->hflags2 & HF2_GIF_MASK)) {
4011         env->nested_state->flags |= KVM_STATE_NESTED_GIF_SET;
4012     } else {
4013         env->nested_state->flags &= ~KVM_STATE_NESTED_GIF_SET;
4014     }
4015 
4016     assert(env->nested_state->size <= max_nested_state_len);
4017     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_NESTED_STATE, env->nested_state);
4018 }
4019 
4020 static int kvm_get_nested_state(X86CPU *cpu)
4021 {
4022     CPUX86State *env = &cpu->env;
4023     int max_nested_state_len = kvm_max_nested_state_length();
4024     int ret;
4025 
4026     if (!env->nested_state) {
4027         return 0;
4028     }
4029 
4030     /*
4031      * It is possible that migration restored a smaller size into
4032      * nested_state->hdr.size than what our kernel support.
4033      * We preserve migration origin nested_state->hdr.size for
4034      * call to KVM_SET_NESTED_STATE but wish that our next call
4035      * to KVM_GET_NESTED_STATE will use max size our kernel support.
4036      */
4037     env->nested_state->size = max_nested_state_len;
4038 
4039     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_NESTED_STATE, env->nested_state);
4040     if (ret < 0) {
4041         return ret;
4042     }
4043 
4044     /*
4045      * Copy flags that are affected by reset to env->hflags and env->hflags2.
4046      */
4047     if (env->nested_state->flags & KVM_STATE_NESTED_GUEST_MODE) {
4048         env->hflags |= HF_GUEST_MASK;
4049     } else {
4050         env->hflags &= ~HF_GUEST_MASK;
4051     }
4052 
4053     /* Keep HF2_GIF_MASK set on !SVM as x86_cpu_pending_interrupt() needs it */
4054     if (cpu_has_svm(env)) {
4055         if (env->nested_state->flags & KVM_STATE_NESTED_GIF_SET) {
4056             env->hflags2 |= HF2_GIF_MASK;
4057         } else {
4058             env->hflags2 &= ~HF2_GIF_MASK;
4059         }
4060     }
4061 
4062     return ret;
4063 }
4064 
4065 int kvm_arch_put_registers(CPUState *cpu, int level)
4066 {
4067     X86CPU *x86_cpu = X86_CPU(cpu);
4068     int ret;
4069 
4070     assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
4071 
4072     /* must be before kvm_put_nested_state so that EFER.SVME is set */
4073     ret = kvm_put_sregs(x86_cpu);
4074     if (ret < 0) {
4075         return ret;
4076     }
4077 
4078     if (level >= KVM_PUT_RESET_STATE) {
4079         ret = kvm_put_nested_state(x86_cpu);
4080         if (ret < 0) {
4081             return ret;
4082         }
4083 
4084         ret = kvm_put_msr_feature_control(x86_cpu);
4085         if (ret < 0) {
4086             return ret;
4087         }
4088     }
4089 
4090     if (level == KVM_PUT_FULL_STATE) {
4091         /* We don't check for kvm_arch_set_tsc_khz() errors here,
4092          * because TSC frequency mismatch shouldn't abort migration,
4093          * unless the user explicitly asked for a more strict TSC
4094          * setting (e.g. using an explicit "tsc-freq" option).
4095          */
4096         kvm_arch_set_tsc_khz(cpu);
4097     }
4098 
4099     ret = kvm_getput_regs(x86_cpu, 1);
4100     if (ret < 0) {
4101         return ret;
4102     }
4103     ret = kvm_put_xsave(x86_cpu);
4104     if (ret < 0) {
4105         return ret;
4106     }
4107     ret = kvm_put_xcrs(x86_cpu);
4108     if (ret < 0) {
4109         return ret;
4110     }
4111     /* must be before kvm_put_msrs */
4112     ret = kvm_inject_mce_oldstyle(x86_cpu);
4113     if (ret < 0) {
4114         return ret;
4115     }
4116     ret = kvm_put_msrs(x86_cpu, level);
4117     if (ret < 0) {
4118         return ret;
4119     }
4120     ret = kvm_put_vcpu_events(x86_cpu, level);
4121     if (ret < 0) {
4122         return ret;
4123     }
4124     if (level >= KVM_PUT_RESET_STATE) {
4125         ret = kvm_put_mp_state(x86_cpu);
4126         if (ret < 0) {
4127             return ret;
4128         }
4129     }
4130 
4131     ret = kvm_put_tscdeadline_msr(x86_cpu);
4132     if (ret < 0) {
4133         return ret;
4134     }
4135     ret = kvm_put_debugregs(x86_cpu);
4136     if (ret < 0) {
4137         return ret;
4138     }
4139     /* must be last */
4140     ret = kvm_guest_debug_workarounds(x86_cpu);
4141     if (ret < 0) {
4142         return ret;
4143     }
4144     return 0;
4145 }
4146 
4147 int kvm_arch_get_registers(CPUState *cs)
4148 {
4149     X86CPU *cpu = X86_CPU(cs);
4150     int ret;
4151 
4152     assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
4153 
4154     ret = kvm_get_vcpu_events(cpu);
4155     if (ret < 0) {
4156         goto out;
4157     }
4158     /*
4159      * KVM_GET_MPSTATE can modify CS and RIP, call it before
4160      * KVM_GET_REGS and KVM_GET_SREGS.
4161      */
4162     ret = kvm_get_mp_state(cpu);
4163     if (ret < 0) {
4164         goto out;
4165     }
4166     ret = kvm_getput_regs(cpu, 0);
4167     if (ret < 0) {
4168         goto out;
4169     }
4170     ret = kvm_get_xsave(cpu);
4171     if (ret < 0) {
4172         goto out;
4173     }
4174     ret = kvm_get_xcrs(cpu);
4175     if (ret < 0) {
4176         goto out;
4177     }
4178     ret = kvm_get_sregs(cpu);
4179     if (ret < 0) {
4180         goto out;
4181     }
4182     ret = kvm_get_msrs(cpu);
4183     if (ret < 0) {
4184         goto out;
4185     }
4186     ret = kvm_get_apic(cpu);
4187     if (ret < 0) {
4188         goto out;
4189     }
4190     ret = kvm_get_debugregs(cpu);
4191     if (ret < 0) {
4192         goto out;
4193     }
4194     ret = kvm_get_nested_state(cpu);
4195     if (ret < 0) {
4196         goto out;
4197     }
4198     ret = 0;
4199  out:
4200     cpu_sync_bndcs_hflags(&cpu->env);
4201     return ret;
4202 }
4203 
4204 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
4205 {
4206     X86CPU *x86_cpu = X86_CPU(cpu);
4207     CPUX86State *env = &x86_cpu->env;
4208     int ret;
4209 
4210     /* Inject NMI */
4211     if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
4212         if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
4213             qemu_mutex_lock_iothread();
4214             cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
4215             qemu_mutex_unlock_iothread();
4216             DPRINTF("injected NMI\n");
4217             ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
4218             if (ret < 0) {
4219                 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
4220                         strerror(-ret));
4221             }
4222         }
4223         if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
4224             qemu_mutex_lock_iothread();
4225             cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
4226             qemu_mutex_unlock_iothread();
4227             DPRINTF("injected SMI\n");
4228             ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
4229             if (ret < 0) {
4230                 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
4231                         strerror(-ret));
4232             }
4233         }
4234     }
4235 
4236     if (!kvm_pic_in_kernel()) {
4237         qemu_mutex_lock_iothread();
4238     }
4239 
4240     /* Force the VCPU out of its inner loop to process any INIT requests
4241      * or (for userspace APIC, but it is cheap to combine the checks here)
4242      * pending TPR access reports.
4243      */
4244     if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
4245         if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
4246             !(env->hflags & HF_SMM_MASK)) {
4247             cpu->exit_request = 1;
4248         }
4249         if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
4250             cpu->exit_request = 1;
4251         }
4252     }
4253 
4254     if (!kvm_pic_in_kernel()) {
4255         /* Try to inject an interrupt if the guest can accept it */
4256         if (run->ready_for_interrupt_injection &&
4257             (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
4258             (env->eflags & IF_MASK)) {
4259             int irq;
4260 
4261             cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
4262             irq = cpu_get_pic_interrupt(env);
4263             if (irq >= 0) {
4264                 struct kvm_interrupt intr;
4265 
4266                 intr.irq = irq;
4267                 DPRINTF("injected interrupt %d\n", irq);
4268                 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
4269                 if (ret < 0) {
4270                     fprintf(stderr,
4271                             "KVM: injection failed, interrupt lost (%s)\n",
4272                             strerror(-ret));
4273                 }
4274             }
4275         }
4276 
4277         /* If we have an interrupt but the guest is not ready to receive an
4278          * interrupt, request an interrupt window exit.  This will
4279          * cause a return to userspace as soon as the guest is ready to
4280          * receive interrupts. */
4281         if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
4282             run->request_interrupt_window = 1;
4283         } else {
4284             run->request_interrupt_window = 0;
4285         }
4286 
4287         DPRINTF("setting tpr\n");
4288         run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
4289 
4290         qemu_mutex_unlock_iothread();
4291     }
4292 }
4293 
4294 static void kvm_rate_limit_on_bus_lock(void)
4295 {
4296     uint64_t delay_ns = ratelimit_calculate_delay(&bus_lock_ratelimit_ctrl, 1);
4297 
4298     if (delay_ns) {
4299         g_usleep(delay_ns / SCALE_US);
4300     }
4301 }
4302 
4303 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
4304 {
4305     X86CPU *x86_cpu = X86_CPU(cpu);
4306     CPUX86State *env = &x86_cpu->env;
4307 
4308     if (run->flags & KVM_RUN_X86_SMM) {
4309         env->hflags |= HF_SMM_MASK;
4310     } else {
4311         env->hflags &= ~HF_SMM_MASK;
4312     }
4313     if (run->if_flag) {
4314         env->eflags |= IF_MASK;
4315     } else {
4316         env->eflags &= ~IF_MASK;
4317     }
4318     if (run->flags & KVM_RUN_X86_BUS_LOCK) {
4319         kvm_rate_limit_on_bus_lock();
4320     }
4321 
4322     /* We need to protect the apic state against concurrent accesses from
4323      * different threads in case the userspace irqchip is used. */
4324     if (!kvm_irqchip_in_kernel()) {
4325         qemu_mutex_lock_iothread();
4326     }
4327     cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
4328     cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
4329     if (!kvm_irqchip_in_kernel()) {
4330         qemu_mutex_unlock_iothread();
4331     }
4332     return cpu_get_mem_attrs(env);
4333 }
4334 
4335 int kvm_arch_process_async_events(CPUState *cs)
4336 {
4337     X86CPU *cpu = X86_CPU(cs);
4338     CPUX86State *env = &cpu->env;
4339 
4340     if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
4341         /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
4342         assert(env->mcg_cap);
4343 
4344         cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
4345 
4346         kvm_cpu_synchronize_state(cs);
4347 
4348         if (env->exception_nr == EXCP08_DBLE) {
4349             /* this means triple fault */
4350             qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
4351             cs->exit_request = 1;
4352             return 0;
4353         }
4354         kvm_queue_exception(env, EXCP12_MCHK, 0, 0);
4355         env->has_error_code = 0;
4356 
4357         cs->halted = 0;
4358         if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
4359             env->mp_state = KVM_MP_STATE_RUNNABLE;
4360         }
4361     }
4362 
4363     if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
4364         !(env->hflags & HF_SMM_MASK)) {
4365         kvm_cpu_synchronize_state(cs);
4366         do_cpu_init(cpu);
4367     }
4368 
4369     if (kvm_irqchip_in_kernel()) {
4370         return 0;
4371     }
4372 
4373     if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
4374         cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
4375         apic_poll_irq(cpu->apic_state);
4376     }
4377     if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
4378          (env->eflags & IF_MASK)) ||
4379         (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
4380         cs->halted = 0;
4381     }
4382     if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
4383         kvm_cpu_synchronize_state(cs);
4384         do_cpu_sipi(cpu);
4385     }
4386     if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
4387         cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
4388         kvm_cpu_synchronize_state(cs);
4389         apic_handle_tpr_access_report(cpu->apic_state, env->eip,
4390                                       env->tpr_access_type);
4391     }
4392 
4393     return cs->halted;
4394 }
4395 
4396 static int kvm_handle_halt(X86CPU *cpu)
4397 {
4398     CPUState *cs = CPU(cpu);
4399     CPUX86State *env = &cpu->env;
4400 
4401     if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
4402           (env->eflags & IF_MASK)) &&
4403         !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
4404         cs->halted = 1;
4405         return EXCP_HLT;
4406     }
4407 
4408     return 0;
4409 }
4410 
4411 static int kvm_handle_tpr_access(X86CPU *cpu)
4412 {
4413     CPUState *cs = CPU(cpu);
4414     struct kvm_run *run = cs->kvm_run;
4415 
4416     apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
4417                                   run->tpr_access.is_write ? TPR_ACCESS_WRITE
4418                                                            : TPR_ACCESS_READ);
4419     return 1;
4420 }
4421 
4422 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
4423 {
4424     static const uint8_t int3 = 0xcc;
4425 
4426     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
4427         cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
4428         return -EINVAL;
4429     }
4430     return 0;
4431 }
4432 
4433 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
4434 {
4435     uint8_t int3;
4436 
4437     if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0)) {
4438         return -EINVAL;
4439     }
4440     if (int3 != 0xcc) {
4441         return 0;
4442     }
4443     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
4444         return -EINVAL;
4445     }
4446     return 0;
4447 }
4448 
4449 static struct {
4450     target_ulong addr;
4451     int len;
4452     int type;
4453 } hw_breakpoint[4];
4454 
4455 static int nb_hw_breakpoint;
4456 
4457 static int find_hw_breakpoint(target_ulong addr, int len, int type)
4458 {
4459     int n;
4460 
4461     for (n = 0; n < nb_hw_breakpoint; n++) {
4462         if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
4463             (hw_breakpoint[n].len == len || len == -1)) {
4464             return n;
4465         }
4466     }
4467     return -1;
4468 }
4469 
4470 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
4471                                   target_ulong len, int type)
4472 {
4473     switch (type) {
4474     case GDB_BREAKPOINT_HW:
4475         len = 1;
4476         break;
4477     case GDB_WATCHPOINT_WRITE:
4478     case GDB_WATCHPOINT_ACCESS:
4479         switch (len) {
4480         case 1:
4481             break;
4482         case 2:
4483         case 4:
4484         case 8:
4485             if (addr & (len - 1)) {
4486                 return -EINVAL;
4487             }
4488             break;
4489         default:
4490             return -EINVAL;
4491         }
4492         break;
4493     default:
4494         return -ENOSYS;
4495     }
4496 
4497     if (nb_hw_breakpoint == 4) {
4498         return -ENOBUFS;
4499     }
4500     if (find_hw_breakpoint(addr, len, type) >= 0) {
4501         return -EEXIST;
4502     }
4503     hw_breakpoint[nb_hw_breakpoint].addr = addr;
4504     hw_breakpoint[nb_hw_breakpoint].len = len;
4505     hw_breakpoint[nb_hw_breakpoint].type = type;
4506     nb_hw_breakpoint++;
4507 
4508     return 0;
4509 }
4510 
4511 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
4512                                   target_ulong len, int type)
4513 {
4514     int n;
4515 
4516     n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
4517     if (n < 0) {
4518         return -ENOENT;
4519     }
4520     nb_hw_breakpoint--;
4521     hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
4522 
4523     return 0;
4524 }
4525 
4526 void kvm_arch_remove_all_hw_breakpoints(void)
4527 {
4528     nb_hw_breakpoint = 0;
4529 }
4530 
4531 static CPUWatchpoint hw_watchpoint;
4532 
4533 static int kvm_handle_debug(X86CPU *cpu,
4534                             struct kvm_debug_exit_arch *arch_info)
4535 {
4536     CPUState *cs = CPU(cpu);
4537     CPUX86State *env = &cpu->env;
4538     int ret = 0;
4539     int n;
4540 
4541     if (arch_info->exception == EXCP01_DB) {
4542         if (arch_info->dr6 & DR6_BS) {
4543             if (cs->singlestep_enabled) {
4544                 ret = EXCP_DEBUG;
4545             }
4546         } else {
4547             for (n = 0; n < 4; n++) {
4548                 if (arch_info->dr6 & (1 << n)) {
4549                     switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
4550                     case 0x0:
4551                         ret = EXCP_DEBUG;
4552                         break;
4553                     case 0x1:
4554                         ret = EXCP_DEBUG;
4555                         cs->watchpoint_hit = &hw_watchpoint;
4556                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
4557                         hw_watchpoint.flags = BP_MEM_WRITE;
4558                         break;
4559                     case 0x3:
4560                         ret = EXCP_DEBUG;
4561                         cs->watchpoint_hit = &hw_watchpoint;
4562                         hw_watchpoint.vaddr = hw_breakpoint[n].addr;
4563                         hw_watchpoint.flags = BP_MEM_ACCESS;
4564                         break;
4565                     }
4566                 }
4567             }
4568         }
4569     } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
4570         ret = EXCP_DEBUG;
4571     }
4572     if (ret == 0) {
4573         cpu_synchronize_state(cs);
4574         assert(env->exception_nr == -1);
4575 
4576         /* pass to guest */
4577         kvm_queue_exception(env, arch_info->exception,
4578                             arch_info->exception == EXCP01_DB,
4579                             arch_info->dr6);
4580         env->has_error_code = 0;
4581     }
4582 
4583     return ret;
4584 }
4585 
4586 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
4587 {
4588     const uint8_t type_code[] = {
4589         [GDB_BREAKPOINT_HW] = 0x0,
4590         [GDB_WATCHPOINT_WRITE] = 0x1,
4591         [GDB_WATCHPOINT_ACCESS] = 0x3
4592     };
4593     const uint8_t len_code[] = {
4594         [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
4595     };
4596     int n;
4597 
4598     if (kvm_sw_breakpoints_active(cpu)) {
4599         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
4600     }
4601     if (nb_hw_breakpoint > 0) {
4602         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
4603         dbg->arch.debugreg[7] = 0x0600;
4604         for (n = 0; n < nb_hw_breakpoint; n++) {
4605             dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
4606             dbg->arch.debugreg[7] |= (2 << (n * 2)) |
4607                 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
4608                 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
4609         }
4610     }
4611 }
4612 
4613 static bool host_supports_vmx(void)
4614 {
4615     uint32_t ecx, unused;
4616 
4617     host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
4618     return ecx & CPUID_EXT_VMX;
4619 }
4620 
4621 #define VMX_INVALID_GUEST_STATE 0x80000021
4622 
4623 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
4624 {
4625     X86CPU *cpu = X86_CPU(cs);
4626     uint64_t code;
4627     int ret;
4628 
4629     switch (run->exit_reason) {
4630     case KVM_EXIT_HLT:
4631         DPRINTF("handle_hlt\n");
4632         qemu_mutex_lock_iothread();
4633         ret = kvm_handle_halt(cpu);
4634         qemu_mutex_unlock_iothread();
4635         break;
4636     case KVM_EXIT_SET_TPR:
4637         ret = 0;
4638         break;
4639     case KVM_EXIT_TPR_ACCESS:
4640         qemu_mutex_lock_iothread();
4641         ret = kvm_handle_tpr_access(cpu);
4642         qemu_mutex_unlock_iothread();
4643         break;
4644     case KVM_EXIT_FAIL_ENTRY:
4645         code = run->fail_entry.hardware_entry_failure_reason;
4646         fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
4647                 code);
4648         if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
4649             fprintf(stderr,
4650                     "\nIf you're running a guest on an Intel machine without "
4651                         "unrestricted mode\n"
4652                     "support, the failure can be most likely due to the guest "
4653                         "entering an invalid\n"
4654                     "state for Intel VT. For example, the guest maybe running "
4655                         "in big real mode\n"
4656                     "which is not supported on less recent Intel processors."
4657                         "\n\n");
4658         }
4659         ret = -1;
4660         break;
4661     case KVM_EXIT_EXCEPTION:
4662         fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
4663                 run->ex.exception, run->ex.error_code);
4664         ret = -1;
4665         break;
4666     case KVM_EXIT_DEBUG:
4667         DPRINTF("kvm_exit_debug\n");
4668         qemu_mutex_lock_iothread();
4669         ret = kvm_handle_debug(cpu, &run->debug.arch);
4670         qemu_mutex_unlock_iothread();
4671         break;
4672     case KVM_EXIT_HYPERV:
4673         ret = kvm_hv_handle_exit(cpu, &run->hyperv);
4674         break;
4675     case KVM_EXIT_IOAPIC_EOI:
4676         ioapic_eoi_broadcast(run->eoi.vector);
4677         ret = 0;
4678         break;
4679     case KVM_EXIT_X86_BUS_LOCK:
4680         /* already handled in kvm_arch_post_run */
4681         ret = 0;
4682         break;
4683     default:
4684         fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
4685         ret = -1;
4686         break;
4687     }
4688 
4689     return ret;
4690 }
4691 
4692 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
4693 {
4694     X86CPU *cpu = X86_CPU(cs);
4695     CPUX86State *env = &cpu->env;
4696 
4697     kvm_cpu_synchronize_state(cs);
4698     return !(env->cr[0] & CR0_PE_MASK) ||
4699            ((env->segs[R_CS].selector  & 3) != 3);
4700 }
4701 
4702 void kvm_arch_init_irq_routing(KVMState *s)
4703 {
4704     /* We know at this point that we're using the in-kernel
4705      * irqchip, so we can use irqfds, and on x86 we know
4706      * we can use msi via irqfd and GSI routing.
4707      */
4708     kvm_msi_via_irqfd_allowed = true;
4709     kvm_gsi_routing_allowed = true;
4710 
4711     if (kvm_irqchip_is_split()) {
4712         int i;
4713 
4714         /* If the ioapic is in QEMU and the lapics are in KVM, reserve
4715            MSI routes for signaling interrupts to the local apics. */
4716         for (i = 0; i < IOAPIC_NUM_PINS; i++) {
4717             if (kvm_irqchip_add_msi_route(s, 0, NULL) < 0) {
4718                 error_report("Could not enable split IRQ mode.");
4719                 exit(1);
4720             }
4721         }
4722     }
4723 }
4724 
4725 int kvm_arch_irqchip_create(KVMState *s)
4726 {
4727     int ret;
4728     if (kvm_kernel_irqchip_split()) {
4729         ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
4730         if (ret) {
4731             error_report("Could not enable split irqchip mode: %s",
4732                          strerror(-ret));
4733             exit(1);
4734         } else {
4735             DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
4736             kvm_split_irqchip = true;
4737             return 1;
4738         }
4739     } else {
4740         return 0;
4741     }
4742 }
4743 
4744 uint64_t kvm_swizzle_msi_ext_dest_id(uint64_t address)
4745 {
4746     CPUX86State *env;
4747     uint64_t ext_id;
4748 
4749     if (!first_cpu) {
4750         return address;
4751     }
4752     env = &X86_CPU(first_cpu)->env;
4753     if (!(env->features[FEAT_KVM] & (1 << KVM_FEATURE_MSI_EXT_DEST_ID))) {
4754         return address;
4755     }
4756 
4757     /*
4758      * If the remappable format bit is set, or the upper bits are
4759      * already set in address_hi, or the low extended bits aren't
4760      * there anyway, do nothing.
4761      */
4762     ext_id = address & (0xff << MSI_ADDR_DEST_IDX_SHIFT);
4763     if (!ext_id || (ext_id & (1 << MSI_ADDR_DEST_IDX_SHIFT)) || (address >> 32)) {
4764         return address;
4765     }
4766 
4767     address &= ~ext_id;
4768     address |= ext_id << 35;
4769     return address;
4770 }
4771 
4772 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
4773                              uint64_t address, uint32_t data, PCIDevice *dev)
4774 {
4775     X86IOMMUState *iommu = x86_iommu_get_default();
4776 
4777     if (iommu) {
4778         X86IOMMUClass *class = X86_IOMMU_DEVICE_GET_CLASS(iommu);
4779 
4780         if (class->int_remap) {
4781             int ret;
4782             MSIMessage src, dst;
4783 
4784             src.address = route->u.msi.address_hi;
4785             src.address <<= VTD_MSI_ADDR_HI_SHIFT;
4786             src.address |= route->u.msi.address_lo;
4787             src.data = route->u.msi.data;
4788 
4789             ret = class->int_remap(iommu, &src, &dst, dev ?     \
4790                                    pci_requester_id(dev) :      \
4791                                    X86_IOMMU_SID_INVALID);
4792             if (ret) {
4793                 trace_kvm_x86_fixup_msi_error(route->gsi);
4794                 return 1;
4795             }
4796 
4797             /*
4798              * Handled untranslated compatibilty format interrupt with
4799              * extended destination ID in the low bits 11-5. */
4800             dst.address = kvm_swizzle_msi_ext_dest_id(dst.address);
4801 
4802             route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
4803             route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
4804             route->u.msi.data = dst.data;
4805             return 0;
4806         }
4807     }
4808 
4809     address = kvm_swizzle_msi_ext_dest_id(address);
4810     route->u.msi.address_hi = address >> VTD_MSI_ADDR_HI_SHIFT;
4811     route->u.msi.address_lo = address & VTD_MSI_ADDR_LO_MASK;
4812     return 0;
4813 }
4814 
4815 typedef struct MSIRouteEntry MSIRouteEntry;
4816 
4817 struct MSIRouteEntry {
4818     PCIDevice *dev;             /* Device pointer */
4819     int vector;                 /* MSI/MSIX vector index */
4820     int virq;                   /* Virtual IRQ index */
4821     QLIST_ENTRY(MSIRouteEntry) list;
4822 };
4823 
4824 /* List of used GSI routes */
4825 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
4826     QLIST_HEAD_INITIALIZER(msi_route_list);
4827 
4828 static void kvm_update_msi_routes_all(void *private, bool global,
4829                                       uint32_t index, uint32_t mask)
4830 {
4831     int cnt = 0, vector;
4832     MSIRouteEntry *entry;
4833     MSIMessage msg;
4834     PCIDevice *dev;
4835 
4836     /* TODO: explicit route update */
4837     QLIST_FOREACH(entry, &msi_route_list, list) {
4838         cnt++;
4839         vector = entry->vector;
4840         dev = entry->dev;
4841         if (msix_enabled(dev) && !msix_is_masked(dev, vector)) {
4842             msg = msix_get_message(dev, vector);
4843         } else if (msi_enabled(dev) && !msi_is_masked(dev, vector)) {
4844             msg = msi_get_message(dev, vector);
4845         } else {
4846             /*
4847              * Either MSI/MSIX is disabled for the device, or the
4848              * specific message was masked out.  Skip this one.
4849              */
4850             continue;
4851         }
4852         kvm_irqchip_update_msi_route(kvm_state, entry->virq, msg, dev);
4853     }
4854     kvm_irqchip_commit_routes(kvm_state);
4855     trace_kvm_x86_update_msi_routes(cnt);
4856 }
4857 
4858 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
4859                                 int vector, PCIDevice *dev)
4860 {
4861     static bool notify_list_inited = false;
4862     MSIRouteEntry *entry;
4863 
4864     if (!dev) {
4865         /* These are (possibly) IOAPIC routes only used for split
4866          * kernel irqchip mode, while what we are housekeeping are
4867          * PCI devices only. */
4868         return 0;
4869     }
4870 
4871     entry = g_new0(MSIRouteEntry, 1);
4872     entry->dev = dev;
4873     entry->vector = vector;
4874     entry->virq = route->gsi;
4875     QLIST_INSERT_HEAD(&msi_route_list, entry, list);
4876 
4877     trace_kvm_x86_add_msi_route(route->gsi);
4878 
4879     if (!notify_list_inited) {
4880         /* For the first time we do add route, add ourselves into
4881          * IOMMU's IEC notify list if needed. */
4882         X86IOMMUState *iommu = x86_iommu_get_default();
4883         if (iommu) {
4884             x86_iommu_iec_register_notifier(iommu,
4885                                             kvm_update_msi_routes_all,
4886                                             NULL);
4887         }
4888         notify_list_inited = true;
4889     }
4890     return 0;
4891 }
4892 
4893 int kvm_arch_release_virq_post(int virq)
4894 {
4895     MSIRouteEntry *entry, *next;
4896     QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
4897         if (entry->virq == virq) {
4898             trace_kvm_x86_remove_msi_route(virq);
4899             QLIST_REMOVE(entry, list);
4900             g_free(entry);
4901             break;
4902         }
4903     }
4904     return 0;
4905 }
4906 
4907 int kvm_arch_msi_data_to_gsi(uint32_t data)
4908 {
4909     abort();
4910 }
4911 
4912 bool kvm_has_waitpkg(void)
4913 {
4914     return has_msr_umwait;
4915 }
4916 
4917 bool kvm_arch_cpu_check_are_resettable(void)
4918 {
4919     return !sev_es_enabled();
4920 }
4921