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