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 <linux/nospec.h>
57 #include <trace/events/kvm.h>
59 #define CREATE_TRACE_POINTS
62 #include <asm/debugreg.h>
66 #include <linux/kernel_stat.h>
67 #include <asm/fpu/internal.h> /* Ugh! */
68 #include <asm/pvclock.h>
69 #include <asm/div64.h>
70 #include <asm/irq_remapping.h>
72 #define MAX_IO_MSRS 256
73 #define KVM_MAX_MCE_BANKS 32
74 #define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
76 #define emul_to_vcpu(ctxt) \
77 container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
80 * - enable syscall per default because its emulated by KVM
81 * - enable LME and LMA per default on 64 bit KVM
85 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
87 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
90 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
91 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
93 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
94 static void process_nmi(struct kvm_vcpu *vcpu);
95 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
97 struct kvm_x86_ops *kvm_x86_ops __read_mostly;
98 EXPORT_SYMBOL_GPL(kvm_x86_ops);
100 static bool __read_mostly ignore_msrs = 0;
101 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
103 unsigned int min_timer_period_us = 500;
104 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
106 static bool __read_mostly kvmclock_periodic_sync = true;
107 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
109 bool __read_mostly kvm_has_tsc_control;
110 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
111 u32 __read_mostly kvm_max_guest_tsc_khz;
112 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
113 u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
114 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
115 u64 __read_mostly kvm_max_tsc_scaling_ratio;
116 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
117 static u64 __read_mostly kvm_default_tsc_scaling_ratio;
119 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
120 static u32 __read_mostly tsc_tolerance_ppm = 250;
121 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
123 /* lapic timer advance (tscdeadline mode only) in nanoseconds */
124 unsigned int __read_mostly lapic_timer_advance_ns = 0;
125 module_param(lapic_timer_advance_ns, uint, S_IRUGO | S_IWUSR);
127 static bool __read_mostly backwards_tsc_observed = false;
129 #define KVM_NR_SHARED_MSRS 16
131 struct kvm_shared_msrs_global {
133 u32 msrs[KVM_NR_SHARED_MSRS];
136 struct kvm_shared_msrs {
137 struct user_return_notifier urn;
139 struct kvm_shared_msr_values {
142 } values[KVM_NR_SHARED_MSRS];
145 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
146 static struct kvm_shared_msrs __percpu *shared_msrs;
148 struct kvm_stats_debugfs_item debugfs_entries[] = {
149 { "pf_fixed", VCPU_STAT(pf_fixed) },
150 { "pf_guest", VCPU_STAT(pf_guest) },
151 { "tlb_flush", VCPU_STAT(tlb_flush) },
152 { "invlpg", VCPU_STAT(invlpg) },
153 { "exits", VCPU_STAT(exits) },
154 { "io_exits", VCPU_STAT(io_exits) },
155 { "mmio_exits", VCPU_STAT(mmio_exits) },
156 { "signal_exits", VCPU_STAT(signal_exits) },
157 { "irq_window", VCPU_STAT(irq_window_exits) },
158 { "nmi_window", VCPU_STAT(nmi_window_exits) },
159 { "halt_exits", VCPU_STAT(halt_exits) },
160 { "halt_successful_poll", VCPU_STAT(halt_successful_poll) },
161 { "halt_attempted_poll", VCPU_STAT(halt_attempted_poll) },
162 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
163 { "hypercalls", VCPU_STAT(hypercalls) },
164 { "request_irq", VCPU_STAT(request_irq_exits) },
165 { "irq_exits", VCPU_STAT(irq_exits) },
166 { "host_state_reload", VCPU_STAT(host_state_reload) },
167 { "efer_reload", VCPU_STAT(efer_reload) },
168 { "fpu_reload", VCPU_STAT(fpu_reload) },
169 { "insn_emulation", VCPU_STAT(insn_emulation) },
170 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
171 { "irq_injections", VCPU_STAT(irq_injections) },
172 { "nmi_injections", VCPU_STAT(nmi_injections) },
173 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
174 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
175 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
176 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
177 { "mmu_flooded", VM_STAT(mmu_flooded) },
178 { "mmu_recycled", VM_STAT(mmu_recycled) },
179 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
180 { "mmu_unsync", VM_STAT(mmu_unsync) },
181 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
182 { "largepages", VM_STAT(lpages) },
186 u64 __read_mostly host_xcr0;
188 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
190 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
193 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
194 vcpu->arch.apf.gfns[i] = ~0;
197 static void kvm_on_user_return(struct user_return_notifier *urn)
200 struct kvm_shared_msrs *locals
201 = container_of(urn, struct kvm_shared_msrs, urn);
202 struct kvm_shared_msr_values *values;
206 * Disabling irqs at this point since the following code could be
207 * interrupted and executed through kvm_arch_hardware_disable()
209 local_irq_save(flags);
210 if (locals->registered) {
211 locals->registered = false;
212 user_return_notifier_unregister(urn);
214 local_irq_restore(flags);
215 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
216 values = &locals->values[slot];
217 if (values->host != values->curr) {
218 wrmsrl(shared_msrs_global.msrs[slot], values->host);
219 values->curr = values->host;
224 static void shared_msr_update(unsigned slot, u32 msr)
227 unsigned int cpu = smp_processor_id();
228 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
230 /* only read, and nobody should modify it at this time,
231 * so don't need lock */
232 if (slot >= shared_msrs_global.nr) {
233 printk(KERN_ERR "kvm: invalid MSR slot!");
236 rdmsrl_safe(msr, &value);
237 smsr->values[slot].host = value;
238 smsr->values[slot].curr = value;
241 void kvm_define_shared_msr(unsigned slot, u32 msr)
243 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
244 shared_msrs_global.msrs[slot] = msr;
245 if (slot >= shared_msrs_global.nr)
246 shared_msrs_global.nr = slot + 1;
248 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
250 static void kvm_shared_msr_cpu_online(void)
254 for (i = 0; i < shared_msrs_global.nr; ++i)
255 shared_msr_update(i, shared_msrs_global.msrs[i]);
258 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
260 unsigned int cpu = smp_processor_id();
261 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
264 value = (value & mask) | (smsr->values[slot].host & ~mask);
265 if (value == smsr->values[slot].curr)
267 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
271 smsr->values[slot].curr = value;
272 if (!smsr->registered) {
273 smsr->urn.on_user_return = kvm_on_user_return;
274 user_return_notifier_register(&smsr->urn);
275 smsr->registered = true;
279 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
281 static void drop_user_return_notifiers(void)
283 unsigned int cpu = smp_processor_id();
284 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
286 if (smsr->registered)
287 kvm_on_user_return(&smsr->urn);
290 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
292 return vcpu->arch.apic_base;
294 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
296 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
298 u64 old_state = vcpu->arch.apic_base &
299 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
300 u64 new_state = msr_info->data &
301 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
302 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) |
303 0x2ff | (guest_cpuid_has_x2apic(vcpu) ? 0 : X2APIC_ENABLE);
305 if (!msr_info->host_initiated &&
306 ((msr_info->data & reserved_bits) != 0 ||
307 new_state == X2APIC_ENABLE ||
308 (new_state == MSR_IA32_APICBASE_ENABLE &&
309 old_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) ||
310 (new_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE) &&
314 kvm_lapic_set_base(vcpu, msr_info->data);
317 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
319 asmlinkage __visible void kvm_spurious_fault(void)
321 /* Fault while not rebooting. We want the trace. */
324 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
326 #define EXCPT_BENIGN 0
327 #define EXCPT_CONTRIBUTORY 1
330 static int exception_class(int vector)
340 return EXCPT_CONTRIBUTORY;
347 #define EXCPT_FAULT 0
349 #define EXCPT_ABORT 2
350 #define EXCPT_INTERRUPT 3
352 static int exception_type(int vector)
356 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
357 return EXCPT_INTERRUPT;
361 /* #DB is trap, as instruction watchpoints are handled elsewhere */
362 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
365 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
368 /* Reserved exceptions will result in fault */
372 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
373 unsigned nr, bool has_error, u32 error_code,
379 kvm_make_request(KVM_REQ_EVENT, vcpu);
381 if (!vcpu->arch.exception.pending) {
383 if (has_error && !is_protmode(vcpu))
385 vcpu->arch.exception.pending = true;
386 vcpu->arch.exception.has_error_code = has_error;
387 vcpu->arch.exception.nr = nr;
388 vcpu->arch.exception.error_code = error_code;
389 vcpu->arch.exception.reinject = reinject;
393 /* to check exception */
394 prev_nr = vcpu->arch.exception.nr;
395 if (prev_nr == DF_VECTOR) {
396 /* triple fault -> shutdown */
397 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
400 class1 = exception_class(prev_nr);
401 class2 = exception_class(nr);
402 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
403 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
404 /* generate double fault per SDM Table 5-5 */
405 vcpu->arch.exception.pending = true;
406 vcpu->arch.exception.has_error_code = true;
407 vcpu->arch.exception.nr = DF_VECTOR;
408 vcpu->arch.exception.error_code = 0;
410 /* replace previous exception with a new one in a hope
411 that instruction re-execution will regenerate lost
416 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
418 kvm_multiple_exception(vcpu, nr, false, 0, false);
420 EXPORT_SYMBOL_GPL(kvm_queue_exception);
422 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
424 kvm_multiple_exception(vcpu, nr, false, 0, true);
426 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
428 void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
431 kvm_inject_gp(vcpu, 0);
433 kvm_x86_ops->skip_emulated_instruction(vcpu);
435 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
437 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
439 ++vcpu->stat.pf_guest;
440 vcpu->arch.cr2 = fault->address;
441 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
443 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
445 static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
447 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
448 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
450 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
452 return fault->nested_page_fault;
455 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
457 atomic_inc(&vcpu->arch.nmi_queued);
458 kvm_make_request(KVM_REQ_NMI, vcpu);
460 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
462 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
464 kvm_multiple_exception(vcpu, nr, true, error_code, false);
466 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
468 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
470 kvm_multiple_exception(vcpu, nr, true, error_code, true);
472 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
475 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
476 * a #GP and return false.
478 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
480 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
482 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
485 EXPORT_SYMBOL_GPL(kvm_require_cpl);
487 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
489 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
492 kvm_queue_exception(vcpu, UD_VECTOR);
495 EXPORT_SYMBOL_GPL(kvm_require_dr);
498 * This function will be used to read from the physical memory of the currently
499 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
500 * can read from guest physical or from the guest's guest physical memory.
502 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
503 gfn_t ngfn, void *data, int offset, int len,
506 struct x86_exception exception;
510 ngpa = gfn_to_gpa(ngfn);
511 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
512 if (real_gfn == UNMAPPED_GVA)
515 real_gfn = gpa_to_gfn(real_gfn);
517 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
519 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
521 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
522 void *data, int offset, int len, u32 access)
524 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
525 data, offset, len, access);
528 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
530 return rsvd_bits(cpuid_maxphyaddr(vcpu), 63) | rsvd_bits(5, 8) |
535 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
537 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
539 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
540 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
543 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
545 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
546 offset * sizeof(u64), sizeof(pdpte),
547 PFERR_USER_MASK|PFERR_WRITE_MASK);
552 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
553 if (is_present_gpte(pdpte[i]) &&
554 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
561 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
562 __set_bit(VCPU_EXREG_PDPTR,
563 (unsigned long *)&vcpu->arch.regs_avail);
564 __set_bit(VCPU_EXREG_PDPTR,
565 (unsigned long *)&vcpu->arch.regs_dirty);
570 EXPORT_SYMBOL_GPL(load_pdptrs);
572 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
574 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
580 if (is_long_mode(vcpu) || !is_pae(vcpu) || !is_paging(vcpu))
583 if (!test_bit(VCPU_EXREG_PDPTR,
584 (unsigned long *)&vcpu->arch.regs_avail))
587 gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
588 offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
589 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
590 PFERR_USER_MASK | PFERR_WRITE_MASK);
593 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
599 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
601 unsigned long old_cr0 = kvm_read_cr0(vcpu);
602 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
607 if (cr0 & 0xffffffff00000000UL)
611 cr0 &= ~CR0_RESERVED_BITS;
613 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
616 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
619 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
621 if ((vcpu->arch.efer & EFER_LME)) {
626 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
631 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
636 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
639 kvm_x86_ops->set_cr0(vcpu, cr0);
641 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
642 kvm_clear_async_pf_completion_queue(vcpu);
643 kvm_async_pf_hash_reset(vcpu);
646 if ((cr0 ^ old_cr0) & update_bits)
647 kvm_mmu_reset_context(vcpu);
649 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
650 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
651 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
652 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
656 EXPORT_SYMBOL_GPL(kvm_set_cr0);
658 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
660 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
662 EXPORT_SYMBOL_GPL(kvm_lmsw);
664 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
666 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
667 !vcpu->guest_xcr0_loaded) {
668 /* kvm_set_xcr() also depends on this */
669 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
670 vcpu->guest_xcr0_loaded = 1;
674 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
676 if (vcpu->guest_xcr0_loaded) {
677 if (vcpu->arch.xcr0 != host_xcr0)
678 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
679 vcpu->guest_xcr0_loaded = 0;
683 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
686 u64 old_xcr0 = vcpu->arch.xcr0;
689 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
690 if (index != XCR_XFEATURE_ENABLED_MASK)
692 if (!(xcr0 & XFEATURE_MASK_FP))
694 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
698 * Do not allow the guest to set bits that we do not support
699 * saving. However, xcr0 bit 0 is always set, even if the
700 * emulated CPU does not support XSAVE (see fx_init).
702 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
703 if (xcr0 & ~valid_bits)
706 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
707 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
710 if (xcr0 & XFEATURE_MASK_AVX512) {
711 if (!(xcr0 & XFEATURE_MASK_YMM))
713 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
716 vcpu->arch.xcr0 = xcr0;
718 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
719 kvm_update_cpuid(vcpu);
723 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
725 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
726 __kvm_set_xcr(vcpu, index, xcr)) {
727 kvm_inject_gp(vcpu, 0);
732 EXPORT_SYMBOL_GPL(kvm_set_xcr);
734 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
736 unsigned long old_cr4 = kvm_read_cr4(vcpu);
737 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
738 X86_CR4_SMEP | X86_CR4_SMAP;
740 if (cr4 & CR4_RESERVED_BITS)
743 if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
746 if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
749 if (!guest_cpuid_has_smap(vcpu) && (cr4 & X86_CR4_SMAP))
752 if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_FSGSBASE))
755 if (is_long_mode(vcpu)) {
756 if (!(cr4 & X86_CR4_PAE))
758 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
759 && ((cr4 ^ old_cr4) & pdptr_bits)
760 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
764 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
765 if (!guest_cpuid_has_pcid(vcpu))
768 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
769 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_ASID_MASK) ||
774 if (kvm_x86_ops->set_cr4(vcpu, cr4))
777 if (((cr4 ^ old_cr4) & pdptr_bits) ||
778 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
779 kvm_mmu_reset_context(vcpu);
781 if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
782 kvm_update_cpuid(vcpu);
786 EXPORT_SYMBOL_GPL(kvm_set_cr4);
788 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
791 cr3 &= ~CR3_PCID_INVD;
794 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
795 kvm_mmu_sync_roots(vcpu);
796 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
800 if (is_long_mode(vcpu)) {
801 if (cr3 & CR3_L_MODE_RESERVED_BITS)
803 } else if (is_pae(vcpu) && is_paging(vcpu) &&
804 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
807 vcpu->arch.cr3 = cr3;
808 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
809 kvm_mmu_new_cr3(vcpu);
812 EXPORT_SYMBOL_GPL(kvm_set_cr3);
814 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
816 if (cr8 & CR8_RESERVED_BITS)
818 if (lapic_in_kernel(vcpu))
819 kvm_lapic_set_tpr(vcpu, cr8);
821 vcpu->arch.cr8 = cr8;
824 EXPORT_SYMBOL_GPL(kvm_set_cr8);
826 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
828 if (lapic_in_kernel(vcpu))
829 return kvm_lapic_get_cr8(vcpu);
831 return vcpu->arch.cr8;
833 EXPORT_SYMBOL_GPL(kvm_get_cr8);
835 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
839 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
840 for (i = 0; i < KVM_NR_DB_REGS; i++)
841 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
842 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
846 static void kvm_update_dr6(struct kvm_vcpu *vcpu)
848 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
849 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
852 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
856 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
857 dr7 = vcpu->arch.guest_debug_dr7;
859 dr7 = vcpu->arch.dr7;
860 kvm_x86_ops->set_dr7(vcpu, dr7);
861 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
862 if (dr7 & DR7_BP_EN_MASK)
863 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
866 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
868 u64 fixed = DR6_FIXED_1;
870 if (!guest_cpuid_has_rtm(vcpu))
875 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
877 size_t size = ARRAY_SIZE(vcpu->arch.db);
881 vcpu->arch.db[array_index_nospec(dr, size)] = val;
882 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
883 vcpu->arch.eff_db[dr] = val;
888 if (val & 0xffffffff00000000ULL)
890 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
891 kvm_update_dr6(vcpu);
896 if (val & 0xffffffff00000000ULL)
898 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
899 kvm_update_dr7(vcpu);
906 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
908 if (__kvm_set_dr(vcpu, dr, val)) {
909 kvm_inject_gp(vcpu, 0);
914 EXPORT_SYMBOL_GPL(kvm_set_dr);
916 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
918 size_t size = ARRAY_SIZE(vcpu->arch.db);
922 *val = vcpu->arch.db[array_index_nospec(dr, size)];
927 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
928 *val = vcpu->arch.dr6;
930 *val = kvm_x86_ops->get_dr6(vcpu);
935 *val = vcpu->arch.dr7;
940 EXPORT_SYMBOL_GPL(kvm_get_dr);
942 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
944 u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
948 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
951 kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
952 kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
955 EXPORT_SYMBOL_GPL(kvm_rdpmc);
958 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
959 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
961 * This list is modified at module load time to reflect the
962 * capabilities of the host cpu. This capabilities test skips MSRs that are
963 * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
964 * may depend on host virtualization features rather than host cpu features.
967 static u32 msrs_to_save[] = {
968 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
971 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
973 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
974 MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
975 MSR_IA32_SPEC_CTRL, MSR_IA32_ARCH_CAPABILITIES
978 static unsigned num_msrs_to_save;
980 static u32 emulated_msrs[] = {
981 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
982 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
983 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
984 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
985 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
986 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
989 HV_X64_MSR_VP_RUNTIME,
990 HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
994 MSR_IA32_TSCDEADLINE,
995 MSR_IA32_MISC_ENABLE,
999 MSR_AMD64_VIRT_SPEC_CTRL,
1002 static unsigned num_emulated_msrs;
1004 u64 kvm_get_arch_capabilities(void)
1008 rdmsrl_safe(MSR_IA32_ARCH_CAPABILITIES, &data);
1010 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1011 data |= ARCH_CAP_RDCL_NO;
1012 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1013 data |= ARCH_CAP_SSB_NO;
1014 if (!boot_cpu_has_bug(X86_BUG_MDS))
1015 data |= ARCH_CAP_MDS_NO;
1018 * On TAA affected systems, export MDS_NO=0 when:
1019 * - TSX is enabled on the host, i.e. X86_FEATURE_RTM=1.
1020 * - Updated microcode is present. This is detected by
1021 * the presence of ARCH_CAP_TSX_CTRL_MSR and ensures
1022 * that VERW clears CPU buffers.
1024 * When MDS_NO=0 is exported, guests deploy clear CPU buffer
1025 * mitigation and don't complain:
1027 * "Vulnerable: Clear CPU buffers attempted, no microcode"
1029 * If TSX is disabled on the system, guests are also mitigated against
1030 * TAA and clear CPU buffer mitigation is not required for guests.
1032 if (!boot_cpu_has(X86_FEATURE_RTM))
1033 data &= ~ARCH_CAP_TAA_NO;
1034 else if (!boot_cpu_has_bug(X86_BUG_TAA))
1035 data |= ARCH_CAP_TAA_NO;
1036 else if (data & ARCH_CAP_TSX_CTRL_MSR)
1037 data &= ~ARCH_CAP_MDS_NO;
1039 /* KVM does not emulate MSR_IA32_TSX_CTRL. */
1040 data &= ~ARCH_CAP_TSX_CTRL_MSR;
1044 EXPORT_SYMBOL_GPL(kvm_get_arch_capabilities);
1046 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1048 if (efer & EFER_FFXSR) {
1049 struct kvm_cpuid_entry2 *feat;
1051 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
1052 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
1056 if (efer & EFER_SVME) {
1057 struct kvm_cpuid_entry2 *feat;
1059 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
1060 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
1067 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1069 if (efer & efer_reserved_bits)
1072 return __kvm_valid_efer(vcpu, efer);
1074 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1076 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1078 u64 old_efer = vcpu->arch.efer;
1079 u64 efer = msr_info->data;
1081 if (efer & efer_reserved_bits)
1084 if (!msr_info->host_initiated) {
1085 if (!__kvm_valid_efer(vcpu, efer))
1088 if (is_paging(vcpu) &&
1089 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1094 efer |= vcpu->arch.efer & EFER_LMA;
1096 kvm_x86_ops->set_efer(vcpu, efer);
1098 /* Update reserved bits */
1099 if ((efer ^ old_efer) & EFER_NX)
1100 kvm_mmu_reset_context(vcpu);
1105 void kvm_enable_efer_bits(u64 mask)
1107 efer_reserved_bits &= ~mask;
1109 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1112 * Writes msr value into into the appropriate "register".
1113 * Returns 0 on success, non-0 otherwise.
1114 * Assumes vcpu_load() was already called.
1116 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
1118 switch (msr->index) {
1121 case MSR_KERNEL_GS_BASE:
1124 if (is_noncanonical_address(msr->data))
1127 case MSR_IA32_SYSENTER_EIP:
1128 case MSR_IA32_SYSENTER_ESP:
1130 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1131 * non-canonical address is written on Intel but not on
1132 * AMD (which ignores the top 32-bits, because it does
1133 * not implement 64-bit SYSENTER).
1135 * 64-bit code should hence be able to write a non-canonical
1136 * value on AMD. Making the address canonical ensures that
1137 * vmentry does not fail on Intel after writing a non-canonical
1138 * value, and that something deterministic happens if the guest
1139 * invokes 64-bit SYSENTER.
1141 msr->data = get_canonical(msr->data);
1143 return kvm_x86_ops->set_msr(vcpu, msr);
1145 EXPORT_SYMBOL_GPL(kvm_set_msr);
1148 * Adapt set_msr() to msr_io()'s calling convention
1150 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1152 struct msr_data msr;
1156 msr.host_initiated = true;
1157 r = kvm_get_msr(vcpu, &msr);
1165 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1167 struct msr_data msr;
1171 msr.host_initiated = true;
1172 return kvm_set_msr(vcpu, &msr);
1175 #ifdef CONFIG_X86_64
1176 struct pvclock_gtod_data {
1179 struct { /* extract of a clocksource struct */
1191 static struct pvclock_gtod_data pvclock_gtod_data;
1193 static void update_pvclock_gtod(struct timekeeper *tk)
1195 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1198 boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
1200 write_seqcount_begin(&vdata->seq);
1202 /* copy pvclock gtod data */
1203 vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
1204 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1205 vdata->clock.mask = tk->tkr_mono.mask;
1206 vdata->clock.mult = tk->tkr_mono.mult;
1207 vdata->clock.shift = tk->tkr_mono.shift;
1209 vdata->boot_ns = boot_ns;
1210 vdata->nsec_base = tk->tkr_mono.xtime_nsec;
1212 write_seqcount_end(&vdata->seq);
1216 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1219 * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
1220 * vcpu_enter_guest. This function is only called from
1221 * the physical CPU that is running vcpu.
1223 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1226 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1230 struct pvclock_wall_clock wc;
1231 struct timespec boot;
1236 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1241 ++version; /* first time write, random junk */
1245 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1248 * The guest calculates current wall clock time by adding
1249 * system time (updated by kvm_guest_time_update below) to the
1250 * wall clock specified here. guest system time equals host
1251 * system time for us, thus we must fill in host boot time here.
1255 if (kvm->arch.kvmclock_offset) {
1256 struct timespec ts = ns_to_timespec(kvm->arch.kvmclock_offset);
1257 boot = timespec_sub(boot, ts);
1259 wc.sec = boot.tv_sec;
1260 wc.nsec = boot.tv_nsec;
1261 wc.version = version;
1263 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1266 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1269 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1271 uint32_t quotient, remainder;
1273 /* Don't try to replace with do_div(), this one calculates
1274 * "(dividend << 32) / divisor" */
1276 : "=a" (quotient), "=d" (remainder)
1277 : "0" (0), "1" (dividend), "r" (divisor) );
1281 static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
1282 s8 *pshift, u32 *pmultiplier)
1289 tps64 = base_khz * 1000LL;
1290 scaled64 = scaled_khz * 1000LL;
1291 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1296 tps32 = (uint32_t)tps64;
1297 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1298 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1306 *pmultiplier = div_frac(scaled64, tps32);
1308 pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
1309 __func__, base_khz, scaled_khz, shift, *pmultiplier);
1312 #ifdef CONFIG_X86_64
1313 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1316 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1317 static unsigned long max_tsc_khz;
1319 static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
1321 return pvclock_scale_delta(nsec, vcpu->arch.virtual_tsc_mult,
1322 vcpu->arch.virtual_tsc_shift);
1325 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1327 u64 v = (u64)khz * (1000000 + ppm);
1332 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1336 /* Guest TSC same frequency as host TSC? */
1338 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1342 /* TSC scaling supported? */
1343 if (!kvm_has_tsc_control) {
1344 if (user_tsc_khz > tsc_khz) {
1345 vcpu->arch.tsc_catchup = 1;
1346 vcpu->arch.tsc_always_catchup = 1;
1349 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
1354 /* TSC scaling required - calculate ratio */
1355 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1356 user_tsc_khz, tsc_khz);
1358 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1359 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1364 vcpu->arch.tsc_scaling_ratio = ratio;
1368 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
1370 u32 thresh_lo, thresh_hi;
1371 int use_scaling = 0;
1373 /* tsc_khz can be zero if TSC calibration fails */
1374 if (this_tsc_khz == 0) {
1375 /* set tsc_scaling_ratio to a safe value */
1376 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1380 /* Compute a scale to convert nanoseconds in TSC cycles */
1381 kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
1382 &vcpu->arch.virtual_tsc_shift,
1383 &vcpu->arch.virtual_tsc_mult);
1384 vcpu->arch.virtual_tsc_khz = this_tsc_khz;
1387 * Compute the variation in TSC rate which is acceptable
1388 * within the range of tolerance and decide if the
1389 * rate being applied is within that bounds of the hardware
1390 * rate. If so, no scaling or compensation need be done.
1392 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1393 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1394 if (this_tsc_khz < thresh_lo || this_tsc_khz > thresh_hi) {
1395 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", this_tsc_khz, thresh_lo, thresh_hi);
1398 return set_tsc_khz(vcpu, this_tsc_khz, use_scaling);
1401 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1403 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1404 vcpu->arch.virtual_tsc_mult,
1405 vcpu->arch.virtual_tsc_shift);
1406 tsc += vcpu->arch.this_tsc_write;
1410 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1412 #ifdef CONFIG_X86_64
1414 struct kvm_arch *ka = &vcpu->kvm->arch;
1415 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1417 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1418 atomic_read(&vcpu->kvm->online_vcpus));
1421 * Once the masterclock is enabled, always perform request in
1422 * order to update it.
1424 * In order to enable masterclock, the host clocksource must be TSC
1425 * and the vcpus need to have matched TSCs. When that happens,
1426 * perform request to enable masterclock.
1428 if (ka->use_master_clock ||
1429 (gtod->clock.vclock_mode == VCLOCK_TSC && vcpus_matched))
1430 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1432 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1433 atomic_read(&vcpu->kvm->online_vcpus),
1434 ka->use_master_clock, gtod->clock.vclock_mode);
1438 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1440 u64 curr_offset = kvm_x86_ops->read_tsc_offset(vcpu);
1441 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1445 * Multiply tsc by a fixed point number represented by ratio.
1447 * The most significant 64-N bits (mult) of ratio represent the
1448 * integral part of the fixed point number; the remaining N bits
1449 * (frac) represent the fractional part, ie. ratio represents a fixed
1450 * point number (mult + frac * 2^(-N)).
1452 * N equals to kvm_tsc_scaling_ratio_frac_bits.
1454 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1456 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1459 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1462 u64 ratio = vcpu->arch.tsc_scaling_ratio;
1464 if (ratio != kvm_default_tsc_scaling_ratio)
1465 _tsc = __scale_tsc(ratio, tsc);
1469 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1471 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1475 tsc = kvm_scale_tsc(vcpu, rdtsc());
1477 return target_tsc - tsc;
1480 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1482 return kvm_x86_ops->read_l1_tsc(vcpu, kvm_scale_tsc(vcpu, host_tsc));
1484 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1486 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1488 struct kvm *kvm = vcpu->kvm;
1489 u64 offset, ns, elapsed;
1490 unsigned long flags;
1493 bool already_matched;
1494 u64 data = msr->data;
1496 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1497 offset = kvm_compute_tsc_offset(vcpu, data);
1498 ns = get_kernel_ns();
1499 elapsed = ns - kvm->arch.last_tsc_nsec;
1501 if (vcpu->arch.virtual_tsc_khz) {
1504 /* n.b - signed multiplication and division required */
1505 usdiff = data - kvm->arch.last_tsc_write;
1506 #ifdef CONFIG_X86_64
1507 usdiff = (usdiff * 1000) / vcpu->arch.virtual_tsc_khz;
1509 /* do_div() only does unsigned */
1510 asm("1: idivl %[divisor]\n"
1511 "2: xor %%edx, %%edx\n"
1512 " movl $0, %[faulted]\n"
1514 ".section .fixup,\"ax\"\n"
1515 "4: movl $1, %[faulted]\n"
1519 _ASM_EXTABLE(1b, 4b)
1521 : "=A"(usdiff), [faulted] "=r" (faulted)
1522 : "A"(usdiff * 1000), [divisor] "rm"(vcpu->arch.virtual_tsc_khz));
1525 do_div(elapsed, 1000);
1530 /* idivl overflow => difference is larger than USEC_PER_SEC */
1532 usdiff = USEC_PER_SEC;
1534 usdiff = USEC_PER_SEC; /* disable TSC match window below */
1537 * Special case: TSC write with a small delta (1 second) of virtual
1538 * cycle time against real time is interpreted as an attempt to
1539 * synchronize the CPU.
1541 * For a reliable TSC, we can match TSC offsets, and for an unstable
1542 * TSC, we add elapsed time in this computation. We could let the
1543 * compensation code attempt to catch up if we fall behind, but
1544 * it's better to try to match offsets from the beginning.
1546 if (usdiff < USEC_PER_SEC &&
1547 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1548 if (!check_tsc_unstable()) {
1549 offset = kvm->arch.cur_tsc_offset;
1550 pr_debug("kvm: matched tsc offset for %llu\n", data);
1552 u64 delta = nsec_to_cycles(vcpu, elapsed);
1554 offset = kvm_compute_tsc_offset(vcpu, data);
1555 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1558 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1561 * We split periods of matched TSC writes into generations.
1562 * For each generation, we track the original measured
1563 * nanosecond time, offset, and write, so if TSCs are in
1564 * sync, we can match exact offset, and if not, we can match
1565 * exact software computation in compute_guest_tsc()
1567 * These values are tracked in kvm->arch.cur_xxx variables.
1569 kvm->arch.cur_tsc_generation++;
1570 kvm->arch.cur_tsc_nsec = ns;
1571 kvm->arch.cur_tsc_write = data;
1572 kvm->arch.cur_tsc_offset = offset;
1574 pr_debug("kvm: new tsc generation %llu, clock %llu\n",
1575 kvm->arch.cur_tsc_generation, data);
1579 * We also track th most recent recorded KHZ, write and time to
1580 * allow the matching interval to be extended at each write.
1582 kvm->arch.last_tsc_nsec = ns;
1583 kvm->arch.last_tsc_write = data;
1584 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1586 vcpu->arch.last_guest_tsc = data;
1588 /* Keep track of which generation this VCPU has synchronized to */
1589 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1590 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1591 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1593 if (guest_cpuid_has_tsc_adjust(vcpu) && !msr->host_initiated)
1594 update_ia32_tsc_adjust_msr(vcpu, offset);
1595 kvm_x86_ops->write_tsc_offset(vcpu, offset);
1596 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1598 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1600 kvm->arch.nr_vcpus_matched_tsc = 0;
1601 } else if (!already_matched) {
1602 kvm->arch.nr_vcpus_matched_tsc++;
1605 kvm_track_tsc_matching(vcpu);
1606 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1609 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1611 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
1614 kvm_x86_ops->adjust_tsc_offset_guest(vcpu, adjustment);
1617 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
1619 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
1620 WARN_ON(adjustment < 0);
1621 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
1622 kvm_x86_ops->adjust_tsc_offset_guest(vcpu, adjustment);
1625 #ifdef CONFIG_X86_64
1627 static cycle_t read_tsc(void)
1629 cycle_t ret = (cycle_t)rdtsc_ordered();
1630 u64 last = pvclock_gtod_data.clock.cycle_last;
1632 if (likely(ret >= last))
1636 * GCC likes to generate cmov here, but this branch is extremely
1637 * predictable (it's just a funciton of time and the likely is
1638 * very likely) and there's a data dependence, so force GCC
1639 * to generate a branch instead. I don't barrier() because
1640 * we don't actually need a barrier, and if this function
1641 * ever gets inlined it will generate worse code.
1647 static inline u64 vgettsc(cycle_t *cycle_now)
1650 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1652 *cycle_now = read_tsc();
1654 v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
1655 return v * gtod->clock.mult;
1658 static int do_monotonic_boot(s64 *t, cycle_t *cycle_now)
1660 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1666 seq = read_seqcount_begin(>od->seq);
1667 mode = gtod->clock.vclock_mode;
1668 ns = gtod->nsec_base;
1669 ns += vgettsc(cycle_now);
1670 ns >>= gtod->clock.shift;
1671 ns += gtod->boot_ns;
1672 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
1678 /* returns true if host is using tsc clocksource */
1679 static bool kvm_get_time_and_clockread(s64 *kernel_ns, cycle_t *cycle_now)
1681 /* checked again under seqlock below */
1682 if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
1685 return do_monotonic_boot(kernel_ns, cycle_now) == VCLOCK_TSC;
1691 * Assuming a stable TSC across physical CPUS, and a stable TSC
1692 * across virtual CPUs, the following condition is possible.
1693 * Each numbered line represents an event visible to both
1694 * CPUs at the next numbered event.
1696 * "timespecX" represents host monotonic time. "tscX" represents
1699 * VCPU0 on CPU0 | VCPU1 on CPU1
1701 * 1. read timespec0,tsc0
1702 * 2. | timespec1 = timespec0 + N
1704 * 3. transition to guest | transition to guest
1705 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1706 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
1707 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1709 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1712 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1714 * - 0 < N - M => M < N
1716 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1717 * always the case (the difference between two distinct xtime instances
1718 * might be smaller then the difference between corresponding TSC reads,
1719 * when updating guest vcpus pvclock areas).
1721 * To avoid that problem, do not allow visibility of distinct
1722 * system_timestamp/tsc_timestamp values simultaneously: use a master
1723 * copy of host monotonic time values. Update that master copy
1726 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1730 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1732 #ifdef CONFIG_X86_64
1733 struct kvm_arch *ka = &kvm->arch;
1735 bool host_tsc_clocksource, vcpus_matched;
1737 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1738 atomic_read(&kvm->online_vcpus));
1741 * If the host uses TSC clock, then passthrough TSC as stable
1744 host_tsc_clocksource = kvm_get_time_and_clockread(
1745 &ka->master_kernel_ns,
1746 &ka->master_cycle_now);
1748 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
1749 && !backwards_tsc_observed
1750 && !ka->boot_vcpu_runs_old_kvmclock;
1752 if (ka->use_master_clock)
1753 atomic_set(&kvm_guest_has_master_clock, 1);
1755 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1756 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1761 static void kvm_gen_update_masterclock(struct kvm *kvm)
1763 #ifdef CONFIG_X86_64
1765 struct kvm_vcpu *vcpu;
1766 struct kvm_arch *ka = &kvm->arch;
1768 spin_lock(&ka->pvclock_gtod_sync_lock);
1769 kvm_make_mclock_inprogress_request(kvm);
1770 /* no guest entries from this point */
1771 pvclock_update_vm_gtod_copy(kvm);
1773 kvm_for_each_vcpu(i, vcpu, kvm)
1774 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1776 /* guest entries allowed */
1777 kvm_for_each_vcpu(i, vcpu, kvm)
1778 clear_bit(KVM_REQ_MCLOCK_INPROGRESS, &vcpu->requests);
1780 spin_unlock(&ka->pvclock_gtod_sync_lock);
1784 static int kvm_guest_time_update(struct kvm_vcpu *v)
1786 unsigned long flags, this_tsc_khz, tgt_tsc_khz;
1787 struct kvm_vcpu_arch *vcpu = &v->arch;
1788 struct kvm_arch *ka = &v->kvm->arch;
1790 u64 tsc_timestamp, host_tsc;
1791 struct pvclock_vcpu_time_info guest_hv_clock;
1793 bool use_master_clock;
1799 * If the host uses TSC clock, then passthrough TSC as stable
1802 spin_lock(&ka->pvclock_gtod_sync_lock);
1803 use_master_clock = ka->use_master_clock;
1804 if (use_master_clock) {
1805 host_tsc = ka->master_cycle_now;
1806 kernel_ns = ka->master_kernel_ns;
1808 spin_unlock(&ka->pvclock_gtod_sync_lock);
1810 /* Keep irq disabled to prevent changes to the clock */
1811 local_irq_save(flags);
1812 this_tsc_khz = __this_cpu_read(cpu_tsc_khz);
1813 if (unlikely(this_tsc_khz == 0)) {
1814 local_irq_restore(flags);
1815 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1818 if (!use_master_clock) {
1820 kernel_ns = get_kernel_ns();
1823 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
1826 * We may have to catch up the TSC to match elapsed wall clock
1827 * time for two reasons, even if kvmclock is used.
1828 * 1) CPU could have been running below the maximum TSC rate
1829 * 2) Broken TSC compensation resets the base at each VCPU
1830 * entry to avoid unknown leaps of TSC even when running
1831 * again on the same CPU. This may cause apparent elapsed
1832 * time to disappear, and the guest to stand still or run
1835 if (vcpu->tsc_catchup) {
1836 u64 tsc = compute_guest_tsc(v, kernel_ns);
1837 if (tsc > tsc_timestamp) {
1838 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
1839 tsc_timestamp = tsc;
1843 local_irq_restore(flags);
1845 if (!vcpu->pv_time_enabled)
1848 if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
1849 tgt_tsc_khz = kvm_has_tsc_control ?
1850 vcpu->virtual_tsc_khz : this_tsc_khz;
1851 kvm_get_time_scale(NSEC_PER_SEC / 1000, tgt_tsc_khz,
1852 &vcpu->hv_clock.tsc_shift,
1853 &vcpu->hv_clock.tsc_to_system_mul);
1854 vcpu->hw_tsc_khz = this_tsc_khz;
1857 /* With all the info we got, fill in the values */
1858 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1859 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1860 vcpu->last_guest_tsc = tsc_timestamp;
1862 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
1863 &guest_hv_clock, sizeof(guest_hv_clock))))
1866 /* This VCPU is paused, but it's legal for a guest to read another
1867 * VCPU's kvmclock, so we really have to follow the specification where
1868 * it says that version is odd if data is being modified, and even after
1871 * Version field updates must be kept separate. This is because
1872 * kvm_write_guest_cached might use a "rep movs" instruction, and
1873 * writes within a string instruction are weakly ordered. So there
1874 * are three writes overall.
1876 * As a small optimization, only write the version field in the first
1877 * and third write. The vcpu->pv_time cache is still valid, because the
1878 * version field is the first in the struct.
1880 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
1882 if (guest_hv_clock.version & 1)
1883 ++guest_hv_clock.version; /* first time write, random junk */
1885 vcpu->hv_clock.version = guest_hv_clock.version + 1;
1886 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1888 sizeof(vcpu->hv_clock.version));
1892 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
1893 pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
1895 if (vcpu->pvclock_set_guest_stopped_request) {
1896 pvclock_flags |= PVCLOCK_GUEST_STOPPED;
1897 vcpu->pvclock_set_guest_stopped_request = false;
1900 /* If the host uses TSC clocksource, then it is stable */
1901 if (use_master_clock)
1902 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
1904 vcpu->hv_clock.flags = pvclock_flags;
1906 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
1908 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1910 sizeof(vcpu->hv_clock));
1914 vcpu->hv_clock.version++;
1915 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1917 sizeof(vcpu->hv_clock.version));
1922 * kvmclock updates which are isolated to a given vcpu, such as
1923 * vcpu->cpu migration, should not allow system_timestamp from
1924 * the rest of the vcpus to remain static. Otherwise ntp frequency
1925 * correction applies to one vcpu's system_timestamp but not
1928 * So in those cases, request a kvmclock update for all vcpus.
1929 * We need to rate-limit these requests though, as they can
1930 * considerably slow guests that have a large number of vcpus.
1931 * The time for a remote vcpu to update its kvmclock is bound
1932 * by the delay we use to rate-limit the updates.
1935 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
1937 static void kvmclock_update_fn(struct work_struct *work)
1940 struct delayed_work *dwork = to_delayed_work(work);
1941 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
1942 kvmclock_update_work);
1943 struct kvm *kvm = container_of(ka, struct kvm, arch);
1944 struct kvm_vcpu *vcpu;
1946 kvm_for_each_vcpu(i, vcpu, kvm) {
1947 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1948 kvm_vcpu_kick(vcpu);
1952 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
1954 struct kvm *kvm = v->kvm;
1956 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1957 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
1958 KVMCLOCK_UPDATE_DELAY);
1961 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
1963 static void kvmclock_sync_fn(struct work_struct *work)
1965 struct delayed_work *dwork = to_delayed_work(work);
1966 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
1967 kvmclock_sync_work);
1968 struct kvm *kvm = container_of(ka, struct kvm, arch);
1970 if (!kvmclock_periodic_sync)
1973 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
1974 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
1975 KVMCLOCK_SYNC_PERIOD);
1978 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1980 u64 mcg_cap = vcpu->arch.mcg_cap;
1981 unsigned bank_num = mcg_cap & 0xff;
1984 case MSR_IA32_MCG_STATUS:
1985 vcpu->arch.mcg_status = data;
1987 case MSR_IA32_MCG_CTL:
1988 if (!(mcg_cap & MCG_CTL_P))
1990 if (data != 0 && data != ~(u64)0)
1992 vcpu->arch.mcg_ctl = data;
1995 if (msr >= MSR_IA32_MC0_CTL &&
1996 msr < MSR_IA32_MCx_CTL(bank_num)) {
1997 u32 offset = msr - MSR_IA32_MC0_CTL;
1998 /* only 0 or all 1s can be written to IA32_MCi_CTL
1999 * some Linux kernels though clear bit 10 in bank 4 to
2000 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2001 * this to avoid an uncatched #GP in the guest
2003 if ((offset & 0x3) == 0 &&
2004 data != 0 && (data | (1 << 10)) != ~(u64)0)
2006 vcpu->arch.mce_banks[offset] = data;
2014 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2016 struct kvm *kvm = vcpu->kvm;
2017 int lm = is_long_mode(vcpu);
2018 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2019 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2020 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2021 : kvm->arch.xen_hvm_config.blob_size_32;
2022 u32 page_num = data & ~PAGE_MASK;
2023 u64 page_addr = data & PAGE_MASK;
2028 if (page_num >= blob_size)
2031 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2036 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2045 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2047 gpa_t gpa = data & ~0x3f;
2049 /* Bits 2:5 are reserved, Should be zero */
2053 vcpu->arch.apf.msr_val = data;
2055 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2056 kvm_clear_async_pf_completion_queue(vcpu);
2057 kvm_async_pf_hash_reset(vcpu);
2061 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2065 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2066 kvm_async_pf_wakeup_all(vcpu);
2070 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2072 vcpu->arch.pv_time_enabled = false;
2075 static void accumulate_steal_time(struct kvm_vcpu *vcpu)
2079 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2082 delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
2083 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2084 vcpu->arch.st.accum_steal = delta;
2087 static void record_steal_time(struct kvm_vcpu *vcpu)
2089 accumulate_steal_time(vcpu);
2091 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2094 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2095 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
2098 vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
2099 vcpu->arch.st.steal.version += 2;
2100 vcpu->arch.st.accum_steal = 0;
2102 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2103 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2106 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2109 u32 msr = msr_info->index;
2110 u64 data = msr_info->data;
2113 case MSR_AMD64_NB_CFG:
2114 case MSR_IA32_UCODE_REV:
2115 case MSR_IA32_UCODE_WRITE:
2116 case MSR_VM_HSAVE_PA:
2117 case MSR_AMD64_PATCH_LOADER:
2118 case MSR_AMD64_BU_CFG2:
2121 case MSR_IA32_ARCH_CAPABILITIES:
2122 if (!msr_info->host_initiated)
2124 vcpu->arch.arch_capabilities = data;
2127 return set_efer(vcpu, msr_info);
2129 data &= ~(u64)0x40; /* ignore flush filter disable */
2130 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2131 data &= ~(u64)0x8; /* ignore TLB cache disable */
2132 data &= ~(u64)0x40000; /* ignore Mc status write enable */
2134 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2139 case MSR_FAM10H_MMIO_CONF_BASE:
2141 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2146 case MSR_IA32_DEBUGCTLMSR:
2148 /* We support the non-activated case already */
2150 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2151 /* Values other than LBR and BTF are vendor-specific,
2152 thus reserved and should throw a #GP */
2155 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2158 case 0x200 ... 0x2ff:
2159 return kvm_mtrr_set_msr(vcpu, msr, data);
2160 case MSR_IA32_APICBASE:
2161 return kvm_set_apic_base(vcpu, msr_info);
2162 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2163 return kvm_x2apic_msr_write(vcpu, msr, data);
2164 case MSR_IA32_TSCDEADLINE:
2165 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2167 case MSR_IA32_TSC_ADJUST:
2168 if (guest_cpuid_has_tsc_adjust(vcpu)) {
2169 if (!msr_info->host_initiated) {
2170 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2171 adjust_tsc_offset_guest(vcpu, adj);
2173 vcpu->arch.ia32_tsc_adjust_msr = data;
2176 case MSR_IA32_MISC_ENABLE:
2177 vcpu->arch.ia32_misc_enable_msr = data;
2179 case MSR_IA32_SMBASE:
2180 if (!msr_info->host_initiated)
2182 vcpu->arch.smbase = data;
2184 case MSR_KVM_WALL_CLOCK_NEW:
2185 case MSR_KVM_WALL_CLOCK:
2186 vcpu->kvm->arch.wall_clock = data;
2187 kvm_write_wall_clock(vcpu->kvm, data);
2189 case MSR_KVM_SYSTEM_TIME_NEW:
2190 case MSR_KVM_SYSTEM_TIME: {
2192 struct kvm_arch *ka = &vcpu->kvm->arch;
2194 kvmclock_reset(vcpu);
2196 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2197 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2199 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2200 set_bit(KVM_REQ_MASTERCLOCK_UPDATE,
2203 ka->boot_vcpu_runs_old_kvmclock = tmp;
2206 vcpu->arch.time = data;
2207 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2209 /* we verify if the enable bit is set... */
2213 gpa_offset = data & ~(PAGE_MASK | 1);
2215 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2216 &vcpu->arch.pv_time, data & ~1ULL,
2217 sizeof(struct pvclock_vcpu_time_info)))
2218 vcpu->arch.pv_time_enabled = false;
2220 vcpu->arch.pv_time_enabled = true;
2224 case MSR_KVM_ASYNC_PF_EN:
2225 if (kvm_pv_enable_async_pf(vcpu, data))
2228 case MSR_KVM_STEAL_TIME:
2230 if (unlikely(!sched_info_on()))
2233 if (data & KVM_STEAL_RESERVED_MASK)
2236 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2237 data & KVM_STEAL_VALID_BITS,
2238 sizeof(struct kvm_steal_time)))
2241 vcpu->arch.st.msr_val = data;
2243 if (!(data & KVM_MSR_ENABLED))
2246 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2249 case MSR_KVM_PV_EOI_EN:
2250 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2254 case MSR_IA32_MCG_CTL:
2255 case MSR_IA32_MCG_STATUS:
2256 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2257 return set_msr_mce(vcpu, msr, data);
2259 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2260 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2261 pr = true; /* fall through */
2262 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2263 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2264 if (kvm_pmu_is_valid_msr(vcpu, msr))
2265 return kvm_pmu_set_msr(vcpu, msr_info);
2267 if (pr || data != 0)
2268 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2269 "0x%x data 0x%llx\n", msr, data);
2271 case MSR_K7_CLK_CTL:
2273 * Ignore all writes to this no longer documented MSR.
2274 * Writes are only relevant for old K7 processors,
2275 * all pre-dating SVM, but a recommended workaround from
2276 * AMD for these chips. It is possible to specify the
2277 * affected processor models on the command line, hence
2278 * the need to ignore the workaround.
2281 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2282 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2283 case HV_X64_MSR_CRASH_CTL:
2284 return kvm_hv_set_msr_common(vcpu, msr, data,
2285 msr_info->host_initiated);
2286 case MSR_IA32_BBL_CR_CTL3:
2287 /* Drop writes to this legacy MSR -- see rdmsr
2288 * counterpart for further detail.
2290 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
2292 case MSR_AMD64_OSVW_ID_LENGTH:
2293 if (!guest_cpuid_has_osvw(vcpu))
2295 vcpu->arch.osvw.length = data;
2297 case MSR_AMD64_OSVW_STATUS:
2298 if (!guest_cpuid_has_osvw(vcpu))
2300 vcpu->arch.osvw.status = data;
2303 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2304 return xen_hvm_config(vcpu, data);
2305 if (kvm_pmu_is_valid_msr(vcpu, msr))
2306 return kvm_pmu_set_msr(vcpu, msr_info);
2308 vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
2312 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
2319 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2323 * Reads an msr value (of 'msr_index') into 'pdata'.
2324 * Returns 0 on success, non-0 otherwise.
2325 * Assumes vcpu_load() was already called.
2327 int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2329 return kvm_x86_ops->get_msr(vcpu, msr);
2331 EXPORT_SYMBOL_GPL(kvm_get_msr);
2333 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2336 u64 mcg_cap = vcpu->arch.mcg_cap;
2337 unsigned bank_num = mcg_cap & 0xff;
2340 case MSR_IA32_P5_MC_ADDR:
2341 case MSR_IA32_P5_MC_TYPE:
2344 case MSR_IA32_MCG_CAP:
2345 data = vcpu->arch.mcg_cap;
2347 case MSR_IA32_MCG_CTL:
2348 if (!(mcg_cap & MCG_CTL_P))
2350 data = vcpu->arch.mcg_ctl;
2352 case MSR_IA32_MCG_STATUS:
2353 data = vcpu->arch.mcg_status;
2356 if (msr >= MSR_IA32_MC0_CTL &&
2357 msr < MSR_IA32_MCx_CTL(bank_num)) {
2358 u32 offset = msr - MSR_IA32_MC0_CTL;
2359 data = vcpu->arch.mce_banks[offset];
2368 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2370 switch (msr_info->index) {
2371 case MSR_IA32_PLATFORM_ID:
2372 case MSR_IA32_EBL_CR_POWERON:
2373 case MSR_IA32_DEBUGCTLMSR:
2374 case MSR_IA32_LASTBRANCHFROMIP:
2375 case MSR_IA32_LASTBRANCHTOIP:
2376 case MSR_IA32_LASTINTFROMIP:
2377 case MSR_IA32_LASTINTTOIP:
2379 case MSR_K8_TSEG_ADDR:
2380 case MSR_K8_TSEG_MASK:
2382 case MSR_VM_HSAVE_PA:
2383 case MSR_K8_INT_PENDING_MSG:
2384 case MSR_AMD64_NB_CFG:
2385 case MSR_FAM10H_MMIO_CONF_BASE:
2386 case MSR_AMD64_BU_CFG2:
2389 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2390 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2391 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2392 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2393 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2394 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2397 case MSR_IA32_UCODE_REV:
2398 msr_info->data = 0x100000000ULL;
2400 case MSR_IA32_ARCH_CAPABILITIES:
2401 if (!msr_info->host_initiated &&
2402 !guest_cpuid_has_arch_capabilities(vcpu))
2404 msr_info->data = vcpu->arch.arch_capabilities;
2407 case 0x200 ... 0x2ff:
2408 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2409 case 0xcd: /* fsb frequency */
2413 * MSR_EBC_FREQUENCY_ID
2414 * Conservative value valid for even the basic CPU models.
2415 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2416 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2417 * and 266MHz for model 3, or 4. Set Core Clock
2418 * Frequency to System Bus Frequency Ratio to 1 (bits
2419 * 31:24) even though these are only valid for CPU
2420 * models > 2, however guests may end up dividing or
2421 * multiplying by zero otherwise.
2423 case MSR_EBC_FREQUENCY_ID:
2424 msr_info->data = 1 << 24;
2426 case MSR_IA32_APICBASE:
2427 msr_info->data = kvm_get_apic_base(vcpu);
2429 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2430 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2432 case MSR_IA32_TSCDEADLINE:
2433 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2435 case MSR_IA32_TSC_ADJUST:
2436 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2438 case MSR_IA32_MISC_ENABLE:
2439 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
2441 case MSR_IA32_SMBASE:
2442 if (!msr_info->host_initiated)
2444 msr_info->data = vcpu->arch.smbase;
2446 case MSR_IA32_PERF_STATUS:
2447 /* TSC increment by tick */
2448 msr_info->data = 1000ULL;
2449 /* CPU multiplier */
2450 msr_info->data |= (((uint64_t)4ULL) << 40);
2453 msr_info->data = vcpu->arch.efer;
2455 case MSR_KVM_WALL_CLOCK:
2456 case MSR_KVM_WALL_CLOCK_NEW:
2457 msr_info->data = vcpu->kvm->arch.wall_clock;
2459 case MSR_KVM_SYSTEM_TIME:
2460 case MSR_KVM_SYSTEM_TIME_NEW:
2461 msr_info->data = vcpu->arch.time;
2463 case MSR_KVM_ASYNC_PF_EN:
2464 msr_info->data = vcpu->arch.apf.msr_val;
2466 case MSR_KVM_STEAL_TIME:
2467 msr_info->data = vcpu->arch.st.msr_val;
2469 case MSR_KVM_PV_EOI_EN:
2470 msr_info->data = vcpu->arch.pv_eoi.msr_val;
2472 case MSR_IA32_P5_MC_ADDR:
2473 case MSR_IA32_P5_MC_TYPE:
2474 case MSR_IA32_MCG_CAP:
2475 case MSR_IA32_MCG_CTL:
2476 case MSR_IA32_MCG_STATUS:
2477 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2478 return get_msr_mce(vcpu, msr_info->index, &msr_info->data);
2479 case MSR_K7_CLK_CTL:
2481 * Provide expected ramp-up count for K7. All other
2482 * are set to zero, indicating minimum divisors for
2485 * This prevents guest kernels on AMD host with CPU
2486 * type 6, model 8 and higher from exploding due to
2487 * the rdmsr failing.
2489 msr_info->data = 0x20000000;
2491 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2492 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2493 case HV_X64_MSR_CRASH_CTL:
2494 return kvm_hv_get_msr_common(vcpu,
2495 msr_info->index, &msr_info->data);
2497 case MSR_IA32_BBL_CR_CTL3:
2498 /* This legacy MSR exists but isn't fully documented in current
2499 * silicon. It is however accessed by winxp in very narrow
2500 * scenarios where it sets bit #19, itself documented as
2501 * a "reserved" bit. Best effort attempt to source coherent
2502 * read data here should the balance of the register be
2503 * interpreted by the guest:
2505 * L2 cache control register 3: 64GB range, 256KB size,
2506 * enabled, latency 0x1, configured
2508 msr_info->data = 0xbe702111;
2510 case MSR_AMD64_OSVW_ID_LENGTH:
2511 if (!guest_cpuid_has_osvw(vcpu))
2513 msr_info->data = vcpu->arch.osvw.length;
2515 case MSR_AMD64_OSVW_STATUS:
2516 if (!guest_cpuid_has_osvw(vcpu))
2518 msr_info->data = vcpu->arch.osvw.status;
2521 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2522 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2524 vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr_info->index);
2527 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr_info->index);
2534 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2537 * Read or write a bunch of msrs. All parameters are kernel addresses.
2539 * @return number of msrs set successfully.
2541 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2542 struct kvm_msr_entry *entries,
2543 int (*do_msr)(struct kvm_vcpu *vcpu,
2544 unsigned index, u64 *data))
2548 idx = srcu_read_lock(&vcpu->kvm->srcu);
2549 for (i = 0; i < msrs->nmsrs; ++i)
2550 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2552 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2558 * Read or write a bunch of msrs. Parameters are user addresses.
2560 * @return number of msrs set successfully.
2562 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2563 int (*do_msr)(struct kvm_vcpu *vcpu,
2564 unsigned index, u64 *data),
2567 struct kvm_msrs msrs;
2568 struct kvm_msr_entry *entries;
2573 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2577 if (msrs.nmsrs >= MAX_IO_MSRS)
2580 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2581 entries = memdup_user(user_msrs->entries, size);
2582 if (IS_ERR(entries)) {
2583 r = PTR_ERR(entries);
2587 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2592 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2603 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2608 case KVM_CAP_IRQCHIP:
2610 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2611 case KVM_CAP_SET_TSS_ADDR:
2612 case KVM_CAP_EXT_CPUID:
2613 case KVM_CAP_EXT_EMUL_CPUID:
2614 case KVM_CAP_CLOCKSOURCE:
2616 case KVM_CAP_NOP_IO_DELAY:
2617 case KVM_CAP_MP_STATE:
2618 case KVM_CAP_SYNC_MMU:
2619 case KVM_CAP_USER_NMI:
2620 case KVM_CAP_REINJECT_CONTROL:
2621 case KVM_CAP_IRQ_INJECT_STATUS:
2622 case KVM_CAP_IOEVENTFD:
2623 case KVM_CAP_IOEVENTFD_NO_LENGTH:
2625 case KVM_CAP_PIT_STATE2:
2626 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2627 case KVM_CAP_XEN_HVM:
2628 case KVM_CAP_ADJUST_CLOCK:
2629 case KVM_CAP_VCPU_EVENTS:
2630 case KVM_CAP_HYPERV:
2631 case KVM_CAP_HYPERV_VAPIC:
2632 case KVM_CAP_HYPERV_SPIN:
2633 case KVM_CAP_PCI_SEGMENT:
2634 case KVM_CAP_DEBUGREGS:
2635 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2637 case KVM_CAP_ASYNC_PF:
2638 case KVM_CAP_GET_TSC_KHZ:
2639 case KVM_CAP_KVMCLOCK_CTRL:
2640 case KVM_CAP_READONLY_MEM:
2641 case KVM_CAP_HYPERV_TIME:
2642 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2643 case KVM_CAP_TSC_DEADLINE_TIMER:
2644 case KVM_CAP_ENABLE_CAP_VM:
2645 case KVM_CAP_DISABLE_QUIRKS:
2646 case KVM_CAP_SET_BOOT_CPU_ID:
2647 case KVM_CAP_SPLIT_IRQCHIP:
2648 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2649 case KVM_CAP_ASSIGN_DEV_IRQ:
2650 case KVM_CAP_PCI_2_3:
2654 case KVM_CAP_X86_SMM:
2655 /* SMBASE is usually relocated above 1M on modern chipsets,
2656 * and SMM handlers might indeed rely on 4G segment limits,
2657 * so do not report SMM to be available if real mode is
2658 * emulated via vm86 mode. Still, do not go to great lengths
2659 * to avoid userspace's usage of the feature, because it is a
2660 * fringe case that is not enabled except via specific settings
2661 * of the module parameters.
2663 r = kvm_x86_ops->has_emulated_msr(MSR_IA32_SMBASE);
2665 case KVM_CAP_COALESCED_MMIO:
2666 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2669 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2671 case KVM_CAP_NR_VCPUS:
2672 r = KVM_SOFT_MAX_VCPUS;
2674 case KVM_CAP_MAX_VCPUS:
2677 case KVM_CAP_NR_MEMSLOTS:
2678 r = KVM_USER_MEM_SLOTS;
2680 case KVM_CAP_PV_MMU: /* obsolete */
2683 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2685 r = iommu_present(&pci_bus_type);
2689 r = KVM_MAX_MCE_BANKS;
2694 case KVM_CAP_TSC_CONTROL:
2695 r = kvm_has_tsc_control;
2705 long kvm_arch_dev_ioctl(struct file *filp,
2706 unsigned int ioctl, unsigned long arg)
2708 void __user *argp = (void __user *)arg;
2712 case KVM_GET_MSR_INDEX_LIST: {
2713 struct kvm_msr_list __user *user_msr_list = argp;
2714 struct kvm_msr_list msr_list;
2718 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2721 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
2722 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2725 if (n < msr_list.nmsrs)
2728 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2729 num_msrs_to_save * sizeof(u32)))
2731 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2733 num_emulated_msrs * sizeof(u32)))
2738 case KVM_GET_SUPPORTED_CPUID:
2739 case KVM_GET_EMULATED_CPUID: {
2740 struct kvm_cpuid2 __user *cpuid_arg = argp;
2741 struct kvm_cpuid2 cpuid;
2744 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2747 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2753 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2758 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2761 mce_cap = KVM_MCE_CAP_SUPPORTED;
2763 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2775 static void wbinvd_ipi(void *garbage)
2780 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2782 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2785 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2787 /* Address WBINVD may be executed by guest */
2788 if (need_emulate_wbinvd(vcpu)) {
2789 if (kvm_x86_ops->has_wbinvd_exit())
2790 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2791 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2792 smp_call_function_single(vcpu->cpu,
2793 wbinvd_ipi, NULL, 1);
2796 kvm_x86_ops->vcpu_load(vcpu, cpu);
2798 /* Apply any externally detected TSC adjustments (due to suspend) */
2799 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2800 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2801 vcpu->arch.tsc_offset_adjustment = 0;
2802 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2805 if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2806 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2807 rdtsc() - vcpu->arch.last_host_tsc;
2809 mark_tsc_unstable("KVM discovered backwards TSC");
2810 if (check_tsc_unstable()) {
2811 u64 offset = kvm_compute_tsc_offset(vcpu,
2812 vcpu->arch.last_guest_tsc);
2813 kvm_x86_ops->write_tsc_offset(vcpu, offset);
2814 vcpu->arch.tsc_catchup = 1;
2817 * On a host with synchronized TSC, there is no need to update
2818 * kvmclock on vcpu->cpu migration
2820 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
2821 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2822 if (vcpu->cpu != cpu)
2823 kvm_migrate_timers(vcpu);
2827 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2830 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2832 kvm_x86_ops->vcpu_put(vcpu);
2833 kvm_put_guest_fpu(vcpu);
2834 vcpu->arch.last_host_tsc = rdtsc();
2836 * If userspace has set any breakpoints or watchpoints, dr6 is restored
2837 * on every vmexit, but if not, we might have a stale dr6 from the
2838 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
2843 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2844 struct kvm_lapic_state *s)
2846 kvm_x86_ops->sync_pir_to_irr(vcpu);
2847 memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2852 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2853 struct kvm_lapic_state *s)
2855 kvm_apic_post_state_restore(vcpu, s);
2856 update_cr8_intercept(vcpu);
2861 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
2863 return (!lapic_in_kernel(vcpu) ||
2864 kvm_apic_accept_pic_intr(vcpu));
2868 * if userspace requested an interrupt window, check that the
2869 * interrupt window is open.
2871 * No need to exit to userspace if we already have an interrupt queued.
2873 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
2875 return kvm_arch_interrupt_allowed(vcpu) &&
2876 !kvm_cpu_has_interrupt(vcpu) &&
2877 !kvm_event_needs_reinjection(vcpu) &&
2878 kvm_cpu_accept_dm_intr(vcpu);
2881 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2882 struct kvm_interrupt *irq)
2884 if (irq->irq >= KVM_NR_INTERRUPTS)
2887 if (!irqchip_in_kernel(vcpu->kvm)) {
2888 kvm_queue_interrupt(vcpu, irq->irq, false);
2889 kvm_make_request(KVM_REQ_EVENT, vcpu);
2894 * With in-kernel LAPIC, we only use this to inject EXTINT, so
2895 * fail for in-kernel 8259.
2897 if (pic_in_kernel(vcpu->kvm))
2900 if (vcpu->arch.pending_external_vector != -1)
2903 vcpu->arch.pending_external_vector = irq->irq;
2904 kvm_make_request(KVM_REQ_EVENT, vcpu);
2908 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2910 kvm_inject_nmi(vcpu);
2915 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
2917 kvm_make_request(KVM_REQ_SMI, vcpu);
2922 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2923 struct kvm_tpr_access_ctl *tac)
2927 vcpu->arch.tpr_access_reporting = !!tac->enabled;
2931 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2935 unsigned bank_num = mcg_cap & 0xff, bank;
2938 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2940 if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2943 vcpu->arch.mcg_cap = mcg_cap;
2944 /* Init IA32_MCG_CTL to all 1s */
2945 if (mcg_cap & MCG_CTL_P)
2946 vcpu->arch.mcg_ctl = ~(u64)0;
2947 /* Init IA32_MCi_CTL to all 1s */
2948 for (bank = 0; bank < bank_num; bank++)
2949 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2954 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2955 struct kvm_x86_mce *mce)
2957 u64 mcg_cap = vcpu->arch.mcg_cap;
2958 unsigned bank_num = mcg_cap & 0xff;
2959 u64 *banks = vcpu->arch.mce_banks;
2961 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2964 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2965 * reporting is disabled
2967 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2968 vcpu->arch.mcg_ctl != ~(u64)0)
2970 banks += 4 * mce->bank;
2972 * if IA32_MCi_CTL is not all 1s, the uncorrected error
2973 * reporting is disabled for the bank
2975 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2977 if (mce->status & MCI_STATUS_UC) {
2978 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2979 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2980 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2983 if (banks[1] & MCI_STATUS_VAL)
2984 mce->status |= MCI_STATUS_OVER;
2985 banks[2] = mce->addr;
2986 banks[3] = mce->misc;
2987 vcpu->arch.mcg_status = mce->mcg_status;
2988 banks[1] = mce->status;
2989 kvm_queue_exception(vcpu, MC_VECTOR);
2990 } else if (!(banks[1] & MCI_STATUS_VAL)
2991 || !(banks[1] & MCI_STATUS_UC)) {
2992 if (banks[1] & MCI_STATUS_VAL)
2993 mce->status |= MCI_STATUS_OVER;
2994 banks[2] = mce->addr;
2995 banks[3] = mce->misc;
2996 banks[1] = mce->status;
2998 banks[1] |= MCI_STATUS_OVER;
3002 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3003 struct kvm_vcpu_events *events)
3006 events->exception.injected =
3007 vcpu->arch.exception.pending &&
3008 !kvm_exception_is_soft(vcpu->arch.exception.nr);
3009 events->exception.nr = vcpu->arch.exception.nr;
3010 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3011 events->exception.pad = 0;
3012 events->exception.error_code = vcpu->arch.exception.error_code;
3014 events->interrupt.injected =
3015 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
3016 events->interrupt.nr = vcpu->arch.interrupt.nr;
3017 events->interrupt.soft = 0;
3018 events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3020 events->nmi.injected = vcpu->arch.nmi_injected;
3021 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3022 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3023 events->nmi.pad = 0;
3025 events->sipi_vector = 0; /* never valid when reporting to user space */
3027 events->smi.smm = is_smm(vcpu);
3028 events->smi.pending = vcpu->arch.smi_pending;
3029 events->smi.smm_inside_nmi =
3030 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3031 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3033 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3034 | KVM_VCPUEVENT_VALID_SHADOW
3035 | KVM_VCPUEVENT_VALID_SMM);
3036 memset(&events->reserved, 0, sizeof(events->reserved));
3039 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
3041 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3042 struct kvm_vcpu_events *events)
3044 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3045 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3046 | KVM_VCPUEVENT_VALID_SHADOW
3047 | KVM_VCPUEVENT_VALID_SMM))
3050 if (events->exception.injected &&
3051 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
3054 /* INITs are latched while in SMM */
3055 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3056 (events->smi.smm || events->smi.pending) &&
3057 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3061 vcpu->arch.exception.pending = events->exception.injected;
3062 vcpu->arch.exception.nr = events->exception.nr;
3063 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3064 vcpu->arch.exception.error_code = events->exception.error_code;
3066 vcpu->arch.interrupt.pending = events->interrupt.injected;
3067 vcpu->arch.interrupt.nr = events->interrupt.nr;
3068 vcpu->arch.interrupt.soft = events->interrupt.soft;
3069 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3070 kvm_x86_ops->set_interrupt_shadow(vcpu,
3071 events->interrupt.shadow);
3073 vcpu->arch.nmi_injected = events->nmi.injected;
3074 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3075 vcpu->arch.nmi_pending = events->nmi.pending;
3076 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3078 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3079 kvm_vcpu_has_lapic(vcpu))
3080 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3082 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3083 u32 hflags = vcpu->arch.hflags;
3084 if (events->smi.smm)
3085 hflags |= HF_SMM_MASK;
3087 hflags &= ~HF_SMM_MASK;
3088 kvm_set_hflags(vcpu, hflags);
3090 vcpu->arch.smi_pending = events->smi.pending;
3091 if (events->smi.smm_inside_nmi)
3092 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3094 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3095 if (kvm_vcpu_has_lapic(vcpu)) {
3096 if (events->smi.latched_init)
3097 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3099 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3103 kvm_make_request(KVM_REQ_EVENT, vcpu);
3108 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3109 struct kvm_debugregs *dbgregs)
3113 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3114 kvm_get_dr(vcpu, 6, &val);
3116 dbgregs->dr7 = vcpu->arch.dr7;
3118 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3121 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3122 struct kvm_debugregs *dbgregs)
3127 if (dbgregs->dr6 & ~0xffffffffull)
3129 if (dbgregs->dr7 & ~0xffffffffull)
3132 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3133 kvm_update_dr0123(vcpu);
3134 vcpu->arch.dr6 = dbgregs->dr6;
3135 kvm_update_dr6(vcpu);
3136 vcpu->arch.dr7 = dbgregs->dr7;
3137 kvm_update_dr7(vcpu);
3142 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3144 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3146 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3147 u64 xstate_bv = xsave->header.xfeatures;
3151 * Copy legacy XSAVE area, to avoid complications with CPUID
3152 * leaves 0 and 1 in the loop below.
3154 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3157 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3158 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3161 * Copy each region from the possibly compacted offset to the
3162 * non-compacted offset.
3164 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3166 u64 feature = valid & -valid;
3167 int index = fls64(feature) - 1;
3168 void *src = get_xsave_addr(xsave, feature);
3171 u32 size, offset, ecx, edx;
3172 cpuid_count(XSTATE_CPUID, index,
3173 &size, &offset, &ecx, &edx);
3174 memcpy(dest + offset, src, size);
3181 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3183 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3184 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3188 * Copy legacy XSAVE area, to avoid complications with CPUID
3189 * leaves 0 and 1 in the loop below.
3191 memcpy(xsave, src, XSAVE_HDR_OFFSET);
3193 /* Set XSTATE_BV and possibly XCOMP_BV. */
3194 xsave->header.xfeatures = xstate_bv;
3196 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3199 * Copy each region from the non-compacted offset to the
3200 * possibly compacted offset.
3202 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3204 u64 feature = valid & -valid;
3205 int index = fls64(feature) - 1;
3206 void *dest = get_xsave_addr(xsave, feature);
3209 u32 size, offset, ecx, edx;
3210 cpuid_count(XSTATE_CPUID, index,
3211 &size, &offset, &ecx, &edx);
3212 memcpy(dest, src + offset, size);
3219 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3220 struct kvm_xsave *guest_xsave)
3222 if (cpu_has_xsave) {
3223 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
3224 fill_xsave((u8 *) guest_xsave->region, vcpu);
3226 memcpy(guest_xsave->region,
3227 &vcpu->arch.guest_fpu.state.fxsave,
3228 sizeof(struct fxregs_state));
3229 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3230 XFEATURE_MASK_FPSSE;
3234 #define XSAVE_MXCSR_OFFSET 24
3236 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3237 struct kvm_xsave *guest_xsave)
3240 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3241 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
3243 if (cpu_has_xsave) {
3245 * Here we allow setting states that are not present in
3246 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
3247 * with old userspace.
3249 if (xstate_bv & ~kvm_supported_xcr0() ||
3250 mxcsr & ~mxcsr_feature_mask)
3252 load_xsave(vcpu, (u8 *)guest_xsave->region);
3254 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
3255 mxcsr & ~mxcsr_feature_mask)
3257 memcpy(&vcpu->arch.guest_fpu.state.fxsave,
3258 guest_xsave->region, sizeof(struct fxregs_state));
3263 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3264 struct kvm_xcrs *guest_xcrs)
3266 if (!cpu_has_xsave) {
3267 guest_xcrs->nr_xcrs = 0;
3271 guest_xcrs->nr_xcrs = 1;
3272 guest_xcrs->flags = 0;
3273 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3274 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3277 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3278 struct kvm_xcrs *guest_xcrs)
3285 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3288 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3289 /* Only support XCR0 currently */
3290 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3291 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3292 guest_xcrs->xcrs[i].value);
3301 * kvm_set_guest_paused() indicates to the guest kernel that it has been
3302 * stopped by the hypervisor. This function will be called from the host only.
3303 * EINVAL is returned when the host attempts to set the flag for a guest that
3304 * does not support pv clocks.
3306 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3308 if (!vcpu->arch.pv_time_enabled)
3310 vcpu->arch.pvclock_set_guest_stopped_request = true;
3311 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3315 long kvm_arch_vcpu_ioctl(struct file *filp,
3316 unsigned int ioctl, unsigned long arg)
3318 struct kvm_vcpu *vcpu = filp->private_data;
3319 void __user *argp = (void __user *)arg;
3322 struct kvm_lapic_state *lapic;
3323 struct kvm_xsave *xsave;
3324 struct kvm_xcrs *xcrs;
3330 case KVM_GET_LAPIC: {
3332 if (!vcpu->arch.apic)
3334 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3339 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3343 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3348 case KVM_SET_LAPIC: {
3350 if (!vcpu->arch.apic)
3352 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3353 if (IS_ERR(u.lapic))
3354 return PTR_ERR(u.lapic);
3356 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3359 case KVM_INTERRUPT: {
3360 struct kvm_interrupt irq;
3363 if (copy_from_user(&irq, argp, sizeof irq))
3365 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3369 r = kvm_vcpu_ioctl_nmi(vcpu);
3373 r = kvm_vcpu_ioctl_smi(vcpu);
3376 case KVM_SET_CPUID: {
3377 struct kvm_cpuid __user *cpuid_arg = argp;
3378 struct kvm_cpuid cpuid;
3381 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3383 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3386 case KVM_SET_CPUID2: {
3387 struct kvm_cpuid2 __user *cpuid_arg = argp;
3388 struct kvm_cpuid2 cpuid;
3391 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3393 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3394 cpuid_arg->entries);
3397 case KVM_GET_CPUID2: {
3398 struct kvm_cpuid2 __user *cpuid_arg = argp;
3399 struct kvm_cpuid2 cpuid;
3402 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3404 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3405 cpuid_arg->entries);
3409 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3415 r = msr_io(vcpu, argp, do_get_msr, 1);
3418 r = msr_io(vcpu, argp, do_set_msr, 0);
3420 case KVM_TPR_ACCESS_REPORTING: {
3421 struct kvm_tpr_access_ctl tac;
3424 if (copy_from_user(&tac, argp, sizeof tac))
3426 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3430 if (copy_to_user(argp, &tac, sizeof tac))
3435 case KVM_SET_VAPIC_ADDR: {
3436 struct kvm_vapic_addr va;
3440 if (!lapic_in_kernel(vcpu))
3443 if (copy_from_user(&va, argp, sizeof va))
3445 idx = srcu_read_lock(&vcpu->kvm->srcu);
3446 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3447 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3450 case KVM_X86_SETUP_MCE: {
3454 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3456 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3459 case KVM_X86_SET_MCE: {
3460 struct kvm_x86_mce mce;
3463 if (copy_from_user(&mce, argp, sizeof mce))
3465 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3468 case KVM_GET_VCPU_EVENTS: {
3469 struct kvm_vcpu_events events;
3471 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3474 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3479 case KVM_SET_VCPU_EVENTS: {
3480 struct kvm_vcpu_events events;
3483 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3486 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3489 case KVM_GET_DEBUGREGS: {
3490 struct kvm_debugregs dbgregs;
3492 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3495 if (copy_to_user(argp, &dbgregs,
3496 sizeof(struct kvm_debugregs)))
3501 case KVM_SET_DEBUGREGS: {
3502 struct kvm_debugregs dbgregs;
3505 if (copy_from_user(&dbgregs, argp,
3506 sizeof(struct kvm_debugregs)))
3509 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3512 case KVM_GET_XSAVE: {
3513 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3518 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3521 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3526 case KVM_SET_XSAVE: {
3527 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3528 if (IS_ERR(u.xsave))
3529 return PTR_ERR(u.xsave);
3531 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3534 case KVM_GET_XCRS: {
3535 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3540 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3543 if (copy_to_user(argp, u.xcrs,
3544 sizeof(struct kvm_xcrs)))
3549 case KVM_SET_XCRS: {
3550 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3552 return PTR_ERR(u.xcrs);
3554 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3557 case KVM_SET_TSC_KHZ: {
3561 user_tsc_khz = (u32)arg;
3563 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3566 if (user_tsc_khz == 0)
3567 user_tsc_khz = tsc_khz;
3569 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
3574 case KVM_GET_TSC_KHZ: {
3575 r = vcpu->arch.virtual_tsc_khz;
3578 case KVM_KVMCLOCK_CTRL: {
3579 r = kvm_set_guest_paused(vcpu);
3590 int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3592 return VM_FAULT_SIGBUS;
3595 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3599 if (addr > (unsigned int)(-3 * PAGE_SIZE))
3601 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3605 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3608 kvm->arch.ept_identity_map_addr = ident_addr;
3612 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3613 u32 kvm_nr_mmu_pages)
3615 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3618 mutex_lock(&kvm->slots_lock);
3620 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3621 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3623 mutex_unlock(&kvm->slots_lock);
3627 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3629 return kvm->arch.n_max_mmu_pages;
3632 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3637 switch (chip->chip_id) {
3638 case KVM_IRQCHIP_PIC_MASTER:
3639 memcpy(&chip->chip.pic,
3640 &pic_irqchip(kvm)->pics[0],
3641 sizeof(struct kvm_pic_state));
3643 case KVM_IRQCHIP_PIC_SLAVE:
3644 memcpy(&chip->chip.pic,
3645 &pic_irqchip(kvm)->pics[1],
3646 sizeof(struct kvm_pic_state));
3648 case KVM_IRQCHIP_IOAPIC:
3649 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3658 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3663 switch (chip->chip_id) {
3664 case KVM_IRQCHIP_PIC_MASTER:
3665 spin_lock(&pic_irqchip(kvm)->lock);
3666 memcpy(&pic_irqchip(kvm)->pics[0],
3668 sizeof(struct kvm_pic_state));
3669 spin_unlock(&pic_irqchip(kvm)->lock);
3671 case KVM_IRQCHIP_PIC_SLAVE:
3672 spin_lock(&pic_irqchip(kvm)->lock);
3673 memcpy(&pic_irqchip(kvm)->pics[1],
3675 sizeof(struct kvm_pic_state));
3676 spin_unlock(&pic_irqchip(kvm)->lock);
3678 case KVM_IRQCHIP_IOAPIC:
3679 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3685 kvm_pic_update_irq(pic_irqchip(kvm));
3689 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3691 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3692 memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
3693 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3697 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3700 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3701 memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
3702 for (i = 0; i < 3; i++)
3703 kvm_pit_load_count(kvm, i, ps->channels[i].count, 0);
3704 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3708 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3710 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3711 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3712 sizeof(ps->channels));
3713 ps->flags = kvm->arch.vpit->pit_state.flags;
3714 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3715 memset(&ps->reserved, 0, sizeof(ps->reserved));
3719 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3723 u32 prev_legacy, cur_legacy;
3724 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3725 prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3726 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3727 if (!prev_legacy && cur_legacy)
3729 memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
3730 sizeof(kvm->arch.vpit->pit_state.channels));
3731 kvm->arch.vpit->pit_state.flags = ps->flags;
3732 for (i = 0; i < 3; i++)
3733 kvm_pit_load_count(kvm, i, kvm->arch.vpit->pit_state.channels[i].count,
3735 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3739 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3740 struct kvm_reinject_control *control)
3742 if (!kvm->arch.vpit)
3744 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3745 kvm->arch.vpit->pit_state.reinject = control->pit_reinject;
3746 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3751 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
3752 * @kvm: kvm instance
3753 * @log: slot id and address to which we copy the log
3755 * Steps 1-4 below provide general overview of dirty page logging. See
3756 * kvm_get_dirty_log_protect() function description for additional details.
3758 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
3759 * always flush the TLB (step 4) even if previous step failed and the dirty
3760 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
3761 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
3762 * writes will be marked dirty for next log read.
3764 * 1. Take a snapshot of the bit and clear it if needed.
3765 * 2. Write protect the corresponding page.
3766 * 3. Copy the snapshot to the userspace.
3767 * 4. Flush TLB's if needed.
3769 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
3771 bool is_dirty = false;
3774 mutex_lock(&kvm->slots_lock);
3777 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
3779 if (kvm_x86_ops->flush_log_dirty)
3780 kvm_x86_ops->flush_log_dirty(kvm);
3782 r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
3785 * All the TLBs can be flushed out of mmu lock, see the comments in
3786 * kvm_mmu_slot_remove_write_access().
3788 lockdep_assert_held(&kvm->slots_lock);
3790 kvm_flush_remote_tlbs(kvm);
3792 mutex_unlock(&kvm->slots_lock);
3796 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
3799 if (!irqchip_in_kernel(kvm))
3802 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3803 irq_event->irq, irq_event->level,
3808 static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3809 struct kvm_enable_cap *cap)
3817 case KVM_CAP_DISABLE_QUIRKS:
3818 kvm->arch.disabled_quirks = cap->args[0];
3821 case KVM_CAP_SPLIT_IRQCHIP: {
3822 mutex_lock(&kvm->lock);
3824 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
3825 goto split_irqchip_unlock;
3827 if (irqchip_in_kernel(kvm))
3828 goto split_irqchip_unlock;
3829 if (atomic_read(&kvm->online_vcpus))
3830 goto split_irqchip_unlock;
3831 r = kvm_setup_empty_irq_routing(kvm);
3833 goto split_irqchip_unlock;
3834 /* Pairs with irqchip_in_kernel. */
3836 kvm->arch.irqchip_split = true;
3837 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
3839 split_irqchip_unlock:
3840 mutex_unlock(&kvm->lock);
3850 long kvm_arch_vm_ioctl(struct file *filp,
3851 unsigned int ioctl, unsigned long arg)
3853 struct kvm *kvm = filp->private_data;
3854 void __user *argp = (void __user *)arg;
3857 * This union makes it completely explicit to gcc-3.x
3858 * that these two variables' stack usage should be
3859 * combined, not added together.
3862 struct kvm_pit_state ps;
3863 struct kvm_pit_state2 ps2;
3864 struct kvm_pit_config pit_config;
3868 case KVM_SET_TSS_ADDR:
3869 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3871 case KVM_SET_IDENTITY_MAP_ADDR: {
3875 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3877 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3880 case KVM_SET_NR_MMU_PAGES:
3881 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3883 case KVM_GET_NR_MMU_PAGES:
3884 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3886 case KVM_CREATE_IRQCHIP: {
3887 struct kvm_pic *vpic;
3889 mutex_lock(&kvm->lock);
3892 goto create_irqchip_unlock;
3894 if (atomic_read(&kvm->online_vcpus))
3895 goto create_irqchip_unlock;
3897 vpic = kvm_create_pic(kvm);
3899 r = kvm_ioapic_init(kvm);
3901 mutex_lock(&kvm->slots_lock);
3902 kvm_destroy_pic(vpic);
3903 mutex_unlock(&kvm->slots_lock);
3904 goto create_irqchip_unlock;
3907 goto create_irqchip_unlock;
3908 r = kvm_setup_default_irq_routing(kvm);
3910 mutex_lock(&kvm->slots_lock);
3911 mutex_lock(&kvm->irq_lock);
3912 kvm_ioapic_destroy(kvm);
3913 kvm_destroy_pic(vpic);
3914 mutex_unlock(&kvm->irq_lock);
3915 mutex_unlock(&kvm->slots_lock);
3916 goto create_irqchip_unlock;
3918 /* Write kvm->irq_routing before kvm->arch.vpic. */
3920 kvm->arch.vpic = vpic;
3921 create_irqchip_unlock:
3922 mutex_unlock(&kvm->lock);
3925 case KVM_CREATE_PIT:
3926 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3928 case KVM_CREATE_PIT2:
3930 if (copy_from_user(&u.pit_config, argp,
3931 sizeof(struct kvm_pit_config)))
3934 mutex_lock(&kvm->lock);
3937 goto create_pit_unlock;
3939 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3943 mutex_unlock(&kvm->lock);
3945 case KVM_GET_IRQCHIP: {
3946 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3947 struct kvm_irqchip *chip;
3949 chip = memdup_user(argp, sizeof(*chip));
3956 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
3957 goto get_irqchip_out;
3958 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3960 goto get_irqchip_out;
3962 if (copy_to_user(argp, chip, sizeof *chip))
3963 goto get_irqchip_out;
3969 case KVM_SET_IRQCHIP: {
3970 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3971 struct kvm_irqchip *chip;
3973 chip = memdup_user(argp, sizeof(*chip));
3980 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
3981 goto set_irqchip_out;
3982 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3984 goto set_irqchip_out;
3992 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
3995 if (!kvm->arch.vpit)
3997 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
4001 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
4008 if (copy_from_user(&u.ps, argp, sizeof u.ps))
4011 if (!kvm->arch.vpit)
4013 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
4016 case KVM_GET_PIT2: {
4018 if (!kvm->arch.vpit)
4020 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
4024 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
4029 case KVM_SET_PIT2: {
4031 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
4034 if (!kvm->arch.vpit)
4036 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
4039 case KVM_REINJECT_CONTROL: {
4040 struct kvm_reinject_control control;
4042 if (copy_from_user(&control, argp, sizeof(control)))
4044 r = kvm_vm_ioctl_reinject(kvm, &control);
4047 case KVM_SET_BOOT_CPU_ID:
4049 mutex_lock(&kvm->lock);
4050 if (atomic_read(&kvm->online_vcpus) != 0)
4053 kvm->arch.bsp_vcpu_id = arg;
4054 mutex_unlock(&kvm->lock);
4056 case KVM_XEN_HVM_CONFIG: {
4057 struct kvm_xen_hvm_config xhc;
4059 if (copy_from_user(&xhc, argp, sizeof(xhc)))
4064 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
4068 case KVM_SET_CLOCK: {
4069 struct kvm_clock_data user_ns;
4074 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
4082 local_irq_disable();
4083 now_ns = get_kernel_ns();
4084 delta = user_ns.clock - now_ns;
4086 kvm->arch.kvmclock_offset = delta;
4087 kvm_gen_update_masterclock(kvm);
4090 case KVM_GET_CLOCK: {
4091 struct kvm_clock_data user_ns;
4094 local_irq_disable();
4095 now_ns = get_kernel_ns();
4096 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
4099 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
4102 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
4107 case KVM_ENABLE_CAP: {
4108 struct kvm_enable_cap cap;
4111 if (copy_from_user(&cap, argp, sizeof(cap)))
4113 r = kvm_vm_ioctl_enable_cap(kvm, &cap);
4117 r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
4123 static void kvm_init_msr_list(void)
4128 for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
4129 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
4133 * Even MSRs that are valid in the host may not be exposed
4134 * to the guests in some cases.
4136 switch (msrs_to_save[i]) {
4137 case MSR_IA32_BNDCFGS:
4138 if (!kvm_x86_ops->mpx_supported())
4142 if (!kvm_x86_ops->rdtscp_supported())
4150 msrs_to_save[j] = msrs_to_save[i];
4153 num_msrs_to_save = j;
4155 for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
4156 if (!kvm_x86_ops->has_emulated_msr(emulated_msrs[i]))
4160 emulated_msrs[j] = emulated_msrs[i];
4163 num_emulated_msrs = j;
4166 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
4174 if (!(vcpu->arch.apic &&
4175 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
4176 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
4187 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
4194 if (!(vcpu->arch.apic &&
4195 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
4197 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
4199 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
4209 static void kvm_set_segment(struct kvm_vcpu *vcpu,
4210 struct kvm_segment *var, int seg)
4212 kvm_x86_ops->set_segment(vcpu, var, seg);
4215 void kvm_get_segment(struct kvm_vcpu *vcpu,
4216 struct kvm_segment *var, int seg)
4218 kvm_x86_ops->get_segment(vcpu, var, seg);
4221 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
4222 struct x86_exception *exception)
4226 BUG_ON(!mmu_is_nested(vcpu));
4228 /* NPT walks are always user-walks */
4229 access |= PFERR_USER_MASK;
4230 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
4235 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
4236 struct x86_exception *exception)
4238 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4239 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4242 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
4243 struct x86_exception *exception)
4245 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4246 access |= PFERR_FETCH_MASK;
4247 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4250 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4251 struct x86_exception *exception)
4253 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4254 access |= PFERR_WRITE_MASK;
4255 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4258 /* uses this to access any guest's mapped memory without checking CPL */
4259 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4260 struct x86_exception *exception)
4262 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
4265 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4266 struct kvm_vcpu *vcpu, u32 access,
4267 struct x86_exception *exception)
4270 int r = X86EMUL_CONTINUE;
4273 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4275 unsigned offset = addr & (PAGE_SIZE-1);
4276 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4279 if (gpa == UNMAPPED_GVA)
4280 return X86EMUL_PROPAGATE_FAULT;
4281 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
4284 r = X86EMUL_IO_NEEDED;
4296 /* used for instruction fetching */
4297 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4298 gva_t addr, void *val, unsigned int bytes,
4299 struct x86_exception *exception)
4301 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4302 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4306 /* Inline kvm_read_guest_virt_helper for speed. */
4307 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
4309 if (unlikely(gpa == UNMAPPED_GVA))
4310 return X86EMUL_PROPAGATE_FAULT;
4312 offset = addr & (PAGE_SIZE-1);
4313 if (WARN_ON(offset + bytes > PAGE_SIZE))
4314 bytes = (unsigned)PAGE_SIZE - offset;
4315 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
4317 if (unlikely(ret < 0))
4318 return X86EMUL_IO_NEEDED;
4320 return X86EMUL_CONTINUE;
4323 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
4324 gva_t addr, void *val, unsigned int bytes,
4325 struct x86_exception *exception)
4327 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4330 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
4331 * is returned, but our callers are not ready for that and they blindly
4332 * call kvm_inject_page_fault. Ensure that they at least do not leak
4333 * uninitialized kernel stack memory into cr2 and error code.
4335 memset(exception, 0, sizeof(*exception));
4336 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4339 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4341 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
4342 gva_t addr, void *val, unsigned int bytes,
4343 struct x86_exception *exception, bool system)
4345 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4348 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
4349 access |= PFERR_USER_MASK;
4351 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
4354 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
4355 unsigned long addr, void *val, unsigned int bytes)
4357 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4358 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
4360 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
4363 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4364 struct kvm_vcpu *vcpu, u32 access,
4365 struct x86_exception *exception)
4368 int r = X86EMUL_CONTINUE;
4371 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4374 unsigned offset = addr & (PAGE_SIZE-1);
4375 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4378 if (gpa == UNMAPPED_GVA)
4379 return X86EMUL_PROPAGATE_FAULT;
4380 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
4382 r = X86EMUL_IO_NEEDED;
4394 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
4395 unsigned int bytes, struct x86_exception *exception,
4398 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4399 u32 access = PFERR_WRITE_MASK;
4401 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
4402 access |= PFERR_USER_MASK;
4405 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
4406 * is returned, but our callers are not ready for that and they blindly
4407 * call kvm_inject_page_fault. Ensure that they at least do not leak
4408 * uninitialized kernel stack memory into cr2 and error code.
4410 memset(exception, 0, sizeof(*exception));
4411 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4415 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
4416 unsigned int bytes, struct x86_exception *exception)
4418 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4419 PFERR_WRITE_MASK, exception);
4421 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4423 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4424 gpa_t *gpa, struct x86_exception *exception,
4427 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
4428 | (write ? PFERR_WRITE_MASK : 0);
4430 if (vcpu_match_mmio_gva(vcpu, gva)
4431 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
4432 vcpu->arch.access, access)) {
4433 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4434 (gva & (PAGE_SIZE - 1));
4435 trace_vcpu_match_mmio(gva, *gpa, write, false);
4439 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4441 if (*gpa == UNMAPPED_GVA)
4444 /* For APIC access vmexit */
4445 if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4448 if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
4449 trace_vcpu_match_mmio(gva, *gpa, write, true);
4456 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4457 const void *val, int bytes)
4461 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
4464 kvm_mmu_pte_write(vcpu, gpa, val, bytes);
4468 struct read_write_emulator_ops {
4469 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4471 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4472 void *val, int bytes);
4473 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4474 int bytes, void *val);
4475 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4476 void *val, int bytes);
4480 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4482 if (vcpu->mmio_read_completed) {
4483 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4484 vcpu->mmio_fragments[0].gpa, val);
4485 vcpu->mmio_read_completed = 0;
4492 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4493 void *val, int bytes)
4495 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
4498 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4499 void *val, int bytes)
4501 return emulator_write_phys(vcpu, gpa, val, bytes);
4504 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4506 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
4507 return vcpu_mmio_write(vcpu, gpa, bytes, val);
4510 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4511 void *val, int bytes)
4513 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
4514 return X86EMUL_IO_NEEDED;
4517 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4518 void *val, int bytes)
4520 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
4522 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
4523 return X86EMUL_CONTINUE;
4526 static const struct read_write_emulator_ops read_emultor = {
4527 .read_write_prepare = read_prepare,
4528 .read_write_emulate = read_emulate,
4529 .read_write_mmio = vcpu_mmio_read,
4530 .read_write_exit_mmio = read_exit_mmio,
4533 static const struct read_write_emulator_ops write_emultor = {
4534 .read_write_emulate = write_emulate,
4535 .read_write_mmio = write_mmio,
4536 .read_write_exit_mmio = write_exit_mmio,
4540 static int emulator_read_write_onepage(unsigned long addr, void *val,
4542 struct x86_exception *exception,
4543 struct kvm_vcpu *vcpu,
4544 const struct read_write_emulator_ops *ops)
4548 bool write = ops->write;
4549 struct kvm_mmio_fragment *frag;
4551 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4554 return X86EMUL_PROPAGATE_FAULT;
4556 /* For APIC access vmexit */
4560 if (ops->read_write_emulate(vcpu, gpa, val, bytes))
4561 return X86EMUL_CONTINUE;
4565 * Is this MMIO handled locally?
4567 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4568 if (handled == bytes)
4569 return X86EMUL_CONTINUE;
4575 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
4576 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
4580 return X86EMUL_CONTINUE;
4583 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
4585 void *val, unsigned int bytes,
4586 struct x86_exception *exception,
4587 const struct read_write_emulator_ops *ops)
4589 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4593 if (ops->read_write_prepare &&
4594 ops->read_write_prepare(vcpu, val, bytes))
4595 return X86EMUL_CONTINUE;
4597 vcpu->mmio_nr_fragments = 0;
4599 /* Crossing a page boundary? */
4600 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4603 now = -addr & ~PAGE_MASK;
4604 rc = emulator_read_write_onepage(addr, val, now, exception,
4607 if (rc != X86EMUL_CONTINUE)
4610 if (ctxt->mode != X86EMUL_MODE_PROT64)
4616 rc = emulator_read_write_onepage(addr, val, bytes, exception,
4618 if (rc != X86EMUL_CONTINUE)
4621 if (!vcpu->mmio_nr_fragments)
4624 gpa = vcpu->mmio_fragments[0].gpa;
4626 vcpu->mmio_needed = 1;
4627 vcpu->mmio_cur_fragment = 0;
4629 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
4630 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
4631 vcpu->run->exit_reason = KVM_EXIT_MMIO;
4632 vcpu->run->mmio.phys_addr = gpa;
4634 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4637 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4641 struct x86_exception *exception)
4643 return emulator_read_write(ctxt, addr, val, bytes,
4644 exception, &read_emultor);
4647 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4651 struct x86_exception *exception)
4653 return emulator_read_write(ctxt, addr, (void *)val, bytes,
4654 exception, &write_emultor);
4657 #define CMPXCHG_TYPE(t, ptr, old, new) \
4658 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4660 #ifdef CONFIG_X86_64
4661 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4663 # define CMPXCHG64(ptr, old, new) \
4664 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4667 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4672 struct x86_exception *exception)
4674 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4680 /* guests cmpxchg8b have to be emulated atomically */
4681 if (bytes > 8 || (bytes & (bytes - 1)))
4684 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4686 if (gpa == UNMAPPED_GVA ||
4687 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4690 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4693 page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
4694 if (is_error_page(page))
4697 kaddr = kmap_atomic(page);
4698 kaddr += offset_in_page(gpa);
4701 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4704 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4707 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
4710 exchanged = CMPXCHG64(kaddr, old, new);
4715 kunmap_atomic(kaddr);
4716 kvm_release_page_dirty(page);
4719 return X86EMUL_CMPXCHG_FAILED;
4721 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
4722 kvm_mmu_pte_write(vcpu, gpa, new, bytes);
4724 return X86EMUL_CONTINUE;
4727 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
4729 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
4732 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
4736 for (i = 0; i < vcpu->arch.pio.count; i++) {
4737 if (vcpu->arch.pio.in)
4738 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
4739 vcpu->arch.pio.size, pd);
4741 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
4742 vcpu->arch.pio.port, vcpu->arch.pio.size,
4746 pd += vcpu->arch.pio.size;
4751 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
4752 unsigned short port, void *val,
4753 unsigned int count, bool in)
4755 vcpu->arch.pio.port = port;
4756 vcpu->arch.pio.in = in;
4757 vcpu->arch.pio.count = count;
4758 vcpu->arch.pio.size = size;
4760 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4761 vcpu->arch.pio.count = 0;
4765 vcpu->run->exit_reason = KVM_EXIT_IO;
4766 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
4767 vcpu->run->io.size = size;
4768 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4769 vcpu->run->io.count = count;
4770 vcpu->run->io.port = port;
4775 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
4776 int size, unsigned short port, void *val,
4779 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4782 if (vcpu->arch.pio.count)
4785 memset(vcpu->arch.pio_data, 0, size * count);
4787 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
4790 memcpy(val, vcpu->arch.pio_data, size * count);
4791 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
4792 vcpu->arch.pio.count = 0;
4799 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
4800 int size, unsigned short port,
4801 const void *val, unsigned int count)
4803 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4805 memcpy(vcpu->arch.pio_data, val, size * count);
4806 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
4807 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
4810 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
4812 return kvm_x86_ops->get_segment_base(vcpu, seg);
4815 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
4817 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
4820 int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
4822 if (!need_emulate_wbinvd(vcpu))
4823 return X86EMUL_CONTINUE;
4825 if (kvm_x86_ops->has_wbinvd_exit()) {
4826 int cpu = get_cpu();
4828 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4829 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
4830 wbinvd_ipi, NULL, 1);
4832 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
4835 return X86EMUL_CONTINUE;
4838 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
4840 kvm_x86_ops->skip_emulated_instruction(vcpu);
4841 return kvm_emulate_wbinvd_noskip(vcpu);
4843 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
4847 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
4849 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
4852 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
4853 unsigned long *dest)
4855 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
4858 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
4859 unsigned long value)
4862 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
4865 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
4867 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
4870 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
4872 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4873 unsigned long value;
4877 value = kvm_read_cr0(vcpu);
4880 value = vcpu->arch.cr2;
4883 value = kvm_read_cr3(vcpu);
4886 value = kvm_read_cr4(vcpu);
4889 value = kvm_get_cr8(vcpu);
4892 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4899 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
4901 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4906 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4909 vcpu->arch.cr2 = val;
4912 res = kvm_set_cr3(vcpu, val);
4915 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4918 res = kvm_set_cr8(vcpu, val);
4921 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4928 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
4930 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
4933 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4935 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
4938 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4940 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
4943 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4945 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4948 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4950 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4953 static unsigned long emulator_get_cached_segment_base(
4954 struct x86_emulate_ctxt *ctxt, int seg)
4956 return get_segment_base(emul_to_vcpu(ctxt), seg);
4959 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4960 struct desc_struct *desc, u32 *base3,
4963 struct kvm_segment var;
4965 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
4966 *selector = var.selector;
4969 memset(desc, 0, sizeof(*desc));
4977 set_desc_limit(desc, var.limit);
4978 set_desc_base(desc, (unsigned long)var.base);
4979 #ifdef CONFIG_X86_64
4981 *base3 = var.base >> 32;
4983 desc->type = var.type;
4985 desc->dpl = var.dpl;
4986 desc->p = var.present;
4987 desc->avl = var.avl;
4995 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
4996 struct desc_struct *desc, u32 base3,
4999 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5000 struct kvm_segment var;
5002 var.selector = selector;
5003 var.base = get_desc_base(desc);
5004 #ifdef CONFIG_X86_64
5005 var.base |= ((u64)base3) << 32;
5007 var.limit = get_desc_limit(desc);
5009 var.limit = (var.limit << 12) | 0xfff;
5010 var.type = desc->type;
5011 var.dpl = desc->dpl;
5016 var.avl = desc->avl;
5017 var.present = desc->p;
5018 var.unusable = !var.present;
5021 kvm_set_segment(vcpu, &var, seg);
5025 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
5026 u32 msr_index, u64 *pdata)
5028 struct msr_data msr;
5031 msr.index = msr_index;
5032 msr.host_initiated = false;
5033 r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
5041 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
5042 u32 msr_index, u64 data)
5044 struct msr_data msr;
5047 msr.index = msr_index;
5048 msr.host_initiated = false;
5049 return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
5052 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
5054 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5056 return vcpu->arch.smbase;
5059 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
5061 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5063 vcpu->arch.smbase = smbase;
5066 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
5069 return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
5072 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
5073 u32 pmc, u64 *pdata)
5075 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
5078 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
5080 emul_to_vcpu(ctxt)->arch.halt_request = 1;
5083 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
5086 kvm_load_guest_fpu(emul_to_vcpu(ctxt));
5088 * CR0.TS may reference the host fpu state, not the guest fpu state,
5089 * so it may be clear at this point.
5094 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
5099 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
5100 struct x86_instruction_info *info,
5101 enum x86_intercept_stage stage)
5103 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
5106 static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
5107 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
5109 kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
5112 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
5114 return kvm_register_read(emul_to_vcpu(ctxt), reg);
5117 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
5119 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
5122 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
5124 kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
5127 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
5129 return emul_to_vcpu(ctxt)->arch.hflags;
5132 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
5134 kvm_set_hflags(emul_to_vcpu(ctxt), emul_flags);
5137 static const struct x86_emulate_ops emulate_ops = {
5138 .read_gpr = emulator_read_gpr,
5139 .write_gpr = emulator_write_gpr,
5140 .read_std = emulator_read_std,
5141 .write_std = emulator_write_std,
5142 .read_phys = kvm_read_guest_phys_system,
5143 .fetch = kvm_fetch_guest_virt,
5144 .read_emulated = emulator_read_emulated,
5145 .write_emulated = emulator_write_emulated,
5146 .cmpxchg_emulated = emulator_cmpxchg_emulated,
5147 .invlpg = emulator_invlpg,
5148 .pio_in_emulated = emulator_pio_in_emulated,
5149 .pio_out_emulated = emulator_pio_out_emulated,
5150 .get_segment = emulator_get_segment,
5151 .set_segment = emulator_set_segment,
5152 .get_cached_segment_base = emulator_get_cached_segment_base,
5153 .get_gdt = emulator_get_gdt,
5154 .get_idt = emulator_get_idt,
5155 .set_gdt = emulator_set_gdt,
5156 .set_idt = emulator_set_idt,
5157 .get_cr = emulator_get_cr,
5158 .set_cr = emulator_set_cr,
5159 .cpl = emulator_get_cpl,
5160 .get_dr = emulator_get_dr,
5161 .set_dr = emulator_set_dr,
5162 .get_smbase = emulator_get_smbase,
5163 .set_smbase = emulator_set_smbase,
5164 .set_msr = emulator_set_msr,
5165 .get_msr = emulator_get_msr,
5166 .check_pmc = emulator_check_pmc,
5167 .read_pmc = emulator_read_pmc,
5168 .halt = emulator_halt,
5169 .wbinvd = emulator_wbinvd,
5170 .fix_hypercall = emulator_fix_hypercall,
5171 .get_fpu = emulator_get_fpu,
5172 .put_fpu = emulator_put_fpu,
5173 .intercept = emulator_intercept,
5174 .get_cpuid = emulator_get_cpuid,
5175 .set_nmi_mask = emulator_set_nmi_mask,
5176 .get_hflags = emulator_get_hflags,
5177 .set_hflags = emulator_set_hflags,
5180 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
5182 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
5184 * an sti; sti; sequence only disable interrupts for the first
5185 * instruction. So, if the last instruction, be it emulated or
5186 * not, left the system with the INT_STI flag enabled, it
5187 * means that the last instruction is an sti. We should not
5188 * leave the flag on in this case. The same goes for mov ss
5190 if (int_shadow & mask)
5192 if (unlikely(int_shadow || mask)) {
5193 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
5195 kvm_make_request(KVM_REQ_EVENT, vcpu);
5199 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
5201 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5202 if (ctxt->exception.vector == PF_VECTOR)
5203 return kvm_propagate_fault(vcpu, &ctxt->exception);
5205 if (ctxt->exception.error_code_valid)
5206 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
5207 ctxt->exception.error_code);
5209 kvm_queue_exception(vcpu, ctxt->exception.vector);
5213 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
5215 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5218 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5220 ctxt->eflags = kvm_get_rflags(vcpu);
5221 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
5223 ctxt->eip = kvm_rip_read(vcpu);
5224 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
5225 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
5226 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
5227 cs_db ? X86EMUL_MODE_PROT32 :
5228 X86EMUL_MODE_PROT16;
5229 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
5230 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
5231 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
5233 init_decode_cache(ctxt);
5234 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5237 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
5239 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5242 init_emulate_ctxt(vcpu);
5246 ctxt->_eip = ctxt->eip + inc_eip;
5247 ret = emulate_int_real(ctxt, irq);
5249 if (ret != X86EMUL_CONTINUE)
5250 return EMULATE_FAIL;
5252 ctxt->eip = ctxt->_eip;
5253 kvm_rip_write(vcpu, ctxt->eip);
5254 kvm_set_rflags(vcpu, ctxt->eflags);
5256 if (irq == NMI_VECTOR)
5257 vcpu->arch.nmi_pending = 0;
5259 vcpu->arch.interrupt.pending = false;
5261 return EMULATE_DONE;
5263 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
5265 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
5267 int r = EMULATE_DONE;
5269 ++vcpu->stat.insn_emulation_fail;
5270 trace_kvm_emulate_insn_failed(vcpu);
5271 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
5272 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5273 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5274 vcpu->run->internal.ndata = 0;
5275 r = EMULATE_USER_EXIT;
5277 kvm_queue_exception(vcpu, UD_VECTOR);
5282 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5283 bool write_fault_to_shadow_pgtable,
5289 if (emulation_type & EMULTYPE_NO_REEXECUTE)
5292 if (!vcpu->arch.mmu.direct_map) {
5294 * Write permission should be allowed since only
5295 * write access need to be emulated.
5297 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5300 * If the mapping is invalid in guest, let cpu retry
5301 * it to generate fault.
5303 if (gpa == UNMAPPED_GVA)
5308 * Do not retry the unhandleable instruction if it faults on the
5309 * readonly host memory, otherwise it will goto a infinite loop:
5310 * retry instruction -> write #PF -> emulation fail -> retry
5311 * instruction -> ...
5313 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
5316 * If the instruction failed on the error pfn, it can not be fixed,
5317 * report the error to userspace.
5319 if (is_error_noslot_pfn(pfn))
5322 kvm_release_pfn_clean(pfn);
5324 /* The instructions are well-emulated on direct mmu. */
5325 if (vcpu->arch.mmu.direct_map) {
5326 unsigned int indirect_shadow_pages;
5328 spin_lock(&vcpu->kvm->mmu_lock);
5329 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
5330 spin_unlock(&vcpu->kvm->mmu_lock);
5332 if (indirect_shadow_pages)
5333 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5339 * if emulation was due to access to shadowed page table
5340 * and it failed try to unshadow page and re-enter the
5341 * guest to let CPU execute the instruction.
5343 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5346 * If the access faults on its page table, it can not
5347 * be fixed by unprotecting shadow page and it should
5348 * be reported to userspace.
5350 return !write_fault_to_shadow_pgtable;
5353 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5354 unsigned long cr2, int emulation_type)
5356 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5357 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
5359 last_retry_eip = vcpu->arch.last_retry_eip;
5360 last_retry_addr = vcpu->arch.last_retry_addr;
5363 * If the emulation is caused by #PF and it is non-page_table
5364 * writing instruction, it means the VM-EXIT is caused by shadow
5365 * page protected, we can zap the shadow page and retry this
5366 * instruction directly.
5368 * Note: if the guest uses a non-page-table modifying instruction
5369 * on the PDE that points to the instruction, then we will unmap
5370 * the instruction and go to an infinite loop. So, we cache the
5371 * last retried eip and the last fault address, if we meet the eip
5372 * and the address again, we can break out of the potential infinite
5375 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
5377 if (!(emulation_type & EMULTYPE_RETRY))
5380 if (x86_page_table_writing_insn(ctxt))
5383 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
5386 vcpu->arch.last_retry_eip = ctxt->eip;
5387 vcpu->arch.last_retry_addr = cr2;
5389 if (!vcpu->arch.mmu.direct_map)
5390 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5392 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5397 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
5398 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
5400 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
5402 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
5403 /* This is a good place to trace that we are exiting SMM. */
5404 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
5406 if (unlikely(vcpu->arch.smi_pending)) {
5407 kvm_make_request(KVM_REQ_SMI, vcpu);
5408 vcpu->arch.smi_pending = 0;
5410 /* Process a latched INIT, if any. */
5411 kvm_make_request(KVM_REQ_EVENT, vcpu);
5415 kvm_mmu_reset_context(vcpu);
5418 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
5420 unsigned changed = vcpu->arch.hflags ^ emul_flags;
5422 vcpu->arch.hflags = emul_flags;
5424 if (changed & HF_SMM_MASK)
5425 kvm_smm_changed(vcpu);
5428 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
5437 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
5438 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
5443 static void kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu, int *r)
5445 struct kvm_run *kvm_run = vcpu->run;
5447 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5448 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
5449 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
5450 kvm_run->debug.arch.exception = DB_VECTOR;
5451 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5452 *r = EMULATE_USER_EXIT;
5454 vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF;
5456 * "Certain debug exceptions may clear bit 0-3. The
5457 * remaining contents of the DR6 register are never
5458 * cleared by the processor".
5460 vcpu->arch.dr6 &= ~15;
5461 vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
5462 kvm_queue_exception(vcpu, DB_VECTOR);
5466 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
5468 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
5469 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
5470 struct kvm_run *kvm_run = vcpu->run;
5471 unsigned long eip = kvm_get_linear_rip(vcpu);
5472 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5473 vcpu->arch.guest_debug_dr7,
5477 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
5478 kvm_run->debug.arch.pc = eip;
5479 kvm_run->debug.arch.exception = DB_VECTOR;
5480 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5481 *r = EMULATE_USER_EXIT;
5486 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
5487 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
5488 unsigned long eip = kvm_get_linear_rip(vcpu);
5489 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5494 vcpu->arch.dr6 &= ~15;
5495 vcpu->arch.dr6 |= dr6 | DR6_RTM;
5496 kvm_queue_exception(vcpu, DB_VECTOR);
5505 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
5512 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5513 bool writeback = true;
5514 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
5517 * Clear write_fault_to_shadow_pgtable here to ensure it is
5520 vcpu->arch.write_fault_to_shadow_pgtable = false;
5521 kvm_clear_exception_queue(vcpu);
5523 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
5524 init_emulate_ctxt(vcpu);
5527 * We will reenter on the same instruction since
5528 * we do not set complete_userspace_io. This does not
5529 * handle watchpoints yet, those would be handled in
5532 if (!(emulation_type & EMULTYPE_SKIP) &&
5533 kvm_vcpu_check_breakpoint(vcpu, &r))
5536 ctxt->interruptibility = 0;
5537 ctxt->have_exception = false;
5538 ctxt->exception.vector = -1;
5539 ctxt->perm_ok = false;
5541 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
5543 r = x86_decode_insn(ctxt, insn, insn_len);
5545 trace_kvm_emulate_insn_start(vcpu);
5546 ++vcpu->stat.insn_emulation;
5547 if (r != EMULATION_OK) {
5548 if (emulation_type & EMULTYPE_TRAP_UD)
5549 return EMULATE_FAIL;
5550 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5552 return EMULATE_DONE;
5553 if (ctxt->have_exception) {
5555 * #UD should result in just EMULATION_FAILED, and trap-like
5556 * exception should not be encountered during decode.
5558 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
5559 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
5560 inject_emulated_exception(vcpu);
5561 return EMULATE_DONE;
5563 if (emulation_type & EMULTYPE_SKIP)
5564 return EMULATE_FAIL;
5565 return handle_emulation_failure(vcpu);
5569 if (emulation_type & EMULTYPE_SKIP) {
5570 kvm_rip_write(vcpu, ctxt->_eip);
5571 if (ctxt->eflags & X86_EFLAGS_RF)
5572 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
5573 return EMULATE_DONE;
5576 if (retry_instruction(ctxt, cr2, emulation_type))
5577 return EMULATE_DONE;
5579 /* this is needed for vmware backdoor interface to work since it
5580 changes registers values during IO operation */
5581 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
5582 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5583 emulator_invalidate_register_cache(ctxt);
5587 r = x86_emulate_insn(ctxt);
5589 if (r == EMULATION_INTERCEPTED)
5590 return EMULATE_DONE;
5592 if (r == EMULATION_FAILED) {
5593 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5595 return EMULATE_DONE;
5597 return handle_emulation_failure(vcpu);
5600 if (ctxt->have_exception) {
5602 if (inject_emulated_exception(vcpu))
5604 } else if (vcpu->arch.pio.count) {
5605 if (!vcpu->arch.pio.in) {
5606 /* FIXME: return into emulator if single-stepping. */
5607 vcpu->arch.pio.count = 0;
5610 vcpu->arch.complete_userspace_io = complete_emulated_pio;
5612 r = EMULATE_USER_EXIT;
5613 } else if (vcpu->mmio_needed) {
5614 if (!vcpu->mmio_is_write)
5616 r = EMULATE_USER_EXIT;
5617 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
5618 } else if (r == EMULATION_RESTART)
5624 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5625 toggle_interruptibility(vcpu, ctxt->interruptibility);
5626 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5627 if (!ctxt->have_exception ||
5628 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
5629 kvm_rip_write(vcpu, ctxt->eip);
5630 if (r == EMULATE_DONE && ctxt->tf)
5631 kvm_vcpu_do_singlestep(vcpu, &r);
5632 __kvm_set_rflags(vcpu, ctxt->eflags);
5636 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
5637 * do nothing, and it will be requested again as soon as
5638 * the shadow expires. But we still need to check here,
5639 * because POPF has no interrupt shadow.
5641 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
5642 kvm_make_request(KVM_REQ_EVENT, vcpu);
5644 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5648 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5650 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5652 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5653 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5654 size, port, &val, 1);
5655 /* do not return to emulator after return from userspace */
5656 vcpu->arch.pio.count = 0;
5659 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5661 static void tsc_bad(void *info)
5663 __this_cpu_write(cpu_tsc_khz, 0);
5666 static void tsc_khz_changed(void *data)
5668 struct cpufreq_freqs *freq = data;
5669 unsigned long khz = 0;
5673 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5674 khz = cpufreq_quick_get(raw_smp_processor_id());
5677 __this_cpu_write(cpu_tsc_khz, khz);
5680 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5683 struct cpufreq_freqs *freq = data;
5685 struct kvm_vcpu *vcpu;
5686 int i, send_ipi = 0;
5689 * We allow guests to temporarily run on slowing clocks,
5690 * provided we notify them after, or to run on accelerating
5691 * clocks, provided we notify them before. Thus time never
5694 * However, we have a problem. We can't atomically update
5695 * the frequency of a given CPU from this function; it is
5696 * merely a notifier, which can be called from any CPU.
5697 * Changing the TSC frequency at arbitrary points in time
5698 * requires a recomputation of local variables related to
5699 * the TSC for each VCPU. We must flag these local variables
5700 * to be updated and be sure the update takes place with the
5701 * new frequency before any guests proceed.
5703 * Unfortunately, the combination of hotplug CPU and frequency
5704 * change creates an intractable locking scenario; the order
5705 * of when these callouts happen is undefined with respect to
5706 * CPU hotplug, and they can race with each other. As such,
5707 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5708 * undefined; you can actually have a CPU frequency change take
5709 * place in between the computation of X and the setting of the
5710 * variable. To protect against this problem, all updates of
5711 * the per_cpu tsc_khz variable are done in an interrupt
5712 * protected IPI, and all callers wishing to update the value
5713 * must wait for a synchronous IPI to complete (which is trivial
5714 * if the caller is on the CPU already). This establishes the
5715 * necessary total order on variable updates.
5717 * Note that because a guest time update may take place
5718 * anytime after the setting of the VCPU's request bit, the
5719 * correct TSC value must be set before the request. However,
5720 * to ensure the update actually makes it to any guest which
5721 * starts running in hardware virtualization between the set
5722 * and the acquisition of the spinlock, we must also ping the
5723 * CPU after setting the request bit.
5727 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
5729 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
5732 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5734 spin_lock(&kvm_lock);
5735 list_for_each_entry(kvm, &vm_list, vm_list) {
5736 kvm_for_each_vcpu(i, vcpu, kvm) {
5737 if (vcpu->cpu != freq->cpu)
5739 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5740 if (vcpu->cpu != smp_processor_id())
5744 spin_unlock(&kvm_lock);
5746 if (freq->old < freq->new && send_ipi) {
5748 * We upscale the frequency. Must make the guest
5749 * doesn't see old kvmclock values while running with
5750 * the new frequency, otherwise we risk the guest sees
5751 * time go backwards.
5753 * In case we update the frequency for another cpu
5754 * (which might be in guest context) send an interrupt
5755 * to kick the cpu out of guest context. Next time
5756 * guest context is entered kvmclock will be updated,
5757 * so the guest will not see stale values.
5759 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5764 static struct notifier_block kvmclock_cpufreq_notifier_block = {
5765 .notifier_call = kvmclock_cpufreq_notifier
5768 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
5769 unsigned long action, void *hcpu)
5771 unsigned int cpu = (unsigned long)hcpu;
5775 case CPU_DOWN_FAILED:
5776 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5778 case CPU_DOWN_PREPARE:
5779 smp_call_function_single(cpu, tsc_bad, NULL, 1);
5785 static struct notifier_block kvmclock_cpu_notifier_block = {
5786 .notifier_call = kvmclock_cpu_notifier,
5787 .priority = -INT_MAX
5790 static void kvm_timer_init(void)
5794 max_tsc_khz = tsc_khz;
5796 cpu_notifier_register_begin();
5797 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5798 #ifdef CONFIG_CPU_FREQ
5799 struct cpufreq_policy policy;
5800 memset(&policy, 0, sizeof(policy));
5802 cpufreq_get_policy(&policy, cpu);
5803 if (policy.cpuinfo.max_freq)
5804 max_tsc_khz = policy.cpuinfo.max_freq;
5807 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
5808 CPUFREQ_TRANSITION_NOTIFIER);
5810 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
5811 for_each_online_cpu(cpu)
5812 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5814 __register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5815 cpu_notifier_register_done();
5819 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
5821 int kvm_is_in_guest(void)
5823 return __this_cpu_read(current_vcpu) != NULL;
5826 static int kvm_is_user_mode(void)
5830 if (__this_cpu_read(current_vcpu))
5831 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
5833 return user_mode != 0;
5836 static unsigned long kvm_get_guest_ip(void)
5838 unsigned long ip = 0;
5840 if (__this_cpu_read(current_vcpu))
5841 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
5846 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5847 .is_in_guest = kvm_is_in_guest,
5848 .is_user_mode = kvm_is_user_mode,
5849 .get_guest_ip = kvm_get_guest_ip,
5852 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
5854 __this_cpu_write(current_vcpu, vcpu);
5856 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
5858 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
5860 __this_cpu_write(current_vcpu, NULL);
5862 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
5864 static void kvm_set_mmio_spte_mask(void)
5867 int maxphyaddr = boot_cpu_data.x86_phys_bits;
5870 * Set the reserved bits and the present bit of an paging-structure
5871 * entry to generate page fault with PFER.RSV = 1.
5873 /* Mask the reserved physical address bits. */
5874 mask = rsvd_bits(maxphyaddr, 51);
5876 /* Bit 62 is always reserved for 32bit host. */
5877 mask |= 0x3ull << 62;
5879 /* Set the present bit. */
5882 #ifdef CONFIG_X86_64
5884 * If reserved bit is not supported, clear the present bit to disable
5887 if (maxphyaddr == 52)
5891 kvm_mmu_set_mmio_spte_mask(mask);
5894 #ifdef CONFIG_X86_64
5895 static void pvclock_gtod_update_fn(struct work_struct *work)
5899 struct kvm_vcpu *vcpu;
5902 spin_lock(&kvm_lock);
5903 list_for_each_entry(kvm, &vm_list, vm_list)
5904 kvm_for_each_vcpu(i, vcpu, kvm)
5905 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
5906 atomic_set(&kvm_guest_has_master_clock, 0);
5907 spin_unlock(&kvm_lock);
5910 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
5913 * Notification about pvclock gtod data update.
5915 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
5918 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
5919 struct timekeeper *tk = priv;
5921 update_pvclock_gtod(tk);
5923 /* disable master clock if host does not trust, or does not
5924 * use, TSC clocksource
5926 if (gtod->clock.vclock_mode != VCLOCK_TSC &&
5927 atomic_read(&kvm_guest_has_master_clock) != 0)
5928 queue_work(system_long_wq, &pvclock_gtod_work);
5933 static struct notifier_block pvclock_gtod_notifier = {
5934 .notifier_call = pvclock_gtod_notify,
5938 int kvm_arch_init(void *opaque)
5941 struct kvm_x86_ops *ops = opaque;
5944 printk(KERN_ERR "kvm: already loaded the other module\n");
5949 if (!ops->cpu_has_kvm_support()) {
5950 printk(KERN_ERR "kvm: no hardware support\n");
5954 if (ops->disabled_by_bios()) {
5955 printk(KERN_ERR "kvm: disabled by bios\n");
5961 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
5963 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
5967 r = kvm_mmu_module_init();
5969 goto out_free_percpu;
5971 kvm_set_mmio_spte_mask();
5975 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
5976 PT_DIRTY_MASK, PT64_NX_MASK, 0);
5980 perf_register_guest_info_callbacks(&kvm_guest_cbs);
5983 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
5986 #ifdef CONFIG_X86_64
5987 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
5993 free_percpu(shared_msrs);
5998 void kvm_arch_exit(void)
6001 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
6003 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6004 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
6005 CPUFREQ_TRANSITION_NOTIFIER);
6006 unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
6007 #ifdef CONFIG_X86_64
6008 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
6011 kvm_mmu_module_exit();
6012 free_percpu(shared_msrs);
6015 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
6017 ++vcpu->stat.halt_exits;
6018 if (lapic_in_kernel(vcpu)) {
6019 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
6022 vcpu->run->exit_reason = KVM_EXIT_HLT;
6026 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
6028 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
6030 kvm_x86_ops->skip_emulated_instruction(vcpu);
6031 return kvm_vcpu_halt(vcpu);
6033 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
6036 * kvm_pv_kick_cpu_op: Kick a vcpu.
6038 * @apicid - apicid of vcpu to be kicked.
6040 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
6042 struct kvm_lapic_irq lapic_irq;
6044 lapic_irq.shorthand = 0;
6045 lapic_irq.dest_mode = 0;
6046 lapic_irq.dest_id = apicid;
6047 lapic_irq.msi_redir_hint = false;
6049 lapic_irq.delivery_mode = APIC_DM_REMRD;
6050 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
6053 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
6055 unsigned long nr, a0, a1, a2, a3, ret;
6056 int op_64_bit, r = 1;
6058 kvm_x86_ops->skip_emulated_instruction(vcpu);
6060 if (kvm_hv_hypercall_enabled(vcpu->kvm))
6061 return kvm_hv_hypercall(vcpu);
6063 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
6064 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
6065 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
6066 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
6067 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
6069 trace_kvm_hypercall(nr, a0, a1, a2, a3);
6071 op_64_bit = is_64_bit_mode(vcpu);
6080 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
6086 case KVM_HC_VAPIC_POLL_IRQ:
6089 case KVM_HC_KICK_CPU:
6090 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
6100 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
6101 ++vcpu->stat.hypercalls;
6104 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
6106 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
6108 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6109 char instruction[3];
6110 unsigned long rip = kvm_rip_read(vcpu);
6112 kvm_x86_ops->patch_hypercall(vcpu, instruction);
6114 return emulator_write_emulated(ctxt, rip, instruction, 3,
6118 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
6120 return vcpu->run->request_interrupt_window &&
6121 likely(!pic_in_kernel(vcpu->kvm));
6124 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
6126 struct kvm_run *kvm_run = vcpu->run;
6128 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
6129 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
6130 kvm_run->cr8 = kvm_get_cr8(vcpu);
6131 kvm_run->apic_base = kvm_get_apic_base(vcpu);
6132 kvm_run->ready_for_interrupt_injection =
6133 pic_in_kernel(vcpu->kvm) ||
6134 kvm_vcpu_ready_for_interrupt_injection(vcpu);
6137 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
6141 if (!kvm_x86_ops->update_cr8_intercept)
6144 if (!vcpu->arch.apic)
6147 if (!vcpu->arch.apic->vapic_addr)
6148 max_irr = kvm_lapic_find_highest_irr(vcpu);
6155 tpr = kvm_lapic_get_cr8(vcpu);
6157 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
6160 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
6164 /* try to reinject previous events if any */
6165 if (vcpu->arch.exception.pending) {
6166 trace_kvm_inj_exception(vcpu->arch.exception.nr,
6167 vcpu->arch.exception.has_error_code,
6168 vcpu->arch.exception.error_code);
6170 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
6171 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
6174 if (vcpu->arch.exception.nr == DB_VECTOR &&
6175 (vcpu->arch.dr7 & DR7_GD)) {
6176 vcpu->arch.dr7 &= ~DR7_GD;
6177 kvm_update_dr7(vcpu);
6180 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
6181 vcpu->arch.exception.has_error_code,
6182 vcpu->arch.exception.error_code,
6183 vcpu->arch.exception.reinject);
6187 if (vcpu->arch.nmi_injected) {
6188 kvm_x86_ops->set_nmi(vcpu);
6192 if (vcpu->arch.interrupt.pending) {
6193 kvm_x86_ops->set_irq(vcpu);
6197 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6198 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6203 /* try to inject new event if pending */
6204 if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
6205 --vcpu->arch.nmi_pending;
6206 vcpu->arch.nmi_injected = true;
6207 kvm_x86_ops->set_nmi(vcpu);
6208 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
6210 * Because interrupts can be injected asynchronously, we are
6211 * calling check_nested_events again here to avoid a race condition.
6212 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
6213 * proposal and current concerns. Perhaps we should be setting
6214 * KVM_REQ_EVENT only on certain events and not unconditionally?
6216 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6217 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6221 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
6222 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
6224 kvm_x86_ops->set_irq(vcpu);
6230 static void process_nmi(struct kvm_vcpu *vcpu)
6235 * x86 is limited to one NMI running, and one NMI pending after it.
6236 * If an NMI is already in progress, limit further NMIs to just one.
6237 * Otherwise, allow two (and we'll inject the first one immediately).
6239 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
6242 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
6243 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
6244 kvm_make_request(KVM_REQ_EVENT, vcpu);
6247 #define put_smstate(type, buf, offset, val) \
6248 *(type *)((buf) + (offset) - 0x7e00) = val
6250 static u32 process_smi_get_segment_flags(struct kvm_segment *seg)
6253 flags |= seg->g << 23;
6254 flags |= seg->db << 22;
6255 flags |= seg->l << 21;
6256 flags |= seg->avl << 20;
6257 flags |= seg->present << 15;
6258 flags |= seg->dpl << 13;
6259 flags |= seg->s << 12;
6260 flags |= seg->type << 8;
6264 static void process_smi_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
6266 struct kvm_segment seg;
6269 kvm_get_segment(vcpu, &seg, n);
6270 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
6273 offset = 0x7f84 + n * 12;
6275 offset = 0x7f2c + (n - 3) * 12;
6277 put_smstate(u32, buf, offset + 8, seg.base);
6278 put_smstate(u32, buf, offset + 4, seg.limit);
6279 put_smstate(u32, buf, offset, process_smi_get_segment_flags(&seg));
6282 #ifdef CONFIG_X86_64
6283 static void process_smi_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
6285 struct kvm_segment seg;
6289 kvm_get_segment(vcpu, &seg, n);
6290 offset = 0x7e00 + n * 16;
6292 flags = process_smi_get_segment_flags(&seg) >> 8;
6293 put_smstate(u16, buf, offset, seg.selector);
6294 put_smstate(u16, buf, offset + 2, flags);
6295 put_smstate(u32, buf, offset + 4, seg.limit);
6296 put_smstate(u64, buf, offset + 8, seg.base);
6300 static void process_smi_save_state_32(struct kvm_vcpu *vcpu, char *buf)
6303 struct kvm_segment seg;
6307 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
6308 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
6309 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
6310 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
6312 for (i = 0; i < 8; i++)
6313 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
6315 kvm_get_dr(vcpu, 6, &val);
6316 put_smstate(u32, buf, 0x7fcc, (u32)val);
6317 kvm_get_dr(vcpu, 7, &val);
6318 put_smstate(u32, buf, 0x7fc8, (u32)val);
6320 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6321 put_smstate(u32, buf, 0x7fc4, seg.selector);
6322 put_smstate(u32, buf, 0x7f64, seg.base);
6323 put_smstate(u32, buf, 0x7f60, seg.limit);
6324 put_smstate(u32, buf, 0x7f5c, process_smi_get_segment_flags(&seg));
6326 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6327 put_smstate(u32, buf, 0x7fc0, seg.selector);
6328 put_smstate(u32, buf, 0x7f80, seg.base);
6329 put_smstate(u32, buf, 0x7f7c, seg.limit);
6330 put_smstate(u32, buf, 0x7f78, process_smi_get_segment_flags(&seg));
6332 kvm_x86_ops->get_gdt(vcpu, &dt);
6333 put_smstate(u32, buf, 0x7f74, dt.address);
6334 put_smstate(u32, buf, 0x7f70, dt.size);
6336 kvm_x86_ops->get_idt(vcpu, &dt);
6337 put_smstate(u32, buf, 0x7f58, dt.address);
6338 put_smstate(u32, buf, 0x7f54, dt.size);
6340 for (i = 0; i < 6; i++)
6341 process_smi_save_seg_32(vcpu, buf, i);
6343 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
6346 put_smstate(u32, buf, 0x7efc, 0x00020000);
6347 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
6350 static void process_smi_save_state_64(struct kvm_vcpu *vcpu, char *buf)
6352 #ifdef CONFIG_X86_64
6354 struct kvm_segment seg;
6358 for (i = 0; i < 16; i++)
6359 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
6361 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
6362 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
6364 kvm_get_dr(vcpu, 6, &val);
6365 put_smstate(u64, buf, 0x7f68, val);
6366 kvm_get_dr(vcpu, 7, &val);
6367 put_smstate(u64, buf, 0x7f60, val);
6369 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
6370 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
6371 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
6373 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
6376 put_smstate(u32, buf, 0x7efc, 0x00020064);
6378 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
6380 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6381 put_smstate(u16, buf, 0x7e90, seg.selector);
6382 put_smstate(u16, buf, 0x7e92, process_smi_get_segment_flags(&seg) >> 8);
6383 put_smstate(u32, buf, 0x7e94, seg.limit);
6384 put_smstate(u64, buf, 0x7e98, seg.base);
6386 kvm_x86_ops->get_idt(vcpu, &dt);
6387 put_smstate(u32, buf, 0x7e84, dt.size);
6388 put_smstate(u64, buf, 0x7e88, dt.address);
6390 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6391 put_smstate(u16, buf, 0x7e70, seg.selector);
6392 put_smstate(u16, buf, 0x7e72, process_smi_get_segment_flags(&seg) >> 8);
6393 put_smstate(u32, buf, 0x7e74, seg.limit);
6394 put_smstate(u64, buf, 0x7e78, seg.base);
6396 kvm_x86_ops->get_gdt(vcpu, &dt);
6397 put_smstate(u32, buf, 0x7e64, dt.size);
6398 put_smstate(u64, buf, 0x7e68, dt.address);
6400 for (i = 0; i < 6; i++)
6401 process_smi_save_seg_64(vcpu, buf, i);
6407 static void process_smi(struct kvm_vcpu *vcpu)
6409 struct kvm_segment cs, ds;
6415 vcpu->arch.smi_pending = true;
6419 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
6420 vcpu->arch.hflags |= HF_SMM_MASK;
6421 memset(buf, 0, 512);
6422 if (guest_cpuid_has_longmode(vcpu))
6423 process_smi_save_state_64(vcpu, buf);
6425 process_smi_save_state_32(vcpu, buf);
6427 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
6429 if (kvm_x86_ops->get_nmi_mask(vcpu))
6430 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
6432 kvm_x86_ops->set_nmi_mask(vcpu, true);
6434 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6435 kvm_rip_write(vcpu, 0x8000);
6437 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
6438 kvm_x86_ops->set_cr0(vcpu, cr0);
6439 vcpu->arch.cr0 = cr0;
6441 kvm_x86_ops->set_cr4(vcpu, 0);
6443 /* Undocumented: IDT limit is set to zero on entry to SMM. */
6444 dt.address = dt.size = 0;
6445 kvm_x86_ops->set_idt(vcpu, &dt);
6447 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
6449 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
6450 cs.base = vcpu->arch.smbase;
6455 cs.limit = ds.limit = 0xffffffff;
6456 cs.type = ds.type = 0x3;
6457 cs.dpl = ds.dpl = 0;
6462 cs.avl = ds.avl = 0;
6463 cs.present = ds.present = 1;
6464 cs.unusable = ds.unusable = 0;
6465 cs.padding = ds.padding = 0;
6467 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
6468 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
6469 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
6470 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
6471 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
6472 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
6474 if (guest_cpuid_has_longmode(vcpu))
6475 kvm_x86_ops->set_efer(vcpu, 0);
6477 kvm_update_cpuid(vcpu);
6478 kvm_mmu_reset_context(vcpu);
6481 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
6483 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
6486 memset(vcpu->arch.eoi_exit_bitmap, 0, 256 / 8);
6488 if (irqchip_split(vcpu->kvm))
6489 kvm_scan_ioapic_routes(vcpu, vcpu->arch.eoi_exit_bitmap);
6491 kvm_x86_ops->sync_pir_to_irr(vcpu);
6492 if (ioapic_in_kernel(vcpu->kvm))
6493 kvm_ioapic_scan_entry(vcpu, vcpu->arch.eoi_exit_bitmap);
6495 kvm_x86_ops->load_eoi_exitmap(vcpu);
6498 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu)
6500 ++vcpu->stat.tlb_flush;
6501 kvm_x86_ops->tlb_flush(vcpu);
6504 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
6506 struct page *page = NULL;
6508 if (!lapic_in_kernel(vcpu))
6511 if (!kvm_x86_ops->set_apic_access_page_addr)
6514 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6515 if (is_error_page(page))
6517 kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
6520 * Do not pin apic access page in memory, the MMU notifier
6521 * will call us again if it is migrated or swapped out.
6525 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
6527 void kvm_arch_mmu_notifier_invalidate_page(struct kvm *kvm,
6528 unsigned long address)
6531 * The physical address of apic access page is stored in the VMCS.
6532 * Update it when it becomes invalid.
6534 if (address == gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT))
6535 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
6539 * Returns 1 to let vcpu_run() continue the guest execution loop without
6540 * exiting to the userspace. Otherwise, the value will be returned to the
6543 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
6547 dm_request_for_irq_injection(vcpu) &&
6548 kvm_cpu_accept_dm_intr(vcpu);
6550 bool req_immediate_exit = false;
6552 if (vcpu->requests) {
6553 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
6554 kvm_mmu_unload(vcpu);
6555 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
6556 __kvm_migrate_timers(vcpu);
6557 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
6558 kvm_gen_update_masterclock(vcpu->kvm);
6559 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
6560 kvm_gen_kvmclock_update(vcpu);
6561 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
6562 r = kvm_guest_time_update(vcpu);
6566 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
6567 kvm_mmu_sync_roots(vcpu);
6568 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
6569 kvm_vcpu_flush_tlb(vcpu);
6570 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
6571 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
6575 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
6576 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6577 vcpu->mmio_needed = 0;
6581 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
6582 vcpu->fpu_active = 0;
6583 kvm_x86_ops->fpu_deactivate(vcpu);
6585 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
6586 /* Page is swapped out. Do synthetic halt */
6587 vcpu->arch.apf.halted = true;
6591 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
6592 record_steal_time(vcpu);
6593 if (kvm_check_request(KVM_REQ_SMI, vcpu))
6595 if (kvm_check_request(KVM_REQ_NMI, vcpu))
6597 if (kvm_check_request(KVM_REQ_PMU, vcpu))
6598 kvm_pmu_handle_event(vcpu);
6599 if (kvm_check_request(KVM_REQ_PMI, vcpu))
6600 kvm_pmu_deliver_pmi(vcpu);
6601 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
6602 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
6603 if (test_bit(vcpu->arch.pending_ioapic_eoi,
6604 (void *) vcpu->arch.eoi_exit_bitmap)) {
6605 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
6606 vcpu->run->eoi.vector =
6607 vcpu->arch.pending_ioapic_eoi;
6612 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
6613 vcpu_scan_ioapic(vcpu);
6614 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
6615 kvm_vcpu_reload_apic_access_page(vcpu);
6616 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
6617 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6618 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
6622 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
6623 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6624 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
6631 * KVM_REQ_EVENT is not set when posted interrupts are set by
6632 * VT-d hardware, so we have to update RVI unconditionally.
6634 if (kvm_lapic_enabled(vcpu)) {
6636 * Update architecture specific hints for APIC
6637 * virtual interrupt delivery.
6639 if (kvm_x86_ops->hwapic_irr_update)
6640 kvm_x86_ops->hwapic_irr_update(vcpu,
6641 kvm_lapic_find_highest_irr(vcpu));
6644 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
6645 kvm_apic_accept_events(vcpu);
6646 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
6651 if (inject_pending_event(vcpu, req_int_win) != 0)
6652 req_immediate_exit = true;
6653 /* enable NMI/IRQ window open exits if needed */
6655 if (vcpu->arch.nmi_pending)
6656 kvm_x86_ops->enable_nmi_window(vcpu);
6657 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
6658 kvm_x86_ops->enable_irq_window(vcpu);
6661 if (kvm_lapic_enabled(vcpu)) {
6662 update_cr8_intercept(vcpu);
6663 kvm_lapic_sync_to_vapic(vcpu);
6667 r = kvm_mmu_reload(vcpu);
6669 goto cancel_injection;
6674 kvm_x86_ops->prepare_guest_switch(vcpu);
6675 if (vcpu->fpu_active)
6676 kvm_load_guest_fpu(vcpu);
6677 vcpu->mode = IN_GUEST_MODE;
6679 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6681 /* We should set ->mode before check ->requests,
6682 * see the comment in make_all_cpus_request.
6684 smp_mb__after_srcu_read_unlock();
6686 local_irq_disable();
6688 if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
6689 || need_resched() || signal_pending(current)) {
6690 vcpu->mode = OUTSIDE_GUEST_MODE;
6694 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6696 goto cancel_injection;
6699 kvm_load_guest_xcr0(vcpu);
6701 if (req_immediate_exit)
6702 smp_send_reschedule(vcpu->cpu);
6704 trace_kvm_entry(vcpu->vcpu_id);
6705 wait_lapic_expire(vcpu);
6706 __kvm_guest_enter();
6708 if (unlikely(vcpu->arch.switch_db_regs)) {
6710 set_debugreg(vcpu->arch.eff_db[0], 0);
6711 set_debugreg(vcpu->arch.eff_db[1], 1);
6712 set_debugreg(vcpu->arch.eff_db[2], 2);
6713 set_debugreg(vcpu->arch.eff_db[3], 3);
6714 set_debugreg(vcpu->arch.dr6, 6);
6715 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6718 kvm_x86_ops->run(vcpu);
6721 * Do this here before restoring debug registers on the host. And
6722 * since we do this before handling the vmexit, a DR access vmexit
6723 * can (a) read the correct value of the debug registers, (b) set
6724 * KVM_DEBUGREG_WONT_EXIT again.
6726 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
6727 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
6728 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
6729 kvm_update_dr0123(vcpu);
6730 kvm_update_dr6(vcpu);
6731 kvm_update_dr7(vcpu);
6732 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6736 * If the guest has used debug registers, at least dr7
6737 * will be disabled while returning to the host.
6738 * If we don't have active breakpoints in the host, we don't
6739 * care about the messed up debug address registers. But if
6740 * we have some of them active, restore the old state.
6742 if (hw_breakpoint_active())
6743 hw_breakpoint_restore();
6745 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
6747 vcpu->mode = OUTSIDE_GUEST_MODE;
6750 kvm_put_guest_xcr0(vcpu);
6752 /* Interrupt is enabled by handle_external_intr() */
6753 kvm_x86_ops->handle_external_intr(vcpu);
6758 * We must have an instruction between local_irq_enable() and
6759 * kvm_guest_exit(), so the timer interrupt isn't delayed by
6760 * the interrupt shadow. The stat.exits increment will do nicely.
6761 * But we need to prevent reordering, hence this barrier():
6769 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6772 * Profile KVM exit RIPs:
6774 if (unlikely(prof_on == KVM_PROFILING)) {
6775 unsigned long rip = kvm_rip_read(vcpu);
6776 profile_hit(KVM_PROFILING, (void *)rip);
6779 if (unlikely(vcpu->arch.tsc_always_catchup))
6780 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6782 if (vcpu->arch.apic_attention)
6783 kvm_lapic_sync_from_vapic(vcpu);
6785 r = kvm_x86_ops->handle_exit(vcpu);
6789 kvm_x86_ops->cancel_injection(vcpu);
6790 if (unlikely(vcpu->arch.apic_attention))
6791 kvm_lapic_sync_from_vapic(vcpu);
6796 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
6798 if (!kvm_arch_vcpu_runnable(vcpu) &&
6799 (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
6800 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6801 kvm_vcpu_block(vcpu);
6802 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6804 if (kvm_x86_ops->post_block)
6805 kvm_x86_ops->post_block(vcpu);
6807 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
6811 kvm_apic_accept_events(vcpu);
6812 switch(vcpu->arch.mp_state) {
6813 case KVM_MP_STATE_HALTED:
6814 vcpu->arch.pv.pv_unhalted = false;
6815 vcpu->arch.mp_state =
6816 KVM_MP_STATE_RUNNABLE;
6817 case KVM_MP_STATE_RUNNABLE:
6818 vcpu->arch.apf.halted = false;
6820 case KVM_MP_STATE_INIT_RECEIVED:
6829 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
6831 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6832 !vcpu->arch.apf.halted);
6835 static int vcpu_run(struct kvm_vcpu *vcpu)
6838 struct kvm *kvm = vcpu->kvm;
6840 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6843 if (kvm_vcpu_running(vcpu)) {
6844 r = vcpu_enter_guest(vcpu);
6846 r = vcpu_block(kvm, vcpu);
6852 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
6853 if (kvm_cpu_has_pending_timer(vcpu))
6854 kvm_inject_pending_timer_irqs(vcpu);
6856 if (dm_request_for_irq_injection(vcpu) &&
6857 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
6859 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
6860 ++vcpu->stat.request_irq_exits;
6864 kvm_check_async_pf_completion(vcpu);
6866 if (signal_pending(current)) {
6868 vcpu->run->exit_reason = KVM_EXIT_INTR;
6869 ++vcpu->stat.signal_exits;
6872 if (need_resched()) {
6873 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6875 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6879 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6884 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
6887 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6888 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
6889 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6890 if (r != EMULATE_DONE)
6895 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
6897 BUG_ON(!vcpu->arch.pio.count);
6899 return complete_emulated_io(vcpu);
6903 * Implements the following, as a state machine:
6907 * for each mmio piece in the fragment
6915 * for each mmio piece in the fragment
6920 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
6922 struct kvm_run *run = vcpu->run;
6923 struct kvm_mmio_fragment *frag;
6926 BUG_ON(!vcpu->mmio_needed);
6928 /* Complete previous fragment */
6929 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
6930 len = min(8u, frag->len);
6931 if (!vcpu->mmio_is_write)
6932 memcpy(frag->data, run->mmio.data, len);
6934 if (frag->len <= 8) {
6935 /* Switch to the next fragment. */
6937 vcpu->mmio_cur_fragment++;
6939 /* Go forward to the next mmio piece. */
6945 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
6946 vcpu->mmio_needed = 0;
6948 /* FIXME: return into emulator if single-stepping. */
6949 if (vcpu->mmio_is_write)
6951 vcpu->mmio_read_completed = 1;
6952 return complete_emulated_io(vcpu);
6955 run->exit_reason = KVM_EXIT_MMIO;
6956 run->mmio.phys_addr = frag->gpa;
6957 if (vcpu->mmio_is_write)
6958 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
6959 run->mmio.len = min(8u, frag->len);
6960 run->mmio.is_write = vcpu->mmio_is_write;
6961 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6966 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
6968 struct fpu *fpu = ¤t->thread.fpu;
6972 fpu__activate_curr(fpu);
6974 if (vcpu->sigset_active)
6975 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
6977 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
6978 kvm_vcpu_block(vcpu);
6979 kvm_apic_accept_events(vcpu);
6980 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
6985 /* re-sync apic's tpr */
6986 if (!lapic_in_kernel(vcpu)) {
6987 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
6993 if (unlikely(vcpu->arch.complete_userspace_io)) {
6994 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
6995 vcpu->arch.complete_userspace_io = NULL;
7000 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
7005 post_kvm_run_save(vcpu);
7006 if (vcpu->sigset_active)
7007 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
7012 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7014 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
7016 * We are here if userspace calls get_regs() in the middle of
7017 * instruction emulation. Registers state needs to be copied
7018 * back from emulation context to vcpu. Userspace shouldn't do
7019 * that usually, but some bad designed PV devices (vmware
7020 * backdoor interface) need this to work
7022 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
7023 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7025 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
7026 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
7027 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
7028 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
7029 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
7030 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
7031 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
7032 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
7033 #ifdef CONFIG_X86_64
7034 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
7035 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
7036 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
7037 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
7038 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
7039 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
7040 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
7041 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
7044 regs->rip = kvm_rip_read(vcpu);
7045 regs->rflags = kvm_get_rflags(vcpu);
7050 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7052 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
7053 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7055 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
7056 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
7057 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
7058 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
7059 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
7060 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
7061 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
7062 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
7063 #ifdef CONFIG_X86_64
7064 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
7065 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
7066 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
7067 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
7068 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
7069 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
7070 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
7071 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
7074 kvm_rip_write(vcpu, regs->rip);
7075 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
7077 vcpu->arch.exception.pending = false;
7079 kvm_make_request(KVM_REQ_EVENT, vcpu);
7084 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
7086 struct kvm_segment cs;
7088 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7092 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
7094 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
7095 struct kvm_sregs *sregs)
7099 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7100 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7101 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7102 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7103 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7104 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7106 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7107 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7109 kvm_x86_ops->get_idt(vcpu, &dt);
7110 sregs->idt.limit = dt.size;
7111 sregs->idt.base = dt.address;
7112 kvm_x86_ops->get_gdt(vcpu, &dt);
7113 sregs->gdt.limit = dt.size;
7114 sregs->gdt.base = dt.address;
7116 sregs->cr0 = kvm_read_cr0(vcpu);
7117 sregs->cr2 = vcpu->arch.cr2;
7118 sregs->cr3 = kvm_read_cr3(vcpu);
7119 sregs->cr4 = kvm_read_cr4(vcpu);
7120 sregs->cr8 = kvm_get_cr8(vcpu);
7121 sregs->efer = vcpu->arch.efer;
7122 sregs->apic_base = kvm_get_apic_base(vcpu);
7124 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
7126 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
7127 set_bit(vcpu->arch.interrupt.nr,
7128 (unsigned long *)sregs->interrupt_bitmap);
7133 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
7134 struct kvm_mp_state *mp_state)
7136 kvm_apic_accept_events(vcpu);
7137 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
7138 vcpu->arch.pv.pv_unhalted)
7139 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
7141 mp_state->mp_state = vcpu->arch.mp_state;
7146 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
7147 struct kvm_mp_state *mp_state)
7149 if (!kvm_vcpu_has_lapic(vcpu) &&
7150 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
7153 /* INITs are latched while in SMM */
7154 if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
7155 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
7156 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
7159 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
7160 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
7161 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
7163 vcpu->arch.mp_state = mp_state->mp_state;
7164 kvm_make_request(KVM_REQ_EVENT, vcpu);
7168 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
7169 int reason, bool has_error_code, u32 error_code)
7171 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
7174 init_emulate_ctxt(vcpu);
7176 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
7177 has_error_code, error_code);
7180 return EMULATE_FAIL;
7182 kvm_rip_write(vcpu, ctxt->eip);
7183 kvm_set_rflags(vcpu, ctxt->eflags);
7184 kvm_make_request(KVM_REQ_EVENT, vcpu);
7185 return EMULATE_DONE;
7187 EXPORT_SYMBOL_GPL(kvm_task_switch);
7189 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
7190 struct kvm_sregs *sregs)
7192 struct msr_data apic_base_msr;
7193 int mmu_reset_needed = 0;
7194 int pending_vec, max_bits, idx;
7197 if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
7200 dt.size = sregs->idt.limit;
7201 dt.address = sregs->idt.base;
7202 kvm_x86_ops->set_idt(vcpu, &dt);
7203 dt.size = sregs->gdt.limit;
7204 dt.address = sregs->gdt.base;
7205 kvm_x86_ops->set_gdt(vcpu, &dt);
7207 vcpu->arch.cr2 = sregs->cr2;
7208 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
7209 vcpu->arch.cr3 = sregs->cr3;
7210 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
7212 kvm_set_cr8(vcpu, sregs->cr8);
7214 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
7215 kvm_x86_ops->set_efer(vcpu, sregs->efer);
7216 apic_base_msr.data = sregs->apic_base;
7217 apic_base_msr.host_initiated = true;
7218 kvm_set_apic_base(vcpu, &apic_base_msr);
7220 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
7221 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
7222 vcpu->arch.cr0 = sregs->cr0;
7224 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
7225 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
7226 if (sregs->cr4 & X86_CR4_OSXSAVE)
7227 kvm_update_cpuid(vcpu);
7229 idx = srcu_read_lock(&vcpu->kvm->srcu);
7230 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu)) {
7231 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
7232 mmu_reset_needed = 1;
7234 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7236 if (mmu_reset_needed)
7237 kvm_mmu_reset_context(vcpu);
7239 max_bits = KVM_NR_INTERRUPTS;
7240 pending_vec = find_first_bit(
7241 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
7242 if (pending_vec < max_bits) {
7243 kvm_queue_interrupt(vcpu, pending_vec, false);
7244 pr_debug("Set back pending irq %d\n", pending_vec);
7247 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7248 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7249 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7250 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7251 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7252 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7254 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7255 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7257 update_cr8_intercept(vcpu);
7259 /* Older userspace won't unhalt the vcpu on reset. */
7260 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
7261 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
7263 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7265 kvm_make_request(KVM_REQ_EVENT, vcpu);
7270 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
7271 struct kvm_guest_debug *dbg)
7273 unsigned long rflags;
7276 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
7278 if (vcpu->arch.exception.pending)
7280 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
7281 kvm_queue_exception(vcpu, DB_VECTOR);
7283 kvm_queue_exception(vcpu, BP_VECTOR);
7287 * Read rflags as long as potentially injected trace flags are still
7290 rflags = kvm_get_rflags(vcpu);
7292 vcpu->guest_debug = dbg->control;
7293 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
7294 vcpu->guest_debug = 0;
7296 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7297 for (i = 0; i < KVM_NR_DB_REGS; ++i)
7298 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
7299 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
7301 for (i = 0; i < KVM_NR_DB_REGS; i++)
7302 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
7304 kvm_update_dr7(vcpu);
7306 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7307 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
7308 get_segment_base(vcpu, VCPU_SREG_CS);
7311 * Trigger an rflags update that will inject or remove the trace
7314 kvm_set_rflags(vcpu, rflags);
7316 kvm_x86_ops->update_bp_intercept(vcpu);
7326 * Translate a guest virtual address to a guest physical address.
7328 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
7329 struct kvm_translation *tr)
7331 unsigned long vaddr = tr->linear_address;
7335 idx = srcu_read_lock(&vcpu->kvm->srcu);
7336 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
7337 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7338 tr->physical_address = gpa;
7339 tr->valid = gpa != UNMAPPED_GVA;
7346 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7348 struct fxregs_state *fxsave =
7349 &vcpu->arch.guest_fpu.state.fxsave;
7351 memcpy(fpu->fpr, fxsave->st_space, 128);
7352 fpu->fcw = fxsave->cwd;
7353 fpu->fsw = fxsave->swd;
7354 fpu->ftwx = fxsave->twd;
7355 fpu->last_opcode = fxsave->fop;
7356 fpu->last_ip = fxsave->rip;
7357 fpu->last_dp = fxsave->rdp;
7358 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
7363 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7365 struct fxregs_state *fxsave =
7366 &vcpu->arch.guest_fpu.state.fxsave;
7368 memcpy(fxsave->st_space, fpu->fpr, 128);
7369 fxsave->cwd = fpu->fcw;
7370 fxsave->swd = fpu->fsw;
7371 fxsave->twd = fpu->ftwx;
7372 fxsave->fop = fpu->last_opcode;
7373 fxsave->rip = fpu->last_ip;
7374 fxsave->rdp = fpu->last_dp;
7375 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
7380 static void fx_init(struct kvm_vcpu *vcpu)
7382 fpstate_init(&vcpu->arch.guest_fpu.state);
7384 vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
7385 host_xcr0 | XSTATE_COMPACTION_ENABLED;
7388 * Ensure guest xcr0 is valid for loading
7390 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
7392 vcpu->arch.cr0 |= X86_CR0_ET;
7395 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
7397 if (vcpu->guest_fpu_loaded)
7401 * Restore all possible states in the guest,
7402 * and assume host would use all available bits.
7403 * Guest xcr0 would be loaded later.
7405 vcpu->guest_fpu_loaded = 1;
7406 __kernel_fpu_begin();
7407 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state);
7411 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
7413 if (!vcpu->guest_fpu_loaded) {
7414 vcpu->fpu_counter = 0;
7418 vcpu->guest_fpu_loaded = 0;
7419 copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
7421 ++vcpu->stat.fpu_reload;
7425 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
7427 void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
7429 kvmclock_reset(vcpu);
7431 kvm_x86_ops->vcpu_free(vcpu);
7432 free_cpumask_var(wbinvd_dirty_mask);
7435 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
7438 struct kvm_vcpu *vcpu;
7440 if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
7441 printk_once(KERN_WARNING
7442 "kvm: SMP vm created on host with unstable TSC; "
7443 "guest TSC will not be reliable\n");
7445 vcpu = kvm_x86_ops->vcpu_create(kvm, id);
7450 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
7454 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
7455 kvm_vcpu_mtrr_init(vcpu);
7456 r = vcpu_load(vcpu);
7459 kvm_vcpu_reset(vcpu, false);
7460 kvm_mmu_setup(vcpu);
7465 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
7467 struct msr_data msr;
7468 struct kvm *kvm = vcpu->kvm;
7470 if (vcpu_load(vcpu))
7473 msr.index = MSR_IA32_TSC;
7474 msr.host_initiated = true;
7475 kvm_write_tsc(vcpu, &msr);
7478 if (!kvmclock_periodic_sync)
7481 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
7482 KVMCLOCK_SYNC_PERIOD);
7485 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
7488 vcpu->arch.apf.msr_val = 0;
7490 r = vcpu_load(vcpu);
7492 kvm_mmu_unload(vcpu);
7495 kvm_x86_ops->vcpu_free(vcpu);
7498 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
7500 vcpu->arch.hflags = 0;
7502 atomic_set(&vcpu->arch.nmi_queued, 0);
7503 vcpu->arch.nmi_pending = 0;
7504 vcpu->arch.nmi_injected = false;
7505 kvm_clear_interrupt_queue(vcpu);
7506 kvm_clear_exception_queue(vcpu);
7508 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
7509 kvm_update_dr0123(vcpu);
7510 vcpu->arch.dr6 = DR6_INIT;
7511 kvm_update_dr6(vcpu);
7512 vcpu->arch.dr7 = DR7_FIXED_1;
7513 kvm_update_dr7(vcpu);
7517 kvm_make_request(KVM_REQ_EVENT, vcpu);
7518 vcpu->arch.apf.msr_val = 0;
7519 vcpu->arch.st.msr_val = 0;
7521 kvmclock_reset(vcpu);
7523 kvm_clear_async_pf_completion_queue(vcpu);
7524 kvm_async_pf_hash_reset(vcpu);
7525 vcpu->arch.apf.halted = false;
7528 kvm_pmu_reset(vcpu);
7529 vcpu->arch.smbase = 0x30000;
7532 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
7533 vcpu->arch.regs_avail = ~0;
7534 vcpu->arch.regs_dirty = ~0;
7536 kvm_x86_ops->vcpu_reset(vcpu, init_event);
7539 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
7541 struct kvm_segment cs;
7543 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7544 cs.selector = vector << 8;
7545 cs.base = vector << 12;
7546 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7547 kvm_rip_write(vcpu, 0);
7550 int kvm_arch_hardware_enable(void)
7553 struct kvm_vcpu *vcpu;
7558 bool stable, backwards_tsc = false;
7560 kvm_shared_msr_cpu_online();
7561 ret = kvm_x86_ops->hardware_enable();
7565 local_tsc = rdtsc();
7566 stable = !check_tsc_unstable();
7567 list_for_each_entry(kvm, &vm_list, vm_list) {
7568 kvm_for_each_vcpu(i, vcpu, kvm) {
7569 if (!stable && vcpu->cpu == smp_processor_id())
7570 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7571 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
7572 backwards_tsc = true;
7573 if (vcpu->arch.last_host_tsc > max_tsc)
7574 max_tsc = vcpu->arch.last_host_tsc;
7580 * Sometimes, even reliable TSCs go backwards. This happens on
7581 * platforms that reset TSC during suspend or hibernate actions, but
7582 * maintain synchronization. We must compensate. Fortunately, we can
7583 * detect that condition here, which happens early in CPU bringup,
7584 * before any KVM threads can be running. Unfortunately, we can't
7585 * bring the TSCs fully up to date with real time, as we aren't yet far
7586 * enough into CPU bringup that we know how much real time has actually
7587 * elapsed; our helper function, get_kernel_ns() will be using boot
7588 * variables that haven't been updated yet.
7590 * So we simply find the maximum observed TSC above, then record the
7591 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
7592 * the adjustment will be applied. Note that we accumulate
7593 * adjustments, in case multiple suspend cycles happen before some VCPU
7594 * gets a chance to run again. In the event that no KVM threads get a
7595 * chance to run, we will miss the entire elapsed period, as we'll have
7596 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
7597 * loose cycle time. This isn't too big a deal, since the loss will be
7598 * uniform across all VCPUs (not to mention the scenario is extremely
7599 * unlikely). It is possible that a second hibernate recovery happens
7600 * much faster than a first, causing the observed TSC here to be
7601 * smaller; this would require additional padding adjustment, which is
7602 * why we set last_host_tsc to the local tsc observed here.
7604 * N.B. - this code below runs only on platforms with reliable TSC,
7605 * as that is the only way backwards_tsc is set above. Also note
7606 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
7607 * have the same delta_cyc adjustment applied if backwards_tsc
7608 * is detected. Note further, this adjustment is only done once,
7609 * as we reset last_host_tsc on all VCPUs to stop this from being
7610 * called multiple times (one for each physical CPU bringup).
7612 * Platforms with unreliable TSCs don't have to deal with this, they
7613 * will be compensated by the logic in vcpu_load, which sets the TSC to
7614 * catchup mode. This will catchup all VCPUs to real time, but cannot
7615 * guarantee that they stay in perfect synchronization.
7617 if (backwards_tsc) {
7618 u64 delta_cyc = max_tsc - local_tsc;
7619 backwards_tsc_observed = true;
7620 list_for_each_entry(kvm, &vm_list, vm_list) {
7621 kvm_for_each_vcpu(i, vcpu, kvm) {
7622 vcpu->arch.tsc_offset_adjustment += delta_cyc;
7623 vcpu->arch.last_host_tsc = local_tsc;
7624 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7628 * We have to disable TSC offset matching.. if you were
7629 * booting a VM while issuing an S4 host suspend....
7630 * you may have some problem. Solving this issue is
7631 * left as an exercise to the reader.
7633 kvm->arch.last_tsc_nsec = 0;
7634 kvm->arch.last_tsc_write = 0;
7641 void kvm_arch_hardware_disable(void)
7643 kvm_x86_ops->hardware_disable();
7644 drop_user_return_notifiers();
7647 int kvm_arch_hardware_setup(void)
7651 r = kvm_x86_ops->hardware_setup();
7655 if (kvm_has_tsc_control) {
7657 * Make sure the user can only configure tsc_khz values that
7658 * fit into a signed integer.
7659 * A min value is not calculated needed because it will always
7660 * be 1 on all machines.
7662 u64 max = min(0x7fffffffULL,
7663 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
7664 kvm_max_guest_tsc_khz = max;
7666 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
7669 kvm_init_msr_list();
7673 void kvm_arch_hardware_unsetup(void)
7675 kvm_x86_ops->hardware_unsetup();
7678 void kvm_arch_check_processor_compat(void *rtn)
7680 kvm_x86_ops->check_processor_compatibility(rtn);
7683 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
7685 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
7687 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
7689 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
7691 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
7694 bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
7696 return irqchip_in_kernel(vcpu->kvm) == lapic_in_kernel(vcpu);
7699 struct static_key kvm_no_apic_vcpu __read_mostly;
7701 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
7707 BUG_ON(vcpu->kvm == NULL);
7710 vcpu->arch.pv.pv_unhalted = false;
7711 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
7712 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_reset_bsp(vcpu))
7713 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7715 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
7717 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
7722 vcpu->arch.pio_data = page_address(page);
7724 kvm_set_tsc_khz(vcpu, max_tsc_khz);
7726 r = kvm_mmu_create(vcpu);
7728 goto fail_free_pio_data;
7730 if (irqchip_in_kernel(kvm)) {
7731 r = kvm_create_lapic(vcpu);
7733 goto fail_mmu_destroy;
7735 static_key_slow_inc(&kvm_no_apic_vcpu);
7737 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
7739 if (!vcpu->arch.mce_banks) {
7741 goto fail_free_lapic;
7743 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
7745 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
7747 goto fail_free_mce_banks;
7752 vcpu->arch.ia32_tsc_adjust_msr = 0x0;
7753 vcpu->arch.pv_time_enabled = false;
7755 vcpu->arch.guest_supported_xcr0 = 0;
7756 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
7758 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
7760 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
7762 kvm_async_pf_hash_reset(vcpu);
7765 vcpu->arch.pending_external_vector = -1;
7769 fail_free_mce_banks:
7770 kfree(vcpu->arch.mce_banks);
7772 kvm_free_lapic(vcpu);
7774 kvm_mmu_destroy(vcpu);
7776 free_page((unsigned long)vcpu->arch.pio_data);
7781 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
7785 kvm_pmu_destroy(vcpu);
7786 kfree(vcpu->arch.mce_banks);
7787 kvm_free_lapic(vcpu);
7788 idx = srcu_read_lock(&vcpu->kvm->srcu);
7789 kvm_mmu_destroy(vcpu);
7790 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7791 free_page((unsigned long)vcpu->arch.pio_data);
7792 if (!lapic_in_kernel(vcpu))
7793 static_key_slow_dec(&kvm_no_apic_vcpu);
7796 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
7798 kvm_x86_ops->sched_in(vcpu, cpu);
7801 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
7806 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
7807 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
7808 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
7809 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
7810 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
7812 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
7813 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
7814 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
7815 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
7816 &kvm->arch.irq_sources_bitmap);
7818 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
7819 mutex_init(&kvm->arch.apic_map_lock);
7820 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
7822 pvclock_update_vm_gtod_copy(kvm);
7824 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
7825 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
7830 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
7833 r = vcpu_load(vcpu);
7835 kvm_mmu_unload(vcpu);
7839 static void kvm_free_vcpus(struct kvm *kvm)
7842 struct kvm_vcpu *vcpu;
7845 * Unpin any mmu pages first.
7847 kvm_for_each_vcpu(i, vcpu, kvm) {
7848 kvm_clear_async_pf_completion_queue(vcpu);
7849 kvm_unload_vcpu_mmu(vcpu);
7851 kvm_for_each_vcpu(i, vcpu, kvm)
7852 kvm_arch_vcpu_free(vcpu);
7854 mutex_lock(&kvm->lock);
7855 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
7856 kvm->vcpus[i] = NULL;
7858 atomic_set(&kvm->online_vcpus, 0);
7859 mutex_unlock(&kvm->lock);
7862 void kvm_arch_sync_events(struct kvm *kvm)
7864 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
7865 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
7866 kvm_free_all_assigned_devices(kvm);
7870 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7874 struct kvm_memslots *slots = kvm_memslots(kvm);
7875 struct kvm_memory_slot *slot, old;
7877 /* Called with kvm->slots_lock held. */
7878 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
7881 slot = id_to_memslot(slots, id);
7887 * MAP_SHARED to prevent internal slot pages from being moved
7890 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
7891 MAP_SHARED | MAP_ANONYMOUS, 0);
7892 if (IS_ERR((void *)hva))
7893 return PTR_ERR((void *)hva);
7902 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
7903 struct kvm_userspace_memory_region m;
7905 m.slot = id | (i << 16);
7907 m.guest_phys_addr = gpa;
7908 m.userspace_addr = hva;
7909 m.memory_size = size;
7910 r = __kvm_set_memory_region(kvm, &m);
7916 r = vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
7922 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
7924 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7928 mutex_lock(&kvm->slots_lock);
7929 r = __x86_set_memory_region(kvm, id, gpa, size);
7930 mutex_unlock(&kvm->slots_lock);
7934 EXPORT_SYMBOL_GPL(x86_set_memory_region);
7936 void kvm_arch_destroy_vm(struct kvm *kvm)
7938 if (current->mm == kvm->mm) {
7940 * Free memory regions allocated on behalf of userspace,
7941 * unless the the memory map has changed due to process exit
7944 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
7945 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
7946 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
7948 kvm_iommu_unmap_guest(kvm);
7949 kfree(kvm->arch.vpic);
7950 kfree(kvm->arch.vioapic);
7951 kvm_free_vcpus(kvm);
7952 kfree(rcu_dereference_check(kvm->arch.apic_map, 1));
7955 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
7956 struct kvm_memory_slot *dont)
7960 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7961 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
7962 kvfree(free->arch.rmap[i]);
7963 free->arch.rmap[i] = NULL;
7968 if (!dont || free->arch.lpage_info[i - 1] !=
7969 dont->arch.lpage_info[i - 1]) {
7970 kvfree(free->arch.lpage_info[i - 1]);
7971 free->arch.lpage_info[i - 1] = NULL;
7976 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
7977 unsigned long npages)
7981 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7986 lpages = gfn_to_index(slot->base_gfn + npages - 1,
7987 slot->base_gfn, level) + 1;
7989 slot->arch.rmap[i] =
7990 kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
7991 if (!slot->arch.rmap[i])
7996 slot->arch.lpage_info[i - 1] = kvm_kvzalloc(lpages *
7997 sizeof(*slot->arch.lpage_info[i - 1]));
7998 if (!slot->arch.lpage_info[i - 1])
8001 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
8002 slot->arch.lpage_info[i - 1][0].write_count = 1;
8003 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
8004 slot->arch.lpage_info[i - 1][lpages - 1].write_count = 1;
8005 ugfn = slot->userspace_addr >> PAGE_SHIFT;
8007 * If the gfn and userspace address are not aligned wrt each
8008 * other, or if explicitly asked to, disable large page
8009 * support for this slot
8011 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
8012 !kvm_largepages_enabled()) {
8015 for (j = 0; j < lpages; ++j)
8016 slot->arch.lpage_info[i - 1][j].write_count = 1;
8023 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8024 kvfree(slot->arch.rmap[i]);
8025 slot->arch.rmap[i] = NULL;
8029 kvfree(slot->arch.lpage_info[i - 1]);
8030 slot->arch.lpage_info[i - 1] = NULL;
8035 void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
8038 * memslots->generation has been incremented.
8039 * mmio generation may have reached its maximum value.
8041 kvm_mmu_invalidate_mmio_sptes(kvm, slots);
8044 int kvm_arch_prepare_memory_region(struct kvm *kvm,
8045 struct kvm_memory_slot *memslot,
8046 const struct kvm_userspace_memory_region *mem,
8047 enum kvm_mr_change change)
8052 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
8053 struct kvm_memory_slot *new)
8055 /* Still write protect RO slot */
8056 if (new->flags & KVM_MEM_READONLY) {
8057 kvm_mmu_slot_remove_write_access(kvm, new);
8062 * Call kvm_x86_ops dirty logging hooks when they are valid.
8064 * kvm_x86_ops->slot_disable_log_dirty is called when:
8066 * - KVM_MR_CREATE with dirty logging is disabled
8067 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
8069 * The reason is, in case of PML, we need to set D-bit for any slots
8070 * with dirty logging disabled in order to eliminate unnecessary GPA
8071 * logging in PML buffer (and potential PML buffer full VMEXT). This
8072 * guarantees leaving PML enabled during guest's lifetime won't have
8073 * any additonal overhead from PML when guest is running with dirty
8074 * logging disabled for memory slots.
8076 * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
8077 * to dirty logging mode.
8079 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
8081 * In case of write protect:
8083 * Write protect all pages for dirty logging.
8085 * All the sptes including the large sptes which point to this
8086 * slot are set to readonly. We can not create any new large
8087 * spte on this slot until the end of the logging.
8089 * See the comments in fast_page_fault().
8091 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
8092 if (kvm_x86_ops->slot_enable_log_dirty)
8093 kvm_x86_ops->slot_enable_log_dirty(kvm, new);
8095 kvm_mmu_slot_remove_write_access(kvm, new);
8097 if (kvm_x86_ops->slot_disable_log_dirty)
8098 kvm_x86_ops->slot_disable_log_dirty(kvm, new);
8102 void kvm_arch_commit_memory_region(struct kvm *kvm,
8103 const struct kvm_userspace_memory_region *mem,
8104 const struct kvm_memory_slot *old,
8105 const struct kvm_memory_slot *new,
8106 enum kvm_mr_change change)
8108 int nr_mmu_pages = 0;
8110 if (!kvm->arch.n_requested_mmu_pages)
8111 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
8114 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
8117 * Dirty logging tracks sptes in 4k granularity, meaning that large
8118 * sptes have to be split. If live migration is successful, the guest
8119 * in the source machine will be destroyed and large sptes will be
8120 * created in the destination. However, if the guest continues to run
8121 * in the source machine (for example if live migration fails), small
8122 * sptes will remain around and cause bad performance.
8124 * Scan sptes if dirty logging has been stopped, dropping those
8125 * which can be collapsed into a single large-page spte. Later
8126 * page faults will create the large-page sptes.
8128 if ((change != KVM_MR_DELETE) &&
8129 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
8130 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
8131 kvm_mmu_zap_collapsible_sptes(kvm, new);
8134 * Set up write protection and/or dirty logging for the new slot.
8136 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
8137 * been zapped so no dirty logging staff is needed for old slot. For
8138 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
8139 * new and it's also covered when dealing with the new slot.
8141 * FIXME: const-ify all uses of struct kvm_memory_slot.
8143 if (change != KVM_MR_DELETE)
8144 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
8147 void kvm_arch_flush_shadow_all(struct kvm *kvm)
8149 kvm_mmu_invalidate_zap_all_pages(kvm);
8152 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
8153 struct kvm_memory_slot *slot)
8155 kvm_mmu_invalidate_zap_all_pages(kvm);
8158 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
8160 if (!list_empty_careful(&vcpu->async_pf.done))
8163 if (kvm_apic_has_events(vcpu))
8166 if (vcpu->arch.pv.pv_unhalted)
8169 if (atomic_read(&vcpu->arch.nmi_queued))
8172 if (test_bit(KVM_REQ_SMI, &vcpu->requests))
8175 if (kvm_arch_interrupt_allowed(vcpu) &&
8176 kvm_cpu_has_interrupt(vcpu))
8182 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
8184 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
8185 kvm_x86_ops->check_nested_events(vcpu, false);
8187 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
8190 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
8192 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
8195 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
8197 return kvm_x86_ops->interrupt_allowed(vcpu);
8200 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
8202 if (is_64_bit_mode(vcpu))
8203 return kvm_rip_read(vcpu);
8204 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
8205 kvm_rip_read(vcpu));
8207 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
8209 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
8211 return kvm_get_linear_rip(vcpu) == linear_rip;
8213 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
8215 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
8217 unsigned long rflags;
8219 rflags = kvm_x86_ops->get_rflags(vcpu);
8220 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8221 rflags &= ~X86_EFLAGS_TF;
8224 EXPORT_SYMBOL_GPL(kvm_get_rflags);
8226 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8228 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
8229 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
8230 rflags |= X86_EFLAGS_TF;
8231 kvm_x86_ops->set_rflags(vcpu, rflags);
8234 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8236 __kvm_set_rflags(vcpu, rflags);
8237 kvm_make_request(KVM_REQ_EVENT, vcpu);
8239 EXPORT_SYMBOL_GPL(kvm_set_rflags);
8241 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
8245 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
8249 r = kvm_mmu_reload(vcpu);
8253 if (!vcpu->arch.mmu.direct_map &&
8254 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
8257 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
8260 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
8262 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
8265 static inline u32 kvm_async_pf_next_probe(u32 key)
8267 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
8270 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8272 u32 key = kvm_async_pf_hash_fn(gfn);
8274 while (vcpu->arch.apf.gfns[key] != ~0)
8275 key = kvm_async_pf_next_probe(key);
8277 vcpu->arch.apf.gfns[key] = gfn;
8280 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
8283 u32 key = kvm_async_pf_hash_fn(gfn);
8285 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
8286 (vcpu->arch.apf.gfns[key] != gfn &&
8287 vcpu->arch.apf.gfns[key] != ~0); i++)
8288 key = kvm_async_pf_next_probe(key);
8293 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8295 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
8298 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8302 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
8304 vcpu->arch.apf.gfns[i] = ~0;
8306 j = kvm_async_pf_next_probe(j);
8307 if (vcpu->arch.apf.gfns[j] == ~0)
8309 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
8311 * k lies cyclically in ]i,j]
8313 * |....j i.k.| or |.k..j i...|
8315 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
8316 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
8321 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
8324 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
8328 static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
8331 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
8335 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
8336 struct kvm_async_pf *work)
8338 struct x86_exception fault;
8340 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
8341 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
8343 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
8344 (vcpu->arch.apf.send_user_only &&
8345 kvm_x86_ops->get_cpl(vcpu) == 0))
8346 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
8347 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
8348 fault.vector = PF_VECTOR;
8349 fault.error_code_valid = true;
8350 fault.error_code = 0;
8351 fault.nested_page_fault = false;
8352 fault.address = work->arch.token;
8353 kvm_inject_page_fault(vcpu, &fault);
8357 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
8358 struct kvm_async_pf *work)
8360 struct x86_exception fault;
8363 if (work->wakeup_all)
8364 work->arch.token = ~0; /* broadcast wakeup */
8366 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
8367 trace_kvm_async_pf_ready(work->arch.token, work->gva);
8369 if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
8370 !apf_get_user(vcpu, &val)) {
8371 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
8372 vcpu->arch.exception.pending &&
8373 vcpu->arch.exception.nr == PF_VECTOR &&
8374 !apf_put_user(vcpu, 0)) {
8375 vcpu->arch.exception.pending = false;
8376 vcpu->arch.exception.nr = 0;
8377 vcpu->arch.exception.has_error_code = false;
8378 vcpu->arch.exception.error_code = 0;
8379 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
8380 fault.vector = PF_VECTOR;
8381 fault.error_code_valid = true;
8382 fault.error_code = 0;
8383 fault.nested_page_fault = false;
8384 fault.address = work->arch.token;
8385 kvm_inject_page_fault(vcpu, &fault);
8388 vcpu->arch.apf.halted = false;
8389 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8392 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
8394 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
8397 return kvm_can_do_async_pf(vcpu);
8400 void kvm_arch_start_assignment(struct kvm *kvm)
8402 atomic_inc(&kvm->arch.assigned_device_count);
8404 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
8406 void kvm_arch_end_assignment(struct kvm *kvm)
8408 atomic_dec(&kvm->arch.assigned_device_count);
8410 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
8412 bool kvm_arch_has_assigned_device(struct kvm *kvm)
8414 return atomic_read(&kvm->arch.assigned_device_count);
8416 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
8418 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
8420 atomic_inc(&kvm->arch.noncoherent_dma_count);
8422 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
8424 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
8426 atomic_dec(&kvm->arch.noncoherent_dma_count);
8428 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
8430 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
8432 return atomic_read(&kvm->arch.noncoherent_dma_count);
8434 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
8436 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
8437 struct irq_bypass_producer *prod)
8439 struct kvm_kernel_irqfd *irqfd =
8440 container_of(cons, struct kvm_kernel_irqfd, consumer);
8442 if (kvm_x86_ops->update_pi_irte) {
8443 irqfd->producer = prod;
8444 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
8445 prod->irq, irqfd->gsi, 1);
8451 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
8452 struct irq_bypass_producer *prod)
8455 struct kvm_kernel_irqfd *irqfd =
8456 container_of(cons, struct kvm_kernel_irqfd, consumer);
8458 if (!kvm_x86_ops->update_pi_irte) {
8459 WARN_ON(irqfd->producer != NULL);
8463 WARN_ON(irqfd->producer != prod);
8464 irqfd->producer = NULL;
8467 * When producer of consumer is unregistered, we change back to
8468 * remapped mode, so we can re-use the current implementation
8469 * when the irq is masked/disabed or the consumer side (KVM
8470 * int this case doesn't want to receive the interrupts.
8472 ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
8474 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
8475 " fails: %d\n", irqfd->consumer.token, ret);
8478 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
8479 uint32_t guest_irq, bool set)
8481 if (!kvm_x86_ops->update_pi_irte)
8484 return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
8487 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
8488 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
8489 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
8490 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
8491 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
8492 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
8493 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
8494 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
8495 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
8496 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
8497 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
8498 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
8499 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
8500 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
8501 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
8502 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
8503 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);