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"
30 #include "assigned-dev.h"
34 #include <linux/clocksource.h>
35 #include <linux/interrupt.h>
36 #include <linux/kvm.h>
38 #include <linux/vmalloc.h>
39 #include <linux/module.h>
40 #include <linux/mman.h>
41 #include <linux/highmem.h>
42 #include <linux/iommu.h>
43 #include <linux/intel-iommu.h>
44 #include <linux/cpufreq.h>
45 #include <linux/user-return-notifier.h>
46 #include <linux/srcu.h>
47 #include <linux/slab.h>
48 #include <linux/perf_event.h>
49 #include <linux/uaccess.h>
50 #include <linux/hash.h>
51 #include <linux/pci.h>
52 #include <linux/timekeeper_internal.h>
53 #include <linux/pvclock_gtod.h>
54 #include <linux/kvm_irqfd.h>
55 #include <linux/irqbypass.h>
56 #include <trace/events/kvm.h>
58 #define CREATE_TRACE_POINTS
61 #include <asm/debugreg.h>
65 #include <linux/kernel_stat.h>
66 #include <asm/fpu/internal.h> /* Ugh! */
67 #include <asm/pvclock.h>
68 #include <asm/div64.h>
69 #include <asm/irq_remapping.h>
71 #define MAX_IO_MSRS 256
72 #define KVM_MAX_MCE_BANKS 32
73 #define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
75 #define emul_to_vcpu(ctxt) \
76 container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
79 * - enable syscall per default because its emulated by KVM
80 * - enable LME and LMA per default on 64 bit KVM
84 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
86 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
89 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
90 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
92 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
93 static void process_nmi(struct kvm_vcpu *vcpu);
94 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
96 struct kvm_x86_ops *kvm_x86_ops __read_mostly;
97 EXPORT_SYMBOL_GPL(kvm_x86_ops);
99 static bool __read_mostly ignore_msrs = 0;
100 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
102 unsigned int min_timer_period_us = 500;
103 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
105 static bool __read_mostly kvmclock_periodic_sync = true;
106 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
108 bool __read_mostly kvm_has_tsc_control;
109 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
110 u32 __read_mostly kvm_max_guest_tsc_khz;
111 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
112 u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
113 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
114 u64 __read_mostly kvm_max_tsc_scaling_ratio;
115 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
116 static u64 __read_mostly kvm_default_tsc_scaling_ratio;
118 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
119 static u32 __read_mostly tsc_tolerance_ppm = 250;
120 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
122 /* lapic timer advance (tscdeadline mode only) in nanoseconds */
123 unsigned int __read_mostly lapic_timer_advance_ns = 0;
124 module_param(lapic_timer_advance_ns, uint, S_IRUGO | S_IWUSR);
126 static bool __read_mostly backwards_tsc_observed = false;
128 #define KVM_NR_SHARED_MSRS 16
130 struct kvm_shared_msrs_global {
132 u32 msrs[KVM_NR_SHARED_MSRS];
135 struct kvm_shared_msrs {
136 struct user_return_notifier urn;
138 struct kvm_shared_msr_values {
141 } values[KVM_NR_SHARED_MSRS];
144 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
145 static struct kvm_shared_msrs __percpu *shared_msrs;
147 struct kvm_stats_debugfs_item debugfs_entries[] = {
148 { "pf_fixed", VCPU_STAT(pf_fixed) },
149 { "pf_guest", VCPU_STAT(pf_guest) },
150 { "tlb_flush", VCPU_STAT(tlb_flush) },
151 { "invlpg", VCPU_STAT(invlpg) },
152 { "exits", VCPU_STAT(exits) },
153 { "io_exits", VCPU_STAT(io_exits) },
154 { "mmio_exits", VCPU_STAT(mmio_exits) },
155 { "signal_exits", VCPU_STAT(signal_exits) },
156 { "irq_window", VCPU_STAT(irq_window_exits) },
157 { "nmi_window", VCPU_STAT(nmi_window_exits) },
158 { "halt_exits", VCPU_STAT(halt_exits) },
159 { "halt_successful_poll", VCPU_STAT(halt_successful_poll) },
160 { "halt_attempted_poll", VCPU_STAT(halt_attempted_poll) },
161 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
162 { "hypercalls", VCPU_STAT(hypercalls) },
163 { "request_irq", VCPU_STAT(request_irq_exits) },
164 { "irq_exits", VCPU_STAT(irq_exits) },
165 { "host_state_reload", VCPU_STAT(host_state_reload) },
166 { "efer_reload", VCPU_STAT(efer_reload) },
167 { "fpu_reload", VCPU_STAT(fpu_reload) },
168 { "insn_emulation", VCPU_STAT(insn_emulation) },
169 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
170 { "irq_injections", VCPU_STAT(irq_injections) },
171 { "nmi_injections", VCPU_STAT(nmi_injections) },
172 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
173 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
174 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
175 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
176 { "mmu_flooded", VM_STAT(mmu_flooded) },
177 { "mmu_recycled", VM_STAT(mmu_recycled) },
178 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
179 { "mmu_unsync", VM_STAT(mmu_unsync) },
180 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
181 { "largepages", VM_STAT(lpages) },
185 u64 __read_mostly host_xcr0;
187 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
189 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
192 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
193 vcpu->arch.apf.gfns[i] = ~0;
196 static void kvm_on_user_return(struct user_return_notifier *urn)
199 struct kvm_shared_msrs *locals
200 = container_of(urn, struct kvm_shared_msrs, urn);
201 struct kvm_shared_msr_values *values;
205 * Disabling irqs at this point since the following code could be
206 * interrupted and executed through kvm_arch_hardware_disable()
208 local_irq_save(flags);
209 if (locals->registered) {
210 locals->registered = false;
211 user_return_notifier_unregister(urn);
213 local_irq_restore(flags);
214 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
215 values = &locals->values[slot];
216 if (values->host != values->curr) {
217 wrmsrl(shared_msrs_global.msrs[slot], values->host);
218 values->curr = values->host;
223 static void shared_msr_update(unsigned slot, u32 msr)
226 unsigned int cpu = smp_processor_id();
227 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
229 /* only read, and nobody should modify it at this time,
230 * so don't need lock */
231 if (slot >= shared_msrs_global.nr) {
232 printk(KERN_ERR "kvm: invalid MSR slot!");
235 rdmsrl_safe(msr, &value);
236 smsr->values[slot].host = value;
237 smsr->values[slot].curr = value;
240 void kvm_define_shared_msr(unsigned slot, u32 msr)
242 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
243 shared_msrs_global.msrs[slot] = msr;
244 if (slot >= shared_msrs_global.nr)
245 shared_msrs_global.nr = slot + 1;
247 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
249 static void kvm_shared_msr_cpu_online(void)
253 for (i = 0; i < shared_msrs_global.nr; ++i)
254 shared_msr_update(i, shared_msrs_global.msrs[i]);
257 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
259 unsigned int cpu = smp_processor_id();
260 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
263 if (((value ^ smsr->values[slot].curr) & mask) == 0)
265 smsr->values[slot].curr = value;
266 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
270 if (!smsr->registered) {
271 smsr->urn.on_user_return = kvm_on_user_return;
272 user_return_notifier_register(&smsr->urn);
273 smsr->registered = true;
277 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
279 static void drop_user_return_notifiers(void)
281 unsigned int cpu = smp_processor_id();
282 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
284 if (smsr->registered)
285 kvm_on_user_return(&smsr->urn);
288 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
290 return vcpu->arch.apic_base;
292 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
294 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
296 u64 old_state = vcpu->arch.apic_base &
297 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
298 u64 new_state = msr_info->data &
299 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
300 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) |
301 0x2ff | (guest_cpuid_has_x2apic(vcpu) ? 0 : X2APIC_ENABLE);
303 if (!msr_info->host_initiated &&
304 ((msr_info->data & reserved_bits) != 0 ||
305 new_state == X2APIC_ENABLE ||
306 (new_state == MSR_IA32_APICBASE_ENABLE &&
307 old_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) ||
308 (new_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE) &&
312 kvm_lapic_set_base(vcpu, msr_info->data);
315 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
317 asmlinkage __visible void kvm_spurious_fault(void)
319 /* Fault while not rebooting. We want the trace. */
322 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
324 #define EXCPT_BENIGN 0
325 #define EXCPT_CONTRIBUTORY 1
328 static int exception_class(int vector)
338 return EXCPT_CONTRIBUTORY;
345 #define EXCPT_FAULT 0
347 #define EXCPT_ABORT 2
348 #define EXCPT_INTERRUPT 3
350 static int exception_type(int vector)
354 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
355 return EXCPT_INTERRUPT;
359 /* #DB is trap, as instruction watchpoints are handled elsewhere */
360 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
363 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
366 /* Reserved exceptions will result in fault */
370 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
371 unsigned nr, bool has_error, u32 error_code,
377 kvm_make_request(KVM_REQ_EVENT, vcpu);
379 if (!vcpu->arch.exception.pending) {
381 if (has_error && !is_protmode(vcpu))
383 vcpu->arch.exception.pending = true;
384 vcpu->arch.exception.has_error_code = has_error;
385 vcpu->arch.exception.nr = nr;
386 vcpu->arch.exception.error_code = error_code;
387 vcpu->arch.exception.reinject = reinject;
391 /* to check exception */
392 prev_nr = vcpu->arch.exception.nr;
393 if (prev_nr == DF_VECTOR) {
394 /* triple fault -> shutdown */
395 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
398 class1 = exception_class(prev_nr);
399 class2 = exception_class(nr);
400 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
401 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
402 /* generate double fault per SDM Table 5-5 */
403 vcpu->arch.exception.pending = true;
404 vcpu->arch.exception.has_error_code = true;
405 vcpu->arch.exception.nr = DF_VECTOR;
406 vcpu->arch.exception.error_code = 0;
408 /* replace previous exception with a new one in a hope
409 that instruction re-execution will regenerate lost
414 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
416 kvm_multiple_exception(vcpu, nr, false, 0, false);
418 EXPORT_SYMBOL_GPL(kvm_queue_exception);
420 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
422 kvm_multiple_exception(vcpu, nr, false, 0, true);
424 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
426 void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
429 kvm_inject_gp(vcpu, 0);
431 kvm_x86_ops->skip_emulated_instruction(vcpu);
433 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
435 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
437 ++vcpu->stat.pf_guest;
438 vcpu->arch.cr2 = fault->address;
439 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
441 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
443 static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
445 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
446 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
448 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
450 return fault->nested_page_fault;
453 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
455 atomic_inc(&vcpu->arch.nmi_queued);
456 kvm_make_request(KVM_REQ_NMI, vcpu);
458 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
460 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
462 kvm_multiple_exception(vcpu, nr, true, error_code, false);
464 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
466 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
468 kvm_multiple_exception(vcpu, nr, true, error_code, true);
470 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
473 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
474 * a #GP and return false.
476 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
478 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
480 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
483 EXPORT_SYMBOL_GPL(kvm_require_cpl);
485 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
487 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
490 kvm_queue_exception(vcpu, UD_VECTOR);
493 EXPORT_SYMBOL_GPL(kvm_require_dr);
496 * This function will be used to read from the physical memory of the currently
497 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
498 * can read from guest physical or from the guest's guest physical memory.
500 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
501 gfn_t ngfn, void *data, int offset, int len,
504 struct x86_exception exception;
508 ngpa = gfn_to_gpa(ngfn);
509 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
510 if (real_gfn == UNMAPPED_GVA)
513 real_gfn = gpa_to_gfn(real_gfn);
515 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
517 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
519 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
520 void *data, int offset, int len, u32 access)
522 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
523 data, offset, len, access);
527 * Load the pae pdptrs. Return true is they are all valid.
529 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
531 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
532 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
535 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
537 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
538 offset * sizeof(u64), sizeof(pdpte),
539 PFERR_USER_MASK|PFERR_WRITE_MASK);
544 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
545 if (is_present_gpte(pdpte[i]) &&
547 vcpu->arch.mmu.guest_rsvd_check.rsvd_bits_mask[0][2])) {
554 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
555 __set_bit(VCPU_EXREG_PDPTR,
556 (unsigned long *)&vcpu->arch.regs_avail);
557 __set_bit(VCPU_EXREG_PDPTR,
558 (unsigned long *)&vcpu->arch.regs_dirty);
563 EXPORT_SYMBOL_GPL(load_pdptrs);
565 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
567 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
573 if (is_long_mode(vcpu) || !is_pae(vcpu))
576 if (!test_bit(VCPU_EXREG_PDPTR,
577 (unsigned long *)&vcpu->arch.regs_avail))
580 gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
581 offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
582 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
583 PFERR_USER_MASK | PFERR_WRITE_MASK);
586 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
592 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
594 unsigned long old_cr0 = kvm_read_cr0(vcpu);
595 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
600 if (cr0 & 0xffffffff00000000UL)
604 cr0 &= ~CR0_RESERVED_BITS;
606 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
609 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
612 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
614 if ((vcpu->arch.efer & EFER_LME)) {
619 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
624 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
629 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
632 kvm_x86_ops->set_cr0(vcpu, cr0);
634 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
635 kvm_clear_async_pf_completion_queue(vcpu);
636 kvm_async_pf_hash_reset(vcpu);
639 if ((cr0 ^ old_cr0) & update_bits)
640 kvm_mmu_reset_context(vcpu);
642 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
643 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
644 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
645 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
649 EXPORT_SYMBOL_GPL(kvm_set_cr0);
651 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
653 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
655 EXPORT_SYMBOL_GPL(kvm_lmsw);
657 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
659 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
660 !vcpu->guest_xcr0_loaded) {
661 /* kvm_set_xcr() also depends on this */
662 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
663 vcpu->guest_xcr0_loaded = 1;
667 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
669 if (vcpu->guest_xcr0_loaded) {
670 if (vcpu->arch.xcr0 != host_xcr0)
671 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
672 vcpu->guest_xcr0_loaded = 0;
676 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
679 u64 old_xcr0 = vcpu->arch.xcr0;
682 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
683 if (index != XCR_XFEATURE_ENABLED_MASK)
685 if (!(xcr0 & XFEATURE_MASK_FP))
687 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
691 * Do not allow the guest to set bits that we do not support
692 * saving. However, xcr0 bit 0 is always set, even if the
693 * emulated CPU does not support XSAVE (see fx_init).
695 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
696 if (xcr0 & ~valid_bits)
699 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
700 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
703 if (xcr0 & XFEATURE_MASK_AVX512) {
704 if (!(xcr0 & XFEATURE_MASK_YMM))
706 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
709 vcpu->arch.xcr0 = xcr0;
711 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
712 kvm_update_cpuid(vcpu);
716 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
718 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
719 __kvm_set_xcr(vcpu, index, xcr)) {
720 kvm_inject_gp(vcpu, 0);
725 EXPORT_SYMBOL_GPL(kvm_set_xcr);
727 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
729 unsigned long old_cr4 = kvm_read_cr4(vcpu);
730 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
731 X86_CR4_SMEP | X86_CR4_SMAP;
733 if (cr4 & CR4_RESERVED_BITS)
736 if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
739 if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
742 if (!guest_cpuid_has_smap(vcpu) && (cr4 & X86_CR4_SMAP))
745 if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_FSGSBASE))
748 if (is_long_mode(vcpu)) {
749 if (!(cr4 & X86_CR4_PAE))
751 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
752 && ((cr4 ^ old_cr4) & pdptr_bits)
753 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
757 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
758 if (!guest_cpuid_has_pcid(vcpu))
761 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
762 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
766 if (kvm_x86_ops->set_cr4(vcpu, cr4))
769 if (((cr4 ^ old_cr4) & pdptr_bits) ||
770 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
771 kvm_mmu_reset_context(vcpu);
773 if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
774 kvm_update_cpuid(vcpu);
778 EXPORT_SYMBOL_GPL(kvm_set_cr4);
780 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
783 cr3 &= ~CR3_PCID_INVD;
786 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
787 kvm_mmu_sync_roots(vcpu);
788 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
792 if (is_long_mode(vcpu)) {
793 if (cr3 & CR3_L_MODE_RESERVED_BITS)
795 } else if (is_pae(vcpu) && is_paging(vcpu) &&
796 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
799 vcpu->arch.cr3 = cr3;
800 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
801 kvm_mmu_new_cr3(vcpu);
804 EXPORT_SYMBOL_GPL(kvm_set_cr3);
806 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
808 if (cr8 & CR8_RESERVED_BITS)
810 if (lapic_in_kernel(vcpu))
811 kvm_lapic_set_tpr(vcpu, cr8);
813 vcpu->arch.cr8 = cr8;
816 EXPORT_SYMBOL_GPL(kvm_set_cr8);
818 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
820 if (lapic_in_kernel(vcpu))
821 return kvm_lapic_get_cr8(vcpu);
823 return vcpu->arch.cr8;
825 EXPORT_SYMBOL_GPL(kvm_get_cr8);
827 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
831 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
832 for (i = 0; i < KVM_NR_DB_REGS; i++)
833 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
834 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
838 static void kvm_update_dr6(struct kvm_vcpu *vcpu)
840 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
841 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
844 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
848 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
849 dr7 = vcpu->arch.guest_debug_dr7;
851 dr7 = vcpu->arch.dr7;
852 kvm_x86_ops->set_dr7(vcpu, dr7);
853 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
854 if (dr7 & DR7_BP_EN_MASK)
855 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
858 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
860 u64 fixed = DR6_FIXED_1;
862 if (!guest_cpuid_has_rtm(vcpu))
867 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
871 vcpu->arch.db[dr] = val;
872 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
873 vcpu->arch.eff_db[dr] = val;
878 if (val & 0xffffffff00000000ULL)
880 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
881 kvm_update_dr6(vcpu);
886 if (val & 0xffffffff00000000ULL)
888 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
889 kvm_update_dr7(vcpu);
896 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
898 if (__kvm_set_dr(vcpu, dr, val)) {
899 kvm_inject_gp(vcpu, 0);
904 EXPORT_SYMBOL_GPL(kvm_set_dr);
906 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
910 *val = vcpu->arch.db[dr];
915 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
916 *val = vcpu->arch.dr6;
918 *val = kvm_x86_ops->get_dr6(vcpu);
923 *val = vcpu->arch.dr7;
928 EXPORT_SYMBOL_GPL(kvm_get_dr);
930 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
932 u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
936 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
939 kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
940 kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
943 EXPORT_SYMBOL_GPL(kvm_rdpmc);
946 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
947 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
949 * This list is modified at module load time to reflect the
950 * capabilities of the host cpu. This capabilities test skips MSRs that are
951 * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
952 * may depend on host virtualization features rather than host cpu features.
955 static u32 msrs_to_save[] = {
956 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
959 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
961 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
962 MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
965 static unsigned num_msrs_to_save;
967 static u32 emulated_msrs[] = {
968 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
969 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
970 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
971 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
972 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
973 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
976 HV_X64_MSR_VP_RUNTIME,
977 HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
981 MSR_IA32_TSCDEADLINE,
982 MSR_IA32_MISC_ENABLE,
988 static unsigned num_emulated_msrs;
990 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
992 if (efer & efer_reserved_bits)
995 if (efer & EFER_FFXSR) {
996 struct kvm_cpuid_entry2 *feat;
998 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
999 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
1003 if (efer & EFER_SVME) {
1004 struct kvm_cpuid_entry2 *feat;
1006 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
1007 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
1013 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1015 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
1017 u64 old_efer = vcpu->arch.efer;
1019 if (!kvm_valid_efer(vcpu, efer))
1023 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1027 efer |= vcpu->arch.efer & EFER_LMA;
1029 kvm_x86_ops->set_efer(vcpu, efer);
1031 /* Update reserved bits */
1032 if ((efer ^ old_efer) & EFER_NX)
1033 kvm_mmu_reset_context(vcpu);
1038 void kvm_enable_efer_bits(u64 mask)
1040 efer_reserved_bits &= ~mask;
1042 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1045 * Writes msr value into into the appropriate "register".
1046 * Returns 0 on success, non-0 otherwise.
1047 * Assumes vcpu_load() was already called.
1049 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
1051 switch (msr->index) {
1054 case MSR_KERNEL_GS_BASE:
1057 if (is_noncanonical_address(msr->data))
1060 case MSR_IA32_SYSENTER_EIP:
1061 case MSR_IA32_SYSENTER_ESP:
1063 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1064 * non-canonical address is written on Intel but not on
1065 * AMD (which ignores the top 32-bits, because it does
1066 * not implement 64-bit SYSENTER).
1068 * 64-bit code should hence be able to write a non-canonical
1069 * value on AMD. Making the address canonical ensures that
1070 * vmentry does not fail on Intel after writing a non-canonical
1071 * value, and that something deterministic happens if the guest
1072 * invokes 64-bit SYSENTER.
1074 msr->data = get_canonical(msr->data);
1076 return kvm_x86_ops->set_msr(vcpu, msr);
1078 EXPORT_SYMBOL_GPL(kvm_set_msr);
1081 * Adapt set_msr() to msr_io()'s calling convention
1083 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1085 struct msr_data msr;
1089 msr.host_initiated = true;
1090 r = kvm_get_msr(vcpu, &msr);
1098 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1100 struct msr_data msr;
1104 msr.host_initiated = true;
1105 return kvm_set_msr(vcpu, &msr);
1108 #ifdef CONFIG_X86_64
1109 struct pvclock_gtod_data {
1112 struct { /* extract of a clocksource struct */
1124 static struct pvclock_gtod_data pvclock_gtod_data;
1126 static void update_pvclock_gtod(struct timekeeper *tk)
1128 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1131 boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
1133 write_seqcount_begin(&vdata->seq);
1135 /* copy pvclock gtod data */
1136 vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
1137 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1138 vdata->clock.mask = tk->tkr_mono.mask;
1139 vdata->clock.mult = tk->tkr_mono.mult;
1140 vdata->clock.shift = tk->tkr_mono.shift;
1142 vdata->boot_ns = boot_ns;
1143 vdata->nsec_base = tk->tkr_mono.xtime_nsec;
1145 write_seqcount_end(&vdata->seq);
1149 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1152 * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
1153 * vcpu_enter_guest. This function is only called from
1154 * the physical CPU that is running vcpu.
1156 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1159 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1163 struct pvclock_wall_clock wc;
1164 struct timespec boot;
1169 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1174 ++version; /* first time write, random junk */
1178 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1181 * The guest calculates current wall clock time by adding
1182 * system time (updated by kvm_guest_time_update below) to the
1183 * wall clock specified here. guest system time equals host
1184 * system time for us, thus we must fill in host boot time here.
1188 if (kvm->arch.kvmclock_offset) {
1189 struct timespec ts = ns_to_timespec(kvm->arch.kvmclock_offset);
1190 boot = timespec_sub(boot, ts);
1192 wc.sec = boot.tv_sec;
1193 wc.nsec = boot.tv_nsec;
1194 wc.version = version;
1196 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1199 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1202 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1204 uint32_t quotient, remainder;
1206 /* Don't try to replace with do_div(), this one calculates
1207 * "(dividend << 32) / divisor" */
1209 : "=a" (quotient), "=d" (remainder)
1210 : "0" (0), "1" (dividend), "r" (divisor) );
1214 static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
1215 s8 *pshift, u32 *pmultiplier)
1222 tps64 = base_khz * 1000LL;
1223 scaled64 = scaled_khz * 1000LL;
1224 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1229 tps32 = (uint32_t)tps64;
1230 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1231 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1239 *pmultiplier = div_frac(scaled64, tps32);
1241 pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
1242 __func__, base_khz, scaled_khz, shift, *pmultiplier);
1245 #ifdef CONFIG_X86_64
1246 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1249 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1250 static unsigned long max_tsc_khz;
1252 static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
1254 return pvclock_scale_delta(nsec, vcpu->arch.virtual_tsc_mult,
1255 vcpu->arch.virtual_tsc_shift);
1258 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1260 u64 v = (u64)khz * (1000000 + ppm);
1265 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1269 /* Guest TSC same frequency as host TSC? */
1271 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1275 /* TSC scaling supported? */
1276 if (!kvm_has_tsc_control) {
1277 if (user_tsc_khz > tsc_khz) {
1278 vcpu->arch.tsc_catchup = 1;
1279 vcpu->arch.tsc_always_catchup = 1;
1282 WARN(1, "user requested TSC rate below hardware speed\n");
1287 /* TSC scaling required - calculate ratio */
1288 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1289 user_tsc_khz, tsc_khz);
1291 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1292 WARN_ONCE(1, "Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1297 vcpu->arch.tsc_scaling_ratio = ratio;
1301 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
1303 u32 thresh_lo, thresh_hi;
1304 int use_scaling = 0;
1306 /* tsc_khz can be zero if TSC calibration fails */
1307 if (this_tsc_khz == 0) {
1308 /* set tsc_scaling_ratio to a safe value */
1309 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1313 /* Compute a scale to convert nanoseconds in TSC cycles */
1314 kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
1315 &vcpu->arch.virtual_tsc_shift,
1316 &vcpu->arch.virtual_tsc_mult);
1317 vcpu->arch.virtual_tsc_khz = this_tsc_khz;
1320 * Compute the variation in TSC rate which is acceptable
1321 * within the range of tolerance and decide if the
1322 * rate being applied is within that bounds of the hardware
1323 * rate. If so, no scaling or compensation need be done.
1325 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1326 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1327 if (this_tsc_khz < thresh_lo || this_tsc_khz > thresh_hi) {
1328 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", this_tsc_khz, thresh_lo, thresh_hi);
1331 return set_tsc_khz(vcpu, this_tsc_khz, use_scaling);
1334 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1336 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1337 vcpu->arch.virtual_tsc_mult,
1338 vcpu->arch.virtual_tsc_shift);
1339 tsc += vcpu->arch.this_tsc_write;
1343 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1345 #ifdef CONFIG_X86_64
1347 struct kvm_arch *ka = &vcpu->kvm->arch;
1348 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1350 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1351 atomic_read(&vcpu->kvm->online_vcpus));
1354 * Once the masterclock is enabled, always perform request in
1355 * order to update it.
1357 * In order to enable masterclock, the host clocksource must be TSC
1358 * and the vcpus need to have matched TSCs. When that happens,
1359 * perform request to enable masterclock.
1361 if (ka->use_master_clock ||
1362 (gtod->clock.vclock_mode == VCLOCK_TSC && vcpus_matched))
1363 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1365 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1366 atomic_read(&vcpu->kvm->online_vcpus),
1367 ka->use_master_clock, gtod->clock.vclock_mode);
1371 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1373 u64 curr_offset = kvm_x86_ops->read_tsc_offset(vcpu);
1374 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1378 * Multiply tsc by a fixed point number represented by ratio.
1380 * The most significant 64-N bits (mult) of ratio represent the
1381 * integral part of the fixed point number; the remaining N bits
1382 * (frac) represent the fractional part, ie. ratio represents a fixed
1383 * point number (mult + frac * 2^(-N)).
1385 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1387 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1389 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1392 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1395 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1397 if (ratio != kvm_default_tsc_scaling_ratio)
1398 _tsc = __scale_tsc(ratio, tsc);
1402 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1404 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1408 tsc = kvm_scale_tsc(vcpu, rdtsc());
1410 return target_tsc - tsc;
1413 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1415 return kvm_x86_ops->read_l1_tsc(vcpu, kvm_scale_tsc(vcpu, host_tsc));
1417 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1419 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1421 struct kvm *kvm = vcpu->kvm;
1422 u64 offset, ns, elapsed;
1423 unsigned long flags;
1426 bool already_matched;
1427 u64 data = msr->data;
1429 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1430 offset = kvm_compute_tsc_offset(vcpu, data);
1431 ns = get_kernel_ns();
1432 elapsed = ns - kvm->arch.last_tsc_nsec;
1434 if (vcpu->arch.virtual_tsc_khz) {
1437 /* n.b - signed multiplication and division required */
1438 usdiff = data - kvm->arch.last_tsc_write;
1439 #ifdef CONFIG_X86_64
1440 usdiff = (usdiff * 1000) / vcpu->arch.virtual_tsc_khz;
1442 /* do_div() only does unsigned */
1443 asm("1: idivl %[divisor]\n"
1444 "2: xor %%edx, %%edx\n"
1445 " movl $0, %[faulted]\n"
1447 ".section .fixup,\"ax\"\n"
1448 "4: movl $1, %[faulted]\n"
1452 _ASM_EXTABLE(1b, 4b)
1454 : "=A"(usdiff), [faulted] "=r" (faulted)
1455 : "A"(usdiff * 1000), [divisor] "rm"(vcpu->arch.virtual_tsc_khz));
1458 do_div(elapsed, 1000);
1463 /* idivl overflow => difference is larger than USEC_PER_SEC */
1465 usdiff = USEC_PER_SEC;
1467 usdiff = USEC_PER_SEC; /* disable TSC match window below */
1470 * Special case: TSC write with a small delta (1 second) of virtual
1471 * cycle time against real time is interpreted as an attempt to
1472 * synchronize the CPU.
1474 * For a reliable TSC, we can match TSC offsets, and for an unstable
1475 * TSC, we add elapsed time in this computation. We could let the
1476 * compensation code attempt to catch up if we fall behind, but
1477 * it's better to try to match offsets from the beginning.
1479 if (usdiff < USEC_PER_SEC &&
1480 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1481 if (!check_tsc_unstable()) {
1482 offset = kvm->arch.cur_tsc_offset;
1483 pr_debug("kvm: matched tsc offset for %llu\n", data);
1485 u64 delta = nsec_to_cycles(vcpu, elapsed);
1487 offset = kvm_compute_tsc_offset(vcpu, data);
1488 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1491 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1494 * We split periods of matched TSC writes into generations.
1495 * For each generation, we track the original measured
1496 * nanosecond time, offset, and write, so if TSCs are in
1497 * sync, we can match exact offset, and if not, we can match
1498 * exact software computation in compute_guest_tsc()
1500 * These values are tracked in kvm->arch.cur_xxx variables.
1502 kvm->arch.cur_tsc_generation++;
1503 kvm->arch.cur_tsc_nsec = ns;
1504 kvm->arch.cur_tsc_write = data;
1505 kvm->arch.cur_tsc_offset = offset;
1507 pr_debug("kvm: new tsc generation %llu, clock %llu\n",
1508 kvm->arch.cur_tsc_generation, data);
1512 * We also track th most recent recorded KHZ, write and time to
1513 * allow the matching interval to be extended at each write.
1515 kvm->arch.last_tsc_nsec = ns;
1516 kvm->arch.last_tsc_write = data;
1517 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1519 vcpu->arch.last_guest_tsc = data;
1521 /* Keep track of which generation this VCPU has synchronized to */
1522 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1523 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1524 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1526 if (guest_cpuid_has_tsc_adjust(vcpu) && !msr->host_initiated)
1527 update_ia32_tsc_adjust_msr(vcpu, offset);
1528 kvm_x86_ops->write_tsc_offset(vcpu, offset);
1529 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1531 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1533 kvm->arch.nr_vcpus_matched_tsc = 0;
1534 } else if (!already_matched) {
1535 kvm->arch.nr_vcpus_matched_tsc++;
1538 kvm_track_tsc_matching(vcpu);
1539 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1542 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1544 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
1547 kvm_x86_ops->adjust_tsc_offset_guest(vcpu, adjustment);
1550 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
1552 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
1553 WARN_ON(adjustment < 0);
1554 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
1555 kvm_x86_ops->adjust_tsc_offset_guest(vcpu, adjustment);
1558 #ifdef CONFIG_X86_64
1560 static cycle_t read_tsc(void)
1562 cycle_t ret = (cycle_t)rdtsc_ordered();
1563 u64 last = pvclock_gtod_data.clock.cycle_last;
1565 if (likely(ret >= last))
1569 * GCC likes to generate cmov here, but this branch is extremely
1570 * predictable (it's just a funciton of time and the likely is
1571 * very likely) and there's a data dependence, so force GCC
1572 * to generate a branch instead. I don't barrier() because
1573 * we don't actually need a barrier, and if this function
1574 * ever gets inlined it will generate worse code.
1580 static inline u64 vgettsc(cycle_t *cycle_now)
1583 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1585 *cycle_now = read_tsc();
1587 v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
1588 return v * gtod->clock.mult;
1591 static int do_monotonic_boot(s64 *t, cycle_t *cycle_now)
1593 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1599 seq = read_seqcount_begin(>od->seq);
1600 mode = gtod->clock.vclock_mode;
1601 ns = gtod->nsec_base;
1602 ns += vgettsc(cycle_now);
1603 ns >>= gtod->clock.shift;
1604 ns += gtod->boot_ns;
1605 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
1611 /* returns true if host is using tsc clocksource */
1612 static bool kvm_get_time_and_clockread(s64 *kernel_ns, cycle_t *cycle_now)
1614 /* checked again under seqlock below */
1615 if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
1618 return do_monotonic_boot(kernel_ns, cycle_now) == VCLOCK_TSC;
1624 * Assuming a stable TSC across physical CPUS, and a stable TSC
1625 * across virtual CPUs, the following condition is possible.
1626 * Each numbered line represents an event visible to both
1627 * CPUs at the next numbered event.
1629 * "timespecX" represents host monotonic time. "tscX" represents
1632 * VCPU0 on CPU0 | VCPU1 on CPU1
1634 * 1. read timespec0,tsc0
1635 * 2. | timespec1 = timespec0 + N
1637 * 3. transition to guest | transition to guest
1638 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1639 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
1640 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1642 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1645 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1647 * - 0 < N - M => M < N
1649 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1650 * always the case (the difference between two distinct xtime instances
1651 * might be smaller then the difference between corresponding TSC reads,
1652 * when updating guest vcpus pvclock areas).
1654 * To avoid that problem, do not allow visibility of distinct
1655 * system_timestamp/tsc_timestamp values simultaneously: use a master
1656 * copy of host monotonic time values. Update that master copy
1659 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1663 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1665 #ifdef CONFIG_X86_64
1666 struct kvm_arch *ka = &kvm->arch;
1668 bool host_tsc_clocksource, vcpus_matched;
1670 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1671 atomic_read(&kvm->online_vcpus));
1674 * If the host uses TSC clock, then passthrough TSC as stable
1677 host_tsc_clocksource = kvm_get_time_and_clockread(
1678 &ka->master_kernel_ns,
1679 &ka->master_cycle_now);
1681 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
1682 && !backwards_tsc_observed
1683 && !ka->boot_vcpu_runs_old_kvmclock;
1685 if (ka->use_master_clock)
1686 atomic_set(&kvm_guest_has_master_clock, 1);
1688 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1689 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1694 static void kvm_gen_update_masterclock(struct kvm *kvm)
1696 #ifdef CONFIG_X86_64
1698 struct kvm_vcpu *vcpu;
1699 struct kvm_arch *ka = &kvm->arch;
1701 spin_lock(&ka->pvclock_gtod_sync_lock);
1702 kvm_make_mclock_inprogress_request(kvm);
1703 /* no guest entries from this point */
1704 pvclock_update_vm_gtod_copy(kvm);
1706 kvm_for_each_vcpu(i, vcpu, kvm)
1707 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1709 /* guest entries allowed */
1710 kvm_for_each_vcpu(i, vcpu, kvm)
1711 clear_bit(KVM_REQ_MCLOCK_INPROGRESS, &vcpu->requests);
1713 spin_unlock(&ka->pvclock_gtod_sync_lock);
1717 static int kvm_guest_time_update(struct kvm_vcpu *v)
1719 unsigned long flags, this_tsc_khz, tgt_tsc_khz;
1720 struct kvm_vcpu_arch *vcpu = &v->arch;
1721 struct kvm_arch *ka = &v->kvm->arch;
1723 u64 tsc_timestamp, host_tsc;
1724 struct pvclock_vcpu_time_info guest_hv_clock;
1726 bool use_master_clock;
1732 * If the host uses TSC clock, then passthrough TSC as stable
1735 spin_lock(&ka->pvclock_gtod_sync_lock);
1736 use_master_clock = ka->use_master_clock;
1737 if (use_master_clock) {
1738 host_tsc = ka->master_cycle_now;
1739 kernel_ns = ka->master_kernel_ns;
1741 spin_unlock(&ka->pvclock_gtod_sync_lock);
1743 /* Keep irq disabled to prevent changes to the clock */
1744 local_irq_save(flags);
1745 this_tsc_khz = __this_cpu_read(cpu_tsc_khz);
1746 if (unlikely(this_tsc_khz == 0)) {
1747 local_irq_restore(flags);
1748 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1751 if (!use_master_clock) {
1753 kernel_ns = get_kernel_ns();
1756 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
1759 * We may have to catch up the TSC to match elapsed wall clock
1760 * time for two reasons, even if kvmclock is used.
1761 * 1) CPU could have been running below the maximum TSC rate
1762 * 2) Broken TSC compensation resets the base at each VCPU
1763 * entry to avoid unknown leaps of TSC even when running
1764 * again on the same CPU. This may cause apparent elapsed
1765 * time to disappear, and the guest to stand still or run
1768 if (vcpu->tsc_catchup) {
1769 u64 tsc = compute_guest_tsc(v, kernel_ns);
1770 if (tsc > tsc_timestamp) {
1771 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
1772 tsc_timestamp = tsc;
1776 local_irq_restore(flags);
1778 if (!vcpu->pv_time_enabled)
1781 if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
1782 tgt_tsc_khz = kvm_has_tsc_control ?
1783 vcpu->virtual_tsc_khz : this_tsc_khz;
1784 kvm_get_time_scale(NSEC_PER_SEC / 1000, tgt_tsc_khz,
1785 &vcpu->hv_clock.tsc_shift,
1786 &vcpu->hv_clock.tsc_to_system_mul);
1787 vcpu->hw_tsc_khz = this_tsc_khz;
1790 /* With all the info we got, fill in the values */
1791 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1792 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1793 vcpu->last_guest_tsc = tsc_timestamp;
1795 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
1796 &guest_hv_clock, sizeof(guest_hv_clock))))
1799 /* This VCPU is paused, but it's legal for a guest to read another
1800 * VCPU's kvmclock, so we really have to follow the specification where
1801 * it says that version is odd if data is being modified, and even after
1804 * Version field updates must be kept separate. This is because
1805 * kvm_write_guest_cached might use a "rep movs" instruction, and
1806 * writes within a string instruction are weakly ordered. So there
1807 * are three writes overall.
1809 * As a small optimization, only write the version field in the first
1810 * and third write. The vcpu->pv_time cache is still valid, because the
1811 * version field is the first in the struct.
1813 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
1815 if (guest_hv_clock.version & 1)
1816 ++guest_hv_clock.version; /* first time write, random junk */
1818 vcpu->hv_clock.version = guest_hv_clock.version + 1;
1819 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1821 sizeof(vcpu->hv_clock.version));
1825 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
1826 pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
1828 if (vcpu->pvclock_set_guest_stopped_request) {
1829 pvclock_flags |= PVCLOCK_GUEST_STOPPED;
1830 vcpu->pvclock_set_guest_stopped_request = false;
1833 /* If the host uses TSC clocksource, then it is stable */
1834 if (use_master_clock)
1835 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
1837 vcpu->hv_clock.flags = pvclock_flags;
1839 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
1841 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1843 sizeof(vcpu->hv_clock));
1847 vcpu->hv_clock.version++;
1848 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1850 sizeof(vcpu->hv_clock.version));
1855 * kvmclock updates which are isolated to a given vcpu, such as
1856 * vcpu->cpu migration, should not allow system_timestamp from
1857 * the rest of the vcpus to remain static. Otherwise ntp frequency
1858 * correction applies to one vcpu's system_timestamp but not
1861 * So in those cases, request a kvmclock update for all vcpus.
1862 * We need to rate-limit these requests though, as they can
1863 * considerably slow guests that have a large number of vcpus.
1864 * The time for a remote vcpu to update its kvmclock is bound
1865 * by the delay we use to rate-limit the updates.
1868 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
1870 static void kvmclock_update_fn(struct work_struct *work)
1873 struct delayed_work *dwork = to_delayed_work(work);
1874 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
1875 kvmclock_update_work);
1876 struct kvm *kvm = container_of(ka, struct kvm, arch);
1877 struct kvm_vcpu *vcpu;
1879 kvm_for_each_vcpu(i, vcpu, kvm) {
1880 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1881 kvm_vcpu_kick(vcpu);
1885 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
1887 struct kvm *kvm = v->kvm;
1889 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1890 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
1891 KVMCLOCK_UPDATE_DELAY);
1894 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
1896 static void kvmclock_sync_fn(struct work_struct *work)
1898 struct delayed_work *dwork = to_delayed_work(work);
1899 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
1900 kvmclock_sync_work);
1901 struct kvm *kvm = container_of(ka, struct kvm, arch);
1903 if (!kvmclock_periodic_sync)
1906 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
1907 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
1908 KVMCLOCK_SYNC_PERIOD);
1911 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1913 u64 mcg_cap = vcpu->arch.mcg_cap;
1914 unsigned bank_num = mcg_cap & 0xff;
1917 case MSR_IA32_MCG_STATUS:
1918 vcpu->arch.mcg_status = data;
1920 case MSR_IA32_MCG_CTL:
1921 if (!(mcg_cap & MCG_CTL_P))
1923 if (data != 0 && data != ~(u64)0)
1925 vcpu->arch.mcg_ctl = data;
1928 if (msr >= MSR_IA32_MC0_CTL &&
1929 msr < MSR_IA32_MCx_CTL(bank_num)) {
1930 u32 offset = msr - MSR_IA32_MC0_CTL;
1931 /* only 0 or all 1s can be written to IA32_MCi_CTL
1932 * some Linux kernels though clear bit 10 in bank 4 to
1933 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
1934 * this to avoid an uncatched #GP in the guest
1936 if ((offset & 0x3) == 0 &&
1937 data != 0 && (data | (1 << 10)) != ~(u64)0)
1939 vcpu->arch.mce_banks[offset] = data;
1947 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
1949 struct kvm *kvm = vcpu->kvm;
1950 int lm = is_long_mode(vcpu);
1951 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
1952 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
1953 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
1954 : kvm->arch.xen_hvm_config.blob_size_32;
1955 u32 page_num = data & ~PAGE_MASK;
1956 u64 page_addr = data & PAGE_MASK;
1961 if (page_num >= blob_size)
1964 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
1969 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
1978 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
1980 gpa_t gpa = data & ~0x3f;
1982 /* Bits 2:5 are reserved, Should be zero */
1986 vcpu->arch.apf.msr_val = data;
1988 if (!(data & KVM_ASYNC_PF_ENABLED)) {
1989 kvm_clear_async_pf_completion_queue(vcpu);
1990 kvm_async_pf_hash_reset(vcpu);
1994 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
1998 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
1999 kvm_async_pf_wakeup_all(vcpu);
2003 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2005 vcpu->arch.pv_time_enabled = false;
2008 static void accumulate_steal_time(struct kvm_vcpu *vcpu)
2012 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2015 delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
2016 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2017 vcpu->arch.st.accum_steal = delta;
2020 static void record_steal_time(struct kvm_vcpu *vcpu)
2022 accumulate_steal_time(vcpu);
2024 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2027 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2028 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
2031 vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
2032 vcpu->arch.st.steal.version += 2;
2033 vcpu->arch.st.accum_steal = 0;
2035 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2036 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2039 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2042 u32 msr = msr_info->index;
2043 u64 data = msr_info->data;
2046 case MSR_AMD64_NB_CFG:
2047 case MSR_IA32_UCODE_REV:
2048 case MSR_IA32_UCODE_WRITE:
2049 case MSR_VM_HSAVE_PA:
2050 case MSR_AMD64_PATCH_LOADER:
2051 case MSR_AMD64_BU_CFG2:
2055 return set_efer(vcpu, data);
2057 data &= ~(u64)0x40; /* ignore flush filter disable */
2058 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2059 data &= ~(u64)0x8; /* ignore TLB cache disable */
2060 data &= ~(u64)0x40000; /* ignore Mc status write enable */
2062 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2067 case MSR_FAM10H_MMIO_CONF_BASE:
2069 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2074 case MSR_IA32_DEBUGCTLMSR:
2076 /* We support the non-activated case already */
2078 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2079 /* Values other than LBR and BTF are vendor-specific,
2080 thus reserved and should throw a #GP */
2083 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2086 case 0x200 ... 0x2ff:
2087 return kvm_mtrr_set_msr(vcpu, msr, data);
2088 case MSR_IA32_APICBASE:
2089 return kvm_set_apic_base(vcpu, msr_info);
2090 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2091 return kvm_x2apic_msr_write(vcpu, msr, data);
2092 case MSR_IA32_TSCDEADLINE:
2093 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2095 case MSR_IA32_TSC_ADJUST:
2096 if (guest_cpuid_has_tsc_adjust(vcpu)) {
2097 if (!msr_info->host_initiated) {
2098 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2099 adjust_tsc_offset_guest(vcpu, adj);
2101 vcpu->arch.ia32_tsc_adjust_msr = data;
2104 case MSR_IA32_MISC_ENABLE:
2105 vcpu->arch.ia32_misc_enable_msr = data;
2107 case MSR_IA32_SMBASE:
2108 if (!msr_info->host_initiated)
2110 vcpu->arch.smbase = data;
2112 case MSR_KVM_WALL_CLOCK_NEW:
2113 case MSR_KVM_WALL_CLOCK:
2114 vcpu->kvm->arch.wall_clock = data;
2115 kvm_write_wall_clock(vcpu->kvm, data);
2117 case MSR_KVM_SYSTEM_TIME_NEW:
2118 case MSR_KVM_SYSTEM_TIME: {
2120 struct kvm_arch *ka = &vcpu->kvm->arch;
2122 kvmclock_reset(vcpu);
2124 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2125 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2127 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2128 set_bit(KVM_REQ_MASTERCLOCK_UPDATE,
2131 ka->boot_vcpu_runs_old_kvmclock = tmp;
2134 vcpu->arch.time = data;
2135 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2137 /* we verify if the enable bit is set... */
2141 gpa_offset = data & ~(PAGE_MASK | 1);
2143 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2144 &vcpu->arch.pv_time, data & ~1ULL,
2145 sizeof(struct pvclock_vcpu_time_info)))
2146 vcpu->arch.pv_time_enabled = false;
2148 vcpu->arch.pv_time_enabled = true;
2152 case MSR_KVM_ASYNC_PF_EN:
2153 if (kvm_pv_enable_async_pf(vcpu, data))
2156 case MSR_KVM_STEAL_TIME:
2158 if (unlikely(!sched_info_on()))
2161 if (data & KVM_STEAL_RESERVED_MASK)
2164 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2165 data & KVM_STEAL_VALID_BITS,
2166 sizeof(struct kvm_steal_time)))
2169 vcpu->arch.st.msr_val = data;
2171 if (!(data & KVM_MSR_ENABLED))
2174 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2177 case MSR_KVM_PV_EOI_EN:
2178 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2182 case MSR_IA32_MCG_CTL:
2183 case MSR_IA32_MCG_STATUS:
2184 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2185 return set_msr_mce(vcpu, msr, data);
2187 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2188 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2189 pr = true; /* fall through */
2190 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2191 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2192 if (kvm_pmu_is_valid_msr(vcpu, msr))
2193 return kvm_pmu_set_msr(vcpu, msr_info);
2195 if (pr || data != 0)
2196 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2197 "0x%x data 0x%llx\n", msr, data);
2199 case MSR_K7_CLK_CTL:
2201 * Ignore all writes to this no longer documented MSR.
2202 * Writes are only relevant for old K7 processors,
2203 * all pre-dating SVM, but a recommended workaround from
2204 * AMD for these chips. It is possible to specify the
2205 * affected processor models on the command line, hence
2206 * the need to ignore the workaround.
2209 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2210 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2211 case HV_X64_MSR_CRASH_CTL:
2212 return kvm_hv_set_msr_common(vcpu, msr, data,
2213 msr_info->host_initiated);
2214 case MSR_IA32_BBL_CR_CTL3:
2215 /* Drop writes to this legacy MSR -- see rdmsr
2216 * counterpart for further detail.
2218 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
2220 case MSR_AMD64_OSVW_ID_LENGTH:
2221 if (!guest_cpuid_has_osvw(vcpu))
2223 vcpu->arch.osvw.length = data;
2225 case MSR_AMD64_OSVW_STATUS:
2226 if (!guest_cpuid_has_osvw(vcpu))
2228 vcpu->arch.osvw.status = data;
2231 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2232 return xen_hvm_config(vcpu, data);
2233 if (kvm_pmu_is_valid_msr(vcpu, msr))
2234 return kvm_pmu_set_msr(vcpu, msr_info);
2236 vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
2240 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
2247 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2251 * Reads an msr value (of 'msr_index') into 'pdata'.
2252 * Returns 0 on success, non-0 otherwise.
2253 * Assumes vcpu_load() was already called.
2255 int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2257 return kvm_x86_ops->get_msr(vcpu, msr);
2259 EXPORT_SYMBOL_GPL(kvm_get_msr);
2261 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2264 u64 mcg_cap = vcpu->arch.mcg_cap;
2265 unsigned bank_num = mcg_cap & 0xff;
2268 case MSR_IA32_P5_MC_ADDR:
2269 case MSR_IA32_P5_MC_TYPE:
2272 case MSR_IA32_MCG_CAP:
2273 data = vcpu->arch.mcg_cap;
2275 case MSR_IA32_MCG_CTL:
2276 if (!(mcg_cap & MCG_CTL_P))
2278 data = vcpu->arch.mcg_ctl;
2280 case MSR_IA32_MCG_STATUS:
2281 data = vcpu->arch.mcg_status;
2284 if (msr >= MSR_IA32_MC0_CTL &&
2285 msr < MSR_IA32_MCx_CTL(bank_num)) {
2286 u32 offset = msr - MSR_IA32_MC0_CTL;
2287 data = vcpu->arch.mce_banks[offset];
2296 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2298 switch (msr_info->index) {
2299 case MSR_IA32_PLATFORM_ID:
2300 case MSR_IA32_EBL_CR_POWERON:
2301 case MSR_IA32_DEBUGCTLMSR:
2302 case MSR_IA32_LASTBRANCHFROMIP:
2303 case MSR_IA32_LASTBRANCHTOIP:
2304 case MSR_IA32_LASTINTFROMIP:
2305 case MSR_IA32_LASTINTTOIP:
2307 case MSR_K8_TSEG_ADDR:
2308 case MSR_K8_TSEG_MASK:
2310 case MSR_VM_HSAVE_PA:
2311 case MSR_K8_INT_PENDING_MSG:
2312 case MSR_AMD64_NB_CFG:
2313 case MSR_FAM10H_MMIO_CONF_BASE:
2314 case MSR_AMD64_BU_CFG2:
2317 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2318 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2319 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2320 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2321 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2322 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2325 case MSR_IA32_UCODE_REV:
2326 msr_info->data = 0x100000000ULL;
2329 case 0x200 ... 0x2ff:
2330 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2331 case 0xcd: /* fsb frequency */
2335 * MSR_EBC_FREQUENCY_ID
2336 * Conservative value valid for even the basic CPU models.
2337 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2338 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2339 * and 266MHz for model 3, or 4. Set Core Clock
2340 * Frequency to System Bus Frequency Ratio to 1 (bits
2341 * 31:24) even though these are only valid for CPU
2342 * models > 2, however guests may end up dividing or
2343 * multiplying by zero otherwise.
2345 case MSR_EBC_FREQUENCY_ID:
2346 msr_info->data = 1 << 24;
2348 case MSR_IA32_APICBASE:
2349 msr_info->data = kvm_get_apic_base(vcpu);
2351 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2352 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2354 case MSR_IA32_TSCDEADLINE:
2355 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2357 case MSR_IA32_TSC_ADJUST:
2358 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2360 case MSR_IA32_MISC_ENABLE:
2361 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
2363 case MSR_IA32_SMBASE:
2364 if (!msr_info->host_initiated)
2366 msr_info->data = vcpu->arch.smbase;
2368 case MSR_IA32_PERF_STATUS:
2369 /* TSC increment by tick */
2370 msr_info->data = 1000ULL;
2371 /* CPU multiplier */
2372 msr_info->data |= (((uint64_t)4ULL) << 40);
2375 msr_info->data = vcpu->arch.efer;
2377 case MSR_KVM_WALL_CLOCK:
2378 case MSR_KVM_WALL_CLOCK_NEW:
2379 msr_info->data = vcpu->kvm->arch.wall_clock;
2381 case MSR_KVM_SYSTEM_TIME:
2382 case MSR_KVM_SYSTEM_TIME_NEW:
2383 msr_info->data = vcpu->arch.time;
2385 case MSR_KVM_ASYNC_PF_EN:
2386 msr_info->data = vcpu->arch.apf.msr_val;
2388 case MSR_KVM_STEAL_TIME:
2389 msr_info->data = vcpu->arch.st.msr_val;
2391 case MSR_KVM_PV_EOI_EN:
2392 msr_info->data = vcpu->arch.pv_eoi.msr_val;
2394 case MSR_IA32_P5_MC_ADDR:
2395 case MSR_IA32_P5_MC_TYPE:
2396 case MSR_IA32_MCG_CAP:
2397 case MSR_IA32_MCG_CTL:
2398 case MSR_IA32_MCG_STATUS:
2399 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2400 return get_msr_mce(vcpu, msr_info->index, &msr_info->data);
2401 case MSR_K7_CLK_CTL:
2403 * Provide expected ramp-up count for K7. All other
2404 * are set to zero, indicating minimum divisors for
2407 * This prevents guest kernels on AMD host with CPU
2408 * type 6, model 8 and higher from exploding due to
2409 * the rdmsr failing.
2411 msr_info->data = 0x20000000;
2413 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2414 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2415 case HV_X64_MSR_CRASH_CTL:
2416 return kvm_hv_get_msr_common(vcpu,
2417 msr_info->index, &msr_info->data);
2419 case MSR_IA32_BBL_CR_CTL3:
2420 /* This legacy MSR exists but isn't fully documented in current
2421 * silicon. It is however accessed by winxp in very narrow
2422 * scenarios where it sets bit #19, itself documented as
2423 * a "reserved" bit. Best effort attempt to source coherent
2424 * read data here should the balance of the register be
2425 * interpreted by the guest:
2427 * L2 cache control register 3: 64GB range, 256KB size,
2428 * enabled, latency 0x1, configured
2430 msr_info->data = 0xbe702111;
2432 case MSR_AMD64_OSVW_ID_LENGTH:
2433 if (!guest_cpuid_has_osvw(vcpu))
2435 msr_info->data = vcpu->arch.osvw.length;
2437 case MSR_AMD64_OSVW_STATUS:
2438 if (!guest_cpuid_has_osvw(vcpu))
2440 msr_info->data = vcpu->arch.osvw.status;
2443 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2444 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2446 vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr_info->index);
2449 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr_info->index);
2456 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2459 * Read or write a bunch of msrs. All parameters are kernel addresses.
2461 * @return number of msrs set successfully.
2463 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2464 struct kvm_msr_entry *entries,
2465 int (*do_msr)(struct kvm_vcpu *vcpu,
2466 unsigned index, u64 *data))
2470 idx = srcu_read_lock(&vcpu->kvm->srcu);
2471 for (i = 0; i < msrs->nmsrs; ++i)
2472 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2474 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2480 * Read or write a bunch of msrs. Parameters are user addresses.
2482 * @return number of msrs set successfully.
2484 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2485 int (*do_msr)(struct kvm_vcpu *vcpu,
2486 unsigned index, u64 *data),
2489 struct kvm_msrs msrs;
2490 struct kvm_msr_entry *entries;
2495 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2499 if (msrs.nmsrs >= MAX_IO_MSRS)
2502 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2503 entries = memdup_user(user_msrs->entries, size);
2504 if (IS_ERR(entries)) {
2505 r = PTR_ERR(entries);
2509 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2514 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2525 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2530 case KVM_CAP_IRQCHIP:
2532 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2533 case KVM_CAP_SET_TSS_ADDR:
2534 case KVM_CAP_EXT_CPUID:
2535 case KVM_CAP_EXT_EMUL_CPUID:
2536 case KVM_CAP_CLOCKSOURCE:
2538 case KVM_CAP_NOP_IO_DELAY:
2539 case KVM_CAP_MP_STATE:
2540 case KVM_CAP_SYNC_MMU:
2541 case KVM_CAP_USER_NMI:
2542 case KVM_CAP_REINJECT_CONTROL:
2543 case KVM_CAP_IRQ_INJECT_STATUS:
2544 case KVM_CAP_IOEVENTFD:
2545 case KVM_CAP_IOEVENTFD_NO_LENGTH:
2547 case KVM_CAP_PIT_STATE2:
2548 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2549 case KVM_CAP_XEN_HVM:
2550 case KVM_CAP_ADJUST_CLOCK:
2551 case KVM_CAP_VCPU_EVENTS:
2552 case KVM_CAP_HYPERV:
2553 case KVM_CAP_HYPERV_VAPIC:
2554 case KVM_CAP_HYPERV_SPIN:
2555 case KVM_CAP_PCI_SEGMENT:
2556 case KVM_CAP_DEBUGREGS:
2557 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2559 case KVM_CAP_ASYNC_PF:
2560 case KVM_CAP_GET_TSC_KHZ:
2561 case KVM_CAP_KVMCLOCK_CTRL:
2562 case KVM_CAP_READONLY_MEM:
2563 case KVM_CAP_HYPERV_TIME:
2564 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2565 case KVM_CAP_TSC_DEADLINE_TIMER:
2566 case KVM_CAP_ENABLE_CAP_VM:
2567 case KVM_CAP_DISABLE_QUIRKS:
2568 case KVM_CAP_SET_BOOT_CPU_ID:
2569 case KVM_CAP_SPLIT_IRQCHIP:
2570 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2571 case KVM_CAP_ASSIGN_DEV_IRQ:
2572 case KVM_CAP_PCI_2_3:
2576 case KVM_CAP_X86_SMM:
2577 /* SMBASE is usually relocated above 1M on modern chipsets,
2578 * and SMM handlers might indeed rely on 4G segment limits,
2579 * so do not report SMM to be available if real mode is
2580 * emulated via vm86 mode. Still, do not go to great lengths
2581 * to avoid userspace's usage of the feature, because it is a
2582 * fringe case that is not enabled except via specific settings
2583 * of the module parameters.
2585 r = kvm_x86_ops->cpu_has_high_real_mode_segbase();
2587 case KVM_CAP_COALESCED_MMIO:
2588 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2591 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2593 case KVM_CAP_NR_VCPUS:
2594 r = KVM_SOFT_MAX_VCPUS;
2596 case KVM_CAP_MAX_VCPUS:
2599 case KVM_CAP_NR_MEMSLOTS:
2600 r = KVM_USER_MEM_SLOTS;
2602 case KVM_CAP_PV_MMU: /* obsolete */
2605 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2607 r = iommu_present(&pci_bus_type);
2611 r = KVM_MAX_MCE_BANKS;
2616 case KVM_CAP_TSC_CONTROL:
2617 r = kvm_has_tsc_control;
2627 long kvm_arch_dev_ioctl(struct file *filp,
2628 unsigned int ioctl, unsigned long arg)
2630 void __user *argp = (void __user *)arg;
2634 case KVM_GET_MSR_INDEX_LIST: {
2635 struct kvm_msr_list __user *user_msr_list = argp;
2636 struct kvm_msr_list msr_list;
2640 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2643 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
2644 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2647 if (n < msr_list.nmsrs)
2650 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2651 num_msrs_to_save * sizeof(u32)))
2653 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2655 num_emulated_msrs * sizeof(u32)))
2660 case KVM_GET_SUPPORTED_CPUID:
2661 case KVM_GET_EMULATED_CPUID: {
2662 struct kvm_cpuid2 __user *cpuid_arg = argp;
2663 struct kvm_cpuid2 cpuid;
2666 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2669 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2675 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2680 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2683 mce_cap = KVM_MCE_CAP_SUPPORTED;
2685 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2697 static void wbinvd_ipi(void *garbage)
2702 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2704 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2707 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2709 /* Address WBINVD may be executed by guest */
2710 if (need_emulate_wbinvd(vcpu)) {
2711 if (kvm_x86_ops->has_wbinvd_exit())
2712 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2713 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2714 smp_call_function_single(vcpu->cpu,
2715 wbinvd_ipi, NULL, 1);
2718 kvm_x86_ops->vcpu_load(vcpu, cpu);
2720 /* Apply any externally detected TSC adjustments (due to suspend) */
2721 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2722 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2723 vcpu->arch.tsc_offset_adjustment = 0;
2724 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2727 if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2728 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2729 rdtsc() - vcpu->arch.last_host_tsc;
2731 mark_tsc_unstable("KVM discovered backwards TSC");
2732 if (check_tsc_unstable()) {
2733 u64 offset = kvm_compute_tsc_offset(vcpu,
2734 vcpu->arch.last_guest_tsc);
2735 kvm_x86_ops->write_tsc_offset(vcpu, offset);
2736 vcpu->arch.tsc_catchup = 1;
2739 * On a host with synchronized TSC, there is no need to update
2740 * kvmclock on vcpu->cpu migration
2742 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
2743 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2744 if (vcpu->cpu != cpu)
2745 kvm_migrate_timers(vcpu);
2749 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2752 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2754 kvm_x86_ops->vcpu_put(vcpu);
2755 kvm_put_guest_fpu(vcpu);
2756 vcpu->arch.last_host_tsc = rdtsc();
2759 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2760 struct kvm_lapic_state *s)
2762 kvm_x86_ops->sync_pir_to_irr(vcpu);
2763 memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2768 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2769 struct kvm_lapic_state *s)
2771 kvm_apic_post_state_restore(vcpu, s);
2772 update_cr8_intercept(vcpu);
2777 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
2779 return (!lapic_in_kernel(vcpu) ||
2780 kvm_apic_accept_pic_intr(vcpu));
2784 * if userspace requested an interrupt window, check that the
2785 * interrupt window is open.
2787 * No need to exit to userspace if we already have an interrupt queued.
2789 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
2791 return kvm_arch_interrupt_allowed(vcpu) &&
2792 !kvm_cpu_has_interrupt(vcpu) &&
2793 !kvm_event_needs_reinjection(vcpu) &&
2794 kvm_cpu_accept_dm_intr(vcpu);
2797 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2798 struct kvm_interrupt *irq)
2800 if (irq->irq >= KVM_NR_INTERRUPTS)
2803 if (!irqchip_in_kernel(vcpu->kvm)) {
2804 kvm_queue_interrupt(vcpu, irq->irq, false);
2805 kvm_make_request(KVM_REQ_EVENT, vcpu);
2810 * With in-kernel LAPIC, we only use this to inject EXTINT, so
2811 * fail for in-kernel 8259.
2813 if (pic_in_kernel(vcpu->kvm))
2816 if (vcpu->arch.pending_external_vector != -1)
2819 vcpu->arch.pending_external_vector = irq->irq;
2820 kvm_make_request(KVM_REQ_EVENT, vcpu);
2824 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2826 kvm_inject_nmi(vcpu);
2831 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
2833 kvm_make_request(KVM_REQ_SMI, vcpu);
2838 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2839 struct kvm_tpr_access_ctl *tac)
2843 vcpu->arch.tpr_access_reporting = !!tac->enabled;
2847 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2851 unsigned bank_num = mcg_cap & 0xff, bank;
2854 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2856 if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2859 vcpu->arch.mcg_cap = mcg_cap;
2860 /* Init IA32_MCG_CTL to all 1s */
2861 if (mcg_cap & MCG_CTL_P)
2862 vcpu->arch.mcg_ctl = ~(u64)0;
2863 /* Init IA32_MCi_CTL to all 1s */
2864 for (bank = 0; bank < bank_num; bank++)
2865 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2870 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2871 struct kvm_x86_mce *mce)
2873 u64 mcg_cap = vcpu->arch.mcg_cap;
2874 unsigned bank_num = mcg_cap & 0xff;
2875 u64 *banks = vcpu->arch.mce_banks;
2877 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2880 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2881 * reporting is disabled
2883 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2884 vcpu->arch.mcg_ctl != ~(u64)0)
2886 banks += 4 * mce->bank;
2888 * if IA32_MCi_CTL is not all 1s, the uncorrected error
2889 * reporting is disabled for the bank
2891 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2893 if (mce->status & MCI_STATUS_UC) {
2894 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2895 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2896 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2899 if (banks[1] & MCI_STATUS_VAL)
2900 mce->status |= MCI_STATUS_OVER;
2901 banks[2] = mce->addr;
2902 banks[3] = mce->misc;
2903 vcpu->arch.mcg_status = mce->mcg_status;
2904 banks[1] = mce->status;
2905 kvm_queue_exception(vcpu, MC_VECTOR);
2906 } else if (!(banks[1] & MCI_STATUS_VAL)
2907 || !(banks[1] & MCI_STATUS_UC)) {
2908 if (banks[1] & MCI_STATUS_VAL)
2909 mce->status |= MCI_STATUS_OVER;
2910 banks[2] = mce->addr;
2911 banks[3] = mce->misc;
2912 banks[1] = mce->status;
2914 banks[1] |= MCI_STATUS_OVER;
2918 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2919 struct kvm_vcpu_events *events)
2922 events->exception.injected =
2923 vcpu->arch.exception.pending &&
2924 !kvm_exception_is_soft(vcpu->arch.exception.nr);
2925 events->exception.nr = vcpu->arch.exception.nr;
2926 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2927 events->exception.pad = 0;
2928 events->exception.error_code = vcpu->arch.exception.error_code;
2930 events->interrupt.injected =
2931 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
2932 events->interrupt.nr = vcpu->arch.interrupt.nr;
2933 events->interrupt.soft = 0;
2934 events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
2936 events->nmi.injected = vcpu->arch.nmi_injected;
2937 events->nmi.pending = vcpu->arch.nmi_pending != 0;
2938 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
2939 events->nmi.pad = 0;
2941 events->sipi_vector = 0; /* never valid when reporting to user space */
2943 events->smi.smm = is_smm(vcpu);
2944 events->smi.pending = vcpu->arch.smi_pending;
2945 events->smi.smm_inside_nmi =
2946 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
2947 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
2949 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
2950 | KVM_VCPUEVENT_VALID_SHADOW
2951 | KVM_VCPUEVENT_VALID_SMM);
2952 memset(&events->reserved, 0, sizeof(events->reserved));
2955 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
2957 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
2958 struct kvm_vcpu_events *events)
2960 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
2961 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2962 | KVM_VCPUEVENT_VALID_SHADOW
2963 | KVM_VCPUEVENT_VALID_SMM))
2966 /* INITs are latched while in SMM */
2967 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
2968 (events->smi.smm || events->smi.pending) &&
2969 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
2973 vcpu->arch.exception.pending = events->exception.injected;
2974 vcpu->arch.exception.nr = events->exception.nr;
2975 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
2976 vcpu->arch.exception.error_code = events->exception.error_code;
2978 vcpu->arch.interrupt.pending = events->interrupt.injected;
2979 vcpu->arch.interrupt.nr = events->interrupt.nr;
2980 vcpu->arch.interrupt.soft = events->interrupt.soft;
2981 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
2982 kvm_x86_ops->set_interrupt_shadow(vcpu,
2983 events->interrupt.shadow);
2985 vcpu->arch.nmi_injected = events->nmi.injected;
2986 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
2987 vcpu->arch.nmi_pending = events->nmi.pending;
2988 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
2990 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
2991 kvm_vcpu_has_lapic(vcpu))
2992 vcpu->arch.apic->sipi_vector = events->sipi_vector;
2994 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
2995 u32 hflags = vcpu->arch.hflags;
2996 if (events->smi.smm)
2997 hflags |= HF_SMM_MASK;
2999 hflags &= ~HF_SMM_MASK;
3000 kvm_set_hflags(vcpu, hflags);
3002 vcpu->arch.smi_pending = events->smi.pending;
3003 if (events->smi.smm_inside_nmi)
3004 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3006 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3007 if (kvm_vcpu_has_lapic(vcpu)) {
3008 if (events->smi.latched_init)
3009 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3011 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3015 kvm_make_request(KVM_REQ_EVENT, vcpu);
3020 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3021 struct kvm_debugregs *dbgregs)
3025 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3026 kvm_get_dr(vcpu, 6, &val);
3028 dbgregs->dr7 = vcpu->arch.dr7;
3030 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3033 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3034 struct kvm_debugregs *dbgregs)
3039 if (dbgregs->dr6 & ~0xffffffffull)
3041 if (dbgregs->dr7 & ~0xffffffffull)
3044 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3045 kvm_update_dr0123(vcpu);
3046 vcpu->arch.dr6 = dbgregs->dr6;
3047 kvm_update_dr6(vcpu);
3048 vcpu->arch.dr7 = dbgregs->dr7;
3049 kvm_update_dr7(vcpu);
3054 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3056 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3058 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3059 u64 xstate_bv = xsave->header.xfeatures;
3063 * Copy legacy XSAVE area, to avoid complications with CPUID
3064 * leaves 0 and 1 in the loop below.
3066 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3069 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3070 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3073 * Copy each region from the possibly compacted offset to the
3074 * non-compacted offset.
3076 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3078 u64 feature = valid & -valid;
3079 int index = fls64(feature) - 1;
3080 void *src = get_xsave_addr(xsave, feature);
3083 u32 size, offset, ecx, edx;
3084 cpuid_count(XSTATE_CPUID, index,
3085 &size, &offset, &ecx, &edx);
3086 memcpy(dest + offset, src, size);
3093 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3095 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3096 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3100 * Copy legacy XSAVE area, to avoid complications with CPUID
3101 * leaves 0 and 1 in the loop below.
3103 memcpy(xsave, src, XSAVE_HDR_OFFSET);
3105 /* Set XSTATE_BV and possibly XCOMP_BV. */
3106 xsave->header.xfeatures = xstate_bv;
3108 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3111 * Copy each region from the non-compacted offset to the
3112 * possibly compacted offset.
3114 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3116 u64 feature = valid & -valid;
3117 int index = fls64(feature) - 1;
3118 void *dest = get_xsave_addr(xsave, feature);
3121 u32 size, offset, ecx, edx;
3122 cpuid_count(XSTATE_CPUID, index,
3123 &size, &offset, &ecx, &edx);
3124 memcpy(dest, src + offset, size);
3131 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3132 struct kvm_xsave *guest_xsave)
3134 if (cpu_has_xsave) {
3135 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
3136 fill_xsave((u8 *) guest_xsave->region, vcpu);
3138 memcpy(guest_xsave->region,
3139 &vcpu->arch.guest_fpu.state.fxsave,
3140 sizeof(struct fxregs_state));
3141 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3142 XFEATURE_MASK_FPSSE;
3146 #define XSAVE_MXCSR_OFFSET 24
3148 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3149 struct kvm_xsave *guest_xsave)
3152 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3153 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
3155 if (cpu_has_xsave) {
3157 * Here we allow setting states that are not present in
3158 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
3159 * with old userspace.
3161 if (xstate_bv & ~kvm_supported_xcr0() ||
3162 mxcsr & ~mxcsr_feature_mask)
3164 load_xsave(vcpu, (u8 *)guest_xsave->region);
3166 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
3167 mxcsr & ~mxcsr_feature_mask)
3169 memcpy(&vcpu->arch.guest_fpu.state.fxsave,
3170 guest_xsave->region, sizeof(struct fxregs_state));
3175 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3176 struct kvm_xcrs *guest_xcrs)
3178 if (!cpu_has_xsave) {
3179 guest_xcrs->nr_xcrs = 0;
3183 guest_xcrs->nr_xcrs = 1;
3184 guest_xcrs->flags = 0;
3185 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3186 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3189 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3190 struct kvm_xcrs *guest_xcrs)
3197 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3200 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3201 /* Only support XCR0 currently */
3202 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3203 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3204 guest_xcrs->xcrs[i].value);
3213 * kvm_set_guest_paused() indicates to the guest kernel that it has been
3214 * stopped by the hypervisor. This function will be called from the host only.
3215 * EINVAL is returned when the host attempts to set the flag for a guest that
3216 * does not support pv clocks.
3218 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3220 if (!vcpu->arch.pv_time_enabled)
3222 vcpu->arch.pvclock_set_guest_stopped_request = true;
3223 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3227 long kvm_arch_vcpu_ioctl(struct file *filp,
3228 unsigned int ioctl, unsigned long arg)
3230 struct kvm_vcpu *vcpu = filp->private_data;
3231 void __user *argp = (void __user *)arg;
3234 struct kvm_lapic_state *lapic;
3235 struct kvm_xsave *xsave;
3236 struct kvm_xcrs *xcrs;
3242 case KVM_GET_LAPIC: {
3244 if (!vcpu->arch.apic)
3246 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3251 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3255 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3260 case KVM_SET_LAPIC: {
3262 if (!vcpu->arch.apic)
3264 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3265 if (IS_ERR(u.lapic))
3266 return PTR_ERR(u.lapic);
3268 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3271 case KVM_INTERRUPT: {
3272 struct kvm_interrupt irq;
3275 if (copy_from_user(&irq, argp, sizeof irq))
3277 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3281 r = kvm_vcpu_ioctl_nmi(vcpu);
3285 r = kvm_vcpu_ioctl_smi(vcpu);
3288 case KVM_SET_CPUID: {
3289 struct kvm_cpuid __user *cpuid_arg = argp;
3290 struct kvm_cpuid cpuid;
3293 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3295 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3298 case KVM_SET_CPUID2: {
3299 struct kvm_cpuid2 __user *cpuid_arg = argp;
3300 struct kvm_cpuid2 cpuid;
3303 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3305 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3306 cpuid_arg->entries);
3309 case KVM_GET_CPUID2: {
3310 struct kvm_cpuid2 __user *cpuid_arg = argp;
3311 struct kvm_cpuid2 cpuid;
3314 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3316 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3317 cpuid_arg->entries);
3321 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3327 r = msr_io(vcpu, argp, do_get_msr, 1);
3330 r = msr_io(vcpu, argp, do_set_msr, 0);
3332 case KVM_TPR_ACCESS_REPORTING: {
3333 struct kvm_tpr_access_ctl tac;
3336 if (copy_from_user(&tac, argp, sizeof tac))
3338 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3342 if (copy_to_user(argp, &tac, sizeof tac))
3347 case KVM_SET_VAPIC_ADDR: {
3348 struct kvm_vapic_addr va;
3352 if (!lapic_in_kernel(vcpu))
3355 if (copy_from_user(&va, argp, sizeof va))
3357 idx = srcu_read_lock(&vcpu->kvm->srcu);
3358 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3359 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3362 case KVM_X86_SETUP_MCE: {
3366 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3368 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3371 case KVM_X86_SET_MCE: {
3372 struct kvm_x86_mce mce;
3375 if (copy_from_user(&mce, argp, sizeof mce))
3377 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3380 case KVM_GET_VCPU_EVENTS: {
3381 struct kvm_vcpu_events events;
3383 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3386 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3391 case KVM_SET_VCPU_EVENTS: {
3392 struct kvm_vcpu_events events;
3395 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3398 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3401 case KVM_GET_DEBUGREGS: {
3402 struct kvm_debugregs dbgregs;
3404 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3407 if (copy_to_user(argp, &dbgregs,
3408 sizeof(struct kvm_debugregs)))
3413 case KVM_SET_DEBUGREGS: {
3414 struct kvm_debugregs dbgregs;
3417 if (copy_from_user(&dbgregs, argp,
3418 sizeof(struct kvm_debugregs)))
3421 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3424 case KVM_GET_XSAVE: {
3425 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3430 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3433 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3438 case KVM_SET_XSAVE: {
3439 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3440 if (IS_ERR(u.xsave))
3441 return PTR_ERR(u.xsave);
3443 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3446 case KVM_GET_XCRS: {
3447 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3452 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3455 if (copy_to_user(argp, u.xcrs,
3456 sizeof(struct kvm_xcrs)))
3461 case KVM_SET_XCRS: {
3462 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3464 return PTR_ERR(u.xcrs);
3466 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3469 case KVM_SET_TSC_KHZ: {
3473 user_tsc_khz = (u32)arg;
3475 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3478 if (user_tsc_khz == 0)
3479 user_tsc_khz = tsc_khz;
3481 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
3486 case KVM_GET_TSC_KHZ: {
3487 r = vcpu->arch.virtual_tsc_khz;
3490 case KVM_KVMCLOCK_CTRL: {
3491 r = kvm_set_guest_paused(vcpu);
3502 int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3504 return VM_FAULT_SIGBUS;
3507 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3511 if (addr > (unsigned int)(-3 * PAGE_SIZE))
3513 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3517 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3520 kvm->arch.ept_identity_map_addr = ident_addr;
3524 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3525 u32 kvm_nr_mmu_pages)
3527 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3530 mutex_lock(&kvm->slots_lock);
3532 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3533 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3535 mutex_unlock(&kvm->slots_lock);
3539 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3541 return kvm->arch.n_max_mmu_pages;
3544 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3549 switch (chip->chip_id) {
3550 case KVM_IRQCHIP_PIC_MASTER:
3551 memcpy(&chip->chip.pic,
3552 &pic_irqchip(kvm)->pics[0],
3553 sizeof(struct kvm_pic_state));
3555 case KVM_IRQCHIP_PIC_SLAVE:
3556 memcpy(&chip->chip.pic,
3557 &pic_irqchip(kvm)->pics[1],
3558 sizeof(struct kvm_pic_state));
3560 case KVM_IRQCHIP_IOAPIC:
3561 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3570 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3575 switch (chip->chip_id) {
3576 case KVM_IRQCHIP_PIC_MASTER:
3577 spin_lock(&pic_irqchip(kvm)->lock);
3578 memcpy(&pic_irqchip(kvm)->pics[0],
3580 sizeof(struct kvm_pic_state));
3581 spin_unlock(&pic_irqchip(kvm)->lock);
3583 case KVM_IRQCHIP_PIC_SLAVE:
3584 spin_lock(&pic_irqchip(kvm)->lock);
3585 memcpy(&pic_irqchip(kvm)->pics[1],
3587 sizeof(struct kvm_pic_state));
3588 spin_unlock(&pic_irqchip(kvm)->lock);
3590 case KVM_IRQCHIP_IOAPIC:
3591 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3597 kvm_pic_update_irq(pic_irqchip(kvm));
3601 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3603 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3604 memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
3605 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3609 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3612 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3613 memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
3614 for (i = 0; i < 3; i++)
3615 kvm_pit_load_count(kvm, i, ps->channels[i].count, 0);
3616 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3620 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3622 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3623 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3624 sizeof(ps->channels));
3625 ps->flags = kvm->arch.vpit->pit_state.flags;
3626 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3627 memset(&ps->reserved, 0, sizeof(ps->reserved));
3631 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3635 u32 prev_legacy, cur_legacy;
3636 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3637 prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3638 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3639 if (!prev_legacy && cur_legacy)
3641 memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
3642 sizeof(kvm->arch.vpit->pit_state.channels));
3643 kvm->arch.vpit->pit_state.flags = ps->flags;
3644 for (i = 0; i < 3; i++)
3645 kvm_pit_load_count(kvm, i, kvm->arch.vpit->pit_state.channels[i].count,
3647 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3651 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3652 struct kvm_reinject_control *control)
3654 if (!kvm->arch.vpit)
3656 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3657 kvm->arch.vpit->pit_state.reinject = control->pit_reinject;
3658 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3663 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
3664 * @kvm: kvm instance
3665 * @log: slot id and address to which we copy the log
3667 * Steps 1-4 below provide general overview of dirty page logging. See
3668 * kvm_get_dirty_log_protect() function description for additional details.
3670 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
3671 * always flush the TLB (step 4) even if previous step failed and the dirty
3672 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
3673 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
3674 * writes will be marked dirty for next log read.
3676 * 1. Take a snapshot of the bit and clear it if needed.
3677 * 2. Write protect the corresponding page.
3678 * 3. Copy the snapshot to the userspace.
3679 * 4. Flush TLB's if needed.
3681 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
3683 bool is_dirty = false;
3686 mutex_lock(&kvm->slots_lock);
3689 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
3691 if (kvm_x86_ops->flush_log_dirty)
3692 kvm_x86_ops->flush_log_dirty(kvm);
3694 r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
3697 * All the TLBs can be flushed out of mmu lock, see the comments in
3698 * kvm_mmu_slot_remove_write_access().
3700 lockdep_assert_held(&kvm->slots_lock);
3702 kvm_flush_remote_tlbs(kvm);
3704 mutex_unlock(&kvm->slots_lock);
3708 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
3711 if (!irqchip_in_kernel(kvm))
3714 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3715 irq_event->irq, irq_event->level,
3720 static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3721 struct kvm_enable_cap *cap)
3729 case KVM_CAP_DISABLE_QUIRKS:
3730 kvm->arch.disabled_quirks = cap->args[0];
3733 case KVM_CAP_SPLIT_IRQCHIP: {
3734 mutex_lock(&kvm->lock);
3736 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
3737 goto split_irqchip_unlock;
3739 if (irqchip_in_kernel(kvm))
3740 goto split_irqchip_unlock;
3741 if (atomic_read(&kvm->online_vcpus))
3742 goto split_irqchip_unlock;
3743 r = kvm_setup_empty_irq_routing(kvm);
3745 goto split_irqchip_unlock;
3746 /* Pairs with irqchip_in_kernel. */
3748 kvm->arch.irqchip_split = true;
3749 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
3751 split_irqchip_unlock:
3752 mutex_unlock(&kvm->lock);
3762 long kvm_arch_vm_ioctl(struct file *filp,
3763 unsigned int ioctl, unsigned long arg)
3765 struct kvm *kvm = filp->private_data;
3766 void __user *argp = (void __user *)arg;
3769 * This union makes it completely explicit to gcc-3.x
3770 * that these two variables' stack usage should be
3771 * combined, not added together.
3774 struct kvm_pit_state ps;
3775 struct kvm_pit_state2 ps2;
3776 struct kvm_pit_config pit_config;
3780 case KVM_SET_TSS_ADDR:
3781 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3783 case KVM_SET_IDENTITY_MAP_ADDR: {
3787 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3789 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3792 case KVM_SET_NR_MMU_PAGES:
3793 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3795 case KVM_GET_NR_MMU_PAGES:
3796 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3798 case KVM_CREATE_IRQCHIP: {
3799 struct kvm_pic *vpic;
3801 mutex_lock(&kvm->lock);
3804 goto create_irqchip_unlock;
3806 if (atomic_read(&kvm->online_vcpus))
3807 goto create_irqchip_unlock;
3809 vpic = kvm_create_pic(kvm);
3811 r = kvm_ioapic_init(kvm);
3813 mutex_lock(&kvm->slots_lock);
3814 kvm_destroy_pic(vpic);
3815 mutex_unlock(&kvm->slots_lock);
3816 goto create_irqchip_unlock;
3819 goto create_irqchip_unlock;
3820 r = kvm_setup_default_irq_routing(kvm);
3822 mutex_lock(&kvm->slots_lock);
3823 mutex_lock(&kvm->irq_lock);
3824 kvm_ioapic_destroy(kvm);
3825 kvm_destroy_pic(vpic);
3826 mutex_unlock(&kvm->irq_lock);
3827 mutex_unlock(&kvm->slots_lock);
3828 goto create_irqchip_unlock;
3830 /* Write kvm->irq_routing before kvm->arch.vpic. */
3832 kvm->arch.vpic = vpic;
3833 create_irqchip_unlock:
3834 mutex_unlock(&kvm->lock);
3837 case KVM_CREATE_PIT:
3838 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3840 case KVM_CREATE_PIT2:
3842 if (copy_from_user(&u.pit_config, argp,
3843 sizeof(struct kvm_pit_config)))
3846 mutex_lock(&kvm->slots_lock);
3849 goto create_pit_unlock;
3851 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3855 mutex_unlock(&kvm->slots_lock);
3857 case KVM_GET_IRQCHIP: {
3858 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3859 struct kvm_irqchip *chip;
3861 chip = memdup_user(argp, sizeof(*chip));
3868 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
3869 goto get_irqchip_out;
3870 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3872 goto get_irqchip_out;
3874 if (copy_to_user(argp, chip, sizeof *chip))
3875 goto get_irqchip_out;
3881 case KVM_SET_IRQCHIP: {
3882 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3883 struct kvm_irqchip *chip;
3885 chip = memdup_user(argp, sizeof(*chip));
3892 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
3893 goto set_irqchip_out;
3894 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3896 goto set_irqchip_out;
3904 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
3907 if (!kvm->arch.vpit)
3909 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
3913 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
3920 if (copy_from_user(&u.ps, argp, sizeof u.ps))
3923 if (!kvm->arch.vpit)
3925 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
3928 case KVM_GET_PIT2: {
3930 if (!kvm->arch.vpit)
3932 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
3936 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
3941 case KVM_SET_PIT2: {
3943 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
3946 if (!kvm->arch.vpit)
3948 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
3951 case KVM_REINJECT_CONTROL: {
3952 struct kvm_reinject_control control;
3954 if (copy_from_user(&control, argp, sizeof(control)))
3956 r = kvm_vm_ioctl_reinject(kvm, &control);
3959 case KVM_SET_BOOT_CPU_ID:
3961 mutex_lock(&kvm->lock);
3962 if (atomic_read(&kvm->online_vcpus) != 0)
3965 kvm->arch.bsp_vcpu_id = arg;
3966 mutex_unlock(&kvm->lock);
3968 case KVM_XEN_HVM_CONFIG: {
3970 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
3971 sizeof(struct kvm_xen_hvm_config)))
3974 if (kvm->arch.xen_hvm_config.flags)
3979 case KVM_SET_CLOCK: {
3980 struct kvm_clock_data user_ns;
3985 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
3993 local_irq_disable();
3994 now_ns = get_kernel_ns();
3995 delta = user_ns.clock - now_ns;
3997 kvm->arch.kvmclock_offset = delta;
3998 kvm_gen_update_masterclock(kvm);
4001 case KVM_GET_CLOCK: {
4002 struct kvm_clock_data user_ns;
4005 local_irq_disable();
4006 now_ns = get_kernel_ns();
4007 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
4010 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
4013 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
4018 case KVM_ENABLE_CAP: {
4019 struct kvm_enable_cap cap;
4022 if (copy_from_user(&cap, argp, sizeof(cap)))
4024 r = kvm_vm_ioctl_enable_cap(kvm, &cap);
4028 r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
4034 static void kvm_init_msr_list(void)
4039 for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
4040 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
4044 * Even MSRs that are valid in the host may not be exposed
4045 * to the guests in some cases.
4047 switch (msrs_to_save[i]) {
4048 case MSR_IA32_BNDCFGS:
4049 if (!kvm_x86_ops->mpx_supported())
4053 if (!kvm_x86_ops->rdtscp_supported())
4061 msrs_to_save[j] = msrs_to_save[i];
4064 num_msrs_to_save = j;
4066 for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
4067 switch (emulated_msrs[i]) {
4068 case MSR_IA32_SMBASE:
4069 if (!kvm_x86_ops->cpu_has_high_real_mode_segbase())
4077 emulated_msrs[j] = emulated_msrs[i];
4080 num_emulated_msrs = j;
4083 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
4091 if (!(vcpu->arch.apic &&
4092 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
4093 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
4104 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
4111 if (!(vcpu->arch.apic &&
4112 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
4114 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
4116 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
4126 static void kvm_set_segment(struct kvm_vcpu *vcpu,
4127 struct kvm_segment *var, int seg)
4129 kvm_x86_ops->set_segment(vcpu, var, seg);
4132 void kvm_get_segment(struct kvm_vcpu *vcpu,
4133 struct kvm_segment *var, int seg)
4135 kvm_x86_ops->get_segment(vcpu, var, seg);
4138 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
4139 struct x86_exception *exception)
4143 BUG_ON(!mmu_is_nested(vcpu));
4145 /* NPT walks are always user-walks */
4146 access |= PFERR_USER_MASK;
4147 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
4152 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
4153 struct x86_exception *exception)
4155 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4156 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4159 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
4160 struct x86_exception *exception)
4162 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4163 access |= PFERR_FETCH_MASK;
4164 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4167 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4168 struct x86_exception *exception)
4170 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4171 access |= PFERR_WRITE_MASK;
4172 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4175 /* uses this to access any guest's mapped memory without checking CPL */
4176 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4177 struct x86_exception *exception)
4179 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
4182 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4183 struct kvm_vcpu *vcpu, u32 access,
4184 struct x86_exception *exception)
4187 int r = X86EMUL_CONTINUE;
4190 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4192 unsigned offset = addr & (PAGE_SIZE-1);
4193 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4196 if (gpa == UNMAPPED_GVA)
4197 return X86EMUL_PROPAGATE_FAULT;
4198 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
4201 r = X86EMUL_IO_NEEDED;
4213 /* used for instruction fetching */
4214 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4215 gva_t addr, void *val, unsigned int bytes,
4216 struct x86_exception *exception)
4218 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4219 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4223 /* Inline kvm_read_guest_virt_helper for speed. */
4224 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
4226 if (unlikely(gpa == UNMAPPED_GVA))
4227 return X86EMUL_PROPAGATE_FAULT;
4229 offset = addr & (PAGE_SIZE-1);
4230 if (WARN_ON(offset + bytes > PAGE_SIZE))
4231 bytes = (unsigned)PAGE_SIZE - offset;
4232 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
4234 if (unlikely(ret < 0))
4235 return X86EMUL_IO_NEEDED;
4237 return X86EMUL_CONTINUE;
4240 int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
4241 gva_t addr, void *val, unsigned int bytes,
4242 struct x86_exception *exception)
4244 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4245 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4247 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4250 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4252 static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4253 gva_t addr, void *val, unsigned int bytes,
4254 struct x86_exception *exception)
4256 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4257 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
4260 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
4261 unsigned long addr, void *val, unsigned int bytes)
4263 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4264 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
4266 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
4269 int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4270 gva_t addr, void *val,
4272 struct x86_exception *exception)
4274 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4276 int r = X86EMUL_CONTINUE;
4279 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4282 unsigned offset = addr & (PAGE_SIZE-1);
4283 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4286 if (gpa == UNMAPPED_GVA)
4287 return X86EMUL_PROPAGATE_FAULT;
4288 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
4290 r = X86EMUL_IO_NEEDED;
4301 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4303 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4304 gpa_t *gpa, struct x86_exception *exception,
4307 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
4308 | (write ? PFERR_WRITE_MASK : 0);
4310 if (vcpu_match_mmio_gva(vcpu, gva)
4311 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
4312 vcpu->arch.access, access)) {
4313 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4314 (gva & (PAGE_SIZE - 1));
4315 trace_vcpu_match_mmio(gva, *gpa, write, false);
4319 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4321 if (*gpa == UNMAPPED_GVA)
4324 /* For APIC access vmexit */
4325 if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4328 if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
4329 trace_vcpu_match_mmio(gva, *gpa, write, true);
4336 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4337 const void *val, int bytes)
4341 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
4344 kvm_mmu_pte_write(vcpu, gpa, val, bytes);
4348 struct read_write_emulator_ops {
4349 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4351 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4352 void *val, int bytes);
4353 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4354 int bytes, void *val);
4355 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4356 void *val, int bytes);
4360 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4362 if (vcpu->mmio_read_completed) {
4363 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4364 vcpu->mmio_fragments[0].gpa, *(u64 *)val);
4365 vcpu->mmio_read_completed = 0;
4372 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4373 void *val, int bytes)
4375 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
4378 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4379 void *val, int bytes)
4381 return emulator_write_phys(vcpu, gpa, val, bytes);
4384 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4386 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
4387 return vcpu_mmio_write(vcpu, gpa, bytes, val);
4390 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4391 void *val, int bytes)
4393 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
4394 return X86EMUL_IO_NEEDED;
4397 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4398 void *val, int bytes)
4400 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
4402 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
4403 return X86EMUL_CONTINUE;
4406 static const struct read_write_emulator_ops read_emultor = {
4407 .read_write_prepare = read_prepare,
4408 .read_write_emulate = read_emulate,
4409 .read_write_mmio = vcpu_mmio_read,
4410 .read_write_exit_mmio = read_exit_mmio,
4413 static const struct read_write_emulator_ops write_emultor = {
4414 .read_write_emulate = write_emulate,
4415 .read_write_mmio = write_mmio,
4416 .read_write_exit_mmio = write_exit_mmio,
4420 static int emulator_read_write_onepage(unsigned long addr, void *val,
4422 struct x86_exception *exception,
4423 struct kvm_vcpu *vcpu,
4424 const struct read_write_emulator_ops *ops)
4428 bool write = ops->write;
4429 struct kvm_mmio_fragment *frag;
4431 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4434 return X86EMUL_PROPAGATE_FAULT;
4436 /* For APIC access vmexit */
4440 if (ops->read_write_emulate(vcpu, gpa, val, bytes))
4441 return X86EMUL_CONTINUE;
4445 * Is this MMIO handled locally?
4447 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4448 if (handled == bytes)
4449 return X86EMUL_CONTINUE;
4455 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
4456 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
4460 return X86EMUL_CONTINUE;
4463 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
4465 void *val, unsigned int bytes,
4466 struct x86_exception *exception,
4467 const struct read_write_emulator_ops *ops)
4469 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4473 if (ops->read_write_prepare &&
4474 ops->read_write_prepare(vcpu, val, bytes))
4475 return X86EMUL_CONTINUE;
4477 vcpu->mmio_nr_fragments = 0;
4479 /* Crossing a page boundary? */
4480 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4483 now = -addr & ~PAGE_MASK;
4484 rc = emulator_read_write_onepage(addr, val, now, exception,
4487 if (rc != X86EMUL_CONTINUE)
4490 if (ctxt->mode != X86EMUL_MODE_PROT64)
4496 rc = emulator_read_write_onepage(addr, val, bytes, exception,
4498 if (rc != X86EMUL_CONTINUE)
4501 if (!vcpu->mmio_nr_fragments)
4504 gpa = vcpu->mmio_fragments[0].gpa;
4506 vcpu->mmio_needed = 1;
4507 vcpu->mmio_cur_fragment = 0;
4509 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
4510 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
4511 vcpu->run->exit_reason = KVM_EXIT_MMIO;
4512 vcpu->run->mmio.phys_addr = gpa;
4514 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4517 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4521 struct x86_exception *exception)
4523 return emulator_read_write(ctxt, addr, val, bytes,
4524 exception, &read_emultor);
4527 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4531 struct x86_exception *exception)
4533 return emulator_read_write(ctxt, addr, (void *)val, bytes,
4534 exception, &write_emultor);
4537 #define CMPXCHG_TYPE(t, ptr, old, new) \
4538 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4540 #ifdef CONFIG_X86_64
4541 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4543 # define CMPXCHG64(ptr, old, new) \
4544 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4547 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4552 struct x86_exception *exception)
4554 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4560 /* guests cmpxchg8b have to be emulated atomically */
4561 if (bytes > 8 || (bytes & (bytes - 1)))
4564 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4566 if (gpa == UNMAPPED_GVA ||
4567 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4570 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4573 page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
4574 if (is_error_page(page))
4577 kaddr = kmap_atomic(page);
4578 kaddr += offset_in_page(gpa);
4581 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4584 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4587 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
4590 exchanged = CMPXCHG64(kaddr, old, new);
4595 kunmap_atomic(kaddr);
4596 kvm_release_page_dirty(page);
4599 return X86EMUL_CMPXCHG_FAILED;
4601 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
4602 kvm_mmu_pte_write(vcpu, gpa, new, bytes);
4604 return X86EMUL_CONTINUE;
4607 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
4609 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
4612 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
4616 for (i = 0; i < vcpu->arch.pio.count; i++) {
4617 if (vcpu->arch.pio.in)
4618 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
4619 vcpu->arch.pio.size, pd);
4621 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
4622 vcpu->arch.pio.port, vcpu->arch.pio.size,
4626 pd += vcpu->arch.pio.size;
4631 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
4632 unsigned short port, void *val,
4633 unsigned int count, bool in)
4635 vcpu->arch.pio.port = port;
4636 vcpu->arch.pio.in = in;
4637 vcpu->arch.pio.count = count;
4638 vcpu->arch.pio.size = size;
4640 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4641 vcpu->arch.pio.count = 0;
4645 vcpu->run->exit_reason = KVM_EXIT_IO;
4646 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
4647 vcpu->run->io.size = size;
4648 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4649 vcpu->run->io.count = count;
4650 vcpu->run->io.port = port;
4655 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
4656 int size, unsigned short port, void *val,
4659 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4662 if (vcpu->arch.pio.count)
4665 memset(vcpu->arch.pio_data, 0, size * count);
4667 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
4670 memcpy(val, vcpu->arch.pio_data, size * count);
4671 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
4672 vcpu->arch.pio.count = 0;
4679 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
4680 int size, unsigned short port,
4681 const void *val, unsigned int count)
4683 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4685 memcpy(vcpu->arch.pio_data, val, size * count);
4686 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
4687 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
4690 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
4692 return kvm_x86_ops->get_segment_base(vcpu, seg);
4695 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
4697 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
4700 int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
4702 if (!need_emulate_wbinvd(vcpu))
4703 return X86EMUL_CONTINUE;
4705 if (kvm_x86_ops->has_wbinvd_exit()) {
4706 int cpu = get_cpu();
4708 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4709 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
4710 wbinvd_ipi, NULL, 1);
4712 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
4715 return X86EMUL_CONTINUE;
4718 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
4720 kvm_x86_ops->skip_emulated_instruction(vcpu);
4721 return kvm_emulate_wbinvd_noskip(vcpu);
4723 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
4727 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
4729 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
4732 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
4733 unsigned long *dest)
4735 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
4738 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
4739 unsigned long value)
4742 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
4745 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
4747 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
4750 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
4752 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4753 unsigned long value;
4757 value = kvm_read_cr0(vcpu);
4760 value = vcpu->arch.cr2;
4763 value = kvm_read_cr3(vcpu);
4766 value = kvm_read_cr4(vcpu);
4769 value = kvm_get_cr8(vcpu);
4772 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4779 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
4781 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4786 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4789 vcpu->arch.cr2 = val;
4792 res = kvm_set_cr3(vcpu, val);
4795 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4798 res = kvm_set_cr8(vcpu, val);
4801 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4808 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
4810 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
4813 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4815 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
4818 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4820 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
4823 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4825 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4828 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4830 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4833 static unsigned long emulator_get_cached_segment_base(
4834 struct x86_emulate_ctxt *ctxt, int seg)
4836 return get_segment_base(emul_to_vcpu(ctxt), seg);
4839 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4840 struct desc_struct *desc, u32 *base3,
4843 struct kvm_segment var;
4845 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
4846 *selector = var.selector;
4849 memset(desc, 0, sizeof(*desc));
4857 set_desc_limit(desc, var.limit);
4858 set_desc_base(desc, (unsigned long)var.base);
4859 #ifdef CONFIG_X86_64
4861 *base3 = var.base >> 32;
4863 desc->type = var.type;
4865 desc->dpl = var.dpl;
4866 desc->p = var.present;
4867 desc->avl = var.avl;
4875 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
4876 struct desc_struct *desc, u32 base3,
4879 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4880 struct kvm_segment var;
4882 var.selector = selector;
4883 var.base = get_desc_base(desc);
4884 #ifdef CONFIG_X86_64
4885 var.base |= ((u64)base3) << 32;
4887 var.limit = get_desc_limit(desc);
4889 var.limit = (var.limit << 12) | 0xfff;
4890 var.type = desc->type;
4891 var.dpl = desc->dpl;
4896 var.avl = desc->avl;
4897 var.present = desc->p;
4898 var.unusable = !var.present;
4901 kvm_set_segment(vcpu, &var, seg);
4905 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
4906 u32 msr_index, u64 *pdata)
4908 struct msr_data msr;
4911 msr.index = msr_index;
4912 msr.host_initiated = false;
4913 r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
4921 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
4922 u32 msr_index, u64 data)
4924 struct msr_data msr;
4927 msr.index = msr_index;
4928 msr.host_initiated = false;
4929 return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
4932 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
4934 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4936 return vcpu->arch.smbase;
4939 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
4941 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4943 vcpu->arch.smbase = smbase;
4946 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
4949 return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
4952 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
4953 u32 pmc, u64 *pdata)
4955 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
4958 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
4960 emul_to_vcpu(ctxt)->arch.halt_request = 1;
4963 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
4966 kvm_load_guest_fpu(emul_to_vcpu(ctxt));
4968 * CR0.TS may reference the host fpu state, not the guest fpu state,
4969 * so it may be clear at this point.
4974 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
4979 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
4980 struct x86_instruction_info *info,
4981 enum x86_intercept_stage stage)
4983 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
4986 static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
4987 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
4989 kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
4992 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
4994 return kvm_register_read(emul_to_vcpu(ctxt), reg);
4997 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
4999 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
5002 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
5004 kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
5007 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
5009 return emul_to_vcpu(ctxt)->arch.hflags;
5012 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
5014 kvm_set_hflags(emul_to_vcpu(ctxt), emul_flags);
5017 static const struct x86_emulate_ops emulate_ops = {
5018 .read_gpr = emulator_read_gpr,
5019 .write_gpr = emulator_write_gpr,
5020 .read_std = kvm_read_guest_virt_system,
5021 .write_std = kvm_write_guest_virt_system,
5022 .read_phys = kvm_read_guest_phys_system,
5023 .fetch = kvm_fetch_guest_virt,
5024 .read_emulated = emulator_read_emulated,
5025 .write_emulated = emulator_write_emulated,
5026 .cmpxchg_emulated = emulator_cmpxchg_emulated,
5027 .invlpg = emulator_invlpg,
5028 .pio_in_emulated = emulator_pio_in_emulated,
5029 .pio_out_emulated = emulator_pio_out_emulated,
5030 .get_segment = emulator_get_segment,
5031 .set_segment = emulator_set_segment,
5032 .get_cached_segment_base = emulator_get_cached_segment_base,
5033 .get_gdt = emulator_get_gdt,
5034 .get_idt = emulator_get_idt,
5035 .set_gdt = emulator_set_gdt,
5036 .set_idt = emulator_set_idt,
5037 .get_cr = emulator_get_cr,
5038 .set_cr = emulator_set_cr,
5039 .cpl = emulator_get_cpl,
5040 .get_dr = emulator_get_dr,
5041 .set_dr = emulator_set_dr,
5042 .get_smbase = emulator_get_smbase,
5043 .set_smbase = emulator_set_smbase,
5044 .set_msr = emulator_set_msr,
5045 .get_msr = emulator_get_msr,
5046 .check_pmc = emulator_check_pmc,
5047 .read_pmc = emulator_read_pmc,
5048 .halt = emulator_halt,
5049 .wbinvd = emulator_wbinvd,
5050 .fix_hypercall = emulator_fix_hypercall,
5051 .get_fpu = emulator_get_fpu,
5052 .put_fpu = emulator_put_fpu,
5053 .intercept = emulator_intercept,
5054 .get_cpuid = emulator_get_cpuid,
5055 .set_nmi_mask = emulator_set_nmi_mask,
5056 .get_hflags = emulator_get_hflags,
5057 .set_hflags = emulator_set_hflags,
5060 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
5062 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
5064 * an sti; sti; sequence only disable interrupts for the first
5065 * instruction. So, if the last instruction, be it emulated or
5066 * not, left the system with the INT_STI flag enabled, it
5067 * means that the last instruction is an sti. We should not
5068 * leave the flag on in this case. The same goes for mov ss
5070 if (int_shadow & mask)
5072 if (unlikely(int_shadow || mask)) {
5073 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
5075 kvm_make_request(KVM_REQ_EVENT, vcpu);
5079 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
5081 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5082 if (ctxt->exception.vector == PF_VECTOR)
5083 return kvm_propagate_fault(vcpu, &ctxt->exception);
5085 if (ctxt->exception.error_code_valid)
5086 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
5087 ctxt->exception.error_code);
5089 kvm_queue_exception(vcpu, ctxt->exception.vector);
5093 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
5095 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5098 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5100 ctxt->eflags = kvm_get_rflags(vcpu);
5101 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
5103 ctxt->eip = kvm_rip_read(vcpu);
5104 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
5105 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
5106 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
5107 cs_db ? X86EMUL_MODE_PROT32 :
5108 X86EMUL_MODE_PROT16;
5109 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
5110 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
5111 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
5113 init_decode_cache(ctxt);
5114 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5117 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
5119 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5122 init_emulate_ctxt(vcpu);
5126 ctxt->_eip = ctxt->eip + inc_eip;
5127 ret = emulate_int_real(ctxt, irq);
5129 if (ret != X86EMUL_CONTINUE)
5130 return EMULATE_FAIL;
5132 ctxt->eip = ctxt->_eip;
5133 kvm_rip_write(vcpu, ctxt->eip);
5134 kvm_set_rflags(vcpu, ctxt->eflags);
5136 if (irq == NMI_VECTOR)
5137 vcpu->arch.nmi_pending = 0;
5139 vcpu->arch.interrupt.pending = false;
5141 return EMULATE_DONE;
5143 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
5145 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
5147 int r = EMULATE_DONE;
5149 ++vcpu->stat.insn_emulation_fail;
5150 trace_kvm_emulate_insn_failed(vcpu);
5151 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
5152 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5153 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5154 vcpu->run->internal.ndata = 0;
5157 kvm_queue_exception(vcpu, UD_VECTOR);
5162 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5163 bool write_fault_to_shadow_pgtable,
5169 if (emulation_type & EMULTYPE_NO_REEXECUTE)
5172 if (!vcpu->arch.mmu.direct_map) {
5174 * Write permission should be allowed since only
5175 * write access need to be emulated.
5177 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5180 * If the mapping is invalid in guest, let cpu retry
5181 * it to generate fault.
5183 if (gpa == UNMAPPED_GVA)
5188 * Do not retry the unhandleable instruction if it faults on the
5189 * readonly host memory, otherwise it will goto a infinite loop:
5190 * retry instruction -> write #PF -> emulation fail -> retry
5191 * instruction -> ...
5193 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
5196 * If the instruction failed on the error pfn, it can not be fixed,
5197 * report the error to userspace.
5199 if (is_error_noslot_pfn(pfn))
5202 kvm_release_pfn_clean(pfn);
5204 /* The instructions are well-emulated on direct mmu. */
5205 if (vcpu->arch.mmu.direct_map) {
5206 unsigned int indirect_shadow_pages;
5208 spin_lock(&vcpu->kvm->mmu_lock);
5209 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
5210 spin_unlock(&vcpu->kvm->mmu_lock);
5212 if (indirect_shadow_pages)
5213 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5219 * if emulation was due to access to shadowed page table
5220 * and it failed try to unshadow page and re-enter the
5221 * guest to let CPU execute the instruction.
5223 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5226 * If the access faults on its page table, it can not
5227 * be fixed by unprotecting shadow page and it should
5228 * be reported to userspace.
5230 return !write_fault_to_shadow_pgtable;
5233 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5234 unsigned long cr2, int emulation_type)
5236 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5237 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
5239 last_retry_eip = vcpu->arch.last_retry_eip;
5240 last_retry_addr = vcpu->arch.last_retry_addr;
5243 * If the emulation is caused by #PF and it is non-page_table
5244 * writing instruction, it means the VM-EXIT is caused by shadow
5245 * page protected, we can zap the shadow page and retry this
5246 * instruction directly.
5248 * Note: if the guest uses a non-page-table modifying instruction
5249 * on the PDE that points to the instruction, then we will unmap
5250 * the instruction and go to an infinite loop. So, we cache the
5251 * last retried eip and the last fault address, if we meet the eip
5252 * and the address again, we can break out of the potential infinite
5255 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
5257 if (!(emulation_type & EMULTYPE_RETRY))
5260 if (x86_page_table_writing_insn(ctxt))
5263 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
5266 vcpu->arch.last_retry_eip = ctxt->eip;
5267 vcpu->arch.last_retry_addr = cr2;
5269 if (!vcpu->arch.mmu.direct_map)
5270 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5272 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5277 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
5278 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
5280 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
5282 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
5283 /* This is a good place to trace that we are exiting SMM. */
5284 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
5286 if (unlikely(vcpu->arch.smi_pending)) {
5287 kvm_make_request(KVM_REQ_SMI, vcpu);
5288 vcpu->arch.smi_pending = 0;
5290 /* Process a latched INIT, if any. */
5291 kvm_make_request(KVM_REQ_EVENT, vcpu);
5295 kvm_mmu_reset_context(vcpu);
5298 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
5300 unsigned changed = vcpu->arch.hflags ^ emul_flags;
5302 vcpu->arch.hflags = emul_flags;
5304 if (changed & HF_SMM_MASK)
5305 kvm_smm_changed(vcpu);
5308 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
5317 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
5318 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
5323 static void kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu, int *r)
5325 struct kvm_run *kvm_run = vcpu->run;
5327 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5328 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
5329 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
5330 kvm_run->debug.arch.exception = DB_VECTOR;
5331 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5332 *r = EMULATE_USER_EXIT;
5334 vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF;
5336 * "Certain debug exceptions may clear bit 0-3. The
5337 * remaining contents of the DR6 register are never
5338 * cleared by the processor".
5340 vcpu->arch.dr6 &= ~15;
5341 vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
5342 kvm_queue_exception(vcpu, DB_VECTOR);
5346 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
5348 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
5349 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
5350 struct kvm_run *kvm_run = vcpu->run;
5351 unsigned long eip = kvm_get_linear_rip(vcpu);
5352 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5353 vcpu->arch.guest_debug_dr7,
5357 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
5358 kvm_run->debug.arch.pc = eip;
5359 kvm_run->debug.arch.exception = DB_VECTOR;
5360 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5361 *r = EMULATE_USER_EXIT;
5366 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
5367 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
5368 unsigned long eip = kvm_get_linear_rip(vcpu);
5369 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5374 vcpu->arch.dr6 &= ~15;
5375 vcpu->arch.dr6 |= dr6 | DR6_RTM;
5376 kvm_queue_exception(vcpu, DB_VECTOR);
5385 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
5392 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5393 bool writeback = true;
5394 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
5397 * Clear write_fault_to_shadow_pgtable here to ensure it is
5400 vcpu->arch.write_fault_to_shadow_pgtable = false;
5401 kvm_clear_exception_queue(vcpu);
5403 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
5404 init_emulate_ctxt(vcpu);
5407 * We will reenter on the same instruction since
5408 * we do not set complete_userspace_io. This does not
5409 * handle watchpoints yet, those would be handled in
5412 if (kvm_vcpu_check_breakpoint(vcpu, &r))
5415 ctxt->interruptibility = 0;
5416 ctxt->have_exception = false;
5417 ctxt->exception.vector = -1;
5418 ctxt->perm_ok = false;
5420 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
5422 r = x86_decode_insn(ctxt, insn, insn_len);
5424 trace_kvm_emulate_insn_start(vcpu);
5425 ++vcpu->stat.insn_emulation;
5426 if (r != EMULATION_OK) {
5427 if (emulation_type & EMULTYPE_TRAP_UD)
5428 return EMULATE_FAIL;
5429 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5431 return EMULATE_DONE;
5432 if (ctxt->have_exception && inject_emulated_exception(vcpu))
5433 return EMULATE_DONE;
5434 if (emulation_type & EMULTYPE_SKIP)
5435 return EMULATE_FAIL;
5436 return handle_emulation_failure(vcpu);
5440 if (emulation_type & EMULTYPE_SKIP) {
5441 kvm_rip_write(vcpu, ctxt->_eip);
5442 if (ctxt->eflags & X86_EFLAGS_RF)
5443 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
5444 return EMULATE_DONE;
5447 if (retry_instruction(ctxt, cr2, emulation_type))
5448 return EMULATE_DONE;
5450 /* this is needed for vmware backdoor interface to work since it
5451 changes registers values during IO operation */
5452 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
5453 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5454 emulator_invalidate_register_cache(ctxt);
5458 r = x86_emulate_insn(ctxt);
5460 if (r == EMULATION_INTERCEPTED)
5461 return EMULATE_DONE;
5463 if (r == EMULATION_FAILED) {
5464 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5466 return EMULATE_DONE;
5468 return handle_emulation_failure(vcpu);
5471 if (ctxt->have_exception) {
5473 if (inject_emulated_exception(vcpu))
5475 } else if (vcpu->arch.pio.count) {
5476 if (!vcpu->arch.pio.in) {
5477 /* FIXME: return into emulator if single-stepping. */
5478 vcpu->arch.pio.count = 0;
5481 vcpu->arch.complete_userspace_io = complete_emulated_pio;
5483 r = EMULATE_USER_EXIT;
5484 } else if (vcpu->mmio_needed) {
5485 if (!vcpu->mmio_is_write)
5487 r = EMULATE_USER_EXIT;
5488 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
5489 } else if (r == EMULATION_RESTART)
5495 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5496 toggle_interruptibility(vcpu, ctxt->interruptibility);
5497 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5498 kvm_rip_write(vcpu, ctxt->eip);
5499 if (r == EMULATE_DONE &&
5500 (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
5501 kvm_vcpu_do_singlestep(vcpu, &r);
5502 if (!ctxt->have_exception ||
5503 exception_type(ctxt->exception.vector) == EXCPT_TRAP)
5504 __kvm_set_rflags(vcpu, ctxt->eflags);
5507 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
5508 * do nothing, and it will be requested again as soon as
5509 * the shadow expires. But we still need to check here,
5510 * because POPF has no interrupt shadow.
5512 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
5513 kvm_make_request(KVM_REQ_EVENT, vcpu);
5515 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5519 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5521 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5523 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5524 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5525 size, port, &val, 1);
5526 /* do not return to emulator after return from userspace */
5527 vcpu->arch.pio.count = 0;
5530 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5532 static void tsc_bad(void *info)
5534 __this_cpu_write(cpu_tsc_khz, 0);
5537 static void tsc_khz_changed(void *data)
5539 struct cpufreq_freqs *freq = data;
5540 unsigned long khz = 0;
5544 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5545 khz = cpufreq_quick_get(raw_smp_processor_id());
5548 __this_cpu_write(cpu_tsc_khz, khz);
5551 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5554 struct cpufreq_freqs *freq = data;
5556 struct kvm_vcpu *vcpu;
5557 int i, send_ipi = 0;
5560 * We allow guests to temporarily run on slowing clocks,
5561 * provided we notify them after, or to run on accelerating
5562 * clocks, provided we notify them before. Thus time never
5565 * However, we have a problem. We can't atomically update
5566 * the frequency of a given CPU from this function; it is
5567 * merely a notifier, which can be called from any CPU.
5568 * Changing the TSC frequency at arbitrary points in time
5569 * requires a recomputation of local variables related to
5570 * the TSC for each VCPU. We must flag these local variables
5571 * to be updated and be sure the update takes place with the
5572 * new frequency before any guests proceed.
5574 * Unfortunately, the combination of hotplug CPU and frequency
5575 * change creates an intractable locking scenario; the order
5576 * of when these callouts happen is undefined with respect to
5577 * CPU hotplug, and they can race with each other. As such,
5578 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5579 * undefined; you can actually have a CPU frequency change take
5580 * place in between the computation of X and the setting of the
5581 * variable. To protect against this problem, all updates of
5582 * the per_cpu tsc_khz variable are done in an interrupt
5583 * protected IPI, and all callers wishing to update the value
5584 * must wait for a synchronous IPI to complete (which is trivial
5585 * if the caller is on the CPU already). This establishes the
5586 * necessary total order on variable updates.
5588 * Note that because a guest time update may take place
5589 * anytime after the setting of the VCPU's request bit, the
5590 * correct TSC value must be set before the request. However,
5591 * to ensure the update actually makes it to any guest which
5592 * starts running in hardware virtualization between the set
5593 * and the acquisition of the spinlock, we must also ping the
5594 * CPU after setting the request bit.
5598 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
5600 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
5603 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5605 spin_lock(&kvm_lock);
5606 list_for_each_entry(kvm, &vm_list, vm_list) {
5607 kvm_for_each_vcpu(i, vcpu, kvm) {
5608 if (vcpu->cpu != freq->cpu)
5610 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5611 if (vcpu->cpu != smp_processor_id())
5615 spin_unlock(&kvm_lock);
5617 if (freq->old < freq->new && send_ipi) {
5619 * We upscale the frequency. Must make the guest
5620 * doesn't see old kvmclock values while running with
5621 * the new frequency, otherwise we risk the guest sees
5622 * time go backwards.
5624 * In case we update the frequency for another cpu
5625 * (which might be in guest context) send an interrupt
5626 * to kick the cpu out of guest context. Next time
5627 * guest context is entered kvmclock will be updated,
5628 * so the guest will not see stale values.
5630 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5635 static struct notifier_block kvmclock_cpufreq_notifier_block = {
5636 .notifier_call = kvmclock_cpufreq_notifier
5639 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
5640 unsigned long action, void *hcpu)
5642 unsigned int cpu = (unsigned long)hcpu;
5646 case CPU_DOWN_FAILED:
5647 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5649 case CPU_DOWN_PREPARE:
5650 smp_call_function_single(cpu, tsc_bad, NULL, 1);
5656 static struct notifier_block kvmclock_cpu_notifier_block = {
5657 .notifier_call = kvmclock_cpu_notifier,
5658 .priority = -INT_MAX
5661 static void kvm_timer_init(void)
5665 max_tsc_khz = tsc_khz;
5667 cpu_notifier_register_begin();
5668 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5669 #ifdef CONFIG_CPU_FREQ
5670 struct cpufreq_policy policy;
5671 memset(&policy, 0, sizeof(policy));
5673 cpufreq_get_policy(&policy, cpu);
5674 if (policy.cpuinfo.max_freq)
5675 max_tsc_khz = policy.cpuinfo.max_freq;
5678 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
5679 CPUFREQ_TRANSITION_NOTIFIER);
5681 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
5682 for_each_online_cpu(cpu)
5683 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5685 __register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5686 cpu_notifier_register_done();
5690 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
5692 int kvm_is_in_guest(void)
5694 return __this_cpu_read(current_vcpu) != NULL;
5697 static int kvm_is_user_mode(void)
5701 if (__this_cpu_read(current_vcpu))
5702 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
5704 return user_mode != 0;
5707 static unsigned long kvm_get_guest_ip(void)
5709 unsigned long ip = 0;
5711 if (__this_cpu_read(current_vcpu))
5712 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
5717 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5718 .is_in_guest = kvm_is_in_guest,
5719 .is_user_mode = kvm_is_user_mode,
5720 .get_guest_ip = kvm_get_guest_ip,
5723 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
5725 __this_cpu_write(current_vcpu, vcpu);
5727 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
5729 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
5731 __this_cpu_write(current_vcpu, NULL);
5733 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
5735 static void kvm_set_mmio_spte_mask(void)
5738 int maxphyaddr = boot_cpu_data.x86_phys_bits;
5741 * Set the reserved bits and the present bit of an paging-structure
5742 * entry to generate page fault with PFER.RSV = 1.
5744 /* Mask the reserved physical address bits. */
5745 mask = rsvd_bits(maxphyaddr, 51);
5747 /* Bit 62 is always reserved for 32bit host. */
5748 mask |= 0x3ull << 62;
5750 /* Set the present bit. */
5753 #ifdef CONFIG_X86_64
5755 * If reserved bit is not supported, clear the present bit to disable
5758 if (maxphyaddr == 52)
5762 kvm_mmu_set_mmio_spte_mask(mask);
5765 #ifdef CONFIG_X86_64
5766 static void pvclock_gtod_update_fn(struct work_struct *work)
5770 struct kvm_vcpu *vcpu;
5773 spin_lock(&kvm_lock);
5774 list_for_each_entry(kvm, &vm_list, vm_list)
5775 kvm_for_each_vcpu(i, vcpu, kvm)
5776 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
5777 atomic_set(&kvm_guest_has_master_clock, 0);
5778 spin_unlock(&kvm_lock);
5781 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
5784 * Notification about pvclock gtod data update.
5786 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
5789 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
5790 struct timekeeper *tk = priv;
5792 update_pvclock_gtod(tk);
5794 /* disable master clock if host does not trust, or does not
5795 * use, TSC clocksource
5797 if (gtod->clock.vclock_mode != VCLOCK_TSC &&
5798 atomic_read(&kvm_guest_has_master_clock) != 0)
5799 queue_work(system_long_wq, &pvclock_gtod_work);
5804 static struct notifier_block pvclock_gtod_notifier = {
5805 .notifier_call = pvclock_gtod_notify,
5809 int kvm_arch_init(void *opaque)
5812 struct kvm_x86_ops *ops = opaque;
5815 printk(KERN_ERR "kvm: already loaded the other module\n");
5820 if (!ops->cpu_has_kvm_support()) {
5821 printk(KERN_ERR "kvm: no hardware support\n");
5825 if (ops->disabled_by_bios()) {
5826 printk(KERN_ERR "kvm: disabled by bios\n");
5832 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
5834 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
5838 r = kvm_mmu_module_init();
5840 goto out_free_percpu;
5842 kvm_set_mmio_spte_mask();
5846 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
5847 PT_DIRTY_MASK, PT64_NX_MASK, 0);
5851 perf_register_guest_info_callbacks(&kvm_guest_cbs);
5854 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
5857 #ifdef CONFIG_X86_64
5858 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
5864 free_percpu(shared_msrs);
5869 void kvm_arch_exit(void)
5872 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
5874 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5875 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
5876 CPUFREQ_TRANSITION_NOTIFIER);
5877 unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5878 #ifdef CONFIG_X86_64
5879 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
5882 kvm_mmu_module_exit();
5883 free_percpu(shared_msrs);
5886 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
5888 ++vcpu->stat.halt_exits;
5889 if (lapic_in_kernel(vcpu)) {
5890 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
5893 vcpu->run->exit_reason = KVM_EXIT_HLT;
5897 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
5899 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
5901 kvm_x86_ops->skip_emulated_instruction(vcpu);
5902 return kvm_vcpu_halt(vcpu);
5904 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
5907 * kvm_pv_kick_cpu_op: Kick a vcpu.
5909 * @apicid - apicid of vcpu to be kicked.
5911 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
5913 struct kvm_lapic_irq lapic_irq;
5915 lapic_irq.shorthand = 0;
5916 lapic_irq.dest_mode = 0;
5917 lapic_irq.dest_id = apicid;
5918 lapic_irq.msi_redir_hint = false;
5920 lapic_irq.delivery_mode = APIC_DM_REMRD;
5921 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
5924 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
5926 unsigned long nr, a0, a1, a2, a3, ret;
5927 int op_64_bit, r = 1;
5929 kvm_x86_ops->skip_emulated_instruction(vcpu);
5931 if (kvm_hv_hypercall_enabled(vcpu->kvm))
5932 return kvm_hv_hypercall(vcpu);
5934 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
5935 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
5936 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
5937 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
5938 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
5940 trace_kvm_hypercall(nr, a0, a1, a2, a3);
5942 op_64_bit = is_64_bit_mode(vcpu);
5951 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
5957 case KVM_HC_VAPIC_POLL_IRQ:
5960 case KVM_HC_KICK_CPU:
5961 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
5971 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
5972 ++vcpu->stat.hypercalls;
5975 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
5977 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
5979 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5980 char instruction[3];
5981 unsigned long rip = kvm_rip_read(vcpu);
5983 kvm_x86_ops->patch_hypercall(vcpu, instruction);
5985 return emulator_write_emulated(ctxt, rip, instruction, 3,
5989 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
5991 return vcpu->run->request_interrupt_window &&
5992 likely(!pic_in_kernel(vcpu->kvm));
5995 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
5997 struct kvm_run *kvm_run = vcpu->run;
5999 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
6000 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
6001 kvm_run->cr8 = kvm_get_cr8(vcpu);
6002 kvm_run->apic_base = kvm_get_apic_base(vcpu);
6003 kvm_run->ready_for_interrupt_injection =
6004 pic_in_kernel(vcpu->kvm) ||
6005 kvm_vcpu_ready_for_interrupt_injection(vcpu);
6008 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
6012 if (!kvm_x86_ops->update_cr8_intercept)
6015 if (!vcpu->arch.apic)
6018 if (!vcpu->arch.apic->vapic_addr)
6019 max_irr = kvm_lapic_find_highest_irr(vcpu);
6026 tpr = kvm_lapic_get_cr8(vcpu);
6028 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
6031 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
6035 /* try to reinject previous events if any */
6036 if (vcpu->arch.exception.pending) {
6037 trace_kvm_inj_exception(vcpu->arch.exception.nr,
6038 vcpu->arch.exception.has_error_code,
6039 vcpu->arch.exception.error_code);
6041 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
6042 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
6045 if (vcpu->arch.exception.nr == DB_VECTOR &&
6046 (vcpu->arch.dr7 & DR7_GD)) {
6047 vcpu->arch.dr7 &= ~DR7_GD;
6048 kvm_update_dr7(vcpu);
6051 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
6052 vcpu->arch.exception.has_error_code,
6053 vcpu->arch.exception.error_code,
6054 vcpu->arch.exception.reinject);
6058 if (vcpu->arch.nmi_injected) {
6059 kvm_x86_ops->set_nmi(vcpu);
6063 if (vcpu->arch.interrupt.pending) {
6064 kvm_x86_ops->set_irq(vcpu);
6068 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6069 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6074 /* try to inject new event if pending */
6075 if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
6076 --vcpu->arch.nmi_pending;
6077 vcpu->arch.nmi_injected = true;
6078 kvm_x86_ops->set_nmi(vcpu);
6079 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
6081 * Because interrupts can be injected asynchronously, we are
6082 * calling check_nested_events again here to avoid a race condition.
6083 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
6084 * proposal and current concerns. Perhaps we should be setting
6085 * KVM_REQ_EVENT only on certain events and not unconditionally?
6087 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6088 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6092 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
6093 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
6095 kvm_x86_ops->set_irq(vcpu);
6101 static void process_nmi(struct kvm_vcpu *vcpu)
6106 * x86 is limited to one NMI running, and one NMI pending after it.
6107 * If an NMI is already in progress, limit further NMIs to just one.
6108 * Otherwise, allow two (and we'll inject the first one immediately).
6110 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
6113 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
6114 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
6115 kvm_make_request(KVM_REQ_EVENT, vcpu);
6118 #define put_smstate(type, buf, offset, val) \
6119 *(type *)((buf) + (offset) - 0x7e00) = val
6121 static u32 process_smi_get_segment_flags(struct kvm_segment *seg)
6124 flags |= seg->g << 23;
6125 flags |= seg->db << 22;
6126 flags |= seg->l << 21;
6127 flags |= seg->avl << 20;
6128 flags |= seg->present << 15;
6129 flags |= seg->dpl << 13;
6130 flags |= seg->s << 12;
6131 flags |= seg->type << 8;
6135 static void process_smi_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
6137 struct kvm_segment seg;
6140 kvm_get_segment(vcpu, &seg, n);
6141 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
6144 offset = 0x7f84 + n * 12;
6146 offset = 0x7f2c + (n - 3) * 12;
6148 put_smstate(u32, buf, offset + 8, seg.base);
6149 put_smstate(u32, buf, offset + 4, seg.limit);
6150 put_smstate(u32, buf, offset, process_smi_get_segment_flags(&seg));
6153 #ifdef CONFIG_X86_64
6154 static void process_smi_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
6156 struct kvm_segment seg;
6160 kvm_get_segment(vcpu, &seg, n);
6161 offset = 0x7e00 + n * 16;
6163 flags = process_smi_get_segment_flags(&seg) >> 8;
6164 put_smstate(u16, buf, offset, seg.selector);
6165 put_smstate(u16, buf, offset + 2, flags);
6166 put_smstate(u32, buf, offset + 4, seg.limit);
6167 put_smstate(u64, buf, offset + 8, seg.base);
6171 static void process_smi_save_state_32(struct kvm_vcpu *vcpu, char *buf)
6174 struct kvm_segment seg;
6178 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
6179 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
6180 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
6181 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
6183 for (i = 0; i < 8; i++)
6184 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
6186 kvm_get_dr(vcpu, 6, &val);
6187 put_smstate(u32, buf, 0x7fcc, (u32)val);
6188 kvm_get_dr(vcpu, 7, &val);
6189 put_smstate(u32, buf, 0x7fc8, (u32)val);
6191 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6192 put_smstate(u32, buf, 0x7fc4, seg.selector);
6193 put_smstate(u32, buf, 0x7f64, seg.base);
6194 put_smstate(u32, buf, 0x7f60, seg.limit);
6195 put_smstate(u32, buf, 0x7f5c, process_smi_get_segment_flags(&seg));
6197 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6198 put_smstate(u32, buf, 0x7fc0, seg.selector);
6199 put_smstate(u32, buf, 0x7f80, seg.base);
6200 put_smstate(u32, buf, 0x7f7c, seg.limit);
6201 put_smstate(u32, buf, 0x7f78, process_smi_get_segment_flags(&seg));
6203 kvm_x86_ops->get_gdt(vcpu, &dt);
6204 put_smstate(u32, buf, 0x7f74, dt.address);
6205 put_smstate(u32, buf, 0x7f70, dt.size);
6207 kvm_x86_ops->get_idt(vcpu, &dt);
6208 put_smstate(u32, buf, 0x7f58, dt.address);
6209 put_smstate(u32, buf, 0x7f54, dt.size);
6211 for (i = 0; i < 6; i++)
6212 process_smi_save_seg_32(vcpu, buf, i);
6214 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
6217 put_smstate(u32, buf, 0x7efc, 0x00020000);
6218 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
6221 static void process_smi_save_state_64(struct kvm_vcpu *vcpu, char *buf)
6223 #ifdef CONFIG_X86_64
6225 struct kvm_segment seg;
6229 for (i = 0; i < 16; i++)
6230 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
6232 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
6233 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
6235 kvm_get_dr(vcpu, 6, &val);
6236 put_smstate(u64, buf, 0x7f68, val);
6237 kvm_get_dr(vcpu, 7, &val);
6238 put_smstate(u64, buf, 0x7f60, val);
6240 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
6241 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
6242 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
6244 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
6247 put_smstate(u32, buf, 0x7efc, 0x00020064);
6249 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
6251 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6252 put_smstate(u16, buf, 0x7e90, seg.selector);
6253 put_smstate(u16, buf, 0x7e92, process_smi_get_segment_flags(&seg) >> 8);
6254 put_smstate(u32, buf, 0x7e94, seg.limit);
6255 put_smstate(u64, buf, 0x7e98, seg.base);
6257 kvm_x86_ops->get_idt(vcpu, &dt);
6258 put_smstate(u32, buf, 0x7e84, dt.size);
6259 put_smstate(u64, buf, 0x7e88, dt.address);
6261 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6262 put_smstate(u16, buf, 0x7e70, seg.selector);
6263 put_smstate(u16, buf, 0x7e72, process_smi_get_segment_flags(&seg) >> 8);
6264 put_smstate(u32, buf, 0x7e74, seg.limit);
6265 put_smstate(u64, buf, 0x7e78, seg.base);
6267 kvm_x86_ops->get_gdt(vcpu, &dt);
6268 put_smstate(u32, buf, 0x7e64, dt.size);
6269 put_smstate(u64, buf, 0x7e68, dt.address);
6271 for (i = 0; i < 6; i++)
6272 process_smi_save_seg_64(vcpu, buf, i);
6278 static void process_smi(struct kvm_vcpu *vcpu)
6280 struct kvm_segment cs, ds;
6286 vcpu->arch.smi_pending = true;
6290 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
6291 vcpu->arch.hflags |= HF_SMM_MASK;
6292 memset(buf, 0, 512);
6293 if (guest_cpuid_has_longmode(vcpu))
6294 process_smi_save_state_64(vcpu, buf);
6296 process_smi_save_state_32(vcpu, buf);
6298 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
6300 if (kvm_x86_ops->get_nmi_mask(vcpu))
6301 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
6303 kvm_x86_ops->set_nmi_mask(vcpu, true);
6305 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6306 kvm_rip_write(vcpu, 0x8000);
6308 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
6309 kvm_x86_ops->set_cr0(vcpu, cr0);
6310 vcpu->arch.cr0 = cr0;
6312 kvm_x86_ops->set_cr4(vcpu, 0);
6314 /* Undocumented: IDT limit is set to zero on entry to SMM. */
6315 dt.address = dt.size = 0;
6316 kvm_x86_ops->set_idt(vcpu, &dt);
6318 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
6320 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
6321 cs.base = vcpu->arch.smbase;
6326 cs.limit = ds.limit = 0xffffffff;
6327 cs.type = ds.type = 0x3;
6328 cs.dpl = ds.dpl = 0;
6333 cs.avl = ds.avl = 0;
6334 cs.present = ds.present = 1;
6335 cs.unusable = ds.unusable = 0;
6336 cs.padding = ds.padding = 0;
6338 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
6339 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
6340 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
6341 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
6342 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
6343 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
6345 if (guest_cpuid_has_longmode(vcpu))
6346 kvm_x86_ops->set_efer(vcpu, 0);
6348 kvm_update_cpuid(vcpu);
6349 kvm_mmu_reset_context(vcpu);
6352 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
6354 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
6357 memset(vcpu->arch.eoi_exit_bitmap, 0, 256 / 8);
6359 if (irqchip_split(vcpu->kvm))
6360 kvm_scan_ioapic_routes(vcpu, vcpu->arch.eoi_exit_bitmap);
6362 kvm_x86_ops->sync_pir_to_irr(vcpu);
6363 kvm_ioapic_scan_entry(vcpu, vcpu->arch.eoi_exit_bitmap);
6365 kvm_x86_ops->load_eoi_exitmap(vcpu);
6368 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu)
6370 ++vcpu->stat.tlb_flush;
6371 kvm_x86_ops->tlb_flush(vcpu);
6374 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
6376 struct page *page = NULL;
6378 if (!lapic_in_kernel(vcpu))
6381 if (!kvm_x86_ops->set_apic_access_page_addr)
6384 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6385 if (is_error_page(page))
6387 kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
6390 * Do not pin apic access page in memory, the MMU notifier
6391 * will call us again if it is migrated or swapped out.
6395 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
6397 void kvm_arch_mmu_notifier_invalidate_page(struct kvm *kvm,
6398 unsigned long address)
6401 * The physical address of apic access page is stored in the VMCS.
6402 * Update it when it becomes invalid.
6404 if (address == gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT))
6405 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
6409 * Returns 1 to let vcpu_run() continue the guest execution loop without
6410 * exiting to the userspace. Otherwise, the value will be returned to the
6413 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
6417 dm_request_for_irq_injection(vcpu) &&
6418 kvm_cpu_accept_dm_intr(vcpu);
6420 bool req_immediate_exit = false;
6422 if (vcpu->requests) {
6423 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
6424 kvm_mmu_unload(vcpu);
6425 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
6426 __kvm_migrate_timers(vcpu);
6427 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
6428 kvm_gen_update_masterclock(vcpu->kvm);
6429 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
6430 kvm_gen_kvmclock_update(vcpu);
6431 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
6432 r = kvm_guest_time_update(vcpu);
6436 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
6437 kvm_mmu_sync_roots(vcpu);
6438 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
6439 kvm_vcpu_flush_tlb(vcpu);
6440 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
6441 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
6445 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
6446 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6450 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
6451 vcpu->fpu_active = 0;
6452 kvm_x86_ops->fpu_deactivate(vcpu);
6454 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
6455 /* Page is swapped out. Do synthetic halt */
6456 vcpu->arch.apf.halted = true;
6460 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
6461 record_steal_time(vcpu);
6462 if (kvm_check_request(KVM_REQ_SMI, vcpu))
6464 if (kvm_check_request(KVM_REQ_NMI, vcpu))
6466 if (kvm_check_request(KVM_REQ_PMU, vcpu))
6467 kvm_pmu_handle_event(vcpu);
6468 if (kvm_check_request(KVM_REQ_PMI, vcpu))
6469 kvm_pmu_deliver_pmi(vcpu);
6470 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
6471 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
6472 if (test_bit(vcpu->arch.pending_ioapic_eoi,
6473 (void *) vcpu->arch.eoi_exit_bitmap)) {
6474 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
6475 vcpu->run->eoi.vector =
6476 vcpu->arch.pending_ioapic_eoi;
6481 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
6482 vcpu_scan_ioapic(vcpu);
6483 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
6484 kvm_vcpu_reload_apic_access_page(vcpu);
6485 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
6486 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6487 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
6491 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
6492 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6493 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
6500 * KVM_REQ_EVENT is not set when posted interrupts are set by
6501 * VT-d hardware, so we have to update RVI unconditionally.
6503 if (kvm_lapic_enabled(vcpu)) {
6505 * Update architecture specific hints for APIC
6506 * virtual interrupt delivery.
6508 if (kvm_x86_ops->hwapic_irr_update)
6509 kvm_x86_ops->hwapic_irr_update(vcpu,
6510 kvm_lapic_find_highest_irr(vcpu));
6513 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
6514 kvm_apic_accept_events(vcpu);
6515 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
6520 if (inject_pending_event(vcpu, req_int_win) != 0)
6521 req_immediate_exit = true;
6522 /* enable NMI/IRQ window open exits if needed */
6524 if (vcpu->arch.nmi_pending)
6525 kvm_x86_ops->enable_nmi_window(vcpu);
6526 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
6527 kvm_x86_ops->enable_irq_window(vcpu);
6530 if (kvm_lapic_enabled(vcpu)) {
6531 update_cr8_intercept(vcpu);
6532 kvm_lapic_sync_to_vapic(vcpu);
6536 r = kvm_mmu_reload(vcpu);
6538 goto cancel_injection;
6543 kvm_x86_ops->prepare_guest_switch(vcpu);
6544 if (vcpu->fpu_active)
6545 kvm_load_guest_fpu(vcpu);
6546 vcpu->mode = IN_GUEST_MODE;
6548 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6550 /* We should set ->mode before check ->requests,
6551 * see the comment in make_all_cpus_request.
6553 smp_mb__after_srcu_read_unlock();
6555 local_irq_disable();
6557 if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
6558 || need_resched() || signal_pending(current)) {
6559 vcpu->mode = OUTSIDE_GUEST_MODE;
6563 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6565 goto cancel_injection;
6568 kvm_load_guest_xcr0(vcpu);
6570 if (req_immediate_exit)
6571 smp_send_reschedule(vcpu->cpu);
6573 trace_kvm_entry(vcpu->vcpu_id);
6574 wait_lapic_expire(vcpu);
6575 __kvm_guest_enter();
6577 if (unlikely(vcpu->arch.switch_db_regs)) {
6579 set_debugreg(vcpu->arch.eff_db[0], 0);
6580 set_debugreg(vcpu->arch.eff_db[1], 1);
6581 set_debugreg(vcpu->arch.eff_db[2], 2);
6582 set_debugreg(vcpu->arch.eff_db[3], 3);
6583 set_debugreg(vcpu->arch.dr6, 6);
6584 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6587 kvm_x86_ops->run(vcpu);
6590 * Do this here before restoring debug registers on the host. And
6591 * since we do this before handling the vmexit, a DR access vmexit
6592 * can (a) read the correct value of the debug registers, (b) set
6593 * KVM_DEBUGREG_WONT_EXIT again.
6595 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
6596 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
6597 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
6598 kvm_update_dr0123(vcpu);
6599 kvm_update_dr6(vcpu);
6600 kvm_update_dr7(vcpu);
6601 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6605 * If the guest has used debug registers, at least dr7
6606 * will be disabled while returning to the host.
6607 * If we don't have active breakpoints in the host, we don't
6608 * care about the messed up debug address registers. But if
6609 * we have some of them active, restore the old state.
6611 if (hw_breakpoint_active())
6612 hw_breakpoint_restore();
6614 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
6616 vcpu->mode = OUTSIDE_GUEST_MODE;
6619 kvm_put_guest_xcr0(vcpu);
6621 /* Interrupt is enabled by handle_external_intr() */
6622 kvm_x86_ops->handle_external_intr(vcpu);
6627 * We must have an instruction between local_irq_enable() and
6628 * kvm_guest_exit(), so the timer interrupt isn't delayed by
6629 * the interrupt shadow. The stat.exits increment will do nicely.
6630 * But we need to prevent reordering, hence this barrier():
6638 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6641 * Profile KVM exit RIPs:
6643 if (unlikely(prof_on == KVM_PROFILING)) {
6644 unsigned long rip = kvm_rip_read(vcpu);
6645 profile_hit(KVM_PROFILING, (void *)rip);
6648 if (unlikely(vcpu->arch.tsc_always_catchup))
6649 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6651 if (vcpu->arch.apic_attention)
6652 kvm_lapic_sync_from_vapic(vcpu);
6654 r = kvm_x86_ops->handle_exit(vcpu);
6658 kvm_x86_ops->cancel_injection(vcpu);
6659 if (unlikely(vcpu->arch.apic_attention))
6660 kvm_lapic_sync_from_vapic(vcpu);
6665 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
6667 if (!kvm_arch_vcpu_runnable(vcpu) &&
6668 (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
6669 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6670 kvm_vcpu_block(vcpu);
6671 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6673 if (kvm_x86_ops->post_block)
6674 kvm_x86_ops->post_block(vcpu);
6676 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
6680 kvm_apic_accept_events(vcpu);
6681 switch(vcpu->arch.mp_state) {
6682 case KVM_MP_STATE_HALTED:
6683 vcpu->arch.pv.pv_unhalted = false;
6684 vcpu->arch.mp_state =
6685 KVM_MP_STATE_RUNNABLE;
6686 case KVM_MP_STATE_RUNNABLE:
6687 vcpu->arch.apf.halted = false;
6689 case KVM_MP_STATE_INIT_RECEIVED:
6698 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
6700 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6701 !vcpu->arch.apf.halted);
6704 static int vcpu_run(struct kvm_vcpu *vcpu)
6707 struct kvm *kvm = vcpu->kvm;
6709 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6712 if (kvm_vcpu_running(vcpu)) {
6713 r = vcpu_enter_guest(vcpu);
6715 r = vcpu_block(kvm, vcpu);
6721 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
6722 if (kvm_cpu_has_pending_timer(vcpu))
6723 kvm_inject_pending_timer_irqs(vcpu);
6725 if (dm_request_for_irq_injection(vcpu) &&
6726 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
6728 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
6729 ++vcpu->stat.request_irq_exits;
6733 kvm_check_async_pf_completion(vcpu);
6735 if (signal_pending(current)) {
6737 vcpu->run->exit_reason = KVM_EXIT_INTR;
6738 ++vcpu->stat.signal_exits;
6741 if (need_resched()) {
6742 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6744 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6748 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6753 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
6756 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6757 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
6758 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6759 if (r != EMULATE_DONE)
6764 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
6766 BUG_ON(!vcpu->arch.pio.count);
6768 return complete_emulated_io(vcpu);
6772 * Implements the following, as a state machine:
6776 * for each mmio piece in the fragment
6784 * for each mmio piece in the fragment
6789 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
6791 struct kvm_run *run = vcpu->run;
6792 struct kvm_mmio_fragment *frag;
6795 BUG_ON(!vcpu->mmio_needed);
6797 /* Complete previous fragment */
6798 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
6799 len = min(8u, frag->len);
6800 if (!vcpu->mmio_is_write)
6801 memcpy(frag->data, run->mmio.data, len);
6803 if (frag->len <= 8) {
6804 /* Switch to the next fragment. */
6806 vcpu->mmio_cur_fragment++;
6808 /* Go forward to the next mmio piece. */
6814 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
6815 vcpu->mmio_needed = 0;
6817 /* FIXME: return into emulator if single-stepping. */
6818 if (vcpu->mmio_is_write)
6820 vcpu->mmio_read_completed = 1;
6821 return complete_emulated_io(vcpu);
6824 run->exit_reason = KVM_EXIT_MMIO;
6825 run->mmio.phys_addr = frag->gpa;
6826 if (vcpu->mmio_is_write)
6827 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
6828 run->mmio.len = min(8u, frag->len);
6829 run->mmio.is_write = vcpu->mmio_is_write;
6830 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6835 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
6837 struct fpu *fpu = ¤t->thread.fpu;
6841 fpu__activate_curr(fpu);
6843 if (vcpu->sigset_active)
6844 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
6846 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
6847 kvm_vcpu_block(vcpu);
6848 kvm_apic_accept_events(vcpu);
6849 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
6854 /* re-sync apic's tpr */
6855 if (!lapic_in_kernel(vcpu)) {
6856 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
6862 if (unlikely(vcpu->arch.complete_userspace_io)) {
6863 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
6864 vcpu->arch.complete_userspace_io = NULL;
6869 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
6874 post_kvm_run_save(vcpu);
6875 if (vcpu->sigset_active)
6876 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
6881 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6883 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
6885 * We are here if userspace calls get_regs() in the middle of
6886 * instruction emulation. Registers state needs to be copied
6887 * back from emulation context to vcpu. Userspace shouldn't do
6888 * that usually, but some bad designed PV devices (vmware
6889 * backdoor interface) need this to work
6891 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
6892 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6894 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
6895 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
6896 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
6897 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
6898 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
6899 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
6900 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
6901 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
6902 #ifdef CONFIG_X86_64
6903 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
6904 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
6905 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
6906 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
6907 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
6908 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
6909 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
6910 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
6913 regs->rip = kvm_rip_read(vcpu);
6914 regs->rflags = kvm_get_rflags(vcpu);
6919 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6921 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
6922 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6924 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
6925 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
6926 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
6927 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
6928 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
6929 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
6930 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
6931 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
6932 #ifdef CONFIG_X86_64
6933 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
6934 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
6935 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
6936 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
6937 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
6938 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
6939 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
6940 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
6943 kvm_rip_write(vcpu, regs->rip);
6944 kvm_set_rflags(vcpu, regs->rflags);
6946 vcpu->arch.exception.pending = false;
6948 kvm_make_request(KVM_REQ_EVENT, vcpu);
6953 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
6955 struct kvm_segment cs;
6957 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
6961 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
6963 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
6964 struct kvm_sregs *sregs)
6968 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6969 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6970 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6971 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6972 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6973 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6975 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6976 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6978 kvm_x86_ops->get_idt(vcpu, &dt);
6979 sregs->idt.limit = dt.size;
6980 sregs->idt.base = dt.address;
6981 kvm_x86_ops->get_gdt(vcpu, &dt);
6982 sregs->gdt.limit = dt.size;
6983 sregs->gdt.base = dt.address;
6985 sregs->cr0 = kvm_read_cr0(vcpu);
6986 sregs->cr2 = vcpu->arch.cr2;
6987 sregs->cr3 = kvm_read_cr3(vcpu);
6988 sregs->cr4 = kvm_read_cr4(vcpu);
6989 sregs->cr8 = kvm_get_cr8(vcpu);
6990 sregs->efer = vcpu->arch.efer;
6991 sregs->apic_base = kvm_get_apic_base(vcpu);
6993 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
6995 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
6996 set_bit(vcpu->arch.interrupt.nr,
6997 (unsigned long *)sregs->interrupt_bitmap);
7002 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
7003 struct kvm_mp_state *mp_state)
7005 kvm_apic_accept_events(vcpu);
7006 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
7007 vcpu->arch.pv.pv_unhalted)
7008 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
7010 mp_state->mp_state = vcpu->arch.mp_state;
7015 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
7016 struct kvm_mp_state *mp_state)
7018 if (!kvm_vcpu_has_lapic(vcpu) &&
7019 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
7022 /* INITs are latched while in SMM */
7023 if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
7024 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
7025 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
7028 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
7029 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
7030 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
7032 vcpu->arch.mp_state = mp_state->mp_state;
7033 kvm_make_request(KVM_REQ_EVENT, vcpu);
7037 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
7038 int reason, bool has_error_code, u32 error_code)
7040 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
7043 init_emulate_ctxt(vcpu);
7045 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
7046 has_error_code, error_code);
7049 return EMULATE_FAIL;
7051 kvm_rip_write(vcpu, ctxt->eip);
7052 kvm_set_rflags(vcpu, ctxt->eflags);
7053 kvm_make_request(KVM_REQ_EVENT, vcpu);
7054 return EMULATE_DONE;
7056 EXPORT_SYMBOL_GPL(kvm_task_switch);
7058 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
7059 struct kvm_sregs *sregs)
7061 struct msr_data apic_base_msr;
7062 int mmu_reset_needed = 0;
7063 int pending_vec, max_bits, idx;
7066 if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
7069 dt.size = sregs->idt.limit;
7070 dt.address = sregs->idt.base;
7071 kvm_x86_ops->set_idt(vcpu, &dt);
7072 dt.size = sregs->gdt.limit;
7073 dt.address = sregs->gdt.base;
7074 kvm_x86_ops->set_gdt(vcpu, &dt);
7076 vcpu->arch.cr2 = sregs->cr2;
7077 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
7078 vcpu->arch.cr3 = sregs->cr3;
7079 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
7081 kvm_set_cr8(vcpu, sregs->cr8);
7083 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
7084 kvm_x86_ops->set_efer(vcpu, sregs->efer);
7085 apic_base_msr.data = sregs->apic_base;
7086 apic_base_msr.host_initiated = true;
7087 kvm_set_apic_base(vcpu, &apic_base_msr);
7089 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
7090 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
7091 vcpu->arch.cr0 = sregs->cr0;
7093 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
7094 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
7095 if (sregs->cr4 & X86_CR4_OSXSAVE)
7096 kvm_update_cpuid(vcpu);
7098 idx = srcu_read_lock(&vcpu->kvm->srcu);
7099 if (!is_long_mode(vcpu) && is_pae(vcpu)) {
7100 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
7101 mmu_reset_needed = 1;
7103 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7105 if (mmu_reset_needed)
7106 kvm_mmu_reset_context(vcpu);
7108 max_bits = KVM_NR_INTERRUPTS;
7109 pending_vec = find_first_bit(
7110 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
7111 if (pending_vec < max_bits) {
7112 kvm_queue_interrupt(vcpu, pending_vec, false);
7113 pr_debug("Set back pending irq %d\n", pending_vec);
7116 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7117 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7118 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7119 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7120 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7121 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7123 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7124 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7126 update_cr8_intercept(vcpu);
7128 /* Older userspace won't unhalt the vcpu on reset. */
7129 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
7130 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
7132 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7134 kvm_make_request(KVM_REQ_EVENT, vcpu);
7139 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
7140 struct kvm_guest_debug *dbg)
7142 unsigned long rflags;
7145 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
7147 if (vcpu->arch.exception.pending)
7149 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
7150 kvm_queue_exception(vcpu, DB_VECTOR);
7152 kvm_queue_exception(vcpu, BP_VECTOR);
7156 * Read rflags as long as potentially injected trace flags are still
7159 rflags = kvm_get_rflags(vcpu);
7161 vcpu->guest_debug = dbg->control;
7162 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
7163 vcpu->guest_debug = 0;
7165 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7166 for (i = 0; i < KVM_NR_DB_REGS; ++i)
7167 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
7168 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
7170 for (i = 0; i < KVM_NR_DB_REGS; i++)
7171 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
7173 kvm_update_dr7(vcpu);
7175 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7176 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
7177 get_segment_base(vcpu, VCPU_SREG_CS);
7180 * Trigger an rflags update that will inject or remove the trace
7183 kvm_set_rflags(vcpu, rflags);
7185 kvm_x86_ops->update_bp_intercept(vcpu);
7195 * Translate a guest virtual address to a guest physical address.
7197 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
7198 struct kvm_translation *tr)
7200 unsigned long vaddr = tr->linear_address;
7204 idx = srcu_read_lock(&vcpu->kvm->srcu);
7205 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
7206 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7207 tr->physical_address = gpa;
7208 tr->valid = gpa != UNMAPPED_GVA;
7215 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7217 struct fxregs_state *fxsave =
7218 &vcpu->arch.guest_fpu.state.fxsave;
7220 memcpy(fpu->fpr, fxsave->st_space, 128);
7221 fpu->fcw = fxsave->cwd;
7222 fpu->fsw = fxsave->swd;
7223 fpu->ftwx = fxsave->twd;
7224 fpu->last_opcode = fxsave->fop;
7225 fpu->last_ip = fxsave->rip;
7226 fpu->last_dp = fxsave->rdp;
7227 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
7232 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7234 struct fxregs_state *fxsave =
7235 &vcpu->arch.guest_fpu.state.fxsave;
7237 memcpy(fxsave->st_space, fpu->fpr, 128);
7238 fxsave->cwd = fpu->fcw;
7239 fxsave->swd = fpu->fsw;
7240 fxsave->twd = fpu->ftwx;
7241 fxsave->fop = fpu->last_opcode;
7242 fxsave->rip = fpu->last_ip;
7243 fxsave->rdp = fpu->last_dp;
7244 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
7249 static void fx_init(struct kvm_vcpu *vcpu)
7251 fpstate_init(&vcpu->arch.guest_fpu.state);
7253 vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
7254 host_xcr0 | XSTATE_COMPACTION_ENABLED;
7257 * Ensure guest xcr0 is valid for loading
7259 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
7261 vcpu->arch.cr0 |= X86_CR0_ET;
7264 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
7266 if (vcpu->guest_fpu_loaded)
7270 * Restore all possible states in the guest,
7271 * and assume host would use all available bits.
7272 * Guest xcr0 would be loaded later.
7274 vcpu->guest_fpu_loaded = 1;
7275 __kernel_fpu_begin();
7276 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state);
7280 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
7282 if (!vcpu->guest_fpu_loaded) {
7283 vcpu->fpu_counter = 0;
7287 vcpu->guest_fpu_loaded = 0;
7288 copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
7290 ++vcpu->stat.fpu_reload;
7292 * If using eager FPU mode, or if the guest is a frequent user
7293 * of the FPU, just leave the FPU active for next time.
7294 * Every 255 times fpu_counter rolls over to 0; a guest that uses
7295 * the FPU in bursts will revert to loading it on demand.
7297 if (!vcpu->arch.eager_fpu) {
7298 if (++vcpu->fpu_counter < 5)
7299 kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
7304 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
7306 void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
7308 kvmclock_reset(vcpu);
7310 kvm_x86_ops->vcpu_free(vcpu);
7311 free_cpumask_var(wbinvd_dirty_mask);
7314 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
7317 struct kvm_vcpu *vcpu;
7319 if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
7320 printk_once(KERN_WARNING
7321 "kvm: SMP vm created on host with unstable TSC; "
7322 "guest TSC will not be reliable\n");
7324 vcpu = kvm_x86_ops->vcpu_create(kvm, id);
7329 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
7333 kvm_vcpu_mtrr_init(vcpu);
7334 r = vcpu_load(vcpu);
7337 kvm_vcpu_reset(vcpu, false);
7338 kvm_mmu_setup(vcpu);
7343 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
7345 struct msr_data msr;
7346 struct kvm *kvm = vcpu->kvm;
7348 if (vcpu_load(vcpu))
7351 msr.index = MSR_IA32_TSC;
7352 msr.host_initiated = true;
7353 kvm_write_tsc(vcpu, &msr);
7356 if (!kvmclock_periodic_sync)
7359 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
7360 KVMCLOCK_SYNC_PERIOD);
7363 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
7366 vcpu->arch.apf.msr_val = 0;
7368 r = vcpu_load(vcpu);
7370 kvm_mmu_unload(vcpu);
7373 kvm_x86_ops->vcpu_free(vcpu);
7376 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
7378 vcpu->arch.hflags = 0;
7380 atomic_set(&vcpu->arch.nmi_queued, 0);
7381 vcpu->arch.nmi_pending = 0;
7382 vcpu->arch.nmi_injected = false;
7383 kvm_clear_interrupt_queue(vcpu);
7384 kvm_clear_exception_queue(vcpu);
7386 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
7387 kvm_update_dr0123(vcpu);
7388 vcpu->arch.dr6 = DR6_INIT;
7389 kvm_update_dr6(vcpu);
7390 vcpu->arch.dr7 = DR7_FIXED_1;
7391 kvm_update_dr7(vcpu);
7395 kvm_make_request(KVM_REQ_EVENT, vcpu);
7396 vcpu->arch.apf.msr_val = 0;
7397 vcpu->arch.st.msr_val = 0;
7399 kvmclock_reset(vcpu);
7401 kvm_clear_async_pf_completion_queue(vcpu);
7402 kvm_async_pf_hash_reset(vcpu);
7403 vcpu->arch.apf.halted = false;
7406 kvm_pmu_reset(vcpu);
7407 vcpu->arch.smbase = 0x30000;
7410 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
7411 vcpu->arch.regs_avail = ~0;
7412 vcpu->arch.regs_dirty = ~0;
7414 kvm_x86_ops->vcpu_reset(vcpu, init_event);
7417 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
7419 struct kvm_segment cs;
7421 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7422 cs.selector = vector << 8;
7423 cs.base = vector << 12;
7424 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7425 kvm_rip_write(vcpu, 0);
7428 int kvm_arch_hardware_enable(void)
7431 struct kvm_vcpu *vcpu;
7436 bool stable, backwards_tsc = false;
7438 kvm_shared_msr_cpu_online();
7439 ret = kvm_x86_ops->hardware_enable();
7443 local_tsc = rdtsc();
7444 stable = !check_tsc_unstable();
7445 list_for_each_entry(kvm, &vm_list, vm_list) {
7446 kvm_for_each_vcpu(i, vcpu, kvm) {
7447 if (!stable && vcpu->cpu == smp_processor_id())
7448 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7449 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
7450 backwards_tsc = true;
7451 if (vcpu->arch.last_host_tsc > max_tsc)
7452 max_tsc = vcpu->arch.last_host_tsc;
7458 * Sometimes, even reliable TSCs go backwards. This happens on
7459 * platforms that reset TSC during suspend or hibernate actions, but
7460 * maintain synchronization. We must compensate. Fortunately, we can
7461 * detect that condition here, which happens early in CPU bringup,
7462 * before any KVM threads can be running. Unfortunately, we can't
7463 * bring the TSCs fully up to date with real time, as we aren't yet far
7464 * enough into CPU bringup that we know how much real time has actually
7465 * elapsed; our helper function, get_kernel_ns() will be using boot
7466 * variables that haven't been updated yet.
7468 * So we simply find the maximum observed TSC above, then record the
7469 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
7470 * the adjustment will be applied. Note that we accumulate
7471 * adjustments, in case multiple suspend cycles happen before some VCPU
7472 * gets a chance to run again. In the event that no KVM threads get a
7473 * chance to run, we will miss the entire elapsed period, as we'll have
7474 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
7475 * loose cycle time. This isn't too big a deal, since the loss will be
7476 * uniform across all VCPUs (not to mention the scenario is extremely
7477 * unlikely). It is possible that a second hibernate recovery happens
7478 * much faster than a first, causing the observed TSC here to be
7479 * smaller; this would require additional padding adjustment, which is
7480 * why we set last_host_tsc to the local tsc observed here.
7482 * N.B. - this code below runs only on platforms with reliable TSC,
7483 * as that is the only way backwards_tsc is set above. Also note
7484 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
7485 * have the same delta_cyc adjustment applied if backwards_tsc
7486 * is detected. Note further, this adjustment is only done once,
7487 * as we reset last_host_tsc on all VCPUs to stop this from being
7488 * called multiple times (one for each physical CPU bringup).
7490 * Platforms with unreliable TSCs don't have to deal with this, they
7491 * will be compensated by the logic in vcpu_load, which sets the TSC to
7492 * catchup mode. This will catchup all VCPUs to real time, but cannot
7493 * guarantee that they stay in perfect synchronization.
7495 if (backwards_tsc) {
7496 u64 delta_cyc = max_tsc - local_tsc;
7497 backwards_tsc_observed = true;
7498 list_for_each_entry(kvm, &vm_list, vm_list) {
7499 kvm_for_each_vcpu(i, vcpu, kvm) {
7500 vcpu->arch.tsc_offset_adjustment += delta_cyc;
7501 vcpu->arch.last_host_tsc = local_tsc;
7502 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7506 * We have to disable TSC offset matching.. if you were
7507 * booting a VM while issuing an S4 host suspend....
7508 * you may have some problem. Solving this issue is
7509 * left as an exercise to the reader.
7511 kvm->arch.last_tsc_nsec = 0;
7512 kvm->arch.last_tsc_write = 0;
7519 void kvm_arch_hardware_disable(void)
7521 kvm_x86_ops->hardware_disable();
7522 drop_user_return_notifiers();
7525 int kvm_arch_hardware_setup(void)
7529 r = kvm_x86_ops->hardware_setup();
7533 if (kvm_has_tsc_control) {
7535 * Make sure the user can only configure tsc_khz values that
7536 * fit into a signed integer.
7537 * A min value is not calculated needed because it will always
7538 * be 1 on all machines.
7540 u64 max = min(0x7fffffffULL,
7541 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
7542 kvm_max_guest_tsc_khz = max;
7544 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
7547 kvm_init_msr_list();
7551 void kvm_arch_hardware_unsetup(void)
7553 kvm_x86_ops->hardware_unsetup();
7556 void kvm_arch_check_processor_compat(void *rtn)
7558 kvm_x86_ops->check_processor_compatibility(rtn);
7561 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
7563 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
7565 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
7567 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
7569 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
7572 bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
7574 return irqchip_in_kernel(vcpu->kvm) == lapic_in_kernel(vcpu);
7577 struct static_key kvm_no_apic_vcpu __read_mostly;
7579 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
7585 BUG_ON(vcpu->kvm == NULL);
7588 vcpu->arch.pv.pv_unhalted = false;
7589 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
7590 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_reset_bsp(vcpu))
7591 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7593 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
7595 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
7600 vcpu->arch.pio_data = page_address(page);
7602 kvm_set_tsc_khz(vcpu, max_tsc_khz);
7604 r = kvm_mmu_create(vcpu);
7606 goto fail_free_pio_data;
7608 if (irqchip_in_kernel(kvm)) {
7609 r = kvm_create_lapic(vcpu);
7611 goto fail_mmu_destroy;
7613 static_key_slow_inc(&kvm_no_apic_vcpu);
7615 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
7617 if (!vcpu->arch.mce_banks) {
7619 goto fail_free_lapic;
7621 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
7623 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
7625 goto fail_free_mce_banks;
7630 vcpu->arch.ia32_tsc_adjust_msr = 0x0;
7631 vcpu->arch.pv_time_enabled = false;
7633 vcpu->arch.guest_supported_xcr0 = 0;
7634 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
7636 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
7638 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
7640 kvm_async_pf_hash_reset(vcpu);
7643 vcpu->arch.pending_external_vector = -1;
7647 fail_free_mce_banks:
7648 kfree(vcpu->arch.mce_banks);
7650 kvm_free_lapic(vcpu);
7652 kvm_mmu_destroy(vcpu);
7654 free_page((unsigned long)vcpu->arch.pio_data);
7659 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
7663 kvm_pmu_destroy(vcpu);
7664 kfree(vcpu->arch.mce_banks);
7665 kvm_free_lapic(vcpu);
7666 idx = srcu_read_lock(&vcpu->kvm->srcu);
7667 kvm_mmu_destroy(vcpu);
7668 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7669 free_page((unsigned long)vcpu->arch.pio_data);
7670 if (!lapic_in_kernel(vcpu))
7671 static_key_slow_dec(&kvm_no_apic_vcpu);
7674 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
7676 kvm_x86_ops->sched_in(vcpu, cpu);
7679 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
7684 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
7685 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
7686 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
7687 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
7688 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
7690 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
7691 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
7692 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
7693 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
7694 &kvm->arch.irq_sources_bitmap);
7696 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
7697 mutex_init(&kvm->arch.apic_map_lock);
7698 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
7700 pvclock_update_vm_gtod_copy(kvm);
7702 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
7703 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
7708 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
7711 r = vcpu_load(vcpu);
7713 kvm_mmu_unload(vcpu);
7717 static void kvm_free_vcpus(struct kvm *kvm)
7720 struct kvm_vcpu *vcpu;
7723 * Unpin any mmu pages first.
7725 kvm_for_each_vcpu(i, vcpu, kvm) {
7726 kvm_clear_async_pf_completion_queue(vcpu);
7727 kvm_unload_vcpu_mmu(vcpu);
7729 kvm_for_each_vcpu(i, vcpu, kvm)
7730 kvm_arch_vcpu_free(vcpu);
7732 mutex_lock(&kvm->lock);
7733 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
7734 kvm->vcpus[i] = NULL;
7736 atomic_set(&kvm->online_vcpus, 0);
7737 mutex_unlock(&kvm->lock);
7740 void kvm_arch_sync_events(struct kvm *kvm)
7742 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
7743 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
7744 kvm_free_all_assigned_devices(kvm);
7748 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7752 struct kvm_memslots *slots = kvm_memslots(kvm);
7753 struct kvm_memory_slot *slot, old;
7755 /* Called with kvm->slots_lock held. */
7756 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
7759 slot = id_to_memslot(slots, id);
7761 if (WARN_ON(slot->npages))
7765 * MAP_SHARED to prevent internal slot pages from being moved
7768 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
7769 MAP_SHARED | MAP_ANONYMOUS, 0);
7770 if (IS_ERR((void *)hva))
7771 return PTR_ERR((void *)hva);
7780 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
7781 struct kvm_userspace_memory_region m;
7783 m.slot = id | (i << 16);
7785 m.guest_phys_addr = gpa;
7786 m.userspace_addr = hva;
7787 m.memory_size = size;
7788 r = __kvm_set_memory_region(kvm, &m);
7794 r = vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
7800 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
7802 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7806 mutex_lock(&kvm->slots_lock);
7807 r = __x86_set_memory_region(kvm, id, gpa, size);
7808 mutex_unlock(&kvm->slots_lock);
7812 EXPORT_SYMBOL_GPL(x86_set_memory_region);
7814 void kvm_arch_destroy_vm(struct kvm *kvm)
7816 if (current->mm == kvm->mm) {
7818 * Free memory regions allocated on behalf of userspace,
7819 * unless the the memory map has changed due to process exit
7822 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
7823 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
7824 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
7826 kvm_iommu_unmap_guest(kvm);
7827 kfree(kvm->arch.vpic);
7828 kfree(kvm->arch.vioapic);
7829 kvm_free_vcpus(kvm);
7830 kfree(rcu_dereference_check(kvm->arch.apic_map, 1));
7833 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
7834 struct kvm_memory_slot *dont)
7838 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7839 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
7840 kvfree(free->arch.rmap[i]);
7841 free->arch.rmap[i] = NULL;
7846 if (!dont || free->arch.lpage_info[i - 1] !=
7847 dont->arch.lpage_info[i - 1]) {
7848 kvfree(free->arch.lpage_info[i - 1]);
7849 free->arch.lpage_info[i - 1] = NULL;
7854 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
7855 unsigned long npages)
7859 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7864 lpages = gfn_to_index(slot->base_gfn + npages - 1,
7865 slot->base_gfn, level) + 1;
7867 slot->arch.rmap[i] =
7868 kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
7869 if (!slot->arch.rmap[i])
7874 slot->arch.lpage_info[i - 1] = kvm_kvzalloc(lpages *
7875 sizeof(*slot->arch.lpage_info[i - 1]));
7876 if (!slot->arch.lpage_info[i - 1])
7879 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
7880 slot->arch.lpage_info[i - 1][0].write_count = 1;
7881 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
7882 slot->arch.lpage_info[i - 1][lpages - 1].write_count = 1;
7883 ugfn = slot->userspace_addr >> PAGE_SHIFT;
7885 * If the gfn and userspace address are not aligned wrt each
7886 * other, or if explicitly asked to, disable large page
7887 * support for this slot
7889 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
7890 !kvm_largepages_enabled()) {
7893 for (j = 0; j < lpages; ++j)
7894 slot->arch.lpage_info[i - 1][j].write_count = 1;
7901 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7902 kvfree(slot->arch.rmap[i]);
7903 slot->arch.rmap[i] = NULL;
7907 kvfree(slot->arch.lpage_info[i - 1]);
7908 slot->arch.lpage_info[i - 1] = NULL;
7913 void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
7916 * memslots->generation has been incremented.
7917 * mmio generation may have reached its maximum value.
7919 kvm_mmu_invalidate_mmio_sptes(kvm, slots);
7922 int kvm_arch_prepare_memory_region(struct kvm *kvm,
7923 struct kvm_memory_slot *memslot,
7924 const struct kvm_userspace_memory_region *mem,
7925 enum kvm_mr_change change)
7930 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
7931 struct kvm_memory_slot *new)
7933 /* Still write protect RO slot */
7934 if (new->flags & KVM_MEM_READONLY) {
7935 kvm_mmu_slot_remove_write_access(kvm, new);
7940 * Call kvm_x86_ops dirty logging hooks when they are valid.
7942 * kvm_x86_ops->slot_disable_log_dirty is called when:
7944 * - KVM_MR_CREATE with dirty logging is disabled
7945 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
7947 * The reason is, in case of PML, we need to set D-bit for any slots
7948 * with dirty logging disabled in order to eliminate unnecessary GPA
7949 * logging in PML buffer (and potential PML buffer full VMEXT). This
7950 * guarantees leaving PML enabled during guest's lifetime won't have
7951 * any additonal overhead from PML when guest is running with dirty
7952 * logging disabled for memory slots.
7954 * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
7955 * to dirty logging mode.
7957 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
7959 * In case of write protect:
7961 * Write protect all pages for dirty logging.
7963 * All the sptes including the large sptes which point to this
7964 * slot are set to readonly. We can not create any new large
7965 * spte on this slot until the end of the logging.
7967 * See the comments in fast_page_fault().
7969 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
7970 if (kvm_x86_ops->slot_enable_log_dirty)
7971 kvm_x86_ops->slot_enable_log_dirty(kvm, new);
7973 kvm_mmu_slot_remove_write_access(kvm, new);
7975 if (kvm_x86_ops->slot_disable_log_dirty)
7976 kvm_x86_ops->slot_disable_log_dirty(kvm, new);
7980 void kvm_arch_commit_memory_region(struct kvm *kvm,
7981 const struct kvm_userspace_memory_region *mem,
7982 const struct kvm_memory_slot *old,
7983 const struct kvm_memory_slot *new,
7984 enum kvm_mr_change change)
7986 int nr_mmu_pages = 0;
7988 if (!kvm->arch.n_requested_mmu_pages)
7989 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
7992 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
7995 * Dirty logging tracks sptes in 4k granularity, meaning that large
7996 * sptes have to be split. If live migration is successful, the guest
7997 * in the source machine will be destroyed and large sptes will be
7998 * created in the destination. However, if the guest continues to run
7999 * in the source machine (for example if live migration fails), small
8000 * sptes will remain around and cause bad performance.
8002 * Scan sptes if dirty logging has been stopped, dropping those
8003 * which can be collapsed into a single large-page spte. Later
8004 * page faults will create the large-page sptes.
8006 if ((change != KVM_MR_DELETE) &&
8007 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
8008 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
8009 kvm_mmu_zap_collapsible_sptes(kvm, new);
8012 * Set up write protection and/or dirty logging for the new slot.
8014 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
8015 * been zapped so no dirty logging staff is needed for old slot. For
8016 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
8017 * new and it's also covered when dealing with the new slot.
8019 * FIXME: const-ify all uses of struct kvm_memory_slot.
8021 if (change != KVM_MR_DELETE)
8022 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
8025 void kvm_arch_flush_shadow_all(struct kvm *kvm)
8027 kvm_mmu_invalidate_zap_all_pages(kvm);
8030 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
8031 struct kvm_memory_slot *slot)
8033 kvm_mmu_invalidate_zap_all_pages(kvm);
8036 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
8038 if (!list_empty_careful(&vcpu->async_pf.done))
8041 if (kvm_apic_has_events(vcpu))
8044 if (vcpu->arch.pv.pv_unhalted)
8047 if (atomic_read(&vcpu->arch.nmi_queued))
8050 if (test_bit(KVM_REQ_SMI, &vcpu->requests))
8053 if (kvm_arch_interrupt_allowed(vcpu) &&
8054 kvm_cpu_has_interrupt(vcpu))
8060 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
8062 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
8063 kvm_x86_ops->check_nested_events(vcpu, false);
8065 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
8068 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
8070 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
8073 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
8075 return kvm_x86_ops->interrupt_allowed(vcpu);
8078 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
8080 if (is_64_bit_mode(vcpu))
8081 return kvm_rip_read(vcpu);
8082 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
8083 kvm_rip_read(vcpu));
8085 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
8087 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
8089 return kvm_get_linear_rip(vcpu) == linear_rip;
8091 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
8093 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
8095 unsigned long rflags;
8097 rflags = kvm_x86_ops->get_rflags(vcpu);
8098 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8099 rflags &= ~X86_EFLAGS_TF;
8102 EXPORT_SYMBOL_GPL(kvm_get_rflags);
8104 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8106 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
8107 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
8108 rflags |= X86_EFLAGS_TF;
8109 kvm_x86_ops->set_rflags(vcpu, rflags);
8112 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8114 __kvm_set_rflags(vcpu, rflags);
8115 kvm_make_request(KVM_REQ_EVENT, vcpu);
8117 EXPORT_SYMBOL_GPL(kvm_set_rflags);
8119 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
8123 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
8127 r = kvm_mmu_reload(vcpu);
8131 if (!vcpu->arch.mmu.direct_map &&
8132 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
8135 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
8138 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
8140 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
8143 static inline u32 kvm_async_pf_next_probe(u32 key)
8145 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
8148 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8150 u32 key = kvm_async_pf_hash_fn(gfn);
8152 while (vcpu->arch.apf.gfns[key] != ~0)
8153 key = kvm_async_pf_next_probe(key);
8155 vcpu->arch.apf.gfns[key] = gfn;
8158 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
8161 u32 key = kvm_async_pf_hash_fn(gfn);
8163 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
8164 (vcpu->arch.apf.gfns[key] != gfn &&
8165 vcpu->arch.apf.gfns[key] != ~0); i++)
8166 key = kvm_async_pf_next_probe(key);
8171 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8173 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
8176 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8180 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
8182 vcpu->arch.apf.gfns[i] = ~0;
8184 j = kvm_async_pf_next_probe(j);
8185 if (vcpu->arch.apf.gfns[j] == ~0)
8187 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
8189 * k lies cyclically in ]i,j]
8191 * |....j i.k.| or |.k..j i...|
8193 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
8194 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
8199 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
8202 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
8206 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
8207 struct kvm_async_pf *work)
8209 struct x86_exception fault;
8211 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
8212 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
8214 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
8215 (vcpu->arch.apf.send_user_only &&
8216 kvm_x86_ops->get_cpl(vcpu) == 0))
8217 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
8218 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
8219 fault.vector = PF_VECTOR;
8220 fault.error_code_valid = true;
8221 fault.error_code = 0;
8222 fault.nested_page_fault = false;
8223 fault.address = work->arch.token;
8224 kvm_inject_page_fault(vcpu, &fault);
8228 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
8229 struct kvm_async_pf *work)
8231 struct x86_exception fault;
8233 if (work->wakeup_all)
8234 work->arch.token = ~0; /* broadcast wakeup */
8236 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
8237 trace_kvm_async_pf_ready(work->arch.token, work->gva);
8239 if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
8240 !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
8241 fault.vector = PF_VECTOR;
8242 fault.error_code_valid = true;
8243 fault.error_code = 0;
8244 fault.nested_page_fault = false;
8245 fault.address = work->arch.token;
8246 kvm_inject_page_fault(vcpu, &fault);
8248 vcpu->arch.apf.halted = false;
8249 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8252 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
8254 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
8257 return kvm_can_do_async_pf(vcpu);
8260 void kvm_arch_start_assignment(struct kvm *kvm)
8262 atomic_inc(&kvm->arch.assigned_device_count);
8264 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
8266 void kvm_arch_end_assignment(struct kvm *kvm)
8268 atomic_dec(&kvm->arch.assigned_device_count);
8270 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
8272 bool kvm_arch_has_assigned_device(struct kvm *kvm)
8274 return atomic_read(&kvm->arch.assigned_device_count);
8276 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
8278 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
8280 atomic_inc(&kvm->arch.noncoherent_dma_count);
8282 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
8284 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
8286 atomic_dec(&kvm->arch.noncoherent_dma_count);
8288 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
8290 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
8292 return atomic_read(&kvm->arch.noncoherent_dma_count);
8294 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
8296 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
8297 struct irq_bypass_producer *prod)
8299 struct kvm_kernel_irqfd *irqfd =
8300 container_of(cons, struct kvm_kernel_irqfd, consumer);
8302 if (kvm_x86_ops->update_pi_irte) {
8303 irqfd->producer = prod;
8304 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
8305 prod->irq, irqfd->gsi, 1);
8311 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
8312 struct irq_bypass_producer *prod)
8315 struct kvm_kernel_irqfd *irqfd =
8316 container_of(cons, struct kvm_kernel_irqfd, consumer);
8318 if (!kvm_x86_ops->update_pi_irte) {
8319 WARN_ON(irqfd->producer != NULL);
8323 WARN_ON(irqfd->producer != prod);
8324 irqfd->producer = NULL;
8327 * When producer of consumer is unregistered, we change back to
8328 * remapped mode, so we can re-use the current implementation
8329 * when the irq is masked/disabed or the consumer side (KVM
8330 * int this case doesn't want to receive the interrupts.
8332 ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
8334 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
8335 " fails: %d\n", irqfd->consumer.token, ret);
8338 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
8339 uint32_t guest_irq, bool set)
8341 if (!kvm_x86_ops->update_pi_irte)
8344 return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
8347 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
8348 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
8349 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
8350 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
8351 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
8352 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
8353 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
8354 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
8355 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
8356 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
8357 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
8358 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
8359 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
8360 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
8361 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
8362 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
8363 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);