block: define 'clock_type' for the accounting code
[qemu.git] / target-i386 / kvm.c
blob2a9953b2d4b584df13c2cf8927030469b77e99cd
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 int kvm_get_tsc(CPUState *cs)
116 X86CPU *cpu = X86_CPU(cs);
117 CPUX86State *env = &cpu->env;
118 struct {
119 struct kvm_msrs info;
120 struct kvm_msr_entry entries[1];
121 } msr_data;
122 int ret;
124 if (env->tsc_valid) {
125 return 0;
128 msr_data.info.nmsrs = 1;
129 msr_data.entries[0].index = MSR_IA32_TSC;
130 env->tsc_valid = !runstate_is_running();
132 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
133 if (ret < 0) {
134 return ret;
137 env->tsc = msr_data.entries[0].data;
138 return 0;
141 static inline void do_kvm_synchronize_tsc(void *arg)
143 CPUState *cpu = arg;
145 kvm_get_tsc(cpu);
148 void kvm_synchronize_all_tsc(void)
150 CPUState *cpu;
152 if (kvm_enabled()) {
153 CPU_FOREACH(cpu) {
154 run_on_cpu(cpu, do_kvm_synchronize_tsc, cpu);
159 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
161 struct kvm_cpuid2 *cpuid;
162 int r, size;
164 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
165 cpuid = g_malloc0(size);
166 cpuid->nent = max;
167 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
168 if (r == 0 && cpuid->nent >= max) {
169 r = -E2BIG;
171 if (r < 0) {
172 if (r == -E2BIG) {
173 g_free(cpuid);
174 return NULL;
175 } else {
176 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
177 strerror(-r));
178 exit(1);
181 return cpuid;
184 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
185 * for all entries.
187 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
189 struct kvm_cpuid2 *cpuid;
190 int max = 1;
191 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
192 max *= 2;
194 return cpuid;
197 static const struct kvm_para_features {
198 int cap;
199 int feature;
200 } para_features[] = {
201 { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
202 { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
203 { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
204 { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
207 static int get_para_features(KVMState *s)
209 int i, features = 0;
211 for (i = 0; i < ARRAY_SIZE(para_features); i++) {
212 if (kvm_check_extension(s, para_features[i].cap)) {
213 features |= (1 << para_features[i].feature);
217 return features;
221 /* Returns the value for a specific register on the cpuid entry
223 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
225 uint32_t ret = 0;
226 switch (reg) {
227 case R_EAX:
228 ret = entry->eax;
229 break;
230 case R_EBX:
231 ret = entry->ebx;
232 break;
233 case R_ECX:
234 ret = entry->ecx;
235 break;
236 case R_EDX:
237 ret = entry->edx;
238 break;
240 return ret;
243 /* Find matching entry for function/index on kvm_cpuid2 struct
245 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
246 uint32_t function,
247 uint32_t index)
249 int i;
250 for (i = 0; i < cpuid->nent; ++i) {
251 if (cpuid->entries[i].function == function &&
252 cpuid->entries[i].index == index) {
253 return &cpuid->entries[i];
256 /* not found: */
257 return NULL;
260 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
261 uint32_t index, int reg)
263 struct kvm_cpuid2 *cpuid;
264 uint32_t ret = 0;
265 uint32_t cpuid_1_edx;
266 bool found = false;
268 cpuid = get_supported_cpuid(s);
270 struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
271 if (entry) {
272 found = true;
273 ret = cpuid_entry_get_reg(entry, reg);
276 /* Fixups for the data returned by KVM, below */
278 if (function == 1 && reg == R_EDX) {
279 /* KVM before 2.6.30 misreports the following features */
280 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
281 } else if (function == 1 && reg == R_ECX) {
282 /* We can set the hypervisor flag, even if KVM does not return it on
283 * GET_SUPPORTED_CPUID
285 ret |= CPUID_EXT_HYPERVISOR;
286 /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
287 * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
288 * and the irqchip is in the kernel.
290 if (kvm_irqchip_in_kernel() &&
291 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
292 ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
295 /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
296 * without the in-kernel irqchip
298 if (!kvm_irqchip_in_kernel()) {
299 ret &= ~CPUID_EXT_X2APIC;
301 } else if (function == 6 && reg == R_EAX) {
302 ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
303 } else if (function == 0x80000001 && reg == R_EDX) {
304 /* On Intel, kvm returns cpuid according to the Intel spec,
305 * so add missing bits according to the AMD spec:
307 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
308 ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
311 g_free(cpuid);
313 /* fallback for older kernels */
314 if ((function == KVM_CPUID_FEATURES) && !found) {
315 ret = get_para_features(s);
318 return ret;
321 typedef struct HWPoisonPage {
322 ram_addr_t ram_addr;
323 QLIST_ENTRY(HWPoisonPage) list;
324 } HWPoisonPage;
326 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
327 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
329 static void kvm_unpoison_all(void *param)
331 HWPoisonPage *page, *next_page;
333 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
334 QLIST_REMOVE(page, list);
335 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
336 g_free(page);
340 static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
342 HWPoisonPage *page;
344 QLIST_FOREACH(page, &hwpoison_page_list, list) {
345 if (page->ram_addr == ram_addr) {
346 return;
349 page = g_new(HWPoisonPage, 1);
350 page->ram_addr = ram_addr;
351 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
354 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
355 int *max_banks)
357 int r;
359 r = kvm_check_extension(s, KVM_CAP_MCE);
360 if (r > 0) {
361 *max_banks = r;
362 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
364 return -ENOSYS;
367 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
369 CPUX86State *env = &cpu->env;
370 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
371 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
372 uint64_t mcg_status = MCG_STATUS_MCIP;
374 if (code == BUS_MCEERR_AR) {
375 status |= MCI_STATUS_AR | 0x134;
376 mcg_status |= MCG_STATUS_EIPV;
377 } else {
378 status |= 0xc0;
379 mcg_status |= MCG_STATUS_RIPV;
381 cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
382 (MCM_ADDR_PHYS << 6) | 0xc,
383 cpu_x86_support_mca_broadcast(env) ?
384 MCE_INJECT_BROADCAST : 0);
387 static void hardware_memory_error(void)
389 fprintf(stderr, "Hardware memory error!\n");
390 exit(1);
393 int kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
395 X86CPU *cpu = X86_CPU(c);
396 CPUX86State *env = &cpu->env;
397 ram_addr_t ram_addr;
398 hwaddr paddr;
400 if ((env->mcg_cap & MCG_SER_P) && addr
401 && (code == BUS_MCEERR_AR || code == BUS_MCEERR_AO)) {
402 if (qemu_ram_addr_from_host(addr, &ram_addr) == NULL ||
403 !kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
404 fprintf(stderr, "Hardware memory error for memory used by "
405 "QEMU itself instead of guest system!\n");
406 /* Hope we are lucky for AO MCE */
407 if (code == BUS_MCEERR_AO) {
408 return 0;
409 } else {
410 hardware_memory_error();
413 kvm_hwpoison_page_add(ram_addr);
414 kvm_mce_inject(cpu, paddr, code);
415 } else {
416 if (code == BUS_MCEERR_AO) {
417 return 0;
418 } else if (code == BUS_MCEERR_AR) {
419 hardware_memory_error();
420 } else {
421 return 1;
424 return 0;
427 int kvm_arch_on_sigbus(int code, void *addr)
429 X86CPU *cpu = X86_CPU(first_cpu);
431 if ((cpu->env.mcg_cap & MCG_SER_P) && addr && code == BUS_MCEERR_AO) {
432 ram_addr_t ram_addr;
433 hwaddr paddr;
435 /* Hope we are lucky for AO MCE */
436 if (qemu_ram_addr_from_host(addr, &ram_addr) == NULL ||
437 !kvm_physical_memory_addr_from_host(first_cpu->kvm_state,
438 addr, &paddr)) {
439 fprintf(stderr, "Hardware memory error for memory used by "
440 "QEMU itself instead of guest system!: %p\n", addr);
441 return 0;
443 kvm_hwpoison_page_add(ram_addr);
444 kvm_mce_inject(X86_CPU(first_cpu), paddr, code);
445 } else {
446 if (code == BUS_MCEERR_AO) {
447 return 0;
448 } else if (code == BUS_MCEERR_AR) {
449 hardware_memory_error();
450 } else {
451 return 1;
454 return 0;
457 static int kvm_inject_mce_oldstyle(X86CPU *cpu)
459 CPUX86State *env = &cpu->env;
461 if (!kvm_has_vcpu_events() && env->exception_injected == EXCP12_MCHK) {
462 unsigned int bank, bank_num = env->mcg_cap & 0xff;
463 struct kvm_x86_mce mce;
465 env->exception_injected = -1;
468 * There must be at least one bank in use if an MCE is pending.
469 * Find it and use its values for the event injection.
471 for (bank = 0; bank < bank_num; bank++) {
472 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
473 break;
476 assert(bank < bank_num);
478 mce.bank = bank;
479 mce.status = env->mce_banks[bank * 4 + 1];
480 mce.mcg_status = env->mcg_status;
481 mce.addr = env->mce_banks[bank * 4 + 2];
482 mce.misc = env->mce_banks[bank * 4 + 3];
484 return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
486 return 0;
489 static void cpu_update_state(void *opaque, int running, RunState state)
491 CPUX86State *env = opaque;
493 if (running) {
494 env->tsc_valid = false;
498 unsigned long kvm_arch_vcpu_id(CPUState *cs)
500 X86CPU *cpu = X86_CPU(cs);
501 return cpu->apic_id;
504 #ifndef KVM_CPUID_SIGNATURE_NEXT
505 #define KVM_CPUID_SIGNATURE_NEXT 0x40000100
506 #endif
508 static bool hyperv_hypercall_available(X86CPU *cpu)
510 return cpu->hyperv_vapic ||
511 (cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY);
514 static bool hyperv_enabled(X86CPU *cpu)
516 CPUState *cs = CPU(cpu);
517 return kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0 &&
518 (hyperv_hypercall_available(cpu) ||
519 cpu->hyperv_time ||
520 cpu->hyperv_relaxed_timing ||
521 cpu->hyperv_crash ||
522 cpu->hyperv_reset ||
523 cpu->hyperv_vpindex ||
524 cpu->hyperv_runtime);
527 static Error *invtsc_mig_blocker;
529 #define KVM_MAX_CPUID_ENTRIES 100
531 int kvm_arch_init_vcpu(CPUState *cs)
533 struct {
534 struct kvm_cpuid2 cpuid;
535 struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
536 } QEMU_PACKED cpuid_data;
537 X86CPU *cpu = X86_CPU(cs);
538 CPUX86State *env = &cpu->env;
539 uint32_t limit, i, j, cpuid_i;
540 uint32_t unused;
541 struct kvm_cpuid_entry2 *c;
542 uint32_t signature[3];
543 int kvm_base = KVM_CPUID_SIGNATURE;
544 int r;
546 memset(&cpuid_data, 0, sizeof(cpuid_data));
548 cpuid_i = 0;
550 /* Paravirtualization CPUIDs */
551 if (hyperv_enabled(cpu)) {
552 c = &cpuid_data.entries[cpuid_i++];
553 c->function = HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
554 if (!cpu->hyperv_vendor_id) {
555 memcpy(signature, "Microsoft Hv", 12);
556 } else {
557 size_t len = strlen(cpu->hyperv_vendor_id);
559 if (len > 12) {
560 error_report("hv-vendor-id truncated to 12 characters");
561 len = 12;
563 memset(signature, 0, 12);
564 memcpy(signature, cpu->hyperv_vendor_id, len);
566 c->eax = HYPERV_CPUID_MIN;
567 c->ebx = signature[0];
568 c->ecx = signature[1];
569 c->edx = signature[2];
571 c = &cpuid_data.entries[cpuid_i++];
572 c->function = HYPERV_CPUID_INTERFACE;
573 memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
574 c->eax = signature[0];
575 c->ebx = 0;
576 c->ecx = 0;
577 c->edx = 0;
579 c = &cpuid_data.entries[cpuid_i++];
580 c->function = HYPERV_CPUID_VERSION;
581 c->eax = 0x00001bbc;
582 c->ebx = 0x00060001;
584 c = &cpuid_data.entries[cpuid_i++];
585 c->function = HYPERV_CPUID_FEATURES;
586 if (cpu->hyperv_relaxed_timing) {
587 c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
589 if (cpu->hyperv_vapic) {
590 c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
591 c->eax |= HV_X64_MSR_APIC_ACCESS_AVAILABLE;
592 has_msr_hv_vapic = true;
594 if (cpu->hyperv_time &&
595 kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) > 0) {
596 c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
597 c->eax |= HV_X64_MSR_TIME_REF_COUNT_AVAILABLE;
598 c->eax |= 0x200;
599 has_msr_hv_tsc = true;
601 if (cpu->hyperv_crash && has_msr_hv_crash) {
602 c->edx |= HV_X64_GUEST_CRASH_MSR_AVAILABLE;
604 if (cpu->hyperv_reset && has_msr_hv_reset) {
605 c->eax |= HV_X64_MSR_RESET_AVAILABLE;
607 if (cpu->hyperv_vpindex && has_msr_hv_vpindex) {
608 c->eax |= HV_X64_MSR_VP_INDEX_AVAILABLE;
610 if (cpu->hyperv_runtime && has_msr_hv_runtime) {
611 c->eax |= HV_X64_MSR_VP_RUNTIME_AVAILABLE;
613 c = &cpuid_data.entries[cpuid_i++];
614 c->function = HYPERV_CPUID_ENLIGHTMENT_INFO;
615 if (cpu->hyperv_relaxed_timing) {
616 c->eax |= HV_X64_RELAXED_TIMING_RECOMMENDED;
618 if (has_msr_hv_vapic) {
619 c->eax |= HV_X64_APIC_ACCESS_RECOMMENDED;
621 c->ebx = cpu->hyperv_spinlock_attempts;
623 c = &cpuid_data.entries[cpuid_i++];
624 c->function = HYPERV_CPUID_IMPLEMENT_LIMITS;
625 c->eax = 0x40;
626 c->ebx = 0x40;
628 kvm_base = KVM_CPUID_SIGNATURE_NEXT;
629 has_msr_hv_hypercall = true;
632 if (cpu->expose_kvm) {
633 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
634 c = &cpuid_data.entries[cpuid_i++];
635 c->function = KVM_CPUID_SIGNATURE | kvm_base;
636 c->eax = KVM_CPUID_FEATURES | kvm_base;
637 c->ebx = signature[0];
638 c->ecx = signature[1];
639 c->edx = signature[2];
641 c = &cpuid_data.entries[cpuid_i++];
642 c->function = KVM_CPUID_FEATURES | kvm_base;
643 c->eax = env->features[FEAT_KVM];
645 has_msr_async_pf_en = c->eax & (1 << KVM_FEATURE_ASYNC_PF);
647 has_msr_pv_eoi_en = c->eax & (1 << KVM_FEATURE_PV_EOI);
649 has_msr_kvm_steal_time = c->eax & (1 << KVM_FEATURE_STEAL_TIME);
652 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
654 for (i = 0; i <= limit; i++) {
655 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
656 fprintf(stderr, "unsupported level value: 0x%x\n", limit);
657 abort();
659 c = &cpuid_data.entries[cpuid_i++];
661 switch (i) {
662 case 2: {
663 /* Keep reading function 2 till all the input is received */
664 int times;
666 c->function = i;
667 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
668 KVM_CPUID_FLAG_STATE_READ_NEXT;
669 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
670 times = c->eax & 0xff;
672 for (j = 1; j < times; ++j) {
673 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
674 fprintf(stderr, "cpuid_data is full, no space for "
675 "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
676 abort();
678 c = &cpuid_data.entries[cpuid_i++];
679 c->function = i;
680 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
681 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
683 break;
685 case 4:
686 case 0xb:
687 case 0xd:
688 for (j = 0; ; j++) {
689 if (i == 0xd && j == 64) {
690 break;
692 c->function = i;
693 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
694 c->index = j;
695 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
697 if (i == 4 && c->eax == 0) {
698 break;
700 if (i == 0xb && !(c->ecx & 0xff00)) {
701 break;
703 if (i == 0xd && c->eax == 0) {
704 continue;
706 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
707 fprintf(stderr, "cpuid_data is full, no space for "
708 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
709 abort();
711 c = &cpuid_data.entries[cpuid_i++];
713 break;
714 default:
715 c->function = i;
716 c->flags = 0;
717 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
718 break;
722 if (limit >= 0x0a) {
723 uint32_t ver;
725 cpu_x86_cpuid(env, 0x0a, 0, &ver, &unused, &unused, &unused);
726 if ((ver & 0xff) > 0) {
727 has_msr_architectural_pmu = true;
728 num_architectural_pmu_counters = (ver & 0xff00) >> 8;
730 /* Shouldn't be more than 32, since that's the number of bits
731 * available in EBX to tell us _which_ counters are available.
732 * Play it safe.
734 if (num_architectural_pmu_counters > MAX_GP_COUNTERS) {
735 num_architectural_pmu_counters = MAX_GP_COUNTERS;
740 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
742 for (i = 0x80000000; i <= limit; i++) {
743 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
744 fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
745 abort();
747 c = &cpuid_data.entries[cpuid_i++];
749 c->function = i;
750 c->flags = 0;
751 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
754 /* Call Centaur's CPUID instructions they are supported. */
755 if (env->cpuid_xlevel2 > 0) {
756 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
758 for (i = 0xC0000000; i <= limit; i++) {
759 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
760 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
761 abort();
763 c = &cpuid_data.entries[cpuid_i++];
765 c->function = i;
766 c->flags = 0;
767 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
771 cpuid_data.cpuid.nent = cpuid_i;
773 if (((env->cpuid_version >> 8)&0xF) >= 6
774 && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
775 (CPUID_MCE | CPUID_MCA)
776 && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
777 uint64_t mcg_cap;
778 int banks;
779 int ret;
781 ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
782 if (ret < 0) {
783 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
784 return ret;
787 if (banks > MCE_BANKS_DEF) {
788 banks = MCE_BANKS_DEF;
790 mcg_cap &= MCE_CAP_DEF;
791 mcg_cap |= banks;
792 ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &mcg_cap);
793 if (ret < 0) {
794 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
795 return ret;
798 env->mcg_cap = mcg_cap;
801 qemu_add_vm_change_state_handler(cpu_update_state, env);
803 c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
804 if (c) {
805 has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
806 !!(c->ecx & CPUID_EXT_SMX);
809 c = cpuid_find_entry(&cpuid_data.cpuid, 0x80000007, 0);
810 if (c && (c->edx & 1<<8) && invtsc_mig_blocker == NULL) {
811 /* for migration */
812 error_setg(&invtsc_mig_blocker,
813 "State blocked by non-migratable CPU device"
814 " (invtsc flag)");
815 migrate_add_blocker(invtsc_mig_blocker);
816 /* for savevm */
817 vmstate_x86_cpu.unmigratable = 1;
820 cpuid_data.cpuid.padding = 0;
821 r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
822 if (r) {
823 return r;
826 r = kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL);
827 if (r && env->tsc_khz) {
828 r = kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz);
829 if (r < 0) {
830 fprintf(stderr, "KVM_SET_TSC_KHZ failed\n");
831 return r;
835 if (has_xsave) {
836 env->kvm_xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
839 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
840 has_msr_mtrr = true;
843 return 0;
846 void kvm_arch_reset_vcpu(X86CPU *cpu)
848 CPUX86State *env = &cpu->env;
850 env->exception_injected = -1;
851 env->interrupt_injected = -1;
852 env->xcr0 = 1;
853 if (kvm_irqchip_in_kernel()) {
854 env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
855 KVM_MP_STATE_UNINITIALIZED;
856 } else {
857 env->mp_state = KVM_MP_STATE_RUNNABLE;
861 void kvm_arch_do_init_vcpu(X86CPU *cpu)
863 CPUX86State *env = &cpu->env;
865 /* APs get directly into wait-for-SIPI state. */
866 if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
867 env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
871 static int kvm_get_supported_msrs(KVMState *s)
873 static int kvm_supported_msrs;
874 int ret = 0;
876 /* first time */
877 if (kvm_supported_msrs == 0) {
878 struct kvm_msr_list msr_list, *kvm_msr_list;
880 kvm_supported_msrs = -1;
882 /* Obtain MSR list from KVM. These are the MSRs that we must
883 * save/restore */
884 msr_list.nmsrs = 0;
885 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
886 if (ret < 0 && ret != -E2BIG) {
887 return ret;
889 /* Old kernel modules had a bug and could write beyond the provided
890 memory. Allocate at least a safe amount of 1K. */
891 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
892 msr_list.nmsrs *
893 sizeof(msr_list.indices[0])));
895 kvm_msr_list->nmsrs = msr_list.nmsrs;
896 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
897 if (ret >= 0) {
898 int i;
900 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
901 if (kvm_msr_list->indices[i] == MSR_STAR) {
902 has_msr_star = true;
903 continue;
905 if (kvm_msr_list->indices[i] == MSR_VM_HSAVE_PA) {
906 has_msr_hsave_pa = true;
907 continue;
909 if (kvm_msr_list->indices[i] == MSR_TSC_AUX) {
910 has_msr_tsc_aux = true;
911 continue;
913 if (kvm_msr_list->indices[i] == MSR_TSC_ADJUST) {
914 has_msr_tsc_adjust = true;
915 continue;
917 if (kvm_msr_list->indices[i] == MSR_IA32_TSCDEADLINE) {
918 has_msr_tsc_deadline = true;
919 continue;
921 if (kvm_msr_list->indices[i] == MSR_IA32_SMBASE) {
922 has_msr_smbase = true;
923 continue;
925 if (kvm_msr_list->indices[i] == MSR_IA32_MISC_ENABLE) {
926 has_msr_misc_enable = true;
927 continue;
929 if (kvm_msr_list->indices[i] == MSR_IA32_BNDCFGS) {
930 has_msr_bndcfgs = true;
931 continue;
933 if (kvm_msr_list->indices[i] == MSR_IA32_XSS) {
934 has_msr_xss = true;
935 continue;
937 if (kvm_msr_list->indices[i] == HV_X64_MSR_CRASH_CTL) {
938 has_msr_hv_crash = true;
939 continue;
941 if (kvm_msr_list->indices[i] == HV_X64_MSR_RESET) {
942 has_msr_hv_reset = true;
943 continue;
945 if (kvm_msr_list->indices[i] == HV_X64_MSR_VP_INDEX) {
946 has_msr_hv_vpindex = true;
947 continue;
949 if (kvm_msr_list->indices[i] == HV_X64_MSR_VP_RUNTIME) {
950 has_msr_hv_runtime = true;
951 continue;
956 g_free(kvm_msr_list);
959 return ret;
962 static Notifier smram_machine_done;
963 static KVMMemoryListener smram_listener;
964 static AddressSpace smram_address_space;
965 static MemoryRegion smram_as_root;
966 static MemoryRegion smram_as_mem;
968 static void register_smram_listener(Notifier *n, void *unused)
970 MemoryRegion *smram =
971 (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
973 /* Outer container... */
974 memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
975 memory_region_set_enabled(&smram_as_root, true);
977 /* ... with two regions inside: normal system memory with low
978 * priority, and...
980 memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
981 get_system_memory(), 0, ~0ull);
982 memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
983 memory_region_set_enabled(&smram_as_mem, true);
985 if (smram) {
986 /* ... SMRAM with higher priority */
987 memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
988 memory_region_set_enabled(smram, true);
991 address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
992 kvm_memory_listener_register(kvm_state, &smram_listener,
993 &smram_address_space, 1);
996 int kvm_arch_init(MachineState *ms, KVMState *s)
998 uint64_t identity_base = 0xfffbc000;
999 uint64_t shadow_mem;
1000 int ret;
1001 struct utsname utsname;
1003 #ifdef KVM_CAP_XSAVE
1004 has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1005 #endif
1007 #ifdef KVM_CAP_XCRS
1008 has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1009 #endif
1011 #ifdef KVM_CAP_PIT_STATE2
1012 has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1013 #endif
1015 ret = kvm_get_supported_msrs(s);
1016 if (ret < 0) {
1017 return ret;
1020 uname(&utsname);
1021 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
1024 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
1025 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
1026 * Since these must be part of guest physical memory, we need to allocate
1027 * them, both by setting their start addresses in the kernel and by
1028 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
1030 * Older KVM versions may not support setting the identity map base. In
1031 * that case we need to stick with the default, i.e. a 256K maximum BIOS
1032 * size.
1034 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
1035 /* Allows up to 16M BIOSes. */
1036 identity_base = 0xfeffc000;
1038 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
1039 if (ret < 0) {
1040 return ret;
1044 /* Set TSS base one page after EPT identity map. */
1045 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
1046 if (ret < 0) {
1047 return ret;
1050 /* Tell fw_cfg to notify the BIOS to reserve the range. */
1051 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
1052 if (ret < 0) {
1053 fprintf(stderr, "e820_add_entry() table is full\n");
1054 return ret;
1056 qemu_register_reset(kvm_unpoison_all, NULL);
1058 shadow_mem = machine_kvm_shadow_mem(ms);
1059 if (shadow_mem != -1) {
1060 shadow_mem /= 4096;
1061 ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
1062 if (ret < 0) {
1063 return ret;
1067 if (kvm_check_extension(s, KVM_CAP_X86_SMM)) {
1068 smram_machine_done.notify = register_smram_listener;
1069 qemu_add_machine_init_done_notifier(&smram_machine_done);
1071 return 0;
1074 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1076 lhs->selector = rhs->selector;
1077 lhs->base = rhs->base;
1078 lhs->limit = rhs->limit;
1079 lhs->type = 3;
1080 lhs->present = 1;
1081 lhs->dpl = 3;
1082 lhs->db = 0;
1083 lhs->s = 1;
1084 lhs->l = 0;
1085 lhs->g = 0;
1086 lhs->avl = 0;
1087 lhs->unusable = 0;
1090 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1092 unsigned flags = rhs->flags;
1093 lhs->selector = rhs->selector;
1094 lhs->base = rhs->base;
1095 lhs->limit = rhs->limit;
1096 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
1097 lhs->present = (flags & DESC_P_MASK) != 0;
1098 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
1099 lhs->db = (flags >> DESC_B_SHIFT) & 1;
1100 lhs->s = (flags & DESC_S_MASK) != 0;
1101 lhs->l = (flags >> DESC_L_SHIFT) & 1;
1102 lhs->g = (flags & DESC_G_MASK) != 0;
1103 lhs->avl = (flags & DESC_AVL_MASK) != 0;
1104 lhs->unusable = 0;
1105 lhs->padding = 0;
1108 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
1110 lhs->selector = rhs->selector;
1111 lhs->base = rhs->base;
1112 lhs->limit = rhs->limit;
1113 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
1114 (rhs->present * DESC_P_MASK) |
1115 (rhs->dpl << DESC_DPL_SHIFT) |
1116 (rhs->db << DESC_B_SHIFT) |
1117 (rhs->s * DESC_S_MASK) |
1118 (rhs->l << DESC_L_SHIFT) |
1119 (rhs->g * DESC_G_MASK) |
1120 (rhs->avl * DESC_AVL_MASK);
1123 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
1125 if (set) {
1126 *kvm_reg = *qemu_reg;
1127 } else {
1128 *qemu_reg = *kvm_reg;
1132 static int kvm_getput_regs(X86CPU *cpu, int set)
1134 CPUX86State *env = &cpu->env;
1135 struct kvm_regs regs;
1136 int ret = 0;
1138 if (!set) {
1139 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
1140 if (ret < 0) {
1141 return ret;
1145 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
1146 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
1147 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
1148 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
1149 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
1150 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
1151 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
1152 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
1153 #ifdef TARGET_X86_64
1154 kvm_getput_reg(&regs.r8, &env->regs[8], set);
1155 kvm_getput_reg(&regs.r9, &env->regs[9], set);
1156 kvm_getput_reg(&regs.r10, &env->regs[10], set);
1157 kvm_getput_reg(&regs.r11, &env->regs[11], set);
1158 kvm_getput_reg(&regs.r12, &env->regs[12], set);
1159 kvm_getput_reg(&regs.r13, &env->regs[13], set);
1160 kvm_getput_reg(&regs.r14, &env->regs[14], set);
1161 kvm_getput_reg(&regs.r15, &env->regs[15], set);
1162 #endif
1164 kvm_getput_reg(&regs.rflags, &env->eflags, set);
1165 kvm_getput_reg(&regs.rip, &env->eip, set);
1167 if (set) {
1168 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
1171 return ret;
1174 static int kvm_put_fpu(X86CPU *cpu)
1176 CPUX86State *env = &cpu->env;
1177 struct kvm_fpu fpu;
1178 int i;
1180 memset(&fpu, 0, sizeof fpu);
1181 fpu.fsw = env->fpus & ~(7 << 11);
1182 fpu.fsw |= (env->fpstt & 7) << 11;
1183 fpu.fcw = env->fpuc;
1184 fpu.last_opcode = env->fpop;
1185 fpu.last_ip = env->fpip;
1186 fpu.last_dp = env->fpdp;
1187 for (i = 0; i < 8; ++i) {
1188 fpu.ftwx |= (!env->fptags[i]) << i;
1190 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
1191 for (i = 0; i < CPU_NB_REGS; i++) {
1192 stq_p(&fpu.xmm[i][0], env->xmm_regs[i].XMM_Q(0));
1193 stq_p(&fpu.xmm[i][8], env->xmm_regs[i].XMM_Q(1));
1195 fpu.mxcsr = env->mxcsr;
1197 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
1200 #define XSAVE_FCW_FSW 0
1201 #define XSAVE_FTW_FOP 1
1202 #define XSAVE_CWD_RIP 2
1203 #define XSAVE_CWD_RDP 4
1204 #define XSAVE_MXCSR 6
1205 #define XSAVE_ST_SPACE 8
1206 #define XSAVE_XMM_SPACE 40
1207 #define XSAVE_XSTATE_BV 128
1208 #define XSAVE_YMMH_SPACE 144
1209 #define XSAVE_BNDREGS 240
1210 #define XSAVE_BNDCSR 256
1211 #define XSAVE_OPMASK 272
1212 #define XSAVE_ZMM_Hi256 288
1213 #define XSAVE_Hi16_ZMM 416
1215 static int kvm_put_xsave(X86CPU *cpu)
1217 CPUX86State *env = &cpu->env;
1218 struct kvm_xsave* xsave = env->kvm_xsave_buf;
1219 uint16_t cwd, swd, twd;
1220 uint8_t *xmm, *ymmh, *zmmh;
1221 int i, r;
1223 if (!has_xsave) {
1224 return kvm_put_fpu(cpu);
1227 memset(xsave, 0, sizeof(struct kvm_xsave));
1228 twd = 0;
1229 swd = env->fpus & ~(7 << 11);
1230 swd |= (env->fpstt & 7) << 11;
1231 cwd = env->fpuc;
1232 for (i = 0; i < 8; ++i) {
1233 twd |= (!env->fptags[i]) << i;
1235 xsave->region[XSAVE_FCW_FSW] = (uint32_t)(swd << 16) + cwd;
1236 xsave->region[XSAVE_FTW_FOP] = (uint32_t)(env->fpop << 16) + twd;
1237 memcpy(&xsave->region[XSAVE_CWD_RIP], &env->fpip, sizeof(env->fpip));
1238 memcpy(&xsave->region[XSAVE_CWD_RDP], &env->fpdp, sizeof(env->fpdp));
1239 memcpy(&xsave->region[XSAVE_ST_SPACE], env->fpregs,
1240 sizeof env->fpregs);
1241 xsave->region[XSAVE_MXCSR] = env->mxcsr;
1242 *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV] = env->xstate_bv;
1243 memcpy(&xsave->region[XSAVE_BNDREGS], env->bnd_regs,
1244 sizeof env->bnd_regs);
1245 memcpy(&xsave->region[XSAVE_BNDCSR], &env->bndcs_regs,
1246 sizeof(env->bndcs_regs));
1247 memcpy(&xsave->region[XSAVE_OPMASK], env->opmask_regs,
1248 sizeof env->opmask_regs);
1250 xmm = (uint8_t *)&xsave->region[XSAVE_XMM_SPACE];
1251 ymmh = (uint8_t *)&xsave->region[XSAVE_YMMH_SPACE];
1252 zmmh = (uint8_t *)&xsave->region[XSAVE_ZMM_Hi256];
1253 for (i = 0; i < CPU_NB_REGS; i++, xmm += 16, ymmh += 16, zmmh += 32) {
1254 stq_p(xmm, env->xmm_regs[i].XMM_Q(0));
1255 stq_p(xmm+8, env->xmm_regs[i].XMM_Q(1));
1256 stq_p(ymmh, env->xmm_regs[i].XMM_Q(2));
1257 stq_p(ymmh+8, env->xmm_regs[i].XMM_Q(3));
1258 stq_p(zmmh, env->xmm_regs[i].XMM_Q(4));
1259 stq_p(zmmh+8, env->xmm_regs[i].XMM_Q(5));
1260 stq_p(zmmh+16, env->xmm_regs[i].XMM_Q(6));
1261 stq_p(zmmh+24, env->xmm_regs[i].XMM_Q(7));
1264 #ifdef TARGET_X86_64
1265 memcpy(&xsave->region[XSAVE_Hi16_ZMM], &env->xmm_regs[16],
1266 16 * sizeof env->xmm_regs[16]);
1267 #endif
1268 r = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
1269 return r;
1272 static int kvm_put_xcrs(X86CPU *cpu)
1274 CPUX86State *env = &cpu->env;
1275 struct kvm_xcrs xcrs = {};
1277 if (!has_xcrs) {
1278 return 0;
1281 xcrs.nr_xcrs = 1;
1282 xcrs.flags = 0;
1283 xcrs.xcrs[0].xcr = 0;
1284 xcrs.xcrs[0].value = env->xcr0;
1285 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
1288 static int kvm_put_sregs(X86CPU *cpu)
1290 CPUX86State *env = &cpu->env;
1291 struct kvm_sregs sregs;
1293 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
1294 if (env->interrupt_injected >= 0) {
1295 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
1296 (uint64_t)1 << (env->interrupt_injected % 64);
1299 if ((env->eflags & VM_MASK)) {
1300 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
1301 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
1302 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
1303 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
1304 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
1305 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
1306 } else {
1307 set_seg(&sregs.cs, &env->segs[R_CS]);
1308 set_seg(&sregs.ds, &env->segs[R_DS]);
1309 set_seg(&sregs.es, &env->segs[R_ES]);
1310 set_seg(&sregs.fs, &env->segs[R_FS]);
1311 set_seg(&sregs.gs, &env->segs[R_GS]);
1312 set_seg(&sregs.ss, &env->segs[R_SS]);
1315 set_seg(&sregs.tr, &env->tr);
1316 set_seg(&sregs.ldt, &env->ldt);
1318 sregs.idt.limit = env->idt.limit;
1319 sregs.idt.base = env->idt.base;
1320 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
1321 sregs.gdt.limit = env->gdt.limit;
1322 sregs.gdt.base = env->gdt.base;
1323 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
1325 sregs.cr0 = env->cr[0];
1326 sregs.cr2 = env->cr[2];
1327 sregs.cr3 = env->cr[3];
1328 sregs.cr4 = env->cr[4];
1330 sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
1331 sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
1333 sregs.efer = env->efer;
1335 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
1338 static void kvm_msr_entry_set(struct kvm_msr_entry *entry,
1339 uint32_t index, uint64_t value)
1341 entry->index = index;
1342 entry->reserved = 0;
1343 entry->data = value;
1346 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
1348 CPUX86State *env = &cpu->env;
1349 struct {
1350 struct kvm_msrs info;
1351 struct kvm_msr_entry entries[1];
1352 } msr_data;
1353 struct kvm_msr_entry *msrs = msr_data.entries;
1355 if (!has_msr_tsc_deadline) {
1356 return 0;
1359 kvm_msr_entry_set(&msrs[0], MSR_IA32_TSCDEADLINE, env->tsc_deadline);
1361 msr_data.info = (struct kvm_msrs) {
1362 .nmsrs = 1,
1365 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, &msr_data);
1369 * Provide a separate write service for the feature control MSR in order to
1370 * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
1371 * before writing any other state because forcibly leaving nested mode
1372 * invalidates the VCPU state.
1374 static int kvm_put_msr_feature_control(X86CPU *cpu)
1376 struct {
1377 struct kvm_msrs info;
1378 struct kvm_msr_entry entry;
1379 } msr_data;
1381 kvm_msr_entry_set(&msr_data.entry, MSR_IA32_FEATURE_CONTROL,
1382 cpu->env.msr_ia32_feature_control);
1384 msr_data.info = (struct kvm_msrs) {
1385 .nmsrs = 1,
1388 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, &msr_data);
1391 static int kvm_put_msrs(X86CPU *cpu, int level)
1393 CPUX86State *env = &cpu->env;
1394 struct {
1395 struct kvm_msrs info;
1396 struct kvm_msr_entry entries[150];
1397 } msr_data;
1398 struct kvm_msr_entry *msrs = msr_data.entries;
1399 int n = 0, i;
1401 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_CS, env->sysenter_cs);
1402 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
1403 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
1404 kvm_msr_entry_set(&msrs[n++], MSR_PAT, env->pat);
1405 if (has_msr_star) {
1406 kvm_msr_entry_set(&msrs[n++], MSR_STAR, env->star);
1408 if (has_msr_hsave_pa) {
1409 kvm_msr_entry_set(&msrs[n++], MSR_VM_HSAVE_PA, env->vm_hsave);
1411 if (has_msr_tsc_aux) {
1412 kvm_msr_entry_set(&msrs[n++], MSR_TSC_AUX, env->tsc_aux);
1414 if (has_msr_tsc_adjust) {
1415 kvm_msr_entry_set(&msrs[n++], MSR_TSC_ADJUST, env->tsc_adjust);
1417 if (has_msr_misc_enable) {
1418 kvm_msr_entry_set(&msrs[n++], MSR_IA32_MISC_ENABLE,
1419 env->msr_ia32_misc_enable);
1421 if (has_msr_smbase) {
1422 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SMBASE, env->smbase);
1424 if (has_msr_bndcfgs) {
1425 kvm_msr_entry_set(&msrs[n++], MSR_IA32_BNDCFGS, env->msr_bndcfgs);
1427 if (has_msr_xss) {
1428 kvm_msr_entry_set(&msrs[n++], MSR_IA32_XSS, env->xss);
1430 #ifdef TARGET_X86_64
1431 if (lm_capable_kernel) {
1432 kvm_msr_entry_set(&msrs[n++], MSR_CSTAR, env->cstar);
1433 kvm_msr_entry_set(&msrs[n++], MSR_KERNELGSBASE, env->kernelgsbase);
1434 kvm_msr_entry_set(&msrs[n++], MSR_FMASK, env->fmask);
1435 kvm_msr_entry_set(&msrs[n++], MSR_LSTAR, env->lstar);
1437 #endif
1439 * The following MSRs have side effects on the guest or are too heavy
1440 * for normal writeback. Limit them to reset or full state updates.
1442 if (level >= KVM_PUT_RESET_STATE) {
1443 kvm_msr_entry_set(&msrs[n++], MSR_IA32_TSC, env->tsc);
1444 kvm_msr_entry_set(&msrs[n++], MSR_KVM_SYSTEM_TIME,
1445 env->system_time_msr);
1446 kvm_msr_entry_set(&msrs[n++], MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
1447 if (has_msr_async_pf_en) {
1448 kvm_msr_entry_set(&msrs[n++], MSR_KVM_ASYNC_PF_EN,
1449 env->async_pf_en_msr);
1451 if (has_msr_pv_eoi_en) {
1452 kvm_msr_entry_set(&msrs[n++], MSR_KVM_PV_EOI_EN,
1453 env->pv_eoi_en_msr);
1455 if (has_msr_kvm_steal_time) {
1456 kvm_msr_entry_set(&msrs[n++], MSR_KVM_STEAL_TIME,
1457 env->steal_time_msr);
1459 if (has_msr_architectural_pmu) {
1460 /* Stop the counter. */
1461 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
1462 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_GLOBAL_CTRL, 0);
1464 /* Set the counter values. */
1465 for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
1466 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_FIXED_CTR0 + i,
1467 env->msr_fixed_counters[i]);
1469 for (i = 0; i < num_architectural_pmu_counters; i++) {
1470 kvm_msr_entry_set(&msrs[n++], MSR_P6_PERFCTR0 + i,
1471 env->msr_gp_counters[i]);
1472 kvm_msr_entry_set(&msrs[n++], MSR_P6_EVNTSEL0 + i,
1473 env->msr_gp_evtsel[i]);
1475 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_GLOBAL_STATUS,
1476 env->msr_global_status);
1477 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1478 env->msr_global_ovf_ctrl);
1480 /* Now start the PMU. */
1481 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_FIXED_CTR_CTRL,
1482 env->msr_fixed_ctr_ctrl);
1483 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_GLOBAL_CTRL,
1484 env->msr_global_ctrl);
1486 if (has_msr_hv_hypercall) {
1487 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_GUEST_OS_ID,
1488 env->msr_hv_guest_os_id);
1489 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_HYPERCALL,
1490 env->msr_hv_hypercall);
1492 if (has_msr_hv_vapic) {
1493 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_APIC_ASSIST_PAGE,
1494 env->msr_hv_vapic);
1496 if (has_msr_hv_tsc) {
1497 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_REFERENCE_TSC,
1498 env->msr_hv_tsc);
1500 if (has_msr_hv_crash) {
1501 int j;
1503 for (j = 0; j < HV_X64_MSR_CRASH_PARAMS; j++)
1504 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_CRASH_P0 + j,
1505 env->msr_hv_crash_params[j]);
1507 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_CRASH_CTL,
1508 HV_X64_MSR_CRASH_CTL_NOTIFY);
1510 if (has_msr_hv_runtime) {
1511 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_VP_RUNTIME,
1512 env->msr_hv_runtime);
1514 if (has_msr_mtrr) {
1515 kvm_msr_entry_set(&msrs[n++], MSR_MTRRdefType, env->mtrr_deftype);
1516 kvm_msr_entry_set(&msrs[n++],
1517 MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
1518 kvm_msr_entry_set(&msrs[n++],
1519 MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
1520 kvm_msr_entry_set(&msrs[n++],
1521 MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
1522 kvm_msr_entry_set(&msrs[n++],
1523 MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
1524 kvm_msr_entry_set(&msrs[n++],
1525 MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
1526 kvm_msr_entry_set(&msrs[n++],
1527 MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
1528 kvm_msr_entry_set(&msrs[n++],
1529 MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
1530 kvm_msr_entry_set(&msrs[n++],
1531 MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
1532 kvm_msr_entry_set(&msrs[n++],
1533 MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
1534 kvm_msr_entry_set(&msrs[n++],
1535 MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
1536 kvm_msr_entry_set(&msrs[n++],
1537 MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
1538 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
1539 kvm_msr_entry_set(&msrs[n++],
1540 MSR_MTRRphysBase(i), env->mtrr_var[i].base);
1541 kvm_msr_entry_set(&msrs[n++],
1542 MSR_MTRRphysMask(i), env->mtrr_var[i].mask);
1546 /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
1547 * kvm_put_msr_feature_control. */
1549 if (env->mcg_cap) {
1550 int i;
1552 kvm_msr_entry_set(&msrs[n++], MSR_MCG_STATUS, env->mcg_status);
1553 kvm_msr_entry_set(&msrs[n++], MSR_MCG_CTL, env->mcg_ctl);
1554 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1555 kvm_msr_entry_set(&msrs[n++], MSR_MC0_CTL + i, env->mce_banks[i]);
1559 msr_data.info = (struct kvm_msrs) {
1560 .nmsrs = n,
1563 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, &msr_data);
1568 static int kvm_get_fpu(X86CPU *cpu)
1570 CPUX86State *env = &cpu->env;
1571 struct kvm_fpu fpu;
1572 int i, ret;
1574 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
1575 if (ret < 0) {
1576 return ret;
1579 env->fpstt = (fpu.fsw >> 11) & 7;
1580 env->fpus = fpu.fsw;
1581 env->fpuc = fpu.fcw;
1582 env->fpop = fpu.last_opcode;
1583 env->fpip = fpu.last_ip;
1584 env->fpdp = fpu.last_dp;
1585 for (i = 0; i < 8; ++i) {
1586 env->fptags[i] = !((fpu.ftwx >> i) & 1);
1588 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
1589 for (i = 0; i < CPU_NB_REGS; i++) {
1590 env->xmm_regs[i].XMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
1591 env->xmm_regs[i].XMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
1593 env->mxcsr = fpu.mxcsr;
1595 return 0;
1598 static int kvm_get_xsave(X86CPU *cpu)
1600 CPUX86State *env = &cpu->env;
1601 struct kvm_xsave* xsave = env->kvm_xsave_buf;
1602 int ret, i;
1603 const uint8_t *xmm, *ymmh, *zmmh;
1604 uint16_t cwd, swd, twd;
1606 if (!has_xsave) {
1607 return kvm_get_fpu(cpu);
1610 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
1611 if (ret < 0) {
1612 return ret;
1615 cwd = (uint16_t)xsave->region[XSAVE_FCW_FSW];
1616 swd = (uint16_t)(xsave->region[XSAVE_FCW_FSW] >> 16);
1617 twd = (uint16_t)xsave->region[XSAVE_FTW_FOP];
1618 env->fpop = (uint16_t)(xsave->region[XSAVE_FTW_FOP] >> 16);
1619 env->fpstt = (swd >> 11) & 7;
1620 env->fpus = swd;
1621 env->fpuc = cwd;
1622 for (i = 0; i < 8; ++i) {
1623 env->fptags[i] = !((twd >> i) & 1);
1625 memcpy(&env->fpip, &xsave->region[XSAVE_CWD_RIP], sizeof(env->fpip));
1626 memcpy(&env->fpdp, &xsave->region[XSAVE_CWD_RDP], sizeof(env->fpdp));
1627 env->mxcsr = xsave->region[XSAVE_MXCSR];
1628 memcpy(env->fpregs, &xsave->region[XSAVE_ST_SPACE],
1629 sizeof env->fpregs);
1630 env->xstate_bv = *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV];
1631 memcpy(env->bnd_regs, &xsave->region[XSAVE_BNDREGS],
1632 sizeof env->bnd_regs);
1633 memcpy(&env->bndcs_regs, &xsave->region[XSAVE_BNDCSR],
1634 sizeof(env->bndcs_regs));
1635 memcpy(env->opmask_regs, &xsave->region[XSAVE_OPMASK],
1636 sizeof env->opmask_regs);
1638 xmm = (const uint8_t *)&xsave->region[XSAVE_XMM_SPACE];
1639 ymmh = (const uint8_t *)&xsave->region[XSAVE_YMMH_SPACE];
1640 zmmh = (const uint8_t *)&xsave->region[XSAVE_ZMM_Hi256];
1641 for (i = 0; i < CPU_NB_REGS; i++, xmm += 16, ymmh += 16, zmmh += 32) {
1642 env->xmm_regs[i].XMM_Q(0) = ldq_p(xmm);
1643 env->xmm_regs[i].XMM_Q(1) = ldq_p(xmm+8);
1644 env->xmm_regs[i].XMM_Q(2) = ldq_p(ymmh);
1645 env->xmm_regs[i].XMM_Q(3) = ldq_p(ymmh+8);
1646 env->xmm_regs[i].XMM_Q(4) = ldq_p(zmmh);
1647 env->xmm_regs[i].XMM_Q(5) = ldq_p(zmmh+8);
1648 env->xmm_regs[i].XMM_Q(6) = ldq_p(zmmh+16);
1649 env->xmm_regs[i].XMM_Q(7) = ldq_p(zmmh+24);
1652 #ifdef TARGET_X86_64
1653 memcpy(&env->xmm_regs[16], &xsave->region[XSAVE_Hi16_ZMM],
1654 16 * sizeof env->xmm_regs[16]);
1655 #endif
1656 return 0;
1659 static int kvm_get_xcrs(X86CPU *cpu)
1661 CPUX86State *env = &cpu->env;
1662 int i, ret;
1663 struct kvm_xcrs xcrs;
1665 if (!has_xcrs) {
1666 return 0;
1669 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
1670 if (ret < 0) {
1671 return ret;
1674 for (i = 0; i < xcrs.nr_xcrs; i++) {
1675 /* Only support xcr0 now */
1676 if (xcrs.xcrs[i].xcr == 0) {
1677 env->xcr0 = xcrs.xcrs[i].value;
1678 break;
1681 return 0;
1684 static int kvm_get_sregs(X86CPU *cpu)
1686 CPUX86State *env = &cpu->env;
1687 struct kvm_sregs sregs;
1688 uint32_t hflags;
1689 int bit, i, ret;
1691 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
1692 if (ret < 0) {
1693 return ret;
1696 /* There can only be one pending IRQ set in the bitmap at a time, so try
1697 to find it and save its number instead (-1 for none). */
1698 env->interrupt_injected = -1;
1699 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
1700 if (sregs.interrupt_bitmap[i]) {
1701 bit = ctz64(sregs.interrupt_bitmap[i]);
1702 env->interrupt_injected = i * 64 + bit;
1703 break;
1707 get_seg(&env->segs[R_CS], &sregs.cs);
1708 get_seg(&env->segs[R_DS], &sregs.ds);
1709 get_seg(&env->segs[R_ES], &sregs.es);
1710 get_seg(&env->segs[R_FS], &sregs.fs);
1711 get_seg(&env->segs[R_GS], &sregs.gs);
1712 get_seg(&env->segs[R_SS], &sregs.ss);
1714 get_seg(&env->tr, &sregs.tr);
1715 get_seg(&env->ldt, &sregs.ldt);
1717 env->idt.limit = sregs.idt.limit;
1718 env->idt.base = sregs.idt.base;
1719 env->gdt.limit = sregs.gdt.limit;
1720 env->gdt.base = sregs.gdt.base;
1722 env->cr[0] = sregs.cr0;
1723 env->cr[2] = sregs.cr2;
1724 env->cr[3] = sregs.cr3;
1725 env->cr[4] = sregs.cr4;
1727 env->efer = sregs.efer;
1729 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
1731 #define HFLAG_COPY_MASK \
1732 ~( HF_CPL_MASK | HF_PE_MASK | HF_MP_MASK | HF_EM_MASK | \
1733 HF_TS_MASK | HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK | \
1734 HF_OSFXSR_MASK | HF_LMA_MASK | HF_CS32_MASK | \
1735 HF_SS32_MASK | HF_CS64_MASK | HF_ADDSEG_MASK)
1737 hflags = (env->segs[R_SS].flags >> DESC_DPL_SHIFT) & HF_CPL_MASK;
1738 hflags |= (env->cr[0] & CR0_PE_MASK) << (HF_PE_SHIFT - CR0_PE_SHIFT);
1739 hflags |= (env->cr[0] << (HF_MP_SHIFT - CR0_MP_SHIFT)) &
1740 (HF_MP_MASK | HF_EM_MASK | HF_TS_MASK);
1741 hflags |= (env->eflags & (HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK));
1742 hflags |= (env->cr[4] & CR4_OSFXSR_MASK) <<
1743 (HF_OSFXSR_SHIFT - CR4_OSFXSR_SHIFT);
1745 if (env->efer & MSR_EFER_LMA) {
1746 hflags |= HF_LMA_MASK;
1749 if ((hflags & HF_LMA_MASK) && (env->segs[R_CS].flags & DESC_L_MASK)) {
1750 hflags |= HF_CS32_MASK | HF_SS32_MASK | HF_CS64_MASK;
1751 } else {
1752 hflags |= (env->segs[R_CS].flags & DESC_B_MASK) >>
1753 (DESC_B_SHIFT - HF_CS32_SHIFT);
1754 hflags |= (env->segs[R_SS].flags & DESC_B_MASK) >>
1755 (DESC_B_SHIFT - HF_SS32_SHIFT);
1756 if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK) ||
1757 !(hflags & HF_CS32_MASK)) {
1758 hflags |= HF_ADDSEG_MASK;
1759 } else {
1760 hflags |= ((env->segs[R_DS].base | env->segs[R_ES].base |
1761 env->segs[R_SS].base) != 0) << HF_ADDSEG_SHIFT;
1764 env->hflags = (env->hflags & HFLAG_COPY_MASK) | hflags;
1766 return 0;
1769 static int kvm_get_msrs(X86CPU *cpu)
1771 CPUX86State *env = &cpu->env;
1772 struct {
1773 struct kvm_msrs info;
1774 struct kvm_msr_entry entries[150];
1775 } msr_data;
1776 struct kvm_msr_entry *msrs = msr_data.entries;
1777 int ret, i, n;
1779 n = 0;
1780 msrs[n++].index = MSR_IA32_SYSENTER_CS;
1781 msrs[n++].index = MSR_IA32_SYSENTER_ESP;
1782 msrs[n++].index = MSR_IA32_SYSENTER_EIP;
1783 msrs[n++].index = MSR_PAT;
1784 if (has_msr_star) {
1785 msrs[n++].index = MSR_STAR;
1787 if (has_msr_hsave_pa) {
1788 msrs[n++].index = MSR_VM_HSAVE_PA;
1790 if (has_msr_tsc_aux) {
1791 msrs[n++].index = MSR_TSC_AUX;
1793 if (has_msr_tsc_adjust) {
1794 msrs[n++].index = MSR_TSC_ADJUST;
1796 if (has_msr_tsc_deadline) {
1797 msrs[n++].index = MSR_IA32_TSCDEADLINE;
1799 if (has_msr_misc_enable) {
1800 msrs[n++].index = MSR_IA32_MISC_ENABLE;
1802 if (has_msr_smbase) {
1803 msrs[n++].index = MSR_IA32_SMBASE;
1805 if (has_msr_feature_control) {
1806 msrs[n++].index = MSR_IA32_FEATURE_CONTROL;
1808 if (has_msr_bndcfgs) {
1809 msrs[n++].index = MSR_IA32_BNDCFGS;
1811 if (has_msr_xss) {
1812 msrs[n++].index = MSR_IA32_XSS;
1816 if (!env->tsc_valid) {
1817 msrs[n++].index = MSR_IA32_TSC;
1818 env->tsc_valid = !runstate_is_running();
1821 #ifdef TARGET_X86_64
1822 if (lm_capable_kernel) {
1823 msrs[n++].index = MSR_CSTAR;
1824 msrs[n++].index = MSR_KERNELGSBASE;
1825 msrs[n++].index = MSR_FMASK;
1826 msrs[n++].index = MSR_LSTAR;
1828 #endif
1829 msrs[n++].index = MSR_KVM_SYSTEM_TIME;
1830 msrs[n++].index = MSR_KVM_WALL_CLOCK;
1831 if (has_msr_async_pf_en) {
1832 msrs[n++].index = MSR_KVM_ASYNC_PF_EN;
1834 if (has_msr_pv_eoi_en) {
1835 msrs[n++].index = MSR_KVM_PV_EOI_EN;
1837 if (has_msr_kvm_steal_time) {
1838 msrs[n++].index = MSR_KVM_STEAL_TIME;
1840 if (has_msr_architectural_pmu) {
1841 msrs[n++].index = MSR_CORE_PERF_FIXED_CTR_CTRL;
1842 msrs[n++].index = MSR_CORE_PERF_GLOBAL_CTRL;
1843 msrs[n++].index = MSR_CORE_PERF_GLOBAL_STATUS;
1844 msrs[n++].index = MSR_CORE_PERF_GLOBAL_OVF_CTRL;
1845 for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
1846 msrs[n++].index = MSR_CORE_PERF_FIXED_CTR0 + i;
1848 for (i = 0; i < num_architectural_pmu_counters; i++) {
1849 msrs[n++].index = MSR_P6_PERFCTR0 + i;
1850 msrs[n++].index = MSR_P6_EVNTSEL0 + i;
1854 if (env->mcg_cap) {
1855 msrs[n++].index = MSR_MCG_STATUS;
1856 msrs[n++].index = MSR_MCG_CTL;
1857 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1858 msrs[n++].index = MSR_MC0_CTL + i;
1862 if (has_msr_hv_hypercall) {
1863 msrs[n++].index = HV_X64_MSR_HYPERCALL;
1864 msrs[n++].index = HV_X64_MSR_GUEST_OS_ID;
1866 if (has_msr_hv_vapic) {
1867 msrs[n++].index = HV_X64_MSR_APIC_ASSIST_PAGE;
1869 if (has_msr_hv_tsc) {
1870 msrs[n++].index = HV_X64_MSR_REFERENCE_TSC;
1872 if (has_msr_hv_crash) {
1873 int j;
1875 for (j = 0; j < HV_X64_MSR_CRASH_PARAMS; j++) {
1876 msrs[n++].index = HV_X64_MSR_CRASH_P0 + j;
1879 if (has_msr_hv_runtime) {
1880 msrs[n++].index = HV_X64_MSR_VP_RUNTIME;
1882 if (has_msr_mtrr) {
1883 msrs[n++].index = MSR_MTRRdefType;
1884 msrs[n++].index = MSR_MTRRfix64K_00000;
1885 msrs[n++].index = MSR_MTRRfix16K_80000;
1886 msrs[n++].index = MSR_MTRRfix16K_A0000;
1887 msrs[n++].index = MSR_MTRRfix4K_C0000;
1888 msrs[n++].index = MSR_MTRRfix4K_C8000;
1889 msrs[n++].index = MSR_MTRRfix4K_D0000;
1890 msrs[n++].index = MSR_MTRRfix4K_D8000;
1891 msrs[n++].index = MSR_MTRRfix4K_E0000;
1892 msrs[n++].index = MSR_MTRRfix4K_E8000;
1893 msrs[n++].index = MSR_MTRRfix4K_F0000;
1894 msrs[n++].index = MSR_MTRRfix4K_F8000;
1895 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
1896 msrs[n++].index = MSR_MTRRphysBase(i);
1897 msrs[n++].index = MSR_MTRRphysMask(i);
1901 msr_data.info = (struct kvm_msrs) {
1902 .nmsrs = n,
1905 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
1906 if (ret < 0) {
1907 return ret;
1910 for (i = 0; i < ret; i++) {
1911 uint32_t index = msrs[i].index;
1912 switch (index) {
1913 case MSR_IA32_SYSENTER_CS:
1914 env->sysenter_cs = msrs[i].data;
1915 break;
1916 case MSR_IA32_SYSENTER_ESP:
1917 env->sysenter_esp = msrs[i].data;
1918 break;
1919 case MSR_IA32_SYSENTER_EIP:
1920 env->sysenter_eip = msrs[i].data;
1921 break;
1922 case MSR_PAT:
1923 env->pat = msrs[i].data;
1924 break;
1925 case MSR_STAR:
1926 env->star = msrs[i].data;
1927 break;
1928 #ifdef TARGET_X86_64
1929 case MSR_CSTAR:
1930 env->cstar = msrs[i].data;
1931 break;
1932 case MSR_KERNELGSBASE:
1933 env->kernelgsbase = msrs[i].data;
1934 break;
1935 case MSR_FMASK:
1936 env->fmask = msrs[i].data;
1937 break;
1938 case MSR_LSTAR:
1939 env->lstar = msrs[i].data;
1940 break;
1941 #endif
1942 case MSR_IA32_TSC:
1943 env->tsc = msrs[i].data;
1944 break;
1945 case MSR_TSC_AUX:
1946 env->tsc_aux = msrs[i].data;
1947 break;
1948 case MSR_TSC_ADJUST:
1949 env->tsc_adjust = msrs[i].data;
1950 break;
1951 case MSR_IA32_TSCDEADLINE:
1952 env->tsc_deadline = msrs[i].data;
1953 break;
1954 case MSR_VM_HSAVE_PA:
1955 env->vm_hsave = msrs[i].data;
1956 break;
1957 case MSR_KVM_SYSTEM_TIME:
1958 env->system_time_msr = msrs[i].data;
1959 break;
1960 case MSR_KVM_WALL_CLOCK:
1961 env->wall_clock_msr = msrs[i].data;
1962 break;
1963 case MSR_MCG_STATUS:
1964 env->mcg_status = msrs[i].data;
1965 break;
1966 case MSR_MCG_CTL:
1967 env->mcg_ctl = msrs[i].data;
1968 break;
1969 case MSR_IA32_MISC_ENABLE:
1970 env->msr_ia32_misc_enable = msrs[i].data;
1971 break;
1972 case MSR_IA32_SMBASE:
1973 env->smbase = msrs[i].data;
1974 break;
1975 case MSR_IA32_FEATURE_CONTROL:
1976 env->msr_ia32_feature_control = msrs[i].data;
1977 break;
1978 case MSR_IA32_BNDCFGS:
1979 env->msr_bndcfgs = msrs[i].data;
1980 break;
1981 case MSR_IA32_XSS:
1982 env->xss = msrs[i].data;
1983 break;
1984 default:
1985 if (msrs[i].index >= MSR_MC0_CTL &&
1986 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
1987 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
1989 break;
1990 case MSR_KVM_ASYNC_PF_EN:
1991 env->async_pf_en_msr = msrs[i].data;
1992 break;
1993 case MSR_KVM_PV_EOI_EN:
1994 env->pv_eoi_en_msr = msrs[i].data;
1995 break;
1996 case MSR_KVM_STEAL_TIME:
1997 env->steal_time_msr = msrs[i].data;
1998 break;
1999 case MSR_CORE_PERF_FIXED_CTR_CTRL:
2000 env->msr_fixed_ctr_ctrl = msrs[i].data;
2001 break;
2002 case MSR_CORE_PERF_GLOBAL_CTRL:
2003 env->msr_global_ctrl = msrs[i].data;
2004 break;
2005 case MSR_CORE_PERF_GLOBAL_STATUS:
2006 env->msr_global_status = msrs[i].data;
2007 break;
2008 case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
2009 env->msr_global_ovf_ctrl = msrs[i].data;
2010 break;
2011 case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
2012 env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
2013 break;
2014 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
2015 env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
2016 break;
2017 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
2018 env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
2019 break;
2020 case HV_X64_MSR_HYPERCALL:
2021 env->msr_hv_hypercall = msrs[i].data;
2022 break;
2023 case HV_X64_MSR_GUEST_OS_ID:
2024 env->msr_hv_guest_os_id = msrs[i].data;
2025 break;
2026 case HV_X64_MSR_APIC_ASSIST_PAGE:
2027 env->msr_hv_vapic = msrs[i].data;
2028 break;
2029 case HV_X64_MSR_REFERENCE_TSC:
2030 env->msr_hv_tsc = msrs[i].data;
2031 break;
2032 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2033 env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
2034 break;
2035 case HV_X64_MSR_VP_RUNTIME:
2036 env->msr_hv_runtime = msrs[i].data;
2037 break;
2038 case MSR_MTRRdefType:
2039 env->mtrr_deftype = msrs[i].data;
2040 break;
2041 case MSR_MTRRfix64K_00000:
2042 env->mtrr_fixed[0] = msrs[i].data;
2043 break;
2044 case MSR_MTRRfix16K_80000:
2045 env->mtrr_fixed[1] = msrs[i].data;
2046 break;
2047 case MSR_MTRRfix16K_A0000:
2048 env->mtrr_fixed[2] = msrs[i].data;
2049 break;
2050 case MSR_MTRRfix4K_C0000:
2051 env->mtrr_fixed[3] = msrs[i].data;
2052 break;
2053 case MSR_MTRRfix4K_C8000:
2054 env->mtrr_fixed[4] = msrs[i].data;
2055 break;
2056 case MSR_MTRRfix4K_D0000:
2057 env->mtrr_fixed[5] = msrs[i].data;
2058 break;
2059 case MSR_MTRRfix4K_D8000:
2060 env->mtrr_fixed[6] = msrs[i].data;
2061 break;
2062 case MSR_MTRRfix4K_E0000:
2063 env->mtrr_fixed[7] = msrs[i].data;
2064 break;
2065 case MSR_MTRRfix4K_E8000:
2066 env->mtrr_fixed[8] = msrs[i].data;
2067 break;
2068 case MSR_MTRRfix4K_F0000:
2069 env->mtrr_fixed[9] = msrs[i].data;
2070 break;
2071 case MSR_MTRRfix4K_F8000:
2072 env->mtrr_fixed[10] = msrs[i].data;
2073 break;
2074 case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
2075 if (index & 1) {
2076 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data;
2077 } else {
2078 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
2080 break;
2084 return 0;
2087 static int kvm_put_mp_state(X86CPU *cpu)
2089 struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
2091 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
2094 static int kvm_get_mp_state(X86CPU *cpu)
2096 CPUState *cs = CPU(cpu);
2097 CPUX86State *env = &cpu->env;
2098 struct kvm_mp_state mp_state;
2099 int ret;
2101 ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
2102 if (ret < 0) {
2103 return ret;
2105 env->mp_state = mp_state.mp_state;
2106 if (kvm_irqchip_in_kernel()) {
2107 cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
2109 return 0;
2112 static int kvm_get_apic(X86CPU *cpu)
2114 DeviceState *apic = cpu->apic_state;
2115 struct kvm_lapic_state kapic;
2116 int ret;
2118 if (apic && kvm_irqchip_in_kernel()) {
2119 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
2120 if (ret < 0) {
2121 return ret;
2124 kvm_get_apic_state(apic, &kapic);
2126 return 0;
2129 static int kvm_put_apic(X86CPU *cpu)
2131 DeviceState *apic = cpu->apic_state;
2132 struct kvm_lapic_state kapic;
2134 if (apic && kvm_irqchip_in_kernel()) {
2135 kvm_put_apic_state(apic, &kapic);
2137 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_LAPIC, &kapic);
2139 return 0;
2142 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
2144 CPUState *cs = CPU(cpu);
2145 CPUX86State *env = &cpu->env;
2146 struct kvm_vcpu_events events = {};
2148 if (!kvm_has_vcpu_events()) {
2149 return 0;
2152 events.exception.injected = (env->exception_injected >= 0);
2153 events.exception.nr = env->exception_injected;
2154 events.exception.has_error_code = env->has_error_code;
2155 events.exception.error_code = env->error_code;
2156 events.exception.pad = 0;
2158 events.interrupt.injected = (env->interrupt_injected >= 0);
2159 events.interrupt.nr = env->interrupt_injected;
2160 events.interrupt.soft = env->soft_interrupt;
2162 events.nmi.injected = env->nmi_injected;
2163 events.nmi.pending = env->nmi_pending;
2164 events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
2165 events.nmi.pad = 0;
2167 events.sipi_vector = env->sipi_vector;
2169 if (has_msr_smbase) {
2170 events.smi.smm = !!(env->hflags & HF_SMM_MASK);
2171 events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
2172 if (kvm_irqchip_in_kernel()) {
2173 /* As soon as these are moved to the kernel, remove them
2174 * from cs->interrupt_request.
2176 events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
2177 events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
2178 cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
2179 } else {
2180 /* Keep these in cs->interrupt_request. */
2181 events.smi.pending = 0;
2182 events.smi.latched_init = 0;
2184 events.flags |= KVM_VCPUEVENT_VALID_SMM;
2187 events.flags = 0;
2188 if (level >= KVM_PUT_RESET_STATE) {
2189 events.flags |=
2190 KVM_VCPUEVENT_VALID_NMI_PENDING | KVM_VCPUEVENT_VALID_SIPI_VECTOR;
2193 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
2196 static int kvm_get_vcpu_events(X86CPU *cpu)
2198 CPUX86State *env = &cpu->env;
2199 struct kvm_vcpu_events events;
2200 int ret;
2202 if (!kvm_has_vcpu_events()) {
2203 return 0;
2206 memset(&events, 0, sizeof(events));
2207 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
2208 if (ret < 0) {
2209 return ret;
2211 env->exception_injected =
2212 events.exception.injected ? events.exception.nr : -1;
2213 env->has_error_code = events.exception.has_error_code;
2214 env->error_code = events.exception.error_code;
2216 env->interrupt_injected =
2217 events.interrupt.injected ? events.interrupt.nr : -1;
2218 env->soft_interrupt = events.interrupt.soft;
2220 env->nmi_injected = events.nmi.injected;
2221 env->nmi_pending = events.nmi.pending;
2222 if (events.nmi.masked) {
2223 env->hflags2 |= HF2_NMI_MASK;
2224 } else {
2225 env->hflags2 &= ~HF2_NMI_MASK;
2228 if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
2229 if (events.smi.smm) {
2230 env->hflags |= HF_SMM_MASK;
2231 } else {
2232 env->hflags &= ~HF_SMM_MASK;
2234 if (events.smi.pending) {
2235 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2236 } else {
2237 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2239 if (events.smi.smm_inside_nmi) {
2240 env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
2241 } else {
2242 env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
2244 if (events.smi.latched_init) {
2245 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2246 } else {
2247 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2251 env->sipi_vector = events.sipi_vector;
2253 return 0;
2256 static int kvm_guest_debug_workarounds(X86CPU *cpu)
2258 CPUState *cs = CPU(cpu);
2259 CPUX86State *env = &cpu->env;
2260 int ret = 0;
2261 unsigned long reinject_trap = 0;
2263 if (!kvm_has_vcpu_events()) {
2264 if (env->exception_injected == 1) {
2265 reinject_trap = KVM_GUESTDBG_INJECT_DB;
2266 } else if (env->exception_injected == 3) {
2267 reinject_trap = KVM_GUESTDBG_INJECT_BP;
2269 env->exception_injected = -1;
2273 * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
2274 * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
2275 * by updating the debug state once again if single-stepping is on.
2276 * Another reason to call kvm_update_guest_debug here is a pending debug
2277 * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
2278 * reinject them via SET_GUEST_DEBUG.
2280 if (reinject_trap ||
2281 (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
2282 ret = kvm_update_guest_debug(cs, reinject_trap);
2284 return ret;
2287 static int kvm_put_debugregs(X86CPU *cpu)
2289 CPUX86State *env = &cpu->env;
2290 struct kvm_debugregs dbgregs;
2291 int i;
2293 if (!kvm_has_debugregs()) {
2294 return 0;
2297 for (i = 0; i < 4; i++) {
2298 dbgregs.db[i] = env->dr[i];
2300 dbgregs.dr6 = env->dr[6];
2301 dbgregs.dr7 = env->dr[7];
2302 dbgregs.flags = 0;
2304 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
2307 static int kvm_get_debugregs(X86CPU *cpu)
2309 CPUX86State *env = &cpu->env;
2310 struct kvm_debugregs dbgregs;
2311 int i, ret;
2313 if (!kvm_has_debugregs()) {
2314 return 0;
2317 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
2318 if (ret < 0) {
2319 return ret;
2321 for (i = 0; i < 4; i++) {
2322 env->dr[i] = dbgregs.db[i];
2324 env->dr[4] = env->dr[6] = dbgregs.dr6;
2325 env->dr[5] = env->dr[7] = dbgregs.dr7;
2327 return 0;
2330 int kvm_arch_put_registers(CPUState *cpu, int level)
2332 X86CPU *x86_cpu = X86_CPU(cpu);
2333 int ret;
2335 assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
2337 if (level >= KVM_PUT_RESET_STATE && has_msr_feature_control) {
2338 ret = kvm_put_msr_feature_control(x86_cpu);
2339 if (ret < 0) {
2340 return ret;
2344 ret = kvm_getput_regs(x86_cpu, 1);
2345 if (ret < 0) {
2346 return ret;
2348 ret = kvm_put_xsave(x86_cpu);
2349 if (ret < 0) {
2350 return ret;
2352 ret = kvm_put_xcrs(x86_cpu);
2353 if (ret < 0) {
2354 return ret;
2356 ret = kvm_put_sregs(x86_cpu);
2357 if (ret < 0) {
2358 return ret;
2360 /* must be before kvm_put_msrs */
2361 ret = kvm_inject_mce_oldstyle(x86_cpu);
2362 if (ret < 0) {
2363 return ret;
2365 ret = kvm_put_msrs(x86_cpu, level);
2366 if (ret < 0) {
2367 return ret;
2369 if (level >= KVM_PUT_RESET_STATE) {
2370 ret = kvm_put_mp_state(x86_cpu);
2371 if (ret < 0) {
2372 return ret;
2374 ret = kvm_put_apic(x86_cpu);
2375 if (ret < 0) {
2376 return ret;
2380 ret = kvm_put_tscdeadline_msr(x86_cpu);
2381 if (ret < 0) {
2382 return ret;
2385 ret = kvm_put_vcpu_events(x86_cpu, level);
2386 if (ret < 0) {
2387 return ret;
2389 ret = kvm_put_debugregs(x86_cpu);
2390 if (ret < 0) {
2391 return ret;
2393 /* must be last */
2394 ret = kvm_guest_debug_workarounds(x86_cpu);
2395 if (ret < 0) {
2396 return ret;
2398 return 0;
2401 int kvm_arch_get_registers(CPUState *cs)
2403 X86CPU *cpu = X86_CPU(cs);
2404 int ret;
2406 assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
2408 ret = kvm_getput_regs(cpu, 0);
2409 if (ret < 0) {
2410 return ret;
2412 ret = kvm_get_xsave(cpu);
2413 if (ret < 0) {
2414 return ret;
2416 ret = kvm_get_xcrs(cpu);
2417 if (ret < 0) {
2418 return ret;
2420 ret = kvm_get_sregs(cpu);
2421 if (ret < 0) {
2422 return ret;
2424 ret = kvm_get_msrs(cpu);
2425 if (ret < 0) {
2426 return ret;
2428 ret = kvm_get_mp_state(cpu);
2429 if (ret < 0) {
2430 return ret;
2432 ret = kvm_get_apic(cpu);
2433 if (ret < 0) {
2434 return ret;
2436 ret = kvm_get_vcpu_events(cpu);
2437 if (ret < 0) {
2438 return ret;
2440 ret = kvm_get_debugregs(cpu);
2441 if (ret < 0) {
2442 return ret;
2444 return 0;
2447 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
2449 X86CPU *x86_cpu = X86_CPU(cpu);
2450 CPUX86State *env = &x86_cpu->env;
2451 int ret;
2453 /* Inject NMI */
2454 if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
2455 if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
2456 qemu_mutex_lock_iothread();
2457 cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
2458 qemu_mutex_unlock_iothread();
2459 DPRINTF("injected NMI\n");
2460 ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
2461 if (ret < 0) {
2462 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
2463 strerror(-ret));
2466 if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
2467 qemu_mutex_lock_iothread();
2468 cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
2469 qemu_mutex_unlock_iothread();
2470 DPRINTF("injected SMI\n");
2471 ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
2472 if (ret < 0) {
2473 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
2474 strerror(-ret));
2479 if (!kvm_irqchip_in_kernel()) {
2480 qemu_mutex_lock_iothread();
2483 /* Force the VCPU out of its inner loop to process any INIT requests
2484 * or (for userspace APIC, but it is cheap to combine the checks here)
2485 * pending TPR access reports.
2487 if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
2488 if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
2489 !(env->hflags & HF_SMM_MASK)) {
2490 cpu->exit_request = 1;
2492 if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
2493 cpu->exit_request = 1;
2497 if (!kvm_irqchip_in_kernel()) {
2498 /* Try to inject an interrupt if the guest can accept it */
2499 if (run->ready_for_interrupt_injection &&
2500 (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
2501 (env->eflags & IF_MASK)) {
2502 int irq;
2504 cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
2505 irq = cpu_get_pic_interrupt(env);
2506 if (irq >= 0) {
2507 struct kvm_interrupt intr;
2509 intr.irq = irq;
2510 DPRINTF("injected interrupt %d\n", irq);
2511 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
2512 if (ret < 0) {
2513 fprintf(stderr,
2514 "KVM: injection failed, interrupt lost (%s)\n",
2515 strerror(-ret));
2520 /* If we have an interrupt but the guest is not ready to receive an
2521 * interrupt, request an interrupt window exit. This will
2522 * cause a return to userspace as soon as the guest is ready to
2523 * receive interrupts. */
2524 if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
2525 run->request_interrupt_window = 1;
2526 } else {
2527 run->request_interrupt_window = 0;
2530 DPRINTF("setting tpr\n");
2531 run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
2533 qemu_mutex_unlock_iothread();
2537 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
2539 X86CPU *x86_cpu = X86_CPU(cpu);
2540 CPUX86State *env = &x86_cpu->env;
2542 if (run->flags & KVM_RUN_X86_SMM) {
2543 env->hflags |= HF_SMM_MASK;
2544 } else {
2545 env->hflags &= HF_SMM_MASK;
2547 if (run->if_flag) {
2548 env->eflags |= IF_MASK;
2549 } else {
2550 env->eflags &= ~IF_MASK;
2553 /* We need to protect the apic state against concurrent accesses from
2554 * different threads in case the userspace irqchip is used. */
2555 if (!kvm_irqchip_in_kernel()) {
2556 qemu_mutex_lock_iothread();
2558 cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
2559 cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
2560 if (!kvm_irqchip_in_kernel()) {
2561 qemu_mutex_unlock_iothread();
2563 return cpu_get_mem_attrs(env);
2566 int kvm_arch_process_async_events(CPUState *cs)
2568 X86CPU *cpu = X86_CPU(cs);
2569 CPUX86State *env = &cpu->env;
2571 if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
2572 /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
2573 assert(env->mcg_cap);
2575 cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
2577 kvm_cpu_synchronize_state(cs);
2579 if (env->exception_injected == EXCP08_DBLE) {
2580 /* this means triple fault */
2581 qemu_system_reset_request();
2582 cs->exit_request = 1;
2583 return 0;
2585 env->exception_injected = EXCP12_MCHK;
2586 env->has_error_code = 0;
2588 cs->halted = 0;
2589 if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
2590 env->mp_state = KVM_MP_STATE_RUNNABLE;
2594 if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
2595 !(env->hflags & HF_SMM_MASK)) {
2596 kvm_cpu_synchronize_state(cs);
2597 do_cpu_init(cpu);
2600 if (kvm_irqchip_in_kernel()) {
2601 return 0;
2604 if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
2605 cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
2606 apic_poll_irq(cpu->apic_state);
2608 if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2609 (env->eflags & IF_MASK)) ||
2610 (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
2611 cs->halted = 0;
2613 if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
2614 kvm_cpu_synchronize_state(cs);
2615 do_cpu_sipi(cpu);
2617 if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
2618 cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
2619 kvm_cpu_synchronize_state(cs);
2620 apic_handle_tpr_access_report(cpu->apic_state, env->eip,
2621 env->tpr_access_type);
2624 return cs->halted;
2627 static int kvm_handle_halt(X86CPU *cpu)
2629 CPUState *cs = CPU(cpu);
2630 CPUX86State *env = &cpu->env;
2632 if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2633 (env->eflags & IF_MASK)) &&
2634 !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
2635 cs->halted = 1;
2636 return EXCP_HLT;
2639 return 0;
2642 static int kvm_handle_tpr_access(X86CPU *cpu)
2644 CPUState *cs = CPU(cpu);
2645 struct kvm_run *run = cs->kvm_run;
2647 apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
2648 run->tpr_access.is_write ? TPR_ACCESS_WRITE
2649 : TPR_ACCESS_READ);
2650 return 1;
2653 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2655 static const uint8_t int3 = 0xcc;
2657 if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
2658 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
2659 return -EINVAL;
2661 return 0;
2664 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2666 uint8_t int3;
2668 if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
2669 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
2670 return -EINVAL;
2672 return 0;
2675 static struct {
2676 target_ulong addr;
2677 int len;
2678 int type;
2679 } hw_breakpoint[4];
2681 static int nb_hw_breakpoint;
2683 static int find_hw_breakpoint(target_ulong addr, int len, int type)
2685 int n;
2687 for (n = 0; n < nb_hw_breakpoint; n++) {
2688 if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
2689 (hw_breakpoint[n].len == len || len == -1)) {
2690 return n;
2693 return -1;
2696 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
2697 target_ulong len, int type)
2699 switch (type) {
2700 case GDB_BREAKPOINT_HW:
2701 len = 1;
2702 break;
2703 case GDB_WATCHPOINT_WRITE:
2704 case GDB_WATCHPOINT_ACCESS:
2705 switch (len) {
2706 case 1:
2707 break;
2708 case 2:
2709 case 4:
2710 case 8:
2711 if (addr & (len - 1)) {
2712 return -EINVAL;
2714 break;
2715 default:
2716 return -EINVAL;
2718 break;
2719 default:
2720 return -ENOSYS;
2723 if (nb_hw_breakpoint == 4) {
2724 return -ENOBUFS;
2726 if (find_hw_breakpoint(addr, len, type) >= 0) {
2727 return -EEXIST;
2729 hw_breakpoint[nb_hw_breakpoint].addr = addr;
2730 hw_breakpoint[nb_hw_breakpoint].len = len;
2731 hw_breakpoint[nb_hw_breakpoint].type = type;
2732 nb_hw_breakpoint++;
2734 return 0;
2737 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
2738 target_ulong len, int type)
2740 int n;
2742 n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
2743 if (n < 0) {
2744 return -ENOENT;
2746 nb_hw_breakpoint--;
2747 hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
2749 return 0;
2752 void kvm_arch_remove_all_hw_breakpoints(void)
2754 nb_hw_breakpoint = 0;
2757 static CPUWatchpoint hw_watchpoint;
2759 static int kvm_handle_debug(X86CPU *cpu,
2760 struct kvm_debug_exit_arch *arch_info)
2762 CPUState *cs = CPU(cpu);
2763 CPUX86State *env = &cpu->env;
2764 int ret = 0;
2765 int n;
2767 if (arch_info->exception == 1) {
2768 if (arch_info->dr6 & (1 << 14)) {
2769 if (cs->singlestep_enabled) {
2770 ret = EXCP_DEBUG;
2772 } else {
2773 for (n = 0; n < 4; n++) {
2774 if (arch_info->dr6 & (1 << n)) {
2775 switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
2776 case 0x0:
2777 ret = EXCP_DEBUG;
2778 break;
2779 case 0x1:
2780 ret = EXCP_DEBUG;
2781 cs->watchpoint_hit = &hw_watchpoint;
2782 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
2783 hw_watchpoint.flags = BP_MEM_WRITE;
2784 break;
2785 case 0x3:
2786 ret = EXCP_DEBUG;
2787 cs->watchpoint_hit = &hw_watchpoint;
2788 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
2789 hw_watchpoint.flags = BP_MEM_ACCESS;
2790 break;
2795 } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
2796 ret = EXCP_DEBUG;
2798 if (ret == 0) {
2799 cpu_synchronize_state(cs);
2800 assert(env->exception_injected == -1);
2802 /* pass to guest */
2803 env->exception_injected = arch_info->exception;
2804 env->has_error_code = 0;
2807 return ret;
2810 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
2812 const uint8_t type_code[] = {
2813 [GDB_BREAKPOINT_HW] = 0x0,
2814 [GDB_WATCHPOINT_WRITE] = 0x1,
2815 [GDB_WATCHPOINT_ACCESS] = 0x3
2817 const uint8_t len_code[] = {
2818 [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
2820 int n;
2822 if (kvm_sw_breakpoints_active(cpu)) {
2823 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
2825 if (nb_hw_breakpoint > 0) {
2826 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
2827 dbg->arch.debugreg[7] = 0x0600;
2828 for (n = 0; n < nb_hw_breakpoint; n++) {
2829 dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
2830 dbg->arch.debugreg[7] |= (2 << (n * 2)) |
2831 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
2832 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
2837 static bool host_supports_vmx(void)
2839 uint32_t ecx, unused;
2841 host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
2842 return ecx & CPUID_EXT_VMX;
2845 #define VMX_INVALID_GUEST_STATE 0x80000021
2847 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
2849 X86CPU *cpu = X86_CPU(cs);
2850 uint64_t code;
2851 int ret;
2853 switch (run->exit_reason) {
2854 case KVM_EXIT_HLT:
2855 DPRINTF("handle_hlt\n");
2856 qemu_mutex_lock_iothread();
2857 ret = kvm_handle_halt(cpu);
2858 qemu_mutex_unlock_iothread();
2859 break;
2860 case KVM_EXIT_SET_TPR:
2861 ret = 0;
2862 break;
2863 case KVM_EXIT_TPR_ACCESS:
2864 qemu_mutex_lock_iothread();
2865 ret = kvm_handle_tpr_access(cpu);
2866 qemu_mutex_unlock_iothread();
2867 break;
2868 case KVM_EXIT_FAIL_ENTRY:
2869 code = run->fail_entry.hardware_entry_failure_reason;
2870 fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
2871 code);
2872 if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
2873 fprintf(stderr,
2874 "\nIf you're running a guest on an Intel machine without "
2875 "unrestricted mode\n"
2876 "support, the failure can be most likely due to the guest "
2877 "entering an invalid\n"
2878 "state for Intel VT. For example, the guest maybe running "
2879 "in big real mode\n"
2880 "which is not supported on less recent Intel processors."
2881 "\n\n");
2883 ret = -1;
2884 break;
2885 case KVM_EXIT_EXCEPTION:
2886 fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
2887 run->ex.exception, run->ex.error_code);
2888 ret = -1;
2889 break;
2890 case KVM_EXIT_DEBUG:
2891 DPRINTF("kvm_exit_debug\n");
2892 qemu_mutex_lock_iothread();
2893 ret = kvm_handle_debug(cpu, &run->debug.arch);
2894 qemu_mutex_unlock_iothread();
2895 break;
2896 default:
2897 fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
2898 ret = -1;
2899 break;
2902 return ret;
2905 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
2907 X86CPU *cpu = X86_CPU(cs);
2908 CPUX86State *env = &cpu->env;
2910 kvm_cpu_synchronize_state(cs);
2911 return !(env->cr[0] & CR0_PE_MASK) ||
2912 ((env->segs[R_CS].selector & 3) != 3);
2915 void kvm_arch_init_irq_routing(KVMState *s)
2917 if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
2918 /* If kernel can't do irq routing, interrupt source
2919 * override 0->2 cannot be set up as required by HPET.
2920 * So we have to disable it.
2922 no_hpet = 1;
2924 /* We know at this point that we're using the in-kernel
2925 * irqchip, so we can use irqfds, and on x86 we know
2926 * we can use msi via irqfd and GSI routing.
2928 kvm_msi_via_irqfd_allowed = true;
2929 kvm_gsi_routing_allowed = true;
2932 /* Classic KVM device assignment interface. Will remain x86 only. */
2933 int kvm_device_pci_assign(KVMState *s, PCIHostDeviceAddress *dev_addr,
2934 uint32_t flags, uint32_t *dev_id)
2936 struct kvm_assigned_pci_dev dev_data = {
2937 .segnr = dev_addr->domain,
2938 .busnr = dev_addr->bus,
2939 .devfn = PCI_DEVFN(dev_addr->slot, dev_addr->function),
2940 .flags = flags,
2942 int ret;
2944 dev_data.assigned_dev_id =
2945 (dev_addr->domain << 16) | (dev_addr->bus << 8) | dev_data.devfn;
2947 ret = kvm_vm_ioctl(s, KVM_ASSIGN_PCI_DEVICE, &dev_data);
2948 if (ret < 0) {
2949 return ret;
2952 *dev_id = dev_data.assigned_dev_id;
2954 return 0;
2957 int kvm_device_pci_deassign(KVMState *s, uint32_t dev_id)
2959 struct kvm_assigned_pci_dev dev_data = {
2960 .assigned_dev_id = dev_id,
2963 return kvm_vm_ioctl(s, KVM_DEASSIGN_PCI_DEVICE, &dev_data);
2966 static int kvm_assign_irq_internal(KVMState *s, uint32_t dev_id,
2967 uint32_t irq_type, uint32_t guest_irq)
2969 struct kvm_assigned_irq assigned_irq = {
2970 .assigned_dev_id = dev_id,
2971 .guest_irq = guest_irq,
2972 .flags = irq_type,
2975 if (kvm_check_extension(s, KVM_CAP_ASSIGN_DEV_IRQ)) {
2976 return kvm_vm_ioctl(s, KVM_ASSIGN_DEV_IRQ, &assigned_irq);
2977 } else {
2978 return kvm_vm_ioctl(s, KVM_ASSIGN_IRQ, &assigned_irq);
2982 int kvm_device_intx_assign(KVMState *s, uint32_t dev_id, bool use_host_msi,
2983 uint32_t guest_irq)
2985 uint32_t irq_type = KVM_DEV_IRQ_GUEST_INTX |
2986 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX);
2988 return kvm_assign_irq_internal(s, dev_id, irq_type, guest_irq);
2991 int kvm_device_intx_set_mask(KVMState *s, uint32_t dev_id, bool masked)
2993 struct kvm_assigned_pci_dev dev_data = {
2994 .assigned_dev_id = dev_id,
2995 .flags = masked ? KVM_DEV_ASSIGN_MASK_INTX : 0,
2998 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_INTX_MASK, &dev_data);
3001 static int kvm_deassign_irq_internal(KVMState *s, uint32_t dev_id,
3002 uint32_t type)
3004 struct kvm_assigned_irq assigned_irq = {
3005 .assigned_dev_id = dev_id,
3006 .flags = type,
3009 return kvm_vm_ioctl(s, KVM_DEASSIGN_DEV_IRQ, &assigned_irq);
3012 int kvm_device_intx_deassign(KVMState *s, uint32_t dev_id, bool use_host_msi)
3014 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_INTX |
3015 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX));
3018 int kvm_device_msi_assign(KVMState *s, uint32_t dev_id, int virq)
3020 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSI |
3021 KVM_DEV_IRQ_GUEST_MSI, virq);
3024 int kvm_device_msi_deassign(KVMState *s, uint32_t dev_id)
3026 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSI |
3027 KVM_DEV_IRQ_HOST_MSI);
3030 bool kvm_device_msix_supported(KVMState *s)
3032 /* The kernel lacks a corresponding KVM_CAP, so we probe by calling
3033 * KVM_ASSIGN_SET_MSIX_NR with an invalid parameter. */
3034 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, NULL) == -EFAULT;
3037 int kvm_device_msix_init_vectors(KVMState *s, uint32_t dev_id,
3038 uint32_t nr_vectors)
3040 struct kvm_assigned_msix_nr msix_nr = {
3041 .assigned_dev_id = dev_id,
3042 .entry_nr = nr_vectors,
3045 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, &msix_nr);
3048 int kvm_device_msix_set_vector(KVMState *s, uint32_t dev_id, uint32_t vector,
3049 int virq)
3051 struct kvm_assigned_msix_entry msix_entry = {
3052 .assigned_dev_id = dev_id,
3053 .gsi = virq,
3054 .entry = vector,
3057 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_ENTRY, &msix_entry);
3060 int kvm_device_msix_assign(KVMState *s, uint32_t dev_id)
3062 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSIX |
3063 KVM_DEV_IRQ_GUEST_MSIX, 0);
3066 int kvm_device_msix_deassign(KVMState *s, uint32_t dev_id)
3068 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSIX |
3069 KVM_DEV_IRQ_HOST_MSIX);
3072 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
3073 uint64_t address, uint32_t data, PCIDevice *dev)
3075 return 0;
3078 int kvm_arch_msi_data_to_gsi(uint32_t data)
3080 abort();