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 <linux/timekeeper_internal.h>
50 #include <linux/pvclock_gtod.h>
51 #include <trace/events/kvm.h>
53 #define CREATE_TRACE_POINTS
56 #include <asm/debugreg.h>
62 #include <asm/fpu-internal.h> /* Ugh! */
64 #include <asm/pvclock.h>
65 #include <asm/div64.h>
67 #define MAX_IO_MSRS 256
68 #define KVM_MAX_MCE_BANKS 32
69 #define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
71 #define emul_to_vcpu(ctxt) \
72 container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
75 * - enable syscall per default because its emulated by KVM
76 * - enable LME and LMA per default on 64 bit KVM
80 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
82 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
85 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
86 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
88 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
89 static void process_nmi(struct kvm_vcpu *vcpu);
91 struct kvm_x86_ops *kvm_x86_ops;
92 EXPORT_SYMBOL_GPL(kvm_x86_ops);
94 static bool ignore_msrs = 0;
95 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
97 unsigned int min_timer_period_us = 500;
98 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
100 bool kvm_has_tsc_control;
101 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
102 u32 kvm_max_guest_tsc_khz;
103 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
105 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
106 static u32 tsc_tolerance_ppm = 250;
107 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
109 #define KVM_NR_SHARED_MSRS 16
111 struct kvm_shared_msrs_global {
113 u32 msrs[KVM_NR_SHARED_MSRS];
116 struct kvm_shared_msrs {
117 struct user_return_notifier urn;
119 struct kvm_shared_msr_values {
122 } values[KVM_NR_SHARED_MSRS];
125 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
126 static struct kvm_shared_msrs __percpu *shared_msrs;
128 struct kvm_stats_debugfs_item debugfs_entries[] = {
129 { "pf_fixed", VCPU_STAT(pf_fixed) },
130 { "pf_guest", VCPU_STAT(pf_guest) },
131 { "tlb_flush", VCPU_STAT(tlb_flush) },
132 { "invlpg", VCPU_STAT(invlpg) },
133 { "exits", VCPU_STAT(exits) },
134 { "io_exits", VCPU_STAT(io_exits) },
135 { "mmio_exits", VCPU_STAT(mmio_exits) },
136 { "signal_exits", VCPU_STAT(signal_exits) },
137 { "irq_window", VCPU_STAT(irq_window_exits) },
138 { "nmi_window", VCPU_STAT(nmi_window_exits) },
139 { "halt_exits", VCPU_STAT(halt_exits) },
140 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
141 { "hypercalls", VCPU_STAT(hypercalls) },
142 { "request_irq", VCPU_STAT(request_irq_exits) },
143 { "irq_exits", VCPU_STAT(irq_exits) },
144 { "host_state_reload", VCPU_STAT(host_state_reload) },
145 { "efer_reload", VCPU_STAT(efer_reload) },
146 { "fpu_reload", VCPU_STAT(fpu_reload) },
147 { "insn_emulation", VCPU_STAT(insn_emulation) },
148 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
149 { "irq_injections", VCPU_STAT(irq_injections) },
150 { "nmi_injections", VCPU_STAT(nmi_injections) },
151 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
152 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
153 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
154 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
155 { "mmu_flooded", VM_STAT(mmu_flooded) },
156 { "mmu_recycled", VM_STAT(mmu_recycled) },
157 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
158 { "mmu_unsync", VM_STAT(mmu_unsync) },
159 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
160 { "largepages", VM_STAT(lpages) },
164 u64 __read_mostly host_xcr0;
166 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
168 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
171 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
172 vcpu->arch.apf.gfns[i] = ~0;
175 static void kvm_on_user_return(struct user_return_notifier *urn)
178 struct kvm_shared_msrs *locals
179 = container_of(urn, struct kvm_shared_msrs, urn);
180 struct kvm_shared_msr_values *values;
182 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
183 values = &locals->values[slot];
184 if (values->host != values->curr) {
185 wrmsrl(shared_msrs_global.msrs[slot], values->host);
186 values->curr = values->host;
189 locals->registered = false;
190 user_return_notifier_unregister(urn);
193 static void shared_msr_update(unsigned slot, u32 msr)
196 unsigned int cpu = smp_processor_id();
197 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
199 /* only read, and nobody should modify it at this time,
200 * so don't need lock */
201 if (slot >= shared_msrs_global.nr) {
202 printk(KERN_ERR "kvm: invalid MSR slot!");
205 rdmsrl_safe(msr, &value);
206 smsr->values[slot].host = value;
207 smsr->values[slot].curr = value;
210 void kvm_define_shared_msr(unsigned slot, u32 msr)
212 if (slot >= shared_msrs_global.nr)
213 shared_msrs_global.nr = slot + 1;
214 shared_msrs_global.msrs[slot] = msr;
215 /* we need ensured the shared_msr_global have been updated */
218 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
220 static void kvm_shared_msr_cpu_online(void)
224 for (i = 0; i < shared_msrs_global.nr; ++i)
225 shared_msr_update(i, shared_msrs_global.msrs[i]);
228 void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
230 unsigned int cpu = smp_processor_id();
231 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
233 if (((value ^ smsr->values[slot].curr) & mask) == 0)
235 smsr->values[slot].curr = value;
236 wrmsrl(shared_msrs_global.msrs[slot], value);
237 if (!smsr->registered) {
238 smsr->urn.on_user_return = kvm_on_user_return;
239 user_return_notifier_register(&smsr->urn);
240 smsr->registered = true;
243 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
245 static void drop_user_return_notifiers(void *ignore)
247 unsigned int cpu = smp_processor_id();
248 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
250 if (smsr->registered)
251 kvm_on_user_return(&smsr->urn);
254 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
256 return vcpu->arch.apic_base;
258 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
260 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
262 /* TODO: reserve bits check */
263 kvm_lapic_set_base(vcpu, data);
265 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
267 asmlinkage void kvm_spurious_fault(void)
269 /* Fault while not rebooting. We want the trace. */
272 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
274 #define EXCPT_BENIGN 0
275 #define EXCPT_CONTRIBUTORY 1
278 static int exception_class(int vector)
288 return EXCPT_CONTRIBUTORY;
295 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
296 unsigned nr, bool has_error, u32 error_code,
302 kvm_make_request(KVM_REQ_EVENT, vcpu);
304 if (!vcpu->arch.exception.pending) {
306 vcpu->arch.exception.pending = true;
307 vcpu->arch.exception.has_error_code = has_error;
308 vcpu->arch.exception.nr = nr;
309 vcpu->arch.exception.error_code = error_code;
310 vcpu->arch.exception.reinject = reinject;
314 /* to check exception */
315 prev_nr = vcpu->arch.exception.nr;
316 if (prev_nr == DF_VECTOR) {
317 /* triple fault -> shutdown */
318 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
321 class1 = exception_class(prev_nr);
322 class2 = exception_class(nr);
323 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
324 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
325 /* generate double fault per SDM Table 5-5 */
326 vcpu->arch.exception.pending = true;
327 vcpu->arch.exception.has_error_code = true;
328 vcpu->arch.exception.nr = DF_VECTOR;
329 vcpu->arch.exception.error_code = 0;
331 /* replace previous exception with a new one in a hope
332 that instruction re-execution will regenerate lost
337 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
339 kvm_multiple_exception(vcpu, nr, false, 0, false);
341 EXPORT_SYMBOL_GPL(kvm_queue_exception);
343 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
345 kvm_multiple_exception(vcpu, nr, false, 0, true);
347 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
349 void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
352 kvm_inject_gp(vcpu, 0);
354 kvm_x86_ops->skip_emulated_instruction(vcpu);
356 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
358 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
360 ++vcpu->stat.pf_guest;
361 vcpu->arch.cr2 = fault->address;
362 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
364 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
366 void kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
368 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
369 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
371 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
374 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
376 atomic_inc(&vcpu->arch.nmi_queued);
377 kvm_make_request(KVM_REQ_NMI, vcpu);
379 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
381 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
383 kvm_multiple_exception(vcpu, nr, true, error_code, false);
385 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
387 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
389 kvm_multiple_exception(vcpu, nr, true, error_code, true);
391 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
394 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
395 * a #GP and return false.
397 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
399 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
401 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
404 EXPORT_SYMBOL_GPL(kvm_require_cpl);
407 * This function will be used to read from the physical memory of the currently
408 * running guest. The difference to kvm_read_guest_page is that this function
409 * can read from guest physical or from the guest's guest physical memory.
411 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
412 gfn_t ngfn, void *data, int offset, int len,
418 ngpa = gfn_to_gpa(ngfn);
419 real_gfn = mmu->translate_gpa(vcpu, ngpa, access);
420 if (real_gfn == UNMAPPED_GVA)
423 real_gfn = gpa_to_gfn(real_gfn);
425 return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
427 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
429 int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
430 void *data, int offset, int len, u32 access)
432 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
433 data, offset, len, access);
437 * Load the pae pdptrs. Return true is they are all valid.
439 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
441 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
442 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
445 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
447 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
448 offset * sizeof(u64), sizeof(pdpte),
449 PFERR_USER_MASK|PFERR_WRITE_MASK);
454 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
455 if (is_present_gpte(pdpte[i]) &&
456 (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
463 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
464 __set_bit(VCPU_EXREG_PDPTR,
465 (unsigned long *)&vcpu->arch.regs_avail);
466 __set_bit(VCPU_EXREG_PDPTR,
467 (unsigned long *)&vcpu->arch.regs_dirty);
472 EXPORT_SYMBOL_GPL(load_pdptrs);
474 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
476 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
482 if (is_long_mode(vcpu) || !is_pae(vcpu))
485 if (!test_bit(VCPU_EXREG_PDPTR,
486 (unsigned long *)&vcpu->arch.regs_avail))
489 gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
490 offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
491 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
492 PFERR_USER_MASK | PFERR_WRITE_MASK);
495 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
501 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
503 unsigned long old_cr0 = kvm_read_cr0(vcpu);
504 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
505 X86_CR0_CD | X86_CR0_NW;
510 if (cr0 & 0xffffffff00000000UL)
514 cr0 &= ~CR0_RESERVED_BITS;
516 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
519 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
522 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
524 if ((vcpu->arch.efer & EFER_LME)) {
529 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
534 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
539 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
542 kvm_x86_ops->set_cr0(vcpu, cr0);
544 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
545 kvm_clear_async_pf_completion_queue(vcpu);
546 kvm_async_pf_hash_reset(vcpu);
549 if ((cr0 ^ old_cr0) & update_bits)
550 kvm_mmu_reset_context(vcpu);
553 EXPORT_SYMBOL_GPL(kvm_set_cr0);
555 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
557 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
559 EXPORT_SYMBOL_GPL(kvm_lmsw);
561 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
563 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
564 !vcpu->guest_xcr0_loaded) {
565 /* kvm_set_xcr() also depends on this */
566 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
567 vcpu->guest_xcr0_loaded = 1;
571 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
573 if (vcpu->guest_xcr0_loaded) {
574 if (vcpu->arch.xcr0 != host_xcr0)
575 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
576 vcpu->guest_xcr0_loaded = 0;
580 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
585 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
586 if (index != XCR_XFEATURE_ENABLED_MASK)
589 if (!(xcr0 & XSTATE_FP))
591 if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
595 * Do not allow the guest to set bits that we do not support
596 * saving. However, xcr0 bit 0 is always set, even if the
597 * emulated CPU does not support XSAVE (see fx_init).
599 valid_bits = vcpu->arch.guest_supported_xcr0 | XSTATE_FP;
600 if (xcr0 & ~valid_bits)
603 kvm_put_guest_xcr0(vcpu);
604 vcpu->arch.xcr0 = xcr0;
608 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
610 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
611 __kvm_set_xcr(vcpu, index, xcr)) {
612 kvm_inject_gp(vcpu, 0);
617 EXPORT_SYMBOL_GPL(kvm_set_xcr);
619 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
621 unsigned long old_cr4 = kvm_read_cr4(vcpu);
622 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
623 X86_CR4_PAE | X86_CR4_SMEP;
624 if (cr4 & CR4_RESERVED_BITS)
627 if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
630 if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
633 if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_FSGSBASE))
636 if (is_long_mode(vcpu)) {
637 if (!(cr4 & X86_CR4_PAE))
639 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
640 && ((cr4 ^ old_cr4) & pdptr_bits)
641 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
645 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
646 if (!guest_cpuid_has_pcid(vcpu))
649 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
650 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
654 if (kvm_x86_ops->set_cr4(vcpu, cr4))
657 if (((cr4 ^ old_cr4) & pdptr_bits) ||
658 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
659 kvm_mmu_reset_context(vcpu);
661 if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
662 kvm_update_cpuid(vcpu);
666 EXPORT_SYMBOL_GPL(kvm_set_cr4);
668 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
670 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
671 kvm_mmu_sync_roots(vcpu);
672 kvm_mmu_flush_tlb(vcpu);
676 if (is_long_mode(vcpu)) {
677 if (kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE)) {
678 if (cr3 & CR3_PCID_ENABLED_RESERVED_BITS)
681 if (cr3 & CR3_L_MODE_RESERVED_BITS)
685 if (cr3 & CR3_PAE_RESERVED_BITS)
687 if (is_paging(vcpu) &&
688 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
692 * We don't check reserved bits in nonpae mode, because
693 * this isn't enforced, and VMware depends on this.
697 vcpu->arch.cr3 = cr3;
698 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
699 kvm_mmu_new_cr3(vcpu);
702 EXPORT_SYMBOL_GPL(kvm_set_cr3);
704 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
706 if (cr8 & CR8_RESERVED_BITS)
708 if (irqchip_in_kernel(vcpu->kvm))
709 kvm_lapic_set_tpr(vcpu, cr8);
711 vcpu->arch.cr8 = cr8;
714 EXPORT_SYMBOL_GPL(kvm_set_cr8);
716 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
718 if (irqchip_in_kernel(vcpu->kvm))
719 return kvm_lapic_get_cr8(vcpu);
721 return vcpu->arch.cr8;
723 EXPORT_SYMBOL_GPL(kvm_get_cr8);
725 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
729 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
730 dr7 = vcpu->arch.guest_debug_dr7;
732 dr7 = vcpu->arch.dr7;
733 kvm_x86_ops->set_dr7(vcpu, dr7);
734 vcpu->arch.switch_db_regs = (dr7 & DR7_BP_EN_MASK);
737 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
741 vcpu->arch.db[dr] = val;
742 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
743 vcpu->arch.eff_db[dr] = val;
746 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
750 if (val & 0xffffffff00000000ULL)
752 vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
755 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
759 if (val & 0xffffffff00000000ULL)
761 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
762 kvm_update_dr7(vcpu);
769 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
773 res = __kvm_set_dr(vcpu, dr, val);
775 kvm_queue_exception(vcpu, UD_VECTOR);
777 kvm_inject_gp(vcpu, 0);
781 EXPORT_SYMBOL_GPL(kvm_set_dr);
783 static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
787 *val = vcpu->arch.db[dr];
790 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
794 *val = vcpu->arch.dr6;
797 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
801 *val = vcpu->arch.dr7;
808 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
810 if (_kvm_get_dr(vcpu, dr, val)) {
811 kvm_queue_exception(vcpu, UD_VECTOR);
816 EXPORT_SYMBOL_GPL(kvm_get_dr);
818 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
820 u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
824 err = kvm_pmu_read_pmc(vcpu, ecx, &data);
827 kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
828 kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
831 EXPORT_SYMBOL_GPL(kvm_rdpmc);
834 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
835 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
837 * This list is modified at module load time to reflect the
838 * capabilities of the host cpu. This capabilities test skips MSRs that are
839 * kvm-specific. Those are put in the beginning of the list.
842 #define KVM_SAVE_MSRS_BEGIN 10
843 static u32 msrs_to_save[] = {
844 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
845 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
846 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
847 HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
849 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
852 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
854 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
855 MSR_IA32_FEATURE_CONTROL
858 static unsigned num_msrs_to_save;
860 static const u32 emulated_msrs[] = {
862 MSR_IA32_TSCDEADLINE,
863 MSR_IA32_MISC_ENABLE,
868 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
870 if (efer & efer_reserved_bits)
873 if (efer & EFER_FFXSR) {
874 struct kvm_cpuid_entry2 *feat;
876 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
877 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
881 if (efer & EFER_SVME) {
882 struct kvm_cpuid_entry2 *feat;
884 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
885 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
891 EXPORT_SYMBOL_GPL(kvm_valid_efer);
893 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
895 u64 old_efer = vcpu->arch.efer;
897 if (!kvm_valid_efer(vcpu, efer))
901 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
905 efer |= vcpu->arch.efer & EFER_LMA;
907 kvm_x86_ops->set_efer(vcpu, efer);
909 /* Update reserved bits */
910 if ((efer ^ old_efer) & EFER_NX)
911 kvm_mmu_reset_context(vcpu);
916 void kvm_enable_efer_bits(u64 mask)
918 efer_reserved_bits &= ~mask;
920 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
924 * Writes msr value into into the appropriate "register".
925 * Returns 0 on success, non-0 otherwise.
926 * Assumes vcpu_load() was already called.
928 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
930 return kvm_x86_ops->set_msr(vcpu, msr);
934 * Adapt set_msr() to msr_io()'s calling convention
936 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
942 msr.host_initiated = true;
943 return kvm_set_msr(vcpu, &msr);
947 struct pvclock_gtod_data {
950 struct { /* extract of a clocksource struct */
958 /* open coded 'struct timespec' */
959 u64 monotonic_time_snsec;
960 time_t monotonic_time_sec;
963 static struct pvclock_gtod_data pvclock_gtod_data;
965 static void update_pvclock_gtod(struct timekeeper *tk)
967 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
969 write_seqcount_begin(&vdata->seq);
971 /* copy pvclock gtod data */
972 vdata->clock.vclock_mode = tk->clock->archdata.vclock_mode;
973 vdata->clock.cycle_last = tk->clock->cycle_last;
974 vdata->clock.mask = tk->clock->mask;
975 vdata->clock.mult = tk->mult;
976 vdata->clock.shift = tk->shift;
978 vdata->monotonic_time_sec = tk->xtime_sec
979 + tk->wall_to_monotonic.tv_sec;
980 vdata->monotonic_time_snsec = tk->xtime_nsec
981 + (tk->wall_to_monotonic.tv_nsec
983 while (vdata->monotonic_time_snsec >=
984 (((u64)NSEC_PER_SEC) << tk->shift)) {
985 vdata->monotonic_time_snsec -=
986 ((u64)NSEC_PER_SEC) << tk->shift;
987 vdata->monotonic_time_sec++;
990 write_seqcount_end(&vdata->seq);
995 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
999 struct pvclock_wall_clock wc;
1000 struct timespec boot;
1005 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1010 ++version; /* first time write, random junk */
1014 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1017 * The guest calculates current wall clock time by adding
1018 * system time (updated by kvm_guest_time_update below) to the
1019 * wall clock specified here. guest system time equals host
1020 * system time for us, thus we must fill in host boot time here.
1024 if (kvm->arch.kvmclock_offset) {
1025 struct timespec ts = ns_to_timespec(kvm->arch.kvmclock_offset);
1026 boot = timespec_sub(boot, ts);
1028 wc.sec = boot.tv_sec;
1029 wc.nsec = boot.tv_nsec;
1030 wc.version = version;
1032 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1035 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1038 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1040 uint32_t quotient, remainder;
1042 /* Don't try to replace with do_div(), this one calculates
1043 * "(dividend << 32) / divisor" */
1045 : "=a" (quotient), "=d" (remainder)
1046 : "0" (0), "1" (dividend), "r" (divisor) );
1050 static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
1051 s8 *pshift, u32 *pmultiplier)
1058 tps64 = base_khz * 1000LL;
1059 scaled64 = scaled_khz * 1000LL;
1060 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1065 tps32 = (uint32_t)tps64;
1066 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1067 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1075 *pmultiplier = div_frac(scaled64, tps32);
1077 pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
1078 __func__, base_khz, scaled_khz, shift, *pmultiplier);
1081 static inline u64 get_kernel_ns(void)
1085 WARN_ON(preemptible());
1087 monotonic_to_bootbased(&ts);
1088 return timespec_to_ns(&ts);
1091 #ifdef CONFIG_X86_64
1092 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1095 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1096 unsigned long max_tsc_khz;
1098 static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
1100 return pvclock_scale_delta(nsec, vcpu->arch.virtual_tsc_mult,
1101 vcpu->arch.virtual_tsc_shift);
1104 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1106 u64 v = (u64)khz * (1000000 + ppm);
1111 static void kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
1113 u32 thresh_lo, thresh_hi;
1114 int use_scaling = 0;
1116 /* tsc_khz can be zero if TSC calibration fails */
1117 if (this_tsc_khz == 0)
1120 /* Compute a scale to convert nanoseconds in TSC cycles */
1121 kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
1122 &vcpu->arch.virtual_tsc_shift,
1123 &vcpu->arch.virtual_tsc_mult);
1124 vcpu->arch.virtual_tsc_khz = this_tsc_khz;
1127 * Compute the variation in TSC rate which is acceptable
1128 * within the range of tolerance and decide if the
1129 * rate being applied is within that bounds of the hardware
1130 * rate. If so, no scaling or compensation need be done.
1132 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1133 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1134 if (this_tsc_khz < thresh_lo || this_tsc_khz > thresh_hi) {
1135 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", this_tsc_khz, thresh_lo, thresh_hi);
1138 kvm_x86_ops->set_tsc_khz(vcpu, this_tsc_khz, use_scaling);
1141 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1143 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1144 vcpu->arch.virtual_tsc_mult,
1145 vcpu->arch.virtual_tsc_shift);
1146 tsc += vcpu->arch.this_tsc_write;
1150 void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1152 #ifdef CONFIG_X86_64
1154 bool do_request = false;
1155 struct kvm_arch *ka = &vcpu->kvm->arch;
1156 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1158 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1159 atomic_read(&vcpu->kvm->online_vcpus));
1161 if (vcpus_matched && gtod->clock.vclock_mode == VCLOCK_TSC)
1162 if (!ka->use_master_clock)
1165 if (!vcpus_matched && ka->use_master_clock)
1169 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1171 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1172 atomic_read(&vcpu->kvm->online_vcpus),
1173 ka->use_master_clock, gtod->clock.vclock_mode);
1177 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1179 u64 curr_offset = kvm_x86_ops->read_tsc_offset(vcpu);
1180 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1183 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1185 struct kvm *kvm = vcpu->kvm;
1186 u64 offset, ns, elapsed;
1187 unsigned long flags;
1190 u64 data = msr->data;
1192 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1193 offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
1194 ns = get_kernel_ns();
1195 elapsed = ns - kvm->arch.last_tsc_nsec;
1197 if (vcpu->arch.virtual_tsc_khz) {
1200 /* n.b - signed multiplication and division required */
1201 usdiff = data - kvm->arch.last_tsc_write;
1202 #ifdef CONFIG_X86_64
1203 usdiff = (usdiff * 1000) / vcpu->arch.virtual_tsc_khz;
1205 /* do_div() only does unsigned */
1206 asm("1: idivl %[divisor]\n"
1207 "2: xor %%edx, %%edx\n"
1208 " movl $0, %[faulted]\n"
1210 ".section .fixup,\"ax\"\n"
1211 "4: movl $1, %[faulted]\n"
1215 _ASM_EXTABLE(1b, 4b)
1217 : "=A"(usdiff), [faulted] "=r" (faulted)
1218 : "A"(usdiff * 1000), [divisor] "rm"(vcpu->arch.virtual_tsc_khz));
1221 do_div(elapsed, 1000);
1226 /* idivl overflow => difference is larger than USEC_PER_SEC */
1228 usdiff = USEC_PER_SEC;
1230 usdiff = USEC_PER_SEC; /* disable TSC match window below */
1233 * Special case: TSC write with a small delta (1 second) of virtual
1234 * cycle time against real time is interpreted as an attempt to
1235 * synchronize the CPU.
1237 * For a reliable TSC, we can match TSC offsets, and for an unstable
1238 * TSC, we add elapsed time in this computation. We could let the
1239 * compensation code attempt to catch up if we fall behind, but
1240 * it's better to try to match offsets from the beginning.
1242 if (usdiff < USEC_PER_SEC &&
1243 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1244 if (!check_tsc_unstable()) {
1245 offset = kvm->arch.cur_tsc_offset;
1246 pr_debug("kvm: matched tsc offset for %llu\n", data);
1248 u64 delta = nsec_to_cycles(vcpu, elapsed);
1250 offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
1251 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1256 * We split periods of matched TSC writes into generations.
1257 * For each generation, we track the original measured
1258 * nanosecond time, offset, and write, so if TSCs are in
1259 * sync, we can match exact offset, and if not, we can match
1260 * exact software computation in compute_guest_tsc()
1262 * These values are tracked in kvm->arch.cur_xxx variables.
1264 kvm->arch.cur_tsc_generation++;
1265 kvm->arch.cur_tsc_nsec = ns;
1266 kvm->arch.cur_tsc_write = data;
1267 kvm->arch.cur_tsc_offset = offset;
1269 pr_debug("kvm: new tsc generation %u, clock %llu\n",
1270 kvm->arch.cur_tsc_generation, data);
1274 * We also track th most recent recorded KHZ, write and time to
1275 * allow the matching interval to be extended at each write.
1277 kvm->arch.last_tsc_nsec = ns;
1278 kvm->arch.last_tsc_write = data;
1279 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1281 vcpu->arch.last_guest_tsc = data;
1283 /* Keep track of which generation this VCPU has synchronized to */
1284 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1285 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1286 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1288 if (guest_cpuid_has_tsc_adjust(vcpu) && !msr->host_initiated)
1289 update_ia32_tsc_adjust_msr(vcpu, offset);
1290 kvm_x86_ops->write_tsc_offset(vcpu, offset);
1291 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1293 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1295 kvm->arch.nr_vcpus_matched_tsc++;
1297 kvm->arch.nr_vcpus_matched_tsc = 0;
1299 kvm_track_tsc_matching(vcpu);
1300 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1303 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1305 #ifdef CONFIG_X86_64
1307 static cycle_t read_tsc(void)
1313 * Empirically, a fence (of type that depends on the CPU)
1314 * before rdtsc is enough to ensure that rdtsc is ordered
1315 * with respect to loads. The various CPU manuals are unclear
1316 * as to whether rdtsc can be reordered with later loads,
1317 * but no one has ever seen it happen.
1320 ret = (cycle_t)vget_cycles();
1322 last = pvclock_gtod_data.clock.cycle_last;
1324 if (likely(ret >= last))
1328 * GCC likes to generate cmov here, but this branch is extremely
1329 * predictable (it's just a funciton of time and the likely is
1330 * very likely) and there's a data dependence, so force GCC
1331 * to generate a branch instead. I don't barrier() because
1332 * we don't actually need a barrier, and if this function
1333 * ever gets inlined it will generate worse code.
1339 static inline u64 vgettsc(cycle_t *cycle_now)
1342 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1344 *cycle_now = read_tsc();
1346 v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
1347 return v * gtod->clock.mult;
1350 static int do_monotonic(struct timespec *ts, cycle_t *cycle_now)
1355 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1359 seq = read_seqcount_begin(>od->seq);
1360 mode = gtod->clock.vclock_mode;
1361 ts->tv_sec = gtod->monotonic_time_sec;
1362 ns = gtod->monotonic_time_snsec;
1363 ns += vgettsc(cycle_now);
1364 ns >>= gtod->clock.shift;
1365 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
1366 timespec_add_ns(ts, ns);
1371 /* returns true if host is using tsc clocksource */
1372 static bool kvm_get_time_and_clockread(s64 *kernel_ns, cycle_t *cycle_now)
1376 /* checked again under seqlock below */
1377 if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
1380 if (do_monotonic(&ts, cycle_now) != VCLOCK_TSC)
1383 monotonic_to_bootbased(&ts);
1384 *kernel_ns = timespec_to_ns(&ts);
1392 * Assuming a stable TSC across physical CPUS, and a stable TSC
1393 * across virtual CPUs, the following condition is possible.
1394 * Each numbered line represents an event visible to both
1395 * CPUs at the next numbered event.
1397 * "timespecX" represents host monotonic time. "tscX" represents
1400 * VCPU0 on CPU0 | VCPU1 on CPU1
1402 * 1. read timespec0,tsc0
1403 * 2. | timespec1 = timespec0 + N
1405 * 3. transition to guest | transition to guest
1406 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1407 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
1408 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1410 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1413 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1415 * - 0 < N - M => M < N
1417 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1418 * always the case (the difference between two distinct xtime instances
1419 * might be smaller then the difference between corresponding TSC reads,
1420 * when updating guest vcpus pvclock areas).
1422 * To avoid that problem, do not allow visibility of distinct
1423 * system_timestamp/tsc_timestamp values simultaneously: use a master
1424 * copy of host monotonic time values. Update that master copy
1427 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1431 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1433 #ifdef CONFIG_X86_64
1434 struct kvm_arch *ka = &kvm->arch;
1436 bool host_tsc_clocksource, vcpus_matched;
1438 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1439 atomic_read(&kvm->online_vcpus));
1442 * If the host uses TSC clock, then passthrough TSC as stable
1445 host_tsc_clocksource = kvm_get_time_and_clockread(
1446 &ka->master_kernel_ns,
1447 &ka->master_cycle_now);
1449 ka->use_master_clock = host_tsc_clocksource & vcpus_matched;
1451 if (ka->use_master_clock)
1452 atomic_set(&kvm_guest_has_master_clock, 1);
1454 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1455 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1460 static void kvm_gen_update_masterclock(struct kvm *kvm)
1462 #ifdef CONFIG_X86_64
1464 struct kvm_vcpu *vcpu;
1465 struct kvm_arch *ka = &kvm->arch;
1467 spin_lock(&ka->pvclock_gtod_sync_lock);
1468 kvm_make_mclock_inprogress_request(kvm);
1469 /* no guest entries from this point */
1470 pvclock_update_vm_gtod_copy(kvm);
1472 kvm_for_each_vcpu(i, vcpu, kvm)
1473 set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
1475 /* guest entries allowed */
1476 kvm_for_each_vcpu(i, vcpu, kvm)
1477 clear_bit(KVM_REQ_MCLOCK_INPROGRESS, &vcpu->requests);
1479 spin_unlock(&ka->pvclock_gtod_sync_lock);
1483 static int kvm_guest_time_update(struct kvm_vcpu *v)
1485 unsigned long flags, this_tsc_khz;
1486 struct kvm_vcpu_arch *vcpu = &v->arch;
1487 struct kvm_arch *ka = &v->kvm->arch;
1489 u64 tsc_timestamp, host_tsc;
1490 struct pvclock_vcpu_time_info guest_hv_clock;
1492 bool use_master_clock;
1498 * If the host uses TSC clock, then passthrough TSC as stable
1501 spin_lock(&ka->pvclock_gtod_sync_lock);
1502 use_master_clock = ka->use_master_clock;
1503 if (use_master_clock) {
1504 host_tsc = ka->master_cycle_now;
1505 kernel_ns = ka->master_kernel_ns;
1507 spin_unlock(&ka->pvclock_gtod_sync_lock);
1509 /* Keep irq disabled to prevent changes to the clock */
1510 local_irq_save(flags);
1511 this_tsc_khz = __get_cpu_var(cpu_tsc_khz);
1512 if (unlikely(this_tsc_khz == 0)) {
1513 local_irq_restore(flags);
1514 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1517 if (!use_master_clock) {
1518 host_tsc = native_read_tsc();
1519 kernel_ns = get_kernel_ns();
1522 tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc);
1525 * We may have to catch up the TSC to match elapsed wall clock
1526 * time for two reasons, even if kvmclock is used.
1527 * 1) CPU could have been running below the maximum TSC rate
1528 * 2) Broken TSC compensation resets the base at each VCPU
1529 * entry to avoid unknown leaps of TSC even when running
1530 * again on the same CPU. This may cause apparent elapsed
1531 * time to disappear, and the guest to stand still or run
1534 if (vcpu->tsc_catchup) {
1535 u64 tsc = compute_guest_tsc(v, kernel_ns);
1536 if (tsc > tsc_timestamp) {
1537 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
1538 tsc_timestamp = tsc;
1542 local_irq_restore(flags);
1544 if (!vcpu->pv_time_enabled)
1547 if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
1548 kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
1549 &vcpu->hv_clock.tsc_shift,
1550 &vcpu->hv_clock.tsc_to_system_mul);
1551 vcpu->hw_tsc_khz = this_tsc_khz;
1554 /* With all the info we got, fill in the values */
1555 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1556 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1557 vcpu->last_kernel_ns = kernel_ns;
1558 vcpu->last_guest_tsc = tsc_timestamp;
1561 * The interface expects us to write an even number signaling that the
1562 * update is finished. Since the guest won't see the intermediate
1563 * state, we just increase by 2 at the end.
1565 vcpu->hv_clock.version += 2;
1567 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
1568 &guest_hv_clock, sizeof(guest_hv_clock))))
1571 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
1572 pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
1574 if (vcpu->pvclock_set_guest_stopped_request) {
1575 pvclock_flags |= PVCLOCK_GUEST_STOPPED;
1576 vcpu->pvclock_set_guest_stopped_request = false;
1579 /* If the host uses TSC clocksource, then it is stable */
1580 if (use_master_clock)
1581 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
1583 vcpu->hv_clock.flags = pvclock_flags;
1585 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1587 sizeof(vcpu->hv_clock));
1592 * kvmclock updates which are isolated to a given vcpu, such as
1593 * vcpu->cpu migration, should not allow system_timestamp from
1594 * the rest of the vcpus to remain static. Otherwise ntp frequency
1595 * correction applies to one vcpu's system_timestamp but not
1598 * So in those cases, request a kvmclock update for all vcpus.
1599 * The worst case for a remote vcpu to update its kvmclock
1600 * is then bounded by maximum nohz sleep latency.
1603 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
1606 struct kvm *kvm = v->kvm;
1607 struct kvm_vcpu *vcpu;
1609 kvm_for_each_vcpu(i, vcpu, kvm) {
1610 set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
1611 kvm_vcpu_kick(vcpu);
1615 static bool msr_mtrr_valid(unsigned msr)
1618 case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
1619 case MSR_MTRRfix64K_00000:
1620 case MSR_MTRRfix16K_80000:
1621 case MSR_MTRRfix16K_A0000:
1622 case MSR_MTRRfix4K_C0000:
1623 case MSR_MTRRfix4K_C8000:
1624 case MSR_MTRRfix4K_D0000:
1625 case MSR_MTRRfix4K_D8000:
1626 case MSR_MTRRfix4K_E0000:
1627 case MSR_MTRRfix4K_E8000:
1628 case MSR_MTRRfix4K_F0000:
1629 case MSR_MTRRfix4K_F8000:
1630 case MSR_MTRRdefType:
1631 case MSR_IA32_CR_PAT:
1639 static bool valid_pat_type(unsigned t)
1641 return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
1644 static bool valid_mtrr_type(unsigned t)
1646 return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
1649 static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1653 if (!msr_mtrr_valid(msr))
1656 if (msr == MSR_IA32_CR_PAT) {
1657 for (i = 0; i < 8; i++)
1658 if (!valid_pat_type((data >> (i * 8)) & 0xff))
1661 } else if (msr == MSR_MTRRdefType) {
1664 return valid_mtrr_type(data & 0xff);
1665 } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
1666 for (i = 0; i < 8 ; i++)
1667 if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
1672 /* variable MTRRs */
1673 return valid_mtrr_type(data & 0xff);
1676 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1678 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1680 if (!mtrr_valid(vcpu, msr, data))
1683 if (msr == MSR_MTRRdefType) {
1684 vcpu->arch.mtrr_state.def_type = data;
1685 vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
1686 } else if (msr == MSR_MTRRfix64K_00000)
1688 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1689 p[1 + msr - MSR_MTRRfix16K_80000] = data;
1690 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1691 p[3 + msr - MSR_MTRRfix4K_C0000] = data;
1692 else if (msr == MSR_IA32_CR_PAT)
1693 vcpu->arch.pat = data;
1694 else { /* Variable MTRRs */
1695 int idx, is_mtrr_mask;
1698 idx = (msr - 0x200) / 2;
1699 is_mtrr_mask = msr - 0x200 - 2 * idx;
1702 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1705 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1709 kvm_mmu_reset_context(vcpu);
1713 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1715 u64 mcg_cap = vcpu->arch.mcg_cap;
1716 unsigned bank_num = mcg_cap & 0xff;
1719 case MSR_IA32_MCG_STATUS:
1720 vcpu->arch.mcg_status = data;
1722 case MSR_IA32_MCG_CTL:
1723 if (!(mcg_cap & MCG_CTL_P))
1725 if (data != 0 && data != ~(u64)0)
1727 vcpu->arch.mcg_ctl = data;
1730 if (msr >= MSR_IA32_MC0_CTL &&
1731 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1732 u32 offset = msr - MSR_IA32_MC0_CTL;
1733 /* only 0 or all 1s can be written to IA32_MCi_CTL
1734 * some Linux kernels though clear bit 10 in bank 4 to
1735 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
1736 * this to avoid an uncatched #GP in the guest
1738 if ((offset & 0x3) == 0 &&
1739 data != 0 && (data | (1 << 10)) != ~(u64)0)
1741 vcpu->arch.mce_banks[offset] = data;
1749 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
1751 struct kvm *kvm = vcpu->kvm;
1752 int lm = is_long_mode(vcpu);
1753 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
1754 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
1755 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
1756 : kvm->arch.xen_hvm_config.blob_size_32;
1757 u32 page_num = data & ~PAGE_MASK;
1758 u64 page_addr = data & PAGE_MASK;
1763 if (page_num >= blob_size)
1766 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
1771 if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
1780 static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
1782 return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
1785 static bool kvm_hv_msr_partition_wide(u32 msr)
1789 case HV_X64_MSR_GUEST_OS_ID:
1790 case HV_X64_MSR_HYPERCALL:
1798 static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1800 struct kvm *kvm = vcpu->kvm;
1803 case HV_X64_MSR_GUEST_OS_ID:
1804 kvm->arch.hv_guest_os_id = data;
1805 /* setting guest os id to zero disables hypercall page */
1806 if (!kvm->arch.hv_guest_os_id)
1807 kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
1809 case HV_X64_MSR_HYPERCALL: {
1814 /* if guest os id is not set hypercall should remain disabled */
1815 if (!kvm->arch.hv_guest_os_id)
1817 if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
1818 kvm->arch.hv_hypercall = data;
1821 gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
1822 addr = gfn_to_hva(kvm, gfn);
1823 if (kvm_is_error_hva(addr))
1825 kvm_x86_ops->patch_hypercall(vcpu, instructions);
1826 ((unsigned char *)instructions)[3] = 0xc3; /* ret */
1827 if (__copy_to_user((void __user *)addr, instructions, 4))
1829 kvm->arch.hv_hypercall = data;
1833 vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1834 "data 0x%llx\n", msr, data);
1840 static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1843 case HV_X64_MSR_APIC_ASSIST_PAGE: {
1846 if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
1847 vcpu->arch.hv_vapic = data;
1850 addr = gfn_to_hva(vcpu->kvm, data >>
1851 HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
1852 if (kvm_is_error_hva(addr))
1854 if (__clear_user((void __user *)addr, PAGE_SIZE))
1856 vcpu->arch.hv_vapic = data;
1859 case HV_X64_MSR_EOI:
1860 return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
1861 case HV_X64_MSR_ICR:
1862 return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
1863 case HV_X64_MSR_TPR:
1864 return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
1866 vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1867 "data 0x%llx\n", msr, data);
1874 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
1876 gpa_t gpa = data & ~0x3f;
1878 /* Bits 2:5 are reserved, Should be zero */
1882 vcpu->arch.apf.msr_val = data;
1884 if (!(data & KVM_ASYNC_PF_ENABLED)) {
1885 kvm_clear_async_pf_completion_queue(vcpu);
1886 kvm_async_pf_hash_reset(vcpu);
1890 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
1894 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
1895 kvm_async_pf_wakeup_all(vcpu);
1899 static void kvmclock_reset(struct kvm_vcpu *vcpu)
1901 vcpu->arch.pv_time_enabled = false;
1904 static void accumulate_steal_time(struct kvm_vcpu *vcpu)
1908 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1911 delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
1912 vcpu->arch.st.last_steal = current->sched_info.run_delay;
1913 vcpu->arch.st.accum_steal = delta;
1916 static void record_steal_time(struct kvm_vcpu *vcpu)
1918 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1921 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1922 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
1925 vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
1926 vcpu->arch.st.steal.version += 2;
1927 vcpu->arch.st.accum_steal = 0;
1929 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1930 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
1933 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1936 u32 msr = msr_info->index;
1937 u64 data = msr_info->data;
1940 case MSR_AMD64_NB_CFG:
1941 case MSR_IA32_UCODE_REV:
1942 case MSR_IA32_UCODE_WRITE:
1943 case MSR_VM_HSAVE_PA:
1944 case MSR_AMD64_PATCH_LOADER:
1945 case MSR_AMD64_BU_CFG2:
1949 return set_efer(vcpu, data);
1951 data &= ~(u64)0x40; /* ignore flush filter disable */
1952 data &= ~(u64)0x100; /* ignore ignne emulation enable */
1953 data &= ~(u64)0x8; /* ignore TLB cache disable */
1955 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
1960 case MSR_FAM10H_MMIO_CONF_BASE:
1962 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
1967 case MSR_IA32_DEBUGCTLMSR:
1969 /* We support the non-activated case already */
1971 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
1972 /* Values other than LBR and BTF are vendor-specific,
1973 thus reserved and should throw a #GP */
1976 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
1979 case 0x200 ... 0x2ff:
1980 return set_msr_mtrr(vcpu, msr, data);
1981 case MSR_IA32_APICBASE:
1982 kvm_set_apic_base(vcpu, data);
1984 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1985 return kvm_x2apic_msr_write(vcpu, msr, data);
1986 case MSR_IA32_TSCDEADLINE:
1987 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1989 case MSR_IA32_TSC_ADJUST:
1990 if (guest_cpuid_has_tsc_adjust(vcpu)) {
1991 if (!msr_info->host_initiated) {
1992 u64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
1993 kvm_x86_ops->adjust_tsc_offset(vcpu, adj, true);
1995 vcpu->arch.ia32_tsc_adjust_msr = data;
1998 case MSR_IA32_MISC_ENABLE:
1999 vcpu->arch.ia32_misc_enable_msr = data;
2001 case MSR_KVM_WALL_CLOCK_NEW:
2002 case MSR_KVM_WALL_CLOCK:
2003 vcpu->kvm->arch.wall_clock = data;
2004 kvm_write_wall_clock(vcpu->kvm, data);
2006 case MSR_KVM_SYSTEM_TIME_NEW:
2007 case MSR_KVM_SYSTEM_TIME: {
2009 kvmclock_reset(vcpu);
2011 vcpu->arch.time = data;
2012 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2014 /* we verify if the enable bit is set... */
2018 gpa_offset = data & ~(PAGE_MASK | 1);
2020 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2021 &vcpu->arch.pv_time, data & ~1ULL,
2022 sizeof(struct pvclock_vcpu_time_info)))
2023 vcpu->arch.pv_time_enabled = false;
2025 vcpu->arch.pv_time_enabled = true;
2029 case MSR_KVM_ASYNC_PF_EN:
2030 if (kvm_pv_enable_async_pf(vcpu, data))
2033 case MSR_KVM_STEAL_TIME:
2035 if (unlikely(!sched_info_on()))
2038 if (data & KVM_STEAL_RESERVED_MASK)
2041 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2042 data & KVM_STEAL_VALID_BITS,
2043 sizeof(struct kvm_steal_time)))
2046 vcpu->arch.st.msr_val = data;
2048 if (!(data & KVM_MSR_ENABLED))
2051 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2054 accumulate_steal_time(vcpu);
2057 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2060 case MSR_KVM_PV_EOI_EN:
2061 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2065 case MSR_IA32_MCG_CTL:
2066 case MSR_IA32_MCG_STATUS:
2067 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
2068 return set_msr_mce(vcpu, msr, data);
2070 /* Performance counters are not protected by a CPUID bit,
2071 * so we should check all of them in the generic path for the sake of
2072 * cross vendor migration.
2073 * Writing a zero into the event select MSRs disables them,
2074 * which we perfectly emulate ;-). Any other value should be at least
2075 * reported, some guests depend on them.
2077 case MSR_K7_EVNTSEL0:
2078 case MSR_K7_EVNTSEL1:
2079 case MSR_K7_EVNTSEL2:
2080 case MSR_K7_EVNTSEL3:
2082 vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
2083 "0x%x data 0x%llx\n", msr, data);
2085 /* at least RHEL 4 unconditionally writes to the perfctr registers,
2086 * so we ignore writes to make it happy.
2088 case MSR_K7_PERFCTR0:
2089 case MSR_K7_PERFCTR1:
2090 case MSR_K7_PERFCTR2:
2091 case MSR_K7_PERFCTR3:
2092 vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
2093 "0x%x data 0x%llx\n", msr, data);
2095 case MSR_P6_PERFCTR0:
2096 case MSR_P6_PERFCTR1:
2098 case MSR_P6_EVNTSEL0:
2099 case MSR_P6_EVNTSEL1:
2100 if (kvm_pmu_msr(vcpu, msr))
2101 return kvm_pmu_set_msr(vcpu, msr_info);
2103 if (pr || data != 0)
2104 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2105 "0x%x data 0x%llx\n", msr, data);
2107 case MSR_K7_CLK_CTL:
2109 * Ignore all writes to this no longer documented MSR.
2110 * Writes are only relevant for old K7 processors,
2111 * all pre-dating SVM, but a recommended workaround from
2112 * AMD for these chips. It is possible to specify the
2113 * affected processor models on the command line, hence
2114 * the need to ignore the workaround.
2117 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2118 if (kvm_hv_msr_partition_wide(msr)) {
2120 mutex_lock(&vcpu->kvm->lock);
2121 r = set_msr_hyperv_pw(vcpu, msr, data);
2122 mutex_unlock(&vcpu->kvm->lock);
2125 return set_msr_hyperv(vcpu, msr, data);
2127 case MSR_IA32_BBL_CR_CTL3:
2128 /* Drop writes to this legacy MSR -- see rdmsr
2129 * counterpart for further detail.
2131 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
2133 case MSR_AMD64_OSVW_ID_LENGTH:
2134 if (!guest_cpuid_has_osvw(vcpu))
2136 vcpu->arch.osvw.length = data;
2138 case MSR_AMD64_OSVW_STATUS:
2139 if (!guest_cpuid_has_osvw(vcpu))
2141 vcpu->arch.osvw.status = data;
2144 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2145 return xen_hvm_config(vcpu, data);
2146 if (kvm_pmu_msr(vcpu, msr))
2147 return kvm_pmu_set_msr(vcpu, msr_info);
2149 vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
2153 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
2160 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2164 * Reads an msr value (of 'msr_index') into 'pdata'.
2165 * Returns 0 on success, non-0 otherwise.
2166 * Assumes vcpu_load() was already called.
2168 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2170 return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
2173 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2175 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
2177 if (!msr_mtrr_valid(msr))
2180 if (msr == MSR_MTRRdefType)
2181 *pdata = vcpu->arch.mtrr_state.def_type +
2182 (vcpu->arch.mtrr_state.enabled << 10);
2183 else if (msr == MSR_MTRRfix64K_00000)
2185 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
2186 *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
2187 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
2188 *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
2189 else if (msr == MSR_IA32_CR_PAT)
2190 *pdata = vcpu->arch.pat;
2191 else { /* Variable MTRRs */
2192 int idx, is_mtrr_mask;
2195 idx = (msr - 0x200) / 2;
2196 is_mtrr_mask = msr - 0x200 - 2 * idx;
2199 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
2202 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
2209 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2212 u64 mcg_cap = vcpu->arch.mcg_cap;
2213 unsigned bank_num = mcg_cap & 0xff;
2216 case MSR_IA32_P5_MC_ADDR:
2217 case MSR_IA32_P5_MC_TYPE:
2220 case MSR_IA32_MCG_CAP:
2221 data = vcpu->arch.mcg_cap;
2223 case MSR_IA32_MCG_CTL:
2224 if (!(mcg_cap & MCG_CTL_P))
2226 data = vcpu->arch.mcg_ctl;
2228 case MSR_IA32_MCG_STATUS:
2229 data = vcpu->arch.mcg_status;
2232 if (msr >= MSR_IA32_MC0_CTL &&
2233 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
2234 u32 offset = msr - MSR_IA32_MC0_CTL;
2235 data = vcpu->arch.mce_banks[offset];
2244 static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2247 struct kvm *kvm = vcpu->kvm;
2250 case HV_X64_MSR_GUEST_OS_ID:
2251 data = kvm->arch.hv_guest_os_id;
2253 case HV_X64_MSR_HYPERCALL:
2254 data = kvm->arch.hv_hypercall;
2257 vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
2265 static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2270 case HV_X64_MSR_VP_INDEX: {
2273 kvm_for_each_vcpu(r, v, vcpu->kvm)
2278 case HV_X64_MSR_EOI:
2279 return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
2280 case HV_X64_MSR_ICR:
2281 return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
2282 case HV_X64_MSR_TPR:
2283 return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
2284 case HV_X64_MSR_APIC_ASSIST_PAGE:
2285 data = vcpu->arch.hv_vapic;
2288 vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
2295 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2300 case MSR_IA32_PLATFORM_ID:
2301 case MSR_IA32_EBL_CR_POWERON:
2302 case MSR_IA32_DEBUGCTLMSR:
2303 case MSR_IA32_LASTBRANCHFROMIP:
2304 case MSR_IA32_LASTBRANCHTOIP:
2305 case MSR_IA32_LASTINTFROMIP:
2306 case MSR_IA32_LASTINTTOIP:
2309 case MSR_VM_HSAVE_PA:
2310 case MSR_K7_EVNTSEL0:
2311 case MSR_K7_PERFCTR0:
2312 case MSR_K8_INT_PENDING_MSG:
2313 case MSR_AMD64_NB_CFG:
2314 case MSR_FAM10H_MMIO_CONF_BASE:
2315 case MSR_AMD64_BU_CFG2:
2318 case MSR_P6_PERFCTR0:
2319 case MSR_P6_PERFCTR1:
2320 case MSR_P6_EVNTSEL0:
2321 case MSR_P6_EVNTSEL1:
2322 if (kvm_pmu_msr(vcpu, msr))
2323 return kvm_pmu_get_msr(vcpu, msr, pdata);
2326 case MSR_IA32_UCODE_REV:
2327 data = 0x100000000ULL;
2330 data = 0x500 | KVM_NR_VAR_MTRR;
2332 case 0x200 ... 0x2ff:
2333 return get_msr_mtrr(vcpu, msr, pdata);
2334 case 0xcd: /* fsb frequency */
2338 * MSR_EBC_FREQUENCY_ID
2339 * Conservative value valid for even the basic CPU models.
2340 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2341 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2342 * and 266MHz for model 3, or 4. Set Core Clock
2343 * Frequency to System Bus Frequency Ratio to 1 (bits
2344 * 31:24) even though these are only valid for CPU
2345 * models > 2, however guests may end up dividing or
2346 * multiplying by zero otherwise.
2348 case MSR_EBC_FREQUENCY_ID:
2351 case MSR_IA32_APICBASE:
2352 data = kvm_get_apic_base(vcpu);
2354 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2355 return kvm_x2apic_msr_read(vcpu, msr, pdata);
2357 case MSR_IA32_TSCDEADLINE:
2358 data = kvm_get_lapic_tscdeadline_msr(vcpu);
2360 case MSR_IA32_TSC_ADJUST:
2361 data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2363 case MSR_IA32_MISC_ENABLE:
2364 data = vcpu->arch.ia32_misc_enable_msr;
2366 case MSR_IA32_PERF_STATUS:
2367 /* TSC increment by tick */
2369 /* CPU multiplier */
2370 data |= (((uint64_t)4ULL) << 40);
2373 data = vcpu->arch.efer;
2375 case MSR_KVM_WALL_CLOCK:
2376 case MSR_KVM_WALL_CLOCK_NEW:
2377 data = vcpu->kvm->arch.wall_clock;
2379 case MSR_KVM_SYSTEM_TIME:
2380 case MSR_KVM_SYSTEM_TIME_NEW:
2381 data = vcpu->arch.time;
2383 case MSR_KVM_ASYNC_PF_EN:
2384 data = vcpu->arch.apf.msr_val;
2386 case MSR_KVM_STEAL_TIME:
2387 data = vcpu->arch.st.msr_val;
2389 case MSR_KVM_PV_EOI_EN:
2390 data = vcpu->arch.pv_eoi.msr_val;
2392 case MSR_IA32_P5_MC_ADDR:
2393 case MSR_IA32_P5_MC_TYPE:
2394 case MSR_IA32_MCG_CAP:
2395 case MSR_IA32_MCG_CTL:
2396 case MSR_IA32_MCG_STATUS:
2397 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
2398 return get_msr_mce(vcpu, msr, pdata);
2399 case MSR_K7_CLK_CTL:
2401 * Provide expected ramp-up count for K7. All other
2402 * are set to zero, indicating minimum divisors for
2405 * This prevents guest kernels on AMD host with CPU
2406 * type 6, model 8 and higher from exploding due to
2407 * the rdmsr failing.
2411 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2412 if (kvm_hv_msr_partition_wide(msr)) {
2414 mutex_lock(&vcpu->kvm->lock);
2415 r = get_msr_hyperv_pw(vcpu, msr, pdata);
2416 mutex_unlock(&vcpu->kvm->lock);
2419 return get_msr_hyperv(vcpu, msr, pdata);
2421 case MSR_IA32_BBL_CR_CTL3:
2422 /* This legacy MSR exists but isn't fully documented in current
2423 * silicon. It is however accessed by winxp in very narrow
2424 * scenarios where it sets bit #19, itself documented as
2425 * a "reserved" bit. Best effort attempt to source coherent
2426 * read data here should the balance of the register be
2427 * interpreted by the guest:
2429 * L2 cache control register 3: 64GB range, 256KB size,
2430 * enabled, latency 0x1, configured
2434 case MSR_AMD64_OSVW_ID_LENGTH:
2435 if (!guest_cpuid_has_osvw(vcpu))
2437 data = vcpu->arch.osvw.length;
2439 case MSR_AMD64_OSVW_STATUS:
2440 if (!guest_cpuid_has_osvw(vcpu))
2442 data = vcpu->arch.osvw.status;
2445 if (kvm_pmu_msr(vcpu, msr))
2446 return kvm_pmu_get_msr(vcpu, msr, pdata);
2448 vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
2451 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
2459 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2462 * Read or write a bunch of msrs. All parameters are kernel addresses.
2464 * @return number of msrs set successfully.
2466 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2467 struct kvm_msr_entry *entries,
2468 int (*do_msr)(struct kvm_vcpu *vcpu,
2469 unsigned index, u64 *data))
2473 idx = srcu_read_lock(&vcpu->kvm->srcu);
2474 for (i = 0; i < msrs->nmsrs; ++i)
2475 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2477 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2483 * Read or write a bunch of msrs. Parameters are user addresses.
2485 * @return number of msrs set successfully.
2487 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2488 int (*do_msr)(struct kvm_vcpu *vcpu,
2489 unsigned index, u64 *data),
2492 struct kvm_msrs msrs;
2493 struct kvm_msr_entry *entries;
2498 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2502 if (msrs.nmsrs >= MAX_IO_MSRS)
2505 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2506 entries = memdup_user(user_msrs->entries, size);
2507 if (IS_ERR(entries)) {
2508 r = PTR_ERR(entries);
2512 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2517 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2528 int kvm_dev_ioctl_check_extension(long ext)
2533 case KVM_CAP_IRQCHIP:
2535 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2536 case KVM_CAP_SET_TSS_ADDR:
2537 case KVM_CAP_EXT_CPUID:
2538 case KVM_CAP_EXT_EMUL_CPUID:
2539 case KVM_CAP_CLOCKSOURCE:
2541 case KVM_CAP_NOP_IO_DELAY:
2542 case KVM_CAP_MP_STATE:
2543 case KVM_CAP_SYNC_MMU:
2544 case KVM_CAP_USER_NMI:
2545 case KVM_CAP_REINJECT_CONTROL:
2546 case KVM_CAP_IRQ_INJECT_STATUS:
2548 case KVM_CAP_IOEVENTFD:
2550 case KVM_CAP_PIT_STATE2:
2551 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2552 case KVM_CAP_XEN_HVM:
2553 case KVM_CAP_ADJUST_CLOCK:
2554 case KVM_CAP_VCPU_EVENTS:
2555 case KVM_CAP_HYPERV:
2556 case KVM_CAP_HYPERV_VAPIC:
2557 case KVM_CAP_HYPERV_SPIN:
2558 case KVM_CAP_PCI_SEGMENT:
2559 case KVM_CAP_DEBUGREGS:
2560 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2562 case KVM_CAP_ASYNC_PF:
2563 case KVM_CAP_GET_TSC_KHZ:
2564 case KVM_CAP_KVMCLOCK_CTRL:
2565 case KVM_CAP_READONLY_MEM:
2566 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2567 case KVM_CAP_ASSIGN_DEV_IRQ:
2568 case KVM_CAP_PCI_2_3:
2572 case KVM_CAP_COALESCED_MMIO:
2573 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2576 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2578 case KVM_CAP_NR_VCPUS:
2579 r = KVM_SOFT_MAX_VCPUS;
2581 case KVM_CAP_MAX_VCPUS:
2584 case KVM_CAP_NR_MEMSLOTS:
2585 r = KVM_USER_MEM_SLOTS;
2587 case KVM_CAP_PV_MMU: /* obsolete */
2590 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2592 r = iommu_present(&pci_bus_type);
2596 r = KVM_MAX_MCE_BANKS;
2601 case KVM_CAP_TSC_CONTROL:
2602 r = kvm_has_tsc_control;
2604 case KVM_CAP_TSC_DEADLINE_TIMER:
2605 r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
2615 long kvm_arch_dev_ioctl(struct file *filp,
2616 unsigned int ioctl, unsigned long arg)
2618 void __user *argp = (void __user *)arg;
2622 case KVM_GET_MSR_INDEX_LIST: {
2623 struct kvm_msr_list __user *user_msr_list = argp;
2624 struct kvm_msr_list msr_list;
2628 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2631 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
2632 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2635 if (n < msr_list.nmsrs)
2638 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2639 num_msrs_to_save * sizeof(u32)))
2641 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2643 ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
2648 case KVM_GET_SUPPORTED_CPUID:
2649 case KVM_GET_EMULATED_CPUID: {
2650 struct kvm_cpuid2 __user *cpuid_arg = argp;
2651 struct kvm_cpuid2 cpuid;
2654 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2657 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2663 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2668 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2671 mce_cap = KVM_MCE_CAP_SUPPORTED;
2673 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2685 static void wbinvd_ipi(void *garbage)
2690 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2692 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2695 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2697 /* Address WBINVD may be executed by guest */
2698 if (need_emulate_wbinvd(vcpu)) {
2699 if (kvm_x86_ops->has_wbinvd_exit())
2700 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2701 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2702 smp_call_function_single(vcpu->cpu,
2703 wbinvd_ipi, NULL, 1);
2706 kvm_x86_ops->vcpu_load(vcpu, cpu);
2708 /* Apply any externally detected TSC adjustments (due to suspend) */
2709 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2710 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2711 vcpu->arch.tsc_offset_adjustment = 0;
2712 set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
2715 if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2716 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2717 native_read_tsc() - vcpu->arch.last_host_tsc;
2719 mark_tsc_unstable("KVM discovered backwards TSC");
2720 if (check_tsc_unstable()) {
2721 u64 offset = kvm_x86_ops->compute_tsc_offset(vcpu,
2722 vcpu->arch.last_guest_tsc);
2723 kvm_x86_ops->write_tsc_offset(vcpu, offset);
2724 vcpu->arch.tsc_catchup = 1;
2727 * On a host with synchronized TSC, there is no need to update
2728 * kvmclock on vcpu->cpu migration
2730 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
2731 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2732 if (vcpu->cpu != cpu)
2733 kvm_migrate_timers(vcpu);
2737 accumulate_steal_time(vcpu);
2738 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2741 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2743 kvm_x86_ops->vcpu_put(vcpu);
2744 kvm_put_guest_fpu(vcpu);
2745 vcpu->arch.last_host_tsc = native_read_tsc();
2748 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2749 struct kvm_lapic_state *s)
2751 kvm_x86_ops->sync_pir_to_irr(vcpu);
2752 memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2757 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2758 struct kvm_lapic_state *s)
2760 kvm_apic_post_state_restore(vcpu, s);
2761 update_cr8_intercept(vcpu);
2766 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2767 struct kvm_interrupt *irq)
2769 if (irq->irq >= KVM_NR_INTERRUPTS)
2771 if (irqchip_in_kernel(vcpu->kvm))
2774 kvm_queue_interrupt(vcpu, irq->irq, false);
2775 kvm_make_request(KVM_REQ_EVENT, vcpu);
2780 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2782 kvm_inject_nmi(vcpu);
2787 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2788 struct kvm_tpr_access_ctl *tac)
2792 vcpu->arch.tpr_access_reporting = !!tac->enabled;
2796 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2800 unsigned bank_num = mcg_cap & 0xff, bank;
2803 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2805 if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2808 vcpu->arch.mcg_cap = mcg_cap;
2809 /* Init IA32_MCG_CTL to all 1s */
2810 if (mcg_cap & MCG_CTL_P)
2811 vcpu->arch.mcg_ctl = ~(u64)0;
2812 /* Init IA32_MCi_CTL to all 1s */
2813 for (bank = 0; bank < bank_num; bank++)
2814 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2819 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2820 struct kvm_x86_mce *mce)
2822 u64 mcg_cap = vcpu->arch.mcg_cap;
2823 unsigned bank_num = mcg_cap & 0xff;
2824 u64 *banks = vcpu->arch.mce_banks;
2826 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2829 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2830 * reporting is disabled
2832 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2833 vcpu->arch.mcg_ctl != ~(u64)0)
2835 banks += 4 * mce->bank;
2837 * if IA32_MCi_CTL is not all 1s, the uncorrected error
2838 * reporting is disabled for the bank
2840 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2842 if (mce->status & MCI_STATUS_UC) {
2843 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2844 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2845 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2848 if (banks[1] & MCI_STATUS_VAL)
2849 mce->status |= MCI_STATUS_OVER;
2850 banks[2] = mce->addr;
2851 banks[3] = mce->misc;
2852 vcpu->arch.mcg_status = mce->mcg_status;
2853 banks[1] = mce->status;
2854 kvm_queue_exception(vcpu, MC_VECTOR);
2855 } else if (!(banks[1] & MCI_STATUS_VAL)
2856 || !(banks[1] & MCI_STATUS_UC)) {
2857 if (banks[1] & MCI_STATUS_VAL)
2858 mce->status |= MCI_STATUS_OVER;
2859 banks[2] = mce->addr;
2860 banks[3] = mce->misc;
2861 banks[1] = mce->status;
2863 banks[1] |= MCI_STATUS_OVER;
2867 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2868 struct kvm_vcpu_events *events)
2871 events->exception.injected =
2872 vcpu->arch.exception.pending &&
2873 !kvm_exception_is_soft(vcpu->arch.exception.nr);
2874 events->exception.nr = vcpu->arch.exception.nr;
2875 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2876 events->exception.pad = 0;
2877 events->exception.error_code = vcpu->arch.exception.error_code;
2879 events->interrupt.injected =
2880 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
2881 events->interrupt.nr = vcpu->arch.interrupt.nr;
2882 events->interrupt.soft = 0;
2883 events->interrupt.shadow =
2884 kvm_x86_ops->get_interrupt_shadow(vcpu,
2885 KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
2887 events->nmi.injected = vcpu->arch.nmi_injected;
2888 events->nmi.pending = vcpu->arch.nmi_pending != 0;
2889 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
2890 events->nmi.pad = 0;
2892 events->sipi_vector = 0; /* never valid when reporting to user space */
2894 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
2895 | KVM_VCPUEVENT_VALID_SHADOW);
2896 memset(&events->reserved, 0, sizeof(events->reserved));
2899 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
2900 struct kvm_vcpu_events *events)
2902 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
2903 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2904 | KVM_VCPUEVENT_VALID_SHADOW))
2908 vcpu->arch.exception.pending = events->exception.injected;
2909 vcpu->arch.exception.nr = events->exception.nr;
2910 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
2911 vcpu->arch.exception.error_code = events->exception.error_code;
2913 vcpu->arch.interrupt.pending = events->interrupt.injected;
2914 vcpu->arch.interrupt.nr = events->interrupt.nr;
2915 vcpu->arch.interrupt.soft = events->interrupt.soft;
2916 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
2917 kvm_x86_ops->set_interrupt_shadow(vcpu,
2918 events->interrupt.shadow);
2920 vcpu->arch.nmi_injected = events->nmi.injected;
2921 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
2922 vcpu->arch.nmi_pending = events->nmi.pending;
2923 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
2925 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
2926 kvm_vcpu_has_lapic(vcpu))
2927 vcpu->arch.apic->sipi_vector = events->sipi_vector;
2929 kvm_make_request(KVM_REQ_EVENT, vcpu);
2934 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
2935 struct kvm_debugregs *dbgregs)
2937 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
2938 dbgregs->dr6 = vcpu->arch.dr6;
2939 dbgregs->dr7 = vcpu->arch.dr7;
2941 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
2944 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
2945 struct kvm_debugregs *dbgregs)
2950 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
2951 vcpu->arch.dr6 = dbgregs->dr6;
2952 vcpu->arch.dr7 = dbgregs->dr7;
2957 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
2958 struct kvm_xsave *guest_xsave)
2960 if (cpu_has_xsave) {
2961 memcpy(guest_xsave->region,
2962 &vcpu->arch.guest_fpu.state->xsave,
2963 vcpu->arch.guest_xstate_size);
2964 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] &=
2965 vcpu->arch.guest_supported_xcr0 | XSTATE_FPSSE;
2967 memcpy(guest_xsave->region,
2968 &vcpu->arch.guest_fpu.state->fxsave,
2969 sizeof(struct i387_fxsave_struct));
2970 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
2975 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
2976 struct kvm_xsave *guest_xsave)
2979 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
2981 if (cpu_has_xsave) {
2983 * Here we allow setting states that are not present in
2984 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
2985 * with old userspace.
2987 if (xstate_bv & ~KVM_SUPPORTED_XCR0)
2989 if (xstate_bv & ~host_xcr0)
2991 memcpy(&vcpu->arch.guest_fpu.state->xsave,
2992 guest_xsave->region, vcpu->arch.guest_xstate_size);
2994 if (xstate_bv & ~XSTATE_FPSSE)
2996 memcpy(&vcpu->arch.guest_fpu.state->fxsave,
2997 guest_xsave->region, sizeof(struct i387_fxsave_struct));
3002 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3003 struct kvm_xcrs *guest_xcrs)
3005 if (!cpu_has_xsave) {
3006 guest_xcrs->nr_xcrs = 0;
3010 guest_xcrs->nr_xcrs = 1;
3011 guest_xcrs->flags = 0;
3012 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3013 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3016 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3017 struct kvm_xcrs *guest_xcrs)
3024 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3027 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3028 /* Only support XCR0 currently */
3029 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3030 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3031 guest_xcrs->xcrs[i].value);
3040 * kvm_set_guest_paused() indicates to the guest kernel that it has been
3041 * stopped by the hypervisor. This function will be called from the host only.
3042 * EINVAL is returned when the host attempts to set the flag for a guest that
3043 * does not support pv clocks.
3045 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3047 if (!vcpu->arch.pv_time_enabled)
3049 vcpu->arch.pvclock_set_guest_stopped_request = true;
3050 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3054 long kvm_arch_vcpu_ioctl(struct file *filp,
3055 unsigned int ioctl, unsigned long arg)
3057 struct kvm_vcpu *vcpu = filp->private_data;
3058 void __user *argp = (void __user *)arg;
3061 struct kvm_lapic_state *lapic;
3062 struct kvm_xsave *xsave;
3063 struct kvm_xcrs *xcrs;
3069 case KVM_GET_LAPIC: {
3071 if (!vcpu->arch.apic)
3073 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3078 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3082 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3087 case KVM_SET_LAPIC: {
3089 if (!vcpu->arch.apic)
3091 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3092 if (IS_ERR(u.lapic))
3093 return PTR_ERR(u.lapic);
3095 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3098 case KVM_INTERRUPT: {
3099 struct kvm_interrupt irq;
3102 if (copy_from_user(&irq, argp, sizeof irq))
3104 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3108 r = kvm_vcpu_ioctl_nmi(vcpu);
3111 case KVM_SET_CPUID: {
3112 struct kvm_cpuid __user *cpuid_arg = argp;
3113 struct kvm_cpuid cpuid;
3116 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3118 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3121 case KVM_SET_CPUID2: {
3122 struct kvm_cpuid2 __user *cpuid_arg = argp;
3123 struct kvm_cpuid2 cpuid;
3126 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3128 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3129 cpuid_arg->entries);
3132 case KVM_GET_CPUID2: {
3133 struct kvm_cpuid2 __user *cpuid_arg = argp;
3134 struct kvm_cpuid2 cpuid;
3137 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3139 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3140 cpuid_arg->entries);
3144 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3150 r = msr_io(vcpu, argp, kvm_get_msr, 1);
3153 r = msr_io(vcpu, argp, do_set_msr, 0);
3155 case KVM_TPR_ACCESS_REPORTING: {
3156 struct kvm_tpr_access_ctl tac;
3159 if (copy_from_user(&tac, argp, sizeof tac))
3161 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3165 if (copy_to_user(argp, &tac, sizeof tac))
3170 case KVM_SET_VAPIC_ADDR: {
3171 struct kvm_vapic_addr va;
3174 if (!irqchip_in_kernel(vcpu->kvm))
3177 if (copy_from_user(&va, argp, sizeof va))
3180 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3183 case KVM_X86_SETUP_MCE: {
3187 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3189 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3192 case KVM_X86_SET_MCE: {
3193 struct kvm_x86_mce mce;
3196 if (copy_from_user(&mce, argp, sizeof mce))
3198 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3201 case KVM_GET_VCPU_EVENTS: {
3202 struct kvm_vcpu_events events;
3204 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3207 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3212 case KVM_SET_VCPU_EVENTS: {
3213 struct kvm_vcpu_events events;
3216 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3219 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3222 case KVM_GET_DEBUGREGS: {
3223 struct kvm_debugregs dbgregs;
3225 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3228 if (copy_to_user(argp, &dbgregs,
3229 sizeof(struct kvm_debugregs)))
3234 case KVM_SET_DEBUGREGS: {
3235 struct kvm_debugregs dbgregs;
3238 if (copy_from_user(&dbgregs, argp,
3239 sizeof(struct kvm_debugregs)))
3242 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3245 case KVM_GET_XSAVE: {
3246 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3251 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3254 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3259 case KVM_SET_XSAVE: {
3260 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3261 if (IS_ERR(u.xsave))
3262 return PTR_ERR(u.xsave);
3264 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3267 case KVM_GET_XCRS: {
3268 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3273 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3276 if (copy_to_user(argp, u.xcrs,
3277 sizeof(struct kvm_xcrs)))
3282 case KVM_SET_XCRS: {
3283 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3285 return PTR_ERR(u.xcrs);
3287 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3290 case KVM_SET_TSC_KHZ: {
3294 user_tsc_khz = (u32)arg;
3296 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3299 if (user_tsc_khz == 0)
3300 user_tsc_khz = tsc_khz;
3302 kvm_set_tsc_khz(vcpu, user_tsc_khz);
3307 case KVM_GET_TSC_KHZ: {
3308 r = vcpu->arch.virtual_tsc_khz;
3311 case KVM_KVMCLOCK_CTRL: {
3312 r = kvm_set_guest_paused(vcpu);
3323 int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3325 return VM_FAULT_SIGBUS;
3328 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3332 if (addr > (unsigned int)(-3 * PAGE_SIZE))
3334 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3338 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3341 kvm->arch.ept_identity_map_addr = ident_addr;
3345 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3346 u32 kvm_nr_mmu_pages)
3348 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3351 mutex_lock(&kvm->slots_lock);
3353 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3354 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3356 mutex_unlock(&kvm->slots_lock);
3360 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3362 return kvm->arch.n_max_mmu_pages;
3365 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3370 switch (chip->chip_id) {
3371 case KVM_IRQCHIP_PIC_MASTER:
3372 memcpy(&chip->chip.pic,
3373 &pic_irqchip(kvm)->pics[0],
3374 sizeof(struct kvm_pic_state));
3376 case KVM_IRQCHIP_PIC_SLAVE:
3377 memcpy(&chip->chip.pic,
3378 &pic_irqchip(kvm)->pics[1],
3379 sizeof(struct kvm_pic_state));
3381 case KVM_IRQCHIP_IOAPIC:
3382 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3391 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3396 switch (chip->chip_id) {
3397 case KVM_IRQCHIP_PIC_MASTER:
3398 spin_lock(&pic_irqchip(kvm)->lock);
3399 memcpy(&pic_irqchip(kvm)->pics[0],
3401 sizeof(struct kvm_pic_state));
3402 spin_unlock(&pic_irqchip(kvm)->lock);
3404 case KVM_IRQCHIP_PIC_SLAVE:
3405 spin_lock(&pic_irqchip(kvm)->lock);
3406 memcpy(&pic_irqchip(kvm)->pics[1],
3408 sizeof(struct kvm_pic_state));
3409 spin_unlock(&pic_irqchip(kvm)->lock);
3411 case KVM_IRQCHIP_IOAPIC:
3412 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3418 kvm_pic_update_irq(pic_irqchip(kvm));
3422 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3426 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3427 memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
3428 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3432 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3436 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3437 memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
3438 kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
3439 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3443 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3447 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3448 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3449 sizeof(ps->channels));
3450 ps->flags = kvm->arch.vpit->pit_state.flags;
3451 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3452 memset(&ps->reserved, 0, sizeof(ps->reserved));
3456 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3458 int r = 0, start = 0;
3459 u32 prev_legacy, cur_legacy;
3460 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3461 prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3462 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3463 if (!prev_legacy && cur_legacy)
3465 memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
3466 sizeof(kvm->arch.vpit->pit_state.channels));
3467 kvm->arch.vpit->pit_state.flags = ps->flags;
3468 kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
3469 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3473 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3474 struct kvm_reinject_control *control)
3476 if (!kvm->arch.vpit)
3478 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3479 kvm->arch.vpit->pit_state.reinject = control->pit_reinject;
3480 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3485 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
3486 * @kvm: kvm instance
3487 * @log: slot id and address to which we copy the log
3489 * We need to keep it in mind that VCPU threads can write to the bitmap
3490 * concurrently. So, to avoid losing data, we keep the following order for
3493 * 1. Take a snapshot of the bit and clear it if needed.
3494 * 2. Write protect the corresponding page.
3495 * 3. Flush TLB's if needed.
3496 * 4. Copy the snapshot to the userspace.
3498 * Between 2 and 3, the guest may write to the page using the remaining TLB
3499 * entry. This is not a problem because the page will be reported dirty at
3500 * step 4 using the snapshot taken before and step 3 ensures that successive
3501 * writes will be logged for the next call.
3503 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
3506 struct kvm_memory_slot *memslot;
3508 unsigned long *dirty_bitmap;
3509 unsigned long *dirty_bitmap_buffer;
3510 bool is_dirty = false;
3512 mutex_lock(&kvm->slots_lock);
3515 if (log->slot >= KVM_USER_MEM_SLOTS)
3518 memslot = id_to_memslot(kvm->memslots, log->slot);
3520 dirty_bitmap = memslot->dirty_bitmap;
3525 n = kvm_dirty_bitmap_bytes(memslot);
3527 dirty_bitmap_buffer = dirty_bitmap + n / sizeof(long);
3528 memset(dirty_bitmap_buffer, 0, n);
3530 spin_lock(&kvm->mmu_lock);
3532 for (i = 0; i < n / sizeof(long); i++) {
3536 if (!dirty_bitmap[i])
3541 mask = xchg(&dirty_bitmap[i], 0);
3542 dirty_bitmap_buffer[i] = mask;
3544 offset = i * BITS_PER_LONG;
3545 kvm_mmu_write_protect_pt_masked(kvm, memslot, offset, mask);
3548 kvm_flush_remote_tlbs(kvm);
3550 spin_unlock(&kvm->mmu_lock);
3553 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
3558 mutex_unlock(&kvm->slots_lock);
3562 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
3565 if (!irqchip_in_kernel(kvm))
3568 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3569 irq_event->irq, irq_event->level,
3574 long kvm_arch_vm_ioctl(struct file *filp,
3575 unsigned int ioctl, unsigned long arg)
3577 struct kvm *kvm = filp->private_data;
3578 void __user *argp = (void __user *)arg;
3581 * This union makes it completely explicit to gcc-3.x
3582 * that these two variables' stack usage should be
3583 * combined, not added together.
3586 struct kvm_pit_state ps;
3587 struct kvm_pit_state2 ps2;
3588 struct kvm_pit_config pit_config;
3592 case KVM_SET_TSS_ADDR:
3593 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3595 case KVM_SET_IDENTITY_MAP_ADDR: {
3599 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3601 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3604 case KVM_SET_NR_MMU_PAGES:
3605 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3607 case KVM_GET_NR_MMU_PAGES:
3608 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3610 case KVM_CREATE_IRQCHIP: {
3611 struct kvm_pic *vpic;
3613 mutex_lock(&kvm->lock);
3616 goto create_irqchip_unlock;
3618 if (atomic_read(&kvm->online_vcpus))
3619 goto create_irqchip_unlock;
3621 vpic = kvm_create_pic(kvm);
3623 r = kvm_ioapic_init(kvm);
3625 mutex_lock(&kvm->slots_lock);
3626 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3628 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3630 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3632 mutex_unlock(&kvm->slots_lock);
3634 goto create_irqchip_unlock;
3637 goto create_irqchip_unlock;
3639 kvm->arch.vpic = vpic;
3641 r = kvm_setup_default_irq_routing(kvm);
3643 mutex_lock(&kvm->slots_lock);
3644 mutex_lock(&kvm->irq_lock);
3645 kvm_ioapic_destroy(kvm);
3646 kvm_destroy_pic(kvm);
3647 mutex_unlock(&kvm->irq_lock);
3648 mutex_unlock(&kvm->slots_lock);
3650 create_irqchip_unlock:
3651 mutex_unlock(&kvm->lock);
3654 case KVM_CREATE_PIT:
3655 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3657 case KVM_CREATE_PIT2:
3659 if (copy_from_user(&u.pit_config, argp,
3660 sizeof(struct kvm_pit_config)))
3663 mutex_lock(&kvm->slots_lock);
3666 goto create_pit_unlock;
3668 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3672 mutex_unlock(&kvm->slots_lock);
3674 case KVM_GET_IRQCHIP: {
3675 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3676 struct kvm_irqchip *chip;
3678 chip = memdup_user(argp, sizeof(*chip));
3685 if (!irqchip_in_kernel(kvm))
3686 goto get_irqchip_out;
3687 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3689 goto get_irqchip_out;
3691 if (copy_to_user(argp, chip, sizeof *chip))
3692 goto get_irqchip_out;
3698 case KVM_SET_IRQCHIP: {
3699 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3700 struct kvm_irqchip *chip;
3702 chip = memdup_user(argp, sizeof(*chip));
3709 if (!irqchip_in_kernel(kvm))
3710 goto set_irqchip_out;
3711 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3713 goto set_irqchip_out;
3721 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
3724 if (!kvm->arch.vpit)
3726 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
3730 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
3737 if (copy_from_user(&u.ps, argp, sizeof u.ps))
3740 if (!kvm->arch.vpit)
3742 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
3745 case KVM_GET_PIT2: {
3747 if (!kvm->arch.vpit)
3749 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
3753 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
3758 case KVM_SET_PIT2: {
3760 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
3763 if (!kvm->arch.vpit)
3765 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
3768 case KVM_REINJECT_CONTROL: {
3769 struct kvm_reinject_control control;
3771 if (copy_from_user(&control, argp, sizeof(control)))
3773 r = kvm_vm_ioctl_reinject(kvm, &control);
3776 case KVM_XEN_HVM_CONFIG: {
3778 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
3779 sizeof(struct kvm_xen_hvm_config)))
3782 if (kvm->arch.xen_hvm_config.flags)
3787 case KVM_SET_CLOCK: {
3788 struct kvm_clock_data user_ns;
3793 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
3801 local_irq_disable();
3802 now_ns = get_kernel_ns();
3803 delta = user_ns.clock - now_ns;
3805 kvm->arch.kvmclock_offset = delta;
3806 kvm_gen_update_masterclock(kvm);
3809 case KVM_GET_CLOCK: {
3810 struct kvm_clock_data user_ns;
3813 local_irq_disable();
3814 now_ns = get_kernel_ns();
3815 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
3818 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
3821 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
3834 static void kvm_init_msr_list(void)
3839 /* skip the first msrs in the list. KVM-specific */
3840 for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
3841 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
3844 msrs_to_save[j] = msrs_to_save[i];
3847 num_msrs_to_save = j;
3850 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
3858 if (!(vcpu->arch.apic &&
3859 !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, n, v))
3860 && kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
3871 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
3878 if (!(vcpu->arch.apic &&
3879 !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, n, v))
3880 && kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
3882 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
3892 static void kvm_set_segment(struct kvm_vcpu *vcpu,
3893 struct kvm_segment *var, int seg)
3895 kvm_x86_ops->set_segment(vcpu, var, seg);
3898 void kvm_get_segment(struct kvm_vcpu *vcpu,
3899 struct kvm_segment *var, int seg)
3901 kvm_x86_ops->get_segment(vcpu, var, seg);
3904 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
3907 struct x86_exception exception;
3909 BUG_ON(!mmu_is_nested(vcpu));
3911 /* NPT walks are always user-walks */
3912 access |= PFERR_USER_MASK;
3913 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, &exception);
3918 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
3919 struct x86_exception *exception)
3921 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3922 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3925 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
3926 struct x86_exception *exception)
3928 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3929 access |= PFERR_FETCH_MASK;
3930 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3933 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
3934 struct x86_exception *exception)
3936 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3937 access |= PFERR_WRITE_MASK;
3938 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3941 /* uses this to access any guest's mapped memory without checking CPL */
3942 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
3943 struct x86_exception *exception)
3945 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
3948 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
3949 struct kvm_vcpu *vcpu, u32 access,
3950 struct x86_exception *exception)
3953 int r = X86EMUL_CONTINUE;
3956 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
3958 unsigned offset = addr & (PAGE_SIZE-1);
3959 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
3962 if (gpa == UNMAPPED_GVA)
3963 return X86EMUL_PROPAGATE_FAULT;
3964 ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
3966 r = X86EMUL_IO_NEEDED;
3978 /* used for instruction fetching */
3979 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
3980 gva_t addr, void *val, unsigned int bytes,
3981 struct x86_exception *exception)
3983 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3984 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3986 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
3987 access | PFERR_FETCH_MASK,
3991 int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
3992 gva_t addr, void *val, unsigned int bytes,
3993 struct x86_exception *exception)
3995 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3996 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3998 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4001 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4003 static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4004 gva_t addr, void *val, unsigned int bytes,
4005 struct x86_exception *exception)
4007 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4008 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
4011 int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4012 gva_t addr, void *val,
4014 struct x86_exception *exception)
4016 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4018 int r = X86EMUL_CONTINUE;
4021 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4024 unsigned offset = addr & (PAGE_SIZE-1);
4025 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4028 if (gpa == UNMAPPED_GVA)
4029 return X86EMUL_PROPAGATE_FAULT;
4030 ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
4032 r = X86EMUL_IO_NEEDED;
4043 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4045 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4046 gpa_t *gpa, struct x86_exception *exception,
4049 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
4050 | (write ? PFERR_WRITE_MASK : 0);
4052 if (vcpu_match_mmio_gva(vcpu, gva)
4053 && !permission_fault(vcpu->arch.walk_mmu, vcpu->arch.access, access)) {
4054 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4055 (gva & (PAGE_SIZE - 1));
4056 trace_vcpu_match_mmio(gva, *gpa, write, false);
4060 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4062 if (*gpa == UNMAPPED_GVA)
4065 /* For APIC access vmexit */
4066 if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4069 if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
4070 trace_vcpu_match_mmio(gva, *gpa, write, true);
4077 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4078 const void *val, int bytes)
4082 ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
4085 kvm_mmu_pte_write(vcpu, gpa, val, bytes);
4089 struct read_write_emulator_ops {
4090 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4092 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4093 void *val, int bytes);
4094 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4095 int bytes, void *val);
4096 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4097 void *val, int bytes);
4101 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4103 if (vcpu->mmio_read_completed) {
4104 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4105 vcpu->mmio_fragments[0].gpa, *(u64 *)val);
4106 vcpu->mmio_read_completed = 0;
4113 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4114 void *val, int bytes)
4116 return !kvm_read_guest(vcpu->kvm, gpa, val, bytes);
4119 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4120 void *val, int bytes)
4122 return emulator_write_phys(vcpu, gpa, val, bytes);
4125 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4127 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
4128 return vcpu_mmio_write(vcpu, gpa, bytes, val);
4131 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4132 void *val, int bytes)
4134 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
4135 return X86EMUL_IO_NEEDED;
4138 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4139 void *val, int bytes)
4141 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
4143 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
4144 return X86EMUL_CONTINUE;
4147 static const struct read_write_emulator_ops read_emultor = {
4148 .read_write_prepare = read_prepare,
4149 .read_write_emulate = read_emulate,
4150 .read_write_mmio = vcpu_mmio_read,
4151 .read_write_exit_mmio = read_exit_mmio,
4154 static const struct read_write_emulator_ops write_emultor = {
4155 .read_write_emulate = write_emulate,
4156 .read_write_mmio = write_mmio,
4157 .read_write_exit_mmio = write_exit_mmio,
4161 static int emulator_read_write_onepage(unsigned long addr, void *val,
4163 struct x86_exception *exception,
4164 struct kvm_vcpu *vcpu,
4165 const struct read_write_emulator_ops *ops)
4169 bool write = ops->write;
4170 struct kvm_mmio_fragment *frag;
4172 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4175 return X86EMUL_PROPAGATE_FAULT;
4177 /* For APIC access vmexit */
4181 if (ops->read_write_emulate(vcpu, gpa, val, bytes))
4182 return X86EMUL_CONTINUE;
4186 * Is this MMIO handled locally?
4188 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4189 if (handled == bytes)
4190 return X86EMUL_CONTINUE;
4196 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
4197 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
4201 return X86EMUL_CONTINUE;
4204 int emulator_read_write(struct x86_emulate_ctxt *ctxt, unsigned long addr,
4205 void *val, unsigned int bytes,
4206 struct x86_exception *exception,
4207 const struct read_write_emulator_ops *ops)
4209 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4213 if (ops->read_write_prepare &&
4214 ops->read_write_prepare(vcpu, val, bytes))
4215 return X86EMUL_CONTINUE;
4217 vcpu->mmio_nr_fragments = 0;
4219 /* Crossing a page boundary? */
4220 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4223 now = -addr & ~PAGE_MASK;
4224 rc = emulator_read_write_onepage(addr, val, now, exception,
4227 if (rc != X86EMUL_CONTINUE)
4234 rc = emulator_read_write_onepage(addr, val, bytes, exception,
4236 if (rc != X86EMUL_CONTINUE)
4239 if (!vcpu->mmio_nr_fragments)
4242 gpa = vcpu->mmio_fragments[0].gpa;
4244 vcpu->mmio_needed = 1;
4245 vcpu->mmio_cur_fragment = 0;
4247 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
4248 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
4249 vcpu->run->exit_reason = KVM_EXIT_MMIO;
4250 vcpu->run->mmio.phys_addr = gpa;
4252 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4255 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4259 struct x86_exception *exception)
4261 return emulator_read_write(ctxt, addr, val, bytes,
4262 exception, &read_emultor);
4265 int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4269 struct x86_exception *exception)
4271 return emulator_read_write(ctxt, addr, (void *)val, bytes,
4272 exception, &write_emultor);
4275 #define CMPXCHG_TYPE(t, ptr, old, new) \
4276 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4278 #ifdef CONFIG_X86_64
4279 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4281 # define CMPXCHG64(ptr, old, new) \
4282 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4285 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4290 struct x86_exception *exception)
4292 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4298 /* guests cmpxchg8b have to be emulated atomically */
4299 if (bytes > 8 || (bytes & (bytes - 1)))
4302 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4304 if (gpa == UNMAPPED_GVA ||
4305 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4308 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4311 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
4312 if (is_error_page(page))
4315 kaddr = kmap_atomic(page);
4316 kaddr += offset_in_page(gpa);
4319 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4322 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4325 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
4328 exchanged = CMPXCHG64(kaddr, old, new);
4333 kunmap_atomic(kaddr);
4334 kvm_release_page_dirty(page);
4337 return X86EMUL_CMPXCHG_FAILED;
4339 kvm_mmu_pte_write(vcpu, gpa, new, bytes);
4341 return X86EMUL_CONTINUE;
4344 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
4346 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
4349 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
4351 /* TODO: String I/O for in kernel device */
4354 if (vcpu->arch.pio.in)
4355 r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
4356 vcpu->arch.pio.size, pd);
4358 r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
4359 vcpu->arch.pio.port, vcpu->arch.pio.size,
4364 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
4365 unsigned short port, void *val,
4366 unsigned int count, bool in)
4368 trace_kvm_pio(!in, port, size, count);
4370 vcpu->arch.pio.port = port;
4371 vcpu->arch.pio.in = in;
4372 vcpu->arch.pio.count = count;
4373 vcpu->arch.pio.size = size;
4375 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4376 vcpu->arch.pio.count = 0;
4380 vcpu->run->exit_reason = KVM_EXIT_IO;
4381 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
4382 vcpu->run->io.size = size;
4383 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4384 vcpu->run->io.count = count;
4385 vcpu->run->io.port = port;
4390 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
4391 int size, unsigned short port, void *val,
4394 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4397 if (vcpu->arch.pio.count)
4400 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
4403 memcpy(val, vcpu->arch.pio_data, size * count);
4404 vcpu->arch.pio.count = 0;
4411 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
4412 int size, unsigned short port,
4413 const void *val, unsigned int count)
4415 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4417 memcpy(vcpu->arch.pio_data, val, size * count);
4418 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
4421 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
4423 return kvm_x86_ops->get_segment_base(vcpu, seg);
4426 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
4428 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
4431 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
4433 if (!need_emulate_wbinvd(vcpu))
4434 return X86EMUL_CONTINUE;
4436 if (kvm_x86_ops->has_wbinvd_exit()) {
4437 int cpu = get_cpu();
4439 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4440 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
4441 wbinvd_ipi, NULL, 1);
4443 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
4446 return X86EMUL_CONTINUE;
4448 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
4450 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
4452 kvm_emulate_wbinvd(emul_to_vcpu(ctxt));
4455 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
4457 return _kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
4460 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
4463 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
4466 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
4468 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
4471 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
4473 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4474 unsigned long value;
4478 value = kvm_read_cr0(vcpu);
4481 value = vcpu->arch.cr2;
4484 value = kvm_read_cr3(vcpu);
4487 value = kvm_read_cr4(vcpu);
4490 value = kvm_get_cr8(vcpu);
4493 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4500 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
4502 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4507 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4510 vcpu->arch.cr2 = val;
4513 res = kvm_set_cr3(vcpu, val);
4516 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4519 res = kvm_set_cr8(vcpu, val);
4522 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4529 static void emulator_set_rflags(struct x86_emulate_ctxt *ctxt, ulong val)
4531 kvm_set_rflags(emul_to_vcpu(ctxt), val);
4534 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
4536 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
4539 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4541 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
4544 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4546 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
4549 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4551 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4554 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4556 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4559 static unsigned long emulator_get_cached_segment_base(
4560 struct x86_emulate_ctxt *ctxt, int seg)
4562 return get_segment_base(emul_to_vcpu(ctxt), seg);
4565 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4566 struct desc_struct *desc, u32 *base3,
4569 struct kvm_segment var;
4571 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
4572 *selector = var.selector;
4575 memset(desc, 0, sizeof(*desc));
4581 set_desc_limit(desc, var.limit);
4582 set_desc_base(desc, (unsigned long)var.base);
4583 #ifdef CONFIG_X86_64
4585 *base3 = var.base >> 32;
4587 desc->type = var.type;
4589 desc->dpl = var.dpl;
4590 desc->p = var.present;
4591 desc->avl = var.avl;
4599 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
4600 struct desc_struct *desc, u32 base3,
4603 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4604 struct kvm_segment var;
4606 var.selector = selector;
4607 var.base = get_desc_base(desc);
4608 #ifdef CONFIG_X86_64
4609 var.base |= ((u64)base3) << 32;
4611 var.limit = get_desc_limit(desc);
4613 var.limit = (var.limit << 12) | 0xfff;
4614 var.type = desc->type;
4615 var.present = desc->p;
4616 var.dpl = desc->dpl;
4621 var.avl = desc->avl;
4622 var.present = desc->p;
4623 var.unusable = !var.present;
4626 kvm_set_segment(vcpu, &var, seg);
4630 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
4631 u32 msr_index, u64 *pdata)
4633 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
4636 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
4637 u32 msr_index, u64 data)
4639 struct msr_data msr;
4642 msr.index = msr_index;
4643 msr.host_initiated = false;
4644 return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
4647 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
4648 u32 pmc, u64 *pdata)
4650 return kvm_pmu_read_pmc(emul_to_vcpu(ctxt), pmc, pdata);
4653 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
4655 emul_to_vcpu(ctxt)->arch.halt_request = 1;
4658 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
4661 kvm_load_guest_fpu(emul_to_vcpu(ctxt));
4663 * CR0.TS may reference the host fpu state, not the guest fpu state,
4664 * so it may be clear at this point.
4669 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
4674 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
4675 struct x86_instruction_info *info,
4676 enum x86_intercept_stage stage)
4678 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
4681 static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
4682 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
4684 kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
4687 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
4689 return kvm_register_read(emul_to_vcpu(ctxt), reg);
4692 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
4694 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
4697 static const struct x86_emulate_ops emulate_ops = {
4698 .read_gpr = emulator_read_gpr,
4699 .write_gpr = emulator_write_gpr,
4700 .read_std = kvm_read_guest_virt_system,
4701 .write_std = kvm_write_guest_virt_system,
4702 .fetch = kvm_fetch_guest_virt,
4703 .read_emulated = emulator_read_emulated,
4704 .write_emulated = emulator_write_emulated,
4705 .cmpxchg_emulated = emulator_cmpxchg_emulated,
4706 .invlpg = emulator_invlpg,
4707 .pio_in_emulated = emulator_pio_in_emulated,
4708 .pio_out_emulated = emulator_pio_out_emulated,
4709 .get_segment = emulator_get_segment,
4710 .set_segment = emulator_set_segment,
4711 .get_cached_segment_base = emulator_get_cached_segment_base,
4712 .get_gdt = emulator_get_gdt,
4713 .get_idt = emulator_get_idt,
4714 .set_gdt = emulator_set_gdt,
4715 .set_idt = emulator_set_idt,
4716 .get_cr = emulator_get_cr,
4717 .set_cr = emulator_set_cr,
4718 .set_rflags = emulator_set_rflags,
4719 .cpl = emulator_get_cpl,
4720 .get_dr = emulator_get_dr,
4721 .set_dr = emulator_set_dr,
4722 .set_msr = emulator_set_msr,
4723 .get_msr = emulator_get_msr,
4724 .read_pmc = emulator_read_pmc,
4725 .halt = emulator_halt,
4726 .wbinvd = emulator_wbinvd,
4727 .fix_hypercall = emulator_fix_hypercall,
4728 .get_fpu = emulator_get_fpu,
4729 .put_fpu = emulator_put_fpu,
4730 .intercept = emulator_intercept,
4731 .get_cpuid = emulator_get_cpuid,
4734 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
4736 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu, mask);
4738 * an sti; sti; sequence only disable interrupts for the first
4739 * instruction. So, if the last instruction, be it emulated or
4740 * not, left the system with the INT_STI flag enabled, it
4741 * means that the last instruction is an sti. We should not
4742 * leave the flag on in this case. The same goes for mov ss
4744 if (!(int_shadow & mask))
4745 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
4748 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
4750 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4751 if (ctxt->exception.vector == PF_VECTOR)
4752 kvm_propagate_fault(vcpu, &ctxt->exception);
4753 else if (ctxt->exception.error_code_valid)
4754 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
4755 ctxt->exception.error_code);
4757 kvm_queue_exception(vcpu, ctxt->exception.vector);
4760 static void init_decode_cache(struct x86_emulate_ctxt *ctxt)
4762 memset(&ctxt->opcode_len, 0,
4763 (void *)&ctxt->_regs - (void *)&ctxt->opcode_len);
4765 ctxt->fetch.start = 0;
4766 ctxt->fetch.end = 0;
4767 ctxt->io_read.pos = 0;
4768 ctxt->io_read.end = 0;
4769 ctxt->mem_read.pos = 0;
4770 ctxt->mem_read.end = 0;
4773 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
4775 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4778 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4780 ctxt->eflags = kvm_get_rflags(vcpu);
4781 ctxt->eip = kvm_rip_read(vcpu);
4782 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
4783 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
4784 cs_l ? X86EMUL_MODE_PROT64 :
4785 cs_db ? X86EMUL_MODE_PROT32 :
4786 X86EMUL_MODE_PROT16;
4787 ctxt->guest_mode = is_guest_mode(vcpu);
4789 init_decode_cache(ctxt);
4790 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
4793 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
4795 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4798 init_emulate_ctxt(vcpu);
4802 ctxt->_eip = ctxt->eip + inc_eip;
4803 ret = emulate_int_real(ctxt, irq);
4805 if (ret != X86EMUL_CONTINUE)
4806 return EMULATE_FAIL;
4808 ctxt->eip = ctxt->_eip;
4809 kvm_rip_write(vcpu, ctxt->eip);
4810 kvm_set_rflags(vcpu, ctxt->eflags);
4812 if (irq == NMI_VECTOR)
4813 vcpu->arch.nmi_pending = 0;
4815 vcpu->arch.interrupt.pending = false;
4817 return EMULATE_DONE;
4819 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
4821 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
4823 int r = EMULATE_DONE;
4825 ++vcpu->stat.insn_emulation_fail;
4826 trace_kvm_emulate_insn_failed(vcpu);
4827 if (!is_guest_mode(vcpu)) {
4828 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4829 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
4830 vcpu->run->internal.ndata = 0;
4833 kvm_queue_exception(vcpu, UD_VECTOR);
4838 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
4839 bool write_fault_to_shadow_pgtable,
4845 if (emulation_type & EMULTYPE_NO_REEXECUTE)
4848 if (!vcpu->arch.mmu.direct_map) {
4850 * Write permission should be allowed since only
4851 * write access need to be emulated.
4853 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
4856 * If the mapping is invalid in guest, let cpu retry
4857 * it to generate fault.
4859 if (gpa == UNMAPPED_GVA)
4864 * Do not retry the unhandleable instruction if it faults on the
4865 * readonly host memory, otherwise it will goto a infinite loop:
4866 * retry instruction -> write #PF -> emulation fail -> retry
4867 * instruction -> ...
4869 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
4872 * If the instruction failed on the error pfn, it can not be fixed,
4873 * report the error to userspace.
4875 if (is_error_noslot_pfn(pfn))
4878 kvm_release_pfn_clean(pfn);
4880 /* The instructions are well-emulated on direct mmu. */
4881 if (vcpu->arch.mmu.direct_map) {
4882 unsigned int indirect_shadow_pages;
4884 spin_lock(&vcpu->kvm->mmu_lock);
4885 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
4886 spin_unlock(&vcpu->kvm->mmu_lock);
4888 if (indirect_shadow_pages)
4889 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
4895 * if emulation was due to access to shadowed page table
4896 * and it failed try to unshadow page and re-enter the
4897 * guest to let CPU execute the instruction.
4899 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
4902 * If the access faults on its page table, it can not
4903 * be fixed by unprotecting shadow page and it should
4904 * be reported to userspace.
4906 return !write_fault_to_shadow_pgtable;
4909 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
4910 unsigned long cr2, int emulation_type)
4912 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4913 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
4915 last_retry_eip = vcpu->arch.last_retry_eip;
4916 last_retry_addr = vcpu->arch.last_retry_addr;
4919 * If the emulation is caused by #PF and it is non-page_table
4920 * writing instruction, it means the VM-EXIT is caused by shadow
4921 * page protected, we can zap the shadow page and retry this
4922 * instruction directly.
4924 * Note: if the guest uses a non-page-table modifying instruction
4925 * on the PDE that points to the instruction, then we will unmap
4926 * the instruction and go to an infinite loop. So, we cache the
4927 * last retried eip and the last fault address, if we meet the eip
4928 * and the address again, we can break out of the potential infinite
4931 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
4933 if (!(emulation_type & EMULTYPE_RETRY))
4936 if (x86_page_table_writing_insn(ctxt))
4939 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
4942 vcpu->arch.last_retry_eip = ctxt->eip;
4943 vcpu->arch.last_retry_addr = cr2;
4945 if (!vcpu->arch.mmu.direct_map)
4946 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
4948 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
4953 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
4954 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
4956 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
4965 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
4966 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
4971 static void kvm_vcpu_check_singlestep(struct kvm_vcpu *vcpu, int *r)
4973 struct kvm_run *kvm_run = vcpu->run;
4976 * Use the "raw" value to see if TF was passed to the processor.
4977 * Note that the new value of the flags has not been saved yet.
4979 * This is correct even for TF set by the guest, because "the
4980 * processor will not generate this exception after the instruction
4981 * that sets the TF flag".
4983 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
4985 if (unlikely(rflags & X86_EFLAGS_TF)) {
4986 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
4987 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1;
4988 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
4989 kvm_run->debug.arch.exception = DB_VECTOR;
4990 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4991 *r = EMULATE_USER_EXIT;
4993 vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF;
4995 * "Certain debug exceptions may clear bit 0-3. The
4996 * remaining contents of the DR6 register are never
4997 * cleared by the processor".
4999 vcpu->arch.dr6 &= ~15;
5000 vcpu->arch.dr6 |= DR6_BS;
5001 kvm_queue_exception(vcpu, DB_VECTOR);
5006 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
5008 struct kvm_run *kvm_run = vcpu->run;
5009 unsigned long eip = vcpu->arch.emulate_ctxt.eip;
5012 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
5013 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
5014 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5015 vcpu->arch.guest_debug_dr7,
5019 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
5020 kvm_run->debug.arch.pc = kvm_rip_read(vcpu) +
5021 get_segment_base(vcpu, VCPU_SREG_CS);
5023 kvm_run->debug.arch.exception = DB_VECTOR;
5024 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5025 *r = EMULATE_USER_EXIT;
5030 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK)) {
5031 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5036 vcpu->arch.dr6 &= ~15;
5037 vcpu->arch.dr6 |= dr6;
5038 kvm_queue_exception(vcpu, DB_VECTOR);
5047 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
5054 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5055 bool writeback = true;
5056 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
5059 * Clear write_fault_to_shadow_pgtable here to ensure it is
5062 vcpu->arch.write_fault_to_shadow_pgtable = false;
5063 kvm_clear_exception_queue(vcpu);
5065 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
5066 init_emulate_ctxt(vcpu);
5069 * We will reenter on the same instruction since
5070 * we do not set complete_userspace_io. This does not
5071 * handle watchpoints yet, those would be handled in
5074 if (kvm_vcpu_check_breakpoint(vcpu, &r))
5077 ctxt->interruptibility = 0;
5078 ctxt->have_exception = false;
5079 ctxt->perm_ok = false;
5081 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
5083 r = x86_decode_insn(ctxt, insn, insn_len);
5085 trace_kvm_emulate_insn_start(vcpu);
5086 ++vcpu->stat.insn_emulation;
5087 if (r != EMULATION_OK) {
5088 if (emulation_type & EMULTYPE_TRAP_UD)
5089 return EMULATE_FAIL;
5090 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5092 return EMULATE_DONE;
5093 if (emulation_type & EMULTYPE_SKIP)
5094 return EMULATE_FAIL;
5095 return handle_emulation_failure(vcpu);
5099 if (emulation_type & EMULTYPE_SKIP) {
5100 kvm_rip_write(vcpu, ctxt->_eip);
5101 return EMULATE_DONE;
5104 if (retry_instruction(ctxt, cr2, emulation_type))
5105 return EMULATE_DONE;
5107 /* this is needed for vmware backdoor interface to work since it
5108 changes registers values during IO operation */
5109 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
5110 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5111 emulator_invalidate_register_cache(ctxt);
5115 r = x86_emulate_insn(ctxt);
5117 if (r == EMULATION_INTERCEPTED)
5118 return EMULATE_DONE;
5120 if (r == EMULATION_FAILED) {
5121 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5123 return EMULATE_DONE;
5125 return handle_emulation_failure(vcpu);
5128 if (ctxt->have_exception) {
5129 inject_emulated_exception(vcpu);
5131 } else if (vcpu->arch.pio.count) {
5132 if (!vcpu->arch.pio.in) {
5133 /* FIXME: return into emulator if single-stepping. */
5134 vcpu->arch.pio.count = 0;
5137 vcpu->arch.complete_userspace_io = complete_emulated_pio;
5139 r = EMULATE_USER_EXIT;
5140 } else if (vcpu->mmio_needed) {
5141 if (!vcpu->mmio_is_write)
5143 r = EMULATE_USER_EXIT;
5144 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
5145 } else if (r == EMULATION_RESTART)
5151 toggle_interruptibility(vcpu, ctxt->interruptibility);
5152 kvm_make_request(KVM_REQ_EVENT, vcpu);
5153 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5154 kvm_rip_write(vcpu, ctxt->eip);
5155 if (r == EMULATE_DONE)
5156 kvm_vcpu_check_singlestep(vcpu, &r);
5157 kvm_set_rflags(vcpu, ctxt->eflags);
5159 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5163 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5165 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5167 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5168 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5169 size, port, &val, 1);
5170 /* do not return to emulator after return from userspace */
5171 vcpu->arch.pio.count = 0;
5174 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5176 static void tsc_bad(void *info)
5178 __this_cpu_write(cpu_tsc_khz, 0);
5181 static void tsc_khz_changed(void *data)
5183 struct cpufreq_freqs *freq = data;
5184 unsigned long khz = 0;
5188 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5189 khz = cpufreq_quick_get(raw_smp_processor_id());
5192 __this_cpu_write(cpu_tsc_khz, khz);
5195 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5198 struct cpufreq_freqs *freq = data;
5200 struct kvm_vcpu *vcpu;
5201 int i, send_ipi = 0;
5204 * We allow guests to temporarily run on slowing clocks,
5205 * provided we notify them after, or to run on accelerating
5206 * clocks, provided we notify them before. Thus time never
5209 * However, we have a problem. We can't atomically update
5210 * the frequency of a given CPU from this function; it is
5211 * merely a notifier, which can be called from any CPU.
5212 * Changing the TSC frequency at arbitrary points in time
5213 * requires a recomputation of local variables related to
5214 * the TSC for each VCPU. We must flag these local variables
5215 * to be updated and be sure the update takes place with the
5216 * new frequency before any guests proceed.
5218 * Unfortunately, the combination of hotplug CPU and frequency
5219 * change creates an intractable locking scenario; the order
5220 * of when these callouts happen is undefined with respect to
5221 * CPU hotplug, and they can race with each other. As such,
5222 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5223 * undefined; you can actually have a CPU frequency change take
5224 * place in between the computation of X and the setting of the
5225 * variable. To protect against this problem, all updates of
5226 * the per_cpu tsc_khz variable are done in an interrupt
5227 * protected IPI, and all callers wishing to update the value
5228 * must wait for a synchronous IPI to complete (which is trivial
5229 * if the caller is on the CPU already). This establishes the
5230 * necessary total order on variable updates.
5232 * Note that because a guest time update may take place
5233 * anytime after the setting of the VCPU's request bit, the
5234 * correct TSC value must be set before the request. However,
5235 * to ensure the update actually makes it to any guest which
5236 * starts running in hardware virtualization between the set
5237 * and the acquisition of the spinlock, we must also ping the
5238 * CPU after setting the request bit.
5242 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
5244 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
5247 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5249 spin_lock(&kvm_lock);
5250 list_for_each_entry(kvm, &vm_list, vm_list) {
5251 kvm_for_each_vcpu(i, vcpu, kvm) {
5252 if (vcpu->cpu != freq->cpu)
5254 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5255 if (vcpu->cpu != smp_processor_id())
5259 spin_unlock(&kvm_lock);
5261 if (freq->old < freq->new && send_ipi) {
5263 * We upscale the frequency. Must make the guest
5264 * doesn't see old kvmclock values while running with
5265 * the new frequency, otherwise we risk the guest sees
5266 * time go backwards.
5268 * In case we update the frequency for another cpu
5269 * (which might be in guest context) send an interrupt
5270 * to kick the cpu out of guest context. Next time
5271 * guest context is entered kvmclock will be updated,
5272 * so the guest will not see stale values.
5274 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5279 static struct notifier_block kvmclock_cpufreq_notifier_block = {
5280 .notifier_call = kvmclock_cpufreq_notifier
5283 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
5284 unsigned long action, void *hcpu)
5286 unsigned int cpu = (unsigned long)hcpu;
5290 case CPU_DOWN_FAILED:
5291 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5293 case CPU_DOWN_PREPARE:
5294 smp_call_function_single(cpu, tsc_bad, NULL, 1);
5300 static struct notifier_block kvmclock_cpu_notifier_block = {
5301 .notifier_call = kvmclock_cpu_notifier,
5302 .priority = -INT_MAX
5305 static void kvm_timer_init(void)
5309 max_tsc_khz = tsc_khz;
5310 register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5311 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5312 #ifdef CONFIG_CPU_FREQ
5313 struct cpufreq_policy policy;
5314 memset(&policy, 0, sizeof(policy));
5316 cpufreq_get_policy(&policy, cpu);
5317 if (policy.cpuinfo.max_freq)
5318 max_tsc_khz = policy.cpuinfo.max_freq;
5321 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
5322 CPUFREQ_TRANSITION_NOTIFIER);
5324 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
5325 for_each_online_cpu(cpu)
5326 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5329 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
5331 int kvm_is_in_guest(void)
5333 return __this_cpu_read(current_vcpu) != NULL;
5336 static int kvm_is_user_mode(void)
5340 if (__this_cpu_read(current_vcpu))
5341 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
5343 return user_mode != 0;
5346 static unsigned long kvm_get_guest_ip(void)
5348 unsigned long ip = 0;
5350 if (__this_cpu_read(current_vcpu))
5351 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
5356 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5357 .is_in_guest = kvm_is_in_guest,
5358 .is_user_mode = kvm_is_user_mode,
5359 .get_guest_ip = kvm_get_guest_ip,
5362 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
5364 __this_cpu_write(current_vcpu, vcpu);
5366 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
5368 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
5370 __this_cpu_write(current_vcpu, NULL);
5372 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
5374 static void kvm_set_mmio_spte_mask(void)
5377 int maxphyaddr = boot_cpu_data.x86_phys_bits;
5380 * Set the reserved bits and the present bit of an paging-structure
5381 * entry to generate page fault with PFER.RSV = 1.
5383 /* Mask the reserved physical address bits. */
5384 mask = ((1ull << (51 - maxphyaddr + 1)) - 1) << maxphyaddr;
5386 /* Bit 62 is always reserved for 32bit host. */
5387 mask |= 0x3ull << 62;
5389 /* Set the present bit. */
5392 #ifdef CONFIG_X86_64
5394 * If reserved bit is not supported, clear the present bit to disable
5397 if (maxphyaddr == 52)
5401 kvm_mmu_set_mmio_spte_mask(mask);
5404 #ifdef CONFIG_X86_64
5405 static void pvclock_gtod_update_fn(struct work_struct *work)
5409 struct kvm_vcpu *vcpu;
5412 spin_lock(&kvm_lock);
5413 list_for_each_entry(kvm, &vm_list, vm_list)
5414 kvm_for_each_vcpu(i, vcpu, kvm)
5415 set_bit(KVM_REQ_MASTERCLOCK_UPDATE, &vcpu->requests);
5416 atomic_set(&kvm_guest_has_master_clock, 0);
5417 spin_unlock(&kvm_lock);
5420 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
5423 * Notification about pvclock gtod data update.
5425 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
5428 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
5429 struct timekeeper *tk = priv;
5431 update_pvclock_gtod(tk);
5433 /* disable master clock if host does not trust, or does not
5434 * use, TSC clocksource
5436 if (gtod->clock.vclock_mode != VCLOCK_TSC &&
5437 atomic_read(&kvm_guest_has_master_clock) != 0)
5438 queue_work(system_long_wq, &pvclock_gtod_work);
5443 static struct notifier_block pvclock_gtod_notifier = {
5444 .notifier_call = pvclock_gtod_notify,
5448 int kvm_arch_init(void *opaque)
5451 struct kvm_x86_ops *ops = opaque;
5454 printk(KERN_ERR "kvm: already loaded the other module\n");
5459 if (!ops->cpu_has_kvm_support()) {
5460 printk(KERN_ERR "kvm: no hardware support\n");
5464 if (ops->disabled_by_bios()) {
5465 printk(KERN_ERR "kvm: disabled by bios\n");
5471 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
5473 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
5477 r = kvm_mmu_module_init();
5479 goto out_free_percpu;
5481 kvm_set_mmio_spte_mask();
5482 kvm_init_msr_list();
5485 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
5486 PT_DIRTY_MASK, PT64_NX_MASK, 0);
5490 perf_register_guest_info_callbacks(&kvm_guest_cbs);
5493 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
5496 #ifdef CONFIG_X86_64
5497 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
5503 free_percpu(shared_msrs);
5508 void kvm_arch_exit(void)
5510 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
5512 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5513 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
5514 CPUFREQ_TRANSITION_NOTIFIER);
5515 unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5516 #ifdef CONFIG_X86_64
5517 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
5520 kvm_mmu_module_exit();
5521 free_percpu(shared_msrs);
5524 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
5526 ++vcpu->stat.halt_exits;
5527 if (irqchip_in_kernel(vcpu->kvm)) {
5528 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
5531 vcpu->run->exit_reason = KVM_EXIT_HLT;
5535 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
5537 int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
5539 u64 param, ingpa, outgpa, ret;
5540 uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
5541 bool fast, longmode;
5545 * hypercall generates UD from non zero cpl and real mode
5548 if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
5549 kvm_queue_exception(vcpu, UD_VECTOR);
5553 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5554 longmode = is_long_mode(vcpu) && cs_l == 1;
5557 param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
5558 (kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
5559 ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
5560 (kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
5561 outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
5562 (kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
5564 #ifdef CONFIG_X86_64
5566 param = kvm_register_read(vcpu, VCPU_REGS_RCX);
5567 ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
5568 outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
5572 code = param & 0xffff;
5573 fast = (param >> 16) & 0x1;
5574 rep_cnt = (param >> 32) & 0xfff;
5575 rep_idx = (param >> 48) & 0xfff;
5577 trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
5580 case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
5581 kvm_vcpu_on_spin(vcpu);
5584 res = HV_STATUS_INVALID_HYPERCALL_CODE;
5588 ret = res | (((u64)rep_done & 0xfff) << 32);
5590 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
5592 kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
5593 kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
5600 * kvm_pv_kick_cpu_op: Kick a vcpu.
5602 * @apicid - apicid of vcpu to be kicked.
5604 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
5606 struct kvm_lapic_irq lapic_irq;
5608 lapic_irq.shorthand = 0;
5609 lapic_irq.dest_mode = 0;
5610 lapic_irq.dest_id = apicid;
5612 lapic_irq.delivery_mode = APIC_DM_REMRD;
5613 kvm_irq_delivery_to_apic(kvm, 0, &lapic_irq, NULL);
5616 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
5618 unsigned long nr, a0, a1, a2, a3, ret;
5621 if (kvm_hv_hypercall_enabled(vcpu->kvm))
5622 return kvm_hv_hypercall(vcpu);
5624 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
5625 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
5626 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
5627 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
5628 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
5630 trace_kvm_hypercall(nr, a0, a1, a2, a3);
5632 if (!is_long_mode(vcpu)) {
5640 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
5646 case KVM_HC_VAPIC_POLL_IRQ:
5649 case KVM_HC_KICK_CPU:
5650 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
5658 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
5659 ++vcpu->stat.hypercalls;
5662 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
5664 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
5666 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5667 char instruction[3];
5668 unsigned long rip = kvm_rip_read(vcpu);
5670 kvm_x86_ops->patch_hypercall(vcpu, instruction);
5672 return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
5676 * Check if userspace requested an interrupt window, and that the
5677 * interrupt window is open.
5679 * No need to exit to userspace if we already have an interrupt queued.
5681 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
5683 return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
5684 vcpu->run->request_interrupt_window &&
5685 kvm_arch_interrupt_allowed(vcpu));
5688 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
5690 struct kvm_run *kvm_run = vcpu->run;
5692 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
5693 kvm_run->cr8 = kvm_get_cr8(vcpu);
5694 kvm_run->apic_base = kvm_get_apic_base(vcpu);
5695 if (irqchip_in_kernel(vcpu->kvm))
5696 kvm_run->ready_for_interrupt_injection = 1;
5698 kvm_run->ready_for_interrupt_injection =
5699 kvm_arch_interrupt_allowed(vcpu) &&
5700 !kvm_cpu_has_interrupt(vcpu) &&
5701 !kvm_event_needs_reinjection(vcpu);
5704 static int vapic_enter(struct kvm_vcpu *vcpu)
5706 struct kvm_lapic *apic = vcpu->arch.apic;
5709 if (!apic || !apic->vapic_addr)
5712 page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
5713 if (is_error_page(page))
5716 vcpu->arch.apic->vapic_page = page;
5720 static void vapic_exit(struct kvm_vcpu *vcpu)
5722 struct kvm_lapic *apic = vcpu->arch.apic;
5725 if (!apic || !apic->vapic_addr)
5728 idx = srcu_read_lock(&vcpu->kvm->srcu);
5729 kvm_release_page_dirty(apic->vapic_page);
5730 mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
5731 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5734 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
5738 if (!kvm_x86_ops->update_cr8_intercept)
5741 if (!vcpu->arch.apic)
5744 if (!vcpu->arch.apic->vapic_addr)
5745 max_irr = kvm_lapic_find_highest_irr(vcpu);
5752 tpr = kvm_lapic_get_cr8(vcpu);
5754 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
5757 static void inject_pending_event(struct kvm_vcpu *vcpu)
5759 /* try to reinject previous events if any */
5760 if (vcpu->arch.exception.pending) {
5761 trace_kvm_inj_exception(vcpu->arch.exception.nr,
5762 vcpu->arch.exception.has_error_code,
5763 vcpu->arch.exception.error_code);
5764 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
5765 vcpu->arch.exception.has_error_code,
5766 vcpu->arch.exception.error_code,
5767 vcpu->arch.exception.reinject);
5771 if (vcpu->arch.nmi_injected) {
5772 kvm_x86_ops->set_nmi(vcpu);
5776 if (vcpu->arch.interrupt.pending) {
5777 kvm_x86_ops->set_irq(vcpu);
5781 /* try to inject new event if pending */
5782 if (vcpu->arch.nmi_pending) {
5783 if (kvm_x86_ops->nmi_allowed(vcpu)) {
5784 --vcpu->arch.nmi_pending;
5785 vcpu->arch.nmi_injected = true;
5786 kvm_x86_ops->set_nmi(vcpu);
5788 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
5789 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
5790 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
5792 kvm_x86_ops->set_irq(vcpu);
5797 static void process_nmi(struct kvm_vcpu *vcpu)
5802 * x86 is limited to one NMI running, and one NMI pending after it.
5803 * If an NMI is already in progress, limit further NMIs to just one.
5804 * Otherwise, allow two (and we'll inject the first one immediately).
5806 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
5809 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
5810 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
5811 kvm_make_request(KVM_REQ_EVENT, vcpu);
5814 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
5816 u64 eoi_exit_bitmap[4];
5819 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
5822 memset(eoi_exit_bitmap, 0, 32);
5825 kvm_ioapic_scan_entry(vcpu, eoi_exit_bitmap, tmr);
5826 kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
5827 kvm_apic_update_tmr(vcpu, tmr);
5831 * Returns 1 to let __vcpu_run() continue the guest execution loop without
5832 * exiting to the userspace. Otherwise, the value will be returned to the
5835 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
5838 bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
5839 vcpu->run->request_interrupt_window;
5840 bool req_immediate_exit = false;
5842 if (vcpu->requests) {
5843 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
5844 kvm_mmu_unload(vcpu);
5845 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
5846 __kvm_migrate_timers(vcpu);
5847 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
5848 kvm_gen_update_masterclock(vcpu->kvm);
5849 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
5850 kvm_gen_kvmclock_update(vcpu);
5851 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
5852 r = kvm_guest_time_update(vcpu);
5856 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
5857 kvm_mmu_sync_roots(vcpu);
5858 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
5859 kvm_x86_ops->tlb_flush(vcpu);
5860 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
5861 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
5865 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
5866 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5870 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
5871 vcpu->fpu_active = 0;
5872 kvm_x86_ops->fpu_deactivate(vcpu);
5874 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
5875 /* Page is swapped out. Do synthetic halt */
5876 vcpu->arch.apf.halted = true;
5880 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
5881 record_steal_time(vcpu);
5882 if (kvm_check_request(KVM_REQ_NMI, vcpu))
5884 if (kvm_check_request(KVM_REQ_PMU, vcpu))
5885 kvm_handle_pmu_event(vcpu);
5886 if (kvm_check_request(KVM_REQ_PMI, vcpu))
5887 kvm_deliver_pmi(vcpu);
5888 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
5889 vcpu_scan_ioapic(vcpu);
5892 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
5893 kvm_apic_accept_events(vcpu);
5894 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
5899 inject_pending_event(vcpu);
5901 /* enable NMI/IRQ window open exits if needed */
5902 if (vcpu->arch.nmi_pending)
5903 req_immediate_exit =
5904 kvm_x86_ops->enable_nmi_window(vcpu) != 0;
5905 else if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
5906 req_immediate_exit =
5907 kvm_x86_ops->enable_irq_window(vcpu) != 0;
5909 if (kvm_lapic_enabled(vcpu)) {
5911 * Update architecture specific hints for APIC
5912 * virtual interrupt delivery.
5914 if (kvm_x86_ops->hwapic_irr_update)
5915 kvm_x86_ops->hwapic_irr_update(vcpu,
5916 kvm_lapic_find_highest_irr(vcpu));
5917 update_cr8_intercept(vcpu);
5918 kvm_lapic_sync_to_vapic(vcpu);
5922 r = kvm_mmu_reload(vcpu);
5924 goto cancel_injection;
5929 kvm_x86_ops->prepare_guest_switch(vcpu);
5930 if (vcpu->fpu_active)
5931 kvm_load_guest_fpu(vcpu);
5932 kvm_load_guest_xcr0(vcpu);
5934 vcpu->mode = IN_GUEST_MODE;
5936 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
5938 /* We should set ->mode before check ->requests,
5939 * see the comment in make_all_cpus_request.
5941 smp_mb__after_srcu_read_unlock();
5943 local_irq_disable();
5945 if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
5946 || need_resched() || signal_pending(current)) {
5947 vcpu->mode = OUTSIDE_GUEST_MODE;
5951 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
5953 goto cancel_injection;
5956 if (req_immediate_exit)
5957 smp_send_reschedule(vcpu->cpu);
5961 if (unlikely(vcpu->arch.switch_db_regs)) {
5963 set_debugreg(vcpu->arch.eff_db[0], 0);
5964 set_debugreg(vcpu->arch.eff_db[1], 1);
5965 set_debugreg(vcpu->arch.eff_db[2], 2);
5966 set_debugreg(vcpu->arch.eff_db[3], 3);
5969 trace_kvm_entry(vcpu->vcpu_id);
5970 kvm_x86_ops->run(vcpu);
5973 * If the guest has used debug registers, at least dr7
5974 * will be disabled while returning to the host.
5975 * If we don't have active breakpoints in the host, we don't
5976 * care about the messed up debug address registers. But if
5977 * we have some of them active, restore the old state.
5979 if (hw_breakpoint_active())
5980 hw_breakpoint_restore();
5982 vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu,
5985 vcpu->mode = OUTSIDE_GUEST_MODE;
5988 /* Interrupt is enabled by handle_external_intr() */
5989 kvm_x86_ops->handle_external_intr(vcpu);
5994 * We must have an instruction between local_irq_enable() and
5995 * kvm_guest_exit(), so the timer interrupt isn't delayed by
5996 * the interrupt shadow. The stat.exits increment will do nicely.
5997 * But we need to prevent reordering, hence this barrier():
6005 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6008 * Profile KVM exit RIPs:
6010 if (unlikely(prof_on == KVM_PROFILING)) {
6011 unsigned long rip = kvm_rip_read(vcpu);
6012 profile_hit(KVM_PROFILING, (void *)rip);
6015 if (unlikely(vcpu->arch.tsc_always_catchup))
6016 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6018 if (vcpu->arch.apic_attention)
6019 kvm_lapic_sync_from_vapic(vcpu);
6021 r = kvm_x86_ops->handle_exit(vcpu);
6025 kvm_x86_ops->cancel_injection(vcpu);
6026 if (unlikely(vcpu->arch.apic_attention))
6027 kvm_lapic_sync_from_vapic(vcpu);
6033 static int __vcpu_run(struct kvm_vcpu *vcpu)
6036 struct kvm *kvm = vcpu->kvm;
6038 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6039 r = vapic_enter(vcpu);
6041 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6047 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6048 !vcpu->arch.apf.halted)
6049 r = vcpu_enter_guest(vcpu);
6051 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6052 kvm_vcpu_block(vcpu);
6053 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6054 if (kvm_check_request(KVM_REQ_UNHALT, vcpu)) {
6055 kvm_apic_accept_events(vcpu);
6056 switch(vcpu->arch.mp_state) {
6057 case KVM_MP_STATE_HALTED:
6058 vcpu->arch.pv.pv_unhalted = false;
6059 vcpu->arch.mp_state =
6060 KVM_MP_STATE_RUNNABLE;
6061 case KVM_MP_STATE_RUNNABLE:
6062 vcpu->arch.apf.halted = false;
6064 case KVM_MP_STATE_INIT_RECEIVED:
6076 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
6077 if (kvm_cpu_has_pending_timer(vcpu))
6078 kvm_inject_pending_timer_irqs(vcpu);
6080 if (dm_request_for_irq_injection(vcpu)) {
6082 vcpu->run->exit_reason = KVM_EXIT_INTR;
6083 ++vcpu->stat.request_irq_exits;
6086 kvm_check_async_pf_completion(vcpu);
6088 if (signal_pending(current)) {
6090 vcpu->run->exit_reason = KVM_EXIT_INTR;
6091 ++vcpu->stat.signal_exits;
6093 if (need_resched()) {
6094 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6096 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6100 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6107 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
6110 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6111 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
6112 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6113 if (r != EMULATE_DONE)
6118 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
6120 BUG_ON(!vcpu->arch.pio.count);
6122 return complete_emulated_io(vcpu);
6126 * Implements the following, as a state machine:
6130 * for each mmio piece in the fragment
6138 * for each mmio piece in the fragment
6143 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
6145 struct kvm_run *run = vcpu->run;
6146 struct kvm_mmio_fragment *frag;
6149 BUG_ON(!vcpu->mmio_needed);
6151 /* Complete previous fragment */
6152 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
6153 len = min(8u, frag->len);
6154 if (!vcpu->mmio_is_write)
6155 memcpy(frag->data, run->mmio.data, len);
6157 if (frag->len <= 8) {
6158 /* Switch to the next fragment. */
6160 vcpu->mmio_cur_fragment++;
6162 /* Go forward to the next mmio piece. */
6168 if (vcpu->mmio_cur_fragment == vcpu->mmio_nr_fragments) {
6169 vcpu->mmio_needed = 0;
6171 /* FIXME: return into emulator if single-stepping. */
6172 if (vcpu->mmio_is_write)
6174 vcpu->mmio_read_completed = 1;
6175 return complete_emulated_io(vcpu);
6178 run->exit_reason = KVM_EXIT_MMIO;
6179 run->mmio.phys_addr = frag->gpa;
6180 if (vcpu->mmio_is_write)
6181 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
6182 run->mmio.len = min(8u, frag->len);
6183 run->mmio.is_write = vcpu->mmio_is_write;
6184 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6189 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
6194 if (!tsk_used_math(current) && init_fpu(current))
6197 if (vcpu->sigset_active)
6198 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
6200 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
6201 kvm_vcpu_block(vcpu);
6202 kvm_apic_accept_events(vcpu);
6203 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
6208 /* re-sync apic's tpr */
6209 if (!irqchip_in_kernel(vcpu->kvm)) {
6210 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
6216 if (unlikely(vcpu->arch.complete_userspace_io)) {
6217 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
6218 vcpu->arch.complete_userspace_io = NULL;
6223 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
6225 r = __vcpu_run(vcpu);
6228 post_kvm_run_save(vcpu);
6229 if (vcpu->sigset_active)
6230 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
6235 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6237 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
6239 * We are here if userspace calls get_regs() in the middle of
6240 * instruction emulation. Registers state needs to be copied
6241 * back from emulation context to vcpu. Userspace shouldn't do
6242 * that usually, but some bad designed PV devices (vmware
6243 * backdoor interface) need this to work
6245 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
6246 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6248 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
6249 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
6250 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
6251 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
6252 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
6253 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
6254 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
6255 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
6256 #ifdef CONFIG_X86_64
6257 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
6258 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
6259 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
6260 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
6261 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
6262 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
6263 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
6264 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
6267 regs->rip = kvm_rip_read(vcpu);
6268 regs->rflags = kvm_get_rflags(vcpu);
6273 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6275 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
6276 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6278 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
6279 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
6280 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
6281 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
6282 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
6283 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
6284 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
6285 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
6286 #ifdef CONFIG_X86_64
6287 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
6288 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
6289 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
6290 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
6291 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
6292 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
6293 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
6294 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
6297 kvm_rip_write(vcpu, regs->rip);
6298 kvm_set_rflags(vcpu, regs->rflags);
6300 vcpu->arch.exception.pending = false;
6302 kvm_make_request(KVM_REQ_EVENT, vcpu);
6307 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
6309 struct kvm_segment cs;
6311 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
6315 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
6317 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
6318 struct kvm_sregs *sregs)
6322 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6323 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6324 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6325 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6326 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6327 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6329 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6330 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6332 kvm_x86_ops->get_idt(vcpu, &dt);
6333 sregs->idt.limit = dt.size;
6334 sregs->idt.base = dt.address;
6335 kvm_x86_ops->get_gdt(vcpu, &dt);
6336 sregs->gdt.limit = dt.size;
6337 sregs->gdt.base = dt.address;
6339 sregs->cr0 = kvm_read_cr0(vcpu);
6340 sregs->cr2 = vcpu->arch.cr2;
6341 sregs->cr3 = kvm_read_cr3(vcpu);
6342 sregs->cr4 = kvm_read_cr4(vcpu);
6343 sregs->cr8 = kvm_get_cr8(vcpu);
6344 sregs->efer = vcpu->arch.efer;
6345 sregs->apic_base = kvm_get_apic_base(vcpu);
6347 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
6349 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
6350 set_bit(vcpu->arch.interrupt.nr,
6351 (unsigned long *)sregs->interrupt_bitmap);
6356 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
6357 struct kvm_mp_state *mp_state)
6359 kvm_apic_accept_events(vcpu);
6360 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
6361 vcpu->arch.pv.pv_unhalted)
6362 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
6364 mp_state->mp_state = vcpu->arch.mp_state;
6369 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
6370 struct kvm_mp_state *mp_state)
6372 if (!kvm_vcpu_has_lapic(vcpu) &&
6373 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
6376 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
6377 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
6378 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
6380 vcpu->arch.mp_state = mp_state->mp_state;
6381 kvm_make_request(KVM_REQ_EVENT, vcpu);
6385 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
6386 int reason, bool has_error_code, u32 error_code)
6388 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6391 init_emulate_ctxt(vcpu);
6393 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
6394 has_error_code, error_code);
6397 return EMULATE_FAIL;
6399 kvm_rip_write(vcpu, ctxt->eip);
6400 kvm_set_rflags(vcpu, ctxt->eflags);
6401 kvm_make_request(KVM_REQ_EVENT, vcpu);
6402 return EMULATE_DONE;
6404 EXPORT_SYMBOL_GPL(kvm_task_switch);
6406 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
6407 struct kvm_sregs *sregs)
6409 int mmu_reset_needed = 0;
6410 int pending_vec, max_bits, idx;
6413 if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
6416 dt.size = sregs->idt.limit;
6417 dt.address = sregs->idt.base;
6418 kvm_x86_ops->set_idt(vcpu, &dt);
6419 dt.size = sregs->gdt.limit;
6420 dt.address = sregs->gdt.base;
6421 kvm_x86_ops->set_gdt(vcpu, &dt);
6423 vcpu->arch.cr2 = sregs->cr2;
6424 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
6425 vcpu->arch.cr3 = sregs->cr3;
6426 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
6428 kvm_set_cr8(vcpu, sregs->cr8);
6430 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
6431 kvm_x86_ops->set_efer(vcpu, sregs->efer);
6432 kvm_set_apic_base(vcpu, sregs->apic_base);
6434 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
6435 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
6436 vcpu->arch.cr0 = sregs->cr0;
6438 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
6439 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
6440 if (sregs->cr4 & X86_CR4_OSXSAVE)
6441 kvm_update_cpuid(vcpu);
6443 idx = srcu_read_lock(&vcpu->kvm->srcu);
6444 if (!is_long_mode(vcpu) && is_pae(vcpu)) {
6445 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
6446 mmu_reset_needed = 1;
6448 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6450 if (mmu_reset_needed)
6451 kvm_mmu_reset_context(vcpu);
6453 max_bits = KVM_NR_INTERRUPTS;
6454 pending_vec = find_first_bit(
6455 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
6456 if (pending_vec < max_bits) {
6457 kvm_queue_interrupt(vcpu, pending_vec, false);
6458 pr_debug("Set back pending irq %d\n", pending_vec);
6461 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6462 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6463 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6464 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6465 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6466 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6468 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6469 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6471 update_cr8_intercept(vcpu);
6473 /* Older userspace won't unhalt the vcpu on reset. */
6474 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
6475 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
6477 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
6479 kvm_make_request(KVM_REQ_EVENT, vcpu);
6484 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
6485 struct kvm_guest_debug *dbg)
6487 unsigned long rflags;
6490 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
6492 if (vcpu->arch.exception.pending)
6494 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
6495 kvm_queue_exception(vcpu, DB_VECTOR);
6497 kvm_queue_exception(vcpu, BP_VECTOR);
6501 * Read rflags as long as potentially injected trace flags are still
6504 rflags = kvm_get_rflags(vcpu);
6506 vcpu->guest_debug = dbg->control;
6507 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
6508 vcpu->guest_debug = 0;
6510 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
6511 for (i = 0; i < KVM_NR_DB_REGS; ++i)
6512 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
6513 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
6515 for (i = 0; i < KVM_NR_DB_REGS; i++)
6516 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
6518 kvm_update_dr7(vcpu);
6520 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6521 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
6522 get_segment_base(vcpu, VCPU_SREG_CS);
6525 * Trigger an rflags update that will inject or remove the trace
6528 kvm_set_rflags(vcpu, rflags);
6530 kvm_x86_ops->update_db_bp_intercept(vcpu);
6540 * Translate a guest virtual address to a guest physical address.
6542 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
6543 struct kvm_translation *tr)
6545 unsigned long vaddr = tr->linear_address;
6549 idx = srcu_read_lock(&vcpu->kvm->srcu);
6550 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
6551 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6552 tr->physical_address = gpa;
6553 tr->valid = gpa != UNMAPPED_GVA;
6560 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
6562 struct i387_fxsave_struct *fxsave =
6563 &vcpu->arch.guest_fpu.state->fxsave;
6565 memcpy(fpu->fpr, fxsave->st_space, 128);
6566 fpu->fcw = fxsave->cwd;
6567 fpu->fsw = fxsave->swd;
6568 fpu->ftwx = fxsave->twd;
6569 fpu->last_opcode = fxsave->fop;
6570 fpu->last_ip = fxsave->rip;
6571 fpu->last_dp = fxsave->rdp;
6572 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
6577 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
6579 struct i387_fxsave_struct *fxsave =
6580 &vcpu->arch.guest_fpu.state->fxsave;
6582 memcpy(fxsave->st_space, fpu->fpr, 128);
6583 fxsave->cwd = fpu->fcw;
6584 fxsave->swd = fpu->fsw;
6585 fxsave->twd = fpu->ftwx;
6586 fxsave->fop = fpu->last_opcode;
6587 fxsave->rip = fpu->last_ip;
6588 fxsave->rdp = fpu->last_dp;
6589 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
6594 int fx_init(struct kvm_vcpu *vcpu)
6598 err = fpu_alloc(&vcpu->arch.guest_fpu);
6602 fpu_finit(&vcpu->arch.guest_fpu);
6605 * Ensure guest xcr0 is valid for loading
6607 vcpu->arch.xcr0 = XSTATE_FP;
6609 vcpu->arch.cr0 |= X86_CR0_ET;
6613 EXPORT_SYMBOL_GPL(fx_init);
6615 static void fx_free(struct kvm_vcpu *vcpu)
6617 fpu_free(&vcpu->arch.guest_fpu);
6620 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
6622 if (vcpu->guest_fpu_loaded)
6626 * Restore all possible states in the guest,
6627 * and assume host would use all available bits.
6628 * Guest xcr0 would be loaded later.
6630 kvm_put_guest_xcr0(vcpu);
6631 vcpu->guest_fpu_loaded = 1;
6632 __kernel_fpu_begin();
6633 fpu_restore_checking(&vcpu->arch.guest_fpu);
6637 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
6639 kvm_put_guest_xcr0(vcpu);
6641 if (!vcpu->guest_fpu_loaded)
6644 vcpu->guest_fpu_loaded = 0;
6645 fpu_save_init(&vcpu->arch.guest_fpu);
6647 ++vcpu->stat.fpu_reload;
6648 kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
6652 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
6654 kvmclock_reset(vcpu);
6656 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
6658 kvm_x86_ops->vcpu_free(vcpu);
6661 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
6664 if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
6665 printk_once(KERN_WARNING
6666 "kvm: SMP vm created on host with unstable TSC; "
6667 "guest TSC will not be reliable\n");
6668 return kvm_x86_ops->vcpu_create(kvm, id);
6671 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
6675 vcpu->arch.mtrr_state.have_fixed = 1;
6676 r = vcpu_load(vcpu);
6679 kvm_vcpu_reset(vcpu);
6680 kvm_mmu_setup(vcpu);
6686 int kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
6689 struct msr_data msr;
6691 r = vcpu_load(vcpu);
6695 msr.index = MSR_IA32_TSC;
6696 msr.host_initiated = true;
6697 kvm_write_tsc(vcpu, &msr);
6703 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
6706 vcpu->arch.apf.msr_val = 0;
6708 r = vcpu_load(vcpu);
6710 kvm_mmu_unload(vcpu);
6714 kvm_x86_ops->vcpu_free(vcpu);
6717 void kvm_vcpu_reset(struct kvm_vcpu *vcpu)
6719 atomic_set(&vcpu->arch.nmi_queued, 0);
6720 vcpu->arch.nmi_pending = 0;
6721 vcpu->arch.nmi_injected = false;
6723 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
6724 vcpu->arch.dr6 = DR6_FIXED_1;
6725 vcpu->arch.dr7 = DR7_FIXED_1;
6726 kvm_update_dr7(vcpu);
6728 kvm_make_request(KVM_REQ_EVENT, vcpu);
6729 vcpu->arch.apf.msr_val = 0;
6730 vcpu->arch.st.msr_val = 0;
6732 kvmclock_reset(vcpu);
6734 kvm_clear_async_pf_completion_queue(vcpu);
6735 kvm_async_pf_hash_reset(vcpu);
6736 vcpu->arch.apf.halted = false;
6738 kvm_pmu_reset(vcpu);
6740 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
6741 vcpu->arch.regs_avail = ~0;
6742 vcpu->arch.regs_dirty = ~0;
6744 kvm_x86_ops->vcpu_reset(vcpu);
6747 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, unsigned int vector)
6749 struct kvm_segment cs;
6751 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
6752 cs.selector = vector << 8;
6753 cs.base = vector << 12;
6754 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
6755 kvm_rip_write(vcpu, 0);
6758 int kvm_arch_hardware_enable(void *garbage)
6761 struct kvm_vcpu *vcpu;
6766 bool stable, backwards_tsc = false;
6768 kvm_shared_msr_cpu_online();
6769 ret = kvm_x86_ops->hardware_enable(garbage);
6773 local_tsc = native_read_tsc();
6774 stable = !check_tsc_unstable();
6775 list_for_each_entry(kvm, &vm_list, vm_list) {
6776 kvm_for_each_vcpu(i, vcpu, kvm) {
6777 if (!stable && vcpu->cpu == smp_processor_id())
6778 set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
6779 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
6780 backwards_tsc = true;
6781 if (vcpu->arch.last_host_tsc > max_tsc)
6782 max_tsc = vcpu->arch.last_host_tsc;
6788 * Sometimes, even reliable TSCs go backwards. This happens on
6789 * platforms that reset TSC during suspend or hibernate actions, but
6790 * maintain synchronization. We must compensate. Fortunately, we can
6791 * detect that condition here, which happens early in CPU bringup,
6792 * before any KVM threads can be running. Unfortunately, we can't
6793 * bring the TSCs fully up to date with real time, as we aren't yet far
6794 * enough into CPU bringup that we know how much real time has actually
6795 * elapsed; our helper function, get_kernel_ns() will be using boot
6796 * variables that haven't been updated yet.
6798 * So we simply find the maximum observed TSC above, then record the
6799 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
6800 * the adjustment will be applied. Note that we accumulate
6801 * adjustments, in case multiple suspend cycles happen before some VCPU
6802 * gets a chance to run again. In the event that no KVM threads get a
6803 * chance to run, we will miss the entire elapsed period, as we'll have
6804 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
6805 * loose cycle time. This isn't too big a deal, since the loss will be
6806 * uniform across all VCPUs (not to mention the scenario is extremely
6807 * unlikely). It is possible that a second hibernate recovery happens
6808 * much faster than a first, causing the observed TSC here to be
6809 * smaller; this would require additional padding adjustment, which is
6810 * why we set last_host_tsc to the local tsc observed here.
6812 * N.B. - this code below runs only on platforms with reliable TSC,
6813 * as that is the only way backwards_tsc is set above. Also note
6814 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
6815 * have the same delta_cyc adjustment applied if backwards_tsc
6816 * is detected. Note further, this adjustment is only done once,
6817 * as we reset last_host_tsc on all VCPUs to stop this from being
6818 * called multiple times (one for each physical CPU bringup).
6820 * Platforms with unreliable TSCs don't have to deal with this, they
6821 * will be compensated by the logic in vcpu_load, which sets the TSC to
6822 * catchup mode. This will catchup all VCPUs to real time, but cannot
6823 * guarantee that they stay in perfect synchronization.
6825 if (backwards_tsc) {
6826 u64 delta_cyc = max_tsc - local_tsc;
6827 list_for_each_entry(kvm, &vm_list, vm_list) {
6828 kvm_for_each_vcpu(i, vcpu, kvm) {
6829 vcpu->arch.tsc_offset_adjustment += delta_cyc;
6830 vcpu->arch.last_host_tsc = local_tsc;
6831 set_bit(KVM_REQ_MASTERCLOCK_UPDATE,
6836 * We have to disable TSC offset matching.. if you were
6837 * booting a VM while issuing an S4 host suspend....
6838 * you may have some problem. Solving this issue is
6839 * left as an exercise to the reader.
6841 kvm->arch.last_tsc_nsec = 0;
6842 kvm->arch.last_tsc_write = 0;
6849 void kvm_arch_hardware_disable(void *garbage)
6851 kvm_x86_ops->hardware_disable(garbage);
6852 drop_user_return_notifiers(garbage);
6855 int kvm_arch_hardware_setup(void)
6857 return kvm_x86_ops->hardware_setup();
6860 void kvm_arch_hardware_unsetup(void)
6862 kvm_x86_ops->hardware_unsetup();
6865 void kvm_arch_check_processor_compat(void *rtn)
6867 kvm_x86_ops->check_processor_compatibility(rtn);
6870 bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
6872 return irqchip_in_kernel(vcpu->kvm) == (vcpu->arch.apic != NULL);
6875 struct static_key kvm_no_apic_vcpu __read_mostly;
6877 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
6883 BUG_ON(vcpu->kvm == NULL);
6886 vcpu->arch.pv.pv_unhalted = false;
6887 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
6888 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
6889 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
6891 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
6893 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
6898 vcpu->arch.pio_data = page_address(page);
6900 kvm_set_tsc_khz(vcpu, max_tsc_khz);
6902 r = kvm_mmu_create(vcpu);
6904 goto fail_free_pio_data;
6906 if (irqchip_in_kernel(kvm)) {
6907 r = kvm_create_lapic(vcpu);
6909 goto fail_mmu_destroy;
6911 static_key_slow_inc(&kvm_no_apic_vcpu);
6913 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
6915 if (!vcpu->arch.mce_banks) {
6917 goto fail_free_lapic;
6919 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
6921 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
6923 goto fail_free_mce_banks;
6928 goto fail_free_wbinvd_dirty_mask;
6930 vcpu->arch.ia32_tsc_adjust_msr = 0x0;
6931 vcpu->arch.pv_time_enabled = false;
6933 vcpu->arch.guest_supported_xcr0 = 0;
6934 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
6936 kvm_async_pf_hash_reset(vcpu);
6940 fail_free_wbinvd_dirty_mask:
6941 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
6942 fail_free_mce_banks:
6943 kfree(vcpu->arch.mce_banks);
6945 kvm_free_lapic(vcpu);
6947 kvm_mmu_destroy(vcpu);
6949 free_page((unsigned long)vcpu->arch.pio_data);
6954 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
6958 kvm_pmu_destroy(vcpu);
6959 kfree(vcpu->arch.mce_banks);
6960 kvm_free_lapic(vcpu);
6961 idx = srcu_read_lock(&vcpu->kvm->srcu);
6962 kvm_mmu_destroy(vcpu);
6963 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6964 free_page((unsigned long)vcpu->arch.pio_data);
6965 if (!irqchip_in_kernel(vcpu->kvm))
6966 static_key_slow_dec(&kvm_no_apic_vcpu);
6969 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
6974 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6975 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
6976 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
6977 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
6979 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
6980 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
6981 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
6982 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
6983 &kvm->arch.irq_sources_bitmap);
6985 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
6986 mutex_init(&kvm->arch.apic_map_lock);
6987 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
6989 pvclock_update_vm_gtod_copy(kvm);
6994 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
6997 r = vcpu_load(vcpu);
6999 kvm_mmu_unload(vcpu);
7003 static void kvm_free_vcpus(struct kvm *kvm)
7006 struct kvm_vcpu *vcpu;
7009 * Unpin any mmu pages first.
7011 kvm_for_each_vcpu(i, vcpu, kvm) {
7012 kvm_clear_async_pf_completion_queue(vcpu);
7013 kvm_unload_vcpu_mmu(vcpu);
7015 kvm_for_each_vcpu(i, vcpu, kvm)
7016 kvm_arch_vcpu_free(vcpu);
7018 mutex_lock(&kvm->lock);
7019 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
7020 kvm->vcpus[i] = NULL;
7022 atomic_set(&kvm->online_vcpus, 0);
7023 mutex_unlock(&kvm->lock);
7026 void kvm_arch_sync_events(struct kvm *kvm)
7028 kvm_free_all_assigned_devices(kvm);
7032 void kvm_arch_destroy_vm(struct kvm *kvm)
7034 if (current->mm == kvm->mm) {
7036 * Free memory regions allocated on behalf of userspace,
7037 * unless the the memory map has changed due to process exit
7040 struct kvm_userspace_memory_region mem;
7041 memset(&mem, 0, sizeof(mem));
7042 mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
7043 kvm_set_memory_region(kvm, &mem);
7045 mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
7046 kvm_set_memory_region(kvm, &mem);
7048 mem.slot = TSS_PRIVATE_MEMSLOT;
7049 kvm_set_memory_region(kvm, &mem);
7051 kvm_iommu_unmap_guest(kvm);
7052 kfree(kvm->arch.vpic);
7053 kfree(kvm->arch.vioapic);
7054 kvm_free_vcpus(kvm);
7055 if (kvm->arch.apic_access_page)
7056 put_page(kvm->arch.apic_access_page);
7057 if (kvm->arch.ept_identity_pagetable)
7058 put_page(kvm->arch.ept_identity_pagetable);
7059 kfree(rcu_dereference_check(kvm->arch.apic_map, 1));
7062 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
7063 struct kvm_memory_slot *dont)
7067 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7068 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
7069 kvm_kvfree(free->arch.rmap[i]);
7070 free->arch.rmap[i] = NULL;
7075 if (!dont || free->arch.lpage_info[i - 1] !=
7076 dont->arch.lpage_info[i - 1]) {
7077 kvm_kvfree(free->arch.lpage_info[i - 1]);
7078 free->arch.lpage_info[i - 1] = NULL;
7083 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
7084 unsigned long npages)
7088 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7093 lpages = gfn_to_index(slot->base_gfn + npages - 1,
7094 slot->base_gfn, level) + 1;
7096 slot->arch.rmap[i] =
7097 kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
7098 if (!slot->arch.rmap[i])
7103 slot->arch.lpage_info[i - 1] = kvm_kvzalloc(lpages *
7104 sizeof(*slot->arch.lpage_info[i - 1]));
7105 if (!slot->arch.lpage_info[i - 1])
7108 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
7109 slot->arch.lpage_info[i - 1][0].write_count = 1;
7110 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
7111 slot->arch.lpage_info[i - 1][lpages - 1].write_count = 1;
7112 ugfn = slot->userspace_addr >> PAGE_SHIFT;
7114 * If the gfn and userspace address are not aligned wrt each
7115 * other, or if explicitly asked to, disable large page
7116 * support for this slot
7118 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
7119 !kvm_largepages_enabled()) {
7122 for (j = 0; j < lpages; ++j)
7123 slot->arch.lpage_info[i - 1][j].write_count = 1;
7130 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7131 kvm_kvfree(slot->arch.rmap[i]);
7132 slot->arch.rmap[i] = NULL;
7136 kvm_kvfree(slot->arch.lpage_info[i - 1]);
7137 slot->arch.lpage_info[i - 1] = NULL;
7142 void kvm_arch_memslots_updated(struct kvm *kvm)
7145 * memslots->generation has been incremented.
7146 * mmio generation may have reached its maximum value.
7148 kvm_mmu_invalidate_mmio_sptes(kvm);
7151 int kvm_arch_prepare_memory_region(struct kvm *kvm,
7152 struct kvm_memory_slot *memslot,
7153 struct kvm_userspace_memory_region *mem,
7154 enum kvm_mr_change change)
7157 * Only private memory slots need to be mapped here since
7158 * KVM_SET_MEMORY_REGION ioctl is no longer supported.
7160 if ((memslot->id >= KVM_USER_MEM_SLOTS) && (change == KVM_MR_CREATE)) {
7161 unsigned long userspace_addr;
7164 * MAP_SHARED to prevent internal slot pages from being moved
7167 userspace_addr = vm_mmap(NULL, 0, memslot->npages * PAGE_SIZE,
7168 PROT_READ | PROT_WRITE,
7169 MAP_SHARED | MAP_ANONYMOUS, 0);
7171 if (IS_ERR((void *)userspace_addr))
7172 return PTR_ERR((void *)userspace_addr);
7174 memslot->userspace_addr = userspace_addr;
7180 void kvm_arch_commit_memory_region(struct kvm *kvm,
7181 struct kvm_userspace_memory_region *mem,
7182 const struct kvm_memory_slot *old,
7183 enum kvm_mr_change change)
7186 int nr_mmu_pages = 0;
7188 if ((mem->slot >= KVM_USER_MEM_SLOTS) && (change == KVM_MR_DELETE)) {
7191 ret = vm_munmap(old->userspace_addr,
7192 old->npages * PAGE_SIZE);
7195 "kvm_vm_ioctl_set_memory_region: "
7196 "failed to munmap memory\n");
7199 if (!kvm->arch.n_requested_mmu_pages)
7200 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
7203 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
7205 * Write protect all pages for dirty logging.
7206 * Existing largepage mappings are destroyed here and new ones will
7207 * not be created until the end of the logging.
7209 if ((change != KVM_MR_DELETE) && (mem->flags & KVM_MEM_LOG_DIRTY_PAGES))
7210 kvm_mmu_slot_remove_write_access(kvm, mem->slot);
7213 void kvm_arch_flush_shadow_all(struct kvm *kvm)
7215 kvm_mmu_invalidate_zap_all_pages(kvm);
7218 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
7219 struct kvm_memory_slot *slot)
7221 kvm_mmu_invalidate_zap_all_pages(kvm);
7224 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
7226 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
7227 !vcpu->arch.apf.halted)
7228 || !list_empty_careful(&vcpu->async_pf.done)
7229 || kvm_apic_has_events(vcpu)
7230 || vcpu->arch.pv.pv_unhalted
7231 || atomic_read(&vcpu->arch.nmi_queued) ||
7232 (kvm_arch_interrupt_allowed(vcpu) &&
7233 kvm_cpu_has_interrupt(vcpu));
7236 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
7238 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
7241 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
7243 return kvm_x86_ops->interrupt_allowed(vcpu);
7246 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
7248 unsigned long current_rip = kvm_rip_read(vcpu) +
7249 get_segment_base(vcpu, VCPU_SREG_CS);
7251 return current_rip == linear_rip;
7253 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
7255 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
7257 unsigned long rflags;
7259 rflags = kvm_x86_ops->get_rflags(vcpu);
7260 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7261 rflags &= ~X86_EFLAGS_TF;
7264 EXPORT_SYMBOL_GPL(kvm_get_rflags);
7266 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
7268 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
7269 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
7270 rflags |= X86_EFLAGS_TF;
7271 kvm_x86_ops->set_rflags(vcpu, rflags);
7272 kvm_make_request(KVM_REQ_EVENT, vcpu);
7274 EXPORT_SYMBOL_GPL(kvm_set_rflags);
7276 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
7280 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
7284 r = kvm_mmu_reload(vcpu);
7288 if (!vcpu->arch.mmu.direct_map &&
7289 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
7292 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
7295 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
7297 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
7300 static inline u32 kvm_async_pf_next_probe(u32 key)
7302 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
7305 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
7307 u32 key = kvm_async_pf_hash_fn(gfn);
7309 while (vcpu->arch.apf.gfns[key] != ~0)
7310 key = kvm_async_pf_next_probe(key);
7312 vcpu->arch.apf.gfns[key] = gfn;
7315 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
7318 u32 key = kvm_async_pf_hash_fn(gfn);
7320 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
7321 (vcpu->arch.apf.gfns[key] != gfn &&
7322 vcpu->arch.apf.gfns[key] != ~0); i++)
7323 key = kvm_async_pf_next_probe(key);
7328 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
7330 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
7333 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
7337 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
7339 vcpu->arch.apf.gfns[i] = ~0;
7341 j = kvm_async_pf_next_probe(j);
7342 if (vcpu->arch.apf.gfns[j] == ~0)
7344 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
7346 * k lies cyclically in ]i,j]
7348 * |....j i.k.| or |.k..j i...|
7350 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
7351 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
7356 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
7359 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
7363 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
7364 struct kvm_async_pf *work)
7366 struct x86_exception fault;
7368 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
7369 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
7371 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
7372 (vcpu->arch.apf.send_user_only &&
7373 kvm_x86_ops->get_cpl(vcpu) == 0))
7374 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
7375 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
7376 fault.vector = PF_VECTOR;
7377 fault.error_code_valid = true;
7378 fault.error_code = 0;
7379 fault.nested_page_fault = false;
7380 fault.address = work->arch.token;
7381 kvm_inject_page_fault(vcpu, &fault);
7385 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
7386 struct kvm_async_pf *work)
7388 struct x86_exception fault;
7390 trace_kvm_async_pf_ready(work->arch.token, work->gva);
7391 if (work->wakeup_all)
7392 work->arch.token = ~0; /* broadcast wakeup */
7394 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
7396 if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
7397 !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
7398 fault.vector = PF_VECTOR;
7399 fault.error_code_valid = true;
7400 fault.error_code = 0;
7401 fault.nested_page_fault = false;
7402 fault.address = work->arch.token;
7403 kvm_inject_page_fault(vcpu, &fault);
7405 vcpu->arch.apf.halted = false;
7406 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7409 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
7411 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
7414 return !kvm_event_needs_reinjection(vcpu) &&
7415 kvm_x86_ops->interrupt_allowed(vcpu);
7418 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
7420 atomic_inc(&kvm->arch.noncoherent_dma_count);
7422 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
7424 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
7426 atomic_dec(&kvm->arch.noncoherent_dma_count);
7428 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
7430 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
7432 return atomic_read(&kvm->arch.noncoherent_dma_count);
7434 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
7436 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
7437 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
7438 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
7439 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
7440 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
7441 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
7442 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
7443 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
7444 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
7445 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
7446 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
7447 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
7448 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);