monitor/qmp: Update comment for commit 4eaca8de268
[qemu/armbru.git] / target / i386 / kvm.c
blob2abc881324355e9480b92bb1d55f9f05ac811631
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/pc.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"
45 #include "hw/pci/pci.h"
46 #include "hw/pci/msi.h"
47 #include "hw/pci/msix.h"
48 #include "migration/blocker.h"
49 #include "exec/memattrs.h"
50 #include "trace.h"
52 //#define DEBUG_KVM
54 #ifdef DEBUG_KVM
55 #define DPRINTF(fmt, ...) \
56 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
57 #else
58 #define DPRINTF(fmt, ...) \
59 do { } while (0)
60 #endif
62 #define MSR_KVM_WALL_CLOCK 0x11
63 #define MSR_KVM_SYSTEM_TIME 0x12
65 /* A 4096-byte buffer can hold the 8-byte kvm_msrs header, plus
66 * 255 kvm_msr_entry structs */
67 #define MSR_BUF_SIZE 4096
69 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
70 KVM_CAP_INFO(SET_TSS_ADDR),
71 KVM_CAP_INFO(EXT_CPUID),
72 KVM_CAP_INFO(MP_STATE),
73 KVM_CAP_LAST_INFO
76 static bool has_msr_star;
77 static bool has_msr_hsave_pa;
78 static bool has_msr_tsc_aux;
79 static bool has_msr_tsc_adjust;
80 static bool has_msr_tsc_deadline;
81 static bool has_msr_feature_control;
82 static bool has_msr_misc_enable;
83 static bool has_msr_smbase;
84 static bool has_msr_bndcfgs;
85 static int lm_capable_kernel;
86 static bool has_msr_hv_hypercall;
87 static bool has_msr_hv_crash;
88 static bool has_msr_hv_reset;
89 static bool has_msr_hv_vpindex;
90 static bool hv_vpindex_settable;
91 static bool has_msr_hv_runtime;
92 static bool has_msr_hv_synic;
93 static bool has_msr_hv_stimer;
94 static bool has_msr_hv_frequencies;
95 static bool has_msr_hv_reenlightenment;
96 static bool has_msr_xss;
97 static bool has_msr_spec_ctrl;
98 static bool has_msr_virt_ssbd;
99 static bool has_msr_smi_count;
100 static bool has_msr_arch_capabs;
101 static bool has_msr_core_capabs;
103 static uint32_t has_architectural_pmu_version;
104 static uint32_t num_architectural_pmu_gp_counters;
105 static uint32_t num_architectural_pmu_fixed_counters;
107 static int has_xsave;
108 static int has_xcrs;
109 static int has_pit_state2;
110 static int has_exception_payload;
112 static bool has_msr_mcg_ext_ctl;
114 static struct kvm_cpuid2 *cpuid_cache;
115 static struct kvm_msr_list *kvm_feature_msrs;
117 int kvm_has_pit_state2(void)
119 return has_pit_state2;
122 bool kvm_has_smm(void)
124 return kvm_check_extension(kvm_state, KVM_CAP_X86_SMM);
127 bool kvm_has_adjust_clock_stable(void)
129 int ret = kvm_check_extension(kvm_state, KVM_CAP_ADJUST_CLOCK);
131 return (ret == KVM_CLOCK_TSC_STABLE);
134 bool kvm_has_exception_payload(void)
136 return has_exception_payload;
139 bool kvm_allows_irq0_override(void)
141 return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
144 static bool kvm_x2apic_api_set_flags(uint64_t flags)
146 KVMState *s = KVM_STATE(current_machine->accelerator);
148 return !kvm_vm_enable_cap(s, KVM_CAP_X2APIC_API, 0, flags);
151 #define MEMORIZE(fn, _result) \
152 ({ \
153 static bool _memorized; \
155 if (_memorized) { \
156 return _result; \
158 _memorized = true; \
159 _result = fn; \
162 static bool has_x2apic_api;
164 bool kvm_has_x2apic_api(void)
166 return has_x2apic_api;
169 bool kvm_enable_x2apic(void)
171 return MEMORIZE(
172 kvm_x2apic_api_set_flags(KVM_X2APIC_API_USE_32BIT_IDS |
173 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK),
174 has_x2apic_api);
177 bool kvm_hv_vpindex_settable(void)
179 return hv_vpindex_settable;
182 static int kvm_get_tsc(CPUState *cs)
184 X86CPU *cpu = X86_CPU(cs);
185 CPUX86State *env = &cpu->env;
186 struct {
187 struct kvm_msrs info;
188 struct kvm_msr_entry entries[1];
189 } msr_data;
190 int ret;
192 if (env->tsc_valid) {
193 return 0;
196 msr_data.info.nmsrs = 1;
197 msr_data.entries[0].index = MSR_IA32_TSC;
198 env->tsc_valid = !runstate_is_running();
200 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
201 if (ret < 0) {
202 return ret;
205 assert(ret == 1);
206 env->tsc = msr_data.entries[0].data;
207 return 0;
210 static inline void do_kvm_synchronize_tsc(CPUState *cpu, run_on_cpu_data arg)
212 kvm_get_tsc(cpu);
215 void kvm_synchronize_all_tsc(void)
217 CPUState *cpu;
219 if (kvm_enabled()) {
220 CPU_FOREACH(cpu) {
221 run_on_cpu(cpu, do_kvm_synchronize_tsc, RUN_ON_CPU_NULL);
226 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
228 struct kvm_cpuid2 *cpuid;
229 int r, size;
231 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
232 cpuid = g_malloc0(size);
233 cpuid->nent = max;
234 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
235 if (r == 0 && cpuid->nent >= max) {
236 r = -E2BIG;
238 if (r < 0) {
239 if (r == -E2BIG) {
240 g_free(cpuid);
241 return NULL;
242 } else {
243 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
244 strerror(-r));
245 exit(1);
248 return cpuid;
251 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
252 * for all entries.
254 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
256 struct kvm_cpuid2 *cpuid;
257 int max = 1;
259 if (cpuid_cache != NULL) {
260 return cpuid_cache;
262 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
263 max *= 2;
265 cpuid_cache = cpuid;
266 return cpuid;
269 static const struct kvm_para_features {
270 int cap;
271 int feature;
272 } para_features[] = {
273 { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
274 { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
275 { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
276 { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
279 static int get_para_features(KVMState *s)
281 int i, features = 0;
283 for (i = 0; i < ARRAY_SIZE(para_features); i++) {
284 if (kvm_check_extension(s, para_features[i].cap)) {
285 features |= (1 << para_features[i].feature);
289 return features;
292 static bool host_tsx_blacklisted(void)
294 int family, model, stepping;\
295 char vendor[CPUID_VENDOR_SZ + 1];
297 host_vendor_fms(vendor, &family, &model, &stepping);
299 /* Check if we are running on a Haswell host known to have broken TSX */
300 return !strcmp(vendor, CPUID_VENDOR_INTEL) &&
301 (family == 6) &&
302 ((model == 63 && stepping < 4) ||
303 model == 60 || model == 69 || model == 70);
306 /* Returns the value for a specific register on the cpuid entry
308 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
310 uint32_t ret = 0;
311 switch (reg) {
312 case R_EAX:
313 ret = entry->eax;
314 break;
315 case R_EBX:
316 ret = entry->ebx;
317 break;
318 case R_ECX:
319 ret = entry->ecx;
320 break;
321 case R_EDX:
322 ret = entry->edx;
323 break;
325 return ret;
328 /* Find matching entry for function/index on kvm_cpuid2 struct
330 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
331 uint32_t function,
332 uint32_t index)
334 int i;
335 for (i = 0; i < cpuid->nent; ++i) {
336 if (cpuid->entries[i].function == function &&
337 cpuid->entries[i].index == index) {
338 return &cpuid->entries[i];
341 /* not found: */
342 return NULL;
345 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
346 uint32_t index, int reg)
348 struct kvm_cpuid2 *cpuid;
349 uint32_t ret = 0;
350 uint32_t cpuid_1_edx;
351 bool found = false;
353 cpuid = get_supported_cpuid(s);
355 struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
356 if (entry) {
357 found = true;
358 ret = cpuid_entry_get_reg(entry, reg);
361 /* Fixups for the data returned by KVM, below */
363 if (function == 1 && reg == R_EDX) {
364 /* KVM before 2.6.30 misreports the following features */
365 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
366 } else if (function == 1 && reg == R_ECX) {
367 /* We can set the hypervisor flag, even if KVM does not return it on
368 * GET_SUPPORTED_CPUID
370 ret |= CPUID_EXT_HYPERVISOR;
371 /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
372 * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
373 * and the irqchip is in the kernel.
375 if (kvm_irqchip_in_kernel() &&
376 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
377 ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
380 /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
381 * without the in-kernel irqchip
383 if (!kvm_irqchip_in_kernel()) {
384 ret &= ~CPUID_EXT_X2APIC;
387 if (enable_cpu_pm) {
388 int disable_exits = kvm_check_extension(s,
389 KVM_CAP_X86_DISABLE_EXITS);
391 if (disable_exits & KVM_X86_DISABLE_EXITS_MWAIT) {
392 ret |= CPUID_EXT_MONITOR;
395 } else if (function == 6 && reg == R_EAX) {
396 ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
397 } else if (function == 7 && index == 0 && reg == R_EBX) {
398 if (host_tsx_blacklisted()) {
399 ret &= ~(CPUID_7_0_EBX_RTM | CPUID_7_0_EBX_HLE);
401 } else if (function == 7 && index == 0 && reg == R_EDX) {
403 * Linux v4.17-v4.20 incorrectly return ARCH_CAPABILITIES on SVM hosts.
404 * We can detect the bug by checking if MSR_IA32_ARCH_CAPABILITIES is
405 * returned by KVM_GET_MSR_INDEX_LIST.
407 if (!has_msr_arch_capabs) {
408 ret &= ~CPUID_7_0_EDX_ARCH_CAPABILITIES;
410 } else if (function == 0x80000001 && reg == R_ECX) {
412 * It's safe to enable TOPOEXT even if it's not returned by
413 * GET_SUPPORTED_CPUID. Unconditionally enabling TOPOEXT here allows
414 * us to keep CPU models including TOPOEXT runnable on older kernels.
416 ret |= CPUID_EXT3_TOPOEXT;
417 } else if (function == 0x80000001 && reg == R_EDX) {
418 /* On Intel, kvm returns cpuid according to the Intel spec,
419 * so add missing bits according to the AMD spec:
421 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
422 ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
423 } else if (function == KVM_CPUID_FEATURES && reg == R_EAX) {
424 /* kvm_pv_unhalt is reported by GET_SUPPORTED_CPUID, but it can't
425 * be enabled without the in-kernel irqchip
427 if (!kvm_irqchip_in_kernel()) {
428 ret &= ~(1U << KVM_FEATURE_PV_UNHALT);
430 } else if (function == KVM_CPUID_FEATURES && reg == R_EDX) {
431 ret |= 1U << KVM_HINTS_REALTIME;
432 found = 1;
435 /* fallback for older kernels */
436 if ((function == KVM_CPUID_FEATURES) && !found) {
437 ret = get_para_features(s);
440 return ret;
443 uint32_t kvm_arch_get_supported_msr_feature(KVMState *s, uint32_t index)
445 struct {
446 struct kvm_msrs info;
447 struct kvm_msr_entry entries[1];
448 } msr_data;
449 uint32_t ret;
451 if (kvm_feature_msrs == NULL) { /* Host doesn't support feature MSRs */
452 return 0;
455 /* Check if requested MSR is supported feature MSR */
456 int i;
457 for (i = 0; i < kvm_feature_msrs->nmsrs; i++)
458 if (kvm_feature_msrs->indices[i] == index) {
459 break;
461 if (i == kvm_feature_msrs->nmsrs) {
462 return 0; /* if the feature MSR is not supported, simply return 0 */
465 msr_data.info.nmsrs = 1;
466 msr_data.entries[0].index = index;
468 ret = kvm_ioctl(s, KVM_GET_MSRS, &msr_data);
469 if (ret != 1) {
470 error_report("KVM get MSR (index=0x%x) feature failed, %s",
471 index, strerror(-ret));
472 exit(1);
475 return msr_data.entries[0].data;
479 typedef struct HWPoisonPage {
480 ram_addr_t ram_addr;
481 QLIST_ENTRY(HWPoisonPage) list;
482 } HWPoisonPage;
484 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
485 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
487 static void kvm_unpoison_all(void *param)
489 HWPoisonPage *page, *next_page;
491 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
492 QLIST_REMOVE(page, list);
493 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
494 g_free(page);
498 static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
500 HWPoisonPage *page;
502 QLIST_FOREACH(page, &hwpoison_page_list, list) {
503 if (page->ram_addr == ram_addr) {
504 return;
507 page = g_new(HWPoisonPage, 1);
508 page->ram_addr = ram_addr;
509 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
512 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
513 int *max_banks)
515 int r;
517 r = kvm_check_extension(s, KVM_CAP_MCE);
518 if (r > 0) {
519 *max_banks = r;
520 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
522 return -ENOSYS;
525 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
527 CPUState *cs = CPU(cpu);
528 CPUX86State *env = &cpu->env;
529 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
530 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
531 uint64_t mcg_status = MCG_STATUS_MCIP;
532 int flags = 0;
534 if (code == BUS_MCEERR_AR) {
535 status |= MCI_STATUS_AR | 0x134;
536 mcg_status |= MCG_STATUS_EIPV;
537 } else {
538 status |= 0xc0;
539 mcg_status |= MCG_STATUS_RIPV;
542 flags = cpu_x86_support_mca_broadcast(env) ? MCE_INJECT_BROADCAST : 0;
543 /* We need to read back the value of MSR_EXT_MCG_CTL that was set by the
544 * guest kernel back into env->mcg_ext_ctl.
546 cpu_synchronize_state(cs);
547 if (env->mcg_ext_ctl & MCG_EXT_CTL_LMCE_EN) {
548 mcg_status |= MCG_STATUS_LMCE;
549 flags = 0;
552 cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
553 (MCM_ADDR_PHYS << 6) | 0xc, flags);
556 static void hardware_memory_error(void)
558 fprintf(stderr, "Hardware memory error!\n");
559 exit(1);
562 void kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
564 X86CPU *cpu = X86_CPU(c);
565 CPUX86State *env = &cpu->env;
566 ram_addr_t ram_addr;
567 hwaddr paddr;
569 /* If we get an action required MCE, it has been injected by KVM
570 * while the VM was running. An action optional MCE instead should
571 * be coming from the main thread, which qemu_init_sigbus identifies
572 * as the "early kill" thread.
574 assert(code == BUS_MCEERR_AR || code == BUS_MCEERR_AO);
576 if ((env->mcg_cap & MCG_SER_P) && addr) {
577 ram_addr = qemu_ram_addr_from_host(addr);
578 if (ram_addr != RAM_ADDR_INVALID &&
579 kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
580 kvm_hwpoison_page_add(ram_addr);
581 kvm_mce_inject(cpu, paddr, code);
582 return;
585 fprintf(stderr, "Hardware memory error for memory used by "
586 "QEMU itself instead of guest system!\n");
589 if (code == BUS_MCEERR_AR) {
590 hardware_memory_error();
593 /* Hope we are lucky for AO MCE */
596 static void kvm_reset_exception(CPUX86State *env)
598 env->exception_nr = -1;
599 env->exception_pending = 0;
600 env->exception_injected = 0;
601 env->exception_has_payload = false;
602 env->exception_payload = 0;
605 static void kvm_queue_exception(CPUX86State *env,
606 int32_t exception_nr,
607 uint8_t exception_has_payload,
608 uint64_t exception_payload)
610 assert(env->exception_nr == -1);
611 assert(!env->exception_pending);
612 assert(!env->exception_injected);
613 assert(!env->exception_has_payload);
615 env->exception_nr = exception_nr;
617 if (has_exception_payload) {
618 env->exception_pending = 1;
620 env->exception_has_payload = exception_has_payload;
621 env->exception_payload = exception_payload;
622 } else {
623 env->exception_injected = 1;
625 if (exception_nr == EXCP01_DB) {
626 assert(exception_has_payload);
627 env->dr[6] = exception_payload;
628 } else if (exception_nr == EXCP0E_PAGE) {
629 assert(exception_has_payload);
630 env->cr[2] = exception_payload;
631 } else {
632 assert(!exception_has_payload);
637 static int kvm_inject_mce_oldstyle(X86CPU *cpu)
639 CPUX86State *env = &cpu->env;
641 if (!kvm_has_vcpu_events() && env->exception_nr == EXCP12_MCHK) {
642 unsigned int bank, bank_num = env->mcg_cap & 0xff;
643 struct kvm_x86_mce mce;
645 kvm_reset_exception(env);
648 * There must be at least one bank in use if an MCE is pending.
649 * Find it and use its values for the event injection.
651 for (bank = 0; bank < bank_num; bank++) {
652 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
653 break;
656 assert(bank < bank_num);
658 mce.bank = bank;
659 mce.status = env->mce_banks[bank * 4 + 1];
660 mce.mcg_status = env->mcg_status;
661 mce.addr = env->mce_banks[bank * 4 + 2];
662 mce.misc = env->mce_banks[bank * 4 + 3];
664 return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
666 return 0;
669 static void cpu_update_state(void *opaque, int running, RunState state)
671 CPUX86State *env = opaque;
673 if (running) {
674 env->tsc_valid = false;
678 unsigned long kvm_arch_vcpu_id(CPUState *cs)
680 X86CPU *cpu = X86_CPU(cs);
681 return cpu->apic_id;
684 #ifndef KVM_CPUID_SIGNATURE_NEXT
685 #define KVM_CPUID_SIGNATURE_NEXT 0x40000100
686 #endif
688 static bool hyperv_enabled(X86CPU *cpu)
690 CPUState *cs = CPU(cpu);
691 return kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0 &&
692 ((cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY) ||
693 cpu->hyperv_features || cpu->hyperv_passthrough);
696 static int kvm_arch_set_tsc_khz(CPUState *cs)
698 X86CPU *cpu = X86_CPU(cs);
699 CPUX86State *env = &cpu->env;
700 int r;
702 if (!env->tsc_khz) {
703 return 0;
706 r = kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL) ?
707 kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) :
708 -ENOTSUP;
709 if (r < 0) {
710 /* When KVM_SET_TSC_KHZ fails, it's an error only if the current
711 * TSC frequency doesn't match the one we want.
713 int cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
714 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
715 -ENOTSUP;
716 if (cur_freq <= 0 || cur_freq != env->tsc_khz) {
717 warn_report("TSC frequency mismatch between "
718 "VM (%" PRId64 " kHz) and host (%d kHz), "
719 "and TSC scaling unavailable",
720 env->tsc_khz, cur_freq);
721 return r;
725 return 0;
728 static bool tsc_is_stable_and_known(CPUX86State *env)
730 if (!env->tsc_khz) {
731 return false;
733 return (env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC)
734 || env->user_tsc_khz;
737 static struct {
738 const char *desc;
739 struct {
740 uint32_t fw;
741 uint32_t bits;
742 } flags[2];
743 uint64_t dependencies;
744 } kvm_hyperv_properties[] = {
745 [HYPERV_FEAT_RELAXED] = {
746 .desc = "relaxed timing (hv-relaxed)",
747 .flags = {
748 {.fw = FEAT_HYPERV_EAX,
749 .bits = HV_HYPERCALL_AVAILABLE},
750 {.fw = FEAT_HV_RECOMM_EAX,
751 .bits = HV_RELAXED_TIMING_RECOMMENDED}
754 [HYPERV_FEAT_VAPIC] = {
755 .desc = "virtual APIC (hv-vapic)",
756 .flags = {
757 {.fw = FEAT_HYPERV_EAX,
758 .bits = HV_HYPERCALL_AVAILABLE | HV_APIC_ACCESS_AVAILABLE},
759 {.fw = FEAT_HV_RECOMM_EAX,
760 .bits = HV_APIC_ACCESS_RECOMMENDED}
763 [HYPERV_FEAT_TIME] = {
764 .desc = "clocksources (hv-time)",
765 .flags = {
766 {.fw = FEAT_HYPERV_EAX,
767 .bits = HV_HYPERCALL_AVAILABLE | HV_TIME_REF_COUNT_AVAILABLE |
768 HV_REFERENCE_TSC_AVAILABLE}
771 [HYPERV_FEAT_CRASH] = {
772 .desc = "crash MSRs (hv-crash)",
773 .flags = {
774 {.fw = FEAT_HYPERV_EDX,
775 .bits = HV_GUEST_CRASH_MSR_AVAILABLE}
778 [HYPERV_FEAT_RESET] = {
779 .desc = "reset MSR (hv-reset)",
780 .flags = {
781 {.fw = FEAT_HYPERV_EAX,
782 .bits = HV_RESET_AVAILABLE}
785 [HYPERV_FEAT_VPINDEX] = {
786 .desc = "VP_INDEX MSR (hv-vpindex)",
787 .flags = {
788 {.fw = FEAT_HYPERV_EAX,
789 .bits = HV_VP_INDEX_AVAILABLE}
792 [HYPERV_FEAT_RUNTIME] = {
793 .desc = "VP_RUNTIME MSR (hv-runtime)",
794 .flags = {
795 {.fw = FEAT_HYPERV_EAX,
796 .bits = HV_VP_RUNTIME_AVAILABLE}
799 [HYPERV_FEAT_SYNIC] = {
800 .desc = "synthetic interrupt controller (hv-synic)",
801 .flags = {
802 {.fw = FEAT_HYPERV_EAX,
803 .bits = HV_SYNIC_AVAILABLE}
806 [HYPERV_FEAT_STIMER] = {
807 .desc = "synthetic timers (hv-stimer)",
808 .flags = {
809 {.fw = FEAT_HYPERV_EAX,
810 .bits = HV_SYNTIMERS_AVAILABLE}
812 .dependencies = BIT(HYPERV_FEAT_SYNIC) | BIT(HYPERV_FEAT_TIME)
814 [HYPERV_FEAT_FREQUENCIES] = {
815 .desc = "frequency MSRs (hv-frequencies)",
816 .flags = {
817 {.fw = FEAT_HYPERV_EAX,
818 .bits = HV_ACCESS_FREQUENCY_MSRS},
819 {.fw = FEAT_HYPERV_EDX,
820 .bits = HV_FREQUENCY_MSRS_AVAILABLE}
823 [HYPERV_FEAT_REENLIGHTENMENT] = {
824 .desc = "reenlightenment MSRs (hv-reenlightenment)",
825 .flags = {
826 {.fw = FEAT_HYPERV_EAX,
827 .bits = HV_ACCESS_REENLIGHTENMENTS_CONTROL}
830 [HYPERV_FEAT_TLBFLUSH] = {
831 .desc = "paravirtualized TLB flush (hv-tlbflush)",
832 .flags = {
833 {.fw = FEAT_HV_RECOMM_EAX,
834 .bits = HV_REMOTE_TLB_FLUSH_RECOMMENDED |
835 HV_EX_PROCESSOR_MASKS_RECOMMENDED}
837 .dependencies = BIT(HYPERV_FEAT_VPINDEX)
839 [HYPERV_FEAT_EVMCS] = {
840 .desc = "enlightened VMCS (hv-evmcs)",
841 .flags = {
842 {.fw = FEAT_HV_RECOMM_EAX,
843 .bits = HV_ENLIGHTENED_VMCS_RECOMMENDED}
845 .dependencies = BIT(HYPERV_FEAT_VAPIC)
847 [HYPERV_FEAT_IPI] = {
848 .desc = "paravirtualized IPI (hv-ipi)",
849 .flags = {
850 {.fw = FEAT_HV_RECOMM_EAX,
851 .bits = HV_CLUSTER_IPI_RECOMMENDED |
852 HV_EX_PROCESSOR_MASKS_RECOMMENDED}
854 .dependencies = BIT(HYPERV_FEAT_VPINDEX)
856 [HYPERV_FEAT_STIMER_DIRECT] = {
857 .desc = "direct mode synthetic timers (hv-stimer-direct)",
858 .flags = {
859 {.fw = FEAT_HYPERV_EDX,
860 .bits = HV_STIMER_DIRECT_MODE_AVAILABLE}
862 .dependencies = BIT(HYPERV_FEAT_STIMER)
866 static struct kvm_cpuid2 *try_get_hv_cpuid(CPUState *cs, int max)
868 struct kvm_cpuid2 *cpuid;
869 int r, size;
871 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
872 cpuid = g_malloc0(size);
873 cpuid->nent = max;
875 r = kvm_vcpu_ioctl(cs, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
876 if (r == 0 && cpuid->nent >= max) {
877 r = -E2BIG;
879 if (r < 0) {
880 if (r == -E2BIG) {
881 g_free(cpuid);
882 return NULL;
883 } else {
884 fprintf(stderr, "KVM_GET_SUPPORTED_HV_CPUID failed: %s\n",
885 strerror(-r));
886 exit(1);
889 return cpuid;
893 * Run KVM_GET_SUPPORTED_HV_CPUID ioctl(), allocating a buffer large enough
894 * for all entries.
896 static struct kvm_cpuid2 *get_supported_hv_cpuid(CPUState *cs)
898 struct kvm_cpuid2 *cpuid;
899 int max = 7; /* 0x40000000..0x40000005, 0x4000000A */
902 * When the buffer is too small, KVM_GET_SUPPORTED_HV_CPUID fails with
903 * -E2BIG, however, it doesn't report back the right size. Keep increasing
904 * it and re-trying until we succeed.
906 while ((cpuid = try_get_hv_cpuid(cs, max)) == NULL) {
907 max++;
909 return cpuid;
913 * When KVM_GET_SUPPORTED_HV_CPUID is not supported we fill CPUID feature
914 * leaves from KVM_CAP_HYPERV* and present MSRs data.
916 static struct kvm_cpuid2 *get_supported_hv_cpuid_legacy(CPUState *cs)
918 X86CPU *cpu = X86_CPU(cs);
919 struct kvm_cpuid2 *cpuid;
920 struct kvm_cpuid_entry2 *entry_feat, *entry_recomm;
922 /* HV_CPUID_FEATURES, HV_CPUID_ENLIGHTMENT_INFO */
923 cpuid = g_malloc0(sizeof(*cpuid) + 2 * sizeof(*cpuid->entries));
924 cpuid->nent = 2;
926 /* HV_CPUID_VENDOR_AND_MAX_FUNCTIONS */
927 entry_feat = &cpuid->entries[0];
928 entry_feat->function = HV_CPUID_FEATURES;
930 entry_recomm = &cpuid->entries[1];
931 entry_recomm->function = HV_CPUID_ENLIGHTMENT_INFO;
932 entry_recomm->ebx = cpu->hyperv_spinlock_attempts;
934 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0) {
935 entry_feat->eax |= HV_HYPERCALL_AVAILABLE;
936 entry_feat->eax |= HV_APIC_ACCESS_AVAILABLE;
937 entry_feat->edx |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
938 entry_recomm->eax |= HV_RELAXED_TIMING_RECOMMENDED;
939 entry_recomm->eax |= HV_APIC_ACCESS_RECOMMENDED;
942 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) > 0) {
943 entry_feat->eax |= HV_TIME_REF_COUNT_AVAILABLE;
944 entry_feat->eax |= HV_REFERENCE_TSC_AVAILABLE;
947 if (has_msr_hv_frequencies) {
948 entry_feat->eax |= HV_ACCESS_FREQUENCY_MSRS;
949 entry_feat->edx |= HV_FREQUENCY_MSRS_AVAILABLE;
952 if (has_msr_hv_crash) {
953 entry_feat->edx |= HV_GUEST_CRASH_MSR_AVAILABLE;
956 if (has_msr_hv_reenlightenment) {
957 entry_feat->eax |= HV_ACCESS_REENLIGHTENMENTS_CONTROL;
960 if (has_msr_hv_reset) {
961 entry_feat->eax |= HV_RESET_AVAILABLE;
964 if (has_msr_hv_vpindex) {
965 entry_feat->eax |= HV_VP_INDEX_AVAILABLE;
968 if (has_msr_hv_runtime) {
969 entry_feat->eax |= HV_VP_RUNTIME_AVAILABLE;
972 if (has_msr_hv_synic) {
973 unsigned int cap = cpu->hyperv_synic_kvm_only ?
974 KVM_CAP_HYPERV_SYNIC : KVM_CAP_HYPERV_SYNIC2;
976 if (kvm_check_extension(cs->kvm_state, cap) > 0) {
977 entry_feat->eax |= HV_SYNIC_AVAILABLE;
981 if (has_msr_hv_stimer) {
982 entry_feat->eax |= HV_SYNTIMERS_AVAILABLE;
985 if (kvm_check_extension(cs->kvm_state,
986 KVM_CAP_HYPERV_TLBFLUSH) > 0) {
987 entry_recomm->eax |= HV_REMOTE_TLB_FLUSH_RECOMMENDED;
988 entry_recomm->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
991 if (kvm_check_extension(cs->kvm_state,
992 KVM_CAP_HYPERV_ENLIGHTENED_VMCS) > 0) {
993 entry_recomm->eax |= HV_ENLIGHTENED_VMCS_RECOMMENDED;
996 if (kvm_check_extension(cs->kvm_state,
997 KVM_CAP_HYPERV_SEND_IPI) > 0) {
998 entry_recomm->eax |= HV_CLUSTER_IPI_RECOMMENDED;
999 entry_recomm->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
1002 return cpuid;
1005 static int hv_cpuid_get_fw(struct kvm_cpuid2 *cpuid, int fw, uint32_t *r)
1007 struct kvm_cpuid_entry2 *entry;
1008 uint32_t func;
1009 int reg;
1011 switch (fw) {
1012 case FEAT_HYPERV_EAX:
1013 reg = R_EAX;
1014 func = HV_CPUID_FEATURES;
1015 break;
1016 case FEAT_HYPERV_EDX:
1017 reg = R_EDX;
1018 func = HV_CPUID_FEATURES;
1019 break;
1020 case FEAT_HV_RECOMM_EAX:
1021 reg = R_EAX;
1022 func = HV_CPUID_ENLIGHTMENT_INFO;
1023 break;
1024 default:
1025 return -EINVAL;
1028 entry = cpuid_find_entry(cpuid, func, 0);
1029 if (!entry) {
1030 return -ENOENT;
1033 switch (reg) {
1034 case R_EAX:
1035 *r = entry->eax;
1036 break;
1037 case R_EDX:
1038 *r = entry->edx;
1039 break;
1040 default:
1041 return -EINVAL;
1044 return 0;
1047 static int hv_cpuid_check_and_set(CPUState *cs, struct kvm_cpuid2 *cpuid,
1048 int feature)
1050 X86CPU *cpu = X86_CPU(cs);
1051 CPUX86State *env = &cpu->env;
1052 uint32_t r, fw, bits;
1053 uint64_t deps;
1054 int i, dep_feat;
1056 if (!hyperv_feat_enabled(cpu, feature) && !cpu->hyperv_passthrough) {
1057 return 0;
1060 deps = kvm_hyperv_properties[feature].dependencies;
1061 while (deps) {
1062 dep_feat = ctz64(deps);
1063 if (!(hyperv_feat_enabled(cpu, dep_feat))) {
1064 fprintf(stderr,
1065 "Hyper-V %s requires Hyper-V %s\n",
1066 kvm_hyperv_properties[feature].desc,
1067 kvm_hyperv_properties[dep_feat].desc);
1068 return 1;
1070 deps &= ~(1ull << dep_feat);
1073 for (i = 0; i < ARRAY_SIZE(kvm_hyperv_properties[feature].flags); i++) {
1074 fw = kvm_hyperv_properties[feature].flags[i].fw;
1075 bits = kvm_hyperv_properties[feature].flags[i].bits;
1077 if (!fw) {
1078 continue;
1081 if (hv_cpuid_get_fw(cpuid, fw, &r) || (r & bits) != bits) {
1082 if (hyperv_feat_enabled(cpu, feature)) {
1083 fprintf(stderr,
1084 "Hyper-V %s is not supported by kernel\n",
1085 kvm_hyperv_properties[feature].desc);
1086 return 1;
1087 } else {
1088 return 0;
1092 env->features[fw] |= bits;
1095 if (cpu->hyperv_passthrough) {
1096 cpu->hyperv_features |= BIT(feature);
1099 return 0;
1103 * Fill in Hyper-V CPUIDs. Returns the number of entries filled in cpuid_ent in
1104 * case of success, errno < 0 in case of failure and 0 when no Hyper-V
1105 * extentions are enabled.
1107 static int hyperv_handle_properties(CPUState *cs,
1108 struct kvm_cpuid_entry2 *cpuid_ent)
1110 X86CPU *cpu = X86_CPU(cs);
1111 CPUX86State *env = &cpu->env;
1112 struct kvm_cpuid2 *cpuid;
1113 struct kvm_cpuid_entry2 *c;
1114 uint32_t signature[3];
1115 uint32_t cpuid_i = 0;
1116 int r;
1118 if (!hyperv_enabled(cpu))
1119 return 0;
1121 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS) ||
1122 cpu->hyperv_passthrough) {
1123 uint16_t evmcs_version;
1125 r = kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_ENLIGHTENED_VMCS, 0,
1126 (uintptr_t)&evmcs_version);
1128 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS) && r) {
1129 fprintf(stderr, "Hyper-V %s is not supported by kernel\n",
1130 kvm_hyperv_properties[HYPERV_FEAT_EVMCS].desc);
1131 return -ENOSYS;
1134 if (!r) {
1135 env->features[FEAT_HV_RECOMM_EAX] |=
1136 HV_ENLIGHTENED_VMCS_RECOMMENDED;
1137 env->features[FEAT_HV_NESTED_EAX] = evmcs_version;
1141 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_CPUID) > 0) {
1142 cpuid = get_supported_hv_cpuid(cs);
1143 } else {
1144 cpuid = get_supported_hv_cpuid_legacy(cs);
1147 if (cpu->hyperv_passthrough) {
1148 memcpy(cpuid_ent, &cpuid->entries[0],
1149 cpuid->nent * sizeof(cpuid->entries[0]));
1151 c = cpuid_find_entry(cpuid, HV_CPUID_FEATURES, 0);
1152 if (c) {
1153 env->features[FEAT_HYPERV_EAX] = c->eax;
1154 env->features[FEAT_HYPERV_EBX] = c->ebx;
1155 env->features[FEAT_HYPERV_EDX] = c->eax;
1157 c = cpuid_find_entry(cpuid, HV_CPUID_ENLIGHTMENT_INFO, 0);
1158 if (c) {
1159 env->features[FEAT_HV_RECOMM_EAX] = c->eax;
1161 /* hv-spinlocks may have been overriden */
1162 if (cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY) {
1163 c->ebx = cpu->hyperv_spinlock_attempts;
1166 c = cpuid_find_entry(cpuid, HV_CPUID_NESTED_FEATURES, 0);
1167 if (c) {
1168 env->features[FEAT_HV_NESTED_EAX] = c->eax;
1172 /* Features */
1173 r = hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_RELAXED);
1174 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_VAPIC);
1175 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_TIME);
1176 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_CRASH);
1177 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_RESET);
1178 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_VPINDEX);
1179 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_RUNTIME);
1180 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_SYNIC);
1181 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_STIMER);
1182 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_FREQUENCIES);
1183 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_REENLIGHTENMENT);
1184 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_TLBFLUSH);
1185 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_EVMCS);
1186 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_IPI);
1187 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_STIMER_DIRECT);
1189 /* Additional dependencies not covered by kvm_hyperv_properties[] */
1190 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC) &&
1191 !cpu->hyperv_synic_kvm_only &&
1192 !hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)) {
1193 fprintf(stderr, "Hyper-V %s requires Hyper-V %s\n",
1194 kvm_hyperv_properties[HYPERV_FEAT_SYNIC].desc,
1195 kvm_hyperv_properties[HYPERV_FEAT_VPINDEX].desc);
1196 r |= 1;
1199 /* Not exposed by KVM but needed to make CPU hotplug in Windows work */
1200 env->features[FEAT_HYPERV_EDX] |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
1202 if (r) {
1203 r = -ENOSYS;
1204 goto free;
1207 if (cpu->hyperv_passthrough) {
1208 /* We already copied all feature words from KVM as is */
1209 r = cpuid->nent;
1210 goto free;
1213 c = &cpuid_ent[cpuid_i++];
1214 c->function = HV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
1215 if (!cpu->hyperv_vendor_id) {
1216 memcpy(signature, "Microsoft Hv", 12);
1217 } else {
1218 size_t len = strlen(cpu->hyperv_vendor_id);
1220 if (len > 12) {
1221 error_report("hv-vendor-id truncated to 12 characters");
1222 len = 12;
1224 memset(signature, 0, 12);
1225 memcpy(signature, cpu->hyperv_vendor_id, len);
1227 c->eax = hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS) ?
1228 HV_CPUID_NESTED_FEATURES : HV_CPUID_IMPLEMENT_LIMITS;
1229 c->ebx = signature[0];
1230 c->ecx = signature[1];
1231 c->edx = signature[2];
1233 c = &cpuid_ent[cpuid_i++];
1234 c->function = HV_CPUID_INTERFACE;
1235 memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
1236 c->eax = signature[0];
1237 c->ebx = 0;
1238 c->ecx = 0;
1239 c->edx = 0;
1241 c = &cpuid_ent[cpuid_i++];
1242 c->function = HV_CPUID_VERSION;
1243 c->eax = 0x00001bbc;
1244 c->ebx = 0x00060001;
1246 c = &cpuid_ent[cpuid_i++];
1247 c->function = HV_CPUID_FEATURES;
1248 c->eax = env->features[FEAT_HYPERV_EAX];
1249 c->ebx = env->features[FEAT_HYPERV_EBX];
1250 c->edx = env->features[FEAT_HYPERV_EDX];
1252 c = &cpuid_ent[cpuid_i++];
1253 c->function = HV_CPUID_ENLIGHTMENT_INFO;
1254 c->eax = env->features[FEAT_HV_RECOMM_EAX];
1255 c->ebx = cpu->hyperv_spinlock_attempts;
1257 c = &cpuid_ent[cpuid_i++];
1258 c->function = HV_CPUID_IMPLEMENT_LIMITS;
1259 c->eax = cpu->hv_max_vps;
1260 c->ebx = 0x40;
1262 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS)) {
1263 __u32 function;
1265 /* Create zeroed 0x40000006..0x40000009 leaves */
1266 for (function = HV_CPUID_IMPLEMENT_LIMITS + 1;
1267 function < HV_CPUID_NESTED_FEATURES; function++) {
1268 c = &cpuid_ent[cpuid_i++];
1269 c->function = function;
1272 c = &cpuid_ent[cpuid_i++];
1273 c->function = HV_CPUID_NESTED_FEATURES;
1274 c->eax = env->features[FEAT_HV_NESTED_EAX];
1276 r = cpuid_i;
1278 free:
1279 g_free(cpuid);
1281 return r;
1284 static Error *hv_passthrough_mig_blocker;
1286 static int hyperv_init_vcpu(X86CPU *cpu)
1288 CPUState *cs = CPU(cpu);
1289 Error *local_err = NULL;
1290 int ret;
1292 if (cpu->hyperv_passthrough && hv_passthrough_mig_blocker == NULL) {
1293 error_setg(&hv_passthrough_mig_blocker,
1294 "'hv-passthrough' CPU flag prevents migration, use explicit"
1295 " set of hv-* flags instead");
1296 ret = migrate_add_blocker(hv_passthrough_mig_blocker, &local_err);
1297 if (local_err) {
1298 error_report_err(local_err);
1299 error_free(hv_passthrough_mig_blocker);
1300 return ret;
1304 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX) && !hv_vpindex_settable) {
1306 * the kernel doesn't support setting vp_index; assert that its value
1307 * is in sync
1309 struct {
1310 struct kvm_msrs info;
1311 struct kvm_msr_entry entries[1];
1312 } msr_data = {
1313 .info.nmsrs = 1,
1314 .entries[0].index = HV_X64_MSR_VP_INDEX,
1317 ret = kvm_vcpu_ioctl(cs, KVM_GET_MSRS, &msr_data);
1318 if (ret < 0) {
1319 return ret;
1321 assert(ret == 1);
1323 if (msr_data.entries[0].data != hyperv_vp_index(CPU(cpu))) {
1324 error_report("kernel's vp_index != QEMU's vp_index");
1325 return -ENXIO;
1329 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
1330 uint32_t synic_cap = cpu->hyperv_synic_kvm_only ?
1331 KVM_CAP_HYPERV_SYNIC : KVM_CAP_HYPERV_SYNIC2;
1332 ret = kvm_vcpu_enable_cap(cs, synic_cap, 0);
1333 if (ret < 0) {
1334 error_report("failed to turn on HyperV SynIC in KVM: %s",
1335 strerror(-ret));
1336 return ret;
1339 if (!cpu->hyperv_synic_kvm_only) {
1340 ret = hyperv_x86_synic_add(cpu);
1341 if (ret < 0) {
1342 error_report("failed to create HyperV SynIC: %s",
1343 strerror(-ret));
1344 return ret;
1349 return 0;
1352 static Error *invtsc_mig_blocker;
1354 #define KVM_MAX_CPUID_ENTRIES 100
1356 int kvm_arch_init_vcpu(CPUState *cs)
1358 struct {
1359 struct kvm_cpuid2 cpuid;
1360 struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
1361 } cpuid_data;
1363 * The kernel defines these structs with padding fields so there
1364 * should be no extra padding in our cpuid_data struct.
1366 QEMU_BUILD_BUG_ON(sizeof(cpuid_data) !=
1367 sizeof(struct kvm_cpuid2) +
1368 sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES);
1370 X86CPU *cpu = X86_CPU(cs);
1371 CPUX86State *env = &cpu->env;
1372 uint32_t limit, i, j, cpuid_i;
1373 uint32_t unused;
1374 struct kvm_cpuid_entry2 *c;
1375 uint32_t signature[3];
1376 int kvm_base = KVM_CPUID_SIGNATURE;
1377 int max_nested_state_len;
1378 int r;
1379 Error *local_err = NULL;
1381 memset(&cpuid_data, 0, sizeof(cpuid_data));
1383 cpuid_i = 0;
1385 r = kvm_arch_set_tsc_khz(cs);
1386 if (r < 0) {
1387 return r;
1390 /* vcpu's TSC frequency is either specified by user, or following
1391 * the value used by KVM if the former is not present. In the
1392 * latter case, we query it from KVM and record in env->tsc_khz,
1393 * so that vcpu's TSC frequency can be migrated later via this field.
1395 if (!env->tsc_khz) {
1396 r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
1397 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
1398 -ENOTSUP;
1399 if (r > 0) {
1400 env->tsc_khz = r;
1404 /* Paravirtualization CPUIDs */
1405 r = hyperv_handle_properties(cs, cpuid_data.entries);
1406 if (r < 0) {
1407 return r;
1408 } else if (r > 0) {
1409 cpuid_i = r;
1410 kvm_base = KVM_CPUID_SIGNATURE_NEXT;
1411 has_msr_hv_hypercall = true;
1414 if (cpu->expose_kvm) {
1415 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
1416 c = &cpuid_data.entries[cpuid_i++];
1417 c->function = KVM_CPUID_SIGNATURE | kvm_base;
1418 c->eax = KVM_CPUID_FEATURES | kvm_base;
1419 c->ebx = signature[0];
1420 c->ecx = signature[1];
1421 c->edx = signature[2];
1423 c = &cpuid_data.entries[cpuid_i++];
1424 c->function = KVM_CPUID_FEATURES | kvm_base;
1425 c->eax = env->features[FEAT_KVM];
1426 c->edx = env->features[FEAT_KVM_HINTS];
1429 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
1431 for (i = 0; i <= limit; i++) {
1432 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1433 fprintf(stderr, "unsupported level value: 0x%x\n", limit);
1434 abort();
1436 c = &cpuid_data.entries[cpuid_i++];
1438 switch (i) {
1439 case 2: {
1440 /* Keep reading function 2 till all the input is received */
1441 int times;
1443 c->function = i;
1444 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
1445 KVM_CPUID_FLAG_STATE_READ_NEXT;
1446 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1447 times = c->eax & 0xff;
1449 for (j = 1; j < times; ++j) {
1450 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1451 fprintf(stderr, "cpuid_data is full, no space for "
1452 "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
1453 abort();
1455 c = &cpuid_data.entries[cpuid_i++];
1456 c->function = i;
1457 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
1458 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1460 break;
1462 case 0x1f:
1463 if (env->nr_dies < 2) {
1464 break;
1466 case 4:
1467 case 0xb:
1468 case 0xd:
1469 for (j = 0; ; j++) {
1470 if (i == 0xd && j == 64) {
1471 break;
1474 if (i == 0x1f && j == 64) {
1475 break;
1478 c->function = i;
1479 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1480 c->index = j;
1481 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1483 if (i == 4 && c->eax == 0) {
1484 break;
1486 if (i == 0xb && !(c->ecx & 0xff00)) {
1487 break;
1489 if (i == 0x1f && !(c->ecx & 0xff00)) {
1490 break;
1492 if (i == 0xd && c->eax == 0) {
1493 continue;
1495 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1496 fprintf(stderr, "cpuid_data is full, no space for "
1497 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1498 abort();
1500 c = &cpuid_data.entries[cpuid_i++];
1502 break;
1503 case 0x14: {
1504 uint32_t times;
1506 c->function = i;
1507 c->index = 0;
1508 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1509 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1510 times = c->eax;
1512 for (j = 1; j <= times; ++j) {
1513 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1514 fprintf(stderr, "cpuid_data is full, no space for "
1515 "cpuid(eax:0x14,ecx:0x%x)\n", j);
1516 abort();
1518 c = &cpuid_data.entries[cpuid_i++];
1519 c->function = i;
1520 c->index = j;
1521 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1522 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1524 break;
1526 default:
1527 c->function = i;
1528 c->flags = 0;
1529 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1530 break;
1534 if (limit >= 0x0a) {
1535 uint32_t eax, edx;
1537 cpu_x86_cpuid(env, 0x0a, 0, &eax, &unused, &unused, &edx);
1539 has_architectural_pmu_version = eax & 0xff;
1540 if (has_architectural_pmu_version > 0) {
1541 num_architectural_pmu_gp_counters = (eax & 0xff00) >> 8;
1543 /* Shouldn't be more than 32, since that's the number of bits
1544 * available in EBX to tell us _which_ counters are available.
1545 * Play it safe.
1547 if (num_architectural_pmu_gp_counters > MAX_GP_COUNTERS) {
1548 num_architectural_pmu_gp_counters = MAX_GP_COUNTERS;
1551 if (has_architectural_pmu_version > 1) {
1552 num_architectural_pmu_fixed_counters = edx & 0x1f;
1554 if (num_architectural_pmu_fixed_counters > MAX_FIXED_COUNTERS) {
1555 num_architectural_pmu_fixed_counters = MAX_FIXED_COUNTERS;
1561 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
1563 for (i = 0x80000000; i <= limit; i++) {
1564 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1565 fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
1566 abort();
1568 c = &cpuid_data.entries[cpuid_i++];
1570 switch (i) {
1571 case 0x8000001d:
1572 /* Query for all AMD cache information leaves */
1573 for (j = 0; ; j++) {
1574 c->function = i;
1575 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1576 c->index = j;
1577 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1579 if (c->eax == 0) {
1580 break;
1582 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1583 fprintf(stderr, "cpuid_data is full, no space for "
1584 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1585 abort();
1587 c = &cpuid_data.entries[cpuid_i++];
1589 break;
1590 default:
1591 c->function = i;
1592 c->flags = 0;
1593 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1594 break;
1598 /* Call Centaur's CPUID instructions they are supported. */
1599 if (env->cpuid_xlevel2 > 0) {
1600 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
1602 for (i = 0xC0000000; i <= limit; i++) {
1603 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1604 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
1605 abort();
1607 c = &cpuid_data.entries[cpuid_i++];
1609 c->function = i;
1610 c->flags = 0;
1611 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1615 cpuid_data.cpuid.nent = cpuid_i;
1617 if (((env->cpuid_version >> 8)&0xF) >= 6
1618 && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
1619 (CPUID_MCE | CPUID_MCA)
1620 && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
1621 uint64_t mcg_cap, unsupported_caps;
1622 int banks;
1623 int ret;
1625 ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
1626 if (ret < 0) {
1627 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
1628 return ret;
1631 if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
1632 error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
1633 (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
1634 return -ENOTSUP;
1637 unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
1638 if (unsupported_caps) {
1639 if (unsupported_caps & MCG_LMCE_P) {
1640 error_report("kvm: LMCE not supported");
1641 return -ENOTSUP;
1643 warn_report("Unsupported MCG_CAP bits: 0x%" PRIx64,
1644 unsupported_caps);
1647 env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
1648 ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
1649 if (ret < 0) {
1650 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
1651 return ret;
1655 qemu_add_vm_change_state_handler(cpu_update_state, env);
1657 c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
1658 if (c) {
1659 has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
1660 !!(c->ecx & CPUID_EXT_SMX);
1663 if (env->mcg_cap & MCG_LMCE_P) {
1664 has_msr_mcg_ext_ctl = has_msr_feature_control = true;
1667 if (!env->user_tsc_khz) {
1668 if ((env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC) &&
1669 invtsc_mig_blocker == NULL) {
1670 error_setg(&invtsc_mig_blocker,
1671 "State blocked by non-migratable CPU device"
1672 " (invtsc flag)");
1673 r = migrate_add_blocker(invtsc_mig_blocker, &local_err);
1674 if (local_err) {
1675 error_report_err(local_err);
1676 error_free(invtsc_mig_blocker);
1677 return r;
1682 if (cpu->vmware_cpuid_freq
1683 /* Guests depend on 0x40000000 to detect this feature, so only expose
1684 * it if KVM exposes leaf 0x40000000. (Conflicts with Hyper-V) */
1685 && cpu->expose_kvm
1686 && kvm_base == KVM_CPUID_SIGNATURE
1687 /* TSC clock must be stable and known for this feature. */
1688 && tsc_is_stable_and_known(env)) {
1690 c = &cpuid_data.entries[cpuid_i++];
1691 c->function = KVM_CPUID_SIGNATURE | 0x10;
1692 c->eax = env->tsc_khz;
1693 /* LAPIC resolution of 1ns (freq: 1GHz) is hardcoded in KVM's
1694 * APIC_BUS_CYCLE_NS */
1695 c->ebx = 1000000;
1696 c->ecx = c->edx = 0;
1698 c = cpuid_find_entry(&cpuid_data.cpuid, kvm_base, 0);
1699 c->eax = MAX(c->eax, KVM_CPUID_SIGNATURE | 0x10);
1702 cpuid_data.cpuid.nent = cpuid_i;
1704 cpuid_data.cpuid.padding = 0;
1705 r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
1706 if (r) {
1707 goto fail;
1710 if (has_xsave) {
1711 env->xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
1714 max_nested_state_len = kvm_max_nested_state_length();
1715 if (max_nested_state_len > 0) {
1716 assert(max_nested_state_len >= offsetof(struct kvm_nested_state, data));
1718 if (cpu_has_vmx(env)) {
1719 struct kvm_vmx_nested_state_hdr *vmx_hdr;
1721 env->nested_state = g_malloc0(max_nested_state_len);
1722 env->nested_state->size = max_nested_state_len;
1723 env->nested_state->format = KVM_STATE_NESTED_FORMAT_VMX;
1725 vmx_hdr = &env->nested_state->hdr.vmx;
1726 vmx_hdr->vmxon_pa = -1ull;
1727 vmx_hdr->vmcs12_pa = -1ull;
1731 cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
1733 if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
1734 has_msr_tsc_aux = false;
1737 r = hyperv_init_vcpu(cpu);
1738 if (r) {
1739 goto fail;
1742 return 0;
1744 fail:
1745 migrate_del_blocker(invtsc_mig_blocker);
1747 return r;
1750 int kvm_arch_destroy_vcpu(CPUState *cs)
1752 X86CPU *cpu = X86_CPU(cs);
1753 CPUX86State *env = &cpu->env;
1755 if (cpu->kvm_msr_buf) {
1756 g_free(cpu->kvm_msr_buf);
1757 cpu->kvm_msr_buf = NULL;
1760 if (env->nested_state) {
1761 g_free(env->nested_state);
1762 env->nested_state = NULL;
1765 return 0;
1768 void kvm_arch_reset_vcpu(X86CPU *cpu)
1770 CPUX86State *env = &cpu->env;
1772 env->xcr0 = 1;
1773 if (kvm_irqchip_in_kernel()) {
1774 env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
1775 KVM_MP_STATE_UNINITIALIZED;
1776 } else {
1777 env->mp_state = KVM_MP_STATE_RUNNABLE;
1780 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
1781 int i;
1782 for (i = 0; i < ARRAY_SIZE(env->msr_hv_synic_sint); i++) {
1783 env->msr_hv_synic_sint[i] = HV_SINT_MASKED;
1786 hyperv_x86_synic_reset(cpu);
1790 void kvm_arch_do_init_vcpu(X86CPU *cpu)
1792 CPUX86State *env = &cpu->env;
1794 /* APs get directly into wait-for-SIPI state. */
1795 if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
1796 env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
1800 static int kvm_get_supported_feature_msrs(KVMState *s)
1802 int ret = 0;
1804 if (kvm_feature_msrs != NULL) {
1805 return 0;
1808 if (!kvm_check_extension(s, KVM_CAP_GET_MSR_FEATURES)) {
1809 return 0;
1812 struct kvm_msr_list msr_list;
1814 msr_list.nmsrs = 0;
1815 ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, &msr_list);
1816 if (ret < 0 && ret != -E2BIG) {
1817 error_report("Fetch KVM feature MSR list failed: %s",
1818 strerror(-ret));
1819 return ret;
1822 assert(msr_list.nmsrs > 0);
1823 kvm_feature_msrs = (struct kvm_msr_list *) \
1824 g_malloc0(sizeof(msr_list) +
1825 msr_list.nmsrs * sizeof(msr_list.indices[0]));
1827 kvm_feature_msrs->nmsrs = msr_list.nmsrs;
1828 ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, kvm_feature_msrs);
1830 if (ret < 0) {
1831 error_report("Fetch KVM feature MSR list failed: %s",
1832 strerror(-ret));
1833 g_free(kvm_feature_msrs);
1834 kvm_feature_msrs = NULL;
1835 return ret;
1838 return 0;
1841 static int kvm_get_supported_msrs(KVMState *s)
1843 static int kvm_supported_msrs;
1844 int ret = 0;
1846 /* first time */
1847 if (kvm_supported_msrs == 0) {
1848 struct kvm_msr_list msr_list, *kvm_msr_list;
1850 kvm_supported_msrs = -1;
1852 /* Obtain MSR list from KVM. These are the MSRs that we must
1853 * save/restore */
1854 msr_list.nmsrs = 0;
1855 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
1856 if (ret < 0 && ret != -E2BIG) {
1857 return ret;
1859 /* Old kernel modules had a bug and could write beyond the provided
1860 memory. Allocate at least a safe amount of 1K. */
1861 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
1862 msr_list.nmsrs *
1863 sizeof(msr_list.indices[0])));
1865 kvm_msr_list->nmsrs = msr_list.nmsrs;
1866 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
1867 if (ret >= 0) {
1868 int i;
1870 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
1871 switch (kvm_msr_list->indices[i]) {
1872 case MSR_STAR:
1873 has_msr_star = true;
1874 break;
1875 case MSR_VM_HSAVE_PA:
1876 has_msr_hsave_pa = true;
1877 break;
1878 case MSR_TSC_AUX:
1879 has_msr_tsc_aux = true;
1880 break;
1881 case MSR_TSC_ADJUST:
1882 has_msr_tsc_adjust = true;
1883 break;
1884 case MSR_IA32_TSCDEADLINE:
1885 has_msr_tsc_deadline = true;
1886 break;
1887 case MSR_IA32_SMBASE:
1888 has_msr_smbase = true;
1889 break;
1890 case MSR_SMI_COUNT:
1891 has_msr_smi_count = true;
1892 break;
1893 case MSR_IA32_MISC_ENABLE:
1894 has_msr_misc_enable = true;
1895 break;
1896 case MSR_IA32_BNDCFGS:
1897 has_msr_bndcfgs = true;
1898 break;
1899 case MSR_IA32_XSS:
1900 has_msr_xss = true;
1901 break;
1902 case HV_X64_MSR_CRASH_CTL:
1903 has_msr_hv_crash = true;
1904 break;
1905 case HV_X64_MSR_RESET:
1906 has_msr_hv_reset = true;
1907 break;
1908 case HV_X64_MSR_VP_INDEX:
1909 has_msr_hv_vpindex = true;
1910 break;
1911 case HV_X64_MSR_VP_RUNTIME:
1912 has_msr_hv_runtime = true;
1913 break;
1914 case HV_X64_MSR_SCONTROL:
1915 has_msr_hv_synic = true;
1916 break;
1917 case HV_X64_MSR_STIMER0_CONFIG:
1918 has_msr_hv_stimer = true;
1919 break;
1920 case HV_X64_MSR_TSC_FREQUENCY:
1921 has_msr_hv_frequencies = true;
1922 break;
1923 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
1924 has_msr_hv_reenlightenment = true;
1925 break;
1926 case MSR_IA32_SPEC_CTRL:
1927 has_msr_spec_ctrl = true;
1928 break;
1929 case MSR_VIRT_SSBD:
1930 has_msr_virt_ssbd = true;
1931 break;
1932 case MSR_IA32_ARCH_CAPABILITIES:
1933 has_msr_arch_capabs = true;
1934 break;
1935 case MSR_IA32_CORE_CAPABILITY:
1936 has_msr_core_capabs = true;
1937 break;
1942 g_free(kvm_msr_list);
1945 return ret;
1948 static Notifier smram_machine_done;
1949 static KVMMemoryListener smram_listener;
1950 static AddressSpace smram_address_space;
1951 static MemoryRegion smram_as_root;
1952 static MemoryRegion smram_as_mem;
1954 static void register_smram_listener(Notifier *n, void *unused)
1956 MemoryRegion *smram =
1957 (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
1959 /* Outer container... */
1960 memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
1961 memory_region_set_enabled(&smram_as_root, true);
1963 /* ... with two regions inside: normal system memory with low
1964 * priority, and...
1966 memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
1967 get_system_memory(), 0, ~0ull);
1968 memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
1969 memory_region_set_enabled(&smram_as_mem, true);
1971 if (smram) {
1972 /* ... SMRAM with higher priority */
1973 memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
1974 memory_region_set_enabled(smram, true);
1977 address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
1978 kvm_memory_listener_register(kvm_state, &smram_listener,
1979 &smram_address_space, 1);
1982 int kvm_arch_init(MachineState *ms, KVMState *s)
1984 uint64_t identity_base = 0xfffbc000;
1985 uint64_t shadow_mem;
1986 int ret;
1987 struct utsname utsname;
1989 has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1990 has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1991 has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1993 hv_vpindex_settable = kvm_check_extension(s, KVM_CAP_HYPERV_VP_INDEX);
1995 has_exception_payload = kvm_check_extension(s, KVM_CAP_EXCEPTION_PAYLOAD);
1996 if (has_exception_payload) {
1997 ret = kvm_vm_enable_cap(s, KVM_CAP_EXCEPTION_PAYLOAD, 0, true);
1998 if (ret < 0) {
1999 error_report("kvm: Failed to enable exception payload cap: %s",
2000 strerror(-ret));
2001 return ret;
2005 ret = kvm_get_supported_msrs(s);
2006 if (ret < 0) {
2007 return ret;
2010 kvm_get_supported_feature_msrs(s);
2012 uname(&utsname);
2013 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
2016 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
2017 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
2018 * Since these must be part of guest physical memory, we need to allocate
2019 * them, both by setting their start addresses in the kernel and by
2020 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
2022 * Older KVM versions may not support setting the identity map base. In
2023 * that case we need to stick with the default, i.e. a 256K maximum BIOS
2024 * size.
2026 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
2027 /* Allows up to 16M BIOSes. */
2028 identity_base = 0xfeffc000;
2030 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
2031 if (ret < 0) {
2032 return ret;
2036 /* Set TSS base one page after EPT identity map. */
2037 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
2038 if (ret < 0) {
2039 return ret;
2042 /* Tell fw_cfg to notify the BIOS to reserve the range. */
2043 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
2044 if (ret < 0) {
2045 fprintf(stderr, "e820_add_entry() table is full\n");
2046 return ret;
2048 qemu_register_reset(kvm_unpoison_all, NULL);
2050 shadow_mem = machine_kvm_shadow_mem(ms);
2051 if (shadow_mem != -1) {
2052 shadow_mem /= 4096;
2053 ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
2054 if (ret < 0) {
2055 return ret;
2059 if (kvm_check_extension(s, KVM_CAP_X86_SMM) &&
2060 object_dynamic_cast(OBJECT(ms), TYPE_PC_MACHINE) &&
2061 pc_machine_is_smm_enabled(PC_MACHINE(ms))) {
2062 smram_machine_done.notify = register_smram_listener;
2063 qemu_add_machine_init_done_notifier(&smram_machine_done);
2066 if (enable_cpu_pm) {
2067 int disable_exits = kvm_check_extension(s, KVM_CAP_X86_DISABLE_EXITS);
2068 int ret;
2070 /* Work around for kernel header with a typo. TODO: fix header and drop. */
2071 #if defined(KVM_X86_DISABLE_EXITS_HTL) && !defined(KVM_X86_DISABLE_EXITS_HLT)
2072 #define KVM_X86_DISABLE_EXITS_HLT KVM_X86_DISABLE_EXITS_HTL
2073 #endif
2074 if (disable_exits) {
2075 disable_exits &= (KVM_X86_DISABLE_EXITS_MWAIT |
2076 KVM_X86_DISABLE_EXITS_HLT |
2077 KVM_X86_DISABLE_EXITS_PAUSE);
2080 ret = kvm_vm_enable_cap(s, KVM_CAP_X86_DISABLE_EXITS, 0,
2081 disable_exits);
2082 if (ret < 0) {
2083 error_report("kvm: guest stopping CPU not supported: %s",
2084 strerror(-ret));
2088 return 0;
2091 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2093 lhs->selector = rhs->selector;
2094 lhs->base = rhs->base;
2095 lhs->limit = rhs->limit;
2096 lhs->type = 3;
2097 lhs->present = 1;
2098 lhs->dpl = 3;
2099 lhs->db = 0;
2100 lhs->s = 1;
2101 lhs->l = 0;
2102 lhs->g = 0;
2103 lhs->avl = 0;
2104 lhs->unusable = 0;
2107 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2109 unsigned flags = rhs->flags;
2110 lhs->selector = rhs->selector;
2111 lhs->base = rhs->base;
2112 lhs->limit = rhs->limit;
2113 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
2114 lhs->present = (flags & DESC_P_MASK) != 0;
2115 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
2116 lhs->db = (flags >> DESC_B_SHIFT) & 1;
2117 lhs->s = (flags & DESC_S_MASK) != 0;
2118 lhs->l = (flags >> DESC_L_SHIFT) & 1;
2119 lhs->g = (flags & DESC_G_MASK) != 0;
2120 lhs->avl = (flags & DESC_AVL_MASK) != 0;
2121 lhs->unusable = !lhs->present;
2122 lhs->padding = 0;
2125 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
2127 lhs->selector = rhs->selector;
2128 lhs->base = rhs->base;
2129 lhs->limit = rhs->limit;
2130 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
2131 ((rhs->present && !rhs->unusable) * DESC_P_MASK) |
2132 (rhs->dpl << DESC_DPL_SHIFT) |
2133 (rhs->db << DESC_B_SHIFT) |
2134 (rhs->s * DESC_S_MASK) |
2135 (rhs->l << DESC_L_SHIFT) |
2136 (rhs->g * DESC_G_MASK) |
2137 (rhs->avl * DESC_AVL_MASK);
2140 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
2142 if (set) {
2143 *kvm_reg = *qemu_reg;
2144 } else {
2145 *qemu_reg = *kvm_reg;
2149 static int kvm_getput_regs(X86CPU *cpu, int set)
2151 CPUX86State *env = &cpu->env;
2152 struct kvm_regs regs;
2153 int ret = 0;
2155 if (!set) {
2156 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
2157 if (ret < 0) {
2158 return ret;
2162 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
2163 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
2164 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
2165 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
2166 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
2167 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
2168 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
2169 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
2170 #ifdef TARGET_X86_64
2171 kvm_getput_reg(&regs.r8, &env->regs[8], set);
2172 kvm_getput_reg(&regs.r9, &env->regs[9], set);
2173 kvm_getput_reg(&regs.r10, &env->regs[10], set);
2174 kvm_getput_reg(&regs.r11, &env->regs[11], set);
2175 kvm_getput_reg(&regs.r12, &env->regs[12], set);
2176 kvm_getput_reg(&regs.r13, &env->regs[13], set);
2177 kvm_getput_reg(&regs.r14, &env->regs[14], set);
2178 kvm_getput_reg(&regs.r15, &env->regs[15], set);
2179 #endif
2181 kvm_getput_reg(&regs.rflags, &env->eflags, set);
2182 kvm_getput_reg(&regs.rip, &env->eip, set);
2184 if (set) {
2185 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
2188 return ret;
2191 static int kvm_put_fpu(X86CPU *cpu)
2193 CPUX86State *env = &cpu->env;
2194 struct kvm_fpu fpu;
2195 int i;
2197 memset(&fpu, 0, sizeof fpu);
2198 fpu.fsw = env->fpus & ~(7 << 11);
2199 fpu.fsw |= (env->fpstt & 7) << 11;
2200 fpu.fcw = env->fpuc;
2201 fpu.last_opcode = env->fpop;
2202 fpu.last_ip = env->fpip;
2203 fpu.last_dp = env->fpdp;
2204 for (i = 0; i < 8; ++i) {
2205 fpu.ftwx |= (!env->fptags[i]) << i;
2207 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
2208 for (i = 0; i < CPU_NB_REGS; i++) {
2209 stq_p(&fpu.xmm[i][0], env->xmm_regs[i].ZMM_Q(0));
2210 stq_p(&fpu.xmm[i][8], env->xmm_regs[i].ZMM_Q(1));
2212 fpu.mxcsr = env->mxcsr;
2214 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
2217 #define XSAVE_FCW_FSW 0
2218 #define XSAVE_FTW_FOP 1
2219 #define XSAVE_CWD_RIP 2
2220 #define XSAVE_CWD_RDP 4
2221 #define XSAVE_MXCSR 6
2222 #define XSAVE_ST_SPACE 8
2223 #define XSAVE_XMM_SPACE 40
2224 #define XSAVE_XSTATE_BV 128
2225 #define XSAVE_YMMH_SPACE 144
2226 #define XSAVE_BNDREGS 240
2227 #define XSAVE_BNDCSR 256
2228 #define XSAVE_OPMASK 272
2229 #define XSAVE_ZMM_Hi256 288
2230 #define XSAVE_Hi16_ZMM 416
2231 #define XSAVE_PKRU 672
2233 #define XSAVE_BYTE_OFFSET(word_offset) \
2234 ((word_offset) * sizeof_field(struct kvm_xsave, region[0]))
2236 #define ASSERT_OFFSET(word_offset, field) \
2237 QEMU_BUILD_BUG_ON(XSAVE_BYTE_OFFSET(word_offset) != \
2238 offsetof(X86XSaveArea, field))
2240 ASSERT_OFFSET(XSAVE_FCW_FSW, legacy.fcw);
2241 ASSERT_OFFSET(XSAVE_FTW_FOP, legacy.ftw);
2242 ASSERT_OFFSET(XSAVE_CWD_RIP, legacy.fpip);
2243 ASSERT_OFFSET(XSAVE_CWD_RDP, legacy.fpdp);
2244 ASSERT_OFFSET(XSAVE_MXCSR, legacy.mxcsr);
2245 ASSERT_OFFSET(XSAVE_ST_SPACE, legacy.fpregs);
2246 ASSERT_OFFSET(XSAVE_XMM_SPACE, legacy.xmm_regs);
2247 ASSERT_OFFSET(XSAVE_XSTATE_BV, header.xstate_bv);
2248 ASSERT_OFFSET(XSAVE_YMMH_SPACE, avx_state);
2249 ASSERT_OFFSET(XSAVE_BNDREGS, bndreg_state);
2250 ASSERT_OFFSET(XSAVE_BNDCSR, bndcsr_state);
2251 ASSERT_OFFSET(XSAVE_OPMASK, opmask_state);
2252 ASSERT_OFFSET(XSAVE_ZMM_Hi256, zmm_hi256_state);
2253 ASSERT_OFFSET(XSAVE_Hi16_ZMM, hi16_zmm_state);
2254 ASSERT_OFFSET(XSAVE_PKRU, pkru_state);
2256 static int kvm_put_xsave(X86CPU *cpu)
2258 CPUX86State *env = &cpu->env;
2259 X86XSaveArea *xsave = env->xsave_buf;
2261 if (!has_xsave) {
2262 return kvm_put_fpu(cpu);
2264 x86_cpu_xsave_all_areas(cpu, xsave);
2266 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
2269 static int kvm_put_xcrs(X86CPU *cpu)
2271 CPUX86State *env = &cpu->env;
2272 struct kvm_xcrs xcrs = {};
2274 if (!has_xcrs) {
2275 return 0;
2278 xcrs.nr_xcrs = 1;
2279 xcrs.flags = 0;
2280 xcrs.xcrs[0].xcr = 0;
2281 xcrs.xcrs[0].value = env->xcr0;
2282 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
2285 static int kvm_put_sregs(X86CPU *cpu)
2287 CPUX86State *env = &cpu->env;
2288 struct kvm_sregs sregs;
2290 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
2291 if (env->interrupt_injected >= 0) {
2292 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
2293 (uint64_t)1 << (env->interrupt_injected % 64);
2296 if ((env->eflags & VM_MASK)) {
2297 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
2298 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
2299 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
2300 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
2301 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
2302 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
2303 } else {
2304 set_seg(&sregs.cs, &env->segs[R_CS]);
2305 set_seg(&sregs.ds, &env->segs[R_DS]);
2306 set_seg(&sregs.es, &env->segs[R_ES]);
2307 set_seg(&sregs.fs, &env->segs[R_FS]);
2308 set_seg(&sregs.gs, &env->segs[R_GS]);
2309 set_seg(&sregs.ss, &env->segs[R_SS]);
2312 set_seg(&sregs.tr, &env->tr);
2313 set_seg(&sregs.ldt, &env->ldt);
2315 sregs.idt.limit = env->idt.limit;
2316 sregs.idt.base = env->idt.base;
2317 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
2318 sregs.gdt.limit = env->gdt.limit;
2319 sregs.gdt.base = env->gdt.base;
2320 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
2322 sregs.cr0 = env->cr[0];
2323 sregs.cr2 = env->cr[2];
2324 sregs.cr3 = env->cr[3];
2325 sregs.cr4 = env->cr[4];
2327 sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
2328 sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
2330 sregs.efer = env->efer;
2332 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
2335 static void kvm_msr_buf_reset(X86CPU *cpu)
2337 memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
2340 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
2342 struct kvm_msrs *msrs = cpu->kvm_msr_buf;
2343 void *limit = ((void *)msrs) + MSR_BUF_SIZE;
2344 struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
2346 assert((void *)(entry + 1) <= limit);
2348 entry->index = index;
2349 entry->reserved = 0;
2350 entry->data = value;
2351 msrs->nmsrs++;
2354 static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
2356 kvm_msr_buf_reset(cpu);
2357 kvm_msr_entry_add(cpu, index, value);
2359 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
2362 void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
2364 int ret;
2366 ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
2367 assert(ret == 1);
2370 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
2372 CPUX86State *env = &cpu->env;
2373 int ret;
2375 if (!has_msr_tsc_deadline) {
2376 return 0;
2379 ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
2380 if (ret < 0) {
2381 return ret;
2384 assert(ret == 1);
2385 return 0;
2389 * Provide a separate write service for the feature control MSR in order to
2390 * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
2391 * before writing any other state because forcibly leaving nested mode
2392 * invalidates the VCPU state.
2394 static int kvm_put_msr_feature_control(X86CPU *cpu)
2396 int ret;
2398 if (!has_msr_feature_control) {
2399 return 0;
2402 ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
2403 cpu->env.msr_ia32_feature_control);
2404 if (ret < 0) {
2405 return ret;
2408 assert(ret == 1);
2409 return 0;
2412 static int kvm_put_msrs(X86CPU *cpu, int level)
2414 CPUX86State *env = &cpu->env;
2415 int i;
2416 int ret;
2418 kvm_msr_buf_reset(cpu);
2420 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
2421 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
2422 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
2423 kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
2424 if (has_msr_star) {
2425 kvm_msr_entry_add(cpu, MSR_STAR, env->star);
2427 if (has_msr_hsave_pa) {
2428 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
2430 if (has_msr_tsc_aux) {
2431 kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
2433 if (has_msr_tsc_adjust) {
2434 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
2436 if (has_msr_misc_enable) {
2437 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
2438 env->msr_ia32_misc_enable);
2440 if (has_msr_smbase) {
2441 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
2443 if (has_msr_smi_count) {
2444 kvm_msr_entry_add(cpu, MSR_SMI_COUNT, env->msr_smi_count);
2446 if (has_msr_bndcfgs) {
2447 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
2449 if (has_msr_xss) {
2450 kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
2452 if (has_msr_spec_ctrl) {
2453 kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, env->spec_ctrl);
2455 if (has_msr_virt_ssbd) {
2456 kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, env->virt_ssbd);
2459 #ifdef TARGET_X86_64
2460 if (lm_capable_kernel) {
2461 kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
2462 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
2463 kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
2464 kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
2466 #endif
2468 /* If host supports feature MSR, write down. */
2469 if (has_msr_arch_capabs) {
2470 kvm_msr_entry_add(cpu, MSR_IA32_ARCH_CAPABILITIES,
2471 env->features[FEAT_ARCH_CAPABILITIES]);
2474 if (has_msr_core_capabs) {
2475 kvm_msr_entry_add(cpu, MSR_IA32_CORE_CAPABILITY,
2476 env->features[FEAT_CORE_CAPABILITY]);
2480 * The following MSRs have side effects on the guest or are too heavy
2481 * for normal writeback. Limit them to reset or full state updates.
2483 if (level >= KVM_PUT_RESET_STATE) {
2484 kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
2485 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
2486 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
2487 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
2488 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
2490 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
2491 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
2493 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
2494 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
2496 if (has_architectural_pmu_version > 0) {
2497 if (has_architectural_pmu_version > 1) {
2498 /* Stop the counter. */
2499 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
2500 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
2503 /* Set the counter values. */
2504 for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
2505 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
2506 env->msr_fixed_counters[i]);
2508 for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
2509 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
2510 env->msr_gp_counters[i]);
2511 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
2512 env->msr_gp_evtsel[i]);
2514 if (has_architectural_pmu_version > 1) {
2515 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
2516 env->msr_global_status);
2517 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
2518 env->msr_global_ovf_ctrl);
2520 /* Now start the PMU. */
2521 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
2522 env->msr_fixed_ctr_ctrl);
2523 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
2524 env->msr_global_ctrl);
2528 * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,
2529 * only sync them to KVM on the first cpu
2531 if (current_cpu == first_cpu) {
2532 if (has_msr_hv_hypercall) {
2533 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
2534 env->msr_hv_guest_os_id);
2535 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
2536 env->msr_hv_hypercall);
2538 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
2539 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,
2540 env->msr_hv_tsc);
2542 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
2543 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL,
2544 env->msr_hv_reenlightenment_control);
2545 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL,
2546 env->msr_hv_tsc_emulation_control);
2547 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS,
2548 env->msr_hv_tsc_emulation_status);
2551 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
2552 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
2553 env->msr_hv_vapic);
2555 if (has_msr_hv_crash) {
2556 int j;
2558 for (j = 0; j < HV_CRASH_PARAMS; j++)
2559 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
2560 env->msr_hv_crash_params[j]);
2562 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);
2564 if (has_msr_hv_runtime) {
2565 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
2567 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)
2568 && hv_vpindex_settable) {
2569 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_INDEX,
2570 hyperv_vp_index(CPU(cpu)));
2572 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
2573 int j;
2575 kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);
2577 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
2578 env->msr_hv_synic_control);
2579 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
2580 env->msr_hv_synic_evt_page);
2581 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
2582 env->msr_hv_synic_msg_page);
2584 for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
2585 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
2586 env->msr_hv_synic_sint[j]);
2589 if (has_msr_hv_stimer) {
2590 int j;
2592 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
2593 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
2594 env->msr_hv_stimer_config[j]);
2597 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
2598 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
2599 env->msr_hv_stimer_count[j]);
2602 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
2603 uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
2605 kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
2606 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
2607 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
2608 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
2609 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
2610 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
2611 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
2612 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
2613 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
2614 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
2615 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
2616 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
2617 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
2618 /* The CPU GPs if we write to a bit above the physical limit of
2619 * the host CPU (and KVM emulates that)
2621 uint64_t mask = env->mtrr_var[i].mask;
2622 mask &= phys_mask;
2624 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
2625 env->mtrr_var[i].base);
2626 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
2629 if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
2630 int addr_num = kvm_arch_get_supported_cpuid(kvm_state,
2631 0x14, 1, R_EAX) & 0x7;
2633 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL,
2634 env->msr_rtit_ctrl);
2635 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS,
2636 env->msr_rtit_status);
2637 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE,
2638 env->msr_rtit_output_base);
2639 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK,
2640 env->msr_rtit_output_mask);
2641 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH,
2642 env->msr_rtit_cr3_match);
2643 for (i = 0; i < addr_num; i++) {
2644 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i,
2645 env->msr_rtit_addrs[i]);
2649 /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
2650 * kvm_put_msr_feature_control. */
2652 if (env->mcg_cap) {
2653 int i;
2655 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
2656 kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
2657 if (has_msr_mcg_ext_ctl) {
2658 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
2660 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
2661 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
2665 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
2666 if (ret < 0) {
2667 return ret;
2670 if (ret < cpu->kvm_msr_buf->nmsrs) {
2671 struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
2672 error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,
2673 (uint32_t)e->index, (uint64_t)e->data);
2676 assert(ret == cpu->kvm_msr_buf->nmsrs);
2677 return 0;
2681 static int kvm_get_fpu(X86CPU *cpu)
2683 CPUX86State *env = &cpu->env;
2684 struct kvm_fpu fpu;
2685 int i, ret;
2687 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
2688 if (ret < 0) {
2689 return ret;
2692 env->fpstt = (fpu.fsw >> 11) & 7;
2693 env->fpus = fpu.fsw;
2694 env->fpuc = fpu.fcw;
2695 env->fpop = fpu.last_opcode;
2696 env->fpip = fpu.last_ip;
2697 env->fpdp = fpu.last_dp;
2698 for (i = 0; i < 8; ++i) {
2699 env->fptags[i] = !((fpu.ftwx >> i) & 1);
2701 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
2702 for (i = 0; i < CPU_NB_REGS; i++) {
2703 env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
2704 env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
2706 env->mxcsr = fpu.mxcsr;
2708 return 0;
2711 static int kvm_get_xsave(X86CPU *cpu)
2713 CPUX86State *env = &cpu->env;
2714 X86XSaveArea *xsave = env->xsave_buf;
2715 int ret;
2717 if (!has_xsave) {
2718 return kvm_get_fpu(cpu);
2721 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
2722 if (ret < 0) {
2723 return ret;
2725 x86_cpu_xrstor_all_areas(cpu, xsave);
2727 return 0;
2730 static int kvm_get_xcrs(X86CPU *cpu)
2732 CPUX86State *env = &cpu->env;
2733 int i, ret;
2734 struct kvm_xcrs xcrs;
2736 if (!has_xcrs) {
2737 return 0;
2740 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
2741 if (ret < 0) {
2742 return ret;
2745 for (i = 0; i < xcrs.nr_xcrs; i++) {
2746 /* Only support xcr0 now */
2747 if (xcrs.xcrs[i].xcr == 0) {
2748 env->xcr0 = xcrs.xcrs[i].value;
2749 break;
2752 return 0;
2755 static int kvm_get_sregs(X86CPU *cpu)
2757 CPUX86State *env = &cpu->env;
2758 struct kvm_sregs sregs;
2759 int bit, i, ret;
2761 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
2762 if (ret < 0) {
2763 return ret;
2766 /* There can only be one pending IRQ set in the bitmap at a time, so try
2767 to find it and save its number instead (-1 for none). */
2768 env->interrupt_injected = -1;
2769 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
2770 if (sregs.interrupt_bitmap[i]) {
2771 bit = ctz64(sregs.interrupt_bitmap[i]);
2772 env->interrupt_injected = i * 64 + bit;
2773 break;
2777 get_seg(&env->segs[R_CS], &sregs.cs);
2778 get_seg(&env->segs[R_DS], &sregs.ds);
2779 get_seg(&env->segs[R_ES], &sregs.es);
2780 get_seg(&env->segs[R_FS], &sregs.fs);
2781 get_seg(&env->segs[R_GS], &sregs.gs);
2782 get_seg(&env->segs[R_SS], &sregs.ss);
2784 get_seg(&env->tr, &sregs.tr);
2785 get_seg(&env->ldt, &sregs.ldt);
2787 env->idt.limit = sregs.idt.limit;
2788 env->idt.base = sregs.idt.base;
2789 env->gdt.limit = sregs.gdt.limit;
2790 env->gdt.base = sregs.gdt.base;
2792 env->cr[0] = sregs.cr0;
2793 env->cr[2] = sregs.cr2;
2794 env->cr[3] = sregs.cr3;
2795 env->cr[4] = sregs.cr4;
2797 env->efer = sregs.efer;
2799 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
2800 x86_update_hflags(env);
2802 return 0;
2805 static int kvm_get_msrs(X86CPU *cpu)
2807 CPUX86State *env = &cpu->env;
2808 struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
2809 int ret, i;
2810 uint64_t mtrr_top_bits;
2812 kvm_msr_buf_reset(cpu);
2814 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
2815 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
2816 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
2817 kvm_msr_entry_add(cpu, MSR_PAT, 0);
2818 if (has_msr_star) {
2819 kvm_msr_entry_add(cpu, MSR_STAR, 0);
2821 if (has_msr_hsave_pa) {
2822 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
2824 if (has_msr_tsc_aux) {
2825 kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
2827 if (has_msr_tsc_adjust) {
2828 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
2830 if (has_msr_tsc_deadline) {
2831 kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
2833 if (has_msr_misc_enable) {
2834 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
2836 if (has_msr_smbase) {
2837 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
2839 if (has_msr_smi_count) {
2840 kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
2842 if (has_msr_feature_control) {
2843 kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
2845 if (has_msr_bndcfgs) {
2846 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
2848 if (has_msr_xss) {
2849 kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
2851 if (has_msr_spec_ctrl) {
2852 kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
2854 if (has_msr_virt_ssbd) {
2855 kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, 0);
2857 if (!env->tsc_valid) {
2858 kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
2859 env->tsc_valid = !runstate_is_running();
2862 #ifdef TARGET_X86_64
2863 if (lm_capable_kernel) {
2864 kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
2865 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
2866 kvm_msr_entry_add(cpu, MSR_FMASK, 0);
2867 kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
2869 #endif
2870 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
2871 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
2872 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
2873 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
2875 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
2876 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
2878 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
2879 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
2881 if (has_architectural_pmu_version > 0) {
2882 if (has_architectural_pmu_version > 1) {
2883 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
2884 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
2885 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
2886 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
2888 for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
2889 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
2891 for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
2892 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
2893 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
2897 if (env->mcg_cap) {
2898 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
2899 kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
2900 if (has_msr_mcg_ext_ctl) {
2901 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
2903 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
2904 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
2908 if (has_msr_hv_hypercall) {
2909 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
2910 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
2912 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
2913 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
2915 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
2916 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
2918 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
2919 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL, 0);
2920 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL, 0);
2921 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS, 0);
2923 if (has_msr_hv_crash) {
2924 int j;
2926 for (j = 0; j < HV_CRASH_PARAMS; j++) {
2927 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
2930 if (has_msr_hv_runtime) {
2931 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
2933 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
2934 uint32_t msr;
2936 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
2937 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
2938 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
2939 for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
2940 kvm_msr_entry_add(cpu, msr, 0);
2943 if (has_msr_hv_stimer) {
2944 uint32_t msr;
2946 for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
2947 msr++) {
2948 kvm_msr_entry_add(cpu, msr, 0);
2951 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
2952 kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
2953 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
2954 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
2955 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
2956 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
2957 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
2958 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
2959 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
2960 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
2961 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
2962 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
2963 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
2964 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
2965 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
2966 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
2970 if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
2971 int addr_num =
2972 kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
2974 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
2975 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
2976 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
2977 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
2978 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
2979 for (i = 0; i < addr_num; i++) {
2980 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
2984 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
2985 if (ret < 0) {
2986 return ret;
2989 if (ret < cpu->kvm_msr_buf->nmsrs) {
2990 struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
2991 error_report("error: failed to get MSR 0x%" PRIx32,
2992 (uint32_t)e->index);
2995 assert(ret == cpu->kvm_msr_buf->nmsrs);
2997 * MTRR masks: Each mask consists of 5 parts
2998 * a 10..0: must be zero
2999 * b 11 : valid bit
3000 * c n-1.12: actual mask bits
3001 * d 51..n: reserved must be zero
3002 * e 63.52: reserved must be zero
3004 * 'n' is the number of physical bits supported by the CPU and is
3005 * apparently always <= 52. We know our 'n' but don't know what
3006 * the destinations 'n' is; it might be smaller, in which case
3007 * it masks (c) on loading. It might be larger, in which case
3008 * we fill 'd' so that d..c is consistent irrespetive of the 'n'
3009 * we're migrating to.
3012 if (cpu->fill_mtrr_mask) {
3013 QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
3014 assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
3015 mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
3016 } else {
3017 mtrr_top_bits = 0;
3020 for (i = 0; i < ret; i++) {
3021 uint32_t index = msrs[i].index;
3022 switch (index) {
3023 case MSR_IA32_SYSENTER_CS:
3024 env->sysenter_cs = msrs[i].data;
3025 break;
3026 case MSR_IA32_SYSENTER_ESP:
3027 env->sysenter_esp = msrs[i].data;
3028 break;
3029 case MSR_IA32_SYSENTER_EIP:
3030 env->sysenter_eip = msrs[i].data;
3031 break;
3032 case MSR_PAT:
3033 env->pat = msrs[i].data;
3034 break;
3035 case MSR_STAR:
3036 env->star = msrs[i].data;
3037 break;
3038 #ifdef TARGET_X86_64
3039 case MSR_CSTAR:
3040 env->cstar = msrs[i].data;
3041 break;
3042 case MSR_KERNELGSBASE:
3043 env->kernelgsbase = msrs[i].data;
3044 break;
3045 case MSR_FMASK:
3046 env->fmask = msrs[i].data;
3047 break;
3048 case MSR_LSTAR:
3049 env->lstar = msrs[i].data;
3050 break;
3051 #endif
3052 case MSR_IA32_TSC:
3053 env->tsc = msrs[i].data;
3054 break;
3055 case MSR_TSC_AUX:
3056 env->tsc_aux = msrs[i].data;
3057 break;
3058 case MSR_TSC_ADJUST:
3059 env->tsc_adjust = msrs[i].data;
3060 break;
3061 case MSR_IA32_TSCDEADLINE:
3062 env->tsc_deadline = msrs[i].data;
3063 break;
3064 case MSR_VM_HSAVE_PA:
3065 env->vm_hsave = msrs[i].data;
3066 break;
3067 case MSR_KVM_SYSTEM_TIME:
3068 env->system_time_msr = msrs[i].data;
3069 break;
3070 case MSR_KVM_WALL_CLOCK:
3071 env->wall_clock_msr = msrs[i].data;
3072 break;
3073 case MSR_MCG_STATUS:
3074 env->mcg_status = msrs[i].data;
3075 break;
3076 case MSR_MCG_CTL:
3077 env->mcg_ctl = msrs[i].data;
3078 break;
3079 case MSR_MCG_EXT_CTL:
3080 env->mcg_ext_ctl = msrs[i].data;
3081 break;
3082 case MSR_IA32_MISC_ENABLE:
3083 env->msr_ia32_misc_enable = msrs[i].data;
3084 break;
3085 case MSR_IA32_SMBASE:
3086 env->smbase = msrs[i].data;
3087 break;
3088 case MSR_SMI_COUNT:
3089 env->msr_smi_count = msrs[i].data;
3090 break;
3091 case MSR_IA32_FEATURE_CONTROL:
3092 env->msr_ia32_feature_control = msrs[i].data;
3093 break;
3094 case MSR_IA32_BNDCFGS:
3095 env->msr_bndcfgs = msrs[i].data;
3096 break;
3097 case MSR_IA32_XSS:
3098 env->xss = msrs[i].data;
3099 break;
3100 default:
3101 if (msrs[i].index >= MSR_MC0_CTL &&
3102 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
3103 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
3105 break;
3106 case MSR_KVM_ASYNC_PF_EN:
3107 env->async_pf_en_msr = msrs[i].data;
3108 break;
3109 case MSR_KVM_PV_EOI_EN:
3110 env->pv_eoi_en_msr = msrs[i].data;
3111 break;
3112 case MSR_KVM_STEAL_TIME:
3113 env->steal_time_msr = msrs[i].data;
3114 break;
3115 case MSR_CORE_PERF_FIXED_CTR_CTRL:
3116 env->msr_fixed_ctr_ctrl = msrs[i].data;
3117 break;
3118 case MSR_CORE_PERF_GLOBAL_CTRL:
3119 env->msr_global_ctrl = msrs[i].data;
3120 break;
3121 case MSR_CORE_PERF_GLOBAL_STATUS:
3122 env->msr_global_status = msrs[i].data;
3123 break;
3124 case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
3125 env->msr_global_ovf_ctrl = msrs[i].data;
3126 break;
3127 case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
3128 env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
3129 break;
3130 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
3131 env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
3132 break;
3133 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
3134 env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
3135 break;
3136 case HV_X64_MSR_HYPERCALL:
3137 env->msr_hv_hypercall = msrs[i].data;
3138 break;
3139 case HV_X64_MSR_GUEST_OS_ID:
3140 env->msr_hv_guest_os_id = msrs[i].data;
3141 break;
3142 case HV_X64_MSR_APIC_ASSIST_PAGE:
3143 env->msr_hv_vapic = msrs[i].data;
3144 break;
3145 case HV_X64_MSR_REFERENCE_TSC:
3146 env->msr_hv_tsc = msrs[i].data;
3147 break;
3148 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3149 env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
3150 break;
3151 case HV_X64_MSR_VP_RUNTIME:
3152 env->msr_hv_runtime = msrs[i].data;
3153 break;
3154 case HV_X64_MSR_SCONTROL:
3155 env->msr_hv_synic_control = msrs[i].data;
3156 break;
3157 case HV_X64_MSR_SIEFP:
3158 env->msr_hv_synic_evt_page = msrs[i].data;
3159 break;
3160 case HV_X64_MSR_SIMP:
3161 env->msr_hv_synic_msg_page = msrs[i].data;
3162 break;
3163 case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
3164 env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
3165 break;
3166 case HV_X64_MSR_STIMER0_CONFIG:
3167 case HV_X64_MSR_STIMER1_CONFIG:
3168 case HV_X64_MSR_STIMER2_CONFIG:
3169 case HV_X64_MSR_STIMER3_CONFIG:
3170 env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
3171 msrs[i].data;
3172 break;
3173 case HV_X64_MSR_STIMER0_COUNT:
3174 case HV_X64_MSR_STIMER1_COUNT:
3175 case HV_X64_MSR_STIMER2_COUNT:
3176 case HV_X64_MSR_STIMER3_COUNT:
3177 env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
3178 msrs[i].data;
3179 break;
3180 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3181 env->msr_hv_reenlightenment_control = msrs[i].data;
3182 break;
3183 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3184 env->msr_hv_tsc_emulation_control = msrs[i].data;
3185 break;
3186 case HV_X64_MSR_TSC_EMULATION_STATUS:
3187 env->msr_hv_tsc_emulation_status = msrs[i].data;
3188 break;
3189 case MSR_MTRRdefType:
3190 env->mtrr_deftype = msrs[i].data;
3191 break;
3192 case MSR_MTRRfix64K_00000:
3193 env->mtrr_fixed[0] = msrs[i].data;
3194 break;
3195 case MSR_MTRRfix16K_80000:
3196 env->mtrr_fixed[1] = msrs[i].data;
3197 break;
3198 case MSR_MTRRfix16K_A0000:
3199 env->mtrr_fixed[2] = msrs[i].data;
3200 break;
3201 case MSR_MTRRfix4K_C0000:
3202 env->mtrr_fixed[3] = msrs[i].data;
3203 break;
3204 case MSR_MTRRfix4K_C8000:
3205 env->mtrr_fixed[4] = msrs[i].data;
3206 break;
3207 case MSR_MTRRfix4K_D0000:
3208 env->mtrr_fixed[5] = msrs[i].data;
3209 break;
3210 case MSR_MTRRfix4K_D8000:
3211 env->mtrr_fixed[6] = msrs[i].data;
3212 break;
3213 case MSR_MTRRfix4K_E0000:
3214 env->mtrr_fixed[7] = msrs[i].data;
3215 break;
3216 case MSR_MTRRfix4K_E8000:
3217 env->mtrr_fixed[8] = msrs[i].data;
3218 break;
3219 case MSR_MTRRfix4K_F0000:
3220 env->mtrr_fixed[9] = msrs[i].data;
3221 break;
3222 case MSR_MTRRfix4K_F8000:
3223 env->mtrr_fixed[10] = msrs[i].data;
3224 break;
3225 case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
3226 if (index & 1) {
3227 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
3228 mtrr_top_bits;
3229 } else {
3230 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
3232 break;
3233 case MSR_IA32_SPEC_CTRL:
3234 env->spec_ctrl = msrs[i].data;
3235 break;
3236 case MSR_VIRT_SSBD:
3237 env->virt_ssbd = msrs[i].data;
3238 break;
3239 case MSR_IA32_RTIT_CTL:
3240 env->msr_rtit_ctrl = msrs[i].data;
3241 break;
3242 case MSR_IA32_RTIT_STATUS:
3243 env->msr_rtit_status = msrs[i].data;
3244 break;
3245 case MSR_IA32_RTIT_OUTPUT_BASE:
3246 env->msr_rtit_output_base = msrs[i].data;
3247 break;
3248 case MSR_IA32_RTIT_OUTPUT_MASK:
3249 env->msr_rtit_output_mask = msrs[i].data;
3250 break;
3251 case MSR_IA32_RTIT_CR3_MATCH:
3252 env->msr_rtit_cr3_match = msrs[i].data;
3253 break;
3254 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
3255 env->msr_rtit_addrs[index - MSR_IA32_RTIT_ADDR0_A] = msrs[i].data;
3256 break;
3260 return 0;
3263 static int kvm_put_mp_state(X86CPU *cpu)
3265 struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
3267 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
3270 static int kvm_get_mp_state(X86CPU *cpu)
3272 CPUState *cs = CPU(cpu);
3273 CPUX86State *env = &cpu->env;
3274 struct kvm_mp_state mp_state;
3275 int ret;
3277 ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
3278 if (ret < 0) {
3279 return ret;
3281 env->mp_state = mp_state.mp_state;
3282 if (kvm_irqchip_in_kernel()) {
3283 cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
3285 return 0;
3288 static int kvm_get_apic(X86CPU *cpu)
3290 DeviceState *apic = cpu->apic_state;
3291 struct kvm_lapic_state kapic;
3292 int ret;
3294 if (apic && kvm_irqchip_in_kernel()) {
3295 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
3296 if (ret < 0) {
3297 return ret;
3300 kvm_get_apic_state(apic, &kapic);
3302 return 0;
3305 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
3307 CPUState *cs = CPU(cpu);
3308 CPUX86State *env = &cpu->env;
3309 struct kvm_vcpu_events events = {};
3311 if (!kvm_has_vcpu_events()) {
3312 return 0;
3315 events.flags = 0;
3317 if (has_exception_payload) {
3318 events.flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
3319 events.exception.pending = env->exception_pending;
3320 events.exception_has_payload = env->exception_has_payload;
3321 events.exception_payload = env->exception_payload;
3323 events.exception.nr = env->exception_nr;
3324 events.exception.injected = env->exception_injected;
3325 events.exception.has_error_code = env->has_error_code;
3326 events.exception.error_code = env->error_code;
3328 events.interrupt.injected = (env->interrupt_injected >= 0);
3329 events.interrupt.nr = env->interrupt_injected;
3330 events.interrupt.soft = env->soft_interrupt;
3332 events.nmi.injected = env->nmi_injected;
3333 events.nmi.pending = env->nmi_pending;
3334 events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
3336 events.sipi_vector = env->sipi_vector;
3338 if (has_msr_smbase) {
3339 events.smi.smm = !!(env->hflags & HF_SMM_MASK);
3340 events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
3341 if (kvm_irqchip_in_kernel()) {
3342 /* As soon as these are moved to the kernel, remove them
3343 * from cs->interrupt_request.
3345 events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
3346 events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
3347 cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
3348 } else {
3349 /* Keep these in cs->interrupt_request. */
3350 events.smi.pending = 0;
3351 events.smi.latched_init = 0;
3353 /* Stop SMI delivery on old machine types to avoid a reboot
3354 * on an inward migration of an old VM.
3356 if (!cpu->kvm_no_smi_migration) {
3357 events.flags |= KVM_VCPUEVENT_VALID_SMM;
3361 if (level >= KVM_PUT_RESET_STATE) {
3362 events.flags |= KVM_VCPUEVENT_VALID_NMI_PENDING;
3363 if (env->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
3364 events.flags |= KVM_VCPUEVENT_VALID_SIPI_VECTOR;
3368 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
3371 static int kvm_get_vcpu_events(X86CPU *cpu)
3373 CPUX86State *env = &cpu->env;
3374 struct kvm_vcpu_events events;
3375 int ret;
3377 if (!kvm_has_vcpu_events()) {
3378 return 0;
3381 memset(&events, 0, sizeof(events));
3382 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
3383 if (ret < 0) {
3384 return ret;
3387 if (events.flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
3388 env->exception_pending = events.exception.pending;
3389 env->exception_has_payload = events.exception_has_payload;
3390 env->exception_payload = events.exception_payload;
3391 } else {
3392 env->exception_pending = 0;
3393 env->exception_has_payload = false;
3395 env->exception_injected = events.exception.injected;
3396 env->exception_nr =
3397 (env->exception_pending || env->exception_injected) ?
3398 events.exception.nr : -1;
3399 env->has_error_code = events.exception.has_error_code;
3400 env->error_code = events.exception.error_code;
3402 env->interrupt_injected =
3403 events.interrupt.injected ? events.interrupt.nr : -1;
3404 env->soft_interrupt = events.interrupt.soft;
3406 env->nmi_injected = events.nmi.injected;
3407 env->nmi_pending = events.nmi.pending;
3408 if (events.nmi.masked) {
3409 env->hflags2 |= HF2_NMI_MASK;
3410 } else {
3411 env->hflags2 &= ~HF2_NMI_MASK;
3414 if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
3415 if (events.smi.smm) {
3416 env->hflags |= HF_SMM_MASK;
3417 } else {
3418 env->hflags &= ~HF_SMM_MASK;
3420 if (events.smi.pending) {
3421 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
3422 } else {
3423 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
3425 if (events.smi.smm_inside_nmi) {
3426 env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
3427 } else {
3428 env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
3430 if (events.smi.latched_init) {
3431 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
3432 } else {
3433 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
3437 env->sipi_vector = events.sipi_vector;
3439 return 0;
3442 static int kvm_guest_debug_workarounds(X86CPU *cpu)
3444 CPUState *cs = CPU(cpu);
3445 CPUX86State *env = &cpu->env;
3446 int ret = 0;
3447 unsigned long reinject_trap = 0;
3449 if (!kvm_has_vcpu_events()) {
3450 if (env->exception_nr == EXCP01_DB) {
3451 reinject_trap = KVM_GUESTDBG_INJECT_DB;
3452 } else if (env->exception_injected == EXCP03_INT3) {
3453 reinject_trap = KVM_GUESTDBG_INJECT_BP;
3455 kvm_reset_exception(env);
3459 * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
3460 * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
3461 * by updating the debug state once again if single-stepping is on.
3462 * Another reason to call kvm_update_guest_debug here is a pending debug
3463 * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
3464 * reinject them via SET_GUEST_DEBUG.
3466 if (reinject_trap ||
3467 (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
3468 ret = kvm_update_guest_debug(cs, reinject_trap);
3470 return ret;
3473 static int kvm_put_debugregs(X86CPU *cpu)
3475 CPUX86State *env = &cpu->env;
3476 struct kvm_debugregs dbgregs;
3477 int i;
3479 if (!kvm_has_debugregs()) {
3480 return 0;
3483 for (i = 0; i < 4; i++) {
3484 dbgregs.db[i] = env->dr[i];
3486 dbgregs.dr6 = env->dr[6];
3487 dbgregs.dr7 = env->dr[7];
3488 dbgregs.flags = 0;
3490 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
3493 static int kvm_get_debugregs(X86CPU *cpu)
3495 CPUX86State *env = &cpu->env;
3496 struct kvm_debugregs dbgregs;
3497 int i, ret;
3499 if (!kvm_has_debugregs()) {
3500 return 0;
3503 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
3504 if (ret < 0) {
3505 return ret;
3507 for (i = 0; i < 4; i++) {
3508 env->dr[i] = dbgregs.db[i];
3510 env->dr[4] = env->dr[6] = dbgregs.dr6;
3511 env->dr[5] = env->dr[7] = dbgregs.dr7;
3513 return 0;
3516 static int kvm_put_nested_state(X86CPU *cpu)
3518 CPUX86State *env = &cpu->env;
3519 int max_nested_state_len = kvm_max_nested_state_length();
3521 if (!env->nested_state) {
3522 return 0;
3525 assert(env->nested_state->size <= max_nested_state_len);
3526 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_NESTED_STATE, env->nested_state);
3529 static int kvm_get_nested_state(X86CPU *cpu)
3531 CPUX86State *env = &cpu->env;
3532 int max_nested_state_len = kvm_max_nested_state_length();
3533 int ret;
3535 if (!env->nested_state) {
3536 return 0;
3540 * It is possible that migration restored a smaller size into
3541 * nested_state->hdr.size than what our kernel support.
3542 * We preserve migration origin nested_state->hdr.size for
3543 * call to KVM_SET_NESTED_STATE but wish that our next call
3544 * to KVM_GET_NESTED_STATE will use max size our kernel support.
3546 env->nested_state->size = max_nested_state_len;
3548 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_NESTED_STATE, env->nested_state);
3549 if (ret < 0) {
3550 return ret;
3553 if (env->nested_state->flags & KVM_STATE_NESTED_GUEST_MODE) {
3554 env->hflags |= HF_GUEST_MASK;
3555 } else {
3556 env->hflags &= ~HF_GUEST_MASK;
3559 return ret;
3562 int kvm_arch_put_registers(CPUState *cpu, int level)
3564 X86CPU *x86_cpu = X86_CPU(cpu);
3565 int ret;
3567 assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
3569 if (level >= KVM_PUT_RESET_STATE) {
3570 ret = kvm_put_nested_state(x86_cpu);
3571 if (ret < 0) {
3572 return ret;
3575 ret = kvm_put_msr_feature_control(x86_cpu);
3576 if (ret < 0) {
3577 return ret;
3581 if (level == KVM_PUT_FULL_STATE) {
3582 /* We don't check for kvm_arch_set_tsc_khz() errors here,
3583 * because TSC frequency mismatch shouldn't abort migration,
3584 * unless the user explicitly asked for a more strict TSC
3585 * setting (e.g. using an explicit "tsc-freq" option).
3587 kvm_arch_set_tsc_khz(cpu);
3590 ret = kvm_getput_regs(x86_cpu, 1);
3591 if (ret < 0) {
3592 return ret;
3594 ret = kvm_put_xsave(x86_cpu);
3595 if (ret < 0) {
3596 return ret;
3598 ret = kvm_put_xcrs(x86_cpu);
3599 if (ret < 0) {
3600 return ret;
3602 ret = kvm_put_sregs(x86_cpu);
3603 if (ret < 0) {
3604 return ret;
3606 /* must be before kvm_put_msrs */
3607 ret = kvm_inject_mce_oldstyle(x86_cpu);
3608 if (ret < 0) {
3609 return ret;
3611 ret = kvm_put_msrs(x86_cpu, level);
3612 if (ret < 0) {
3613 return ret;
3615 ret = kvm_put_vcpu_events(x86_cpu, level);
3616 if (ret < 0) {
3617 return ret;
3619 if (level >= KVM_PUT_RESET_STATE) {
3620 ret = kvm_put_mp_state(x86_cpu);
3621 if (ret < 0) {
3622 return ret;
3626 ret = kvm_put_tscdeadline_msr(x86_cpu);
3627 if (ret < 0) {
3628 return ret;
3630 ret = kvm_put_debugregs(x86_cpu);
3631 if (ret < 0) {
3632 return ret;
3634 /* must be last */
3635 ret = kvm_guest_debug_workarounds(x86_cpu);
3636 if (ret < 0) {
3637 return ret;
3639 return 0;
3642 int kvm_arch_get_registers(CPUState *cs)
3644 X86CPU *cpu = X86_CPU(cs);
3645 int ret;
3647 assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
3649 ret = kvm_get_vcpu_events(cpu);
3650 if (ret < 0) {
3651 goto out;
3654 * KVM_GET_MPSTATE can modify CS and RIP, call it before
3655 * KVM_GET_REGS and KVM_GET_SREGS.
3657 ret = kvm_get_mp_state(cpu);
3658 if (ret < 0) {
3659 goto out;
3661 ret = kvm_getput_regs(cpu, 0);
3662 if (ret < 0) {
3663 goto out;
3665 ret = kvm_get_xsave(cpu);
3666 if (ret < 0) {
3667 goto out;
3669 ret = kvm_get_xcrs(cpu);
3670 if (ret < 0) {
3671 goto out;
3673 ret = kvm_get_sregs(cpu);
3674 if (ret < 0) {
3675 goto out;
3677 ret = kvm_get_msrs(cpu);
3678 if (ret < 0) {
3679 goto out;
3681 ret = kvm_get_apic(cpu);
3682 if (ret < 0) {
3683 goto out;
3685 ret = kvm_get_debugregs(cpu);
3686 if (ret < 0) {
3687 goto out;
3689 ret = kvm_get_nested_state(cpu);
3690 if (ret < 0) {
3691 goto out;
3693 ret = 0;
3694 out:
3695 cpu_sync_bndcs_hflags(&cpu->env);
3696 return ret;
3699 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
3701 X86CPU *x86_cpu = X86_CPU(cpu);
3702 CPUX86State *env = &x86_cpu->env;
3703 int ret;
3705 /* Inject NMI */
3706 if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
3707 if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
3708 qemu_mutex_lock_iothread();
3709 cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
3710 qemu_mutex_unlock_iothread();
3711 DPRINTF("injected NMI\n");
3712 ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
3713 if (ret < 0) {
3714 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
3715 strerror(-ret));
3718 if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
3719 qemu_mutex_lock_iothread();
3720 cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
3721 qemu_mutex_unlock_iothread();
3722 DPRINTF("injected SMI\n");
3723 ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
3724 if (ret < 0) {
3725 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
3726 strerror(-ret));
3731 if (!kvm_pic_in_kernel()) {
3732 qemu_mutex_lock_iothread();
3735 /* Force the VCPU out of its inner loop to process any INIT requests
3736 * or (for userspace APIC, but it is cheap to combine the checks here)
3737 * pending TPR access reports.
3739 if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
3740 if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
3741 !(env->hflags & HF_SMM_MASK)) {
3742 cpu->exit_request = 1;
3744 if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
3745 cpu->exit_request = 1;
3749 if (!kvm_pic_in_kernel()) {
3750 /* Try to inject an interrupt if the guest can accept it */
3751 if (run->ready_for_interrupt_injection &&
3752 (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
3753 (env->eflags & IF_MASK)) {
3754 int irq;
3756 cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
3757 irq = cpu_get_pic_interrupt(env);
3758 if (irq >= 0) {
3759 struct kvm_interrupt intr;
3761 intr.irq = irq;
3762 DPRINTF("injected interrupt %d\n", irq);
3763 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
3764 if (ret < 0) {
3765 fprintf(stderr,
3766 "KVM: injection failed, interrupt lost (%s)\n",
3767 strerror(-ret));
3772 /* If we have an interrupt but the guest is not ready to receive an
3773 * interrupt, request an interrupt window exit. This will
3774 * cause a return to userspace as soon as the guest is ready to
3775 * receive interrupts. */
3776 if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
3777 run->request_interrupt_window = 1;
3778 } else {
3779 run->request_interrupt_window = 0;
3782 DPRINTF("setting tpr\n");
3783 run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
3785 qemu_mutex_unlock_iothread();
3789 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
3791 X86CPU *x86_cpu = X86_CPU(cpu);
3792 CPUX86State *env = &x86_cpu->env;
3794 if (run->flags & KVM_RUN_X86_SMM) {
3795 env->hflags |= HF_SMM_MASK;
3796 } else {
3797 env->hflags &= ~HF_SMM_MASK;
3799 if (run->if_flag) {
3800 env->eflags |= IF_MASK;
3801 } else {
3802 env->eflags &= ~IF_MASK;
3805 /* We need to protect the apic state against concurrent accesses from
3806 * different threads in case the userspace irqchip is used. */
3807 if (!kvm_irqchip_in_kernel()) {
3808 qemu_mutex_lock_iothread();
3810 cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
3811 cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
3812 if (!kvm_irqchip_in_kernel()) {
3813 qemu_mutex_unlock_iothread();
3815 return cpu_get_mem_attrs(env);
3818 int kvm_arch_process_async_events(CPUState *cs)
3820 X86CPU *cpu = X86_CPU(cs);
3821 CPUX86State *env = &cpu->env;
3823 if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
3824 /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
3825 assert(env->mcg_cap);
3827 cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
3829 kvm_cpu_synchronize_state(cs);
3831 if (env->exception_nr == EXCP08_DBLE) {
3832 /* this means triple fault */
3833 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
3834 cs->exit_request = 1;
3835 return 0;
3837 kvm_queue_exception(env, EXCP12_MCHK, 0, 0);
3838 env->has_error_code = 0;
3840 cs->halted = 0;
3841 if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
3842 env->mp_state = KVM_MP_STATE_RUNNABLE;
3846 if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
3847 !(env->hflags & HF_SMM_MASK)) {
3848 kvm_cpu_synchronize_state(cs);
3849 do_cpu_init(cpu);
3852 if (kvm_irqchip_in_kernel()) {
3853 return 0;
3856 if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
3857 cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
3858 apic_poll_irq(cpu->apic_state);
3860 if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
3861 (env->eflags & IF_MASK)) ||
3862 (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
3863 cs->halted = 0;
3865 if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
3866 kvm_cpu_synchronize_state(cs);
3867 do_cpu_sipi(cpu);
3869 if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
3870 cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
3871 kvm_cpu_synchronize_state(cs);
3872 apic_handle_tpr_access_report(cpu->apic_state, env->eip,
3873 env->tpr_access_type);
3876 return cs->halted;
3879 static int kvm_handle_halt(X86CPU *cpu)
3881 CPUState *cs = CPU(cpu);
3882 CPUX86State *env = &cpu->env;
3884 if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
3885 (env->eflags & IF_MASK)) &&
3886 !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
3887 cs->halted = 1;
3888 return EXCP_HLT;
3891 return 0;
3894 static int kvm_handle_tpr_access(X86CPU *cpu)
3896 CPUState *cs = CPU(cpu);
3897 struct kvm_run *run = cs->kvm_run;
3899 apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
3900 run->tpr_access.is_write ? TPR_ACCESS_WRITE
3901 : TPR_ACCESS_READ);
3902 return 1;
3905 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
3907 static const uint8_t int3 = 0xcc;
3909 if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
3910 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
3911 return -EINVAL;
3913 return 0;
3916 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
3918 uint8_t int3;
3920 if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
3921 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
3922 return -EINVAL;
3924 return 0;
3927 static struct {
3928 target_ulong addr;
3929 int len;
3930 int type;
3931 } hw_breakpoint[4];
3933 static int nb_hw_breakpoint;
3935 static int find_hw_breakpoint(target_ulong addr, int len, int type)
3937 int n;
3939 for (n = 0; n < nb_hw_breakpoint; n++) {
3940 if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
3941 (hw_breakpoint[n].len == len || len == -1)) {
3942 return n;
3945 return -1;
3948 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
3949 target_ulong len, int type)
3951 switch (type) {
3952 case GDB_BREAKPOINT_HW:
3953 len = 1;
3954 break;
3955 case GDB_WATCHPOINT_WRITE:
3956 case GDB_WATCHPOINT_ACCESS:
3957 switch (len) {
3958 case 1:
3959 break;
3960 case 2:
3961 case 4:
3962 case 8:
3963 if (addr & (len - 1)) {
3964 return -EINVAL;
3966 break;
3967 default:
3968 return -EINVAL;
3970 break;
3971 default:
3972 return -ENOSYS;
3975 if (nb_hw_breakpoint == 4) {
3976 return -ENOBUFS;
3978 if (find_hw_breakpoint(addr, len, type) >= 0) {
3979 return -EEXIST;
3981 hw_breakpoint[nb_hw_breakpoint].addr = addr;
3982 hw_breakpoint[nb_hw_breakpoint].len = len;
3983 hw_breakpoint[nb_hw_breakpoint].type = type;
3984 nb_hw_breakpoint++;
3986 return 0;
3989 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
3990 target_ulong len, int type)
3992 int n;
3994 n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
3995 if (n < 0) {
3996 return -ENOENT;
3998 nb_hw_breakpoint--;
3999 hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
4001 return 0;
4004 void kvm_arch_remove_all_hw_breakpoints(void)
4006 nb_hw_breakpoint = 0;
4009 static CPUWatchpoint hw_watchpoint;
4011 static int kvm_handle_debug(X86CPU *cpu,
4012 struct kvm_debug_exit_arch *arch_info)
4014 CPUState *cs = CPU(cpu);
4015 CPUX86State *env = &cpu->env;
4016 int ret = 0;
4017 int n;
4019 if (arch_info->exception == EXCP01_DB) {
4020 if (arch_info->dr6 & DR6_BS) {
4021 if (cs->singlestep_enabled) {
4022 ret = EXCP_DEBUG;
4024 } else {
4025 for (n = 0; n < 4; n++) {
4026 if (arch_info->dr6 & (1 << n)) {
4027 switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
4028 case 0x0:
4029 ret = EXCP_DEBUG;
4030 break;
4031 case 0x1:
4032 ret = EXCP_DEBUG;
4033 cs->watchpoint_hit = &hw_watchpoint;
4034 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
4035 hw_watchpoint.flags = BP_MEM_WRITE;
4036 break;
4037 case 0x3:
4038 ret = EXCP_DEBUG;
4039 cs->watchpoint_hit = &hw_watchpoint;
4040 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
4041 hw_watchpoint.flags = BP_MEM_ACCESS;
4042 break;
4047 } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
4048 ret = EXCP_DEBUG;
4050 if (ret == 0) {
4051 cpu_synchronize_state(cs);
4052 assert(env->exception_nr == -1);
4054 /* pass to guest */
4055 kvm_queue_exception(env, arch_info->exception,
4056 arch_info->exception == EXCP01_DB,
4057 arch_info->dr6);
4058 env->has_error_code = 0;
4061 return ret;
4064 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
4066 const uint8_t type_code[] = {
4067 [GDB_BREAKPOINT_HW] = 0x0,
4068 [GDB_WATCHPOINT_WRITE] = 0x1,
4069 [GDB_WATCHPOINT_ACCESS] = 0x3
4071 const uint8_t len_code[] = {
4072 [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
4074 int n;
4076 if (kvm_sw_breakpoints_active(cpu)) {
4077 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
4079 if (nb_hw_breakpoint > 0) {
4080 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
4081 dbg->arch.debugreg[7] = 0x0600;
4082 for (n = 0; n < nb_hw_breakpoint; n++) {
4083 dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
4084 dbg->arch.debugreg[7] |= (2 << (n * 2)) |
4085 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
4086 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
4091 static bool host_supports_vmx(void)
4093 uint32_t ecx, unused;
4095 host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
4096 return ecx & CPUID_EXT_VMX;
4099 #define VMX_INVALID_GUEST_STATE 0x80000021
4101 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
4103 X86CPU *cpu = X86_CPU(cs);
4104 uint64_t code;
4105 int ret;
4107 switch (run->exit_reason) {
4108 case KVM_EXIT_HLT:
4109 DPRINTF("handle_hlt\n");
4110 qemu_mutex_lock_iothread();
4111 ret = kvm_handle_halt(cpu);
4112 qemu_mutex_unlock_iothread();
4113 break;
4114 case KVM_EXIT_SET_TPR:
4115 ret = 0;
4116 break;
4117 case KVM_EXIT_TPR_ACCESS:
4118 qemu_mutex_lock_iothread();
4119 ret = kvm_handle_tpr_access(cpu);
4120 qemu_mutex_unlock_iothread();
4121 break;
4122 case KVM_EXIT_FAIL_ENTRY:
4123 code = run->fail_entry.hardware_entry_failure_reason;
4124 fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
4125 code);
4126 if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
4127 fprintf(stderr,
4128 "\nIf you're running a guest on an Intel machine without "
4129 "unrestricted mode\n"
4130 "support, the failure can be most likely due to the guest "
4131 "entering an invalid\n"
4132 "state for Intel VT. For example, the guest maybe running "
4133 "in big real mode\n"
4134 "which is not supported on less recent Intel processors."
4135 "\n\n");
4137 ret = -1;
4138 break;
4139 case KVM_EXIT_EXCEPTION:
4140 fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
4141 run->ex.exception, run->ex.error_code);
4142 ret = -1;
4143 break;
4144 case KVM_EXIT_DEBUG:
4145 DPRINTF("kvm_exit_debug\n");
4146 qemu_mutex_lock_iothread();
4147 ret = kvm_handle_debug(cpu, &run->debug.arch);
4148 qemu_mutex_unlock_iothread();
4149 break;
4150 case KVM_EXIT_HYPERV:
4151 ret = kvm_hv_handle_exit(cpu, &run->hyperv);
4152 break;
4153 case KVM_EXIT_IOAPIC_EOI:
4154 ioapic_eoi_broadcast(run->eoi.vector);
4155 ret = 0;
4156 break;
4157 default:
4158 fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
4159 ret = -1;
4160 break;
4163 return ret;
4166 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
4168 X86CPU *cpu = X86_CPU(cs);
4169 CPUX86State *env = &cpu->env;
4171 kvm_cpu_synchronize_state(cs);
4172 return !(env->cr[0] & CR0_PE_MASK) ||
4173 ((env->segs[R_CS].selector & 3) != 3);
4176 void kvm_arch_init_irq_routing(KVMState *s)
4178 if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
4179 /* If kernel can't do irq routing, interrupt source
4180 * override 0->2 cannot be set up as required by HPET.
4181 * So we have to disable it.
4183 no_hpet = 1;
4185 /* We know at this point that we're using the in-kernel
4186 * irqchip, so we can use irqfds, and on x86 we know
4187 * we can use msi via irqfd and GSI routing.
4189 kvm_msi_via_irqfd_allowed = true;
4190 kvm_gsi_routing_allowed = true;
4192 if (kvm_irqchip_is_split()) {
4193 int i;
4195 /* If the ioapic is in QEMU and the lapics are in KVM, reserve
4196 MSI routes for signaling interrupts to the local apics. */
4197 for (i = 0; i < IOAPIC_NUM_PINS; i++) {
4198 if (kvm_irqchip_add_msi_route(s, 0, NULL) < 0) {
4199 error_report("Could not enable split IRQ mode.");
4200 exit(1);
4206 int kvm_arch_irqchip_create(MachineState *ms, KVMState *s)
4208 int ret;
4209 if (machine_kernel_irqchip_split(ms)) {
4210 ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
4211 if (ret) {
4212 error_report("Could not enable split irqchip mode: %s",
4213 strerror(-ret));
4214 exit(1);
4215 } else {
4216 DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
4217 kvm_split_irqchip = true;
4218 return 1;
4220 } else {
4221 return 0;
4225 /* Classic KVM device assignment interface. Will remain x86 only. */
4226 int kvm_device_pci_assign(KVMState *s, PCIHostDeviceAddress *dev_addr,
4227 uint32_t flags, uint32_t *dev_id)
4229 struct kvm_assigned_pci_dev dev_data = {
4230 .segnr = dev_addr->domain,
4231 .busnr = dev_addr->bus,
4232 .devfn = PCI_DEVFN(dev_addr->slot, dev_addr->function),
4233 .flags = flags,
4235 int ret;
4237 dev_data.assigned_dev_id =
4238 (dev_addr->domain << 16) | (dev_addr->bus << 8) | dev_data.devfn;
4240 ret = kvm_vm_ioctl(s, KVM_ASSIGN_PCI_DEVICE, &dev_data);
4241 if (ret < 0) {
4242 return ret;
4245 *dev_id = dev_data.assigned_dev_id;
4247 return 0;
4250 int kvm_device_pci_deassign(KVMState *s, uint32_t dev_id)
4252 struct kvm_assigned_pci_dev dev_data = {
4253 .assigned_dev_id = dev_id,
4256 return kvm_vm_ioctl(s, KVM_DEASSIGN_PCI_DEVICE, &dev_data);
4259 static int kvm_assign_irq_internal(KVMState *s, uint32_t dev_id,
4260 uint32_t irq_type, uint32_t guest_irq)
4262 struct kvm_assigned_irq assigned_irq = {
4263 .assigned_dev_id = dev_id,
4264 .guest_irq = guest_irq,
4265 .flags = irq_type,
4268 if (kvm_check_extension(s, KVM_CAP_ASSIGN_DEV_IRQ)) {
4269 return kvm_vm_ioctl(s, KVM_ASSIGN_DEV_IRQ, &assigned_irq);
4270 } else {
4271 return kvm_vm_ioctl(s, KVM_ASSIGN_IRQ, &assigned_irq);
4275 int kvm_device_intx_assign(KVMState *s, uint32_t dev_id, bool use_host_msi,
4276 uint32_t guest_irq)
4278 uint32_t irq_type = KVM_DEV_IRQ_GUEST_INTX |
4279 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX);
4281 return kvm_assign_irq_internal(s, dev_id, irq_type, guest_irq);
4284 int kvm_device_intx_set_mask(KVMState *s, uint32_t dev_id, bool masked)
4286 struct kvm_assigned_pci_dev dev_data = {
4287 .assigned_dev_id = dev_id,
4288 .flags = masked ? KVM_DEV_ASSIGN_MASK_INTX : 0,
4291 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_INTX_MASK, &dev_data);
4294 static int kvm_deassign_irq_internal(KVMState *s, uint32_t dev_id,
4295 uint32_t type)
4297 struct kvm_assigned_irq assigned_irq = {
4298 .assigned_dev_id = dev_id,
4299 .flags = type,
4302 return kvm_vm_ioctl(s, KVM_DEASSIGN_DEV_IRQ, &assigned_irq);
4305 int kvm_device_intx_deassign(KVMState *s, uint32_t dev_id, bool use_host_msi)
4307 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_INTX |
4308 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX));
4311 int kvm_device_msi_assign(KVMState *s, uint32_t dev_id, int virq)
4313 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSI |
4314 KVM_DEV_IRQ_GUEST_MSI, virq);
4317 int kvm_device_msi_deassign(KVMState *s, uint32_t dev_id)
4319 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSI |
4320 KVM_DEV_IRQ_HOST_MSI);
4323 bool kvm_device_msix_supported(KVMState *s)
4325 /* The kernel lacks a corresponding KVM_CAP, so we probe by calling
4326 * KVM_ASSIGN_SET_MSIX_NR with an invalid parameter. */
4327 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, NULL) == -EFAULT;
4330 int kvm_device_msix_init_vectors(KVMState *s, uint32_t dev_id,
4331 uint32_t nr_vectors)
4333 struct kvm_assigned_msix_nr msix_nr = {
4334 .assigned_dev_id = dev_id,
4335 .entry_nr = nr_vectors,
4338 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, &msix_nr);
4341 int kvm_device_msix_set_vector(KVMState *s, uint32_t dev_id, uint32_t vector,
4342 int virq)
4344 struct kvm_assigned_msix_entry msix_entry = {
4345 .assigned_dev_id = dev_id,
4346 .gsi = virq,
4347 .entry = vector,
4350 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_ENTRY, &msix_entry);
4353 int kvm_device_msix_assign(KVMState *s, uint32_t dev_id)
4355 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSIX |
4356 KVM_DEV_IRQ_GUEST_MSIX, 0);
4359 int kvm_device_msix_deassign(KVMState *s, uint32_t dev_id)
4361 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSIX |
4362 KVM_DEV_IRQ_HOST_MSIX);
4365 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
4366 uint64_t address, uint32_t data, PCIDevice *dev)
4368 X86IOMMUState *iommu = x86_iommu_get_default();
4370 if (iommu) {
4371 int ret;
4372 MSIMessage src, dst;
4373 X86IOMMUClass *class = X86_IOMMU_GET_CLASS(iommu);
4375 if (!class->int_remap) {
4376 return 0;
4379 src.address = route->u.msi.address_hi;
4380 src.address <<= VTD_MSI_ADDR_HI_SHIFT;
4381 src.address |= route->u.msi.address_lo;
4382 src.data = route->u.msi.data;
4384 ret = class->int_remap(iommu, &src, &dst, dev ? \
4385 pci_requester_id(dev) : \
4386 X86_IOMMU_SID_INVALID);
4387 if (ret) {
4388 trace_kvm_x86_fixup_msi_error(route->gsi);
4389 return 1;
4392 route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
4393 route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
4394 route->u.msi.data = dst.data;
4397 return 0;
4400 typedef struct MSIRouteEntry MSIRouteEntry;
4402 struct MSIRouteEntry {
4403 PCIDevice *dev; /* Device pointer */
4404 int vector; /* MSI/MSIX vector index */
4405 int virq; /* Virtual IRQ index */
4406 QLIST_ENTRY(MSIRouteEntry) list;
4409 /* List of used GSI routes */
4410 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
4411 QLIST_HEAD_INITIALIZER(msi_route_list);
4413 static void kvm_update_msi_routes_all(void *private, bool global,
4414 uint32_t index, uint32_t mask)
4416 int cnt = 0, vector;
4417 MSIRouteEntry *entry;
4418 MSIMessage msg;
4419 PCIDevice *dev;
4421 /* TODO: explicit route update */
4422 QLIST_FOREACH(entry, &msi_route_list, list) {
4423 cnt++;
4424 vector = entry->vector;
4425 dev = entry->dev;
4426 if (msix_enabled(dev) && !msix_is_masked(dev, vector)) {
4427 msg = msix_get_message(dev, vector);
4428 } else if (msi_enabled(dev) && !msi_is_masked(dev, vector)) {
4429 msg = msi_get_message(dev, vector);
4430 } else {
4432 * Either MSI/MSIX is disabled for the device, or the
4433 * specific message was masked out. Skip this one.
4435 continue;
4437 kvm_irqchip_update_msi_route(kvm_state, entry->virq, msg, dev);
4439 kvm_irqchip_commit_routes(kvm_state);
4440 trace_kvm_x86_update_msi_routes(cnt);
4443 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
4444 int vector, PCIDevice *dev)
4446 static bool notify_list_inited = false;
4447 MSIRouteEntry *entry;
4449 if (!dev) {
4450 /* These are (possibly) IOAPIC routes only used for split
4451 * kernel irqchip mode, while what we are housekeeping are
4452 * PCI devices only. */
4453 return 0;
4456 entry = g_new0(MSIRouteEntry, 1);
4457 entry->dev = dev;
4458 entry->vector = vector;
4459 entry->virq = route->gsi;
4460 QLIST_INSERT_HEAD(&msi_route_list, entry, list);
4462 trace_kvm_x86_add_msi_route(route->gsi);
4464 if (!notify_list_inited) {
4465 /* For the first time we do add route, add ourselves into
4466 * IOMMU's IEC notify list if needed. */
4467 X86IOMMUState *iommu = x86_iommu_get_default();
4468 if (iommu) {
4469 x86_iommu_iec_register_notifier(iommu,
4470 kvm_update_msi_routes_all,
4471 NULL);
4473 notify_list_inited = true;
4475 return 0;
4478 int kvm_arch_release_virq_post(int virq)
4480 MSIRouteEntry *entry, *next;
4481 QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
4482 if (entry->virq == virq) {
4483 trace_kvm_x86_remove_msi_route(virq);
4484 QLIST_REMOVE(entry, list);
4485 g_free(entry);
4486 break;
4489 return 0;
4492 int kvm_arch_msi_data_to_gsi(uint32_t data)
4494 abort();