x86/cpu: use standard-headers/asm-x86.kvm_para.h
[qemu/ar7.git] / target / i386 / kvm.c
blob6511329d11ed0bcd91f52922b8e72c0f1db5ac6b
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 "standard-headers/asm-x86/kvm_para.h"
23 #include "qemu-common.h"
24 #include "cpu.h"
25 #include "sysemu/sysemu.h"
26 #include "sysemu/hw_accel.h"
27 #include "sysemu/kvm_int.h"
28 #include "kvm_i386.h"
29 #include "hyperv.h"
30 #include "hyperv-proto.h"
32 #include "exec/gdbstub.h"
33 #include "qemu/host-utils.h"
34 #include "qemu/config-file.h"
35 #include "qemu/error-report.h"
36 #include "hw/i386/pc.h"
37 #include "hw/i386/apic.h"
38 #include "hw/i386/apic_internal.h"
39 #include "hw/i386/apic-msidef.h"
40 #include "hw/i386/intel_iommu.h"
41 #include "hw/i386/x86-iommu.h"
43 #include "exec/ioport.h"
44 #include "hw/pci/pci.h"
45 #include "hw/pci/msi.h"
46 #include "hw/pci/msix.h"
47 #include "migration/blocker.h"
48 #include "exec/memattrs.h"
49 #include "trace.h"
51 //#define DEBUG_KVM
53 #ifdef DEBUG_KVM
54 #define DPRINTF(fmt, ...) \
55 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
56 #else
57 #define DPRINTF(fmt, ...) \
58 do { } while (0)
59 #endif
61 #define MSR_KVM_WALL_CLOCK 0x11
62 #define MSR_KVM_SYSTEM_TIME 0x12
64 /* A 4096-byte buffer can hold the 8-byte kvm_msrs header, plus
65 * 255 kvm_msr_entry structs */
66 #define MSR_BUF_SIZE 4096
68 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
69 KVM_CAP_INFO(SET_TSS_ADDR),
70 KVM_CAP_INFO(EXT_CPUID),
71 KVM_CAP_INFO(MP_STATE),
72 KVM_CAP_LAST_INFO
75 static bool has_msr_star;
76 static bool has_msr_hsave_pa;
77 static bool has_msr_tsc_aux;
78 static bool has_msr_tsc_adjust;
79 static bool has_msr_tsc_deadline;
80 static bool has_msr_feature_control;
81 static bool has_msr_misc_enable;
82 static bool has_msr_smbase;
83 static bool has_msr_bndcfgs;
84 static int lm_capable_kernel;
85 static bool has_msr_hv_hypercall;
86 static bool has_msr_hv_crash;
87 static bool has_msr_hv_reset;
88 static bool has_msr_hv_vpindex;
89 static bool has_msr_hv_runtime;
90 static bool has_msr_hv_synic;
91 static bool has_msr_hv_stimer;
92 static bool has_msr_hv_frequencies;
93 static bool has_msr_hv_reenlightenment;
94 static bool has_msr_xss;
95 static bool has_msr_spec_ctrl;
96 static bool has_msr_virt_ssbd;
97 static bool has_msr_smi_count;
99 static uint32_t has_architectural_pmu_version;
100 static uint32_t num_architectural_pmu_gp_counters;
101 static uint32_t num_architectural_pmu_fixed_counters;
103 static int has_xsave;
104 static int has_xcrs;
105 static int has_pit_state2;
107 static bool has_msr_mcg_ext_ctl;
109 static struct kvm_cpuid2 *cpuid_cache;
111 int kvm_has_pit_state2(void)
113 return has_pit_state2;
116 bool kvm_has_smm(void)
118 return kvm_check_extension(kvm_state, KVM_CAP_X86_SMM);
121 bool kvm_has_adjust_clock_stable(void)
123 int ret = kvm_check_extension(kvm_state, KVM_CAP_ADJUST_CLOCK);
125 return (ret == KVM_CLOCK_TSC_STABLE);
128 bool kvm_allows_irq0_override(void)
130 return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
133 static bool kvm_x2apic_api_set_flags(uint64_t flags)
135 KVMState *s = KVM_STATE(current_machine->accelerator);
137 return !kvm_vm_enable_cap(s, KVM_CAP_X2APIC_API, 0, flags);
140 #define MEMORIZE(fn, _result) \
141 ({ \
142 static bool _memorized; \
144 if (_memorized) { \
145 return _result; \
147 _memorized = true; \
148 _result = fn; \
151 static bool has_x2apic_api;
153 bool kvm_has_x2apic_api(void)
155 return has_x2apic_api;
158 bool kvm_enable_x2apic(void)
160 return MEMORIZE(
161 kvm_x2apic_api_set_flags(KVM_X2APIC_API_USE_32BIT_IDS |
162 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK),
163 has_x2apic_api);
166 static int kvm_get_tsc(CPUState *cs)
168 X86CPU *cpu = X86_CPU(cs);
169 CPUX86State *env = &cpu->env;
170 struct {
171 struct kvm_msrs info;
172 struct kvm_msr_entry entries[1];
173 } msr_data;
174 int ret;
176 if (env->tsc_valid) {
177 return 0;
180 msr_data.info.nmsrs = 1;
181 msr_data.entries[0].index = MSR_IA32_TSC;
182 env->tsc_valid = !runstate_is_running();
184 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
185 if (ret < 0) {
186 return ret;
189 assert(ret == 1);
190 env->tsc = msr_data.entries[0].data;
191 return 0;
194 static inline void do_kvm_synchronize_tsc(CPUState *cpu, run_on_cpu_data arg)
196 kvm_get_tsc(cpu);
199 void kvm_synchronize_all_tsc(void)
201 CPUState *cpu;
203 if (kvm_enabled()) {
204 CPU_FOREACH(cpu) {
205 run_on_cpu(cpu, do_kvm_synchronize_tsc, RUN_ON_CPU_NULL);
210 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
212 struct kvm_cpuid2 *cpuid;
213 int r, size;
215 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
216 cpuid = g_malloc0(size);
217 cpuid->nent = max;
218 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
219 if (r == 0 && cpuid->nent >= max) {
220 r = -E2BIG;
222 if (r < 0) {
223 if (r == -E2BIG) {
224 g_free(cpuid);
225 return NULL;
226 } else {
227 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
228 strerror(-r));
229 exit(1);
232 return cpuid;
235 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
236 * for all entries.
238 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
240 struct kvm_cpuid2 *cpuid;
241 int max = 1;
243 if (cpuid_cache != NULL) {
244 return cpuid_cache;
246 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
247 max *= 2;
249 cpuid_cache = cpuid;
250 return cpuid;
253 static const struct kvm_para_features {
254 int cap;
255 int feature;
256 } para_features[] = {
257 { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
258 { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
259 { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
260 { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
263 static int get_para_features(KVMState *s)
265 int i, features = 0;
267 for (i = 0; i < ARRAY_SIZE(para_features); i++) {
268 if (kvm_check_extension(s, para_features[i].cap)) {
269 features |= (1 << para_features[i].feature);
273 return features;
276 static bool host_tsx_blacklisted(void)
278 int family, model, stepping;\
279 char vendor[CPUID_VENDOR_SZ + 1];
281 host_vendor_fms(vendor, &family, &model, &stepping);
283 /* Check if we are running on a Haswell host known to have broken TSX */
284 return !strcmp(vendor, CPUID_VENDOR_INTEL) &&
285 (family == 6) &&
286 ((model == 63 && stepping < 4) ||
287 model == 60 || model == 69 || model == 70);
290 /* Returns the value for a specific register on the cpuid entry
292 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
294 uint32_t ret = 0;
295 switch (reg) {
296 case R_EAX:
297 ret = entry->eax;
298 break;
299 case R_EBX:
300 ret = entry->ebx;
301 break;
302 case R_ECX:
303 ret = entry->ecx;
304 break;
305 case R_EDX:
306 ret = entry->edx;
307 break;
309 return ret;
312 /* Find matching entry for function/index on kvm_cpuid2 struct
314 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
315 uint32_t function,
316 uint32_t index)
318 int i;
319 for (i = 0; i < cpuid->nent; ++i) {
320 if (cpuid->entries[i].function == function &&
321 cpuid->entries[i].index == index) {
322 return &cpuid->entries[i];
325 /* not found: */
326 return NULL;
329 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
330 uint32_t index, int reg)
332 struct kvm_cpuid2 *cpuid;
333 uint32_t ret = 0;
334 uint32_t cpuid_1_edx;
335 bool found = false;
337 cpuid = get_supported_cpuid(s);
339 struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
340 if (entry) {
341 found = true;
342 ret = cpuid_entry_get_reg(entry, reg);
345 /* Fixups for the data returned by KVM, below */
347 if (function == 1 && reg == R_EDX) {
348 /* KVM before 2.6.30 misreports the following features */
349 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
350 } else if (function == 1 && reg == R_ECX) {
351 /* We can set the hypervisor flag, even if KVM does not return it on
352 * GET_SUPPORTED_CPUID
354 ret |= CPUID_EXT_HYPERVISOR;
355 /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
356 * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
357 * and the irqchip is in the kernel.
359 if (kvm_irqchip_in_kernel() &&
360 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
361 ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
364 /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
365 * without the in-kernel irqchip
367 if (!kvm_irqchip_in_kernel()) {
368 ret &= ~CPUID_EXT_X2APIC;
370 } else if (function == 6 && reg == R_EAX) {
371 ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
372 } else if (function == 7 && index == 0 && reg == R_EBX) {
373 if (host_tsx_blacklisted()) {
374 ret &= ~(CPUID_7_0_EBX_RTM | CPUID_7_0_EBX_HLE);
376 } else if (function == 0x80000001 && reg == R_EDX) {
377 /* On Intel, kvm returns cpuid according to the Intel spec,
378 * so add missing bits according to the AMD spec:
380 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
381 ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
382 } else if (function == KVM_CPUID_FEATURES && reg == R_EAX) {
383 /* kvm_pv_unhalt is reported by GET_SUPPORTED_CPUID, but it can't
384 * be enabled without the in-kernel irqchip
386 if (!kvm_irqchip_in_kernel()) {
387 ret &= ~(1U << KVM_FEATURE_PV_UNHALT);
389 } else if (function == KVM_CPUID_FEATURES && reg == R_EDX) {
390 ret |= 1U << KVM_HINTS_DEDICATED;
391 found = 1;
394 /* fallback for older kernels */
395 if ((function == KVM_CPUID_FEATURES) && !found) {
396 ret = get_para_features(s);
399 return ret;
402 typedef struct HWPoisonPage {
403 ram_addr_t ram_addr;
404 QLIST_ENTRY(HWPoisonPage) list;
405 } HWPoisonPage;
407 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
408 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
410 static void kvm_unpoison_all(void *param)
412 HWPoisonPage *page, *next_page;
414 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
415 QLIST_REMOVE(page, list);
416 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
417 g_free(page);
421 static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
423 HWPoisonPage *page;
425 QLIST_FOREACH(page, &hwpoison_page_list, list) {
426 if (page->ram_addr == ram_addr) {
427 return;
430 page = g_new(HWPoisonPage, 1);
431 page->ram_addr = ram_addr;
432 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
435 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
436 int *max_banks)
438 int r;
440 r = kvm_check_extension(s, KVM_CAP_MCE);
441 if (r > 0) {
442 *max_banks = r;
443 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
445 return -ENOSYS;
448 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
450 CPUState *cs = CPU(cpu);
451 CPUX86State *env = &cpu->env;
452 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
453 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
454 uint64_t mcg_status = MCG_STATUS_MCIP;
455 int flags = 0;
457 if (code == BUS_MCEERR_AR) {
458 status |= MCI_STATUS_AR | 0x134;
459 mcg_status |= MCG_STATUS_EIPV;
460 } else {
461 status |= 0xc0;
462 mcg_status |= MCG_STATUS_RIPV;
465 flags = cpu_x86_support_mca_broadcast(env) ? MCE_INJECT_BROADCAST : 0;
466 /* We need to read back the value of MSR_EXT_MCG_CTL that was set by the
467 * guest kernel back into env->mcg_ext_ctl.
469 cpu_synchronize_state(cs);
470 if (env->mcg_ext_ctl & MCG_EXT_CTL_LMCE_EN) {
471 mcg_status |= MCG_STATUS_LMCE;
472 flags = 0;
475 cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
476 (MCM_ADDR_PHYS << 6) | 0xc, flags);
479 static void hardware_memory_error(void)
481 fprintf(stderr, "Hardware memory error!\n");
482 exit(1);
485 void kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
487 X86CPU *cpu = X86_CPU(c);
488 CPUX86State *env = &cpu->env;
489 ram_addr_t ram_addr;
490 hwaddr paddr;
492 /* If we get an action required MCE, it has been injected by KVM
493 * while the VM was running. An action optional MCE instead should
494 * be coming from the main thread, which qemu_init_sigbus identifies
495 * as the "early kill" thread.
497 assert(code == BUS_MCEERR_AR || code == BUS_MCEERR_AO);
499 if ((env->mcg_cap & MCG_SER_P) && addr) {
500 ram_addr = qemu_ram_addr_from_host(addr);
501 if (ram_addr != RAM_ADDR_INVALID &&
502 kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
503 kvm_hwpoison_page_add(ram_addr);
504 kvm_mce_inject(cpu, paddr, code);
505 return;
508 fprintf(stderr, "Hardware memory error for memory used by "
509 "QEMU itself instead of guest system!\n");
512 if (code == BUS_MCEERR_AR) {
513 hardware_memory_error();
516 /* Hope we are lucky for AO MCE */
519 static int kvm_inject_mce_oldstyle(X86CPU *cpu)
521 CPUX86State *env = &cpu->env;
523 if (!kvm_has_vcpu_events() && env->exception_injected == EXCP12_MCHK) {
524 unsigned int bank, bank_num = env->mcg_cap & 0xff;
525 struct kvm_x86_mce mce;
527 env->exception_injected = -1;
530 * There must be at least one bank in use if an MCE is pending.
531 * Find it and use its values for the event injection.
533 for (bank = 0; bank < bank_num; bank++) {
534 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
535 break;
538 assert(bank < bank_num);
540 mce.bank = bank;
541 mce.status = env->mce_banks[bank * 4 + 1];
542 mce.mcg_status = env->mcg_status;
543 mce.addr = env->mce_banks[bank * 4 + 2];
544 mce.misc = env->mce_banks[bank * 4 + 3];
546 return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
548 return 0;
551 static void cpu_update_state(void *opaque, int running, RunState state)
553 CPUX86State *env = opaque;
555 if (running) {
556 env->tsc_valid = false;
560 unsigned long kvm_arch_vcpu_id(CPUState *cs)
562 X86CPU *cpu = X86_CPU(cs);
563 return cpu->apic_id;
566 #ifndef KVM_CPUID_SIGNATURE_NEXT
567 #define KVM_CPUID_SIGNATURE_NEXT 0x40000100
568 #endif
570 static bool hyperv_hypercall_available(X86CPU *cpu)
572 return cpu->hyperv_vapic ||
573 (cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY);
576 static bool hyperv_enabled(X86CPU *cpu)
578 CPUState *cs = CPU(cpu);
579 return kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0 &&
580 (hyperv_hypercall_available(cpu) ||
581 cpu->hyperv_time ||
582 cpu->hyperv_relaxed_timing ||
583 cpu->hyperv_crash ||
584 cpu->hyperv_reset ||
585 cpu->hyperv_vpindex ||
586 cpu->hyperv_runtime ||
587 cpu->hyperv_synic ||
588 cpu->hyperv_stimer ||
589 cpu->hyperv_reenlightenment);
592 static int kvm_arch_set_tsc_khz(CPUState *cs)
594 X86CPU *cpu = X86_CPU(cs);
595 CPUX86State *env = &cpu->env;
596 int r;
598 if (!env->tsc_khz) {
599 return 0;
602 r = kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL) ?
603 kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) :
604 -ENOTSUP;
605 if (r < 0) {
606 /* When KVM_SET_TSC_KHZ fails, it's an error only if the current
607 * TSC frequency doesn't match the one we want.
609 int cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
610 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
611 -ENOTSUP;
612 if (cur_freq <= 0 || cur_freq != env->tsc_khz) {
613 warn_report("TSC frequency mismatch between "
614 "VM (%" PRId64 " kHz) and host (%d kHz), "
615 "and TSC scaling unavailable",
616 env->tsc_khz, cur_freq);
617 return r;
621 return 0;
624 static bool tsc_is_stable_and_known(CPUX86State *env)
626 if (!env->tsc_khz) {
627 return false;
629 return (env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC)
630 || env->user_tsc_khz;
633 static int hyperv_handle_properties(CPUState *cs)
635 X86CPU *cpu = X86_CPU(cs);
636 CPUX86State *env = &cpu->env;
638 if (cpu->hyperv_relaxed_timing) {
639 env->features[FEAT_HYPERV_EAX] |= HV_HYPERCALL_AVAILABLE;
641 if (cpu->hyperv_vapic) {
642 env->features[FEAT_HYPERV_EAX] |= HV_HYPERCALL_AVAILABLE;
643 env->features[FEAT_HYPERV_EAX] |= HV_APIC_ACCESS_AVAILABLE;
645 if (cpu->hyperv_time) {
646 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) <= 0) {
647 fprintf(stderr, "Hyper-V clocksources "
648 "(requested by 'hv-time' cpu flag) "
649 "are not supported by kernel\n");
650 return -ENOSYS;
652 env->features[FEAT_HYPERV_EAX] |= HV_HYPERCALL_AVAILABLE;
653 env->features[FEAT_HYPERV_EAX] |= HV_TIME_REF_COUNT_AVAILABLE;
654 env->features[FEAT_HYPERV_EAX] |= HV_REFERENCE_TSC_AVAILABLE;
656 if (cpu->hyperv_frequencies) {
657 if (!has_msr_hv_frequencies) {
658 fprintf(stderr, "Hyper-V frequency MSRs "
659 "(requested by 'hv-frequencies' cpu flag) "
660 "are not supported by kernel\n");
661 return -ENOSYS;
663 env->features[FEAT_HYPERV_EAX] |= HV_ACCESS_FREQUENCY_MSRS;
664 env->features[FEAT_HYPERV_EDX] |= HV_FREQUENCY_MSRS_AVAILABLE;
666 if (cpu->hyperv_crash) {
667 if (!has_msr_hv_crash) {
668 fprintf(stderr, "Hyper-V crash MSRs "
669 "(requested by 'hv-crash' cpu flag) "
670 "are not supported by kernel\n");
671 return -ENOSYS;
673 env->features[FEAT_HYPERV_EDX] |= HV_GUEST_CRASH_MSR_AVAILABLE;
675 if (cpu->hyperv_reenlightenment) {
676 if (!has_msr_hv_reenlightenment) {
677 fprintf(stderr,
678 "Hyper-V Reenlightenment MSRs "
679 "(requested by 'hv-reenlightenment' cpu flag) "
680 "are not supported by kernel\n");
681 return -ENOSYS;
683 env->features[FEAT_HYPERV_EAX] |= HV_ACCESS_REENLIGHTENMENTS_CONTROL;
685 env->features[FEAT_HYPERV_EDX] |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
686 if (cpu->hyperv_reset) {
687 if (!has_msr_hv_reset) {
688 fprintf(stderr, "Hyper-V reset MSR "
689 "(requested by 'hv-reset' cpu flag) "
690 "is not supported by kernel\n");
691 return -ENOSYS;
693 env->features[FEAT_HYPERV_EAX] |= HV_RESET_AVAILABLE;
695 if (cpu->hyperv_vpindex) {
696 if (!has_msr_hv_vpindex) {
697 fprintf(stderr, "Hyper-V VP_INDEX MSR "
698 "(requested by 'hv-vpindex' cpu flag) "
699 "is not supported by kernel\n");
700 return -ENOSYS;
702 env->features[FEAT_HYPERV_EAX] |= HV_VP_INDEX_AVAILABLE;
704 if (cpu->hyperv_runtime) {
705 if (!has_msr_hv_runtime) {
706 fprintf(stderr, "Hyper-V VP_RUNTIME MSR "
707 "(requested by 'hv-runtime' cpu flag) "
708 "is not supported by kernel\n");
709 return -ENOSYS;
711 env->features[FEAT_HYPERV_EAX] |= HV_VP_RUNTIME_AVAILABLE;
713 if (cpu->hyperv_synic) {
714 if (!has_msr_hv_synic ||
715 kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_SYNIC, 0)) {
716 fprintf(stderr, "Hyper-V SynIC is not supported by kernel\n");
717 return -ENOSYS;
720 env->features[FEAT_HYPERV_EAX] |= HV_SYNIC_AVAILABLE;
722 if (cpu->hyperv_stimer) {
723 if (!has_msr_hv_stimer) {
724 fprintf(stderr, "Hyper-V timers aren't supported by kernel\n");
725 return -ENOSYS;
727 env->features[FEAT_HYPERV_EAX] |= HV_SYNTIMERS_AVAILABLE;
729 return 0;
732 static Error *invtsc_mig_blocker;
734 #define KVM_MAX_CPUID_ENTRIES 100
736 int kvm_arch_init_vcpu(CPUState *cs)
738 struct {
739 struct kvm_cpuid2 cpuid;
740 struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
741 } QEMU_PACKED cpuid_data;
742 X86CPU *cpu = X86_CPU(cs);
743 CPUX86State *env = &cpu->env;
744 uint32_t limit, i, j, cpuid_i;
745 uint32_t unused;
746 struct kvm_cpuid_entry2 *c;
747 uint32_t signature[3];
748 int kvm_base = KVM_CPUID_SIGNATURE;
749 int r;
750 Error *local_err = NULL;
752 memset(&cpuid_data, 0, sizeof(cpuid_data));
754 cpuid_i = 0;
756 r = kvm_arch_set_tsc_khz(cs);
757 if (r < 0) {
758 goto fail;
761 /* vcpu's TSC frequency is either specified by user, or following
762 * the value used by KVM if the former is not present. In the
763 * latter case, we query it from KVM and record in env->tsc_khz,
764 * so that vcpu's TSC frequency can be migrated later via this field.
766 if (!env->tsc_khz) {
767 r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
768 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
769 -ENOTSUP;
770 if (r > 0) {
771 env->tsc_khz = r;
775 /* Paravirtualization CPUIDs */
776 if (hyperv_enabled(cpu)) {
777 c = &cpuid_data.entries[cpuid_i++];
778 c->function = HV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
779 if (!cpu->hyperv_vendor_id) {
780 memcpy(signature, "Microsoft Hv", 12);
781 } else {
782 size_t len = strlen(cpu->hyperv_vendor_id);
784 if (len > 12) {
785 error_report("hv-vendor-id truncated to 12 characters");
786 len = 12;
788 memset(signature, 0, 12);
789 memcpy(signature, cpu->hyperv_vendor_id, len);
791 c->eax = HV_CPUID_MIN;
792 c->ebx = signature[0];
793 c->ecx = signature[1];
794 c->edx = signature[2];
796 c = &cpuid_data.entries[cpuid_i++];
797 c->function = HV_CPUID_INTERFACE;
798 memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
799 c->eax = signature[0];
800 c->ebx = 0;
801 c->ecx = 0;
802 c->edx = 0;
804 c = &cpuid_data.entries[cpuid_i++];
805 c->function = HV_CPUID_VERSION;
806 c->eax = 0x00001bbc;
807 c->ebx = 0x00060001;
809 c = &cpuid_data.entries[cpuid_i++];
810 c->function = HV_CPUID_FEATURES;
811 r = hyperv_handle_properties(cs);
812 if (r) {
813 return r;
815 c->eax = env->features[FEAT_HYPERV_EAX];
816 c->ebx = env->features[FEAT_HYPERV_EBX];
817 c->edx = env->features[FEAT_HYPERV_EDX];
819 c = &cpuid_data.entries[cpuid_i++];
820 c->function = HV_CPUID_ENLIGHTMENT_INFO;
821 if (cpu->hyperv_relaxed_timing) {
822 c->eax |= HV_RELAXED_TIMING_RECOMMENDED;
824 if (cpu->hyperv_vapic) {
825 c->eax |= HV_APIC_ACCESS_RECOMMENDED;
827 c->ebx = cpu->hyperv_spinlock_attempts;
829 c = &cpuid_data.entries[cpuid_i++];
830 c->function = HV_CPUID_IMPLEMENT_LIMITS;
832 c->eax = cpu->hv_max_vps;
833 c->ebx = 0x40;
835 kvm_base = KVM_CPUID_SIGNATURE_NEXT;
836 has_msr_hv_hypercall = true;
839 if (cpu->expose_kvm) {
840 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
841 c = &cpuid_data.entries[cpuid_i++];
842 c->function = KVM_CPUID_SIGNATURE | kvm_base;
843 c->eax = KVM_CPUID_FEATURES | kvm_base;
844 c->ebx = signature[0];
845 c->ecx = signature[1];
846 c->edx = signature[2];
848 c = &cpuid_data.entries[cpuid_i++];
849 c->function = KVM_CPUID_FEATURES | kvm_base;
850 c->eax = env->features[FEAT_KVM];
851 c->edx = env->features[FEAT_KVM_HINTS];
854 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
856 for (i = 0; i <= limit; i++) {
857 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
858 fprintf(stderr, "unsupported level value: 0x%x\n", limit);
859 abort();
861 c = &cpuid_data.entries[cpuid_i++];
863 switch (i) {
864 case 2: {
865 /* Keep reading function 2 till all the input is received */
866 int times;
868 c->function = i;
869 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
870 KVM_CPUID_FLAG_STATE_READ_NEXT;
871 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
872 times = c->eax & 0xff;
874 for (j = 1; j < times; ++j) {
875 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
876 fprintf(stderr, "cpuid_data is full, no space for "
877 "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
878 abort();
880 c = &cpuid_data.entries[cpuid_i++];
881 c->function = i;
882 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
883 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
885 break;
887 case 4:
888 case 0xb:
889 case 0xd:
890 for (j = 0; ; j++) {
891 if (i == 0xd && j == 64) {
892 break;
894 c->function = i;
895 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
896 c->index = j;
897 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
899 if (i == 4 && c->eax == 0) {
900 break;
902 if (i == 0xb && !(c->ecx & 0xff00)) {
903 break;
905 if (i == 0xd && c->eax == 0) {
906 continue;
908 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
909 fprintf(stderr, "cpuid_data is full, no space for "
910 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
911 abort();
913 c = &cpuid_data.entries[cpuid_i++];
915 break;
916 case 0x14: {
917 uint32_t times;
919 c->function = i;
920 c->index = 0;
921 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
922 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
923 times = c->eax;
925 for (j = 1; j <= times; ++j) {
926 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
927 fprintf(stderr, "cpuid_data is full, no space for "
928 "cpuid(eax:0x14,ecx:0x%x)\n", j);
929 abort();
931 c = &cpuid_data.entries[cpuid_i++];
932 c->function = i;
933 c->index = j;
934 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
935 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
937 break;
939 default:
940 c->function = i;
941 c->flags = 0;
942 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
943 break;
947 if (limit >= 0x0a) {
948 uint32_t eax, edx;
950 cpu_x86_cpuid(env, 0x0a, 0, &eax, &unused, &unused, &edx);
952 has_architectural_pmu_version = eax & 0xff;
953 if (has_architectural_pmu_version > 0) {
954 num_architectural_pmu_gp_counters = (eax & 0xff00) >> 8;
956 /* Shouldn't be more than 32, since that's the number of bits
957 * available in EBX to tell us _which_ counters are available.
958 * Play it safe.
960 if (num_architectural_pmu_gp_counters > MAX_GP_COUNTERS) {
961 num_architectural_pmu_gp_counters = MAX_GP_COUNTERS;
964 if (has_architectural_pmu_version > 1) {
965 num_architectural_pmu_fixed_counters = edx & 0x1f;
967 if (num_architectural_pmu_fixed_counters > MAX_FIXED_COUNTERS) {
968 num_architectural_pmu_fixed_counters = MAX_FIXED_COUNTERS;
974 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
976 for (i = 0x80000000; i <= limit; i++) {
977 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
978 fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
979 abort();
981 c = &cpuid_data.entries[cpuid_i++];
983 c->function = i;
984 c->flags = 0;
985 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
988 /* Call Centaur's CPUID instructions they are supported. */
989 if (env->cpuid_xlevel2 > 0) {
990 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
992 for (i = 0xC0000000; i <= limit; i++) {
993 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
994 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
995 abort();
997 c = &cpuid_data.entries[cpuid_i++];
999 c->function = i;
1000 c->flags = 0;
1001 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1005 cpuid_data.cpuid.nent = cpuid_i;
1007 if (((env->cpuid_version >> 8)&0xF) >= 6
1008 && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
1009 (CPUID_MCE | CPUID_MCA)
1010 && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
1011 uint64_t mcg_cap, unsupported_caps;
1012 int banks;
1013 int ret;
1015 ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
1016 if (ret < 0) {
1017 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
1018 return ret;
1021 if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
1022 error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
1023 (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
1024 return -ENOTSUP;
1027 unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
1028 if (unsupported_caps) {
1029 if (unsupported_caps & MCG_LMCE_P) {
1030 error_report("kvm: LMCE not supported");
1031 return -ENOTSUP;
1033 warn_report("Unsupported MCG_CAP bits: 0x%" PRIx64,
1034 unsupported_caps);
1037 env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
1038 ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
1039 if (ret < 0) {
1040 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
1041 return ret;
1045 qemu_add_vm_change_state_handler(cpu_update_state, env);
1047 c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
1048 if (c) {
1049 has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
1050 !!(c->ecx & CPUID_EXT_SMX);
1053 if (env->mcg_cap & MCG_LMCE_P) {
1054 has_msr_mcg_ext_ctl = has_msr_feature_control = true;
1057 if (!env->user_tsc_khz) {
1058 if ((env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC) &&
1059 invtsc_mig_blocker == NULL) {
1060 /* for migration */
1061 error_setg(&invtsc_mig_blocker,
1062 "State blocked by non-migratable CPU device"
1063 " (invtsc flag)");
1064 r = migrate_add_blocker(invtsc_mig_blocker, &local_err);
1065 if (local_err) {
1066 error_report_err(local_err);
1067 error_free(invtsc_mig_blocker);
1068 goto fail;
1070 /* for savevm */
1071 vmstate_x86_cpu.unmigratable = 1;
1075 if (cpu->vmware_cpuid_freq
1076 /* Guests depend on 0x40000000 to detect this feature, so only expose
1077 * it if KVM exposes leaf 0x40000000. (Conflicts with Hyper-V) */
1078 && cpu->expose_kvm
1079 && kvm_base == KVM_CPUID_SIGNATURE
1080 /* TSC clock must be stable and known for this feature. */
1081 && tsc_is_stable_and_known(env)) {
1083 c = &cpuid_data.entries[cpuid_i++];
1084 c->function = KVM_CPUID_SIGNATURE | 0x10;
1085 c->eax = env->tsc_khz;
1086 /* LAPIC resolution of 1ns (freq: 1GHz) is hardcoded in KVM's
1087 * APIC_BUS_CYCLE_NS */
1088 c->ebx = 1000000;
1089 c->ecx = c->edx = 0;
1091 c = cpuid_find_entry(&cpuid_data.cpuid, kvm_base, 0);
1092 c->eax = MAX(c->eax, KVM_CPUID_SIGNATURE | 0x10);
1095 cpuid_data.cpuid.nent = cpuid_i;
1097 cpuid_data.cpuid.padding = 0;
1098 r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
1099 if (r) {
1100 goto fail;
1103 if (has_xsave) {
1104 env->kvm_xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
1106 cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
1108 if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
1109 has_msr_tsc_aux = false;
1112 return 0;
1114 fail:
1115 migrate_del_blocker(invtsc_mig_blocker);
1116 return r;
1119 void kvm_arch_reset_vcpu(X86CPU *cpu)
1121 CPUX86State *env = &cpu->env;
1123 env->xcr0 = 1;
1124 if (kvm_irqchip_in_kernel()) {
1125 env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
1126 KVM_MP_STATE_UNINITIALIZED;
1127 } else {
1128 env->mp_state = KVM_MP_STATE_RUNNABLE;
1131 if (cpu->hyperv_synic) {
1132 int i;
1133 for (i = 0; i < ARRAY_SIZE(env->msr_hv_synic_sint); i++) {
1134 env->msr_hv_synic_sint[i] = HV_SINT_MASKED;
1139 void kvm_arch_do_init_vcpu(X86CPU *cpu)
1141 CPUX86State *env = &cpu->env;
1143 /* APs get directly into wait-for-SIPI state. */
1144 if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
1145 env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
1149 static int kvm_get_supported_msrs(KVMState *s)
1151 static int kvm_supported_msrs;
1152 int ret = 0;
1154 /* first time */
1155 if (kvm_supported_msrs == 0) {
1156 struct kvm_msr_list msr_list, *kvm_msr_list;
1158 kvm_supported_msrs = -1;
1160 /* Obtain MSR list from KVM. These are the MSRs that we must
1161 * save/restore */
1162 msr_list.nmsrs = 0;
1163 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
1164 if (ret < 0 && ret != -E2BIG) {
1165 return ret;
1167 /* Old kernel modules had a bug and could write beyond the provided
1168 memory. Allocate at least a safe amount of 1K. */
1169 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
1170 msr_list.nmsrs *
1171 sizeof(msr_list.indices[0])));
1173 kvm_msr_list->nmsrs = msr_list.nmsrs;
1174 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
1175 if (ret >= 0) {
1176 int i;
1178 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
1179 switch (kvm_msr_list->indices[i]) {
1180 case MSR_STAR:
1181 has_msr_star = true;
1182 break;
1183 case MSR_VM_HSAVE_PA:
1184 has_msr_hsave_pa = true;
1185 break;
1186 case MSR_TSC_AUX:
1187 has_msr_tsc_aux = true;
1188 break;
1189 case MSR_TSC_ADJUST:
1190 has_msr_tsc_adjust = true;
1191 break;
1192 case MSR_IA32_TSCDEADLINE:
1193 has_msr_tsc_deadline = true;
1194 break;
1195 case MSR_IA32_SMBASE:
1196 has_msr_smbase = true;
1197 break;
1198 case MSR_SMI_COUNT:
1199 has_msr_smi_count = true;
1200 break;
1201 case MSR_IA32_MISC_ENABLE:
1202 has_msr_misc_enable = true;
1203 break;
1204 case MSR_IA32_BNDCFGS:
1205 has_msr_bndcfgs = true;
1206 break;
1207 case MSR_IA32_XSS:
1208 has_msr_xss = true;
1209 break;
1210 case HV_X64_MSR_CRASH_CTL:
1211 has_msr_hv_crash = true;
1212 break;
1213 case HV_X64_MSR_RESET:
1214 has_msr_hv_reset = true;
1215 break;
1216 case HV_X64_MSR_VP_INDEX:
1217 has_msr_hv_vpindex = true;
1218 break;
1219 case HV_X64_MSR_VP_RUNTIME:
1220 has_msr_hv_runtime = true;
1221 break;
1222 case HV_X64_MSR_SCONTROL:
1223 has_msr_hv_synic = true;
1224 break;
1225 case HV_X64_MSR_STIMER0_CONFIG:
1226 has_msr_hv_stimer = true;
1227 break;
1228 case HV_X64_MSR_TSC_FREQUENCY:
1229 has_msr_hv_frequencies = true;
1230 break;
1231 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
1232 has_msr_hv_reenlightenment = true;
1233 break;
1234 case MSR_IA32_SPEC_CTRL:
1235 has_msr_spec_ctrl = true;
1236 break;
1237 case MSR_VIRT_SSBD:
1238 has_msr_virt_ssbd = true;
1239 break;
1244 g_free(kvm_msr_list);
1247 return ret;
1250 static Notifier smram_machine_done;
1251 static KVMMemoryListener smram_listener;
1252 static AddressSpace smram_address_space;
1253 static MemoryRegion smram_as_root;
1254 static MemoryRegion smram_as_mem;
1256 static void register_smram_listener(Notifier *n, void *unused)
1258 MemoryRegion *smram =
1259 (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
1261 /* Outer container... */
1262 memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
1263 memory_region_set_enabled(&smram_as_root, true);
1265 /* ... with two regions inside: normal system memory with low
1266 * priority, and...
1268 memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
1269 get_system_memory(), 0, ~0ull);
1270 memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
1271 memory_region_set_enabled(&smram_as_mem, true);
1273 if (smram) {
1274 /* ... SMRAM with higher priority */
1275 memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
1276 memory_region_set_enabled(smram, true);
1279 address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
1280 kvm_memory_listener_register(kvm_state, &smram_listener,
1281 &smram_address_space, 1);
1284 int kvm_arch_init(MachineState *ms, KVMState *s)
1286 uint64_t identity_base = 0xfffbc000;
1287 uint64_t shadow_mem;
1288 int ret;
1289 struct utsname utsname;
1291 #ifdef KVM_CAP_XSAVE
1292 has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1293 #endif
1295 #ifdef KVM_CAP_XCRS
1296 has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1297 #endif
1299 #ifdef KVM_CAP_PIT_STATE2
1300 has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1301 #endif
1303 ret = kvm_get_supported_msrs(s);
1304 if (ret < 0) {
1305 return ret;
1308 uname(&utsname);
1309 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
1312 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
1313 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
1314 * Since these must be part of guest physical memory, we need to allocate
1315 * them, both by setting their start addresses in the kernel and by
1316 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
1318 * Older KVM versions may not support setting the identity map base. In
1319 * that case we need to stick with the default, i.e. a 256K maximum BIOS
1320 * size.
1322 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
1323 /* Allows up to 16M BIOSes. */
1324 identity_base = 0xfeffc000;
1326 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
1327 if (ret < 0) {
1328 return ret;
1332 /* Set TSS base one page after EPT identity map. */
1333 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
1334 if (ret < 0) {
1335 return ret;
1338 /* Tell fw_cfg to notify the BIOS to reserve the range. */
1339 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
1340 if (ret < 0) {
1341 fprintf(stderr, "e820_add_entry() table is full\n");
1342 return ret;
1344 qemu_register_reset(kvm_unpoison_all, NULL);
1346 shadow_mem = machine_kvm_shadow_mem(ms);
1347 if (shadow_mem != -1) {
1348 shadow_mem /= 4096;
1349 ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
1350 if (ret < 0) {
1351 return ret;
1355 if (kvm_check_extension(s, KVM_CAP_X86_SMM) &&
1356 object_dynamic_cast(OBJECT(ms), TYPE_PC_MACHINE) &&
1357 pc_machine_is_smm_enabled(PC_MACHINE(ms))) {
1358 smram_machine_done.notify = register_smram_listener;
1359 qemu_add_machine_init_done_notifier(&smram_machine_done);
1361 return 0;
1364 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1366 lhs->selector = rhs->selector;
1367 lhs->base = rhs->base;
1368 lhs->limit = rhs->limit;
1369 lhs->type = 3;
1370 lhs->present = 1;
1371 lhs->dpl = 3;
1372 lhs->db = 0;
1373 lhs->s = 1;
1374 lhs->l = 0;
1375 lhs->g = 0;
1376 lhs->avl = 0;
1377 lhs->unusable = 0;
1380 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1382 unsigned flags = rhs->flags;
1383 lhs->selector = rhs->selector;
1384 lhs->base = rhs->base;
1385 lhs->limit = rhs->limit;
1386 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
1387 lhs->present = (flags & DESC_P_MASK) != 0;
1388 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
1389 lhs->db = (flags >> DESC_B_SHIFT) & 1;
1390 lhs->s = (flags & DESC_S_MASK) != 0;
1391 lhs->l = (flags >> DESC_L_SHIFT) & 1;
1392 lhs->g = (flags & DESC_G_MASK) != 0;
1393 lhs->avl = (flags & DESC_AVL_MASK) != 0;
1394 lhs->unusable = !lhs->present;
1395 lhs->padding = 0;
1398 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
1400 lhs->selector = rhs->selector;
1401 lhs->base = rhs->base;
1402 lhs->limit = rhs->limit;
1403 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
1404 ((rhs->present && !rhs->unusable) * DESC_P_MASK) |
1405 (rhs->dpl << DESC_DPL_SHIFT) |
1406 (rhs->db << DESC_B_SHIFT) |
1407 (rhs->s * DESC_S_MASK) |
1408 (rhs->l << DESC_L_SHIFT) |
1409 (rhs->g * DESC_G_MASK) |
1410 (rhs->avl * DESC_AVL_MASK);
1413 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
1415 if (set) {
1416 *kvm_reg = *qemu_reg;
1417 } else {
1418 *qemu_reg = *kvm_reg;
1422 static int kvm_getput_regs(X86CPU *cpu, int set)
1424 CPUX86State *env = &cpu->env;
1425 struct kvm_regs regs;
1426 int ret = 0;
1428 if (!set) {
1429 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
1430 if (ret < 0) {
1431 return ret;
1435 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
1436 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
1437 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
1438 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
1439 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
1440 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
1441 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
1442 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
1443 #ifdef TARGET_X86_64
1444 kvm_getput_reg(&regs.r8, &env->regs[8], set);
1445 kvm_getput_reg(&regs.r9, &env->regs[9], set);
1446 kvm_getput_reg(&regs.r10, &env->regs[10], set);
1447 kvm_getput_reg(&regs.r11, &env->regs[11], set);
1448 kvm_getput_reg(&regs.r12, &env->regs[12], set);
1449 kvm_getput_reg(&regs.r13, &env->regs[13], set);
1450 kvm_getput_reg(&regs.r14, &env->regs[14], set);
1451 kvm_getput_reg(&regs.r15, &env->regs[15], set);
1452 #endif
1454 kvm_getput_reg(&regs.rflags, &env->eflags, set);
1455 kvm_getput_reg(&regs.rip, &env->eip, set);
1457 if (set) {
1458 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
1461 return ret;
1464 static int kvm_put_fpu(X86CPU *cpu)
1466 CPUX86State *env = &cpu->env;
1467 struct kvm_fpu fpu;
1468 int i;
1470 memset(&fpu, 0, sizeof fpu);
1471 fpu.fsw = env->fpus & ~(7 << 11);
1472 fpu.fsw |= (env->fpstt & 7) << 11;
1473 fpu.fcw = env->fpuc;
1474 fpu.last_opcode = env->fpop;
1475 fpu.last_ip = env->fpip;
1476 fpu.last_dp = env->fpdp;
1477 for (i = 0; i < 8; ++i) {
1478 fpu.ftwx |= (!env->fptags[i]) << i;
1480 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
1481 for (i = 0; i < CPU_NB_REGS; i++) {
1482 stq_p(&fpu.xmm[i][0], env->xmm_regs[i].ZMM_Q(0));
1483 stq_p(&fpu.xmm[i][8], env->xmm_regs[i].ZMM_Q(1));
1485 fpu.mxcsr = env->mxcsr;
1487 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
1490 #define XSAVE_FCW_FSW 0
1491 #define XSAVE_FTW_FOP 1
1492 #define XSAVE_CWD_RIP 2
1493 #define XSAVE_CWD_RDP 4
1494 #define XSAVE_MXCSR 6
1495 #define XSAVE_ST_SPACE 8
1496 #define XSAVE_XMM_SPACE 40
1497 #define XSAVE_XSTATE_BV 128
1498 #define XSAVE_YMMH_SPACE 144
1499 #define XSAVE_BNDREGS 240
1500 #define XSAVE_BNDCSR 256
1501 #define XSAVE_OPMASK 272
1502 #define XSAVE_ZMM_Hi256 288
1503 #define XSAVE_Hi16_ZMM 416
1504 #define XSAVE_PKRU 672
1506 #define XSAVE_BYTE_OFFSET(word_offset) \
1507 ((word_offset) * sizeof(((struct kvm_xsave *)0)->region[0]))
1509 #define ASSERT_OFFSET(word_offset, field) \
1510 QEMU_BUILD_BUG_ON(XSAVE_BYTE_OFFSET(word_offset) != \
1511 offsetof(X86XSaveArea, field))
1513 ASSERT_OFFSET(XSAVE_FCW_FSW, legacy.fcw);
1514 ASSERT_OFFSET(XSAVE_FTW_FOP, legacy.ftw);
1515 ASSERT_OFFSET(XSAVE_CWD_RIP, legacy.fpip);
1516 ASSERT_OFFSET(XSAVE_CWD_RDP, legacy.fpdp);
1517 ASSERT_OFFSET(XSAVE_MXCSR, legacy.mxcsr);
1518 ASSERT_OFFSET(XSAVE_ST_SPACE, legacy.fpregs);
1519 ASSERT_OFFSET(XSAVE_XMM_SPACE, legacy.xmm_regs);
1520 ASSERT_OFFSET(XSAVE_XSTATE_BV, header.xstate_bv);
1521 ASSERT_OFFSET(XSAVE_YMMH_SPACE, avx_state);
1522 ASSERT_OFFSET(XSAVE_BNDREGS, bndreg_state);
1523 ASSERT_OFFSET(XSAVE_BNDCSR, bndcsr_state);
1524 ASSERT_OFFSET(XSAVE_OPMASK, opmask_state);
1525 ASSERT_OFFSET(XSAVE_ZMM_Hi256, zmm_hi256_state);
1526 ASSERT_OFFSET(XSAVE_Hi16_ZMM, hi16_zmm_state);
1527 ASSERT_OFFSET(XSAVE_PKRU, pkru_state);
1529 static int kvm_put_xsave(X86CPU *cpu)
1531 CPUX86State *env = &cpu->env;
1532 X86XSaveArea *xsave = env->kvm_xsave_buf;
1534 if (!has_xsave) {
1535 return kvm_put_fpu(cpu);
1537 x86_cpu_xsave_all_areas(cpu, xsave);
1539 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
1542 static int kvm_put_xcrs(X86CPU *cpu)
1544 CPUX86State *env = &cpu->env;
1545 struct kvm_xcrs xcrs = {};
1547 if (!has_xcrs) {
1548 return 0;
1551 xcrs.nr_xcrs = 1;
1552 xcrs.flags = 0;
1553 xcrs.xcrs[0].xcr = 0;
1554 xcrs.xcrs[0].value = env->xcr0;
1555 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
1558 static int kvm_put_sregs(X86CPU *cpu)
1560 CPUX86State *env = &cpu->env;
1561 struct kvm_sregs sregs;
1563 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
1564 if (env->interrupt_injected >= 0) {
1565 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
1566 (uint64_t)1 << (env->interrupt_injected % 64);
1569 if ((env->eflags & VM_MASK)) {
1570 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
1571 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
1572 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
1573 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
1574 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
1575 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
1576 } else {
1577 set_seg(&sregs.cs, &env->segs[R_CS]);
1578 set_seg(&sregs.ds, &env->segs[R_DS]);
1579 set_seg(&sregs.es, &env->segs[R_ES]);
1580 set_seg(&sregs.fs, &env->segs[R_FS]);
1581 set_seg(&sregs.gs, &env->segs[R_GS]);
1582 set_seg(&sregs.ss, &env->segs[R_SS]);
1585 set_seg(&sregs.tr, &env->tr);
1586 set_seg(&sregs.ldt, &env->ldt);
1588 sregs.idt.limit = env->idt.limit;
1589 sregs.idt.base = env->idt.base;
1590 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
1591 sregs.gdt.limit = env->gdt.limit;
1592 sregs.gdt.base = env->gdt.base;
1593 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
1595 sregs.cr0 = env->cr[0];
1596 sregs.cr2 = env->cr[2];
1597 sregs.cr3 = env->cr[3];
1598 sregs.cr4 = env->cr[4];
1600 sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
1601 sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
1603 sregs.efer = env->efer;
1605 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
1608 static void kvm_msr_buf_reset(X86CPU *cpu)
1610 memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
1613 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
1615 struct kvm_msrs *msrs = cpu->kvm_msr_buf;
1616 void *limit = ((void *)msrs) + MSR_BUF_SIZE;
1617 struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
1619 assert((void *)(entry + 1) <= limit);
1621 entry->index = index;
1622 entry->reserved = 0;
1623 entry->data = value;
1624 msrs->nmsrs++;
1627 static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
1629 kvm_msr_buf_reset(cpu);
1630 kvm_msr_entry_add(cpu, index, value);
1632 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1635 void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
1637 int ret;
1639 ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
1640 assert(ret == 1);
1643 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
1645 CPUX86State *env = &cpu->env;
1646 int ret;
1648 if (!has_msr_tsc_deadline) {
1649 return 0;
1652 ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
1653 if (ret < 0) {
1654 return ret;
1657 assert(ret == 1);
1658 return 0;
1662 * Provide a separate write service for the feature control MSR in order to
1663 * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
1664 * before writing any other state because forcibly leaving nested mode
1665 * invalidates the VCPU state.
1667 static int kvm_put_msr_feature_control(X86CPU *cpu)
1669 int ret;
1671 if (!has_msr_feature_control) {
1672 return 0;
1675 ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
1676 cpu->env.msr_ia32_feature_control);
1677 if (ret < 0) {
1678 return ret;
1681 assert(ret == 1);
1682 return 0;
1685 static int kvm_put_msrs(X86CPU *cpu, int level)
1687 CPUX86State *env = &cpu->env;
1688 int i;
1689 int ret;
1691 kvm_msr_buf_reset(cpu);
1693 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
1694 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
1695 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
1696 kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
1697 if (has_msr_star) {
1698 kvm_msr_entry_add(cpu, MSR_STAR, env->star);
1700 if (has_msr_hsave_pa) {
1701 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
1703 if (has_msr_tsc_aux) {
1704 kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
1706 if (has_msr_tsc_adjust) {
1707 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
1709 if (has_msr_misc_enable) {
1710 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
1711 env->msr_ia32_misc_enable);
1713 if (has_msr_smbase) {
1714 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
1716 if (has_msr_smi_count) {
1717 kvm_msr_entry_add(cpu, MSR_SMI_COUNT, env->msr_smi_count);
1719 if (has_msr_bndcfgs) {
1720 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
1722 if (has_msr_xss) {
1723 kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
1725 if (has_msr_spec_ctrl) {
1726 kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, env->spec_ctrl);
1728 if (has_msr_virt_ssbd) {
1729 kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, env->virt_ssbd);
1732 #ifdef TARGET_X86_64
1733 if (lm_capable_kernel) {
1734 kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
1735 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
1736 kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
1737 kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
1739 #endif
1742 * The following MSRs have side effects on the guest or are too heavy
1743 * for normal writeback. Limit them to reset or full state updates.
1745 if (level >= KVM_PUT_RESET_STATE) {
1746 kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
1747 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
1748 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
1749 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
1750 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
1752 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
1753 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
1755 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
1756 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
1758 if (has_architectural_pmu_version > 0) {
1759 if (has_architectural_pmu_version > 1) {
1760 /* Stop the counter. */
1761 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
1762 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
1765 /* Set the counter values. */
1766 for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
1767 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
1768 env->msr_fixed_counters[i]);
1770 for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
1771 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
1772 env->msr_gp_counters[i]);
1773 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
1774 env->msr_gp_evtsel[i]);
1776 if (has_architectural_pmu_version > 1) {
1777 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
1778 env->msr_global_status);
1779 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1780 env->msr_global_ovf_ctrl);
1782 /* Now start the PMU. */
1783 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
1784 env->msr_fixed_ctr_ctrl);
1785 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
1786 env->msr_global_ctrl);
1790 * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,
1791 * only sync them to KVM on the first cpu
1793 if (current_cpu == first_cpu) {
1794 if (has_msr_hv_hypercall) {
1795 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
1796 env->msr_hv_guest_os_id);
1797 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
1798 env->msr_hv_hypercall);
1800 if (cpu->hyperv_time) {
1801 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,
1802 env->msr_hv_tsc);
1804 if (cpu->hyperv_reenlightenment) {
1805 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL,
1806 env->msr_hv_reenlightenment_control);
1807 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL,
1808 env->msr_hv_tsc_emulation_control);
1809 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS,
1810 env->msr_hv_tsc_emulation_status);
1813 if (cpu->hyperv_vapic) {
1814 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
1815 env->msr_hv_vapic);
1817 if (has_msr_hv_crash) {
1818 int j;
1820 for (j = 0; j < HV_CRASH_PARAMS; j++)
1821 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
1822 env->msr_hv_crash_params[j]);
1824 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);
1826 if (has_msr_hv_runtime) {
1827 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
1829 if (cpu->hyperv_synic) {
1830 int j;
1832 kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);
1834 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
1835 env->msr_hv_synic_control);
1836 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
1837 env->msr_hv_synic_evt_page);
1838 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
1839 env->msr_hv_synic_msg_page);
1841 for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
1842 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
1843 env->msr_hv_synic_sint[j]);
1846 if (has_msr_hv_stimer) {
1847 int j;
1849 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
1850 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
1851 env->msr_hv_stimer_config[j]);
1854 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
1855 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
1856 env->msr_hv_stimer_count[j]);
1859 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
1860 uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
1862 kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
1863 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
1864 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
1865 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
1866 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
1867 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
1868 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
1869 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
1870 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
1871 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
1872 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
1873 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
1874 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
1875 /* The CPU GPs if we write to a bit above the physical limit of
1876 * the host CPU (and KVM emulates that)
1878 uint64_t mask = env->mtrr_var[i].mask;
1879 mask &= phys_mask;
1881 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
1882 env->mtrr_var[i].base);
1883 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
1886 if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
1887 int addr_num = kvm_arch_get_supported_cpuid(kvm_state,
1888 0x14, 1, R_EAX) & 0x7;
1890 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL,
1891 env->msr_rtit_ctrl);
1892 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS,
1893 env->msr_rtit_status);
1894 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE,
1895 env->msr_rtit_output_base);
1896 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK,
1897 env->msr_rtit_output_mask);
1898 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH,
1899 env->msr_rtit_cr3_match);
1900 for (i = 0; i < addr_num; i++) {
1901 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i,
1902 env->msr_rtit_addrs[i]);
1906 /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
1907 * kvm_put_msr_feature_control. */
1909 if (env->mcg_cap) {
1910 int i;
1912 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
1913 kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
1914 if (has_msr_mcg_ext_ctl) {
1915 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
1917 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1918 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
1922 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1923 if (ret < 0) {
1924 return ret;
1927 if (ret < cpu->kvm_msr_buf->nmsrs) {
1928 struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
1929 error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,
1930 (uint32_t)e->index, (uint64_t)e->data);
1933 assert(ret == cpu->kvm_msr_buf->nmsrs);
1934 return 0;
1938 static int kvm_get_fpu(X86CPU *cpu)
1940 CPUX86State *env = &cpu->env;
1941 struct kvm_fpu fpu;
1942 int i, ret;
1944 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
1945 if (ret < 0) {
1946 return ret;
1949 env->fpstt = (fpu.fsw >> 11) & 7;
1950 env->fpus = fpu.fsw;
1951 env->fpuc = fpu.fcw;
1952 env->fpop = fpu.last_opcode;
1953 env->fpip = fpu.last_ip;
1954 env->fpdp = fpu.last_dp;
1955 for (i = 0; i < 8; ++i) {
1956 env->fptags[i] = !((fpu.ftwx >> i) & 1);
1958 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
1959 for (i = 0; i < CPU_NB_REGS; i++) {
1960 env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
1961 env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
1963 env->mxcsr = fpu.mxcsr;
1965 return 0;
1968 static int kvm_get_xsave(X86CPU *cpu)
1970 CPUX86State *env = &cpu->env;
1971 X86XSaveArea *xsave = env->kvm_xsave_buf;
1972 int ret;
1974 if (!has_xsave) {
1975 return kvm_get_fpu(cpu);
1978 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
1979 if (ret < 0) {
1980 return ret;
1982 x86_cpu_xrstor_all_areas(cpu, xsave);
1984 return 0;
1987 static int kvm_get_xcrs(X86CPU *cpu)
1989 CPUX86State *env = &cpu->env;
1990 int i, ret;
1991 struct kvm_xcrs xcrs;
1993 if (!has_xcrs) {
1994 return 0;
1997 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
1998 if (ret < 0) {
1999 return ret;
2002 for (i = 0; i < xcrs.nr_xcrs; i++) {
2003 /* Only support xcr0 now */
2004 if (xcrs.xcrs[i].xcr == 0) {
2005 env->xcr0 = xcrs.xcrs[i].value;
2006 break;
2009 return 0;
2012 static int kvm_get_sregs(X86CPU *cpu)
2014 CPUX86State *env = &cpu->env;
2015 struct kvm_sregs sregs;
2016 int bit, i, ret;
2018 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
2019 if (ret < 0) {
2020 return ret;
2023 /* There can only be one pending IRQ set in the bitmap at a time, so try
2024 to find it and save its number instead (-1 for none). */
2025 env->interrupt_injected = -1;
2026 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
2027 if (sregs.interrupt_bitmap[i]) {
2028 bit = ctz64(sregs.interrupt_bitmap[i]);
2029 env->interrupt_injected = i * 64 + bit;
2030 break;
2034 get_seg(&env->segs[R_CS], &sregs.cs);
2035 get_seg(&env->segs[R_DS], &sregs.ds);
2036 get_seg(&env->segs[R_ES], &sregs.es);
2037 get_seg(&env->segs[R_FS], &sregs.fs);
2038 get_seg(&env->segs[R_GS], &sregs.gs);
2039 get_seg(&env->segs[R_SS], &sregs.ss);
2041 get_seg(&env->tr, &sregs.tr);
2042 get_seg(&env->ldt, &sregs.ldt);
2044 env->idt.limit = sregs.idt.limit;
2045 env->idt.base = sregs.idt.base;
2046 env->gdt.limit = sregs.gdt.limit;
2047 env->gdt.base = sregs.gdt.base;
2049 env->cr[0] = sregs.cr0;
2050 env->cr[2] = sregs.cr2;
2051 env->cr[3] = sregs.cr3;
2052 env->cr[4] = sregs.cr4;
2054 env->efer = sregs.efer;
2056 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
2057 x86_update_hflags(env);
2059 return 0;
2062 static int kvm_get_msrs(X86CPU *cpu)
2064 CPUX86State *env = &cpu->env;
2065 struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
2066 int ret, i;
2067 uint64_t mtrr_top_bits;
2069 kvm_msr_buf_reset(cpu);
2071 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
2072 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
2073 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
2074 kvm_msr_entry_add(cpu, MSR_PAT, 0);
2075 if (has_msr_star) {
2076 kvm_msr_entry_add(cpu, MSR_STAR, 0);
2078 if (has_msr_hsave_pa) {
2079 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
2081 if (has_msr_tsc_aux) {
2082 kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
2084 if (has_msr_tsc_adjust) {
2085 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
2087 if (has_msr_tsc_deadline) {
2088 kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
2090 if (has_msr_misc_enable) {
2091 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
2093 if (has_msr_smbase) {
2094 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
2096 if (has_msr_smi_count) {
2097 kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
2099 if (has_msr_feature_control) {
2100 kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
2102 if (has_msr_bndcfgs) {
2103 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
2105 if (has_msr_xss) {
2106 kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
2108 if (has_msr_spec_ctrl) {
2109 kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
2111 if (has_msr_virt_ssbd) {
2112 kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, 0);
2114 if (!env->tsc_valid) {
2115 kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
2116 env->tsc_valid = !runstate_is_running();
2119 #ifdef TARGET_X86_64
2120 if (lm_capable_kernel) {
2121 kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
2122 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
2123 kvm_msr_entry_add(cpu, MSR_FMASK, 0);
2124 kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
2126 #endif
2127 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
2128 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
2129 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
2130 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
2132 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
2133 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
2135 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
2136 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
2138 if (has_architectural_pmu_version > 0) {
2139 if (has_architectural_pmu_version > 1) {
2140 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
2141 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
2142 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
2143 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
2145 for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
2146 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
2148 for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
2149 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
2150 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
2154 if (env->mcg_cap) {
2155 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
2156 kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
2157 if (has_msr_mcg_ext_ctl) {
2158 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
2160 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
2161 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
2165 if (has_msr_hv_hypercall) {
2166 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
2167 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
2169 if (cpu->hyperv_vapic) {
2170 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
2172 if (cpu->hyperv_time) {
2173 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
2175 if (cpu->hyperv_reenlightenment) {
2176 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL, 0);
2177 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL, 0);
2178 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS, 0);
2180 if (has_msr_hv_crash) {
2181 int j;
2183 for (j = 0; j < HV_CRASH_PARAMS; j++) {
2184 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
2187 if (has_msr_hv_runtime) {
2188 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
2190 if (cpu->hyperv_synic) {
2191 uint32_t msr;
2193 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
2194 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
2195 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
2196 for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
2197 kvm_msr_entry_add(cpu, msr, 0);
2200 if (has_msr_hv_stimer) {
2201 uint32_t msr;
2203 for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
2204 msr++) {
2205 kvm_msr_entry_add(cpu, msr, 0);
2208 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
2209 kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
2210 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
2211 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
2212 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
2213 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
2214 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
2215 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
2216 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
2217 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
2218 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
2219 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
2220 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
2221 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
2222 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
2223 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
2227 if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
2228 int addr_num =
2229 kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
2231 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
2232 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
2233 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
2234 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
2235 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
2236 for (i = 0; i < addr_num; i++) {
2237 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
2241 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
2242 if (ret < 0) {
2243 return ret;
2246 if (ret < cpu->kvm_msr_buf->nmsrs) {
2247 struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
2248 error_report("error: failed to get MSR 0x%" PRIx32,
2249 (uint32_t)e->index);
2252 assert(ret == cpu->kvm_msr_buf->nmsrs);
2254 * MTRR masks: Each mask consists of 5 parts
2255 * a 10..0: must be zero
2256 * b 11 : valid bit
2257 * c n-1.12: actual mask bits
2258 * d 51..n: reserved must be zero
2259 * e 63.52: reserved must be zero
2261 * 'n' is the number of physical bits supported by the CPU and is
2262 * apparently always <= 52. We know our 'n' but don't know what
2263 * the destinations 'n' is; it might be smaller, in which case
2264 * it masks (c) on loading. It might be larger, in which case
2265 * we fill 'd' so that d..c is consistent irrespetive of the 'n'
2266 * we're migrating to.
2269 if (cpu->fill_mtrr_mask) {
2270 QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
2271 assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
2272 mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
2273 } else {
2274 mtrr_top_bits = 0;
2277 for (i = 0; i < ret; i++) {
2278 uint32_t index = msrs[i].index;
2279 switch (index) {
2280 case MSR_IA32_SYSENTER_CS:
2281 env->sysenter_cs = msrs[i].data;
2282 break;
2283 case MSR_IA32_SYSENTER_ESP:
2284 env->sysenter_esp = msrs[i].data;
2285 break;
2286 case MSR_IA32_SYSENTER_EIP:
2287 env->sysenter_eip = msrs[i].data;
2288 break;
2289 case MSR_PAT:
2290 env->pat = msrs[i].data;
2291 break;
2292 case MSR_STAR:
2293 env->star = msrs[i].data;
2294 break;
2295 #ifdef TARGET_X86_64
2296 case MSR_CSTAR:
2297 env->cstar = msrs[i].data;
2298 break;
2299 case MSR_KERNELGSBASE:
2300 env->kernelgsbase = msrs[i].data;
2301 break;
2302 case MSR_FMASK:
2303 env->fmask = msrs[i].data;
2304 break;
2305 case MSR_LSTAR:
2306 env->lstar = msrs[i].data;
2307 break;
2308 #endif
2309 case MSR_IA32_TSC:
2310 env->tsc = msrs[i].data;
2311 break;
2312 case MSR_TSC_AUX:
2313 env->tsc_aux = msrs[i].data;
2314 break;
2315 case MSR_TSC_ADJUST:
2316 env->tsc_adjust = msrs[i].data;
2317 break;
2318 case MSR_IA32_TSCDEADLINE:
2319 env->tsc_deadline = msrs[i].data;
2320 break;
2321 case MSR_VM_HSAVE_PA:
2322 env->vm_hsave = msrs[i].data;
2323 break;
2324 case MSR_KVM_SYSTEM_TIME:
2325 env->system_time_msr = msrs[i].data;
2326 break;
2327 case MSR_KVM_WALL_CLOCK:
2328 env->wall_clock_msr = msrs[i].data;
2329 break;
2330 case MSR_MCG_STATUS:
2331 env->mcg_status = msrs[i].data;
2332 break;
2333 case MSR_MCG_CTL:
2334 env->mcg_ctl = msrs[i].data;
2335 break;
2336 case MSR_MCG_EXT_CTL:
2337 env->mcg_ext_ctl = msrs[i].data;
2338 break;
2339 case MSR_IA32_MISC_ENABLE:
2340 env->msr_ia32_misc_enable = msrs[i].data;
2341 break;
2342 case MSR_IA32_SMBASE:
2343 env->smbase = msrs[i].data;
2344 break;
2345 case MSR_SMI_COUNT:
2346 env->msr_smi_count = msrs[i].data;
2347 break;
2348 case MSR_IA32_FEATURE_CONTROL:
2349 env->msr_ia32_feature_control = msrs[i].data;
2350 break;
2351 case MSR_IA32_BNDCFGS:
2352 env->msr_bndcfgs = msrs[i].data;
2353 break;
2354 case MSR_IA32_XSS:
2355 env->xss = msrs[i].data;
2356 break;
2357 default:
2358 if (msrs[i].index >= MSR_MC0_CTL &&
2359 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
2360 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
2362 break;
2363 case MSR_KVM_ASYNC_PF_EN:
2364 env->async_pf_en_msr = msrs[i].data;
2365 break;
2366 case MSR_KVM_PV_EOI_EN:
2367 env->pv_eoi_en_msr = msrs[i].data;
2368 break;
2369 case MSR_KVM_STEAL_TIME:
2370 env->steal_time_msr = msrs[i].data;
2371 break;
2372 case MSR_CORE_PERF_FIXED_CTR_CTRL:
2373 env->msr_fixed_ctr_ctrl = msrs[i].data;
2374 break;
2375 case MSR_CORE_PERF_GLOBAL_CTRL:
2376 env->msr_global_ctrl = msrs[i].data;
2377 break;
2378 case MSR_CORE_PERF_GLOBAL_STATUS:
2379 env->msr_global_status = msrs[i].data;
2380 break;
2381 case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
2382 env->msr_global_ovf_ctrl = msrs[i].data;
2383 break;
2384 case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
2385 env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
2386 break;
2387 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
2388 env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
2389 break;
2390 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
2391 env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
2392 break;
2393 case HV_X64_MSR_HYPERCALL:
2394 env->msr_hv_hypercall = msrs[i].data;
2395 break;
2396 case HV_X64_MSR_GUEST_OS_ID:
2397 env->msr_hv_guest_os_id = msrs[i].data;
2398 break;
2399 case HV_X64_MSR_APIC_ASSIST_PAGE:
2400 env->msr_hv_vapic = msrs[i].data;
2401 break;
2402 case HV_X64_MSR_REFERENCE_TSC:
2403 env->msr_hv_tsc = msrs[i].data;
2404 break;
2405 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2406 env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
2407 break;
2408 case HV_X64_MSR_VP_RUNTIME:
2409 env->msr_hv_runtime = msrs[i].data;
2410 break;
2411 case HV_X64_MSR_SCONTROL:
2412 env->msr_hv_synic_control = msrs[i].data;
2413 break;
2414 case HV_X64_MSR_SIEFP:
2415 env->msr_hv_synic_evt_page = msrs[i].data;
2416 break;
2417 case HV_X64_MSR_SIMP:
2418 env->msr_hv_synic_msg_page = msrs[i].data;
2419 break;
2420 case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
2421 env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
2422 break;
2423 case HV_X64_MSR_STIMER0_CONFIG:
2424 case HV_X64_MSR_STIMER1_CONFIG:
2425 case HV_X64_MSR_STIMER2_CONFIG:
2426 case HV_X64_MSR_STIMER3_CONFIG:
2427 env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
2428 msrs[i].data;
2429 break;
2430 case HV_X64_MSR_STIMER0_COUNT:
2431 case HV_X64_MSR_STIMER1_COUNT:
2432 case HV_X64_MSR_STIMER2_COUNT:
2433 case HV_X64_MSR_STIMER3_COUNT:
2434 env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
2435 msrs[i].data;
2436 break;
2437 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2438 env->msr_hv_reenlightenment_control = msrs[i].data;
2439 break;
2440 case HV_X64_MSR_TSC_EMULATION_CONTROL:
2441 env->msr_hv_tsc_emulation_control = msrs[i].data;
2442 break;
2443 case HV_X64_MSR_TSC_EMULATION_STATUS:
2444 env->msr_hv_tsc_emulation_status = msrs[i].data;
2445 break;
2446 case MSR_MTRRdefType:
2447 env->mtrr_deftype = msrs[i].data;
2448 break;
2449 case MSR_MTRRfix64K_00000:
2450 env->mtrr_fixed[0] = msrs[i].data;
2451 break;
2452 case MSR_MTRRfix16K_80000:
2453 env->mtrr_fixed[1] = msrs[i].data;
2454 break;
2455 case MSR_MTRRfix16K_A0000:
2456 env->mtrr_fixed[2] = msrs[i].data;
2457 break;
2458 case MSR_MTRRfix4K_C0000:
2459 env->mtrr_fixed[3] = msrs[i].data;
2460 break;
2461 case MSR_MTRRfix4K_C8000:
2462 env->mtrr_fixed[4] = msrs[i].data;
2463 break;
2464 case MSR_MTRRfix4K_D0000:
2465 env->mtrr_fixed[5] = msrs[i].data;
2466 break;
2467 case MSR_MTRRfix4K_D8000:
2468 env->mtrr_fixed[6] = msrs[i].data;
2469 break;
2470 case MSR_MTRRfix4K_E0000:
2471 env->mtrr_fixed[7] = msrs[i].data;
2472 break;
2473 case MSR_MTRRfix4K_E8000:
2474 env->mtrr_fixed[8] = msrs[i].data;
2475 break;
2476 case MSR_MTRRfix4K_F0000:
2477 env->mtrr_fixed[9] = msrs[i].data;
2478 break;
2479 case MSR_MTRRfix4K_F8000:
2480 env->mtrr_fixed[10] = msrs[i].data;
2481 break;
2482 case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
2483 if (index & 1) {
2484 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
2485 mtrr_top_bits;
2486 } else {
2487 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
2489 break;
2490 case MSR_IA32_SPEC_CTRL:
2491 env->spec_ctrl = msrs[i].data;
2492 break;
2493 case MSR_VIRT_SSBD:
2494 env->virt_ssbd = msrs[i].data;
2495 break;
2496 case MSR_IA32_RTIT_CTL:
2497 env->msr_rtit_ctrl = msrs[i].data;
2498 break;
2499 case MSR_IA32_RTIT_STATUS:
2500 env->msr_rtit_status = msrs[i].data;
2501 break;
2502 case MSR_IA32_RTIT_OUTPUT_BASE:
2503 env->msr_rtit_output_base = msrs[i].data;
2504 break;
2505 case MSR_IA32_RTIT_OUTPUT_MASK:
2506 env->msr_rtit_output_mask = msrs[i].data;
2507 break;
2508 case MSR_IA32_RTIT_CR3_MATCH:
2509 env->msr_rtit_cr3_match = msrs[i].data;
2510 break;
2511 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2512 env->msr_rtit_addrs[index - MSR_IA32_RTIT_ADDR0_A] = msrs[i].data;
2513 break;
2517 return 0;
2520 static int kvm_put_mp_state(X86CPU *cpu)
2522 struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
2524 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
2527 static int kvm_get_mp_state(X86CPU *cpu)
2529 CPUState *cs = CPU(cpu);
2530 CPUX86State *env = &cpu->env;
2531 struct kvm_mp_state mp_state;
2532 int ret;
2534 ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
2535 if (ret < 0) {
2536 return ret;
2538 env->mp_state = mp_state.mp_state;
2539 if (kvm_irqchip_in_kernel()) {
2540 cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
2542 return 0;
2545 static int kvm_get_apic(X86CPU *cpu)
2547 DeviceState *apic = cpu->apic_state;
2548 struct kvm_lapic_state kapic;
2549 int ret;
2551 if (apic && kvm_irqchip_in_kernel()) {
2552 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
2553 if (ret < 0) {
2554 return ret;
2557 kvm_get_apic_state(apic, &kapic);
2559 return 0;
2562 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
2564 CPUState *cs = CPU(cpu);
2565 CPUX86State *env = &cpu->env;
2566 struct kvm_vcpu_events events = {};
2568 if (!kvm_has_vcpu_events()) {
2569 return 0;
2572 events.exception.injected = (env->exception_injected >= 0);
2573 events.exception.nr = env->exception_injected;
2574 events.exception.has_error_code = env->has_error_code;
2575 events.exception.error_code = env->error_code;
2576 events.exception.pad = 0;
2578 events.interrupt.injected = (env->interrupt_injected >= 0);
2579 events.interrupt.nr = env->interrupt_injected;
2580 events.interrupt.soft = env->soft_interrupt;
2582 events.nmi.injected = env->nmi_injected;
2583 events.nmi.pending = env->nmi_pending;
2584 events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
2585 events.nmi.pad = 0;
2587 events.sipi_vector = env->sipi_vector;
2588 events.flags = 0;
2590 if (has_msr_smbase) {
2591 events.smi.smm = !!(env->hflags & HF_SMM_MASK);
2592 events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
2593 if (kvm_irqchip_in_kernel()) {
2594 /* As soon as these are moved to the kernel, remove them
2595 * from cs->interrupt_request.
2597 events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
2598 events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
2599 cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
2600 } else {
2601 /* Keep these in cs->interrupt_request. */
2602 events.smi.pending = 0;
2603 events.smi.latched_init = 0;
2605 /* Stop SMI delivery on old machine types to avoid a reboot
2606 * on an inward migration of an old VM.
2608 if (!cpu->kvm_no_smi_migration) {
2609 events.flags |= KVM_VCPUEVENT_VALID_SMM;
2613 if (level >= KVM_PUT_RESET_STATE) {
2614 events.flags |= KVM_VCPUEVENT_VALID_NMI_PENDING;
2615 if (env->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
2616 events.flags |= KVM_VCPUEVENT_VALID_SIPI_VECTOR;
2620 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
2623 static int kvm_get_vcpu_events(X86CPU *cpu)
2625 CPUX86State *env = &cpu->env;
2626 struct kvm_vcpu_events events;
2627 int ret;
2629 if (!kvm_has_vcpu_events()) {
2630 return 0;
2633 memset(&events, 0, sizeof(events));
2634 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
2635 if (ret < 0) {
2636 return ret;
2638 env->exception_injected =
2639 events.exception.injected ? events.exception.nr : -1;
2640 env->has_error_code = events.exception.has_error_code;
2641 env->error_code = events.exception.error_code;
2643 env->interrupt_injected =
2644 events.interrupt.injected ? events.interrupt.nr : -1;
2645 env->soft_interrupt = events.interrupt.soft;
2647 env->nmi_injected = events.nmi.injected;
2648 env->nmi_pending = events.nmi.pending;
2649 if (events.nmi.masked) {
2650 env->hflags2 |= HF2_NMI_MASK;
2651 } else {
2652 env->hflags2 &= ~HF2_NMI_MASK;
2655 if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
2656 if (events.smi.smm) {
2657 env->hflags |= HF_SMM_MASK;
2658 } else {
2659 env->hflags &= ~HF_SMM_MASK;
2661 if (events.smi.pending) {
2662 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2663 } else {
2664 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2666 if (events.smi.smm_inside_nmi) {
2667 env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
2668 } else {
2669 env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
2671 if (events.smi.latched_init) {
2672 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2673 } else {
2674 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2678 env->sipi_vector = events.sipi_vector;
2680 return 0;
2683 static int kvm_guest_debug_workarounds(X86CPU *cpu)
2685 CPUState *cs = CPU(cpu);
2686 CPUX86State *env = &cpu->env;
2687 int ret = 0;
2688 unsigned long reinject_trap = 0;
2690 if (!kvm_has_vcpu_events()) {
2691 if (env->exception_injected == 1) {
2692 reinject_trap = KVM_GUESTDBG_INJECT_DB;
2693 } else if (env->exception_injected == 3) {
2694 reinject_trap = KVM_GUESTDBG_INJECT_BP;
2696 env->exception_injected = -1;
2700 * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
2701 * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
2702 * by updating the debug state once again if single-stepping is on.
2703 * Another reason to call kvm_update_guest_debug here is a pending debug
2704 * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
2705 * reinject them via SET_GUEST_DEBUG.
2707 if (reinject_trap ||
2708 (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
2709 ret = kvm_update_guest_debug(cs, reinject_trap);
2711 return ret;
2714 static int kvm_put_debugregs(X86CPU *cpu)
2716 CPUX86State *env = &cpu->env;
2717 struct kvm_debugregs dbgregs;
2718 int i;
2720 if (!kvm_has_debugregs()) {
2721 return 0;
2724 for (i = 0; i < 4; i++) {
2725 dbgregs.db[i] = env->dr[i];
2727 dbgregs.dr6 = env->dr[6];
2728 dbgregs.dr7 = env->dr[7];
2729 dbgregs.flags = 0;
2731 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
2734 static int kvm_get_debugregs(X86CPU *cpu)
2736 CPUX86State *env = &cpu->env;
2737 struct kvm_debugregs dbgregs;
2738 int i, ret;
2740 if (!kvm_has_debugregs()) {
2741 return 0;
2744 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
2745 if (ret < 0) {
2746 return ret;
2748 for (i = 0; i < 4; i++) {
2749 env->dr[i] = dbgregs.db[i];
2751 env->dr[4] = env->dr[6] = dbgregs.dr6;
2752 env->dr[5] = env->dr[7] = dbgregs.dr7;
2754 return 0;
2757 int kvm_arch_put_registers(CPUState *cpu, int level)
2759 X86CPU *x86_cpu = X86_CPU(cpu);
2760 int ret;
2762 assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
2764 if (level >= KVM_PUT_RESET_STATE) {
2765 ret = kvm_put_msr_feature_control(x86_cpu);
2766 if (ret < 0) {
2767 return ret;
2771 if (level == KVM_PUT_FULL_STATE) {
2772 /* We don't check for kvm_arch_set_tsc_khz() errors here,
2773 * because TSC frequency mismatch shouldn't abort migration,
2774 * unless the user explicitly asked for a more strict TSC
2775 * setting (e.g. using an explicit "tsc-freq" option).
2777 kvm_arch_set_tsc_khz(cpu);
2780 ret = kvm_getput_regs(x86_cpu, 1);
2781 if (ret < 0) {
2782 return ret;
2784 ret = kvm_put_xsave(x86_cpu);
2785 if (ret < 0) {
2786 return ret;
2788 ret = kvm_put_xcrs(x86_cpu);
2789 if (ret < 0) {
2790 return ret;
2792 ret = kvm_put_sregs(x86_cpu);
2793 if (ret < 0) {
2794 return ret;
2796 /* must be before kvm_put_msrs */
2797 ret = kvm_inject_mce_oldstyle(x86_cpu);
2798 if (ret < 0) {
2799 return ret;
2801 ret = kvm_put_msrs(x86_cpu, level);
2802 if (ret < 0) {
2803 return ret;
2805 ret = kvm_put_vcpu_events(x86_cpu, level);
2806 if (ret < 0) {
2807 return ret;
2809 if (level >= KVM_PUT_RESET_STATE) {
2810 ret = kvm_put_mp_state(x86_cpu);
2811 if (ret < 0) {
2812 return ret;
2816 ret = kvm_put_tscdeadline_msr(x86_cpu);
2817 if (ret < 0) {
2818 return ret;
2820 ret = kvm_put_debugregs(x86_cpu);
2821 if (ret < 0) {
2822 return ret;
2824 /* must be last */
2825 ret = kvm_guest_debug_workarounds(x86_cpu);
2826 if (ret < 0) {
2827 return ret;
2829 return 0;
2832 int kvm_arch_get_registers(CPUState *cs)
2834 X86CPU *cpu = X86_CPU(cs);
2835 int ret;
2837 assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
2839 ret = kvm_get_vcpu_events(cpu);
2840 if (ret < 0) {
2841 goto out;
2844 * KVM_GET_MPSTATE can modify CS and RIP, call it before
2845 * KVM_GET_REGS and KVM_GET_SREGS.
2847 ret = kvm_get_mp_state(cpu);
2848 if (ret < 0) {
2849 goto out;
2851 ret = kvm_getput_regs(cpu, 0);
2852 if (ret < 0) {
2853 goto out;
2855 ret = kvm_get_xsave(cpu);
2856 if (ret < 0) {
2857 goto out;
2859 ret = kvm_get_xcrs(cpu);
2860 if (ret < 0) {
2861 goto out;
2863 ret = kvm_get_sregs(cpu);
2864 if (ret < 0) {
2865 goto out;
2867 ret = kvm_get_msrs(cpu);
2868 if (ret < 0) {
2869 goto out;
2871 ret = kvm_get_apic(cpu);
2872 if (ret < 0) {
2873 goto out;
2875 ret = kvm_get_debugregs(cpu);
2876 if (ret < 0) {
2877 goto out;
2879 ret = 0;
2880 out:
2881 cpu_sync_bndcs_hflags(&cpu->env);
2882 return ret;
2885 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
2887 X86CPU *x86_cpu = X86_CPU(cpu);
2888 CPUX86State *env = &x86_cpu->env;
2889 int ret;
2891 /* Inject NMI */
2892 if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
2893 if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
2894 qemu_mutex_lock_iothread();
2895 cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
2896 qemu_mutex_unlock_iothread();
2897 DPRINTF("injected NMI\n");
2898 ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
2899 if (ret < 0) {
2900 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
2901 strerror(-ret));
2904 if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
2905 qemu_mutex_lock_iothread();
2906 cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
2907 qemu_mutex_unlock_iothread();
2908 DPRINTF("injected SMI\n");
2909 ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
2910 if (ret < 0) {
2911 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
2912 strerror(-ret));
2917 if (!kvm_pic_in_kernel()) {
2918 qemu_mutex_lock_iothread();
2921 /* Force the VCPU out of its inner loop to process any INIT requests
2922 * or (for userspace APIC, but it is cheap to combine the checks here)
2923 * pending TPR access reports.
2925 if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
2926 if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
2927 !(env->hflags & HF_SMM_MASK)) {
2928 cpu->exit_request = 1;
2930 if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
2931 cpu->exit_request = 1;
2935 if (!kvm_pic_in_kernel()) {
2936 /* Try to inject an interrupt if the guest can accept it */
2937 if (run->ready_for_interrupt_injection &&
2938 (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
2939 (env->eflags & IF_MASK)) {
2940 int irq;
2942 cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
2943 irq = cpu_get_pic_interrupt(env);
2944 if (irq >= 0) {
2945 struct kvm_interrupt intr;
2947 intr.irq = irq;
2948 DPRINTF("injected interrupt %d\n", irq);
2949 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
2950 if (ret < 0) {
2951 fprintf(stderr,
2952 "KVM: injection failed, interrupt lost (%s)\n",
2953 strerror(-ret));
2958 /* If we have an interrupt but the guest is not ready to receive an
2959 * interrupt, request an interrupt window exit. This will
2960 * cause a return to userspace as soon as the guest is ready to
2961 * receive interrupts. */
2962 if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
2963 run->request_interrupt_window = 1;
2964 } else {
2965 run->request_interrupt_window = 0;
2968 DPRINTF("setting tpr\n");
2969 run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
2971 qemu_mutex_unlock_iothread();
2975 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
2977 X86CPU *x86_cpu = X86_CPU(cpu);
2978 CPUX86State *env = &x86_cpu->env;
2980 if (run->flags & KVM_RUN_X86_SMM) {
2981 env->hflags |= HF_SMM_MASK;
2982 } else {
2983 env->hflags &= ~HF_SMM_MASK;
2985 if (run->if_flag) {
2986 env->eflags |= IF_MASK;
2987 } else {
2988 env->eflags &= ~IF_MASK;
2991 /* We need to protect the apic state against concurrent accesses from
2992 * different threads in case the userspace irqchip is used. */
2993 if (!kvm_irqchip_in_kernel()) {
2994 qemu_mutex_lock_iothread();
2996 cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
2997 cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
2998 if (!kvm_irqchip_in_kernel()) {
2999 qemu_mutex_unlock_iothread();
3001 return cpu_get_mem_attrs(env);
3004 int kvm_arch_process_async_events(CPUState *cs)
3006 X86CPU *cpu = X86_CPU(cs);
3007 CPUX86State *env = &cpu->env;
3009 if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
3010 /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
3011 assert(env->mcg_cap);
3013 cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
3015 kvm_cpu_synchronize_state(cs);
3017 if (env->exception_injected == EXCP08_DBLE) {
3018 /* this means triple fault */
3019 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
3020 cs->exit_request = 1;
3021 return 0;
3023 env->exception_injected = EXCP12_MCHK;
3024 env->has_error_code = 0;
3026 cs->halted = 0;
3027 if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
3028 env->mp_state = KVM_MP_STATE_RUNNABLE;
3032 if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
3033 !(env->hflags & HF_SMM_MASK)) {
3034 kvm_cpu_synchronize_state(cs);
3035 do_cpu_init(cpu);
3038 if (kvm_irqchip_in_kernel()) {
3039 return 0;
3042 if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
3043 cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
3044 apic_poll_irq(cpu->apic_state);
3046 if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
3047 (env->eflags & IF_MASK)) ||
3048 (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
3049 cs->halted = 0;
3051 if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
3052 kvm_cpu_synchronize_state(cs);
3053 do_cpu_sipi(cpu);
3055 if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
3056 cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
3057 kvm_cpu_synchronize_state(cs);
3058 apic_handle_tpr_access_report(cpu->apic_state, env->eip,
3059 env->tpr_access_type);
3062 return cs->halted;
3065 static int kvm_handle_halt(X86CPU *cpu)
3067 CPUState *cs = CPU(cpu);
3068 CPUX86State *env = &cpu->env;
3070 if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
3071 (env->eflags & IF_MASK)) &&
3072 !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
3073 cs->halted = 1;
3074 return EXCP_HLT;
3077 return 0;
3080 static int kvm_handle_tpr_access(X86CPU *cpu)
3082 CPUState *cs = CPU(cpu);
3083 struct kvm_run *run = cs->kvm_run;
3085 apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
3086 run->tpr_access.is_write ? TPR_ACCESS_WRITE
3087 : TPR_ACCESS_READ);
3088 return 1;
3091 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
3093 static const uint8_t int3 = 0xcc;
3095 if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
3096 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
3097 return -EINVAL;
3099 return 0;
3102 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
3104 uint8_t int3;
3106 if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
3107 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
3108 return -EINVAL;
3110 return 0;
3113 static struct {
3114 target_ulong addr;
3115 int len;
3116 int type;
3117 } hw_breakpoint[4];
3119 static int nb_hw_breakpoint;
3121 static int find_hw_breakpoint(target_ulong addr, int len, int type)
3123 int n;
3125 for (n = 0; n < nb_hw_breakpoint; n++) {
3126 if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
3127 (hw_breakpoint[n].len == len || len == -1)) {
3128 return n;
3131 return -1;
3134 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
3135 target_ulong len, int type)
3137 switch (type) {
3138 case GDB_BREAKPOINT_HW:
3139 len = 1;
3140 break;
3141 case GDB_WATCHPOINT_WRITE:
3142 case GDB_WATCHPOINT_ACCESS:
3143 switch (len) {
3144 case 1:
3145 break;
3146 case 2:
3147 case 4:
3148 case 8:
3149 if (addr & (len - 1)) {
3150 return -EINVAL;
3152 break;
3153 default:
3154 return -EINVAL;
3156 break;
3157 default:
3158 return -ENOSYS;
3161 if (nb_hw_breakpoint == 4) {
3162 return -ENOBUFS;
3164 if (find_hw_breakpoint(addr, len, type) >= 0) {
3165 return -EEXIST;
3167 hw_breakpoint[nb_hw_breakpoint].addr = addr;
3168 hw_breakpoint[nb_hw_breakpoint].len = len;
3169 hw_breakpoint[nb_hw_breakpoint].type = type;
3170 nb_hw_breakpoint++;
3172 return 0;
3175 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
3176 target_ulong len, int type)
3178 int n;
3180 n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
3181 if (n < 0) {
3182 return -ENOENT;
3184 nb_hw_breakpoint--;
3185 hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
3187 return 0;
3190 void kvm_arch_remove_all_hw_breakpoints(void)
3192 nb_hw_breakpoint = 0;
3195 static CPUWatchpoint hw_watchpoint;
3197 static int kvm_handle_debug(X86CPU *cpu,
3198 struct kvm_debug_exit_arch *arch_info)
3200 CPUState *cs = CPU(cpu);
3201 CPUX86State *env = &cpu->env;
3202 int ret = 0;
3203 int n;
3205 if (arch_info->exception == 1) {
3206 if (arch_info->dr6 & (1 << 14)) {
3207 if (cs->singlestep_enabled) {
3208 ret = EXCP_DEBUG;
3210 } else {
3211 for (n = 0; n < 4; n++) {
3212 if (arch_info->dr6 & (1 << n)) {
3213 switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
3214 case 0x0:
3215 ret = EXCP_DEBUG;
3216 break;
3217 case 0x1:
3218 ret = EXCP_DEBUG;
3219 cs->watchpoint_hit = &hw_watchpoint;
3220 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
3221 hw_watchpoint.flags = BP_MEM_WRITE;
3222 break;
3223 case 0x3:
3224 ret = EXCP_DEBUG;
3225 cs->watchpoint_hit = &hw_watchpoint;
3226 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
3227 hw_watchpoint.flags = BP_MEM_ACCESS;
3228 break;
3233 } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
3234 ret = EXCP_DEBUG;
3236 if (ret == 0) {
3237 cpu_synchronize_state(cs);
3238 assert(env->exception_injected == -1);
3240 /* pass to guest */
3241 env->exception_injected = arch_info->exception;
3242 env->has_error_code = 0;
3245 return ret;
3248 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
3250 const uint8_t type_code[] = {
3251 [GDB_BREAKPOINT_HW] = 0x0,
3252 [GDB_WATCHPOINT_WRITE] = 0x1,
3253 [GDB_WATCHPOINT_ACCESS] = 0x3
3255 const uint8_t len_code[] = {
3256 [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
3258 int n;
3260 if (kvm_sw_breakpoints_active(cpu)) {
3261 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
3263 if (nb_hw_breakpoint > 0) {
3264 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
3265 dbg->arch.debugreg[7] = 0x0600;
3266 for (n = 0; n < nb_hw_breakpoint; n++) {
3267 dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
3268 dbg->arch.debugreg[7] |= (2 << (n * 2)) |
3269 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
3270 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
3275 static bool host_supports_vmx(void)
3277 uint32_t ecx, unused;
3279 host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
3280 return ecx & CPUID_EXT_VMX;
3283 #define VMX_INVALID_GUEST_STATE 0x80000021
3285 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
3287 X86CPU *cpu = X86_CPU(cs);
3288 uint64_t code;
3289 int ret;
3291 switch (run->exit_reason) {
3292 case KVM_EXIT_HLT:
3293 DPRINTF("handle_hlt\n");
3294 qemu_mutex_lock_iothread();
3295 ret = kvm_handle_halt(cpu);
3296 qemu_mutex_unlock_iothread();
3297 break;
3298 case KVM_EXIT_SET_TPR:
3299 ret = 0;
3300 break;
3301 case KVM_EXIT_TPR_ACCESS:
3302 qemu_mutex_lock_iothread();
3303 ret = kvm_handle_tpr_access(cpu);
3304 qemu_mutex_unlock_iothread();
3305 break;
3306 case KVM_EXIT_FAIL_ENTRY:
3307 code = run->fail_entry.hardware_entry_failure_reason;
3308 fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
3309 code);
3310 if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
3311 fprintf(stderr,
3312 "\nIf you're running a guest on an Intel machine without "
3313 "unrestricted mode\n"
3314 "support, the failure can be most likely due to the guest "
3315 "entering an invalid\n"
3316 "state for Intel VT. For example, the guest maybe running "
3317 "in big real mode\n"
3318 "which is not supported on less recent Intel processors."
3319 "\n\n");
3321 ret = -1;
3322 break;
3323 case KVM_EXIT_EXCEPTION:
3324 fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
3325 run->ex.exception, run->ex.error_code);
3326 ret = -1;
3327 break;
3328 case KVM_EXIT_DEBUG:
3329 DPRINTF("kvm_exit_debug\n");
3330 qemu_mutex_lock_iothread();
3331 ret = kvm_handle_debug(cpu, &run->debug.arch);
3332 qemu_mutex_unlock_iothread();
3333 break;
3334 case KVM_EXIT_HYPERV:
3335 ret = kvm_hv_handle_exit(cpu, &run->hyperv);
3336 break;
3337 case KVM_EXIT_IOAPIC_EOI:
3338 ioapic_eoi_broadcast(run->eoi.vector);
3339 ret = 0;
3340 break;
3341 default:
3342 fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
3343 ret = -1;
3344 break;
3347 return ret;
3350 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
3352 X86CPU *cpu = X86_CPU(cs);
3353 CPUX86State *env = &cpu->env;
3355 kvm_cpu_synchronize_state(cs);
3356 return !(env->cr[0] & CR0_PE_MASK) ||
3357 ((env->segs[R_CS].selector & 3) != 3);
3360 void kvm_arch_init_irq_routing(KVMState *s)
3362 if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
3363 /* If kernel can't do irq routing, interrupt source
3364 * override 0->2 cannot be set up as required by HPET.
3365 * So we have to disable it.
3367 no_hpet = 1;
3369 /* We know at this point that we're using the in-kernel
3370 * irqchip, so we can use irqfds, and on x86 we know
3371 * we can use msi via irqfd and GSI routing.
3373 kvm_msi_via_irqfd_allowed = true;
3374 kvm_gsi_routing_allowed = true;
3376 if (kvm_irqchip_is_split()) {
3377 int i;
3379 /* If the ioapic is in QEMU and the lapics are in KVM, reserve
3380 MSI routes for signaling interrupts to the local apics. */
3381 for (i = 0; i < IOAPIC_NUM_PINS; i++) {
3382 if (kvm_irqchip_add_msi_route(s, 0, NULL) < 0) {
3383 error_report("Could not enable split IRQ mode.");
3384 exit(1);
3390 int kvm_arch_irqchip_create(MachineState *ms, KVMState *s)
3392 int ret;
3393 if (machine_kernel_irqchip_split(ms)) {
3394 ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
3395 if (ret) {
3396 error_report("Could not enable split irqchip mode: %s",
3397 strerror(-ret));
3398 exit(1);
3399 } else {
3400 DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
3401 kvm_split_irqchip = true;
3402 return 1;
3404 } else {
3405 return 0;
3409 /* Classic KVM device assignment interface. Will remain x86 only. */
3410 int kvm_device_pci_assign(KVMState *s, PCIHostDeviceAddress *dev_addr,
3411 uint32_t flags, uint32_t *dev_id)
3413 struct kvm_assigned_pci_dev dev_data = {
3414 .segnr = dev_addr->domain,
3415 .busnr = dev_addr->bus,
3416 .devfn = PCI_DEVFN(dev_addr->slot, dev_addr->function),
3417 .flags = flags,
3419 int ret;
3421 dev_data.assigned_dev_id =
3422 (dev_addr->domain << 16) | (dev_addr->bus << 8) | dev_data.devfn;
3424 ret = kvm_vm_ioctl(s, KVM_ASSIGN_PCI_DEVICE, &dev_data);
3425 if (ret < 0) {
3426 return ret;
3429 *dev_id = dev_data.assigned_dev_id;
3431 return 0;
3434 int kvm_device_pci_deassign(KVMState *s, uint32_t dev_id)
3436 struct kvm_assigned_pci_dev dev_data = {
3437 .assigned_dev_id = dev_id,
3440 return kvm_vm_ioctl(s, KVM_DEASSIGN_PCI_DEVICE, &dev_data);
3443 static int kvm_assign_irq_internal(KVMState *s, uint32_t dev_id,
3444 uint32_t irq_type, uint32_t guest_irq)
3446 struct kvm_assigned_irq assigned_irq = {
3447 .assigned_dev_id = dev_id,
3448 .guest_irq = guest_irq,
3449 .flags = irq_type,
3452 if (kvm_check_extension(s, KVM_CAP_ASSIGN_DEV_IRQ)) {
3453 return kvm_vm_ioctl(s, KVM_ASSIGN_DEV_IRQ, &assigned_irq);
3454 } else {
3455 return kvm_vm_ioctl(s, KVM_ASSIGN_IRQ, &assigned_irq);
3459 int kvm_device_intx_assign(KVMState *s, uint32_t dev_id, bool use_host_msi,
3460 uint32_t guest_irq)
3462 uint32_t irq_type = KVM_DEV_IRQ_GUEST_INTX |
3463 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX);
3465 return kvm_assign_irq_internal(s, dev_id, irq_type, guest_irq);
3468 int kvm_device_intx_set_mask(KVMState *s, uint32_t dev_id, bool masked)
3470 struct kvm_assigned_pci_dev dev_data = {
3471 .assigned_dev_id = dev_id,
3472 .flags = masked ? KVM_DEV_ASSIGN_MASK_INTX : 0,
3475 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_INTX_MASK, &dev_data);
3478 static int kvm_deassign_irq_internal(KVMState *s, uint32_t dev_id,
3479 uint32_t type)
3481 struct kvm_assigned_irq assigned_irq = {
3482 .assigned_dev_id = dev_id,
3483 .flags = type,
3486 return kvm_vm_ioctl(s, KVM_DEASSIGN_DEV_IRQ, &assigned_irq);
3489 int kvm_device_intx_deassign(KVMState *s, uint32_t dev_id, bool use_host_msi)
3491 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_INTX |
3492 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX));
3495 int kvm_device_msi_assign(KVMState *s, uint32_t dev_id, int virq)
3497 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSI |
3498 KVM_DEV_IRQ_GUEST_MSI, virq);
3501 int kvm_device_msi_deassign(KVMState *s, uint32_t dev_id)
3503 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSI |
3504 KVM_DEV_IRQ_HOST_MSI);
3507 bool kvm_device_msix_supported(KVMState *s)
3509 /* The kernel lacks a corresponding KVM_CAP, so we probe by calling
3510 * KVM_ASSIGN_SET_MSIX_NR with an invalid parameter. */
3511 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, NULL) == -EFAULT;
3514 int kvm_device_msix_init_vectors(KVMState *s, uint32_t dev_id,
3515 uint32_t nr_vectors)
3517 struct kvm_assigned_msix_nr msix_nr = {
3518 .assigned_dev_id = dev_id,
3519 .entry_nr = nr_vectors,
3522 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, &msix_nr);
3525 int kvm_device_msix_set_vector(KVMState *s, uint32_t dev_id, uint32_t vector,
3526 int virq)
3528 struct kvm_assigned_msix_entry msix_entry = {
3529 .assigned_dev_id = dev_id,
3530 .gsi = virq,
3531 .entry = vector,
3534 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_ENTRY, &msix_entry);
3537 int kvm_device_msix_assign(KVMState *s, uint32_t dev_id)
3539 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSIX |
3540 KVM_DEV_IRQ_GUEST_MSIX, 0);
3543 int kvm_device_msix_deassign(KVMState *s, uint32_t dev_id)
3545 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSIX |
3546 KVM_DEV_IRQ_HOST_MSIX);
3549 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
3550 uint64_t address, uint32_t data, PCIDevice *dev)
3552 X86IOMMUState *iommu = x86_iommu_get_default();
3554 if (iommu) {
3555 int ret;
3556 MSIMessage src, dst;
3557 X86IOMMUClass *class = X86_IOMMU_GET_CLASS(iommu);
3559 src.address = route->u.msi.address_hi;
3560 src.address <<= VTD_MSI_ADDR_HI_SHIFT;
3561 src.address |= route->u.msi.address_lo;
3562 src.data = route->u.msi.data;
3564 ret = class->int_remap(iommu, &src, &dst, dev ? \
3565 pci_requester_id(dev) : \
3566 X86_IOMMU_SID_INVALID);
3567 if (ret) {
3568 trace_kvm_x86_fixup_msi_error(route->gsi);
3569 return 1;
3572 route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
3573 route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
3574 route->u.msi.data = dst.data;
3577 return 0;
3580 typedef struct MSIRouteEntry MSIRouteEntry;
3582 struct MSIRouteEntry {
3583 PCIDevice *dev; /* Device pointer */
3584 int vector; /* MSI/MSIX vector index */
3585 int virq; /* Virtual IRQ index */
3586 QLIST_ENTRY(MSIRouteEntry) list;
3589 /* List of used GSI routes */
3590 static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
3591 QLIST_HEAD_INITIALIZER(msi_route_list);
3593 static void kvm_update_msi_routes_all(void *private, bool global,
3594 uint32_t index, uint32_t mask)
3596 int cnt = 0;
3597 MSIRouteEntry *entry;
3598 MSIMessage msg;
3599 PCIDevice *dev;
3601 /* TODO: explicit route update */
3602 QLIST_FOREACH(entry, &msi_route_list, list) {
3603 cnt++;
3604 dev = entry->dev;
3605 if (!msix_enabled(dev) && !msi_enabled(dev)) {
3606 continue;
3608 msg = pci_get_msi_message(dev, entry->vector);
3609 kvm_irqchip_update_msi_route(kvm_state, entry->virq, msg, dev);
3611 kvm_irqchip_commit_routes(kvm_state);
3612 trace_kvm_x86_update_msi_routes(cnt);
3615 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
3616 int vector, PCIDevice *dev)
3618 static bool notify_list_inited = false;
3619 MSIRouteEntry *entry;
3621 if (!dev) {
3622 /* These are (possibly) IOAPIC routes only used for split
3623 * kernel irqchip mode, while what we are housekeeping are
3624 * PCI devices only. */
3625 return 0;
3628 entry = g_new0(MSIRouteEntry, 1);
3629 entry->dev = dev;
3630 entry->vector = vector;
3631 entry->virq = route->gsi;
3632 QLIST_INSERT_HEAD(&msi_route_list, entry, list);
3634 trace_kvm_x86_add_msi_route(route->gsi);
3636 if (!notify_list_inited) {
3637 /* For the first time we do add route, add ourselves into
3638 * IOMMU's IEC notify list if needed. */
3639 X86IOMMUState *iommu = x86_iommu_get_default();
3640 if (iommu) {
3641 x86_iommu_iec_register_notifier(iommu,
3642 kvm_update_msi_routes_all,
3643 NULL);
3645 notify_list_inited = true;
3647 return 0;
3650 int kvm_arch_release_virq_post(int virq)
3652 MSIRouteEntry *entry, *next;
3653 QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
3654 if (entry->virq == virq) {
3655 trace_kvm_x86_remove_msi_route(virq);
3656 QLIST_REMOVE(entry, list);
3657 g_free(entry);
3658 break;
3661 return 0;
3664 int kvm_arch_msi_data_to_gsi(uint32_t data)
3666 abort();