Merge remote-tracking branch 'qemu-kvm-tmp/memory/batch' into staging
[qemu.git] / target-i386 / kvm.c
blob90a6ffba0204122e538a172d06b79eeec56d2325
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_tsc_deadline;
63 static bool has_msr_async_pf_en;
64 static int lm_capable_kernel;
66 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
68 struct kvm_cpuid2 *cpuid;
69 int r, size;
71 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
72 cpuid = (struct kvm_cpuid2 *)g_malloc0(size);
73 cpuid->nent = max;
74 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
75 if (r == 0 && cpuid->nent >= max) {
76 r = -E2BIG;
78 if (r < 0) {
79 if (r == -E2BIG) {
80 g_free(cpuid);
81 return NULL;
82 } else {
83 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
84 strerror(-r));
85 exit(1);
88 return cpuid;
91 struct kvm_para_features {
92 int cap;
93 int feature;
94 } para_features[] = {
95 { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
96 { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
97 { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
98 { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
99 { -1, -1 }
102 static int get_para_features(KVMState *s)
104 int i, features = 0;
106 for (i = 0; i < ARRAY_SIZE(para_features) - 1; i++) {
107 if (kvm_check_extension(s, para_features[i].cap)) {
108 features |= (1 << para_features[i].feature);
112 return features;
116 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
117 uint32_t index, int reg)
119 struct kvm_cpuid2 *cpuid;
120 int i, max;
121 uint32_t ret = 0;
122 uint32_t cpuid_1_edx;
123 int has_kvm_features = 0;
125 max = 1;
126 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
127 max *= 2;
130 for (i = 0; i < cpuid->nent; ++i) {
131 if (cpuid->entries[i].function == function &&
132 cpuid->entries[i].index == index) {
133 if (cpuid->entries[i].function == KVM_CPUID_FEATURES) {
134 has_kvm_features = 1;
136 switch (reg) {
137 case R_EAX:
138 ret = cpuid->entries[i].eax;
139 break;
140 case R_EBX:
141 ret = cpuid->entries[i].ebx;
142 break;
143 case R_ECX:
144 ret = cpuid->entries[i].ecx;
145 break;
146 case R_EDX:
147 ret = cpuid->entries[i].edx;
148 switch (function) {
149 case 1:
150 /* KVM before 2.6.30 misreports the following features */
151 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
152 break;
153 case 0x80000001:
154 /* On Intel, kvm returns cpuid according to the Intel spec,
155 * so add missing bits according to the AMD spec:
157 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
158 ret |= cpuid_1_edx & 0x183f7ff;
159 break;
161 break;
166 g_free(cpuid);
168 /* fallback for older kernels */
169 if (!has_kvm_features && (function == KVM_CPUID_FEATURES)) {
170 ret = get_para_features(s);
173 return ret;
176 typedef struct HWPoisonPage {
177 ram_addr_t ram_addr;
178 QLIST_ENTRY(HWPoisonPage) list;
179 } HWPoisonPage;
181 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
182 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
184 static void kvm_unpoison_all(void *param)
186 HWPoisonPage *page, *next_page;
188 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
189 QLIST_REMOVE(page, list);
190 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
191 g_free(page);
195 static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
197 HWPoisonPage *page;
199 QLIST_FOREACH(page, &hwpoison_page_list, list) {
200 if (page->ram_addr == ram_addr) {
201 return;
204 page = g_malloc(sizeof(HWPoisonPage));
205 page->ram_addr = ram_addr;
206 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
209 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
210 int *max_banks)
212 int r;
214 r = kvm_check_extension(s, KVM_CAP_MCE);
215 if (r > 0) {
216 *max_banks = r;
217 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
219 return -ENOSYS;
222 static void kvm_mce_inject(CPUState *env, target_phys_addr_t paddr, int code)
224 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
225 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
226 uint64_t mcg_status = MCG_STATUS_MCIP;
228 if (code == BUS_MCEERR_AR) {
229 status |= MCI_STATUS_AR | 0x134;
230 mcg_status |= MCG_STATUS_EIPV;
231 } else {
232 status |= 0xc0;
233 mcg_status |= MCG_STATUS_RIPV;
235 cpu_x86_inject_mce(NULL, env, 9, status, mcg_status, paddr,
236 (MCM_ADDR_PHYS << 6) | 0xc,
237 cpu_x86_support_mca_broadcast(env) ?
238 MCE_INJECT_BROADCAST : 0);
241 static void hardware_memory_error(void)
243 fprintf(stderr, "Hardware memory error!\n");
244 exit(1);
247 int kvm_arch_on_sigbus_vcpu(CPUState *env, int code, void *addr)
249 ram_addr_t ram_addr;
250 target_phys_addr_t paddr;
252 if ((env->mcg_cap & MCG_SER_P) && addr
253 && (code == BUS_MCEERR_AR || code == BUS_MCEERR_AO)) {
254 if (qemu_ram_addr_from_host(addr, &ram_addr) ||
255 !kvm_physical_memory_addr_from_ram(env->kvm_state, ram_addr,
256 &paddr)) {
257 fprintf(stderr, "Hardware memory error for memory used by "
258 "QEMU itself instead of guest system!\n");
259 /* Hope we are lucky for AO MCE */
260 if (code == BUS_MCEERR_AO) {
261 return 0;
262 } else {
263 hardware_memory_error();
266 kvm_hwpoison_page_add(ram_addr);
267 kvm_mce_inject(env, paddr, code);
268 } else {
269 if (code == BUS_MCEERR_AO) {
270 return 0;
271 } else if (code == BUS_MCEERR_AR) {
272 hardware_memory_error();
273 } else {
274 return 1;
277 return 0;
280 int kvm_arch_on_sigbus(int code, void *addr)
282 if ((first_cpu->mcg_cap & MCG_SER_P) && addr && code == BUS_MCEERR_AO) {
283 ram_addr_t ram_addr;
284 target_phys_addr_t paddr;
286 /* Hope we are lucky for AO MCE */
287 if (qemu_ram_addr_from_host(addr, &ram_addr) ||
288 !kvm_physical_memory_addr_from_ram(first_cpu->kvm_state, ram_addr,
289 &paddr)) {
290 fprintf(stderr, "Hardware memory error for memory used by "
291 "QEMU itself instead of guest system!: %p\n", addr);
292 return 0;
294 kvm_hwpoison_page_add(ram_addr);
295 kvm_mce_inject(first_cpu, paddr, code);
296 } else {
297 if (code == BUS_MCEERR_AO) {
298 return 0;
299 } else if (code == BUS_MCEERR_AR) {
300 hardware_memory_error();
301 } else {
302 return 1;
305 return 0;
308 static int kvm_inject_mce_oldstyle(CPUState *env)
310 if (!kvm_has_vcpu_events() && env->exception_injected == EXCP12_MCHK) {
311 unsigned int bank, bank_num = env->mcg_cap & 0xff;
312 struct kvm_x86_mce mce;
314 env->exception_injected = -1;
317 * There must be at least one bank in use if an MCE is pending.
318 * Find it and use its values for the event injection.
320 for (bank = 0; bank < bank_num; bank++) {
321 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
322 break;
325 assert(bank < bank_num);
327 mce.bank = bank;
328 mce.status = env->mce_banks[bank * 4 + 1];
329 mce.mcg_status = env->mcg_status;
330 mce.addr = env->mce_banks[bank * 4 + 2];
331 mce.misc = env->mce_banks[bank * 4 + 3];
333 return kvm_vcpu_ioctl(env, KVM_X86_SET_MCE, &mce);
335 return 0;
338 static void cpu_update_state(void *opaque, int running, RunState state)
340 CPUState *env = opaque;
342 if (running) {
343 env->tsc_valid = false;
347 int kvm_arch_init_vcpu(CPUState *env)
349 struct {
350 struct kvm_cpuid2 cpuid;
351 struct kvm_cpuid_entry2 entries[100];
352 } QEMU_PACKED cpuid_data;
353 KVMState *s = env->kvm_state;
354 uint32_t limit, i, j, cpuid_i;
355 uint32_t unused;
356 struct kvm_cpuid_entry2 *c;
357 uint32_t signature[3];
358 int r;
360 env->cpuid_features &= kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
362 i = env->cpuid_ext_features & CPUID_EXT_HYPERVISOR;
363 env->cpuid_ext_features &= kvm_arch_get_supported_cpuid(s, 1, 0, R_ECX);
364 env->cpuid_ext_features |= i;
366 env->cpuid_ext2_features &= kvm_arch_get_supported_cpuid(s, 0x80000001,
367 0, R_EDX);
368 env->cpuid_ext3_features &= kvm_arch_get_supported_cpuid(s, 0x80000001,
369 0, R_ECX);
370 env->cpuid_svm_features &= kvm_arch_get_supported_cpuid(s, 0x8000000A,
371 0, R_EDX);
373 cpuid_i = 0;
375 /* Paravirtualization CPUIDs */
376 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
377 c = &cpuid_data.entries[cpuid_i++];
378 memset(c, 0, sizeof(*c));
379 c->function = KVM_CPUID_SIGNATURE;
380 c->eax = 0;
381 c->ebx = signature[0];
382 c->ecx = signature[1];
383 c->edx = signature[2];
385 c = &cpuid_data.entries[cpuid_i++];
386 memset(c, 0, sizeof(*c));
387 c->function = KVM_CPUID_FEATURES;
388 c->eax = env->cpuid_kvm_features &
389 kvm_arch_get_supported_cpuid(s, KVM_CPUID_FEATURES, 0, R_EAX);
391 has_msr_async_pf_en = c->eax & (1 << KVM_FEATURE_ASYNC_PF);
393 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
395 for (i = 0; i <= limit; i++) {
396 c = &cpuid_data.entries[cpuid_i++];
398 switch (i) {
399 case 2: {
400 /* Keep reading function 2 till all the input is received */
401 int times;
403 c->function = i;
404 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
405 KVM_CPUID_FLAG_STATE_READ_NEXT;
406 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
407 times = c->eax & 0xff;
409 for (j = 1; j < times; ++j) {
410 c = &cpuid_data.entries[cpuid_i++];
411 c->function = i;
412 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
413 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
415 break;
417 case 4:
418 case 0xb:
419 case 0xd:
420 for (j = 0; ; j++) {
421 if (i == 0xd && j == 64) {
422 break;
424 c->function = i;
425 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
426 c->index = j;
427 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
429 if (i == 4 && c->eax == 0) {
430 break;
432 if (i == 0xb && !(c->ecx & 0xff00)) {
433 break;
435 if (i == 0xd && c->eax == 0) {
436 continue;
438 c = &cpuid_data.entries[cpuid_i++];
440 break;
441 default:
442 c->function = i;
443 c->flags = 0;
444 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
445 break;
448 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
450 for (i = 0x80000000; i <= limit; i++) {
451 c = &cpuid_data.entries[cpuid_i++];
453 c->function = i;
454 c->flags = 0;
455 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
458 /* Call Centaur's CPUID instructions they are supported. */
459 if (env->cpuid_xlevel2 > 0) {
460 env->cpuid_ext4_features &=
461 kvm_arch_get_supported_cpuid(s, 0xC0000001, 0, R_EDX);
462 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
464 for (i = 0xC0000000; i <= limit; i++) {
465 c = &cpuid_data.entries[cpuid_i++];
467 c->function = i;
468 c->flags = 0;
469 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
473 cpuid_data.cpuid.nent = cpuid_i;
475 if (((env->cpuid_version >> 8)&0xF) >= 6
476 && (env->cpuid_features&(CPUID_MCE|CPUID_MCA)) == (CPUID_MCE|CPUID_MCA)
477 && kvm_check_extension(env->kvm_state, KVM_CAP_MCE) > 0) {
478 uint64_t mcg_cap;
479 int banks;
480 int ret;
482 ret = kvm_get_mce_cap_supported(env->kvm_state, &mcg_cap, &banks);
483 if (ret < 0) {
484 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
485 return ret;
488 if (banks > MCE_BANKS_DEF) {
489 banks = MCE_BANKS_DEF;
491 mcg_cap &= MCE_CAP_DEF;
492 mcg_cap |= banks;
493 ret = kvm_vcpu_ioctl(env, KVM_X86_SETUP_MCE, &mcg_cap);
494 if (ret < 0) {
495 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
496 return ret;
499 env->mcg_cap = mcg_cap;
502 qemu_add_vm_change_state_handler(cpu_update_state, env);
504 r = kvm_vcpu_ioctl(env, KVM_SET_CPUID2, &cpuid_data);
505 if (r) {
506 return r;
509 r = kvm_check_extension(env->kvm_state, KVM_CAP_TSC_CONTROL);
510 if (r && env->tsc_khz) {
511 r = kvm_vcpu_ioctl(env, KVM_SET_TSC_KHZ, env->tsc_khz);
512 if (r < 0) {
513 fprintf(stderr, "KVM_SET_TSC_KHZ failed\n");
514 return r;
518 return 0;
521 void kvm_arch_reset_vcpu(CPUState *env)
523 env->exception_injected = -1;
524 env->interrupt_injected = -1;
525 env->xcr0 = 1;
526 if (kvm_irqchip_in_kernel()) {
527 env->mp_state = cpu_is_bsp(env) ? KVM_MP_STATE_RUNNABLE :
528 KVM_MP_STATE_UNINITIALIZED;
529 } else {
530 env->mp_state = KVM_MP_STATE_RUNNABLE;
534 static int kvm_get_supported_msrs(KVMState *s)
536 static int kvm_supported_msrs;
537 int ret = 0;
539 /* first time */
540 if (kvm_supported_msrs == 0) {
541 struct kvm_msr_list msr_list, *kvm_msr_list;
543 kvm_supported_msrs = -1;
545 /* Obtain MSR list from KVM. These are the MSRs that we must
546 * save/restore */
547 msr_list.nmsrs = 0;
548 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
549 if (ret < 0 && ret != -E2BIG) {
550 return ret;
552 /* Old kernel modules had a bug and could write beyond the provided
553 memory. Allocate at least a safe amount of 1K. */
554 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
555 msr_list.nmsrs *
556 sizeof(msr_list.indices[0])));
558 kvm_msr_list->nmsrs = msr_list.nmsrs;
559 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
560 if (ret >= 0) {
561 int i;
563 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
564 if (kvm_msr_list->indices[i] == MSR_STAR) {
565 has_msr_star = true;
566 continue;
568 if (kvm_msr_list->indices[i] == MSR_VM_HSAVE_PA) {
569 has_msr_hsave_pa = true;
570 continue;
572 if (kvm_msr_list->indices[i] == MSR_IA32_TSCDEADLINE) {
573 has_msr_tsc_deadline = true;
574 continue;
579 g_free(kvm_msr_list);
582 return ret;
585 int kvm_arch_init(KVMState *s)
587 uint64_t identity_base = 0xfffbc000;
588 int ret;
589 struct utsname utsname;
591 ret = kvm_get_supported_msrs(s);
592 if (ret < 0) {
593 return ret;
596 uname(&utsname);
597 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
600 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
601 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
602 * Since these must be part of guest physical memory, we need to allocate
603 * them, both by setting their start addresses in the kernel and by
604 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
606 * Older KVM versions may not support setting the identity map base. In
607 * that case we need to stick with the default, i.e. a 256K maximum BIOS
608 * size.
610 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
611 /* Allows up to 16M BIOSes. */
612 identity_base = 0xfeffc000;
614 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
615 if (ret < 0) {
616 return ret;
620 /* Set TSS base one page after EPT identity map. */
621 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
622 if (ret < 0) {
623 return ret;
626 /* Tell fw_cfg to notify the BIOS to reserve the range. */
627 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
628 if (ret < 0) {
629 fprintf(stderr, "e820_add_entry() table is full\n");
630 return ret;
632 qemu_register_reset(kvm_unpoison_all, NULL);
634 return 0;
637 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
639 lhs->selector = rhs->selector;
640 lhs->base = rhs->base;
641 lhs->limit = rhs->limit;
642 lhs->type = 3;
643 lhs->present = 1;
644 lhs->dpl = 3;
645 lhs->db = 0;
646 lhs->s = 1;
647 lhs->l = 0;
648 lhs->g = 0;
649 lhs->avl = 0;
650 lhs->unusable = 0;
653 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
655 unsigned flags = rhs->flags;
656 lhs->selector = rhs->selector;
657 lhs->base = rhs->base;
658 lhs->limit = rhs->limit;
659 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
660 lhs->present = (flags & DESC_P_MASK) != 0;
661 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
662 lhs->db = (flags >> DESC_B_SHIFT) & 1;
663 lhs->s = (flags & DESC_S_MASK) != 0;
664 lhs->l = (flags >> DESC_L_SHIFT) & 1;
665 lhs->g = (flags & DESC_G_MASK) != 0;
666 lhs->avl = (flags & DESC_AVL_MASK) != 0;
667 lhs->unusable = 0;
670 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
672 lhs->selector = rhs->selector;
673 lhs->base = rhs->base;
674 lhs->limit = rhs->limit;
675 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
676 (rhs->present * DESC_P_MASK) |
677 (rhs->dpl << DESC_DPL_SHIFT) |
678 (rhs->db << DESC_B_SHIFT) |
679 (rhs->s * DESC_S_MASK) |
680 (rhs->l << DESC_L_SHIFT) |
681 (rhs->g * DESC_G_MASK) |
682 (rhs->avl * DESC_AVL_MASK);
685 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
687 if (set) {
688 *kvm_reg = *qemu_reg;
689 } else {
690 *qemu_reg = *kvm_reg;
694 static int kvm_getput_regs(CPUState *env, int set)
696 struct kvm_regs regs;
697 int ret = 0;
699 if (!set) {
700 ret = kvm_vcpu_ioctl(env, KVM_GET_REGS, &regs);
701 if (ret < 0) {
702 return ret;
706 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
707 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
708 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
709 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
710 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
711 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
712 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
713 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
714 #ifdef TARGET_X86_64
715 kvm_getput_reg(&regs.r8, &env->regs[8], set);
716 kvm_getput_reg(&regs.r9, &env->regs[9], set);
717 kvm_getput_reg(&regs.r10, &env->regs[10], set);
718 kvm_getput_reg(&regs.r11, &env->regs[11], set);
719 kvm_getput_reg(&regs.r12, &env->regs[12], set);
720 kvm_getput_reg(&regs.r13, &env->regs[13], set);
721 kvm_getput_reg(&regs.r14, &env->regs[14], set);
722 kvm_getput_reg(&regs.r15, &env->regs[15], set);
723 #endif
725 kvm_getput_reg(&regs.rflags, &env->eflags, set);
726 kvm_getput_reg(&regs.rip, &env->eip, set);
728 if (set) {
729 ret = kvm_vcpu_ioctl(env, KVM_SET_REGS, &regs);
732 return ret;
735 static int kvm_put_fpu(CPUState *env)
737 struct kvm_fpu fpu;
738 int i;
740 memset(&fpu, 0, sizeof fpu);
741 fpu.fsw = env->fpus & ~(7 << 11);
742 fpu.fsw |= (env->fpstt & 7) << 11;
743 fpu.fcw = env->fpuc;
744 fpu.last_opcode = env->fpop;
745 fpu.last_ip = env->fpip;
746 fpu.last_dp = env->fpdp;
747 for (i = 0; i < 8; ++i) {
748 fpu.ftwx |= (!env->fptags[i]) << i;
750 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
751 memcpy(fpu.xmm, env->xmm_regs, sizeof env->xmm_regs);
752 fpu.mxcsr = env->mxcsr;
754 return kvm_vcpu_ioctl(env, KVM_SET_FPU, &fpu);
757 #define XSAVE_CWD_RIP 2
758 #define XSAVE_CWD_RDP 4
759 #define XSAVE_MXCSR 6
760 #define XSAVE_ST_SPACE 8
761 #define XSAVE_XMM_SPACE 40
762 #define XSAVE_XSTATE_BV 128
763 #define XSAVE_YMMH_SPACE 144
765 static int kvm_put_xsave(CPUState *env)
767 int i, r;
768 struct kvm_xsave* xsave;
769 uint16_t cwd, swd, twd;
771 if (!kvm_has_xsave()) {
772 return kvm_put_fpu(env);
775 xsave = qemu_memalign(4096, sizeof(struct kvm_xsave));
776 memset(xsave, 0, sizeof(struct kvm_xsave));
777 twd = 0;
778 swd = env->fpus & ~(7 << 11);
779 swd |= (env->fpstt & 7) << 11;
780 cwd = env->fpuc;
781 for (i = 0; i < 8; ++i) {
782 twd |= (!env->fptags[i]) << i;
784 xsave->region[0] = (uint32_t)(swd << 16) + cwd;
785 xsave->region[1] = (uint32_t)(env->fpop << 16) + twd;
786 memcpy(&xsave->region[XSAVE_CWD_RIP], &env->fpip, sizeof(env->fpip));
787 memcpy(&xsave->region[XSAVE_CWD_RDP], &env->fpdp, sizeof(env->fpdp));
788 memcpy(&xsave->region[XSAVE_ST_SPACE], env->fpregs,
789 sizeof env->fpregs);
790 memcpy(&xsave->region[XSAVE_XMM_SPACE], env->xmm_regs,
791 sizeof env->xmm_regs);
792 xsave->region[XSAVE_MXCSR] = env->mxcsr;
793 *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV] = env->xstate_bv;
794 memcpy(&xsave->region[XSAVE_YMMH_SPACE], env->ymmh_regs,
795 sizeof env->ymmh_regs);
796 r = kvm_vcpu_ioctl(env, KVM_SET_XSAVE, xsave);
797 g_free(xsave);
798 return r;
801 static int kvm_put_xcrs(CPUState *env)
803 struct kvm_xcrs xcrs;
805 if (!kvm_has_xcrs()) {
806 return 0;
809 xcrs.nr_xcrs = 1;
810 xcrs.flags = 0;
811 xcrs.xcrs[0].xcr = 0;
812 xcrs.xcrs[0].value = env->xcr0;
813 return kvm_vcpu_ioctl(env, KVM_SET_XCRS, &xcrs);
816 static int kvm_put_sregs(CPUState *env)
818 struct kvm_sregs sregs;
820 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
821 if (env->interrupt_injected >= 0) {
822 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
823 (uint64_t)1 << (env->interrupt_injected % 64);
826 if ((env->eflags & VM_MASK)) {
827 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
828 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
829 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
830 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
831 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
832 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
833 } else {
834 set_seg(&sregs.cs, &env->segs[R_CS]);
835 set_seg(&sregs.ds, &env->segs[R_DS]);
836 set_seg(&sregs.es, &env->segs[R_ES]);
837 set_seg(&sregs.fs, &env->segs[R_FS]);
838 set_seg(&sregs.gs, &env->segs[R_GS]);
839 set_seg(&sregs.ss, &env->segs[R_SS]);
842 set_seg(&sregs.tr, &env->tr);
843 set_seg(&sregs.ldt, &env->ldt);
845 sregs.idt.limit = env->idt.limit;
846 sregs.idt.base = env->idt.base;
847 sregs.gdt.limit = env->gdt.limit;
848 sregs.gdt.base = env->gdt.base;
850 sregs.cr0 = env->cr[0];
851 sregs.cr2 = env->cr[2];
852 sregs.cr3 = env->cr[3];
853 sregs.cr4 = env->cr[4];
855 sregs.cr8 = cpu_get_apic_tpr(env->apic_state);
856 sregs.apic_base = cpu_get_apic_base(env->apic_state);
858 sregs.efer = env->efer;
860 return kvm_vcpu_ioctl(env, KVM_SET_SREGS, &sregs);
863 static void kvm_msr_entry_set(struct kvm_msr_entry *entry,
864 uint32_t index, uint64_t value)
866 entry->index = index;
867 entry->data = value;
870 static int kvm_put_msrs(CPUState *env, int level)
872 struct {
873 struct kvm_msrs info;
874 struct kvm_msr_entry entries[100];
875 } msr_data;
876 struct kvm_msr_entry *msrs = msr_data.entries;
877 int n = 0;
879 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_CS, env->sysenter_cs);
880 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
881 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
882 kvm_msr_entry_set(&msrs[n++], MSR_PAT, env->pat);
883 if (has_msr_star) {
884 kvm_msr_entry_set(&msrs[n++], MSR_STAR, env->star);
886 if (has_msr_hsave_pa) {
887 kvm_msr_entry_set(&msrs[n++], MSR_VM_HSAVE_PA, env->vm_hsave);
889 if (has_msr_tsc_deadline) {
890 kvm_msr_entry_set(&msrs[n++], MSR_IA32_TSCDEADLINE, env->tsc_deadline);
892 #ifdef TARGET_X86_64
893 if (lm_capable_kernel) {
894 kvm_msr_entry_set(&msrs[n++], MSR_CSTAR, env->cstar);
895 kvm_msr_entry_set(&msrs[n++], MSR_KERNELGSBASE, env->kernelgsbase);
896 kvm_msr_entry_set(&msrs[n++], MSR_FMASK, env->fmask);
897 kvm_msr_entry_set(&msrs[n++], MSR_LSTAR, env->lstar);
899 #endif
900 if (level == KVM_PUT_FULL_STATE) {
902 * KVM is yet unable to synchronize TSC values of multiple VCPUs on
903 * writeback. Until this is fixed, we only write the offset to SMP
904 * guests after migration, desynchronizing the VCPUs, but avoiding
905 * huge jump-backs that would occur without any writeback at all.
907 if (smp_cpus == 1 || env->tsc != 0) {
908 kvm_msr_entry_set(&msrs[n++], MSR_IA32_TSC, env->tsc);
912 * The following paravirtual MSRs have side effects on the guest or are
913 * too heavy for normal writeback. Limit them to reset or full state
914 * updates.
916 if (level >= KVM_PUT_RESET_STATE) {
917 kvm_msr_entry_set(&msrs[n++], MSR_KVM_SYSTEM_TIME,
918 env->system_time_msr);
919 kvm_msr_entry_set(&msrs[n++], MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
920 if (has_msr_async_pf_en) {
921 kvm_msr_entry_set(&msrs[n++], MSR_KVM_ASYNC_PF_EN,
922 env->async_pf_en_msr);
925 if (env->mcg_cap) {
926 int i;
928 kvm_msr_entry_set(&msrs[n++], MSR_MCG_STATUS, env->mcg_status);
929 kvm_msr_entry_set(&msrs[n++], MSR_MCG_CTL, env->mcg_ctl);
930 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
931 kvm_msr_entry_set(&msrs[n++], MSR_MC0_CTL + i, env->mce_banks[i]);
935 msr_data.info.nmsrs = n;
937 return kvm_vcpu_ioctl(env, KVM_SET_MSRS, &msr_data);
942 static int kvm_get_fpu(CPUState *env)
944 struct kvm_fpu fpu;
945 int i, ret;
947 ret = kvm_vcpu_ioctl(env, KVM_GET_FPU, &fpu);
948 if (ret < 0) {
949 return ret;
952 env->fpstt = (fpu.fsw >> 11) & 7;
953 env->fpus = fpu.fsw;
954 env->fpuc = fpu.fcw;
955 env->fpop = fpu.last_opcode;
956 env->fpip = fpu.last_ip;
957 env->fpdp = fpu.last_dp;
958 for (i = 0; i < 8; ++i) {
959 env->fptags[i] = !((fpu.ftwx >> i) & 1);
961 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
962 memcpy(env->xmm_regs, fpu.xmm, sizeof env->xmm_regs);
963 env->mxcsr = fpu.mxcsr;
965 return 0;
968 static int kvm_get_xsave(CPUState *env)
970 struct kvm_xsave* xsave;
971 int ret, i;
972 uint16_t cwd, swd, twd;
974 if (!kvm_has_xsave()) {
975 return kvm_get_fpu(env);
978 xsave = qemu_memalign(4096, sizeof(struct kvm_xsave));
979 ret = kvm_vcpu_ioctl(env, KVM_GET_XSAVE, xsave);
980 if (ret < 0) {
981 g_free(xsave);
982 return ret;
985 cwd = (uint16_t)xsave->region[0];
986 swd = (uint16_t)(xsave->region[0] >> 16);
987 twd = (uint16_t)xsave->region[1];
988 env->fpop = (uint16_t)(xsave->region[1] >> 16);
989 env->fpstt = (swd >> 11) & 7;
990 env->fpus = swd;
991 env->fpuc = cwd;
992 for (i = 0; i < 8; ++i) {
993 env->fptags[i] = !((twd >> i) & 1);
995 memcpy(&env->fpip, &xsave->region[XSAVE_CWD_RIP], sizeof(env->fpip));
996 memcpy(&env->fpdp, &xsave->region[XSAVE_CWD_RDP], sizeof(env->fpdp));
997 env->mxcsr = xsave->region[XSAVE_MXCSR];
998 memcpy(env->fpregs, &xsave->region[XSAVE_ST_SPACE],
999 sizeof env->fpregs);
1000 memcpy(env->xmm_regs, &xsave->region[XSAVE_XMM_SPACE],
1001 sizeof env->xmm_regs);
1002 env->xstate_bv = *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV];
1003 memcpy(env->ymmh_regs, &xsave->region[XSAVE_YMMH_SPACE],
1004 sizeof env->ymmh_regs);
1005 g_free(xsave);
1006 return 0;
1009 static int kvm_get_xcrs(CPUState *env)
1011 int i, ret;
1012 struct kvm_xcrs xcrs;
1014 if (!kvm_has_xcrs()) {
1015 return 0;
1018 ret = kvm_vcpu_ioctl(env, KVM_GET_XCRS, &xcrs);
1019 if (ret < 0) {
1020 return ret;
1023 for (i = 0; i < xcrs.nr_xcrs; i++) {
1024 /* Only support xcr0 now */
1025 if (xcrs.xcrs[0].xcr == 0) {
1026 env->xcr0 = xcrs.xcrs[0].value;
1027 break;
1030 return 0;
1033 static int kvm_get_sregs(CPUState *env)
1035 struct kvm_sregs sregs;
1036 uint32_t hflags;
1037 int bit, i, ret;
1039 ret = kvm_vcpu_ioctl(env, KVM_GET_SREGS, &sregs);
1040 if (ret < 0) {
1041 return ret;
1044 /* There can only be one pending IRQ set in the bitmap at a time, so try
1045 to find it and save its number instead (-1 for none). */
1046 env->interrupt_injected = -1;
1047 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
1048 if (sregs.interrupt_bitmap[i]) {
1049 bit = ctz64(sregs.interrupt_bitmap[i]);
1050 env->interrupt_injected = i * 64 + bit;
1051 break;
1055 get_seg(&env->segs[R_CS], &sregs.cs);
1056 get_seg(&env->segs[R_DS], &sregs.ds);
1057 get_seg(&env->segs[R_ES], &sregs.es);
1058 get_seg(&env->segs[R_FS], &sregs.fs);
1059 get_seg(&env->segs[R_GS], &sregs.gs);
1060 get_seg(&env->segs[R_SS], &sregs.ss);
1062 get_seg(&env->tr, &sregs.tr);
1063 get_seg(&env->ldt, &sregs.ldt);
1065 env->idt.limit = sregs.idt.limit;
1066 env->idt.base = sregs.idt.base;
1067 env->gdt.limit = sregs.gdt.limit;
1068 env->gdt.base = sregs.gdt.base;
1070 env->cr[0] = sregs.cr0;
1071 env->cr[2] = sregs.cr2;
1072 env->cr[3] = sregs.cr3;
1073 env->cr[4] = sregs.cr4;
1075 cpu_set_apic_base(env->apic_state, sregs.apic_base);
1077 env->efer = sregs.efer;
1078 //cpu_set_apic_tpr(env->apic_state, sregs.cr8);
1080 #define HFLAG_COPY_MASK \
1081 ~( HF_CPL_MASK | HF_PE_MASK | HF_MP_MASK | HF_EM_MASK | \
1082 HF_TS_MASK | HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK | \
1083 HF_OSFXSR_MASK | HF_LMA_MASK | HF_CS32_MASK | \
1084 HF_SS32_MASK | HF_CS64_MASK | HF_ADDSEG_MASK)
1086 hflags = (env->segs[R_CS].flags >> DESC_DPL_SHIFT) & HF_CPL_MASK;
1087 hflags |= (env->cr[0] & CR0_PE_MASK) << (HF_PE_SHIFT - CR0_PE_SHIFT);
1088 hflags |= (env->cr[0] << (HF_MP_SHIFT - CR0_MP_SHIFT)) &
1089 (HF_MP_MASK | HF_EM_MASK | HF_TS_MASK);
1090 hflags |= (env->eflags & (HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK));
1091 hflags |= (env->cr[4] & CR4_OSFXSR_MASK) <<
1092 (HF_OSFXSR_SHIFT - CR4_OSFXSR_SHIFT);
1094 if (env->efer & MSR_EFER_LMA) {
1095 hflags |= HF_LMA_MASK;
1098 if ((hflags & HF_LMA_MASK) && (env->segs[R_CS].flags & DESC_L_MASK)) {
1099 hflags |= HF_CS32_MASK | HF_SS32_MASK | HF_CS64_MASK;
1100 } else {
1101 hflags |= (env->segs[R_CS].flags & DESC_B_MASK) >>
1102 (DESC_B_SHIFT - HF_CS32_SHIFT);
1103 hflags |= (env->segs[R_SS].flags & DESC_B_MASK) >>
1104 (DESC_B_SHIFT - HF_SS32_SHIFT);
1105 if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK) ||
1106 !(hflags & HF_CS32_MASK)) {
1107 hflags |= HF_ADDSEG_MASK;
1108 } else {
1109 hflags |= ((env->segs[R_DS].base | env->segs[R_ES].base |
1110 env->segs[R_SS].base) != 0) << HF_ADDSEG_SHIFT;
1113 env->hflags = (env->hflags & HFLAG_COPY_MASK) | hflags;
1115 return 0;
1118 static int kvm_get_msrs(CPUState *env)
1120 struct {
1121 struct kvm_msrs info;
1122 struct kvm_msr_entry entries[100];
1123 } msr_data;
1124 struct kvm_msr_entry *msrs = msr_data.entries;
1125 int ret, i, n;
1127 n = 0;
1128 msrs[n++].index = MSR_IA32_SYSENTER_CS;
1129 msrs[n++].index = MSR_IA32_SYSENTER_ESP;
1130 msrs[n++].index = MSR_IA32_SYSENTER_EIP;
1131 msrs[n++].index = MSR_PAT;
1132 if (has_msr_star) {
1133 msrs[n++].index = MSR_STAR;
1135 if (has_msr_hsave_pa) {
1136 msrs[n++].index = MSR_VM_HSAVE_PA;
1138 if (has_msr_tsc_deadline) {
1139 msrs[n++].index = MSR_IA32_TSCDEADLINE;
1142 if (!env->tsc_valid) {
1143 msrs[n++].index = MSR_IA32_TSC;
1144 env->tsc_valid = !runstate_is_running();
1147 #ifdef TARGET_X86_64
1148 if (lm_capable_kernel) {
1149 msrs[n++].index = MSR_CSTAR;
1150 msrs[n++].index = MSR_KERNELGSBASE;
1151 msrs[n++].index = MSR_FMASK;
1152 msrs[n++].index = MSR_LSTAR;
1154 #endif
1155 msrs[n++].index = MSR_KVM_SYSTEM_TIME;
1156 msrs[n++].index = MSR_KVM_WALL_CLOCK;
1157 if (has_msr_async_pf_en) {
1158 msrs[n++].index = MSR_KVM_ASYNC_PF_EN;
1161 if (env->mcg_cap) {
1162 msrs[n++].index = MSR_MCG_STATUS;
1163 msrs[n++].index = MSR_MCG_CTL;
1164 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1165 msrs[n++].index = MSR_MC0_CTL + i;
1169 msr_data.info.nmsrs = n;
1170 ret = kvm_vcpu_ioctl(env, KVM_GET_MSRS, &msr_data);
1171 if (ret < 0) {
1172 return ret;
1175 for (i = 0; i < ret; i++) {
1176 switch (msrs[i].index) {
1177 case MSR_IA32_SYSENTER_CS:
1178 env->sysenter_cs = msrs[i].data;
1179 break;
1180 case MSR_IA32_SYSENTER_ESP:
1181 env->sysenter_esp = msrs[i].data;
1182 break;
1183 case MSR_IA32_SYSENTER_EIP:
1184 env->sysenter_eip = msrs[i].data;
1185 break;
1186 case MSR_PAT:
1187 env->pat = msrs[i].data;
1188 break;
1189 case MSR_STAR:
1190 env->star = msrs[i].data;
1191 break;
1192 #ifdef TARGET_X86_64
1193 case MSR_CSTAR:
1194 env->cstar = msrs[i].data;
1195 break;
1196 case MSR_KERNELGSBASE:
1197 env->kernelgsbase = msrs[i].data;
1198 break;
1199 case MSR_FMASK:
1200 env->fmask = msrs[i].data;
1201 break;
1202 case MSR_LSTAR:
1203 env->lstar = msrs[i].data;
1204 break;
1205 #endif
1206 case MSR_IA32_TSC:
1207 env->tsc = msrs[i].data;
1208 break;
1209 case MSR_IA32_TSCDEADLINE:
1210 env->tsc_deadline = msrs[i].data;
1211 break;
1212 case MSR_VM_HSAVE_PA:
1213 env->vm_hsave = msrs[i].data;
1214 break;
1215 case MSR_KVM_SYSTEM_TIME:
1216 env->system_time_msr = msrs[i].data;
1217 break;
1218 case MSR_KVM_WALL_CLOCK:
1219 env->wall_clock_msr = msrs[i].data;
1220 break;
1221 case MSR_MCG_STATUS:
1222 env->mcg_status = msrs[i].data;
1223 break;
1224 case MSR_MCG_CTL:
1225 env->mcg_ctl = msrs[i].data;
1226 break;
1227 default:
1228 if (msrs[i].index >= MSR_MC0_CTL &&
1229 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
1230 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
1232 break;
1233 case MSR_KVM_ASYNC_PF_EN:
1234 env->async_pf_en_msr = msrs[i].data;
1235 break;
1239 return 0;
1242 static int kvm_put_mp_state(CPUState *env)
1244 struct kvm_mp_state mp_state = { .mp_state = env->mp_state };
1246 return kvm_vcpu_ioctl(env, KVM_SET_MP_STATE, &mp_state);
1249 static int kvm_get_mp_state(CPUState *env)
1251 struct kvm_mp_state mp_state;
1252 int ret;
1254 ret = kvm_vcpu_ioctl(env, KVM_GET_MP_STATE, &mp_state);
1255 if (ret < 0) {
1256 return ret;
1258 env->mp_state = mp_state.mp_state;
1259 if (kvm_irqchip_in_kernel()) {
1260 env->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
1262 return 0;
1265 static int kvm_put_vcpu_events(CPUState *env, int level)
1267 struct kvm_vcpu_events events;
1269 if (!kvm_has_vcpu_events()) {
1270 return 0;
1273 events.exception.injected = (env->exception_injected >= 0);
1274 events.exception.nr = env->exception_injected;
1275 events.exception.has_error_code = env->has_error_code;
1276 events.exception.error_code = env->error_code;
1278 events.interrupt.injected = (env->interrupt_injected >= 0);
1279 events.interrupt.nr = env->interrupt_injected;
1280 events.interrupt.soft = env->soft_interrupt;
1282 events.nmi.injected = env->nmi_injected;
1283 events.nmi.pending = env->nmi_pending;
1284 events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
1286 events.sipi_vector = env->sipi_vector;
1288 events.flags = 0;
1289 if (level >= KVM_PUT_RESET_STATE) {
1290 events.flags |=
1291 KVM_VCPUEVENT_VALID_NMI_PENDING | KVM_VCPUEVENT_VALID_SIPI_VECTOR;
1294 return kvm_vcpu_ioctl(env, KVM_SET_VCPU_EVENTS, &events);
1297 static int kvm_get_vcpu_events(CPUState *env)
1299 struct kvm_vcpu_events events;
1300 int ret;
1302 if (!kvm_has_vcpu_events()) {
1303 return 0;
1306 ret = kvm_vcpu_ioctl(env, KVM_GET_VCPU_EVENTS, &events);
1307 if (ret < 0) {
1308 return ret;
1310 env->exception_injected =
1311 events.exception.injected ? events.exception.nr : -1;
1312 env->has_error_code = events.exception.has_error_code;
1313 env->error_code = events.exception.error_code;
1315 env->interrupt_injected =
1316 events.interrupt.injected ? events.interrupt.nr : -1;
1317 env->soft_interrupt = events.interrupt.soft;
1319 env->nmi_injected = events.nmi.injected;
1320 env->nmi_pending = events.nmi.pending;
1321 if (events.nmi.masked) {
1322 env->hflags2 |= HF2_NMI_MASK;
1323 } else {
1324 env->hflags2 &= ~HF2_NMI_MASK;
1327 env->sipi_vector = events.sipi_vector;
1329 return 0;
1332 static int kvm_guest_debug_workarounds(CPUState *env)
1334 int ret = 0;
1335 unsigned long reinject_trap = 0;
1337 if (!kvm_has_vcpu_events()) {
1338 if (env->exception_injected == 1) {
1339 reinject_trap = KVM_GUESTDBG_INJECT_DB;
1340 } else if (env->exception_injected == 3) {
1341 reinject_trap = KVM_GUESTDBG_INJECT_BP;
1343 env->exception_injected = -1;
1347 * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
1348 * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
1349 * by updating the debug state once again if single-stepping is on.
1350 * Another reason to call kvm_update_guest_debug here is a pending debug
1351 * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
1352 * reinject them via SET_GUEST_DEBUG.
1354 if (reinject_trap ||
1355 (!kvm_has_robust_singlestep() && env->singlestep_enabled)) {
1356 ret = kvm_update_guest_debug(env, reinject_trap);
1358 return ret;
1361 static int kvm_put_debugregs(CPUState *env)
1363 struct kvm_debugregs dbgregs;
1364 int i;
1366 if (!kvm_has_debugregs()) {
1367 return 0;
1370 for (i = 0; i < 4; i++) {
1371 dbgregs.db[i] = env->dr[i];
1373 dbgregs.dr6 = env->dr[6];
1374 dbgregs.dr7 = env->dr[7];
1375 dbgregs.flags = 0;
1377 return kvm_vcpu_ioctl(env, KVM_SET_DEBUGREGS, &dbgregs);
1380 static int kvm_get_debugregs(CPUState *env)
1382 struct kvm_debugregs dbgregs;
1383 int i, ret;
1385 if (!kvm_has_debugregs()) {
1386 return 0;
1389 ret = kvm_vcpu_ioctl(env, KVM_GET_DEBUGREGS, &dbgregs);
1390 if (ret < 0) {
1391 return ret;
1393 for (i = 0; i < 4; i++) {
1394 env->dr[i] = dbgregs.db[i];
1396 env->dr[4] = env->dr[6] = dbgregs.dr6;
1397 env->dr[5] = env->dr[7] = dbgregs.dr7;
1399 return 0;
1402 int kvm_arch_put_registers(CPUState *env, int level)
1404 int ret;
1406 assert(cpu_is_stopped(env) || qemu_cpu_is_self(env));
1408 ret = kvm_getput_regs(env, 1);
1409 if (ret < 0) {
1410 return ret;
1412 ret = kvm_put_xsave(env);
1413 if (ret < 0) {
1414 return ret;
1416 ret = kvm_put_xcrs(env);
1417 if (ret < 0) {
1418 return ret;
1420 ret = kvm_put_sregs(env);
1421 if (ret < 0) {
1422 return ret;
1424 /* must be before kvm_put_msrs */
1425 ret = kvm_inject_mce_oldstyle(env);
1426 if (ret < 0) {
1427 return ret;
1429 ret = kvm_put_msrs(env, level);
1430 if (ret < 0) {
1431 return ret;
1433 if (level >= KVM_PUT_RESET_STATE) {
1434 ret = kvm_put_mp_state(env);
1435 if (ret < 0) {
1436 return ret;
1439 ret = kvm_put_vcpu_events(env, level);
1440 if (ret < 0) {
1441 return ret;
1443 ret = kvm_put_debugregs(env);
1444 if (ret < 0) {
1445 return ret;
1447 /* must be last */
1448 ret = kvm_guest_debug_workarounds(env);
1449 if (ret < 0) {
1450 return ret;
1452 return 0;
1455 int kvm_arch_get_registers(CPUState *env)
1457 int ret;
1459 assert(cpu_is_stopped(env) || qemu_cpu_is_self(env));
1461 ret = kvm_getput_regs(env, 0);
1462 if (ret < 0) {
1463 return ret;
1465 ret = kvm_get_xsave(env);
1466 if (ret < 0) {
1467 return ret;
1469 ret = kvm_get_xcrs(env);
1470 if (ret < 0) {
1471 return ret;
1473 ret = kvm_get_sregs(env);
1474 if (ret < 0) {
1475 return ret;
1477 ret = kvm_get_msrs(env);
1478 if (ret < 0) {
1479 return ret;
1481 ret = kvm_get_mp_state(env);
1482 if (ret < 0) {
1483 return ret;
1485 ret = kvm_get_vcpu_events(env);
1486 if (ret < 0) {
1487 return ret;
1489 ret = kvm_get_debugregs(env);
1490 if (ret < 0) {
1491 return ret;
1493 return 0;
1496 void kvm_arch_pre_run(CPUState *env, struct kvm_run *run)
1498 int ret;
1500 /* Inject NMI */
1501 if (env->interrupt_request & CPU_INTERRUPT_NMI) {
1502 env->interrupt_request &= ~CPU_INTERRUPT_NMI;
1503 DPRINTF("injected NMI\n");
1504 ret = kvm_vcpu_ioctl(env, KVM_NMI);
1505 if (ret < 0) {
1506 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
1507 strerror(-ret));
1511 if (!kvm_irqchip_in_kernel()) {
1512 /* Force the VCPU out of its inner loop to process the INIT request */
1513 if (env->interrupt_request & CPU_INTERRUPT_INIT) {
1514 env->exit_request = 1;
1517 /* Try to inject an interrupt if the guest can accept it */
1518 if (run->ready_for_interrupt_injection &&
1519 (env->interrupt_request & CPU_INTERRUPT_HARD) &&
1520 (env->eflags & IF_MASK)) {
1521 int irq;
1523 env->interrupt_request &= ~CPU_INTERRUPT_HARD;
1524 irq = cpu_get_pic_interrupt(env);
1525 if (irq >= 0) {
1526 struct kvm_interrupt intr;
1528 intr.irq = irq;
1529 DPRINTF("injected interrupt %d\n", irq);
1530 ret = kvm_vcpu_ioctl(env, KVM_INTERRUPT, &intr);
1531 if (ret < 0) {
1532 fprintf(stderr,
1533 "KVM: injection failed, interrupt lost (%s)\n",
1534 strerror(-ret));
1539 /* If we have an interrupt but the guest is not ready to receive an
1540 * interrupt, request an interrupt window exit. This will
1541 * cause a return to userspace as soon as the guest is ready to
1542 * receive interrupts. */
1543 if ((env->interrupt_request & CPU_INTERRUPT_HARD)) {
1544 run->request_interrupt_window = 1;
1545 } else {
1546 run->request_interrupt_window = 0;
1549 DPRINTF("setting tpr\n");
1550 run->cr8 = cpu_get_apic_tpr(env->apic_state);
1554 void kvm_arch_post_run(CPUState *env, struct kvm_run *run)
1556 if (run->if_flag) {
1557 env->eflags |= IF_MASK;
1558 } else {
1559 env->eflags &= ~IF_MASK;
1561 cpu_set_apic_tpr(env->apic_state, run->cr8);
1562 cpu_set_apic_base(env->apic_state, run->apic_base);
1565 int kvm_arch_process_async_events(CPUState *env)
1567 if (env->interrupt_request & CPU_INTERRUPT_MCE) {
1568 /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
1569 assert(env->mcg_cap);
1571 env->interrupt_request &= ~CPU_INTERRUPT_MCE;
1573 kvm_cpu_synchronize_state(env);
1575 if (env->exception_injected == EXCP08_DBLE) {
1576 /* this means triple fault */
1577 qemu_system_reset_request();
1578 env->exit_request = 1;
1579 return 0;
1581 env->exception_injected = EXCP12_MCHK;
1582 env->has_error_code = 0;
1584 env->halted = 0;
1585 if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
1586 env->mp_state = KVM_MP_STATE_RUNNABLE;
1590 if (kvm_irqchip_in_kernel()) {
1591 return 0;
1594 if (((env->interrupt_request & CPU_INTERRUPT_HARD) &&
1595 (env->eflags & IF_MASK)) ||
1596 (env->interrupt_request & CPU_INTERRUPT_NMI)) {
1597 env->halted = 0;
1599 if (env->interrupt_request & CPU_INTERRUPT_INIT) {
1600 kvm_cpu_synchronize_state(env);
1601 do_cpu_init(env);
1603 if (env->interrupt_request & CPU_INTERRUPT_SIPI) {
1604 kvm_cpu_synchronize_state(env);
1605 do_cpu_sipi(env);
1608 return env->halted;
1611 static int kvm_handle_halt(CPUState *env)
1613 if (!((env->interrupt_request & CPU_INTERRUPT_HARD) &&
1614 (env->eflags & IF_MASK)) &&
1615 !(env->interrupt_request & CPU_INTERRUPT_NMI)) {
1616 env->halted = 1;
1617 return EXCP_HLT;
1620 return 0;
1623 int kvm_arch_insert_sw_breakpoint(CPUState *env, struct kvm_sw_breakpoint *bp)
1625 static const uint8_t int3 = 0xcc;
1627 if (cpu_memory_rw_debug(env, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
1628 cpu_memory_rw_debug(env, bp->pc, (uint8_t *)&int3, 1, 1)) {
1629 return -EINVAL;
1631 return 0;
1634 int kvm_arch_remove_sw_breakpoint(CPUState *env, struct kvm_sw_breakpoint *bp)
1636 uint8_t int3;
1638 if (cpu_memory_rw_debug(env, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
1639 cpu_memory_rw_debug(env, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
1640 return -EINVAL;
1642 return 0;
1645 static struct {
1646 target_ulong addr;
1647 int len;
1648 int type;
1649 } hw_breakpoint[4];
1651 static int nb_hw_breakpoint;
1653 static int find_hw_breakpoint(target_ulong addr, int len, int type)
1655 int n;
1657 for (n = 0; n < nb_hw_breakpoint; n++) {
1658 if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
1659 (hw_breakpoint[n].len == len || len == -1)) {
1660 return n;
1663 return -1;
1666 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
1667 target_ulong len, int type)
1669 switch (type) {
1670 case GDB_BREAKPOINT_HW:
1671 len = 1;
1672 break;
1673 case GDB_WATCHPOINT_WRITE:
1674 case GDB_WATCHPOINT_ACCESS:
1675 switch (len) {
1676 case 1:
1677 break;
1678 case 2:
1679 case 4:
1680 case 8:
1681 if (addr & (len - 1)) {
1682 return -EINVAL;
1684 break;
1685 default:
1686 return -EINVAL;
1688 break;
1689 default:
1690 return -ENOSYS;
1693 if (nb_hw_breakpoint == 4) {
1694 return -ENOBUFS;
1696 if (find_hw_breakpoint(addr, len, type) >= 0) {
1697 return -EEXIST;
1699 hw_breakpoint[nb_hw_breakpoint].addr = addr;
1700 hw_breakpoint[nb_hw_breakpoint].len = len;
1701 hw_breakpoint[nb_hw_breakpoint].type = type;
1702 nb_hw_breakpoint++;
1704 return 0;
1707 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
1708 target_ulong len, int type)
1710 int n;
1712 n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
1713 if (n < 0) {
1714 return -ENOENT;
1716 nb_hw_breakpoint--;
1717 hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
1719 return 0;
1722 void kvm_arch_remove_all_hw_breakpoints(void)
1724 nb_hw_breakpoint = 0;
1727 static CPUWatchpoint hw_watchpoint;
1729 static int kvm_handle_debug(struct kvm_debug_exit_arch *arch_info)
1731 int ret = 0;
1732 int n;
1734 if (arch_info->exception == 1) {
1735 if (arch_info->dr6 & (1 << 14)) {
1736 if (cpu_single_env->singlestep_enabled) {
1737 ret = EXCP_DEBUG;
1739 } else {
1740 for (n = 0; n < 4; n++) {
1741 if (arch_info->dr6 & (1 << n)) {
1742 switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
1743 case 0x0:
1744 ret = EXCP_DEBUG;
1745 break;
1746 case 0x1:
1747 ret = EXCP_DEBUG;
1748 cpu_single_env->watchpoint_hit = &hw_watchpoint;
1749 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
1750 hw_watchpoint.flags = BP_MEM_WRITE;
1751 break;
1752 case 0x3:
1753 ret = EXCP_DEBUG;
1754 cpu_single_env->watchpoint_hit = &hw_watchpoint;
1755 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
1756 hw_watchpoint.flags = BP_MEM_ACCESS;
1757 break;
1762 } else if (kvm_find_sw_breakpoint(cpu_single_env, arch_info->pc)) {
1763 ret = EXCP_DEBUG;
1765 if (ret == 0) {
1766 cpu_synchronize_state(cpu_single_env);
1767 assert(cpu_single_env->exception_injected == -1);
1769 /* pass to guest */
1770 cpu_single_env->exception_injected = arch_info->exception;
1771 cpu_single_env->has_error_code = 0;
1774 return ret;
1777 void kvm_arch_update_guest_debug(CPUState *env, struct kvm_guest_debug *dbg)
1779 const uint8_t type_code[] = {
1780 [GDB_BREAKPOINT_HW] = 0x0,
1781 [GDB_WATCHPOINT_WRITE] = 0x1,
1782 [GDB_WATCHPOINT_ACCESS] = 0x3
1784 const uint8_t len_code[] = {
1785 [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
1787 int n;
1789 if (kvm_sw_breakpoints_active(env)) {
1790 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
1792 if (nb_hw_breakpoint > 0) {
1793 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
1794 dbg->arch.debugreg[7] = 0x0600;
1795 for (n = 0; n < nb_hw_breakpoint; n++) {
1796 dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
1797 dbg->arch.debugreg[7] |= (2 << (n * 2)) |
1798 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
1799 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
1804 static bool host_supports_vmx(void)
1806 uint32_t ecx, unused;
1808 host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
1809 return ecx & CPUID_EXT_VMX;
1812 #define VMX_INVALID_GUEST_STATE 0x80000021
1814 int kvm_arch_handle_exit(CPUState *env, struct kvm_run *run)
1816 uint64_t code;
1817 int ret;
1819 switch (run->exit_reason) {
1820 case KVM_EXIT_HLT:
1821 DPRINTF("handle_hlt\n");
1822 ret = kvm_handle_halt(env);
1823 break;
1824 case KVM_EXIT_SET_TPR:
1825 ret = 0;
1826 break;
1827 case KVM_EXIT_FAIL_ENTRY:
1828 code = run->fail_entry.hardware_entry_failure_reason;
1829 fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
1830 code);
1831 if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
1832 fprintf(stderr,
1833 "\nIf you're runnning a guest on an Intel machine without "
1834 "unrestricted mode\n"
1835 "support, the failure can be most likely due to the guest "
1836 "entering an invalid\n"
1837 "state for Intel VT. For example, the guest maybe running "
1838 "in big real mode\n"
1839 "which is not supported on less recent Intel processors."
1840 "\n\n");
1842 ret = -1;
1843 break;
1844 case KVM_EXIT_EXCEPTION:
1845 fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
1846 run->ex.exception, run->ex.error_code);
1847 ret = -1;
1848 break;
1849 case KVM_EXIT_DEBUG:
1850 DPRINTF("kvm_exit_debug\n");
1851 ret = kvm_handle_debug(&run->debug.arch);
1852 break;
1853 default:
1854 fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
1855 ret = -1;
1856 break;
1859 return ret;
1862 bool kvm_arch_stop_on_emulation_error(CPUState *env)
1864 return !(env->cr[0] & CR0_PE_MASK) ||
1865 ((env->segs[R_CS].selector & 3) != 3);