4 * Copyright (C) 2006-2008 Qumranet Technologies
5 * Copyright IBM, Corp. 2008
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 <sys/types.h>
16 #include <sys/ioctl.h>
18 #include <sys/utsname.h>
20 #include <linux/kvm.h>
21 #include <linux/kvm_para.h>
23 #include "qemu-common.h"
29 #include "host-utils.h"
39 #define DPRINTF(fmt, ...) \
40 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
42 #define DPRINTF(fmt, ...) \
46 #define MSR_KVM_WALL_CLOCK 0x11
47 #define MSR_KVM_SYSTEM_TIME 0x12
50 #define BUS_MCEERR_AR 4
53 #define BUS_MCEERR_AO 5
56 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
57 KVM_CAP_INFO(SET_TSS_ADDR),
58 KVM_CAP_INFO(EXT_CPUID),
59 KVM_CAP_INFO(MP_STATE),
63 static bool has_msr_star;
64 static bool has_msr_hsave_pa;
65 static bool has_msr_tsc_deadline;
66 static bool has_msr_async_pf_en;
67 static bool has_msr_pv_eoi_en;
68 static bool has_msr_misc_enable;
69 static int lm_capable_kernel;
71 bool kvm_allows_irq0_override(void)
73 return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
76 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
78 struct kvm_cpuid2 *cpuid;
81 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
82 cpuid = (struct kvm_cpuid2 *)g_malloc0(size);
84 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
85 if (r == 0 && cpuid->nent >= max) {
93 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
101 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
104 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
106 struct kvm_cpuid2 *cpuid;
108 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
114 struct kvm_para_features {
117 } para_features[] = {
118 { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
119 { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
120 { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
121 { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
125 static int get_para_features(KVMState *s)
129 for (i = 0; i < ARRAY_SIZE(para_features) - 1; i++) {
130 if (kvm_check_extension(s, para_features[i].cap)) {
131 features |= (1 << para_features[i].feature);
139 /* Returns the value for a specific register on the cpuid entry
141 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
161 /* Find matching entry for function/index on kvm_cpuid2 struct
163 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
168 for (i = 0; i < cpuid->nent; ++i) {
169 if (cpuid->entries[i].function == function &&
170 cpuid->entries[i].index == index) {
171 return &cpuid->entries[i];
178 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
179 uint32_t index, int reg)
181 struct kvm_cpuid2 *cpuid;
183 uint32_t cpuid_1_edx;
186 cpuid = get_supported_cpuid(s);
188 struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
191 ret = cpuid_entry_get_reg(entry, reg);
194 /* Fixups for the data returned by KVM, below */
196 if (function == 1 && reg == R_EDX) {
197 /* KVM before 2.6.30 misreports the following features */
198 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
199 } else if (function == 1 && reg == R_ECX) {
200 /* We can set the hypervisor flag, even if KVM does not return it on
201 * GET_SUPPORTED_CPUID
203 ret |= CPUID_EXT_HYPERVISOR;
204 /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
205 * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
206 * and the irqchip is in the kernel.
208 if (kvm_irqchip_in_kernel() &&
209 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
210 ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
213 /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
214 * without the in-kernel irqchip
216 if (!kvm_irqchip_in_kernel()) {
217 ret &= ~CPUID_EXT_X2APIC;
219 } else if (function == 0x80000001 && reg == R_EDX) {
220 /* On Intel, kvm returns cpuid according to the Intel spec,
221 * so add missing bits according to the AMD spec:
223 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
224 ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
229 /* fallback for older kernels */
230 if ((function == KVM_CPUID_FEATURES) && !found) {
231 ret = get_para_features(s);
237 typedef struct HWPoisonPage {
239 QLIST_ENTRY(HWPoisonPage) list;
242 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
243 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
245 static void kvm_unpoison_all(void *param)
247 HWPoisonPage *page, *next_page;
249 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
250 QLIST_REMOVE(page, list);
251 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
256 static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
260 QLIST_FOREACH(page, &hwpoison_page_list, list) {
261 if (page->ram_addr == ram_addr) {
265 page = g_malloc(sizeof(HWPoisonPage));
266 page->ram_addr = ram_addr;
267 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
270 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
275 r = kvm_check_extension(s, KVM_CAP_MCE);
278 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
283 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
285 CPUX86State *env = &cpu->env;
286 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
287 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
288 uint64_t mcg_status = MCG_STATUS_MCIP;
290 if (code == BUS_MCEERR_AR) {
291 status |= MCI_STATUS_AR | 0x134;
292 mcg_status |= MCG_STATUS_EIPV;
295 mcg_status |= MCG_STATUS_RIPV;
297 cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
298 (MCM_ADDR_PHYS << 6) | 0xc,
299 cpu_x86_support_mca_broadcast(env) ?
300 MCE_INJECT_BROADCAST : 0);
303 static void hardware_memory_error(void)
305 fprintf(stderr, "Hardware memory error!\n");
309 int kvm_arch_on_sigbus_vcpu(CPUX86State *env, int code, void *addr)
311 X86CPU *cpu = x86_env_get_cpu(env);
315 if ((env->mcg_cap & MCG_SER_P) && addr
316 && (code == BUS_MCEERR_AR || code == BUS_MCEERR_AO)) {
317 if (qemu_ram_addr_from_host(addr, &ram_addr) ||
318 !kvm_physical_memory_addr_from_host(env->kvm_state, addr, &paddr)) {
319 fprintf(stderr, "Hardware memory error for memory used by "
320 "QEMU itself instead of guest system!\n");
321 /* Hope we are lucky for AO MCE */
322 if (code == BUS_MCEERR_AO) {
325 hardware_memory_error();
328 kvm_hwpoison_page_add(ram_addr);
329 kvm_mce_inject(cpu, paddr, code);
331 if (code == BUS_MCEERR_AO) {
333 } else if (code == BUS_MCEERR_AR) {
334 hardware_memory_error();
342 int kvm_arch_on_sigbus(int code, void *addr)
344 if ((first_cpu->mcg_cap & MCG_SER_P) && addr && code == BUS_MCEERR_AO) {
348 /* Hope we are lucky for AO MCE */
349 if (qemu_ram_addr_from_host(addr, &ram_addr) ||
350 !kvm_physical_memory_addr_from_host(first_cpu->kvm_state, addr,
352 fprintf(stderr, "Hardware memory error for memory used by "
353 "QEMU itself instead of guest system!: %p\n", addr);
356 kvm_hwpoison_page_add(ram_addr);
357 kvm_mce_inject(x86_env_get_cpu(first_cpu), paddr, code);
359 if (code == BUS_MCEERR_AO) {
361 } else if (code == BUS_MCEERR_AR) {
362 hardware_memory_error();
370 static int kvm_inject_mce_oldstyle(CPUX86State *env)
372 if (!kvm_has_vcpu_events() && env->exception_injected == EXCP12_MCHK) {
373 unsigned int bank, bank_num = env->mcg_cap & 0xff;
374 struct kvm_x86_mce mce;
376 env->exception_injected = -1;
379 * There must be at least one bank in use if an MCE is pending.
380 * Find it and use its values for the event injection.
382 for (bank = 0; bank < bank_num; bank++) {
383 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
387 assert(bank < bank_num);
390 mce.status = env->mce_banks[bank * 4 + 1];
391 mce.mcg_status = env->mcg_status;
392 mce.addr = env->mce_banks[bank * 4 + 2];
393 mce.misc = env->mce_banks[bank * 4 + 3];
395 return kvm_vcpu_ioctl(env, KVM_X86_SET_MCE, &mce);
400 static void cpu_update_state(void *opaque, int running, RunState state)
402 CPUX86State *env = opaque;
405 env->tsc_valid = false;
409 int kvm_arch_init_vcpu(CPUX86State *env)
412 struct kvm_cpuid2 cpuid;
413 struct kvm_cpuid_entry2 entries[100];
414 } QEMU_PACKED cpuid_data;
415 uint32_t limit, i, j, cpuid_i;
417 struct kvm_cpuid_entry2 *c;
418 uint32_t signature[3];
423 /* Paravirtualization CPUIDs */
424 c = &cpuid_data.entries[cpuid_i++];
425 memset(c, 0, sizeof(*c));
426 c->function = KVM_CPUID_SIGNATURE;
427 if (!hyperv_enabled()) {
428 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
431 memcpy(signature, "Microsoft Hv", 12);
432 c->eax = HYPERV_CPUID_MIN;
434 c->ebx = signature[0];
435 c->ecx = signature[1];
436 c->edx = signature[2];
438 c = &cpuid_data.entries[cpuid_i++];
439 memset(c, 0, sizeof(*c));
440 c->function = KVM_CPUID_FEATURES;
441 c->eax = env->cpuid_kvm_features;
443 if (hyperv_enabled()) {
444 memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
445 c->eax = signature[0];
447 c = &cpuid_data.entries[cpuid_i++];
448 memset(c, 0, sizeof(*c));
449 c->function = HYPERV_CPUID_VERSION;
453 c = &cpuid_data.entries[cpuid_i++];
454 memset(c, 0, sizeof(*c));
455 c->function = HYPERV_CPUID_FEATURES;
456 if (hyperv_relaxed_timing_enabled()) {
457 c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
459 if (hyperv_vapic_recommended()) {
460 c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
461 c->eax |= HV_X64_MSR_APIC_ACCESS_AVAILABLE;
464 c = &cpuid_data.entries[cpuid_i++];
465 memset(c, 0, sizeof(*c));
466 c->function = HYPERV_CPUID_ENLIGHTMENT_INFO;
467 if (hyperv_relaxed_timing_enabled()) {
468 c->eax |= HV_X64_RELAXED_TIMING_RECOMMENDED;
470 if (hyperv_vapic_recommended()) {
471 c->eax |= HV_X64_APIC_ACCESS_RECOMMENDED;
473 c->ebx = hyperv_get_spinlock_retries();
475 c = &cpuid_data.entries[cpuid_i++];
476 memset(c, 0, sizeof(*c));
477 c->function = HYPERV_CPUID_IMPLEMENT_LIMITS;
481 c = &cpuid_data.entries[cpuid_i++];
482 memset(c, 0, sizeof(*c));
483 c->function = KVM_CPUID_SIGNATURE_NEXT;
484 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
486 c->ebx = signature[0];
487 c->ecx = signature[1];
488 c->edx = signature[2];
491 has_msr_async_pf_en = c->eax & (1 << KVM_FEATURE_ASYNC_PF);
493 has_msr_pv_eoi_en = c->eax & (1 << KVM_FEATURE_PV_EOI);
495 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
497 for (i = 0; i <= limit; i++) {
498 c = &cpuid_data.entries[cpuid_i++];
502 /* Keep reading function 2 till all the input is received */
506 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
507 KVM_CPUID_FLAG_STATE_READ_NEXT;
508 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
509 times = c->eax & 0xff;
511 for (j = 1; j < times; ++j) {
512 c = &cpuid_data.entries[cpuid_i++];
514 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
515 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
523 if (i == 0xd && j == 64) {
527 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
529 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
531 if (i == 4 && c->eax == 0) {
534 if (i == 0xb && !(c->ecx & 0xff00)) {
537 if (i == 0xd && c->eax == 0) {
540 c = &cpuid_data.entries[cpuid_i++];
546 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
550 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
552 for (i = 0x80000000; i <= limit; i++) {
553 c = &cpuid_data.entries[cpuid_i++];
557 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
560 /* Call Centaur's CPUID instructions they are supported. */
561 if (env->cpuid_xlevel2 > 0) {
562 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
564 for (i = 0xC0000000; i <= limit; i++) {
565 c = &cpuid_data.entries[cpuid_i++];
569 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
573 cpuid_data.cpuid.nent = cpuid_i;
575 if (((env->cpuid_version >> 8)&0xF) >= 6
576 && (env->cpuid_features&(CPUID_MCE|CPUID_MCA)) == (CPUID_MCE|CPUID_MCA)
577 && kvm_check_extension(env->kvm_state, KVM_CAP_MCE) > 0) {
582 ret = kvm_get_mce_cap_supported(env->kvm_state, &mcg_cap, &banks);
584 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
588 if (banks > MCE_BANKS_DEF) {
589 banks = MCE_BANKS_DEF;
591 mcg_cap &= MCE_CAP_DEF;
593 ret = kvm_vcpu_ioctl(env, KVM_X86_SETUP_MCE, &mcg_cap);
595 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
599 env->mcg_cap = mcg_cap;
602 qemu_add_vm_change_state_handler(cpu_update_state, env);
604 cpuid_data.cpuid.padding = 0;
605 r = kvm_vcpu_ioctl(env, KVM_SET_CPUID2, &cpuid_data);
610 r = kvm_check_extension(env->kvm_state, KVM_CAP_TSC_CONTROL);
611 if (r && env->tsc_khz) {
612 r = kvm_vcpu_ioctl(env, KVM_SET_TSC_KHZ, env->tsc_khz);
614 fprintf(stderr, "KVM_SET_TSC_KHZ failed\n");
619 if (kvm_has_xsave()) {
620 env->kvm_xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
626 void kvm_arch_reset_vcpu(CPUX86State *env)
628 X86CPU *cpu = x86_env_get_cpu(env);
630 env->exception_injected = -1;
631 env->interrupt_injected = -1;
633 if (kvm_irqchip_in_kernel()) {
634 env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
635 KVM_MP_STATE_UNINITIALIZED;
637 env->mp_state = KVM_MP_STATE_RUNNABLE;
641 static int kvm_get_supported_msrs(KVMState *s)
643 static int kvm_supported_msrs;
647 if (kvm_supported_msrs == 0) {
648 struct kvm_msr_list msr_list, *kvm_msr_list;
650 kvm_supported_msrs = -1;
652 /* Obtain MSR list from KVM. These are the MSRs that we must
655 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
656 if (ret < 0 && ret != -E2BIG) {
659 /* Old kernel modules had a bug and could write beyond the provided
660 memory. Allocate at least a safe amount of 1K. */
661 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
663 sizeof(msr_list.indices[0])));
665 kvm_msr_list->nmsrs = msr_list.nmsrs;
666 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
670 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
671 if (kvm_msr_list->indices[i] == MSR_STAR) {
675 if (kvm_msr_list->indices[i] == MSR_VM_HSAVE_PA) {
676 has_msr_hsave_pa = true;
679 if (kvm_msr_list->indices[i] == MSR_IA32_TSCDEADLINE) {
680 has_msr_tsc_deadline = true;
683 if (kvm_msr_list->indices[i] == MSR_IA32_MISC_ENABLE) {
684 has_msr_misc_enable = true;
690 g_free(kvm_msr_list);
696 int kvm_arch_init(KVMState *s)
698 QemuOptsList *list = qemu_find_opts("machine");
699 uint64_t identity_base = 0xfffbc000;
702 struct utsname utsname;
704 ret = kvm_get_supported_msrs(s);
710 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
713 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
714 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
715 * Since these must be part of guest physical memory, we need to allocate
716 * them, both by setting their start addresses in the kernel and by
717 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
719 * Older KVM versions may not support setting the identity map base. In
720 * that case we need to stick with the default, i.e. a 256K maximum BIOS
723 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
724 /* Allows up to 16M BIOSes. */
725 identity_base = 0xfeffc000;
727 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
733 /* Set TSS base one page after EPT identity map. */
734 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
739 /* Tell fw_cfg to notify the BIOS to reserve the range. */
740 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
742 fprintf(stderr, "e820_add_entry() table is full\n");
745 qemu_register_reset(kvm_unpoison_all, NULL);
747 if (!QTAILQ_EMPTY(&list->head)) {
748 shadow_mem = qemu_opt_get_size(QTAILQ_FIRST(&list->head),
749 "kvm_shadow_mem", -1);
750 if (shadow_mem != -1) {
752 ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
761 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
763 lhs->selector = rhs->selector;
764 lhs->base = rhs->base;
765 lhs->limit = rhs->limit;
777 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
779 unsigned flags = rhs->flags;
780 lhs->selector = rhs->selector;
781 lhs->base = rhs->base;
782 lhs->limit = rhs->limit;
783 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
784 lhs->present = (flags & DESC_P_MASK) != 0;
785 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
786 lhs->db = (flags >> DESC_B_SHIFT) & 1;
787 lhs->s = (flags & DESC_S_MASK) != 0;
788 lhs->l = (flags >> DESC_L_SHIFT) & 1;
789 lhs->g = (flags & DESC_G_MASK) != 0;
790 lhs->avl = (flags & DESC_AVL_MASK) != 0;
795 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
797 lhs->selector = rhs->selector;
798 lhs->base = rhs->base;
799 lhs->limit = rhs->limit;
800 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
801 (rhs->present * DESC_P_MASK) |
802 (rhs->dpl << DESC_DPL_SHIFT) |
803 (rhs->db << DESC_B_SHIFT) |
804 (rhs->s * DESC_S_MASK) |
805 (rhs->l << DESC_L_SHIFT) |
806 (rhs->g * DESC_G_MASK) |
807 (rhs->avl * DESC_AVL_MASK);
810 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
813 *kvm_reg = *qemu_reg;
815 *qemu_reg = *kvm_reg;
819 static int kvm_getput_regs(CPUX86State *env, int set)
821 struct kvm_regs regs;
825 ret = kvm_vcpu_ioctl(env, KVM_GET_REGS, ®s);
831 kvm_getput_reg(®s.rax, &env->regs[R_EAX], set);
832 kvm_getput_reg(®s.rbx, &env->regs[R_EBX], set);
833 kvm_getput_reg(®s.rcx, &env->regs[R_ECX], set);
834 kvm_getput_reg(®s.rdx, &env->regs[R_EDX], set);
835 kvm_getput_reg(®s.rsi, &env->regs[R_ESI], set);
836 kvm_getput_reg(®s.rdi, &env->regs[R_EDI], set);
837 kvm_getput_reg(®s.rsp, &env->regs[R_ESP], set);
838 kvm_getput_reg(®s.rbp, &env->regs[R_EBP], set);
840 kvm_getput_reg(®s.r8, &env->regs[8], set);
841 kvm_getput_reg(®s.r9, &env->regs[9], set);
842 kvm_getput_reg(®s.r10, &env->regs[10], set);
843 kvm_getput_reg(®s.r11, &env->regs[11], set);
844 kvm_getput_reg(®s.r12, &env->regs[12], set);
845 kvm_getput_reg(®s.r13, &env->regs[13], set);
846 kvm_getput_reg(®s.r14, &env->regs[14], set);
847 kvm_getput_reg(®s.r15, &env->regs[15], set);
850 kvm_getput_reg(®s.rflags, &env->eflags, set);
851 kvm_getput_reg(®s.rip, &env->eip, set);
854 ret = kvm_vcpu_ioctl(env, KVM_SET_REGS, ®s);
860 static int kvm_put_fpu(CPUX86State *env)
865 memset(&fpu, 0, sizeof fpu);
866 fpu.fsw = env->fpus & ~(7 << 11);
867 fpu.fsw |= (env->fpstt & 7) << 11;
869 fpu.last_opcode = env->fpop;
870 fpu.last_ip = env->fpip;
871 fpu.last_dp = env->fpdp;
872 for (i = 0; i < 8; ++i) {
873 fpu.ftwx |= (!env->fptags[i]) << i;
875 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
876 memcpy(fpu.xmm, env->xmm_regs, sizeof env->xmm_regs);
877 fpu.mxcsr = env->mxcsr;
879 return kvm_vcpu_ioctl(env, KVM_SET_FPU, &fpu);
882 #define XSAVE_FCW_FSW 0
883 #define XSAVE_FTW_FOP 1
884 #define XSAVE_CWD_RIP 2
885 #define XSAVE_CWD_RDP 4
886 #define XSAVE_MXCSR 6
887 #define XSAVE_ST_SPACE 8
888 #define XSAVE_XMM_SPACE 40
889 #define XSAVE_XSTATE_BV 128
890 #define XSAVE_YMMH_SPACE 144
892 static int kvm_put_xsave(CPUX86State *env)
894 struct kvm_xsave* xsave = env->kvm_xsave_buf;
895 uint16_t cwd, swd, twd;
898 if (!kvm_has_xsave()) {
899 return kvm_put_fpu(env);
902 memset(xsave, 0, sizeof(struct kvm_xsave));
904 swd = env->fpus & ~(7 << 11);
905 swd |= (env->fpstt & 7) << 11;
907 for (i = 0; i < 8; ++i) {
908 twd |= (!env->fptags[i]) << i;
910 xsave->region[XSAVE_FCW_FSW] = (uint32_t)(swd << 16) + cwd;
911 xsave->region[XSAVE_FTW_FOP] = (uint32_t)(env->fpop << 16) + twd;
912 memcpy(&xsave->region[XSAVE_CWD_RIP], &env->fpip, sizeof(env->fpip));
913 memcpy(&xsave->region[XSAVE_CWD_RDP], &env->fpdp, sizeof(env->fpdp));
914 memcpy(&xsave->region[XSAVE_ST_SPACE], env->fpregs,
916 memcpy(&xsave->region[XSAVE_XMM_SPACE], env->xmm_regs,
917 sizeof env->xmm_regs);
918 xsave->region[XSAVE_MXCSR] = env->mxcsr;
919 *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV] = env->xstate_bv;
920 memcpy(&xsave->region[XSAVE_YMMH_SPACE], env->ymmh_regs,
921 sizeof env->ymmh_regs);
922 r = kvm_vcpu_ioctl(env, KVM_SET_XSAVE, xsave);
926 static int kvm_put_xcrs(CPUX86State *env)
928 struct kvm_xcrs xcrs;
930 if (!kvm_has_xcrs()) {
936 xcrs.xcrs[0].xcr = 0;
937 xcrs.xcrs[0].value = env->xcr0;
938 return kvm_vcpu_ioctl(env, KVM_SET_XCRS, &xcrs);
941 static int kvm_put_sregs(CPUX86State *env)
943 struct kvm_sregs sregs;
945 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
946 if (env->interrupt_injected >= 0) {
947 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
948 (uint64_t)1 << (env->interrupt_injected % 64);
951 if ((env->eflags & VM_MASK)) {
952 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
953 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
954 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
955 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
956 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
957 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
959 set_seg(&sregs.cs, &env->segs[R_CS]);
960 set_seg(&sregs.ds, &env->segs[R_DS]);
961 set_seg(&sregs.es, &env->segs[R_ES]);
962 set_seg(&sregs.fs, &env->segs[R_FS]);
963 set_seg(&sregs.gs, &env->segs[R_GS]);
964 set_seg(&sregs.ss, &env->segs[R_SS]);
967 set_seg(&sregs.tr, &env->tr);
968 set_seg(&sregs.ldt, &env->ldt);
970 sregs.idt.limit = env->idt.limit;
971 sregs.idt.base = env->idt.base;
972 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
973 sregs.gdt.limit = env->gdt.limit;
974 sregs.gdt.base = env->gdt.base;
975 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
977 sregs.cr0 = env->cr[0];
978 sregs.cr2 = env->cr[2];
979 sregs.cr3 = env->cr[3];
980 sregs.cr4 = env->cr[4];
982 sregs.cr8 = cpu_get_apic_tpr(env->apic_state);
983 sregs.apic_base = cpu_get_apic_base(env->apic_state);
985 sregs.efer = env->efer;
987 return kvm_vcpu_ioctl(env, KVM_SET_SREGS, &sregs);
990 static void kvm_msr_entry_set(struct kvm_msr_entry *entry,
991 uint32_t index, uint64_t value)
993 entry->index = index;
997 static int kvm_put_msrs(CPUX86State *env, int level)
1000 struct kvm_msrs info;
1001 struct kvm_msr_entry entries[100];
1003 struct kvm_msr_entry *msrs = msr_data.entries;
1006 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_CS, env->sysenter_cs);
1007 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
1008 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
1009 kvm_msr_entry_set(&msrs[n++], MSR_PAT, env->pat);
1011 kvm_msr_entry_set(&msrs[n++], MSR_STAR, env->star);
1013 if (has_msr_hsave_pa) {
1014 kvm_msr_entry_set(&msrs[n++], MSR_VM_HSAVE_PA, env->vm_hsave);
1016 if (has_msr_tsc_deadline) {
1017 kvm_msr_entry_set(&msrs[n++], MSR_IA32_TSCDEADLINE, env->tsc_deadline);
1019 if (has_msr_misc_enable) {
1020 kvm_msr_entry_set(&msrs[n++], MSR_IA32_MISC_ENABLE,
1021 env->msr_ia32_misc_enable);
1023 #ifdef TARGET_X86_64
1024 if (lm_capable_kernel) {
1025 kvm_msr_entry_set(&msrs[n++], MSR_CSTAR, env->cstar);
1026 kvm_msr_entry_set(&msrs[n++], MSR_KERNELGSBASE, env->kernelgsbase);
1027 kvm_msr_entry_set(&msrs[n++], MSR_FMASK, env->fmask);
1028 kvm_msr_entry_set(&msrs[n++], MSR_LSTAR, env->lstar);
1031 if (level == KVM_PUT_FULL_STATE) {
1033 * KVM is yet unable to synchronize TSC values of multiple VCPUs on
1034 * writeback. Until this is fixed, we only write the offset to SMP
1035 * guests after migration, desynchronizing the VCPUs, but avoiding
1036 * huge jump-backs that would occur without any writeback at all.
1038 if (smp_cpus == 1 || env->tsc != 0) {
1039 kvm_msr_entry_set(&msrs[n++], MSR_IA32_TSC, env->tsc);
1043 * The following paravirtual MSRs have side effects on the guest or are
1044 * too heavy for normal writeback. Limit them to reset or full state
1047 if (level >= KVM_PUT_RESET_STATE) {
1048 kvm_msr_entry_set(&msrs[n++], MSR_KVM_SYSTEM_TIME,
1049 env->system_time_msr);
1050 kvm_msr_entry_set(&msrs[n++], MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
1051 if (has_msr_async_pf_en) {
1052 kvm_msr_entry_set(&msrs[n++], MSR_KVM_ASYNC_PF_EN,
1053 env->async_pf_en_msr);
1055 if (has_msr_pv_eoi_en) {
1056 kvm_msr_entry_set(&msrs[n++], MSR_KVM_PV_EOI_EN,
1057 env->pv_eoi_en_msr);
1059 if (hyperv_hypercall_available()) {
1060 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_GUEST_OS_ID, 0);
1061 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_HYPERCALL, 0);
1063 if (hyperv_vapic_recommended()) {
1064 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_APIC_ASSIST_PAGE, 0);
1070 kvm_msr_entry_set(&msrs[n++], MSR_MCG_STATUS, env->mcg_status);
1071 kvm_msr_entry_set(&msrs[n++], MSR_MCG_CTL, env->mcg_ctl);
1072 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1073 kvm_msr_entry_set(&msrs[n++], MSR_MC0_CTL + i, env->mce_banks[i]);
1077 msr_data.info.nmsrs = n;
1079 return kvm_vcpu_ioctl(env, KVM_SET_MSRS, &msr_data);
1084 static int kvm_get_fpu(CPUX86State *env)
1089 ret = kvm_vcpu_ioctl(env, KVM_GET_FPU, &fpu);
1094 env->fpstt = (fpu.fsw >> 11) & 7;
1095 env->fpus = fpu.fsw;
1096 env->fpuc = fpu.fcw;
1097 env->fpop = fpu.last_opcode;
1098 env->fpip = fpu.last_ip;
1099 env->fpdp = fpu.last_dp;
1100 for (i = 0; i < 8; ++i) {
1101 env->fptags[i] = !((fpu.ftwx >> i) & 1);
1103 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
1104 memcpy(env->xmm_regs, fpu.xmm, sizeof env->xmm_regs);
1105 env->mxcsr = fpu.mxcsr;
1110 static int kvm_get_xsave(CPUX86State *env)
1112 struct kvm_xsave* xsave = env->kvm_xsave_buf;
1114 uint16_t cwd, swd, twd;
1116 if (!kvm_has_xsave()) {
1117 return kvm_get_fpu(env);
1120 ret = kvm_vcpu_ioctl(env, KVM_GET_XSAVE, xsave);
1125 cwd = (uint16_t)xsave->region[XSAVE_FCW_FSW];
1126 swd = (uint16_t)(xsave->region[XSAVE_FCW_FSW] >> 16);
1127 twd = (uint16_t)xsave->region[XSAVE_FTW_FOP];
1128 env->fpop = (uint16_t)(xsave->region[XSAVE_FTW_FOP] >> 16);
1129 env->fpstt = (swd >> 11) & 7;
1132 for (i = 0; i < 8; ++i) {
1133 env->fptags[i] = !((twd >> i) & 1);
1135 memcpy(&env->fpip, &xsave->region[XSAVE_CWD_RIP], sizeof(env->fpip));
1136 memcpy(&env->fpdp, &xsave->region[XSAVE_CWD_RDP], sizeof(env->fpdp));
1137 env->mxcsr = xsave->region[XSAVE_MXCSR];
1138 memcpy(env->fpregs, &xsave->region[XSAVE_ST_SPACE],
1139 sizeof env->fpregs);
1140 memcpy(env->xmm_regs, &xsave->region[XSAVE_XMM_SPACE],
1141 sizeof env->xmm_regs);
1142 env->xstate_bv = *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV];
1143 memcpy(env->ymmh_regs, &xsave->region[XSAVE_YMMH_SPACE],
1144 sizeof env->ymmh_regs);
1148 static int kvm_get_xcrs(CPUX86State *env)
1151 struct kvm_xcrs xcrs;
1153 if (!kvm_has_xcrs()) {
1157 ret = kvm_vcpu_ioctl(env, KVM_GET_XCRS, &xcrs);
1162 for (i = 0; i < xcrs.nr_xcrs; i++) {
1163 /* Only support xcr0 now */
1164 if (xcrs.xcrs[0].xcr == 0) {
1165 env->xcr0 = xcrs.xcrs[0].value;
1172 static int kvm_get_sregs(CPUX86State *env)
1174 struct kvm_sregs sregs;
1178 ret = kvm_vcpu_ioctl(env, KVM_GET_SREGS, &sregs);
1183 /* There can only be one pending IRQ set in the bitmap at a time, so try
1184 to find it and save its number instead (-1 for none). */
1185 env->interrupt_injected = -1;
1186 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
1187 if (sregs.interrupt_bitmap[i]) {
1188 bit = ctz64(sregs.interrupt_bitmap[i]);
1189 env->interrupt_injected = i * 64 + bit;
1194 get_seg(&env->segs[R_CS], &sregs.cs);
1195 get_seg(&env->segs[R_DS], &sregs.ds);
1196 get_seg(&env->segs[R_ES], &sregs.es);
1197 get_seg(&env->segs[R_FS], &sregs.fs);
1198 get_seg(&env->segs[R_GS], &sregs.gs);
1199 get_seg(&env->segs[R_SS], &sregs.ss);
1201 get_seg(&env->tr, &sregs.tr);
1202 get_seg(&env->ldt, &sregs.ldt);
1204 env->idt.limit = sregs.idt.limit;
1205 env->idt.base = sregs.idt.base;
1206 env->gdt.limit = sregs.gdt.limit;
1207 env->gdt.base = sregs.gdt.base;
1209 env->cr[0] = sregs.cr0;
1210 env->cr[2] = sregs.cr2;
1211 env->cr[3] = sregs.cr3;
1212 env->cr[4] = sregs.cr4;
1214 env->efer = sregs.efer;
1216 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
1218 #define HFLAG_COPY_MASK \
1219 ~( HF_CPL_MASK | HF_PE_MASK | HF_MP_MASK | HF_EM_MASK | \
1220 HF_TS_MASK | HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK | \
1221 HF_OSFXSR_MASK | HF_LMA_MASK | HF_CS32_MASK | \
1222 HF_SS32_MASK | HF_CS64_MASK | HF_ADDSEG_MASK)
1224 hflags = (env->segs[R_CS].flags >> DESC_DPL_SHIFT) & HF_CPL_MASK;
1225 hflags |= (env->cr[0] & CR0_PE_MASK) << (HF_PE_SHIFT - CR0_PE_SHIFT);
1226 hflags |= (env->cr[0] << (HF_MP_SHIFT - CR0_MP_SHIFT)) &
1227 (HF_MP_MASK | HF_EM_MASK | HF_TS_MASK);
1228 hflags |= (env->eflags & (HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK));
1229 hflags |= (env->cr[4] & CR4_OSFXSR_MASK) <<
1230 (HF_OSFXSR_SHIFT - CR4_OSFXSR_SHIFT);
1232 if (env->efer & MSR_EFER_LMA) {
1233 hflags |= HF_LMA_MASK;
1236 if ((hflags & HF_LMA_MASK) && (env->segs[R_CS].flags & DESC_L_MASK)) {
1237 hflags |= HF_CS32_MASK | HF_SS32_MASK | HF_CS64_MASK;
1239 hflags |= (env->segs[R_CS].flags & DESC_B_MASK) >>
1240 (DESC_B_SHIFT - HF_CS32_SHIFT);
1241 hflags |= (env->segs[R_SS].flags & DESC_B_MASK) >>
1242 (DESC_B_SHIFT - HF_SS32_SHIFT);
1243 if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK) ||
1244 !(hflags & HF_CS32_MASK)) {
1245 hflags |= HF_ADDSEG_MASK;
1247 hflags |= ((env->segs[R_DS].base | env->segs[R_ES].base |
1248 env->segs[R_SS].base) != 0) << HF_ADDSEG_SHIFT;
1251 env->hflags = (env->hflags & HFLAG_COPY_MASK) | hflags;
1256 static int kvm_get_msrs(CPUX86State *env)
1259 struct kvm_msrs info;
1260 struct kvm_msr_entry entries[100];
1262 struct kvm_msr_entry *msrs = msr_data.entries;
1266 msrs[n++].index = MSR_IA32_SYSENTER_CS;
1267 msrs[n++].index = MSR_IA32_SYSENTER_ESP;
1268 msrs[n++].index = MSR_IA32_SYSENTER_EIP;
1269 msrs[n++].index = MSR_PAT;
1271 msrs[n++].index = MSR_STAR;
1273 if (has_msr_hsave_pa) {
1274 msrs[n++].index = MSR_VM_HSAVE_PA;
1276 if (has_msr_tsc_deadline) {
1277 msrs[n++].index = MSR_IA32_TSCDEADLINE;
1279 if (has_msr_misc_enable) {
1280 msrs[n++].index = MSR_IA32_MISC_ENABLE;
1283 if (!env->tsc_valid) {
1284 msrs[n++].index = MSR_IA32_TSC;
1285 env->tsc_valid = !runstate_is_running();
1288 #ifdef TARGET_X86_64
1289 if (lm_capable_kernel) {
1290 msrs[n++].index = MSR_CSTAR;
1291 msrs[n++].index = MSR_KERNELGSBASE;
1292 msrs[n++].index = MSR_FMASK;
1293 msrs[n++].index = MSR_LSTAR;
1296 msrs[n++].index = MSR_KVM_SYSTEM_TIME;
1297 msrs[n++].index = MSR_KVM_WALL_CLOCK;
1298 if (has_msr_async_pf_en) {
1299 msrs[n++].index = MSR_KVM_ASYNC_PF_EN;
1301 if (has_msr_pv_eoi_en) {
1302 msrs[n++].index = MSR_KVM_PV_EOI_EN;
1306 msrs[n++].index = MSR_MCG_STATUS;
1307 msrs[n++].index = MSR_MCG_CTL;
1308 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1309 msrs[n++].index = MSR_MC0_CTL + i;
1313 msr_data.info.nmsrs = n;
1314 ret = kvm_vcpu_ioctl(env, KVM_GET_MSRS, &msr_data);
1319 for (i = 0; i < ret; i++) {
1320 switch (msrs[i].index) {
1321 case MSR_IA32_SYSENTER_CS:
1322 env->sysenter_cs = msrs[i].data;
1324 case MSR_IA32_SYSENTER_ESP:
1325 env->sysenter_esp = msrs[i].data;
1327 case MSR_IA32_SYSENTER_EIP:
1328 env->sysenter_eip = msrs[i].data;
1331 env->pat = msrs[i].data;
1334 env->star = msrs[i].data;
1336 #ifdef TARGET_X86_64
1338 env->cstar = msrs[i].data;
1340 case MSR_KERNELGSBASE:
1341 env->kernelgsbase = msrs[i].data;
1344 env->fmask = msrs[i].data;
1347 env->lstar = msrs[i].data;
1351 env->tsc = msrs[i].data;
1353 case MSR_IA32_TSCDEADLINE:
1354 env->tsc_deadline = msrs[i].data;
1356 case MSR_VM_HSAVE_PA:
1357 env->vm_hsave = msrs[i].data;
1359 case MSR_KVM_SYSTEM_TIME:
1360 env->system_time_msr = msrs[i].data;
1362 case MSR_KVM_WALL_CLOCK:
1363 env->wall_clock_msr = msrs[i].data;
1365 case MSR_MCG_STATUS:
1366 env->mcg_status = msrs[i].data;
1369 env->mcg_ctl = msrs[i].data;
1371 case MSR_IA32_MISC_ENABLE:
1372 env->msr_ia32_misc_enable = msrs[i].data;
1375 if (msrs[i].index >= MSR_MC0_CTL &&
1376 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
1377 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
1380 case MSR_KVM_ASYNC_PF_EN:
1381 env->async_pf_en_msr = msrs[i].data;
1383 case MSR_KVM_PV_EOI_EN:
1384 env->pv_eoi_en_msr = msrs[i].data;
1392 static int kvm_put_mp_state(CPUX86State *env)
1394 struct kvm_mp_state mp_state = { .mp_state = env->mp_state };
1396 return kvm_vcpu_ioctl(env, KVM_SET_MP_STATE, &mp_state);
1399 static int kvm_get_mp_state(X86CPU *cpu)
1401 CPUX86State *env = &cpu->env;
1402 struct kvm_mp_state mp_state;
1405 ret = kvm_vcpu_ioctl(env, KVM_GET_MP_STATE, &mp_state);
1409 env->mp_state = mp_state.mp_state;
1410 if (kvm_irqchip_in_kernel()) {
1411 env->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
1416 static int kvm_get_apic(CPUX86State *env)
1418 DeviceState *apic = env->apic_state;
1419 struct kvm_lapic_state kapic;
1422 if (apic && kvm_irqchip_in_kernel()) {
1423 ret = kvm_vcpu_ioctl(env, KVM_GET_LAPIC, &kapic);
1428 kvm_get_apic_state(apic, &kapic);
1433 static int kvm_put_apic(CPUX86State *env)
1435 DeviceState *apic = env->apic_state;
1436 struct kvm_lapic_state kapic;
1438 if (apic && kvm_irqchip_in_kernel()) {
1439 kvm_put_apic_state(apic, &kapic);
1441 return kvm_vcpu_ioctl(env, KVM_SET_LAPIC, &kapic);
1446 static int kvm_put_vcpu_events(CPUX86State *env, int level)
1448 struct kvm_vcpu_events events;
1450 if (!kvm_has_vcpu_events()) {
1454 events.exception.injected = (env->exception_injected >= 0);
1455 events.exception.nr = env->exception_injected;
1456 events.exception.has_error_code = env->has_error_code;
1457 events.exception.error_code = env->error_code;
1458 events.exception.pad = 0;
1460 events.interrupt.injected = (env->interrupt_injected >= 0);
1461 events.interrupt.nr = env->interrupt_injected;
1462 events.interrupt.soft = env->soft_interrupt;
1464 events.nmi.injected = env->nmi_injected;
1465 events.nmi.pending = env->nmi_pending;
1466 events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
1469 events.sipi_vector = env->sipi_vector;
1472 if (level >= KVM_PUT_RESET_STATE) {
1474 KVM_VCPUEVENT_VALID_NMI_PENDING | KVM_VCPUEVENT_VALID_SIPI_VECTOR;
1477 return kvm_vcpu_ioctl(env, KVM_SET_VCPU_EVENTS, &events);
1480 static int kvm_get_vcpu_events(CPUX86State *env)
1482 struct kvm_vcpu_events events;
1485 if (!kvm_has_vcpu_events()) {
1489 ret = kvm_vcpu_ioctl(env, KVM_GET_VCPU_EVENTS, &events);
1493 env->exception_injected =
1494 events.exception.injected ? events.exception.nr : -1;
1495 env->has_error_code = events.exception.has_error_code;
1496 env->error_code = events.exception.error_code;
1498 env->interrupt_injected =
1499 events.interrupt.injected ? events.interrupt.nr : -1;
1500 env->soft_interrupt = events.interrupt.soft;
1502 env->nmi_injected = events.nmi.injected;
1503 env->nmi_pending = events.nmi.pending;
1504 if (events.nmi.masked) {
1505 env->hflags2 |= HF2_NMI_MASK;
1507 env->hflags2 &= ~HF2_NMI_MASK;
1510 env->sipi_vector = events.sipi_vector;
1515 static int kvm_guest_debug_workarounds(CPUX86State *env)
1518 unsigned long reinject_trap = 0;
1520 if (!kvm_has_vcpu_events()) {
1521 if (env->exception_injected == 1) {
1522 reinject_trap = KVM_GUESTDBG_INJECT_DB;
1523 } else if (env->exception_injected == 3) {
1524 reinject_trap = KVM_GUESTDBG_INJECT_BP;
1526 env->exception_injected = -1;
1530 * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
1531 * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
1532 * by updating the debug state once again if single-stepping is on.
1533 * Another reason to call kvm_update_guest_debug here is a pending debug
1534 * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
1535 * reinject them via SET_GUEST_DEBUG.
1537 if (reinject_trap ||
1538 (!kvm_has_robust_singlestep() && env->singlestep_enabled)) {
1539 ret = kvm_update_guest_debug(env, reinject_trap);
1544 static int kvm_put_debugregs(CPUX86State *env)
1546 struct kvm_debugregs dbgregs;
1549 if (!kvm_has_debugregs()) {
1553 for (i = 0; i < 4; i++) {
1554 dbgregs.db[i] = env->dr[i];
1556 dbgregs.dr6 = env->dr[6];
1557 dbgregs.dr7 = env->dr[7];
1560 return kvm_vcpu_ioctl(env, KVM_SET_DEBUGREGS, &dbgregs);
1563 static int kvm_get_debugregs(CPUX86State *env)
1565 struct kvm_debugregs dbgregs;
1568 if (!kvm_has_debugregs()) {
1572 ret = kvm_vcpu_ioctl(env, KVM_GET_DEBUGREGS, &dbgregs);
1576 for (i = 0; i < 4; i++) {
1577 env->dr[i] = dbgregs.db[i];
1579 env->dr[4] = env->dr[6] = dbgregs.dr6;
1580 env->dr[5] = env->dr[7] = dbgregs.dr7;
1585 int kvm_arch_put_registers(CPUX86State *env, int level)
1587 CPUState *cpu = ENV_GET_CPU(env);
1590 assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
1592 ret = kvm_getput_regs(env, 1);
1596 ret = kvm_put_xsave(env);
1600 ret = kvm_put_xcrs(env);
1604 ret = kvm_put_sregs(env);
1608 /* must be before kvm_put_msrs */
1609 ret = kvm_inject_mce_oldstyle(env);
1613 ret = kvm_put_msrs(env, level);
1617 if (level >= KVM_PUT_RESET_STATE) {
1618 ret = kvm_put_mp_state(env);
1622 ret = kvm_put_apic(env);
1627 ret = kvm_put_vcpu_events(env, level);
1631 ret = kvm_put_debugregs(env);
1636 ret = kvm_guest_debug_workarounds(env);
1643 int kvm_arch_get_registers(CPUX86State *env)
1645 X86CPU *cpu = x86_env_get_cpu(env);
1648 assert(cpu_is_stopped(CPU(cpu)) || qemu_cpu_is_self(CPU(cpu)));
1650 ret = kvm_getput_regs(env, 0);
1654 ret = kvm_get_xsave(env);
1658 ret = kvm_get_xcrs(env);
1662 ret = kvm_get_sregs(env);
1666 ret = kvm_get_msrs(env);
1670 ret = kvm_get_mp_state(cpu);
1674 ret = kvm_get_apic(env);
1678 ret = kvm_get_vcpu_events(env);
1682 ret = kvm_get_debugregs(env);
1689 void kvm_arch_pre_run(CPUX86State *env, struct kvm_run *run)
1694 if (env->interrupt_request & CPU_INTERRUPT_NMI) {
1695 env->interrupt_request &= ~CPU_INTERRUPT_NMI;
1696 DPRINTF("injected NMI\n");
1697 ret = kvm_vcpu_ioctl(env, KVM_NMI);
1699 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
1704 if (!kvm_irqchip_in_kernel()) {
1705 /* Force the VCPU out of its inner loop to process any INIT requests
1706 * or pending TPR access reports. */
1707 if (env->interrupt_request &
1708 (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
1709 env->exit_request = 1;
1712 /* Try to inject an interrupt if the guest can accept it */
1713 if (run->ready_for_interrupt_injection &&
1714 (env->interrupt_request & CPU_INTERRUPT_HARD) &&
1715 (env->eflags & IF_MASK)) {
1718 env->interrupt_request &= ~CPU_INTERRUPT_HARD;
1719 irq = cpu_get_pic_interrupt(env);
1721 struct kvm_interrupt intr;
1724 DPRINTF("injected interrupt %d\n", irq);
1725 ret = kvm_vcpu_ioctl(env, KVM_INTERRUPT, &intr);
1728 "KVM: injection failed, interrupt lost (%s)\n",
1734 /* If we have an interrupt but the guest is not ready to receive an
1735 * interrupt, request an interrupt window exit. This will
1736 * cause a return to userspace as soon as the guest is ready to
1737 * receive interrupts. */
1738 if ((env->interrupt_request & CPU_INTERRUPT_HARD)) {
1739 run->request_interrupt_window = 1;
1741 run->request_interrupt_window = 0;
1744 DPRINTF("setting tpr\n");
1745 run->cr8 = cpu_get_apic_tpr(env->apic_state);
1749 void kvm_arch_post_run(CPUX86State *env, struct kvm_run *run)
1752 env->eflags |= IF_MASK;
1754 env->eflags &= ~IF_MASK;
1756 cpu_set_apic_tpr(env->apic_state, run->cr8);
1757 cpu_set_apic_base(env->apic_state, run->apic_base);
1760 int kvm_arch_process_async_events(CPUX86State *env)
1762 X86CPU *cpu = x86_env_get_cpu(env);
1764 if (env->interrupt_request & CPU_INTERRUPT_MCE) {
1765 /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
1766 assert(env->mcg_cap);
1768 env->interrupt_request &= ~CPU_INTERRUPT_MCE;
1770 kvm_cpu_synchronize_state(env);
1772 if (env->exception_injected == EXCP08_DBLE) {
1773 /* this means triple fault */
1774 qemu_system_reset_request();
1775 env->exit_request = 1;
1778 env->exception_injected = EXCP12_MCHK;
1779 env->has_error_code = 0;
1782 if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
1783 env->mp_state = KVM_MP_STATE_RUNNABLE;
1787 if (kvm_irqchip_in_kernel()) {
1791 if (env->interrupt_request & CPU_INTERRUPT_POLL) {
1792 env->interrupt_request &= ~CPU_INTERRUPT_POLL;
1793 apic_poll_irq(env->apic_state);
1795 if (((env->interrupt_request & CPU_INTERRUPT_HARD) &&
1796 (env->eflags & IF_MASK)) ||
1797 (env->interrupt_request & CPU_INTERRUPT_NMI)) {
1800 if (env->interrupt_request & CPU_INTERRUPT_INIT) {
1801 kvm_cpu_synchronize_state(env);
1804 if (env->interrupt_request & CPU_INTERRUPT_SIPI) {
1805 kvm_cpu_synchronize_state(env);
1808 if (env->interrupt_request & CPU_INTERRUPT_TPR) {
1809 env->interrupt_request &= ~CPU_INTERRUPT_TPR;
1810 kvm_cpu_synchronize_state(env);
1811 apic_handle_tpr_access_report(env->apic_state, env->eip,
1812 env->tpr_access_type);
1818 static int kvm_handle_halt(X86CPU *cpu)
1820 CPUX86State *env = &cpu->env;
1822 if (!((env->interrupt_request & CPU_INTERRUPT_HARD) &&
1823 (env->eflags & IF_MASK)) &&
1824 !(env->interrupt_request & CPU_INTERRUPT_NMI)) {
1832 static int kvm_handle_tpr_access(CPUX86State *env)
1834 struct kvm_run *run = env->kvm_run;
1836 apic_handle_tpr_access_report(env->apic_state, run->tpr_access.rip,
1837 run->tpr_access.is_write ? TPR_ACCESS_WRITE
1842 int kvm_arch_insert_sw_breakpoint(CPUX86State *env, struct kvm_sw_breakpoint *bp)
1844 static const uint8_t int3 = 0xcc;
1846 if (cpu_memory_rw_debug(env, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
1847 cpu_memory_rw_debug(env, bp->pc, (uint8_t *)&int3, 1, 1)) {
1853 int kvm_arch_remove_sw_breakpoint(CPUX86State *env, struct kvm_sw_breakpoint *bp)
1857 if (cpu_memory_rw_debug(env, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
1858 cpu_memory_rw_debug(env, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
1870 static int nb_hw_breakpoint;
1872 static int find_hw_breakpoint(target_ulong addr, int len, int type)
1876 for (n = 0; n < nb_hw_breakpoint; n++) {
1877 if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
1878 (hw_breakpoint[n].len == len || len == -1)) {
1885 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
1886 target_ulong len, int type)
1889 case GDB_BREAKPOINT_HW:
1892 case GDB_WATCHPOINT_WRITE:
1893 case GDB_WATCHPOINT_ACCESS:
1900 if (addr & (len - 1)) {
1912 if (nb_hw_breakpoint == 4) {
1915 if (find_hw_breakpoint(addr, len, type) >= 0) {
1918 hw_breakpoint[nb_hw_breakpoint].addr = addr;
1919 hw_breakpoint[nb_hw_breakpoint].len = len;
1920 hw_breakpoint[nb_hw_breakpoint].type = type;
1926 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
1927 target_ulong len, int type)
1931 n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
1936 hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
1941 void kvm_arch_remove_all_hw_breakpoints(void)
1943 nb_hw_breakpoint = 0;
1946 static CPUWatchpoint hw_watchpoint;
1948 static int kvm_handle_debug(struct kvm_debug_exit_arch *arch_info)
1953 if (arch_info->exception == 1) {
1954 if (arch_info->dr6 & (1 << 14)) {
1955 if (cpu_single_env->singlestep_enabled) {
1959 for (n = 0; n < 4; n++) {
1960 if (arch_info->dr6 & (1 << n)) {
1961 switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
1967 cpu_single_env->watchpoint_hit = &hw_watchpoint;
1968 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
1969 hw_watchpoint.flags = BP_MEM_WRITE;
1973 cpu_single_env->watchpoint_hit = &hw_watchpoint;
1974 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
1975 hw_watchpoint.flags = BP_MEM_ACCESS;
1981 } else if (kvm_find_sw_breakpoint(cpu_single_env, arch_info->pc)) {
1985 cpu_synchronize_state(cpu_single_env);
1986 assert(cpu_single_env->exception_injected == -1);
1989 cpu_single_env->exception_injected = arch_info->exception;
1990 cpu_single_env->has_error_code = 0;
1996 void kvm_arch_update_guest_debug(CPUX86State *env, struct kvm_guest_debug *dbg)
1998 const uint8_t type_code[] = {
1999 [GDB_BREAKPOINT_HW] = 0x0,
2000 [GDB_WATCHPOINT_WRITE] = 0x1,
2001 [GDB_WATCHPOINT_ACCESS] = 0x3
2003 const uint8_t len_code[] = {
2004 [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
2008 if (kvm_sw_breakpoints_active(env)) {
2009 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
2011 if (nb_hw_breakpoint > 0) {
2012 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
2013 dbg->arch.debugreg[7] = 0x0600;
2014 for (n = 0; n < nb_hw_breakpoint; n++) {
2015 dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
2016 dbg->arch.debugreg[7] |= (2 << (n * 2)) |
2017 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
2018 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
2023 static bool host_supports_vmx(void)
2025 uint32_t ecx, unused;
2027 host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
2028 return ecx & CPUID_EXT_VMX;
2031 #define VMX_INVALID_GUEST_STATE 0x80000021
2033 int kvm_arch_handle_exit(CPUX86State *env, struct kvm_run *run)
2035 X86CPU *cpu = x86_env_get_cpu(env);
2039 switch (run->exit_reason) {
2041 DPRINTF("handle_hlt\n");
2042 ret = kvm_handle_halt(cpu);
2044 case KVM_EXIT_SET_TPR:
2047 case KVM_EXIT_TPR_ACCESS:
2048 ret = kvm_handle_tpr_access(env);
2050 case KVM_EXIT_FAIL_ENTRY:
2051 code = run->fail_entry.hardware_entry_failure_reason;
2052 fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
2054 if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
2056 "\nIf you're running a guest on an Intel machine without "
2057 "unrestricted mode\n"
2058 "support, the failure can be most likely due to the guest "
2059 "entering an invalid\n"
2060 "state for Intel VT. For example, the guest maybe running "
2061 "in big real mode\n"
2062 "which is not supported on less recent Intel processors."
2067 case KVM_EXIT_EXCEPTION:
2068 fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
2069 run->ex.exception, run->ex.error_code);
2072 case KVM_EXIT_DEBUG:
2073 DPRINTF("kvm_exit_debug\n");
2074 ret = kvm_handle_debug(&run->debug.arch);
2077 fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
2085 bool kvm_arch_stop_on_emulation_error(CPUX86State *env)
2087 kvm_cpu_synchronize_state(env);
2088 return !(env->cr[0] & CR0_PE_MASK) ||
2089 ((env->segs[R_CS].selector & 3) != 3);
2092 void kvm_arch_init_irq_routing(KVMState *s)
2094 if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
2095 /* If kernel can't do irq routing, interrupt source
2096 * override 0->2 cannot be set up as required by HPET.
2097 * So we have to disable it.
2101 /* We know at this point that we're using the in-kernel
2102 * irqchip, so we can use irqfds, and on x86 we know
2103 * we can use msi via irqfd and GSI routing.
2105 kvm_irqfds_allowed = true;
2106 kvm_msi_via_irqfd_allowed = true;
2107 kvm_gsi_routing_allowed = true;
2110 /* Classic KVM device assignment interface. Will remain x86 only. */
2111 int kvm_device_pci_assign(KVMState *s, PCIHostDeviceAddress *dev_addr,
2112 uint32_t flags, uint32_t *dev_id)
2114 struct kvm_assigned_pci_dev dev_data = {
2115 .segnr = dev_addr->domain,
2116 .busnr = dev_addr->bus,
2117 .devfn = PCI_DEVFN(dev_addr->slot, dev_addr->function),
2122 dev_data.assigned_dev_id =
2123 (dev_addr->domain << 16) | (dev_addr->bus << 8) | dev_data.devfn;
2125 ret = kvm_vm_ioctl(s, KVM_ASSIGN_PCI_DEVICE, &dev_data);
2130 *dev_id = dev_data.assigned_dev_id;
2135 int kvm_device_pci_deassign(KVMState *s, uint32_t dev_id)
2137 struct kvm_assigned_pci_dev dev_data = {
2138 .assigned_dev_id = dev_id,
2141 return kvm_vm_ioctl(s, KVM_DEASSIGN_PCI_DEVICE, &dev_data);
2144 static int kvm_assign_irq_internal(KVMState *s, uint32_t dev_id,
2145 uint32_t irq_type, uint32_t guest_irq)
2147 struct kvm_assigned_irq assigned_irq = {
2148 .assigned_dev_id = dev_id,
2149 .guest_irq = guest_irq,
2153 if (kvm_check_extension(s, KVM_CAP_ASSIGN_DEV_IRQ)) {
2154 return kvm_vm_ioctl(s, KVM_ASSIGN_DEV_IRQ, &assigned_irq);
2156 return kvm_vm_ioctl(s, KVM_ASSIGN_IRQ, &assigned_irq);
2160 int kvm_device_intx_assign(KVMState *s, uint32_t dev_id, bool use_host_msi,
2163 uint32_t irq_type = KVM_DEV_IRQ_GUEST_INTX |
2164 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX);
2166 return kvm_assign_irq_internal(s, dev_id, irq_type, guest_irq);
2169 int kvm_device_intx_set_mask(KVMState *s, uint32_t dev_id, bool masked)
2171 struct kvm_assigned_pci_dev dev_data = {
2172 .assigned_dev_id = dev_id,
2173 .flags = masked ? KVM_DEV_ASSIGN_MASK_INTX : 0,
2176 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_INTX_MASK, &dev_data);
2179 static int kvm_deassign_irq_internal(KVMState *s, uint32_t dev_id,
2182 struct kvm_assigned_irq assigned_irq = {
2183 .assigned_dev_id = dev_id,
2187 return kvm_vm_ioctl(s, KVM_DEASSIGN_DEV_IRQ, &assigned_irq);
2190 int kvm_device_intx_deassign(KVMState *s, uint32_t dev_id, bool use_host_msi)
2192 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_INTX |
2193 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX));
2196 int kvm_device_msi_assign(KVMState *s, uint32_t dev_id, int virq)
2198 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSI |
2199 KVM_DEV_IRQ_GUEST_MSI, virq);
2202 int kvm_device_msi_deassign(KVMState *s, uint32_t dev_id)
2204 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSI |
2205 KVM_DEV_IRQ_HOST_MSI);
2208 bool kvm_device_msix_supported(KVMState *s)
2210 /* The kernel lacks a corresponding KVM_CAP, so we probe by calling
2211 * KVM_ASSIGN_SET_MSIX_NR with an invalid parameter. */
2212 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, NULL) == -EFAULT;
2215 int kvm_device_msix_init_vectors(KVMState *s, uint32_t dev_id,
2216 uint32_t nr_vectors)
2218 struct kvm_assigned_msix_nr msix_nr = {
2219 .assigned_dev_id = dev_id,
2220 .entry_nr = nr_vectors,
2223 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, &msix_nr);
2226 int kvm_device_msix_set_vector(KVMState *s, uint32_t dev_id, uint32_t vector,
2229 struct kvm_assigned_msix_entry msix_entry = {
2230 .assigned_dev_id = dev_id,
2235 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_ENTRY, &msix_entry);
2238 int kvm_device_msix_assign(KVMState *s, uint32_t dev_id)
2240 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSIX |
2241 KVM_DEV_IRQ_GUEST_MSIX, 0);
2244 int kvm_device_msix_deassign(KVMState *s, uint32_t dev_id)
2246 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSIX |
2247 KVM_DEV_IRQ_HOST_MSIX);