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 <linux/clocksource.h>
31 #include <linux/interrupt.h>
32 #include <linux/kvm.h>
34 #include <linux/vmalloc.h>
35 #include <linux/module.h>
36 #include <linux/mman.h>
37 #include <linux/highmem.h>
38 #include <linux/iommu.h>
39 #include <linux/intel-iommu.h>
40 #include <linux/cpufreq.h>
41 #include <linux/user-return-notifier.h>
42 #include <linux/srcu.h>
43 #include <linux/slab.h>
44 #include <linux/perf_event.h>
45 #include <linux/uaccess.h>
46 #include <linux/hash.h>
47 #include <linux/pci.h>
48 #include <trace/events/kvm.h>
50 #define CREATE_TRACE_POINTS
53 #include <asm/debugreg.h>
60 #include <asm/pvclock.h>
61 #include <asm/div64.h>
63 #define MAX_IO_MSRS 256
64 #define KVM_MAX_MCE_BANKS 32
65 #define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
67 #define emul_to_vcpu(ctxt) \
68 container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
71 * - enable syscall per default because its emulated by KVM
72 * - enable LME and LMA per default on 64 bit KVM
76 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
78 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
81 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
82 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
84 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
85 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
86 struct kvm_cpuid_entry2 __user *entries);
87 static void process_nmi(struct kvm_vcpu *vcpu);
89 struct kvm_x86_ops *kvm_x86_ops;
90 EXPORT_SYMBOL_GPL(kvm_x86_ops);
93 module_param_named(ignore_msrs, ignore_msrs, bool, S_IRUGO | S_IWUSR);
95 bool kvm_has_tsc_control;
96 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
97 u32 kvm_max_guest_tsc_khz;
98 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
100 #define KVM_NR_SHARED_MSRS 16
102 struct kvm_shared_msrs_global {
104 u32 msrs[KVM_NR_SHARED_MSRS];
107 struct kvm_shared_msrs {
108 struct user_return_notifier urn;
110 struct kvm_shared_msr_values {
113 } values[KVM_NR_SHARED_MSRS];
116 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
117 static DEFINE_PER_CPU(struct kvm_shared_msrs, shared_msrs);
119 struct kvm_stats_debugfs_item debugfs_entries[] = {
120 { "pf_fixed", VCPU_STAT(pf_fixed) },
121 { "pf_guest", VCPU_STAT(pf_guest) },
122 { "tlb_flush", VCPU_STAT(tlb_flush) },
123 { "invlpg", VCPU_STAT(invlpg) },
124 { "exits", VCPU_STAT(exits) },
125 { "io_exits", VCPU_STAT(io_exits) },
126 { "mmio_exits", VCPU_STAT(mmio_exits) },
127 { "signal_exits", VCPU_STAT(signal_exits) },
128 { "irq_window", VCPU_STAT(irq_window_exits) },
129 { "nmi_window", VCPU_STAT(nmi_window_exits) },
130 { "halt_exits", VCPU_STAT(halt_exits) },
131 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
132 { "hypercalls", VCPU_STAT(hypercalls) },
133 { "request_irq", VCPU_STAT(request_irq_exits) },
134 { "irq_exits", VCPU_STAT(irq_exits) },
135 { "host_state_reload", VCPU_STAT(host_state_reload) },
136 { "efer_reload", VCPU_STAT(efer_reload) },
137 { "fpu_reload", VCPU_STAT(fpu_reload) },
138 { "insn_emulation", VCPU_STAT(insn_emulation) },
139 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
140 { "irq_injections", VCPU_STAT(irq_injections) },
141 { "nmi_injections", VCPU_STAT(nmi_injections) },
142 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
143 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
144 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
145 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
146 { "mmu_flooded", VM_STAT(mmu_flooded) },
147 { "mmu_recycled", VM_STAT(mmu_recycled) },
148 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
149 { "mmu_unsync", VM_STAT(mmu_unsync) },
150 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
151 { "largepages", VM_STAT(lpages) },
155 u64 __read_mostly host_xcr0;
157 int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
159 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
162 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
163 vcpu->arch.apf.gfns[i] = ~0;
166 static void kvm_on_user_return(struct user_return_notifier *urn)
169 struct kvm_shared_msrs *locals
170 = container_of(urn, struct kvm_shared_msrs, urn);
171 struct kvm_shared_msr_values *values;
173 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
174 values = &locals->values[slot];
175 if (values->host != values->curr) {
176 wrmsrl(shared_msrs_global.msrs[slot], values->host);
177 values->curr = values->host;
180 locals->registered = false;
181 user_return_notifier_unregister(urn);
184 static void shared_msr_update(unsigned slot, u32 msr)
186 struct kvm_shared_msrs *smsr;
189 smsr = &__get_cpu_var(shared_msrs);
190 /* only read, and nobody should modify it at this time,
191 * so don't need lock */
192 if (slot >= shared_msrs_global.nr) {
193 printk(KERN_ERR "kvm: invalid MSR slot!");
196 rdmsrl_safe(msr, &value);
197 smsr->values[slot].host = value;
198 smsr->values[slot].curr = value;
201 void kvm_define_shared_msr(unsigned slot, u32 msr)
203 if (slot >= shared_msrs_global.nr)
204 shared_msrs_global.nr = slot + 1;
205 shared_msrs_global.msrs[slot] = msr;
206 /* we need ensured the shared_msr_global have been updated */
209 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
211 static void kvm_shared_msr_cpu_online(void)
215 for (i = 0; i < shared_msrs_global.nr; ++i)
216 shared_msr_update(i, shared_msrs_global.msrs[i]);
219 void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
221 struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
223 if (((value ^ smsr->values[slot].curr) & mask) == 0)
225 smsr->values[slot].curr = value;
226 wrmsrl(shared_msrs_global.msrs[slot], value);
227 if (!smsr->registered) {
228 smsr->urn.on_user_return = kvm_on_user_return;
229 user_return_notifier_register(&smsr->urn);
230 smsr->registered = true;
233 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
235 static void drop_user_return_notifiers(void *ignore)
237 struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
239 if (smsr->registered)
240 kvm_on_user_return(&smsr->urn);
243 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
245 if (irqchip_in_kernel(vcpu->kvm))
246 return vcpu->arch.apic_base;
248 return vcpu->arch.apic_base;
250 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
252 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
254 /* TODO: reserve bits check */
255 if (irqchip_in_kernel(vcpu->kvm))
256 kvm_lapic_set_base(vcpu, data);
258 vcpu->arch.apic_base = data;
260 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
262 #define EXCPT_BENIGN 0
263 #define EXCPT_CONTRIBUTORY 1
266 static int exception_class(int vector)
276 return EXCPT_CONTRIBUTORY;
283 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
284 unsigned nr, bool has_error, u32 error_code,
290 kvm_make_request(KVM_REQ_EVENT, vcpu);
292 if (!vcpu->arch.exception.pending) {
294 vcpu->arch.exception.pending = true;
295 vcpu->arch.exception.has_error_code = has_error;
296 vcpu->arch.exception.nr = nr;
297 vcpu->arch.exception.error_code = error_code;
298 vcpu->arch.exception.reinject = reinject;
302 /* to check exception */
303 prev_nr = vcpu->arch.exception.nr;
304 if (prev_nr == DF_VECTOR) {
305 /* triple fault -> shutdown */
306 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
309 class1 = exception_class(prev_nr);
310 class2 = exception_class(nr);
311 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
312 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
313 /* generate double fault per SDM Table 5-5 */
314 vcpu->arch.exception.pending = true;
315 vcpu->arch.exception.has_error_code = true;
316 vcpu->arch.exception.nr = DF_VECTOR;
317 vcpu->arch.exception.error_code = 0;
319 /* replace previous exception with a new one in a hope
320 that instruction re-execution will regenerate lost
325 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
327 kvm_multiple_exception(vcpu, nr, false, 0, false);
329 EXPORT_SYMBOL_GPL(kvm_queue_exception);
331 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
333 kvm_multiple_exception(vcpu, nr, false, 0, true);
335 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
337 void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
340 kvm_inject_gp(vcpu, 0);
342 kvm_x86_ops->skip_emulated_instruction(vcpu);
344 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
346 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
348 ++vcpu->stat.pf_guest;
349 vcpu->arch.cr2 = fault->address;
350 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
352 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
354 void kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
356 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
357 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
359 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
362 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
364 atomic_inc(&vcpu->arch.nmi_queued);
365 kvm_make_request(KVM_REQ_NMI, vcpu);
367 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
369 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
371 kvm_multiple_exception(vcpu, nr, true, error_code, false);
373 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
375 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
377 kvm_multiple_exception(vcpu, nr, true, error_code, true);
379 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
382 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
383 * a #GP and return false.
385 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
387 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
389 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
392 EXPORT_SYMBOL_GPL(kvm_require_cpl);
395 * This function will be used to read from the physical memory of the currently
396 * running guest. The difference to kvm_read_guest_page is that this function
397 * can read from guest physical or from the guest's guest physical memory.
399 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
400 gfn_t ngfn, void *data, int offset, int len,
406 ngpa = gfn_to_gpa(ngfn);
407 real_gfn = mmu->translate_gpa(vcpu, ngpa, access);
408 if (real_gfn == UNMAPPED_GVA)
411 real_gfn = gpa_to_gfn(real_gfn);
413 return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
415 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
417 int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
418 void *data, int offset, int len, u32 access)
420 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
421 data, offset, len, access);
425 * Load the pae pdptrs. Return true is they are all valid.
427 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
429 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
430 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
433 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
435 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
436 offset * sizeof(u64), sizeof(pdpte),
437 PFERR_USER_MASK|PFERR_WRITE_MASK);
442 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
443 if (is_present_gpte(pdpte[i]) &&
444 (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
451 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
452 __set_bit(VCPU_EXREG_PDPTR,
453 (unsigned long *)&vcpu->arch.regs_avail);
454 __set_bit(VCPU_EXREG_PDPTR,
455 (unsigned long *)&vcpu->arch.regs_dirty);
460 EXPORT_SYMBOL_GPL(load_pdptrs);
462 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
464 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
470 if (is_long_mode(vcpu) || !is_pae(vcpu))
473 if (!test_bit(VCPU_EXREG_PDPTR,
474 (unsigned long *)&vcpu->arch.regs_avail))
477 gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
478 offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
479 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
480 PFERR_USER_MASK | PFERR_WRITE_MASK);
483 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
489 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
491 unsigned long old_cr0 = kvm_read_cr0(vcpu);
492 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
493 X86_CR0_CD | X86_CR0_NW;
498 if (cr0 & 0xffffffff00000000UL)
502 cr0 &= ~CR0_RESERVED_BITS;
504 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
507 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
510 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
512 if ((vcpu->arch.efer & EFER_LME)) {
517 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
522 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
527 kvm_x86_ops->set_cr0(vcpu, cr0);
529 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
530 kvm_clear_async_pf_completion_queue(vcpu);
531 kvm_async_pf_hash_reset(vcpu);
534 if ((cr0 ^ old_cr0) & update_bits)
535 kvm_mmu_reset_context(vcpu);
538 EXPORT_SYMBOL_GPL(kvm_set_cr0);
540 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
542 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
544 EXPORT_SYMBOL_GPL(kvm_lmsw);
546 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
550 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
551 if (index != XCR_XFEATURE_ENABLED_MASK)
554 if (kvm_x86_ops->get_cpl(vcpu) != 0)
556 if (!(xcr0 & XSTATE_FP))
558 if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
560 if (xcr0 & ~host_xcr0)
562 vcpu->arch.xcr0 = xcr0;
563 vcpu->guest_xcr0_loaded = 0;
567 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
569 if (__kvm_set_xcr(vcpu, index, xcr)) {
570 kvm_inject_gp(vcpu, 0);
575 EXPORT_SYMBOL_GPL(kvm_set_xcr);
577 static bool guest_cpuid_has_xsave(struct kvm_vcpu *vcpu)
579 struct kvm_cpuid_entry2 *best;
581 if (!static_cpu_has(X86_FEATURE_XSAVE))
584 best = kvm_find_cpuid_entry(vcpu, 1, 0);
585 return best && (best->ecx & bit(X86_FEATURE_XSAVE));
588 static bool guest_cpuid_has_smep(struct kvm_vcpu *vcpu)
590 struct kvm_cpuid_entry2 *best;
592 best = kvm_find_cpuid_entry(vcpu, 7, 0);
593 return best && (best->ebx & bit(X86_FEATURE_SMEP));
596 static bool guest_cpuid_has_fsgsbase(struct kvm_vcpu *vcpu)
598 struct kvm_cpuid_entry2 *best;
600 best = kvm_find_cpuid_entry(vcpu, 7, 0);
601 return best && (best->ebx & bit(X86_FEATURE_FSGSBASE));
604 static void update_cpuid(struct kvm_vcpu *vcpu)
606 struct kvm_cpuid_entry2 *best;
607 struct kvm_lapic *apic = vcpu->arch.apic;
609 best = kvm_find_cpuid_entry(vcpu, 1, 0);
613 /* Update OSXSAVE bit */
614 if (cpu_has_xsave && best->function == 0x1) {
615 best->ecx &= ~(bit(X86_FEATURE_OSXSAVE));
616 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE))
617 best->ecx |= bit(X86_FEATURE_OSXSAVE);
621 if (best->ecx & bit(X86_FEATURE_TSC_DEADLINE_TIMER))
622 apic->lapic_timer.timer_mode_mask = 3 << 17;
624 apic->lapic_timer.timer_mode_mask = 1 << 17;
628 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
630 unsigned long old_cr4 = kvm_read_cr4(vcpu);
631 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
632 X86_CR4_PAE | X86_CR4_SMEP;
633 if (cr4 & CR4_RESERVED_BITS)
636 if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
639 if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
642 if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_RDWRGSFS))
645 if (is_long_mode(vcpu)) {
646 if (!(cr4 & X86_CR4_PAE))
648 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
649 && ((cr4 ^ old_cr4) & pdptr_bits)
650 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
654 if (kvm_x86_ops->set_cr4(vcpu, cr4))
657 if ((cr4 ^ old_cr4) & pdptr_bits)
658 kvm_mmu_reset_context(vcpu);
660 if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
665 EXPORT_SYMBOL_GPL(kvm_set_cr4);
667 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
669 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
670 kvm_mmu_sync_roots(vcpu);
671 kvm_mmu_flush_tlb(vcpu);
675 if (is_long_mode(vcpu)) {
676 if (cr3 & CR3_L_MODE_RESERVED_BITS)
680 if (cr3 & CR3_PAE_RESERVED_BITS)
682 if (is_paging(vcpu) &&
683 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
687 * We don't check reserved bits in nonpae mode, because
688 * this isn't enforced, and VMware depends on this.
693 * Does the new cr3 value map to physical memory? (Note, we
694 * catch an invalid cr3 even in real-mode, because it would
695 * cause trouble later on when we turn on paging anyway.)
697 * A real CPU would silently accept an invalid cr3 and would
698 * attempt to use it - with largely undefined (and often hard
699 * to debug) behavior on the guest side.
701 if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
703 vcpu->arch.cr3 = cr3;
704 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
705 vcpu->arch.mmu.new_cr3(vcpu);
708 EXPORT_SYMBOL_GPL(kvm_set_cr3);
710 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
712 if (cr8 & CR8_RESERVED_BITS)
714 if (irqchip_in_kernel(vcpu->kvm))
715 kvm_lapic_set_tpr(vcpu, cr8);
717 vcpu->arch.cr8 = cr8;
720 EXPORT_SYMBOL_GPL(kvm_set_cr8);
722 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
724 if (irqchip_in_kernel(vcpu->kvm))
725 return kvm_lapic_get_cr8(vcpu);
727 return vcpu->arch.cr8;
729 EXPORT_SYMBOL_GPL(kvm_get_cr8);
731 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
735 vcpu->arch.db[dr] = val;
736 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
737 vcpu->arch.eff_db[dr] = val;
740 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
744 if (val & 0xffffffff00000000ULL)
746 vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
749 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
753 if (val & 0xffffffff00000000ULL)
755 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
756 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
757 kvm_x86_ops->set_dr7(vcpu, vcpu->arch.dr7);
758 vcpu->arch.switch_db_regs = (val & DR7_BP_EN_MASK);
766 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
770 res = __kvm_set_dr(vcpu, dr, val);
772 kvm_queue_exception(vcpu, UD_VECTOR);
774 kvm_inject_gp(vcpu, 0);
778 EXPORT_SYMBOL_GPL(kvm_set_dr);
780 static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
784 *val = vcpu->arch.db[dr];
787 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
791 *val = vcpu->arch.dr6;
794 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
798 *val = vcpu->arch.dr7;
805 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
807 if (_kvm_get_dr(vcpu, dr, val)) {
808 kvm_queue_exception(vcpu, UD_VECTOR);
813 EXPORT_SYMBOL_GPL(kvm_get_dr);
816 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
817 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
819 * This list is modified at module load time to reflect the
820 * capabilities of the host cpu. This capabilities test skips MSRs that are
821 * kvm-specific. Those are put in the beginning of the list.
824 #define KVM_SAVE_MSRS_BEGIN 9
825 static u32 msrs_to_save[] = {
826 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
827 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
828 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
829 HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
830 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
833 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
835 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA
838 static unsigned num_msrs_to_save;
840 static u32 emulated_msrs[] = {
841 MSR_IA32_TSCDEADLINE,
842 MSR_IA32_MISC_ENABLE,
847 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
849 u64 old_efer = vcpu->arch.efer;
851 if (efer & efer_reserved_bits)
855 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
858 if (efer & EFER_FFXSR) {
859 struct kvm_cpuid_entry2 *feat;
861 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
862 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
866 if (efer & EFER_SVME) {
867 struct kvm_cpuid_entry2 *feat;
869 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
870 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
875 efer |= vcpu->arch.efer & EFER_LMA;
877 kvm_x86_ops->set_efer(vcpu, efer);
879 vcpu->arch.mmu.base_role.nxe = (efer & EFER_NX) && !tdp_enabled;
881 /* Update reserved bits */
882 if ((efer ^ old_efer) & EFER_NX)
883 kvm_mmu_reset_context(vcpu);
888 void kvm_enable_efer_bits(u64 mask)
890 efer_reserved_bits &= ~mask;
892 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
896 * Writes msr value into into the appropriate "register".
897 * Returns 0 on success, non-0 otherwise.
898 * Assumes vcpu_load() was already called.
900 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
902 return kvm_x86_ops->set_msr(vcpu, msr_index, data);
906 * Adapt set_msr() to msr_io()'s calling convention
908 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
910 return kvm_set_msr(vcpu, index, *data);
913 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
917 struct pvclock_wall_clock wc;
918 struct timespec boot;
923 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
928 ++version; /* first time write, random junk */
932 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
935 * The guest calculates current wall clock time by adding
936 * system time (updated by kvm_guest_time_update below) to the
937 * wall clock specified here. guest system time equals host
938 * system time for us, thus we must fill in host boot time here.
942 wc.sec = boot.tv_sec;
943 wc.nsec = boot.tv_nsec;
944 wc.version = version;
946 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
949 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
952 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
954 uint32_t quotient, remainder;
956 /* Don't try to replace with do_div(), this one calculates
957 * "(dividend << 32) / divisor" */
959 : "=a" (quotient), "=d" (remainder)
960 : "0" (0), "1" (dividend), "r" (divisor) );
964 static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
965 s8 *pshift, u32 *pmultiplier)
972 tps64 = base_khz * 1000LL;
973 scaled64 = scaled_khz * 1000LL;
974 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
979 tps32 = (uint32_t)tps64;
980 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
981 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
989 *pmultiplier = div_frac(scaled64, tps32);
991 pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
992 __func__, base_khz, scaled_khz, shift, *pmultiplier);
995 static inline u64 get_kernel_ns(void)
999 WARN_ON(preemptible());
1001 monotonic_to_bootbased(&ts);
1002 return timespec_to_ns(&ts);
1005 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1006 unsigned long max_tsc_khz;
1008 static inline int kvm_tsc_changes_freq(void)
1010 int cpu = get_cpu();
1011 int ret = !boot_cpu_has(X86_FEATURE_CONSTANT_TSC) &&
1012 cpufreq_quick_get(cpu) != 0;
1017 u64 vcpu_tsc_khz(struct kvm_vcpu *vcpu)
1019 if (vcpu->arch.virtual_tsc_khz)
1020 return vcpu->arch.virtual_tsc_khz;
1022 return __this_cpu_read(cpu_tsc_khz);
1025 static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
1029 WARN_ON(preemptible());
1030 if (kvm_tsc_changes_freq())
1031 printk_once(KERN_WARNING
1032 "kvm: unreliable cycle conversion on adjustable rate TSC\n");
1033 ret = nsec * vcpu_tsc_khz(vcpu);
1034 do_div(ret, USEC_PER_SEC);
1038 static void kvm_init_tsc_catchup(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
1040 /* Compute a scale to convert nanoseconds in TSC cycles */
1041 kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
1042 &vcpu->arch.tsc_catchup_shift,
1043 &vcpu->arch.tsc_catchup_mult);
1046 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1048 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.last_tsc_nsec,
1049 vcpu->arch.tsc_catchup_mult,
1050 vcpu->arch.tsc_catchup_shift);
1051 tsc += vcpu->arch.last_tsc_write;
1055 void kvm_write_tsc(struct kvm_vcpu *vcpu, u64 data)
1057 struct kvm *kvm = vcpu->kvm;
1058 u64 offset, ns, elapsed;
1059 unsigned long flags;
1062 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1063 offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
1064 ns = get_kernel_ns();
1065 elapsed = ns - kvm->arch.last_tsc_nsec;
1066 sdiff = data - kvm->arch.last_tsc_write;
1071 * Special case: close write to TSC within 5 seconds of
1072 * another CPU is interpreted as an attempt to synchronize
1073 * The 5 seconds is to accommodate host load / swapping as
1074 * well as any reset of TSC during the boot process.
1076 * In that case, for a reliable TSC, we can match TSC offsets,
1077 * or make a best guest using elapsed value.
1079 if (sdiff < nsec_to_cycles(vcpu, 5ULL * NSEC_PER_SEC) &&
1080 elapsed < 5ULL * NSEC_PER_SEC) {
1081 if (!check_tsc_unstable()) {
1082 offset = kvm->arch.last_tsc_offset;
1083 pr_debug("kvm: matched tsc offset for %llu\n", data);
1085 u64 delta = nsec_to_cycles(vcpu, elapsed);
1087 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1089 ns = kvm->arch.last_tsc_nsec;
1091 kvm->arch.last_tsc_nsec = ns;
1092 kvm->arch.last_tsc_write = data;
1093 kvm->arch.last_tsc_offset = offset;
1094 kvm_x86_ops->write_tsc_offset(vcpu, offset);
1095 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1097 /* Reset of TSC must disable overshoot protection below */
1098 vcpu->arch.hv_clock.tsc_timestamp = 0;
1099 vcpu->arch.last_tsc_write = data;
1100 vcpu->arch.last_tsc_nsec = ns;
1102 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1104 static int kvm_guest_time_update(struct kvm_vcpu *v)
1106 unsigned long flags;
1107 struct kvm_vcpu_arch *vcpu = &v->arch;
1109 unsigned long this_tsc_khz;
1110 s64 kernel_ns, max_kernel_ns;
1113 /* Keep irq disabled to prevent changes to the clock */
1114 local_irq_save(flags);
1115 tsc_timestamp = kvm_x86_ops->read_l1_tsc(v);
1116 kernel_ns = get_kernel_ns();
1117 this_tsc_khz = vcpu_tsc_khz(v);
1118 if (unlikely(this_tsc_khz == 0)) {
1119 local_irq_restore(flags);
1120 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1125 * We may have to catch up the TSC to match elapsed wall clock
1126 * time for two reasons, even if kvmclock is used.
1127 * 1) CPU could have been running below the maximum TSC rate
1128 * 2) Broken TSC compensation resets the base at each VCPU
1129 * entry to avoid unknown leaps of TSC even when running
1130 * again on the same CPU. This may cause apparent elapsed
1131 * time to disappear, and the guest to stand still or run
1134 if (vcpu->tsc_catchup) {
1135 u64 tsc = compute_guest_tsc(v, kernel_ns);
1136 if (tsc > tsc_timestamp) {
1137 kvm_x86_ops->adjust_tsc_offset(v, tsc - tsc_timestamp);
1138 tsc_timestamp = tsc;
1142 local_irq_restore(flags);
1144 if (!vcpu->time_page)
1148 * Time as measured by the TSC may go backwards when resetting the base
1149 * tsc_timestamp. The reason for this is that the TSC resolution is
1150 * higher than the resolution of the other clock scales. Thus, many
1151 * possible measurments of the TSC correspond to one measurement of any
1152 * other clock, and so a spread of values is possible. This is not a
1153 * problem for the computation of the nanosecond clock; with TSC rates
1154 * around 1GHZ, there can only be a few cycles which correspond to one
1155 * nanosecond value, and any path through this code will inevitably
1156 * take longer than that. However, with the kernel_ns value itself,
1157 * the precision may be much lower, down to HZ granularity. If the
1158 * first sampling of TSC against kernel_ns ends in the low part of the
1159 * range, and the second in the high end of the range, we can get:
1161 * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new
1163 * As the sampling errors potentially range in the thousands of cycles,
1164 * it is possible such a time value has already been observed by the
1165 * guest. To protect against this, we must compute the system time as
1166 * observed by the guest and ensure the new system time is greater.
1169 if (vcpu->hv_clock.tsc_timestamp && vcpu->last_guest_tsc) {
1170 max_kernel_ns = vcpu->last_guest_tsc -
1171 vcpu->hv_clock.tsc_timestamp;
1172 max_kernel_ns = pvclock_scale_delta(max_kernel_ns,
1173 vcpu->hv_clock.tsc_to_system_mul,
1174 vcpu->hv_clock.tsc_shift);
1175 max_kernel_ns += vcpu->last_kernel_ns;
1178 if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
1179 kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
1180 &vcpu->hv_clock.tsc_shift,
1181 &vcpu->hv_clock.tsc_to_system_mul);
1182 vcpu->hw_tsc_khz = this_tsc_khz;
1185 if (max_kernel_ns > kernel_ns)
1186 kernel_ns = max_kernel_ns;
1188 /* With all the info we got, fill in the values */
1189 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1190 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1191 vcpu->last_kernel_ns = kernel_ns;
1192 vcpu->last_guest_tsc = tsc_timestamp;
1193 vcpu->hv_clock.flags = 0;
1196 * The interface expects us to write an even number signaling that the
1197 * update is finished. Since the guest won't see the intermediate
1198 * state, we just increase by 2 at the end.
1200 vcpu->hv_clock.version += 2;
1202 shared_kaddr = kmap_atomic(vcpu->time_page, KM_USER0);
1204 memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
1205 sizeof(vcpu->hv_clock));
1207 kunmap_atomic(shared_kaddr, KM_USER0);
1209 mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
1213 static bool msr_mtrr_valid(unsigned msr)
1216 case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
1217 case MSR_MTRRfix64K_00000:
1218 case MSR_MTRRfix16K_80000:
1219 case MSR_MTRRfix16K_A0000:
1220 case MSR_MTRRfix4K_C0000:
1221 case MSR_MTRRfix4K_C8000:
1222 case MSR_MTRRfix4K_D0000:
1223 case MSR_MTRRfix4K_D8000:
1224 case MSR_MTRRfix4K_E0000:
1225 case MSR_MTRRfix4K_E8000:
1226 case MSR_MTRRfix4K_F0000:
1227 case MSR_MTRRfix4K_F8000:
1228 case MSR_MTRRdefType:
1229 case MSR_IA32_CR_PAT:
1237 static bool valid_pat_type(unsigned t)
1239 return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
1242 static bool valid_mtrr_type(unsigned t)
1244 return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
1247 static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1251 if (!msr_mtrr_valid(msr))
1254 if (msr == MSR_IA32_CR_PAT) {
1255 for (i = 0; i < 8; i++)
1256 if (!valid_pat_type((data >> (i * 8)) & 0xff))
1259 } else if (msr == MSR_MTRRdefType) {
1262 return valid_mtrr_type(data & 0xff);
1263 } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
1264 for (i = 0; i < 8 ; i++)
1265 if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
1270 /* variable MTRRs */
1271 return valid_mtrr_type(data & 0xff);
1274 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1276 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1278 if (!mtrr_valid(vcpu, msr, data))
1281 if (msr == MSR_MTRRdefType) {
1282 vcpu->arch.mtrr_state.def_type = data;
1283 vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
1284 } else if (msr == MSR_MTRRfix64K_00000)
1286 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1287 p[1 + msr - MSR_MTRRfix16K_80000] = data;
1288 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1289 p[3 + msr - MSR_MTRRfix4K_C0000] = data;
1290 else if (msr == MSR_IA32_CR_PAT)
1291 vcpu->arch.pat = data;
1292 else { /* Variable MTRRs */
1293 int idx, is_mtrr_mask;
1296 idx = (msr - 0x200) / 2;
1297 is_mtrr_mask = msr - 0x200 - 2 * idx;
1300 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1303 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1307 kvm_mmu_reset_context(vcpu);
1311 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1313 u64 mcg_cap = vcpu->arch.mcg_cap;
1314 unsigned bank_num = mcg_cap & 0xff;
1317 case MSR_IA32_MCG_STATUS:
1318 vcpu->arch.mcg_status = data;
1320 case MSR_IA32_MCG_CTL:
1321 if (!(mcg_cap & MCG_CTL_P))
1323 if (data != 0 && data != ~(u64)0)
1325 vcpu->arch.mcg_ctl = data;
1328 if (msr >= MSR_IA32_MC0_CTL &&
1329 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1330 u32 offset = msr - MSR_IA32_MC0_CTL;
1331 /* only 0 or all 1s can be written to IA32_MCi_CTL
1332 * some Linux kernels though clear bit 10 in bank 4 to
1333 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
1334 * this to avoid an uncatched #GP in the guest
1336 if ((offset & 0x3) == 0 &&
1337 data != 0 && (data | (1 << 10)) != ~(u64)0)
1339 vcpu->arch.mce_banks[offset] = data;
1347 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
1349 struct kvm *kvm = vcpu->kvm;
1350 int lm = is_long_mode(vcpu);
1351 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
1352 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
1353 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
1354 : kvm->arch.xen_hvm_config.blob_size_32;
1355 u32 page_num = data & ~PAGE_MASK;
1356 u64 page_addr = data & PAGE_MASK;
1361 if (page_num >= blob_size)
1364 page = kzalloc(PAGE_SIZE, GFP_KERNEL);
1368 if (copy_from_user(page, blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE))
1370 if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
1379 static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
1381 return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
1384 static bool kvm_hv_msr_partition_wide(u32 msr)
1388 case HV_X64_MSR_GUEST_OS_ID:
1389 case HV_X64_MSR_HYPERCALL:
1397 static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1399 struct kvm *kvm = vcpu->kvm;
1402 case HV_X64_MSR_GUEST_OS_ID:
1403 kvm->arch.hv_guest_os_id = data;
1404 /* setting guest os id to zero disables hypercall page */
1405 if (!kvm->arch.hv_guest_os_id)
1406 kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
1408 case HV_X64_MSR_HYPERCALL: {
1413 /* if guest os id is not set hypercall should remain disabled */
1414 if (!kvm->arch.hv_guest_os_id)
1416 if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
1417 kvm->arch.hv_hypercall = data;
1420 gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
1421 addr = gfn_to_hva(kvm, gfn);
1422 if (kvm_is_error_hva(addr))
1424 kvm_x86_ops->patch_hypercall(vcpu, instructions);
1425 ((unsigned char *)instructions)[3] = 0xc3; /* ret */
1426 if (__copy_to_user((void __user *)addr, instructions, 4))
1428 kvm->arch.hv_hypercall = data;
1432 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1433 "data 0x%llx\n", msr, data);
1439 static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1442 case HV_X64_MSR_APIC_ASSIST_PAGE: {
1445 if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
1446 vcpu->arch.hv_vapic = data;
1449 addr = gfn_to_hva(vcpu->kvm, data >>
1450 HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
1451 if (kvm_is_error_hva(addr))
1453 if (__clear_user((void __user *)addr, PAGE_SIZE))
1455 vcpu->arch.hv_vapic = data;
1458 case HV_X64_MSR_EOI:
1459 return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
1460 case HV_X64_MSR_ICR:
1461 return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
1462 case HV_X64_MSR_TPR:
1463 return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
1465 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1466 "data 0x%llx\n", msr, data);
1473 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
1475 gpa_t gpa = data & ~0x3f;
1477 /* Bits 2:5 are resrved, Should be zero */
1481 vcpu->arch.apf.msr_val = data;
1483 if (!(data & KVM_ASYNC_PF_ENABLED)) {
1484 kvm_clear_async_pf_completion_queue(vcpu);
1485 kvm_async_pf_hash_reset(vcpu);
1489 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa))
1492 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
1493 kvm_async_pf_wakeup_all(vcpu);
1497 static void kvmclock_reset(struct kvm_vcpu *vcpu)
1499 if (vcpu->arch.time_page) {
1500 kvm_release_page_dirty(vcpu->arch.time_page);
1501 vcpu->arch.time_page = NULL;
1505 static void accumulate_steal_time(struct kvm_vcpu *vcpu)
1509 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1512 delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
1513 vcpu->arch.st.last_steal = current->sched_info.run_delay;
1514 vcpu->arch.st.accum_steal = delta;
1517 static void record_steal_time(struct kvm_vcpu *vcpu)
1519 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1522 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1523 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
1526 vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
1527 vcpu->arch.st.steal.version += 2;
1528 vcpu->arch.st.accum_steal = 0;
1530 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1531 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
1534 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1538 return set_efer(vcpu, data);
1540 data &= ~(u64)0x40; /* ignore flush filter disable */
1541 data &= ~(u64)0x100; /* ignore ignne emulation enable */
1543 pr_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
1548 case MSR_FAM10H_MMIO_CONF_BASE:
1550 pr_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
1555 case MSR_AMD64_NB_CFG:
1557 case MSR_IA32_DEBUGCTLMSR:
1559 /* We support the non-activated case already */
1561 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
1562 /* Values other than LBR and BTF are vendor-specific,
1563 thus reserved and should throw a #GP */
1566 pr_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
1569 case MSR_IA32_UCODE_REV:
1570 case MSR_IA32_UCODE_WRITE:
1571 case MSR_VM_HSAVE_PA:
1572 case MSR_AMD64_PATCH_LOADER:
1574 case 0x200 ... 0x2ff:
1575 return set_msr_mtrr(vcpu, msr, data);
1576 case MSR_IA32_APICBASE:
1577 kvm_set_apic_base(vcpu, data);
1579 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1580 return kvm_x2apic_msr_write(vcpu, msr, data);
1581 case MSR_IA32_TSCDEADLINE:
1582 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1584 case MSR_IA32_MISC_ENABLE:
1585 vcpu->arch.ia32_misc_enable_msr = data;
1587 case MSR_KVM_WALL_CLOCK_NEW:
1588 case MSR_KVM_WALL_CLOCK:
1589 vcpu->kvm->arch.wall_clock = data;
1590 kvm_write_wall_clock(vcpu->kvm, data);
1592 case MSR_KVM_SYSTEM_TIME_NEW:
1593 case MSR_KVM_SYSTEM_TIME: {
1594 kvmclock_reset(vcpu);
1596 vcpu->arch.time = data;
1597 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1599 /* we verify if the enable bit is set... */
1603 /* ...but clean it before doing the actual write */
1604 vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
1606 /* Check that the address is 32-byte aligned. */
1607 if (vcpu->arch.time_offset &
1608 (sizeof(struct pvclock_vcpu_time_info) - 1))
1611 vcpu->arch.time_page =
1612 gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
1614 if (is_error_page(vcpu->arch.time_page)) {
1615 kvm_release_page_clean(vcpu->arch.time_page);
1616 vcpu->arch.time_page = NULL;
1620 case MSR_KVM_ASYNC_PF_EN:
1621 if (kvm_pv_enable_async_pf(vcpu, data))
1624 case MSR_KVM_STEAL_TIME:
1626 if (unlikely(!sched_info_on()))
1629 if (data & KVM_STEAL_RESERVED_MASK)
1632 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
1633 data & KVM_STEAL_VALID_BITS))
1636 vcpu->arch.st.msr_val = data;
1638 if (!(data & KVM_MSR_ENABLED))
1641 vcpu->arch.st.last_steal = current->sched_info.run_delay;
1644 accumulate_steal_time(vcpu);
1647 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
1651 case MSR_IA32_MCG_CTL:
1652 case MSR_IA32_MCG_STATUS:
1653 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1654 return set_msr_mce(vcpu, msr, data);
1656 /* Performance counters are not protected by a CPUID bit,
1657 * so we should check all of them in the generic path for the sake of
1658 * cross vendor migration.
1659 * Writing a zero into the event select MSRs disables them,
1660 * which we perfectly emulate ;-). Any other value should be at least
1661 * reported, some guests depend on them.
1663 case MSR_P6_EVNTSEL0:
1664 case MSR_P6_EVNTSEL1:
1665 case MSR_K7_EVNTSEL0:
1666 case MSR_K7_EVNTSEL1:
1667 case MSR_K7_EVNTSEL2:
1668 case MSR_K7_EVNTSEL3:
1670 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1671 "0x%x data 0x%llx\n", msr, data);
1673 /* at least RHEL 4 unconditionally writes to the perfctr registers,
1674 * so we ignore writes to make it happy.
1676 case MSR_P6_PERFCTR0:
1677 case MSR_P6_PERFCTR1:
1678 case MSR_K7_PERFCTR0:
1679 case MSR_K7_PERFCTR1:
1680 case MSR_K7_PERFCTR2:
1681 case MSR_K7_PERFCTR3:
1682 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1683 "0x%x data 0x%llx\n", msr, data);
1685 case MSR_K7_CLK_CTL:
1687 * Ignore all writes to this no longer documented MSR.
1688 * Writes are only relevant for old K7 processors,
1689 * all pre-dating SVM, but a recommended workaround from
1690 * AMD for these chips. It is possible to speicify the
1691 * affected processor models on the command line, hence
1692 * the need to ignore the workaround.
1695 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1696 if (kvm_hv_msr_partition_wide(msr)) {
1698 mutex_lock(&vcpu->kvm->lock);
1699 r = set_msr_hyperv_pw(vcpu, msr, data);
1700 mutex_unlock(&vcpu->kvm->lock);
1703 return set_msr_hyperv(vcpu, msr, data);
1705 case MSR_IA32_BBL_CR_CTL3:
1706 /* Drop writes to this legacy MSR -- see rdmsr
1707 * counterpart for further detail.
1709 pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
1712 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
1713 return xen_hvm_config(vcpu, data);
1715 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
1719 pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
1726 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
1730 * Reads an msr value (of 'msr_index') into 'pdata'.
1731 * Returns 0 on success, non-0 otherwise.
1732 * Assumes vcpu_load() was already called.
1734 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1736 return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
1739 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1741 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1743 if (!msr_mtrr_valid(msr))
1746 if (msr == MSR_MTRRdefType)
1747 *pdata = vcpu->arch.mtrr_state.def_type +
1748 (vcpu->arch.mtrr_state.enabled << 10);
1749 else if (msr == MSR_MTRRfix64K_00000)
1751 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1752 *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
1753 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1754 *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
1755 else if (msr == MSR_IA32_CR_PAT)
1756 *pdata = vcpu->arch.pat;
1757 else { /* Variable MTRRs */
1758 int idx, is_mtrr_mask;
1761 idx = (msr - 0x200) / 2;
1762 is_mtrr_mask = msr - 0x200 - 2 * idx;
1765 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1768 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1775 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1778 u64 mcg_cap = vcpu->arch.mcg_cap;
1779 unsigned bank_num = mcg_cap & 0xff;
1782 case MSR_IA32_P5_MC_ADDR:
1783 case MSR_IA32_P5_MC_TYPE:
1786 case MSR_IA32_MCG_CAP:
1787 data = vcpu->arch.mcg_cap;
1789 case MSR_IA32_MCG_CTL:
1790 if (!(mcg_cap & MCG_CTL_P))
1792 data = vcpu->arch.mcg_ctl;
1794 case MSR_IA32_MCG_STATUS:
1795 data = vcpu->arch.mcg_status;
1798 if (msr >= MSR_IA32_MC0_CTL &&
1799 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1800 u32 offset = msr - MSR_IA32_MC0_CTL;
1801 data = vcpu->arch.mce_banks[offset];
1810 static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1813 struct kvm *kvm = vcpu->kvm;
1816 case HV_X64_MSR_GUEST_OS_ID:
1817 data = kvm->arch.hv_guest_os_id;
1819 case HV_X64_MSR_HYPERCALL:
1820 data = kvm->arch.hv_hypercall;
1823 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1831 static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1836 case HV_X64_MSR_VP_INDEX: {
1839 kvm_for_each_vcpu(r, v, vcpu->kvm)
1844 case HV_X64_MSR_EOI:
1845 return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
1846 case HV_X64_MSR_ICR:
1847 return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
1848 case HV_X64_MSR_TPR:
1849 return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
1850 case HV_X64_MSR_APIC_ASSIST_PAGE:
1851 data = vcpu->arch.hv_vapic;
1854 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1861 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1866 case MSR_IA32_PLATFORM_ID:
1867 case MSR_IA32_EBL_CR_POWERON:
1868 case MSR_IA32_DEBUGCTLMSR:
1869 case MSR_IA32_LASTBRANCHFROMIP:
1870 case MSR_IA32_LASTBRANCHTOIP:
1871 case MSR_IA32_LASTINTFROMIP:
1872 case MSR_IA32_LASTINTTOIP:
1875 case MSR_VM_HSAVE_PA:
1876 case MSR_P6_PERFCTR0:
1877 case MSR_P6_PERFCTR1:
1878 case MSR_P6_EVNTSEL0:
1879 case MSR_P6_EVNTSEL1:
1880 case MSR_K7_EVNTSEL0:
1881 case MSR_K7_PERFCTR0:
1882 case MSR_K8_INT_PENDING_MSG:
1883 case MSR_AMD64_NB_CFG:
1884 case MSR_FAM10H_MMIO_CONF_BASE:
1887 case MSR_IA32_UCODE_REV:
1888 data = 0x100000000ULL;
1891 data = 0x500 | KVM_NR_VAR_MTRR;
1893 case 0x200 ... 0x2ff:
1894 return get_msr_mtrr(vcpu, msr, pdata);
1895 case 0xcd: /* fsb frequency */
1899 * MSR_EBC_FREQUENCY_ID
1900 * Conservative value valid for even the basic CPU models.
1901 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
1902 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
1903 * and 266MHz for model 3, or 4. Set Core Clock
1904 * Frequency to System Bus Frequency Ratio to 1 (bits
1905 * 31:24) even though these are only valid for CPU
1906 * models > 2, however guests may end up dividing or
1907 * multiplying by zero otherwise.
1909 case MSR_EBC_FREQUENCY_ID:
1912 case MSR_IA32_APICBASE:
1913 data = kvm_get_apic_base(vcpu);
1915 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1916 return kvm_x2apic_msr_read(vcpu, msr, pdata);
1918 case MSR_IA32_TSCDEADLINE:
1919 data = kvm_get_lapic_tscdeadline_msr(vcpu);
1921 case MSR_IA32_MISC_ENABLE:
1922 data = vcpu->arch.ia32_misc_enable_msr;
1924 case MSR_IA32_PERF_STATUS:
1925 /* TSC increment by tick */
1927 /* CPU multiplier */
1928 data |= (((uint64_t)4ULL) << 40);
1931 data = vcpu->arch.efer;
1933 case MSR_KVM_WALL_CLOCK:
1934 case MSR_KVM_WALL_CLOCK_NEW:
1935 data = vcpu->kvm->arch.wall_clock;
1937 case MSR_KVM_SYSTEM_TIME:
1938 case MSR_KVM_SYSTEM_TIME_NEW:
1939 data = vcpu->arch.time;
1941 case MSR_KVM_ASYNC_PF_EN:
1942 data = vcpu->arch.apf.msr_val;
1944 case MSR_KVM_STEAL_TIME:
1945 data = vcpu->arch.st.msr_val;
1947 case MSR_IA32_P5_MC_ADDR:
1948 case MSR_IA32_P5_MC_TYPE:
1949 case MSR_IA32_MCG_CAP:
1950 case MSR_IA32_MCG_CTL:
1951 case MSR_IA32_MCG_STATUS:
1952 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1953 return get_msr_mce(vcpu, msr, pdata);
1954 case MSR_K7_CLK_CTL:
1956 * Provide expected ramp-up count for K7. All other
1957 * are set to zero, indicating minimum divisors for
1960 * This prevents guest kernels on AMD host with CPU
1961 * type 6, model 8 and higher from exploding due to
1962 * the rdmsr failing.
1966 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1967 if (kvm_hv_msr_partition_wide(msr)) {
1969 mutex_lock(&vcpu->kvm->lock);
1970 r = get_msr_hyperv_pw(vcpu, msr, pdata);
1971 mutex_unlock(&vcpu->kvm->lock);
1974 return get_msr_hyperv(vcpu, msr, pdata);
1976 case MSR_IA32_BBL_CR_CTL3:
1977 /* This legacy MSR exists but isn't fully documented in current
1978 * silicon. It is however accessed by winxp in very narrow
1979 * scenarios where it sets bit #19, itself documented as
1980 * a "reserved" bit. Best effort attempt to source coherent
1981 * read data here should the balance of the register be
1982 * interpreted by the guest:
1984 * L2 cache control register 3: 64GB range, 256KB size,
1985 * enabled, latency 0x1, configured
1991 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
1994 pr_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
2002 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2005 * Read or write a bunch of msrs. All parameters are kernel addresses.
2007 * @return number of msrs set successfully.
2009 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2010 struct kvm_msr_entry *entries,
2011 int (*do_msr)(struct kvm_vcpu *vcpu,
2012 unsigned index, u64 *data))
2016 idx = srcu_read_lock(&vcpu->kvm->srcu);
2017 for (i = 0; i < msrs->nmsrs; ++i)
2018 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2020 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2026 * Read or write a bunch of msrs. Parameters are user addresses.
2028 * @return number of msrs set successfully.
2030 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2031 int (*do_msr)(struct kvm_vcpu *vcpu,
2032 unsigned index, u64 *data),
2035 struct kvm_msrs msrs;
2036 struct kvm_msr_entry *entries;
2041 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2045 if (msrs.nmsrs >= MAX_IO_MSRS)
2049 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2050 entries = kmalloc(size, GFP_KERNEL);
2055 if (copy_from_user(entries, user_msrs->entries, size))
2058 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2063 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2074 int kvm_dev_ioctl_check_extension(long ext)
2079 case KVM_CAP_IRQCHIP:
2081 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2082 case KVM_CAP_SET_TSS_ADDR:
2083 case KVM_CAP_EXT_CPUID:
2084 case KVM_CAP_CLOCKSOURCE:
2086 case KVM_CAP_NOP_IO_DELAY:
2087 case KVM_CAP_MP_STATE:
2088 case KVM_CAP_SYNC_MMU:
2089 case KVM_CAP_USER_NMI:
2090 case KVM_CAP_REINJECT_CONTROL:
2091 case KVM_CAP_IRQ_INJECT_STATUS:
2092 case KVM_CAP_ASSIGN_DEV_IRQ:
2094 case KVM_CAP_IOEVENTFD:
2096 case KVM_CAP_PIT_STATE2:
2097 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2098 case KVM_CAP_XEN_HVM:
2099 case KVM_CAP_ADJUST_CLOCK:
2100 case KVM_CAP_VCPU_EVENTS:
2101 case KVM_CAP_HYPERV:
2102 case KVM_CAP_HYPERV_VAPIC:
2103 case KVM_CAP_HYPERV_SPIN:
2104 case KVM_CAP_PCI_SEGMENT:
2105 case KVM_CAP_DEBUGREGS:
2106 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2108 case KVM_CAP_ASYNC_PF:
2109 case KVM_CAP_GET_TSC_KHZ:
2112 case KVM_CAP_COALESCED_MMIO:
2113 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2116 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2118 case KVM_CAP_NR_VCPUS:
2119 r = KVM_SOFT_MAX_VCPUS;
2121 case KVM_CAP_MAX_VCPUS:
2124 case KVM_CAP_NR_MEMSLOTS:
2125 r = KVM_MEMORY_SLOTS;
2127 case KVM_CAP_PV_MMU: /* obsolete */
2131 r = iommu_present(&pci_bus_type);
2134 r = KVM_MAX_MCE_BANKS;
2139 case KVM_CAP_TSC_CONTROL:
2140 r = kvm_has_tsc_control;
2142 case KVM_CAP_TSC_DEADLINE_TIMER:
2143 r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
2153 long kvm_arch_dev_ioctl(struct file *filp,
2154 unsigned int ioctl, unsigned long arg)
2156 void __user *argp = (void __user *)arg;
2160 case KVM_GET_MSR_INDEX_LIST: {
2161 struct kvm_msr_list __user *user_msr_list = argp;
2162 struct kvm_msr_list msr_list;
2166 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2169 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
2170 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2173 if (n < msr_list.nmsrs)
2176 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2177 num_msrs_to_save * sizeof(u32)))
2179 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2181 ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
2186 case KVM_GET_SUPPORTED_CPUID: {
2187 struct kvm_cpuid2 __user *cpuid_arg = argp;
2188 struct kvm_cpuid2 cpuid;
2191 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2193 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
2194 cpuid_arg->entries);
2199 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2204 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2207 mce_cap = KVM_MCE_CAP_SUPPORTED;
2209 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2221 static void wbinvd_ipi(void *garbage)
2226 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2228 return vcpu->kvm->arch.iommu_domain &&
2229 !(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY);
2232 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2234 /* Address WBINVD may be executed by guest */
2235 if (need_emulate_wbinvd(vcpu)) {
2236 if (kvm_x86_ops->has_wbinvd_exit())
2237 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2238 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2239 smp_call_function_single(vcpu->cpu,
2240 wbinvd_ipi, NULL, 1);
2243 kvm_x86_ops->vcpu_load(vcpu, cpu);
2244 if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2245 /* Make sure TSC doesn't go backwards */
2249 tsc = kvm_x86_ops->read_l1_tsc(vcpu);
2250 tsc_delta = !vcpu->arch.last_guest_tsc ? 0 :
2251 tsc - vcpu->arch.last_guest_tsc;
2254 mark_tsc_unstable("KVM discovered backwards TSC");
2255 if (check_tsc_unstable()) {
2256 kvm_x86_ops->adjust_tsc_offset(vcpu, -tsc_delta);
2257 vcpu->arch.tsc_catchup = 1;
2259 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2260 if (vcpu->cpu != cpu)
2261 kvm_migrate_timers(vcpu);
2265 accumulate_steal_time(vcpu);
2266 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2269 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2271 kvm_x86_ops->vcpu_put(vcpu);
2272 kvm_put_guest_fpu(vcpu);
2273 vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu);
2276 static int is_efer_nx(void)
2278 unsigned long long efer = 0;
2280 rdmsrl_safe(MSR_EFER, &efer);
2281 return efer & EFER_NX;
2284 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
2287 struct kvm_cpuid_entry2 *e, *entry;
2290 for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
2291 e = &vcpu->arch.cpuid_entries[i];
2292 if (e->function == 0x80000001) {
2297 if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
2298 entry->edx &= ~(1 << 20);
2299 printk(KERN_INFO "kvm: guest NX capability removed\n");
2303 /* when an old userspace process fills a new kernel module */
2304 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
2305 struct kvm_cpuid *cpuid,
2306 struct kvm_cpuid_entry __user *entries)
2309 struct kvm_cpuid_entry *cpuid_entries;
2312 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2315 cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
2319 if (copy_from_user(cpuid_entries, entries,
2320 cpuid->nent * sizeof(struct kvm_cpuid_entry)))
2322 for (i = 0; i < cpuid->nent; i++) {
2323 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
2324 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
2325 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
2326 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
2327 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
2328 vcpu->arch.cpuid_entries[i].index = 0;
2329 vcpu->arch.cpuid_entries[i].flags = 0;
2330 vcpu->arch.cpuid_entries[i].padding[0] = 0;
2331 vcpu->arch.cpuid_entries[i].padding[1] = 0;
2332 vcpu->arch.cpuid_entries[i].padding[2] = 0;
2334 vcpu->arch.cpuid_nent = cpuid->nent;
2335 cpuid_fix_nx_cap(vcpu);
2337 kvm_apic_set_version(vcpu);
2338 kvm_x86_ops->cpuid_update(vcpu);
2342 vfree(cpuid_entries);
2347 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
2348 struct kvm_cpuid2 *cpuid,
2349 struct kvm_cpuid_entry2 __user *entries)
2354 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2357 if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
2358 cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
2360 vcpu->arch.cpuid_nent = cpuid->nent;
2361 kvm_apic_set_version(vcpu);
2362 kvm_x86_ops->cpuid_update(vcpu);
2370 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
2371 struct kvm_cpuid2 *cpuid,
2372 struct kvm_cpuid_entry2 __user *entries)
2377 if (cpuid->nent < vcpu->arch.cpuid_nent)
2380 if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
2381 vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
2386 cpuid->nent = vcpu->arch.cpuid_nent;
2390 static void cpuid_mask(u32 *word, int wordnum)
2392 *word &= boot_cpu_data.x86_capability[wordnum];
2395 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
2398 entry->function = function;
2399 entry->index = index;
2400 cpuid_count(entry->function, entry->index,
2401 &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
2405 static bool supported_xcr0_bit(unsigned bit)
2407 u64 mask = ((u64)1 << bit);
2409 return mask & (XSTATE_FP | XSTATE_SSE | XSTATE_YMM) & host_xcr0;
2412 #define F(x) bit(X86_FEATURE_##x)
2414 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
2415 u32 index, int *nent, int maxnent)
2417 unsigned f_nx = is_efer_nx() ? F(NX) : 0;
2418 #ifdef CONFIG_X86_64
2419 unsigned f_gbpages = (kvm_x86_ops->get_lpage_level() == PT_PDPE_LEVEL)
2421 unsigned f_lm = F(LM);
2423 unsigned f_gbpages = 0;
2426 unsigned f_rdtscp = kvm_x86_ops->rdtscp_supported() ? F(RDTSCP) : 0;
2429 const u32 kvm_supported_word0_x86_features =
2430 F(FPU) | F(VME) | F(DE) | F(PSE) |
2431 F(TSC) | F(MSR) | F(PAE) | F(MCE) |
2432 F(CX8) | F(APIC) | 0 /* Reserved */ | F(SEP) |
2433 F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
2434 F(PAT) | F(PSE36) | 0 /* PSN */ | F(CLFLSH) |
2435 0 /* Reserved, DS, ACPI */ | F(MMX) |
2436 F(FXSR) | F(XMM) | F(XMM2) | F(SELFSNOOP) |
2437 0 /* HTT, TM, Reserved, PBE */;
2438 /* cpuid 0x80000001.edx */
2439 const u32 kvm_supported_word1_x86_features =
2440 F(FPU) | F(VME) | F(DE) | F(PSE) |
2441 F(TSC) | F(MSR) | F(PAE) | F(MCE) |
2442 F(CX8) | F(APIC) | 0 /* Reserved */ | F(SYSCALL) |
2443 F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
2444 F(PAT) | F(PSE36) | 0 /* Reserved */ |
2445 f_nx | 0 /* Reserved */ | F(MMXEXT) | F(MMX) |
2446 F(FXSR) | F(FXSR_OPT) | f_gbpages | f_rdtscp |
2447 0 /* Reserved */ | f_lm | F(3DNOWEXT) | F(3DNOW);
2449 const u32 kvm_supported_word4_x86_features =
2450 F(XMM3) | F(PCLMULQDQ) | 0 /* DTES64, MONITOR */ |
2451 0 /* DS-CPL, VMX, SMX, EST */ |
2452 0 /* TM2 */ | F(SSSE3) | 0 /* CNXT-ID */ | 0 /* Reserved */ |
2453 0 /* Reserved */ | F(CX16) | 0 /* xTPR Update, PDCM */ |
2454 0 /* Reserved, DCA */ | F(XMM4_1) |
2455 F(XMM4_2) | F(X2APIC) | F(MOVBE) | F(POPCNT) |
2456 0 /* Reserved*/ | F(AES) | F(XSAVE) | 0 /* OSXSAVE */ | F(AVX) |
2457 F(F16C) | F(RDRAND);
2458 /* cpuid 0x80000001.ecx */
2459 const u32 kvm_supported_word6_x86_features =
2460 F(LAHF_LM) | F(CMP_LEGACY) | 0 /*SVM*/ | 0 /* ExtApicSpace */ |
2461 F(CR8_LEGACY) | F(ABM) | F(SSE4A) | F(MISALIGNSSE) |
2462 F(3DNOWPREFETCH) | 0 /* OSVW */ | 0 /* IBS */ | F(XOP) |
2463 0 /* SKINIT, WDT, LWP */ | F(FMA4) | F(TBM);
2465 /* cpuid 0xC0000001.edx */
2466 const u32 kvm_supported_word5_x86_features =
2467 F(XSTORE) | F(XSTORE_EN) | F(XCRYPT) | F(XCRYPT_EN) |
2468 F(ACE2) | F(ACE2_EN) | F(PHE) | F(PHE_EN) |
2472 const u32 kvm_supported_word9_x86_features =
2473 F(SMEP) | F(FSGSBASE) | F(ERMS);
2475 /* all calls to cpuid_count() should be made on the same cpu */
2477 do_cpuid_1_ent(entry, function, index);
2482 entry->eax = min(entry->eax, (u32)0xd);
2485 entry->edx &= kvm_supported_word0_x86_features;
2486 cpuid_mask(&entry->edx, 0);
2487 entry->ecx &= kvm_supported_word4_x86_features;
2488 cpuid_mask(&entry->ecx, 4);
2489 /* we support x2apic emulation even if host does not support
2490 * it since we emulate x2apic in software */
2491 entry->ecx |= F(X2APIC);
2493 /* function 2 entries are STATEFUL. That is, repeated cpuid commands
2494 * may return different values. This forces us to get_cpu() before
2495 * issuing the first command, and also to emulate this annoying behavior
2496 * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
2498 int t, times = entry->eax & 0xff;
2500 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
2501 entry->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
2502 for (t = 1; t < times && *nent < maxnent; ++t) {
2503 do_cpuid_1_ent(&entry[t], function, 0);
2504 entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
2509 /* function 4 has additional index. */
2513 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2514 /* read more entries until cache_type is zero */
2515 for (i = 1; *nent < maxnent; ++i) {
2516 cache_type = entry[i - 1].eax & 0x1f;
2519 do_cpuid_1_ent(&entry[i], function, i);
2521 KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2527 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2528 /* Mask ebx against host capbability word 9 */
2530 entry->ebx &= kvm_supported_word9_x86_features;
2531 cpuid_mask(&entry->ebx, 9);
2541 /* function 0xb has additional index. */
2545 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2546 /* read more entries until level_type is zero */
2547 for (i = 1; *nent < maxnent; ++i) {
2548 level_type = entry[i - 1].ecx & 0xff00;
2551 do_cpuid_1_ent(&entry[i], function, i);
2553 KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2561 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2562 for (idx = 1, i = 1; *nent < maxnent && idx < 64; ++idx) {
2563 do_cpuid_1_ent(&entry[i], function, idx);
2564 if (entry[i].eax == 0 || !supported_xcr0_bit(idx))
2567 KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2573 case KVM_CPUID_SIGNATURE: {
2574 char signature[12] = "KVMKVMKVM\0\0";
2575 u32 *sigptr = (u32 *)signature;
2577 entry->ebx = sigptr[0];
2578 entry->ecx = sigptr[1];
2579 entry->edx = sigptr[2];
2582 case KVM_CPUID_FEATURES:
2583 entry->eax = (1 << KVM_FEATURE_CLOCKSOURCE) |
2584 (1 << KVM_FEATURE_NOP_IO_DELAY) |
2585 (1 << KVM_FEATURE_CLOCKSOURCE2) |
2586 (1 << KVM_FEATURE_ASYNC_PF) |
2587 (1 << KVM_FEATURE_CLOCKSOURCE_STABLE_BIT);
2589 if (sched_info_on())
2590 entry->eax |= (1 << KVM_FEATURE_STEAL_TIME);
2597 entry->eax = min(entry->eax, 0x8000001a);
2600 entry->edx &= kvm_supported_word1_x86_features;
2601 cpuid_mask(&entry->edx, 1);
2602 entry->ecx &= kvm_supported_word6_x86_features;
2603 cpuid_mask(&entry->ecx, 6);
2606 unsigned g_phys_as = (entry->eax >> 16) & 0xff;
2607 unsigned virt_as = max((entry->eax >> 8) & 0xff, 48U);
2608 unsigned phys_as = entry->eax & 0xff;
2611 g_phys_as = phys_as;
2612 entry->eax = g_phys_as | (virt_as << 8);
2613 entry->ebx = entry->edx = 0;
2617 entry->ecx = entry->edx = 0;
2623 /*Add support for Centaur's CPUID instruction*/
2625 /*Just support up to 0xC0000004 now*/
2626 entry->eax = min(entry->eax, 0xC0000004);
2629 entry->edx &= kvm_supported_word5_x86_features;
2630 cpuid_mask(&entry->edx, 5);
2632 case 3: /* Processor serial number */
2633 case 5: /* MONITOR/MWAIT */
2634 case 6: /* Thermal management */
2635 case 0xA: /* Architectural Performance Monitoring */
2636 case 0x80000007: /* Advanced power management */
2641 entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
2645 kvm_x86_ops->set_supported_cpuid(function, entry);
2652 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
2653 struct kvm_cpuid_entry2 __user *entries)
2655 struct kvm_cpuid_entry2 *cpuid_entries;
2656 int limit, nent = 0, r = -E2BIG;
2659 if (cpuid->nent < 1)
2661 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2662 cpuid->nent = KVM_MAX_CPUID_ENTRIES;
2664 cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
2668 do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
2669 limit = cpuid_entries[0].eax;
2670 for (func = 1; func <= limit && nent < cpuid->nent; ++func)
2671 do_cpuid_ent(&cpuid_entries[nent], func, 0,
2672 &nent, cpuid->nent);
2674 if (nent >= cpuid->nent)
2677 do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
2678 limit = cpuid_entries[nent - 1].eax;
2679 for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
2680 do_cpuid_ent(&cpuid_entries[nent], func, 0,
2681 &nent, cpuid->nent);
2686 if (nent >= cpuid->nent)
2689 /* Add support for Centaur's CPUID instruction. */
2690 if (boot_cpu_data.x86_vendor == X86_VENDOR_CENTAUR) {
2691 do_cpuid_ent(&cpuid_entries[nent], 0xC0000000, 0,
2692 &nent, cpuid->nent);
2695 if (nent >= cpuid->nent)
2698 limit = cpuid_entries[nent - 1].eax;
2699 for (func = 0xC0000001;
2700 func <= limit && nent < cpuid->nent; ++func)
2701 do_cpuid_ent(&cpuid_entries[nent], func, 0,
2702 &nent, cpuid->nent);
2705 if (nent >= cpuid->nent)
2709 do_cpuid_ent(&cpuid_entries[nent], KVM_CPUID_SIGNATURE, 0, &nent,
2713 if (nent >= cpuid->nent)
2716 do_cpuid_ent(&cpuid_entries[nent], KVM_CPUID_FEATURES, 0, &nent,
2720 if (nent >= cpuid->nent)
2724 if (copy_to_user(entries, cpuid_entries,
2725 nent * sizeof(struct kvm_cpuid_entry2)))
2731 vfree(cpuid_entries);
2736 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2737 struct kvm_lapic_state *s)
2739 memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2744 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2745 struct kvm_lapic_state *s)
2747 memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
2748 kvm_apic_post_state_restore(vcpu);
2749 update_cr8_intercept(vcpu);
2754 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2755 struct kvm_interrupt *irq)
2757 if (irq->irq < 0 || irq->irq >= 256)
2759 if (irqchip_in_kernel(vcpu->kvm))
2762 kvm_queue_interrupt(vcpu, irq->irq, false);
2763 kvm_make_request(KVM_REQ_EVENT, vcpu);
2768 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2770 kvm_inject_nmi(vcpu);
2775 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2776 struct kvm_tpr_access_ctl *tac)
2780 vcpu->arch.tpr_access_reporting = !!tac->enabled;
2784 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2788 unsigned bank_num = mcg_cap & 0xff, bank;
2791 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2793 if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2796 vcpu->arch.mcg_cap = mcg_cap;
2797 /* Init IA32_MCG_CTL to all 1s */
2798 if (mcg_cap & MCG_CTL_P)
2799 vcpu->arch.mcg_ctl = ~(u64)0;
2800 /* Init IA32_MCi_CTL to all 1s */
2801 for (bank = 0; bank < bank_num; bank++)
2802 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2807 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2808 struct kvm_x86_mce *mce)
2810 u64 mcg_cap = vcpu->arch.mcg_cap;
2811 unsigned bank_num = mcg_cap & 0xff;
2812 u64 *banks = vcpu->arch.mce_banks;
2814 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2817 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2818 * reporting is disabled
2820 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2821 vcpu->arch.mcg_ctl != ~(u64)0)
2823 banks += 4 * mce->bank;
2825 * if IA32_MCi_CTL is not all 1s, the uncorrected error
2826 * reporting is disabled for the bank
2828 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2830 if (mce->status & MCI_STATUS_UC) {
2831 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2832 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2833 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2836 if (banks[1] & MCI_STATUS_VAL)
2837 mce->status |= MCI_STATUS_OVER;
2838 banks[2] = mce->addr;
2839 banks[3] = mce->misc;
2840 vcpu->arch.mcg_status = mce->mcg_status;
2841 banks[1] = mce->status;
2842 kvm_queue_exception(vcpu, MC_VECTOR);
2843 } else if (!(banks[1] & MCI_STATUS_VAL)
2844 || !(banks[1] & MCI_STATUS_UC)) {
2845 if (banks[1] & MCI_STATUS_VAL)
2846 mce->status |= MCI_STATUS_OVER;
2847 banks[2] = mce->addr;
2848 banks[3] = mce->misc;
2849 banks[1] = mce->status;
2851 banks[1] |= MCI_STATUS_OVER;
2855 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2856 struct kvm_vcpu_events *events)
2859 events->exception.injected =
2860 vcpu->arch.exception.pending &&
2861 !kvm_exception_is_soft(vcpu->arch.exception.nr);
2862 events->exception.nr = vcpu->arch.exception.nr;
2863 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2864 events->exception.pad = 0;
2865 events->exception.error_code = vcpu->arch.exception.error_code;
2867 events->interrupt.injected =
2868 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
2869 events->interrupt.nr = vcpu->arch.interrupt.nr;
2870 events->interrupt.soft = 0;
2871 events->interrupt.shadow =
2872 kvm_x86_ops->get_interrupt_shadow(vcpu,
2873 KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
2875 events->nmi.injected = vcpu->arch.nmi_injected;
2876 events->nmi.pending = vcpu->arch.nmi_pending != 0;
2877 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
2878 events->nmi.pad = 0;
2880 events->sipi_vector = vcpu->arch.sipi_vector;
2882 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
2883 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2884 | KVM_VCPUEVENT_VALID_SHADOW);
2885 memset(&events->reserved, 0, sizeof(events->reserved));
2888 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
2889 struct kvm_vcpu_events *events)
2891 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
2892 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2893 | KVM_VCPUEVENT_VALID_SHADOW))
2897 vcpu->arch.exception.pending = events->exception.injected;
2898 vcpu->arch.exception.nr = events->exception.nr;
2899 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
2900 vcpu->arch.exception.error_code = events->exception.error_code;
2902 vcpu->arch.interrupt.pending = events->interrupt.injected;
2903 vcpu->arch.interrupt.nr = events->interrupt.nr;
2904 vcpu->arch.interrupt.soft = events->interrupt.soft;
2905 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
2906 kvm_x86_ops->set_interrupt_shadow(vcpu,
2907 events->interrupt.shadow);
2909 vcpu->arch.nmi_injected = events->nmi.injected;
2910 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
2911 vcpu->arch.nmi_pending = events->nmi.pending;
2912 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
2914 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR)
2915 vcpu->arch.sipi_vector = events->sipi_vector;
2917 kvm_make_request(KVM_REQ_EVENT, vcpu);
2922 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
2923 struct kvm_debugregs *dbgregs)
2925 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
2926 dbgregs->dr6 = vcpu->arch.dr6;
2927 dbgregs->dr7 = vcpu->arch.dr7;
2929 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
2932 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
2933 struct kvm_debugregs *dbgregs)
2938 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
2939 vcpu->arch.dr6 = dbgregs->dr6;
2940 vcpu->arch.dr7 = dbgregs->dr7;
2945 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
2946 struct kvm_xsave *guest_xsave)
2949 memcpy(guest_xsave->region,
2950 &vcpu->arch.guest_fpu.state->xsave,
2953 memcpy(guest_xsave->region,
2954 &vcpu->arch.guest_fpu.state->fxsave,
2955 sizeof(struct i387_fxsave_struct));
2956 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
2961 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
2962 struct kvm_xsave *guest_xsave)
2965 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
2968 memcpy(&vcpu->arch.guest_fpu.state->xsave,
2969 guest_xsave->region, xstate_size);
2971 if (xstate_bv & ~XSTATE_FPSSE)
2973 memcpy(&vcpu->arch.guest_fpu.state->fxsave,
2974 guest_xsave->region, sizeof(struct i387_fxsave_struct));
2979 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
2980 struct kvm_xcrs *guest_xcrs)
2982 if (!cpu_has_xsave) {
2983 guest_xcrs->nr_xcrs = 0;
2987 guest_xcrs->nr_xcrs = 1;
2988 guest_xcrs->flags = 0;
2989 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
2990 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
2993 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
2994 struct kvm_xcrs *guest_xcrs)
3001 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3004 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3005 /* Only support XCR0 currently */
3006 if (guest_xcrs->xcrs[0].xcr == XCR_XFEATURE_ENABLED_MASK) {
3007 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3008 guest_xcrs->xcrs[0].value);
3016 long kvm_arch_vcpu_ioctl(struct file *filp,
3017 unsigned int ioctl, unsigned long arg)
3019 struct kvm_vcpu *vcpu = filp->private_data;
3020 void __user *argp = (void __user *)arg;
3023 struct kvm_lapic_state *lapic;
3024 struct kvm_xsave *xsave;
3025 struct kvm_xcrs *xcrs;
3031 case KVM_GET_LAPIC: {
3033 if (!vcpu->arch.apic)
3035 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3040 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3044 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3049 case KVM_SET_LAPIC: {
3051 if (!vcpu->arch.apic)
3053 u.lapic = kmalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3058 if (copy_from_user(u.lapic, argp, sizeof(struct kvm_lapic_state)))
3060 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3066 case KVM_INTERRUPT: {
3067 struct kvm_interrupt irq;
3070 if (copy_from_user(&irq, argp, sizeof irq))
3072 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3079 r = kvm_vcpu_ioctl_nmi(vcpu);
3085 case KVM_SET_CPUID: {
3086 struct kvm_cpuid __user *cpuid_arg = argp;
3087 struct kvm_cpuid cpuid;
3090 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3092 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3097 case KVM_SET_CPUID2: {
3098 struct kvm_cpuid2 __user *cpuid_arg = argp;
3099 struct kvm_cpuid2 cpuid;
3102 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3104 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3105 cpuid_arg->entries);
3110 case KVM_GET_CPUID2: {
3111 struct kvm_cpuid2 __user *cpuid_arg = argp;
3112 struct kvm_cpuid2 cpuid;
3115 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3117 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3118 cpuid_arg->entries);
3122 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3128 r = msr_io(vcpu, argp, kvm_get_msr, 1);
3131 r = msr_io(vcpu, argp, do_set_msr, 0);
3133 case KVM_TPR_ACCESS_REPORTING: {
3134 struct kvm_tpr_access_ctl tac;
3137 if (copy_from_user(&tac, argp, sizeof tac))
3139 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3143 if (copy_to_user(argp, &tac, sizeof tac))
3148 case KVM_SET_VAPIC_ADDR: {
3149 struct kvm_vapic_addr va;
3152 if (!irqchip_in_kernel(vcpu->kvm))
3155 if (copy_from_user(&va, argp, sizeof va))
3158 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3161 case KVM_X86_SETUP_MCE: {
3165 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3167 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3170 case KVM_X86_SET_MCE: {
3171 struct kvm_x86_mce mce;
3174 if (copy_from_user(&mce, argp, sizeof mce))
3176 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3179 case KVM_GET_VCPU_EVENTS: {
3180 struct kvm_vcpu_events events;
3182 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3185 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3190 case KVM_SET_VCPU_EVENTS: {
3191 struct kvm_vcpu_events events;
3194 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3197 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3200 case KVM_GET_DEBUGREGS: {
3201 struct kvm_debugregs dbgregs;
3203 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3206 if (copy_to_user(argp, &dbgregs,
3207 sizeof(struct kvm_debugregs)))
3212 case KVM_SET_DEBUGREGS: {
3213 struct kvm_debugregs dbgregs;
3216 if (copy_from_user(&dbgregs, argp,
3217 sizeof(struct kvm_debugregs)))
3220 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3223 case KVM_GET_XSAVE: {
3224 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3229 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3232 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3237 case KVM_SET_XSAVE: {
3238 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3244 if (copy_from_user(u.xsave, argp, sizeof(struct kvm_xsave)))
3247 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3250 case KVM_GET_XCRS: {
3251 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3256 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3259 if (copy_to_user(argp, u.xcrs,
3260 sizeof(struct kvm_xcrs)))
3265 case KVM_SET_XCRS: {
3266 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3272 if (copy_from_user(u.xcrs, argp,
3273 sizeof(struct kvm_xcrs)))
3276 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3279 case KVM_SET_TSC_KHZ: {
3283 if (!kvm_has_tsc_control)
3286 user_tsc_khz = (u32)arg;
3288 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3291 kvm_x86_ops->set_tsc_khz(vcpu, user_tsc_khz);
3296 case KVM_GET_TSC_KHZ: {
3298 if (check_tsc_unstable())
3301 r = vcpu_tsc_khz(vcpu);
3313 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3317 if (addr > (unsigned int)(-3 * PAGE_SIZE))
3319 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3323 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3326 kvm->arch.ept_identity_map_addr = ident_addr;
3330 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3331 u32 kvm_nr_mmu_pages)
3333 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3336 mutex_lock(&kvm->slots_lock);
3337 spin_lock(&kvm->mmu_lock);
3339 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3340 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3342 spin_unlock(&kvm->mmu_lock);
3343 mutex_unlock(&kvm->slots_lock);
3347 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3349 return kvm->arch.n_max_mmu_pages;
3352 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3357 switch (chip->chip_id) {
3358 case KVM_IRQCHIP_PIC_MASTER:
3359 memcpy(&chip->chip.pic,
3360 &pic_irqchip(kvm)->pics[0],
3361 sizeof(struct kvm_pic_state));
3363 case KVM_IRQCHIP_PIC_SLAVE:
3364 memcpy(&chip->chip.pic,
3365 &pic_irqchip(kvm)->pics[1],
3366 sizeof(struct kvm_pic_state));
3368 case KVM_IRQCHIP_IOAPIC:
3369 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3378 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3383 switch (chip->chip_id) {
3384 case KVM_IRQCHIP_PIC_MASTER:
3385 spin_lock(&pic_irqchip(kvm)->lock);
3386 memcpy(&pic_irqchip(kvm)->pics[0],
3388 sizeof(struct kvm_pic_state));
3389 spin_unlock(&pic_irqchip(kvm)->lock);
3391 case KVM_IRQCHIP_PIC_SLAVE:
3392 spin_lock(&pic_irqchip(kvm)->lock);
3393 memcpy(&pic_irqchip(kvm)->pics[1],
3395 sizeof(struct kvm_pic_state));
3396 spin_unlock(&pic_irqchip(kvm)->lock);
3398 case KVM_IRQCHIP_IOAPIC:
3399 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3405 kvm_pic_update_irq(pic_irqchip(kvm));
3409 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3413 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3414 memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
3415 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3419 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3423 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3424 memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
3425 kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
3426 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3430 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3434 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3435 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3436 sizeof(ps->channels));
3437 ps->flags = kvm->arch.vpit->pit_state.flags;
3438 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3439 memset(&ps->reserved, 0, sizeof(ps->reserved));
3443 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3445 int r = 0, start = 0;
3446 u32 prev_legacy, cur_legacy;
3447 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3448 prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3449 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3450 if (!prev_legacy && cur_legacy)
3452 memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
3453 sizeof(kvm->arch.vpit->pit_state.channels));
3454 kvm->arch.vpit->pit_state.flags = ps->flags;
3455 kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
3456 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3460 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3461 struct kvm_reinject_control *control)
3463 if (!kvm->arch.vpit)
3465 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3466 kvm->arch.vpit->pit_state.pit_timer.reinject = control->pit_reinject;
3467 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3472 * Get (and clear) the dirty memory log for a memory slot.
3474 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
3475 struct kvm_dirty_log *log)
3478 struct kvm_memory_slot *memslot;
3480 unsigned long is_dirty = 0;
3482 mutex_lock(&kvm->slots_lock);
3485 if (log->slot >= KVM_MEMORY_SLOTS)
3488 memslot = &kvm->memslots->memslots[log->slot];
3490 if (!memslot->dirty_bitmap)
3493 n = kvm_dirty_bitmap_bytes(memslot);
3495 for (i = 0; !is_dirty && i < n/sizeof(long); i++)
3496 is_dirty = memslot->dirty_bitmap[i];
3498 /* If nothing is dirty, don't bother messing with page tables. */
3500 struct kvm_memslots *slots, *old_slots;
3501 unsigned long *dirty_bitmap;
3503 dirty_bitmap = memslot->dirty_bitmap_head;
3504 if (memslot->dirty_bitmap == dirty_bitmap)
3505 dirty_bitmap += n / sizeof(long);
3506 memset(dirty_bitmap, 0, n);
3509 slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
3512 memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
3513 slots->memslots[log->slot].dirty_bitmap = dirty_bitmap;
3514 slots->generation++;
3516 old_slots = kvm->memslots;
3517 rcu_assign_pointer(kvm->memslots, slots);
3518 synchronize_srcu_expedited(&kvm->srcu);
3519 dirty_bitmap = old_slots->memslots[log->slot].dirty_bitmap;
3522 spin_lock(&kvm->mmu_lock);
3523 kvm_mmu_slot_remove_write_access(kvm, log->slot);
3524 spin_unlock(&kvm->mmu_lock);
3527 if (copy_to_user(log->dirty_bitmap, dirty_bitmap, n))
3531 if (clear_user(log->dirty_bitmap, n))
3537 mutex_unlock(&kvm->slots_lock);
3541 long kvm_arch_vm_ioctl(struct file *filp,
3542 unsigned int ioctl, unsigned long arg)
3544 struct kvm *kvm = filp->private_data;
3545 void __user *argp = (void __user *)arg;
3548 * This union makes it completely explicit to gcc-3.x
3549 * that these two variables' stack usage should be
3550 * combined, not added together.
3553 struct kvm_pit_state ps;
3554 struct kvm_pit_state2 ps2;
3555 struct kvm_pit_config pit_config;
3559 case KVM_SET_TSS_ADDR:
3560 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3564 case KVM_SET_IDENTITY_MAP_ADDR: {
3568 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3570 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3575 case KVM_SET_NR_MMU_PAGES:
3576 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3580 case KVM_GET_NR_MMU_PAGES:
3581 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3583 case KVM_CREATE_IRQCHIP: {
3584 struct kvm_pic *vpic;
3586 mutex_lock(&kvm->lock);
3589 goto create_irqchip_unlock;
3591 if (atomic_read(&kvm->online_vcpus))
3592 goto create_irqchip_unlock;
3594 vpic = kvm_create_pic(kvm);
3596 r = kvm_ioapic_init(kvm);
3598 mutex_lock(&kvm->slots_lock);
3599 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3601 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3603 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3605 mutex_unlock(&kvm->slots_lock);
3607 goto create_irqchip_unlock;
3610 goto create_irqchip_unlock;
3612 kvm->arch.vpic = vpic;
3614 r = kvm_setup_default_irq_routing(kvm);
3616 mutex_lock(&kvm->slots_lock);
3617 mutex_lock(&kvm->irq_lock);
3618 kvm_ioapic_destroy(kvm);
3619 kvm_destroy_pic(kvm);
3620 mutex_unlock(&kvm->irq_lock);
3621 mutex_unlock(&kvm->slots_lock);
3623 create_irqchip_unlock:
3624 mutex_unlock(&kvm->lock);
3627 case KVM_CREATE_PIT:
3628 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3630 case KVM_CREATE_PIT2:
3632 if (copy_from_user(&u.pit_config, argp,
3633 sizeof(struct kvm_pit_config)))
3636 mutex_lock(&kvm->slots_lock);
3639 goto create_pit_unlock;
3641 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3645 mutex_unlock(&kvm->slots_lock);
3647 case KVM_IRQ_LINE_STATUS:
3648 case KVM_IRQ_LINE: {
3649 struct kvm_irq_level irq_event;
3652 if (copy_from_user(&irq_event, argp, sizeof irq_event))
3655 if (irqchip_in_kernel(kvm)) {
3657 status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3658 irq_event.irq, irq_event.level);
3659 if (ioctl == KVM_IRQ_LINE_STATUS) {
3661 irq_event.status = status;
3662 if (copy_to_user(argp, &irq_event,
3670 case KVM_GET_IRQCHIP: {
3671 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3672 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
3678 if (copy_from_user(chip, argp, sizeof *chip))
3679 goto get_irqchip_out;
3681 if (!irqchip_in_kernel(kvm))
3682 goto get_irqchip_out;
3683 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3685 goto get_irqchip_out;
3687 if (copy_to_user(argp, chip, sizeof *chip))
3688 goto get_irqchip_out;
3696 case KVM_SET_IRQCHIP: {
3697 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3698 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
3704 if (copy_from_user(chip, argp, sizeof *chip))
3705 goto set_irqchip_out;
3707 if (!irqchip_in_kernel(kvm))
3708 goto set_irqchip_out;
3709 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3711 goto set_irqchip_out;
3721 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
3724 if (!kvm->arch.vpit)
3726 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
3730 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
3737 if (copy_from_user(&u.ps, argp, sizeof u.ps))
3740 if (!kvm->arch.vpit)
3742 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
3748 case KVM_GET_PIT2: {
3750 if (!kvm->arch.vpit)
3752 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
3756 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
3761 case KVM_SET_PIT2: {
3763 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
3766 if (!kvm->arch.vpit)
3768 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
3774 case KVM_REINJECT_CONTROL: {
3775 struct kvm_reinject_control control;
3777 if (copy_from_user(&control, argp, sizeof(control)))
3779 r = kvm_vm_ioctl_reinject(kvm, &control);
3785 case KVM_XEN_HVM_CONFIG: {
3787 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
3788 sizeof(struct kvm_xen_hvm_config)))
3791 if (kvm->arch.xen_hvm_config.flags)
3796 case KVM_SET_CLOCK: {
3797 struct kvm_clock_data user_ns;
3802 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
3810 local_irq_disable();
3811 now_ns = get_kernel_ns();
3812 delta = user_ns.clock - now_ns;
3814 kvm->arch.kvmclock_offset = delta;
3817 case KVM_GET_CLOCK: {
3818 struct kvm_clock_data user_ns;
3821 local_irq_disable();
3822 now_ns = get_kernel_ns();
3823 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
3826 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
3829 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
3842 static void kvm_init_msr_list(void)
3847 /* skip the first msrs in the list. KVM-specific */
3848 for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
3849 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
3852 msrs_to_save[j] = msrs_to_save[i];
3855 num_msrs_to_save = j;
3858 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
3866 if (!(vcpu->arch.apic &&
3867 !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, n, v))
3868 && kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
3879 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
3886 if (!(vcpu->arch.apic &&
3887 !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, n, v))
3888 && kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
3890 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
3900 static void kvm_set_segment(struct kvm_vcpu *vcpu,
3901 struct kvm_segment *var, int seg)
3903 kvm_x86_ops->set_segment(vcpu, var, seg);
3906 void kvm_get_segment(struct kvm_vcpu *vcpu,
3907 struct kvm_segment *var, int seg)
3909 kvm_x86_ops->get_segment(vcpu, var, seg);
3912 static gpa_t translate_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
3917 static gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
3920 struct x86_exception exception;
3922 BUG_ON(!mmu_is_nested(vcpu));
3924 /* NPT walks are always user-walks */
3925 access |= PFERR_USER_MASK;
3926 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, &exception);
3931 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
3932 struct x86_exception *exception)
3934 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3935 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3938 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
3939 struct x86_exception *exception)
3941 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3942 access |= PFERR_FETCH_MASK;
3943 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3946 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
3947 struct x86_exception *exception)
3949 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3950 access |= PFERR_WRITE_MASK;
3951 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3954 /* uses this to access any guest's mapped memory without checking CPL */
3955 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
3956 struct x86_exception *exception)
3958 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
3961 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
3962 struct kvm_vcpu *vcpu, u32 access,
3963 struct x86_exception *exception)
3966 int r = X86EMUL_CONTINUE;
3969 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
3971 unsigned offset = addr & (PAGE_SIZE-1);
3972 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
3975 if (gpa == UNMAPPED_GVA)
3976 return X86EMUL_PROPAGATE_FAULT;
3977 ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
3979 r = X86EMUL_IO_NEEDED;
3991 /* used for instruction fetching */
3992 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
3993 gva_t addr, void *val, unsigned int bytes,
3994 struct x86_exception *exception)
3996 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3997 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3999 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
4000 access | PFERR_FETCH_MASK,
4004 int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
4005 gva_t addr, void *val, unsigned int bytes,
4006 struct x86_exception *exception)
4008 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4009 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4011 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4014 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4016 static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4017 gva_t addr, void *val, unsigned int bytes,
4018 struct x86_exception *exception)
4020 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4021 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
4024 int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4025 gva_t addr, void *val,
4027 struct x86_exception *exception)
4029 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4031 int r = X86EMUL_CONTINUE;
4034 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4037 unsigned offset = addr & (PAGE_SIZE-1);
4038 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4041 if (gpa == UNMAPPED_GVA)
4042 return X86EMUL_PROPAGATE_FAULT;
4043 ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
4045 r = X86EMUL_IO_NEEDED;
4056 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4058 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4059 gpa_t *gpa, struct x86_exception *exception,
4062 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4064 if (vcpu_match_mmio_gva(vcpu, gva) &&
4065 check_write_user_access(vcpu, write, access,
4066 vcpu->arch.access)) {
4067 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4068 (gva & (PAGE_SIZE - 1));
4069 trace_vcpu_match_mmio(gva, *gpa, write, false);
4074 access |= PFERR_WRITE_MASK;
4076 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4078 if (*gpa == UNMAPPED_GVA)
4081 /* For APIC access vmexit */
4082 if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4085 if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
4086 trace_vcpu_match_mmio(gva, *gpa, write, true);
4093 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4094 const void *val, int bytes)
4098 ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
4101 kvm_mmu_pte_write(vcpu, gpa, val, bytes, 1);
4105 struct read_write_emulator_ops {
4106 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4108 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4109 void *val, int bytes);
4110 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4111 int bytes, void *val);
4112 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4113 void *val, int bytes);
4117 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4119 if (vcpu->mmio_read_completed) {
4120 memcpy(val, vcpu->mmio_data, bytes);
4121 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4122 vcpu->mmio_phys_addr, *(u64 *)val);
4123 vcpu->mmio_read_completed = 0;
4130 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4131 void *val, int bytes)
4133 return !kvm_read_guest(vcpu->kvm, gpa, val, bytes);
4136 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4137 void *val, int bytes)
4139 return emulator_write_phys(vcpu, gpa, val, bytes);
4142 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4144 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
4145 return vcpu_mmio_write(vcpu, gpa, bytes, val);
4148 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4149 void *val, int bytes)
4151 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
4152 return X86EMUL_IO_NEEDED;
4155 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4156 void *val, int bytes)
4158 memcpy(vcpu->mmio_data, val, bytes);
4159 memcpy(vcpu->run->mmio.data, vcpu->mmio_data, 8);
4160 return X86EMUL_CONTINUE;
4163 static struct read_write_emulator_ops read_emultor = {
4164 .read_write_prepare = read_prepare,
4165 .read_write_emulate = read_emulate,
4166 .read_write_mmio = vcpu_mmio_read,
4167 .read_write_exit_mmio = read_exit_mmio,
4170 static struct read_write_emulator_ops write_emultor = {
4171 .read_write_emulate = write_emulate,
4172 .read_write_mmio = write_mmio,
4173 .read_write_exit_mmio = write_exit_mmio,
4177 static int emulator_read_write_onepage(unsigned long addr, void *val,
4179 struct x86_exception *exception,
4180 struct kvm_vcpu *vcpu,
4181 struct read_write_emulator_ops *ops)
4185 bool write = ops->write;
4187 if (ops->read_write_prepare &&
4188 ops->read_write_prepare(vcpu, val, bytes))
4189 return X86EMUL_CONTINUE;
4191 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4194 return X86EMUL_PROPAGATE_FAULT;
4196 /* For APIC access vmexit */
4200 if (ops->read_write_emulate(vcpu, gpa, val, bytes))
4201 return X86EMUL_CONTINUE;
4205 * Is this MMIO handled locally?
4207 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4208 if (handled == bytes)
4209 return X86EMUL_CONTINUE;
4215 vcpu->mmio_needed = 1;
4216 vcpu->run->exit_reason = KVM_EXIT_MMIO;
4217 vcpu->run->mmio.phys_addr = vcpu->mmio_phys_addr = gpa;
4218 vcpu->mmio_size = bytes;
4219 vcpu->run->mmio.len = min(vcpu->mmio_size, 8);
4220 vcpu->run->mmio.is_write = vcpu->mmio_is_write = write;
4221 vcpu->mmio_index = 0;
4223 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4226 int emulator_read_write(struct x86_emulate_ctxt *ctxt, unsigned long addr,
4227 void *val, unsigned int bytes,
4228 struct x86_exception *exception,
4229 struct read_write_emulator_ops *ops)
4231 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4233 /* Crossing a page boundary? */
4234 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4237 now = -addr & ~PAGE_MASK;
4238 rc = emulator_read_write_onepage(addr, val, now, exception,
4241 if (rc != X86EMUL_CONTINUE)
4248 return emulator_read_write_onepage(addr, val, bytes, exception,
4252 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4256 struct x86_exception *exception)
4258 return emulator_read_write(ctxt, addr, val, bytes,
4259 exception, &read_emultor);
4262 int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4266 struct x86_exception *exception)
4268 return emulator_read_write(ctxt, addr, (void *)val, bytes,
4269 exception, &write_emultor);
4272 #define CMPXCHG_TYPE(t, ptr, old, new) \
4273 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4275 #ifdef CONFIG_X86_64
4276 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4278 # define CMPXCHG64(ptr, old, new) \
4279 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4282 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4287 struct x86_exception *exception)
4289 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4295 /* guests cmpxchg8b have to be emulated atomically */
4296 if (bytes > 8 || (bytes & (bytes - 1)))
4299 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4301 if (gpa == UNMAPPED_GVA ||
4302 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4305 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4308 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
4309 if (is_error_page(page)) {
4310 kvm_release_page_clean(page);
4314 kaddr = kmap_atomic(page, KM_USER0);
4315 kaddr += offset_in_page(gpa);
4318 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4321 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4324 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
4327 exchanged = CMPXCHG64(kaddr, old, new);
4332 kunmap_atomic(kaddr, KM_USER0);
4333 kvm_release_page_dirty(page);
4336 return X86EMUL_CMPXCHG_FAILED;
4338 kvm_mmu_pte_write(vcpu, gpa, new, bytes, 1);
4340 return X86EMUL_CONTINUE;
4343 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
4345 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
4348 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
4350 /* TODO: String I/O for in kernel device */
4353 if (vcpu->arch.pio.in)
4354 r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
4355 vcpu->arch.pio.size, pd);
4357 r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
4358 vcpu->arch.pio.port, vcpu->arch.pio.size,
4364 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
4365 int size, unsigned short port, void *val,
4368 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4370 if (vcpu->arch.pio.count)
4373 trace_kvm_pio(0, port, size, count);
4375 vcpu->arch.pio.port = port;
4376 vcpu->arch.pio.in = 1;
4377 vcpu->arch.pio.count = count;
4378 vcpu->arch.pio.size = size;
4380 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4382 memcpy(val, vcpu->arch.pio_data, size * count);
4383 vcpu->arch.pio.count = 0;
4387 vcpu->run->exit_reason = KVM_EXIT_IO;
4388 vcpu->run->io.direction = KVM_EXIT_IO_IN;
4389 vcpu->run->io.size = size;
4390 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4391 vcpu->run->io.count = count;
4392 vcpu->run->io.port = port;
4397 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
4398 int size, unsigned short port,
4399 const void *val, unsigned int count)
4401 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4403 trace_kvm_pio(1, port, size, count);
4405 vcpu->arch.pio.port = port;
4406 vcpu->arch.pio.in = 0;
4407 vcpu->arch.pio.count = count;
4408 vcpu->arch.pio.size = size;
4410 memcpy(vcpu->arch.pio_data, val, size * count);
4412 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4413 vcpu->arch.pio.count = 0;
4417 vcpu->run->exit_reason = KVM_EXIT_IO;
4418 vcpu->run->io.direction = KVM_EXIT_IO_OUT;
4419 vcpu->run->io.size = size;
4420 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4421 vcpu->run->io.count = count;
4422 vcpu->run->io.port = port;
4427 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
4429 return kvm_x86_ops->get_segment_base(vcpu, seg);
4432 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
4434 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
4437 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
4439 if (!need_emulate_wbinvd(vcpu))
4440 return X86EMUL_CONTINUE;
4442 if (kvm_x86_ops->has_wbinvd_exit()) {
4443 int cpu = get_cpu();
4445 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4446 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
4447 wbinvd_ipi, NULL, 1);
4449 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
4452 return X86EMUL_CONTINUE;
4454 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
4456 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
4458 kvm_emulate_wbinvd(emul_to_vcpu(ctxt));
4461 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
4463 return _kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
4466 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
4469 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
4472 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
4474 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
4477 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
4479 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4480 unsigned long value;
4484 value = kvm_read_cr0(vcpu);
4487 value = vcpu->arch.cr2;
4490 value = kvm_read_cr3(vcpu);
4493 value = kvm_read_cr4(vcpu);
4496 value = kvm_get_cr8(vcpu);
4499 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
4506 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
4508 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4513 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4516 vcpu->arch.cr2 = val;
4519 res = kvm_set_cr3(vcpu, val);
4522 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4525 res = kvm_set_cr8(vcpu, val);
4528 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
4535 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
4537 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
4540 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4542 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
4545 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4547 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
4550 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4552 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4555 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4557 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4560 static unsigned long emulator_get_cached_segment_base(
4561 struct x86_emulate_ctxt *ctxt, int seg)
4563 return get_segment_base(emul_to_vcpu(ctxt), seg);
4566 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4567 struct desc_struct *desc, u32 *base3,
4570 struct kvm_segment var;
4572 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
4573 *selector = var.selector;
4580 set_desc_limit(desc, var.limit);
4581 set_desc_base(desc, (unsigned long)var.base);
4582 #ifdef CONFIG_X86_64
4584 *base3 = var.base >> 32;
4586 desc->type = var.type;
4588 desc->dpl = var.dpl;
4589 desc->p = var.present;
4590 desc->avl = var.avl;
4598 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
4599 struct desc_struct *desc, u32 base3,
4602 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4603 struct kvm_segment var;
4605 var.selector = selector;
4606 var.base = get_desc_base(desc);
4607 #ifdef CONFIG_X86_64
4608 var.base |= ((u64)base3) << 32;
4610 var.limit = get_desc_limit(desc);
4612 var.limit = (var.limit << 12) | 0xfff;
4613 var.type = desc->type;
4614 var.present = desc->p;
4615 var.dpl = desc->dpl;
4620 var.avl = desc->avl;
4621 var.present = desc->p;
4622 var.unusable = !var.present;
4625 kvm_set_segment(vcpu, &var, seg);
4629 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
4630 u32 msr_index, u64 *pdata)
4632 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
4635 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
4636 u32 msr_index, u64 data)
4638 return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
4641 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
4643 emul_to_vcpu(ctxt)->arch.halt_request = 1;
4646 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
4649 kvm_load_guest_fpu(emul_to_vcpu(ctxt));
4651 * CR0.TS may reference the host fpu state, not the guest fpu state,
4652 * so it may be clear at this point.
4657 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
4662 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
4663 struct x86_instruction_info *info,
4664 enum x86_intercept_stage stage)
4666 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
4669 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
4670 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
4672 struct kvm_cpuid_entry2 *cpuid = NULL;
4675 cpuid = kvm_find_cpuid_entry(emul_to_vcpu(ctxt),
4691 static struct x86_emulate_ops emulate_ops = {
4692 .read_std = kvm_read_guest_virt_system,
4693 .write_std = kvm_write_guest_virt_system,
4694 .fetch = kvm_fetch_guest_virt,
4695 .read_emulated = emulator_read_emulated,
4696 .write_emulated = emulator_write_emulated,
4697 .cmpxchg_emulated = emulator_cmpxchg_emulated,
4698 .invlpg = emulator_invlpg,
4699 .pio_in_emulated = emulator_pio_in_emulated,
4700 .pio_out_emulated = emulator_pio_out_emulated,
4701 .get_segment = emulator_get_segment,
4702 .set_segment = emulator_set_segment,
4703 .get_cached_segment_base = emulator_get_cached_segment_base,
4704 .get_gdt = emulator_get_gdt,
4705 .get_idt = emulator_get_idt,
4706 .set_gdt = emulator_set_gdt,
4707 .set_idt = emulator_set_idt,
4708 .get_cr = emulator_get_cr,
4709 .set_cr = emulator_set_cr,
4710 .cpl = emulator_get_cpl,
4711 .get_dr = emulator_get_dr,
4712 .set_dr = emulator_set_dr,
4713 .set_msr = emulator_set_msr,
4714 .get_msr = emulator_get_msr,
4715 .halt = emulator_halt,
4716 .wbinvd = emulator_wbinvd,
4717 .fix_hypercall = emulator_fix_hypercall,
4718 .get_fpu = emulator_get_fpu,
4719 .put_fpu = emulator_put_fpu,
4720 .intercept = emulator_intercept,
4721 .get_cpuid = emulator_get_cpuid,
4724 static void cache_all_regs(struct kvm_vcpu *vcpu)
4726 kvm_register_read(vcpu, VCPU_REGS_RAX);
4727 kvm_register_read(vcpu, VCPU_REGS_RSP);
4728 kvm_register_read(vcpu, VCPU_REGS_RIP);
4729 vcpu->arch.regs_dirty = ~0;
4732 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
4734 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu, mask);
4736 * an sti; sti; sequence only disable interrupts for the first
4737 * instruction. So, if the last instruction, be it emulated or
4738 * not, left the system with the INT_STI flag enabled, it
4739 * means that the last instruction is an sti. We should not
4740 * leave the flag on in this case. The same goes for mov ss
4742 if (!(int_shadow & mask))
4743 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
4746 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
4748 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4749 if (ctxt->exception.vector == PF_VECTOR)
4750 kvm_propagate_fault(vcpu, &ctxt->exception);
4751 else if (ctxt->exception.error_code_valid)
4752 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
4753 ctxt->exception.error_code);
4755 kvm_queue_exception(vcpu, ctxt->exception.vector);
4758 static void init_decode_cache(struct x86_emulate_ctxt *ctxt,
4759 const unsigned long *regs)
4761 memset(&ctxt->twobyte, 0,
4762 (void *)&ctxt->regs - (void *)&ctxt->twobyte);
4763 memcpy(ctxt->regs, regs, sizeof(ctxt->regs));
4765 ctxt->fetch.start = 0;
4766 ctxt->fetch.end = 0;
4767 ctxt->io_read.pos = 0;
4768 ctxt->io_read.end = 0;
4769 ctxt->mem_read.pos = 0;
4770 ctxt->mem_read.end = 0;
4773 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
4775 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4779 * TODO: fix emulate.c to use guest_read/write_register
4780 * instead of direct ->regs accesses, can save hundred cycles
4781 * on Intel for instructions that don't read/change RSP, for
4784 cache_all_regs(vcpu);
4786 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4788 ctxt->eflags = kvm_get_rflags(vcpu);
4789 ctxt->eip = kvm_rip_read(vcpu);
4790 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
4791 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
4792 cs_l ? X86EMUL_MODE_PROT64 :
4793 cs_db ? X86EMUL_MODE_PROT32 :
4794 X86EMUL_MODE_PROT16;
4795 ctxt->guest_mode = is_guest_mode(vcpu);
4797 init_decode_cache(ctxt, vcpu->arch.regs);
4798 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
4801 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
4803 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4806 init_emulate_ctxt(vcpu);
4810 ctxt->_eip = ctxt->eip + inc_eip;
4811 ret = emulate_int_real(ctxt, irq);
4813 if (ret != X86EMUL_CONTINUE)
4814 return EMULATE_FAIL;
4816 ctxt->eip = ctxt->_eip;
4817 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
4818 kvm_rip_write(vcpu, ctxt->eip);
4819 kvm_set_rflags(vcpu, ctxt->eflags);
4821 if (irq == NMI_VECTOR)
4822 vcpu->arch.nmi_pending = 0;
4824 vcpu->arch.interrupt.pending = false;
4826 return EMULATE_DONE;
4828 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
4830 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
4832 int r = EMULATE_DONE;
4834 ++vcpu->stat.insn_emulation_fail;
4835 trace_kvm_emulate_insn_failed(vcpu);
4836 if (!is_guest_mode(vcpu)) {
4837 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4838 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
4839 vcpu->run->internal.ndata = 0;
4842 kvm_queue_exception(vcpu, UD_VECTOR);
4847 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t gva)
4855 * if emulation was due to access to shadowed page table
4856 * and it failed try to unshadow page and re-entetr the
4857 * guest to let CPU execute the instruction.
4859 if (kvm_mmu_unprotect_page_virt(vcpu, gva))
4862 gpa = kvm_mmu_gva_to_gpa_system(vcpu, gva, NULL);
4864 if (gpa == UNMAPPED_GVA)
4865 return true; /* let cpu generate fault */
4867 if (!kvm_is_error_hva(gfn_to_hva(vcpu->kvm, gpa >> PAGE_SHIFT)))
4873 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
4880 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4881 bool writeback = true;
4883 kvm_clear_exception_queue(vcpu);
4885 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
4886 init_emulate_ctxt(vcpu);
4887 ctxt->interruptibility = 0;
4888 ctxt->have_exception = false;
4889 ctxt->perm_ok = false;
4891 ctxt->only_vendor_specific_insn
4892 = emulation_type & EMULTYPE_TRAP_UD;
4894 r = x86_decode_insn(ctxt, insn, insn_len);
4896 trace_kvm_emulate_insn_start(vcpu);
4897 ++vcpu->stat.insn_emulation;
4898 if (r != EMULATION_OK) {
4899 if (emulation_type & EMULTYPE_TRAP_UD)
4900 return EMULATE_FAIL;
4901 if (reexecute_instruction(vcpu, cr2))
4902 return EMULATE_DONE;
4903 if (emulation_type & EMULTYPE_SKIP)
4904 return EMULATE_FAIL;
4905 return handle_emulation_failure(vcpu);
4909 if (emulation_type & EMULTYPE_SKIP) {
4910 kvm_rip_write(vcpu, ctxt->_eip);
4911 return EMULATE_DONE;
4914 /* this is needed for vmware backdoor interface to work since it
4915 changes registers values during IO operation */
4916 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
4917 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
4918 memcpy(ctxt->regs, vcpu->arch.regs, sizeof ctxt->regs);
4922 r = x86_emulate_insn(ctxt);
4924 if (r == EMULATION_INTERCEPTED)
4925 return EMULATE_DONE;
4927 if (r == EMULATION_FAILED) {
4928 if (reexecute_instruction(vcpu, cr2))
4929 return EMULATE_DONE;
4931 return handle_emulation_failure(vcpu);
4934 if (ctxt->have_exception) {
4935 inject_emulated_exception(vcpu);
4937 } else if (vcpu->arch.pio.count) {
4938 if (!vcpu->arch.pio.in)
4939 vcpu->arch.pio.count = 0;
4942 r = EMULATE_DO_MMIO;
4943 } else if (vcpu->mmio_needed) {
4944 if (!vcpu->mmio_is_write)
4946 r = EMULATE_DO_MMIO;
4947 } else if (r == EMULATION_RESTART)
4953 toggle_interruptibility(vcpu, ctxt->interruptibility);
4954 kvm_set_rflags(vcpu, ctxt->eflags);
4955 kvm_make_request(KVM_REQ_EVENT, vcpu);
4956 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
4957 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
4958 kvm_rip_write(vcpu, ctxt->eip);
4960 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
4964 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
4966 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
4968 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
4969 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
4970 size, port, &val, 1);
4971 /* do not return to emulator after return from userspace */
4972 vcpu->arch.pio.count = 0;
4975 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
4977 static void tsc_bad(void *info)
4979 __this_cpu_write(cpu_tsc_khz, 0);
4982 static void tsc_khz_changed(void *data)
4984 struct cpufreq_freqs *freq = data;
4985 unsigned long khz = 0;
4989 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
4990 khz = cpufreq_quick_get(raw_smp_processor_id());
4993 __this_cpu_write(cpu_tsc_khz, khz);
4996 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
4999 struct cpufreq_freqs *freq = data;
5001 struct kvm_vcpu *vcpu;
5002 int i, send_ipi = 0;
5005 * We allow guests to temporarily run on slowing clocks,
5006 * provided we notify them after, or to run on accelerating
5007 * clocks, provided we notify them before. Thus time never
5010 * However, we have a problem. We can't atomically update
5011 * the frequency of a given CPU from this function; it is
5012 * merely a notifier, which can be called from any CPU.
5013 * Changing the TSC frequency at arbitrary points in time
5014 * requires a recomputation of local variables related to
5015 * the TSC for each VCPU. We must flag these local variables
5016 * to be updated and be sure the update takes place with the
5017 * new frequency before any guests proceed.
5019 * Unfortunately, the combination of hotplug CPU and frequency
5020 * change creates an intractable locking scenario; the order
5021 * of when these callouts happen is undefined with respect to
5022 * CPU hotplug, and they can race with each other. As such,
5023 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5024 * undefined; you can actually have a CPU frequency change take
5025 * place in between the computation of X and the setting of the
5026 * variable. To protect against this problem, all updates of
5027 * the per_cpu tsc_khz variable are done in an interrupt
5028 * protected IPI, and all callers wishing to update the value
5029 * must wait for a synchronous IPI to complete (which is trivial
5030 * if the caller is on the CPU already). This establishes the
5031 * necessary total order on variable updates.
5033 * Note that because a guest time update may take place
5034 * anytime after the setting of the VCPU's request bit, the
5035 * correct TSC value must be set before the request. However,
5036 * to ensure the update actually makes it to any guest which
5037 * starts running in hardware virtualization between the set
5038 * and the acquisition of the spinlock, we must also ping the
5039 * CPU after setting the request bit.
5043 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
5045 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
5048 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5050 raw_spin_lock(&kvm_lock);
5051 list_for_each_entry(kvm, &vm_list, vm_list) {
5052 kvm_for_each_vcpu(i, vcpu, kvm) {
5053 if (vcpu->cpu != freq->cpu)
5055 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5056 if (vcpu->cpu != smp_processor_id())
5060 raw_spin_unlock(&kvm_lock);
5062 if (freq->old < freq->new && send_ipi) {
5064 * We upscale the frequency. Must make the guest
5065 * doesn't see old kvmclock values while running with
5066 * the new frequency, otherwise we risk the guest sees
5067 * time go backwards.
5069 * In case we update the frequency for another cpu
5070 * (which might be in guest context) send an interrupt
5071 * to kick the cpu out of guest context. Next time
5072 * guest context is entered kvmclock will be updated,
5073 * so the guest will not see stale values.
5075 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5080 static struct notifier_block kvmclock_cpufreq_notifier_block = {
5081 .notifier_call = kvmclock_cpufreq_notifier
5084 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
5085 unsigned long action, void *hcpu)
5087 unsigned int cpu = (unsigned long)hcpu;
5091 case CPU_DOWN_FAILED:
5092 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5094 case CPU_DOWN_PREPARE:
5095 smp_call_function_single(cpu, tsc_bad, NULL, 1);
5101 static struct notifier_block kvmclock_cpu_notifier_block = {
5102 .notifier_call = kvmclock_cpu_notifier,
5103 .priority = -INT_MAX
5106 static void kvm_timer_init(void)
5110 max_tsc_khz = tsc_khz;
5111 register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5112 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5113 #ifdef CONFIG_CPU_FREQ
5114 struct cpufreq_policy policy;
5115 memset(&policy, 0, sizeof(policy));
5117 cpufreq_get_policy(&policy, cpu);
5118 if (policy.cpuinfo.max_freq)
5119 max_tsc_khz = policy.cpuinfo.max_freq;
5122 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
5123 CPUFREQ_TRANSITION_NOTIFIER);
5125 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
5126 for_each_online_cpu(cpu)
5127 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5130 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
5132 static int kvm_is_in_guest(void)
5134 return percpu_read(current_vcpu) != NULL;
5137 static int kvm_is_user_mode(void)
5141 if (percpu_read(current_vcpu))
5142 user_mode = kvm_x86_ops->get_cpl(percpu_read(current_vcpu));
5144 return user_mode != 0;
5147 static unsigned long kvm_get_guest_ip(void)
5149 unsigned long ip = 0;
5151 if (percpu_read(current_vcpu))
5152 ip = kvm_rip_read(percpu_read(current_vcpu));
5157 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5158 .is_in_guest = kvm_is_in_guest,
5159 .is_user_mode = kvm_is_user_mode,
5160 .get_guest_ip = kvm_get_guest_ip,
5163 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
5165 percpu_write(current_vcpu, vcpu);
5167 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
5169 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
5171 percpu_write(current_vcpu, NULL);
5173 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
5175 static void kvm_set_mmio_spte_mask(void)
5178 int maxphyaddr = boot_cpu_data.x86_phys_bits;
5181 * Set the reserved bits and the present bit of an paging-structure
5182 * entry to generate page fault with PFER.RSV = 1.
5184 mask = ((1ull << (62 - maxphyaddr + 1)) - 1) << maxphyaddr;
5187 #ifdef CONFIG_X86_64
5189 * If reserved bit is not supported, clear the present bit to disable
5192 if (maxphyaddr == 52)
5196 kvm_mmu_set_mmio_spte_mask(mask);
5199 int kvm_arch_init(void *opaque)
5202 struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
5205 printk(KERN_ERR "kvm: already loaded the other module\n");
5210 if (!ops->cpu_has_kvm_support()) {
5211 printk(KERN_ERR "kvm: no hardware support\n");
5215 if (ops->disabled_by_bios()) {
5216 printk(KERN_ERR "kvm: disabled by bios\n");
5221 r = kvm_mmu_module_init();
5225 kvm_set_mmio_spte_mask();
5226 kvm_init_msr_list();
5229 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
5230 PT_DIRTY_MASK, PT64_NX_MASK, 0);
5234 perf_register_guest_info_callbacks(&kvm_guest_cbs);
5237 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
5245 void kvm_arch_exit(void)
5247 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
5249 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5250 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
5251 CPUFREQ_TRANSITION_NOTIFIER);
5252 unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5254 kvm_mmu_module_exit();
5257 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
5259 ++vcpu->stat.halt_exits;
5260 if (irqchip_in_kernel(vcpu->kvm)) {
5261 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
5264 vcpu->run->exit_reason = KVM_EXIT_HLT;
5268 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
5270 static inline gpa_t hc_gpa(struct kvm_vcpu *vcpu, unsigned long a0,
5273 if (is_long_mode(vcpu))
5276 return a0 | ((gpa_t)a1 << 32);
5279 int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
5281 u64 param, ingpa, outgpa, ret;
5282 uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
5283 bool fast, longmode;
5287 * hypercall generates UD from non zero cpl and real mode
5290 if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
5291 kvm_queue_exception(vcpu, UD_VECTOR);
5295 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5296 longmode = is_long_mode(vcpu) && cs_l == 1;
5299 param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
5300 (kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
5301 ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
5302 (kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
5303 outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
5304 (kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
5306 #ifdef CONFIG_X86_64
5308 param = kvm_register_read(vcpu, VCPU_REGS_RCX);
5309 ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
5310 outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
5314 code = param & 0xffff;
5315 fast = (param >> 16) & 0x1;
5316 rep_cnt = (param >> 32) & 0xfff;
5317 rep_idx = (param >> 48) & 0xfff;
5319 trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
5322 case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
5323 kvm_vcpu_on_spin(vcpu);
5326 res = HV_STATUS_INVALID_HYPERCALL_CODE;
5330 ret = res | (((u64)rep_done & 0xfff) << 32);
5332 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
5334 kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
5335 kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
5341 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
5343 unsigned long nr, a0, a1, a2, a3, ret;
5346 if (kvm_hv_hypercall_enabled(vcpu->kvm))
5347 return kvm_hv_hypercall(vcpu);
5349 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
5350 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
5351 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
5352 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
5353 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
5355 trace_kvm_hypercall(nr, a0, a1, a2, a3);
5357 if (!is_long_mode(vcpu)) {
5365 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
5371 case KVM_HC_VAPIC_POLL_IRQ:
5375 r = kvm_pv_mmu_op(vcpu, a0, hc_gpa(vcpu, a1, a2), &ret);
5382 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
5383 ++vcpu->stat.hypercalls;
5386 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
5388 int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
5390 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5391 char instruction[3];
5392 unsigned long rip = kvm_rip_read(vcpu);
5395 * Blow out the MMU to ensure that no other VCPU has an active mapping
5396 * to ensure that the updated hypercall appears atomically across all
5399 kvm_mmu_zap_all(vcpu->kvm);
5401 kvm_x86_ops->patch_hypercall(vcpu, instruction);
5403 return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
5406 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
5408 struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
5409 int j, nent = vcpu->arch.cpuid_nent;
5411 e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
5412 /* when no next entry is found, the current entry[i] is reselected */
5413 for (j = i + 1; ; j = (j + 1) % nent) {
5414 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
5415 if (ej->function == e->function) {
5416 ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
5420 return 0; /* silence gcc, even though control never reaches here */
5423 /* find an entry with matching function, matching index (if needed), and that
5424 * should be read next (if it's stateful) */
5425 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
5426 u32 function, u32 index)
5428 if (e->function != function)
5430 if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
5432 if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
5433 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
5438 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry(struct kvm_vcpu *vcpu,
5439 u32 function, u32 index)
5442 struct kvm_cpuid_entry2 *best = NULL;
5444 for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
5445 struct kvm_cpuid_entry2 *e;
5447 e = &vcpu->arch.cpuid_entries[i];
5448 if (is_matching_cpuid_entry(e, function, index)) {
5449 if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
5450 move_to_next_stateful_cpuid_entry(vcpu, i);
5457 EXPORT_SYMBOL_GPL(kvm_find_cpuid_entry);
5459 int cpuid_maxphyaddr(struct kvm_vcpu *vcpu)
5461 struct kvm_cpuid_entry2 *best;
5463 best = kvm_find_cpuid_entry(vcpu, 0x80000000, 0);
5464 if (!best || best->eax < 0x80000008)
5466 best = kvm_find_cpuid_entry(vcpu, 0x80000008, 0);
5468 return best->eax & 0xff;
5474 * If no match is found, check whether we exceed the vCPU's limit
5475 * and return the content of the highest valid _standard_ leaf instead.
5476 * This is to satisfy the CPUID specification.
5478 static struct kvm_cpuid_entry2* check_cpuid_limit(struct kvm_vcpu *vcpu,
5479 u32 function, u32 index)
5481 struct kvm_cpuid_entry2 *maxlevel;
5483 maxlevel = kvm_find_cpuid_entry(vcpu, function & 0x80000000, 0);
5484 if (!maxlevel || maxlevel->eax >= function)
5486 if (function & 0x80000000) {
5487 maxlevel = kvm_find_cpuid_entry(vcpu, 0, 0);
5491 return kvm_find_cpuid_entry(vcpu, maxlevel->eax, index);
5494 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
5496 u32 function, index;
5497 struct kvm_cpuid_entry2 *best;
5499 function = kvm_register_read(vcpu, VCPU_REGS_RAX);
5500 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
5501 kvm_register_write(vcpu, VCPU_REGS_RAX, 0);
5502 kvm_register_write(vcpu, VCPU_REGS_RBX, 0);
5503 kvm_register_write(vcpu, VCPU_REGS_RCX, 0);
5504 kvm_register_write(vcpu, VCPU_REGS_RDX, 0);
5505 best = kvm_find_cpuid_entry(vcpu, function, index);
5508 best = check_cpuid_limit(vcpu, function, index);
5511 kvm_register_write(vcpu, VCPU_REGS_RAX, best->eax);
5512 kvm_register_write(vcpu, VCPU_REGS_RBX, best->ebx);
5513 kvm_register_write(vcpu, VCPU_REGS_RCX, best->ecx);
5514 kvm_register_write(vcpu, VCPU_REGS_RDX, best->edx);
5516 kvm_x86_ops->skip_emulated_instruction(vcpu);
5517 trace_kvm_cpuid(function,
5518 kvm_register_read(vcpu, VCPU_REGS_RAX),
5519 kvm_register_read(vcpu, VCPU_REGS_RBX),
5520 kvm_register_read(vcpu, VCPU_REGS_RCX),
5521 kvm_register_read(vcpu, VCPU_REGS_RDX));
5523 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
5526 * Check if userspace requested an interrupt window, and that the
5527 * interrupt window is open.
5529 * No need to exit to userspace if we already have an interrupt queued.
5531 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
5533 return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
5534 vcpu->run->request_interrupt_window &&
5535 kvm_arch_interrupt_allowed(vcpu));
5538 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
5540 struct kvm_run *kvm_run = vcpu->run;
5542 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
5543 kvm_run->cr8 = kvm_get_cr8(vcpu);
5544 kvm_run->apic_base = kvm_get_apic_base(vcpu);
5545 if (irqchip_in_kernel(vcpu->kvm))
5546 kvm_run->ready_for_interrupt_injection = 1;
5548 kvm_run->ready_for_interrupt_injection =
5549 kvm_arch_interrupt_allowed(vcpu) &&
5550 !kvm_cpu_has_interrupt(vcpu) &&
5551 !kvm_event_needs_reinjection(vcpu);
5554 static void vapic_enter(struct kvm_vcpu *vcpu)
5556 struct kvm_lapic *apic = vcpu->arch.apic;
5559 if (!apic || !apic->vapic_addr)
5562 page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
5564 vcpu->arch.apic->vapic_page = page;
5567 static void vapic_exit(struct kvm_vcpu *vcpu)
5569 struct kvm_lapic *apic = vcpu->arch.apic;
5572 if (!apic || !apic->vapic_addr)
5575 idx = srcu_read_lock(&vcpu->kvm->srcu);
5576 kvm_release_page_dirty(apic->vapic_page);
5577 mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
5578 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5581 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
5585 if (!kvm_x86_ops->update_cr8_intercept)
5588 if (!vcpu->arch.apic)
5591 if (!vcpu->arch.apic->vapic_addr)
5592 max_irr = kvm_lapic_find_highest_irr(vcpu);
5599 tpr = kvm_lapic_get_cr8(vcpu);
5601 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
5604 static void inject_pending_event(struct kvm_vcpu *vcpu)
5606 /* try to reinject previous events if any */
5607 if (vcpu->arch.exception.pending) {
5608 trace_kvm_inj_exception(vcpu->arch.exception.nr,
5609 vcpu->arch.exception.has_error_code,
5610 vcpu->arch.exception.error_code);
5611 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
5612 vcpu->arch.exception.has_error_code,
5613 vcpu->arch.exception.error_code,
5614 vcpu->arch.exception.reinject);
5618 if (vcpu->arch.nmi_injected) {
5619 kvm_x86_ops->set_nmi(vcpu);
5623 if (vcpu->arch.interrupt.pending) {
5624 kvm_x86_ops->set_irq(vcpu);
5628 /* try to inject new event if pending */
5629 if (vcpu->arch.nmi_pending) {
5630 if (kvm_x86_ops->nmi_allowed(vcpu)) {
5631 --vcpu->arch.nmi_pending;
5632 vcpu->arch.nmi_injected = true;
5633 kvm_x86_ops->set_nmi(vcpu);
5635 } else if (kvm_cpu_has_interrupt(vcpu)) {
5636 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
5637 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
5639 kvm_x86_ops->set_irq(vcpu);
5644 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
5646 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
5647 !vcpu->guest_xcr0_loaded) {
5648 /* kvm_set_xcr() also depends on this */
5649 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
5650 vcpu->guest_xcr0_loaded = 1;
5654 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
5656 if (vcpu->guest_xcr0_loaded) {
5657 if (vcpu->arch.xcr0 != host_xcr0)
5658 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
5659 vcpu->guest_xcr0_loaded = 0;
5663 static void process_nmi(struct kvm_vcpu *vcpu)
5668 * x86 is limited to one NMI running, and one NMI pending after it.
5669 * If an NMI is already in progress, limit further NMIs to just one.
5670 * Otherwise, allow two (and we'll inject the first one immediately).
5672 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
5675 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
5676 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
5677 kvm_make_request(KVM_REQ_EVENT, vcpu);
5680 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
5683 bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
5684 vcpu->run->request_interrupt_window;
5686 if (vcpu->requests) {
5687 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
5688 kvm_mmu_unload(vcpu);
5689 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
5690 __kvm_migrate_timers(vcpu);
5691 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
5692 r = kvm_guest_time_update(vcpu);
5696 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
5697 kvm_mmu_sync_roots(vcpu);
5698 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
5699 kvm_x86_ops->tlb_flush(vcpu);
5700 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
5701 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
5705 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
5706 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5710 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
5711 vcpu->fpu_active = 0;
5712 kvm_x86_ops->fpu_deactivate(vcpu);
5714 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
5715 /* Page is swapped out. Do synthetic halt */
5716 vcpu->arch.apf.halted = true;
5720 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
5721 record_steal_time(vcpu);
5722 if (kvm_check_request(KVM_REQ_NMI, vcpu))
5727 r = kvm_mmu_reload(vcpu);
5731 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
5732 inject_pending_event(vcpu);
5734 /* enable NMI/IRQ window open exits if needed */
5735 if (vcpu->arch.nmi_pending)
5736 kvm_x86_ops->enable_nmi_window(vcpu);
5737 else if (kvm_cpu_has_interrupt(vcpu) || req_int_win)
5738 kvm_x86_ops->enable_irq_window(vcpu);
5740 if (kvm_lapic_enabled(vcpu)) {
5741 update_cr8_intercept(vcpu);
5742 kvm_lapic_sync_to_vapic(vcpu);
5748 kvm_x86_ops->prepare_guest_switch(vcpu);
5749 if (vcpu->fpu_active)
5750 kvm_load_guest_fpu(vcpu);
5751 kvm_load_guest_xcr0(vcpu);
5753 vcpu->mode = IN_GUEST_MODE;
5755 /* We should set ->mode before check ->requests,
5756 * see the comment in make_all_cpus_request.
5760 local_irq_disable();
5762 if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
5763 || need_resched() || signal_pending(current)) {
5764 vcpu->mode = OUTSIDE_GUEST_MODE;
5768 kvm_x86_ops->cancel_injection(vcpu);
5773 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
5777 if (unlikely(vcpu->arch.switch_db_regs)) {
5779 set_debugreg(vcpu->arch.eff_db[0], 0);
5780 set_debugreg(vcpu->arch.eff_db[1], 1);
5781 set_debugreg(vcpu->arch.eff_db[2], 2);
5782 set_debugreg(vcpu->arch.eff_db[3], 3);
5785 trace_kvm_entry(vcpu->vcpu_id);
5786 kvm_x86_ops->run(vcpu);
5789 * If the guest has used debug registers, at least dr7
5790 * will be disabled while returning to the host.
5791 * If we don't have active breakpoints in the host, we don't
5792 * care about the messed up debug address registers. But if
5793 * we have some of them active, restore the old state.
5795 if (hw_breakpoint_active())
5796 hw_breakpoint_restore();
5798 vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu);
5800 vcpu->mode = OUTSIDE_GUEST_MODE;
5807 * We must have an instruction between local_irq_enable() and
5808 * kvm_guest_exit(), so the timer interrupt isn't delayed by
5809 * the interrupt shadow. The stat.exits increment will do nicely.
5810 * But we need to prevent reordering, hence this barrier():
5818 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
5821 * Profile KVM exit RIPs:
5823 if (unlikely(prof_on == KVM_PROFILING)) {
5824 unsigned long rip = kvm_rip_read(vcpu);
5825 profile_hit(KVM_PROFILING, (void *)rip);
5829 kvm_lapic_sync_from_vapic(vcpu);
5831 r = kvm_x86_ops->handle_exit(vcpu);
5837 static int __vcpu_run(struct kvm_vcpu *vcpu)
5840 struct kvm *kvm = vcpu->kvm;
5842 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
5843 pr_debug("vcpu %d received sipi with vector # %x\n",
5844 vcpu->vcpu_id, vcpu->arch.sipi_vector);
5845 kvm_lapic_reset(vcpu);
5846 r = kvm_arch_vcpu_reset(vcpu);
5849 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5852 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
5857 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
5858 !vcpu->arch.apf.halted)
5859 r = vcpu_enter_guest(vcpu);
5861 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5862 kvm_vcpu_block(vcpu);
5863 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
5864 if (kvm_check_request(KVM_REQ_UNHALT, vcpu))
5866 switch(vcpu->arch.mp_state) {
5867 case KVM_MP_STATE_HALTED:
5868 vcpu->arch.mp_state =
5869 KVM_MP_STATE_RUNNABLE;
5870 case KVM_MP_STATE_RUNNABLE:
5871 vcpu->arch.apf.halted = false;
5873 case KVM_MP_STATE_SIPI_RECEIVED:
5884 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
5885 if (kvm_cpu_has_pending_timer(vcpu))
5886 kvm_inject_pending_timer_irqs(vcpu);
5888 if (dm_request_for_irq_injection(vcpu)) {
5890 vcpu->run->exit_reason = KVM_EXIT_INTR;
5891 ++vcpu->stat.request_irq_exits;
5894 kvm_check_async_pf_completion(vcpu);
5896 if (signal_pending(current)) {
5898 vcpu->run->exit_reason = KVM_EXIT_INTR;
5899 ++vcpu->stat.signal_exits;
5901 if (need_resched()) {
5902 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5904 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
5908 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5915 static int complete_mmio(struct kvm_vcpu *vcpu)
5917 struct kvm_run *run = vcpu->run;
5920 if (!(vcpu->arch.pio.count || vcpu->mmio_needed))
5923 if (vcpu->mmio_needed) {
5924 vcpu->mmio_needed = 0;
5925 if (!vcpu->mmio_is_write)
5926 memcpy(vcpu->mmio_data + vcpu->mmio_index,
5928 vcpu->mmio_index += 8;
5929 if (vcpu->mmio_index < vcpu->mmio_size) {
5930 run->exit_reason = KVM_EXIT_MMIO;
5931 run->mmio.phys_addr = vcpu->mmio_phys_addr + vcpu->mmio_index;
5932 memcpy(run->mmio.data, vcpu->mmio_data + vcpu->mmio_index, 8);
5933 run->mmio.len = min(vcpu->mmio_size - vcpu->mmio_index, 8);
5934 run->mmio.is_write = vcpu->mmio_is_write;
5935 vcpu->mmio_needed = 1;
5938 if (vcpu->mmio_is_write)
5940 vcpu->mmio_read_completed = 1;
5942 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
5943 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
5944 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
5945 if (r != EMULATE_DONE)
5950 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
5955 if (!tsk_used_math(current) && init_fpu(current))
5958 if (vcpu->sigset_active)
5959 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
5961 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
5962 kvm_vcpu_block(vcpu);
5963 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
5968 /* re-sync apic's tpr */
5969 if (!irqchip_in_kernel(vcpu->kvm)) {
5970 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
5976 r = complete_mmio(vcpu);
5980 if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL)
5981 kvm_register_write(vcpu, VCPU_REGS_RAX,
5982 kvm_run->hypercall.ret);
5984 r = __vcpu_run(vcpu);
5987 post_kvm_run_save(vcpu);
5988 if (vcpu->sigset_active)
5989 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
5994 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
5996 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
5998 * We are here if userspace calls get_regs() in the middle of
5999 * instruction emulation. Registers state needs to be copied
6000 * back from emulation context to vcpu. Usrapace shouldn't do
6001 * that usually, but some bad designed PV devices (vmware
6002 * backdoor interface) need this to work
6004 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6005 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
6006 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6008 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
6009 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
6010 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
6011 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
6012 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
6013 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
6014 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
6015 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
6016 #ifdef CONFIG_X86_64
6017 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
6018 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
6019 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
6020 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
6021 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
6022 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
6023 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
6024 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
6027 regs->rip = kvm_rip_read(vcpu);
6028 regs->rflags = kvm_get_rflags(vcpu);
6033 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6035 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
6036 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6038 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
6039 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
6040 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
6041 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
6042 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
6043 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
6044 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
6045 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
6046 #ifdef CONFIG_X86_64
6047 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
6048 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
6049 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
6050 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
6051 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
6052 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
6053 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
6054 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
6057 kvm_rip_write(vcpu, regs->rip);
6058 kvm_set_rflags(vcpu, regs->rflags);
6060 vcpu->arch.exception.pending = false;
6062 kvm_make_request(KVM_REQ_EVENT, vcpu);
6067 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
6069 struct kvm_segment cs;
6071 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
6075 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
6077 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
6078 struct kvm_sregs *sregs)
6082 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6083 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6084 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6085 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6086 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6087 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6089 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6090 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6092 kvm_x86_ops->get_idt(vcpu, &dt);
6093 sregs->idt.limit = dt.size;
6094 sregs->idt.base = dt.address;
6095 kvm_x86_ops->get_gdt(vcpu, &dt);
6096 sregs->gdt.limit = dt.size;
6097 sregs->gdt.base = dt.address;
6099 sregs->cr0 = kvm_read_cr0(vcpu);
6100 sregs->cr2 = vcpu->arch.cr2;
6101 sregs->cr3 = kvm_read_cr3(vcpu);
6102 sregs->cr4 = kvm_read_cr4(vcpu);
6103 sregs->cr8 = kvm_get_cr8(vcpu);
6104 sregs->efer = vcpu->arch.efer;
6105 sregs->apic_base = kvm_get_apic_base(vcpu);
6107 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
6109 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
6110 set_bit(vcpu->arch.interrupt.nr,
6111 (unsigned long *)sregs->interrupt_bitmap);
6116 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
6117 struct kvm_mp_state *mp_state)
6119 mp_state->mp_state = vcpu->arch.mp_state;
6123 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
6124 struct kvm_mp_state *mp_state)
6126 vcpu->arch.mp_state = mp_state->mp_state;
6127 kvm_make_request(KVM_REQ_EVENT, vcpu);
6131 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason,
6132 bool has_error_code, u32 error_code)
6134 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6137 init_emulate_ctxt(vcpu);
6139 ret = emulator_task_switch(ctxt, tss_selector, reason,
6140 has_error_code, error_code);
6143 return EMULATE_FAIL;
6145 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
6146 kvm_rip_write(vcpu, ctxt->eip);
6147 kvm_set_rflags(vcpu, ctxt->eflags);
6148 kvm_make_request(KVM_REQ_EVENT, vcpu);
6149 return EMULATE_DONE;
6151 EXPORT_SYMBOL_GPL(kvm_task_switch);
6153 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
6154 struct kvm_sregs *sregs)
6156 int mmu_reset_needed = 0;
6157 int pending_vec, max_bits, idx;
6160 if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
6163 dt.size = sregs->idt.limit;
6164 dt.address = sregs->idt.base;
6165 kvm_x86_ops->set_idt(vcpu, &dt);
6166 dt.size = sregs->gdt.limit;
6167 dt.address = sregs->gdt.base;
6168 kvm_x86_ops->set_gdt(vcpu, &dt);
6170 vcpu->arch.cr2 = sregs->cr2;
6171 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
6172 vcpu->arch.cr3 = sregs->cr3;
6173 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
6175 kvm_set_cr8(vcpu, sregs->cr8);
6177 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
6178 kvm_x86_ops->set_efer(vcpu, sregs->efer);
6179 kvm_set_apic_base(vcpu, sregs->apic_base);
6181 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
6182 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
6183 vcpu->arch.cr0 = sregs->cr0;
6185 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
6186 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
6187 if (sregs->cr4 & X86_CR4_OSXSAVE)
6190 idx = srcu_read_lock(&vcpu->kvm->srcu);
6191 if (!is_long_mode(vcpu) && is_pae(vcpu)) {
6192 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
6193 mmu_reset_needed = 1;
6195 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6197 if (mmu_reset_needed)
6198 kvm_mmu_reset_context(vcpu);
6200 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
6201 pending_vec = find_first_bit(
6202 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
6203 if (pending_vec < max_bits) {
6204 kvm_queue_interrupt(vcpu, pending_vec, false);
6205 pr_debug("Set back pending irq %d\n", pending_vec);
6208 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6209 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6210 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6211 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6212 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6213 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6215 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6216 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6218 update_cr8_intercept(vcpu);
6220 /* Older userspace won't unhalt the vcpu on reset. */
6221 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
6222 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
6224 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
6226 kvm_make_request(KVM_REQ_EVENT, vcpu);
6231 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
6232 struct kvm_guest_debug *dbg)
6234 unsigned long rflags;
6237 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
6239 if (vcpu->arch.exception.pending)
6241 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
6242 kvm_queue_exception(vcpu, DB_VECTOR);
6244 kvm_queue_exception(vcpu, BP_VECTOR);
6248 * Read rflags as long as potentially injected trace flags are still
6251 rflags = kvm_get_rflags(vcpu);
6253 vcpu->guest_debug = dbg->control;
6254 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
6255 vcpu->guest_debug = 0;
6257 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
6258 for (i = 0; i < KVM_NR_DB_REGS; ++i)
6259 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
6260 vcpu->arch.switch_db_regs =
6261 (dbg->arch.debugreg[7] & DR7_BP_EN_MASK);
6263 for (i = 0; i < KVM_NR_DB_REGS; i++)
6264 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
6265 vcpu->arch.switch_db_regs = (vcpu->arch.dr7 & DR7_BP_EN_MASK);
6268 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6269 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
6270 get_segment_base(vcpu, VCPU_SREG_CS);
6273 * Trigger an rflags update that will inject or remove the trace
6276 kvm_set_rflags(vcpu, rflags);
6278 kvm_x86_ops->set_guest_debug(vcpu, dbg);
6288 * Translate a guest virtual address to a guest physical address.
6290 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
6291 struct kvm_translation *tr)
6293 unsigned long vaddr = tr->linear_address;
6297 idx = srcu_read_lock(&vcpu->kvm->srcu);
6298 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
6299 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6300 tr->physical_address = gpa;
6301 tr->valid = gpa != UNMAPPED_GVA;
6308 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
6310 struct i387_fxsave_struct *fxsave =
6311 &vcpu->arch.guest_fpu.state->fxsave;
6313 memcpy(fpu->fpr, fxsave->st_space, 128);
6314 fpu->fcw = fxsave->cwd;
6315 fpu->fsw = fxsave->swd;
6316 fpu->ftwx = fxsave->twd;
6317 fpu->last_opcode = fxsave->fop;
6318 fpu->last_ip = fxsave->rip;
6319 fpu->last_dp = fxsave->rdp;
6320 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
6325 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
6327 struct i387_fxsave_struct *fxsave =
6328 &vcpu->arch.guest_fpu.state->fxsave;
6330 memcpy(fxsave->st_space, fpu->fpr, 128);
6331 fxsave->cwd = fpu->fcw;
6332 fxsave->swd = fpu->fsw;
6333 fxsave->twd = fpu->ftwx;
6334 fxsave->fop = fpu->last_opcode;
6335 fxsave->rip = fpu->last_ip;
6336 fxsave->rdp = fpu->last_dp;
6337 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
6342 int fx_init(struct kvm_vcpu *vcpu)
6346 err = fpu_alloc(&vcpu->arch.guest_fpu);
6350 fpu_finit(&vcpu->arch.guest_fpu);
6353 * Ensure guest xcr0 is valid for loading
6355 vcpu->arch.xcr0 = XSTATE_FP;
6357 vcpu->arch.cr0 |= X86_CR0_ET;
6361 EXPORT_SYMBOL_GPL(fx_init);
6363 static void fx_free(struct kvm_vcpu *vcpu)
6365 fpu_free(&vcpu->arch.guest_fpu);
6368 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
6370 if (vcpu->guest_fpu_loaded)
6374 * Restore all possible states in the guest,
6375 * and assume host would use all available bits.
6376 * Guest xcr0 would be loaded later.
6378 kvm_put_guest_xcr0(vcpu);
6379 vcpu->guest_fpu_loaded = 1;
6380 unlazy_fpu(current);
6381 fpu_restore_checking(&vcpu->arch.guest_fpu);
6385 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
6387 kvm_put_guest_xcr0(vcpu);
6389 if (!vcpu->guest_fpu_loaded)
6392 vcpu->guest_fpu_loaded = 0;
6393 fpu_save_init(&vcpu->arch.guest_fpu);
6394 ++vcpu->stat.fpu_reload;
6395 kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
6399 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
6401 kvmclock_reset(vcpu);
6403 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
6405 kvm_x86_ops->vcpu_free(vcpu);
6408 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
6411 if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
6412 printk_once(KERN_WARNING
6413 "kvm: SMP vm created on host with unstable TSC; "
6414 "guest TSC will not be reliable\n");
6415 return kvm_x86_ops->vcpu_create(kvm, id);
6418 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
6422 vcpu->arch.mtrr_state.have_fixed = 1;
6424 r = kvm_arch_vcpu_reset(vcpu);
6426 r = kvm_mmu_setup(vcpu);
6432 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
6434 vcpu->arch.apf.msr_val = 0;
6437 kvm_mmu_unload(vcpu);
6441 kvm_x86_ops->vcpu_free(vcpu);
6444 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
6446 atomic_set(&vcpu->arch.nmi_queued, 0);
6447 vcpu->arch.nmi_pending = 0;
6448 vcpu->arch.nmi_injected = false;
6450 vcpu->arch.switch_db_regs = 0;
6451 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
6452 vcpu->arch.dr6 = DR6_FIXED_1;
6453 vcpu->arch.dr7 = DR7_FIXED_1;
6455 kvm_make_request(KVM_REQ_EVENT, vcpu);
6456 vcpu->arch.apf.msr_val = 0;
6457 vcpu->arch.st.msr_val = 0;
6459 kvmclock_reset(vcpu);
6461 kvm_clear_async_pf_completion_queue(vcpu);
6462 kvm_async_pf_hash_reset(vcpu);
6463 vcpu->arch.apf.halted = false;
6465 return kvm_x86_ops->vcpu_reset(vcpu);
6468 int kvm_arch_hardware_enable(void *garbage)
6471 struct kvm_vcpu *vcpu;
6474 kvm_shared_msr_cpu_online();
6475 list_for_each_entry(kvm, &vm_list, vm_list)
6476 kvm_for_each_vcpu(i, vcpu, kvm)
6477 if (vcpu->cpu == smp_processor_id())
6478 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6479 return kvm_x86_ops->hardware_enable(garbage);
6482 void kvm_arch_hardware_disable(void *garbage)
6484 kvm_x86_ops->hardware_disable(garbage);
6485 drop_user_return_notifiers(garbage);
6488 int kvm_arch_hardware_setup(void)
6490 return kvm_x86_ops->hardware_setup();
6493 void kvm_arch_hardware_unsetup(void)
6495 kvm_x86_ops->hardware_unsetup();
6498 void kvm_arch_check_processor_compat(void *rtn)
6500 kvm_x86_ops->check_processor_compatibility(rtn);
6503 bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
6505 return irqchip_in_kernel(vcpu->kvm) == (vcpu->arch.apic != NULL);
6508 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
6514 BUG_ON(vcpu->kvm == NULL);
6517 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
6518 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
6519 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
6520 vcpu->arch.mmu.translate_gpa = translate_gpa;
6521 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
6522 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
6523 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
6525 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
6527 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
6532 vcpu->arch.pio_data = page_address(page);
6534 kvm_init_tsc_catchup(vcpu, max_tsc_khz);
6536 r = kvm_mmu_create(vcpu);
6538 goto fail_free_pio_data;
6540 if (irqchip_in_kernel(kvm)) {
6541 r = kvm_create_lapic(vcpu);
6543 goto fail_mmu_destroy;
6546 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
6548 if (!vcpu->arch.mce_banks) {
6550 goto fail_free_lapic;
6552 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
6554 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL))
6555 goto fail_free_mce_banks;
6557 kvm_async_pf_hash_reset(vcpu);
6560 fail_free_mce_banks:
6561 kfree(vcpu->arch.mce_banks);
6563 kvm_free_lapic(vcpu);
6565 kvm_mmu_destroy(vcpu);
6567 free_page((unsigned long)vcpu->arch.pio_data);
6572 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
6576 kfree(vcpu->arch.mce_banks);
6577 kvm_free_lapic(vcpu);
6578 idx = srcu_read_lock(&vcpu->kvm->srcu);
6579 kvm_mmu_destroy(vcpu);
6580 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6581 free_page((unsigned long)vcpu->arch.pio_data);
6584 int kvm_arch_init_vm(struct kvm *kvm)
6586 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6587 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
6589 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
6590 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
6592 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
6597 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
6600 kvm_mmu_unload(vcpu);
6604 static void kvm_free_vcpus(struct kvm *kvm)
6607 struct kvm_vcpu *vcpu;
6610 * Unpin any mmu pages first.
6612 kvm_for_each_vcpu(i, vcpu, kvm) {
6613 kvm_clear_async_pf_completion_queue(vcpu);
6614 kvm_unload_vcpu_mmu(vcpu);
6616 kvm_for_each_vcpu(i, vcpu, kvm)
6617 kvm_arch_vcpu_free(vcpu);
6619 mutex_lock(&kvm->lock);
6620 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
6621 kvm->vcpus[i] = NULL;
6623 atomic_set(&kvm->online_vcpus, 0);
6624 mutex_unlock(&kvm->lock);
6627 void kvm_arch_sync_events(struct kvm *kvm)
6629 kvm_free_all_assigned_devices(kvm);
6633 void kvm_arch_destroy_vm(struct kvm *kvm)
6635 kvm_iommu_unmap_guest(kvm);
6636 kfree(kvm->arch.vpic);
6637 kfree(kvm->arch.vioapic);
6638 kvm_free_vcpus(kvm);
6639 if (kvm->arch.apic_access_page)
6640 put_page(kvm->arch.apic_access_page);
6641 if (kvm->arch.ept_identity_pagetable)
6642 put_page(kvm->arch.ept_identity_pagetable);
6645 int kvm_arch_prepare_memory_region(struct kvm *kvm,
6646 struct kvm_memory_slot *memslot,
6647 struct kvm_memory_slot old,
6648 struct kvm_userspace_memory_region *mem,
6651 int npages = memslot->npages;
6652 int map_flags = MAP_PRIVATE | MAP_ANONYMOUS;
6654 /* Prevent internal slot pages from being moved by fork()/COW. */
6655 if (memslot->id >= KVM_MEMORY_SLOTS)
6656 map_flags = MAP_SHARED | MAP_ANONYMOUS;
6658 /*To keep backward compatibility with older userspace,
6659 *x86 needs to hanlde !user_alloc case.
6662 if (npages && !old.rmap) {
6663 unsigned long userspace_addr;
6665 down_write(¤t->mm->mmap_sem);
6666 userspace_addr = do_mmap(NULL, 0,
6668 PROT_READ | PROT_WRITE,
6671 up_write(¤t->mm->mmap_sem);
6673 if (IS_ERR((void *)userspace_addr))
6674 return PTR_ERR((void *)userspace_addr);
6676 memslot->userspace_addr = userspace_addr;
6684 void kvm_arch_commit_memory_region(struct kvm *kvm,
6685 struct kvm_userspace_memory_region *mem,
6686 struct kvm_memory_slot old,
6690 int nr_mmu_pages = 0, npages = mem->memory_size >> PAGE_SHIFT;
6692 if (!user_alloc && !old.user_alloc && old.rmap && !npages) {
6695 down_write(¤t->mm->mmap_sem);
6696 ret = do_munmap(current->mm, old.userspace_addr,
6697 old.npages * PAGE_SIZE);
6698 up_write(¤t->mm->mmap_sem);
6701 "kvm_vm_ioctl_set_memory_region: "
6702 "failed to munmap memory\n");
6705 if (!kvm->arch.n_requested_mmu_pages)
6706 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
6708 spin_lock(&kvm->mmu_lock);
6710 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
6711 kvm_mmu_slot_remove_write_access(kvm, mem->slot);
6712 spin_unlock(&kvm->mmu_lock);
6715 void kvm_arch_flush_shadow(struct kvm *kvm)
6717 kvm_mmu_zap_all(kvm);
6718 kvm_reload_remote_mmus(kvm);
6721 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
6723 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6724 !vcpu->arch.apf.halted)
6725 || !list_empty_careful(&vcpu->async_pf.done)
6726 || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
6727 || atomic_read(&vcpu->arch.nmi_queued) ||
6728 (kvm_arch_interrupt_allowed(vcpu) &&
6729 kvm_cpu_has_interrupt(vcpu));
6732 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
6735 int cpu = vcpu->cpu;
6737 if (waitqueue_active(&vcpu->wq)) {
6738 wake_up_interruptible(&vcpu->wq);
6739 ++vcpu->stat.halt_wakeup;
6743 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
6744 if (kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE)
6745 smp_send_reschedule(cpu);
6749 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
6751 return kvm_x86_ops->interrupt_allowed(vcpu);
6754 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
6756 unsigned long current_rip = kvm_rip_read(vcpu) +
6757 get_segment_base(vcpu, VCPU_SREG_CS);
6759 return current_rip == linear_rip;
6761 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
6763 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
6765 unsigned long rflags;
6767 rflags = kvm_x86_ops->get_rflags(vcpu);
6768 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6769 rflags &= ~X86_EFLAGS_TF;
6772 EXPORT_SYMBOL_GPL(kvm_get_rflags);
6774 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
6776 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
6777 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
6778 rflags |= X86_EFLAGS_TF;
6779 kvm_x86_ops->set_rflags(vcpu, rflags);
6780 kvm_make_request(KVM_REQ_EVENT, vcpu);
6782 EXPORT_SYMBOL_GPL(kvm_set_rflags);
6784 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
6788 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
6789 is_error_page(work->page))
6792 r = kvm_mmu_reload(vcpu);
6796 if (!vcpu->arch.mmu.direct_map &&
6797 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
6800 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
6803 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
6805 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
6808 static inline u32 kvm_async_pf_next_probe(u32 key)
6810 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
6813 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6815 u32 key = kvm_async_pf_hash_fn(gfn);
6817 while (vcpu->arch.apf.gfns[key] != ~0)
6818 key = kvm_async_pf_next_probe(key);
6820 vcpu->arch.apf.gfns[key] = gfn;
6823 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
6826 u32 key = kvm_async_pf_hash_fn(gfn);
6828 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
6829 (vcpu->arch.apf.gfns[key] != gfn &&
6830 vcpu->arch.apf.gfns[key] != ~0); i++)
6831 key = kvm_async_pf_next_probe(key);
6836 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6838 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
6841 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6845 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
6847 vcpu->arch.apf.gfns[i] = ~0;
6849 j = kvm_async_pf_next_probe(j);
6850 if (vcpu->arch.apf.gfns[j] == ~0)
6852 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
6854 * k lies cyclically in ]i,j]
6856 * |....j i.k.| or |.k..j i...|
6858 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
6859 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
6864 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
6867 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
6871 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
6872 struct kvm_async_pf *work)
6874 struct x86_exception fault;
6876 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
6877 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
6879 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
6880 (vcpu->arch.apf.send_user_only &&
6881 kvm_x86_ops->get_cpl(vcpu) == 0))
6882 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
6883 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
6884 fault.vector = PF_VECTOR;
6885 fault.error_code_valid = true;
6886 fault.error_code = 0;
6887 fault.nested_page_fault = false;
6888 fault.address = work->arch.token;
6889 kvm_inject_page_fault(vcpu, &fault);
6893 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
6894 struct kvm_async_pf *work)
6896 struct x86_exception fault;
6898 trace_kvm_async_pf_ready(work->arch.token, work->gva);
6899 if (is_error_page(work->page))
6900 work->arch.token = ~0; /* broadcast wakeup */
6902 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
6904 if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
6905 !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
6906 fault.vector = PF_VECTOR;
6907 fault.error_code_valid = true;
6908 fault.error_code = 0;
6909 fault.nested_page_fault = false;
6910 fault.address = work->arch.token;
6911 kvm_inject_page_fault(vcpu, &fault);
6913 vcpu->arch.apf.halted = false;
6916 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
6918 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
6921 return !kvm_event_needs_reinjection(vcpu) &&
6922 kvm_x86_ops->interrupt_allowed(vcpu);
6925 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
6926 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
6927 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
6928 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
6929 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
6930 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
6931 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
6932 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
6933 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
6934 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
6935 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
6936 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);