hw/arm/virt: Set minimum_page_bits to 12
[qemu/ar7.git] / target-i386 / kvm.c
blob0472f45fd092591eacdeab6da78aaa48e1062919
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) \
133 ({ \
134 static typeof(fn) _result; \
135 static bool _memorized; \
137 if (_memorized) { \
138 return _result; \
140 _memorized = true; \
141 _result = fn; \
144 bool kvm_enable_x2apic(void)
146 return MEMORIZE(
147 kvm_x2apic_api_set_flags(KVM_X2APIC_API_USE_32BIT_IDS |
148 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK));
151 static int kvm_get_tsc(CPUState *cs)
153 X86CPU *cpu = X86_CPU(cs);
154 CPUX86State *env = &cpu->env;
155 struct {
156 struct kvm_msrs info;
157 struct kvm_msr_entry entries[1];
158 } msr_data;
159 int ret;
161 if (env->tsc_valid) {
162 return 0;
165 msr_data.info.nmsrs = 1;
166 msr_data.entries[0].index = MSR_IA32_TSC;
167 env->tsc_valid = !runstate_is_running();
169 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
170 if (ret < 0) {
171 return ret;
174 assert(ret == 1);
175 env->tsc = msr_data.entries[0].data;
176 return 0;
179 static inline void do_kvm_synchronize_tsc(CPUState *cpu, void *arg)
181 kvm_get_tsc(cpu);
184 void kvm_synchronize_all_tsc(void)
186 CPUState *cpu;
188 if (kvm_enabled()) {
189 CPU_FOREACH(cpu) {
190 run_on_cpu(cpu, do_kvm_synchronize_tsc, NULL);
195 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
197 struct kvm_cpuid2 *cpuid;
198 int r, size;
200 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
201 cpuid = g_malloc0(size);
202 cpuid->nent = max;
203 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
204 if (r == 0 && cpuid->nent >= max) {
205 r = -E2BIG;
207 if (r < 0) {
208 if (r == -E2BIG) {
209 g_free(cpuid);
210 return NULL;
211 } else {
212 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
213 strerror(-r));
214 exit(1);
217 return cpuid;
220 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
221 * for all entries.
223 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
225 struct kvm_cpuid2 *cpuid;
226 int max = 1;
228 if (cpuid_cache != NULL) {
229 return cpuid_cache;
231 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
232 max *= 2;
234 cpuid_cache = cpuid;
235 return cpuid;
238 static const struct kvm_para_features {
239 int cap;
240 int feature;
241 } para_features[] = {
242 { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
243 { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
244 { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
245 { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
248 static int get_para_features(KVMState *s)
250 int i, features = 0;
252 for (i = 0; i < ARRAY_SIZE(para_features); i++) {
253 if (kvm_check_extension(s, para_features[i].cap)) {
254 features |= (1 << para_features[i].feature);
258 return features;
262 /* Returns the value for a specific register on the cpuid entry
264 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
266 uint32_t ret = 0;
267 switch (reg) {
268 case R_EAX:
269 ret = entry->eax;
270 break;
271 case R_EBX:
272 ret = entry->ebx;
273 break;
274 case R_ECX:
275 ret = entry->ecx;
276 break;
277 case R_EDX:
278 ret = entry->edx;
279 break;
281 return ret;
284 /* Find matching entry for function/index on kvm_cpuid2 struct
286 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
287 uint32_t function,
288 uint32_t index)
290 int i;
291 for (i = 0; i < cpuid->nent; ++i) {
292 if (cpuid->entries[i].function == function &&
293 cpuid->entries[i].index == index) {
294 return &cpuid->entries[i];
297 /* not found: */
298 return NULL;
301 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
302 uint32_t index, int reg)
304 struct kvm_cpuid2 *cpuid;
305 uint32_t ret = 0;
306 uint32_t cpuid_1_edx;
307 bool found = false;
309 cpuid = get_supported_cpuid(s);
311 struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
312 if (entry) {
313 found = true;
314 ret = cpuid_entry_get_reg(entry, reg);
317 /* Fixups for the data returned by KVM, below */
319 if (function == 1 && reg == R_EDX) {
320 /* KVM before 2.6.30 misreports the following features */
321 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
322 } else if (function == 1 && reg == R_ECX) {
323 /* We can set the hypervisor flag, even if KVM does not return it on
324 * GET_SUPPORTED_CPUID
326 ret |= CPUID_EXT_HYPERVISOR;
327 /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
328 * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
329 * and the irqchip is in the kernel.
331 if (kvm_irqchip_in_kernel() &&
332 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
333 ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
336 /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
337 * without the in-kernel irqchip
339 if (!kvm_irqchip_in_kernel()) {
340 ret &= ~CPUID_EXT_X2APIC;
342 } else if (function == 6 && reg == R_EAX) {
343 ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
344 } else if (function == 0x80000001 && reg == R_EDX) {
345 /* On Intel, kvm returns cpuid according to the Intel spec,
346 * so add missing bits according to the AMD spec:
348 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
349 ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
350 } else if (function == KVM_CPUID_FEATURES && reg == R_EAX) {
351 /* kvm_pv_unhalt is reported by GET_SUPPORTED_CPUID, but it can't
352 * be enabled without the in-kernel irqchip
354 if (!kvm_irqchip_in_kernel()) {
355 ret &= ~(1U << KVM_FEATURE_PV_UNHALT);
359 /* fallback for older kernels */
360 if ((function == KVM_CPUID_FEATURES) && !found) {
361 ret = get_para_features(s);
364 return ret;
367 typedef struct HWPoisonPage {
368 ram_addr_t ram_addr;
369 QLIST_ENTRY(HWPoisonPage) list;
370 } HWPoisonPage;
372 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
373 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
375 static void kvm_unpoison_all(void *param)
377 HWPoisonPage *page, *next_page;
379 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
380 QLIST_REMOVE(page, list);
381 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
382 g_free(page);
386 static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
388 HWPoisonPage *page;
390 QLIST_FOREACH(page, &hwpoison_page_list, list) {
391 if (page->ram_addr == ram_addr) {
392 return;
395 page = g_new(HWPoisonPage, 1);
396 page->ram_addr = ram_addr;
397 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
400 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
401 int *max_banks)
403 int r;
405 r = kvm_check_extension(s, KVM_CAP_MCE);
406 if (r > 0) {
407 *max_banks = r;
408 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
410 return -ENOSYS;
413 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
415 CPUState *cs = CPU(cpu);
416 CPUX86State *env = &cpu->env;
417 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
418 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
419 uint64_t mcg_status = MCG_STATUS_MCIP;
420 int flags = 0;
422 if (code == BUS_MCEERR_AR) {
423 status |= MCI_STATUS_AR | 0x134;
424 mcg_status |= MCG_STATUS_EIPV;
425 } else {
426 status |= 0xc0;
427 mcg_status |= MCG_STATUS_RIPV;
430 flags = cpu_x86_support_mca_broadcast(env) ? MCE_INJECT_BROADCAST : 0;
431 /* We need to read back the value of MSR_EXT_MCG_CTL that was set by the
432 * guest kernel back into env->mcg_ext_ctl.
434 cpu_synchronize_state(cs);
435 if (env->mcg_ext_ctl & MCG_EXT_CTL_LMCE_EN) {
436 mcg_status |= MCG_STATUS_LMCE;
437 flags = 0;
440 cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
441 (MCM_ADDR_PHYS << 6) | 0xc, flags);
444 static void hardware_memory_error(void)
446 fprintf(stderr, "Hardware memory error!\n");
447 exit(1);
450 int kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
452 X86CPU *cpu = X86_CPU(c);
453 CPUX86State *env = &cpu->env;
454 ram_addr_t ram_addr;
455 hwaddr paddr;
457 if ((env->mcg_cap & MCG_SER_P) && addr
458 && (code == BUS_MCEERR_AR || code == BUS_MCEERR_AO)) {
459 ram_addr = qemu_ram_addr_from_host(addr);
460 if (ram_addr == RAM_ADDR_INVALID ||
461 !kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
462 fprintf(stderr, "Hardware memory error for memory used by "
463 "QEMU itself instead of guest system!\n");
464 /* Hope we are lucky for AO MCE */
465 if (code == BUS_MCEERR_AO) {
466 return 0;
467 } else {
468 hardware_memory_error();
471 kvm_hwpoison_page_add(ram_addr);
472 kvm_mce_inject(cpu, paddr, code);
473 } else {
474 if (code == BUS_MCEERR_AO) {
475 return 0;
476 } else if (code == BUS_MCEERR_AR) {
477 hardware_memory_error();
478 } else {
479 return 1;
482 return 0;
485 int kvm_arch_on_sigbus(int code, void *addr)
487 X86CPU *cpu = X86_CPU(first_cpu);
489 if ((cpu->env.mcg_cap & MCG_SER_P) && addr && code == BUS_MCEERR_AO) {
490 ram_addr_t ram_addr;
491 hwaddr paddr;
493 /* Hope we are lucky for AO MCE */
494 ram_addr = qemu_ram_addr_from_host(addr);
495 if (ram_addr == RAM_ADDR_INVALID ||
496 !kvm_physical_memory_addr_from_host(first_cpu->kvm_state,
497 addr, &paddr)) {
498 fprintf(stderr, "Hardware memory error for memory used by "
499 "QEMU itself instead of guest system!: %p\n", addr);
500 return 0;
502 kvm_hwpoison_page_add(ram_addr);
503 kvm_mce_inject(X86_CPU(first_cpu), paddr, code);
504 } else {
505 if (code == BUS_MCEERR_AO) {
506 return 0;
507 } else if (code == BUS_MCEERR_AR) {
508 hardware_memory_error();
509 } else {
510 return 1;
513 return 0;
516 static int kvm_inject_mce_oldstyle(X86CPU *cpu)
518 CPUX86State *env = &cpu->env;
520 if (!kvm_has_vcpu_events() && env->exception_injected == EXCP12_MCHK) {
521 unsigned int bank, bank_num = env->mcg_cap & 0xff;
522 struct kvm_x86_mce mce;
524 env->exception_injected = -1;
527 * There must be at least one bank in use if an MCE is pending.
528 * Find it and use its values for the event injection.
530 for (bank = 0; bank < bank_num; bank++) {
531 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
532 break;
535 assert(bank < bank_num);
537 mce.bank = bank;
538 mce.status = env->mce_banks[bank * 4 + 1];
539 mce.mcg_status = env->mcg_status;
540 mce.addr = env->mce_banks[bank * 4 + 2];
541 mce.misc = env->mce_banks[bank * 4 + 3];
543 return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
545 return 0;
548 static void cpu_update_state(void *opaque, int running, RunState state)
550 CPUX86State *env = opaque;
552 if (running) {
553 env->tsc_valid = false;
557 unsigned long kvm_arch_vcpu_id(CPUState *cs)
559 X86CPU *cpu = X86_CPU(cs);
560 return cpu->apic_id;
563 #ifndef KVM_CPUID_SIGNATURE_NEXT
564 #define KVM_CPUID_SIGNATURE_NEXT 0x40000100
565 #endif
567 static bool hyperv_hypercall_available(X86CPU *cpu)
569 return cpu->hyperv_vapic ||
570 (cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY);
573 static bool hyperv_enabled(X86CPU *cpu)
575 CPUState *cs = CPU(cpu);
576 return kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0 &&
577 (hyperv_hypercall_available(cpu) ||
578 cpu->hyperv_time ||
579 cpu->hyperv_relaxed_timing ||
580 cpu->hyperv_crash ||
581 cpu->hyperv_reset ||
582 cpu->hyperv_vpindex ||
583 cpu->hyperv_runtime ||
584 cpu->hyperv_synic ||
585 cpu->hyperv_stimer);
588 static int kvm_arch_set_tsc_khz(CPUState *cs)
590 X86CPU *cpu = X86_CPU(cs);
591 CPUX86State *env = &cpu->env;
592 int r;
594 if (!env->tsc_khz) {
595 return 0;
598 r = kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL) ?
599 kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) :
600 -ENOTSUP;
601 if (r < 0) {
602 /* When KVM_SET_TSC_KHZ fails, it's an error only if the current
603 * TSC frequency doesn't match the one we want.
605 int cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
606 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
607 -ENOTSUP;
608 if (cur_freq <= 0 || cur_freq != env->tsc_khz) {
609 error_report("warning: TSC frequency mismatch between "
610 "VM (%" PRId64 " kHz) and host (%d kHz), "
611 "and TSC scaling unavailable",
612 env->tsc_khz, cur_freq);
613 return r;
617 return 0;
620 static int hyperv_handle_properties(CPUState *cs)
622 X86CPU *cpu = X86_CPU(cs);
623 CPUX86State *env = &cpu->env;
625 if (cpu->hyperv_time &&
626 kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) <= 0) {
627 cpu->hyperv_time = false;
630 if (cpu->hyperv_relaxed_timing) {
631 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_HYPERCALL_AVAILABLE;
633 if (cpu->hyperv_vapic) {
634 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_HYPERCALL_AVAILABLE;
635 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_APIC_ACCESS_AVAILABLE;
637 if (cpu->hyperv_time) {
638 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_HYPERCALL_AVAILABLE;
639 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_TIME_REF_COUNT_AVAILABLE;
640 env->features[FEAT_HYPERV_EAX] |= 0x200;
642 if (cpu->hyperv_crash && has_msr_hv_crash) {
643 env->features[FEAT_HYPERV_EDX] |= HV_X64_GUEST_CRASH_MSR_AVAILABLE;
645 env->features[FEAT_HYPERV_EDX] |= HV_X64_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
646 if (cpu->hyperv_reset && has_msr_hv_reset) {
647 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_RESET_AVAILABLE;
649 if (cpu->hyperv_vpindex && has_msr_hv_vpindex) {
650 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_VP_INDEX_AVAILABLE;
652 if (cpu->hyperv_runtime && has_msr_hv_runtime) {
653 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_VP_RUNTIME_AVAILABLE;
655 if (cpu->hyperv_synic) {
656 int sint;
658 if (!has_msr_hv_synic ||
659 kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_SYNIC, 0)) {
660 fprintf(stderr, "Hyper-V SynIC is not supported by kernel\n");
661 return -ENOSYS;
664 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_SYNIC_AVAILABLE;
665 env->msr_hv_synic_version = HV_SYNIC_VERSION_1;
666 for (sint = 0; sint < ARRAY_SIZE(env->msr_hv_synic_sint); sint++) {
667 env->msr_hv_synic_sint[sint] = HV_SYNIC_SINT_MASKED;
670 if (cpu->hyperv_stimer) {
671 if (!has_msr_hv_stimer) {
672 fprintf(stderr, "Hyper-V timers aren't supported by kernel\n");
673 return -ENOSYS;
675 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_SYNTIMER_AVAILABLE;
677 return 0;
680 static Error *invtsc_mig_blocker;
682 #define KVM_MAX_CPUID_ENTRIES 100
684 int kvm_arch_init_vcpu(CPUState *cs)
686 struct {
687 struct kvm_cpuid2 cpuid;
688 struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
689 } QEMU_PACKED cpuid_data;
690 X86CPU *cpu = X86_CPU(cs);
691 CPUX86State *env = &cpu->env;
692 uint32_t limit, i, j, cpuid_i;
693 uint32_t unused;
694 struct kvm_cpuid_entry2 *c;
695 uint32_t signature[3];
696 int kvm_base = KVM_CPUID_SIGNATURE;
697 int r;
699 memset(&cpuid_data, 0, sizeof(cpuid_data));
701 cpuid_i = 0;
703 /* Paravirtualization CPUIDs */
704 if (hyperv_enabled(cpu)) {
705 c = &cpuid_data.entries[cpuid_i++];
706 c->function = HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
707 if (!cpu->hyperv_vendor_id) {
708 memcpy(signature, "Microsoft Hv", 12);
709 } else {
710 size_t len = strlen(cpu->hyperv_vendor_id);
712 if (len > 12) {
713 error_report("hv-vendor-id truncated to 12 characters");
714 len = 12;
716 memset(signature, 0, 12);
717 memcpy(signature, cpu->hyperv_vendor_id, len);
719 c->eax = HYPERV_CPUID_MIN;
720 c->ebx = signature[0];
721 c->ecx = signature[1];
722 c->edx = signature[2];
724 c = &cpuid_data.entries[cpuid_i++];
725 c->function = HYPERV_CPUID_INTERFACE;
726 memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
727 c->eax = signature[0];
728 c->ebx = 0;
729 c->ecx = 0;
730 c->edx = 0;
732 c = &cpuid_data.entries[cpuid_i++];
733 c->function = HYPERV_CPUID_VERSION;
734 c->eax = 0x00001bbc;
735 c->ebx = 0x00060001;
737 c = &cpuid_data.entries[cpuid_i++];
738 c->function = HYPERV_CPUID_FEATURES;
739 r = hyperv_handle_properties(cs);
740 if (r) {
741 return r;
743 c->eax = env->features[FEAT_HYPERV_EAX];
744 c->ebx = env->features[FEAT_HYPERV_EBX];
745 c->edx = env->features[FEAT_HYPERV_EDX];
747 c = &cpuid_data.entries[cpuid_i++];
748 c->function = HYPERV_CPUID_ENLIGHTMENT_INFO;
749 if (cpu->hyperv_relaxed_timing) {
750 c->eax |= HV_X64_RELAXED_TIMING_RECOMMENDED;
752 if (cpu->hyperv_vapic) {
753 c->eax |= HV_X64_APIC_ACCESS_RECOMMENDED;
755 c->ebx = cpu->hyperv_spinlock_attempts;
757 c = &cpuid_data.entries[cpuid_i++];
758 c->function = HYPERV_CPUID_IMPLEMENT_LIMITS;
759 c->eax = 0x40;
760 c->ebx = 0x40;
762 kvm_base = KVM_CPUID_SIGNATURE_NEXT;
763 has_msr_hv_hypercall = true;
766 if (cpu->expose_kvm) {
767 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
768 c = &cpuid_data.entries[cpuid_i++];
769 c->function = KVM_CPUID_SIGNATURE | kvm_base;
770 c->eax = KVM_CPUID_FEATURES | kvm_base;
771 c->ebx = signature[0];
772 c->ecx = signature[1];
773 c->edx = signature[2];
775 c = &cpuid_data.entries[cpuid_i++];
776 c->function = KVM_CPUID_FEATURES | kvm_base;
777 c->eax = env->features[FEAT_KVM];
780 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
782 for (i = 0; i <= limit; i++) {
783 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
784 fprintf(stderr, "unsupported level value: 0x%x\n", limit);
785 abort();
787 c = &cpuid_data.entries[cpuid_i++];
789 switch (i) {
790 case 2: {
791 /* Keep reading function 2 till all the input is received */
792 int times;
794 c->function = i;
795 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
796 KVM_CPUID_FLAG_STATE_READ_NEXT;
797 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
798 times = c->eax & 0xff;
800 for (j = 1; j < times; ++j) {
801 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
802 fprintf(stderr, "cpuid_data is full, no space for "
803 "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
804 abort();
806 c = &cpuid_data.entries[cpuid_i++];
807 c->function = i;
808 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
809 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
811 break;
813 case 4:
814 case 0xb:
815 case 0xd:
816 for (j = 0; ; j++) {
817 if (i == 0xd && j == 64) {
818 break;
820 c->function = i;
821 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
822 c->index = j;
823 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
825 if (i == 4 && c->eax == 0) {
826 break;
828 if (i == 0xb && !(c->ecx & 0xff00)) {
829 break;
831 if (i == 0xd && c->eax == 0) {
832 continue;
834 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
835 fprintf(stderr, "cpuid_data is full, no space for "
836 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
837 abort();
839 c = &cpuid_data.entries[cpuid_i++];
841 break;
842 default:
843 c->function = i;
844 c->flags = 0;
845 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
846 break;
850 if (limit >= 0x0a) {
851 uint32_t ver;
853 cpu_x86_cpuid(env, 0x0a, 0, &ver, &unused, &unused, &unused);
854 if ((ver & 0xff) > 0) {
855 has_msr_architectural_pmu = true;
856 num_architectural_pmu_counters = (ver & 0xff00) >> 8;
858 /* Shouldn't be more than 32, since that's the number of bits
859 * available in EBX to tell us _which_ counters are available.
860 * Play it safe.
862 if (num_architectural_pmu_counters > MAX_GP_COUNTERS) {
863 num_architectural_pmu_counters = MAX_GP_COUNTERS;
868 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
870 for (i = 0x80000000; i <= limit; i++) {
871 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
872 fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
873 abort();
875 c = &cpuid_data.entries[cpuid_i++];
877 c->function = i;
878 c->flags = 0;
879 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
882 /* Call Centaur's CPUID instructions they are supported. */
883 if (env->cpuid_xlevel2 > 0) {
884 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
886 for (i = 0xC0000000; i <= limit; i++) {
887 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
888 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
889 abort();
891 c = &cpuid_data.entries[cpuid_i++];
893 c->function = i;
894 c->flags = 0;
895 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
899 cpuid_data.cpuid.nent = cpuid_i;
901 if (((env->cpuid_version >> 8)&0xF) >= 6
902 && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
903 (CPUID_MCE | CPUID_MCA)
904 && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
905 uint64_t mcg_cap, unsupported_caps;
906 int banks;
907 int ret;
909 ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
910 if (ret < 0) {
911 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
912 return ret;
915 if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
916 error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
917 (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
918 return -ENOTSUP;
921 unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
922 if (unsupported_caps) {
923 if (unsupported_caps & MCG_LMCE_P) {
924 error_report("kvm: LMCE not supported");
925 return -ENOTSUP;
927 error_report("warning: Unsupported MCG_CAP bits: 0x%" PRIx64,
928 unsupported_caps);
931 env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
932 ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
933 if (ret < 0) {
934 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
935 return ret;
939 qemu_add_vm_change_state_handler(cpu_update_state, env);
941 c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
942 if (c) {
943 has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
944 !!(c->ecx & CPUID_EXT_SMX);
947 if (env->mcg_cap & MCG_LMCE_P) {
948 has_msr_mcg_ext_ctl = has_msr_feature_control = true;
951 c = cpuid_find_entry(&cpuid_data.cpuid, 0x80000007, 0);
952 if (c && (c->edx & 1<<8) && invtsc_mig_blocker == NULL) {
953 /* for migration */
954 error_setg(&invtsc_mig_blocker,
955 "State blocked by non-migratable CPU device"
956 " (invtsc flag)");
957 migrate_add_blocker(invtsc_mig_blocker);
958 /* for savevm */
959 vmstate_x86_cpu.unmigratable = 1;
962 cpuid_data.cpuid.padding = 0;
963 r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
964 if (r) {
965 return r;
968 r = kvm_arch_set_tsc_khz(cs);
969 if (r < 0) {
970 return r;
973 /* vcpu's TSC frequency is either specified by user, or following
974 * the value used by KVM if the former is not present. In the
975 * latter case, we query it from KVM and record in env->tsc_khz,
976 * so that vcpu's TSC frequency can be migrated later via this field.
978 if (!env->tsc_khz) {
979 r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
980 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
981 -ENOTSUP;
982 if (r > 0) {
983 env->tsc_khz = r;
987 if (has_xsave) {
988 env->kvm_xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
990 cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
992 if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
993 has_msr_tsc_aux = false;
996 return 0;
999 void kvm_arch_reset_vcpu(X86CPU *cpu)
1001 CPUX86State *env = &cpu->env;
1003 env->exception_injected = -1;
1004 env->interrupt_injected = -1;
1005 env->xcr0 = 1;
1006 if (kvm_irqchip_in_kernel()) {
1007 env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
1008 KVM_MP_STATE_UNINITIALIZED;
1009 } else {
1010 env->mp_state = KVM_MP_STATE_RUNNABLE;
1014 void kvm_arch_do_init_vcpu(X86CPU *cpu)
1016 CPUX86State *env = &cpu->env;
1018 /* APs get directly into wait-for-SIPI state. */
1019 if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
1020 env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
1024 static int kvm_get_supported_msrs(KVMState *s)
1026 static int kvm_supported_msrs;
1027 int ret = 0;
1029 /* first time */
1030 if (kvm_supported_msrs == 0) {
1031 struct kvm_msr_list msr_list, *kvm_msr_list;
1033 kvm_supported_msrs = -1;
1035 /* Obtain MSR list from KVM. These are the MSRs that we must
1036 * save/restore */
1037 msr_list.nmsrs = 0;
1038 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
1039 if (ret < 0 && ret != -E2BIG) {
1040 return ret;
1042 /* Old kernel modules had a bug and could write beyond the provided
1043 memory. Allocate at least a safe amount of 1K. */
1044 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
1045 msr_list.nmsrs *
1046 sizeof(msr_list.indices[0])));
1048 kvm_msr_list->nmsrs = msr_list.nmsrs;
1049 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
1050 if (ret >= 0) {
1051 int i;
1053 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
1054 if (kvm_msr_list->indices[i] == MSR_STAR) {
1055 has_msr_star = true;
1056 continue;
1058 if (kvm_msr_list->indices[i] == MSR_VM_HSAVE_PA) {
1059 has_msr_hsave_pa = true;
1060 continue;
1062 if (kvm_msr_list->indices[i] == MSR_TSC_AUX) {
1063 has_msr_tsc_aux = true;
1064 continue;
1066 if (kvm_msr_list->indices[i] == MSR_TSC_ADJUST) {
1067 has_msr_tsc_adjust = true;
1068 continue;
1070 if (kvm_msr_list->indices[i] == MSR_IA32_TSCDEADLINE) {
1071 has_msr_tsc_deadline = true;
1072 continue;
1074 if (kvm_msr_list->indices[i] == MSR_IA32_SMBASE) {
1075 has_msr_smbase = true;
1076 continue;
1078 if (kvm_msr_list->indices[i] == MSR_IA32_MISC_ENABLE) {
1079 has_msr_misc_enable = true;
1080 continue;
1082 if (kvm_msr_list->indices[i] == MSR_IA32_BNDCFGS) {
1083 has_msr_bndcfgs = true;
1084 continue;
1086 if (kvm_msr_list->indices[i] == MSR_IA32_XSS) {
1087 has_msr_xss = true;
1088 continue;
1090 if (kvm_msr_list->indices[i] == HV_X64_MSR_CRASH_CTL) {
1091 has_msr_hv_crash = true;
1092 continue;
1094 if (kvm_msr_list->indices[i] == HV_X64_MSR_RESET) {
1095 has_msr_hv_reset = true;
1096 continue;
1098 if (kvm_msr_list->indices[i] == HV_X64_MSR_VP_INDEX) {
1099 has_msr_hv_vpindex = true;
1100 continue;
1102 if (kvm_msr_list->indices[i] == HV_X64_MSR_VP_RUNTIME) {
1103 has_msr_hv_runtime = true;
1104 continue;
1106 if (kvm_msr_list->indices[i] == HV_X64_MSR_SCONTROL) {
1107 has_msr_hv_synic = true;
1108 continue;
1110 if (kvm_msr_list->indices[i] == HV_X64_MSR_STIMER0_CONFIG) {
1111 has_msr_hv_stimer = true;
1112 continue;
1117 g_free(kvm_msr_list);
1120 return ret;
1123 static Notifier smram_machine_done;
1124 static KVMMemoryListener smram_listener;
1125 static AddressSpace smram_address_space;
1126 static MemoryRegion smram_as_root;
1127 static MemoryRegion smram_as_mem;
1129 static void register_smram_listener(Notifier *n, void *unused)
1131 MemoryRegion *smram =
1132 (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
1134 /* Outer container... */
1135 memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
1136 memory_region_set_enabled(&smram_as_root, true);
1138 /* ... with two regions inside: normal system memory with low
1139 * priority, and...
1141 memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
1142 get_system_memory(), 0, ~0ull);
1143 memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
1144 memory_region_set_enabled(&smram_as_mem, true);
1146 if (smram) {
1147 /* ... SMRAM with higher priority */
1148 memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
1149 memory_region_set_enabled(smram, true);
1152 address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
1153 kvm_memory_listener_register(kvm_state, &smram_listener,
1154 &smram_address_space, 1);
1157 int kvm_arch_init(MachineState *ms, KVMState *s)
1159 uint64_t identity_base = 0xfffbc000;
1160 uint64_t shadow_mem;
1161 int ret;
1162 struct utsname utsname;
1164 #ifdef KVM_CAP_XSAVE
1165 has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1166 #endif
1168 #ifdef KVM_CAP_XCRS
1169 has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1170 #endif
1172 #ifdef KVM_CAP_PIT_STATE2
1173 has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1174 #endif
1176 ret = kvm_get_supported_msrs(s);
1177 if (ret < 0) {
1178 return ret;
1181 uname(&utsname);
1182 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
1185 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
1186 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
1187 * Since these must be part of guest physical memory, we need to allocate
1188 * them, both by setting their start addresses in the kernel and by
1189 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
1191 * Older KVM versions may not support setting the identity map base. In
1192 * that case we need to stick with the default, i.e. a 256K maximum BIOS
1193 * size.
1195 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
1196 /* Allows up to 16M BIOSes. */
1197 identity_base = 0xfeffc000;
1199 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
1200 if (ret < 0) {
1201 return ret;
1205 /* Set TSS base one page after EPT identity map. */
1206 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
1207 if (ret < 0) {
1208 return ret;
1211 /* Tell fw_cfg to notify the BIOS to reserve the range. */
1212 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
1213 if (ret < 0) {
1214 fprintf(stderr, "e820_add_entry() table is full\n");
1215 return ret;
1217 qemu_register_reset(kvm_unpoison_all, NULL);
1219 shadow_mem = machine_kvm_shadow_mem(ms);
1220 if (shadow_mem != -1) {
1221 shadow_mem /= 4096;
1222 ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
1223 if (ret < 0) {
1224 return ret;
1228 if (kvm_check_extension(s, KVM_CAP_X86_SMM)) {
1229 smram_machine_done.notify = register_smram_listener;
1230 qemu_add_machine_init_done_notifier(&smram_machine_done);
1232 return 0;
1235 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1237 lhs->selector = rhs->selector;
1238 lhs->base = rhs->base;
1239 lhs->limit = rhs->limit;
1240 lhs->type = 3;
1241 lhs->present = 1;
1242 lhs->dpl = 3;
1243 lhs->db = 0;
1244 lhs->s = 1;
1245 lhs->l = 0;
1246 lhs->g = 0;
1247 lhs->avl = 0;
1248 lhs->unusable = 0;
1251 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1253 unsigned flags = rhs->flags;
1254 lhs->selector = rhs->selector;
1255 lhs->base = rhs->base;
1256 lhs->limit = rhs->limit;
1257 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
1258 lhs->present = (flags & DESC_P_MASK) != 0;
1259 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
1260 lhs->db = (flags >> DESC_B_SHIFT) & 1;
1261 lhs->s = (flags & DESC_S_MASK) != 0;
1262 lhs->l = (flags >> DESC_L_SHIFT) & 1;
1263 lhs->g = (flags & DESC_G_MASK) != 0;
1264 lhs->avl = (flags & DESC_AVL_MASK) != 0;
1265 lhs->unusable = !lhs->present;
1266 lhs->padding = 0;
1269 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
1271 lhs->selector = rhs->selector;
1272 lhs->base = rhs->base;
1273 lhs->limit = rhs->limit;
1274 if (rhs->unusable) {
1275 lhs->flags = 0;
1276 } else {
1277 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
1278 (rhs->present * DESC_P_MASK) |
1279 (rhs->dpl << DESC_DPL_SHIFT) |
1280 (rhs->db << DESC_B_SHIFT) |
1281 (rhs->s * DESC_S_MASK) |
1282 (rhs->l << DESC_L_SHIFT) |
1283 (rhs->g * DESC_G_MASK) |
1284 (rhs->avl * DESC_AVL_MASK);
1288 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
1290 if (set) {
1291 *kvm_reg = *qemu_reg;
1292 } else {
1293 *qemu_reg = *kvm_reg;
1297 static int kvm_getput_regs(X86CPU *cpu, int set)
1299 CPUX86State *env = &cpu->env;
1300 struct kvm_regs regs;
1301 int ret = 0;
1303 if (!set) {
1304 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
1305 if (ret < 0) {
1306 return ret;
1310 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
1311 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
1312 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
1313 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
1314 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
1315 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
1316 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
1317 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
1318 #ifdef TARGET_X86_64
1319 kvm_getput_reg(&regs.r8, &env->regs[8], set);
1320 kvm_getput_reg(&regs.r9, &env->regs[9], set);
1321 kvm_getput_reg(&regs.r10, &env->regs[10], set);
1322 kvm_getput_reg(&regs.r11, &env->regs[11], set);
1323 kvm_getput_reg(&regs.r12, &env->regs[12], set);
1324 kvm_getput_reg(&regs.r13, &env->regs[13], set);
1325 kvm_getput_reg(&regs.r14, &env->regs[14], set);
1326 kvm_getput_reg(&regs.r15, &env->regs[15], set);
1327 #endif
1329 kvm_getput_reg(&regs.rflags, &env->eflags, set);
1330 kvm_getput_reg(&regs.rip, &env->eip, set);
1332 if (set) {
1333 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
1336 return ret;
1339 static int kvm_put_fpu(X86CPU *cpu)
1341 CPUX86State *env = &cpu->env;
1342 struct kvm_fpu fpu;
1343 int i;
1345 memset(&fpu, 0, sizeof fpu);
1346 fpu.fsw = env->fpus & ~(7 << 11);
1347 fpu.fsw |= (env->fpstt & 7) << 11;
1348 fpu.fcw = env->fpuc;
1349 fpu.last_opcode = env->fpop;
1350 fpu.last_ip = env->fpip;
1351 fpu.last_dp = env->fpdp;
1352 for (i = 0; i < 8; ++i) {
1353 fpu.ftwx |= (!env->fptags[i]) << i;
1355 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
1356 for (i = 0; i < CPU_NB_REGS; i++) {
1357 stq_p(&fpu.xmm[i][0], env->xmm_regs[i].ZMM_Q(0));
1358 stq_p(&fpu.xmm[i][8], env->xmm_regs[i].ZMM_Q(1));
1360 fpu.mxcsr = env->mxcsr;
1362 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
1365 #define XSAVE_FCW_FSW 0
1366 #define XSAVE_FTW_FOP 1
1367 #define XSAVE_CWD_RIP 2
1368 #define XSAVE_CWD_RDP 4
1369 #define XSAVE_MXCSR 6
1370 #define XSAVE_ST_SPACE 8
1371 #define XSAVE_XMM_SPACE 40
1372 #define XSAVE_XSTATE_BV 128
1373 #define XSAVE_YMMH_SPACE 144
1374 #define XSAVE_BNDREGS 240
1375 #define XSAVE_BNDCSR 256
1376 #define XSAVE_OPMASK 272
1377 #define XSAVE_ZMM_Hi256 288
1378 #define XSAVE_Hi16_ZMM 416
1379 #define XSAVE_PKRU 672
1381 #define XSAVE_BYTE_OFFSET(word_offset) \
1382 ((word_offset) * sizeof(((struct kvm_xsave *)0)->region[0]))
1384 #define ASSERT_OFFSET(word_offset, field) \
1385 QEMU_BUILD_BUG_ON(XSAVE_BYTE_OFFSET(word_offset) != \
1386 offsetof(X86XSaveArea, field))
1388 ASSERT_OFFSET(XSAVE_FCW_FSW, legacy.fcw);
1389 ASSERT_OFFSET(XSAVE_FTW_FOP, legacy.ftw);
1390 ASSERT_OFFSET(XSAVE_CWD_RIP, legacy.fpip);
1391 ASSERT_OFFSET(XSAVE_CWD_RDP, legacy.fpdp);
1392 ASSERT_OFFSET(XSAVE_MXCSR, legacy.mxcsr);
1393 ASSERT_OFFSET(XSAVE_ST_SPACE, legacy.fpregs);
1394 ASSERT_OFFSET(XSAVE_XMM_SPACE, legacy.xmm_regs);
1395 ASSERT_OFFSET(XSAVE_XSTATE_BV, header.xstate_bv);
1396 ASSERT_OFFSET(XSAVE_YMMH_SPACE, avx_state);
1397 ASSERT_OFFSET(XSAVE_BNDREGS, bndreg_state);
1398 ASSERT_OFFSET(XSAVE_BNDCSR, bndcsr_state);
1399 ASSERT_OFFSET(XSAVE_OPMASK, opmask_state);
1400 ASSERT_OFFSET(XSAVE_ZMM_Hi256, zmm_hi256_state);
1401 ASSERT_OFFSET(XSAVE_Hi16_ZMM, hi16_zmm_state);
1402 ASSERT_OFFSET(XSAVE_PKRU, pkru_state);
1404 static int kvm_put_xsave(X86CPU *cpu)
1406 CPUX86State *env = &cpu->env;
1407 X86XSaveArea *xsave = env->kvm_xsave_buf;
1408 uint16_t cwd, swd, twd;
1409 int i;
1411 if (!has_xsave) {
1412 return kvm_put_fpu(cpu);
1415 memset(xsave, 0, sizeof(struct kvm_xsave));
1416 twd = 0;
1417 swd = env->fpus & ~(7 << 11);
1418 swd |= (env->fpstt & 7) << 11;
1419 cwd = env->fpuc;
1420 for (i = 0; i < 8; ++i) {
1421 twd |= (!env->fptags[i]) << i;
1423 xsave->legacy.fcw = cwd;
1424 xsave->legacy.fsw = swd;
1425 xsave->legacy.ftw = twd;
1426 xsave->legacy.fpop = env->fpop;
1427 xsave->legacy.fpip = env->fpip;
1428 xsave->legacy.fpdp = env->fpdp;
1429 memcpy(&xsave->legacy.fpregs, env->fpregs,
1430 sizeof env->fpregs);
1431 xsave->legacy.mxcsr = env->mxcsr;
1432 xsave->header.xstate_bv = env->xstate_bv;
1433 memcpy(&xsave->bndreg_state.bnd_regs, env->bnd_regs,
1434 sizeof env->bnd_regs);
1435 xsave->bndcsr_state.bndcsr = env->bndcs_regs;
1436 memcpy(&xsave->opmask_state.opmask_regs, env->opmask_regs,
1437 sizeof env->opmask_regs);
1439 for (i = 0; i < CPU_NB_REGS; i++) {
1440 uint8_t *xmm = xsave->legacy.xmm_regs[i];
1441 uint8_t *ymmh = xsave->avx_state.ymmh[i];
1442 uint8_t *zmmh = xsave->zmm_hi256_state.zmm_hi256[i];
1443 stq_p(xmm, env->xmm_regs[i].ZMM_Q(0));
1444 stq_p(xmm+8, env->xmm_regs[i].ZMM_Q(1));
1445 stq_p(ymmh, env->xmm_regs[i].ZMM_Q(2));
1446 stq_p(ymmh+8, env->xmm_regs[i].ZMM_Q(3));
1447 stq_p(zmmh, env->xmm_regs[i].ZMM_Q(4));
1448 stq_p(zmmh+8, env->xmm_regs[i].ZMM_Q(5));
1449 stq_p(zmmh+16, env->xmm_regs[i].ZMM_Q(6));
1450 stq_p(zmmh+24, env->xmm_regs[i].ZMM_Q(7));
1453 #ifdef TARGET_X86_64
1454 memcpy(&xsave->hi16_zmm_state.hi16_zmm, &env->xmm_regs[16],
1455 16 * sizeof env->xmm_regs[16]);
1456 memcpy(&xsave->pkru_state, &env->pkru, sizeof env->pkru);
1457 #endif
1458 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
1461 static int kvm_put_xcrs(X86CPU *cpu)
1463 CPUX86State *env = &cpu->env;
1464 struct kvm_xcrs xcrs = {};
1466 if (!has_xcrs) {
1467 return 0;
1470 xcrs.nr_xcrs = 1;
1471 xcrs.flags = 0;
1472 xcrs.xcrs[0].xcr = 0;
1473 xcrs.xcrs[0].value = env->xcr0;
1474 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
1477 static int kvm_put_sregs(X86CPU *cpu)
1479 CPUX86State *env = &cpu->env;
1480 struct kvm_sregs sregs;
1482 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
1483 if (env->interrupt_injected >= 0) {
1484 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
1485 (uint64_t)1 << (env->interrupt_injected % 64);
1488 if ((env->eflags & VM_MASK)) {
1489 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
1490 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
1491 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
1492 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
1493 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
1494 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
1495 } else {
1496 set_seg(&sregs.cs, &env->segs[R_CS]);
1497 set_seg(&sregs.ds, &env->segs[R_DS]);
1498 set_seg(&sregs.es, &env->segs[R_ES]);
1499 set_seg(&sregs.fs, &env->segs[R_FS]);
1500 set_seg(&sregs.gs, &env->segs[R_GS]);
1501 set_seg(&sregs.ss, &env->segs[R_SS]);
1504 set_seg(&sregs.tr, &env->tr);
1505 set_seg(&sregs.ldt, &env->ldt);
1507 sregs.idt.limit = env->idt.limit;
1508 sregs.idt.base = env->idt.base;
1509 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
1510 sregs.gdt.limit = env->gdt.limit;
1511 sregs.gdt.base = env->gdt.base;
1512 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
1514 sregs.cr0 = env->cr[0];
1515 sregs.cr2 = env->cr[2];
1516 sregs.cr3 = env->cr[3];
1517 sregs.cr4 = env->cr[4];
1519 sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
1520 sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
1522 sregs.efer = env->efer;
1524 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
1527 static void kvm_msr_buf_reset(X86CPU *cpu)
1529 memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
1532 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
1534 struct kvm_msrs *msrs = cpu->kvm_msr_buf;
1535 void *limit = ((void *)msrs) + MSR_BUF_SIZE;
1536 struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
1538 assert((void *)(entry + 1) <= limit);
1540 entry->index = index;
1541 entry->reserved = 0;
1542 entry->data = value;
1543 msrs->nmsrs++;
1546 static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
1548 kvm_msr_buf_reset(cpu);
1549 kvm_msr_entry_add(cpu, index, value);
1551 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1554 void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
1556 int ret;
1558 ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
1559 assert(ret == 1);
1562 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
1564 CPUX86State *env = &cpu->env;
1565 int ret;
1567 if (!has_msr_tsc_deadline) {
1568 return 0;
1571 ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
1572 if (ret < 0) {
1573 return ret;
1576 assert(ret == 1);
1577 return 0;
1581 * Provide a separate write service for the feature control MSR in order to
1582 * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
1583 * before writing any other state because forcibly leaving nested mode
1584 * invalidates the VCPU state.
1586 static int kvm_put_msr_feature_control(X86CPU *cpu)
1588 int ret;
1590 if (!has_msr_feature_control) {
1591 return 0;
1594 ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
1595 cpu->env.msr_ia32_feature_control);
1596 if (ret < 0) {
1597 return ret;
1600 assert(ret == 1);
1601 return 0;
1604 static int kvm_put_msrs(X86CPU *cpu, int level)
1606 CPUX86State *env = &cpu->env;
1607 int i;
1608 int ret;
1610 kvm_msr_buf_reset(cpu);
1612 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
1613 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
1614 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
1615 kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
1616 if (has_msr_star) {
1617 kvm_msr_entry_add(cpu, MSR_STAR, env->star);
1619 if (has_msr_hsave_pa) {
1620 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
1622 if (has_msr_tsc_aux) {
1623 kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
1625 if (has_msr_tsc_adjust) {
1626 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
1628 if (has_msr_misc_enable) {
1629 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
1630 env->msr_ia32_misc_enable);
1632 if (has_msr_smbase) {
1633 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
1635 if (has_msr_bndcfgs) {
1636 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
1638 if (has_msr_xss) {
1639 kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
1641 #ifdef TARGET_X86_64
1642 if (lm_capable_kernel) {
1643 kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
1644 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
1645 kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
1646 kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
1648 #endif
1650 * The following MSRs have side effects on the guest or are too heavy
1651 * for normal writeback. Limit them to reset or full state updates.
1653 if (level >= KVM_PUT_RESET_STATE) {
1654 kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
1655 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
1656 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
1657 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
1658 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
1660 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
1661 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
1663 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
1664 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
1666 if (has_msr_architectural_pmu) {
1667 /* Stop the counter. */
1668 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
1669 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
1671 /* Set the counter values. */
1672 for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
1673 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
1674 env->msr_fixed_counters[i]);
1676 for (i = 0; i < num_architectural_pmu_counters; i++) {
1677 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
1678 env->msr_gp_counters[i]);
1679 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
1680 env->msr_gp_evtsel[i]);
1682 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
1683 env->msr_global_status);
1684 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1685 env->msr_global_ovf_ctrl);
1687 /* Now start the PMU. */
1688 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
1689 env->msr_fixed_ctr_ctrl);
1690 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
1691 env->msr_global_ctrl);
1693 if (has_msr_hv_hypercall) {
1694 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
1695 env->msr_hv_guest_os_id);
1696 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
1697 env->msr_hv_hypercall);
1699 if (cpu->hyperv_vapic) {
1700 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
1701 env->msr_hv_vapic);
1703 if (cpu->hyperv_time) {
1704 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, env->msr_hv_tsc);
1706 if (has_msr_hv_crash) {
1707 int j;
1709 for (j = 0; j < HV_X64_MSR_CRASH_PARAMS; j++)
1710 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
1711 env->msr_hv_crash_params[j]);
1713 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL,
1714 HV_X64_MSR_CRASH_CTL_NOTIFY);
1716 if (has_msr_hv_runtime) {
1717 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
1719 if (cpu->hyperv_synic) {
1720 int j;
1722 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
1723 env->msr_hv_synic_control);
1724 kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION,
1725 env->msr_hv_synic_version);
1726 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
1727 env->msr_hv_synic_evt_page);
1728 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
1729 env->msr_hv_synic_msg_page);
1731 for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
1732 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
1733 env->msr_hv_synic_sint[j]);
1736 if (has_msr_hv_stimer) {
1737 int j;
1739 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
1740 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
1741 env->msr_hv_stimer_config[j]);
1744 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
1745 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
1746 env->msr_hv_stimer_count[j]);
1749 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
1750 uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
1752 kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
1753 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
1754 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
1755 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
1756 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
1757 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
1758 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
1759 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
1760 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
1761 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
1762 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
1763 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
1764 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
1765 /* The CPU GPs if we write to a bit above the physical limit of
1766 * the host CPU (and KVM emulates that)
1768 uint64_t mask = env->mtrr_var[i].mask;
1769 mask &= phys_mask;
1771 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
1772 env->mtrr_var[i].base);
1773 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
1777 /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
1778 * kvm_put_msr_feature_control. */
1780 if (env->mcg_cap) {
1781 int i;
1783 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
1784 kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
1785 if (has_msr_mcg_ext_ctl) {
1786 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
1788 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1789 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
1793 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1794 if (ret < 0) {
1795 return ret;
1798 assert(ret == cpu->kvm_msr_buf->nmsrs);
1799 return 0;
1803 static int kvm_get_fpu(X86CPU *cpu)
1805 CPUX86State *env = &cpu->env;
1806 struct kvm_fpu fpu;
1807 int i, ret;
1809 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
1810 if (ret < 0) {
1811 return ret;
1814 env->fpstt = (fpu.fsw >> 11) & 7;
1815 env->fpus = fpu.fsw;
1816 env->fpuc = fpu.fcw;
1817 env->fpop = fpu.last_opcode;
1818 env->fpip = fpu.last_ip;
1819 env->fpdp = fpu.last_dp;
1820 for (i = 0; i < 8; ++i) {
1821 env->fptags[i] = !((fpu.ftwx >> i) & 1);
1823 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
1824 for (i = 0; i < CPU_NB_REGS; i++) {
1825 env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
1826 env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
1828 env->mxcsr = fpu.mxcsr;
1830 return 0;
1833 static int kvm_get_xsave(X86CPU *cpu)
1835 CPUX86State *env = &cpu->env;
1836 X86XSaveArea *xsave = env->kvm_xsave_buf;
1837 int ret, i;
1838 uint16_t cwd, swd, twd;
1840 if (!has_xsave) {
1841 return kvm_get_fpu(cpu);
1844 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
1845 if (ret < 0) {
1846 return ret;
1849 cwd = xsave->legacy.fcw;
1850 swd = xsave->legacy.fsw;
1851 twd = xsave->legacy.ftw;
1852 env->fpop = xsave->legacy.fpop;
1853 env->fpstt = (swd >> 11) & 7;
1854 env->fpus = swd;
1855 env->fpuc = cwd;
1856 for (i = 0; i < 8; ++i) {
1857 env->fptags[i] = !((twd >> i) & 1);
1859 env->fpip = xsave->legacy.fpip;
1860 env->fpdp = xsave->legacy.fpdp;
1861 env->mxcsr = xsave->legacy.mxcsr;
1862 memcpy(env->fpregs, &xsave->legacy.fpregs,
1863 sizeof env->fpregs);
1864 env->xstate_bv = xsave->header.xstate_bv;
1865 memcpy(env->bnd_regs, &xsave->bndreg_state.bnd_regs,
1866 sizeof env->bnd_regs);
1867 env->bndcs_regs = xsave->bndcsr_state.bndcsr;
1868 memcpy(env->opmask_regs, &xsave->opmask_state.opmask_regs,
1869 sizeof env->opmask_regs);
1871 for (i = 0; i < CPU_NB_REGS; i++) {
1872 uint8_t *xmm = xsave->legacy.xmm_regs[i];
1873 uint8_t *ymmh = xsave->avx_state.ymmh[i];
1874 uint8_t *zmmh = xsave->zmm_hi256_state.zmm_hi256[i];
1875 env->xmm_regs[i].ZMM_Q(0) = ldq_p(xmm);
1876 env->xmm_regs[i].ZMM_Q(1) = ldq_p(xmm+8);
1877 env->xmm_regs[i].ZMM_Q(2) = ldq_p(ymmh);
1878 env->xmm_regs[i].ZMM_Q(3) = ldq_p(ymmh+8);
1879 env->xmm_regs[i].ZMM_Q(4) = ldq_p(zmmh);
1880 env->xmm_regs[i].ZMM_Q(5) = ldq_p(zmmh+8);
1881 env->xmm_regs[i].ZMM_Q(6) = ldq_p(zmmh+16);
1882 env->xmm_regs[i].ZMM_Q(7) = ldq_p(zmmh+24);
1885 #ifdef TARGET_X86_64
1886 memcpy(&env->xmm_regs[16], &xsave->hi16_zmm_state.hi16_zmm,
1887 16 * sizeof env->xmm_regs[16]);
1888 memcpy(&env->pkru, &xsave->pkru_state, sizeof env->pkru);
1889 #endif
1890 return 0;
1893 static int kvm_get_xcrs(X86CPU *cpu)
1895 CPUX86State *env = &cpu->env;
1896 int i, ret;
1897 struct kvm_xcrs xcrs;
1899 if (!has_xcrs) {
1900 return 0;
1903 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
1904 if (ret < 0) {
1905 return ret;
1908 for (i = 0; i < xcrs.nr_xcrs; i++) {
1909 /* Only support xcr0 now */
1910 if (xcrs.xcrs[i].xcr == 0) {
1911 env->xcr0 = xcrs.xcrs[i].value;
1912 break;
1915 return 0;
1918 static int kvm_get_sregs(X86CPU *cpu)
1920 CPUX86State *env = &cpu->env;
1921 struct kvm_sregs sregs;
1922 uint32_t hflags;
1923 int bit, i, ret;
1925 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
1926 if (ret < 0) {
1927 return ret;
1930 /* There can only be one pending IRQ set in the bitmap at a time, so try
1931 to find it and save its number instead (-1 for none). */
1932 env->interrupt_injected = -1;
1933 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
1934 if (sregs.interrupt_bitmap[i]) {
1935 bit = ctz64(sregs.interrupt_bitmap[i]);
1936 env->interrupt_injected = i * 64 + bit;
1937 break;
1941 get_seg(&env->segs[R_CS], &sregs.cs);
1942 get_seg(&env->segs[R_DS], &sregs.ds);
1943 get_seg(&env->segs[R_ES], &sregs.es);
1944 get_seg(&env->segs[R_FS], &sregs.fs);
1945 get_seg(&env->segs[R_GS], &sregs.gs);
1946 get_seg(&env->segs[R_SS], &sregs.ss);
1948 get_seg(&env->tr, &sregs.tr);
1949 get_seg(&env->ldt, &sregs.ldt);
1951 env->idt.limit = sregs.idt.limit;
1952 env->idt.base = sregs.idt.base;
1953 env->gdt.limit = sregs.gdt.limit;
1954 env->gdt.base = sregs.gdt.base;
1956 env->cr[0] = sregs.cr0;
1957 env->cr[2] = sregs.cr2;
1958 env->cr[3] = sregs.cr3;
1959 env->cr[4] = sregs.cr4;
1961 env->efer = sregs.efer;
1963 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
1965 #define HFLAG_COPY_MASK \
1966 ~( HF_CPL_MASK | HF_PE_MASK | HF_MP_MASK | HF_EM_MASK | \
1967 HF_TS_MASK | HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK | \
1968 HF_OSFXSR_MASK | HF_LMA_MASK | HF_CS32_MASK | \
1969 HF_SS32_MASK | HF_CS64_MASK | HF_ADDSEG_MASK)
1971 hflags = env->hflags & HFLAG_COPY_MASK;
1972 hflags |= (env->segs[R_SS].flags >> DESC_DPL_SHIFT) & HF_CPL_MASK;
1973 hflags |= (env->cr[0] & CR0_PE_MASK) << (HF_PE_SHIFT - CR0_PE_SHIFT);
1974 hflags |= (env->cr[0] << (HF_MP_SHIFT - CR0_MP_SHIFT)) &
1975 (HF_MP_MASK | HF_EM_MASK | HF_TS_MASK);
1976 hflags |= (env->eflags & (HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK));
1978 if (env->cr[4] & CR4_OSFXSR_MASK) {
1979 hflags |= HF_OSFXSR_MASK;
1982 if (env->efer & MSR_EFER_LMA) {
1983 hflags |= HF_LMA_MASK;
1986 if ((hflags & HF_LMA_MASK) && (env->segs[R_CS].flags & DESC_L_MASK)) {
1987 hflags |= HF_CS32_MASK | HF_SS32_MASK | HF_CS64_MASK;
1988 } else {
1989 hflags |= (env->segs[R_CS].flags & DESC_B_MASK) >>
1990 (DESC_B_SHIFT - HF_CS32_SHIFT);
1991 hflags |= (env->segs[R_SS].flags & DESC_B_MASK) >>
1992 (DESC_B_SHIFT - HF_SS32_SHIFT);
1993 if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK) ||
1994 !(hflags & HF_CS32_MASK)) {
1995 hflags |= HF_ADDSEG_MASK;
1996 } else {
1997 hflags |= ((env->segs[R_DS].base | env->segs[R_ES].base |
1998 env->segs[R_SS].base) != 0) << HF_ADDSEG_SHIFT;
2001 env->hflags = hflags;
2003 return 0;
2006 static int kvm_get_msrs(X86CPU *cpu)
2008 CPUX86State *env = &cpu->env;
2009 struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
2010 int ret, i;
2011 uint64_t mtrr_top_bits;
2013 kvm_msr_buf_reset(cpu);
2015 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
2016 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
2017 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
2018 kvm_msr_entry_add(cpu, MSR_PAT, 0);
2019 if (has_msr_star) {
2020 kvm_msr_entry_add(cpu, MSR_STAR, 0);
2022 if (has_msr_hsave_pa) {
2023 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
2025 if (has_msr_tsc_aux) {
2026 kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
2028 if (has_msr_tsc_adjust) {
2029 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
2031 if (has_msr_tsc_deadline) {
2032 kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
2034 if (has_msr_misc_enable) {
2035 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
2037 if (has_msr_smbase) {
2038 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
2040 if (has_msr_feature_control) {
2041 kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
2043 if (has_msr_bndcfgs) {
2044 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
2046 if (has_msr_xss) {
2047 kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
2051 if (!env->tsc_valid) {
2052 kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
2053 env->tsc_valid = !runstate_is_running();
2056 #ifdef TARGET_X86_64
2057 if (lm_capable_kernel) {
2058 kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
2059 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
2060 kvm_msr_entry_add(cpu, MSR_FMASK, 0);
2061 kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
2063 #endif
2064 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
2065 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
2066 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
2067 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
2069 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
2070 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
2072 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
2073 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
2075 if (has_msr_architectural_pmu) {
2076 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
2077 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
2078 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
2079 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
2080 for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
2081 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
2083 for (i = 0; i < num_architectural_pmu_counters; i++) {
2084 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
2085 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
2089 if (env->mcg_cap) {
2090 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
2091 kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
2092 if (has_msr_mcg_ext_ctl) {
2093 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
2095 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
2096 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
2100 if (has_msr_hv_hypercall) {
2101 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
2102 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
2104 if (cpu->hyperv_vapic) {
2105 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
2107 if (cpu->hyperv_time) {
2108 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
2110 if (has_msr_hv_crash) {
2111 int j;
2113 for (j = 0; j < HV_X64_MSR_CRASH_PARAMS; j++) {
2114 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
2117 if (has_msr_hv_runtime) {
2118 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
2120 if (cpu->hyperv_synic) {
2121 uint32_t msr;
2123 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
2124 kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, 0);
2125 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
2126 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
2127 for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
2128 kvm_msr_entry_add(cpu, msr, 0);
2131 if (has_msr_hv_stimer) {
2132 uint32_t msr;
2134 for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
2135 msr++) {
2136 kvm_msr_entry_add(cpu, msr, 0);
2139 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
2140 kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
2141 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
2142 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
2143 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
2144 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
2145 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
2146 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
2147 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
2148 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
2149 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
2150 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
2151 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
2152 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
2153 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
2154 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
2158 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
2159 if (ret < 0) {
2160 return ret;
2163 assert(ret == cpu->kvm_msr_buf->nmsrs);
2165 * MTRR masks: Each mask consists of 5 parts
2166 * a 10..0: must be zero
2167 * b 11 : valid bit
2168 * c n-1.12: actual mask bits
2169 * d 51..n: reserved must be zero
2170 * e 63.52: reserved must be zero
2172 * 'n' is the number of physical bits supported by the CPU and is
2173 * apparently always <= 52. We know our 'n' but don't know what
2174 * the destinations 'n' is; it might be smaller, in which case
2175 * it masks (c) on loading. It might be larger, in which case
2176 * we fill 'd' so that d..c is consistent irrespetive of the 'n'
2177 * we're migrating to.
2180 if (cpu->fill_mtrr_mask) {
2181 QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
2182 assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
2183 mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
2184 } else {
2185 mtrr_top_bits = 0;
2188 for (i = 0; i < ret; i++) {
2189 uint32_t index = msrs[i].index;
2190 switch (index) {
2191 case MSR_IA32_SYSENTER_CS:
2192 env->sysenter_cs = msrs[i].data;
2193 break;
2194 case MSR_IA32_SYSENTER_ESP:
2195 env->sysenter_esp = msrs[i].data;
2196 break;
2197 case MSR_IA32_SYSENTER_EIP:
2198 env->sysenter_eip = msrs[i].data;
2199 break;
2200 case MSR_PAT:
2201 env->pat = msrs[i].data;
2202 break;
2203 case MSR_STAR:
2204 env->star = msrs[i].data;
2205 break;
2206 #ifdef TARGET_X86_64
2207 case MSR_CSTAR:
2208 env->cstar = msrs[i].data;
2209 break;
2210 case MSR_KERNELGSBASE:
2211 env->kernelgsbase = msrs[i].data;
2212 break;
2213 case MSR_FMASK:
2214 env->fmask = msrs[i].data;
2215 break;
2216 case MSR_LSTAR:
2217 env->lstar = msrs[i].data;
2218 break;
2219 #endif
2220 case MSR_IA32_TSC:
2221 env->tsc = msrs[i].data;
2222 break;
2223 case MSR_TSC_AUX:
2224 env->tsc_aux = msrs[i].data;
2225 break;
2226 case MSR_TSC_ADJUST:
2227 env->tsc_adjust = msrs[i].data;
2228 break;
2229 case MSR_IA32_TSCDEADLINE:
2230 env->tsc_deadline = msrs[i].data;
2231 break;
2232 case MSR_VM_HSAVE_PA:
2233 env->vm_hsave = msrs[i].data;
2234 break;
2235 case MSR_KVM_SYSTEM_TIME:
2236 env->system_time_msr = msrs[i].data;
2237 break;
2238 case MSR_KVM_WALL_CLOCK:
2239 env->wall_clock_msr = msrs[i].data;
2240 break;
2241 case MSR_MCG_STATUS:
2242 env->mcg_status = msrs[i].data;
2243 break;
2244 case MSR_MCG_CTL:
2245 env->mcg_ctl = msrs[i].data;
2246 break;
2247 case MSR_MCG_EXT_CTL:
2248 env->mcg_ext_ctl = msrs[i].data;
2249 break;
2250 case MSR_IA32_MISC_ENABLE:
2251 env->msr_ia32_misc_enable = msrs[i].data;
2252 break;
2253 case MSR_IA32_SMBASE:
2254 env->smbase = msrs[i].data;
2255 break;
2256 case MSR_IA32_FEATURE_CONTROL:
2257 env->msr_ia32_feature_control = msrs[i].data;
2258 break;
2259 case MSR_IA32_BNDCFGS:
2260 env->msr_bndcfgs = msrs[i].data;
2261 break;
2262 case MSR_IA32_XSS:
2263 env->xss = msrs[i].data;
2264 break;
2265 default:
2266 if (msrs[i].index >= MSR_MC0_CTL &&
2267 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
2268 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
2270 break;
2271 case MSR_KVM_ASYNC_PF_EN:
2272 env->async_pf_en_msr = msrs[i].data;
2273 break;
2274 case MSR_KVM_PV_EOI_EN:
2275 env->pv_eoi_en_msr = msrs[i].data;
2276 break;
2277 case MSR_KVM_STEAL_TIME:
2278 env->steal_time_msr = msrs[i].data;
2279 break;
2280 case MSR_CORE_PERF_FIXED_CTR_CTRL:
2281 env->msr_fixed_ctr_ctrl = msrs[i].data;
2282 break;
2283 case MSR_CORE_PERF_GLOBAL_CTRL:
2284 env->msr_global_ctrl = msrs[i].data;
2285 break;
2286 case MSR_CORE_PERF_GLOBAL_STATUS:
2287 env->msr_global_status = msrs[i].data;
2288 break;
2289 case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
2290 env->msr_global_ovf_ctrl = msrs[i].data;
2291 break;
2292 case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
2293 env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
2294 break;
2295 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
2296 env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
2297 break;
2298 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
2299 env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
2300 break;
2301 case HV_X64_MSR_HYPERCALL:
2302 env->msr_hv_hypercall = msrs[i].data;
2303 break;
2304 case HV_X64_MSR_GUEST_OS_ID:
2305 env->msr_hv_guest_os_id = msrs[i].data;
2306 break;
2307 case HV_X64_MSR_APIC_ASSIST_PAGE:
2308 env->msr_hv_vapic = msrs[i].data;
2309 break;
2310 case HV_X64_MSR_REFERENCE_TSC:
2311 env->msr_hv_tsc = msrs[i].data;
2312 break;
2313 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2314 env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
2315 break;
2316 case HV_X64_MSR_VP_RUNTIME:
2317 env->msr_hv_runtime = msrs[i].data;
2318 break;
2319 case HV_X64_MSR_SCONTROL:
2320 env->msr_hv_synic_control = msrs[i].data;
2321 break;
2322 case HV_X64_MSR_SVERSION:
2323 env->msr_hv_synic_version = msrs[i].data;
2324 break;
2325 case HV_X64_MSR_SIEFP:
2326 env->msr_hv_synic_evt_page = msrs[i].data;
2327 break;
2328 case HV_X64_MSR_SIMP:
2329 env->msr_hv_synic_msg_page = msrs[i].data;
2330 break;
2331 case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
2332 env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
2333 break;
2334 case HV_X64_MSR_STIMER0_CONFIG:
2335 case HV_X64_MSR_STIMER1_CONFIG:
2336 case HV_X64_MSR_STIMER2_CONFIG:
2337 case HV_X64_MSR_STIMER3_CONFIG:
2338 env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
2339 msrs[i].data;
2340 break;
2341 case HV_X64_MSR_STIMER0_COUNT:
2342 case HV_X64_MSR_STIMER1_COUNT:
2343 case HV_X64_MSR_STIMER2_COUNT:
2344 case HV_X64_MSR_STIMER3_COUNT:
2345 env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
2346 msrs[i].data;
2347 break;
2348 case MSR_MTRRdefType:
2349 env->mtrr_deftype = msrs[i].data;
2350 break;
2351 case MSR_MTRRfix64K_00000:
2352 env->mtrr_fixed[0] = msrs[i].data;
2353 break;
2354 case MSR_MTRRfix16K_80000:
2355 env->mtrr_fixed[1] = msrs[i].data;
2356 break;
2357 case MSR_MTRRfix16K_A0000:
2358 env->mtrr_fixed[2] = msrs[i].data;
2359 break;
2360 case MSR_MTRRfix4K_C0000:
2361 env->mtrr_fixed[3] = msrs[i].data;
2362 break;
2363 case MSR_MTRRfix4K_C8000:
2364 env->mtrr_fixed[4] = msrs[i].data;
2365 break;
2366 case MSR_MTRRfix4K_D0000:
2367 env->mtrr_fixed[5] = msrs[i].data;
2368 break;
2369 case MSR_MTRRfix4K_D8000:
2370 env->mtrr_fixed[6] = msrs[i].data;
2371 break;
2372 case MSR_MTRRfix4K_E0000:
2373 env->mtrr_fixed[7] = msrs[i].data;
2374 break;
2375 case MSR_MTRRfix4K_E8000:
2376 env->mtrr_fixed[8] = msrs[i].data;
2377 break;
2378 case MSR_MTRRfix4K_F0000:
2379 env->mtrr_fixed[9] = msrs[i].data;
2380 break;
2381 case MSR_MTRRfix4K_F8000:
2382 env->mtrr_fixed[10] = msrs[i].data;
2383 break;
2384 case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
2385 if (index & 1) {
2386 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
2387 mtrr_top_bits;
2388 } else {
2389 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
2391 break;
2395 return 0;
2398 static int kvm_put_mp_state(X86CPU *cpu)
2400 struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
2402 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
2405 static int kvm_get_mp_state(X86CPU *cpu)
2407 CPUState *cs = CPU(cpu);
2408 CPUX86State *env = &cpu->env;
2409 struct kvm_mp_state mp_state;
2410 int ret;
2412 ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
2413 if (ret < 0) {
2414 return ret;
2416 env->mp_state = mp_state.mp_state;
2417 if (kvm_irqchip_in_kernel()) {
2418 cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
2420 return 0;
2423 static int kvm_get_apic(X86CPU *cpu)
2425 DeviceState *apic = cpu->apic_state;
2426 struct kvm_lapic_state kapic;
2427 int ret;
2429 if (apic && kvm_irqchip_in_kernel()) {
2430 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
2431 if (ret < 0) {
2432 return ret;
2435 kvm_get_apic_state(apic, &kapic);
2437 return 0;
2440 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
2442 CPUState *cs = CPU(cpu);
2443 CPUX86State *env = &cpu->env;
2444 struct kvm_vcpu_events events = {};
2446 if (!kvm_has_vcpu_events()) {
2447 return 0;
2450 events.exception.injected = (env->exception_injected >= 0);
2451 events.exception.nr = env->exception_injected;
2452 events.exception.has_error_code = env->has_error_code;
2453 events.exception.error_code = env->error_code;
2454 events.exception.pad = 0;
2456 events.interrupt.injected = (env->interrupt_injected >= 0);
2457 events.interrupt.nr = env->interrupt_injected;
2458 events.interrupt.soft = env->soft_interrupt;
2460 events.nmi.injected = env->nmi_injected;
2461 events.nmi.pending = env->nmi_pending;
2462 events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
2463 events.nmi.pad = 0;
2465 events.sipi_vector = env->sipi_vector;
2466 events.flags = 0;
2468 if (has_msr_smbase) {
2469 events.smi.smm = !!(env->hflags & HF_SMM_MASK);
2470 events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
2471 if (kvm_irqchip_in_kernel()) {
2472 /* As soon as these are moved to the kernel, remove them
2473 * from cs->interrupt_request.
2475 events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
2476 events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
2477 cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
2478 } else {
2479 /* Keep these in cs->interrupt_request. */
2480 events.smi.pending = 0;
2481 events.smi.latched_init = 0;
2483 events.flags |= KVM_VCPUEVENT_VALID_SMM;
2486 if (level >= KVM_PUT_RESET_STATE) {
2487 events.flags |=
2488 KVM_VCPUEVENT_VALID_NMI_PENDING | KVM_VCPUEVENT_VALID_SIPI_VECTOR;
2491 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
2494 static int kvm_get_vcpu_events(X86CPU *cpu)
2496 CPUX86State *env = &cpu->env;
2497 struct kvm_vcpu_events events;
2498 int ret;
2500 if (!kvm_has_vcpu_events()) {
2501 return 0;
2504 memset(&events, 0, sizeof(events));
2505 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
2506 if (ret < 0) {
2507 return ret;
2509 env->exception_injected =
2510 events.exception.injected ? events.exception.nr : -1;
2511 env->has_error_code = events.exception.has_error_code;
2512 env->error_code = events.exception.error_code;
2514 env->interrupt_injected =
2515 events.interrupt.injected ? events.interrupt.nr : -1;
2516 env->soft_interrupt = events.interrupt.soft;
2518 env->nmi_injected = events.nmi.injected;
2519 env->nmi_pending = events.nmi.pending;
2520 if (events.nmi.masked) {
2521 env->hflags2 |= HF2_NMI_MASK;
2522 } else {
2523 env->hflags2 &= ~HF2_NMI_MASK;
2526 if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
2527 if (events.smi.smm) {
2528 env->hflags |= HF_SMM_MASK;
2529 } else {
2530 env->hflags &= ~HF_SMM_MASK;
2532 if (events.smi.pending) {
2533 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2534 } else {
2535 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2537 if (events.smi.smm_inside_nmi) {
2538 env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
2539 } else {
2540 env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
2542 if (events.smi.latched_init) {
2543 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2544 } else {
2545 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2549 env->sipi_vector = events.sipi_vector;
2551 return 0;
2554 static int kvm_guest_debug_workarounds(X86CPU *cpu)
2556 CPUState *cs = CPU(cpu);
2557 CPUX86State *env = &cpu->env;
2558 int ret = 0;
2559 unsigned long reinject_trap = 0;
2561 if (!kvm_has_vcpu_events()) {
2562 if (env->exception_injected == 1) {
2563 reinject_trap = KVM_GUESTDBG_INJECT_DB;
2564 } else if (env->exception_injected == 3) {
2565 reinject_trap = KVM_GUESTDBG_INJECT_BP;
2567 env->exception_injected = -1;
2571 * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
2572 * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
2573 * by updating the debug state once again if single-stepping is on.
2574 * Another reason to call kvm_update_guest_debug here is a pending debug
2575 * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
2576 * reinject them via SET_GUEST_DEBUG.
2578 if (reinject_trap ||
2579 (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
2580 ret = kvm_update_guest_debug(cs, reinject_trap);
2582 return ret;
2585 static int kvm_put_debugregs(X86CPU *cpu)
2587 CPUX86State *env = &cpu->env;
2588 struct kvm_debugregs dbgregs;
2589 int i;
2591 if (!kvm_has_debugregs()) {
2592 return 0;
2595 for (i = 0; i < 4; i++) {
2596 dbgregs.db[i] = env->dr[i];
2598 dbgregs.dr6 = env->dr[6];
2599 dbgregs.dr7 = env->dr[7];
2600 dbgregs.flags = 0;
2602 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
2605 static int kvm_get_debugregs(X86CPU *cpu)
2607 CPUX86State *env = &cpu->env;
2608 struct kvm_debugregs dbgregs;
2609 int i, ret;
2611 if (!kvm_has_debugregs()) {
2612 return 0;
2615 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
2616 if (ret < 0) {
2617 return ret;
2619 for (i = 0; i < 4; i++) {
2620 env->dr[i] = dbgregs.db[i];
2622 env->dr[4] = env->dr[6] = dbgregs.dr6;
2623 env->dr[5] = env->dr[7] = dbgregs.dr7;
2625 return 0;
2628 int kvm_arch_put_registers(CPUState *cpu, int level)
2630 X86CPU *x86_cpu = X86_CPU(cpu);
2631 int ret;
2633 assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
2635 if (level >= KVM_PUT_RESET_STATE) {
2636 ret = kvm_put_msr_feature_control(x86_cpu);
2637 if (ret < 0) {
2638 return ret;
2642 if (level == KVM_PUT_FULL_STATE) {
2643 /* We don't check for kvm_arch_set_tsc_khz() errors here,
2644 * because TSC frequency mismatch shouldn't abort migration,
2645 * unless the user explicitly asked for a more strict TSC
2646 * setting (e.g. using an explicit "tsc-freq" option).
2648 kvm_arch_set_tsc_khz(cpu);
2651 ret = kvm_getput_regs(x86_cpu, 1);
2652 if (ret < 0) {
2653 return ret;
2655 ret = kvm_put_xsave(x86_cpu);
2656 if (ret < 0) {
2657 return ret;
2659 ret = kvm_put_xcrs(x86_cpu);
2660 if (ret < 0) {
2661 return ret;
2663 ret = kvm_put_sregs(x86_cpu);
2664 if (ret < 0) {
2665 return ret;
2667 /* must be before kvm_put_msrs */
2668 ret = kvm_inject_mce_oldstyle(x86_cpu);
2669 if (ret < 0) {
2670 return ret;
2672 ret = kvm_put_msrs(x86_cpu, level);
2673 if (ret < 0) {
2674 return ret;
2676 if (level >= KVM_PUT_RESET_STATE) {
2677 ret = kvm_put_mp_state(x86_cpu);
2678 if (ret < 0) {
2679 return ret;
2683 ret = kvm_put_tscdeadline_msr(x86_cpu);
2684 if (ret < 0) {
2685 return ret;
2688 ret = kvm_put_vcpu_events(x86_cpu, level);
2689 if (ret < 0) {
2690 return ret;
2692 ret = kvm_put_debugregs(x86_cpu);
2693 if (ret < 0) {
2694 return ret;
2696 /* must be last */
2697 ret = kvm_guest_debug_workarounds(x86_cpu);
2698 if (ret < 0) {
2699 return ret;
2701 return 0;
2704 int kvm_arch_get_registers(CPUState *cs)
2706 X86CPU *cpu = X86_CPU(cs);
2707 int ret;
2709 assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
2711 ret = kvm_getput_regs(cpu, 0);
2712 if (ret < 0) {
2713 goto out;
2715 ret = kvm_get_xsave(cpu);
2716 if (ret < 0) {
2717 goto out;
2719 ret = kvm_get_xcrs(cpu);
2720 if (ret < 0) {
2721 goto out;
2723 ret = kvm_get_sregs(cpu);
2724 if (ret < 0) {
2725 goto out;
2727 ret = kvm_get_msrs(cpu);
2728 if (ret < 0) {
2729 goto out;
2731 ret = kvm_get_mp_state(cpu);
2732 if (ret < 0) {
2733 goto out;
2735 ret = kvm_get_apic(cpu);
2736 if (ret < 0) {
2737 goto out;
2739 ret = kvm_get_vcpu_events(cpu);
2740 if (ret < 0) {
2741 goto out;
2743 ret = kvm_get_debugregs(cpu);
2744 if (ret < 0) {
2745 goto out;
2747 ret = 0;
2748 out:
2749 cpu_sync_bndcs_hflags(&cpu->env);
2750 return ret;
2753 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
2755 X86CPU *x86_cpu = X86_CPU(cpu);
2756 CPUX86State *env = &x86_cpu->env;
2757 int ret;
2759 /* Inject NMI */
2760 if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
2761 if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
2762 qemu_mutex_lock_iothread();
2763 cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
2764 qemu_mutex_unlock_iothread();
2765 DPRINTF("injected NMI\n");
2766 ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
2767 if (ret < 0) {
2768 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
2769 strerror(-ret));
2772 if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
2773 qemu_mutex_lock_iothread();
2774 cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
2775 qemu_mutex_unlock_iothread();
2776 DPRINTF("injected SMI\n");
2777 ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
2778 if (ret < 0) {
2779 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
2780 strerror(-ret));
2785 if (!kvm_pic_in_kernel()) {
2786 qemu_mutex_lock_iothread();
2789 /* Force the VCPU out of its inner loop to process any INIT requests
2790 * or (for userspace APIC, but it is cheap to combine the checks here)
2791 * pending TPR access reports.
2793 if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
2794 if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
2795 !(env->hflags & HF_SMM_MASK)) {
2796 cpu->exit_request = 1;
2798 if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
2799 cpu->exit_request = 1;
2803 if (!kvm_pic_in_kernel()) {
2804 /* Try to inject an interrupt if the guest can accept it */
2805 if (run->ready_for_interrupt_injection &&
2806 (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
2807 (env->eflags & IF_MASK)) {
2808 int irq;
2810 cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
2811 irq = cpu_get_pic_interrupt(env);
2812 if (irq >= 0) {
2813 struct kvm_interrupt intr;
2815 intr.irq = irq;
2816 DPRINTF("injected interrupt %d\n", irq);
2817 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
2818 if (ret < 0) {
2819 fprintf(stderr,
2820 "KVM: injection failed, interrupt lost (%s)\n",
2821 strerror(-ret));
2826 /* If we have an interrupt but the guest is not ready to receive an
2827 * interrupt, request an interrupt window exit. This will
2828 * cause a return to userspace as soon as the guest is ready to
2829 * receive interrupts. */
2830 if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
2831 run->request_interrupt_window = 1;
2832 } else {
2833 run->request_interrupt_window = 0;
2836 DPRINTF("setting tpr\n");
2837 run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
2839 qemu_mutex_unlock_iothread();
2843 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
2845 X86CPU *x86_cpu = X86_CPU(cpu);
2846 CPUX86State *env = &x86_cpu->env;
2848 if (run->flags & KVM_RUN_X86_SMM) {
2849 env->hflags |= HF_SMM_MASK;
2850 } else {
2851 env->hflags &= HF_SMM_MASK;
2853 if (run->if_flag) {
2854 env->eflags |= IF_MASK;
2855 } else {
2856 env->eflags &= ~IF_MASK;
2859 /* We need to protect the apic state against concurrent accesses from
2860 * different threads in case the userspace irqchip is used. */
2861 if (!kvm_irqchip_in_kernel()) {
2862 qemu_mutex_lock_iothread();
2864 cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
2865 cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
2866 if (!kvm_irqchip_in_kernel()) {
2867 qemu_mutex_unlock_iothread();
2869 return cpu_get_mem_attrs(env);
2872 int kvm_arch_process_async_events(CPUState *cs)
2874 X86CPU *cpu = X86_CPU(cs);
2875 CPUX86State *env = &cpu->env;
2877 if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
2878 /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
2879 assert(env->mcg_cap);
2881 cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
2883 kvm_cpu_synchronize_state(cs);
2885 if (env->exception_injected == EXCP08_DBLE) {
2886 /* this means triple fault */
2887 qemu_system_reset_request();
2888 cs->exit_request = 1;
2889 return 0;
2891 env->exception_injected = EXCP12_MCHK;
2892 env->has_error_code = 0;
2894 cs->halted = 0;
2895 if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
2896 env->mp_state = KVM_MP_STATE_RUNNABLE;
2900 if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
2901 !(env->hflags & HF_SMM_MASK)) {
2902 kvm_cpu_synchronize_state(cs);
2903 do_cpu_init(cpu);
2906 if (kvm_irqchip_in_kernel()) {
2907 return 0;
2910 if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
2911 cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
2912 apic_poll_irq(cpu->apic_state);
2914 if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2915 (env->eflags & IF_MASK)) ||
2916 (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
2917 cs->halted = 0;
2919 if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
2920 kvm_cpu_synchronize_state(cs);
2921 do_cpu_sipi(cpu);
2923 if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
2924 cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
2925 kvm_cpu_synchronize_state(cs);
2926 apic_handle_tpr_access_report(cpu->apic_state, env->eip,
2927 env->tpr_access_type);
2930 return cs->halted;
2933 static int kvm_handle_halt(X86CPU *cpu)
2935 CPUState *cs = CPU(cpu);
2936 CPUX86State *env = &cpu->env;
2938 if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2939 (env->eflags & IF_MASK)) &&
2940 !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
2941 cs->halted = 1;
2942 return EXCP_HLT;
2945 return 0;
2948 static int kvm_handle_tpr_access(X86CPU *cpu)
2950 CPUState *cs = CPU(cpu);
2951 struct kvm_run *run = cs->kvm_run;
2953 apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
2954 run->tpr_access.is_write ? TPR_ACCESS_WRITE
2955 : TPR_ACCESS_READ);
2956 return 1;
2959 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2961 static const uint8_t int3 = 0xcc;
2963 if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
2964 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
2965 return -EINVAL;
2967 return 0;
2970 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2972 uint8_t int3;
2974 if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
2975 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
2976 return -EINVAL;
2978 return 0;
2981 static struct {
2982 target_ulong addr;
2983 int len;
2984 int type;
2985 } hw_breakpoint[4];
2987 static int nb_hw_breakpoint;
2989 static int find_hw_breakpoint(target_ulong addr, int len, int type)
2991 int n;
2993 for (n = 0; n < nb_hw_breakpoint; n++) {
2994 if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
2995 (hw_breakpoint[n].len == len || len == -1)) {
2996 return n;
2999 return -1;
3002 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
3003 target_ulong len, int type)
3005 switch (type) {
3006 case GDB_BREAKPOINT_HW:
3007 len = 1;
3008 break;
3009 case GDB_WATCHPOINT_WRITE:
3010 case GDB_WATCHPOINT_ACCESS:
3011 switch (len) {
3012 case 1:
3013 break;
3014 case 2:
3015 case 4:
3016 case 8:
3017 if (addr & (len - 1)) {
3018 return -EINVAL;
3020 break;
3021 default:
3022 return -EINVAL;
3024 break;
3025 default:
3026 return -ENOSYS;
3029 if (nb_hw_breakpoint == 4) {
3030 return -ENOBUFS;
3032 if (find_hw_breakpoint(addr, len, type) >= 0) {
3033 return -EEXIST;
3035 hw_breakpoint[nb_hw_breakpoint].addr = addr;
3036 hw_breakpoint[nb_hw_breakpoint].len = len;
3037 hw_breakpoint[nb_hw_breakpoint].type = type;
3038 nb_hw_breakpoint++;
3040 return 0;
3043 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
3044 target_ulong len, int type)
3046 int n;
3048 n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
3049 if (n < 0) {
3050 return -ENOENT;
3052 nb_hw_breakpoint--;
3053 hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
3055 return 0;
3058 void kvm_arch_remove_all_hw_breakpoints(void)
3060 nb_hw_breakpoint = 0;
3063 static CPUWatchpoint hw_watchpoint;
3065 static int kvm_handle_debug(X86CPU *cpu,
3066 struct kvm_debug_exit_arch *arch_info)
3068 CPUState *cs = CPU(cpu);
3069 CPUX86State *env = &cpu->env;
3070 int ret = 0;
3071 int n;
3073 if (arch_info->exception == 1) {
3074 if (arch_info->dr6 & (1 << 14)) {
3075 if (cs->singlestep_enabled) {
3076 ret = EXCP_DEBUG;
3078 } else {
3079 for (n = 0; n < 4; n++) {
3080 if (arch_info->dr6 & (1 << n)) {
3081 switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
3082 case 0x0:
3083 ret = EXCP_DEBUG;
3084 break;
3085 case 0x1:
3086 ret = EXCP_DEBUG;
3087 cs->watchpoint_hit = &hw_watchpoint;
3088 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
3089 hw_watchpoint.flags = BP_MEM_WRITE;
3090 break;
3091 case 0x3:
3092 ret = EXCP_DEBUG;
3093 cs->watchpoint_hit = &hw_watchpoint;
3094 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
3095 hw_watchpoint.flags = BP_MEM_ACCESS;
3096 break;
3101 } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
3102 ret = EXCP_DEBUG;
3104 if (ret == 0) {
3105 cpu_synchronize_state(cs);
3106 assert(env->exception_injected == -1);
3108 /* pass to guest */
3109 env->exception_injected = arch_info->exception;
3110 env->has_error_code = 0;
3113 return ret;
3116 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
3118 const uint8_t type_code[] = {
3119 [GDB_BREAKPOINT_HW] = 0x0,
3120 [GDB_WATCHPOINT_WRITE] = 0x1,
3121 [GDB_WATCHPOINT_ACCESS] = 0x3
3123 const uint8_t len_code[] = {
3124 [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
3126 int n;
3128 if (kvm_sw_breakpoints_active(cpu)) {
3129 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
3131 if (nb_hw_breakpoint > 0) {
3132 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
3133 dbg->arch.debugreg[7] = 0x0600;
3134 for (n = 0; n < nb_hw_breakpoint; n++) {
3135 dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
3136 dbg->arch.debugreg[7] |= (2 << (n * 2)) |
3137 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
3138 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
3143 static bool host_supports_vmx(void)
3145 uint32_t ecx, unused;
3147 host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
3148 return ecx & CPUID_EXT_VMX;
3151 #define VMX_INVALID_GUEST_STATE 0x80000021
3153 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
3155 X86CPU *cpu = X86_CPU(cs);
3156 uint64_t code;
3157 int ret;
3159 switch (run->exit_reason) {
3160 case KVM_EXIT_HLT:
3161 DPRINTF("handle_hlt\n");
3162 qemu_mutex_lock_iothread();
3163 ret = kvm_handle_halt(cpu);
3164 qemu_mutex_unlock_iothread();
3165 break;
3166 case KVM_EXIT_SET_TPR:
3167 ret = 0;
3168 break;
3169 case KVM_EXIT_TPR_ACCESS:
3170 qemu_mutex_lock_iothread();
3171 ret = kvm_handle_tpr_access(cpu);
3172 qemu_mutex_unlock_iothread();
3173 break;
3174 case KVM_EXIT_FAIL_ENTRY:
3175 code = run->fail_entry.hardware_entry_failure_reason;
3176 fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
3177 code);
3178 if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
3179 fprintf(stderr,
3180 "\nIf you're running a guest on an Intel machine without "
3181 "unrestricted mode\n"
3182 "support, the failure can be most likely due to the guest "
3183 "entering an invalid\n"
3184 "state for Intel VT. For example, the guest maybe running "
3185 "in big real mode\n"
3186 "which is not supported on less recent Intel processors."
3187 "\n\n");
3189 ret = -1;
3190 break;
3191 case KVM_EXIT_EXCEPTION:
3192 fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
3193 run->ex.exception, run->ex.error_code);
3194 ret = -1;
3195 break;
3196 case KVM_EXIT_DEBUG:
3197 DPRINTF("kvm_exit_debug\n");
3198 qemu_mutex_lock_iothread();
3199 ret = kvm_handle_debug(cpu, &run->debug.arch);
3200 qemu_mutex_unlock_iothread();
3201 break;
3202 case KVM_EXIT_HYPERV:
3203 ret = kvm_hv_handle_exit(cpu, &run->hyperv);
3204 break;
3205 case KVM_EXIT_IOAPIC_EOI:
3206 ioapic_eoi_broadcast(run->eoi.vector);
3207 ret = 0;
3208 break;
3209 default:
3210 fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
3211 ret = -1;
3212 break;
3215 return ret;
3218 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
3220 X86CPU *cpu = X86_CPU(cs);
3221 CPUX86State *env = &cpu->env;
3223 kvm_cpu_synchronize_state(cs);
3224 return !(env->cr[0] & CR0_PE_MASK) ||
3225 ((env->segs[R_CS].selector & 3) != 3);
3228 void kvm_arch_init_irq_routing(KVMState *s)
3230 if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
3231 /* If kernel can't do irq routing, interrupt source
3232 * override 0->2 cannot be set up as required by HPET.
3233 * So we have to disable it.
3235 no_hpet = 1;
3237 /* We know at this point that we're using the in-kernel
3238 * irqchip, so we can use irqfds, and on x86 we know
3239 * we can use msi via irqfd and GSI routing.
3241 kvm_msi_via_irqfd_allowed = true;
3242 kvm_gsi_routing_allowed = true;
3244 if (kvm_irqchip_is_split()) {
3245 int i;
3247 /* If the ioapic is in QEMU and the lapics are in KVM, reserve
3248 MSI routes for signaling interrupts to the local apics. */
3249 for (i = 0; i < IOAPIC_NUM_PINS; i++) {
3250 if (kvm_irqchip_add_msi_route(s, 0, NULL) < 0) {
3251 error_report("Could not enable split IRQ mode.");
3252 exit(1);
3258 int kvm_arch_irqchip_create(MachineState *ms, KVMState *s)
3260 int ret;
3261 if (machine_kernel_irqchip_split(ms)) {
3262 ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
3263 if (ret) {
3264 error_report("Could not enable split irqchip mode: %s",
3265 strerror(-ret));
3266 exit(1);
3267 } else {
3268 DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
3269 kvm_split_irqchip = true;
3270 return 1;
3272 } else {
3273 return 0;
3277 /* Classic KVM device assignment interface. Will remain x86 only. */
3278 int kvm_device_pci_assign(KVMState *s, PCIHostDeviceAddress *dev_addr,
3279 uint32_t flags, uint32_t *dev_id)
3281 struct kvm_assigned_pci_dev dev_data = {
3282 .segnr = dev_addr->domain,
3283 .busnr = dev_addr->bus,
3284 .devfn = PCI_DEVFN(dev_addr->slot, dev_addr->function),
3285 .flags = flags,
3287 int ret;
3289 dev_data.assigned_dev_id =
3290 (dev_addr->domain << 16) | (dev_addr->bus << 8) | dev_data.devfn;
3292 ret = kvm_vm_ioctl(s, KVM_ASSIGN_PCI_DEVICE, &dev_data);
3293 if (ret < 0) {
3294 return ret;
3297 *dev_id = dev_data.assigned_dev_id;
3299 return 0;
3302 int kvm_device_pci_deassign(KVMState *s, uint32_t dev_id)
3304 struct kvm_assigned_pci_dev dev_data = {
3305 .assigned_dev_id = dev_id,
3308 return kvm_vm_ioctl(s, KVM_DEASSIGN_PCI_DEVICE, &dev_data);
3311 static int kvm_assign_irq_internal(KVMState *s, uint32_t dev_id,
3312 uint32_t irq_type, uint32_t guest_irq)
3314 struct kvm_assigned_irq assigned_irq = {
3315 .assigned_dev_id = dev_id,
3316 .guest_irq = guest_irq,
3317 .flags = irq_type,
3320 if (kvm_check_extension(s, KVM_CAP_ASSIGN_DEV_IRQ)) {
3321 return kvm_vm_ioctl(s, KVM_ASSIGN_DEV_IRQ, &assigned_irq);
3322 } else {
3323 return kvm_vm_ioctl(s, KVM_ASSIGN_IRQ, &assigned_irq);
3327 int kvm_device_intx_assign(KVMState *s, uint32_t dev_id, bool use_host_msi,
3328 uint32_t guest_irq)
3330 uint32_t irq_type = KVM_DEV_IRQ_GUEST_INTX |
3331 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX);
3333 return kvm_assign_irq_internal(s, dev_id, irq_type, guest_irq);
3336 int kvm_device_intx_set_mask(KVMState *s, uint32_t dev_id, bool masked)
3338 struct kvm_assigned_pci_dev dev_data = {
3339 .assigned_dev_id = dev_id,
3340 .flags = masked ? KVM_DEV_ASSIGN_MASK_INTX : 0,
3343 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_INTX_MASK, &dev_data);
3346 static int kvm_deassign_irq_internal(KVMState *s, uint32_t dev_id,
3347 uint32_t type)
3349 struct kvm_assigned_irq assigned_irq = {
3350 .assigned_dev_id = dev_id,
3351 .flags = type,
3354 return kvm_vm_ioctl(s, KVM_DEASSIGN_DEV_IRQ, &assigned_irq);
3357 int kvm_device_intx_deassign(KVMState *s, uint32_t dev_id, bool use_host_msi)
3359 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_INTX |
3360 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX));
3363 int kvm_device_msi_assign(KVMState *s, uint32_t dev_id, int virq)
3365 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSI |
3366 KVM_DEV_IRQ_GUEST_MSI, virq);
3369 int kvm_device_msi_deassign(KVMState *s, uint32_t dev_id)
3371 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSI |
3372 KVM_DEV_IRQ_HOST_MSI);
3375 bool kvm_device_msix_supported(KVMState *s)
3377 /* The kernel lacks a corresponding KVM_CAP, so we probe by calling
3378 * KVM_ASSIGN_SET_MSIX_NR with an invalid parameter. */
3379 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, NULL) == -EFAULT;
3382 int kvm_device_msix_init_vectors(KVMState *s, uint32_t dev_id,
3383 uint32_t nr_vectors)
3385 struct kvm_assigned_msix_nr msix_nr = {
3386 .assigned_dev_id = dev_id,
3387 .entry_nr = nr_vectors,
3390 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, &msix_nr);
3393 int kvm_device_msix_set_vector(KVMState *s, uint32_t dev_id, uint32_t vector,
3394 int virq)
3396 struct kvm_assigned_msix_entry msix_entry = {
3397 .assigned_dev_id = dev_id,
3398 .gsi = virq,
3399 .entry = vector,
3402 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_ENTRY, &msix_entry);
3405 int kvm_device_msix_assign(KVMState *s, uint32_t dev_id)
3407 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSIX |
3408 KVM_DEV_IRQ_GUEST_MSIX, 0);
3411 int kvm_device_msix_deassign(KVMState *s, uint32_t dev_id)
3413 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSIX |
3414 KVM_DEV_IRQ_HOST_MSIX);
3417 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
3418 uint64_t address, uint32_t data, PCIDevice *dev)
3420 X86IOMMUState *iommu = x86_iommu_get_default();
3422 if (iommu) {
3423 int ret;
3424 MSIMessage src, dst;
3425 X86IOMMUClass *class = X86_IOMMU_GET_CLASS(iommu);
3427 src.address = route->u.msi.address_hi;
3428 src.address <<= VTD_MSI_ADDR_HI_SHIFT;
3429 src.address |= route->u.msi.address_lo;
3430 src.data = route->u.msi.data;
3432 ret = class->int_remap(iommu, &src, &dst, dev ? \
3433 pci_requester_id(dev) : \
3434 X86_IOMMU_SID_INVALID);
3435 if (ret) {
3436 trace_kvm_x86_fixup_msi_error(route->gsi);
3437 return 1;
3440 route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
3441 route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
3442 route->u.msi.data = dst.data;
3445 return 0;
3448 typedef struct MSIRouteEntry MSIRouteEntry;
3450 struct MSIRouteEntry {
3451 PCIDevice *dev; /* Device pointer */
3452 int vector; /* MSI/MSIX vector index */
3453 int virq; /* Virtual IRQ index */
3454 QLIST_ENTRY(MSIRouteEntry) list;
3457 /* List of used GSI routes */
3458 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
3459 QLIST_HEAD_INITIALIZER(msi_route_list);
3461 static void kvm_update_msi_routes_all(void *private, bool global,
3462 uint32_t index, uint32_t mask)
3464 int cnt = 0;
3465 MSIRouteEntry *entry;
3466 MSIMessage msg;
3467 /* TODO: explicit route update */
3468 QLIST_FOREACH(entry, &msi_route_list, list) {
3469 cnt++;
3470 msg = pci_get_msi_message(entry->dev, entry->vector);
3471 kvm_irqchip_update_msi_route(kvm_state, entry->virq,
3472 msg, entry->dev);
3474 kvm_irqchip_commit_routes(kvm_state);
3475 trace_kvm_x86_update_msi_routes(cnt);
3478 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
3479 int vector, PCIDevice *dev)
3481 static bool notify_list_inited = false;
3482 MSIRouteEntry *entry;
3484 if (!dev) {
3485 /* These are (possibly) IOAPIC routes only used for split
3486 * kernel irqchip mode, while what we are housekeeping are
3487 * PCI devices only. */
3488 return 0;
3491 entry = g_new0(MSIRouteEntry, 1);
3492 entry->dev = dev;
3493 entry->vector = vector;
3494 entry->virq = route->gsi;
3495 QLIST_INSERT_HEAD(&msi_route_list, entry, list);
3497 trace_kvm_x86_add_msi_route(route->gsi);
3499 if (!notify_list_inited) {
3500 /* For the first time we do add route, add ourselves into
3501 * IOMMU's IEC notify list if needed. */
3502 X86IOMMUState *iommu = x86_iommu_get_default();
3503 if (iommu) {
3504 x86_iommu_iec_register_notifier(iommu,
3505 kvm_update_msi_routes_all,
3506 NULL);
3508 notify_list_inited = true;
3510 return 0;
3513 int kvm_arch_release_virq_post(int virq)
3515 MSIRouteEntry *entry, *next;
3516 QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
3517 if (entry->virq == virq) {
3518 trace_kvm_x86_remove_msi_route(virq);
3519 QLIST_REMOVE(entry, list);
3520 break;
3523 return 0;
3526 int kvm_arch_msi_data_to_gsi(uint32_t data)
3528 abort();