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