build-sys: remove qmp-commands-old.h
[qemu/kevin.git] / target-i386 / kvm.c
blobf1ad805665adf518d3a7bf92d6f9d5a18b9abe34
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_async_pf_en;
87 static bool has_msr_pv_eoi_en;
88 static bool has_msr_misc_enable;
89 static bool has_msr_smbase;
90 static bool has_msr_bndcfgs;
91 static bool has_msr_kvm_steal_time;
92 static int lm_capable_kernel;
93 static bool has_msr_hv_hypercall;
94 static bool has_msr_hv_vapic;
95 static bool has_msr_hv_tsc;
96 static bool has_msr_hv_crash;
97 static bool has_msr_hv_reset;
98 static bool has_msr_hv_vpindex;
99 static bool has_msr_hv_runtime;
100 static bool has_msr_hv_synic;
101 static bool has_msr_hv_stimer;
102 static bool has_msr_mtrr;
103 static bool has_msr_xss;
105 static bool has_msr_architectural_pmu;
106 static uint32_t num_architectural_pmu_counters;
108 static int has_xsave;
109 static int has_xcrs;
110 static int has_pit_state2;
112 static bool has_msr_mcg_ext_ctl;
114 static struct kvm_cpuid2 *cpuid_cache;
116 int kvm_has_pit_state2(void)
118 return has_pit_state2;
121 bool kvm_has_smm(void)
123 return kvm_check_extension(kvm_state, KVM_CAP_X86_SMM);
126 bool kvm_allows_irq0_override(void)
128 return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
131 static int kvm_get_tsc(CPUState *cs)
133 X86CPU *cpu = X86_CPU(cs);
134 CPUX86State *env = &cpu->env;
135 struct {
136 struct kvm_msrs info;
137 struct kvm_msr_entry entries[1];
138 } msr_data;
139 int ret;
141 if (env->tsc_valid) {
142 return 0;
145 msr_data.info.nmsrs = 1;
146 msr_data.entries[0].index = MSR_IA32_TSC;
147 env->tsc_valid = !runstate_is_running();
149 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
150 if (ret < 0) {
151 return ret;
154 assert(ret == 1);
155 env->tsc = msr_data.entries[0].data;
156 return 0;
159 static inline void do_kvm_synchronize_tsc(void *arg)
161 CPUState *cpu = arg;
163 kvm_get_tsc(cpu);
166 void kvm_synchronize_all_tsc(void)
168 CPUState *cpu;
170 if (kvm_enabled()) {
171 CPU_FOREACH(cpu) {
172 run_on_cpu(cpu, do_kvm_synchronize_tsc, cpu);
177 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
179 struct kvm_cpuid2 *cpuid;
180 int r, size;
182 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
183 cpuid = g_malloc0(size);
184 cpuid->nent = max;
185 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
186 if (r == 0 && cpuid->nent >= max) {
187 r = -E2BIG;
189 if (r < 0) {
190 if (r == -E2BIG) {
191 g_free(cpuid);
192 return NULL;
193 } else {
194 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
195 strerror(-r));
196 exit(1);
199 return cpuid;
202 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
203 * for all entries.
205 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
207 struct kvm_cpuid2 *cpuid;
208 int max = 1;
210 if (cpuid_cache != NULL) {
211 return cpuid_cache;
213 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
214 max *= 2;
216 cpuid_cache = cpuid;
217 return cpuid;
220 static const struct kvm_para_features {
221 int cap;
222 int feature;
223 } para_features[] = {
224 { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
225 { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
226 { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
227 { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
230 static int get_para_features(KVMState *s)
232 int i, features = 0;
234 for (i = 0; i < ARRAY_SIZE(para_features); i++) {
235 if (kvm_check_extension(s, para_features[i].cap)) {
236 features |= (1 << para_features[i].feature);
240 return features;
244 /* Returns the value for a specific register on the cpuid entry
246 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
248 uint32_t ret = 0;
249 switch (reg) {
250 case R_EAX:
251 ret = entry->eax;
252 break;
253 case R_EBX:
254 ret = entry->ebx;
255 break;
256 case R_ECX:
257 ret = entry->ecx;
258 break;
259 case R_EDX:
260 ret = entry->edx;
261 break;
263 return ret;
266 /* Find matching entry for function/index on kvm_cpuid2 struct
268 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
269 uint32_t function,
270 uint32_t index)
272 int i;
273 for (i = 0; i < cpuid->nent; ++i) {
274 if (cpuid->entries[i].function == function &&
275 cpuid->entries[i].index == index) {
276 return &cpuid->entries[i];
279 /* not found: */
280 return NULL;
283 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
284 uint32_t index, int reg)
286 struct kvm_cpuid2 *cpuid;
287 uint32_t ret = 0;
288 uint32_t cpuid_1_edx;
289 bool found = false;
291 cpuid = get_supported_cpuid(s);
293 struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
294 if (entry) {
295 found = true;
296 ret = cpuid_entry_get_reg(entry, reg);
299 /* Fixups for the data returned by KVM, below */
301 if (function == 1 && reg == R_EDX) {
302 /* KVM before 2.6.30 misreports the following features */
303 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
304 } else if (function == 1 && reg == R_ECX) {
305 /* We can set the hypervisor flag, even if KVM does not return it on
306 * GET_SUPPORTED_CPUID
308 ret |= CPUID_EXT_HYPERVISOR;
309 /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
310 * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
311 * and the irqchip is in the kernel.
313 if (kvm_irqchip_in_kernel() &&
314 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
315 ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
318 /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
319 * without the in-kernel irqchip
321 if (!kvm_irqchip_in_kernel()) {
322 ret &= ~CPUID_EXT_X2APIC;
324 } else if (function == 6 && reg == R_EAX) {
325 ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
326 } else if (function == 0x80000001 && reg == R_EDX) {
327 /* On Intel, kvm returns cpuid according to the Intel spec,
328 * so add missing bits according to the AMD spec:
330 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
331 ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
332 } else if (function == KVM_CPUID_FEATURES && reg == R_EAX) {
333 /* kvm_pv_unhalt is reported by GET_SUPPORTED_CPUID, but it can't
334 * be enabled without the in-kernel irqchip
336 if (!kvm_irqchip_in_kernel()) {
337 ret &= ~(1U << KVM_FEATURE_PV_UNHALT);
341 /* fallback for older kernels */
342 if ((function == KVM_CPUID_FEATURES) && !found) {
343 ret = get_para_features(s);
346 return ret;
349 typedef struct HWPoisonPage {
350 ram_addr_t ram_addr;
351 QLIST_ENTRY(HWPoisonPage) list;
352 } HWPoisonPage;
354 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
355 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
357 static void kvm_unpoison_all(void *param)
359 HWPoisonPage *page, *next_page;
361 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
362 QLIST_REMOVE(page, list);
363 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
364 g_free(page);
368 static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
370 HWPoisonPage *page;
372 QLIST_FOREACH(page, &hwpoison_page_list, list) {
373 if (page->ram_addr == ram_addr) {
374 return;
377 page = g_new(HWPoisonPage, 1);
378 page->ram_addr = ram_addr;
379 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
382 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
383 int *max_banks)
385 int r;
387 r = kvm_check_extension(s, KVM_CAP_MCE);
388 if (r > 0) {
389 *max_banks = r;
390 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
392 return -ENOSYS;
395 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
397 CPUState *cs = CPU(cpu);
398 CPUX86State *env = &cpu->env;
399 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
400 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
401 uint64_t mcg_status = MCG_STATUS_MCIP;
402 int flags = 0;
404 if (code == BUS_MCEERR_AR) {
405 status |= MCI_STATUS_AR | 0x134;
406 mcg_status |= MCG_STATUS_EIPV;
407 } else {
408 status |= 0xc0;
409 mcg_status |= MCG_STATUS_RIPV;
412 flags = cpu_x86_support_mca_broadcast(env) ? MCE_INJECT_BROADCAST : 0;
413 /* We need to read back the value of MSR_EXT_MCG_CTL that was set by the
414 * guest kernel back into env->mcg_ext_ctl.
416 cpu_synchronize_state(cs);
417 if (env->mcg_ext_ctl & MCG_EXT_CTL_LMCE_EN) {
418 mcg_status |= MCG_STATUS_LMCE;
419 flags = 0;
422 cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
423 (MCM_ADDR_PHYS << 6) | 0xc, flags);
426 static void hardware_memory_error(void)
428 fprintf(stderr, "Hardware memory error!\n");
429 exit(1);
432 int kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
434 X86CPU *cpu = X86_CPU(c);
435 CPUX86State *env = &cpu->env;
436 ram_addr_t ram_addr;
437 hwaddr paddr;
439 if ((env->mcg_cap & MCG_SER_P) && addr
440 && (code == BUS_MCEERR_AR || code == BUS_MCEERR_AO)) {
441 ram_addr = qemu_ram_addr_from_host(addr);
442 if (ram_addr == RAM_ADDR_INVALID ||
443 !kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
444 fprintf(stderr, "Hardware memory error for memory used by "
445 "QEMU itself instead of guest system!\n");
446 /* Hope we are lucky for AO MCE */
447 if (code == BUS_MCEERR_AO) {
448 return 0;
449 } else {
450 hardware_memory_error();
453 kvm_hwpoison_page_add(ram_addr);
454 kvm_mce_inject(cpu, paddr, code);
455 } else {
456 if (code == BUS_MCEERR_AO) {
457 return 0;
458 } else if (code == BUS_MCEERR_AR) {
459 hardware_memory_error();
460 } else {
461 return 1;
464 return 0;
467 int kvm_arch_on_sigbus(int code, void *addr)
469 X86CPU *cpu = X86_CPU(first_cpu);
471 if ((cpu->env.mcg_cap & MCG_SER_P) && addr && code == BUS_MCEERR_AO) {
472 ram_addr_t ram_addr;
473 hwaddr paddr;
475 /* Hope we are lucky for AO MCE */
476 ram_addr = qemu_ram_addr_from_host(addr);
477 if (ram_addr == RAM_ADDR_INVALID ||
478 !kvm_physical_memory_addr_from_host(first_cpu->kvm_state,
479 addr, &paddr)) {
480 fprintf(stderr, "Hardware memory error for memory used by "
481 "QEMU itself instead of guest system!: %p\n", addr);
482 return 0;
484 kvm_hwpoison_page_add(ram_addr);
485 kvm_mce_inject(X86_CPU(first_cpu), paddr, code);
486 } else {
487 if (code == BUS_MCEERR_AO) {
488 return 0;
489 } else if (code == BUS_MCEERR_AR) {
490 hardware_memory_error();
491 } else {
492 return 1;
495 return 0;
498 static int kvm_inject_mce_oldstyle(X86CPU *cpu)
500 CPUX86State *env = &cpu->env;
502 if (!kvm_has_vcpu_events() && env->exception_injected == EXCP12_MCHK) {
503 unsigned int bank, bank_num = env->mcg_cap & 0xff;
504 struct kvm_x86_mce mce;
506 env->exception_injected = -1;
509 * There must be at least one bank in use if an MCE is pending.
510 * Find it and use its values for the event injection.
512 for (bank = 0; bank < bank_num; bank++) {
513 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
514 break;
517 assert(bank < bank_num);
519 mce.bank = bank;
520 mce.status = env->mce_banks[bank * 4 + 1];
521 mce.mcg_status = env->mcg_status;
522 mce.addr = env->mce_banks[bank * 4 + 2];
523 mce.misc = env->mce_banks[bank * 4 + 3];
525 return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
527 return 0;
530 static void cpu_update_state(void *opaque, int running, RunState state)
532 CPUX86State *env = opaque;
534 if (running) {
535 env->tsc_valid = false;
539 unsigned long kvm_arch_vcpu_id(CPUState *cs)
541 X86CPU *cpu = X86_CPU(cs);
542 return cpu->apic_id;
545 #ifndef KVM_CPUID_SIGNATURE_NEXT
546 #define KVM_CPUID_SIGNATURE_NEXT 0x40000100
547 #endif
549 static bool hyperv_hypercall_available(X86CPU *cpu)
551 return cpu->hyperv_vapic ||
552 (cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY);
555 static bool hyperv_enabled(X86CPU *cpu)
557 CPUState *cs = CPU(cpu);
558 return kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0 &&
559 (hyperv_hypercall_available(cpu) ||
560 cpu->hyperv_time ||
561 cpu->hyperv_relaxed_timing ||
562 cpu->hyperv_crash ||
563 cpu->hyperv_reset ||
564 cpu->hyperv_vpindex ||
565 cpu->hyperv_runtime ||
566 cpu->hyperv_synic ||
567 cpu->hyperv_stimer);
570 static int kvm_arch_set_tsc_khz(CPUState *cs)
572 X86CPU *cpu = X86_CPU(cs);
573 CPUX86State *env = &cpu->env;
574 int r;
576 if (!env->tsc_khz) {
577 return 0;
580 r = kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL) ?
581 kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) :
582 -ENOTSUP;
583 if (r < 0) {
584 /* When KVM_SET_TSC_KHZ fails, it's an error only if the current
585 * TSC frequency doesn't match the one we want.
587 int cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
588 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
589 -ENOTSUP;
590 if (cur_freq <= 0 || cur_freq != env->tsc_khz) {
591 error_report("warning: TSC frequency mismatch between "
592 "VM (%" PRId64 " kHz) and host (%d kHz), "
593 "and TSC scaling unavailable",
594 env->tsc_khz, cur_freq);
595 return r;
599 return 0;
602 static int hyperv_handle_properties(CPUState *cs)
604 X86CPU *cpu = X86_CPU(cs);
605 CPUX86State *env = &cpu->env;
607 if (cpu->hyperv_relaxed_timing) {
608 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_HYPERCALL_AVAILABLE;
610 if (cpu->hyperv_vapic) {
611 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_HYPERCALL_AVAILABLE;
612 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_APIC_ACCESS_AVAILABLE;
613 has_msr_hv_vapic = true;
615 if (cpu->hyperv_time &&
616 kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) > 0) {
617 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_HYPERCALL_AVAILABLE;
618 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_TIME_REF_COUNT_AVAILABLE;
619 env->features[FEAT_HYPERV_EAX] |= 0x200;
620 has_msr_hv_tsc = true;
622 if (cpu->hyperv_crash && has_msr_hv_crash) {
623 env->features[FEAT_HYPERV_EDX] |= HV_X64_GUEST_CRASH_MSR_AVAILABLE;
625 env->features[FEAT_HYPERV_EDX] |= HV_X64_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
626 if (cpu->hyperv_reset && has_msr_hv_reset) {
627 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_RESET_AVAILABLE;
629 if (cpu->hyperv_vpindex && has_msr_hv_vpindex) {
630 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_VP_INDEX_AVAILABLE;
632 if (cpu->hyperv_runtime && has_msr_hv_runtime) {
633 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_VP_RUNTIME_AVAILABLE;
635 if (cpu->hyperv_synic) {
636 int sint;
638 if (!has_msr_hv_synic ||
639 kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_SYNIC, 0)) {
640 fprintf(stderr, "Hyper-V SynIC is not supported by kernel\n");
641 return -ENOSYS;
644 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_SYNIC_AVAILABLE;
645 env->msr_hv_synic_version = HV_SYNIC_VERSION_1;
646 for (sint = 0; sint < ARRAY_SIZE(env->msr_hv_synic_sint); sint++) {
647 env->msr_hv_synic_sint[sint] = HV_SYNIC_SINT_MASKED;
650 if (cpu->hyperv_stimer) {
651 if (!has_msr_hv_stimer) {
652 fprintf(stderr, "Hyper-V timers aren't supported by kernel\n");
653 return -ENOSYS;
655 env->features[FEAT_HYPERV_EAX] |= HV_X64_MSR_SYNTIMER_AVAILABLE;
657 return 0;
660 static Error *invtsc_mig_blocker;
662 #define KVM_MAX_CPUID_ENTRIES 100
664 int kvm_arch_init_vcpu(CPUState *cs)
666 struct {
667 struct kvm_cpuid2 cpuid;
668 struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
669 } QEMU_PACKED cpuid_data;
670 X86CPU *cpu = X86_CPU(cs);
671 CPUX86State *env = &cpu->env;
672 uint32_t limit, i, j, cpuid_i;
673 uint32_t unused;
674 struct kvm_cpuid_entry2 *c;
675 uint32_t signature[3];
676 int kvm_base = KVM_CPUID_SIGNATURE;
677 int r;
679 memset(&cpuid_data, 0, sizeof(cpuid_data));
681 cpuid_i = 0;
683 /* Paravirtualization CPUIDs */
684 if (hyperv_enabled(cpu)) {
685 c = &cpuid_data.entries[cpuid_i++];
686 c->function = HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
687 if (!cpu->hyperv_vendor_id) {
688 memcpy(signature, "Microsoft Hv", 12);
689 } else {
690 size_t len = strlen(cpu->hyperv_vendor_id);
692 if (len > 12) {
693 error_report("hv-vendor-id truncated to 12 characters");
694 len = 12;
696 memset(signature, 0, 12);
697 memcpy(signature, cpu->hyperv_vendor_id, len);
699 c->eax = HYPERV_CPUID_MIN;
700 c->ebx = signature[0];
701 c->ecx = signature[1];
702 c->edx = signature[2];
704 c = &cpuid_data.entries[cpuid_i++];
705 c->function = HYPERV_CPUID_INTERFACE;
706 memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
707 c->eax = signature[0];
708 c->ebx = 0;
709 c->ecx = 0;
710 c->edx = 0;
712 c = &cpuid_data.entries[cpuid_i++];
713 c->function = HYPERV_CPUID_VERSION;
714 c->eax = 0x00001bbc;
715 c->ebx = 0x00060001;
717 c = &cpuid_data.entries[cpuid_i++];
718 c->function = HYPERV_CPUID_FEATURES;
719 r = hyperv_handle_properties(cs);
720 if (r) {
721 return r;
723 c->eax = env->features[FEAT_HYPERV_EAX];
724 c->ebx = env->features[FEAT_HYPERV_EBX];
725 c->edx = env->features[FEAT_HYPERV_EDX];
727 c = &cpuid_data.entries[cpuid_i++];
728 c->function = HYPERV_CPUID_ENLIGHTMENT_INFO;
729 if (cpu->hyperv_relaxed_timing) {
730 c->eax |= HV_X64_RELAXED_TIMING_RECOMMENDED;
732 if (has_msr_hv_vapic) {
733 c->eax |= HV_X64_APIC_ACCESS_RECOMMENDED;
735 c->ebx = cpu->hyperv_spinlock_attempts;
737 c = &cpuid_data.entries[cpuid_i++];
738 c->function = HYPERV_CPUID_IMPLEMENT_LIMITS;
739 c->eax = 0x40;
740 c->ebx = 0x40;
742 kvm_base = KVM_CPUID_SIGNATURE_NEXT;
743 has_msr_hv_hypercall = true;
746 if (cpu->expose_kvm) {
747 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
748 c = &cpuid_data.entries[cpuid_i++];
749 c->function = KVM_CPUID_SIGNATURE | kvm_base;
750 c->eax = KVM_CPUID_FEATURES | kvm_base;
751 c->ebx = signature[0];
752 c->ecx = signature[1];
753 c->edx = signature[2];
755 c = &cpuid_data.entries[cpuid_i++];
756 c->function = KVM_CPUID_FEATURES | kvm_base;
757 c->eax = env->features[FEAT_KVM];
759 has_msr_async_pf_en = c->eax & (1 << KVM_FEATURE_ASYNC_PF);
761 has_msr_pv_eoi_en = c->eax & (1 << KVM_FEATURE_PV_EOI);
763 has_msr_kvm_steal_time = c->eax & (1 << KVM_FEATURE_STEAL_TIME);
766 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
768 for (i = 0; i <= limit; i++) {
769 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
770 fprintf(stderr, "unsupported level value: 0x%x\n", limit);
771 abort();
773 c = &cpuid_data.entries[cpuid_i++];
775 switch (i) {
776 case 2: {
777 /* Keep reading function 2 till all the input is received */
778 int times;
780 c->function = i;
781 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
782 KVM_CPUID_FLAG_STATE_READ_NEXT;
783 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
784 times = c->eax & 0xff;
786 for (j = 1; j < times; ++j) {
787 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
788 fprintf(stderr, "cpuid_data is full, no space for "
789 "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
790 abort();
792 c = &cpuid_data.entries[cpuid_i++];
793 c->function = i;
794 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
795 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
797 break;
799 case 4:
800 case 0xb:
801 case 0xd:
802 for (j = 0; ; j++) {
803 if (i == 0xd && j == 64) {
804 break;
806 c->function = i;
807 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
808 c->index = j;
809 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
811 if (i == 4 && c->eax == 0) {
812 break;
814 if (i == 0xb && !(c->ecx & 0xff00)) {
815 break;
817 if (i == 0xd && c->eax == 0) {
818 continue;
820 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
821 fprintf(stderr, "cpuid_data is full, no space for "
822 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
823 abort();
825 c = &cpuid_data.entries[cpuid_i++];
827 break;
828 default:
829 c->function = i;
830 c->flags = 0;
831 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
832 break;
836 if (limit >= 0x0a) {
837 uint32_t ver;
839 cpu_x86_cpuid(env, 0x0a, 0, &ver, &unused, &unused, &unused);
840 if ((ver & 0xff) > 0) {
841 has_msr_architectural_pmu = true;
842 num_architectural_pmu_counters = (ver & 0xff00) >> 8;
844 /* Shouldn't be more than 32, since that's the number of bits
845 * available in EBX to tell us _which_ counters are available.
846 * Play it safe.
848 if (num_architectural_pmu_counters > MAX_GP_COUNTERS) {
849 num_architectural_pmu_counters = MAX_GP_COUNTERS;
854 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
856 for (i = 0x80000000; i <= limit; i++) {
857 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
858 fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
859 abort();
861 c = &cpuid_data.entries[cpuid_i++];
863 c->function = i;
864 c->flags = 0;
865 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
868 /* Call Centaur's CPUID instructions they are supported. */
869 if (env->cpuid_xlevel2 > 0) {
870 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
872 for (i = 0xC0000000; i <= limit; i++) {
873 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
874 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
875 abort();
877 c = &cpuid_data.entries[cpuid_i++];
879 c->function = i;
880 c->flags = 0;
881 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
885 cpuid_data.cpuid.nent = cpuid_i;
887 if (((env->cpuid_version >> 8)&0xF) >= 6
888 && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
889 (CPUID_MCE | CPUID_MCA)
890 && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
891 uint64_t mcg_cap, unsupported_caps;
892 int banks;
893 int ret;
895 ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
896 if (ret < 0) {
897 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
898 return ret;
901 if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
902 error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
903 (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
904 return -ENOTSUP;
907 unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
908 if (unsupported_caps) {
909 if (unsupported_caps & MCG_LMCE_P) {
910 error_report("kvm: LMCE not supported");
911 return -ENOTSUP;
913 error_report("warning: Unsupported MCG_CAP bits: 0x%" PRIx64,
914 unsupported_caps);
917 env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
918 ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
919 if (ret < 0) {
920 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
921 return ret;
925 qemu_add_vm_change_state_handler(cpu_update_state, env);
927 c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
928 if (c) {
929 has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
930 !!(c->ecx & CPUID_EXT_SMX);
933 if (env->mcg_cap & MCG_LMCE_P) {
934 has_msr_mcg_ext_ctl = has_msr_feature_control = true;
937 c = cpuid_find_entry(&cpuid_data.cpuid, 0x80000007, 0);
938 if (c && (c->edx & 1<<8) && invtsc_mig_blocker == NULL) {
939 /* for migration */
940 error_setg(&invtsc_mig_blocker,
941 "State blocked by non-migratable CPU device"
942 " (invtsc flag)");
943 migrate_add_blocker(invtsc_mig_blocker);
944 /* for savevm */
945 vmstate_x86_cpu.unmigratable = 1;
948 cpuid_data.cpuid.padding = 0;
949 r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
950 if (r) {
951 return r;
954 r = kvm_arch_set_tsc_khz(cs);
955 if (r < 0) {
956 return r;
959 /* vcpu's TSC frequency is either specified by user, or following
960 * the value used by KVM if the former is not present. In the
961 * latter case, we query it from KVM and record in env->tsc_khz,
962 * so that vcpu's TSC frequency can be migrated later via this field.
964 if (!env->tsc_khz) {
965 r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
966 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
967 -ENOTSUP;
968 if (r > 0) {
969 env->tsc_khz = r;
973 if (has_xsave) {
974 env->kvm_xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
976 cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
978 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
979 has_msr_mtrr = true;
981 if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
982 has_msr_tsc_aux = false;
985 return 0;
988 void kvm_arch_reset_vcpu(X86CPU *cpu)
990 CPUX86State *env = &cpu->env;
992 env->exception_injected = -1;
993 env->interrupt_injected = -1;
994 env->xcr0 = 1;
995 if (kvm_irqchip_in_kernel()) {
996 env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
997 KVM_MP_STATE_UNINITIALIZED;
998 } else {
999 env->mp_state = KVM_MP_STATE_RUNNABLE;
1003 void kvm_arch_do_init_vcpu(X86CPU *cpu)
1005 CPUX86State *env = &cpu->env;
1007 /* APs get directly into wait-for-SIPI state. */
1008 if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
1009 env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
1013 static int kvm_get_supported_msrs(KVMState *s)
1015 static int kvm_supported_msrs;
1016 int ret = 0;
1018 /* first time */
1019 if (kvm_supported_msrs == 0) {
1020 struct kvm_msr_list msr_list, *kvm_msr_list;
1022 kvm_supported_msrs = -1;
1024 /* Obtain MSR list from KVM. These are the MSRs that we must
1025 * save/restore */
1026 msr_list.nmsrs = 0;
1027 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
1028 if (ret < 0 && ret != -E2BIG) {
1029 return ret;
1031 /* Old kernel modules had a bug and could write beyond the provided
1032 memory. Allocate at least a safe amount of 1K. */
1033 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
1034 msr_list.nmsrs *
1035 sizeof(msr_list.indices[0])));
1037 kvm_msr_list->nmsrs = msr_list.nmsrs;
1038 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
1039 if (ret >= 0) {
1040 int i;
1042 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
1043 if (kvm_msr_list->indices[i] == MSR_STAR) {
1044 has_msr_star = true;
1045 continue;
1047 if (kvm_msr_list->indices[i] == MSR_VM_HSAVE_PA) {
1048 has_msr_hsave_pa = true;
1049 continue;
1051 if (kvm_msr_list->indices[i] == MSR_TSC_AUX) {
1052 has_msr_tsc_aux = true;
1053 continue;
1055 if (kvm_msr_list->indices[i] == MSR_TSC_ADJUST) {
1056 has_msr_tsc_adjust = true;
1057 continue;
1059 if (kvm_msr_list->indices[i] == MSR_IA32_TSCDEADLINE) {
1060 has_msr_tsc_deadline = true;
1061 continue;
1063 if (kvm_msr_list->indices[i] == MSR_IA32_SMBASE) {
1064 has_msr_smbase = true;
1065 continue;
1067 if (kvm_msr_list->indices[i] == MSR_IA32_MISC_ENABLE) {
1068 has_msr_misc_enable = true;
1069 continue;
1071 if (kvm_msr_list->indices[i] == MSR_IA32_BNDCFGS) {
1072 has_msr_bndcfgs = true;
1073 continue;
1075 if (kvm_msr_list->indices[i] == MSR_IA32_XSS) {
1076 has_msr_xss = true;
1077 continue;
1079 if (kvm_msr_list->indices[i] == HV_X64_MSR_CRASH_CTL) {
1080 has_msr_hv_crash = true;
1081 continue;
1083 if (kvm_msr_list->indices[i] == HV_X64_MSR_RESET) {
1084 has_msr_hv_reset = true;
1085 continue;
1087 if (kvm_msr_list->indices[i] == HV_X64_MSR_VP_INDEX) {
1088 has_msr_hv_vpindex = true;
1089 continue;
1091 if (kvm_msr_list->indices[i] == HV_X64_MSR_VP_RUNTIME) {
1092 has_msr_hv_runtime = true;
1093 continue;
1095 if (kvm_msr_list->indices[i] == HV_X64_MSR_SCONTROL) {
1096 has_msr_hv_synic = true;
1097 continue;
1099 if (kvm_msr_list->indices[i] == HV_X64_MSR_STIMER0_CONFIG) {
1100 has_msr_hv_stimer = true;
1101 continue;
1106 g_free(kvm_msr_list);
1109 return ret;
1112 static Notifier smram_machine_done;
1113 static KVMMemoryListener smram_listener;
1114 static AddressSpace smram_address_space;
1115 static MemoryRegion smram_as_root;
1116 static MemoryRegion smram_as_mem;
1118 static void register_smram_listener(Notifier *n, void *unused)
1120 MemoryRegion *smram =
1121 (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
1123 /* Outer container... */
1124 memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
1125 memory_region_set_enabled(&smram_as_root, true);
1127 /* ... with two regions inside: normal system memory with low
1128 * priority, and...
1130 memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
1131 get_system_memory(), 0, ~0ull);
1132 memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
1133 memory_region_set_enabled(&smram_as_mem, true);
1135 if (smram) {
1136 /* ... SMRAM with higher priority */
1137 memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
1138 memory_region_set_enabled(smram, true);
1141 address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
1142 kvm_memory_listener_register(kvm_state, &smram_listener,
1143 &smram_address_space, 1);
1146 int kvm_arch_init(MachineState *ms, KVMState *s)
1148 uint64_t identity_base = 0xfffbc000;
1149 uint64_t shadow_mem;
1150 int ret;
1151 struct utsname utsname;
1153 #ifdef KVM_CAP_XSAVE
1154 has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1155 #endif
1157 #ifdef KVM_CAP_XCRS
1158 has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1159 #endif
1161 #ifdef KVM_CAP_PIT_STATE2
1162 has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1163 #endif
1165 ret = kvm_get_supported_msrs(s);
1166 if (ret < 0) {
1167 return ret;
1170 uname(&utsname);
1171 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
1174 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
1175 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
1176 * Since these must be part of guest physical memory, we need to allocate
1177 * them, both by setting their start addresses in the kernel and by
1178 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
1180 * Older KVM versions may not support setting the identity map base. In
1181 * that case we need to stick with the default, i.e. a 256K maximum BIOS
1182 * size.
1184 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
1185 /* Allows up to 16M BIOSes. */
1186 identity_base = 0xfeffc000;
1188 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
1189 if (ret < 0) {
1190 return ret;
1194 /* Set TSS base one page after EPT identity map. */
1195 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
1196 if (ret < 0) {
1197 return ret;
1200 /* Tell fw_cfg to notify the BIOS to reserve the range. */
1201 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
1202 if (ret < 0) {
1203 fprintf(stderr, "e820_add_entry() table is full\n");
1204 return ret;
1206 qemu_register_reset(kvm_unpoison_all, NULL);
1208 shadow_mem = machine_kvm_shadow_mem(ms);
1209 if (shadow_mem != -1) {
1210 shadow_mem /= 4096;
1211 ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
1212 if (ret < 0) {
1213 return ret;
1217 if (kvm_check_extension(s, KVM_CAP_X86_SMM)) {
1218 smram_machine_done.notify = register_smram_listener;
1219 qemu_add_machine_init_done_notifier(&smram_machine_done);
1221 return 0;
1224 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1226 lhs->selector = rhs->selector;
1227 lhs->base = rhs->base;
1228 lhs->limit = rhs->limit;
1229 lhs->type = 3;
1230 lhs->present = 1;
1231 lhs->dpl = 3;
1232 lhs->db = 0;
1233 lhs->s = 1;
1234 lhs->l = 0;
1235 lhs->g = 0;
1236 lhs->avl = 0;
1237 lhs->unusable = 0;
1240 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1242 unsigned flags = rhs->flags;
1243 lhs->selector = rhs->selector;
1244 lhs->base = rhs->base;
1245 lhs->limit = rhs->limit;
1246 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
1247 lhs->present = (flags & DESC_P_MASK) != 0;
1248 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
1249 lhs->db = (flags >> DESC_B_SHIFT) & 1;
1250 lhs->s = (flags & DESC_S_MASK) != 0;
1251 lhs->l = (flags >> DESC_L_SHIFT) & 1;
1252 lhs->g = (flags & DESC_G_MASK) != 0;
1253 lhs->avl = (flags & DESC_AVL_MASK) != 0;
1254 lhs->unusable = !lhs->present;
1255 lhs->padding = 0;
1258 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
1260 lhs->selector = rhs->selector;
1261 lhs->base = rhs->base;
1262 lhs->limit = rhs->limit;
1263 if (rhs->unusable) {
1264 lhs->flags = 0;
1265 } else {
1266 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
1267 (rhs->present * DESC_P_MASK) |
1268 (rhs->dpl << DESC_DPL_SHIFT) |
1269 (rhs->db << DESC_B_SHIFT) |
1270 (rhs->s * DESC_S_MASK) |
1271 (rhs->l << DESC_L_SHIFT) |
1272 (rhs->g * DESC_G_MASK) |
1273 (rhs->avl * DESC_AVL_MASK);
1277 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
1279 if (set) {
1280 *kvm_reg = *qemu_reg;
1281 } else {
1282 *qemu_reg = *kvm_reg;
1286 static int kvm_getput_regs(X86CPU *cpu, int set)
1288 CPUX86State *env = &cpu->env;
1289 struct kvm_regs regs;
1290 int ret = 0;
1292 if (!set) {
1293 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
1294 if (ret < 0) {
1295 return ret;
1299 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
1300 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
1301 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
1302 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
1303 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
1304 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
1305 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
1306 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
1307 #ifdef TARGET_X86_64
1308 kvm_getput_reg(&regs.r8, &env->regs[8], set);
1309 kvm_getput_reg(&regs.r9, &env->regs[9], set);
1310 kvm_getput_reg(&regs.r10, &env->regs[10], set);
1311 kvm_getput_reg(&regs.r11, &env->regs[11], set);
1312 kvm_getput_reg(&regs.r12, &env->regs[12], set);
1313 kvm_getput_reg(&regs.r13, &env->regs[13], set);
1314 kvm_getput_reg(&regs.r14, &env->regs[14], set);
1315 kvm_getput_reg(&regs.r15, &env->regs[15], set);
1316 #endif
1318 kvm_getput_reg(&regs.rflags, &env->eflags, set);
1319 kvm_getput_reg(&regs.rip, &env->eip, set);
1321 if (set) {
1322 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
1325 return ret;
1328 static int kvm_put_fpu(X86CPU *cpu)
1330 CPUX86State *env = &cpu->env;
1331 struct kvm_fpu fpu;
1332 int i;
1334 memset(&fpu, 0, sizeof fpu);
1335 fpu.fsw = env->fpus & ~(7 << 11);
1336 fpu.fsw |= (env->fpstt & 7) << 11;
1337 fpu.fcw = env->fpuc;
1338 fpu.last_opcode = env->fpop;
1339 fpu.last_ip = env->fpip;
1340 fpu.last_dp = env->fpdp;
1341 for (i = 0; i < 8; ++i) {
1342 fpu.ftwx |= (!env->fptags[i]) << i;
1344 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
1345 for (i = 0; i < CPU_NB_REGS; i++) {
1346 stq_p(&fpu.xmm[i][0], env->xmm_regs[i].ZMM_Q(0));
1347 stq_p(&fpu.xmm[i][8], env->xmm_regs[i].ZMM_Q(1));
1349 fpu.mxcsr = env->mxcsr;
1351 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
1354 #define XSAVE_FCW_FSW 0
1355 #define XSAVE_FTW_FOP 1
1356 #define XSAVE_CWD_RIP 2
1357 #define XSAVE_CWD_RDP 4
1358 #define XSAVE_MXCSR 6
1359 #define XSAVE_ST_SPACE 8
1360 #define XSAVE_XMM_SPACE 40
1361 #define XSAVE_XSTATE_BV 128
1362 #define XSAVE_YMMH_SPACE 144
1363 #define XSAVE_BNDREGS 240
1364 #define XSAVE_BNDCSR 256
1365 #define XSAVE_OPMASK 272
1366 #define XSAVE_ZMM_Hi256 288
1367 #define XSAVE_Hi16_ZMM 416
1368 #define XSAVE_PKRU 672
1370 #define XSAVE_BYTE_OFFSET(word_offset) \
1371 ((word_offset) * sizeof(((struct kvm_xsave *)0)->region[0]))
1373 #define ASSERT_OFFSET(word_offset, field) \
1374 QEMU_BUILD_BUG_ON(XSAVE_BYTE_OFFSET(word_offset) != \
1375 offsetof(X86XSaveArea, field))
1377 ASSERT_OFFSET(XSAVE_FCW_FSW, legacy.fcw);
1378 ASSERT_OFFSET(XSAVE_FTW_FOP, legacy.ftw);
1379 ASSERT_OFFSET(XSAVE_CWD_RIP, legacy.fpip);
1380 ASSERT_OFFSET(XSAVE_CWD_RDP, legacy.fpdp);
1381 ASSERT_OFFSET(XSAVE_MXCSR, legacy.mxcsr);
1382 ASSERT_OFFSET(XSAVE_ST_SPACE, legacy.fpregs);
1383 ASSERT_OFFSET(XSAVE_XMM_SPACE, legacy.xmm_regs);
1384 ASSERT_OFFSET(XSAVE_XSTATE_BV, header.xstate_bv);
1385 ASSERT_OFFSET(XSAVE_YMMH_SPACE, avx_state);
1386 ASSERT_OFFSET(XSAVE_BNDREGS, bndreg_state);
1387 ASSERT_OFFSET(XSAVE_BNDCSR, bndcsr_state);
1388 ASSERT_OFFSET(XSAVE_OPMASK, opmask_state);
1389 ASSERT_OFFSET(XSAVE_ZMM_Hi256, zmm_hi256_state);
1390 ASSERT_OFFSET(XSAVE_Hi16_ZMM, hi16_zmm_state);
1391 ASSERT_OFFSET(XSAVE_PKRU, pkru_state);
1393 static int kvm_put_xsave(X86CPU *cpu)
1395 CPUX86State *env = &cpu->env;
1396 X86XSaveArea *xsave = env->kvm_xsave_buf;
1397 uint16_t cwd, swd, twd;
1398 int i;
1400 if (!has_xsave) {
1401 return kvm_put_fpu(cpu);
1404 memset(xsave, 0, sizeof(struct kvm_xsave));
1405 twd = 0;
1406 swd = env->fpus & ~(7 << 11);
1407 swd |= (env->fpstt & 7) << 11;
1408 cwd = env->fpuc;
1409 for (i = 0; i < 8; ++i) {
1410 twd |= (!env->fptags[i]) << i;
1412 xsave->legacy.fcw = cwd;
1413 xsave->legacy.fsw = swd;
1414 xsave->legacy.ftw = twd;
1415 xsave->legacy.fpop = env->fpop;
1416 xsave->legacy.fpip = env->fpip;
1417 xsave->legacy.fpdp = env->fpdp;
1418 memcpy(&xsave->legacy.fpregs, env->fpregs,
1419 sizeof env->fpregs);
1420 xsave->legacy.mxcsr = env->mxcsr;
1421 xsave->header.xstate_bv = env->xstate_bv;
1422 memcpy(&xsave->bndreg_state.bnd_regs, env->bnd_regs,
1423 sizeof env->bnd_regs);
1424 xsave->bndcsr_state.bndcsr = env->bndcs_regs;
1425 memcpy(&xsave->opmask_state.opmask_regs, env->opmask_regs,
1426 sizeof env->opmask_regs);
1428 for (i = 0; i < CPU_NB_REGS; i++) {
1429 uint8_t *xmm = xsave->legacy.xmm_regs[i];
1430 uint8_t *ymmh = xsave->avx_state.ymmh[i];
1431 uint8_t *zmmh = xsave->zmm_hi256_state.zmm_hi256[i];
1432 stq_p(xmm, env->xmm_regs[i].ZMM_Q(0));
1433 stq_p(xmm+8, env->xmm_regs[i].ZMM_Q(1));
1434 stq_p(ymmh, env->xmm_regs[i].ZMM_Q(2));
1435 stq_p(ymmh+8, env->xmm_regs[i].ZMM_Q(3));
1436 stq_p(zmmh, env->xmm_regs[i].ZMM_Q(4));
1437 stq_p(zmmh+8, env->xmm_regs[i].ZMM_Q(5));
1438 stq_p(zmmh+16, env->xmm_regs[i].ZMM_Q(6));
1439 stq_p(zmmh+24, env->xmm_regs[i].ZMM_Q(7));
1442 #ifdef TARGET_X86_64
1443 memcpy(&xsave->hi16_zmm_state.hi16_zmm, &env->xmm_regs[16],
1444 16 * sizeof env->xmm_regs[16]);
1445 memcpy(&xsave->pkru_state, &env->pkru, sizeof env->pkru);
1446 #endif
1447 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
1450 static int kvm_put_xcrs(X86CPU *cpu)
1452 CPUX86State *env = &cpu->env;
1453 struct kvm_xcrs xcrs = {};
1455 if (!has_xcrs) {
1456 return 0;
1459 xcrs.nr_xcrs = 1;
1460 xcrs.flags = 0;
1461 xcrs.xcrs[0].xcr = 0;
1462 xcrs.xcrs[0].value = env->xcr0;
1463 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
1466 static int kvm_put_sregs(X86CPU *cpu)
1468 CPUX86State *env = &cpu->env;
1469 struct kvm_sregs sregs;
1471 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
1472 if (env->interrupt_injected >= 0) {
1473 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
1474 (uint64_t)1 << (env->interrupt_injected % 64);
1477 if ((env->eflags & VM_MASK)) {
1478 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
1479 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
1480 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
1481 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
1482 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
1483 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
1484 } else {
1485 set_seg(&sregs.cs, &env->segs[R_CS]);
1486 set_seg(&sregs.ds, &env->segs[R_DS]);
1487 set_seg(&sregs.es, &env->segs[R_ES]);
1488 set_seg(&sregs.fs, &env->segs[R_FS]);
1489 set_seg(&sregs.gs, &env->segs[R_GS]);
1490 set_seg(&sregs.ss, &env->segs[R_SS]);
1493 set_seg(&sregs.tr, &env->tr);
1494 set_seg(&sregs.ldt, &env->ldt);
1496 sregs.idt.limit = env->idt.limit;
1497 sregs.idt.base = env->idt.base;
1498 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
1499 sregs.gdt.limit = env->gdt.limit;
1500 sregs.gdt.base = env->gdt.base;
1501 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
1503 sregs.cr0 = env->cr[0];
1504 sregs.cr2 = env->cr[2];
1505 sregs.cr3 = env->cr[3];
1506 sregs.cr4 = env->cr[4];
1508 sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
1509 sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
1511 sregs.efer = env->efer;
1513 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
1516 static void kvm_msr_buf_reset(X86CPU *cpu)
1518 memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
1521 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
1523 struct kvm_msrs *msrs = cpu->kvm_msr_buf;
1524 void *limit = ((void *)msrs) + MSR_BUF_SIZE;
1525 struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
1527 assert((void *)(entry + 1) <= limit);
1529 entry->index = index;
1530 entry->reserved = 0;
1531 entry->data = value;
1532 msrs->nmsrs++;
1535 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
1537 CPUX86State *env = &cpu->env;
1538 int ret;
1540 if (!has_msr_tsc_deadline) {
1541 return 0;
1544 kvm_msr_buf_reset(cpu);
1545 kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
1547 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1548 if (ret < 0) {
1549 return ret;
1552 assert(ret == 1);
1553 return 0;
1557 * Provide a separate write service for the feature control MSR in order to
1558 * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
1559 * before writing any other state because forcibly leaving nested mode
1560 * invalidates the VCPU state.
1562 static int kvm_put_msr_feature_control(X86CPU *cpu)
1564 int ret;
1566 if (!has_msr_feature_control) {
1567 return 0;
1570 kvm_msr_buf_reset(cpu);
1571 kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL,
1572 cpu->env.msr_ia32_feature_control);
1574 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1575 if (ret < 0) {
1576 return ret;
1579 assert(ret == 1);
1580 return 0;
1583 static int kvm_put_msrs(X86CPU *cpu, int level)
1585 CPUX86State *env = &cpu->env;
1586 int i;
1587 int ret;
1589 kvm_msr_buf_reset(cpu);
1591 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
1592 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
1593 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
1594 kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
1595 if (has_msr_star) {
1596 kvm_msr_entry_add(cpu, MSR_STAR, env->star);
1598 if (has_msr_hsave_pa) {
1599 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
1601 if (has_msr_tsc_aux) {
1602 kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
1604 if (has_msr_tsc_adjust) {
1605 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
1607 if (has_msr_misc_enable) {
1608 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
1609 env->msr_ia32_misc_enable);
1611 if (has_msr_smbase) {
1612 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
1614 if (has_msr_bndcfgs) {
1615 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
1617 if (has_msr_xss) {
1618 kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
1620 #ifdef TARGET_X86_64
1621 if (lm_capable_kernel) {
1622 kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
1623 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
1624 kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
1625 kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
1627 #endif
1629 * The following MSRs have side effects on the guest or are too heavy
1630 * for normal writeback. Limit them to reset or full state updates.
1632 if (level >= KVM_PUT_RESET_STATE) {
1633 kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
1634 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
1635 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
1636 if (has_msr_async_pf_en) {
1637 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
1639 if (has_msr_pv_eoi_en) {
1640 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
1642 if (has_msr_kvm_steal_time) {
1643 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
1645 if (has_msr_architectural_pmu) {
1646 /* Stop the counter. */
1647 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
1648 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
1650 /* Set the counter values. */
1651 for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
1652 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
1653 env->msr_fixed_counters[i]);
1655 for (i = 0; i < num_architectural_pmu_counters; i++) {
1656 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
1657 env->msr_gp_counters[i]);
1658 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
1659 env->msr_gp_evtsel[i]);
1661 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
1662 env->msr_global_status);
1663 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1664 env->msr_global_ovf_ctrl);
1666 /* Now start the PMU. */
1667 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
1668 env->msr_fixed_ctr_ctrl);
1669 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
1670 env->msr_global_ctrl);
1672 if (has_msr_hv_hypercall) {
1673 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
1674 env->msr_hv_guest_os_id);
1675 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
1676 env->msr_hv_hypercall);
1678 if (has_msr_hv_vapic) {
1679 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
1680 env->msr_hv_vapic);
1682 if (has_msr_hv_tsc) {
1683 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, env->msr_hv_tsc);
1685 if (has_msr_hv_crash) {
1686 int j;
1688 for (j = 0; j < HV_X64_MSR_CRASH_PARAMS; j++)
1689 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
1690 env->msr_hv_crash_params[j]);
1692 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL,
1693 HV_X64_MSR_CRASH_CTL_NOTIFY);
1695 if (has_msr_hv_runtime) {
1696 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
1698 if (cpu->hyperv_synic) {
1699 int j;
1701 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
1702 env->msr_hv_synic_control);
1703 kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION,
1704 env->msr_hv_synic_version);
1705 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
1706 env->msr_hv_synic_evt_page);
1707 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
1708 env->msr_hv_synic_msg_page);
1710 for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
1711 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
1712 env->msr_hv_synic_sint[j]);
1715 if (has_msr_hv_stimer) {
1716 int j;
1718 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
1719 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
1720 env->msr_hv_stimer_config[j]);
1723 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
1724 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
1725 env->msr_hv_stimer_count[j]);
1728 if (has_msr_mtrr) {
1729 uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
1731 kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
1732 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
1733 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
1734 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
1735 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
1736 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
1737 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
1738 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
1739 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
1740 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
1741 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
1742 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
1743 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
1744 /* The CPU GPs if we write to a bit above the physical limit of
1745 * the host CPU (and KVM emulates that)
1747 uint64_t mask = env->mtrr_var[i].mask;
1748 mask &= phys_mask;
1750 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
1751 env->mtrr_var[i].base);
1752 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
1756 /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
1757 * kvm_put_msr_feature_control. */
1759 if (env->mcg_cap) {
1760 int i;
1762 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
1763 kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
1764 if (has_msr_mcg_ext_ctl) {
1765 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
1767 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1768 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
1772 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1773 if (ret < 0) {
1774 return ret;
1777 assert(ret == cpu->kvm_msr_buf->nmsrs);
1778 return 0;
1782 static int kvm_get_fpu(X86CPU *cpu)
1784 CPUX86State *env = &cpu->env;
1785 struct kvm_fpu fpu;
1786 int i, ret;
1788 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
1789 if (ret < 0) {
1790 return ret;
1793 env->fpstt = (fpu.fsw >> 11) & 7;
1794 env->fpus = fpu.fsw;
1795 env->fpuc = fpu.fcw;
1796 env->fpop = fpu.last_opcode;
1797 env->fpip = fpu.last_ip;
1798 env->fpdp = fpu.last_dp;
1799 for (i = 0; i < 8; ++i) {
1800 env->fptags[i] = !((fpu.ftwx >> i) & 1);
1802 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
1803 for (i = 0; i < CPU_NB_REGS; i++) {
1804 env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
1805 env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
1807 env->mxcsr = fpu.mxcsr;
1809 return 0;
1812 static int kvm_get_xsave(X86CPU *cpu)
1814 CPUX86State *env = &cpu->env;
1815 X86XSaveArea *xsave = env->kvm_xsave_buf;
1816 int ret, i;
1817 uint16_t cwd, swd, twd;
1819 if (!has_xsave) {
1820 return kvm_get_fpu(cpu);
1823 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
1824 if (ret < 0) {
1825 return ret;
1828 cwd = xsave->legacy.fcw;
1829 swd = xsave->legacy.fsw;
1830 twd = xsave->legacy.ftw;
1831 env->fpop = xsave->legacy.fpop;
1832 env->fpstt = (swd >> 11) & 7;
1833 env->fpus = swd;
1834 env->fpuc = cwd;
1835 for (i = 0; i < 8; ++i) {
1836 env->fptags[i] = !((twd >> i) & 1);
1838 env->fpip = xsave->legacy.fpip;
1839 env->fpdp = xsave->legacy.fpdp;
1840 env->mxcsr = xsave->legacy.mxcsr;
1841 memcpy(env->fpregs, &xsave->legacy.fpregs,
1842 sizeof env->fpregs);
1843 env->xstate_bv = xsave->header.xstate_bv;
1844 memcpy(env->bnd_regs, &xsave->bndreg_state.bnd_regs,
1845 sizeof env->bnd_regs);
1846 env->bndcs_regs = xsave->bndcsr_state.bndcsr;
1847 memcpy(env->opmask_regs, &xsave->opmask_state.opmask_regs,
1848 sizeof env->opmask_regs);
1850 for (i = 0; i < CPU_NB_REGS; i++) {
1851 uint8_t *xmm = xsave->legacy.xmm_regs[i];
1852 uint8_t *ymmh = xsave->avx_state.ymmh[i];
1853 uint8_t *zmmh = xsave->zmm_hi256_state.zmm_hi256[i];
1854 env->xmm_regs[i].ZMM_Q(0) = ldq_p(xmm);
1855 env->xmm_regs[i].ZMM_Q(1) = ldq_p(xmm+8);
1856 env->xmm_regs[i].ZMM_Q(2) = ldq_p(ymmh);
1857 env->xmm_regs[i].ZMM_Q(3) = ldq_p(ymmh+8);
1858 env->xmm_regs[i].ZMM_Q(4) = ldq_p(zmmh);
1859 env->xmm_regs[i].ZMM_Q(5) = ldq_p(zmmh+8);
1860 env->xmm_regs[i].ZMM_Q(6) = ldq_p(zmmh+16);
1861 env->xmm_regs[i].ZMM_Q(7) = ldq_p(zmmh+24);
1864 #ifdef TARGET_X86_64
1865 memcpy(&env->xmm_regs[16], &xsave->hi16_zmm_state.hi16_zmm,
1866 16 * sizeof env->xmm_regs[16]);
1867 memcpy(&env->pkru, &xsave->pkru_state, sizeof env->pkru);
1868 #endif
1869 return 0;
1872 static int kvm_get_xcrs(X86CPU *cpu)
1874 CPUX86State *env = &cpu->env;
1875 int i, ret;
1876 struct kvm_xcrs xcrs;
1878 if (!has_xcrs) {
1879 return 0;
1882 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
1883 if (ret < 0) {
1884 return ret;
1887 for (i = 0; i < xcrs.nr_xcrs; i++) {
1888 /* Only support xcr0 now */
1889 if (xcrs.xcrs[i].xcr == 0) {
1890 env->xcr0 = xcrs.xcrs[i].value;
1891 break;
1894 return 0;
1897 static int kvm_get_sregs(X86CPU *cpu)
1899 CPUX86State *env = &cpu->env;
1900 struct kvm_sregs sregs;
1901 uint32_t hflags;
1902 int bit, i, ret;
1904 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
1905 if (ret < 0) {
1906 return ret;
1909 /* There can only be one pending IRQ set in the bitmap at a time, so try
1910 to find it and save its number instead (-1 for none). */
1911 env->interrupt_injected = -1;
1912 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
1913 if (sregs.interrupt_bitmap[i]) {
1914 bit = ctz64(sregs.interrupt_bitmap[i]);
1915 env->interrupt_injected = i * 64 + bit;
1916 break;
1920 get_seg(&env->segs[R_CS], &sregs.cs);
1921 get_seg(&env->segs[R_DS], &sregs.ds);
1922 get_seg(&env->segs[R_ES], &sregs.es);
1923 get_seg(&env->segs[R_FS], &sregs.fs);
1924 get_seg(&env->segs[R_GS], &sregs.gs);
1925 get_seg(&env->segs[R_SS], &sregs.ss);
1927 get_seg(&env->tr, &sregs.tr);
1928 get_seg(&env->ldt, &sregs.ldt);
1930 env->idt.limit = sregs.idt.limit;
1931 env->idt.base = sregs.idt.base;
1932 env->gdt.limit = sregs.gdt.limit;
1933 env->gdt.base = sregs.gdt.base;
1935 env->cr[0] = sregs.cr0;
1936 env->cr[2] = sregs.cr2;
1937 env->cr[3] = sregs.cr3;
1938 env->cr[4] = sregs.cr4;
1940 env->efer = sregs.efer;
1942 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
1944 #define HFLAG_COPY_MASK \
1945 ~( HF_CPL_MASK | HF_PE_MASK | HF_MP_MASK | HF_EM_MASK | \
1946 HF_TS_MASK | HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK | \
1947 HF_OSFXSR_MASK | HF_LMA_MASK | HF_CS32_MASK | \
1948 HF_SS32_MASK | HF_CS64_MASK | HF_ADDSEG_MASK)
1950 hflags = env->hflags & HFLAG_COPY_MASK;
1951 hflags |= (env->segs[R_SS].flags >> DESC_DPL_SHIFT) & HF_CPL_MASK;
1952 hflags |= (env->cr[0] & CR0_PE_MASK) << (HF_PE_SHIFT - CR0_PE_SHIFT);
1953 hflags |= (env->cr[0] << (HF_MP_SHIFT - CR0_MP_SHIFT)) &
1954 (HF_MP_MASK | HF_EM_MASK | HF_TS_MASK);
1955 hflags |= (env->eflags & (HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK));
1957 if (env->cr[4] & CR4_OSFXSR_MASK) {
1958 hflags |= HF_OSFXSR_MASK;
1961 if (env->efer & MSR_EFER_LMA) {
1962 hflags |= HF_LMA_MASK;
1965 if ((hflags & HF_LMA_MASK) && (env->segs[R_CS].flags & DESC_L_MASK)) {
1966 hflags |= HF_CS32_MASK | HF_SS32_MASK | HF_CS64_MASK;
1967 } else {
1968 hflags |= (env->segs[R_CS].flags & DESC_B_MASK) >>
1969 (DESC_B_SHIFT - HF_CS32_SHIFT);
1970 hflags |= (env->segs[R_SS].flags & DESC_B_MASK) >>
1971 (DESC_B_SHIFT - HF_SS32_SHIFT);
1972 if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK) ||
1973 !(hflags & HF_CS32_MASK)) {
1974 hflags |= HF_ADDSEG_MASK;
1975 } else {
1976 hflags |= ((env->segs[R_DS].base | env->segs[R_ES].base |
1977 env->segs[R_SS].base) != 0) << HF_ADDSEG_SHIFT;
1980 env->hflags = hflags;
1982 return 0;
1985 static int kvm_get_msrs(X86CPU *cpu)
1987 CPUX86State *env = &cpu->env;
1988 struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
1989 int ret, i;
1990 uint64_t mtrr_top_bits;
1992 kvm_msr_buf_reset(cpu);
1994 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
1995 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
1996 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
1997 kvm_msr_entry_add(cpu, MSR_PAT, 0);
1998 if (has_msr_star) {
1999 kvm_msr_entry_add(cpu, MSR_STAR, 0);
2001 if (has_msr_hsave_pa) {
2002 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
2004 if (has_msr_tsc_aux) {
2005 kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
2007 if (has_msr_tsc_adjust) {
2008 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
2010 if (has_msr_tsc_deadline) {
2011 kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
2013 if (has_msr_misc_enable) {
2014 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
2016 if (has_msr_smbase) {
2017 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
2019 if (has_msr_feature_control) {
2020 kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
2022 if (has_msr_bndcfgs) {
2023 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
2025 if (has_msr_xss) {
2026 kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
2030 if (!env->tsc_valid) {
2031 kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
2032 env->tsc_valid = !runstate_is_running();
2035 #ifdef TARGET_X86_64
2036 if (lm_capable_kernel) {
2037 kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
2038 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
2039 kvm_msr_entry_add(cpu, MSR_FMASK, 0);
2040 kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
2042 #endif
2043 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
2044 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
2045 if (has_msr_async_pf_en) {
2046 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
2048 if (has_msr_pv_eoi_en) {
2049 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
2051 if (has_msr_kvm_steal_time) {
2052 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
2054 if (has_msr_architectural_pmu) {
2055 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
2056 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
2057 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
2058 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
2059 for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
2060 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
2062 for (i = 0; i < num_architectural_pmu_counters; i++) {
2063 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
2064 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
2068 if (env->mcg_cap) {
2069 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
2070 kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
2071 if (has_msr_mcg_ext_ctl) {
2072 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
2074 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
2075 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
2079 if (has_msr_hv_hypercall) {
2080 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
2081 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
2083 if (has_msr_hv_vapic) {
2084 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
2086 if (has_msr_hv_tsc) {
2087 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
2089 if (has_msr_hv_crash) {
2090 int j;
2092 for (j = 0; j < HV_X64_MSR_CRASH_PARAMS; j++) {
2093 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
2096 if (has_msr_hv_runtime) {
2097 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
2099 if (cpu->hyperv_synic) {
2100 uint32_t msr;
2102 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
2103 kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, 0);
2104 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
2105 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
2106 for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
2107 kvm_msr_entry_add(cpu, msr, 0);
2110 if (has_msr_hv_stimer) {
2111 uint32_t msr;
2113 for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
2114 msr++) {
2115 kvm_msr_entry_add(cpu, msr, 0);
2118 if (has_msr_mtrr) {
2119 kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
2120 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
2121 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
2122 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
2123 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
2124 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
2125 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
2126 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
2127 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
2128 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
2129 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
2130 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
2131 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
2132 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
2133 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
2137 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
2138 if (ret < 0) {
2139 return ret;
2142 assert(ret == cpu->kvm_msr_buf->nmsrs);
2144 * MTRR masks: Each mask consists of 5 parts
2145 * a 10..0: must be zero
2146 * b 11 : valid bit
2147 * c n-1.12: actual mask bits
2148 * d 51..n: reserved must be zero
2149 * e 63.52: reserved must be zero
2151 * 'n' is the number of physical bits supported by the CPU and is
2152 * apparently always <= 52. We know our 'n' but don't know what
2153 * the destinations 'n' is; it might be smaller, in which case
2154 * it masks (c) on loading. It might be larger, in which case
2155 * we fill 'd' so that d..c is consistent irrespetive of the 'n'
2156 * we're migrating to.
2159 if (cpu->fill_mtrr_mask) {
2160 QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
2161 assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
2162 mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
2163 } else {
2164 mtrr_top_bits = 0;
2167 for (i = 0; i < ret; i++) {
2168 uint32_t index = msrs[i].index;
2169 switch (index) {
2170 case MSR_IA32_SYSENTER_CS:
2171 env->sysenter_cs = msrs[i].data;
2172 break;
2173 case MSR_IA32_SYSENTER_ESP:
2174 env->sysenter_esp = msrs[i].data;
2175 break;
2176 case MSR_IA32_SYSENTER_EIP:
2177 env->sysenter_eip = msrs[i].data;
2178 break;
2179 case MSR_PAT:
2180 env->pat = msrs[i].data;
2181 break;
2182 case MSR_STAR:
2183 env->star = msrs[i].data;
2184 break;
2185 #ifdef TARGET_X86_64
2186 case MSR_CSTAR:
2187 env->cstar = msrs[i].data;
2188 break;
2189 case MSR_KERNELGSBASE:
2190 env->kernelgsbase = msrs[i].data;
2191 break;
2192 case MSR_FMASK:
2193 env->fmask = msrs[i].data;
2194 break;
2195 case MSR_LSTAR:
2196 env->lstar = msrs[i].data;
2197 break;
2198 #endif
2199 case MSR_IA32_TSC:
2200 env->tsc = msrs[i].data;
2201 break;
2202 case MSR_TSC_AUX:
2203 env->tsc_aux = msrs[i].data;
2204 break;
2205 case MSR_TSC_ADJUST:
2206 env->tsc_adjust = msrs[i].data;
2207 break;
2208 case MSR_IA32_TSCDEADLINE:
2209 env->tsc_deadline = msrs[i].data;
2210 break;
2211 case MSR_VM_HSAVE_PA:
2212 env->vm_hsave = msrs[i].data;
2213 break;
2214 case MSR_KVM_SYSTEM_TIME:
2215 env->system_time_msr = msrs[i].data;
2216 break;
2217 case MSR_KVM_WALL_CLOCK:
2218 env->wall_clock_msr = msrs[i].data;
2219 break;
2220 case MSR_MCG_STATUS:
2221 env->mcg_status = msrs[i].data;
2222 break;
2223 case MSR_MCG_CTL:
2224 env->mcg_ctl = msrs[i].data;
2225 break;
2226 case MSR_MCG_EXT_CTL:
2227 env->mcg_ext_ctl = msrs[i].data;
2228 break;
2229 case MSR_IA32_MISC_ENABLE:
2230 env->msr_ia32_misc_enable = msrs[i].data;
2231 break;
2232 case MSR_IA32_SMBASE:
2233 env->smbase = msrs[i].data;
2234 break;
2235 case MSR_IA32_FEATURE_CONTROL:
2236 env->msr_ia32_feature_control = msrs[i].data;
2237 break;
2238 case MSR_IA32_BNDCFGS:
2239 env->msr_bndcfgs = msrs[i].data;
2240 break;
2241 case MSR_IA32_XSS:
2242 env->xss = msrs[i].data;
2243 break;
2244 default:
2245 if (msrs[i].index >= MSR_MC0_CTL &&
2246 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
2247 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
2249 break;
2250 case MSR_KVM_ASYNC_PF_EN:
2251 env->async_pf_en_msr = msrs[i].data;
2252 break;
2253 case MSR_KVM_PV_EOI_EN:
2254 env->pv_eoi_en_msr = msrs[i].data;
2255 break;
2256 case MSR_KVM_STEAL_TIME:
2257 env->steal_time_msr = msrs[i].data;
2258 break;
2259 case MSR_CORE_PERF_FIXED_CTR_CTRL:
2260 env->msr_fixed_ctr_ctrl = msrs[i].data;
2261 break;
2262 case MSR_CORE_PERF_GLOBAL_CTRL:
2263 env->msr_global_ctrl = msrs[i].data;
2264 break;
2265 case MSR_CORE_PERF_GLOBAL_STATUS:
2266 env->msr_global_status = msrs[i].data;
2267 break;
2268 case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
2269 env->msr_global_ovf_ctrl = msrs[i].data;
2270 break;
2271 case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
2272 env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
2273 break;
2274 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
2275 env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
2276 break;
2277 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
2278 env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
2279 break;
2280 case HV_X64_MSR_HYPERCALL:
2281 env->msr_hv_hypercall = msrs[i].data;
2282 break;
2283 case HV_X64_MSR_GUEST_OS_ID:
2284 env->msr_hv_guest_os_id = msrs[i].data;
2285 break;
2286 case HV_X64_MSR_APIC_ASSIST_PAGE:
2287 env->msr_hv_vapic = msrs[i].data;
2288 break;
2289 case HV_X64_MSR_REFERENCE_TSC:
2290 env->msr_hv_tsc = msrs[i].data;
2291 break;
2292 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2293 env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
2294 break;
2295 case HV_X64_MSR_VP_RUNTIME:
2296 env->msr_hv_runtime = msrs[i].data;
2297 break;
2298 case HV_X64_MSR_SCONTROL:
2299 env->msr_hv_synic_control = msrs[i].data;
2300 break;
2301 case HV_X64_MSR_SVERSION:
2302 env->msr_hv_synic_version = msrs[i].data;
2303 break;
2304 case HV_X64_MSR_SIEFP:
2305 env->msr_hv_synic_evt_page = msrs[i].data;
2306 break;
2307 case HV_X64_MSR_SIMP:
2308 env->msr_hv_synic_msg_page = msrs[i].data;
2309 break;
2310 case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
2311 env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
2312 break;
2313 case HV_X64_MSR_STIMER0_CONFIG:
2314 case HV_X64_MSR_STIMER1_CONFIG:
2315 case HV_X64_MSR_STIMER2_CONFIG:
2316 case HV_X64_MSR_STIMER3_CONFIG:
2317 env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
2318 msrs[i].data;
2319 break;
2320 case HV_X64_MSR_STIMER0_COUNT:
2321 case HV_X64_MSR_STIMER1_COUNT:
2322 case HV_X64_MSR_STIMER2_COUNT:
2323 case HV_X64_MSR_STIMER3_COUNT:
2324 env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
2325 msrs[i].data;
2326 break;
2327 case MSR_MTRRdefType:
2328 env->mtrr_deftype = msrs[i].data;
2329 break;
2330 case MSR_MTRRfix64K_00000:
2331 env->mtrr_fixed[0] = msrs[i].data;
2332 break;
2333 case MSR_MTRRfix16K_80000:
2334 env->mtrr_fixed[1] = msrs[i].data;
2335 break;
2336 case MSR_MTRRfix16K_A0000:
2337 env->mtrr_fixed[2] = msrs[i].data;
2338 break;
2339 case MSR_MTRRfix4K_C0000:
2340 env->mtrr_fixed[3] = msrs[i].data;
2341 break;
2342 case MSR_MTRRfix4K_C8000:
2343 env->mtrr_fixed[4] = msrs[i].data;
2344 break;
2345 case MSR_MTRRfix4K_D0000:
2346 env->mtrr_fixed[5] = msrs[i].data;
2347 break;
2348 case MSR_MTRRfix4K_D8000:
2349 env->mtrr_fixed[6] = msrs[i].data;
2350 break;
2351 case MSR_MTRRfix4K_E0000:
2352 env->mtrr_fixed[7] = msrs[i].data;
2353 break;
2354 case MSR_MTRRfix4K_E8000:
2355 env->mtrr_fixed[8] = msrs[i].data;
2356 break;
2357 case MSR_MTRRfix4K_F0000:
2358 env->mtrr_fixed[9] = msrs[i].data;
2359 break;
2360 case MSR_MTRRfix4K_F8000:
2361 env->mtrr_fixed[10] = msrs[i].data;
2362 break;
2363 case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
2364 if (index & 1) {
2365 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
2366 mtrr_top_bits;
2367 } else {
2368 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
2370 break;
2374 return 0;
2377 static int kvm_put_mp_state(X86CPU *cpu)
2379 struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
2381 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
2384 static int kvm_get_mp_state(X86CPU *cpu)
2386 CPUState *cs = CPU(cpu);
2387 CPUX86State *env = &cpu->env;
2388 struct kvm_mp_state mp_state;
2389 int ret;
2391 ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
2392 if (ret < 0) {
2393 return ret;
2395 env->mp_state = mp_state.mp_state;
2396 if (kvm_irqchip_in_kernel()) {
2397 cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
2399 return 0;
2402 static int kvm_get_apic(X86CPU *cpu)
2404 DeviceState *apic = cpu->apic_state;
2405 struct kvm_lapic_state kapic;
2406 int ret;
2408 if (apic && kvm_irqchip_in_kernel()) {
2409 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
2410 if (ret < 0) {
2411 return ret;
2414 kvm_get_apic_state(apic, &kapic);
2416 return 0;
2419 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
2421 CPUState *cs = CPU(cpu);
2422 CPUX86State *env = &cpu->env;
2423 struct kvm_vcpu_events events = {};
2425 if (!kvm_has_vcpu_events()) {
2426 return 0;
2429 events.exception.injected = (env->exception_injected >= 0);
2430 events.exception.nr = env->exception_injected;
2431 events.exception.has_error_code = env->has_error_code;
2432 events.exception.error_code = env->error_code;
2433 events.exception.pad = 0;
2435 events.interrupt.injected = (env->interrupt_injected >= 0);
2436 events.interrupt.nr = env->interrupt_injected;
2437 events.interrupt.soft = env->soft_interrupt;
2439 events.nmi.injected = env->nmi_injected;
2440 events.nmi.pending = env->nmi_pending;
2441 events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
2442 events.nmi.pad = 0;
2444 events.sipi_vector = env->sipi_vector;
2446 if (has_msr_smbase) {
2447 events.smi.smm = !!(env->hflags & HF_SMM_MASK);
2448 events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
2449 if (kvm_irqchip_in_kernel()) {
2450 /* As soon as these are moved to the kernel, remove them
2451 * from cs->interrupt_request.
2453 events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
2454 events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
2455 cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
2456 } else {
2457 /* Keep these in cs->interrupt_request. */
2458 events.smi.pending = 0;
2459 events.smi.latched_init = 0;
2461 events.flags |= KVM_VCPUEVENT_VALID_SMM;
2464 events.flags = 0;
2465 if (level >= KVM_PUT_RESET_STATE) {
2466 events.flags |=
2467 KVM_VCPUEVENT_VALID_NMI_PENDING | KVM_VCPUEVENT_VALID_SIPI_VECTOR;
2470 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
2473 static int kvm_get_vcpu_events(X86CPU *cpu)
2475 CPUX86State *env = &cpu->env;
2476 struct kvm_vcpu_events events;
2477 int ret;
2479 if (!kvm_has_vcpu_events()) {
2480 return 0;
2483 memset(&events, 0, sizeof(events));
2484 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
2485 if (ret < 0) {
2486 return ret;
2488 env->exception_injected =
2489 events.exception.injected ? events.exception.nr : -1;
2490 env->has_error_code = events.exception.has_error_code;
2491 env->error_code = events.exception.error_code;
2493 env->interrupt_injected =
2494 events.interrupt.injected ? events.interrupt.nr : -1;
2495 env->soft_interrupt = events.interrupt.soft;
2497 env->nmi_injected = events.nmi.injected;
2498 env->nmi_pending = events.nmi.pending;
2499 if (events.nmi.masked) {
2500 env->hflags2 |= HF2_NMI_MASK;
2501 } else {
2502 env->hflags2 &= ~HF2_NMI_MASK;
2505 if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
2506 if (events.smi.smm) {
2507 env->hflags |= HF_SMM_MASK;
2508 } else {
2509 env->hflags &= ~HF_SMM_MASK;
2511 if (events.smi.pending) {
2512 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2513 } else {
2514 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2516 if (events.smi.smm_inside_nmi) {
2517 env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
2518 } else {
2519 env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
2521 if (events.smi.latched_init) {
2522 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2523 } else {
2524 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2528 env->sipi_vector = events.sipi_vector;
2530 return 0;
2533 static int kvm_guest_debug_workarounds(X86CPU *cpu)
2535 CPUState *cs = CPU(cpu);
2536 CPUX86State *env = &cpu->env;
2537 int ret = 0;
2538 unsigned long reinject_trap = 0;
2540 if (!kvm_has_vcpu_events()) {
2541 if (env->exception_injected == 1) {
2542 reinject_trap = KVM_GUESTDBG_INJECT_DB;
2543 } else if (env->exception_injected == 3) {
2544 reinject_trap = KVM_GUESTDBG_INJECT_BP;
2546 env->exception_injected = -1;
2550 * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
2551 * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
2552 * by updating the debug state once again if single-stepping is on.
2553 * Another reason to call kvm_update_guest_debug here is a pending debug
2554 * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
2555 * reinject them via SET_GUEST_DEBUG.
2557 if (reinject_trap ||
2558 (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
2559 ret = kvm_update_guest_debug(cs, reinject_trap);
2561 return ret;
2564 static int kvm_put_debugregs(X86CPU *cpu)
2566 CPUX86State *env = &cpu->env;
2567 struct kvm_debugregs dbgregs;
2568 int i;
2570 if (!kvm_has_debugregs()) {
2571 return 0;
2574 for (i = 0; i < 4; i++) {
2575 dbgregs.db[i] = env->dr[i];
2577 dbgregs.dr6 = env->dr[6];
2578 dbgregs.dr7 = env->dr[7];
2579 dbgregs.flags = 0;
2581 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
2584 static int kvm_get_debugregs(X86CPU *cpu)
2586 CPUX86State *env = &cpu->env;
2587 struct kvm_debugregs dbgregs;
2588 int i, ret;
2590 if (!kvm_has_debugregs()) {
2591 return 0;
2594 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
2595 if (ret < 0) {
2596 return ret;
2598 for (i = 0; i < 4; i++) {
2599 env->dr[i] = dbgregs.db[i];
2601 env->dr[4] = env->dr[6] = dbgregs.dr6;
2602 env->dr[5] = env->dr[7] = dbgregs.dr7;
2604 return 0;
2607 int kvm_arch_put_registers(CPUState *cpu, int level)
2609 X86CPU *x86_cpu = X86_CPU(cpu);
2610 int ret;
2612 assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
2614 if (level >= KVM_PUT_RESET_STATE) {
2615 ret = kvm_put_msr_feature_control(x86_cpu);
2616 if (ret < 0) {
2617 return ret;
2621 if (level == KVM_PUT_FULL_STATE) {
2622 /* We don't check for kvm_arch_set_tsc_khz() errors here,
2623 * because TSC frequency mismatch shouldn't abort migration,
2624 * unless the user explicitly asked for a more strict TSC
2625 * setting (e.g. using an explicit "tsc-freq" option).
2627 kvm_arch_set_tsc_khz(cpu);
2630 ret = kvm_getput_regs(x86_cpu, 1);
2631 if (ret < 0) {
2632 return ret;
2634 ret = kvm_put_xsave(x86_cpu);
2635 if (ret < 0) {
2636 return ret;
2638 ret = kvm_put_xcrs(x86_cpu);
2639 if (ret < 0) {
2640 return ret;
2642 ret = kvm_put_sregs(x86_cpu);
2643 if (ret < 0) {
2644 return ret;
2646 /* must be before kvm_put_msrs */
2647 ret = kvm_inject_mce_oldstyle(x86_cpu);
2648 if (ret < 0) {
2649 return ret;
2651 ret = kvm_put_msrs(x86_cpu, level);
2652 if (ret < 0) {
2653 return ret;
2655 if (level >= KVM_PUT_RESET_STATE) {
2656 ret = kvm_put_mp_state(x86_cpu);
2657 if (ret < 0) {
2658 return ret;
2662 ret = kvm_put_tscdeadline_msr(x86_cpu);
2663 if (ret < 0) {
2664 return ret;
2667 ret = kvm_put_vcpu_events(x86_cpu, level);
2668 if (ret < 0) {
2669 return ret;
2671 ret = kvm_put_debugregs(x86_cpu);
2672 if (ret < 0) {
2673 return ret;
2675 /* must be last */
2676 ret = kvm_guest_debug_workarounds(x86_cpu);
2677 if (ret < 0) {
2678 return ret;
2680 return 0;
2683 int kvm_arch_get_registers(CPUState *cs)
2685 X86CPU *cpu = X86_CPU(cs);
2686 int ret;
2688 assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
2690 ret = kvm_getput_regs(cpu, 0);
2691 if (ret < 0) {
2692 goto out;
2694 ret = kvm_get_xsave(cpu);
2695 if (ret < 0) {
2696 goto out;
2698 ret = kvm_get_xcrs(cpu);
2699 if (ret < 0) {
2700 goto out;
2702 ret = kvm_get_sregs(cpu);
2703 if (ret < 0) {
2704 goto out;
2706 ret = kvm_get_msrs(cpu);
2707 if (ret < 0) {
2708 goto out;
2710 ret = kvm_get_mp_state(cpu);
2711 if (ret < 0) {
2712 goto out;
2714 ret = kvm_get_apic(cpu);
2715 if (ret < 0) {
2716 goto out;
2718 ret = kvm_get_vcpu_events(cpu);
2719 if (ret < 0) {
2720 goto out;
2722 ret = kvm_get_debugregs(cpu);
2723 if (ret < 0) {
2724 goto out;
2726 ret = 0;
2727 out:
2728 cpu_sync_bndcs_hflags(&cpu->env);
2729 return ret;
2732 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
2734 X86CPU *x86_cpu = X86_CPU(cpu);
2735 CPUX86State *env = &x86_cpu->env;
2736 int ret;
2738 /* Inject NMI */
2739 if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
2740 if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
2741 qemu_mutex_lock_iothread();
2742 cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
2743 qemu_mutex_unlock_iothread();
2744 DPRINTF("injected NMI\n");
2745 ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
2746 if (ret < 0) {
2747 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
2748 strerror(-ret));
2751 if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
2752 qemu_mutex_lock_iothread();
2753 cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
2754 qemu_mutex_unlock_iothread();
2755 DPRINTF("injected SMI\n");
2756 ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
2757 if (ret < 0) {
2758 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
2759 strerror(-ret));
2764 if (!kvm_pic_in_kernel()) {
2765 qemu_mutex_lock_iothread();
2768 /* Force the VCPU out of its inner loop to process any INIT requests
2769 * or (for userspace APIC, but it is cheap to combine the checks here)
2770 * pending TPR access reports.
2772 if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
2773 if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
2774 !(env->hflags & HF_SMM_MASK)) {
2775 cpu->exit_request = 1;
2777 if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
2778 cpu->exit_request = 1;
2782 if (!kvm_pic_in_kernel()) {
2783 /* Try to inject an interrupt if the guest can accept it */
2784 if (run->ready_for_interrupt_injection &&
2785 (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
2786 (env->eflags & IF_MASK)) {
2787 int irq;
2789 cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
2790 irq = cpu_get_pic_interrupt(env);
2791 if (irq >= 0) {
2792 struct kvm_interrupt intr;
2794 intr.irq = irq;
2795 DPRINTF("injected interrupt %d\n", irq);
2796 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
2797 if (ret < 0) {
2798 fprintf(stderr,
2799 "KVM: injection failed, interrupt lost (%s)\n",
2800 strerror(-ret));
2805 /* If we have an interrupt but the guest is not ready to receive an
2806 * interrupt, request an interrupt window exit. This will
2807 * cause a return to userspace as soon as the guest is ready to
2808 * receive interrupts. */
2809 if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
2810 run->request_interrupt_window = 1;
2811 } else {
2812 run->request_interrupt_window = 0;
2815 DPRINTF("setting tpr\n");
2816 run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
2818 qemu_mutex_unlock_iothread();
2822 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
2824 X86CPU *x86_cpu = X86_CPU(cpu);
2825 CPUX86State *env = &x86_cpu->env;
2827 if (run->flags & KVM_RUN_X86_SMM) {
2828 env->hflags |= HF_SMM_MASK;
2829 } else {
2830 env->hflags &= HF_SMM_MASK;
2832 if (run->if_flag) {
2833 env->eflags |= IF_MASK;
2834 } else {
2835 env->eflags &= ~IF_MASK;
2838 /* We need to protect the apic state against concurrent accesses from
2839 * different threads in case the userspace irqchip is used. */
2840 if (!kvm_irqchip_in_kernel()) {
2841 qemu_mutex_lock_iothread();
2843 cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
2844 cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
2845 if (!kvm_irqchip_in_kernel()) {
2846 qemu_mutex_unlock_iothread();
2848 return cpu_get_mem_attrs(env);
2851 int kvm_arch_process_async_events(CPUState *cs)
2853 X86CPU *cpu = X86_CPU(cs);
2854 CPUX86State *env = &cpu->env;
2856 if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
2857 /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
2858 assert(env->mcg_cap);
2860 cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
2862 kvm_cpu_synchronize_state(cs);
2864 if (env->exception_injected == EXCP08_DBLE) {
2865 /* this means triple fault */
2866 qemu_system_reset_request();
2867 cs->exit_request = 1;
2868 return 0;
2870 env->exception_injected = EXCP12_MCHK;
2871 env->has_error_code = 0;
2873 cs->halted = 0;
2874 if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
2875 env->mp_state = KVM_MP_STATE_RUNNABLE;
2879 if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
2880 !(env->hflags & HF_SMM_MASK)) {
2881 kvm_cpu_synchronize_state(cs);
2882 do_cpu_init(cpu);
2885 if (kvm_irqchip_in_kernel()) {
2886 return 0;
2889 if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
2890 cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
2891 apic_poll_irq(cpu->apic_state);
2893 if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2894 (env->eflags & IF_MASK)) ||
2895 (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
2896 cs->halted = 0;
2898 if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
2899 kvm_cpu_synchronize_state(cs);
2900 do_cpu_sipi(cpu);
2902 if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
2903 cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
2904 kvm_cpu_synchronize_state(cs);
2905 apic_handle_tpr_access_report(cpu->apic_state, env->eip,
2906 env->tpr_access_type);
2909 return cs->halted;
2912 static int kvm_handle_halt(X86CPU *cpu)
2914 CPUState *cs = CPU(cpu);
2915 CPUX86State *env = &cpu->env;
2917 if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2918 (env->eflags & IF_MASK)) &&
2919 !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
2920 cs->halted = 1;
2921 return EXCP_HLT;
2924 return 0;
2927 static int kvm_handle_tpr_access(X86CPU *cpu)
2929 CPUState *cs = CPU(cpu);
2930 struct kvm_run *run = cs->kvm_run;
2932 apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
2933 run->tpr_access.is_write ? TPR_ACCESS_WRITE
2934 : TPR_ACCESS_READ);
2935 return 1;
2938 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2940 static const uint8_t int3 = 0xcc;
2942 if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
2943 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
2944 return -EINVAL;
2946 return 0;
2949 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2951 uint8_t int3;
2953 if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
2954 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
2955 return -EINVAL;
2957 return 0;
2960 static struct {
2961 target_ulong addr;
2962 int len;
2963 int type;
2964 } hw_breakpoint[4];
2966 static int nb_hw_breakpoint;
2968 static int find_hw_breakpoint(target_ulong addr, int len, int type)
2970 int n;
2972 for (n = 0; n < nb_hw_breakpoint; n++) {
2973 if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
2974 (hw_breakpoint[n].len == len || len == -1)) {
2975 return n;
2978 return -1;
2981 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
2982 target_ulong len, int type)
2984 switch (type) {
2985 case GDB_BREAKPOINT_HW:
2986 len = 1;
2987 break;
2988 case GDB_WATCHPOINT_WRITE:
2989 case GDB_WATCHPOINT_ACCESS:
2990 switch (len) {
2991 case 1:
2992 break;
2993 case 2:
2994 case 4:
2995 case 8:
2996 if (addr & (len - 1)) {
2997 return -EINVAL;
2999 break;
3000 default:
3001 return -EINVAL;
3003 break;
3004 default:
3005 return -ENOSYS;
3008 if (nb_hw_breakpoint == 4) {
3009 return -ENOBUFS;
3011 if (find_hw_breakpoint(addr, len, type) >= 0) {
3012 return -EEXIST;
3014 hw_breakpoint[nb_hw_breakpoint].addr = addr;
3015 hw_breakpoint[nb_hw_breakpoint].len = len;
3016 hw_breakpoint[nb_hw_breakpoint].type = type;
3017 nb_hw_breakpoint++;
3019 return 0;
3022 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
3023 target_ulong len, int type)
3025 int n;
3027 n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
3028 if (n < 0) {
3029 return -ENOENT;
3031 nb_hw_breakpoint--;
3032 hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
3034 return 0;
3037 void kvm_arch_remove_all_hw_breakpoints(void)
3039 nb_hw_breakpoint = 0;
3042 static CPUWatchpoint hw_watchpoint;
3044 static int kvm_handle_debug(X86CPU *cpu,
3045 struct kvm_debug_exit_arch *arch_info)
3047 CPUState *cs = CPU(cpu);
3048 CPUX86State *env = &cpu->env;
3049 int ret = 0;
3050 int n;
3052 if (arch_info->exception == 1) {
3053 if (arch_info->dr6 & (1 << 14)) {
3054 if (cs->singlestep_enabled) {
3055 ret = EXCP_DEBUG;
3057 } else {
3058 for (n = 0; n < 4; n++) {
3059 if (arch_info->dr6 & (1 << n)) {
3060 switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
3061 case 0x0:
3062 ret = EXCP_DEBUG;
3063 break;
3064 case 0x1:
3065 ret = EXCP_DEBUG;
3066 cs->watchpoint_hit = &hw_watchpoint;
3067 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
3068 hw_watchpoint.flags = BP_MEM_WRITE;
3069 break;
3070 case 0x3:
3071 ret = EXCP_DEBUG;
3072 cs->watchpoint_hit = &hw_watchpoint;
3073 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
3074 hw_watchpoint.flags = BP_MEM_ACCESS;
3075 break;
3080 } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
3081 ret = EXCP_DEBUG;
3083 if (ret == 0) {
3084 cpu_synchronize_state(cs);
3085 assert(env->exception_injected == -1);
3087 /* pass to guest */
3088 env->exception_injected = arch_info->exception;
3089 env->has_error_code = 0;
3092 return ret;
3095 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
3097 const uint8_t type_code[] = {
3098 [GDB_BREAKPOINT_HW] = 0x0,
3099 [GDB_WATCHPOINT_WRITE] = 0x1,
3100 [GDB_WATCHPOINT_ACCESS] = 0x3
3102 const uint8_t len_code[] = {
3103 [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
3105 int n;
3107 if (kvm_sw_breakpoints_active(cpu)) {
3108 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
3110 if (nb_hw_breakpoint > 0) {
3111 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
3112 dbg->arch.debugreg[7] = 0x0600;
3113 for (n = 0; n < nb_hw_breakpoint; n++) {
3114 dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
3115 dbg->arch.debugreg[7] |= (2 << (n * 2)) |
3116 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
3117 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
3122 static bool host_supports_vmx(void)
3124 uint32_t ecx, unused;
3126 host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
3127 return ecx & CPUID_EXT_VMX;
3130 #define VMX_INVALID_GUEST_STATE 0x80000021
3132 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
3134 X86CPU *cpu = X86_CPU(cs);
3135 uint64_t code;
3136 int ret;
3138 switch (run->exit_reason) {
3139 case KVM_EXIT_HLT:
3140 DPRINTF("handle_hlt\n");
3141 qemu_mutex_lock_iothread();
3142 ret = kvm_handle_halt(cpu);
3143 qemu_mutex_unlock_iothread();
3144 break;
3145 case KVM_EXIT_SET_TPR:
3146 ret = 0;
3147 break;
3148 case KVM_EXIT_TPR_ACCESS:
3149 qemu_mutex_lock_iothread();
3150 ret = kvm_handle_tpr_access(cpu);
3151 qemu_mutex_unlock_iothread();
3152 break;
3153 case KVM_EXIT_FAIL_ENTRY:
3154 code = run->fail_entry.hardware_entry_failure_reason;
3155 fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
3156 code);
3157 if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
3158 fprintf(stderr,
3159 "\nIf you're running a guest on an Intel machine without "
3160 "unrestricted mode\n"
3161 "support, the failure can be most likely due to the guest "
3162 "entering an invalid\n"
3163 "state for Intel VT. For example, the guest maybe running "
3164 "in big real mode\n"
3165 "which is not supported on less recent Intel processors."
3166 "\n\n");
3168 ret = -1;
3169 break;
3170 case KVM_EXIT_EXCEPTION:
3171 fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
3172 run->ex.exception, run->ex.error_code);
3173 ret = -1;
3174 break;
3175 case KVM_EXIT_DEBUG:
3176 DPRINTF("kvm_exit_debug\n");
3177 qemu_mutex_lock_iothread();
3178 ret = kvm_handle_debug(cpu, &run->debug.arch);
3179 qemu_mutex_unlock_iothread();
3180 break;
3181 case KVM_EXIT_HYPERV:
3182 ret = kvm_hv_handle_exit(cpu, &run->hyperv);
3183 break;
3184 case KVM_EXIT_IOAPIC_EOI:
3185 ioapic_eoi_broadcast(run->eoi.vector);
3186 ret = 0;
3187 break;
3188 default:
3189 fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
3190 ret = -1;
3191 break;
3194 return ret;
3197 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
3199 X86CPU *cpu = X86_CPU(cs);
3200 CPUX86State *env = &cpu->env;
3202 kvm_cpu_synchronize_state(cs);
3203 return !(env->cr[0] & CR0_PE_MASK) ||
3204 ((env->segs[R_CS].selector & 3) != 3);
3207 void kvm_arch_init_irq_routing(KVMState *s)
3209 if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
3210 /* If kernel can't do irq routing, interrupt source
3211 * override 0->2 cannot be set up as required by HPET.
3212 * So we have to disable it.
3214 no_hpet = 1;
3216 /* We know at this point that we're using the in-kernel
3217 * irqchip, so we can use irqfds, and on x86 we know
3218 * we can use msi via irqfd and GSI routing.
3220 kvm_msi_via_irqfd_allowed = true;
3221 kvm_gsi_routing_allowed = true;
3223 if (kvm_irqchip_is_split()) {
3224 int i;
3226 /* If the ioapic is in QEMU and the lapics are in KVM, reserve
3227 MSI routes for signaling interrupts to the local apics. */
3228 for (i = 0; i < IOAPIC_NUM_PINS; i++) {
3229 if (kvm_irqchip_add_msi_route(s, 0, NULL) < 0) {
3230 error_report("Could not enable split IRQ mode.");
3231 exit(1);
3237 int kvm_arch_irqchip_create(MachineState *ms, KVMState *s)
3239 int ret;
3240 if (machine_kernel_irqchip_split(ms)) {
3241 ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
3242 if (ret) {
3243 error_report("Could not enable split irqchip mode: %s",
3244 strerror(-ret));
3245 exit(1);
3246 } else {
3247 DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
3248 kvm_split_irqchip = true;
3249 return 1;
3251 } else {
3252 return 0;
3256 /* Classic KVM device assignment interface. Will remain x86 only. */
3257 int kvm_device_pci_assign(KVMState *s, PCIHostDeviceAddress *dev_addr,
3258 uint32_t flags, uint32_t *dev_id)
3260 struct kvm_assigned_pci_dev dev_data = {
3261 .segnr = dev_addr->domain,
3262 .busnr = dev_addr->bus,
3263 .devfn = PCI_DEVFN(dev_addr->slot, dev_addr->function),
3264 .flags = flags,
3266 int ret;
3268 dev_data.assigned_dev_id =
3269 (dev_addr->domain << 16) | (dev_addr->bus << 8) | dev_data.devfn;
3271 ret = kvm_vm_ioctl(s, KVM_ASSIGN_PCI_DEVICE, &dev_data);
3272 if (ret < 0) {
3273 return ret;
3276 *dev_id = dev_data.assigned_dev_id;
3278 return 0;
3281 int kvm_device_pci_deassign(KVMState *s, uint32_t dev_id)
3283 struct kvm_assigned_pci_dev dev_data = {
3284 .assigned_dev_id = dev_id,
3287 return kvm_vm_ioctl(s, KVM_DEASSIGN_PCI_DEVICE, &dev_data);
3290 static int kvm_assign_irq_internal(KVMState *s, uint32_t dev_id,
3291 uint32_t irq_type, uint32_t guest_irq)
3293 struct kvm_assigned_irq assigned_irq = {
3294 .assigned_dev_id = dev_id,
3295 .guest_irq = guest_irq,
3296 .flags = irq_type,
3299 if (kvm_check_extension(s, KVM_CAP_ASSIGN_DEV_IRQ)) {
3300 return kvm_vm_ioctl(s, KVM_ASSIGN_DEV_IRQ, &assigned_irq);
3301 } else {
3302 return kvm_vm_ioctl(s, KVM_ASSIGN_IRQ, &assigned_irq);
3306 int kvm_device_intx_assign(KVMState *s, uint32_t dev_id, bool use_host_msi,
3307 uint32_t guest_irq)
3309 uint32_t irq_type = KVM_DEV_IRQ_GUEST_INTX |
3310 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX);
3312 return kvm_assign_irq_internal(s, dev_id, irq_type, guest_irq);
3315 int kvm_device_intx_set_mask(KVMState *s, uint32_t dev_id, bool masked)
3317 struct kvm_assigned_pci_dev dev_data = {
3318 .assigned_dev_id = dev_id,
3319 .flags = masked ? KVM_DEV_ASSIGN_MASK_INTX : 0,
3322 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_INTX_MASK, &dev_data);
3325 static int kvm_deassign_irq_internal(KVMState *s, uint32_t dev_id,
3326 uint32_t type)
3328 struct kvm_assigned_irq assigned_irq = {
3329 .assigned_dev_id = dev_id,
3330 .flags = type,
3333 return kvm_vm_ioctl(s, KVM_DEASSIGN_DEV_IRQ, &assigned_irq);
3336 int kvm_device_intx_deassign(KVMState *s, uint32_t dev_id, bool use_host_msi)
3338 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_INTX |
3339 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX));
3342 int kvm_device_msi_assign(KVMState *s, uint32_t dev_id, int virq)
3344 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSI |
3345 KVM_DEV_IRQ_GUEST_MSI, virq);
3348 int kvm_device_msi_deassign(KVMState *s, uint32_t dev_id)
3350 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSI |
3351 KVM_DEV_IRQ_HOST_MSI);
3354 bool kvm_device_msix_supported(KVMState *s)
3356 /* The kernel lacks a corresponding KVM_CAP, so we probe by calling
3357 * KVM_ASSIGN_SET_MSIX_NR with an invalid parameter. */
3358 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, NULL) == -EFAULT;
3361 int kvm_device_msix_init_vectors(KVMState *s, uint32_t dev_id,
3362 uint32_t nr_vectors)
3364 struct kvm_assigned_msix_nr msix_nr = {
3365 .assigned_dev_id = dev_id,
3366 .entry_nr = nr_vectors,
3369 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, &msix_nr);
3372 int kvm_device_msix_set_vector(KVMState *s, uint32_t dev_id, uint32_t vector,
3373 int virq)
3375 struct kvm_assigned_msix_entry msix_entry = {
3376 .assigned_dev_id = dev_id,
3377 .gsi = virq,
3378 .entry = vector,
3381 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_ENTRY, &msix_entry);
3384 int kvm_device_msix_assign(KVMState *s, uint32_t dev_id)
3386 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSIX |
3387 KVM_DEV_IRQ_GUEST_MSIX, 0);
3390 int kvm_device_msix_deassign(KVMState *s, uint32_t dev_id)
3392 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSIX |
3393 KVM_DEV_IRQ_HOST_MSIX);
3396 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
3397 uint64_t address, uint32_t data, PCIDevice *dev)
3399 X86IOMMUState *iommu = x86_iommu_get_default();
3401 if (iommu) {
3402 int ret;
3403 MSIMessage src, dst;
3404 X86IOMMUClass *class = X86_IOMMU_GET_CLASS(iommu);
3406 src.address = route->u.msi.address_hi;
3407 src.address <<= VTD_MSI_ADDR_HI_SHIFT;
3408 src.address |= route->u.msi.address_lo;
3409 src.data = route->u.msi.data;
3411 ret = class->int_remap(iommu, &src, &dst, dev ? \
3412 pci_requester_id(dev) : \
3413 X86_IOMMU_SID_INVALID);
3414 if (ret) {
3415 trace_kvm_x86_fixup_msi_error(route->gsi);
3416 return 1;
3419 route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
3420 route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
3421 route->u.msi.data = dst.data;
3424 return 0;
3427 typedef struct MSIRouteEntry MSIRouteEntry;
3429 struct MSIRouteEntry {
3430 PCIDevice *dev; /* Device pointer */
3431 int vector; /* MSI/MSIX vector index */
3432 int virq; /* Virtual IRQ index */
3433 QLIST_ENTRY(MSIRouteEntry) list;
3436 /* List of used GSI routes */
3437 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
3438 QLIST_HEAD_INITIALIZER(msi_route_list);
3440 static void kvm_update_msi_routes_all(void *private, bool global,
3441 uint32_t index, uint32_t mask)
3443 int cnt = 0;
3444 MSIRouteEntry *entry;
3445 MSIMessage msg;
3446 /* TODO: explicit route update */
3447 QLIST_FOREACH(entry, &msi_route_list, list) {
3448 cnt++;
3449 msg = pci_get_msi_message(entry->dev, entry->vector);
3450 kvm_irqchip_update_msi_route(kvm_state, entry->virq,
3451 msg, entry->dev);
3453 kvm_irqchip_commit_routes(kvm_state);
3454 trace_kvm_x86_update_msi_routes(cnt);
3457 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
3458 int vector, PCIDevice *dev)
3460 static bool notify_list_inited = false;
3461 MSIRouteEntry *entry;
3463 if (!dev) {
3464 /* These are (possibly) IOAPIC routes only used for split
3465 * kernel irqchip mode, while what we are housekeeping are
3466 * PCI devices only. */
3467 return 0;
3470 entry = g_new0(MSIRouteEntry, 1);
3471 entry->dev = dev;
3472 entry->vector = vector;
3473 entry->virq = route->gsi;
3474 QLIST_INSERT_HEAD(&msi_route_list, entry, list);
3476 trace_kvm_x86_add_msi_route(route->gsi);
3478 if (!notify_list_inited) {
3479 /* For the first time we do add route, add ourselves into
3480 * IOMMU's IEC notify list if needed. */
3481 X86IOMMUState *iommu = x86_iommu_get_default();
3482 if (iommu) {
3483 x86_iommu_iec_register_notifier(iommu,
3484 kvm_update_msi_routes_all,
3485 NULL);
3487 notify_list_inited = true;
3489 return 0;
3492 int kvm_arch_release_virq_post(int virq)
3494 MSIRouteEntry *entry, *next;
3495 QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
3496 if (entry->virq == virq) {
3497 trace_kvm_x86_remove_msi_route(virq);
3498 QLIST_REMOVE(entry, list);
3499 break;
3502 return 0;
3505 int kvm_arch_msi_data_to_gsi(uint32_t data)
3507 abort();