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 = array_index_nospec(
1998 msr - MSR_IA32_MC0_CTL,
1999 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2001 /* only 0 or all 1s can be written to IA32_MCi_CTL
2002 * some Linux kernels though clear bit 10 in bank 4 to
2003 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2004 * this to avoid an uncatched #GP in the guest
2006 if ((offset & 0x3) == 0 &&
2007 data != 0 && (data | (1 << 10)) != ~(u64)0)
2009 vcpu->arch.mce_banks[offset] = data;
2017 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2019 struct kvm *kvm = vcpu->kvm;
2020 int lm = is_long_mode(vcpu);
2021 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2022 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2023 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2024 : kvm->arch.xen_hvm_config.blob_size_32;
2025 u32 page_num = data & ~PAGE_MASK;
2026 u64 page_addr = data & PAGE_MASK;
2031 if (page_num >= blob_size)
2034 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2039 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2048 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2050 gpa_t gpa = data & ~0x3f;
2052 /* Bits 2:5 are reserved, Should be zero */
2056 vcpu->arch.apf.msr_val = data;
2058 if (!(data & KVM_ASYNC_PF_ENABLED)) {
2059 kvm_clear_async_pf_completion_queue(vcpu);
2060 kvm_async_pf_hash_reset(vcpu);
2064 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2068 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2069 kvm_async_pf_wakeup_all(vcpu);
2073 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2075 vcpu->arch.pv_time_enabled = false;
2078 static void accumulate_steal_time(struct kvm_vcpu *vcpu)
2082 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2085 delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
2086 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2087 vcpu->arch.st.accum_steal = delta;
2090 static void record_steal_time(struct kvm_vcpu *vcpu)
2092 accumulate_steal_time(vcpu);
2094 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2097 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2098 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
2101 vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
2102 vcpu->arch.st.steal.version += 2;
2103 vcpu->arch.st.accum_steal = 0;
2105 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2106 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2109 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2112 u32 msr = msr_info->index;
2113 u64 data = msr_info->data;
2116 case MSR_AMD64_NB_CFG:
2117 case MSR_IA32_UCODE_REV:
2118 case MSR_IA32_UCODE_WRITE:
2119 case MSR_VM_HSAVE_PA:
2120 case MSR_AMD64_PATCH_LOADER:
2121 case MSR_AMD64_BU_CFG2:
2124 case MSR_IA32_ARCH_CAPABILITIES:
2125 if (!msr_info->host_initiated)
2127 vcpu->arch.arch_capabilities = data;
2130 return set_efer(vcpu, msr_info);
2132 data &= ~(u64)0x40; /* ignore flush filter disable */
2133 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2134 data &= ~(u64)0x8; /* ignore TLB cache disable */
2135 data &= ~(u64)0x40000; /* ignore Mc status write enable */
2137 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2142 case MSR_FAM10H_MMIO_CONF_BASE:
2144 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2149 case MSR_IA32_DEBUGCTLMSR:
2151 /* We support the non-activated case already */
2153 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2154 /* Values other than LBR and BTF are vendor-specific,
2155 thus reserved and should throw a #GP */
2158 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2161 case 0x200 ... 0x2ff:
2162 return kvm_mtrr_set_msr(vcpu, msr, data);
2163 case MSR_IA32_APICBASE:
2164 return kvm_set_apic_base(vcpu, msr_info);
2165 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
2166 return kvm_x2apic_msr_write(vcpu, msr, data);
2167 case MSR_IA32_TSCDEADLINE:
2168 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2170 case MSR_IA32_TSC_ADJUST:
2171 if (guest_cpuid_has_tsc_adjust(vcpu)) {
2172 if (!msr_info->host_initiated) {
2173 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2174 adjust_tsc_offset_guest(vcpu, adj);
2175 /* Before back to guest, tsc_timestamp must be adjusted
2176 * as well, otherwise guest's percpu pvclock time could jump.
2178 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2180 vcpu->arch.ia32_tsc_adjust_msr = data;
2183 case MSR_IA32_MISC_ENABLE:
2184 vcpu->arch.ia32_misc_enable_msr = data;
2186 case MSR_IA32_SMBASE:
2187 if (!msr_info->host_initiated)
2189 vcpu->arch.smbase = data;
2191 case MSR_KVM_WALL_CLOCK_NEW:
2192 case MSR_KVM_WALL_CLOCK:
2193 vcpu->kvm->arch.wall_clock = data;
2194 kvm_write_wall_clock(vcpu->kvm, data);
2196 case MSR_KVM_SYSTEM_TIME_NEW:
2197 case MSR_KVM_SYSTEM_TIME: {
2199 struct kvm_arch *ka = &vcpu->kvm->arch;
2201 kvmclock_reset(vcpu);
2203 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2204 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2206 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2207 set_bit(KVM_REQ_MASTERCLOCK_UPDATE,
2210 ka->boot_vcpu_runs_old_kvmclock = tmp;
2213 vcpu->arch.time = data;
2214 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2216 /* we verify if the enable bit is set... */
2220 gpa_offset = data & ~(PAGE_MASK | 1);
2222 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2223 &vcpu->arch.pv_time, data & ~1ULL,
2224 sizeof(struct pvclock_vcpu_time_info)))
2225 vcpu->arch.pv_time_enabled = false;
2227 vcpu->arch.pv_time_enabled = true;
2231 case MSR_KVM_ASYNC_PF_EN:
2232 if (kvm_pv_enable_async_pf(vcpu, data))
2235 case MSR_KVM_STEAL_TIME:
2237 if (unlikely(!sched_info_on()))
2240 if (data & KVM_STEAL_RESERVED_MASK)
2243 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2244 data & KVM_STEAL_VALID_BITS,
2245 sizeof(struct kvm_steal_time)))
2248 vcpu->arch.st.msr_val = data;
2250 if (!(data & KVM_MSR_ENABLED))
2253 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2256 case MSR_KVM_PV_EOI_EN:
2257 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2261 case MSR_IA32_MCG_CTL:
2262 case MSR_IA32_MCG_STATUS:
2263 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2264 return set_msr_mce(vcpu, msr, data);
2266 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2267 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2268 pr = true; /* fall through */
2269 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2270 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2271 if (kvm_pmu_is_valid_msr(vcpu, msr))
2272 return kvm_pmu_set_msr(vcpu, msr_info);
2274 if (pr || data != 0)
2275 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2276 "0x%x data 0x%llx\n", msr, data);
2278 case MSR_K7_CLK_CTL:
2280 * Ignore all writes to this no longer documented MSR.
2281 * Writes are only relevant for old K7 processors,
2282 * all pre-dating SVM, but a recommended workaround from
2283 * AMD for these chips. It is possible to specify the
2284 * affected processor models on the command line, hence
2285 * the need to ignore the workaround.
2288 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2289 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2290 case HV_X64_MSR_CRASH_CTL:
2291 return kvm_hv_set_msr_common(vcpu, msr, data,
2292 msr_info->host_initiated);
2293 case MSR_IA32_BBL_CR_CTL3:
2294 /* Drop writes to this legacy MSR -- see rdmsr
2295 * counterpart for further detail.
2297 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
2299 case MSR_AMD64_OSVW_ID_LENGTH:
2300 if (!guest_cpuid_has_osvw(vcpu))
2302 vcpu->arch.osvw.length = data;
2304 case MSR_AMD64_OSVW_STATUS:
2305 if (!guest_cpuid_has_osvw(vcpu))
2307 vcpu->arch.osvw.status = data;
2310 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2311 return xen_hvm_config(vcpu, data);
2312 if (kvm_pmu_is_valid_msr(vcpu, msr))
2313 return kvm_pmu_set_msr(vcpu, msr_info);
2315 vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
2319 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
2326 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2330 * Reads an msr value (of 'msr_index') into 'pdata'.
2331 * Returns 0 on success, non-0 otherwise.
2332 * Assumes vcpu_load() was already called.
2334 int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2336 return kvm_x86_ops->get_msr(vcpu, msr);
2338 EXPORT_SYMBOL_GPL(kvm_get_msr);
2340 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2343 u64 mcg_cap = vcpu->arch.mcg_cap;
2344 unsigned bank_num = mcg_cap & 0xff;
2347 case MSR_IA32_P5_MC_ADDR:
2348 case MSR_IA32_P5_MC_TYPE:
2351 case MSR_IA32_MCG_CAP:
2352 data = vcpu->arch.mcg_cap;
2354 case MSR_IA32_MCG_CTL:
2355 if (!(mcg_cap & MCG_CTL_P))
2357 data = vcpu->arch.mcg_ctl;
2359 case MSR_IA32_MCG_STATUS:
2360 data = vcpu->arch.mcg_status;
2363 if (msr >= MSR_IA32_MC0_CTL &&
2364 msr < MSR_IA32_MCx_CTL(bank_num)) {
2365 u32 offset = array_index_nospec(
2366 msr - MSR_IA32_MC0_CTL,
2367 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2369 data = vcpu->arch.mce_banks[offset];
2378 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2380 switch (msr_info->index) {
2381 case MSR_IA32_PLATFORM_ID:
2382 case MSR_IA32_EBL_CR_POWERON:
2383 case MSR_IA32_DEBUGCTLMSR:
2384 case MSR_IA32_LASTBRANCHFROMIP:
2385 case MSR_IA32_LASTBRANCHTOIP:
2386 case MSR_IA32_LASTINTFROMIP:
2387 case MSR_IA32_LASTINTTOIP:
2389 case MSR_K8_TSEG_ADDR:
2390 case MSR_K8_TSEG_MASK:
2392 case MSR_VM_HSAVE_PA:
2393 case MSR_K8_INT_PENDING_MSG:
2394 case MSR_AMD64_NB_CFG:
2395 case MSR_FAM10H_MMIO_CONF_BASE:
2396 case MSR_AMD64_BU_CFG2:
2399 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2400 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2401 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2402 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2403 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2404 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2407 case MSR_IA32_UCODE_REV:
2408 msr_info->data = 0x100000000ULL;
2410 case MSR_IA32_ARCH_CAPABILITIES:
2411 if (!msr_info->host_initiated &&
2412 !guest_cpuid_has_arch_capabilities(vcpu))
2414 msr_info->data = vcpu->arch.arch_capabilities;
2417 case 0x200 ... 0x2ff:
2418 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2419 case 0xcd: /* fsb frequency */
2423 * MSR_EBC_FREQUENCY_ID
2424 * Conservative value valid for even the basic CPU models.
2425 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2426 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2427 * and 266MHz for model 3, or 4. Set Core Clock
2428 * Frequency to System Bus Frequency Ratio to 1 (bits
2429 * 31:24) even though these are only valid for CPU
2430 * models > 2, however guests may end up dividing or
2431 * multiplying by zero otherwise.
2433 case MSR_EBC_FREQUENCY_ID:
2434 msr_info->data = 1 << 24;
2436 case MSR_IA32_APICBASE:
2437 msr_info->data = kvm_get_apic_base(vcpu);
2439 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
2440 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2442 case MSR_IA32_TSCDEADLINE:
2443 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2445 case MSR_IA32_TSC_ADJUST:
2446 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2448 case MSR_IA32_MISC_ENABLE:
2449 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
2451 case MSR_IA32_SMBASE:
2452 if (!msr_info->host_initiated)
2454 msr_info->data = vcpu->arch.smbase;
2456 case MSR_IA32_PERF_STATUS:
2457 /* TSC increment by tick */
2458 msr_info->data = 1000ULL;
2459 /* CPU multiplier */
2460 msr_info->data |= (((uint64_t)4ULL) << 40);
2463 msr_info->data = vcpu->arch.efer;
2465 case MSR_KVM_WALL_CLOCK:
2466 case MSR_KVM_WALL_CLOCK_NEW:
2467 msr_info->data = vcpu->kvm->arch.wall_clock;
2469 case MSR_KVM_SYSTEM_TIME:
2470 case MSR_KVM_SYSTEM_TIME_NEW:
2471 msr_info->data = vcpu->arch.time;
2473 case MSR_KVM_ASYNC_PF_EN:
2474 msr_info->data = vcpu->arch.apf.msr_val;
2476 case MSR_KVM_STEAL_TIME:
2477 msr_info->data = vcpu->arch.st.msr_val;
2479 case MSR_KVM_PV_EOI_EN:
2480 msr_info->data = vcpu->arch.pv_eoi.msr_val;
2482 case MSR_IA32_P5_MC_ADDR:
2483 case MSR_IA32_P5_MC_TYPE:
2484 case MSR_IA32_MCG_CAP:
2485 case MSR_IA32_MCG_CTL:
2486 case MSR_IA32_MCG_STATUS:
2487 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2488 return get_msr_mce(vcpu, msr_info->index, &msr_info->data);
2489 case MSR_K7_CLK_CTL:
2491 * Provide expected ramp-up count for K7. All other
2492 * are set to zero, indicating minimum divisors for
2495 * This prevents guest kernels on AMD host with CPU
2496 * type 6, model 8 and higher from exploding due to
2497 * the rdmsr failing.
2499 msr_info->data = 0x20000000;
2501 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2502 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2503 case HV_X64_MSR_CRASH_CTL:
2504 return kvm_hv_get_msr_common(vcpu,
2505 msr_info->index, &msr_info->data);
2507 case MSR_IA32_BBL_CR_CTL3:
2508 /* This legacy MSR exists but isn't fully documented in current
2509 * silicon. It is however accessed by winxp in very narrow
2510 * scenarios where it sets bit #19, itself documented as
2511 * a "reserved" bit. Best effort attempt to source coherent
2512 * read data here should the balance of the register be
2513 * interpreted by the guest:
2515 * L2 cache control register 3: 64GB range, 256KB size,
2516 * enabled, latency 0x1, configured
2518 msr_info->data = 0xbe702111;
2520 case MSR_AMD64_OSVW_ID_LENGTH:
2521 if (!guest_cpuid_has_osvw(vcpu))
2523 msr_info->data = vcpu->arch.osvw.length;
2525 case MSR_AMD64_OSVW_STATUS:
2526 if (!guest_cpuid_has_osvw(vcpu))
2528 msr_info->data = vcpu->arch.osvw.status;
2531 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2532 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2534 vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr_info->index);
2537 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr_info->index);
2544 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2547 * Read or write a bunch of msrs. All parameters are kernel addresses.
2549 * @return number of msrs set successfully.
2551 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2552 struct kvm_msr_entry *entries,
2553 int (*do_msr)(struct kvm_vcpu *vcpu,
2554 unsigned index, u64 *data))
2558 idx = srcu_read_lock(&vcpu->kvm->srcu);
2559 for (i = 0; i < msrs->nmsrs; ++i)
2560 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2562 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2568 * Read or write a bunch of msrs. Parameters are user addresses.
2570 * @return number of msrs set successfully.
2572 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2573 int (*do_msr)(struct kvm_vcpu *vcpu,
2574 unsigned index, u64 *data),
2577 struct kvm_msrs msrs;
2578 struct kvm_msr_entry *entries;
2583 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2587 if (msrs.nmsrs >= MAX_IO_MSRS)
2590 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2591 entries = memdup_user(user_msrs->entries, size);
2592 if (IS_ERR(entries)) {
2593 r = PTR_ERR(entries);
2597 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2602 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2613 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2618 case KVM_CAP_IRQCHIP:
2620 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2621 case KVM_CAP_SET_TSS_ADDR:
2622 case KVM_CAP_EXT_CPUID:
2623 case KVM_CAP_EXT_EMUL_CPUID:
2624 case KVM_CAP_CLOCKSOURCE:
2626 case KVM_CAP_NOP_IO_DELAY:
2627 case KVM_CAP_MP_STATE:
2628 case KVM_CAP_SYNC_MMU:
2629 case KVM_CAP_USER_NMI:
2630 case KVM_CAP_REINJECT_CONTROL:
2631 case KVM_CAP_IRQ_INJECT_STATUS:
2632 case KVM_CAP_IOEVENTFD:
2633 case KVM_CAP_IOEVENTFD_NO_LENGTH:
2635 case KVM_CAP_PIT_STATE2:
2636 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2637 case KVM_CAP_XEN_HVM:
2638 case KVM_CAP_ADJUST_CLOCK:
2639 case KVM_CAP_VCPU_EVENTS:
2640 case KVM_CAP_HYPERV:
2641 case KVM_CAP_HYPERV_VAPIC:
2642 case KVM_CAP_HYPERV_SPIN:
2643 case KVM_CAP_PCI_SEGMENT:
2644 case KVM_CAP_DEBUGREGS:
2645 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2647 case KVM_CAP_ASYNC_PF:
2648 case KVM_CAP_GET_TSC_KHZ:
2649 case KVM_CAP_KVMCLOCK_CTRL:
2650 case KVM_CAP_READONLY_MEM:
2651 case KVM_CAP_HYPERV_TIME:
2652 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2653 case KVM_CAP_TSC_DEADLINE_TIMER:
2654 case KVM_CAP_ENABLE_CAP_VM:
2655 case KVM_CAP_DISABLE_QUIRKS:
2656 case KVM_CAP_SET_BOOT_CPU_ID:
2657 case KVM_CAP_SPLIT_IRQCHIP:
2658 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2659 case KVM_CAP_ASSIGN_DEV_IRQ:
2660 case KVM_CAP_PCI_2_3:
2664 case KVM_CAP_X86_SMM:
2665 /* SMBASE is usually relocated above 1M on modern chipsets,
2666 * and SMM handlers might indeed rely on 4G segment limits,
2667 * so do not report SMM to be available if real mode is
2668 * emulated via vm86 mode. Still, do not go to great lengths
2669 * to avoid userspace's usage of the feature, because it is a
2670 * fringe case that is not enabled except via specific settings
2671 * of the module parameters.
2673 r = kvm_x86_ops->has_emulated_msr(MSR_IA32_SMBASE);
2675 case KVM_CAP_COALESCED_MMIO:
2676 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2679 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2681 case KVM_CAP_NR_VCPUS:
2682 r = KVM_SOFT_MAX_VCPUS;
2684 case KVM_CAP_MAX_VCPUS:
2687 case KVM_CAP_NR_MEMSLOTS:
2688 r = KVM_USER_MEM_SLOTS;
2690 case KVM_CAP_PV_MMU: /* obsolete */
2693 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2695 r = iommu_present(&pci_bus_type);
2699 r = KVM_MAX_MCE_BANKS;
2704 case KVM_CAP_TSC_CONTROL:
2705 r = kvm_has_tsc_control;
2715 long kvm_arch_dev_ioctl(struct file *filp,
2716 unsigned int ioctl, unsigned long arg)
2718 void __user *argp = (void __user *)arg;
2722 case KVM_GET_MSR_INDEX_LIST: {
2723 struct kvm_msr_list __user *user_msr_list = argp;
2724 struct kvm_msr_list msr_list;
2728 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2731 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
2732 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2735 if (n < msr_list.nmsrs)
2738 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2739 num_msrs_to_save * sizeof(u32)))
2741 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2743 num_emulated_msrs * sizeof(u32)))
2748 case KVM_GET_SUPPORTED_CPUID:
2749 case KVM_GET_EMULATED_CPUID: {
2750 struct kvm_cpuid2 __user *cpuid_arg = argp;
2751 struct kvm_cpuid2 cpuid;
2754 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2757 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2763 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2768 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2771 mce_cap = KVM_MCE_CAP_SUPPORTED;
2773 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2785 static void wbinvd_ipi(void *garbage)
2790 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2792 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2795 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2797 /* Address WBINVD may be executed by guest */
2798 if (need_emulate_wbinvd(vcpu)) {
2799 if (kvm_x86_ops->has_wbinvd_exit())
2800 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2801 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2802 smp_call_function_single(vcpu->cpu,
2803 wbinvd_ipi, NULL, 1);
2806 kvm_x86_ops->vcpu_load(vcpu, cpu);
2808 /* Apply any externally detected TSC adjustments (due to suspend) */
2809 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2810 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2811 vcpu->arch.tsc_offset_adjustment = 0;
2812 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2815 if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2816 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2817 rdtsc() - vcpu->arch.last_host_tsc;
2819 mark_tsc_unstable("KVM discovered backwards TSC");
2820 if (check_tsc_unstable()) {
2821 u64 offset = kvm_compute_tsc_offset(vcpu,
2822 vcpu->arch.last_guest_tsc);
2823 kvm_x86_ops->write_tsc_offset(vcpu, offset);
2824 vcpu->arch.tsc_catchup = 1;
2827 * On a host with synchronized TSC, there is no need to update
2828 * kvmclock on vcpu->cpu migration
2830 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
2831 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2832 if (vcpu->cpu != cpu)
2833 kvm_migrate_timers(vcpu);
2837 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2840 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2842 kvm_x86_ops->vcpu_put(vcpu);
2843 kvm_put_guest_fpu(vcpu);
2844 vcpu->arch.last_host_tsc = rdtsc();
2846 * If userspace has set any breakpoints or watchpoints, dr6 is restored
2847 * on every vmexit, but if not, we might have a stale dr6 from the
2848 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
2853 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2854 struct kvm_lapic_state *s)
2856 kvm_x86_ops->sync_pir_to_irr(vcpu);
2857 memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2862 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2863 struct kvm_lapic_state *s)
2865 kvm_apic_post_state_restore(vcpu, s);
2866 update_cr8_intercept(vcpu);
2871 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
2873 return (!lapic_in_kernel(vcpu) ||
2874 kvm_apic_accept_pic_intr(vcpu));
2878 * if userspace requested an interrupt window, check that the
2879 * interrupt window is open.
2881 * No need to exit to userspace if we already have an interrupt queued.
2883 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
2885 return kvm_arch_interrupt_allowed(vcpu) &&
2886 !kvm_cpu_has_interrupt(vcpu) &&
2887 !kvm_event_needs_reinjection(vcpu) &&
2888 kvm_cpu_accept_dm_intr(vcpu);
2891 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2892 struct kvm_interrupt *irq)
2894 if (irq->irq >= KVM_NR_INTERRUPTS)
2897 if (!irqchip_in_kernel(vcpu->kvm)) {
2898 kvm_queue_interrupt(vcpu, irq->irq, false);
2899 kvm_make_request(KVM_REQ_EVENT, vcpu);
2904 * With in-kernel LAPIC, we only use this to inject EXTINT, so
2905 * fail for in-kernel 8259.
2907 if (pic_in_kernel(vcpu->kvm))
2910 if (vcpu->arch.pending_external_vector != -1)
2913 vcpu->arch.pending_external_vector = irq->irq;
2914 kvm_make_request(KVM_REQ_EVENT, vcpu);
2918 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2920 kvm_inject_nmi(vcpu);
2925 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
2927 kvm_make_request(KVM_REQ_SMI, vcpu);
2932 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2933 struct kvm_tpr_access_ctl *tac)
2937 vcpu->arch.tpr_access_reporting = !!tac->enabled;
2941 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2945 unsigned bank_num = mcg_cap & 0xff, bank;
2948 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
2950 if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2953 vcpu->arch.mcg_cap = mcg_cap;
2954 /* Init IA32_MCG_CTL to all 1s */
2955 if (mcg_cap & MCG_CTL_P)
2956 vcpu->arch.mcg_ctl = ~(u64)0;
2957 /* Init IA32_MCi_CTL to all 1s */
2958 for (bank = 0; bank < bank_num; bank++)
2959 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2964 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2965 struct kvm_x86_mce *mce)
2967 u64 mcg_cap = vcpu->arch.mcg_cap;
2968 unsigned bank_num = mcg_cap & 0xff;
2969 u64 *banks = vcpu->arch.mce_banks;
2971 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2974 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2975 * reporting is disabled
2977 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2978 vcpu->arch.mcg_ctl != ~(u64)0)
2980 banks += 4 * mce->bank;
2982 * if IA32_MCi_CTL is not all 1s, the uncorrected error
2983 * reporting is disabled for the bank
2985 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2987 if (mce->status & MCI_STATUS_UC) {
2988 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2989 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2990 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2993 if (banks[1] & MCI_STATUS_VAL)
2994 mce->status |= MCI_STATUS_OVER;
2995 banks[2] = mce->addr;
2996 banks[3] = mce->misc;
2997 vcpu->arch.mcg_status = mce->mcg_status;
2998 banks[1] = mce->status;
2999 kvm_queue_exception(vcpu, MC_VECTOR);
3000 } else if (!(banks[1] & MCI_STATUS_VAL)
3001 || !(banks[1] & MCI_STATUS_UC)) {
3002 if (banks[1] & MCI_STATUS_VAL)
3003 mce->status |= MCI_STATUS_OVER;
3004 banks[2] = mce->addr;
3005 banks[3] = mce->misc;
3006 banks[1] = mce->status;
3008 banks[1] |= MCI_STATUS_OVER;
3012 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3013 struct kvm_vcpu_events *events)
3016 events->exception.injected =
3017 vcpu->arch.exception.pending &&
3018 !kvm_exception_is_soft(vcpu->arch.exception.nr);
3019 events->exception.nr = vcpu->arch.exception.nr;
3020 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3021 events->exception.pad = 0;
3022 events->exception.error_code = vcpu->arch.exception.error_code;
3024 events->interrupt.injected =
3025 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
3026 events->interrupt.nr = vcpu->arch.interrupt.nr;
3027 events->interrupt.soft = 0;
3028 events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3030 events->nmi.injected = vcpu->arch.nmi_injected;
3031 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3032 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3033 events->nmi.pad = 0;
3035 events->sipi_vector = 0; /* never valid when reporting to user space */
3037 events->smi.smm = is_smm(vcpu);
3038 events->smi.pending = vcpu->arch.smi_pending;
3039 events->smi.smm_inside_nmi =
3040 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3041 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3043 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3044 | KVM_VCPUEVENT_VALID_SHADOW
3045 | KVM_VCPUEVENT_VALID_SMM);
3046 memset(&events->reserved, 0, sizeof(events->reserved));
3049 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
3051 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3052 struct kvm_vcpu_events *events)
3054 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3055 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3056 | KVM_VCPUEVENT_VALID_SHADOW
3057 | KVM_VCPUEVENT_VALID_SMM))
3060 if (events->exception.injected &&
3061 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
3064 /* INITs are latched while in SMM */
3065 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3066 (events->smi.smm || events->smi.pending) &&
3067 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3071 vcpu->arch.exception.pending = events->exception.injected;
3072 vcpu->arch.exception.nr = events->exception.nr;
3073 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3074 vcpu->arch.exception.error_code = events->exception.error_code;
3076 vcpu->arch.interrupt.pending = events->interrupt.injected;
3077 vcpu->arch.interrupt.nr = events->interrupt.nr;
3078 vcpu->arch.interrupt.soft = events->interrupt.soft;
3079 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3080 kvm_x86_ops->set_interrupt_shadow(vcpu,
3081 events->interrupt.shadow);
3083 vcpu->arch.nmi_injected = events->nmi.injected;
3084 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3085 vcpu->arch.nmi_pending = events->nmi.pending;
3086 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3088 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3089 kvm_vcpu_has_lapic(vcpu))
3090 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3092 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3093 u32 hflags = vcpu->arch.hflags;
3094 if (events->smi.smm)
3095 hflags |= HF_SMM_MASK;
3097 hflags &= ~HF_SMM_MASK;
3098 kvm_set_hflags(vcpu, hflags);
3100 vcpu->arch.smi_pending = events->smi.pending;
3101 if (events->smi.smm_inside_nmi)
3102 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3104 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3105 if (kvm_vcpu_has_lapic(vcpu)) {
3106 if (events->smi.latched_init)
3107 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3109 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3113 kvm_make_request(KVM_REQ_EVENT, vcpu);
3118 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3119 struct kvm_debugregs *dbgregs)
3123 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3124 kvm_get_dr(vcpu, 6, &val);
3126 dbgregs->dr7 = vcpu->arch.dr7;
3128 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3131 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3132 struct kvm_debugregs *dbgregs)
3137 if (dbgregs->dr6 & ~0xffffffffull)
3139 if (dbgregs->dr7 & ~0xffffffffull)
3142 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3143 kvm_update_dr0123(vcpu);
3144 vcpu->arch.dr6 = dbgregs->dr6;
3145 kvm_update_dr6(vcpu);
3146 vcpu->arch.dr7 = dbgregs->dr7;
3147 kvm_update_dr7(vcpu);
3152 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3154 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3156 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3157 u64 xstate_bv = xsave->header.xfeatures;
3161 * Copy legacy XSAVE area, to avoid complications with CPUID
3162 * leaves 0 and 1 in the loop below.
3164 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3167 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3168 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3171 * Copy each region from the possibly compacted offset to the
3172 * non-compacted offset.
3174 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3176 u64 feature = valid & -valid;
3177 int index = fls64(feature) - 1;
3178 void *src = get_xsave_addr(xsave, feature);
3181 u32 size, offset, ecx, edx;
3182 cpuid_count(XSTATE_CPUID, index,
3183 &size, &offset, &ecx, &edx);
3184 memcpy(dest + offset, src, size);
3191 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3193 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3194 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3198 * Copy legacy XSAVE area, to avoid complications with CPUID
3199 * leaves 0 and 1 in the loop below.
3201 memcpy(xsave, src, XSAVE_HDR_OFFSET);
3203 /* Set XSTATE_BV and possibly XCOMP_BV. */
3204 xsave->header.xfeatures = xstate_bv;
3206 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3209 * Copy each region from the non-compacted offset to the
3210 * possibly compacted offset.
3212 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3214 u64 feature = valid & -valid;
3215 int index = fls64(feature) - 1;
3216 void *dest = get_xsave_addr(xsave, feature);
3219 u32 size, offset, ecx, edx;
3220 cpuid_count(XSTATE_CPUID, index,
3221 &size, &offset, &ecx, &edx);
3222 memcpy(dest, src + offset, size);
3229 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3230 struct kvm_xsave *guest_xsave)
3232 if (cpu_has_xsave) {
3233 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
3234 fill_xsave((u8 *) guest_xsave->region, vcpu);
3236 memcpy(guest_xsave->region,
3237 &vcpu->arch.guest_fpu.state.fxsave,
3238 sizeof(struct fxregs_state));
3239 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3240 XFEATURE_MASK_FPSSE;
3244 #define XSAVE_MXCSR_OFFSET 24
3246 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3247 struct kvm_xsave *guest_xsave)
3250 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3251 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
3253 if (cpu_has_xsave) {
3255 * Here we allow setting states that are not present in
3256 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
3257 * with old userspace.
3259 if (xstate_bv & ~kvm_supported_xcr0() ||
3260 mxcsr & ~mxcsr_feature_mask)
3262 load_xsave(vcpu, (u8 *)guest_xsave->region);
3264 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
3265 mxcsr & ~mxcsr_feature_mask)
3267 memcpy(&vcpu->arch.guest_fpu.state.fxsave,
3268 guest_xsave->region, sizeof(struct fxregs_state));
3273 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3274 struct kvm_xcrs *guest_xcrs)
3276 if (!cpu_has_xsave) {
3277 guest_xcrs->nr_xcrs = 0;
3281 guest_xcrs->nr_xcrs = 1;
3282 guest_xcrs->flags = 0;
3283 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3284 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3287 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3288 struct kvm_xcrs *guest_xcrs)
3295 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3298 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3299 /* Only support XCR0 currently */
3300 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3301 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3302 guest_xcrs->xcrs[i].value);
3311 * kvm_set_guest_paused() indicates to the guest kernel that it has been
3312 * stopped by the hypervisor. This function will be called from the host only.
3313 * EINVAL is returned when the host attempts to set the flag for a guest that
3314 * does not support pv clocks.
3316 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3318 if (!vcpu->arch.pv_time_enabled)
3320 vcpu->arch.pvclock_set_guest_stopped_request = true;
3321 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3325 long kvm_arch_vcpu_ioctl(struct file *filp,
3326 unsigned int ioctl, unsigned long arg)
3328 struct kvm_vcpu *vcpu = filp->private_data;
3329 void __user *argp = (void __user *)arg;
3332 struct kvm_lapic_state *lapic;
3333 struct kvm_xsave *xsave;
3334 struct kvm_xcrs *xcrs;
3340 case KVM_GET_LAPIC: {
3342 if (!vcpu->arch.apic)
3344 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3349 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3353 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3358 case KVM_SET_LAPIC: {
3360 if (!vcpu->arch.apic)
3362 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3363 if (IS_ERR(u.lapic))
3364 return PTR_ERR(u.lapic);
3366 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3369 case KVM_INTERRUPT: {
3370 struct kvm_interrupt irq;
3373 if (copy_from_user(&irq, argp, sizeof irq))
3375 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3379 r = kvm_vcpu_ioctl_nmi(vcpu);
3383 r = kvm_vcpu_ioctl_smi(vcpu);
3386 case KVM_SET_CPUID: {
3387 struct kvm_cpuid __user *cpuid_arg = argp;
3388 struct kvm_cpuid cpuid;
3391 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3393 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3396 case KVM_SET_CPUID2: {
3397 struct kvm_cpuid2 __user *cpuid_arg = argp;
3398 struct kvm_cpuid2 cpuid;
3401 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3403 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3404 cpuid_arg->entries);
3407 case KVM_GET_CPUID2: {
3408 struct kvm_cpuid2 __user *cpuid_arg = argp;
3409 struct kvm_cpuid2 cpuid;
3412 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3414 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3415 cpuid_arg->entries);
3419 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3425 r = msr_io(vcpu, argp, do_get_msr, 1);
3428 r = msr_io(vcpu, argp, do_set_msr, 0);
3430 case KVM_TPR_ACCESS_REPORTING: {
3431 struct kvm_tpr_access_ctl tac;
3434 if (copy_from_user(&tac, argp, sizeof tac))
3436 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3440 if (copy_to_user(argp, &tac, sizeof tac))
3445 case KVM_SET_VAPIC_ADDR: {
3446 struct kvm_vapic_addr va;
3450 if (!lapic_in_kernel(vcpu))
3453 if (copy_from_user(&va, argp, sizeof va))
3455 idx = srcu_read_lock(&vcpu->kvm->srcu);
3456 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3457 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3460 case KVM_X86_SETUP_MCE: {
3464 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3466 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3469 case KVM_X86_SET_MCE: {
3470 struct kvm_x86_mce mce;
3473 if (copy_from_user(&mce, argp, sizeof mce))
3475 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3478 case KVM_GET_VCPU_EVENTS: {
3479 struct kvm_vcpu_events events;
3481 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3484 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3489 case KVM_SET_VCPU_EVENTS: {
3490 struct kvm_vcpu_events events;
3493 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3496 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3499 case KVM_GET_DEBUGREGS: {
3500 struct kvm_debugregs dbgregs;
3502 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3505 if (copy_to_user(argp, &dbgregs,
3506 sizeof(struct kvm_debugregs)))
3511 case KVM_SET_DEBUGREGS: {
3512 struct kvm_debugregs dbgregs;
3515 if (copy_from_user(&dbgregs, argp,
3516 sizeof(struct kvm_debugregs)))
3519 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3522 case KVM_GET_XSAVE: {
3523 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3528 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3531 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3536 case KVM_SET_XSAVE: {
3537 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3538 if (IS_ERR(u.xsave))
3539 return PTR_ERR(u.xsave);
3541 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3544 case KVM_GET_XCRS: {
3545 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3550 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3553 if (copy_to_user(argp, u.xcrs,
3554 sizeof(struct kvm_xcrs)))
3559 case KVM_SET_XCRS: {
3560 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3562 return PTR_ERR(u.xcrs);
3564 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3567 case KVM_SET_TSC_KHZ: {
3571 user_tsc_khz = (u32)arg;
3573 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3576 if (user_tsc_khz == 0)
3577 user_tsc_khz = tsc_khz;
3579 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
3584 case KVM_GET_TSC_KHZ: {
3585 r = vcpu->arch.virtual_tsc_khz;
3588 case KVM_KVMCLOCK_CTRL: {
3589 r = kvm_set_guest_paused(vcpu);
3600 int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3602 return VM_FAULT_SIGBUS;
3605 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3609 if (addr > (unsigned int)(-3 * PAGE_SIZE))
3611 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3615 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3618 kvm->arch.ept_identity_map_addr = ident_addr;
3622 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3623 u32 kvm_nr_mmu_pages)
3625 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3628 mutex_lock(&kvm->slots_lock);
3630 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3631 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3633 mutex_unlock(&kvm->slots_lock);
3637 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3639 return kvm->arch.n_max_mmu_pages;
3642 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3647 switch (chip->chip_id) {
3648 case KVM_IRQCHIP_PIC_MASTER:
3649 memcpy(&chip->chip.pic,
3650 &pic_irqchip(kvm)->pics[0],
3651 sizeof(struct kvm_pic_state));
3653 case KVM_IRQCHIP_PIC_SLAVE:
3654 memcpy(&chip->chip.pic,
3655 &pic_irqchip(kvm)->pics[1],
3656 sizeof(struct kvm_pic_state));
3658 case KVM_IRQCHIP_IOAPIC:
3659 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3668 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3673 switch (chip->chip_id) {
3674 case KVM_IRQCHIP_PIC_MASTER:
3675 spin_lock(&pic_irqchip(kvm)->lock);
3676 memcpy(&pic_irqchip(kvm)->pics[0],
3678 sizeof(struct kvm_pic_state));
3679 spin_unlock(&pic_irqchip(kvm)->lock);
3681 case KVM_IRQCHIP_PIC_SLAVE:
3682 spin_lock(&pic_irqchip(kvm)->lock);
3683 memcpy(&pic_irqchip(kvm)->pics[1],
3685 sizeof(struct kvm_pic_state));
3686 spin_unlock(&pic_irqchip(kvm)->lock);
3688 case KVM_IRQCHIP_IOAPIC:
3689 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3695 kvm_pic_update_irq(pic_irqchip(kvm));
3699 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3701 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3702 memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
3703 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3707 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3710 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3711 memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
3712 for (i = 0; i < 3; i++)
3713 kvm_pit_load_count(kvm, i, ps->channels[i].count, 0);
3714 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3718 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3720 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3721 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3722 sizeof(ps->channels));
3723 ps->flags = kvm->arch.vpit->pit_state.flags;
3724 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3725 memset(&ps->reserved, 0, sizeof(ps->reserved));
3729 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3733 u32 prev_legacy, cur_legacy;
3734 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3735 prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3736 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3737 if (!prev_legacy && cur_legacy)
3739 memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
3740 sizeof(kvm->arch.vpit->pit_state.channels));
3741 kvm->arch.vpit->pit_state.flags = ps->flags;
3742 for (i = 0; i < 3; i++)
3743 kvm_pit_load_count(kvm, i, kvm->arch.vpit->pit_state.channels[i].count,
3745 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3749 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3750 struct kvm_reinject_control *control)
3752 if (!kvm->arch.vpit)
3754 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3755 kvm->arch.vpit->pit_state.reinject = control->pit_reinject;
3756 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3761 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
3762 * @kvm: kvm instance
3763 * @log: slot id and address to which we copy the log
3765 * Steps 1-4 below provide general overview of dirty page logging. See
3766 * kvm_get_dirty_log_protect() function description for additional details.
3768 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
3769 * always flush the TLB (step 4) even if previous step failed and the dirty
3770 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
3771 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
3772 * writes will be marked dirty for next log read.
3774 * 1. Take a snapshot of the bit and clear it if needed.
3775 * 2. Write protect the corresponding page.
3776 * 3. Copy the snapshot to the userspace.
3777 * 4. Flush TLB's if needed.
3779 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
3781 bool is_dirty = false;
3784 mutex_lock(&kvm->slots_lock);
3787 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
3789 if (kvm_x86_ops->flush_log_dirty)
3790 kvm_x86_ops->flush_log_dirty(kvm);
3792 r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
3795 * All the TLBs can be flushed out of mmu lock, see the comments in
3796 * kvm_mmu_slot_remove_write_access().
3798 lockdep_assert_held(&kvm->slots_lock);
3800 kvm_flush_remote_tlbs(kvm);
3802 mutex_unlock(&kvm->slots_lock);
3806 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
3809 if (!irqchip_in_kernel(kvm))
3812 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3813 irq_event->irq, irq_event->level,
3818 static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3819 struct kvm_enable_cap *cap)
3827 case KVM_CAP_DISABLE_QUIRKS:
3828 kvm->arch.disabled_quirks = cap->args[0];
3831 case KVM_CAP_SPLIT_IRQCHIP: {
3832 mutex_lock(&kvm->lock);
3834 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
3835 goto split_irqchip_unlock;
3837 if (irqchip_in_kernel(kvm))
3838 goto split_irqchip_unlock;
3839 if (atomic_read(&kvm->online_vcpus))
3840 goto split_irqchip_unlock;
3841 r = kvm_setup_empty_irq_routing(kvm);
3843 goto split_irqchip_unlock;
3844 /* Pairs with irqchip_in_kernel. */
3846 kvm->arch.irqchip_split = true;
3847 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
3849 split_irqchip_unlock:
3850 mutex_unlock(&kvm->lock);
3860 long kvm_arch_vm_ioctl(struct file *filp,
3861 unsigned int ioctl, unsigned long arg)
3863 struct kvm *kvm = filp->private_data;
3864 void __user *argp = (void __user *)arg;
3867 * This union makes it completely explicit to gcc-3.x
3868 * that these two variables' stack usage should be
3869 * combined, not added together.
3872 struct kvm_pit_state ps;
3873 struct kvm_pit_state2 ps2;
3874 struct kvm_pit_config pit_config;
3878 case KVM_SET_TSS_ADDR:
3879 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3881 case KVM_SET_IDENTITY_MAP_ADDR: {
3885 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3887 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3890 case KVM_SET_NR_MMU_PAGES:
3891 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3893 case KVM_GET_NR_MMU_PAGES:
3894 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3896 case KVM_CREATE_IRQCHIP: {
3897 struct kvm_pic *vpic;
3899 mutex_lock(&kvm->lock);
3902 goto create_irqchip_unlock;
3904 if (atomic_read(&kvm->online_vcpus))
3905 goto create_irqchip_unlock;
3907 vpic = kvm_create_pic(kvm);
3909 r = kvm_ioapic_init(kvm);
3911 mutex_lock(&kvm->slots_lock);
3912 kvm_destroy_pic(vpic);
3913 mutex_unlock(&kvm->slots_lock);
3914 goto create_irqchip_unlock;
3917 goto create_irqchip_unlock;
3918 r = kvm_setup_default_irq_routing(kvm);
3920 mutex_lock(&kvm->slots_lock);
3921 mutex_lock(&kvm->irq_lock);
3922 kvm_ioapic_destroy(kvm);
3923 kvm_destroy_pic(vpic);
3924 mutex_unlock(&kvm->irq_lock);
3925 mutex_unlock(&kvm->slots_lock);
3926 goto create_irqchip_unlock;
3928 /* Write kvm->irq_routing before kvm->arch.vpic. */
3930 kvm->arch.vpic = vpic;
3931 create_irqchip_unlock:
3932 mutex_unlock(&kvm->lock);
3935 case KVM_CREATE_PIT:
3936 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3938 case KVM_CREATE_PIT2:
3940 if (copy_from_user(&u.pit_config, argp,
3941 sizeof(struct kvm_pit_config)))
3944 mutex_lock(&kvm->lock);
3947 goto create_pit_unlock;
3949 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3953 mutex_unlock(&kvm->lock);
3955 case KVM_GET_IRQCHIP: {
3956 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3957 struct kvm_irqchip *chip;
3959 chip = memdup_user(argp, sizeof(*chip));
3966 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
3967 goto get_irqchip_out;
3968 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3970 goto get_irqchip_out;
3972 if (copy_to_user(argp, chip, sizeof *chip))
3973 goto get_irqchip_out;
3979 case KVM_SET_IRQCHIP: {
3980 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3981 struct kvm_irqchip *chip;
3983 chip = memdup_user(argp, sizeof(*chip));
3990 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
3991 goto set_irqchip_out;
3992 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3994 goto set_irqchip_out;
4002 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
4005 if (!kvm->arch.vpit)
4007 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
4011 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
4018 if (copy_from_user(&u.ps, argp, sizeof u.ps))
4020 mutex_lock(&kvm->lock);
4022 if (!kvm->arch.vpit)
4024 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
4026 mutex_unlock(&kvm->lock);
4029 case KVM_GET_PIT2: {
4031 if (!kvm->arch.vpit)
4033 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
4037 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
4042 case KVM_SET_PIT2: {
4044 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
4046 mutex_lock(&kvm->lock);
4048 if (!kvm->arch.vpit)
4050 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
4052 mutex_unlock(&kvm->lock);
4055 case KVM_REINJECT_CONTROL: {
4056 struct kvm_reinject_control control;
4058 if (copy_from_user(&control, argp, sizeof(control)))
4060 r = kvm_vm_ioctl_reinject(kvm, &control);
4063 case KVM_SET_BOOT_CPU_ID:
4065 mutex_lock(&kvm->lock);
4066 if (atomic_read(&kvm->online_vcpus) != 0)
4069 kvm->arch.bsp_vcpu_id = arg;
4070 mutex_unlock(&kvm->lock);
4072 case KVM_XEN_HVM_CONFIG: {
4073 struct kvm_xen_hvm_config xhc;
4075 if (copy_from_user(&xhc, argp, sizeof(xhc)))
4080 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
4084 case KVM_SET_CLOCK: {
4085 struct kvm_clock_data user_ns;
4090 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
4098 local_irq_disable();
4099 now_ns = get_kernel_ns();
4100 delta = user_ns.clock - now_ns;
4102 kvm->arch.kvmclock_offset = delta;
4103 kvm_gen_update_masterclock(kvm);
4106 case KVM_GET_CLOCK: {
4107 struct kvm_clock_data user_ns;
4110 local_irq_disable();
4111 now_ns = get_kernel_ns();
4112 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
4115 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
4118 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
4123 case KVM_ENABLE_CAP: {
4124 struct kvm_enable_cap cap;
4127 if (copy_from_user(&cap, argp, sizeof(cap)))
4129 r = kvm_vm_ioctl_enable_cap(kvm, &cap);
4133 r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
4139 static void kvm_init_msr_list(void)
4144 for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
4145 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
4149 * Even MSRs that are valid in the host may not be exposed
4150 * to the guests in some cases.
4152 switch (msrs_to_save[i]) {
4153 case MSR_IA32_BNDCFGS:
4154 if (!kvm_x86_ops->mpx_supported())
4158 if (!kvm_x86_ops->rdtscp_supported())
4166 msrs_to_save[j] = msrs_to_save[i];
4169 num_msrs_to_save = j;
4171 for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
4172 if (!kvm_x86_ops->has_emulated_msr(emulated_msrs[i]))
4176 emulated_msrs[j] = emulated_msrs[i];
4179 num_emulated_msrs = j;
4182 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
4190 if (!(vcpu->arch.apic &&
4191 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
4192 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
4203 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
4210 if (!(vcpu->arch.apic &&
4211 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
4213 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
4215 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
4225 static void kvm_set_segment(struct kvm_vcpu *vcpu,
4226 struct kvm_segment *var, int seg)
4228 kvm_x86_ops->set_segment(vcpu, var, seg);
4231 void kvm_get_segment(struct kvm_vcpu *vcpu,
4232 struct kvm_segment *var, int seg)
4234 kvm_x86_ops->get_segment(vcpu, var, seg);
4237 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
4238 struct x86_exception *exception)
4242 BUG_ON(!mmu_is_nested(vcpu));
4244 /* NPT walks are always user-walks */
4245 access |= PFERR_USER_MASK;
4246 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
4251 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
4252 struct x86_exception *exception)
4254 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4255 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4258 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
4259 struct x86_exception *exception)
4261 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4262 access |= PFERR_FETCH_MASK;
4263 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4266 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4267 struct x86_exception *exception)
4269 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4270 access |= PFERR_WRITE_MASK;
4271 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4274 /* uses this to access any guest's mapped memory without checking CPL */
4275 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4276 struct x86_exception *exception)
4278 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
4281 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4282 struct kvm_vcpu *vcpu, u32 access,
4283 struct x86_exception *exception)
4286 int r = X86EMUL_CONTINUE;
4289 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4291 unsigned offset = addr & (PAGE_SIZE-1);
4292 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4295 if (gpa == UNMAPPED_GVA)
4296 return X86EMUL_PROPAGATE_FAULT;
4297 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
4300 r = X86EMUL_IO_NEEDED;
4312 /* used for instruction fetching */
4313 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4314 gva_t addr, void *val, unsigned int bytes,
4315 struct x86_exception *exception)
4317 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4318 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4322 /* Inline kvm_read_guest_virt_helper for speed. */
4323 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
4325 if (unlikely(gpa == UNMAPPED_GVA))
4326 return X86EMUL_PROPAGATE_FAULT;
4328 offset = addr & (PAGE_SIZE-1);
4329 if (WARN_ON(offset + bytes > PAGE_SIZE))
4330 bytes = (unsigned)PAGE_SIZE - offset;
4331 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
4333 if (unlikely(ret < 0))
4334 return X86EMUL_IO_NEEDED;
4336 return X86EMUL_CONTINUE;
4339 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
4340 gva_t addr, void *val, unsigned int bytes,
4341 struct x86_exception *exception)
4343 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4346 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
4347 * is returned, but our callers are not ready for that and they blindly
4348 * call kvm_inject_page_fault. Ensure that they at least do not leak
4349 * uninitialized kernel stack memory into cr2 and error code.
4351 memset(exception, 0, sizeof(*exception));
4352 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4355 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4357 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
4358 gva_t addr, void *val, unsigned int bytes,
4359 struct x86_exception *exception, bool system)
4361 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4364 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
4365 access |= PFERR_USER_MASK;
4367 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
4370 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
4371 unsigned long addr, void *val, unsigned int bytes)
4373 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4374 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
4376 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
4379 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4380 struct kvm_vcpu *vcpu, u32 access,
4381 struct x86_exception *exception)
4384 int r = X86EMUL_CONTINUE;
4387 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4390 unsigned offset = addr & (PAGE_SIZE-1);
4391 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4394 if (gpa == UNMAPPED_GVA)
4395 return X86EMUL_PROPAGATE_FAULT;
4396 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
4398 r = X86EMUL_IO_NEEDED;
4410 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
4411 unsigned int bytes, struct x86_exception *exception,
4414 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4415 u32 access = PFERR_WRITE_MASK;
4417 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
4418 access |= PFERR_USER_MASK;
4421 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
4422 * is returned, but our callers are not ready for that and they blindly
4423 * call kvm_inject_page_fault. Ensure that they at least do not leak
4424 * uninitialized kernel stack memory into cr2 and error code.
4426 memset(exception, 0, sizeof(*exception));
4427 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4431 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
4432 unsigned int bytes, struct x86_exception *exception)
4434 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4435 PFERR_WRITE_MASK, exception);
4437 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4439 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4440 gpa_t *gpa, struct x86_exception *exception,
4443 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
4444 | (write ? PFERR_WRITE_MASK : 0);
4446 if (vcpu_match_mmio_gva(vcpu, gva)
4447 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
4448 vcpu->arch.access, access)) {
4449 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4450 (gva & (PAGE_SIZE - 1));
4451 trace_vcpu_match_mmio(gva, *gpa, write, false);
4455 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4457 if (*gpa == UNMAPPED_GVA)
4460 /* For APIC access vmexit */
4461 if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4464 if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
4465 trace_vcpu_match_mmio(gva, *gpa, write, true);
4472 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4473 const void *val, int bytes)
4477 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
4480 kvm_mmu_pte_write(vcpu, gpa, val, bytes);
4484 struct read_write_emulator_ops {
4485 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4487 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4488 void *val, int bytes);
4489 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4490 int bytes, void *val);
4491 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4492 void *val, int bytes);
4496 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4498 if (vcpu->mmio_read_completed) {
4499 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4500 vcpu->mmio_fragments[0].gpa, val);
4501 vcpu->mmio_read_completed = 0;
4508 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4509 void *val, int bytes)
4511 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
4514 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4515 void *val, int bytes)
4517 return emulator_write_phys(vcpu, gpa, val, bytes);
4520 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4522 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
4523 return vcpu_mmio_write(vcpu, gpa, bytes, val);
4526 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4527 void *val, int bytes)
4529 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
4530 return X86EMUL_IO_NEEDED;
4533 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4534 void *val, int bytes)
4536 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
4538 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
4539 return X86EMUL_CONTINUE;
4542 static const struct read_write_emulator_ops read_emultor = {
4543 .read_write_prepare = read_prepare,
4544 .read_write_emulate = read_emulate,
4545 .read_write_mmio = vcpu_mmio_read,
4546 .read_write_exit_mmio = read_exit_mmio,
4549 static const struct read_write_emulator_ops write_emultor = {
4550 .read_write_emulate = write_emulate,
4551 .read_write_mmio = write_mmio,
4552 .read_write_exit_mmio = write_exit_mmio,
4556 static int emulator_read_write_onepage(unsigned long addr, void *val,
4558 struct x86_exception *exception,
4559 struct kvm_vcpu *vcpu,
4560 const struct read_write_emulator_ops *ops)
4564 bool write = ops->write;
4565 struct kvm_mmio_fragment *frag;
4567 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4570 return X86EMUL_PROPAGATE_FAULT;
4572 /* For APIC access vmexit */
4576 if (ops->read_write_emulate(vcpu, gpa, val, bytes))
4577 return X86EMUL_CONTINUE;
4581 * Is this MMIO handled locally?
4583 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4584 if (handled == bytes)
4585 return X86EMUL_CONTINUE;
4591 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
4592 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
4596 return X86EMUL_CONTINUE;
4599 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
4601 void *val, unsigned int bytes,
4602 struct x86_exception *exception,
4603 const struct read_write_emulator_ops *ops)
4605 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4609 if (ops->read_write_prepare &&
4610 ops->read_write_prepare(vcpu, val, bytes))
4611 return X86EMUL_CONTINUE;
4613 vcpu->mmio_nr_fragments = 0;
4615 /* Crossing a page boundary? */
4616 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4619 now = -addr & ~PAGE_MASK;
4620 rc = emulator_read_write_onepage(addr, val, now, exception,
4623 if (rc != X86EMUL_CONTINUE)
4626 if (ctxt->mode != X86EMUL_MODE_PROT64)
4632 rc = emulator_read_write_onepage(addr, val, bytes, exception,
4634 if (rc != X86EMUL_CONTINUE)
4637 if (!vcpu->mmio_nr_fragments)
4640 gpa = vcpu->mmio_fragments[0].gpa;
4642 vcpu->mmio_needed = 1;
4643 vcpu->mmio_cur_fragment = 0;
4645 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
4646 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
4647 vcpu->run->exit_reason = KVM_EXIT_MMIO;
4648 vcpu->run->mmio.phys_addr = gpa;
4650 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4653 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4657 struct x86_exception *exception)
4659 return emulator_read_write(ctxt, addr, val, bytes,
4660 exception, &read_emultor);
4663 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4667 struct x86_exception *exception)
4669 return emulator_read_write(ctxt, addr, (void *)val, bytes,
4670 exception, &write_emultor);
4673 #define CMPXCHG_TYPE(t, ptr, old, new) \
4674 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4676 #ifdef CONFIG_X86_64
4677 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4679 # define CMPXCHG64(ptr, old, new) \
4680 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4683 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4688 struct x86_exception *exception)
4690 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4696 /* guests cmpxchg8b have to be emulated atomically */
4697 if (bytes > 8 || (bytes & (bytes - 1)))
4700 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4702 if (gpa == UNMAPPED_GVA ||
4703 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4706 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4709 page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
4710 if (is_error_page(page))
4713 kaddr = kmap_atomic(page);
4714 kaddr += offset_in_page(gpa);
4717 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4720 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4723 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
4726 exchanged = CMPXCHG64(kaddr, old, new);
4731 kunmap_atomic(kaddr);
4732 kvm_release_page_dirty(page);
4735 return X86EMUL_CMPXCHG_FAILED;
4737 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
4738 kvm_mmu_pte_write(vcpu, gpa, new, bytes);
4740 return X86EMUL_CONTINUE;
4743 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
4745 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
4748 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
4752 for (i = 0; i < vcpu->arch.pio.count; i++) {
4753 if (vcpu->arch.pio.in)
4754 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
4755 vcpu->arch.pio.size, pd);
4757 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
4758 vcpu->arch.pio.port, vcpu->arch.pio.size,
4762 pd += vcpu->arch.pio.size;
4767 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
4768 unsigned short port, void *val,
4769 unsigned int count, bool in)
4771 vcpu->arch.pio.port = port;
4772 vcpu->arch.pio.in = in;
4773 vcpu->arch.pio.count = count;
4774 vcpu->arch.pio.size = size;
4776 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4777 vcpu->arch.pio.count = 0;
4781 vcpu->run->exit_reason = KVM_EXIT_IO;
4782 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
4783 vcpu->run->io.size = size;
4784 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4785 vcpu->run->io.count = count;
4786 vcpu->run->io.port = port;
4791 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
4792 int size, unsigned short port, void *val,
4795 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4798 if (vcpu->arch.pio.count)
4801 memset(vcpu->arch.pio_data, 0, size * count);
4803 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
4806 memcpy(val, vcpu->arch.pio_data, size * count);
4807 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
4808 vcpu->arch.pio.count = 0;
4815 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
4816 int size, unsigned short port,
4817 const void *val, unsigned int count)
4819 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4821 memcpy(vcpu->arch.pio_data, val, size * count);
4822 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
4823 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
4826 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
4828 return kvm_x86_ops->get_segment_base(vcpu, seg);
4831 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
4833 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
4836 int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
4838 if (!need_emulate_wbinvd(vcpu))
4839 return X86EMUL_CONTINUE;
4841 if (kvm_x86_ops->has_wbinvd_exit()) {
4842 int cpu = get_cpu();
4844 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4845 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
4846 wbinvd_ipi, NULL, 1);
4848 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
4851 return X86EMUL_CONTINUE;
4854 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
4856 kvm_x86_ops->skip_emulated_instruction(vcpu);
4857 return kvm_emulate_wbinvd_noskip(vcpu);
4859 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
4863 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
4865 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
4868 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
4869 unsigned long *dest)
4871 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
4874 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
4875 unsigned long value)
4878 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
4881 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
4883 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
4886 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
4888 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4889 unsigned long value;
4893 value = kvm_read_cr0(vcpu);
4896 value = vcpu->arch.cr2;
4899 value = kvm_read_cr3(vcpu);
4902 value = kvm_read_cr4(vcpu);
4905 value = kvm_get_cr8(vcpu);
4908 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4915 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
4917 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4922 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4925 vcpu->arch.cr2 = val;
4928 res = kvm_set_cr3(vcpu, val);
4931 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4934 res = kvm_set_cr8(vcpu, val);
4937 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4944 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
4946 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
4949 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4951 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
4954 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4956 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
4959 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4961 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4964 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4966 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4969 static unsigned long emulator_get_cached_segment_base(
4970 struct x86_emulate_ctxt *ctxt, int seg)
4972 return get_segment_base(emul_to_vcpu(ctxt), seg);
4975 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4976 struct desc_struct *desc, u32 *base3,
4979 struct kvm_segment var;
4981 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
4982 *selector = var.selector;
4985 memset(desc, 0, sizeof(*desc));
4993 set_desc_limit(desc, var.limit);
4994 set_desc_base(desc, (unsigned long)var.base);
4995 #ifdef CONFIG_X86_64
4997 *base3 = var.base >> 32;
4999 desc->type = var.type;
5001 desc->dpl = var.dpl;
5002 desc->p = var.present;
5003 desc->avl = var.avl;
5011 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
5012 struct desc_struct *desc, u32 base3,
5015 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5016 struct kvm_segment var;
5018 var.selector = selector;
5019 var.base = get_desc_base(desc);
5020 #ifdef CONFIG_X86_64
5021 var.base |= ((u64)base3) << 32;
5023 var.limit = get_desc_limit(desc);
5025 var.limit = (var.limit << 12) | 0xfff;
5026 var.type = desc->type;
5027 var.dpl = desc->dpl;
5032 var.avl = desc->avl;
5033 var.present = desc->p;
5034 var.unusable = !var.present;
5037 kvm_set_segment(vcpu, &var, seg);
5041 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
5042 u32 msr_index, u64 *pdata)
5044 struct msr_data msr;
5047 msr.index = msr_index;
5048 msr.host_initiated = false;
5049 r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
5057 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
5058 u32 msr_index, u64 data)
5060 struct msr_data msr;
5063 msr.index = msr_index;
5064 msr.host_initiated = false;
5065 return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
5068 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
5070 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5072 return vcpu->arch.smbase;
5075 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
5077 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5079 vcpu->arch.smbase = smbase;
5082 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
5085 return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
5088 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
5089 u32 pmc, u64 *pdata)
5091 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
5094 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
5096 emul_to_vcpu(ctxt)->arch.halt_request = 1;
5099 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
5102 kvm_load_guest_fpu(emul_to_vcpu(ctxt));
5104 * CR0.TS may reference the host fpu state, not the guest fpu state,
5105 * so it may be clear at this point.
5110 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
5115 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
5116 struct x86_instruction_info *info,
5117 enum x86_intercept_stage stage)
5119 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
5122 static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
5123 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
5125 kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
5128 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
5130 return kvm_register_read(emul_to_vcpu(ctxt), reg);
5133 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
5135 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
5138 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
5140 kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
5143 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
5145 return emul_to_vcpu(ctxt)->arch.hflags;
5148 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
5150 kvm_set_hflags(emul_to_vcpu(ctxt), emul_flags);
5153 static const struct x86_emulate_ops emulate_ops = {
5154 .read_gpr = emulator_read_gpr,
5155 .write_gpr = emulator_write_gpr,
5156 .read_std = emulator_read_std,
5157 .write_std = emulator_write_std,
5158 .read_phys = kvm_read_guest_phys_system,
5159 .fetch = kvm_fetch_guest_virt,
5160 .read_emulated = emulator_read_emulated,
5161 .write_emulated = emulator_write_emulated,
5162 .cmpxchg_emulated = emulator_cmpxchg_emulated,
5163 .invlpg = emulator_invlpg,
5164 .pio_in_emulated = emulator_pio_in_emulated,
5165 .pio_out_emulated = emulator_pio_out_emulated,
5166 .get_segment = emulator_get_segment,
5167 .set_segment = emulator_set_segment,
5168 .get_cached_segment_base = emulator_get_cached_segment_base,
5169 .get_gdt = emulator_get_gdt,
5170 .get_idt = emulator_get_idt,
5171 .set_gdt = emulator_set_gdt,
5172 .set_idt = emulator_set_idt,
5173 .get_cr = emulator_get_cr,
5174 .set_cr = emulator_set_cr,
5175 .cpl = emulator_get_cpl,
5176 .get_dr = emulator_get_dr,
5177 .set_dr = emulator_set_dr,
5178 .get_smbase = emulator_get_smbase,
5179 .set_smbase = emulator_set_smbase,
5180 .set_msr = emulator_set_msr,
5181 .get_msr = emulator_get_msr,
5182 .check_pmc = emulator_check_pmc,
5183 .read_pmc = emulator_read_pmc,
5184 .halt = emulator_halt,
5185 .wbinvd = emulator_wbinvd,
5186 .fix_hypercall = emulator_fix_hypercall,
5187 .get_fpu = emulator_get_fpu,
5188 .put_fpu = emulator_put_fpu,
5189 .intercept = emulator_intercept,
5190 .get_cpuid = emulator_get_cpuid,
5191 .set_nmi_mask = emulator_set_nmi_mask,
5192 .get_hflags = emulator_get_hflags,
5193 .set_hflags = emulator_set_hflags,
5196 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
5198 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
5200 * an sti; sti; sequence only disable interrupts for the first
5201 * instruction. So, if the last instruction, be it emulated or
5202 * not, left the system with the INT_STI flag enabled, it
5203 * means that the last instruction is an sti. We should not
5204 * leave the flag on in this case. The same goes for mov ss
5206 if (int_shadow & mask)
5208 if (unlikely(int_shadow || mask)) {
5209 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
5211 kvm_make_request(KVM_REQ_EVENT, vcpu);
5215 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
5217 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5218 if (ctxt->exception.vector == PF_VECTOR)
5219 return kvm_propagate_fault(vcpu, &ctxt->exception);
5221 if (ctxt->exception.error_code_valid)
5222 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
5223 ctxt->exception.error_code);
5225 kvm_queue_exception(vcpu, ctxt->exception.vector);
5229 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
5231 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5234 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5236 ctxt->eflags = kvm_get_rflags(vcpu);
5237 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
5239 ctxt->eip = kvm_rip_read(vcpu);
5240 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
5241 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
5242 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
5243 cs_db ? X86EMUL_MODE_PROT32 :
5244 X86EMUL_MODE_PROT16;
5245 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
5246 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
5247 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
5249 init_decode_cache(ctxt);
5250 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5253 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
5255 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5258 init_emulate_ctxt(vcpu);
5262 ctxt->_eip = ctxt->eip + inc_eip;
5263 ret = emulate_int_real(ctxt, irq);
5265 if (ret != X86EMUL_CONTINUE)
5266 return EMULATE_FAIL;
5268 ctxt->eip = ctxt->_eip;
5269 kvm_rip_write(vcpu, ctxt->eip);
5270 kvm_set_rflags(vcpu, ctxt->eflags);
5272 if (irq == NMI_VECTOR)
5273 vcpu->arch.nmi_pending = 0;
5275 vcpu->arch.interrupt.pending = false;
5277 return EMULATE_DONE;
5279 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
5281 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
5283 int r = EMULATE_DONE;
5285 ++vcpu->stat.insn_emulation_fail;
5286 trace_kvm_emulate_insn_failed(vcpu);
5287 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
5288 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5289 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5290 vcpu->run->internal.ndata = 0;
5291 r = EMULATE_USER_EXIT;
5293 kvm_queue_exception(vcpu, UD_VECTOR);
5298 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5299 bool write_fault_to_shadow_pgtable,
5305 if (emulation_type & EMULTYPE_NO_REEXECUTE)
5308 if (!vcpu->arch.mmu.direct_map) {
5310 * Write permission should be allowed since only
5311 * write access need to be emulated.
5313 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5316 * If the mapping is invalid in guest, let cpu retry
5317 * it to generate fault.
5319 if (gpa == UNMAPPED_GVA)
5324 * Do not retry the unhandleable instruction if it faults on the
5325 * readonly host memory, otherwise it will goto a infinite loop:
5326 * retry instruction -> write #PF -> emulation fail -> retry
5327 * instruction -> ...
5329 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
5332 * If the instruction failed on the error pfn, it can not be fixed,
5333 * report the error to userspace.
5335 if (is_error_noslot_pfn(pfn))
5338 kvm_release_pfn_clean(pfn);
5340 /* The instructions are well-emulated on direct mmu. */
5341 if (vcpu->arch.mmu.direct_map) {
5342 unsigned int indirect_shadow_pages;
5344 spin_lock(&vcpu->kvm->mmu_lock);
5345 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
5346 spin_unlock(&vcpu->kvm->mmu_lock);
5348 if (indirect_shadow_pages)
5349 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5355 * if emulation was due to access to shadowed page table
5356 * and it failed try to unshadow page and re-enter the
5357 * guest to let CPU execute the instruction.
5359 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5362 * If the access faults on its page table, it can not
5363 * be fixed by unprotecting shadow page and it should
5364 * be reported to userspace.
5366 return !write_fault_to_shadow_pgtable;
5369 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5370 unsigned long cr2, int emulation_type)
5372 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5373 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
5375 last_retry_eip = vcpu->arch.last_retry_eip;
5376 last_retry_addr = vcpu->arch.last_retry_addr;
5379 * If the emulation is caused by #PF and it is non-page_table
5380 * writing instruction, it means the VM-EXIT is caused by shadow
5381 * page protected, we can zap the shadow page and retry this
5382 * instruction directly.
5384 * Note: if the guest uses a non-page-table modifying instruction
5385 * on the PDE that points to the instruction, then we will unmap
5386 * the instruction and go to an infinite loop. So, we cache the
5387 * last retried eip and the last fault address, if we meet the eip
5388 * and the address again, we can break out of the potential infinite
5391 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
5393 if (!(emulation_type & EMULTYPE_RETRY))
5396 if (x86_page_table_writing_insn(ctxt))
5399 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
5402 vcpu->arch.last_retry_eip = ctxt->eip;
5403 vcpu->arch.last_retry_addr = cr2;
5405 if (!vcpu->arch.mmu.direct_map)
5406 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5408 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5413 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
5414 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
5416 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
5418 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
5419 /* This is a good place to trace that we are exiting SMM. */
5420 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
5422 if (unlikely(vcpu->arch.smi_pending)) {
5423 kvm_make_request(KVM_REQ_SMI, vcpu);
5424 vcpu->arch.smi_pending = 0;
5426 /* Process a latched INIT, if any. */
5427 kvm_make_request(KVM_REQ_EVENT, vcpu);
5431 kvm_mmu_reset_context(vcpu);
5434 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
5436 unsigned changed = vcpu->arch.hflags ^ emul_flags;
5438 vcpu->arch.hflags = emul_flags;
5440 if (changed & HF_SMM_MASK)
5441 kvm_smm_changed(vcpu);
5444 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
5453 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
5454 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
5459 static void kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu, int *r)
5461 struct kvm_run *kvm_run = vcpu->run;
5463 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5464 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
5465 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
5466 kvm_run->debug.arch.exception = DB_VECTOR;
5467 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5468 *r = EMULATE_USER_EXIT;
5470 vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF;
5472 * "Certain debug exceptions may clear bit 0-3. The
5473 * remaining contents of the DR6 register are never
5474 * cleared by the processor".
5476 vcpu->arch.dr6 &= ~15;
5477 vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
5478 kvm_queue_exception(vcpu, DB_VECTOR);
5482 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
5484 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
5485 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
5486 struct kvm_run *kvm_run = vcpu->run;
5487 unsigned long eip = kvm_get_linear_rip(vcpu);
5488 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5489 vcpu->arch.guest_debug_dr7,
5493 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
5494 kvm_run->debug.arch.pc = eip;
5495 kvm_run->debug.arch.exception = DB_VECTOR;
5496 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5497 *r = EMULATE_USER_EXIT;
5502 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
5503 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
5504 unsigned long eip = kvm_get_linear_rip(vcpu);
5505 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5510 vcpu->arch.dr6 &= ~15;
5511 vcpu->arch.dr6 |= dr6 | DR6_RTM;
5512 kvm_queue_exception(vcpu, DB_VECTOR);
5521 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
5528 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5529 bool writeback = true;
5530 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
5533 * Clear write_fault_to_shadow_pgtable here to ensure it is
5536 vcpu->arch.write_fault_to_shadow_pgtable = false;
5537 kvm_clear_exception_queue(vcpu);
5539 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
5540 init_emulate_ctxt(vcpu);
5543 * We will reenter on the same instruction since
5544 * we do not set complete_userspace_io. This does not
5545 * handle watchpoints yet, those would be handled in
5548 if (!(emulation_type & EMULTYPE_SKIP) &&
5549 kvm_vcpu_check_breakpoint(vcpu, &r))
5552 ctxt->interruptibility = 0;
5553 ctxt->have_exception = false;
5554 ctxt->exception.vector = -1;
5555 ctxt->perm_ok = false;
5557 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
5559 r = x86_decode_insn(ctxt, insn, insn_len);
5561 trace_kvm_emulate_insn_start(vcpu);
5562 ++vcpu->stat.insn_emulation;
5563 if (r != EMULATION_OK) {
5564 if (emulation_type & EMULTYPE_TRAP_UD)
5565 return EMULATE_FAIL;
5566 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5568 return EMULATE_DONE;
5569 if (ctxt->have_exception) {
5571 * #UD should result in just EMULATION_FAILED, and trap-like
5572 * exception should not be encountered during decode.
5574 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
5575 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
5576 inject_emulated_exception(vcpu);
5577 return EMULATE_DONE;
5579 if (emulation_type & EMULTYPE_SKIP)
5580 return EMULATE_FAIL;
5581 return handle_emulation_failure(vcpu);
5585 if (emulation_type & EMULTYPE_SKIP) {
5586 kvm_rip_write(vcpu, ctxt->_eip);
5587 if (ctxt->eflags & X86_EFLAGS_RF)
5588 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
5589 return EMULATE_DONE;
5592 if (retry_instruction(ctxt, cr2, emulation_type))
5593 return EMULATE_DONE;
5595 /* this is needed for vmware backdoor interface to work since it
5596 changes registers values during IO operation */
5597 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
5598 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5599 emulator_invalidate_register_cache(ctxt);
5603 r = x86_emulate_insn(ctxt);
5605 if (r == EMULATION_INTERCEPTED)
5606 return EMULATE_DONE;
5608 if (r == EMULATION_FAILED) {
5609 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5611 return EMULATE_DONE;
5613 return handle_emulation_failure(vcpu);
5616 if (ctxt->have_exception) {
5618 if (inject_emulated_exception(vcpu))
5620 } else if (vcpu->arch.pio.count) {
5621 if (!vcpu->arch.pio.in) {
5622 /* FIXME: return into emulator if single-stepping. */
5623 vcpu->arch.pio.count = 0;
5626 vcpu->arch.complete_userspace_io = complete_emulated_pio;
5628 r = EMULATE_USER_EXIT;
5629 } else if (vcpu->mmio_needed) {
5630 if (!vcpu->mmio_is_write)
5632 r = EMULATE_USER_EXIT;
5633 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
5634 } else if (r == EMULATION_RESTART)
5640 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5641 toggle_interruptibility(vcpu, ctxt->interruptibility);
5642 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5643 if (!ctxt->have_exception ||
5644 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
5645 kvm_rip_write(vcpu, ctxt->eip);
5646 if (r == EMULATE_DONE && ctxt->tf)
5647 kvm_vcpu_do_singlestep(vcpu, &r);
5648 __kvm_set_rflags(vcpu, ctxt->eflags);
5652 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
5653 * do nothing, and it will be requested again as soon as
5654 * the shadow expires. But we still need to check here,
5655 * because POPF has no interrupt shadow.
5657 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
5658 kvm_make_request(KVM_REQ_EVENT, vcpu);
5660 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5664 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5666 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5668 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5669 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5670 size, port, &val, 1);
5671 /* do not return to emulator after return from userspace */
5672 vcpu->arch.pio.count = 0;
5675 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5677 static void tsc_bad(void *info)
5679 __this_cpu_write(cpu_tsc_khz, 0);
5682 static void tsc_khz_changed(void *data)
5684 struct cpufreq_freqs *freq = data;
5685 unsigned long khz = 0;
5689 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5690 khz = cpufreq_quick_get(raw_smp_processor_id());
5693 __this_cpu_write(cpu_tsc_khz, khz);
5696 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5699 struct cpufreq_freqs *freq = data;
5701 struct kvm_vcpu *vcpu;
5702 int i, send_ipi = 0;
5705 * We allow guests to temporarily run on slowing clocks,
5706 * provided we notify them after, or to run on accelerating
5707 * clocks, provided we notify them before. Thus time never
5710 * However, we have a problem. We can't atomically update
5711 * the frequency of a given CPU from this function; it is
5712 * merely a notifier, which can be called from any CPU.
5713 * Changing the TSC frequency at arbitrary points in time
5714 * requires a recomputation of local variables related to
5715 * the TSC for each VCPU. We must flag these local variables
5716 * to be updated and be sure the update takes place with the
5717 * new frequency before any guests proceed.
5719 * Unfortunately, the combination of hotplug CPU and frequency
5720 * change creates an intractable locking scenario; the order
5721 * of when these callouts happen is undefined with respect to
5722 * CPU hotplug, and they can race with each other. As such,
5723 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5724 * undefined; you can actually have a CPU frequency change take
5725 * place in between the computation of X and the setting of the
5726 * variable. To protect against this problem, all updates of
5727 * the per_cpu tsc_khz variable are done in an interrupt
5728 * protected IPI, and all callers wishing to update the value
5729 * must wait for a synchronous IPI to complete (which is trivial
5730 * if the caller is on the CPU already). This establishes the
5731 * necessary total order on variable updates.
5733 * Note that because a guest time update may take place
5734 * anytime after the setting of the VCPU's request bit, the
5735 * correct TSC value must be set before the request. However,
5736 * to ensure the update actually makes it to any guest which
5737 * starts running in hardware virtualization between the set
5738 * and the acquisition of the spinlock, we must also ping the
5739 * CPU after setting the request bit.
5743 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
5745 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
5748 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5750 spin_lock(&kvm_lock);
5751 list_for_each_entry(kvm, &vm_list, vm_list) {
5752 kvm_for_each_vcpu(i, vcpu, kvm) {
5753 if (vcpu->cpu != freq->cpu)
5755 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5756 if (vcpu->cpu != smp_processor_id())
5760 spin_unlock(&kvm_lock);
5762 if (freq->old < freq->new && send_ipi) {
5764 * We upscale the frequency. Must make the guest
5765 * doesn't see old kvmclock values while running with
5766 * the new frequency, otherwise we risk the guest sees
5767 * time go backwards.
5769 * In case we update the frequency for another cpu
5770 * (which might be in guest context) send an interrupt
5771 * to kick the cpu out of guest context. Next time
5772 * guest context is entered kvmclock will be updated,
5773 * so the guest will not see stale values.
5775 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5780 static struct notifier_block kvmclock_cpufreq_notifier_block = {
5781 .notifier_call = kvmclock_cpufreq_notifier
5784 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
5785 unsigned long action, void *hcpu)
5787 unsigned int cpu = (unsigned long)hcpu;
5791 case CPU_DOWN_FAILED:
5792 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5794 case CPU_DOWN_PREPARE:
5795 smp_call_function_single(cpu, tsc_bad, NULL, 1);
5801 static struct notifier_block kvmclock_cpu_notifier_block = {
5802 .notifier_call = kvmclock_cpu_notifier,
5803 .priority = -INT_MAX
5806 static void kvm_timer_init(void)
5810 max_tsc_khz = tsc_khz;
5812 cpu_notifier_register_begin();
5813 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5814 #ifdef CONFIG_CPU_FREQ
5815 struct cpufreq_policy policy;
5816 memset(&policy, 0, sizeof(policy));
5818 cpufreq_get_policy(&policy, cpu);
5819 if (policy.cpuinfo.max_freq)
5820 max_tsc_khz = policy.cpuinfo.max_freq;
5823 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
5824 CPUFREQ_TRANSITION_NOTIFIER);
5826 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
5827 for_each_online_cpu(cpu)
5828 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5830 __register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5831 cpu_notifier_register_done();
5835 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
5837 int kvm_is_in_guest(void)
5839 return __this_cpu_read(current_vcpu) != NULL;
5842 static int kvm_is_user_mode(void)
5846 if (__this_cpu_read(current_vcpu))
5847 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
5849 return user_mode != 0;
5852 static unsigned long kvm_get_guest_ip(void)
5854 unsigned long ip = 0;
5856 if (__this_cpu_read(current_vcpu))
5857 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
5862 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5863 .is_in_guest = kvm_is_in_guest,
5864 .is_user_mode = kvm_is_user_mode,
5865 .get_guest_ip = kvm_get_guest_ip,
5868 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
5870 __this_cpu_write(current_vcpu, vcpu);
5872 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
5874 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
5876 __this_cpu_write(current_vcpu, NULL);
5878 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
5880 static void kvm_set_mmio_spte_mask(void)
5883 int maxphyaddr = boot_cpu_data.x86_phys_bits;
5886 * Set the reserved bits and the present bit of an paging-structure
5887 * entry to generate page fault with PFER.RSV = 1.
5889 /* Mask the reserved physical address bits. */
5890 mask = rsvd_bits(maxphyaddr, 51);
5892 /* Bit 62 is always reserved for 32bit host. */
5893 mask |= 0x3ull << 62;
5895 /* Set the present bit. */
5899 * If reserved bit is not supported, clear the present bit to disable
5902 if (maxphyaddr == 52)
5905 kvm_mmu_set_mmio_spte_mask(mask);
5908 #ifdef CONFIG_X86_64
5909 static void pvclock_gtod_update_fn(struct work_struct *work)
5913 struct kvm_vcpu *vcpu;
5916 spin_lock(&kvm_lock);
5917 list_for_each_entry(kvm, &vm_list, vm_list)
5918 kvm_for_each_vcpu(i, vcpu, kvm)
5919 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
5920 atomic_set(&kvm_guest_has_master_clock, 0);
5921 spin_unlock(&kvm_lock);
5924 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
5927 * Notification about pvclock gtod data update.
5929 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
5932 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
5933 struct timekeeper *tk = priv;
5935 update_pvclock_gtod(tk);
5937 /* disable master clock if host does not trust, or does not
5938 * use, TSC clocksource
5940 if (gtod->clock.vclock_mode != VCLOCK_TSC &&
5941 atomic_read(&kvm_guest_has_master_clock) != 0)
5942 queue_work(system_long_wq, &pvclock_gtod_work);
5947 static struct notifier_block pvclock_gtod_notifier = {
5948 .notifier_call = pvclock_gtod_notify,
5952 int kvm_arch_init(void *opaque)
5955 struct kvm_x86_ops *ops = opaque;
5958 printk(KERN_ERR "kvm: already loaded the other module\n");
5963 if (!ops->cpu_has_kvm_support()) {
5964 printk(KERN_ERR "kvm: no hardware support\n");
5968 if (ops->disabled_by_bios()) {
5969 printk(KERN_ERR "kvm: disabled by bios\n");
5975 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
5977 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
5981 r = kvm_mmu_module_init();
5983 goto out_free_percpu;
5985 kvm_set_mmio_spte_mask();
5989 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
5990 PT_DIRTY_MASK, PT64_NX_MASK, 0);
5994 perf_register_guest_info_callbacks(&kvm_guest_cbs);
5997 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
6000 #ifdef CONFIG_X86_64
6001 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
6007 free_percpu(shared_msrs);
6012 void kvm_arch_exit(void)
6015 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
6017 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6018 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
6019 CPUFREQ_TRANSITION_NOTIFIER);
6020 unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
6021 #ifdef CONFIG_X86_64
6022 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
6023 cancel_work_sync(&pvclock_gtod_work);
6026 kvm_mmu_module_exit();
6027 free_percpu(shared_msrs);
6030 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
6032 ++vcpu->stat.halt_exits;
6033 if (lapic_in_kernel(vcpu)) {
6034 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
6037 vcpu->run->exit_reason = KVM_EXIT_HLT;
6041 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
6043 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
6045 kvm_x86_ops->skip_emulated_instruction(vcpu);
6046 return kvm_vcpu_halt(vcpu);
6048 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
6051 * kvm_pv_kick_cpu_op: Kick a vcpu.
6053 * @apicid - apicid of vcpu to be kicked.
6055 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
6057 struct kvm_lapic_irq lapic_irq;
6059 lapic_irq.shorthand = 0;
6060 lapic_irq.dest_mode = 0;
6061 lapic_irq.dest_id = apicid;
6062 lapic_irq.msi_redir_hint = false;
6064 lapic_irq.delivery_mode = APIC_DM_REMRD;
6065 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
6068 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
6070 unsigned long nr, a0, a1, a2, a3, ret;
6071 int op_64_bit, r = 1;
6073 kvm_x86_ops->skip_emulated_instruction(vcpu);
6075 if (kvm_hv_hypercall_enabled(vcpu->kvm))
6076 return kvm_hv_hypercall(vcpu);
6078 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
6079 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
6080 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
6081 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
6082 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
6084 trace_kvm_hypercall(nr, a0, a1, a2, a3);
6086 op_64_bit = is_64_bit_mode(vcpu);
6095 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
6101 case KVM_HC_VAPIC_POLL_IRQ:
6104 case KVM_HC_KICK_CPU:
6105 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
6115 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
6116 ++vcpu->stat.hypercalls;
6119 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
6121 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
6123 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6124 char instruction[3];
6125 unsigned long rip = kvm_rip_read(vcpu);
6127 kvm_x86_ops->patch_hypercall(vcpu, instruction);
6129 return emulator_write_emulated(ctxt, rip, instruction, 3,
6133 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
6135 return vcpu->run->request_interrupt_window &&
6136 likely(!pic_in_kernel(vcpu->kvm));
6139 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
6141 struct kvm_run *kvm_run = vcpu->run;
6143 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
6144 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
6145 kvm_run->cr8 = kvm_get_cr8(vcpu);
6146 kvm_run->apic_base = kvm_get_apic_base(vcpu);
6147 kvm_run->ready_for_interrupt_injection =
6148 pic_in_kernel(vcpu->kvm) ||
6149 kvm_vcpu_ready_for_interrupt_injection(vcpu);
6152 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
6156 if (!kvm_x86_ops->update_cr8_intercept)
6159 if (!vcpu->arch.apic)
6162 if (!vcpu->arch.apic->vapic_addr)
6163 max_irr = kvm_lapic_find_highest_irr(vcpu);
6170 tpr = kvm_lapic_get_cr8(vcpu);
6172 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
6175 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
6179 /* try to reinject previous events if any */
6180 if (vcpu->arch.exception.pending) {
6181 trace_kvm_inj_exception(vcpu->arch.exception.nr,
6182 vcpu->arch.exception.has_error_code,
6183 vcpu->arch.exception.error_code);
6185 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
6186 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
6189 if (vcpu->arch.exception.nr == DB_VECTOR &&
6190 (vcpu->arch.dr7 & DR7_GD)) {
6191 vcpu->arch.dr7 &= ~DR7_GD;
6192 kvm_update_dr7(vcpu);
6195 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
6196 vcpu->arch.exception.has_error_code,
6197 vcpu->arch.exception.error_code,
6198 vcpu->arch.exception.reinject);
6202 if (vcpu->arch.nmi_injected) {
6203 kvm_x86_ops->set_nmi(vcpu);
6207 if (vcpu->arch.interrupt.pending) {
6208 kvm_x86_ops->set_irq(vcpu);
6212 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6213 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6218 /* try to inject new event if pending */
6219 if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
6220 --vcpu->arch.nmi_pending;
6221 vcpu->arch.nmi_injected = true;
6222 kvm_x86_ops->set_nmi(vcpu);
6223 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
6225 * Because interrupts can be injected asynchronously, we are
6226 * calling check_nested_events again here to avoid a race condition.
6227 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
6228 * proposal and current concerns. Perhaps we should be setting
6229 * KVM_REQ_EVENT only on certain events and not unconditionally?
6231 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6232 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6236 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
6237 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
6239 kvm_x86_ops->set_irq(vcpu);
6245 static void process_nmi(struct kvm_vcpu *vcpu)
6250 * x86 is limited to one NMI running, and one NMI pending after it.
6251 * If an NMI is already in progress, limit further NMIs to just one.
6252 * Otherwise, allow two (and we'll inject the first one immediately).
6254 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
6257 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
6258 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
6259 kvm_make_request(KVM_REQ_EVENT, vcpu);
6262 #define put_smstate(type, buf, offset, val) \
6263 *(type *)((buf) + (offset) - 0x7e00) = val
6265 static u32 process_smi_get_segment_flags(struct kvm_segment *seg)
6268 flags |= seg->g << 23;
6269 flags |= seg->db << 22;
6270 flags |= seg->l << 21;
6271 flags |= seg->avl << 20;
6272 flags |= seg->present << 15;
6273 flags |= seg->dpl << 13;
6274 flags |= seg->s << 12;
6275 flags |= seg->type << 8;
6279 static void process_smi_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
6281 struct kvm_segment seg;
6284 kvm_get_segment(vcpu, &seg, n);
6285 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
6288 offset = 0x7f84 + n * 12;
6290 offset = 0x7f2c + (n - 3) * 12;
6292 put_smstate(u32, buf, offset + 8, seg.base);
6293 put_smstate(u32, buf, offset + 4, seg.limit);
6294 put_smstate(u32, buf, offset, process_smi_get_segment_flags(&seg));
6297 #ifdef CONFIG_X86_64
6298 static void process_smi_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
6300 struct kvm_segment seg;
6304 kvm_get_segment(vcpu, &seg, n);
6305 offset = 0x7e00 + n * 16;
6307 flags = process_smi_get_segment_flags(&seg) >> 8;
6308 put_smstate(u16, buf, offset, seg.selector);
6309 put_smstate(u16, buf, offset + 2, flags);
6310 put_smstate(u32, buf, offset + 4, seg.limit);
6311 put_smstate(u64, buf, offset + 8, seg.base);
6315 static void process_smi_save_state_32(struct kvm_vcpu *vcpu, char *buf)
6318 struct kvm_segment seg;
6322 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
6323 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
6324 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
6325 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
6327 for (i = 0; i < 8; i++)
6328 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
6330 kvm_get_dr(vcpu, 6, &val);
6331 put_smstate(u32, buf, 0x7fcc, (u32)val);
6332 kvm_get_dr(vcpu, 7, &val);
6333 put_smstate(u32, buf, 0x7fc8, (u32)val);
6335 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6336 put_smstate(u32, buf, 0x7fc4, seg.selector);
6337 put_smstate(u32, buf, 0x7f64, seg.base);
6338 put_smstate(u32, buf, 0x7f60, seg.limit);
6339 put_smstate(u32, buf, 0x7f5c, process_smi_get_segment_flags(&seg));
6341 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6342 put_smstate(u32, buf, 0x7fc0, seg.selector);
6343 put_smstate(u32, buf, 0x7f80, seg.base);
6344 put_smstate(u32, buf, 0x7f7c, seg.limit);
6345 put_smstate(u32, buf, 0x7f78, process_smi_get_segment_flags(&seg));
6347 kvm_x86_ops->get_gdt(vcpu, &dt);
6348 put_smstate(u32, buf, 0x7f74, dt.address);
6349 put_smstate(u32, buf, 0x7f70, dt.size);
6351 kvm_x86_ops->get_idt(vcpu, &dt);
6352 put_smstate(u32, buf, 0x7f58, dt.address);
6353 put_smstate(u32, buf, 0x7f54, dt.size);
6355 for (i = 0; i < 6; i++)
6356 process_smi_save_seg_32(vcpu, buf, i);
6358 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
6361 put_smstate(u32, buf, 0x7efc, 0x00020000);
6362 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
6365 static void process_smi_save_state_64(struct kvm_vcpu *vcpu, char *buf)
6367 #ifdef CONFIG_X86_64
6369 struct kvm_segment seg;
6373 for (i = 0; i < 16; i++)
6374 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
6376 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
6377 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
6379 kvm_get_dr(vcpu, 6, &val);
6380 put_smstate(u64, buf, 0x7f68, val);
6381 kvm_get_dr(vcpu, 7, &val);
6382 put_smstate(u64, buf, 0x7f60, val);
6384 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
6385 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
6386 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
6388 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
6391 put_smstate(u32, buf, 0x7efc, 0x00020064);
6393 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
6395 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6396 put_smstate(u16, buf, 0x7e90, seg.selector);
6397 put_smstate(u16, buf, 0x7e92, process_smi_get_segment_flags(&seg) >> 8);
6398 put_smstate(u32, buf, 0x7e94, seg.limit);
6399 put_smstate(u64, buf, 0x7e98, seg.base);
6401 kvm_x86_ops->get_idt(vcpu, &dt);
6402 put_smstate(u32, buf, 0x7e84, dt.size);
6403 put_smstate(u64, buf, 0x7e88, dt.address);
6405 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6406 put_smstate(u16, buf, 0x7e70, seg.selector);
6407 put_smstate(u16, buf, 0x7e72, process_smi_get_segment_flags(&seg) >> 8);
6408 put_smstate(u32, buf, 0x7e74, seg.limit);
6409 put_smstate(u64, buf, 0x7e78, seg.base);
6411 kvm_x86_ops->get_gdt(vcpu, &dt);
6412 put_smstate(u32, buf, 0x7e64, dt.size);
6413 put_smstate(u64, buf, 0x7e68, dt.address);
6415 for (i = 0; i < 6; i++)
6416 process_smi_save_seg_64(vcpu, buf, i);
6422 static void process_smi(struct kvm_vcpu *vcpu)
6424 struct kvm_segment cs, ds;
6430 vcpu->arch.smi_pending = true;
6434 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
6435 vcpu->arch.hflags |= HF_SMM_MASK;
6436 memset(buf, 0, 512);
6437 if (guest_cpuid_has_longmode(vcpu))
6438 process_smi_save_state_64(vcpu, buf);
6440 process_smi_save_state_32(vcpu, buf);
6442 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
6444 if (kvm_x86_ops->get_nmi_mask(vcpu))
6445 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
6447 kvm_x86_ops->set_nmi_mask(vcpu, true);
6449 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6450 kvm_rip_write(vcpu, 0x8000);
6452 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
6453 kvm_x86_ops->set_cr0(vcpu, cr0);
6454 vcpu->arch.cr0 = cr0;
6456 kvm_x86_ops->set_cr4(vcpu, 0);
6458 /* Undocumented: IDT limit is set to zero on entry to SMM. */
6459 dt.address = dt.size = 0;
6460 kvm_x86_ops->set_idt(vcpu, &dt);
6462 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
6464 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
6465 cs.base = vcpu->arch.smbase;
6470 cs.limit = ds.limit = 0xffffffff;
6471 cs.type = ds.type = 0x3;
6472 cs.dpl = ds.dpl = 0;
6477 cs.avl = ds.avl = 0;
6478 cs.present = ds.present = 1;
6479 cs.unusable = ds.unusable = 0;
6480 cs.padding = ds.padding = 0;
6482 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
6483 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
6484 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
6485 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
6486 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
6487 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
6489 if (guest_cpuid_has_longmode(vcpu))
6490 kvm_x86_ops->set_efer(vcpu, 0);
6492 kvm_update_cpuid(vcpu);
6493 kvm_mmu_reset_context(vcpu);
6496 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
6498 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
6501 memset(vcpu->arch.eoi_exit_bitmap, 0, 256 / 8);
6503 if (irqchip_split(vcpu->kvm))
6504 kvm_scan_ioapic_routes(vcpu, vcpu->arch.eoi_exit_bitmap);
6506 kvm_x86_ops->sync_pir_to_irr(vcpu);
6507 if (ioapic_in_kernel(vcpu->kvm))
6508 kvm_ioapic_scan_entry(vcpu, vcpu->arch.eoi_exit_bitmap);
6510 kvm_x86_ops->load_eoi_exitmap(vcpu);
6513 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu)
6515 ++vcpu->stat.tlb_flush;
6516 kvm_x86_ops->tlb_flush(vcpu);
6519 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
6521 struct page *page = NULL;
6523 if (!lapic_in_kernel(vcpu))
6526 if (!kvm_x86_ops->set_apic_access_page_addr)
6529 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6530 if (is_error_page(page))
6532 kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
6535 * Do not pin apic access page in memory, the MMU notifier
6536 * will call us again if it is migrated or swapped out.
6540 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
6542 void kvm_arch_mmu_notifier_invalidate_page(struct kvm *kvm,
6543 unsigned long address)
6546 * The physical address of apic access page is stored in the VMCS.
6547 * Update it when it becomes invalid.
6549 if (address == gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT))
6550 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
6554 * Returns 1 to let vcpu_run() continue the guest execution loop without
6555 * exiting to the userspace. Otherwise, the value will be returned to the
6558 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
6562 dm_request_for_irq_injection(vcpu) &&
6563 kvm_cpu_accept_dm_intr(vcpu);
6565 bool req_immediate_exit = false;
6567 if (vcpu->requests) {
6568 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
6569 kvm_mmu_unload(vcpu);
6570 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
6571 __kvm_migrate_timers(vcpu);
6572 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
6573 kvm_gen_update_masterclock(vcpu->kvm);
6574 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
6575 kvm_gen_kvmclock_update(vcpu);
6576 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
6577 r = kvm_guest_time_update(vcpu);
6581 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
6582 kvm_mmu_sync_roots(vcpu);
6583 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
6584 kvm_vcpu_flush_tlb(vcpu);
6585 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
6586 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
6590 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
6591 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6592 vcpu->mmio_needed = 0;
6596 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
6597 vcpu->fpu_active = 0;
6598 kvm_x86_ops->fpu_deactivate(vcpu);
6600 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
6601 /* Page is swapped out. Do synthetic halt */
6602 vcpu->arch.apf.halted = true;
6606 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
6607 record_steal_time(vcpu);
6608 if (kvm_check_request(KVM_REQ_SMI, vcpu))
6610 if (kvm_check_request(KVM_REQ_NMI, vcpu))
6612 if (kvm_check_request(KVM_REQ_PMU, vcpu))
6613 kvm_pmu_handle_event(vcpu);
6614 if (kvm_check_request(KVM_REQ_PMI, vcpu))
6615 kvm_pmu_deliver_pmi(vcpu);
6616 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
6617 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
6618 if (test_bit(vcpu->arch.pending_ioapic_eoi,
6619 (void *) vcpu->arch.eoi_exit_bitmap)) {
6620 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
6621 vcpu->run->eoi.vector =
6622 vcpu->arch.pending_ioapic_eoi;
6627 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
6628 vcpu_scan_ioapic(vcpu);
6629 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
6630 kvm_vcpu_reload_apic_access_page(vcpu);
6631 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
6632 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6633 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
6637 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
6638 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6639 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
6646 * KVM_REQ_EVENT is not set when posted interrupts are set by
6647 * VT-d hardware, so we have to update RVI unconditionally.
6649 if (kvm_lapic_enabled(vcpu)) {
6651 * Update architecture specific hints for APIC
6652 * virtual interrupt delivery.
6654 if (kvm_x86_ops->hwapic_irr_update)
6655 kvm_x86_ops->hwapic_irr_update(vcpu,
6656 kvm_lapic_find_highest_irr(vcpu));
6659 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
6660 kvm_apic_accept_events(vcpu);
6661 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
6666 if (inject_pending_event(vcpu, req_int_win) != 0)
6667 req_immediate_exit = true;
6668 /* enable NMI/IRQ window open exits if needed */
6670 if (vcpu->arch.nmi_pending)
6671 kvm_x86_ops->enable_nmi_window(vcpu);
6672 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
6673 kvm_x86_ops->enable_irq_window(vcpu);
6676 if (kvm_lapic_enabled(vcpu)) {
6677 update_cr8_intercept(vcpu);
6678 kvm_lapic_sync_to_vapic(vcpu);
6682 r = kvm_mmu_reload(vcpu);
6684 goto cancel_injection;
6689 kvm_x86_ops->prepare_guest_switch(vcpu);
6690 if (vcpu->fpu_active)
6691 kvm_load_guest_fpu(vcpu);
6692 vcpu->mode = IN_GUEST_MODE;
6694 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6696 /* We should set ->mode before check ->requests,
6697 * see the comment in make_all_cpus_request.
6699 smp_mb__after_srcu_read_unlock();
6701 local_irq_disable();
6703 if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
6704 || need_resched() || signal_pending(current)) {
6705 vcpu->mode = OUTSIDE_GUEST_MODE;
6709 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6711 goto cancel_injection;
6714 kvm_load_guest_xcr0(vcpu);
6716 if (req_immediate_exit)
6717 smp_send_reschedule(vcpu->cpu);
6719 trace_kvm_entry(vcpu->vcpu_id);
6720 wait_lapic_expire(vcpu);
6721 __kvm_guest_enter();
6723 if (unlikely(vcpu->arch.switch_db_regs)) {
6725 set_debugreg(vcpu->arch.eff_db[0], 0);
6726 set_debugreg(vcpu->arch.eff_db[1], 1);
6727 set_debugreg(vcpu->arch.eff_db[2], 2);
6728 set_debugreg(vcpu->arch.eff_db[3], 3);
6729 set_debugreg(vcpu->arch.dr6, 6);
6730 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6731 } else if (unlikely(hw_breakpoint_active())) {
6735 kvm_x86_ops->run(vcpu);
6738 * Do this here before restoring debug registers on the host. And
6739 * since we do this before handling the vmexit, a DR access vmexit
6740 * can (a) read the correct value of the debug registers, (b) set
6741 * KVM_DEBUGREG_WONT_EXIT again.
6743 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
6744 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
6745 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
6746 kvm_update_dr0123(vcpu);
6747 kvm_update_dr6(vcpu);
6748 kvm_update_dr7(vcpu);
6749 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6753 * If the guest has used debug registers, at least dr7
6754 * will be disabled while returning to the host.
6755 * If we don't have active breakpoints in the host, we don't
6756 * care about the messed up debug address registers. But if
6757 * we have some of them active, restore the old state.
6759 if (hw_breakpoint_active())
6760 hw_breakpoint_restore();
6762 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
6764 vcpu->mode = OUTSIDE_GUEST_MODE;
6767 kvm_put_guest_xcr0(vcpu);
6769 /* Interrupt is enabled by handle_external_intr() */
6770 kvm_x86_ops->handle_external_intr(vcpu);
6775 * We must have an instruction between local_irq_enable() and
6776 * kvm_guest_exit(), so the timer interrupt isn't delayed by
6777 * the interrupt shadow. The stat.exits increment will do nicely.
6778 * But we need to prevent reordering, hence this barrier():
6786 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6789 * Profile KVM exit RIPs:
6791 if (unlikely(prof_on == KVM_PROFILING)) {
6792 unsigned long rip = kvm_rip_read(vcpu);
6793 profile_hit(KVM_PROFILING, (void *)rip);
6796 if (unlikely(vcpu->arch.tsc_always_catchup))
6797 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6799 if (vcpu->arch.apic_attention)
6800 kvm_lapic_sync_from_vapic(vcpu);
6802 r = kvm_x86_ops->handle_exit(vcpu);
6806 kvm_x86_ops->cancel_injection(vcpu);
6807 if (unlikely(vcpu->arch.apic_attention))
6808 kvm_lapic_sync_from_vapic(vcpu);
6813 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
6815 if (!kvm_arch_vcpu_runnable(vcpu) &&
6816 (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
6817 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6818 kvm_vcpu_block(vcpu);
6819 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6821 if (kvm_x86_ops->post_block)
6822 kvm_x86_ops->post_block(vcpu);
6824 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
6828 kvm_apic_accept_events(vcpu);
6829 switch(vcpu->arch.mp_state) {
6830 case KVM_MP_STATE_HALTED:
6831 vcpu->arch.pv.pv_unhalted = false;
6832 vcpu->arch.mp_state =
6833 KVM_MP_STATE_RUNNABLE;
6834 case KVM_MP_STATE_RUNNABLE:
6835 vcpu->arch.apf.halted = false;
6837 case KVM_MP_STATE_INIT_RECEIVED:
6846 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
6848 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6849 !vcpu->arch.apf.halted);
6852 static int vcpu_run(struct kvm_vcpu *vcpu)
6855 struct kvm *kvm = vcpu->kvm;
6857 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6860 if (kvm_vcpu_running(vcpu)) {
6861 r = vcpu_enter_guest(vcpu);
6863 r = vcpu_block(kvm, vcpu);
6869 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
6870 if (kvm_cpu_has_pending_timer(vcpu))
6871 kvm_inject_pending_timer_irqs(vcpu);
6873 if (dm_request_for_irq_injection(vcpu) &&
6874 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
6876 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
6877 ++vcpu->stat.request_irq_exits;
6881 kvm_check_async_pf_completion(vcpu);
6883 if (signal_pending(current)) {
6885 vcpu->run->exit_reason = KVM_EXIT_INTR;
6886 ++vcpu->stat.signal_exits;
6889 if (need_resched()) {
6890 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6892 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6896 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6901 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
6904 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6905 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
6906 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6907 if (r != EMULATE_DONE)
6912 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
6914 BUG_ON(!vcpu->arch.pio.count);
6916 return complete_emulated_io(vcpu);
6920 * Implements the following, as a state machine:
6924 * for each mmio piece in the fragment
6932 * for each mmio piece in the fragment
6937 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
6939 struct kvm_run *run = vcpu->run;
6940 struct kvm_mmio_fragment *frag;
6943 BUG_ON(!vcpu->mmio_needed);
6945 /* Complete previous fragment */
6946 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
6947 len = min(8u, frag->len);
6948 if (!vcpu->mmio_is_write)
6949 memcpy(frag->data, run->mmio.data, len);
6951 if (frag->len <= 8) {
6952 /* Switch to the next fragment. */
6954 vcpu->mmio_cur_fragment++;
6956 /* Go forward to the next mmio piece. */
6962 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
6963 vcpu->mmio_needed = 0;
6965 /* FIXME: return into emulator if single-stepping. */
6966 if (vcpu->mmio_is_write)
6968 vcpu->mmio_read_completed = 1;
6969 return complete_emulated_io(vcpu);
6972 run->exit_reason = KVM_EXIT_MMIO;
6973 run->mmio.phys_addr = frag->gpa;
6974 if (vcpu->mmio_is_write)
6975 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
6976 run->mmio.len = min(8u, frag->len);
6977 run->mmio.is_write = vcpu->mmio_is_write;
6978 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6983 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
6985 struct fpu *fpu = ¤t->thread.fpu;
6989 fpu__activate_curr(fpu);
6991 if (vcpu->sigset_active)
6992 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
6994 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
6995 kvm_vcpu_block(vcpu);
6996 kvm_apic_accept_events(vcpu);
6997 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
7002 /* re-sync apic's tpr */
7003 if (!lapic_in_kernel(vcpu)) {
7004 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
7010 if (unlikely(vcpu->arch.complete_userspace_io)) {
7011 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
7012 vcpu->arch.complete_userspace_io = NULL;
7017 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
7022 post_kvm_run_save(vcpu);
7023 if (vcpu->sigset_active)
7024 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
7029 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7031 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
7033 * We are here if userspace calls get_regs() in the middle of
7034 * instruction emulation. Registers state needs to be copied
7035 * back from emulation context to vcpu. Userspace shouldn't do
7036 * that usually, but some bad designed PV devices (vmware
7037 * backdoor interface) need this to work
7039 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
7040 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7042 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
7043 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
7044 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
7045 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
7046 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
7047 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
7048 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
7049 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
7050 #ifdef CONFIG_X86_64
7051 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
7052 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
7053 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
7054 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
7055 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
7056 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
7057 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
7058 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
7061 regs->rip = kvm_rip_read(vcpu);
7062 regs->rflags = kvm_get_rflags(vcpu);
7067 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7069 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
7070 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7072 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
7073 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
7074 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
7075 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
7076 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
7077 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
7078 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
7079 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
7080 #ifdef CONFIG_X86_64
7081 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
7082 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
7083 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
7084 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
7085 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
7086 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
7087 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
7088 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
7091 kvm_rip_write(vcpu, regs->rip);
7092 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
7094 vcpu->arch.exception.pending = false;
7096 kvm_make_request(KVM_REQ_EVENT, vcpu);
7101 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
7103 struct kvm_segment cs;
7105 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7109 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
7111 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
7112 struct kvm_sregs *sregs)
7116 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7117 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7118 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7119 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7120 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7121 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7123 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7124 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7126 kvm_x86_ops->get_idt(vcpu, &dt);
7127 sregs->idt.limit = dt.size;
7128 sregs->idt.base = dt.address;
7129 kvm_x86_ops->get_gdt(vcpu, &dt);
7130 sregs->gdt.limit = dt.size;
7131 sregs->gdt.base = dt.address;
7133 sregs->cr0 = kvm_read_cr0(vcpu);
7134 sregs->cr2 = vcpu->arch.cr2;
7135 sregs->cr3 = kvm_read_cr3(vcpu);
7136 sregs->cr4 = kvm_read_cr4(vcpu);
7137 sregs->cr8 = kvm_get_cr8(vcpu);
7138 sregs->efer = vcpu->arch.efer;
7139 sregs->apic_base = kvm_get_apic_base(vcpu);
7141 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
7143 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
7144 set_bit(vcpu->arch.interrupt.nr,
7145 (unsigned long *)sregs->interrupt_bitmap);
7150 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
7151 struct kvm_mp_state *mp_state)
7153 kvm_apic_accept_events(vcpu);
7154 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
7155 vcpu->arch.pv.pv_unhalted)
7156 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
7158 mp_state->mp_state = vcpu->arch.mp_state;
7163 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
7164 struct kvm_mp_state *mp_state)
7166 if (!kvm_vcpu_has_lapic(vcpu) &&
7167 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
7170 /* INITs are latched while in SMM */
7171 if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
7172 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
7173 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
7176 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
7177 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
7178 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
7180 vcpu->arch.mp_state = mp_state->mp_state;
7181 kvm_make_request(KVM_REQ_EVENT, vcpu);
7185 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
7186 int reason, bool has_error_code, u32 error_code)
7188 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
7191 init_emulate_ctxt(vcpu);
7193 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
7194 has_error_code, error_code);
7197 return EMULATE_FAIL;
7199 kvm_rip_write(vcpu, ctxt->eip);
7200 kvm_set_rflags(vcpu, ctxt->eflags);
7201 kvm_make_request(KVM_REQ_EVENT, vcpu);
7202 return EMULATE_DONE;
7204 EXPORT_SYMBOL_GPL(kvm_task_switch);
7206 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
7207 struct kvm_sregs *sregs)
7209 struct msr_data apic_base_msr;
7210 int mmu_reset_needed = 0;
7211 int pending_vec, max_bits, idx;
7214 if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
7217 dt.size = sregs->idt.limit;
7218 dt.address = sregs->idt.base;
7219 kvm_x86_ops->set_idt(vcpu, &dt);
7220 dt.size = sregs->gdt.limit;
7221 dt.address = sregs->gdt.base;
7222 kvm_x86_ops->set_gdt(vcpu, &dt);
7224 vcpu->arch.cr2 = sregs->cr2;
7225 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
7226 vcpu->arch.cr3 = sregs->cr3;
7227 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
7229 kvm_set_cr8(vcpu, sregs->cr8);
7231 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
7232 kvm_x86_ops->set_efer(vcpu, sregs->efer);
7233 apic_base_msr.data = sregs->apic_base;
7234 apic_base_msr.host_initiated = true;
7235 kvm_set_apic_base(vcpu, &apic_base_msr);
7237 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
7238 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
7239 vcpu->arch.cr0 = sregs->cr0;
7241 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
7242 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
7243 if (sregs->cr4 & X86_CR4_OSXSAVE)
7244 kvm_update_cpuid(vcpu);
7246 idx = srcu_read_lock(&vcpu->kvm->srcu);
7247 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu)) {
7248 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
7249 mmu_reset_needed = 1;
7251 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7253 if (mmu_reset_needed)
7254 kvm_mmu_reset_context(vcpu);
7256 max_bits = KVM_NR_INTERRUPTS;
7257 pending_vec = find_first_bit(
7258 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
7259 if (pending_vec < max_bits) {
7260 kvm_queue_interrupt(vcpu, pending_vec, false);
7261 pr_debug("Set back pending irq %d\n", pending_vec);
7264 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7265 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7266 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7267 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7268 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7269 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7271 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7272 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7274 update_cr8_intercept(vcpu);
7276 /* Older userspace won't unhalt the vcpu on reset. */
7277 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
7278 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
7280 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7282 kvm_make_request(KVM_REQ_EVENT, vcpu);
7287 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
7288 struct kvm_guest_debug *dbg)
7290 unsigned long rflags;
7293 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
7295 if (vcpu->arch.exception.pending)
7297 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
7298 kvm_queue_exception(vcpu, DB_VECTOR);
7300 kvm_queue_exception(vcpu, BP_VECTOR);
7304 * Read rflags as long as potentially injected trace flags are still
7307 rflags = kvm_get_rflags(vcpu);
7309 vcpu->guest_debug = dbg->control;
7310 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
7311 vcpu->guest_debug = 0;
7313 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7314 for (i = 0; i < KVM_NR_DB_REGS; ++i)
7315 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
7316 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
7318 for (i = 0; i < KVM_NR_DB_REGS; i++)
7319 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
7321 kvm_update_dr7(vcpu);
7323 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7324 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
7325 get_segment_base(vcpu, VCPU_SREG_CS);
7328 * Trigger an rflags update that will inject or remove the trace
7331 kvm_set_rflags(vcpu, rflags);
7333 kvm_x86_ops->update_bp_intercept(vcpu);
7343 * Translate a guest virtual address to a guest physical address.
7345 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
7346 struct kvm_translation *tr)
7348 unsigned long vaddr = tr->linear_address;
7352 idx = srcu_read_lock(&vcpu->kvm->srcu);
7353 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
7354 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7355 tr->physical_address = gpa;
7356 tr->valid = gpa != UNMAPPED_GVA;
7363 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7365 struct fxregs_state *fxsave =
7366 &vcpu->arch.guest_fpu.state.fxsave;
7368 memcpy(fpu->fpr, fxsave->st_space, 128);
7369 fpu->fcw = fxsave->cwd;
7370 fpu->fsw = fxsave->swd;
7371 fpu->ftwx = fxsave->twd;
7372 fpu->last_opcode = fxsave->fop;
7373 fpu->last_ip = fxsave->rip;
7374 fpu->last_dp = fxsave->rdp;
7375 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
7380 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7382 struct fxregs_state *fxsave =
7383 &vcpu->arch.guest_fpu.state.fxsave;
7385 memcpy(fxsave->st_space, fpu->fpr, 128);
7386 fxsave->cwd = fpu->fcw;
7387 fxsave->swd = fpu->fsw;
7388 fxsave->twd = fpu->ftwx;
7389 fxsave->fop = fpu->last_opcode;
7390 fxsave->rip = fpu->last_ip;
7391 fxsave->rdp = fpu->last_dp;
7392 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
7397 static void fx_init(struct kvm_vcpu *vcpu)
7399 fpstate_init(&vcpu->arch.guest_fpu.state);
7401 vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
7402 host_xcr0 | XSTATE_COMPACTION_ENABLED;
7405 * Ensure guest xcr0 is valid for loading
7407 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
7409 vcpu->arch.cr0 |= X86_CR0_ET;
7412 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
7414 if (vcpu->guest_fpu_loaded)
7418 * Restore all possible states in the guest,
7419 * and assume host would use all available bits.
7420 * Guest xcr0 would be loaded later.
7422 vcpu->guest_fpu_loaded = 1;
7423 __kernel_fpu_begin();
7424 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state);
7428 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
7430 if (!vcpu->guest_fpu_loaded) {
7431 vcpu->fpu_counter = 0;
7435 vcpu->guest_fpu_loaded = 0;
7436 copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
7438 ++vcpu->stat.fpu_reload;
7442 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
7444 void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
7446 kvmclock_reset(vcpu);
7448 kvm_x86_ops->vcpu_free(vcpu);
7449 free_cpumask_var(wbinvd_dirty_mask);
7452 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
7455 struct kvm_vcpu *vcpu;
7457 if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
7458 printk_once(KERN_WARNING
7459 "kvm: SMP vm created on host with unstable TSC; "
7460 "guest TSC will not be reliable\n");
7462 vcpu = kvm_x86_ops->vcpu_create(kvm, id);
7467 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
7471 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
7472 kvm_vcpu_mtrr_init(vcpu);
7473 r = vcpu_load(vcpu);
7476 kvm_vcpu_reset(vcpu, false);
7477 kvm_mmu_setup(vcpu);
7482 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
7484 struct msr_data msr;
7485 struct kvm *kvm = vcpu->kvm;
7487 if (vcpu_load(vcpu))
7490 msr.index = MSR_IA32_TSC;
7491 msr.host_initiated = true;
7492 kvm_write_tsc(vcpu, &msr);
7495 if (!kvmclock_periodic_sync)
7498 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
7499 KVMCLOCK_SYNC_PERIOD);
7502 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
7505 vcpu->arch.apf.msr_val = 0;
7507 r = vcpu_load(vcpu);
7509 kvm_mmu_unload(vcpu);
7512 kvm_arch_vcpu_free(vcpu);
7515 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
7517 vcpu->arch.hflags = 0;
7519 atomic_set(&vcpu->arch.nmi_queued, 0);
7520 vcpu->arch.nmi_pending = 0;
7521 vcpu->arch.nmi_injected = false;
7522 kvm_clear_interrupt_queue(vcpu);
7523 kvm_clear_exception_queue(vcpu);
7525 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
7526 kvm_update_dr0123(vcpu);
7527 vcpu->arch.dr6 = DR6_INIT;
7528 kvm_update_dr6(vcpu);
7529 vcpu->arch.dr7 = DR7_FIXED_1;
7530 kvm_update_dr7(vcpu);
7534 kvm_make_request(KVM_REQ_EVENT, vcpu);
7535 vcpu->arch.apf.msr_val = 0;
7536 vcpu->arch.st.msr_val = 0;
7538 kvmclock_reset(vcpu);
7540 kvm_clear_async_pf_completion_queue(vcpu);
7541 kvm_async_pf_hash_reset(vcpu);
7542 vcpu->arch.apf.halted = false;
7545 kvm_pmu_reset(vcpu);
7546 vcpu->arch.smbase = 0x30000;
7549 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
7550 vcpu->arch.regs_avail = ~0;
7551 vcpu->arch.regs_dirty = ~0;
7553 kvm_x86_ops->vcpu_reset(vcpu, init_event);
7556 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
7558 struct kvm_segment cs;
7560 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7561 cs.selector = vector << 8;
7562 cs.base = vector << 12;
7563 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7564 kvm_rip_write(vcpu, 0);
7567 int kvm_arch_hardware_enable(void)
7570 struct kvm_vcpu *vcpu;
7575 bool stable, backwards_tsc = false;
7577 kvm_shared_msr_cpu_online();
7578 ret = kvm_x86_ops->hardware_enable();
7582 local_tsc = rdtsc();
7583 stable = !check_tsc_unstable();
7584 list_for_each_entry(kvm, &vm_list, vm_list) {
7585 kvm_for_each_vcpu(i, vcpu, kvm) {
7586 if (!stable && vcpu->cpu == smp_processor_id())
7587 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7588 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
7589 backwards_tsc = true;
7590 if (vcpu->arch.last_host_tsc > max_tsc)
7591 max_tsc = vcpu->arch.last_host_tsc;
7597 * Sometimes, even reliable TSCs go backwards. This happens on
7598 * platforms that reset TSC during suspend or hibernate actions, but
7599 * maintain synchronization. We must compensate. Fortunately, we can
7600 * detect that condition here, which happens early in CPU bringup,
7601 * before any KVM threads can be running. Unfortunately, we can't
7602 * bring the TSCs fully up to date with real time, as we aren't yet far
7603 * enough into CPU bringup that we know how much real time has actually
7604 * elapsed; our helper function, get_kernel_ns() will be using boot
7605 * variables that haven't been updated yet.
7607 * So we simply find the maximum observed TSC above, then record the
7608 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
7609 * the adjustment will be applied. Note that we accumulate
7610 * adjustments, in case multiple suspend cycles happen before some VCPU
7611 * gets a chance to run again. In the event that no KVM threads get a
7612 * chance to run, we will miss the entire elapsed period, as we'll have
7613 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
7614 * loose cycle time. This isn't too big a deal, since the loss will be
7615 * uniform across all VCPUs (not to mention the scenario is extremely
7616 * unlikely). It is possible that a second hibernate recovery happens
7617 * much faster than a first, causing the observed TSC here to be
7618 * smaller; this would require additional padding adjustment, which is
7619 * why we set last_host_tsc to the local tsc observed here.
7621 * N.B. - this code below runs only on platforms with reliable TSC,
7622 * as that is the only way backwards_tsc is set above. Also note
7623 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
7624 * have the same delta_cyc adjustment applied if backwards_tsc
7625 * is detected. Note further, this adjustment is only done once,
7626 * as we reset last_host_tsc on all VCPUs to stop this from being
7627 * called multiple times (one for each physical CPU bringup).
7629 * Platforms with unreliable TSCs don't have to deal with this, they
7630 * will be compensated by the logic in vcpu_load, which sets the TSC to
7631 * catchup mode. This will catchup all VCPUs to real time, but cannot
7632 * guarantee that they stay in perfect synchronization.
7634 if (backwards_tsc) {
7635 u64 delta_cyc = max_tsc - local_tsc;
7636 backwards_tsc_observed = true;
7637 list_for_each_entry(kvm, &vm_list, vm_list) {
7638 kvm_for_each_vcpu(i, vcpu, kvm) {
7639 vcpu->arch.tsc_offset_adjustment += delta_cyc;
7640 vcpu->arch.last_host_tsc = local_tsc;
7641 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7645 * We have to disable TSC offset matching.. if you were
7646 * booting a VM while issuing an S4 host suspend....
7647 * you may have some problem. Solving this issue is
7648 * left as an exercise to the reader.
7650 kvm->arch.last_tsc_nsec = 0;
7651 kvm->arch.last_tsc_write = 0;
7658 void kvm_arch_hardware_disable(void)
7660 kvm_x86_ops->hardware_disable();
7661 drop_user_return_notifiers();
7664 int kvm_arch_hardware_setup(void)
7668 r = kvm_x86_ops->hardware_setup();
7672 if (kvm_has_tsc_control) {
7674 * Make sure the user can only configure tsc_khz values that
7675 * fit into a signed integer.
7676 * A min value is not calculated needed because it will always
7677 * be 1 on all machines.
7679 u64 max = min(0x7fffffffULL,
7680 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
7681 kvm_max_guest_tsc_khz = max;
7683 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
7686 kvm_init_msr_list();
7690 void kvm_arch_hardware_unsetup(void)
7692 kvm_x86_ops->hardware_unsetup();
7695 void kvm_arch_check_processor_compat(void *rtn)
7697 kvm_x86_ops->check_processor_compatibility(rtn);
7700 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
7702 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
7704 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
7706 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
7708 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
7711 bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
7713 return irqchip_in_kernel(vcpu->kvm) == lapic_in_kernel(vcpu);
7716 struct static_key kvm_no_apic_vcpu __read_mostly;
7718 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
7724 BUG_ON(vcpu->kvm == NULL);
7727 vcpu->arch.pv.pv_unhalted = false;
7728 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
7729 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_reset_bsp(vcpu))
7730 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7732 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
7734 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
7739 vcpu->arch.pio_data = page_address(page);
7741 kvm_set_tsc_khz(vcpu, max_tsc_khz);
7743 r = kvm_mmu_create(vcpu);
7745 goto fail_free_pio_data;
7747 if (irqchip_in_kernel(kvm)) {
7748 r = kvm_create_lapic(vcpu);
7750 goto fail_mmu_destroy;
7752 static_key_slow_inc(&kvm_no_apic_vcpu);
7754 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
7756 if (!vcpu->arch.mce_banks) {
7758 goto fail_free_lapic;
7760 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
7762 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
7764 goto fail_free_mce_banks;
7769 vcpu->arch.ia32_tsc_adjust_msr = 0x0;
7770 vcpu->arch.pv_time_enabled = false;
7772 vcpu->arch.guest_supported_xcr0 = 0;
7773 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
7775 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
7777 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
7779 kvm_async_pf_hash_reset(vcpu);
7782 vcpu->arch.pending_external_vector = -1;
7786 fail_free_mce_banks:
7787 kfree(vcpu->arch.mce_banks);
7789 kvm_free_lapic(vcpu);
7791 kvm_mmu_destroy(vcpu);
7793 free_page((unsigned long)vcpu->arch.pio_data);
7798 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
7802 kvm_pmu_destroy(vcpu);
7803 kfree(vcpu->arch.mce_banks);
7804 kvm_free_lapic(vcpu);
7805 idx = srcu_read_lock(&vcpu->kvm->srcu);
7806 kvm_mmu_destroy(vcpu);
7807 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7808 free_page((unsigned long)vcpu->arch.pio_data);
7809 if (!lapic_in_kernel(vcpu))
7810 static_key_slow_dec(&kvm_no_apic_vcpu);
7813 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
7815 kvm_x86_ops->sched_in(vcpu, cpu);
7818 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
7823 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
7824 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
7825 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
7826 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
7827 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
7829 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
7830 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
7831 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
7832 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
7833 &kvm->arch.irq_sources_bitmap);
7835 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
7836 mutex_init(&kvm->arch.apic_map_lock);
7837 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
7839 pvclock_update_vm_gtod_copy(kvm);
7841 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
7842 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
7847 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
7850 r = vcpu_load(vcpu);
7852 kvm_mmu_unload(vcpu);
7856 static void kvm_free_vcpus(struct kvm *kvm)
7859 struct kvm_vcpu *vcpu;
7862 * Unpin any mmu pages first.
7864 kvm_for_each_vcpu(i, vcpu, kvm) {
7865 kvm_clear_async_pf_completion_queue(vcpu);
7866 kvm_unload_vcpu_mmu(vcpu);
7868 kvm_for_each_vcpu(i, vcpu, kvm)
7869 kvm_arch_vcpu_free(vcpu);
7871 mutex_lock(&kvm->lock);
7872 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
7873 kvm->vcpus[i] = NULL;
7875 atomic_set(&kvm->online_vcpus, 0);
7876 mutex_unlock(&kvm->lock);
7879 void kvm_arch_sync_events(struct kvm *kvm)
7881 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
7882 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
7883 kvm_free_all_assigned_devices(kvm);
7887 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7891 struct kvm_memslots *slots = kvm_memslots(kvm);
7892 struct kvm_memory_slot *slot, old;
7894 /* Called with kvm->slots_lock held. */
7895 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
7898 slot = id_to_memslot(slots, id);
7904 * MAP_SHARED to prevent internal slot pages from being moved
7907 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
7908 MAP_SHARED | MAP_ANONYMOUS, 0);
7909 if (IS_ERR((void *)hva))
7910 return PTR_ERR((void *)hva);
7919 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
7920 struct kvm_userspace_memory_region m;
7922 m.slot = id | (i << 16);
7924 m.guest_phys_addr = gpa;
7925 m.userspace_addr = hva;
7926 m.memory_size = size;
7927 r = __kvm_set_memory_region(kvm, &m);
7933 r = vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
7939 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
7941 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7945 mutex_lock(&kvm->slots_lock);
7946 r = __x86_set_memory_region(kvm, id, gpa, size);
7947 mutex_unlock(&kvm->slots_lock);
7951 EXPORT_SYMBOL_GPL(x86_set_memory_region);
7953 void kvm_arch_destroy_vm(struct kvm *kvm)
7955 if (current->mm == kvm->mm) {
7957 * Free memory regions allocated on behalf of userspace,
7958 * unless the the memory map has changed due to process exit
7961 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
7962 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
7963 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
7965 kvm_iommu_unmap_guest(kvm);
7966 kfree(kvm->arch.vpic);
7967 kfree(kvm->arch.vioapic);
7968 kvm_free_vcpus(kvm);
7969 kfree(rcu_dereference_check(kvm->arch.apic_map, 1));
7972 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
7973 struct kvm_memory_slot *dont)
7977 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7978 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
7979 kvfree(free->arch.rmap[i]);
7980 free->arch.rmap[i] = NULL;
7985 if (!dont || free->arch.lpage_info[i - 1] !=
7986 dont->arch.lpage_info[i - 1]) {
7987 kvfree(free->arch.lpage_info[i - 1]);
7988 free->arch.lpage_info[i - 1] = NULL;
7993 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
7994 unsigned long npages)
7999 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
8000 * old arrays will be freed by __kvm_set_memory_region() if installing
8001 * the new memslot is successful.
8003 memset(&slot->arch, 0, sizeof(slot->arch));
8005 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8010 lpages = gfn_to_index(slot->base_gfn + npages - 1,
8011 slot->base_gfn, level) + 1;
8013 slot->arch.rmap[i] =
8014 kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
8015 if (!slot->arch.rmap[i])
8020 slot->arch.lpage_info[i - 1] = kvm_kvzalloc(lpages *
8021 sizeof(*slot->arch.lpage_info[i - 1]));
8022 if (!slot->arch.lpage_info[i - 1])
8025 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
8026 slot->arch.lpage_info[i - 1][0].write_count = 1;
8027 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
8028 slot->arch.lpage_info[i - 1][lpages - 1].write_count = 1;
8029 ugfn = slot->userspace_addr >> PAGE_SHIFT;
8031 * If the gfn and userspace address are not aligned wrt each
8032 * other, or if explicitly asked to, disable large page
8033 * support for this slot
8035 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
8036 !kvm_largepages_enabled()) {
8039 for (j = 0; j < lpages; ++j)
8040 slot->arch.lpage_info[i - 1][j].write_count = 1;
8047 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8048 kvfree(slot->arch.rmap[i]);
8049 slot->arch.rmap[i] = NULL;
8053 kvfree(slot->arch.lpage_info[i - 1]);
8054 slot->arch.lpage_info[i - 1] = NULL;
8059 void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
8062 * memslots->generation has been incremented.
8063 * mmio generation may have reached its maximum value.
8065 kvm_mmu_invalidate_mmio_sptes(kvm, slots);
8068 int kvm_arch_prepare_memory_region(struct kvm *kvm,
8069 struct kvm_memory_slot *memslot,
8070 const struct kvm_userspace_memory_region *mem,
8071 enum kvm_mr_change change)
8073 if (change == KVM_MR_MOVE)
8074 return kvm_arch_create_memslot(kvm, memslot,
8075 mem->memory_size >> PAGE_SHIFT);
8080 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
8081 struct kvm_memory_slot *new)
8083 /* Still write protect RO slot */
8084 if (new->flags & KVM_MEM_READONLY) {
8085 kvm_mmu_slot_remove_write_access(kvm, new);
8090 * Call kvm_x86_ops dirty logging hooks when they are valid.
8092 * kvm_x86_ops->slot_disable_log_dirty is called when:
8094 * - KVM_MR_CREATE with dirty logging is disabled
8095 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
8097 * The reason is, in case of PML, we need to set D-bit for any slots
8098 * with dirty logging disabled in order to eliminate unnecessary GPA
8099 * logging in PML buffer (and potential PML buffer full VMEXT). This
8100 * guarantees leaving PML enabled during guest's lifetime won't have
8101 * any additonal overhead from PML when guest is running with dirty
8102 * logging disabled for memory slots.
8104 * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
8105 * to dirty logging mode.
8107 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
8109 * In case of write protect:
8111 * Write protect all pages for dirty logging.
8113 * All the sptes including the large sptes which point to this
8114 * slot are set to readonly. We can not create any new large
8115 * spte on this slot until the end of the logging.
8117 * See the comments in fast_page_fault().
8119 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
8120 if (kvm_x86_ops->slot_enable_log_dirty)
8121 kvm_x86_ops->slot_enable_log_dirty(kvm, new);
8123 kvm_mmu_slot_remove_write_access(kvm, new);
8125 if (kvm_x86_ops->slot_disable_log_dirty)
8126 kvm_x86_ops->slot_disable_log_dirty(kvm, new);
8130 void kvm_arch_commit_memory_region(struct kvm *kvm,
8131 const struct kvm_userspace_memory_region *mem,
8132 const struct kvm_memory_slot *old,
8133 const struct kvm_memory_slot *new,
8134 enum kvm_mr_change change)
8136 int nr_mmu_pages = 0;
8138 if (!kvm->arch.n_requested_mmu_pages)
8139 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
8142 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
8145 * Dirty logging tracks sptes in 4k granularity, meaning that large
8146 * sptes have to be split. If live migration is successful, the guest
8147 * in the source machine will be destroyed and large sptes will be
8148 * created in the destination. However, if the guest continues to run
8149 * in the source machine (for example if live migration fails), small
8150 * sptes will remain around and cause bad performance.
8152 * Scan sptes if dirty logging has been stopped, dropping those
8153 * which can be collapsed into a single large-page spte. Later
8154 * page faults will create the large-page sptes.
8156 if ((change != KVM_MR_DELETE) &&
8157 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
8158 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
8159 kvm_mmu_zap_collapsible_sptes(kvm, new);
8162 * Set up write protection and/or dirty logging for the new slot.
8164 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
8165 * been zapped so no dirty logging staff is needed for old slot. For
8166 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
8167 * new and it's also covered when dealing with the new slot.
8169 * FIXME: const-ify all uses of struct kvm_memory_slot.
8171 if (change != KVM_MR_DELETE)
8172 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
8175 void kvm_arch_flush_shadow_all(struct kvm *kvm)
8177 kvm_mmu_invalidate_zap_all_pages(kvm);
8180 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
8181 struct kvm_memory_slot *slot)
8183 kvm_mmu_invalidate_zap_all_pages(kvm);
8186 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
8188 if (!list_empty_careful(&vcpu->async_pf.done))
8191 if (kvm_apic_has_events(vcpu))
8194 if (vcpu->arch.pv.pv_unhalted)
8197 if (atomic_read(&vcpu->arch.nmi_queued))
8200 if (test_bit(KVM_REQ_SMI, &vcpu->requests))
8203 if (kvm_arch_interrupt_allowed(vcpu) &&
8204 kvm_cpu_has_interrupt(vcpu))
8210 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
8212 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
8213 kvm_x86_ops->check_nested_events(vcpu, false);
8215 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
8218 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
8220 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
8223 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
8225 return kvm_x86_ops->interrupt_allowed(vcpu);
8228 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
8230 if (is_64_bit_mode(vcpu))
8231 return kvm_rip_read(vcpu);
8232 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
8233 kvm_rip_read(vcpu));
8235 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
8237 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
8239 return kvm_get_linear_rip(vcpu) == linear_rip;
8241 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
8243 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
8245 unsigned long rflags;
8247 rflags = kvm_x86_ops->get_rflags(vcpu);
8248 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8249 rflags &= ~X86_EFLAGS_TF;
8252 EXPORT_SYMBOL_GPL(kvm_get_rflags);
8254 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8256 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
8257 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
8258 rflags |= X86_EFLAGS_TF;
8259 kvm_x86_ops->set_rflags(vcpu, rflags);
8262 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8264 __kvm_set_rflags(vcpu, rflags);
8265 kvm_make_request(KVM_REQ_EVENT, vcpu);
8267 EXPORT_SYMBOL_GPL(kvm_set_rflags);
8269 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
8273 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
8277 r = kvm_mmu_reload(vcpu);
8281 if (!vcpu->arch.mmu.direct_map &&
8282 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
8285 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
8288 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
8290 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
8293 static inline u32 kvm_async_pf_next_probe(u32 key)
8295 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
8298 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8300 u32 key = kvm_async_pf_hash_fn(gfn);
8302 while (vcpu->arch.apf.gfns[key] != ~0)
8303 key = kvm_async_pf_next_probe(key);
8305 vcpu->arch.apf.gfns[key] = gfn;
8308 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
8311 u32 key = kvm_async_pf_hash_fn(gfn);
8313 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
8314 (vcpu->arch.apf.gfns[key] != gfn &&
8315 vcpu->arch.apf.gfns[key] != ~0); i++)
8316 key = kvm_async_pf_next_probe(key);
8321 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8323 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
8326 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8330 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
8332 vcpu->arch.apf.gfns[i] = ~0;
8334 j = kvm_async_pf_next_probe(j);
8335 if (vcpu->arch.apf.gfns[j] == ~0)
8337 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
8339 * k lies cyclically in ]i,j]
8341 * |....j i.k.| or |.k..j i...|
8343 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
8344 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
8349 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
8352 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
8356 static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
8359 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
8363 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
8364 struct kvm_async_pf *work)
8366 struct x86_exception fault;
8368 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
8369 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
8371 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
8372 (vcpu->arch.apf.send_user_only &&
8373 kvm_x86_ops->get_cpl(vcpu) == 0))
8374 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
8375 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
8376 fault.vector = PF_VECTOR;
8377 fault.error_code_valid = true;
8378 fault.error_code = 0;
8379 fault.nested_page_fault = false;
8380 fault.address = work->arch.token;
8381 kvm_inject_page_fault(vcpu, &fault);
8385 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
8386 struct kvm_async_pf *work)
8388 struct x86_exception fault;
8391 if (work->wakeup_all)
8392 work->arch.token = ~0; /* broadcast wakeup */
8394 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
8395 trace_kvm_async_pf_ready(work->arch.token, work->gva);
8397 if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
8398 !apf_get_user(vcpu, &val)) {
8399 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
8400 vcpu->arch.exception.pending &&
8401 vcpu->arch.exception.nr == PF_VECTOR &&
8402 !apf_put_user(vcpu, 0)) {
8403 vcpu->arch.exception.pending = false;
8404 vcpu->arch.exception.nr = 0;
8405 vcpu->arch.exception.has_error_code = false;
8406 vcpu->arch.exception.error_code = 0;
8407 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
8408 fault.vector = PF_VECTOR;
8409 fault.error_code_valid = true;
8410 fault.error_code = 0;
8411 fault.nested_page_fault = false;
8412 fault.address = work->arch.token;
8413 kvm_inject_page_fault(vcpu, &fault);
8416 vcpu->arch.apf.halted = false;
8417 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8420 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
8422 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
8425 return kvm_can_do_async_pf(vcpu);
8428 void kvm_arch_start_assignment(struct kvm *kvm)
8430 atomic_inc(&kvm->arch.assigned_device_count);
8432 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
8434 void kvm_arch_end_assignment(struct kvm *kvm)
8436 atomic_dec(&kvm->arch.assigned_device_count);
8438 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
8440 bool kvm_arch_has_assigned_device(struct kvm *kvm)
8442 return atomic_read(&kvm->arch.assigned_device_count);
8444 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
8446 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
8448 atomic_inc(&kvm->arch.noncoherent_dma_count);
8450 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
8452 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
8454 atomic_dec(&kvm->arch.noncoherent_dma_count);
8456 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
8458 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
8460 return atomic_read(&kvm->arch.noncoherent_dma_count);
8462 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
8464 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
8465 struct irq_bypass_producer *prod)
8467 struct kvm_kernel_irqfd *irqfd =
8468 container_of(cons, struct kvm_kernel_irqfd, consumer);
8470 if (kvm_x86_ops->update_pi_irte) {
8471 irqfd->producer = prod;
8472 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
8473 prod->irq, irqfd->gsi, 1);
8479 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
8480 struct irq_bypass_producer *prod)
8483 struct kvm_kernel_irqfd *irqfd =
8484 container_of(cons, struct kvm_kernel_irqfd, consumer);
8486 if (!kvm_x86_ops->update_pi_irte) {
8487 WARN_ON(irqfd->producer != NULL);
8491 WARN_ON(irqfd->producer != prod);
8492 irqfd->producer = NULL;
8495 * When producer of consumer is unregistered, we change back to
8496 * remapped mode, so we can re-use the current implementation
8497 * when the irq is masked/disabed or the consumer side (KVM
8498 * int this case doesn't want to receive the interrupts.
8500 ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
8502 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
8503 " fails: %d\n", irqfd->consumer.token, ret);
8506 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
8507 uint32_t guest_irq, bool set)
8509 if (!kvm_x86_ops->update_pi_irte)
8512 return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
8515 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
8516 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
8517 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
8518 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
8519 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
8520 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
8521 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
8522 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
8523 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
8524 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
8525 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
8526 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
8527 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
8528 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
8529 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
8530 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
8531 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);