Merge remote-tracking branch 'remotes/maxreitz/tags/pull-block-2020-03-26' into staging
[qemu.git] / target / i386 / kvm.c
blob69eb43d796e6efa8773dd60f8af126f80db1630f
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/reset.h"
28 #include "sysemu/runstate.h"
29 #include "kvm_i386.h"
30 #include "hyperv.h"
31 #include "hyperv-proto.h"
33 #include "exec/gdbstub.h"
34 #include "qemu/host-utils.h"
35 #include "qemu/main-loop.h"
36 #include "qemu/config-file.h"
37 #include "qemu/error-report.h"
38 #include "hw/i386/x86.h"
39 #include "hw/i386/apic.h"
40 #include "hw/i386/apic_internal.h"
41 #include "hw/i386/apic-msidef.h"
42 #include "hw/i386/intel_iommu.h"
43 #include "hw/i386/x86-iommu.h"
44 #include "hw/i386/e820_memory_layout.h"
46 #include "hw/pci/pci.h"
47 #include "hw/pci/msi.h"
48 #include "hw/pci/msix.h"
49 #include "migration/blocker.h"
50 #include "exec/memattrs.h"
51 #include "trace.h"
53 //#define DEBUG_KVM
55 #ifdef DEBUG_KVM
56 #define DPRINTF(fmt, ...) \
57 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
58 #else
59 #define DPRINTF(fmt, ...) \
60 do { } while (0)
61 #endif
63 #define MSR_KVM_WALL_CLOCK 0x11
64 #define MSR_KVM_SYSTEM_TIME 0x12
66 /* A 4096-byte buffer can hold the 8-byte kvm_msrs header, plus
67 * 255 kvm_msr_entry structs */
68 #define MSR_BUF_SIZE 4096
70 static void kvm_init_msrs(X86CPU *cpu);
72 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
73 KVM_CAP_INFO(SET_TSS_ADDR),
74 KVM_CAP_INFO(EXT_CPUID),
75 KVM_CAP_INFO(MP_STATE),
76 KVM_CAP_LAST_INFO
79 static bool has_msr_star;
80 static bool has_msr_hsave_pa;
81 static bool has_msr_tsc_aux;
82 static bool has_msr_tsc_adjust;
83 static bool has_msr_tsc_deadline;
84 static bool has_msr_feature_control;
85 static bool has_msr_misc_enable;
86 static bool has_msr_smbase;
87 static bool has_msr_bndcfgs;
88 static int lm_capable_kernel;
89 static bool has_msr_hv_hypercall;
90 static bool has_msr_hv_crash;
91 static bool has_msr_hv_reset;
92 static bool has_msr_hv_vpindex;
93 static bool hv_vpindex_settable;
94 static bool has_msr_hv_runtime;
95 static bool has_msr_hv_synic;
96 static bool has_msr_hv_stimer;
97 static bool has_msr_hv_frequencies;
98 static bool has_msr_hv_reenlightenment;
99 static bool has_msr_xss;
100 static bool has_msr_umwait;
101 static bool has_msr_spec_ctrl;
102 static bool has_msr_tsx_ctrl;
103 static bool has_msr_virt_ssbd;
104 static bool has_msr_smi_count;
105 static bool has_msr_arch_capabs;
106 static bool has_msr_core_capabs;
107 static bool has_msr_vmx_vmfunc;
108 static bool has_msr_ucode_rev;
110 static uint32_t has_architectural_pmu_version;
111 static uint32_t num_architectural_pmu_gp_counters;
112 static uint32_t num_architectural_pmu_fixed_counters;
114 static int has_xsave;
115 static int has_xcrs;
116 static int has_pit_state2;
117 static int has_exception_payload;
119 static bool has_msr_mcg_ext_ctl;
121 static struct kvm_cpuid2 *cpuid_cache;
122 static struct kvm_msr_list *kvm_feature_msrs;
124 int kvm_has_pit_state2(void)
126 return has_pit_state2;
129 bool kvm_has_smm(void)
131 return kvm_check_extension(kvm_state, KVM_CAP_X86_SMM);
134 bool kvm_has_adjust_clock_stable(void)
136 int ret = kvm_check_extension(kvm_state, KVM_CAP_ADJUST_CLOCK);
138 return (ret == KVM_CLOCK_TSC_STABLE);
141 bool kvm_has_exception_payload(void)
143 return has_exception_payload;
146 bool kvm_allows_irq0_override(void)
148 return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
151 static bool kvm_x2apic_api_set_flags(uint64_t flags)
153 KVMState *s = KVM_STATE(current_accel());
155 return !kvm_vm_enable_cap(s, KVM_CAP_X2APIC_API, 0, flags);
158 #define MEMORIZE(fn, _result) \
159 ({ \
160 static bool _memorized; \
162 if (_memorized) { \
163 return _result; \
165 _memorized = true; \
166 _result = fn; \
169 static bool has_x2apic_api;
171 bool kvm_has_x2apic_api(void)
173 return has_x2apic_api;
176 bool kvm_enable_x2apic(void)
178 return MEMORIZE(
179 kvm_x2apic_api_set_flags(KVM_X2APIC_API_USE_32BIT_IDS |
180 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK),
181 has_x2apic_api);
184 bool kvm_hv_vpindex_settable(void)
186 return hv_vpindex_settable;
189 static int kvm_get_tsc(CPUState *cs)
191 X86CPU *cpu = X86_CPU(cs);
192 CPUX86State *env = &cpu->env;
193 struct {
194 struct kvm_msrs info;
195 struct kvm_msr_entry entries[1];
196 } msr_data = {};
197 int ret;
199 if (env->tsc_valid) {
200 return 0;
203 memset(&msr_data, 0, sizeof(msr_data));
204 msr_data.info.nmsrs = 1;
205 msr_data.entries[0].index = MSR_IA32_TSC;
206 env->tsc_valid = !runstate_is_running();
208 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
209 if (ret < 0) {
210 return ret;
213 assert(ret == 1);
214 env->tsc = msr_data.entries[0].data;
215 return 0;
218 static inline void do_kvm_synchronize_tsc(CPUState *cpu, run_on_cpu_data arg)
220 kvm_get_tsc(cpu);
223 void kvm_synchronize_all_tsc(void)
225 CPUState *cpu;
227 if (kvm_enabled()) {
228 CPU_FOREACH(cpu) {
229 run_on_cpu(cpu, do_kvm_synchronize_tsc, RUN_ON_CPU_NULL);
234 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
236 struct kvm_cpuid2 *cpuid;
237 int r, size;
239 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
240 cpuid = g_malloc0(size);
241 cpuid->nent = max;
242 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
243 if (r == 0 && cpuid->nent >= max) {
244 r = -E2BIG;
246 if (r < 0) {
247 if (r == -E2BIG) {
248 g_free(cpuid);
249 return NULL;
250 } else {
251 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
252 strerror(-r));
253 exit(1);
256 return cpuid;
259 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
260 * for all entries.
262 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
264 struct kvm_cpuid2 *cpuid;
265 int max = 1;
267 if (cpuid_cache != NULL) {
268 return cpuid_cache;
270 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
271 max *= 2;
273 cpuid_cache = cpuid;
274 return cpuid;
277 static const struct kvm_para_features {
278 int cap;
279 int feature;
280 } para_features[] = {
281 { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
282 { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
283 { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
284 { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
287 static int get_para_features(KVMState *s)
289 int i, features = 0;
291 for (i = 0; i < ARRAY_SIZE(para_features); i++) {
292 if (kvm_check_extension(s, para_features[i].cap)) {
293 features |= (1 << para_features[i].feature);
297 return features;
300 static bool host_tsx_blacklisted(void)
302 int family, model, stepping;\
303 char vendor[CPUID_VENDOR_SZ + 1];
305 host_vendor_fms(vendor, &family, &model, &stepping);
307 /* Check if we are running on a Haswell host known to have broken TSX */
308 return !strcmp(vendor, CPUID_VENDOR_INTEL) &&
309 (family == 6) &&
310 ((model == 63 && stepping < 4) ||
311 model == 60 || model == 69 || model == 70);
314 /* Returns the value for a specific register on the cpuid entry
316 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
318 uint32_t ret = 0;
319 switch (reg) {
320 case R_EAX:
321 ret = entry->eax;
322 break;
323 case R_EBX:
324 ret = entry->ebx;
325 break;
326 case R_ECX:
327 ret = entry->ecx;
328 break;
329 case R_EDX:
330 ret = entry->edx;
331 break;
333 return ret;
336 /* Find matching entry for function/index on kvm_cpuid2 struct
338 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
339 uint32_t function,
340 uint32_t index)
342 int i;
343 for (i = 0; i < cpuid->nent; ++i) {
344 if (cpuid->entries[i].function == function &&
345 cpuid->entries[i].index == index) {
346 return &cpuid->entries[i];
349 /* not found: */
350 return NULL;
353 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
354 uint32_t index, int reg)
356 struct kvm_cpuid2 *cpuid;
357 uint32_t ret = 0;
358 uint32_t cpuid_1_edx;
359 bool found = false;
361 cpuid = get_supported_cpuid(s);
363 struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
364 if (entry) {
365 found = true;
366 ret = cpuid_entry_get_reg(entry, reg);
369 /* Fixups for the data returned by KVM, below */
371 if (function == 1 && reg == R_EDX) {
372 /* KVM before 2.6.30 misreports the following features */
373 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
374 } else if (function == 1 && reg == R_ECX) {
375 /* We can set the hypervisor flag, even if KVM does not return it on
376 * GET_SUPPORTED_CPUID
378 ret |= CPUID_EXT_HYPERVISOR;
379 /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
380 * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
381 * and the irqchip is in the kernel.
383 if (kvm_irqchip_in_kernel() &&
384 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
385 ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
388 /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
389 * without the in-kernel irqchip
391 if (!kvm_irqchip_in_kernel()) {
392 ret &= ~CPUID_EXT_X2APIC;
395 if (enable_cpu_pm) {
396 int disable_exits = kvm_check_extension(s,
397 KVM_CAP_X86_DISABLE_EXITS);
399 if (disable_exits & KVM_X86_DISABLE_EXITS_MWAIT) {
400 ret |= CPUID_EXT_MONITOR;
403 } else if (function == 6 && reg == R_EAX) {
404 ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
405 } else if (function == 7 && index == 0 && reg == R_EBX) {
406 if (host_tsx_blacklisted()) {
407 ret &= ~(CPUID_7_0_EBX_RTM | CPUID_7_0_EBX_HLE);
409 } else if (function == 7 && index == 0 && reg == R_ECX) {
410 if (enable_cpu_pm) {
411 ret |= CPUID_7_0_ECX_WAITPKG;
412 } else {
413 ret &= ~CPUID_7_0_ECX_WAITPKG;
415 } else if (function == 7 && index == 0 && reg == R_EDX) {
417 * Linux v4.17-v4.20 incorrectly return ARCH_CAPABILITIES on SVM hosts.
418 * We can detect the bug by checking if MSR_IA32_ARCH_CAPABILITIES is
419 * returned by KVM_GET_MSR_INDEX_LIST.
421 if (!has_msr_arch_capabs) {
422 ret &= ~CPUID_7_0_EDX_ARCH_CAPABILITIES;
424 } else if (function == 0x80000001 && reg == R_ECX) {
426 * It's safe to enable TOPOEXT even if it's not returned by
427 * GET_SUPPORTED_CPUID. Unconditionally enabling TOPOEXT here allows
428 * us to keep CPU models including TOPOEXT runnable on older kernels.
430 ret |= CPUID_EXT3_TOPOEXT;
431 } else if (function == 0x80000001 && reg == R_EDX) {
432 /* On Intel, kvm returns cpuid according to the Intel spec,
433 * so add missing bits according to the AMD spec:
435 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
436 ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
437 } else if (function == KVM_CPUID_FEATURES && reg == R_EAX) {
438 /* kvm_pv_unhalt is reported by GET_SUPPORTED_CPUID, but it can't
439 * be enabled without the in-kernel irqchip
441 if (!kvm_irqchip_in_kernel()) {
442 ret &= ~(1U << KVM_FEATURE_PV_UNHALT);
444 } else if (function == KVM_CPUID_FEATURES && reg == R_EDX) {
445 ret |= 1U << KVM_HINTS_REALTIME;
446 found = 1;
449 /* fallback for older kernels */
450 if ((function == KVM_CPUID_FEATURES) && !found) {
451 ret = get_para_features(s);
454 return ret;
457 uint64_t kvm_arch_get_supported_msr_feature(KVMState *s, uint32_t index)
459 struct {
460 struct kvm_msrs info;
461 struct kvm_msr_entry entries[1];
462 } msr_data = {};
463 uint64_t value;
464 uint32_t ret, can_be_one, must_be_one;
466 if (kvm_feature_msrs == NULL) { /* Host doesn't support feature MSRs */
467 return 0;
470 /* Check if requested MSR is supported feature MSR */
471 int i;
472 for (i = 0; i < kvm_feature_msrs->nmsrs; i++)
473 if (kvm_feature_msrs->indices[i] == index) {
474 break;
476 if (i == kvm_feature_msrs->nmsrs) {
477 return 0; /* if the feature MSR is not supported, simply return 0 */
480 msr_data.info.nmsrs = 1;
481 msr_data.entries[0].index = index;
483 ret = kvm_ioctl(s, KVM_GET_MSRS, &msr_data);
484 if (ret != 1) {
485 error_report("KVM get MSR (index=0x%x) feature failed, %s",
486 index, strerror(-ret));
487 exit(1);
490 value = msr_data.entries[0].data;
491 switch (index) {
492 case MSR_IA32_VMX_PROCBASED_CTLS2:
493 /* KVM forgot to add these bits for some time, do this ourselves. */
494 if (kvm_arch_get_supported_cpuid(s, 0xD, 1, R_ECX) & CPUID_XSAVE_XSAVES) {
495 value |= (uint64_t)VMX_SECONDARY_EXEC_XSAVES << 32;
497 if (kvm_arch_get_supported_cpuid(s, 1, 0, R_ECX) & CPUID_EXT_RDRAND) {
498 value |= (uint64_t)VMX_SECONDARY_EXEC_RDRAND_EXITING << 32;
500 if (kvm_arch_get_supported_cpuid(s, 7, 0, R_EBX) & CPUID_7_0_EBX_INVPCID) {
501 value |= (uint64_t)VMX_SECONDARY_EXEC_ENABLE_INVPCID << 32;
503 if (kvm_arch_get_supported_cpuid(s, 7, 0, R_EBX) & CPUID_7_0_EBX_RDSEED) {
504 value |= (uint64_t)VMX_SECONDARY_EXEC_RDSEED_EXITING << 32;
506 if (kvm_arch_get_supported_cpuid(s, 0x80000001, 0, R_EDX) & CPUID_EXT2_RDTSCP) {
507 value |= (uint64_t)VMX_SECONDARY_EXEC_RDTSCP << 32;
509 /* fall through */
510 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
511 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
512 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
513 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
515 * Return true for bits that can be one, but do not have to be one.
516 * The SDM tells us which bits could have a "must be one" setting,
517 * so we can do the opposite transformation in make_vmx_msr_value.
519 must_be_one = (uint32_t)value;
520 can_be_one = (uint32_t)(value >> 32);
521 return can_be_one & ~must_be_one;
523 default:
524 return value;
529 typedef struct HWPoisonPage {
530 ram_addr_t ram_addr;
531 QLIST_ENTRY(HWPoisonPage) list;
532 } HWPoisonPage;
534 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
535 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
537 static void kvm_unpoison_all(void *param)
539 HWPoisonPage *page, *next_page;
541 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
542 QLIST_REMOVE(page, list);
543 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
544 g_free(page);
548 static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
550 HWPoisonPage *page;
552 QLIST_FOREACH(page, &hwpoison_page_list, list) {
553 if (page->ram_addr == ram_addr) {
554 return;
557 page = g_new(HWPoisonPage, 1);
558 page->ram_addr = ram_addr;
559 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
562 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
563 int *max_banks)
565 int r;
567 r = kvm_check_extension(s, KVM_CAP_MCE);
568 if (r > 0) {
569 *max_banks = r;
570 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
572 return -ENOSYS;
575 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
577 CPUState *cs = CPU(cpu);
578 CPUX86State *env = &cpu->env;
579 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
580 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
581 uint64_t mcg_status = MCG_STATUS_MCIP;
582 int flags = 0;
584 if (code == BUS_MCEERR_AR) {
585 status |= MCI_STATUS_AR | 0x134;
586 mcg_status |= MCG_STATUS_EIPV;
587 } else {
588 status |= 0xc0;
589 mcg_status |= MCG_STATUS_RIPV;
592 flags = cpu_x86_support_mca_broadcast(env) ? MCE_INJECT_BROADCAST : 0;
593 /* We need to read back the value of MSR_EXT_MCG_CTL that was set by the
594 * guest kernel back into env->mcg_ext_ctl.
596 cpu_synchronize_state(cs);
597 if (env->mcg_ext_ctl & MCG_EXT_CTL_LMCE_EN) {
598 mcg_status |= MCG_STATUS_LMCE;
599 flags = 0;
602 cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
603 (MCM_ADDR_PHYS << 6) | 0xc, flags);
606 static void hardware_memory_error(void *host_addr)
608 error_report("QEMU got Hardware memory error at addr %p", host_addr);
609 exit(1);
612 void kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
614 X86CPU *cpu = X86_CPU(c);
615 CPUX86State *env = &cpu->env;
616 ram_addr_t ram_addr;
617 hwaddr paddr;
619 /* If we get an action required MCE, it has been injected by KVM
620 * while the VM was running. An action optional MCE instead should
621 * be coming from the main thread, which qemu_init_sigbus identifies
622 * as the "early kill" thread.
624 assert(code == BUS_MCEERR_AR || code == BUS_MCEERR_AO);
626 if ((env->mcg_cap & MCG_SER_P) && addr) {
627 ram_addr = qemu_ram_addr_from_host(addr);
628 if (ram_addr != RAM_ADDR_INVALID &&
629 kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
630 kvm_hwpoison_page_add(ram_addr);
631 kvm_mce_inject(cpu, paddr, code);
634 * Use different logging severity based on error type.
635 * If there is additional MCE reporting on the hypervisor, QEMU VA
636 * could be another source to identify the PA and MCE details.
638 if (code == BUS_MCEERR_AR) {
639 error_report("Guest MCE Memory Error at QEMU addr %p and "
640 "GUEST addr 0x%" HWADDR_PRIx " of type %s injected",
641 addr, paddr, "BUS_MCEERR_AR");
642 } else {
643 warn_report("Guest MCE Memory Error at QEMU addr %p and "
644 "GUEST addr 0x%" HWADDR_PRIx " of type %s injected",
645 addr, paddr, "BUS_MCEERR_AO");
648 return;
651 if (code == BUS_MCEERR_AO) {
652 warn_report("Hardware memory error at addr %p of type %s "
653 "for memory used by QEMU itself instead of guest system!",
654 addr, "BUS_MCEERR_AO");
658 if (code == BUS_MCEERR_AR) {
659 hardware_memory_error(addr);
662 /* Hope we are lucky for AO MCE */
665 static void kvm_reset_exception(CPUX86State *env)
667 env->exception_nr = -1;
668 env->exception_pending = 0;
669 env->exception_injected = 0;
670 env->exception_has_payload = false;
671 env->exception_payload = 0;
674 static void kvm_queue_exception(CPUX86State *env,
675 int32_t exception_nr,
676 uint8_t exception_has_payload,
677 uint64_t exception_payload)
679 assert(env->exception_nr == -1);
680 assert(!env->exception_pending);
681 assert(!env->exception_injected);
682 assert(!env->exception_has_payload);
684 env->exception_nr = exception_nr;
686 if (has_exception_payload) {
687 env->exception_pending = 1;
689 env->exception_has_payload = exception_has_payload;
690 env->exception_payload = exception_payload;
691 } else {
692 env->exception_injected = 1;
694 if (exception_nr == EXCP01_DB) {
695 assert(exception_has_payload);
696 env->dr[6] = exception_payload;
697 } else if (exception_nr == EXCP0E_PAGE) {
698 assert(exception_has_payload);
699 env->cr[2] = exception_payload;
700 } else {
701 assert(!exception_has_payload);
706 static int kvm_inject_mce_oldstyle(X86CPU *cpu)
708 CPUX86State *env = &cpu->env;
710 if (!kvm_has_vcpu_events() && env->exception_nr == EXCP12_MCHK) {
711 unsigned int bank, bank_num = env->mcg_cap & 0xff;
712 struct kvm_x86_mce mce;
714 kvm_reset_exception(env);
717 * There must be at least one bank in use if an MCE is pending.
718 * Find it and use its values for the event injection.
720 for (bank = 0; bank < bank_num; bank++) {
721 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
722 break;
725 assert(bank < bank_num);
727 mce.bank = bank;
728 mce.status = env->mce_banks[bank * 4 + 1];
729 mce.mcg_status = env->mcg_status;
730 mce.addr = env->mce_banks[bank * 4 + 2];
731 mce.misc = env->mce_banks[bank * 4 + 3];
733 return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
735 return 0;
738 static void cpu_update_state(void *opaque, int running, RunState state)
740 CPUX86State *env = opaque;
742 if (running) {
743 env->tsc_valid = false;
747 unsigned long kvm_arch_vcpu_id(CPUState *cs)
749 X86CPU *cpu = X86_CPU(cs);
750 return cpu->apic_id;
753 #ifndef KVM_CPUID_SIGNATURE_NEXT
754 #define KVM_CPUID_SIGNATURE_NEXT 0x40000100
755 #endif
757 static bool hyperv_enabled(X86CPU *cpu)
759 CPUState *cs = CPU(cpu);
760 return kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0 &&
761 ((cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY) ||
762 cpu->hyperv_features || cpu->hyperv_passthrough);
765 static int kvm_arch_set_tsc_khz(CPUState *cs)
767 X86CPU *cpu = X86_CPU(cs);
768 CPUX86State *env = &cpu->env;
769 int r;
771 if (!env->tsc_khz) {
772 return 0;
775 r = kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL) ?
776 kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) :
777 -ENOTSUP;
778 if (r < 0) {
779 /* When KVM_SET_TSC_KHZ fails, it's an error only if the current
780 * TSC frequency doesn't match the one we want.
782 int cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
783 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
784 -ENOTSUP;
785 if (cur_freq <= 0 || cur_freq != env->tsc_khz) {
786 warn_report("TSC frequency mismatch between "
787 "VM (%" PRId64 " kHz) and host (%d kHz), "
788 "and TSC scaling unavailable",
789 env->tsc_khz, cur_freq);
790 return r;
794 return 0;
797 static bool tsc_is_stable_and_known(CPUX86State *env)
799 if (!env->tsc_khz) {
800 return false;
802 return (env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC)
803 || env->user_tsc_khz;
806 static struct {
807 const char *desc;
808 struct {
809 uint32_t fw;
810 uint32_t bits;
811 } flags[2];
812 uint64_t dependencies;
813 } kvm_hyperv_properties[] = {
814 [HYPERV_FEAT_RELAXED] = {
815 .desc = "relaxed timing (hv-relaxed)",
816 .flags = {
817 {.fw = FEAT_HYPERV_EAX,
818 .bits = HV_HYPERCALL_AVAILABLE},
819 {.fw = FEAT_HV_RECOMM_EAX,
820 .bits = HV_RELAXED_TIMING_RECOMMENDED}
823 [HYPERV_FEAT_VAPIC] = {
824 .desc = "virtual APIC (hv-vapic)",
825 .flags = {
826 {.fw = FEAT_HYPERV_EAX,
827 .bits = HV_HYPERCALL_AVAILABLE | HV_APIC_ACCESS_AVAILABLE},
828 {.fw = FEAT_HV_RECOMM_EAX,
829 .bits = HV_APIC_ACCESS_RECOMMENDED}
832 [HYPERV_FEAT_TIME] = {
833 .desc = "clocksources (hv-time)",
834 .flags = {
835 {.fw = FEAT_HYPERV_EAX,
836 .bits = HV_HYPERCALL_AVAILABLE | HV_TIME_REF_COUNT_AVAILABLE |
837 HV_REFERENCE_TSC_AVAILABLE}
840 [HYPERV_FEAT_CRASH] = {
841 .desc = "crash MSRs (hv-crash)",
842 .flags = {
843 {.fw = FEAT_HYPERV_EDX,
844 .bits = HV_GUEST_CRASH_MSR_AVAILABLE}
847 [HYPERV_FEAT_RESET] = {
848 .desc = "reset MSR (hv-reset)",
849 .flags = {
850 {.fw = FEAT_HYPERV_EAX,
851 .bits = HV_RESET_AVAILABLE}
854 [HYPERV_FEAT_VPINDEX] = {
855 .desc = "VP_INDEX MSR (hv-vpindex)",
856 .flags = {
857 {.fw = FEAT_HYPERV_EAX,
858 .bits = HV_VP_INDEX_AVAILABLE}
861 [HYPERV_FEAT_RUNTIME] = {
862 .desc = "VP_RUNTIME MSR (hv-runtime)",
863 .flags = {
864 {.fw = FEAT_HYPERV_EAX,
865 .bits = HV_VP_RUNTIME_AVAILABLE}
868 [HYPERV_FEAT_SYNIC] = {
869 .desc = "synthetic interrupt controller (hv-synic)",
870 .flags = {
871 {.fw = FEAT_HYPERV_EAX,
872 .bits = HV_SYNIC_AVAILABLE}
875 [HYPERV_FEAT_STIMER] = {
876 .desc = "synthetic timers (hv-stimer)",
877 .flags = {
878 {.fw = FEAT_HYPERV_EAX,
879 .bits = HV_SYNTIMERS_AVAILABLE}
881 .dependencies = BIT(HYPERV_FEAT_SYNIC) | BIT(HYPERV_FEAT_TIME)
883 [HYPERV_FEAT_FREQUENCIES] = {
884 .desc = "frequency MSRs (hv-frequencies)",
885 .flags = {
886 {.fw = FEAT_HYPERV_EAX,
887 .bits = HV_ACCESS_FREQUENCY_MSRS},
888 {.fw = FEAT_HYPERV_EDX,
889 .bits = HV_FREQUENCY_MSRS_AVAILABLE}
892 [HYPERV_FEAT_REENLIGHTENMENT] = {
893 .desc = "reenlightenment MSRs (hv-reenlightenment)",
894 .flags = {
895 {.fw = FEAT_HYPERV_EAX,
896 .bits = HV_ACCESS_REENLIGHTENMENTS_CONTROL}
899 [HYPERV_FEAT_TLBFLUSH] = {
900 .desc = "paravirtualized TLB flush (hv-tlbflush)",
901 .flags = {
902 {.fw = FEAT_HV_RECOMM_EAX,
903 .bits = HV_REMOTE_TLB_FLUSH_RECOMMENDED |
904 HV_EX_PROCESSOR_MASKS_RECOMMENDED}
906 .dependencies = BIT(HYPERV_FEAT_VPINDEX)
908 [HYPERV_FEAT_EVMCS] = {
909 .desc = "enlightened VMCS (hv-evmcs)",
910 .flags = {
911 {.fw = FEAT_HV_RECOMM_EAX,
912 .bits = HV_ENLIGHTENED_VMCS_RECOMMENDED}
914 .dependencies = BIT(HYPERV_FEAT_VAPIC)
916 [HYPERV_FEAT_IPI] = {
917 .desc = "paravirtualized IPI (hv-ipi)",
918 .flags = {
919 {.fw = FEAT_HV_RECOMM_EAX,
920 .bits = HV_CLUSTER_IPI_RECOMMENDED |
921 HV_EX_PROCESSOR_MASKS_RECOMMENDED}
923 .dependencies = BIT(HYPERV_FEAT_VPINDEX)
925 [HYPERV_FEAT_STIMER_DIRECT] = {
926 .desc = "direct mode synthetic timers (hv-stimer-direct)",
927 .flags = {
928 {.fw = FEAT_HYPERV_EDX,
929 .bits = HV_STIMER_DIRECT_MODE_AVAILABLE}
931 .dependencies = BIT(HYPERV_FEAT_STIMER)
935 static struct kvm_cpuid2 *try_get_hv_cpuid(CPUState *cs, int max)
937 struct kvm_cpuid2 *cpuid;
938 int r, size;
940 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
941 cpuid = g_malloc0(size);
942 cpuid->nent = max;
944 r = kvm_vcpu_ioctl(cs, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
945 if (r == 0 && cpuid->nent >= max) {
946 r = -E2BIG;
948 if (r < 0) {
949 if (r == -E2BIG) {
950 g_free(cpuid);
951 return NULL;
952 } else {
953 fprintf(stderr, "KVM_GET_SUPPORTED_HV_CPUID failed: %s\n",
954 strerror(-r));
955 exit(1);
958 return cpuid;
962 * Run KVM_GET_SUPPORTED_HV_CPUID ioctl(), allocating a buffer large enough
963 * for all entries.
965 static struct kvm_cpuid2 *get_supported_hv_cpuid(CPUState *cs)
967 struct kvm_cpuid2 *cpuid;
968 int max = 7; /* 0x40000000..0x40000005, 0x4000000A */
971 * When the buffer is too small, KVM_GET_SUPPORTED_HV_CPUID fails with
972 * -E2BIG, however, it doesn't report back the right size. Keep increasing
973 * it and re-trying until we succeed.
975 while ((cpuid = try_get_hv_cpuid(cs, max)) == NULL) {
976 max++;
978 return cpuid;
982 * When KVM_GET_SUPPORTED_HV_CPUID is not supported we fill CPUID feature
983 * leaves from KVM_CAP_HYPERV* and present MSRs data.
985 static struct kvm_cpuid2 *get_supported_hv_cpuid_legacy(CPUState *cs)
987 X86CPU *cpu = X86_CPU(cs);
988 struct kvm_cpuid2 *cpuid;
989 struct kvm_cpuid_entry2 *entry_feat, *entry_recomm;
991 /* HV_CPUID_FEATURES, HV_CPUID_ENLIGHTMENT_INFO */
992 cpuid = g_malloc0(sizeof(*cpuid) + 2 * sizeof(*cpuid->entries));
993 cpuid->nent = 2;
995 /* HV_CPUID_VENDOR_AND_MAX_FUNCTIONS */
996 entry_feat = &cpuid->entries[0];
997 entry_feat->function = HV_CPUID_FEATURES;
999 entry_recomm = &cpuid->entries[1];
1000 entry_recomm->function = HV_CPUID_ENLIGHTMENT_INFO;
1001 entry_recomm->ebx = cpu->hyperv_spinlock_attempts;
1003 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0) {
1004 entry_feat->eax |= HV_HYPERCALL_AVAILABLE;
1005 entry_feat->eax |= HV_APIC_ACCESS_AVAILABLE;
1006 entry_feat->edx |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
1007 entry_recomm->eax |= HV_RELAXED_TIMING_RECOMMENDED;
1008 entry_recomm->eax |= HV_APIC_ACCESS_RECOMMENDED;
1011 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) > 0) {
1012 entry_feat->eax |= HV_TIME_REF_COUNT_AVAILABLE;
1013 entry_feat->eax |= HV_REFERENCE_TSC_AVAILABLE;
1016 if (has_msr_hv_frequencies) {
1017 entry_feat->eax |= HV_ACCESS_FREQUENCY_MSRS;
1018 entry_feat->edx |= HV_FREQUENCY_MSRS_AVAILABLE;
1021 if (has_msr_hv_crash) {
1022 entry_feat->edx |= HV_GUEST_CRASH_MSR_AVAILABLE;
1025 if (has_msr_hv_reenlightenment) {
1026 entry_feat->eax |= HV_ACCESS_REENLIGHTENMENTS_CONTROL;
1029 if (has_msr_hv_reset) {
1030 entry_feat->eax |= HV_RESET_AVAILABLE;
1033 if (has_msr_hv_vpindex) {
1034 entry_feat->eax |= HV_VP_INDEX_AVAILABLE;
1037 if (has_msr_hv_runtime) {
1038 entry_feat->eax |= HV_VP_RUNTIME_AVAILABLE;
1041 if (has_msr_hv_synic) {
1042 unsigned int cap = cpu->hyperv_synic_kvm_only ?
1043 KVM_CAP_HYPERV_SYNIC : KVM_CAP_HYPERV_SYNIC2;
1045 if (kvm_check_extension(cs->kvm_state, cap) > 0) {
1046 entry_feat->eax |= HV_SYNIC_AVAILABLE;
1050 if (has_msr_hv_stimer) {
1051 entry_feat->eax |= HV_SYNTIMERS_AVAILABLE;
1054 if (kvm_check_extension(cs->kvm_state,
1055 KVM_CAP_HYPERV_TLBFLUSH) > 0) {
1056 entry_recomm->eax |= HV_REMOTE_TLB_FLUSH_RECOMMENDED;
1057 entry_recomm->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
1060 if (kvm_check_extension(cs->kvm_state,
1061 KVM_CAP_HYPERV_ENLIGHTENED_VMCS) > 0) {
1062 entry_recomm->eax |= HV_ENLIGHTENED_VMCS_RECOMMENDED;
1065 if (kvm_check_extension(cs->kvm_state,
1066 KVM_CAP_HYPERV_SEND_IPI) > 0) {
1067 entry_recomm->eax |= HV_CLUSTER_IPI_RECOMMENDED;
1068 entry_recomm->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
1071 return cpuid;
1074 static int hv_cpuid_get_fw(struct kvm_cpuid2 *cpuid, int fw, uint32_t *r)
1076 struct kvm_cpuid_entry2 *entry;
1077 uint32_t func;
1078 int reg;
1080 switch (fw) {
1081 case FEAT_HYPERV_EAX:
1082 reg = R_EAX;
1083 func = HV_CPUID_FEATURES;
1084 break;
1085 case FEAT_HYPERV_EDX:
1086 reg = R_EDX;
1087 func = HV_CPUID_FEATURES;
1088 break;
1089 case FEAT_HV_RECOMM_EAX:
1090 reg = R_EAX;
1091 func = HV_CPUID_ENLIGHTMENT_INFO;
1092 break;
1093 default:
1094 return -EINVAL;
1097 entry = cpuid_find_entry(cpuid, func, 0);
1098 if (!entry) {
1099 return -ENOENT;
1102 switch (reg) {
1103 case R_EAX:
1104 *r = entry->eax;
1105 break;
1106 case R_EDX:
1107 *r = entry->edx;
1108 break;
1109 default:
1110 return -EINVAL;
1113 return 0;
1116 static int hv_cpuid_check_and_set(CPUState *cs, struct kvm_cpuid2 *cpuid,
1117 int feature)
1119 X86CPU *cpu = X86_CPU(cs);
1120 CPUX86State *env = &cpu->env;
1121 uint32_t r, fw, bits;
1122 uint64_t deps;
1123 int i, dep_feat;
1125 if (!hyperv_feat_enabled(cpu, feature) && !cpu->hyperv_passthrough) {
1126 return 0;
1129 deps = kvm_hyperv_properties[feature].dependencies;
1130 while (deps) {
1131 dep_feat = ctz64(deps);
1132 if (!(hyperv_feat_enabled(cpu, dep_feat))) {
1133 fprintf(stderr,
1134 "Hyper-V %s requires Hyper-V %s\n",
1135 kvm_hyperv_properties[feature].desc,
1136 kvm_hyperv_properties[dep_feat].desc);
1137 return 1;
1139 deps &= ~(1ull << dep_feat);
1142 for (i = 0; i < ARRAY_SIZE(kvm_hyperv_properties[feature].flags); i++) {
1143 fw = kvm_hyperv_properties[feature].flags[i].fw;
1144 bits = kvm_hyperv_properties[feature].flags[i].bits;
1146 if (!fw) {
1147 continue;
1150 if (hv_cpuid_get_fw(cpuid, fw, &r) || (r & bits) != bits) {
1151 if (hyperv_feat_enabled(cpu, feature)) {
1152 fprintf(stderr,
1153 "Hyper-V %s is not supported by kernel\n",
1154 kvm_hyperv_properties[feature].desc);
1155 return 1;
1156 } else {
1157 return 0;
1161 env->features[fw] |= bits;
1164 if (cpu->hyperv_passthrough) {
1165 cpu->hyperv_features |= BIT(feature);
1168 return 0;
1172 * Fill in Hyper-V CPUIDs. Returns the number of entries filled in cpuid_ent in
1173 * case of success, errno < 0 in case of failure and 0 when no Hyper-V
1174 * extentions are enabled.
1176 static int hyperv_handle_properties(CPUState *cs,
1177 struct kvm_cpuid_entry2 *cpuid_ent)
1179 X86CPU *cpu = X86_CPU(cs);
1180 CPUX86State *env = &cpu->env;
1181 struct kvm_cpuid2 *cpuid;
1182 struct kvm_cpuid_entry2 *c;
1183 uint32_t signature[3];
1184 uint32_t cpuid_i = 0;
1185 int r;
1187 if (!hyperv_enabled(cpu))
1188 return 0;
1190 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS) ||
1191 cpu->hyperv_passthrough) {
1192 uint16_t evmcs_version;
1194 r = kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_ENLIGHTENED_VMCS, 0,
1195 (uintptr_t)&evmcs_version);
1197 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS) && r) {
1198 fprintf(stderr, "Hyper-V %s is not supported by kernel\n",
1199 kvm_hyperv_properties[HYPERV_FEAT_EVMCS].desc);
1200 return -ENOSYS;
1203 if (!r) {
1204 env->features[FEAT_HV_RECOMM_EAX] |=
1205 HV_ENLIGHTENED_VMCS_RECOMMENDED;
1206 env->features[FEAT_HV_NESTED_EAX] = evmcs_version;
1210 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_CPUID) > 0) {
1211 cpuid = get_supported_hv_cpuid(cs);
1212 } else {
1213 cpuid = get_supported_hv_cpuid_legacy(cs);
1216 if (cpu->hyperv_passthrough) {
1217 memcpy(cpuid_ent, &cpuid->entries[0],
1218 cpuid->nent * sizeof(cpuid->entries[0]));
1220 c = cpuid_find_entry(cpuid, HV_CPUID_FEATURES, 0);
1221 if (c) {
1222 env->features[FEAT_HYPERV_EAX] = c->eax;
1223 env->features[FEAT_HYPERV_EBX] = c->ebx;
1224 env->features[FEAT_HYPERV_EDX] = c->eax;
1226 c = cpuid_find_entry(cpuid, HV_CPUID_ENLIGHTMENT_INFO, 0);
1227 if (c) {
1228 env->features[FEAT_HV_RECOMM_EAX] = c->eax;
1230 /* hv-spinlocks may have been overriden */
1231 if (cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY) {
1232 c->ebx = cpu->hyperv_spinlock_attempts;
1235 c = cpuid_find_entry(cpuid, HV_CPUID_NESTED_FEATURES, 0);
1236 if (c) {
1237 env->features[FEAT_HV_NESTED_EAX] = c->eax;
1241 if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_ON) {
1242 env->features[FEAT_HV_RECOMM_EAX] |= HV_NO_NONARCH_CORESHARING;
1243 } else if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_AUTO) {
1244 c = cpuid_find_entry(cpuid, HV_CPUID_ENLIGHTMENT_INFO, 0);
1245 if (c) {
1246 env->features[FEAT_HV_RECOMM_EAX] |=
1247 c->eax & HV_NO_NONARCH_CORESHARING;
1251 /* Features */
1252 r = hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_RELAXED);
1253 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_VAPIC);
1254 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_TIME);
1255 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_CRASH);
1256 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_RESET);
1257 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_VPINDEX);
1258 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_RUNTIME);
1259 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_SYNIC);
1260 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_STIMER);
1261 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_FREQUENCIES);
1262 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_REENLIGHTENMENT);
1263 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_TLBFLUSH);
1264 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_EVMCS);
1265 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_IPI);
1266 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_STIMER_DIRECT);
1268 /* Additional dependencies not covered by kvm_hyperv_properties[] */
1269 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC) &&
1270 !cpu->hyperv_synic_kvm_only &&
1271 !hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)) {
1272 fprintf(stderr, "Hyper-V %s requires Hyper-V %s\n",
1273 kvm_hyperv_properties[HYPERV_FEAT_SYNIC].desc,
1274 kvm_hyperv_properties[HYPERV_FEAT_VPINDEX].desc);
1275 r |= 1;
1278 /* Not exposed by KVM but needed to make CPU hotplug in Windows work */
1279 env->features[FEAT_HYPERV_EDX] |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
1281 if (r) {
1282 r = -ENOSYS;
1283 goto free;
1286 if (cpu->hyperv_passthrough) {
1287 /* We already copied all feature words from KVM as is */
1288 r = cpuid->nent;
1289 goto free;
1292 c = &cpuid_ent[cpuid_i++];
1293 c->function = HV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
1294 if (!cpu->hyperv_vendor_id) {
1295 memcpy(signature, "Microsoft Hv", 12);
1296 } else {
1297 size_t len = strlen(cpu->hyperv_vendor_id);
1299 if (len > 12) {
1300 error_report("hv-vendor-id truncated to 12 characters");
1301 len = 12;
1303 memset(signature, 0, 12);
1304 memcpy(signature, cpu->hyperv_vendor_id, len);
1306 c->eax = hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS) ?
1307 HV_CPUID_NESTED_FEATURES : HV_CPUID_IMPLEMENT_LIMITS;
1308 c->ebx = signature[0];
1309 c->ecx = signature[1];
1310 c->edx = signature[2];
1312 c = &cpuid_ent[cpuid_i++];
1313 c->function = HV_CPUID_INTERFACE;
1314 memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
1315 c->eax = signature[0];
1316 c->ebx = 0;
1317 c->ecx = 0;
1318 c->edx = 0;
1320 c = &cpuid_ent[cpuid_i++];
1321 c->function = HV_CPUID_VERSION;
1322 c->eax = 0x00001bbc;
1323 c->ebx = 0x00060001;
1325 c = &cpuid_ent[cpuid_i++];
1326 c->function = HV_CPUID_FEATURES;
1327 c->eax = env->features[FEAT_HYPERV_EAX];
1328 c->ebx = env->features[FEAT_HYPERV_EBX];
1329 c->edx = env->features[FEAT_HYPERV_EDX];
1331 c = &cpuid_ent[cpuid_i++];
1332 c->function = HV_CPUID_ENLIGHTMENT_INFO;
1333 c->eax = env->features[FEAT_HV_RECOMM_EAX];
1334 c->ebx = cpu->hyperv_spinlock_attempts;
1336 c = &cpuid_ent[cpuid_i++];
1337 c->function = HV_CPUID_IMPLEMENT_LIMITS;
1338 c->eax = cpu->hv_max_vps;
1339 c->ebx = 0x40;
1341 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS)) {
1342 __u32 function;
1344 /* Create zeroed 0x40000006..0x40000009 leaves */
1345 for (function = HV_CPUID_IMPLEMENT_LIMITS + 1;
1346 function < HV_CPUID_NESTED_FEATURES; function++) {
1347 c = &cpuid_ent[cpuid_i++];
1348 c->function = function;
1351 c = &cpuid_ent[cpuid_i++];
1352 c->function = HV_CPUID_NESTED_FEATURES;
1353 c->eax = env->features[FEAT_HV_NESTED_EAX];
1355 r = cpuid_i;
1357 free:
1358 g_free(cpuid);
1360 return r;
1363 static Error *hv_passthrough_mig_blocker;
1364 static Error *hv_no_nonarch_cs_mig_blocker;
1366 static int hyperv_init_vcpu(X86CPU *cpu)
1368 CPUState *cs = CPU(cpu);
1369 Error *local_err = NULL;
1370 int ret;
1372 if (cpu->hyperv_passthrough && hv_passthrough_mig_blocker == NULL) {
1373 error_setg(&hv_passthrough_mig_blocker,
1374 "'hv-passthrough' CPU flag prevents migration, use explicit"
1375 " set of hv-* flags instead");
1376 ret = migrate_add_blocker(hv_passthrough_mig_blocker, &local_err);
1377 if (local_err) {
1378 error_report_err(local_err);
1379 error_free(hv_passthrough_mig_blocker);
1380 return ret;
1384 if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_AUTO &&
1385 hv_no_nonarch_cs_mig_blocker == NULL) {
1386 error_setg(&hv_no_nonarch_cs_mig_blocker,
1387 "'hv-no-nonarch-coresharing=auto' CPU flag prevents migration"
1388 " use explicit 'hv-no-nonarch-coresharing=on' instead (but"
1389 " make sure SMT is disabled and/or that vCPUs are properly"
1390 " pinned)");
1391 ret = migrate_add_blocker(hv_no_nonarch_cs_mig_blocker, &local_err);
1392 if (local_err) {
1393 error_report_err(local_err);
1394 error_free(hv_no_nonarch_cs_mig_blocker);
1395 return ret;
1399 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX) && !hv_vpindex_settable) {
1401 * the kernel doesn't support setting vp_index; assert that its value
1402 * is in sync
1404 struct {
1405 struct kvm_msrs info;
1406 struct kvm_msr_entry entries[1];
1407 } msr_data = {
1408 .info.nmsrs = 1,
1409 .entries[0].index = HV_X64_MSR_VP_INDEX,
1412 ret = kvm_vcpu_ioctl(cs, KVM_GET_MSRS, &msr_data);
1413 if (ret < 0) {
1414 return ret;
1416 assert(ret == 1);
1418 if (msr_data.entries[0].data != hyperv_vp_index(CPU(cpu))) {
1419 error_report("kernel's vp_index != QEMU's vp_index");
1420 return -ENXIO;
1424 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
1425 uint32_t synic_cap = cpu->hyperv_synic_kvm_only ?
1426 KVM_CAP_HYPERV_SYNIC : KVM_CAP_HYPERV_SYNIC2;
1427 ret = kvm_vcpu_enable_cap(cs, synic_cap, 0);
1428 if (ret < 0) {
1429 error_report("failed to turn on HyperV SynIC in KVM: %s",
1430 strerror(-ret));
1431 return ret;
1434 if (!cpu->hyperv_synic_kvm_only) {
1435 ret = hyperv_x86_synic_add(cpu);
1436 if (ret < 0) {
1437 error_report("failed to create HyperV SynIC: %s",
1438 strerror(-ret));
1439 return ret;
1444 return 0;
1447 static Error *invtsc_mig_blocker;
1449 #define KVM_MAX_CPUID_ENTRIES 100
1451 int kvm_arch_init_vcpu(CPUState *cs)
1453 struct {
1454 struct kvm_cpuid2 cpuid;
1455 struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
1456 } cpuid_data;
1458 * The kernel defines these structs with padding fields so there
1459 * should be no extra padding in our cpuid_data struct.
1461 QEMU_BUILD_BUG_ON(sizeof(cpuid_data) !=
1462 sizeof(struct kvm_cpuid2) +
1463 sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES);
1465 X86CPU *cpu = X86_CPU(cs);
1466 CPUX86State *env = &cpu->env;
1467 uint32_t limit, i, j, cpuid_i;
1468 uint32_t unused;
1469 struct kvm_cpuid_entry2 *c;
1470 uint32_t signature[3];
1471 int kvm_base = KVM_CPUID_SIGNATURE;
1472 int max_nested_state_len;
1473 int r;
1474 Error *local_err = NULL;
1476 memset(&cpuid_data, 0, sizeof(cpuid_data));
1478 cpuid_i = 0;
1480 r = kvm_arch_set_tsc_khz(cs);
1481 if (r < 0) {
1482 return r;
1485 /* vcpu's TSC frequency is either specified by user, or following
1486 * the value used by KVM if the former is not present. In the
1487 * latter case, we query it from KVM and record in env->tsc_khz,
1488 * so that vcpu's TSC frequency can be migrated later via this field.
1490 if (!env->tsc_khz) {
1491 r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
1492 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
1493 -ENOTSUP;
1494 if (r > 0) {
1495 env->tsc_khz = r;
1499 /* Paravirtualization CPUIDs */
1500 r = hyperv_handle_properties(cs, cpuid_data.entries);
1501 if (r < 0) {
1502 return r;
1503 } else if (r > 0) {
1504 cpuid_i = r;
1505 kvm_base = KVM_CPUID_SIGNATURE_NEXT;
1506 has_msr_hv_hypercall = true;
1509 if (cpu->expose_kvm) {
1510 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
1511 c = &cpuid_data.entries[cpuid_i++];
1512 c->function = KVM_CPUID_SIGNATURE | kvm_base;
1513 c->eax = KVM_CPUID_FEATURES | kvm_base;
1514 c->ebx = signature[0];
1515 c->ecx = signature[1];
1516 c->edx = signature[2];
1518 c = &cpuid_data.entries[cpuid_i++];
1519 c->function = KVM_CPUID_FEATURES | kvm_base;
1520 c->eax = env->features[FEAT_KVM];
1521 c->edx = env->features[FEAT_KVM_HINTS];
1524 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
1526 for (i = 0; i <= limit; i++) {
1527 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1528 fprintf(stderr, "unsupported level value: 0x%x\n", limit);
1529 abort();
1531 c = &cpuid_data.entries[cpuid_i++];
1533 switch (i) {
1534 case 2: {
1535 /* Keep reading function 2 till all the input is received */
1536 int times;
1538 c->function = i;
1539 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
1540 KVM_CPUID_FLAG_STATE_READ_NEXT;
1541 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1542 times = c->eax & 0xff;
1544 for (j = 1; j < times; ++j) {
1545 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1546 fprintf(stderr, "cpuid_data is full, no space for "
1547 "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
1548 abort();
1550 c = &cpuid_data.entries[cpuid_i++];
1551 c->function = i;
1552 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
1553 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1555 break;
1557 case 0x1f:
1558 if (env->nr_dies < 2) {
1559 break;
1561 case 4:
1562 case 0xb:
1563 case 0xd:
1564 for (j = 0; ; j++) {
1565 if (i == 0xd && j == 64) {
1566 break;
1569 if (i == 0x1f && j == 64) {
1570 break;
1573 c->function = i;
1574 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1575 c->index = j;
1576 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1578 if (i == 4 && c->eax == 0) {
1579 break;
1581 if (i == 0xb && !(c->ecx & 0xff00)) {
1582 break;
1584 if (i == 0x1f && !(c->ecx & 0xff00)) {
1585 break;
1587 if (i == 0xd && c->eax == 0) {
1588 continue;
1590 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1591 fprintf(stderr, "cpuid_data is full, no space for "
1592 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1593 abort();
1595 c = &cpuid_data.entries[cpuid_i++];
1597 break;
1598 case 0x7:
1599 case 0x14: {
1600 uint32_t times;
1602 c->function = i;
1603 c->index = 0;
1604 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1605 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1606 times = c->eax;
1608 for (j = 1; j <= times; ++j) {
1609 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1610 fprintf(stderr, "cpuid_data is full, no space for "
1611 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1612 abort();
1614 c = &cpuid_data.entries[cpuid_i++];
1615 c->function = i;
1616 c->index = j;
1617 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1618 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1620 break;
1622 default:
1623 c->function = i;
1624 c->flags = 0;
1625 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1626 if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
1628 * KVM already returns all zeroes if a CPUID entry is missing,
1629 * so we can omit it and avoid hitting KVM's 80-entry limit.
1631 cpuid_i--;
1633 break;
1637 if (limit >= 0x0a) {
1638 uint32_t eax, edx;
1640 cpu_x86_cpuid(env, 0x0a, 0, &eax, &unused, &unused, &edx);
1642 has_architectural_pmu_version = eax & 0xff;
1643 if (has_architectural_pmu_version > 0) {
1644 num_architectural_pmu_gp_counters = (eax & 0xff00) >> 8;
1646 /* Shouldn't be more than 32, since that's the number of bits
1647 * available in EBX to tell us _which_ counters are available.
1648 * Play it safe.
1650 if (num_architectural_pmu_gp_counters > MAX_GP_COUNTERS) {
1651 num_architectural_pmu_gp_counters = MAX_GP_COUNTERS;
1654 if (has_architectural_pmu_version > 1) {
1655 num_architectural_pmu_fixed_counters = edx & 0x1f;
1657 if (num_architectural_pmu_fixed_counters > MAX_FIXED_COUNTERS) {
1658 num_architectural_pmu_fixed_counters = MAX_FIXED_COUNTERS;
1664 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
1666 for (i = 0x80000000; i <= limit; i++) {
1667 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1668 fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
1669 abort();
1671 c = &cpuid_data.entries[cpuid_i++];
1673 switch (i) {
1674 case 0x8000001d:
1675 /* Query for all AMD cache information leaves */
1676 for (j = 0; ; j++) {
1677 c->function = i;
1678 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1679 c->index = j;
1680 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1682 if (c->eax == 0) {
1683 break;
1685 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1686 fprintf(stderr, "cpuid_data is full, no space for "
1687 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1688 abort();
1690 c = &cpuid_data.entries[cpuid_i++];
1692 break;
1693 default:
1694 c->function = i;
1695 c->flags = 0;
1696 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1697 if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
1699 * KVM already returns all zeroes if a CPUID entry is missing,
1700 * so we can omit it and avoid hitting KVM's 80-entry limit.
1702 cpuid_i--;
1704 break;
1708 /* Call Centaur's CPUID instructions they are supported. */
1709 if (env->cpuid_xlevel2 > 0) {
1710 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
1712 for (i = 0xC0000000; i <= limit; i++) {
1713 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1714 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
1715 abort();
1717 c = &cpuid_data.entries[cpuid_i++];
1719 c->function = i;
1720 c->flags = 0;
1721 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1725 cpuid_data.cpuid.nent = cpuid_i;
1727 if (((env->cpuid_version >> 8)&0xF) >= 6
1728 && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
1729 (CPUID_MCE | CPUID_MCA)
1730 && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
1731 uint64_t mcg_cap, unsupported_caps;
1732 int banks;
1733 int ret;
1735 ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
1736 if (ret < 0) {
1737 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
1738 return ret;
1741 if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
1742 error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
1743 (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
1744 return -ENOTSUP;
1747 unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
1748 if (unsupported_caps) {
1749 if (unsupported_caps & MCG_LMCE_P) {
1750 error_report("kvm: LMCE not supported");
1751 return -ENOTSUP;
1753 warn_report("Unsupported MCG_CAP bits: 0x%" PRIx64,
1754 unsupported_caps);
1757 env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
1758 ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
1759 if (ret < 0) {
1760 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
1761 return ret;
1765 qemu_add_vm_change_state_handler(cpu_update_state, env);
1767 c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
1768 if (c) {
1769 has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
1770 !!(c->ecx & CPUID_EXT_SMX);
1773 if (env->mcg_cap & MCG_LMCE_P) {
1774 has_msr_mcg_ext_ctl = has_msr_feature_control = true;
1777 if (!env->user_tsc_khz) {
1778 if ((env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC) &&
1779 invtsc_mig_blocker == NULL) {
1780 error_setg(&invtsc_mig_blocker,
1781 "State blocked by non-migratable CPU device"
1782 " (invtsc flag)");
1783 r = migrate_add_blocker(invtsc_mig_blocker, &local_err);
1784 if (local_err) {
1785 error_report_err(local_err);
1786 error_free(invtsc_mig_blocker);
1787 return r;
1792 if (cpu->vmware_cpuid_freq
1793 /* Guests depend on 0x40000000 to detect this feature, so only expose
1794 * it if KVM exposes leaf 0x40000000. (Conflicts with Hyper-V) */
1795 && cpu->expose_kvm
1796 && kvm_base == KVM_CPUID_SIGNATURE
1797 /* TSC clock must be stable and known for this feature. */
1798 && tsc_is_stable_and_known(env)) {
1800 c = &cpuid_data.entries[cpuid_i++];
1801 c->function = KVM_CPUID_SIGNATURE | 0x10;
1802 c->eax = env->tsc_khz;
1803 /* LAPIC resolution of 1ns (freq: 1GHz) is hardcoded in KVM's
1804 * APIC_BUS_CYCLE_NS */
1805 c->ebx = 1000000;
1806 c->ecx = c->edx = 0;
1808 c = cpuid_find_entry(&cpuid_data.cpuid, kvm_base, 0);
1809 c->eax = MAX(c->eax, KVM_CPUID_SIGNATURE | 0x10);
1812 cpuid_data.cpuid.nent = cpuid_i;
1814 cpuid_data.cpuid.padding = 0;
1815 r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
1816 if (r) {
1817 goto fail;
1820 if (has_xsave) {
1821 env->xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
1822 memset(env->xsave_buf, 0, sizeof(struct kvm_xsave));
1825 max_nested_state_len = kvm_max_nested_state_length();
1826 if (max_nested_state_len > 0) {
1827 assert(max_nested_state_len >= offsetof(struct kvm_nested_state, data));
1829 if (cpu_has_vmx(env)) {
1830 struct kvm_vmx_nested_state_hdr *vmx_hdr;
1832 env->nested_state = g_malloc0(max_nested_state_len);
1833 env->nested_state->size = max_nested_state_len;
1834 env->nested_state->format = KVM_STATE_NESTED_FORMAT_VMX;
1836 vmx_hdr = &env->nested_state->hdr.vmx;
1837 vmx_hdr->vmxon_pa = -1ull;
1838 vmx_hdr->vmcs12_pa = -1ull;
1842 cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
1844 if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
1845 has_msr_tsc_aux = false;
1848 kvm_init_msrs(cpu);
1850 r = hyperv_init_vcpu(cpu);
1851 if (r) {
1852 goto fail;
1855 return 0;
1857 fail:
1858 migrate_del_blocker(invtsc_mig_blocker);
1860 return r;
1863 int kvm_arch_destroy_vcpu(CPUState *cs)
1865 X86CPU *cpu = X86_CPU(cs);
1866 CPUX86State *env = &cpu->env;
1868 if (cpu->kvm_msr_buf) {
1869 g_free(cpu->kvm_msr_buf);
1870 cpu->kvm_msr_buf = NULL;
1873 if (env->nested_state) {
1874 g_free(env->nested_state);
1875 env->nested_state = NULL;
1878 return 0;
1881 void kvm_arch_reset_vcpu(X86CPU *cpu)
1883 CPUX86State *env = &cpu->env;
1885 env->xcr0 = 1;
1886 if (kvm_irqchip_in_kernel()) {
1887 env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
1888 KVM_MP_STATE_UNINITIALIZED;
1889 } else {
1890 env->mp_state = KVM_MP_STATE_RUNNABLE;
1893 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
1894 int i;
1895 for (i = 0; i < ARRAY_SIZE(env->msr_hv_synic_sint); i++) {
1896 env->msr_hv_synic_sint[i] = HV_SINT_MASKED;
1899 hyperv_x86_synic_reset(cpu);
1901 /* enabled by default */
1902 env->poll_control_msr = 1;
1905 void kvm_arch_do_init_vcpu(X86CPU *cpu)
1907 CPUX86State *env = &cpu->env;
1909 /* APs get directly into wait-for-SIPI state. */
1910 if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
1911 env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
1915 static int kvm_get_supported_feature_msrs(KVMState *s)
1917 int ret = 0;
1919 if (kvm_feature_msrs != NULL) {
1920 return 0;
1923 if (!kvm_check_extension(s, KVM_CAP_GET_MSR_FEATURES)) {
1924 return 0;
1927 struct kvm_msr_list msr_list;
1929 msr_list.nmsrs = 0;
1930 ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, &msr_list);
1931 if (ret < 0 && ret != -E2BIG) {
1932 error_report("Fetch KVM feature MSR list failed: %s",
1933 strerror(-ret));
1934 return ret;
1937 assert(msr_list.nmsrs > 0);
1938 kvm_feature_msrs = (struct kvm_msr_list *) \
1939 g_malloc0(sizeof(msr_list) +
1940 msr_list.nmsrs * sizeof(msr_list.indices[0]));
1942 kvm_feature_msrs->nmsrs = msr_list.nmsrs;
1943 ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, kvm_feature_msrs);
1945 if (ret < 0) {
1946 error_report("Fetch KVM feature MSR list failed: %s",
1947 strerror(-ret));
1948 g_free(kvm_feature_msrs);
1949 kvm_feature_msrs = NULL;
1950 return ret;
1953 return 0;
1956 static int kvm_get_supported_msrs(KVMState *s)
1958 int ret = 0;
1959 struct kvm_msr_list msr_list, *kvm_msr_list;
1962 * Obtain MSR list from KVM. These are the MSRs that we must
1963 * save/restore.
1965 msr_list.nmsrs = 0;
1966 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
1967 if (ret < 0 && ret != -E2BIG) {
1968 return ret;
1971 * Old kernel modules had a bug and could write beyond the provided
1972 * memory. Allocate at least a safe amount of 1K.
1974 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
1975 msr_list.nmsrs *
1976 sizeof(msr_list.indices[0])));
1978 kvm_msr_list->nmsrs = msr_list.nmsrs;
1979 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
1980 if (ret >= 0) {
1981 int i;
1983 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
1984 switch (kvm_msr_list->indices[i]) {
1985 case MSR_STAR:
1986 has_msr_star = true;
1987 break;
1988 case MSR_VM_HSAVE_PA:
1989 has_msr_hsave_pa = true;
1990 break;
1991 case MSR_TSC_AUX:
1992 has_msr_tsc_aux = true;
1993 break;
1994 case MSR_TSC_ADJUST:
1995 has_msr_tsc_adjust = true;
1996 break;
1997 case MSR_IA32_TSCDEADLINE:
1998 has_msr_tsc_deadline = true;
1999 break;
2000 case MSR_IA32_SMBASE:
2001 has_msr_smbase = true;
2002 break;
2003 case MSR_SMI_COUNT:
2004 has_msr_smi_count = true;
2005 break;
2006 case MSR_IA32_MISC_ENABLE:
2007 has_msr_misc_enable = true;
2008 break;
2009 case MSR_IA32_BNDCFGS:
2010 has_msr_bndcfgs = true;
2011 break;
2012 case MSR_IA32_XSS:
2013 has_msr_xss = true;
2014 break;
2015 case MSR_IA32_UMWAIT_CONTROL:
2016 has_msr_umwait = true;
2017 break;
2018 case HV_X64_MSR_CRASH_CTL:
2019 has_msr_hv_crash = true;
2020 break;
2021 case HV_X64_MSR_RESET:
2022 has_msr_hv_reset = true;
2023 break;
2024 case HV_X64_MSR_VP_INDEX:
2025 has_msr_hv_vpindex = true;
2026 break;
2027 case HV_X64_MSR_VP_RUNTIME:
2028 has_msr_hv_runtime = true;
2029 break;
2030 case HV_X64_MSR_SCONTROL:
2031 has_msr_hv_synic = true;
2032 break;
2033 case HV_X64_MSR_STIMER0_CONFIG:
2034 has_msr_hv_stimer = true;
2035 break;
2036 case HV_X64_MSR_TSC_FREQUENCY:
2037 has_msr_hv_frequencies = true;
2038 break;
2039 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2040 has_msr_hv_reenlightenment = true;
2041 break;
2042 case MSR_IA32_SPEC_CTRL:
2043 has_msr_spec_ctrl = true;
2044 break;
2045 case MSR_IA32_TSX_CTRL:
2046 has_msr_tsx_ctrl = true;
2047 break;
2048 case MSR_VIRT_SSBD:
2049 has_msr_virt_ssbd = true;
2050 break;
2051 case MSR_IA32_ARCH_CAPABILITIES:
2052 has_msr_arch_capabs = true;
2053 break;
2054 case MSR_IA32_CORE_CAPABILITY:
2055 has_msr_core_capabs = true;
2056 break;
2057 case MSR_IA32_VMX_VMFUNC:
2058 has_msr_vmx_vmfunc = true;
2059 break;
2060 case MSR_IA32_UCODE_REV:
2061 has_msr_ucode_rev = true;
2062 break;
2067 g_free(kvm_msr_list);
2069 return ret;
2072 static Notifier smram_machine_done;
2073 static KVMMemoryListener smram_listener;
2074 static AddressSpace smram_address_space;
2075 static MemoryRegion smram_as_root;
2076 static MemoryRegion smram_as_mem;
2078 static void register_smram_listener(Notifier *n, void *unused)
2080 MemoryRegion *smram =
2081 (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
2083 /* Outer container... */
2084 memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
2085 memory_region_set_enabled(&smram_as_root, true);
2087 /* ... with two regions inside: normal system memory with low
2088 * priority, and...
2090 memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
2091 get_system_memory(), 0, ~0ull);
2092 memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
2093 memory_region_set_enabled(&smram_as_mem, true);
2095 if (smram) {
2096 /* ... SMRAM with higher priority */
2097 memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
2098 memory_region_set_enabled(smram, true);
2101 address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
2102 kvm_memory_listener_register(kvm_state, &smram_listener,
2103 &smram_address_space, 1);
2106 int kvm_arch_init(MachineState *ms, KVMState *s)
2108 uint64_t identity_base = 0xfffbc000;
2109 uint64_t shadow_mem;
2110 int ret;
2111 struct utsname utsname;
2113 has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
2114 has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
2115 has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
2117 hv_vpindex_settable = kvm_check_extension(s, KVM_CAP_HYPERV_VP_INDEX);
2119 has_exception_payload = kvm_check_extension(s, KVM_CAP_EXCEPTION_PAYLOAD);
2120 if (has_exception_payload) {
2121 ret = kvm_vm_enable_cap(s, KVM_CAP_EXCEPTION_PAYLOAD, 0, true);
2122 if (ret < 0) {
2123 error_report("kvm: Failed to enable exception payload cap: %s",
2124 strerror(-ret));
2125 return ret;
2129 ret = kvm_get_supported_msrs(s);
2130 if (ret < 0) {
2131 return ret;
2134 kvm_get_supported_feature_msrs(s);
2136 uname(&utsname);
2137 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
2140 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
2141 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
2142 * Since these must be part of guest physical memory, we need to allocate
2143 * them, both by setting their start addresses in the kernel and by
2144 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
2146 * Older KVM versions may not support setting the identity map base. In
2147 * that case we need to stick with the default, i.e. a 256K maximum BIOS
2148 * size.
2150 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
2151 /* Allows up to 16M BIOSes. */
2152 identity_base = 0xfeffc000;
2154 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
2155 if (ret < 0) {
2156 return ret;
2160 /* Set TSS base one page after EPT identity map. */
2161 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
2162 if (ret < 0) {
2163 return ret;
2166 /* Tell fw_cfg to notify the BIOS to reserve the range. */
2167 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
2168 if (ret < 0) {
2169 fprintf(stderr, "e820_add_entry() table is full\n");
2170 return ret;
2172 qemu_register_reset(kvm_unpoison_all, NULL);
2174 shadow_mem = object_property_get_int(OBJECT(s), "kvm-shadow-mem", &error_abort);
2175 if (shadow_mem != -1) {
2176 shadow_mem /= 4096;
2177 ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
2178 if (ret < 0) {
2179 return ret;
2183 if (kvm_check_extension(s, KVM_CAP_X86_SMM) &&
2184 object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE) &&
2185 x86_machine_is_smm_enabled(X86_MACHINE(ms))) {
2186 smram_machine_done.notify = register_smram_listener;
2187 qemu_add_machine_init_done_notifier(&smram_machine_done);
2190 if (enable_cpu_pm) {
2191 int disable_exits = kvm_check_extension(s, KVM_CAP_X86_DISABLE_EXITS);
2192 int ret;
2194 /* Work around for kernel header with a typo. TODO: fix header and drop. */
2195 #if defined(KVM_X86_DISABLE_EXITS_HTL) && !defined(KVM_X86_DISABLE_EXITS_HLT)
2196 #define KVM_X86_DISABLE_EXITS_HLT KVM_X86_DISABLE_EXITS_HTL
2197 #endif
2198 if (disable_exits) {
2199 disable_exits &= (KVM_X86_DISABLE_EXITS_MWAIT |
2200 KVM_X86_DISABLE_EXITS_HLT |
2201 KVM_X86_DISABLE_EXITS_PAUSE |
2202 KVM_X86_DISABLE_EXITS_CSTATE);
2205 ret = kvm_vm_enable_cap(s, KVM_CAP_X86_DISABLE_EXITS, 0,
2206 disable_exits);
2207 if (ret < 0) {
2208 error_report("kvm: guest stopping CPU not supported: %s",
2209 strerror(-ret));
2213 return 0;
2216 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2218 lhs->selector = rhs->selector;
2219 lhs->base = rhs->base;
2220 lhs->limit = rhs->limit;
2221 lhs->type = 3;
2222 lhs->present = 1;
2223 lhs->dpl = 3;
2224 lhs->db = 0;
2225 lhs->s = 1;
2226 lhs->l = 0;
2227 lhs->g = 0;
2228 lhs->avl = 0;
2229 lhs->unusable = 0;
2232 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2234 unsigned flags = rhs->flags;
2235 lhs->selector = rhs->selector;
2236 lhs->base = rhs->base;
2237 lhs->limit = rhs->limit;
2238 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
2239 lhs->present = (flags & DESC_P_MASK) != 0;
2240 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
2241 lhs->db = (flags >> DESC_B_SHIFT) & 1;
2242 lhs->s = (flags & DESC_S_MASK) != 0;
2243 lhs->l = (flags >> DESC_L_SHIFT) & 1;
2244 lhs->g = (flags & DESC_G_MASK) != 0;
2245 lhs->avl = (flags & DESC_AVL_MASK) != 0;
2246 lhs->unusable = !lhs->present;
2247 lhs->padding = 0;
2250 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
2252 lhs->selector = rhs->selector;
2253 lhs->base = rhs->base;
2254 lhs->limit = rhs->limit;
2255 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
2256 ((rhs->present && !rhs->unusable) * DESC_P_MASK) |
2257 (rhs->dpl << DESC_DPL_SHIFT) |
2258 (rhs->db << DESC_B_SHIFT) |
2259 (rhs->s * DESC_S_MASK) |
2260 (rhs->l << DESC_L_SHIFT) |
2261 (rhs->g * DESC_G_MASK) |
2262 (rhs->avl * DESC_AVL_MASK);
2265 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
2267 if (set) {
2268 *kvm_reg = *qemu_reg;
2269 } else {
2270 *qemu_reg = *kvm_reg;
2274 static int kvm_getput_regs(X86CPU *cpu, int set)
2276 CPUX86State *env = &cpu->env;
2277 struct kvm_regs regs;
2278 int ret = 0;
2280 if (!set) {
2281 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
2282 if (ret < 0) {
2283 return ret;
2287 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
2288 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
2289 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
2290 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
2291 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
2292 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
2293 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
2294 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
2295 #ifdef TARGET_X86_64
2296 kvm_getput_reg(&regs.r8, &env->regs[8], set);
2297 kvm_getput_reg(&regs.r9, &env->regs[9], set);
2298 kvm_getput_reg(&regs.r10, &env->regs[10], set);
2299 kvm_getput_reg(&regs.r11, &env->regs[11], set);
2300 kvm_getput_reg(&regs.r12, &env->regs[12], set);
2301 kvm_getput_reg(&regs.r13, &env->regs[13], set);
2302 kvm_getput_reg(&regs.r14, &env->regs[14], set);
2303 kvm_getput_reg(&regs.r15, &env->regs[15], set);
2304 #endif
2306 kvm_getput_reg(&regs.rflags, &env->eflags, set);
2307 kvm_getput_reg(&regs.rip, &env->eip, set);
2309 if (set) {
2310 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
2313 return ret;
2316 static int kvm_put_fpu(X86CPU *cpu)
2318 CPUX86State *env = &cpu->env;
2319 struct kvm_fpu fpu;
2320 int i;
2322 memset(&fpu, 0, sizeof fpu);
2323 fpu.fsw = env->fpus & ~(7 << 11);
2324 fpu.fsw |= (env->fpstt & 7) << 11;
2325 fpu.fcw = env->fpuc;
2326 fpu.last_opcode = env->fpop;
2327 fpu.last_ip = env->fpip;
2328 fpu.last_dp = env->fpdp;
2329 for (i = 0; i < 8; ++i) {
2330 fpu.ftwx |= (!env->fptags[i]) << i;
2332 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
2333 for (i = 0; i < CPU_NB_REGS; i++) {
2334 stq_p(&fpu.xmm[i][0], env->xmm_regs[i].ZMM_Q(0));
2335 stq_p(&fpu.xmm[i][8], env->xmm_regs[i].ZMM_Q(1));
2337 fpu.mxcsr = env->mxcsr;
2339 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
2342 #define XSAVE_FCW_FSW 0
2343 #define XSAVE_FTW_FOP 1
2344 #define XSAVE_CWD_RIP 2
2345 #define XSAVE_CWD_RDP 4
2346 #define XSAVE_MXCSR 6
2347 #define XSAVE_ST_SPACE 8
2348 #define XSAVE_XMM_SPACE 40
2349 #define XSAVE_XSTATE_BV 128
2350 #define XSAVE_YMMH_SPACE 144
2351 #define XSAVE_BNDREGS 240
2352 #define XSAVE_BNDCSR 256
2353 #define XSAVE_OPMASK 272
2354 #define XSAVE_ZMM_Hi256 288
2355 #define XSAVE_Hi16_ZMM 416
2356 #define XSAVE_PKRU 672
2358 #define XSAVE_BYTE_OFFSET(word_offset) \
2359 ((word_offset) * sizeof_field(struct kvm_xsave, region[0]))
2361 #define ASSERT_OFFSET(word_offset, field) \
2362 QEMU_BUILD_BUG_ON(XSAVE_BYTE_OFFSET(word_offset) != \
2363 offsetof(X86XSaveArea, field))
2365 ASSERT_OFFSET(XSAVE_FCW_FSW, legacy.fcw);
2366 ASSERT_OFFSET(XSAVE_FTW_FOP, legacy.ftw);
2367 ASSERT_OFFSET(XSAVE_CWD_RIP, legacy.fpip);
2368 ASSERT_OFFSET(XSAVE_CWD_RDP, legacy.fpdp);
2369 ASSERT_OFFSET(XSAVE_MXCSR, legacy.mxcsr);
2370 ASSERT_OFFSET(XSAVE_ST_SPACE, legacy.fpregs);
2371 ASSERT_OFFSET(XSAVE_XMM_SPACE, legacy.xmm_regs);
2372 ASSERT_OFFSET(XSAVE_XSTATE_BV, header.xstate_bv);
2373 ASSERT_OFFSET(XSAVE_YMMH_SPACE, avx_state);
2374 ASSERT_OFFSET(XSAVE_BNDREGS, bndreg_state);
2375 ASSERT_OFFSET(XSAVE_BNDCSR, bndcsr_state);
2376 ASSERT_OFFSET(XSAVE_OPMASK, opmask_state);
2377 ASSERT_OFFSET(XSAVE_ZMM_Hi256, zmm_hi256_state);
2378 ASSERT_OFFSET(XSAVE_Hi16_ZMM, hi16_zmm_state);
2379 ASSERT_OFFSET(XSAVE_PKRU, pkru_state);
2381 static int kvm_put_xsave(X86CPU *cpu)
2383 CPUX86State *env = &cpu->env;
2384 X86XSaveArea *xsave = env->xsave_buf;
2386 if (!has_xsave) {
2387 return kvm_put_fpu(cpu);
2389 x86_cpu_xsave_all_areas(cpu, xsave);
2391 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
2394 static int kvm_put_xcrs(X86CPU *cpu)
2396 CPUX86State *env = &cpu->env;
2397 struct kvm_xcrs xcrs = {};
2399 if (!has_xcrs) {
2400 return 0;
2403 xcrs.nr_xcrs = 1;
2404 xcrs.flags = 0;
2405 xcrs.xcrs[0].xcr = 0;
2406 xcrs.xcrs[0].value = env->xcr0;
2407 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
2410 static int kvm_put_sregs(X86CPU *cpu)
2412 CPUX86State *env = &cpu->env;
2413 struct kvm_sregs sregs;
2415 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
2416 if (env->interrupt_injected >= 0) {
2417 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
2418 (uint64_t)1 << (env->interrupt_injected % 64);
2421 if ((env->eflags & VM_MASK)) {
2422 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
2423 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
2424 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
2425 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
2426 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
2427 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
2428 } else {
2429 set_seg(&sregs.cs, &env->segs[R_CS]);
2430 set_seg(&sregs.ds, &env->segs[R_DS]);
2431 set_seg(&sregs.es, &env->segs[R_ES]);
2432 set_seg(&sregs.fs, &env->segs[R_FS]);
2433 set_seg(&sregs.gs, &env->segs[R_GS]);
2434 set_seg(&sregs.ss, &env->segs[R_SS]);
2437 set_seg(&sregs.tr, &env->tr);
2438 set_seg(&sregs.ldt, &env->ldt);
2440 sregs.idt.limit = env->idt.limit;
2441 sregs.idt.base = env->idt.base;
2442 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
2443 sregs.gdt.limit = env->gdt.limit;
2444 sregs.gdt.base = env->gdt.base;
2445 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
2447 sregs.cr0 = env->cr[0];
2448 sregs.cr2 = env->cr[2];
2449 sregs.cr3 = env->cr[3];
2450 sregs.cr4 = env->cr[4];
2452 sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
2453 sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
2455 sregs.efer = env->efer;
2457 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
2460 static void kvm_msr_buf_reset(X86CPU *cpu)
2462 memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
2465 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
2467 struct kvm_msrs *msrs = cpu->kvm_msr_buf;
2468 void *limit = ((void *)msrs) + MSR_BUF_SIZE;
2469 struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
2471 assert((void *)(entry + 1) <= limit);
2473 entry->index = index;
2474 entry->reserved = 0;
2475 entry->data = value;
2476 msrs->nmsrs++;
2479 static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
2481 kvm_msr_buf_reset(cpu);
2482 kvm_msr_entry_add(cpu, index, value);
2484 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
2487 void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
2489 int ret;
2491 ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
2492 assert(ret == 1);
2495 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
2497 CPUX86State *env = &cpu->env;
2498 int ret;
2500 if (!has_msr_tsc_deadline) {
2501 return 0;
2504 ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
2505 if (ret < 0) {
2506 return ret;
2509 assert(ret == 1);
2510 return 0;
2514 * Provide a separate write service for the feature control MSR in order to
2515 * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
2516 * before writing any other state because forcibly leaving nested mode
2517 * invalidates the VCPU state.
2519 static int kvm_put_msr_feature_control(X86CPU *cpu)
2521 int ret;
2523 if (!has_msr_feature_control) {
2524 return 0;
2527 ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
2528 cpu->env.msr_ia32_feature_control);
2529 if (ret < 0) {
2530 return ret;
2533 assert(ret == 1);
2534 return 0;
2537 static uint64_t make_vmx_msr_value(uint32_t index, uint32_t features)
2539 uint32_t default1, can_be_one, can_be_zero;
2540 uint32_t must_be_one;
2542 switch (index) {
2543 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2544 default1 = 0x00000016;
2545 break;
2546 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2547 default1 = 0x0401e172;
2548 break;
2549 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
2550 default1 = 0x000011ff;
2551 break;
2552 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2553 default1 = 0x00036dff;
2554 break;
2555 case MSR_IA32_VMX_PROCBASED_CTLS2:
2556 default1 = 0;
2557 break;
2558 default:
2559 abort();
2562 /* If a feature bit is set, the control can be either set or clear.
2563 * Otherwise the value is limited to either 0 or 1 by default1.
2565 can_be_one = features | default1;
2566 can_be_zero = features | ~default1;
2567 must_be_one = ~can_be_zero;
2570 * Bit 0:31 -> 0 if the control bit can be zero (i.e. 1 if it must be one).
2571 * Bit 32:63 -> 1 if the control bit can be one.
2573 return must_be_one | (((uint64_t)can_be_one) << 32);
2576 #define VMCS12_MAX_FIELD_INDEX (0x17)
2578 static void kvm_msr_entry_add_vmx(X86CPU *cpu, FeatureWordArray f)
2580 uint64_t kvm_vmx_basic =
2581 kvm_arch_get_supported_msr_feature(kvm_state,
2582 MSR_IA32_VMX_BASIC);
2584 if (!kvm_vmx_basic) {
2585 /* If the kernel doesn't support VMX feature (kvm_intel.nested=0),
2586 * then kvm_vmx_basic will be 0 and KVM_SET_MSR will fail.
2588 return;
2591 uint64_t kvm_vmx_misc =
2592 kvm_arch_get_supported_msr_feature(kvm_state,
2593 MSR_IA32_VMX_MISC);
2594 uint64_t kvm_vmx_ept_vpid =
2595 kvm_arch_get_supported_msr_feature(kvm_state,
2596 MSR_IA32_VMX_EPT_VPID_CAP);
2599 * If the guest is 64-bit, a value of 1 is allowed for the host address
2600 * space size vmexit control.
2602 uint64_t fixed_vmx_exit = f[FEAT_8000_0001_EDX] & CPUID_EXT2_LM
2603 ? (uint64_t)VMX_VM_EXIT_HOST_ADDR_SPACE_SIZE << 32 : 0;
2606 * Bits 0-30, 32-44 and 50-53 come from the host. KVM should
2607 * not change them for backwards compatibility.
2609 uint64_t fixed_vmx_basic = kvm_vmx_basic &
2610 (MSR_VMX_BASIC_VMCS_REVISION_MASK |
2611 MSR_VMX_BASIC_VMXON_REGION_SIZE_MASK |
2612 MSR_VMX_BASIC_VMCS_MEM_TYPE_MASK);
2615 * Same for bits 0-4 and 25-27. Bits 16-24 (CR3 target count) can
2616 * change in the future but are always zero for now, clear them to be
2617 * future proof. Bits 32-63 in theory could change, though KVM does
2618 * not support dual-monitor treatment and probably never will; mask
2619 * them out as well.
2621 uint64_t fixed_vmx_misc = kvm_vmx_misc &
2622 (MSR_VMX_MISC_PREEMPTION_TIMER_SHIFT_MASK |
2623 MSR_VMX_MISC_MAX_MSR_LIST_SIZE_MASK);
2626 * EPT memory types should not change either, so we do not bother
2627 * adding features for them.
2629 uint64_t fixed_vmx_ept_mask =
2630 (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_ENABLE_EPT ?
2631 MSR_VMX_EPT_UC | MSR_VMX_EPT_WB : 0);
2632 uint64_t fixed_vmx_ept_vpid = kvm_vmx_ept_vpid & fixed_vmx_ept_mask;
2634 kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
2635 make_vmx_msr_value(MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
2636 f[FEAT_VMX_PROCBASED_CTLS]));
2637 kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PINBASED_CTLS,
2638 make_vmx_msr_value(MSR_IA32_VMX_TRUE_PINBASED_CTLS,
2639 f[FEAT_VMX_PINBASED_CTLS]));
2640 kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_EXIT_CTLS,
2641 make_vmx_msr_value(MSR_IA32_VMX_TRUE_EXIT_CTLS,
2642 f[FEAT_VMX_EXIT_CTLS]) | fixed_vmx_exit);
2643 kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_ENTRY_CTLS,
2644 make_vmx_msr_value(MSR_IA32_VMX_TRUE_ENTRY_CTLS,
2645 f[FEAT_VMX_ENTRY_CTLS]));
2646 kvm_msr_entry_add(cpu, MSR_IA32_VMX_PROCBASED_CTLS2,
2647 make_vmx_msr_value(MSR_IA32_VMX_PROCBASED_CTLS2,
2648 f[FEAT_VMX_SECONDARY_CTLS]));
2649 kvm_msr_entry_add(cpu, MSR_IA32_VMX_EPT_VPID_CAP,
2650 f[FEAT_VMX_EPT_VPID_CAPS] | fixed_vmx_ept_vpid);
2651 kvm_msr_entry_add(cpu, MSR_IA32_VMX_BASIC,
2652 f[FEAT_VMX_BASIC] | fixed_vmx_basic);
2653 kvm_msr_entry_add(cpu, MSR_IA32_VMX_MISC,
2654 f[FEAT_VMX_MISC] | fixed_vmx_misc);
2655 if (has_msr_vmx_vmfunc) {
2656 kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMFUNC, f[FEAT_VMX_VMFUNC]);
2660 * Just to be safe, write these with constant values. The CRn_FIXED1
2661 * MSRs are generated by KVM based on the vCPU's CPUID.
2663 kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR0_FIXED0,
2664 CR0_PE_MASK | CR0_PG_MASK | CR0_NE_MASK);
2665 kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR4_FIXED0,
2666 CR4_VMXE_MASK);
2667 kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM,
2668 VMCS12_MAX_FIELD_INDEX << 1);
2671 static int kvm_buf_set_msrs(X86CPU *cpu)
2673 int ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
2674 if (ret < 0) {
2675 return ret;
2678 if (ret < cpu->kvm_msr_buf->nmsrs) {
2679 struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
2680 error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,
2681 (uint32_t)e->index, (uint64_t)e->data);
2684 assert(ret == cpu->kvm_msr_buf->nmsrs);
2685 return 0;
2688 static void kvm_init_msrs(X86CPU *cpu)
2690 CPUX86State *env = &cpu->env;
2692 kvm_msr_buf_reset(cpu);
2693 if (has_msr_arch_capabs) {
2694 kvm_msr_entry_add(cpu, MSR_IA32_ARCH_CAPABILITIES,
2695 env->features[FEAT_ARCH_CAPABILITIES]);
2698 if (has_msr_core_capabs) {
2699 kvm_msr_entry_add(cpu, MSR_IA32_CORE_CAPABILITY,
2700 env->features[FEAT_CORE_CAPABILITY]);
2703 if (has_msr_ucode_rev) {
2704 kvm_msr_entry_add(cpu, MSR_IA32_UCODE_REV, cpu->ucode_rev);
2708 * Older kernels do not include VMX MSRs in KVM_GET_MSR_INDEX_LIST, but
2709 * all kernels with MSR features should have them.
2711 if (kvm_feature_msrs && cpu_has_vmx(env)) {
2712 kvm_msr_entry_add_vmx(cpu, env->features);
2715 assert(kvm_buf_set_msrs(cpu) == 0);
2718 static int kvm_put_msrs(X86CPU *cpu, int level)
2720 CPUX86State *env = &cpu->env;
2721 int i;
2723 kvm_msr_buf_reset(cpu);
2725 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
2726 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
2727 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
2728 kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
2729 if (has_msr_star) {
2730 kvm_msr_entry_add(cpu, MSR_STAR, env->star);
2732 if (has_msr_hsave_pa) {
2733 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
2735 if (has_msr_tsc_aux) {
2736 kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
2738 if (has_msr_tsc_adjust) {
2739 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
2741 if (has_msr_misc_enable) {
2742 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
2743 env->msr_ia32_misc_enable);
2745 if (has_msr_smbase) {
2746 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
2748 if (has_msr_smi_count) {
2749 kvm_msr_entry_add(cpu, MSR_SMI_COUNT, env->msr_smi_count);
2751 if (has_msr_bndcfgs) {
2752 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
2754 if (has_msr_xss) {
2755 kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
2757 if (has_msr_umwait) {
2758 kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, env->umwait);
2760 if (has_msr_spec_ctrl) {
2761 kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, env->spec_ctrl);
2763 if (has_msr_tsx_ctrl) {
2764 kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, env->tsx_ctrl);
2766 if (has_msr_virt_ssbd) {
2767 kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, env->virt_ssbd);
2770 #ifdef TARGET_X86_64
2771 if (lm_capable_kernel) {
2772 kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
2773 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
2774 kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
2775 kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
2777 #endif
2780 * The following MSRs have side effects on the guest or are too heavy
2781 * for normal writeback. Limit them to reset or full state updates.
2783 if (level >= KVM_PUT_RESET_STATE) {
2784 kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
2785 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
2786 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
2787 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
2788 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
2790 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
2791 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
2793 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
2794 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
2797 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
2798 kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, env->poll_control_msr);
2801 if (has_architectural_pmu_version > 0) {
2802 if (has_architectural_pmu_version > 1) {
2803 /* Stop the counter. */
2804 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
2805 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
2808 /* Set the counter values. */
2809 for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
2810 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
2811 env->msr_fixed_counters[i]);
2813 for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
2814 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
2815 env->msr_gp_counters[i]);
2816 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
2817 env->msr_gp_evtsel[i]);
2819 if (has_architectural_pmu_version > 1) {
2820 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
2821 env->msr_global_status);
2822 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
2823 env->msr_global_ovf_ctrl);
2825 /* Now start the PMU. */
2826 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
2827 env->msr_fixed_ctr_ctrl);
2828 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
2829 env->msr_global_ctrl);
2833 * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,
2834 * only sync them to KVM on the first cpu
2836 if (current_cpu == first_cpu) {
2837 if (has_msr_hv_hypercall) {
2838 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
2839 env->msr_hv_guest_os_id);
2840 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
2841 env->msr_hv_hypercall);
2843 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
2844 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,
2845 env->msr_hv_tsc);
2847 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
2848 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL,
2849 env->msr_hv_reenlightenment_control);
2850 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL,
2851 env->msr_hv_tsc_emulation_control);
2852 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS,
2853 env->msr_hv_tsc_emulation_status);
2856 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
2857 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
2858 env->msr_hv_vapic);
2860 if (has_msr_hv_crash) {
2861 int j;
2863 for (j = 0; j < HV_CRASH_PARAMS; j++)
2864 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
2865 env->msr_hv_crash_params[j]);
2867 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);
2869 if (has_msr_hv_runtime) {
2870 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
2872 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)
2873 && hv_vpindex_settable) {
2874 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_INDEX,
2875 hyperv_vp_index(CPU(cpu)));
2877 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
2878 int j;
2880 kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);
2882 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
2883 env->msr_hv_synic_control);
2884 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
2885 env->msr_hv_synic_evt_page);
2886 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
2887 env->msr_hv_synic_msg_page);
2889 for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
2890 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
2891 env->msr_hv_synic_sint[j]);
2894 if (has_msr_hv_stimer) {
2895 int j;
2897 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
2898 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
2899 env->msr_hv_stimer_config[j]);
2902 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
2903 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
2904 env->msr_hv_stimer_count[j]);
2907 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
2908 uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
2910 kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
2911 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
2912 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
2913 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
2914 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
2915 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
2916 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
2917 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
2918 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
2919 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
2920 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
2921 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
2922 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
2923 /* The CPU GPs if we write to a bit above the physical limit of
2924 * the host CPU (and KVM emulates that)
2926 uint64_t mask = env->mtrr_var[i].mask;
2927 mask &= phys_mask;
2929 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
2930 env->mtrr_var[i].base);
2931 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
2934 if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
2935 int addr_num = kvm_arch_get_supported_cpuid(kvm_state,
2936 0x14, 1, R_EAX) & 0x7;
2938 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL,
2939 env->msr_rtit_ctrl);
2940 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS,
2941 env->msr_rtit_status);
2942 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE,
2943 env->msr_rtit_output_base);
2944 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK,
2945 env->msr_rtit_output_mask);
2946 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH,
2947 env->msr_rtit_cr3_match);
2948 for (i = 0; i < addr_num; i++) {
2949 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i,
2950 env->msr_rtit_addrs[i]);
2954 /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
2955 * kvm_put_msr_feature_control. */
2958 if (env->mcg_cap) {
2959 int i;
2961 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
2962 kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
2963 if (has_msr_mcg_ext_ctl) {
2964 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
2966 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
2967 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
2971 return kvm_buf_set_msrs(cpu);
2975 static int kvm_get_fpu(X86CPU *cpu)
2977 CPUX86State *env = &cpu->env;
2978 struct kvm_fpu fpu;
2979 int i, ret;
2981 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
2982 if (ret < 0) {
2983 return ret;
2986 env->fpstt = (fpu.fsw >> 11) & 7;
2987 env->fpus = fpu.fsw;
2988 env->fpuc = fpu.fcw;
2989 env->fpop = fpu.last_opcode;
2990 env->fpip = fpu.last_ip;
2991 env->fpdp = fpu.last_dp;
2992 for (i = 0; i < 8; ++i) {
2993 env->fptags[i] = !((fpu.ftwx >> i) & 1);
2995 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
2996 for (i = 0; i < CPU_NB_REGS; i++) {
2997 env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
2998 env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
3000 env->mxcsr = fpu.mxcsr;
3002 return 0;
3005 static int kvm_get_xsave(X86CPU *cpu)
3007 CPUX86State *env = &cpu->env;
3008 X86XSaveArea *xsave = env->xsave_buf;
3009 int ret;
3011 if (!has_xsave) {
3012 return kvm_get_fpu(cpu);
3015 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
3016 if (ret < 0) {
3017 return ret;
3019 x86_cpu_xrstor_all_areas(cpu, xsave);
3021 return 0;
3024 static int kvm_get_xcrs(X86CPU *cpu)
3026 CPUX86State *env = &cpu->env;
3027 int i, ret;
3028 struct kvm_xcrs xcrs;
3030 if (!has_xcrs) {
3031 return 0;
3034 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
3035 if (ret < 0) {
3036 return ret;
3039 for (i = 0; i < xcrs.nr_xcrs; i++) {
3040 /* Only support xcr0 now */
3041 if (xcrs.xcrs[i].xcr == 0) {
3042 env->xcr0 = xcrs.xcrs[i].value;
3043 break;
3046 return 0;
3049 static int kvm_get_sregs(X86CPU *cpu)
3051 CPUX86State *env = &cpu->env;
3052 struct kvm_sregs sregs;
3053 int bit, i, ret;
3055 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
3056 if (ret < 0) {
3057 return ret;
3060 /* There can only be one pending IRQ set in the bitmap at a time, so try
3061 to find it and save its number instead (-1 for none). */
3062 env->interrupt_injected = -1;
3063 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
3064 if (sregs.interrupt_bitmap[i]) {
3065 bit = ctz64(sregs.interrupt_bitmap[i]);
3066 env->interrupt_injected = i * 64 + bit;
3067 break;
3071 get_seg(&env->segs[R_CS], &sregs.cs);
3072 get_seg(&env->segs[R_DS], &sregs.ds);
3073 get_seg(&env->segs[R_ES], &sregs.es);
3074 get_seg(&env->segs[R_FS], &sregs.fs);
3075 get_seg(&env->segs[R_GS], &sregs.gs);
3076 get_seg(&env->segs[R_SS], &sregs.ss);
3078 get_seg(&env->tr, &sregs.tr);
3079 get_seg(&env->ldt, &sregs.ldt);
3081 env->idt.limit = sregs.idt.limit;
3082 env->idt.base = sregs.idt.base;
3083 env->gdt.limit = sregs.gdt.limit;
3084 env->gdt.base = sregs.gdt.base;
3086 env->cr[0] = sregs.cr0;
3087 env->cr[2] = sregs.cr2;
3088 env->cr[3] = sregs.cr3;
3089 env->cr[4] = sregs.cr4;
3091 env->efer = sregs.efer;
3093 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
3094 x86_update_hflags(env);
3096 return 0;
3099 static int kvm_get_msrs(X86CPU *cpu)
3101 CPUX86State *env = &cpu->env;
3102 struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
3103 int ret, i;
3104 uint64_t mtrr_top_bits;
3106 kvm_msr_buf_reset(cpu);
3108 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
3109 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
3110 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
3111 kvm_msr_entry_add(cpu, MSR_PAT, 0);
3112 if (has_msr_star) {
3113 kvm_msr_entry_add(cpu, MSR_STAR, 0);
3115 if (has_msr_hsave_pa) {
3116 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
3118 if (has_msr_tsc_aux) {
3119 kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
3121 if (has_msr_tsc_adjust) {
3122 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
3124 if (has_msr_tsc_deadline) {
3125 kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
3127 if (has_msr_misc_enable) {
3128 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
3130 if (has_msr_smbase) {
3131 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
3133 if (has_msr_smi_count) {
3134 kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
3136 if (has_msr_feature_control) {
3137 kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
3139 if (has_msr_bndcfgs) {
3140 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
3142 if (has_msr_xss) {
3143 kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
3145 if (has_msr_umwait) {
3146 kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, 0);
3148 if (has_msr_spec_ctrl) {
3149 kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
3151 if (has_msr_tsx_ctrl) {
3152 kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, 0);
3154 if (has_msr_virt_ssbd) {
3155 kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, 0);
3157 if (!env->tsc_valid) {
3158 kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
3159 env->tsc_valid = !runstate_is_running();
3162 #ifdef TARGET_X86_64
3163 if (lm_capable_kernel) {
3164 kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
3165 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
3166 kvm_msr_entry_add(cpu, MSR_FMASK, 0);
3167 kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
3169 #endif
3170 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
3171 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
3172 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
3173 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
3175 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
3176 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
3178 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
3179 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
3181 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
3182 kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, 1);
3184 if (has_architectural_pmu_version > 0) {
3185 if (has_architectural_pmu_version > 1) {
3186 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
3187 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
3188 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
3189 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
3191 for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
3192 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
3194 for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
3195 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
3196 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
3200 if (env->mcg_cap) {
3201 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
3202 kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
3203 if (has_msr_mcg_ext_ctl) {
3204 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
3206 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3207 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
3211 if (has_msr_hv_hypercall) {
3212 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
3213 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
3215 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3216 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
3218 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
3219 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
3221 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
3222 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL, 0);
3223 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL, 0);
3224 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS, 0);
3226 if (has_msr_hv_crash) {
3227 int j;
3229 for (j = 0; j < HV_CRASH_PARAMS; j++) {
3230 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
3233 if (has_msr_hv_runtime) {
3234 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
3236 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3237 uint32_t msr;
3239 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
3240 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
3241 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
3242 for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
3243 kvm_msr_entry_add(cpu, msr, 0);
3246 if (has_msr_hv_stimer) {
3247 uint32_t msr;
3249 for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
3250 msr++) {
3251 kvm_msr_entry_add(cpu, msr, 0);
3254 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3255 kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
3256 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
3257 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
3258 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
3259 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
3260 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
3261 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
3262 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
3263 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
3264 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
3265 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
3266 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
3267 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
3268 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
3269 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
3273 if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
3274 int addr_num =
3275 kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
3277 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
3278 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
3279 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
3280 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
3281 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
3282 for (i = 0; i < addr_num; i++) {
3283 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
3287 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
3288 if (ret < 0) {
3289 return ret;
3292 if (ret < cpu->kvm_msr_buf->nmsrs) {
3293 struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
3294 error_report("error: failed to get MSR 0x%" PRIx32,
3295 (uint32_t)e->index);
3298 assert(ret == cpu->kvm_msr_buf->nmsrs);
3300 * MTRR masks: Each mask consists of 5 parts
3301 * a 10..0: must be zero
3302 * b 11 : valid bit
3303 * c n-1.12: actual mask bits
3304 * d 51..n: reserved must be zero
3305 * e 63.52: reserved must be zero
3307 * 'n' is the number of physical bits supported by the CPU and is
3308 * apparently always <= 52. We know our 'n' but don't know what
3309 * the destinations 'n' is; it might be smaller, in which case
3310 * it masks (c) on loading. It might be larger, in which case
3311 * we fill 'd' so that d..c is consistent irrespetive of the 'n'
3312 * we're migrating to.
3315 if (cpu->fill_mtrr_mask) {
3316 QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
3317 assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
3318 mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
3319 } else {
3320 mtrr_top_bits = 0;
3323 for (i = 0; i < ret; i++) {
3324 uint32_t index = msrs[i].index;
3325 switch (index) {
3326 case MSR_IA32_SYSENTER_CS:
3327 env->sysenter_cs = msrs[i].data;
3328 break;
3329 case MSR_IA32_SYSENTER_ESP:
3330 env->sysenter_esp = msrs[i].data;
3331 break;
3332 case MSR_IA32_SYSENTER_EIP:
3333 env->sysenter_eip = msrs[i].data;
3334 break;
3335 case MSR_PAT:
3336 env->pat = msrs[i].data;
3337 break;
3338 case MSR_STAR:
3339 env->star = msrs[i].data;
3340 break;
3341 #ifdef TARGET_X86_64
3342 case MSR_CSTAR:
3343 env->cstar = msrs[i].data;
3344 break;
3345 case MSR_KERNELGSBASE:
3346 env->kernelgsbase = msrs[i].data;
3347 break;
3348 case MSR_FMASK:
3349 env->fmask = msrs[i].data;
3350 break;
3351 case MSR_LSTAR:
3352 env->lstar = msrs[i].data;
3353 break;
3354 #endif
3355 case MSR_IA32_TSC:
3356 env->tsc = msrs[i].data;
3357 break;
3358 case MSR_TSC_AUX:
3359 env->tsc_aux = msrs[i].data;
3360 break;
3361 case MSR_TSC_ADJUST:
3362 env->tsc_adjust = msrs[i].data;
3363 break;
3364 case MSR_IA32_TSCDEADLINE:
3365 env->tsc_deadline = msrs[i].data;
3366 break;
3367 case MSR_VM_HSAVE_PA:
3368 env->vm_hsave = msrs[i].data;
3369 break;
3370 case MSR_KVM_SYSTEM_TIME:
3371 env->system_time_msr = msrs[i].data;
3372 break;
3373 case MSR_KVM_WALL_CLOCK:
3374 env->wall_clock_msr = msrs[i].data;
3375 break;
3376 case MSR_MCG_STATUS:
3377 env->mcg_status = msrs[i].data;
3378 break;
3379 case MSR_MCG_CTL:
3380 env->mcg_ctl = msrs[i].data;
3381 break;
3382 case MSR_MCG_EXT_CTL:
3383 env->mcg_ext_ctl = msrs[i].data;
3384 break;
3385 case MSR_IA32_MISC_ENABLE:
3386 env->msr_ia32_misc_enable = msrs[i].data;
3387 break;
3388 case MSR_IA32_SMBASE:
3389 env->smbase = msrs[i].data;
3390 break;
3391 case MSR_SMI_COUNT:
3392 env->msr_smi_count = msrs[i].data;
3393 break;
3394 case MSR_IA32_FEATURE_CONTROL:
3395 env->msr_ia32_feature_control = msrs[i].data;
3396 break;
3397 case MSR_IA32_BNDCFGS:
3398 env->msr_bndcfgs = msrs[i].data;
3399 break;
3400 case MSR_IA32_XSS:
3401 env->xss = msrs[i].data;
3402 break;
3403 case MSR_IA32_UMWAIT_CONTROL:
3404 env->umwait = msrs[i].data;
3405 break;
3406 default:
3407 if (msrs[i].index >= MSR_MC0_CTL &&
3408 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
3409 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
3411 break;
3412 case MSR_KVM_ASYNC_PF_EN:
3413 env->async_pf_en_msr = msrs[i].data;
3414 break;
3415 case MSR_KVM_PV_EOI_EN:
3416 env->pv_eoi_en_msr = msrs[i].data;
3417 break;
3418 case MSR_KVM_STEAL_TIME:
3419 env->steal_time_msr = msrs[i].data;
3420 break;
3421 case MSR_KVM_POLL_CONTROL: {
3422 env->poll_control_msr = msrs[i].data;
3423 break;
3425 case MSR_CORE_PERF_FIXED_CTR_CTRL:
3426 env->msr_fixed_ctr_ctrl = msrs[i].data;
3427 break;
3428 case MSR_CORE_PERF_GLOBAL_CTRL:
3429 env->msr_global_ctrl = msrs[i].data;
3430 break;
3431 case MSR_CORE_PERF_GLOBAL_STATUS:
3432 env->msr_global_status = msrs[i].data;
3433 break;
3434 case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
3435 env->msr_global_ovf_ctrl = msrs[i].data;
3436 break;
3437 case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
3438 env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
3439 break;
3440 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
3441 env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
3442 break;
3443 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
3444 env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
3445 break;
3446 case HV_X64_MSR_HYPERCALL:
3447 env->msr_hv_hypercall = msrs[i].data;
3448 break;
3449 case HV_X64_MSR_GUEST_OS_ID:
3450 env->msr_hv_guest_os_id = msrs[i].data;
3451 break;
3452 case HV_X64_MSR_APIC_ASSIST_PAGE:
3453 env->msr_hv_vapic = msrs[i].data;
3454 break;
3455 case HV_X64_MSR_REFERENCE_TSC:
3456 env->msr_hv_tsc = msrs[i].data;
3457 break;
3458 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3459 env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
3460 break;
3461 case HV_X64_MSR_VP_RUNTIME:
3462 env->msr_hv_runtime = msrs[i].data;
3463 break;
3464 case HV_X64_MSR_SCONTROL:
3465 env->msr_hv_synic_control = msrs[i].data;
3466 break;
3467 case HV_X64_MSR_SIEFP:
3468 env->msr_hv_synic_evt_page = msrs[i].data;
3469 break;
3470 case HV_X64_MSR_SIMP:
3471 env->msr_hv_synic_msg_page = msrs[i].data;
3472 break;
3473 case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
3474 env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
3475 break;
3476 case HV_X64_MSR_STIMER0_CONFIG:
3477 case HV_X64_MSR_STIMER1_CONFIG:
3478 case HV_X64_MSR_STIMER2_CONFIG:
3479 case HV_X64_MSR_STIMER3_CONFIG:
3480 env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
3481 msrs[i].data;
3482 break;
3483 case HV_X64_MSR_STIMER0_COUNT:
3484 case HV_X64_MSR_STIMER1_COUNT:
3485 case HV_X64_MSR_STIMER2_COUNT:
3486 case HV_X64_MSR_STIMER3_COUNT:
3487 env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
3488 msrs[i].data;
3489 break;
3490 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3491 env->msr_hv_reenlightenment_control = msrs[i].data;
3492 break;
3493 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3494 env->msr_hv_tsc_emulation_control = msrs[i].data;
3495 break;
3496 case HV_X64_MSR_TSC_EMULATION_STATUS:
3497 env->msr_hv_tsc_emulation_status = msrs[i].data;
3498 break;
3499 case MSR_MTRRdefType:
3500 env->mtrr_deftype = msrs[i].data;
3501 break;
3502 case MSR_MTRRfix64K_00000:
3503 env->mtrr_fixed[0] = msrs[i].data;
3504 break;
3505 case MSR_MTRRfix16K_80000:
3506 env->mtrr_fixed[1] = msrs[i].data;
3507 break;
3508 case MSR_MTRRfix16K_A0000:
3509 env->mtrr_fixed[2] = msrs[i].data;
3510 break;
3511 case MSR_MTRRfix4K_C0000:
3512 env->mtrr_fixed[3] = msrs[i].data;
3513 break;
3514 case MSR_MTRRfix4K_C8000:
3515 env->mtrr_fixed[4] = msrs[i].data;
3516 break;
3517 case MSR_MTRRfix4K_D0000:
3518 env->mtrr_fixed[5] = msrs[i].data;
3519 break;
3520 case MSR_MTRRfix4K_D8000:
3521 env->mtrr_fixed[6] = msrs[i].data;
3522 break;
3523 case MSR_MTRRfix4K_E0000:
3524 env->mtrr_fixed[7] = msrs[i].data;
3525 break;
3526 case MSR_MTRRfix4K_E8000:
3527 env->mtrr_fixed[8] = msrs[i].data;
3528 break;
3529 case MSR_MTRRfix4K_F0000:
3530 env->mtrr_fixed[9] = msrs[i].data;
3531 break;
3532 case MSR_MTRRfix4K_F8000:
3533 env->mtrr_fixed[10] = msrs[i].data;
3534 break;
3535 case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
3536 if (index & 1) {
3537 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
3538 mtrr_top_bits;
3539 } else {
3540 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
3542 break;
3543 case MSR_IA32_SPEC_CTRL:
3544 env->spec_ctrl = msrs[i].data;
3545 break;
3546 case MSR_IA32_TSX_CTRL:
3547 env->tsx_ctrl = msrs[i].data;
3548 break;
3549 case MSR_VIRT_SSBD:
3550 env->virt_ssbd = msrs[i].data;
3551 break;
3552 case MSR_IA32_RTIT_CTL:
3553 env->msr_rtit_ctrl = msrs[i].data;
3554 break;
3555 case MSR_IA32_RTIT_STATUS:
3556 env->msr_rtit_status = msrs[i].data;
3557 break;
3558 case MSR_IA32_RTIT_OUTPUT_BASE:
3559 env->msr_rtit_output_base = msrs[i].data;
3560 break;
3561 case MSR_IA32_RTIT_OUTPUT_MASK:
3562 env->msr_rtit_output_mask = msrs[i].data;
3563 break;
3564 case MSR_IA32_RTIT_CR3_MATCH:
3565 env->msr_rtit_cr3_match = msrs[i].data;
3566 break;
3567 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
3568 env->msr_rtit_addrs[index - MSR_IA32_RTIT_ADDR0_A] = msrs[i].data;
3569 break;
3573 return 0;
3576 static int kvm_put_mp_state(X86CPU *cpu)
3578 struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
3580 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
3583 static int kvm_get_mp_state(X86CPU *cpu)
3585 CPUState *cs = CPU(cpu);
3586 CPUX86State *env = &cpu->env;
3587 struct kvm_mp_state mp_state;
3588 int ret;
3590 ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
3591 if (ret < 0) {
3592 return ret;
3594 env->mp_state = mp_state.mp_state;
3595 if (kvm_irqchip_in_kernel()) {
3596 cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
3598 return 0;
3601 static int kvm_get_apic(X86CPU *cpu)
3603 DeviceState *apic = cpu->apic_state;
3604 struct kvm_lapic_state kapic;
3605 int ret;
3607 if (apic && kvm_irqchip_in_kernel()) {
3608 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
3609 if (ret < 0) {
3610 return ret;
3613 kvm_get_apic_state(apic, &kapic);
3615 return 0;
3618 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
3620 CPUState *cs = CPU(cpu);
3621 CPUX86State *env = &cpu->env;
3622 struct kvm_vcpu_events events = {};
3624 if (!kvm_has_vcpu_events()) {
3625 return 0;
3628 events.flags = 0;
3630 if (has_exception_payload) {
3631 events.flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
3632 events.exception.pending = env->exception_pending;
3633 events.exception_has_payload = env->exception_has_payload;
3634 events.exception_payload = env->exception_payload;
3636 events.exception.nr = env->exception_nr;
3637 events.exception.injected = env->exception_injected;
3638 events.exception.has_error_code = env->has_error_code;
3639 events.exception.error_code = env->error_code;
3641 events.interrupt.injected = (env->interrupt_injected >= 0);
3642 events.interrupt.nr = env->interrupt_injected;
3643 events.interrupt.soft = env->soft_interrupt;
3645 events.nmi.injected = env->nmi_injected;
3646 events.nmi.pending = env->nmi_pending;
3647 events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
3649 events.sipi_vector = env->sipi_vector;
3651 if (has_msr_smbase) {
3652 events.smi.smm = !!(env->hflags & HF_SMM_MASK);
3653 events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
3654 if (kvm_irqchip_in_kernel()) {
3655 /* As soon as these are moved to the kernel, remove them
3656 * from cs->interrupt_request.
3658 events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
3659 events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
3660 cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
3661 } else {
3662 /* Keep these in cs->interrupt_request. */
3663 events.smi.pending = 0;
3664 events.smi.latched_init = 0;
3666 /* Stop SMI delivery on old machine types to avoid a reboot
3667 * on an inward migration of an old VM.
3669 if (!cpu->kvm_no_smi_migration) {
3670 events.flags |= KVM_VCPUEVENT_VALID_SMM;
3674 if (level >= KVM_PUT_RESET_STATE) {
3675 events.flags |= KVM_VCPUEVENT_VALID_NMI_PENDING;
3676 if (env->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
3677 events.flags |= KVM_VCPUEVENT_VALID_SIPI_VECTOR;
3681 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
3684 static int kvm_get_vcpu_events(X86CPU *cpu)
3686 CPUX86State *env = &cpu->env;
3687 struct kvm_vcpu_events events;
3688 int ret;
3690 if (!kvm_has_vcpu_events()) {
3691 return 0;
3694 memset(&events, 0, sizeof(events));
3695 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
3696 if (ret < 0) {
3697 return ret;
3700 if (events.flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
3701 env->exception_pending = events.exception.pending;
3702 env->exception_has_payload = events.exception_has_payload;
3703 env->exception_payload = events.exception_payload;
3704 } else {
3705 env->exception_pending = 0;
3706 env->exception_has_payload = false;
3708 env->exception_injected = events.exception.injected;
3709 env->exception_nr =
3710 (env->exception_pending || env->exception_injected) ?
3711 events.exception.nr : -1;
3712 env->has_error_code = events.exception.has_error_code;
3713 env->error_code = events.exception.error_code;
3715 env->interrupt_injected =
3716 events.interrupt.injected ? events.interrupt.nr : -1;
3717 env->soft_interrupt = events.interrupt.soft;
3719 env->nmi_injected = events.nmi.injected;
3720 env->nmi_pending = events.nmi.pending;
3721 if (events.nmi.masked) {
3722 env->hflags2 |= HF2_NMI_MASK;
3723 } else {
3724 env->hflags2 &= ~HF2_NMI_MASK;
3727 if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
3728 if (events.smi.smm) {
3729 env->hflags |= HF_SMM_MASK;
3730 } else {
3731 env->hflags &= ~HF_SMM_MASK;
3733 if (events.smi.pending) {
3734 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
3735 } else {
3736 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
3738 if (events.smi.smm_inside_nmi) {
3739 env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
3740 } else {
3741 env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
3743 if (events.smi.latched_init) {
3744 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
3745 } else {
3746 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
3750 env->sipi_vector = events.sipi_vector;
3752 return 0;
3755 static int kvm_guest_debug_workarounds(X86CPU *cpu)
3757 CPUState *cs = CPU(cpu);
3758 CPUX86State *env = &cpu->env;
3759 int ret = 0;
3760 unsigned long reinject_trap = 0;
3762 if (!kvm_has_vcpu_events()) {
3763 if (env->exception_nr == EXCP01_DB) {
3764 reinject_trap = KVM_GUESTDBG_INJECT_DB;
3765 } else if (env->exception_injected == EXCP03_INT3) {
3766 reinject_trap = KVM_GUESTDBG_INJECT_BP;
3768 kvm_reset_exception(env);
3772 * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
3773 * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
3774 * by updating the debug state once again if single-stepping is on.
3775 * Another reason to call kvm_update_guest_debug here is a pending debug
3776 * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
3777 * reinject them via SET_GUEST_DEBUG.
3779 if (reinject_trap ||
3780 (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
3781 ret = kvm_update_guest_debug(cs, reinject_trap);
3783 return ret;
3786 static int kvm_put_debugregs(X86CPU *cpu)
3788 CPUX86State *env = &cpu->env;
3789 struct kvm_debugregs dbgregs;
3790 int i;
3792 if (!kvm_has_debugregs()) {
3793 return 0;
3796 memset(&dbgregs, 0, sizeof(dbgregs));
3797 for (i = 0; i < 4; i++) {
3798 dbgregs.db[i] = env->dr[i];
3800 dbgregs.dr6 = env->dr[6];
3801 dbgregs.dr7 = env->dr[7];
3802 dbgregs.flags = 0;
3804 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
3807 static int kvm_get_debugregs(X86CPU *cpu)
3809 CPUX86State *env = &cpu->env;
3810 struct kvm_debugregs dbgregs;
3811 int i, ret;
3813 if (!kvm_has_debugregs()) {
3814 return 0;
3817 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
3818 if (ret < 0) {
3819 return ret;
3821 for (i = 0; i < 4; i++) {
3822 env->dr[i] = dbgregs.db[i];
3824 env->dr[4] = env->dr[6] = dbgregs.dr6;
3825 env->dr[5] = env->dr[7] = dbgregs.dr7;
3827 return 0;
3830 static int kvm_put_nested_state(X86CPU *cpu)
3832 CPUX86State *env = &cpu->env;
3833 int max_nested_state_len = kvm_max_nested_state_length();
3835 if (!env->nested_state) {
3836 return 0;
3839 assert(env->nested_state->size <= max_nested_state_len);
3840 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_NESTED_STATE, env->nested_state);
3843 static int kvm_get_nested_state(X86CPU *cpu)
3845 CPUX86State *env = &cpu->env;
3846 int max_nested_state_len = kvm_max_nested_state_length();
3847 int ret;
3849 if (!env->nested_state) {
3850 return 0;
3854 * It is possible that migration restored a smaller size into
3855 * nested_state->hdr.size than what our kernel support.
3856 * We preserve migration origin nested_state->hdr.size for
3857 * call to KVM_SET_NESTED_STATE but wish that our next call
3858 * to KVM_GET_NESTED_STATE will use max size our kernel support.
3860 env->nested_state->size = max_nested_state_len;
3862 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_NESTED_STATE, env->nested_state);
3863 if (ret < 0) {
3864 return ret;
3867 if (env->nested_state->flags & KVM_STATE_NESTED_GUEST_MODE) {
3868 env->hflags |= HF_GUEST_MASK;
3869 } else {
3870 env->hflags &= ~HF_GUEST_MASK;
3873 return ret;
3876 int kvm_arch_put_registers(CPUState *cpu, int level)
3878 X86CPU *x86_cpu = X86_CPU(cpu);
3879 int ret;
3881 assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
3883 if (level >= KVM_PUT_RESET_STATE) {
3884 ret = kvm_put_nested_state(x86_cpu);
3885 if (ret < 0) {
3886 return ret;
3889 ret = kvm_put_msr_feature_control(x86_cpu);
3890 if (ret < 0) {
3891 return ret;
3895 if (level == KVM_PUT_FULL_STATE) {
3896 /* We don't check for kvm_arch_set_tsc_khz() errors here,
3897 * because TSC frequency mismatch shouldn't abort migration,
3898 * unless the user explicitly asked for a more strict TSC
3899 * setting (e.g. using an explicit "tsc-freq" option).
3901 kvm_arch_set_tsc_khz(cpu);
3904 ret = kvm_getput_regs(x86_cpu, 1);
3905 if (ret < 0) {
3906 return ret;
3908 ret = kvm_put_xsave(x86_cpu);
3909 if (ret < 0) {
3910 return ret;
3912 ret = kvm_put_xcrs(x86_cpu);
3913 if (ret < 0) {
3914 return ret;
3916 ret = kvm_put_sregs(x86_cpu);
3917 if (ret < 0) {
3918 return ret;
3920 /* must be before kvm_put_msrs */
3921 ret = kvm_inject_mce_oldstyle(x86_cpu);
3922 if (ret < 0) {
3923 return ret;
3925 ret = kvm_put_msrs(x86_cpu, level);
3926 if (ret < 0) {
3927 return ret;
3929 ret = kvm_put_vcpu_events(x86_cpu, level);
3930 if (ret < 0) {
3931 return ret;
3933 if (level >= KVM_PUT_RESET_STATE) {
3934 ret = kvm_put_mp_state(x86_cpu);
3935 if (ret < 0) {
3936 return ret;
3940 ret = kvm_put_tscdeadline_msr(x86_cpu);
3941 if (ret < 0) {
3942 return ret;
3944 ret = kvm_put_debugregs(x86_cpu);
3945 if (ret < 0) {
3946 return ret;
3948 /* must be last */
3949 ret = kvm_guest_debug_workarounds(x86_cpu);
3950 if (ret < 0) {
3951 return ret;
3953 return 0;
3956 int kvm_arch_get_registers(CPUState *cs)
3958 X86CPU *cpu = X86_CPU(cs);
3959 int ret;
3961 assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
3963 ret = kvm_get_vcpu_events(cpu);
3964 if (ret < 0) {
3965 goto out;
3968 * KVM_GET_MPSTATE can modify CS and RIP, call it before
3969 * KVM_GET_REGS and KVM_GET_SREGS.
3971 ret = kvm_get_mp_state(cpu);
3972 if (ret < 0) {
3973 goto out;
3975 ret = kvm_getput_regs(cpu, 0);
3976 if (ret < 0) {
3977 goto out;
3979 ret = kvm_get_xsave(cpu);
3980 if (ret < 0) {
3981 goto out;
3983 ret = kvm_get_xcrs(cpu);
3984 if (ret < 0) {
3985 goto out;
3987 ret = kvm_get_sregs(cpu);
3988 if (ret < 0) {
3989 goto out;
3991 ret = kvm_get_msrs(cpu);
3992 if (ret < 0) {
3993 goto out;
3995 ret = kvm_get_apic(cpu);
3996 if (ret < 0) {
3997 goto out;
3999 ret = kvm_get_debugregs(cpu);
4000 if (ret < 0) {
4001 goto out;
4003 ret = kvm_get_nested_state(cpu);
4004 if (ret < 0) {
4005 goto out;
4007 ret = 0;
4008 out:
4009 cpu_sync_bndcs_hflags(&cpu->env);
4010 return ret;
4013 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
4015 X86CPU *x86_cpu = X86_CPU(cpu);
4016 CPUX86State *env = &x86_cpu->env;
4017 int ret;
4019 /* Inject NMI */
4020 if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
4021 if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
4022 qemu_mutex_lock_iothread();
4023 cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
4024 qemu_mutex_unlock_iothread();
4025 DPRINTF("injected NMI\n");
4026 ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
4027 if (ret < 0) {
4028 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
4029 strerror(-ret));
4032 if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
4033 qemu_mutex_lock_iothread();
4034 cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
4035 qemu_mutex_unlock_iothread();
4036 DPRINTF("injected SMI\n");
4037 ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
4038 if (ret < 0) {
4039 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
4040 strerror(-ret));
4045 if (!kvm_pic_in_kernel()) {
4046 qemu_mutex_lock_iothread();
4049 /* Force the VCPU out of its inner loop to process any INIT requests
4050 * or (for userspace APIC, but it is cheap to combine the checks here)
4051 * pending TPR access reports.
4053 if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
4054 if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
4055 !(env->hflags & HF_SMM_MASK)) {
4056 cpu->exit_request = 1;
4058 if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
4059 cpu->exit_request = 1;
4063 if (!kvm_pic_in_kernel()) {
4064 /* Try to inject an interrupt if the guest can accept it */
4065 if (run->ready_for_interrupt_injection &&
4066 (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
4067 (env->eflags & IF_MASK)) {
4068 int irq;
4070 cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
4071 irq = cpu_get_pic_interrupt(env);
4072 if (irq >= 0) {
4073 struct kvm_interrupt intr;
4075 intr.irq = irq;
4076 DPRINTF("injected interrupt %d\n", irq);
4077 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
4078 if (ret < 0) {
4079 fprintf(stderr,
4080 "KVM: injection failed, interrupt lost (%s)\n",
4081 strerror(-ret));
4086 /* If we have an interrupt but the guest is not ready to receive an
4087 * interrupt, request an interrupt window exit. This will
4088 * cause a return to userspace as soon as the guest is ready to
4089 * receive interrupts. */
4090 if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
4091 run->request_interrupt_window = 1;
4092 } else {
4093 run->request_interrupt_window = 0;
4096 DPRINTF("setting tpr\n");
4097 run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
4099 qemu_mutex_unlock_iothread();
4103 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
4105 X86CPU *x86_cpu = X86_CPU(cpu);
4106 CPUX86State *env = &x86_cpu->env;
4108 if (run->flags & KVM_RUN_X86_SMM) {
4109 env->hflags |= HF_SMM_MASK;
4110 } else {
4111 env->hflags &= ~HF_SMM_MASK;
4113 if (run->if_flag) {
4114 env->eflags |= IF_MASK;
4115 } else {
4116 env->eflags &= ~IF_MASK;
4119 /* We need to protect the apic state against concurrent accesses from
4120 * different threads in case the userspace irqchip is used. */
4121 if (!kvm_irqchip_in_kernel()) {
4122 qemu_mutex_lock_iothread();
4124 cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
4125 cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
4126 if (!kvm_irqchip_in_kernel()) {
4127 qemu_mutex_unlock_iothread();
4129 return cpu_get_mem_attrs(env);
4132 int kvm_arch_process_async_events(CPUState *cs)
4134 X86CPU *cpu = X86_CPU(cs);
4135 CPUX86State *env = &cpu->env;
4137 if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
4138 /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
4139 assert(env->mcg_cap);
4141 cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
4143 kvm_cpu_synchronize_state(cs);
4145 if (env->exception_nr == EXCP08_DBLE) {
4146 /* this means triple fault */
4147 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
4148 cs->exit_request = 1;
4149 return 0;
4151 kvm_queue_exception(env, EXCP12_MCHK, 0, 0);
4152 env->has_error_code = 0;
4154 cs->halted = 0;
4155 if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
4156 env->mp_state = KVM_MP_STATE_RUNNABLE;
4160 if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
4161 !(env->hflags & HF_SMM_MASK)) {
4162 kvm_cpu_synchronize_state(cs);
4163 do_cpu_init(cpu);
4166 if (kvm_irqchip_in_kernel()) {
4167 return 0;
4170 if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
4171 cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
4172 apic_poll_irq(cpu->apic_state);
4174 if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
4175 (env->eflags & IF_MASK)) ||
4176 (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
4177 cs->halted = 0;
4179 if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
4180 kvm_cpu_synchronize_state(cs);
4181 do_cpu_sipi(cpu);
4183 if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
4184 cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
4185 kvm_cpu_synchronize_state(cs);
4186 apic_handle_tpr_access_report(cpu->apic_state, env->eip,
4187 env->tpr_access_type);
4190 return cs->halted;
4193 static int kvm_handle_halt(X86CPU *cpu)
4195 CPUState *cs = CPU(cpu);
4196 CPUX86State *env = &cpu->env;
4198 if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
4199 (env->eflags & IF_MASK)) &&
4200 !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
4201 cs->halted = 1;
4202 return EXCP_HLT;
4205 return 0;
4208 static int kvm_handle_tpr_access(X86CPU *cpu)
4210 CPUState *cs = CPU(cpu);
4211 struct kvm_run *run = cs->kvm_run;
4213 apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
4214 run->tpr_access.is_write ? TPR_ACCESS_WRITE
4215 : TPR_ACCESS_READ);
4216 return 1;
4219 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
4221 static const uint8_t int3 = 0xcc;
4223 if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
4224 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
4225 return -EINVAL;
4227 return 0;
4230 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
4232 uint8_t int3;
4234 if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
4235 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
4236 return -EINVAL;
4238 return 0;
4241 static struct {
4242 target_ulong addr;
4243 int len;
4244 int type;
4245 } hw_breakpoint[4];
4247 static int nb_hw_breakpoint;
4249 static int find_hw_breakpoint(target_ulong addr, int len, int type)
4251 int n;
4253 for (n = 0; n < nb_hw_breakpoint; n++) {
4254 if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
4255 (hw_breakpoint[n].len == len || len == -1)) {
4256 return n;
4259 return -1;
4262 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
4263 target_ulong len, int type)
4265 switch (type) {
4266 case GDB_BREAKPOINT_HW:
4267 len = 1;
4268 break;
4269 case GDB_WATCHPOINT_WRITE:
4270 case GDB_WATCHPOINT_ACCESS:
4271 switch (len) {
4272 case 1:
4273 break;
4274 case 2:
4275 case 4:
4276 case 8:
4277 if (addr & (len - 1)) {
4278 return -EINVAL;
4280 break;
4281 default:
4282 return -EINVAL;
4284 break;
4285 default:
4286 return -ENOSYS;
4289 if (nb_hw_breakpoint == 4) {
4290 return -ENOBUFS;
4292 if (find_hw_breakpoint(addr, len, type) >= 0) {
4293 return -EEXIST;
4295 hw_breakpoint[nb_hw_breakpoint].addr = addr;
4296 hw_breakpoint[nb_hw_breakpoint].len = len;
4297 hw_breakpoint[nb_hw_breakpoint].type = type;
4298 nb_hw_breakpoint++;
4300 return 0;
4303 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
4304 target_ulong len, int type)
4306 int n;
4308 n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
4309 if (n < 0) {
4310 return -ENOENT;
4312 nb_hw_breakpoint--;
4313 hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
4315 return 0;
4318 void kvm_arch_remove_all_hw_breakpoints(void)
4320 nb_hw_breakpoint = 0;
4323 static CPUWatchpoint hw_watchpoint;
4325 static int kvm_handle_debug(X86CPU *cpu,
4326 struct kvm_debug_exit_arch *arch_info)
4328 CPUState *cs = CPU(cpu);
4329 CPUX86State *env = &cpu->env;
4330 int ret = 0;
4331 int n;
4333 if (arch_info->exception == EXCP01_DB) {
4334 if (arch_info->dr6 & DR6_BS) {
4335 if (cs->singlestep_enabled) {
4336 ret = EXCP_DEBUG;
4338 } else {
4339 for (n = 0; n < 4; n++) {
4340 if (arch_info->dr6 & (1 << n)) {
4341 switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
4342 case 0x0:
4343 ret = EXCP_DEBUG;
4344 break;
4345 case 0x1:
4346 ret = EXCP_DEBUG;
4347 cs->watchpoint_hit = &hw_watchpoint;
4348 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
4349 hw_watchpoint.flags = BP_MEM_WRITE;
4350 break;
4351 case 0x3:
4352 ret = EXCP_DEBUG;
4353 cs->watchpoint_hit = &hw_watchpoint;
4354 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
4355 hw_watchpoint.flags = BP_MEM_ACCESS;
4356 break;
4361 } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
4362 ret = EXCP_DEBUG;
4364 if (ret == 0) {
4365 cpu_synchronize_state(cs);
4366 assert(env->exception_nr == -1);
4368 /* pass to guest */
4369 kvm_queue_exception(env, arch_info->exception,
4370 arch_info->exception == EXCP01_DB,
4371 arch_info->dr6);
4372 env->has_error_code = 0;
4375 return ret;
4378 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
4380 const uint8_t type_code[] = {
4381 [GDB_BREAKPOINT_HW] = 0x0,
4382 [GDB_WATCHPOINT_WRITE] = 0x1,
4383 [GDB_WATCHPOINT_ACCESS] = 0x3
4385 const uint8_t len_code[] = {
4386 [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
4388 int n;
4390 if (kvm_sw_breakpoints_active(cpu)) {
4391 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
4393 if (nb_hw_breakpoint > 0) {
4394 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
4395 dbg->arch.debugreg[7] = 0x0600;
4396 for (n = 0; n < nb_hw_breakpoint; n++) {
4397 dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
4398 dbg->arch.debugreg[7] |= (2 << (n * 2)) |
4399 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
4400 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
4405 static bool host_supports_vmx(void)
4407 uint32_t ecx, unused;
4409 host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
4410 return ecx & CPUID_EXT_VMX;
4413 #define VMX_INVALID_GUEST_STATE 0x80000021
4415 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
4417 X86CPU *cpu = X86_CPU(cs);
4418 uint64_t code;
4419 int ret;
4421 switch (run->exit_reason) {
4422 case KVM_EXIT_HLT:
4423 DPRINTF("handle_hlt\n");
4424 qemu_mutex_lock_iothread();
4425 ret = kvm_handle_halt(cpu);
4426 qemu_mutex_unlock_iothread();
4427 break;
4428 case KVM_EXIT_SET_TPR:
4429 ret = 0;
4430 break;
4431 case KVM_EXIT_TPR_ACCESS:
4432 qemu_mutex_lock_iothread();
4433 ret = kvm_handle_tpr_access(cpu);
4434 qemu_mutex_unlock_iothread();
4435 break;
4436 case KVM_EXIT_FAIL_ENTRY:
4437 code = run->fail_entry.hardware_entry_failure_reason;
4438 fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
4439 code);
4440 if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
4441 fprintf(stderr,
4442 "\nIf you're running a guest on an Intel machine without "
4443 "unrestricted mode\n"
4444 "support, the failure can be most likely due to the guest "
4445 "entering an invalid\n"
4446 "state for Intel VT. For example, the guest maybe running "
4447 "in big real mode\n"
4448 "which is not supported on less recent Intel processors."
4449 "\n\n");
4451 ret = -1;
4452 break;
4453 case KVM_EXIT_EXCEPTION:
4454 fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
4455 run->ex.exception, run->ex.error_code);
4456 ret = -1;
4457 break;
4458 case KVM_EXIT_DEBUG:
4459 DPRINTF("kvm_exit_debug\n");
4460 qemu_mutex_lock_iothread();
4461 ret = kvm_handle_debug(cpu, &run->debug.arch);
4462 qemu_mutex_unlock_iothread();
4463 break;
4464 case KVM_EXIT_HYPERV:
4465 ret = kvm_hv_handle_exit(cpu, &run->hyperv);
4466 break;
4467 case KVM_EXIT_IOAPIC_EOI:
4468 ioapic_eoi_broadcast(run->eoi.vector);
4469 ret = 0;
4470 break;
4471 default:
4472 fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
4473 ret = -1;
4474 break;
4477 return ret;
4480 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
4482 X86CPU *cpu = X86_CPU(cs);
4483 CPUX86State *env = &cpu->env;
4485 kvm_cpu_synchronize_state(cs);
4486 return !(env->cr[0] & CR0_PE_MASK) ||
4487 ((env->segs[R_CS].selector & 3) != 3);
4490 void kvm_arch_init_irq_routing(KVMState *s)
4492 if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
4493 /* If kernel can't do irq routing, interrupt source
4494 * override 0->2 cannot be set up as required by HPET.
4495 * So we have to disable it.
4497 no_hpet = 1;
4499 /* We know at this point that we're using the in-kernel
4500 * irqchip, so we can use irqfds, and on x86 we know
4501 * we can use msi via irqfd and GSI routing.
4503 kvm_msi_via_irqfd_allowed = true;
4504 kvm_gsi_routing_allowed = true;
4506 if (kvm_irqchip_is_split()) {
4507 int i;
4509 /* If the ioapic is in QEMU and the lapics are in KVM, reserve
4510 MSI routes for signaling interrupts to the local apics. */
4511 for (i = 0; i < IOAPIC_NUM_PINS; i++) {
4512 if (kvm_irqchip_add_msi_route(s, 0, NULL) < 0) {
4513 error_report("Could not enable split IRQ mode.");
4514 exit(1);
4520 int kvm_arch_irqchip_create(KVMState *s)
4522 int ret;
4523 if (kvm_kernel_irqchip_split()) {
4524 ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
4525 if (ret) {
4526 error_report("Could not enable split irqchip mode: %s",
4527 strerror(-ret));
4528 exit(1);
4529 } else {
4530 DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
4531 kvm_split_irqchip = true;
4532 return 1;
4534 } else {
4535 return 0;
4539 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
4540 uint64_t address, uint32_t data, PCIDevice *dev)
4542 X86IOMMUState *iommu = x86_iommu_get_default();
4544 if (iommu) {
4545 int ret;
4546 MSIMessage src, dst;
4547 X86IOMMUClass *class = X86_IOMMU_GET_CLASS(iommu);
4549 if (!class->int_remap) {
4550 return 0;
4553 src.address = route->u.msi.address_hi;
4554 src.address <<= VTD_MSI_ADDR_HI_SHIFT;
4555 src.address |= route->u.msi.address_lo;
4556 src.data = route->u.msi.data;
4558 ret = class->int_remap(iommu, &src, &dst, dev ? \
4559 pci_requester_id(dev) : \
4560 X86_IOMMU_SID_INVALID);
4561 if (ret) {
4562 trace_kvm_x86_fixup_msi_error(route->gsi);
4563 return 1;
4566 route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
4567 route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
4568 route->u.msi.data = dst.data;
4571 return 0;
4574 typedef struct MSIRouteEntry MSIRouteEntry;
4576 struct MSIRouteEntry {
4577 PCIDevice *dev; /* Device pointer */
4578 int vector; /* MSI/MSIX vector index */
4579 int virq; /* Virtual IRQ index */
4580 QLIST_ENTRY(MSIRouteEntry) list;
4583 /* List of used GSI routes */
4584 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
4585 QLIST_HEAD_INITIALIZER(msi_route_list);
4587 static void kvm_update_msi_routes_all(void *private, bool global,
4588 uint32_t index, uint32_t mask)
4590 int cnt = 0, vector;
4591 MSIRouteEntry *entry;
4592 MSIMessage msg;
4593 PCIDevice *dev;
4595 /* TODO: explicit route update */
4596 QLIST_FOREACH(entry, &msi_route_list, list) {
4597 cnt++;
4598 vector = entry->vector;
4599 dev = entry->dev;
4600 if (msix_enabled(dev) && !msix_is_masked(dev, vector)) {
4601 msg = msix_get_message(dev, vector);
4602 } else if (msi_enabled(dev) && !msi_is_masked(dev, vector)) {
4603 msg = msi_get_message(dev, vector);
4604 } else {
4606 * Either MSI/MSIX is disabled for the device, or the
4607 * specific message was masked out. Skip this one.
4609 continue;
4611 kvm_irqchip_update_msi_route(kvm_state, entry->virq, msg, dev);
4613 kvm_irqchip_commit_routes(kvm_state);
4614 trace_kvm_x86_update_msi_routes(cnt);
4617 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
4618 int vector, PCIDevice *dev)
4620 static bool notify_list_inited = false;
4621 MSIRouteEntry *entry;
4623 if (!dev) {
4624 /* These are (possibly) IOAPIC routes only used for split
4625 * kernel irqchip mode, while what we are housekeeping are
4626 * PCI devices only. */
4627 return 0;
4630 entry = g_new0(MSIRouteEntry, 1);
4631 entry->dev = dev;
4632 entry->vector = vector;
4633 entry->virq = route->gsi;
4634 QLIST_INSERT_HEAD(&msi_route_list, entry, list);
4636 trace_kvm_x86_add_msi_route(route->gsi);
4638 if (!notify_list_inited) {
4639 /* For the first time we do add route, add ourselves into
4640 * IOMMU's IEC notify list if needed. */
4641 X86IOMMUState *iommu = x86_iommu_get_default();
4642 if (iommu) {
4643 x86_iommu_iec_register_notifier(iommu,
4644 kvm_update_msi_routes_all,
4645 NULL);
4647 notify_list_inited = true;
4649 return 0;
4652 int kvm_arch_release_virq_post(int virq)
4654 MSIRouteEntry *entry, *next;
4655 QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
4656 if (entry->virq == virq) {
4657 trace_kvm_x86_remove_msi_route(virq);
4658 QLIST_REMOVE(entry, list);
4659 g_free(entry);
4660 break;
4663 return 0;
4666 int kvm_arch_msi_data_to_gsi(uint32_t data)
4668 abort();