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