colo-proxy: fix memory leak
[qemu/ar7.git] / target-i386 / kvm.c
blob86b41a9c215ff87d4f8afa7c62cc2f84ef5689e8
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 "qemu/osdep.h"
16 #include "qapi/error.h"
17 #include <sys/ioctl.h>
18 #include <sys/utsname.h>
20 #include <linux/kvm.h>
21 #include <linux/kvm_para.h>
23 #include "qemu-common.h"
24 #include "cpu.h"
25 #include "sysemu/sysemu.h"
26 #include "sysemu/kvm_int.h"
27 #include "kvm_i386.h"
28 #include "hyperv.h"
30 #include "exec/gdbstub.h"
31 #include "qemu/host-utils.h"
32 #include "qemu/config-file.h"
33 #include "qemu/error-report.h"
34 #include "hw/i386/pc.h"
35 #include "hw/i386/apic.h"
36 #include "hw/i386/apic_internal.h"
37 #include "hw/i386/apic-msidef.h"
38 #include "hw/i386/intel_iommu.h"
39 #include "hw/i386/x86-iommu.h"
41 #include "exec/ioport.h"
42 #include "standard-headers/asm-x86/hyperv.h"
43 #include "hw/pci/pci.h"
44 #include "hw/pci/msi.h"
45 #include "migration/migration.h"
46 #include "exec/memattrs.h"
47 #include "trace.h"
49 //#define DEBUG_KVM
51 #ifdef DEBUG_KVM
52 #define DPRINTF(fmt, ...) \
53 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
54 #else
55 #define DPRINTF(fmt, ...) \
56 do { } while (0)
57 #endif
59 #define MSR_KVM_WALL_CLOCK 0x11
60 #define MSR_KVM_SYSTEM_TIME 0x12
62 /* A 4096-byte buffer can hold the 8-byte kvm_msrs header, plus
63 * 255 kvm_msr_entry structs */
64 #define MSR_BUF_SIZE 4096
66 #ifndef BUS_MCEERR_AR
67 #define BUS_MCEERR_AR 4
68 #endif
69 #ifndef BUS_MCEERR_AO
70 #define BUS_MCEERR_AO 5
71 #endif
73 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
74 KVM_CAP_INFO(SET_TSS_ADDR),
75 KVM_CAP_INFO(EXT_CPUID),
76 KVM_CAP_INFO(MP_STATE),
77 KVM_CAP_LAST_INFO
80 static bool has_msr_star;
81 static bool has_msr_hsave_pa;
82 static bool has_msr_tsc_aux;
83 static bool has_msr_tsc_adjust;
84 static bool has_msr_tsc_deadline;
85 static bool has_msr_feature_control;
86 static bool has_msr_misc_enable;
87 static bool has_msr_smbase;
88 static bool has_msr_bndcfgs;
89 static int lm_capable_kernel;
90 static bool has_msr_hv_hypercall;
91 static bool has_msr_hv_crash;
92 static bool has_msr_hv_reset;
93 static bool has_msr_hv_vpindex;
94 static bool has_msr_hv_runtime;
95 static bool has_msr_hv_synic;
96 static bool has_msr_hv_stimer;
97 static bool has_msr_xss;
99 static bool has_msr_architectural_pmu;
100 static uint32_t num_architectural_pmu_counters;
102 static int has_xsave;
103 static int has_xcrs;
104 static int has_pit_state2;
106 static bool has_msr_mcg_ext_ctl;
108 static struct kvm_cpuid2 *cpuid_cache;
110 int kvm_has_pit_state2(void)
112 return has_pit_state2;
115 bool kvm_has_smm(void)
117 return kvm_check_extension(kvm_state, KVM_CAP_X86_SMM);
120 bool kvm_allows_irq0_override(void)
122 return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
125 static bool kvm_x2apic_api_set_flags(uint64_t flags)
127 KVMState *s = KVM_STATE(current_machine->accelerator);
129 return !kvm_vm_enable_cap(s, KVM_CAP_X2APIC_API, 0, flags);
132 #define MEMORIZE(fn, _result) \
133 ({ \
134 static bool _memorized; \
136 if (_memorized) { \
137 return _result; \
139 _memorized = true; \
140 _result = fn; \
143 static bool has_x2apic_api;
145 bool kvm_has_x2apic_api(void)
147 return has_x2apic_api;
150 bool kvm_enable_x2apic(void)
152 return MEMORIZE(
153 kvm_x2apic_api_set_flags(KVM_X2APIC_API_USE_32BIT_IDS |
154 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK),
155 has_x2apic_api);
158 static int kvm_get_tsc(CPUState *cs)
160 X86CPU *cpu = X86_CPU(cs);
161 CPUX86State *env = &cpu->env;
162 struct {
163 struct kvm_msrs info;
164 struct kvm_msr_entry entries[1];
165 } msr_data;
166 int ret;
168 if (env->tsc_valid) {
169 return 0;
172 msr_data.info.nmsrs = 1;
173 msr_data.entries[0].index = MSR_IA32_TSC;
174 env->tsc_valid = !runstate_is_running();
176 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
177 if (ret < 0) {
178 return ret;
181 assert(ret == 1);
182 env->tsc = msr_data.entries[0].data;
183 return 0;
186 static inline void do_kvm_synchronize_tsc(CPUState *cpu, void *arg)
188 kvm_get_tsc(cpu);
191 void kvm_synchronize_all_tsc(void)
193 CPUState *cpu;
195 if (kvm_enabled()) {
196 CPU_FOREACH(cpu) {
197 run_on_cpu(cpu, do_kvm_synchronize_tsc, NULL);
202 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
204 struct kvm_cpuid2 *cpuid;
205 int r, size;
207 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
208 cpuid = g_malloc0(size);
209 cpuid->nent = max;
210 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
211 if (r == 0 && cpuid->nent >= max) {
212 r = -E2BIG;
214 if (r < 0) {
215 if (r == -E2BIG) {
216 g_free(cpuid);
217 return NULL;
218 } else {
219 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
220 strerror(-r));
221 exit(1);
224 return cpuid;
227 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
228 * for all entries.
230 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
232 struct kvm_cpuid2 *cpuid;
233 int max = 1;
235 if (cpuid_cache != NULL) {
236 return cpuid_cache;
238 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
239 max *= 2;
241 cpuid_cache = cpuid;
242 return cpuid;
245 static const struct kvm_para_features {
246 int cap;
247 int feature;
248 } para_features[] = {
249 { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
250 { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
251 { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
252 { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
255 static int get_para_features(KVMState *s)
257 int i, features = 0;
259 for (i = 0; i < ARRAY_SIZE(para_features); i++) {
260 if (kvm_check_extension(s, para_features[i].cap)) {
261 features |= (1 << para_features[i].feature);
265 return features;
269 /* Returns the value for a specific register on the cpuid entry
271 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
273 uint32_t ret = 0;
274 switch (reg) {
275 case R_EAX:
276 ret = entry->eax;
277 break;
278 case R_EBX:
279 ret = entry->ebx;
280 break;
281 case R_ECX:
282 ret = entry->ecx;
283 break;
284 case R_EDX:
285 ret = entry->edx;
286 break;
288 return ret;
291 /* Find matching entry for function/index on kvm_cpuid2 struct
293 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
294 uint32_t function,
295 uint32_t index)
297 int i;
298 for (i = 0; i < cpuid->nent; ++i) {
299 if (cpuid->entries[i].function == function &&
300 cpuid->entries[i].index == index) {
301 return &cpuid->entries[i];
304 /* not found: */
305 return NULL;
308 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
309 uint32_t index, int reg)
311 struct kvm_cpuid2 *cpuid;
312 uint32_t ret = 0;
313 uint32_t cpuid_1_edx;
314 bool found = false;
316 cpuid = get_supported_cpuid(s);
318 struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
319 if (entry) {
320 found = true;
321 ret = cpuid_entry_get_reg(entry, reg);
324 /* Fixups for the data returned by KVM, below */
326 if (function == 1 && reg == R_EDX) {
327 /* KVM before 2.6.30 misreports the following features */
328 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
329 } else if (function == 1 && reg == R_ECX) {
330 /* We can set the hypervisor flag, even if KVM does not return it on
331 * GET_SUPPORTED_CPUID
333 ret |= CPUID_EXT_HYPERVISOR;
334 /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
335 * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
336 * and the irqchip is in the kernel.
338 if (kvm_irqchip_in_kernel() &&
339 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
340 ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
343 /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
344 * without the in-kernel irqchip
346 if (!kvm_irqchip_in_kernel()) {
347 ret &= ~CPUID_EXT_X2APIC;
349 } else if (function == 6 && reg == R_EAX) {
350 ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
351 } else if (function == 0x80000001 && reg == R_EDX) {
352 /* On Intel, kvm returns cpuid according to the Intel spec,
353 * so add missing bits according to the AMD spec:
355 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
356 ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
357 } else if (function == KVM_CPUID_FEATURES && reg == R_EAX) {
358 /* kvm_pv_unhalt is reported by GET_SUPPORTED_CPUID, but it can't
359 * be enabled without the in-kernel irqchip
361 if (!kvm_irqchip_in_kernel()) {
362 ret &= ~(1U << KVM_FEATURE_PV_UNHALT);
366 /* fallback for older kernels */
367 if ((function == KVM_CPUID_FEATURES) && !found) {
368 ret = get_para_features(s);
371 return ret;
374 typedef struct HWPoisonPage {
375 ram_addr_t ram_addr;
376 QLIST_ENTRY(HWPoisonPage) list;
377 } HWPoisonPage;
379 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
380 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
382 static void kvm_unpoison_all(void *param)
384 HWPoisonPage *page, *next_page;
386 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
387 QLIST_REMOVE(page, list);
388 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
389 g_free(page);
393 static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
395 HWPoisonPage *page;
397 QLIST_FOREACH(page, &hwpoison_page_list, list) {
398 if (page->ram_addr == ram_addr) {
399 return;
402 page = g_new(HWPoisonPage, 1);
403 page->ram_addr = ram_addr;
404 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
407 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
408 int *max_banks)
410 int r;
412 r = kvm_check_extension(s, KVM_CAP_MCE);
413 if (r > 0) {
414 *max_banks = r;
415 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
417 return -ENOSYS;
420 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
422 CPUState *cs = CPU(cpu);
423 CPUX86State *env = &cpu->env;
424 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
425 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
426 uint64_t mcg_status = MCG_STATUS_MCIP;
427 int flags = 0;
429 if (code == BUS_MCEERR_AR) {
430 status |= MCI_STATUS_AR | 0x134;
431 mcg_status |= MCG_STATUS_EIPV;
432 } else {
433 status |= 0xc0;
434 mcg_status |= MCG_STATUS_RIPV;
437 flags = cpu_x86_support_mca_broadcast(env) ? MCE_INJECT_BROADCAST : 0;
438 /* We need to read back the value of MSR_EXT_MCG_CTL that was set by the
439 * guest kernel back into env->mcg_ext_ctl.
441 cpu_synchronize_state(cs);
442 if (env->mcg_ext_ctl & MCG_EXT_CTL_LMCE_EN) {
443 mcg_status |= MCG_STATUS_LMCE;
444 flags = 0;
447 cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
448 (MCM_ADDR_PHYS << 6) | 0xc, flags);
451 static void hardware_memory_error(void)
453 fprintf(stderr, "Hardware memory error!\n");
454 exit(1);
457 int kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
459 X86CPU *cpu = X86_CPU(c);
460 CPUX86State *env = &cpu->env;
461 ram_addr_t ram_addr;
462 hwaddr paddr;
464 if ((env->mcg_cap & MCG_SER_P) && addr
465 && (code == BUS_MCEERR_AR || code == BUS_MCEERR_AO)) {
466 ram_addr = qemu_ram_addr_from_host(addr);
467 if (ram_addr == RAM_ADDR_INVALID ||
468 !kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
469 fprintf(stderr, "Hardware memory error for memory used by "
470 "QEMU itself instead of guest system!\n");
471 /* Hope we are lucky for AO MCE */
472 if (code == BUS_MCEERR_AO) {
473 return 0;
474 } else {
475 hardware_memory_error();
478 kvm_hwpoison_page_add(ram_addr);
479 kvm_mce_inject(cpu, paddr, code);
480 } else {
481 if (code == BUS_MCEERR_AO) {
482 return 0;
483 } else if (code == BUS_MCEERR_AR) {
484 hardware_memory_error();
485 } else {
486 return 1;
489 return 0;
492 int kvm_arch_on_sigbus(int code, void *addr)
494 X86CPU *cpu = X86_CPU(first_cpu);
496 if ((cpu->env.mcg_cap & MCG_SER_P) && addr && code == BUS_MCEERR_AO) {
497 ram_addr_t ram_addr;
498 hwaddr paddr;
500 /* Hope we are lucky for AO MCE */
501 ram_addr = qemu_ram_addr_from_host(addr);
502 if (ram_addr == RAM_ADDR_INVALID ||
503 !kvm_physical_memory_addr_from_host(first_cpu->kvm_state,
504 addr, &paddr)) {
505 fprintf(stderr, "Hardware memory error for memory used by "
506 "QEMU itself instead of guest system!: %p\n", addr);
507 return 0;
509 kvm_hwpoison_page_add(ram_addr);
510 kvm_mce_inject(X86_CPU(first_cpu), paddr, code);
511 } else {
512 if (code == BUS_MCEERR_AO) {
513 return 0;
514 } else if (code == BUS_MCEERR_AR) {
515 hardware_memory_error();
516 } else {
517 return 1;
520 return 0;
523 static int kvm_inject_mce_oldstyle(X86CPU *cpu)
525 CPUX86State *env = &cpu->env;
527 if (!kvm_has_vcpu_events() && env->exception_injected == EXCP12_MCHK) {
528 unsigned int bank, bank_num = env->mcg_cap & 0xff;
529 struct kvm_x86_mce mce;
531 env->exception_injected = -1;
534 * There must be at least one bank in use if an MCE is pending.
535 * Find it and use its values for the event injection.
537 for (bank = 0; bank < bank_num; bank++) {
538 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
539 break;
542 assert(bank < bank_num);
544 mce.bank = bank;
545 mce.status = env->mce_banks[bank * 4 + 1];
546 mce.mcg_status = env->mcg_status;
547 mce.addr = env->mce_banks[bank * 4 + 2];
548 mce.misc = env->mce_banks[bank * 4 + 3];
550 return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
552 return 0;
555 static void cpu_update_state(void *opaque, int running, RunState state)
557 CPUX86State *env = opaque;
559 if (running) {
560 env->tsc_valid = false;
564 unsigned long kvm_arch_vcpu_id(CPUState *cs)
566 X86CPU *cpu = X86_CPU(cs);
567 return cpu->apic_id;
570 #ifndef KVM_CPUID_SIGNATURE_NEXT
571 #define KVM_CPUID_SIGNATURE_NEXT 0x40000100
572 #endif
574 static bool hyperv_hypercall_available(X86CPU *cpu)
576 return cpu->hyperv_vapic ||
577 (cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY);
580 static bool hyperv_enabled(X86CPU *cpu)
582 CPUState *cs = CPU(cpu);
583 return kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0 &&
584 (hyperv_hypercall_available(cpu) ||
585 cpu->hyperv_time ||
586 cpu->hyperv_relaxed_timing ||
587 cpu->hyperv_crash ||
588 cpu->hyperv_reset ||
589 cpu->hyperv_vpindex ||
590 cpu->hyperv_runtime ||
591 cpu->hyperv_synic ||
592 cpu->hyperv_stimer);
595 static int kvm_arch_set_tsc_khz(CPUState *cs)
597 X86CPU *cpu = X86_CPU(cs);
598 CPUX86State *env = &cpu->env;
599 int r;
601 if (!env->tsc_khz) {
602 return 0;
605 r = kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL) ?
606 kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) :
607 -ENOTSUP;
608 if (r < 0) {
609 /* When KVM_SET_TSC_KHZ fails, it's an error only if the current
610 * TSC frequency doesn't match the one we want.
612 int cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
613 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
614 -ENOTSUP;
615 if (cur_freq <= 0 || cur_freq != env->tsc_khz) {
616 error_report("warning: TSC frequency mismatch between "
617 "VM (%" PRId64 " kHz) and host (%d kHz), "
618 "and TSC scaling unavailable",
619 env->tsc_khz, cur_freq);
620 return r;
624 return 0;
627 static int hyperv_handle_properties(CPUState *cs)
629 X86CPU *cpu = X86_CPU(cs);
630 CPUX86State *env = &cpu->env;
632 if (cpu->hyperv_time &&
633 kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) <= 0) {
634 cpu->hyperv_time = false;
637 if (cpu->hyperv_relaxed_timing) {
638 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_HYPERCALL_AVAILABLE;
640 if (cpu->hyperv_vapic) {
641 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_HYPERCALL_AVAILABLE;
642 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_APIC_ACCESS_AVAILABLE;
644 if (cpu->hyperv_time) {
645 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_HYPERCALL_AVAILABLE;
646 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_TIME_REF_COUNT_AVAILABLE;
647 env->features[FEAT_HYPERV_EAX] |= 0x200;
649 if (cpu->hyperv_crash && has_msr_hv_crash) {
650 env->features[FEAT_HYPERV_EDX] |= HV_X64_GUEST_CRASH_MSR_AVAILABLE;
652 env->features[FEAT_HYPERV_EDX] |= HV_X64_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
653 if (cpu->hyperv_reset && has_msr_hv_reset) {
654 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_RESET_AVAILABLE;
656 if (cpu->hyperv_vpindex && has_msr_hv_vpindex) {
657 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_VP_INDEX_AVAILABLE;
659 if (cpu->hyperv_runtime && has_msr_hv_runtime) {
660 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_VP_RUNTIME_AVAILABLE;
662 if (cpu->hyperv_synic) {
663 int sint;
665 if (!has_msr_hv_synic ||
666 kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_SYNIC, 0)) {
667 fprintf(stderr, "Hyper-V SynIC is not supported by kernel\n");
668 return -ENOSYS;
671 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_SYNIC_AVAILABLE;
672 env->msr_hv_synic_version = HV_SYNIC_VERSION_1;
673 for (sint = 0; sint < ARRAY_SIZE(env->msr_hv_synic_sint); sint++) {
674 env->msr_hv_synic_sint[sint] = HV_SYNIC_SINT_MASKED;
677 if (cpu->hyperv_stimer) {
678 if (!has_msr_hv_stimer) {
679 fprintf(stderr, "Hyper-V timers aren't supported by kernel\n");
680 return -ENOSYS;
682 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_SYNTIMER_AVAILABLE;
684 return 0;
687 static Error *invtsc_mig_blocker;
689 #define KVM_MAX_CPUID_ENTRIES 100
691 int kvm_arch_init_vcpu(CPUState *cs)
693 struct {
694 struct kvm_cpuid2 cpuid;
695 struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
696 } QEMU_PACKED cpuid_data;
697 X86CPU *cpu = X86_CPU(cs);
698 CPUX86State *env = &cpu->env;
699 uint32_t limit, i, j, cpuid_i;
700 uint32_t unused;
701 struct kvm_cpuid_entry2 *c;
702 uint32_t signature[3];
703 int kvm_base = KVM_CPUID_SIGNATURE;
704 int r;
706 memset(&cpuid_data, 0, sizeof(cpuid_data));
708 cpuid_i = 0;
710 /* Paravirtualization CPUIDs */
711 if (hyperv_enabled(cpu)) {
712 c = &cpuid_data.entries[cpuid_i++];
713 c->function = HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
714 if (!cpu->hyperv_vendor_id) {
715 memcpy(signature, "Microsoft Hv", 12);
716 } else {
717 size_t len = strlen(cpu->hyperv_vendor_id);
719 if (len > 12) {
720 error_report("hv-vendor-id truncated to 12 characters");
721 len = 12;
723 memset(signature, 0, 12);
724 memcpy(signature, cpu->hyperv_vendor_id, len);
726 c->eax = HYPERV_CPUID_MIN;
727 c->ebx = signature[0];
728 c->ecx = signature[1];
729 c->edx = signature[2];
731 c = &cpuid_data.entries[cpuid_i++];
732 c->function = HYPERV_CPUID_INTERFACE;
733 memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
734 c->eax = signature[0];
735 c->ebx = 0;
736 c->ecx = 0;
737 c->edx = 0;
739 c = &cpuid_data.entries[cpuid_i++];
740 c->function = HYPERV_CPUID_VERSION;
741 c->eax = 0x00001bbc;
742 c->ebx = 0x00060001;
744 c = &cpuid_data.entries[cpuid_i++];
745 c->function = HYPERV_CPUID_FEATURES;
746 r = hyperv_handle_properties(cs);
747 if (r) {
748 return r;
750 c->eax = env->features[FEAT_HYPERV_EAX];
751 c->ebx = env->features[FEAT_HYPERV_EBX];
752 c->edx = env->features[FEAT_HYPERV_EDX];
754 c = &cpuid_data.entries[cpuid_i++];
755 c->function = HYPERV_CPUID_ENLIGHTMENT_INFO;
756 if (cpu->hyperv_relaxed_timing) {
757 c->eax |= HV_X64_RELAXED_TIMING_RECOMMENDED;
759 if (cpu->hyperv_vapic) {
760 c->eax |= HV_X64_APIC_ACCESS_RECOMMENDED;
762 c->ebx = cpu->hyperv_spinlock_attempts;
764 c = &cpuid_data.entries[cpuid_i++];
765 c->function = HYPERV_CPUID_IMPLEMENT_LIMITS;
766 c->eax = 0x40;
767 c->ebx = 0x40;
769 kvm_base = KVM_CPUID_SIGNATURE_NEXT;
770 has_msr_hv_hypercall = true;
773 if (cpu->expose_kvm) {
774 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
775 c = &cpuid_data.entries[cpuid_i++];
776 c->function = KVM_CPUID_SIGNATURE | kvm_base;
777 c->eax = KVM_CPUID_FEATURES | kvm_base;
778 c->ebx = signature[0];
779 c->ecx = signature[1];
780 c->edx = signature[2];
782 c = &cpuid_data.entries[cpuid_i++];
783 c->function = KVM_CPUID_FEATURES | kvm_base;
784 c->eax = env->features[FEAT_KVM];
787 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
789 for (i = 0; i <= limit; i++) {
790 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
791 fprintf(stderr, "unsupported level value: 0x%x\n", limit);
792 abort();
794 c = &cpuid_data.entries[cpuid_i++];
796 switch (i) {
797 case 2: {
798 /* Keep reading function 2 till all the input is received */
799 int times;
801 c->function = i;
802 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
803 KVM_CPUID_FLAG_STATE_READ_NEXT;
804 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
805 times = c->eax & 0xff;
807 for (j = 1; j < times; ++j) {
808 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
809 fprintf(stderr, "cpuid_data is full, no space for "
810 "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
811 abort();
813 c = &cpuid_data.entries[cpuid_i++];
814 c->function = i;
815 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
816 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
818 break;
820 case 4:
821 case 0xb:
822 case 0xd:
823 for (j = 0; ; j++) {
824 if (i == 0xd && j == 64) {
825 break;
827 c->function = i;
828 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
829 c->index = j;
830 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
832 if (i == 4 && c->eax == 0) {
833 break;
835 if (i == 0xb && !(c->ecx & 0xff00)) {
836 break;
838 if (i == 0xd && c->eax == 0) {
839 continue;
841 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
842 fprintf(stderr, "cpuid_data is full, no space for "
843 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
844 abort();
846 c = &cpuid_data.entries[cpuid_i++];
848 break;
849 default:
850 c->function = i;
851 c->flags = 0;
852 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
853 break;
857 if (limit >= 0x0a) {
858 uint32_t ver;
860 cpu_x86_cpuid(env, 0x0a, 0, &ver, &unused, &unused, &unused);
861 if ((ver & 0xff) > 0) {
862 has_msr_architectural_pmu = true;
863 num_architectural_pmu_counters = (ver & 0xff00) >> 8;
865 /* Shouldn't be more than 32, since that's the number of bits
866 * available in EBX to tell us _which_ counters are available.
867 * Play it safe.
869 if (num_architectural_pmu_counters > MAX_GP_COUNTERS) {
870 num_architectural_pmu_counters = MAX_GP_COUNTERS;
875 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
877 for (i = 0x80000000; i <= limit; i++) {
878 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
879 fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
880 abort();
882 c = &cpuid_data.entries[cpuid_i++];
884 c->function = i;
885 c->flags = 0;
886 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
889 /* Call Centaur's CPUID instructions they are supported. */
890 if (env->cpuid_xlevel2 > 0) {
891 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
893 for (i = 0xC0000000; i <= limit; i++) {
894 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
895 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
896 abort();
898 c = &cpuid_data.entries[cpuid_i++];
900 c->function = i;
901 c->flags = 0;
902 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
906 cpuid_data.cpuid.nent = cpuid_i;
908 if (((env->cpuid_version >> 8)&0xF) >= 6
909 && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
910 (CPUID_MCE | CPUID_MCA)
911 && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
912 uint64_t mcg_cap, unsupported_caps;
913 int banks;
914 int ret;
916 ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
917 if (ret < 0) {
918 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
919 return ret;
922 if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
923 error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
924 (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
925 return -ENOTSUP;
928 unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
929 if (unsupported_caps) {
930 if (unsupported_caps & MCG_LMCE_P) {
931 error_report("kvm: LMCE not supported");
932 return -ENOTSUP;
934 error_report("warning: Unsupported MCG_CAP bits: 0x%" PRIx64,
935 unsupported_caps);
938 env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
939 ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
940 if (ret < 0) {
941 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
942 return ret;
946 qemu_add_vm_change_state_handler(cpu_update_state, env);
948 c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
949 if (c) {
950 has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
951 !!(c->ecx & CPUID_EXT_SMX);
954 if (env->mcg_cap & MCG_LMCE_P) {
955 has_msr_mcg_ext_ctl = has_msr_feature_control = true;
958 c = cpuid_find_entry(&cpuid_data.cpuid, 0x80000007, 0);
959 if (c && (c->edx & 1<<8) && invtsc_mig_blocker == NULL) {
960 /* for migration */
961 error_setg(&invtsc_mig_blocker,
962 "State blocked by non-migratable CPU device"
963 " (invtsc flag)");
964 migrate_add_blocker(invtsc_mig_blocker);
965 /* for savevm */
966 vmstate_x86_cpu.unmigratable = 1;
969 cpuid_data.cpuid.padding = 0;
970 r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
971 if (r) {
972 return r;
975 r = kvm_arch_set_tsc_khz(cs);
976 if (r < 0) {
977 return r;
980 /* vcpu's TSC frequency is either specified by user, or following
981 * the value used by KVM if the former is not present. In the
982 * latter case, we query it from KVM and record in env->tsc_khz,
983 * so that vcpu's TSC frequency can be migrated later via this field.
985 if (!env->tsc_khz) {
986 r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
987 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
988 -ENOTSUP;
989 if (r > 0) {
990 env->tsc_khz = r;
994 if (has_xsave) {
995 env->kvm_xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
997 cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
999 if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
1000 has_msr_tsc_aux = false;
1003 return 0;
1006 void kvm_arch_reset_vcpu(X86CPU *cpu)
1008 CPUX86State *env = &cpu->env;
1010 env->exception_injected = -1;
1011 env->interrupt_injected = -1;
1012 env->xcr0 = 1;
1013 if (kvm_irqchip_in_kernel()) {
1014 env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
1015 KVM_MP_STATE_UNINITIALIZED;
1016 } else {
1017 env->mp_state = KVM_MP_STATE_RUNNABLE;
1021 void kvm_arch_do_init_vcpu(X86CPU *cpu)
1023 CPUX86State *env = &cpu->env;
1025 /* APs get directly into wait-for-SIPI state. */
1026 if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
1027 env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
1031 static int kvm_get_supported_msrs(KVMState *s)
1033 static int kvm_supported_msrs;
1034 int ret = 0;
1036 /* first time */
1037 if (kvm_supported_msrs == 0) {
1038 struct kvm_msr_list msr_list, *kvm_msr_list;
1040 kvm_supported_msrs = -1;
1042 /* Obtain MSR list from KVM. These are the MSRs that we must
1043 * save/restore */
1044 msr_list.nmsrs = 0;
1045 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
1046 if (ret < 0 && ret != -E2BIG) {
1047 return ret;
1049 /* Old kernel modules had a bug and could write beyond the provided
1050 memory. Allocate at least a safe amount of 1K. */
1051 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
1052 msr_list.nmsrs *
1053 sizeof(msr_list.indices[0])));
1055 kvm_msr_list->nmsrs = msr_list.nmsrs;
1056 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
1057 if (ret >= 0) {
1058 int i;
1060 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
1061 if (kvm_msr_list->indices[i] == MSR_STAR) {
1062 has_msr_star = true;
1063 continue;
1065 if (kvm_msr_list->indices[i] == MSR_VM_HSAVE_PA) {
1066 has_msr_hsave_pa = true;
1067 continue;
1069 if (kvm_msr_list->indices[i] == MSR_TSC_AUX) {
1070 has_msr_tsc_aux = true;
1071 continue;
1073 if (kvm_msr_list->indices[i] == MSR_TSC_ADJUST) {
1074 has_msr_tsc_adjust = true;
1075 continue;
1077 if (kvm_msr_list->indices[i] == MSR_IA32_TSCDEADLINE) {
1078 has_msr_tsc_deadline = true;
1079 continue;
1081 if (kvm_msr_list->indices[i] == MSR_IA32_SMBASE) {
1082 has_msr_smbase = true;
1083 continue;
1085 if (kvm_msr_list->indices[i] == MSR_IA32_MISC_ENABLE) {
1086 has_msr_misc_enable = true;
1087 continue;
1089 if (kvm_msr_list->indices[i] == MSR_IA32_BNDCFGS) {
1090 has_msr_bndcfgs = true;
1091 continue;
1093 if (kvm_msr_list->indices[i] == MSR_IA32_XSS) {
1094 has_msr_xss = true;
1095 continue;
1097 if (kvm_msr_list->indices[i] == HV_X64_MSR_CRASH_CTL) {
1098 has_msr_hv_crash = true;
1099 continue;
1101 if (kvm_msr_list->indices[i] == HV_X64_MSR_RESET) {
1102 has_msr_hv_reset = true;
1103 continue;
1105 if (kvm_msr_list->indices[i] == HV_X64_MSR_VP_INDEX) {
1106 has_msr_hv_vpindex = true;
1107 continue;
1109 if (kvm_msr_list->indices[i] == HV_X64_MSR_VP_RUNTIME) {
1110 has_msr_hv_runtime = true;
1111 continue;
1113 if (kvm_msr_list->indices[i] == HV_X64_MSR_SCONTROL) {
1114 has_msr_hv_synic = true;
1115 continue;
1117 if (kvm_msr_list->indices[i] == HV_X64_MSR_STIMER0_CONFIG) {
1118 has_msr_hv_stimer = true;
1119 continue;
1124 g_free(kvm_msr_list);
1127 return ret;
1130 static Notifier smram_machine_done;
1131 static KVMMemoryListener smram_listener;
1132 static AddressSpace smram_address_space;
1133 static MemoryRegion smram_as_root;
1134 static MemoryRegion smram_as_mem;
1136 static void register_smram_listener(Notifier *n, void *unused)
1138 MemoryRegion *smram =
1139 (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
1141 /* Outer container... */
1142 memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
1143 memory_region_set_enabled(&smram_as_root, true);
1145 /* ... with two regions inside: normal system memory with low
1146 * priority, and...
1148 memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
1149 get_system_memory(), 0, ~0ull);
1150 memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
1151 memory_region_set_enabled(&smram_as_mem, true);
1153 if (smram) {
1154 /* ... SMRAM with higher priority */
1155 memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
1156 memory_region_set_enabled(smram, true);
1159 address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
1160 kvm_memory_listener_register(kvm_state, &smram_listener,
1161 &smram_address_space, 1);
1164 int kvm_arch_init(MachineState *ms, KVMState *s)
1166 uint64_t identity_base = 0xfffbc000;
1167 uint64_t shadow_mem;
1168 int ret;
1169 struct utsname utsname;
1171 #ifdef KVM_CAP_XSAVE
1172 has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1173 #endif
1175 #ifdef KVM_CAP_XCRS
1176 has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1177 #endif
1179 #ifdef KVM_CAP_PIT_STATE2
1180 has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1181 #endif
1183 ret = kvm_get_supported_msrs(s);
1184 if (ret < 0) {
1185 return ret;
1188 uname(&utsname);
1189 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
1192 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
1193 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
1194 * Since these must be part of guest physical memory, we need to allocate
1195 * them, both by setting their start addresses in the kernel and by
1196 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
1198 * Older KVM versions may not support setting the identity map base. In
1199 * that case we need to stick with the default, i.e. a 256K maximum BIOS
1200 * size.
1202 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
1203 /* Allows up to 16M BIOSes. */
1204 identity_base = 0xfeffc000;
1206 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
1207 if (ret < 0) {
1208 return ret;
1212 /* Set TSS base one page after EPT identity map. */
1213 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
1214 if (ret < 0) {
1215 return ret;
1218 /* Tell fw_cfg to notify the BIOS to reserve the range. */
1219 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
1220 if (ret < 0) {
1221 fprintf(stderr, "e820_add_entry() table is full\n");
1222 return ret;
1224 qemu_register_reset(kvm_unpoison_all, NULL);
1226 shadow_mem = machine_kvm_shadow_mem(ms);
1227 if (shadow_mem != -1) {
1228 shadow_mem /= 4096;
1229 ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
1230 if (ret < 0) {
1231 return ret;
1235 if (kvm_check_extension(s, KVM_CAP_X86_SMM)) {
1236 smram_machine_done.notify = register_smram_listener;
1237 qemu_add_machine_init_done_notifier(&smram_machine_done);
1239 return 0;
1242 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1244 lhs->selector = rhs->selector;
1245 lhs->base = rhs->base;
1246 lhs->limit = rhs->limit;
1247 lhs->type = 3;
1248 lhs->present = 1;
1249 lhs->dpl = 3;
1250 lhs->db = 0;
1251 lhs->s = 1;
1252 lhs->l = 0;
1253 lhs->g = 0;
1254 lhs->avl = 0;
1255 lhs->unusable = 0;
1258 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1260 unsigned flags = rhs->flags;
1261 lhs->selector = rhs->selector;
1262 lhs->base = rhs->base;
1263 lhs->limit = rhs->limit;
1264 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
1265 lhs->present = (flags & DESC_P_MASK) != 0;
1266 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
1267 lhs->db = (flags >> DESC_B_SHIFT) & 1;
1268 lhs->s = (flags & DESC_S_MASK) != 0;
1269 lhs->l = (flags >> DESC_L_SHIFT) & 1;
1270 lhs->g = (flags & DESC_G_MASK) != 0;
1271 lhs->avl = (flags & DESC_AVL_MASK) != 0;
1272 lhs->unusable = !lhs->present;
1273 lhs->padding = 0;
1276 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
1278 lhs->selector = rhs->selector;
1279 lhs->base = rhs->base;
1280 lhs->limit = rhs->limit;
1281 if (rhs->unusable) {
1282 lhs->flags = 0;
1283 } else {
1284 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
1285 (rhs->present * DESC_P_MASK) |
1286 (rhs->dpl << DESC_DPL_SHIFT) |
1287 (rhs->db << DESC_B_SHIFT) |
1288 (rhs->s * DESC_S_MASK) |
1289 (rhs->l << DESC_L_SHIFT) |
1290 (rhs->g * DESC_G_MASK) |
1291 (rhs->avl * DESC_AVL_MASK);
1295 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
1297 if (set) {
1298 *kvm_reg = *qemu_reg;
1299 } else {
1300 *qemu_reg = *kvm_reg;
1304 static int kvm_getput_regs(X86CPU *cpu, int set)
1306 CPUX86State *env = &cpu->env;
1307 struct kvm_regs regs;
1308 int ret = 0;
1310 if (!set) {
1311 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
1312 if (ret < 0) {
1313 return ret;
1317 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
1318 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
1319 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
1320 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
1321 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
1322 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
1323 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
1324 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
1325 #ifdef TARGET_X86_64
1326 kvm_getput_reg(&regs.r8, &env->regs[8], set);
1327 kvm_getput_reg(&regs.r9, &env->regs[9], set);
1328 kvm_getput_reg(&regs.r10, &env->regs[10], set);
1329 kvm_getput_reg(&regs.r11, &env->regs[11], set);
1330 kvm_getput_reg(&regs.r12, &env->regs[12], set);
1331 kvm_getput_reg(&regs.r13, &env->regs[13], set);
1332 kvm_getput_reg(&regs.r14, &env->regs[14], set);
1333 kvm_getput_reg(&regs.r15, &env->regs[15], set);
1334 #endif
1336 kvm_getput_reg(&regs.rflags, &env->eflags, set);
1337 kvm_getput_reg(&regs.rip, &env->eip, set);
1339 if (set) {
1340 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
1343 return ret;
1346 static int kvm_put_fpu(X86CPU *cpu)
1348 CPUX86State *env = &cpu->env;
1349 struct kvm_fpu fpu;
1350 int i;
1352 memset(&fpu, 0, sizeof fpu);
1353 fpu.fsw = env->fpus & ~(7 << 11);
1354 fpu.fsw |= (env->fpstt & 7) << 11;
1355 fpu.fcw = env->fpuc;
1356 fpu.last_opcode = env->fpop;
1357 fpu.last_ip = env->fpip;
1358 fpu.last_dp = env->fpdp;
1359 for (i = 0; i < 8; ++i) {
1360 fpu.ftwx |= (!env->fptags[i]) << i;
1362 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
1363 for (i = 0; i < CPU_NB_REGS; i++) {
1364 stq_p(&fpu.xmm[i][0], env->xmm_regs[i].ZMM_Q(0));
1365 stq_p(&fpu.xmm[i][8], env->xmm_regs[i].ZMM_Q(1));
1367 fpu.mxcsr = env->mxcsr;
1369 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
1372 #define XSAVE_FCW_FSW 0
1373 #define XSAVE_FTW_FOP 1
1374 #define XSAVE_CWD_RIP 2
1375 #define XSAVE_CWD_RDP 4
1376 #define XSAVE_MXCSR 6
1377 #define XSAVE_ST_SPACE 8
1378 #define XSAVE_XMM_SPACE 40
1379 #define XSAVE_XSTATE_BV 128
1380 #define XSAVE_YMMH_SPACE 144
1381 #define XSAVE_BNDREGS 240
1382 #define XSAVE_BNDCSR 256
1383 #define XSAVE_OPMASK 272
1384 #define XSAVE_ZMM_Hi256 288
1385 #define XSAVE_Hi16_ZMM 416
1386 #define XSAVE_PKRU 672
1388 #define XSAVE_BYTE_OFFSET(word_offset) \
1389 ((word_offset) * sizeof(((struct kvm_xsave *)0)->region[0]))
1391 #define ASSERT_OFFSET(word_offset, field) \
1392 QEMU_BUILD_BUG_ON(XSAVE_BYTE_OFFSET(word_offset) != \
1393 offsetof(X86XSaveArea, field))
1395 ASSERT_OFFSET(XSAVE_FCW_FSW, legacy.fcw);
1396 ASSERT_OFFSET(XSAVE_FTW_FOP, legacy.ftw);
1397 ASSERT_OFFSET(XSAVE_CWD_RIP, legacy.fpip);
1398 ASSERT_OFFSET(XSAVE_CWD_RDP, legacy.fpdp);
1399 ASSERT_OFFSET(XSAVE_MXCSR, legacy.mxcsr);
1400 ASSERT_OFFSET(XSAVE_ST_SPACE, legacy.fpregs);
1401 ASSERT_OFFSET(XSAVE_XMM_SPACE, legacy.xmm_regs);
1402 ASSERT_OFFSET(XSAVE_XSTATE_BV, header.xstate_bv);
1403 ASSERT_OFFSET(XSAVE_YMMH_SPACE, avx_state);
1404 ASSERT_OFFSET(XSAVE_BNDREGS, bndreg_state);
1405 ASSERT_OFFSET(XSAVE_BNDCSR, bndcsr_state);
1406 ASSERT_OFFSET(XSAVE_OPMASK, opmask_state);
1407 ASSERT_OFFSET(XSAVE_ZMM_Hi256, zmm_hi256_state);
1408 ASSERT_OFFSET(XSAVE_Hi16_ZMM, hi16_zmm_state);
1409 ASSERT_OFFSET(XSAVE_PKRU, pkru_state);
1411 static int kvm_put_xsave(X86CPU *cpu)
1413 CPUX86State *env = &cpu->env;
1414 X86XSaveArea *xsave = env->kvm_xsave_buf;
1415 uint16_t cwd, swd, twd;
1416 int i;
1418 if (!has_xsave) {
1419 return kvm_put_fpu(cpu);
1422 memset(xsave, 0, sizeof(struct kvm_xsave));
1423 twd = 0;
1424 swd = env->fpus & ~(7 << 11);
1425 swd |= (env->fpstt & 7) << 11;
1426 cwd = env->fpuc;
1427 for (i = 0; i < 8; ++i) {
1428 twd |= (!env->fptags[i]) << i;
1430 xsave->legacy.fcw = cwd;
1431 xsave->legacy.fsw = swd;
1432 xsave->legacy.ftw = twd;
1433 xsave->legacy.fpop = env->fpop;
1434 xsave->legacy.fpip = env->fpip;
1435 xsave->legacy.fpdp = env->fpdp;
1436 memcpy(&xsave->legacy.fpregs, env->fpregs,
1437 sizeof env->fpregs);
1438 xsave->legacy.mxcsr = env->mxcsr;
1439 xsave->header.xstate_bv = env->xstate_bv;
1440 memcpy(&xsave->bndreg_state.bnd_regs, env->bnd_regs,
1441 sizeof env->bnd_regs);
1442 xsave->bndcsr_state.bndcsr = env->bndcs_regs;
1443 memcpy(&xsave->opmask_state.opmask_regs, env->opmask_regs,
1444 sizeof env->opmask_regs);
1446 for (i = 0; i < CPU_NB_REGS; i++) {
1447 uint8_t *xmm = xsave->legacy.xmm_regs[i];
1448 uint8_t *ymmh = xsave->avx_state.ymmh[i];
1449 uint8_t *zmmh = xsave->zmm_hi256_state.zmm_hi256[i];
1450 stq_p(xmm, env->xmm_regs[i].ZMM_Q(0));
1451 stq_p(xmm+8, env->xmm_regs[i].ZMM_Q(1));
1452 stq_p(ymmh, env->xmm_regs[i].ZMM_Q(2));
1453 stq_p(ymmh+8, env->xmm_regs[i].ZMM_Q(3));
1454 stq_p(zmmh, env->xmm_regs[i].ZMM_Q(4));
1455 stq_p(zmmh+8, env->xmm_regs[i].ZMM_Q(5));
1456 stq_p(zmmh+16, env->xmm_regs[i].ZMM_Q(6));
1457 stq_p(zmmh+24, env->xmm_regs[i].ZMM_Q(7));
1460 #ifdef TARGET_X86_64
1461 memcpy(&xsave->hi16_zmm_state.hi16_zmm, &env->xmm_regs[16],
1462 16 * sizeof env->xmm_regs[16]);
1463 memcpy(&xsave->pkru_state, &env->pkru, sizeof env->pkru);
1464 #endif
1465 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
1468 static int kvm_put_xcrs(X86CPU *cpu)
1470 CPUX86State *env = &cpu->env;
1471 struct kvm_xcrs xcrs = {};
1473 if (!has_xcrs) {
1474 return 0;
1477 xcrs.nr_xcrs = 1;
1478 xcrs.flags = 0;
1479 xcrs.xcrs[0].xcr = 0;
1480 xcrs.xcrs[0].value = env->xcr0;
1481 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
1484 static int kvm_put_sregs(X86CPU *cpu)
1486 CPUX86State *env = &cpu->env;
1487 struct kvm_sregs sregs;
1489 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
1490 if (env->interrupt_injected >= 0) {
1491 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
1492 (uint64_t)1 << (env->interrupt_injected % 64);
1495 if ((env->eflags & VM_MASK)) {
1496 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
1497 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
1498 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
1499 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
1500 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
1501 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
1502 } else {
1503 set_seg(&sregs.cs, &env->segs[R_CS]);
1504 set_seg(&sregs.ds, &env->segs[R_DS]);
1505 set_seg(&sregs.es, &env->segs[R_ES]);
1506 set_seg(&sregs.fs, &env->segs[R_FS]);
1507 set_seg(&sregs.gs, &env->segs[R_GS]);
1508 set_seg(&sregs.ss, &env->segs[R_SS]);
1511 set_seg(&sregs.tr, &env->tr);
1512 set_seg(&sregs.ldt, &env->ldt);
1514 sregs.idt.limit = env->idt.limit;
1515 sregs.idt.base = env->idt.base;
1516 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
1517 sregs.gdt.limit = env->gdt.limit;
1518 sregs.gdt.base = env->gdt.base;
1519 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
1521 sregs.cr0 = env->cr[0];
1522 sregs.cr2 = env->cr[2];
1523 sregs.cr3 = env->cr[3];
1524 sregs.cr4 = env->cr[4];
1526 sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
1527 sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
1529 sregs.efer = env->efer;
1531 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
1534 static void kvm_msr_buf_reset(X86CPU *cpu)
1536 memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
1539 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
1541 struct kvm_msrs *msrs = cpu->kvm_msr_buf;
1542 void *limit = ((void *)msrs) + MSR_BUF_SIZE;
1543 struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
1545 assert((void *)(entry + 1) <= limit);
1547 entry->index = index;
1548 entry->reserved = 0;
1549 entry->data = value;
1550 msrs->nmsrs++;
1553 static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
1555 kvm_msr_buf_reset(cpu);
1556 kvm_msr_entry_add(cpu, index, value);
1558 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1561 void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
1563 int ret;
1565 ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
1566 assert(ret == 1);
1569 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
1571 CPUX86State *env = &cpu->env;
1572 int ret;
1574 if (!has_msr_tsc_deadline) {
1575 return 0;
1578 ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
1579 if (ret < 0) {
1580 return ret;
1583 assert(ret == 1);
1584 return 0;
1588 * Provide a separate write service for the feature control MSR in order to
1589 * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
1590 * before writing any other state because forcibly leaving nested mode
1591 * invalidates the VCPU state.
1593 static int kvm_put_msr_feature_control(X86CPU *cpu)
1595 int ret;
1597 if (!has_msr_feature_control) {
1598 return 0;
1601 ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
1602 cpu->env.msr_ia32_feature_control);
1603 if (ret < 0) {
1604 return ret;
1607 assert(ret == 1);
1608 return 0;
1611 static int kvm_put_msrs(X86CPU *cpu, int level)
1613 CPUX86State *env = &cpu->env;
1614 int i;
1615 int ret;
1617 kvm_msr_buf_reset(cpu);
1619 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
1620 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
1621 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
1622 kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
1623 if (has_msr_star) {
1624 kvm_msr_entry_add(cpu, MSR_STAR, env->star);
1626 if (has_msr_hsave_pa) {
1627 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
1629 if (has_msr_tsc_aux) {
1630 kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
1632 if (has_msr_tsc_adjust) {
1633 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
1635 if (has_msr_misc_enable) {
1636 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
1637 env->msr_ia32_misc_enable);
1639 if (has_msr_smbase) {
1640 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
1642 if (has_msr_bndcfgs) {
1643 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
1645 if (has_msr_xss) {
1646 kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
1648 #ifdef TARGET_X86_64
1649 if (lm_capable_kernel) {
1650 kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
1651 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
1652 kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
1653 kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
1655 #endif
1657 * The following MSRs have side effects on the guest or are too heavy
1658 * for normal writeback. Limit them to reset or full state updates.
1660 if (level >= KVM_PUT_RESET_STATE) {
1661 kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
1662 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
1663 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
1664 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
1665 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
1667 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
1668 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
1670 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
1671 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
1673 if (has_msr_architectural_pmu) {
1674 /* Stop the counter. */
1675 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
1676 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
1678 /* Set the counter values. */
1679 for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
1680 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
1681 env->msr_fixed_counters[i]);
1683 for (i = 0; i < num_architectural_pmu_counters; i++) {
1684 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
1685 env->msr_gp_counters[i]);
1686 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
1687 env->msr_gp_evtsel[i]);
1689 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
1690 env->msr_global_status);
1691 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1692 env->msr_global_ovf_ctrl);
1694 /* Now start the PMU. */
1695 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
1696 env->msr_fixed_ctr_ctrl);
1697 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
1698 env->msr_global_ctrl);
1700 if (has_msr_hv_hypercall) {
1701 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
1702 env->msr_hv_guest_os_id);
1703 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
1704 env->msr_hv_hypercall);
1706 if (cpu->hyperv_vapic) {
1707 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
1708 env->msr_hv_vapic);
1710 if (cpu->hyperv_time) {
1711 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, env->msr_hv_tsc);
1713 if (has_msr_hv_crash) {
1714 int j;
1716 for (j = 0; j < HV_X64_MSR_CRASH_PARAMS; j++)
1717 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
1718 env->msr_hv_crash_params[j]);
1720 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL,
1721 HV_X64_MSR_CRASH_CTL_NOTIFY);
1723 if (has_msr_hv_runtime) {
1724 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
1726 if (cpu->hyperv_synic) {
1727 int j;
1729 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
1730 env->msr_hv_synic_control);
1731 kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION,
1732 env->msr_hv_synic_version);
1733 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
1734 env->msr_hv_synic_evt_page);
1735 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
1736 env->msr_hv_synic_msg_page);
1738 for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
1739 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
1740 env->msr_hv_synic_sint[j]);
1743 if (has_msr_hv_stimer) {
1744 int j;
1746 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
1747 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
1748 env->msr_hv_stimer_config[j]);
1751 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
1752 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
1753 env->msr_hv_stimer_count[j]);
1756 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
1757 uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
1759 kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
1760 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
1761 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
1762 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
1763 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
1764 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
1765 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
1766 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
1767 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
1768 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
1769 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
1770 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
1771 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
1772 /* The CPU GPs if we write to a bit above the physical limit of
1773 * the host CPU (and KVM emulates that)
1775 uint64_t mask = env->mtrr_var[i].mask;
1776 mask &= phys_mask;
1778 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
1779 env->mtrr_var[i].base);
1780 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
1784 /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
1785 * kvm_put_msr_feature_control. */
1787 if (env->mcg_cap) {
1788 int i;
1790 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
1791 kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
1792 if (has_msr_mcg_ext_ctl) {
1793 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
1795 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1796 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
1800 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1801 if (ret < 0) {
1802 return ret;
1805 assert(ret == cpu->kvm_msr_buf->nmsrs);
1806 return 0;
1810 static int kvm_get_fpu(X86CPU *cpu)
1812 CPUX86State *env = &cpu->env;
1813 struct kvm_fpu fpu;
1814 int i, ret;
1816 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
1817 if (ret < 0) {
1818 return ret;
1821 env->fpstt = (fpu.fsw >> 11) & 7;
1822 env->fpus = fpu.fsw;
1823 env->fpuc = fpu.fcw;
1824 env->fpop = fpu.last_opcode;
1825 env->fpip = fpu.last_ip;
1826 env->fpdp = fpu.last_dp;
1827 for (i = 0; i < 8; ++i) {
1828 env->fptags[i] = !((fpu.ftwx >> i) & 1);
1830 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
1831 for (i = 0; i < CPU_NB_REGS; i++) {
1832 env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
1833 env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
1835 env->mxcsr = fpu.mxcsr;
1837 return 0;
1840 static int kvm_get_xsave(X86CPU *cpu)
1842 CPUX86State *env = &cpu->env;
1843 X86XSaveArea *xsave = env->kvm_xsave_buf;
1844 int ret, i;
1845 uint16_t cwd, swd, twd;
1847 if (!has_xsave) {
1848 return kvm_get_fpu(cpu);
1851 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
1852 if (ret < 0) {
1853 return ret;
1856 cwd = xsave->legacy.fcw;
1857 swd = xsave->legacy.fsw;
1858 twd = xsave->legacy.ftw;
1859 env->fpop = xsave->legacy.fpop;
1860 env->fpstt = (swd >> 11) & 7;
1861 env->fpus = swd;
1862 env->fpuc = cwd;
1863 for (i = 0; i < 8; ++i) {
1864 env->fptags[i] = !((twd >> i) & 1);
1866 env->fpip = xsave->legacy.fpip;
1867 env->fpdp = xsave->legacy.fpdp;
1868 env->mxcsr = xsave->legacy.mxcsr;
1869 memcpy(env->fpregs, &xsave->legacy.fpregs,
1870 sizeof env->fpregs);
1871 env->xstate_bv = xsave->header.xstate_bv;
1872 memcpy(env->bnd_regs, &xsave->bndreg_state.bnd_regs,
1873 sizeof env->bnd_regs);
1874 env->bndcs_regs = xsave->bndcsr_state.bndcsr;
1875 memcpy(env->opmask_regs, &xsave->opmask_state.opmask_regs,
1876 sizeof env->opmask_regs);
1878 for (i = 0; i < CPU_NB_REGS; i++) {
1879 uint8_t *xmm = xsave->legacy.xmm_regs[i];
1880 uint8_t *ymmh = xsave->avx_state.ymmh[i];
1881 uint8_t *zmmh = xsave->zmm_hi256_state.zmm_hi256[i];
1882 env->xmm_regs[i].ZMM_Q(0) = ldq_p(xmm);
1883 env->xmm_regs[i].ZMM_Q(1) = ldq_p(xmm+8);
1884 env->xmm_regs[i].ZMM_Q(2) = ldq_p(ymmh);
1885 env->xmm_regs[i].ZMM_Q(3) = ldq_p(ymmh+8);
1886 env->xmm_regs[i].ZMM_Q(4) = ldq_p(zmmh);
1887 env->xmm_regs[i].ZMM_Q(5) = ldq_p(zmmh+8);
1888 env->xmm_regs[i].ZMM_Q(6) = ldq_p(zmmh+16);
1889 env->xmm_regs[i].ZMM_Q(7) = ldq_p(zmmh+24);
1892 #ifdef TARGET_X86_64
1893 memcpy(&env->xmm_regs[16], &xsave->hi16_zmm_state.hi16_zmm,
1894 16 * sizeof env->xmm_regs[16]);
1895 memcpy(&env->pkru, &xsave->pkru_state, sizeof env->pkru);
1896 #endif
1897 return 0;
1900 static int kvm_get_xcrs(X86CPU *cpu)
1902 CPUX86State *env = &cpu->env;
1903 int i, ret;
1904 struct kvm_xcrs xcrs;
1906 if (!has_xcrs) {
1907 return 0;
1910 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
1911 if (ret < 0) {
1912 return ret;
1915 for (i = 0; i < xcrs.nr_xcrs; i++) {
1916 /* Only support xcr0 now */
1917 if (xcrs.xcrs[i].xcr == 0) {
1918 env->xcr0 = xcrs.xcrs[i].value;
1919 break;
1922 return 0;
1925 static int kvm_get_sregs(X86CPU *cpu)
1927 CPUX86State *env = &cpu->env;
1928 struct kvm_sregs sregs;
1929 uint32_t hflags;
1930 int bit, i, ret;
1932 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
1933 if (ret < 0) {
1934 return ret;
1937 /* There can only be one pending IRQ set in the bitmap at a time, so try
1938 to find it and save its number instead (-1 for none). */
1939 env->interrupt_injected = -1;
1940 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
1941 if (sregs.interrupt_bitmap[i]) {
1942 bit = ctz64(sregs.interrupt_bitmap[i]);
1943 env->interrupt_injected = i * 64 + bit;
1944 break;
1948 get_seg(&env->segs[R_CS], &sregs.cs);
1949 get_seg(&env->segs[R_DS], &sregs.ds);
1950 get_seg(&env->segs[R_ES], &sregs.es);
1951 get_seg(&env->segs[R_FS], &sregs.fs);
1952 get_seg(&env->segs[R_GS], &sregs.gs);
1953 get_seg(&env->segs[R_SS], &sregs.ss);
1955 get_seg(&env->tr, &sregs.tr);
1956 get_seg(&env->ldt, &sregs.ldt);
1958 env->idt.limit = sregs.idt.limit;
1959 env->idt.base = sregs.idt.base;
1960 env->gdt.limit = sregs.gdt.limit;
1961 env->gdt.base = sregs.gdt.base;
1963 env->cr[0] = sregs.cr0;
1964 env->cr[2] = sregs.cr2;
1965 env->cr[3] = sregs.cr3;
1966 env->cr[4] = sregs.cr4;
1968 env->efer = sregs.efer;
1970 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
1972 #define HFLAG_COPY_MASK \
1973 ~( HF_CPL_MASK | HF_PE_MASK | HF_MP_MASK | HF_EM_MASK | \
1974 HF_TS_MASK | HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK | \
1975 HF_OSFXSR_MASK | HF_LMA_MASK | HF_CS32_MASK | \
1976 HF_SS32_MASK | HF_CS64_MASK | HF_ADDSEG_MASK)
1978 hflags = env->hflags & HFLAG_COPY_MASK;
1979 hflags |= (env->segs[R_SS].flags >> DESC_DPL_SHIFT) & HF_CPL_MASK;
1980 hflags |= (env->cr[0] & CR0_PE_MASK) << (HF_PE_SHIFT - CR0_PE_SHIFT);
1981 hflags |= (env->cr[0] << (HF_MP_SHIFT - CR0_MP_SHIFT)) &
1982 (HF_MP_MASK | HF_EM_MASK | HF_TS_MASK);
1983 hflags |= (env->eflags & (HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK));
1985 if (env->cr[4] & CR4_OSFXSR_MASK) {
1986 hflags |= HF_OSFXSR_MASK;
1989 if (env->efer & MSR_EFER_LMA) {
1990 hflags |= HF_LMA_MASK;
1993 if ((hflags & HF_LMA_MASK) && (env->segs[R_CS].flags & DESC_L_MASK)) {
1994 hflags |= HF_CS32_MASK | HF_SS32_MASK | HF_CS64_MASK;
1995 } else {
1996 hflags |= (env->segs[R_CS].flags & DESC_B_MASK) >>
1997 (DESC_B_SHIFT - HF_CS32_SHIFT);
1998 hflags |= (env->segs[R_SS].flags & DESC_B_MASK) >>
1999 (DESC_B_SHIFT - HF_SS32_SHIFT);
2000 if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK) ||
2001 !(hflags & HF_CS32_MASK)) {
2002 hflags |= HF_ADDSEG_MASK;
2003 } else {
2004 hflags |= ((env->segs[R_DS].base | env->segs[R_ES].base |
2005 env->segs[R_SS].base) != 0) << HF_ADDSEG_SHIFT;
2008 env->hflags = hflags;
2010 return 0;
2013 static int kvm_get_msrs(X86CPU *cpu)
2015 CPUX86State *env = &cpu->env;
2016 struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
2017 int ret, i;
2018 uint64_t mtrr_top_bits;
2020 kvm_msr_buf_reset(cpu);
2022 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
2023 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
2024 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
2025 kvm_msr_entry_add(cpu, MSR_PAT, 0);
2026 if (has_msr_star) {
2027 kvm_msr_entry_add(cpu, MSR_STAR, 0);
2029 if (has_msr_hsave_pa) {
2030 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
2032 if (has_msr_tsc_aux) {
2033 kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
2035 if (has_msr_tsc_adjust) {
2036 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
2038 if (has_msr_tsc_deadline) {
2039 kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
2041 if (has_msr_misc_enable) {
2042 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
2044 if (has_msr_smbase) {
2045 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
2047 if (has_msr_feature_control) {
2048 kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
2050 if (has_msr_bndcfgs) {
2051 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
2053 if (has_msr_xss) {
2054 kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
2058 if (!env->tsc_valid) {
2059 kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
2060 env->tsc_valid = !runstate_is_running();
2063 #ifdef TARGET_X86_64
2064 if (lm_capable_kernel) {
2065 kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
2066 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
2067 kvm_msr_entry_add(cpu, MSR_FMASK, 0);
2068 kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
2070 #endif
2071 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
2072 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
2073 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
2074 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
2076 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
2077 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
2079 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
2080 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
2082 if (has_msr_architectural_pmu) {
2083 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
2084 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
2085 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
2086 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
2087 for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
2088 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
2090 for (i = 0; i < num_architectural_pmu_counters; i++) {
2091 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
2092 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
2096 if (env->mcg_cap) {
2097 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
2098 kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
2099 if (has_msr_mcg_ext_ctl) {
2100 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
2102 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
2103 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
2107 if (has_msr_hv_hypercall) {
2108 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
2109 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
2111 if (cpu->hyperv_vapic) {
2112 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
2114 if (cpu->hyperv_time) {
2115 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
2117 if (has_msr_hv_crash) {
2118 int j;
2120 for (j = 0; j < HV_X64_MSR_CRASH_PARAMS; j++) {
2121 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
2124 if (has_msr_hv_runtime) {
2125 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
2127 if (cpu->hyperv_synic) {
2128 uint32_t msr;
2130 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
2131 kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, 0);
2132 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
2133 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
2134 for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
2135 kvm_msr_entry_add(cpu, msr, 0);
2138 if (has_msr_hv_stimer) {
2139 uint32_t msr;
2141 for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
2142 msr++) {
2143 kvm_msr_entry_add(cpu, msr, 0);
2146 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
2147 kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
2148 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
2149 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
2150 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
2151 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
2152 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
2153 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
2154 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
2155 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
2156 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
2157 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
2158 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
2159 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
2160 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
2161 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
2165 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
2166 if (ret < 0) {
2167 return ret;
2170 assert(ret == cpu->kvm_msr_buf->nmsrs);
2172 * MTRR masks: Each mask consists of 5 parts
2173 * a 10..0: must be zero
2174 * b 11 : valid bit
2175 * c n-1.12: actual mask bits
2176 * d 51..n: reserved must be zero
2177 * e 63.52: reserved must be zero
2179 * 'n' is the number of physical bits supported by the CPU and is
2180 * apparently always <= 52. We know our 'n' but don't know what
2181 * the destinations 'n' is; it might be smaller, in which case
2182 * it masks (c) on loading. It might be larger, in which case
2183 * we fill 'd' so that d..c is consistent irrespetive of the 'n'
2184 * we're migrating to.
2187 if (cpu->fill_mtrr_mask) {
2188 QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
2189 assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
2190 mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
2191 } else {
2192 mtrr_top_bits = 0;
2195 for (i = 0; i < ret; i++) {
2196 uint32_t index = msrs[i].index;
2197 switch (index) {
2198 case MSR_IA32_SYSENTER_CS:
2199 env->sysenter_cs = msrs[i].data;
2200 break;
2201 case MSR_IA32_SYSENTER_ESP:
2202 env->sysenter_esp = msrs[i].data;
2203 break;
2204 case MSR_IA32_SYSENTER_EIP:
2205 env->sysenter_eip = msrs[i].data;
2206 break;
2207 case MSR_PAT:
2208 env->pat = msrs[i].data;
2209 break;
2210 case MSR_STAR:
2211 env->star = msrs[i].data;
2212 break;
2213 #ifdef TARGET_X86_64
2214 case MSR_CSTAR:
2215 env->cstar = msrs[i].data;
2216 break;
2217 case MSR_KERNELGSBASE:
2218 env->kernelgsbase = msrs[i].data;
2219 break;
2220 case MSR_FMASK:
2221 env->fmask = msrs[i].data;
2222 break;
2223 case MSR_LSTAR:
2224 env->lstar = msrs[i].data;
2225 break;
2226 #endif
2227 case MSR_IA32_TSC:
2228 env->tsc = msrs[i].data;
2229 break;
2230 case MSR_TSC_AUX:
2231 env->tsc_aux = msrs[i].data;
2232 break;
2233 case MSR_TSC_ADJUST:
2234 env->tsc_adjust = msrs[i].data;
2235 break;
2236 case MSR_IA32_TSCDEADLINE:
2237 env->tsc_deadline = msrs[i].data;
2238 break;
2239 case MSR_VM_HSAVE_PA:
2240 env->vm_hsave = msrs[i].data;
2241 break;
2242 case MSR_KVM_SYSTEM_TIME:
2243 env->system_time_msr = msrs[i].data;
2244 break;
2245 case MSR_KVM_WALL_CLOCK:
2246 env->wall_clock_msr = msrs[i].data;
2247 break;
2248 case MSR_MCG_STATUS:
2249 env->mcg_status = msrs[i].data;
2250 break;
2251 case MSR_MCG_CTL:
2252 env->mcg_ctl = msrs[i].data;
2253 break;
2254 case MSR_MCG_EXT_CTL:
2255 env->mcg_ext_ctl = msrs[i].data;
2256 break;
2257 case MSR_IA32_MISC_ENABLE:
2258 env->msr_ia32_misc_enable = msrs[i].data;
2259 break;
2260 case MSR_IA32_SMBASE:
2261 env->smbase = msrs[i].data;
2262 break;
2263 case MSR_IA32_FEATURE_CONTROL:
2264 env->msr_ia32_feature_control = msrs[i].data;
2265 break;
2266 case MSR_IA32_BNDCFGS:
2267 env->msr_bndcfgs = msrs[i].data;
2268 break;
2269 case MSR_IA32_XSS:
2270 env->xss = msrs[i].data;
2271 break;
2272 default:
2273 if (msrs[i].index >= MSR_MC0_CTL &&
2274 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
2275 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
2277 break;
2278 case MSR_KVM_ASYNC_PF_EN:
2279 env->async_pf_en_msr = msrs[i].data;
2280 break;
2281 case MSR_KVM_PV_EOI_EN:
2282 env->pv_eoi_en_msr = msrs[i].data;
2283 break;
2284 case MSR_KVM_STEAL_TIME:
2285 env->steal_time_msr = msrs[i].data;
2286 break;
2287 case MSR_CORE_PERF_FIXED_CTR_CTRL:
2288 env->msr_fixed_ctr_ctrl = msrs[i].data;
2289 break;
2290 case MSR_CORE_PERF_GLOBAL_CTRL:
2291 env->msr_global_ctrl = msrs[i].data;
2292 break;
2293 case MSR_CORE_PERF_GLOBAL_STATUS:
2294 env->msr_global_status = msrs[i].data;
2295 break;
2296 case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
2297 env->msr_global_ovf_ctrl = msrs[i].data;
2298 break;
2299 case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
2300 env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
2301 break;
2302 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
2303 env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
2304 break;
2305 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
2306 env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
2307 break;
2308 case HV_X64_MSR_HYPERCALL:
2309 env->msr_hv_hypercall = msrs[i].data;
2310 break;
2311 case HV_X64_MSR_GUEST_OS_ID:
2312 env->msr_hv_guest_os_id = msrs[i].data;
2313 break;
2314 case HV_X64_MSR_APIC_ASSIST_PAGE:
2315 env->msr_hv_vapic = msrs[i].data;
2316 break;
2317 case HV_X64_MSR_REFERENCE_TSC:
2318 env->msr_hv_tsc = msrs[i].data;
2319 break;
2320 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2321 env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
2322 break;
2323 case HV_X64_MSR_VP_RUNTIME:
2324 env->msr_hv_runtime = msrs[i].data;
2325 break;
2326 case HV_X64_MSR_SCONTROL:
2327 env->msr_hv_synic_control = msrs[i].data;
2328 break;
2329 case HV_X64_MSR_SVERSION:
2330 env->msr_hv_synic_version = msrs[i].data;
2331 break;
2332 case HV_X64_MSR_SIEFP:
2333 env->msr_hv_synic_evt_page = msrs[i].data;
2334 break;
2335 case HV_X64_MSR_SIMP:
2336 env->msr_hv_synic_msg_page = msrs[i].data;
2337 break;
2338 case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
2339 env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
2340 break;
2341 case HV_X64_MSR_STIMER0_CONFIG:
2342 case HV_X64_MSR_STIMER1_CONFIG:
2343 case HV_X64_MSR_STIMER2_CONFIG:
2344 case HV_X64_MSR_STIMER3_CONFIG:
2345 env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
2346 msrs[i].data;
2347 break;
2348 case HV_X64_MSR_STIMER0_COUNT:
2349 case HV_X64_MSR_STIMER1_COUNT:
2350 case HV_X64_MSR_STIMER2_COUNT:
2351 case HV_X64_MSR_STIMER3_COUNT:
2352 env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
2353 msrs[i].data;
2354 break;
2355 case MSR_MTRRdefType:
2356 env->mtrr_deftype = msrs[i].data;
2357 break;
2358 case MSR_MTRRfix64K_00000:
2359 env->mtrr_fixed[0] = msrs[i].data;
2360 break;
2361 case MSR_MTRRfix16K_80000:
2362 env->mtrr_fixed[1] = msrs[i].data;
2363 break;
2364 case MSR_MTRRfix16K_A0000:
2365 env->mtrr_fixed[2] = msrs[i].data;
2366 break;
2367 case MSR_MTRRfix4K_C0000:
2368 env->mtrr_fixed[3] = msrs[i].data;
2369 break;
2370 case MSR_MTRRfix4K_C8000:
2371 env->mtrr_fixed[4] = msrs[i].data;
2372 break;
2373 case MSR_MTRRfix4K_D0000:
2374 env->mtrr_fixed[5] = msrs[i].data;
2375 break;
2376 case MSR_MTRRfix4K_D8000:
2377 env->mtrr_fixed[6] = msrs[i].data;
2378 break;
2379 case MSR_MTRRfix4K_E0000:
2380 env->mtrr_fixed[7] = msrs[i].data;
2381 break;
2382 case MSR_MTRRfix4K_E8000:
2383 env->mtrr_fixed[8] = msrs[i].data;
2384 break;
2385 case MSR_MTRRfix4K_F0000:
2386 env->mtrr_fixed[9] = msrs[i].data;
2387 break;
2388 case MSR_MTRRfix4K_F8000:
2389 env->mtrr_fixed[10] = msrs[i].data;
2390 break;
2391 case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
2392 if (index & 1) {
2393 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
2394 mtrr_top_bits;
2395 } else {
2396 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
2398 break;
2402 return 0;
2405 static int kvm_put_mp_state(X86CPU *cpu)
2407 struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
2409 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
2412 static int kvm_get_mp_state(X86CPU *cpu)
2414 CPUState *cs = CPU(cpu);
2415 CPUX86State *env = &cpu->env;
2416 struct kvm_mp_state mp_state;
2417 int ret;
2419 ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
2420 if (ret < 0) {
2421 return ret;
2423 env->mp_state = mp_state.mp_state;
2424 if (kvm_irqchip_in_kernel()) {
2425 cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
2427 return 0;
2430 static int kvm_get_apic(X86CPU *cpu)
2432 DeviceState *apic = cpu->apic_state;
2433 struct kvm_lapic_state kapic;
2434 int ret;
2436 if (apic && kvm_irqchip_in_kernel()) {
2437 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
2438 if (ret < 0) {
2439 return ret;
2442 kvm_get_apic_state(apic, &kapic);
2444 return 0;
2447 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
2449 CPUState *cs = CPU(cpu);
2450 CPUX86State *env = &cpu->env;
2451 struct kvm_vcpu_events events = {};
2453 if (!kvm_has_vcpu_events()) {
2454 return 0;
2457 events.exception.injected = (env->exception_injected >= 0);
2458 events.exception.nr = env->exception_injected;
2459 events.exception.has_error_code = env->has_error_code;
2460 events.exception.error_code = env->error_code;
2461 events.exception.pad = 0;
2463 events.interrupt.injected = (env->interrupt_injected >= 0);
2464 events.interrupt.nr = env->interrupt_injected;
2465 events.interrupt.soft = env->soft_interrupt;
2467 events.nmi.injected = env->nmi_injected;
2468 events.nmi.pending = env->nmi_pending;
2469 events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
2470 events.nmi.pad = 0;
2472 events.sipi_vector = env->sipi_vector;
2473 events.flags = 0;
2475 if (has_msr_smbase) {
2476 events.smi.smm = !!(env->hflags & HF_SMM_MASK);
2477 events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
2478 if (kvm_irqchip_in_kernel()) {
2479 /* As soon as these are moved to the kernel, remove them
2480 * from cs->interrupt_request.
2482 events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
2483 events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
2484 cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
2485 } else {
2486 /* Keep these in cs->interrupt_request. */
2487 events.smi.pending = 0;
2488 events.smi.latched_init = 0;
2490 events.flags |= KVM_VCPUEVENT_VALID_SMM;
2493 if (level >= KVM_PUT_RESET_STATE) {
2494 events.flags |=
2495 KVM_VCPUEVENT_VALID_NMI_PENDING | KVM_VCPUEVENT_VALID_SIPI_VECTOR;
2498 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
2501 static int kvm_get_vcpu_events(X86CPU *cpu)
2503 CPUX86State *env = &cpu->env;
2504 struct kvm_vcpu_events events;
2505 int ret;
2507 if (!kvm_has_vcpu_events()) {
2508 return 0;
2511 memset(&events, 0, sizeof(events));
2512 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
2513 if (ret < 0) {
2514 return ret;
2516 env->exception_injected =
2517 events.exception.injected ? events.exception.nr : -1;
2518 env->has_error_code = events.exception.has_error_code;
2519 env->error_code = events.exception.error_code;
2521 env->interrupt_injected =
2522 events.interrupt.injected ? events.interrupt.nr : -1;
2523 env->soft_interrupt = events.interrupt.soft;
2525 env->nmi_injected = events.nmi.injected;
2526 env->nmi_pending = events.nmi.pending;
2527 if (events.nmi.masked) {
2528 env->hflags2 |= HF2_NMI_MASK;
2529 } else {
2530 env->hflags2 &= ~HF2_NMI_MASK;
2533 if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
2534 if (events.smi.smm) {
2535 env->hflags |= HF_SMM_MASK;
2536 } else {
2537 env->hflags &= ~HF_SMM_MASK;
2539 if (events.smi.pending) {
2540 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2541 } else {
2542 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2544 if (events.smi.smm_inside_nmi) {
2545 env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
2546 } else {
2547 env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
2549 if (events.smi.latched_init) {
2550 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2551 } else {
2552 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2556 env->sipi_vector = events.sipi_vector;
2558 return 0;
2561 static int kvm_guest_debug_workarounds(X86CPU *cpu)
2563 CPUState *cs = CPU(cpu);
2564 CPUX86State *env = &cpu->env;
2565 int ret = 0;
2566 unsigned long reinject_trap = 0;
2568 if (!kvm_has_vcpu_events()) {
2569 if (env->exception_injected == 1) {
2570 reinject_trap = KVM_GUESTDBG_INJECT_DB;
2571 } else if (env->exception_injected == 3) {
2572 reinject_trap = KVM_GUESTDBG_INJECT_BP;
2574 env->exception_injected = -1;
2578 * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
2579 * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
2580 * by updating the debug state once again if single-stepping is on.
2581 * Another reason to call kvm_update_guest_debug here is a pending debug
2582 * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
2583 * reinject them via SET_GUEST_DEBUG.
2585 if (reinject_trap ||
2586 (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
2587 ret = kvm_update_guest_debug(cs, reinject_trap);
2589 return ret;
2592 static int kvm_put_debugregs(X86CPU *cpu)
2594 CPUX86State *env = &cpu->env;
2595 struct kvm_debugregs dbgregs;
2596 int i;
2598 if (!kvm_has_debugregs()) {
2599 return 0;
2602 for (i = 0; i < 4; i++) {
2603 dbgregs.db[i] = env->dr[i];
2605 dbgregs.dr6 = env->dr[6];
2606 dbgregs.dr7 = env->dr[7];
2607 dbgregs.flags = 0;
2609 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
2612 static int kvm_get_debugregs(X86CPU *cpu)
2614 CPUX86State *env = &cpu->env;
2615 struct kvm_debugregs dbgregs;
2616 int i, ret;
2618 if (!kvm_has_debugregs()) {
2619 return 0;
2622 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
2623 if (ret < 0) {
2624 return ret;
2626 for (i = 0; i < 4; i++) {
2627 env->dr[i] = dbgregs.db[i];
2629 env->dr[4] = env->dr[6] = dbgregs.dr6;
2630 env->dr[5] = env->dr[7] = dbgregs.dr7;
2632 return 0;
2635 int kvm_arch_put_registers(CPUState *cpu, int level)
2637 X86CPU *x86_cpu = X86_CPU(cpu);
2638 int ret;
2640 assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
2642 if (level >= KVM_PUT_RESET_STATE) {
2643 ret = kvm_put_msr_feature_control(x86_cpu);
2644 if (ret < 0) {
2645 return ret;
2649 if (level == KVM_PUT_FULL_STATE) {
2650 /* We don't check for kvm_arch_set_tsc_khz() errors here,
2651 * because TSC frequency mismatch shouldn't abort migration,
2652 * unless the user explicitly asked for a more strict TSC
2653 * setting (e.g. using an explicit "tsc-freq" option).
2655 kvm_arch_set_tsc_khz(cpu);
2658 ret = kvm_getput_regs(x86_cpu, 1);
2659 if (ret < 0) {
2660 return ret;
2662 ret = kvm_put_xsave(x86_cpu);
2663 if (ret < 0) {
2664 return ret;
2666 ret = kvm_put_xcrs(x86_cpu);
2667 if (ret < 0) {
2668 return ret;
2670 ret = kvm_put_sregs(x86_cpu);
2671 if (ret < 0) {
2672 return ret;
2674 /* must be before kvm_put_msrs */
2675 ret = kvm_inject_mce_oldstyle(x86_cpu);
2676 if (ret < 0) {
2677 return ret;
2679 ret = kvm_put_msrs(x86_cpu, level);
2680 if (ret < 0) {
2681 return ret;
2683 if (level >= KVM_PUT_RESET_STATE) {
2684 ret = kvm_put_mp_state(x86_cpu);
2685 if (ret < 0) {
2686 return ret;
2690 ret = kvm_put_tscdeadline_msr(x86_cpu);
2691 if (ret < 0) {
2692 return ret;
2695 ret = kvm_put_vcpu_events(x86_cpu, level);
2696 if (ret < 0) {
2697 return ret;
2699 ret = kvm_put_debugregs(x86_cpu);
2700 if (ret < 0) {
2701 return ret;
2703 /* must be last */
2704 ret = kvm_guest_debug_workarounds(x86_cpu);
2705 if (ret < 0) {
2706 return ret;
2708 return 0;
2711 int kvm_arch_get_registers(CPUState *cs)
2713 X86CPU *cpu = X86_CPU(cs);
2714 int ret;
2716 assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
2718 ret = kvm_getput_regs(cpu, 0);
2719 if (ret < 0) {
2720 goto out;
2722 ret = kvm_get_xsave(cpu);
2723 if (ret < 0) {
2724 goto out;
2726 ret = kvm_get_xcrs(cpu);
2727 if (ret < 0) {
2728 goto out;
2730 ret = kvm_get_sregs(cpu);
2731 if (ret < 0) {
2732 goto out;
2734 ret = kvm_get_msrs(cpu);
2735 if (ret < 0) {
2736 goto out;
2738 ret = kvm_get_mp_state(cpu);
2739 if (ret < 0) {
2740 goto out;
2742 ret = kvm_get_apic(cpu);
2743 if (ret < 0) {
2744 goto out;
2746 ret = kvm_get_vcpu_events(cpu);
2747 if (ret < 0) {
2748 goto out;
2750 ret = kvm_get_debugregs(cpu);
2751 if (ret < 0) {
2752 goto out;
2754 ret = 0;
2755 out:
2756 cpu_sync_bndcs_hflags(&cpu->env);
2757 return ret;
2760 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
2762 X86CPU *x86_cpu = X86_CPU(cpu);
2763 CPUX86State *env = &x86_cpu->env;
2764 int ret;
2766 /* Inject NMI */
2767 if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
2768 if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
2769 qemu_mutex_lock_iothread();
2770 cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
2771 qemu_mutex_unlock_iothread();
2772 DPRINTF("injected NMI\n");
2773 ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
2774 if (ret < 0) {
2775 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
2776 strerror(-ret));
2779 if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
2780 qemu_mutex_lock_iothread();
2781 cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
2782 qemu_mutex_unlock_iothread();
2783 DPRINTF("injected SMI\n");
2784 ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
2785 if (ret < 0) {
2786 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
2787 strerror(-ret));
2792 if (!kvm_pic_in_kernel()) {
2793 qemu_mutex_lock_iothread();
2796 /* Force the VCPU out of its inner loop to process any INIT requests
2797 * or (for userspace APIC, but it is cheap to combine the checks here)
2798 * pending TPR access reports.
2800 if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
2801 if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
2802 !(env->hflags & HF_SMM_MASK)) {
2803 cpu->exit_request = 1;
2805 if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
2806 cpu->exit_request = 1;
2810 if (!kvm_pic_in_kernel()) {
2811 /* Try to inject an interrupt if the guest can accept it */
2812 if (run->ready_for_interrupt_injection &&
2813 (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
2814 (env->eflags & IF_MASK)) {
2815 int irq;
2817 cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
2818 irq = cpu_get_pic_interrupt(env);
2819 if (irq >= 0) {
2820 struct kvm_interrupt intr;
2822 intr.irq = irq;
2823 DPRINTF("injected interrupt %d\n", irq);
2824 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
2825 if (ret < 0) {
2826 fprintf(stderr,
2827 "KVM: injection failed, interrupt lost (%s)\n",
2828 strerror(-ret));
2833 /* If we have an interrupt but the guest is not ready to receive an
2834 * interrupt, request an interrupt window exit. This will
2835 * cause a return to userspace as soon as the guest is ready to
2836 * receive interrupts. */
2837 if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
2838 run->request_interrupt_window = 1;
2839 } else {
2840 run->request_interrupt_window = 0;
2843 DPRINTF("setting tpr\n");
2844 run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
2846 qemu_mutex_unlock_iothread();
2850 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
2852 X86CPU *x86_cpu = X86_CPU(cpu);
2853 CPUX86State *env = &x86_cpu->env;
2855 if (run->flags & KVM_RUN_X86_SMM) {
2856 env->hflags |= HF_SMM_MASK;
2857 } else {
2858 env->hflags &= HF_SMM_MASK;
2860 if (run->if_flag) {
2861 env->eflags |= IF_MASK;
2862 } else {
2863 env->eflags &= ~IF_MASK;
2866 /* We need to protect the apic state against concurrent accesses from
2867 * different threads in case the userspace irqchip is used. */
2868 if (!kvm_irqchip_in_kernel()) {
2869 qemu_mutex_lock_iothread();
2871 cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
2872 cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
2873 if (!kvm_irqchip_in_kernel()) {
2874 qemu_mutex_unlock_iothread();
2876 return cpu_get_mem_attrs(env);
2879 int kvm_arch_process_async_events(CPUState *cs)
2881 X86CPU *cpu = X86_CPU(cs);
2882 CPUX86State *env = &cpu->env;
2884 if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
2885 /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
2886 assert(env->mcg_cap);
2888 cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
2890 kvm_cpu_synchronize_state(cs);
2892 if (env->exception_injected == EXCP08_DBLE) {
2893 /* this means triple fault */
2894 qemu_system_reset_request();
2895 cs->exit_request = 1;
2896 return 0;
2898 env->exception_injected = EXCP12_MCHK;
2899 env->has_error_code = 0;
2901 cs->halted = 0;
2902 if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
2903 env->mp_state = KVM_MP_STATE_RUNNABLE;
2907 if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
2908 !(env->hflags & HF_SMM_MASK)) {
2909 kvm_cpu_synchronize_state(cs);
2910 do_cpu_init(cpu);
2913 if (kvm_irqchip_in_kernel()) {
2914 return 0;
2917 if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
2918 cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
2919 apic_poll_irq(cpu->apic_state);
2921 if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2922 (env->eflags & IF_MASK)) ||
2923 (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
2924 cs->halted = 0;
2926 if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
2927 kvm_cpu_synchronize_state(cs);
2928 do_cpu_sipi(cpu);
2930 if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
2931 cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
2932 kvm_cpu_synchronize_state(cs);
2933 apic_handle_tpr_access_report(cpu->apic_state, env->eip,
2934 env->tpr_access_type);
2937 return cs->halted;
2940 static int kvm_handle_halt(X86CPU *cpu)
2942 CPUState *cs = CPU(cpu);
2943 CPUX86State *env = &cpu->env;
2945 if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2946 (env->eflags & IF_MASK)) &&
2947 !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
2948 cs->halted = 1;
2949 return EXCP_HLT;
2952 return 0;
2955 static int kvm_handle_tpr_access(X86CPU *cpu)
2957 CPUState *cs = CPU(cpu);
2958 struct kvm_run *run = cs->kvm_run;
2960 apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
2961 run->tpr_access.is_write ? TPR_ACCESS_WRITE
2962 : TPR_ACCESS_READ);
2963 return 1;
2966 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2968 static const uint8_t int3 = 0xcc;
2970 if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
2971 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
2972 return -EINVAL;
2974 return 0;
2977 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2979 uint8_t int3;
2981 if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
2982 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
2983 return -EINVAL;
2985 return 0;
2988 static struct {
2989 target_ulong addr;
2990 int len;
2991 int type;
2992 } hw_breakpoint[4];
2994 static int nb_hw_breakpoint;
2996 static int find_hw_breakpoint(target_ulong addr, int len, int type)
2998 int n;
3000 for (n = 0; n < nb_hw_breakpoint; n++) {
3001 if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
3002 (hw_breakpoint[n].len == len || len == -1)) {
3003 return n;
3006 return -1;
3009 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
3010 target_ulong len, int type)
3012 switch (type) {
3013 case GDB_BREAKPOINT_HW:
3014 len = 1;
3015 break;
3016 case GDB_WATCHPOINT_WRITE:
3017 case GDB_WATCHPOINT_ACCESS:
3018 switch (len) {
3019 case 1:
3020 break;
3021 case 2:
3022 case 4:
3023 case 8:
3024 if (addr & (len - 1)) {
3025 return -EINVAL;
3027 break;
3028 default:
3029 return -EINVAL;
3031 break;
3032 default:
3033 return -ENOSYS;
3036 if (nb_hw_breakpoint == 4) {
3037 return -ENOBUFS;
3039 if (find_hw_breakpoint(addr, len, type) >= 0) {
3040 return -EEXIST;
3042 hw_breakpoint[nb_hw_breakpoint].addr = addr;
3043 hw_breakpoint[nb_hw_breakpoint].len = len;
3044 hw_breakpoint[nb_hw_breakpoint].type = type;
3045 nb_hw_breakpoint++;
3047 return 0;
3050 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
3051 target_ulong len, int type)
3053 int n;
3055 n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
3056 if (n < 0) {
3057 return -ENOENT;
3059 nb_hw_breakpoint--;
3060 hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
3062 return 0;
3065 void kvm_arch_remove_all_hw_breakpoints(void)
3067 nb_hw_breakpoint = 0;
3070 static CPUWatchpoint hw_watchpoint;
3072 static int kvm_handle_debug(X86CPU *cpu,
3073 struct kvm_debug_exit_arch *arch_info)
3075 CPUState *cs = CPU(cpu);
3076 CPUX86State *env = &cpu->env;
3077 int ret = 0;
3078 int n;
3080 if (arch_info->exception == 1) {
3081 if (arch_info->dr6 & (1 << 14)) {
3082 if (cs->singlestep_enabled) {
3083 ret = EXCP_DEBUG;
3085 } else {
3086 for (n = 0; n < 4; n++) {
3087 if (arch_info->dr6 & (1 << n)) {
3088 switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
3089 case 0x0:
3090 ret = EXCP_DEBUG;
3091 break;
3092 case 0x1:
3093 ret = EXCP_DEBUG;
3094 cs->watchpoint_hit = &hw_watchpoint;
3095 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
3096 hw_watchpoint.flags = BP_MEM_WRITE;
3097 break;
3098 case 0x3:
3099 ret = EXCP_DEBUG;
3100 cs->watchpoint_hit = &hw_watchpoint;
3101 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
3102 hw_watchpoint.flags = BP_MEM_ACCESS;
3103 break;
3108 } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
3109 ret = EXCP_DEBUG;
3111 if (ret == 0) {
3112 cpu_synchronize_state(cs);
3113 assert(env->exception_injected == -1);
3115 /* pass to guest */
3116 env->exception_injected = arch_info->exception;
3117 env->has_error_code = 0;
3120 return ret;
3123 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
3125 const uint8_t type_code[] = {
3126 [GDB_BREAKPOINT_HW] = 0x0,
3127 [GDB_WATCHPOINT_WRITE] = 0x1,
3128 [GDB_WATCHPOINT_ACCESS] = 0x3
3130 const uint8_t len_code[] = {
3131 [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
3133 int n;
3135 if (kvm_sw_breakpoints_active(cpu)) {
3136 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
3138 if (nb_hw_breakpoint > 0) {
3139 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
3140 dbg->arch.debugreg[7] = 0x0600;
3141 for (n = 0; n < nb_hw_breakpoint; n++) {
3142 dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
3143 dbg->arch.debugreg[7] |= (2 << (n * 2)) |
3144 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
3145 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
3150 static bool host_supports_vmx(void)
3152 uint32_t ecx, unused;
3154 host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
3155 return ecx & CPUID_EXT_VMX;
3158 #define VMX_INVALID_GUEST_STATE 0x80000021
3160 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
3162 X86CPU *cpu = X86_CPU(cs);
3163 uint64_t code;
3164 int ret;
3166 switch (run->exit_reason) {
3167 case KVM_EXIT_HLT:
3168 DPRINTF("handle_hlt\n");
3169 qemu_mutex_lock_iothread();
3170 ret = kvm_handle_halt(cpu);
3171 qemu_mutex_unlock_iothread();
3172 break;
3173 case KVM_EXIT_SET_TPR:
3174 ret = 0;
3175 break;
3176 case KVM_EXIT_TPR_ACCESS:
3177 qemu_mutex_lock_iothread();
3178 ret = kvm_handle_tpr_access(cpu);
3179 qemu_mutex_unlock_iothread();
3180 break;
3181 case KVM_EXIT_FAIL_ENTRY:
3182 code = run->fail_entry.hardware_entry_failure_reason;
3183 fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
3184 code);
3185 if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
3186 fprintf(stderr,
3187 "\nIf you're running a guest on an Intel machine without "
3188 "unrestricted mode\n"
3189 "support, the failure can be most likely due to the guest "
3190 "entering an invalid\n"
3191 "state for Intel VT. For example, the guest maybe running "
3192 "in big real mode\n"
3193 "which is not supported on less recent Intel processors."
3194 "\n\n");
3196 ret = -1;
3197 break;
3198 case KVM_EXIT_EXCEPTION:
3199 fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
3200 run->ex.exception, run->ex.error_code);
3201 ret = -1;
3202 break;
3203 case KVM_EXIT_DEBUG:
3204 DPRINTF("kvm_exit_debug\n");
3205 qemu_mutex_lock_iothread();
3206 ret = kvm_handle_debug(cpu, &run->debug.arch);
3207 qemu_mutex_unlock_iothread();
3208 break;
3209 case KVM_EXIT_HYPERV:
3210 ret = kvm_hv_handle_exit(cpu, &run->hyperv);
3211 break;
3212 case KVM_EXIT_IOAPIC_EOI:
3213 ioapic_eoi_broadcast(run->eoi.vector);
3214 ret = 0;
3215 break;
3216 default:
3217 fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
3218 ret = -1;
3219 break;
3222 return ret;
3225 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
3227 X86CPU *cpu = X86_CPU(cs);
3228 CPUX86State *env = &cpu->env;
3230 kvm_cpu_synchronize_state(cs);
3231 return !(env->cr[0] & CR0_PE_MASK) ||
3232 ((env->segs[R_CS].selector & 3) != 3);
3235 void kvm_arch_init_irq_routing(KVMState *s)
3237 if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
3238 /* If kernel can't do irq routing, interrupt source
3239 * override 0->2 cannot be set up as required by HPET.
3240 * So we have to disable it.
3242 no_hpet = 1;
3244 /* We know at this point that we're using the in-kernel
3245 * irqchip, so we can use irqfds, and on x86 we know
3246 * we can use msi via irqfd and GSI routing.
3248 kvm_msi_via_irqfd_allowed = true;
3249 kvm_gsi_routing_allowed = true;
3251 if (kvm_irqchip_is_split()) {
3252 int i;
3254 /* If the ioapic is in QEMU and the lapics are in KVM, reserve
3255 MSI routes for signaling interrupts to the local apics. */
3256 for (i = 0; i < IOAPIC_NUM_PINS; i++) {
3257 if (kvm_irqchip_add_msi_route(s, 0, NULL) < 0) {
3258 error_report("Could not enable split IRQ mode.");
3259 exit(1);
3265 int kvm_arch_irqchip_create(MachineState *ms, KVMState *s)
3267 int ret;
3268 if (machine_kernel_irqchip_split(ms)) {
3269 ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
3270 if (ret) {
3271 error_report("Could not enable split irqchip mode: %s",
3272 strerror(-ret));
3273 exit(1);
3274 } else {
3275 DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
3276 kvm_split_irqchip = true;
3277 return 1;
3279 } else {
3280 return 0;
3284 /* Classic KVM device assignment interface. Will remain x86 only. */
3285 int kvm_device_pci_assign(KVMState *s, PCIHostDeviceAddress *dev_addr,
3286 uint32_t flags, uint32_t *dev_id)
3288 struct kvm_assigned_pci_dev dev_data = {
3289 .segnr = dev_addr->domain,
3290 .busnr = dev_addr->bus,
3291 .devfn = PCI_DEVFN(dev_addr->slot, dev_addr->function),
3292 .flags = flags,
3294 int ret;
3296 dev_data.assigned_dev_id =
3297 (dev_addr->domain << 16) | (dev_addr->bus << 8) | dev_data.devfn;
3299 ret = kvm_vm_ioctl(s, KVM_ASSIGN_PCI_DEVICE, &dev_data);
3300 if (ret < 0) {
3301 return ret;
3304 *dev_id = dev_data.assigned_dev_id;
3306 return 0;
3309 int kvm_device_pci_deassign(KVMState *s, uint32_t dev_id)
3311 struct kvm_assigned_pci_dev dev_data = {
3312 .assigned_dev_id = dev_id,
3315 return kvm_vm_ioctl(s, KVM_DEASSIGN_PCI_DEVICE, &dev_data);
3318 static int kvm_assign_irq_internal(KVMState *s, uint32_t dev_id,
3319 uint32_t irq_type, uint32_t guest_irq)
3321 struct kvm_assigned_irq assigned_irq = {
3322 .assigned_dev_id = dev_id,
3323 .guest_irq = guest_irq,
3324 .flags = irq_type,
3327 if (kvm_check_extension(s, KVM_CAP_ASSIGN_DEV_IRQ)) {
3328 return kvm_vm_ioctl(s, KVM_ASSIGN_DEV_IRQ, &assigned_irq);
3329 } else {
3330 return kvm_vm_ioctl(s, KVM_ASSIGN_IRQ, &assigned_irq);
3334 int kvm_device_intx_assign(KVMState *s, uint32_t dev_id, bool use_host_msi,
3335 uint32_t guest_irq)
3337 uint32_t irq_type = KVM_DEV_IRQ_GUEST_INTX |
3338 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX);
3340 return kvm_assign_irq_internal(s, dev_id, irq_type, guest_irq);
3343 int kvm_device_intx_set_mask(KVMState *s, uint32_t dev_id, bool masked)
3345 struct kvm_assigned_pci_dev dev_data = {
3346 .assigned_dev_id = dev_id,
3347 .flags = masked ? KVM_DEV_ASSIGN_MASK_INTX : 0,
3350 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_INTX_MASK, &dev_data);
3353 static int kvm_deassign_irq_internal(KVMState *s, uint32_t dev_id,
3354 uint32_t type)
3356 struct kvm_assigned_irq assigned_irq = {
3357 .assigned_dev_id = dev_id,
3358 .flags = type,
3361 return kvm_vm_ioctl(s, KVM_DEASSIGN_DEV_IRQ, &assigned_irq);
3364 int kvm_device_intx_deassign(KVMState *s, uint32_t dev_id, bool use_host_msi)
3366 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_INTX |
3367 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX));
3370 int kvm_device_msi_assign(KVMState *s, uint32_t dev_id, int virq)
3372 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSI |
3373 KVM_DEV_IRQ_GUEST_MSI, virq);
3376 int kvm_device_msi_deassign(KVMState *s, uint32_t dev_id)
3378 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSI |
3379 KVM_DEV_IRQ_HOST_MSI);
3382 bool kvm_device_msix_supported(KVMState *s)
3384 /* The kernel lacks a corresponding KVM_CAP, so we probe by calling
3385 * KVM_ASSIGN_SET_MSIX_NR with an invalid parameter. */
3386 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, NULL) == -EFAULT;
3389 int kvm_device_msix_init_vectors(KVMState *s, uint32_t dev_id,
3390 uint32_t nr_vectors)
3392 struct kvm_assigned_msix_nr msix_nr = {
3393 .assigned_dev_id = dev_id,
3394 .entry_nr = nr_vectors,
3397 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, &msix_nr);
3400 int kvm_device_msix_set_vector(KVMState *s, uint32_t dev_id, uint32_t vector,
3401 int virq)
3403 struct kvm_assigned_msix_entry msix_entry = {
3404 .assigned_dev_id = dev_id,
3405 .gsi = virq,
3406 .entry = vector,
3409 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_ENTRY, &msix_entry);
3412 int kvm_device_msix_assign(KVMState *s, uint32_t dev_id)
3414 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSIX |
3415 KVM_DEV_IRQ_GUEST_MSIX, 0);
3418 int kvm_device_msix_deassign(KVMState *s, uint32_t dev_id)
3420 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSIX |
3421 KVM_DEV_IRQ_HOST_MSIX);
3424 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
3425 uint64_t address, uint32_t data, PCIDevice *dev)
3427 X86IOMMUState *iommu = x86_iommu_get_default();
3429 if (iommu) {
3430 int ret;
3431 MSIMessage src, dst;
3432 X86IOMMUClass *class = X86_IOMMU_GET_CLASS(iommu);
3434 src.address = route->u.msi.address_hi;
3435 src.address <<= VTD_MSI_ADDR_HI_SHIFT;
3436 src.address |= route->u.msi.address_lo;
3437 src.data = route->u.msi.data;
3439 ret = class->int_remap(iommu, &src, &dst, dev ? \
3440 pci_requester_id(dev) : \
3441 X86_IOMMU_SID_INVALID);
3442 if (ret) {
3443 trace_kvm_x86_fixup_msi_error(route->gsi);
3444 return 1;
3447 route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
3448 route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
3449 route->u.msi.data = dst.data;
3452 return 0;
3455 typedef struct MSIRouteEntry MSIRouteEntry;
3457 struct MSIRouteEntry {
3458 PCIDevice *dev; /* Device pointer */
3459 int vector; /* MSI/MSIX vector index */
3460 int virq; /* Virtual IRQ index */
3461 QLIST_ENTRY(MSIRouteEntry) list;
3464 /* List of used GSI routes */
3465 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
3466 QLIST_HEAD_INITIALIZER(msi_route_list);
3468 static void kvm_update_msi_routes_all(void *private, bool global,
3469 uint32_t index, uint32_t mask)
3471 int cnt = 0;
3472 MSIRouteEntry *entry;
3473 MSIMessage msg;
3474 /* TODO: explicit route update */
3475 QLIST_FOREACH(entry, &msi_route_list, list) {
3476 cnt++;
3477 msg = pci_get_msi_message(entry->dev, entry->vector);
3478 kvm_irqchip_update_msi_route(kvm_state, entry->virq,
3479 msg, entry->dev);
3481 kvm_irqchip_commit_routes(kvm_state);
3482 trace_kvm_x86_update_msi_routes(cnt);
3485 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
3486 int vector, PCIDevice *dev)
3488 static bool notify_list_inited = false;
3489 MSIRouteEntry *entry;
3491 if (!dev) {
3492 /* These are (possibly) IOAPIC routes only used for split
3493 * kernel irqchip mode, while what we are housekeeping are
3494 * PCI devices only. */
3495 return 0;
3498 entry = g_new0(MSIRouteEntry, 1);
3499 entry->dev = dev;
3500 entry->vector = vector;
3501 entry->virq = route->gsi;
3502 QLIST_INSERT_HEAD(&msi_route_list, entry, list);
3504 trace_kvm_x86_add_msi_route(route->gsi);
3506 if (!notify_list_inited) {
3507 /* For the first time we do add route, add ourselves into
3508 * IOMMU's IEC notify list if needed. */
3509 X86IOMMUState *iommu = x86_iommu_get_default();
3510 if (iommu) {
3511 x86_iommu_iec_register_notifier(iommu,
3512 kvm_update_msi_routes_all,
3513 NULL);
3515 notify_list_inited = true;
3517 return 0;
3520 int kvm_arch_release_virq_post(int virq)
3522 MSIRouteEntry *entry, *next;
3523 QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
3524 if (entry->virq == virq) {
3525 trace_kvm_x86_remove_msi_route(virq);
3526 QLIST_REMOVE(entry, list);
3527 break;
3530 return 0;
3533 int kvm_arch_msi_data_to_gsi(uint32_t data)
3535 abort();