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);
90 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
92 struct kvm_x86_ops *kvm_x86_ops;
93 EXPORT_SYMBOL_GPL(kvm_x86_ops);
95 static bool ignore_msrs = 0;
96 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
98 unsigned int min_timer_period_us = 500;
99 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
101 bool kvm_has_tsc_control;
102 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
103 u32 kvm_max_guest_tsc_khz;
104 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
106 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
107 static u32 tsc_tolerance_ppm = 250;
108 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
110 static bool backwards_tsc_observed = false;
112 #define KVM_NR_SHARED_MSRS 16
114 struct kvm_shared_msrs_global {
116 u32 msrs[KVM_NR_SHARED_MSRS];
119 struct kvm_shared_msrs {
120 struct user_return_notifier urn;
122 struct kvm_shared_msr_values {
125 } values[KVM_NR_SHARED_MSRS];
128 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
129 static struct kvm_shared_msrs __percpu *shared_msrs;
131 struct kvm_stats_debugfs_item debugfs_entries[] = {
132 { "pf_fixed", VCPU_STAT(pf_fixed) },
133 { "pf_guest", VCPU_STAT(pf_guest) },
134 { "tlb_flush", VCPU_STAT(tlb_flush) },
135 { "invlpg", VCPU_STAT(invlpg) },
136 { "exits", VCPU_STAT(exits) },
137 { "io_exits", VCPU_STAT(io_exits) },
138 { "mmio_exits", VCPU_STAT(mmio_exits) },
139 { "signal_exits", VCPU_STAT(signal_exits) },
140 { "irq_window", VCPU_STAT(irq_window_exits) },
141 { "nmi_window", VCPU_STAT(nmi_window_exits) },
142 { "halt_exits", VCPU_STAT(halt_exits) },
143 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
144 { "hypercalls", VCPU_STAT(hypercalls) },
145 { "request_irq", VCPU_STAT(request_irq_exits) },
146 { "irq_exits", VCPU_STAT(irq_exits) },
147 { "host_state_reload", VCPU_STAT(host_state_reload) },
148 { "efer_reload", VCPU_STAT(efer_reload) },
149 { "fpu_reload", VCPU_STAT(fpu_reload) },
150 { "insn_emulation", VCPU_STAT(insn_emulation) },
151 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
152 { "irq_injections", VCPU_STAT(irq_injections) },
153 { "nmi_injections", VCPU_STAT(nmi_injections) },
154 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
155 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
156 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
157 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
158 { "mmu_flooded", VM_STAT(mmu_flooded) },
159 { "mmu_recycled", VM_STAT(mmu_recycled) },
160 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
161 { "mmu_unsync", VM_STAT(mmu_unsync) },
162 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
163 { "largepages", VM_STAT(lpages) },
167 u64 __read_mostly host_xcr0;
169 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
171 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
174 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
175 vcpu->arch.apf.gfns[i] = ~0;
178 static void kvm_on_user_return(struct user_return_notifier *urn)
181 struct kvm_shared_msrs *locals
182 = container_of(urn, struct kvm_shared_msrs, urn);
183 struct kvm_shared_msr_values *values;
185 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
186 values = &locals->values[slot];
187 if (values->host != values->curr) {
188 wrmsrl(shared_msrs_global.msrs[slot], values->host);
189 values->curr = values->host;
192 locals->registered = false;
193 user_return_notifier_unregister(urn);
196 static void shared_msr_update(unsigned slot, u32 msr)
199 unsigned int cpu = smp_processor_id();
200 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
202 /* only read, and nobody should modify it at this time,
203 * so don't need lock */
204 if (slot >= shared_msrs_global.nr) {
205 printk(KERN_ERR "kvm: invalid MSR slot!");
208 rdmsrl_safe(msr, &value);
209 smsr->values[slot].host = value;
210 smsr->values[slot].curr = value;
213 void kvm_define_shared_msr(unsigned slot, u32 msr)
215 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
216 if (slot >= shared_msrs_global.nr)
217 shared_msrs_global.nr = slot + 1;
218 shared_msrs_global.msrs[slot] = msr;
219 /* we need ensured the shared_msr_global have been updated */
222 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
224 static void kvm_shared_msr_cpu_online(void)
228 for (i = 0; i < shared_msrs_global.nr; ++i)
229 shared_msr_update(i, shared_msrs_global.msrs[i]);
232 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
234 unsigned int cpu = smp_processor_id();
235 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
238 if (((value ^ smsr->values[slot].curr) & mask) == 0)
240 smsr->values[slot].curr = value;
241 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
245 if (!smsr->registered) {
246 smsr->urn.on_user_return = kvm_on_user_return;
247 user_return_notifier_register(&smsr->urn);
248 smsr->registered = true;
252 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
254 static void drop_user_return_notifiers(void)
256 unsigned int cpu = smp_processor_id();
257 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
259 if (smsr->registered)
260 kvm_on_user_return(&smsr->urn);
263 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
265 return vcpu->arch.apic_base;
267 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
269 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
271 u64 old_state = vcpu->arch.apic_base &
272 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
273 u64 new_state = msr_info->data &
274 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
275 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) |
276 0x2ff | (guest_cpuid_has_x2apic(vcpu) ? 0 : X2APIC_ENABLE);
278 if (!msr_info->host_initiated &&
279 ((msr_info->data & reserved_bits) != 0 ||
280 new_state == X2APIC_ENABLE ||
281 (new_state == MSR_IA32_APICBASE_ENABLE &&
282 old_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) ||
283 (new_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE) &&
287 kvm_lapic_set_base(vcpu, msr_info->data);
290 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
292 asmlinkage __visible void kvm_spurious_fault(void)
294 /* Fault while not rebooting. We want the trace. */
297 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
299 #define EXCPT_BENIGN 0
300 #define EXCPT_CONTRIBUTORY 1
303 static int exception_class(int vector)
313 return EXCPT_CONTRIBUTORY;
320 #define EXCPT_FAULT 0
322 #define EXCPT_ABORT 2
323 #define EXCPT_INTERRUPT 3
325 static int exception_type(int vector)
329 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
330 return EXCPT_INTERRUPT;
334 /* #DB is trap, as instruction watchpoints are handled elsewhere */
335 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
338 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
341 /* Reserved exceptions will result in fault */
345 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
346 unsigned nr, bool has_error, u32 error_code,
352 kvm_make_request(KVM_REQ_EVENT, vcpu);
354 if (!vcpu->arch.exception.pending) {
356 if (has_error && !is_protmode(vcpu))
358 vcpu->arch.exception.pending = true;
359 vcpu->arch.exception.has_error_code = has_error;
360 vcpu->arch.exception.nr = nr;
361 vcpu->arch.exception.error_code = error_code;
362 vcpu->arch.exception.reinject = reinject;
366 /* to check exception */
367 prev_nr = vcpu->arch.exception.nr;
368 if (prev_nr == DF_VECTOR) {
369 /* triple fault -> shutdown */
370 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
373 class1 = exception_class(prev_nr);
374 class2 = exception_class(nr);
375 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
376 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
377 /* generate double fault per SDM Table 5-5 */
378 vcpu->arch.exception.pending = true;
379 vcpu->arch.exception.has_error_code = true;
380 vcpu->arch.exception.nr = DF_VECTOR;
381 vcpu->arch.exception.error_code = 0;
383 /* replace previous exception with a new one in a hope
384 that instruction re-execution will regenerate lost
389 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
391 kvm_multiple_exception(vcpu, nr, false, 0, false);
393 EXPORT_SYMBOL_GPL(kvm_queue_exception);
395 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
397 kvm_multiple_exception(vcpu, nr, false, 0, true);
399 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
401 void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
404 kvm_inject_gp(vcpu, 0);
406 kvm_x86_ops->skip_emulated_instruction(vcpu);
408 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
410 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
412 ++vcpu->stat.pf_guest;
413 vcpu->arch.cr2 = fault->address;
414 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
416 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
418 static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
420 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
421 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
423 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
425 return fault->nested_page_fault;
428 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
430 atomic_inc(&vcpu->arch.nmi_queued);
431 kvm_make_request(KVM_REQ_NMI, vcpu);
433 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
435 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
437 kvm_multiple_exception(vcpu, nr, true, error_code, false);
439 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
441 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
443 kvm_multiple_exception(vcpu, nr, true, error_code, true);
445 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
448 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
449 * a #GP and return false.
451 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
453 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
455 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
458 EXPORT_SYMBOL_GPL(kvm_require_cpl);
460 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
462 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
465 kvm_queue_exception(vcpu, UD_VECTOR);
468 EXPORT_SYMBOL_GPL(kvm_require_dr);
471 * This function will be used to read from the physical memory of the currently
472 * running guest. The difference to kvm_read_guest_page is that this function
473 * can read from guest physical or from the guest's guest physical memory.
475 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
476 gfn_t ngfn, void *data, int offset, int len,
479 struct x86_exception exception;
483 ngpa = gfn_to_gpa(ngfn);
484 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
485 if (real_gfn == UNMAPPED_GVA)
488 real_gfn = gpa_to_gfn(real_gfn);
490 return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
492 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
494 int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
495 void *data, int offset, int len, u32 access)
497 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
498 data, offset, len, access);
502 * Load the pae pdptrs. Return true is they are all valid.
504 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
506 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
507 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
510 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
512 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
513 offset * sizeof(u64), sizeof(pdpte),
514 PFERR_USER_MASK|PFERR_WRITE_MASK);
519 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
520 if (is_present_gpte(pdpte[i]) &&
521 (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
528 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
529 __set_bit(VCPU_EXREG_PDPTR,
530 (unsigned long *)&vcpu->arch.regs_avail);
531 __set_bit(VCPU_EXREG_PDPTR,
532 (unsigned long *)&vcpu->arch.regs_dirty);
537 EXPORT_SYMBOL_GPL(load_pdptrs);
539 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
541 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
547 if (is_long_mode(vcpu) || !is_pae(vcpu))
550 if (!test_bit(VCPU_EXREG_PDPTR,
551 (unsigned long *)&vcpu->arch.regs_avail))
554 gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
555 offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
556 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
557 PFERR_USER_MASK | PFERR_WRITE_MASK);
560 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
566 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
568 unsigned long old_cr0 = kvm_read_cr0(vcpu);
569 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
570 X86_CR0_CD | X86_CR0_NW;
575 if (cr0 & 0xffffffff00000000UL)
579 cr0 &= ~CR0_RESERVED_BITS;
581 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
584 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
587 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
589 if ((vcpu->arch.efer & EFER_LME)) {
594 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
599 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
604 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
607 kvm_x86_ops->set_cr0(vcpu, cr0);
609 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
610 kvm_clear_async_pf_completion_queue(vcpu);
611 kvm_async_pf_hash_reset(vcpu);
614 if ((cr0 ^ old_cr0) & update_bits)
615 kvm_mmu_reset_context(vcpu);
618 EXPORT_SYMBOL_GPL(kvm_set_cr0);
620 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
622 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
624 EXPORT_SYMBOL_GPL(kvm_lmsw);
626 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
628 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
629 !vcpu->guest_xcr0_loaded) {
630 /* kvm_set_xcr() also depends on this */
631 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
632 vcpu->guest_xcr0_loaded = 1;
636 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
638 if (vcpu->guest_xcr0_loaded) {
639 if (vcpu->arch.xcr0 != host_xcr0)
640 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
641 vcpu->guest_xcr0_loaded = 0;
645 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
648 u64 old_xcr0 = vcpu->arch.xcr0;
651 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
652 if (index != XCR_XFEATURE_ENABLED_MASK)
654 if (!(xcr0 & XSTATE_FP))
656 if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
660 * Do not allow the guest to set bits that we do not support
661 * saving. However, xcr0 bit 0 is always set, even if the
662 * emulated CPU does not support XSAVE (see fx_init).
664 valid_bits = vcpu->arch.guest_supported_xcr0 | XSTATE_FP;
665 if (xcr0 & ~valid_bits)
668 if ((!(xcr0 & XSTATE_BNDREGS)) != (!(xcr0 & XSTATE_BNDCSR)))
671 if (xcr0 & XSTATE_AVX512) {
672 if (!(xcr0 & XSTATE_YMM))
674 if ((xcr0 & XSTATE_AVX512) != XSTATE_AVX512)
677 kvm_put_guest_xcr0(vcpu);
678 vcpu->arch.xcr0 = xcr0;
680 if ((xcr0 ^ old_xcr0) & XSTATE_EXTEND_MASK)
681 kvm_update_cpuid(vcpu);
685 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
687 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
688 __kvm_set_xcr(vcpu, index, xcr)) {
689 kvm_inject_gp(vcpu, 0);
694 EXPORT_SYMBOL_GPL(kvm_set_xcr);
696 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
698 unsigned long old_cr4 = kvm_read_cr4(vcpu);
699 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
700 X86_CR4_PAE | X86_CR4_SMEP;
701 if (cr4 & CR4_RESERVED_BITS)
704 if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
707 if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
710 if (!guest_cpuid_has_smap(vcpu) && (cr4 & X86_CR4_SMAP))
713 if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_FSGSBASE))
716 if (is_long_mode(vcpu)) {
717 if (!(cr4 & X86_CR4_PAE))
719 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
720 && ((cr4 ^ old_cr4) & pdptr_bits)
721 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
725 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
726 if (!guest_cpuid_has_pcid(vcpu))
729 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
730 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
734 if (kvm_x86_ops->set_cr4(vcpu, cr4))
737 if (((cr4 ^ old_cr4) & pdptr_bits) ||
738 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
739 kvm_mmu_reset_context(vcpu);
741 if ((cr4 ^ old_cr4) & X86_CR4_SMAP)
742 update_permission_bitmask(vcpu, vcpu->arch.walk_mmu, false);
744 if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
745 kvm_update_cpuid(vcpu);
749 EXPORT_SYMBOL_GPL(kvm_set_cr4);
751 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
753 cr3 &= ~CR3_PCID_INVD;
755 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
756 kvm_mmu_sync_roots(vcpu);
757 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
761 if (is_long_mode(vcpu)) {
762 if (cr3 & CR3_L_MODE_RESERVED_BITS)
764 } else if (is_pae(vcpu) && is_paging(vcpu) &&
765 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
768 vcpu->arch.cr3 = cr3;
769 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
770 kvm_mmu_new_cr3(vcpu);
773 EXPORT_SYMBOL_GPL(kvm_set_cr3);
775 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
777 if (cr8 & CR8_RESERVED_BITS)
779 if (irqchip_in_kernel(vcpu->kvm))
780 kvm_lapic_set_tpr(vcpu, cr8);
782 vcpu->arch.cr8 = cr8;
785 EXPORT_SYMBOL_GPL(kvm_set_cr8);
787 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
789 if (irqchip_in_kernel(vcpu->kvm))
790 return kvm_lapic_get_cr8(vcpu);
792 return vcpu->arch.cr8;
794 EXPORT_SYMBOL_GPL(kvm_get_cr8);
796 static void kvm_update_dr6(struct kvm_vcpu *vcpu)
798 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
799 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
802 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
806 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
807 dr7 = vcpu->arch.guest_debug_dr7;
809 dr7 = vcpu->arch.dr7;
810 kvm_x86_ops->set_dr7(vcpu, dr7);
811 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
812 if (dr7 & DR7_BP_EN_MASK)
813 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
816 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
818 u64 fixed = DR6_FIXED_1;
820 if (!guest_cpuid_has_rtm(vcpu))
825 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
829 vcpu->arch.db[dr] = val;
830 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
831 vcpu->arch.eff_db[dr] = val;
836 if (val & 0xffffffff00000000ULL)
838 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
839 kvm_update_dr6(vcpu);
844 if (val & 0xffffffff00000000ULL)
846 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
847 kvm_update_dr7(vcpu);
854 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
856 if (__kvm_set_dr(vcpu, dr, val)) {
857 kvm_inject_gp(vcpu, 0);
862 EXPORT_SYMBOL_GPL(kvm_set_dr);
864 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
868 *val = vcpu->arch.db[dr];
873 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
874 *val = vcpu->arch.dr6;
876 *val = kvm_x86_ops->get_dr6(vcpu);
881 *val = vcpu->arch.dr7;
886 EXPORT_SYMBOL_GPL(kvm_get_dr);
888 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
890 u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
894 err = kvm_pmu_read_pmc(vcpu, ecx, &data);
897 kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
898 kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
901 EXPORT_SYMBOL_GPL(kvm_rdpmc);
904 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
905 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
907 * This list is modified at module load time to reflect the
908 * capabilities of the host cpu. This capabilities test skips MSRs that are
909 * kvm-specific. Those are put in the beginning of the list.
912 #define KVM_SAVE_MSRS_BEGIN 12
913 static u32 msrs_to_save[] = {
914 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
915 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
916 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
917 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
918 HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
920 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
923 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
925 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
926 MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS
929 static unsigned num_msrs_to_save;
931 static const u32 emulated_msrs[] = {
933 MSR_IA32_TSCDEADLINE,
934 MSR_IA32_MISC_ENABLE,
939 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
941 if (efer & efer_reserved_bits)
944 if (efer & EFER_FFXSR) {
945 struct kvm_cpuid_entry2 *feat;
947 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
948 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
952 if (efer & EFER_SVME) {
953 struct kvm_cpuid_entry2 *feat;
955 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
956 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
962 EXPORT_SYMBOL_GPL(kvm_valid_efer);
964 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
966 u64 old_efer = vcpu->arch.efer;
968 if (!kvm_valid_efer(vcpu, efer))
972 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
976 efer |= vcpu->arch.efer & EFER_LMA;
978 kvm_x86_ops->set_efer(vcpu, efer);
980 /* Update reserved bits */
981 if ((efer ^ old_efer) & EFER_NX)
982 kvm_mmu_reset_context(vcpu);
987 void kvm_enable_efer_bits(u64 mask)
989 efer_reserved_bits &= ~mask;
991 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
994 * Writes msr value into into the appropriate "register".
995 * Returns 0 on success, non-0 otherwise.
996 * Assumes vcpu_load() was already called.
998 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
1000 switch (msr->index) {
1003 case MSR_KERNEL_GS_BASE:
1006 if (is_noncanonical_address(msr->data))
1009 case MSR_IA32_SYSENTER_EIP:
1010 case MSR_IA32_SYSENTER_ESP:
1012 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1013 * non-canonical address is written on Intel but not on
1014 * AMD (which ignores the top 32-bits, because it does
1015 * not implement 64-bit SYSENTER).
1017 * 64-bit code should hence be able to write a non-canonical
1018 * value on AMD. Making the address canonical ensures that
1019 * vmentry does not fail on Intel after writing a non-canonical
1020 * value, and that something deterministic happens if the guest
1021 * invokes 64-bit SYSENTER.
1023 msr->data = get_canonical(msr->data);
1025 return kvm_x86_ops->set_msr(vcpu, msr);
1027 EXPORT_SYMBOL_GPL(kvm_set_msr);
1030 * Adapt set_msr() to msr_io()'s calling convention
1032 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1034 struct msr_data msr;
1038 msr.host_initiated = true;
1039 return kvm_set_msr(vcpu, &msr);
1042 #ifdef CONFIG_X86_64
1043 struct pvclock_gtod_data {
1046 struct { /* extract of a clocksource struct */
1058 static struct pvclock_gtod_data pvclock_gtod_data;
1060 static void update_pvclock_gtod(struct timekeeper *tk)
1062 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1065 boot_ns = ktime_to_ns(ktime_add(tk->tkr.base_mono, tk->offs_boot));
1067 write_seqcount_begin(&vdata->seq);
1069 /* copy pvclock gtod data */
1070 vdata->clock.vclock_mode = tk->tkr.clock->archdata.vclock_mode;
1071 vdata->clock.cycle_last = tk->tkr.cycle_last;
1072 vdata->clock.mask = tk->tkr.mask;
1073 vdata->clock.mult = tk->tkr.mult;
1074 vdata->clock.shift = tk->tkr.shift;
1076 vdata->boot_ns = boot_ns;
1077 vdata->nsec_base = tk->tkr.xtime_nsec;
1079 write_seqcount_end(&vdata->seq);
1084 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1088 struct pvclock_wall_clock wc;
1089 struct timespec boot;
1094 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1099 ++version; /* first time write, random junk */
1103 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1106 * The guest calculates current wall clock time by adding
1107 * system time (updated by kvm_guest_time_update below) to the
1108 * wall clock specified here. guest system time equals host
1109 * system time for us, thus we must fill in host boot time here.
1113 if (kvm->arch.kvmclock_offset) {
1114 struct timespec ts = ns_to_timespec(kvm->arch.kvmclock_offset);
1115 boot = timespec_sub(boot, ts);
1117 wc.sec = boot.tv_sec;
1118 wc.nsec = boot.tv_nsec;
1119 wc.version = version;
1121 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1124 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1127 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1129 uint32_t quotient, remainder;
1131 /* Don't try to replace with do_div(), this one calculates
1132 * "(dividend << 32) / divisor" */
1134 : "=a" (quotient), "=d" (remainder)
1135 : "0" (0), "1" (dividend), "r" (divisor) );
1139 static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
1140 s8 *pshift, u32 *pmultiplier)
1147 tps64 = base_khz * 1000LL;
1148 scaled64 = scaled_khz * 1000LL;
1149 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1154 tps32 = (uint32_t)tps64;
1155 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1156 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1164 *pmultiplier = div_frac(scaled64, tps32);
1166 pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
1167 __func__, base_khz, scaled_khz, shift, *pmultiplier);
1170 static inline u64 get_kernel_ns(void)
1172 return ktime_get_boot_ns();
1175 #ifdef CONFIG_X86_64
1176 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1179 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1180 unsigned long max_tsc_khz;
1182 static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
1184 return pvclock_scale_delta(nsec, vcpu->arch.virtual_tsc_mult,
1185 vcpu->arch.virtual_tsc_shift);
1188 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1190 u64 v = (u64)khz * (1000000 + ppm);
1195 static void kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
1197 u32 thresh_lo, thresh_hi;
1198 int use_scaling = 0;
1200 /* tsc_khz can be zero if TSC calibration fails */
1201 if (this_tsc_khz == 0)
1204 /* Compute a scale to convert nanoseconds in TSC cycles */
1205 kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
1206 &vcpu->arch.virtual_tsc_shift,
1207 &vcpu->arch.virtual_tsc_mult);
1208 vcpu->arch.virtual_tsc_khz = this_tsc_khz;
1211 * Compute the variation in TSC rate which is acceptable
1212 * within the range of tolerance and decide if the
1213 * rate being applied is within that bounds of the hardware
1214 * rate. If so, no scaling or compensation need be done.
1216 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1217 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1218 if (this_tsc_khz < thresh_lo || this_tsc_khz > thresh_hi) {
1219 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", this_tsc_khz, thresh_lo, thresh_hi);
1222 kvm_x86_ops->set_tsc_khz(vcpu, this_tsc_khz, use_scaling);
1225 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1227 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1228 vcpu->arch.virtual_tsc_mult,
1229 vcpu->arch.virtual_tsc_shift);
1230 tsc += vcpu->arch.this_tsc_write;
1234 void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1236 #ifdef CONFIG_X86_64
1238 bool do_request = false;
1239 struct kvm_arch *ka = &vcpu->kvm->arch;
1240 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1242 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1243 atomic_read(&vcpu->kvm->online_vcpus));
1245 if (vcpus_matched && gtod->clock.vclock_mode == VCLOCK_TSC)
1246 if (!ka->use_master_clock)
1249 if (!vcpus_matched && ka->use_master_clock)
1253 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1255 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1256 atomic_read(&vcpu->kvm->online_vcpus),
1257 ka->use_master_clock, gtod->clock.vclock_mode);
1261 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1263 u64 curr_offset = kvm_x86_ops->read_tsc_offset(vcpu);
1264 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1267 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1269 struct kvm *kvm = vcpu->kvm;
1270 u64 offset, ns, elapsed;
1271 unsigned long flags;
1274 bool already_matched;
1275 u64 data = msr->data;
1277 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1278 offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
1279 ns = get_kernel_ns();
1280 elapsed = ns - kvm->arch.last_tsc_nsec;
1282 if (vcpu->arch.virtual_tsc_khz) {
1285 /* n.b - signed multiplication and division required */
1286 usdiff = data - kvm->arch.last_tsc_write;
1287 #ifdef CONFIG_X86_64
1288 usdiff = (usdiff * 1000) / vcpu->arch.virtual_tsc_khz;
1290 /* do_div() only does unsigned */
1291 asm("1: idivl %[divisor]\n"
1292 "2: xor %%edx, %%edx\n"
1293 " movl $0, %[faulted]\n"
1295 ".section .fixup,\"ax\"\n"
1296 "4: movl $1, %[faulted]\n"
1300 _ASM_EXTABLE(1b, 4b)
1302 : "=A"(usdiff), [faulted] "=r" (faulted)
1303 : "A"(usdiff * 1000), [divisor] "rm"(vcpu->arch.virtual_tsc_khz));
1306 do_div(elapsed, 1000);
1311 /* idivl overflow => difference is larger than USEC_PER_SEC */
1313 usdiff = USEC_PER_SEC;
1315 usdiff = USEC_PER_SEC; /* disable TSC match window below */
1318 * Special case: TSC write with a small delta (1 second) of virtual
1319 * cycle time against real time is interpreted as an attempt to
1320 * synchronize the CPU.
1322 * For a reliable TSC, we can match TSC offsets, and for an unstable
1323 * TSC, we add elapsed time in this computation. We could let the
1324 * compensation code attempt to catch up if we fall behind, but
1325 * it's better to try to match offsets from the beginning.
1327 if (usdiff < USEC_PER_SEC &&
1328 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1329 if (!check_tsc_unstable()) {
1330 offset = kvm->arch.cur_tsc_offset;
1331 pr_debug("kvm: matched tsc offset for %llu\n", data);
1333 u64 delta = nsec_to_cycles(vcpu, elapsed);
1335 offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
1336 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1339 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1342 * We split periods of matched TSC writes into generations.
1343 * For each generation, we track the original measured
1344 * nanosecond time, offset, and write, so if TSCs are in
1345 * sync, we can match exact offset, and if not, we can match
1346 * exact software computation in compute_guest_tsc()
1348 * These values are tracked in kvm->arch.cur_xxx variables.
1350 kvm->arch.cur_tsc_generation++;
1351 kvm->arch.cur_tsc_nsec = ns;
1352 kvm->arch.cur_tsc_write = data;
1353 kvm->arch.cur_tsc_offset = offset;
1355 pr_debug("kvm: new tsc generation %llu, clock %llu\n",
1356 kvm->arch.cur_tsc_generation, data);
1360 * We also track th most recent recorded KHZ, write and time to
1361 * allow the matching interval to be extended at each write.
1363 kvm->arch.last_tsc_nsec = ns;
1364 kvm->arch.last_tsc_write = data;
1365 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1367 vcpu->arch.last_guest_tsc = data;
1369 /* Keep track of which generation this VCPU has synchronized to */
1370 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1371 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1372 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1374 if (guest_cpuid_has_tsc_adjust(vcpu) && !msr->host_initiated)
1375 update_ia32_tsc_adjust_msr(vcpu, offset);
1376 kvm_x86_ops->write_tsc_offset(vcpu, offset);
1377 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1379 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1381 kvm->arch.nr_vcpus_matched_tsc = 0;
1382 } else if (!already_matched) {
1383 kvm->arch.nr_vcpus_matched_tsc++;
1386 kvm_track_tsc_matching(vcpu);
1387 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1390 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1392 #ifdef CONFIG_X86_64
1394 static cycle_t read_tsc(void)
1400 * Empirically, a fence (of type that depends on the CPU)
1401 * before rdtsc is enough to ensure that rdtsc is ordered
1402 * with respect to loads. The various CPU manuals are unclear
1403 * as to whether rdtsc can be reordered with later loads,
1404 * but no one has ever seen it happen.
1407 ret = (cycle_t)vget_cycles();
1409 last = pvclock_gtod_data.clock.cycle_last;
1411 if (likely(ret >= last))
1415 * GCC likes to generate cmov here, but this branch is extremely
1416 * predictable (it's just a funciton of time and the likely is
1417 * very likely) and there's a data dependence, so force GCC
1418 * to generate a branch instead. I don't barrier() because
1419 * we don't actually need a barrier, and if this function
1420 * ever gets inlined it will generate worse code.
1426 static inline u64 vgettsc(cycle_t *cycle_now)
1429 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1431 *cycle_now = read_tsc();
1433 v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
1434 return v * gtod->clock.mult;
1437 static int do_monotonic_boot(s64 *t, cycle_t *cycle_now)
1439 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1445 seq = read_seqcount_begin(>od->seq);
1446 mode = gtod->clock.vclock_mode;
1447 ns = gtod->nsec_base;
1448 ns += vgettsc(cycle_now);
1449 ns >>= gtod->clock.shift;
1450 ns += gtod->boot_ns;
1451 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
1457 /* returns true if host is using tsc clocksource */
1458 static bool kvm_get_time_and_clockread(s64 *kernel_ns, cycle_t *cycle_now)
1460 /* checked again under seqlock below */
1461 if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
1464 return do_monotonic_boot(kernel_ns, cycle_now) == VCLOCK_TSC;
1470 * Assuming a stable TSC across physical CPUS, and a stable TSC
1471 * across virtual CPUs, the following condition is possible.
1472 * Each numbered line represents an event visible to both
1473 * CPUs at the next numbered event.
1475 * "timespecX" represents host monotonic time. "tscX" represents
1478 * VCPU0 on CPU0 | VCPU1 on CPU1
1480 * 1. read timespec0,tsc0
1481 * 2. | timespec1 = timespec0 + N
1483 * 3. transition to guest | transition to guest
1484 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1485 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
1486 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1488 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1491 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1493 * - 0 < N - M => M < N
1495 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1496 * always the case (the difference between two distinct xtime instances
1497 * might be smaller then the difference between corresponding TSC reads,
1498 * when updating guest vcpus pvclock areas).
1500 * To avoid that problem, do not allow visibility of distinct
1501 * system_timestamp/tsc_timestamp values simultaneously: use a master
1502 * copy of host monotonic time values. Update that master copy
1505 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1509 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1511 #ifdef CONFIG_X86_64
1512 struct kvm_arch *ka = &kvm->arch;
1514 bool host_tsc_clocksource, vcpus_matched;
1516 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1517 atomic_read(&kvm->online_vcpus));
1520 * If the host uses TSC clock, then passthrough TSC as stable
1523 host_tsc_clocksource = kvm_get_time_and_clockread(
1524 &ka->master_kernel_ns,
1525 &ka->master_cycle_now);
1527 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
1528 && !backwards_tsc_observed;
1530 if (ka->use_master_clock)
1531 atomic_set(&kvm_guest_has_master_clock, 1);
1533 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1534 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1539 static void kvm_gen_update_masterclock(struct kvm *kvm)
1541 #ifdef CONFIG_X86_64
1543 struct kvm_vcpu *vcpu;
1544 struct kvm_arch *ka = &kvm->arch;
1546 spin_lock(&ka->pvclock_gtod_sync_lock);
1547 kvm_make_mclock_inprogress_request(kvm);
1548 /* no guest entries from this point */
1549 pvclock_update_vm_gtod_copy(kvm);
1551 kvm_for_each_vcpu(i, vcpu, kvm)
1552 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1554 /* guest entries allowed */
1555 kvm_for_each_vcpu(i, vcpu, kvm)
1556 clear_bit(KVM_REQ_MCLOCK_INPROGRESS, &vcpu->requests);
1558 spin_unlock(&ka->pvclock_gtod_sync_lock);
1562 static int kvm_guest_time_update(struct kvm_vcpu *v)
1564 unsigned long flags, this_tsc_khz;
1565 struct kvm_vcpu_arch *vcpu = &v->arch;
1566 struct kvm_arch *ka = &v->kvm->arch;
1568 u64 tsc_timestamp, host_tsc;
1569 struct pvclock_vcpu_time_info guest_hv_clock;
1571 bool use_master_clock;
1577 * If the host uses TSC clock, then passthrough TSC as stable
1580 spin_lock(&ka->pvclock_gtod_sync_lock);
1581 use_master_clock = ka->use_master_clock;
1582 if (use_master_clock) {
1583 host_tsc = ka->master_cycle_now;
1584 kernel_ns = ka->master_kernel_ns;
1586 spin_unlock(&ka->pvclock_gtod_sync_lock);
1588 /* Keep irq disabled to prevent changes to the clock */
1589 local_irq_save(flags);
1590 this_tsc_khz = __this_cpu_read(cpu_tsc_khz);
1591 if (unlikely(this_tsc_khz == 0)) {
1592 local_irq_restore(flags);
1593 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1596 if (!use_master_clock) {
1597 host_tsc = native_read_tsc();
1598 kernel_ns = get_kernel_ns();
1601 tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc);
1604 * We may have to catch up the TSC to match elapsed wall clock
1605 * time for two reasons, even if kvmclock is used.
1606 * 1) CPU could have been running below the maximum TSC rate
1607 * 2) Broken TSC compensation resets the base at each VCPU
1608 * entry to avoid unknown leaps of TSC even when running
1609 * again on the same CPU. This may cause apparent elapsed
1610 * time to disappear, and the guest to stand still or run
1613 if (vcpu->tsc_catchup) {
1614 u64 tsc = compute_guest_tsc(v, kernel_ns);
1615 if (tsc > tsc_timestamp) {
1616 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
1617 tsc_timestamp = tsc;
1621 local_irq_restore(flags);
1623 if (!vcpu->pv_time_enabled)
1626 if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
1627 kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
1628 &vcpu->hv_clock.tsc_shift,
1629 &vcpu->hv_clock.tsc_to_system_mul);
1630 vcpu->hw_tsc_khz = this_tsc_khz;
1633 /* With all the info we got, fill in the values */
1634 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1635 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1636 vcpu->last_guest_tsc = tsc_timestamp;
1639 * The interface expects us to write an even number signaling that the
1640 * update is finished. Since the guest won't see the intermediate
1641 * state, we just increase by 2 at the end.
1643 vcpu->hv_clock.version += 2;
1645 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
1646 &guest_hv_clock, sizeof(guest_hv_clock))))
1649 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
1650 pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
1652 if (vcpu->pvclock_set_guest_stopped_request) {
1653 pvclock_flags |= PVCLOCK_GUEST_STOPPED;
1654 vcpu->pvclock_set_guest_stopped_request = false;
1657 /* If the host uses TSC clocksource, then it is stable */
1658 if (use_master_clock)
1659 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
1661 vcpu->hv_clock.flags = pvclock_flags;
1663 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1665 sizeof(vcpu->hv_clock));
1670 * kvmclock updates which are isolated to a given vcpu, such as
1671 * vcpu->cpu migration, should not allow system_timestamp from
1672 * the rest of the vcpus to remain static. Otherwise ntp frequency
1673 * correction applies to one vcpu's system_timestamp but not
1676 * So in those cases, request a kvmclock update for all vcpus.
1677 * We need to rate-limit these requests though, as they can
1678 * considerably slow guests that have a large number of vcpus.
1679 * The time for a remote vcpu to update its kvmclock is bound
1680 * by the delay we use to rate-limit the updates.
1683 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
1685 static void kvmclock_update_fn(struct work_struct *work)
1688 struct delayed_work *dwork = to_delayed_work(work);
1689 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
1690 kvmclock_update_work);
1691 struct kvm *kvm = container_of(ka, struct kvm, arch);
1692 struct kvm_vcpu *vcpu;
1694 kvm_for_each_vcpu(i, vcpu, kvm) {
1695 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1696 kvm_vcpu_kick(vcpu);
1700 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
1702 struct kvm *kvm = v->kvm;
1704 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1705 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
1706 KVMCLOCK_UPDATE_DELAY);
1709 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
1711 static void kvmclock_sync_fn(struct work_struct *work)
1713 struct delayed_work *dwork = to_delayed_work(work);
1714 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
1715 kvmclock_sync_work);
1716 struct kvm *kvm = container_of(ka, struct kvm, arch);
1718 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
1719 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
1720 KVMCLOCK_SYNC_PERIOD);
1723 static bool msr_mtrr_valid(unsigned msr)
1726 case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
1727 case MSR_MTRRfix64K_00000:
1728 case MSR_MTRRfix16K_80000:
1729 case MSR_MTRRfix16K_A0000:
1730 case MSR_MTRRfix4K_C0000:
1731 case MSR_MTRRfix4K_C8000:
1732 case MSR_MTRRfix4K_D0000:
1733 case MSR_MTRRfix4K_D8000:
1734 case MSR_MTRRfix4K_E0000:
1735 case MSR_MTRRfix4K_E8000:
1736 case MSR_MTRRfix4K_F0000:
1737 case MSR_MTRRfix4K_F8000:
1738 case MSR_MTRRdefType:
1739 case MSR_IA32_CR_PAT:
1747 static bool valid_pat_type(unsigned t)
1749 return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
1752 static bool valid_mtrr_type(unsigned t)
1754 return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
1757 bool kvm_mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1762 if (!msr_mtrr_valid(msr))
1765 if (msr == MSR_IA32_CR_PAT) {
1766 for (i = 0; i < 8; i++)
1767 if (!valid_pat_type((data >> (i * 8)) & 0xff))
1770 } else if (msr == MSR_MTRRdefType) {
1773 return valid_mtrr_type(data & 0xff);
1774 } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
1775 for (i = 0; i < 8 ; i++)
1776 if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
1781 /* variable MTRRs */
1782 WARN_ON(!(msr >= 0x200 && msr < 0x200 + 2 * KVM_NR_VAR_MTRR));
1784 mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
1785 if ((msr & 1) == 0) {
1787 if (!valid_mtrr_type(data & 0xff))
1794 kvm_inject_gp(vcpu, 0);
1800 EXPORT_SYMBOL_GPL(kvm_mtrr_valid);
1802 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1804 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1806 if (!kvm_mtrr_valid(vcpu, msr, data))
1809 if (msr == MSR_MTRRdefType) {
1810 vcpu->arch.mtrr_state.def_type = data;
1811 vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
1812 } else if (msr == MSR_MTRRfix64K_00000)
1814 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1815 p[1 + msr - MSR_MTRRfix16K_80000] = data;
1816 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1817 p[3 + msr - MSR_MTRRfix4K_C0000] = data;
1818 else if (msr == MSR_IA32_CR_PAT)
1819 vcpu->arch.pat = data;
1820 else { /* Variable MTRRs */
1821 int idx, is_mtrr_mask;
1824 idx = (msr - 0x200) / 2;
1825 is_mtrr_mask = msr - 0x200 - 2 * idx;
1828 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1831 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1835 kvm_mmu_reset_context(vcpu);
1839 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1841 u64 mcg_cap = vcpu->arch.mcg_cap;
1842 unsigned bank_num = mcg_cap & 0xff;
1845 case MSR_IA32_MCG_STATUS:
1846 vcpu->arch.mcg_status = data;
1848 case MSR_IA32_MCG_CTL:
1849 if (!(mcg_cap & MCG_CTL_P))
1851 if (data != 0 && data != ~(u64)0)
1853 vcpu->arch.mcg_ctl = data;
1856 if (msr >= MSR_IA32_MC0_CTL &&
1857 msr < MSR_IA32_MCx_CTL(bank_num)) {
1858 u32 offset = msr - MSR_IA32_MC0_CTL;
1859 /* only 0 or all 1s can be written to IA32_MCi_CTL
1860 * some Linux kernels though clear bit 10 in bank 4 to
1861 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
1862 * this to avoid an uncatched #GP in the guest
1864 if ((offset & 0x3) == 0 &&
1865 data != 0 && (data | (1 << 10)) != ~(u64)0)
1867 vcpu->arch.mce_banks[offset] = data;
1875 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
1877 struct kvm *kvm = vcpu->kvm;
1878 int lm = is_long_mode(vcpu);
1879 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
1880 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
1881 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
1882 : kvm->arch.xen_hvm_config.blob_size_32;
1883 u32 page_num = data & ~PAGE_MASK;
1884 u64 page_addr = data & PAGE_MASK;
1889 if (page_num >= blob_size)
1892 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
1897 if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
1906 static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
1908 return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
1911 static bool kvm_hv_msr_partition_wide(u32 msr)
1915 case HV_X64_MSR_GUEST_OS_ID:
1916 case HV_X64_MSR_HYPERCALL:
1917 case HV_X64_MSR_REFERENCE_TSC:
1918 case HV_X64_MSR_TIME_REF_COUNT:
1926 static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1928 struct kvm *kvm = vcpu->kvm;
1931 case HV_X64_MSR_GUEST_OS_ID:
1932 kvm->arch.hv_guest_os_id = data;
1933 /* setting guest os id to zero disables hypercall page */
1934 if (!kvm->arch.hv_guest_os_id)
1935 kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
1937 case HV_X64_MSR_HYPERCALL: {
1942 /* if guest os id is not set hypercall should remain disabled */
1943 if (!kvm->arch.hv_guest_os_id)
1945 if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
1946 kvm->arch.hv_hypercall = data;
1949 gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
1950 addr = gfn_to_hva(kvm, gfn);
1951 if (kvm_is_error_hva(addr))
1953 kvm_x86_ops->patch_hypercall(vcpu, instructions);
1954 ((unsigned char *)instructions)[3] = 0xc3; /* ret */
1955 if (__copy_to_user((void __user *)addr, instructions, 4))
1957 kvm->arch.hv_hypercall = data;
1958 mark_page_dirty(kvm, gfn);
1961 case HV_X64_MSR_REFERENCE_TSC: {
1963 HV_REFERENCE_TSC_PAGE tsc_ref;
1964 memset(&tsc_ref, 0, sizeof(tsc_ref));
1965 kvm->arch.hv_tsc_page = data;
1966 if (!(data & HV_X64_MSR_TSC_REFERENCE_ENABLE))
1968 gfn = data >> HV_X64_MSR_TSC_REFERENCE_ADDRESS_SHIFT;
1969 if (kvm_write_guest(kvm, gfn << HV_X64_MSR_TSC_REFERENCE_ADDRESS_SHIFT,
1970 &tsc_ref, sizeof(tsc_ref)))
1972 mark_page_dirty(kvm, gfn);
1976 vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1977 "data 0x%llx\n", msr, data);
1983 static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1986 case HV_X64_MSR_APIC_ASSIST_PAGE: {
1990 if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
1991 vcpu->arch.hv_vapic = data;
1992 if (kvm_lapic_enable_pv_eoi(vcpu, 0))
1996 gfn = data >> HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT;
1997 addr = gfn_to_hva(vcpu->kvm, gfn);
1998 if (kvm_is_error_hva(addr))
2000 if (__clear_user((void __user *)addr, PAGE_SIZE))
2002 vcpu->arch.hv_vapic = data;
2003 mark_page_dirty(vcpu->kvm, gfn);
2004 if (kvm_lapic_enable_pv_eoi(vcpu, gfn_to_gpa(gfn) | KVM_MSR_ENABLED))
2008 case HV_X64_MSR_EOI:
2009 return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
2010 case HV_X64_MSR_ICR:
2011 return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
2012 case HV_X64_MSR_TPR:
2013 return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
2015 vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
2016 "data 0x%llx\n", msr, data);
2023 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2025 gpa_t gpa = data & ~0x3f;
2027 /* Bits 2:5 are reserved, Should be zero */
2031 vcpu->arch.apf.msr_val = data;
2033 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2034 kvm_clear_async_pf_completion_queue(vcpu);
2035 kvm_async_pf_hash_reset(vcpu);
2039 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2043 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2044 kvm_async_pf_wakeup_all(vcpu);
2048 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2050 vcpu->arch.pv_time_enabled = false;
2053 static void accumulate_steal_time(struct kvm_vcpu *vcpu)
2057 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2060 delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
2061 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2062 vcpu->arch.st.accum_steal = delta;
2065 static void record_steal_time(struct kvm_vcpu *vcpu)
2067 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2070 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2071 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
2074 vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
2075 vcpu->arch.st.steal.version += 2;
2076 vcpu->arch.st.accum_steal = 0;
2078 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2079 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2082 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2085 u32 msr = msr_info->index;
2086 u64 data = msr_info->data;
2089 case MSR_AMD64_NB_CFG:
2090 case MSR_IA32_UCODE_REV:
2091 case MSR_IA32_UCODE_WRITE:
2092 case MSR_VM_HSAVE_PA:
2093 case MSR_AMD64_PATCH_LOADER:
2094 case MSR_AMD64_BU_CFG2:
2098 return set_efer(vcpu, data);
2100 data &= ~(u64)0x40; /* ignore flush filter disable */
2101 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2102 data &= ~(u64)0x8; /* ignore TLB cache disable */
2103 data &= ~(u64)0x40000; /* ignore Mc status write enable */
2105 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2110 case MSR_FAM10H_MMIO_CONF_BASE:
2112 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2117 case MSR_IA32_DEBUGCTLMSR:
2119 /* We support the non-activated case already */
2121 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2122 /* Values other than LBR and BTF are vendor-specific,
2123 thus reserved and should throw a #GP */
2126 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2129 case 0x200 ... 0x2ff:
2130 return set_msr_mtrr(vcpu, msr, data);
2131 case MSR_IA32_APICBASE:
2132 return kvm_set_apic_base(vcpu, msr_info);
2133 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2134 return kvm_x2apic_msr_write(vcpu, msr, data);
2135 case MSR_IA32_TSCDEADLINE:
2136 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2138 case MSR_IA32_TSC_ADJUST:
2139 if (guest_cpuid_has_tsc_adjust(vcpu)) {
2140 if (!msr_info->host_initiated) {
2141 u64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2142 kvm_x86_ops->adjust_tsc_offset(vcpu, adj, true);
2144 vcpu->arch.ia32_tsc_adjust_msr = data;
2147 case MSR_IA32_MISC_ENABLE:
2148 vcpu->arch.ia32_misc_enable_msr = data;
2150 case MSR_KVM_WALL_CLOCK_NEW:
2151 case MSR_KVM_WALL_CLOCK:
2152 vcpu->kvm->arch.wall_clock = data;
2153 kvm_write_wall_clock(vcpu->kvm, data);
2155 case MSR_KVM_SYSTEM_TIME_NEW:
2156 case MSR_KVM_SYSTEM_TIME: {
2158 kvmclock_reset(vcpu);
2160 vcpu->arch.time = data;
2161 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2163 /* we verify if the enable bit is set... */
2167 gpa_offset = data & ~(PAGE_MASK | 1);
2169 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2170 &vcpu->arch.pv_time, data & ~1ULL,
2171 sizeof(struct pvclock_vcpu_time_info)))
2172 vcpu->arch.pv_time_enabled = false;
2174 vcpu->arch.pv_time_enabled = true;
2178 case MSR_KVM_ASYNC_PF_EN:
2179 if (kvm_pv_enable_async_pf(vcpu, data))
2182 case MSR_KVM_STEAL_TIME:
2184 if (unlikely(!sched_info_on()))
2187 if (data & KVM_STEAL_RESERVED_MASK)
2190 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2191 data & KVM_STEAL_VALID_BITS,
2192 sizeof(struct kvm_steal_time)))
2195 vcpu->arch.st.msr_val = data;
2197 if (!(data & KVM_MSR_ENABLED))
2200 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2203 accumulate_steal_time(vcpu);
2206 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2209 case MSR_KVM_PV_EOI_EN:
2210 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2214 case MSR_IA32_MCG_CTL:
2215 case MSR_IA32_MCG_STATUS:
2216 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2217 return set_msr_mce(vcpu, msr, data);
2219 /* Performance counters are not protected by a CPUID bit,
2220 * so we should check all of them in the generic path for the sake of
2221 * cross vendor migration.
2222 * Writing a zero into the event select MSRs disables them,
2223 * which we perfectly emulate ;-). Any other value should be at least
2224 * reported, some guests depend on them.
2226 case MSR_K7_EVNTSEL0:
2227 case MSR_K7_EVNTSEL1:
2228 case MSR_K7_EVNTSEL2:
2229 case MSR_K7_EVNTSEL3:
2231 vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
2232 "0x%x data 0x%llx\n", msr, data);
2234 /* at least RHEL 4 unconditionally writes to the perfctr registers,
2235 * so we ignore writes to make it happy.
2237 case MSR_K7_PERFCTR0:
2238 case MSR_K7_PERFCTR1:
2239 case MSR_K7_PERFCTR2:
2240 case MSR_K7_PERFCTR3:
2241 vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
2242 "0x%x data 0x%llx\n", msr, data);
2244 case MSR_P6_PERFCTR0:
2245 case MSR_P6_PERFCTR1:
2247 case MSR_P6_EVNTSEL0:
2248 case MSR_P6_EVNTSEL1:
2249 if (kvm_pmu_msr(vcpu, msr))
2250 return kvm_pmu_set_msr(vcpu, msr_info);
2252 if (pr || data != 0)
2253 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2254 "0x%x data 0x%llx\n", msr, data);
2256 case MSR_K7_CLK_CTL:
2258 * Ignore all writes to this no longer documented MSR.
2259 * Writes are only relevant for old K7 processors,
2260 * all pre-dating SVM, but a recommended workaround from
2261 * AMD for these chips. It is possible to specify the
2262 * affected processor models on the command line, hence
2263 * the need to ignore the workaround.
2266 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2267 if (kvm_hv_msr_partition_wide(msr)) {
2269 mutex_lock(&vcpu->kvm->lock);
2270 r = set_msr_hyperv_pw(vcpu, msr, data);
2271 mutex_unlock(&vcpu->kvm->lock);
2274 return set_msr_hyperv(vcpu, msr, data);
2276 case MSR_IA32_BBL_CR_CTL3:
2277 /* Drop writes to this legacy MSR -- see rdmsr
2278 * counterpart for further detail.
2280 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
2282 case MSR_AMD64_OSVW_ID_LENGTH:
2283 if (!guest_cpuid_has_osvw(vcpu))
2285 vcpu->arch.osvw.length = data;
2287 case MSR_AMD64_OSVW_STATUS:
2288 if (!guest_cpuid_has_osvw(vcpu))
2290 vcpu->arch.osvw.status = data;
2293 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2294 return xen_hvm_config(vcpu, data);
2295 if (kvm_pmu_msr(vcpu, msr))
2296 return kvm_pmu_set_msr(vcpu, msr_info);
2298 vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
2302 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
2309 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2313 * Reads an msr value (of 'msr_index') into 'pdata'.
2314 * Returns 0 on success, non-0 otherwise.
2315 * Assumes vcpu_load() was already called.
2317 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2319 return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
2322 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2324 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
2326 if (!msr_mtrr_valid(msr))
2329 if (msr == MSR_MTRRdefType)
2330 *pdata = vcpu->arch.mtrr_state.def_type +
2331 (vcpu->arch.mtrr_state.enabled << 10);
2332 else if (msr == MSR_MTRRfix64K_00000)
2334 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
2335 *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
2336 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
2337 *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
2338 else if (msr == MSR_IA32_CR_PAT)
2339 *pdata = vcpu->arch.pat;
2340 else { /* Variable MTRRs */
2341 int idx, is_mtrr_mask;
2344 idx = (msr - 0x200) / 2;
2345 is_mtrr_mask = msr - 0x200 - 2 * idx;
2348 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
2351 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
2358 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2361 u64 mcg_cap = vcpu->arch.mcg_cap;
2362 unsigned bank_num = mcg_cap & 0xff;
2365 case MSR_IA32_P5_MC_ADDR:
2366 case MSR_IA32_P5_MC_TYPE:
2369 case MSR_IA32_MCG_CAP:
2370 data = vcpu->arch.mcg_cap;
2372 case MSR_IA32_MCG_CTL:
2373 if (!(mcg_cap & MCG_CTL_P))
2375 data = vcpu->arch.mcg_ctl;
2377 case MSR_IA32_MCG_STATUS:
2378 data = vcpu->arch.mcg_status;
2381 if (msr >= MSR_IA32_MC0_CTL &&
2382 msr < MSR_IA32_MCx_CTL(bank_num)) {
2383 u32 offset = msr - MSR_IA32_MC0_CTL;
2384 data = vcpu->arch.mce_banks[offset];
2393 static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2396 struct kvm *kvm = vcpu->kvm;
2399 case HV_X64_MSR_GUEST_OS_ID:
2400 data = kvm->arch.hv_guest_os_id;
2402 case HV_X64_MSR_HYPERCALL:
2403 data = kvm->arch.hv_hypercall;
2405 case HV_X64_MSR_TIME_REF_COUNT: {
2407 div_u64(get_kernel_ns() + kvm->arch.kvmclock_offset, 100);
2410 case HV_X64_MSR_REFERENCE_TSC:
2411 data = kvm->arch.hv_tsc_page;
2414 vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
2422 static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2427 case HV_X64_MSR_VP_INDEX: {
2430 kvm_for_each_vcpu(r, v, vcpu->kvm) {
2438 case HV_X64_MSR_EOI:
2439 return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
2440 case HV_X64_MSR_ICR:
2441 return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
2442 case HV_X64_MSR_TPR:
2443 return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
2444 case HV_X64_MSR_APIC_ASSIST_PAGE:
2445 data = vcpu->arch.hv_vapic;
2448 vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
2455 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2460 case MSR_IA32_PLATFORM_ID:
2461 case MSR_IA32_EBL_CR_POWERON:
2462 case MSR_IA32_DEBUGCTLMSR:
2463 case MSR_IA32_LASTBRANCHFROMIP:
2464 case MSR_IA32_LASTBRANCHTOIP:
2465 case MSR_IA32_LASTINTFROMIP:
2466 case MSR_IA32_LASTINTTOIP:
2469 case MSR_VM_HSAVE_PA:
2470 case MSR_K7_EVNTSEL0:
2471 case MSR_K7_EVNTSEL1:
2472 case MSR_K7_EVNTSEL2:
2473 case MSR_K7_EVNTSEL3:
2474 case MSR_K7_PERFCTR0:
2475 case MSR_K7_PERFCTR1:
2476 case MSR_K7_PERFCTR2:
2477 case MSR_K7_PERFCTR3:
2478 case MSR_K8_INT_PENDING_MSG:
2479 case MSR_AMD64_NB_CFG:
2480 case MSR_FAM10H_MMIO_CONF_BASE:
2481 case MSR_AMD64_BU_CFG2:
2484 case MSR_P6_PERFCTR0:
2485 case MSR_P6_PERFCTR1:
2486 case MSR_P6_EVNTSEL0:
2487 case MSR_P6_EVNTSEL1:
2488 if (kvm_pmu_msr(vcpu, msr))
2489 return kvm_pmu_get_msr(vcpu, msr, pdata);
2492 case MSR_IA32_UCODE_REV:
2493 data = 0x100000000ULL;
2496 data = 0x500 | KVM_NR_VAR_MTRR;
2498 case 0x200 ... 0x2ff:
2499 return get_msr_mtrr(vcpu, msr, pdata);
2500 case 0xcd: /* fsb frequency */
2504 * MSR_EBC_FREQUENCY_ID
2505 * Conservative value valid for even the basic CPU models.
2506 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2507 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2508 * and 266MHz for model 3, or 4. Set Core Clock
2509 * Frequency to System Bus Frequency Ratio to 1 (bits
2510 * 31:24) even though these are only valid for CPU
2511 * models > 2, however guests may end up dividing or
2512 * multiplying by zero otherwise.
2514 case MSR_EBC_FREQUENCY_ID:
2517 case MSR_IA32_APICBASE:
2518 data = kvm_get_apic_base(vcpu);
2520 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2521 return kvm_x2apic_msr_read(vcpu, msr, pdata);
2523 case MSR_IA32_TSCDEADLINE:
2524 data = kvm_get_lapic_tscdeadline_msr(vcpu);
2526 case MSR_IA32_TSC_ADJUST:
2527 data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2529 case MSR_IA32_MISC_ENABLE:
2530 data = vcpu->arch.ia32_misc_enable_msr;
2532 case MSR_IA32_PERF_STATUS:
2533 /* TSC increment by tick */
2535 /* CPU multiplier */
2536 data |= (((uint64_t)4ULL) << 40);
2539 data = vcpu->arch.efer;
2541 case MSR_KVM_WALL_CLOCK:
2542 case MSR_KVM_WALL_CLOCK_NEW:
2543 data = vcpu->kvm->arch.wall_clock;
2545 case MSR_KVM_SYSTEM_TIME:
2546 case MSR_KVM_SYSTEM_TIME_NEW:
2547 data = vcpu->arch.time;
2549 case MSR_KVM_ASYNC_PF_EN:
2550 data = vcpu->arch.apf.msr_val;
2552 case MSR_KVM_STEAL_TIME:
2553 data = vcpu->arch.st.msr_val;
2555 case MSR_KVM_PV_EOI_EN:
2556 data = vcpu->arch.pv_eoi.msr_val;
2558 case MSR_IA32_P5_MC_ADDR:
2559 case MSR_IA32_P5_MC_TYPE:
2560 case MSR_IA32_MCG_CAP:
2561 case MSR_IA32_MCG_CTL:
2562 case MSR_IA32_MCG_STATUS:
2563 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2564 return get_msr_mce(vcpu, msr, pdata);
2565 case MSR_K7_CLK_CTL:
2567 * Provide expected ramp-up count for K7. All other
2568 * are set to zero, indicating minimum divisors for
2571 * This prevents guest kernels on AMD host with CPU
2572 * type 6, model 8 and higher from exploding due to
2573 * the rdmsr failing.
2577 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2578 if (kvm_hv_msr_partition_wide(msr)) {
2580 mutex_lock(&vcpu->kvm->lock);
2581 r = get_msr_hyperv_pw(vcpu, msr, pdata);
2582 mutex_unlock(&vcpu->kvm->lock);
2585 return get_msr_hyperv(vcpu, msr, pdata);
2587 case MSR_IA32_BBL_CR_CTL3:
2588 /* This legacy MSR exists but isn't fully documented in current
2589 * silicon. It is however accessed by winxp in very narrow
2590 * scenarios where it sets bit #19, itself documented as
2591 * a "reserved" bit. Best effort attempt to source coherent
2592 * read data here should the balance of the register be
2593 * interpreted by the guest:
2595 * L2 cache control register 3: 64GB range, 256KB size,
2596 * enabled, latency 0x1, configured
2600 case MSR_AMD64_OSVW_ID_LENGTH:
2601 if (!guest_cpuid_has_osvw(vcpu))
2603 data = vcpu->arch.osvw.length;
2605 case MSR_AMD64_OSVW_STATUS:
2606 if (!guest_cpuid_has_osvw(vcpu))
2608 data = vcpu->arch.osvw.status;
2611 if (kvm_pmu_msr(vcpu, msr))
2612 return kvm_pmu_get_msr(vcpu, msr, pdata);
2614 vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
2617 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
2625 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2628 * Read or write a bunch of msrs. All parameters are kernel addresses.
2630 * @return number of msrs set successfully.
2632 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2633 struct kvm_msr_entry *entries,
2634 int (*do_msr)(struct kvm_vcpu *vcpu,
2635 unsigned index, u64 *data))
2639 idx = srcu_read_lock(&vcpu->kvm->srcu);
2640 for (i = 0; i < msrs->nmsrs; ++i)
2641 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2643 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2649 * Read or write a bunch of msrs. Parameters are user addresses.
2651 * @return number of msrs set successfully.
2653 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2654 int (*do_msr)(struct kvm_vcpu *vcpu,
2655 unsigned index, u64 *data),
2658 struct kvm_msrs msrs;
2659 struct kvm_msr_entry *entries;
2664 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2668 if (msrs.nmsrs >= MAX_IO_MSRS)
2671 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2672 entries = memdup_user(user_msrs->entries, size);
2673 if (IS_ERR(entries)) {
2674 r = PTR_ERR(entries);
2678 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2683 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2694 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2699 case KVM_CAP_IRQCHIP:
2701 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2702 case KVM_CAP_SET_TSS_ADDR:
2703 case KVM_CAP_EXT_CPUID:
2704 case KVM_CAP_EXT_EMUL_CPUID:
2705 case KVM_CAP_CLOCKSOURCE:
2707 case KVM_CAP_NOP_IO_DELAY:
2708 case KVM_CAP_MP_STATE:
2709 case KVM_CAP_SYNC_MMU:
2710 case KVM_CAP_USER_NMI:
2711 case KVM_CAP_REINJECT_CONTROL:
2712 case KVM_CAP_IRQ_INJECT_STATUS:
2714 case KVM_CAP_IOEVENTFD:
2715 case KVM_CAP_IOEVENTFD_NO_LENGTH:
2717 case KVM_CAP_PIT_STATE2:
2718 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2719 case KVM_CAP_XEN_HVM:
2720 case KVM_CAP_ADJUST_CLOCK:
2721 case KVM_CAP_VCPU_EVENTS:
2722 case KVM_CAP_HYPERV:
2723 case KVM_CAP_HYPERV_VAPIC:
2724 case KVM_CAP_HYPERV_SPIN:
2725 case KVM_CAP_PCI_SEGMENT:
2726 case KVM_CAP_DEBUGREGS:
2727 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2729 case KVM_CAP_ASYNC_PF:
2730 case KVM_CAP_GET_TSC_KHZ:
2731 case KVM_CAP_KVMCLOCK_CTRL:
2732 case KVM_CAP_READONLY_MEM:
2733 case KVM_CAP_HYPERV_TIME:
2734 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2735 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2736 case KVM_CAP_ASSIGN_DEV_IRQ:
2737 case KVM_CAP_PCI_2_3:
2741 case KVM_CAP_COALESCED_MMIO:
2742 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2745 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2747 case KVM_CAP_NR_VCPUS:
2748 r = KVM_SOFT_MAX_VCPUS;
2750 case KVM_CAP_MAX_VCPUS:
2753 case KVM_CAP_NR_MEMSLOTS:
2754 r = KVM_USER_MEM_SLOTS;
2756 case KVM_CAP_PV_MMU: /* obsolete */
2759 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2761 r = iommu_present(&pci_bus_type);
2765 r = KVM_MAX_MCE_BANKS;
2770 case KVM_CAP_TSC_CONTROL:
2771 r = kvm_has_tsc_control;
2773 case KVM_CAP_TSC_DEADLINE_TIMER:
2774 r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
2784 long kvm_arch_dev_ioctl(struct file *filp,
2785 unsigned int ioctl, unsigned long arg)
2787 void __user *argp = (void __user *)arg;
2791 case KVM_GET_MSR_INDEX_LIST: {
2792 struct kvm_msr_list __user *user_msr_list = argp;
2793 struct kvm_msr_list msr_list;
2797 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2800 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
2801 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2804 if (n < msr_list.nmsrs)
2807 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2808 num_msrs_to_save * sizeof(u32)))
2810 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2812 ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
2817 case KVM_GET_SUPPORTED_CPUID:
2818 case KVM_GET_EMULATED_CPUID: {
2819 struct kvm_cpuid2 __user *cpuid_arg = argp;
2820 struct kvm_cpuid2 cpuid;
2823 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2826 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2832 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2837 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2840 mce_cap = KVM_MCE_CAP_SUPPORTED;
2842 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2854 static void wbinvd_ipi(void *garbage)
2859 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2861 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2864 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2866 /* Address WBINVD may be executed by guest */
2867 if (need_emulate_wbinvd(vcpu)) {
2868 if (kvm_x86_ops->has_wbinvd_exit())
2869 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2870 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2871 smp_call_function_single(vcpu->cpu,
2872 wbinvd_ipi, NULL, 1);
2875 kvm_x86_ops->vcpu_load(vcpu, cpu);
2877 /* Apply any externally detected TSC adjustments (due to suspend) */
2878 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2879 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2880 vcpu->arch.tsc_offset_adjustment = 0;
2881 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2884 if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2885 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2886 native_read_tsc() - vcpu->arch.last_host_tsc;
2888 mark_tsc_unstable("KVM discovered backwards TSC");
2889 if (check_tsc_unstable()) {
2890 u64 offset = kvm_x86_ops->compute_tsc_offset(vcpu,
2891 vcpu->arch.last_guest_tsc);
2892 kvm_x86_ops->write_tsc_offset(vcpu, offset);
2893 vcpu->arch.tsc_catchup = 1;
2896 * On a host with synchronized TSC, there is no need to update
2897 * kvmclock on vcpu->cpu migration
2899 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
2900 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2901 if (vcpu->cpu != cpu)
2902 kvm_migrate_timers(vcpu);
2906 accumulate_steal_time(vcpu);
2907 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2910 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2912 kvm_x86_ops->vcpu_put(vcpu);
2913 kvm_put_guest_fpu(vcpu);
2914 vcpu->arch.last_host_tsc = native_read_tsc();
2917 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2918 struct kvm_lapic_state *s)
2920 kvm_x86_ops->sync_pir_to_irr(vcpu);
2921 memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2926 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2927 struct kvm_lapic_state *s)
2929 kvm_apic_post_state_restore(vcpu, s);
2930 update_cr8_intercept(vcpu);
2935 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2936 struct kvm_interrupt *irq)
2938 if (irq->irq >= KVM_NR_INTERRUPTS)
2940 if (irqchip_in_kernel(vcpu->kvm))
2943 kvm_queue_interrupt(vcpu, irq->irq, false);
2944 kvm_make_request(KVM_REQ_EVENT, vcpu);
2949 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2951 kvm_inject_nmi(vcpu);
2956 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2957 struct kvm_tpr_access_ctl *tac)
2961 vcpu->arch.tpr_access_reporting = !!tac->enabled;
2965 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2969 unsigned bank_num = mcg_cap & 0xff, bank;
2972 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2974 if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2977 vcpu->arch.mcg_cap = mcg_cap;
2978 /* Init IA32_MCG_CTL to all 1s */
2979 if (mcg_cap & MCG_CTL_P)
2980 vcpu->arch.mcg_ctl = ~(u64)0;
2981 /* Init IA32_MCi_CTL to all 1s */
2982 for (bank = 0; bank < bank_num; bank++)
2983 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2988 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2989 struct kvm_x86_mce *mce)
2991 u64 mcg_cap = vcpu->arch.mcg_cap;
2992 unsigned bank_num = mcg_cap & 0xff;
2993 u64 *banks = vcpu->arch.mce_banks;
2995 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2998 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2999 * reporting is disabled
3001 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3002 vcpu->arch.mcg_ctl != ~(u64)0)
3004 banks += 4 * mce->bank;
3006 * if IA32_MCi_CTL is not all 1s, the uncorrected error
3007 * reporting is disabled for the bank
3009 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3011 if (mce->status & MCI_STATUS_UC) {
3012 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3013 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3014 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3017 if (banks[1] & MCI_STATUS_VAL)
3018 mce->status |= MCI_STATUS_OVER;
3019 banks[2] = mce->addr;
3020 banks[3] = mce->misc;
3021 vcpu->arch.mcg_status = mce->mcg_status;
3022 banks[1] = mce->status;
3023 kvm_queue_exception(vcpu, MC_VECTOR);
3024 } else if (!(banks[1] & MCI_STATUS_VAL)
3025 || !(banks[1] & MCI_STATUS_UC)) {
3026 if (banks[1] & MCI_STATUS_VAL)
3027 mce->status |= MCI_STATUS_OVER;
3028 banks[2] = mce->addr;
3029 banks[3] = mce->misc;
3030 banks[1] = mce->status;
3032 banks[1] |= MCI_STATUS_OVER;
3036 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3037 struct kvm_vcpu_events *events)
3040 events->exception.injected =
3041 vcpu->arch.exception.pending &&
3042 !kvm_exception_is_soft(vcpu->arch.exception.nr);
3043 events->exception.nr = vcpu->arch.exception.nr;
3044 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3045 events->exception.pad = 0;
3046 events->exception.error_code = vcpu->arch.exception.error_code;
3048 events->interrupt.injected =
3049 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
3050 events->interrupt.nr = vcpu->arch.interrupt.nr;
3051 events->interrupt.soft = 0;
3052 events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3054 events->nmi.injected = vcpu->arch.nmi_injected;
3055 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3056 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3057 events->nmi.pad = 0;
3059 events->sipi_vector = 0; /* never valid when reporting to user space */
3061 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3062 | KVM_VCPUEVENT_VALID_SHADOW);
3063 memset(&events->reserved, 0, sizeof(events->reserved));
3066 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3067 struct kvm_vcpu_events *events)
3069 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3070 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3071 | KVM_VCPUEVENT_VALID_SHADOW))
3075 vcpu->arch.exception.pending = events->exception.injected;
3076 vcpu->arch.exception.nr = events->exception.nr;
3077 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3078 vcpu->arch.exception.error_code = events->exception.error_code;
3080 vcpu->arch.interrupt.pending = events->interrupt.injected;
3081 vcpu->arch.interrupt.nr = events->interrupt.nr;
3082 vcpu->arch.interrupt.soft = events->interrupt.soft;
3083 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3084 kvm_x86_ops->set_interrupt_shadow(vcpu,
3085 events->interrupt.shadow);
3087 vcpu->arch.nmi_injected = events->nmi.injected;
3088 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3089 vcpu->arch.nmi_pending = events->nmi.pending;
3090 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3092 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3093 kvm_vcpu_has_lapic(vcpu))
3094 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3096 kvm_make_request(KVM_REQ_EVENT, vcpu);
3101 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3102 struct kvm_debugregs *dbgregs)
3106 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3107 kvm_get_dr(vcpu, 6, &val);
3109 dbgregs->dr7 = vcpu->arch.dr7;
3111 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3114 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3115 struct kvm_debugregs *dbgregs)
3120 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3121 vcpu->arch.dr6 = dbgregs->dr6;
3122 kvm_update_dr6(vcpu);
3123 vcpu->arch.dr7 = dbgregs->dr7;
3124 kvm_update_dr7(vcpu);
3129 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3130 struct kvm_xsave *guest_xsave)
3132 if (cpu_has_xsave) {
3133 memcpy(guest_xsave->region,
3134 &vcpu->arch.guest_fpu.state->xsave,
3135 vcpu->arch.guest_xstate_size);
3136 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] &=
3137 vcpu->arch.guest_supported_xcr0 | XSTATE_FPSSE;
3139 memcpy(guest_xsave->region,
3140 &vcpu->arch.guest_fpu.state->fxsave,
3141 sizeof(struct i387_fxsave_struct));
3142 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3147 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3148 struct kvm_xsave *guest_xsave)
3151 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3153 if (cpu_has_xsave) {
3155 * Here we allow setting states that are not present in
3156 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
3157 * with old userspace.
3159 if (xstate_bv & ~kvm_supported_xcr0())
3161 memcpy(&vcpu->arch.guest_fpu.state->xsave,
3162 guest_xsave->region, vcpu->arch.guest_xstate_size);
3164 if (xstate_bv & ~XSTATE_FPSSE)
3166 memcpy(&vcpu->arch.guest_fpu.state->fxsave,
3167 guest_xsave->region, sizeof(struct i387_fxsave_struct));
3172 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3173 struct kvm_xcrs *guest_xcrs)
3175 if (!cpu_has_xsave) {
3176 guest_xcrs->nr_xcrs = 0;
3180 guest_xcrs->nr_xcrs = 1;
3181 guest_xcrs->flags = 0;
3182 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3183 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3186 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3187 struct kvm_xcrs *guest_xcrs)
3194 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3197 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3198 /* Only support XCR0 currently */
3199 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3200 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3201 guest_xcrs->xcrs[i].value);
3210 * kvm_set_guest_paused() indicates to the guest kernel that it has been
3211 * stopped by the hypervisor. This function will be called from the host only.
3212 * EINVAL is returned when the host attempts to set the flag for a guest that
3213 * does not support pv clocks.
3215 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3217 if (!vcpu->arch.pv_time_enabled)
3219 vcpu->arch.pvclock_set_guest_stopped_request = true;
3220 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3224 long kvm_arch_vcpu_ioctl(struct file *filp,
3225 unsigned int ioctl, unsigned long arg)
3227 struct kvm_vcpu *vcpu = filp->private_data;
3228 void __user *argp = (void __user *)arg;
3231 struct kvm_lapic_state *lapic;
3232 struct kvm_xsave *xsave;
3233 struct kvm_xcrs *xcrs;
3239 case KVM_GET_LAPIC: {
3241 if (!vcpu->arch.apic)
3243 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3248 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3252 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3257 case KVM_SET_LAPIC: {
3259 if (!vcpu->arch.apic)
3261 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3262 if (IS_ERR(u.lapic))
3263 return PTR_ERR(u.lapic);
3265 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3268 case KVM_INTERRUPT: {
3269 struct kvm_interrupt irq;
3272 if (copy_from_user(&irq, argp, sizeof irq))
3274 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3278 r = kvm_vcpu_ioctl_nmi(vcpu);
3281 case KVM_SET_CPUID: {
3282 struct kvm_cpuid __user *cpuid_arg = argp;
3283 struct kvm_cpuid cpuid;
3286 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3288 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3291 case KVM_SET_CPUID2: {
3292 struct kvm_cpuid2 __user *cpuid_arg = argp;
3293 struct kvm_cpuid2 cpuid;
3296 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3298 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3299 cpuid_arg->entries);
3302 case KVM_GET_CPUID2: {
3303 struct kvm_cpuid2 __user *cpuid_arg = argp;
3304 struct kvm_cpuid2 cpuid;
3307 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3309 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3310 cpuid_arg->entries);
3314 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3320 r = msr_io(vcpu, argp, kvm_get_msr, 1);
3323 r = msr_io(vcpu, argp, do_set_msr, 0);
3325 case KVM_TPR_ACCESS_REPORTING: {
3326 struct kvm_tpr_access_ctl tac;
3329 if (copy_from_user(&tac, argp, sizeof tac))
3331 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3335 if (copy_to_user(argp, &tac, sizeof tac))
3340 case KVM_SET_VAPIC_ADDR: {
3341 struct kvm_vapic_addr va;
3344 if (!irqchip_in_kernel(vcpu->kvm))
3347 if (copy_from_user(&va, argp, sizeof va))
3349 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3352 case KVM_X86_SETUP_MCE: {
3356 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3358 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3361 case KVM_X86_SET_MCE: {
3362 struct kvm_x86_mce mce;
3365 if (copy_from_user(&mce, argp, sizeof mce))
3367 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3370 case KVM_GET_VCPU_EVENTS: {
3371 struct kvm_vcpu_events events;
3373 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3376 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3381 case KVM_SET_VCPU_EVENTS: {
3382 struct kvm_vcpu_events events;
3385 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3388 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3391 case KVM_GET_DEBUGREGS: {
3392 struct kvm_debugregs dbgregs;
3394 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3397 if (copy_to_user(argp, &dbgregs,
3398 sizeof(struct kvm_debugregs)))
3403 case KVM_SET_DEBUGREGS: {
3404 struct kvm_debugregs dbgregs;
3407 if (copy_from_user(&dbgregs, argp,
3408 sizeof(struct kvm_debugregs)))
3411 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3414 case KVM_GET_XSAVE: {
3415 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3420 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3423 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3428 case KVM_SET_XSAVE: {
3429 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3430 if (IS_ERR(u.xsave))
3431 return PTR_ERR(u.xsave);
3433 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3436 case KVM_GET_XCRS: {
3437 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3442 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3445 if (copy_to_user(argp, u.xcrs,
3446 sizeof(struct kvm_xcrs)))
3451 case KVM_SET_XCRS: {
3452 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3454 return PTR_ERR(u.xcrs);
3456 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3459 case KVM_SET_TSC_KHZ: {
3463 user_tsc_khz = (u32)arg;
3465 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3468 if (user_tsc_khz == 0)
3469 user_tsc_khz = tsc_khz;
3471 kvm_set_tsc_khz(vcpu, user_tsc_khz);
3476 case KVM_GET_TSC_KHZ: {
3477 r = vcpu->arch.virtual_tsc_khz;
3480 case KVM_KVMCLOCK_CTRL: {
3481 r = kvm_set_guest_paused(vcpu);
3492 int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3494 return VM_FAULT_SIGBUS;
3497 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3501 if (addr > (unsigned int)(-3 * PAGE_SIZE))
3503 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3507 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3510 kvm->arch.ept_identity_map_addr = ident_addr;
3514 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3515 u32 kvm_nr_mmu_pages)
3517 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3520 mutex_lock(&kvm->slots_lock);
3522 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3523 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3525 mutex_unlock(&kvm->slots_lock);
3529 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3531 return kvm->arch.n_max_mmu_pages;
3534 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3539 switch (chip->chip_id) {
3540 case KVM_IRQCHIP_PIC_MASTER:
3541 memcpy(&chip->chip.pic,
3542 &pic_irqchip(kvm)->pics[0],
3543 sizeof(struct kvm_pic_state));
3545 case KVM_IRQCHIP_PIC_SLAVE:
3546 memcpy(&chip->chip.pic,
3547 &pic_irqchip(kvm)->pics[1],
3548 sizeof(struct kvm_pic_state));
3550 case KVM_IRQCHIP_IOAPIC:
3551 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3560 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3565 switch (chip->chip_id) {
3566 case KVM_IRQCHIP_PIC_MASTER:
3567 spin_lock(&pic_irqchip(kvm)->lock);
3568 memcpy(&pic_irqchip(kvm)->pics[0],
3570 sizeof(struct kvm_pic_state));
3571 spin_unlock(&pic_irqchip(kvm)->lock);
3573 case KVM_IRQCHIP_PIC_SLAVE:
3574 spin_lock(&pic_irqchip(kvm)->lock);
3575 memcpy(&pic_irqchip(kvm)->pics[1],
3577 sizeof(struct kvm_pic_state));
3578 spin_unlock(&pic_irqchip(kvm)->lock);
3580 case KVM_IRQCHIP_IOAPIC:
3581 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3587 kvm_pic_update_irq(pic_irqchip(kvm));
3591 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3595 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3596 memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
3597 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3601 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3605 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3606 memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
3607 kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
3608 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3612 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3616 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3617 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3618 sizeof(ps->channels));
3619 ps->flags = kvm->arch.vpit->pit_state.flags;
3620 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3621 memset(&ps->reserved, 0, sizeof(ps->reserved));
3625 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3627 int r = 0, start = 0;
3628 u32 prev_legacy, cur_legacy;
3629 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3630 prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3631 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3632 if (!prev_legacy && cur_legacy)
3634 memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
3635 sizeof(kvm->arch.vpit->pit_state.channels));
3636 kvm->arch.vpit->pit_state.flags = ps->flags;
3637 kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
3638 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3642 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3643 struct kvm_reinject_control *control)
3645 if (!kvm->arch.vpit)
3647 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3648 kvm->arch.vpit->pit_state.reinject = control->pit_reinject;
3649 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3654 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
3655 * @kvm: kvm instance
3656 * @log: slot id and address to which we copy the log
3658 * We need to keep it in mind that VCPU threads can write to the bitmap
3659 * concurrently. So, to avoid losing data, we keep the following order for
3662 * 1. Take a snapshot of the bit and clear it if needed.
3663 * 2. Write protect the corresponding page.
3664 * 3. Flush TLB's if needed.
3665 * 4. Copy the snapshot to the userspace.
3667 * Between 2 and 3, the guest may write to the page using the remaining TLB
3668 * entry. This is not a problem because the page will be reported dirty at
3669 * step 4 using the snapshot taken before and step 3 ensures that successive
3670 * writes will be logged for the next call.
3672 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
3675 struct kvm_memory_slot *memslot;
3677 unsigned long *dirty_bitmap;
3678 unsigned long *dirty_bitmap_buffer;
3679 bool is_dirty = false;
3681 mutex_lock(&kvm->slots_lock);
3684 if (log->slot >= KVM_USER_MEM_SLOTS)
3687 memslot = id_to_memslot(kvm->memslots, log->slot);
3689 dirty_bitmap = memslot->dirty_bitmap;
3694 n = kvm_dirty_bitmap_bytes(memslot);
3696 dirty_bitmap_buffer = dirty_bitmap + n / sizeof(long);
3697 memset(dirty_bitmap_buffer, 0, n);
3699 spin_lock(&kvm->mmu_lock);
3701 for (i = 0; i < n / sizeof(long); i++) {
3705 if (!dirty_bitmap[i])
3710 mask = xchg(&dirty_bitmap[i], 0);
3711 dirty_bitmap_buffer[i] = mask;
3713 offset = i * BITS_PER_LONG;
3714 kvm_mmu_write_protect_pt_masked(kvm, memslot, offset, mask);
3717 spin_unlock(&kvm->mmu_lock);
3719 /* See the comments in kvm_mmu_slot_remove_write_access(). */
3720 lockdep_assert_held(&kvm->slots_lock);
3723 * All the TLBs can be flushed out of mmu lock, see the comments in
3724 * kvm_mmu_slot_remove_write_access().
3727 kvm_flush_remote_tlbs(kvm);
3730 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
3735 mutex_unlock(&kvm->slots_lock);
3739 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
3742 if (!irqchip_in_kernel(kvm))
3745 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3746 irq_event->irq, irq_event->level,
3751 long kvm_arch_vm_ioctl(struct file *filp,
3752 unsigned int ioctl, unsigned long arg)
3754 struct kvm *kvm = filp->private_data;
3755 void __user *argp = (void __user *)arg;
3758 * This union makes it completely explicit to gcc-3.x
3759 * that these two variables' stack usage should be
3760 * combined, not added together.
3763 struct kvm_pit_state ps;
3764 struct kvm_pit_state2 ps2;
3765 struct kvm_pit_config pit_config;
3769 case KVM_SET_TSS_ADDR:
3770 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3772 case KVM_SET_IDENTITY_MAP_ADDR: {
3776 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3778 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3781 case KVM_SET_NR_MMU_PAGES:
3782 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3784 case KVM_GET_NR_MMU_PAGES:
3785 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3787 case KVM_CREATE_IRQCHIP: {
3788 struct kvm_pic *vpic;
3790 mutex_lock(&kvm->lock);
3793 goto create_irqchip_unlock;
3795 if (atomic_read(&kvm->online_vcpus))
3796 goto create_irqchip_unlock;
3798 vpic = kvm_create_pic(kvm);
3800 r = kvm_ioapic_init(kvm);
3802 mutex_lock(&kvm->slots_lock);
3803 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3805 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3807 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3809 mutex_unlock(&kvm->slots_lock);
3811 goto create_irqchip_unlock;
3814 goto create_irqchip_unlock;
3816 kvm->arch.vpic = vpic;
3818 r = kvm_setup_default_irq_routing(kvm);
3820 mutex_lock(&kvm->slots_lock);
3821 mutex_lock(&kvm->irq_lock);
3822 kvm_ioapic_destroy(kvm);
3823 kvm_destroy_pic(kvm);
3824 mutex_unlock(&kvm->irq_lock);
3825 mutex_unlock(&kvm->slots_lock);
3827 create_irqchip_unlock:
3828 mutex_unlock(&kvm->lock);
3831 case KVM_CREATE_PIT:
3832 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3834 case KVM_CREATE_PIT2:
3836 if (copy_from_user(&u.pit_config, argp,
3837 sizeof(struct kvm_pit_config)))
3840 mutex_lock(&kvm->slots_lock);
3843 goto create_pit_unlock;
3845 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3849 mutex_unlock(&kvm->slots_lock);
3851 case KVM_GET_IRQCHIP: {
3852 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3853 struct kvm_irqchip *chip;
3855 chip = memdup_user(argp, sizeof(*chip));
3862 if (!irqchip_in_kernel(kvm))
3863 goto get_irqchip_out;
3864 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3866 goto get_irqchip_out;
3868 if (copy_to_user(argp, chip, sizeof *chip))
3869 goto get_irqchip_out;
3875 case KVM_SET_IRQCHIP: {
3876 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3877 struct kvm_irqchip *chip;
3879 chip = memdup_user(argp, sizeof(*chip));
3886 if (!irqchip_in_kernel(kvm))
3887 goto set_irqchip_out;
3888 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3890 goto set_irqchip_out;
3898 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
3901 if (!kvm->arch.vpit)
3903 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
3907 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
3914 if (copy_from_user(&u.ps, argp, sizeof u.ps))
3917 if (!kvm->arch.vpit)
3919 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
3922 case KVM_GET_PIT2: {
3924 if (!kvm->arch.vpit)
3926 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
3930 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
3935 case KVM_SET_PIT2: {
3937 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
3940 if (!kvm->arch.vpit)
3942 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
3945 case KVM_REINJECT_CONTROL: {
3946 struct kvm_reinject_control control;
3948 if (copy_from_user(&control, argp, sizeof(control)))
3950 r = kvm_vm_ioctl_reinject(kvm, &control);
3953 case KVM_XEN_HVM_CONFIG: {
3955 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
3956 sizeof(struct kvm_xen_hvm_config)))
3959 if (kvm->arch.xen_hvm_config.flags)
3964 case KVM_SET_CLOCK: {
3965 struct kvm_clock_data user_ns;
3970 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
3978 local_irq_disable();
3979 now_ns = get_kernel_ns();
3980 delta = user_ns.clock - now_ns;
3982 kvm->arch.kvmclock_offset = delta;
3983 kvm_gen_update_masterclock(kvm);
3986 case KVM_GET_CLOCK: {
3987 struct kvm_clock_data user_ns;
3990 local_irq_disable();
3991 now_ns = get_kernel_ns();
3992 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
3995 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
3998 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
4011 static void kvm_init_msr_list(void)
4016 /* skip the first msrs in the list. KVM-specific */
4017 for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
4018 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
4022 * Even MSRs that are valid in the host may not be exposed
4023 * to the guests in some cases. We could work around this
4024 * in VMX with the generic MSR save/load machinery, but it
4025 * is not really worthwhile since it will really only
4026 * happen with nested virtualization.
4028 switch (msrs_to_save[i]) {
4029 case MSR_IA32_BNDCFGS:
4030 if (!kvm_x86_ops->mpx_supported())
4038 msrs_to_save[j] = msrs_to_save[i];
4041 num_msrs_to_save = j;
4044 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
4052 if (!(vcpu->arch.apic &&
4053 !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, n, v))
4054 && kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
4065 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
4072 if (!(vcpu->arch.apic &&
4073 !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, n, v))
4074 && kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
4076 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
4086 static void kvm_set_segment(struct kvm_vcpu *vcpu,
4087 struct kvm_segment *var, int seg)
4089 kvm_x86_ops->set_segment(vcpu, var, seg);
4092 void kvm_get_segment(struct kvm_vcpu *vcpu,
4093 struct kvm_segment *var, int seg)
4095 kvm_x86_ops->get_segment(vcpu, var, seg);
4098 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
4099 struct x86_exception *exception)
4103 BUG_ON(!mmu_is_nested(vcpu));
4105 /* NPT walks are always user-walks */
4106 access |= PFERR_USER_MASK;
4107 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
4112 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
4113 struct x86_exception *exception)
4115 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4116 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4119 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
4120 struct x86_exception *exception)
4122 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4123 access |= PFERR_FETCH_MASK;
4124 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4127 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4128 struct x86_exception *exception)
4130 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4131 access |= PFERR_WRITE_MASK;
4132 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4135 /* uses this to access any guest's mapped memory without checking CPL */
4136 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4137 struct x86_exception *exception)
4139 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
4142 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4143 struct kvm_vcpu *vcpu, u32 access,
4144 struct x86_exception *exception)
4147 int r = X86EMUL_CONTINUE;
4150 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4152 unsigned offset = addr & (PAGE_SIZE-1);
4153 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4156 if (gpa == UNMAPPED_GVA)
4157 return X86EMUL_PROPAGATE_FAULT;
4158 ret = kvm_read_guest_page(vcpu->kvm, gpa >> PAGE_SHIFT, data,
4161 r = X86EMUL_IO_NEEDED;
4173 /* used for instruction fetching */
4174 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4175 gva_t addr, void *val, unsigned int bytes,
4176 struct x86_exception *exception)
4178 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4179 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4183 /* Inline kvm_read_guest_virt_helper for speed. */
4184 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
4186 if (unlikely(gpa == UNMAPPED_GVA))
4187 return X86EMUL_PROPAGATE_FAULT;
4189 offset = addr & (PAGE_SIZE-1);
4190 if (WARN_ON(offset + bytes > PAGE_SIZE))
4191 bytes = (unsigned)PAGE_SIZE - offset;
4192 ret = kvm_read_guest_page(vcpu->kvm, gpa >> PAGE_SHIFT, val,
4194 if (unlikely(ret < 0))
4195 return X86EMUL_IO_NEEDED;
4197 return X86EMUL_CONTINUE;
4200 int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
4201 gva_t addr, void *val, unsigned int bytes,
4202 struct x86_exception *exception)
4204 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4205 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4207 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4210 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4212 static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4213 gva_t addr, void *val, unsigned int bytes,
4214 struct x86_exception *exception)
4216 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4217 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
4220 int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4221 gva_t addr, void *val,
4223 struct x86_exception *exception)
4225 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4227 int r = X86EMUL_CONTINUE;
4230 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4233 unsigned offset = addr & (PAGE_SIZE-1);
4234 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4237 if (gpa == UNMAPPED_GVA)
4238 return X86EMUL_PROPAGATE_FAULT;
4239 ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
4241 r = X86EMUL_IO_NEEDED;
4252 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4254 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4255 gpa_t *gpa, struct x86_exception *exception,
4258 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
4259 | (write ? PFERR_WRITE_MASK : 0);
4261 if (vcpu_match_mmio_gva(vcpu, gva)
4262 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
4263 vcpu->arch.access, access)) {
4264 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4265 (gva & (PAGE_SIZE - 1));
4266 trace_vcpu_match_mmio(gva, *gpa, write, false);
4270 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4272 if (*gpa == UNMAPPED_GVA)
4275 /* For APIC access vmexit */
4276 if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4279 if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
4280 trace_vcpu_match_mmio(gva, *gpa, write, true);
4287 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4288 const void *val, int bytes)
4292 ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
4295 kvm_mmu_pte_write(vcpu, gpa, val, bytes);
4299 struct read_write_emulator_ops {
4300 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4302 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4303 void *val, int bytes);
4304 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4305 int bytes, void *val);
4306 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4307 void *val, int bytes);
4311 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4313 if (vcpu->mmio_read_completed) {
4314 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4315 vcpu->mmio_fragments[0].gpa, *(u64 *)val);
4316 vcpu->mmio_read_completed = 0;
4323 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4324 void *val, int bytes)
4326 return !kvm_read_guest(vcpu->kvm, gpa, val, bytes);
4329 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4330 void *val, int bytes)
4332 return emulator_write_phys(vcpu, gpa, val, bytes);
4335 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4337 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
4338 return vcpu_mmio_write(vcpu, gpa, bytes, val);
4341 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4342 void *val, int bytes)
4344 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
4345 return X86EMUL_IO_NEEDED;
4348 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4349 void *val, int bytes)
4351 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
4353 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
4354 return X86EMUL_CONTINUE;
4357 static const struct read_write_emulator_ops read_emultor = {
4358 .read_write_prepare = read_prepare,
4359 .read_write_emulate = read_emulate,
4360 .read_write_mmio = vcpu_mmio_read,
4361 .read_write_exit_mmio = read_exit_mmio,
4364 static const struct read_write_emulator_ops write_emultor = {
4365 .read_write_emulate = write_emulate,
4366 .read_write_mmio = write_mmio,
4367 .read_write_exit_mmio = write_exit_mmio,
4371 static int emulator_read_write_onepage(unsigned long addr, void *val,
4373 struct x86_exception *exception,
4374 struct kvm_vcpu *vcpu,
4375 const struct read_write_emulator_ops *ops)
4379 bool write = ops->write;
4380 struct kvm_mmio_fragment *frag;
4382 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4385 return X86EMUL_PROPAGATE_FAULT;
4387 /* For APIC access vmexit */
4391 if (ops->read_write_emulate(vcpu, gpa, val, bytes))
4392 return X86EMUL_CONTINUE;
4396 * Is this MMIO handled locally?
4398 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4399 if (handled == bytes)
4400 return X86EMUL_CONTINUE;
4406 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
4407 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
4411 return X86EMUL_CONTINUE;
4414 int emulator_read_write(struct x86_emulate_ctxt *ctxt, unsigned long addr,
4415 void *val, unsigned int bytes,
4416 struct x86_exception *exception,
4417 const struct read_write_emulator_ops *ops)
4419 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4423 if (ops->read_write_prepare &&
4424 ops->read_write_prepare(vcpu, val, bytes))
4425 return X86EMUL_CONTINUE;
4427 vcpu->mmio_nr_fragments = 0;
4429 /* Crossing a page boundary? */
4430 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4433 now = -addr & ~PAGE_MASK;
4434 rc = emulator_read_write_onepage(addr, val, now, exception,
4437 if (rc != X86EMUL_CONTINUE)
4444 rc = emulator_read_write_onepage(addr, val, bytes, exception,
4446 if (rc != X86EMUL_CONTINUE)
4449 if (!vcpu->mmio_nr_fragments)
4452 gpa = vcpu->mmio_fragments[0].gpa;
4454 vcpu->mmio_needed = 1;
4455 vcpu->mmio_cur_fragment = 0;
4457 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
4458 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
4459 vcpu->run->exit_reason = KVM_EXIT_MMIO;
4460 vcpu->run->mmio.phys_addr = gpa;
4462 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4465 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4469 struct x86_exception *exception)
4471 return emulator_read_write(ctxt, addr, val, bytes,
4472 exception, &read_emultor);
4475 int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4479 struct x86_exception *exception)
4481 return emulator_read_write(ctxt, addr, (void *)val, bytes,
4482 exception, &write_emultor);
4485 #define CMPXCHG_TYPE(t, ptr, old, new) \
4486 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4488 #ifdef CONFIG_X86_64
4489 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4491 # define CMPXCHG64(ptr, old, new) \
4492 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4495 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4500 struct x86_exception *exception)
4502 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4508 /* guests cmpxchg8b have to be emulated atomically */
4509 if (bytes > 8 || (bytes & (bytes - 1)))
4512 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4514 if (gpa == UNMAPPED_GVA ||
4515 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4518 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4521 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
4522 if (is_error_page(page))
4525 kaddr = kmap_atomic(page);
4526 kaddr += offset_in_page(gpa);
4529 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4532 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4535 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
4538 exchanged = CMPXCHG64(kaddr, old, new);
4543 kunmap_atomic(kaddr);
4544 kvm_release_page_dirty(page);
4547 return X86EMUL_CMPXCHG_FAILED;
4549 mark_page_dirty(vcpu->kvm, gpa >> PAGE_SHIFT);
4550 kvm_mmu_pte_write(vcpu, gpa, new, bytes);
4552 return X86EMUL_CONTINUE;
4555 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
4557 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
4560 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
4562 /* TODO: String I/O for in kernel device */
4565 if (vcpu->arch.pio.in)
4566 r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
4567 vcpu->arch.pio.size, pd);
4569 r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
4570 vcpu->arch.pio.port, vcpu->arch.pio.size,
4575 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
4576 unsigned short port, void *val,
4577 unsigned int count, bool in)
4579 vcpu->arch.pio.port = port;
4580 vcpu->arch.pio.in = in;
4581 vcpu->arch.pio.count = count;
4582 vcpu->arch.pio.size = size;
4584 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4585 vcpu->arch.pio.count = 0;
4589 vcpu->run->exit_reason = KVM_EXIT_IO;
4590 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
4591 vcpu->run->io.size = size;
4592 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4593 vcpu->run->io.count = count;
4594 vcpu->run->io.port = port;
4599 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
4600 int size, unsigned short port, void *val,
4603 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4606 if (vcpu->arch.pio.count)
4609 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
4612 memcpy(val, vcpu->arch.pio_data, size * count);
4613 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
4614 vcpu->arch.pio.count = 0;
4621 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
4622 int size, unsigned short port,
4623 const void *val, unsigned int count)
4625 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4627 memcpy(vcpu->arch.pio_data, val, size * count);
4628 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
4629 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
4632 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
4634 return kvm_x86_ops->get_segment_base(vcpu, seg);
4637 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
4639 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
4642 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
4644 if (!need_emulate_wbinvd(vcpu))
4645 return X86EMUL_CONTINUE;
4647 if (kvm_x86_ops->has_wbinvd_exit()) {
4648 int cpu = get_cpu();
4650 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4651 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
4652 wbinvd_ipi, NULL, 1);
4654 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
4657 return X86EMUL_CONTINUE;
4659 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
4661 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
4663 kvm_emulate_wbinvd(emul_to_vcpu(ctxt));
4666 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
4668 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
4671 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
4674 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
4677 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
4679 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
4682 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
4684 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4685 unsigned long value;
4689 value = kvm_read_cr0(vcpu);
4692 value = vcpu->arch.cr2;
4695 value = kvm_read_cr3(vcpu);
4698 value = kvm_read_cr4(vcpu);
4701 value = kvm_get_cr8(vcpu);
4704 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4711 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
4713 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4718 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4721 vcpu->arch.cr2 = val;
4724 res = kvm_set_cr3(vcpu, val);
4727 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4730 res = kvm_set_cr8(vcpu, val);
4733 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4740 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
4742 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
4745 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4747 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
4750 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4752 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
4755 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4757 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4760 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4762 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4765 static unsigned long emulator_get_cached_segment_base(
4766 struct x86_emulate_ctxt *ctxt, int seg)
4768 return get_segment_base(emul_to_vcpu(ctxt), seg);
4771 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4772 struct desc_struct *desc, u32 *base3,
4775 struct kvm_segment var;
4777 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
4778 *selector = var.selector;
4781 memset(desc, 0, sizeof(*desc));
4787 set_desc_limit(desc, var.limit);
4788 set_desc_base(desc, (unsigned long)var.base);
4789 #ifdef CONFIG_X86_64
4791 *base3 = var.base >> 32;
4793 desc->type = var.type;
4795 desc->dpl = var.dpl;
4796 desc->p = var.present;
4797 desc->avl = var.avl;
4805 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
4806 struct desc_struct *desc, u32 base3,
4809 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4810 struct kvm_segment var;
4812 var.selector = selector;
4813 var.base = get_desc_base(desc);
4814 #ifdef CONFIG_X86_64
4815 var.base |= ((u64)base3) << 32;
4817 var.limit = get_desc_limit(desc);
4819 var.limit = (var.limit << 12) | 0xfff;
4820 var.type = desc->type;
4821 var.dpl = desc->dpl;
4826 var.avl = desc->avl;
4827 var.present = desc->p;
4828 var.unusable = !var.present;
4831 kvm_set_segment(vcpu, &var, seg);
4835 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
4836 u32 msr_index, u64 *pdata)
4838 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
4841 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
4842 u32 msr_index, u64 data)
4844 struct msr_data msr;
4847 msr.index = msr_index;
4848 msr.host_initiated = false;
4849 return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
4852 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
4855 return kvm_pmu_check_pmc(emul_to_vcpu(ctxt), pmc);
4858 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
4859 u32 pmc, u64 *pdata)
4861 return kvm_pmu_read_pmc(emul_to_vcpu(ctxt), pmc, pdata);
4864 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
4866 emul_to_vcpu(ctxt)->arch.halt_request = 1;
4869 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
4872 kvm_load_guest_fpu(emul_to_vcpu(ctxt));
4874 * CR0.TS may reference the host fpu state, not the guest fpu state,
4875 * so it may be clear at this point.
4880 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
4885 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
4886 struct x86_instruction_info *info,
4887 enum x86_intercept_stage stage)
4889 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
4892 static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
4893 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
4895 kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
4898 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
4900 return kvm_register_read(emul_to_vcpu(ctxt), reg);
4903 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
4905 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
4908 static const struct x86_emulate_ops emulate_ops = {
4909 .read_gpr = emulator_read_gpr,
4910 .write_gpr = emulator_write_gpr,
4911 .read_std = kvm_read_guest_virt_system,
4912 .write_std = kvm_write_guest_virt_system,
4913 .fetch = kvm_fetch_guest_virt,
4914 .read_emulated = emulator_read_emulated,
4915 .write_emulated = emulator_write_emulated,
4916 .cmpxchg_emulated = emulator_cmpxchg_emulated,
4917 .invlpg = emulator_invlpg,
4918 .pio_in_emulated = emulator_pio_in_emulated,
4919 .pio_out_emulated = emulator_pio_out_emulated,
4920 .get_segment = emulator_get_segment,
4921 .set_segment = emulator_set_segment,
4922 .get_cached_segment_base = emulator_get_cached_segment_base,
4923 .get_gdt = emulator_get_gdt,
4924 .get_idt = emulator_get_idt,
4925 .set_gdt = emulator_set_gdt,
4926 .set_idt = emulator_set_idt,
4927 .get_cr = emulator_get_cr,
4928 .set_cr = emulator_set_cr,
4929 .cpl = emulator_get_cpl,
4930 .get_dr = emulator_get_dr,
4931 .set_dr = emulator_set_dr,
4932 .set_msr = emulator_set_msr,
4933 .get_msr = emulator_get_msr,
4934 .check_pmc = emulator_check_pmc,
4935 .read_pmc = emulator_read_pmc,
4936 .halt = emulator_halt,
4937 .wbinvd = emulator_wbinvd,
4938 .fix_hypercall = emulator_fix_hypercall,
4939 .get_fpu = emulator_get_fpu,
4940 .put_fpu = emulator_put_fpu,
4941 .intercept = emulator_intercept,
4942 .get_cpuid = emulator_get_cpuid,
4945 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
4947 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
4949 * an sti; sti; sequence only disable interrupts for the first
4950 * instruction. So, if the last instruction, be it emulated or
4951 * not, left the system with the INT_STI flag enabled, it
4952 * means that the last instruction is an sti. We should not
4953 * leave the flag on in this case. The same goes for mov ss
4955 if (int_shadow & mask)
4957 if (unlikely(int_shadow || mask)) {
4958 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
4960 kvm_make_request(KVM_REQ_EVENT, vcpu);
4964 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
4966 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4967 if (ctxt->exception.vector == PF_VECTOR)
4968 return kvm_propagate_fault(vcpu, &ctxt->exception);
4970 if (ctxt->exception.error_code_valid)
4971 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
4972 ctxt->exception.error_code);
4974 kvm_queue_exception(vcpu, ctxt->exception.vector);
4978 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
4980 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4983 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4985 ctxt->eflags = kvm_get_rflags(vcpu);
4986 ctxt->eip = kvm_rip_read(vcpu);
4987 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
4988 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
4989 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
4990 cs_db ? X86EMUL_MODE_PROT32 :
4991 X86EMUL_MODE_PROT16;
4992 ctxt->guest_mode = is_guest_mode(vcpu);
4994 init_decode_cache(ctxt);
4995 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
4998 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
5000 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5003 init_emulate_ctxt(vcpu);
5007 ctxt->_eip = ctxt->eip + inc_eip;
5008 ret = emulate_int_real(ctxt, irq);
5010 if (ret != X86EMUL_CONTINUE)
5011 return EMULATE_FAIL;
5013 ctxt->eip = ctxt->_eip;
5014 kvm_rip_write(vcpu, ctxt->eip);
5015 kvm_set_rflags(vcpu, ctxt->eflags);
5017 if (irq == NMI_VECTOR)
5018 vcpu->arch.nmi_pending = 0;
5020 vcpu->arch.interrupt.pending = false;
5022 return EMULATE_DONE;
5024 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
5026 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
5028 int r = EMULATE_DONE;
5030 ++vcpu->stat.insn_emulation_fail;
5031 trace_kvm_emulate_insn_failed(vcpu);
5032 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
5033 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5034 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5035 vcpu->run->internal.ndata = 0;
5038 kvm_queue_exception(vcpu, UD_VECTOR);
5043 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5044 bool write_fault_to_shadow_pgtable,
5050 if (emulation_type & EMULTYPE_NO_REEXECUTE)
5053 if (!vcpu->arch.mmu.direct_map) {
5055 * Write permission should be allowed since only
5056 * write access need to be emulated.
5058 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5061 * If the mapping is invalid in guest, let cpu retry
5062 * it to generate fault.
5064 if (gpa == UNMAPPED_GVA)
5069 * Do not retry the unhandleable instruction if it faults on the
5070 * readonly host memory, otherwise it will goto a infinite loop:
5071 * retry instruction -> write #PF -> emulation fail -> retry
5072 * instruction -> ...
5074 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
5077 * If the instruction failed on the error pfn, it can not be fixed,
5078 * report the error to userspace.
5080 if (is_error_noslot_pfn(pfn))
5083 kvm_release_pfn_clean(pfn);
5085 /* The instructions are well-emulated on direct mmu. */
5086 if (vcpu->arch.mmu.direct_map) {
5087 unsigned int indirect_shadow_pages;
5089 spin_lock(&vcpu->kvm->mmu_lock);
5090 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
5091 spin_unlock(&vcpu->kvm->mmu_lock);
5093 if (indirect_shadow_pages)
5094 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5100 * if emulation was due to access to shadowed page table
5101 * and it failed try to unshadow page and re-enter the
5102 * guest to let CPU execute the instruction.
5104 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5107 * If the access faults on its page table, it can not
5108 * be fixed by unprotecting shadow page and it should
5109 * be reported to userspace.
5111 return !write_fault_to_shadow_pgtable;
5114 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5115 unsigned long cr2, int emulation_type)
5117 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5118 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
5120 last_retry_eip = vcpu->arch.last_retry_eip;
5121 last_retry_addr = vcpu->arch.last_retry_addr;
5124 * If the emulation is caused by #PF and it is non-page_table
5125 * writing instruction, it means the VM-EXIT is caused by shadow
5126 * page protected, we can zap the shadow page and retry this
5127 * instruction directly.
5129 * Note: if the guest uses a non-page-table modifying instruction
5130 * on the PDE that points to the instruction, then we will unmap
5131 * the instruction and go to an infinite loop. So, we cache the
5132 * last retried eip and the last fault address, if we meet the eip
5133 * and the address again, we can break out of the potential infinite
5136 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
5138 if (!(emulation_type & EMULTYPE_RETRY))
5141 if (x86_page_table_writing_insn(ctxt))
5144 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
5147 vcpu->arch.last_retry_eip = ctxt->eip;
5148 vcpu->arch.last_retry_addr = cr2;
5150 if (!vcpu->arch.mmu.direct_map)
5151 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5153 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5158 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
5159 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
5161 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
5170 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
5171 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
5176 static void kvm_vcpu_check_singlestep(struct kvm_vcpu *vcpu, unsigned long rflags, int *r)
5178 struct kvm_run *kvm_run = vcpu->run;
5181 * rflags is the old, "raw" value of the flags. The new value has
5182 * not been saved yet.
5184 * This is correct even for TF set by the guest, because "the
5185 * processor will not generate this exception after the instruction
5186 * that sets the TF flag".
5188 if (unlikely(rflags & X86_EFLAGS_TF)) {
5189 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5190 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 |
5192 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
5193 kvm_run->debug.arch.exception = DB_VECTOR;
5194 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5195 *r = EMULATE_USER_EXIT;
5197 vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF;
5199 * "Certain debug exceptions may clear bit 0-3. The
5200 * remaining contents of the DR6 register are never
5201 * cleared by the processor".
5203 vcpu->arch.dr6 &= ~15;
5204 vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
5205 kvm_queue_exception(vcpu, DB_VECTOR);
5210 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
5212 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
5213 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
5214 struct kvm_run *kvm_run = vcpu->run;
5215 unsigned long eip = kvm_get_linear_rip(vcpu);
5216 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5217 vcpu->arch.guest_debug_dr7,
5221 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
5222 kvm_run->debug.arch.pc = eip;
5223 kvm_run->debug.arch.exception = DB_VECTOR;
5224 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5225 *r = EMULATE_USER_EXIT;
5230 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
5231 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
5232 unsigned long eip = kvm_get_linear_rip(vcpu);
5233 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5238 vcpu->arch.dr6 &= ~15;
5239 vcpu->arch.dr6 |= dr6 | DR6_RTM;
5240 kvm_queue_exception(vcpu, DB_VECTOR);
5249 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
5256 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5257 bool writeback = true;
5258 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
5261 * Clear write_fault_to_shadow_pgtable here to ensure it is
5264 vcpu->arch.write_fault_to_shadow_pgtable = false;
5265 kvm_clear_exception_queue(vcpu);
5267 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
5268 init_emulate_ctxt(vcpu);
5271 * We will reenter on the same instruction since
5272 * we do not set complete_userspace_io. This does not
5273 * handle watchpoints yet, those would be handled in
5276 if (kvm_vcpu_check_breakpoint(vcpu, &r))
5279 ctxt->interruptibility = 0;
5280 ctxt->have_exception = false;
5281 ctxt->exception.vector = -1;
5282 ctxt->perm_ok = false;
5284 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
5286 r = x86_decode_insn(ctxt, insn, insn_len);
5288 trace_kvm_emulate_insn_start(vcpu);
5289 ++vcpu->stat.insn_emulation;
5290 if (r != EMULATION_OK) {
5291 if (emulation_type & EMULTYPE_TRAP_UD)
5292 return EMULATE_FAIL;
5293 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5295 return EMULATE_DONE;
5296 if (emulation_type & EMULTYPE_SKIP)
5297 return EMULATE_FAIL;
5298 return handle_emulation_failure(vcpu);
5302 if (emulation_type & EMULTYPE_SKIP) {
5303 kvm_rip_write(vcpu, ctxt->_eip);
5304 if (ctxt->eflags & X86_EFLAGS_RF)
5305 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
5306 return EMULATE_DONE;
5309 if (retry_instruction(ctxt, cr2, emulation_type))
5310 return EMULATE_DONE;
5312 /* this is needed for vmware backdoor interface to work since it
5313 changes registers values during IO operation */
5314 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
5315 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5316 emulator_invalidate_register_cache(ctxt);
5320 r = x86_emulate_insn(ctxt);
5322 if (r == EMULATION_INTERCEPTED)
5323 return EMULATE_DONE;
5325 if (r == EMULATION_FAILED) {
5326 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5328 return EMULATE_DONE;
5330 return handle_emulation_failure(vcpu);
5333 if (ctxt->have_exception) {
5335 if (inject_emulated_exception(vcpu))
5337 } else if (vcpu->arch.pio.count) {
5338 if (!vcpu->arch.pio.in) {
5339 /* FIXME: return into emulator if single-stepping. */
5340 vcpu->arch.pio.count = 0;
5343 vcpu->arch.complete_userspace_io = complete_emulated_pio;
5345 r = EMULATE_USER_EXIT;
5346 } else if (vcpu->mmio_needed) {
5347 if (!vcpu->mmio_is_write)
5349 r = EMULATE_USER_EXIT;
5350 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
5351 } else if (r == EMULATION_RESTART)
5357 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5358 toggle_interruptibility(vcpu, ctxt->interruptibility);
5359 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5360 kvm_rip_write(vcpu, ctxt->eip);
5361 if (r == EMULATE_DONE)
5362 kvm_vcpu_check_singlestep(vcpu, rflags, &r);
5363 __kvm_set_rflags(vcpu, ctxt->eflags);
5366 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
5367 * do nothing, and it will be requested again as soon as
5368 * the shadow expires. But we still need to check here,
5369 * because POPF has no interrupt shadow.
5371 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
5372 kvm_make_request(KVM_REQ_EVENT, vcpu);
5374 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5378 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5380 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5382 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5383 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5384 size, port, &val, 1);
5385 /* do not return to emulator after return from userspace */
5386 vcpu->arch.pio.count = 0;
5389 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5391 static void tsc_bad(void *info)
5393 __this_cpu_write(cpu_tsc_khz, 0);
5396 static void tsc_khz_changed(void *data)
5398 struct cpufreq_freqs *freq = data;
5399 unsigned long khz = 0;
5403 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5404 khz = cpufreq_quick_get(raw_smp_processor_id());
5407 __this_cpu_write(cpu_tsc_khz, khz);
5410 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5413 struct cpufreq_freqs *freq = data;
5415 struct kvm_vcpu *vcpu;
5416 int i, send_ipi = 0;
5419 * We allow guests to temporarily run on slowing clocks,
5420 * provided we notify them after, or to run on accelerating
5421 * clocks, provided we notify them before. Thus time never
5424 * However, we have a problem. We can't atomically update
5425 * the frequency of a given CPU from this function; it is
5426 * merely a notifier, which can be called from any CPU.
5427 * Changing the TSC frequency at arbitrary points in time
5428 * requires a recomputation of local variables related to
5429 * the TSC for each VCPU. We must flag these local variables
5430 * to be updated and be sure the update takes place with the
5431 * new frequency before any guests proceed.
5433 * Unfortunately, the combination of hotplug CPU and frequency
5434 * change creates an intractable locking scenario; the order
5435 * of when these callouts happen is undefined with respect to
5436 * CPU hotplug, and they can race with each other. As such,
5437 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5438 * undefined; you can actually have a CPU frequency change take
5439 * place in between the computation of X and the setting of the
5440 * variable. To protect against this problem, all updates of
5441 * the per_cpu tsc_khz variable are done in an interrupt
5442 * protected IPI, and all callers wishing to update the value
5443 * must wait for a synchronous IPI to complete (which is trivial
5444 * if the caller is on the CPU already). This establishes the
5445 * necessary total order on variable updates.
5447 * Note that because a guest time update may take place
5448 * anytime after the setting of the VCPU's request bit, the
5449 * correct TSC value must be set before the request. However,
5450 * to ensure the update actually makes it to any guest which
5451 * starts running in hardware virtualization between the set
5452 * and the acquisition of the spinlock, we must also ping the
5453 * CPU after setting the request bit.
5457 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
5459 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
5462 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5464 spin_lock(&kvm_lock);
5465 list_for_each_entry(kvm, &vm_list, vm_list) {
5466 kvm_for_each_vcpu(i, vcpu, kvm) {
5467 if (vcpu->cpu != freq->cpu)
5469 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5470 if (vcpu->cpu != smp_processor_id())
5474 spin_unlock(&kvm_lock);
5476 if (freq->old < freq->new && send_ipi) {
5478 * We upscale the frequency. Must make the guest
5479 * doesn't see old kvmclock values while running with
5480 * the new frequency, otherwise we risk the guest sees
5481 * time go backwards.
5483 * In case we update the frequency for another cpu
5484 * (which might be in guest context) send an interrupt
5485 * to kick the cpu out of guest context. Next time
5486 * guest context is entered kvmclock will be updated,
5487 * so the guest will not see stale values.
5489 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5494 static struct notifier_block kvmclock_cpufreq_notifier_block = {
5495 .notifier_call = kvmclock_cpufreq_notifier
5498 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
5499 unsigned long action, void *hcpu)
5501 unsigned int cpu = (unsigned long)hcpu;
5505 case CPU_DOWN_FAILED:
5506 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5508 case CPU_DOWN_PREPARE:
5509 smp_call_function_single(cpu, tsc_bad, NULL, 1);
5515 static struct notifier_block kvmclock_cpu_notifier_block = {
5516 .notifier_call = kvmclock_cpu_notifier,
5517 .priority = -INT_MAX
5520 static void kvm_timer_init(void)
5524 max_tsc_khz = tsc_khz;
5526 cpu_notifier_register_begin();
5527 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5528 #ifdef CONFIG_CPU_FREQ
5529 struct cpufreq_policy policy;
5530 memset(&policy, 0, sizeof(policy));
5532 cpufreq_get_policy(&policy, cpu);
5533 if (policy.cpuinfo.max_freq)
5534 max_tsc_khz = policy.cpuinfo.max_freq;
5537 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
5538 CPUFREQ_TRANSITION_NOTIFIER);
5540 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
5541 for_each_online_cpu(cpu)
5542 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5544 __register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5545 cpu_notifier_register_done();
5549 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
5551 int kvm_is_in_guest(void)
5553 return __this_cpu_read(current_vcpu) != NULL;
5556 static int kvm_is_user_mode(void)
5560 if (__this_cpu_read(current_vcpu))
5561 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
5563 return user_mode != 0;
5566 static unsigned long kvm_get_guest_ip(void)
5568 unsigned long ip = 0;
5570 if (__this_cpu_read(current_vcpu))
5571 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
5576 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5577 .is_in_guest = kvm_is_in_guest,
5578 .is_user_mode = kvm_is_user_mode,
5579 .get_guest_ip = kvm_get_guest_ip,
5582 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
5584 __this_cpu_write(current_vcpu, vcpu);
5586 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
5588 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
5590 __this_cpu_write(current_vcpu, NULL);
5592 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
5594 static void kvm_set_mmio_spte_mask(void)
5597 int maxphyaddr = boot_cpu_data.x86_phys_bits;
5600 * Set the reserved bits and the present bit of an paging-structure
5601 * entry to generate page fault with PFER.RSV = 1.
5603 /* Mask the reserved physical address bits. */
5604 mask = rsvd_bits(maxphyaddr, 51);
5606 /* Bit 62 is always reserved for 32bit host. */
5607 mask |= 0x3ull << 62;
5609 /* Set the present bit. */
5612 #ifdef CONFIG_X86_64
5614 * If reserved bit is not supported, clear the present bit to disable
5617 if (maxphyaddr == 52)
5621 kvm_mmu_set_mmio_spte_mask(mask);
5624 #ifdef CONFIG_X86_64
5625 static void pvclock_gtod_update_fn(struct work_struct *work)
5629 struct kvm_vcpu *vcpu;
5632 spin_lock(&kvm_lock);
5633 list_for_each_entry(kvm, &vm_list, vm_list)
5634 kvm_for_each_vcpu(i, vcpu, kvm)
5635 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
5636 atomic_set(&kvm_guest_has_master_clock, 0);
5637 spin_unlock(&kvm_lock);
5640 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
5643 * Notification about pvclock gtod data update.
5645 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
5648 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
5649 struct timekeeper *tk = priv;
5651 update_pvclock_gtod(tk);
5653 /* disable master clock if host does not trust, or does not
5654 * use, TSC clocksource
5656 if (gtod->clock.vclock_mode != VCLOCK_TSC &&
5657 atomic_read(&kvm_guest_has_master_clock) != 0)
5658 queue_work(system_long_wq, &pvclock_gtod_work);
5663 static struct notifier_block pvclock_gtod_notifier = {
5664 .notifier_call = pvclock_gtod_notify,
5668 int kvm_arch_init(void *opaque)
5671 struct kvm_x86_ops *ops = opaque;
5674 printk(KERN_ERR "kvm: already loaded the other module\n");
5679 if (!ops->cpu_has_kvm_support()) {
5680 printk(KERN_ERR "kvm: no hardware support\n");
5684 if (ops->disabled_by_bios()) {
5685 printk(KERN_ERR "kvm: disabled by bios\n");
5691 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
5693 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
5697 r = kvm_mmu_module_init();
5699 goto out_free_percpu;
5701 kvm_set_mmio_spte_mask();
5704 kvm_init_msr_list();
5706 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
5707 PT_DIRTY_MASK, PT64_NX_MASK, 0);
5711 perf_register_guest_info_callbacks(&kvm_guest_cbs);
5714 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
5717 #ifdef CONFIG_X86_64
5718 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
5724 free_percpu(shared_msrs);
5729 void kvm_arch_exit(void)
5731 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
5733 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5734 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
5735 CPUFREQ_TRANSITION_NOTIFIER);
5736 unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5737 #ifdef CONFIG_X86_64
5738 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
5741 kvm_mmu_module_exit();
5742 free_percpu(shared_msrs);
5745 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
5747 ++vcpu->stat.halt_exits;
5748 if (irqchip_in_kernel(vcpu->kvm)) {
5749 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
5752 vcpu->run->exit_reason = KVM_EXIT_HLT;
5756 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
5758 int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
5760 u64 param, ingpa, outgpa, ret;
5761 uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
5762 bool fast, longmode;
5765 * hypercall generates UD from non zero cpl and real mode
5768 if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
5769 kvm_queue_exception(vcpu, UD_VECTOR);
5773 longmode = is_64_bit_mode(vcpu);
5776 param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
5777 (kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
5778 ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
5779 (kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
5780 outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
5781 (kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
5783 #ifdef CONFIG_X86_64
5785 param = kvm_register_read(vcpu, VCPU_REGS_RCX);
5786 ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
5787 outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
5791 code = param & 0xffff;
5792 fast = (param >> 16) & 0x1;
5793 rep_cnt = (param >> 32) & 0xfff;
5794 rep_idx = (param >> 48) & 0xfff;
5796 trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
5799 case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
5800 kvm_vcpu_on_spin(vcpu);
5803 res = HV_STATUS_INVALID_HYPERCALL_CODE;
5807 ret = res | (((u64)rep_done & 0xfff) << 32);
5809 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
5811 kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
5812 kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
5819 * kvm_pv_kick_cpu_op: Kick a vcpu.
5821 * @apicid - apicid of vcpu to be kicked.
5823 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
5825 struct kvm_lapic_irq lapic_irq;
5827 lapic_irq.shorthand = 0;
5828 lapic_irq.dest_mode = 0;
5829 lapic_irq.dest_id = apicid;
5831 lapic_irq.delivery_mode = APIC_DM_REMRD;
5832 kvm_irq_delivery_to_apic(kvm, 0, &lapic_irq, NULL);
5835 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
5837 unsigned long nr, a0, a1, a2, a3, ret;
5838 int op_64_bit, r = 1;
5840 if (kvm_hv_hypercall_enabled(vcpu->kvm))
5841 return kvm_hv_hypercall(vcpu);
5843 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
5844 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
5845 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
5846 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
5847 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
5849 trace_kvm_hypercall(nr, a0, a1, a2, a3);
5851 op_64_bit = is_64_bit_mode(vcpu);
5860 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
5866 case KVM_HC_VAPIC_POLL_IRQ:
5869 case KVM_HC_KICK_CPU:
5870 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
5880 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
5881 ++vcpu->stat.hypercalls;
5884 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
5886 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
5888 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5889 char instruction[3];
5890 unsigned long rip = kvm_rip_read(vcpu);
5892 kvm_x86_ops->patch_hypercall(vcpu, instruction);
5894 return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
5898 * Check if userspace requested an interrupt window, and that the
5899 * interrupt window is open.
5901 * No need to exit to userspace if we already have an interrupt queued.
5903 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
5905 return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
5906 vcpu->run->request_interrupt_window &&
5907 kvm_arch_interrupt_allowed(vcpu));
5910 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
5912 struct kvm_run *kvm_run = vcpu->run;
5914 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
5915 kvm_run->cr8 = kvm_get_cr8(vcpu);
5916 kvm_run->apic_base = kvm_get_apic_base(vcpu);
5917 if (irqchip_in_kernel(vcpu->kvm))
5918 kvm_run->ready_for_interrupt_injection = 1;
5920 kvm_run->ready_for_interrupt_injection =
5921 kvm_arch_interrupt_allowed(vcpu) &&
5922 !kvm_cpu_has_interrupt(vcpu) &&
5923 !kvm_event_needs_reinjection(vcpu);
5926 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
5930 if (!kvm_x86_ops->update_cr8_intercept)
5933 if (!vcpu->arch.apic)
5936 if (!vcpu->arch.apic->vapic_addr)
5937 max_irr = kvm_lapic_find_highest_irr(vcpu);
5944 tpr = kvm_lapic_get_cr8(vcpu);
5946 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
5949 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
5953 /* try to reinject previous events if any */
5954 if (vcpu->arch.exception.pending) {
5955 trace_kvm_inj_exception(vcpu->arch.exception.nr,
5956 vcpu->arch.exception.has_error_code,
5957 vcpu->arch.exception.error_code);
5959 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
5960 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
5963 if (vcpu->arch.exception.nr == DB_VECTOR &&
5964 (vcpu->arch.dr7 & DR7_GD)) {
5965 vcpu->arch.dr7 &= ~DR7_GD;
5966 kvm_update_dr7(vcpu);
5969 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
5970 vcpu->arch.exception.has_error_code,
5971 vcpu->arch.exception.error_code,
5972 vcpu->arch.exception.reinject);
5976 if (vcpu->arch.nmi_injected) {
5977 kvm_x86_ops->set_nmi(vcpu);
5981 if (vcpu->arch.interrupt.pending) {
5982 kvm_x86_ops->set_irq(vcpu);
5986 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
5987 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
5992 /* try to inject new event if pending */
5993 if (vcpu->arch.nmi_pending) {
5994 if (kvm_x86_ops->nmi_allowed(vcpu)) {
5995 --vcpu->arch.nmi_pending;
5996 vcpu->arch.nmi_injected = true;
5997 kvm_x86_ops->set_nmi(vcpu);
5999 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
6001 * Because interrupts can be injected asynchronously, we are
6002 * calling check_nested_events again here to avoid a race condition.
6003 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
6004 * proposal and current concerns. Perhaps we should be setting
6005 * KVM_REQ_EVENT only on certain events and not unconditionally?
6007 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6008 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6012 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
6013 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
6015 kvm_x86_ops->set_irq(vcpu);
6021 static void process_nmi(struct kvm_vcpu *vcpu)
6026 * x86 is limited to one NMI running, and one NMI pending after it.
6027 * If an NMI is already in progress, limit further NMIs to just one.
6028 * Otherwise, allow two (and we'll inject the first one immediately).
6030 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
6033 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
6034 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
6035 kvm_make_request(KVM_REQ_EVENT, vcpu);
6038 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
6040 u64 eoi_exit_bitmap[4];
6043 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
6046 memset(eoi_exit_bitmap, 0, 32);
6049 kvm_ioapic_scan_entry(vcpu, eoi_exit_bitmap, tmr);
6050 kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
6051 kvm_apic_update_tmr(vcpu, tmr);
6054 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu)
6056 ++vcpu->stat.tlb_flush;
6057 kvm_x86_ops->tlb_flush(vcpu);
6060 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
6062 struct page *page = NULL;
6064 if (!irqchip_in_kernel(vcpu->kvm))
6067 if (!kvm_x86_ops->set_apic_access_page_addr)
6070 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6071 kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
6074 * Do not pin apic access page in memory, the MMU notifier
6075 * will call us again if it is migrated or swapped out.
6079 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
6081 void kvm_arch_mmu_notifier_invalidate_page(struct kvm *kvm,
6082 unsigned long address)
6085 * The physical address of apic access page is stored in the VMCS.
6086 * Update it when it becomes invalid.
6088 if (address == gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT))
6089 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
6093 * Returns 1 to let __vcpu_run() continue the guest execution loop without
6094 * exiting to the userspace. Otherwise, the value will be returned to the
6097 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
6100 bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
6101 vcpu->run->request_interrupt_window;
6102 bool req_immediate_exit = false;
6104 if (vcpu->requests) {
6105 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
6106 kvm_mmu_unload(vcpu);
6107 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
6108 __kvm_migrate_timers(vcpu);
6109 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
6110 kvm_gen_update_masterclock(vcpu->kvm);
6111 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
6112 kvm_gen_kvmclock_update(vcpu);
6113 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
6114 r = kvm_guest_time_update(vcpu);
6118 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
6119 kvm_mmu_sync_roots(vcpu);
6120 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
6121 kvm_vcpu_flush_tlb(vcpu);
6122 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
6123 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
6127 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
6128 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6132 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
6133 vcpu->fpu_active = 0;
6134 kvm_x86_ops->fpu_deactivate(vcpu);
6136 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
6137 /* Page is swapped out. Do synthetic halt */
6138 vcpu->arch.apf.halted = true;
6142 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
6143 record_steal_time(vcpu);
6144 if (kvm_check_request(KVM_REQ_NMI, vcpu))
6146 if (kvm_check_request(KVM_REQ_PMU, vcpu))
6147 kvm_handle_pmu_event(vcpu);
6148 if (kvm_check_request(KVM_REQ_PMI, vcpu))
6149 kvm_deliver_pmi(vcpu);
6150 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
6151 vcpu_scan_ioapic(vcpu);
6152 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
6153 kvm_vcpu_reload_apic_access_page(vcpu);
6156 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
6157 kvm_apic_accept_events(vcpu);
6158 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
6163 if (inject_pending_event(vcpu, req_int_win) != 0)
6164 req_immediate_exit = true;
6165 /* enable NMI/IRQ window open exits if needed */
6166 else if (vcpu->arch.nmi_pending)
6167 kvm_x86_ops->enable_nmi_window(vcpu);
6168 else if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
6169 kvm_x86_ops->enable_irq_window(vcpu);
6171 if (kvm_lapic_enabled(vcpu)) {
6173 * Update architecture specific hints for APIC
6174 * virtual interrupt delivery.
6176 if (kvm_x86_ops->hwapic_irr_update)
6177 kvm_x86_ops->hwapic_irr_update(vcpu,
6178 kvm_lapic_find_highest_irr(vcpu));
6179 update_cr8_intercept(vcpu);
6180 kvm_lapic_sync_to_vapic(vcpu);
6184 r = kvm_mmu_reload(vcpu);
6186 goto cancel_injection;
6191 kvm_x86_ops->prepare_guest_switch(vcpu);
6192 if (vcpu->fpu_active)
6193 kvm_load_guest_fpu(vcpu);
6194 kvm_load_guest_xcr0(vcpu);
6196 vcpu->mode = IN_GUEST_MODE;
6198 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6200 /* We should set ->mode before check ->requests,
6201 * see the comment in make_all_cpus_request.
6203 smp_mb__after_srcu_read_unlock();
6205 local_irq_disable();
6207 if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
6208 || need_resched() || signal_pending(current)) {
6209 vcpu->mode = OUTSIDE_GUEST_MODE;
6213 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6215 goto cancel_injection;
6218 if (req_immediate_exit)
6219 smp_send_reschedule(vcpu->cpu);
6223 if (unlikely(vcpu->arch.switch_db_regs)) {
6225 set_debugreg(vcpu->arch.eff_db[0], 0);
6226 set_debugreg(vcpu->arch.eff_db[1], 1);
6227 set_debugreg(vcpu->arch.eff_db[2], 2);
6228 set_debugreg(vcpu->arch.eff_db[3], 3);
6229 set_debugreg(vcpu->arch.dr6, 6);
6232 trace_kvm_entry(vcpu->vcpu_id);
6233 kvm_x86_ops->run(vcpu);
6236 * Do this here before restoring debug registers on the host. And
6237 * since we do this before handling the vmexit, a DR access vmexit
6238 * can (a) read the correct value of the debug registers, (b) set
6239 * KVM_DEBUGREG_WONT_EXIT again.
6241 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
6244 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
6245 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
6246 for (i = 0; i < KVM_NR_DB_REGS; i++)
6247 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
6251 * If the guest has used debug registers, at least dr7
6252 * will be disabled while returning to the host.
6253 * If we don't have active breakpoints in the host, we don't
6254 * care about the messed up debug address registers. But if
6255 * we have some of them active, restore the old state.
6257 if (hw_breakpoint_active())
6258 hw_breakpoint_restore();
6260 vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu,
6263 vcpu->mode = OUTSIDE_GUEST_MODE;
6266 /* Interrupt is enabled by handle_external_intr() */
6267 kvm_x86_ops->handle_external_intr(vcpu);
6272 * We must have an instruction between local_irq_enable() and
6273 * kvm_guest_exit(), so the timer interrupt isn't delayed by
6274 * the interrupt shadow. The stat.exits increment will do nicely.
6275 * But we need to prevent reordering, hence this barrier():
6283 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6286 * Profile KVM exit RIPs:
6288 if (unlikely(prof_on == KVM_PROFILING)) {
6289 unsigned long rip = kvm_rip_read(vcpu);
6290 profile_hit(KVM_PROFILING, (void *)rip);
6293 if (unlikely(vcpu->arch.tsc_always_catchup))
6294 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6296 if (vcpu->arch.apic_attention)
6297 kvm_lapic_sync_from_vapic(vcpu);
6299 r = kvm_x86_ops->handle_exit(vcpu);
6303 kvm_x86_ops->cancel_injection(vcpu);
6304 if (unlikely(vcpu->arch.apic_attention))
6305 kvm_lapic_sync_from_vapic(vcpu);
6311 static int __vcpu_run(struct kvm_vcpu *vcpu)
6314 struct kvm *kvm = vcpu->kvm;
6316 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6320 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6321 !vcpu->arch.apf.halted)
6322 r = vcpu_enter_guest(vcpu);
6324 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6325 kvm_vcpu_block(vcpu);
6326 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6327 if (kvm_check_request(KVM_REQ_UNHALT, vcpu)) {
6328 kvm_apic_accept_events(vcpu);
6329 switch(vcpu->arch.mp_state) {
6330 case KVM_MP_STATE_HALTED:
6331 vcpu->arch.pv.pv_unhalted = false;
6332 vcpu->arch.mp_state =
6333 KVM_MP_STATE_RUNNABLE;
6334 case KVM_MP_STATE_RUNNABLE:
6335 vcpu->arch.apf.halted = false;
6337 case KVM_MP_STATE_INIT_RECEIVED:
6349 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
6350 if (kvm_cpu_has_pending_timer(vcpu))
6351 kvm_inject_pending_timer_irqs(vcpu);
6353 if (dm_request_for_irq_injection(vcpu)) {
6355 vcpu->run->exit_reason = KVM_EXIT_INTR;
6356 ++vcpu->stat.request_irq_exits;
6359 kvm_check_async_pf_completion(vcpu);
6361 if (signal_pending(current)) {
6363 vcpu->run->exit_reason = KVM_EXIT_INTR;
6364 ++vcpu->stat.signal_exits;
6366 if (need_resched()) {
6367 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6369 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6373 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6378 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
6381 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6382 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
6383 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6384 if (r != EMULATE_DONE)
6389 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
6391 BUG_ON(!vcpu->arch.pio.count);
6393 return complete_emulated_io(vcpu);
6397 * Implements the following, as a state machine:
6401 * for each mmio piece in the fragment
6409 * for each mmio piece in the fragment
6414 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
6416 struct kvm_run *run = vcpu->run;
6417 struct kvm_mmio_fragment *frag;
6420 BUG_ON(!vcpu->mmio_needed);
6422 /* Complete previous fragment */
6423 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
6424 len = min(8u, frag->len);
6425 if (!vcpu->mmio_is_write)
6426 memcpy(frag->data, run->mmio.data, len);
6428 if (frag->len <= 8) {
6429 /* Switch to the next fragment. */
6431 vcpu->mmio_cur_fragment++;
6433 /* Go forward to the next mmio piece. */
6439 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
6440 vcpu->mmio_needed = 0;
6442 /* FIXME: return into emulator if single-stepping. */
6443 if (vcpu->mmio_is_write)
6445 vcpu->mmio_read_completed = 1;
6446 return complete_emulated_io(vcpu);
6449 run->exit_reason = KVM_EXIT_MMIO;
6450 run->mmio.phys_addr = frag->gpa;
6451 if (vcpu->mmio_is_write)
6452 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
6453 run->mmio.len = min(8u, frag->len);
6454 run->mmio.is_write = vcpu->mmio_is_write;
6455 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6460 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
6465 if (!tsk_used_math(current) && init_fpu(current))
6468 if (vcpu->sigset_active)
6469 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
6471 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
6472 kvm_vcpu_block(vcpu);
6473 kvm_apic_accept_events(vcpu);
6474 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
6479 /* re-sync apic's tpr */
6480 if (!irqchip_in_kernel(vcpu->kvm)) {
6481 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
6487 if (unlikely(vcpu->arch.complete_userspace_io)) {
6488 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
6489 vcpu->arch.complete_userspace_io = NULL;
6494 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
6496 r = __vcpu_run(vcpu);
6499 post_kvm_run_save(vcpu);
6500 if (vcpu->sigset_active)
6501 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
6506 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6508 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
6510 * We are here if userspace calls get_regs() in the middle of
6511 * instruction emulation. Registers state needs to be copied
6512 * back from emulation context to vcpu. Userspace shouldn't do
6513 * that usually, but some bad designed PV devices (vmware
6514 * backdoor interface) need this to work
6516 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
6517 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6519 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
6520 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
6521 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
6522 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
6523 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
6524 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
6525 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
6526 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
6527 #ifdef CONFIG_X86_64
6528 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
6529 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
6530 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
6531 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
6532 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
6533 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
6534 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
6535 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
6538 regs->rip = kvm_rip_read(vcpu);
6539 regs->rflags = kvm_get_rflags(vcpu);
6544 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6546 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
6547 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6549 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
6550 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
6551 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
6552 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
6553 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
6554 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
6555 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
6556 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
6557 #ifdef CONFIG_X86_64
6558 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
6559 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
6560 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
6561 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
6562 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
6563 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
6564 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
6565 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
6568 kvm_rip_write(vcpu, regs->rip);
6569 kvm_set_rflags(vcpu, regs->rflags);
6571 vcpu->arch.exception.pending = false;
6573 kvm_make_request(KVM_REQ_EVENT, vcpu);
6578 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
6580 struct kvm_segment cs;
6582 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
6586 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
6588 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
6589 struct kvm_sregs *sregs)
6593 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6594 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6595 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6596 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6597 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6598 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6600 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6601 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6603 kvm_x86_ops->get_idt(vcpu, &dt);
6604 sregs->idt.limit = dt.size;
6605 sregs->idt.base = dt.address;
6606 kvm_x86_ops->get_gdt(vcpu, &dt);
6607 sregs->gdt.limit = dt.size;
6608 sregs->gdt.base = dt.address;
6610 sregs->cr0 = kvm_read_cr0(vcpu);
6611 sregs->cr2 = vcpu->arch.cr2;
6612 sregs->cr3 = kvm_read_cr3(vcpu);
6613 sregs->cr4 = kvm_read_cr4(vcpu);
6614 sregs->cr8 = kvm_get_cr8(vcpu);
6615 sregs->efer = vcpu->arch.efer;
6616 sregs->apic_base = kvm_get_apic_base(vcpu);
6618 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
6620 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
6621 set_bit(vcpu->arch.interrupt.nr,
6622 (unsigned long *)sregs->interrupt_bitmap);
6627 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
6628 struct kvm_mp_state *mp_state)
6630 kvm_apic_accept_events(vcpu);
6631 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
6632 vcpu->arch.pv.pv_unhalted)
6633 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
6635 mp_state->mp_state = vcpu->arch.mp_state;
6640 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
6641 struct kvm_mp_state *mp_state)
6643 if (!kvm_vcpu_has_lapic(vcpu) &&
6644 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
6647 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
6648 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
6649 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
6651 vcpu->arch.mp_state = mp_state->mp_state;
6652 kvm_make_request(KVM_REQ_EVENT, vcpu);
6656 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
6657 int reason, bool has_error_code, u32 error_code)
6659 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6662 init_emulate_ctxt(vcpu);
6664 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
6665 has_error_code, error_code);
6668 return EMULATE_FAIL;
6670 kvm_rip_write(vcpu, ctxt->eip);
6671 kvm_set_rflags(vcpu, ctxt->eflags);
6672 kvm_make_request(KVM_REQ_EVENT, vcpu);
6673 return EMULATE_DONE;
6675 EXPORT_SYMBOL_GPL(kvm_task_switch);
6677 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
6678 struct kvm_sregs *sregs)
6680 struct msr_data apic_base_msr;
6681 int mmu_reset_needed = 0;
6682 int pending_vec, max_bits, idx;
6685 if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
6688 dt.size = sregs->idt.limit;
6689 dt.address = sregs->idt.base;
6690 kvm_x86_ops->set_idt(vcpu, &dt);
6691 dt.size = sregs->gdt.limit;
6692 dt.address = sregs->gdt.base;
6693 kvm_x86_ops->set_gdt(vcpu, &dt);
6695 vcpu->arch.cr2 = sregs->cr2;
6696 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
6697 vcpu->arch.cr3 = sregs->cr3;
6698 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
6700 kvm_set_cr8(vcpu, sregs->cr8);
6702 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
6703 kvm_x86_ops->set_efer(vcpu, sregs->efer);
6704 apic_base_msr.data = sregs->apic_base;
6705 apic_base_msr.host_initiated = true;
6706 kvm_set_apic_base(vcpu, &apic_base_msr);
6708 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
6709 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
6710 vcpu->arch.cr0 = sregs->cr0;
6712 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
6713 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
6714 if (sregs->cr4 & X86_CR4_OSXSAVE)
6715 kvm_update_cpuid(vcpu);
6717 idx = srcu_read_lock(&vcpu->kvm->srcu);
6718 if (!is_long_mode(vcpu) && is_pae(vcpu)) {
6719 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
6720 mmu_reset_needed = 1;
6722 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6724 if (mmu_reset_needed)
6725 kvm_mmu_reset_context(vcpu);
6727 max_bits = KVM_NR_INTERRUPTS;
6728 pending_vec = find_first_bit(
6729 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
6730 if (pending_vec < max_bits) {
6731 kvm_queue_interrupt(vcpu, pending_vec, false);
6732 pr_debug("Set back pending irq %d\n", pending_vec);
6735 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6736 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6737 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6738 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6739 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6740 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6742 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6743 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6745 update_cr8_intercept(vcpu);
6747 /* Older userspace won't unhalt the vcpu on reset. */
6748 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
6749 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
6751 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
6753 kvm_make_request(KVM_REQ_EVENT, vcpu);
6758 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
6759 struct kvm_guest_debug *dbg)
6761 unsigned long rflags;
6764 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
6766 if (vcpu->arch.exception.pending)
6768 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
6769 kvm_queue_exception(vcpu, DB_VECTOR);
6771 kvm_queue_exception(vcpu, BP_VECTOR);
6775 * Read rflags as long as potentially injected trace flags are still
6778 rflags = kvm_get_rflags(vcpu);
6780 vcpu->guest_debug = dbg->control;
6781 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
6782 vcpu->guest_debug = 0;
6784 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
6785 for (i = 0; i < KVM_NR_DB_REGS; ++i)
6786 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
6787 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
6789 for (i = 0; i < KVM_NR_DB_REGS; i++)
6790 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
6792 kvm_update_dr7(vcpu);
6794 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6795 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
6796 get_segment_base(vcpu, VCPU_SREG_CS);
6799 * Trigger an rflags update that will inject or remove the trace
6802 kvm_set_rflags(vcpu, rflags);
6804 kvm_x86_ops->update_db_bp_intercept(vcpu);
6814 * Translate a guest virtual address to a guest physical address.
6816 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
6817 struct kvm_translation *tr)
6819 unsigned long vaddr = tr->linear_address;
6823 idx = srcu_read_lock(&vcpu->kvm->srcu);
6824 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
6825 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6826 tr->physical_address = gpa;
6827 tr->valid = gpa != UNMAPPED_GVA;
6834 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
6836 struct i387_fxsave_struct *fxsave =
6837 &vcpu->arch.guest_fpu.state->fxsave;
6839 memcpy(fpu->fpr, fxsave->st_space, 128);
6840 fpu->fcw = fxsave->cwd;
6841 fpu->fsw = fxsave->swd;
6842 fpu->ftwx = fxsave->twd;
6843 fpu->last_opcode = fxsave->fop;
6844 fpu->last_ip = fxsave->rip;
6845 fpu->last_dp = fxsave->rdp;
6846 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
6851 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
6853 struct i387_fxsave_struct *fxsave =
6854 &vcpu->arch.guest_fpu.state->fxsave;
6856 memcpy(fxsave->st_space, fpu->fpr, 128);
6857 fxsave->cwd = fpu->fcw;
6858 fxsave->swd = fpu->fsw;
6859 fxsave->twd = fpu->ftwx;
6860 fxsave->fop = fpu->last_opcode;
6861 fxsave->rip = fpu->last_ip;
6862 fxsave->rdp = fpu->last_dp;
6863 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
6868 int fx_init(struct kvm_vcpu *vcpu)
6872 err = fpu_alloc(&vcpu->arch.guest_fpu);
6876 fpu_finit(&vcpu->arch.guest_fpu);
6879 * Ensure guest xcr0 is valid for loading
6881 vcpu->arch.xcr0 = XSTATE_FP;
6883 vcpu->arch.cr0 |= X86_CR0_ET;
6887 EXPORT_SYMBOL_GPL(fx_init);
6889 static void fx_free(struct kvm_vcpu *vcpu)
6891 fpu_free(&vcpu->arch.guest_fpu);
6894 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
6896 if (vcpu->guest_fpu_loaded)
6900 * Restore all possible states in the guest,
6901 * and assume host would use all available bits.
6902 * Guest xcr0 would be loaded later.
6904 kvm_put_guest_xcr0(vcpu);
6905 vcpu->guest_fpu_loaded = 1;
6906 __kernel_fpu_begin();
6907 fpu_restore_checking(&vcpu->arch.guest_fpu);
6911 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
6913 kvm_put_guest_xcr0(vcpu);
6915 if (!vcpu->guest_fpu_loaded)
6918 vcpu->guest_fpu_loaded = 0;
6919 fpu_save_init(&vcpu->arch.guest_fpu);
6921 ++vcpu->stat.fpu_reload;
6922 kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
6926 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
6928 kvmclock_reset(vcpu);
6930 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
6932 kvm_x86_ops->vcpu_free(vcpu);
6935 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
6938 if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
6939 printk_once(KERN_WARNING
6940 "kvm: SMP vm created on host with unstable TSC; "
6941 "guest TSC will not be reliable\n");
6942 return kvm_x86_ops->vcpu_create(kvm, id);
6945 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
6949 vcpu->arch.mtrr_state.have_fixed = 1;
6950 r = vcpu_load(vcpu);
6953 kvm_vcpu_reset(vcpu);
6954 kvm_mmu_setup(vcpu);
6960 int kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
6963 struct msr_data msr;
6964 struct kvm *kvm = vcpu->kvm;
6966 r = vcpu_load(vcpu);
6970 msr.index = MSR_IA32_TSC;
6971 msr.host_initiated = true;
6972 kvm_write_tsc(vcpu, &msr);
6975 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
6976 KVMCLOCK_SYNC_PERIOD);
6981 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
6984 vcpu->arch.apf.msr_val = 0;
6986 r = vcpu_load(vcpu);
6988 kvm_mmu_unload(vcpu);
6992 kvm_x86_ops->vcpu_free(vcpu);
6995 void kvm_vcpu_reset(struct kvm_vcpu *vcpu)
6997 atomic_set(&vcpu->arch.nmi_queued, 0);
6998 vcpu->arch.nmi_pending = 0;
6999 vcpu->arch.nmi_injected = false;
7000 kvm_clear_interrupt_queue(vcpu);
7001 kvm_clear_exception_queue(vcpu);
7003 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
7004 vcpu->arch.dr6 = DR6_INIT;
7005 kvm_update_dr6(vcpu);
7006 vcpu->arch.dr7 = DR7_FIXED_1;
7007 kvm_update_dr7(vcpu);
7009 kvm_make_request(KVM_REQ_EVENT, vcpu);
7010 vcpu->arch.apf.msr_val = 0;
7011 vcpu->arch.st.msr_val = 0;
7013 kvmclock_reset(vcpu);
7015 kvm_clear_async_pf_completion_queue(vcpu);
7016 kvm_async_pf_hash_reset(vcpu);
7017 vcpu->arch.apf.halted = false;
7019 kvm_pmu_reset(vcpu);
7021 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
7022 vcpu->arch.regs_avail = ~0;
7023 vcpu->arch.regs_dirty = ~0;
7025 kvm_x86_ops->vcpu_reset(vcpu);
7028 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, unsigned int vector)
7030 struct kvm_segment cs;
7032 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7033 cs.selector = vector << 8;
7034 cs.base = vector << 12;
7035 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7036 kvm_rip_write(vcpu, 0);
7039 int kvm_arch_hardware_enable(void)
7042 struct kvm_vcpu *vcpu;
7047 bool stable, backwards_tsc = false;
7049 kvm_shared_msr_cpu_online();
7050 ret = kvm_x86_ops->hardware_enable();
7054 local_tsc = native_read_tsc();
7055 stable = !check_tsc_unstable();
7056 list_for_each_entry(kvm, &vm_list, vm_list) {
7057 kvm_for_each_vcpu(i, vcpu, kvm) {
7058 if (!stable && vcpu->cpu == smp_processor_id())
7059 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7060 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
7061 backwards_tsc = true;
7062 if (vcpu->arch.last_host_tsc > max_tsc)
7063 max_tsc = vcpu->arch.last_host_tsc;
7069 * Sometimes, even reliable TSCs go backwards. This happens on
7070 * platforms that reset TSC during suspend or hibernate actions, but
7071 * maintain synchronization. We must compensate. Fortunately, we can
7072 * detect that condition here, which happens early in CPU bringup,
7073 * before any KVM threads can be running. Unfortunately, we can't
7074 * bring the TSCs fully up to date with real time, as we aren't yet far
7075 * enough into CPU bringup that we know how much real time has actually
7076 * elapsed; our helper function, get_kernel_ns() will be using boot
7077 * variables that haven't been updated yet.
7079 * So we simply find the maximum observed TSC above, then record the
7080 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
7081 * the adjustment will be applied. Note that we accumulate
7082 * adjustments, in case multiple suspend cycles happen before some VCPU
7083 * gets a chance to run again. In the event that no KVM threads get a
7084 * chance to run, we will miss the entire elapsed period, as we'll have
7085 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
7086 * loose cycle time. This isn't too big a deal, since the loss will be
7087 * uniform across all VCPUs (not to mention the scenario is extremely
7088 * unlikely). It is possible that a second hibernate recovery happens
7089 * much faster than a first, causing the observed TSC here to be
7090 * smaller; this would require additional padding adjustment, which is
7091 * why we set last_host_tsc to the local tsc observed here.
7093 * N.B. - this code below runs only on platforms with reliable TSC,
7094 * as that is the only way backwards_tsc is set above. Also note
7095 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
7096 * have the same delta_cyc adjustment applied if backwards_tsc
7097 * is detected. Note further, this adjustment is only done once,
7098 * as we reset last_host_tsc on all VCPUs to stop this from being
7099 * called multiple times (one for each physical CPU bringup).
7101 * Platforms with unreliable TSCs don't have to deal with this, they
7102 * will be compensated by the logic in vcpu_load, which sets the TSC to
7103 * catchup mode. This will catchup all VCPUs to real time, but cannot
7104 * guarantee that they stay in perfect synchronization.
7106 if (backwards_tsc) {
7107 u64 delta_cyc = max_tsc - local_tsc;
7108 backwards_tsc_observed = true;
7109 list_for_each_entry(kvm, &vm_list, vm_list) {
7110 kvm_for_each_vcpu(i, vcpu, kvm) {
7111 vcpu->arch.tsc_offset_adjustment += delta_cyc;
7112 vcpu->arch.last_host_tsc = local_tsc;
7113 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7117 * We have to disable TSC offset matching.. if you were
7118 * booting a VM while issuing an S4 host suspend....
7119 * you may have some problem. Solving this issue is
7120 * left as an exercise to the reader.
7122 kvm->arch.last_tsc_nsec = 0;
7123 kvm->arch.last_tsc_write = 0;
7130 void kvm_arch_hardware_disable(void)
7132 kvm_x86_ops->hardware_disable();
7133 drop_user_return_notifiers();
7136 int kvm_arch_hardware_setup(void)
7138 return kvm_x86_ops->hardware_setup();
7141 void kvm_arch_hardware_unsetup(void)
7143 kvm_x86_ops->hardware_unsetup();
7146 void kvm_arch_check_processor_compat(void *rtn)
7148 kvm_x86_ops->check_processor_compatibility(rtn);
7151 bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
7153 return irqchip_in_kernel(vcpu->kvm) == (vcpu->arch.apic != NULL);
7156 struct static_key kvm_no_apic_vcpu __read_mostly;
7158 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
7164 BUG_ON(vcpu->kvm == NULL);
7167 vcpu->arch.pv.pv_unhalted = false;
7168 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
7169 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
7170 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7172 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
7174 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
7179 vcpu->arch.pio_data = page_address(page);
7181 kvm_set_tsc_khz(vcpu, max_tsc_khz);
7183 r = kvm_mmu_create(vcpu);
7185 goto fail_free_pio_data;
7187 if (irqchip_in_kernel(kvm)) {
7188 r = kvm_create_lapic(vcpu);
7190 goto fail_mmu_destroy;
7192 static_key_slow_inc(&kvm_no_apic_vcpu);
7194 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
7196 if (!vcpu->arch.mce_banks) {
7198 goto fail_free_lapic;
7200 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
7202 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
7204 goto fail_free_mce_banks;
7209 goto fail_free_wbinvd_dirty_mask;
7211 vcpu->arch.ia32_tsc_adjust_msr = 0x0;
7212 vcpu->arch.pv_time_enabled = false;
7214 vcpu->arch.guest_supported_xcr0 = 0;
7215 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
7217 kvm_async_pf_hash_reset(vcpu);
7221 fail_free_wbinvd_dirty_mask:
7222 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
7223 fail_free_mce_banks:
7224 kfree(vcpu->arch.mce_banks);
7226 kvm_free_lapic(vcpu);
7228 kvm_mmu_destroy(vcpu);
7230 free_page((unsigned long)vcpu->arch.pio_data);
7235 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
7239 kvm_pmu_destroy(vcpu);
7240 kfree(vcpu->arch.mce_banks);
7241 kvm_free_lapic(vcpu);
7242 idx = srcu_read_lock(&vcpu->kvm->srcu);
7243 kvm_mmu_destroy(vcpu);
7244 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7245 free_page((unsigned long)vcpu->arch.pio_data);
7246 if (!irqchip_in_kernel(vcpu->kvm))
7247 static_key_slow_dec(&kvm_no_apic_vcpu);
7250 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
7252 kvm_x86_ops->sched_in(vcpu, cpu);
7255 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
7260 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
7261 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
7262 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
7263 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
7265 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
7266 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
7267 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
7268 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
7269 &kvm->arch.irq_sources_bitmap);
7271 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
7272 mutex_init(&kvm->arch.apic_map_lock);
7273 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
7275 pvclock_update_vm_gtod_copy(kvm);
7277 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
7278 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
7283 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
7286 r = vcpu_load(vcpu);
7288 kvm_mmu_unload(vcpu);
7292 static void kvm_free_vcpus(struct kvm *kvm)
7295 struct kvm_vcpu *vcpu;
7298 * Unpin any mmu pages first.
7300 kvm_for_each_vcpu(i, vcpu, kvm) {
7301 kvm_clear_async_pf_completion_queue(vcpu);
7302 kvm_unload_vcpu_mmu(vcpu);
7304 kvm_for_each_vcpu(i, vcpu, kvm)
7305 kvm_arch_vcpu_free(vcpu);
7307 mutex_lock(&kvm->lock);
7308 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
7309 kvm->vcpus[i] = NULL;
7311 atomic_set(&kvm->online_vcpus, 0);
7312 mutex_unlock(&kvm->lock);
7315 void kvm_arch_sync_events(struct kvm *kvm)
7317 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
7318 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
7319 kvm_free_all_assigned_devices(kvm);
7323 void kvm_arch_destroy_vm(struct kvm *kvm)
7325 if (current->mm == kvm->mm) {
7327 * Free memory regions allocated on behalf of userspace,
7328 * unless the the memory map has changed due to process exit
7331 struct kvm_userspace_memory_region mem;
7332 memset(&mem, 0, sizeof(mem));
7333 mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
7334 kvm_set_memory_region(kvm, &mem);
7336 mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
7337 kvm_set_memory_region(kvm, &mem);
7339 mem.slot = TSS_PRIVATE_MEMSLOT;
7340 kvm_set_memory_region(kvm, &mem);
7342 kvm_iommu_unmap_guest(kvm);
7343 kfree(kvm->arch.vpic);
7344 kfree(kvm->arch.vioapic);
7345 kvm_free_vcpus(kvm);
7346 kfree(rcu_dereference_check(kvm->arch.apic_map, 1));
7349 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
7350 struct kvm_memory_slot *dont)
7354 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7355 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
7356 kvm_kvfree(free->arch.rmap[i]);
7357 free->arch.rmap[i] = NULL;
7362 if (!dont || free->arch.lpage_info[i - 1] !=
7363 dont->arch.lpage_info[i - 1]) {
7364 kvm_kvfree(free->arch.lpage_info[i - 1]);
7365 free->arch.lpage_info[i - 1] = NULL;
7370 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
7371 unsigned long npages)
7375 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7380 lpages = gfn_to_index(slot->base_gfn + npages - 1,
7381 slot->base_gfn, level) + 1;
7383 slot->arch.rmap[i] =
7384 kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
7385 if (!slot->arch.rmap[i])
7390 slot->arch.lpage_info[i - 1] = kvm_kvzalloc(lpages *
7391 sizeof(*slot->arch.lpage_info[i - 1]));
7392 if (!slot->arch.lpage_info[i - 1])
7395 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
7396 slot->arch.lpage_info[i - 1][0].write_count = 1;
7397 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
7398 slot->arch.lpage_info[i - 1][lpages - 1].write_count = 1;
7399 ugfn = slot->userspace_addr >> PAGE_SHIFT;
7401 * If the gfn and userspace address are not aligned wrt each
7402 * other, or if explicitly asked to, disable large page
7403 * support for this slot
7405 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
7406 !kvm_largepages_enabled()) {
7409 for (j = 0; j < lpages; ++j)
7410 slot->arch.lpage_info[i - 1][j].write_count = 1;
7417 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7418 kvm_kvfree(slot->arch.rmap[i]);
7419 slot->arch.rmap[i] = NULL;
7423 kvm_kvfree(slot->arch.lpage_info[i - 1]);
7424 slot->arch.lpage_info[i - 1] = NULL;
7429 void kvm_arch_memslots_updated(struct kvm *kvm)
7432 * memslots->generation has been incremented.
7433 * mmio generation may have reached its maximum value.
7435 kvm_mmu_invalidate_mmio_sptes(kvm);
7438 int kvm_arch_prepare_memory_region(struct kvm *kvm,
7439 struct kvm_memory_slot *memslot,
7440 struct kvm_userspace_memory_region *mem,
7441 enum kvm_mr_change change)
7444 * Only private memory slots need to be mapped here since
7445 * KVM_SET_MEMORY_REGION ioctl is no longer supported.
7447 if ((memslot->id >= KVM_USER_MEM_SLOTS) && (change == KVM_MR_CREATE)) {
7448 unsigned long userspace_addr;
7451 * MAP_SHARED to prevent internal slot pages from being moved
7454 userspace_addr = vm_mmap(NULL, 0, memslot->npages * PAGE_SIZE,
7455 PROT_READ | PROT_WRITE,
7456 MAP_SHARED | MAP_ANONYMOUS, 0);
7458 if (IS_ERR((void *)userspace_addr))
7459 return PTR_ERR((void *)userspace_addr);
7461 memslot->userspace_addr = userspace_addr;
7467 void kvm_arch_commit_memory_region(struct kvm *kvm,
7468 struct kvm_userspace_memory_region *mem,
7469 const struct kvm_memory_slot *old,
7470 enum kvm_mr_change change)
7473 int nr_mmu_pages = 0;
7475 if ((mem->slot >= KVM_USER_MEM_SLOTS) && (change == KVM_MR_DELETE)) {
7478 ret = vm_munmap(old->userspace_addr,
7479 old->npages * PAGE_SIZE);
7482 "kvm_vm_ioctl_set_memory_region: "
7483 "failed to munmap memory\n");
7486 if (!kvm->arch.n_requested_mmu_pages)
7487 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
7490 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
7492 * Write protect all pages for dirty logging.
7494 * All the sptes including the large sptes which point to this
7495 * slot are set to readonly. We can not create any new large
7496 * spte on this slot until the end of the logging.
7498 * See the comments in fast_page_fault().
7500 if ((change != KVM_MR_DELETE) && (mem->flags & KVM_MEM_LOG_DIRTY_PAGES))
7501 kvm_mmu_slot_remove_write_access(kvm, mem->slot);
7504 void kvm_arch_flush_shadow_all(struct kvm *kvm)
7506 kvm_mmu_invalidate_zap_all_pages(kvm);
7509 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
7510 struct kvm_memory_slot *slot)
7512 kvm_mmu_invalidate_zap_all_pages(kvm);
7515 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
7517 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
7518 kvm_x86_ops->check_nested_events(vcpu, false);
7520 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
7521 !vcpu->arch.apf.halted)
7522 || !list_empty_careful(&vcpu->async_pf.done)
7523 || kvm_apic_has_events(vcpu)
7524 || vcpu->arch.pv.pv_unhalted
7525 || atomic_read(&vcpu->arch.nmi_queued) ||
7526 (kvm_arch_interrupt_allowed(vcpu) &&
7527 kvm_cpu_has_interrupt(vcpu));
7530 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
7532 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
7535 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
7537 return kvm_x86_ops->interrupt_allowed(vcpu);
7540 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
7542 if (is_64_bit_mode(vcpu))
7543 return kvm_rip_read(vcpu);
7544 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
7545 kvm_rip_read(vcpu));
7547 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
7549 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
7551 return kvm_get_linear_rip(vcpu) == linear_rip;
7553 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
7555 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
7557 unsigned long rflags;
7559 rflags = kvm_x86_ops->get_rflags(vcpu);
7560 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7561 rflags &= ~X86_EFLAGS_TF;
7564 EXPORT_SYMBOL_GPL(kvm_get_rflags);
7566 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
7568 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
7569 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
7570 rflags |= X86_EFLAGS_TF;
7571 kvm_x86_ops->set_rflags(vcpu, rflags);
7574 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
7576 __kvm_set_rflags(vcpu, rflags);
7577 kvm_make_request(KVM_REQ_EVENT, vcpu);
7579 EXPORT_SYMBOL_GPL(kvm_set_rflags);
7581 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
7585 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
7589 r = kvm_mmu_reload(vcpu);
7593 if (!vcpu->arch.mmu.direct_map &&
7594 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
7597 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
7600 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
7602 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
7605 static inline u32 kvm_async_pf_next_probe(u32 key)
7607 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
7610 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
7612 u32 key = kvm_async_pf_hash_fn(gfn);
7614 while (vcpu->arch.apf.gfns[key] != ~0)
7615 key = kvm_async_pf_next_probe(key);
7617 vcpu->arch.apf.gfns[key] = gfn;
7620 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
7623 u32 key = kvm_async_pf_hash_fn(gfn);
7625 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
7626 (vcpu->arch.apf.gfns[key] != gfn &&
7627 vcpu->arch.apf.gfns[key] != ~0); i++)
7628 key = kvm_async_pf_next_probe(key);
7633 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
7635 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
7638 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
7642 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
7644 vcpu->arch.apf.gfns[i] = ~0;
7646 j = kvm_async_pf_next_probe(j);
7647 if (vcpu->arch.apf.gfns[j] == ~0)
7649 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
7651 * k lies cyclically in ]i,j]
7653 * |....j i.k.| or |.k..j i...|
7655 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
7656 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
7661 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
7664 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
7668 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
7669 struct kvm_async_pf *work)
7671 struct x86_exception fault;
7673 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
7674 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
7676 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
7677 (vcpu->arch.apf.send_user_only &&
7678 kvm_x86_ops->get_cpl(vcpu) == 0))
7679 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
7680 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
7681 fault.vector = PF_VECTOR;
7682 fault.error_code_valid = true;
7683 fault.error_code = 0;
7684 fault.nested_page_fault = false;
7685 fault.address = work->arch.token;
7686 kvm_inject_page_fault(vcpu, &fault);
7690 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
7691 struct kvm_async_pf *work)
7693 struct x86_exception fault;
7695 trace_kvm_async_pf_ready(work->arch.token, work->gva);
7696 if (work->wakeup_all)
7697 work->arch.token = ~0; /* broadcast wakeup */
7699 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
7701 if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
7702 !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
7703 fault.vector = PF_VECTOR;
7704 fault.error_code_valid = true;
7705 fault.error_code = 0;
7706 fault.nested_page_fault = false;
7707 fault.address = work->arch.token;
7708 kvm_inject_page_fault(vcpu, &fault);
7710 vcpu->arch.apf.halted = false;
7711 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7714 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
7716 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
7719 return !kvm_event_needs_reinjection(vcpu) &&
7720 kvm_x86_ops->interrupt_allowed(vcpu);
7723 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
7725 atomic_inc(&kvm->arch.noncoherent_dma_count);
7727 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
7729 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
7731 atomic_dec(&kvm->arch.noncoherent_dma_count);
7733 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
7735 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
7737 return atomic_read(&kvm->arch.noncoherent_dma_count);
7739 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
7741 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
7742 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
7743 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
7744 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
7745 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
7746 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
7747 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
7748 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
7749 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
7750 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
7751 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
7752 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
7753 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
7754 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);