vfio/spapr: Create DMA window dynamically (SPAPR IOMMU v2)
[qemu.git] / target-i386 / kvm.c
blobf3698f19b53b92d1b941e89260d7e87da5b13909
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 <linux/kvm_para.h>
23 #include "qemu-common.h"
24 #include "cpu.h"
25 #include "sysemu/sysemu.h"
26 #include "sysemu/kvm_int.h"
27 #include "kvm_i386.h"
28 #include "hyperv.h"
30 #include "exec/gdbstub.h"
31 #include "qemu/host-utils.h"
32 #include "qemu/config-file.h"
33 #include "qemu/error-report.h"
34 #include "hw/i386/pc.h"
35 #include "hw/i386/apic.h"
36 #include "hw/i386/apic_internal.h"
37 #include "hw/i386/apic-msidef.h"
39 #include "exec/ioport.h"
40 #include "standard-headers/asm-x86/hyperv.h"
41 #include "hw/pci/pci.h"
42 #include "hw/pci/msi.h"
43 #include "migration/migration.h"
44 #include "exec/memattrs.h"
46 //#define DEBUG_KVM
48 #ifdef DEBUG_KVM
49 #define DPRINTF(fmt, ...) \
50 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
51 #else
52 #define DPRINTF(fmt, ...) \
53 do { } while (0)
54 #endif
56 #define MSR_KVM_WALL_CLOCK 0x11
57 #define MSR_KVM_SYSTEM_TIME 0x12
59 /* A 4096-byte buffer can hold the 8-byte kvm_msrs header, plus
60 * 255 kvm_msr_entry structs */
61 #define MSR_BUF_SIZE 4096
63 #ifndef BUS_MCEERR_AR
64 #define BUS_MCEERR_AR 4
65 #endif
66 #ifndef BUS_MCEERR_AO
67 #define BUS_MCEERR_AO 5
68 #endif
70 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
71 KVM_CAP_INFO(SET_TSS_ADDR),
72 KVM_CAP_INFO(EXT_CPUID),
73 KVM_CAP_INFO(MP_STATE),
74 KVM_CAP_LAST_INFO
77 static bool has_msr_star;
78 static bool has_msr_hsave_pa;
79 static bool has_msr_tsc_aux;
80 static bool has_msr_tsc_adjust;
81 static bool has_msr_tsc_deadline;
82 static bool has_msr_feature_control;
83 static bool has_msr_async_pf_en;
84 static bool has_msr_pv_eoi_en;
85 static bool has_msr_misc_enable;
86 static bool has_msr_smbase;
87 static bool has_msr_bndcfgs;
88 static bool has_msr_kvm_steal_time;
89 static int lm_capable_kernel;
90 static bool has_msr_hv_hypercall;
91 static bool has_msr_hv_vapic;
92 static bool has_msr_hv_tsc;
93 static bool has_msr_hv_crash;
94 static bool has_msr_hv_reset;
95 static bool has_msr_hv_vpindex;
96 static bool has_msr_hv_runtime;
97 static bool has_msr_hv_synic;
98 static bool has_msr_hv_stimer;
99 static bool has_msr_mtrr;
100 static bool has_msr_xss;
102 static bool has_msr_architectural_pmu;
103 static uint32_t num_architectural_pmu_counters;
105 static int has_xsave;
106 static int has_xcrs;
107 static int has_pit_state2;
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_allows_irq0_override(void)
123 return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
126 static int kvm_get_tsc(CPUState *cs)
128 X86CPU *cpu = X86_CPU(cs);
129 CPUX86State *env = &cpu->env;
130 struct {
131 struct kvm_msrs info;
132 struct kvm_msr_entry entries[1];
133 } msr_data;
134 int ret;
136 if (env->tsc_valid) {
137 return 0;
140 msr_data.info.nmsrs = 1;
141 msr_data.entries[0].index = MSR_IA32_TSC;
142 env->tsc_valid = !runstate_is_running();
144 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
145 if (ret < 0) {
146 return ret;
149 assert(ret == 1);
150 env->tsc = msr_data.entries[0].data;
151 return 0;
154 static inline void do_kvm_synchronize_tsc(void *arg)
156 CPUState *cpu = arg;
158 kvm_get_tsc(cpu);
161 void kvm_synchronize_all_tsc(void)
163 CPUState *cpu;
165 if (kvm_enabled()) {
166 CPU_FOREACH(cpu) {
167 run_on_cpu(cpu, do_kvm_synchronize_tsc, cpu);
172 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
174 struct kvm_cpuid2 *cpuid;
175 int r, size;
177 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
178 cpuid = g_malloc0(size);
179 cpuid->nent = max;
180 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
181 if (r == 0 && cpuid->nent >= max) {
182 r = -E2BIG;
184 if (r < 0) {
185 if (r == -E2BIG) {
186 g_free(cpuid);
187 return NULL;
188 } else {
189 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
190 strerror(-r));
191 exit(1);
194 return cpuid;
197 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
198 * for all entries.
200 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
202 struct kvm_cpuid2 *cpuid;
203 int max = 1;
205 if (cpuid_cache != NULL) {
206 return cpuid_cache;
208 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
209 max *= 2;
211 cpuid_cache = cpuid;
212 return cpuid;
215 static const struct kvm_para_features {
216 int cap;
217 int feature;
218 } para_features[] = {
219 { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
220 { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
221 { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
222 { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
225 static int get_para_features(KVMState *s)
227 int i, features = 0;
229 for (i = 0; i < ARRAY_SIZE(para_features); i++) {
230 if (kvm_check_extension(s, para_features[i].cap)) {
231 features |= (1 << para_features[i].feature);
235 return features;
239 /* Returns the value for a specific register on the cpuid entry
241 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
243 uint32_t ret = 0;
244 switch (reg) {
245 case R_EAX:
246 ret = entry->eax;
247 break;
248 case R_EBX:
249 ret = entry->ebx;
250 break;
251 case R_ECX:
252 ret = entry->ecx;
253 break;
254 case R_EDX:
255 ret = entry->edx;
256 break;
258 return ret;
261 /* Find matching entry for function/index on kvm_cpuid2 struct
263 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
264 uint32_t function,
265 uint32_t index)
267 int i;
268 for (i = 0; i < cpuid->nent; ++i) {
269 if (cpuid->entries[i].function == function &&
270 cpuid->entries[i].index == index) {
271 return &cpuid->entries[i];
274 /* not found: */
275 return NULL;
278 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
279 uint32_t index, int reg)
281 struct kvm_cpuid2 *cpuid;
282 uint32_t ret = 0;
283 uint32_t cpuid_1_edx;
284 bool found = false;
286 cpuid = get_supported_cpuid(s);
288 struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
289 if (entry) {
290 found = true;
291 ret = cpuid_entry_get_reg(entry, reg);
294 /* Fixups for the data returned by KVM, below */
296 if (function == 1 && reg == R_EDX) {
297 /* KVM before 2.6.30 misreports the following features */
298 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
299 } else if (function == 1 && reg == R_ECX) {
300 /* We can set the hypervisor flag, even if KVM does not return it on
301 * GET_SUPPORTED_CPUID
303 ret |= CPUID_EXT_HYPERVISOR;
304 /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
305 * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
306 * and the irqchip is in the kernel.
308 if (kvm_irqchip_in_kernel() &&
309 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
310 ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
313 /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
314 * without the in-kernel irqchip
316 if (!kvm_irqchip_in_kernel()) {
317 ret &= ~CPUID_EXT_X2APIC;
319 } else if (function == 6 && reg == R_EAX) {
320 ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
321 } else if (function == 0x80000001 && reg == R_EDX) {
322 /* On Intel, kvm returns cpuid according to the Intel spec,
323 * so add missing bits according to the AMD spec:
325 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
326 ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
329 /* fallback for older kernels */
330 if ((function == KVM_CPUID_FEATURES) && !found) {
331 ret = get_para_features(s);
334 return ret;
337 typedef struct HWPoisonPage {
338 ram_addr_t ram_addr;
339 QLIST_ENTRY(HWPoisonPage) list;
340 } HWPoisonPage;
342 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
343 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
345 static void kvm_unpoison_all(void *param)
347 HWPoisonPage *page, *next_page;
349 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
350 QLIST_REMOVE(page, list);
351 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
352 g_free(page);
356 static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
358 HWPoisonPage *page;
360 QLIST_FOREACH(page, &hwpoison_page_list, list) {
361 if (page->ram_addr == ram_addr) {
362 return;
365 page = g_new(HWPoisonPage, 1);
366 page->ram_addr = ram_addr;
367 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
370 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
371 int *max_banks)
373 int r;
375 r = kvm_check_extension(s, KVM_CAP_MCE);
376 if (r > 0) {
377 *max_banks = r;
378 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
380 return -ENOSYS;
383 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
385 CPUX86State *env = &cpu->env;
386 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
387 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
388 uint64_t mcg_status = MCG_STATUS_MCIP;
390 if (code == BUS_MCEERR_AR) {
391 status |= MCI_STATUS_AR | 0x134;
392 mcg_status |= MCG_STATUS_EIPV;
393 } else {
394 status |= 0xc0;
395 mcg_status |= MCG_STATUS_RIPV;
397 cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
398 (MCM_ADDR_PHYS << 6) | 0xc,
399 cpu_x86_support_mca_broadcast(env) ?
400 MCE_INJECT_BROADCAST : 0);
403 static void hardware_memory_error(void)
405 fprintf(stderr, "Hardware memory error!\n");
406 exit(1);
409 int kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
411 X86CPU *cpu = X86_CPU(c);
412 CPUX86State *env = &cpu->env;
413 ram_addr_t ram_addr;
414 hwaddr paddr;
416 if ((env->mcg_cap & MCG_SER_P) && addr
417 && (code == BUS_MCEERR_AR || code == BUS_MCEERR_AO)) {
418 ram_addr = qemu_ram_addr_from_host(addr);
419 if (ram_addr == RAM_ADDR_INVALID ||
420 !kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
421 fprintf(stderr, "Hardware memory error for memory used by "
422 "QEMU itself instead of guest system!\n");
423 /* Hope we are lucky for AO MCE */
424 if (code == BUS_MCEERR_AO) {
425 return 0;
426 } else {
427 hardware_memory_error();
430 kvm_hwpoison_page_add(ram_addr);
431 kvm_mce_inject(cpu, paddr, code);
432 } else {
433 if (code == BUS_MCEERR_AO) {
434 return 0;
435 } else if (code == BUS_MCEERR_AR) {
436 hardware_memory_error();
437 } else {
438 return 1;
441 return 0;
444 int kvm_arch_on_sigbus(int code, void *addr)
446 X86CPU *cpu = X86_CPU(first_cpu);
448 if ((cpu->env.mcg_cap & MCG_SER_P) && addr && code == BUS_MCEERR_AO) {
449 ram_addr_t ram_addr;
450 hwaddr paddr;
452 /* Hope we are lucky for AO MCE */
453 ram_addr = qemu_ram_addr_from_host(addr);
454 if (ram_addr == RAM_ADDR_INVALID ||
455 !kvm_physical_memory_addr_from_host(first_cpu->kvm_state,
456 addr, &paddr)) {
457 fprintf(stderr, "Hardware memory error for memory used by "
458 "QEMU itself instead of guest system!: %p\n", addr);
459 return 0;
461 kvm_hwpoison_page_add(ram_addr);
462 kvm_mce_inject(X86_CPU(first_cpu), paddr, code);
463 } else {
464 if (code == BUS_MCEERR_AO) {
465 return 0;
466 } else if (code == BUS_MCEERR_AR) {
467 hardware_memory_error();
468 } else {
469 return 1;
472 return 0;
475 static int kvm_inject_mce_oldstyle(X86CPU *cpu)
477 CPUX86State *env = &cpu->env;
479 if (!kvm_has_vcpu_events() && env->exception_injected == EXCP12_MCHK) {
480 unsigned int bank, bank_num = env->mcg_cap & 0xff;
481 struct kvm_x86_mce mce;
483 env->exception_injected = -1;
486 * There must be at least one bank in use if an MCE is pending.
487 * Find it and use its values for the event injection.
489 for (bank = 0; bank < bank_num; bank++) {
490 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
491 break;
494 assert(bank < bank_num);
496 mce.bank = bank;
497 mce.status = env->mce_banks[bank * 4 + 1];
498 mce.mcg_status = env->mcg_status;
499 mce.addr = env->mce_banks[bank * 4 + 2];
500 mce.misc = env->mce_banks[bank * 4 + 3];
502 return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
504 return 0;
507 static void cpu_update_state(void *opaque, int running, RunState state)
509 CPUX86State *env = opaque;
511 if (running) {
512 env->tsc_valid = false;
516 unsigned long kvm_arch_vcpu_id(CPUState *cs)
518 X86CPU *cpu = X86_CPU(cs);
519 return cpu->apic_id;
522 #ifndef KVM_CPUID_SIGNATURE_NEXT
523 #define KVM_CPUID_SIGNATURE_NEXT 0x40000100
524 #endif
526 static bool hyperv_hypercall_available(X86CPU *cpu)
528 return cpu->hyperv_vapic ||
529 (cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY);
532 static bool hyperv_enabled(X86CPU *cpu)
534 CPUState *cs = CPU(cpu);
535 return kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0 &&
536 (hyperv_hypercall_available(cpu) ||
537 cpu->hyperv_time ||
538 cpu->hyperv_relaxed_timing ||
539 cpu->hyperv_crash ||
540 cpu->hyperv_reset ||
541 cpu->hyperv_vpindex ||
542 cpu->hyperv_runtime ||
543 cpu->hyperv_synic ||
544 cpu->hyperv_stimer);
547 static int kvm_arch_set_tsc_khz(CPUState *cs)
549 X86CPU *cpu = X86_CPU(cs);
550 CPUX86State *env = &cpu->env;
551 int r;
553 if (!env->tsc_khz) {
554 return 0;
557 r = kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL) ?
558 kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) :
559 -ENOTSUP;
560 if (r < 0) {
561 /* When KVM_SET_TSC_KHZ fails, it's an error only if the current
562 * TSC frequency doesn't match the one we want.
564 int cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
565 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
566 -ENOTSUP;
567 if (cur_freq <= 0 || cur_freq != env->tsc_khz) {
568 error_report("warning: TSC frequency mismatch between "
569 "VM and host, and TSC scaling unavailable");
570 return r;
574 return 0;
577 static Error *invtsc_mig_blocker;
579 #define KVM_MAX_CPUID_ENTRIES 100
581 int kvm_arch_init_vcpu(CPUState *cs)
583 struct {
584 struct kvm_cpuid2 cpuid;
585 struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
586 } QEMU_PACKED cpuid_data;
587 X86CPU *cpu = X86_CPU(cs);
588 CPUX86State *env = &cpu->env;
589 uint32_t limit, i, j, cpuid_i;
590 uint32_t unused;
591 struct kvm_cpuid_entry2 *c;
592 uint32_t signature[3];
593 int kvm_base = KVM_CPUID_SIGNATURE;
594 int r;
596 memset(&cpuid_data, 0, sizeof(cpuid_data));
598 cpuid_i = 0;
600 /* Paravirtualization CPUIDs */
601 if (hyperv_enabled(cpu)) {
602 c = &cpuid_data.entries[cpuid_i++];
603 c->function = HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
604 if (!cpu->hyperv_vendor_id) {
605 memcpy(signature, "Microsoft Hv", 12);
606 } else {
607 size_t len = strlen(cpu->hyperv_vendor_id);
609 if (len > 12) {
610 error_report("hv-vendor-id truncated to 12 characters");
611 len = 12;
613 memset(signature, 0, 12);
614 memcpy(signature, cpu->hyperv_vendor_id, len);
616 c->eax = HYPERV_CPUID_MIN;
617 c->ebx = signature[0];
618 c->ecx = signature[1];
619 c->edx = signature[2];
621 c = &cpuid_data.entries[cpuid_i++];
622 c->function = HYPERV_CPUID_INTERFACE;
623 memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
624 c->eax = signature[0];
625 c->ebx = 0;
626 c->ecx = 0;
627 c->edx = 0;
629 c = &cpuid_data.entries[cpuid_i++];
630 c->function = HYPERV_CPUID_VERSION;
631 c->eax = 0x00001bbc;
632 c->ebx = 0x00060001;
634 c = &cpuid_data.entries[cpuid_i++];
635 c->function = HYPERV_CPUID_FEATURES;
636 if (cpu->hyperv_relaxed_timing) {
637 c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
639 if (cpu->hyperv_vapic) {
640 c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
641 c->eax |= HV_X64_MSR_APIC_ACCESS_AVAILABLE;
642 has_msr_hv_vapic = true;
644 if (cpu->hyperv_time &&
645 kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) > 0) {
646 c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
647 c->eax |= HV_X64_MSR_TIME_REF_COUNT_AVAILABLE;
648 c->eax |= 0x200;
649 has_msr_hv_tsc = true;
651 if (cpu->hyperv_crash && has_msr_hv_crash) {
652 c->edx |= HV_X64_GUEST_CRASH_MSR_AVAILABLE;
654 c->edx |= HV_X64_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
655 if (cpu->hyperv_reset && has_msr_hv_reset) {
656 c->eax |= HV_X64_MSR_RESET_AVAILABLE;
658 if (cpu->hyperv_vpindex && has_msr_hv_vpindex) {
659 c->eax |= HV_X64_MSR_VP_INDEX_AVAILABLE;
661 if (cpu->hyperv_runtime && has_msr_hv_runtime) {
662 c->eax |= HV_X64_MSR_VP_RUNTIME_AVAILABLE;
664 if (cpu->hyperv_synic) {
665 int sint;
667 if (!has_msr_hv_synic ||
668 kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_SYNIC, 0)) {
669 fprintf(stderr, "Hyper-V SynIC is not supported by kernel\n");
670 return -ENOSYS;
673 c->eax |= HV_X64_MSR_SYNIC_AVAILABLE;
674 env->msr_hv_synic_version = HV_SYNIC_VERSION_1;
675 for (sint = 0; sint < ARRAY_SIZE(env->msr_hv_synic_sint); sint++) {
676 env->msr_hv_synic_sint[sint] = HV_SYNIC_SINT_MASKED;
679 if (cpu->hyperv_stimer) {
680 if (!has_msr_hv_stimer) {
681 fprintf(stderr, "Hyper-V timers aren't supported by kernel\n");
682 return -ENOSYS;
684 c->eax |= HV_X64_MSR_SYNTIMER_AVAILABLE;
686 c = &cpuid_data.entries[cpuid_i++];
687 c->function = HYPERV_CPUID_ENLIGHTMENT_INFO;
688 if (cpu->hyperv_relaxed_timing) {
689 c->eax |= HV_X64_RELAXED_TIMING_RECOMMENDED;
691 if (has_msr_hv_vapic) {
692 c->eax |= HV_X64_APIC_ACCESS_RECOMMENDED;
694 c->ebx = cpu->hyperv_spinlock_attempts;
696 c = &cpuid_data.entries[cpuid_i++];
697 c->function = HYPERV_CPUID_IMPLEMENT_LIMITS;
698 c->eax = 0x40;
699 c->ebx = 0x40;
701 kvm_base = KVM_CPUID_SIGNATURE_NEXT;
702 has_msr_hv_hypercall = true;
705 if (cpu->expose_kvm) {
706 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
707 c = &cpuid_data.entries[cpuid_i++];
708 c->function = KVM_CPUID_SIGNATURE | kvm_base;
709 c->eax = KVM_CPUID_FEATURES | kvm_base;
710 c->ebx = signature[0];
711 c->ecx = signature[1];
712 c->edx = signature[2];
714 c = &cpuid_data.entries[cpuid_i++];
715 c->function = KVM_CPUID_FEATURES | kvm_base;
716 c->eax = env->features[FEAT_KVM];
718 has_msr_async_pf_en = c->eax & (1 << KVM_FEATURE_ASYNC_PF);
720 has_msr_pv_eoi_en = c->eax & (1 << KVM_FEATURE_PV_EOI);
722 has_msr_kvm_steal_time = c->eax & (1 << KVM_FEATURE_STEAL_TIME);
725 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
727 for (i = 0; i <= limit; i++) {
728 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
729 fprintf(stderr, "unsupported level value: 0x%x\n", limit);
730 abort();
732 c = &cpuid_data.entries[cpuid_i++];
734 switch (i) {
735 case 2: {
736 /* Keep reading function 2 till all the input is received */
737 int times;
739 c->function = i;
740 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
741 KVM_CPUID_FLAG_STATE_READ_NEXT;
742 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
743 times = c->eax & 0xff;
745 for (j = 1; j < times; ++j) {
746 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
747 fprintf(stderr, "cpuid_data is full, no space for "
748 "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
749 abort();
751 c = &cpuid_data.entries[cpuid_i++];
752 c->function = i;
753 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
754 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
756 break;
758 case 4:
759 case 0xb:
760 case 0xd:
761 for (j = 0; ; j++) {
762 if (i == 0xd && j == 64) {
763 break;
765 c->function = i;
766 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
767 c->index = j;
768 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
770 if (i == 4 && c->eax == 0) {
771 break;
773 if (i == 0xb && !(c->ecx & 0xff00)) {
774 break;
776 if (i == 0xd && c->eax == 0) {
777 continue;
779 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
780 fprintf(stderr, "cpuid_data is full, no space for "
781 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
782 abort();
784 c = &cpuid_data.entries[cpuid_i++];
786 break;
787 default:
788 c->function = i;
789 c->flags = 0;
790 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
791 break;
795 if (limit >= 0x0a) {
796 uint32_t ver;
798 cpu_x86_cpuid(env, 0x0a, 0, &ver, &unused, &unused, &unused);
799 if ((ver & 0xff) > 0) {
800 has_msr_architectural_pmu = true;
801 num_architectural_pmu_counters = (ver & 0xff00) >> 8;
803 /* Shouldn't be more than 32, since that's the number of bits
804 * available in EBX to tell us _which_ counters are available.
805 * Play it safe.
807 if (num_architectural_pmu_counters > MAX_GP_COUNTERS) {
808 num_architectural_pmu_counters = MAX_GP_COUNTERS;
813 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
815 for (i = 0x80000000; i <= limit; i++) {
816 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
817 fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
818 abort();
820 c = &cpuid_data.entries[cpuid_i++];
822 c->function = i;
823 c->flags = 0;
824 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
827 /* Call Centaur's CPUID instructions they are supported. */
828 if (env->cpuid_xlevel2 > 0) {
829 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
831 for (i = 0xC0000000; i <= limit; i++) {
832 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
833 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
834 abort();
836 c = &cpuid_data.entries[cpuid_i++];
838 c->function = i;
839 c->flags = 0;
840 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
844 cpuid_data.cpuid.nent = cpuid_i;
846 if (((env->cpuid_version >> 8)&0xF) >= 6
847 && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
848 (CPUID_MCE | CPUID_MCA)
849 && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
850 uint64_t mcg_cap, unsupported_caps;
851 int banks;
852 int ret;
854 ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
855 if (ret < 0) {
856 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
857 return ret;
860 if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
861 error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
862 (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
863 return -ENOTSUP;
866 unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
867 if (unsupported_caps) {
868 error_report("warning: Unsupported MCG_CAP bits: 0x%" PRIx64,
869 unsupported_caps);
872 env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
873 ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
874 if (ret < 0) {
875 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
876 return ret;
880 qemu_add_vm_change_state_handler(cpu_update_state, env);
882 c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
883 if (c) {
884 has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
885 !!(c->ecx & CPUID_EXT_SMX);
888 c = cpuid_find_entry(&cpuid_data.cpuid, 0x80000007, 0);
889 if (c && (c->edx & 1<<8) && invtsc_mig_blocker == NULL) {
890 /* for migration */
891 error_setg(&invtsc_mig_blocker,
892 "State blocked by non-migratable CPU device"
893 " (invtsc flag)");
894 migrate_add_blocker(invtsc_mig_blocker);
895 /* for savevm */
896 vmstate_x86_cpu.unmigratable = 1;
899 cpuid_data.cpuid.padding = 0;
900 r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
901 if (r) {
902 return r;
905 r = kvm_arch_set_tsc_khz(cs);
906 if (r < 0) {
907 return r;
910 /* vcpu's TSC frequency is either specified by user, or following
911 * the value used by KVM if the former is not present. In the
912 * latter case, we query it from KVM and record in env->tsc_khz,
913 * so that vcpu's TSC frequency can be migrated later via this field.
915 if (!env->tsc_khz) {
916 r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
917 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
918 -ENOTSUP;
919 if (r > 0) {
920 env->tsc_khz = r;
924 if (has_xsave) {
925 env->kvm_xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
927 cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
929 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
930 has_msr_mtrr = true;
932 if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
933 has_msr_tsc_aux = false;
936 return 0;
939 void kvm_arch_reset_vcpu(X86CPU *cpu)
941 CPUX86State *env = &cpu->env;
943 env->exception_injected = -1;
944 env->interrupt_injected = -1;
945 env->xcr0 = 1;
946 if (kvm_irqchip_in_kernel()) {
947 env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
948 KVM_MP_STATE_UNINITIALIZED;
949 } else {
950 env->mp_state = KVM_MP_STATE_RUNNABLE;
954 void kvm_arch_do_init_vcpu(X86CPU *cpu)
956 CPUX86State *env = &cpu->env;
958 /* APs get directly into wait-for-SIPI state. */
959 if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
960 env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
964 static int kvm_get_supported_msrs(KVMState *s)
966 static int kvm_supported_msrs;
967 int ret = 0;
969 /* first time */
970 if (kvm_supported_msrs == 0) {
971 struct kvm_msr_list msr_list, *kvm_msr_list;
973 kvm_supported_msrs = -1;
975 /* Obtain MSR list from KVM. These are the MSRs that we must
976 * save/restore */
977 msr_list.nmsrs = 0;
978 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
979 if (ret < 0 && ret != -E2BIG) {
980 return ret;
982 /* Old kernel modules had a bug and could write beyond the provided
983 memory. Allocate at least a safe amount of 1K. */
984 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
985 msr_list.nmsrs *
986 sizeof(msr_list.indices[0])));
988 kvm_msr_list->nmsrs = msr_list.nmsrs;
989 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
990 if (ret >= 0) {
991 int i;
993 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
994 if (kvm_msr_list->indices[i] == MSR_STAR) {
995 has_msr_star = true;
996 continue;
998 if (kvm_msr_list->indices[i] == MSR_VM_HSAVE_PA) {
999 has_msr_hsave_pa = true;
1000 continue;
1002 if (kvm_msr_list->indices[i] == MSR_TSC_AUX) {
1003 has_msr_tsc_aux = true;
1004 continue;
1006 if (kvm_msr_list->indices[i] == MSR_TSC_ADJUST) {
1007 has_msr_tsc_adjust = true;
1008 continue;
1010 if (kvm_msr_list->indices[i] == MSR_IA32_TSCDEADLINE) {
1011 has_msr_tsc_deadline = true;
1012 continue;
1014 if (kvm_msr_list->indices[i] == MSR_IA32_SMBASE) {
1015 has_msr_smbase = true;
1016 continue;
1018 if (kvm_msr_list->indices[i] == MSR_IA32_MISC_ENABLE) {
1019 has_msr_misc_enable = true;
1020 continue;
1022 if (kvm_msr_list->indices[i] == MSR_IA32_BNDCFGS) {
1023 has_msr_bndcfgs = true;
1024 continue;
1026 if (kvm_msr_list->indices[i] == MSR_IA32_XSS) {
1027 has_msr_xss = true;
1028 continue;
1030 if (kvm_msr_list->indices[i] == HV_X64_MSR_CRASH_CTL) {
1031 has_msr_hv_crash = true;
1032 continue;
1034 if (kvm_msr_list->indices[i] == HV_X64_MSR_RESET) {
1035 has_msr_hv_reset = true;
1036 continue;
1038 if (kvm_msr_list->indices[i] == HV_X64_MSR_VP_INDEX) {
1039 has_msr_hv_vpindex = true;
1040 continue;
1042 if (kvm_msr_list->indices[i] == HV_X64_MSR_VP_RUNTIME) {
1043 has_msr_hv_runtime = true;
1044 continue;
1046 if (kvm_msr_list->indices[i] == HV_X64_MSR_SCONTROL) {
1047 has_msr_hv_synic = true;
1048 continue;
1050 if (kvm_msr_list->indices[i] == HV_X64_MSR_STIMER0_CONFIG) {
1051 has_msr_hv_stimer = true;
1052 continue;
1057 g_free(kvm_msr_list);
1060 return ret;
1063 static Notifier smram_machine_done;
1064 static KVMMemoryListener smram_listener;
1065 static AddressSpace smram_address_space;
1066 static MemoryRegion smram_as_root;
1067 static MemoryRegion smram_as_mem;
1069 static void register_smram_listener(Notifier *n, void *unused)
1071 MemoryRegion *smram =
1072 (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
1074 /* Outer container... */
1075 memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
1076 memory_region_set_enabled(&smram_as_root, true);
1078 /* ... with two regions inside: normal system memory with low
1079 * priority, and...
1081 memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
1082 get_system_memory(), 0, ~0ull);
1083 memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
1084 memory_region_set_enabled(&smram_as_mem, true);
1086 if (smram) {
1087 /* ... SMRAM with higher priority */
1088 memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
1089 memory_region_set_enabled(smram, true);
1092 address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
1093 kvm_memory_listener_register(kvm_state, &smram_listener,
1094 &smram_address_space, 1);
1097 int kvm_arch_init(MachineState *ms, KVMState *s)
1099 uint64_t identity_base = 0xfffbc000;
1100 uint64_t shadow_mem;
1101 int ret;
1102 struct utsname utsname;
1104 #ifdef KVM_CAP_XSAVE
1105 has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1106 #endif
1108 #ifdef KVM_CAP_XCRS
1109 has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1110 #endif
1112 #ifdef KVM_CAP_PIT_STATE2
1113 has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1114 #endif
1116 ret = kvm_get_supported_msrs(s);
1117 if (ret < 0) {
1118 return ret;
1121 uname(&utsname);
1122 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
1125 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
1126 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
1127 * Since these must be part of guest physical memory, we need to allocate
1128 * them, both by setting their start addresses in the kernel and by
1129 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
1131 * Older KVM versions may not support setting the identity map base. In
1132 * that case we need to stick with the default, i.e. a 256K maximum BIOS
1133 * size.
1135 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
1136 /* Allows up to 16M BIOSes. */
1137 identity_base = 0xfeffc000;
1139 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
1140 if (ret < 0) {
1141 return ret;
1145 /* Set TSS base one page after EPT identity map. */
1146 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
1147 if (ret < 0) {
1148 return ret;
1151 /* Tell fw_cfg to notify the BIOS to reserve the range. */
1152 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
1153 if (ret < 0) {
1154 fprintf(stderr, "e820_add_entry() table is full\n");
1155 return ret;
1157 qemu_register_reset(kvm_unpoison_all, NULL);
1159 shadow_mem = machine_kvm_shadow_mem(ms);
1160 if (shadow_mem != -1) {
1161 shadow_mem /= 4096;
1162 ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
1163 if (ret < 0) {
1164 return ret;
1168 if (kvm_check_extension(s, KVM_CAP_X86_SMM)) {
1169 smram_machine_done.notify = register_smram_listener;
1170 qemu_add_machine_init_done_notifier(&smram_machine_done);
1172 return 0;
1175 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1177 lhs->selector = rhs->selector;
1178 lhs->base = rhs->base;
1179 lhs->limit = rhs->limit;
1180 lhs->type = 3;
1181 lhs->present = 1;
1182 lhs->dpl = 3;
1183 lhs->db = 0;
1184 lhs->s = 1;
1185 lhs->l = 0;
1186 lhs->g = 0;
1187 lhs->avl = 0;
1188 lhs->unusable = 0;
1191 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1193 unsigned flags = rhs->flags;
1194 lhs->selector = rhs->selector;
1195 lhs->base = rhs->base;
1196 lhs->limit = rhs->limit;
1197 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
1198 lhs->present = (flags & DESC_P_MASK) != 0;
1199 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
1200 lhs->db = (flags >> DESC_B_SHIFT) & 1;
1201 lhs->s = (flags & DESC_S_MASK) != 0;
1202 lhs->l = (flags >> DESC_L_SHIFT) & 1;
1203 lhs->g = (flags & DESC_G_MASK) != 0;
1204 lhs->avl = (flags & DESC_AVL_MASK) != 0;
1205 lhs->unusable = !lhs->present;
1206 lhs->padding = 0;
1209 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
1211 lhs->selector = rhs->selector;
1212 lhs->base = rhs->base;
1213 lhs->limit = rhs->limit;
1214 if (rhs->unusable) {
1215 lhs->flags = 0;
1216 } else {
1217 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
1218 (rhs->present * DESC_P_MASK) |
1219 (rhs->dpl << DESC_DPL_SHIFT) |
1220 (rhs->db << DESC_B_SHIFT) |
1221 (rhs->s * DESC_S_MASK) |
1222 (rhs->l << DESC_L_SHIFT) |
1223 (rhs->g * DESC_G_MASK) |
1224 (rhs->avl * DESC_AVL_MASK);
1228 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
1230 if (set) {
1231 *kvm_reg = *qemu_reg;
1232 } else {
1233 *qemu_reg = *kvm_reg;
1237 static int kvm_getput_regs(X86CPU *cpu, int set)
1239 CPUX86State *env = &cpu->env;
1240 struct kvm_regs regs;
1241 int ret = 0;
1243 if (!set) {
1244 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
1245 if (ret < 0) {
1246 return ret;
1250 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
1251 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
1252 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
1253 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
1254 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
1255 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
1256 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
1257 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
1258 #ifdef TARGET_X86_64
1259 kvm_getput_reg(&regs.r8, &env->regs[8], set);
1260 kvm_getput_reg(&regs.r9, &env->regs[9], set);
1261 kvm_getput_reg(&regs.r10, &env->regs[10], set);
1262 kvm_getput_reg(&regs.r11, &env->regs[11], set);
1263 kvm_getput_reg(&regs.r12, &env->regs[12], set);
1264 kvm_getput_reg(&regs.r13, &env->regs[13], set);
1265 kvm_getput_reg(&regs.r14, &env->regs[14], set);
1266 kvm_getput_reg(&regs.r15, &env->regs[15], set);
1267 #endif
1269 kvm_getput_reg(&regs.rflags, &env->eflags, set);
1270 kvm_getput_reg(&regs.rip, &env->eip, set);
1272 if (set) {
1273 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
1276 return ret;
1279 static int kvm_put_fpu(X86CPU *cpu)
1281 CPUX86State *env = &cpu->env;
1282 struct kvm_fpu fpu;
1283 int i;
1285 memset(&fpu, 0, sizeof fpu);
1286 fpu.fsw = env->fpus & ~(7 << 11);
1287 fpu.fsw |= (env->fpstt & 7) << 11;
1288 fpu.fcw = env->fpuc;
1289 fpu.last_opcode = env->fpop;
1290 fpu.last_ip = env->fpip;
1291 fpu.last_dp = env->fpdp;
1292 for (i = 0; i < 8; ++i) {
1293 fpu.ftwx |= (!env->fptags[i]) << i;
1295 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
1296 for (i = 0; i < CPU_NB_REGS; i++) {
1297 stq_p(&fpu.xmm[i][0], env->xmm_regs[i].ZMM_Q(0));
1298 stq_p(&fpu.xmm[i][8], env->xmm_regs[i].ZMM_Q(1));
1300 fpu.mxcsr = env->mxcsr;
1302 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
1305 #define XSAVE_FCW_FSW 0
1306 #define XSAVE_FTW_FOP 1
1307 #define XSAVE_CWD_RIP 2
1308 #define XSAVE_CWD_RDP 4
1309 #define XSAVE_MXCSR 6
1310 #define XSAVE_ST_SPACE 8
1311 #define XSAVE_XMM_SPACE 40
1312 #define XSAVE_XSTATE_BV 128
1313 #define XSAVE_YMMH_SPACE 144
1314 #define XSAVE_BNDREGS 240
1315 #define XSAVE_BNDCSR 256
1316 #define XSAVE_OPMASK 272
1317 #define XSAVE_ZMM_Hi256 288
1318 #define XSAVE_Hi16_ZMM 416
1319 #define XSAVE_PKRU 672
1321 #define XSAVE_BYTE_OFFSET(word_offset) \
1322 ((word_offset) * sizeof(((struct kvm_xsave *)0)->region[0]))
1324 #define ASSERT_OFFSET(word_offset, field) \
1325 QEMU_BUILD_BUG_ON(XSAVE_BYTE_OFFSET(word_offset) != \
1326 offsetof(X86XSaveArea, field))
1328 ASSERT_OFFSET(XSAVE_FCW_FSW, legacy.fcw);
1329 ASSERT_OFFSET(XSAVE_FTW_FOP, legacy.ftw);
1330 ASSERT_OFFSET(XSAVE_CWD_RIP, legacy.fpip);
1331 ASSERT_OFFSET(XSAVE_CWD_RDP, legacy.fpdp);
1332 ASSERT_OFFSET(XSAVE_MXCSR, legacy.mxcsr);
1333 ASSERT_OFFSET(XSAVE_ST_SPACE, legacy.fpregs);
1334 ASSERT_OFFSET(XSAVE_XMM_SPACE, legacy.xmm_regs);
1335 ASSERT_OFFSET(XSAVE_XSTATE_BV, header.xstate_bv);
1336 ASSERT_OFFSET(XSAVE_YMMH_SPACE, avx_state);
1337 ASSERT_OFFSET(XSAVE_BNDREGS, bndreg_state);
1338 ASSERT_OFFSET(XSAVE_BNDCSR, bndcsr_state);
1339 ASSERT_OFFSET(XSAVE_OPMASK, opmask_state);
1340 ASSERT_OFFSET(XSAVE_ZMM_Hi256, zmm_hi256_state);
1341 ASSERT_OFFSET(XSAVE_Hi16_ZMM, hi16_zmm_state);
1342 ASSERT_OFFSET(XSAVE_PKRU, pkru_state);
1344 static int kvm_put_xsave(X86CPU *cpu)
1346 CPUX86State *env = &cpu->env;
1347 X86XSaveArea *xsave = env->kvm_xsave_buf;
1348 uint16_t cwd, swd, twd;
1349 int i;
1351 if (!has_xsave) {
1352 return kvm_put_fpu(cpu);
1355 memset(xsave, 0, sizeof(struct kvm_xsave));
1356 twd = 0;
1357 swd = env->fpus & ~(7 << 11);
1358 swd |= (env->fpstt & 7) << 11;
1359 cwd = env->fpuc;
1360 for (i = 0; i < 8; ++i) {
1361 twd |= (!env->fptags[i]) << i;
1363 xsave->legacy.fcw = cwd;
1364 xsave->legacy.fsw = swd;
1365 xsave->legacy.ftw = twd;
1366 xsave->legacy.fpop = env->fpop;
1367 xsave->legacy.fpip = env->fpip;
1368 xsave->legacy.fpdp = env->fpdp;
1369 memcpy(&xsave->legacy.fpregs, env->fpregs,
1370 sizeof env->fpregs);
1371 xsave->legacy.mxcsr = env->mxcsr;
1372 xsave->header.xstate_bv = env->xstate_bv;
1373 memcpy(&xsave->bndreg_state.bnd_regs, env->bnd_regs,
1374 sizeof env->bnd_regs);
1375 xsave->bndcsr_state.bndcsr = env->bndcs_regs;
1376 memcpy(&xsave->opmask_state.opmask_regs, env->opmask_regs,
1377 sizeof env->opmask_regs);
1379 for (i = 0; i < CPU_NB_REGS; i++) {
1380 uint8_t *xmm = xsave->legacy.xmm_regs[i];
1381 uint8_t *ymmh = xsave->avx_state.ymmh[i];
1382 uint8_t *zmmh = xsave->zmm_hi256_state.zmm_hi256[i];
1383 stq_p(xmm, env->xmm_regs[i].ZMM_Q(0));
1384 stq_p(xmm+8, env->xmm_regs[i].ZMM_Q(1));
1385 stq_p(ymmh, env->xmm_regs[i].ZMM_Q(2));
1386 stq_p(ymmh+8, env->xmm_regs[i].ZMM_Q(3));
1387 stq_p(zmmh, env->xmm_regs[i].ZMM_Q(4));
1388 stq_p(zmmh+8, env->xmm_regs[i].ZMM_Q(5));
1389 stq_p(zmmh+16, env->xmm_regs[i].ZMM_Q(6));
1390 stq_p(zmmh+24, env->xmm_regs[i].ZMM_Q(7));
1393 #ifdef TARGET_X86_64
1394 memcpy(&xsave->hi16_zmm_state.hi16_zmm, &env->xmm_regs[16],
1395 16 * sizeof env->xmm_regs[16]);
1396 memcpy(&xsave->pkru_state, &env->pkru, sizeof env->pkru);
1397 #endif
1398 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
1401 static int kvm_put_xcrs(X86CPU *cpu)
1403 CPUX86State *env = &cpu->env;
1404 struct kvm_xcrs xcrs = {};
1406 if (!has_xcrs) {
1407 return 0;
1410 xcrs.nr_xcrs = 1;
1411 xcrs.flags = 0;
1412 xcrs.xcrs[0].xcr = 0;
1413 xcrs.xcrs[0].value = env->xcr0;
1414 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
1417 static int kvm_put_sregs(X86CPU *cpu)
1419 CPUX86State *env = &cpu->env;
1420 struct kvm_sregs sregs;
1422 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
1423 if (env->interrupt_injected >= 0) {
1424 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
1425 (uint64_t)1 << (env->interrupt_injected % 64);
1428 if ((env->eflags & VM_MASK)) {
1429 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
1430 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
1431 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
1432 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
1433 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
1434 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
1435 } else {
1436 set_seg(&sregs.cs, &env->segs[R_CS]);
1437 set_seg(&sregs.ds, &env->segs[R_DS]);
1438 set_seg(&sregs.es, &env->segs[R_ES]);
1439 set_seg(&sregs.fs, &env->segs[R_FS]);
1440 set_seg(&sregs.gs, &env->segs[R_GS]);
1441 set_seg(&sregs.ss, &env->segs[R_SS]);
1444 set_seg(&sregs.tr, &env->tr);
1445 set_seg(&sregs.ldt, &env->ldt);
1447 sregs.idt.limit = env->idt.limit;
1448 sregs.idt.base = env->idt.base;
1449 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
1450 sregs.gdt.limit = env->gdt.limit;
1451 sregs.gdt.base = env->gdt.base;
1452 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
1454 sregs.cr0 = env->cr[0];
1455 sregs.cr2 = env->cr[2];
1456 sregs.cr3 = env->cr[3];
1457 sregs.cr4 = env->cr[4];
1459 sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
1460 sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
1462 sregs.efer = env->efer;
1464 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
1467 static void kvm_msr_buf_reset(X86CPU *cpu)
1469 memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
1472 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
1474 struct kvm_msrs *msrs = cpu->kvm_msr_buf;
1475 void *limit = ((void *)msrs) + MSR_BUF_SIZE;
1476 struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
1478 assert((void *)(entry + 1) <= limit);
1480 entry->index = index;
1481 entry->reserved = 0;
1482 entry->data = value;
1483 msrs->nmsrs++;
1486 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
1488 CPUX86State *env = &cpu->env;
1489 int ret;
1491 if (!has_msr_tsc_deadline) {
1492 return 0;
1495 kvm_msr_buf_reset(cpu);
1496 kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
1498 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1499 if (ret < 0) {
1500 return ret;
1503 assert(ret == 1);
1504 return 0;
1508 * Provide a separate write service for the feature control MSR in order to
1509 * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
1510 * before writing any other state because forcibly leaving nested mode
1511 * invalidates the VCPU state.
1513 static int kvm_put_msr_feature_control(X86CPU *cpu)
1515 int ret;
1517 if (!has_msr_feature_control) {
1518 return 0;
1521 kvm_msr_buf_reset(cpu);
1522 kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL,
1523 cpu->env.msr_ia32_feature_control);
1525 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1526 if (ret < 0) {
1527 return ret;
1530 assert(ret == 1);
1531 return 0;
1534 static int kvm_put_msrs(X86CPU *cpu, int level)
1536 CPUX86State *env = &cpu->env;
1537 int i;
1538 int ret;
1540 kvm_msr_buf_reset(cpu);
1542 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
1543 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
1544 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
1545 kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
1546 if (has_msr_star) {
1547 kvm_msr_entry_add(cpu, MSR_STAR, env->star);
1549 if (has_msr_hsave_pa) {
1550 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
1552 if (has_msr_tsc_aux) {
1553 kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
1555 if (has_msr_tsc_adjust) {
1556 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
1558 if (has_msr_misc_enable) {
1559 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
1560 env->msr_ia32_misc_enable);
1562 if (has_msr_smbase) {
1563 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
1565 if (has_msr_bndcfgs) {
1566 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
1568 if (has_msr_xss) {
1569 kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
1571 #ifdef TARGET_X86_64
1572 if (lm_capable_kernel) {
1573 kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
1574 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
1575 kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
1576 kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
1578 #endif
1580 * The following MSRs have side effects on the guest or are too heavy
1581 * for normal writeback. Limit them to reset or full state updates.
1583 if (level >= KVM_PUT_RESET_STATE) {
1584 kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
1585 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
1586 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
1587 if (has_msr_async_pf_en) {
1588 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
1590 if (has_msr_pv_eoi_en) {
1591 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
1593 if (has_msr_kvm_steal_time) {
1594 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
1596 if (has_msr_architectural_pmu) {
1597 /* Stop the counter. */
1598 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
1599 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
1601 /* Set the counter values. */
1602 for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
1603 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
1604 env->msr_fixed_counters[i]);
1606 for (i = 0; i < num_architectural_pmu_counters; i++) {
1607 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
1608 env->msr_gp_counters[i]);
1609 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
1610 env->msr_gp_evtsel[i]);
1612 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
1613 env->msr_global_status);
1614 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1615 env->msr_global_ovf_ctrl);
1617 /* Now start the PMU. */
1618 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
1619 env->msr_fixed_ctr_ctrl);
1620 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
1621 env->msr_global_ctrl);
1623 if (has_msr_hv_hypercall) {
1624 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
1625 env->msr_hv_guest_os_id);
1626 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
1627 env->msr_hv_hypercall);
1629 if (has_msr_hv_vapic) {
1630 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
1631 env->msr_hv_vapic);
1633 if (has_msr_hv_tsc) {
1634 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, env->msr_hv_tsc);
1636 if (has_msr_hv_crash) {
1637 int j;
1639 for (j = 0; j < HV_X64_MSR_CRASH_PARAMS; j++)
1640 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
1641 env->msr_hv_crash_params[j]);
1643 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL,
1644 HV_X64_MSR_CRASH_CTL_NOTIFY);
1646 if (has_msr_hv_runtime) {
1647 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
1649 if (cpu->hyperv_synic) {
1650 int j;
1652 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
1653 env->msr_hv_synic_control);
1654 kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION,
1655 env->msr_hv_synic_version);
1656 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
1657 env->msr_hv_synic_evt_page);
1658 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
1659 env->msr_hv_synic_msg_page);
1661 for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
1662 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
1663 env->msr_hv_synic_sint[j]);
1666 if (has_msr_hv_stimer) {
1667 int j;
1669 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
1670 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
1671 env->msr_hv_stimer_config[j]);
1674 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
1675 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
1676 env->msr_hv_stimer_count[j]);
1679 if (has_msr_mtrr) {
1680 kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
1681 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
1682 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
1683 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
1684 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
1685 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
1686 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
1687 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
1688 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
1689 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
1690 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
1691 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
1692 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
1693 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
1694 env->mtrr_var[i].base);
1695 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i),
1696 env->mtrr_var[i].mask);
1700 /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
1701 * kvm_put_msr_feature_control. */
1703 if (env->mcg_cap) {
1704 int i;
1706 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
1707 kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
1708 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1709 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
1713 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1714 if (ret < 0) {
1715 return ret;
1718 assert(ret == cpu->kvm_msr_buf->nmsrs);
1719 return 0;
1723 static int kvm_get_fpu(X86CPU *cpu)
1725 CPUX86State *env = &cpu->env;
1726 struct kvm_fpu fpu;
1727 int i, ret;
1729 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
1730 if (ret < 0) {
1731 return ret;
1734 env->fpstt = (fpu.fsw >> 11) & 7;
1735 env->fpus = fpu.fsw;
1736 env->fpuc = fpu.fcw;
1737 env->fpop = fpu.last_opcode;
1738 env->fpip = fpu.last_ip;
1739 env->fpdp = fpu.last_dp;
1740 for (i = 0; i < 8; ++i) {
1741 env->fptags[i] = !((fpu.ftwx >> i) & 1);
1743 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
1744 for (i = 0; i < CPU_NB_REGS; i++) {
1745 env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
1746 env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
1748 env->mxcsr = fpu.mxcsr;
1750 return 0;
1753 static int kvm_get_xsave(X86CPU *cpu)
1755 CPUX86State *env = &cpu->env;
1756 X86XSaveArea *xsave = env->kvm_xsave_buf;
1757 int ret, i;
1758 uint16_t cwd, swd, twd;
1760 if (!has_xsave) {
1761 return kvm_get_fpu(cpu);
1764 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
1765 if (ret < 0) {
1766 return ret;
1769 cwd = xsave->legacy.fcw;
1770 swd = xsave->legacy.fsw;
1771 twd = xsave->legacy.ftw;
1772 env->fpop = xsave->legacy.fpop;
1773 env->fpstt = (swd >> 11) & 7;
1774 env->fpus = swd;
1775 env->fpuc = cwd;
1776 for (i = 0; i < 8; ++i) {
1777 env->fptags[i] = !((twd >> i) & 1);
1779 env->fpip = xsave->legacy.fpip;
1780 env->fpdp = xsave->legacy.fpdp;
1781 env->mxcsr = xsave->legacy.mxcsr;
1782 memcpy(env->fpregs, &xsave->legacy.fpregs,
1783 sizeof env->fpregs);
1784 env->xstate_bv = xsave->header.xstate_bv;
1785 memcpy(env->bnd_regs, &xsave->bndreg_state.bnd_regs,
1786 sizeof env->bnd_regs);
1787 env->bndcs_regs = xsave->bndcsr_state.bndcsr;
1788 memcpy(env->opmask_regs, &xsave->opmask_state.opmask_regs,
1789 sizeof env->opmask_regs);
1791 for (i = 0; i < CPU_NB_REGS; i++) {
1792 uint8_t *xmm = xsave->legacy.xmm_regs[i];
1793 uint8_t *ymmh = xsave->avx_state.ymmh[i];
1794 uint8_t *zmmh = xsave->zmm_hi256_state.zmm_hi256[i];
1795 env->xmm_regs[i].ZMM_Q(0) = ldq_p(xmm);
1796 env->xmm_regs[i].ZMM_Q(1) = ldq_p(xmm+8);
1797 env->xmm_regs[i].ZMM_Q(2) = ldq_p(ymmh);
1798 env->xmm_regs[i].ZMM_Q(3) = ldq_p(ymmh+8);
1799 env->xmm_regs[i].ZMM_Q(4) = ldq_p(zmmh);
1800 env->xmm_regs[i].ZMM_Q(5) = ldq_p(zmmh+8);
1801 env->xmm_regs[i].ZMM_Q(6) = ldq_p(zmmh+16);
1802 env->xmm_regs[i].ZMM_Q(7) = ldq_p(zmmh+24);
1805 #ifdef TARGET_X86_64
1806 memcpy(&env->xmm_regs[16], &xsave->hi16_zmm_state.hi16_zmm,
1807 16 * sizeof env->xmm_regs[16]);
1808 memcpy(&env->pkru, &xsave->pkru_state, sizeof env->pkru);
1809 #endif
1810 return 0;
1813 static int kvm_get_xcrs(X86CPU *cpu)
1815 CPUX86State *env = &cpu->env;
1816 int i, ret;
1817 struct kvm_xcrs xcrs;
1819 if (!has_xcrs) {
1820 return 0;
1823 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
1824 if (ret < 0) {
1825 return ret;
1828 for (i = 0; i < xcrs.nr_xcrs; i++) {
1829 /* Only support xcr0 now */
1830 if (xcrs.xcrs[i].xcr == 0) {
1831 env->xcr0 = xcrs.xcrs[i].value;
1832 break;
1835 return 0;
1838 static int kvm_get_sregs(X86CPU *cpu)
1840 CPUX86State *env = &cpu->env;
1841 struct kvm_sregs sregs;
1842 uint32_t hflags;
1843 int bit, i, ret;
1845 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
1846 if (ret < 0) {
1847 return ret;
1850 /* There can only be one pending IRQ set in the bitmap at a time, so try
1851 to find it and save its number instead (-1 for none). */
1852 env->interrupt_injected = -1;
1853 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
1854 if (sregs.interrupt_bitmap[i]) {
1855 bit = ctz64(sregs.interrupt_bitmap[i]);
1856 env->interrupt_injected = i * 64 + bit;
1857 break;
1861 get_seg(&env->segs[R_CS], &sregs.cs);
1862 get_seg(&env->segs[R_DS], &sregs.ds);
1863 get_seg(&env->segs[R_ES], &sregs.es);
1864 get_seg(&env->segs[R_FS], &sregs.fs);
1865 get_seg(&env->segs[R_GS], &sregs.gs);
1866 get_seg(&env->segs[R_SS], &sregs.ss);
1868 get_seg(&env->tr, &sregs.tr);
1869 get_seg(&env->ldt, &sregs.ldt);
1871 env->idt.limit = sregs.idt.limit;
1872 env->idt.base = sregs.idt.base;
1873 env->gdt.limit = sregs.gdt.limit;
1874 env->gdt.base = sregs.gdt.base;
1876 env->cr[0] = sregs.cr0;
1877 env->cr[2] = sregs.cr2;
1878 env->cr[3] = sregs.cr3;
1879 env->cr[4] = sregs.cr4;
1881 env->efer = sregs.efer;
1883 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
1885 #define HFLAG_COPY_MASK \
1886 ~( HF_CPL_MASK | HF_PE_MASK | HF_MP_MASK | HF_EM_MASK | \
1887 HF_TS_MASK | HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK | \
1888 HF_OSFXSR_MASK | HF_LMA_MASK | HF_CS32_MASK | \
1889 HF_SS32_MASK | HF_CS64_MASK | HF_ADDSEG_MASK)
1891 hflags = env->hflags & HFLAG_COPY_MASK;
1892 hflags |= (env->segs[R_SS].flags >> DESC_DPL_SHIFT) & HF_CPL_MASK;
1893 hflags |= (env->cr[0] & CR0_PE_MASK) << (HF_PE_SHIFT - CR0_PE_SHIFT);
1894 hflags |= (env->cr[0] << (HF_MP_SHIFT - CR0_MP_SHIFT)) &
1895 (HF_MP_MASK | HF_EM_MASK | HF_TS_MASK);
1896 hflags |= (env->eflags & (HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK));
1898 if (env->cr[4] & CR4_OSFXSR_MASK) {
1899 hflags |= HF_OSFXSR_MASK;
1902 if (env->efer & MSR_EFER_LMA) {
1903 hflags |= HF_LMA_MASK;
1906 if ((hflags & HF_LMA_MASK) && (env->segs[R_CS].flags & DESC_L_MASK)) {
1907 hflags |= HF_CS32_MASK | HF_SS32_MASK | HF_CS64_MASK;
1908 } else {
1909 hflags |= (env->segs[R_CS].flags & DESC_B_MASK) >>
1910 (DESC_B_SHIFT - HF_CS32_SHIFT);
1911 hflags |= (env->segs[R_SS].flags & DESC_B_MASK) >>
1912 (DESC_B_SHIFT - HF_SS32_SHIFT);
1913 if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK) ||
1914 !(hflags & HF_CS32_MASK)) {
1915 hflags |= HF_ADDSEG_MASK;
1916 } else {
1917 hflags |= ((env->segs[R_DS].base | env->segs[R_ES].base |
1918 env->segs[R_SS].base) != 0) << HF_ADDSEG_SHIFT;
1921 env->hflags = hflags;
1923 return 0;
1926 static int kvm_get_msrs(X86CPU *cpu)
1928 CPUX86State *env = &cpu->env;
1929 struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
1930 int ret, i;
1932 kvm_msr_buf_reset(cpu);
1934 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
1935 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
1936 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
1937 kvm_msr_entry_add(cpu, MSR_PAT, 0);
1938 if (has_msr_star) {
1939 kvm_msr_entry_add(cpu, MSR_STAR, 0);
1941 if (has_msr_hsave_pa) {
1942 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
1944 if (has_msr_tsc_aux) {
1945 kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
1947 if (has_msr_tsc_adjust) {
1948 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
1950 if (has_msr_tsc_deadline) {
1951 kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
1953 if (has_msr_misc_enable) {
1954 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
1956 if (has_msr_smbase) {
1957 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
1959 if (has_msr_feature_control) {
1960 kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
1962 if (has_msr_bndcfgs) {
1963 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
1965 if (has_msr_xss) {
1966 kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
1970 if (!env->tsc_valid) {
1971 kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
1972 env->tsc_valid = !runstate_is_running();
1975 #ifdef TARGET_X86_64
1976 if (lm_capable_kernel) {
1977 kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
1978 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
1979 kvm_msr_entry_add(cpu, MSR_FMASK, 0);
1980 kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
1982 #endif
1983 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
1984 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
1985 if (has_msr_async_pf_en) {
1986 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
1988 if (has_msr_pv_eoi_en) {
1989 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
1991 if (has_msr_kvm_steal_time) {
1992 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
1994 if (has_msr_architectural_pmu) {
1995 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
1996 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
1997 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
1998 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
1999 for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
2000 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
2002 for (i = 0; i < num_architectural_pmu_counters; i++) {
2003 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
2004 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
2008 if (env->mcg_cap) {
2009 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
2010 kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
2011 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
2012 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
2016 if (has_msr_hv_hypercall) {
2017 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
2018 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
2020 if (has_msr_hv_vapic) {
2021 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
2023 if (has_msr_hv_tsc) {
2024 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
2026 if (has_msr_hv_crash) {
2027 int j;
2029 for (j = 0; j < HV_X64_MSR_CRASH_PARAMS; j++) {
2030 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
2033 if (has_msr_hv_runtime) {
2034 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
2036 if (cpu->hyperv_synic) {
2037 uint32_t msr;
2039 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
2040 kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, 0);
2041 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
2042 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
2043 for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
2044 kvm_msr_entry_add(cpu, msr, 0);
2047 if (has_msr_hv_stimer) {
2048 uint32_t msr;
2050 for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
2051 msr++) {
2052 kvm_msr_entry_add(cpu, msr, 0);
2055 if (has_msr_mtrr) {
2056 kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
2057 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
2058 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
2059 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
2060 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
2061 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
2062 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
2063 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
2064 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
2065 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
2066 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
2067 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
2068 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
2069 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
2070 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
2074 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
2075 if (ret < 0) {
2076 return ret;
2079 assert(ret == cpu->kvm_msr_buf->nmsrs);
2080 for (i = 0; i < ret; i++) {
2081 uint32_t index = msrs[i].index;
2082 switch (index) {
2083 case MSR_IA32_SYSENTER_CS:
2084 env->sysenter_cs = msrs[i].data;
2085 break;
2086 case MSR_IA32_SYSENTER_ESP:
2087 env->sysenter_esp = msrs[i].data;
2088 break;
2089 case MSR_IA32_SYSENTER_EIP:
2090 env->sysenter_eip = msrs[i].data;
2091 break;
2092 case MSR_PAT:
2093 env->pat = msrs[i].data;
2094 break;
2095 case MSR_STAR:
2096 env->star = msrs[i].data;
2097 break;
2098 #ifdef TARGET_X86_64
2099 case MSR_CSTAR:
2100 env->cstar = msrs[i].data;
2101 break;
2102 case MSR_KERNELGSBASE:
2103 env->kernelgsbase = msrs[i].data;
2104 break;
2105 case MSR_FMASK:
2106 env->fmask = msrs[i].data;
2107 break;
2108 case MSR_LSTAR:
2109 env->lstar = msrs[i].data;
2110 break;
2111 #endif
2112 case MSR_IA32_TSC:
2113 env->tsc = msrs[i].data;
2114 break;
2115 case MSR_TSC_AUX:
2116 env->tsc_aux = msrs[i].data;
2117 break;
2118 case MSR_TSC_ADJUST:
2119 env->tsc_adjust = msrs[i].data;
2120 break;
2121 case MSR_IA32_TSCDEADLINE:
2122 env->tsc_deadline = msrs[i].data;
2123 break;
2124 case MSR_VM_HSAVE_PA:
2125 env->vm_hsave = msrs[i].data;
2126 break;
2127 case MSR_KVM_SYSTEM_TIME:
2128 env->system_time_msr = msrs[i].data;
2129 break;
2130 case MSR_KVM_WALL_CLOCK:
2131 env->wall_clock_msr = msrs[i].data;
2132 break;
2133 case MSR_MCG_STATUS:
2134 env->mcg_status = msrs[i].data;
2135 break;
2136 case MSR_MCG_CTL:
2137 env->mcg_ctl = msrs[i].data;
2138 break;
2139 case MSR_IA32_MISC_ENABLE:
2140 env->msr_ia32_misc_enable = msrs[i].data;
2141 break;
2142 case MSR_IA32_SMBASE:
2143 env->smbase = msrs[i].data;
2144 break;
2145 case MSR_IA32_FEATURE_CONTROL:
2146 env->msr_ia32_feature_control = msrs[i].data;
2147 break;
2148 case MSR_IA32_BNDCFGS:
2149 env->msr_bndcfgs = msrs[i].data;
2150 break;
2151 case MSR_IA32_XSS:
2152 env->xss = msrs[i].data;
2153 break;
2154 default:
2155 if (msrs[i].index >= MSR_MC0_CTL &&
2156 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
2157 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
2159 break;
2160 case MSR_KVM_ASYNC_PF_EN:
2161 env->async_pf_en_msr = msrs[i].data;
2162 break;
2163 case MSR_KVM_PV_EOI_EN:
2164 env->pv_eoi_en_msr = msrs[i].data;
2165 break;
2166 case MSR_KVM_STEAL_TIME:
2167 env->steal_time_msr = msrs[i].data;
2168 break;
2169 case MSR_CORE_PERF_FIXED_CTR_CTRL:
2170 env->msr_fixed_ctr_ctrl = msrs[i].data;
2171 break;
2172 case MSR_CORE_PERF_GLOBAL_CTRL:
2173 env->msr_global_ctrl = msrs[i].data;
2174 break;
2175 case MSR_CORE_PERF_GLOBAL_STATUS:
2176 env->msr_global_status = msrs[i].data;
2177 break;
2178 case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
2179 env->msr_global_ovf_ctrl = msrs[i].data;
2180 break;
2181 case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
2182 env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
2183 break;
2184 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
2185 env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
2186 break;
2187 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
2188 env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
2189 break;
2190 case HV_X64_MSR_HYPERCALL:
2191 env->msr_hv_hypercall = msrs[i].data;
2192 break;
2193 case HV_X64_MSR_GUEST_OS_ID:
2194 env->msr_hv_guest_os_id = msrs[i].data;
2195 break;
2196 case HV_X64_MSR_APIC_ASSIST_PAGE:
2197 env->msr_hv_vapic = msrs[i].data;
2198 break;
2199 case HV_X64_MSR_REFERENCE_TSC:
2200 env->msr_hv_tsc = msrs[i].data;
2201 break;
2202 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2203 env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
2204 break;
2205 case HV_X64_MSR_VP_RUNTIME:
2206 env->msr_hv_runtime = msrs[i].data;
2207 break;
2208 case HV_X64_MSR_SCONTROL:
2209 env->msr_hv_synic_control = msrs[i].data;
2210 break;
2211 case HV_X64_MSR_SVERSION:
2212 env->msr_hv_synic_version = msrs[i].data;
2213 break;
2214 case HV_X64_MSR_SIEFP:
2215 env->msr_hv_synic_evt_page = msrs[i].data;
2216 break;
2217 case HV_X64_MSR_SIMP:
2218 env->msr_hv_synic_msg_page = msrs[i].data;
2219 break;
2220 case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
2221 env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
2222 break;
2223 case HV_X64_MSR_STIMER0_CONFIG:
2224 case HV_X64_MSR_STIMER1_CONFIG:
2225 case HV_X64_MSR_STIMER2_CONFIG:
2226 case HV_X64_MSR_STIMER3_CONFIG:
2227 env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
2228 msrs[i].data;
2229 break;
2230 case HV_X64_MSR_STIMER0_COUNT:
2231 case HV_X64_MSR_STIMER1_COUNT:
2232 case HV_X64_MSR_STIMER2_COUNT:
2233 case HV_X64_MSR_STIMER3_COUNT:
2234 env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
2235 msrs[i].data;
2236 break;
2237 case MSR_MTRRdefType:
2238 env->mtrr_deftype = msrs[i].data;
2239 break;
2240 case MSR_MTRRfix64K_00000:
2241 env->mtrr_fixed[0] = msrs[i].data;
2242 break;
2243 case MSR_MTRRfix16K_80000:
2244 env->mtrr_fixed[1] = msrs[i].data;
2245 break;
2246 case MSR_MTRRfix16K_A0000:
2247 env->mtrr_fixed[2] = msrs[i].data;
2248 break;
2249 case MSR_MTRRfix4K_C0000:
2250 env->mtrr_fixed[3] = msrs[i].data;
2251 break;
2252 case MSR_MTRRfix4K_C8000:
2253 env->mtrr_fixed[4] = msrs[i].data;
2254 break;
2255 case MSR_MTRRfix4K_D0000:
2256 env->mtrr_fixed[5] = msrs[i].data;
2257 break;
2258 case MSR_MTRRfix4K_D8000:
2259 env->mtrr_fixed[6] = msrs[i].data;
2260 break;
2261 case MSR_MTRRfix4K_E0000:
2262 env->mtrr_fixed[7] = msrs[i].data;
2263 break;
2264 case MSR_MTRRfix4K_E8000:
2265 env->mtrr_fixed[8] = msrs[i].data;
2266 break;
2267 case MSR_MTRRfix4K_F0000:
2268 env->mtrr_fixed[9] = msrs[i].data;
2269 break;
2270 case MSR_MTRRfix4K_F8000:
2271 env->mtrr_fixed[10] = msrs[i].data;
2272 break;
2273 case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
2274 if (index & 1) {
2275 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data;
2276 } else {
2277 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
2279 break;
2283 return 0;
2286 static int kvm_put_mp_state(X86CPU *cpu)
2288 struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
2290 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
2293 static int kvm_get_mp_state(X86CPU *cpu)
2295 CPUState *cs = CPU(cpu);
2296 CPUX86State *env = &cpu->env;
2297 struct kvm_mp_state mp_state;
2298 int ret;
2300 ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
2301 if (ret < 0) {
2302 return ret;
2304 env->mp_state = mp_state.mp_state;
2305 if (kvm_irqchip_in_kernel()) {
2306 cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
2308 return 0;
2311 static int kvm_get_apic(X86CPU *cpu)
2313 DeviceState *apic = cpu->apic_state;
2314 struct kvm_lapic_state kapic;
2315 int ret;
2317 if (apic && kvm_irqchip_in_kernel()) {
2318 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
2319 if (ret < 0) {
2320 return ret;
2323 kvm_get_apic_state(apic, &kapic);
2325 return 0;
2328 static int kvm_put_apic(X86CPU *cpu)
2330 DeviceState *apic = cpu->apic_state;
2331 struct kvm_lapic_state kapic;
2333 if (apic && kvm_irqchip_in_kernel()) {
2334 kvm_put_apic_state(apic, &kapic);
2336 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_LAPIC, &kapic);
2338 return 0;
2341 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
2343 CPUState *cs = CPU(cpu);
2344 CPUX86State *env = &cpu->env;
2345 struct kvm_vcpu_events events = {};
2347 if (!kvm_has_vcpu_events()) {
2348 return 0;
2351 events.exception.injected = (env->exception_injected >= 0);
2352 events.exception.nr = env->exception_injected;
2353 events.exception.has_error_code = env->has_error_code;
2354 events.exception.error_code = env->error_code;
2355 events.exception.pad = 0;
2357 events.interrupt.injected = (env->interrupt_injected >= 0);
2358 events.interrupt.nr = env->interrupt_injected;
2359 events.interrupt.soft = env->soft_interrupt;
2361 events.nmi.injected = env->nmi_injected;
2362 events.nmi.pending = env->nmi_pending;
2363 events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
2364 events.nmi.pad = 0;
2366 events.sipi_vector = env->sipi_vector;
2368 if (has_msr_smbase) {
2369 events.smi.smm = !!(env->hflags & HF_SMM_MASK);
2370 events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
2371 if (kvm_irqchip_in_kernel()) {
2372 /* As soon as these are moved to the kernel, remove them
2373 * from cs->interrupt_request.
2375 events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
2376 events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
2377 cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
2378 } else {
2379 /* Keep these in cs->interrupt_request. */
2380 events.smi.pending = 0;
2381 events.smi.latched_init = 0;
2383 events.flags |= KVM_VCPUEVENT_VALID_SMM;
2386 events.flags = 0;
2387 if (level >= KVM_PUT_RESET_STATE) {
2388 events.flags |=
2389 KVM_VCPUEVENT_VALID_NMI_PENDING | KVM_VCPUEVENT_VALID_SIPI_VECTOR;
2392 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
2395 static int kvm_get_vcpu_events(X86CPU *cpu)
2397 CPUX86State *env = &cpu->env;
2398 struct kvm_vcpu_events events;
2399 int ret;
2401 if (!kvm_has_vcpu_events()) {
2402 return 0;
2405 memset(&events, 0, sizeof(events));
2406 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
2407 if (ret < 0) {
2408 return ret;
2410 env->exception_injected =
2411 events.exception.injected ? events.exception.nr : -1;
2412 env->has_error_code = events.exception.has_error_code;
2413 env->error_code = events.exception.error_code;
2415 env->interrupt_injected =
2416 events.interrupt.injected ? events.interrupt.nr : -1;
2417 env->soft_interrupt = events.interrupt.soft;
2419 env->nmi_injected = events.nmi.injected;
2420 env->nmi_pending = events.nmi.pending;
2421 if (events.nmi.masked) {
2422 env->hflags2 |= HF2_NMI_MASK;
2423 } else {
2424 env->hflags2 &= ~HF2_NMI_MASK;
2427 if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
2428 if (events.smi.smm) {
2429 env->hflags |= HF_SMM_MASK;
2430 } else {
2431 env->hflags &= ~HF_SMM_MASK;
2433 if (events.smi.pending) {
2434 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2435 } else {
2436 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2438 if (events.smi.smm_inside_nmi) {
2439 env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
2440 } else {
2441 env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
2443 if (events.smi.latched_init) {
2444 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2445 } else {
2446 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2450 env->sipi_vector = events.sipi_vector;
2452 return 0;
2455 static int kvm_guest_debug_workarounds(X86CPU *cpu)
2457 CPUState *cs = CPU(cpu);
2458 CPUX86State *env = &cpu->env;
2459 int ret = 0;
2460 unsigned long reinject_trap = 0;
2462 if (!kvm_has_vcpu_events()) {
2463 if (env->exception_injected == 1) {
2464 reinject_trap = KVM_GUESTDBG_INJECT_DB;
2465 } else if (env->exception_injected == 3) {
2466 reinject_trap = KVM_GUESTDBG_INJECT_BP;
2468 env->exception_injected = -1;
2472 * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
2473 * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
2474 * by updating the debug state once again if single-stepping is on.
2475 * Another reason to call kvm_update_guest_debug here is a pending debug
2476 * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
2477 * reinject them via SET_GUEST_DEBUG.
2479 if (reinject_trap ||
2480 (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
2481 ret = kvm_update_guest_debug(cs, reinject_trap);
2483 return ret;
2486 static int kvm_put_debugregs(X86CPU *cpu)
2488 CPUX86State *env = &cpu->env;
2489 struct kvm_debugregs dbgregs;
2490 int i;
2492 if (!kvm_has_debugregs()) {
2493 return 0;
2496 for (i = 0; i < 4; i++) {
2497 dbgregs.db[i] = env->dr[i];
2499 dbgregs.dr6 = env->dr[6];
2500 dbgregs.dr7 = env->dr[7];
2501 dbgregs.flags = 0;
2503 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
2506 static int kvm_get_debugregs(X86CPU *cpu)
2508 CPUX86State *env = &cpu->env;
2509 struct kvm_debugregs dbgregs;
2510 int i, ret;
2512 if (!kvm_has_debugregs()) {
2513 return 0;
2516 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
2517 if (ret < 0) {
2518 return ret;
2520 for (i = 0; i < 4; i++) {
2521 env->dr[i] = dbgregs.db[i];
2523 env->dr[4] = env->dr[6] = dbgregs.dr6;
2524 env->dr[5] = env->dr[7] = dbgregs.dr7;
2526 return 0;
2529 int kvm_arch_put_registers(CPUState *cpu, int level)
2531 X86CPU *x86_cpu = X86_CPU(cpu);
2532 int ret;
2534 assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
2536 if (level >= KVM_PUT_RESET_STATE) {
2537 ret = kvm_put_msr_feature_control(x86_cpu);
2538 if (ret < 0) {
2539 return ret;
2543 if (level == KVM_PUT_FULL_STATE) {
2544 /* We don't check for kvm_arch_set_tsc_khz() errors here,
2545 * because TSC frequency mismatch shouldn't abort migration,
2546 * unless the user explicitly asked for a more strict TSC
2547 * setting (e.g. using an explicit "tsc-freq" option).
2549 kvm_arch_set_tsc_khz(cpu);
2552 ret = kvm_getput_regs(x86_cpu, 1);
2553 if (ret < 0) {
2554 return ret;
2556 ret = kvm_put_xsave(x86_cpu);
2557 if (ret < 0) {
2558 return ret;
2560 ret = kvm_put_xcrs(x86_cpu);
2561 if (ret < 0) {
2562 return ret;
2564 ret = kvm_put_sregs(x86_cpu);
2565 if (ret < 0) {
2566 return ret;
2568 /* must be before kvm_put_msrs */
2569 ret = kvm_inject_mce_oldstyle(x86_cpu);
2570 if (ret < 0) {
2571 return ret;
2573 ret = kvm_put_msrs(x86_cpu, level);
2574 if (ret < 0) {
2575 return ret;
2577 if (level >= KVM_PUT_RESET_STATE) {
2578 ret = kvm_put_mp_state(x86_cpu);
2579 if (ret < 0) {
2580 return ret;
2582 ret = kvm_put_apic(x86_cpu);
2583 if (ret < 0) {
2584 return ret;
2588 ret = kvm_put_tscdeadline_msr(x86_cpu);
2589 if (ret < 0) {
2590 return ret;
2593 ret = kvm_put_vcpu_events(x86_cpu, level);
2594 if (ret < 0) {
2595 return ret;
2597 ret = kvm_put_debugregs(x86_cpu);
2598 if (ret < 0) {
2599 return ret;
2601 /* must be last */
2602 ret = kvm_guest_debug_workarounds(x86_cpu);
2603 if (ret < 0) {
2604 return ret;
2606 return 0;
2609 int kvm_arch_get_registers(CPUState *cs)
2611 X86CPU *cpu = X86_CPU(cs);
2612 int ret;
2614 assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
2616 ret = kvm_getput_regs(cpu, 0);
2617 if (ret < 0) {
2618 goto out;
2620 ret = kvm_get_xsave(cpu);
2621 if (ret < 0) {
2622 goto out;
2624 ret = kvm_get_xcrs(cpu);
2625 if (ret < 0) {
2626 goto out;
2628 ret = kvm_get_sregs(cpu);
2629 if (ret < 0) {
2630 goto out;
2632 ret = kvm_get_msrs(cpu);
2633 if (ret < 0) {
2634 goto out;
2636 ret = kvm_get_mp_state(cpu);
2637 if (ret < 0) {
2638 goto out;
2640 ret = kvm_get_apic(cpu);
2641 if (ret < 0) {
2642 goto out;
2644 ret = kvm_get_vcpu_events(cpu);
2645 if (ret < 0) {
2646 goto out;
2648 ret = kvm_get_debugregs(cpu);
2649 if (ret < 0) {
2650 goto out;
2652 ret = 0;
2653 out:
2654 cpu_sync_bndcs_hflags(&cpu->env);
2655 return ret;
2658 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
2660 X86CPU *x86_cpu = X86_CPU(cpu);
2661 CPUX86State *env = &x86_cpu->env;
2662 int ret;
2664 /* Inject NMI */
2665 if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
2666 if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
2667 qemu_mutex_lock_iothread();
2668 cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
2669 qemu_mutex_unlock_iothread();
2670 DPRINTF("injected NMI\n");
2671 ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
2672 if (ret < 0) {
2673 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
2674 strerror(-ret));
2677 if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
2678 qemu_mutex_lock_iothread();
2679 cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
2680 qemu_mutex_unlock_iothread();
2681 DPRINTF("injected SMI\n");
2682 ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
2683 if (ret < 0) {
2684 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
2685 strerror(-ret));
2690 if (!kvm_pic_in_kernel()) {
2691 qemu_mutex_lock_iothread();
2694 /* Force the VCPU out of its inner loop to process any INIT requests
2695 * or (for userspace APIC, but it is cheap to combine the checks here)
2696 * pending TPR access reports.
2698 if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
2699 if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
2700 !(env->hflags & HF_SMM_MASK)) {
2701 cpu->exit_request = 1;
2703 if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
2704 cpu->exit_request = 1;
2708 if (!kvm_pic_in_kernel()) {
2709 /* Try to inject an interrupt if the guest can accept it */
2710 if (run->ready_for_interrupt_injection &&
2711 (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
2712 (env->eflags & IF_MASK)) {
2713 int irq;
2715 cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
2716 irq = cpu_get_pic_interrupt(env);
2717 if (irq >= 0) {
2718 struct kvm_interrupt intr;
2720 intr.irq = irq;
2721 DPRINTF("injected interrupt %d\n", irq);
2722 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
2723 if (ret < 0) {
2724 fprintf(stderr,
2725 "KVM: injection failed, interrupt lost (%s)\n",
2726 strerror(-ret));
2731 /* If we have an interrupt but the guest is not ready to receive an
2732 * interrupt, request an interrupt window exit. This will
2733 * cause a return to userspace as soon as the guest is ready to
2734 * receive interrupts. */
2735 if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
2736 run->request_interrupt_window = 1;
2737 } else {
2738 run->request_interrupt_window = 0;
2741 DPRINTF("setting tpr\n");
2742 run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
2744 qemu_mutex_unlock_iothread();
2748 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
2750 X86CPU *x86_cpu = X86_CPU(cpu);
2751 CPUX86State *env = &x86_cpu->env;
2753 if (run->flags & KVM_RUN_X86_SMM) {
2754 env->hflags |= HF_SMM_MASK;
2755 } else {
2756 env->hflags &= HF_SMM_MASK;
2758 if (run->if_flag) {
2759 env->eflags |= IF_MASK;
2760 } else {
2761 env->eflags &= ~IF_MASK;
2764 /* We need to protect the apic state against concurrent accesses from
2765 * different threads in case the userspace irqchip is used. */
2766 if (!kvm_irqchip_in_kernel()) {
2767 qemu_mutex_lock_iothread();
2769 cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
2770 cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
2771 if (!kvm_irqchip_in_kernel()) {
2772 qemu_mutex_unlock_iothread();
2774 return cpu_get_mem_attrs(env);
2777 int kvm_arch_process_async_events(CPUState *cs)
2779 X86CPU *cpu = X86_CPU(cs);
2780 CPUX86State *env = &cpu->env;
2782 if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
2783 /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
2784 assert(env->mcg_cap);
2786 cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
2788 kvm_cpu_synchronize_state(cs);
2790 if (env->exception_injected == EXCP08_DBLE) {
2791 /* this means triple fault */
2792 qemu_system_reset_request();
2793 cs->exit_request = 1;
2794 return 0;
2796 env->exception_injected = EXCP12_MCHK;
2797 env->has_error_code = 0;
2799 cs->halted = 0;
2800 if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
2801 env->mp_state = KVM_MP_STATE_RUNNABLE;
2805 if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
2806 !(env->hflags & HF_SMM_MASK)) {
2807 kvm_cpu_synchronize_state(cs);
2808 do_cpu_init(cpu);
2811 if (kvm_irqchip_in_kernel()) {
2812 return 0;
2815 if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
2816 cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
2817 apic_poll_irq(cpu->apic_state);
2819 if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2820 (env->eflags & IF_MASK)) ||
2821 (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
2822 cs->halted = 0;
2824 if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
2825 kvm_cpu_synchronize_state(cs);
2826 do_cpu_sipi(cpu);
2828 if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
2829 cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
2830 kvm_cpu_synchronize_state(cs);
2831 apic_handle_tpr_access_report(cpu->apic_state, env->eip,
2832 env->tpr_access_type);
2835 return cs->halted;
2838 static int kvm_handle_halt(X86CPU *cpu)
2840 CPUState *cs = CPU(cpu);
2841 CPUX86State *env = &cpu->env;
2843 if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2844 (env->eflags & IF_MASK)) &&
2845 !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
2846 cs->halted = 1;
2847 return EXCP_HLT;
2850 return 0;
2853 static int kvm_handle_tpr_access(X86CPU *cpu)
2855 CPUState *cs = CPU(cpu);
2856 struct kvm_run *run = cs->kvm_run;
2858 apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
2859 run->tpr_access.is_write ? TPR_ACCESS_WRITE
2860 : TPR_ACCESS_READ);
2861 return 1;
2864 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2866 static const uint8_t int3 = 0xcc;
2868 if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
2869 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
2870 return -EINVAL;
2872 return 0;
2875 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2877 uint8_t int3;
2879 if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
2880 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
2881 return -EINVAL;
2883 return 0;
2886 static struct {
2887 target_ulong addr;
2888 int len;
2889 int type;
2890 } hw_breakpoint[4];
2892 static int nb_hw_breakpoint;
2894 static int find_hw_breakpoint(target_ulong addr, int len, int type)
2896 int n;
2898 for (n = 0; n < nb_hw_breakpoint; n++) {
2899 if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
2900 (hw_breakpoint[n].len == len || len == -1)) {
2901 return n;
2904 return -1;
2907 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
2908 target_ulong len, int type)
2910 switch (type) {
2911 case GDB_BREAKPOINT_HW:
2912 len = 1;
2913 break;
2914 case GDB_WATCHPOINT_WRITE:
2915 case GDB_WATCHPOINT_ACCESS:
2916 switch (len) {
2917 case 1:
2918 break;
2919 case 2:
2920 case 4:
2921 case 8:
2922 if (addr & (len - 1)) {
2923 return -EINVAL;
2925 break;
2926 default:
2927 return -EINVAL;
2929 break;
2930 default:
2931 return -ENOSYS;
2934 if (nb_hw_breakpoint == 4) {
2935 return -ENOBUFS;
2937 if (find_hw_breakpoint(addr, len, type) >= 0) {
2938 return -EEXIST;
2940 hw_breakpoint[nb_hw_breakpoint].addr = addr;
2941 hw_breakpoint[nb_hw_breakpoint].len = len;
2942 hw_breakpoint[nb_hw_breakpoint].type = type;
2943 nb_hw_breakpoint++;
2945 return 0;
2948 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
2949 target_ulong len, int type)
2951 int n;
2953 n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
2954 if (n < 0) {
2955 return -ENOENT;
2957 nb_hw_breakpoint--;
2958 hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
2960 return 0;
2963 void kvm_arch_remove_all_hw_breakpoints(void)
2965 nb_hw_breakpoint = 0;
2968 static CPUWatchpoint hw_watchpoint;
2970 static int kvm_handle_debug(X86CPU *cpu,
2971 struct kvm_debug_exit_arch *arch_info)
2973 CPUState *cs = CPU(cpu);
2974 CPUX86State *env = &cpu->env;
2975 int ret = 0;
2976 int n;
2978 if (arch_info->exception == 1) {
2979 if (arch_info->dr6 & (1 << 14)) {
2980 if (cs->singlestep_enabled) {
2981 ret = EXCP_DEBUG;
2983 } else {
2984 for (n = 0; n < 4; n++) {
2985 if (arch_info->dr6 & (1 << n)) {
2986 switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
2987 case 0x0:
2988 ret = EXCP_DEBUG;
2989 break;
2990 case 0x1:
2991 ret = EXCP_DEBUG;
2992 cs->watchpoint_hit = &hw_watchpoint;
2993 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
2994 hw_watchpoint.flags = BP_MEM_WRITE;
2995 break;
2996 case 0x3:
2997 ret = EXCP_DEBUG;
2998 cs->watchpoint_hit = &hw_watchpoint;
2999 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
3000 hw_watchpoint.flags = BP_MEM_ACCESS;
3001 break;
3006 } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
3007 ret = EXCP_DEBUG;
3009 if (ret == 0) {
3010 cpu_synchronize_state(cs);
3011 assert(env->exception_injected == -1);
3013 /* pass to guest */
3014 env->exception_injected = arch_info->exception;
3015 env->has_error_code = 0;
3018 return ret;
3021 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
3023 const uint8_t type_code[] = {
3024 [GDB_BREAKPOINT_HW] = 0x0,
3025 [GDB_WATCHPOINT_WRITE] = 0x1,
3026 [GDB_WATCHPOINT_ACCESS] = 0x3
3028 const uint8_t len_code[] = {
3029 [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
3031 int n;
3033 if (kvm_sw_breakpoints_active(cpu)) {
3034 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
3036 if (nb_hw_breakpoint > 0) {
3037 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
3038 dbg->arch.debugreg[7] = 0x0600;
3039 for (n = 0; n < nb_hw_breakpoint; n++) {
3040 dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
3041 dbg->arch.debugreg[7] |= (2 << (n * 2)) |
3042 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
3043 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
3048 static bool host_supports_vmx(void)
3050 uint32_t ecx, unused;
3052 host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
3053 return ecx & CPUID_EXT_VMX;
3056 #define VMX_INVALID_GUEST_STATE 0x80000021
3058 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
3060 X86CPU *cpu = X86_CPU(cs);
3061 uint64_t code;
3062 int ret;
3064 switch (run->exit_reason) {
3065 case KVM_EXIT_HLT:
3066 DPRINTF("handle_hlt\n");
3067 qemu_mutex_lock_iothread();
3068 ret = kvm_handle_halt(cpu);
3069 qemu_mutex_unlock_iothread();
3070 break;
3071 case KVM_EXIT_SET_TPR:
3072 ret = 0;
3073 break;
3074 case KVM_EXIT_TPR_ACCESS:
3075 qemu_mutex_lock_iothread();
3076 ret = kvm_handle_tpr_access(cpu);
3077 qemu_mutex_unlock_iothread();
3078 break;
3079 case KVM_EXIT_FAIL_ENTRY:
3080 code = run->fail_entry.hardware_entry_failure_reason;
3081 fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
3082 code);
3083 if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
3084 fprintf(stderr,
3085 "\nIf you're running a guest on an Intel machine without "
3086 "unrestricted mode\n"
3087 "support, the failure can be most likely due to the guest "
3088 "entering an invalid\n"
3089 "state for Intel VT. For example, the guest maybe running "
3090 "in big real mode\n"
3091 "which is not supported on less recent Intel processors."
3092 "\n\n");
3094 ret = -1;
3095 break;
3096 case KVM_EXIT_EXCEPTION:
3097 fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
3098 run->ex.exception, run->ex.error_code);
3099 ret = -1;
3100 break;
3101 case KVM_EXIT_DEBUG:
3102 DPRINTF("kvm_exit_debug\n");
3103 qemu_mutex_lock_iothread();
3104 ret = kvm_handle_debug(cpu, &run->debug.arch);
3105 qemu_mutex_unlock_iothread();
3106 break;
3107 case KVM_EXIT_HYPERV:
3108 ret = kvm_hv_handle_exit(cpu, &run->hyperv);
3109 break;
3110 case KVM_EXIT_IOAPIC_EOI:
3111 ioapic_eoi_broadcast(run->eoi.vector);
3112 ret = 0;
3113 break;
3114 default:
3115 fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
3116 ret = -1;
3117 break;
3120 return ret;
3123 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
3125 X86CPU *cpu = X86_CPU(cs);
3126 CPUX86State *env = &cpu->env;
3128 kvm_cpu_synchronize_state(cs);
3129 return !(env->cr[0] & CR0_PE_MASK) ||
3130 ((env->segs[R_CS].selector & 3) != 3);
3133 void kvm_arch_init_irq_routing(KVMState *s)
3135 if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
3136 /* If kernel can't do irq routing, interrupt source
3137 * override 0->2 cannot be set up as required by HPET.
3138 * So we have to disable it.
3140 no_hpet = 1;
3142 /* We know at this point that we're using the in-kernel
3143 * irqchip, so we can use irqfds, and on x86 we know
3144 * we can use msi via irqfd and GSI routing.
3146 kvm_msi_via_irqfd_allowed = true;
3147 kvm_gsi_routing_allowed = true;
3149 if (kvm_irqchip_is_split()) {
3150 int i;
3152 /* If the ioapic is in QEMU and the lapics are in KVM, reserve
3153 MSI routes for signaling interrupts to the local apics. */
3154 for (i = 0; i < IOAPIC_NUM_PINS; i++) {
3155 struct MSIMessage msg = { 0x0, 0x0 };
3156 if (kvm_irqchip_add_msi_route(s, msg, NULL) < 0) {
3157 error_report("Could not enable split IRQ mode.");
3158 exit(1);
3164 int kvm_arch_irqchip_create(MachineState *ms, KVMState *s)
3166 int ret;
3167 if (machine_kernel_irqchip_split(ms)) {
3168 ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
3169 if (ret) {
3170 error_report("Could not enable split irqchip mode: %s\n",
3171 strerror(-ret));
3172 exit(1);
3173 } else {
3174 DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
3175 kvm_split_irqchip = true;
3176 return 1;
3178 } else {
3179 return 0;
3183 /* Classic KVM device assignment interface. Will remain x86 only. */
3184 int kvm_device_pci_assign(KVMState *s, PCIHostDeviceAddress *dev_addr,
3185 uint32_t flags, uint32_t *dev_id)
3187 struct kvm_assigned_pci_dev dev_data = {
3188 .segnr = dev_addr->domain,
3189 .busnr = dev_addr->bus,
3190 .devfn = PCI_DEVFN(dev_addr->slot, dev_addr->function),
3191 .flags = flags,
3193 int ret;
3195 dev_data.assigned_dev_id =
3196 (dev_addr->domain << 16) | (dev_addr->bus << 8) | dev_data.devfn;
3198 ret = kvm_vm_ioctl(s, KVM_ASSIGN_PCI_DEVICE, &dev_data);
3199 if (ret < 0) {
3200 return ret;
3203 *dev_id = dev_data.assigned_dev_id;
3205 return 0;
3208 int kvm_device_pci_deassign(KVMState *s, uint32_t dev_id)
3210 struct kvm_assigned_pci_dev dev_data = {
3211 .assigned_dev_id = dev_id,
3214 return kvm_vm_ioctl(s, KVM_DEASSIGN_PCI_DEVICE, &dev_data);
3217 static int kvm_assign_irq_internal(KVMState *s, uint32_t dev_id,
3218 uint32_t irq_type, uint32_t guest_irq)
3220 struct kvm_assigned_irq assigned_irq = {
3221 .assigned_dev_id = dev_id,
3222 .guest_irq = guest_irq,
3223 .flags = irq_type,
3226 if (kvm_check_extension(s, KVM_CAP_ASSIGN_DEV_IRQ)) {
3227 return kvm_vm_ioctl(s, KVM_ASSIGN_DEV_IRQ, &assigned_irq);
3228 } else {
3229 return kvm_vm_ioctl(s, KVM_ASSIGN_IRQ, &assigned_irq);
3233 int kvm_device_intx_assign(KVMState *s, uint32_t dev_id, bool use_host_msi,
3234 uint32_t guest_irq)
3236 uint32_t irq_type = KVM_DEV_IRQ_GUEST_INTX |
3237 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX);
3239 return kvm_assign_irq_internal(s, dev_id, irq_type, guest_irq);
3242 int kvm_device_intx_set_mask(KVMState *s, uint32_t dev_id, bool masked)
3244 struct kvm_assigned_pci_dev dev_data = {
3245 .assigned_dev_id = dev_id,
3246 .flags = masked ? KVM_DEV_ASSIGN_MASK_INTX : 0,
3249 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_INTX_MASK, &dev_data);
3252 static int kvm_deassign_irq_internal(KVMState *s, uint32_t dev_id,
3253 uint32_t type)
3255 struct kvm_assigned_irq assigned_irq = {
3256 .assigned_dev_id = dev_id,
3257 .flags = type,
3260 return kvm_vm_ioctl(s, KVM_DEASSIGN_DEV_IRQ, &assigned_irq);
3263 int kvm_device_intx_deassign(KVMState *s, uint32_t dev_id, bool use_host_msi)
3265 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_INTX |
3266 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX));
3269 int kvm_device_msi_assign(KVMState *s, uint32_t dev_id, int virq)
3271 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSI |
3272 KVM_DEV_IRQ_GUEST_MSI, virq);
3275 int kvm_device_msi_deassign(KVMState *s, uint32_t dev_id)
3277 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSI |
3278 KVM_DEV_IRQ_HOST_MSI);
3281 bool kvm_device_msix_supported(KVMState *s)
3283 /* The kernel lacks a corresponding KVM_CAP, so we probe by calling
3284 * KVM_ASSIGN_SET_MSIX_NR with an invalid parameter. */
3285 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, NULL) == -EFAULT;
3288 int kvm_device_msix_init_vectors(KVMState *s, uint32_t dev_id,
3289 uint32_t nr_vectors)
3291 struct kvm_assigned_msix_nr msix_nr = {
3292 .assigned_dev_id = dev_id,
3293 .entry_nr = nr_vectors,
3296 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, &msix_nr);
3299 int kvm_device_msix_set_vector(KVMState *s, uint32_t dev_id, uint32_t vector,
3300 int virq)
3302 struct kvm_assigned_msix_entry msix_entry = {
3303 .assigned_dev_id = dev_id,
3304 .gsi = virq,
3305 .entry = vector,
3308 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_ENTRY, &msix_entry);
3311 int kvm_device_msix_assign(KVMState *s, uint32_t dev_id)
3313 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSIX |
3314 KVM_DEV_IRQ_GUEST_MSIX, 0);
3317 int kvm_device_msix_deassign(KVMState *s, uint32_t dev_id)
3319 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSIX |
3320 KVM_DEV_IRQ_HOST_MSIX);
3323 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
3324 uint64_t address, uint32_t data, PCIDevice *dev)
3326 return 0;
3329 int kvm_arch_msi_data_to_gsi(uint32_t data)
3331 abort();