qemu-gdb: extract parts of "qemu coroutine" implementation
[qemu.git] / target-i386 / kvm.c
blob64046cb69d614d52cf5eb02a827c1ff48d574dd4
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_int.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 "qemu/error-report.h"
32 #include "hw/i386/pc.h"
33 #include "hw/i386/apic.h"
34 #include "hw/i386/apic_internal.h"
35 #include "hw/i386/apic-msidef.h"
36 #include "exec/ioport.h"
37 #include "standard-headers/asm-x86/hyperv.h"
38 #include "hw/pci/pci.h"
39 #include "migration/migration.h"
40 #include "exec/memattrs.h"
42 //#define DEBUG_KVM
44 #ifdef DEBUG_KVM
45 #define DPRINTF(fmt, ...) \
46 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
47 #else
48 #define DPRINTF(fmt, ...) \
49 do { } while (0)
50 #endif
52 #define MSR_KVM_WALL_CLOCK 0x11
53 #define MSR_KVM_SYSTEM_TIME 0x12
55 #ifndef BUS_MCEERR_AR
56 #define BUS_MCEERR_AR 4
57 #endif
58 #ifndef BUS_MCEERR_AO
59 #define BUS_MCEERR_AO 5
60 #endif
62 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
63 KVM_CAP_INFO(SET_TSS_ADDR),
64 KVM_CAP_INFO(EXT_CPUID),
65 KVM_CAP_INFO(MP_STATE),
66 KVM_CAP_LAST_INFO
69 static bool has_msr_star;
70 static bool has_msr_hsave_pa;
71 static bool has_msr_tsc_aux;
72 static bool has_msr_tsc_adjust;
73 static bool has_msr_tsc_deadline;
74 static bool has_msr_feature_control;
75 static bool has_msr_async_pf_en;
76 static bool has_msr_pv_eoi_en;
77 static bool has_msr_misc_enable;
78 static bool has_msr_smbase;
79 static bool has_msr_bndcfgs;
80 static bool has_msr_kvm_steal_time;
81 static int lm_capable_kernel;
82 static bool has_msr_hv_hypercall;
83 static bool has_msr_hv_vapic;
84 static bool has_msr_hv_tsc;
85 static bool has_msr_hv_crash;
86 static bool has_msr_hv_reset;
87 static bool has_msr_hv_vpindex;
88 static bool has_msr_hv_runtime;
89 static bool has_msr_mtrr;
90 static bool has_msr_xss;
92 static bool has_msr_architectural_pmu;
93 static uint32_t num_architectural_pmu_counters;
95 static int has_xsave;
96 static int has_xcrs;
97 static int has_pit_state2;
99 int kvm_has_pit_state2(void)
101 return has_pit_state2;
104 bool kvm_has_smm(void)
106 return kvm_check_extension(kvm_state, KVM_CAP_X86_SMM);
109 bool kvm_allows_irq0_override(void)
111 return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
114 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
116 struct kvm_cpuid2 *cpuid;
117 int r, size;
119 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
120 cpuid = g_malloc0(size);
121 cpuid->nent = max;
122 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
123 if (r == 0 && cpuid->nent >= max) {
124 r = -E2BIG;
126 if (r < 0) {
127 if (r == -E2BIG) {
128 g_free(cpuid);
129 return NULL;
130 } else {
131 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
132 strerror(-r));
133 exit(1);
136 return cpuid;
139 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
140 * for all entries.
142 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
144 struct kvm_cpuid2 *cpuid;
145 int max = 1;
146 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
147 max *= 2;
149 return cpuid;
152 static const struct kvm_para_features {
153 int cap;
154 int feature;
155 } para_features[] = {
156 { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
157 { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
158 { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
159 { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
162 static int get_para_features(KVMState *s)
164 int i, features = 0;
166 for (i = 0; i < ARRAY_SIZE(para_features); i++) {
167 if (kvm_check_extension(s, para_features[i].cap)) {
168 features |= (1 << para_features[i].feature);
172 return features;
176 /* Returns the value for a specific register on the cpuid entry
178 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
180 uint32_t ret = 0;
181 switch (reg) {
182 case R_EAX:
183 ret = entry->eax;
184 break;
185 case R_EBX:
186 ret = entry->ebx;
187 break;
188 case R_ECX:
189 ret = entry->ecx;
190 break;
191 case R_EDX:
192 ret = entry->edx;
193 break;
195 return ret;
198 /* Find matching entry for function/index on kvm_cpuid2 struct
200 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
201 uint32_t function,
202 uint32_t index)
204 int i;
205 for (i = 0; i < cpuid->nent; ++i) {
206 if (cpuid->entries[i].function == function &&
207 cpuid->entries[i].index == index) {
208 return &cpuid->entries[i];
211 /* not found: */
212 return NULL;
215 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
216 uint32_t index, int reg)
218 struct kvm_cpuid2 *cpuid;
219 uint32_t ret = 0;
220 uint32_t cpuid_1_edx;
221 bool found = false;
223 cpuid = get_supported_cpuid(s);
225 struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
226 if (entry) {
227 found = true;
228 ret = cpuid_entry_get_reg(entry, reg);
231 /* Fixups for the data returned by KVM, below */
233 if (function == 1 && reg == R_EDX) {
234 /* KVM before 2.6.30 misreports the following features */
235 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
236 } else if (function == 1 && reg == R_ECX) {
237 /* We can set the hypervisor flag, even if KVM does not return it on
238 * GET_SUPPORTED_CPUID
240 ret |= CPUID_EXT_HYPERVISOR;
241 /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
242 * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
243 * and the irqchip is in the kernel.
245 if (kvm_irqchip_in_kernel() &&
246 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
247 ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
250 /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
251 * without the in-kernel irqchip
253 if (!kvm_irqchip_in_kernel()) {
254 ret &= ~CPUID_EXT_X2APIC;
256 } else if (function == 6 && reg == R_EAX) {
257 ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
258 } else if (function == 0x80000001 && reg == R_EDX) {
259 /* On Intel, kvm returns cpuid according to the Intel spec,
260 * so add missing bits according to the AMD spec:
262 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
263 ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
266 g_free(cpuid);
268 /* fallback for older kernels */
269 if ((function == KVM_CPUID_FEATURES) && !found) {
270 ret = get_para_features(s);
273 return ret;
276 typedef struct HWPoisonPage {
277 ram_addr_t ram_addr;
278 QLIST_ENTRY(HWPoisonPage) list;
279 } HWPoisonPage;
281 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
282 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
284 static void kvm_unpoison_all(void *param)
286 HWPoisonPage *page, *next_page;
288 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
289 QLIST_REMOVE(page, list);
290 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
291 g_free(page);
295 static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
297 HWPoisonPage *page;
299 QLIST_FOREACH(page, &hwpoison_page_list, list) {
300 if (page->ram_addr == ram_addr) {
301 return;
304 page = g_new(HWPoisonPage, 1);
305 page->ram_addr = ram_addr;
306 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
309 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
310 int *max_banks)
312 int r;
314 r = kvm_check_extension(s, KVM_CAP_MCE);
315 if (r > 0) {
316 *max_banks = r;
317 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
319 return -ENOSYS;
322 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
324 CPUX86State *env = &cpu->env;
325 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
326 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
327 uint64_t mcg_status = MCG_STATUS_MCIP;
329 if (code == BUS_MCEERR_AR) {
330 status |= MCI_STATUS_AR | 0x134;
331 mcg_status |= MCG_STATUS_EIPV;
332 } else {
333 status |= 0xc0;
334 mcg_status |= MCG_STATUS_RIPV;
336 cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
337 (MCM_ADDR_PHYS << 6) | 0xc,
338 cpu_x86_support_mca_broadcast(env) ?
339 MCE_INJECT_BROADCAST : 0);
342 static void hardware_memory_error(void)
344 fprintf(stderr, "Hardware memory error!\n");
345 exit(1);
348 int kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
350 X86CPU *cpu = X86_CPU(c);
351 CPUX86State *env = &cpu->env;
352 ram_addr_t ram_addr;
353 hwaddr paddr;
355 if ((env->mcg_cap & MCG_SER_P) && addr
356 && (code == BUS_MCEERR_AR || code == BUS_MCEERR_AO)) {
357 if (qemu_ram_addr_from_host(addr, &ram_addr) == NULL ||
358 !kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
359 fprintf(stderr, "Hardware memory error for memory used by "
360 "QEMU itself instead of guest system!\n");
361 /* Hope we are lucky for AO MCE */
362 if (code == BUS_MCEERR_AO) {
363 return 0;
364 } else {
365 hardware_memory_error();
368 kvm_hwpoison_page_add(ram_addr);
369 kvm_mce_inject(cpu, paddr, code);
370 } else {
371 if (code == BUS_MCEERR_AO) {
372 return 0;
373 } else if (code == BUS_MCEERR_AR) {
374 hardware_memory_error();
375 } else {
376 return 1;
379 return 0;
382 int kvm_arch_on_sigbus(int code, void *addr)
384 X86CPU *cpu = X86_CPU(first_cpu);
386 if ((cpu->env.mcg_cap & MCG_SER_P) && addr && code == BUS_MCEERR_AO) {
387 ram_addr_t ram_addr;
388 hwaddr paddr;
390 /* Hope we are lucky for AO MCE */
391 if (qemu_ram_addr_from_host(addr, &ram_addr) == NULL ||
392 !kvm_physical_memory_addr_from_host(first_cpu->kvm_state,
393 addr, &paddr)) {
394 fprintf(stderr, "Hardware memory error for memory used by "
395 "QEMU itself instead of guest system!: %p\n", addr);
396 return 0;
398 kvm_hwpoison_page_add(ram_addr);
399 kvm_mce_inject(X86_CPU(first_cpu), paddr, code);
400 } else {
401 if (code == BUS_MCEERR_AO) {
402 return 0;
403 } else if (code == BUS_MCEERR_AR) {
404 hardware_memory_error();
405 } else {
406 return 1;
409 return 0;
412 static int kvm_inject_mce_oldstyle(X86CPU *cpu)
414 CPUX86State *env = &cpu->env;
416 if (!kvm_has_vcpu_events() && env->exception_injected == EXCP12_MCHK) {
417 unsigned int bank, bank_num = env->mcg_cap & 0xff;
418 struct kvm_x86_mce mce;
420 env->exception_injected = -1;
423 * There must be at least one bank in use if an MCE is pending.
424 * Find it and use its values for the event injection.
426 for (bank = 0; bank < bank_num; bank++) {
427 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
428 break;
431 assert(bank < bank_num);
433 mce.bank = bank;
434 mce.status = env->mce_banks[bank * 4 + 1];
435 mce.mcg_status = env->mcg_status;
436 mce.addr = env->mce_banks[bank * 4 + 2];
437 mce.misc = env->mce_banks[bank * 4 + 3];
439 return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
441 return 0;
444 static void cpu_update_state(void *opaque, int running, RunState state)
446 CPUX86State *env = opaque;
448 if (running) {
449 env->tsc_valid = false;
453 unsigned long kvm_arch_vcpu_id(CPUState *cs)
455 X86CPU *cpu = X86_CPU(cs);
456 return cpu->apic_id;
459 #ifndef KVM_CPUID_SIGNATURE_NEXT
460 #define KVM_CPUID_SIGNATURE_NEXT 0x40000100
461 #endif
463 static bool hyperv_hypercall_available(X86CPU *cpu)
465 return cpu->hyperv_vapic ||
466 (cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY);
469 static bool hyperv_enabled(X86CPU *cpu)
471 CPUState *cs = CPU(cpu);
472 return kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0 &&
473 (hyperv_hypercall_available(cpu) ||
474 cpu->hyperv_time ||
475 cpu->hyperv_relaxed_timing ||
476 cpu->hyperv_crash ||
477 cpu->hyperv_reset ||
478 cpu->hyperv_vpindex ||
479 cpu->hyperv_runtime);
482 static Error *invtsc_mig_blocker;
484 #define KVM_MAX_CPUID_ENTRIES 100
486 int kvm_arch_init_vcpu(CPUState *cs)
488 struct {
489 struct kvm_cpuid2 cpuid;
490 struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
491 } QEMU_PACKED cpuid_data;
492 X86CPU *cpu = X86_CPU(cs);
493 CPUX86State *env = &cpu->env;
494 uint32_t limit, i, j, cpuid_i;
495 uint32_t unused;
496 struct kvm_cpuid_entry2 *c;
497 uint32_t signature[3];
498 int kvm_base = KVM_CPUID_SIGNATURE;
499 int r;
501 memset(&cpuid_data, 0, sizeof(cpuid_data));
503 cpuid_i = 0;
505 /* Paravirtualization CPUIDs */
506 if (hyperv_enabled(cpu)) {
507 c = &cpuid_data.entries[cpuid_i++];
508 c->function = HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
509 if (!cpu->hyperv_vendor_id) {
510 memcpy(signature, "Microsoft Hv", 12);
511 } else {
512 size_t len = strlen(cpu->hyperv_vendor_id);
514 if (len > 12) {
515 error_report("hv-vendor-id truncated to 12 characters");
516 len = 12;
518 memset(signature, 0, 12);
519 memcpy(signature, cpu->hyperv_vendor_id, len);
521 c->eax = HYPERV_CPUID_MIN;
522 c->ebx = signature[0];
523 c->ecx = signature[1];
524 c->edx = signature[2];
526 c = &cpuid_data.entries[cpuid_i++];
527 c->function = HYPERV_CPUID_INTERFACE;
528 memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
529 c->eax = signature[0];
530 c->ebx = 0;
531 c->ecx = 0;
532 c->edx = 0;
534 c = &cpuid_data.entries[cpuid_i++];
535 c->function = HYPERV_CPUID_VERSION;
536 c->eax = 0x00001bbc;
537 c->ebx = 0x00060001;
539 c = &cpuid_data.entries[cpuid_i++];
540 c->function = HYPERV_CPUID_FEATURES;
541 if (cpu->hyperv_relaxed_timing) {
542 c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
544 if (cpu->hyperv_vapic) {
545 c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
546 c->eax |= HV_X64_MSR_APIC_ACCESS_AVAILABLE;
547 has_msr_hv_vapic = true;
549 if (cpu->hyperv_time &&
550 kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) > 0) {
551 c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
552 c->eax |= HV_X64_MSR_TIME_REF_COUNT_AVAILABLE;
553 c->eax |= 0x200;
554 has_msr_hv_tsc = true;
556 if (cpu->hyperv_crash && has_msr_hv_crash) {
557 c->edx |= HV_X64_GUEST_CRASH_MSR_AVAILABLE;
559 if (cpu->hyperv_reset && has_msr_hv_reset) {
560 c->eax |= HV_X64_MSR_RESET_AVAILABLE;
562 if (cpu->hyperv_vpindex && has_msr_hv_vpindex) {
563 c->eax |= HV_X64_MSR_VP_INDEX_AVAILABLE;
565 if (cpu->hyperv_runtime && has_msr_hv_runtime) {
566 c->eax |= HV_X64_MSR_VP_RUNTIME_AVAILABLE;
568 c = &cpuid_data.entries[cpuid_i++];
569 c->function = HYPERV_CPUID_ENLIGHTMENT_INFO;
570 if (cpu->hyperv_relaxed_timing) {
571 c->eax |= HV_X64_RELAXED_TIMING_RECOMMENDED;
573 if (has_msr_hv_vapic) {
574 c->eax |= HV_X64_APIC_ACCESS_RECOMMENDED;
576 c->ebx = cpu->hyperv_spinlock_attempts;
578 c = &cpuid_data.entries[cpuid_i++];
579 c->function = HYPERV_CPUID_IMPLEMENT_LIMITS;
580 c->eax = 0x40;
581 c->ebx = 0x40;
583 kvm_base = KVM_CPUID_SIGNATURE_NEXT;
584 has_msr_hv_hypercall = true;
587 if (cpu->expose_kvm) {
588 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
589 c = &cpuid_data.entries[cpuid_i++];
590 c->function = KVM_CPUID_SIGNATURE | kvm_base;
591 c->eax = KVM_CPUID_FEATURES | kvm_base;
592 c->ebx = signature[0];
593 c->ecx = signature[1];
594 c->edx = signature[2];
596 c = &cpuid_data.entries[cpuid_i++];
597 c->function = KVM_CPUID_FEATURES | kvm_base;
598 c->eax = env->features[FEAT_KVM];
600 has_msr_async_pf_en = c->eax & (1 << KVM_FEATURE_ASYNC_PF);
602 has_msr_pv_eoi_en = c->eax & (1 << KVM_FEATURE_PV_EOI);
604 has_msr_kvm_steal_time = c->eax & (1 << KVM_FEATURE_STEAL_TIME);
607 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
609 for (i = 0; i <= limit; i++) {
610 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
611 fprintf(stderr, "unsupported level value: 0x%x\n", limit);
612 abort();
614 c = &cpuid_data.entries[cpuid_i++];
616 switch (i) {
617 case 2: {
618 /* Keep reading function 2 till all the input is received */
619 int times;
621 c->function = i;
622 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
623 KVM_CPUID_FLAG_STATE_READ_NEXT;
624 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
625 times = c->eax & 0xff;
627 for (j = 1; j < times; ++j) {
628 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
629 fprintf(stderr, "cpuid_data is full, no space for "
630 "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
631 abort();
633 c = &cpuid_data.entries[cpuid_i++];
634 c->function = i;
635 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
636 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
638 break;
640 case 4:
641 case 0xb:
642 case 0xd:
643 for (j = 0; ; j++) {
644 if (i == 0xd && j == 64) {
645 break;
647 c->function = i;
648 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
649 c->index = j;
650 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
652 if (i == 4 && c->eax == 0) {
653 break;
655 if (i == 0xb && !(c->ecx & 0xff00)) {
656 break;
658 if (i == 0xd && c->eax == 0) {
659 continue;
661 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
662 fprintf(stderr, "cpuid_data is full, no space for "
663 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
664 abort();
666 c = &cpuid_data.entries[cpuid_i++];
668 break;
669 default:
670 c->function = i;
671 c->flags = 0;
672 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
673 break;
677 if (limit >= 0x0a) {
678 uint32_t ver;
680 cpu_x86_cpuid(env, 0x0a, 0, &ver, &unused, &unused, &unused);
681 if ((ver & 0xff) > 0) {
682 has_msr_architectural_pmu = true;
683 num_architectural_pmu_counters = (ver & 0xff00) >> 8;
685 /* Shouldn't be more than 32, since that's the number of bits
686 * available in EBX to tell us _which_ counters are available.
687 * Play it safe.
689 if (num_architectural_pmu_counters > MAX_GP_COUNTERS) {
690 num_architectural_pmu_counters = MAX_GP_COUNTERS;
695 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
697 for (i = 0x80000000; i <= limit; i++) {
698 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
699 fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
700 abort();
702 c = &cpuid_data.entries[cpuid_i++];
704 c->function = i;
705 c->flags = 0;
706 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
709 /* Call Centaur's CPUID instructions they are supported. */
710 if (env->cpuid_xlevel2 > 0) {
711 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
713 for (i = 0xC0000000; i <= limit; i++) {
714 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
715 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
716 abort();
718 c = &cpuid_data.entries[cpuid_i++];
720 c->function = i;
721 c->flags = 0;
722 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
726 cpuid_data.cpuid.nent = cpuid_i;
728 if (((env->cpuid_version >> 8)&0xF) >= 6
729 && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
730 (CPUID_MCE | CPUID_MCA)
731 && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
732 uint64_t mcg_cap;
733 int banks;
734 int ret;
736 ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
737 if (ret < 0) {
738 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
739 return ret;
742 if (banks > MCE_BANKS_DEF) {
743 banks = MCE_BANKS_DEF;
745 mcg_cap &= MCE_CAP_DEF;
746 mcg_cap |= banks;
747 ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &mcg_cap);
748 if (ret < 0) {
749 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
750 return ret;
753 env->mcg_cap = mcg_cap;
756 qemu_add_vm_change_state_handler(cpu_update_state, env);
758 c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
759 if (c) {
760 has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
761 !!(c->ecx & CPUID_EXT_SMX);
764 c = cpuid_find_entry(&cpuid_data.cpuid, 0x80000007, 0);
765 if (c && (c->edx & 1<<8) && invtsc_mig_blocker == NULL) {
766 /* for migration */
767 error_setg(&invtsc_mig_blocker,
768 "State blocked by non-migratable CPU device"
769 " (invtsc flag)");
770 migrate_add_blocker(invtsc_mig_blocker);
771 /* for savevm */
772 vmstate_x86_cpu.unmigratable = 1;
775 cpuid_data.cpuid.padding = 0;
776 r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
777 if (r) {
778 return r;
781 r = kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL);
782 if (r && env->tsc_khz) {
783 r = kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz);
784 if (r < 0) {
785 fprintf(stderr, "KVM_SET_TSC_KHZ failed\n");
786 return r;
790 if (has_xsave) {
791 env->kvm_xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
794 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
795 has_msr_mtrr = true;
798 return 0;
801 void kvm_arch_reset_vcpu(X86CPU *cpu)
803 CPUX86State *env = &cpu->env;
805 env->exception_injected = -1;
806 env->interrupt_injected = -1;
807 env->xcr0 = 1;
808 if (kvm_irqchip_in_kernel()) {
809 env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
810 KVM_MP_STATE_UNINITIALIZED;
811 } else {
812 env->mp_state = KVM_MP_STATE_RUNNABLE;
816 void kvm_arch_do_init_vcpu(X86CPU *cpu)
818 CPUX86State *env = &cpu->env;
820 /* APs get directly into wait-for-SIPI state. */
821 if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
822 env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
826 static int kvm_get_supported_msrs(KVMState *s)
828 static int kvm_supported_msrs;
829 int ret = 0;
831 /* first time */
832 if (kvm_supported_msrs == 0) {
833 struct kvm_msr_list msr_list, *kvm_msr_list;
835 kvm_supported_msrs = -1;
837 /* Obtain MSR list from KVM. These are the MSRs that we must
838 * save/restore */
839 msr_list.nmsrs = 0;
840 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
841 if (ret < 0 && ret != -E2BIG) {
842 return ret;
844 /* Old kernel modules had a bug and could write beyond the provided
845 memory. Allocate at least a safe amount of 1K. */
846 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
847 msr_list.nmsrs *
848 sizeof(msr_list.indices[0])));
850 kvm_msr_list->nmsrs = msr_list.nmsrs;
851 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
852 if (ret >= 0) {
853 int i;
855 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
856 if (kvm_msr_list->indices[i] == MSR_STAR) {
857 has_msr_star = true;
858 continue;
860 if (kvm_msr_list->indices[i] == MSR_VM_HSAVE_PA) {
861 has_msr_hsave_pa = true;
862 continue;
864 if (kvm_msr_list->indices[i] == MSR_TSC_AUX) {
865 has_msr_tsc_aux = true;
866 continue;
868 if (kvm_msr_list->indices[i] == MSR_TSC_ADJUST) {
869 has_msr_tsc_adjust = true;
870 continue;
872 if (kvm_msr_list->indices[i] == MSR_IA32_TSCDEADLINE) {
873 has_msr_tsc_deadline = true;
874 continue;
876 if (kvm_msr_list->indices[i] == MSR_IA32_SMBASE) {
877 has_msr_smbase = true;
878 continue;
880 if (kvm_msr_list->indices[i] == MSR_IA32_MISC_ENABLE) {
881 has_msr_misc_enable = true;
882 continue;
884 if (kvm_msr_list->indices[i] == MSR_IA32_BNDCFGS) {
885 has_msr_bndcfgs = true;
886 continue;
888 if (kvm_msr_list->indices[i] == MSR_IA32_XSS) {
889 has_msr_xss = true;
890 continue;
892 if (kvm_msr_list->indices[i] == HV_X64_MSR_CRASH_CTL) {
893 has_msr_hv_crash = true;
894 continue;
896 if (kvm_msr_list->indices[i] == HV_X64_MSR_RESET) {
897 has_msr_hv_reset = true;
898 continue;
900 if (kvm_msr_list->indices[i] == HV_X64_MSR_VP_INDEX) {
901 has_msr_hv_vpindex = true;
902 continue;
904 if (kvm_msr_list->indices[i] == HV_X64_MSR_VP_RUNTIME) {
905 has_msr_hv_runtime = true;
906 continue;
911 g_free(kvm_msr_list);
914 return ret;
917 static Notifier smram_machine_done;
918 static KVMMemoryListener smram_listener;
919 static AddressSpace smram_address_space;
920 static MemoryRegion smram_as_root;
921 static MemoryRegion smram_as_mem;
923 static void register_smram_listener(Notifier *n, void *unused)
925 MemoryRegion *smram =
926 (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
928 /* Outer container... */
929 memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
930 memory_region_set_enabled(&smram_as_root, true);
932 /* ... with two regions inside: normal system memory with low
933 * priority, and...
935 memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
936 get_system_memory(), 0, ~0ull);
937 memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
938 memory_region_set_enabled(&smram_as_mem, true);
940 if (smram) {
941 /* ... SMRAM with higher priority */
942 memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
943 memory_region_set_enabled(smram, true);
946 address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
947 kvm_memory_listener_register(kvm_state, &smram_listener,
948 &smram_address_space, 1);
951 int kvm_arch_init(MachineState *ms, KVMState *s)
953 uint64_t identity_base = 0xfffbc000;
954 uint64_t shadow_mem;
955 int ret;
956 struct utsname utsname;
958 #ifdef KVM_CAP_XSAVE
959 has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
960 #endif
962 #ifdef KVM_CAP_XCRS
963 has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
964 #endif
966 #ifdef KVM_CAP_PIT_STATE2
967 has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
968 #endif
970 ret = kvm_get_supported_msrs(s);
971 if (ret < 0) {
972 return ret;
975 uname(&utsname);
976 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
979 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
980 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
981 * Since these must be part of guest physical memory, we need to allocate
982 * them, both by setting their start addresses in the kernel and by
983 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
985 * Older KVM versions may not support setting the identity map base. In
986 * that case we need to stick with the default, i.e. a 256K maximum BIOS
987 * size.
989 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
990 /* Allows up to 16M BIOSes. */
991 identity_base = 0xfeffc000;
993 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
994 if (ret < 0) {
995 return ret;
999 /* Set TSS base one page after EPT identity map. */
1000 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
1001 if (ret < 0) {
1002 return ret;
1005 /* Tell fw_cfg to notify the BIOS to reserve the range. */
1006 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
1007 if (ret < 0) {
1008 fprintf(stderr, "e820_add_entry() table is full\n");
1009 return ret;
1011 qemu_register_reset(kvm_unpoison_all, NULL);
1013 shadow_mem = machine_kvm_shadow_mem(ms);
1014 if (shadow_mem != -1) {
1015 shadow_mem /= 4096;
1016 ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
1017 if (ret < 0) {
1018 return ret;
1022 if (kvm_check_extension(s, KVM_CAP_X86_SMM)) {
1023 smram_machine_done.notify = register_smram_listener;
1024 qemu_add_machine_init_done_notifier(&smram_machine_done);
1026 return 0;
1029 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1031 lhs->selector = rhs->selector;
1032 lhs->base = rhs->base;
1033 lhs->limit = rhs->limit;
1034 lhs->type = 3;
1035 lhs->present = 1;
1036 lhs->dpl = 3;
1037 lhs->db = 0;
1038 lhs->s = 1;
1039 lhs->l = 0;
1040 lhs->g = 0;
1041 lhs->avl = 0;
1042 lhs->unusable = 0;
1045 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1047 unsigned flags = rhs->flags;
1048 lhs->selector = rhs->selector;
1049 lhs->base = rhs->base;
1050 lhs->limit = rhs->limit;
1051 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
1052 lhs->present = (flags & DESC_P_MASK) != 0;
1053 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
1054 lhs->db = (flags >> DESC_B_SHIFT) & 1;
1055 lhs->s = (flags & DESC_S_MASK) != 0;
1056 lhs->l = (flags >> DESC_L_SHIFT) & 1;
1057 lhs->g = (flags & DESC_G_MASK) != 0;
1058 lhs->avl = (flags & DESC_AVL_MASK) != 0;
1059 lhs->unusable = 0;
1060 lhs->padding = 0;
1063 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
1065 lhs->selector = rhs->selector;
1066 lhs->base = rhs->base;
1067 lhs->limit = rhs->limit;
1068 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
1069 (rhs->present * DESC_P_MASK) |
1070 (rhs->dpl << DESC_DPL_SHIFT) |
1071 (rhs->db << DESC_B_SHIFT) |
1072 (rhs->s * DESC_S_MASK) |
1073 (rhs->l << DESC_L_SHIFT) |
1074 (rhs->g * DESC_G_MASK) |
1075 (rhs->avl * DESC_AVL_MASK);
1078 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
1080 if (set) {
1081 *kvm_reg = *qemu_reg;
1082 } else {
1083 *qemu_reg = *kvm_reg;
1087 static int kvm_getput_regs(X86CPU *cpu, int set)
1089 CPUX86State *env = &cpu->env;
1090 struct kvm_regs regs;
1091 int ret = 0;
1093 if (!set) {
1094 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
1095 if (ret < 0) {
1096 return ret;
1100 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
1101 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
1102 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
1103 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
1104 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
1105 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
1106 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
1107 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
1108 #ifdef TARGET_X86_64
1109 kvm_getput_reg(&regs.r8, &env->regs[8], set);
1110 kvm_getput_reg(&regs.r9, &env->regs[9], set);
1111 kvm_getput_reg(&regs.r10, &env->regs[10], set);
1112 kvm_getput_reg(&regs.r11, &env->regs[11], set);
1113 kvm_getput_reg(&regs.r12, &env->regs[12], set);
1114 kvm_getput_reg(&regs.r13, &env->regs[13], set);
1115 kvm_getput_reg(&regs.r14, &env->regs[14], set);
1116 kvm_getput_reg(&regs.r15, &env->regs[15], set);
1117 #endif
1119 kvm_getput_reg(&regs.rflags, &env->eflags, set);
1120 kvm_getput_reg(&regs.rip, &env->eip, set);
1122 if (set) {
1123 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
1126 return ret;
1129 static int kvm_put_fpu(X86CPU *cpu)
1131 CPUX86State *env = &cpu->env;
1132 struct kvm_fpu fpu;
1133 int i;
1135 memset(&fpu, 0, sizeof fpu);
1136 fpu.fsw = env->fpus & ~(7 << 11);
1137 fpu.fsw |= (env->fpstt & 7) << 11;
1138 fpu.fcw = env->fpuc;
1139 fpu.last_opcode = env->fpop;
1140 fpu.last_ip = env->fpip;
1141 fpu.last_dp = env->fpdp;
1142 for (i = 0; i < 8; ++i) {
1143 fpu.ftwx |= (!env->fptags[i]) << i;
1145 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
1146 for (i = 0; i < CPU_NB_REGS; i++) {
1147 stq_p(&fpu.xmm[i][0], env->xmm_regs[i].XMM_Q(0));
1148 stq_p(&fpu.xmm[i][8], env->xmm_regs[i].XMM_Q(1));
1150 fpu.mxcsr = env->mxcsr;
1152 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
1155 #define XSAVE_FCW_FSW 0
1156 #define XSAVE_FTW_FOP 1
1157 #define XSAVE_CWD_RIP 2
1158 #define XSAVE_CWD_RDP 4
1159 #define XSAVE_MXCSR 6
1160 #define XSAVE_ST_SPACE 8
1161 #define XSAVE_XMM_SPACE 40
1162 #define XSAVE_XSTATE_BV 128
1163 #define XSAVE_YMMH_SPACE 144
1164 #define XSAVE_BNDREGS 240
1165 #define XSAVE_BNDCSR 256
1166 #define XSAVE_OPMASK 272
1167 #define XSAVE_ZMM_Hi256 288
1168 #define XSAVE_Hi16_ZMM 416
1170 static int kvm_put_xsave(X86CPU *cpu)
1172 CPUX86State *env = &cpu->env;
1173 struct kvm_xsave* xsave = env->kvm_xsave_buf;
1174 uint16_t cwd, swd, twd;
1175 uint8_t *xmm, *ymmh, *zmmh;
1176 int i, r;
1178 if (!has_xsave) {
1179 return kvm_put_fpu(cpu);
1182 memset(xsave, 0, sizeof(struct kvm_xsave));
1183 twd = 0;
1184 swd = env->fpus & ~(7 << 11);
1185 swd |= (env->fpstt & 7) << 11;
1186 cwd = env->fpuc;
1187 for (i = 0; i < 8; ++i) {
1188 twd |= (!env->fptags[i]) << i;
1190 xsave->region[XSAVE_FCW_FSW] = (uint32_t)(swd << 16) + cwd;
1191 xsave->region[XSAVE_FTW_FOP] = (uint32_t)(env->fpop << 16) + twd;
1192 memcpy(&xsave->region[XSAVE_CWD_RIP], &env->fpip, sizeof(env->fpip));
1193 memcpy(&xsave->region[XSAVE_CWD_RDP], &env->fpdp, sizeof(env->fpdp));
1194 memcpy(&xsave->region[XSAVE_ST_SPACE], env->fpregs,
1195 sizeof env->fpregs);
1196 xsave->region[XSAVE_MXCSR] = env->mxcsr;
1197 *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV] = env->xstate_bv;
1198 memcpy(&xsave->region[XSAVE_BNDREGS], env->bnd_regs,
1199 sizeof env->bnd_regs);
1200 memcpy(&xsave->region[XSAVE_BNDCSR], &env->bndcs_regs,
1201 sizeof(env->bndcs_regs));
1202 memcpy(&xsave->region[XSAVE_OPMASK], env->opmask_regs,
1203 sizeof env->opmask_regs);
1205 xmm = (uint8_t *)&xsave->region[XSAVE_XMM_SPACE];
1206 ymmh = (uint8_t *)&xsave->region[XSAVE_YMMH_SPACE];
1207 zmmh = (uint8_t *)&xsave->region[XSAVE_ZMM_Hi256];
1208 for (i = 0; i < CPU_NB_REGS; i++, xmm += 16, ymmh += 16, zmmh += 32) {
1209 stq_p(xmm, env->xmm_regs[i].XMM_Q(0));
1210 stq_p(xmm+8, env->xmm_regs[i].XMM_Q(1));
1211 stq_p(ymmh, env->xmm_regs[i].XMM_Q(2));
1212 stq_p(ymmh+8, env->xmm_regs[i].XMM_Q(3));
1213 stq_p(zmmh, env->xmm_regs[i].XMM_Q(4));
1214 stq_p(zmmh+8, env->xmm_regs[i].XMM_Q(5));
1215 stq_p(zmmh+16, env->xmm_regs[i].XMM_Q(6));
1216 stq_p(zmmh+24, env->xmm_regs[i].XMM_Q(7));
1219 #ifdef TARGET_X86_64
1220 memcpy(&xsave->region[XSAVE_Hi16_ZMM], &env->xmm_regs[16],
1221 16 * sizeof env->xmm_regs[16]);
1222 #endif
1223 r = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
1224 return r;
1227 static int kvm_put_xcrs(X86CPU *cpu)
1229 CPUX86State *env = &cpu->env;
1230 struct kvm_xcrs xcrs = {};
1232 if (!has_xcrs) {
1233 return 0;
1236 xcrs.nr_xcrs = 1;
1237 xcrs.flags = 0;
1238 xcrs.xcrs[0].xcr = 0;
1239 xcrs.xcrs[0].value = env->xcr0;
1240 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
1243 static int kvm_put_sregs(X86CPU *cpu)
1245 CPUX86State *env = &cpu->env;
1246 struct kvm_sregs sregs;
1248 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
1249 if (env->interrupt_injected >= 0) {
1250 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
1251 (uint64_t)1 << (env->interrupt_injected % 64);
1254 if ((env->eflags & VM_MASK)) {
1255 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
1256 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
1257 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
1258 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
1259 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
1260 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
1261 } else {
1262 set_seg(&sregs.cs, &env->segs[R_CS]);
1263 set_seg(&sregs.ds, &env->segs[R_DS]);
1264 set_seg(&sregs.es, &env->segs[R_ES]);
1265 set_seg(&sregs.fs, &env->segs[R_FS]);
1266 set_seg(&sregs.gs, &env->segs[R_GS]);
1267 set_seg(&sregs.ss, &env->segs[R_SS]);
1270 set_seg(&sregs.tr, &env->tr);
1271 set_seg(&sregs.ldt, &env->ldt);
1273 sregs.idt.limit = env->idt.limit;
1274 sregs.idt.base = env->idt.base;
1275 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
1276 sregs.gdt.limit = env->gdt.limit;
1277 sregs.gdt.base = env->gdt.base;
1278 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
1280 sregs.cr0 = env->cr[0];
1281 sregs.cr2 = env->cr[2];
1282 sregs.cr3 = env->cr[3];
1283 sregs.cr4 = env->cr[4];
1285 sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
1286 sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
1288 sregs.efer = env->efer;
1290 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
1293 static void kvm_msr_entry_set(struct kvm_msr_entry *entry,
1294 uint32_t index, uint64_t value)
1296 entry->index = index;
1297 entry->reserved = 0;
1298 entry->data = value;
1301 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
1303 CPUX86State *env = &cpu->env;
1304 struct {
1305 struct kvm_msrs info;
1306 struct kvm_msr_entry entries[1];
1307 } msr_data;
1308 struct kvm_msr_entry *msrs = msr_data.entries;
1310 if (!has_msr_tsc_deadline) {
1311 return 0;
1314 kvm_msr_entry_set(&msrs[0], MSR_IA32_TSCDEADLINE, env->tsc_deadline);
1316 msr_data.info = (struct kvm_msrs) {
1317 .nmsrs = 1,
1320 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, &msr_data);
1324 * Provide a separate write service for the feature control MSR in order to
1325 * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
1326 * before writing any other state because forcibly leaving nested mode
1327 * invalidates the VCPU state.
1329 static int kvm_put_msr_feature_control(X86CPU *cpu)
1331 struct {
1332 struct kvm_msrs info;
1333 struct kvm_msr_entry entry;
1334 } msr_data;
1336 kvm_msr_entry_set(&msr_data.entry, MSR_IA32_FEATURE_CONTROL,
1337 cpu->env.msr_ia32_feature_control);
1339 msr_data.info = (struct kvm_msrs) {
1340 .nmsrs = 1,
1343 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, &msr_data);
1346 static int kvm_put_msrs(X86CPU *cpu, int level)
1348 CPUX86State *env = &cpu->env;
1349 struct {
1350 struct kvm_msrs info;
1351 struct kvm_msr_entry entries[150];
1352 } msr_data;
1353 struct kvm_msr_entry *msrs = msr_data.entries;
1354 int n = 0, i;
1356 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_CS, env->sysenter_cs);
1357 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
1358 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
1359 kvm_msr_entry_set(&msrs[n++], MSR_PAT, env->pat);
1360 if (has_msr_star) {
1361 kvm_msr_entry_set(&msrs[n++], MSR_STAR, env->star);
1363 if (has_msr_hsave_pa) {
1364 kvm_msr_entry_set(&msrs[n++], MSR_VM_HSAVE_PA, env->vm_hsave);
1366 if (has_msr_tsc_aux) {
1367 kvm_msr_entry_set(&msrs[n++], MSR_TSC_AUX, env->tsc_aux);
1369 if (has_msr_tsc_adjust) {
1370 kvm_msr_entry_set(&msrs[n++], MSR_TSC_ADJUST, env->tsc_adjust);
1372 if (has_msr_misc_enable) {
1373 kvm_msr_entry_set(&msrs[n++], MSR_IA32_MISC_ENABLE,
1374 env->msr_ia32_misc_enable);
1376 if (has_msr_smbase) {
1377 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SMBASE, env->smbase);
1379 if (has_msr_bndcfgs) {
1380 kvm_msr_entry_set(&msrs[n++], MSR_IA32_BNDCFGS, env->msr_bndcfgs);
1382 if (has_msr_xss) {
1383 kvm_msr_entry_set(&msrs[n++], MSR_IA32_XSS, env->xss);
1385 #ifdef TARGET_X86_64
1386 if (lm_capable_kernel) {
1387 kvm_msr_entry_set(&msrs[n++], MSR_CSTAR, env->cstar);
1388 kvm_msr_entry_set(&msrs[n++], MSR_KERNELGSBASE, env->kernelgsbase);
1389 kvm_msr_entry_set(&msrs[n++], MSR_FMASK, env->fmask);
1390 kvm_msr_entry_set(&msrs[n++], MSR_LSTAR, env->lstar);
1392 #endif
1394 * The following MSRs have side effects on the guest or are too heavy
1395 * for normal writeback. Limit them to reset or full state updates.
1397 if (level >= KVM_PUT_RESET_STATE) {
1398 kvm_msr_entry_set(&msrs[n++], MSR_IA32_TSC, env->tsc);
1399 kvm_msr_entry_set(&msrs[n++], MSR_KVM_SYSTEM_TIME,
1400 env->system_time_msr);
1401 kvm_msr_entry_set(&msrs[n++], MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
1402 if (has_msr_async_pf_en) {
1403 kvm_msr_entry_set(&msrs[n++], MSR_KVM_ASYNC_PF_EN,
1404 env->async_pf_en_msr);
1406 if (has_msr_pv_eoi_en) {
1407 kvm_msr_entry_set(&msrs[n++], MSR_KVM_PV_EOI_EN,
1408 env->pv_eoi_en_msr);
1410 if (has_msr_kvm_steal_time) {
1411 kvm_msr_entry_set(&msrs[n++], MSR_KVM_STEAL_TIME,
1412 env->steal_time_msr);
1414 if (has_msr_architectural_pmu) {
1415 /* Stop the counter. */
1416 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
1417 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_GLOBAL_CTRL, 0);
1419 /* Set the counter values. */
1420 for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
1421 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_FIXED_CTR0 + i,
1422 env->msr_fixed_counters[i]);
1424 for (i = 0; i < num_architectural_pmu_counters; i++) {
1425 kvm_msr_entry_set(&msrs[n++], MSR_P6_PERFCTR0 + i,
1426 env->msr_gp_counters[i]);
1427 kvm_msr_entry_set(&msrs[n++], MSR_P6_EVNTSEL0 + i,
1428 env->msr_gp_evtsel[i]);
1430 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_GLOBAL_STATUS,
1431 env->msr_global_status);
1432 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1433 env->msr_global_ovf_ctrl);
1435 /* Now start the PMU. */
1436 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_FIXED_CTR_CTRL,
1437 env->msr_fixed_ctr_ctrl);
1438 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_GLOBAL_CTRL,
1439 env->msr_global_ctrl);
1441 if (has_msr_hv_hypercall) {
1442 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_GUEST_OS_ID,
1443 env->msr_hv_guest_os_id);
1444 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_HYPERCALL,
1445 env->msr_hv_hypercall);
1447 if (has_msr_hv_vapic) {
1448 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_APIC_ASSIST_PAGE,
1449 env->msr_hv_vapic);
1451 if (has_msr_hv_tsc) {
1452 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_REFERENCE_TSC,
1453 env->msr_hv_tsc);
1455 if (has_msr_hv_crash) {
1456 int j;
1458 for (j = 0; j < HV_X64_MSR_CRASH_PARAMS; j++)
1459 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_CRASH_P0 + j,
1460 env->msr_hv_crash_params[j]);
1462 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_CRASH_CTL,
1463 HV_X64_MSR_CRASH_CTL_NOTIFY);
1465 if (has_msr_hv_runtime) {
1466 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_VP_RUNTIME,
1467 env->msr_hv_runtime);
1469 if (has_msr_mtrr) {
1470 kvm_msr_entry_set(&msrs[n++], MSR_MTRRdefType, env->mtrr_deftype);
1471 kvm_msr_entry_set(&msrs[n++],
1472 MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
1473 kvm_msr_entry_set(&msrs[n++],
1474 MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
1475 kvm_msr_entry_set(&msrs[n++],
1476 MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
1477 kvm_msr_entry_set(&msrs[n++],
1478 MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
1479 kvm_msr_entry_set(&msrs[n++],
1480 MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
1481 kvm_msr_entry_set(&msrs[n++],
1482 MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
1483 kvm_msr_entry_set(&msrs[n++],
1484 MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
1485 kvm_msr_entry_set(&msrs[n++],
1486 MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
1487 kvm_msr_entry_set(&msrs[n++],
1488 MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
1489 kvm_msr_entry_set(&msrs[n++],
1490 MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
1491 kvm_msr_entry_set(&msrs[n++],
1492 MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
1493 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
1494 kvm_msr_entry_set(&msrs[n++],
1495 MSR_MTRRphysBase(i), env->mtrr_var[i].base);
1496 kvm_msr_entry_set(&msrs[n++],
1497 MSR_MTRRphysMask(i), env->mtrr_var[i].mask);
1501 /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
1502 * kvm_put_msr_feature_control. */
1504 if (env->mcg_cap) {
1505 int i;
1507 kvm_msr_entry_set(&msrs[n++], MSR_MCG_STATUS, env->mcg_status);
1508 kvm_msr_entry_set(&msrs[n++], MSR_MCG_CTL, env->mcg_ctl);
1509 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1510 kvm_msr_entry_set(&msrs[n++], MSR_MC0_CTL + i, env->mce_banks[i]);
1514 msr_data.info = (struct kvm_msrs) {
1515 .nmsrs = n,
1518 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, &msr_data);
1523 static int kvm_get_fpu(X86CPU *cpu)
1525 CPUX86State *env = &cpu->env;
1526 struct kvm_fpu fpu;
1527 int i, ret;
1529 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
1530 if (ret < 0) {
1531 return ret;
1534 env->fpstt = (fpu.fsw >> 11) & 7;
1535 env->fpus = fpu.fsw;
1536 env->fpuc = fpu.fcw;
1537 env->fpop = fpu.last_opcode;
1538 env->fpip = fpu.last_ip;
1539 env->fpdp = fpu.last_dp;
1540 for (i = 0; i < 8; ++i) {
1541 env->fptags[i] = !((fpu.ftwx >> i) & 1);
1543 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
1544 for (i = 0; i < CPU_NB_REGS; i++) {
1545 env->xmm_regs[i].XMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
1546 env->xmm_regs[i].XMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
1548 env->mxcsr = fpu.mxcsr;
1550 return 0;
1553 static int kvm_get_xsave(X86CPU *cpu)
1555 CPUX86State *env = &cpu->env;
1556 struct kvm_xsave* xsave = env->kvm_xsave_buf;
1557 int ret, i;
1558 const uint8_t *xmm, *ymmh, *zmmh;
1559 uint16_t cwd, swd, twd;
1561 if (!has_xsave) {
1562 return kvm_get_fpu(cpu);
1565 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
1566 if (ret < 0) {
1567 return ret;
1570 cwd = (uint16_t)xsave->region[XSAVE_FCW_FSW];
1571 swd = (uint16_t)(xsave->region[XSAVE_FCW_FSW] >> 16);
1572 twd = (uint16_t)xsave->region[XSAVE_FTW_FOP];
1573 env->fpop = (uint16_t)(xsave->region[XSAVE_FTW_FOP] >> 16);
1574 env->fpstt = (swd >> 11) & 7;
1575 env->fpus = swd;
1576 env->fpuc = cwd;
1577 for (i = 0; i < 8; ++i) {
1578 env->fptags[i] = !((twd >> i) & 1);
1580 memcpy(&env->fpip, &xsave->region[XSAVE_CWD_RIP], sizeof(env->fpip));
1581 memcpy(&env->fpdp, &xsave->region[XSAVE_CWD_RDP], sizeof(env->fpdp));
1582 env->mxcsr = xsave->region[XSAVE_MXCSR];
1583 memcpy(env->fpregs, &xsave->region[XSAVE_ST_SPACE],
1584 sizeof env->fpregs);
1585 env->xstate_bv = *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV];
1586 memcpy(env->bnd_regs, &xsave->region[XSAVE_BNDREGS],
1587 sizeof env->bnd_regs);
1588 memcpy(&env->bndcs_regs, &xsave->region[XSAVE_BNDCSR],
1589 sizeof(env->bndcs_regs));
1590 memcpy(env->opmask_regs, &xsave->region[XSAVE_OPMASK],
1591 sizeof env->opmask_regs);
1593 xmm = (const uint8_t *)&xsave->region[XSAVE_XMM_SPACE];
1594 ymmh = (const uint8_t *)&xsave->region[XSAVE_YMMH_SPACE];
1595 zmmh = (const uint8_t *)&xsave->region[XSAVE_ZMM_Hi256];
1596 for (i = 0; i < CPU_NB_REGS; i++, xmm += 16, ymmh += 16, zmmh += 32) {
1597 env->xmm_regs[i].XMM_Q(0) = ldq_p(xmm);
1598 env->xmm_regs[i].XMM_Q(1) = ldq_p(xmm+8);
1599 env->xmm_regs[i].XMM_Q(2) = ldq_p(ymmh);
1600 env->xmm_regs[i].XMM_Q(3) = ldq_p(ymmh+8);
1601 env->xmm_regs[i].XMM_Q(4) = ldq_p(zmmh);
1602 env->xmm_regs[i].XMM_Q(5) = ldq_p(zmmh+8);
1603 env->xmm_regs[i].XMM_Q(6) = ldq_p(zmmh+16);
1604 env->xmm_regs[i].XMM_Q(7) = ldq_p(zmmh+24);
1607 #ifdef TARGET_X86_64
1608 memcpy(&env->xmm_regs[16], &xsave->region[XSAVE_Hi16_ZMM],
1609 16 * sizeof env->xmm_regs[16]);
1610 #endif
1611 return 0;
1614 static int kvm_get_xcrs(X86CPU *cpu)
1616 CPUX86State *env = &cpu->env;
1617 int i, ret;
1618 struct kvm_xcrs xcrs;
1620 if (!has_xcrs) {
1621 return 0;
1624 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
1625 if (ret < 0) {
1626 return ret;
1629 for (i = 0; i < xcrs.nr_xcrs; i++) {
1630 /* Only support xcr0 now */
1631 if (xcrs.xcrs[i].xcr == 0) {
1632 env->xcr0 = xcrs.xcrs[i].value;
1633 break;
1636 return 0;
1639 static int kvm_get_sregs(X86CPU *cpu)
1641 CPUX86State *env = &cpu->env;
1642 struct kvm_sregs sregs;
1643 uint32_t hflags;
1644 int bit, i, ret;
1646 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
1647 if (ret < 0) {
1648 return ret;
1651 /* There can only be one pending IRQ set in the bitmap at a time, so try
1652 to find it and save its number instead (-1 for none). */
1653 env->interrupt_injected = -1;
1654 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
1655 if (sregs.interrupt_bitmap[i]) {
1656 bit = ctz64(sregs.interrupt_bitmap[i]);
1657 env->interrupt_injected = i * 64 + bit;
1658 break;
1662 get_seg(&env->segs[R_CS], &sregs.cs);
1663 get_seg(&env->segs[R_DS], &sregs.ds);
1664 get_seg(&env->segs[R_ES], &sregs.es);
1665 get_seg(&env->segs[R_FS], &sregs.fs);
1666 get_seg(&env->segs[R_GS], &sregs.gs);
1667 get_seg(&env->segs[R_SS], &sregs.ss);
1669 get_seg(&env->tr, &sregs.tr);
1670 get_seg(&env->ldt, &sregs.ldt);
1672 env->idt.limit = sregs.idt.limit;
1673 env->idt.base = sregs.idt.base;
1674 env->gdt.limit = sregs.gdt.limit;
1675 env->gdt.base = sregs.gdt.base;
1677 env->cr[0] = sregs.cr0;
1678 env->cr[2] = sregs.cr2;
1679 env->cr[3] = sregs.cr3;
1680 env->cr[4] = sregs.cr4;
1682 env->efer = sregs.efer;
1684 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
1686 #define HFLAG_COPY_MASK \
1687 ~( HF_CPL_MASK | HF_PE_MASK | HF_MP_MASK | HF_EM_MASK | \
1688 HF_TS_MASK | HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK | \
1689 HF_OSFXSR_MASK | HF_LMA_MASK | HF_CS32_MASK | \
1690 HF_SS32_MASK | HF_CS64_MASK | HF_ADDSEG_MASK)
1692 hflags = (env->segs[R_SS].flags >> DESC_DPL_SHIFT) & HF_CPL_MASK;
1693 hflags |= (env->cr[0] & CR0_PE_MASK) << (HF_PE_SHIFT - CR0_PE_SHIFT);
1694 hflags |= (env->cr[0] << (HF_MP_SHIFT - CR0_MP_SHIFT)) &
1695 (HF_MP_MASK | HF_EM_MASK | HF_TS_MASK);
1696 hflags |= (env->eflags & (HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK));
1697 hflags |= (env->cr[4] & CR4_OSFXSR_MASK) <<
1698 (HF_OSFXSR_SHIFT - CR4_OSFXSR_SHIFT);
1700 if (env->efer & MSR_EFER_LMA) {
1701 hflags |= HF_LMA_MASK;
1704 if ((hflags & HF_LMA_MASK) && (env->segs[R_CS].flags & DESC_L_MASK)) {
1705 hflags |= HF_CS32_MASK | HF_SS32_MASK | HF_CS64_MASK;
1706 } else {
1707 hflags |= (env->segs[R_CS].flags & DESC_B_MASK) >>
1708 (DESC_B_SHIFT - HF_CS32_SHIFT);
1709 hflags |= (env->segs[R_SS].flags & DESC_B_MASK) >>
1710 (DESC_B_SHIFT - HF_SS32_SHIFT);
1711 if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK) ||
1712 !(hflags & HF_CS32_MASK)) {
1713 hflags |= HF_ADDSEG_MASK;
1714 } else {
1715 hflags |= ((env->segs[R_DS].base | env->segs[R_ES].base |
1716 env->segs[R_SS].base) != 0) << HF_ADDSEG_SHIFT;
1719 env->hflags = (env->hflags & HFLAG_COPY_MASK) | hflags;
1721 return 0;
1724 static int kvm_get_msrs(X86CPU *cpu)
1726 CPUX86State *env = &cpu->env;
1727 struct {
1728 struct kvm_msrs info;
1729 struct kvm_msr_entry entries[150];
1730 } msr_data;
1731 struct kvm_msr_entry *msrs = msr_data.entries;
1732 int ret, i, n;
1734 n = 0;
1735 msrs[n++].index = MSR_IA32_SYSENTER_CS;
1736 msrs[n++].index = MSR_IA32_SYSENTER_ESP;
1737 msrs[n++].index = MSR_IA32_SYSENTER_EIP;
1738 msrs[n++].index = MSR_PAT;
1739 if (has_msr_star) {
1740 msrs[n++].index = MSR_STAR;
1742 if (has_msr_hsave_pa) {
1743 msrs[n++].index = MSR_VM_HSAVE_PA;
1745 if (has_msr_tsc_aux) {
1746 msrs[n++].index = MSR_TSC_AUX;
1748 if (has_msr_tsc_adjust) {
1749 msrs[n++].index = MSR_TSC_ADJUST;
1751 if (has_msr_tsc_deadline) {
1752 msrs[n++].index = MSR_IA32_TSCDEADLINE;
1754 if (has_msr_misc_enable) {
1755 msrs[n++].index = MSR_IA32_MISC_ENABLE;
1757 if (has_msr_smbase) {
1758 msrs[n++].index = MSR_IA32_SMBASE;
1760 if (has_msr_feature_control) {
1761 msrs[n++].index = MSR_IA32_FEATURE_CONTROL;
1763 if (has_msr_bndcfgs) {
1764 msrs[n++].index = MSR_IA32_BNDCFGS;
1766 if (has_msr_xss) {
1767 msrs[n++].index = MSR_IA32_XSS;
1771 if (!env->tsc_valid) {
1772 msrs[n++].index = MSR_IA32_TSC;
1773 env->tsc_valid = !runstate_is_running();
1776 #ifdef TARGET_X86_64
1777 if (lm_capable_kernel) {
1778 msrs[n++].index = MSR_CSTAR;
1779 msrs[n++].index = MSR_KERNELGSBASE;
1780 msrs[n++].index = MSR_FMASK;
1781 msrs[n++].index = MSR_LSTAR;
1783 #endif
1784 msrs[n++].index = MSR_KVM_SYSTEM_TIME;
1785 msrs[n++].index = MSR_KVM_WALL_CLOCK;
1786 if (has_msr_async_pf_en) {
1787 msrs[n++].index = MSR_KVM_ASYNC_PF_EN;
1789 if (has_msr_pv_eoi_en) {
1790 msrs[n++].index = MSR_KVM_PV_EOI_EN;
1792 if (has_msr_kvm_steal_time) {
1793 msrs[n++].index = MSR_KVM_STEAL_TIME;
1795 if (has_msr_architectural_pmu) {
1796 msrs[n++].index = MSR_CORE_PERF_FIXED_CTR_CTRL;
1797 msrs[n++].index = MSR_CORE_PERF_GLOBAL_CTRL;
1798 msrs[n++].index = MSR_CORE_PERF_GLOBAL_STATUS;
1799 msrs[n++].index = MSR_CORE_PERF_GLOBAL_OVF_CTRL;
1800 for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
1801 msrs[n++].index = MSR_CORE_PERF_FIXED_CTR0 + i;
1803 for (i = 0; i < num_architectural_pmu_counters; i++) {
1804 msrs[n++].index = MSR_P6_PERFCTR0 + i;
1805 msrs[n++].index = MSR_P6_EVNTSEL0 + i;
1809 if (env->mcg_cap) {
1810 msrs[n++].index = MSR_MCG_STATUS;
1811 msrs[n++].index = MSR_MCG_CTL;
1812 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1813 msrs[n++].index = MSR_MC0_CTL + i;
1817 if (has_msr_hv_hypercall) {
1818 msrs[n++].index = HV_X64_MSR_HYPERCALL;
1819 msrs[n++].index = HV_X64_MSR_GUEST_OS_ID;
1821 if (has_msr_hv_vapic) {
1822 msrs[n++].index = HV_X64_MSR_APIC_ASSIST_PAGE;
1824 if (has_msr_hv_tsc) {
1825 msrs[n++].index = HV_X64_MSR_REFERENCE_TSC;
1827 if (has_msr_hv_crash) {
1828 int j;
1830 for (j = 0; j < HV_X64_MSR_CRASH_PARAMS; j++) {
1831 msrs[n++].index = HV_X64_MSR_CRASH_P0 + j;
1834 if (has_msr_hv_runtime) {
1835 msrs[n++].index = HV_X64_MSR_VP_RUNTIME;
1837 if (has_msr_mtrr) {
1838 msrs[n++].index = MSR_MTRRdefType;
1839 msrs[n++].index = MSR_MTRRfix64K_00000;
1840 msrs[n++].index = MSR_MTRRfix16K_80000;
1841 msrs[n++].index = MSR_MTRRfix16K_A0000;
1842 msrs[n++].index = MSR_MTRRfix4K_C0000;
1843 msrs[n++].index = MSR_MTRRfix4K_C8000;
1844 msrs[n++].index = MSR_MTRRfix4K_D0000;
1845 msrs[n++].index = MSR_MTRRfix4K_D8000;
1846 msrs[n++].index = MSR_MTRRfix4K_E0000;
1847 msrs[n++].index = MSR_MTRRfix4K_E8000;
1848 msrs[n++].index = MSR_MTRRfix4K_F0000;
1849 msrs[n++].index = MSR_MTRRfix4K_F8000;
1850 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
1851 msrs[n++].index = MSR_MTRRphysBase(i);
1852 msrs[n++].index = MSR_MTRRphysMask(i);
1856 msr_data.info = (struct kvm_msrs) {
1857 .nmsrs = n,
1860 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
1861 if (ret < 0) {
1862 return ret;
1865 for (i = 0; i < ret; i++) {
1866 uint32_t index = msrs[i].index;
1867 switch (index) {
1868 case MSR_IA32_SYSENTER_CS:
1869 env->sysenter_cs = msrs[i].data;
1870 break;
1871 case MSR_IA32_SYSENTER_ESP:
1872 env->sysenter_esp = msrs[i].data;
1873 break;
1874 case MSR_IA32_SYSENTER_EIP:
1875 env->sysenter_eip = msrs[i].data;
1876 break;
1877 case MSR_PAT:
1878 env->pat = msrs[i].data;
1879 break;
1880 case MSR_STAR:
1881 env->star = msrs[i].data;
1882 break;
1883 #ifdef TARGET_X86_64
1884 case MSR_CSTAR:
1885 env->cstar = msrs[i].data;
1886 break;
1887 case MSR_KERNELGSBASE:
1888 env->kernelgsbase = msrs[i].data;
1889 break;
1890 case MSR_FMASK:
1891 env->fmask = msrs[i].data;
1892 break;
1893 case MSR_LSTAR:
1894 env->lstar = msrs[i].data;
1895 break;
1896 #endif
1897 case MSR_IA32_TSC:
1898 env->tsc = msrs[i].data;
1899 break;
1900 case MSR_TSC_AUX:
1901 env->tsc_aux = msrs[i].data;
1902 break;
1903 case MSR_TSC_ADJUST:
1904 env->tsc_adjust = msrs[i].data;
1905 break;
1906 case MSR_IA32_TSCDEADLINE:
1907 env->tsc_deadline = msrs[i].data;
1908 break;
1909 case MSR_VM_HSAVE_PA:
1910 env->vm_hsave = msrs[i].data;
1911 break;
1912 case MSR_KVM_SYSTEM_TIME:
1913 env->system_time_msr = msrs[i].data;
1914 break;
1915 case MSR_KVM_WALL_CLOCK:
1916 env->wall_clock_msr = msrs[i].data;
1917 break;
1918 case MSR_MCG_STATUS:
1919 env->mcg_status = msrs[i].data;
1920 break;
1921 case MSR_MCG_CTL:
1922 env->mcg_ctl = msrs[i].data;
1923 break;
1924 case MSR_IA32_MISC_ENABLE:
1925 env->msr_ia32_misc_enable = msrs[i].data;
1926 break;
1927 case MSR_IA32_SMBASE:
1928 env->smbase = msrs[i].data;
1929 break;
1930 case MSR_IA32_FEATURE_CONTROL:
1931 env->msr_ia32_feature_control = msrs[i].data;
1932 break;
1933 case MSR_IA32_BNDCFGS:
1934 env->msr_bndcfgs = msrs[i].data;
1935 break;
1936 case MSR_IA32_XSS:
1937 env->xss = msrs[i].data;
1938 break;
1939 default:
1940 if (msrs[i].index >= MSR_MC0_CTL &&
1941 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
1942 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
1944 break;
1945 case MSR_KVM_ASYNC_PF_EN:
1946 env->async_pf_en_msr = msrs[i].data;
1947 break;
1948 case MSR_KVM_PV_EOI_EN:
1949 env->pv_eoi_en_msr = msrs[i].data;
1950 break;
1951 case MSR_KVM_STEAL_TIME:
1952 env->steal_time_msr = msrs[i].data;
1953 break;
1954 case MSR_CORE_PERF_FIXED_CTR_CTRL:
1955 env->msr_fixed_ctr_ctrl = msrs[i].data;
1956 break;
1957 case MSR_CORE_PERF_GLOBAL_CTRL:
1958 env->msr_global_ctrl = msrs[i].data;
1959 break;
1960 case MSR_CORE_PERF_GLOBAL_STATUS:
1961 env->msr_global_status = msrs[i].data;
1962 break;
1963 case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
1964 env->msr_global_ovf_ctrl = msrs[i].data;
1965 break;
1966 case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
1967 env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
1968 break;
1969 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
1970 env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
1971 break;
1972 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
1973 env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
1974 break;
1975 case HV_X64_MSR_HYPERCALL:
1976 env->msr_hv_hypercall = msrs[i].data;
1977 break;
1978 case HV_X64_MSR_GUEST_OS_ID:
1979 env->msr_hv_guest_os_id = msrs[i].data;
1980 break;
1981 case HV_X64_MSR_APIC_ASSIST_PAGE:
1982 env->msr_hv_vapic = msrs[i].data;
1983 break;
1984 case HV_X64_MSR_REFERENCE_TSC:
1985 env->msr_hv_tsc = msrs[i].data;
1986 break;
1987 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
1988 env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
1989 break;
1990 case HV_X64_MSR_VP_RUNTIME:
1991 env->msr_hv_runtime = msrs[i].data;
1992 break;
1993 case MSR_MTRRdefType:
1994 env->mtrr_deftype = msrs[i].data;
1995 break;
1996 case MSR_MTRRfix64K_00000:
1997 env->mtrr_fixed[0] = msrs[i].data;
1998 break;
1999 case MSR_MTRRfix16K_80000:
2000 env->mtrr_fixed[1] = msrs[i].data;
2001 break;
2002 case MSR_MTRRfix16K_A0000:
2003 env->mtrr_fixed[2] = msrs[i].data;
2004 break;
2005 case MSR_MTRRfix4K_C0000:
2006 env->mtrr_fixed[3] = msrs[i].data;
2007 break;
2008 case MSR_MTRRfix4K_C8000:
2009 env->mtrr_fixed[4] = msrs[i].data;
2010 break;
2011 case MSR_MTRRfix4K_D0000:
2012 env->mtrr_fixed[5] = msrs[i].data;
2013 break;
2014 case MSR_MTRRfix4K_D8000:
2015 env->mtrr_fixed[6] = msrs[i].data;
2016 break;
2017 case MSR_MTRRfix4K_E0000:
2018 env->mtrr_fixed[7] = msrs[i].data;
2019 break;
2020 case MSR_MTRRfix4K_E8000:
2021 env->mtrr_fixed[8] = msrs[i].data;
2022 break;
2023 case MSR_MTRRfix4K_F0000:
2024 env->mtrr_fixed[9] = msrs[i].data;
2025 break;
2026 case MSR_MTRRfix4K_F8000:
2027 env->mtrr_fixed[10] = msrs[i].data;
2028 break;
2029 case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
2030 if (index & 1) {
2031 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data;
2032 } else {
2033 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
2035 break;
2039 return 0;
2042 static int kvm_put_mp_state(X86CPU *cpu)
2044 struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
2046 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
2049 static int kvm_get_mp_state(X86CPU *cpu)
2051 CPUState *cs = CPU(cpu);
2052 CPUX86State *env = &cpu->env;
2053 struct kvm_mp_state mp_state;
2054 int ret;
2056 ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
2057 if (ret < 0) {
2058 return ret;
2060 env->mp_state = mp_state.mp_state;
2061 if (kvm_irqchip_in_kernel()) {
2062 cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
2064 return 0;
2067 static int kvm_get_apic(X86CPU *cpu)
2069 DeviceState *apic = cpu->apic_state;
2070 struct kvm_lapic_state kapic;
2071 int ret;
2073 if (apic && kvm_irqchip_in_kernel()) {
2074 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
2075 if (ret < 0) {
2076 return ret;
2079 kvm_get_apic_state(apic, &kapic);
2081 return 0;
2084 static int kvm_put_apic(X86CPU *cpu)
2086 DeviceState *apic = cpu->apic_state;
2087 struct kvm_lapic_state kapic;
2089 if (apic && kvm_irqchip_in_kernel()) {
2090 kvm_put_apic_state(apic, &kapic);
2092 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_LAPIC, &kapic);
2094 return 0;
2097 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
2099 CPUState *cs = CPU(cpu);
2100 CPUX86State *env = &cpu->env;
2101 struct kvm_vcpu_events events = {};
2103 if (!kvm_has_vcpu_events()) {
2104 return 0;
2107 events.exception.injected = (env->exception_injected >= 0);
2108 events.exception.nr = env->exception_injected;
2109 events.exception.has_error_code = env->has_error_code;
2110 events.exception.error_code = env->error_code;
2111 events.exception.pad = 0;
2113 events.interrupt.injected = (env->interrupt_injected >= 0);
2114 events.interrupt.nr = env->interrupt_injected;
2115 events.interrupt.soft = env->soft_interrupt;
2117 events.nmi.injected = env->nmi_injected;
2118 events.nmi.pending = env->nmi_pending;
2119 events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
2120 events.nmi.pad = 0;
2122 events.sipi_vector = env->sipi_vector;
2124 if (has_msr_smbase) {
2125 events.smi.smm = !!(env->hflags & HF_SMM_MASK);
2126 events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
2127 if (kvm_irqchip_in_kernel()) {
2128 /* As soon as these are moved to the kernel, remove them
2129 * from cs->interrupt_request.
2131 events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
2132 events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
2133 cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
2134 } else {
2135 /* Keep these in cs->interrupt_request. */
2136 events.smi.pending = 0;
2137 events.smi.latched_init = 0;
2139 events.flags |= KVM_VCPUEVENT_VALID_SMM;
2142 events.flags = 0;
2143 if (level >= KVM_PUT_RESET_STATE) {
2144 events.flags |=
2145 KVM_VCPUEVENT_VALID_NMI_PENDING | KVM_VCPUEVENT_VALID_SIPI_VECTOR;
2148 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
2151 static int kvm_get_vcpu_events(X86CPU *cpu)
2153 CPUX86State *env = &cpu->env;
2154 struct kvm_vcpu_events events;
2155 int ret;
2157 if (!kvm_has_vcpu_events()) {
2158 return 0;
2161 memset(&events, 0, sizeof(events));
2162 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
2163 if (ret < 0) {
2164 return ret;
2166 env->exception_injected =
2167 events.exception.injected ? events.exception.nr : -1;
2168 env->has_error_code = events.exception.has_error_code;
2169 env->error_code = events.exception.error_code;
2171 env->interrupt_injected =
2172 events.interrupt.injected ? events.interrupt.nr : -1;
2173 env->soft_interrupt = events.interrupt.soft;
2175 env->nmi_injected = events.nmi.injected;
2176 env->nmi_pending = events.nmi.pending;
2177 if (events.nmi.masked) {
2178 env->hflags2 |= HF2_NMI_MASK;
2179 } else {
2180 env->hflags2 &= ~HF2_NMI_MASK;
2183 if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
2184 if (events.smi.smm) {
2185 env->hflags |= HF_SMM_MASK;
2186 } else {
2187 env->hflags &= ~HF_SMM_MASK;
2189 if (events.smi.pending) {
2190 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2191 } else {
2192 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2194 if (events.smi.smm_inside_nmi) {
2195 env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
2196 } else {
2197 env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
2199 if (events.smi.latched_init) {
2200 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2201 } else {
2202 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2206 env->sipi_vector = events.sipi_vector;
2208 return 0;
2211 static int kvm_guest_debug_workarounds(X86CPU *cpu)
2213 CPUState *cs = CPU(cpu);
2214 CPUX86State *env = &cpu->env;
2215 int ret = 0;
2216 unsigned long reinject_trap = 0;
2218 if (!kvm_has_vcpu_events()) {
2219 if (env->exception_injected == 1) {
2220 reinject_trap = KVM_GUESTDBG_INJECT_DB;
2221 } else if (env->exception_injected == 3) {
2222 reinject_trap = KVM_GUESTDBG_INJECT_BP;
2224 env->exception_injected = -1;
2228 * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
2229 * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
2230 * by updating the debug state once again if single-stepping is on.
2231 * Another reason to call kvm_update_guest_debug here is a pending debug
2232 * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
2233 * reinject them via SET_GUEST_DEBUG.
2235 if (reinject_trap ||
2236 (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
2237 ret = kvm_update_guest_debug(cs, reinject_trap);
2239 return ret;
2242 static int kvm_put_debugregs(X86CPU *cpu)
2244 CPUX86State *env = &cpu->env;
2245 struct kvm_debugregs dbgregs;
2246 int i;
2248 if (!kvm_has_debugregs()) {
2249 return 0;
2252 for (i = 0; i < 4; i++) {
2253 dbgregs.db[i] = env->dr[i];
2255 dbgregs.dr6 = env->dr[6];
2256 dbgregs.dr7 = env->dr[7];
2257 dbgregs.flags = 0;
2259 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
2262 static int kvm_get_debugregs(X86CPU *cpu)
2264 CPUX86State *env = &cpu->env;
2265 struct kvm_debugregs dbgregs;
2266 int i, ret;
2268 if (!kvm_has_debugregs()) {
2269 return 0;
2272 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
2273 if (ret < 0) {
2274 return ret;
2276 for (i = 0; i < 4; i++) {
2277 env->dr[i] = dbgregs.db[i];
2279 env->dr[4] = env->dr[6] = dbgregs.dr6;
2280 env->dr[5] = env->dr[7] = dbgregs.dr7;
2282 return 0;
2285 int kvm_arch_put_registers(CPUState *cpu, int level)
2287 X86CPU *x86_cpu = X86_CPU(cpu);
2288 int ret;
2290 assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
2292 if (level >= KVM_PUT_RESET_STATE && has_msr_feature_control) {
2293 ret = kvm_put_msr_feature_control(x86_cpu);
2294 if (ret < 0) {
2295 return ret;
2299 ret = kvm_getput_regs(x86_cpu, 1);
2300 if (ret < 0) {
2301 return ret;
2303 ret = kvm_put_xsave(x86_cpu);
2304 if (ret < 0) {
2305 return ret;
2307 ret = kvm_put_xcrs(x86_cpu);
2308 if (ret < 0) {
2309 return ret;
2311 ret = kvm_put_sregs(x86_cpu);
2312 if (ret < 0) {
2313 return ret;
2315 /* must be before kvm_put_msrs */
2316 ret = kvm_inject_mce_oldstyle(x86_cpu);
2317 if (ret < 0) {
2318 return ret;
2320 ret = kvm_put_msrs(x86_cpu, level);
2321 if (ret < 0) {
2322 return ret;
2324 if (level >= KVM_PUT_RESET_STATE) {
2325 ret = kvm_put_mp_state(x86_cpu);
2326 if (ret < 0) {
2327 return ret;
2329 ret = kvm_put_apic(x86_cpu);
2330 if (ret < 0) {
2331 return ret;
2335 ret = kvm_put_tscdeadline_msr(x86_cpu);
2336 if (ret < 0) {
2337 return ret;
2340 ret = kvm_put_vcpu_events(x86_cpu, level);
2341 if (ret < 0) {
2342 return ret;
2344 ret = kvm_put_debugregs(x86_cpu);
2345 if (ret < 0) {
2346 return ret;
2348 /* must be last */
2349 ret = kvm_guest_debug_workarounds(x86_cpu);
2350 if (ret < 0) {
2351 return ret;
2353 return 0;
2356 int kvm_arch_get_registers(CPUState *cs)
2358 X86CPU *cpu = X86_CPU(cs);
2359 int ret;
2361 assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
2363 ret = kvm_getput_regs(cpu, 0);
2364 if (ret < 0) {
2365 return ret;
2367 ret = kvm_get_xsave(cpu);
2368 if (ret < 0) {
2369 return ret;
2371 ret = kvm_get_xcrs(cpu);
2372 if (ret < 0) {
2373 return ret;
2375 ret = kvm_get_sregs(cpu);
2376 if (ret < 0) {
2377 return ret;
2379 ret = kvm_get_msrs(cpu);
2380 if (ret < 0) {
2381 return ret;
2383 ret = kvm_get_mp_state(cpu);
2384 if (ret < 0) {
2385 return ret;
2387 ret = kvm_get_apic(cpu);
2388 if (ret < 0) {
2389 return ret;
2391 ret = kvm_get_vcpu_events(cpu);
2392 if (ret < 0) {
2393 return ret;
2395 ret = kvm_get_debugregs(cpu);
2396 if (ret < 0) {
2397 return ret;
2399 return 0;
2402 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
2404 X86CPU *x86_cpu = X86_CPU(cpu);
2405 CPUX86State *env = &x86_cpu->env;
2406 int ret;
2408 /* Inject NMI */
2409 if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
2410 if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
2411 qemu_mutex_lock_iothread();
2412 cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
2413 qemu_mutex_unlock_iothread();
2414 DPRINTF("injected NMI\n");
2415 ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
2416 if (ret < 0) {
2417 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
2418 strerror(-ret));
2421 if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
2422 qemu_mutex_lock_iothread();
2423 cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
2424 qemu_mutex_unlock_iothread();
2425 DPRINTF("injected SMI\n");
2426 ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
2427 if (ret < 0) {
2428 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
2429 strerror(-ret));
2434 if (!kvm_irqchip_in_kernel()) {
2435 qemu_mutex_lock_iothread();
2438 /* Force the VCPU out of its inner loop to process any INIT requests
2439 * or (for userspace APIC, but it is cheap to combine the checks here)
2440 * pending TPR access reports.
2442 if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
2443 if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
2444 !(env->hflags & HF_SMM_MASK)) {
2445 cpu->exit_request = 1;
2447 if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
2448 cpu->exit_request = 1;
2452 if (!kvm_irqchip_in_kernel()) {
2453 /* Try to inject an interrupt if the guest can accept it */
2454 if (run->ready_for_interrupt_injection &&
2455 (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
2456 (env->eflags & IF_MASK)) {
2457 int irq;
2459 cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
2460 irq = cpu_get_pic_interrupt(env);
2461 if (irq >= 0) {
2462 struct kvm_interrupt intr;
2464 intr.irq = irq;
2465 DPRINTF("injected interrupt %d\n", irq);
2466 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
2467 if (ret < 0) {
2468 fprintf(stderr,
2469 "KVM: injection failed, interrupt lost (%s)\n",
2470 strerror(-ret));
2475 /* If we have an interrupt but the guest is not ready to receive an
2476 * interrupt, request an interrupt window exit. This will
2477 * cause a return to userspace as soon as the guest is ready to
2478 * receive interrupts. */
2479 if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
2480 run->request_interrupt_window = 1;
2481 } else {
2482 run->request_interrupt_window = 0;
2485 DPRINTF("setting tpr\n");
2486 run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
2488 qemu_mutex_unlock_iothread();
2492 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
2494 X86CPU *x86_cpu = X86_CPU(cpu);
2495 CPUX86State *env = &x86_cpu->env;
2497 if (run->flags & KVM_RUN_X86_SMM) {
2498 env->hflags |= HF_SMM_MASK;
2499 } else {
2500 env->hflags &= HF_SMM_MASK;
2502 if (run->if_flag) {
2503 env->eflags |= IF_MASK;
2504 } else {
2505 env->eflags &= ~IF_MASK;
2508 /* We need to protect the apic state against concurrent accesses from
2509 * different threads in case the userspace irqchip is used. */
2510 if (!kvm_irqchip_in_kernel()) {
2511 qemu_mutex_lock_iothread();
2513 cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
2514 cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
2515 if (!kvm_irqchip_in_kernel()) {
2516 qemu_mutex_unlock_iothread();
2518 return cpu_get_mem_attrs(env);
2521 int kvm_arch_process_async_events(CPUState *cs)
2523 X86CPU *cpu = X86_CPU(cs);
2524 CPUX86State *env = &cpu->env;
2526 if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
2527 /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
2528 assert(env->mcg_cap);
2530 cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
2532 kvm_cpu_synchronize_state(cs);
2534 if (env->exception_injected == EXCP08_DBLE) {
2535 /* this means triple fault */
2536 qemu_system_reset_request();
2537 cs->exit_request = 1;
2538 return 0;
2540 env->exception_injected = EXCP12_MCHK;
2541 env->has_error_code = 0;
2543 cs->halted = 0;
2544 if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
2545 env->mp_state = KVM_MP_STATE_RUNNABLE;
2549 if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
2550 !(env->hflags & HF_SMM_MASK)) {
2551 kvm_cpu_synchronize_state(cs);
2552 do_cpu_init(cpu);
2555 if (kvm_irqchip_in_kernel()) {
2556 return 0;
2559 if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
2560 cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
2561 apic_poll_irq(cpu->apic_state);
2563 if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2564 (env->eflags & IF_MASK)) ||
2565 (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
2566 cs->halted = 0;
2568 if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
2569 kvm_cpu_synchronize_state(cs);
2570 do_cpu_sipi(cpu);
2572 if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
2573 cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
2574 kvm_cpu_synchronize_state(cs);
2575 apic_handle_tpr_access_report(cpu->apic_state, env->eip,
2576 env->tpr_access_type);
2579 return cs->halted;
2582 static int kvm_handle_halt(X86CPU *cpu)
2584 CPUState *cs = CPU(cpu);
2585 CPUX86State *env = &cpu->env;
2587 if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2588 (env->eflags & IF_MASK)) &&
2589 !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
2590 cs->halted = 1;
2591 return EXCP_HLT;
2594 return 0;
2597 static int kvm_handle_tpr_access(X86CPU *cpu)
2599 CPUState *cs = CPU(cpu);
2600 struct kvm_run *run = cs->kvm_run;
2602 apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
2603 run->tpr_access.is_write ? TPR_ACCESS_WRITE
2604 : TPR_ACCESS_READ);
2605 return 1;
2608 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2610 static const uint8_t int3 = 0xcc;
2612 if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
2613 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
2614 return -EINVAL;
2616 return 0;
2619 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2621 uint8_t int3;
2623 if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
2624 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
2625 return -EINVAL;
2627 return 0;
2630 static struct {
2631 target_ulong addr;
2632 int len;
2633 int type;
2634 } hw_breakpoint[4];
2636 static int nb_hw_breakpoint;
2638 static int find_hw_breakpoint(target_ulong addr, int len, int type)
2640 int n;
2642 for (n = 0; n < nb_hw_breakpoint; n++) {
2643 if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
2644 (hw_breakpoint[n].len == len || len == -1)) {
2645 return n;
2648 return -1;
2651 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
2652 target_ulong len, int type)
2654 switch (type) {
2655 case GDB_BREAKPOINT_HW:
2656 len = 1;
2657 break;
2658 case GDB_WATCHPOINT_WRITE:
2659 case GDB_WATCHPOINT_ACCESS:
2660 switch (len) {
2661 case 1:
2662 break;
2663 case 2:
2664 case 4:
2665 case 8:
2666 if (addr & (len - 1)) {
2667 return -EINVAL;
2669 break;
2670 default:
2671 return -EINVAL;
2673 break;
2674 default:
2675 return -ENOSYS;
2678 if (nb_hw_breakpoint == 4) {
2679 return -ENOBUFS;
2681 if (find_hw_breakpoint(addr, len, type) >= 0) {
2682 return -EEXIST;
2684 hw_breakpoint[nb_hw_breakpoint].addr = addr;
2685 hw_breakpoint[nb_hw_breakpoint].len = len;
2686 hw_breakpoint[nb_hw_breakpoint].type = type;
2687 nb_hw_breakpoint++;
2689 return 0;
2692 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
2693 target_ulong len, int type)
2695 int n;
2697 n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
2698 if (n < 0) {
2699 return -ENOENT;
2701 nb_hw_breakpoint--;
2702 hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
2704 return 0;
2707 void kvm_arch_remove_all_hw_breakpoints(void)
2709 nb_hw_breakpoint = 0;
2712 static CPUWatchpoint hw_watchpoint;
2714 static int kvm_handle_debug(X86CPU *cpu,
2715 struct kvm_debug_exit_arch *arch_info)
2717 CPUState *cs = CPU(cpu);
2718 CPUX86State *env = &cpu->env;
2719 int ret = 0;
2720 int n;
2722 if (arch_info->exception == 1) {
2723 if (arch_info->dr6 & (1 << 14)) {
2724 if (cs->singlestep_enabled) {
2725 ret = EXCP_DEBUG;
2727 } else {
2728 for (n = 0; n < 4; n++) {
2729 if (arch_info->dr6 & (1 << n)) {
2730 switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
2731 case 0x0:
2732 ret = EXCP_DEBUG;
2733 break;
2734 case 0x1:
2735 ret = EXCP_DEBUG;
2736 cs->watchpoint_hit = &hw_watchpoint;
2737 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
2738 hw_watchpoint.flags = BP_MEM_WRITE;
2739 break;
2740 case 0x3:
2741 ret = EXCP_DEBUG;
2742 cs->watchpoint_hit = &hw_watchpoint;
2743 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
2744 hw_watchpoint.flags = BP_MEM_ACCESS;
2745 break;
2750 } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
2751 ret = EXCP_DEBUG;
2753 if (ret == 0) {
2754 cpu_synchronize_state(cs);
2755 assert(env->exception_injected == -1);
2757 /* pass to guest */
2758 env->exception_injected = arch_info->exception;
2759 env->has_error_code = 0;
2762 return ret;
2765 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
2767 const uint8_t type_code[] = {
2768 [GDB_BREAKPOINT_HW] = 0x0,
2769 [GDB_WATCHPOINT_WRITE] = 0x1,
2770 [GDB_WATCHPOINT_ACCESS] = 0x3
2772 const uint8_t len_code[] = {
2773 [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
2775 int n;
2777 if (kvm_sw_breakpoints_active(cpu)) {
2778 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
2780 if (nb_hw_breakpoint > 0) {
2781 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
2782 dbg->arch.debugreg[7] = 0x0600;
2783 for (n = 0; n < nb_hw_breakpoint; n++) {
2784 dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
2785 dbg->arch.debugreg[7] |= (2 << (n * 2)) |
2786 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
2787 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
2792 static bool host_supports_vmx(void)
2794 uint32_t ecx, unused;
2796 host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
2797 return ecx & CPUID_EXT_VMX;
2800 #define VMX_INVALID_GUEST_STATE 0x80000021
2802 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
2804 X86CPU *cpu = X86_CPU(cs);
2805 uint64_t code;
2806 int ret;
2808 switch (run->exit_reason) {
2809 case KVM_EXIT_HLT:
2810 DPRINTF("handle_hlt\n");
2811 qemu_mutex_lock_iothread();
2812 ret = kvm_handle_halt(cpu);
2813 qemu_mutex_unlock_iothread();
2814 break;
2815 case KVM_EXIT_SET_TPR:
2816 ret = 0;
2817 break;
2818 case KVM_EXIT_TPR_ACCESS:
2819 qemu_mutex_lock_iothread();
2820 ret = kvm_handle_tpr_access(cpu);
2821 qemu_mutex_unlock_iothread();
2822 break;
2823 case KVM_EXIT_FAIL_ENTRY:
2824 code = run->fail_entry.hardware_entry_failure_reason;
2825 fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
2826 code);
2827 if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
2828 fprintf(stderr,
2829 "\nIf you're running a guest on an Intel machine without "
2830 "unrestricted mode\n"
2831 "support, the failure can be most likely due to the guest "
2832 "entering an invalid\n"
2833 "state for Intel VT. For example, the guest maybe running "
2834 "in big real mode\n"
2835 "which is not supported on less recent Intel processors."
2836 "\n\n");
2838 ret = -1;
2839 break;
2840 case KVM_EXIT_EXCEPTION:
2841 fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
2842 run->ex.exception, run->ex.error_code);
2843 ret = -1;
2844 break;
2845 case KVM_EXIT_DEBUG:
2846 DPRINTF("kvm_exit_debug\n");
2847 qemu_mutex_lock_iothread();
2848 ret = kvm_handle_debug(cpu, &run->debug.arch);
2849 qemu_mutex_unlock_iothread();
2850 break;
2851 default:
2852 fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
2853 ret = -1;
2854 break;
2857 return ret;
2860 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
2862 X86CPU *cpu = X86_CPU(cs);
2863 CPUX86State *env = &cpu->env;
2865 kvm_cpu_synchronize_state(cs);
2866 return !(env->cr[0] & CR0_PE_MASK) ||
2867 ((env->segs[R_CS].selector & 3) != 3);
2870 void kvm_arch_init_irq_routing(KVMState *s)
2872 if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
2873 /* If kernel can't do irq routing, interrupt source
2874 * override 0->2 cannot be set up as required by HPET.
2875 * So we have to disable it.
2877 no_hpet = 1;
2879 /* We know at this point that we're using the in-kernel
2880 * irqchip, so we can use irqfds, and on x86 we know
2881 * we can use msi via irqfd and GSI routing.
2883 kvm_msi_via_irqfd_allowed = true;
2884 kvm_gsi_routing_allowed = true;
2887 /* Classic KVM device assignment interface. Will remain x86 only. */
2888 int kvm_device_pci_assign(KVMState *s, PCIHostDeviceAddress *dev_addr,
2889 uint32_t flags, uint32_t *dev_id)
2891 struct kvm_assigned_pci_dev dev_data = {
2892 .segnr = dev_addr->domain,
2893 .busnr = dev_addr->bus,
2894 .devfn = PCI_DEVFN(dev_addr->slot, dev_addr->function),
2895 .flags = flags,
2897 int ret;
2899 dev_data.assigned_dev_id =
2900 (dev_addr->domain << 16) | (dev_addr->bus << 8) | dev_data.devfn;
2902 ret = kvm_vm_ioctl(s, KVM_ASSIGN_PCI_DEVICE, &dev_data);
2903 if (ret < 0) {
2904 return ret;
2907 *dev_id = dev_data.assigned_dev_id;
2909 return 0;
2912 int kvm_device_pci_deassign(KVMState *s, uint32_t dev_id)
2914 struct kvm_assigned_pci_dev dev_data = {
2915 .assigned_dev_id = dev_id,
2918 return kvm_vm_ioctl(s, KVM_DEASSIGN_PCI_DEVICE, &dev_data);
2921 static int kvm_assign_irq_internal(KVMState *s, uint32_t dev_id,
2922 uint32_t irq_type, uint32_t guest_irq)
2924 struct kvm_assigned_irq assigned_irq = {
2925 .assigned_dev_id = dev_id,
2926 .guest_irq = guest_irq,
2927 .flags = irq_type,
2930 if (kvm_check_extension(s, KVM_CAP_ASSIGN_DEV_IRQ)) {
2931 return kvm_vm_ioctl(s, KVM_ASSIGN_DEV_IRQ, &assigned_irq);
2932 } else {
2933 return kvm_vm_ioctl(s, KVM_ASSIGN_IRQ, &assigned_irq);
2937 int kvm_device_intx_assign(KVMState *s, uint32_t dev_id, bool use_host_msi,
2938 uint32_t guest_irq)
2940 uint32_t irq_type = KVM_DEV_IRQ_GUEST_INTX |
2941 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX);
2943 return kvm_assign_irq_internal(s, dev_id, irq_type, guest_irq);
2946 int kvm_device_intx_set_mask(KVMState *s, uint32_t dev_id, bool masked)
2948 struct kvm_assigned_pci_dev dev_data = {
2949 .assigned_dev_id = dev_id,
2950 .flags = masked ? KVM_DEV_ASSIGN_MASK_INTX : 0,
2953 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_INTX_MASK, &dev_data);
2956 static int kvm_deassign_irq_internal(KVMState *s, uint32_t dev_id,
2957 uint32_t type)
2959 struct kvm_assigned_irq assigned_irq = {
2960 .assigned_dev_id = dev_id,
2961 .flags = type,
2964 return kvm_vm_ioctl(s, KVM_DEASSIGN_DEV_IRQ, &assigned_irq);
2967 int kvm_device_intx_deassign(KVMState *s, uint32_t dev_id, bool use_host_msi)
2969 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_INTX |
2970 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX));
2973 int kvm_device_msi_assign(KVMState *s, uint32_t dev_id, int virq)
2975 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSI |
2976 KVM_DEV_IRQ_GUEST_MSI, virq);
2979 int kvm_device_msi_deassign(KVMState *s, uint32_t dev_id)
2981 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSI |
2982 KVM_DEV_IRQ_HOST_MSI);
2985 bool kvm_device_msix_supported(KVMState *s)
2987 /* The kernel lacks a corresponding KVM_CAP, so we probe by calling
2988 * KVM_ASSIGN_SET_MSIX_NR with an invalid parameter. */
2989 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, NULL) == -EFAULT;
2992 int kvm_device_msix_init_vectors(KVMState *s, uint32_t dev_id,
2993 uint32_t nr_vectors)
2995 struct kvm_assigned_msix_nr msix_nr = {
2996 .assigned_dev_id = dev_id,
2997 .entry_nr = nr_vectors,
3000 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, &msix_nr);
3003 int kvm_device_msix_set_vector(KVMState *s, uint32_t dev_id, uint32_t vector,
3004 int virq)
3006 struct kvm_assigned_msix_entry msix_entry = {
3007 .assigned_dev_id = dev_id,
3008 .gsi = virq,
3009 .entry = vector,
3012 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_ENTRY, &msix_entry);
3015 int kvm_device_msix_assign(KVMState *s, uint32_t dev_id)
3017 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSIX |
3018 KVM_DEV_IRQ_GUEST_MSIX, 0);
3021 int kvm_device_msix_deassign(KVMState *s, uint32_t dev_id)
3023 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSIX |
3024 KVM_DEV_IRQ_HOST_MSIX);
3027 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
3028 uint64_t address, uint32_t data, PCIDevice *dev)
3030 return 0;
3033 int kvm_arch_msi_data_to_gsi(uint32_t data)
3035 abort();