2 * Kernel-based Virtual Machine driver for Linux
4 * derived from drivers/kvm/kvm_main.c
6 * Copyright (C) 2006 Qumranet, Inc.
7 * Copyright (C) 2008 Qumranet, Inc.
8 * Copyright IBM Corporation, 2008
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
14 * Amit Shah <amit.shah@qumranet.com>
15 * Ben-Ami Yassour <benami@il.ibm.com>
17 * This work is licensed under the terms of the GNU GPL, version 2. See
18 * the COPYING file in the top-level directory.
22 #include <linux/kvm_host.h>
27 #include "kvm_cache_regs.h"
30 #include "assigned-dev.h"
34 #include <linux/clocksource.h>
35 #include <linux/interrupt.h>
36 #include <linux/kvm.h>
38 #include <linux/vmalloc.h>
39 #include <linux/module.h>
40 #include <linux/mman.h>
41 #include <linux/highmem.h>
42 #include <linux/iommu.h>
43 #include <linux/intel-iommu.h>
44 #include <linux/cpufreq.h>
45 #include <linux/user-return-notifier.h>
46 #include <linux/srcu.h>
47 #include <linux/slab.h>
48 #include <linux/perf_event.h>
49 #include <linux/uaccess.h>
50 #include <linux/hash.h>
51 #include <linux/pci.h>
52 #include <linux/timekeeper_internal.h>
53 #include <linux/pvclock_gtod.h>
54 #include <linux/kvm_irqfd.h>
55 #include <linux/irqbypass.h>
56 #include <trace/events/kvm.h>
58 #define CREATE_TRACE_POINTS
61 #include <asm/debugreg.h>
65 #include <linux/kernel_stat.h>
66 #include <asm/fpu/internal.h> /* Ugh! */
67 #include <asm/pvclock.h>
68 #include <asm/div64.h>
69 #include <asm/irq_remapping.h>
71 #define MAX_IO_MSRS 256
72 #define KVM_MAX_MCE_BANKS 32
73 #define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
75 #define emul_to_vcpu(ctxt) \
76 container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
79 * - enable syscall per default because its emulated by KVM
80 * - enable LME and LMA per default on 64 bit KVM
84 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
86 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
89 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
90 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
92 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
93 static void process_nmi(struct kvm_vcpu *vcpu);
94 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
96 struct kvm_x86_ops *kvm_x86_ops __read_mostly;
97 EXPORT_SYMBOL_GPL(kvm_x86_ops);
99 static bool __read_mostly ignore_msrs = 0;
100 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
102 unsigned int min_timer_period_us = 500;
103 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
105 static bool __read_mostly kvmclock_periodic_sync = true;
106 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
108 bool __read_mostly kvm_has_tsc_control;
109 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
110 u32 __read_mostly kvm_max_guest_tsc_khz;
111 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
112 u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
113 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
114 u64 __read_mostly kvm_max_tsc_scaling_ratio;
115 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
117 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
118 static u32 __read_mostly tsc_tolerance_ppm = 250;
119 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
121 /* lapic timer advance (tscdeadline mode only) in nanoseconds */
122 unsigned int __read_mostly lapic_timer_advance_ns = 0;
123 module_param(lapic_timer_advance_ns, uint, S_IRUGO | S_IWUSR);
125 static bool __read_mostly backwards_tsc_observed = false;
127 #define KVM_NR_SHARED_MSRS 16
129 struct kvm_shared_msrs_global {
131 u32 msrs[KVM_NR_SHARED_MSRS];
134 struct kvm_shared_msrs {
135 struct user_return_notifier urn;
137 struct kvm_shared_msr_values {
140 } values[KVM_NR_SHARED_MSRS];
143 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
144 static struct kvm_shared_msrs __percpu *shared_msrs;
146 struct kvm_stats_debugfs_item debugfs_entries[] = {
147 { "pf_fixed", VCPU_STAT(pf_fixed) },
148 { "pf_guest", VCPU_STAT(pf_guest) },
149 { "tlb_flush", VCPU_STAT(tlb_flush) },
150 { "invlpg", VCPU_STAT(invlpg) },
151 { "exits", VCPU_STAT(exits) },
152 { "io_exits", VCPU_STAT(io_exits) },
153 { "mmio_exits", VCPU_STAT(mmio_exits) },
154 { "signal_exits", VCPU_STAT(signal_exits) },
155 { "irq_window", VCPU_STAT(irq_window_exits) },
156 { "nmi_window", VCPU_STAT(nmi_window_exits) },
157 { "halt_exits", VCPU_STAT(halt_exits) },
158 { "halt_successful_poll", VCPU_STAT(halt_successful_poll) },
159 { "halt_attempted_poll", VCPU_STAT(halt_attempted_poll) },
160 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
161 { "hypercalls", VCPU_STAT(hypercalls) },
162 { "request_irq", VCPU_STAT(request_irq_exits) },
163 { "irq_exits", VCPU_STAT(irq_exits) },
164 { "host_state_reload", VCPU_STAT(host_state_reload) },
165 { "efer_reload", VCPU_STAT(efer_reload) },
166 { "fpu_reload", VCPU_STAT(fpu_reload) },
167 { "insn_emulation", VCPU_STAT(insn_emulation) },
168 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
169 { "irq_injections", VCPU_STAT(irq_injections) },
170 { "nmi_injections", VCPU_STAT(nmi_injections) },
171 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
172 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
173 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
174 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
175 { "mmu_flooded", VM_STAT(mmu_flooded) },
176 { "mmu_recycled", VM_STAT(mmu_recycled) },
177 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
178 { "mmu_unsync", VM_STAT(mmu_unsync) },
179 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
180 { "largepages", VM_STAT(lpages) },
184 u64 __read_mostly host_xcr0;
186 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
188 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
191 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
192 vcpu->arch.apf.gfns[i] = ~0;
195 static void kvm_on_user_return(struct user_return_notifier *urn)
198 struct kvm_shared_msrs *locals
199 = container_of(urn, struct kvm_shared_msrs, urn);
200 struct kvm_shared_msr_values *values;
202 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
203 values = &locals->values[slot];
204 if (values->host != values->curr) {
205 wrmsrl(shared_msrs_global.msrs[slot], values->host);
206 values->curr = values->host;
209 locals->registered = false;
210 user_return_notifier_unregister(urn);
213 static void shared_msr_update(unsigned slot, u32 msr)
216 unsigned int cpu = smp_processor_id();
217 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
219 /* only read, and nobody should modify it at this time,
220 * so don't need lock */
221 if (slot >= shared_msrs_global.nr) {
222 printk(KERN_ERR "kvm: invalid MSR slot!");
225 rdmsrl_safe(msr, &value);
226 smsr->values[slot].host = value;
227 smsr->values[slot].curr = value;
230 void kvm_define_shared_msr(unsigned slot, u32 msr)
232 BUG_ON(slot >= KVM_NR_SHARED_MSRS);
233 shared_msrs_global.msrs[slot] = msr;
234 if (slot >= shared_msrs_global.nr)
235 shared_msrs_global.nr = slot + 1;
237 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
239 static void kvm_shared_msr_cpu_online(void)
243 for (i = 0; i < shared_msrs_global.nr; ++i)
244 shared_msr_update(i, shared_msrs_global.msrs[i]);
247 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
249 unsigned int cpu = smp_processor_id();
250 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
253 if (((value ^ smsr->values[slot].curr) & mask) == 0)
255 smsr->values[slot].curr = value;
256 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
260 if (!smsr->registered) {
261 smsr->urn.on_user_return = kvm_on_user_return;
262 user_return_notifier_register(&smsr->urn);
263 smsr->registered = true;
267 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
269 static void drop_user_return_notifiers(void)
271 unsigned int cpu = smp_processor_id();
272 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
274 if (smsr->registered)
275 kvm_on_user_return(&smsr->urn);
278 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
280 return vcpu->arch.apic_base;
282 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
284 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
286 u64 old_state = vcpu->arch.apic_base &
287 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
288 u64 new_state = msr_info->data &
289 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
290 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) |
291 0x2ff | (guest_cpuid_has_x2apic(vcpu) ? 0 : X2APIC_ENABLE);
293 if (!msr_info->host_initiated &&
294 ((msr_info->data & reserved_bits) != 0 ||
295 new_state == X2APIC_ENABLE ||
296 (new_state == MSR_IA32_APICBASE_ENABLE &&
297 old_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) ||
298 (new_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE) &&
302 kvm_lapic_set_base(vcpu, msr_info->data);
305 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
307 asmlinkage __visible void kvm_spurious_fault(void)
309 /* Fault while not rebooting. We want the trace. */
312 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
314 #define EXCPT_BENIGN 0
315 #define EXCPT_CONTRIBUTORY 1
318 static int exception_class(int vector)
328 return EXCPT_CONTRIBUTORY;
335 #define EXCPT_FAULT 0
337 #define EXCPT_ABORT 2
338 #define EXCPT_INTERRUPT 3
340 static int exception_type(int vector)
344 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
345 return EXCPT_INTERRUPT;
349 /* #DB is trap, as instruction watchpoints are handled elsewhere */
350 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
353 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
356 /* Reserved exceptions will result in fault */
360 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
361 unsigned nr, bool has_error, u32 error_code,
367 kvm_make_request(KVM_REQ_EVENT, vcpu);
369 if (!vcpu->arch.exception.pending) {
371 if (has_error && !is_protmode(vcpu))
373 vcpu->arch.exception.pending = true;
374 vcpu->arch.exception.has_error_code = has_error;
375 vcpu->arch.exception.nr = nr;
376 vcpu->arch.exception.error_code = error_code;
377 vcpu->arch.exception.reinject = reinject;
381 /* to check exception */
382 prev_nr = vcpu->arch.exception.nr;
383 if (prev_nr == DF_VECTOR) {
384 /* triple fault -> shutdown */
385 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
388 class1 = exception_class(prev_nr);
389 class2 = exception_class(nr);
390 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
391 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
392 /* generate double fault per SDM Table 5-5 */
393 vcpu->arch.exception.pending = true;
394 vcpu->arch.exception.has_error_code = true;
395 vcpu->arch.exception.nr = DF_VECTOR;
396 vcpu->arch.exception.error_code = 0;
398 /* replace previous exception with a new one in a hope
399 that instruction re-execution will regenerate lost
404 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
406 kvm_multiple_exception(vcpu, nr, false, 0, false);
408 EXPORT_SYMBOL_GPL(kvm_queue_exception);
410 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
412 kvm_multiple_exception(vcpu, nr, false, 0, true);
414 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
416 void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
419 kvm_inject_gp(vcpu, 0);
421 kvm_x86_ops->skip_emulated_instruction(vcpu);
423 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
425 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
427 ++vcpu->stat.pf_guest;
428 vcpu->arch.cr2 = fault->address;
429 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
431 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
433 static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
435 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
436 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
438 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
440 return fault->nested_page_fault;
443 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
445 atomic_inc(&vcpu->arch.nmi_queued);
446 kvm_make_request(KVM_REQ_NMI, vcpu);
448 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
450 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
452 kvm_multiple_exception(vcpu, nr, true, error_code, false);
454 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
456 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
458 kvm_multiple_exception(vcpu, nr, true, error_code, true);
460 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
463 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
464 * a #GP and return false.
466 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
468 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
470 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
473 EXPORT_SYMBOL_GPL(kvm_require_cpl);
475 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
477 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
480 kvm_queue_exception(vcpu, UD_VECTOR);
483 EXPORT_SYMBOL_GPL(kvm_require_dr);
486 * This function will be used to read from the physical memory of the currently
487 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
488 * can read from guest physical or from the guest's guest physical memory.
490 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
491 gfn_t ngfn, void *data, int offset, int len,
494 struct x86_exception exception;
498 ngpa = gfn_to_gpa(ngfn);
499 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
500 if (real_gfn == UNMAPPED_GVA)
503 real_gfn = gpa_to_gfn(real_gfn);
505 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
507 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
509 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
510 void *data, int offset, int len, u32 access)
512 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
513 data, offset, len, access);
517 * Load the pae pdptrs. Return true is they are all valid.
519 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
521 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
522 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
525 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
527 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
528 offset * sizeof(u64), sizeof(pdpte),
529 PFERR_USER_MASK|PFERR_WRITE_MASK);
534 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
535 if (is_present_gpte(pdpte[i]) &&
537 vcpu->arch.mmu.guest_rsvd_check.rsvd_bits_mask[0][2])) {
544 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
545 __set_bit(VCPU_EXREG_PDPTR,
546 (unsigned long *)&vcpu->arch.regs_avail);
547 __set_bit(VCPU_EXREG_PDPTR,
548 (unsigned long *)&vcpu->arch.regs_dirty);
553 EXPORT_SYMBOL_GPL(load_pdptrs);
555 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
557 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
563 if (is_long_mode(vcpu) || !is_pae(vcpu))
566 if (!test_bit(VCPU_EXREG_PDPTR,
567 (unsigned long *)&vcpu->arch.regs_avail))
570 gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
571 offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
572 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
573 PFERR_USER_MASK | PFERR_WRITE_MASK);
576 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
582 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
584 unsigned long old_cr0 = kvm_read_cr0(vcpu);
585 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
590 if (cr0 & 0xffffffff00000000UL)
594 cr0 &= ~CR0_RESERVED_BITS;
596 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
599 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
602 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
604 if ((vcpu->arch.efer & EFER_LME)) {
609 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
614 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
619 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
622 kvm_x86_ops->set_cr0(vcpu, cr0);
624 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
625 kvm_clear_async_pf_completion_queue(vcpu);
626 kvm_async_pf_hash_reset(vcpu);
629 if ((cr0 ^ old_cr0) & update_bits)
630 kvm_mmu_reset_context(vcpu);
632 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
633 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
634 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
635 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
639 EXPORT_SYMBOL_GPL(kvm_set_cr0);
641 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
643 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
645 EXPORT_SYMBOL_GPL(kvm_lmsw);
647 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
649 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
650 !vcpu->guest_xcr0_loaded) {
651 /* kvm_set_xcr() also depends on this */
652 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
653 vcpu->guest_xcr0_loaded = 1;
657 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
659 if (vcpu->guest_xcr0_loaded) {
660 if (vcpu->arch.xcr0 != host_xcr0)
661 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
662 vcpu->guest_xcr0_loaded = 0;
666 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
669 u64 old_xcr0 = vcpu->arch.xcr0;
672 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
673 if (index != XCR_XFEATURE_ENABLED_MASK)
675 if (!(xcr0 & XSTATE_FP))
677 if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
681 * Do not allow the guest to set bits that we do not support
682 * saving. However, xcr0 bit 0 is always set, even if the
683 * emulated CPU does not support XSAVE (see fx_init).
685 valid_bits = vcpu->arch.guest_supported_xcr0 | XSTATE_FP;
686 if (xcr0 & ~valid_bits)
689 if ((!(xcr0 & XSTATE_BNDREGS)) != (!(xcr0 & XSTATE_BNDCSR)))
692 if (xcr0 & XSTATE_AVX512) {
693 if (!(xcr0 & XSTATE_YMM))
695 if ((xcr0 & XSTATE_AVX512) != XSTATE_AVX512)
698 kvm_put_guest_xcr0(vcpu);
699 vcpu->arch.xcr0 = xcr0;
701 if ((xcr0 ^ old_xcr0) & XSTATE_EXTEND_MASK)
702 kvm_update_cpuid(vcpu);
706 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
708 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
709 __kvm_set_xcr(vcpu, index, xcr)) {
710 kvm_inject_gp(vcpu, 0);
715 EXPORT_SYMBOL_GPL(kvm_set_xcr);
717 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
719 unsigned long old_cr4 = kvm_read_cr4(vcpu);
720 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
721 X86_CR4_SMEP | X86_CR4_SMAP;
723 if (cr4 & CR4_RESERVED_BITS)
726 if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
729 if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
732 if (!guest_cpuid_has_smap(vcpu) && (cr4 & X86_CR4_SMAP))
735 if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_FSGSBASE))
738 if (is_long_mode(vcpu)) {
739 if (!(cr4 & X86_CR4_PAE))
741 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
742 && ((cr4 ^ old_cr4) & pdptr_bits)
743 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
747 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
748 if (!guest_cpuid_has_pcid(vcpu))
751 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
752 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
756 if (kvm_x86_ops->set_cr4(vcpu, cr4))
759 if (((cr4 ^ old_cr4) & pdptr_bits) ||
760 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
761 kvm_mmu_reset_context(vcpu);
763 if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
764 kvm_update_cpuid(vcpu);
768 EXPORT_SYMBOL_GPL(kvm_set_cr4);
770 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
773 cr3 &= ~CR3_PCID_INVD;
776 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
777 kvm_mmu_sync_roots(vcpu);
778 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
782 if (is_long_mode(vcpu)) {
783 if (cr3 & CR3_L_MODE_RESERVED_BITS)
785 } else if (is_pae(vcpu) && is_paging(vcpu) &&
786 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
789 vcpu->arch.cr3 = cr3;
790 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
791 kvm_mmu_new_cr3(vcpu);
794 EXPORT_SYMBOL_GPL(kvm_set_cr3);
796 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
798 if (cr8 & CR8_RESERVED_BITS)
800 if (lapic_in_kernel(vcpu))
801 kvm_lapic_set_tpr(vcpu, cr8);
803 vcpu->arch.cr8 = cr8;
806 EXPORT_SYMBOL_GPL(kvm_set_cr8);
808 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
810 if (lapic_in_kernel(vcpu))
811 return kvm_lapic_get_cr8(vcpu);
813 return vcpu->arch.cr8;
815 EXPORT_SYMBOL_GPL(kvm_get_cr8);
817 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
821 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
822 for (i = 0; i < KVM_NR_DB_REGS; i++)
823 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
824 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
828 static void kvm_update_dr6(struct kvm_vcpu *vcpu)
830 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
831 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
834 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
838 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
839 dr7 = vcpu->arch.guest_debug_dr7;
841 dr7 = vcpu->arch.dr7;
842 kvm_x86_ops->set_dr7(vcpu, dr7);
843 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
844 if (dr7 & DR7_BP_EN_MASK)
845 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
848 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
850 u64 fixed = DR6_FIXED_1;
852 if (!guest_cpuid_has_rtm(vcpu))
857 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
861 vcpu->arch.db[dr] = val;
862 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
863 vcpu->arch.eff_db[dr] = val;
868 if (val & 0xffffffff00000000ULL)
870 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
871 kvm_update_dr6(vcpu);
876 if (val & 0xffffffff00000000ULL)
878 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
879 kvm_update_dr7(vcpu);
886 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
888 if (__kvm_set_dr(vcpu, dr, val)) {
889 kvm_inject_gp(vcpu, 0);
894 EXPORT_SYMBOL_GPL(kvm_set_dr);
896 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
900 *val = vcpu->arch.db[dr];
905 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
906 *val = vcpu->arch.dr6;
908 *val = kvm_x86_ops->get_dr6(vcpu);
913 *val = vcpu->arch.dr7;
918 EXPORT_SYMBOL_GPL(kvm_get_dr);
920 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
922 u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
926 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
929 kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
930 kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
933 EXPORT_SYMBOL_GPL(kvm_rdpmc);
936 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
937 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
939 * This list is modified at module load time to reflect the
940 * capabilities of the host cpu. This capabilities test skips MSRs that are
941 * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
942 * may depend on host virtualization features rather than host cpu features.
945 static u32 msrs_to_save[] = {
946 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
949 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
951 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
952 MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS
955 static unsigned num_msrs_to_save;
957 static u32 emulated_msrs[] = {
958 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
959 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
960 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
961 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
962 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
963 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
966 HV_X64_MSR_VP_RUNTIME,
967 HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
971 MSR_IA32_TSCDEADLINE,
972 MSR_IA32_MISC_ENABLE,
978 static unsigned num_emulated_msrs;
980 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
982 if (efer & efer_reserved_bits)
985 if (efer & EFER_FFXSR) {
986 struct kvm_cpuid_entry2 *feat;
988 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
989 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
993 if (efer & EFER_SVME) {
994 struct kvm_cpuid_entry2 *feat;
996 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
997 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
1003 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1005 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
1007 u64 old_efer = vcpu->arch.efer;
1009 if (!kvm_valid_efer(vcpu, efer))
1013 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1017 efer |= vcpu->arch.efer & EFER_LMA;
1019 kvm_x86_ops->set_efer(vcpu, efer);
1021 /* Update reserved bits */
1022 if ((efer ^ old_efer) & EFER_NX)
1023 kvm_mmu_reset_context(vcpu);
1028 void kvm_enable_efer_bits(u64 mask)
1030 efer_reserved_bits &= ~mask;
1032 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1035 * Writes msr value into into the appropriate "register".
1036 * Returns 0 on success, non-0 otherwise.
1037 * Assumes vcpu_load() was already called.
1039 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
1041 switch (msr->index) {
1044 case MSR_KERNEL_GS_BASE:
1047 if (is_noncanonical_address(msr->data))
1050 case MSR_IA32_SYSENTER_EIP:
1051 case MSR_IA32_SYSENTER_ESP:
1053 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1054 * non-canonical address is written on Intel but not on
1055 * AMD (which ignores the top 32-bits, because it does
1056 * not implement 64-bit SYSENTER).
1058 * 64-bit code should hence be able to write a non-canonical
1059 * value on AMD. Making the address canonical ensures that
1060 * vmentry does not fail on Intel after writing a non-canonical
1061 * value, and that something deterministic happens if the guest
1062 * invokes 64-bit SYSENTER.
1064 msr->data = get_canonical(msr->data);
1066 return kvm_x86_ops->set_msr(vcpu, msr);
1068 EXPORT_SYMBOL_GPL(kvm_set_msr);
1071 * Adapt set_msr() to msr_io()'s calling convention
1073 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1075 struct msr_data msr;
1079 msr.host_initiated = true;
1080 r = kvm_get_msr(vcpu, &msr);
1088 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1090 struct msr_data msr;
1094 msr.host_initiated = true;
1095 return kvm_set_msr(vcpu, &msr);
1098 #ifdef CONFIG_X86_64
1099 struct pvclock_gtod_data {
1102 struct { /* extract of a clocksource struct */
1114 static struct pvclock_gtod_data pvclock_gtod_data;
1116 static void update_pvclock_gtod(struct timekeeper *tk)
1118 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1121 boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
1123 write_seqcount_begin(&vdata->seq);
1125 /* copy pvclock gtod data */
1126 vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
1127 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1128 vdata->clock.mask = tk->tkr_mono.mask;
1129 vdata->clock.mult = tk->tkr_mono.mult;
1130 vdata->clock.shift = tk->tkr_mono.shift;
1132 vdata->boot_ns = boot_ns;
1133 vdata->nsec_base = tk->tkr_mono.xtime_nsec;
1135 write_seqcount_end(&vdata->seq);
1139 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1142 * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
1143 * vcpu_enter_guest. This function is only called from
1144 * the physical CPU that is running vcpu.
1146 kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1149 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1153 struct pvclock_wall_clock wc;
1154 struct timespec boot;
1159 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1164 ++version; /* first time write, random junk */
1168 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1171 * The guest calculates current wall clock time by adding
1172 * system time (updated by kvm_guest_time_update below) to the
1173 * wall clock specified here. guest system time equals host
1174 * system time for us, thus we must fill in host boot time here.
1178 if (kvm->arch.kvmclock_offset) {
1179 struct timespec ts = ns_to_timespec(kvm->arch.kvmclock_offset);
1180 boot = timespec_sub(boot, ts);
1182 wc.sec = boot.tv_sec;
1183 wc.nsec = boot.tv_nsec;
1184 wc.version = version;
1186 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1189 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1192 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1194 uint32_t quotient, remainder;
1196 /* Don't try to replace with do_div(), this one calculates
1197 * "(dividend << 32) / divisor" */
1199 : "=a" (quotient), "=d" (remainder)
1200 : "0" (0), "1" (dividend), "r" (divisor) );
1204 static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
1205 s8 *pshift, u32 *pmultiplier)
1212 tps64 = base_khz * 1000LL;
1213 scaled64 = scaled_khz * 1000LL;
1214 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1219 tps32 = (uint32_t)tps64;
1220 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1221 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1229 *pmultiplier = div_frac(scaled64, tps32);
1231 pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
1232 __func__, base_khz, scaled_khz, shift, *pmultiplier);
1235 #ifdef CONFIG_X86_64
1236 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1239 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1240 static unsigned long max_tsc_khz;
1242 static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
1244 return pvclock_scale_delta(nsec, vcpu->arch.virtual_tsc_mult,
1245 vcpu->arch.virtual_tsc_shift);
1248 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1250 u64 v = (u64)khz * (1000000 + ppm);
1255 static void kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
1257 u32 thresh_lo, thresh_hi;
1258 int use_scaling = 0;
1260 /* tsc_khz can be zero if TSC calibration fails */
1261 if (this_tsc_khz == 0)
1264 /* Compute a scale to convert nanoseconds in TSC cycles */
1265 kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
1266 &vcpu->arch.virtual_tsc_shift,
1267 &vcpu->arch.virtual_tsc_mult);
1268 vcpu->arch.virtual_tsc_khz = this_tsc_khz;
1271 * Compute the variation in TSC rate which is acceptable
1272 * within the range of tolerance and decide if the
1273 * rate being applied is within that bounds of the hardware
1274 * rate. If so, no scaling or compensation need be done.
1276 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1277 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1278 if (this_tsc_khz < thresh_lo || this_tsc_khz > thresh_hi) {
1279 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", this_tsc_khz, thresh_lo, thresh_hi);
1282 kvm_x86_ops->set_tsc_khz(vcpu, this_tsc_khz, use_scaling);
1285 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1287 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1288 vcpu->arch.virtual_tsc_mult,
1289 vcpu->arch.virtual_tsc_shift);
1290 tsc += vcpu->arch.this_tsc_write;
1294 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1296 #ifdef CONFIG_X86_64
1298 struct kvm_arch *ka = &vcpu->kvm->arch;
1299 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1301 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1302 atomic_read(&vcpu->kvm->online_vcpus));
1305 * Once the masterclock is enabled, always perform request in
1306 * order to update it.
1308 * In order to enable masterclock, the host clocksource must be TSC
1309 * and the vcpus need to have matched TSCs. When that happens,
1310 * perform request to enable masterclock.
1312 if (ka->use_master_clock ||
1313 (gtod->clock.vclock_mode == VCLOCK_TSC && vcpus_matched))
1314 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1316 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1317 atomic_read(&vcpu->kvm->online_vcpus),
1318 ka->use_master_clock, gtod->clock.vclock_mode);
1322 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1324 u64 curr_offset = kvm_x86_ops->read_tsc_offset(vcpu);
1325 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1328 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1330 struct kvm *kvm = vcpu->kvm;
1331 u64 offset, ns, elapsed;
1332 unsigned long flags;
1335 bool already_matched;
1336 u64 data = msr->data;
1338 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1339 offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
1340 ns = get_kernel_ns();
1341 elapsed = ns - kvm->arch.last_tsc_nsec;
1343 if (vcpu->arch.virtual_tsc_khz) {
1346 /* n.b - signed multiplication and division required */
1347 usdiff = data - kvm->arch.last_tsc_write;
1348 #ifdef CONFIG_X86_64
1349 usdiff = (usdiff * 1000) / vcpu->arch.virtual_tsc_khz;
1351 /* do_div() only does unsigned */
1352 asm("1: idivl %[divisor]\n"
1353 "2: xor %%edx, %%edx\n"
1354 " movl $0, %[faulted]\n"
1356 ".section .fixup,\"ax\"\n"
1357 "4: movl $1, %[faulted]\n"
1361 _ASM_EXTABLE(1b, 4b)
1363 : "=A"(usdiff), [faulted] "=r" (faulted)
1364 : "A"(usdiff * 1000), [divisor] "rm"(vcpu->arch.virtual_tsc_khz));
1367 do_div(elapsed, 1000);
1372 /* idivl overflow => difference is larger than USEC_PER_SEC */
1374 usdiff = USEC_PER_SEC;
1376 usdiff = USEC_PER_SEC; /* disable TSC match window below */
1379 * Special case: TSC write with a small delta (1 second) of virtual
1380 * cycle time against real time is interpreted as an attempt to
1381 * synchronize the CPU.
1383 * For a reliable TSC, we can match TSC offsets, and for an unstable
1384 * TSC, we add elapsed time in this computation. We could let the
1385 * compensation code attempt to catch up if we fall behind, but
1386 * it's better to try to match offsets from the beginning.
1388 if (usdiff < USEC_PER_SEC &&
1389 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1390 if (!check_tsc_unstable()) {
1391 offset = kvm->arch.cur_tsc_offset;
1392 pr_debug("kvm: matched tsc offset for %llu\n", data);
1394 u64 delta = nsec_to_cycles(vcpu, elapsed);
1396 offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
1397 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1400 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1403 * We split periods of matched TSC writes into generations.
1404 * For each generation, we track the original measured
1405 * nanosecond time, offset, and write, so if TSCs are in
1406 * sync, we can match exact offset, and if not, we can match
1407 * exact software computation in compute_guest_tsc()
1409 * These values are tracked in kvm->arch.cur_xxx variables.
1411 kvm->arch.cur_tsc_generation++;
1412 kvm->arch.cur_tsc_nsec = ns;
1413 kvm->arch.cur_tsc_write = data;
1414 kvm->arch.cur_tsc_offset = offset;
1416 pr_debug("kvm: new tsc generation %llu, clock %llu\n",
1417 kvm->arch.cur_tsc_generation, data);
1421 * We also track th most recent recorded KHZ, write and time to
1422 * allow the matching interval to be extended at each write.
1424 kvm->arch.last_tsc_nsec = ns;
1425 kvm->arch.last_tsc_write = data;
1426 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1428 vcpu->arch.last_guest_tsc = data;
1430 /* Keep track of which generation this VCPU has synchronized to */
1431 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1432 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1433 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1435 if (guest_cpuid_has_tsc_adjust(vcpu) && !msr->host_initiated)
1436 update_ia32_tsc_adjust_msr(vcpu, offset);
1437 kvm_x86_ops->write_tsc_offset(vcpu, offset);
1438 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1440 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1442 kvm->arch.nr_vcpus_matched_tsc = 0;
1443 } else if (!already_matched) {
1444 kvm->arch.nr_vcpus_matched_tsc++;
1447 kvm_track_tsc_matching(vcpu);
1448 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1451 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1453 #ifdef CONFIG_X86_64
1455 static cycle_t read_tsc(void)
1457 cycle_t ret = (cycle_t)rdtsc_ordered();
1458 u64 last = pvclock_gtod_data.clock.cycle_last;
1460 if (likely(ret >= last))
1464 * GCC likes to generate cmov here, but this branch is extremely
1465 * predictable (it's just a funciton of time and the likely is
1466 * very likely) and there's a data dependence, so force GCC
1467 * to generate a branch instead. I don't barrier() because
1468 * we don't actually need a barrier, and if this function
1469 * ever gets inlined it will generate worse code.
1475 static inline u64 vgettsc(cycle_t *cycle_now)
1478 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1480 *cycle_now = read_tsc();
1482 v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
1483 return v * gtod->clock.mult;
1486 static int do_monotonic_boot(s64 *t, cycle_t *cycle_now)
1488 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1494 seq = read_seqcount_begin(>od->seq);
1495 mode = gtod->clock.vclock_mode;
1496 ns = gtod->nsec_base;
1497 ns += vgettsc(cycle_now);
1498 ns >>= gtod->clock.shift;
1499 ns += gtod->boot_ns;
1500 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
1506 /* returns true if host is using tsc clocksource */
1507 static bool kvm_get_time_and_clockread(s64 *kernel_ns, cycle_t *cycle_now)
1509 /* checked again under seqlock below */
1510 if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
1513 return do_monotonic_boot(kernel_ns, cycle_now) == VCLOCK_TSC;
1519 * Assuming a stable TSC across physical CPUS, and a stable TSC
1520 * across virtual CPUs, the following condition is possible.
1521 * Each numbered line represents an event visible to both
1522 * CPUs at the next numbered event.
1524 * "timespecX" represents host monotonic time. "tscX" represents
1527 * VCPU0 on CPU0 | VCPU1 on CPU1
1529 * 1. read timespec0,tsc0
1530 * 2. | timespec1 = timespec0 + N
1532 * 3. transition to guest | transition to guest
1533 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1534 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
1535 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1537 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1540 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1542 * - 0 < N - M => M < N
1544 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1545 * always the case (the difference between two distinct xtime instances
1546 * might be smaller then the difference between corresponding TSC reads,
1547 * when updating guest vcpus pvclock areas).
1549 * To avoid that problem, do not allow visibility of distinct
1550 * system_timestamp/tsc_timestamp values simultaneously: use a master
1551 * copy of host monotonic time values. Update that master copy
1554 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1558 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1560 #ifdef CONFIG_X86_64
1561 struct kvm_arch *ka = &kvm->arch;
1563 bool host_tsc_clocksource, vcpus_matched;
1565 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1566 atomic_read(&kvm->online_vcpus));
1569 * If the host uses TSC clock, then passthrough TSC as stable
1572 host_tsc_clocksource = kvm_get_time_and_clockread(
1573 &ka->master_kernel_ns,
1574 &ka->master_cycle_now);
1576 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
1577 && !backwards_tsc_observed
1578 && !ka->boot_vcpu_runs_old_kvmclock;
1580 if (ka->use_master_clock)
1581 atomic_set(&kvm_guest_has_master_clock, 1);
1583 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1584 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1589 static void kvm_gen_update_masterclock(struct kvm *kvm)
1591 #ifdef CONFIG_X86_64
1593 struct kvm_vcpu *vcpu;
1594 struct kvm_arch *ka = &kvm->arch;
1596 spin_lock(&ka->pvclock_gtod_sync_lock);
1597 kvm_make_mclock_inprogress_request(kvm);
1598 /* no guest entries from this point */
1599 pvclock_update_vm_gtod_copy(kvm);
1601 kvm_for_each_vcpu(i, vcpu, kvm)
1602 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1604 /* guest entries allowed */
1605 kvm_for_each_vcpu(i, vcpu, kvm)
1606 clear_bit(KVM_REQ_MCLOCK_INPROGRESS, &vcpu->requests);
1608 spin_unlock(&ka->pvclock_gtod_sync_lock);
1612 static int kvm_guest_time_update(struct kvm_vcpu *v)
1614 unsigned long flags, this_tsc_khz;
1615 struct kvm_vcpu_arch *vcpu = &v->arch;
1616 struct kvm_arch *ka = &v->kvm->arch;
1618 u64 tsc_timestamp, host_tsc;
1619 struct pvclock_vcpu_time_info guest_hv_clock;
1621 bool use_master_clock;
1627 * If the host uses TSC clock, then passthrough TSC as stable
1630 spin_lock(&ka->pvclock_gtod_sync_lock);
1631 use_master_clock = ka->use_master_clock;
1632 if (use_master_clock) {
1633 host_tsc = ka->master_cycle_now;
1634 kernel_ns = ka->master_kernel_ns;
1636 spin_unlock(&ka->pvclock_gtod_sync_lock);
1638 /* Keep irq disabled to prevent changes to the clock */
1639 local_irq_save(flags);
1640 this_tsc_khz = __this_cpu_read(cpu_tsc_khz);
1641 if (unlikely(this_tsc_khz == 0)) {
1642 local_irq_restore(flags);
1643 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1646 if (!use_master_clock) {
1648 kernel_ns = get_kernel_ns();
1651 tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc);
1654 * We may have to catch up the TSC to match elapsed wall clock
1655 * time for two reasons, even if kvmclock is used.
1656 * 1) CPU could have been running below the maximum TSC rate
1657 * 2) Broken TSC compensation resets the base at each VCPU
1658 * entry to avoid unknown leaps of TSC even when running
1659 * again on the same CPU. This may cause apparent elapsed
1660 * time to disappear, and the guest to stand still or run
1663 if (vcpu->tsc_catchup) {
1664 u64 tsc = compute_guest_tsc(v, kernel_ns);
1665 if (tsc > tsc_timestamp) {
1666 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
1667 tsc_timestamp = tsc;
1671 local_irq_restore(flags);
1673 if (!vcpu->pv_time_enabled)
1676 if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
1677 kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
1678 &vcpu->hv_clock.tsc_shift,
1679 &vcpu->hv_clock.tsc_to_system_mul);
1680 vcpu->hw_tsc_khz = this_tsc_khz;
1683 /* With all the info we got, fill in the values */
1684 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1685 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1686 vcpu->last_guest_tsc = tsc_timestamp;
1688 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
1689 &guest_hv_clock, sizeof(guest_hv_clock))))
1692 /* This VCPU is paused, but it's legal for a guest to read another
1693 * VCPU's kvmclock, so we really have to follow the specification where
1694 * it says that version is odd if data is being modified, and even after
1697 * Version field updates must be kept separate. This is because
1698 * kvm_write_guest_cached might use a "rep movs" instruction, and
1699 * writes within a string instruction are weakly ordered. So there
1700 * are three writes overall.
1702 * As a small optimization, only write the version field in the first
1703 * and third write. The vcpu->pv_time cache is still valid, because the
1704 * version field is the first in the struct.
1706 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
1708 vcpu->hv_clock.version = guest_hv_clock.version + 1;
1709 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1711 sizeof(vcpu->hv_clock.version));
1715 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
1716 pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
1718 if (vcpu->pvclock_set_guest_stopped_request) {
1719 pvclock_flags |= PVCLOCK_GUEST_STOPPED;
1720 vcpu->pvclock_set_guest_stopped_request = false;
1723 /* If the host uses TSC clocksource, then it is stable */
1724 if (use_master_clock)
1725 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
1727 vcpu->hv_clock.flags = pvclock_flags;
1729 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
1731 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1733 sizeof(vcpu->hv_clock));
1737 vcpu->hv_clock.version++;
1738 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1740 sizeof(vcpu->hv_clock.version));
1745 * kvmclock updates which are isolated to a given vcpu, such as
1746 * vcpu->cpu migration, should not allow system_timestamp from
1747 * the rest of the vcpus to remain static. Otherwise ntp frequency
1748 * correction applies to one vcpu's system_timestamp but not
1751 * So in those cases, request a kvmclock update for all vcpus.
1752 * We need to rate-limit these requests though, as they can
1753 * considerably slow guests that have a large number of vcpus.
1754 * The time for a remote vcpu to update its kvmclock is bound
1755 * by the delay we use to rate-limit the updates.
1758 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
1760 static void kvmclock_update_fn(struct work_struct *work)
1763 struct delayed_work *dwork = to_delayed_work(work);
1764 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
1765 kvmclock_update_work);
1766 struct kvm *kvm = container_of(ka, struct kvm, arch);
1767 struct kvm_vcpu *vcpu;
1769 kvm_for_each_vcpu(i, vcpu, kvm) {
1770 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1771 kvm_vcpu_kick(vcpu);
1775 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
1777 struct kvm *kvm = v->kvm;
1779 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1780 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
1781 KVMCLOCK_UPDATE_DELAY);
1784 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
1786 static void kvmclock_sync_fn(struct work_struct *work)
1788 struct delayed_work *dwork = to_delayed_work(work);
1789 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
1790 kvmclock_sync_work);
1791 struct kvm *kvm = container_of(ka, struct kvm, arch);
1793 if (!kvmclock_periodic_sync)
1796 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
1797 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
1798 KVMCLOCK_SYNC_PERIOD);
1801 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1803 u64 mcg_cap = vcpu->arch.mcg_cap;
1804 unsigned bank_num = mcg_cap & 0xff;
1807 case MSR_IA32_MCG_STATUS:
1808 vcpu->arch.mcg_status = data;
1810 case MSR_IA32_MCG_CTL:
1811 if (!(mcg_cap & MCG_CTL_P))
1813 if (data != 0 && data != ~(u64)0)
1815 vcpu->arch.mcg_ctl = data;
1818 if (msr >= MSR_IA32_MC0_CTL &&
1819 msr < MSR_IA32_MCx_CTL(bank_num)) {
1820 u32 offset = msr - MSR_IA32_MC0_CTL;
1821 /* only 0 or all 1s can be written to IA32_MCi_CTL
1822 * some Linux kernels though clear bit 10 in bank 4 to
1823 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
1824 * this to avoid an uncatched #GP in the guest
1826 if ((offset & 0x3) == 0 &&
1827 data != 0 && (data | (1 << 10)) != ~(u64)0)
1829 vcpu->arch.mce_banks[offset] = data;
1837 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
1839 struct kvm *kvm = vcpu->kvm;
1840 int lm = is_long_mode(vcpu);
1841 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
1842 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
1843 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
1844 : kvm->arch.xen_hvm_config.blob_size_32;
1845 u32 page_num = data & ~PAGE_MASK;
1846 u64 page_addr = data & PAGE_MASK;
1851 if (page_num >= blob_size)
1854 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
1859 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
1868 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
1870 gpa_t gpa = data & ~0x3f;
1872 /* Bits 2:5 are reserved, Should be zero */
1876 vcpu->arch.apf.msr_val = data;
1878 if (!(data & KVM_ASYNC_PF_ENABLED)) {
1879 kvm_clear_async_pf_completion_queue(vcpu);
1880 kvm_async_pf_hash_reset(vcpu);
1884 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
1888 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
1889 kvm_async_pf_wakeup_all(vcpu);
1893 static void kvmclock_reset(struct kvm_vcpu *vcpu)
1895 vcpu->arch.pv_time_enabled = false;
1898 static void accumulate_steal_time(struct kvm_vcpu *vcpu)
1902 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1905 delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
1906 vcpu->arch.st.last_steal = current->sched_info.run_delay;
1907 vcpu->arch.st.accum_steal = delta;
1910 static void record_steal_time(struct kvm_vcpu *vcpu)
1912 accumulate_steal_time(vcpu);
1914 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1917 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1918 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
1921 vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
1922 vcpu->arch.st.steal.version += 2;
1923 vcpu->arch.st.accum_steal = 0;
1925 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1926 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
1929 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1932 u32 msr = msr_info->index;
1933 u64 data = msr_info->data;
1936 case MSR_AMD64_NB_CFG:
1937 case MSR_IA32_UCODE_REV:
1938 case MSR_IA32_UCODE_WRITE:
1939 case MSR_VM_HSAVE_PA:
1940 case MSR_AMD64_PATCH_LOADER:
1941 case MSR_AMD64_BU_CFG2:
1945 return set_efer(vcpu, data);
1947 data &= ~(u64)0x40; /* ignore flush filter disable */
1948 data &= ~(u64)0x100; /* ignore ignne emulation enable */
1949 data &= ~(u64)0x8; /* ignore TLB cache disable */
1950 data &= ~(u64)0x40000; /* ignore Mc status write enable */
1952 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
1957 case MSR_FAM10H_MMIO_CONF_BASE:
1959 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
1964 case MSR_IA32_DEBUGCTLMSR:
1966 /* We support the non-activated case already */
1968 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
1969 /* Values other than LBR and BTF are vendor-specific,
1970 thus reserved and should throw a #GP */
1973 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
1976 case 0x200 ... 0x2ff:
1977 return kvm_mtrr_set_msr(vcpu, msr, data);
1978 case MSR_IA32_APICBASE:
1979 return kvm_set_apic_base(vcpu, msr_info);
1980 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1981 return kvm_x2apic_msr_write(vcpu, msr, data);
1982 case MSR_IA32_TSCDEADLINE:
1983 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1985 case MSR_IA32_TSC_ADJUST:
1986 if (guest_cpuid_has_tsc_adjust(vcpu)) {
1987 if (!msr_info->host_initiated) {
1988 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
1989 adjust_tsc_offset_guest(vcpu, adj);
1991 vcpu->arch.ia32_tsc_adjust_msr = data;
1994 case MSR_IA32_MISC_ENABLE:
1995 vcpu->arch.ia32_misc_enable_msr = data;
1997 case MSR_IA32_SMBASE:
1998 if (!msr_info->host_initiated)
2000 vcpu->arch.smbase = data;
2002 case MSR_KVM_WALL_CLOCK_NEW:
2003 case MSR_KVM_WALL_CLOCK:
2004 vcpu->kvm->arch.wall_clock = data;
2005 kvm_write_wall_clock(vcpu->kvm, data);
2007 case MSR_KVM_SYSTEM_TIME_NEW:
2008 case MSR_KVM_SYSTEM_TIME: {
2010 struct kvm_arch *ka = &vcpu->kvm->arch;
2012 kvmclock_reset(vcpu);
2014 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2015 bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2017 if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2018 set_bit(KVM_REQ_MASTERCLOCK_UPDATE,
2021 ka->boot_vcpu_runs_old_kvmclock = tmp;
2024 vcpu->arch.time = data;
2025 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2027 /* we verify if the enable bit is set... */
2031 gpa_offset = data & ~(PAGE_MASK | 1);
2033 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2034 &vcpu->arch.pv_time, data & ~1ULL,
2035 sizeof(struct pvclock_vcpu_time_info)))
2036 vcpu->arch.pv_time_enabled = false;
2038 vcpu->arch.pv_time_enabled = true;
2042 case MSR_KVM_ASYNC_PF_EN:
2043 if (kvm_pv_enable_async_pf(vcpu, data))
2046 case MSR_KVM_STEAL_TIME:
2048 if (unlikely(!sched_info_on()))
2051 if (data & KVM_STEAL_RESERVED_MASK)
2054 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2055 data & KVM_STEAL_VALID_BITS,
2056 sizeof(struct kvm_steal_time)))
2059 vcpu->arch.st.msr_val = data;
2061 if (!(data & KVM_MSR_ENABLED))
2064 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2067 case MSR_KVM_PV_EOI_EN:
2068 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2072 case MSR_IA32_MCG_CTL:
2073 case MSR_IA32_MCG_STATUS:
2074 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2075 return set_msr_mce(vcpu, msr, data);
2077 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2078 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2079 pr = true; /* fall through */
2080 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2081 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2082 if (kvm_pmu_is_valid_msr(vcpu, msr))
2083 return kvm_pmu_set_msr(vcpu, msr_info);
2085 if (pr || data != 0)
2086 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2087 "0x%x data 0x%llx\n", msr, data);
2089 case MSR_K7_CLK_CTL:
2091 * Ignore all writes to this no longer documented MSR.
2092 * Writes are only relevant for old K7 processors,
2093 * all pre-dating SVM, but a recommended workaround from
2094 * AMD for these chips. It is possible to specify the
2095 * affected processor models on the command line, hence
2096 * the need to ignore the workaround.
2099 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2100 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2101 case HV_X64_MSR_CRASH_CTL:
2102 return kvm_hv_set_msr_common(vcpu, msr, data,
2103 msr_info->host_initiated);
2104 case MSR_IA32_BBL_CR_CTL3:
2105 /* Drop writes to this legacy MSR -- see rdmsr
2106 * counterpart for further detail.
2108 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
2110 case MSR_AMD64_OSVW_ID_LENGTH:
2111 if (!guest_cpuid_has_osvw(vcpu))
2113 vcpu->arch.osvw.length = data;
2115 case MSR_AMD64_OSVW_STATUS:
2116 if (!guest_cpuid_has_osvw(vcpu))
2118 vcpu->arch.osvw.status = data;
2121 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2122 return xen_hvm_config(vcpu, data);
2123 if (kvm_pmu_is_valid_msr(vcpu, msr))
2124 return kvm_pmu_set_msr(vcpu, msr_info);
2126 vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
2130 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
2137 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2141 * Reads an msr value (of 'msr_index') into 'pdata'.
2142 * Returns 0 on success, non-0 otherwise.
2143 * Assumes vcpu_load() was already called.
2145 int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2147 return kvm_x86_ops->get_msr(vcpu, msr);
2149 EXPORT_SYMBOL_GPL(kvm_get_msr);
2151 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2154 u64 mcg_cap = vcpu->arch.mcg_cap;
2155 unsigned bank_num = mcg_cap & 0xff;
2158 case MSR_IA32_P5_MC_ADDR:
2159 case MSR_IA32_P5_MC_TYPE:
2162 case MSR_IA32_MCG_CAP:
2163 data = vcpu->arch.mcg_cap;
2165 case MSR_IA32_MCG_CTL:
2166 if (!(mcg_cap & MCG_CTL_P))
2168 data = vcpu->arch.mcg_ctl;
2170 case MSR_IA32_MCG_STATUS:
2171 data = vcpu->arch.mcg_status;
2174 if (msr >= MSR_IA32_MC0_CTL &&
2175 msr < MSR_IA32_MCx_CTL(bank_num)) {
2176 u32 offset = msr - MSR_IA32_MC0_CTL;
2177 data = vcpu->arch.mce_banks[offset];
2186 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2188 switch (msr_info->index) {
2189 case MSR_IA32_PLATFORM_ID:
2190 case MSR_IA32_EBL_CR_POWERON:
2191 case MSR_IA32_DEBUGCTLMSR:
2192 case MSR_IA32_LASTBRANCHFROMIP:
2193 case MSR_IA32_LASTBRANCHTOIP:
2194 case MSR_IA32_LASTINTFROMIP:
2195 case MSR_IA32_LASTINTTOIP:
2197 case MSR_K8_TSEG_ADDR:
2198 case MSR_K8_TSEG_MASK:
2200 case MSR_VM_HSAVE_PA:
2201 case MSR_K8_INT_PENDING_MSG:
2202 case MSR_AMD64_NB_CFG:
2203 case MSR_FAM10H_MMIO_CONF_BASE:
2204 case MSR_AMD64_BU_CFG2:
2207 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2208 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2209 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2210 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2211 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2212 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2215 case MSR_IA32_UCODE_REV:
2216 msr_info->data = 0x100000000ULL;
2219 case 0x200 ... 0x2ff:
2220 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2221 case 0xcd: /* fsb frequency */
2225 * MSR_EBC_FREQUENCY_ID
2226 * Conservative value valid for even the basic CPU models.
2227 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2228 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2229 * and 266MHz for model 3, or 4. Set Core Clock
2230 * Frequency to System Bus Frequency Ratio to 1 (bits
2231 * 31:24) even though these are only valid for CPU
2232 * models > 2, however guests may end up dividing or
2233 * multiplying by zero otherwise.
2235 case MSR_EBC_FREQUENCY_ID:
2236 msr_info->data = 1 << 24;
2238 case MSR_IA32_APICBASE:
2239 msr_info->data = kvm_get_apic_base(vcpu);
2241 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2242 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2244 case MSR_IA32_TSCDEADLINE:
2245 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2247 case MSR_IA32_TSC_ADJUST:
2248 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2250 case MSR_IA32_MISC_ENABLE:
2251 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
2253 case MSR_IA32_SMBASE:
2254 if (!msr_info->host_initiated)
2256 msr_info->data = vcpu->arch.smbase;
2258 case MSR_IA32_PERF_STATUS:
2259 /* TSC increment by tick */
2260 msr_info->data = 1000ULL;
2261 /* CPU multiplier */
2262 msr_info->data |= (((uint64_t)4ULL) << 40);
2265 msr_info->data = vcpu->arch.efer;
2267 case MSR_KVM_WALL_CLOCK:
2268 case MSR_KVM_WALL_CLOCK_NEW:
2269 msr_info->data = vcpu->kvm->arch.wall_clock;
2271 case MSR_KVM_SYSTEM_TIME:
2272 case MSR_KVM_SYSTEM_TIME_NEW:
2273 msr_info->data = vcpu->arch.time;
2275 case MSR_KVM_ASYNC_PF_EN:
2276 msr_info->data = vcpu->arch.apf.msr_val;
2278 case MSR_KVM_STEAL_TIME:
2279 msr_info->data = vcpu->arch.st.msr_val;
2281 case MSR_KVM_PV_EOI_EN:
2282 msr_info->data = vcpu->arch.pv_eoi.msr_val;
2284 case MSR_IA32_P5_MC_ADDR:
2285 case MSR_IA32_P5_MC_TYPE:
2286 case MSR_IA32_MCG_CAP:
2287 case MSR_IA32_MCG_CTL:
2288 case MSR_IA32_MCG_STATUS:
2289 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2290 return get_msr_mce(vcpu, msr_info->index, &msr_info->data);
2291 case MSR_K7_CLK_CTL:
2293 * Provide expected ramp-up count for K7. All other
2294 * are set to zero, indicating minimum divisors for
2297 * This prevents guest kernels on AMD host with CPU
2298 * type 6, model 8 and higher from exploding due to
2299 * the rdmsr failing.
2301 msr_info->data = 0x20000000;
2303 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2304 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2305 case HV_X64_MSR_CRASH_CTL:
2306 return kvm_hv_get_msr_common(vcpu,
2307 msr_info->index, &msr_info->data);
2309 case MSR_IA32_BBL_CR_CTL3:
2310 /* This legacy MSR exists but isn't fully documented in current
2311 * silicon. It is however accessed by winxp in very narrow
2312 * scenarios where it sets bit #19, itself documented as
2313 * a "reserved" bit. Best effort attempt to source coherent
2314 * read data here should the balance of the register be
2315 * interpreted by the guest:
2317 * L2 cache control register 3: 64GB range, 256KB size,
2318 * enabled, latency 0x1, configured
2320 msr_info->data = 0xbe702111;
2322 case MSR_AMD64_OSVW_ID_LENGTH:
2323 if (!guest_cpuid_has_osvw(vcpu))
2325 msr_info->data = vcpu->arch.osvw.length;
2327 case MSR_AMD64_OSVW_STATUS:
2328 if (!guest_cpuid_has_osvw(vcpu))
2330 msr_info->data = vcpu->arch.osvw.status;
2333 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2334 return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2336 vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr_info->index);
2339 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr_info->index);
2346 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2349 * Read or write a bunch of msrs. All parameters are kernel addresses.
2351 * @return number of msrs set successfully.
2353 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2354 struct kvm_msr_entry *entries,
2355 int (*do_msr)(struct kvm_vcpu *vcpu,
2356 unsigned index, u64 *data))
2360 idx = srcu_read_lock(&vcpu->kvm->srcu);
2361 for (i = 0; i < msrs->nmsrs; ++i)
2362 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2364 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2370 * Read or write a bunch of msrs. Parameters are user addresses.
2372 * @return number of msrs set successfully.
2374 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2375 int (*do_msr)(struct kvm_vcpu *vcpu,
2376 unsigned index, u64 *data),
2379 struct kvm_msrs msrs;
2380 struct kvm_msr_entry *entries;
2385 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2389 if (msrs.nmsrs >= MAX_IO_MSRS)
2392 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2393 entries = memdup_user(user_msrs->entries, size);
2394 if (IS_ERR(entries)) {
2395 r = PTR_ERR(entries);
2399 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2404 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2415 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2420 case KVM_CAP_IRQCHIP:
2422 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2423 case KVM_CAP_SET_TSS_ADDR:
2424 case KVM_CAP_EXT_CPUID:
2425 case KVM_CAP_EXT_EMUL_CPUID:
2426 case KVM_CAP_CLOCKSOURCE:
2428 case KVM_CAP_NOP_IO_DELAY:
2429 case KVM_CAP_MP_STATE:
2430 case KVM_CAP_SYNC_MMU:
2431 case KVM_CAP_USER_NMI:
2432 case KVM_CAP_REINJECT_CONTROL:
2433 case KVM_CAP_IRQ_INJECT_STATUS:
2434 case KVM_CAP_IOEVENTFD:
2435 case KVM_CAP_IOEVENTFD_NO_LENGTH:
2437 case KVM_CAP_PIT_STATE2:
2438 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2439 case KVM_CAP_XEN_HVM:
2440 case KVM_CAP_ADJUST_CLOCK:
2441 case KVM_CAP_VCPU_EVENTS:
2442 case KVM_CAP_HYPERV:
2443 case KVM_CAP_HYPERV_VAPIC:
2444 case KVM_CAP_HYPERV_SPIN:
2445 case KVM_CAP_PCI_SEGMENT:
2446 case KVM_CAP_DEBUGREGS:
2447 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2449 case KVM_CAP_ASYNC_PF:
2450 case KVM_CAP_GET_TSC_KHZ:
2451 case KVM_CAP_KVMCLOCK_CTRL:
2452 case KVM_CAP_READONLY_MEM:
2453 case KVM_CAP_HYPERV_TIME:
2454 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2455 case KVM_CAP_TSC_DEADLINE_TIMER:
2456 case KVM_CAP_ENABLE_CAP_VM:
2457 case KVM_CAP_DISABLE_QUIRKS:
2458 case KVM_CAP_SET_BOOT_CPU_ID:
2459 case KVM_CAP_SPLIT_IRQCHIP:
2460 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2461 case KVM_CAP_ASSIGN_DEV_IRQ:
2462 case KVM_CAP_PCI_2_3:
2466 case KVM_CAP_X86_SMM:
2467 /* SMBASE is usually relocated above 1M on modern chipsets,
2468 * and SMM handlers might indeed rely on 4G segment limits,
2469 * so do not report SMM to be available if real mode is
2470 * emulated via vm86 mode. Still, do not go to great lengths
2471 * to avoid userspace's usage of the feature, because it is a
2472 * fringe case that is not enabled except via specific settings
2473 * of the module parameters.
2475 r = kvm_x86_ops->cpu_has_high_real_mode_segbase();
2477 case KVM_CAP_COALESCED_MMIO:
2478 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2481 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2483 case KVM_CAP_NR_VCPUS:
2484 r = KVM_SOFT_MAX_VCPUS;
2486 case KVM_CAP_MAX_VCPUS:
2489 case KVM_CAP_NR_MEMSLOTS:
2490 r = KVM_USER_MEM_SLOTS;
2492 case KVM_CAP_PV_MMU: /* obsolete */
2495 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2497 r = iommu_present(&pci_bus_type);
2501 r = KVM_MAX_MCE_BANKS;
2506 case KVM_CAP_TSC_CONTROL:
2507 r = kvm_has_tsc_control;
2517 long kvm_arch_dev_ioctl(struct file *filp,
2518 unsigned int ioctl, unsigned long arg)
2520 void __user *argp = (void __user *)arg;
2524 case KVM_GET_MSR_INDEX_LIST: {
2525 struct kvm_msr_list __user *user_msr_list = argp;
2526 struct kvm_msr_list msr_list;
2530 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2533 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
2534 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2537 if (n < msr_list.nmsrs)
2540 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2541 num_msrs_to_save * sizeof(u32)))
2543 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2545 num_emulated_msrs * sizeof(u32)))
2550 case KVM_GET_SUPPORTED_CPUID:
2551 case KVM_GET_EMULATED_CPUID: {
2552 struct kvm_cpuid2 __user *cpuid_arg = argp;
2553 struct kvm_cpuid2 cpuid;
2556 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2559 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2565 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2570 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2573 mce_cap = KVM_MCE_CAP_SUPPORTED;
2575 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2587 static void wbinvd_ipi(void *garbage)
2592 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2594 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2597 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2599 /* Address WBINVD may be executed by guest */
2600 if (need_emulate_wbinvd(vcpu)) {
2601 if (kvm_x86_ops->has_wbinvd_exit())
2602 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2603 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2604 smp_call_function_single(vcpu->cpu,
2605 wbinvd_ipi, NULL, 1);
2608 kvm_x86_ops->vcpu_load(vcpu, cpu);
2610 /* Apply any externally detected TSC adjustments (due to suspend) */
2611 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2612 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2613 vcpu->arch.tsc_offset_adjustment = 0;
2614 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2617 if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2618 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2619 rdtsc() - vcpu->arch.last_host_tsc;
2621 mark_tsc_unstable("KVM discovered backwards TSC");
2622 if (check_tsc_unstable()) {
2623 u64 offset = kvm_x86_ops->compute_tsc_offset(vcpu,
2624 vcpu->arch.last_guest_tsc);
2625 kvm_x86_ops->write_tsc_offset(vcpu, offset);
2626 vcpu->arch.tsc_catchup = 1;
2629 * On a host with synchronized TSC, there is no need to update
2630 * kvmclock on vcpu->cpu migration
2632 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
2633 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2634 if (vcpu->cpu != cpu)
2635 kvm_migrate_timers(vcpu);
2639 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2642 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2644 kvm_x86_ops->vcpu_put(vcpu);
2645 kvm_put_guest_fpu(vcpu);
2646 vcpu->arch.last_host_tsc = rdtsc();
2649 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2650 struct kvm_lapic_state *s)
2652 kvm_x86_ops->sync_pir_to_irr(vcpu);
2653 memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2658 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2659 struct kvm_lapic_state *s)
2661 kvm_apic_post_state_restore(vcpu, s);
2662 update_cr8_intercept(vcpu);
2667 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2668 struct kvm_interrupt *irq)
2670 if (irq->irq >= KVM_NR_INTERRUPTS)
2673 if (!irqchip_in_kernel(vcpu->kvm)) {
2674 kvm_queue_interrupt(vcpu, irq->irq, false);
2675 kvm_make_request(KVM_REQ_EVENT, vcpu);
2680 * With in-kernel LAPIC, we only use this to inject EXTINT, so
2681 * fail for in-kernel 8259.
2683 if (pic_in_kernel(vcpu->kvm))
2686 if (vcpu->arch.pending_external_vector != -1)
2689 vcpu->arch.pending_external_vector = irq->irq;
2693 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2695 kvm_inject_nmi(vcpu);
2700 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
2702 kvm_make_request(KVM_REQ_SMI, vcpu);
2707 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2708 struct kvm_tpr_access_ctl *tac)
2712 vcpu->arch.tpr_access_reporting = !!tac->enabled;
2716 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2720 unsigned bank_num = mcg_cap & 0xff, bank;
2723 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2725 if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2728 vcpu->arch.mcg_cap = mcg_cap;
2729 /* Init IA32_MCG_CTL to all 1s */
2730 if (mcg_cap & MCG_CTL_P)
2731 vcpu->arch.mcg_ctl = ~(u64)0;
2732 /* Init IA32_MCi_CTL to all 1s */
2733 for (bank = 0; bank < bank_num; bank++)
2734 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2739 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2740 struct kvm_x86_mce *mce)
2742 u64 mcg_cap = vcpu->arch.mcg_cap;
2743 unsigned bank_num = mcg_cap & 0xff;
2744 u64 *banks = vcpu->arch.mce_banks;
2746 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2749 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2750 * reporting is disabled
2752 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2753 vcpu->arch.mcg_ctl != ~(u64)0)
2755 banks += 4 * mce->bank;
2757 * if IA32_MCi_CTL is not all 1s, the uncorrected error
2758 * reporting is disabled for the bank
2760 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2762 if (mce->status & MCI_STATUS_UC) {
2763 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2764 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2765 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2768 if (banks[1] & MCI_STATUS_VAL)
2769 mce->status |= MCI_STATUS_OVER;
2770 banks[2] = mce->addr;
2771 banks[3] = mce->misc;
2772 vcpu->arch.mcg_status = mce->mcg_status;
2773 banks[1] = mce->status;
2774 kvm_queue_exception(vcpu, MC_VECTOR);
2775 } else if (!(banks[1] & MCI_STATUS_VAL)
2776 || !(banks[1] & MCI_STATUS_UC)) {
2777 if (banks[1] & MCI_STATUS_VAL)
2778 mce->status |= MCI_STATUS_OVER;
2779 banks[2] = mce->addr;
2780 banks[3] = mce->misc;
2781 banks[1] = mce->status;
2783 banks[1] |= MCI_STATUS_OVER;
2787 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2788 struct kvm_vcpu_events *events)
2791 events->exception.injected =
2792 vcpu->arch.exception.pending &&
2793 !kvm_exception_is_soft(vcpu->arch.exception.nr);
2794 events->exception.nr = vcpu->arch.exception.nr;
2795 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2796 events->exception.pad = 0;
2797 events->exception.error_code = vcpu->arch.exception.error_code;
2799 events->interrupt.injected =
2800 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
2801 events->interrupt.nr = vcpu->arch.interrupt.nr;
2802 events->interrupt.soft = 0;
2803 events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
2805 events->nmi.injected = vcpu->arch.nmi_injected;
2806 events->nmi.pending = vcpu->arch.nmi_pending != 0;
2807 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
2808 events->nmi.pad = 0;
2810 events->sipi_vector = 0; /* never valid when reporting to user space */
2812 events->smi.smm = is_smm(vcpu);
2813 events->smi.pending = vcpu->arch.smi_pending;
2814 events->smi.smm_inside_nmi =
2815 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
2816 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
2818 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
2819 | KVM_VCPUEVENT_VALID_SHADOW
2820 | KVM_VCPUEVENT_VALID_SMM);
2821 memset(&events->reserved, 0, sizeof(events->reserved));
2824 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
2825 struct kvm_vcpu_events *events)
2827 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
2828 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2829 | KVM_VCPUEVENT_VALID_SHADOW
2830 | KVM_VCPUEVENT_VALID_SMM))
2834 vcpu->arch.exception.pending = events->exception.injected;
2835 vcpu->arch.exception.nr = events->exception.nr;
2836 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
2837 vcpu->arch.exception.error_code = events->exception.error_code;
2839 vcpu->arch.interrupt.pending = events->interrupt.injected;
2840 vcpu->arch.interrupt.nr = events->interrupt.nr;
2841 vcpu->arch.interrupt.soft = events->interrupt.soft;
2842 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
2843 kvm_x86_ops->set_interrupt_shadow(vcpu,
2844 events->interrupt.shadow);
2846 vcpu->arch.nmi_injected = events->nmi.injected;
2847 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
2848 vcpu->arch.nmi_pending = events->nmi.pending;
2849 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
2851 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
2852 kvm_vcpu_has_lapic(vcpu))
2853 vcpu->arch.apic->sipi_vector = events->sipi_vector;
2855 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
2856 if (events->smi.smm)
2857 vcpu->arch.hflags |= HF_SMM_MASK;
2859 vcpu->arch.hflags &= ~HF_SMM_MASK;
2860 vcpu->arch.smi_pending = events->smi.pending;
2861 if (events->smi.smm_inside_nmi)
2862 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
2864 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
2865 if (kvm_vcpu_has_lapic(vcpu)) {
2866 if (events->smi.latched_init)
2867 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
2869 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
2873 kvm_make_request(KVM_REQ_EVENT, vcpu);
2878 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
2879 struct kvm_debugregs *dbgregs)
2883 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
2884 kvm_get_dr(vcpu, 6, &val);
2886 dbgregs->dr7 = vcpu->arch.dr7;
2888 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
2891 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
2892 struct kvm_debugregs *dbgregs)
2897 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
2898 kvm_update_dr0123(vcpu);
2899 vcpu->arch.dr6 = dbgregs->dr6;
2900 kvm_update_dr6(vcpu);
2901 vcpu->arch.dr7 = dbgregs->dr7;
2902 kvm_update_dr7(vcpu);
2907 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
2909 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
2911 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
2912 u64 xstate_bv = xsave->header.xfeatures;
2916 * Copy legacy XSAVE area, to avoid complications with CPUID
2917 * leaves 0 and 1 in the loop below.
2919 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
2922 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
2925 * Copy each region from the possibly compacted offset to the
2926 * non-compacted offset.
2928 valid = xstate_bv & ~XSTATE_FPSSE;
2930 u64 feature = valid & -valid;
2931 int index = fls64(feature) - 1;
2932 void *src = get_xsave_addr(xsave, feature);
2935 u32 size, offset, ecx, edx;
2936 cpuid_count(XSTATE_CPUID, index,
2937 &size, &offset, &ecx, &edx);
2938 memcpy(dest + offset, src, size);
2945 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
2947 struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
2948 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
2952 * Copy legacy XSAVE area, to avoid complications with CPUID
2953 * leaves 0 and 1 in the loop below.
2955 memcpy(xsave, src, XSAVE_HDR_OFFSET);
2957 /* Set XSTATE_BV and possibly XCOMP_BV. */
2958 xsave->header.xfeatures = xstate_bv;
2960 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
2963 * Copy each region from the non-compacted offset to the
2964 * possibly compacted offset.
2966 valid = xstate_bv & ~XSTATE_FPSSE;
2968 u64 feature = valid & -valid;
2969 int index = fls64(feature) - 1;
2970 void *dest = get_xsave_addr(xsave, feature);
2973 u32 size, offset, ecx, edx;
2974 cpuid_count(XSTATE_CPUID, index,
2975 &size, &offset, &ecx, &edx);
2976 memcpy(dest, src + offset, size);
2983 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
2984 struct kvm_xsave *guest_xsave)
2986 if (cpu_has_xsave) {
2987 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
2988 fill_xsave((u8 *) guest_xsave->region, vcpu);
2990 memcpy(guest_xsave->region,
2991 &vcpu->arch.guest_fpu.state.fxsave,
2992 sizeof(struct fxregs_state));
2993 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
2998 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
2999 struct kvm_xsave *guest_xsave)
3002 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3004 if (cpu_has_xsave) {
3006 * Here we allow setting states that are not present in
3007 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
3008 * with old userspace.
3010 if (xstate_bv & ~kvm_supported_xcr0())
3012 load_xsave(vcpu, (u8 *)guest_xsave->region);
3014 if (xstate_bv & ~XSTATE_FPSSE)
3016 memcpy(&vcpu->arch.guest_fpu.state.fxsave,
3017 guest_xsave->region, sizeof(struct fxregs_state));
3022 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3023 struct kvm_xcrs *guest_xcrs)
3025 if (!cpu_has_xsave) {
3026 guest_xcrs->nr_xcrs = 0;
3030 guest_xcrs->nr_xcrs = 1;
3031 guest_xcrs->flags = 0;
3032 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3033 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3036 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3037 struct kvm_xcrs *guest_xcrs)
3044 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3047 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3048 /* Only support XCR0 currently */
3049 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3050 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3051 guest_xcrs->xcrs[i].value);
3060 * kvm_set_guest_paused() indicates to the guest kernel that it has been
3061 * stopped by the hypervisor. This function will be called from the host only.
3062 * EINVAL is returned when the host attempts to set the flag for a guest that
3063 * does not support pv clocks.
3065 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3067 if (!vcpu->arch.pv_time_enabled)
3069 vcpu->arch.pvclock_set_guest_stopped_request = true;
3070 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3074 long kvm_arch_vcpu_ioctl(struct file *filp,
3075 unsigned int ioctl, unsigned long arg)
3077 struct kvm_vcpu *vcpu = filp->private_data;
3078 void __user *argp = (void __user *)arg;
3081 struct kvm_lapic_state *lapic;
3082 struct kvm_xsave *xsave;
3083 struct kvm_xcrs *xcrs;
3089 case KVM_GET_LAPIC: {
3091 if (!vcpu->arch.apic)
3093 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3098 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3102 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3107 case KVM_SET_LAPIC: {
3109 if (!vcpu->arch.apic)
3111 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3112 if (IS_ERR(u.lapic))
3113 return PTR_ERR(u.lapic);
3115 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3118 case KVM_INTERRUPT: {
3119 struct kvm_interrupt irq;
3122 if (copy_from_user(&irq, argp, sizeof irq))
3124 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3128 r = kvm_vcpu_ioctl_nmi(vcpu);
3132 r = kvm_vcpu_ioctl_smi(vcpu);
3135 case KVM_SET_CPUID: {
3136 struct kvm_cpuid __user *cpuid_arg = argp;
3137 struct kvm_cpuid cpuid;
3140 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3142 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3145 case KVM_SET_CPUID2: {
3146 struct kvm_cpuid2 __user *cpuid_arg = argp;
3147 struct kvm_cpuid2 cpuid;
3150 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3152 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3153 cpuid_arg->entries);
3156 case KVM_GET_CPUID2: {
3157 struct kvm_cpuid2 __user *cpuid_arg = argp;
3158 struct kvm_cpuid2 cpuid;
3161 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3163 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3164 cpuid_arg->entries);
3168 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3174 r = msr_io(vcpu, argp, do_get_msr, 1);
3177 r = msr_io(vcpu, argp, do_set_msr, 0);
3179 case KVM_TPR_ACCESS_REPORTING: {
3180 struct kvm_tpr_access_ctl tac;
3183 if (copy_from_user(&tac, argp, sizeof tac))
3185 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3189 if (copy_to_user(argp, &tac, sizeof tac))
3194 case KVM_SET_VAPIC_ADDR: {
3195 struct kvm_vapic_addr va;
3198 if (!lapic_in_kernel(vcpu))
3201 if (copy_from_user(&va, argp, sizeof va))
3203 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3206 case KVM_X86_SETUP_MCE: {
3210 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3212 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3215 case KVM_X86_SET_MCE: {
3216 struct kvm_x86_mce mce;
3219 if (copy_from_user(&mce, argp, sizeof mce))
3221 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3224 case KVM_GET_VCPU_EVENTS: {
3225 struct kvm_vcpu_events events;
3227 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3230 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3235 case KVM_SET_VCPU_EVENTS: {
3236 struct kvm_vcpu_events events;
3239 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3242 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3245 case KVM_GET_DEBUGREGS: {
3246 struct kvm_debugregs dbgregs;
3248 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3251 if (copy_to_user(argp, &dbgregs,
3252 sizeof(struct kvm_debugregs)))
3257 case KVM_SET_DEBUGREGS: {
3258 struct kvm_debugregs dbgregs;
3261 if (copy_from_user(&dbgregs, argp,
3262 sizeof(struct kvm_debugregs)))
3265 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3268 case KVM_GET_XSAVE: {
3269 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3274 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3277 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3282 case KVM_SET_XSAVE: {
3283 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3284 if (IS_ERR(u.xsave))
3285 return PTR_ERR(u.xsave);
3287 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3290 case KVM_GET_XCRS: {
3291 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3296 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3299 if (copy_to_user(argp, u.xcrs,
3300 sizeof(struct kvm_xcrs)))
3305 case KVM_SET_XCRS: {
3306 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3308 return PTR_ERR(u.xcrs);
3310 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3313 case KVM_SET_TSC_KHZ: {
3317 user_tsc_khz = (u32)arg;
3319 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3322 if (user_tsc_khz == 0)
3323 user_tsc_khz = tsc_khz;
3325 kvm_set_tsc_khz(vcpu, user_tsc_khz);
3330 case KVM_GET_TSC_KHZ: {
3331 r = vcpu->arch.virtual_tsc_khz;
3334 case KVM_KVMCLOCK_CTRL: {
3335 r = kvm_set_guest_paused(vcpu);
3346 int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3348 return VM_FAULT_SIGBUS;
3351 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3355 if (addr > (unsigned int)(-3 * PAGE_SIZE))
3357 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3361 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3364 kvm->arch.ept_identity_map_addr = ident_addr;
3368 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3369 u32 kvm_nr_mmu_pages)
3371 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3374 mutex_lock(&kvm->slots_lock);
3376 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3377 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3379 mutex_unlock(&kvm->slots_lock);
3383 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3385 return kvm->arch.n_max_mmu_pages;
3388 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3393 switch (chip->chip_id) {
3394 case KVM_IRQCHIP_PIC_MASTER:
3395 memcpy(&chip->chip.pic,
3396 &pic_irqchip(kvm)->pics[0],
3397 sizeof(struct kvm_pic_state));
3399 case KVM_IRQCHIP_PIC_SLAVE:
3400 memcpy(&chip->chip.pic,
3401 &pic_irqchip(kvm)->pics[1],
3402 sizeof(struct kvm_pic_state));
3404 case KVM_IRQCHIP_IOAPIC:
3405 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3414 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3419 switch (chip->chip_id) {
3420 case KVM_IRQCHIP_PIC_MASTER:
3421 spin_lock(&pic_irqchip(kvm)->lock);
3422 memcpy(&pic_irqchip(kvm)->pics[0],
3424 sizeof(struct kvm_pic_state));
3425 spin_unlock(&pic_irqchip(kvm)->lock);
3427 case KVM_IRQCHIP_PIC_SLAVE:
3428 spin_lock(&pic_irqchip(kvm)->lock);
3429 memcpy(&pic_irqchip(kvm)->pics[1],
3431 sizeof(struct kvm_pic_state));
3432 spin_unlock(&pic_irqchip(kvm)->lock);
3434 case KVM_IRQCHIP_IOAPIC:
3435 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3441 kvm_pic_update_irq(pic_irqchip(kvm));
3445 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3447 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3448 memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
3449 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3453 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3455 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3456 memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
3457 kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
3458 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3462 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3464 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3465 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3466 sizeof(ps->channels));
3467 ps->flags = kvm->arch.vpit->pit_state.flags;
3468 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3469 memset(&ps->reserved, 0, sizeof(ps->reserved));
3473 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3476 u32 prev_legacy, cur_legacy;
3477 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3478 prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3479 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3480 if (!prev_legacy && cur_legacy)
3482 memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
3483 sizeof(kvm->arch.vpit->pit_state.channels));
3484 kvm->arch.vpit->pit_state.flags = ps->flags;
3485 kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
3486 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3490 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3491 struct kvm_reinject_control *control)
3493 if (!kvm->arch.vpit)
3495 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3496 kvm->arch.vpit->pit_state.reinject = control->pit_reinject;
3497 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3502 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
3503 * @kvm: kvm instance
3504 * @log: slot id and address to which we copy the log
3506 * Steps 1-4 below provide general overview of dirty page logging. See
3507 * kvm_get_dirty_log_protect() function description for additional details.
3509 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
3510 * always flush the TLB (step 4) even if previous step failed and the dirty
3511 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
3512 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
3513 * writes will be marked dirty for next log read.
3515 * 1. Take a snapshot of the bit and clear it if needed.
3516 * 2. Write protect the corresponding page.
3517 * 3. Copy the snapshot to the userspace.
3518 * 4. Flush TLB's if needed.
3520 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
3522 bool is_dirty = false;
3525 mutex_lock(&kvm->slots_lock);
3528 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
3530 if (kvm_x86_ops->flush_log_dirty)
3531 kvm_x86_ops->flush_log_dirty(kvm);
3533 r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
3536 * All the TLBs can be flushed out of mmu lock, see the comments in
3537 * kvm_mmu_slot_remove_write_access().
3539 lockdep_assert_held(&kvm->slots_lock);
3541 kvm_flush_remote_tlbs(kvm);
3543 mutex_unlock(&kvm->slots_lock);
3547 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
3550 if (!irqchip_in_kernel(kvm))
3553 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3554 irq_event->irq, irq_event->level,
3559 static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3560 struct kvm_enable_cap *cap)
3568 case KVM_CAP_DISABLE_QUIRKS:
3569 kvm->arch.disabled_quirks = cap->args[0];
3572 case KVM_CAP_SPLIT_IRQCHIP: {
3573 mutex_lock(&kvm->lock);
3575 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
3576 goto split_irqchip_unlock;
3578 if (irqchip_in_kernel(kvm))
3579 goto split_irqchip_unlock;
3580 if (atomic_read(&kvm->online_vcpus))
3581 goto split_irqchip_unlock;
3582 r = kvm_setup_empty_irq_routing(kvm);
3584 goto split_irqchip_unlock;
3585 /* Pairs with irqchip_in_kernel. */
3587 kvm->arch.irqchip_split = true;
3588 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
3590 split_irqchip_unlock:
3591 mutex_unlock(&kvm->lock);
3601 long kvm_arch_vm_ioctl(struct file *filp,
3602 unsigned int ioctl, unsigned long arg)
3604 struct kvm *kvm = filp->private_data;
3605 void __user *argp = (void __user *)arg;
3608 * This union makes it completely explicit to gcc-3.x
3609 * that these two variables' stack usage should be
3610 * combined, not added together.
3613 struct kvm_pit_state ps;
3614 struct kvm_pit_state2 ps2;
3615 struct kvm_pit_config pit_config;
3619 case KVM_SET_TSS_ADDR:
3620 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3622 case KVM_SET_IDENTITY_MAP_ADDR: {
3626 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3628 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3631 case KVM_SET_NR_MMU_PAGES:
3632 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3634 case KVM_GET_NR_MMU_PAGES:
3635 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3637 case KVM_CREATE_IRQCHIP: {
3638 struct kvm_pic *vpic;
3640 mutex_lock(&kvm->lock);
3643 goto create_irqchip_unlock;
3645 if (atomic_read(&kvm->online_vcpus))
3646 goto create_irqchip_unlock;
3648 vpic = kvm_create_pic(kvm);
3650 r = kvm_ioapic_init(kvm);
3652 mutex_lock(&kvm->slots_lock);
3653 kvm_destroy_pic(vpic);
3654 mutex_unlock(&kvm->slots_lock);
3655 goto create_irqchip_unlock;
3658 goto create_irqchip_unlock;
3659 r = kvm_setup_default_irq_routing(kvm);
3661 mutex_lock(&kvm->slots_lock);
3662 mutex_lock(&kvm->irq_lock);
3663 kvm_ioapic_destroy(kvm);
3664 kvm_destroy_pic(vpic);
3665 mutex_unlock(&kvm->irq_lock);
3666 mutex_unlock(&kvm->slots_lock);
3667 goto create_irqchip_unlock;
3669 /* Write kvm->irq_routing before kvm->arch.vpic. */
3671 kvm->arch.vpic = vpic;
3672 create_irqchip_unlock:
3673 mutex_unlock(&kvm->lock);
3676 case KVM_CREATE_PIT:
3677 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3679 case KVM_CREATE_PIT2:
3681 if (copy_from_user(&u.pit_config, argp,
3682 sizeof(struct kvm_pit_config)))
3685 mutex_lock(&kvm->slots_lock);
3688 goto create_pit_unlock;
3690 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3694 mutex_unlock(&kvm->slots_lock);
3696 case KVM_GET_IRQCHIP: {
3697 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3698 struct kvm_irqchip *chip;
3700 chip = memdup_user(argp, sizeof(*chip));
3707 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
3708 goto get_irqchip_out;
3709 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3711 goto get_irqchip_out;
3713 if (copy_to_user(argp, chip, sizeof *chip))
3714 goto get_irqchip_out;
3720 case KVM_SET_IRQCHIP: {
3721 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3722 struct kvm_irqchip *chip;
3724 chip = memdup_user(argp, sizeof(*chip));
3731 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
3732 goto set_irqchip_out;
3733 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3735 goto set_irqchip_out;
3743 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
3746 if (!kvm->arch.vpit)
3748 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
3752 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
3759 if (copy_from_user(&u.ps, argp, sizeof u.ps))
3762 if (!kvm->arch.vpit)
3764 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
3767 case KVM_GET_PIT2: {
3769 if (!kvm->arch.vpit)
3771 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
3775 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
3780 case KVM_SET_PIT2: {
3782 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
3785 if (!kvm->arch.vpit)
3787 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
3790 case KVM_REINJECT_CONTROL: {
3791 struct kvm_reinject_control control;
3793 if (copy_from_user(&control, argp, sizeof(control)))
3795 r = kvm_vm_ioctl_reinject(kvm, &control);
3798 case KVM_SET_BOOT_CPU_ID:
3800 mutex_lock(&kvm->lock);
3801 if (atomic_read(&kvm->online_vcpus) != 0)
3804 kvm->arch.bsp_vcpu_id = arg;
3805 mutex_unlock(&kvm->lock);
3807 case KVM_XEN_HVM_CONFIG: {
3809 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
3810 sizeof(struct kvm_xen_hvm_config)))
3813 if (kvm->arch.xen_hvm_config.flags)
3818 case KVM_SET_CLOCK: {
3819 struct kvm_clock_data user_ns;
3824 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
3832 local_irq_disable();
3833 now_ns = get_kernel_ns();
3834 delta = user_ns.clock - now_ns;
3836 kvm->arch.kvmclock_offset = delta;
3837 kvm_gen_update_masterclock(kvm);
3840 case KVM_GET_CLOCK: {
3841 struct kvm_clock_data user_ns;
3844 local_irq_disable();
3845 now_ns = get_kernel_ns();
3846 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
3849 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
3852 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
3857 case KVM_ENABLE_CAP: {
3858 struct kvm_enable_cap cap;
3861 if (copy_from_user(&cap, argp, sizeof(cap)))
3863 r = kvm_vm_ioctl_enable_cap(kvm, &cap);
3867 r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
3873 static void kvm_init_msr_list(void)
3878 for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
3879 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
3883 * Even MSRs that are valid in the host may not be exposed
3884 * to the guests in some cases. We could work around this
3885 * in VMX with the generic MSR save/load machinery, but it
3886 * is not really worthwhile since it will really only
3887 * happen with nested virtualization.
3889 switch (msrs_to_save[i]) {
3890 case MSR_IA32_BNDCFGS:
3891 if (!kvm_x86_ops->mpx_supported())
3899 msrs_to_save[j] = msrs_to_save[i];
3902 num_msrs_to_save = j;
3904 for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
3905 switch (emulated_msrs[i]) {
3906 case MSR_IA32_SMBASE:
3907 if (!kvm_x86_ops->cpu_has_high_real_mode_segbase())
3915 emulated_msrs[j] = emulated_msrs[i];
3918 num_emulated_msrs = j;
3921 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
3929 if (!(vcpu->arch.apic &&
3930 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
3931 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
3942 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
3949 if (!(vcpu->arch.apic &&
3950 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
3952 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
3954 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
3964 static void kvm_set_segment(struct kvm_vcpu *vcpu,
3965 struct kvm_segment *var, int seg)
3967 kvm_x86_ops->set_segment(vcpu, var, seg);
3970 void kvm_get_segment(struct kvm_vcpu *vcpu,
3971 struct kvm_segment *var, int seg)
3973 kvm_x86_ops->get_segment(vcpu, var, seg);
3976 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
3977 struct x86_exception *exception)
3981 BUG_ON(!mmu_is_nested(vcpu));
3983 /* NPT walks are always user-walks */
3984 access |= PFERR_USER_MASK;
3985 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
3990 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
3991 struct x86_exception *exception)
3993 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3994 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3997 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
3998 struct x86_exception *exception)
4000 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4001 access |= PFERR_FETCH_MASK;
4002 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4005 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4006 struct x86_exception *exception)
4008 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4009 access |= PFERR_WRITE_MASK;
4010 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4013 /* uses this to access any guest's mapped memory without checking CPL */
4014 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4015 struct x86_exception *exception)
4017 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
4020 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4021 struct kvm_vcpu *vcpu, u32 access,
4022 struct x86_exception *exception)
4025 int r = X86EMUL_CONTINUE;
4028 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4030 unsigned offset = addr & (PAGE_SIZE-1);
4031 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4034 if (gpa == UNMAPPED_GVA)
4035 return X86EMUL_PROPAGATE_FAULT;
4036 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
4039 r = X86EMUL_IO_NEEDED;
4051 /* used for instruction fetching */
4052 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4053 gva_t addr, void *val, unsigned int bytes,
4054 struct x86_exception *exception)
4056 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4057 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4061 /* Inline kvm_read_guest_virt_helper for speed. */
4062 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
4064 if (unlikely(gpa == UNMAPPED_GVA))
4065 return X86EMUL_PROPAGATE_FAULT;
4067 offset = addr & (PAGE_SIZE-1);
4068 if (WARN_ON(offset + bytes > PAGE_SIZE))
4069 bytes = (unsigned)PAGE_SIZE - offset;
4070 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
4072 if (unlikely(ret < 0))
4073 return X86EMUL_IO_NEEDED;
4075 return X86EMUL_CONTINUE;
4078 int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
4079 gva_t addr, void *val, unsigned int bytes,
4080 struct x86_exception *exception)
4082 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4083 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4085 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4088 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4090 static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4091 gva_t addr, void *val, unsigned int bytes,
4092 struct x86_exception *exception)
4094 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4095 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
4098 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
4099 unsigned long addr, void *val, unsigned int bytes)
4101 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4102 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
4104 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
4107 int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4108 gva_t addr, void *val,
4110 struct x86_exception *exception)
4112 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4114 int r = X86EMUL_CONTINUE;
4117 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4120 unsigned offset = addr & (PAGE_SIZE-1);
4121 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4124 if (gpa == UNMAPPED_GVA)
4125 return X86EMUL_PROPAGATE_FAULT;
4126 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
4128 r = X86EMUL_IO_NEEDED;
4139 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4141 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4142 gpa_t *gpa, struct x86_exception *exception,
4145 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
4146 | (write ? PFERR_WRITE_MASK : 0);
4148 if (vcpu_match_mmio_gva(vcpu, gva)
4149 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
4150 vcpu->arch.access, access)) {
4151 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4152 (gva & (PAGE_SIZE - 1));
4153 trace_vcpu_match_mmio(gva, *gpa, write, false);
4157 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4159 if (*gpa == UNMAPPED_GVA)
4162 /* For APIC access vmexit */
4163 if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4166 if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
4167 trace_vcpu_match_mmio(gva, *gpa, write, true);
4174 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4175 const void *val, int bytes)
4179 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
4182 kvm_mmu_pte_write(vcpu, gpa, val, bytes);
4186 struct read_write_emulator_ops {
4187 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4189 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4190 void *val, int bytes);
4191 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4192 int bytes, void *val);
4193 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4194 void *val, int bytes);
4198 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4200 if (vcpu->mmio_read_completed) {
4201 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4202 vcpu->mmio_fragments[0].gpa, *(u64 *)val);
4203 vcpu->mmio_read_completed = 0;
4210 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4211 void *val, int bytes)
4213 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
4216 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4217 void *val, int bytes)
4219 return emulator_write_phys(vcpu, gpa, val, bytes);
4222 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4224 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
4225 return vcpu_mmio_write(vcpu, gpa, bytes, val);
4228 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4229 void *val, int bytes)
4231 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
4232 return X86EMUL_IO_NEEDED;
4235 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4236 void *val, int bytes)
4238 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
4240 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
4241 return X86EMUL_CONTINUE;
4244 static const struct read_write_emulator_ops read_emultor = {
4245 .read_write_prepare = read_prepare,
4246 .read_write_emulate = read_emulate,
4247 .read_write_mmio = vcpu_mmio_read,
4248 .read_write_exit_mmio = read_exit_mmio,
4251 static const struct read_write_emulator_ops write_emultor = {
4252 .read_write_emulate = write_emulate,
4253 .read_write_mmio = write_mmio,
4254 .read_write_exit_mmio = write_exit_mmio,
4258 static int emulator_read_write_onepage(unsigned long addr, void *val,
4260 struct x86_exception *exception,
4261 struct kvm_vcpu *vcpu,
4262 const struct read_write_emulator_ops *ops)
4266 bool write = ops->write;
4267 struct kvm_mmio_fragment *frag;
4269 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4272 return X86EMUL_PROPAGATE_FAULT;
4274 /* For APIC access vmexit */
4278 if (ops->read_write_emulate(vcpu, gpa, val, bytes))
4279 return X86EMUL_CONTINUE;
4283 * Is this MMIO handled locally?
4285 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4286 if (handled == bytes)
4287 return X86EMUL_CONTINUE;
4293 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
4294 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
4298 return X86EMUL_CONTINUE;
4301 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
4303 void *val, unsigned int bytes,
4304 struct x86_exception *exception,
4305 const struct read_write_emulator_ops *ops)
4307 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4311 if (ops->read_write_prepare &&
4312 ops->read_write_prepare(vcpu, val, bytes))
4313 return X86EMUL_CONTINUE;
4315 vcpu->mmio_nr_fragments = 0;
4317 /* Crossing a page boundary? */
4318 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4321 now = -addr & ~PAGE_MASK;
4322 rc = emulator_read_write_onepage(addr, val, now, exception,
4325 if (rc != X86EMUL_CONTINUE)
4328 if (ctxt->mode != X86EMUL_MODE_PROT64)
4334 rc = emulator_read_write_onepage(addr, val, bytes, exception,
4336 if (rc != X86EMUL_CONTINUE)
4339 if (!vcpu->mmio_nr_fragments)
4342 gpa = vcpu->mmio_fragments[0].gpa;
4344 vcpu->mmio_needed = 1;
4345 vcpu->mmio_cur_fragment = 0;
4347 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
4348 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
4349 vcpu->run->exit_reason = KVM_EXIT_MMIO;
4350 vcpu->run->mmio.phys_addr = gpa;
4352 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4355 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4359 struct x86_exception *exception)
4361 return emulator_read_write(ctxt, addr, val, bytes,
4362 exception, &read_emultor);
4365 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4369 struct x86_exception *exception)
4371 return emulator_read_write(ctxt, addr, (void *)val, bytes,
4372 exception, &write_emultor);
4375 #define CMPXCHG_TYPE(t, ptr, old, new) \
4376 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4378 #ifdef CONFIG_X86_64
4379 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4381 # define CMPXCHG64(ptr, old, new) \
4382 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4385 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4390 struct x86_exception *exception)
4392 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4398 /* guests cmpxchg8b have to be emulated atomically */
4399 if (bytes > 8 || (bytes & (bytes - 1)))
4402 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4404 if (gpa == UNMAPPED_GVA ||
4405 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4408 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4411 page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
4412 if (is_error_page(page))
4415 kaddr = kmap_atomic(page);
4416 kaddr += offset_in_page(gpa);
4419 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4422 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4425 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
4428 exchanged = CMPXCHG64(kaddr, old, new);
4433 kunmap_atomic(kaddr);
4434 kvm_release_page_dirty(page);
4437 return X86EMUL_CMPXCHG_FAILED;
4439 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
4440 kvm_mmu_pte_write(vcpu, gpa, new, bytes);
4442 return X86EMUL_CONTINUE;
4445 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
4447 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
4450 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
4452 /* TODO: String I/O for in kernel device */
4455 if (vcpu->arch.pio.in)
4456 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
4457 vcpu->arch.pio.size, pd);
4459 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
4460 vcpu->arch.pio.port, vcpu->arch.pio.size,
4465 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
4466 unsigned short port, void *val,
4467 unsigned int count, bool in)
4469 vcpu->arch.pio.port = port;
4470 vcpu->arch.pio.in = in;
4471 vcpu->arch.pio.count = count;
4472 vcpu->arch.pio.size = size;
4474 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4475 vcpu->arch.pio.count = 0;
4479 vcpu->run->exit_reason = KVM_EXIT_IO;
4480 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
4481 vcpu->run->io.size = size;
4482 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4483 vcpu->run->io.count = count;
4484 vcpu->run->io.port = port;
4489 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
4490 int size, unsigned short port, void *val,
4493 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4496 if (vcpu->arch.pio.count)
4499 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
4502 memcpy(val, vcpu->arch.pio_data, size * count);
4503 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
4504 vcpu->arch.pio.count = 0;
4511 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
4512 int size, unsigned short port,
4513 const void *val, unsigned int count)
4515 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4517 memcpy(vcpu->arch.pio_data, val, size * count);
4518 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
4519 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
4522 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
4524 return kvm_x86_ops->get_segment_base(vcpu, seg);
4527 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
4529 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
4532 int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
4534 if (!need_emulate_wbinvd(vcpu))
4535 return X86EMUL_CONTINUE;
4537 if (kvm_x86_ops->has_wbinvd_exit()) {
4538 int cpu = get_cpu();
4540 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4541 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
4542 wbinvd_ipi, NULL, 1);
4544 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
4547 return X86EMUL_CONTINUE;
4550 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
4552 kvm_x86_ops->skip_emulated_instruction(vcpu);
4553 return kvm_emulate_wbinvd_noskip(vcpu);
4555 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
4559 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
4561 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
4564 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
4565 unsigned long *dest)
4567 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
4570 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
4571 unsigned long value)
4574 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
4577 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
4579 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
4582 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
4584 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4585 unsigned long value;
4589 value = kvm_read_cr0(vcpu);
4592 value = vcpu->arch.cr2;
4595 value = kvm_read_cr3(vcpu);
4598 value = kvm_read_cr4(vcpu);
4601 value = kvm_get_cr8(vcpu);
4604 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4611 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
4613 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4618 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4621 vcpu->arch.cr2 = val;
4624 res = kvm_set_cr3(vcpu, val);
4627 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4630 res = kvm_set_cr8(vcpu, val);
4633 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4640 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
4642 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
4645 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4647 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
4650 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4652 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
4655 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4657 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4660 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4662 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4665 static unsigned long emulator_get_cached_segment_base(
4666 struct x86_emulate_ctxt *ctxt, int seg)
4668 return get_segment_base(emul_to_vcpu(ctxt), seg);
4671 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4672 struct desc_struct *desc, u32 *base3,
4675 struct kvm_segment var;
4677 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
4678 *selector = var.selector;
4681 memset(desc, 0, sizeof(*desc));
4687 set_desc_limit(desc, var.limit);
4688 set_desc_base(desc, (unsigned long)var.base);
4689 #ifdef CONFIG_X86_64
4691 *base3 = var.base >> 32;
4693 desc->type = var.type;
4695 desc->dpl = var.dpl;
4696 desc->p = var.present;
4697 desc->avl = var.avl;
4705 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
4706 struct desc_struct *desc, u32 base3,
4709 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4710 struct kvm_segment var;
4712 var.selector = selector;
4713 var.base = get_desc_base(desc);
4714 #ifdef CONFIG_X86_64
4715 var.base |= ((u64)base3) << 32;
4717 var.limit = get_desc_limit(desc);
4719 var.limit = (var.limit << 12) | 0xfff;
4720 var.type = desc->type;
4721 var.dpl = desc->dpl;
4726 var.avl = desc->avl;
4727 var.present = desc->p;
4728 var.unusable = !var.present;
4731 kvm_set_segment(vcpu, &var, seg);
4735 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
4736 u32 msr_index, u64 *pdata)
4738 struct msr_data msr;
4741 msr.index = msr_index;
4742 msr.host_initiated = false;
4743 r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
4751 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
4752 u32 msr_index, u64 data)
4754 struct msr_data msr;
4757 msr.index = msr_index;
4758 msr.host_initiated = false;
4759 return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
4762 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
4764 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4766 return vcpu->arch.smbase;
4769 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
4771 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4773 vcpu->arch.smbase = smbase;
4776 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
4779 return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
4782 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
4783 u32 pmc, u64 *pdata)
4785 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
4788 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
4790 emul_to_vcpu(ctxt)->arch.halt_request = 1;
4793 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
4796 kvm_load_guest_fpu(emul_to_vcpu(ctxt));
4798 * CR0.TS may reference the host fpu state, not the guest fpu state,
4799 * so it may be clear at this point.
4804 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
4809 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
4810 struct x86_instruction_info *info,
4811 enum x86_intercept_stage stage)
4813 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
4816 static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
4817 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
4819 kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
4822 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
4824 return kvm_register_read(emul_to_vcpu(ctxt), reg);
4827 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
4829 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
4832 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
4834 kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
4837 static const struct x86_emulate_ops emulate_ops = {
4838 .read_gpr = emulator_read_gpr,
4839 .write_gpr = emulator_write_gpr,
4840 .read_std = kvm_read_guest_virt_system,
4841 .write_std = kvm_write_guest_virt_system,
4842 .read_phys = kvm_read_guest_phys_system,
4843 .fetch = kvm_fetch_guest_virt,
4844 .read_emulated = emulator_read_emulated,
4845 .write_emulated = emulator_write_emulated,
4846 .cmpxchg_emulated = emulator_cmpxchg_emulated,
4847 .invlpg = emulator_invlpg,
4848 .pio_in_emulated = emulator_pio_in_emulated,
4849 .pio_out_emulated = emulator_pio_out_emulated,
4850 .get_segment = emulator_get_segment,
4851 .set_segment = emulator_set_segment,
4852 .get_cached_segment_base = emulator_get_cached_segment_base,
4853 .get_gdt = emulator_get_gdt,
4854 .get_idt = emulator_get_idt,
4855 .set_gdt = emulator_set_gdt,
4856 .set_idt = emulator_set_idt,
4857 .get_cr = emulator_get_cr,
4858 .set_cr = emulator_set_cr,
4859 .cpl = emulator_get_cpl,
4860 .get_dr = emulator_get_dr,
4861 .set_dr = emulator_set_dr,
4862 .get_smbase = emulator_get_smbase,
4863 .set_smbase = emulator_set_smbase,
4864 .set_msr = emulator_set_msr,
4865 .get_msr = emulator_get_msr,
4866 .check_pmc = emulator_check_pmc,
4867 .read_pmc = emulator_read_pmc,
4868 .halt = emulator_halt,
4869 .wbinvd = emulator_wbinvd,
4870 .fix_hypercall = emulator_fix_hypercall,
4871 .get_fpu = emulator_get_fpu,
4872 .put_fpu = emulator_put_fpu,
4873 .intercept = emulator_intercept,
4874 .get_cpuid = emulator_get_cpuid,
4875 .set_nmi_mask = emulator_set_nmi_mask,
4878 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
4880 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
4882 * an sti; sti; sequence only disable interrupts for the first
4883 * instruction. So, if the last instruction, be it emulated or
4884 * not, left the system with the INT_STI flag enabled, it
4885 * means that the last instruction is an sti. We should not
4886 * leave the flag on in this case. The same goes for mov ss
4888 if (int_shadow & mask)
4890 if (unlikely(int_shadow || mask)) {
4891 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
4893 kvm_make_request(KVM_REQ_EVENT, vcpu);
4897 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
4899 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4900 if (ctxt->exception.vector == PF_VECTOR)
4901 return kvm_propagate_fault(vcpu, &ctxt->exception);
4903 if (ctxt->exception.error_code_valid)
4904 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
4905 ctxt->exception.error_code);
4907 kvm_queue_exception(vcpu, ctxt->exception.vector);
4911 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
4913 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4916 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4918 ctxt->eflags = kvm_get_rflags(vcpu);
4919 ctxt->eip = kvm_rip_read(vcpu);
4920 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
4921 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
4922 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
4923 cs_db ? X86EMUL_MODE_PROT32 :
4924 X86EMUL_MODE_PROT16;
4925 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
4926 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
4927 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
4928 ctxt->emul_flags = vcpu->arch.hflags;
4930 init_decode_cache(ctxt);
4931 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
4934 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
4936 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4939 init_emulate_ctxt(vcpu);
4943 ctxt->_eip = ctxt->eip + inc_eip;
4944 ret = emulate_int_real(ctxt, irq);
4946 if (ret != X86EMUL_CONTINUE)
4947 return EMULATE_FAIL;
4949 ctxt->eip = ctxt->_eip;
4950 kvm_rip_write(vcpu, ctxt->eip);
4951 kvm_set_rflags(vcpu, ctxt->eflags);
4953 if (irq == NMI_VECTOR)
4954 vcpu->arch.nmi_pending = 0;
4956 vcpu->arch.interrupt.pending = false;
4958 return EMULATE_DONE;
4960 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
4962 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
4964 int r = EMULATE_DONE;
4966 ++vcpu->stat.insn_emulation_fail;
4967 trace_kvm_emulate_insn_failed(vcpu);
4968 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
4969 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4970 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
4971 vcpu->run->internal.ndata = 0;
4974 kvm_queue_exception(vcpu, UD_VECTOR);
4979 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
4980 bool write_fault_to_shadow_pgtable,
4986 if (emulation_type & EMULTYPE_NO_REEXECUTE)
4989 if (!vcpu->arch.mmu.direct_map) {
4991 * Write permission should be allowed since only
4992 * write access need to be emulated.
4994 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
4997 * If the mapping is invalid in guest, let cpu retry
4998 * it to generate fault.
5000 if (gpa == UNMAPPED_GVA)
5005 * Do not retry the unhandleable instruction if it faults on the
5006 * readonly host memory, otherwise it will goto a infinite loop:
5007 * retry instruction -> write #PF -> emulation fail -> retry
5008 * instruction -> ...
5010 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
5013 * If the instruction failed on the error pfn, it can not be fixed,
5014 * report the error to userspace.
5016 if (is_error_noslot_pfn(pfn))
5019 kvm_release_pfn_clean(pfn);
5021 /* The instructions are well-emulated on direct mmu. */
5022 if (vcpu->arch.mmu.direct_map) {
5023 unsigned int indirect_shadow_pages;
5025 spin_lock(&vcpu->kvm->mmu_lock);
5026 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
5027 spin_unlock(&vcpu->kvm->mmu_lock);
5029 if (indirect_shadow_pages)
5030 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5036 * if emulation was due to access to shadowed page table
5037 * and it failed try to unshadow page and re-enter the
5038 * guest to let CPU execute the instruction.
5040 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5043 * If the access faults on its page table, it can not
5044 * be fixed by unprotecting shadow page and it should
5045 * be reported to userspace.
5047 return !write_fault_to_shadow_pgtable;
5050 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5051 unsigned long cr2, int emulation_type)
5053 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5054 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
5056 last_retry_eip = vcpu->arch.last_retry_eip;
5057 last_retry_addr = vcpu->arch.last_retry_addr;
5060 * If the emulation is caused by #PF and it is non-page_table
5061 * writing instruction, it means the VM-EXIT is caused by shadow
5062 * page protected, we can zap the shadow page and retry this
5063 * instruction directly.
5065 * Note: if the guest uses a non-page-table modifying instruction
5066 * on the PDE that points to the instruction, then we will unmap
5067 * the instruction and go to an infinite loop. So, we cache the
5068 * last retried eip and the last fault address, if we meet the eip
5069 * and the address again, we can break out of the potential infinite
5072 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
5074 if (!(emulation_type & EMULTYPE_RETRY))
5077 if (x86_page_table_writing_insn(ctxt))
5080 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
5083 vcpu->arch.last_retry_eip = ctxt->eip;
5084 vcpu->arch.last_retry_addr = cr2;
5086 if (!vcpu->arch.mmu.direct_map)
5087 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5089 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5094 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
5095 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
5097 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
5099 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
5100 /* This is a good place to trace that we are exiting SMM. */
5101 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
5103 if (unlikely(vcpu->arch.smi_pending)) {
5104 kvm_make_request(KVM_REQ_SMI, vcpu);
5105 vcpu->arch.smi_pending = 0;
5107 /* Process a latched INIT, if any. */
5108 kvm_make_request(KVM_REQ_EVENT, vcpu);
5112 kvm_mmu_reset_context(vcpu);
5115 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
5117 unsigned changed = vcpu->arch.hflags ^ emul_flags;
5119 vcpu->arch.hflags = emul_flags;
5121 if (changed & HF_SMM_MASK)
5122 kvm_smm_changed(vcpu);
5125 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
5134 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
5135 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
5140 static void kvm_vcpu_check_singlestep(struct kvm_vcpu *vcpu, unsigned long rflags, int *r)
5142 struct kvm_run *kvm_run = vcpu->run;
5145 * rflags is the old, "raw" value of the flags. The new value has
5146 * not been saved yet.
5148 * This is correct even for TF set by the guest, because "the
5149 * processor will not generate this exception after the instruction
5150 * that sets the TF flag".
5152 if (unlikely(rflags & X86_EFLAGS_TF)) {
5153 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5154 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 |
5156 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
5157 kvm_run->debug.arch.exception = DB_VECTOR;
5158 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5159 *r = EMULATE_USER_EXIT;
5161 vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF;
5163 * "Certain debug exceptions may clear bit 0-3. The
5164 * remaining contents of the DR6 register are never
5165 * cleared by the processor".
5167 vcpu->arch.dr6 &= ~15;
5168 vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
5169 kvm_queue_exception(vcpu, DB_VECTOR);
5174 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
5176 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
5177 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
5178 struct kvm_run *kvm_run = vcpu->run;
5179 unsigned long eip = kvm_get_linear_rip(vcpu);
5180 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5181 vcpu->arch.guest_debug_dr7,
5185 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
5186 kvm_run->debug.arch.pc = eip;
5187 kvm_run->debug.arch.exception = DB_VECTOR;
5188 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5189 *r = EMULATE_USER_EXIT;
5194 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
5195 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
5196 unsigned long eip = kvm_get_linear_rip(vcpu);
5197 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5202 vcpu->arch.dr6 &= ~15;
5203 vcpu->arch.dr6 |= dr6 | DR6_RTM;
5204 kvm_queue_exception(vcpu, DB_VECTOR);
5213 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
5220 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5221 bool writeback = true;
5222 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
5225 * Clear write_fault_to_shadow_pgtable here to ensure it is
5228 vcpu->arch.write_fault_to_shadow_pgtable = false;
5229 kvm_clear_exception_queue(vcpu);
5231 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
5232 init_emulate_ctxt(vcpu);
5235 * We will reenter on the same instruction since
5236 * we do not set complete_userspace_io. This does not
5237 * handle watchpoints yet, those would be handled in
5240 if (kvm_vcpu_check_breakpoint(vcpu, &r))
5243 ctxt->interruptibility = 0;
5244 ctxt->have_exception = false;
5245 ctxt->exception.vector = -1;
5246 ctxt->perm_ok = false;
5248 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
5250 r = x86_decode_insn(ctxt, insn, insn_len);
5252 trace_kvm_emulate_insn_start(vcpu);
5253 ++vcpu->stat.insn_emulation;
5254 if (r != EMULATION_OK) {
5255 if (emulation_type & EMULTYPE_TRAP_UD)
5256 return EMULATE_FAIL;
5257 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5259 return EMULATE_DONE;
5260 if (emulation_type & EMULTYPE_SKIP)
5261 return EMULATE_FAIL;
5262 return handle_emulation_failure(vcpu);
5266 if (emulation_type & EMULTYPE_SKIP) {
5267 kvm_rip_write(vcpu, ctxt->_eip);
5268 if (ctxt->eflags & X86_EFLAGS_RF)
5269 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
5270 return EMULATE_DONE;
5273 if (retry_instruction(ctxt, cr2, emulation_type))
5274 return EMULATE_DONE;
5276 /* this is needed for vmware backdoor interface to work since it
5277 changes registers values during IO operation */
5278 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
5279 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5280 emulator_invalidate_register_cache(ctxt);
5284 r = x86_emulate_insn(ctxt);
5286 if (r == EMULATION_INTERCEPTED)
5287 return EMULATE_DONE;
5289 if (r == EMULATION_FAILED) {
5290 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5292 return EMULATE_DONE;
5294 return handle_emulation_failure(vcpu);
5297 if (ctxt->have_exception) {
5299 if (inject_emulated_exception(vcpu))
5301 } else if (vcpu->arch.pio.count) {
5302 if (!vcpu->arch.pio.in) {
5303 /* FIXME: return into emulator if single-stepping. */
5304 vcpu->arch.pio.count = 0;
5307 vcpu->arch.complete_userspace_io = complete_emulated_pio;
5309 r = EMULATE_USER_EXIT;
5310 } else if (vcpu->mmio_needed) {
5311 if (!vcpu->mmio_is_write)
5313 r = EMULATE_USER_EXIT;
5314 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
5315 } else if (r == EMULATION_RESTART)
5321 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5322 toggle_interruptibility(vcpu, ctxt->interruptibility);
5323 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5324 if (vcpu->arch.hflags != ctxt->emul_flags)
5325 kvm_set_hflags(vcpu, ctxt->emul_flags);
5326 kvm_rip_write(vcpu, ctxt->eip);
5327 if (r == EMULATE_DONE)
5328 kvm_vcpu_check_singlestep(vcpu, rflags, &r);
5329 if (!ctxt->have_exception ||
5330 exception_type(ctxt->exception.vector) == EXCPT_TRAP)
5331 __kvm_set_rflags(vcpu, ctxt->eflags);
5334 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
5335 * do nothing, and it will be requested again as soon as
5336 * the shadow expires. But we still need to check here,
5337 * because POPF has no interrupt shadow.
5339 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
5340 kvm_make_request(KVM_REQ_EVENT, vcpu);
5342 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5346 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5348 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5350 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5351 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5352 size, port, &val, 1);
5353 /* do not return to emulator after return from userspace */
5354 vcpu->arch.pio.count = 0;
5357 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5359 static void tsc_bad(void *info)
5361 __this_cpu_write(cpu_tsc_khz, 0);
5364 static void tsc_khz_changed(void *data)
5366 struct cpufreq_freqs *freq = data;
5367 unsigned long khz = 0;
5371 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5372 khz = cpufreq_quick_get(raw_smp_processor_id());
5375 __this_cpu_write(cpu_tsc_khz, khz);
5378 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5381 struct cpufreq_freqs *freq = data;
5383 struct kvm_vcpu *vcpu;
5384 int i, send_ipi = 0;
5387 * We allow guests to temporarily run on slowing clocks,
5388 * provided we notify them after, or to run on accelerating
5389 * clocks, provided we notify them before. Thus time never
5392 * However, we have a problem. We can't atomically update
5393 * the frequency of a given CPU from this function; it is
5394 * merely a notifier, which can be called from any CPU.
5395 * Changing the TSC frequency at arbitrary points in time
5396 * requires a recomputation of local variables related to
5397 * the TSC for each VCPU. We must flag these local variables
5398 * to be updated and be sure the update takes place with the
5399 * new frequency before any guests proceed.
5401 * Unfortunately, the combination of hotplug CPU and frequency
5402 * change creates an intractable locking scenario; the order
5403 * of when these callouts happen is undefined with respect to
5404 * CPU hotplug, and they can race with each other. As such,
5405 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5406 * undefined; you can actually have a CPU frequency change take
5407 * place in between the computation of X and the setting of the
5408 * variable. To protect against this problem, all updates of
5409 * the per_cpu tsc_khz variable are done in an interrupt
5410 * protected IPI, and all callers wishing to update the value
5411 * must wait for a synchronous IPI to complete (which is trivial
5412 * if the caller is on the CPU already). This establishes the
5413 * necessary total order on variable updates.
5415 * Note that because a guest time update may take place
5416 * anytime after the setting of the VCPU's request bit, the
5417 * correct TSC value must be set before the request. However,
5418 * to ensure the update actually makes it to any guest which
5419 * starts running in hardware virtualization between the set
5420 * and the acquisition of the spinlock, we must also ping the
5421 * CPU after setting the request bit.
5425 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
5427 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
5430 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5432 spin_lock(&kvm_lock);
5433 list_for_each_entry(kvm, &vm_list, vm_list) {
5434 kvm_for_each_vcpu(i, vcpu, kvm) {
5435 if (vcpu->cpu != freq->cpu)
5437 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5438 if (vcpu->cpu != smp_processor_id())
5442 spin_unlock(&kvm_lock);
5444 if (freq->old < freq->new && send_ipi) {
5446 * We upscale the frequency. Must make the guest
5447 * doesn't see old kvmclock values while running with
5448 * the new frequency, otherwise we risk the guest sees
5449 * time go backwards.
5451 * In case we update the frequency for another cpu
5452 * (which might be in guest context) send an interrupt
5453 * to kick the cpu out of guest context. Next time
5454 * guest context is entered kvmclock will be updated,
5455 * so the guest will not see stale values.
5457 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5462 static struct notifier_block kvmclock_cpufreq_notifier_block = {
5463 .notifier_call = kvmclock_cpufreq_notifier
5466 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
5467 unsigned long action, void *hcpu)
5469 unsigned int cpu = (unsigned long)hcpu;
5473 case CPU_DOWN_FAILED:
5474 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5476 case CPU_DOWN_PREPARE:
5477 smp_call_function_single(cpu, tsc_bad, NULL, 1);
5483 static struct notifier_block kvmclock_cpu_notifier_block = {
5484 .notifier_call = kvmclock_cpu_notifier,
5485 .priority = -INT_MAX
5488 static void kvm_timer_init(void)
5492 max_tsc_khz = tsc_khz;
5494 cpu_notifier_register_begin();
5495 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5496 #ifdef CONFIG_CPU_FREQ
5497 struct cpufreq_policy policy;
5498 memset(&policy, 0, sizeof(policy));
5500 cpufreq_get_policy(&policy, cpu);
5501 if (policy.cpuinfo.max_freq)
5502 max_tsc_khz = policy.cpuinfo.max_freq;
5505 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
5506 CPUFREQ_TRANSITION_NOTIFIER);
5508 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
5509 for_each_online_cpu(cpu)
5510 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5512 __register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5513 cpu_notifier_register_done();
5517 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
5519 int kvm_is_in_guest(void)
5521 return __this_cpu_read(current_vcpu) != NULL;
5524 static int kvm_is_user_mode(void)
5528 if (__this_cpu_read(current_vcpu))
5529 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
5531 return user_mode != 0;
5534 static unsigned long kvm_get_guest_ip(void)
5536 unsigned long ip = 0;
5538 if (__this_cpu_read(current_vcpu))
5539 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
5544 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5545 .is_in_guest = kvm_is_in_guest,
5546 .is_user_mode = kvm_is_user_mode,
5547 .get_guest_ip = kvm_get_guest_ip,
5550 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
5552 __this_cpu_write(current_vcpu, vcpu);
5554 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
5556 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
5558 __this_cpu_write(current_vcpu, NULL);
5560 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
5562 static void kvm_set_mmio_spte_mask(void)
5565 int maxphyaddr = boot_cpu_data.x86_phys_bits;
5568 * Set the reserved bits and the present bit of an paging-structure
5569 * entry to generate page fault with PFER.RSV = 1.
5571 /* Mask the reserved physical address bits. */
5572 mask = rsvd_bits(maxphyaddr, 51);
5574 /* Bit 62 is always reserved for 32bit host. */
5575 mask |= 0x3ull << 62;
5577 /* Set the present bit. */
5580 #ifdef CONFIG_X86_64
5582 * If reserved bit is not supported, clear the present bit to disable
5585 if (maxphyaddr == 52)
5589 kvm_mmu_set_mmio_spte_mask(mask);
5592 #ifdef CONFIG_X86_64
5593 static void pvclock_gtod_update_fn(struct work_struct *work)
5597 struct kvm_vcpu *vcpu;
5600 spin_lock(&kvm_lock);
5601 list_for_each_entry(kvm, &vm_list, vm_list)
5602 kvm_for_each_vcpu(i, vcpu, kvm)
5603 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
5604 atomic_set(&kvm_guest_has_master_clock, 0);
5605 spin_unlock(&kvm_lock);
5608 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
5611 * Notification about pvclock gtod data update.
5613 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
5616 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
5617 struct timekeeper *tk = priv;
5619 update_pvclock_gtod(tk);
5621 /* disable master clock if host does not trust, or does not
5622 * use, TSC clocksource
5624 if (gtod->clock.vclock_mode != VCLOCK_TSC &&
5625 atomic_read(&kvm_guest_has_master_clock) != 0)
5626 queue_work(system_long_wq, &pvclock_gtod_work);
5631 static struct notifier_block pvclock_gtod_notifier = {
5632 .notifier_call = pvclock_gtod_notify,
5636 int kvm_arch_init(void *opaque)
5639 struct kvm_x86_ops *ops = opaque;
5642 printk(KERN_ERR "kvm: already loaded the other module\n");
5647 if (!ops->cpu_has_kvm_support()) {
5648 printk(KERN_ERR "kvm: no hardware support\n");
5652 if (ops->disabled_by_bios()) {
5653 printk(KERN_ERR "kvm: disabled by bios\n");
5659 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
5661 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
5665 r = kvm_mmu_module_init();
5667 goto out_free_percpu;
5669 kvm_set_mmio_spte_mask();
5673 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
5674 PT_DIRTY_MASK, PT64_NX_MASK, 0);
5678 perf_register_guest_info_callbacks(&kvm_guest_cbs);
5681 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
5684 #ifdef CONFIG_X86_64
5685 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
5691 free_percpu(shared_msrs);
5696 void kvm_arch_exit(void)
5698 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
5700 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5701 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
5702 CPUFREQ_TRANSITION_NOTIFIER);
5703 unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5704 #ifdef CONFIG_X86_64
5705 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
5708 kvm_mmu_module_exit();
5709 free_percpu(shared_msrs);
5712 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
5714 ++vcpu->stat.halt_exits;
5715 if (lapic_in_kernel(vcpu)) {
5716 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
5719 vcpu->run->exit_reason = KVM_EXIT_HLT;
5723 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
5725 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
5727 kvm_x86_ops->skip_emulated_instruction(vcpu);
5728 return kvm_vcpu_halt(vcpu);
5730 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
5733 * kvm_pv_kick_cpu_op: Kick a vcpu.
5735 * @apicid - apicid of vcpu to be kicked.
5737 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
5739 struct kvm_lapic_irq lapic_irq;
5741 lapic_irq.shorthand = 0;
5742 lapic_irq.dest_mode = 0;
5743 lapic_irq.dest_id = apicid;
5744 lapic_irq.msi_redir_hint = false;
5746 lapic_irq.delivery_mode = APIC_DM_REMRD;
5747 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
5750 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
5752 unsigned long nr, a0, a1, a2, a3, ret;
5753 int op_64_bit, r = 1;
5755 kvm_x86_ops->skip_emulated_instruction(vcpu);
5757 if (kvm_hv_hypercall_enabled(vcpu->kvm))
5758 return kvm_hv_hypercall(vcpu);
5760 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
5761 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
5762 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
5763 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
5764 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
5766 trace_kvm_hypercall(nr, a0, a1, a2, a3);
5768 op_64_bit = is_64_bit_mode(vcpu);
5777 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
5783 case KVM_HC_VAPIC_POLL_IRQ:
5786 case KVM_HC_KICK_CPU:
5787 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
5797 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
5798 ++vcpu->stat.hypercalls;
5801 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
5803 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
5805 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5806 char instruction[3];
5807 unsigned long rip = kvm_rip_read(vcpu);
5809 kvm_x86_ops->patch_hypercall(vcpu, instruction);
5811 return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
5815 * Check if userspace requested an interrupt window, and that the
5816 * interrupt window is open.
5818 * No need to exit to userspace if we already have an interrupt queued.
5820 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
5822 if (!vcpu->run->request_interrupt_window || pic_in_kernel(vcpu->kvm))
5825 if (kvm_cpu_has_interrupt(vcpu))
5828 return (irqchip_split(vcpu->kvm)
5829 ? kvm_apic_accept_pic_intr(vcpu)
5830 : kvm_arch_interrupt_allowed(vcpu));
5833 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
5835 struct kvm_run *kvm_run = vcpu->run;
5837 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
5838 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
5839 kvm_run->cr8 = kvm_get_cr8(vcpu);
5840 kvm_run->apic_base = kvm_get_apic_base(vcpu);
5841 if (!irqchip_in_kernel(vcpu->kvm))
5842 kvm_run->ready_for_interrupt_injection =
5843 kvm_arch_interrupt_allowed(vcpu) &&
5844 !kvm_cpu_has_interrupt(vcpu) &&
5845 !kvm_event_needs_reinjection(vcpu);
5846 else if (!pic_in_kernel(vcpu->kvm))
5847 kvm_run->ready_for_interrupt_injection =
5848 kvm_apic_accept_pic_intr(vcpu) &&
5849 !kvm_cpu_has_interrupt(vcpu);
5851 kvm_run->ready_for_interrupt_injection = 1;
5854 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
5858 if (!kvm_x86_ops->update_cr8_intercept)
5861 if (!vcpu->arch.apic)
5864 if (!vcpu->arch.apic->vapic_addr)
5865 max_irr = kvm_lapic_find_highest_irr(vcpu);
5872 tpr = kvm_lapic_get_cr8(vcpu);
5874 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
5877 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
5881 /* try to reinject previous events if any */
5882 if (vcpu->arch.exception.pending) {
5883 trace_kvm_inj_exception(vcpu->arch.exception.nr,
5884 vcpu->arch.exception.has_error_code,
5885 vcpu->arch.exception.error_code);
5887 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
5888 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
5891 if (vcpu->arch.exception.nr == DB_VECTOR &&
5892 (vcpu->arch.dr7 & DR7_GD)) {
5893 vcpu->arch.dr7 &= ~DR7_GD;
5894 kvm_update_dr7(vcpu);
5897 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
5898 vcpu->arch.exception.has_error_code,
5899 vcpu->arch.exception.error_code,
5900 vcpu->arch.exception.reinject);
5904 if (vcpu->arch.nmi_injected) {
5905 kvm_x86_ops->set_nmi(vcpu);
5909 if (vcpu->arch.interrupt.pending) {
5910 kvm_x86_ops->set_irq(vcpu);
5914 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
5915 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
5920 /* try to inject new event if pending */
5921 if (vcpu->arch.nmi_pending) {
5922 if (kvm_x86_ops->nmi_allowed(vcpu)) {
5923 --vcpu->arch.nmi_pending;
5924 vcpu->arch.nmi_injected = true;
5925 kvm_x86_ops->set_nmi(vcpu);
5927 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
5929 * Because interrupts can be injected asynchronously, we are
5930 * calling check_nested_events again here to avoid a race condition.
5931 * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
5932 * proposal and current concerns. Perhaps we should be setting
5933 * KVM_REQ_EVENT only on certain events and not unconditionally?
5935 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
5936 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
5940 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
5941 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
5943 kvm_x86_ops->set_irq(vcpu);
5949 static void process_nmi(struct kvm_vcpu *vcpu)
5954 * x86 is limited to one NMI running, and one NMI pending after it.
5955 * If an NMI is already in progress, limit further NMIs to just one.
5956 * Otherwise, allow two (and we'll inject the first one immediately).
5958 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
5961 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
5962 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
5963 kvm_make_request(KVM_REQ_EVENT, vcpu);
5966 #define put_smstate(type, buf, offset, val) \
5967 *(type *)((buf) + (offset) - 0x7e00) = val
5969 static u32 process_smi_get_segment_flags(struct kvm_segment *seg)
5972 flags |= seg->g << 23;
5973 flags |= seg->db << 22;
5974 flags |= seg->l << 21;
5975 flags |= seg->avl << 20;
5976 flags |= seg->present << 15;
5977 flags |= seg->dpl << 13;
5978 flags |= seg->s << 12;
5979 flags |= seg->type << 8;
5983 static void process_smi_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
5985 struct kvm_segment seg;
5988 kvm_get_segment(vcpu, &seg, n);
5989 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
5992 offset = 0x7f84 + n * 12;
5994 offset = 0x7f2c + (n - 3) * 12;
5996 put_smstate(u32, buf, offset + 8, seg.base);
5997 put_smstate(u32, buf, offset + 4, seg.limit);
5998 put_smstate(u32, buf, offset, process_smi_get_segment_flags(&seg));
6001 #ifdef CONFIG_X86_64
6002 static void process_smi_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
6004 struct kvm_segment seg;
6008 kvm_get_segment(vcpu, &seg, n);
6009 offset = 0x7e00 + n * 16;
6011 flags = process_smi_get_segment_flags(&seg) >> 8;
6012 put_smstate(u16, buf, offset, seg.selector);
6013 put_smstate(u16, buf, offset + 2, flags);
6014 put_smstate(u32, buf, offset + 4, seg.limit);
6015 put_smstate(u64, buf, offset + 8, seg.base);
6019 static void process_smi_save_state_32(struct kvm_vcpu *vcpu, char *buf)
6022 struct kvm_segment seg;
6026 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
6027 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
6028 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
6029 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
6031 for (i = 0; i < 8; i++)
6032 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
6034 kvm_get_dr(vcpu, 6, &val);
6035 put_smstate(u32, buf, 0x7fcc, (u32)val);
6036 kvm_get_dr(vcpu, 7, &val);
6037 put_smstate(u32, buf, 0x7fc8, (u32)val);
6039 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6040 put_smstate(u32, buf, 0x7fc4, seg.selector);
6041 put_smstate(u32, buf, 0x7f64, seg.base);
6042 put_smstate(u32, buf, 0x7f60, seg.limit);
6043 put_smstate(u32, buf, 0x7f5c, process_smi_get_segment_flags(&seg));
6045 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6046 put_smstate(u32, buf, 0x7fc0, seg.selector);
6047 put_smstate(u32, buf, 0x7f80, seg.base);
6048 put_smstate(u32, buf, 0x7f7c, seg.limit);
6049 put_smstate(u32, buf, 0x7f78, process_smi_get_segment_flags(&seg));
6051 kvm_x86_ops->get_gdt(vcpu, &dt);
6052 put_smstate(u32, buf, 0x7f74, dt.address);
6053 put_smstate(u32, buf, 0x7f70, dt.size);
6055 kvm_x86_ops->get_idt(vcpu, &dt);
6056 put_smstate(u32, buf, 0x7f58, dt.address);
6057 put_smstate(u32, buf, 0x7f54, dt.size);
6059 for (i = 0; i < 6; i++)
6060 process_smi_save_seg_32(vcpu, buf, i);
6062 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
6065 put_smstate(u32, buf, 0x7efc, 0x00020000);
6066 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
6069 static void process_smi_save_state_64(struct kvm_vcpu *vcpu, char *buf)
6071 #ifdef CONFIG_X86_64
6073 struct kvm_segment seg;
6077 for (i = 0; i < 16; i++)
6078 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
6080 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
6081 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
6083 kvm_get_dr(vcpu, 6, &val);
6084 put_smstate(u64, buf, 0x7f68, val);
6085 kvm_get_dr(vcpu, 7, &val);
6086 put_smstate(u64, buf, 0x7f60, val);
6088 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
6089 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
6090 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
6092 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
6095 put_smstate(u32, buf, 0x7efc, 0x00020064);
6097 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
6099 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6100 put_smstate(u16, buf, 0x7e90, seg.selector);
6101 put_smstate(u16, buf, 0x7e92, process_smi_get_segment_flags(&seg) >> 8);
6102 put_smstate(u32, buf, 0x7e94, seg.limit);
6103 put_smstate(u64, buf, 0x7e98, seg.base);
6105 kvm_x86_ops->get_idt(vcpu, &dt);
6106 put_smstate(u32, buf, 0x7e84, dt.size);
6107 put_smstate(u64, buf, 0x7e88, dt.address);
6109 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6110 put_smstate(u16, buf, 0x7e70, seg.selector);
6111 put_smstate(u16, buf, 0x7e72, process_smi_get_segment_flags(&seg) >> 8);
6112 put_smstate(u32, buf, 0x7e74, seg.limit);
6113 put_smstate(u64, buf, 0x7e78, seg.base);
6115 kvm_x86_ops->get_gdt(vcpu, &dt);
6116 put_smstate(u32, buf, 0x7e64, dt.size);
6117 put_smstate(u64, buf, 0x7e68, dt.address);
6119 for (i = 0; i < 6; i++)
6120 process_smi_save_seg_64(vcpu, buf, i);
6126 static void process_smi(struct kvm_vcpu *vcpu)
6128 struct kvm_segment cs, ds;
6134 vcpu->arch.smi_pending = true;
6138 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
6139 vcpu->arch.hflags |= HF_SMM_MASK;
6140 memset(buf, 0, 512);
6141 if (guest_cpuid_has_longmode(vcpu))
6142 process_smi_save_state_64(vcpu, buf);
6144 process_smi_save_state_32(vcpu, buf);
6146 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
6148 if (kvm_x86_ops->get_nmi_mask(vcpu))
6149 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
6151 kvm_x86_ops->set_nmi_mask(vcpu, true);
6153 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6154 kvm_rip_write(vcpu, 0x8000);
6156 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
6157 kvm_x86_ops->set_cr0(vcpu, cr0);
6158 vcpu->arch.cr0 = cr0;
6160 kvm_x86_ops->set_cr4(vcpu, 0);
6162 /* Undocumented: IDT limit is set to zero on entry to SMM. */
6163 dt.address = dt.size = 0;
6164 kvm_x86_ops->set_idt(vcpu, &dt);
6166 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
6168 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
6169 cs.base = vcpu->arch.smbase;
6174 cs.limit = ds.limit = 0xffffffff;
6175 cs.type = ds.type = 0x3;
6176 cs.dpl = ds.dpl = 0;
6181 cs.avl = ds.avl = 0;
6182 cs.present = ds.present = 1;
6183 cs.unusable = ds.unusable = 0;
6184 cs.padding = ds.padding = 0;
6186 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
6187 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
6188 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
6189 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
6190 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
6191 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
6193 if (guest_cpuid_has_longmode(vcpu))
6194 kvm_x86_ops->set_efer(vcpu, 0);
6196 kvm_update_cpuid(vcpu);
6197 kvm_mmu_reset_context(vcpu);
6200 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
6202 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
6205 memset(vcpu->arch.eoi_exit_bitmap, 0, 256 / 8);
6207 if (irqchip_split(vcpu->kvm))
6208 kvm_scan_ioapic_routes(vcpu, vcpu->arch.eoi_exit_bitmap);
6210 kvm_x86_ops->sync_pir_to_irr(vcpu);
6211 kvm_ioapic_scan_entry(vcpu, vcpu->arch.eoi_exit_bitmap);
6213 kvm_x86_ops->load_eoi_exitmap(vcpu);
6216 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu)
6218 ++vcpu->stat.tlb_flush;
6219 kvm_x86_ops->tlb_flush(vcpu);
6222 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
6224 struct page *page = NULL;
6226 if (!lapic_in_kernel(vcpu))
6229 if (!kvm_x86_ops->set_apic_access_page_addr)
6232 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6233 if (is_error_page(page))
6235 kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
6238 * Do not pin apic access page in memory, the MMU notifier
6239 * will call us again if it is migrated or swapped out.
6243 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
6245 void kvm_arch_mmu_notifier_invalidate_page(struct kvm *kvm,
6246 unsigned long address)
6249 * The physical address of apic access page is stored in the VMCS.
6250 * Update it when it becomes invalid.
6252 if (address == gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT))
6253 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
6257 * Returns 1 to let vcpu_run() continue the guest execution loop without
6258 * exiting to the userspace. Otherwise, the value will be returned to the
6261 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
6264 bool req_int_win = !lapic_in_kernel(vcpu) &&
6265 vcpu->run->request_interrupt_window;
6266 bool req_immediate_exit = false;
6268 if (vcpu->requests) {
6269 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
6270 kvm_mmu_unload(vcpu);
6271 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
6272 __kvm_migrate_timers(vcpu);
6273 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
6274 kvm_gen_update_masterclock(vcpu->kvm);
6275 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
6276 kvm_gen_kvmclock_update(vcpu);
6277 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
6278 r = kvm_guest_time_update(vcpu);
6282 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
6283 kvm_mmu_sync_roots(vcpu);
6284 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
6285 kvm_vcpu_flush_tlb(vcpu);
6286 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
6287 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
6291 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
6292 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6296 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
6297 vcpu->fpu_active = 0;
6298 kvm_x86_ops->fpu_deactivate(vcpu);
6300 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
6301 /* Page is swapped out. Do synthetic halt */
6302 vcpu->arch.apf.halted = true;
6306 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
6307 record_steal_time(vcpu);
6308 if (kvm_check_request(KVM_REQ_SMI, vcpu))
6310 if (kvm_check_request(KVM_REQ_NMI, vcpu))
6312 if (kvm_check_request(KVM_REQ_PMU, vcpu))
6313 kvm_pmu_handle_event(vcpu);
6314 if (kvm_check_request(KVM_REQ_PMI, vcpu))
6315 kvm_pmu_deliver_pmi(vcpu);
6316 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
6317 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
6318 if (test_bit(vcpu->arch.pending_ioapic_eoi,
6319 (void *) vcpu->arch.eoi_exit_bitmap)) {
6320 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
6321 vcpu->run->eoi.vector =
6322 vcpu->arch.pending_ioapic_eoi;
6327 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
6328 vcpu_scan_ioapic(vcpu);
6329 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
6330 kvm_vcpu_reload_apic_access_page(vcpu);
6331 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
6332 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6333 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
6337 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
6338 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6339 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
6346 * KVM_REQ_EVENT is not set when posted interrupts are set by
6347 * VT-d hardware, so we have to update RVI unconditionally.
6349 if (kvm_lapic_enabled(vcpu)) {
6351 * Update architecture specific hints for APIC
6352 * virtual interrupt delivery.
6354 if (kvm_x86_ops->hwapic_irr_update)
6355 kvm_x86_ops->hwapic_irr_update(vcpu,
6356 kvm_lapic_find_highest_irr(vcpu));
6359 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
6360 kvm_apic_accept_events(vcpu);
6361 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
6366 if (inject_pending_event(vcpu, req_int_win) != 0)
6367 req_immediate_exit = true;
6368 /* enable NMI/IRQ window open exits if needed */
6369 else if (vcpu->arch.nmi_pending)
6370 kvm_x86_ops->enable_nmi_window(vcpu);
6371 else if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
6372 kvm_x86_ops->enable_irq_window(vcpu);
6374 if (kvm_lapic_enabled(vcpu)) {
6375 update_cr8_intercept(vcpu);
6376 kvm_lapic_sync_to_vapic(vcpu);
6380 r = kvm_mmu_reload(vcpu);
6382 goto cancel_injection;
6387 kvm_x86_ops->prepare_guest_switch(vcpu);
6388 if (vcpu->fpu_active)
6389 kvm_load_guest_fpu(vcpu);
6390 kvm_load_guest_xcr0(vcpu);
6392 vcpu->mode = IN_GUEST_MODE;
6394 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6396 /* We should set ->mode before check ->requests,
6397 * see the comment in make_all_cpus_request.
6399 smp_mb__after_srcu_read_unlock();
6401 local_irq_disable();
6403 if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
6404 || need_resched() || signal_pending(current)) {
6405 vcpu->mode = OUTSIDE_GUEST_MODE;
6409 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6411 goto cancel_injection;
6414 if (req_immediate_exit)
6415 smp_send_reschedule(vcpu->cpu);
6417 __kvm_guest_enter();
6419 if (unlikely(vcpu->arch.switch_db_regs)) {
6421 set_debugreg(vcpu->arch.eff_db[0], 0);
6422 set_debugreg(vcpu->arch.eff_db[1], 1);
6423 set_debugreg(vcpu->arch.eff_db[2], 2);
6424 set_debugreg(vcpu->arch.eff_db[3], 3);
6425 set_debugreg(vcpu->arch.dr6, 6);
6426 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6429 trace_kvm_entry(vcpu->vcpu_id);
6430 wait_lapic_expire(vcpu);
6431 kvm_x86_ops->run(vcpu);
6434 * Do this here before restoring debug registers on the host. And
6435 * since we do this before handling the vmexit, a DR access vmexit
6436 * can (a) read the correct value of the debug registers, (b) set
6437 * KVM_DEBUGREG_WONT_EXIT again.
6439 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
6442 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
6443 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
6444 for (i = 0; i < KVM_NR_DB_REGS; i++)
6445 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
6449 * If the guest has used debug registers, at least dr7
6450 * will be disabled while returning to the host.
6451 * If we don't have active breakpoints in the host, we don't
6452 * care about the messed up debug address registers. But if
6453 * we have some of them active, restore the old state.
6455 if (hw_breakpoint_active())
6456 hw_breakpoint_restore();
6458 vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu,
6461 vcpu->mode = OUTSIDE_GUEST_MODE;
6464 /* Interrupt is enabled by handle_external_intr() */
6465 kvm_x86_ops->handle_external_intr(vcpu);
6470 * We must have an instruction between local_irq_enable() and
6471 * kvm_guest_exit(), so the timer interrupt isn't delayed by
6472 * the interrupt shadow. The stat.exits increment will do nicely.
6473 * But we need to prevent reordering, hence this barrier():
6481 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6484 * Profile KVM exit RIPs:
6486 if (unlikely(prof_on == KVM_PROFILING)) {
6487 unsigned long rip = kvm_rip_read(vcpu);
6488 profile_hit(KVM_PROFILING, (void *)rip);
6491 if (unlikely(vcpu->arch.tsc_always_catchup))
6492 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6494 if (vcpu->arch.apic_attention)
6495 kvm_lapic_sync_from_vapic(vcpu);
6497 r = kvm_x86_ops->handle_exit(vcpu);
6501 kvm_x86_ops->cancel_injection(vcpu);
6502 if (unlikely(vcpu->arch.apic_attention))
6503 kvm_lapic_sync_from_vapic(vcpu);
6508 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
6510 if (!kvm_arch_vcpu_runnable(vcpu) &&
6511 (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
6512 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6513 kvm_vcpu_block(vcpu);
6514 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6516 if (kvm_x86_ops->post_block)
6517 kvm_x86_ops->post_block(vcpu);
6519 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
6523 kvm_apic_accept_events(vcpu);
6524 switch(vcpu->arch.mp_state) {
6525 case KVM_MP_STATE_HALTED:
6526 vcpu->arch.pv.pv_unhalted = false;
6527 vcpu->arch.mp_state =
6528 KVM_MP_STATE_RUNNABLE;
6529 case KVM_MP_STATE_RUNNABLE:
6530 vcpu->arch.apf.halted = false;
6532 case KVM_MP_STATE_INIT_RECEIVED:
6541 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
6543 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6544 !vcpu->arch.apf.halted);
6547 static int vcpu_run(struct kvm_vcpu *vcpu)
6550 struct kvm *kvm = vcpu->kvm;
6552 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6555 if (kvm_vcpu_running(vcpu)) {
6556 r = vcpu_enter_guest(vcpu);
6558 r = vcpu_block(kvm, vcpu);
6564 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
6565 if (kvm_cpu_has_pending_timer(vcpu))
6566 kvm_inject_pending_timer_irqs(vcpu);
6568 if (dm_request_for_irq_injection(vcpu)) {
6570 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
6571 ++vcpu->stat.request_irq_exits;
6575 kvm_check_async_pf_completion(vcpu);
6577 if (signal_pending(current)) {
6579 vcpu->run->exit_reason = KVM_EXIT_INTR;
6580 ++vcpu->stat.signal_exits;
6583 if (need_resched()) {
6584 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6586 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6590 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6595 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
6598 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6599 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
6600 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6601 if (r != EMULATE_DONE)
6606 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
6608 BUG_ON(!vcpu->arch.pio.count);
6610 return complete_emulated_io(vcpu);
6614 * Implements the following, as a state machine:
6618 * for each mmio piece in the fragment
6626 * for each mmio piece in the fragment
6631 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
6633 struct kvm_run *run = vcpu->run;
6634 struct kvm_mmio_fragment *frag;
6637 BUG_ON(!vcpu->mmio_needed);
6639 /* Complete previous fragment */
6640 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
6641 len = min(8u, frag->len);
6642 if (!vcpu->mmio_is_write)
6643 memcpy(frag->data, run->mmio.data, len);
6645 if (frag->len <= 8) {
6646 /* Switch to the next fragment. */
6648 vcpu->mmio_cur_fragment++;
6650 /* Go forward to the next mmio piece. */
6656 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
6657 vcpu->mmio_needed = 0;
6659 /* FIXME: return into emulator if single-stepping. */
6660 if (vcpu->mmio_is_write)
6662 vcpu->mmio_read_completed = 1;
6663 return complete_emulated_io(vcpu);
6666 run->exit_reason = KVM_EXIT_MMIO;
6667 run->mmio.phys_addr = frag->gpa;
6668 if (vcpu->mmio_is_write)
6669 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
6670 run->mmio.len = min(8u, frag->len);
6671 run->mmio.is_write = vcpu->mmio_is_write;
6672 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6677 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
6679 struct fpu *fpu = ¤t->thread.fpu;
6683 fpu__activate_curr(fpu);
6685 if (vcpu->sigset_active)
6686 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
6688 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
6689 kvm_vcpu_block(vcpu);
6690 kvm_apic_accept_events(vcpu);
6691 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
6696 /* re-sync apic's tpr */
6697 if (!lapic_in_kernel(vcpu)) {
6698 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
6704 if (unlikely(vcpu->arch.complete_userspace_io)) {
6705 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
6706 vcpu->arch.complete_userspace_io = NULL;
6711 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
6716 post_kvm_run_save(vcpu);
6717 if (vcpu->sigset_active)
6718 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
6723 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6725 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
6727 * We are here if userspace calls get_regs() in the middle of
6728 * instruction emulation. Registers state needs to be copied
6729 * back from emulation context to vcpu. Userspace shouldn't do
6730 * that usually, but some bad designed PV devices (vmware
6731 * backdoor interface) need this to work
6733 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
6734 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6736 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
6737 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
6738 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
6739 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
6740 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
6741 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
6742 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
6743 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
6744 #ifdef CONFIG_X86_64
6745 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
6746 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
6747 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
6748 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
6749 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
6750 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
6751 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
6752 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
6755 regs->rip = kvm_rip_read(vcpu);
6756 regs->rflags = kvm_get_rflags(vcpu);
6761 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6763 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
6764 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6766 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
6767 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
6768 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
6769 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
6770 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
6771 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
6772 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
6773 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
6774 #ifdef CONFIG_X86_64
6775 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
6776 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
6777 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
6778 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
6779 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
6780 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
6781 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
6782 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
6785 kvm_rip_write(vcpu, regs->rip);
6786 kvm_set_rflags(vcpu, regs->rflags);
6788 vcpu->arch.exception.pending = false;
6790 kvm_make_request(KVM_REQ_EVENT, vcpu);
6795 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
6797 struct kvm_segment cs;
6799 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
6803 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
6805 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
6806 struct kvm_sregs *sregs)
6810 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6811 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6812 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6813 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6814 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6815 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6817 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6818 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6820 kvm_x86_ops->get_idt(vcpu, &dt);
6821 sregs->idt.limit = dt.size;
6822 sregs->idt.base = dt.address;
6823 kvm_x86_ops->get_gdt(vcpu, &dt);
6824 sregs->gdt.limit = dt.size;
6825 sregs->gdt.base = dt.address;
6827 sregs->cr0 = kvm_read_cr0(vcpu);
6828 sregs->cr2 = vcpu->arch.cr2;
6829 sregs->cr3 = kvm_read_cr3(vcpu);
6830 sregs->cr4 = kvm_read_cr4(vcpu);
6831 sregs->cr8 = kvm_get_cr8(vcpu);
6832 sregs->efer = vcpu->arch.efer;
6833 sregs->apic_base = kvm_get_apic_base(vcpu);
6835 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
6837 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
6838 set_bit(vcpu->arch.interrupt.nr,
6839 (unsigned long *)sregs->interrupt_bitmap);
6844 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
6845 struct kvm_mp_state *mp_state)
6847 kvm_apic_accept_events(vcpu);
6848 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
6849 vcpu->arch.pv.pv_unhalted)
6850 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
6852 mp_state->mp_state = vcpu->arch.mp_state;
6857 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
6858 struct kvm_mp_state *mp_state)
6860 if (!kvm_vcpu_has_lapic(vcpu) &&
6861 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
6864 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
6865 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
6866 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
6868 vcpu->arch.mp_state = mp_state->mp_state;
6869 kvm_make_request(KVM_REQ_EVENT, vcpu);
6873 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
6874 int reason, bool has_error_code, u32 error_code)
6876 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6879 init_emulate_ctxt(vcpu);
6881 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
6882 has_error_code, error_code);
6885 return EMULATE_FAIL;
6887 kvm_rip_write(vcpu, ctxt->eip);
6888 kvm_set_rflags(vcpu, ctxt->eflags);
6889 kvm_make_request(KVM_REQ_EVENT, vcpu);
6890 return EMULATE_DONE;
6892 EXPORT_SYMBOL_GPL(kvm_task_switch);
6894 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
6895 struct kvm_sregs *sregs)
6897 struct msr_data apic_base_msr;
6898 int mmu_reset_needed = 0;
6899 int pending_vec, max_bits, idx;
6902 if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
6905 dt.size = sregs->idt.limit;
6906 dt.address = sregs->idt.base;
6907 kvm_x86_ops->set_idt(vcpu, &dt);
6908 dt.size = sregs->gdt.limit;
6909 dt.address = sregs->gdt.base;
6910 kvm_x86_ops->set_gdt(vcpu, &dt);
6912 vcpu->arch.cr2 = sregs->cr2;
6913 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
6914 vcpu->arch.cr3 = sregs->cr3;
6915 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
6917 kvm_set_cr8(vcpu, sregs->cr8);
6919 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
6920 kvm_x86_ops->set_efer(vcpu, sregs->efer);
6921 apic_base_msr.data = sregs->apic_base;
6922 apic_base_msr.host_initiated = true;
6923 kvm_set_apic_base(vcpu, &apic_base_msr);
6925 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
6926 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
6927 vcpu->arch.cr0 = sregs->cr0;
6929 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
6930 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
6931 if (sregs->cr4 & X86_CR4_OSXSAVE)
6932 kvm_update_cpuid(vcpu);
6934 idx = srcu_read_lock(&vcpu->kvm->srcu);
6935 if (!is_long_mode(vcpu) && is_pae(vcpu)) {
6936 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
6937 mmu_reset_needed = 1;
6939 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6941 if (mmu_reset_needed)
6942 kvm_mmu_reset_context(vcpu);
6944 max_bits = KVM_NR_INTERRUPTS;
6945 pending_vec = find_first_bit(
6946 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
6947 if (pending_vec < max_bits) {
6948 kvm_queue_interrupt(vcpu, pending_vec, false);
6949 pr_debug("Set back pending irq %d\n", pending_vec);
6952 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6953 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6954 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6955 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6956 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6957 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6959 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6960 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6962 update_cr8_intercept(vcpu);
6964 /* Older userspace won't unhalt the vcpu on reset. */
6965 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
6966 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
6968 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
6970 kvm_make_request(KVM_REQ_EVENT, vcpu);
6975 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
6976 struct kvm_guest_debug *dbg)
6978 unsigned long rflags;
6981 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
6983 if (vcpu->arch.exception.pending)
6985 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
6986 kvm_queue_exception(vcpu, DB_VECTOR);
6988 kvm_queue_exception(vcpu, BP_VECTOR);
6992 * Read rflags as long as potentially injected trace flags are still
6995 rflags = kvm_get_rflags(vcpu);
6997 vcpu->guest_debug = dbg->control;
6998 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
6999 vcpu->guest_debug = 0;
7001 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7002 for (i = 0; i < KVM_NR_DB_REGS; ++i)
7003 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
7004 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
7006 for (i = 0; i < KVM_NR_DB_REGS; i++)
7007 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
7009 kvm_update_dr7(vcpu);
7011 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7012 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
7013 get_segment_base(vcpu, VCPU_SREG_CS);
7016 * Trigger an rflags update that will inject or remove the trace
7019 kvm_set_rflags(vcpu, rflags);
7021 kvm_x86_ops->update_db_bp_intercept(vcpu);
7031 * Translate a guest virtual address to a guest physical address.
7033 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
7034 struct kvm_translation *tr)
7036 unsigned long vaddr = tr->linear_address;
7040 idx = srcu_read_lock(&vcpu->kvm->srcu);
7041 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
7042 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7043 tr->physical_address = gpa;
7044 tr->valid = gpa != UNMAPPED_GVA;
7051 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7053 struct fxregs_state *fxsave =
7054 &vcpu->arch.guest_fpu.state.fxsave;
7056 memcpy(fpu->fpr, fxsave->st_space, 128);
7057 fpu->fcw = fxsave->cwd;
7058 fpu->fsw = fxsave->swd;
7059 fpu->ftwx = fxsave->twd;
7060 fpu->last_opcode = fxsave->fop;
7061 fpu->last_ip = fxsave->rip;
7062 fpu->last_dp = fxsave->rdp;
7063 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
7068 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7070 struct fxregs_state *fxsave =
7071 &vcpu->arch.guest_fpu.state.fxsave;
7073 memcpy(fxsave->st_space, fpu->fpr, 128);
7074 fxsave->cwd = fpu->fcw;
7075 fxsave->swd = fpu->fsw;
7076 fxsave->twd = fpu->ftwx;
7077 fxsave->fop = fpu->last_opcode;
7078 fxsave->rip = fpu->last_ip;
7079 fxsave->rdp = fpu->last_dp;
7080 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
7085 static void fx_init(struct kvm_vcpu *vcpu)
7087 fpstate_init(&vcpu->arch.guest_fpu.state);
7089 vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
7090 host_xcr0 | XSTATE_COMPACTION_ENABLED;
7093 * Ensure guest xcr0 is valid for loading
7095 vcpu->arch.xcr0 = XSTATE_FP;
7097 vcpu->arch.cr0 |= X86_CR0_ET;
7100 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
7102 if (vcpu->guest_fpu_loaded)
7106 * Restore all possible states in the guest,
7107 * and assume host would use all available bits.
7108 * Guest xcr0 would be loaded later.
7110 kvm_put_guest_xcr0(vcpu);
7111 vcpu->guest_fpu_loaded = 1;
7112 __kernel_fpu_begin();
7113 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state);
7117 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
7119 kvm_put_guest_xcr0(vcpu);
7121 if (!vcpu->guest_fpu_loaded) {
7122 vcpu->fpu_counter = 0;
7126 vcpu->guest_fpu_loaded = 0;
7127 copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
7129 ++vcpu->stat.fpu_reload;
7131 * If using eager FPU mode, or if the guest is a frequent user
7132 * of the FPU, just leave the FPU active for next time.
7133 * Every 255 times fpu_counter rolls over to 0; a guest that uses
7134 * the FPU in bursts will revert to loading it on demand.
7136 if (!vcpu->arch.eager_fpu) {
7137 if (++vcpu->fpu_counter < 5)
7138 kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
7143 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
7145 kvmclock_reset(vcpu);
7147 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
7148 kvm_x86_ops->vcpu_free(vcpu);
7151 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
7154 struct kvm_vcpu *vcpu;
7156 if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
7157 printk_once(KERN_WARNING
7158 "kvm: SMP vm created on host with unstable TSC; "
7159 "guest TSC will not be reliable\n");
7161 vcpu = kvm_x86_ops->vcpu_create(kvm, id);
7166 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
7170 kvm_vcpu_mtrr_init(vcpu);
7171 r = vcpu_load(vcpu);
7174 kvm_vcpu_reset(vcpu, false);
7175 kvm_mmu_setup(vcpu);
7180 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
7182 struct msr_data msr;
7183 struct kvm *kvm = vcpu->kvm;
7185 if (vcpu_load(vcpu))
7188 msr.index = MSR_IA32_TSC;
7189 msr.host_initiated = true;
7190 kvm_write_tsc(vcpu, &msr);
7193 if (!kvmclock_periodic_sync)
7196 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
7197 KVMCLOCK_SYNC_PERIOD);
7200 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
7203 vcpu->arch.apf.msr_val = 0;
7205 r = vcpu_load(vcpu);
7207 kvm_mmu_unload(vcpu);
7210 kvm_x86_ops->vcpu_free(vcpu);
7213 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
7215 vcpu->arch.hflags = 0;
7217 atomic_set(&vcpu->arch.nmi_queued, 0);
7218 vcpu->arch.nmi_pending = 0;
7219 vcpu->arch.nmi_injected = false;
7220 kvm_clear_interrupt_queue(vcpu);
7221 kvm_clear_exception_queue(vcpu);
7223 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
7224 kvm_update_dr0123(vcpu);
7225 vcpu->arch.dr6 = DR6_INIT;
7226 kvm_update_dr6(vcpu);
7227 vcpu->arch.dr7 = DR7_FIXED_1;
7228 kvm_update_dr7(vcpu);
7232 kvm_make_request(KVM_REQ_EVENT, vcpu);
7233 vcpu->arch.apf.msr_val = 0;
7234 vcpu->arch.st.msr_val = 0;
7236 kvmclock_reset(vcpu);
7238 kvm_clear_async_pf_completion_queue(vcpu);
7239 kvm_async_pf_hash_reset(vcpu);
7240 vcpu->arch.apf.halted = false;
7243 kvm_pmu_reset(vcpu);
7244 vcpu->arch.smbase = 0x30000;
7247 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
7248 vcpu->arch.regs_avail = ~0;
7249 vcpu->arch.regs_dirty = ~0;
7251 kvm_x86_ops->vcpu_reset(vcpu, init_event);
7254 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
7256 struct kvm_segment cs;
7258 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7259 cs.selector = vector << 8;
7260 cs.base = vector << 12;
7261 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7262 kvm_rip_write(vcpu, 0);
7265 int kvm_arch_hardware_enable(void)
7268 struct kvm_vcpu *vcpu;
7273 bool stable, backwards_tsc = false;
7275 kvm_shared_msr_cpu_online();
7276 ret = kvm_x86_ops->hardware_enable();
7280 local_tsc = rdtsc();
7281 stable = !check_tsc_unstable();
7282 list_for_each_entry(kvm, &vm_list, vm_list) {
7283 kvm_for_each_vcpu(i, vcpu, kvm) {
7284 if (!stable && vcpu->cpu == smp_processor_id())
7285 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7286 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
7287 backwards_tsc = true;
7288 if (vcpu->arch.last_host_tsc > max_tsc)
7289 max_tsc = vcpu->arch.last_host_tsc;
7295 * Sometimes, even reliable TSCs go backwards. This happens on
7296 * platforms that reset TSC during suspend or hibernate actions, but
7297 * maintain synchronization. We must compensate. Fortunately, we can
7298 * detect that condition here, which happens early in CPU bringup,
7299 * before any KVM threads can be running. Unfortunately, we can't
7300 * bring the TSCs fully up to date with real time, as we aren't yet far
7301 * enough into CPU bringup that we know how much real time has actually
7302 * elapsed; our helper function, get_kernel_ns() will be using boot
7303 * variables that haven't been updated yet.
7305 * So we simply find the maximum observed TSC above, then record the
7306 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
7307 * the adjustment will be applied. Note that we accumulate
7308 * adjustments, in case multiple suspend cycles happen before some VCPU
7309 * gets a chance to run again. In the event that no KVM threads get a
7310 * chance to run, we will miss the entire elapsed period, as we'll have
7311 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
7312 * loose cycle time. This isn't too big a deal, since the loss will be
7313 * uniform across all VCPUs (not to mention the scenario is extremely
7314 * unlikely). It is possible that a second hibernate recovery happens
7315 * much faster than a first, causing the observed TSC here to be
7316 * smaller; this would require additional padding adjustment, which is
7317 * why we set last_host_tsc to the local tsc observed here.
7319 * N.B. - this code below runs only on platforms with reliable TSC,
7320 * as that is the only way backwards_tsc is set above. Also note
7321 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
7322 * have the same delta_cyc adjustment applied if backwards_tsc
7323 * is detected. Note further, this adjustment is only done once,
7324 * as we reset last_host_tsc on all VCPUs to stop this from being
7325 * called multiple times (one for each physical CPU bringup).
7327 * Platforms with unreliable TSCs don't have to deal with this, they
7328 * will be compensated by the logic in vcpu_load, which sets the TSC to
7329 * catchup mode. This will catchup all VCPUs to real time, but cannot
7330 * guarantee that they stay in perfect synchronization.
7332 if (backwards_tsc) {
7333 u64 delta_cyc = max_tsc - local_tsc;
7334 backwards_tsc_observed = true;
7335 list_for_each_entry(kvm, &vm_list, vm_list) {
7336 kvm_for_each_vcpu(i, vcpu, kvm) {
7337 vcpu->arch.tsc_offset_adjustment += delta_cyc;
7338 vcpu->arch.last_host_tsc = local_tsc;
7339 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7343 * We have to disable TSC offset matching.. if you were
7344 * booting a VM while issuing an S4 host suspend....
7345 * you may have some problem. Solving this issue is
7346 * left as an exercise to the reader.
7348 kvm->arch.last_tsc_nsec = 0;
7349 kvm->arch.last_tsc_write = 0;
7356 void kvm_arch_hardware_disable(void)
7358 kvm_x86_ops->hardware_disable();
7359 drop_user_return_notifiers();
7362 int kvm_arch_hardware_setup(void)
7366 r = kvm_x86_ops->hardware_setup();
7370 kvm_init_msr_list();
7374 void kvm_arch_hardware_unsetup(void)
7376 kvm_x86_ops->hardware_unsetup();
7379 void kvm_arch_check_processor_compat(void *rtn)
7381 kvm_x86_ops->check_processor_compatibility(rtn);
7384 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
7386 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
7388 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
7390 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
7392 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
7395 bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
7397 return irqchip_in_kernel(vcpu->kvm) == lapic_in_kernel(vcpu);
7400 struct static_key kvm_no_apic_vcpu __read_mostly;
7402 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
7408 BUG_ON(vcpu->kvm == NULL);
7411 vcpu->arch.pv.pv_unhalted = false;
7412 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
7413 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_reset_bsp(vcpu))
7414 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7416 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
7418 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
7423 vcpu->arch.pio_data = page_address(page);
7425 kvm_set_tsc_khz(vcpu, max_tsc_khz);
7427 r = kvm_mmu_create(vcpu);
7429 goto fail_free_pio_data;
7431 if (irqchip_in_kernel(kvm)) {
7432 r = kvm_create_lapic(vcpu);
7434 goto fail_mmu_destroy;
7436 static_key_slow_inc(&kvm_no_apic_vcpu);
7438 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
7440 if (!vcpu->arch.mce_banks) {
7442 goto fail_free_lapic;
7444 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
7446 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
7448 goto fail_free_mce_banks;
7453 vcpu->arch.ia32_tsc_adjust_msr = 0x0;
7454 vcpu->arch.pv_time_enabled = false;
7456 vcpu->arch.guest_supported_xcr0 = 0;
7457 vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
7459 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
7461 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
7463 kvm_async_pf_hash_reset(vcpu);
7466 vcpu->arch.pending_external_vector = -1;
7470 fail_free_mce_banks:
7471 kfree(vcpu->arch.mce_banks);
7473 kvm_free_lapic(vcpu);
7475 kvm_mmu_destroy(vcpu);
7477 free_page((unsigned long)vcpu->arch.pio_data);
7482 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
7486 kvm_pmu_destroy(vcpu);
7487 kfree(vcpu->arch.mce_banks);
7488 kvm_free_lapic(vcpu);
7489 idx = srcu_read_lock(&vcpu->kvm->srcu);
7490 kvm_mmu_destroy(vcpu);
7491 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7492 free_page((unsigned long)vcpu->arch.pio_data);
7493 if (!lapic_in_kernel(vcpu))
7494 static_key_slow_dec(&kvm_no_apic_vcpu);
7497 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
7499 kvm_x86_ops->sched_in(vcpu, cpu);
7502 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
7507 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
7508 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
7509 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
7510 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
7511 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
7513 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
7514 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
7515 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
7516 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
7517 &kvm->arch.irq_sources_bitmap);
7519 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
7520 mutex_init(&kvm->arch.apic_map_lock);
7521 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
7523 pvclock_update_vm_gtod_copy(kvm);
7525 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
7526 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
7531 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
7534 r = vcpu_load(vcpu);
7536 kvm_mmu_unload(vcpu);
7540 static void kvm_free_vcpus(struct kvm *kvm)
7543 struct kvm_vcpu *vcpu;
7546 * Unpin any mmu pages first.
7548 kvm_for_each_vcpu(i, vcpu, kvm) {
7549 kvm_clear_async_pf_completion_queue(vcpu);
7550 kvm_unload_vcpu_mmu(vcpu);
7552 kvm_for_each_vcpu(i, vcpu, kvm)
7553 kvm_arch_vcpu_free(vcpu);
7555 mutex_lock(&kvm->lock);
7556 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
7557 kvm->vcpus[i] = NULL;
7559 atomic_set(&kvm->online_vcpus, 0);
7560 mutex_unlock(&kvm->lock);
7563 void kvm_arch_sync_events(struct kvm *kvm)
7565 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
7566 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
7567 kvm_free_all_assigned_devices(kvm);
7571 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7575 struct kvm_memslots *slots = kvm_memslots(kvm);
7576 struct kvm_memory_slot *slot, old;
7578 /* Called with kvm->slots_lock held. */
7579 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
7582 slot = id_to_memslot(slots, id);
7584 if (WARN_ON(slot->npages))
7588 * MAP_SHARED to prevent internal slot pages from being moved
7591 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
7592 MAP_SHARED | MAP_ANONYMOUS, 0);
7593 if (IS_ERR((void *)hva))
7594 return PTR_ERR((void *)hva);
7603 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
7604 struct kvm_userspace_memory_region m;
7606 m.slot = id | (i << 16);
7608 m.guest_phys_addr = gpa;
7609 m.userspace_addr = hva;
7610 m.memory_size = size;
7611 r = __kvm_set_memory_region(kvm, &m);
7617 r = vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
7623 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
7625 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7629 mutex_lock(&kvm->slots_lock);
7630 r = __x86_set_memory_region(kvm, id, gpa, size);
7631 mutex_unlock(&kvm->slots_lock);
7635 EXPORT_SYMBOL_GPL(x86_set_memory_region);
7637 void kvm_arch_destroy_vm(struct kvm *kvm)
7639 if (current->mm == kvm->mm) {
7641 * Free memory regions allocated on behalf of userspace,
7642 * unless the the memory map has changed due to process exit
7645 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
7646 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
7647 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
7649 kvm_iommu_unmap_guest(kvm);
7650 kfree(kvm->arch.vpic);
7651 kfree(kvm->arch.vioapic);
7652 kvm_free_vcpus(kvm);
7653 kfree(rcu_dereference_check(kvm->arch.apic_map, 1));
7656 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
7657 struct kvm_memory_slot *dont)
7661 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7662 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
7663 kvfree(free->arch.rmap[i]);
7664 free->arch.rmap[i] = NULL;
7669 if (!dont || free->arch.lpage_info[i - 1] !=
7670 dont->arch.lpage_info[i - 1]) {
7671 kvfree(free->arch.lpage_info[i - 1]);
7672 free->arch.lpage_info[i - 1] = NULL;
7677 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
7678 unsigned long npages)
7682 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7687 lpages = gfn_to_index(slot->base_gfn + npages - 1,
7688 slot->base_gfn, level) + 1;
7690 slot->arch.rmap[i] =
7691 kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
7692 if (!slot->arch.rmap[i])
7697 slot->arch.lpage_info[i - 1] = kvm_kvzalloc(lpages *
7698 sizeof(*slot->arch.lpage_info[i - 1]));
7699 if (!slot->arch.lpage_info[i - 1])
7702 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
7703 slot->arch.lpage_info[i - 1][0].write_count = 1;
7704 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
7705 slot->arch.lpage_info[i - 1][lpages - 1].write_count = 1;
7706 ugfn = slot->userspace_addr >> PAGE_SHIFT;
7708 * If the gfn and userspace address are not aligned wrt each
7709 * other, or if explicitly asked to, disable large page
7710 * support for this slot
7712 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
7713 !kvm_largepages_enabled()) {
7716 for (j = 0; j < lpages; ++j)
7717 slot->arch.lpage_info[i - 1][j].write_count = 1;
7724 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7725 kvfree(slot->arch.rmap[i]);
7726 slot->arch.rmap[i] = NULL;
7730 kvfree(slot->arch.lpage_info[i - 1]);
7731 slot->arch.lpage_info[i - 1] = NULL;
7736 void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
7739 * memslots->generation has been incremented.
7740 * mmio generation may have reached its maximum value.
7742 kvm_mmu_invalidate_mmio_sptes(kvm, slots);
7745 int kvm_arch_prepare_memory_region(struct kvm *kvm,
7746 struct kvm_memory_slot *memslot,
7747 const struct kvm_userspace_memory_region *mem,
7748 enum kvm_mr_change change)
7753 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
7754 struct kvm_memory_slot *new)
7756 /* Still write protect RO slot */
7757 if (new->flags & KVM_MEM_READONLY) {
7758 kvm_mmu_slot_remove_write_access(kvm, new);
7763 * Call kvm_x86_ops dirty logging hooks when they are valid.
7765 * kvm_x86_ops->slot_disable_log_dirty is called when:
7767 * - KVM_MR_CREATE with dirty logging is disabled
7768 * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
7770 * The reason is, in case of PML, we need to set D-bit for any slots
7771 * with dirty logging disabled in order to eliminate unnecessary GPA
7772 * logging in PML buffer (and potential PML buffer full VMEXT). This
7773 * guarantees leaving PML enabled during guest's lifetime won't have
7774 * any additonal overhead from PML when guest is running with dirty
7775 * logging disabled for memory slots.
7777 * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
7778 * to dirty logging mode.
7780 * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
7782 * In case of write protect:
7784 * Write protect all pages for dirty logging.
7786 * All the sptes including the large sptes which point to this
7787 * slot are set to readonly. We can not create any new large
7788 * spte on this slot until the end of the logging.
7790 * See the comments in fast_page_fault().
7792 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
7793 if (kvm_x86_ops->slot_enable_log_dirty)
7794 kvm_x86_ops->slot_enable_log_dirty(kvm, new);
7796 kvm_mmu_slot_remove_write_access(kvm, new);
7798 if (kvm_x86_ops->slot_disable_log_dirty)
7799 kvm_x86_ops->slot_disable_log_dirty(kvm, new);
7803 void kvm_arch_commit_memory_region(struct kvm *kvm,
7804 const struct kvm_userspace_memory_region *mem,
7805 const struct kvm_memory_slot *old,
7806 const struct kvm_memory_slot *new,
7807 enum kvm_mr_change change)
7809 int nr_mmu_pages = 0;
7811 if (!kvm->arch.n_requested_mmu_pages)
7812 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
7815 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
7818 * Dirty logging tracks sptes in 4k granularity, meaning that large
7819 * sptes have to be split. If live migration is successful, the guest
7820 * in the source machine will be destroyed and large sptes will be
7821 * created in the destination. However, if the guest continues to run
7822 * in the source machine (for example if live migration fails), small
7823 * sptes will remain around and cause bad performance.
7825 * Scan sptes if dirty logging has been stopped, dropping those
7826 * which can be collapsed into a single large-page spte. Later
7827 * page faults will create the large-page sptes.
7829 if ((change != KVM_MR_DELETE) &&
7830 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
7831 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
7832 kvm_mmu_zap_collapsible_sptes(kvm, new);
7835 * Set up write protection and/or dirty logging for the new slot.
7837 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
7838 * been zapped so no dirty logging staff is needed for old slot. For
7839 * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
7840 * new and it's also covered when dealing with the new slot.
7842 * FIXME: const-ify all uses of struct kvm_memory_slot.
7844 if (change != KVM_MR_DELETE)
7845 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
7848 void kvm_arch_flush_shadow_all(struct kvm *kvm)
7850 kvm_mmu_invalidate_zap_all_pages(kvm);
7853 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
7854 struct kvm_memory_slot *slot)
7856 kvm_mmu_invalidate_zap_all_pages(kvm);
7859 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
7861 if (!list_empty_careful(&vcpu->async_pf.done))
7864 if (kvm_apic_has_events(vcpu))
7867 if (vcpu->arch.pv.pv_unhalted)
7870 if (atomic_read(&vcpu->arch.nmi_queued))
7873 if (test_bit(KVM_REQ_SMI, &vcpu->requests))
7876 if (kvm_arch_interrupt_allowed(vcpu) &&
7877 kvm_cpu_has_interrupt(vcpu))
7883 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
7885 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
7886 kvm_x86_ops->check_nested_events(vcpu, false);
7888 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
7891 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
7893 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
7896 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
7898 return kvm_x86_ops->interrupt_allowed(vcpu);
7901 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
7903 if (is_64_bit_mode(vcpu))
7904 return kvm_rip_read(vcpu);
7905 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
7906 kvm_rip_read(vcpu));
7908 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
7910 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
7912 return kvm_get_linear_rip(vcpu) == linear_rip;
7914 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
7916 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
7918 unsigned long rflags;
7920 rflags = kvm_x86_ops->get_rflags(vcpu);
7921 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7922 rflags &= ~X86_EFLAGS_TF;
7925 EXPORT_SYMBOL_GPL(kvm_get_rflags);
7927 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
7929 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
7930 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
7931 rflags |= X86_EFLAGS_TF;
7932 kvm_x86_ops->set_rflags(vcpu, rflags);
7935 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
7937 __kvm_set_rflags(vcpu, rflags);
7938 kvm_make_request(KVM_REQ_EVENT, vcpu);
7940 EXPORT_SYMBOL_GPL(kvm_set_rflags);
7942 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
7946 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
7950 r = kvm_mmu_reload(vcpu);
7954 if (!vcpu->arch.mmu.direct_map &&
7955 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
7958 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
7961 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
7963 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
7966 static inline u32 kvm_async_pf_next_probe(u32 key)
7968 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
7971 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
7973 u32 key = kvm_async_pf_hash_fn(gfn);
7975 while (vcpu->arch.apf.gfns[key] != ~0)
7976 key = kvm_async_pf_next_probe(key);
7978 vcpu->arch.apf.gfns[key] = gfn;
7981 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
7984 u32 key = kvm_async_pf_hash_fn(gfn);
7986 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
7987 (vcpu->arch.apf.gfns[key] != gfn &&
7988 vcpu->arch.apf.gfns[key] != ~0); i++)
7989 key = kvm_async_pf_next_probe(key);
7994 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
7996 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
7999 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8003 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
8005 vcpu->arch.apf.gfns[i] = ~0;
8007 j = kvm_async_pf_next_probe(j);
8008 if (vcpu->arch.apf.gfns[j] == ~0)
8010 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
8012 * k lies cyclically in ]i,j]
8014 * |....j i.k.| or |.k..j i...|
8016 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
8017 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
8022 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
8025 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
8029 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
8030 struct kvm_async_pf *work)
8032 struct x86_exception fault;
8034 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
8035 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
8037 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
8038 (vcpu->arch.apf.send_user_only &&
8039 kvm_x86_ops->get_cpl(vcpu) == 0))
8040 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
8041 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
8042 fault.vector = PF_VECTOR;
8043 fault.error_code_valid = true;
8044 fault.error_code = 0;
8045 fault.nested_page_fault = false;
8046 fault.address = work->arch.token;
8047 kvm_inject_page_fault(vcpu, &fault);
8051 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
8052 struct kvm_async_pf *work)
8054 struct x86_exception fault;
8056 trace_kvm_async_pf_ready(work->arch.token, work->gva);
8057 if (work->wakeup_all)
8058 work->arch.token = ~0; /* broadcast wakeup */
8060 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
8062 if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
8063 !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
8064 fault.vector = PF_VECTOR;
8065 fault.error_code_valid = true;
8066 fault.error_code = 0;
8067 fault.nested_page_fault = false;
8068 fault.address = work->arch.token;
8069 kvm_inject_page_fault(vcpu, &fault);
8071 vcpu->arch.apf.halted = false;
8072 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8075 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
8077 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
8080 return !kvm_event_needs_reinjection(vcpu) &&
8081 kvm_x86_ops->interrupt_allowed(vcpu);
8084 void kvm_arch_start_assignment(struct kvm *kvm)
8086 atomic_inc(&kvm->arch.assigned_device_count);
8088 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
8090 void kvm_arch_end_assignment(struct kvm *kvm)
8092 atomic_dec(&kvm->arch.assigned_device_count);
8094 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
8096 bool kvm_arch_has_assigned_device(struct kvm *kvm)
8098 return atomic_read(&kvm->arch.assigned_device_count);
8100 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
8102 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
8104 atomic_inc(&kvm->arch.noncoherent_dma_count);
8106 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
8108 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
8110 atomic_dec(&kvm->arch.noncoherent_dma_count);
8112 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
8114 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
8116 return atomic_read(&kvm->arch.noncoherent_dma_count);
8118 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
8120 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
8121 struct irq_bypass_producer *prod)
8123 struct kvm_kernel_irqfd *irqfd =
8124 container_of(cons, struct kvm_kernel_irqfd, consumer);
8126 if (kvm_x86_ops->update_pi_irte) {
8127 irqfd->producer = prod;
8128 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
8129 prod->irq, irqfd->gsi, 1);
8135 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
8136 struct irq_bypass_producer *prod)
8139 struct kvm_kernel_irqfd *irqfd =
8140 container_of(cons, struct kvm_kernel_irqfd, consumer);
8142 if (!kvm_x86_ops->update_pi_irte) {
8143 WARN_ON(irqfd->producer != NULL);
8147 WARN_ON(irqfd->producer != prod);
8148 irqfd->producer = NULL;
8151 * When producer of consumer is unregistered, we change back to
8152 * remapped mode, so we can re-use the current implementation
8153 * when the irq is masked/disabed or the consumer side (KVM
8154 * int this case doesn't want to receive the interrupts.
8156 ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
8158 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
8159 " fails: %d\n", irqfd->consumer.token, ret);
8162 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
8163 uint32_t guest_irq, bool set)
8165 if (!kvm_x86_ops->update_pi_irte)
8168 return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
8171 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
8172 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
8173 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
8174 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
8175 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
8176 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
8177 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
8178 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
8179 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
8180 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
8181 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
8182 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
8183 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
8184 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
8185 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
8186 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
8187 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);