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 affiliates.
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"
31 #include <linux/clocksource.h>
32 #include <linux/interrupt.h>
33 #include <linux/kvm.h>
35 #include <linux/vmalloc.h>
36 #include <linux/module.h>
37 #include <linux/mman.h>
38 #include <linux/highmem.h>
39 #include <linux/iommu.h>
40 #include <linux/intel-iommu.h>
41 #include <linux/cpufreq.h>
42 #include <linux/user-return-notifier.h>
43 #include <linux/srcu.h>
44 #include <linux/slab.h>
45 #include <linux/perf_event.h>
46 #include <linux/uaccess.h>
47 #include <linux/hash.h>
48 #include <linux/pci.h>
49 #include <trace/events/kvm.h>
51 #define CREATE_TRACE_POINTS
54 #include <asm/debugreg.h>
60 #include <asm/fpu-internal.h> /* Ugh! */
62 #include <asm/pvclock.h>
63 #include <asm/div64.h>
65 #define MAX_IO_MSRS 256
66 #define KVM_MAX_MCE_BANKS 32
67 #define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
69 #define emul_to_vcpu(ctxt) \
70 container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
73 * - enable syscall per default because its emulated by KVM
74 * - enable LME and LMA per default on 64 bit KVM
78 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
80 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
83 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
84 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
86 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
87 static void process_nmi(struct kvm_vcpu *vcpu);
89 struct kvm_x86_ops *kvm_x86_ops;
90 EXPORT_SYMBOL_GPL(kvm_x86_ops);
92 static bool ignore_msrs = 0;
93 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
95 bool kvm_has_tsc_control;
96 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
97 u32 kvm_max_guest_tsc_khz;
98 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
100 #define KVM_NR_SHARED_MSRS 16
102 struct kvm_shared_msrs_global {
104 u32 msrs[KVM_NR_SHARED_MSRS];
107 struct kvm_shared_msrs {
108 struct user_return_notifier urn;
110 struct kvm_shared_msr_values {
113 } values[KVM_NR_SHARED_MSRS];
116 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
117 static DEFINE_PER_CPU(struct kvm_shared_msrs, shared_msrs);
119 struct kvm_stats_debugfs_item debugfs_entries[] = {
120 { "pf_fixed", VCPU_STAT(pf_fixed) },
121 { "pf_guest", VCPU_STAT(pf_guest) },
122 { "tlb_flush", VCPU_STAT(tlb_flush) },
123 { "invlpg", VCPU_STAT(invlpg) },
124 { "exits", VCPU_STAT(exits) },
125 { "io_exits", VCPU_STAT(io_exits) },
126 { "mmio_exits", VCPU_STAT(mmio_exits) },
127 { "signal_exits", VCPU_STAT(signal_exits) },
128 { "irq_window", VCPU_STAT(irq_window_exits) },
129 { "nmi_window", VCPU_STAT(nmi_window_exits) },
130 { "halt_exits", VCPU_STAT(halt_exits) },
131 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
132 { "hypercalls", VCPU_STAT(hypercalls) },
133 { "request_irq", VCPU_STAT(request_irq_exits) },
134 { "irq_exits", VCPU_STAT(irq_exits) },
135 { "host_state_reload", VCPU_STAT(host_state_reload) },
136 { "efer_reload", VCPU_STAT(efer_reload) },
137 { "fpu_reload", VCPU_STAT(fpu_reload) },
138 { "insn_emulation", VCPU_STAT(insn_emulation) },
139 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
140 { "irq_injections", VCPU_STAT(irq_injections) },
141 { "nmi_injections", VCPU_STAT(nmi_injections) },
142 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
143 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
144 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
145 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
146 { "mmu_flooded", VM_STAT(mmu_flooded) },
147 { "mmu_recycled", VM_STAT(mmu_recycled) },
148 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
149 { "mmu_unsync", VM_STAT(mmu_unsync) },
150 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
151 { "largepages", VM_STAT(lpages) },
155 u64 __read_mostly host_xcr0;
157 int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
159 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
162 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
163 vcpu->arch.apf.gfns[i] = ~0;
166 static void kvm_on_user_return(struct user_return_notifier *urn)
169 struct kvm_shared_msrs *locals
170 = container_of(urn, struct kvm_shared_msrs, urn);
171 struct kvm_shared_msr_values *values;
173 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
174 values = &locals->values[slot];
175 if (values->host != values->curr) {
176 wrmsrl(shared_msrs_global.msrs[slot], values->host);
177 values->curr = values->host;
180 locals->registered = false;
181 user_return_notifier_unregister(urn);
184 static void shared_msr_update(unsigned slot, u32 msr)
186 struct kvm_shared_msrs *smsr;
189 smsr = &__get_cpu_var(shared_msrs);
190 /* only read, and nobody should modify it at this time,
191 * so don't need lock */
192 if (slot >= shared_msrs_global.nr) {
193 printk(KERN_ERR "kvm: invalid MSR slot!");
196 rdmsrl_safe(msr, &value);
197 smsr->values[slot].host = value;
198 smsr->values[slot].curr = value;
201 void kvm_define_shared_msr(unsigned slot, u32 msr)
203 if (slot >= shared_msrs_global.nr)
204 shared_msrs_global.nr = slot + 1;
205 shared_msrs_global.msrs[slot] = msr;
206 /* we need ensured the shared_msr_global have been updated */
209 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
211 static void kvm_shared_msr_cpu_online(void)
215 for (i = 0; i < shared_msrs_global.nr; ++i)
216 shared_msr_update(i, shared_msrs_global.msrs[i]);
219 void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
221 struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
223 if (((value ^ smsr->values[slot].curr) & mask) == 0)
225 smsr->values[slot].curr = value;
226 wrmsrl(shared_msrs_global.msrs[slot], value);
227 if (!smsr->registered) {
228 smsr->urn.on_user_return = kvm_on_user_return;
229 user_return_notifier_register(&smsr->urn);
230 smsr->registered = true;
233 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
235 static void drop_user_return_notifiers(void *ignore)
237 struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
239 if (smsr->registered)
240 kvm_on_user_return(&smsr->urn);
243 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
245 if (irqchip_in_kernel(vcpu->kvm))
246 return vcpu->arch.apic_base;
248 return vcpu->arch.apic_base;
250 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
252 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
254 /* TODO: reserve bits check */
255 if (irqchip_in_kernel(vcpu->kvm))
256 kvm_lapic_set_base(vcpu, data);
258 vcpu->arch.apic_base = data;
260 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
262 #define EXCPT_BENIGN 0
263 #define EXCPT_CONTRIBUTORY 1
266 static int exception_class(int vector)
276 return EXCPT_CONTRIBUTORY;
283 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
284 unsigned nr, bool has_error, u32 error_code,
290 kvm_make_request(KVM_REQ_EVENT, vcpu);
292 if (!vcpu->arch.exception.pending) {
294 vcpu->arch.exception.pending = true;
295 vcpu->arch.exception.has_error_code = has_error;
296 vcpu->arch.exception.nr = nr;
297 vcpu->arch.exception.error_code = error_code;
298 vcpu->arch.exception.reinject = reinject;
302 /* to check exception */
303 prev_nr = vcpu->arch.exception.nr;
304 if (prev_nr == DF_VECTOR) {
305 /* triple fault -> shutdown */
306 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
309 class1 = exception_class(prev_nr);
310 class2 = exception_class(nr);
311 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
312 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
313 /* generate double fault per SDM Table 5-5 */
314 vcpu->arch.exception.pending = true;
315 vcpu->arch.exception.has_error_code = true;
316 vcpu->arch.exception.nr = DF_VECTOR;
317 vcpu->arch.exception.error_code = 0;
319 /* replace previous exception with a new one in a hope
320 that instruction re-execution will regenerate lost
325 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
327 kvm_multiple_exception(vcpu, nr, false, 0, false);
329 EXPORT_SYMBOL_GPL(kvm_queue_exception);
331 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
333 kvm_multiple_exception(vcpu, nr, false, 0, true);
335 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
337 void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
340 kvm_inject_gp(vcpu, 0);
342 kvm_x86_ops->skip_emulated_instruction(vcpu);
344 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
346 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
348 ++vcpu->stat.pf_guest;
349 vcpu->arch.cr2 = fault->address;
350 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
352 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
354 void kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
356 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
357 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
359 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
362 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
364 atomic_inc(&vcpu->arch.nmi_queued);
365 kvm_make_request(KVM_REQ_NMI, vcpu);
367 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
369 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
371 kvm_multiple_exception(vcpu, nr, true, error_code, false);
373 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
375 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
377 kvm_multiple_exception(vcpu, nr, true, error_code, true);
379 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
382 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
383 * a #GP and return false.
385 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
387 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
389 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
392 EXPORT_SYMBOL_GPL(kvm_require_cpl);
395 * This function will be used to read from the physical memory of the currently
396 * running guest. The difference to kvm_read_guest_page is that this function
397 * can read from guest physical or from the guest's guest physical memory.
399 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
400 gfn_t ngfn, void *data, int offset, int len,
406 ngpa = gfn_to_gpa(ngfn);
407 real_gfn = mmu->translate_gpa(vcpu, ngpa, access);
408 if (real_gfn == UNMAPPED_GVA)
411 real_gfn = gpa_to_gfn(real_gfn);
413 return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
415 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
417 int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
418 void *data, int offset, int len, u32 access)
420 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
421 data, offset, len, access);
425 * Load the pae pdptrs. Return true is they are all valid.
427 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
429 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
430 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
433 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
435 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
436 offset * sizeof(u64), sizeof(pdpte),
437 PFERR_USER_MASK|PFERR_WRITE_MASK);
442 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
443 if (is_present_gpte(pdpte[i]) &&
444 (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
451 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
452 __set_bit(VCPU_EXREG_PDPTR,
453 (unsigned long *)&vcpu->arch.regs_avail);
454 __set_bit(VCPU_EXREG_PDPTR,
455 (unsigned long *)&vcpu->arch.regs_dirty);
460 EXPORT_SYMBOL_GPL(load_pdptrs);
462 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
464 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
470 if (is_long_mode(vcpu) || !is_pae(vcpu))
473 if (!test_bit(VCPU_EXREG_PDPTR,
474 (unsigned long *)&vcpu->arch.regs_avail))
477 gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
478 offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
479 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
480 PFERR_USER_MASK | PFERR_WRITE_MASK);
483 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
489 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
491 unsigned long old_cr0 = kvm_read_cr0(vcpu);
492 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
493 X86_CR0_CD | X86_CR0_NW;
498 if (cr0 & 0xffffffff00000000UL)
502 cr0 &= ~CR0_RESERVED_BITS;
504 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
507 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
510 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
512 if ((vcpu->arch.efer & EFER_LME)) {
517 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
522 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
527 kvm_x86_ops->set_cr0(vcpu, cr0);
529 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
530 kvm_clear_async_pf_completion_queue(vcpu);
531 kvm_async_pf_hash_reset(vcpu);
534 if ((cr0 ^ old_cr0) & update_bits)
535 kvm_mmu_reset_context(vcpu);
538 EXPORT_SYMBOL_GPL(kvm_set_cr0);
540 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
542 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
544 EXPORT_SYMBOL_GPL(kvm_lmsw);
546 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
550 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
551 if (index != XCR_XFEATURE_ENABLED_MASK)
554 if (kvm_x86_ops->get_cpl(vcpu) != 0)
556 if (!(xcr0 & XSTATE_FP))
558 if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
560 if (xcr0 & ~host_xcr0)
562 vcpu->arch.xcr0 = xcr0;
563 vcpu->guest_xcr0_loaded = 0;
567 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
569 if (__kvm_set_xcr(vcpu, index, xcr)) {
570 kvm_inject_gp(vcpu, 0);
575 EXPORT_SYMBOL_GPL(kvm_set_xcr);
577 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
579 unsigned long old_cr4 = kvm_read_cr4(vcpu);
580 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
581 X86_CR4_PAE | X86_CR4_SMEP;
582 if (cr4 & CR4_RESERVED_BITS)
585 if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
588 if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
591 if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_RDWRGSFS))
594 if (is_long_mode(vcpu)) {
595 if (!(cr4 & X86_CR4_PAE))
597 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
598 && ((cr4 ^ old_cr4) & pdptr_bits)
599 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
603 if (kvm_x86_ops->set_cr4(vcpu, cr4))
606 if ((cr4 ^ old_cr4) & pdptr_bits)
607 kvm_mmu_reset_context(vcpu);
609 if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
610 kvm_update_cpuid(vcpu);
614 EXPORT_SYMBOL_GPL(kvm_set_cr4);
616 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
618 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
619 kvm_mmu_sync_roots(vcpu);
620 kvm_mmu_flush_tlb(vcpu);
624 if (is_long_mode(vcpu)) {
625 if (cr3 & CR3_L_MODE_RESERVED_BITS)
629 if (cr3 & CR3_PAE_RESERVED_BITS)
631 if (is_paging(vcpu) &&
632 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
636 * We don't check reserved bits in nonpae mode, because
637 * this isn't enforced, and VMware depends on this.
642 * Does the new cr3 value map to physical memory? (Note, we
643 * catch an invalid cr3 even in real-mode, because it would
644 * cause trouble later on when we turn on paging anyway.)
646 * A real CPU would silently accept an invalid cr3 and would
647 * attempt to use it - with largely undefined (and often hard
648 * to debug) behavior on the guest side.
650 if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
652 vcpu->arch.cr3 = cr3;
653 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
654 vcpu->arch.mmu.new_cr3(vcpu);
657 EXPORT_SYMBOL_GPL(kvm_set_cr3);
659 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
661 if (cr8 & CR8_RESERVED_BITS)
663 if (irqchip_in_kernel(vcpu->kvm))
664 kvm_lapic_set_tpr(vcpu, cr8);
666 vcpu->arch.cr8 = cr8;
669 EXPORT_SYMBOL_GPL(kvm_set_cr8);
671 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
673 if (irqchip_in_kernel(vcpu->kvm))
674 return kvm_lapic_get_cr8(vcpu);
676 return vcpu->arch.cr8;
678 EXPORT_SYMBOL_GPL(kvm_get_cr8);
680 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
684 vcpu->arch.db[dr] = val;
685 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
686 vcpu->arch.eff_db[dr] = val;
689 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
693 if (val & 0xffffffff00000000ULL)
695 vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
698 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
702 if (val & 0xffffffff00000000ULL)
704 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
705 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
706 kvm_x86_ops->set_dr7(vcpu, vcpu->arch.dr7);
707 vcpu->arch.switch_db_regs = (val & DR7_BP_EN_MASK);
715 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
719 res = __kvm_set_dr(vcpu, dr, val);
721 kvm_queue_exception(vcpu, UD_VECTOR);
723 kvm_inject_gp(vcpu, 0);
727 EXPORT_SYMBOL_GPL(kvm_set_dr);
729 static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
733 *val = vcpu->arch.db[dr];
736 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
740 *val = vcpu->arch.dr6;
743 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
747 *val = vcpu->arch.dr7;
754 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
756 if (_kvm_get_dr(vcpu, dr, val)) {
757 kvm_queue_exception(vcpu, UD_VECTOR);
762 EXPORT_SYMBOL_GPL(kvm_get_dr);
764 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
766 u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
770 err = kvm_pmu_read_pmc(vcpu, ecx, &data);
773 kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
774 kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
777 EXPORT_SYMBOL_GPL(kvm_rdpmc);
780 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
781 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
783 * This list is modified at module load time to reflect the
784 * capabilities of the host cpu. This capabilities test skips MSRs that are
785 * kvm-specific. Those are put in the beginning of the list.
788 #define KVM_SAVE_MSRS_BEGIN 9
789 static u32 msrs_to_save[] = {
790 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
791 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
792 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
793 HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
794 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
797 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
799 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA
802 static unsigned num_msrs_to_save;
804 static u32 emulated_msrs[] = {
805 MSR_IA32_TSCDEADLINE,
806 MSR_IA32_MISC_ENABLE,
811 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
813 u64 old_efer = vcpu->arch.efer;
815 if (efer & efer_reserved_bits)
819 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
822 if (efer & EFER_FFXSR) {
823 struct kvm_cpuid_entry2 *feat;
825 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
826 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
830 if (efer & EFER_SVME) {
831 struct kvm_cpuid_entry2 *feat;
833 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
834 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
839 efer |= vcpu->arch.efer & EFER_LMA;
841 kvm_x86_ops->set_efer(vcpu, efer);
843 vcpu->arch.mmu.base_role.nxe = (efer & EFER_NX) && !tdp_enabled;
845 /* Update reserved bits */
846 if ((efer ^ old_efer) & EFER_NX)
847 kvm_mmu_reset_context(vcpu);
852 void kvm_enable_efer_bits(u64 mask)
854 efer_reserved_bits &= ~mask;
856 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
860 * Writes msr value into into the appropriate "register".
861 * Returns 0 on success, non-0 otherwise.
862 * Assumes vcpu_load() was already called.
864 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
866 return kvm_x86_ops->set_msr(vcpu, msr_index, data);
870 * Adapt set_msr() to msr_io()'s calling convention
872 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
874 return kvm_set_msr(vcpu, index, *data);
877 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
881 struct pvclock_wall_clock wc;
882 struct timespec boot;
887 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
892 ++version; /* first time write, random junk */
896 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
899 * The guest calculates current wall clock time by adding
900 * system time (updated by kvm_guest_time_update below) to the
901 * wall clock specified here. guest system time equals host
902 * system time for us, thus we must fill in host boot time here.
906 wc.sec = boot.tv_sec;
907 wc.nsec = boot.tv_nsec;
908 wc.version = version;
910 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
913 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
916 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
918 uint32_t quotient, remainder;
920 /* Don't try to replace with do_div(), this one calculates
921 * "(dividend << 32) / divisor" */
923 : "=a" (quotient), "=d" (remainder)
924 : "0" (0), "1" (dividend), "r" (divisor) );
928 static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
929 s8 *pshift, u32 *pmultiplier)
936 tps64 = base_khz * 1000LL;
937 scaled64 = scaled_khz * 1000LL;
938 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
943 tps32 = (uint32_t)tps64;
944 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
945 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
953 *pmultiplier = div_frac(scaled64, tps32);
955 pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
956 __func__, base_khz, scaled_khz, shift, *pmultiplier);
959 static inline u64 get_kernel_ns(void)
963 WARN_ON(preemptible());
965 monotonic_to_bootbased(&ts);
966 return timespec_to_ns(&ts);
969 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
970 unsigned long max_tsc_khz;
972 static inline int kvm_tsc_changes_freq(void)
975 int ret = !boot_cpu_has(X86_FEATURE_CONSTANT_TSC) &&
976 cpufreq_quick_get(cpu) != 0;
981 u64 vcpu_tsc_khz(struct kvm_vcpu *vcpu)
983 if (vcpu->arch.virtual_tsc_khz)
984 return vcpu->arch.virtual_tsc_khz;
986 return __this_cpu_read(cpu_tsc_khz);
989 static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
993 WARN_ON(preemptible());
994 if (kvm_tsc_changes_freq())
995 printk_once(KERN_WARNING
996 "kvm: unreliable cycle conversion on adjustable rate TSC\n");
997 ret = nsec * vcpu_tsc_khz(vcpu);
998 do_div(ret, USEC_PER_SEC);
1002 static void kvm_init_tsc_catchup(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
1004 /* Compute a scale to convert nanoseconds in TSC cycles */
1005 kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
1006 &vcpu->arch.tsc_catchup_shift,
1007 &vcpu->arch.tsc_catchup_mult);
1010 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1012 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.last_tsc_nsec,
1013 vcpu->arch.tsc_catchup_mult,
1014 vcpu->arch.tsc_catchup_shift);
1015 tsc += vcpu->arch.last_tsc_write;
1019 void kvm_write_tsc(struct kvm_vcpu *vcpu, u64 data)
1021 struct kvm *kvm = vcpu->kvm;
1022 u64 offset, ns, elapsed;
1023 unsigned long flags;
1026 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1027 offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
1028 ns = get_kernel_ns();
1029 elapsed = ns - kvm->arch.last_tsc_nsec;
1030 sdiff = data - kvm->arch.last_tsc_write;
1035 * Special case: close write to TSC within 5 seconds of
1036 * another CPU is interpreted as an attempt to synchronize
1037 * The 5 seconds is to accommodate host load / swapping as
1038 * well as any reset of TSC during the boot process.
1040 * In that case, for a reliable TSC, we can match TSC offsets,
1041 * or make a best guest using elapsed value.
1043 if (sdiff < nsec_to_cycles(vcpu, 5ULL * NSEC_PER_SEC) &&
1044 elapsed < 5ULL * NSEC_PER_SEC) {
1045 if (!check_tsc_unstable()) {
1046 offset = kvm->arch.last_tsc_offset;
1047 pr_debug("kvm: matched tsc offset for %llu\n", data);
1049 u64 delta = nsec_to_cycles(vcpu, elapsed);
1051 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1053 ns = kvm->arch.last_tsc_nsec;
1055 kvm->arch.last_tsc_nsec = ns;
1056 kvm->arch.last_tsc_write = data;
1057 kvm->arch.last_tsc_offset = offset;
1058 kvm_x86_ops->write_tsc_offset(vcpu, offset);
1059 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1061 /* Reset of TSC must disable overshoot protection below */
1062 vcpu->arch.hv_clock.tsc_timestamp = 0;
1063 vcpu->arch.last_tsc_write = data;
1064 vcpu->arch.last_tsc_nsec = ns;
1066 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1068 static int kvm_guest_time_update(struct kvm_vcpu *v)
1070 unsigned long flags;
1071 struct kvm_vcpu_arch *vcpu = &v->arch;
1073 unsigned long this_tsc_khz;
1074 s64 kernel_ns, max_kernel_ns;
1077 /* Keep irq disabled to prevent changes to the clock */
1078 local_irq_save(flags);
1079 tsc_timestamp = kvm_x86_ops->read_l1_tsc(v);
1080 kernel_ns = get_kernel_ns();
1081 this_tsc_khz = vcpu_tsc_khz(v);
1082 if (unlikely(this_tsc_khz == 0)) {
1083 local_irq_restore(flags);
1084 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1089 * We may have to catch up the TSC to match elapsed wall clock
1090 * time for two reasons, even if kvmclock is used.
1091 * 1) CPU could have been running below the maximum TSC rate
1092 * 2) Broken TSC compensation resets the base at each VCPU
1093 * entry to avoid unknown leaps of TSC even when running
1094 * again on the same CPU. This may cause apparent elapsed
1095 * time to disappear, and the guest to stand still or run
1098 if (vcpu->tsc_catchup) {
1099 u64 tsc = compute_guest_tsc(v, kernel_ns);
1100 if (tsc > tsc_timestamp) {
1101 kvm_x86_ops->adjust_tsc_offset(v, tsc - tsc_timestamp);
1102 tsc_timestamp = tsc;
1106 local_irq_restore(flags);
1108 if (!vcpu->time_page)
1112 * Time as measured by the TSC may go backwards when resetting the base
1113 * tsc_timestamp. The reason for this is that the TSC resolution is
1114 * higher than the resolution of the other clock scales. Thus, many
1115 * possible measurments of the TSC correspond to one measurement of any
1116 * other clock, and so a spread of values is possible. This is not a
1117 * problem for the computation of the nanosecond clock; with TSC rates
1118 * around 1GHZ, there can only be a few cycles which correspond to one
1119 * nanosecond value, and any path through this code will inevitably
1120 * take longer than that. However, with the kernel_ns value itself,
1121 * the precision may be much lower, down to HZ granularity. If the
1122 * first sampling of TSC against kernel_ns ends in the low part of the
1123 * range, and the second in the high end of the range, we can get:
1125 * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new
1127 * As the sampling errors potentially range in the thousands of cycles,
1128 * it is possible such a time value has already been observed by the
1129 * guest. To protect against this, we must compute the system time as
1130 * observed by the guest and ensure the new system time is greater.
1133 if (vcpu->hv_clock.tsc_timestamp && vcpu->last_guest_tsc) {
1134 max_kernel_ns = vcpu->last_guest_tsc -
1135 vcpu->hv_clock.tsc_timestamp;
1136 max_kernel_ns = pvclock_scale_delta(max_kernel_ns,
1137 vcpu->hv_clock.tsc_to_system_mul,
1138 vcpu->hv_clock.tsc_shift);
1139 max_kernel_ns += vcpu->last_kernel_ns;
1142 if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
1143 kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
1144 &vcpu->hv_clock.tsc_shift,
1145 &vcpu->hv_clock.tsc_to_system_mul);
1146 vcpu->hw_tsc_khz = this_tsc_khz;
1149 if (max_kernel_ns > kernel_ns)
1150 kernel_ns = max_kernel_ns;
1152 /* With all the info we got, fill in the values */
1153 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1154 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1155 vcpu->last_kernel_ns = kernel_ns;
1156 vcpu->last_guest_tsc = tsc_timestamp;
1157 vcpu->hv_clock.flags = 0;
1160 * The interface expects us to write an even number signaling that the
1161 * update is finished. Since the guest won't see the intermediate
1162 * state, we just increase by 2 at the end.
1164 vcpu->hv_clock.version += 2;
1166 shared_kaddr = kmap_atomic(vcpu->time_page, KM_USER0);
1168 memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
1169 sizeof(vcpu->hv_clock));
1171 kunmap_atomic(shared_kaddr, KM_USER0);
1173 mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
1177 static bool msr_mtrr_valid(unsigned msr)
1180 case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
1181 case MSR_MTRRfix64K_00000:
1182 case MSR_MTRRfix16K_80000:
1183 case MSR_MTRRfix16K_A0000:
1184 case MSR_MTRRfix4K_C0000:
1185 case MSR_MTRRfix4K_C8000:
1186 case MSR_MTRRfix4K_D0000:
1187 case MSR_MTRRfix4K_D8000:
1188 case MSR_MTRRfix4K_E0000:
1189 case MSR_MTRRfix4K_E8000:
1190 case MSR_MTRRfix4K_F0000:
1191 case MSR_MTRRfix4K_F8000:
1192 case MSR_MTRRdefType:
1193 case MSR_IA32_CR_PAT:
1201 static bool valid_pat_type(unsigned t)
1203 return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
1206 static bool valid_mtrr_type(unsigned t)
1208 return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
1211 static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1215 if (!msr_mtrr_valid(msr))
1218 if (msr == MSR_IA32_CR_PAT) {
1219 for (i = 0; i < 8; i++)
1220 if (!valid_pat_type((data >> (i * 8)) & 0xff))
1223 } else if (msr == MSR_MTRRdefType) {
1226 return valid_mtrr_type(data & 0xff);
1227 } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
1228 for (i = 0; i < 8 ; i++)
1229 if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
1234 /* variable MTRRs */
1235 return valid_mtrr_type(data & 0xff);
1238 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1240 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1242 if (!mtrr_valid(vcpu, msr, data))
1245 if (msr == MSR_MTRRdefType) {
1246 vcpu->arch.mtrr_state.def_type = data;
1247 vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
1248 } else if (msr == MSR_MTRRfix64K_00000)
1250 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1251 p[1 + msr - MSR_MTRRfix16K_80000] = data;
1252 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1253 p[3 + msr - MSR_MTRRfix4K_C0000] = data;
1254 else if (msr == MSR_IA32_CR_PAT)
1255 vcpu->arch.pat = data;
1256 else { /* Variable MTRRs */
1257 int idx, is_mtrr_mask;
1260 idx = (msr - 0x200) / 2;
1261 is_mtrr_mask = msr - 0x200 - 2 * idx;
1264 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1267 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1271 kvm_mmu_reset_context(vcpu);
1275 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1277 u64 mcg_cap = vcpu->arch.mcg_cap;
1278 unsigned bank_num = mcg_cap & 0xff;
1281 case MSR_IA32_MCG_STATUS:
1282 vcpu->arch.mcg_status = data;
1284 case MSR_IA32_MCG_CTL:
1285 if (!(mcg_cap & MCG_CTL_P))
1287 if (data != 0 && data != ~(u64)0)
1289 vcpu->arch.mcg_ctl = data;
1292 if (msr >= MSR_IA32_MC0_CTL &&
1293 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1294 u32 offset = msr - MSR_IA32_MC0_CTL;
1295 /* only 0 or all 1s can be written to IA32_MCi_CTL
1296 * some Linux kernels though clear bit 10 in bank 4 to
1297 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
1298 * this to avoid an uncatched #GP in the guest
1300 if ((offset & 0x3) == 0 &&
1301 data != 0 && (data | (1 << 10)) != ~(u64)0)
1303 vcpu->arch.mce_banks[offset] = data;
1311 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
1313 struct kvm *kvm = vcpu->kvm;
1314 int lm = is_long_mode(vcpu);
1315 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
1316 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
1317 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
1318 : kvm->arch.xen_hvm_config.blob_size_32;
1319 u32 page_num = data & ~PAGE_MASK;
1320 u64 page_addr = data & PAGE_MASK;
1325 if (page_num >= blob_size)
1328 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
1333 if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
1342 static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
1344 return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
1347 static bool kvm_hv_msr_partition_wide(u32 msr)
1351 case HV_X64_MSR_GUEST_OS_ID:
1352 case HV_X64_MSR_HYPERCALL:
1360 static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1362 struct kvm *kvm = vcpu->kvm;
1365 case HV_X64_MSR_GUEST_OS_ID:
1366 kvm->arch.hv_guest_os_id = data;
1367 /* setting guest os id to zero disables hypercall page */
1368 if (!kvm->arch.hv_guest_os_id)
1369 kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
1371 case HV_X64_MSR_HYPERCALL: {
1376 /* if guest os id is not set hypercall should remain disabled */
1377 if (!kvm->arch.hv_guest_os_id)
1379 if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
1380 kvm->arch.hv_hypercall = data;
1383 gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
1384 addr = gfn_to_hva(kvm, gfn);
1385 if (kvm_is_error_hva(addr))
1387 kvm_x86_ops->patch_hypercall(vcpu, instructions);
1388 ((unsigned char *)instructions)[3] = 0xc3; /* ret */
1389 if (__copy_to_user((void __user *)addr, instructions, 4))
1391 kvm->arch.hv_hypercall = data;
1395 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1396 "data 0x%llx\n", msr, data);
1402 static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1405 case HV_X64_MSR_APIC_ASSIST_PAGE: {
1408 if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
1409 vcpu->arch.hv_vapic = data;
1412 addr = gfn_to_hva(vcpu->kvm, data >>
1413 HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
1414 if (kvm_is_error_hva(addr))
1416 if (__clear_user((void __user *)addr, PAGE_SIZE))
1418 vcpu->arch.hv_vapic = data;
1421 case HV_X64_MSR_EOI:
1422 return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
1423 case HV_X64_MSR_ICR:
1424 return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
1425 case HV_X64_MSR_TPR:
1426 return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
1428 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1429 "data 0x%llx\n", msr, data);
1436 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
1438 gpa_t gpa = data & ~0x3f;
1440 /* Bits 2:5 are resrved, Should be zero */
1444 vcpu->arch.apf.msr_val = data;
1446 if (!(data & KVM_ASYNC_PF_ENABLED)) {
1447 kvm_clear_async_pf_completion_queue(vcpu);
1448 kvm_async_pf_hash_reset(vcpu);
1452 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa))
1455 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
1456 kvm_async_pf_wakeup_all(vcpu);
1460 static void kvmclock_reset(struct kvm_vcpu *vcpu)
1462 if (vcpu->arch.time_page) {
1463 kvm_release_page_dirty(vcpu->arch.time_page);
1464 vcpu->arch.time_page = NULL;
1468 static void accumulate_steal_time(struct kvm_vcpu *vcpu)
1472 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1475 delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
1476 vcpu->arch.st.last_steal = current->sched_info.run_delay;
1477 vcpu->arch.st.accum_steal = delta;
1480 static void record_steal_time(struct kvm_vcpu *vcpu)
1482 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1485 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1486 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
1489 vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
1490 vcpu->arch.st.steal.version += 2;
1491 vcpu->arch.st.accum_steal = 0;
1493 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1494 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
1497 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1503 return set_efer(vcpu, data);
1505 data &= ~(u64)0x40; /* ignore flush filter disable */
1506 data &= ~(u64)0x100; /* ignore ignne emulation enable */
1508 pr_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
1513 case MSR_FAM10H_MMIO_CONF_BASE:
1515 pr_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
1520 case MSR_AMD64_NB_CFG:
1522 case MSR_IA32_DEBUGCTLMSR:
1524 /* We support the non-activated case already */
1526 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
1527 /* Values other than LBR and BTF are vendor-specific,
1528 thus reserved and should throw a #GP */
1531 pr_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
1534 case MSR_IA32_UCODE_REV:
1535 case MSR_IA32_UCODE_WRITE:
1536 case MSR_VM_HSAVE_PA:
1537 case MSR_AMD64_PATCH_LOADER:
1539 case 0x200 ... 0x2ff:
1540 return set_msr_mtrr(vcpu, msr, data);
1541 case MSR_IA32_APICBASE:
1542 kvm_set_apic_base(vcpu, data);
1544 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1545 return kvm_x2apic_msr_write(vcpu, msr, data);
1546 case MSR_IA32_TSCDEADLINE:
1547 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1549 case MSR_IA32_MISC_ENABLE:
1550 vcpu->arch.ia32_misc_enable_msr = data;
1552 case MSR_KVM_WALL_CLOCK_NEW:
1553 case MSR_KVM_WALL_CLOCK:
1554 vcpu->kvm->arch.wall_clock = data;
1555 kvm_write_wall_clock(vcpu->kvm, data);
1557 case MSR_KVM_SYSTEM_TIME_NEW:
1558 case MSR_KVM_SYSTEM_TIME: {
1559 kvmclock_reset(vcpu);
1561 vcpu->arch.time = data;
1562 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1564 /* we verify if the enable bit is set... */
1568 /* ...but clean it before doing the actual write */
1569 vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
1571 vcpu->arch.time_page =
1572 gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
1574 if (is_error_page(vcpu->arch.time_page)) {
1575 kvm_release_page_clean(vcpu->arch.time_page);
1576 vcpu->arch.time_page = NULL;
1580 case MSR_KVM_ASYNC_PF_EN:
1581 if (kvm_pv_enable_async_pf(vcpu, data))
1584 case MSR_KVM_STEAL_TIME:
1586 if (unlikely(!sched_info_on()))
1589 if (data & KVM_STEAL_RESERVED_MASK)
1592 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
1593 data & KVM_STEAL_VALID_BITS))
1596 vcpu->arch.st.msr_val = data;
1598 if (!(data & KVM_MSR_ENABLED))
1601 vcpu->arch.st.last_steal = current->sched_info.run_delay;
1604 accumulate_steal_time(vcpu);
1607 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
1611 case MSR_IA32_MCG_CTL:
1612 case MSR_IA32_MCG_STATUS:
1613 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1614 return set_msr_mce(vcpu, msr, data);
1616 /* Performance counters are not protected by a CPUID bit,
1617 * so we should check all of them in the generic path for the sake of
1618 * cross vendor migration.
1619 * Writing a zero into the event select MSRs disables them,
1620 * which we perfectly emulate ;-). Any other value should be at least
1621 * reported, some guests depend on them.
1623 case MSR_K7_EVNTSEL0:
1624 case MSR_K7_EVNTSEL1:
1625 case MSR_K7_EVNTSEL2:
1626 case MSR_K7_EVNTSEL3:
1628 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1629 "0x%x data 0x%llx\n", msr, data);
1631 /* at least RHEL 4 unconditionally writes to the perfctr registers,
1632 * so we ignore writes to make it happy.
1634 case MSR_K7_PERFCTR0:
1635 case MSR_K7_PERFCTR1:
1636 case MSR_K7_PERFCTR2:
1637 case MSR_K7_PERFCTR3:
1638 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1639 "0x%x data 0x%llx\n", msr, data);
1641 case MSR_P6_PERFCTR0:
1642 case MSR_P6_PERFCTR1:
1644 case MSR_P6_EVNTSEL0:
1645 case MSR_P6_EVNTSEL1:
1646 if (kvm_pmu_msr(vcpu, msr))
1647 return kvm_pmu_set_msr(vcpu, msr, data);
1649 if (pr || data != 0)
1650 pr_unimpl(vcpu, "disabled perfctr wrmsr: "
1651 "0x%x data 0x%llx\n", msr, data);
1653 case MSR_K7_CLK_CTL:
1655 * Ignore all writes to this no longer documented MSR.
1656 * Writes are only relevant for old K7 processors,
1657 * all pre-dating SVM, but a recommended workaround from
1658 * AMD for these chips. It is possible to speicify the
1659 * affected processor models on the command line, hence
1660 * the need to ignore the workaround.
1663 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1664 if (kvm_hv_msr_partition_wide(msr)) {
1666 mutex_lock(&vcpu->kvm->lock);
1667 r = set_msr_hyperv_pw(vcpu, msr, data);
1668 mutex_unlock(&vcpu->kvm->lock);
1671 return set_msr_hyperv(vcpu, msr, data);
1673 case MSR_IA32_BBL_CR_CTL3:
1674 /* Drop writes to this legacy MSR -- see rdmsr
1675 * counterpart for further detail.
1677 pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
1680 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
1681 return xen_hvm_config(vcpu, data);
1682 if (kvm_pmu_msr(vcpu, msr))
1683 return kvm_pmu_set_msr(vcpu, msr, data);
1685 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
1689 pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
1696 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
1700 * Reads an msr value (of 'msr_index') into 'pdata'.
1701 * Returns 0 on success, non-0 otherwise.
1702 * Assumes vcpu_load() was already called.
1704 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1706 return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
1709 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1711 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1713 if (!msr_mtrr_valid(msr))
1716 if (msr == MSR_MTRRdefType)
1717 *pdata = vcpu->arch.mtrr_state.def_type +
1718 (vcpu->arch.mtrr_state.enabled << 10);
1719 else if (msr == MSR_MTRRfix64K_00000)
1721 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1722 *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
1723 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1724 *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
1725 else if (msr == MSR_IA32_CR_PAT)
1726 *pdata = vcpu->arch.pat;
1727 else { /* Variable MTRRs */
1728 int idx, is_mtrr_mask;
1731 idx = (msr - 0x200) / 2;
1732 is_mtrr_mask = msr - 0x200 - 2 * idx;
1735 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1738 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1745 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1748 u64 mcg_cap = vcpu->arch.mcg_cap;
1749 unsigned bank_num = mcg_cap & 0xff;
1752 case MSR_IA32_P5_MC_ADDR:
1753 case MSR_IA32_P5_MC_TYPE:
1756 case MSR_IA32_MCG_CAP:
1757 data = vcpu->arch.mcg_cap;
1759 case MSR_IA32_MCG_CTL:
1760 if (!(mcg_cap & MCG_CTL_P))
1762 data = vcpu->arch.mcg_ctl;
1764 case MSR_IA32_MCG_STATUS:
1765 data = vcpu->arch.mcg_status;
1768 if (msr >= MSR_IA32_MC0_CTL &&
1769 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1770 u32 offset = msr - MSR_IA32_MC0_CTL;
1771 data = vcpu->arch.mce_banks[offset];
1780 static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1783 struct kvm *kvm = vcpu->kvm;
1786 case HV_X64_MSR_GUEST_OS_ID:
1787 data = kvm->arch.hv_guest_os_id;
1789 case HV_X64_MSR_HYPERCALL:
1790 data = kvm->arch.hv_hypercall;
1793 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1801 static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1806 case HV_X64_MSR_VP_INDEX: {
1809 kvm_for_each_vcpu(r, v, vcpu->kvm)
1814 case HV_X64_MSR_EOI:
1815 return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
1816 case HV_X64_MSR_ICR:
1817 return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
1818 case HV_X64_MSR_TPR:
1819 return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
1820 case HV_X64_MSR_APIC_ASSIST_PAGE:
1821 data = vcpu->arch.hv_vapic;
1824 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1831 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1836 case MSR_IA32_PLATFORM_ID:
1837 case MSR_IA32_EBL_CR_POWERON:
1838 case MSR_IA32_DEBUGCTLMSR:
1839 case MSR_IA32_LASTBRANCHFROMIP:
1840 case MSR_IA32_LASTBRANCHTOIP:
1841 case MSR_IA32_LASTINTFROMIP:
1842 case MSR_IA32_LASTINTTOIP:
1845 case MSR_VM_HSAVE_PA:
1846 case MSR_K7_EVNTSEL0:
1847 case MSR_K7_PERFCTR0:
1848 case MSR_K8_INT_PENDING_MSG:
1849 case MSR_AMD64_NB_CFG:
1850 case MSR_FAM10H_MMIO_CONF_BASE:
1853 case MSR_P6_PERFCTR0:
1854 case MSR_P6_PERFCTR1:
1855 case MSR_P6_EVNTSEL0:
1856 case MSR_P6_EVNTSEL1:
1857 if (kvm_pmu_msr(vcpu, msr))
1858 return kvm_pmu_get_msr(vcpu, msr, pdata);
1861 case MSR_IA32_UCODE_REV:
1862 data = 0x100000000ULL;
1865 data = 0x500 | KVM_NR_VAR_MTRR;
1867 case 0x200 ... 0x2ff:
1868 return get_msr_mtrr(vcpu, msr, pdata);
1869 case 0xcd: /* fsb frequency */
1873 * MSR_EBC_FREQUENCY_ID
1874 * Conservative value valid for even the basic CPU models.
1875 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
1876 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
1877 * and 266MHz for model 3, or 4. Set Core Clock
1878 * Frequency to System Bus Frequency Ratio to 1 (bits
1879 * 31:24) even though these are only valid for CPU
1880 * models > 2, however guests may end up dividing or
1881 * multiplying by zero otherwise.
1883 case MSR_EBC_FREQUENCY_ID:
1886 case MSR_IA32_APICBASE:
1887 data = kvm_get_apic_base(vcpu);
1889 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1890 return kvm_x2apic_msr_read(vcpu, msr, pdata);
1892 case MSR_IA32_TSCDEADLINE:
1893 data = kvm_get_lapic_tscdeadline_msr(vcpu);
1895 case MSR_IA32_MISC_ENABLE:
1896 data = vcpu->arch.ia32_misc_enable_msr;
1898 case MSR_IA32_PERF_STATUS:
1899 /* TSC increment by tick */
1901 /* CPU multiplier */
1902 data |= (((uint64_t)4ULL) << 40);
1905 data = vcpu->arch.efer;
1907 case MSR_KVM_WALL_CLOCK:
1908 case MSR_KVM_WALL_CLOCK_NEW:
1909 data = vcpu->kvm->arch.wall_clock;
1911 case MSR_KVM_SYSTEM_TIME:
1912 case MSR_KVM_SYSTEM_TIME_NEW:
1913 data = vcpu->arch.time;
1915 case MSR_KVM_ASYNC_PF_EN:
1916 data = vcpu->arch.apf.msr_val;
1918 case MSR_KVM_STEAL_TIME:
1919 data = vcpu->arch.st.msr_val;
1921 case MSR_IA32_P5_MC_ADDR:
1922 case MSR_IA32_P5_MC_TYPE:
1923 case MSR_IA32_MCG_CAP:
1924 case MSR_IA32_MCG_CTL:
1925 case MSR_IA32_MCG_STATUS:
1926 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1927 return get_msr_mce(vcpu, msr, pdata);
1928 case MSR_K7_CLK_CTL:
1930 * Provide expected ramp-up count for K7. All other
1931 * are set to zero, indicating minimum divisors for
1934 * This prevents guest kernels on AMD host with CPU
1935 * type 6, model 8 and higher from exploding due to
1936 * the rdmsr failing.
1940 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1941 if (kvm_hv_msr_partition_wide(msr)) {
1943 mutex_lock(&vcpu->kvm->lock);
1944 r = get_msr_hyperv_pw(vcpu, msr, pdata);
1945 mutex_unlock(&vcpu->kvm->lock);
1948 return get_msr_hyperv(vcpu, msr, pdata);
1950 case MSR_IA32_BBL_CR_CTL3:
1951 /* This legacy MSR exists but isn't fully documented in current
1952 * silicon. It is however accessed by winxp in very narrow
1953 * scenarios where it sets bit #19, itself documented as
1954 * a "reserved" bit. Best effort attempt to source coherent
1955 * read data here should the balance of the register be
1956 * interpreted by the guest:
1958 * L2 cache control register 3: 64GB range, 256KB size,
1959 * enabled, latency 0x1, configured
1964 if (kvm_pmu_msr(vcpu, msr))
1965 return kvm_pmu_get_msr(vcpu, msr, pdata);
1967 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
1970 pr_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
1978 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
1981 * Read or write a bunch of msrs. All parameters are kernel addresses.
1983 * @return number of msrs set successfully.
1985 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
1986 struct kvm_msr_entry *entries,
1987 int (*do_msr)(struct kvm_vcpu *vcpu,
1988 unsigned index, u64 *data))
1992 idx = srcu_read_lock(&vcpu->kvm->srcu);
1993 for (i = 0; i < msrs->nmsrs; ++i)
1994 if (do_msr(vcpu, entries[i].index, &entries[i].data))
1996 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2002 * Read or write a bunch of msrs. Parameters are user addresses.
2004 * @return number of msrs set successfully.
2006 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2007 int (*do_msr)(struct kvm_vcpu *vcpu,
2008 unsigned index, u64 *data),
2011 struct kvm_msrs msrs;
2012 struct kvm_msr_entry *entries;
2017 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2021 if (msrs.nmsrs >= MAX_IO_MSRS)
2024 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2025 entries = memdup_user(user_msrs->entries, size);
2026 if (IS_ERR(entries)) {
2027 r = PTR_ERR(entries);
2031 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2036 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2047 int kvm_dev_ioctl_check_extension(long ext)
2052 case KVM_CAP_IRQCHIP:
2054 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2055 case KVM_CAP_SET_TSS_ADDR:
2056 case KVM_CAP_EXT_CPUID:
2057 case KVM_CAP_CLOCKSOURCE:
2059 case KVM_CAP_NOP_IO_DELAY:
2060 case KVM_CAP_MP_STATE:
2061 case KVM_CAP_SYNC_MMU:
2062 case KVM_CAP_USER_NMI:
2063 case KVM_CAP_REINJECT_CONTROL:
2064 case KVM_CAP_IRQ_INJECT_STATUS:
2065 case KVM_CAP_ASSIGN_DEV_IRQ:
2067 case KVM_CAP_IOEVENTFD:
2069 case KVM_CAP_PIT_STATE2:
2070 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2071 case KVM_CAP_XEN_HVM:
2072 case KVM_CAP_ADJUST_CLOCK:
2073 case KVM_CAP_VCPU_EVENTS:
2074 case KVM_CAP_HYPERV:
2075 case KVM_CAP_HYPERV_VAPIC:
2076 case KVM_CAP_HYPERV_SPIN:
2077 case KVM_CAP_PCI_SEGMENT:
2078 case KVM_CAP_DEBUGREGS:
2079 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2081 case KVM_CAP_ASYNC_PF:
2082 case KVM_CAP_GET_TSC_KHZ:
2085 case KVM_CAP_COALESCED_MMIO:
2086 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2089 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2091 case KVM_CAP_NR_VCPUS:
2092 r = KVM_SOFT_MAX_VCPUS;
2094 case KVM_CAP_MAX_VCPUS:
2097 case KVM_CAP_NR_MEMSLOTS:
2098 r = KVM_MEMORY_SLOTS;
2100 case KVM_CAP_PV_MMU: /* obsolete */
2104 r = iommu_present(&pci_bus_type);
2107 r = KVM_MAX_MCE_BANKS;
2112 case KVM_CAP_TSC_CONTROL:
2113 r = kvm_has_tsc_control;
2115 case KVM_CAP_TSC_DEADLINE_TIMER:
2116 r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
2126 long kvm_arch_dev_ioctl(struct file *filp,
2127 unsigned int ioctl, unsigned long arg)
2129 void __user *argp = (void __user *)arg;
2133 case KVM_GET_MSR_INDEX_LIST: {
2134 struct kvm_msr_list __user *user_msr_list = argp;
2135 struct kvm_msr_list msr_list;
2139 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2142 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
2143 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2146 if (n < msr_list.nmsrs)
2149 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2150 num_msrs_to_save * sizeof(u32)))
2152 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2154 ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
2159 case KVM_GET_SUPPORTED_CPUID: {
2160 struct kvm_cpuid2 __user *cpuid_arg = argp;
2161 struct kvm_cpuid2 cpuid;
2164 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2166 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
2167 cpuid_arg->entries);
2172 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2177 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2180 mce_cap = KVM_MCE_CAP_SUPPORTED;
2182 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2194 static void wbinvd_ipi(void *garbage)
2199 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2201 return vcpu->kvm->arch.iommu_domain &&
2202 !(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY);
2205 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2207 /* Address WBINVD may be executed by guest */
2208 if (need_emulate_wbinvd(vcpu)) {
2209 if (kvm_x86_ops->has_wbinvd_exit())
2210 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2211 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2212 smp_call_function_single(vcpu->cpu,
2213 wbinvd_ipi, NULL, 1);
2216 kvm_x86_ops->vcpu_load(vcpu, cpu);
2217 if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2218 /* Make sure TSC doesn't go backwards */
2222 tsc = kvm_x86_ops->read_l1_tsc(vcpu);
2223 tsc_delta = !vcpu->arch.last_guest_tsc ? 0 :
2224 tsc - vcpu->arch.last_guest_tsc;
2227 mark_tsc_unstable("KVM discovered backwards TSC");
2228 if (check_tsc_unstable()) {
2229 kvm_x86_ops->adjust_tsc_offset(vcpu, -tsc_delta);
2230 vcpu->arch.tsc_catchup = 1;
2232 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2233 if (vcpu->cpu != cpu)
2234 kvm_migrate_timers(vcpu);
2238 accumulate_steal_time(vcpu);
2239 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2242 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2244 kvm_x86_ops->vcpu_put(vcpu);
2245 kvm_put_guest_fpu(vcpu);
2246 vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu);
2249 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2250 struct kvm_lapic_state *s)
2252 memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2257 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2258 struct kvm_lapic_state *s)
2260 memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
2261 kvm_apic_post_state_restore(vcpu);
2262 update_cr8_intercept(vcpu);
2267 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2268 struct kvm_interrupt *irq)
2270 if (irq->irq < 0 || irq->irq >= 256)
2272 if (irqchip_in_kernel(vcpu->kvm))
2275 kvm_queue_interrupt(vcpu, irq->irq, false);
2276 kvm_make_request(KVM_REQ_EVENT, vcpu);
2281 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2283 kvm_inject_nmi(vcpu);
2288 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2289 struct kvm_tpr_access_ctl *tac)
2293 vcpu->arch.tpr_access_reporting = !!tac->enabled;
2297 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2301 unsigned bank_num = mcg_cap & 0xff, bank;
2304 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2306 if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2309 vcpu->arch.mcg_cap = mcg_cap;
2310 /* Init IA32_MCG_CTL to all 1s */
2311 if (mcg_cap & MCG_CTL_P)
2312 vcpu->arch.mcg_ctl = ~(u64)0;
2313 /* Init IA32_MCi_CTL to all 1s */
2314 for (bank = 0; bank < bank_num; bank++)
2315 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2320 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2321 struct kvm_x86_mce *mce)
2323 u64 mcg_cap = vcpu->arch.mcg_cap;
2324 unsigned bank_num = mcg_cap & 0xff;
2325 u64 *banks = vcpu->arch.mce_banks;
2327 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2330 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2331 * reporting is disabled
2333 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2334 vcpu->arch.mcg_ctl != ~(u64)0)
2336 banks += 4 * mce->bank;
2338 * if IA32_MCi_CTL is not all 1s, the uncorrected error
2339 * reporting is disabled for the bank
2341 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2343 if (mce->status & MCI_STATUS_UC) {
2344 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2345 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2346 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2349 if (banks[1] & MCI_STATUS_VAL)
2350 mce->status |= MCI_STATUS_OVER;
2351 banks[2] = mce->addr;
2352 banks[3] = mce->misc;
2353 vcpu->arch.mcg_status = mce->mcg_status;
2354 banks[1] = mce->status;
2355 kvm_queue_exception(vcpu, MC_VECTOR);
2356 } else if (!(banks[1] & MCI_STATUS_VAL)
2357 || !(banks[1] & MCI_STATUS_UC)) {
2358 if (banks[1] & MCI_STATUS_VAL)
2359 mce->status |= MCI_STATUS_OVER;
2360 banks[2] = mce->addr;
2361 banks[3] = mce->misc;
2362 banks[1] = mce->status;
2364 banks[1] |= MCI_STATUS_OVER;
2368 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2369 struct kvm_vcpu_events *events)
2372 events->exception.injected =
2373 vcpu->arch.exception.pending &&
2374 !kvm_exception_is_soft(vcpu->arch.exception.nr);
2375 events->exception.nr = vcpu->arch.exception.nr;
2376 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2377 events->exception.pad = 0;
2378 events->exception.error_code = vcpu->arch.exception.error_code;
2380 events->interrupt.injected =
2381 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
2382 events->interrupt.nr = vcpu->arch.interrupt.nr;
2383 events->interrupt.soft = 0;
2384 events->interrupt.shadow =
2385 kvm_x86_ops->get_interrupt_shadow(vcpu,
2386 KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
2388 events->nmi.injected = vcpu->arch.nmi_injected;
2389 events->nmi.pending = vcpu->arch.nmi_pending != 0;
2390 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
2391 events->nmi.pad = 0;
2393 events->sipi_vector = vcpu->arch.sipi_vector;
2395 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
2396 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2397 | KVM_VCPUEVENT_VALID_SHADOW);
2398 memset(&events->reserved, 0, sizeof(events->reserved));
2401 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
2402 struct kvm_vcpu_events *events)
2404 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
2405 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2406 | KVM_VCPUEVENT_VALID_SHADOW))
2410 vcpu->arch.exception.pending = events->exception.injected;
2411 vcpu->arch.exception.nr = events->exception.nr;
2412 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
2413 vcpu->arch.exception.error_code = events->exception.error_code;
2415 vcpu->arch.interrupt.pending = events->interrupt.injected;
2416 vcpu->arch.interrupt.nr = events->interrupt.nr;
2417 vcpu->arch.interrupt.soft = events->interrupt.soft;
2418 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
2419 kvm_x86_ops->set_interrupt_shadow(vcpu,
2420 events->interrupt.shadow);
2422 vcpu->arch.nmi_injected = events->nmi.injected;
2423 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
2424 vcpu->arch.nmi_pending = events->nmi.pending;
2425 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
2427 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR)
2428 vcpu->arch.sipi_vector = events->sipi_vector;
2430 kvm_make_request(KVM_REQ_EVENT, vcpu);
2435 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
2436 struct kvm_debugregs *dbgregs)
2438 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
2439 dbgregs->dr6 = vcpu->arch.dr6;
2440 dbgregs->dr7 = vcpu->arch.dr7;
2442 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
2445 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
2446 struct kvm_debugregs *dbgregs)
2451 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
2452 vcpu->arch.dr6 = dbgregs->dr6;
2453 vcpu->arch.dr7 = dbgregs->dr7;
2458 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
2459 struct kvm_xsave *guest_xsave)
2462 memcpy(guest_xsave->region,
2463 &vcpu->arch.guest_fpu.state->xsave,
2466 memcpy(guest_xsave->region,
2467 &vcpu->arch.guest_fpu.state->fxsave,
2468 sizeof(struct i387_fxsave_struct));
2469 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
2474 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
2475 struct kvm_xsave *guest_xsave)
2478 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
2481 memcpy(&vcpu->arch.guest_fpu.state->xsave,
2482 guest_xsave->region, xstate_size);
2484 if (xstate_bv & ~XSTATE_FPSSE)
2486 memcpy(&vcpu->arch.guest_fpu.state->fxsave,
2487 guest_xsave->region, sizeof(struct i387_fxsave_struct));
2492 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
2493 struct kvm_xcrs *guest_xcrs)
2495 if (!cpu_has_xsave) {
2496 guest_xcrs->nr_xcrs = 0;
2500 guest_xcrs->nr_xcrs = 1;
2501 guest_xcrs->flags = 0;
2502 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
2503 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
2506 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
2507 struct kvm_xcrs *guest_xcrs)
2514 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
2517 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
2518 /* Only support XCR0 currently */
2519 if (guest_xcrs->xcrs[0].xcr == XCR_XFEATURE_ENABLED_MASK) {
2520 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
2521 guest_xcrs->xcrs[0].value);
2529 long kvm_arch_vcpu_ioctl(struct file *filp,
2530 unsigned int ioctl, unsigned long arg)
2532 struct kvm_vcpu *vcpu = filp->private_data;
2533 void __user *argp = (void __user *)arg;
2536 struct kvm_lapic_state *lapic;
2537 struct kvm_xsave *xsave;
2538 struct kvm_xcrs *xcrs;
2544 case KVM_GET_LAPIC: {
2546 if (!vcpu->arch.apic)
2548 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
2553 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
2557 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
2562 case KVM_SET_LAPIC: {
2564 if (!vcpu->arch.apic)
2566 u.lapic = memdup_user(argp, sizeof(*u.lapic));
2567 if (IS_ERR(u.lapic)) {
2568 r = PTR_ERR(u.lapic);
2572 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
2578 case KVM_INTERRUPT: {
2579 struct kvm_interrupt irq;
2582 if (copy_from_user(&irq, argp, sizeof irq))
2584 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
2591 r = kvm_vcpu_ioctl_nmi(vcpu);
2597 case KVM_SET_CPUID: {
2598 struct kvm_cpuid __user *cpuid_arg = argp;
2599 struct kvm_cpuid cpuid;
2602 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2604 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
2609 case KVM_SET_CPUID2: {
2610 struct kvm_cpuid2 __user *cpuid_arg = argp;
2611 struct kvm_cpuid2 cpuid;
2614 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2616 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
2617 cpuid_arg->entries);
2622 case KVM_GET_CPUID2: {
2623 struct kvm_cpuid2 __user *cpuid_arg = argp;
2624 struct kvm_cpuid2 cpuid;
2627 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2629 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
2630 cpuid_arg->entries);
2634 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2640 r = msr_io(vcpu, argp, kvm_get_msr, 1);
2643 r = msr_io(vcpu, argp, do_set_msr, 0);
2645 case KVM_TPR_ACCESS_REPORTING: {
2646 struct kvm_tpr_access_ctl tac;
2649 if (copy_from_user(&tac, argp, sizeof tac))
2651 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
2655 if (copy_to_user(argp, &tac, sizeof tac))
2660 case KVM_SET_VAPIC_ADDR: {
2661 struct kvm_vapic_addr va;
2664 if (!irqchip_in_kernel(vcpu->kvm))
2667 if (copy_from_user(&va, argp, sizeof va))
2670 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
2673 case KVM_X86_SETUP_MCE: {
2677 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
2679 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
2682 case KVM_X86_SET_MCE: {
2683 struct kvm_x86_mce mce;
2686 if (copy_from_user(&mce, argp, sizeof mce))
2688 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
2691 case KVM_GET_VCPU_EVENTS: {
2692 struct kvm_vcpu_events events;
2694 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
2697 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
2702 case KVM_SET_VCPU_EVENTS: {
2703 struct kvm_vcpu_events events;
2706 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
2709 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
2712 case KVM_GET_DEBUGREGS: {
2713 struct kvm_debugregs dbgregs;
2715 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
2718 if (copy_to_user(argp, &dbgregs,
2719 sizeof(struct kvm_debugregs)))
2724 case KVM_SET_DEBUGREGS: {
2725 struct kvm_debugregs dbgregs;
2728 if (copy_from_user(&dbgregs, argp,
2729 sizeof(struct kvm_debugregs)))
2732 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
2735 case KVM_GET_XSAVE: {
2736 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
2741 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
2744 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
2749 case KVM_SET_XSAVE: {
2750 u.xsave = memdup_user(argp, sizeof(*u.xsave));
2751 if (IS_ERR(u.xsave)) {
2752 r = PTR_ERR(u.xsave);
2756 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
2759 case KVM_GET_XCRS: {
2760 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
2765 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
2768 if (copy_to_user(argp, u.xcrs,
2769 sizeof(struct kvm_xcrs)))
2774 case KVM_SET_XCRS: {
2775 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
2776 if (IS_ERR(u.xcrs)) {
2777 r = PTR_ERR(u.xcrs);
2781 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
2784 case KVM_SET_TSC_KHZ: {
2788 if (!kvm_has_tsc_control)
2791 user_tsc_khz = (u32)arg;
2793 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
2796 kvm_x86_ops->set_tsc_khz(vcpu, user_tsc_khz);
2801 case KVM_GET_TSC_KHZ: {
2803 if (check_tsc_unstable())
2806 r = vcpu_tsc_khz(vcpu);
2818 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
2822 if (addr > (unsigned int)(-3 * PAGE_SIZE))
2824 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
2828 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
2831 kvm->arch.ept_identity_map_addr = ident_addr;
2835 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
2836 u32 kvm_nr_mmu_pages)
2838 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
2841 mutex_lock(&kvm->slots_lock);
2842 spin_lock(&kvm->mmu_lock);
2844 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
2845 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
2847 spin_unlock(&kvm->mmu_lock);
2848 mutex_unlock(&kvm->slots_lock);
2852 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
2854 return kvm->arch.n_max_mmu_pages;
2857 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2862 switch (chip->chip_id) {
2863 case KVM_IRQCHIP_PIC_MASTER:
2864 memcpy(&chip->chip.pic,
2865 &pic_irqchip(kvm)->pics[0],
2866 sizeof(struct kvm_pic_state));
2868 case KVM_IRQCHIP_PIC_SLAVE:
2869 memcpy(&chip->chip.pic,
2870 &pic_irqchip(kvm)->pics[1],
2871 sizeof(struct kvm_pic_state));
2873 case KVM_IRQCHIP_IOAPIC:
2874 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
2883 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2888 switch (chip->chip_id) {
2889 case KVM_IRQCHIP_PIC_MASTER:
2890 spin_lock(&pic_irqchip(kvm)->lock);
2891 memcpy(&pic_irqchip(kvm)->pics[0],
2893 sizeof(struct kvm_pic_state));
2894 spin_unlock(&pic_irqchip(kvm)->lock);
2896 case KVM_IRQCHIP_PIC_SLAVE:
2897 spin_lock(&pic_irqchip(kvm)->lock);
2898 memcpy(&pic_irqchip(kvm)->pics[1],
2900 sizeof(struct kvm_pic_state));
2901 spin_unlock(&pic_irqchip(kvm)->lock);
2903 case KVM_IRQCHIP_IOAPIC:
2904 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
2910 kvm_pic_update_irq(pic_irqchip(kvm));
2914 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2918 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2919 memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
2920 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2924 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2928 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2929 memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
2930 kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
2931 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2935 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2939 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2940 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
2941 sizeof(ps->channels));
2942 ps->flags = kvm->arch.vpit->pit_state.flags;
2943 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2944 memset(&ps->reserved, 0, sizeof(ps->reserved));
2948 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2950 int r = 0, start = 0;
2951 u32 prev_legacy, cur_legacy;
2952 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2953 prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
2954 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
2955 if (!prev_legacy && cur_legacy)
2957 memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
2958 sizeof(kvm->arch.vpit->pit_state.channels));
2959 kvm->arch.vpit->pit_state.flags = ps->flags;
2960 kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
2961 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2965 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
2966 struct kvm_reinject_control *control)
2968 if (!kvm->arch.vpit)
2970 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2971 kvm->arch.vpit->pit_state.pit_timer.reinject = control->pit_reinject;
2972 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2977 * write_protect_slot - write protect a slot for dirty logging
2978 * @kvm: the kvm instance
2979 * @memslot: the slot we protect
2980 * @dirty_bitmap: the bitmap indicating which pages are dirty
2981 * @nr_dirty_pages: the number of dirty pages
2983 * We have two ways to find all sptes to protect:
2984 * 1. Use kvm_mmu_slot_remove_write_access() which walks all shadow pages and
2985 * checks ones that have a spte mapping a page in the slot.
2986 * 2. Use kvm_mmu_rmap_write_protect() for each gfn found in the bitmap.
2988 * Generally speaking, if there are not so many dirty pages compared to the
2989 * number of shadow pages, we should use the latter.
2991 * Note that letting others write into a page marked dirty in the old bitmap
2992 * by using the remaining tlb entry is not a problem. That page will become
2993 * write protected again when we flush the tlb and then be reported dirty to
2994 * the user space by copying the old bitmap.
2996 static void write_protect_slot(struct kvm *kvm,
2997 struct kvm_memory_slot *memslot,
2998 unsigned long *dirty_bitmap,
2999 unsigned long nr_dirty_pages)
3001 /* Not many dirty pages compared to # of shadow pages. */
3002 if (nr_dirty_pages < kvm->arch.n_used_mmu_pages) {
3003 unsigned long gfn_offset;
3005 for_each_set_bit(gfn_offset, dirty_bitmap, memslot->npages) {
3006 unsigned long gfn = memslot->base_gfn + gfn_offset;
3008 spin_lock(&kvm->mmu_lock);
3009 kvm_mmu_rmap_write_protect(kvm, gfn, memslot);
3010 spin_unlock(&kvm->mmu_lock);
3012 kvm_flush_remote_tlbs(kvm);
3014 spin_lock(&kvm->mmu_lock);
3015 kvm_mmu_slot_remove_write_access(kvm, memslot->id);
3016 spin_unlock(&kvm->mmu_lock);
3021 * Get (and clear) the dirty memory log for a memory slot.
3023 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
3024 struct kvm_dirty_log *log)
3027 struct kvm_memory_slot *memslot;
3028 unsigned long n, nr_dirty_pages;
3030 mutex_lock(&kvm->slots_lock);
3033 if (log->slot >= KVM_MEMORY_SLOTS)
3036 memslot = id_to_memslot(kvm->memslots, log->slot);
3038 if (!memslot->dirty_bitmap)
3041 n = kvm_dirty_bitmap_bytes(memslot);
3042 nr_dirty_pages = memslot->nr_dirty_pages;
3044 /* If nothing is dirty, don't bother messing with page tables. */
3045 if (nr_dirty_pages) {
3046 struct kvm_memslots *slots, *old_slots;
3047 unsigned long *dirty_bitmap, *dirty_bitmap_head;
3049 dirty_bitmap = memslot->dirty_bitmap;
3050 dirty_bitmap_head = memslot->dirty_bitmap_head;
3051 if (dirty_bitmap == dirty_bitmap_head)
3052 dirty_bitmap_head += n / sizeof(long);
3053 memset(dirty_bitmap_head, 0, n);
3056 slots = kmemdup(kvm->memslots, sizeof(*kvm->memslots), GFP_KERNEL);
3060 memslot = id_to_memslot(slots, log->slot);
3061 memslot->nr_dirty_pages = 0;
3062 memslot->dirty_bitmap = dirty_bitmap_head;
3063 update_memslots(slots, NULL);
3065 old_slots = kvm->memslots;
3066 rcu_assign_pointer(kvm->memslots, slots);
3067 synchronize_srcu_expedited(&kvm->srcu);
3070 write_protect_slot(kvm, memslot, dirty_bitmap, nr_dirty_pages);
3073 if (copy_to_user(log->dirty_bitmap, dirty_bitmap, n))
3077 if (clear_user(log->dirty_bitmap, n))
3083 mutex_unlock(&kvm->slots_lock);
3087 long kvm_arch_vm_ioctl(struct file *filp,
3088 unsigned int ioctl, unsigned long arg)
3090 struct kvm *kvm = filp->private_data;
3091 void __user *argp = (void __user *)arg;
3094 * This union makes it completely explicit to gcc-3.x
3095 * that these two variables' stack usage should be
3096 * combined, not added together.
3099 struct kvm_pit_state ps;
3100 struct kvm_pit_state2 ps2;
3101 struct kvm_pit_config pit_config;
3105 case KVM_SET_TSS_ADDR:
3106 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3110 case KVM_SET_IDENTITY_MAP_ADDR: {
3114 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3116 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3121 case KVM_SET_NR_MMU_PAGES:
3122 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3126 case KVM_GET_NR_MMU_PAGES:
3127 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3129 case KVM_CREATE_IRQCHIP: {
3130 struct kvm_pic *vpic;
3132 mutex_lock(&kvm->lock);
3135 goto create_irqchip_unlock;
3137 vpic = kvm_create_pic(kvm);
3139 r = kvm_ioapic_init(kvm);
3141 mutex_lock(&kvm->slots_lock);
3142 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3144 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3146 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3148 mutex_unlock(&kvm->slots_lock);
3150 goto create_irqchip_unlock;
3153 goto create_irqchip_unlock;
3155 kvm->arch.vpic = vpic;
3157 r = kvm_setup_default_irq_routing(kvm);
3159 mutex_lock(&kvm->slots_lock);
3160 mutex_lock(&kvm->irq_lock);
3161 kvm_ioapic_destroy(kvm);
3162 kvm_destroy_pic(kvm);
3163 mutex_unlock(&kvm->irq_lock);
3164 mutex_unlock(&kvm->slots_lock);
3166 create_irqchip_unlock:
3167 mutex_unlock(&kvm->lock);
3170 case KVM_CREATE_PIT:
3171 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3173 case KVM_CREATE_PIT2:
3175 if (copy_from_user(&u.pit_config, argp,
3176 sizeof(struct kvm_pit_config)))
3179 mutex_lock(&kvm->slots_lock);
3182 goto create_pit_unlock;
3184 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3188 mutex_unlock(&kvm->slots_lock);
3190 case KVM_IRQ_LINE_STATUS:
3191 case KVM_IRQ_LINE: {
3192 struct kvm_irq_level irq_event;
3195 if (copy_from_user(&irq_event, argp, sizeof irq_event))
3198 if (irqchip_in_kernel(kvm)) {
3200 status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3201 irq_event.irq, irq_event.level);
3202 if (ioctl == KVM_IRQ_LINE_STATUS) {
3204 irq_event.status = status;
3205 if (copy_to_user(argp, &irq_event,
3213 case KVM_GET_IRQCHIP: {
3214 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3215 struct kvm_irqchip *chip;
3217 chip = memdup_user(argp, sizeof(*chip));
3224 if (!irqchip_in_kernel(kvm))
3225 goto get_irqchip_out;
3226 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3228 goto get_irqchip_out;
3230 if (copy_to_user(argp, chip, sizeof *chip))
3231 goto get_irqchip_out;
3239 case KVM_SET_IRQCHIP: {
3240 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3241 struct kvm_irqchip *chip;
3243 chip = memdup_user(argp, sizeof(*chip));
3250 if (!irqchip_in_kernel(kvm))
3251 goto set_irqchip_out;
3252 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3254 goto set_irqchip_out;
3264 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
3267 if (!kvm->arch.vpit)
3269 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
3273 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
3280 if (copy_from_user(&u.ps, argp, sizeof u.ps))
3283 if (!kvm->arch.vpit)
3285 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
3291 case KVM_GET_PIT2: {
3293 if (!kvm->arch.vpit)
3295 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
3299 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
3304 case KVM_SET_PIT2: {
3306 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
3309 if (!kvm->arch.vpit)
3311 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
3317 case KVM_REINJECT_CONTROL: {
3318 struct kvm_reinject_control control;
3320 if (copy_from_user(&control, argp, sizeof(control)))
3322 r = kvm_vm_ioctl_reinject(kvm, &control);
3328 case KVM_XEN_HVM_CONFIG: {
3330 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
3331 sizeof(struct kvm_xen_hvm_config)))
3334 if (kvm->arch.xen_hvm_config.flags)
3339 case KVM_SET_CLOCK: {
3340 struct kvm_clock_data user_ns;
3345 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
3353 local_irq_disable();
3354 now_ns = get_kernel_ns();
3355 delta = user_ns.clock - now_ns;
3357 kvm->arch.kvmclock_offset = delta;
3360 case KVM_GET_CLOCK: {
3361 struct kvm_clock_data user_ns;
3364 local_irq_disable();
3365 now_ns = get_kernel_ns();
3366 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
3369 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
3372 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
3385 static void kvm_init_msr_list(void)
3390 /* skip the first msrs in the list. KVM-specific */
3391 for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
3392 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
3395 msrs_to_save[j] = msrs_to_save[i];
3398 num_msrs_to_save = j;
3401 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
3409 if (!(vcpu->arch.apic &&
3410 !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, n, v))
3411 && kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
3422 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
3429 if (!(vcpu->arch.apic &&
3430 !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, n, v))
3431 && kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
3433 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
3443 static void kvm_set_segment(struct kvm_vcpu *vcpu,
3444 struct kvm_segment *var, int seg)
3446 kvm_x86_ops->set_segment(vcpu, var, seg);
3449 void kvm_get_segment(struct kvm_vcpu *vcpu,
3450 struct kvm_segment *var, int seg)
3452 kvm_x86_ops->get_segment(vcpu, var, seg);
3455 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
3458 struct x86_exception exception;
3460 BUG_ON(!mmu_is_nested(vcpu));
3462 /* NPT walks are always user-walks */
3463 access |= PFERR_USER_MASK;
3464 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, &exception);
3469 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
3470 struct x86_exception *exception)
3472 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3473 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3476 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
3477 struct x86_exception *exception)
3479 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3480 access |= PFERR_FETCH_MASK;
3481 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3484 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
3485 struct x86_exception *exception)
3487 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3488 access |= PFERR_WRITE_MASK;
3489 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3492 /* uses this to access any guest's mapped memory without checking CPL */
3493 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
3494 struct x86_exception *exception)
3496 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
3499 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
3500 struct kvm_vcpu *vcpu, u32 access,
3501 struct x86_exception *exception)
3504 int r = X86EMUL_CONTINUE;
3507 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
3509 unsigned offset = addr & (PAGE_SIZE-1);
3510 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
3513 if (gpa == UNMAPPED_GVA)
3514 return X86EMUL_PROPAGATE_FAULT;
3515 ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
3517 r = X86EMUL_IO_NEEDED;
3529 /* used for instruction fetching */
3530 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
3531 gva_t addr, void *val, unsigned int bytes,
3532 struct x86_exception *exception)
3534 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3535 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3537 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
3538 access | PFERR_FETCH_MASK,
3542 int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
3543 gva_t addr, void *val, unsigned int bytes,
3544 struct x86_exception *exception)
3546 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3547 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3549 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
3552 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
3554 static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
3555 gva_t addr, void *val, unsigned int bytes,
3556 struct x86_exception *exception)
3558 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3559 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
3562 int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
3563 gva_t addr, void *val,
3565 struct x86_exception *exception)
3567 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3569 int r = X86EMUL_CONTINUE;
3572 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
3575 unsigned offset = addr & (PAGE_SIZE-1);
3576 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
3579 if (gpa == UNMAPPED_GVA)
3580 return X86EMUL_PROPAGATE_FAULT;
3581 ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
3583 r = X86EMUL_IO_NEEDED;
3594 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
3596 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
3597 gpa_t *gpa, struct x86_exception *exception,
3600 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3602 if (vcpu_match_mmio_gva(vcpu, gva) &&
3603 check_write_user_access(vcpu, write, access,
3604 vcpu->arch.access)) {
3605 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
3606 (gva & (PAGE_SIZE - 1));
3607 trace_vcpu_match_mmio(gva, *gpa, write, false);
3612 access |= PFERR_WRITE_MASK;
3614 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3616 if (*gpa == UNMAPPED_GVA)
3619 /* For APIC access vmexit */
3620 if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3623 if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
3624 trace_vcpu_match_mmio(gva, *gpa, write, true);
3631 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
3632 const void *val, int bytes)
3636 ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
3639 kvm_mmu_pte_write(vcpu, gpa, val, bytes);
3643 struct read_write_emulator_ops {
3644 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
3646 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
3647 void *val, int bytes);
3648 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
3649 int bytes, void *val);
3650 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
3651 void *val, int bytes);
3655 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
3657 if (vcpu->mmio_read_completed) {
3658 memcpy(val, vcpu->mmio_data, bytes);
3659 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
3660 vcpu->mmio_phys_addr, *(u64 *)val);
3661 vcpu->mmio_read_completed = 0;
3668 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
3669 void *val, int bytes)
3671 return !kvm_read_guest(vcpu->kvm, gpa, val, bytes);
3674 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
3675 void *val, int bytes)
3677 return emulator_write_phys(vcpu, gpa, val, bytes);
3680 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
3682 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
3683 return vcpu_mmio_write(vcpu, gpa, bytes, val);
3686 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
3687 void *val, int bytes)
3689 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
3690 return X86EMUL_IO_NEEDED;
3693 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
3694 void *val, int bytes)
3696 memcpy(vcpu->mmio_data, val, bytes);
3697 memcpy(vcpu->run->mmio.data, vcpu->mmio_data, 8);
3698 return X86EMUL_CONTINUE;
3701 static struct read_write_emulator_ops read_emultor = {
3702 .read_write_prepare = read_prepare,
3703 .read_write_emulate = read_emulate,
3704 .read_write_mmio = vcpu_mmio_read,
3705 .read_write_exit_mmio = read_exit_mmio,
3708 static struct read_write_emulator_ops write_emultor = {
3709 .read_write_emulate = write_emulate,
3710 .read_write_mmio = write_mmio,
3711 .read_write_exit_mmio = write_exit_mmio,
3715 static int emulator_read_write_onepage(unsigned long addr, void *val,
3717 struct x86_exception *exception,
3718 struct kvm_vcpu *vcpu,
3719 struct read_write_emulator_ops *ops)
3723 bool write = ops->write;
3725 if (ops->read_write_prepare &&
3726 ops->read_write_prepare(vcpu, val, bytes))
3727 return X86EMUL_CONTINUE;
3729 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
3732 return X86EMUL_PROPAGATE_FAULT;
3734 /* For APIC access vmexit */
3738 if (ops->read_write_emulate(vcpu, gpa, val, bytes))
3739 return X86EMUL_CONTINUE;
3743 * Is this MMIO handled locally?
3745 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
3746 if (handled == bytes)
3747 return X86EMUL_CONTINUE;
3753 vcpu->mmio_needed = 1;
3754 vcpu->run->exit_reason = KVM_EXIT_MMIO;
3755 vcpu->run->mmio.phys_addr = vcpu->mmio_phys_addr = gpa;
3756 vcpu->mmio_size = bytes;
3757 vcpu->run->mmio.len = min(vcpu->mmio_size, 8);
3758 vcpu->run->mmio.is_write = vcpu->mmio_is_write = write;
3759 vcpu->mmio_index = 0;
3761 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
3764 int emulator_read_write(struct x86_emulate_ctxt *ctxt, unsigned long addr,
3765 void *val, unsigned int bytes,
3766 struct x86_exception *exception,
3767 struct read_write_emulator_ops *ops)
3769 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3771 /* Crossing a page boundary? */
3772 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
3775 now = -addr & ~PAGE_MASK;
3776 rc = emulator_read_write_onepage(addr, val, now, exception,
3779 if (rc != X86EMUL_CONTINUE)
3786 return emulator_read_write_onepage(addr, val, bytes, exception,
3790 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
3794 struct x86_exception *exception)
3796 return emulator_read_write(ctxt, addr, val, bytes,
3797 exception, &read_emultor);
3800 int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
3804 struct x86_exception *exception)
3806 return emulator_read_write(ctxt, addr, (void *)val, bytes,
3807 exception, &write_emultor);
3810 #define CMPXCHG_TYPE(t, ptr, old, new) \
3811 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
3813 #ifdef CONFIG_X86_64
3814 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
3816 # define CMPXCHG64(ptr, old, new) \
3817 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
3820 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
3825 struct x86_exception *exception)
3827 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3833 /* guests cmpxchg8b have to be emulated atomically */
3834 if (bytes > 8 || (bytes & (bytes - 1)))
3837 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
3839 if (gpa == UNMAPPED_GVA ||
3840 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3843 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
3846 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
3847 if (is_error_page(page)) {
3848 kvm_release_page_clean(page);
3852 kaddr = kmap_atomic(page, KM_USER0);
3853 kaddr += offset_in_page(gpa);
3856 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
3859 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
3862 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
3865 exchanged = CMPXCHG64(kaddr, old, new);
3870 kunmap_atomic(kaddr, KM_USER0);
3871 kvm_release_page_dirty(page);
3874 return X86EMUL_CMPXCHG_FAILED;
3876 kvm_mmu_pte_write(vcpu, gpa, new, bytes);
3878 return X86EMUL_CONTINUE;
3881 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
3883 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
3886 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
3888 /* TODO: String I/O for in kernel device */
3891 if (vcpu->arch.pio.in)
3892 r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
3893 vcpu->arch.pio.size, pd);
3895 r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
3896 vcpu->arch.pio.port, vcpu->arch.pio.size,
3901 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
3902 unsigned short port, void *val,
3903 unsigned int count, bool in)
3905 trace_kvm_pio(!in, port, size, count);
3907 vcpu->arch.pio.port = port;
3908 vcpu->arch.pio.in = in;
3909 vcpu->arch.pio.count = count;
3910 vcpu->arch.pio.size = size;
3912 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
3913 vcpu->arch.pio.count = 0;
3917 vcpu->run->exit_reason = KVM_EXIT_IO;
3918 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
3919 vcpu->run->io.size = size;
3920 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
3921 vcpu->run->io.count = count;
3922 vcpu->run->io.port = port;
3927 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
3928 int size, unsigned short port, void *val,
3931 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3934 if (vcpu->arch.pio.count)
3937 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
3940 memcpy(val, vcpu->arch.pio_data, size * count);
3941 vcpu->arch.pio.count = 0;
3948 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
3949 int size, unsigned short port,
3950 const void *val, unsigned int count)
3952 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3954 memcpy(vcpu->arch.pio_data, val, size * count);
3955 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
3958 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
3960 return kvm_x86_ops->get_segment_base(vcpu, seg);
3963 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
3965 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
3968 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
3970 if (!need_emulate_wbinvd(vcpu))
3971 return X86EMUL_CONTINUE;
3973 if (kvm_x86_ops->has_wbinvd_exit()) {
3974 int cpu = get_cpu();
3976 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3977 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
3978 wbinvd_ipi, NULL, 1);
3980 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
3983 return X86EMUL_CONTINUE;
3985 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
3987 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
3989 kvm_emulate_wbinvd(emul_to_vcpu(ctxt));
3992 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
3994 return _kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
3997 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
4000 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
4003 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
4005 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
4008 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
4010 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4011 unsigned long value;
4015 value = kvm_read_cr0(vcpu);
4018 value = vcpu->arch.cr2;
4021 value = kvm_read_cr3(vcpu);
4024 value = kvm_read_cr4(vcpu);
4027 value = kvm_get_cr8(vcpu);
4030 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
4037 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
4039 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4044 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4047 vcpu->arch.cr2 = val;
4050 res = kvm_set_cr3(vcpu, val);
4053 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4056 res = kvm_set_cr8(vcpu, val);
4059 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
4066 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
4068 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
4071 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4073 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
4076 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4078 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
4081 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4083 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4086 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4088 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4091 static unsigned long emulator_get_cached_segment_base(
4092 struct x86_emulate_ctxt *ctxt, int seg)
4094 return get_segment_base(emul_to_vcpu(ctxt), seg);
4097 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4098 struct desc_struct *desc, u32 *base3,
4101 struct kvm_segment var;
4103 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
4104 *selector = var.selector;
4111 set_desc_limit(desc, var.limit);
4112 set_desc_base(desc, (unsigned long)var.base);
4113 #ifdef CONFIG_X86_64
4115 *base3 = var.base >> 32;
4117 desc->type = var.type;
4119 desc->dpl = var.dpl;
4120 desc->p = var.present;
4121 desc->avl = var.avl;
4129 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
4130 struct desc_struct *desc, u32 base3,
4133 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4134 struct kvm_segment var;
4136 var.selector = selector;
4137 var.base = get_desc_base(desc);
4138 #ifdef CONFIG_X86_64
4139 var.base |= ((u64)base3) << 32;
4141 var.limit = get_desc_limit(desc);
4143 var.limit = (var.limit << 12) | 0xfff;
4144 var.type = desc->type;
4145 var.present = desc->p;
4146 var.dpl = desc->dpl;
4151 var.avl = desc->avl;
4152 var.present = desc->p;
4153 var.unusable = !var.present;
4156 kvm_set_segment(vcpu, &var, seg);
4160 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
4161 u32 msr_index, u64 *pdata)
4163 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
4166 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
4167 u32 msr_index, u64 data)
4169 return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
4172 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
4173 u32 pmc, u64 *pdata)
4175 return kvm_pmu_read_pmc(emul_to_vcpu(ctxt), pmc, pdata);
4178 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
4180 emul_to_vcpu(ctxt)->arch.halt_request = 1;
4183 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
4186 kvm_load_guest_fpu(emul_to_vcpu(ctxt));
4188 * CR0.TS may reference the host fpu state, not the guest fpu state,
4189 * so it may be clear at this point.
4194 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
4199 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
4200 struct x86_instruction_info *info,
4201 enum x86_intercept_stage stage)
4203 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
4206 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
4207 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
4209 struct kvm_cpuid_entry2 *cpuid = NULL;
4212 cpuid = kvm_find_cpuid_entry(emul_to_vcpu(ctxt),
4228 static struct x86_emulate_ops emulate_ops = {
4229 .read_std = kvm_read_guest_virt_system,
4230 .write_std = kvm_write_guest_virt_system,
4231 .fetch = kvm_fetch_guest_virt,
4232 .read_emulated = emulator_read_emulated,
4233 .write_emulated = emulator_write_emulated,
4234 .cmpxchg_emulated = emulator_cmpxchg_emulated,
4235 .invlpg = emulator_invlpg,
4236 .pio_in_emulated = emulator_pio_in_emulated,
4237 .pio_out_emulated = emulator_pio_out_emulated,
4238 .get_segment = emulator_get_segment,
4239 .set_segment = emulator_set_segment,
4240 .get_cached_segment_base = emulator_get_cached_segment_base,
4241 .get_gdt = emulator_get_gdt,
4242 .get_idt = emulator_get_idt,
4243 .set_gdt = emulator_set_gdt,
4244 .set_idt = emulator_set_idt,
4245 .get_cr = emulator_get_cr,
4246 .set_cr = emulator_set_cr,
4247 .cpl = emulator_get_cpl,
4248 .get_dr = emulator_get_dr,
4249 .set_dr = emulator_set_dr,
4250 .set_msr = emulator_set_msr,
4251 .get_msr = emulator_get_msr,
4252 .read_pmc = emulator_read_pmc,
4253 .halt = emulator_halt,
4254 .wbinvd = emulator_wbinvd,
4255 .fix_hypercall = emulator_fix_hypercall,
4256 .get_fpu = emulator_get_fpu,
4257 .put_fpu = emulator_put_fpu,
4258 .intercept = emulator_intercept,
4259 .get_cpuid = emulator_get_cpuid,
4262 static void cache_all_regs(struct kvm_vcpu *vcpu)
4264 kvm_register_read(vcpu, VCPU_REGS_RAX);
4265 kvm_register_read(vcpu, VCPU_REGS_RSP);
4266 kvm_register_read(vcpu, VCPU_REGS_RIP);
4267 vcpu->arch.regs_dirty = ~0;
4270 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
4272 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu, mask);
4274 * an sti; sti; sequence only disable interrupts for the first
4275 * instruction. So, if the last instruction, be it emulated or
4276 * not, left the system with the INT_STI flag enabled, it
4277 * means that the last instruction is an sti. We should not
4278 * leave the flag on in this case. The same goes for mov ss
4280 if (!(int_shadow & mask))
4281 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
4284 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
4286 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4287 if (ctxt->exception.vector == PF_VECTOR)
4288 kvm_propagate_fault(vcpu, &ctxt->exception);
4289 else if (ctxt->exception.error_code_valid)
4290 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
4291 ctxt->exception.error_code);
4293 kvm_queue_exception(vcpu, ctxt->exception.vector);
4296 static void init_decode_cache(struct x86_emulate_ctxt *ctxt,
4297 const unsigned long *regs)
4299 memset(&ctxt->twobyte, 0,
4300 (void *)&ctxt->regs - (void *)&ctxt->twobyte);
4301 memcpy(ctxt->regs, regs, sizeof(ctxt->regs));
4303 ctxt->fetch.start = 0;
4304 ctxt->fetch.end = 0;
4305 ctxt->io_read.pos = 0;
4306 ctxt->io_read.end = 0;
4307 ctxt->mem_read.pos = 0;
4308 ctxt->mem_read.end = 0;
4311 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
4313 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4317 * TODO: fix emulate.c to use guest_read/write_register
4318 * instead of direct ->regs accesses, can save hundred cycles
4319 * on Intel for instructions that don't read/change RSP, for
4322 cache_all_regs(vcpu);
4324 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4326 ctxt->eflags = kvm_get_rflags(vcpu);
4327 ctxt->eip = kvm_rip_read(vcpu);
4328 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
4329 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
4330 cs_l ? X86EMUL_MODE_PROT64 :
4331 cs_db ? X86EMUL_MODE_PROT32 :
4332 X86EMUL_MODE_PROT16;
4333 ctxt->guest_mode = is_guest_mode(vcpu);
4335 init_decode_cache(ctxt, vcpu->arch.regs);
4336 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
4339 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
4341 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4344 init_emulate_ctxt(vcpu);
4348 ctxt->_eip = ctxt->eip + inc_eip;
4349 ret = emulate_int_real(ctxt, irq);
4351 if (ret != X86EMUL_CONTINUE)
4352 return EMULATE_FAIL;
4354 ctxt->eip = ctxt->_eip;
4355 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
4356 kvm_rip_write(vcpu, ctxt->eip);
4357 kvm_set_rflags(vcpu, ctxt->eflags);
4359 if (irq == NMI_VECTOR)
4360 vcpu->arch.nmi_pending = 0;
4362 vcpu->arch.interrupt.pending = false;
4364 return EMULATE_DONE;
4366 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
4368 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
4370 int r = EMULATE_DONE;
4372 ++vcpu->stat.insn_emulation_fail;
4373 trace_kvm_emulate_insn_failed(vcpu);
4374 if (!is_guest_mode(vcpu)) {
4375 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4376 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
4377 vcpu->run->internal.ndata = 0;
4380 kvm_queue_exception(vcpu, UD_VECTOR);
4385 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t gva)
4393 * if emulation was due to access to shadowed page table
4394 * and it failed try to unshadow page and re-entetr the
4395 * guest to let CPU execute the instruction.
4397 if (kvm_mmu_unprotect_page_virt(vcpu, gva))
4400 gpa = kvm_mmu_gva_to_gpa_system(vcpu, gva, NULL);
4402 if (gpa == UNMAPPED_GVA)
4403 return true; /* let cpu generate fault */
4405 if (!kvm_is_error_hva(gfn_to_hva(vcpu->kvm, gpa >> PAGE_SHIFT)))
4411 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
4412 unsigned long cr2, int emulation_type)
4414 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4415 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
4417 last_retry_eip = vcpu->arch.last_retry_eip;
4418 last_retry_addr = vcpu->arch.last_retry_addr;
4421 * If the emulation is caused by #PF and it is non-page_table
4422 * writing instruction, it means the VM-EXIT is caused by shadow
4423 * page protected, we can zap the shadow page and retry this
4424 * instruction directly.
4426 * Note: if the guest uses a non-page-table modifying instruction
4427 * on the PDE that points to the instruction, then we will unmap
4428 * the instruction and go to an infinite loop. So, we cache the
4429 * last retried eip and the last fault address, if we meet the eip
4430 * and the address again, we can break out of the potential infinite
4433 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
4435 if (!(emulation_type & EMULTYPE_RETRY))
4438 if (x86_page_table_writing_insn(ctxt))
4441 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
4444 vcpu->arch.last_retry_eip = ctxt->eip;
4445 vcpu->arch.last_retry_addr = cr2;
4447 if (!vcpu->arch.mmu.direct_map)
4448 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
4450 kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
4455 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
4462 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4463 bool writeback = true;
4465 kvm_clear_exception_queue(vcpu);
4467 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
4468 init_emulate_ctxt(vcpu);
4469 ctxt->interruptibility = 0;
4470 ctxt->have_exception = false;
4471 ctxt->perm_ok = false;
4473 ctxt->only_vendor_specific_insn
4474 = emulation_type & EMULTYPE_TRAP_UD;
4476 r = x86_decode_insn(ctxt, insn, insn_len);
4478 trace_kvm_emulate_insn_start(vcpu);
4479 ++vcpu->stat.insn_emulation;
4480 if (r != EMULATION_OK) {
4481 if (emulation_type & EMULTYPE_TRAP_UD)
4482 return EMULATE_FAIL;
4483 if (reexecute_instruction(vcpu, cr2))
4484 return EMULATE_DONE;
4485 if (emulation_type & EMULTYPE_SKIP)
4486 return EMULATE_FAIL;
4487 return handle_emulation_failure(vcpu);
4491 if (emulation_type & EMULTYPE_SKIP) {
4492 kvm_rip_write(vcpu, ctxt->_eip);
4493 return EMULATE_DONE;
4496 if (retry_instruction(ctxt, cr2, emulation_type))
4497 return EMULATE_DONE;
4499 /* this is needed for vmware backdoor interface to work since it
4500 changes registers values during IO operation */
4501 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
4502 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
4503 memcpy(ctxt->regs, vcpu->arch.regs, sizeof ctxt->regs);
4507 r = x86_emulate_insn(ctxt);
4509 if (r == EMULATION_INTERCEPTED)
4510 return EMULATE_DONE;
4512 if (r == EMULATION_FAILED) {
4513 if (reexecute_instruction(vcpu, cr2))
4514 return EMULATE_DONE;
4516 return handle_emulation_failure(vcpu);
4519 if (ctxt->have_exception) {
4520 inject_emulated_exception(vcpu);
4522 } else if (vcpu->arch.pio.count) {
4523 if (!vcpu->arch.pio.in)
4524 vcpu->arch.pio.count = 0;
4527 r = EMULATE_DO_MMIO;
4528 } else if (vcpu->mmio_needed) {
4529 if (!vcpu->mmio_is_write)
4531 r = EMULATE_DO_MMIO;
4532 } else if (r == EMULATION_RESTART)
4538 toggle_interruptibility(vcpu, ctxt->interruptibility);
4539 kvm_set_rflags(vcpu, ctxt->eflags);
4540 kvm_make_request(KVM_REQ_EVENT, vcpu);
4541 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
4542 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
4543 kvm_rip_write(vcpu, ctxt->eip);
4545 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
4549 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
4551 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
4553 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
4554 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
4555 size, port, &val, 1);
4556 /* do not return to emulator after return from userspace */
4557 vcpu->arch.pio.count = 0;
4560 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
4562 static void tsc_bad(void *info)
4564 __this_cpu_write(cpu_tsc_khz, 0);
4567 static void tsc_khz_changed(void *data)
4569 struct cpufreq_freqs *freq = data;
4570 unsigned long khz = 0;
4574 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
4575 khz = cpufreq_quick_get(raw_smp_processor_id());
4578 __this_cpu_write(cpu_tsc_khz, khz);
4581 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
4584 struct cpufreq_freqs *freq = data;
4586 struct kvm_vcpu *vcpu;
4587 int i, send_ipi = 0;
4590 * We allow guests to temporarily run on slowing clocks,
4591 * provided we notify them after, or to run on accelerating
4592 * clocks, provided we notify them before. Thus time never
4595 * However, we have a problem. We can't atomically update
4596 * the frequency of a given CPU from this function; it is
4597 * merely a notifier, which can be called from any CPU.
4598 * Changing the TSC frequency at arbitrary points in time
4599 * requires a recomputation of local variables related to
4600 * the TSC for each VCPU. We must flag these local variables
4601 * to be updated and be sure the update takes place with the
4602 * new frequency before any guests proceed.
4604 * Unfortunately, the combination of hotplug CPU and frequency
4605 * change creates an intractable locking scenario; the order
4606 * of when these callouts happen is undefined with respect to
4607 * CPU hotplug, and they can race with each other. As such,
4608 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
4609 * undefined; you can actually have a CPU frequency change take
4610 * place in between the computation of X and the setting of the
4611 * variable. To protect against this problem, all updates of
4612 * the per_cpu tsc_khz variable are done in an interrupt
4613 * protected IPI, and all callers wishing to update the value
4614 * must wait for a synchronous IPI to complete (which is trivial
4615 * if the caller is on the CPU already). This establishes the
4616 * necessary total order on variable updates.
4618 * Note that because a guest time update may take place
4619 * anytime after the setting of the VCPU's request bit, the
4620 * correct TSC value must be set before the request. However,
4621 * to ensure the update actually makes it to any guest which
4622 * starts running in hardware virtualization between the set
4623 * and the acquisition of the spinlock, we must also ping the
4624 * CPU after setting the request bit.
4628 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
4630 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
4633 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
4635 raw_spin_lock(&kvm_lock);
4636 list_for_each_entry(kvm, &vm_list, vm_list) {
4637 kvm_for_each_vcpu(i, vcpu, kvm) {
4638 if (vcpu->cpu != freq->cpu)
4640 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4641 if (vcpu->cpu != smp_processor_id())
4645 raw_spin_unlock(&kvm_lock);
4647 if (freq->old < freq->new && send_ipi) {
4649 * We upscale the frequency. Must make the guest
4650 * doesn't see old kvmclock values while running with
4651 * the new frequency, otherwise we risk the guest sees
4652 * time go backwards.
4654 * In case we update the frequency for another cpu
4655 * (which might be in guest context) send an interrupt
4656 * to kick the cpu out of guest context. Next time
4657 * guest context is entered kvmclock will be updated,
4658 * so the guest will not see stale values.
4660 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
4665 static struct notifier_block kvmclock_cpufreq_notifier_block = {
4666 .notifier_call = kvmclock_cpufreq_notifier
4669 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
4670 unsigned long action, void *hcpu)
4672 unsigned int cpu = (unsigned long)hcpu;
4676 case CPU_DOWN_FAILED:
4677 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
4679 case CPU_DOWN_PREPARE:
4680 smp_call_function_single(cpu, tsc_bad, NULL, 1);
4686 static struct notifier_block kvmclock_cpu_notifier_block = {
4687 .notifier_call = kvmclock_cpu_notifier,
4688 .priority = -INT_MAX
4691 static void kvm_timer_init(void)
4695 max_tsc_khz = tsc_khz;
4696 register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
4697 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
4698 #ifdef CONFIG_CPU_FREQ
4699 struct cpufreq_policy policy;
4700 memset(&policy, 0, sizeof(policy));
4702 cpufreq_get_policy(&policy, cpu);
4703 if (policy.cpuinfo.max_freq)
4704 max_tsc_khz = policy.cpuinfo.max_freq;
4707 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
4708 CPUFREQ_TRANSITION_NOTIFIER);
4710 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
4711 for_each_online_cpu(cpu)
4712 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
4715 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
4717 int kvm_is_in_guest(void)
4719 return __this_cpu_read(current_vcpu) != NULL;
4722 static int kvm_is_user_mode(void)
4726 if (__this_cpu_read(current_vcpu))
4727 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
4729 return user_mode != 0;
4732 static unsigned long kvm_get_guest_ip(void)
4734 unsigned long ip = 0;
4736 if (__this_cpu_read(current_vcpu))
4737 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
4742 static struct perf_guest_info_callbacks kvm_guest_cbs = {
4743 .is_in_guest = kvm_is_in_guest,
4744 .is_user_mode = kvm_is_user_mode,
4745 .get_guest_ip = kvm_get_guest_ip,
4748 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
4750 __this_cpu_write(current_vcpu, vcpu);
4752 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
4754 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
4756 __this_cpu_write(current_vcpu, NULL);
4758 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
4760 static void kvm_set_mmio_spte_mask(void)
4763 int maxphyaddr = boot_cpu_data.x86_phys_bits;
4766 * Set the reserved bits and the present bit of an paging-structure
4767 * entry to generate page fault with PFER.RSV = 1.
4769 mask = ((1ull << (62 - maxphyaddr + 1)) - 1) << maxphyaddr;
4772 #ifdef CONFIG_X86_64
4774 * If reserved bit is not supported, clear the present bit to disable
4777 if (maxphyaddr == 52)
4781 kvm_mmu_set_mmio_spte_mask(mask);
4784 int kvm_arch_init(void *opaque)
4787 struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
4790 printk(KERN_ERR "kvm: already loaded the other module\n");
4795 if (!ops->cpu_has_kvm_support()) {
4796 printk(KERN_ERR "kvm: no hardware support\n");
4800 if (ops->disabled_by_bios()) {
4801 printk(KERN_ERR "kvm: disabled by bios\n");
4806 r = kvm_mmu_module_init();
4810 kvm_set_mmio_spte_mask();
4811 kvm_init_msr_list();
4814 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
4815 PT_DIRTY_MASK, PT64_NX_MASK, 0);
4819 perf_register_guest_info_callbacks(&kvm_guest_cbs);
4822 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
4830 void kvm_arch_exit(void)
4832 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
4834 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
4835 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
4836 CPUFREQ_TRANSITION_NOTIFIER);
4837 unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
4839 kvm_mmu_module_exit();
4842 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
4844 ++vcpu->stat.halt_exits;
4845 if (irqchip_in_kernel(vcpu->kvm)) {
4846 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
4849 vcpu->run->exit_reason = KVM_EXIT_HLT;
4853 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
4855 int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
4857 u64 param, ingpa, outgpa, ret;
4858 uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
4859 bool fast, longmode;
4863 * hypercall generates UD from non zero cpl and real mode
4866 if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
4867 kvm_queue_exception(vcpu, UD_VECTOR);
4871 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4872 longmode = is_long_mode(vcpu) && cs_l == 1;
4875 param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
4876 (kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
4877 ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
4878 (kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
4879 outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
4880 (kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
4882 #ifdef CONFIG_X86_64
4884 param = kvm_register_read(vcpu, VCPU_REGS_RCX);
4885 ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
4886 outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
4890 code = param & 0xffff;
4891 fast = (param >> 16) & 0x1;
4892 rep_cnt = (param >> 32) & 0xfff;
4893 rep_idx = (param >> 48) & 0xfff;
4895 trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
4898 case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
4899 kvm_vcpu_on_spin(vcpu);
4902 res = HV_STATUS_INVALID_HYPERCALL_CODE;
4906 ret = res | (((u64)rep_done & 0xfff) << 32);
4908 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
4910 kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
4911 kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
4917 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
4919 unsigned long nr, a0, a1, a2, a3, ret;
4922 if (kvm_hv_hypercall_enabled(vcpu->kvm))
4923 return kvm_hv_hypercall(vcpu);
4925 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
4926 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
4927 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
4928 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
4929 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
4931 trace_kvm_hypercall(nr, a0, a1, a2, a3);
4933 if (!is_long_mode(vcpu)) {
4941 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
4947 case KVM_HC_VAPIC_POLL_IRQ:
4955 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
4956 ++vcpu->stat.hypercalls;
4959 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
4961 int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
4963 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4964 char instruction[3];
4965 unsigned long rip = kvm_rip_read(vcpu);
4968 * Blow out the MMU to ensure that no other VCPU has an active mapping
4969 * to ensure that the updated hypercall appears atomically across all
4972 kvm_mmu_zap_all(vcpu->kvm);
4974 kvm_x86_ops->patch_hypercall(vcpu, instruction);
4976 return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
4980 * Check if userspace requested an interrupt window, and that the
4981 * interrupt window is open.
4983 * No need to exit to userspace if we already have an interrupt queued.
4985 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
4987 return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
4988 vcpu->run->request_interrupt_window &&
4989 kvm_arch_interrupt_allowed(vcpu));
4992 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
4994 struct kvm_run *kvm_run = vcpu->run;
4996 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
4997 kvm_run->cr8 = kvm_get_cr8(vcpu);
4998 kvm_run->apic_base = kvm_get_apic_base(vcpu);
4999 if (irqchip_in_kernel(vcpu->kvm))
5000 kvm_run->ready_for_interrupt_injection = 1;
5002 kvm_run->ready_for_interrupt_injection =
5003 kvm_arch_interrupt_allowed(vcpu) &&
5004 !kvm_cpu_has_interrupt(vcpu) &&
5005 !kvm_event_needs_reinjection(vcpu);
5008 static void vapic_enter(struct kvm_vcpu *vcpu)
5010 struct kvm_lapic *apic = vcpu->arch.apic;
5013 if (!apic || !apic->vapic_addr)
5016 page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
5018 vcpu->arch.apic->vapic_page = page;
5021 static void vapic_exit(struct kvm_vcpu *vcpu)
5023 struct kvm_lapic *apic = vcpu->arch.apic;
5026 if (!apic || !apic->vapic_addr)
5029 idx = srcu_read_lock(&vcpu->kvm->srcu);
5030 kvm_release_page_dirty(apic->vapic_page);
5031 mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
5032 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5035 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
5039 if (!kvm_x86_ops->update_cr8_intercept)
5042 if (!vcpu->arch.apic)
5045 if (!vcpu->arch.apic->vapic_addr)
5046 max_irr = kvm_lapic_find_highest_irr(vcpu);
5053 tpr = kvm_lapic_get_cr8(vcpu);
5055 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
5058 static void inject_pending_event(struct kvm_vcpu *vcpu)
5060 /* try to reinject previous events if any */
5061 if (vcpu->arch.exception.pending) {
5062 trace_kvm_inj_exception(vcpu->arch.exception.nr,
5063 vcpu->arch.exception.has_error_code,
5064 vcpu->arch.exception.error_code);
5065 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
5066 vcpu->arch.exception.has_error_code,
5067 vcpu->arch.exception.error_code,
5068 vcpu->arch.exception.reinject);
5072 if (vcpu->arch.nmi_injected) {
5073 kvm_x86_ops->set_nmi(vcpu);
5077 if (vcpu->arch.interrupt.pending) {
5078 kvm_x86_ops->set_irq(vcpu);
5082 /* try to inject new event if pending */
5083 if (vcpu->arch.nmi_pending) {
5084 if (kvm_x86_ops->nmi_allowed(vcpu)) {
5085 --vcpu->arch.nmi_pending;
5086 vcpu->arch.nmi_injected = true;
5087 kvm_x86_ops->set_nmi(vcpu);
5089 } else if (kvm_cpu_has_interrupt(vcpu)) {
5090 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
5091 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
5093 kvm_x86_ops->set_irq(vcpu);
5098 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
5100 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
5101 !vcpu->guest_xcr0_loaded) {
5102 /* kvm_set_xcr() also depends on this */
5103 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
5104 vcpu->guest_xcr0_loaded = 1;
5108 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
5110 if (vcpu->guest_xcr0_loaded) {
5111 if (vcpu->arch.xcr0 != host_xcr0)
5112 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
5113 vcpu->guest_xcr0_loaded = 0;
5117 static void process_nmi(struct kvm_vcpu *vcpu)
5122 * x86 is limited to one NMI running, and one NMI pending after it.
5123 * If an NMI is already in progress, limit further NMIs to just one.
5124 * Otherwise, allow two (and we'll inject the first one immediately).
5126 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
5129 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
5130 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
5131 kvm_make_request(KVM_REQ_EVENT, vcpu);
5134 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
5137 bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
5138 vcpu->run->request_interrupt_window;
5139 bool req_immediate_exit = 0;
5141 if (vcpu->requests) {
5142 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
5143 kvm_mmu_unload(vcpu);
5144 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
5145 __kvm_migrate_timers(vcpu);
5146 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
5147 r = kvm_guest_time_update(vcpu);
5151 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
5152 kvm_mmu_sync_roots(vcpu);
5153 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
5154 kvm_x86_ops->tlb_flush(vcpu);
5155 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
5156 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
5160 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
5161 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5165 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
5166 vcpu->fpu_active = 0;
5167 kvm_x86_ops->fpu_deactivate(vcpu);
5169 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
5170 /* Page is swapped out. Do synthetic halt */
5171 vcpu->arch.apf.halted = true;
5175 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
5176 record_steal_time(vcpu);
5177 if (kvm_check_request(KVM_REQ_NMI, vcpu))
5179 req_immediate_exit =
5180 kvm_check_request(KVM_REQ_IMMEDIATE_EXIT, vcpu);
5181 if (kvm_check_request(KVM_REQ_PMU, vcpu))
5182 kvm_handle_pmu_event(vcpu);
5183 if (kvm_check_request(KVM_REQ_PMI, vcpu))
5184 kvm_deliver_pmi(vcpu);
5187 r = kvm_mmu_reload(vcpu);
5191 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
5192 inject_pending_event(vcpu);
5194 /* enable NMI/IRQ window open exits if needed */
5195 if (vcpu->arch.nmi_pending)
5196 kvm_x86_ops->enable_nmi_window(vcpu);
5197 else if (kvm_cpu_has_interrupt(vcpu) || req_int_win)
5198 kvm_x86_ops->enable_irq_window(vcpu);
5200 if (kvm_lapic_enabled(vcpu)) {
5201 update_cr8_intercept(vcpu);
5202 kvm_lapic_sync_to_vapic(vcpu);
5208 kvm_x86_ops->prepare_guest_switch(vcpu);
5209 if (vcpu->fpu_active)
5210 kvm_load_guest_fpu(vcpu);
5211 kvm_load_guest_xcr0(vcpu);
5213 vcpu->mode = IN_GUEST_MODE;
5215 /* We should set ->mode before check ->requests,
5216 * see the comment in make_all_cpus_request.
5220 local_irq_disable();
5222 if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
5223 || need_resched() || signal_pending(current)) {
5224 vcpu->mode = OUTSIDE_GUEST_MODE;
5228 kvm_x86_ops->cancel_injection(vcpu);
5233 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
5235 if (req_immediate_exit)
5236 smp_send_reschedule(vcpu->cpu);
5240 if (unlikely(vcpu->arch.switch_db_regs)) {
5242 set_debugreg(vcpu->arch.eff_db[0], 0);
5243 set_debugreg(vcpu->arch.eff_db[1], 1);
5244 set_debugreg(vcpu->arch.eff_db[2], 2);
5245 set_debugreg(vcpu->arch.eff_db[3], 3);
5248 trace_kvm_entry(vcpu->vcpu_id);
5249 kvm_x86_ops->run(vcpu);
5252 * If the guest has used debug registers, at least dr7
5253 * will be disabled while returning to the host.
5254 * If we don't have active breakpoints in the host, we don't
5255 * care about the messed up debug address registers. But if
5256 * we have some of them active, restore the old state.
5258 if (hw_breakpoint_active())
5259 hw_breakpoint_restore();
5261 vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu);
5263 vcpu->mode = OUTSIDE_GUEST_MODE;
5270 * We must have an instruction between local_irq_enable() and
5271 * kvm_guest_exit(), so the timer interrupt isn't delayed by
5272 * the interrupt shadow. The stat.exits increment will do nicely.
5273 * But we need to prevent reordering, hence this barrier():
5281 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
5284 * Profile KVM exit RIPs:
5286 if (unlikely(prof_on == KVM_PROFILING)) {
5287 unsigned long rip = kvm_rip_read(vcpu);
5288 profile_hit(KVM_PROFILING, (void *)rip);
5292 kvm_lapic_sync_from_vapic(vcpu);
5294 r = kvm_x86_ops->handle_exit(vcpu);
5300 static int __vcpu_run(struct kvm_vcpu *vcpu)
5303 struct kvm *kvm = vcpu->kvm;
5305 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
5306 pr_debug("vcpu %d received sipi with vector # %x\n",
5307 vcpu->vcpu_id, vcpu->arch.sipi_vector);
5308 kvm_lapic_reset(vcpu);
5309 r = kvm_arch_vcpu_reset(vcpu);
5312 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5315 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
5320 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
5321 !vcpu->arch.apf.halted)
5322 r = vcpu_enter_guest(vcpu);
5324 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5325 kvm_vcpu_block(vcpu);
5326 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
5327 if (kvm_check_request(KVM_REQ_UNHALT, vcpu))
5329 switch(vcpu->arch.mp_state) {
5330 case KVM_MP_STATE_HALTED:
5331 vcpu->arch.mp_state =
5332 KVM_MP_STATE_RUNNABLE;
5333 case KVM_MP_STATE_RUNNABLE:
5334 vcpu->arch.apf.halted = false;
5336 case KVM_MP_STATE_SIPI_RECEIVED:
5347 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
5348 if (kvm_cpu_has_pending_timer(vcpu))
5349 kvm_inject_pending_timer_irqs(vcpu);
5351 if (dm_request_for_irq_injection(vcpu)) {
5353 vcpu->run->exit_reason = KVM_EXIT_INTR;
5354 ++vcpu->stat.request_irq_exits;
5357 kvm_check_async_pf_completion(vcpu);
5359 if (signal_pending(current)) {
5361 vcpu->run->exit_reason = KVM_EXIT_INTR;
5362 ++vcpu->stat.signal_exits;
5364 if (need_resched()) {
5365 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5367 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
5371 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5378 static int complete_mmio(struct kvm_vcpu *vcpu)
5380 struct kvm_run *run = vcpu->run;
5383 if (!(vcpu->arch.pio.count || vcpu->mmio_needed))
5386 if (vcpu->mmio_needed) {
5387 vcpu->mmio_needed = 0;
5388 if (!vcpu->mmio_is_write)
5389 memcpy(vcpu->mmio_data + vcpu->mmio_index,
5391 vcpu->mmio_index += 8;
5392 if (vcpu->mmio_index < vcpu->mmio_size) {
5393 run->exit_reason = KVM_EXIT_MMIO;
5394 run->mmio.phys_addr = vcpu->mmio_phys_addr + vcpu->mmio_index;
5395 memcpy(run->mmio.data, vcpu->mmio_data + vcpu->mmio_index, 8);
5396 run->mmio.len = min(vcpu->mmio_size - vcpu->mmio_index, 8);
5397 run->mmio.is_write = vcpu->mmio_is_write;
5398 vcpu->mmio_needed = 1;
5401 if (vcpu->mmio_is_write)
5403 vcpu->mmio_read_completed = 1;
5405 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
5406 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
5407 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
5408 if (r != EMULATE_DONE)
5413 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
5418 if (!tsk_used_math(current) && init_fpu(current))
5421 if (vcpu->sigset_active)
5422 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
5424 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
5425 kvm_vcpu_block(vcpu);
5426 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
5431 /* re-sync apic's tpr */
5432 if (!irqchip_in_kernel(vcpu->kvm)) {
5433 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
5439 r = complete_mmio(vcpu);
5443 r = __vcpu_run(vcpu);
5446 post_kvm_run_save(vcpu);
5447 if (vcpu->sigset_active)
5448 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
5453 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
5455 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
5457 * We are here if userspace calls get_regs() in the middle of
5458 * instruction emulation. Registers state needs to be copied
5459 * back from emulation context to vcpu. Usrapace shouldn't do
5460 * that usually, but some bad designed PV devices (vmware
5461 * backdoor interface) need this to work
5463 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5464 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
5465 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5467 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
5468 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
5469 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
5470 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
5471 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
5472 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
5473 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
5474 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
5475 #ifdef CONFIG_X86_64
5476 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
5477 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
5478 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
5479 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
5480 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
5481 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
5482 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
5483 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
5486 regs->rip = kvm_rip_read(vcpu);
5487 regs->rflags = kvm_get_rflags(vcpu);
5492 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
5494 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
5495 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5497 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
5498 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
5499 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
5500 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
5501 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
5502 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
5503 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
5504 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
5505 #ifdef CONFIG_X86_64
5506 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
5507 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
5508 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
5509 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
5510 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
5511 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
5512 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
5513 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
5516 kvm_rip_write(vcpu, regs->rip);
5517 kvm_set_rflags(vcpu, regs->rflags);
5519 vcpu->arch.exception.pending = false;
5521 kvm_make_request(KVM_REQ_EVENT, vcpu);
5526 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
5528 struct kvm_segment cs;
5530 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
5534 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
5536 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
5537 struct kvm_sregs *sregs)
5541 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
5542 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
5543 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
5544 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
5545 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
5546 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
5548 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
5549 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
5551 kvm_x86_ops->get_idt(vcpu, &dt);
5552 sregs->idt.limit = dt.size;
5553 sregs->idt.base = dt.address;
5554 kvm_x86_ops->get_gdt(vcpu, &dt);
5555 sregs->gdt.limit = dt.size;
5556 sregs->gdt.base = dt.address;
5558 sregs->cr0 = kvm_read_cr0(vcpu);
5559 sregs->cr2 = vcpu->arch.cr2;
5560 sregs->cr3 = kvm_read_cr3(vcpu);
5561 sregs->cr4 = kvm_read_cr4(vcpu);
5562 sregs->cr8 = kvm_get_cr8(vcpu);
5563 sregs->efer = vcpu->arch.efer;
5564 sregs->apic_base = kvm_get_apic_base(vcpu);
5566 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
5568 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
5569 set_bit(vcpu->arch.interrupt.nr,
5570 (unsigned long *)sregs->interrupt_bitmap);
5575 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
5576 struct kvm_mp_state *mp_state)
5578 mp_state->mp_state = vcpu->arch.mp_state;
5582 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
5583 struct kvm_mp_state *mp_state)
5585 vcpu->arch.mp_state = mp_state->mp_state;
5586 kvm_make_request(KVM_REQ_EVENT, vcpu);
5590 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason,
5591 bool has_error_code, u32 error_code)
5593 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5596 init_emulate_ctxt(vcpu);
5598 ret = emulator_task_switch(ctxt, tss_selector, reason,
5599 has_error_code, error_code);
5602 return EMULATE_FAIL;
5604 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
5605 kvm_rip_write(vcpu, ctxt->eip);
5606 kvm_set_rflags(vcpu, ctxt->eflags);
5607 kvm_make_request(KVM_REQ_EVENT, vcpu);
5608 return EMULATE_DONE;
5610 EXPORT_SYMBOL_GPL(kvm_task_switch);
5612 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
5613 struct kvm_sregs *sregs)
5615 int mmu_reset_needed = 0;
5616 int pending_vec, max_bits, idx;
5619 dt.size = sregs->idt.limit;
5620 dt.address = sregs->idt.base;
5621 kvm_x86_ops->set_idt(vcpu, &dt);
5622 dt.size = sregs->gdt.limit;
5623 dt.address = sregs->gdt.base;
5624 kvm_x86_ops->set_gdt(vcpu, &dt);
5626 vcpu->arch.cr2 = sregs->cr2;
5627 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
5628 vcpu->arch.cr3 = sregs->cr3;
5629 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
5631 kvm_set_cr8(vcpu, sregs->cr8);
5633 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
5634 kvm_x86_ops->set_efer(vcpu, sregs->efer);
5635 kvm_set_apic_base(vcpu, sregs->apic_base);
5637 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
5638 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
5639 vcpu->arch.cr0 = sregs->cr0;
5641 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
5642 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
5643 if (sregs->cr4 & X86_CR4_OSXSAVE)
5644 kvm_update_cpuid(vcpu);
5646 idx = srcu_read_lock(&vcpu->kvm->srcu);
5647 if (!is_long_mode(vcpu) && is_pae(vcpu)) {
5648 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
5649 mmu_reset_needed = 1;
5651 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5653 if (mmu_reset_needed)
5654 kvm_mmu_reset_context(vcpu);
5656 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
5657 pending_vec = find_first_bit(
5658 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
5659 if (pending_vec < max_bits) {
5660 kvm_queue_interrupt(vcpu, pending_vec, false);
5661 pr_debug("Set back pending irq %d\n", pending_vec);
5664 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
5665 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
5666 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
5667 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
5668 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
5669 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
5671 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
5672 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
5674 update_cr8_intercept(vcpu);
5676 /* Older userspace won't unhalt the vcpu on reset. */
5677 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
5678 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
5680 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5682 kvm_make_request(KVM_REQ_EVENT, vcpu);
5687 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
5688 struct kvm_guest_debug *dbg)
5690 unsigned long rflags;
5693 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
5695 if (vcpu->arch.exception.pending)
5697 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
5698 kvm_queue_exception(vcpu, DB_VECTOR);
5700 kvm_queue_exception(vcpu, BP_VECTOR);
5704 * Read rflags as long as potentially injected trace flags are still
5707 rflags = kvm_get_rflags(vcpu);
5709 vcpu->guest_debug = dbg->control;
5710 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
5711 vcpu->guest_debug = 0;
5713 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5714 for (i = 0; i < KVM_NR_DB_REGS; ++i)
5715 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
5716 vcpu->arch.switch_db_regs =
5717 (dbg->arch.debugreg[7] & DR7_BP_EN_MASK);
5719 for (i = 0; i < KVM_NR_DB_REGS; i++)
5720 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
5721 vcpu->arch.switch_db_regs = (vcpu->arch.dr7 & DR7_BP_EN_MASK);
5724 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
5725 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
5726 get_segment_base(vcpu, VCPU_SREG_CS);
5729 * Trigger an rflags update that will inject or remove the trace
5732 kvm_set_rflags(vcpu, rflags);
5734 kvm_x86_ops->set_guest_debug(vcpu, dbg);
5744 * Translate a guest virtual address to a guest physical address.
5746 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
5747 struct kvm_translation *tr)
5749 unsigned long vaddr = tr->linear_address;
5753 idx = srcu_read_lock(&vcpu->kvm->srcu);
5754 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
5755 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5756 tr->physical_address = gpa;
5757 tr->valid = gpa != UNMAPPED_GVA;
5764 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
5766 struct i387_fxsave_struct *fxsave =
5767 &vcpu->arch.guest_fpu.state->fxsave;
5769 memcpy(fpu->fpr, fxsave->st_space, 128);
5770 fpu->fcw = fxsave->cwd;
5771 fpu->fsw = fxsave->swd;
5772 fpu->ftwx = fxsave->twd;
5773 fpu->last_opcode = fxsave->fop;
5774 fpu->last_ip = fxsave->rip;
5775 fpu->last_dp = fxsave->rdp;
5776 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
5781 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
5783 struct i387_fxsave_struct *fxsave =
5784 &vcpu->arch.guest_fpu.state->fxsave;
5786 memcpy(fxsave->st_space, fpu->fpr, 128);
5787 fxsave->cwd = fpu->fcw;
5788 fxsave->swd = fpu->fsw;
5789 fxsave->twd = fpu->ftwx;
5790 fxsave->fop = fpu->last_opcode;
5791 fxsave->rip = fpu->last_ip;
5792 fxsave->rdp = fpu->last_dp;
5793 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
5798 int fx_init(struct kvm_vcpu *vcpu)
5802 err = fpu_alloc(&vcpu->arch.guest_fpu);
5806 fpu_finit(&vcpu->arch.guest_fpu);
5809 * Ensure guest xcr0 is valid for loading
5811 vcpu->arch.xcr0 = XSTATE_FP;
5813 vcpu->arch.cr0 |= X86_CR0_ET;
5817 EXPORT_SYMBOL_GPL(fx_init);
5819 static void fx_free(struct kvm_vcpu *vcpu)
5821 fpu_free(&vcpu->arch.guest_fpu);
5824 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
5826 if (vcpu->guest_fpu_loaded)
5830 * Restore all possible states in the guest,
5831 * and assume host would use all available bits.
5832 * Guest xcr0 would be loaded later.
5834 kvm_put_guest_xcr0(vcpu);
5835 vcpu->guest_fpu_loaded = 1;
5836 unlazy_fpu(current);
5837 fpu_restore_checking(&vcpu->arch.guest_fpu);
5841 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
5843 kvm_put_guest_xcr0(vcpu);
5845 if (!vcpu->guest_fpu_loaded)
5848 vcpu->guest_fpu_loaded = 0;
5849 fpu_save_init(&vcpu->arch.guest_fpu);
5850 ++vcpu->stat.fpu_reload;
5851 kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
5855 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
5857 kvmclock_reset(vcpu);
5859 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
5861 kvm_x86_ops->vcpu_free(vcpu);
5864 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
5867 if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
5868 printk_once(KERN_WARNING
5869 "kvm: SMP vm created on host with unstable TSC; "
5870 "guest TSC will not be reliable\n");
5871 return kvm_x86_ops->vcpu_create(kvm, id);
5874 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
5878 vcpu->arch.mtrr_state.have_fixed = 1;
5880 r = kvm_arch_vcpu_reset(vcpu);
5882 r = kvm_mmu_setup(vcpu);
5888 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
5890 vcpu->arch.apf.msr_val = 0;
5893 kvm_mmu_unload(vcpu);
5897 kvm_x86_ops->vcpu_free(vcpu);
5900 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
5902 atomic_set(&vcpu->arch.nmi_queued, 0);
5903 vcpu->arch.nmi_pending = 0;
5904 vcpu->arch.nmi_injected = false;
5906 vcpu->arch.switch_db_regs = 0;
5907 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
5908 vcpu->arch.dr6 = DR6_FIXED_1;
5909 vcpu->arch.dr7 = DR7_FIXED_1;
5911 kvm_make_request(KVM_REQ_EVENT, vcpu);
5912 vcpu->arch.apf.msr_val = 0;
5913 vcpu->arch.st.msr_val = 0;
5915 kvmclock_reset(vcpu);
5917 kvm_clear_async_pf_completion_queue(vcpu);
5918 kvm_async_pf_hash_reset(vcpu);
5919 vcpu->arch.apf.halted = false;
5921 kvm_pmu_reset(vcpu);
5923 return kvm_x86_ops->vcpu_reset(vcpu);
5926 int kvm_arch_hardware_enable(void *garbage)
5929 struct kvm_vcpu *vcpu;
5932 kvm_shared_msr_cpu_online();
5933 list_for_each_entry(kvm, &vm_list, vm_list)
5934 kvm_for_each_vcpu(i, vcpu, kvm)
5935 if (vcpu->cpu == smp_processor_id())
5936 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5937 return kvm_x86_ops->hardware_enable(garbage);
5940 void kvm_arch_hardware_disable(void *garbage)
5942 kvm_x86_ops->hardware_disable(garbage);
5943 drop_user_return_notifiers(garbage);
5946 int kvm_arch_hardware_setup(void)
5948 return kvm_x86_ops->hardware_setup();
5951 void kvm_arch_hardware_unsetup(void)
5953 kvm_x86_ops->hardware_unsetup();
5956 void kvm_arch_check_processor_compat(void *rtn)
5958 kvm_x86_ops->check_processor_compatibility(rtn);
5961 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
5967 BUG_ON(vcpu->kvm == NULL);
5970 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
5971 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
5972 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5974 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
5976 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
5981 vcpu->arch.pio_data = page_address(page);
5983 kvm_init_tsc_catchup(vcpu, max_tsc_khz);
5985 r = kvm_mmu_create(vcpu);
5987 goto fail_free_pio_data;
5989 if (irqchip_in_kernel(kvm)) {
5990 r = kvm_create_lapic(vcpu);
5992 goto fail_mmu_destroy;
5995 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
5997 if (!vcpu->arch.mce_banks) {
5999 goto fail_free_lapic;
6001 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
6003 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL))
6004 goto fail_free_mce_banks;
6006 kvm_async_pf_hash_reset(vcpu);
6010 fail_free_mce_banks:
6011 kfree(vcpu->arch.mce_banks);
6013 kvm_free_lapic(vcpu);
6015 kvm_mmu_destroy(vcpu);
6017 free_page((unsigned long)vcpu->arch.pio_data);
6022 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
6026 kvm_pmu_destroy(vcpu);
6027 kfree(vcpu->arch.mce_banks);
6028 kvm_free_lapic(vcpu);
6029 idx = srcu_read_lock(&vcpu->kvm->srcu);
6030 kvm_mmu_destroy(vcpu);
6031 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6032 free_page((unsigned long)vcpu->arch.pio_data);
6035 int kvm_arch_init_vm(struct kvm *kvm)
6037 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6038 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
6040 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
6041 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
6043 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
6048 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
6051 kvm_mmu_unload(vcpu);
6055 static void kvm_free_vcpus(struct kvm *kvm)
6058 struct kvm_vcpu *vcpu;
6061 * Unpin any mmu pages first.
6063 kvm_for_each_vcpu(i, vcpu, kvm) {
6064 kvm_clear_async_pf_completion_queue(vcpu);
6065 kvm_unload_vcpu_mmu(vcpu);
6067 kvm_for_each_vcpu(i, vcpu, kvm)
6068 kvm_arch_vcpu_free(vcpu);
6070 mutex_lock(&kvm->lock);
6071 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
6072 kvm->vcpus[i] = NULL;
6074 atomic_set(&kvm->online_vcpus, 0);
6075 mutex_unlock(&kvm->lock);
6078 void kvm_arch_sync_events(struct kvm *kvm)
6080 kvm_free_all_assigned_devices(kvm);
6084 void kvm_arch_destroy_vm(struct kvm *kvm)
6086 kvm_iommu_unmap_guest(kvm);
6087 kfree(kvm->arch.vpic);
6088 kfree(kvm->arch.vioapic);
6089 kvm_free_vcpus(kvm);
6090 if (kvm->arch.apic_access_page)
6091 put_page(kvm->arch.apic_access_page);
6092 if (kvm->arch.ept_identity_pagetable)
6093 put_page(kvm->arch.ept_identity_pagetable);
6096 int kvm_arch_prepare_memory_region(struct kvm *kvm,
6097 struct kvm_memory_slot *memslot,
6098 struct kvm_memory_slot old,
6099 struct kvm_userspace_memory_region *mem,
6102 int npages = memslot->npages;
6103 int map_flags = MAP_PRIVATE | MAP_ANONYMOUS;
6105 /* Prevent internal slot pages from being moved by fork()/COW. */
6106 if (memslot->id >= KVM_MEMORY_SLOTS)
6107 map_flags = MAP_SHARED | MAP_ANONYMOUS;
6109 /*To keep backward compatibility with older userspace,
6110 *x86 needs to hanlde !user_alloc case.
6113 if (npages && !old.rmap) {
6114 unsigned long userspace_addr;
6116 down_write(¤t->mm->mmap_sem);
6117 userspace_addr = do_mmap(NULL, 0,
6119 PROT_READ | PROT_WRITE,
6122 up_write(¤t->mm->mmap_sem);
6124 if (IS_ERR((void *)userspace_addr))
6125 return PTR_ERR((void *)userspace_addr);
6127 memslot->userspace_addr = userspace_addr;
6135 void kvm_arch_commit_memory_region(struct kvm *kvm,
6136 struct kvm_userspace_memory_region *mem,
6137 struct kvm_memory_slot old,
6141 int nr_mmu_pages = 0, npages = mem->memory_size >> PAGE_SHIFT;
6143 if (!user_alloc && !old.user_alloc && old.rmap && !npages) {
6146 down_write(¤t->mm->mmap_sem);
6147 ret = do_munmap(current->mm, old.userspace_addr,
6148 old.npages * PAGE_SIZE);
6149 up_write(¤t->mm->mmap_sem);
6152 "kvm_vm_ioctl_set_memory_region: "
6153 "failed to munmap memory\n");
6156 if (!kvm->arch.n_requested_mmu_pages)
6157 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
6159 spin_lock(&kvm->mmu_lock);
6161 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
6162 kvm_mmu_slot_remove_write_access(kvm, mem->slot);
6163 spin_unlock(&kvm->mmu_lock);
6166 void kvm_arch_flush_shadow(struct kvm *kvm)
6168 kvm_mmu_zap_all(kvm);
6169 kvm_reload_remote_mmus(kvm);
6172 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
6174 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6175 !vcpu->arch.apf.halted)
6176 || !list_empty_careful(&vcpu->async_pf.done)
6177 || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
6178 || atomic_read(&vcpu->arch.nmi_queued) ||
6179 (kvm_arch_interrupt_allowed(vcpu) &&
6180 kvm_cpu_has_interrupt(vcpu));
6183 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
6186 int cpu = vcpu->cpu;
6188 if (waitqueue_active(&vcpu->wq)) {
6189 wake_up_interruptible(&vcpu->wq);
6190 ++vcpu->stat.halt_wakeup;
6194 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
6195 if (kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE)
6196 smp_send_reschedule(cpu);
6200 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
6202 return kvm_x86_ops->interrupt_allowed(vcpu);
6205 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
6207 unsigned long current_rip = kvm_rip_read(vcpu) +
6208 get_segment_base(vcpu, VCPU_SREG_CS);
6210 return current_rip == linear_rip;
6212 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
6214 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
6216 unsigned long rflags;
6218 rflags = kvm_x86_ops->get_rflags(vcpu);
6219 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6220 rflags &= ~X86_EFLAGS_TF;
6223 EXPORT_SYMBOL_GPL(kvm_get_rflags);
6225 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
6227 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
6228 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
6229 rflags |= X86_EFLAGS_TF;
6230 kvm_x86_ops->set_rflags(vcpu, rflags);
6231 kvm_make_request(KVM_REQ_EVENT, vcpu);
6233 EXPORT_SYMBOL_GPL(kvm_set_rflags);
6235 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
6239 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
6240 is_error_page(work->page))
6243 r = kvm_mmu_reload(vcpu);
6247 if (!vcpu->arch.mmu.direct_map &&
6248 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
6251 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
6254 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
6256 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
6259 static inline u32 kvm_async_pf_next_probe(u32 key)
6261 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
6264 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6266 u32 key = kvm_async_pf_hash_fn(gfn);
6268 while (vcpu->arch.apf.gfns[key] != ~0)
6269 key = kvm_async_pf_next_probe(key);
6271 vcpu->arch.apf.gfns[key] = gfn;
6274 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
6277 u32 key = kvm_async_pf_hash_fn(gfn);
6279 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
6280 (vcpu->arch.apf.gfns[key] != gfn &&
6281 vcpu->arch.apf.gfns[key] != ~0); i++)
6282 key = kvm_async_pf_next_probe(key);
6287 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6289 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
6292 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6296 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
6298 vcpu->arch.apf.gfns[i] = ~0;
6300 j = kvm_async_pf_next_probe(j);
6301 if (vcpu->arch.apf.gfns[j] == ~0)
6303 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
6305 * k lies cyclically in ]i,j]
6307 * |....j i.k.| or |.k..j i...|
6309 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
6310 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
6315 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
6318 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
6322 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
6323 struct kvm_async_pf *work)
6325 struct x86_exception fault;
6327 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
6328 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
6330 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
6331 (vcpu->arch.apf.send_user_only &&
6332 kvm_x86_ops->get_cpl(vcpu) == 0))
6333 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
6334 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
6335 fault.vector = PF_VECTOR;
6336 fault.error_code_valid = true;
6337 fault.error_code = 0;
6338 fault.nested_page_fault = false;
6339 fault.address = work->arch.token;
6340 kvm_inject_page_fault(vcpu, &fault);
6344 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
6345 struct kvm_async_pf *work)
6347 struct x86_exception fault;
6349 trace_kvm_async_pf_ready(work->arch.token, work->gva);
6350 if (is_error_page(work->page))
6351 work->arch.token = ~0; /* broadcast wakeup */
6353 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
6355 if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
6356 !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
6357 fault.vector = PF_VECTOR;
6358 fault.error_code_valid = true;
6359 fault.error_code = 0;
6360 fault.nested_page_fault = false;
6361 fault.address = work->arch.token;
6362 kvm_inject_page_fault(vcpu, &fault);
6364 vcpu->arch.apf.halted = false;
6367 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
6369 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
6372 return !kvm_event_needs_reinjection(vcpu) &&
6373 kvm_x86_ops->interrupt_allowed(vcpu);
6376 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
6377 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
6378 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
6379 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
6380 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
6381 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
6382 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
6383 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
6384 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
6385 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
6386 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
6387 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);