2 * Kernel-based Virtual Machine driver for Linux
4 * derived from drivers/kvm/kvm_main.c
6 * Copyright (C) 2006 Qumranet, Inc.
7 * Copyright (C) 2008 Qumranet, Inc.
8 * Copyright IBM Corporation, 2008
9 * Copyright 2010 Red Hat, Inc. and/or its affilates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
14 * Amit Shah <amit.shah@qumranet.com>
15 * Ben-Ami Yassour <benami@il.ibm.com>
17 * This work is licensed under the terms of the GNU GPL, version 2. See
18 * the COPYING file in the top-level directory.
22 #include <linux/kvm_host.h>
27 #include "kvm_cache_regs.h"
30 #include <linux/clocksource.h>
31 #include <linux/interrupt.h>
32 #include <linux/kvm.h>
34 #include <linux/vmalloc.h>
35 #include <linux/module.h>
36 #include <linux/mman.h>
37 #include <linux/highmem.h>
38 #include <linux/iommu.h>
39 #include <linux/intel-iommu.h>
40 #include <linux/cpufreq.h>
41 #include <linux/user-return-notifier.h>
42 #include <linux/srcu.h>
43 #include <linux/slab.h>
44 #include <linux/perf_event.h>
45 #include <linux/uaccess.h>
46 #include <trace/events/kvm.h>
48 #define CREATE_TRACE_POINTS
51 #include <asm/debugreg.h>
59 #define MAX_IO_MSRS 256
60 #define CR0_RESERVED_BITS \
61 (~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
62 | X86_CR0_ET | X86_CR0_NE | X86_CR0_WP | X86_CR0_AM \
63 | X86_CR0_NW | X86_CR0_CD | X86_CR0_PG))
64 #define CR4_RESERVED_BITS \
65 (~(unsigned long)(X86_CR4_VME | X86_CR4_PVI | X86_CR4_TSD | X86_CR4_DE\
66 | X86_CR4_PSE | X86_CR4_PAE | X86_CR4_MCE \
67 | X86_CR4_PGE | X86_CR4_PCE | X86_CR4_OSFXSR \
69 | X86_CR4_OSXMMEXCPT | X86_CR4_VMXE))
71 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
73 #define KVM_MAX_MCE_BANKS 32
74 #define KVM_MCE_CAP_SUPPORTED MCG_CTL_P
77 * - enable syscall per default because its emulated by KVM
78 * - enable LME and LMA per default on 64 bit KVM
81 static u64 __read_mostly efer_reserved_bits = 0xfffffffffffffafeULL;
83 static u64 __read_mostly efer_reserved_bits = 0xfffffffffffffffeULL;
86 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
87 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
89 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
90 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
91 struct kvm_cpuid_entry2 __user *entries);
93 struct kvm_x86_ops *kvm_x86_ops;
94 EXPORT_SYMBOL_GPL(kvm_x86_ops);
97 module_param_named(ignore_msrs, ignore_msrs, bool, S_IRUGO | S_IWUSR);
99 #define KVM_NR_SHARED_MSRS 16
101 struct kvm_shared_msrs_global {
103 u32 msrs[KVM_NR_SHARED_MSRS];
106 struct kvm_shared_msrs {
107 struct user_return_notifier urn;
109 struct kvm_shared_msr_values {
112 } values[KVM_NR_SHARED_MSRS];
115 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
116 static DEFINE_PER_CPU(struct kvm_shared_msrs, shared_msrs);
118 struct kvm_stats_debugfs_item debugfs_entries[] = {
119 { "pf_fixed", VCPU_STAT(pf_fixed) },
120 { "pf_guest", VCPU_STAT(pf_guest) },
121 { "tlb_flush", VCPU_STAT(tlb_flush) },
122 { "invlpg", VCPU_STAT(invlpg) },
123 { "exits", VCPU_STAT(exits) },
124 { "io_exits", VCPU_STAT(io_exits) },
125 { "mmio_exits", VCPU_STAT(mmio_exits) },
126 { "signal_exits", VCPU_STAT(signal_exits) },
127 { "irq_window", VCPU_STAT(irq_window_exits) },
128 { "nmi_window", VCPU_STAT(nmi_window_exits) },
129 { "halt_exits", VCPU_STAT(halt_exits) },
130 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
131 { "hypercalls", VCPU_STAT(hypercalls) },
132 { "request_irq", VCPU_STAT(request_irq_exits) },
133 { "irq_exits", VCPU_STAT(irq_exits) },
134 { "host_state_reload", VCPU_STAT(host_state_reload) },
135 { "efer_reload", VCPU_STAT(efer_reload) },
136 { "fpu_reload", VCPU_STAT(fpu_reload) },
137 { "insn_emulation", VCPU_STAT(insn_emulation) },
138 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
139 { "irq_injections", VCPU_STAT(irq_injections) },
140 { "nmi_injections", VCPU_STAT(nmi_injections) },
141 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
142 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
143 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
144 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
145 { "mmu_flooded", VM_STAT(mmu_flooded) },
146 { "mmu_recycled", VM_STAT(mmu_recycled) },
147 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
148 { "mmu_unsync", VM_STAT(mmu_unsync) },
149 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
150 { "largepages", VM_STAT(lpages) },
154 u64 __read_mostly host_xcr0;
156 static inline u32 bit(int bitno)
158 return 1 << (bitno & 31);
161 static void kvm_on_user_return(struct user_return_notifier *urn)
164 struct kvm_shared_msrs *locals
165 = container_of(urn, struct kvm_shared_msrs, urn);
166 struct kvm_shared_msr_values *values;
168 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
169 values = &locals->values[slot];
170 if (values->host != values->curr) {
171 wrmsrl(shared_msrs_global.msrs[slot], values->host);
172 values->curr = values->host;
175 locals->registered = false;
176 user_return_notifier_unregister(urn);
179 static void shared_msr_update(unsigned slot, u32 msr)
181 struct kvm_shared_msrs *smsr;
184 smsr = &__get_cpu_var(shared_msrs);
185 /* only read, and nobody should modify it at this time,
186 * so don't need lock */
187 if (slot >= shared_msrs_global.nr) {
188 printk(KERN_ERR "kvm: invalid MSR slot!");
191 rdmsrl_safe(msr, &value);
192 smsr->values[slot].host = value;
193 smsr->values[slot].curr = value;
196 void kvm_define_shared_msr(unsigned slot, u32 msr)
198 if (slot >= shared_msrs_global.nr)
199 shared_msrs_global.nr = slot + 1;
200 shared_msrs_global.msrs[slot] = msr;
201 /* we need ensured the shared_msr_global have been updated */
204 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
206 static void kvm_shared_msr_cpu_online(void)
210 for (i = 0; i < shared_msrs_global.nr; ++i)
211 shared_msr_update(i, shared_msrs_global.msrs[i]);
214 void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
216 struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
218 if (((value ^ smsr->values[slot].curr) & mask) == 0)
220 smsr->values[slot].curr = value;
221 wrmsrl(shared_msrs_global.msrs[slot], value);
222 if (!smsr->registered) {
223 smsr->urn.on_user_return = kvm_on_user_return;
224 user_return_notifier_register(&smsr->urn);
225 smsr->registered = true;
228 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
230 static void drop_user_return_notifiers(void *ignore)
232 struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
234 if (smsr->registered)
235 kvm_on_user_return(&smsr->urn);
238 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
240 if (irqchip_in_kernel(vcpu->kvm))
241 return vcpu->arch.apic_base;
243 return vcpu->arch.apic_base;
245 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
247 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
249 /* TODO: reserve bits check */
250 if (irqchip_in_kernel(vcpu->kvm))
251 kvm_lapic_set_base(vcpu, data);
253 vcpu->arch.apic_base = data;
255 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
257 #define EXCPT_BENIGN 0
258 #define EXCPT_CONTRIBUTORY 1
261 static int exception_class(int vector)
271 return EXCPT_CONTRIBUTORY;
278 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
279 unsigned nr, bool has_error, u32 error_code,
285 if (!vcpu->arch.exception.pending) {
287 vcpu->arch.exception.pending = true;
288 vcpu->arch.exception.has_error_code = has_error;
289 vcpu->arch.exception.nr = nr;
290 vcpu->arch.exception.error_code = error_code;
291 vcpu->arch.exception.reinject = reinject;
295 /* to check exception */
296 prev_nr = vcpu->arch.exception.nr;
297 if (prev_nr == DF_VECTOR) {
298 /* triple fault -> shutdown */
299 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
302 class1 = exception_class(prev_nr);
303 class2 = exception_class(nr);
304 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
305 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
306 /* generate double fault per SDM Table 5-5 */
307 vcpu->arch.exception.pending = true;
308 vcpu->arch.exception.has_error_code = true;
309 vcpu->arch.exception.nr = DF_VECTOR;
310 vcpu->arch.exception.error_code = 0;
312 /* replace previous exception with a new one in a hope
313 that instruction re-execution will regenerate lost
318 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
320 kvm_multiple_exception(vcpu, nr, false, 0, false);
322 EXPORT_SYMBOL_GPL(kvm_queue_exception);
324 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
326 kvm_multiple_exception(vcpu, nr, false, 0, true);
328 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
330 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, unsigned long addr,
333 ++vcpu->stat.pf_guest;
334 vcpu->arch.cr2 = addr;
335 kvm_queue_exception_e(vcpu, PF_VECTOR, error_code);
338 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
340 vcpu->arch.nmi_pending = 1;
342 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
344 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
346 kvm_multiple_exception(vcpu, nr, true, error_code, false);
348 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
350 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
352 kvm_multiple_exception(vcpu, nr, true, error_code, true);
354 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
357 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
358 * a #GP and return false.
360 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
362 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
364 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
367 EXPORT_SYMBOL_GPL(kvm_require_cpl);
370 * Load the pae pdptrs. Return true is they are all valid.
372 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
374 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
375 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
378 u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
380 ret = kvm_read_guest_page(vcpu->kvm, pdpt_gfn, pdpte,
381 offset * sizeof(u64), sizeof(pdpte));
386 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
387 if (is_present_gpte(pdpte[i]) &&
388 (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
395 memcpy(vcpu->arch.pdptrs, pdpte, sizeof(vcpu->arch.pdptrs));
396 __set_bit(VCPU_EXREG_PDPTR,
397 (unsigned long *)&vcpu->arch.regs_avail);
398 __set_bit(VCPU_EXREG_PDPTR,
399 (unsigned long *)&vcpu->arch.regs_dirty);
404 EXPORT_SYMBOL_GPL(load_pdptrs);
406 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
408 u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
412 if (is_long_mode(vcpu) || !is_pae(vcpu))
415 if (!test_bit(VCPU_EXREG_PDPTR,
416 (unsigned long *)&vcpu->arch.regs_avail))
419 r = kvm_read_guest(vcpu->kvm, vcpu->arch.cr3 & ~31u, pdpte, sizeof(pdpte));
422 changed = memcmp(pdpte, vcpu->arch.pdptrs, sizeof(pdpte)) != 0;
428 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
430 unsigned long old_cr0 = kvm_read_cr0(vcpu);
431 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
432 X86_CR0_CD | X86_CR0_NW;
437 if (cr0 & 0xffffffff00000000UL)
441 cr0 &= ~CR0_RESERVED_BITS;
443 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
446 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
449 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
451 if ((vcpu->arch.efer & EFER_LME)) {
456 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
461 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.cr3))
465 kvm_x86_ops->set_cr0(vcpu, cr0);
467 if ((cr0 ^ old_cr0) & update_bits)
468 kvm_mmu_reset_context(vcpu);
471 EXPORT_SYMBOL_GPL(kvm_set_cr0);
473 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
475 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
477 EXPORT_SYMBOL_GPL(kvm_lmsw);
479 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
483 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
484 if (index != XCR_XFEATURE_ENABLED_MASK)
487 if (kvm_x86_ops->get_cpl(vcpu) != 0)
489 if (!(xcr0 & XSTATE_FP))
491 if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
493 if (xcr0 & ~host_xcr0)
495 vcpu->arch.xcr0 = xcr0;
496 vcpu->guest_xcr0_loaded = 0;
500 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
502 if (__kvm_set_xcr(vcpu, index, xcr)) {
503 kvm_inject_gp(vcpu, 0);
508 EXPORT_SYMBOL_GPL(kvm_set_xcr);
510 static bool guest_cpuid_has_xsave(struct kvm_vcpu *vcpu)
512 struct kvm_cpuid_entry2 *best;
514 best = kvm_find_cpuid_entry(vcpu, 1, 0);
515 return best && (best->ecx & bit(X86_FEATURE_XSAVE));
518 static void update_cpuid(struct kvm_vcpu *vcpu)
520 struct kvm_cpuid_entry2 *best;
522 best = kvm_find_cpuid_entry(vcpu, 1, 0);
526 /* Update OSXSAVE bit */
527 if (cpu_has_xsave && best->function == 0x1) {
528 best->ecx &= ~(bit(X86_FEATURE_OSXSAVE));
529 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE))
530 best->ecx |= bit(X86_FEATURE_OSXSAVE);
534 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
536 unsigned long old_cr4 = kvm_read_cr4(vcpu);
537 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE;
539 if (cr4 & CR4_RESERVED_BITS)
542 if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
545 if (is_long_mode(vcpu)) {
546 if (!(cr4 & X86_CR4_PAE))
548 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
549 && ((cr4 ^ old_cr4) & pdptr_bits)
550 && !load_pdptrs(vcpu, vcpu->arch.cr3))
553 if (cr4 & X86_CR4_VMXE)
556 kvm_x86_ops->set_cr4(vcpu, cr4);
558 if ((cr4 ^ old_cr4) & pdptr_bits)
559 kvm_mmu_reset_context(vcpu);
561 if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
566 EXPORT_SYMBOL_GPL(kvm_set_cr4);
568 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
570 if (cr3 == vcpu->arch.cr3 && !pdptrs_changed(vcpu)) {
571 kvm_mmu_sync_roots(vcpu);
572 kvm_mmu_flush_tlb(vcpu);
576 if (is_long_mode(vcpu)) {
577 if (cr3 & CR3_L_MODE_RESERVED_BITS)
581 if (cr3 & CR3_PAE_RESERVED_BITS)
583 if (is_paging(vcpu) && !load_pdptrs(vcpu, cr3))
587 * We don't check reserved bits in nonpae mode, because
588 * this isn't enforced, and VMware depends on this.
593 * Does the new cr3 value map to physical memory? (Note, we
594 * catch an invalid cr3 even in real-mode, because it would
595 * cause trouble later on when we turn on paging anyway.)
597 * A real CPU would silently accept an invalid cr3 and would
598 * attempt to use it - with largely undefined (and often hard
599 * to debug) behavior on the guest side.
601 if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
603 vcpu->arch.cr3 = cr3;
604 vcpu->arch.mmu.new_cr3(vcpu);
607 EXPORT_SYMBOL_GPL(kvm_set_cr3);
609 int __kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
611 if (cr8 & CR8_RESERVED_BITS)
613 if (irqchip_in_kernel(vcpu->kvm))
614 kvm_lapic_set_tpr(vcpu, cr8);
616 vcpu->arch.cr8 = cr8;
620 void kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
622 if (__kvm_set_cr8(vcpu, cr8))
623 kvm_inject_gp(vcpu, 0);
625 EXPORT_SYMBOL_GPL(kvm_set_cr8);
627 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
629 if (irqchip_in_kernel(vcpu->kvm))
630 return kvm_lapic_get_cr8(vcpu);
632 return vcpu->arch.cr8;
634 EXPORT_SYMBOL_GPL(kvm_get_cr8);
636 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
640 vcpu->arch.db[dr] = val;
641 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
642 vcpu->arch.eff_db[dr] = val;
645 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
649 if (val & 0xffffffff00000000ULL)
651 vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
654 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
658 if (val & 0xffffffff00000000ULL)
660 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
661 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
662 kvm_x86_ops->set_dr7(vcpu, vcpu->arch.dr7);
663 vcpu->arch.switch_db_regs = (val & DR7_BP_EN_MASK);
671 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
675 res = __kvm_set_dr(vcpu, dr, val);
677 kvm_queue_exception(vcpu, UD_VECTOR);
679 kvm_inject_gp(vcpu, 0);
683 EXPORT_SYMBOL_GPL(kvm_set_dr);
685 static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
689 *val = vcpu->arch.db[dr];
692 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
696 *val = vcpu->arch.dr6;
699 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
703 *val = vcpu->arch.dr7;
710 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
712 if (_kvm_get_dr(vcpu, dr, val)) {
713 kvm_queue_exception(vcpu, UD_VECTOR);
718 EXPORT_SYMBOL_GPL(kvm_get_dr);
721 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
722 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
724 * This list is modified at module load time to reflect the
725 * capabilities of the host cpu. This capabilities test skips MSRs that are
726 * kvm-specific. Those are put in the beginning of the list.
729 #define KVM_SAVE_MSRS_BEGIN 7
730 static u32 msrs_to_save[] = {
731 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
732 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
733 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
734 HV_X64_MSR_APIC_ASSIST_PAGE,
735 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
738 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
740 MSR_IA32_TSC, MSR_IA32_PERF_STATUS, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA
743 static unsigned num_msrs_to_save;
745 static u32 emulated_msrs[] = {
746 MSR_IA32_MISC_ENABLE,
751 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
753 u64 old_efer = vcpu->arch.efer;
755 if (efer & efer_reserved_bits)
759 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
762 if (efer & EFER_FFXSR) {
763 struct kvm_cpuid_entry2 *feat;
765 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
766 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
770 if (efer & EFER_SVME) {
771 struct kvm_cpuid_entry2 *feat;
773 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
774 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
779 efer |= vcpu->arch.efer & EFER_LMA;
781 kvm_x86_ops->set_efer(vcpu, efer);
783 vcpu->arch.mmu.base_role.nxe = (efer & EFER_NX) && !tdp_enabled;
784 kvm_mmu_reset_context(vcpu);
786 /* Update reserved bits */
787 if ((efer ^ old_efer) & EFER_NX)
788 kvm_mmu_reset_context(vcpu);
793 void kvm_enable_efer_bits(u64 mask)
795 efer_reserved_bits &= ~mask;
797 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
801 * Writes msr value into into the appropriate "register".
802 * Returns 0 on success, non-0 otherwise.
803 * Assumes vcpu_load() was already called.
805 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
807 return kvm_x86_ops->set_msr(vcpu, msr_index, data);
811 * Adapt set_msr() to msr_io()'s calling convention
813 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
815 return kvm_set_msr(vcpu, index, *data);
818 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
822 struct pvclock_wall_clock wc;
823 struct timespec boot;
828 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
833 ++version; /* first time write, random junk */
837 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
840 * The guest calculates current wall clock time by adding
841 * system time (updated by kvm_write_guest_time below) to the
842 * wall clock specified here. guest system time equals host
843 * system time for us, thus we must fill in host boot time here.
847 wc.sec = boot.tv_sec;
848 wc.nsec = boot.tv_nsec;
849 wc.version = version;
851 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
854 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
857 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
859 uint32_t quotient, remainder;
861 /* Don't try to replace with do_div(), this one calculates
862 * "(dividend << 32) / divisor" */
864 : "=a" (quotient), "=d" (remainder)
865 : "0" (0), "1" (dividend), "r" (divisor) );
869 static void kvm_set_time_scale(uint32_t tsc_khz, struct pvclock_vcpu_time_info *hv_clock)
871 uint64_t nsecs = 1000000000LL;
876 tps64 = tsc_khz * 1000LL;
877 while (tps64 > nsecs*2) {
882 tps32 = (uint32_t)tps64;
883 while (tps32 <= (uint32_t)nsecs) {
888 hv_clock->tsc_shift = shift;
889 hv_clock->tsc_to_system_mul = div_frac(nsecs, tps32);
891 pr_debug("%s: tsc_khz %u, tsc_shift %d, tsc_mul %u\n",
892 __func__, tsc_khz, hv_clock->tsc_shift,
893 hv_clock->tsc_to_system_mul);
896 static inline u64 get_kernel_ns(void)
900 WARN_ON(preemptible());
902 monotonic_to_bootbased(&ts);
903 return timespec_to_ns(&ts);
906 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
908 static inline int kvm_tsc_changes_freq(void)
911 int ret = !boot_cpu_has(X86_FEATURE_CONSTANT_TSC) &&
912 cpufreq_quick_get(cpu) != 0;
917 static inline u64 nsec_to_cycles(u64 nsec)
919 WARN_ON(preemptible());
920 if (kvm_tsc_changes_freq())
921 printk_once(KERN_WARNING
922 "kvm: unreliable cycle conversion on adjustable rate TSC\n");
923 return (nsec * __get_cpu_var(cpu_tsc_khz)) / USEC_PER_SEC;
926 void kvm_write_tsc(struct kvm_vcpu *vcpu, u64 data)
928 struct kvm *kvm = vcpu->kvm;
929 u64 offset, ns, elapsed;
933 spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
934 offset = data - native_read_tsc();
935 ns = get_kernel_ns();
936 elapsed = ns - kvm->arch.last_tsc_nsec;
937 sdiff = data - kvm->arch.last_tsc_write;
942 * Special case: close write to TSC within 5 seconds of
943 * another CPU is interpreted as an attempt to synchronize
944 * The 5 seconds is to accomodate host load / swapping as
945 * well as any reset of TSC during the boot process.
947 * In that case, for a reliable TSC, we can match TSC offsets,
948 * or make a best guest using elapsed value.
950 if (sdiff < nsec_to_cycles(5ULL * NSEC_PER_SEC) &&
951 elapsed < 5ULL * NSEC_PER_SEC) {
952 if (!check_tsc_unstable()) {
953 offset = kvm->arch.last_tsc_offset;
954 pr_debug("kvm: matched tsc offset for %llu\n", data);
956 u64 delta = nsec_to_cycles(elapsed);
958 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
960 ns = kvm->arch.last_tsc_nsec;
962 kvm->arch.last_tsc_nsec = ns;
963 kvm->arch.last_tsc_write = data;
964 kvm->arch.last_tsc_offset = offset;
965 kvm_x86_ops->write_tsc_offset(vcpu, offset);
966 spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
968 /* Reset of TSC must disable overshoot protection below */
969 vcpu->arch.hv_clock.tsc_timestamp = 0;
971 EXPORT_SYMBOL_GPL(kvm_write_tsc);
973 static int kvm_write_guest_time(struct kvm_vcpu *v)
976 struct kvm_vcpu_arch *vcpu = &v->arch;
978 unsigned long this_tsc_khz;
981 if ((!vcpu->time_page))
984 /* Keep irq disabled to prevent changes to the clock */
985 local_irq_save(flags);
986 kvm_get_msr(v, MSR_IA32_TSC, &vcpu->hv_clock.tsc_timestamp);
987 kernel_ns = get_kernel_ns();
988 this_tsc_khz = __get_cpu_var(cpu_tsc_khz);
989 local_irq_restore(flags);
991 if (unlikely(this_tsc_khz == 0)) {
992 kvm_make_request(KVM_REQ_KVMCLOCK_UPDATE, v);
996 if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
997 kvm_set_time_scale(this_tsc_khz, &vcpu->hv_clock);
998 vcpu->hw_tsc_khz = this_tsc_khz;
1001 /* With all the info we got, fill in the values */
1002 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1003 vcpu->hv_clock.flags = 0;
1006 * The interface expects us to write an even number signaling that the
1007 * update is finished. Since the guest won't see the intermediate
1008 * state, we just increase by 2 at the end.
1010 vcpu->hv_clock.version += 2;
1012 shared_kaddr = kmap_atomic(vcpu->time_page, KM_USER0);
1014 memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
1015 sizeof(vcpu->hv_clock));
1017 kunmap_atomic(shared_kaddr, KM_USER0);
1019 mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
1023 static int kvm_request_guest_time_update(struct kvm_vcpu *v)
1025 struct kvm_vcpu_arch *vcpu = &v->arch;
1027 if (!vcpu->time_page)
1029 kvm_make_request(KVM_REQ_KVMCLOCK_UPDATE, v);
1033 static bool msr_mtrr_valid(unsigned msr)
1036 case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
1037 case MSR_MTRRfix64K_00000:
1038 case MSR_MTRRfix16K_80000:
1039 case MSR_MTRRfix16K_A0000:
1040 case MSR_MTRRfix4K_C0000:
1041 case MSR_MTRRfix4K_C8000:
1042 case MSR_MTRRfix4K_D0000:
1043 case MSR_MTRRfix4K_D8000:
1044 case MSR_MTRRfix4K_E0000:
1045 case MSR_MTRRfix4K_E8000:
1046 case MSR_MTRRfix4K_F0000:
1047 case MSR_MTRRfix4K_F8000:
1048 case MSR_MTRRdefType:
1049 case MSR_IA32_CR_PAT:
1057 static bool valid_pat_type(unsigned t)
1059 return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
1062 static bool valid_mtrr_type(unsigned t)
1064 return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
1067 static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1071 if (!msr_mtrr_valid(msr))
1074 if (msr == MSR_IA32_CR_PAT) {
1075 for (i = 0; i < 8; i++)
1076 if (!valid_pat_type((data >> (i * 8)) & 0xff))
1079 } else if (msr == MSR_MTRRdefType) {
1082 return valid_mtrr_type(data & 0xff);
1083 } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
1084 for (i = 0; i < 8 ; i++)
1085 if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
1090 /* variable MTRRs */
1091 return valid_mtrr_type(data & 0xff);
1094 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1096 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1098 if (!mtrr_valid(vcpu, msr, data))
1101 if (msr == MSR_MTRRdefType) {
1102 vcpu->arch.mtrr_state.def_type = data;
1103 vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
1104 } else if (msr == MSR_MTRRfix64K_00000)
1106 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1107 p[1 + msr - MSR_MTRRfix16K_80000] = data;
1108 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1109 p[3 + msr - MSR_MTRRfix4K_C0000] = data;
1110 else if (msr == MSR_IA32_CR_PAT)
1111 vcpu->arch.pat = data;
1112 else { /* Variable MTRRs */
1113 int idx, is_mtrr_mask;
1116 idx = (msr - 0x200) / 2;
1117 is_mtrr_mask = msr - 0x200 - 2 * idx;
1120 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1123 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1127 kvm_mmu_reset_context(vcpu);
1131 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1133 u64 mcg_cap = vcpu->arch.mcg_cap;
1134 unsigned bank_num = mcg_cap & 0xff;
1137 case MSR_IA32_MCG_STATUS:
1138 vcpu->arch.mcg_status = data;
1140 case MSR_IA32_MCG_CTL:
1141 if (!(mcg_cap & MCG_CTL_P))
1143 if (data != 0 && data != ~(u64)0)
1145 vcpu->arch.mcg_ctl = data;
1148 if (msr >= MSR_IA32_MC0_CTL &&
1149 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1150 u32 offset = msr - MSR_IA32_MC0_CTL;
1151 /* only 0 or all 1s can be written to IA32_MCi_CTL
1152 * some Linux kernels though clear bit 10 in bank 4 to
1153 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
1154 * this to avoid an uncatched #GP in the guest
1156 if ((offset & 0x3) == 0 &&
1157 data != 0 && (data | (1 << 10)) != ~(u64)0)
1159 vcpu->arch.mce_banks[offset] = data;
1167 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
1169 struct kvm *kvm = vcpu->kvm;
1170 int lm = is_long_mode(vcpu);
1171 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
1172 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
1173 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
1174 : kvm->arch.xen_hvm_config.blob_size_32;
1175 u32 page_num = data & ~PAGE_MASK;
1176 u64 page_addr = data & PAGE_MASK;
1181 if (page_num >= blob_size)
1184 page = kzalloc(PAGE_SIZE, GFP_KERNEL);
1188 if (copy_from_user(page, blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE))
1190 if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
1199 static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
1201 return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
1204 static bool kvm_hv_msr_partition_wide(u32 msr)
1208 case HV_X64_MSR_GUEST_OS_ID:
1209 case HV_X64_MSR_HYPERCALL:
1217 static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1219 struct kvm *kvm = vcpu->kvm;
1222 case HV_X64_MSR_GUEST_OS_ID:
1223 kvm->arch.hv_guest_os_id = data;
1224 /* setting guest os id to zero disables hypercall page */
1225 if (!kvm->arch.hv_guest_os_id)
1226 kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
1228 case HV_X64_MSR_HYPERCALL: {
1233 /* if guest os id is not set hypercall should remain disabled */
1234 if (!kvm->arch.hv_guest_os_id)
1236 if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
1237 kvm->arch.hv_hypercall = data;
1240 gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
1241 addr = gfn_to_hva(kvm, gfn);
1242 if (kvm_is_error_hva(addr))
1244 kvm_x86_ops->patch_hypercall(vcpu, instructions);
1245 ((unsigned char *)instructions)[3] = 0xc3; /* ret */
1246 if (copy_to_user((void __user *)addr, instructions, 4))
1248 kvm->arch.hv_hypercall = data;
1252 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1253 "data 0x%llx\n", msr, data);
1259 static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1262 case HV_X64_MSR_APIC_ASSIST_PAGE: {
1265 if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
1266 vcpu->arch.hv_vapic = data;
1269 addr = gfn_to_hva(vcpu->kvm, data >>
1270 HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
1271 if (kvm_is_error_hva(addr))
1273 if (clear_user((void __user *)addr, PAGE_SIZE))
1275 vcpu->arch.hv_vapic = data;
1278 case HV_X64_MSR_EOI:
1279 return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
1280 case HV_X64_MSR_ICR:
1281 return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
1282 case HV_X64_MSR_TPR:
1283 return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
1285 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1286 "data 0x%llx\n", msr, data);
1293 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1297 return set_efer(vcpu, data);
1299 data &= ~(u64)0x40; /* ignore flush filter disable */
1300 data &= ~(u64)0x100; /* ignore ignne emulation enable */
1302 pr_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
1307 case MSR_FAM10H_MMIO_CONF_BASE:
1309 pr_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
1314 case MSR_AMD64_NB_CFG:
1316 case MSR_IA32_DEBUGCTLMSR:
1318 /* We support the non-activated case already */
1320 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
1321 /* Values other than LBR and BTF are vendor-specific,
1322 thus reserved and should throw a #GP */
1325 pr_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
1328 case MSR_IA32_UCODE_REV:
1329 case MSR_IA32_UCODE_WRITE:
1330 case MSR_VM_HSAVE_PA:
1331 case MSR_AMD64_PATCH_LOADER:
1333 case 0x200 ... 0x2ff:
1334 return set_msr_mtrr(vcpu, msr, data);
1335 case MSR_IA32_APICBASE:
1336 kvm_set_apic_base(vcpu, data);
1338 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1339 return kvm_x2apic_msr_write(vcpu, msr, data);
1340 case MSR_IA32_MISC_ENABLE:
1341 vcpu->arch.ia32_misc_enable_msr = data;
1343 case MSR_KVM_WALL_CLOCK_NEW:
1344 case MSR_KVM_WALL_CLOCK:
1345 vcpu->kvm->arch.wall_clock = data;
1346 kvm_write_wall_clock(vcpu->kvm, data);
1348 case MSR_KVM_SYSTEM_TIME_NEW:
1349 case MSR_KVM_SYSTEM_TIME: {
1350 if (vcpu->arch.time_page) {
1351 kvm_release_page_dirty(vcpu->arch.time_page);
1352 vcpu->arch.time_page = NULL;
1355 vcpu->arch.time = data;
1357 /* we verify if the enable bit is set... */
1361 /* ...but clean it before doing the actual write */
1362 vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
1364 vcpu->arch.time_page =
1365 gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
1367 if (is_error_page(vcpu->arch.time_page)) {
1368 kvm_release_page_clean(vcpu->arch.time_page);
1369 vcpu->arch.time_page = NULL;
1372 kvm_request_guest_time_update(vcpu);
1375 case MSR_IA32_MCG_CTL:
1376 case MSR_IA32_MCG_STATUS:
1377 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1378 return set_msr_mce(vcpu, msr, data);
1380 /* Performance counters are not protected by a CPUID bit,
1381 * so we should check all of them in the generic path for the sake of
1382 * cross vendor migration.
1383 * Writing a zero into the event select MSRs disables them,
1384 * which we perfectly emulate ;-). Any other value should be at least
1385 * reported, some guests depend on them.
1387 case MSR_P6_EVNTSEL0:
1388 case MSR_P6_EVNTSEL1:
1389 case MSR_K7_EVNTSEL0:
1390 case MSR_K7_EVNTSEL1:
1391 case MSR_K7_EVNTSEL2:
1392 case MSR_K7_EVNTSEL3:
1394 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1395 "0x%x data 0x%llx\n", msr, data);
1397 /* at least RHEL 4 unconditionally writes to the perfctr registers,
1398 * so we ignore writes to make it happy.
1400 case MSR_P6_PERFCTR0:
1401 case MSR_P6_PERFCTR1:
1402 case MSR_K7_PERFCTR0:
1403 case MSR_K7_PERFCTR1:
1404 case MSR_K7_PERFCTR2:
1405 case MSR_K7_PERFCTR3:
1406 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1407 "0x%x data 0x%llx\n", msr, data);
1409 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1410 if (kvm_hv_msr_partition_wide(msr)) {
1412 mutex_lock(&vcpu->kvm->lock);
1413 r = set_msr_hyperv_pw(vcpu, msr, data);
1414 mutex_unlock(&vcpu->kvm->lock);
1417 return set_msr_hyperv(vcpu, msr, data);
1420 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
1421 return xen_hvm_config(vcpu, data);
1423 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
1427 pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
1434 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
1438 * Reads an msr value (of 'msr_index') into 'pdata'.
1439 * Returns 0 on success, non-0 otherwise.
1440 * Assumes vcpu_load() was already called.
1442 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1444 return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
1447 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1449 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1451 if (!msr_mtrr_valid(msr))
1454 if (msr == MSR_MTRRdefType)
1455 *pdata = vcpu->arch.mtrr_state.def_type +
1456 (vcpu->arch.mtrr_state.enabled << 10);
1457 else if (msr == MSR_MTRRfix64K_00000)
1459 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1460 *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
1461 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1462 *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
1463 else if (msr == MSR_IA32_CR_PAT)
1464 *pdata = vcpu->arch.pat;
1465 else { /* Variable MTRRs */
1466 int idx, is_mtrr_mask;
1469 idx = (msr - 0x200) / 2;
1470 is_mtrr_mask = msr - 0x200 - 2 * idx;
1473 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1476 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1483 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1486 u64 mcg_cap = vcpu->arch.mcg_cap;
1487 unsigned bank_num = mcg_cap & 0xff;
1490 case MSR_IA32_P5_MC_ADDR:
1491 case MSR_IA32_P5_MC_TYPE:
1494 case MSR_IA32_MCG_CAP:
1495 data = vcpu->arch.mcg_cap;
1497 case MSR_IA32_MCG_CTL:
1498 if (!(mcg_cap & MCG_CTL_P))
1500 data = vcpu->arch.mcg_ctl;
1502 case MSR_IA32_MCG_STATUS:
1503 data = vcpu->arch.mcg_status;
1506 if (msr >= MSR_IA32_MC0_CTL &&
1507 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1508 u32 offset = msr - MSR_IA32_MC0_CTL;
1509 data = vcpu->arch.mce_banks[offset];
1518 static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1521 struct kvm *kvm = vcpu->kvm;
1524 case HV_X64_MSR_GUEST_OS_ID:
1525 data = kvm->arch.hv_guest_os_id;
1527 case HV_X64_MSR_HYPERCALL:
1528 data = kvm->arch.hv_hypercall;
1531 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1539 static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1544 case HV_X64_MSR_VP_INDEX: {
1547 kvm_for_each_vcpu(r, v, vcpu->kvm)
1552 case HV_X64_MSR_EOI:
1553 return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
1554 case HV_X64_MSR_ICR:
1555 return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
1556 case HV_X64_MSR_TPR:
1557 return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
1559 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1566 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1571 case MSR_IA32_PLATFORM_ID:
1572 case MSR_IA32_UCODE_REV:
1573 case MSR_IA32_EBL_CR_POWERON:
1574 case MSR_IA32_DEBUGCTLMSR:
1575 case MSR_IA32_LASTBRANCHFROMIP:
1576 case MSR_IA32_LASTBRANCHTOIP:
1577 case MSR_IA32_LASTINTFROMIP:
1578 case MSR_IA32_LASTINTTOIP:
1581 case MSR_VM_HSAVE_PA:
1582 case MSR_P6_PERFCTR0:
1583 case MSR_P6_PERFCTR1:
1584 case MSR_P6_EVNTSEL0:
1585 case MSR_P6_EVNTSEL1:
1586 case MSR_K7_EVNTSEL0:
1587 case MSR_K7_PERFCTR0:
1588 case MSR_K8_INT_PENDING_MSG:
1589 case MSR_AMD64_NB_CFG:
1590 case MSR_FAM10H_MMIO_CONF_BASE:
1594 data = 0x500 | KVM_NR_VAR_MTRR;
1596 case 0x200 ... 0x2ff:
1597 return get_msr_mtrr(vcpu, msr, pdata);
1598 case 0xcd: /* fsb frequency */
1601 case MSR_IA32_APICBASE:
1602 data = kvm_get_apic_base(vcpu);
1604 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1605 return kvm_x2apic_msr_read(vcpu, msr, pdata);
1607 case MSR_IA32_MISC_ENABLE:
1608 data = vcpu->arch.ia32_misc_enable_msr;
1610 case MSR_IA32_PERF_STATUS:
1611 /* TSC increment by tick */
1613 /* CPU multiplier */
1614 data |= (((uint64_t)4ULL) << 40);
1617 data = vcpu->arch.efer;
1619 case MSR_KVM_WALL_CLOCK:
1620 case MSR_KVM_WALL_CLOCK_NEW:
1621 data = vcpu->kvm->arch.wall_clock;
1623 case MSR_KVM_SYSTEM_TIME:
1624 case MSR_KVM_SYSTEM_TIME_NEW:
1625 data = vcpu->arch.time;
1627 case MSR_IA32_P5_MC_ADDR:
1628 case MSR_IA32_P5_MC_TYPE:
1629 case MSR_IA32_MCG_CAP:
1630 case MSR_IA32_MCG_CTL:
1631 case MSR_IA32_MCG_STATUS:
1632 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1633 return get_msr_mce(vcpu, msr, pdata);
1634 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1635 if (kvm_hv_msr_partition_wide(msr)) {
1637 mutex_lock(&vcpu->kvm->lock);
1638 r = get_msr_hyperv_pw(vcpu, msr, pdata);
1639 mutex_unlock(&vcpu->kvm->lock);
1642 return get_msr_hyperv(vcpu, msr, pdata);
1646 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
1649 pr_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
1657 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
1660 * Read or write a bunch of msrs. All parameters are kernel addresses.
1662 * @return number of msrs set successfully.
1664 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
1665 struct kvm_msr_entry *entries,
1666 int (*do_msr)(struct kvm_vcpu *vcpu,
1667 unsigned index, u64 *data))
1671 idx = srcu_read_lock(&vcpu->kvm->srcu);
1672 for (i = 0; i < msrs->nmsrs; ++i)
1673 if (do_msr(vcpu, entries[i].index, &entries[i].data))
1675 srcu_read_unlock(&vcpu->kvm->srcu, idx);
1681 * Read or write a bunch of msrs. Parameters are user addresses.
1683 * @return number of msrs set successfully.
1685 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
1686 int (*do_msr)(struct kvm_vcpu *vcpu,
1687 unsigned index, u64 *data),
1690 struct kvm_msrs msrs;
1691 struct kvm_msr_entry *entries;
1696 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
1700 if (msrs.nmsrs >= MAX_IO_MSRS)
1704 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
1705 entries = kmalloc(size, GFP_KERNEL);
1710 if (copy_from_user(entries, user_msrs->entries, size))
1713 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
1718 if (writeback && copy_to_user(user_msrs->entries, entries, size))
1729 int kvm_dev_ioctl_check_extension(long ext)
1734 case KVM_CAP_IRQCHIP:
1736 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
1737 case KVM_CAP_SET_TSS_ADDR:
1738 case KVM_CAP_EXT_CPUID:
1739 case KVM_CAP_CLOCKSOURCE:
1741 case KVM_CAP_NOP_IO_DELAY:
1742 case KVM_CAP_MP_STATE:
1743 case KVM_CAP_SYNC_MMU:
1744 case KVM_CAP_REINJECT_CONTROL:
1745 case KVM_CAP_IRQ_INJECT_STATUS:
1746 case KVM_CAP_ASSIGN_DEV_IRQ:
1748 case KVM_CAP_IOEVENTFD:
1750 case KVM_CAP_PIT_STATE2:
1751 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
1752 case KVM_CAP_XEN_HVM:
1753 case KVM_CAP_ADJUST_CLOCK:
1754 case KVM_CAP_VCPU_EVENTS:
1755 case KVM_CAP_HYPERV:
1756 case KVM_CAP_HYPERV_VAPIC:
1757 case KVM_CAP_HYPERV_SPIN:
1758 case KVM_CAP_PCI_SEGMENT:
1759 case KVM_CAP_DEBUGREGS:
1760 case KVM_CAP_X86_ROBUST_SINGLESTEP:
1764 case KVM_CAP_COALESCED_MMIO:
1765 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
1768 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
1770 case KVM_CAP_NR_VCPUS:
1773 case KVM_CAP_NR_MEMSLOTS:
1774 r = KVM_MEMORY_SLOTS;
1776 case KVM_CAP_PV_MMU: /* obsolete */
1783 r = KVM_MAX_MCE_BANKS;
1796 long kvm_arch_dev_ioctl(struct file *filp,
1797 unsigned int ioctl, unsigned long arg)
1799 void __user *argp = (void __user *)arg;
1803 case KVM_GET_MSR_INDEX_LIST: {
1804 struct kvm_msr_list __user *user_msr_list = argp;
1805 struct kvm_msr_list msr_list;
1809 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
1812 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
1813 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
1816 if (n < msr_list.nmsrs)
1819 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
1820 num_msrs_to_save * sizeof(u32)))
1822 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
1824 ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
1829 case KVM_GET_SUPPORTED_CPUID: {
1830 struct kvm_cpuid2 __user *cpuid_arg = argp;
1831 struct kvm_cpuid2 cpuid;
1834 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1836 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
1837 cpuid_arg->entries);
1842 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1847 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
1850 mce_cap = KVM_MCE_CAP_SUPPORTED;
1852 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
1864 static void wbinvd_ipi(void *garbage)
1869 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
1871 return vcpu->kvm->arch.iommu_domain &&
1872 !(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY);
1875 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1877 /* Address WBINVD may be executed by guest */
1878 if (need_emulate_wbinvd(vcpu)) {
1879 if (kvm_x86_ops->has_wbinvd_exit())
1880 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
1881 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
1882 smp_call_function_single(vcpu->cpu,
1883 wbinvd_ipi, NULL, 1);
1886 kvm_x86_ops->vcpu_load(vcpu, cpu);
1887 if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
1888 /* Make sure TSC doesn't go backwards */
1889 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
1890 native_read_tsc() - vcpu->arch.last_host_tsc;
1892 mark_tsc_unstable("KVM discovered backwards TSC");
1893 if (check_tsc_unstable())
1894 kvm_x86_ops->adjust_tsc_offset(vcpu, -tsc_delta);
1895 kvm_migrate_timers(vcpu);
1900 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
1902 kvm_x86_ops->vcpu_put(vcpu);
1903 kvm_put_guest_fpu(vcpu);
1904 vcpu->arch.last_host_tsc = native_read_tsc();
1907 static int is_efer_nx(void)
1909 unsigned long long efer = 0;
1911 rdmsrl_safe(MSR_EFER, &efer);
1912 return efer & EFER_NX;
1915 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
1918 struct kvm_cpuid_entry2 *e, *entry;
1921 for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
1922 e = &vcpu->arch.cpuid_entries[i];
1923 if (e->function == 0x80000001) {
1928 if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
1929 entry->edx &= ~(1 << 20);
1930 printk(KERN_INFO "kvm: guest NX capability removed\n");
1934 /* when an old userspace process fills a new kernel module */
1935 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
1936 struct kvm_cpuid *cpuid,
1937 struct kvm_cpuid_entry __user *entries)
1940 struct kvm_cpuid_entry *cpuid_entries;
1943 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1946 cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
1950 if (copy_from_user(cpuid_entries, entries,
1951 cpuid->nent * sizeof(struct kvm_cpuid_entry)))
1953 for (i = 0; i < cpuid->nent; i++) {
1954 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
1955 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
1956 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
1957 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
1958 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
1959 vcpu->arch.cpuid_entries[i].index = 0;
1960 vcpu->arch.cpuid_entries[i].flags = 0;
1961 vcpu->arch.cpuid_entries[i].padding[0] = 0;
1962 vcpu->arch.cpuid_entries[i].padding[1] = 0;
1963 vcpu->arch.cpuid_entries[i].padding[2] = 0;
1965 vcpu->arch.cpuid_nent = cpuid->nent;
1966 cpuid_fix_nx_cap(vcpu);
1968 kvm_apic_set_version(vcpu);
1969 kvm_x86_ops->cpuid_update(vcpu);
1973 vfree(cpuid_entries);
1978 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
1979 struct kvm_cpuid2 *cpuid,
1980 struct kvm_cpuid_entry2 __user *entries)
1985 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1988 if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
1989 cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
1991 vcpu->arch.cpuid_nent = cpuid->nent;
1992 kvm_apic_set_version(vcpu);
1993 kvm_x86_ops->cpuid_update(vcpu);
2001 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
2002 struct kvm_cpuid2 *cpuid,
2003 struct kvm_cpuid_entry2 __user *entries)
2008 if (cpuid->nent < vcpu->arch.cpuid_nent)
2011 if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
2012 vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
2017 cpuid->nent = vcpu->arch.cpuid_nent;
2021 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
2024 entry->function = function;
2025 entry->index = index;
2026 cpuid_count(entry->function, entry->index,
2027 &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
2031 #define F(x) bit(X86_FEATURE_##x)
2033 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
2034 u32 index, int *nent, int maxnent)
2036 unsigned f_nx = is_efer_nx() ? F(NX) : 0;
2037 #ifdef CONFIG_X86_64
2038 unsigned f_gbpages = (kvm_x86_ops->get_lpage_level() == PT_PDPE_LEVEL)
2040 unsigned f_lm = F(LM);
2042 unsigned f_gbpages = 0;
2045 unsigned f_rdtscp = kvm_x86_ops->rdtscp_supported() ? F(RDTSCP) : 0;
2048 const u32 kvm_supported_word0_x86_features =
2049 F(FPU) | F(VME) | F(DE) | F(PSE) |
2050 F(TSC) | F(MSR) | F(PAE) | F(MCE) |
2051 F(CX8) | F(APIC) | 0 /* Reserved */ | F(SEP) |
2052 F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
2053 F(PAT) | F(PSE36) | 0 /* PSN */ | F(CLFLSH) |
2054 0 /* Reserved, DS, ACPI */ | F(MMX) |
2055 F(FXSR) | F(XMM) | F(XMM2) | F(SELFSNOOP) |
2056 0 /* HTT, TM, Reserved, PBE */;
2057 /* cpuid 0x80000001.edx */
2058 const u32 kvm_supported_word1_x86_features =
2059 F(FPU) | F(VME) | F(DE) | F(PSE) |
2060 F(TSC) | F(MSR) | F(PAE) | F(MCE) |
2061 F(CX8) | F(APIC) | 0 /* Reserved */ | F(SYSCALL) |
2062 F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
2063 F(PAT) | F(PSE36) | 0 /* Reserved */ |
2064 f_nx | 0 /* Reserved */ | F(MMXEXT) | F(MMX) |
2065 F(FXSR) | F(FXSR_OPT) | f_gbpages | f_rdtscp |
2066 0 /* Reserved */ | f_lm | F(3DNOWEXT) | F(3DNOW);
2068 const u32 kvm_supported_word4_x86_features =
2069 F(XMM3) | F(PCLMULQDQ) | 0 /* DTES64, MONITOR */ |
2070 0 /* DS-CPL, VMX, SMX, EST */ |
2071 0 /* TM2 */ | F(SSSE3) | 0 /* CNXT-ID */ | 0 /* Reserved */ |
2072 0 /* Reserved */ | F(CX16) | 0 /* xTPR Update, PDCM */ |
2073 0 /* Reserved, DCA */ | F(XMM4_1) |
2074 F(XMM4_2) | F(X2APIC) | F(MOVBE) | F(POPCNT) |
2075 0 /* Reserved, AES */ | F(XSAVE) | 0 /* OSXSAVE */ | F(AVX);
2076 /* cpuid 0x80000001.ecx */
2077 const u32 kvm_supported_word6_x86_features =
2078 F(LAHF_LM) | F(CMP_LEGACY) | F(SVM) | 0 /* ExtApicSpace */ |
2079 F(CR8_LEGACY) | F(ABM) | F(SSE4A) | F(MISALIGNSSE) |
2080 F(3DNOWPREFETCH) | 0 /* OSVW */ | 0 /* IBS */ | F(SSE5) |
2081 0 /* SKINIT */ | 0 /* WDT */;
2083 /* all calls to cpuid_count() should be made on the same cpu */
2085 do_cpuid_1_ent(entry, function, index);
2090 entry->eax = min(entry->eax, (u32)0xd);
2093 entry->edx &= kvm_supported_word0_x86_features;
2094 entry->ecx &= kvm_supported_word4_x86_features;
2095 /* we support x2apic emulation even if host does not support
2096 * it since we emulate x2apic in software */
2097 entry->ecx |= F(X2APIC);
2099 /* function 2 entries are STATEFUL. That is, repeated cpuid commands
2100 * may return different values. This forces us to get_cpu() before
2101 * issuing the first command, and also to emulate this annoying behavior
2102 * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
2104 int t, times = entry->eax & 0xff;
2106 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
2107 entry->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
2108 for (t = 1; t < times && *nent < maxnent; ++t) {
2109 do_cpuid_1_ent(&entry[t], function, 0);
2110 entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
2115 /* function 4 and 0xb have additional index. */
2119 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2120 /* read more entries until cache_type is zero */
2121 for (i = 1; *nent < maxnent; ++i) {
2122 cache_type = entry[i - 1].eax & 0x1f;
2125 do_cpuid_1_ent(&entry[i], function, i);
2127 KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2135 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2136 /* read more entries until level_type is zero */
2137 for (i = 1; *nent < maxnent; ++i) {
2138 level_type = entry[i - 1].ecx & 0xff00;
2141 do_cpuid_1_ent(&entry[i], function, i);
2143 KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2151 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2152 for (i = 1; *nent < maxnent; ++i) {
2153 if (entry[i - 1].eax == 0 && i != 2)
2155 do_cpuid_1_ent(&entry[i], function, i);
2157 KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2162 case KVM_CPUID_SIGNATURE: {
2163 char signature[12] = "KVMKVMKVM\0\0";
2164 u32 *sigptr = (u32 *)signature;
2166 entry->ebx = sigptr[0];
2167 entry->ecx = sigptr[1];
2168 entry->edx = sigptr[2];
2171 case KVM_CPUID_FEATURES:
2172 entry->eax = (1 << KVM_FEATURE_CLOCKSOURCE) |
2173 (1 << KVM_FEATURE_NOP_IO_DELAY) |
2174 (1 << KVM_FEATURE_CLOCKSOURCE2) |
2175 (1 << KVM_FEATURE_CLOCKSOURCE_STABLE_BIT);
2181 entry->eax = min(entry->eax, 0x8000001a);
2184 entry->edx &= kvm_supported_word1_x86_features;
2185 entry->ecx &= kvm_supported_word6_x86_features;
2189 kvm_x86_ops->set_supported_cpuid(function, entry);
2196 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
2197 struct kvm_cpuid_entry2 __user *entries)
2199 struct kvm_cpuid_entry2 *cpuid_entries;
2200 int limit, nent = 0, r = -E2BIG;
2203 if (cpuid->nent < 1)
2205 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2206 cpuid->nent = KVM_MAX_CPUID_ENTRIES;
2208 cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
2212 do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
2213 limit = cpuid_entries[0].eax;
2214 for (func = 1; func <= limit && nent < cpuid->nent; ++func)
2215 do_cpuid_ent(&cpuid_entries[nent], func, 0,
2216 &nent, cpuid->nent);
2218 if (nent >= cpuid->nent)
2221 do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
2222 limit = cpuid_entries[nent - 1].eax;
2223 for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
2224 do_cpuid_ent(&cpuid_entries[nent], func, 0,
2225 &nent, cpuid->nent);
2230 if (nent >= cpuid->nent)
2233 do_cpuid_ent(&cpuid_entries[nent], KVM_CPUID_SIGNATURE, 0, &nent,
2237 if (nent >= cpuid->nent)
2240 do_cpuid_ent(&cpuid_entries[nent], KVM_CPUID_FEATURES, 0, &nent,
2244 if (nent >= cpuid->nent)
2248 if (copy_to_user(entries, cpuid_entries,
2249 nent * sizeof(struct kvm_cpuid_entry2)))
2255 vfree(cpuid_entries);
2260 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2261 struct kvm_lapic_state *s)
2263 memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2268 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2269 struct kvm_lapic_state *s)
2271 memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
2272 kvm_apic_post_state_restore(vcpu);
2273 update_cr8_intercept(vcpu);
2278 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2279 struct kvm_interrupt *irq)
2281 if (irq->irq < 0 || irq->irq >= 256)
2283 if (irqchip_in_kernel(vcpu->kvm))
2286 kvm_queue_interrupt(vcpu, irq->irq, false);
2291 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2293 kvm_inject_nmi(vcpu);
2298 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2299 struct kvm_tpr_access_ctl *tac)
2303 vcpu->arch.tpr_access_reporting = !!tac->enabled;
2307 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2311 unsigned bank_num = mcg_cap & 0xff, bank;
2314 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2316 if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2319 vcpu->arch.mcg_cap = mcg_cap;
2320 /* Init IA32_MCG_CTL to all 1s */
2321 if (mcg_cap & MCG_CTL_P)
2322 vcpu->arch.mcg_ctl = ~(u64)0;
2323 /* Init IA32_MCi_CTL to all 1s */
2324 for (bank = 0; bank < bank_num; bank++)
2325 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2330 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2331 struct kvm_x86_mce *mce)
2333 u64 mcg_cap = vcpu->arch.mcg_cap;
2334 unsigned bank_num = mcg_cap & 0xff;
2335 u64 *banks = vcpu->arch.mce_banks;
2337 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2340 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2341 * reporting is disabled
2343 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2344 vcpu->arch.mcg_ctl != ~(u64)0)
2346 banks += 4 * mce->bank;
2348 * if IA32_MCi_CTL is not all 1s, the uncorrected error
2349 * reporting is disabled for the bank
2351 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2353 if (mce->status & MCI_STATUS_UC) {
2354 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2355 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2356 printk(KERN_DEBUG "kvm: set_mce: "
2357 "injects mce exception while "
2358 "previous one is in progress!\n");
2359 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2362 if (banks[1] & MCI_STATUS_VAL)
2363 mce->status |= MCI_STATUS_OVER;
2364 banks[2] = mce->addr;
2365 banks[3] = mce->misc;
2366 vcpu->arch.mcg_status = mce->mcg_status;
2367 banks[1] = mce->status;
2368 kvm_queue_exception(vcpu, MC_VECTOR);
2369 } else if (!(banks[1] & MCI_STATUS_VAL)
2370 || !(banks[1] & MCI_STATUS_UC)) {
2371 if (banks[1] & MCI_STATUS_VAL)
2372 mce->status |= MCI_STATUS_OVER;
2373 banks[2] = mce->addr;
2374 banks[3] = mce->misc;
2375 banks[1] = mce->status;
2377 banks[1] |= MCI_STATUS_OVER;
2381 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2382 struct kvm_vcpu_events *events)
2384 events->exception.injected =
2385 vcpu->arch.exception.pending &&
2386 !kvm_exception_is_soft(vcpu->arch.exception.nr);
2387 events->exception.nr = vcpu->arch.exception.nr;
2388 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2389 events->exception.error_code = vcpu->arch.exception.error_code;
2391 events->interrupt.injected =
2392 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
2393 events->interrupt.nr = vcpu->arch.interrupt.nr;
2394 events->interrupt.soft = 0;
2395 events->interrupt.shadow =
2396 kvm_x86_ops->get_interrupt_shadow(vcpu,
2397 KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
2399 events->nmi.injected = vcpu->arch.nmi_injected;
2400 events->nmi.pending = vcpu->arch.nmi_pending;
2401 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
2403 events->sipi_vector = vcpu->arch.sipi_vector;
2405 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
2406 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2407 | KVM_VCPUEVENT_VALID_SHADOW);
2410 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
2411 struct kvm_vcpu_events *events)
2413 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
2414 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2415 | KVM_VCPUEVENT_VALID_SHADOW))
2418 vcpu->arch.exception.pending = events->exception.injected;
2419 vcpu->arch.exception.nr = events->exception.nr;
2420 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
2421 vcpu->arch.exception.error_code = events->exception.error_code;
2423 vcpu->arch.interrupt.pending = events->interrupt.injected;
2424 vcpu->arch.interrupt.nr = events->interrupt.nr;
2425 vcpu->arch.interrupt.soft = events->interrupt.soft;
2426 if (vcpu->arch.interrupt.pending && irqchip_in_kernel(vcpu->kvm))
2427 kvm_pic_clear_isr_ack(vcpu->kvm);
2428 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
2429 kvm_x86_ops->set_interrupt_shadow(vcpu,
2430 events->interrupt.shadow);
2432 vcpu->arch.nmi_injected = events->nmi.injected;
2433 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
2434 vcpu->arch.nmi_pending = events->nmi.pending;
2435 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
2437 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR)
2438 vcpu->arch.sipi_vector = events->sipi_vector;
2443 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
2444 struct kvm_debugregs *dbgregs)
2446 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
2447 dbgregs->dr6 = vcpu->arch.dr6;
2448 dbgregs->dr7 = vcpu->arch.dr7;
2452 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
2453 struct kvm_debugregs *dbgregs)
2458 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
2459 vcpu->arch.dr6 = dbgregs->dr6;
2460 vcpu->arch.dr7 = dbgregs->dr7;
2465 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
2466 struct kvm_xsave *guest_xsave)
2469 memcpy(guest_xsave->region,
2470 &vcpu->arch.guest_fpu.state->xsave,
2473 memcpy(guest_xsave->region,
2474 &vcpu->arch.guest_fpu.state->fxsave,
2475 sizeof(struct i387_fxsave_struct));
2476 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
2481 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
2482 struct kvm_xsave *guest_xsave)
2485 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
2488 memcpy(&vcpu->arch.guest_fpu.state->xsave,
2489 guest_xsave->region, xstate_size);
2491 if (xstate_bv & ~XSTATE_FPSSE)
2493 memcpy(&vcpu->arch.guest_fpu.state->fxsave,
2494 guest_xsave->region, sizeof(struct i387_fxsave_struct));
2499 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
2500 struct kvm_xcrs *guest_xcrs)
2502 if (!cpu_has_xsave) {
2503 guest_xcrs->nr_xcrs = 0;
2507 guest_xcrs->nr_xcrs = 1;
2508 guest_xcrs->flags = 0;
2509 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
2510 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
2513 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
2514 struct kvm_xcrs *guest_xcrs)
2521 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
2524 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
2525 /* Only support XCR0 currently */
2526 if (guest_xcrs->xcrs[0].xcr == XCR_XFEATURE_ENABLED_MASK) {
2527 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
2528 guest_xcrs->xcrs[0].value);
2536 long kvm_arch_vcpu_ioctl(struct file *filp,
2537 unsigned int ioctl, unsigned long arg)
2539 struct kvm_vcpu *vcpu = filp->private_data;
2540 void __user *argp = (void __user *)arg;
2543 struct kvm_lapic_state *lapic;
2544 struct kvm_xsave *xsave;
2545 struct kvm_xcrs *xcrs;
2551 case KVM_GET_LAPIC: {
2553 if (!vcpu->arch.apic)
2555 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
2560 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
2564 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
2569 case KVM_SET_LAPIC: {
2571 if (!vcpu->arch.apic)
2573 u.lapic = kmalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
2578 if (copy_from_user(u.lapic, argp, sizeof(struct kvm_lapic_state)))
2580 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
2586 case KVM_INTERRUPT: {
2587 struct kvm_interrupt irq;
2590 if (copy_from_user(&irq, argp, sizeof irq))
2592 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
2599 r = kvm_vcpu_ioctl_nmi(vcpu);
2605 case KVM_SET_CPUID: {
2606 struct kvm_cpuid __user *cpuid_arg = argp;
2607 struct kvm_cpuid cpuid;
2610 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2612 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
2617 case KVM_SET_CPUID2: {
2618 struct kvm_cpuid2 __user *cpuid_arg = argp;
2619 struct kvm_cpuid2 cpuid;
2622 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2624 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
2625 cpuid_arg->entries);
2630 case KVM_GET_CPUID2: {
2631 struct kvm_cpuid2 __user *cpuid_arg = argp;
2632 struct kvm_cpuid2 cpuid;
2635 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2637 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
2638 cpuid_arg->entries);
2642 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2648 r = msr_io(vcpu, argp, kvm_get_msr, 1);
2651 r = msr_io(vcpu, argp, do_set_msr, 0);
2653 case KVM_TPR_ACCESS_REPORTING: {
2654 struct kvm_tpr_access_ctl tac;
2657 if (copy_from_user(&tac, argp, sizeof tac))
2659 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
2663 if (copy_to_user(argp, &tac, sizeof tac))
2668 case KVM_SET_VAPIC_ADDR: {
2669 struct kvm_vapic_addr va;
2672 if (!irqchip_in_kernel(vcpu->kvm))
2675 if (copy_from_user(&va, argp, sizeof va))
2678 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
2681 case KVM_X86_SETUP_MCE: {
2685 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
2687 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
2690 case KVM_X86_SET_MCE: {
2691 struct kvm_x86_mce mce;
2694 if (copy_from_user(&mce, argp, sizeof mce))
2696 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
2699 case KVM_GET_VCPU_EVENTS: {
2700 struct kvm_vcpu_events events;
2702 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
2705 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
2710 case KVM_SET_VCPU_EVENTS: {
2711 struct kvm_vcpu_events events;
2714 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
2717 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
2720 case KVM_GET_DEBUGREGS: {
2721 struct kvm_debugregs dbgregs;
2723 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
2726 if (copy_to_user(argp, &dbgregs,
2727 sizeof(struct kvm_debugregs)))
2732 case KVM_SET_DEBUGREGS: {
2733 struct kvm_debugregs dbgregs;
2736 if (copy_from_user(&dbgregs, argp,
2737 sizeof(struct kvm_debugregs)))
2740 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
2743 case KVM_GET_XSAVE: {
2744 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
2749 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
2752 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
2757 case KVM_SET_XSAVE: {
2758 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
2764 if (copy_from_user(u.xsave, argp, sizeof(struct kvm_xsave)))
2767 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
2770 case KVM_GET_XCRS: {
2771 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
2776 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
2779 if (copy_to_user(argp, u.xcrs,
2780 sizeof(struct kvm_xcrs)))
2785 case KVM_SET_XCRS: {
2786 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
2792 if (copy_from_user(u.xcrs, argp,
2793 sizeof(struct kvm_xcrs)))
2796 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
2807 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
2811 if (addr > (unsigned int)(-3 * PAGE_SIZE))
2813 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
2817 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
2820 kvm->arch.ept_identity_map_addr = ident_addr;
2824 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
2825 u32 kvm_nr_mmu_pages)
2827 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
2830 mutex_lock(&kvm->slots_lock);
2831 spin_lock(&kvm->mmu_lock);
2833 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
2834 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
2836 spin_unlock(&kvm->mmu_lock);
2837 mutex_unlock(&kvm->slots_lock);
2841 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
2843 return kvm->arch.n_max_mmu_pages;
2846 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2851 switch (chip->chip_id) {
2852 case KVM_IRQCHIP_PIC_MASTER:
2853 memcpy(&chip->chip.pic,
2854 &pic_irqchip(kvm)->pics[0],
2855 sizeof(struct kvm_pic_state));
2857 case KVM_IRQCHIP_PIC_SLAVE:
2858 memcpy(&chip->chip.pic,
2859 &pic_irqchip(kvm)->pics[1],
2860 sizeof(struct kvm_pic_state));
2862 case KVM_IRQCHIP_IOAPIC:
2863 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
2872 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2877 switch (chip->chip_id) {
2878 case KVM_IRQCHIP_PIC_MASTER:
2879 raw_spin_lock(&pic_irqchip(kvm)->lock);
2880 memcpy(&pic_irqchip(kvm)->pics[0],
2882 sizeof(struct kvm_pic_state));
2883 raw_spin_unlock(&pic_irqchip(kvm)->lock);
2885 case KVM_IRQCHIP_PIC_SLAVE:
2886 raw_spin_lock(&pic_irqchip(kvm)->lock);
2887 memcpy(&pic_irqchip(kvm)->pics[1],
2889 sizeof(struct kvm_pic_state));
2890 raw_spin_unlock(&pic_irqchip(kvm)->lock);
2892 case KVM_IRQCHIP_IOAPIC:
2893 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
2899 kvm_pic_update_irq(pic_irqchip(kvm));
2903 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2907 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2908 memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
2909 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2913 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2917 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2918 memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
2919 kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
2920 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2924 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2928 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2929 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
2930 sizeof(ps->channels));
2931 ps->flags = kvm->arch.vpit->pit_state.flags;
2932 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2936 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2938 int r = 0, start = 0;
2939 u32 prev_legacy, cur_legacy;
2940 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2941 prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
2942 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
2943 if (!prev_legacy && cur_legacy)
2945 memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
2946 sizeof(kvm->arch.vpit->pit_state.channels));
2947 kvm->arch.vpit->pit_state.flags = ps->flags;
2948 kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
2949 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2953 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
2954 struct kvm_reinject_control *control)
2956 if (!kvm->arch.vpit)
2958 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2959 kvm->arch.vpit->pit_state.pit_timer.reinject = control->pit_reinject;
2960 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2965 * Get (and clear) the dirty memory log for a memory slot.
2967 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
2968 struct kvm_dirty_log *log)
2971 struct kvm_memory_slot *memslot;
2973 unsigned long is_dirty = 0;
2975 mutex_lock(&kvm->slots_lock);
2978 if (log->slot >= KVM_MEMORY_SLOTS)
2981 memslot = &kvm->memslots->memslots[log->slot];
2983 if (!memslot->dirty_bitmap)
2986 n = kvm_dirty_bitmap_bytes(memslot);
2988 for (i = 0; !is_dirty && i < n/sizeof(long); i++)
2989 is_dirty = memslot->dirty_bitmap[i];
2991 /* If nothing is dirty, don't bother messing with page tables. */
2993 struct kvm_memslots *slots, *old_slots;
2994 unsigned long *dirty_bitmap;
2996 spin_lock(&kvm->mmu_lock);
2997 kvm_mmu_slot_remove_write_access(kvm, log->slot);
2998 spin_unlock(&kvm->mmu_lock);
3001 dirty_bitmap = vmalloc(n);
3004 memset(dirty_bitmap, 0, n);
3007 slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
3009 vfree(dirty_bitmap);
3012 memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
3013 slots->memslots[log->slot].dirty_bitmap = dirty_bitmap;
3015 old_slots = kvm->memslots;
3016 rcu_assign_pointer(kvm->memslots, slots);
3017 synchronize_srcu_expedited(&kvm->srcu);
3018 dirty_bitmap = old_slots->memslots[log->slot].dirty_bitmap;
3022 if (copy_to_user(log->dirty_bitmap, dirty_bitmap, n)) {
3023 vfree(dirty_bitmap);
3026 vfree(dirty_bitmap);
3029 if (clear_user(log->dirty_bitmap, n))
3035 mutex_unlock(&kvm->slots_lock);
3039 long kvm_arch_vm_ioctl(struct file *filp,
3040 unsigned int ioctl, unsigned long arg)
3042 struct kvm *kvm = filp->private_data;
3043 void __user *argp = (void __user *)arg;
3046 * This union makes it completely explicit to gcc-3.x
3047 * that these two variables' stack usage should be
3048 * combined, not added together.
3051 struct kvm_pit_state ps;
3052 struct kvm_pit_state2 ps2;
3053 struct kvm_pit_config pit_config;
3057 case KVM_SET_TSS_ADDR:
3058 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3062 case KVM_SET_IDENTITY_MAP_ADDR: {
3066 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3068 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3073 case KVM_SET_NR_MMU_PAGES:
3074 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3078 case KVM_GET_NR_MMU_PAGES:
3079 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3081 case KVM_CREATE_IRQCHIP: {
3082 struct kvm_pic *vpic;
3084 mutex_lock(&kvm->lock);
3087 goto create_irqchip_unlock;
3089 vpic = kvm_create_pic(kvm);
3091 r = kvm_ioapic_init(kvm);
3093 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3096 goto create_irqchip_unlock;
3099 goto create_irqchip_unlock;
3101 kvm->arch.vpic = vpic;
3103 r = kvm_setup_default_irq_routing(kvm);
3105 mutex_lock(&kvm->irq_lock);
3106 kvm_ioapic_destroy(kvm);
3107 kvm_destroy_pic(kvm);
3108 mutex_unlock(&kvm->irq_lock);
3110 create_irqchip_unlock:
3111 mutex_unlock(&kvm->lock);
3114 case KVM_CREATE_PIT:
3115 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3117 case KVM_CREATE_PIT2:
3119 if (copy_from_user(&u.pit_config, argp,
3120 sizeof(struct kvm_pit_config)))
3123 mutex_lock(&kvm->slots_lock);
3126 goto create_pit_unlock;
3128 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3132 mutex_unlock(&kvm->slots_lock);
3134 case KVM_IRQ_LINE_STATUS:
3135 case KVM_IRQ_LINE: {
3136 struct kvm_irq_level irq_event;
3139 if (copy_from_user(&irq_event, argp, sizeof irq_event))
3142 if (irqchip_in_kernel(kvm)) {
3144 status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3145 irq_event.irq, irq_event.level);
3146 if (ioctl == KVM_IRQ_LINE_STATUS) {
3148 irq_event.status = status;
3149 if (copy_to_user(argp, &irq_event,
3157 case KVM_GET_IRQCHIP: {
3158 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3159 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
3165 if (copy_from_user(chip, argp, sizeof *chip))
3166 goto get_irqchip_out;
3168 if (!irqchip_in_kernel(kvm))
3169 goto get_irqchip_out;
3170 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3172 goto get_irqchip_out;
3174 if (copy_to_user(argp, chip, sizeof *chip))
3175 goto get_irqchip_out;
3183 case KVM_SET_IRQCHIP: {
3184 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3185 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
3191 if (copy_from_user(chip, argp, sizeof *chip))
3192 goto set_irqchip_out;
3194 if (!irqchip_in_kernel(kvm))
3195 goto set_irqchip_out;
3196 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3198 goto set_irqchip_out;
3208 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
3211 if (!kvm->arch.vpit)
3213 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
3217 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
3224 if (copy_from_user(&u.ps, argp, sizeof u.ps))
3227 if (!kvm->arch.vpit)
3229 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
3235 case KVM_GET_PIT2: {
3237 if (!kvm->arch.vpit)
3239 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
3243 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
3248 case KVM_SET_PIT2: {
3250 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
3253 if (!kvm->arch.vpit)
3255 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
3261 case KVM_REINJECT_CONTROL: {
3262 struct kvm_reinject_control control;
3264 if (copy_from_user(&control, argp, sizeof(control)))
3266 r = kvm_vm_ioctl_reinject(kvm, &control);
3272 case KVM_XEN_HVM_CONFIG: {
3274 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
3275 sizeof(struct kvm_xen_hvm_config)))
3278 if (kvm->arch.xen_hvm_config.flags)
3283 case KVM_SET_CLOCK: {
3284 struct kvm_clock_data user_ns;
3289 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
3297 now_ns = get_kernel_ns();
3298 delta = user_ns.clock - now_ns;
3299 kvm->arch.kvmclock_offset = delta;
3302 case KVM_GET_CLOCK: {
3303 struct kvm_clock_data user_ns;
3306 now_ns = get_kernel_ns();
3307 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
3311 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
3324 static void kvm_init_msr_list(void)
3329 /* skip the first msrs in the list. KVM-specific */
3330 for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
3331 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
3334 msrs_to_save[j] = msrs_to_save[i];
3337 num_msrs_to_save = j;
3340 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
3343 if (vcpu->arch.apic &&
3344 !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, len, v))
3347 return kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, len, v);
3350 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
3352 if (vcpu->arch.apic &&
3353 !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, len, v))
3356 return kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, len, v);
3359 static void kvm_set_segment(struct kvm_vcpu *vcpu,
3360 struct kvm_segment *var, int seg)
3362 kvm_x86_ops->set_segment(vcpu, var, seg);
3365 void kvm_get_segment(struct kvm_vcpu *vcpu,
3366 struct kvm_segment *var, int seg)
3368 kvm_x86_ops->get_segment(vcpu, var, seg);
3371 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva, u32 *error)
3373 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3374 return vcpu->arch.mmu.gva_to_gpa(vcpu, gva, access, error);
3377 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva, u32 *error)
3379 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3380 access |= PFERR_FETCH_MASK;
3381 return vcpu->arch.mmu.gva_to_gpa(vcpu, gva, access, error);
3384 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva, u32 *error)
3386 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3387 access |= PFERR_WRITE_MASK;
3388 return vcpu->arch.mmu.gva_to_gpa(vcpu, gva, access, error);
3391 /* uses this to access any guest's mapped memory without checking CPL */
3392 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva, u32 *error)
3394 return vcpu->arch.mmu.gva_to_gpa(vcpu, gva, 0, error);
3397 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
3398 struct kvm_vcpu *vcpu, u32 access,
3402 int r = X86EMUL_CONTINUE;
3405 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr, access, error);
3406 unsigned offset = addr & (PAGE_SIZE-1);
3407 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
3410 if (gpa == UNMAPPED_GVA) {
3411 r = X86EMUL_PROPAGATE_FAULT;
3414 ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
3416 r = X86EMUL_IO_NEEDED;
3428 /* used for instruction fetching */
3429 static int kvm_fetch_guest_virt(gva_t addr, void *val, unsigned int bytes,
3430 struct kvm_vcpu *vcpu, u32 *error)
3432 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3433 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
3434 access | PFERR_FETCH_MASK, error);
3437 static int kvm_read_guest_virt(gva_t addr, void *val, unsigned int bytes,
3438 struct kvm_vcpu *vcpu, u32 *error)
3440 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3441 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
3445 static int kvm_read_guest_virt_system(gva_t addr, void *val, unsigned int bytes,
3446 struct kvm_vcpu *vcpu, u32 *error)
3448 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, error);
3451 static int kvm_write_guest_virt_system(gva_t addr, void *val,
3453 struct kvm_vcpu *vcpu,
3457 int r = X86EMUL_CONTINUE;
3460 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr,
3461 PFERR_WRITE_MASK, error);
3462 unsigned offset = addr & (PAGE_SIZE-1);
3463 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
3466 if (gpa == UNMAPPED_GVA) {
3467 r = X86EMUL_PROPAGATE_FAULT;
3470 ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
3472 r = X86EMUL_IO_NEEDED;
3484 static int emulator_read_emulated(unsigned long addr,
3487 unsigned int *error_code,
3488 struct kvm_vcpu *vcpu)
3492 if (vcpu->mmio_read_completed) {
3493 memcpy(val, vcpu->mmio_data, bytes);
3494 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
3495 vcpu->mmio_phys_addr, *(u64 *)val);
3496 vcpu->mmio_read_completed = 0;
3497 return X86EMUL_CONTINUE;
3500 gpa = kvm_mmu_gva_to_gpa_read(vcpu, addr, error_code);
3502 if (gpa == UNMAPPED_GVA)
3503 return X86EMUL_PROPAGATE_FAULT;
3505 /* For APIC access vmexit */
3506 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3509 if (kvm_read_guest_virt(addr, val, bytes, vcpu, NULL)
3510 == X86EMUL_CONTINUE)
3511 return X86EMUL_CONTINUE;
3515 * Is this MMIO handled locally?
3517 if (!vcpu_mmio_read(vcpu, gpa, bytes, val)) {
3518 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes, gpa, *(u64 *)val);
3519 return X86EMUL_CONTINUE;
3522 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
3524 vcpu->mmio_needed = 1;
3525 vcpu->run->exit_reason = KVM_EXIT_MMIO;
3526 vcpu->run->mmio.phys_addr = vcpu->mmio_phys_addr = gpa;
3527 vcpu->run->mmio.len = vcpu->mmio_size = bytes;
3528 vcpu->run->mmio.is_write = vcpu->mmio_is_write = 0;
3530 return X86EMUL_IO_NEEDED;
3533 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
3534 const void *val, int bytes)
3538 ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
3541 kvm_mmu_pte_write(vcpu, gpa, val, bytes, 1);
3545 static int emulator_write_emulated_onepage(unsigned long addr,
3548 unsigned int *error_code,
3549 struct kvm_vcpu *vcpu)
3553 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, error_code);
3555 if (gpa == UNMAPPED_GVA)
3556 return X86EMUL_PROPAGATE_FAULT;
3558 /* For APIC access vmexit */
3559 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3562 if (emulator_write_phys(vcpu, gpa, val, bytes))
3563 return X86EMUL_CONTINUE;
3566 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
3568 * Is this MMIO handled locally?
3570 if (!vcpu_mmio_write(vcpu, gpa, bytes, val))
3571 return X86EMUL_CONTINUE;
3573 vcpu->mmio_needed = 1;
3574 vcpu->run->exit_reason = KVM_EXIT_MMIO;
3575 vcpu->run->mmio.phys_addr = vcpu->mmio_phys_addr = gpa;
3576 vcpu->run->mmio.len = vcpu->mmio_size = bytes;
3577 vcpu->run->mmio.is_write = vcpu->mmio_is_write = 1;
3578 memcpy(vcpu->run->mmio.data, val, bytes);
3580 return X86EMUL_CONTINUE;
3583 int emulator_write_emulated(unsigned long addr,
3586 unsigned int *error_code,
3587 struct kvm_vcpu *vcpu)
3589 /* Crossing a page boundary? */
3590 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
3593 now = -addr & ~PAGE_MASK;
3594 rc = emulator_write_emulated_onepage(addr, val, now, error_code,
3596 if (rc != X86EMUL_CONTINUE)
3602 return emulator_write_emulated_onepage(addr, val, bytes, error_code,
3606 #define CMPXCHG_TYPE(t, ptr, old, new) \
3607 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
3609 #ifdef CONFIG_X86_64
3610 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
3612 # define CMPXCHG64(ptr, old, new) \
3613 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
3616 static int emulator_cmpxchg_emulated(unsigned long addr,
3620 unsigned int *error_code,
3621 struct kvm_vcpu *vcpu)
3628 /* guests cmpxchg8b have to be emulated atomically */
3629 if (bytes > 8 || (bytes & (bytes - 1)))
3632 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
3634 if (gpa == UNMAPPED_GVA ||
3635 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3638 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
3641 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
3642 if (is_error_page(page)) {
3643 kvm_release_page_clean(page);
3647 kaddr = kmap_atomic(page, KM_USER0);
3648 kaddr += offset_in_page(gpa);
3651 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
3654 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
3657 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
3660 exchanged = CMPXCHG64(kaddr, old, new);
3665 kunmap_atomic(kaddr, KM_USER0);
3666 kvm_release_page_dirty(page);
3669 return X86EMUL_CMPXCHG_FAILED;
3671 kvm_mmu_pte_write(vcpu, gpa, new, bytes, 1);
3673 return X86EMUL_CONTINUE;
3676 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
3678 return emulator_write_emulated(addr, new, bytes, error_code, vcpu);
3681 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
3683 /* TODO: String I/O for in kernel device */
3686 if (vcpu->arch.pio.in)
3687 r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
3688 vcpu->arch.pio.size, pd);
3690 r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
3691 vcpu->arch.pio.port, vcpu->arch.pio.size,
3697 static int emulator_pio_in_emulated(int size, unsigned short port, void *val,
3698 unsigned int count, struct kvm_vcpu *vcpu)
3700 if (vcpu->arch.pio.count)
3703 trace_kvm_pio(1, port, size, 1);
3705 vcpu->arch.pio.port = port;
3706 vcpu->arch.pio.in = 1;
3707 vcpu->arch.pio.count = count;
3708 vcpu->arch.pio.size = size;
3710 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
3712 memcpy(val, vcpu->arch.pio_data, size * count);
3713 vcpu->arch.pio.count = 0;
3717 vcpu->run->exit_reason = KVM_EXIT_IO;
3718 vcpu->run->io.direction = KVM_EXIT_IO_IN;
3719 vcpu->run->io.size = size;
3720 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
3721 vcpu->run->io.count = count;
3722 vcpu->run->io.port = port;
3727 static int emulator_pio_out_emulated(int size, unsigned short port,
3728 const void *val, unsigned int count,
3729 struct kvm_vcpu *vcpu)
3731 trace_kvm_pio(0, port, size, 1);
3733 vcpu->arch.pio.port = port;
3734 vcpu->arch.pio.in = 0;
3735 vcpu->arch.pio.count = count;
3736 vcpu->arch.pio.size = size;
3738 memcpy(vcpu->arch.pio_data, val, size * count);
3740 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
3741 vcpu->arch.pio.count = 0;
3745 vcpu->run->exit_reason = KVM_EXIT_IO;
3746 vcpu->run->io.direction = KVM_EXIT_IO_OUT;
3747 vcpu->run->io.size = size;
3748 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
3749 vcpu->run->io.count = count;
3750 vcpu->run->io.port = port;
3755 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
3757 return kvm_x86_ops->get_segment_base(vcpu, seg);
3760 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
3762 kvm_mmu_invlpg(vcpu, address);
3763 return X86EMUL_CONTINUE;
3766 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
3768 if (!need_emulate_wbinvd(vcpu))
3769 return X86EMUL_CONTINUE;
3771 if (kvm_x86_ops->has_wbinvd_exit()) {
3772 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
3773 wbinvd_ipi, NULL, 1);
3774 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
3777 return X86EMUL_CONTINUE;
3779 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
3781 int emulate_clts(struct kvm_vcpu *vcpu)
3783 kvm_x86_ops->set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
3784 kvm_x86_ops->fpu_activate(vcpu);
3785 return X86EMUL_CONTINUE;
3788 int emulator_get_dr(int dr, unsigned long *dest, struct kvm_vcpu *vcpu)
3790 return _kvm_get_dr(vcpu, dr, dest);
3793 int emulator_set_dr(int dr, unsigned long value, struct kvm_vcpu *vcpu)
3796 return __kvm_set_dr(vcpu, dr, value);
3799 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
3801 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
3804 static unsigned long emulator_get_cr(int cr, struct kvm_vcpu *vcpu)
3806 unsigned long value;
3810 value = kvm_read_cr0(vcpu);
3813 value = vcpu->arch.cr2;
3816 value = vcpu->arch.cr3;
3819 value = kvm_read_cr4(vcpu);
3822 value = kvm_get_cr8(vcpu);
3825 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
3832 static int emulator_set_cr(int cr, unsigned long val, struct kvm_vcpu *vcpu)
3838 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
3841 vcpu->arch.cr2 = val;
3844 res = kvm_set_cr3(vcpu, val);
3847 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
3850 res = __kvm_set_cr8(vcpu, val & 0xfUL);
3853 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
3860 static int emulator_get_cpl(struct kvm_vcpu *vcpu)
3862 return kvm_x86_ops->get_cpl(vcpu);
3865 static void emulator_get_gdt(struct desc_ptr *dt, struct kvm_vcpu *vcpu)
3867 kvm_x86_ops->get_gdt(vcpu, dt);
3870 static void emulator_get_idt(struct desc_ptr *dt, struct kvm_vcpu *vcpu)
3872 kvm_x86_ops->get_idt(vcpu, dt);
3875 static unsigned long emulator_get_cached_segment_base(int seg,
3876 struct kvm_vcpu *vcpu)
3878 return get_segment_base(vcpu, seg);
3881 static bool emulator_get_cached_descriptor(struct desc_struct *desc, int seg,
3882 struct kvm_vcpu *vcpu)
3884 struct kvm_segment var;
3886 kvm_get_segment(vcpu, &var, seg);
3893 set_desc_limit(desc, var.limit);
3894 set_desc_base(desc, (unsigned long)var.base);
3895 desc->type = var.type;
3897 desc->dpl = var.dpl;
3898 desc->p = var.present;
3899 desc->avl = var.avl;
3907 static void emulator_set_cached_descriptor(struct desc_struct *desc, int seg,
3908 struct kvm_vcpu *vcpu)
3910 struct kvm_segment var;
3912 /* needed to preserve selector */
3913 kvm_get_segment(vcpu, &var, seg);
3915 var.base = get_desc_base(desc);
3916 var.limit = get_desc_limit(desc);
3918 var.limit = (var.limit << 12) | 0xfff;
3919 var.type = desc->type;
3920 var.present = desc->p;
3921 var.dpl = desc->dpl;
3926 var.avl = desc->avl;
3927 var.present = desc->p;
3928 var.unusable = !var.present;
3931 kvm_set_segment(vcpu, &var, seg);
3935 static u16 emulator_get_segment_selector(int seg, struct kvm_vcpu *vcpu)
3937 struct kvm_segment kvm_seg;
3939 kvm_get_segment(vcpu, &kvm_seg, seg);
3940 return kvm_seg.selector;
3943 static void emulator_set_segment_selector(u16 sel, int seg,
3944 struct kvm_vcpu *vcpu)
3946 struct kvm_segment kvm_seg;
3948 kvm_get_segment(vcpu, &kvm_seg, seg);
3949 kvm_seg.selector = sel;
3950 kvm_set_segment(vcpu, &kvm_seg, seg);
3953 static struct x86_emulate_ops emulate_ops = {
3954 .read_std = kvm_read_guest_virt_system,
3955 .write_std = kvm_write_guest_virt_system,
3956 .fetch = kvm_fetch_guest_virt,
3957 .read_emulated = emulator_read_emulated,
3958 .write_emulated = emulator_write_emulated,
3959 .cmpxchg_emulated = emulator_cmpxchg_emulated,
3960 .pio_in_emulated = emulator_pio_in_emulated,
3961 .pio_out_emulated = emulator_pio_out_emulated,
3962 .get_cached_descriptor = emulator_get_cached_descriptor,
3963 .set_cached_descriptor = emulator_set_cached_descriptor,
3964 .get_segment_selector = emulator_get_segment_selector,
3965 .set_segment_selector = emulator_set_segment_selector,
3966 .get_cached_segment_base = emulator_get_cached_segment_base,
3967 .get_gdt = emulator_get_gdt,
3968 .get_idt = emulator_get_idt,
3969 .get_cr = emulator_get_cr,
3970 .set_cr = emulator_set_cr,
3971 .cpl = emulator_get_cpl,
3972 .get_dr = emulator_get_dr,
3973 .set_dr = emulator_set_dr,
3974 .set_msr = kvm_set_msr,
3975 .get_msr = kvm_get_msr,
3978 static void cache_all_regs(struct kvm_vcpu *vcpu)
3980 kvm_register_read(vcpu, VCPU_REGS_RAX);
3981 kvm_register_read(vcpu, VCPU_REGS_RSP);
3982 kvm_register_read(vcpu, VCPU_REGS_RIP);
3983 vcpu->arch.regs_dirty = ~0;
3986 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
3988 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu, mask);
3990 * an sti; sti; sequence only disable interrupts for the first
3991 * instruction. So, if the last instruction, be it emulated or
3992 * not, left the system with the INT_STI flag enabled, it
3993 * means that the last instruction is an sti. We should not
3994 * leave the flag on in this case. The same goes for mov ss
3996 if (!(int_shadow & mask))
3997 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
4000 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
4002 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4003 if (ctxt->exception == PF_VECTOR)
4004 kvm_inject_page_fault(vcpu, ctxt->cr2, ctxt->error_code);
4005 else if (ctxt->error_code_valid)
4006 kvm_queue_exception_e(vcpu, ctxt->exception, ctxt->error_code);
4008 kvm_queue_exception(vcpu, ctxt->exception);
4011 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
4013 struct decode_cache *c = &vcpu->arch.emulate_ctxt.decode;
4016 cache_all_regs(vcpu);
4018 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4020 vcpu->arch.emulate_ctxt.vcpu = vcpu;
4021 vcpu->arch.emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
4022 vcpu->arch.emulate_ctxt.eip = kvm_rip_read(vcpu);
4023 vcpu->arch.emulate_ctxt.mode =
4024 (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
4025 (vcpu->arch.emulate_ctxt.eflags & X86_EFLAGS_VM)
4026 ? X86EMUL_MODE_VM86 : cs_l
4027 ? X86EMUL_MODE_PROT64 : cs_db
4028 ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
4029 memset(c, 0, sizeof(struct decode_cache));
4030 memcpy(c->regs, vcpu->arch.regs, sizeof c->regs);
4033 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
4035 ++vcpu->stat.insn_emulation_fail;
4036 trace_kvm_emulate_insn_failed(vcpu);
4037 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4038 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
4039 vcpu->run->internal.ndata = 0;
4040 kvm_queue_exception(vcpu, UD_VECTOR);
4041 return EMULATE_FAIL;
4044 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t gva)
4052 * if emulation was due to access to shadowed page table
4053 * and it failed try to unshadow page and re-entetr the
4054 * guest to let CPU execute the instruction.
4056 if (kvm_mmu_unprotect_page_virt(vcpu, gva))
4059 gpa = kvm_mmu_gva_to_gpa_system(vcpu, gva, NULL);
4061 if (gpa == UNMAPPED_GVA)
4062 return true; /* let cpu generate fault */
4064 if (!kvm_is_error_hva(gfn_to_hva(vcpu->kvm, gpa >> PAGE_SHIFT)))
4070 int emulate_instruction(struct kvm_vcpu *vcpu,
4076 struct decode_cache *c = &vcpu->arch.emulate_ctxt.decode;
4078 kvm_clear_exception_queue(vcpu);
4079 vcpu->arch.mmio_fault_cr2 = cr2;
4081 * TODO: fix emulate.c to use guest_read/write_register
4082 * instead of direct ->regs accesses, can save hundred cycles
4083 * on Intel for instructions that don't read/change RSP, for
4086 cache_all_regs(vcpu);
4088 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
4089 init_emulate_ctxt(vcpu);
4090 vcpu->arch.emulate_ctxt.interruptibility = 0;
4091 vcpu->arch.emulate_ctxt.exception = -1;
4092 vcpu->arch.emulate_ctxt.perm_ok = false;
4094 r = x86_decode_insn(&vcpu->arch.emulate_ctxt);
4095 trace_kvm_emulate_insn_start(vcpu);
4097 /* Only allow emulation of specific instructions on #UD
4098 * (namely VMMCALL, sysenter, sysexit, syscall)*/
4099 if (emulation_type & EMULTYPE_TRAP_UD) {
4101 return EMULATE_FAIL;
4103 case 0x01: /* VMMCALL */
4104 if (c->modrm_mod != 3 || c->modrm_rm != 1)
4105 return EMULATE_FAIL;
4107 case 0x34: /* sysenter */
4108 case 0x35: /* sysexit */
4109 if (c->modrm_mod != 0 || c->modrm_rm != 0)
4110 return EMULATE_FAIL;
4112 case 0x05: /* syscall */
4113 if (c->modrm_mod != 0 || c->modrm_rm != 0)
4114 return EMULATE_FAIL;
4117 return EMULATE_FAIL;
4120 if (!(c->modrm_reg == 0 || c->modrm_reg == 3))
4121 return EMULATE_FAIL;
4124 ++vcpu->stat.insn_emulation;
4126 if (reexecute_instruction(vcpu, cr2))
4127 return EMULATE_DONE;
4128 if (emulation_type & EMULTYPE_SKIP)
4129 return EMULATE_FAIL;
4130 return handle_emulation_failure(vcpu);
4134 if (emulation_type & EMULTYPE_SKIP) {
4135 kvm_rip_write(vcpu, vcpu->arch.emulate_ctxt.decode.eip);
4136 return EMULATE_DONE;
4139 /* this is needed for vmware backdor interface to work since it
4140 changes registers values during IO operation */
4141 memcpy(c->regs, vcpu->arch.regs, sizeof c->regs);
4144 r = x86_emulate_insn(&vcpu->arch.emulate_ctxt);
4146 if (r) { /* emulation failed */
4147 if (reexecute_instruction(vcpu, cr2))
4148 return EMULATE_DONE;
4150 return handle_emulation_failure(vcpu);
4155 if (vcpu->arch.emulate_ctxt.exception >= 0)
4156 inject_emulated_exception(vcpu);
4157 else if (vcpu->arch.pio.count) {
4158 if (!vcpu->arch.pio.in)
4159 vcpu->arch.pio.count = 0;
4160 r = EMULATE_DO_MMIO;
4161 } else if (vcpu->mmio_needed) {
4162 if (vcpu->mmio_is_write)
4163 vcpu->mmio_needed = 0;
4164 r = EMULATE_DO_MMIO;
4165 } else if (vcpu->arch.emulate_ctxt.restart)
4168 toggle_interruptibility(vcpu, vcpu->arch.emulate_ctxt.interruptibility);
4169 kvm_x86_ops->set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
4170 memcpy(vcpu->arch.regs, c->regs, sizeof c->regs);
4171 kvm_rip_write(vcpu, vcpu->arch.emulate_ctxt.eip);
4175 EXPORT_SYMBOL_GPL(emulate_instruction);
4177 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
4179 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
4180 int ret = emulator_pio_out_emulated(size, port, &val, 1, vcpu);
4181 /* do not return to emulator after return from userspace */
4182 vcpu->arch.pio.count = 0;
4185 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
4187 static void tsc_bad(void *info)
4189 __get_cpu_var(cpu_tsc_khz) = 0;
4192 static void tsc_khz_changed(void *data)
4194 struct cpufreq_freqs *freq = data;
4195 unsigned long khz = 0;
4199 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
4200 khz = cpufreq_quick_get(raw_smp_processor_id());
4203 __get_cpu_var(cpu_tsc_khz) = khz;
4206 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
4209 struct cpufreq_freqs *freq = data;
4211 struct kvm_vcpu *vcpu;
4212 int i, send_ipi = 0;
4215 * We allow guests to temporarily run on slowing clocks,
4216 * provided we notify them after, or to run on accelerating
4217 * clocks, provided we notify them before. Thus time never
4220 * However, we have a problem. We can't atomically update
4221 * the frequency of a given CPU from this function; it is
4222 * merely a notifier, which can be called from any CPU.
4223 * Changing the TSC frequency at arbitrary points in time
4224 * requires a recomputation of local variables related to
4225 * the TSC for each VCPU. We must flag these local variables
4226 * to be updated and be sure the update takes place with the
4227 * new frequency before any guests proceed.
4229 * Unfortunately, the combination of hotplug CPU and frequency
4230 * change creates an intractable locking scenario; the order
4231 * of when these callouts happen is undefined with respect to
4232 * CPU hotplug, and they can race with each other. As such,
4233 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
4234 * undefined; you can actually have a CPU frequency change take
4235 * place in between the computation of X and the setting of the
4236 * variable. To protect against this problem, all updates of
4237 * the per_cpu tsc_khz variable are done in an interrupt
4238 * protected IPI, and all callers wishing to update the value
4239 * must wait for a synchronous IPI to complete (which is trivial
4240 * if the caller is on the CPU already). This establishes the
4241 * necessary total order on variable updates.
4243 * Note that because a guest time update may take place
4244 * anytime after the setting of the VCPU's request bit, the
4245 * correct TSC value must be set before the request. However,
4246 * to ensure the update actually makes it to any guest which
4247 * starts running in hardware virtualization between the set
4248 * and the acquisition of the spinlock, we must also ping the
4249 * CPU after setting the request bit.
4253 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
4255 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
4258 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
4260 spin_lock(&kvm_lock);
4261 list_for_each_entry(kvm, &vm_list, vm_list) {
4262 kvm_for_each_vcpu(i, vcpu, kvm) {
4263 if (vcpu->cpu != freq->cpu)
4265 if (!kvm_request_guest_time_update(vcpu))
4267 if (vcpu->cpu != smp_processor_id())
4271 spin_unlock(&kvm_lock);
4273 if (freq->old < freq->new && send_ipi) {
4275 * We upscale the frequency. Must make the guest
4276 * doesn't see old kvmclock values while running with
4277 * the new frequency, otherwise we risk the guest sees
4278 * time go backwards.
4280 * In case we update the frequency for another cpu
4281 * (which might be in guest context) send an interrupt
4282 * to kick the cpu out of guest context. Next time
4283 * guest context is entered kvmclock will be updated,
4284 * so the guest will not see stale values.
4286 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
4291 static struct notifier_block kvmclock_cpufreq_notifier_block = {
4292 .notifier_call = kvmclock_cpufreq_notifier
4295 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
4296 unsigned long action, void *hcpu)
4298 unsigned int cpu = (unsigned long)hcpu;
4302 case CPU_DOWN_FAILED:
4303 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
4305 case CPU_DOWN_PREPARE:
4306 smp_call_function_single(cpu, tsc_bad, NULL, 1);
4312 static struct notifier_block kvmclock_cpu_notifier_block = {
4313 .notifier_call = kvmclock_cpu_notifier,
4314 .priority = -INT_MAX
4317 static void kvm_timer_init(void)
4321 register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
4322 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
4323 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
4324 CPUFREQ_TRANSITION_NOTIFIER);
4326 for_each_online_cpu(cpu)
4327 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
4330 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
4332 static int kvm_is_in_guest(void)
4334 return percpu_read(current_vcpu) != NULL;
4337 static int kvm_is_user_mode(void)
4341 if (percpu_read(current_vcpu))
4342 user_mode = kvm_x86_ops->get_cpl(percpu_read(current_vcpu));
4344 return user_mode != 0;
4347 static unsigned long kvm_get_guest_ip(void)
4349 unsigned long ip = 0;
4351 if (percpu_read(current_vcpu))
4352 ip = kvm_rip_read(percpu_read(current_vcpu));
4357 static struct perf_guest_info_callbacks kvm_guest_cbs = {
4358 .is_in_guest = kvm_is_in_guest,
4359 .is_user_mode = kvm_is_user_mode,
4360 .get_guest_ip = kvm_get_guest_ip,
4363 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
4365 percpu_write(current_vcpu, vcpu);
4367 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
4369 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
4371 percpu_write(current_vcpu, NULL);
4373 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
4375 int kvm_arch_init(void *opaque)
4378 struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
4381 printk(KERN_ERR "kvm: already loaded the other module\n");
4386 if (!ops->cpu_has_kvm_support()) {
4387 printk(KERN_ERR "kvm: no hardware support\n");
4391 if (ops->disabled_by_bios()) {
4392 printk(KERN_ERR "kvm: disabled by bios\n");
4397 r = kvm_mmu_module_init();
4401 kvm_init_msr_list();
4404 kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
4405 kvm_mmu_set_base_ptes(PT_PRESENT_MASK);
4406 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
4407 PT_DIRTY_MASK, PT64_NX_MASK, 0);
4411 perf_register_guest_info_callbacks(&kvm_guest_cbs);
4414 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
4422 void kvm_arch_exit(void)
4424 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
4426 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
4427 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
4428 CPUFREQ_TRANSITION_NOTIFIER);
4429 unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
4431 kvm_mmu_module_exit();
4434 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
4436 ++vcpu->stat.halt_exits;
4437 if (irqchip_in_kernel(vcpu->kvm)) {
4438 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
4441 vcpu->run->exit_reason = KVM_EXIT_HLT;
4445 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
4447 static inline gpa_t hc_gpa(struct kvm_vcpu *vcpu, unsigned long a0,
4450 if (is_long_mode(vcpu))
4453 return a0 | ((gpa_t)a1 << 32);
4456 int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
4458 u64 param, ingpa, outgpa, ret;
4459 uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
4460 bool fast, longmode;
4464 * hypercall generates UD from non zero cpl and real mode
4467 if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
4468 kvm_queue_exception(vcpu, UD_VECTOR);
4472 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4473 longmode = is_long_mode(vcpu) && cs_l == 1;
4476 param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
4477 (kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
4478 ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
4479 (kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
4480 outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
4481 (kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
4483 #ifdef CONFIG_X86_64
4485 param = kvm_register_read(vcpu, VCPU_REGS_RCX);
4486 ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
4487 outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
4491 code = param & 0xffff;
4492 fast = (param >> 16) & 0x1;
4493 rep_cnt = (param >> 32) & 0xfff;
4494 rep_idx = (param >> 48) & 0xfff;
4496 trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
4499 case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
4500 kvm_vcpu_on_spin(vcpu);
4503 res = HV_STATUS_INVALID_HYPERCALL_CODE;
4507 ret = res | (((u64)rep_done & 0xfff) << 32);
4509 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
4511 kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
4512 kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
4518 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
4520 unsigned long nr, a0, a1, a2, a3, ret;
4523 if (kvm_hv_hypercall_enabled(vcpu->kvm))
4524 return kvm_hv_hypercall(vcpu);
4526 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
4527 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
4528 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
4529 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
4530 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
4532 trace_kvm_hypercall(nr, a0, a1, a2, a3);
4534 if (!is_long_mode(vcpu)) {
4542 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
4548 case KVM_HC_VAPIC_POLL_IRQ:
4552 r = kvm_pv_mmu_op(vcpu, a0, hc_gpa(vcpu, a1, a2), &ret);
4559 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
4560 ++vcpu->stat.hypercalls;
4563 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
4565 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
4567 char instruction[3];
4568 unsigned long rip = kvm_rip_read(vcpu);
4571 * Blow out the MMU to ensure that no other VCPU has an active mapping
4572 * to ensure that the updated hypercall appears atomically across all
4575 kvm_mmu_zap_all(vcpu->kvm);
4577 kvm_x86_ops->patch_hypercall(vcpu, instruction);
4579 return emulator_write_emulated(rip, instruction, 3, NULL, vcpu);
4582 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
4584 struct desc_ptr dt = { limit, base };
4586 kvm_x86_ops->set_gdt(vcpu, &dt);
4589 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
4591 struct desc_ptr dt = { limit, base };
4593 kvm_x86_ops->set_idt(vcpu, &dt);
4596 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
4598 struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
4599 int j, nent = vcpu->arch.cpuid_nent;
4601 e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
4602 /* when no next entry is found, the current entry[i] is reselected */
4603 for (j = i + 1; ; j = (j + 1) % nent) {
4604 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
4605 if (ej->function == e->function) {
4606 ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
4610 return 0; /* silence gcc, even though control never reaches here */
4613 /* find an entry with matching function, matching index (if needed), and that
4614 * should be read next (if it's stateful) */
4615 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
4616 u32 function, u32 index)
4618 if (e->function != function)
4620 if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
4622 if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
4623 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
4628 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry(struct kvm_vcpu *vcpu,
4629 u32 function, u32 index)
4632 struct kvm_cpuid_entry2 *best = NULL;
4634 for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
4635 struct kvm_cpuid_entry2 *e;
4637 e = &vcpu->arch.cpuid_entries[i];
4638 if (is_matching_cpuid_entry(e, function, index)) {
4639 if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
4640 move_to_next_stateful_cpuid_entry(vcpu, i);
4645 * Both basic or both extended?
4647 if (((e->function ^ function) & 0x80000000) == 0)
4648 if (!best || e->function > best->function)
4653 EXPORT_SYMBOL_GPL(kvm_find_cpuid_entry);
4655 int cpuid_maxphyaddr(struct kvm_vcpu *vcpu)
4657 struct kvm_cpuid_entry2 *best;
4659 best = kvm_find_cpuid_entry(vcpu, 0x80000000, 0);
4660 if (!best || best->eax < 0x80000008)
4662 best = kvm_find_cpuid_entry(vcpu, 0x80000008, 0);
4664 return best->eax & 0xff;
4669 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
4671 u32 function, index;
4672 struct kvm_cpuid_entry2 *best;
4674 function = kvm_register_read(vcpu, VCPU_REGS_RAX);
4675 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
4676 kvm_register_write(vcpu, VCPU_REGS_RAX, 0);
4677 kvm_register_write(vcpu, VCPU_REGS_RBX, 0);
4678 kvm_register_write(vcpu, VCPU_REGS_RCX, 0);
4679 kvm_register_write(vcpu, VCPU_REGS_RDX, 0);
4680 best = kvm_find_cpuid_entry(vcpu, function, index);
4682 kvm_register_write(vcpu, VCPU_REGS_RAX, best->eax);
4683 kvm_register_write(vcpu, VCPU_REGS_RBX, best->ebx);
4684 kvm_register_write(vcpu, VCPU_REGS_RCX, best->ecx);
4685 kvm_register_write(vcpu, VCPU_REGS_RDX, best->edx);
4687 kvm_x86_ops->skip_emulated_instruction(vcpu);
4688 trace_kvm_cpuid(function,
4689 kvm_register_read(vcpu, VCPU_REGS_RAX),
4690 kvm_register_read(vcpu, VCPU_REGS_RBX),
4691 kvm_register_read(vcpu, VCPU_REGS_RCX),
4692 kvm_register_read(vcpu, VCPU_REGS_RDX));
4694 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
4697 * Check if userspace requested an interrupt window, and that the
4698 * interrupt window is open.
4700 * No need to exit to userspace if we already have an interrupt queued.
4702 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
4704 return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
4705 vcpu->run->request_interrupt_window &&
4706 kvm_arch_interrupt_allowed(vcpu));
4709 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
4711 struct kvm_run *kvm_run = vcpu->run;
4713 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
4714 kvm_run->cr8 = kvm_get_cr8(vcpu);
4715 kvm_run->apic_base = kvm_get_apic_base(vcpu);
4716 if (irqchip_in_kernel(vcpu->kvm))
4717 kvm_run->ready_for_interrupt_injection = 1;
4719 kvm_run->ready_for_interrupt_injection =
4720 kvm_arch_interrupt_allowed(vcpu) &&
4721 !kvm_cpu_has_interrupt(vcpu) &&
4722 !kvm_event_needs_reinjection(vcpu);
4725 static void vapic_enter(struct kvm_vcpu *vcpu)
4727 struct kvm_lapic *apic = vcpu->arch.apic;
4730 if (!apic || !apic->vapic_addr)
4733 page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
4735 vcpu->arch.apic->vapic_page = page;
4738 static void vapic_exit(struct kvm_vcpu *vcpu)
4740 struct kvm_lapic *apic = vcpu->arch.apic;
4743 if (!apic || !apic->vapic_addr)
4746 idx = srcu_read_lock(&vcpu->kvm->srcu);
4747 kvm_release_page_dirty(apic->vapic_page);
4748 mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
4749 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4752 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
4756 if (!kvm_x86_ops->update_cr8_intercept)
4759 if (!vcpu->arch.apic)
4762 if (!vcpu->arch.apic->vapic_addr)
4763 max_irr = kvm_lapic_find_highest_irr(vcpu);
4770 tpr = kvm_lapic_get_cr8(vcpu);
4772 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
4775 static void inject_pending_event(struct kvm_vcpu *vcpu)
4777 /* try to reinject previous events if any */
4778 if (vcpu->arch.exception.pending) {
4779 trace_kvm_inj_exception(vcpu->arch.exception.nr,
4780 vcpu->arch.exception.has_error_code,
4781 vcpu->arch.exception.error_code);
4782 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
4783 vcpu->arch.exception.has_error_code,
4784 vcpu->arch.exception.error_code,
4785 vcpu->arch.exception.reinject);
4789 if (vcpu->arch.nmi_injected) {
4790 kvm_x86_ops->set_nmi(vcpu);
4794 if (vcpu->arch.interrupt.pending) {
4795 kvm_x86_ops->set_irq(vcpu);
4799 /* try to inject new event if pending */
4800 if (vcpu->arch.nmi_pending) {
4801 if (kvm_x86_ops->nmi_allowed(vcpu)) {
4802 vcpu->arch.nmi_pending = false;
4803 vcpu->arch.nmi_injected = true;
4804 kvm_x86_ops->set_nmi(vcpu);
4806 } else if (kvm_cpu_has_interrupt(vcpu)) {
4807 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
4808 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
4810 kvm_x86_ops->set_irq(vcpu);
4815 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
4817 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
4818 !vcpu->guest_xcr0_loaded) {
4819 /* kvm_set_xcr() also depends on this */
4820 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
4821 vcpu->guest_xcr0_loaded = 1;
4825 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
4827 if (vcpu->guest_xcr0_loaded) {
4828 if (vcpu->arch.xcr0 != host_xcr0)
4829 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
4830 vcpu->guest_xcr0_loaded = 0;
4834 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
4837 bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
4838 vcpu->run->request_interrupt_window;
4840 if (vcpu->requests) {
4841 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
4842 kvm_mmu_unload(vcpu);
4843 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
4844 __kvm_migrate_timers(vcpu);
4845 if (kvm_check_request(KVM_REQ_KVMCLOCK_UPDATE, vcpu)) {
4846 r = kvm_write_guest_time(vcpu);
4850 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
4851 kvm_mmu_sync_roots(vcpu);
4852 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
4853 kvm_x86_ops->tlb_flush(vcpu);
4854 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
4855 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
4859 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
4860 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4864 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
4865 vcpu->fpu_active = 0;
4866 kvm_x86_ops->fpu_deactivate(vcpu);
4870 r = kvm_mmu_reload(vcpu);
4876 kvm_x86_ops->prepare_guest_switch(vcpu);
4877 if (vcpu->fpu_active)
4878 kvm_load_guest_fpu(vcpu);
4879 kvm_load_guest_xcr0(vcpu);
4881 atomic_set(&vcpu->guest_mode, 1);
4884 local_irq_disable();
4886 if (!atomic_read(&vcpu->guest_mode) || vcpu->requests
4887 || need_resched() || signal_pending(current)) {
4888 atomic_set(&vcpu->guest_mode, 0);
4896 inject_pending_event(vcpu);
4898 /* enable NMI/IRQ window open exits if needed */
4899 if (vcpu->arch.nmi_pending)
4900 kvm_x86_ops->enable_nmi_window(vcpu);
4901 else if (kvm_cpu_has_interrupt(vcpu) || req_int_win)
4902 kvm_x86_ops->enable_irq_window(vcpu);
4904 if (kvm_lapic_enabled(vcpu)) {
4905 update_cr8_intercept(vcpu);
4906 kvm_lapic_sync_to_vapic(vcpu);
4909 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
4913 if (unlikely(vcpu->arch.switch_db_regs)) {
4915 set_debugreg(vcpu->arch.eff_db[0], 0);
4916 set_debugreg(vcpu->arch.eff_db[1], 1);
4917 set_debugreg(vcpu->arch.eff_db[2], 2);
4918 set_debugreg(vcpu->arch.eff_db[3], 3);
4921 trace_kvm_entry(vcpu->vcpu_id);
4922 kvm_x86_ops->run(vcpu);
4925 * If the guest has used debug registers, at least dr7
4926 * will be disabled while returning to the host.
4927 * If we don't have active breakpoints in the host, we don't
4928 * care about the messed up debug address registers. But if
4929 * we have some of them active, restore the old state.
4931 if (hw_breakpoint_active())
4932 hw_breakpoint_restore();
4934 atomic_set(&vcpu->guest_mode, 0);
4941 * We must have an instruction between local_irq_enable() and
4942 * kvm_guest_exit(), so the timer interrupt isn't delayed by
4943 * the interrupt shadow. The stat.exits increment will do nicely.
4944 * But we need to prevent reordering, hence this barrier():
4952 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
4955 * Profile KVM exit RIPs:
4957 if (unlikely(prof_on == KVM_PROFILING)) {
4958 unsigned long rip = kvm_rip_read(vcpu);
4959 profile_hit(KVM_PROFILING, (void *)rip);
4963 kvm_lapic_sync_from_vapic(vcpu);
4965 r = kvm_x86_ops->handle_exit(vcpu);
4971 static int __vcpu_run(struct kvm_vcpu *vcpu)
4974 struct kvm *kvm = vcpu->kvm;
4976 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
4977 pr_debug("vcpu %d received sipi with vector # %x\n",
4978 vcpu->vcpu_id, vcpu->arch.sipi_vector);
4979 kvm_lapic_reset(vcpu);
4980 r = kvm_arch_vcpu_reset(vcpu);
4983 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
4986 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
4991 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE)
4992 r = vcpu_enter_guest(vcpu);
4994 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
4995 kvm_vcpu_block(vcpu);
4996 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
4997 if (kvm_check_request(KVM_REQ_UNHALT, vcpu))
4999 switch(vcpu->arch.mp_state) {
5000 case KVM_MP_STATE_HALTED:
5001 vcpu->arch.mp_state =
5002 KVM_MP_STATE_RUNNABLE;
5003 case KVM_MP_STATE_RUNNABLE:
5005 case KVM_MP_STATE_SIPI_RECEIVED:
5016 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
5017 if (kvm_cpu_has_pending_timer(vcpu))
5018 kvm_inject_pending_timer_irqs(vcpu);
5020 if (dm_request_for_irq_injection(vcpu)) {
5022 vcpu->run->exit_reason = KVM_EXIT_INTR;
5023 ++vcpu->stat.request_irq_exits;
5025 if (signal_pending(current)) {
5027 vcpu->run->exit_reason = KVM_EXIT_INTR;
5028 ++vcpu->stat.signal_exits;
5030 if (need_resched()) {
5031 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5033 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
5037 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5044 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
5049 if (vcpu->sigset_active)
5050 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
5052 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
5053 kvm_vcpu_block(vcpu);
5054 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
5059 /* re-sync apic's tpr */
5060 if (!irqchip_in_kernel(vcpu->kvm))
5061 kvm_set_cr8(vcpu, kvm_run->cr8);
5063 if (vcpu->arch.pio.count || vcpu->mmio_needed ||
5064 vcpu->arch.emulate_ctxt.restart) {
5065 if (vcpu->mmio_needed) {
5066 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
5067 vcpu->mmio_read_completed = 1;
5068 vcpu->mmio_needed = 0;
5070 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
5071 r = emulate_instruction(vcpu, 0, 0, EMULTYPE_NO_DECODE);
5072 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
5073 if (r != EMULATE_DONE) {
5078 if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL)
5079 kvm_register_write(vcpu, VCPU_REGS_RAX,
5080 kvm_run->hypercall.ret);
5082 r = __vcpu_run(vcpu);
5085 post_kvm_run_save(vcpu);
5086 if (vcpu->sigset_active)
5087 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
5092 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
5094 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
5095 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
5096 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
5097 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
5098 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
5099 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
5100 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
5101 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
5102 #ifdef CONFIG_X86_64
5103 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
5104 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
5105 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
5106 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
5107 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
5108 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
5109 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
5110 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
5113 regs->rip = kvm_rip_read(vcpu);
5114 regs->rflags = kvm_get_rflags(vcpu);
5119 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
5121 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
5122 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
5123 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
5124 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
5125 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
5126 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
5127 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
5128 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
5129 #ifdef CONFIG_X86_64
5130 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
5131 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
5132 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
5133 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
5134 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
5135 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
5136 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
5137 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
5140 kvm_rip_write(vcpu, regs->rip);
5141 kvm_set_rflags(vcpu, regs->rflags);
5143 vcpu->arch.exception.pending = false;
5148 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
5150 struct kvm_segment cs;
5152 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
5156 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
5158 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
5159 struct kvm_sregs *sregs)
5163 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
5164 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
5165 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
5166 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
5167 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
5168 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
5170 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
5171 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
5173 kvm_x86_ops->get_idt(vcpu, &dt);
5174 sregs->idt.limit = dt.size;
5175 sregs->idt.base = dt.address;
5176 kvm_x86_ops->get_gdt(vcpu, &dt);
5177 sregs->gdt.limit = dt.size;
5178 sregs->gdt.base = dt.address;
5180 sregs->cr0 = kvm_read_cr0(vcpu);
5181 sregs->cr2 = vcpu->arch.cr2;
5182 sregs->cr3 = vcpu->arch.cr3;
5183 sregs->cr4 = kvm_read_cr4(vcpu);
5184 sregs->cr8 = kvm_get_cr8(vcpu);
5185 sregs->efer = vcpu->arch.efer;
5186 sregs->apic_base = kvm_get_apic_base(vcpu);
5188 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
5190 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
5191 set_bit(vcpu->arch.interrupt.nr,
5192 (unsigned long *)sregs->interrupt_bitmap);
5197 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
5198 struct kvm_mp_state *mp_state)
5200 mp_state->mp_state = vcpu->arch.mp_state;
5204 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
5205 struct kvm_mp_state *mp_state)
5207 vcpu->arch.mp_state = mp_state->mp_state;
5211 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason,
5212 bool has_error_code, u32 error_code)
5214 struct decode_cache *c = &vcpu->arch.emulate_ctxt.decode;
5217 init_emulate_ctxt(vcpu);
5219 ret = emulator_task_switch(&vcpu->arch.emulate_ctxt,
5220 tss_selector, reason, has_error_code,
5224 return EMULATE_FAIL;
5226 memcpy(vcpu->arch.regs, c->regs, sizeof c->regs);
5227 kvm_rip_write(vcpu, vcpu->arch.emulate_ctxt.eip);
5228 kvm_x86_ops->set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
5229 return EMULATE_DONE;
5231 EXPORT_SYMBOL_GPL(kvm_task_switch);
5233 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
5234 struct kvm_sregs *sregs)
5236 int mmu_reset_needed = 0;
5237 int pending_vec, max_bits;
5240 dt.size = sregs->idt.limit;
5241 dt.address = sregs->idt.base;
5242 kvm_x86_ops->set_idt(vcpu, &dt);
5243 dt.size = sregs->gdt.limit;
5244 dt.address = sregs->gdt.base;
5245 kvm_x86_ops->set_gdt(vcpu, &dt);
5247 vcpu->arch.cr2 = sregs->cr2;
5248 mmu_reset_needed |= vcpu->arch.cr3 != sregs->cr3;
5249 vcpu->arch.cr3 = sregs->cr3;
5251 kvm_set_cr8(vcpu, sregs->cr8);
5253 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
5254 kvm_x86_ops->set_efer(vcpu, sregs->efer);
5255 kvm_set_apic_base(vcpu, sregs->apic_base);
5257 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
5258 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
5259 vcpu->arch.cr0 = sregs->cr0;
5261 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
5262 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
5263 if (!is_long_mode(vcpu) && is_pae(vcpu)) {
5264 load_pdptrs(vcpu, vcpu->arch.cr3);
5265 mmu_reset_needed = 1;
5268 if (mmu_reset_needed)
5269 kvm_mmu_reset_context(vcpu);
5271 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
5272 pending_vec = find_first_bit(
5273 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
5274 if (pending_vec < max_bits) {
5275 kvm_queue_interrupt(vcpu, pending_vec, false);
5276 pr_debug("Set back pending irq %d\n", pending_vec);
5277 if (irqchip_in_kernel(vcpu->kvm))
5278 kvm_pic_clear_isr_ack(vcpu->kvm);
5281 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
5282 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
5283 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
5284 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
5285 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
5286 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
5288 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
5289 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
5291 update_cr8_intercept(vcpu);
5293 /* Older userspace won't unhalt the vcpu on reset. */
5294 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
5295 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
5297 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5302 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
5303 struct kvm_guest_debug *dbg)
5305 unsigned long rflags;
5308 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
5310 if (vcpu->arch.exception.pending)
5312 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
5313 kvm_queue_exception(vcpu, DB_VECTOR);
5315 kvm_queue_exception(vcpu, BP_VECTOR);
5319 * Read rflags as long as potentially injected trace flags are still
5322 rflags = kvm_get_rflags(vcpu);
5324 vcpu->guest_debug = dbg->control;
5325 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
5326 vcpu->guest_debug = 0;
5328 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5329 for (i = 0; i < KVM_NR_DB_REGS; ++i)
5330 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
5331 vcpu->arch.switch_db_regs =
5332 (dbg->arch.debugreg[7] & DR7_BP_EN_MASK);
5334 for (i = 0; i < KVM_NR_DB_REGS; i++)
5335 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
5336 vcpu->arch.switch_db_regs = (vcpu->arch.dr7 & DR7_BP_EN_MASK);
5339 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
5340 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
5341 get_segment_base(vcpu, VCPU_SREG_CS);
5344 * Trigger an rflags update that will inject or remove the trace
5347 kvm_set_rflags(vcpu, rflags);
5349 kvm_x86_ops->set_guest_debug(vcpu, dbg);
5359 * Translate a guest virtual address to a guest physical address.
5361 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
5362 struct kvm_translation *tr)
5364 unsigned long vaddr = tr->linear_address;
5368 idx = srcu_read_lock(&vcpu->kvm->srcu);
5369 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
5370 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5371 tr->physical_address = gpa;
5372 tr->valid = gpa != UNMAPPED_GVA;
5379 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
5381 struct i387_fxsave_struct *fxsave =
5382 &vcpu->arch.guest_fpu.state->fxsave;
5384 memcpy(fpu->fpr, fxsave->st_space, 128);
5385 fpu->fcw = fxsave->cwd;
5386 fpu->fsw = fxsave->swd;
5387 fpu->ftwx = fxsave->twd;
5388 fpu->last_opcode = fxsave->fop;
5389 fpu->last_ip = fxsave->rip;
5390 fpu->last_dp = fxsave->rdp;
5391 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
5396 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
5398 struct i387_fxsave_struct *fxsave =
5399 &vcpu->arch.guest_fpu.state->fxsave;
5401 memcpy(fxsave->st_space, fpu->fpr, 128);
5402 fxsave->cwd = fpu->fcw;
5403 fxsave->swd = fpu->fsw;
5404 fxsave->twd = fpu->ftwx;
5405 fxsave->fop = fpu->last_opcode;
5406 fxsave->rip = fpu->last_ip;
5407 fxsave->rdp = fpu->last_dp;
5408 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
5413 int fx_init(struct kvm_vcpu *vcpu)
5417 err = fpu_alloc(&vcpu->arch.guest_fpu);
5421 fpu_finit(&vcpu->arch.guest_fpu);
5424 * Ensure guest xcr0 is valid for loading
5426 vcpu->arch.xcr0 = XSTATE_FP;
5428 vcpu->arch.cr0 |= X86_CR0_ET;
5432 EXPORT_SYMBOL_GPL(fx_init);
5434 static void fx_free(struct kvm_vcpu *vcpu)
5436 fpu_free(&vcpu->arch.guest_fpu);
5439 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
5441 if (vcpu->guest_fpu_loaded)
5445 * Restore all possible states in the guest,
5446 * and assume host would use all available bits.
5447 * Guest xcr0 would be loaded later.
5449 kvm_put_guest_xcr0(vcpu);
5450 vcpu->guest_fpu_loaded = 1;
5451 unlazy_fpu(current);
5452 fpu_restore_checking(&vcpu->arch.guest_fpu);
5456 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
5458 kvm_put_guest_xcr0(vcpu);
5460 if (!vcpu->guest_fpu_loaded)
5463 vcpu->guest_fpu_loaded = 0;
5464 fpu_save_init(&vcpu->arch.guest_fpu);
5465 ++vcpu->stat.fpu_reload;
5466 kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
5470 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
5472 if (vcpu->arch.time_page) {
5473 kvm_release_page_dirty(vcpu->arch.time_page);
5474 vcpu->arch.time_page = NULL;
5477 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
5479 kvm_x86_ops->vcpu_free(vcpu);
5482 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
5485 if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
5486 printk_once(KERN_WARNING
5487 "kvm: SMP vm created on host with unstable TSC; "
5488 "guest TSC will not be reliable\n");
5489 return kvm_x86_ops->vcpu_create(kvm, id);
5492 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
5496 vcpu->arch.mtrr_state.have_fixed = 1;
5498 r = kvm_arch_vcpu_reset(vcpu);
5500 r = kvm_mmu_setup(vcpu);
5507 kvm_x86_ops->vcpu_free(vcpu);
5511 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
5514 kvm_mmu_unload(vcpu);
5518 kvm_x86_ops->vcpu_free(vcpu);
5521 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
5523 vcpu->arch.nmi_pending = false;
5524 vcpu->arch.nmi_injected = false;
5526 vcpu->arch.switch_db_regs = 0;
5527 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
5528 vcpu->arch.dr6 = DR6_FIXED_1;
5529 vcpu->arch.dr7 = DR7_FIXED_1;
5531 return kvm_x86_ops->vcpu_reset(vcpu);
5534 int kvm_arch_hardware_enable(void *garbage)
5537 struct kvm_vcpu *vcpu;
5540 kvm_shared_msr_cpu_online();
5541 list_for_each_entry(kvm, &vm_list, vm_list)
5542 kvm_for_each_vcpu(i, vcpu, kvm)
5543 if (vcpu->cpu == smp_processor_id())
5544 kvm_request_guest_time_update(vcpu);
5545 return kvm_x86_ops->hardware_enable(garbage);
5548 void kvm_arch_hardware_disable(void *garbage)
5550 kvm_x86_ops->hardware_disable(garbage);
5551 drop_user_return_notifiers(garbage);
5554 int kvm_arch_hardware_setup(void)
5556 return kvm_x86_ops->hardware_setup();
5559 void kvm_arch_hardware_unsetup(void)
5561 kvm_x86_ops->hardware_unsetup();
5564 void kvm_arch_check_processor_compat(void *rtn)
5566 kvm_x86_ops->check_processor_compatibility(rtn);
5569 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
5575 BUG_ON(vcpu->kvm == NULL);
5578 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
5579 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
5580 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
5581 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5583 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
5585 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
5590 vcpu->arch.pio_data = page_address(page);
5592 r = kvm_mmu_create(vcpu);
5594 goto fail_free_pio_data;
5596 if (irqchip_in_kernel(kvm)) {
5597 r = kvm_create_lapic(vcpu);
5599 goto fail_mmu_destroy;
5602 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
5604 if (!vcpu->arch.mce_banks) {
5606 goto fail_free_lapic;
5608 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
5610 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL))
5611 goto fail_free_mce_banks;
5614 fail_free_mce_banks:
5615 kfree(vcpu->arch.mce_banks);
5617 kvm_free_lapic(vcpu);
5619 kvm_mmu_destroy(vcpu);
5621 free_page((unsigned long)vcpu->arch.pio_data);
5626 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
5630 kfree(vcpu->arch.mce_banks);
5631 kvm_free_lapic(vcpu);
5632 idx = srcu_read_lock(&vcpu->kvm->srcu);
5633 kvm_mmu_destroy(vcpu);
5634 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5635 free_page((unsigned long)vcpu->arch.pio_data);
5638 struct kvm *kvm_arch_create_vm(void)
5640 struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
5643 return ERR_PTR(-ENOMEM);
5645 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
5646 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
5648 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
5649 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
5651 spin_lock_init(&kvm->arch.tsc_write_lock);
5656 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
5659 kvm_mmu_unload(vcpu);
5663 static void kvm_free_vcpus(struct kvm *kvm)
5666 struct kvm_vcpu *vcpu;
5669 * Unpin any mmu pages first.
5671 kvm_for_each_vcpu(i, vcpu, kvm)
5672 kvm_unload_vcpu_mmu(vcpu);
5673 kvm_for_each_vcpu(i, vcpu, kvm)
5674 kvm_arch_vcpu_free(vcpu);
5676 mutex_lock(&kvm->lock);
5677 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
5678 kvm->vcpus[i] = NULL;
5680 atomic_set(&kvm->online_vcpus, 0);
5681 mutex_unlock(&kvm->lock);
5684 void kvm_arch_sync_events(struct kvm *kvm)
5686 kvm_free_all_assigned_devices(kvm);
5690 void kvm_arch_destroy_vm(struct kvm *kvm)
5692 kvm_iommu_unmap_guest(kvm);
5693 kfree(kvm->arch.vpic);
5694 kfree(kvm->arch.vioapic);
5695 kvm_free_vcpus(kvm);
5696 kvm_free_physmem(kvm);
5697 if (kvm->arch.apic_access_page)
5698 put_page(kvm->arch.apic_access_page);
5699 if (kvm->arch.ept_identity_pagetable)
5700 put_page(kvm->arch.ept_identity_pagetable);
5701 cleanup_srcu_struct(&kvm->srcu);
5705 int kvm_arch_prepare_memory_region(struct kvm *kvm,
5706 struct kvm_memory_slot *memslot,
5707 struct kvm_memory_slot old,
5708 struct kvm_userspace_memory_region *mem,
5711 int npages = memslot->npages;
5712 int map_flags = MAP_PRIVATE | MAP_ANONYMOUS;
5714 /* Prevent internal slot pages from being moved by fork()/COW. */
5715 if (memslot->id >= KVM_MEMORY_SLOTS)
5716 map_flags = MAP_SHARED | MAP_ANONYMOUS;
5718 /*To keep backward compatibility with older userspace,
5719 *x86 needs to hanlde !user_alloc case.
5722 if (npages && !old.rmap) {
5723 unsigned long userspace_addr;
5725 down_write(¤t->mm->mmap_sem);
5726 userspace_addr = do_mmap(NULL, 0,
5728 PROT_READ | PROT_WRITE,
5731 up_write(¤t->mm->mmap_sem);
5733 if (IS_ERR((void *)userspace_addr))
5734 return PTR_ERR((void *)userspace_addr);
5736 memslot->userspace_addr = userspace_addr;
5744 void kvm_arch_commit_memory_region(struct kvm *kvm,
5745 struct kvm_userspace_memory_region *mem,
5746 struct kvm_memory_slot old,
5750 int npages = mem->memory_size >> PAGE_SHIFT;
5752 if (!user_alloc && !old.user_alloc && old.rmap && !npages) {
5755 down_write(¤t->mm->mmap_sem);
5756 ret = do_munmap(current->mm, old.userspace_addr,
5757 old.npages * PAGE_SIZE);
5758 up_write(¤t->mm->mmap_sem);
5761 "kvm_vm_ioctl_set_memory_region: "
5762 "failed to munmap memory\n");
5765 spin_lock(&kvm->mmu_lock);
5766 if (!kvm->arch.n_requested_mmu_pages) {
5767 unsigned int nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
5768 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
5771 kvm_mmu_slot_remove_write_access(kvm, mem->slot);
5772 spin_unlock(&kvm->mmu_lock);
5775 void kvm_arch_flush_shadow(struct kvm *kvm)
5777 kvm_mmu_zap_all(kvm);
5778 kvm_reload_remote_mmus(kvm);
5781 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
5783 return vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE
5784 || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
5785 || vcpu->arch.nmi_pending ||
5786 (kvm_arch_interrupt_allowed(vcpu) &&
5787 kvm_cpu_has_interrupt(vcpu));
5790 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
5793 int cpu = vcpu->cpu;
5795 if (waitqueue_active(&vcpu->wq)) {
5796 wake_up_interruptible(&vcpu->wq);
5797 ++vcpu->stat.halt_wakeup;
5801 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
5802 if (atomic_xchg(&vcpu->guest_mode, 0))
5803 smp_send_reschedule(cpu);
5807 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
5809 return kvm_x86_ops->interrupt_allowed(vcpu);
5812 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
5814 unsigned long current_rip = kvm_rip_read(vcpu) +
5815 get_segment_base(vcpu, VCPU_SREG_CS);
5817 return current_rip == linear_rip;
5819 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
5821 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
5823 unsigned long rflags;
5825 rflags = kvm_x86_ops->get_rflags(vcpu);
5826 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
5827 rflags &= ~X86_EFLAGS_TF;
5830 EXPORT_SYMBOL_GPL(kvm_get_rflags);
5832 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
5834 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
5835 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
5836 rflags |= X86_EFLAGS_TF;
5837 kvm_x86_ops->set_rflags(vcpu, rflags);
5839 EXPORT_SYMBOL_GPL(kvm_set_rflags);
5841 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
5842 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
5843 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
5844 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
5845 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
5846 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
5847 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
5848 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
5849 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
5850 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
5851 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
5852 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);