Merge remote-tracking branch 'sstabellini/xen-next' into staging
[qemu.git] / target-i386 / kvm.c
blob70ef74b80aba7d66c7383671fe607eb44fe562dc
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 <sys/types.h>
16 #include <sys/ioctl.h>
17 #include <sys/mman.h>
18 #include <sys/utsname.h>
20 #include <linux/kvm.h>
21 #include <linux/kvm_para.h>
23 #include "qemu-common.h"
24 #include "sysemu.h"
25 #include "kvm.h"
26 #include "cpu.h"
27 #include "gdbstub.h"
28 #include "host-utils.h"
29 #include "hw/pc.h"
30 #include "hw/apic.h"
31 #include "ioport.h"
33 //#define DEBUG_KVM
35 #ifdef DEBUG_KVM
36 #define DPRINTF(fmt, ...) \
37 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
38 #else
39 #define DPRINTF(fmt, ...) \
40 do { } while (0)
41 #endif
43 #define MSR_KVM_WALL_CLOCK 0x11
44 #define MSR_KVM_SYSTEM_TIME 0x12
46 #ifndef BUS_MCEERR_AR
47 #define BUS_MCEERR_AR 4
48 #endif
49 #ifndef BUS_MCEERR_AO
50 #define BUS_MCEERR_AO 5
51 #endif
53 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
54 KVM_CAP_INFO(SET_TSS_ADDR),
55 KVM_CAP_INFO(EXT_CPUID),
56 KVM_CAP_INFO(MP_STATE),
57 KVM_CAP_LAST_INFO
60 static bool has_msr_star;
61 static bool has_msr_hsave_pa;
62 static bool has_msr_async_pf_en;
63 static int lm_capable_kernel;
65 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
67 struct kvm_cpuid2 *cpuid;
68 int r, size;
70 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
71 cpuid = (struct kvm_cpuid2 *)g_malloc0(size);
72 cpuid->nent = max;
73 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
74 if (r == 0 && cpuid->nent >= max) {
75 r = -E2BIG;
77 if (r < 0) {
78 if (r == -E2BIG) {
79 g_free(cpuid);
80 return NULL;
81 } else {
82 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
83 strerror(-r));
84 exit(1);
87 return cpuid;
90 struct kvm_para_features {
91 int cap;
92 int feature;
93 } para_features[] = {
94 { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
95 { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
96 { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
97 { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
98 { -1, -1 }
101 static int get_para_features(KVMState *s)
103 int i, features = 0;
105 for (i = 0; i < ARRAY_SIZE(para_features) - 1; i++) {
106 if (kvm_check_extension(s, para_features[i].cap)) {
107 features |= (1 << para_features[i].feature);
111 return features;
115 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
116 uint32_t index, int reg)
118 struct kvm_cpuid2 *cpuid;
119 int i, max;
120 uint32_t ret = 0;
121 uint32_t cpuid_1_edx;
122 int has_kvm_features = 0;
124 max = 1;
125 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
126 max *= 2;
129 for (i = 0; i < cpuid->nent; ++i) {
130 if (cpuid->entries[i].function == function &&
131 cpuid->entries[i].index == index) {
132 if (cpuid->entries[i].function == KVM_CPUID_FEATURES) {
133 has_kvm_features = 1;
135 switch (reg) {
136 case R_EAX:
137 ret = cpuid->entries[i].eax;
138 break;
139 case R_EBX:
140 ret = cpuid->entries[i].ebx;
141 break;
142 case R_ECX:
143 ret = cpuid->entries[i].ecx;
144 break;
145 case R_EDX:
146 ret = cpuid->entries[i].edx;
147 switch (function) {
148 case 1:
149 /* KVM before 2.6.30 misreports the following features */
150 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
151 break;
152 case 0x80000001:
153 /* On Intel, kvm returns cpuid according to the Intel spec,
154 * so add missing bits according to the AMD spec:
156 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
157 ret |= cpuid_1_edx & 0x183f7ff;
158 break;
160 break;
165 g_free(cpuid);
167 /* fallback for older kernels */
168 if (!has_kvm_features && (function == KVM_CPUID_FEATURES)) {
169 ret = get_para_features(s);
172 return ret;
175 typedef struct HWPoisonPage {
176 ram_addr_t ram_addr;
177 QLIST_ENTRY(HWPoisonPage) list;
178 } HWPoisonPage;
180 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
181 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
183 static void kvm_unpoison_all(void *param)
185 HWPoisonPage *page, *next_page;
187 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
188 QLIST_REMOVE(page, list);
189 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
190 g_free(page);
194 static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
196 HWPoisonPage *page;
198 QLIST_FOREACH(page, &hwpoison_page_list, list) {
199 if (page->ram_addr == ram_addr) {
200 return;
203 page = g_malloc(sizeof(HWPoisonPage));
204 page->ram_addr = ram_addr;
205 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
208 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
209 int *max_banks)
211 int r;
213 r = kvm_check_extension(s, KVM_CAP_MCE);
214 if (r > 0) {
215 *max_banks = r;
216 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
218 return -ENOSYS;
221 static void kvm_mce_inject(CPUState *env, target_phys_addr_t paddr, int code)
223 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
224 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
225 uint64_t mcg_status = MCG_STATUS_MCIP;
227 if (code == BUS_MCEERR_AR) {
228 status |= MCI_STATUS_AR | 0x134;
229 mcg_status |= MCG_STATUS_EIPV;
230 } else {
231 status |= 0xc0;
232 mcg_status |= MCG_STATUS_RIPV;
234 cpu_x86_inject_mce(NULL, env, 9, status, mcg_status, paddr,
235 (MCM_ADDR_PHYS << 6) | 0xc,
236 cpu_x86_support_mca_broadcast(env) ?
237 MCE_INJECT_BROADCAST : 0);
240 static void hardware_memory_error(void)
242 fprintf(stderr, "Hardware memory error!\n");
243 exit(1);
246 int kvm_arch_on_sigbus_vcpu(CPUState *env, int code, void *addr)
248 ram_addr_t ram_addr;
249 target_phys_addr_t paddr;
251 if ((env->mcg_cap & MCG_SER_P) && addr
252 && (code == BUS_MCEERR_AR || code == BUS_MCEERR_AO)) {
253 if (qemu_ram_addr_from_host(addr, &ram_addr) ||
254 !kvm_physical_memory_addr_from_ram(env->kvm_state, ram_addr,
255 &paddr)) {
256 fprintf(stderr, "Hardware memory error for memory used by "
257 "QEMU itself instead of guest system!\n");
258 /* Hope we are lucky for AO MCE */
259 if (code == BUS_MCEERR_AO) {
260 return 0;
261 } else {
262 hardware_memory_error();
265 kvm_hwpoison_page_add(ram_addr);
266 kvm_mce_inject(env, paddr, code);
267 } else {
268 if (code == BUS_MCEERR_AO) {
269 return 0;
270 } else if (code == BUS_MCEERR_AR) {
271 hardware_memory_error();
272 } else {
273 return 1;
276 return 0;
279 int kvm_arch_on_sigbus(int code, void *addr)
281 if ((first_cpu->mcg_cap & MCG_SER_P) && addr && code == BUS_MCEERR_AO) {
282 ram_addr_t ram_addr;
283 target_phys_addr_t paddr;
285 /* Hope we are lucky for AO MCE */
286 if (qemu_ram_addr_from_host(addr, &ram_addr) ||
287 !kvm_physical_memory_addr_from_ram(first_cpu->kvm_state, ram_addr,
288 &paddr)) {
289 fprintf(stderr, "Hardware memory error for memory used by "
290 "QEMU itself instead of guest system!: %p\n", addr);
291 return 0;
293 kvm_hwpoison_page_add(ram_addr);
294 kvm_mce_inject(first_cpu, paddr, code);
295 } else {
296 if (code == BUS_MCEERR_AO) {
297 return 0;
298 } else if (code == BUS_MCEERR_AR) {
299 hardware_memory_error();
300 } else {
301 return 1;
304 return 0;
307 static int kvm_inject_mce_oldstyle(CPUState *env)
309 if (!kvm_has_vcpu_events() && env->exception_injected == EXCP12_MCHK) {
310 unsigned int bank, bank_num = env->mcg_cap & 0xff;
311 struct kvm_x86_mce mce;
313 env->exception_injected = -1;
316 * There must be at least one bank in use if an MCE is pending.
317 * Find it and use its values for the event injection.
319 for (bank = 0; bank < bank_num; bank++) {
320 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
321 break;
324 assert(bank < bank_num);
326 mce.bank = bank;
327 mce.status = env->mce_banks[bank * 4 + 1];
328 mce.mcg_status = env->mcg_status;
329 mce.addr = env->mce_banks[bank * 4 + 2];
330 mce.misc = env->mce_banks[bank * 4 + 3];
332 return kvm_vcpu_ioctl(env, KVM_X86_SET_MCE, &mce);
334 return 0;
337 static void cpu_update_state(void *opaque, int running, int reason)
339 CPUState *env = opaque;
341 if (running) {
342 env->tsc_valid = false;
346 int kvm_arch_init_vcpu(CPUState *env)
348 struct {
349 struct kvm_cpuid2 cpuid;
350 struct kvm_cpuid_entry2 entries[100];
351 } QEMU_PACKED cpuid_data;
352 KVMState *s = env->kvm_state;
353 uint32_t limit, i, j, cpuid_i;
354 uint32_t unused;
355 struct kvm_cpuid_entry2 *c;
356 uint32_t signature[3];
357 int r;
359 env->cpuid_features &= kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
361 i = env->cpuid_ext_features & CPUID_EXT_HYPERVISOR;
362 env->cpuid_ext_features &= kvm_arch_get_supported_cpuid(s, 1, 0, R_ECX);
363 env->cpuid_ext_features |= i;
365 env->cpuid_ext2_features &= kvm_arch_get_supported_cpuid(s, 0x80000001,
366 0, R_EDX);
367 env->cpuid_ext3_features &= kvm_arch_get_supported_cpuid(s, 0x80000001,
368 0, R_ECX);
369 env->cpuid_svm_features &= kvm_arch_get_supported_cpuid(s, 0x8000000A,
370 0, R_EDX);
372 cpuid_i = 0;
374 /* Paravirtualization CPUIDs */
375 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
376 c = &cpuid_data.entries[cpuid_i++];
377 memset(c, 0, sizeof(*c));
378 c->function = KVM_CPUID_SIGNATURE;
379 c->eax = 0;
380 c->ebx = signature[0];
381 c->ecx = signature[1];
382 c->edx = signature[2];
384 c = &cpuid_data.entries[cpuid_i++];
385 memset(c, 0, sizeof(*c));
386 c->function = KVM_CPUID_FEATURES;
387 c->eax = env->cpuid_kvm_features &
388 kvm_arch_get_supported_cpuid(s, KVM_CPUID_FEATURES, 0, R_EAX);
390 has_msr_async_pf_en = c->eax & (1 << KVM_FEATURE_ASYNC_PF);
392 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
394 for (i = 0; i <= limit; i++) {
395 c = &cpuid_data.entries[cpuid_i++];
397 switch (i) {
398 case 2: {
399 /* Keep reading function 2 till all the input is received */
400 int times;
402 c->function = i;
403 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
404 KVM_CPUID_FLAG_STATE_READ_NEXT;
405 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
406 times = c->eax & 0xff;
408 for (j = 1; j < times; ++j) {
409 c = &cpuid_data.entries[cpuid_i++];
410 c->function = i;
411 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
412 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
414 break;
416 case 4:
417 case 0xb:
418 case 0xd:
419 for (j = 0; ; j++) {
420 if (i == 0xd && j == 64) {
421 break;
423 c->function = i;
424 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
425 c->index = j;
426 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
428 if (i == 4 && c->eax == 0) {
429 break;
431 if (i == 0xb && !(c->ecx & 0xff00)) {
432 break;
434 if (i == 0xd && c->eax == 0) {
435 continue;
437 c = &cpuid_data.entries[cpuid_i++];
439 break;
440 default:
441 c->function = i;
442 c->flags = 0;
443 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
444 break;
447 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
449 for (i = 0x80000000; i <= limit; i++) {
450 c = &cpuid_data.entries[cpuid_i++];
452 c->function = i;
453 c->flags = 0;
454 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
457 /* Call Centaur's CPUID instructions they are supported. */
458 if (env->cpuid_xlevel2 > 0) {
459 env->cpuid_ext4_features &=
460 kvm_arch_get_supported_cpuid(s, 0xC0000001, 0, R_EDX);
461 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
463 for (i = 0xC0000000; i <= limit; i++) {
464 c = &cpuid_data.entries[cpuid_i++];
466 c->function = i;
467 c->flags = 0;
468 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
472 cpuid_data.cpuid.nent = cpuid_i;
474 if (((env->cpuid_version >> 8)&0xF) >= 6
475 && (env->cpuid_features&(CPUID_MCE|CPUID_MCA)) == (CPUID_MCE|CPUID_MCA)
476 && kvm_check_extension(env->kvm_state, KVM_CAP_MCE) > 0) {
477 uint64_t mcg_cap;
478 int banks;
479 int ret;
481 ret = kvm_get_mce_cap_supported(env->kvm_state, &mcg_cap, &banks);
482 if (ret < 0) {
483 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
484 return ret;
487 if (banks > MCE_BANKS_DEF) {
488 banks = MCE_BANKS_DEF;
490 mcg_cap &= MCE_CAP_DEF;
491 mcg_cap |= banks;
492 ret = kvm_vcpu_ioctl(env, KVM_X86_SETUP_MCE, &mcg_cap);
493 if (ret < 0) {
494 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
495 return ret;
498 env->mcg_cap = mcg_cap;
501 qemu_add_vm_change_state_handler(cpu_update_state, env);
503 r = kvm_vcpu_ioctl(env, KVM_SET_CPUID2, &cpuid_data);
504 if (r) {
505 return r;
508 r = kvm_check_extension(env->kvm_state, KVM_CAP_TSC_CONTROL);
509 if (r && env->tsc_khz) {
510 r = kvm_vcpu_ioctl(env, KVM_SET_TSC_KHZ, env->tsc_khz);
511 if (r < 0) {
512 fprintf(stderr, "KVM_SET_TSC_KHZ failed\n");
513 return r;
517 return 0;
520 void kvm_arch_reset_vcpu(CPUState *env)
522 env->exception_injected = -1;
523 env->interrupt_injected = -1;
524 env->xcr0 = 1;
525 if (kvm_irqchip_in_kernel()) {
526 env->mp_state = cpu_is_bsp(env) ? KVM_MP_STATE_RUNNABLE :
527 KVM_MP_STATE_UNINITIALIZED;
528 } else {
529 env->mp_state = KVM_MP_STATE_RUNNABLE;
533 static int kvm_get_supported_msrs(KVMState *s)
535 static int kvm_supported_msrs;
536 int ret = 0;
538 /* first time */
539 if (kvm_supported_msrs == 0) {
540 struct kvm_msr_list msr_list, *kvm_msr_list;
542 kvm_supported_msrs = -1;
544 /* Obtain MSR list from KVM. These are the MSRs that we must
545 * save/restore */
546 msr_list.nmsrs = 0;
547 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
548 if (ret < 0 && ret != -E2BIG) {
549 return ret;
551 /* Old kernel modules had a bug and could write beyond the provided
552 memory. Allocate at least a safe amount of 1K. */
553 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
554 msr_list.nmsrs *
555 sizeof(msr_list.indices[0])));
557 kvm_msr_list->nmsrs = msr_list.nmsrs;
558 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
559 if (ret >= 0) {
560 int i;
562 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
563 if (kvm_msr_list->indices[i] == MSR_STAR) {
564 has_msr_star = true;
565 continue;
567 if (kvm_msr_list->indices[i] == MSR_VM_HSAVE_PA) {
568 has_msr_hsave_pa = true;
569 continue;
574 g_free(kvm_msr_list);
577 return ret;
580 int kvm_arch_init(KVMState *s)
582 uint64_t identity_base = 0xfffbc000;
583 int ret;
584 struct utsname utsname;
586 ret = kvm_get_supported_msrs(s);
587 if (ret < 0) {
588 return ret;
591 uname(&utsname);
592 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
595 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
596 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
597 * Since these must be part of guest physical memory, we need to allocate
598 * them, both by setting their start addresses in the kernel and by
599 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
601 * Older KVM versions may not support setting the identity map base. In
602 * that case we need to stick with the default, i.e. a 256K maximum BIOS
603 * size.
605 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
606 /* Allows up to 16M BIOSes. */
607 identity_base = 0xfeffc000;
609 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
610 if (ret < 0) {
611 return ret;
615 /* Set TSS base one page after EPT identity map. */
616 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
617 if (ret < 0) {
618 return ret;
621 /* Tell fw_cfg to notify the BIOS to reserve the range. */
622 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
623 if (ret < 0) {
624 fprintf(stderr, "e820_add_entry() table is full\n");
625 return ret;
627 qemu_register_reset(kvm_unpoison_all, NULL);
629 return 0;
632 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
634 lhs->selector = rhs->selector;
635 lhs->base = rhs->base;
636 lhs->limit = rhs->limit;
637 lhs->type = 3;
638 lhs->present = 1;
639 lhs->dpl = 3;
640 lhs->db = 0;
641 lhs->s = 1;
642 lhs->l = 0;
643 lhs->g = 0;
644 lhs->avl = 0;
645 lhs->unusable = 0;
648 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
650 unsigned flags = rhs->flags;
651 lhs->selector = rhs->selector;
652 lhs->base = rhs->base;
653 lhs->limit = rhs->limit;
654 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
655 lhs->present = (flags & DESC_P_MASK) != 0;
656 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
657 lhs->db = (flags >> DESC_B_SHIFT) & 1;
658 lhs->s = (flags & DESC_S_MASK) != 0;
659 lhs->l = (flags >> DESC_L_SHIFT) & 1;
660 lhs->g = (flags & DESC_G_MASK) != 0;
661 lhs->avl = (flags & DESC_AVL_MASK) != 0;
662 lhs->unusable = 0;
665 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
667 lhs->selector = rhs->selector;
668 lhs->base = rhs->base;
669 lhs->limit = rhs->limit;
670 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
671 (rhs->present * DESC_P_MASK) |
672 (rhs->dpl << DESC_DPL_SHIFT) |
673 (rhs->db << DESC_B_SHIFT) |
674 (rhs->s * DESC_S_MASK) |
675 (rhs->l << DESC_L_SHIFT) |
676 (rhs->g * DESC_G_MASK) |
677 (rhs->avl * DESC_AVL_MASK);
680 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
682 if (set) {
683 *kvm_reg = *qemu_reg;
684 } else {
685 *qemu_reg = *kvm_reg;
689 static int kvm_getput_regs(CPUState *env, int set)
691 struct kvm_regs regs;
692 int ret = 0;
694 if (!set) {
695 ret = kvm_vcpu_ioctl(env, KVM_GET_REGS, &regs);
696 if (ret < 0) {
697 return ret;
701 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
702 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
703 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
704 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
705 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
706 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
707 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
708 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
709 #ifdef TARGET_X86_64
710 kvm_getput_reg(&regs.r8, &env->regs[8], set);
711 kvm_getput_reg(&regs.r9, &env->regs[9], set);
712 kvm_getput_reg(&regs.r10, &env->regs[10], set);
713 kvm_getput_reg(&regs.r11, &env->regs[11], set);
714 kvm_getput_reg(&regs.r12, &env->regs[12], set);
715 kvm_getput_reg(&regs.r13, &env->regs[13], set);
716 kvm_getput_reg(&regs.r14, &env->regs[14], set);
717 kvm_getput_reg(&regs.r15, &env->regs[15], set);
718 #endif
720 kvm_getput_reg(&regs.rflags, &env->eflags, set);
721 kvm_getput_reg(&regs.rip, &env->eip, set);
723 if (set) {
724 ret = kvm_vcpu_ioctl(env, KVM_SET_REGS, &regs);
727 return ret;
730 static int kvm_put_fpu(CPUState *env)
732 struct kvm_fpu fpu;
733 int i;
735 memset(&fpu, 0, sizeof fpu);
736 fpu.fsw = env->fpus & ~(7 << 11);
737 fpu.fsw |= (env->fpstt & 7) << 11;
738 fpu.fcw = env->fpuc;
739 fpu.last_opcode = env->fpop;
740 fpu.last_ip = env->fpip;
741 fpu.last_dp = env->fpdp;
742 for (i = 0; i < 8; ++i) {
743 fpu.ftwx |= (!env->fptags[i]) << i;
745 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
746 memcpy(fpu.xmm, env->xmm_regs, sizeof env->xmm_regs);
747 fpu.mxcsr = env->mxcsr;
749 return kvm_vcpu_ioctl(env, KVM_SET_FPU, &fpu);
752 #define XSAVE_CWD_RIP 2
753 #define XSAVE_CWD_RDP 4
754 #define XSAVE_MXCSR 6
755 #define XSAVE_ST_SPACE 8
756 #define XSAVE_XMM_SPACE 40
757 #define XSAVE_XSTATE_BV 128
758 #define XSAVE_YMMH_SPACE 144
760 static int kvm_put_xsave(CPUState *env)
762 int i, r;
763 struct kvm_xsave* xsave;
764 uint16_t cwd, swd, twd;
766 if (!kvm_has_xsave()) {
767 return kvm_put_fpu(env);
770 xsave = qemu_memalign(4096, sizeof(struct kvm_xsave));
771 memset(xsave, 0, sizeof(struct kvm_xsave));
772 cwd = swd = twd = 0;
773 swd = env->fpus & ~(7 << 11);
774 swd |= (env->fpstt & 7) << 11;
775 cwd = env->fpuc;
776 for (i = 0; i < 8; ++i) {
777 twd |= (!env->fptags[i]) << i;
779 xsave->region[0] = (uint32_t)(swd << 16) + cwd;
780 xsave->region[1] = (uint32_t)(env->fpop << 16) + twd;
781 memcpy(&xsave->region[XSAVE_CWD_RIP], &env->fpip, sizeof(env->fpip));
782 memcpy(&xsave->region[XSAVE_CWD_RDP], &env->fpdp, sizeof(env->fpdp));
783 memcpy(&xsave->region[XSAVE_ST_SPACE], env->fpregs,
784 sizeof env->fpregs);
785 memcpy(&xsave->region[XSAVE_XMM_SPACE], env->xmm_regs,
786 sizeof env->xmm_regs);
787 xsave->region[XSAVE_MXCSR] = env->mxcsr;
788 *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV] = env->xstate_bv;
789 memcpy(&xsave->region[XSAVE_YMMH_SPACE], env->ymmh_regs,
790 sizeof env->ymmh_regs);
791 r = kvm_vcpu_ioctl(env, KVM_SET_XSAVE, xsave);
792 g_free(xsave);
793 return r;
796 static int kvm_put_xcrs(CPUState *env)
798 struct kvm_xcrs xcrs;
800 if (!kvm_has_xcrs()) {
801 return 0;
804 xcrs.nr_xcrs = 1;
805 xcrs.flags = 0;
806 xcrs.xcrs[0].xcr = 0;
807 xcrs.xcrs[0].value = env->xcr0;
808 return kvm_vcpu_ioctl(env, KVM_SET_XCRS, &xcrs);
811 static int kvm_put_sregs(CPUState *env)
813 struct kvm_sregs sregs;
815 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
816 if (env->interrupt_injected >= 0) {
817 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
818 (uint64_t)1 << (env->interrupt_injected % 64);
821 if ((env->eflags & VM_MASK)) {
822 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
823 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
824 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
825 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
826 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
827 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
828 } else {
829 set_seg(&sregs.cs, &env->segs[R_CS]);
830 set_seg(&sregs.ds, &env->segs[R_DS]);
831 set_seg(&sregs.es, &env->segs[R_ES]);
832 set_seg(&sregs.fs, &env->segs[R_FS]);
833 set_seg(&sregs.gs, &env->segs[R_GS]);
834 set_seg(&sregs.ss, &env->segs[R_SS]);
837 set_seg(&sregs.tr, &env->tr);
838 set_seg(&sregs.ldt, &env->ldt);
840 sregs.idt.limit = env->idt.limit;
841 sregs.idt.base = env->idt.base;
842 sregs.gdt.limit = env->gdt.limit;
843 sregs.gdt.base = env->gdt.base;
845 sregs.cr0 = env->cr[0];
846 sregs.cr2 = env->cr[2];
847 sregs.cr3 = env->cr[3];
848 sregs.cr4 = env->cr[4];
850 sregs.cr8 = cpu_get_apic_tpr(env->apic_state);
851 sregs.apic_base = cpu_get_apic_base(env->apic_state);
853 sregs.efer = env->efer;
855 return kvm_vcpu_ioctl(env, KVM_SET_SREGS, &sregs);
858 static void kvm_msr_entry_set(struct kvm_msr_entry *entry,
859 uint32_t index, uint64_t value)
861 entry->index = index;
862 entry->data = value;
865 static int kvm_put_msrs(CPUState *env, int level)
867 struct {
868 struct kvm_msrs info;
869 struct kvm_msr_entry entries[100];
870 } msr_data;
871 struct kvm_msr_entry *msrs = msr_data.entries;
872 int n = 0;
874 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_CS, env->sysenter_cs);
875 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
876 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
877 kvm_msr_entry_set(&msrs[n++], MSR_PAT, env->pat);
878 if (has_msr_star) {
879 kvm_msr_entry_set(&msrs[n++], MSR_STAR, env->star);
881 if (has_msr_hsave_pa) {
882 kvm_msr_entry_set(&msrs[n++], MSR_VM_HSAVE_PA, env->vm_hsave);
884 #ifdef TARGET_X86_64
885 if (lm_capable_kernel) {
886 kvm_msr_entry_set(&msrs[n++], MSR_CSTAR, env->cstar);
887 kvm_msr_entry_set(&msrs[n++], MSR_KERNELGSBASE, env->kernelgsbase);
888 kvm_msr_entry_set(&msrs[n++], MSR_FMASK, env->fmask);
889 kvm_msr_entry_set(&msrs[n++], MSR_LSTAR, env->lstar);
891 #endif
892 if (level == KVM_PUT_FULL_STATE) {
894 * KVM is yet unable to synchronize TSC values of multiple VCPUs on
895 * writeback. Until this is fixed, we only write the offset to SMP
896 * guests after migration, desynchronizing the VCPUs, but avoiding
897 * huge jump-backs that would occur without any writeback at all.
899 if (smp_cpus == 1 || env->tsc != 0) {
900 kvm_msr_entry_set(&msrs[n++], MSR_IA32_TSC, env->tsc);
904 * The following paravirtual MSRs have side effects on the guest or are
905 * too heavy for normal writeback. Limit them to reset or full state
906 * updates.
908 if (level >= KVM_PUT_RESET_STATE) {
909 kvm_msr_entry_set(&msrs[n++], MSR_KVM_SYSTEM_TIME,
910 env->system_time_msr);
911 kvm_msr_entry_set(&msrs[n++], MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
912 if (has_msr_async_pf_en) {
913 kvm_msr_entry_set(&msrs[n++], MSR_KVM_ASYNC_PF_EN,
914 env->async_pf_en_msr);
917 if (env->mcg_cap) {
918 int i;
920 kvm_msr_entry_set(&msrs[n++], MSR_MCG_STATUS, env->mcg_status);
921 kvm_msr_entry_set(&msrs[n++], MSR_MCG_CTL, env->mcg_ctl);
922 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
923 kvm_msr_entry_set(&msrs[n++], MSR_MC0_CTL + i, env->mce_banks[i]);
927 msr_data.info.nmsrs = n;
929 return kvm_vcpu_ioctl(env, KVM_SET_MSRS, &msr_data);
934 static int kvm_get_fpu(CPUState *env)
936 struct kvm_fpu fpu;
937 int i, ret;
939 ret = kvm_vcpu_ioctl(env, KVM_GET_FPU, &fpu);
940 if (ret < 0) {
941 return ret;
944 env->fpstt = (fpu.fsw >> 11) & 7;
945 env->fpus = fpu.fsw;
946 env->fpuc = fpu.fcw;
947 env->fpop = fpu.last_opcode;
948 env->fpip = fpu.last_ip;
949 env->fpdp = fpu.last_dp;
950 for (i = 0; i < 8; ++i) {
951 env->fptags[i] = !((fpu.ftwx >> i) & 1);
953 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
954 memcpy(env->xmm_regs, fpu.xmm, sizeof env->xmm_regs);
955 env->mxcsr = fpu.mxcsr;
957 return 0;
960 static int kvm_get_xsave(CPUState *env)
962 struct kvm_xsave* xsave;
963 int ret, i;
964 uint16_t cwd, swd, twd;
966 if (!kvm_has_xsave()) {
967 return kvm_get_fpu(env);
970 xsave = qemu_memalign(4096, sizeof(struct kvm_xsave));
971 ret = kvm_vcpu_ioctl(env, KVM_GET_XSAVE, xsave);
972 if (ret < 0) {
973 g_free(xsave);
974 return ret;
977 cwd = (uint16_t)xsave->region[0];
978 swd = (uint16_t)(xsave->region[0] >> 16);
979 twd = (uint16_t)xsave->region[1];
980 env->fpop = (uint16_t)(xsave->region[1] >> 16);
981 env->fpstt = (swd >> 11) & 7;
982 env->fpus = swd;
983 env->fpuc = cwd;
984 for (i = 0; i < 8; ++i) {
985 env->fptags[i] = !((twd >> i) & 1);
987 memcpy(&env->fpip, &xsave->region[XSAVE_CWD_RIP], sizeof(env->fpip));
988 memcpy(&env->fpdp, &xsave->region[XSAVE_CWD_RDP], sizeof(env->fpdp));
989 env->mxcsr = xsave->region[XSAVE_MXCSR];
990 memcpy(env->fpregs, &xsave->region[XSAVE_ST_SPACE],
991 sizeof env->fpregs);
992 memcpy(env->xmm_regs, &xsave->region[XSAVE_XMM_SPACE],
993 sizeof env->xmm_regs);
994 env->xstate_bv = *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV];
995 memcpy(env->ymmh_regs, &xsave->region[XSAVE_YMMH_SPACE],
996 sizeof env->ymmh_regs);
997 g_free(xsave);
998 return 0;
1001 static int kvm_get_xcrs(CPUState *env)
1003 int i, ret;
1004 struct kvm_xcrs xcrs;
1006 if (!kvm_has_xcrs()) {
1007 return 0;
1010 ret = kvm_vcpu_ioctl(env, KVM_GET_XCRS, &xcrs);
1011 if (ret < 0) {
1012 return ret;
1015 for (i = 0; i < xcrs.nr_xcrs; i++) {
1016 /* Only support xcr0 now */
1017 if (xcrs.xcrs[0].xcr == 0) {
1018 env->xcr0 = xcrs.xcrs[0].value;
1019 break;
1022 return 0;
1025 static int kvm_get_sregs(CPUState *env)
1027 struct kvm_sregs sregs;
1028 uint32_t hflags;
1029 int bit, i, ret;
1031 ret = kvm_vcpu_ioctl(env, KVM_GET_SREGS, &sregs);
1032 if (ret < 0) {
1033 return ret;
1036 /* There can only be one pending IRQ set in the bitmap at a time, so try
1037 to find it and save its number instead (-1 for none). */
1038 env->interrupt_injected = -1;
1039 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
1040 if (sregs.interrupt_bitmap[i]) {
1041 bit = ctz64(sregs.interrupt_bitmap[i]);
1042 env->interrupt_injected = i * 64 + bit;
1043 break;
1047 get_seg(&env->segs[R_CS], &sregs.cs);
1048 get_seg(&env->segs[R_DS], &sregs.ds);
1049 get_seg(&env->segs[R_ES], &sregs.es);
1050 get_seg(&env->segs[R_FS], &sregs.fs);
1051 get_seg(&env->segs[R_GS], &sregs.gs);
1052 get_seg(&env->segs[R_SS], &sregs.ss);
1054 get_seg(&env->tr, &sregs.tr);
1055 get_seg(&env->ldt, &sregs.ldt);
1057 env->idt.limit = sregs.idt.limit;
1058 env->idt.base = sregs.idt.base;
1059 env->gdt.limit = sregs.gdt.limit;
1060 env->gdt.base = sregs.gdt.base;
1062 env->cr[0] = sregs.cr0;
1063 env->cr[2] = sregs.cr2;
1064 env->cr[3] = sregs.cr3;
1065 env->cr[4] = sregs.cr4;
1067 cpu_set_apic_base(env->apic_state, sregs.apic_base);
1069 env->efer = sregs.efer;
1070 //cpu_set_apic_tpr(env->apic_state, sregs.cr8);
1072 #define HFLAG_COPY_MASK \
1073 ~( HF_CPL_MASK | HF_PE_MASK | HF_MP_MASK | HF_EM_MASK | \
1074 HF_TS_MASK | HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK | \
1075 HF_OSFXSR_MASK | HF_LMA_MASK | HF_CS32_MASK | \
1076 HF_SS32_MASK | HF_CS64_MASK | HF_ADDSEG_MASK)
1078 hflags = (env->segs[R_CS].flags >> DESC_DPL_SHIFT) & HF_CPL_MASK;
1079 hflags |= (env->cr[0] & CR0_PE_MASK) << (HF_PE_SHIFT - CR0_PE_SHIFT);
1080 hflags |= (env->cr[0] << (HF_MP_SHIFT - CR0_MP_SHIFT)) &
1081 (HF_MP_MASK | HF_EM_MASK | HF_TS_MASK);
1082 hflags |= (env->eflags & (HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK));
1083 hflags |= (env->cr[4] & CR4_OSFXSR_MASK) <<
1084 (HF_OSFXSR_SHIFT - CR4_OSFXSR_SHIFT);
1086 if (env->efer & MSR_EFER_LMA) {
1087 hflags |= HF_LMA_MASK;
1090 if ((hflags & HF_LMA_MASK) && (env->segs[R_CS].flags & DESC_L_MASK)) {
1091 hflags |= HF_CS32_MASK | HF_SS32_MASK | HF_CS64_MASK;
1092 } else {
1093 hflags |= (env->segs[R_CS].flags & DESC_B_MASK) >>
1094 (DESC_B_SHIFT - HF_CS32_SHIFT);
1095 hflags |= (env->segs[R_SS].flags & DESC_B_MASK) >>
1096 (DESC_B_SHIFT - HF_SS32_SHIFT);
1097 if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK) ||
1098 !(hflags & HF_CS32_MASK)) {
1099 hflags |= HF_ADDSEG_MASK;
1100 } else {
1101 hflags |= ((env->segs[R_DS].base | env->segs[R_ES].base |
1102 env->segs[R_SS].base) != 0) << HF_ADDSEG_SHIFT;
1105 env->hflags = (env->hflags & HFLAG_COPY_MASK) | hflags;
1107 return 0;
1110 static int kvm_get_msrs(CPUState *env)
1112 struct {
1113 struct kvm_msrs info;
1114 struct kvm_msr_entry entries[100];
1115 } msr_data;
1116 struct kvm_msr_entry *msrs = msr_data.entries;
1117 int ret, i, n;
1119 n = 0;
1120 msrs[n++].index = MSR_IA32_SYSENTER_CS;
1121 msrs[n++].index = MSR_IA32_SYSENTER_ESP;
1122 msrs[n++].index = MSR_IA32_SYSENTER_EIP;
1123 msrs[n++].index = MSR_PAT;
1124 if (has_msr_star) {
1125 msrs[n++].index = MSR_STAR;
1127 if (has_msr_hsave_pa) {
1128 msrs[n++].index = MSR_VM_HSAVE_PA;
1131 if (!env->tsc_valid) {
1132 msrs[n++].index = MSR_IA32_TSC;
1133 env->tsc_valid = !vm_running;
1136 #ifdef TARGET_X86_64
1137 if (lm_capable_kernel) {
1138 msrs[n++].index = MSR_CSTAR;
1139 msrs[n++].index = MSR_KERNELGSBASE;
1140 msrs[n++].index = MSR_FMASK;
1141 msrs[n++].index = MSR_LSTAR;
1143 #endif
1144 msrs[n++].index = MSR_KVM_SYSTEM_TIME;
1145 msrs[n++].index = MSR_KVM_WALL_CLOCK;
1146 if (has_msr_async_pf_en) {
1147 msrs[n++].index = MSR_KVM_ASYNC_PF_EN;
1150 if (env->mcg_cap) {
1151 msrs[n++].index = MSR_MCG_STATUS;
1152 msrs[n++].index = MSR_MCG_CTL;
1153 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1154 msrs[n++].index = MSR_MC0_CTL + i;
1158 msr_data.info.nmsrs = n;
1159 ret = kvm_vcpu_ioctl(env, KVM_GET_MSRS, &msr_data);
1160 if (ret < 0) {
1161 return ret;
1164 for (i = 0; i < ret; i++) {
1165 switch (msrs[i].index) {
1166 case MSR_IA32_SYSENTER_CS:
1167 env->sysenter_cs = msrs[i].data;
1168 break;
1169 case MSR_IA32_SYSENTER_ESP:
1170 env->sysenter_esp = msrs[i].data;
1171 break;
1172 case MSR_IA32_SYSENTER_EIP:
1173 env->sysenter_eip = msrs[i].data;
1174 break;
1175 case MSR_PAT:
1176 env->pat = msrs[i].data;
1177 break;
1178 case MSR_STAR:
1179 env->star = msrs[i].data;
1180 break;
1181 #ifdef TARGET_X86_64
1182 case MSR_CSTAR:
1183 env->cstar = msrs[i].data;
1184 break;
1185 case MSR_KERNELGSBASE:
1186 env->kernelgsbase = msrs[i].data;
1187 break;
1188 case MSR_FMASK:
1189 env->fmask = msrs[i].data;
1190 break;
1191 case MSR_LSTAR:
1192 env->lstar = msrs[i].data;
1193 break;
1194 #endif
1195 case MSR_IA32_TSC:
1196 env->tsc = msrs[i].data;
1197 break;
1198 case MSR_VM_HSAVE_PA:
1199 env->vm_hsave = msrs[i].data;
1200 break;
1201 case MSR_KVM_SYSTEM_TIME:
1202 env->system_time_msr = msrs[i].data;
1203 break;
1204 case MSR_KVM_WALL_CLOCK:
1205 env->wall_clock_msr = msrs[i].data;
1206 break;
1207 case MSR_MCG_STATUS:
1208 env->mcg_status = msrs[i].data;
1209 break;
1210 case MSR_MCG_CTL:
1211 env->mcg_ctl = msrs[i].data;
1212 break;
1213 default:
1214 if (msrs[i].index >= MSR_MC0_CTL &&
1215 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
1216 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
1218 break;
1219 case MSR_KVM_ASYNC_PF_EN:
1220 env->async_pf_en_msr = msrs[i].data;
1221 break;
1225 return 0;
1228 static int kvm_put_mp_state(CPUState *env)
1230 struct kvm_mp_state mp_state = { .mp_state = env->mp_state };
1232 return kvm_vcpu_ioctl(env, KVM_SET_MP_STATE, &mp_state);
1235 static int kvm_get_mp_state(CPUState *env)
1237 struct kvm_mp_state mp_state;
1238 int ret;
1240 ret = kvm_vcpu_ioctl(env, KVM_GET_MP_STATE, &mp_state);
1241 if (ret < 0) {
1242 return ret;
1244 env->mp_state = mp_state.mp_state;
1245 if (kvm_irqchip_in_kernel()) {
1246 env->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
1248 return 0;
1251 static int kvm_put_vcpu_events(CPUState *env, int level)
1253 struct kvm_vcpu_events events;
1255 if (!kvm_has_vcpu_events()) {
1256 return 0;
1259 events.exception.injected = (env->exception_injected >= 0);
1260 events.exception.nr = env->exception_injected;
1261 events.exception.has_error_code = env->has_error_code;
1262 events.exception.error_code = env->error_code;
1264 events.interrupt.injected = (env->interrupt_injected >= 0);
1265 events.interrupt.nr = env->interrupt_injected;
1266 events.interrupt.soft = env->soft_interrupt;
1268 events.nmi.injected = env->nmi_injected;
1269 events.nmi.pending = env->nmi_pending;
1270 events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
1272 events.sipi_vector = env->sipi_vector;
1274 events.flags = 0;
1275 if (level >= KVM_PUT_RESET_STATE) {
1276 events.flags |=
1277 KVM_VCPUEVENT_VALID_NMI_PENDING | KVM_VCPUEVENT_VALID_SIPI_VECTOR;
1280 return kvm_vcpu_ioctl(env, KVM_SET_VCPU_EVENTS, &events);
1283 static int kvm_get_vcpu_events(CPUState *env)
1285 struct kvm_vcpu_events events;
1286 int ret;
1288 if (!kvm_has_vcpu_events()) {
1289 return 0;
1292 ret = kvm_vcpu_ioctl(env, KVM_GET_VCPU_EVENTS, &events);
1293 if (ret < 0) {
1294 return ret;
1296 env->exception_injected =
1297 events.exception.injected ? events.exception.nr : -1;
1298 env->has_error_code = events.exception.has_error_code;
1299 env->error_code = events.exception.error_code;
1301 env->interrupt_injected =
1302 events.interrupt.injected ? events.interrupt.nr : -1;
1303 env->soft_interrupt = events.interrupt.soft;
1305 env->nmi_injected = events.nmi.injected;
1306 env->nmi_pending = events.nmi.pending;
1307 if (events.nmi.masked) {
1308 env->hflags2 |= HF2_NMI_MASK;
1309 } else {
1310 env->hflags2 &= ~HF2_NMI_MASK;
1313 env->sipi_vector = events.sipi_vector;
1315 return 0;
1318 static int kvm_guest_debug_workarounds(CPUState *env)
1320 int ret = 0;
1321 unsigned long reinject_trap = 0;
1323 if (!kvm_has_vcpu_events()) {
1324 if (env->exception_injected == 1) {
1325 reinject_trap = KVM_GUESTDBG_INJECT_DB;
1326 } else if (env->exception_injected == 3) {
1327 reinject_trap = KVM_GUESTDBG_INJECT_BP;
1329 env->exception_injected = -1;
1333 * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
1334 * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
1335 * by updating the debug state once again if single-stepping is on.
1336 * Another reason to call kvm_update_guest_debug here is a pending debug
1337 * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
1338 * reinject them via SET_GUEST_DEBUG.
1340 if (reinject_trap ||
1341 (!kvm_has_robust_singlestep() && env->singlestep_enabled)) {
1342 ret = kvm_update_guest_debug(env, reinject_trap);
1344 return ret;
1347 static int kvm_put_debugregs(CPUState *env)
1349 struct kvm_debugregs dbgregs;
1350 int i;
1352 if (!kvm_has_debugregs()) {
1353 return 0;
1356 for (i = 0; i < 4; i++) {
1357 dbgregs.db[i] = env->dr[i];
1359 dbgregs.dr6 = env->dr[6];
1360 dbgregs.dr7 = env->dr[7];
1361 dbgregs.flags = 0;
1363 return kvm_vcpu_ioctl(env, KVM_SET_DEBUGREGS, &dbgregs);
1366 static int kvm_get_debugregs(CPUState *env)
1368 struct kvm_debugregs dbgregs;
1369 int i, ret;
1371 if (!kvm_has_debugregs()) {
1372 return 0;
1375 ret = kvm_vcpu_ioctl(env, KVM_GET_DEBUGREGS, &dbgregs);
1376 if (ret < 0) {
1377 return ret;
1379 for (i = 0; i < 4; i++) {
1380 env->dr[i] = dbgregs.db[i];
1382 env->dr[4] = env->dr[6] = dbgregs.dr6;
1383 env->dr[5] = env->dr[7] = dbgregs.dr7;
1385 return 0;
1388 int kvm_arch_put_registers(CPUState *env, int level)
1390 int ret;
1392 assert(cpu_is_stopped(env) || qemu_cpu_is_self(env));
1394 ret = kvm_getput_regs(env, 1);
1395 if (ret < 0) {
1396 return ret;
1398 ret = kvm_put_xsave(env);
1399 if (ret < 0) {
1400 return ret;
1402 ret = kvm_put_xcrs(env);
1403 if (ret < 0) {
1404 return ret;
1406 ret = kvm_put_sregs(env);
1407 if (ret < 0) {
1408 return ret;
1410 /* must be before kvm_put_msrs */
1411 ret = kvm_inject_mce_oldstyle(env);
1412 if (ret < 0) {
1413 return ret;
1415 ret = kvm_put_msrs(env, level);
1416 if (ret < 0) {
1417 return ret;
1419 if (level >= KVM_PUT_RESET_STATE) {
1420 ret = kvm_put_mp_state(env);
1421 if (ret < 0) {
1422 return ret;
1425 ret = kvm_put_vcpu_events(env, level);
1426 if (ret < 0) {
1427 return ret;
1429 ret = kvm_put_debugregs(env);
1430 if (ret < 0) {
1431 return ret;
1433 /* must be last */
1434 ret = kvm_guest_debug_workarounds(env);
1435 if (ret < 0) {
1436 return ret;
1438 return 0;
1441 int kvm_arch_get_registers(CPUState *env)
1443 int ret;
1445 assert(cpu_is_stopped(env) || qemu_cpu_is_self(env));
1447 ret = kvm_getput_regs(env, 0);
1448 if (ret < 0) {
1449 return ret;
1451 ret = kvm_get_xsave(env);
1452 if (ret < 0) {
1453 return ret;
1455 ret = kvm_get_xcrs(env);
1456 if (ret < 0) {
1457 return ret;
1459 ret = kvm_get_sregs(env);
1460 if (ret < 0) {
1461 return ret;
1463 ret = kvm_get_msrs(env);
1464 if (ret < 0) {
1465 return ret;
1467 ret = kvm_get_mp_state(env);
1468 if (ret < 0) {
1469 return ret;
1471 ret = kvm_get_vcpu_events(env);
1472 if (ret < 0) {
1473 return ret;
1475 ret = kvm_get_debugregs(env);
1476 if (ret < 0) {
1477 return ret;
1479 return 0;
1482 void kvm_arch_pre_run(CPUState *env, struct kvm_run *run)
1484 int ret;
1486 /* Inject NMI */
1487 if (env->interrupt_request & CPU_INTERRUPT_NMI) {
1488 env->interrupt_request &= ~CPU_INTERRUPT_NMI;
1489 DPRINTF("injected NMI\n");
1490 ret = kvm_vcpu_ioctl(env, KVM_NMI);
1491 if (ret < 0) {
1492 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
1493 strerror(-ret));
1497 if (!kvm_irqchip_in_kernel()) {
1498 /* Force the VCPU out of its inner loop to process the INIT request */
1499 if (env->interrupt_request & CPU_INTERRUPT_INIT) {
1500 env->exit_request = 1;
1503 /* Try to inject an interrupt if the guest can accept it */
1504 if (run->ready_for_interrupt_injection &&
1505 (env->interrupt_request & CPU_INTERRUPT_HARD) &&
1506 (env->eflags & IF_MASK)) {
1507 int irq;
1509 env->interrupt_request &= ~CPU_INTERRUPT_HARD;
1510 irq = cpu_get_pic_interrupt(env);
1511 if (irq >= 0) {
1512 struct kvm_interrupt intr;
1514 intr.irq = irq;
1515 DPRINTF("injected interrupt %d\n", irq);
1516 ret = kvm_vcpu_ioctl(env, KVM_INTERRUPT, &intr);
1517 if (ret < 0) {
1518 fprintf(stderr,
1519 "KVM: injection failed, interrupt lost (%s)\n",
1520 strerror(-ret));
1525 /* If we have an interrupt but the guest is not ready to receive an
1526 * interrupt, request an interrupt window exit. This will
1527 * cause a return to userspace as soon as the guest is ready to
1528 * receive interrupts. */
1529 if ((env->interrupt_request & CPU_INTERRUPT_HARD)) {
1530 run->request_interrupt_window = 1;
1531 } else {
1532 run->request_interrupt_window = 0;
1535 DPRINTF("setting tpr\n");
1536 run->cr8 = cpu_get_apic_tpr(env->apic_state);
1540 void kvm_arch_post_run(CPUState *env, struct kvm_run *run)
1542 if (run->if_flag) {
1543 env->eflags |= IF_MASK;
1544 } else {
1545 env->eflags &= ~IF_MASK;
1547 cpu_set_apic_tpr(env->apic_state, run->cr8);
1548 cpu_set_apic_base(env->apic_state, run->apic_base);
1551 int kvm_arch_process_async_events(CPUState *env)
1553 if (env->interrupt_request & CPU_INTERRUPT_MCE) {
1554 /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
1555 assert(env->mcg_cap);
1557 env->interrupt_request &= ~CPU_INTERRUPT_MCE;
1559 kvm_cpu_synchronize_state(env);
1561 if (env->exception_injected == EXCP08_DBLE) {
1562 /* this means triple fault */
1563 qemu_system_reset_request();
1564 env->exit_request = 1;
1565 return 0;
1567 env->exception_injected = EXCP12_MCHK;
1568 env->has_error_code = 0;
1570 env->halted = 0;
1571 if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
1572 env->mp_state = KVM_MP_STATE_RUNNABLE;
1576 if (kvm_irqchip_in_kernel()) {
1577 return 0;
1580 if (((env->interrupt_request & CPU_INTERRUPT_HARD) &&
1581 (env->eflags & IF_MASK)) ||
1582 (env->interrupt_request & CPU_INTERRUPT_NMI)) {
1583 env->halted = 0;
1585 if (env->interrupt_request & CPU_INTERRUPT_INIT) {
1586 kvm_cpu_synchronize_state(env);
1587 do_cpu_init(env);
1589 if (env->interrupt_request & CPU_INTERRUPT_SIPI) {
1590 kvm_cpu_synchronize_state(env);
1591 do_cpu_sipi(env);
1594 return env->halted;
1597 static int kvm_handle_halt(CPUState *env)
1599 if (!((env->interrupt_request & CPU_INTERRUPT_HARD) &&
1600 (env->eflags & IF_MASK)) &&
1601 !(env->interrupt_request & CPU_INTERRUPT_NMI)) {
1602 env->halted = 1;
1603 return EXCP_HLT;
1606 return 0;
1609 int kvm_arch_insert_sw_breakpoint(CPUState *env, struct kvm_sw_breakpoint *bp)
1611 static const uint8_t int3 = 0xcc;
1613 if (cpu_memory_rw_debug(env, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
1614 cpu_memory_rw_debug(env, bp->pc, (uint8_t *)&int3, 1, 1)) {
1615 return -EINVAL;
1617 return 0;
1620 int kvm_arch_remove_sw_breakpoint(CPUState *env, struct kvm_sw_breakpoint *bp)
1622 uint8_t int3;
1624 if (cpu_memory_rw_debug(env, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
1625 cpu_memory_rw_debug(env, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
1626 return -EINVAL;
1628 return 0;
1631 static struct {
1632 target_ulong addr;
1633 int len;
1634 int type;
1635 } hw_breakpoint[4];
1637 static int nb_hw_breakpoint;
1639 static int find_hw_breakpoint(target_ulong addr, int len, int type)
1641 int n;
1643 for (n = 0; n < nb_hw_breakpoint; n++) {
1644 if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
1645 (hw_breakpoint[n].len == len || len == -1)) {
1646 return n;
1649 return -1;
1652 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
1653 target_ulong len, int type)
1655 switch (type) {
1656 case GDB_BREAKPOINT_HW:
1657 len = 1;
1658 break;
1659 case GDB_WATCHPOINT_WRITE:
1660 case GDB_WATCHPOINT_ACCESS:
1661 switch (len) {
1662 case 1:
1663 break;
1664 case 2:
1665 case 4:
1666 case 8:
1667 if (addr & (len - 1)) {
1668 return -EINVAL;
1670 break;
1671 default:
1672 return -EINVAL;
1674 break;
1675 default:
1676 return -ENOSYS;
1679 if (nb_hw_breakpoint == 4) {
1680 return -ENOBUFS;
1682 if (find_hw_breakpoint(addr, len, type) >= 0) {
1683 return -EEXIST;
1685 hw_breakpoint[nb_hw_breakpoint].addr = addr;
1686 hw_breakpoint[nb_hw_breakpoint].len = len;
1687 hw_breakpoint[nb_hw_breakpoint].type = type;
1688 nb_hw_breakpoint++;
1690 return 0;
1693 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
1694 target_ulong len, int type)
1696 int n;
1698 n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
1699 if (n < 0) {
1700 return -ENOENT;
1702 nb_hw_breakpoint--;
1703 hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
1705 return 0;
1708 void kvm_arch_remove_all_hw_breakpoints(void)
1710 nb_hw_breakpoint = 0;
1713 static CPUWatchpoint hw_watchpoint;
1715 static int kvm_handle_debug(struct kvm_debug_exit_arch *arch_info)
1717 int ret = 0;
1718 int n;
1720 if (arch_info->exception == 1) {
1721 if (arch_info->dr6 & (1 << 14)) {
1722 if (cpu_single_env->singlestep_enabled) {
1723 ret = EXCP_DEBUG;
1725 } else {
1726 for (n = 0; n < 4; n++) {
1727 if (arch_info->dr6 & (1 << n)) {
1728 switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
1729 case 0x0:
1730 ret = EXCP_DEBUG;
1731 break;
1732 case 0x1:
1733 ret = EXCP_DEBUG;
1734 cpu_single_env->watchpoint_hit = &hw_watchpoint;
1735 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
1736 hw_watchpoint.flags = BP_MEM_WRITE;
1737 break;
1738 case 0x3:
1739 ret = EXCP_DEBUG;
1740 cpu_single_env->watchpoint_hit = &hw_watchpoint;
1741 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
1742 hw_watchpoint.flags = BP_MEM_ACCESS;
1743 break;
1748 } else if (kvm_find_sw_breakpoint(cpu_single_env, arch_info->pc)) {
1749 ret = EXCP_DEBUG;
1751 if (ret == 0) {
1752 cpu_synchronize_state(cpu_single_env);
1753 assert(cpu_single_env->exception_injected == -1);
1755 /* pass to guest */
1756 cpu_single_env->exception_injected = arch_info->exception;
1757 cpu_single_env->has_error_code = 0;
1760 return ret;
1763 void kvm_arch_update_guest_debug(CPUState *env, struct kvm_guest_debug *dbg)
1765 const uint8_t type_code[] = {
1766 [GDB_BREAKPOINT_HW] = 0x0,
1767 [GDB_WATCHPOINT_WRITE] = 0x1,
1768 [GDB_WATCHPOINT_ACCESS] = 0x3
1770 const uint8_t len_code[] = {
1771 [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
1773 int n;
1775 if (kvm_sw_breakpoints_active(env)) {
1776 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
1778 if (nb_hw_breakpoint > 0) {
1779 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
1780 dbg->arch.debugreg[7] = 0x0600;
1781 for (n = 0; n < nb_hw_breakpoint; n++) {
1782 dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
1783 dbg->arch.debugreg[7] |= (2 << (n * 2)) |
1784 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
1785 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
1790 static bool host_supports_vmx(void)
1792 uint32_t ecx, unused;
1794 host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
1795 return ecx & CPUID_EXT_VMX;
1798 #define VMX_INVALID_GUEST_STATE 0x80000021
1800 int kvm_arch_handle_exit(CPUState *env, struct kvm_run *run)
1802 uint64_t code;
1803 int ret;
1805 switch (run->exit_reason) {
1806 case KVM_EXIT_HLT:
1807 DPRINTF("handle_hlt\n");
1808 ret = kvm_handle_halt(env);
1809 break;
1810 case KVM_EXIT_SET_TPR:
1811 ret = 0;
1812 break;
1813 case KVM_EXIT_FAIL_ENTRY:
1814 code = run->fail_entry.hardware_entry_failure_reason;
1815 fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
1816 code);
1817 if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
1818 fprintf(stderr,
1819 "\nIf you're runnning a guest on an Intel machine without "
1820 "unrestricted mode\n"
1821 "support, the failure can be most likely due to the guest "
1822 "entering an invalid\n"
1823 "state for Intel VT. For example, the guest maybe running "
1824 "in big real mode\n"
1825 "which is not supported on less recent Intel processors."
1826 "\n\n");
1828 ret = -1;
1829 break;
1830 case KVM_EXIT_EXCEPTION:
1831 fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
1832 run->ex.exception, run->ex.error_code);
1833 ret = -1;
1834 break;
1835 case KVM_EXIT_DEBUG:
1836 DPRINTF("kvm_exit_debug\n");
1837 ret = kvm_handle_debug(&run->debug.arch);
1838 break;
1839 default:
1840 fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
1841 ret = -1;
1842 break;
1845 return ret;
1848 bool kvm_arch_stop_on_emulation_error(CPUState *env)
1850 return !(env->cr[0] & CR0_PE_MASK) ||
1851 ((env->segs[R_CS].selector & 3) != 3);