KVM: add support for AMD nested live migration
[qemu/kevin.git] / target / i386 / kvm.c
blob2b6b7443d2730f0e61f80389ce30cef854bab827
1 /*
2 * QEMU KVM support
4 * Copyright (C) 2006-2008 Qumranet Technologies
5 * Copyright IBM, Corp. 2008
7 * Authors:
8 * Anthony Liguori <aliguori@us.ibm.com>
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.
15 #include "qemu/osdep.h"
16 #include "qapi/error.h"
17 #include <sys/ioctl.h>
18 #include <sys/utsname.h>
20 #include <linux/kvm.h>
21 #include "standard-headers/asm-x86/kvm_para.h"
23 #include "cpu.h"
24 #include "sysemu/sysemu.h"
25 #include "sysemu/hw_accel.h"
26 #include "sysemu/kvm_int.h"
27 #include "sysemu/runstate.h"
28 #include "kvm_i386.h"
29 #include "hyperv.h"
30 #include "hyperv-proto.h"
32 #include "exec/gdbstub.h"
33 #include "qemu/host-utils.h"
34 #include "qemu/main-loop.h"
35 #include "qemu/config-file.h"
36 #include "qemu/error-report.h"
37 #include "hw/i386/x86.h"
38 #include "hw/i386/apic.h"
39 #include "hw/i386/apic_internal.h"
40 #include "hw/i386/apic-msidef.h"
41 #include "hw/i386/intel_iommu.h"
42 #include "hw/i386/x86-iommu.h"
43 #include "hw/i386/e820_memory_layout.h"
45 #include "hw/pci/pci.h"
46 #include "hw/pci/msi.h"
47 #include "hw/pci/msix.h"
48 #include "migration/blocker.h"
49 #include "exec/memattrs.h"
50 #include "trace.h"
52 //#define DEBUG_KVM
54 #ifdef DEBUG_KVM
55 #define DPRINTF(fmt, ...) \
56 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
57 #else
58 #define DPRINTF(fmt, ...) \
59 do { } while (0)
60 #endif
62 /* From arch/x86/kvm/lapic.h */
63 #define KVM_APIC_BUS_CYCLE_NS 1
64 #define KVM_APIC_BUS_FREQUENCY (1000000000ULL / KVM_APIC_BUS_CYCLE_NS)
66 #define MSR_KVM_WALL_CLOCK 0x11
67 #define MSR_KVM_SYSTEM_TIME 0x12
69 /* A 4096-byte buffer can hold the 8-byte kvm_msrs header, plus
70 * 255 kvm_msr_entry structs */
71 #define MSR_BUF_SIZE 4096
73 static void kvm_init_msrs(X86CPU *cpu);
75 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
76 KVM_CAP_INFO(SET_TSS_ADDR),
77 KVM_CAP_INFO(EXT_CPUID),
78 KVM_CAP_INFO(MP_STATE),
79 KVM_CAP_LAST_INFO
82 static bool has_msr_star;
83 static bool has_msr_hsave_pa;
84 static bool has_msr_tsc_aux;
85 static bool has_msr_tsc_adjust;
86 static bool has_msr_tsc_deadline;
87 static bool has_msr_feature_control;
88 static bool has_msr_misc_enable;
89 static bool has_msr_smbase;
90 static bool has_msr_bndcfgs;
91 static int lm_capable_kernel;
92 static bool has_msr_hv_hypercall;
93 static bool has_msr_hv_crash;
94 static bool has_msr_hv_reset;
95 static bool has_msr_hv_vpindex;
96 static bool hv_vpindex_settable;
97 static bool has_msr_hv_runtime;
98 static bool has_msr_hv_synic;
99 static bool has_msr_hv_stimer;
100 static bool has_msr_hv_frequencies;
101 static bool has_msr_hv_reenlightenment;
102 static bool has_msr_xss;
103 static bool has_msr_umwait;
104 static bool has_msr_spec_ctrl;
105 static bool has_msr_tsx_ctrl;
106 static bool has_msr_virt_ssbd;
107 static bool has_msr_smi_count;
108 static bool has_msr_arch_capabs;
109 static bool has_msr_core_capabs;
110 static bool has_msr_vmx_vmfunc;
111 static bool has_msr_ucode_rev;
112 static bool has_msr_vmx_procbased_ctls2;
113 static bool has_msr_perf_capabs;
115 static uint32_t has_architectural_pmu_version;
116 static uint32_t num_architectural_pmu_gp_counters;
117 static uint32_t num_architectural_pmu_fixed_counters;
119 static int has_xsave;
120 static int has_xcrs;
121 static int has_pit_state2;
122 static int has_exception_payload;
124 static bool has_msr_mcg_ext_ctl;
126 static struct kvm_cpuid2 *cpuid_cache;
127 static struct kvm_msr_list *kvm_feature_msrs;
129 int kvm_has_pit_state2(void)
131 return has_pit_state2;
134 bool kvm_has_smm(void)
136 return kvm_check_extension(kvm_state, KVM_CAP_X86_SMM);
139 bool kvm_has_adjust_clock_stable(void)
141 int ret = kvm_check_extension(kvm_state, KVM_CAP_ADJUST_CLOCK);
143 return (ret == KVM_CLOCK_TSC_STABLE);
146 bool kvm_has_exception_payload(void)
148 return has_exception_payload;
151 bool kvm_allows_irq0_override(void)
153 return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
156 static bool kvm_x2apic_api_set_flags(uint64_t flags)
158 KVMState *s = KVM_STATE(current_accel());
160 return !kvm_vm_enable_cap(s, KVM_CAP_X2APIC_API, 0, flags);
163 #define MEMORIZE(fn, _result) \
164 ({ \
165 static bool _memorized; \
167 if (_memorized) { \
168 return _result; \
170 _memorized = true; \
171 _result = fn; \
174 static bool has_x2apic_api;
176 bool kvm_has_x2apic_api(void)
178 return has_x2apic_api;
181 bool kvm_enable_x2apic(void)
183 return MEMORIZE(
184 kvm_x2apic_api_set_flags(KVM_X2APIC_API_USE_32BIT_IDS |
185 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK),
186 has_x2apic_api);
189 bool kvm_hv_vpindex_settable(void)
191 return hv_vpindex_settable;
194 static int kvm_get_tsc(CPUState *cs)
196 X86CPU *cpu = X86_CPU(cs);
197 CPUX86State *env = &cpu->env;
198 struct {
199 struct kvm_msrs info;
200 struct kvm_msr_entry entries[1];
201 } msr_data = {};
202 int ret;
204 if (env->tsc_valid) {
205 return 0;
208 memset(&msr_data, 0, sizeof(msr_data));
209 msr_data.info.nmsrs = 1;
210 msr_data.entries[0].index = MSR_IA32_TSC;
211 env->tsc_valid = !runstate_is_running();
213 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
214 if (ret < 0) {
215 return ret;
218 assert(ret == 1);
219 env->tsc = msr_data.entries[0].data;
220 return 0;
223 static inline void do_kvm_synchronize_tsc(CPUState *cpu, run_on_cpu_data arg)
225 kvm_get_tsc(cpu);
228 void kvm_synchronize_all_tsc(void)
230 CPUState *cpu;
232 if (kvm_enabled()) {
233 CPU_FOREACH(cpu) {
234 run_on_cpu(cpu, do_kvm_synchronize_tsc, RUN_ON_CPU_NULL);
239 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
241 struct kvm_cpuid2 *cpuid;
242 int r, size;
244 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
245 cpuid = g_malloc0(size);
246 cpuid->nent = max;
247 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
248 if (r == 0 && cpuid->nent >= max) {
249 r = -E2BIG;
251 if (r < 0) {
252 if (r == -E2BIG) {
253 g_free(cpuid);
254 return NULL;
255 } else {
256 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
257 strerror(-r));
258 exit(1);
261 return cpuid;
264 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
265 * for all entries.
267 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
269 struct kvm_cpuid2 *cpuid;
270 int max = 1;
272 if (cpuid_cache != NULL) {
273 return cpuid_cache;
275 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
276 max *= 2;
278 cpuid_cache = cpuid;
279 return cpuid;
282 static const struct kvm_para_features {
283 int cap;
284 int feature;
285 } para_features[] = {
286 { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
287 { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
288 { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
289 { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
292 static int get_para_features(KVMState *s)
294 int i, features = 0;
296 for (i = 0; i < ARRAY_SIZE(para_features); i++) {
297 if (kvm_check_extension(s, para_features[i].cap)) {
298 features |= (1 << para_features[i].feature);
302 return features;
305 static bool host_tsx_blacklisted(void)
307 int family, model, stepping;\
308 char vendor[CPUID_VENDOR_SZ + 1];
310 host_vendor_fms(vendor, &family, &model, &stepping);
312 /* Check if we are running on a Haswell host known to have broken TSX */
313 return !strcmp(vendor, CPUID_VENDOR_INTEL) &&
314 (family == 6) &&
315 ((model == 63 && stepping < 4) ||
316 model == 60 || model == 69 || model == 70);
319 /* Returns the value for a specific register on the cpuid entry
321 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
323 uint32_t ret = 0;
324 switch (reg) {
325 case R_EAX:
326 ret = entry->eax;
327 break;
328 case R_EBX:
329 ret = entry->ebx;
330 break;
331 case R_ECX:
332 ret = entry->ecx;
333 break;
334 case R_EDX:
335 ret = entry->edx;
336 break;
338 return ret;
341 /* Find matching entry for function/index on kvm_cpuid2 struct
343 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
344 uint32_t function,
345 uint32_t index)
347 int i;
348 for (i = 0; i < cpuid->nent; ++i) {
349 if (cpuid->entries[i].function == function &&
350 cpuid->entries[i].index == index) {
351 return &cpuid->entries[i];
354 /* not found: */
355 return NULL;
358 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
359 uint32_t index, int reg)
361 struct kvm_cpuid2 *cpuid;
362 uint32_t ret = 0;
363 uint32_t cpuid_1_edx;
364 bool found = false;
366 cpuid = get_supported_cpuid(s);
368 struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
369 if (entry) {
370 found = true;
371 ret = cpuid_entry_get_reg(entry, reg);
374 /* Fixups for the data returned by KVM, below */
376 if (function == 1 && reg == R_EDX) {
377 /* KVM before 2.6.30 misreports the following features */
378 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
379 } else if (function == 1 && reg == R_ECX) {
380 /* We can set the hypervisor flag, even if KVM does not return it on
381 * GET_SUPPORTED_CPUID
383 ret |= CPUID_EXT_HYPERVISOR;
384 /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
385 * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
386 * and the irqchip is in the kernel.
388 if (kvm_irqchip_in_kernel() &&
389 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
390 ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
393 /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
394 * without the in-kernel irqchip
396 if (!kvm_irqchip_in_kernel()) {
397 ret &= ~CPUID_EXT_X2APIC;
400 if (enable_cpu_pm) {
401 int disable_exits = kvm_check_extension(s,
402 KVM_CAP_X86_DISABLE_EXITS);
404 if (disable_exits & KVM_X86_DISABLE_EXITS_MWAIT) {
405 ret |= CPUID_EXT_MONITOR;
408 } else if (function == 6 && reg == R_EAX) {
409 ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
410 } else if (function == 7 && index == 0 && reg == R_EBX) {
411 if (host_tsx_blacklisted()) {
412 ret &= ~(CPUID_7_0_EBX_RTM | CPUID_7_0_EBX_HLE);
414 } else if (function == 7 && index == 0 && reg == R_ECX) {
415 if (enable_cpu_pm) {
416 ret |= CPUID_7_0_ECX_WAITPKG;
417 } else {
418 ret &= ~CPUID_7_0_ECX_WAITPKG;
420 } else if (function == 7 && index == 0 && reg == R_EDX) {
422 * Linux v4.17-v4.20 incorrectly return ARCH_CAPABILITIES on SVM hosts.
423 * We can detect the bug by checking if MSR_IA32_ARCH_CAPABILITIES is
424 * returned by KVM_GET_MSR_INDEX_LIST.
426 if (!has_msr_arch_capabs) {
427 ret &= ~CPUID_7_0_EDX_ARCH_CAPABILITIES;
429 } else if (function == 0x80000001 && reg == R_ECX) {
431 * It's safe to enable TOPOEXT even if it's not returned by
432 * GET_SUPPORTED_CPUID. Unconditionally enabling TOPOEXT here allows
433 * us to keep CPU models including TOPOEXT runnable on older kernels.
435 ret |= CPUID_EXT3_TOPOEXT;
436 } else if (function == 0x80000001 && reg == R_EDX) {
437 /* On Intel, kvm returns cpuid according to the Intel spec,
438 * so add missing bits according to the AMD spec:
440 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
441 ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
442 } else if (function == KVM_CPUID_FEATURES && reg == R_EAX) {
443 /* kvm_pv_unhalt is reported by GET_SUPPORTED_CPUID, but it can't
444 * be enabled without the in-kernel irqchip
446 if (!kvm_irqchip_in_kernel()) {
447 ret &= ~(1U << KVM_FEATURE_PV_UNHALT);
449 } else if (function == KVM_CPUID_FEATURES && reg == R_EDX) {
450 ret |= 1U << KVM_HINTS_REALTIME;
451 found = 1;
454 /* fallback for older kernels */
455 if ((function == KVM_CPUID_FEATURES) && !found) {
456 ret = get_para_features(s);
459 return ret;
462 uint64_t kvm_arch_get_supported_msr_feature(KVMState *s, uint32_t index)
464 struct {
465 struct kvm_msrs info;
466 struct kvm_msr_entry entries[1];
467 } msr_data = {};
468 uint64_t value;
469 uint32_t ret, can_be_one, must_be_one;
471 if (kvm_feature_msrs == NULL) { /* Host doesn't support feature MSRs */
472 return 0;
475 /* Check if requested MSR is supported feature MSR */
476 int i;
477 for (i = 0; i < kvm_feature_msrs->nmsrs; i++)
478 if (kvm_feature_msrs->indices[i] == index) {
479 break;
481 if (i == kvm_feature_msrs->nmsrs) {
482 return 0; /* if the feature MSR is not supported, simply return 0 */
485 msr_data.info.nmsrs = 1;
486 msr_data.entries[0].index = index;
488 ret = kvm_ioctl(s, KVM_GET_MSRS, &msr_data);
489 if (ret != 1) {
490 error_report("KVM get MSR (index=0x%x) feature failed, %s",
491 index, strerror(-ret));
492 exit(1);
495 value = msr_data.entries[0].data;
496 switch (index) {
497 case MSR_IA32_VMX_PROCBASED_CTLS2:
498 if (!has_msr_vmx_procbased_ctls2) {
499 /* KVM forgot to add these bits for some time, do this ourselves. */
500 if (kvm_arch_get_supported_cpuid(s, 0xD, 1, R_ECX) &
501 CPUID_XSAVE_XSAVES) {
502 value |= (uint64_t)VMX_SECONDARY_EXEC_XSAVES << 32;
504 if (kvm_arch_get_supported_cpuid(s, 1, 0, R_ECX) &
505 CPUID_EXT_RDRAND) {
506 value |= (uint64_t)VMX_SECONDARY_EXEC_RDRAND_EXITING << 32;
508 if (kvm_arch_get_supported_cpuid(s, 7, 0, R_EBX) &
509 CPUID_7_0_EBX_INVPCID) {
510 value |= (uint64_t)VMX_SECONDARY_EXEC_ENABLE_INVPCID << 32;
512 if (kvm_arch_get_supported_cpuid(s, 7, 0, R_EBX) &
513 CPUID_7_0_EBX_RDSEED) {
514 value |= (uint64_t)VMX_SECONDARY_EXEC_RDSEED_EXITING << 32;
516 if (kvm_arch_get_supported_cpuid(s, 0x80000001, 0, R_EDX) &
517 CPUID_EXT2_RDTSCP) {
518 value |= (uint64_t)VMX_SECONDARY_EXEC_RDTSCP << 32;
521 /* fall through */
522 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
523 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
524 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
525 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
527 * Return true for bits that can be one, but do not have to be one.
528 * The SDM tells us which bits could have a "must be one" setting,
529 * so we can do the opposite transformation in make_vmx_msr_value.
531 must_be_one = (uint32_t)value;
532 can_be_one = (uint32_t)(value >> 32);
533 return can_be_one & ~must_be_one;
535 default:
536 return value;
540 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
541 int *max_banks)
543 int r;
545 r = kvm_check_extension(s, KVM_CAP_MCE);
546 if (r > 0) {
547 *max_banks = r;
548 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
550 return -ENOSYS;
553 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
555 CPUState *cs = CPU(cpu);
556 CPUX86State *env = &cpu->env;
557 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
558 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
559 uint64_t mcg_status = MCG_STATUS_MCIP;
560 int flags = 0;
562 if (code == BUS_MCEERR_AR) {
563 status |= MCI_STATUS_AR | 0x134;
564 mcg_status |= MCG_STATUS_EIPV;
565 } else {
566 status |= 0xc0;
567 mcg_status |= MCG_STATUS_RIPV;
570 flags = cpu_x86_support_mca_broadcast(env) ? MCE_INJECT_BROADCAST : 0;
571 /* We need to read back the value of MSR_EXT_MCG_CTL that was set by the
572 * guest kernel back into env->mcg_ext_ctl.
574 cpu_synchronize_state(cs);
575 if (env->mcg_ext_ctl & MCG_EXT_CTL_LMCE_EN) {
576 mcg_status |= MCG_STATUS_LMCE;
577 flags = 0;
580 cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
581 (MCM_ADDR_PHYS << 6) | 0xc, flags);
584 static void hardware_memory_error(void *host_addr)
586 error_report("QEMU got Hardware memory error at addr %p", host_addr);
587 exit(1);
590 void kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
592 X86CPU *cpu = X86_CPU(c);
593 CPUX86State *env = &cpu->env;
594 ram_addr_t ram_addr;
595 hwaddr paddr;
597 /* If we get an action required MCE, it has been injected by KVM
598 * while the VM was running. An action optional MCE instead should
599 * be coming from the main thread, which qemu_init_sigbus identifies
600 * as the "early kill" thread.
602 assert(code == BUS_MCEERR_AR || code == BUS_MCEERR_AO);
604 if ((env->mcg_cap & MCG_SER_P) && addr) {
605 ram_addr = qemu_ram_addr_from_host(addr);
606 if (ram_addr != RAM_ADDR_INVALID &&
607 kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
608 kvm_hwpoison_page_add(ram_addr);
609 kvm_mce_inject(cpu, paddr, code);
612 * Use different logging severity based on error type.
613 * If there is additional MCE reporting on the hypervisor, QEMU VA
614 * could be another source to identify the PA and MCE details.
616 if (code == BUS_MCEERR_AR) {
617 error_report("Guest MCE Memory Error at QEMU addr %p and "
618 "GUEST addr 0x%" HWADDR_PRIx " of type %s injected",
619 addr, paddr, "BUS_MCEERR_AR");
620 } else {
621 warn_report("Guest MCE Memory Error at QEMU addr %p and "
622 "GUEST addr 0x%" HWADDR_PRIx " of type %s injected",
623 addr, paddr, "BUS_MCEERR_AO");
626 return;
629 if (code == BUS_MCEERR_AO) {
630 warn_report("Hardware memory error at addr %p of type %s "
631 "for memory used by QEMU itself instead of guest system!",
632 addr, "BUS_MCEERR_AO");
636 if (code == BUS_MCEERR_AR) {
637 hardware_memory_error(addr);
640 /* Hope we are lucky for AO MCE */
643 static void kvm_reset_exception(CPUX86State *env)
645 env->exception_nr = -1;
646 env->exception_pending = 0;
647 env->exception_injected = 0;
648 env->exception_has_payload = false;
649 env->exception_payload = 0;
652 static void kvm_queue_exception(CPUX86State *env,
653 int32_t exception_nr,
654 uint8_t exception_has_payload,
655 uint64_t exception_payload)
657 assert(env->exception_nr == -1);
658 assert(!env->exception_pending);
659 assert(!env->exception_injected);
660 assert(!env->exception_has_payload);
662 env->exception_nr = exception_nr;
664 if (has_exception_payload) {
665 env->exception_pending = 1;
667 env->exception_has_payload = exception_has_payload;
668 env->exception_payload = exception_payload;
669 } else {
670 env->exception_injected = 1;
672 if (exception_nr == EXCP01_DB) {
673 assert(exception_has_payload);
674 env->dr[6] = exception_payload;
675 } else if (exception_nr == EXCP0E_PAGE) {
676 assert(exception_has_payload);
677 env->cr[2] = exception_payload;
678 } else {
679 assert(!exception_has_payload);
684 static int kvm_inject_mce_oldstyle(X86CPU *cpu)
686 CPUX86State *env = &cpu->env;
688 if (!kvm_has_vcpu_events() && env->exception_nr == EXCP12_MCHK) {
689 unsigned int bank, bank_num = env->mcg_cap & 0xff;
690 struct kvm_x86_mce mce;
692 kvm_reset_exception(env);
695 * There must be at least one bank in use if an MCE is pending.
696 * Find it and use its values for the event injection.
698 for (bank = 0; bank < bank_num; bank++) {
699 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
700 break;
703 assert(bank < bank_num);
705 mce.bank = bank;
706 mce.status = env->mce_banks[bank * 4 + 1];
707 mce.mcg_status = env->mcg_status;
708 mce.addr = env->mce_banks[bank * 4 + 2];
709 mce.misc = env->mce_banks[bank * 4 + 3];
711 return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
713 return 0;
716 static void cpu_update_state(void *opaque, int running, RunState state)
718 CPUX86State *env = opaque;
720 if (running) {
721 env->tsc_valid = false;
725 unsigned long kvm_arch_vcpu_id(CPUState *cs)
727 X86CPU *cpu = X86_CPU(cs);
728 return cpu->apic_id;
731 #ifndef KVM_CPUID_SIGNATURE_NEXT
732 #define KVM_CPUID_SIGNATURE_NEXT 0x40000100
733 #endif
735 static bool hyperv_enabled(X86CPU *cpu)
737 CPUState *cs = CPU(cpu);
738 return kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0 &&
739 ((cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY) ||
740 cpu->hyperv_features || cpu->hyperv_passthrough);
744 * Check whether target_freq is within conservative
745 * ntp correctable bounds (250ppm) of freq
747 static inline bool freq_within_bounds(int freq, int target_freq)
749 int max_freq = freq + (freq * 250 / 1000000);
750 int min_freq = freq - (freq * 250 / 1000000);
752 if (target_freq >= min_freq && target_freq <= max_freq) {
753 return true;
756 return false;
759 static int kvm_arch_set_tsc_khz(CPUState *cs)
761 X86CPU *cpu = X86_CPU(cs);
762 CPUX86State *env = &cpu->env;
763 int r, cur_freq;
764 bool set_ioctl = false;
766 if (!env->tsc_khz) {
767 return 0;
770 cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
771 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) : -ENOTSUP;
774 * If TSC scaling is supported, attempt to set TSC frequency.
776 if (kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL)) {
777 set_ioctl = true;
781 * If desired TSC frequency is within bounds of NTP correction,
782 * attempt to set TSC frequency.
784 if (cur_freq != -ENOTSUP && freq_within_bounds(cur_freq, env->tsc_khz)) {
785 set_ioctl = true;
788 r = set_ioctl ?
789 kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) :
790 -ENOTSUP;
792 if (r < 0) {
793 /* When KVM_SET_TSC_KHZ fails, it's an error only if the current
794 * TSC frequency doesn't match the one we want.
796 cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
797 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
798 -ENOTSUP;
799 if (cur_freq <= 0 || cur_freq != env->tsc_khz) {
800 warn_report("TSC frequency mismatch between "
801 "VM (%" PRId64 " kHz) and host (%d kHz), "
802 "and TSC scaling unavailable",
803 env->tsc_khz, cur_freq);
804 return r;
808 return 0;
811 static bool tsc_is_stable_and_known(CPUX86State *env)
813 if (!env->tsc_khz) {
814 return false;
816 return (env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC)
817 || env->user_tsc_khz;
820 static struct {
821 const char *desc;
822 struct {
823 uint32_t fw;
824 uint32_t bits;
825 } flags[2];
826 uint64_t dependencies;
827 } kvm_hyperv_properties[] = {
828 [HYPERV_FEAT_RELAXED] = {
829 .desc = "relaxed timing (hv-relaxed)",
830 .flags = {
831 {.fw = FEAT_HYPERV_EAX,
832 .bits = HV_HYPERCALL_AVAILABLE},
833 {.fw = FEAT_HV_RECOMM_EAX,
834 .bits = HV_RELAXED_TIMING_RECOMMENDED}
837 [HYPERV_FEAT_VAPIC] = {
838 .desc = "virtual APIC (hv-vapic)",
839 .flags = {
840 {.fw = FEAT_HYPERV_EAX,
841 .bits = HV_HYPERCALL_AVAILABLE | HV_APIC_ACCESS_AVAILABLE},
842 {.fw = FEAT_HV_RECOMM_EAX,
843 .bits = HV_APIC_ACCESS_RECOMMENDED}
846 [HYPERV_FEAT_TIME] = {
847 .desc = "clocksources (hv-time)",
848 .flags = {
849 {.fw = FEAT_HYPERV_EAX,
850 .bits = HV_HYPERCALL_AVAILABLE | HV_TIME_REF_COUNT_AVAILABLE |
851 HV_REFERENCE_TSC_AVAILABLE}
854 [HYPERV_FEAT_CRASH] = {
855 .desc = "crash MSRs (hv-crash)",
856 .flags = {
857 {.fw = FEAT_HYPERV_EDX,
858 .bits = HV_GUEST_CRASH_MSR_AVAILABLE}
861 [HYPERV_FEAT_RESET] = {
862 .desc = "reset MSR (hv-reset)",
863 .flags = {
864 {.fw = FEAT_HYPERV_EAX,
865 .bits = HV_RESET_AVAILABLE}
868 [HYPERV_FEAT_VPINDEX] = {
869 .desc = "VP_INDEX MSR (hv-vpindex)",
870 .flags = {
871 {.fw = FEAT_HYPERV_EAX,
872 .bits = HV_VP_INDEX_AVAILABLE}
875 [HYPERV_FEAT_RUNTIME] = {
876 .desc = "VP_RUNTIME MSR (hv-runtime)",
877 .flags = {
878 {.fw = FEAT_HYPERV_EAX,
879 .bits = HV_VP_RUNTIME_AVAILABLE}
882 [HYPERV_FEAT_SYNIC] = {
883 .desc = "synthetic interrupt controller (hv-synic)",
884 .flags = {
885 {.fw = FEAT_HYPERV_EAX,
886 .bits = HV_SYNIC_AVAILABLE}
889 [HYPERV_FEAT_STIMER] = {
890 .desc = "synthetic timers (hv-stimer)",
891 .flags = {
892 {.fw = FEAT_HYPERV_EAX,
893 .bits = HV_SYNTIMERS_AVAILABLE}
895 .dependencies = BIT(HYPERV_FEAT_SYNIC) | BIT(HYPERV_FEAT_TIME)
897 [HYPERV_FEAT_FREQUENCIES] = {
898 .desc = "frequency MSRs (hv-frequencies)",
899 .flags = {
900 {.fw = FEAT_HYPERV_EAX,
901 .bits = HV_ACCESS_FREQUENCY_MSRS},
902 {.fw = FEAT_HYPERV_EDX,
903 .bits = HV_FREQUENCY_MSRS_AVAILABLE}
906 [HYPERV_FEAT_REENLIGHTENMENT] = {
907 .desc = "reenlightenment MSRs (hv-reenlightenment)",
908 .flags = {
909 {.fw = FEAT_HYPERV_EAX,
910 .bits = HV_ACCESS_REENLIGHTENMENTS_CONTROL}
913 [HYPERV_FEAT_TLBFLUSH] = {
914 .desc = "paravirtualized TLB flush (hv-tlbflush)",
915 .flags = {
916 {.fw = FEAT_HV_RECOMM_EAX,
917 .bits = HV_REMOTE_TLB_FLUSH_RECOMMENDED |
918 HV_EX_PROCESSOR_MASKS_RECOMMENDED}
920 .dependencies = BIT(HYPERV_FEAT_VPINDEX)
922 [HYPERV_FEAT_EVMCS] = {
923 .desc = "enlightened VMCS (hv-evmcs)",
924 .flags = {
925 {.fw = FEAT_HV_RECOMM_EAX,
926 .bits = HV_ENLIGHTENED_VMCS_RECOMMENDED}
928 .dependencies = BIT(HYPERV_FEAT_VAPIC)
930 [HYPERV_FEAT_IPI] = {
931 .desc = "paravirtualized IPI (hv-ipi)",
932 .flags = {
933 {.fw = FEAT_HV_RECOMM_EAX,
934 .bits = HV_CLUSTER_IPI_RECOMMENDED |
935 HV_EX_PROCESSOR_MASKS_RECOMMENDED}
937 .dependencies = BIT(HYPERV_FEAT_VPINDEX)
939 [HYPERV_FEAT_STIMER_DIRECT] = {
940 .desc = "direct mode synthetic timers (hv-stimer-direct)",
941 .flags = {
942 {.fw = FEAT_HYPERV_EDX,
943 .bits = HV_STIMER_DIRECT_MODE_AVAILABLE}
945 .dependencies = BIT(HYPERV_FEAT_STIMER)
949 static struct kvm_cpuid2 *try_get_hv_cpuid(CPUState *cs, int max)
951 struct kvm_cpuid2 *cpuid;
952 int r, size;
954 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
955 cpuid = g_malloc0(size);
956 cpuid->nent = max;
958 r = kvm_vcpu_ioctl(cs, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
959 if (r == 0 && cpuid->nent >= max) {
960 r = -E2BIG;
962 if (r < 0) {
963 if (r == -E2BIG) {
964 g_free(cpuid);
965 return NULL;
966 } else {
967 fprintf(stderr, "KVM_GET_SUPPORTED_HV_CPUID failed: %s\n",
968 strerror(-r));
969 exit(1);
972 return cpuid;
976 * Run KVM_GET_SUPPORTED_HV_CPUID ioctl(), allocating a buffer large enough
977 * for all entries.
979 static struct kvm_cpuid2 *get_supported_hv_cpuid(CPUState *cs)
981 struct kvm_cpuid2 *cpuid;
982 int max = 7; /* 0x40000000..0x40000005, 0x4000000A */
985 * When the buffer is too small, KVM_GET_SUPPORTED_HV_CPUID fails with
986 * -E2BIG, however, it doesn't report back the right size. Keep increasing
987 * it and re-trying until we succeed.
989 while ((cpuid = try_get_hv_cpuid(cs, max)) == NULL) {
990 max++;
992 return cpuid;
996 * When KVM_GET_SUPPORTED_HV_CPUID is not supported we fill CPUID feature
997 * leaves from KVM_CAP_HYPERV* and present MSRs data.
999 static struct kvm_cpuid2 *get_supported_hv_cpuid_legacy(CPUState *cs)
1001 X86CPU *cpu = X86_CPU(cs);
1002 struct kvm_cpuid2 *cpuid;
1003 struct kvm_cpuid_entry2 *entry_feat, *entry_recomm;
1005 /* HV_CPUID_FEATURES, HV_CPUID_ENLIGHTMENT_INFO */
1006 cpuid = g_malloc0(sizeof(*cpuid) + 2 * sizeof(*cpuid->entries));
1007 cpuid->nent = 2;
1009 /* HV_CPUID_VENDOR_AND_MAX_FUNCTIONS */
1010 entry_feat = &cpuid->entries[0];
1011 entry_feat->function = HV_CPUID_FEATURES;
1013 entry_recomm = &cpuid->entries[1];
1014 entry_recomm->function = HV_CPUID_ENLIGHTMENT_INFO;
1015 entry_recomm->ebx = cpu->hyperv_spinlock_attempts;
1017 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0) {
1018 entry_feat->eax |= HV_HYPERCALL_AVAILABLE;
1019 entry_feat->eax |= HV_APIC_ACCESS_AVAILABLE;
1020 entry_feat->edx |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
1021 entry_recomm->eax |= HV_RELAXED_TIMING_RECOMMENDED;
1022 entry_recomm->eax |= HV_APIC_ACCESS_RECOMMENDED;
1025 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) > 0) {
1026 entry_feat->eax |= HV_TIME_REF_COUNT_AVAILABLE;
1027 entry_feat->eax |= HV_REFERENCE_TSC_AVAILABLE;
1030 if (has_msr_hv_frequencies) {
1031 entry_feat->eax |= HV_ACCESS_FREQUENCY_MSRS;
1032 entry_feat->edx |= HV_FREQUENCY_MSRS_AVAILABLE;
1035 if (has_msr_hv_crash) {
1036 entry_feat->edx |= HV_GUEST_CRASH_MSR_AVAILABLE;
1039 if (has_msr_hv_reenlightenment) {
1040 entry_feat->eax |= HV_ACCESS_REENLIGHTENMENTS_CONTROL;
1043 if (has_msr_hv_reset) {
1044 entry_feat->eax |= HV_RESET_AVAILABLE;
1047 if (has_msr_hv_vpindex) {
1048 entry_feat->eax |= HV_VP_INDEX_AVAILABLE;
1051 if (has_msr_hv_runtime) {
1052 entry_feat->eax |= HV_VP_RUNTIME_AVAILABLE;
1055 if (has_msr_hv_synic) {
1056 unsigned int cap = cpu->hyperv_synic_kvm_only ?
1057 KVM_CAP_HYPERV_SYNIC : KVM_CAP_HYPERV_SYNIC2;
1059 if (kvm_check_extension(cs->kvm_state, cap) > 0) {
1060 entry_feat->eax |= HV_SYNIC_AVAILABLE;
1064 if (has_msr_hv_stimer) {
1065 entry_feat->eax |= HV_SYNTIMERS_AVAILABLE;
1068 if (kvm_check_extension(cs->kvm_state,
1069 KVM_CAP_HYPERV_TLBFLUSH) > 0) {
1070 entry_recomm->eax |= HV_REMOTE_TLB_FLUSH_RECOMMENDED;
1071 entry_recomm->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
1074 if (kvm_check_extension(cs->kvm_state,
1075 KVM_CAP_HYPERV_ENLIGHTENED_VMCS) > 0) {
1076 entry_recomm->eax |= HV_ENLIGHTENED_VMCS_RECOMMENDED;
1079 if (kvm_check_extension(cs->kvm_state,
1080 KVM_CAP_HYPERV_SEND_IPI) > 0) {
1081 entry_recomm->eax |= HV_CLUSTER_IPI_RECOMMENDED;
1082 entry_recomm->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
1085 return cpuid;
1088 static int hv_cpuid_get_fw(struct kvm_cpuid2 *cpuid, int fw, uint32_t *r)
1090 struct kvm_cpuid_entry2 *entry;
1091 uint32_t func;
1092 int reg;
1094 switch (fw) {
1095 case FEAT_HYPERV_EAX:
1096 reg = R_EAX;
1097 func = HV_CPUID_FEATURES;
1098 break;
1099 case FEAT_HYPERV_EDX:
1100 reg = R_EDX;
1101 func = HV_CPUID_FEATURES;
1102 break;
1103 case FEAT_HV_RECOMM_EAX:
1104 reg = R_EAX;
1105 func = HV_CPUID_ENLIGHTMENT_INFO;
1106 break;
1107 default:
1108 return -EINVAL;
1111 entry = cpuid_find_entry(cpuid, func, 0);
1112 if (!entry) {
1113 return -ENOENT;
1116 switch (reg) {
1117 case R_EAX:
1118 *r = entry->eax;
1119 break;
1120 case R_EDX:
1121 *r = entry->edx;
1122 break;
1123 default:
1124 return -EINVAL;
1127 return 0;
1130 static int hv_cpuid_check_and_set(CPUState *cs, struct kvm_cpuid2 *cpuid,
1131 int feature)
1133 X86CPU *cpu = X86_CPU(cs);
1134 CPUX86State *env = &cpu->env;
1135 uint32_t r, fw, bits;
1136 uint64_t deps;
1137 int i, dep_feat;
1139 if (!hyperv_feat_enabled(cpu, feature) && !cpu->hyperv_passthrough) {
1140 return 0;
1143 deps = kvm_hyperv_properties[feature].dependencies;
1144 while (deps) {
1145 dep_feat = ctz64(deps);
1146 if (!(hyperv_feat_enabled(cpu, dep_feat))) {
1147 fprintf(stderr,
1148 "Hyper-V %s requires Hyper-V %s\n",
1149 kvm_hyperv_properties[feature].desc,
1150 kvm_hyperv_properties[dep_feat].desc);
1151 return 1;
1153 deps &= ~(1ull << dep_feat);
1156 for (i = 0; i < ARRAY_SIZE(kvm_hyperv_properties[feature].flags); i++) {
1157 fw = kvm_hyperv_properties[feature].flags[i].fw;
1158 bits = kvm_hyperv_properties[feature].flags[i].bits;
1160 if (!fw) {
1161 continue;
1164 if (hv_cpuid_get_fw(cpuid, fw, &r) || (r & bits) != bits) {
1165 if (hyperv_feat_enabled(cpu, feature)) {
1166 fprintf(stderr,
1167 "Hyper-V %s is not supported by kernel\n",
1168 kvm_hyperv_properties[feature].desc);
1169 return 1;
1170 } else {
1171 return 0;
1175 env->features[fw] |= bits;
1178 if (cpu->hyperv_passthrough) {
1179 cpu->hyperv_features |= BIT(feature);
1182 return 0;
1186 * Fill in Hyper-V CPUIDs. Returns the number of entries filled in cpuid_ent in
1187 * case of success, errno < 0 in case of failure and 0 when no Hyper-V
1188 * extentions are enabled.
1190 static int hyperv_handle_properties(CPUState *cs,
1191 struct kvm_cpuid_entry2 *cpuid_ent)
1193 X86CPU *cpu = X86_CPU(cs);
1194 CPUX86State *env = &cpu->env;
1195 struct kvm_cpuid2 *cpuid;
1196 struct kvm_cpuid_entry2 *c;
1197 uint32_t signature[3];
1198 uint32_t cpuid_i = 0;
1199 int r;
1201 if (!hyperv_enabled(cpu))
1202 return 0;
1204 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS) ||
1205 cpu->hyperv_passthrough) {
1206 uint16_t evmcs_version;
1208 r = kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_ENLIGHTENED_VMCS, 0,
1209 (uintptr_t)&evmcs_version);
1211 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS) && r) {
1212 fprintf(stderr, "Hyper-V %s is not supported by kernel\n",
1213 kvm_hyperv_properties[HYPERV_FEAT_EVMCS].desc);
1214 return -ENOSYS;
1217 if (!r) {
1218 env->features[FEAT_HV_RECOMM_EAX] |=
1219 HV_ENLIGHTENED_VMCS_RECOMMENDED;
1220 env->features[FEAT_HV_NESTED_EAX] = evmcs_version;
1224 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_CPUID) > 0) {
1225 cpuid = get_supported_hv_cpuid(cs);
1226 } else {
1227 cpuid = get_supported_hv_cpuid_legacy(cs);
1230 if (cpu->hyperv_passthrough) {
1231 memcpy(cpuid_ent, &cpuid->entries[0],
1232 cpuid->nent * sizeof(cpuid->entries[0]));
1234 c = cpuid_find_entry(cpuid, HV_CPUID_FEATURES, 0);
1235 if (c) {
1236 env->features[FEAT_HYPERV_EAX] = c->eax;
1237 env->features[FEAT_HYPERV_EBX] = c->ebx;
1238 env->features[FEAT_HYPERV_EDX] = c->eax;
1240 c = cpuid_find_entry(cpuid, HV_CPUID_ENLIGHTMENT_INFO, 0);
1241 if (c) {
1242 env->features[FEAT_HV_RECOMM_EAX] = c->eax;
1244 /* hv-spinlocks may have been overriden */
1245 if (cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY) {
1246 c->ebx = cpu->hyperv_spinlock_attempts;
1249 c = cpuid_find_entry(cpuid, HV_CPUID_NESTED_FEATURES, 0);
1250 if (c) {
1251 env->features[FEAT_HV_NESTED_EAX] = c->eax;
1255 if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_ON) {
1256 env->features[FEAT_HV_RECOMM_EAX] |= HV_NO_NONARCH_CORESHARING;
1257 } else if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_AUTO) {
1258 c = cpuid_find_entry(cpuid, HV_CPUID_ENLIGHTMENT_INFO, 0);
1259 if (c) {
1260 env->features[FEAT_HV_RECOMM_EAX] |=
1261 c->eax & HV_NO_NONARCH_CORESHARING;
1265 /* Features */
1266 r = hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_RELAXED);
1267 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_VAPIC);
1268 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_TIME);
1269 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_CRASH);
1270 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_RESET);
1271 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_VPINDEX);
1272 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_RUNTIME);
1273 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_SYNIC);
1274 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_STIMER);
1275 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_FREQUENCIES);
1276 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_REENLIGHTENMENT);
1277 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_TLBFLUSH);
1278 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_EVMCS);
1279 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_IPI);
1280 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_STIMER_DIRECT);
1282 /* Additional dependencies not covered by kvm_hyperv_properties[] */
1283 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC) &&
1284 !cpu->hyperv_synic_kvm_only &&
1285 !hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)) {
1286 fprintf(stderr, "Hyper-V %s requires Hyper-V %s\n",
1287 kvm_hyperv_properties[HYPERV_FEAT_SYNIC].desc,
1288 kvm_hyperv_properties[HYPERV_FEAT_VPINDEX].desc);
1289 r |= 1;
1292 /* Not exposed by KVM but needed to make CPU hotplug in Windows work */
1293 env->features[FEAT_HYPERV_EDX] |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
1295 if (r) {
1296 r = -ENOSYS;
1297 goto free;
1300 if (cpu->hyperv_passthrough) {
1301 /* We already copied all feature words from KVM as is */
1302 r = cpuid->nent;
1303 goto free;
1306 c = &cpuid_ent[cpuid_i++];
1307 c->function = HV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
1308 if (!cpu->hyperv_vendor_id) {
1309 memcpy(signature, "Microsoft Hv", 12);
1310 } else {
1311 size_t len = strlen(cpu->hyperv_vendor_id);
1313 if (len > 12) {
1314 error_report("hv-vendor-id truncated to 12 characters");
1315 len = 12;
1317 memset(signature, 0, 12);
1318 memcpy(signature, cpu->hyperv_vendor_id, len);
1320 c->eax = hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS) ?
1321 HV_CPUID_NESTED_FEATURES : HV_CPUID_IMPLEMENT_LIMITS;
1322 c->ebx = signature[0];
1323 c->ecx = signature[1];
1324 c->edx = signature[2];
1326 c = &cpuid_ent[cpuid_i++];
1327 c->function = HV_CPUID_INTERFACE;
1328 memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
1329 c->eax = signature[0];
1330 c->ebx = 0;
1331 c->ecx = 0;
1332 c->edx = 0;
1334 c = &cpuid_ent[cpuid_i++];
1335 c->function = HV_CPUID_VERSION;
1336 c->eax = 0x00001bbc;
1337 c->ebx = 0x00060001;
1339 c = &cpuid_ent[cpuid_i++];
1340 c->function = HV_CPUID_FEATURES;
1341 c->eax = env->features[FEAT_HYPERV_EAX];
1342 c->ebx = env->features[FEAT_HYPERV_EBX];
1343 c->edx = env->features[FEAT_HYPERV_EDX];
1345 c = &cpuid_ent[cpuid_i++];
1346 c->function = HV_CPUID_ENLIGHTMENT_INFO;
1347 c->eax = env->features[FEAT_HV_RECOMM_EAX];
1348 c->ebx = cpu->hyperv_spinlock_attempts;
1350 c = &cpuid_ent[cpuid_i++];
1351 c->function = HV_CPUID_IMPLEMENT_LIMITS;
1352 c->eax = cpu->hv_max_vps;
1353 c->ebx = 0x40;
1355 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS)) {
1356 __u32 function;
1358 /* Create zeroed 0x40000006..0x40000009 leaves */
1359 for (function = HV_CPUID_IMPLEMENT_LIMITS + 1;
1360 function < HV_CPUID_NESTED_FEATURES; function++) {
1361 c = &cpuid_ent[cpuid_i++];
1362 c->function = function;
1365 c = &cpuid_ent[cpuid_i++];
1366 c->function = HV_CPUID_NESTED_FEATURES;
1367 c->eax = env->features[FEAT_HV_NESTED_EAX];
1369 r = cpuid_i;
1371 free:
1372 g_free(cpuid);
1374 return r;
1377 static Error *hv_passthrough_mig_blocker;
1378 static Error *hv_no_nonarch_cs_mig_blocker;
1380 static int hyperv_init_vcpu(X86CPU *cpu)
1382 CPUState *cs = CPU(cpu);
1383 Error *local_err = NULL;
1384 int ret;
1386 if (cpu->hyperv_passthrough && hv_passthrough_mig_blocker == NULL) {
1387 error_setg(&hv_passthrough_mig_blocker,
1388 "'hv-passthrough' CPU flag prevents migration, use explicit"
1389 " set of hv-* flags instead");
1390 ret = migrate_add_blocker(hv_passthrough_mig_blocker, &local_err);
1391 if (local_err) {
1392 error_report_err(local_err);
1393 error_free(hv_passthrough_mig_blocker);
1394 return ret;
1398 if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_AUTO &&
1399 hv_no_nonarch_cs_mig_blocker == NULL) {
1400 error_setg(&hv_no_nonarch_cs_mig_blocker,
1401 "'hv-no-nonarch-coresharing=auto' CPU flag prevents migration"
1402 " use explicit 'hv-no-nonarch-coresharing=on' instead (but"
1403 " make sure SMT is disabled and/or that vCPUs are properly"
1404 " pinned)");
1405 ret = migrate_add_blocker(hv_no_nonarch_cs_mig_blocker, &local_err);
1406 if (local_err) {
1407 error_report_err(local_err);
1408 error_free(hv_no_nonarch_cs_mig_blocker);
1409 return ret;
1413 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX) && !hv_vpindex_settable) {
1415 * the kernel doesn't support setting vp_index; assert that its value
1416 * is in sync
1418 struct {
1419 struct kvm_msrs info;
1420 struct kvm_msr_entry entries[1];
1421 } msr_data = {
1422 .info.nmsrs = 1,
1423 .entries[0].index = HV_X64_MSR_VP_INDEX,
1426 ret = kvm_vcpu_ioctl(cs, KVM_GET_MSRS, &msr_data);
1427 if (ret < 0) {
1428 return ret;
1430 assert(ret == 1);
1432 if (msr_data.entries[0].data != hyperv_vp_index(CPU(cpu))) {
1433 error_report("kernel's vp_index != QEMU's vp_index");
1434 return -ENXIO;
1438 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
1439 uint32_t synic_cap = cpu->hyperv_synic_kvm_only ?
1440 KVM_CAP_HYPERV_SYNIC : KVM_CAP_HYPERV_SYNIC2;
1441 ret = kvm_vcpu_enable_cap(cs, synic_cap, 0);
1442 if (ret < 0) {
1443 error_report("failed to turn on HyperV SynIC in KVM: %s",
1444 strerror(-ret));
1445 return ret;
1448 if (!cpu->hyperv_synic_kvm_only) {
1449 ret = hyperv_x86_synic_add(cpu);
1450 if (ret < 0) {
1451 error_report("failed to create HyperV SynIC: %s",
1452 strerror(-ret));
1453 return ret;
1458 return 0;
1461 static Error *invtsc_mig_blocker;
1463 #define KVM_MAX_CPUID_ENTRIES 100
1465 int kvm_arch_init_vcpu(CPUState *cs)
1467 struct {
1468 struct kvm_cpuid2 cpuid;
1469 struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
1470 } cpuid_data;
1472 * The kernel defines these structs with padding fields so there
1473 * should be no extra padding in our cpuid_data struct.
1475 QEMU_BUILD_BUG_ON(sizeof(cpuid_data) !=
1476 sizeof(struct kvm_cpuid2) +
1477 sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES);
1479 X86CPU *cpu = X86_CPU(cs);
1480 CPUX86State *env = &cpu->env;
1481 uint32_t limit, i, j, cpuid_i;
1482 uint32_t unused;
1483 struct kvm_cpuid_entry2 *c;
1484 uint32_t signature[3];
1485 int kvm_base = KVM_CPUID_SIGNATURE;
1486 int max_nested_state_len;
1487 int r;
1488 Error *local_err = NULL;
1490 memset(&cpuid_data, 0, sizeof(cpuid_data));
1492 cpuid_i = 0;
1494 r = kvm_arch_set_tsc_khz(cs);
1495 if (r < 0) {
1496 return r;
1499 /* vcpu's TSC frequency is either specified by user, or following
1500 * the value used by KVM if the former is not present. In the
1501 * latter case, we query it from KVM and record in env->tsc_khz,
1502 * so that vcpu's TSC frequency can be migrated later via this field.
1504 if (!env->tsc_khz) {
1505 r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
1506 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
1507 -ENOTSUP;
1508 if (r > 0) {
1509 env->tsc_khz = r;
1513 env->apic_bus_freq = KVM_APIC_BUS_FREQUENCY;
1515 /* Paravirtualization CPUIDs */
1516 r = hyperv_handle_properties(cs, cpuid_data.entries);
1517 if (r < 0) {
1518 return r;
1519 } else if (r > 0) {
1520 cpuid_i = r;
1521 kvm_base = KVM_CPUID_SIGNATURE_NEXT;
1522 has_msr_hv_hypercall = true;
1525 if (cpu->expose_kvm) {
1526 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
1527 c = &cpuid_data.entries[cpuid_i++];
1528 c->function = KVM_CPUID_SIGNATURE | kvm_base;
1529 c->eax = KVM_CPUID_FEATURES | kvm_base;
1530 c->ebx = signature[0];
1531 c->ecx = signature[1];
1532 c->edx = signature[2];
1534 c = &cpuid_data.entries[cpuid_i++];
1535 c->function = KVM_CPUID_FEATURES | kvm_base;
1536 c->eax = env->features[FEAT_KVM];
1537 c->edx = env->features[FEAT_KVM_HINTS];
1540 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
1542 for (i = 0; i <= limit; i++) {
1543 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1544 fprintf(stderr, "unsupported level value: 0x%x\n", limit);
1545 abort();
1547 c = &cpuid_data.entries[cpuid_i++];
1549 switch (i) {
1550 case 2: {
1551 /* Keep reading function 2 till all the input is received */
1552 int times;
1554 c->function = i;
1555 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
1556 KVM_CPUID_FLAG_STATE_READ_NEXT;
1557 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1558 times = c->eax & 0xff;
1560 for (j = 1; j < times; ++j) {
1561 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1562 fprintf(stderr, "cpuid_data is full, no space for "
1563 "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
1564 abort();
1566 c = &cpuid_data.entries[cpuid_i++];
1567 c->function = i;
1568 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
1569 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1571 break;
1573 case 0x1f:
1574 if (env->nr_dies < 2) {
1575 break;
1577 case 4:
1578 case 0xb:
1579 case 0xd:
1580 for (j = 0; ; j++) {
1581 if (i == 0xd && j == 64) {
1582 break;
1585 if (i == 0x1f && j == 64) {
1586 break;
1589 c->function = i;
1590 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1591 c->index = j;
1592 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1594 if (i == 4 && c->eax == 0) {
1595 break;
1597 if (i == 0xb && !(c->ecx & 0xff00)) {
1598 break;
1600 if (i == 0x1f && !(c->ecx & 0xff00)) {
1601 break;
1603 if (i == 0xd && c->eax == 0) {
1604 continue;
1606 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1607 fprintf(stderr, "cpuid_data is full, no space for "
1608 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1609 abort();
1611 c = &cpuid_data.entries[cpuid_i++];
1613 break;
1614 case 0x7:
1615 case 0x14: {
1616 uint32_t times;
1618 c->function = i;
1619 c->index = 0;
1620 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1621 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1622 times = c->eax;
1624 for (j = 1; j <= times; ++j) {
1625 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1626 fprintf(stderr, "cpuid_data is full, no space for "
1627 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1628 abort();
1630 c = &cpuid_data.entries[cpuid_i++];
1631 c->function = i;
1632 c->index = j;
1633 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1634 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1636 break;
1638 default:
1639 c->function = i;
1640 c->flags = 0;
1641 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1642 if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
1644 * KVM already returns all zeroes if a CPUID entry is missing,
1645 * so we can omit it and avoid hitting KVM's 80-entry limit.
1647 cpuid_i--;
1649 break;
1653 if (limit >= 0x0a) {
1654 uint32_t eax, edx;
1656 cpu_x86_cpuid(env, 0x0a, 0, &eax, &unused, &unused, &edx);
1658 has_architectural_pmu_version = eax & 0xff;
1659 if (has_architectural_pmu_version > 0) {
1660 num_architectural_pmu_gp_counters = (eax & 0xff00) >> 8;
1662 /* Shouldn't be more than 32, since that's the number of bits
1663 * available in EBX to tell us _which_ counters are available.
1664 * Play it safe.
1666 if (num_architectural_pmu_gp_counters > MAX_GP_COUNTERS) {
1667 num_architectural_pmu_gp_counters = MAX_GP_COUNTERS;
1670 if (has_architectural_pmu_version > 1) {
1671 num_architectural_pmu_fixed_counters = edx & 0x1f;
1673 if (num_architectural_pmu_fixed_counters > MAX_FIXED_COUNTERS) {
1674 num_architectural_pmu_fixed_counters = MAX_FIXED_COUNTERS;
1680 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
1682 for (i = 0x80000000; i <= limit; i++) {
1683 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1684 fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
1685 abort();
1687 c = &cpuid_data.entries[cpuid_i++];
1689 switch (i) {
1690 case 0x8000001d:
1691 /* Query for all AMD cache information leaves */
1692 for (j = 0; ; j++) {
1693 c->function = i;
1694 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1695 c->index = j;
1696 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1698 if (c->eax == 0) {
1699 break;
1701 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1702 fprintf(stderr, "cpuid_data is full, no space for "
1703 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1704 abort();
1706 c = &cpuid_data.entries[cpuid_i++];
1708 break;
1709 default:
1710 c->function = i;
1711 c->flags = 0;
1712 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1713 if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
1715 * KVM already returns all zeroes if a CPUID entry is missing,
1716 * so we can omit it and avoid hitting KVM's 80-entry limit.
1718 cpuid_i--;
1720 break;
1724 /* Call Centaur's CPUID instructions they are supported. */
1725 if (env->cpuid_xlevel2 > 0) {
1726 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
1728 for (i = 0xC0000000; i <= limit; i++) {
1729 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1730 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
1731 abort();
1733 c = &cpuid_data.entries[cpuid_i++];
1735 c->function = i;
1736 c->flags = 0;
1737 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1741 cpuid_data.cpuid.nent = cpuid_i;
1743 if (((env->cpuid_version >> 8)&0xF) >= 6
1744 && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
1745 (CPUID_MCE | CPUID_MCA)
1746 && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
1747 uint64_t mcg_cap, unsupported_caps;
1748 int banks;
1749 int ret;
1751 ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
1752 if (ret < 0) {
1753 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
1754 return ret;
1757 if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
1758 error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
1759 (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
1760 return -ENOTSUP;
1763 unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
1764 if (unsupported_caps) {
1765 if (unsupported_caps & MCG_LMCE_P) {
1766 error_report("kvm: LMCE not supported");
1767 return -ENOTSUP;
1769 warn_report("Unsupported MCG_CAP bits: 0x%" PRIx64,
1770 unsupported_caps);
1773 env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
1774 ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
1775 if (ret < 0) {
1776 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
1777 return ret;
1781 cpu->vmsentry = qemu_add_vm_change_state_handler(cpu_update_state, env);
1783 c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
1784 if (c) {
1785 has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
1786 !!(c->ecx & CPUID_EXT_SMX);
1789 if (env->mcg_cap & MCG_LMCE_P) {
1790 has_msr_mcg_ext_ctl = has_msr_feature_control = true;
1793 if (!env->user_tsc_khz) {
1794 if ((env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC) &&
1795 invtsc_mig_blocker == NULL) {
1796 error_setg(&invtsc_mig_blocker,
1797 "State blocked by non-migratable CPU device"
1798 " (invtsc flag)");
1799 r = migrate_add_blocker(invtsc_mig_blocker, &local_err);
1800 if (local_err) {
1801 error_report_err(local_err);
1802 error_free(invtsc_mig_blocker);
1803 return r;
1808 if (cpu->vmware_cpuid_freq
1809 /* Guests depend on 0x40000000 to detect this feature, so only expose
1810 * it if KVM exposes leaf 0x40000000. (Conflicts with Hyper-V) */
1811 && cpu->expose_kvm
1812 && kvm_base == KVM_CPUID_SIGNATURE
1813 /* TSC clock must be stable and known for this feature. */
1814 && tsc_is_stable_and_known(env)) {
1816 c = &cpuid_data.entries[cpuid_i++];
1817 c->function = KVM_CPUID_SIGNATURE | 0x10;
1818 c->eax = env->tsc_khz;
1819 c->ebx = env->apic_bus_freq / 1000; /* Hz to KHz */
1820 c->ecx = c->edx = 0;
1822 c = cpuid_find_entry(&cpuid_data.cpuid, kvm_base, 0);
1823 c->eax = MAX(c->eax, KVM_CPUID_SIGNATURE | 0x10);
1826 cpuid_data.cpuid.nent = cpuid_i;
1828 cpuid_data.cpuid.padding = 0;
1829 r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
1830 if (r) {
1831 goto fail;
1834 if (has_xsave) {
1835 env->xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
1836 memset(env->xsave_buf, 0, sizeof(struct kvm_xsave));
1839 max_nested_state_len = kvm_max_nested_state_length();
1840 if (max_nested_state_len > 0) {
1841 assert(max_nested_state_len >= offsetof(struct kvm_nested_state, data));
1843 if (cpu_has_vmx(env) || cpu_has_svm(env)) {
1844 struct kvm_vmx_nested_state_hdr *vmx_hdr;
1846 env->nested_state = g_malloc0(max_nested_state_len);
1847 env->nested_state->size = max_nested_state_len;
1848 env->nested_state->format = KVM_STATE_NESTED_FORMAT_VMX;
1850 if (cpu_has_vmx(env)) {
1851 vmx_hdr = &env->nested_state->hdr.vmx;
1852 vmx_hdr->vmxon_pa = -1ull;
1853 vmx_hdr->vmcs12_pa = -1ull;
1858 cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
1860 if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
1861 has_msr_tsc_aux = false;
1864 kvm_init_msrs(cpu);
1866 r = hyperv_init_vcpu(cpu);
1867 if (r) {
1868 goto fail;
1871 return 0;
1873 fail:
1874 migrate_del_blocker(invtsc_mig_blocker);
1876 return r;
1879 int kvm_arch_destroy_vcpu(CPUState *cs)
1881 X86CPU *cpu = X86_CPU(cs);
1882 CPUX86State *env = &cpu->env;
1884 if (cpu->kvm_msr_buf) {
1885 g_free(cpu->kvm_msr_buf);
1886 cpu->kvm_msr_buf = NULL;
1889 if (env->nested_state) {
1890 g_free(env->nested_state);
1891 env->nested_state = NULL;
1894 qemu_del_vm_change_state_handler(cpu->vmsentry);
1896 return 0;
1899 void kvm_arch_reset_vcpu(X86CPU *cpu)
1901 CPUX86State *env = &cpu->env;
1903 env->xcr0 = 1;
1904 if (kvm_irqchip_in_kernel()) {
1905 env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
1906 KVM_MP_STATE_UNINITIALIZED;
1907 } else {
1908 env->mp_state = KVM_MP_STATE_RUNNABLE;
1911 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
1912 int i;
1913 for (i = 0; i < ARRAY_SIZE(env->msr_hv_synic_sint); i++) {
1914 env->msr_hv_synic_sint[i] = HV_SINT_MASKED;
1917 hyperv_x86_synic_reset(cpu);
1919 /* enabled by default */
1920 env->poll_control_msr = 1;
1923 void kvm_arch_do_init_vcpu(X86CPU *cpu)
1925 CPUX86State *env = &cpu->env;
1927 /* APs get directly into wait-for-SIPI state. */
1928 if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
1929 env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
1933 static int kvm_get_supported_feature_msrs(KVMState *s)
1935 int ret = 0;
1937 if (kvm_feature_msrs != NULL) {
1938 return 0;
1941 if (!kvm_check_extension(s, KVM_CAP_GET_MSR_FEATURES)) {
1942 return 0;
1945 struct kvm_msr_list msr_list;
1947 msr_list.nmsrs = 0;
1948 ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, &msr_list);
1949 if (ret < 0 && ret != -E2BIG) {
1950 error_report("Fetch KVM feature MSR list failed: %s",
1951 strerror(-ret));
1952 return ret;
1955 assert(msr_list.nmsrs > 0);
1956 kvm_feature_msrs = (struct kvm_msr_list *) \
1957 g_malloc0(sizeof(msr_list) +
1958 msr_list.nmsrs * sizeof(msr_list.indices[0]));
1960 kvm_feature_msrs->nmsrs = msr_list.nmsrs;
1961 ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, kvm_feature_msrs);
1963 if (ret < 0) {
1964 error_report("Fetch KVM feature MSR list failed: %s",
1965 strerror(-ret));
1966 g_free(kvm_feature_msrs);
1967 kvm_feature_msrs = NULL;
1968 return ret;
1971 return 0;
1974 static int kvm_get_supported_msrs(KVMState *s)
1976 int ret = 0;
1977 struct kvm_msr_list msr_list, *kvm_msr_list;
1980 * Obtain MSR list from KVM. These are the MSRs that we must
1981 * save/restore.
1983 msr_list.nmsrs = 0;
1984 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
1985 if (ret < 0 && ret != -E2BIG) {
1986 return ret;
1989 * Old kernel modules had a bug and could write beyond the provided
1990 * memory. Allocate at least a safe amount of 1K.
1992 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
1993 msr_list.nmsrs *
1994 sizeof(msr_list.indices[0])));
1996 kvm_msr_list->nmsrs = msr_list.nmsrs;
1997 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
1998 if (ret >= 0) {
1999 int i;
2001 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
2002 switch (kvm_msr_list->indices[i]) {
2003 case MSR_STAR:
2004 has_msr_star = true;
2005 break;
2006 case MSR_VM_HSAVE_PA:
2007 has_msr_hsave_pa = true;
2008 break;
2009 case MSR_TSC_AUX:
2010 has_msr_tsc_aux = true;
2011 break;
2012 case MSR_TSC_ADJUST:
2013 has_msr_tsc_adjust = true;
2014 break;
2015 case MSR_IA32_TSCDEADLINE:
2016 has_msr_tsc_deadline = true;
2017 break;
2018 case MSR_IA32_SMBASE:
2019 has_msr_smbase = true;
2020 break;
2021 case MSR_SMI_COUNT:
2022 has_msr_smi_count = true;
2023 break;
2024 case MSR_IA32_MISC_ENABLE:
2025 has_msr_misc_enable = true;
2026 break;
2027 case MSR_IA32_BNDCFGS:
2028 has_msr_bndcfgs = true;
2029 break;
2030 case MSR_IA32_XSS:
2031 has_msr_xss = true;
2032 break;
2033 case MSR_IA32_UMWAIT_CONTROL:
2034 has_msr_umwait = true;
2035 break;
2036 case HV_X64_MSR_CRASH_CTL:
2037 has_msr_hv_crash = true;
2038 break;
2039 case HV_X64_MSR_RESET:
2040 has_msr_hv_reset = true;
2041 break;
2042 case HV_X64_MSR_VP_INDEX:
2043 has_msr_hv_vpindex = true;
2044 break;
2045 case HV_X64_MSR_VP_RUNTIME:
2046 has_msr_hv_runtime = true;
2047 break;
2048 case HV_X64_MSR_SCONTROL:
2049 has_msr_hv_synic = true;
2050 break;
2051 case HV_X64_MSR_STIMER0_CONFIG:
2052 has_msr_hv_stimer = true;
2053 break;
2054 case HV_X64_MSR_TSC_FREQUENCY:
2055 has_msr_hv_frequencies = true;
2056 break;
2057 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2058 has_msr_hv_reenlightenment = true;
2059 break;
2060 case MSR_IA32_SPEC_CTRL:
2061 has_msr_spec_ctrl = true;
2062 break;
2063 case MSR_IA32_TSX_CTRL:
2064 has_msr_tsx_ctrl = true;
2065 break;
2066 case MSR_VIRT_SSBD:
2067 has_msr_virt_ssbd = true;
2068 break;
2069 case MSR_IA32_ARCH_CAPABILITIES:
2070 has_msr_arch_capabs = true;
2071 break;
2072 case MSR_IA32_CORE_CAPABILITY:
2073 has_msr_core_capabs = true;
2074 break;
2075 case MSR_IA32_PERF_CAPABILITIES:
2076 has_msr_perf_capabs = true;
2077 break;
2078 case MSR_IA32_VMX_VMFUNC:
2079 has_msr_vmx_vmfunc = true;
2080 break;
2081 case MSR_IA32_UCODE_REV:
2082 has_msr_ucode_rev = true;
2083 break;
2084 case MSR_IA32_VMX_PROCBASED_CTLS2:
2085 has_msr_vmx_procbased_ctls2 = true;
2086 break;
2091 g_free(kvm_msr_list);
2093 return ret;
2096 static Notifier smram_machine_done;
2097 static KVMMemoryListener smram_listener;
2098 static AddressSpace smram_address_space;
2099 static MemoryRegion smram_as_root;
2100 static MemoryRegion smram_as_mem;
2102 static void register_smram_listener(Notifier *n, void *unused)
2104 MemoryRegion *smram =
2105 (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
2107 /* Outer container... */
2108 memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
2109 memory_region_set_enabled(&smram_as_root, true);
2111 /* ... with two regions inside: normal system memory with low
2112 * priority, and...
2114 memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
2115 get_system_memory(), 0, ~0ull);
2116 memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
2117 memory_region_set_enabled(&smram_as_mem, true);
2119 if (smram) {
2120 /* ... SMRAM with higher priority */
2121 memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
2122 memory_region_set_enabled(smram, true);
2125 address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
2126 kvm_memory_listener_register(kvm_state, &smram_listener,
2127 &smram_address_space, 1);
2130 int kvm_arch_init(MachineState *ms, KVMState *s)
2132 uint64_t identity_base = 0xfffbc000;
2133 uint64_t shadow_mem;
2134 int ret;
2135 struct utsname utsname;
2137 has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
2138 has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
2139 has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
2141 hv_vpindex_settable = kvm_check_extension(s, KVM_CAP_HYPERV_VP_INDEX);
2143 has_exception_payload = kvm_check_extension(s, KVM_CAP_EXCEPTION_PAYLOAD);
2144 if (has_exception_payload) {
2145 ret = kvm_vm_enable_cap(s, KVM_CAP_EXCEPTION_PAYLOAD, 0, true);
2146 if (ret < 0) {
2147 error_report("kvm: Failed to enable exception payload cap: %s",
2148 strerror(-ret));
2149 return ret;
2153 ret = kvm_get_supported_msrs(s);
2154 if (ret < 0) {
2155 return ret;
2158 kvm_get_supported_feature_msrs(s);
2160 uname(&utsname);
2161 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
2164 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
2165 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
2166 * Since these must be part of guest physical memory, we need to allocate
2167 * them, both by setting their start addresses in the kernel and by
2168 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
2170 * Older KVM versions may not support setting the identity map base. In
2171 * that case we need to stick with the default, i.e. a 256K maximum BIOS
2172 * size.
2174 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
2175 /* Allows up to 16M BIOSes. */
2176 identity_base = 0xfeffc000;
2178 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
2179 if (ret < 0) {
2180 return ret;
2184 /* Set TSS base one page after EPT identity map. */
2185 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
2186 if (ret < 0) {
2187 return ret;
2190 /* Tell fw_cfg to notify the BIOS to reserve the range. */
2191 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
2192 if (ret < 0) {
2193 fprintf(stderr, "e820_add_entry() table is full\n");
2194 return ret;
2197 shadow_mem = object_property_get_int(OBJECT(s), "kvm-shadow-mem", &error_abort);
2198 if (shadow_mem != -1) {
2199 shadow_mem /= 4096;
2200 ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
2201 if (ret < 0) {
2202 return ret;
2206 if (kvm_check_extension(s, KVM_CAP_X86_SMM) &&
2207 object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE) &&
2208 x86_machine_is_smm_enabled(X86_MACHINE(ms))) {
2209 smram_machine_done.notify = register_smram_listener;
2210 qemu_add_machine_init_done_notifier(&smram_machine_done);
2213 if (enable_cpu_pm) {
2214 int disable_exits = kvm_check_extension(s, KVM_CAP_X86_DISABLE_EXITS);
2215 int ret;
2217 /* Work around for kernel header with a typo. TODO: fix header and drop. */
2218 #if defined(KVM_X86_DISABLE_EXITS_HTL) && !defined(KVM_X86_DISABLE_EXITS_HLT)
2219 #define KVM_X86_DISABLE_EXITS_HLT KVM_X86_DISABLE_EXITS_HTL
2220 #endif
2221 if (disable_exits) {
2222 disable_exits &= (KVM_X86_DISABLE_EXITS_MWAIT |
2223 KVM_X86_DISABLE_EXITS_HLT |
2224 KVM_X86_DISABLE_EXITS_PAUSE |
2225 KVM_X86_DISABLE_EXITS_CSTATE);
2228 ret = kvm_vm_enable_cap(s, KVM_CAP_X86_DISABLE_EXITS, 0,
2229 disable_exits);
2230 if (ret < 0) {
2231 error_report("kvm: guest stopping CPU not supported: %s",
2232 strerror(-ret));
2236 return 0;
2239 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2241 lhs->selector = rhs->selector;
2242 lhs->base = rhs->base;
2243 lhs->limit = rhs->limit;
2244 lhs->type = 3;
2245 lhs->present = 1;
2246 lhs->dpl = 3;
2247 lhs->db = 0;
2248 lhs->s = 1;
2249 lhs->l = 0;
2250 lhs->g = 0;
2251 lhs->avl = 0;
2252 lhs->unusable = 0;
2255 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2257 unsigned flags = rhs->flags;
2258 lhs->selector = rhs->selector;
2259 lhs->base = rhs->base;
2260 lhs->limit = rhs->limit;
2261 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
2262 lhs->present = (flags & DESC_P_MASK) != 0;
2263 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
2264 lhs->db = (flags >> DESC_B_SHIFT) & 1;
2265 lhs->s = (flags & DESC_S_MASK) != 0;
2266 lhs->l = (flags >> DESC_L_SHIFT) & 1;
2267 lhs->g = (flags & DESC_G_MASK) != 0;
2268 lhs->avl = (flags & DESC_AVL_MASK) != 0;
2269 lhs->unusable = !lhs->present;
2270 lhs->padding = 0;
2273 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
2275 lhs->selector = rhs->selector;
2276 lhs->base = rhs->base;
2277 lhs->limit = rhs->limit;
2278 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
2279 ((rhs->present && !rhs->unusable) * DESC_P_MASK) |
2280 (rhs->dpl << DESC_DPL_SHIFT) |
2281 (rhs->db << DESC_B_SHIFT) |
2282 (rhs->s * DESC_S_MASK) |
2283 (rhs->l << DESC_L_SHIFT) |
2284 (rhs->g * DESC_G_MASK) |
2285 (rhs->avl * DESC_AVL_MASK);
2288 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
2290 if (set) {
2291 *kvm_reg = *qemu_reg;
2292 } else {
2293 *qemu_reg = *kvm_reg;
2297 static int kvm_getput_regs(X86CPU *cpu, int set)
2299 CPUX86State *env = &cpu->env;
2300 struct kvm_regs regs;
2301 int ret = 0;
2303 if (!set) {
2304 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
2305 if (ret < 0) {
2306 return ret;
2310 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
2311 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
2312 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
2313 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
2314 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
2315 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
2316 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
2317 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
2318 #ifdef TARGET_X86_64
2319 kvm_getput_reg(&regs.r8, &env->regs[8], set);
2320 kvm_getput_reg(&regs.r9, &env->regs[9], set);
2321 kvm_getput_reg(&regs.r10, &env->regs[10], set);
2322 kvm_getput_reg(&regs.r11, &env->regs[11], set);
2323 kvm_getput_reg(&regs.r12, &env->regs[12], set);
2324 kvm_getput_reg(&regs.r13, &env->regs[13], set);
2325 kvm_getput_reg(&regs.r14, &env->regs[14], set);
2326 kvm_getput_reg(&regs.r15, &env->regs[15], set);
2327 #endif
2329 kvm_getput_reg(&regs.rflags, &env->eflags, set);
2330 kvm_getput_reg(&regs.rip, &env->eip, set);
2332 if (set) {
2333 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
2336 return ret;
2339 static int kvm_put_fpu(X86CPU *cpu)
2341 CPUX86State *env = &cpu->env;
2342 struct kvm_fpu fpu;
2343 int i;
2345 memset(&fpu, 0, sizeof fpu);
2346 fpu.fsw = env->fpus & ~(7 << 11);
2347 fpu.fsw |= (env->fpstt & 7) << 11;
2348 fpu.fcw = env->fpuc;
2349 fpu.last_opcode = env->fpop;
2350 fpu.last_ip = env->fpip;
2351 fpu.last_dp = env->fpdp;
2352 for (i = 0; i < 8; ++i) {
2353 fpu.ftwx |= (!env->fptags[i]) << i;
2355 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
2356 for (i = 0; i < CPU_NB_REGS; i++) {
2357 stq_p(&fpu.xmm[i][0], env->xmm_regs[i].ZMM_Q(0));
2358 stq_p(&fpu.xmm[i][8], env->xmm_regs[i].ZMM_Q(1));
2360 fpu.mxcsr = env->mxcsr;
2362 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
2365 #define XSAVE_FCW_FSW 0
2366 #define XSAVE_FTW_FOP 1
2367 #define XSAVE_CWD_RIP 2
2368 #define XSAVE_CWD_RDP 4
2369 #define XSAVE_MXCSR 6
2370 #define XSAVE_ST_SPACE 8
2371 #define XSAVE_XMM_SPACE 40
2372 #define XSAVE_XSTATE_BV 128
2373 #define XSAVE_YMMH_SPACE 144
2374 #define XSAVE_BNDREGS 240
2375 #define XSAVE_BNDCSR 256
2376 #define XSAVE_OPMASK 272
2377 #define XSAVE_ZMM_Hi256 288
2378 #define XSAVE_Hi16_ZMM 416
2379 #define XSAVE_PKRU 672
2381 #define XSAVE_BYTE_OFFSET(word_offset) \
2382 ((word_offset) * sizeof_field(struct kvm_xsave, region[0]))
2384 #define ASSERT_OFFSET(word_offset, field) \
2385 QEMU_BUILD_BUG_ON(XSAVE_BYTE_OFFSET(word_offset) != \
2386 offsetof(X86XSaveArea, field))
2388 ASSERT_OFFSET(XSAVE_FCW_FSW, legacy.fcw);
2389 ASSERT_OFFSET(XSAVE_FTW_FOP, legacy.ftw);
2390 ASSERT_OFFSET(XSAVE_CWD_RIP, legacy.fpip);
2391 ASSERT_OFFSET(XSAVE_CWD_RDP, legacy.fpdp);
2392 ASSERT_OFFSET(XSAVE_MXCSR, legacy.mxcsr);
2393 ASSERT_OFFSET(XSAVE_ST_SPACE, legacy.fpregs);
2394 ASSERT_OFFSET(XSAVE_XMM_SPACE, legacy.xmm_regs);
2395 ASSERT_OFFSET(XSAVE_XSTATE_BV, header.xstate_bv);
2396 ASSERT_OFFSET(XSAVE_YMMH_SPACE, avx_state);
2397 ASSERT_OFFSET(XSAVE_BNDREGS, bndreg_state);
2398 ASSERT_OFFSET(XSAVE_BNDCSR, bndcsr_state);
2399 ASSERT_OFFSET(XSAVE_OPMASK, opmask_state);
2400 ASSERT_OFFSET(XSAVE_ZMM_Hi256, zmm_hi256_state);
2401 ASSERT_OFFSET(XSAVE_Hi16_ZMM, hi16_zmm_state);
2402 ASSERT_OFFSET(XSAVE_PKRU, pkru_state);
2404 static int kvm_put_xsave(X86CPU *cpu)
2406 CPUX86State *env = &cpu->env;
2407 X86XSaveArea *xsave = env->xsave_buf;
2409 if (!has_xsave) {
2410 return kvm_put_fpu(cpu);
2412 x86_cpu_xsave_all_areas(cpu, xsave);
2414 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
2417 static int kvm_put_xcrs(X86CPU *cpu)
2419 CPUX86State *env = &cpu->env;
2420 struct kvm_xcrs xcrs = {};
2422 if (!has_xcrs) {
2423 return 0;
2426 xcrs.nr_xcrs = 1;
2427 xcrs.flags = 0;
2428 xcrs.xcrs[0].xcr = 0;
2429 xcrs.xcrs[0].value = env->xcr0;
2430 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
2433 static int kvm_put_sregs(X86CPU *cpu)
2435 CPUX86State *env = &cpu->env;
2436 struct kvm_sregs sregs;
2438 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
2439 if (env->interrupt_injected >= 0) {
2440 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
2441 (uint64_t)1 << (env->interrupt_injected % 64);
2444 if ((env->eflags & VM_MASK)) {
2445 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
2446 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
2447 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
2448 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
2449 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
2450 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
2451 } else {
2452 set_seg(&sregs.cs, &env->segs[R_CS]);
2453 set_seg(&sregs.ds, &env->segs[R_DS]);
2454 set_seg(&sregs.es, &env->segs[R_ES]);
2455 set_seg(&sregs.fs, &env->segs[R_FS]);
2456 set_seg(&sregs.gs, &env->segs[R_GS]);
2457 set_seg(&sregs.ss, &env->segs[R_SS]);
2460 set_seg(&sregs.tr, &env->tr);
2461 set_seg(&sregs.ldt, &env->ldt);
2463 sregs.idt.limit = env->idt.limit;
2464 sregs.idt.base = env->idt.base;
2465 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
2466 sregs.gdt.limit = env->gdt.limit;
2467 sregs.gdt.base = env->gdt.base;
2468 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
2470 sregs.cr0 = env->cr[0];
2471 sregs.cr2 = env->cr[2];
2472 sregs.cr3 = env->cr[3];
2473 sregs.cr4 = env->cr[4];
2475 sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
2476 sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
2478 sregs.efer = env->efer;
2480 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
2483 static void kvm_msr_buf_reset(X86CPU *cpu)
2485 memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
2488 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
2490 struct kvm_msrs *msrs = cpu->kvm_msr_buf;
2491 void *limit = ((void *)msrs) + MSR_BUF_SIZE;
2492 struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
2494 assert((void *)(entry + 1) <= limit);
2496 entry->index = index;
2497 entry->reserved = 0;
2498 entry->data = value;
2499 msrs->nmsrs++;
2502 static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
2504 kvm_msr_buf_reset(cpu);
2505 kvm_msr_entry_add(cpu, index, value);
2507 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
2510 void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
2512 int ret;
2514 ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
2515 assert(ret == 1);
2518 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
2520 CPUX86State *env = &cpu->env;
2521 int ret;
2523 if (!has_msr_tsc_deadline) {
2524 return 0;
2527 ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
2528 if (ret < 0) {
2529 return ret;
2532 assert(ret == 1);
2533 return 0;
2537 * Provide a separate write service for the feature control MSR in order to
2538 * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
2539 * before writing any other state because forcibly leaving nested mode
2540 * invalidates the VCPU state.
2542 static int kvm_put_msr_feature_control(X86CPU *cpu)
2544 int ret;
2546 if (!has_msr_feature_control) {
2547 return 0;
2550 ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
2551 cpu->env.msr_ia32_feature_control);
2552 if (ret < 0) {
2553 return ret;
2556 assert(ret == 1);
2557 return 0;
2560 static uint64_t make_vmx_msr_value(uint32_t index, uint32_t features)
2562 uint32_t default1, can_be_one, can_be_zero;
2563 uint32_t must_be_one;
2565 switch (index) {
2566 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2567 default1 = 0x00000016;
2568 break;
2569 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2570 default1 = 0x0401e172;
2571 break;
2572 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
2573 default1 = 0x000011ff;
2574 break;
2575 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2576 default1 = 0x00036dff;
2577 break;
2578 case MSR_IA32_VMX_PROCBASED_CTLS2:
2579 default1 = 0;
2580 break;
2581 default:
2582 abort();
2585 /* If a feature bit is set, the control can be either set or clear.
2586 * Otherwise the value is limited to either 0 or 1 by default1.
2588 can_be_one = features | default1;
2589 can_be_zero = features | ~default1;
2590 must_be_one = ~can_be_zero;
2593 * Bit 0:31 -> 0 if the control bit can be zero (i.e. 1 if it must be one).
2594 * Bit 32:63 -> 1 if the control bit can be one.
2596 return must_be_one | (((uint64_t)can_be_one) << 32);
2599 #define VMCS12_MAX_FIELD_INDEX (0x17)
2601 static void kvm_msr_entry_add_vmx(X86CPU *cpu, FeatureWordArray f)
2603 uint64_t kvm_vmx_basic =
2604 kvm_arch_get_supported_msr_feature(kvm_state,
2605 MSR_IA32_VMX_BASIC);
2607 if (!kvm_vmx_basic) {
2608 /* If the kernel doesn't support VMX feature (kvm_intel.nested=0),
2609 * then kvm_vmx_basic will be 0 and KVM_SET_MSR will fail.
2611 return;
2614 uint64_t kvm_vmx_misc =
2615 kvm_arch_get_supported_msr_feature(kvm_state,
2616 MSR_IA32_VMX_MISC);
2617 uint64_t kvm_vmx_ept_vpid =
2618 kvm_arch_get_supported_msr_feature(kvm_state,
2619 MSR_IA32_VMX_EPT_VPID_CAP);
2622 * If the guest is 64-bit, a value of 1 is allowed for the host address
2623 * space size vmexit control.
2625 uint64_t fixed_vmx_exit = f[FEAT_8000_0001_EDX] & CPUID_EXT2_LM
2626 ? (uint64_t)VMX_VM_EXIT_HOST_ADDR_SPACE_SIZE << 32 : 0;
2629 * Bits 0-30, 32-44 and 50-53 come from the host. KVM should
2630 * not change them for backwards compatibility.
2632 uint64_t fixed_vmx_basic = kvm_vmx_basic &
2633 (MSR_VMX_BASIC_VMCS_REVISION_MASK |
2634 MSR_VMX_BASIC_VMXON_REGION_SIZE_MASK |
2635 MSR_VMX_BASIC_VMCS_MEM_TYPE_MASK);
2638 * Same for bits 0-4 and 25-27. Bits 16-24 (CR3 target count) can
2639 * change in the future but are always zero for now, clear them to be
2640 * future proof. Bits 32-63 in theory could change, though KVM does
2641 * not support dual-monitor treatment and probably never will; mask
2642 * them out as well.
2644 uint64_t fixed_vmx_misc = kvm_vmx_misc &
2645 (MSR_VMX_MISC_PREEMPTION_TIMER_SHIFT_MASK |
2646 MSR_VMX_MISC_MAX_MSR_LIST_SIZE_MASK);
2649 * EPT memory types should not change either, so we do not bother
2650 * adding features for them.
2652 uint64_t fixed_vmx_ept_mask =
2653 (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_ENABLE_EPT ?
2654 MSR_VMX_EPT_UC | MSR_VMX_EPT_WB : 0);
2655 uint64_t fixed_vmx_ept_vpid = kvm_vmx_ept_vpid & fixed_vmx_ept_mask;
2657 kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
2658 make_vmx_msr_value(MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
2659 f[FEAT_VMX_PROCBASED_CTLS]));
2660 kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PINBASED_CTLS,
2661 make_vmx_msr_value(MSR_IA32_VMX_TRUE_PINBASED_CTLS,
2662 f[FEAT_VMX_PINBASED_CTLS]));
2663 kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_EXIT_CTLS,
2664 make_vmx_msr_value(MSR_IA32_VMX_TRUE_EXIT_CTLS,
2665 f[FEAT_VMX_EXIT_CTLS]) | fixed_vmx_exit);
2666 kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_ENTRY_CTLS,
2667 make_vmx_msr_value(MSR_IA32_VMX_TRUE_ENTRY_CTLS,
2668 f[FEAT_VMX_ENTRY_CTLS]));
2669 kvm_msr_entry_add(cpu, MSR_IA32_VMX_PROCBASED_CTLS2,
2670 make_vmx_msr_value(MSR_IA32_VMX_PROCBASED_CTLS2,
2671 f[FEAT_VMX_SECONDARY_CTLS]));
2672 kvm_msr_entry_add(cpu, MSR_IA32_VMX_EPT_VPID_CAP,
2673 f[FEAT_VMX_EPT_VPID_CAPS] | fixed_vmx_ept_vpid);
2674 kvm_msr_entry_add(cpu, MSR_IA32_VMX_BASIC,
2675 f[FEAT_VMX_BASIC] | fixed_vmx_basic);
2676 kvm_msr_entry_add(cpu, MSR_IA32_VMX_MISC,
2677 f[FEAT_VMX_MISC] | fixed_vmx_misc);
2678 if (has_msr_vmx_vmfunc) {
2679 kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMFUNC, f[FEAT_VMX_VMFUNC]);
2683 * Just to be safe, write these with constant values. The CRn_FIXED1
2684 * MSRs are generated by KVM based on the vCPU's CPUID.
2686 kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR0_FIXED0,
2687 CR0_PE_MASK | CR0_PG_MASK | CR0_NE_MASK);
2688 kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR4_FIXED0,
2689 CR4_VMXE_MASK);
2690 kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM,
2691 VMCS12_MAX_FIELD_INDEX << 1);
2694 static void kvm_msr_entry_add_perf(X86CPU *cpu, FeatureWordArray f)
2696 uint64_t kvm_perf_cap =
2697 kvm_arch_get_supported_msr_feature(kvm_state,
2698 MSR_IA32_PERF_CAPABILITIES);
2700 if (kvm_perf_cap) {
2701 kvm_msr_entry_add(cpu, MSR_IA32_PERF_CAPABILITIES,
2702 kvm_perf_cap & f[FEAT_PERF_CAPABILITIES]);
2706 static int kvm_buf_set_msrs(X86CPU *cpu)
2708 int ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
2709 if (ret < 0) {
2710 return ret;
2713 if (ret < cpu->kvm_msr_buf->nmsrs) {
2714 struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
2715 error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,
2716 (uint32_t)e->index, (uint64_t)e->data);
2719 assert(ret == cpu->kvm_msr_buf->nmsrs);
2720 return 0;
2723 static void kvm_init_msrs(X86CPU *cpu)
2725 CPUX86State *env = &cpu->env;
2727 kvm_msr_buf_reset(cpu);
2728 if (has_msr_arch_capabs) {
2729 kvm_msr_entry_add(cpu, MSR_IA32_ARCH_CAPABILITIES,
2730 env->features[FEAT_ARCH_CAPABILITIES]);
2733 if (has_msr_core_capabs) {
2734 kvm_msr_entry_add(cpu, MSR_IA32_CORE_CAPABILITY,
2735 env->features[FEAT_CORE_CAPABILITY]);
2738 if (has_msr_perf_capabs && cpu->enable_pmu) {
2739 kvm_msr_entry_add_perf(cpu, env->features);
2742 if (has_msr_ucode_rev) {
2743 kvm_msr_entry_add(cpu, MSR_IA32_UCODE_REV, cpu->ucode_rev);
2747 * Older kernels do not include VMX MSRs in KVM_GET_MSR_INDEX_LIST, but
2748 * all kernels with MSR features should have them.
2750 if (kvm_feature_msrs && cpu_has_vmx(env)) {
2751 kvm_msr_entry_add_vmx(cpu, env->features);
2754 assert(kvm_buf_set_msrs(cpu) == 0);
2757 static int kvm_put_msrs(X86CPU *cpu, int level)
2759 CPUX86State *env = &cpu->env;
2760 int i;
2762 kvm_msr_buf_reset(cpu);
2764 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
2765 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
2766 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
2767 kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
2768 if (has_msr_star) {
2769 kvm_msr_entry_add(cpu, MSR_STAR, env->star);
2771 if (has_msr_hsave_pa) {
2772 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
2774 if (has_msr_tsc_aux) {
2775 kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
2777 if (has_msr_tsc_adjust) {
2778 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
2780 if (has_msr_misc_enable) {
2781 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
2782 env->msr_ia32_misc_enable);
2784 if (has_msr_smbase) {
2785 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
2787 if (has_msr_smi_count) {
2788 kvm_msr_entry_add(cpu, MSR_SMI_COUNT, env->msr_smi_count);
2790 if (has_msr_bndcfgs) {
2791 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
2793 if (has_msr_xss) {
2794 kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
2796 if (has_msr_umwait) {
2797 kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, env->umwait);
2799 if (has_msr_spec_ctrl) {
2800 kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, env->spec_ctrl);
2802 if (has_msr_tsx_ctrl) {
2803 kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, env->tsx_ctrl);
2805 if (has_msr_virt_ssbd) {
2806 kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, env->virt_ssbd);
2809 #ifdef TARGET_X86_64
2810 if (lm_capable_kernel) {
2811 kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
2812 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
2813 kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
2814 kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
2816 #endif
2819 * The following MSRs have side effects on the guest or are too heavy
2820 * for normal writeback. Limit them to reset or full state updates.
2822 if (level >= KVM_PUT_RESET_STATE) {
2823 kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
2824 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
2825 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
2826 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
2827 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
2829 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
2830 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
2832 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
2833 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
2836 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
2837 kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, env->poll_control_msr);
2840 if (has_architectural_pmu_version > 0) {
2841 if (has_architectural_pmu_version > 1) {
2842 /* Stop the counter. */
2843 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
2844 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
2847 /* Set the counter values. */
2848 for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
2849 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
2850 env->msr_fixed_counters[i]);
2852 for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
2853 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
2854 env->msr_gp_counters[i]);
2855 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
2856 env->msr_gp_evtsel[i]);
2858 if (has_architectural_pmu_version > 1) {
2859 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
2860 env->msr_global_status);
2861 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
2862 env->msr_global_ovf_ctrl);
2864 /* Now start the PMU. */
2865 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
2866 env->msr_fixed_ctr_ctrl);
2867 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
2868 env->msr_global_ctrl);
2872 * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,
2873 * only sync them to KVM on the first cpu
2875 if (current_cpu == first_cpu) {
2876 if (has_msr_hv_hypercall) {
2877 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
2878 env->msr_hv_guest_os_id);
2879 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
2880 env->msr_hv_hypercall);
2882 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
2883 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,
2884 env->msr_hv_tsc);
2886 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
2887 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL,
2888 env->msr_hv_reenlightenment_control);
2889 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL,
2890 env->msr_hv_tsc_emulation_control);
2891 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS,
2892 env->msr_hv_tsc_emulation_status);
2895 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
2896 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
2897 env->msr_hv_vapic);
2899 if (has_msr_hv_crash) {
2900 int j;
2902 for (j = 0; j < HV_CRASH_PARAMS; j++)
2903 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
2904 env->msr_hv_crash_params[j]);
2906 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);
2908 if (has_msr_hv_runtime) {
2909 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
2911 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)
2912 && hv_vpindex_settable) {
2913 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_INDEX,
2914 hyperv_vp_index(CPU(cpu)));
2916 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
2917 int j;
2919 kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);
2921 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
2922 env->msr_hv_synic_control);
2923 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
2924 env->msr_hv_synic_evt_page);
2925 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
2926 env->msr_hv_synic_msg_page);
2928 for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
2929 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
2930 env->msr_hv_synic_sint[j]);
2933 if (has_msr_hv_stimer) {
2934 int j;
2936 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
2937 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
2938 env->msr_hv_stimer_config[j]);
2941 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
2942 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
2943 env->msr_hv_stimer_count[j]);
2946 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
2947 uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
2949 kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
2950 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
2951 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
2952 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
2953 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
2954 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
2955 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
2956 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
2957 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
2958 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
2959 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
2960 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
2961 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
2962 /* The CPU GPs if we write to a bit above the physical limit of
2963 * the host CPU (and KVM emulates that)
2965 uint64_t mask = env->mtrr_var[i].mask;
2966 mask &= phys_mask;
2968 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
2969 env->mtrr_var[i].base);
2970 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
2973 if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
2974 int addr_num = kvm_arch_get_supported_cpuid(kvm_state,
2975 0x14, 1, R_EAX) & 0x7;
2977 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL,
2978 env->msr_rtit_ctrl);
2979 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS,
2980 env->msr_rtit_status);
2981 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE,
2982 env->msr_rtit_output_base);
2983 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK,
2984 env->msr_rtit_output_mask);
2985 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH,
2986 env->msr_rtit_cr3_match);
2987 for (i = 0; i < addr_num; i++) {
2988 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i,
2989 env->msr_rtit_addrs[i]);
2993 /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
2994 * kvm_put_msr_feature_control. */
2997 if (env->mcg_cap) {
2998 int i;
3000 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
3001 kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
3002 if (has_msr_mcg_ext_ctl) {
3003 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
3005 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3006 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
3010 return kvm_buf_set_msrs(cpu);
3014 static int kvm_get_fpu(X86CPU *cpu)
3016 CPUX86State *env = &cpu->env;
3017 struct kvm_fpu fpu;
3018 int i, ret;
3020 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
3021 if (ret < 0) {
3022 return ret;
3025 env->fpstt = (fpu.fsw >> 11) & 7;
3026 env->fpus = fpu.fsw;
3027 env->fpuc = fpu.fcw;
3028 env->fpop = fpu.last_opcode;
3029 env->fpip = fpu.last_ip;
3030 env->fpdp = fpu.last_dp;
3031 for (i = 0; i < 8; ++i) {
3032 env->fptags[i] = !((fpu.ftwx >> i) & 1);
3034 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
3035 for (i = 0; i < CPU_NB_REGS; i++) {
3036 env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
3037 env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
3039 env->mxcsr = fpu.mxcsr;
3041 return 0;
3044 static int kvm_get_xsave(X86CPU *cpu)
3046 CPUX86State *env = &cpu->env;
3047 X86XSaveArea *xsave = env->xsave_buf;
3048 int ret;
3050 if (!has_xsave) {
3051 return kvm_get_fpu(cpu);
3054 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
3055 if (ret < 0) {
3056 return ret;
3058 x86_cpu_xrstor_all_areas(cpu, xsave);
3060 return 0;
3063 static int kvm_get_xcrs(X86CPU *cpu)
3065 CPUX86State *env = &cpu->env;
3066 int i, ret;
3067 struct kvm_xcrs xcrs;
3069 if (!has_xcrs) {
3070 return 0;
3073 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
3074 if (ret < 0) {
3075 return ret;
3078 for (i = 0; i < xcrs.nr_xcrs; i++) {
3079 /* Only support xcr0 now */
3080 if (xcrs.xcrs[i].xcr == 0) {
3081 env->xcr0 = xcrs.xcrs[i].value;
3082 break;
3085 return 0;
3088 static int kvm_get_sregs(X86CPU *cpu)
3090 CPUX86State *env = &cpu->env;
3091 struct kvm_sregs sregs;
3092 int bit, i, ret;
3094 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
3095 if (ret < 0) {
3096 return ret;
3099 /* There can only be one pending IRQ set in the bitmap at a time, so try
3100 to find it and save its number instead (-1 for none). */
3101 env->interrupt_injected = -1;
3102 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
3103 if (sregs.interrupt_bitmap[i]) {
3104 bit = ctz64(sregs.interrupt_bitmap[i]);
3105 env->interrupt_injected = i * 64 + bit;
3106 break;
3110 get_seg(&env->segs[R_CS], &sregs.cs);
3111 get_seg(&env->segs[R_DS], &sregs.ds);
3112 get_seg(&env->segs[R_ES], &sregs.es);
3113 get_seg(&env->segs[R_FS], &sregs.fs);
3114 get_seg(&env->segs[R_GS], &sregs.gs);
3115 get_seg(&env->segs[R_SS], &sregs.ss);
3117 get_seg(&env->tr, &sregs.tr);
3118 get_seg(&env->ldt, &sregs.ldt);
3120 env->idt.limit = sregs.idt.limit;
3121 env->idt.base = sregs.idt.base;
3122 env->gdt.limit = sregs.gdt.limit;
3123 env->gdt.base = sregs.gdt.base;
3125 env->cr[0] = sregs.cr0;
3126 env->cr[2] = sregs.cr2;
3127 env->cr[3] = sregs.cr3;
3128 env->cr[4] = sregs.cr4;
3130 env->efer = sregs.efer;
3132 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
3133 x86_update_hflags(env);
3135 return 0;
3138 static int kvm_get_msrs(X86CPU *cpu)
3140 CPUX86State *env = &cpu->env;
3141 struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
3142 int ret, i;
3143 uint64_t mtrr_top_bits;
3145 kvm_msr_buf_reset(cpu);
3147 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
3148 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
3149 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
3150 kvm_msr_entry_add(cpu, MSR_PAT, 0);
3151 if (has_msr_star) {
3152 kvm_msr_entry_add(cpu, MSR_STAR, 0);
3154 if (has_msr_hsave_pa) {
3155 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
3157 if (has_msr_tsc_aux) {
3158 kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
3160 if (has_msr_tsc_adjust) {
3161 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
3163 if (has_msr_tsc_deadline) {
3164 kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
3166 if (has_msr_misc_enable) {
3167 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
3169 if (has_msr_smbase) {
3170 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
3172 if (has_msr_smi_count) {
3173 kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
3175 if (has_msr_feature_control) {
3176 kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
3178 if (has_msr_bndcfgs) {
3179 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
3181 if (has_msr_xss) {
3182 kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
3184 if (has_msr_umwait) {
3185 kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, 0);
3187 if (has_msr_spec_ctrl) {
3188 kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
3190 if (has_msr_tsx_ctrl) {
3191 kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, 0);
3193 if (has_msr_virt_ssbd) {
3194 kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, 0);
3196 if (!env->tsc_valid) {
3197 kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
3198 env->tsc_valid = !runstate_is_running();
3201 #ifdef TARGET_X86_64
3202 if (lm_capable_kernel) {
3203 kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
3204 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
3205 kvm_msr_entry_add(cpu, MSR_FMASK, 0);
3206 kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
3208 #endif
3209 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
3210 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
3211 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
3212 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
3214 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
3215 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
3217 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
3218 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
3220 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
3221 kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, 1);
3223 if (has_architectural_pmu_version > 0) {
3224 if (has_architectural_pmu_version > 1) {
3225 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
3226 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
3227 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
3228 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
3230 for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
3231 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
3233 for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
3234 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
3235 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
3239 if (env->mcg_cap) {
3240 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
3241 kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
3242 if (has_msr_mcg_ext_ctl) {
3243 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
3245 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3246 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
3250 if (has_msr_hv_hypercall) {
3251 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
3252 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
3254 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3255 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
3257 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
3258 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
3260 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
3261 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL, 0);
3262 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL, 0);
3263 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS, 0);
3265 if (has_msr_hv_crash) {
3266 int j;
3268 for (j = 0; j < HV_CRASH_PARAMS; j++) {
3269 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
3272 if (has_msr_hv_runtime) {
3273 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
3275 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3276 uint32_t msr;
3278 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
3279 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
3280 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
3281 for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
3282 kvm_msr_entry_add(cpu, msr, 0);
3285 if (has_msr_hv_stimer) {
3286 uint32_t msr;
3288 for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
3289 msr++) {
3290 kvm_msr_entry_add(cpu, msr, 0);
3293 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3294 kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
3295 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
3296 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
3297 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
3298 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
3299 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
3300 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
3301 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
3302 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
3303 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
3304 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
3305 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
3306 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
3307 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
3308 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
3312 if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
3313 int addr_num =
3314 kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
3316 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
3317 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
3318 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
3319 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
3320 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
3321 for (i = 0; i < addr_num; i++) {
3322 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
3326 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
3327 if (ret < 0) {
3328 return ret;
3331 if (ret < cpu->kvm_msr_buf->nmsrs) {
3332 struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
3333 error_report("error: failed to get MSR 0x%" PRIx32,
3334 (uint32_t)e->index);
3337 assert(ret == cpu->kvm_msr_buf->nmsrs);
3339 * MTRR masks: Each mask consists of 5 parts
3340 * a 10..0: must be zero
3341 * b 11 : valid bit
3342 * c n-1.12: actual mask bits
3343 * d 51..n: reserved must be zero
3344 * e 63.52: reserved must be zero
3346 * 'n' is the number of physical bits supported by the CPU and is
3347 * apparently always <= 52. We know our 'n' but don't know what
3348 * the destinations 'n' is; it might be smaller, in which case
3349 * it masks (c) on loading. It might be larger, in which case
3350 * we fill 'd' so that d..c is consistent irrespetive of the 'n'
3351 * we're migrating to.
3354 if (cpu->fill_mtrr_mask) {
3355 QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
3356 assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
3357 mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
3358 } else {
3359 mtrr_top_bits = 0;
3362 for (i = 0; i < ret; i++) {
3363 uint32_t index = msrs[i].index;
3364 switch (index) {
3365 case MSR_IA32_SYSENTER_CS:
3366 env->sysenter_cs = msrs[i].data;
3367 break;
3368 case MSR_IA32_SYSENTER_ESP:
3369 env->sysenter_esp = msrs[i].data;
3370 break;
3371 case MSR_IA32_SYSENTER_EIP:
3372 env->sysenter_eip = msrs[i].data;
3373 break;
3374 case MSR_PAT:
3375 env->pat = msrs[i].data;
3376 break;
3377 case MSR_STAR:
3378 env->star = msrs[i].data;
3379 break;
3380 #ifdef TARGET_X86_64
3381 case MSR_CSTAR:
3382 env->cstar = msrs[i].data;
3383 break;
3384 case MSR_KERNELGSBASE:
3385 env->kernelgsbase = msrs[i].data;
3386 break;
3387 case MSR_FMASK:
3388 env->fmask = msrs[i].data;
3389 break;
3390 case MSR_LSTAR:
3391 env->lstar = msrs[i].data;
3392 break;
3393 #endif
3394 case MSR_IA32_TSC:
3395 env->tsc = msrs[i].data;
3396 break;
3397 case MSR_TSC_AUX:
3398 env->tsc_aux = msrs[i].data;
3399 break;
3400 case MSR_TSC_ADJUST:
3401 env->tsc_adjust = msrs[i].data;
3402 break;
3403 case MSR_IA32_TSCDEADLINE:
3404 env->tsc_deadline = msrs[i].data;
3405 break;
3406 case MSR_VM_HSAVE_PA:
3407 env->vm_hsave = msrs[i].data;
3408 break;
3409 case MSR_KVM_SYSTEM_TIME:
3410 env->system_time_msr = msrs[i].data;
3411 break;
3412 case MSR_KVM_WALL_CLOCK:
3413 env->wall_clock_msr = msrs[i].data;
3414 break;
3415 case MSR_MCG_STATUS:
3416 env->mcg_status = msrs[i].data;
3417 break;
3418 case MSR_MCG_CTL:
3419 env->mcg_ctl = msrs[i].data;
3420 break;
3421 case MSR_MCG_EXT_CTL:
3422 env->mcg_ext_ctl = msrs[i].data;
3423 break;
3424 case MSR_IA32_MISC_ENABLE:
3425 env->msr_ia32_misc_enable = msrs[i].data;
3426 break;
3427 case MSR_IA32_SMBASE:
3428 env->smbase = msrs[i].data;
3429 break;
3430 case MSR_SMI_COUNT:
3431 env->msr_smi_count = msrs[i].data;
3432 break;
3433 case MSR_IA32_FEATURE_CONTROL:
3434 env->msr_ia32_feature_control = msrs[i].data;
3435 break;
3436 case MSR_IA32_BNDCFGS:
3437 env->msr_bndcfgs = msrs[i].data;
3438 break;
3439 case MSR_IA32_XSS:
3440 env->xss = msrs[i].data;
3441 break;
3442 case MSR_IA32_UMWAIT_CONTROL:
3443 env->umwait = msrs[i].data;
3444 break;
3445 default:
3446 if (msrs[i].index >= MSR_MC0_CTL &&
3447 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
3448 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
3450 break;
3451 case MSR_KVM_ASYNC_PF_EN:
3452 env->async_pf_en_msr = msrs[i].data;
3453 break;
3454 case MSR_KVM_PV_EOI_EN:
3455 env->pv_eoi_en_msr = msrs[i].data;
3456 break;
3457 case MSR_KVM_STEAL_TIME:
3458 env->steal_time_msr = msrs[i].data;
3459 break;
3460 case MSR_KVM_POLL_CONTROL: {
3461 env->poll_control_msr = msrs[i].data;
3462 break;
3464 case MSR_CORE_PERF_FIXED_CTR_CTRL:
3465 env->msr_fixed_ctr_ctrl = msrs[i].data;
3466 break;
3467 case MSR_CORE_PERF_GLOBAL_CTRL:
3468 env->msr_global_ctrl = msrs[i].data;
3469 break;
3470 case MSR_CORE_PERF_GLOBAL_STATUS:
3471 env->msr_global_status = msrs[i].data;
3472 break;
3473 case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
3474 env->msr_global_ovf_ctrl = msrs[i].data;
3475 break;
3476 case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
3477 env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
3478 break;
3479 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
3480 env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
3481 break;
3482 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
3483 env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
3484 break;
3485 case HV_X64_MSR_HYPERCALL:
3486 env->msr_hv_hypercall = msrs[i].data;
3487 break;
3488 case HV_X64_MSR_GUEST_OS_ID:
3489 env->msr_hv_guest_os_id = msrs[i].data;
3490 break;
3491 case HV_X64_MSR_APIC_ASSIST_PAGE:
3492 env->msr_hv_vapic = msrs[i].data;
3493 break;
3494 case HV_X64_MSR_REFERENCE_TSC:
3495 env->msr_hv_tsc = msrs[i].data;
3496 break;
3497 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3498 env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
3499 break;
3500 case HV_X64_MSR_VP_RUNTIME:
3501 env->msr_hv_runtime = msrs[i].data;
3502 break;
3503 case HV_X64_MSR_SCONTROL:
3504 env->msr_hv_synic_control = msrs[i].data;
3505 break;
3506 case HV_X64_MSR_SIEFP:
3507 env->msr_hv_synic_evt_page = msrs[i].data;
3508 break;
3509 case HV_X64_MSR_SIMP:
3510 env->msr_hv_synic_msg_page = msrs[i].data;
3511 break;
3512 case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
3513 env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
3514 break;
3515 case HV_X64_MSR_STIMER0_CONFIG:
3516 case HV_X64_MSR_STIMER1_CONFIG:
3517 case HV_X64_MSR_STIMER2_CONFIG:
3518 case HV_X64_MSR_STIMER3_CONFIG:
3519 env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
3520 msrs[i].data;
3521 break;
3522 case HV_X64_MSR_STIMER0_COUNT:
3523 case HV_X64_MSR_STIMER1_COUNT:
3524 case HV_X64_MSR_STIMER2_COUNT:
3525 case HV_X64_MSR_STIMER3_COUNT:
3526 env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
3527 msrs[i].data;
3528 break;
3529 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3530 env->msr_hv_reenlightenment_control = msrs[i].data;
3531 break;
3532 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3533 env->msr_hv_tsc_emulation_control = msrs[i].data;
3534 break;
3535 case HV_X64_MSR_TSC_EMULATION_STATUS:
3536 env->msr_hv_tsc_emulation_status = msrs[i].data;
3537 break;
3538 case MSR_MTRRdefType:
3539 env->mtrr_deftype = msrs[i].data;
3540 break;
3541 case MSR_MTRRfix64K_00000:
3542 env->mtrr_fixed[0] = msrs[i].data;
3543 break;
3544 case MSR_MTRRfix16K_80000:
3545 env->mtrr_fixed[1] = msrs[i].data;
3546 break;
3547 case MSR_MTRRfix16K_A0000:
3548 env->mtrr_fixed[2] = msrs[i].data;
3549 break;
3550 case MSR_MTRRfix4K_C0000:
3551 env->mtrr_fixed[3] = msrs[i].data;
3552 break;
3553 case MSR_MTRRfix4K_C8000:
3554 env->mtrr_fixed[4] = msrs[i].data;
3555 break;
3556 case MSR_MTRRfix4K_D0000:
3557 env->mtrr_fixed[5] = msrs[i].data;
3558 break;
3559 case MSR_MTRRfix4K_D8000:
3560 env->mtrr_fixed[6] = msrs[i].data;
3561 break;
3562 case MSR_MTRRfix4K_E0000:
3563 env->mtrr_fixed[7] = msrs[i].data;
3564 break;
3565 case MSR_MTRRfix4K_E8000:
3566 env->mtrr_fixed[8] = msrs[i].data;
3567 break;
3568 case MSR_MTRRfix4K_F0000:
3569 env->mtrr_fixed[9] = msrs[i].data;
3570 break;
3571 case MSR_MTRRfix4K_F8000:
3572 env->mtrr_fixed[10] = msrs[i].data;
3573 break;
3574 case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
3575 if (index & 1) {
3576 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
3577 mtrr_top_bits;
3578 } else {
3579 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
3581 break;
3582 case MSR_IA32_SPEC_CTRL:
3583 env->spec_ctrl = msrs[i].data;
3584 break;
3585 case MSR_IA32_TSX_CTRL:
3586 env->tsx_ctrl = msrs[i].data;
3587 break;
3588 case MSR_VIRT_SSBD:
3589 env->virt_ssbd = msrs[i].data;
3590 break;
3591 case MSR_IA32_RTIT_CTL:
3592 env->msr_rtit_ctrl = msrs[i].data;
3593 break;
3594 case MSR_IA32_RTIT_STATUS:
3595 env->msr_rtit_status = msrs[i].data;
3596 break;
3597 case MSR_IA32_RTIT_OUTPUT_BASE:
3598 env->msr_rtit_output_base = msrs[i].data;
3599 break;
3600 case MSR_IA32_RTIT_OUTPUT_MASK:
3601 env->msr_rtit_output_mask = msrs[i].data;
3602 break;
3603 case MSR_IA32_RTIT_CR3_MATCH:
3604 env->msr_rtit_cr3_match = msrs[i].data;
3605 break;
3606 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
3607 env->msr_rtit_addrs[index - MSR_IA32_RTIT_ADDR0_A] = msrs[i].data;
3608 break;
3612 return 0;
3615 static int kvm_put_mp_state(X86CPU *cpu)
3617 struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
3619 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
3622 static int kvm_get_mp_state(X86CPU *cpu)
3624 CPUState *cs = CPU(cpu);
3625 CPUX86State *env = &cpu->env;
3626 struct kvm_mp_state mp_state;
3627 int ret;
3629 ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
3630 if (ret < 0) {
3631 return ret;
3633 env->mp_state = mp_state.mp_state;
3634 if (kvm_irqchip_in_kernel()) {
3635 cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
3637 return 0;
3640 static int kvm_get_apic(X86CPU *cpu)
3642 DeviceState *apic = cpu->apic_state;
3643 struct kvm_lapic_state kapic;
3644 int ret;
3646 if (apic && kvm_irqchip_in_kernel()) {
3647 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
3648 if (ret < 0) {
3649 return ret;
3652 kvm_get_apic_state(apic, &kapic);
3654 return 0;
3657 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
3659 CPUState *cs = CPU(cpu);
3660 CPUX86State *env = &cpu->env;
3661 struct kvm_vcpu_events events = {};
3663 if (!kvm_has_vcpu_events()) {
3664 return 0;
3667 events.flags = 0;
3669 if (has_exception_payload) {
3670 events.flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
3671 events.exception.pending = env->exception_pending;
3672 events.exception_has_payload = env->exception_has_payload;
3673 events.exception_payload = env->exception_payload;
3675 events.exception.nr = env->exception_nr;
3676 events.exception.injected = env->exception_injected;
3677 events.exception.has_error_code = env->has_error_code;
3678 events.exception.error_code = env->error_code;
3680 events.interrupt.injected = (env->interrupt_injected >= 0);
3681 events.interrupt.nr = env->interrupt_injected;
3682 events.interrupt.soft = env->soft_interrupt;
3684 events.nmi.injected = env->nmi_injected;
3685 events.nmi.pending = env->nmi_pending;
3686 events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
3688 events.sipi_vector = env->sipi_vector;
3690 if (has_msr_smbase) {
3691 events.smi.smm = !!(env->hflags & HF_SMM_MASK);
3692 events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
3693 if (kvm_irqchip_in_kernel()) {
3694 /* As soon as these are moved to the kernel, remove them
3695 * from cs->interrupt_request.
3697 events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
3698 events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
3699 cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
3700 } else {
3701 /* Keep these in cs->interrupt_request. */
3702 events.smi.pending = 0;
3703 events.smi.latched_init = 0;
3705 /* Stop SMI delivery on old machine types to avoid a reboot
3706 * on an inward migration of an old VM.
3708 if (!cpu->kvm_no_smi_migration) {
3709 events.flags |= KVM_VCPUEVENT_VALID_SMM;
3713 if (level >= KVM_PUT_RESET_STATE) {
3714 events.flags |= KVM_VCPUEVENT_VALID_NMI_PENDING;
3715 if (env->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
3716 events.flags |= KVM_VCPUEVENT_VALID_SIPI_VECTOR;
3720 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
3723 static int kvm_get_vcpu_events(X86CPU *cpu)
3725 CPUX86State *env = &cpu->env;
3726 struct kvm_vcpu_events events;
3727 int ret;
3729 if (!kvm_has_vcpu_events()) {
3730 return 0;
3733 memset(&events, 0, sizeof(events));
3734 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
3735 if (ret < 0) {
3736 return ret;
3739 if (events.flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
3740 env->exception_pending = events.exception.pending;
3741 env->exception_has_payload = events.exception_has_payload;
3742 env->exception_payload = events.exception_payload;
3743 } else {
3744 env->exception_pending = 0;
3745 env->exception_has_payload = false;
3747 env->exception_injected = events.exception.injected;
3748 env->exception_nr =
3749 (env->exception_pending || env->exception_injected) ?
3750 events.exception.nr : -1;
3751 env->has_error_code = events.exception.has_error_code;
3752 env->error_code = events.exception.error_code;
3754 env->interrupt_injected =
3755 events.interrupt.injected ? events.interrupt.nr : -1;
3756 env->soft_interrupt = events.interrupt.soft;
3758 env->nmi_injected = events.nmi.injected;
3759 env->nmi_pending = events.nmi.pending;
3760 if (events.nmi.masked) {
3761 env->hflags2 |= HF2_NMI_MASK;
3762 } else {
3763 env->hflags2 &= ~HF2_NMI_MASK;
3766 if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
3767 if (events.smi.smm) {
3768 env->hflags |= HF_SMM_MASK;
3769 } else {
3770 env->hflags &= ~HF_SMM_MASK;
3772 if (events.smi.pending) {
3773 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
3774 } else {
3775 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
3777 if (events.smi.smm_inside_nmi) {
3778 env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
3779 } else {
3780 env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
3782 if (events.smi.latched_init) {
3783 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
3784 } else {
3785 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
3789 env->sipi_vector = events.sipi_vector;
3791 return 0;
3794 static int kvm_guest_debug_workarounds(X86CPU *cpu)
3796 CPUState *cs = CPU(cpu);
3797 CPUX86State *env = &cpu->env;
3798 int ret = 0;
3799 unsigned long reinject_trap = 0;
3801 if (!kvm_has_vcpu_events()) {
3802 if (env->exception_nr == EXCP01_DB) {
3803 reinject_trap = KVM_GUESTDBG_INJECT_DB;
3804 } else if (env->exception_injected == EXCP03_INT3) {
3805 reinject_trap = KVM_GUESTDBG_INJECT_BP;
3807 kvm_reset_exception(env);
3811 * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
3812 * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
3813 * by updating the debug state once again if single-stepping is on.
3814 * Another reason to call kvm_update_guest_debug here is a pending debug
3815 * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
3816 * reinject them via SET_GUEST_DEBUG.
3818 if (reinject_trap ||
3819 (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
3820 ret = kvm_update_guest_debug(cs, reinject_trap);
3822 return ret;
3825 static int kvm_put_debugregs(X86CPU *cpu)
3827 CPUX86State *env = &cpu->env;
3828 struct kvm_debugregs dbgregs;
3829 int i;
3831 if (!kvm_has_debugregs()) {
3832 return 0;
3835 memset(&dbgregs, 0, sizeof(dbgregs));
3836 for (i = 0; i < 4; i++) {
3837 dbgregs.db[i] = env->dr[i];
3839 dbgregs.dr6 = env->dr[6];
3840 dbgregs.dr7 = env->dr[7];
3841 dbgregs.flags = 0;
3843 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
3846 static int kvm_get_debugregs(X86CPU *cpu)
3848 CPUX86State *env = &cpu->env;
3849 struct kvm_debugregs dbgregs;
3850 int i, ret;
3852 if (!kvm_has_debugregs()) {
3853 return 0;
3856 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
3857 if (ret < 0) {
3858 return ret;
3860 for (i = 0; i < 4; i++) {
3861 env->dr[i] = dbgregs.db[i];
3863 env->dr[4] = env->dr[6] = dbgregs.dr6;
3864 env->dr[5] = env->dr[7] = dbgregs.dr7;
3866 return 0;
3869 static int kvm_put_nested_state(X86CPU *cpu)
3871 CPUX86State *env = &cpu->env;
3872 int max_nested_state_len = kvm_max_nested_state_length();
3874 if (!env->nested_state) {
3875 return 0;
3879 * Copy flags that are affected by reset from env->hflags and env->hflags2.
3881 if (env->hflags & HF_GUEST_MASK) {
3882 env->nested_state->flags |= KVM_STATE_NESTED_GUEST_MODE;
3883 } else {
3884 env->nested_state->flags &= ~KVM_STATE_NESTED_GUEST_MODE;
3886 if (env->hflags2 & HF2_GIF_MASK) {
3887 env->nested_state->flags |= KVM_STATE_NESTED_GIF_SET;
3888 } else {
3889 env->nested_state->flags &= ~KVM_STATE_NESTED_GIF_SET;
3892 assert(env->nested_state->size <= max_nested_state_len);
3893 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_NESTED_STATE, env->nested_state);
3896 static int kvm_get_nested_state(X86CPU *cpu)
3898 CPUX86State *env = &cpu->env;
3899 int max_nested_state_len = kvm_max_nested_state_length();
3900 int ret;
3902 if (!env->nested_state) {
3903 return 0;
3907 * It is possible that migration restored a smaller size into
3908 * nested_state->hdr.size than what our kernel support.
3909 * We preserve migration origin nested_state->hdr.size for
3910 * call to KVM_SET_NESTED_STATE but wish that our next call
3911 * to KVM_GET_NESTED_STATE will use max size our kernel support.
3913 env->nested_state->size = max_nested_state_len;
3915 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_NESTED_STATE, env->nested_state);
3916 if (ret < 0) {
3917 return ret;
3921 * Copy flags that are affected by reset to env->hflags and env->hflags2.
3923 if (env->nested_state->flags & KVM_STATE_NESTED_GUEST_MODE) {
3924 env->hflags |= HF_GUEST_MASK;
3925 } else {
3926 env->hflags &= ~HF_GUEST_MASK;
3928 if (env->nested_state->flags & KVM_STATE_NESTED_GIF_SET) {
3929 env->hflags2 |= HF2_GIF_MASK;
3930 } else {
3931 env->hflags2 &= ~HF2_GIF_MASK;
3934 return ret;
3937 int kvm_arch_put_registers(CPUState *cpu, int level)
3939 X86CPU *x86_cpu = X86_CPU(cpu);
3940 int ret;
3942 assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
3944 /* must be before kvm_put_nested_state so that EFER.SVME is set */
3945 ret = kvm_put_sregs(x86_cpu);
3946 if (ret < 0) {
3947 return ret;
3950 if (level >= KVM_PUT_RESET_STATE) {
3951 ret = kvm_put_nested_state(x86_cpu);
3952 if (ret < 0) {
3953 return ret;
3956 ret = kvm_put_msr_feature_control(x86_cpu);
3957 if (ret < 0) {
3958 return ret;
3962 if (level == KVM_PUT_FULL_STATE) {
3963 /* We don't check for kvm_arch_set_tsc_khz() errors here,
3964 * because TSC frequency mismatch shouldn't abort migration,
3965 * unless the user explicitly asked for a more strict TSC
3966 * setting (e.g. using an explicit "tsc-freq" option).
3968 kvm_arch_set_tsc_khz(cpu);
3971 ret = kvm_getput_regs(x86_cpu, 1);
3972 if (ret < 0) {
3973 return ret;
3975 ret = kvm_put_xsave(x86_cpu);
3976 if (ret < 0) {
3977 return ret;
3979 ret = kvm_put_xcrs(x86_cpu);
3980 if (ret < 0) {
3981 return ret;
3983 /* must be before kvm_put_msrs */
3984 ret = kvm_inject_mce_oldstyle(x86_cpu);
3985 if (ret < 0) {
3986 return ret;
3988 ret = kvm_put_msrs(x86_cpu, level);
3989 if (ret < 0) {
3990 return ret;
3992 ret = kvm_put_vcpu_events(x86_cpu, level);
3993 if (ret < 0) {
3994 return ret;
3996 if (level >= KVM_PUT_RESET_STATE) {
3997 ret = kvm_put_mp_state(x86_cpu);
3998 if (ret < 0) {
3999 return ret;
4003 ret = kvm_put_tscdeadline_msr(x86_cpu);
4004 if (ret < 0) {
4005 return ret;
4007 ret = kvm_put_debugregs(x86_cpu);
4008 if (ret < 0) {
4009 return ret;
4011 /* must be last */
4012 ret = kvm_guest_debug_workarounds(x86_cpu);
4013 if (ret < 0) {
4014 return ret;
4016 return 0;
4019 int kvm_arch_get_registers(CPUState *cs)
4021 X86CPU *cpu = X86_CPU(cs);
4022 int ret;
4024 assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
4026 ret = kvm_get_vcpu_events(cpu);
4027 if (ret < 0) {
4028 goto out;
4031 * KVM_GET_MPSTATE can modify CS and RIP, call it before
4032 * KVM_GET_REGS and KVM_GET_SREGS.
4034 ret = kvm_get_mp_state(cpu);
4035 if (ret < 0) {
4036 goto out;
4038 ret = kvm_getput_regs(cpu, 0);
4039 if (ret < 0) {
4040 goto out;
4042 ret = kvm_get_xsave(cpu);
4043 if (ret < 0) {
4044 goto out;
4046 ret = kvm_get_xcrs(cpu);
4047 if (ret < 0) {
4048 goto out;
4050 ret = kvm_get_sregs(cpu);
4051 if (ret < 0) {
4052 goto out;
4054 ret = kvm_get_msrs(cpu);
4055 if (ret < 0) {
4056 goto out;
4058 ret = kvm_get_apic(cpu);
4059 if (ret < 0) {
4060 goto out;
4062 ret = kvm_get_debugregs(cpu);
4063 if (ret < 0) {
4064 goto out;
4066 ret = kvm_get_nested_state(cpu);
4067 if (ret < 0) {
4068 goto out;
4070 ret = 0;
4071 out:
4072 cpu_sync_bndcs_hflags(&cpu->env);
4073 return ret;
4076 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
4078 X86CPU *x86_cpu = X86_CPU(cpu);
4079 CPUX86State *env = &x86_cpu->env;
4080 int ret;
4082 /* Inject NMI */
4083 if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
4084 if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
4085 qemu_mutex_lock_iothread();
4086 cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
4087 qemu_mutex_unlock_iothread();
4088 DPRINTF("injected NMI\n");
4089 ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
4090 if (ret < 0) {
4091 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
4092 strerror(-ret));
4095 if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
4096 qemu_mutex_lock_iothread();
4097 cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
4098 qemu_mutex_unlock_iothread();
4099 DPRINTF("injected SMI\n");
4100 ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
4101 if (ret < 0) {
4102 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
4103 strerror(-ret));
4108 if (!kvm_pic_in_kernel()) {
4109 qemu_mutex_lock_iothread();
4112 /* Force the VCPU out of its inner loop to process any INIT requests
4113 * or (for userspace APIC, but it is cheap to combine the checks here)
4114 * pending TPR access reports.
4116 if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
4117 if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
4118 !(env->hflags & HF_SMM_MASK)) {
4119 cpu->exit_request = 1;
4121 if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
4122 cpu->exit_request = 1;
4126 if (!kvm_pic_in_kernel()) {
4127 /* Try to inject an interrupt if the guest can accept it */
4128 if (run->ready_for_interrupt_injection &&
4129 (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
4130 (env->eflags & IF_MASK)) {
4131 int irq;
4133 cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
4134 irq = cpu_get_pic_interrupt(env);
4135 if (irq >= 0) {
4136 struct kvm_interrupt intr;
4138 intr.irq = irq;
4139 DPRINTF("injected interrupt %d\n", irq);
4140 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
4141 if (ret < 0) {
4142 fprintf(stderr,
4143 "KVM: injection failed, interrupt lost (%s)\n",
4144 strerror(-ret));
4149 /* If we have an interrupt but the guest is not ready to receive an
4150 * interrupt, request an interrupt window exit. This will
4151 * cause a return to userspace as soon as the guest is ready to
4152 * receive interrupts. */
4153 if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
4154 run->request_interrupt_window = 1;
4155 } else {
4156 run->request_interrupt_window = 0;
4159 DPRINTF("setting tpr\n");
4160 run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
4162 qemu_mutex_unlock_iothread();
4166 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
4168 X86CPU *x86_cpu = X86_CPU(cpu);
4169 CPUX86State *env = &x86_cpu->env;
4171 if (run->flags & KVM_RUN_X86_SMM) {
4172 env->hflags |= HF_SMM_MASK;
4173 } else {
4174 env->hflags &= ~HF_SMM_MASK;
4176 if (run->if_flag) {
4177 env->eflags |= IF_MASK;
4178 } else {
4179 env->eflags &= ~IF_MASK;
4182 /* We need to protect the apic state against concurrent accesses from
4183 * different threads in case the userspace irqchip is used. */
4184 if (!kvm_irqchip_in_kernel()) {
4185 qemu_mutex_lock_iothread();
4187 cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
4188 cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
4189 if (!kvm_irqchip_in_kernel()) {
4190 qemu_mutex_unlock_iothread();
4192 return cpu_get_mem_attrs(env);
4195 int kvm_arch_process_async_events(CPUState *cs)
4197 X86CPU *cpu = X86_CPU(cs);
4198 CPUX86State *env = &cpu->env;
4200 if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
4201 /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
4202 assert(env->mcg_cap);
4204 cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
4206 kvm_cpu_synchronize_state(cs);
4208 if (env->exception_nr == EXCP08_DBLE) {
4209 /* this means triple fault */
4210 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
4211 cs->exit_request = 1;
4212 return 0;
4214 kvm_queue_exception(env, EXCP12_MCHK, 0, 0);
4215 env->has_error_code = 0;
4217 cs->halted = 0;
4218 if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
4219 env->mp_state = KVM_MP_STATE_RUNNABLE;
4223 if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
4224 !(env->hflags & HF_SMM_MASK)) {
4225 kvm_cpu_synchronize_state(cs);
4226 do_cpu_init(cpu);
4229 if (kvm_irqchip_in_kernel()) {
4230 return 0;
4233 if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
4234 cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
4235 apic_poll_irq(cpu->apic_state);
4237 if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
4238 (env->eflags & IF_MASK)) ||
4239 (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
4240 cs->halted = 0;
4242 if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
4243 kvm_cpu_synchronize_state(cs);
4244 do_cpu_sipi(cpu);
4246 if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
4247 cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
4248 kvm_cpu_synchronize_state(cs);
4249 apic_handle_tpr_access_report(cpu->apic_state, env->eip,
4250 env->tpr_access_type);
4253 return cs->halted;
4256 static int kvm_handle_halt(X86CPU *cpu)
4258 CPUState *cs = CPU(cpu);
4259 CPUX86State *env = &cpu->env;
4261 if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
4262 (env->eflags & IF_MASK)) &&
4263 !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
4264 cs->halted = 1;
4265 return EXCP_HLT;
4268 return 0;
4271 static int kvm_handle_tpr_access(X86CPU *cpu)
4273 CPUState *cs = CPU(cpu);
4274 struct kvm_run *run = cs->kvm_run;
4276 apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
4277 run->tpr_access.is_write ? TPR_ACCESS_WRITE
4278 : TPR_ACCESS_READ);
4279 return 1;
4282 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
4284 static const uint8_t int3 = 0xcc;
4286 if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
4287 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
4288 return -EINVAL;
4290 return 0;
4293 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
4295 uint8_t int3;
4297 if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
4298 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
4299 return -EINVAL;
4301 return 0;
4304 static struct {
4305 target_ulong addr;
4306 int len;
4307 int type;
4308 } hw_breakpoint[4];
4310 static int nb_hw_breakpoint;
4312 static int find_hw_breakpoint(target_ulong addr, int len, int type)
4314 int n;
4316 for (n = 0; n < nb_hw_breakpoint; n++) {
4317 if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
4318 (hw_breakpoint[n].len == len || len == -1)) {
4319 return n;
4322 return -1;
4325 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
4326 target_ulong len, int type)
4328 switch (type) {
4329 case GDB_BREAKPOINT_HW:
4330 len = 1;
4331 break;
4332 case GDB_WATCHPOINT_WRITE:
4333 case GDB_WATCHPOINT_ACCESS:
4334 switch (len) {
4335 case 1:
4336 break;
4337 case 2:
4338 case 4:
4339 case 8:
4340 if (addr & (len - 1)) {
4341 return -EINVAL;
4343 break;
4344 default:
4345 return -EINVAL;
4347 break;
4348 default:
4349 return -ENOSYS;
4352 if (nb_hw_breakpoint == 4) {
4353 return -ENOBUFS;
4355 if (find_hw_breakpoint(addr, len, type) >= 0) {
4356 return -EEXIST;
4358 hw_breakpoint[nb_hw_breakpoint].addr = addr;
4359 hw_breakpoint[nb_hw_breakpoint].len = len;
4360 hw_breakpoint[nb_hw_breakpoint].type = type;
4361 nb_hw_breakpoint++;
4363 return 0;
4366 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
4367 target_ulong len, int type)
4369 int n;
4371 n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
4372 if (n < 0) {
4373 return -ENOENT;
4375 nb_hw_breakpoint--;
4376 hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
4378 return 0;
4381 void kvm_arch_remove_all_hw_breakpoints(void)
4383 nb_hw_breakpoint = 0;
4386 static CPUWatchpoint hw_watchpoint;
4388 static int kvm_handle_debug(X86CPU *cpu,
4389 struct kvm_debug_exit_arch *arch_info)
4391 CPUState *cs = CPU(cpu);
4392 CPUX86State *env = &cpu->env;
4393 int ret = 0;
4394 int n;
4396 if (arch_info->exception == EXCP01_DB) {
4397 if (arch_info->dr6 & DR6_BS) {
4398 if (cs->singlestep_enabled) {
4399 ret = EXCP_DEBUG;
4401 } else {
4402 for (n = 0; n < 4; n++) {
4403 if (arch_info->dr6 & (1 << n)) {
4404 switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
4405 case 0x0:
4406 ret = EXCP_DEBUG;
4407 break;
4408 case 0x1:
4409 ret = EXCP_DEBUG;
4410 cs->watchpoint_hit = &hw_watchpoint;
4411 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
4412 hw_watchpoint.flags = BP_MEM_WRITE;
4413 break;
4414 case 0x3:
4415 ret = EXCP_DEBUG;
4416 cs->watchpoint_hit = &hw_watchpoint;
4417 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
4418 hw_watchpoint.flags = BP_MEM_ACCESS;
4419 break;
4424 } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
4425 ret = EXCP_DEBUG;
4427 if (ret == 0) {
4428 cpu_synchronize_state(cs);
4429 assert(env->exception_nr == -1);
4431 /* pass to guest */
4432 kvm_queue_exception(env, arch_info->exception,
4433 arch_info->exception == EXCP01_DB,
4434 arch_info->dr6);
4435 env->has_error_code = 0;
4438 return ret;
4441 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
4443 const uint8_t type_code[] = {
4444 [GDB_BREAKPOINT_HW] = 0x0,
4445 [GDB_WATCHPOINT_WRITE] = 0x1,
4446 [GDB_WATCHPOINT_ACCESS] = 0x3
4448 const uint8_t len_code[] = {
4449 [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
4451 int n;
4453 if (kvm_sw_breakpoints_active(cpu)) {
4454 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
4456 if (nb_hw_breakpoint > 0) {
4457 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
4458 dbg->arch.debugreg[7] = 0x0600;
4459 for (n = 0; n < nb_hw_breakpoint; n++) {
4460 dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
4461 dbg->arch.debugreg[7] |= (2 << (n * 2)) |
4462 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
4463 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
4468 static bool host_supports_vmx(void)
4470 uint32_t ecx, unused;
4472 host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
4473 return ecx & CPUID_EXT_VMX;
4476 #define VMX_INVALID_GUEST_STATE 0x80000021
4478 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
4480 X86CPU *cpu = X86_CPU(cs);
4481 uint64_t code;
4482 int ret;
4484 switch (run->exit_reason) {
4485 case KVM_EXIT_HLT:
4486 DPRINTF("handle_hlt\n");
4487 qemu_mutex_lock_iothread();
4488 ret = kvm_handle_halt(cpu);
4489 qemu_mutex_unlock_iothread();
4490 break;
4491 case KVM_EXIT_SET_TPR:
4492 ret = 0;
4493 break;
4494 case KVM_EXIT_TPR_ACCESS:
4495 qemu_mutex_lock_iothread();
4496 ret = kvm_handle_tpr_access(cpu);
4497 qemu_mutex_unlock_iothread();
4498 break;
4499 case KVM_EXIT_FAIL_ENTRY:
4500 code = run->fail_entry.hardware_entry_failure_reason;
4501 fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
4502 code);
4503 if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
4504 fprintf(stderr,
4505 "\nIf you're running a guest on an Intel machine without "
4506 "unrestricted mode\n"
4507 "support, the failure can be most likely due to the guest "
4508 "entering an invalid\n"
4509 "state for Intel VT. For example, the guest maybe running "
4510 "in big real mode\n"
4511 "which is not supported on less recent Intel processors."
4512 "\n\n");
4514 ret = -1;
4515 break;
4516 case KVM_EXIT_EXCEPTION:
4517 fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
4518 run->ex.exception, run->ex.error_code);
4519 ret = -1;
4520 break;
4521 case KVM_EXIT_DEBUG:
4522 DPRINTF("kvm_exit_debug\n");
4523 qemu_mutex_lock_iothread();
4524 ret = kvm_handle_debug(cpu, &run->debug.arch);
4525 qemu_mutex_unlock_iothread();
4526 break;
4527 case KVM_EXIT_HYPERV:
4528 ret = kvm_hv_handle_exit(cpu, &run->hyperv);
4529 break;
4530 case KVM_EXIT_IOAPIC_EOI:
4531 ioapic_eoi_broadcast(run->eoi.vector);
4532 ret = 0;
4533 break;
4534 default:
4535 fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
4536 ret = -1;
4537 break;
4540 return ret;
4543 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
4545 X86CPU *cpu = X86_CPU(cs);
4546 CPUX86State *env = &cpu->env;
4548 kvm_cpu_synchronize_state(cs);
4549 return !(env->cr[0] & CR0_PE_MASK) ||
4550 ((env->segs[R_CS].selector & 3) != 3);
4553 void kvm_arch_init_irq_routing(KVMState *s)
4555 if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
4556 /* If kernel can't do irq routing, interrupt source
4557 * override 0->2 cannot be set up as required by HPET.
4558 * So we have to disable it.
4560 no_hpet = 1;
4562 /* We know at this point that we're using the in-kernel
4563 * irqchip, so we can use irqfds, and on x86 we know
4564 * we can use msi via irqfd and GSI routing.
4566 kvm_msi_via_irqfd_allowed = true;
4567 kvm_gsi_routing_allowed = true;
4569 if (kvm_irqchip_is_split()) {
4570 int i;
4572 /* If the ioapic is in QEMU and the lapics are in KVM, reserve
4573 MSI routes for signaling interrupts to the local apics. */
4574 for (i = 0; i < IOAPIC_NUM_PINS; i++) {
4575 if (kvm_irqchip_add_msi_route(s, 0, NULL) < 0) {
4576 error_report("Could not enable split IRQ mode.");
4577 exit(1);
4583 int kvm_arch_irqchip_create(KVMState *s)
4585 int ret;
4586 if (kvm_kernel_irqchip_split()) {
4587 ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
4588 if (ret) {
4589 error_report("Could not enable split irqchip mode: %s",
4590 strerror(-ret));
4591 exit(1);
4592 } else {
4593 DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
4594 kvm_split_irqchip = true;
4595 return 1;
4597 } else {
4598 return 0;
4602 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
4603 uint64_t address, uint32_t data, PCIDevice *dev)
4605 X86IOMMUState *iommu = x86_iommu_get_default();
4607 if (iommu) {
4608 int ret;
4609 MSIMessage src, dst;
4610 X86IOMMUClass *class = X86_IOMMU_GET_CLASS(iommu);
4612 if (!class->int_remap) {
4613 return 0;
4616 src.address = route->u.msi.address_hi;
4617 src.address <<= VTD_MSI_ADDR_HI_SHIFT;
4618 src.address |= route->u.msi.address_lo;
4619 src.data = route->u.msi.data;
4621 ret = class->int_remap(iommu, &src, &dst, dev ? \
4622 pci_requester_id(dev) : \
4623 X86_IOMMU_SID_INVALID);
4624 if (ret) {
4625 trace_kvm_x86_fixup_msi_error(route->gsi);
4626 return 1;
4629 route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
4630 route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
4631 route->u.msi.data = dst.data;
4634 return 0;
4637 typedef struct MSIRouteEntry MSIRouteEntry;
4639 struct MSIRouteEntry {
4640 PCIDevice *dev; /* Device pointer */
4641 int vector; /* MSI/MSIX vector index */
4642 int virq; /* Virtual IRQ index */
4643 QLIST_ENTRY(MSIRouteEntry) list;
4646 /* List of used GSI routes */
4647 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
4648 QLIST_HEAD_INITIALIZER(msi_route_list);
4650 static void kvm_update_msi_routes_all(void *private, bool global,
4651 uint32_t index, uint32_t mask)
4653 int cnt = 0, vector;
4654 MSIRouteEntry *entry;
4655 MSIMessage msg;
4656 PCIDevice *dev;
4658 /* TODO: explicit route update */
4659 QLIST_FOREACH(entry, &msi_route_list, list) {
4660 cnt++;
4661 vector = entry->vector;
4662 dev = entry->dev;
4663 if (msix_enabled(dev) && !msix_is_masked(dev, vector)) {
4664 msg = msix_get_message(dev, vector);
4665 } else if (msi_enabled(dev) && !msi_is_masked(dev, vector)) {
4666 msg = msi_get_message(dev, vector);
4667 } else {
4669 * Either MSI/MSIX is disabled for the device, or the
4670 * specific message was masked out. Skip this one.
4672 continue;
4674 kvm_irqchip_update_msi_route(kvm_state, entry->virq, msg, dev);
4676 kvm_irqchip_commit_routes(kvm_state);
4677 trace_kvm_x86_update_msi_routes(cnt);
4680 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
4681 int vector, PCIDevice *dev)
4683 static bool notify_list_inited = false;
4684 MSIRouteEntry *entry;
4686 if (!dev) {
4687 /* These are (possibly) IOAPIC routes only used for split
4688 * kernel irqchip mode, while what we are housekeeping are
4689 * PCI devices only. */
4690 return 0;
4693 entry = g_new0(MSIRouteEntry, 1);
4694 entry->dev = dev;
4695 entry->vector = vector;
4696 entry->virq = route->gsi;
4697 QLIST_INSERT_HEAD(&msi_route_list, entry, list);
4699 trace_kvm_x86_add_msi_route(route->gsi);
4701 if (!notify_list_inited) {
4702 /* For the first time we do add route, add ourselves into
4703 * IOMMU's IEC notify list if needed. */
4704 X86IOMMUState *iommu = x86_iommu_get_default();
4705 if (iommu) {
4706 x86_iommu_iec_register_notifier(iommu,
4707 kvm_update_msi_routes_all,
4708 NULL);
4710 notify_list_inited = true;
4712 return 0;
4715 int kvm_arch_release_virq_post(int virq)
4717 MSIRouteEntry *entry, *next;
4718 QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
4719 if (entry->virq == virq) {
4720 trace_kvm_x86_remove_msi_route(virq);
4721 QLIST_REMOVE(entry, list);
4722 g_free(entry);
4723 break;
4726 return 0;
4729 int kvm_arch_msi_data_to_gsi(uint32_t data)
4731 abort();