hyperv: make overlay pages for SynIC
[qemu/ar7.git] / target / i386 / kvm.c
blob7b7a56593e88f48d0f5fac644f06b2fc8d4672a9
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 "qemu-common.h"
24 #include "cpu.h"
25 #include "sysemu/sysemu.h"
26 #include "sysemu/hw_accel.h"
27 #include "sysemu/kvm_int.h"
28 #include "kvm_i386.h"
29 #include "hyperv.h"
30 #include "hyperv-proto.h"
32 #include "exec/gdbstub.h"
33 #include "qemu/host-utils.h"
34 #include "qemu/config-file.h"
35 #include "qemu/error-report.h"
36 #include "hw/i386/pc.h"
37 #include "hw/i386/apic.h"
38 #include "hw/i386/apic_internal.h"
39 #include "hw/i386/apic-msidef.h"
40 #include "hw/i386/intel_iommu.h"
41 #include "hw/i386/x86-iommu.h"
43 #include "hw/pci/pci.h"
44 #include "hw/pci/msi.h"
45 #include "hw/pci/msix.h"
46 #include "migration/blocker.h"
47 #include "exec/memattrs.h"
48 #include "trace.h"
50 //#define DEBUG_KVM
52 #ifdef DEBUG_KVM
53 #define DPRINTF(fmt, ...) \
54 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
55 #else
56 #define DPRINTF(fmt, ...) \
57 do { } while (0)
58 #endif
60 #define MSR_KVM_WALL_CLOCK 0x11
61 #define MSR_KVM_SYSTEM_TIME 0x12
63 /* A 4096-byte buffer can hold the 8-byte kvm_msrs header, plus
64 * 255 kvm_msr_entry structs */
65 #define MSR_BUF_SIZE 4096
67 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
68 KVM_CAP_INFO(SET_TSS_ADDR),
69 KVM_CAP_INFO(EXT_CPUID),
70 KVM_CAP_INFO(MP_STATE),
71 KVM_CAP_LAST_INFO
74 static bool has_msr_star;
75 static bool has_msr_hsave_pa;
76 static bool has_msr_tsc_aux;
77 static bool has_msr_tsc_adjust;
78 static bool has_msr_tsc_deadline;
79 static bool has_msr_feature_control;
80 static bool has_msr_misc_enable;
81 static bool has_msr_smbase;
82 static bool has_msr_bndcfgs;
83 static int lm_capable_kernel;
84 static bool has_msr_hv_hypercall;
85 static bool has_msr_hv_crash;
86 static bool has_msr_hv_reset;
87 static bool has_msr_hv_vpindex;
88 static bool hv_vpindex_settable;
89 static bool has_msr_hv_runtime;
90 static bool has_msr_hv_synic;
91 static bool has_msr_hv_stimer;
92 static bool has_msr_hv_frequencies;
93 static bool has_msr_hv_reenlightenment;
94 static bool has_msr_xss;
95 static bool has_msr_spec_ctrl;
96 static bool has_msr_virt_ssbd;
97 static bool has_msr_smi_count;
99 static uint32_t has_architectural_pmu_version;
100 static uint32_t num_architectural_pmu_gp_counters;
101 static uint32_t num_architectural_pmu_fixed_counters;
103 static int has_xsave;
104 static int has_xcrs;
105 static int has_pit_state2;
107 static bool has_msr_mcg_ext_ctl;
109 static struct kvm_cpuid2 *cpuid_cache;
111 int kvm_has_pit_state2(void)
113 return has_pit_state2;
116 bool kvm_has_smm(void)
118 return kvm_check_extension(kvm_state, KVM_CAP_X86_SMM);
121 bool kvm_has_adjust_clock_stable(void)
123 int ret = kvm_check_extension(kvm_state, KVM_CAP_ADJUST_CLOCK);
125 return (ret == KVM_CLOCK_TSC_STABLE);
128 bool kvm_allows_irq0_override(void)
130 return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
133 static bool kvm_x2apic_api_set_flags(uint64_t flags)
135 KVMState *s = KVM_STATE(current_machine->accelerator);
137 return !kvm_vm_enable_cap(s, KVM_CAP_X2APIC_API, 0, flags);
140 #define MEMORIZE(fn, _result) \
141 ({ \
142 static bool _memorized; \
144 if (_memorized) { \
145 return _result; \
147 _memorized = true; \
148 _result = fn; \
151 static bool has_x2apic_api;
153 bool kvm_has_x2apic_api(void)
155 return has_x2apic_api;
158 bool kvm_enable_x2apic(void)
160 return MEMORIZE(
161 kvm_x2apic_api_set_flags(KVM_X2APIC_API_USE_32BIT_IDS |
162 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK),
163 has_x2apic_api);
166 bool kvm_hv_vpindex_settable(void)
168 return hv_vpindex_settable;
171 static int kvm_get_tsc(CPUState *cs)
173 X86CPU *cpu = X86_CPU(cs);
174 CPUX86State *env = &cpu->env;
175 struct {
176 struct kvm_msrs info;
177 struct kvm_msr_entry entries[1];
178 } msr_data;
179 int ret;
181 if (env->tsc_valid) {
182 return 0;
185 msr_data.info.nmsrs = 1;
186 msr_data.entries[0].index = MSR_IA32_TSC;
187 env->tsc_valid = !runstate_is_running();
189 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
190 if (ret < 0) {
191 return ret;
194 assert(ret == 1);
195 env->tsc = msr_data.entries[0].data;
196 return 0;
199 static inline void do_kvm_synchronize_tsc(CPUState *cpu, run_on_cpu_data arg)
201 kvm_get_tsc(cpu);
204 void kvm_synchronize_all_tsc(void)
206 CPUState *cpu;
208 if (kvm_enabled()) {
209 CPU_FOREACH(cpu) {
210 run_on_cpu(cpu, do_kvm_synchronize_tsc, RUN_ON_CPU_NULL);
215 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
217 struct kvm_cpuid2 *cpuid;
218 int r, size;
220 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
221 cpuid = g_malloc0(size);
222 cpuid->nent = max;
223 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
224 if (r == 0 && cpuid->nent >= max) {
225 r = -E2BIG;
227 if (r < 0) {
228 if (r == -E2BIG) {
229 g_free(cpuid);
230 return NULL;
231 } else {
232 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
233 strerror(-r));
234 exit(1);
237 return cpuid;
240 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
241 * for all entries.
243 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
245 struct kvm_cpuid2 *cpuid;
246 int max = 1;
248 if (cpuid_cache != NULL) {
249 return cpuid_cache;
251 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
252 max *= 2;
254 cpuid_cache = cpuid;
255 return cpuid;
258 static const struct kvm_para_features {
259 int cap;
260 int feature;
261 } para_features[] = {
262 { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
263 { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
264 { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
265 { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
268 static int get_para_features(KVMState *s)
270 int i, features = 0;
272 for (i = 0; i < ARRAY_SIZE(para_features); i++) {
273 if (kvm_check_extension(s, para_features[i].cap)) {
274 features |= (1 << para_features[i].feature);
278 return features;
281 static bool host_tsx_blacklisted(void)
283 int family, model, stepping;\
284 char vendor[CPUID_VENDOR_SZ + 1];
286 host_vendor_fms(vendor, &family, &model, &stepping);
288 /* Check if we are running on a Haswell host known to have broken TSX */
289 return !strcmp(vendor, CPUID_VENDOR_INTEL) &&
290 (family == 6) &&
291 ((model == 63 && stepping < 4) ||
292 model == 60 || model == 69 || model == 70);
295 /* Returns the value for a specific register on the cpuid entry
297 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
299 uint32_t ret = 0;
300 switch (reg) {
301 case R_EAX:
302 ret = entry->eax;
303 break;
304 case R_EBX:
305 ret = entry->ebx;
306 break;
307 case R_ECX:
308 ret = entry->ecx;
309 break;
310 case R_EDX:
311 ret = entry->edx;
312 break;
314 return ret;
317 /* Find matching entry for function/index on kvm_cpuid2 struct
319 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
320 uint32_t function,
321 uint32_t index)
323 int i;
324 for (i = 0; i < cpuid->nent; ++i) {
325 if (cpuid->entries[i].function == function &&
326 cpuid->entries[i].index == index) {
327 return &cpuid->entries[i];
330 /* not found: */
331 return NULL;
334 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
335 uint32_t index, int reg)
337 struct kvm_cpuid2 *cpuid;
338 uint32_t ret = 0;
339 uint32_t cpuid_1_edx;
340 bool found = false;
342 cpuid = get_supported_cpuid(s);
344 struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
345 if (entry) {
346 found = true;
347 ret = cpuid_entry_get_reg(entry, reg);
350 /* Fixups for the data returned by KVM, below */
352 if (function == 1 && reg == R_EDX) {
353 /* KVM before 2.6.30 misreports the following features */
354 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
355 } else if (function == 1 && reg == R_ECX) {
356 /* We can set the hypervisor flag, even if KVM does not return it on
357 * GET_SUPPORTED_CPUID
359 ret |= CPUID_EXT_HYPERVISOR;
360 /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
361 * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
362 * and the irqchip is in the kernel.
364 if (kvm_irqchip_in_kernel() &&
365 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
366 ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
369 /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
370 * without the in-kernel irqchip
372 if (!kvm_irqchip_in_kernel()) {
373 ret &= ~CPUID_EXT_X2APIC;
376 if (enable_cpu_pm) {
377 int disable_exits = kvm_check_extension(s,
378 KVM_CAP_X86_DISABLE_EXITS);
380 if (disable_exits & KVM_X86_DISABLE_EXITS_MWAIT) {
381 ret |= CPUID_EXT_MONITOR;
384 } else if (function == 6 && reg == R_EAX) {
385 ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
386 } else if (function == 7 && index == 0 && reg == R_EBX) {
387 if (host_tsx_blacklisted()) {
388 ret &= ~(CPUID_7_0_EBX_RTM | CPUID_7_0_EBX_HLE);
390 } else if (function == 0x80000001 && reg == R_ECX) {
392 * It's safe to enable TOPOEXT even if it's not returned by
393 * GET_SUPPORTED_CPUID. Unconditionally enabling TOPOEXT here allows
394 * us to keep CPU models including TOPOEXT runnable on older kernels.
396 ret |= CPUID_EXT3_TOPOEXT;
397 } else if (function == 0x80000001 && reg == R_EDX) {
398 /* On Intel, kvm returns cpuid according to the Intel spec,
399 * so add missing bits according to the AMD spec:
401 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
402 ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
403 } else if (function == KVM_CPUID_FEATURES && reg == R_EAX) {
404 /* kvm_pv_unhalt is reported by GET_SUPPORTED_CPUID, but it can't
405 * be enabled without the in-kernel irqchip
407 if (!kvm_irqchip_in_kernel()) {
408 ret &= ~(1U << KVM_FEATURE_PV_UNHALT);
410 } else if (function == KVM_CPUID_FEATURES && reg == R_EDX) {
411 ret |= 1U << KVM_HINTS_REALTIME;
412 found = 1;
415 /* fallback for older kernels */
416 if ((function == KVM_CPUID_FEATURES) && !found) {
417 ret = get_para_features(s);
420 return ret;
423 typedef struct HWPoisonPage {
424 ram_addr_t ram_addr;
425 QLIST_ENTRY(HWPoisonPage) list;
426 } HWPoisonPage;
428 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
429 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
431 static void kvm_unpoison_all(void *param)
433 HWPoisonPage *page, *next_page;
435 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
436 QLIST_REMOVE(page, list);
437 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
438 g_free(page);
442 static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
444 HWPoisonPage *page;
446 QLIST_FOREACH(page, &hwpoison_page_list, list) {
447 if (page->ram_addr == ram_addr) {
448 return;
451 page = g_new(HWPoisonPage, 1);
452 page->ram_addr = ram_addr;
453 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
456 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
457 int *max_banks)
459 int r;
461 r = kvm_check_extension(s, KVM_CAP_MCE);
462 if (r > 0) {
463 *max_banks = r;
464 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
466 return -ENOSYS;
469 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
471 CPUState *cs = CPU(cpu);
472 CPUX86State *env = &cpu->env;
473 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
474 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
475 uint64_t mcg_status = MCG_STATUS_MCIP;
476 int flags = 0;
478 if (code == BUS_MCEERR_AR) {
479 status |= MCI_STATUS_AR | 0x134;
480 mcg_status |= MCG_STATUS_EIPV;
481 } else {
482 status |= 0xc0;
483 mcg_status |= MCG_STATUS_RIPV;
486 flags = cpu_x86_support_mca_broadcast(env) ? MCE_INJECT_BROADCAST : 0;
487 /* We need to read back the value of MSR_EXT_MCG_CTL that was set by the
488 * guest kernel back into env->mcg_ext_ctl.
490 cpu_synchronize_state(cs);
491 if (env->mcg_ext_ctl & MCG_EXT_CTL_LMCE_EN) {
492 mcg_status |= MCG_STATUS_LMCE;
493 flags = 0;
496 cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
497 (MCM_ADDR_PHYS << 6) | 0xc, flags);
500 static void hardware_memory_error(void)
502 fprintf(stderr, "Hardware memory error!\n");
503 exit(1);
506 void kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
508 X86CPU *cpu = X86_CPU(c);
509 CPUX86State *env = &cpu->env;
510 ram_addr_t ram_addr;
511 hwaddr paddr;
513 /* If we get an action required MCE, it has been injected by KVM
514 * while the VM was running. An action optional MCE instead should
515 * be coming from the main thread, which qemu_init_sigbus identifies
516 * as the "early kill" thread.
518 assert(code == BUS_MCEERR_AR || code == BUS_MCEERR_AO);
520 if ((env->mcg_cap & MCG_SER_P) && addr) {
521 ram_addr = qemu_ram_addr_from_host(addr);
522 if (ram_addr != RAM_ADDR_INVALID &&
523 kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
524 kvm_hwpoison_page_add(ram_addr);
525 kvm_mce_inject(cpu, paddr, code);
526 return;
529 fprintf(stderr, "Hardware memory error for memory used by "
530 "QEMU itself instead of guest system!\n");
533 if (code == BUS_MCEERR_AR) {
534 hardware_memory_error();
537 /* Hope we are lucky for AO MCE */
540 static int kvm_inject_mce_oldstyle(X86CPU *cpu)
542 CPUX86State *env = &cpu->env;
544 if (!kvm_has_vcpu_events() && env->exception_injected == EXCP12_MCHK) {
545 unsigned int bank, bank_num = env->mcg_cap & 0xff;
546 struct kvm_x86_mce mce;
548 env->exception_injected = -1;
551 * There must be at least one bank in use if an MCE is pending.
552 * Find it and use its values for the event injection.
554 for (bank = 0; bank < bank_num; bank++) {
555 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
556 break;
559 assert(bank < bank_num);
561 mce.bank = bank;
562 mce.status = env->mce_banks[bank * 4 + 1];
563 mce.mcg_status = env->mcg_status;
564 mce.addr = env->mce_banks[bank * 4 + 2];
565 mce.misc = env->mce_banks[bank * 4 + 3];
567 return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
569 return 0;
572 static void cpu_update_state(void *opaque, int running, RunState state)
574 CPUX86State *env = opaque;
576 if (running) {
577 env->tsc_valid = false;
581 unsigned long kvm_arch_vcpu_id(CPUState *cs)
583 X86CPU *cpu = X86_CPU(cs);
584 return cpu->apic_id;
587 #ifndef KVM_CPUID_SIGNATURE_NEXT
588 #define KVM_CPUID_SIGNATURE_NEXT 0x40000100
589 #endif
591 static bool hyperv_hypercall_available(X86CPU *cpu)
593 return cpu->hyperv_vapic ||
594 (cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY);
597 static bool hyperv_enabled(X86CPU *cpu)
599 CPUState *cs = CPU(cpu);
600 return kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0 &&
601 (hyperv_hypercall_available(cpu) ||
602 cpu->hyperv_time ||
603 cpu->hyperv_relaxed_timing ||
604 cpu->hyperv_crash ||
605 cpu->hyperv_reset ||
606 cpu->hyperv_vpindex ||
607 cpu->hyperv_runtime ||
608 cpu->hyperv_synic ||
609 cpu->hyperv_stimer ||
610 cpu->hyperv_reenlightenment ||
611 cpu->hyperv_tlbflush ||
612 cpu->hyperv_ipi);
615 static int kvm_arch_set_tsc_khz(CPUState *cs)
617 X86CPU *cpu = X86_CPU(cs);
618 CPUX86State *env = &cpu->env;
619 int r;
621 if (!env->tsc_khz) {
622 return 0;
625 r = kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL) ?
626 kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) :
627 -ENOTSUP;
628 if (r < 0) {
629 /* When KVM_SET_TSC_KHZ fails, it's an error only if the current
630 * TSC frequency doesn't match the one we want.
632 int cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
633 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
634 -ENOTSUP;
635 if (cur_freq <= 0 || cur_freq != env->tsc_khz) {
636 warn_report("TSC frequency mismatch between "
637 "VM (%" PRId64 " kHz) and host (%d kHz), "
638 "and TSC scaling unavailable",
639 env->tsc_khz, cur_freq);
640 return r;
644 return 0;
647 static bool tsc_is_stable_and_known(CPUX86State *env)
649 if (!env->tsc_khz) {
650 return false;
652 return (env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC)
653 || env->user_tsc_khz;
656 static int hyperv_handle_properties(CPUState *cs)
658 X86CPU *cpu = X86_CPU(cs);
659 CPUX86State *env = &cpu->env;
661 if (cpu->hyperv_relaxed_timing) {
662 env->features[FEAT_HYPERV_EAX] |= HV_HYPERCALL_AVAILABLE;
664 if (cpu->hyperv_vapic) {
665 env->features[FEAT_HYPERV_EAX] |= HV_HYPERCALL_AVAILABLE;
666 env->features[FEAT_HYPERV_EAX] |= HV_APIC_ACCESS_AVAILABLE;
668 if (cpu->hyperv_time) {
669 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) <= 0) {
670 fprintf(stderr, "Hyper-V clocksources "
671 "(requested by 'hv-time' cpu flag) "
672 "are not supported by kernel\n");
673 return -ENOSYS;
675 env->features[FEAT_HYPERV_EAX] |= HV_HYPERCALL_AVAILABLE;
676 env->features[FEAT_HYPERV_EAX] |= HV_TIME_REF_COUNT_AVAILABLE;
677 env->features[FEAT_HYPERV_EAX] |= HV_REFERENCE_TSC_AVAILABLE;
679 if (cpu->hyperv_frequencies) {
680 if (!has_msr_hv_frequencies) {
681 fprintf(stderr, "Hyper-V frequency MSRs "
682 "(requested by 'hv-frequencies' cpu flag) "
683 "are not supported by kernel\n");
684 return -ENOSYS;
686 env->features[FEAT_HYPERV_EAX] |= HV_ACCESS_FREQUENCY_MSRS;
687 env->features[FEAT_HYPERV_EDX] |= HV_FREQUENCY_MSRS_AVAILABLE;
689 if (cpu->hyperv_crash) {
690 if (!has_msr_hv_crash) {
691 fprintf(stderr, "Hyper-V crash MSRs "
692 "(requested by 'hv-crash' cpu flag) "
693 "are not supported by kernel\n");
694 return -ENOSYS;
696 env->features[FEAT_HYPERV_EDX] |= HV_GUEST_CRASH_MSR_AVAILABLE;
698 if (cpu->hyperv_reenlightenment) {
699 if (!has_msr_hv_reenlightenment) {
700 fprintf(stderr,
701 "Hyper-V Reenlightenment MSRs "
702 "(requested by 'hv-reenlightenment' cpu flag) "
703 "are not supported by kernel\n");
704 return -ENOSYS;
706 env->features[FEAT_HYPERV_EAX] |= HV_ACCESS_REENLIGHTENMENTS_CONTROL;
708 env->features[FEAT_HYPERV_EDX] |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
709 if (cpu->hyperv_reset) {
710 if (!has_msr_hv_reset) {
711 fprintf(stderr, "Hyper-V reset MSR "
712 "(requested by 'hv-reset' cpu flag) "
713 "is not supported by kernel\n");
714 return -ENOSYS;
716 env->features[FEAT_HYPERV_EAX] |= HV_RESET_AVAILABLE;
718 if (cpu->hyperv_vpindex) {
719 if (!has_msr_hv_vpindex) {
720 fprintf(stderr, "Hyper-V VP_INDEX MSR "
721 "(requested by 'hv-vpindex' cpu flag) "
722 "is not supported by kernel\n");
723 return -ENOSYS;
725 env->features[FEAT_HYPERV_EAX] |= HV_VP_INDEX_AVAILABLE;
727 if (cpu->hyperv_runtime) {
728 if (!has_msr_hv_runtime) {
729 fprintf(stderr, "Hyper-V VP_RUNTIME MSR "
730 "(requested by 'hv-runtime' cpu flag) "
731 "is not supported by kernel\n");
732 return -ENOSYS;
734 env->features[FEAT_HYPERV_EAX] |= HV_VP_RUNTIME_AVAILABLE;
736 if (cpu->hyperv_synic) {
737 unsigned int cap = KVM_CAP_HYPERV_SYNIC;
738 if (!cpu->hyperv_synic_kvm_only) {
739 if (!cpu->hyperv_vpindex) {
740 fprintf(stderr, "Hyper-V SynIC "
741 "(requested by 'hv-synic' cpu flag) "
742 "requires Hyper-V VP_INDEX ('hv-vpindex')\n");
743 return -ENOSYS;
745 cap = KVM_CAP_HYPERV_SYNIC2;
748 if (!has_msr_hv_synic || !kvm_check_extension(cs->kvm_state, cap)) {
749 fprintf(stderr, "Hyper-V SynIC (requested by 'hv-synic' cpu flag) "
750 "is not supported by kernel\n");
751 return -ENOSYS;
754 env->features[FEAT_HYPERV_EAX] |= HV_SYNIC_AVAILABLE;
756 if (cpu->hyperv_stimer) {
757 if (!has_msr_hv_stimer) {
758 fprintf(stderr, "Hyper-V timers aren't supported by kernel\n");
759 return -ENOSYS;
761 env->features[FEAT_HYPERV_EAX] |= HV_SYNTIMERS_AVAILABLE;
763 return 0;
766 static int hyperv_init_vcpu(X86CPU *cpu)
768 CPUState *cs = CPU(cpu);
769 int ret;
771 if (cpu->hyperv_vpindex && !hv_vpindex_settable) {
773 * the kernel doesn't support setting vp_index; assert that its value
774 * is in sync
776 struct {
777 struct kvm_msrs info;
778 struct kvm_msr_entry entries[1];
779 } msr_data = {
780 .info.nmsrs = 1,
781 .entries[0].index = HV_X64_MSR_VP_INDEX,
784 ret = kvm_vcpu_ioctl(cs, KVM_GET_MSRS, &msr_data);
785 if (ret < 0) {
786 return ret;
788 assert(ret == 1);
790 if (msr_data.entries[0].data != hyperv_vp_index(CPU(cpu))) {
791 error_report("kernel's vp_index != QEMU's vp_index");
792 return -ENXIO;
796 if (cpu->hyperv_synic) {
797 uint32_t synic_cap = cpu->hyperv_synic_kvm_only ?
798 KVM_CAP_HYPERV_SYNIC : KVM_CAP_HYPERV_SYNIC2;
799 ret = kvm_vcpu_enable_cap(cs, synic_cap, 0);
800 if (ret < 0) {
801 error_report("failed to turn on HyperV SynIC in KVM: %s",
802 strerror(-ret));
803 return ret;
806 if (!cpu->hyperv_synic_kvm_only) {
807 ret = hyperv_x86_synic_add(cpu);
808 if (ret < 0) {
809 error_report("failed to create HyperV SynIC: %s",
810 strerror(-ret));
811 return ret;
816 return 0;
819 static Error *invtsc_mig_blocker;
821 #define KVM_MAX_CPUID_ENTRIES 100
823 int kvm_arch_init_vcpu(CPUState *cs)
825 struct {
826 struct kvm_cpuid2 cpuid;
827 struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
828 } QEMU_PACKED cpuid_data;
829 X86CPU *cpu = X86_CPU(cs);
830 CPUX86State *env = &cpu->env;
831 uint32_t limit, i, j, cpuid_i;
832 uint32_t unused;
833 struct kvm_cpuid_entry2 *c;
834 uint32_t signature[3];
835 int kvm_base = KVM_CPUID_SIGNATURE;
836 int r;
837 Error *local_err = NULL;
839 memset(&cpuid_data, 0, sizeof(cpuid_data));
841 cpuid_i = 0;
843 r = kvm_arch_set_tsc_khz(cs);
844 if (r < 0) {
845 goto fail;
848 /* vcpu's TSC frequency is either specified by user, or following
849 * the value used by KVM if the former is not present. In the
850 * latter case, we query it from KVM and record in env->tsc_khz,
851 * so that vcpu's TSC frequency can be migrated later via this field.
853 if (!env->tsc_khz) {
854 r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
855 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
856 -ENOTSUP;
857 if (r > 0) {
858 env->tsc_khz = r;
862 /* Paravirtualization CPUIDs */
863 if (hyperv_enabled(cpu)) {
864 c = &cpuid_data.entries[cpuid_i++];
865 c->function = HV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
866 if (!cpu->hyperv_vendor_id) {
867 memcpy(signature, "Microsoft Hv", 12);
868 } else {
869 size_t len = strlen(cpu->hyperv_vendor_id);
871 if (len > 12) {
872 error_report("hv-vendor-id truncated to 12 characters");
873 len = 12;
875 memset(signature, 0, 12);
876 memcpy(signature, cpu->hyperv_vendor_id, len);
878 c->eax = HV_CPUID_MIN;
879 c->ebx = signature[0];
880 c->ecx = signature[1];
881 c->edx = signature[2];
883 c = &cpuid_data.entries[cpuid_i++];
884 c->function = HV_CPUID_INTERFACE;
885 memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
886 c->eax = signature[0];
887 c->ebx = 0;
888 c->ecx = 0;
889 c->edx = 0;
891 c = &cpuid_data.entries[cpuid_i++];
892 c->function = HV_CPUID_VERSION;
893 c->eax = 0x00001bbc;
894 c->ebx = 0x00060001;
896 c = &cpuid_data.entries[cpuid_i++];
897 c->function = HV_CPUID_FEATURES;
898 r = hyperv_handle_properties(cs);
899 if (r) {
900 return r;
902 c->eax = env->features[FEAT_HYPERV_EAX];
903 c->ebx = env->features[FEAT_HYPERV_EBX];
904 c->edx = env->features[FEAT_HYPERV_EDX];
906 c = &cpuid_data.entries[cpuid_i++];
907 c->function = HV_CPUID_ENLIGHTMENT_INFO;
908 if (cpu->hyperv_relaxed_timing) {
909 c->eax |= HV_RELAXED_TIMING_RECOMMENDED;
911 if (cpu->hyperv_vapic) {
912 c->eax |= HV_APIC_ACCESS_RECOMMENDED;
914 if (cpu->hyperv_tlbflush) {
915 if (kvm_check_extension(cs->kvm_state,
916 KVM_CAP_HYPERV_TLBFLUSH) <= 0) {
917 fprintf(stderr, "Hyper-V TLB flush support "
918 "(requested by 'hv-tlbflush' cpu flag) "
919 " is not supported by kernel\n");
920 return -ENOSYS;
922 c->eax |= HV_REMOTE_TLB_FLUSH_RECOMMENDED;
923 c->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
925 if (cpu->hyperv_ipi) {
926 if (kvm_check_extension(cs->kvm_state,
927 KVM_CAP_HYPERV_SEND_IPI) <= 0) {
928 fprintf(stderr, "Hyper-V IPI send support "
929 "(requested by 'hv-ipi' cpu flag) "
930 " is not supported by kernel\n");
931 return -ENOSYS;
933 c->eax |= HV_CLUSTER_IPI_RECOMMENDED;
934 c->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
937 c->ebx = cpu->hyperv_spinlock_attempts;
939 c = &cpuid_data.entries[cpuid_i++];
940 c->function = HV_CPUID_IMPLEMENT_LIMITS;
942 c->eax = cpu->hv_max_vps;
943 c->ebx = 0x40;
945 kvm_base = KVM_CPUID_SIGNATURE_NEXT;
946 has_msr_hv_hypercall = true;
949 if (cpu->expose_kvm) {
950 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
951 c = &cpuid_data.entries[cpuid_i++];
952 c->function = KVM_CPUID_SIGNATURE | kvm_base;
953 c->eax = KVM_CPUID_FEATURES | kvm_base;
954 c->ebx = signature[0];
955 c->ecx = signature[1];
956 c->edx = signature[2];
958 c = &cpuid_data.entries[cpuid_i++];
959 c->function = KVM_CPUID_FEATURES | kvm_base;
960 c->eax = env->features[FEAT_KVM];
961 c->edx = env->features[FEAT_KVM_HINTS];
964 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
966 for (i = 0; i <= limit; i++) {
967 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
968 fprintf(stderr, "unsupported level value: 0x%x\n", limit);
969 abort();
971 c = &cpuid_data.entries[cpuid_i++];
973 switch (i) {
974 case 2: {
975 /* Keep reading function 2 till all the input is received */
976 int times;
978 c->function = i;
979 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
980 KVM_CPUID_FLAG_STATE_READ_NEXT;
981 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
982 times = c->eax & 0xff;
984 for (j = 1; j < times; ++j) {
985 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
986 fprintf(stderr, "cpuid_data is full, no space for "
987 "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
988 abort();
990 c = &cpuid_data.entries[cpuid_i++];
991 c->function = i;
992 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
993 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
995 break;
997 case 4:
998 case 0xb:
999 case 0xd:
1000 for (j = 0; ; j++) {
1001 if (i == 0xd && j == 64) {
1002 break;
1004 c->function = i;
1005 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1006 c->index = j;
1007 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1009 if (i == 4 && c->eax == 0) {
1010 break;
1012 if (i == 0xb && !(c->ecx & 0xff00)) {
1013 break;
1015 if (i == 0xd && c->eax == 0) {
1016 continue;
1018 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1019 fprintf(stderr, "cpuid_data is full, no space for "
1020 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1021 abort();
1023 c = &cpuid_data.entries[cpuid_i++];
1025 break;
1026 case 0x14: {
1027 uint32_t times;
1029 c->function = i;
1030 c->index = 0;
1031 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1032 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1033 times = c->eax;
1035 for (j = 1; j <= times; ++j) {
1036 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1037 fprintf(stderr, "cpuid_data is full, no space for "
1038 "cpuid(eax:0x14,ecx:0x%x)\n", j);
1039 abort();
1041 c = &cpuid_data.entries[cpuid_i++];
1042 c->function = i;
1043 c->index = j;
1044 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1045 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1047 break;
1049 default:
1050 c->function = i;
1051 c->flags = 0;
1052 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1053 break;
1057 if (limit >= 0x0a) {
1058 uint32_t eax, edx;
1060 cpu_x86_cpuid(env, 0x0a, 0, &eax, &unused, &unused, &edx);
1062 has_architectural_pmu_version = eax & 0xff;
1063 if (has_architectural_pmu_version > 0) {
1064 num_architectural_pmu_gp_counters = (eax & 0xff00) >> 8;
1066 /* Shouldn't be more than 32, since that's the number of bits
1067 * available in EBX to tell us _which_ counters are available.
1068 * Play it safe.
1070 if (num_architectural_pmu_gp_counters > MAX_GP_COUNTERS) {
1071 num_architectural_pmu_gp_counters = MAX_GP_COUNTERS;
1074 if (has_architectural_pmu_version > 1) {
1075 num_architectural_pmu_fixed_counters = edx & 0x1f;
1077 if (num_architectural_pmu_fixed_counters > MAX_FIXED_COUNTERS) {
1078 num_architectural_pmu_fixed_counters = MAX_FIXED_COUNTERS;
1084 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
1086 for (i = 0x80000000; i <= limit; i++) {
1087 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1088 fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
1089 abort();
1091 c = &cpuid_data.entries[cpuid_i++];
1093 switch (i) {
1094 case 0x8000001d:
1095 /* Query for all AMD cache information leaves */
1096 for (j = 0; ; j++) {
1097 c->function = i;
1098 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1099 c->index = j;
1100 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1102 if (c->eax == 0) {
1103 break;
1105 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1106 fprintf(stderr, "cpuid_data is full, no space for "
1107 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1108 abort();
1110 c = &cpuid_data.entries[cpuid_i++];
1112 break;
1113 default:
1114 c->function = i;
1115 c->flags = 0;
1116 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1117 break;
1121 /* Call Centaur's CPUID instructions they are supported. */
1122 if (env->cpuid_xlevel2 > 0) {
1123 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
1125 for (i = 0xC0000000; i <= limit; i++) {
1126 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1127 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
1128 abort();
1130 c = &cpuid_data.entries[cpuid_i++];
1132 c->function = i;
1133 c->flags = 0;
1134 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1138 cpuid_data.cpuid.nent = cpuid_i;
1140 if (((env->cpuid_version >> 8)&0xF) >= 6
1141 && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
1142 (CPUID_MCE | CPUID_MCA)
1143 && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
1144 uint64_t mcg_cap, unsupported_caps;
1145 int banks;
1146 int ret;
1148 ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
1149 if (ret < 0) {
1150 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
1151 return ret;
1154 if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
1155 error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
1156 (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
1157 return -ENOTSUP;
1160 unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
1161 if (unsupported_caps) {
1162 if (unsupported_caps & MCG_LMCE_P) {
1163 error_report("kvm: LMCE not supported");
1164 return -ENOTSUP;
1166 warn_report("Unsupported MCG_CAP bits: 0x%" PRIx64,
1167 unsupported_caps);
1170 env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
1171 ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
1172 if (ret < 0) {
1173 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
1174 return ret;
1178 qemu_add_vm_change_state_handler(cpu_update_state, env);
1180 c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
1181 if (c) {
1182 has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
1183 !!(c->ecx & CPUID_EXT_SMX);
1186 if (env->mcg_cap & MCG_LMCE_P) {
1187 has_msr_mcg_ext_ctl = has_msr_feature_control = true;
1190 if (!env->user_tsc_khz) {
1191 if ((env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC) &&
1192 invtsc_mig_blocker == NULL) {
1193 /* for migration */
1194 error_setg(&invtsc_mig_blocker,
1195 "State blocked by non-migratable CPU device"
1196 " (invtsc flag)");
1197 r = migrate_add_blocker(invtsc_mig_blocker, &local_err);
1198 if (local_err) {
1199 error_report_err(local_err);
1200 error_free(invtsc_mig_blocker);
1201 goto fail;
1203 /* for savevm */
1204 vmstate_x86_cpu.unmigratable = 1;
1208 if (cpu->vmware_cpuid_freq
1209 /* Guests depend on 0x40000000 to detect this feature, so only expose
1210 * it if KVM exposes leaf 0x40000000. (Conflicts with Hyper-V) */
1211 && cpu->expose_kvm
1212 && kvm_base == KVM_CPUID_SIGNATURE
1213 /* TSC clock must be stable and known for this feature. */
1214 && tsc_is_stable_and_known(env)) {
1216 c = &cpuid_data.entries[cpuid_i++];
1217 c->function = KVM_CPUID_SIGNATURE | 0x10;
1218 c->eax = env->tsc_khz;
1219 /* LAPIC resolution of 1ns (freq: 1GHz) is hardcoded in KVM's
1220 * APIC_BUS_CYCLE_NS */
1221 c->ebx = 1000000;
1222 c->ecx = c->edx = 0;
1224 c = cpuid_find_entry(&cpuid_data.cpuid, kvm_base, 0);
1225 c->eax = MAX(c->eax, KVM_CPUID_SIGNATURE | 0x10);
1228 cpuid_data.cpuid.nent = cpuid_i;
1230 cpuid_data.cpuid.padding = 0;
1231 r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
1232 if (r) {
1233 goto fail;
1236 if (has_xsave) {
1237 env->xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
1239 cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
1241 if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
1242 has_msr_tsc_aux = false;
1245 r = hyperv_init_vcpu(cpu);
1246 if (r) {
1247 goto fail;
1250 return 0;
1252 fail:
1253 migrate_del_blocker(invtsc_mig_blocker);
1254 return r;
1257 void kvm_arch_reset_vcpu(X86CPU *cpu)
1259 CPUX86State *env = &cpu->env;
1261 env->xcr0 = 1;
1262 if (kvm_irqchip_in_kernel()) {
1263 env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
1264 KVM_MP_STATE_UNINITIALIZED;
1265 } else {
1266 env->mp_state = KVM_MP_STATE_RUNNABLE;
1269 if (cpu->hyperv_synic) {
1270 int i;
1271 for (i = 0; i < ARRAY_SIZE(env->msr_hv_synic_sint); i++) {
1272 env->msr_hv_synic_sint[i] = HV_SINT_MASKED;
1275 hyperv_x86_synic_reset(cpu);
1279 void kvm_arch_do_init_vcpu(X86CPU *cpu)
1281 CPUX86State *env = &cpu->env;
1283 /* APs get directly into wait-for-SIPI state. */
1284 if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
1285 env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
1289 static int kvm_get_supported_msrs(KVMState *s)
1291 static int kvm_supported_msrs;
1292 int ret = 0;
1294 /* first time */
1295 if (kvm_supported_msrs == 0) {
1296 struct kvm_msr_list msr_list, *kvm_msr_list;
1298 kvm_supported_msrs = -1;
1300 /* Obtain MSR list from KVM. These are the MSRs that we must
1301 * save/restore */
1302 msr_list.nmsrs = 0;
1303 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
1304 if (ret < 0 && ret != -E2BIG) {
1305 return ret;
1307 /* Old kernel modules had a bug and could write beyond the provided
1308 memory. Allocate at least a safe amount of 1K. */
1309 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
1310 msr_list.nmsrs *
1311 sizeof(msr_list.indices[0])));
1313 kvm_msr_list->nmsrs = msr_list.nmsrs;
1314 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
1315 if (ret >= 0) {
1316 int i;
1318 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
1319 switch (kvm_msr_list->indices[i]) {
1320 case MSR_STAR:
1321 has_msr_star = true;
1322 break;
1323 case MSR_VM_HSAVE_PA:
1324 has_msr_hsave_pa = true;
1325 break;
1326 case MSR_TSC_AUX:
1327 has_msr_tsc_aux = true;
1328 break;
1329 case MSR_TSC_ADJUST:
1330 has_msr_tsc_adjust = true;
1331 break;
1332 case MSR_IA32_TSCDEADLINE:
1333 has_msr_tsc_deadline = true;
1334 break;
1335 case MSR_IA32_SMBASE:
1336 has_msr_smbase = true;
1337 break;
1338 case MSR_SMI_COUNT:
1339 has_msr_smi_count = true;
1340 break;
1341 case MSR_IA32_MISC_ENABLE:
1342 has_msr_misc_enable = true;
1343 break;
1344 case MSR_IA32_BNDCFGS:
1345 has_msr_bndcfgs = true;
1346 break;
1347 case MSR_IA32_XSS:
1348 has_msr_xss = true;
1349 break;
1350 case HV_X64_MSR_CRASH_CTL:
1351 has_msr_hv_crash = true;
1352 break;
1353 case HV_X64_MSR_RESET:
1354 has_msr_hv_reset = true;
1355 break;
1356 case HV_X64_MSR_VP_INDEX:
1357 has_msr_hv_vpindex = true;
1358 break;
1359 case HV_X64_MSR_VP_RUNTIME:
1360 has_msr_hv_runtime = true;
1361 break;
1362 case HV_X64_MSR_SCONTROL:
1363 has_msr_hv_synic = true;
1364 break;
1365 case HV_X64_MSR_STIMER0_CONFIG:
1366 has_msr_hv_stimer = true;
1367 break;
1368 case HV_X64_MSR_TSC_FREQUENCY:
1369 has_msr_hv_frequencies = true;
1370 break;
1371 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
1372 has_msr_hv_reenlightenment = true;
1373 break;
1374 case MSR_IA32_SPEC_CTRL:
1375 has_msr_spec_ctrl = true;
1376 break;
1377 case MSR_VIRT_SSBD:
1378 has_msr_virt_ssbd = true;
1379 break;
1384 g_free(kvm_msr_list);
1387 return ret;
1390 static Notifier smram_machine_done;
1391 static KVMMemoryListener smram_listener;
1392 static AddressSpace smram_address_space;
1393 static MemoryRegion smram_as_root;
1394 static MemoryRegion smram_as_mem;
1396 static void register_smram_listener(Notifier *n, void *unused)
1398 MemoryRegion *smram =
1399 (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
1401 /* Outer container... */
1402 memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
1403 memory_region_set_enabled(&smram_as_root, true);
1405 /* ... with two regions inside: normal system memory with low
1406 * priority, and...
1408 memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
1409 get_system_memory(), 0, ~0ull);
1410 memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
1411 memory_region_set_enabled(&smram_as_mem, true);
1413 if (smram) {
1414 /* ... SMRAM with higher priority */
1415 memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
1416 memory_region_set_enabled(smram, true);
1419 address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
1420 kvm_memory_listener_register(kvm_state, &smram_listener,
1421 &smram_address_space, 1);
1424 int kvm_arch_init(MachineState *ms, KVMState *s)
1426 uint64_t identity_base = 0xfffbc000;
1427 uint64_t shadow_mem;
1428 int ret;
1429 struct utsname utsname;
1431 has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1432 has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1433 has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1435 hv_vpindex_settable = kvm_check_extension(s, KVM_CAP_HYPERV_VP_INDEX);
1437 ret = kvm_get_supported_msrs(s);
1438 if (ret < 0) {
1439 return ret;
1442 uname(&utsname);
1443 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
1446 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
1447 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
1448 * Since these must be part of guest physical memory, we need to allocate
1449 * them, both by setting their start addresses in the kernel and by
1450 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
1452 * Older KVM versions may not support setting the identity map base. In
1453 * that case we need to stick with the default, i.e. a 256K maximum BIOS
1454 * size.
1456 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
1457 /* Allows up to 16M BIOSes. */
1458 identity_base = 0xfeffc000;
1460 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
1461 if (ret < 0) {
1462 return ret;
1466 /* Set TSS base one page after EPT identity map. */
1467 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
1468 if (ret < 0) {
1469 return ret;
1472 /* Tell fw_cfg to notify the BIOS to reserve the range. */
1473 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
1474 if (ret < 0) {
1475 fprintf(stderr, "e820_add_entry() table is full\n");
1476 return ret;
1478 qemu_register_reset(kvm_unpoison_all, NULL);
1480 shadow_mem = machine_kvm_shadow_mem(ms);
1481 if (shadow_mem != -1) {
1482 shadow_mem /= 4096;
1483 ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
1484 if (ret < 0) {
1485 return ret;
1489 if (kvm_check_extension(s, KVM_CAP_X86_SMM) &&
1490 object_dynamic_cast(OBJECT(ms), TYPE_PC_MACHINE) &&
1491 pc_machine_is_smm_enabled(PC_MACHINE(ms))) {
1492 smram_machine_done.notify = register_smram_listener;
1493 qemu_add_machine_init_done_notifier(&smram_machine_done);
1496 if (enable_cpu_pm) {
1497 int disable_exits = kvm_check_extension(s, KVM_CAP_X86_DISABLE_EXITS);
1498 int ret;
1500 /* Work around for kernel header with a typo. TODO: fix header and drop. */
1501 #if defined(KVM_X86_DISABLE_EXITS_HTL) && !defined(KVM_X86_DISABLE_EXITS_HLT)
1502 #define KVM_X86_DISABLE_EXITS_HLT KVM_X86_DISABLE_EXITS_HTL
1503 #endif
1504 if (disable_exits) {
1505 disable_exits &= (KVM_X86_DISABLE_EXITS_MWAIT |
1506 KVM_X86_DISABLE_EXITS_HLT |
1507 KVM_X86_DISABLE_EXITS_PAUSE);
1510 ret = kvm_vm_enable_cap(s, KVM_CAP_X86_DISABLE_EXITS, 0,
1511 disable_exits);
1512 if (ret < 0) {
1513 error_report("kvm: guest stopping CPU not supported: %s",
1514 strerror(-ret));
1518 return 0;
1521 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1523 lhs->selector = rhs->selector;
1524 lhs->base = rhs->base;
1525 lhs->limit = rhs->limit;
1526 lhs->type = 3;
1527 lhs->present = 1;
1528 lhs->dpl = 3;
1529 lhs->db = 0;
1530 lhs->s = 1;
1531 lhs->l = 0;
1532 lhs->g = 0;
1533 lhs->avl = 0;
1534 lhs->unusable = 0;
1537 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1539 unsigned flags = rhs->flags;
1540 lhs->selector = rhs->selector;
1541 lhs->base = rhs->base;
1542 lhs->limit = rhs->limit;
1543 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
1544 lhs->present = (flags & DESC_P_MASK) != 0;
1545 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
1546 lhs->db = (flags >> DESC_B_SHIFT) & 1;
1547 lhs->s = (flags & DESC_S_MASK) != 0;
1548 lhs->l = (flags >> DESC_L_SHIFT) & 1;
1549 lhs->g = (flags & DESC_G_MASK) != 0;
1550 lhs->avl = (flags & DESC_AVL_MASK) != 0;
1551 lhs->unusable = !lhs->present;
1552 lhs->padding = 0;
1555 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
1557 lhs->selector = rhs->selector;
1558 lhs->base = rhs->base;
1559 lhs->limit = rhs->limit;
1560 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
1561 ((rhs->present && !rhs->unusable) * DESC_P_MASK) |
1562 (rhs->dpl << DESC_DPL_SHIFT) |
1563 (rhs->db << DESC_B_SHIFT) |
1564 (rhs->s * DESC_S_MASK) |
1565 (rhs->l << DESC_L_SHIFT) |
1566 (rhs->g * DESC_G_MASK) |
1567 (rhs->avl * DESC_AVL_MASK);
1570 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
1572 if (set) {
1573 *kvm_reg = *qemu_reg;
1574 } else {
1575 *qemu_reg = *kvm_reg;
1579 static int kvm_getput_regs(X86CPU *cpu, int set)
1581 CPUX86State *env = &cpu->env;
1582 struct kvm_regs regs;
1583 int ret = 0;
1585 if (!set) {
1586 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
1587 if (ret < 0) {
1588 return ret;
1592 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
1593 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
1594 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
1595 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
1596 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
1597 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
1598 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
1599 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
1600 #ifdef TARGET_X86_64
1601 kvm_getput_reg(&regs.r8, &env->regs[8], set);
1602 kvm_getput_reg(&regs.r9, &env->regs[9], set);
1603 kvm_getput_reg(&regs.r10, &env->regs[10], set);
1604 kvm_getput_reg(&regs.r11, &env->regs[11], set);
1605 kvm_getput_reg(&regs.r12, &env->regs[12], set);
1606 kvm_getput_reg(&regs.r13, &env->regs[13], set);
1607 kvm_getput_reg(&regs.r14, &env->regs[14], set);
1608 kvm_getput_reg(&regs.r15, &env->regs[15], set);
1609 #endif
1611 kvm_getput_reg(&regs.rflags, &env->eflags, set);
1612 kvm_getput_reg(&regs.rip, &env->eip, set);
1614 if (set) {
1615 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
1618 return ret;
1621 static int kvm_put_fpu(X86CPU *cpu)
1623 CPUX86State *env = &cpu->env;
1624 struct kvm_fpu fpu;
1625 int i;
1627 memset(&fpu, 0, sizeof fpu);
1628 fpu.fsw = env->fpus & ~(7 << 11);
1629 fpu.fsw |= (env->fpstt & 7) << 11;
1630 fpu.fcw = env->fpuc;
1631 fpu.last_opcode = env->fpop;
1632 fpu.last_ip = env->fpip;
1633 fpu.last_dp = env->fpdp;
1634 for (i = 0; i < 8; ++i) {
1635 fpu.ftwx |= (!env->fptags[i]) << i;
1637 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
1638 for (i = 0; i < CPU_NB_REGS; i++) {
1639 stq_p(&fpu.xmm[i][0], env->xmm_regs[i].ZMM_Q(0));
1640 stq_p(&fpu.xmm[i][8], env->xmm_regs[i].ZMM_Q(1));
1642 fpu.mxcsr = env->mxcsr;
1644 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
1647 #define XSAVE_FCW_FSW 0
1648 #define XSAVE_FTW_FOP 1
1649 #define XSAVE_CWD_RIP 2
1650 #define XSAVE_CWD_RDP 4
1651 #define XSAVE_MXCSR 6
1652 #define XSAVE_ST_SPACE 8
1653 #define XSAVE_XMM_SPACE 40
1654 #define XSAVE_XSTATE_BV 128
1655 #define XSAVE_YMMH_SPACE 144
1656 #define XSAVE_BNDREGS 240
1657 #define XSAVE_BNDCSR 256
1658 #define XSAVE_OPMASK 272
1659 #define XSAVE_ZMM_Hi256 288
1660 #define XSAVE_Hi16_ZMM 416
1661 #define XSAVE_PKRU 672
1663 #define XSAVE_BYTE_OFFSET(word_offset) \
1664 ((word_offset) * sizeof_field(struct kvm_xsave, region[0]))
1666 #define ASSERT_OFFSET(word_offset, field) \
1667 QEMU_BUILD_BUG_ON(XSAVE_BYTE_OFFSET(word_offset) != \
1668 offsetof(X86XSaveArea, field))
1670 ASSERT_OFFSET(XSAVE_FCW_FSW, legacy.fcw);
1671 ASSERT_OFFSET(XSAVE_FTW_FOP, legacy.ftw);
1672 ASSERT_OFFSET(XSAVE_CWD_RIP, legacy.fpip);
1673 ASSERT_OFFSET(XSAVE_CWD_RDP, legacy.fpdp);
1674 ASSERT_OFFSET(XSAVE_MXCSR, legacy.mxcsr);
1675 ASSERT_OFFSET(XSAVE_ST_SPACE, legacy.fpregs);
1676 ASSERT_OFFSET(XSAVE_XMM_SPACE, legacy.xmm_regs);
1677 ASSERT_OFFSET(XSAVE_XSTATE_BV, header.xstate_bv);
1678 ASSERT_OFFSET(XSAVE_YMMH_SPACE, avx_state);
1679 ASSERT_OFFSET(XSAVE_BNDREGS, bndreg_state);
1680 ASSERT_OFFSET(XSAVE_BNDCSR, bndcsr_state);
1681 ASSERT_OFFSET(XSAVE_OPMASK, opmask_state);
1682 ASSERT_OFFSET(XSAVE_ZMM_Hi256, zmm_hi256_state);
1683 ASSERT_OFFSET(XSAVE_Hi16_ZMM, hi16_zmm_state);
1684 ASSERT_OFFSET(XSAVE_PKRU, pkru_state);
1686 static int kvm_put_xsave(X86CPU *cpu)
1688 CPUX86State *env = &cpu->env;
1689 X86XSaveArea *xsave = env->xsave_buf;
1691 if (!has_xsave) {
1692 return kvm_put_fpu(cpu);
1694 x86_cpu_xsave_all_areas(cpu, xsave);
1696 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
1699 static int kvm_put_xcrs(X86CPU *cpu)
1701 CPUX86State *env = &cpu->env;
1702 struct kvm_xcrs xcrs = {};
1704 if (!has_xcrs) {
1705 return 0;
1708 xcrs.nr_xcrs = 1;
1709 xcrs.flags = 0;
1710 xcrs.xcrs[0].xcr = 0;
1711 xcrs.xcrs[0].value = env->xcr0;
1712 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
1715 static int kvm_put_sregs(X86CPU *cpu)
1717 CPUX86State *env = &cpu->env;
1718 struct kvm_sregs sregs;
1720 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
1721 if (env->interrupt_injected >= 0) {
1722 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
1723 (uint64_t)1 << (env->interrupt_injected % 64);
1726 if ((env->eflags & VM_MASK)) {
1727 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
1728 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
1729 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
1730 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
1731 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
1732 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
1733 } else {
1734 set_seg(&sregs.cs, &env->segs[R_CS]);
1735 set_seg(&sregs.ds, &env->segs[R_DS]);
1736 set_seg(&sregs.es, &env->segs[R_ES]);
1737 set_seg(&sregs.fs, &env->segs[R_FS]);
1738 set_seg(&sregs.gs, &env->segs[R_GS]);
1739 set_seg(&sregs.ss, &env->segs[R_SS]);
1742 set_seg(&sregs.tr, &env->tr);
1743 set_seg(&sregs.ldt, &env->ldt);
1745 sregs.idt.limit = env->idt.limit;
1746 sregs.idt.base = env->idt.base;
1747 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
1748 sregs.gdt.limit = env->gdt.limit;
1749 sregs.gdt.base = env->gdt.base;
1750 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
1752 sregs.cr0 = env->cr[0];
1753 sregs.cr2 = env->cr[2];
1754 sregs.cr3 = env->cr[3];
1755 sregs.cr4 = env->cr[4];
1757 sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
1758 sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
1760 sregs.efer = env->efer;
1762 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
1765 static void kvm_msr_buf_reset(X86CPU *cpu)
1767 memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
1770 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
1772 struct kvm_msrs *msrs = cpu->kvm_msr_buf;
1773 void *limit = ((void *)msrs) + MSR_BUF_SIZE;
1774 struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
1776 assert((void *)(entry + 1) <= limit);
1778 entry->index = index;
1779 entry->reserved = 0;
1780 entry->data = value;
1781 msrs->nmsrs++;
1784 static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
1786 kvm_msr_buf_reset(cpu);
1787 kvm_msr_entry_add(cpu, index, value);
1789 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1792 void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
1794 int ret;
1796 ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
1797 assert(ret == 1);
1800 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
1802 CPUX86State *env = &cpu->env;
1803 int ret;
1805 if (!has_msr_tsc_deadline) {
1806 return 0;
1809 ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
1810 if (ret < 0) {
1811 return ret;
1814 assert(ret == 1);
1815 return 0;
1819 * Provide a separate write service for the feature control MSR in order to
1820 * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
1821 * before writing any other state because forcibly leaving nested mode
1822 * invalidates the VCPU state.
1824 static int kvm_put_msr_feature_control(X86CPU *cpu)
1826 int ret;
1828 if (!has_msr_feature_control) {
1829 return 0;
1832 ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
1833 cpu->env.msr_ia32_feature_control);
1834 if (ret < 0) {
1835 return ret;
1838 assert(ret == 1);
1839 return 0;
1842 static int kvm_put_msrs(X86CPU *cpu, int level)
1844 CPUX86State *env = &cpu->env;
1845 int i;
1846 int ret;
1848 kvm_msr_buf_reset(cpu);
1850 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
1851 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
1852 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
1853 kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
1854 if (has_msr_star) {
1855 kvm_msr_entry_add(cpu, MSR_STAR, env->star);
1857 if (has_msr_hsave_pa) {
1858 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
1860 if (has_msr_tsc_aux) {
1861 kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
1863 if (has_msr_tsc_adjust) {
1864 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
1866 if (has_msr_misc_enable) {
1867 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
1868 env->msr_ia32_misc_enable);
1870 if (has_msr_smbase) {
1871 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
1873 if (has_msr_smi_count) {
1874 kvm_msr_entry_add(cpu, MSR_SMI_COUNT, env->msr_smi_count);
1876 if (has_msr_bndcfgs) {
1877 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
1879 if (has_msr_xss) {
1880 kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
1882 if (has_msr_spec_ctrl) {
1883 kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, env->spec_ctrl);
1885 if (has_msr_virt_ssbd) {
1886 kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, env->virt_ssbd);
1889 #ifdef TARGET_X86_64
1890 if (lm_capable_kernel) {
1891 kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
1892 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
1893 kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
1894 kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
1896 #endif
1899 * The following MSRs have side effects on the guest or are too heavy
1900 * for normal writeback. Limit them to reset or full state updates.
1902 if (level >= KVM_PUT_RESET_STATE) {
1903 kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
1904 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
1905 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
1906 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
1907 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
1909 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
1910 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
1912 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
1913 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
1915 if (has_architectural_pmu_version > 0) {
1916 if (has_architectural_pmu_version > 1) {
1917 /* Stop the counter. */
1918 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
1919 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
1922 /* Set the counter values. */
1923 for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
1924 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
1925 env->msr_fixed_counters[i]);
1927 for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
1928 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
1929 env->msr_gp_counters[i]);
1930 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
1931 env->msr_gp_evtsel[i]);
1933 if (has_architectural_pmu_version > 1) {
1934 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
1935 env->msr_global_status);
1936 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1937 env->msr_global_ovf_ctrl);
1939 /* Now start the PMU. */
1940 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
1941 env->msr_fixed_ctr_ctrl);
1942 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
1943 env->msr_global_ctrl);
1947 * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,
1948 * only sync them to KVM on the first cpu
1950 if (current_cpu == first_cpu) {
1951 if (has_msr_hv_hypercall) {
1952 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
1953 env->msr_hv_guest_os_id);
1954 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
1955 env->msr_hv_hypercall);
1957 if (cpu->hyperv_time) {
1958 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,
1959 env->msr_hv_tsc);
1961 if (cpu->hyperv_reenlightenment) {
1962 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL,
1963 env->msr_hv_reenlightenment_control);
1964 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL,
1965 env->msr_hv_tsc_emulation_control);
1966 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS,
1967 env->msr_hv_tsc_emulation_status);
1970 if (cpu->hyperv_vapic) {
1971 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
1972 env->msr_hv_vapic);
1974 if (has_msr_hv_crash) {
1975 int j;
1977 for (j = 0; j < HV_CRASH_PARAMS; j++)
1978 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
1979 env->msr_hv_crash_params[j]);
1981 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);
1983 if (has_msr_hv_runtime) {
1984 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
1986 if (cpu->hyperv_vpindex && hv_vpindex_settable) {
1987 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_INDEX,
1988 hyperv_vp_index(CPU(cpu)));
1990 if (cpu->hyperv_synic) {
1991 int j;
1993 kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);
1995 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
1996 env->msr_hv_synic_control);
1997 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
1998 env->msr_hv_synic_evt_page);
1999 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
2000 env->msr_hv_synic_msg_page);
2002 for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
2003 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
2004 env->msr_hv_synic_sint[j]);
2007 if (has_msr_hv_stimer) {
2008 int j;
2010 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
2011 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
2012 env->msr_hv_stimer_config[j]);
2015 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
2016 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
2017 env->msr_hv_stimer_count[j]);
2020 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
2021 uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
2023 kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
2024 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
2025 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
2026 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
2027 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
2028 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
2029 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
2030 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
2031 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
2032 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
2033 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
2034 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
2035 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
2036 /* The CPU GPs if we write to a bit above the physical limit of
2037 * the host CPU (and KVM emulates that)
2039 uint64_t mask = env->mtrr_var[i].mask;
2040 mask &= phys_mask;
2042 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
2043 env->mtrr_var[i].base);
2044 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
2047 if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
2048 int addr_num = kvm_arch_get_supported_cpuid(kvm_state,
2049 0x14, 1, R_EAX) & 0x7;
2051 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL,
2052 env->msr_rtit_ctrl);
2053 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS,
2054 env->msr_rtit_status);
2055 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE,
2056 env->msr_rtit_output_base);
2057 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK,
2058 env->msr_rtit_output_mask);
2059 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH,
2060 env->msr_rtit_cr3_match);
2061 for (i = 0; i < addr_num; i++) {
2062 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i,
2063 env->msr_rtit_addrs[i]);
2067 /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
2068 * kvm_put_msr_feature_control. */
2070 if (env->mcg_cap) {
2071 int i;
2073 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
2074 kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
2075 if (has_msr_mcg_ext_ctl) {
2076 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
2078 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
2079 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
2083 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
2084 if (ret < 0) {
2085 return ret;
2088 if (ret < cpu->kvm_msr_buf->nmsrs) {
2089 struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
2090 error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,
2091 (uint32_t)e->index, (uint64_t)e->data);
2094 assert(ret == cpu->kvm_msr_buf->nmsrs);
2095 return 0;
2099 static int kvm_get_fpu(X86CPU *cpu)
2101 CPUX86State *env = &cpu->env;
2102 struct kvm_fpu fpu;
2103 int i, ret;
2105 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
2106 if (ret < 0) {
2107 return ret;
2110 env->fpstt = (fpu.fsw >> 11) & 7;
2111 env->fpus = fpu.fsw;
2112 env->fpuc = fpu.fcw;
2113 env->fpop = fpu.last_opcode;
2114 env->fpip = fpu.last_ip;
2115 env->fpdp = fpu.last_dp;
2116 for (i = 0; i < 8; ++i) {
2117 env->fptags[i] = !((fpu.ftwx >> i) & 1);
2119 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
2120 for (i = 0; i < CPU_NB_REGS; i++) {
2121 env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
2122 env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
2124 env->mxcsr = fpu.mxcsr;
2126 return 0;
2129 static int kvm_get_xsave(X86CPU *cpu)
2131 CPUX86State *env = &cpu->env;
2132 X86XSaveArea *xsave = env->xsave_buf;
2133 int ret;
2135 if (!has_xsave) {
2136 return kvm_get_fpu(cpu);
2139 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
2140 if (ret < 0) {
2141 return ret;
2143 x86_cpu_xrstor_all_areas(cpu, xsave);
2145 return 0;
2148 static int kvm_get_xcrs(X86CPU *cpu)
2150 CPUX86State *env = &cpu->env;
2151 int i, ret;
2152 struct kvm_xcrs xcrs;
2154 if (!has_xcrs) {
2155 return 0;
2158 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
2159 if (ret < 0) {
2160 return ret;
2163 for (i = 0; i < xcrs.nr_xcrs; i++) {
2164 /* Only support xcr0 now */
2165 if (xcrs.xcrs[i].xcr == 0) {
2166 env->xcr0 = xcrs.xcrs[i].value;
2167 break;
2170 return 0;
2173 static int kvm_get_sregs(X86CPU *cpu)
2175 CPUX86State *env = &cpu->env;
2176 struct kvm_sregs sregs;
2177 int bit, i, ret;
2179 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
2180 if (ret < 0) {
2181 return ret;
2184 /* There can only be one pending IRQ set in the bitmap at a time, so try
2185 to find it and save its number instead (-1 for none). */
2186 env->interrupt_injected = -1;
2187 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
2188 if (sregs.interrupt_bitmap[i]) {
2189 bit = ctz64(sregs.interrupt_bitmap[i]);
2190 env->interrupt_injected = i * 64 + bit;
2191 break;
2195 get_seg(&env->segs[R_CS], &sregs.cs);
2196 get_seg(&env->segs[R_DS], &sregs.ds);
2197 get_seg(&env->segs[R_ES], &sregs.es);
2198 get_seg(&env->segs[R_FS], &sregs.fs);
2199 get_seg(&env->segs[R_GS], &sregs.gs);
2200 get_seg(&env->segs[R_SS], &sregs.ss);
2202 get_seg(&env->tr, &sregs.tr);
2203 get_seg(&env->ldt, &sregs.ldt);
2205 env->idt.limit = sregs.idt.limit;
2206 env->idt.base = sregs.idt.base;
2207 env->gdt.limit = sregs.gdt.limit;
2208 env->gdt.base = sregs.gdt.base;
2210 env->cr[0] = sregs.cr0;
2211 env->cr[2] = sregs.cr2;
2212 env->cr[3] = sregs.cr3;
2213 env->cr[4] = sregs.cr4;
2215 env->efer = sregs.efer;
2217 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
2218 x86_update_hflags(env);
2220 return 0;
2223 static int kvm_get_msrs(X86CPU *cpu)
2225 CPUX86State *env = &cpu->env;
2226 struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
2227 int ret, i;
2228 uint64_t mtrr_top_bits;
2230 kvm_msr_buf_reset(cpu);
2232 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
2233 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
2234 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
2235 kvm_msr_entry_add(cpu, MSR_PAT, 0);
2236 if (has_msr_star) {
2237 kvm_msr_entry_add(cpu, MSR_STAR, 0);
2239 if (has_msr_hsave_pa) {
2240 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
2242 if (has_msr_tsc_aux) {
2243 kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
2245 if (has_msr_tsc_adjust) {
2246 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
2248 if (has_msr_tsc_deadline) {
2249 kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
2251 if (has_msr_misc_enable) {
2252 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
2254 if (has_msr_smbase) {
2255 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
2257 if (has_msr_smi_count) {
2258 kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
2260 if (has_msr_feature_control) {
2261 kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
2263 if (has_msr_bndcfgs) {
2264 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
2266 if (has_msr_xss) {
2267 kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
2269 if (has_msr_spec_ctrl) {
2270 kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
2272 if (has_msr_virt_ssbd) {
2273 kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, 0);
2275 if (!env->tsc_valid) {
2276 kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
2277 env->tsc_valid = !runstate_is_running();
2280 #ifdef TARGET_X86_64
2281 if (lm_capable_kernel) {
2282 kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
2283 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
2284 kvm_msr_entry_add(cpu, MSR_FMASK, 0);
2285 kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
2287 #endif
2288 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
2289 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
2290 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
2291 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
2293 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
2294 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
2296 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
2297 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
2299 if (has_architectural_pmu_version > 0) {
2300 if (has_architectural_pmu_version > 1) {
2301 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
2302 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
2303 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
2304 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
2306 for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
2307 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
2309 for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
2310 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
2311 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
2315 if (env->mcg_cap) {
2316 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
2317 kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
2318 if (has_msr_mcg_ext_ctl) {
2319 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
2321 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
2322 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
2326 if (has_msr_hv_hypercall) {
2327 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
2328 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
2330 if (cpu->hyperv_vapic) {
2331 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
2333 if (cpu->hyperv_time) {
2334 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
2336 if (cpu->hyperv_reenlightenment) {
2337 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL, 0);
2338 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL, 0);
2339 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS, 0);
2341 if (has_msr_hv_crash) {
2342 int j;
2344 for (j = 0; j < HV_CRASH_PARAMS; j++) {
2345 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
2348 if (has_msr_hv_runtime) {
2349 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
2351 if (cpu->hyperv_synic) {
2352 uint32_t msr;
2354 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
2355 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
2356 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
2357 for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
2358 kvm_msr_entry_add(cpu, msr, 0);
2361 if (has_msr_hv_stimer) {
2362 uint32_t msr;
2364 for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
2365 msr++) {
2366 kvm_msr_entry_add(cpu, msr, 0);
2369 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
2370 kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
2371 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
2372 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
2373 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
2374 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
2375 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
2376 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
2377 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
2378 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
2379 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
2380 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
2381 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
2382 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
2383 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
2384 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
2388 if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
2389 int addr_num =
2390 kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
2392 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
2393 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
2394 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
2395 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
2396 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
2397 for (i = 0; i < addr_num; i++) {
2398 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
2402 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
2403 if (ret < 0) {
2404 return ret;
2407 if (ret < cpu->kvm_msr_buf->nmsrs) {
2408 struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
2409 error_report("error: failed to get MSR 0x%" PRIx32,
2410 (uint32_t)e->index);
2413 assert(ret == cpu->kvm_msr_buf->nmsrs);
2415 * MTRR masks: Each mask consists of 5 parts
2416 * a 10..0: must be zero
2417 * b 11 : valid bit
2418 * c n-1.12: actual mask bits
2419 * d 51..n: reserved must be zero
2420 * e 63.52: reserved must be zero
2422 * 'n' is the number of physical bits supported by the CPU and is
2423 * apparently always <= 52. We know our 'n' but don't know what
2424 * the destinations 'n' is; it might be smaller, in which case
2425 * it masks (c) on loading. It might be larger, in which case
2426 * we fill 'd' so that d..c is consistent irrespetive of the 'n'
2427 * we're migrating to.
2430 if (cpu->fill_mtrr_mask) {
2431 QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
2432 assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
2433 mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
2434 } else {
2435 mtrr_top_bits = 0;
2438 for (i = 0; i < ret; i++) {
2439 uint32_t index = msrs[i].index;
2440 switch (index) {
2441 case MSR_IA32_SYSENTER_CS:
2442 env->sysenter_cs = msrs[i].data;
2443 break;
2444 case MSR_IA32_SYSENTER_ESP:
2445 env->sysenter_esp = msrs[i].data;
2446 break;
2447 case MSR_IA32_SYSENTER_EIP:
2448 env->sysenter_eip = msrs[i].data;
2449 break;
2450 case MSR_PAT:
2451 env->pat = msrs[i].data;
2452 break;
2453 case MSR_STAR:
2454 env->star = msrs[i].data;
2455 break;
2456 #ifdef TARGET_X86_64
2457 case MSR_CSTAR:
2458 env->cstar = msrs[i].data;
2459 break;
2460 case MSR_KERNELGSBASE:
2461 env->kernelgsbase = msrs[i].data;
2462 break;
2463 case MSR_FMASK:
2464 env->fmask = msrs[i].data;
2465 break;
2466 case MSR_LSTAR:
2467 env->lstar = msrs[i].data;
2468 break;
2469 #endif
2470 case MSR_IA32_TSC:
2471 env->tsc = msrs[i].data;
2472 break;
2473 case MSR_TSC_AUX:
2474 env->tsc_aux = msrs[i].data;
2475 break;
2476 case MSR_TSC_ADJUST:
2477 env->tsc_adjust = msrs[i].data;
2478 break;
2479 case MSR_IA32_TSCDEADLINE:
2480 env->tsc_deadline = msrs[i].data;
2481 break;
2482 case MSR_VM_HSAVE_PA:
2483 env->vm_hsave = msrs[i].data;
2484 break;
2485 case MSR_KVM_SYSTEM_TIME:
2486 env->system_time_msr = msrs[i].data;
2487 break;
2488 case MSR_KVM_WALL_CLOCK:
2489 env->wall_clock_msr = msrs[i].data;
2490 break;
2491 case MSR_MCG_STATUS:
2492 env->mcg_status = msrs[i].data;
2493 break;
2494 case MSR_MCG_CTL:
2495 env->mcg_ctl = msrs[i].data;
2496 break;
2497 case MSR_MCG_EXT_CTL:
2498 env->mcg_ext_ctl = msrs[i].data;
2499 break;
2500 case MSR_IA32_MISC_ENABLE:
2501 env->msr_ia32_misc_enable = msrs[i].data;
2502 break;
2503 case MSR_IA32_SMBASE:
2504 env->smbase = msrs[i].data;
2505 break;
2506 case MSR_SMI_COUNT:
2507 env->msr_smi_count = msrs[i].data;
2508 break;
2509 case MSR_IA32_FEATURE_CONTROL:
2510 env->msr_ia32_feature_control = msrs[i].data;
2511 break;
2512 case MSR_IA32_BNDCFGS:
2513 env->msr_bndcfgs = msrs[i].data;
2514 break;
2515 case MSR_IA32_XSS:
2516 env->xss = msrs[i].data;
2517 break;
2518 default:
2519 if (msrs[i].index >= MSR_MC0_CTL &&
2520 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
2521 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
2523 break;
2524 case MSR_KVM_ASYNC_PF_EN:
2525 env->async_pf_en_msr = msrs[i].data;
2526 break;
2527 case MSR_KVM_PV_EOI_EN:
2528 env->pv_eoi_en_msr = msrs[i].data;
2529 break;
2530 case MSR_KVM_STEAL_TIME:
2531 env->steal_time_msr = msrs[i].data;
2532 break;
2533 case MSR_CORE_PERF_FIXED_CTR_CTRL:
2534 env->msr_fixed_ctr_ctrl = msrs[i].data;
2535 break;
2536 case MSR_CORE_PERF_GLOBAL_CTRL:
2537 env->msr_global_ctrl = msrs[i].data;
2538 break;
2539 case MSR_CORE_PERF_GLOBAL_STATUS:
2540 env->msr_global_status = msrs[i].data;
2541 break;
2542 case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
2543 env->msr_global_ovf_ctrl = msrs[i].data;
2544 break;
2545 case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
2546 env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
2547 break;
2548 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
2549 env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
2550 break;
2551 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
2552 env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
2553 break;
2554 case HV_X64_MSR_HYPERCALL:
2555 env->msr_hv_hypercall = msrs[i].data;
2556 break;
2557 case HV_X64_MSR_GUEST_OS_ID:
2558 env->msr_hv_guest_os_id = msrs[i].data;
2559 break;
2560 case HV_X64_MSR_APIC_ASSIST_PAGE:
2561 env->msr_hv_vapic = msrs[i].data;
2562 break;
2563 case HV_X64_MSR_REFERENCE_TSC:
2564 env->msr_hv_tsc = msrs[i].data;
2565 break;
2566 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2567 env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
2568 break;
2569 case HV_X64_MSR_VP_RUNTIME:
2570 env->msr_hv_runtime = msrs[i].data;
2571 break;
2572 case HV_X64_MSR_SCONTROL:
2573 env->msr_hv_synic_control = msrs[i].data;
2574 break;
2575 case HV_X64_MSR_SIEFP:
2576 env->msr_hv_synic_evt_page = msrs[i].data;
2577 break;
2578 case HV_X64_MSR_SIMP:
2579 env->msr_hv_synic_msg_page = msrs[i].data;
2580 break;
2581 case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
2582 env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
2583 break;
2584 case HV_X64_MSR_STIMER0_CONFIG:
2585 case HV_X64_MSR_STIMER1_CONFIG:
2586 case HV_X64_MSR_STIMER2_CONFIG:
2587 case HV_X64_MSR_STIMER3_CONFIG:
2588 env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
2589 msrs[i].data;
2590 break;
2591 case HV_X64_MSR_STIMER0_COUNT:
2592 case HV_X64_MSR_STIMER1_COUNT:
2593 case HV_X64_MSR_STIMER2_COUNT:
2594 case HV_X64_MSR_STIMER3_COUNT:
2595 env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
2596 msrs[i].data;
2597 break;
2598 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2599 env->msr_hv_reenlightenment_control = msrs[i].data;
2600 break;
2601 case HV_X64_MSR_TSC_EMULATION_CONTROL:
2602 env->msr_hv_tsc_emulation_control = msrs[i].data;
2603 break;
2604 case HV_X64_MSR_TSC_EMULATION_STATUS:
2605 env->msr_hv_tsc_emulation_status = msrs[i].data;
2606 break;
2607 case MSR_MTRRdefType:
2608 env->mtrr_deftype = msrs[i].data;
2609 break;
2610 case MSR_MTRRfix64K_00000:
2611 env->mtrr_fixed[0] = msrs[i].data;
2612 break;
2613 case MSR_MTRRfix16K_80000:
2614 env->mtrr_fixed[1] = msrs[i].data;
2615 break;
2616 case MSR_MTRRfix16K_A0000:
2617 env->mtrr_fixed[2] = msrs[i].data;
2618 break;
2619 case MSR_MTRRfix4K_C0000:
2620 env->mtrr_fixed[3] = msrs[i].data;
2621 break;
2622 case MSR_MTRRfix4K_C8000:
2623 env->mtrr_fixed[4] = msrs[i].data;
2624 break;
2625 case MSR_MTRRfix4K_D0000:
2626 env->mtrr_fixed[5] = msrs[i].data;
2627 break;
2628 case MSR_MTRRfix4K_D8000:
2629 env->mtrr_fixed[6] = msrs[i].data;
2630 break;
2631 case MSR_MTRRfix4K_E0000:
2632 env->mtrr_fixed[7] = msrs[i].data;
2633 break;
2634 case MSR_MTRRfix4K_E8000:
2635 env->mtrr_fixed[8] = msrs[i].data;
2636 break;
2637 case MSR_MTRRfix4K_F0000:
2638 env->mtrr_fixed[9] = msrs[i].data;
2639 break;
2640 case MSR_MTRRfix4K_F8000:
2641 env->mtrr_fixed[10] = msrs[i].data;
2642 break;
2643 case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
2644 if (index & 1) {
2645 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
2646 mtrr_top_bits;
2647 } else {
2648 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
2650 break;
2651 case MSR_IA32_SPEC_CTRL:
2652 env->spec_ctrl = msrs[i].data;
2653 break;
2654 case MSR_VIRT_SSBD:
2655 env->virt_ssbd = msrs[i].data;
2656 break;
2657 case MSR_IA32_RTIT_CTL:
2658 env->msr_rtit_ctrl = msrs[i].data;
2659 break;
2660 case MSR_IA32_RTIT_STATUS:
2661 env->msr_rtit_status = msrs[i].data;
2662 break;
2663 case MSR_IA32_RTIT_OUTPUT_BASE:
2664 env->msr_rtit_output_base = msrs[i].data;
2665 break;
2666 case MSR_IA32_RTIT_OUTPUT_MASK:
2667 env->msr_rtit_output_mask = msrs[i].data;
2668 break;
2669 case MSR_IA32_RTIT_CR3_MATCH:
2670 env->msr_rtit_cr3_match = msrs[i].data;
2671 break;
2672 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2673 env->msr_rtit_addrs[index - MSR_IA32_RTIT_ADDR0_A] = msrs[i].data;
2674 break;
2678 return 0;
2681 static int kvm_put_mp_state(X86CPU *cpu)
2683 struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
2685 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
2688 static int kvm_get_mp_state(X86CPU *cpu)
2690 CPUState *cs = CPU(cpu);
2691 CPUX86State *env = &cpu->env;
2692 struct kvm_mp_state mp_state;
2693 int ret;
2695 ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
2696 if (ret < 0) {
2697 return ret;
2699 env->mp_state = mp_state.mp_state;
2700 if (kvm_irqchip_in_kernel()) {
2701 cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
2703 return 0;
2706 static int kvm_get_apic(X86CPU *cpu)
2708 DeviceState *apic = cpu->apic_state;
2709 struct kvm_lapic_state kapic;
2710 int ret;
2712 if (apic && kvm_irqchip_in_kernel()) {
2713 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
2714 if (ret < 0) {
2715 return ret;
2718 kvm_get_apic_state(apic, &kapic);
2720 return 0;
2723 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
2725 CPUState *cs = CPU(cpu);
2726 CPUX86State *env = &cpu->env;
2727 struct kvm_vcpu_events events = {};
2729 if (!kvm_has_vcpu_events()) {
2730 return 0;
2733 events.exception.injected = (env->exception_injected >= 0);
2734 events.exception.nr = env->exception_injected;
2735 events.exception.has_error_code = env->has_error_code;
2736 events.exception.error_code = env->error_code;
2738 events.interrupt.injected = (env->interrupt_injected >= 0);
2739 events.interrupt.nr = env->interrupt_injected;
2740 events.interrupt.soft = env->soft_interrupt;
2742 events.nmi.injected = env->nmi_injected;
2743 events.nmi.pending = env->nmi_pending;
2744 events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
2746 events.sipi_vector = env->sipi_vector;
2747 events.flags = 0;
2749 if (has_msr_smbase) {
2750 events.smi.smm = !!(env->hflags & HF_SMM_MASK);
2751 events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
2752 if (kvm_irqchip_in_kernel()) {
2753 /* As soon as these are moved to the kernel, remove them
2754 * from cs->interrupt_request.
2756 events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
2757 events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
2758 cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
2759 } else {
2760 /* Keep these in cs->interrupt_request. */
2761 events.smi.pending = 0;
2762 events.smi.latched_init = 0;
2764 /* Stop SMI delivery on old machine types to avoid a reboot
2765 * on an inward migration of an old VM.
2767 if (!cpu->kvm_no_smi_migration) {
2768 events.flags |= KVM_VCPUEVENT_VALID_SMM;
2772 if (level >= KVM_PUT_RESET_STATE) {
2773 events.flags |= KVM_VCPUEVENT_VALID_NMI_PENDING;
2774 if (env->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
2775 events.flags |= KVM_VCPUEVENT_VALID_SIPI_VECTOR;
2779 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
2782 static int kvm_get_vcpu_events(X86CPU *cpu)
2784 CPUX86State *env = &cpu->env;
2785 struct kvm_vcpu_events events;
2786 int ret;
2788 if (!kvm_has_vcpu_events()) {
2789 return 0;
2792 memset(&events, 0, sizeof(events));
2793 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
2794 if (ret < 0) {
2795 return ret;
2797 env->exception_injected =
2798 events.exception.injected ? events.exception.nr : -1;
2799 env->has_error_code = events.exception.has_error_code;
2800 env->error_code = events.exception.error_code;
2802 env->interrupt_injected =
2803 events.interrupt.injected ? events.interrupt.nr : -1;
2804 env->soft_interrupt = events.interrupt.soft;
2806 env->nmi_injected = events.nmi.injected;
2807 env->nmi_pending = events.nmi.pending;
2808 if (events.nmi.masked) {
2809 env->hflags2 |= HF2_NMI_MASK;
2810 } else {
2811 env->hflags2 &= ~HF2_NMI_MASK;
2814 if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
2815 if (events.smi.smm) {
2816 env->hflags |= HF_SMM_MASK;
2817 } else {
2818 env->hflags &= ~HF_SMM_MASK;
2820 if (events.smi.pending) {
2821 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2822 } else {
2823 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2825 if (events.smi.smm_inside_nmi) {
2826 env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
2827 } else {
2828 env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
2830 if (events.smi.latched_init) {
2831 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2832 } else {
2833 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2837 env->sipi_vector = events.sipi_vector;
2839 return 0;
2842 static int kvm_guest_debug_workarounds(X86CPU *cpu)
2844 CPUState *cs = CPU(cpu);
2845 CPUX86State *env = &cpu->env;
2846 int ret = 0;
2847 unsigned long reinject_trap = 0;
2849 if (!kvm_has_vcpu_events()) {
2850 if (env->exception_injected == 1) {
2851 reinject_trap = KVM_GUESTDBG_INJECT_DB;
2852 } else if (env->exception_injected == 3) {
2853 reinject_trap = KVM_GUESTDBG_INJECT_BP;
2855 env->exception_injected = -1;
2859 * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
2860 * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
2861 * by updating the debug state once again if single-stepping is on.
2862 * Another reason to call kvm_update_guest_debug here is a pending debug
2863 * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
2864 * reinject them via SET_GUEST_DEBUG.
2866 if (reinject_trap ||
2867 (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
2868 ret = kvm_update_guest_debug(cs, reinject_trap);
2870 return ret;
2873 static int kvm_put_debugregs(X86CPU *cpu)
2875 CPUX86State *env = &cpu->env;
2876 struct kvm_debugregs dbgregs;
2877 int i;
2879 if (!kvm_has_debugregs()) {
2880 return 0;
2883 for (i = 0; i < 4; i++) {
2884 dbgregs.db[i] = env->dr[i];
2886 dbgregs.dr6 = env->dr[6];
2887 dbgregs.dr7 = env->dr[7];
2888 dbgregs.flags = 0;
2890 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
2893 static int kvm_get_debugregs(X86CPU *cpu)
2895 CPUX86State *env = &cpu->env;
2896 struct kvm_debugregs dbgregs;
2897 int i, ret;
2899 if (!kvm_has_debugregs()) {
2900 return 0;
2903 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
2904 if (ret < 0) {
2905 return ret;
2907 for (i = 0; i < 4; i++) {
2908 env->dr[i] = dbgregs.db[i];
2910 env->dr[4] = env->dr[6] = dbgregs.dr6;
2911 env->dr[5] = env->dr[7] = dbgregs.dr7;
2913 return 0;
2916 int kvm_arch_put_registers(CPUState *cpu, int level)
2918 X86CPU *x86_cpu = X86_CPU(cpu);
2919 int ret;
2921 assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
2923 if (level >= KVM_PUT_RESET_STATE) {
2924 ret = kvm_put_msr_feature_control(x86_cpu);
2925 if (ret < 0) {
2926 return ret;
2930 if (level == KVM_PUT_FULL_STATE) {
2931 /* We don't check for kvm_arch_set_tsc_khz() errors here,
2932 * because TSC frequency mismatch shouldn't abort migration,
2933 * unless the user explicitly asked for a more strict TSC
2934 * setting (e.g. using an explicit "tsc-freq" option).
2936 kvm_arch_set_tsc_khz(cpu);
2939 ret = kvm_getput_regs(x86_cpu, 1);
2940 if (ret < 0) {
2941 return ret;
2943 ret = kvm_put_xsave(x86_cpu);
2944 if (ret < 0) {
2945 return ret;
2947 ret = kvm_put_xcrs(x86_cpu);
2948 if (ret < 0) {
2949 return ret;
2951 ret = kvm_put_sregs(x86_cpu);
2952 if (ret < 0) {
2953 return ret;
2955 /* must be before kvm_put_msrs */
2956 ret = kvm_inject_mce_oldstyle(x86_cpu);
2957 if (ret < 0) {
2958 return ret;
2960 ret = kvm_put_msrs(x86_cpu, level);
2961 if (ret < 0) {
2962 return ret;
2964 ret = kvm_put_vcpu_events(x86_cpu, level);
2965 if (ret < 0) {
2966 return ret;
2968 if (level >= KVM_PUT_RESET_STATE) {
2969 ret = kvm_put_mp_state(x86_cpu);
2970 if (ret < 0) {
2971 return ret;
2975 ret = kvm_put_tscdeadline_msr(x86_cpu);
2976 if (ret < 0) {
2977 return ret;
2979 ret = kvm_put_debugregs(x86_cpu);
2980 if (ret < 0) {
2981 return ret;
2983 /* must be last */
2984 ret = kvm_guest_debug_workarounds(x86_cpu);
2985 if (ret < 0) {
2986 return ret;
2988 return 0;
2991 int kvm_arch_get_registers(CPUState *cs)
2993 X86CPU *cpu = X86_CPU(cs);
2994 int ret;
2996 assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
2998 ret = kvm_get_vcpu_events(cpu);
2999 if (ret < 0) {
3000 goto out;
3003 * KVM_GET_MPSTATE can modify CS and RIP, call it before
3004 * KVM_GET_REGS and KVM_GET_SREGS.
3006 ret = kvm_get_mp_state(cpu);
3007 if (ret < 0) {
3008 goto out;
3010 ret = kvm_getput_regs(cpu, 0);
3011 if (ret < 0) {
3012 goto out;
3014 ret = kvm_get_xsave(cpu);
3015 if (ret < 0) {
3016 goto out;
3018 ret = kvm_get_xcrs(cpu);
3019 if (ret < 0) {
3020 goto out;
3022 ret = kvm_get_sregs(cpu);
3023 if (ret < 0) {
3024 goto out;
3026 ret = kvm_get_msrs(cpu);
3027 if (ret < 0) {
3028 goto out;
3030 ret = kvm_get_apic(cpu);
3031 if (ret < 0) {
3032 goto out;
3034 ret = kvm_get_debugregs(cpu);
3035 if (ret < 0) {
3036 goto out;
3038 ret = 0;
3039 out:
3040 cpu_sync_bndcs_hflags(&cpu->env);
3041 return ret;
3044 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
3046 X86CPU *x86_cpu = X86_CPU(cpu);
3047 CPUX86State *env = &x86_cpu->env;
3048 int ret;
3050 /* Inject NMI */
3051 if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
3052 if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
3053 qemu_mutex_lock_iothread();
3054 cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
3055 qemu_mutex_unlock_iothread();
3056 DPRINTF("injected NMI\n");
3057 ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
3058 if (ret < 0) {
3059 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
3060 strerror(-ret));
3063 if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
3064 qemu_mutex_lock_iothread();
3065 cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
3066 qemu_mutex_unlock_iothread();
3067 DPRINTF("injected SMI\n");
3068 ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
3069 if (ret < 0) {
3070 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
3071 strerror(-ret));
3076 if (!kvm_pic_in_kernel()) {
3077 qemu_mutex_lock_iothread();
3080 /* Force the VCPU out of its inner loop to process any INIT requests
3081 * or (for userspace APIC, but it is cheap to combine the checks here)
3082 * pending TPR access reports.
3084 if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
3085 if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
3086 !(env->hflags & HF_SMM_MASK)) {
3087 cpu->exit_request = 1;
3089 if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
3090 cpu->exit_request = 1;
3094 if (!kvm_pic_in_kernel()) {
3095 /* Try to inject an interrupt if the guest can accept it */
3096 if (run->ready_for_interrupt_injection &&
3097 (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
3098 (env->eflags & IF_MASK)) {
3099 int irq;
3101 cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
3102 irq = cpu_get_pic_interrupt(env);
3103 if (irq >= 0) {
3104 struct kvm_interrupt intr;
3106 intr.irq = irq;
3107 DPRINTF("injected interrupt %d\n", irq);
3108 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
3109 if (ret < 0) {
3110 fprintf(stderr,
3111 "KVM: injection failed, interrupt lost (%s)\n",
3112 strerror(-ret));
3117 /* If we have an interrupt but the guest is not ready to receive an
3118 * interrupt, request an interrupt window exit. This will
3119 * cause a return to userspace as soon as the guest is ready to
3120 * receive interrupts. */
3121 if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
3122 run->request_interrupt_window = 1;
3123 } else {
3124 run->request_interrupt_window = 0;
3127 DPRINTF("setting tpr\n");
3128 run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
3130 qemu_mutex_unlock_iothread();
3134 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
3136 X86CPU *x86_cpu = X86_CPU(cpu);
3137 CPUX86State *env = &x86_cpu->env;
3139 if (run->flags & KVM_RUN_X86_SMM) {
3140 env->hflags |= HF_SMM_MASK;
3141 } else {
3142 env->hflags &= ~HF_SMM_MASK;
3144 if (run->if_flag) {
3145 env->eflags |= IF_MASK;
3146 } else {
3147 env->eflags &= ~IF_MASK;
3150 /* We need to protect the apic state against concurrent accesses from
3151 * different threads in case the userspace irqchip is used. */
3152 if (!kvm_irqchip_in_kernel()) {
3153 qemu_mutex_lock_iothread();
3155 cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
3156 cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
3157 if (!kvm_irqchip_in_kernel()) {
3158 qemu_mutex_unlock_iothread();
3160 return cpu_get_mem_attrs(env);
3163 int kvm_arch_process_async_events(CPUState *cs)
3165 X86CPU *cpu = X86_CPU(cs);
3166 CPUX86State *env = &cpu->env;
3168 if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
3169 /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
3170 assert(env->mcg_cap);
3172 cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
3174 kvm_cpu_synchronize_state(cs);
3176 if (env->exception_injected == EXCP08_DBLE) {
3177 /* this means triple fault */
3178 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
3179 cs->exit_request = 1;
3180 return 0;
3182 env->exception_injected = EXCP12_MCHK;
3183 env->has_error_code = 0;
3185 cs->halted = 0;
3186 if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
3187 env->mp_state = KVM_MP_STATE_RUNNABLE;
3191 if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
3192 !(env->hflags & HF_SMM_MASK)) {
3193 kvm_cpu_synchronize_state(cs);
3194 do_cpu_init(cpu);
3197 if (kvm_irqchip_in_kernel()) {
3198 return 0;
3201 if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
3202 cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
3203 apic_poll_irq(cpu->apic_state);
3205 if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
3206 (env->eflags & IF_MASK)) ||
3207 (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
3208 cs->halted = 0;
3210 if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
3211 kvm_cpu_synchronize_state(cs);
3212 do_cpu_sipi(cpu);
3214 if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
3215 cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
3216 kvm_cpu_synchronize_state(cs);
3217 apic_handle_tpr_access_report(cpu->apic_state, env->eip,
3218 env->tpr_access_type);
3221 return cs->halted;
3224 static int kvm_handle_halt(X86CPU *cpu)
3226 CPUState *cs = CPU(cpu);
3227 CPUX86State *env = &cpu->env;
3229 if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
3230 (env->eflags & IF_MASK)) &&
3231 !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
3232 cs->halted = 1;
3233 return EXCP_HLT;
3236 return 0;
3239 static int kvm_handle_tpr_access(X86CPU *cpu)
3241 CPUState *cs = CPU(cpu);
3242 struct kvm_run *run = cs->kvm_run;
3244 apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
3245 run->tpr_access.is_write ? TPR_ACCESS_WRITE
3246 : TPR_ACCESS_READ);
3247 return 1;
3250 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
3252 static const uint8_t int3 = 0xcc;
3254 if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
3255 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
3256 return -EINVAL;
3258 return 0;
3261 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
3263 uint8_t int3;
3265 if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
3266 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
3267 return -EINVAL;
3269 return 0;
3272 static struct {
3273 target_ulong addr;
3274 int len;
3275 int type;
3276 } hw_breakpoint[4];
3278 static int nb_hw_breakpoint;
3280 static int find_hw_breakpoint(target_ulong addr, int len, int type)
3282 int n;
3284 for (n = 0; n < nb_hw_breakpoint; n++) {
3285 if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
3286 (hw_breakpoint[n].len == len || len == -1)) {
3287 return n;
3290 return -1;
3293 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
3294 target_ulong len, int type)
3296 switch (type) {
3297 case GDB_BREAKPOINT_HW:
3298 len = 1;
3299 break;
3300 case GDB_WATCHPOINT_WRITE:
3301 case GDB_WATCHPOINT_ACCESS:
3302 switch (len) {
3303 case 1:
3304 break;
3305 case 2:
3306 case 4:
3307 case 8:
3308 if (addr & (len - 1)) {
3309 return -EINVAL;
3311 break;
3312 default:
3313 return -EINVAL;
3315 break;
3316 default:
3317 return -ENOSYS;
3320 if (nb_hw_breakpoint == 4) {
3321 return -ENOBUFS;
3323 if (find_hw_breakpoint(addr, len, type) >= 0) {
3324 return -EEXIST;
3326 hw_breakpoint[nb_hw_breakpoint].addr = addr;
3327 hw_breakpoint[nb_hw_breakpoint].len = len;
3328 hw_breakpoint[nb_hw_breakpoint].type = type;
3329 nb_hw_breakpoint++;
3331 return 0;
3334 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
3335 target_ulong len, int type)
3337 int n;
3339 n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
3340 if (n < 0) {
3341 return -ENOENT;
3343 nb_hw_breakpoint--;
3344 hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
3346 return 0;
3349 void kvm_arch_remove_all_hw_breakpoints(void)
3351 nb_hw_breakpoint = 0;
3354 static CPUWatchpoint hw_watchpoint;
3356 static int kvm_handle_debug(X86CPU *cpu,
3357 struct kvm_debug_exit_arch *arch_info)
3359 CPUState *cs = CPU(cpu);
3360 CPUX86State *env = &cpu->env;
3361 int ret = 0;
3362 int n;
3364 if (arch_info->exception == 1) {
3365 if (arch_info->dr6 & (1 << 14)) {
3366 if (cs->singlestep_enabled) {
3367 ret = EXCP_DEBUG;
3369 } else {
3370 for (n = 0; n < 4; n++) {
3371 if (arch_info->dr6 & (1 << n)) {
3372 switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
3373 case 0x0:
3374 ret = EXCP_DEBUG;
3375 break;
3376 case 0x1:
3377 ret = EXCP_DEBUG;
3378 cs->watchpoint_hit = &hw_watchpoint;
3379 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
3380 hw_watchpoint.flags = BP_MEM_WRITE;
3381 break;
3382 case 0x3:
3383 ret = EXCP_DEBUG;
3384 cs->watchpoint_hit = &hw_watchpoint;
3385 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
3386 hw_watchpoint.flags = BP_MEM_ACCESS;
3387 break;
3392 } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
3393 ret = EXCP_DEBUG;
3395 if (ret == 0) {
3396 cpu_synchronize_state(cs);
3397 assert(env->exception_injected == -1);
3399 /* pass to guest */
3400 env->exception_injected = arch_info->exception;
3401 env->has_error_code = 0;
3404 return ret;
3407 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
3409 const uint8_t type_code[] = {
3410 [GDB_BREAKPOINT_HW] = 0x0,
3411 [GDB_WATCHPOINT_WRITE] = 0x1,
3412 [GDB_WATCHPOINT_ACCESS] = 0x3
3414 const uint8_t len_code[] = {
3415 [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
3417 int n;
3419 if (kvm_sw_breakpoints_active(cpu)) {
3420 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
3422 if (nb_hw_breakpoint > 0) {
3423 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
3424 dbg->arch.debugreg[7] = 0x0600;
3425 for (n = 0; n < nb_hw_breakpoint; n++) {
3426 dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
3427 dbg->arch.debugreg[7] |= (2 << (n * 2)) |
3428 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
3429 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
3434 static bool host_supports_vmx(void)
3436 uint32_t ecx, unused;
3438 host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
3439 return ecx & CPUID_EXT_VMX;
3442 #define VMX_INVALID_GUEST_STATE 0x80000021
3444 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
3446 X86CPU *cpu = X86_CPU(cs);
3447 uint64_t code;
3448 int ret;
3450 switch (run->exit_reason) {
3451 case KVM_EXIT_HLT:
3452 DPRINTF("handle_hlt\n");
3453 qemu_mutex_lock_iothread();
3454 ret = kvm_handle_halt(cpu);
3455 qemu_mutex_unlock_iothread();
3456 break;
3457 case KVM_EXIT_SET_TPR:
3458 ret = 0;
3459 break;
3460 case KVM_EXIT_TPR_ACCESS:
3461 qemu_mutex_lock_iothread();
3462 ret = kvm_handle_tpr_access(cpu);
3463 qemu_mutex_unlock_iothread();
3464 break;
3465 case KVM_EXIT_FAIL_ENTRY:
3466 code = run->fail_entry.hardware_entry_failure_reason;
3467 fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
3468 code);
3469 if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
3470 fprintf(stderr,
3471 "\nIf you're running a guest on an Intel machine without "
3472 "unrestricted mode\n"
3473 "support, the failure can be most likely due to the guest "
3474 "entering an invalid\n"
3475 "state for Intel VT. For example, the guest maybe running "
3476 "in big real mode\n"
3477 "which is not supported on less recent Intel processors."
3478 "\n\n");
3480 ret = -1;
3481 break;
3482 case KVM_EXIT_EXCEPTION:
3483 fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
3484 run->ex.exception, run->ex.error_code);
3485 ret = -1;
3486 break;
3487 case KVM_EXIT_DEBUG:
3488 DPRINTF("kvm_exit_debug\n");
3489 qemu_mutex_lock_iothread();
3490 ret = kvm_handle_debug(cpu, &run->debug.arch);
3491 qemu_mutex_unlock_iothread();
3492 break;
3493 case KVM_EXIT_HYPERV:
3494 ret = kvm_hv_handle_exit(cpu, &run->hyperv);
3495 break;
3496 case KVM_EXIT_IOAPIC_EOI:
3497 ioapic_eoi_broadcast(run->eoi.vector);
3498 ret = 0;
3499 break;
3500 default:
3501 fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
3502 ret = -1;
3503 break;
3506 return ret;
3509 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
3511 X86CPU *cpu = X86_CPU(cs);
3512 CPUX86State *env = &cpu->env;
3514 kvm_cpu_synchronize_state(cs);
3515 return !(env->cr[0] & CR0_PE_MASK) ||
3516 ((env->segs[R_CS].selector & 3) != 3);
3519 void kvm_arch_init_irq_routing(KVMState *s)
3521 if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
3522 /* If kernel can't do irq routing, interrupt source
3523 * override 0->2 cannot be set up as required by HPET.
3524 * So we have to disable it.
3526 no_hpet = 1;
3528 /* We know at this point that we're using the in-kernel
3529 * irqchip, so we can use irqfds, and on x86 we know
3530 * we can use msi via irqfd and GSI routing.
3532 kvm_msi_via_irqfd_allowed = true;
3533 kvm_gsi_routing_allowed = true;
3535 if (kvm_irqchip_is_split()) {
3536 int i;
3538 /* If the ioapic is in QEMU and the lapics are in KVM, reserve
3539 MSI routes for signaling interrupts to the local apics. */
3540 for (i = 0; i < IOAPIC_NUM_PINS; i++) {
3541 if (kvm_irqchip_add_msi_route(s, 0, NULL) < 0) {
3542 error_report("Could not enable split IRQ mode.");
3543 exit(1);
3549 int kvm_arch_irqchip_create(MachineState *ms, KVMState *s)
3551 int ret;
3552 if (machine_kernel_irqchip_split(ms)) {
3553 ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
3554 if (ret) {
3555 error_report("Could not enable split irqchip mode: %s",
3556 strerror(-ret));
3557 exit(1);
3558 } else {
3559 DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
3560 kvm_split_irqchip = true;
3561 return 1;
3563 } else {
3564 return 0;
3568 /* Classic KVM device assignment interface. Will remain x86 only. */
3569 int kvm_device_pci_assign(KVMState *s, PCIHostDeviceAddress *dev_addr,
3570 uint32_t flags, uint32_t *dev_id)
3572 struct kvm_assigned_pci_dev dev_data = {
3573 .segnr = dev_addr->domain,
3574 .busnr = dev_addr->bus,
3575 .devfn = PCI_DEVFN(dev_addr->slot, dev_addr->function),
3576 .flags = flags,
3578 int ret;
3580 dev_data.assigned_dev_id =
3581 (dev_addr->domain << 16) | (dev_addr->bus << 8) | dev_data.devfn;
3583 ret = kvm_vm_ioctl(s, KVM_ASSIGN_PCI_DEVICE, &dev_data);
3584 if (ret < 0) {
3585 return ret;
3588 *dev_id = dev_data.assigned_dev_id;
3590 return 0;
3593 int kvm_device_pci_deassign(KVMState *s, uint32_t dev_id)
3595 struct kvm_assigned_pci_dev dev_data = {
3596 .assigned_dev_id = dev_id,
3599 return kvm_vm_ioctl(s, KVM_DEASSIGN_PCI_DEVICE, &dev_data);
3602 static int kvm_assign_irq_internal(KVMState *s, uint32_t dev_id,
3603 uint32_t irq_type, uint32_t guest_irq)
3605 struct kvm_assigned_irq assigned_irq = {
3606 .assigned_dev_id = dev_id,
3607 .guest_irq = guest_irq,
3608 .flags = irq_type,
3611 if (kvm_check_extension(s, KVM_CAP_ASSIGN_DEV_IRQ)) {
3612 return kvm_vm_ioctl(s, KVM_ASSIGN_DEV_IRQ, &assigned_irq);
3613 } else {
3614 return kvm_vm_ioctl(s, KVM_ASSIGN_IRQ, &assigned_irq);
3618 int kvm_device_intx_assign(KVMState *s, uint32_t dev_id, bool use_host_msi,
3619 uint32_t guest_irq)
3621 uint32_t irq_type = KVM_DEV_IRQ_GUEST_INTX |
3622 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX);
3624 return kvm_assign_irq_internal(s, dev_id, irq_type, guest_irq);
3627 int kvm_device_intx_set_mask(KVMState *s, uint32_t dev_id, bool masked)
3629 struct kvm_assigned_pci_dev dev_data = {
3630 .assigned_dev_id = dev_id,
3631 .flags = masked ? KVM_DEV_ASSIGN_MASK_INTX : 0,
3634 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_INTX_MASK, &dev_data);
3637 static int kvm_deassign_irq_internal(KVMState *s, uint32_t dev_id,
3638 uint32_t type)
3640 struct kvm_assigned_irq assigned_irq = {
3641 .assigned_dev_id = dev_id,
3642 .flags = type,
3645 return kvm_vm_ioctl(s, KVM_DEASSIGN_DEV_IRQ, &assigned_irq);
3648 int kvm_device_intx_deassign(KVMState *s, uint32_t dev_id, bool use_host_msi)
3650 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_INTX |
3651 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX));
3654 int kvm_device_msi_assign(KVMState *s, uint32_t dev_id, int virq)
3656 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSI |
3657 KVM_DEV_IRQ_GUEST_MSI, virq);
3660 int kvm_device_msi_deassign(KVMState *s, uint32_t dev_id)
3662 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSI |
3663 KVM_DEV_IRQ_HOST_MSI);
3666 bool kvm_device_msix_supported(KVMState *s)
3668 /* The kernel lacks a corresponding KVM_CAP, so we probe by calling
3669 * KVM_ASSIGN_SET_MSIX_NR with an invalid parameter. */
3670 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, NULL) == -EFAULT;
3673 int kvm_device_msix_init_vectors(KVMState *s, uint32_t dev_id,
3674 uint32_t nr_vectors)
3676 struct kvm_assigned_msix_nr msix_nr = {
3677 .assigned_dev_id = dev_id,
3678 .entry_nr = nr_vectors,
3681 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, &msix_nr);
3684 int kvm_device_msix_set_vector(KVMState *s, uint32_t dev_id, uint32_t vector,
3685 int virq)
3687 struct kvm_assigned_msix_entry msix_entry = {
3688 .assigned_dev_id = dev_id,
3689 .gsi = virq,
3690 .entry = vector,
3693 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_ENTRY, &msix_entry);
3696 int kvm_device_msix_assign(KVMState *s, uint32_t dev_id)
3698 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSIX |
3699 KVM_DEV_IRQ_GUEST_MSIX, 0);
3702 int kvm_device_msix_deassign(KVMState *s, uint32_t dev_id)
3704 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSIX |
3705 KVM_DEV_IRQ_HOST_MSIX);
3708 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
3709 uint64_t address, uint32_t data, PCIDevice *dev)
3711 X86IOMMUState *iommu = x86_iommu_get_default();
3713 if (iommu) {
3714 int ret;
3715 MSIMessage src, dst;
3716 X86IOMMUClass *class = X86_IOMMU_GET_CLASS(iommu);
3718 if (!class->int_remap) {
3719 return 0;
3722 src.address = route->u.msi.address_hi;
3723 src.address <<= VTD_MSI_ADDR_HI_SHIFT;
3724 src.address |= route->u.msi.address_lo;
3725 src.data = route->u.msi.data;
3727 ret = class->int_remap(iommu, &src, &dst, dev ? \
3728 pci_requester_id(dev) : \
3729 X86_IOMMU_SID_INVALID);
3730 if (ret) {
3731 trace_kvm_x86_fixup_msi_error(route->gsi);
3732 return 1;
3735 route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
3736 route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
3737 route->u.msi.data = dst.data;
3740 return 0;
3743 typedef struct MSIRouteEntry MSIRouteEntry;
3745 struct MSIRouteEntry {
3746 PCIDevice *dev; /* Device pointer */
3747 int vector; /* MSI/MSIX vector index */
3748 int virq; /* Virtual IRQ index */
3749 QLIST_ENTRY(MSIRouteEntry) list;
3752 /* List of used GSI routes */
3753 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
3754 QLIST_HEAD_INITIALIZER(msi_route_list);
3756 static void kvm_update_msi_routes_all(void *private, bool global,
3757 uint32_t index, uint32_t mask)
3759 int cnt = 0;
3760 MSIRouteEntry *entry;
3761 MSIMessage msg;
3762 PCIDevice *dev;
3764 /* TODO: explicit route update */
3765 QLIST_FOREACH(entry, &msi_route_list, list) {
3766 cnt++;
3767 dev = entry->dev;
3768 if (!msix_enabled(dev) && !msi_enabled(dev)) {
3769 continue;
3771 msg = pci_get_msi_message(dev, entry->vector);
3772 kvm_irqchip_update_msi_route(kvm_state, entry->virq, msg, dev);
3774 kvm_irqchip_commit_routes(kvm_state);
3775 trace_kvm_x86_update_msi_routes(cnt);
3778 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
3779 int vector, PCIDevice *dev)
3781 static bool notify_list_inited = false;
3782 MSIRouteEntry *entry;
3784 if (!dev) {
3785 /* These are (possibly) IOAPIC routes only used for split
3786 * kernel irqchip mode, while what we are housekeeping are
3787 * PCI devices only. */
3788 return 0;
3791 entry = g_new0(MSIRouteEntry, 1);
3792 entry->dev = dev;
3793 entry->vector = vector;
3794 entry->virq = route->gsi;
3795 QLIST_INSERT_HEAD(&msi_route_list, entry, list);
3797 trace_kvm_x86_add_msi_route(route->gsi);
3799 if (!notify_list_inited) {
3800 /* For the first time we do add route, add ourselves into
3801 * IOMMU's IEC notify list if needed. */
3802 X86IOMMUState *iommu = x86_iommu_get_default();
3803 if (iommu) {
3804 x86_iommu_iec_register_notifier(iommu,
3805 kvm_update_msi_routes_all,
3806 NULL);
3808 notify_list_inited = true;
3810 return 0;
3813 int kvm_arch_release_virq_post(int virq)
3815 MSIRouteEntry *entry, *next;
3816 QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
3817 if (entry->virq == virq) {
3818 trace_kvm_x86_remove_msi_route(virq);
3819 QLIST_REMOVE(entry, list);
3820 g_free(entry);
3821 break;
3824 return 0;
3827 int kvm_arch_msi_data_to_gsi(uint32_t data)
3829 abort();