tcg: Change tcg_gen_exit_tb argument to uintptr_t
[qemu/kevin.git] / target-i386 / kvm.c
blob749aa09a21a69951ac6647ac9595279ac68a18f2
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/sysemu.h"
25 #include "sysemu/kvm.h"
26 #include "kvm_i386.h"
27 #include "cpu.h"
28 #include "exec/gdbstub.h"
29 #include "qemu/host-utils.h"
30 #include "qemu/config-file.h"
31 #include "hw/i386/pc.h"
32 #include "hw/i386/apic.h"
33 #include "exec/ioport.h"
34 #include <asm/hyperv.h>
35 #include "hw/pci/pci.h"
37 //#define DEBUG_KVM
39 #ifdef DEBUG_KVM
40 #define DPRINTF(fmt, ...) \
41 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
42 #else
43 #define DPRINTF(fmt, ...) \
44 do { } while (0)
45 #endif
47 #define MSR_KVM_WALL_CLOCK 0x11
48 #define MSR_KVM_SYSTEM_TIME 0x12
50 #ifndef BUS_MCEERR_AR
51 #define BUS_MCEERR_AR 4
52 #endif
53 #ifndef BUS_MCEERR_AO
54 #define BUS_MCEERR_AO 5
55 #endif
57 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
58 KVM_CAP_INFO(SET_TSS_ADDR),
59 KVM_CAP_INFO(EXT_CPUID),
60 KVM_CAP_INFO(MP_STATE),
61 KVM_CAP_LAST_INFO
64 static bool has_msr_star;
65 static bool has_msr_hsave_pa;
66 static bool has_msr_tsc_adjust;
67 static bool has_msr_tsc_deadline;
68 static bool has_msr_feature_control;
69 static bool has_msr_async_pf_en;
70 static bool has_msr_pv_eoi_en;
71 static bool has_msr_misc_enable;
72 static bool has_msr_kvm_steal_time;
73 static int lm_capable_kernel;
75 static bool has_msr_architectural_pmu;
76 static uint32_t num_architectural_pmu_counters;
78 bool kvm_allows_irq0_override(void)
80 return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
83 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
85 struct kvm_cpuid2 *cpuid;
86 int r, size;
88 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
89 cpuid = (struct kvm_cpuid2 *)g_malloc0(size);
90 cpuid->nent = max;
91 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
92 if (r == 0 && cpuid->nent >= max) {
93 r = -E2BIG;
95 if (r < 0) {
96 if (r == -E2BIG) {
97 g_free(cpuid);
98 return NULL;
99 } else {
100 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
101 strerror(-r));
102 exit(1);
105 return cpuid;
108 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
109 * for all entries.
111 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
113 struct kvm_cpuid2 *cpuid;
114 int max = 1;
115 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
116 max *= 2;
118 return cpuid;
121 struct kvm_para_features {
122 int cap;
123 int feature;
124 } para_features[] = {
125 { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
126 { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
127 { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
128 { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
129 { -1, -1 }
132 static int get_para_features(KVMState *s)
134 int i, features = 0;
136 for (i = 0; i < ARRAY_SIZE(para_features) - 1; i++) {
137 if (kvm_check_extension(s, para_features[i].cap)) {
138 features |= (1 << para_features[i].feature);
142 return features;
146 /* Returns the value for a specific register on the cpuid entry
148 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
150 uint32_t ret = 0;
151 switch (reg) {
152 case R_EAX:
153 ret = entry->eax;
154 break;
155 case R_EBX:
156 ret = entry->ebx;
157 break;
158 case R_ECX:
159 ret = entry->ecx;
160 break;
161 case R_EDX:
162 ret = entry->edx;
163 break;
165 return ret;
168 /* Find matching entry for function/index on kvm_cpuid2 struct
170 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
171 uint32_t function,
172 uint32_t index)
174 int i;
175 for (i = 0; i < cpuid->nent; ++i) {
176 if (cpuid->entries[i].function == function &&
177 cpuid->entries[i].index == index) {
178 return &cpuid->entries[i];
181 /* not found: */
182 return NULL;
185 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
186 uint32_t index, int reg)
188 struct kvm_cpuid2 *cpuid;
189 uint32_t ret = 0;
190 uint32_t cpuid_1_edx;
191 bool found = false;
193 cpuid = get_supported_cpuid(s);
195 struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
196 if (entry) {
197 found = true;
198 ret = cpuid_entry_get_reg(entry, reg);
201 /* Fixups for the data returned by KVM, below */
203 if (function == 1 && reg == R_EDX) {
204 /* KVM before 2.6.30 misreports the following features */
205 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
206 } else if (function == 1 && reg == R_ECX) {
207 /* We can set the hypervisor flag, even if KVM does not return it on
208 * GET_SUPPORTED_CPUID
210 ret |= CPUID_EXT_HYPERVISOR;
211 /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
212 * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
213 * and the irqchip is in the kernel.
215 if (kvm_irqchip_in_kernel() &&
216 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
217 ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
220 /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
221 * without the in-kernel irqchip
223 if (!kvm_irqchip_in_kernel()) {
224 ret &= ~CPUID_EXT_X2APIC;
226 } else if (function == 0x80000001 && reg == R_EDX) {
227 /* On Intel, kvm returns cpuid according to the Intel spec,
228 * so add missing bits according to the AMD spec:
230 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
231 ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
234 g_free(cpuid);
236 /* fallback for older kernels */
237 if ((function == KVM_CPUID_FEATURES) && !found) {
238 ret = get_para_features(s);
241 return ret;
244 typedef struct HWPoisonPage {
245 ram_addr_t ram_addr;
246 QLIST_ENTRY(HWPoisonPage) list;
247 } HWPoisonPage;
249 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
250 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
252 static void kvm_unpoison_all(void *param)
254 HWPoisonPage *page, *next_page;
256 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
257 QLIST_REMOVE(page, list);
258 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
259 g_free(page);
263 static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
265 HWPoisonPage *page;
267 QLIST_FOREACH(page, &hwpoison_page_list, list) {
268 if (page->ram_addr == ram_addr) {
269 return;
272 page = g_malloc(sizeof(HWPoisonPage));
273 page->ram_addr = ram_addr;
274 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
277 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
278 int *max_banks)
280 int r;
282 r = kvm_check_extension(s, KVM_CAP_MCE);
283 if (r > 0) {
284 *max_banks = r;
285 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
287 return -ENOSYS;
290 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
292 CPUX86State *env = &cpu->env;
293 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
294 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
295 uint64_t mcg_status = MCG_STATUS_MCIP;
297 if (code == BUS_MCEERR_AR) {
298 status |= MCI_STATUS_AR | 0x134;
299 mcg_status |= MCG_STATUS_EIPV;
300 } else {
301 status |= 0xc0;
302 mcg_status |= MCG_STATUS_RIPV;
304 cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
305 (MCM_ADDR_PHYS << 6) | 0xc,
306 cpu_x86_support_mca_broadcast(env) ?
307 MCE_INJECT_BROADCAST : 0);
310 static void hardware_memory_error(void)
312 fprintf(stderr, "Hardware memory error!\n");
313 exit(1);
316 int kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
318 X86CPU *cpu = X86_CPU(c);
319 CPUX86State *env = &cpu->env;
320 ram_addr_t ram_addr;
321 hwaddr paddr;
323 if ((env->mcg_cap & MCG_SER_P) && addr
324 && (code == BUS_MCEERR_AR || code == BUS_MCEERR_AO)) {
325 if (qemu_ram_addr_from_host(addr, &ram_addr) == NULL ||
326 !kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
327 fprintf(stderr, "Hardware memory error for memory used by "
328 "QEMU itself instead of guest system!\n");
329 /* Hope we are lucky for AO MCE */
330 if (code == BUS_MCEERR_AO) {
331 return 0;
332 } else {
333 hardware_memory_error();
336 kvm_hwpoison_page_add(ram_addr);
337 kvm_mce_inject(cpu, paddr, code);
338 } else {
339 if (code == BUS_MCEERR_AO) {
340 return 0;
341 } else if (code == BUS_MCEERR_AR) {
342 hardware_memory_error();
343 } else {
344 return 1;
347 return 0;
350 int kvm_arch_on_sigbus(int code, void *addr)
352 X86CPU *cpu = X86_CPU(first_cpu);
354 if ((cpu->env.mcg_cap & MCG_SER_P) && addr && code == BUS_MCEERR_AO) {
355 ram_addr_t ram_addr;
356 hwaddr paddr;
358 /* Hope we are lucky for AO MCE */
359 if (qemu_ram_addr_from_host(addr, &ram_addr) == NULL ||
360 !kvm_physical_memory_addr_from_host(first_cpu->kvm_state,
361 addr, &paddr)) {
362 fprintf(stderr, "Hardware memory error for memory used by "
363 "QEMU itself instead of guest system!: %p\n", addr);
364 return 0;
366 kvm_hwpoison_page_add(ram_addr);
367 kvm_mce_inject(X86_CPU(first_cpu), paddr, code);
368 } else {
369 if (code == BUS_MCEERR_AO) {
370 return 0;
371 } else if (code == BUS_MCEERR_AR) {
372 hardware_memory_error();
373 } else {
374 return 1;
377 return 0;
380 static int kvm_inject_mce_oldstyle(X86CPU *cpu)
382 CPUX86State *env = &cpu->env;
384 if (!kvm_has_vcpu_events() && env->exception_injected == EXCP12_MCHK) {
385 unsigned int bank, bank_num = env->mcg_cap & 0xff;
386 struct kvm_x86_mce mce;
388 env->exception_injected = -1;
391 * There must be at least one bank in use if an MCE is pending.
392 * Find it and use its values for the event injection.
394 for (bank = 0; bank < bank_num; bank++) {
395 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
396 break;
399 assert(bank < bank_num);
401 mce.bank = bank;
402 mce.status = env->mce_banks[bank * 4 + 1];
403 mce.mcg_status = env->mcg_status;
404 mce.addr = env->mce_banks[bank * 4 + 2];
405 mce.misc = env->mce_banks[bank * 4 + 3];
407 return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
409 return 0;
412 static void cpu_update_state(void *opaque, int running, RunState state)
414 CPUX86State *env = opaque;
416 if (running) {
417 env->tsc_valid = false;
421 unsigned long kvm_arch_vcpu_id(CPUState *cs)
423 X86CPU *cpu = X86_CPU(cs);
424 return cpu->env.cpuid_apic_id;
427 #ifndef KVM_CPUID_SIGNATURE_NEXT
428 #define KVM_CPUID_SIGNATURE_NEXT 0x40000100
429 #endif
431 static bool hyperv_hypercall_available(X86CPU *cpu)
433 return cpu->hyperv_vapic ||
434 (cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY);
437 static bool hyperv_enabled(X86CPU *cpu)
439 return hyperv_hypercall_available(cpu) ||
440 cpu->hyperv_relaxed_timing;
443 #define KVM_MAX_CPUID_ENTRIES 100
445 int kvm_arch_init_vcpu(CPUState *cs)
447 struct {
448 struct kvm_cpuid2 cpuid;
449 struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
450 } QEMU_PACKED cpuid_data;
451 X86CPU *cpu = X86_CPU(cs);
452 CPUX86State *env = &cpu->env;
453 uint32_t limit, i, j, cpuid_i;
454 uint32_t unused;
455 struct kvm_cpuid_entry2 *c;
456 uint32_t signature[3];
457 int r;
459 cpuid_i = 0;
461 /* Paravirtualization CPUIDs */
462 c = &cpuid_data.entries[cpuid_i++];
463 memset(c, 0, sizeof(*c));
464 c->function = KVM_CPUID_SIGNATURE;
465 if (!hyperv_enabled(cpu)) {
466 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
467 c->eax = 0;
468 } else {
469 memcpy(signature, "Microsoft Hv", 12);
470 c->eax = HYPERV_CPUID_MIN;
472 c->ebx = signature[0];
473 c->ecx = signature[1];
474 c->edx = signature[2];
476 c = &cpuid_data.entries[cpuid_i++];
477 memset(c, 0, sizeof(*c));
478 c->function = KVM_CPUID_FEATURES;
479 c->eax = env->features[FEAT_KVM];
481 if (hyperv_enabled(cpu)) {
482 memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
483 c->eax = signature[0];
485 c = &cpuid_data.entries[cpuid_i++];
486 memset(c, 0, sizeof(*c));
487 c->function = HYPERV_CPUID_VERSION;
488 c->eax = 0x00001bbc;
489 c->ebx = 0x00060001;
491 c = &cpuid_data.entries[cpuid_i++];
492 memset(c, 0, sizeof(*c));
493 c->function = HYPERV_CPUID_FEATURES;
494 if (cpu->hyperv_relaxed_timing) {
495 c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
497 if (cpu->hyperv_vapic) {
498 c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
499 c->eax |= HV_X64_MSR_APIC_ACCESS_AVAILABLE;
502 c = &cpuid_data.entries[cpuid_i++];
503 memset(c, 0, sizeof(*c));
504 c->function = HYPERV_CPUID_ENLIGHTMENT_INFO;
505 if (cpu->hyperv_relaxed_timing) {
506 c->eax |= HV_X64_RELAXED_TIMING_RECOMMENDED;
508 if (cpu->hyperv_vapic) {
509 c->eax |= HV_X64_APIC_ACCESS_RECOMMENDED;
511 c->ebx = cpu->hyperv_spinlock_attempts;
513 c = &cpuid_data.entries[cpuid_i++];
514 memset(c, 0, sizeof(*c));
515 c->function = HYPERV_CPUID_IMPLEMENT_LIMITS;
516 c->eax = 0x40;
517 c->ebx = 0x40;
519 c = &cpuid_data.entries[cpuid_i++];
520 memset(c, 0, sizeof(*c));
521 c->function = KVM_CPUID_SIGNATURE_NEXT;
522 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
523 c->eax = 0;
524 c->ebx = signature[0];
525 c->ecx = signature[1];
526 c->edx = signature[2];
529 has_msr_async_pf_en = c->eax & (1 << KVM_FEATURE_ASYNC_PF);
531 has_msr_pv_eoi_en = c->eax & (1 << KVM_FEATURE_PV_EOI);
533 has_msr_kvm_steal_time = c->eax & (1 << KVM_FEATURE_STEAL_TIME);
535 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
537 for (i = 0; i <= limit; i++) {
538 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
539 fprintf(stderr, "unsupported level value: 0x%x\n", limit);
540 abort();
542 c = &cpuid_data.entries[cpuid_i++];
544 switch (i) {
545 case 2: {
546 /* Keep reading function 2 till all the input is received */
547 int times;
549 c->function = i;
550 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
551 KVM_CPUID_FLAG_STATE_READ_NEXT;
552 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
553 times = c->eax & 0xff;
555 for (j = 1; j < times; ++j) {
556 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
557 fprintf(stderr, "cpuid_data is full, no space for "
558 "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
559 abort();
561 c = &cpuid_data.entries[cpuid_i++];
562 c->function = i;
563 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
564 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
566 break;
568 case 4:
569 case 0xb:
570 case 0xd:
571 for (j = 0; ; j++) {
572 if (i == 0xd && j == 64) {
573 break;
575 c->function = i;
576 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
577 c->index = j;
578 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
580 if (i == 4 && c->eax == 0) {
581 break;
583 if (i == 0xb && !(c->ecx & 0xff00)) {
584 break;
586 if (i == 0xd && c->eax == 0) {
587 continue;
589 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
590 fprintf(stderr, "cpuid_data is full, no space for "
591 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
592 abort();
594 c = &cpuid_data.entries[cpuid_i++];
596 break;
597 default:
598 c->function = i;
599 c->flags = 0;
600 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
601 break;
605 if (limit >= 0x0a) {
606 uint32_t ver;
608 cpu_x86_cpuid(env, 0x0a, 0, &ver, &unused, &unused, &unused);
609 if ((ver & 0xff) > 0) {
610 has_msr_architectural_pmu = true;
611 num_architectural_pmu_counters = (ver & 0xff00) >> 8;
613 /* Shouldn't be more than 32, since that's the number of bits
614 * available in EBX to tell us _which_ counters are available.
615 * Play it safe.
617 if (num_architectural_pmu_counters > MAX_GP_COUNTERS) {
618 num_architectural_pmu_counters = MAX_GP_COUNTERS;
623 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
625 for (i = 0x80000000; i <= limit; i++) {
626 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
627 fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
628 abort();
630 c = &cpuid_data.entries[cpuid_i++];
632 c->function = i;
633 c->flags = 0;
634 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
637 /* Call Centaur's CPUID instructions they are supported. */
638 if (env->cpuid_xlevel2 > 0) {
639 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
641 for (i = 0xC0000000; i <= limit; i++) {
642 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
643 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
644 abort();
646 c = &cpuid_data.entries[cpuid_i++];
648 c->function = i;
649 c->flags = 0;
650 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
654 cpuid_data.cpuid.nent = cpuid_i;
656 if (((env->cpuid_version >> 8)&0xF) >= 6
657 && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
658 (CPUID_MCE | CPUID_MCA)
659 && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
660 uint64_t mcg_cap;
661 int banks;
662 int ret;
664 ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
665 if (ret < 0) {
666 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
667 return ret;
670 if (banks > MCE_BANKS_DEF) {
671 banks = MCE_BANKS_DEF;
673 mcg_cap &= MCE_CAP_DEF;
674 mcg_cap |= banks;
675 ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &mcg_cap);
676 if (ret < 0) {
677 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
678 return ret;
681 env->mcg_cap = mcg_cap;
684 qemu_add_vm_change_state_handler(cpu_update_state, env);
686 c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
687 if (c) {
688 has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
689 !!(c->ecx & CPUID_EXT_SMX);
692 cpuid_data.cpuid.padding = 0;
693 r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
694 if (r) {
695 return r;
698 r = kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL);
699 if (r && env->tsc_khz) {
700 r = kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz);
701 if (r < 0) {
702 fprintf(stderr, "KVM_SET_TSC_KHZ failed\n");
703 return r;
707 if (kvm_has_xsave()) {
708 env->kvm_xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
711 return 0;
714 void kvm_arch_reset_vcpu(CPUState *cs)
716 X86CPU *cpu = X86_CPU(cs);
717 CPUX86State *env = &cpu->env;
719 env->exception_injected = -1;
720 env->interrupt_injected = -1;
721 env->xcr0 = 1;
722 if (kvm_irqchip_in_kernel()) {
723 env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
724 KVM_MP_STATE_UNINITIALIZED;
725 } else {
726 env->mp_state = KVM_MP_STATE_RUNNABLE;
730 static int kvm_get_supported_msrs(KVMState *s)
732 static int kvm_supported_msrs;
733 int ret = 0;
735 /* first time */
736 if (kvm_supported_msrs == 0) {
737 struct kvm_msr_list msr_list, *kvm_msr_list;
739 kvm_supported_msrs = -1;
741 /* Obtain MSR list from KVM. These are the MSRs that we must
742 * save/restore */
743 msr_list.nmsrs = 0;
744 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
745 if (ret < 0 && ret != -E2BIG) {
746 return ret;
748 /* Old kernel modules had a bug and could write beyond the provided
749 memory. Allocate at least a safe amount of 1K. */
750 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
751 msr_list.nmsrs *
752 sizeof(msr_list.indices[0])));
754 kvm_msr_list->nmsrs = msr_list.nmsrs;
755 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
756 if (ret >= 0) {
757 int i;
759 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
760 if (kvm_msr_list->indices[i] == MSR_STAR) {
761 has_msr_star = true;
762 continue;
764 if (kvm_msr_list->indices[i] == MSR_VM_HSAVE_PA) {
765 has_msr_hsave_pa = true;
766 continue;
768 if (kvm_msr_list->indices[i] == MSR_TSC_ADJUST) {
769 has_msr_tsc_adjust = true;
770 continue;
772 if (kvm_msr_list->indices[i] == MSR_IA32_TSCDEADLINE) {
773 has_msr_tsc_deadline = true;
774 continue;
776 if (kvm_msr_list->indices[i] == MSR_IA32_MISC_ENABLE) {
777 has_msr_misc_enable = true;
778 continue;
783 g_free(kvm_msr_list);
786 return ret;
789 int kvm_arch_init(KVMState *s)
791 uint64_t identity_base = 0xfffbc000;
792 uint64_t shadow_mem;
793 int ret;
794 struct utsname utsname;
796 ret = kvm_get_supported_msrs(s);
797 if (ret < 0) {
798 return ret;
801 uname(&utsname);
802 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
805 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
806 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
807 * Since these must be part of guest physical memory, we need to allocate
808 * them, both by setting their start addresses in the kernel and by
809 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
811 * Older KVM versions may not support setting the identity map base. In
812 * that case we need to stick with the default, i.e. a 256K maximum BIOS
813 * size.
815 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
816 /* Allows up to 16M BIOSes. */
817 identity_base = 0xfeffc000;
819 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
820 if (ret < 0) {
821 return ret;
825 /* Set TSS base one page after EPT identity map. */
826 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
827 if (ret < 0) {
828 return ret;
831 /* Tell fw_cfg to notify the BIOS to reserve the range. */
832 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
833 if (ret < 0) {
834 fprintf(stderr, "e820_add_entry() table is full\n");
835 return ret;
837 qemu_register_reset(kvm_unpoison_all, NULL);
839 shadow_mem = qemu_opt_get_size(qemu_get_machine_opts(),
840 "kvm_shadow_mem", -1);
841 if (shadow_mem != -1) {
842 shadow_mem /= 4096;
843 ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
844 if (ret < 0) {
845 return ret;
848 return 0;
851 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
853 lhs->selector = rhs->selector;
854 lhs->base = rhs->base;
855 lhs->limit = rhs->limit;
856 lhs->type = 3;
857 lhs->present = 1;
858 lhs->dpl = 3;
859 lhs->db = 0;
860 lhs->s = 1;
861 lhs->l = 0;
862 lhs->g = 0;
863 lhs->avl = 0;
864 lhs->unusable = 0;
867 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
869 unsigned flags = rhs->flags;
870 lhs->selector = rhs->selector;
871 lhs->base = rhs->base;
872 lhs->limit = rhs->limit;
873 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
874 lhs->present = (flags & DESC_P_MASK) != 0;
875 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
876 lhs->db = (flags >> DESC_B_SHIFT) & 1;
877 lhs->s = (flags & DESC_S_MASK) != 0;
878 lhs->l = (flags >> DESC_L_SHIFT) & 1;
879 lhs->g = (flags & DESC_G_MASK) != 0;
880 lhs->avl = (flags & DESC_AVL_MASK) != 0;
881 lhs->unusable = 0;
882 lhs->padding = 0;
885 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
887 lhs->selector = rhs->selector;
888 lhs->base = rhs->base;
889 lhs->limit = rhs->limit;
890 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
891 (rhs->present * DESC_P_MASK) |
892 (rhs->dpl << DESC_DPL_SHIFT) |
893 (rhs->db << DESC_B_SHIFT) |
894 (rhs->s * DESC_S_MASK) |
895 (rhs->l << DESC_L_SHIFT) |
896 (rhs->g * DESC_G_MASK) |
897 (rhs->avl * DESC_AVL_MASK);
900 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
902 if (set) {
903 *kvm_reg = *qemu_reg;
904 } else {
905 *qemu_reg = *kvm_reg;
909 static int kvm_getput_regs(X86CPU *cpu, int set)
911 CPUX86State *env = &cpu->env;
912 struct kvm_regs regs;
913 int ret = 0;
915 if (!set) {
916 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
917 if (ret < 0) {
918 return ret;
922 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
923 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
924 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
925 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
926 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
927 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
928 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
929 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
930 #ifdef TARGET_X86_64
931 kvm_getput_reg(&regs.r8, &env->regs[8], set);
932 kvm_getput_reg(&regs.r9, &env->regs[9], set);
933 kvm_getput_reg(&regs.r10, &env->regs[10], set);
934 kvm_getput_reg(&regs.r11, &env->regs[11], set);
935 kvm_getput_reg(&regs.r12, &env->regs[12], set);
936 kvm_getput_reg(&regs.r13, &env->regs[13], set);
937 kvm_getput_reg(&regs.r14, &env->regs[14], set);
938 kvm_getput_reg(&regs.r15, &env->regs[15], set);
939 #endif
941 kvm_getput_reg(&regs.rflags, &env->eflags, set);
942 kvm_getput_reg(&regs.rip, &env->eip, set);
944 if (set) {
945 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
948 return ret;
951 static int kvm_put_fpu(X86CPU *cpu)
953 CPUX86State *env = &cpu->env;
954 struct kvm_fpu fpu;
955 int i;
957 memset(&fpu, 0, sizeof fpu);
958 fpu.fsw = env->fpus & ~(7 << 11);
959 fpu.fsw |= (env->fpstt & 7) << 11;
960 fpu.fcw = env->fpuc;
961 fpu.last_opcode = env->fpop;
962 fpu.last_ip = env->fpip;
963 fpu.last_dp = env->fpdp;
964 for (i = 0; i < 8; ++i) {
965 fpu.ftwx |= (!env->fptags[i]) << i;
967 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
968 memcpy(fpu.xmm, env->xmm_regs, sizeof env->xmm_regs);
969 fpu.mxcsr = env->mxcsr;
971 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
974 #define XSAVE_FCW_FSW 0
975 #define XSAVE_FTW_FOP 1
976 #define XSAVE_CWD_RIP 2
977 #define XSAVE_CWD_RDP 4
978 #define XSAVE_MXCSR 6
979 #define XSAVE_ST_SPACE 8
980 #define XSAVE_XMM_SPACE 40
981 #define XSAVE_XSTATE_BV 128
982 #define XSAVE_YMMH_SPACE 144
984 static int kvm_put_xsave(X86CPU *cpu)
986 CPUX86State *env = &cpu->env;
987 struct kvm_xsave* xsave = env->kvm_xsave_buf;
988 uint16_t cwd, swd, twd;
989 int i, r;
991 if (!kvm_has_xsave()) {
992 return kvm_put_fpu(cpu);
995 memset(xsave, 0, sizeof(struct kvm_xsave));
996 twd = 0;
997 swd = env->fpus & ~(7 << 11);
998 swd |= (env->fpstt & 7) << 11;
999 cwd = env->fpuc;
1000 for (i = 0; i < 8; ++i) {
1001 twd |= (!env->fptags[i]) << i;
1003 xsave->region[XSAVE_FCW_FSW] = (uint32_t)(swd << 16) + cwd;
1004 xsave->region[XSAVE_FTW_FOP] = (uint32_t)(env->fpop << 16) + twd;
1005 memcpy(&xsave->region[XSAVE_CWD_RIP], &env->fpip, sizeof(env->fpip));
1006 memcpy(&xsave->region[XSAVE_CWD_RDP], &env->fpdp, sizeof(env->fpdp));
1007 memcpy(&xsave->region[XSAVE_ST_SPACE], env->fpregs,
1008 sizeof env->fpregs);
1009 memcpy(&xsave->region[XSAVE_XMM_SPACE], env->xmm_regs,
1010 sizeof env->xmm_regs);
1011 xsave->region[XSAVE_MXCSR] = env->mxcsr;
1012 *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV] = env->xstate_bv;
1013 memcpy(&xsave->region[XSAVE_YMMH_SPACE], env->ymmh_regs,
1014 sizeof env->ymmh_regs);
1015 r = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
1016 return r;
1019 static int kvm_put_xcrs(X86CPU *cpu)
1021 CPUX86State *env = &cpu->env;
1022 struct kvm_xcrs xcrs;
1024 if (!kvm_has_xcrs()) {
1025 return 0;
1028 xcrs.nr_xcrs = 1;
1029 xcrs.flags = 0;
1030 xcrs.xcrs[0].xcr = 0;
1031 xcrs.xcrs[0].value = env->xcr0;
1032 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
1035 static int kvm_put_sregs(X86CPU *cpu)
1037 CPUX86State *env = &cpu->env;
1038 struct kvm_sregs sregs;
1040 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
1041 if (env->interrupt_injected >= 0) {
1042 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
1043 (uint64_t)1 << (env->interrupt_injected % 64);
1046 if ((env->eflags & VM_MASK)) {
1047 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
1048 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
1049 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
1050 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
1051 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
1052 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
1053 } else {
1054 set_seg(&sregs.cs, &env->segs[R_CS]);
1055 set_seg(&sregs.ds, &env->segs[R_DS]);
1056 set_seg(&sregs.es, &env->segs[R_ES]);
1057 set_seg(&sregs.fs, &env->segs[R_FS]);
1058 set_seg(&sregs.gs, &env->segs[R_GS]);
1059 set_seg(&sregs.ss, &env->segs[R_SS]);
1062 set_seg(&sregs.tr, &env->tr);
1063 set_seg(&sregs.ldt, &env->ldt);
1065 sregs.idt.limit = env->idt.limit;
1066 sregs.idt.base = env->idt.base;
1067 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
1068 sregs.gdt.limit = env->gdt.limit;
1069 sregs.gdt.base = env->gdt.base;
1070 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
1072 sregs.cr0 = env->cr[0];
1073 sregs.cr2 = env->cr[2];
1074 sregs.cr3 = env->cr[3];
1075 sregs.cr4 = env->cr[4];
1077 sregs.cr8 = cpu_get_apic_tpr(env->apic_state);
1078 sregs.apic_base = cpu_get_apic_base(env->apic_state);
1080 sregs.efer = env->efer;
1082 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
1085 static void kvm_msr_entry_set(struct kvm_msr_entry *entry,
1086 uint32_t index, uint64_t value)
1088 entry->index = index;
1089 entry->data = value;
1092 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
1094 CPUX86State *env = &cpu->env;
1095 struct {
1096 struct kvm_msrs info;
1097 struct kvm_msr_entry entries[1];
1098 } msr_data;
1099 struct kvm_msr_entry *msrs = msr_data.entries;
1101 if (!has_msr_tsc_deadline) {
1102 return 0;
1105 kvm_msr_entry_set(&msrs[0], MSR_IA32_TSCDEADLINE, env->tsc_deadline);
1107 msr_data.info.nmsrs = 1;
1109 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, &msr_data);
1112 static int kvm_put_msrs(X86CPU *cpu, int level)
1114 CPUX86State *env = &cpu->env;
1115 struct {
1116 struct kvm_msrs info;
1117 struct kvm_msr_entry entries[100];
1118 } msr_data;
1119 struct kvm_msr_entry *msrs = msr_data.entries;
1120 int n = 0, i;
1122 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_CS, env->sysenter_cs);
1123 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
1124 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
1125 kvm_msr_entry_set(&msrs[n++], MSR_PAT, env->pat);
1126 if (has_msr_star) {
1127 kvm_msr_entry_set(&msrs[n++], MSR_STAR, env->star);
1129 if (has_msr_hsave_pa) {
1130 kvm_msr_entry_set(&msrs[n++], MSR_VM_HSAVE_PA, env->vm_hsave);
1132 if (has_msr_tsc_adjust) {
1133 kvm_msr_entry_set(&msrs[n++], MSR_TSC_ADJUST, env->tsc_adjust);
1135 if (has_msr_misc_enable) {
1136 kvm_msr_entry_set(&msrs[n++], MSR_IA32_MISC_ENABLE,
1137 env->msr_ia32_misc_enable);
1139 #ifdef TARGET_X86_64
1140 if (lm_capable_kernel) {
1141 kvm_msr_entry_set(&msrs[n++], MSR_CSTAR, env->cstar);
1142 kvm_msr_entry_set(&msrs[n++], MSR_KERNELGSBASE, env->kernelgsbase);
1143 kvm_msr_entry_set(&msrs[n++], MSR_FMASK, env->fmask);
1144 kvm_msr_entry_set(&msrs[n++], MSR_LSTAR, env->lstar);
1146 #endif
1147 if (level == KVM_PUT_FULL_STATE) {
1149 * KVM is yet unable to synchronize TSC values of multiple VCPUs on
1150 * writeback. Until this is fixed, we only write the offset to SMP
1151 * guests after migration, desynchronizing the VCPUs, but avoiding
1152 * huge jump-backs that would occur without any writeback at all.
1154 if (smp_cpus == 1 || env->tsc != 0) {
1155 kvm_msr_entry_set(&msrs[n++], MSR_IA32_TSC, env->tsc);
1159 * The following MSRs have side effects on the guest or are too heavy
1160 * for normal writeback. Limit them to reset or full state updates.
1162 if (level >= KVM_PUT_RESET_STATE) {
1163 kvm_msr_entry_set(&msrs[n++], MSR_KVM_SYSTEM_TIME,
1164 env->system_time_msr);
1165 kvm_msr_entry_set(&msrs[n++], MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
1166 if (has_msr_async_pf_en) {
1167 kvm_msr_entry_set(&msrs[n++], MSR_KVM_ASYNC_PF_EN,
1168 env->async_pf_en_msr);
1170 if (has_msr_pv_eoi_en) {
1171 kvm_msr_entry_set(&msrs[n++], MSR_KVM_PV_EOI_EN,
1172 env->pv_eoi_en_msr);
1174 if (has_msr_kvm_steal_time) {
1175 kvm_msr_entry_set(&msrs[n++], MSR_KVM_STEAL_TIME,
1176 env->steal_time_msr);
1178 if (has_msr_architectural_pmu) {
1179 /* Stop the counter. */
1180 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
1181 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_GLOBAL_CTRL, 0);
1183 /* Set the counter values. */
1184 for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
1185 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_FIXED_CTR0 + i,
1186 env->msr_fixed_counters[i]);
1188 for (i = 0; i < num_architectural_pmu_counters; i++) {
1189 kvm_msr_entry_set(&msrs[n++], MSR_P6_PERFCTR0 + i,
1190 env->msr_gp_counters[i]);
1191 kvm_msr_entry_set(&msrs[n++], MSR_P6_EVNTSEL0 + i,
1192 env->msr_gp_evtsel[i]);
1194 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_GLOBAL_STATUS,
1195 env->msr_global_status);
1196 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1197 env->msr_global_ovf_ctrl);
1199 /* Now start the PMU. */
1200 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_FIXED_CTR_CTRL,
1201 env->msr_fixed_ctr_ctrl);
1202 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_GLOBAL_CTRL,
1203 env->msr_global_ctrl);
1205 if (hyperv_hypercall_available(cpu)) {
1206 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_GUEST_OS_ID, 0);
1207 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_HYPERCALL, 0);
1209 if (cpu->hyperv_vapic) {
1210 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_APIC_ASSIST_PAGE, 0);
1212 if (has_msr_feature_control) {
1213 kvm_msr_entry_set(&msrs[n++], MSR_IA32_FEATURE_CONTROL,
1214 env->msr_ia32_feature_control);
1217 if (env->mcg_cap) {
1218 int i;
1220 kvm_msr_entry_set(&msrs[n++], MSR_MCG_STATUS, env->mcg_status);
1221 kvm_msr_entry_set(&msrs[n++], MSR_MCG_CTL, env->mcg_ctl);
1222 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1223 kvm_msr_entry_set(&msrs[n++], MSR_MC0_CTL + i, env->mce_banks[i]);
1227 msr_data.info.nmsrs = n;
1229 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, &msr_data);
1234 static int kvm_get_fpu(X86CPU *cpu)
1236 CPUX86State *env = &cpu->env;
1237 struct kvm_fpu fpu;
1238 int i, ret;
1240 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
1241 if (ret < 0) {
1242 return ret;
1245 env->fpstt = (fpu.fsw >> 11) & 7;
1246 env->fpus = fpu.fsw;
1247 env->fpuc = fpu.fcw;
1248 env->fpop = fpu.last_opcode;
1249 env->fpip = fpu.last_ip;
1250 env->fpdp = fpu.last_dp;
1251 for (i = 0; i < 8; ++i) {
1252 env->fptags[i] = !((fpu.ftwx >> i) & 1);
1254 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
1255 memcpy(env->xmm_regs, fpu.xmm, sizeof env->xmm_regs);
1256 env->mxcsr = fpu.mxcsr;
1258 return 0;
1261 static int kvm_get_xsave(X86CPU *cpu)
1263 CPUX86State *env = &cpu->env;
1264 struct kvm_xsave* xsave = env->kvm_xsave_buf;
1265 int ret, i;
1266 uint16_t cwd, swd, twd;
1268 if (!kvm_has_xsave()) {
1269 return kvm_get_fpu(cpu);
1272 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
1273 if (ret < 0) {
1274 return ret;
1277 cwd = (uint16_t)xsave->region[XSAVE_FCW_FSW];
1278 swd = (uint16_t)(xsave->region[XSAVE_FCW_FSW] >> 16);
1279 twd = (uint16_t)xsave->region[XSAVE_FTW_FOP];
1280 env->fpop = (uint16_t)(xsave->region[XSAVE_FTW_FOP] >> 16);
1281 env->fpstt = (swd >> 11) & 7;
1282 env->fpus = swd;
1283 env->fpuc = cwd;
1284 for (i = 0; i < 8; ++i) {
1285 env->fptags[i] = !((twd >> i) & 1);
1287 memcpy(&env->fpip, &xsave->region[XSAVE_CWD_RIP], sizeof(env->fpip));
1288 memcpy(&env->fpdp, &xsave->region[XSAVE_CWD_RDP], sizeof(env->fpdp));
1289 env->mxcsr = xsave->region[XSAVE_MXCSR];
1290 memcpy(env->fpregs, &xsave->region[XSAVE_ST_SPACE],
1291 sizeof env->fpregs);
1292 memcpy(env->xmm_regs, &xsave->region[XSAVE_XMM_SPACE],
1293 sizeof env->xmm_regs);
1294 env->xstate_bv = *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV];
1295 memcpy(env->ymmh_regs, &xsave->region[XSAVE_YMMH_SPACE],
1296 sizeof env->ymmh_regs);
1297 return 0;
1300 static int kvm_get_xcrs(X86CPU *cpu)
1302 CPUX86State *env = &cpu->env;
1303 int i, ret;
1304 struct kvm_xcrs xcrs;
1306 if (!kvm_has_xcrs()) {
1307 return 0;
1310 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
1311 if (ret < 0) {
1312 return ret;
1315 for (i = 0; i < xcrs.nr_xcrs; i++) {
1316 /* Only support xcr0 now */
1317 if (xcrs.xcrs[0].xcr == 0) {
1318 env->xcr0 = xcrs.xcrs[0].value;
1319 break;
1322 return 0;
1325 static int kvm_get_sregs(X86CPU *cpu)
1327 CPUX86State *env = &cpu->env;
1328 struct kvm_sregs sregs;
1329 uint32_t hflags;
1330 int bit, i, ret;
1332 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
1333 if (ret < 0) {
1334 return ret;
1337 /* There can only be one pending IRQ set in the bitmap at a time, so try
1338 to find it and save its number instead (-1 for none). */
1339 env->interrupt_injected = -1;
1340 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
1341 if (sregs.interrupt_bitmap[i]) {
1342 bit = ctz64(sregs.interrupt_bitmap[i]);
1343 env->interrupt_injected = i * 64 + bit;
1344 break;
1348 get_seg(&env->segs[R_CS], &sregs.cs);
1349 get_seg(&env->segs[R_DS], &sregs.ds);
1350 get_seg(&env->segs[R_ES], &sregs.es);
1351 get_seg(&env->segs[R_FS], &sregs.fs);
1352 get_seg(&env->segs[R_GS], &sregs.gs);
1353 get_seg(&env->segs[R_SS], &sregs.ss);
1355 get_seg(&env->tr, &sregs.tr);
1356 get_seg(&env->ldt, &sregs.ldt);
1358 env->idt.limit = sregs.idt.limit;
1359 env->idt.base = sregs.idt.base;
1360 env->gdt.limit = sregs.gdt.limit;
1361 env->gdt.base = sregs.gdt.base;
1363 env->cr[0] = sregs.cr0;
1364 env->cr[2] = sregs.cr2;
1365 env->cr[3] = sregs.cr3;
1366 env->cr[4] = sregs.cr4;
1368 env->efer = sregs.efer;
1370 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
1372 #define HFLAG_COPY_MASK \
1373 ~( HF_CPL_MASK | HF_PE_MASK | HF_MP_MASK | HF_EM_MASK | \
1374 HF_TS_MASK | HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK | \
1375 HF_OSFXSR_MASK | HF_LMA_MASK | HF_CS32_MASK | \
1376 HF_SS32_MASK | HF_CS64_MASK | HF_ADDSEG_MASK)
1378 hflags = (env->segs[R_CS].flags >> DESC_DPL_SHIFT) & HF_CPL_MASK;
1379 hflags |= (env->cr[0] & CR0_PE_MASK) << (HF_PE_SHIFT - CR0_PE_SHIFT);
1380 hflags |= (env->cr[0] << (HF_MP_SHIFT - CR0_MP_SHIFT)) &
1381 (HF_MP_MASK | HF_EM_MASK | HF_TS_MASK);
1382 hflags |= (env->eflags & (HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK));
1383 hflags |= (env->cr[4] & CR4_OSFXSR_MASK) <<
1384 (HF_OSFXSR_SHIFT - CR4_OSFXSR_SHIFT);
1386 if (env->efer & MSR_EFER_LMA) {
1387 hflags |= HF_LMA_MASK;
1390 if ((hflags & HF_LMA_MASK) && (env->segs[R_CS].flags & DESC_L_MASK)) {
1391 hflags |= HF_CS32_MASK | HF_SS32_MASK | HF_CS64_MASK;
1392 } else {
1393 hflags |= (env->segs[R_CS].flags & DESC_B_MASK) >>
1394 (DESC_B_SHIFT - HF_CS32_SHIFT);
1395 hflags |= (env->segs[R_SS].flags & DESC_B_MASK) >>
1396 (DESC_B_SHIFT - HF_SS32_SHIFT);
1397 if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK) ||
1398 !(hflags & HF_CS32_MASK)) {
1399 hflags |= HF_ADDSEG_MASK;
1400 } else {
1401 hflags |= ((env->segs[R_DS].base | env->segs[R_ES].base |
1402 env->segs[R_SS].base) != 0) << HF_ADDSEG_SHIFT;
1405 env->hflags = (env->hflags & HFLAG_COPY_MASK) | hflags;
1407 return 0;
1410 static int kvm_get_msrs(X86CPU *cpu)
1412 CPUX86State *env = &cpu->env;
1413 struct {
1414 struct kvm_msrs info;
1415 struct kvm_msr_entry entries[100];
1416 } msr_data;
1417 struct kvm_msr_entry *msrs = msr_data.entries;
1418 int ret, i, n;
1420 n = 0;
1421 msrs[n++].index = MSR_IA32_SYSENTER_CS;
1422 msrs[n++].index = MSR_IA32_SYSENTER_ESP;
1423 msrs[n++].index = MSR_IA32_SYSENTER_EIP;
1424 msrs[n++].index = MSR_PAT;
1425 if (has_msr_star) {
1426 msrs[n++].index = MSR_STAR;
1428 if (has_msr_hsave_pa) {
1429 msrs[n++].index = MSR_VM_HSAVE_PA;
1431 if (has_msr_tsc_adjust) {
1432 msrs[n++].index = MSR_TSC_ADJUST;
1434 if (has_msr_tsc_deadline) {
1435 msrs[n++].index = MSR_IA32_TSCDEADLINE;
1437 if (has_msr_misc_enable) {
1438 msrs[n++].index = MSR_IA32_MISC_ENABLE;
1440 if (has_msr_feature_control) {
1441 msrs[n++].index = MSR_IA32_FEATURE_CONTROL;
1444 if (!env->tsc_valid) {
1445 msrs[n++].index = MSR_IA32_TSC;
1446 env->tsc_valid = !runstate_is_running();
1449 #ifdef TARGET_X86_64
1450 if (lm_capable_kernel) {
1451 msrs[n++].index = MSR_CSTAR;
1452 msrs[n++].index = MSR_KERNELGSBASE;
1453 msrs[n++].index = MSR_FMASK;
1454 msrs[n++].index = MSR_LSTAR;
1456 #endif
1457 msrs[n++].index = MSR_KVM_SYSTEM_TIME;
1458 msrs[n++].index = MSR_KVM_WALL_CLOCK;
1459 if (has_msr_async_pf_en) {
1460 msrs[n++].index = MSR_KVM_ASYNC_PF_EN;
1462 if (has_msr_pv_eoi_en) {
1463 msrs[n++].index = MSR_KVM_PV_EOI_EN;
1465 if (has_msr_kvm_steal_time) {
1466 msrs[n++].index = MSR_KVM_STEAL_TIME;
1468 if (has_msr_architectural_pmu) {
1469 msrs[n++].index = MSR_CORE_PERF_FIXED_CTR_CTRL;
1470 msrs[n++].index = MSR_CORE_PERF_GLOBAL_CTRL;
1471 msrs[n++].index = MSR_CORE_PERF_GLOBAL_STATUS;
1472 msrs[n++].index = MSR_CORE_PERF_GLOBAL_OVF_CTRL;
1473 for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
1474 msrs[n++].index = MSR_CORE_PERF_FIXED_CTR0 + i;
1476 for (i = 0; i < num_architectural_pmu_counters; i++) {
1477 msrs[n++].index = MSR_P6_PERFCTR0 + i;
1478 msrs[n++].index = MSR_P6_EVNTSEL0 + i;
1482 if (env->mcg_cap) {
1483 msrs[n++].index = MSR_MCG_STATUS;
1484 msrs[n++].index = MSR_MCG_CTL;
1485 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1486 msrs[n++].index = MSR_MC0_CTL + i;
1490 msr_data.info.nmsrs = n;
1491 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
1492 if (ret < 0) {
1493 return ret;
1496 for (i = 0; i < ret; i++) {
1497 uint32_t index = msrs[i].index;
1498 switch (index) {
1499 case MSR_IA32_SYSENTER_CS:
1500 env->sysenter_cs = msrs[i].data;
1501 break;
1502 case MSR_IA32_SYSENTER_ESP:
1503 env->sysenter_esp = msrs[i].data;
1504 break;
1505 case MSR_IA32_SYSENTER_EIP:
1506 env->sysenter_eip = msrs[i].data;
1507 break;
1508 case MSR_PAT:
1509 env->pat = msrs[i].data;
1510 break;
1511 case MSR_STAR:
1512 env->star = msrs[i].data;
1513 break;
1514 #ifdef TARGET_X86_64
1515 case MSR_CSTAR:
1516 env->cstar = msrs[i].data;
1517 break;
1518 case MSR_KERNELGSBASE:
1519 env->kernelgsbase = msrs[i].data;
1520 break;
1521 case MSR_FMASK:
1522 env->fmask = msrs[i].data;
1523 break;
1524 case MSR_LSTAR:
1525 env->lstar = msrs[i].data;
1526 break;
1527 #endif
1528 case MSR_IA32_TSC:
1529 env->tsc = msrs[i].data;
1530 break;
1531 case MSR_TSC_ADJUST:
1532 env->tsc_adjust = msrs[i].data;
1533 break;
1534 case MSR_IA32_TSCDEADLINE:
1535 env->tsc_deadline = msrs[i].data;
1536 break;
1537 case MSR_VM_HSAVE_PA:
1538 env->vm_hsave = msrs[i].data;
1539 break;
1540 case MSR_KVM_SYSTEM_TIME:
1541 env->system_time_msr = msrs[i].data;
1542 break;
1543 case MSR_KVM_WALL_CLOCK:
1544 env->wall_clock_msr = msrs[i].data;
1545 break;
1546 case MSR_MCG_STATUS:
1547 env->mcg_status = msrs[i].data;
1548 break;
1549 case MSR_MCG_CTL:
1550 env->mcg_ctl = msrs[i].data;
1551 break;
1552 case MSR_IA32_MISC_ENABLE:
1553 env->msr_ia32_misc_enable = msrs[i].data;
1554 break;
1555 case MSR_IA32_FEATURE_CONTROL:
1556 env->msr_ia32_feature_control = msrs[i].data;
1557 break;
1558 default:
1559 if (msrs[i].index >= MSR_MC0_CTL &&
1560 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
1561 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
1563 break;
1564 case MSR_KVM_ASYNC_PF_EN:
1565 env->async_pf_en_msr = msrs[i].data;
1566 break;
1567 case MSR_KVM_PV_EOI_EN:
1568 env->pv_eoi_en_msr = msrs[i].data;
1569 break;
1570 case MSR_KVM_STEAL_TIME:
1571 env->steal_time_msr = msrs[i].data;
1572 break;
1573 case MSR_CORE_PERF_FIXED_CTR_CTRL:
1574 env->msr_fixed_ctr_ctrl = msrs[i].data;
1575 break;
1576 case MSR_CORE_PERF_GLOBAL_CTRL:
1577 env->msr_global_ctrl = msrs[i].data;
1578 break;
1579 case MSR_CORE_PERF_GLOBAL_STATUS:
1580 env->msr_global_status = msrs[i].data;
1581 break;
1582 case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
1583 env->msr_global_ovf_ctrl = msrs[i].data;
1584 break;
1585 case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
1586 env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
1587 break;
1588 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
1589 env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
1590 break;
1591 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
1592 env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
1593 break;
1597 return 0;
1600 static int kvm_put_mp_state(X86CPU *cpu)
1602 struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
1604 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
1607 static int kvm_get_mp_state(X86CPU *cpu)
1609 CPUState *cs = CPU(cpu);
1610 CPUX86State *env = &cpu->env;
1611 struct kvm_mp_state mp_state;
1612 int ret;
1614 ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
1615 if (ret < 0) {
1616 return ret;
1618 env->mp_state = mp_state.mp_state;
1619 if (kvm_irqchip_in_kernel()) {
1620 cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
1622 return 0;
1625 static int kvm_get_apic(X86CPU *cpu)
1627 CPUX86State *env = &cpu->env;
1628 DeviceState *apic = env->apic_state;
1629 struct kvm_lapic_state kapic;
1630 int ret;
1632 if (apic && kvm_irqchip_in_kernel()) {
1633 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
1634 if (ret < 0) {
1635 return ret;
1638 kvm_get_apic_state(apic, &kapic);
1640 return 0;
1643 static int kvm_put_apic(X86CPU *cpu)
1645 CPUX86State *env = &cpu->env;
1646 DeviceState *apic = env->apic_state;
1647 struct kvm_lapic_state kapic;
1649 if (apic && kvm_irqchip_in_kernel()) {
1650 kvm_put_apic_state(apic, &kapic);
1652 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_LAPIC, &kapic);
1654 return 0;
1657 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
1659 CPUX86State *env = &cpu->env;
1660 struct kvm_vcpu_events events;
1662 if (!kvm_has_vcpu_events()) {
1663 return 0;
1666 events.exception.injected = (env->exception_injected >= 0);
1667 events.exception.nr = env->exception_injected;
1668 events.exception.has_error_code = env->has_error_code;
1669 events.exception.error_code = env->error_code;
1670 events.exception.pad = 0;
1672 events.interrupt.injected = (env->interrupt_injected >= 0);
1673 events.interrupt.nr = env->interrupt_injected;
1674 events.interrupt.soft = env->soft_interrupt;
1676 events.nmi.injected = env->nmi_injected;
1677 events.nmi.pending = env->nmi_pending;
1678 events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
1679 events.nmi.pad = 0;
1681 events.sipi_vector = env->sipi_vector;
1683 events.flags = 0;
1684 if (level >= KVM_PUT_RESET_STATE) {
1685 events.flags |=
1686 KVM_VCPUEVENT_VALID_NMI_PENDING | KVM_VCPUEVENT_VALID_SIPI_VECTOR;
1689 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
1692 static int kvm_get_vcpu_events(X86CPU *cpu)
1694 CPUX86State *env = &cpu->env;
1695 struct kvm_vcpu_events events;
1696 int ret;
1698 if (!kvm_has_vcpu_events()) {
1699 return 0;
1702 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
1703 if (ret < 0) {
1704 return ret;
1706 env->exception_injected =
1707 events.exception.injected ? events.exception.nr : -1;
1708 env->has_error_code = events.exception.has_error_code;
1709 env->error_code = events.exception.error_code;
1711 env->interrupt_injected =
1712 events.interrupt.injected ? events.interrupt.nr : -1;
1713 env->soft_interrupt = events.interrupt.soft;
1715 env->nmi_injected = events.nmi.injected;
1716 env->nmi_pending = events.nmi.pending;
1717 if (events.nmi.masked) {
1718 env->hflags2 |= HF2_NMI_MASK;
1719 } else {
1720 env->hflags2 &= ~HF2_NMI_MASK;
1723 env->sipi_vector = events.sipi_vector;
1725 return 0;
1728 static int kvm_guest_debug_workarounds(X86CPU *cpu)
1730 CPUState *cs = CPU(cpu);
1731 CPUX86State *env = &cpu->env;
1732 int ret = 0;
1733 unsigned long reinject_trap = 0;
1735 if (!kvm_has_vcpu_events()) {
1736 if (env->exception_injected == 1) {
1737 reinject_trap = KVM_GUESTDBG_INJECT_DB;
1738 } else if (env->exception_injected == 3) {
1739 reinject_trap = KVM_GUESTDBG_INJECT_BP;
1741 env->exception_injected = -1;
1745 * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
1746 * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
1747 * by updating the debug state once again if single-stepping is on.
1748 * Another reason to call kvm_update_guest_debug here is a pending debug
1749 * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
1750 * reinject them via SET_GUEST_DEBUG.
1752 if (reinject_trap ||
1753 (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
1754 ret = kvm_update_guest_debug(cs, reinject_trap);
1756 return ret;
1759 static int kvm_put_debugregs(X86CPU *cpu)
1761 CPUX86State *env = &cpu->env;
1762 struct kvm_debugregs dbgregs;
1763 int i;
1765 if (!kvm_has_debugregs()) {
1766 return 0;
1769 for (i = 0; i < 4; i++) {
1770 dbgregs.db[i] = env->dr[i];
1772 dbgregs.dr6 = env->dr[6];
1773 dbgregs.dr7 = env->dr[7];
1774 dbgregs.flags = 0;
1776 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
1779 static int kvm_get_debugregs(X86CPU *cpu)
1781 CPUX86State *env = &cpu->env;
1782 struct kvm_debugregs dbgregs;
1783 int i, ret;
1785 if (!kvm_has_debugregs()) {
1786 return 0;
1789 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
1790 if (ret < 0) {
1791 return ret;
1793 for (i = 0; i < 4; i++) {
1794 env->dr[i] = dbgregs.db[i];
1796 env->dr[4] = env->dr[6] = dbgregs.dr6;
1797 env->dr[5] = env->dr[7] = dbgregs.dr7;
1799 return 0;
1802 int kvm_arch_put_registers(CPUState *cpu, int level)
1804 X86CPU *x86_cpu = X86_CPU(cpu);
1805 int ret;
1807 assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
1809 ret = kvm_getput_regs(x86_cpu, 1);
1810 if (ret < 0) {
1811 return ret;
1813 ret = kvm_put_xsave(x86_cpu);
1814 if (ret < 0) {
1815 return ret;
1817 ret = kvm_put_xcrs(x86_cpu);
1818 if (ret < 0) {
1819 return ret;
1821 ret = kvm_put_sregs(x86_cpu);
1822 if (ret < 0) {
1823 return ret;
1825 /* must be before kvm_put_msrs */
1826 ret = kvm_inject_mce_oldstyle(x86_cpu);
1827 if (ret < 0) {
1828 return ret;
1830 ret = kvm_put_msrs(x86_cpu, level);
1831 if (ret < 0) {
1832 return ret;
1834 if (level >= KVM_PUT_RESET_STATE) {
1835 ret = kvm_put_mp_state(x86_cpu);
1836 if (ret < 0) {
1837 return ret;
1839 ret = kvm_put_apic(x86_cpu);
1840 if (ret < 0) {
1841 return ret;
1845 ret = kvm_put_tscdeadline_msr(x86_cpu);
1846 if (ret < 0) {
1847 return ret;
1850 ret = kvm_put_vcpu_events(x86_cpu, level);
1851 if (ret < 0) {
1852 return ret;
1854 ret = kvm_put_debugregs(x86_cpu);
1855 if (ret < 0) {
1856 return ret;
1858 /* must be last */
1859 ret = kvm_guest_debug_workarounds(x86_cpu);
1860 if (ret < 0) {
1861 return ret;
1863 return 0;
1866 int kvm_arch_get_registers(CPUState *cs)
1868 X86CPU *cpu = X86_CPU(cs);
1869 int ret;
1871 assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
1873 ret = kvm_getput_regs(cpu, 0);
1874 if (ret < 0) {
1875 return ret;
1877 ret = kvm_get_xsave(cpu);
1878 if (ret < 0) {
1879 return ret;
1881 ret = kvm_get_xcrs(cpu);
1882 if (ret < 0) {
1883 return ret;
1885 ret = kvm_get_sregs(cpu);
1886 if (ret < 0) {
1887 return ret;
1889 ret = kvm_get_msrs(cpu);
1890 if (ret < 0) {
1891 return ret;
1893 ret = kvm_get_mp_state(cpu);
1894 if (ret < 0) {
1895 return ret;
1897 ret = kvm_get_apic(cpu);
1898 if (ret < 0) {
1899 return ret;
1901 ret = kvm_get_vcpu_events(cpu);
1902 if (ret < 0) {
1903 return ret;
1905 ret = kvm_get_debugregs(cpu);
1906 if (ret < 0) {
1907 return ret;
1909 return 0;
1912 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
1914 X86CPU *x86_cpu = X86_CPU(cpu);
1915 CPUX86State *env = &x86_cpu->env;
1916 int ret;
1918 /* Inject NMI */
1919 if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
1920 cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
1921 DPRINTF("injected NMI\n");
1922 ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
1923 if (ret < 0) {
1924 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
1925 strerror(-ret));
1929 if (!kvm_irqchip_in_kernel()) {
1930 /* Force the VCPU out of its inner loop to process any INIT requests
1931 * or pending TPR access reports. */
1932 if (cpu->interrupt_request &
1933 (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
1934 cpu->exit_request = 1;
1937 /* Try to inject an interrupt if the guest can accept it */
1938 if (run->ready_for_interrupt_injection &&
1939 (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
1940 (env->eflags & IF_MASK)) {
1941 int irq;
1943 cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
1944 irq = cpu_get_pic_interrupt(env);
1945 if (irq >= 0) {
1946 struct kvm_interrupt intr;
1948 intr.irq = irq;
1949 DPRINTF("injected interrupt %d\n", irq);
1950 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
1951 if (ret < 0) {
1952 fprintf(stderr,
1953 "KVM: injection failed, interrupt lost (%s)\n",
1954 strerror(-ret));
1959 /* If we have an interrupt but the guest is not ready to receive an
1960 * interrupt, request an interrupt window exit. This will
1961 * cause a return to userspace as soon as the guest is ready to
1962 * receive interrupts. */
1963 if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
1964 run->request_interrupt_window = 1;
1965 } else {
1966 run->request_interrupt_window = 0;
1969 DPRINTF("setting tpr\n");
1970 run->cr8 = cpu_get_apic_tpr(env->apic_state);
1974 void kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
1976 X86CPU *x86_cpu = X86_CPU(cpu);
1977 CPUX86State *env = &x86_cpu->env;
1979 if (run->if_flag) {
1980 env->eflags |= IF_MASK;
1981 } else {
1982 env->eflags &= ~IF_MASK;
1984 cpu_set_apic_tpr(env->apic_state, run->cr8);
1985 cpu_set_apic_base(env->apic_state, run->apic_base);
1988 int kvm_arch_process_async_events(CPUState *cs)
1990 X86CPU *cpu = X86_CPU(cs);
1991 CPUX86State *env = &cpu->env;
1993 if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
1994 /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
1995 assert(env->mcg_cap);
1997 cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
1999 kvm_cpu_synchronize_state(cs);
2001 if (env->exception_injected == EXCP08_DBLE) {
2002 /* this means triple fault */
2003 qemu_system_reset_request();
2004 cs->exit_request = 1;
2005 return 0;
2007 env->exception_injected = EXCP12_MCHK;
2008 env->has_error_code = 0;
2010 cs->halted = 0;
2011 if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
2012 env->mp_state = KVM_MP_STATE_RUNNABLE;
2016 if (kvm_irqchip_in_kernel()) {
2017 return 0;
2020 if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
2021 cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
2022 apic_poll_irq(env->apic_state);
2024 if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2025 (env->eflags & IF_MASK)) ||
2026 (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
2027 cs->halted = 0;
2029 if (cs->interrupt_request & CPU_INTERRUPT_INIT) {
2030 kvm_cpu_synchronize_state(cs);
2031 do_cpu_init(cpu);
2033 if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
2034 kvm_cpu_synchronize_state(cs);
2035 do_cpu_sipi(cpu);
2037 if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
2038 cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
2039 kvm_cpu_synchronize_state(cs);
2040 apic_handle_tpr_access_report(env->apic_state, env->eip,
2041 env->tpr_access_type);
2044 return cs->halted;
2047 static int kvm_handle_halt(X86CPU *cpu)
2049 CPUState *cs = CPU(cpu);
2050 CPUX86State *env = &cpu->env;
2052 if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2053 (env->eflags & IF_MASK)) &&
2054 !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
2055 cs->halted = 1;
2056 return EXCP_HLT;
2059 return 0;
2062 static int kvm_handle_tpr_access(X86CPU *cpu)
2064 CPUX86State *env = &cpu->env;
2065 CPUState *cs = CPU(cpu);
2066 struct kvm_run *run = cs->kvm_run;
2068 apic_handle_tpr_access_report(env->apic_state, run->tpr_access.rip,
2069 run->tpr_access.is_write ? TPR_ACCESS_WRITE
2070 : TPR_ACCESS_READ);
2071 return 1;
2074 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2076 static const uint8_t int3 = 0xcc;
2078 if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
2079 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
2080 return -EINVAL;
2082 return 0;
2085 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2087 uint8_t int3;
2089 if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
2090 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
2091 return -EINVAL;
2093 return 0;
2096 static struct {
2097 target_ulong addr;
2098 int len;
2099 int type;
2100 } hw_breakpoint[4];
2102 static int nb_hw_breakpoint;
2104 static int find_hw_breakpoint(target_ulong addr, int len, int type)
2106 int n;
2108 for (n = 0; n < nb_hw_breakpoint; n++) {
2109 if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
2110 (hw_breakpoint[n].len == len || len == -1)) {
2111 return n;
2114 return -1;
2117 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
2118 target_ulong len, int type)
2120 switch (type) {
2121 case GDB_BREAKPOINT_HW:
2122 len = 1;
2123 break;
2124 case GDB_WATCHPOINT_WRITE:
2125 case GDB_WATCHPOINT_ACCESS:
2126 switch (len) {
2127 case 1:
2128 break;
2129 case 2:
2130 case 4:
2131 case 8:
2132 if (addr & (len - 1)) {
2133 return -EINVAL;
2135 break;
2136 default:
2137 return -EINVAL;
2139 break;
2140 default:
2141 return -ENOSYS;
2144 if (nb_hw_breakpoint == 4) {
2145 return -ENOBUFS;
2147 if (find_hw_breakpoint(addr, len, type) >= 0) {
2148 return -EEXIST;
2150 hw_breakpoint[nb_hw_breakpoint].addr = addr;
2151 hw_breakpoint[nb_hw_breakpoint].len = len;
2152 hw_breakpoint[nb_hw_breakpoint].type = type;
2153 nb_hw_breakpoint++;
2155 return 0;
2158 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
2159 target_ulong len, int type)
2161 int n;
2163 n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
2164 if (n < 0) {
2165 return -ENOENT;
2167 nb_hw_breakpoint--;
2168 hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
2170 return 0;
2173 void kvm_arch_remove_all_hw_breakpoints(void)
2175 nb_hw_breakpoint = 0;
2178 static CPUWatchpoint hw_watchpoint;
2180 static int kvm_handle_debug(X86CPU *cpu,
2181 struct kvm_debug_exit_arch *arch_info)
2183 CPUState *cs = CPU(cpu);
2184 CPUX86State *env = &cpu->env;
2185 int ret = 0;
2186 int n;
2188 if (arch_info->exception == 1) {
2189 if (arch_info->dr6 & (1 << 14)) {
2190 if (cs->singlestep_enabled) {
2191 ret = EXCP_DEBUG;
2193 } else {
2194 for (n = 0; n < 4; n++) {
2195 if (arch_info->dr6 & (1 << n)) {
2196 switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
2197 case 0x0:
2198 ret = EXCP_DEBUG;
2199 break;
2200 case 0x1:
2201 ret = EXCP_DEBUG;
2202 env->watchpoint_hit = &hw_watchpoint;
2203 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
2204 hw_watchpoint.flags = BP_MEM_WRITE;
2205 break;
2206 case 0x3:
2207 ret = EXCP_DEBUG;
2208 env->watchpoint_hit = &hw_watchpoint;
2209 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
2210 hw_watchpoint.flags = BP_MEM_ACCESS;
2211 break;
2216 } else if (kvm_find_sw_breakpoint(CPU(cpu), arch_info->pc)) {
2217 ret = EXCP_DEBUG;
2219 if (ret == 0) {
2220 cpu_synchronize_state(CPU(cpu));
2221 assert(env->exception_injected == -1);
2223 /* pass to guest */
2224 env->exception_injected = arch_info->exception;
2225 env->has_error_code = 0;
2228 return ret;
2231 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
2233 const uint8_t type_code[] = {
2234 [GDB_BREAKPOINT_HW] = 0x0,
2235 [GDB_WATCHPOINT_WRITE] = 0x1,
2236 [GDB_WATCHPOINT_ACCESS] = 0x3
2238 const uint8_t len_code[] = {
2239 [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
2241 int n;
2243 if (kvm_sw_breakpoints_active(cpu)) {
2244 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
2246 if (nb_hw_breakpoint > 0) {
2247 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
2248 dbg->arch.debugreg[7] = 0x0600;
2249 for (n = 0; n < nb_hw_breakpoint; n++) {
2250 dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
2251 dbg->arch.debugreg[7] |= (2 << (n * 2)) |
2252 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
2253 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
2258 static bool host_supports_vmx(void)
2260 uint32_t ecx, unused;
2262 host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
2263 return ecx & CPUID_EXT_VMX;
2266 #define VMX_INVALID_GUEST_STATE 0x80000021
2268 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
2270 X86CPU *cpu = X86_CPU(cs);
2271 uint64_t code;
2272 int ret;
2274 switch (run->exit_reason) {
2275 case KVM_EXIT_HLT:
2276 DPRINTF("handle_hlt\n");
2277 ret = kvm_handle_halt(cpu);
2278 break;
2279 case KVM_EXIT_SET_TPR:
2280 ret = 0;
2281 break;
2282 case KVM_EXIT_TPR_ACCESS:
2283 ret = kvm_handle_tpr_access(cpu);
2284 break;
2285 case KVM_EXIT_FAIL_ENTRY:
2286 code = run->fail_entry.hardware_entry_failure_reason;
2287 fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
2288 code);
2289 if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
2290 fprintf(stderr,
2291 "\nIf you're running a guest on an Intel machine without "
2292 "unrestricted mode\n"
2293 "support, the failure can be most likely due to the guest "
2294 "entering an invalid\n"
2295 "state for Intel VT. For example, the guest maybe running "
2296 "in big real mode\n"
2297 "which is not supported on less recent Intel processors."
2298 "\n\n");
2300 ret = -1;
2301 break;
2302 case KVM_EXIT_EXCEPTION:
2303 fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
2304 run->ex.exception, run->ex.error_code);
2305 ret = -1;
2306 break;
2307 case KVM_EXIT_DEBUG:
2308 DPRINTF("kvm_exit_debug\n");
2309 ret = kvm_handle_debug(cpu, &run->debug.arch);
2310 break;
2311 default:
2312 fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
2313 ret = -1;
2314 break;
2317 return ret;
2320 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
2322 X86CPU *cpu = X86_CPU(cs);
2323 CPUX86State *env = &cpu->env;
2325 kvm_cpu_synchronize_state(cs);
2326 return !(env->cr[0] & CR0_PE_MASK) ||
2327 ((env->segs[R_CS].selector & 3) != 3);
2330 void kvm_arch_init_irq_routing(KVMState *s)
2332 if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
2333 /* If kernel can't do irq routing, interrupt source
2334 * override 0->2 cannot be set up as required by HPET.
2335 * So we have to disable it.
2337 no_hpet = 1;
2339 /* We know at this point that we're using the in-kernel
2340 * irqchip, so we can use irqfds, and on x86 we know
2341 * we can use msi via irqfd and GSI routing.
2343 kvm_irqfds_allowed = true;
2344 kvm_msi_via_irqfd_allowed = true;
2345 kvm_gsi_routing_allowed = true;
2348 /* Classic KVM device assignment interface. Will remain x86 only. */
2349 int kvm_device_pci_assign(KVMState *s, PCIHostDeviceAddress *dev_addr,
2350 uint32_t flags, uint32_t *dev_id)
2352 struct kvm_assigned_pci_dev dev_data = {
2353 .segnr = dev_addr->domain,
2354 .busnr = dev_addr->bus,
2355 .devfn = PCI_DEVFN(dev_addr->slot, dev_addr->function),
2356 .flags = flags,
2358 int ret;
2360 dev_data.assigned_dev_id =
2361 (dev_addr->domain << 16) | (dev_addr->bus << 8) | dev_data.devfn;
2363 ret = kvm_vm_ioctl(s, KVM_ASSIGN_PCI_DEVICE, &dev_data);
2364 if (ret < 0) {
2365 return ret;
2368 *dev_id = dev_data.assigned_dev_id;
2370 return 0;
2373 int kvm_device_pci_deassign(KVMState *s, uint32_t dev_id)
2375 struct kvm_assigned_pci_dev dev_data = {
2376 .assigned_dev_id = dev_id,
2379 return kvm_vm_ioctl(s, KVM_DEASSIGN_PCI_DEVICE, &dev_data);
2382 static int kvm_assign_irq_internal(KVMState *s, uint32_t dev_id,
2383 uint32_t irq_type, uint32_t guest_irq)
2385 struct kvm_assigned_irq assigned_irq = {
2386 .assigned_dev_id = dev_id,
2387 .guest_irq = guest_irq,
2388 .flags = irq_type,
2391 if (kvm_check_extension(s, KVM_CAP_ASSIGN_DEV_IRQ)) {
2392 return kvm_vm_ioctl(s, KVM_ASSIGN_DEV_IRQ, &assigned_irq);
2393 } else {
2394 return kvm_vm_ioctl(s, KVM_ASSIGN_IRQ, &assigned_irq);
2398 int kvm_device_intx_assign(KVMState *s, uint32_t dev_id, bool use_host_msi,
2399 uint32_t guest_irq)
2401 uint32_t irq_type = KVM_DEV_IRQ_GUEST_INTX |
2402 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX);
2404 return kvm_assign_irq_internal(s, dev_id, irq_type, guest_irq);
2407 int kvm_device_intx_set_mask(KVMState *s, uint32_t dev_id, bool masked)
2409 struct kvm_assigned_pci_dev dev_data = {
2410 .assigned_dev_id = dev_id,
2411 .flags = masked ? KVM_DEV_ASSIGN_MASK_INTX : 0,
2414 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_INTX_MASK, &dev_data);
2417 static int kvm_deassign_irq_internal(KVMState *s, uint32_t dev_id,
2418 uint32_t type)
2420 struct kvm_assigned_irq assigned_irq = {
2421 .assigned_dev_id = dev_id,
2422 .flags = type,
2425 return kvm_vm_ioctl(s, KVM_DEASSIGN_DEV_IRQ, &assigned_irq);
2428 int kvm_device_intx_deassign(KVMState *s, uint32_t dev_id, bool use_host_msi)
2430 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_INTX |
2431 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX));
2434 int kvm_device_msi_assign(KVMState *s, uint32_t dev_id, int virq)
2436 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSI |
2437 KVM_DEV_IRQ_GUEST_MSI, virq);
2440 int kvm_device_msi_deassign(KVMState *s, uint32_t dev_id)
2442 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSI |
2443 KVM_DEV_IRQ_HOST_MSI);
2446 bool kvm_device_msix_supported(KVMState *s)
2448 /* The kernel lacks a corresponding KVM_CAP, so we probe by calling
2449 * KVM_ASSIGN_SET_MSIX_NR with an invalid parameter. */
2450 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, NULL) == -EFAULT;
2453 int kvm_device_msix_init_vectors(KVMState *s, uint32_t dev_id,
2454 uint32_t nr_vectors)
2456 struct kvm_assigned_msix_nr msix_nr = {
2457 .assigned_dev_id = dev_id,
2458 .entry_nr = nr_vectors,
2461 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, &msix_nr);
2464 int kvm_device_msix_set_vector(KVMState *s, uint32_t dev_id, uint32_t vector,
2465 int virq)
2467 struct kvm_assigned_msix_entry msix_entry = {
2468 .assigned_dev_id = dev_id,
2469 .gsi = virq,
2470 .entry = vector,
2473 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_ENTRY, &msix_entry);
2476 int kvm_device_msix_assign(KVMState *s, uint32_t dev_id)
2478 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSIX |
2479 KVM_DEV_IRQ_GUEST_MSIX, 0);
2482 int kvm_device_msix_deassign(KVMState *s, uint32_t dev_id)
2484 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSIX |
2485 KVM_DEV_IRQ_HOST_MSIX);