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 + 0x3ff:
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);
2176 vcpu->arch.ia32_tsc_adjust_msr = data;
2179 case MSR_IA32_MISC_ENABLE:
2180 vcpu->arch.ia32_misc_enable_msr = data;
2182 case MSR_IA32_SMBASE:
2183 if (!msr_info->host_initiated)
2185 vcpu->arch.smbase = data;
2187 case MSR_KVM_WALL_CLOCK_NEW:
2188 case MSR_KVM_WALL_CLOCK:
2189 vcpu->kvm->arch.wall_clock = data;
2190 kvm_write_wall_clock(vcpu->kvm, data);
2192 case MSR_KVM_SYSTEM_TIME_NEW:
2193 case MSR_KVM_SYSTEM_TIME: {
2195 struct kvm_arch *ka = &vcpu->kvm->arch;
2197 kvmclock_reset(vcpu);
2199 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2200 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2202 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2203 set_bit(KVM_REQ_MASTERCLOCK_UPDATE,
2206 ka->boot_vcpu_runs_old_kvmclock = tmp;
2209 vcpu->arch.time = data;
2210 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2212 /* we verify if the enable bit is set... */
2216 gpa_offset = data & ~(PAGE_MASK | 1);
2218 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2219 &vcpu->arch.pv_time, data & ~1ULL,
2220 sizeof(struct pvclock_vcpu_time_info)))
2221 vcpu->arch.pv_time_enabled = false;
2223 vcpu->arch.pv_time_enabled = true;
2227 case MSR_KVM_ASYNC_PF_EN:
2228 if (kvm_pv_enable_async_pf(vcpu, data))
2231 case MSR_KVM_STEAL_TIME:
2233 if (unlikely(!sched_info_on()))
2236 if (data & KVM_STEAL_RESERVED_MASK)
2239 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2240 data & KVM_STEAL_VALID_BITS,
2241 sizeof(struct kvm_steal_time)))
2244 vcpu->arch.st.msr_val = data;
2246 if (!(data & KVM_MSR_ENABLED))
2249 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2252 case MSR_KVM_PV_EOI_EN:
2253 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2257 case MSR_IA32_MCG_CTL:
2258 case MSR_IA32_MCG_STATUS:
2259 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2260 return set_msr_mce(vcpu, msr, data);
2262 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2263 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2264 pr = true; /* fall through */
2265 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2266 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2267 if (kvm_pmu_is_valid_msr(vcpu, msr))
2268 return kvm_pmu_set_msr(vcpu, msr_info);
2270 if (pr || data != 0)
2271 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2272 "0x%x data 0x%llx\n", msr, data);
2274 case MSR_K7_CLK_CTL:
2276 * Ignore all writes to this no longer documented MSR.
2277 * Writes are only relevant for old K7 processors,
2278 * all pre-dating SVM, but a recommended workaround from
2279 * AMD for these chips. It is possible to specify the
2280 * affected processor models on the command line, hence
2281 * the need to ignore the workaround.
2284 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2285 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2286 case HV_X64_MSR_CRASH_CTL:
2287 return kvm_hv_set_msr_common(vcpu, msr, data,
2288 msr_info->host_initiated);
2289 case MSR_IA32_BBL_CR_CTL3:
2290 /* Drop writes to this legacy MSR -- see rdmsr
2291 * counterpart for further detail.
2293 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
2295 case MSR_AMD64_OSVW_ID_LENGTH:
2296 if (!guest_cpuid_has_osvw(vcpu))
2298 vcpu->arch.osvw.length = data;
2300 case MSR_AMD64_OSVW_STATUS:
2301 if (!guest_cpuid_has_osvw(vcpu))
2303 vcpu->arch.osvw.status = data;
2306 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2307 return xen_hvm_config(vcpu, data);
2308 if (kvm_pmu_is_valid_msr(vcpu, msr))
2309 return kvm_pmu_set_msr(vcpu, msr_info);
2311 vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
2315 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
2322 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2326 * Reads an msr value (of 'msr_index') into 'pdata'.
2327 * Returns 0 on success, non-0 otherwise.
2328 * Assumes vcpu_load() was already called.
2330 int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2332 return kvm_x86_ops->get_msr(vcpu, msr);
2334 EXPORT_SYMBOL_GPL(kvm_get_msr);
2336 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2339 u64 mcg_cap = vcpu->arch.mcg_cap;
2340 unsigned bank_num = mcg_cap & 0xff;
2343 case MSR_IA32_P5_MC_ADDR:
2344 case MSR_IA32_P5_MC_TYPE:
2347 case MSR_IA32_MCG_CAP:
2348 data = vcpu->arch.mcg_cap;
2350 case MSR_IA32_MCG_CTL:
2351 if (!(mcg_cap & MCG_CTL_P))
2353 data = vcpu->arch.mcg_ctl;
2355 case MSR_IA32_MCG_STATUS:
2356 data = vcpu->arch.mcg_status;
2359 if (msr >= MSR_IA32_MC0_CTL &&
2360 msr < MSR_IA32_MCx_CTL(bank_num)) {
2361 u32 offset = array_index_nospec(
2362 msr - MSR_IA32_MC0_CTL,
2363 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2365 data = vcpu->arch.mce_banks[offset];
2374 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2376 switch (msr_info->index) {
2377 case MSR_IA32_PLATFORM_ID:
2378 case MSR_IA32_EBL_CR_POWERON:
2379 case MSR_IA32_DEBUGCTLMSR:
2380 case MSR_IA32_LASTBRANCHFROMIP:
2381 case MSR_IA32_LASTBRANCHTOIP:
2382 case MSR_IA32_LASTINTFROMIP:
2383 case MSR_IA32_LASTINTTOIP:
2385 case MSR_K8_TSEG_ADDR:
2386 case MSR_K8_TSEG_MASK:
2388 case MSR_VM_HSAVE_PA:
2389 case MSR_K8_INT_PENDING_MSG:
2390 case MSR_AMD64_NB_CFG:
2391 case MSR_FAM10H_MMIO_CONF_BASE:
2392 case MSR_AMD64_BU_CFG2:
2395 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2396 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2397 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2398 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2399 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2400 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2403 case MSR_IA32_UCODE_REV:
2404 msr_info->data = 0x100000000ULL;
2406 case MSR_IA32_ARCH_CAPABILITIES:
2407 if (!msr_info->host_initiated &&
2408 !guest_cpuid_has_arch_capabilities(vcpu))
2410 msr_info->data = vcpu->arch.arch_capabilities;
2413 case 0x200 ... 0x2ff:
2414 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2415 case 0xcd: /* fsb frequency */
2419 * MSR_EBC_FREQUENCY_ID
2420 * Conservative value valid for even the basic CPU models.
2421 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2422 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2423 * and 266MHz for model 3, or 4. Set Core Clock
2424 * Frequency to System Bus Frequency Ratio to 1 (bits
2425 * 31:24) even though these are only valid for CPU
2426 * models > 2, however guests may end up dividing or
2427 * multiplying by zero otherwise.
2429 case MSR_EBC_FREQUENCY_ID:
2430 msr_info->data = 1 << 24;
2432 case MSR_IA32_APICBASE:
2433 msr_info->data = kvm_get_apic_base(vcpu);
2435 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2436 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2438 case MSR_IA32_TSCDEADLINE:
2439 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2441 case MSR_IA32_TSC_ADJUST:
2442 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2444 case MSR_IA32_MISC_ENABLE:
2445 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
2447 case MSR_IA32_SMBASE:
2448 if (!msr_info->host_initiated)
2450 msr_info->data = vcpu->arch.smbase;
2452 case MSR_IA32_PERF_STATUS:
2453 /* TSC increment by tick */
2454 msr_info->data = 1000ULL;
2455 /* CPU multiplier */
2456 msr_info->data |= (((uint64_t)4ULL) << 40);
2459 msr_info->data = vcpu->arch.efer;
2461 case MSR_KVM_WALL_CLOCK:
2462 case MSR_KVM_WALL_CLOCK_NEW:
2463 msr_info->data = vcpu->kvm->arch.wall_clock;
2465 case MSR_KVM_SYSTEM_TIME:
2466 case MSR_KVM_SYSTEM_TIME_NEW:
2467 msr_info->data = vcpu->arch.time;
2469 case MSR_KVM_ASYNC_PF_EN:
2470 msr_info->data = vcpu->arch.apf.msr_val;
2472 case MSR_KVM_STEAL_TIME:
2473 msr_info->data = vcpu->arch.st.msr_val;
2475 case MSR_KVM_PV_EOI_EN:
2476 msr_info->data = vcpu->arch.pv_eoi.msr_val;
2478 case MSR_IA32_P5_MC_ADDR:
2479 case MSR_IA32_P5_MC_TYPE:
2480 case MSR_IA32_MCG_CAP:
2481 case MSR_IA32_MCG_CTL:
2482 case MSR_IA32_MCG_STATUS:
2483 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2484 return get_msr_mce(vcpu, msr_info->index, &msr_info->data);
2485 case MSR_K7_CLK_CTL:
2487 * Provide expected ramp-up count for K7. All other
2488 * are set to zero, indicating minimum divisors for
2491 * This prevents guest kernels on AMD host with CPU
2492 * type 6, model 8 and higher from exploding due to
2493 * the rdmsr failing.
2495 msr_info->data = 0x20000000;
2497 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2498 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2499 case HV_X64_MSR_CRASH_CTL:
2500 return kvm_hv_get_msr_common(vcpu,
2501 msr_info->index, &msr_info->data);
2503 case MSR_IA32_BBL_CR_CTL3:
2504 /* This legacy MSR exists but isn't fully documented in current
2505 * silicon. It is however accessed by winxp in very narrow
2506 * scenarios where it sets bit #19, itself documented as
2507 * a "reserved" bit. Best effort attempt to source coherent
2508 * read data here should the balance of the register be
2509 * interpreted by the guest:
2511 * L2 cache control register 3: 64GB range, 256KB size,
2512 * enabled, latency 0x1, configured
2514 msr_info->data = 0xbe702111;
2516 case MSR_AMD64_OSVW_ID_LENGTH:
2517 if (!guest_cpuid_has_osvw(vcpu))
2519 msr_info->data = vcpu->arch.osvw.length;
2521 case MSR_AMD64_OSVW_STATUS:
2522 if (!guest_cpuid_has_osvw(vcpu))
2524 msr_info->data = vcpu->arch.osvw.status;
2527 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2528 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2530 vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr_info->index);
2533 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr_info->index);
2540 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2543 * Read or write a bunch of msrs. All parameters are kernel addresses.
2545 * @return number of msrs set successfully.
2547 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2548 struct kvm_msr_entry *entries,
2549 int (*do_msr)(struct kvm_vcpu *vcpu,
2550 unsigned index, u64 *data))
2554 idx = srcu_read_lock(&vcpu->kvm->srcu);
2555 for (i = 0; i < msrs->nmsrs; ++i)
2556 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2558 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2564 * Read or write a bunch of msrs. Parameters are user addresses.
2566 * @return number of msrs set successfully.
2568 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2569 int (*do_msr)(struct kvm_vcpu *vcpu,
2570 unsigned index, u64 *data),
2573 struct kvm_msrs msrs;
2574 struct kvm_msr_entry *entries;
2579 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2583 if (msrs.nmsrs >= MAX_IO_MSRS)
2586 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2587 entries = memdup_user(user_msrs->entries, size);
2588 if (IS_ERR(entries)) {
2589 r = PTR_ERR(entries);
2593 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2598 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2609 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2614 case KVM_CAP_IRQCHIP:
2616 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2617 case KVM_CAP_SET_TSS_ADDR:
2618 case KVM_CAP_EXT_CPUID:
2619 case KVM_CAP_EXT_EMUL_CPUID:
2620 case KVM_CAP_CLOCKSOURCE:
2622 case KVM_CAP_NOP_IO_DELAY:
2623 case KVM_CAP_MP_STATE:
2624 case KVM_CAP_SYNC_MMU:
2625 case KVM_CAP_USER_NMI:
2626 case KVM_CAP_REINJECT_CONTROL:
2627 case KVM_CAP_IRQ_INJECT_STATUS:
2628 case KVM_CAP_IOEVENTFD:
2629 case KVM_CAP_IOEVENTFD_NO_LENGTH:
2631 case KVM_CAP_PIT_STATE2:
2632 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2633 case KVM_CAP_XEN_HVM:
2634 case KVM_CAP_ADJUST_CLOCK:
2635 case KVM_CAP_VCPU_EVENTS:
2636 case KVM_CAP_HYPERV:
2637 case KVM_CAP_HYPERV_VAPIC:
2638 case KVM_CAP_HYPERV_SPIN:
2639 case KVM_CAP_PCI_SEGMENT:
2640 case KVM_CAP_DEBUGREGS:
2641 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2643 case KVM_CAP_ASYNC_PF:
2644 case KVM_CAP_GET_TSC_KHZ:
2645 case KVM_CAP_KVMCLOCK_CTRL:
2646 case KVM_CAP_READONLY_MEM:
2647 case KVM_CAP_HYPERV_TIME:
2648 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2649 case KVM_CAP_TSC_DEADLINE_TIMER:
2650 case KVM_CAP_ENABLE_CAP_VM:
2651 case KVM_CAP_DISABLE_QUIRKS:
2652 case KVM_CAP_SET_BOOT_CPU_ID:
2653 case KVM_CAP_SPLIT_IRQCHIP:
2654 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2655 case KVM_CAP_ASSIGN_DEV_IRQ:
2656 case KVM_CAP_PCI_2_3:
2660 case KVM_CAP_X86_SMM:
2661 /* SMBASE is usually relocated above 1M on modern chipsets,
2662 * and SMM handlers might indeed rely on 4G segment limits,
2663 * so do not report SMM to be available if real mode is
2664 * emulated via vm86 mode. Still, do not go to great lengths
2665 * to avoid userspace's usage of the feature, because it is a
2666 * fringe case that is not enabled except via specific settings
2667 * of the module parameters.
2669 r = kvm_x86_ops->has_emulated_msr(MSR_IA32_SMBASE);
2671 case KVM_CAP_COALESCED_MMIO:
2672 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2675 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2677 case KVM_CAP_NR_VCPUS:
2678 r = KVM_SOFT_MAX_VCPUS;
2680 case KVM_CAP_MAX_VCPUS:
2683 case KVM_CAP_NR_MEMSLOTS:
2684 r = KVM_USER_MEM_SLOTS;
2686 case KVM_CAP_PV_MMU: /* obsolete */
2689 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2691 r = iommu_present(&pci_bus_type);
2695 r = KVM_MAX_MCE_BANKS;
2700 case KVM_CAP_TSC_CONTROL:
2701 r = kvm_has_tsc_control;
2711 long kvm_arch_dev_ioctl(struct file *filp,
2712 unsigned int ioctl, unsigned long arg)
2714 void __user *argp = (void __user *)arg;
2718 case KVM_GET_MSR_INDEX_LIST: {
2719 struct kvm_msr_list __user *user_msr_list = argp;
2720 struct kvm_msr_list msr_list;
2724 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2727 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
2728 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2731 if (n < msr_list.nmsrs)
2734 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2735 num_msrs_to_save * sizeof(u32)))
2737 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2739 num_emulated_msrs * sizeof(u32)))
2744 case KVM_GET_SUPPORTED_CPUID:
2745 case KVM_GET_EMULATED_CPUID: {
2746 struct kvm_cpuid2 __user *cpuid_arg = argp;
2747 struct kvm_cpuid2 cpuid;
2750 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2753 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2759 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2764 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2767 mce_cap = KVM_MCE_CAP_SUPPORTED;
2769 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2781 static void wbinvd_ipi(void *garbage)
2786 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2788 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2791 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2793 /* Address WBINVD may be executed by guest */
2794 if (need_emulate_wbinvd(vcpu)) {
2795 if (kvm_x86_ops->has_wbinvd_exit())
2796 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2797 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2798 smp_call_function_single(vcpu->cpu,
2799 wbinvd_ipi, NULL, 1);
2802 kvm_x86_ops->vcpu_load(vcpu, cpu);
2804 /* Apply any externally detected TSC adjustments (due to suspend) */
2805 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2806 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2807 vcpu->arch.tsc_offset_adjustment = 0;
2808 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2811 if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2812 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2813 rdtsc() - vcpu->arch.last_host_tsc;
2815 mark_tsc_unstable("KVM discovered backwards TSC");
2816 if (check_tsc_unstable()) {
2817 u64 offset = kvm_compute_tsc_offset(vcpu,
2818 vcpu->arch.last_guest_tsc);
2819 kvm_x86_ops->write_tsc_offset(vcpu, offset);
2820 vcpu->arch.tsc_catchup = 1;
2823 * On a host with synchronized TSC, there is no need to update
2824 * kvmclock on vcpu->cpu migration
2826 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
2827 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2828 if (vcpu->cpu != cpu)
2829 kvm_migrate_timers(vcpu);
2833 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2836 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2838 kvm_x86_ops->vcpu_put(vcpu);
2839 kvm_put_guest_fpu(vcpu);
2840 vcpu->arch.last_host_tsc = rdtsc();
2842 * If userspace has set any breakpoints or watchpoints, dr6 is restored
2843 * on every vmexit, but if not, we might have a stale dr6 from the
2844 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
2849 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2850 struct kvm_lapic_state *s)
2852 kvm_x86_ops->sync_pir_to_irr(vcpu);
2853 memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2858 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2859 struct kvm_lapic_state *s)
2861 kvm_apic_post_state_restore(vcpu, s);
2862 update_cr8_intercept(vcpu);
2867 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
2869 return (!lapic_in_kernel(vcpu) ||
2870 kvm_apic_accept_pic_intr(vcpu));
2874 * if userspace requested an interrupt window, check that the
2875 * interrupt window is open.
2877 * No need to exit to userspace if we already have an interrupt queued.
2879 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
2881 return kvm_arch_interrupt_allowed(vcpu) &&
2882 !kvm_cpu_has_interrupt(vcpu) &&
2883 !kvm_event_needs_reinjection(vcpu) &&
2884 kvm_cpu_accept_dm_intr(vcpu);
2887 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2888 struct kvm_interrupt *irq)
2890 if (irq->irq >= KVM_NR_INTERRUPTS)
2893 if (!irqchip_in_kernel(vcpu->kvm)) {
2894 kvm_queue_interrupt(vcpu, irq->irq, false);
2895 kvm_make_request(KVM_REQ_EVENT, vcpu);
2900 * With in-kernel LAPIC, we only use this to inject EXTINT, so
2901 * fail for in-kernel 8259.
2903 if (pic_in_kernel(vcpu->kvm))
2906 if (vcpu->arch.pending_external_vector != -1)
2909 vcpu->arch.pending_external_vector = irq->irq;
2910 kvm_make_request(KVM_REQ_EVENT, vcpu);
2914 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2916 kvm_inject_nmi(vcpu);
2921 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
2923 kvm_make_request(KVM_REQ_SMI, vcpu);
2928 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2929 struct kvm_tpr_access_ctl *tac)
2933 vcpu->arch.tpr_access_reporting = !!tac->enabled;
2937 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2941 unsigned bank_num = mcg_cap & 0xff, bank;
2944 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2946 if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2949 vcpu->arch.mcg_cap = mcg_cap;
2950 /* Init IA32_MCG_CTL to all 1s */
2951 if (mcg_cap & MCG_CTL_P)
2952 vcpu->arch.mcg_ctl = ~(u64)0;
2953 /* Init IA32_MCi_CTL to all 1s */
2954 for (bank = 0; bank < bank_num; bank++)
2955 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2960 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2961 struct kvm_x86_mce *mce)
2963 u64 mcg_cap = vcpu->arch.mcg_cap;
2964 unsigned bank_num = mcg_cap & 0xff;
2965 u64 *banks = vcpu->arch.mce_banks;
2967 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2970 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2971 * reporting is disabled
2973 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2974 vcpu->arch.mcg_ctl != ~(u64)0)
2976 banks += 4 * mce->bank;
2978 * if IA32_MCi_CTL is not all 1s, the uncorrected error
2979 * reporting is disabled for the bank
2981 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2983 if (mce->status & MCI_STATUS_UC) {
2984 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2985 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2986 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2989 if (banks[1] & MCI_STATUS_VAL)
2990 mce->status |= MCI_STATUS_OVER;
2991 banks[2] = mce->addr;
2992 banks[3] = mce->misc;
2993 vcpu->arch.mcg_status = mce->mcg_status;
2994 banks[1] = mce->status;
2995 kvm_queue_exception(vcpu, MC_VECTOR);
2996 } else if (!(banks[1] & MCI_STATUS_VAL)
2997 || !(banks[1] & MCI_STATUS_UC)) {
2998 if (banks[1] & MCI_STATUS_VAL)
2999 mce->status |= MCI_STATUS_OVER;
3000 banks[2] = mce->addr;
3001 banks[3] = mce->misc;
3002 banks[1] = mce->status;
3004 banks[1] |= MCI_STATUS_OVER;
3008 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3009 struct kvm_vcpu_events *events)
3012 events->exception.injected =
3013 vcpu->arch.exception.pending &&
3014 !kvm_exception_is_soft(vcpu->arch.exception.nr);
3015 events->exception.nr = vcpu->arch.exception.nr;
3016 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3017 events->exception.pad = 0;
3018 events->exception.error_code = vcpu->arch.exception.error_code;
3020 events->interrupt.injected =
3021 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
3022 events->interrupt.nr = vcpu->arch.interrupt.nr;
3023 events->interrupt.soft = 0;
3024 events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3026 events->nmi.injected = vcpu->arch.nmi_injected;
3027 events->nmi.pending = vcpu->arch.nmi_pending != 0;
3028 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3029 events->nmi.pad = 0;
3031 events->sipi_vector = 0; /* never valid when reporting to user space */
3033 events->smi.smm = is_smm(vcpu);
3034 events->smi.pending = vcpu->arch.smi_pending;
3035 events->smi.smm_inside_nmi =
3036 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3037 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3039 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3040 | KVM_VCPUEVENT_VALID_SHADOW
3041 | KVM_VCPUEVENT_VALID_SMM);
3042 memset(&events->reserved, 0, sizeof(events->reserved));
3045 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
3047 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3048 struct kvm_vcpu_events *events)
3050 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3051 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3052 | KVM_VCPUEVENT_VALID_SHADOW
3053 | KVM_VCPUEVENT_VALID_SMM))
3056 if (events->exception.injected &&
3057 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
3060 /* INITs are latched while in SMM */
3061 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3062 (events->smi.smm || events->smi.pending) &&
3063 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3067 vcpu->arch.exception.pending = events->exception.injected;
3068 vcpu->arch.exception.nr = events->exception.nr;
3069 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3070 vcpu->arch.exception.error_code = events->exception.error_code;
3072 vcpu->arch.interrupt.pending = events->interrupt.injected;
3073 vcpu->arch.interrupt.nr = events->interrupt.nr;
3074 vcpu->arch.interrupt.soft = events->interrupt.soft;
3075 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3076 kvm_x86_ops->set_interrupt_shadow(vcpu,
3077 events->interrupt.shadow);
3079 vcpu->arch.nmi_injected = events->nmi.injected;
3080 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3081 vcpu->arch.nmi_pending = events->nmi.pending;
3082 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3084 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3085 kvm_vcpu_has_lapic(vcpu))
3086 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3088 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3089 u32 hflags = vcpu->arch.hflags;
3090 if (events->smi.smm)
3091 hflags |= HF_SMM_MASK;
3093 hflags &= ~HF_SMM_MASK;
3094 kvm_set_hflags(vcpu, hflags);
3096 vcpu->arch.smi_pending = events->smi.pending;
3097 if (events->smi.smm_inside_nmi)
3098 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3100 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3101 if (kvm_vcpu_has_lapic(vcpu)) {
3102 if (events->smi.latched_init)
3103 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3105 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3109 kvm_make_request(KVM_REQ_EVENT, vcpu);
3114 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3115 struct kvm_debugregs *dbgregs)
3119 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3120 kvm_get_dr(vcpu, 6, &val);
3122 dbgregs->dr7 = vcpu->arch.dr7;
3124 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3127 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3128 struct kvm_debugregs *dbgregs)
3133 if (dbgregs->dr6 & ~0xffffffffull)
3135 if (dbgregs->dr7 & ~0xffffffffull)
3138 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3139 kvm_update_dr0123(vcpu);
3140 vcpu->arch.dr6 = dbgregs->dr6;
3141 kvm_update_dr6(vcpu);
3142 vcpu->arch.dr7 = dbgregs->dr7;
3143 kvm_update_dr7(vcpu);
3148 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3150 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3152 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3153 u64 xstate_bv = xsave->header.xfeatures;
3157 * Copy legacy XSAVE area, to avoid complications with CPUID
3158 * leaves 0 and 1 in the loop below.
3160 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3163 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3164 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3167 * Copy each region from the possibly compacted offset to the
3168 * non-compacted offset.
3170 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3172 u64 feature = valid & -valid;
3173 int index = fls64(feature) - 1;
3174 void *src = get_xsave_addr(xsave, feature);
3177 u32 size, offset, ecx, edx;
3178 cpuid_count(XSTATE_CPUID, index,
3179 &size, &offset, &ecx, &edx);
3180 memcpy(dest + offset, src, size);
3187 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3189 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3190 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3194 * Copy legacy XSAVE area, to avoid complications with CPUID
3195 * leaves 0 and 1 in the loop below.
3197 memcpy(xsave, src, XSAVE_HDR_OFFSET);
3199 /* Set XSTATE_BV and possibly XCOMP_BV. */
3200 xsave->header.xfeatures = xstate_bv;
3202 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3205 * Copy each region from the non-compacted offset to the
3206 * possibly compacted offset.
3208 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3210 u64 feature = valid & -valid;
3211 int index = fls64(feature) - 1;
3212 void *dest = get_xsave_addr(xsave, feature);
3215 u32 size, offset, ecx, edx;
3216 cpuid_count(XSTATE_CPUID, index,
3217 &size, &offset, &ecx, &edx);
3218 memcpy(dest, src + offset, size);
3225 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3226 struct kvm_xsave *guest_xsave)
3228 if (cpu_has_xsave) {
3229 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
3230 fill_xsave((u8 *) guest_xsave->region, vcpu);
3232 memcpy(guest_xsave->region,
3233 &vcpu->arch.guest_fpu.state.fxsave,
3234 sizeof(struct fxregs_state));
3235 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3236 XFEATURE_MASK_FPSSE;
3240 #define XSAVE_MXCSR_OFFSET 24
3242 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3243 struct kvm_xsave *guest_xsave)
3246 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3247 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
3249 if (cpu_has_xsave) {
3251 * Here we allow setting states that are not present in
3252 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
3253 * with old userspace.
3255 if (xstate_bv & ~kvm_supported_xcr0() ||
3256 mxcsr & ~mxcsr_feature_mask)
3258 load_xsave(vcpu, (u8 *)guest_xsave->region);
3260 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
3261 mxcsr & ~mxcsr_feature_mask)
3263 memcpy(&vcpu->arch.guest_fpu.state.fxsave,
3264 guest_xsave->region, sizeof(struct fxregs_state));
3269 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3270 struct kvm_xcrs *guest_xcrs)
3272 if (!cpu_has_xsave) {
3273 guest_xcrs->nr_xcrs = 0;
3277 guest_xcrs->nr_xcrs = 1;
3278 guest_xcrs->flags = 0;
3279 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3280 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3283 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3284 struct kvm_xcrs *guest_xcrs)
3291 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3294 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3295 /* Only support XCR0 currently */
3296 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3297 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3298 guest_xcrs->xcrs[i].value);
3307 * kvm_set_guest_paused() indicates to the guest kernel that it has been
3308 * stopped by the hypervisor. This function will be called from the host only.
3309 * EINVAL is returned when the host attempts to set the flag for a guest that
3310 * does not support pv clocks.
3312 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3314 if (!vcpu->arch.pv_time_enabled)
3316 vcpu->arch.pvclock_set_guest_stopped_request = true;
3317 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3321 long kvm_arch_vcpu_ioctl(struct file *filp,
3322 unsigned int ioctl, unsigned long arg)
3324 struct kvm_vcpu *vcpu = filp->private_data;
3325 void __user *argp = (void __user *)arg;
3328 struct kvm_lapic_state *lapic;
3329 struct kvm_xsave *xsave;
3330 struct kvm_xcrs *xcrs;
3336 case KVM_GET_LAPIC: {
3338 if (!vcpu->arch.apic)
3340 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3345 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3349 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3354 case KVM_SET_LAPIC: {
3356 if (!vcpu->arch.apic)
3358 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3359 if (IS_ERR(u.lapic))
3360 return PTR_ERR(u.lapic);
3362 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3365 case KVM_INTERRUPT: {
3366 struct kvm_interrupt irq;
3369 if (copy_from_user(&irq, argp, sizeof irq))
3371 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3375 r = kvm_vcpu_ioctl_nmi(vcpu);
3379 r = kvm_vcpu_ioctl_smi(vcpu);
3382 case KVM_SET_CPUID: {
3383 struct kvm_cpuid __user *cpuid_arg = argp;
3384 struct kvm_cpuid cpuid;
3387 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3389 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3392 case KVM_SET_CPUID2: {
3393 struct kvm_cpuid2 __user *cpuid_arg = argp;
3394 struct kvm_cpuid2 cpuid;
3397 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3399 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3400 cpuid_arg->entries);
3403 case KVM_GET_CPUID2: {
3404 struct kvm_cpuid2 __user *cpuid_arg = argp;
3405 struct kvm_cpuid2 cpuid;
3408 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3410 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3411 cpuid_arg->entries);
3415 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3421 r = msr_io(vcpu, argp, do_get_msr, 1);
3424 r = msr_io(vcpu, argp, do_set_msr, 0);
3426 case KVM_TPR_ACCESS_REPORTING: {
3427 struct kvm_tpr_access_ctl tac;
3430 if (copy_from_user(&tac, argp, sizeof tac))
3432 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3436 if (copy_to_user(argp, &tac, sizeof tac))
3441 case KVM_SET_VAPIC_ADDR: {
3442 struct kvm_vapic_addr va;
3446 if (!lapic_in_kernel(vcpu))
3449 if (copy_from_user(&va, argp, sizeof va))
3451 idx = srcu_read_lock(&vcpu->kvm->srcu);
3452 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3453 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3456 case KVM_X86_SETUP_MCE: {
3460 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3462 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3465 case KVM_X86_SET_MCE: {
3466 struct kvm_x86_mce mce;
3469 if (copy_from_user(&mce, argp, sizeof mce))
3471 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3474 case KVM_GET_VCPU_EVENTS: {
3475 struct kvm_vcpu_events events;
3477 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3480 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3485 case KVM_SET_VCPU_EVENTS: {
3486 struct kvm_vcpu_events events;
3489 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3492 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3495 case KVM_GET_DEBUGREGS: {
3496 struct kvm_debugregs dbgregs;
3498 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3501 if (copy_to_user(argp, &dbgregs,
3502 sizeof(struct kvm_debugregs)))
3507 case KVM_SET_DEBUGREGS: {
3508 struct kvm_debugregs dbgregs;
3511 if (copy_from_user(&dbgregs, argp,
3512 sizeof(struct kvm_debugregs)))
3515 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3518 case KVM_GET_XSAVE: {
3519 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3524 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3527 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3532 case KVM_SET_XSAVE: {
3533 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3534 if (IS_ERR(u.xsave))
3535 return PTR_ERR(u.xsave);
3537 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3540 case KVM_GET_XCRS: {
3541 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3546 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3549 if (copy_to_user(argp, u.xcrs,
3550 sizeof(struct kvm_xcrs)))
3555 case KVM_SET_XCRS: {
3556 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3558 return PTR_ERR(u.xcrs);
3560 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3563 case KVM_SET_TSC_KHZ: {
3567 user_tsc_khz = (u32)arg;
3569 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3572 if (user_tsc_khz == 0)
3573 user_tsc_khz = tsc_khz;
3575 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
3580 case KVM_GET_TSC_KHZ: {
3581 r = vcpu->arch.virtual_tsc_khz;
3584 case KVM_KVMCLOCK_CTRL: {
3585 r = kvm_set_guest_paused(vcpu);
3596 int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3598 return VM_FAULT_SIGBUS;
3601 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3605 if (addr > (unsigned int)(-3 * PAGE_SIZE))
3607 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3611 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3614 kvm->arch.ept_identity_map_addr = ident_addr;
3618 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3619 u32 kvm_nr_mmu_pages)
3621 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3624 mutex_lock(&kvm->slots_lock);
3626 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3627 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3629 mutex_unlock(&kvm->slots_lock);
3633 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3635 return kvm->arch.n_max_mmu_pages;
3638 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3643 switch (chip->chip_id) {
3644 case KVM_IRQCHIP_PIC_MASTER:
3645 memcpy(&chip->chip.pic,
3646 &pic_irqchip(kvm)->pics[0],
3647 sizeof(struct kvm_pic_state));
3649 case KVM_IRQCHIP_PIC_SLAVE:
3650 memcpy(&chip->chip.pic,
3651 &pic_irqchip(kvm)->pics[1],
3652 sizeof(struct kvm_pic_state));
3654 case KVM_IRQCHIP_IOAPIC:
3655 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3664 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3669 switch (chip->chip_id) {
3670 case KVM_IRQCHIP_PIC_MASTER:
3671 spin_lock(&pic_irqchip(kvm)->lock);
3672 memcpy(&pic_irqchip(kvm)->pics[0],
3674 sizeof(struct kvm_pic_state));
3675 spin_unlock(&pic_irqchip(kvm)->lock);
3677 case KVM_IRQCHIP_PIC_SLAVE:
3678 spin_lock(&pic_irqchip(kvm)->lock);
3679 memcpy(&pic_irqchip(kvm)->pics[1],
3681 sizeof(struct kvm_pic_state));
3682 spin_unlock(&pic_irqchip(kvm)->lock);
3684 case KVM_IRQCHIP_IOAPIC:
3685 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3691 kvm_pic_update_irq(pic_irqchip(kvm));
3695 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3697 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3698 memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
3699 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3703 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3706 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3707 memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
3708 for (i = 0; i < 3; i++)
3709 kvm_pit_load_count(kvm, i, ps->channels[i].count, 0);
3710 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3714 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3716 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3717 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3718 sizeof(ps->channels));
3719 ps->flags = kvm->arch.vpit->pit_state.flags;
3720 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3721 memset(&ps->reserved, 0, sizeof(ps->reserved));
3725 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3729 u32 prev_legacy, cur_legacy;
3730 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3731 prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3732 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3733 if (!prev_legacy && cur_legacy)
3735 memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
3736 sizeof(kvm->arch.vpit->pit_state.channels));
3737 kvm->arch.vpit->pit_state.flags = ps->flags;
3738 for (i = 0; i < 3; i++)
3739 kvm_pit_load_count(kvm, i, kvm->arch.vpit->pit_state.channels[i].count,
3741 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3745 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3746 struct kvm_reinject_control *control)
3748 if (!kvm->arch.vpit)
3750 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3751 kvm->arch.vpit->pit_state.reinject = control->pit_reinject;
3752 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3757 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
3758 * @kvm: kvm instance
3759 * @log: slot id and address to which we copy the log
3761 * Steps 1-4 below provide general overview of dirty page logging. See
3762 * kvm_get_dirty_log_protect() function description for additional details.
3764 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
3765 * always flush the TLB (step 4) even if previous step failed and the dirty
3766 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
3767 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
3768 * writes will be marked dirty for next log read.
3770 * 1. Take a snapshot of the bit and clear it if needed.
3771 * 2. Write protect the corresponding page.
3772 * 3. Copy the snapshot to the userspace.
3773 * 4. Flush TLB's if needed.
3775 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
3777 bool is_dirty = false;
3780 mutex_lock(&kvm->slots_lock);
3783 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
3785 if (kvm_x86_ops->flush_log_dirty)
3786 kvm_x86_ops->flush_log_dirty(kvm);
3788 r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
3791 * All the TLBs can be flushed out of mmu lock, see the comments in
3792 * kvm_mmu_slot_remove_write_access().
3794 lockdep_assert_held(&kvm->slots_lock);
3796 kvm_flush_remote_tlbs(kvm);
3798 mutex_unlock(&kvm->slots_lock);
3802 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
3805 if (!irqchip_in_kernel(kvm))
3808 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3809 irq_event->irq, irq_event->level,
3814 static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3815 struct kvm_enable_cap *cap)
3823 case KVM_CAP_DISABLE_QUIRKS:
3824 kvm->arch.disabled_quirks = cap->args[0];
3827 case KVM_CAP_SPLIT_IRQCHIP: {
3828 mutex_lock(&kvm->lock);
3830 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
3831 goto split_irqchip_unlock;
3833 if (irqchip_in_kernel(kvm))
3834 goto split_irqchip_unlock;
3835 if (atomic_read(&kvm->online_vcpus))
3836 goto split_irqchip_unlock;
3837 r = kvm_setup_empty_irq_routing(kvm);
3839 goto split_irqchip_unlock;
3840 /* Pairs with irqchip_in_kernel. */
3842 kvm->arch.irqchip_split = true;
3843 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
3845 split_irqchip_unlock:
3846 mutex_unlock(&kvm->lock);
3856 long kvm_arch_vm_ioctl(struct file *filp,
3857 unsigned int ioctl, unsigned long arg)
3859 struct kvm *kvm = filp->private_data;
3860 void __user *argp = (void __user *)arg;
3863 * This union makes it completely explicit to gcc-3.x
3864 * that these two variables' stack usage should be
3865 * combined, not added together.
3868 struct kvm_pit_state ps;
3869 struct kvm_pit_state2 ps2;
3870 struct kvm_pit_config pit_config;
3874 case KVM_SET_TSS_ADDR:
3875 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3877 case KVM_SET_IDENTITY_MAP_ADDR: {
3881 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3883 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3886 case KVM_SET_NR_MMU_PAGES:
3887 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3889 case KVM_GET_NR_MMU_PAGES:
3890 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3892 case KVM_CREATE_IRQCHIP: {
3893 struct kvm_pic *vpic;
3895 mutex_lock(&kvm->lock);
3898 goto create_irqchip_unlock;
3900 if (atomic_read(&kvm->online_vcpus))
3901 goto create_irqchip_unlock;
3903 vpic = kvm_create_pic(kvm);
3905 r = kvm_ioapic_init(kvm);
3907 mutex_lock(&kvm->slots_lock);
3908 kvm_destroy_pic(vpic);
3909 mutex_unlock(&kvm->slots_lock);
3910 goto create_irqchip_unlock;
3913 goto create_irqchip_unlock;
3914 r = kvm_setup_default_irq_routing(kvm);
3916 mutex_lock(&kvm->slots_lock);
3917 mutex_lock(&kvm->irq_lock);
3918 kvm_ioapic_destroy(kvm);
3919 kvm_destroy_pic(vpic);
3920 mutex_unlock(&kvm->irq_lock);
3921 mutex_unlock(&kvm->slots_lock);
3922 goto create_irqchip_unlock;
3924 /* Write kvm->irq_routing before kvm->arch.vpic. */
3926 kvm->arch.vpic = vpic;
3927 create_irqchip_unlock:
3928 mutex_unlock(&kvm->lock);
3931 case KVM_CREATE_PIT:
3932 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3934 case KVM_CREATE_PIT2:
3936 if (copy_from_user(&u.pit_config, argp,
3937 sizeof(struct kvm_pit_config)))
3940 mutex_lock(&kvm->lock);
3943 goto create_pit_unlock;
3945 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3949 mutex_unlock(&kvm->lock);
3951 case KVM_GET_IRQCHIP: {
3952 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3953 struct kvm_irqchip *chip;
3955 chip = memdup_user(argp, sizeof(*chip));
3962 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
3963 goto get_irqchip_out;
3964 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3966 goto get_irqchip_out;
3968 if (copy_to_user(argp, chip, sizeof *chip))
3969 goto get_irqchip_out;
3975 case KVM_SET_IRQCHIP: {
3976 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3977 struct kvm_irqchip *chip;
3979 chip = memdup_user(argp, sizeof(*chip));
3986 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
3987 goto set_irqchip_out;
3988 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3990 goto set_irqchip_out;
3998 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
4001 if (!kvm->arch.vpit)
4003 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
4007 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
4014 if (copy_from_user(&u.ps, argp, sizeof u.ps))
4017 if (!kvm->arch.vpit)
4019 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
4022 case KVM_GET_PIT2: {
4024 if (!kvm->arch.vpit)
4026 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
4030 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
4035 case KVM_SET_PIT2: {
4037 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
4040 if (!kvm->arch.vpit)
4042 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
4045 case KVM_REINJECT_CONTROL: {
4046 struct kvm_reinject_control control;
4048 if (copy_from_user(&control, argp, sizeof(control)))
4050 r = kvm_vm_ioctl_reinject(kvm, &control);
4053 case KVM_SET_BOOT_CPU_ID:
4055 mutex_lock(&kvm->lock);
4056 if (atomic_read(&kvm->online_vcpus) != 0)
4059 kvm->arch.bsp_vcpu_id = arg;
4060 mutex_unlock(&kvm->lock);
4062 case KVM_XEN_HVM_CONFIG: {
4063 struct kvm_xen_hvm_config xhc;
4065 if (copy_from_user(&xhc, argp, sizeof(xhc)))
4070 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
4074 case KVM_SET_CLOCK: {
4075 struct kvm_clock_data user_ns;
4080 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
4088 local_irq_disable();
4089 now_ns = get_kernel_ns();
4090 delta = user_ns.clock - now_ns;
4092 kvm->arch.kvmclock_offset = delta;
4093 kvm_gen_update_masterclock(kvm);
4096 case KVM_GET_CLOCK: {
4097 struct kvm_clock_data user_ns;
4100 local_irq_disable();
4101 now_ns = get_kernel_ns();
4102 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
4105 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
4108 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
4113 case KVM_ENABLE_CAP: {
4114 struct kvm_enable_cap cap;
4117 if (copy_from_user(&cap, argp, sizeof(cap)))
4119 r = kvm_vm_ioctl_enable_cap(kvm, &cap);
4123 r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
4129 static void kvm_init_msr_list(void)
4134 for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
4135 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
4139 * Even MSRs that are valid in the host may not be exposed
4140 * to the guests in some cases.
4142 switch (msrs_to_save[i]) {
4143 case MSR_IA32_BNDCFGS:
4144 if (!kvm_x86_ops->mpx_supported())
4148 if (!kvm_x86_ops->rdtscp_supported())
4156 msrs_to_save[j] = msrs_to_save[i];
4159 num_msrs_to_save = j;
4161 for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
4162 if (!kvm_x86_ops->has_emulated_msr(emulated_msrs[i]))
4166 emulated_msrs[j] = emulated_msrs[i];
4169 num_emulated_msrs = j;
4172 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
4180 if (!(vcpu->arch.apic &&
4181 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
4182 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
4193 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
4200 if (!(vcpu->arch.apic &&
4201 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
4203 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
4205 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
4215 static void kvm_set_segment(struct kvm_vcpu *vcpu,
4216 struct kvm_segment *var, int seg)
4218 kvm_x86_ops->set_segment(vcpu, var, seg);
4221 void kvm_get_segment(struct kvm_vcpu *vcpu,
4222 struct kvm_segment *var, int seg)
4224 kvm_x86_ops->get_segment(vcpu, var, seg);
4227 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
4228 struct x86_exception *exception)
4232 BUG_ON(!mmu_is_nested(vcpu));
4234 /* NPT walks are always user-walks */
4235 access |= PFERR_USER_MASK;
4236 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
4241 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
4242 struct x86_exception *exception)
4244 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4245 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4248 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
4249 struct x86_exception *exception)
4251 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4252 access |= PFERR_FETCH_MASK;
4253 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4256 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4257 struct x86_exception *exception)
4259 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4260 access |= PFERR_WRITE_MASK;
4261 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4264 /* uses this to access any guest's mapped memory without checking CPL */
4265 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4266 struct x86_exception *exception)
4268 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
4271 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4272 struct kvm_vcpu *vcpu, u32 access,
4273 struct x86_exception *exception)
4276 int r = X86EMUL_CONTINUE;
4279 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4281 unsigned offset = addr & (PAGE_SIZE-1);
4282 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4285 if (gpa == UNMAPPED_GVA)
4286 return X86EMUL_PROPAGATE_FAULT;
4287 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
4290 r = X86EMUL_IO_NEEDED;
4302 /* used for instruction fetching */
4303 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4304 gva_t addr, void *val, unsigned int bytes,
4305 struct x86_exception *exception)
4307 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4308 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4312 /* Inline kvm_read_guest_virt_helper for speed. */
4313 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
4315 if (unlikely(gpa == UNMAPPED_GVA))
4316 return X86EMUL_PROPAGATE_FAULT;
4318 offset = addr & (PAGE_SIZE-1);
4319 if (WARN_ON(offset + bytes > PAGE_SIZE))
4320 bytes = (unsigned)PAGE_SIZE - offset;
4321 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
4323 if (unlikely(ret < 0))
4324 return X86EMUL_IO_NEEDED;
4326 return X86EMUL_CONTINUE;
4329 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
4330 gva_t addr, void *val, unsigned int bytes,
4331 struct x86_exception *exception)
4333 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4336 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
4337 * is returned, but our callers are not ready for that and they blindly
4338 * call kvm_inject_page_fault. Ensure that they at least do not leak
4339 * uninitialized kernel stack memory into cr2 and error code.
4341 memset(exception, 0, sizeof(*exception));
4342 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4345 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4347 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
4348 gva_t addr, void *val, unsigned int bytes,
4349 struct x86_exception *exception, bool system)
4351 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4354 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
4355 access |= PFERR_USER_MASK;
4357 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
4360 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
4361 unsigned long addr, void *val, unsigned int bytes)
4363 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4364 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
4366 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
4369 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4370 struct kvm_vcpu *vcpu, u32 access,
4371 struct x86_exception *exception)
4374 int r = X86EMUL_CONTINUE;
4377 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4380 unsigned offset = addr & (PAGE_SIZE-1);
4381 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4384 if (gpa == UNMAPPED_GVA)
4385 return X86EMUL_PROPAGATE_FAULT;
4386 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
4388 r = X86EMUL_IO_NEEDED;
4400 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
4401 unsigned int bytes, struct x86_exception *exception,
4404 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4405 u32 access = PFERR_WRITE_MASK;
4407 if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
4408 access |= PFERR_USER_MASK;
4411 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
4412 * is returned, but our callers are not ready for that and they blindly
4413 * call kvm_inject_page_fault. Ensure that they at least do not leak
4414 * uninitialized kernel stack memory into cr2 and error code.
4416 memset(exception, 0, sizeof(*exception));
4417 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4421 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
4422 unsigned int bytes, struct x86_exception *exception)
4424 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4425 PFERR_WRITE_MASK, exception);
4427 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4429 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4430 gpa_t *gpa, struct x86_exception *exception,
4433 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
4434 | (write ? PFERR_WRITE_MASK : 0);
4436 if (vcpu_match_mmio_gva(vcpu, gva)
4437 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
4438 vcpu->arch.access, access)) {
4439 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4440 (gva & (PAGE_SIZE - 1));
4441 trace_vcpu_match_mmio(gva, *gpa, write, false);
4445 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4447 if (*gpa == UNMAPPED_GVA)
4450 /* For APIC access vmexit */
4451 if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4454 if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
4455 trace_vcpu_match_mmio(gva, *gpa, write, true);
4462 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4463 const void *val, int bytes)
4467 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
4470 kvm_mmu_pte_write(vcpu, gpa, val, bytes);
4474 struct read_write_emulator_ops {
4475 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4477 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4478 void *val, int bytes);
4479 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4480 int bytes, void *val);
4481 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4482 void *val, int bytes);
4486 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4488 if (vcpu->mmio_read_completed) {
4489 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4490 vcpu->mmio_fragments[0].gpa, val);
4491 vcpu->mmio_read_completed = 0;
4498 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4499 void *val, int bytes)
4501 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
4504 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4505 void *val, int bytes)
4507 return emulator_write_phys(vcpu, gpa, val, bytes);
4510 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4512 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
4513 return vcpu_mmio_write(vcpu, gpa, bytes, val);
4516 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4517 void *val, int bytes)
4519 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
4520 return X86EMUL_IO_NEEDED;
4523 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4524 void *val, int bytes)
4526 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
4528 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
4529 return X86EMUL_CONTINUE;
4532 static const struct read_write_emulator_ops read_emultor = {
4533 .read_write_prepare = read_prepare,
4534 .read_write_emulate = read_emulate,
4535 .read_write_mmio = vcpu_mmio_read,
4536 .read_write_exit_mmio = read_exit_mmio,
4539 static const struct read_write_emulator_ops write_emultor = {
4540 .read_write_emulate = write_emulate,
4541 .read_write_mmio = write_mmio,
4542 .read_write_exit_mmio = write_exit_mmio,
4546 static int emulator_read_write_onepage(unsigned long addr, void *val,
4548 struct x86_exception *exception,
4549 struct kvm_vcpu *vcpu,
4550 const struct read_write_emulator_ops *ops)
4554 bool write = ops->write;
4555 struct kvm_mmio_fragment *frag;
4557 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4560 return X86EMUL_PROPAGATE_FAULT;
4562 /* For APIC access vmexit */
4566 if (ops->read_write_emulate(vcpu, gpa, val, bytes))
4567 return X86EMUL_CONTINUE;
4571 * Is this MMIO handled locally?
4573 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4574 if (handled == bytes)
4575 return X86EMUL_CONTINUE;
4581 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
4582 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
4586 return X86EMUL_CONTINUE;
4589 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
4591 void *val, unsigned int bytes,
4592 struct x86_exception *exception,
4593 const struct read_write_emulator_ops *ops)
4595 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4599 if (ops->read_write_prepare &&
4600 ops->read_write_prepare(vcpu, val, bytes))
4601 return X86EMUL_CONTINUE;
4603 vcpu->mmio_nr_fragments = 0;
4605 /* Crossing a page boundary? */
4606 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4609 now = -addr & ~PAGE_MASK;
4610 rc = emulator_read_write_onepage(addr, val, now, exception,
4613 if (rc != X86EMUL_CONTINUE)
4616 if (ctxt->mode != X86EMUL_MODE_PROT64)
4622 rc = emulator_read_write_onepage(addr, val, bytes, exception,
4624 if (rc != X86EMUL_CONTINUE)
4627 if (!vcpu->mmio_nr_fragments)
4630 gpa = vcpu->mmio_fragments[0].gpa;
4632 vcpu->mmio_needed = 1;
4633 vcpu->mmio_cur_fragment = 0;
4635 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
4636 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
4637 vcpu->run->exit_reason = KVM_EXIT_MMIO;
4638 vcpu->run->mmio.phys_addr = gpa;
4640 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4643 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4647 struct x86_exception *exception)
4649 return emulator_read_write(ctxt, addr, val, bytes,
4650 exception, &read_emultor);
4653 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4657 struct x86_exception *exception)
4659 return emulator_read_write(ctxt, addr, (void *)val, bytes,
4660 exception, &write_emultor);
4663 #define CMPXCHG_TYPE(t, ptr, old, new) \
4664 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4666 #ifdef CONFIG_X86_64
4667 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4669 # define CMPXCHG64(ptr, old, new) \
4670 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4673 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4678 struct x86_exception *exception)
4680 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4686 /* guests cmpxchg8b have to be emulated atomically */
4687 if (bytes > 8 || (bytes & (bytes - 1)))
4690 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4692 if (gpa == UNMAPPED_GVA ||
4693 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4696 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4699 page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
4700 if (is_error_page(page))
4703 kaddr = kmap_atomic(page);
4704 kaddr += offset_in_page(gpa);
4707 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4710 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4713 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
4716 exchanged = CMPXCHG64(kaddr, old, new);
4721 kunmap_atomic(kaddr);
4722 kvm_release_page_dirty(page);
4725 return X86EMUL_CMPXCHG_FAILED;
4727 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
4728 kvm_mmu_pte_write(vcpu, gpa, new, bytes);
4730 return X86EMUL_CONTINUE;
4733 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
4735 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
4738 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
4742 for (i = 0; i < vcpu->arch.pio.count; i++) {
4743 if (vcpu->arch.pio.in)
4744 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
4745 vcpu->arch.pio.size, pd);
4747 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
4748 vcpu->arch.pio.port, vcpu->arch.pio.size,
4752 pd += vcpu->arch.pio.size;
4757 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
4758 unsigned short port, void *val,
4759 unsigned int count, bool in)
4761 vcpu->arch.pio.port = port;
4762 vcpu->arch.pio.in = in;
4763 vcpu->arch.pio.count = count;
4764 vcpu->arch.pio.size = size;
4766 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4767 vcpu->arch.pio.count = 0;
4771 vcpu->run->exit_reason = KVM_EXIT_IO;
4772 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
4773 vcpu->run->io.size = size;
4774 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4775 vcpu->run->io.count = count;
4776 vcpu->run->io.port = port;
4781 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
4782 int size, unsigned short port, void *val,
4785 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4788 if (vcpu->arch.pio.count)
4791 memset(vcpu->arch.pio_data, 0, size * count);
4793 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
4796 memcpy(val, vcpu->arch.pio_data, size * count);
4797 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
4798 vcpu->arch.pio.count = 0;
4805 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
4806 int size, unsigned short port,
4807 const void *val, unsigned int count)
4809 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4811 memcpy(vcpu->arch.pio_data, val, size * count);
4812 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
4813 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
4816 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
4818 return kvm_x86_ops->get_segment_base(vcpu, seg);
4821 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
4823 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
4826 int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
4828 if (!need_emulate_wbinvd(vcpu))
4829 return X86EMUL_CONTINUE;
4831 if (kvm_x86_ops->has_wbinvd_exit()) {
4832 int cpu = get_cpu();
4834 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4835 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
4836 wbinvd_ipi, NULL, 1);
4838 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
4841 return X86EMUL_CONTINUE;
4844 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
4846 kvm_x86_ops->skip_emulated_instruction(vcpu);
4847 return kvm_emulate_wbinvd_noskip(vcpu);
4849 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
4853 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
4855 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
4858 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
4859 unsigned long *dest)
4861 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
4864 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
4865 unsigned long value)
4868 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
4871 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
4873 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
4876 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
4878 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4879 unsigned long value;
4883 value = kvm_read_cr0(vcpu);
4886 value = vcpu->arch.cr2;
4889 value = kvm_read_cr3(vcpu);
4892 value = kvm_read_cr4(vcpu);
4895 value = kvm_get_cr8(vcpu);
4898 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4905 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
4907 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4912 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4915 vcpu->arch.cr2 = val;
4918 res = kvm_set_cr3(vcpu, val);
4921 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4924 res = kvm_set_cr8(vcpu, val);
4927 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4934 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
4936 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
4939 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4941 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
4944 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4946 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
4949 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4951 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4954 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4956 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4959 static unsigned long emulator_get_cached_segment_base(
4960 struct x86_emulate_ctxt *ctxt, int seg)
4962 return get_segment_base(emul_to_vcpu(ctxt), seg);
4965 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4966 struct desc_struct *desc, u32 *base3,
4969 struct kvm_segment var;
4971 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
4972 *selector = var.selector;
4975 memset(desc, 0, sizeof(*desc));
4983 set_desc_limit(desc, var.limit);
4984 set_desc_base(desc, (unsigned long)var.base);
4985 #ifdef CONFIG_X86_64
4987 *base3 = var.base >> 32;
4989 desc->type = var.type;
4991 desc->dpl = var.dpl;
4992 desc->p = var.present;
4993 desc->avl = var.avl;
5001 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
5002 struct desc_struct *desc, u32 base3,
5005 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5006 struct kvm_segment var;
5008 var.selector = selector;
5009 var.base = get_desc_base(desc);
5010 #ifdef CONFIG_X86_64
5011 var.base |= ((u64)base3) << 32;
5013 var.limit = get_desc_limit(desc);
5015 var.limit = (var.limit << 12) | 0xfff;
5016 var.type = desc->type;
5017 var.dpl = desc->dpl;
5022 var.avl = desc->avl;
5023 var.present = desc->p;
5024 var.unusable = !var.present;
5027 kvm_set_segment(vcpu, &var, seg);
5031 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
5032 u32 msr_index, u64 *pdata)
5034 struct msr_data msr;
5037 msr.index = msr_index;
5038 msr.host_initiated = false;
5039 r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
5047 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
5048 u32 msr_index, u64 data)
5050 struct msr_data msr;
5053 msr.index = msr_index;
5054 msr.host_initiated = false;
5055 return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
5058 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
5060 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5062 return vcpu->arch.smbase;
5065 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
5067 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5069 vcpu->arch.smbase = smbase;
5072 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
5075 return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
5078 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
5079 u32 pmc, u64 *pdata)
5081 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
5084 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
5086 emul_to_vcpu(ctxt)->arch.halt_request = 1;
5089 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
5092 kvm_load_guest_fpu(emul_to_vcpu(ctxt));
5094 * CR0.TS may reference the host fpu state, not the guest fpu state,
5095 * so it may be clear at this point.
5100 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
5105 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
5106 struct x86_instruction_info *info,
5107 enum x86_intercept_stage stage)
5109 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
5112 static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
5113 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
5115 kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
5118 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
5120 return kvm_register_read(emul_to_vcpu(ctxt), reg);
5123 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
5125 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
5128 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
5130 kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
5133 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
5135 return emul_to_vcpu(ctxt)->arch.hflags;
5138 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
5140 kvm_set_hflags(emul_to_vcpu(ctxt), emul_flags);
5143 static const struct x86_emulate_ops emulate_ops = {
5144 .read_gpr = emulator_read_gpr,
5145 .write_gpr = emulator_write_gpr,
5146 .read_std = emulator_read_std,
5147 .write_std = emulator_write_std,
5148 .read_phys = kvm_read_guest_phys_system,
5149 .fetch = kvm_fetch_guest_virt,
5150 .read_emulated = emulator_read_emulated,
5151 .write_emulated = emulator_write_emulated,
5152 .cmpxchg_emulated = emulator_cmpxchg_emulated,
5153 .invlpg = emulator_invlpg,
5154 .pio_in_emulated = emulator_pio_in_emulated,
5155 .pio_out_emulated = emulator_pio_out_emulated,
5156 .get_segment = emulator_get_segment,
5157 .set_segment = emulator_set_segment,
5158 .get_cached_segment_base = emulator_get_cached_segment_base,
5159 .get_gdt = emulator_get_gdt,
5160 .get_idt = emulator_get_idt,
5161 .set_gdt = emulator_set_gdt,
5162 .set_idt = emulator_set_idt,
5163 .get_cr = emulator_get_cr,
5164 .set_cr = emulator_set_cr,
5165 .cpl = emulator_get_cpl,
5166 .get_dr = emulator_get_dr,
5167 .set_dr = emulator_set_dr,
5168 .get_smbase = emulator_get_smbase,
5169 .set_smbase = emulator_set_smbase,
5170 .set_msr = emulator_set_msr,
5171 .get_msr = emulator_get_msr,
5172 .check_pmc = emulator_check_pmc,
5173 .read_pmc = emulator_read_pmc,
5174 .halt = emulator_halt,
5175 .wbinvd = emulator_wbinvd,
5176 .fix_hypercall = emulator_fix_hypercall,
5177 .get_fpu = emulator_get_fpu,
5178 .put_fpu = emulator_put_fpu,
5179 .intercept = emulator_intercept,
5180 .get_cpuid = emulator_get_cpuid,
5181 .set_nmi_mask = emulator_set_nmi_mask,
5182 .get_hflags = emulator_get_hflags,
5183 .set_hflags = emulator_set_hflags,
5186 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
5188 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
5190 * an sti; sti; sequence only disable interrupts for the first
5191 * instruction. So, if the last instruction, be it emulated or
5192 * not, left the system with the INT_STI flag enabled, it
5193 * means that the last instruction is an sti. We should not
5194 * leave the flag on in this case. The same goes for mov ss
5196 if (int_shadow & mask)
5198 if (unlikely(int_shadow || mask)) {
5199 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
5201 kvm_make_request(KVM_REQ_EVENT, vcpu);
5205 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
5207 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5208 if (ctxt->exception.vector == PF_VECTOR)
5209 return kvm_propagate_fault(vcpu, &ctxt->exception);
5211 if (ctxt->exception.error_code_valid)
5212 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
5213 ctxt->exception.error_code);
5215 kvm_queue_exception(vcpu, ctxt->exception.vector);
5219 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
5221 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5224 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5226 ctxt->eflags = kvm_get_rflags(vcpu);
5227 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
5229 ctxt->eip = kvm_rip_read(vcpu);
5230 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
5231 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
5232 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
5233 cs_db ? X86EMUL_MODE_PROT32 :
5234 X86EMUL_MODE_PROT16;
5235 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
5236 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
5237 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
5239 init_decode_cache(ctxt);
5240 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5243 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
5245 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5248 init_emulate_ctxt(vcpu);
5252 ctxt->_eip = ctxt->eip + inc_eip;
5253 ret = emulate_int_real(ctxt, irq);
5255 if (ret != X86EMUL_CONTINUE)
5256 return EMULATE_FAIL;
5258 ctxt->eip = ctxt->_eip;
5259 kvm_rip_write(vcpu, ctxt->eip);
5260 kvm_set_rflags(vcpu, ctxt->eflags);
5262 if (irq == NMI_VECTOR)
5263 vcpu->arch.nmi_pending = 0;
5265 vcpu->arch.interrupt.pending = false;
5267 return EMULATE_DONE;
5269 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
5271 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
5273 int r = EMULATE_DONE;
5275 ++vcpu->stat.insn_emulation_fail;
5276 trace_kvm_emulate_insn_failed(vcpu);
5277 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
5278 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5279 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5280 vcpu->run->internal.ndata = 0;
5281 r = EMULATE_USER_EXIT;
5283 kvm_queue_exception(vcpu, UD_VECTOR);
5288 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5289 bool write_fault_to_shadow_pgtable,
5295 if (emulation_type & EMULTYPE_NO_REEXECUTE)
5298 if (!vcpu->arch.mmu.direct_map) {
5300 * Write permission should be allowed since only
5301 * write access need to be emulated.
5303 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5306 * If the mapping is invalid in guest, let cpu retry
5307 * it to generate fault.
5309 if (gpa == UNMAPPED_GVA)
5314 * Do not retry the unhandleable instruction if it faults on the
5315 * readonly host memory, otherwise it will goto a infinite loop:
5316 * retry instruction -> write #PF -> emulation fail -> retry
5317 * instruction -> ...
5319 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
5322 * If the instruction failed on the error pfn, it can not be fixed,
5323 * report the error to userspace.
5325 if (is_error_noslot_pfn(pfn))
5328 kvm_release_pfn_clean(pfn);
5330 /* The instructions are well-emulated on direct mmu. */
5331 if (vcpu->arch.mmu.direct_map) {
5332 unsigned int indirect_shadow_pages;
5334 spin_lock(&vcpu->kvm->mmu_lock);
5335 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
5336 spin_unlock(&vcpu->kvm->mmu_lock);
5338 if (indirect_shadow_pages)
5339 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5345 * if emulation was due to access to shadowed page table
5346 * and it failed try to unshadow page and re-enter the
5347 * guest to let CPU execute the instruction.
5349 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5352 * If the access faults on its page table, it can not
5353 * be fixed by unprotecting shadow page and it should
5354 * be reported to userspace.
5356 return !write_fault_to_shadow_pgtable;
5359 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5360 unsigned long cr2, int emulation_type)
5362 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5363 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
5365 last_retry_eip = vcpu->arch.last_retry_eip;
5366 last_retry_addr = vcpu->arch.last_retry_addr;
5369 * If the emulation is caused by #PF and it is non-page_table
5370 * writing instruction, it means the VM-EXIT is caused by shadow
5371 * page protected, we can zap the shadow page and retry this
5372 * instruction directly.
5374 * Note: if the guest uses a non-page-table modifying instruction
5375 * on the PDE that points to the instruction, then we will unmap
5376 * the instruction and go to an infinite loop. So, we cache the
5377 * last retried eip and the last fault address, if we meet the eip
5378 * and the address again, we can break out of the potential infinite
5381 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
5383 if (!(emulation_type & EMULTYPE_RETRY))
5386 if (x86_page_table_writing_insn(ctxt))
5389 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
5392 vcpu->arch.last_retry_eip = ctxt->eip;
5393 vcpu->arch.last_retry_addr = cr2;
5395 if (!vcpu->arch.mmu.direct_map)
5396 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5398 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5403 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
5404 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
5406 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
5408 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
5409 /* This is a good place to trace that we are exiting SMM. */
5410 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
5412 if (unlikely(vcpu->arch.smi_pending)) {
5413 kvm_make_request(KVM_REQ_SMI, vcpu);
5414 vcpu->arch.smi_pending = 0;
5416 /* Process a latched INIT, if any. */
5417 kvm_make_request(KVM_REQ_EVENT, vcpu);
5421 kvm_mmu_reset_context(vcpu);
5424 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
5426 unsigned changed = vcpu->arch.hflags ^ emul_flags;
5428 vcpu->arch.hflags = emul_flags;
5430 if (changed & HF_SMM_MASK)
5431 kvm_smm_changed(vcpu);
5434 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
5443 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
5444 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
5449 static void kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu, int *r)
5451 struct kvm_run *kvm_run = vcpu->run;
5453 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5454 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
5455 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
5456 kvm_run->debug.arch.exception = DB_VECTOR;
5457 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5458 *r = EMULATE_USER_EXIT;
5460 vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF;
5462 * "Certain debug exceptions may clear bit 0-3. The
5463 * remaining contents of the DR6 register are never
5464 * cleared by the processor".
5466 vcpu->arch.dr6 &= ~15;
5467 vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
5468 kvm_queue_exception(vcpu, DB_VECTOR);
5472 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
5474 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
5475 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
5476 struct kvm_run *kvm_run = vcpu->run;
5477 unsigned long eip = kvm_get_linear_rip(vcpu);
5478 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5479 vcpu->arch.guest_debug_dr7,
5483 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
5484 kvm_run->debug.arch.pc = eip;
5485 kvm_run->debug.arch.exception = DB_VECTOR;
5486 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5487 *r = EMULATE_USER_EXIT;
5492 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
5493 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
5494 unsigned long eip = kvm_get_linear_rip(vcpu);
5495 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5500 vcpu->arch.dr6 &= ~15;
5501 vcpu->arch.dr6 |= dr6 | DR6_RTM;
5502 kvm_queue_exception(vcpu, DB_VECTOR);
5511 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
5518 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5519 bool writeback = true;
5520 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
5523 * Clear write_fault_to_shadow_pgtable here to ensure it is
5526 vcpu->arch.write_fault_to_shadow_pgtable = false;
5527 kvm_clear_exception_queue(vcpu);
5529 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
5530 init_emulate_ctxt(vcpu);
5533 * We will reenter on the same instruction since
5534 * we do not set complete_userspace_io. This does not
5535 * handle watchpoints yet, those would be handled in
5538 if (!(emulation_type & EMULTYPE_SKIP) &&
5539 kvm_vcpu_check_breakpoint(vcpu, &r))
5542 ctxt->interruptibility = 0;
5543 ctxt->have_exception = false;
5544 ctxt->exception.vector = -1;
5545 ctxt->perm_ok = false;
5547 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
5549 r = x86_decode_insn(ctxt, insn, insn_len);
5551 trace_kvm_emulate_insn_start(vcpu);
5552 ++vcpu->stat.insn_emulation;
5553 if (r != EMULATION_OK) {
5554 if (emulation_type & EMULTYPE_TRAP_UD)
5555 return EMULATE_FAIL;
5556 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5558 return EMULATE_DONE;
5559 if (ctxt->have_exception) {
5561 * #UD should result in just EMULATION_FAILED, and trap-like
5562 * exception should not be encountered during decode.
5564 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
5565 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
5566 inject_emulated_exception(vcpu);
5567 return EMULATE_DONE;
5569 if (emulation_type & EMULTYPE_SKIP)
5570 return EMULATE_FAIL;
5571 return handle_emulation_failure(vcpu);
5575 if (emulation_type & EMULTYPE_SKIP) {
5576 kvm_rip_write(vcpu, ctxt->_eip);
5577 if (ctxt->eflags & X86_EFLAGS_RF)
5578 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
5579 return EMULATE_DONE;
5582 if (retry_instruction(ctxt, cr2, emulation_type))
5583 return EMULATE_DONE;
5585 /* this is needed for vmware backdoor interface to work since it
5586 changes registers values during IO operation */
5587 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
5588 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5589 emulator_invalidate_register_cache(ctxt);
5593 r = x86_emulate_insn(ctxt);
5595 if (r == EMULATION_INTERCEPTED)
5596 return EMULATE_DONE;
5598 if (r == EMULATION_FAILED) {
5599 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5601 return EMULATE_DONE;
5603 return handle_emulation_failure(vcpu);
5606 if (ctxt->have_exception) {
5608 if (inject_emulated_exception(vcpu))
5610 } else if (vcpu->arch.pio.count) {
5611 if (!vcpu->arch.pio.in) {
5612 /* FIXME: return into emulator if single-stepping. */
5613 vcpu->arch.pio.count = 0;
5616 vcpu->arch.complete_userspace_io = complete_emulated_pio;
5618 r = EMULATE_USER_EXIT;
5619 } else if (vcpu->mmio_needed) {
5620 if (!vcpu->mmio_is_write)
5622 r = EMULATE_USER_EXIT;
5623 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
5624 } else if (r == EMULATION_RESTART)
5630 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5631 toggle_interruptibility(vcpu, ctxt->interruptibility);
5632 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5633 if (!ctxt->have_exception ||
5634 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
5635 kvm_rip_write(vcpu, ctxt->eip);
5636 if (r == EMULATE_DONE && ctxt->tf)
5637 kvm_vcpu_do_singlestep(vcpu, &r);
5638 __kvm_set_rflags(vcpu, ctxt->eflags);
5642 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
5643 * do nothing, and it will be requested again as soon as
5644 * the shadow expires. But we still need to check here,
5645 * because POPF has no interrupt shadow.
5647 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
5648 kvm_make_request(KVM_REQ_EVENT, vcpu);
5650 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5654 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5656 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5658 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5659 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5660 size, port, &val, 1);
5661 /* do not return to emulator after return from userspace */
5662 vcpu->arch.pio.count = 0;
5665 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5667 static void tsc_bad(void *info)
5669 __this_cpu_write(cpu_tsc_khz, 0);
5672 static void tsc_khz_changed(void *data)
5674 struct cpufreq_freqs *freq = data;
5675 unsigned long khz = 0;
5679 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5680 khz = cpufreq_quick_get(raw_smp_processor_id());
5683 __this_cpu_write(cpu_tsc_khz, khz);
5686 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5689 struct cpufreq_freqs *freq = data;
5691 struct kvm_vcpu *vcpu;
5692 int i, send_ipi = 0;
5695 * We allow guests to temporarily run on slowing clocks,
5696 * provided we notify them after, or to run on accelerating
5697 * clocks, provided we notify them before. Thus time never
5700 * However, we have a problem. We can't atomically update
5701 * the frequency of a given CPU from this function; it is
5702 * merely a notifier, which can be called from any CPU.
5703 * Changing the TSC frequency at arbitrary points in time
5704 * requires a recomputation of local variables related to
5705 * the TSC for each VCPU. We must flag these local variables
5706 * to be updated and be sure the update takes place with the
5707 * new frequency before any guests proceed.
5709 * Unfortunately, the combination of hotplug CPU and frequency
5710 * change creates an intractable locking scenario; the order
5711 * of when these callouts happen is undefined with respect to
5712 * CPU hotplug, and they can race with each other. As such,
5713 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5714 * undefined; you can actually have a CPU frequency change take
5715 * place in between the computation of X and the setting of the
5716 * variable. To protect against this problem, all updates of
5717 * the per_cpu tsc_khz variable are done in an interrupt
5718 * protected IPI, and all callers wishing to update the value
5719 * must wait for a synchronous IPI to complete (which is trivial
5720 * if the caller is on the CPU already). This establishes the
5721 * necessary total order on variable updates.
5723 * Note that because a guest time update may take place
5724 * anytime after the setting of the VCPU's request bit, the
5725 * correct TSC value must be set before the request. However,
5726 * to ensure the update actually makes it to any guest which
5727 * starts running in hardware virtualization between the set
5728 * and the acquisition of the spinlock, we must also ping the
5729 * CPU after setting the request bit.
5733 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
5735 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
5738 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5740 spin_lock(&kvm_lock);
5741 list_for_each_entry(kvm, &vm_list, vm_list) {
5742 kvm_for_each_vcpu(i, vcpu, kvm) {
5743 if (vcpu->cpu != freq->cpu)
5745 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5746 if (vcpu->cpu != smp_processor_id())
5750 spin_unlock(&kvm_lock);
5752 if (freq->old < freq->new && send_ipi) {
5754 * We upscale the frequency. Must make the guest
5755 * doesn't see old kvmclock values while running with
5756 * the new frequency, otherwise we risk the guest sees
5757 * time go backwards.
5759 * In case we update the frequency for another cpu
5760 * (which might be in guest context) send an interrupt
5761 * to kick the cpu out of guest context. Next time
5762 * guest context is entered kvmclock will be updated,
5763 * so the guest will not see stale values.
5765 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5770 static struct notifier_block kvmclock_cpufreq_notifier_block = {
5771 .notifier_call = kvmclock_cpufreq_notifier
5774 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
5775 unsigned long action, void *hcpu)
5777 unsigned int cpu = (unsigned long)hcpu;
5781 case CPU_DOWN_FAILED:
5782 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5784 case CPU_DOWN_PREPARE:
5785 smp_call_function_single(cpu, tsc_bad, NULL, 1);
5791 static struct notifier_block kvmclock_cpu_notifier_block = {
5792 .notifier_call = kvmclock_cpu_notifier,
5793 .priority = -INT_MAX
5796 static void kvm_timer_init(void)
5800 max_tsc_khz = tsc_khz;
5802 cpu_notifier_register_begin();
5803 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5804 #ifdef CONFIG_CPU_FREQ
5805 struct cpufreq_policy policy;
5806 memset(&policy, 0, sizeof(policy));
5808 cpufreq_get_policy(&policy, cpu);
5809 if (policy.cpuinfo.max_freq)
5810 max_tsc_khz = policy.cpuinfo.max_freq;
5813 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
5814 CPUFREQ_TRANSITION_NOTIFIER);
5816 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
5817 for_each_online_cpu(cpu)
5818 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5820 __register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5821 cpu_notifier_register_done();
5825 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
5827 int kvm_is_in_guest(void)
5829 return __this_cpu_read(current_vcpu) != NULL;
5832 static int kvm_is_user_mode(void)
5836 if (__this_cpu_read(current_vcpu))
5837 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
5839 return user_mode != 0;
5842 static unsigned long kvm_get_guest_ip(void)
5844 unsigned long ip = 0;
5846 if (__this_cpu_read(current_vcpu))
5847 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
5852 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5853 .is_in_guest = kvm_is_in_guest,
5854 .is_user_mode = kvm_is_user_mode,
5855 .get_guest_ip = kvm_get_guest_ip,
5858 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
5860 __this_cpu_write(current_vcpu, vcpu);
5862 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
5864 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
5866 __this_cpu_write(current_vcpu, NULL);
5868 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
5870 static void kvm_set_mmio_spte_mask(void)
5873 int maxphyaddr = boot_cpu_data.x86_phys_bits;
5876 * Set the reserved bits and the present bit of an paging-structure
5877 * entry to generate page fault with PFER.RSV = 1.
5879 /* Mask the reserved physical address bits. */
5880 mask = rsvd_bits(maxphyaddr, 51);
5882 /* Bit 62 is always reserved for 32bit host. */
5883 mask |= 0x3ull << 62;
5885 /* Set the present bit. */
5889 * If reserved bit is not supported, clear the present bit to disable
5892 if (maxphyaddr == 52)
5895 kvm_mmu_set_mmio_spte_mask(mask);
5898 #ifdef CONFIG_X86_64
5899 static void pvclock_gtod_update_fn(struct work_struct *work)
5903 struct kvm_vcpu *vcpu;
5906 spin_lock(&kvm_lock);
5907 list_for_each_entry(kvm, &vm_list, vm_list)
5908 kvm_for_each_vcpu(i, vcpu, kvm)
5909 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
5910 atomic_set(&kvm_guest_has_master_clock, 0);
5911 spin_unlock(&kvm_lock);
5914 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
5917 * Notification about pvclock gtod data update.
5919 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
5922 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
5923 struct timekeeper *tk = priv;
5925 update_pvclock_gtod(tk);
5927 /* disable master clock if host does not trust, or does not
5928 * use, TSC clocksource
5930 if (gtod->clock.vclock_mode != VCLOCK_TSC &&
5931 atomic_read(&kvm_guest_has_master_clock) != 0)
5932 queue_work(system_long_wq, &pvclock_gtod_work);
5937 static struct notifier_block pvclock_gtod_notifier = {
5938 .notifier_call = pvclock_gtod_notify,
5942 int kvm_arch_init(void *opaque)
5945 struct kvm_x86_ops *ops = opaque;
5948 printk(KERN_ERR "kvm: already loaded the other module\n");
5953 if (!ops->cpu_has_kvm_support()) {
5954 printk(KERN_ERR "kvm: no hardware support\n");
5958 if (ops->disabled_by_bios()) {
5959 printk(KERN_ERR "kvm: disabled by bios\n");
5965 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
5967 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
5971 r = kvm_mmu_module_init();
5973 goto out_free_percpu;
5975 kvm_set_mmio_spte_mask();
5979 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
5980 PT_DIRTY_MASK, PT64_NX_MASK, 0);
5984 perf_register_guest_info_callbacks(&kvm_guest_cbs);
5987 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
5990 #ifdef CONFIG_X86_64
5991 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
5997 free_percpu(shared_msrs);
6002 void kvm_arch_exit(void)
6005 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
6007 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6008 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
6009 CPUFREQ_TRANSITION_NOTIFIER);
6010 unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
6011 #ifdef CONFIG_X86_64
6012 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
6015 kvm_mmu_module_exit();
6016 free_percpu(shared_msrs);
6019 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
6021 ++vcpu->stat.halt_exits;
6022 if (lapic_in_kernel(vcpu)) {
6023 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
6026 vcpu->run->exit_reason = KVM_EXIT_HLT;
6030 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
6032 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
6034 kvm_x86_ops->skip_emulated_instruction(vcpu);
6035 return kvm_vcpu_halt(vcpu);
6037 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
6040 * kvm_pv_kick_cpu_op: Kick a vcpu.
6042 * @apicid - apicid of vcpu to be kicked.
6044 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
6046 struct kvm_lapic_irq lapic_irq;
6048 lapic_irq.shorthand = 0;
6049 lapic_irq.dest_mode = 0;
6050 lapic_irq.dest_id = apicid;
6051 lapic_irq.msi_redir_hint = false;
6053 lapic_irq.delivery_mode = APIC_DM_REMRD;
6054 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
6057 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
6059 unsigned long nr, a0, a1, a2, a3, ret;
6060 int op_64_bit, r = 1;
6062 kvm_x86_ops->skip_emulated_instruction(vcpu);
6064 if (kvm_hv_hypercall_enabled(vcpu->kvm))
6065 return kvm_hv_hypercall(vcpu);
6067 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
6068 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
6069 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
6070 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
6071 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
6073 trace_kvm_hypercall(nr, a0, a1, a2, a3);
6075 op_64_bit = is_64_bit_mode(vcpu);
6084 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
6090 case KVM_HC_VAPIC_POLL_IRQ:
6093 case KVM_HC_KICK_CPU:
6094 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
6104 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
6105 ++vcpu->stat.hypercalls;
6108 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
6110 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
6112 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6113 char instruction[3];
6114 unsigned long rip = kvm_rip_read(vcpu);
6116 kvm_x86_ops->patch_hypercall(vcpu, instruction);
6118 return emulator_write_emulated(ctxt, rip, instruction, 3,
6122 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
6124 return vcpu->run->request_interrupt_window &&
6125 likely(!pic_in_kernel(vcpu->kvm));
6128 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
6130 struct kvm_run *kvm_run = vcpu->run;
6132 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
6133 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
6134 kvm_run->cr8 = kvm_get_cr8(vcpu);
6135 kvm_run->apic_base = kvm_get_apic_base(vcpu);
6136 kvm_run->ready_for_interrupt_injection =
6137 pic_in_kernel(vcpu->kvm) ||
6138 kvm_vcpu_ready_for_interrupt_injection(vcpu);
6141 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
6145 if (!kvm_x86_ops->update_cr8_intercept)
6148 if (!vcpu->arch.apic)
6151 if (!vcpu->arch.apic->vapic_addr)
6152 max_irr = kvm_lapic_find_highest_irr(vcpu);
6159 tpr = kvm_lapic_get_cr8(vcpu);
6161 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
6164 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
6168 /* try to reinject previous events if any */
6169 if (vcpu->arch.exception.pending) {
6170 trace_kvm_inj_exception(vcpu->arch.exception.nr,
6171 vcpu->arch.exception.has_error_code,
6172 vcpu->arch.exception.error_code);
6174 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
6175 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
6178 if (vcpu->arch.exception.nr == DB_VECTOR &&
6179 (vcpu->arch.dr7 & DR7_GD)) {
6180 vcpu->arch.dr7 &= ~DR7_GD;
6181 kvm_update_dr7(vcpu);
6184 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
6185 vcpu->arch.exception.has_error_code,
6186 vcpu->arch.exception.error_code,
6187 vcpu->arch.exception.reinject);
6191 if (vcpu->arch.nmi_injected) {
6192 kvm_x86_ops->set_nmi(vcpu);
6196 if (vcpu->arch.interrupt.pending) {
6197 kvm_x86_ops->set_irq(vcpu);
6201 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6202 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6207 /* try to inject new event if pending */
6208 if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
6209 --vcpu->arch.nmi_pending;
6210 vcpu->arch.nmi_injected = true;
6211 kvm_x86_ops->set_nmi(vcpu);
6212 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
6214 * Because interrupts can be injected asynchronously, we are
6215 * calling check_nested_events again here to avoid a race condition.
6216 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
6217 * proposal and current concerns. Perhaps we should be setting
6218 * KVM_REQ_EVENT only on certain events and not unconditionally?
6220 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6221 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6225 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
6226 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
6228 kvm_x86_ops->set_irq(vcpu);
6234 static void process_nmi(struct kvm_vcpu *vcpu)
6239 * x86 is limited to one NMI running, and one NMI pending after it.
6240 * If an NMI is already in progress, limit further NMIs to just one.
6241 * Otherwise, allow two (and we'll inject the first one immediately).
6243 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
6246 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
6247 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
6248 kvm_make_request(KVM_REQ_EVENT, vcpu);
6251 #define put_smstate(type, buf, offset, val) \
6252 *(type *)((buf) + (offset) - 0x7e00) = val
6254 static u32 process_smi_get_segment_flags(struct kvm_segment *seg)
6257 flags |= seg->g << 23;
6258 flags |= seg->db << 22;
6259 flags |= seg->l << 21;
6260 flags |= seg->avl << 20;
6261 flags |= seg->present << 15;
6262 flags |= seg->dpl << 13;
6263 flags |= seg->s << 12;
6264 flags |= seg->type << 8;
6268 static void process_smi_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
6270 struct kvm_segment seg;
6273 kvm_get_segment(vcpu, &seg, n);
6274 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
6277 offset = 0x7f84 + n * 12;
6279 offset = 0x7f2c + (n - 3) * 12;
6281 put_smstate(u32, buf, offset + 8, seg.base);
6282 put_smstate(u32, buf, offset + 4, seg.limit);
6283 put_smstate(u32, buf, offset, process_smi_get_segment_flags(&seg));
6286 #ifdef CONFIG_X86_64
6287 static void process_smi_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
6289 struct kvm_segment seg;
6293 kvm_get_segment(vcpu, &seg, n);
6294 offset = 0x7e00 + n * 16;
6296 flags = process_smi_get_segment_flags(&seg) >> 8;
6297 put_smstate(u16, buf, offset, seg.selector);
6298 put_smstate(u16, buf, offset + 2, flags);
6299 put_smstate(u32, buf, offset + 4, seg.limit);
6300 put_smstate(u64, buf, offset + 8, seg.base);
6304 static void process_smi_save_state_32(struct kvm_vcpu *vcpu, char *buf)
6307 struct kvm_segment seg;
6311 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
6312 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
6313 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
6314 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
6316 for (i = 0; i < 8; i++)
6317 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
6319 kvm_get_dr(vcpu, 6, &val);
6320 put_smstate(u32, buf, 0x7fcc, (u32)val);
6321 kvm_get_dr(vcpu, 7, &val);
6322 put_smstate(u32, buf, 0x7fc8, (u32)val);
6324 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6325 put_smstate(u32, buf, 0x7fc4, seg.selector);
6326 put_smstate(u32, buf, 0x7f64, seg.base);
6327 put_smstate(u32, buf, 0x7f60, seg.limit);
6328 put_smstate(u32, buf, 0x7f5c, process_smi_get_segment_flags(&seg));
6330 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6331 put_smstate(u32, buf, 0x7fc0, seg.selector);
6332 put_smstate(u32, buf, 0x7f80, seg.base);
6333 put_smstate(u32, buf, 0x7f7c, seg.limit);
6334 put_smstate(u32, buf, 0x7f78, process_smi_get_segment_flags(&seg));
6336 kvm_x86_ops->get_gdt(vcpu, &dt);
6337 put_smstate(u32, buf, 0x7f74, dt.address);
6338 put_smstate(u32, buf, 0x7f70, dt.size);
6340 kvm_x86_ops->get_idt(vcpu, &dt);
6341 put_smstate(u32, buf, 0x7f58, dt.address);
6342 put_smstate(u32, buf, 0x7f54, dt.size);
6344 for (i = 0; i < 6; i++)
6345 process_smi_save_seg_32(vcpu, buf, i);
6347 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
6350 put_smstate(u32, buf, 0x7efc, 0x00020000);
6351 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
6354 static void process_smi_save_state_64(struct kvm_vcpu *vcpu, char *buf)
6356 #ifdef CONFIG_X86_64
6358 struct kvm_segment seg;
6362 for (i = 0; i < 16; i++)
6363 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
6365 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
6366 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
6368 kvm_get_dr(vcpu, 6, &val);
6369 put_smstate(u64, buf, 0x7f68, val);
6370 kvm_get_dr(vcpu, 7, &val);
6371 put_smstate(u64, buf, 0x7f60, val);
6373 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
6374 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
6375 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
6377 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
6380 put_smstate(u32, buf, 0x7efc, 0x00020064);
6382 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
6384 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6385 put_smstate(u16, buf, 0x7e90, seg.selector);
6386 put_smstate(u16, buf, 0x7e92, process_smi_get_segment_flags(&seg) >> 8);
6387 put_smstate(u32, buf, 0x7e94, seg.limit);
6388 put_smstate(u64, buf, 0x7e98, seg.base);
6390 kvm_x86_ops->get_idt(vcpu, &dt);
6391 put_smstate(u32, buf, 0x7e84, dt.size);
6392 put_smstate(u64, buf, 0x7e88, dt.address);
6394 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6395 put_smstate(u16, buf, 0x7e70, seg.selector);
6396 put_smstate(u16, buf, 0x7e72, process_smi_get_segment_flags(&seg) >> 8);
6397 put_smstate(u32, buf, 0x7e74, seg.limit);
6398 put_smstate(u64, buf, 0x7e78, seg.base);
6400 kvm_x86_ops->get_gdt(vcpu, &dt);
6401 put_smstate(u32, buf, 0x7e64, dt.size);
6402 put_smstate(u64, buf, 0x7e68, dt.address);
6404 for (i = 0; i < 6; i++)
6405 process_smi_save_seg_64(vcpu, buf, i);
6411 static void process_smi(struct kvm_vcpu *vcpu)
6413 struct kvm_segment cs, ds;
6419 vcpu->arch.smi_pending = true;
6423 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
6424 vcpu->arch.hflags |= HF_SMM_MASK;
6425 memset(buf, 0, 512);
6426 if (guest_cpuid_has_longmode(vcpu))
6427 process_smi_save_state_64(vcpu, buf);
6429 process_smi_save_state_32(vcpu, buf);
6431 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
6433 if (kvm_x86_ops->get_nmi_mask(vcpu))
6434 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
6436 kvm_x86_ops->set_nmi_mask(vcpu, true);
6438 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6439 kvm_rip_write(vcpu, 0x8000);
6441 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
6442 kvm_x86_ops->set_cr0(vcpu, cr0);
6443 vcpu->arch.cr0 = cr0;
6445 kvm_x86_ops->set_cr4(vcpu, 0);
6447 /* Undocumented: IDT limit is set to zero on entry to SMM. */
6448 dt.address = dt.size = 0;
6449 kvm_x86_ops->set_idt(vcpu, &dt);
6451 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
6453 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
6454 cs.base = vcpu->arch.smbase;
6459 cs.limit = ds.limit = 0xffffffff;
6460 cs.type = ds.type = 0x3;
6461 cs.dpl = ds.dpl = 0;
6466 cs.avl = ds.avl = 0;
6467 cs.present = ds.present = 1;
6468 cs.unusable = ds.unusable = 0;
6469 cs.padding = ds.padding = 0;
6471 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
6472 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
6473 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
6474 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
6475 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
6476 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
6478 if (guest_cpuid_has_longmode(vcpu))
6479 kvm_x86_ops->set_efer(vcpu, 0);
6481 kvm_update_cpuid(vcpu);
6482 kvm_mmu_reset_context(vcpu);
6485 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
6487 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
6490 memset(vcpu->arch.eoi_exit_bitmap, 0, 256 / 8);
6492 if (irqchip_split(vcpu->kvm))
6493 kvm_scan_ioapic_routes(vcpu, vcpu->arch.eoi_exit_bitmap);
6495 kvm_x86_ops->sync_pir_to_irr(vcpu);
6496 if (ioapic_in_kernel(vcpu->kvm))
6497 kvm_ioapic_scan_entry(vcpu, vcpu->arch.eoi_exit_bitmap);
6499 kvm_x86_ops->load_eoi_exitmap(vcpu);
6502 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu)
6504 ++vcpu->stat.tlb_flush;
6505 kvm_x86_ops->tlb_flush(vcpu);
6508 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
6510 struct page *page = NULL;
6512 if (!lapic_in_kernel(vcpu))
6515 if (!kvm_x86_ops->set_apic_access_page_addr)
6518 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6519 if (is_error_page(page))
6521 kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
6524 * Do not pin apic access page in memory, the MMU notifier
6525 * will call us again if it is migrated or swapped out.
6529 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
6531 void kvm_arch_mmu_notifier_invalidate_page(struct kvm *kvm,
6532 unsigned long address)
6535 * The physical address of apic access page is stored in the VMCS.
6536 * Update it when it becomes invalid.
6538 if (address == gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT))
6539 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
6543 * Returns 1 to let vcpu_run() continue the guest execution loop without
6544 * exiting to the userspace. Otherwise, the value will be returned to the
6547 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
6551 dm_request_for_irq_injection(vcpu) &&
6552 kvm_cpu_accept_dm_intr(vcpu);
6554 bool req_immediate_exit = false;
6556 if (vcpu->requests) {
6557 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
6558 kvm_mmu_unload(vcpu);
6559 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
6560 __kvm_migrate_timers(vcpu);
6561 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
6562 kvm_gen_update_masterclock(vcpu->kvm);
6563 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
6564 kvm_gen_kvmclock_update(vcpu);
6565 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
6566 r = kvm_guest_time_update(vcpu);
6570 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
6571 kvm_mmu_sync_roots(vcpu);
6572 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
6573 kvm_vcpu_flush_tlb(vcpu);
6574 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
6575 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
6579 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
6580 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6581 vcpu->mmio_needed = 0;
6585 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
6586 vcpu->fpu_active = 0;
6587 kvm_x86_ops->fpu_deactivate(vcpu);
6589 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
6590 /* Page is swapped out. Do synthetic halt */
6591 vcpu->arch.apf.halted = true;
6595 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
6596 record_steal_time(vcpu);
6597 if (kvm_check_request(KVM_REQ_SMI, vcpu))
6599 if (kvm_check_request(KVM_REQ_NMI, vcpu))
6601 if (kvm_check_request(KVM_REQ_PMU, vcpu))
6602 kvm_pmu_handle_event(vcpu);
6603 if (kvm_check_request(KVM_REQ_PMI, vcpu))
6604 kvm_pmu_deliver_pmi(vcpu);
6605 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
6606 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
6607 if (test_bit(vcpu->arch.pending_ioapic_eoi,
6608 (void *) vcpu->arch.eoi_exit_bitmap)) {
6609 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
6610 vcpu->run->eoi.vector =
6611 vcpu->arch.pending_ioapic_eoi;
6616 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
6617 vcpu_scan_ioapic(vcpu);
6618 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
6619 kvm_vcpu_reload_apic_access_page(vcpu);
6620 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
6621 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6622 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
6626 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
6627 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6628 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
6635 * KVM_REQ_EVENT is not set when posted interrupts are set by
6636 * VT-d hardware, so we have to update RVI unconditionally.
6638 if (kvm_lapic_enabled(vcpu)) {
6640 * Update architecture specific hints for APIC
6641 * virtual interrupt delivery.
6643 if (kvm_x86_ops->hwapic_irr_update)
6644 kvm_x86_ops->hwapic_irr_update(vcpu,
6645 kvm_lapic_find_highest_irr(vcpu));
6648 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
6649 kvm_apic_accept_events(vcpu);
6650 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
6655 if (inject_pending_event(vcpu, req_int_win) != 0)
6656 req_immediate_exit = true;
6657 /* enable NMI/IRQ window open exits if needed */
6659 if (vcpu->arch.nmi_pending)
6660 kvm_x86_ops->enable_nmi_window(vcpu);
6661 if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
6662 kvm_x86_ops->enable_irq_window(vcpu);
6665 if (kvm_lapic_enabled(vcpu)) {
6666 update_cr8_intercept(vcpu);
6667 kvm_lapic_sync_to_vapic(vcpu);
6671 r = kvm_mmu_reload(vcpu);
6673 goto cancel_injection;
6678 kvm_x86_ops->prepare_guest_switch(vcpu);
6679 if (vcpu->fpu_active)
6680 kvm_load_guest_fpu(vcpu);
6681 vcpu->mode = IN_GUEST_MODE;
6683 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6685 /* We should set ->mode before check ->requests,
6686 * see the comment in make_all_cpus_request.
6688 smp_mb__after_srcu_read_unlock();
6690 local_irq_disable();
6692 if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
6693 || need_resched() || signal_pending(current)) {
6694 vcpu->mode = OUTSIDE_GUEST_MODE;
6698 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6700 goto cancel_injection;
6703 kvm_load_guest_xcr0(vcpu);
6705 if (req_immediate_exit)
6706 smp_send_reschedule(vcpu->cpu);
6708 trace_kvm_entry(vcpu->vcpu_id);
6709 wait_lapic_expire(vcpu);
6710 __kvm_guest_enter();
6712 if (unlikely(vcpu->arch.switch_db_regs)) {
6714 set_debugreg(vcpu->arch.eff_db[0], 0);
6715 set_debugreg(vcpu->arch.eff_db[1], 1);
6716 set_debugreg(vcpu->arch.eff_db[2], 2);
6717 set_debugreg(vcpu->arch.eff_db[3], 3);
6718 set_debugreg(vcpu->arch.dr6, 6);
6719 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6722 kvm_x86_ops->run(vcpu);
6725 * Do this here before restoring debug registers on the host. And
6726 * since we do this before handling the vmexit, a DR access vmexit
6727 * can (a) read the correct value of the debug registers, (b) set
6728 * KVM_DEBUGREG_WONT_EXIT again.
6730 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
6731 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
6732 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
6733 kvm_update_dr0123(vcpu);
6734 kvm_update_dr6(vcpu);
6735 kvm_update_dr7(vcpu);
6736 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6740 * If the guest has used debug registers, at least dr7
6741 * will be disabled while returning to the host.
6742 * If we don't have active breakpoints in the host, we don't
6743 * care about the messed up debug address registers. But if
6744 * we have some of them active, restore the old state.
6746 if (hw_breakpoint_active())
6747 hw_breakpoint_restore();
6749 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
6751 vcpu->mode = OUTSIDE_GUEST_MODE;
6754 kvm_put_guest_xcr0(vcpu);
6756 /* Interrupt is enabled by handle_external_intr() */
6757 kvm_x86_ops->handle_external_intr(vcpu);
6762 * We must have an instruction between local_irq_enable() and
6763 * kvm_guest_exit(), so the timer interrupt isn't delayed by
6764 * the interrupt shadow. The stat.exits increment will do nicely.
6765 * But we need to prevent reordering, hence this barrier():
6773 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6776 * Profile KVM exit RIPs:
6778 if (unlikely(prof_on == KVM_PROFILING)) {
6779 unsigned long rip = kvm_rip_read(vcpu);
6780 profile_hit(KVM_PROFILING, (void *)rip);
6783 if (unlikely(vcpu->arch.tsc_always_catchup))
6784 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6786 if (vcpu->arch.apic_attention)
6787 kvm_lapic_sync_from_vapic(vcpu);
6789 r = kvm_x86_ops->handle_exit(vcpu);
6793 kvm_x86_ops->cancel_injection(vcpu);
6794 if (unlikely(vcpu->arch.apic_attention))
6795 kvm_lapic_sync_from_vapic(vcpu);
6800 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
6802 if (!kvm_arch_vcpu_runnable(vcpu) &&
6803 (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
6804 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6805 kvm_vcpu_block(vcpu);
6806 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6808 if (kvm_x86_ops->post_block)
6809 kvm_x86_ops->post_block(vcpu);
6811 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
6815 kvm_apic_accept_events(vcpu);
6816 switch(vcpu->arch.mp_state) {
6817 case KVM_MP_STATE_HALTED:
6818 vcpu->arch.pv.pv_unhalted = false;
6819 vcpu->arch.mp_state =
6820 KVM_MP_STATE_RUNNABLE;
6821 case KVM_MP_STATE_RUNNABLE:
6822 vcpu->arch.apf.halted = false;
6824 case KVM_MP_STATE_INIT_RECEIVED:
6833 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
6835 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6836 !vcpu->arch.apf.halted);
6839 static int vcpu_run(struct kvm_vcpu *vcpu)
6842 struct kvm *kvm = vcpu->kvm;
6844 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6847 if (kvm_vcpu_running(vcpu)) {
6848 r = vcpu_enter_guest(vcpu);
6850 r = vcpu_block(kvm, vcpu);
6856 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
6857 if (kvm_cpu_has_pending_timer(vcpu))
6858 kvm_inject_pending_timer_irqs(vcpu);
6860 if (dm_request_for_irq_injection(vcpu) &&
6861 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
6863 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
6864 ++vcpu->stat.request_irq_exits;
6868 kvm_check_async_pf_completion(vcpu);
6870 if (signal_pending(current)) {
6872 vcpu->run->exit_reason = KVM_EXIT_INTR;
6873 ++vcpu->stat.signal_exits;
6876 if (need_resched()) {
6877 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6879 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6883 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6888 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
6891 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6892 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
6893 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6894 if (r != EMULATE_DONE)
6899 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
6901 BUG_ON(!vcpu->arch.pio.count);
6903 return complete_emulated_io(vcpu);
6907 * Implements the following, as a state machine:
6911 * for each mmio piece in the fragment
6919 * for each mmio piece in the fragment
6924 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
6926 struct kvm_run *run = vcpu->run;
6927 struct kvm_mmio_fragment *frag;
6930 BUG_ON(!vcpu->mmio_needed);
6932 /* Complete previous fragment */
6933 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
6934 len = min(8u, frag->len);
6935 if (!vcpu->mmio_is_write)
6936 memcpy(frag->data, run->mmio.data, len);
6938 if (frag->len <= 8) {
6939 /* Switch to the next fragment. */
6941 vcpu->mmio_cur_fragment++;
6943 /* Go forward to the next mmio piece. */
6949 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
6950 vcpu->mmio_needed = 0;
6952 /* FIXME: return into emulator if single-stepping. */
6953 if (vcpu->mmio_is_write)
6955 vcpu->mmio_read_completed = 1;
6956 return complete_emulated_io(vcpu);
6959 run->exit_reason = KVM_EXIT_MMIO;
6960 run->mmio.phys_addr = frag->gpa;
6961 if (vcpu->mmio_is_write)
6962 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
6963 run->mmio.len = min(8u, frag->len);
6964 run->mmio.is_write = vcpu->mmio_is_write;
6965 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6970 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
6972 struct fpu *fpu = ¤t->thread.fpu;
6976 fpu__activate_curr(fpu);
6978 if (vcpu->sigset_active)
6979 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
6981 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
6982 kvm_vcpu_block(vcpu);
6983 kvm_apic_accept_events(vcpu);
6984 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
6989 /* re-sync apic's tpr */
6990 if (!lapic_in_kernel(vcpu)) {
6991 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
6997 if (unlikely(vcpu->arch.complete_userspace_io)) {
6998 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
6999 vcpu->arch.complete_userspace_io = NULL;
7004 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
7009 post_kvm_run_save(vcpu);
7010 if (vcpu->sigset_active)
7011 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
7016 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7018 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
7020 * We are here if userspace calls get_regs() in the middle of
7021 * instruction emulation. Registers state needs to be copied
7022 * back from emulation context to vcpu. Userspace shouldn't do
7023 * that usually, but some bad designed PV devices (vmware
7024 * backdoor interface) need this to work
7026 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
7027 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7029 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
7030 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
7031 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
7032 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
7033 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
7034 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
7035 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
7036 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
7037 #ifdef CONFIG_X86_64
7038 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
7039 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
7040 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
7041 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
7042 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
7043 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
7044 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
7045 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
7048 regs->rip = kvm_rip_read(vcpu);
7049 regs->rflags = kvm_get_rflags(vcpu);
7054 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7056 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
7057 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7059 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
7060 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
7061 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
7062 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
7063 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
7064 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
7065 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
7066 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
7067 #ifdef CONFIG_X86_64
7068 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
7069 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
7070 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
7071 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
7072 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
7073 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
7074 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
7075 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
7078 kvm_rip_write(vcpu, regs->rip);
7079 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
7081 vcpu->arch.exception.pending = false;
7083 kvm_make_request(KVM_REQ_EVENT, vcpu);
7088 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
7090 struct kvm_segment cs;
7092 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7096 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
7098 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
7099 struct kvm_sregs *sregs)
7103 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7104 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7105 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7106 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7107 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7108 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7110 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7111 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7113 kvm_x86_ops->get_idt(vcpu, &dt);
7114 sregs->idt.limit = dt.size;
7115 sregs->idt.base = dt.address;
7116 kvm_x86_ops->get_gdt(vcpu, &dt);
7117 sregs->gdt.limit = dt.size;
7118 sregs->gdt.base = dt.address;
7120 sregs->cr0 = kvm_read_cr0(vcpu);
7121 sregs->cr2 = vcpu->arch.cr2;
7122 sregs->cr3 = kvm_read_cr3(vcpu);
7123 sregs->cr4 = kvm_read_cr4(vcpu);
7124 sregs->cr8 = kvm_get_cr8(vcpu);
7125 sregs->efer = vcpu->arch.efer;
7126 sregs->apic_base = kvm_get_apic_base(vcpu);
7128 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
7130 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
7131 set_bit(vcpu->arch.interrupt.nr,
7132 (unsigned long *)sregs->interrupt_bitmap);
7137 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
7138 struct kvm_mp_state *mp_state)
7140 kvm_apic_accept_events(vcpu);
7141 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
7142 vcpu->arch.pv.pv_unhalted)
7143 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
7145 mp_state->mp_state = vcpu->arch.mp_state;
7150 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
7151 struct kvm_mp_state *mp_state)
7153 if (!kvm_vcpu_has_lapic(vcpu) &&
7154 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
7157 /* INITs are latched while in SMM */
7158 if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
7159 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
7160 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
7163 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
7164 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
7165 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
7167 vcpu->arch.mp_state = mp_state->mp_state;
7168 kvm_make_request(KVM_REQ_EVENT, vcpu);
7172 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
7173 int reason, bool has_error_code, u32 error_code)
7175 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
7178 init_emulate_ctxt(vcpu);
7180 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
7181 has_error_code, error_code);
7184 return EMULATE_FAIL;
7186 kvm_rip_write(vcpu, ctxt->eip);
7187 kvm_set_rflags(vcpu, ctxt->eflags);
7188 kvm_make_request(KVM_REQ_EVENT, vcpu);
7189 return EMULATE_DONE;
7191 EXPORT_SYMBOL_GPL(kvm_task_switch);
7193 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
7194 struct kvm_sregs *sregs)
7196 struct msr_data apic_base_msr;
7197 int mmu_reset_needed = 0;
7198 int pending_vec, max_bits, idx;
7201 if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
7204 dt.size = sregs->idt.limit;
7205 dt.address = sregs->idt.base;
7206 kvm_x86_ops->set_idt(vcpu, &dt);
7207 dt.size = sregs->gdt.limit;
7208 dt.address = sregs->gdt.base;
7209 kvm_x86_ops->set_gdt(vcpu, &dt);
7211 vcpu->arch.cr2 = sregs->cr2;
7212 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
7213 vcpu->arch.cr3 = sregs->cr3;
7214 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
7216 kvm_set_cr8(vcpu, sregs->cr8);
7218 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
7219 kvm_x86_ops->set_efer(vcpu, sregs->efer);
7220 apic_base_msr.data = sregs->apic_base;
7221 apic_base_msr.host_initiated = true;
7222 kvm_set_apic_base(vcpu, &apic_base_msr);
7224 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
7225 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
7226 vcpu->arch.cr0 = sregs->cr0;
7228 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
7229 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
7230 if (sregs->cr4 & X86_CR4_OSXSAVE)
7231 kvm_update_cpuid(vcpu);
7233 idx = srcu_read_lock(&vcpu->kvm->srcu);
7234 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu)) {
7235 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
7236 mmu_reset_needed = 1;
7238 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7240 if (mmu_reset_needed)
7241 kvm_mmu_reset_context(vcpu);
7243 max_bits = KVM_NR_INTERRUPTS;
7244 pending_vec = find_first_bit(
7245 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
7246 if (pending_vec < max_bits) {
7247 kvm_queue_interrupt(vcpu, pending_vec, false);
7248 pr_debug("Set back pending irq %d\n", pending_vec);
7251 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7252 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7253 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7254 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7255 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7256 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7258 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7259 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7261 update_cr8_intercept(vcpu);
7263 /* Older userspace won't unhalt the vcpu on reset. */
7264 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
7265 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
7267 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7269 kvm_make_request(KVM_REQ_EVENT, vcpu);
7274 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
7275 struct kvm_guest_debug *dbg)
7277 unsigned long rflags;
7280 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
7282 if (vcpu->arch.exception.pending)
7284 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
7285 kvm_queue_exception(vcpu, DB_VECTOR);
7287 kvm_queue_exception(vcpu, BP_VECTOR);
7291 * Read rflags as long as potentially injected trace flags are still
7294 rflags = kvm_get_rflags(vcpu);
7296 vcpu->guest_debug = dbg->control;
7297 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
7298 vcpu->guest_debug = 0;
7300 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7301 for (i = 0; i < KVM_NR_DB_REGS; ++i)
7302 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
7303 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
7305 for (i = 0; i < KVM_NR_DB_REGS; i++)
7306 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
7308 kvm_update_dr7(vcpu);
7310 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7311 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
7312 get_segment_base(vcpu, VCPU_SREG_CS);
7315 * Trigger an rflags update that will inject or remove the trace
7318 kvm_set_rflags(vcpu, rflags);
7320 kvm_x86_ops->update_bp_intercept(vcpu);
7330 * Translate a guest virtual address to a guest physical address.
7332 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
7333 struct kvm_translation *tr)
7335 unsigned long vaddr = tr->linear_address;
7339 idx = srcu_read_lock(&vcpu->kvm->srcu);
7340 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
7341 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7342 tr->physical_address = gpa;
7343 tr->valid = gpa != UNMAPPED_GVA;
7350 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7352 struct fxregs_state *fxsave =
7353 &vcpu->arch.guest_fpu.state.fxsave;
7355 memcpy(fpu->fpr, fxsave->st_space, 128);
7356 fpu->fcw = fxsave->cwd;
7357 fpu->fsw = fxsave->swd;
7358 fpu->ftwx = fxsave->twd;
7359 fpu->last_opcode = fxsave->fop;
7360 fpu->last_ip = fxsave->rip;
7361 fpu->last_dp = fxsave->rdp;
7362 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
7367 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7369 struct fxregs_state *fxsave =
7370 &vcpu->arch.guest_fpu.state.fxsave;
7372 memcpy(fxsave->st_space, fpu->fpr, 128);
7373 fxsave->cwd = fpu->fcw;
7374 fxsave->swd = fpu->fsw;
7375 fxsave->twd = fpu->ftwx;
7376 fxsave->fop = fpu->last_opcode;
7377 fxsave->rip = fpu->last_ip;
7378 fxsave->rdp = fpu->last_dp;
7379 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
7384 static void fx_init(struct kvm_vcpu *vcpu)
7386 fpstate_init(&vcpu->arch.guest_fpu.state);
7388 vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
7389 host_xcr0 | XSTATE_COMPACTION_ENABLED;
7392 * Ensure guest xcr0 is valid for loading
7394 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
7396 vcpu->arch.cr0 |= X86_CR0_ET;
7399 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
7401 if (vcpu->guest_fpu_loaded)
7405 * Restore all possible states in the guest,
7406 * and assume host would use all available bits.
7407 * Guest xcr0 would be loaded later.
7409 vcpu->guest_fpu_loaded = 1;
7410 __kernel_fpu_begin();
7411 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state);
7415 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
7417 if (!vcpu->guest_fpu_loaded) {
7418 vcpu->fpu_counter = 0;
7422 vcpu->guest_fpu_loaded = 0;
7423 copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
7425 ++vcpu->stat.fpu_reload;
7429 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
7431 void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
7433 kvmclock_reset(vcpu);
7435 kvm_x86_ops->vcpu_free(vcpu);
7436 free_cpumask_var(wbinvd_dirty_mask);
7439 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
7442 struct kvm_vcpu *vcpu;
7444 if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
7445 printk_once(KERN_WARNING
7446 "kvm: SMP vm created on host with unstable TSC; "
7447 "guest TSC will not be reliable\n");
7449 vcpu = kvm_x86_ops->vcpu_create(kvm, id);
7454 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
7458 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
7459 kvm_vcpu_mtrr_init(vcpu);
7460 r = vcpu_load(vcpu);
7463 kvm_vcpu_reset(vcpu, false);
7464 kvm_mmu_setup(vcpu);
7469 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
7471 struct msr_data msr;
7472 struct kvm *kvm = vcpu->kvm;
7474 if (vcpu_load(vcpu))
7477 msr.index = MSR_IA32_TSC;
7478 msr.host_initiated = true;
7479 kvm_write_tsc(vcpu, &msr);
7482 if (!kvmclock_periodic_sync)
7485 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
7486 KVMCLOCK_SYNC_PERIOD);
7489 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
7492 vcpu->arch.apf.msr_val = 0;
7494 r = vcpu_load(vcpu);
7496 kvm_mmu_unload(vcpu);
7499 kvm_arch_vcpu_free(vcpu);
7502 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
7504 vcpu->arch.hflags = 0;
7506 atomic_set(&vcpu->arch.nmi_queued, 0);
7507 vcpu->arch.nmi_pending = 0;
7508 vcpu->arch.nmi_injected = false;
7509 kvm_clear_interrupt_queue(vcpu);
7510 kvm_clear_exception_queue(vcpu);
7512 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
7513 kvm_update_dr0123(vcpu);
7514 vcpu->arch.dr6 = DR6_INIT;
7515 kvm_update_dr6(vcpu);
7516 vcpu->arch.dr7 = DR7_FIXED_1;
7517 kvm_update_dr7(vcpu);
7521 kvm_make_request(KVM_REQ_EVENT, vcpu);
7522 vcpu->arch.apf.msr_val = 0;
7523 vcpu->arch.st.msr_val = 0;
7525 kvmclock_reset(vcpu);
7527 kvm_clear_async_pf_completion_queue(vcpu);
7528 kvm_async_pf_hash_reset(vcpu);
7529 vcpu->arch.apf.halted = false;
7532 kvm_pmu_reset(vcpu);
7533 vcpu->arch.smbase = 0x30000;
7536 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
7537 vcpu->arch.regs_avail = ~0;
7538 vcpu->arch.regs_dirty = ~0;
7540 kvm_x86_ops->vcpu_reset(vcpu, init_event);
7543 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
7545 struct kvm_segment cs;
7547 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7548 cs.selector = vector << 8;
7549 cs.base = vector << 12;
7550 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7551 kvm_rip_write(vcpu, 0);
7554 int kvm_arch_hardware_enable(void)
7557 struct kvm_vcpu *vcpu;
7562 bool stable, backwards_tsc = false;
7564 kvm_shared_msr_cpu_online();
7565 ret = kvm_x86_ops->hardware_enable();
7569 local_tsc = rdtsc();
7570 stable = !check_tsc_unstable();
7571 list_for_each_entry(kvm, &vm_list, vm_list) {
7572 kvm_for_each_vcpu(i, vcpu, kvm) {
7573 if (!stable && vcpu->cpu == smp_processor_id())
7574 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7575 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
7576 backwards_tsc = true;
7577 if (vcpu->arch.last_host_tsc > max_tsc)
7578 max_tsc = vcpu->arch.last_host_tsc;
7584 * Sometimes, even reliable TSCs go backwards. This happens on
7585 * platforms that reset TSC during suspend or hibernate actions, but
7586 * maintain synchronization. We must compensate. Fortunately, we can
7587 * detect that condition here, which happens early in CPU bringup,
7588 * before any KVM threads can be running. Unfortunately, we can't
7589 * bring the TSCs fully up to date with real time, as we aren't yet far
7590 * enough into CPU bringup that we know how much real time has actually
7591 * elapsed; our helper function, get_kernel_ns() will be using boot
7592 * variables that haven't been updated yet.
7594 * So we simply find the maximum observed TSC above, then record the
7595 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
7596 * the adjustment will be applied. Note that we accumulate
7597 * adjustments, in case multiple suspend cycles happen before some VCPU
7598 * gets a chance to run again. In the event that no KVM threads get a
7599 * chance to run, we will miss the entire elapsed period, as we'll have
7600 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
7601 * loose cycle time. This isn't too big a deal, since the loss will be
7602 * uniform across all VCPUs (not to mention the scenario is extremely
7603 * unlikely). It is possible that a second hibernate recovery happens
7604 * much faster than a first, causing the observed TSC here to be
7605 * smaller; this would require additional padding adjustment, which is
7606 * why we set last_host_tsc to the local tsc observed here.
7608 * N.B. - this code below runs only on platforms with reliable TSC,
7609 * as that is the only way backwards_tsc is set above. Also note
7610 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
7611 * have the same delta_cyc adjustment applied if backwards_tsc
7612 * is detected. Note further, this adjustment is only done once,
7613 * as we reset last_host_tsc on all VCPUs to stop this from being
7614 * called multiple times (one for each physical CPU bringup).
7616 * Platforms with unreliable TSCs don't have to deal with this, they
7617 * will be compensated by the logic in vcpu_load, which sets the TSC to
7618 * catchup mode. This will catchup all VCPUs to real time, but cannot
7619 * guarantee that they stay in perfect synchronization.
7621 if (backwards_tsc) {
7622 u64 delta_cyc = max_tsc - local_tsc;
7623 backwards_tsc_observed = true;
7624 list_for_each_entry(kvm, &vm_list, vm_list) {
7625 kvm_for_each_vcpu(i, vcpu, kvm) {
7626 vcpu->arch.tsc_offset_adjustment += delta_cyc;
7627 vcpu->arch.last_host_tsc = local_tsc;
7628 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7632 * We have to disable TSC offset matching.. if you were
7633 * booting a VM while issuing an S4 host suspend....
7634 * you may have some problem. Solving this issue is
7635 * left as an exercise to the reader.
7637 kvm->arch.last_tsc_nsec = 0;
7638 kvm->arch.last_tsc_write = 0;
7645 void kvm_arch_hardware_disable(void)
7647 kvm_x86_ops->hardware_disable();
7648 drop_user_return_notifiers();
7651 int kvm_arch_hardware_setup(void)
7655 r = kvm_x86_ops->hardware_setup();
7659 if (kvm_has_tsc_control) {
7661 * Make sure the user can only configure tsc_khz values that
7662 * fit into a signed integer.
7663 * A min value is not calculated needed because it will always
7664 * be 1 on all machines.
7666 u64 max = min(0x7fffffffULL,
7667 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
7668 kvm_max_guest_tsc_khz = max;
7670 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
7673 kvm_init_msr_list();
7677 void kvm_arch_hardware_unsetup(void)
7679 kvm_x86_ops->hardware_unsetup();
7682 void kvm_arch_check_processor_compat(void *rtn)
7684 kvm_x86_ops->check_processor_compatibility(rtn);
7687 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
7689 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
7691 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
7693 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
7695 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
7698 bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
7700 return irqchip_in_kernel(vcpu->kvm) == lapic_in_kernel(vcpu);
7703 struct static_key kvm_no_apic_vcpu __read_mostly;
7705 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
7711 BUG_ON(vcpu->kvm == NULL);
7714 vcpu->arch.pv.pv_unhalted = false;
7715 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
7716 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_reset_bsp(vcpu))
7717 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7719 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
7721 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
7726 vcpu->arch.pio_data = page_address(page);
7728 kvm_set_tsc_khz(vcpu, max_tsc_khz);
7730 r = kvm_mmu_create(vcpu);
7732 goto fail_free_pio_data;
7734 if (irqchip_in_kernel(kvm)) {
7735 r = kvm_create_lapic(vcpu);
7737 goto fail_mmu_destroy;
7739 static_key_slow_inc(&kvm_no_apic_vcpu);
7741 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
7743 if (!vcpu->arch.mce_banks) {
7745 goto fail_free_lapic;
7747 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
7749 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
7751 goto fail_free_mce_banks;
7756 vcpu->arch.ia32_tsc_adjust_msr = 0x0;
7757 vcpu->arch.pv_time_enabled = false;
7759 vcpu->arch.guest_supported_xcr0 = 0;
7760 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
7762 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
7764 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
7766 kvm_async_pf_hash_reset(vcpu);
7769 vcpu->arch.pending_external_vector = -1;
7773 fail_free_mce_banks:
7774 kfree(vcpu->arch.mce_banks);
7776 kvm_free_lapic(vcpu);
7778 kvm_mmu_destroy(vcpu);
7780 free_page((unsigned long)vcpu->arch.pio_data);
7785 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
7789 kvm_pmu_destroy(vcpu);
7790 kfree(vcpu->arch.mce_banks);
7791 kvm_free_lapic(vcpu);
7792 idx = srcu_read_lock(&vcpu->kvm->srcu);
7793 kvm_mmu_destroy(vcpu);
7794 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7795 free_page((unsigned long)vcpu->arch.pio_data);
7796 if (!lapic_in_kernel(vcpu))
7797 static_key_slow_dec(&kvm_no_apic_vcpu);
7800 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
7802 kvm_x86_ops->sched_in(vcpu, cpu);
7805 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
7810 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
7811 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
7812 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
7813 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
7814 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
7816 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
7817 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
7818 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
7819 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
7820 &kvm->arch.irq_sources_bitmap);
7822 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
7823 mutex_init(&kvm->arch.apic_map_lock);
7824 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
7826 pvclock_update_vm_gtod_copy(kvm);
7828 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
7829 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
7834 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
7837 r = vcpu_load(vcpu);
7839 kvm_mmu_unload(vcpu);
7843 static void kvm_free_vcpus(struct kvm *kvm)
7846 struct kvm_vcpu *vcpu;
7849 * Unpin any mmu pages first.
7851 kvm_for_each_vcpu(i, vcpu, kvm) {
7852 kvm_clear_async_pf_completion_queue(vcpu);
7853 kvm_unload_vcpu_mmu(vcpu);
7855 kvm_for_each_vcpu(i, vcpu, kvm)
7856 kvm_arch_vcpu_free(vcpu);
7858 mutex_lock(&kvm->lock);
7859 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
7860 kvm->vcpus[i] = NULL;
7862 atomic_set(&kvm->online_vcpus, 0);
7863 mutex_unlock(&kvm->lock);
7866 void kvm_arch_sync_events(struct kvm *kvm)
7868 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
7869 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
7870 kvm_free_all_assigned_devices(kvm);
7874 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7878 struct kvm_memslots *slots = kvm_memslots(kvm);
7879 struct kvm_memory_slot *slot, old;
7881 /* Called with kvm->slots_lock held. */
7882 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
7885 slot = id_to_memslot(slots, id);
7891 * MAP_SHARED to prevent internal slot pages from being moved
7894 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
7895 MAP_SHARED | MAP_ANONYMOUS, 0);
7896 if (IS_ERR((void *)hva))
7897 return PTR_ERR((void *)hva);
7906 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
7907 struct kvm_userspace_memory_region m;
7909 m.slot = id | (i << 16);
7911 m.guest_phys_addr = gpa;
7912 m.userspace_addr = hva;
7913 m.memory_size = size;
7914 r = __kvm_set_memory_region(kvm, &m);
7920 r = vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
7926 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
7928 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7932 mutex_lock(&kvm->slots_lock);
7933 r = __x86_set_memory_region(kvm, id, gpa, size);
7934 mutex_unlock(&kvm->slots_lock);
7938 EXPORT_SYMBOL_GPL(x86_set_memory_region);
7940 void kvm_arch_destroy_vm(struct kvm *kvm)
7942 if (current->mm == kvm->mm) {
7944 * Free memory regions allocated on behalf of userspace,
7945 * unless the the memory map has changed due to process exit
7948 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
7949 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
7950 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
7952 kvm_iommu_unmap_guest(kvm);
7953 kfree(kvm->arch.vpic);
7954 kfree(kvm->arch.vioapic);
7955 kvm_free_vcpus(kvm);
7956 kfree(rcu_dereference_check(kvm->arch.apic_map, 1));
7959 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
7960 struct kvm_memory_slot *dont)
7964 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7965 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
7966 kvfree(free->arch.rmap[i]);
7967 free->arch.rmap[i] = NULL;
7972 if (!dont || free->arch.lpage_info[i - 1] !=
7973 dont->arch.lpage_info[i - 1]) {
7974 kvfree(free->arch.lpage_info[i - 1]);
7975 free->arch.lpage_info[i - 1] = NULL;
7980 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
7981 unsigned long npages)
7985 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7990 lpages = gfn_to_index(slot->base_gfn + npages - 1,
7991 slot->base_gfn, level) + 1;
7993 slot->arch.rmap[i] =
7994 kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
7995 if (!slot->arch.rmap[i])
8000 slot->arch.lpage_info[i - 1] = kvm_kvzalloc(lpages *
8001 sizeof(*slot->arch.lpage_info[i - 1]));
8002 if (!slot->arch.lpage_info[i - 1])
8005 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
8006 slot->arch.lpage_info[i - 1][0].write_count = 1;
8007 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
8008 slot->arch.lpage_info[i - 1][lpages - 1].write_count = 1;
8009 ugfn = slot->userspace_addr >> PAGE_SHIFT;
8011 * If the gfn and userspace address are not aligned wrt each
8012 * other, or if explicitly asked to, disable large page
8013 * support for this slot
8015 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
8016 !kvm_largepages_enabled()) {
8019 for (j = 0; j < lpages; ++j)
8020 slot->arch.lpage_info[i - 1][j].write_count = 1;
8027 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8028 kvfree(slot->arch.rmap[i]);
8029 slot->arch.rmap[i] = NULL;
8033 kvfree(slot->arch.lpage_info[i - 1]);
8034 slot->arch.lpage_info[i - 1] = NULL;
8039 void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
8042 * memslots->generation has been incremented.
8043 * mmio generation may have reached its maximum value.
8045 kvm_mmu_invalidate_mmio_sptes(kvm, slots);
8048 int kvm_arch_prepare_memory_region(struct kvm *kvm,
8049 struct kvm_memory_slot *memslot,
8050 const struct kvm_userspace_memory_region *mem,
8051 enum kvm_mr_change change)
8056 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
8057 struct kvm_memory_slot *new)
8059 /* Still write protect RO slot */
8060 if (new->flags & KVM_MEM_READONLY) {
8061 kvm_mmu_slot_remove_write_access(kvm, new);
8066 * Call kvm_x86_ops dirty logging hooks when they are valid.
8068 * kvm_x86_ops->slot_disable_log_dirty is called when:
8070 * - KVM_MR_CREATE with dirty logging is disabled
8071 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
8073 * The reason is, in case of PML, we need to set D-bit for any slots
8074 * with dirty logging disabled in order to eliminate unnecessary GPA
8075 * logging in PML buffer (and potential PML buffer full VMEXT). This
8076 * guarantees leaving PML enabled during guest's lifetime won't have
8077 * any additonal overhead from PML when guest is running with dirty
8078 * logging disabled for memory slots.
8080 * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
8081 * to dirty logging mode.
8083 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
8085 * In case of write protect:
8087 * Write protect all pages for dirty logging.
8089 * All the sptes including the large sptes which point to this
8090 * slot are set to readonly. We can not create any new large
8091 * spte on this slot until the end of the logging.
8093 * See the comments in fast_page_fault().
8095 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
8096 if (kvm_x86_ops->slot_enable_log_dirty)
8097 kvm_x86_ops->slot_enable_log_dirty(kvm, new);
8099 kvm_mmu_slot_remove_write_access(kvm, new);
8101 if (kvm_x86_ops->slot_disable_log_dirty)
8102 kvm_x86_ops->slot_disable_log_dirty(kvm, new);
8106 void kvm_arch_commit_memory_region(struct kvm *kvm,
8107 const struct kvm_userspace_memory_region *mem,
8108 const struct kvm_memory_slot *old,
8109 const struct kvm_memory_slot *new,
8110 enum kvm_mr_change change)
8112 int nr_mmu_pages = 0;
8114 if (!kvm->arch.n_requested_mmu_pages)
8115 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
8118 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
8121 * Dirty logging tracks sptes in 4k granularity, meaning that large
8122 * sptes have to be split. If live migration is successful, the guest
8123 * in the source machine will be destroyed and large sptes will be
8124 * created in the destination. However, if the guest continues to run
8125 * in the source machine (for example if live migration fails), small
8126 * sptes will remain around and cause bad performance.
8128 * Scan sptes if dirty logging has been stopped, dropping those
8129 * which can be collapsed into a single large-page spte. Later
8130 * page faults will create the large-page sptes.
8132 if ((change != KVM_MR_DELETE) &&
8133 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
8134 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
8135 kvm_mmu_zap_collapsible_sptes(kvm, new);
8138 * Set up write protection and/or dirty logging for the new slot.
8140 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
8141 * been zapped so no dirty logging staff is needed for old slot. For
8142 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
8143 * new and it's also covered when dealing with the new slot.
8145 * FIXME: const-ify all uses of struct kvm_memory_slot.
8147 if (change != KVM_MR_DELETE)
8148 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
8151 void kvm_arch_flush_shadow_all(struct kvm *kvm)
8153 kvm_mmu_invalidate_zap_all_pages(kvm);
8156 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
8157 struct kvm_memory_slot *slot)
8159 kvm_mmu_invalidate_zap_all_pages(kvm);
8162 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
8164 if (!list_empty_careful(&vcpu->async_pf.done))
8167 if (kvm_apic_has_events(vcpu))
8170 if (vcpu->arch.pv.pv_unhalted)
8173 if (atomic_read(&vcpu->arch.nmi_queued))
8176 if (test_bit(KVM_REQ_SMI, &vcpu->requests))
8179 if (kvm_arch_interrupt_allowed(vcpu) &&
8180 kvm_cpu_has_interrupt(vcpu))
8186 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
8188 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
8189 kvm_x86_ops->check_nested_events(vcpu, false);
8191 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
8194 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
8196 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
8199 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
8201 return kvm_x86_ops->interrupt_allowed(vcpu);
8204 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
8206 if (is_64_bit_mode(vcpu))
8207 return kvm_rip_read(vcpu);
8208 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
8209 kvm_rip_read(vcpu));
8211 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
8213 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
8215 return kvm_get_linear_rip(vcpu) == linear_rip;
8217 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
8219 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
8221 unsigned long rflags;
8223 rflags = kvm_x86_ops->get_rflags(vcpu);
8224 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8225 rflags &= ~X86_EFLAGS_TF;
8228 EXPORT_SYMBOL_GPL(kvm_get_rflags);
8230 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8232 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
8233 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
8234 rflags |= X86_EFLAGS_TF;
8235 kvm_x86_ops->set_rflags(vcpu, rflags);
8238 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8240 __kvm_set_rflags(vcpu, rflags);
8241 kvm_make_request(KVM_REQ_EVENT, vcpu);
8243 EXPORT_SYMBOL_GPL(kvm_set_rflags);
8245 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
8249 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
8253 r = kvm_mmu_reload(vcpu);
8257 if (!vcpu->arch.mmu.direct_map &&
8258 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
8261 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
8264 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
8266 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
8269 static inline u32 kvm_async_pf_next_probe(u32 key)
8271 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
8274 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8276 u32 key = kvm_async_pf_hash_fn(gfn);
8278 while (vcpu->arch.apf.gfns[key] != ~0)
8279 key = kvm_async_pf_next_probe(key);
8281 vcpu->arch.apf.gfns[key] = gfn;
8284 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
8287 u32 key = kvm_async_pf_hash_fn(gfn);
8289 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
8290 (vcpu->arch.apf.gfns[key] != gfn &&
8291 vcpu->arch.apf.gfns[key] != ~0); i++)
8292 key = kvm_async_pf_next_probe(key);
8297 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8299 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
8302 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8306 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
8308 vcpu->arch.apf.gfns[i] = ~0;
8310 j = kvm_async_pf_next_probe(j);
8311 if (vcpu->arch.apf.gfns[j] == ~0)
8313 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
8315 * k lies cyclically in ]i,j]
8317 * |....j i.k.| or |.k..j i...|
8319 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
8320 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
8325 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
8328 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
8332 static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
8335 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
8339 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
8340 struct kvm_async_pf *work)
8342 struct x86_exception fault;
8344 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
8345 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
8347 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
8348 (vcpu->arch.apf.send_user_only &&
8349 kvm_x86_ops->get_cpl(vcpu) == 0))
8350 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
8351 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
8352 fault.vector = PF_VECTOR;
8353 fault.error_code_valid = true;
8354 fault.error_code = 0;
8355 fault.nested_page_fault = false;
8356 fault.address = work->arch.token;
8357 kvm_inject_page_fault(vcpu, &fault);
8361 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
8362 struct kvm_async_pf *work)
8364 struct x86_exception fault;
8367 if (work->wakeup_all)
8368 work->arch.token = ~0; /* broadcast wakeup */
8370 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
8371 trace_kvm_async_pf_ready(work->arch.token, work->gva);
8373 if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
8374 !apf_get_user(vcpu, &val)) {
8375 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
8376 vcpu->arch.exception.pending &&
8377 vcpu->arch.exception.nr == PF_VECTOR &&
8378 !apf_put_user(vcpu, 0)) {
8379 vcpu->arch.exception.pending = false;
8380 vcpu->arch.exception.nr = 0;
8381 vcpu->arch.exception.has_error_code = false;
8382 vcpu->arch.exception.error_code = 0;
8383 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
8384 fault.vector = PF_VECTOR;
8385 fault.error_code_valid = true;
8386 fault.error_code = 0;
8387 fault.nested_page_fault = false;
8388 fault.address = work->arch.token;
8389 kvm_inject_page_fault(vcpu, &fault);
8392 vcpu->arch.apf.halted = false;
8393 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8396 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
8398 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
8401 return kvm_can_do_async_pf(vcpu);
8404 void kvm_arch_start_assignment(struct kvm *kvm)
8406 atomic_inc(&kvm->arch.assigned_device_count);
8408 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
8410 void kvm_arch_end_assignment(struct kvm *kvm)
8412 atomic_dec(&kvm->arch.assigned_device_count);
8414 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
8416 bool kvm_arch_has_assigned_device(struct kvm *kvm)
8418 return atomic_read(&kvm->arch.assigned_device_count);
8420 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
8422 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
8424 atomic_inc(&kvm->arch.noncoherent_dma_count);
8426 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
8428 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
8430 atomic_dec(&kvm->arch.noncoherent_dma_count);
8432 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
8434 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
8436 return atomic_read(&kvm->arch.noncoherent_dma_count);
8438 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
8440 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
8441 struct irq_bypass_producer *prod)
8443 struct kvm_kernel_irqfd *irqfd =
8444 container_of(cons, struct kvm_kernel_irqfd, consumer);
8446 if (kvm_x86_ops->update_pi_irte) {
8447 irqfd->producer = prod;
8448 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
8449 prod->irq, irqfd->gsi, 1);
8455 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
8456 struct irq_bypass_producer *prod)
8459 struct kvm_kernel_irqfd *irqfd =
8460 container_of(cons, struct kvm_kernel_irqfd, consumer);
8462 if (!kvm_x86_ops->update_pi_irte) {
8463 WARN_ON(irqfd->producer != NULL);
8467 WARN_ON(irqfd->producer != prod);
8468 irqfd->producer = NULL;
8471 * When producer of consumer is unregistered, we change back to
8472 * remapped mode, so we can re-use the current implementation
8473 * when the irq is masked/disabed or the consumer side (KVM
8474 * int this case doesn't want to receive the interrupts.
8476 ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
8478 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
8479 " fails: %d\n", irqfd->consumer.token, ret);
8482 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
8483 uint32_t guest_irq, bool set)
8485 if (!kvm_x86_ops->update_pi_irte)
8488 return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
8491 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
8492 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
8493 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
8494 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
8495 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
8496 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
8497 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
8498 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
8499 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
8500 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
8501 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
8502 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
8503 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
8504 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
8505 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
8506 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
8507 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);