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 unsigned int min_timer_period_us = 500;
96 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
98 bool kvm_has_tsc_control;
99 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
100 u32 kvm_max_guest_tsc_khz;
101 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
103 #define KVM_NR_SHARED_MSRS 16
105 struct kvm_shared_msrs_global {
107 u32 msrs[KVM_NR_SHARED_MSRS];
110 struct kvm_shared_msrs {
111 struct user_return_notifier urn;
113 struct kvm_shared_msr_values {
116 } values[KVM_NR_SHARED_MSRS];
119 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
120 static DEFINE_PER_CPU(struct kvm_shared_msrs, shared_msrs);
122 struct kvm_stats_debugfs_item debugfs_entries[] = {
123 { "pf_fixed", VCPU_STAT(pf_fixed) },
124 { "pf_guest", VCPU_STAT(pf_guest) },
125 { "tlb_flush", VCPU_STAT(tlb_flush) },
126 { "invlpg", VCPU_STAT(invlpg) },
127 { "exits", VCPU_STAT(exits) },
128 { "io_exits", VCPU_STAT(io_exits) },
129 { "mmio_exits", VCPU_STAT(mmio_exits) },
130 { "signal_exits", VCPU_STAT(signal_exits) },
131 { "irq_window", VCPU_STAT(irq_window_exits) },
132 { "nmi_window", VCPU_STAT(nmi_window_exits) },
133 { "halt_exits", VCPU_STAT(halt_exits) },
134 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
135 { "hypercalls", VCPU_STAT(hypercalls) },
136 { "request_irq", VCPU_STAT(request_irq_exits) },
137 { "irq_exits", VCPU_STAT(irq_exits) },
138 { "host_state_reload", VCPU_STAT(host_state_reload) },
139 { "efer_reload", VCPU_STAT(efer_reload) },
140 { "fpu_reload", VCPU_STAT(fpu_reload) },
141 { "insn_emulation", VCPU_STAT(insn_emulation) },
142 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
143 { "irq_injections", VCPU_STAT(irq_injections) },
144 { "nmi_injections", VCPU_STAT(nmi_injections) },
145 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
146 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
147 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
148 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
149 { "mmu_flooded", VM_STAT(mmu_flooded) },
150 { "mmu_recycled", VM_STAT(mmu_recycled) },
151 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
152 { "mmu_unsync", VM_STAT(mmu_unsync) },
153 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
154 { "largepages", VM_STAT(lpages) },
158 u64 __read_mostly host_xcr0;
160 int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
162 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
165 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
166 vcpu->arch.apf.gfns[i] = ~0;
169 static void kvm_on_user_return(struct user_return_notifier *urn)
172 struct kvm_shared_msrs *locals
173 = container_of(urn, struct kvm_shared_msrs, urn);
174 struct kvm_shared_msr_values *values;
178 * Disabling irqs at this point since the following code could be
179 * interrupted and executed through kvm_arch_hardware_disable()
181 local_irq_save(flags);
182 if (locals->registered) {
183 locals->registered = false;
184 user_return_notifier_unregister(urn);
186 local_irq_restore(flags);
187 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
188 values = &locals->values[slot];
189 if (values->host != values->curr) {
190 wrmsrl(shared_msrs_global.msrs[slot], values->host);
191 values->curr = values->host;
196 static void shared_msr_update(unsigned slot, u32 msr)
198 struct kvm_shared_msrs *smsr;
201 smsr = &__get_cpu_var(shared_msrs);
202 /* only read, and nobody should modify it at this time,
203 * so don't need lock */
204 if (slot >= shared_msrs_global.nr) {
205 printk(KERN_ERR "kvm: invalid MSR slot!");
208 rdmsrl_safe(msr, &value);
209 smsr->values[slot].host = value;
210 smsr->values[slot].curr = value;
213 void kvm_define_shared_msr(unsigned slot, u32 msr)
215 if (slot >= shared_msrs_global.nr)
216 shared_msrs_global.nr = slot + 1;
217 shared_msrs_global.msrs[slot] = msr;
218 /* we need ensured the shared_msr_global have been updated */
221 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
223 static void kvm_shared_msr_cpu_online(void)
227 for (i = 0; i < shared_msrs_global.nr; ++i)
228 shared_msr_update(i, shared_msrs_global.msrs[i]);
231 void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
233 struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
235 if (((value ^ smsr->values[slot].curr) & mask) == 0)
237 smsr->values[slot].curr = value;
238 wrmsrl(shared_msrs_global.msrs[slot], value);
239 if (!smsr->registered) {
240 smsr->urn.on_user_return = kvm_on_user_return;
241 user_return_notifier_register(&smsr->urn);
242 smsr->registered = true;
245 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
247 static void drop_user_return_notifiers(void *ignore)
249 struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
251 if (smsr->registered)
252 kvm_on_user_return(&smsr->urn);
255 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
257 if (irqchip_in_kernel(vcpu->kvm))
258 return vcpu->arch.apic_base;
260 return vcpu->arch.apic_base;
262 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
264 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
266 /* TODO: reserve bits check */
267 if (irqchip_in_kernel(vcpu->kvm))
268 kvm_lapic_set_base(vcpu, data);
270 vcpu->arch.apic_base = data;
272 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
274 #define EXCPT_BENIGN 0
275 #define EXCPT_CONTRIBUTORY 1
278 static int exception_class(int vector)
288 return EXCPT_CONTRIBUTORY;
295 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
296 unsigned nr, bool has_error, u32 error_code,
302 kvm_make_request(KVM_REQ_EVENT, vcpu);
304 if (!vcpu->arch.exception.pending) {
306 vcpu->arch.exception.pending = true;
307 vcpu->arch.exception.has_error_code = has_error;
308 vcpu->arch.exception.nr = nr;
309 vcpu->arch.exception.error_code = error_code;
310 vcpu->arch.exception.reinject = reinject;
314 /* to check exception */
315 prev_nr = vcpu->arch.exception.nr;
316 if (prev_nr == DF_VECTOR) {
317 /* triple fault -> shutdown */
318 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
321 class1 = exception_class(prev_nr);
322 class2 = exception_class(nr);
323 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
324 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
325 /* generate double fault per SDM Table 5-5 */
326 vcpu->arch.exception.pending = true;
327 vcpu->arch.exception.has_error_code = true;
328 vcpu->arch.exception.nr = DF_VECTOR;
329 vcpu->arch.exception.error_code = 0;
331 /* replace previous exception with a new one in a hope
332 that instruction re-execution will regenerate lost
337 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
339 kvm_multiple_exception(vcpu, nr, false, 0, false);
341 EXPORT_SYMBOL_GPL(kvm_queue_exception);
343 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
345 kvm_multiple_exception(vcpu, nr, false, 0, true);
347 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
349 void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
352 kvm_inject_gp(vcpu, 0);
354 kvm_x86_ops->skip_emulated_instruction(vcpu);
356 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
358 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
360 ++vcpu->stat.pf_guest;
361 vcpu->arch.cr2 = fault->address;
362 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
364 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
366 void kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
368 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
369 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
371 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
374 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
376 atomic_inc(&vcpu->arch.nmi_queued);
377 kvm_make_request(KVM_REQ_NMI, vcpu);
379 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
381 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
383 kvm_multiple_exception(vcpu, nr, true, error_code, false);
385 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
387 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
389 kvm_multiple_exception(vcpu, nr, true, error_code, true);
391 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
394 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
395 * a #GP and return false.
397 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
399 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
401 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
404 EXPORT_SYMBOL_GPL(kvm_require_cpl);
407 * This function will be used to read from the physical memory of the currently
408 * running guest. The difference to kvm_read_guest_page is that this function
409 * can read from guest physical or from the guest's guest physical memory.
411 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
412 gfn_t ngfn, void *data, int offset, int len,
418 ngpa = gfn_to_gpa(ngfn);
419 real_gfn = mmu->translate_gpa(vcpu, ngpa, access);
420 if (real_gfn == UNMAPPED_GVA)
423 real_gfn = gpa_to_gfn(real_gfn);
425 return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
427 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
429 int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
430 void *data, int offset, int len, u32 access)
432 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
433 data, offset, len, access);
437 * Load the pae pdptrs. Return true is they are all valid.
439 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
441 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
442 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
445 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
447 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
448 offset * sizeof(u64), sizeof(pdpte),
449 PFERR_USER_MASK|PFERR_WRITE_MASK);
454 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
455 if (is_present_gpte(pdpte[i]) &&
456 (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
463 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
464 __set_bit(VCPU_EXREG_PDPTR,
465 (unsigned long *)&vcpu->arch.regs_avail);
466 __set_bit(VCPU_EXREG_PDPTR,
467 (unsigned long *)&vcpu->arch.regs_dirty);
472 EXPORT_SYMBOL_GPL(load_pdptrs);
474 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
476 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
482 if (is_long_mode(vcpu) || !is_pae(vcpu))
485 if (!test_bit(VCPU_EXREG_PDPTR,
486 (unsigned long *)&vcpu->arch.regs_avail))
489 gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
490 offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
491 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
492 PFERR_USER_MASK | PFERR_WRITE_MASK);
495 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
501 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
503 unsigned long old_cr0 = kvm_read_cr0(vcpu);
504 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
505 X86_CR0_CD | X86_CR0_NW;
510 if (cr0 & 0xffffffff00000000UL)
514 cr0 &= ~CR0_RESERVED_BITS;
516 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
519 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
522 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
524 if ((vcpu->arch.efer & EFER_LME)) {
529 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
534 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
539 kvm_x86_ops->set_cr0(vcpu, cr0);
541 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
542 kvm_clear_async_pf_completion_queue(vcpu);
543 kvm_async_pf_hash_reset(vcpu);
546 if ((cr0 ^ old_cr0) & update_bits)
547 kvm_mmu_reset_context(vcpu);
550 EXPORT_SYMBOL_GPL(kvm_set_cr0);
552 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
554 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
556 EXPORT_SYMBOL_GPL(kvm_lmsw);
558 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
562 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
563 if (index != XCR_XFEATURE_ENABLED_MASK)
566 if (!(xcr0 & XSTATE_FP))
568 if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
570 if (xcr0 & ~host_xcr0)
572 vcpu->arch.xcr0 = xcr0;
573 vcpu->guest_xcr0_loaded = 0;
577 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
579 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
580 __kvm_set_xcr(vcpu, index, xcr)) {
581 kvm_inject_gp(vcpu, 0);
586 EXPORT_SYMBOL_GPL(kvm_set_xcr);
588 static bool guest_cpuid_has_xsave(struct kvm_vcpu *vcpu)
590 struct kvm_cpuid_entry2 *best;
592 if (!static_cpu_has(X86_FEATURE_XSAVE))
595 best = kvm_find_cpuid_entry(vcpu, 1, 0);
596 return best && (best->ecx & bit(X86_FEATURE_XSAVE));
599 static bool guest_cpuid_has_smep(struct kvm_vcpu *vcpu)
601 struct kvm_cpuid_entry2 *best;
603 best = kvm_find_cpuid_entry(vcpu, 7, 0);
604 return best && (best->ebx & bit(X86_FEATURE_SMEP));
607 static bool guest_cpuid_has_fsgsbase(struct kvm_vcpu *vcpu)
609 struct kvm_cpuid_entry2 *best;
611 best = kvm_find_cpuid_entry(vcpu, 7, 0);
612 return best && (best->ebx & bit(X86_FEATURE_FSGSBASE));
615 static void update_cpuid(struct kvm_vcpu *vcpu)
617 struct kvm_cpuid_entry2 *best;
618 struct kvm_lapic *apic = vcpu->arch.apic;
620 best = kvm_find_cpuid_entry(vcpu, 1, 0);
624 /* Update OSXSAVE bit */
625 if (cpu_has_xsave && best->function == 0x1) {
626 best->ecx &= ~(bit(X86_FEATURE_OSXSAVE));
627 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE))
628 best->ecx |= bit(X86_FEATURE_OSXSAVE);
632 if (best->ecx & bit(X86_FEATURE_TSC_DEADLINE_TIMER))
633 apic->lapic_timer.timer_mode_mask = 3 << 17;
635 apic->lapic_timer.timer_mode_mask = 1 << 17;
639 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
641 unsigned long old_cr4 = kvm_read_cr4(vcpu);
642 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
643 X86_CR4_PAE | X86_CR4_SMEP;
644 if (cr4 & CR4_RESERVED_BITS)
647 if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
650 if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
653 if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_RDWRGSFS))
656 if (is_long_mode(vcpu)) {
657 if (!(cr4 & X86_CR4_PAE))
659 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
660 && ((cr4 ^ old_cr4) & pdptr_bits)
661 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
665 if (kvm_x86_ops->set_cr4(vcpu, cr4))
668 if ((cr4 ^ old_cr4) & pdptr_bits)
669 kvm_mmu_reset_context(vcpu);
671 if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
676 EXPORT_SYMBOL_GPL(kvm_set_cr4);
678 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
680 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
681 kvm_mmu_sync_roots(vcpu);
682 kvm_mmu_flush_tlb(vcpu);
686 if (is_long_mode(vcpu)) {
687 if (cr3 & CR3_L_MODE_RESERVED_BITS)
691 if (cr3 & CR3_PAE_RESERVED_BITS)
693 if (is_paging(vcpu) &&
694 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
698 * We don't check reserved bits in nonpae mode, because
699 * this isn't enforced, and VMware depends on this.
704 * Does the new cr3 value map to physical memory? (Note, we
705 * catch an invalid cr3 even in real-mode, because it would
706 * cause trouble later on when we turn on paging anyway.)
708 * A real CPU would silently accept an invalid cr3 and would
709 * attempt to use it - with largely undefined (and often hard
710 * to debug) behavior on the guest side.
712 if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
714 vcpu->arch.cr3 = cr3;
715 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
716 vcpu->arch.mmu.new_cr3(vcpu);
719 EXPORT_SYMBOL_GPL(kvm_set_cr3);
721 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
723 if (cr8 & CR8_RESERVED_BITS)
725 if (irqchip_in_kernel(vcpu->kvm))
726 kvm_lapic_set_tpr(vcpu, cr8);
728 vcpu->arch.cr8 = cr8;
731 EXPORT_SYMBOL_GPL(kvm_set_cr8);
733 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
735 if (irqchip_in_kernel(vcpu->kvm))
736 return kvm_lapic_get_cr8(vcpu);
738 return vcpu->arch.cr8;
740 EXPORT_SYMBOL_GPL(kvm_get_cr8);
742 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
746 vcpu->arch.db[dr] = val;
747 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
748 vcpu->arch.eff_db[dr] = val;
751 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
755 if (val & 0xffffffff00000000ULL)
757 vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
760 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
764 if (val & 0xffffffff00000000ULL)
766 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
767 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
768 kvm_x86_ops->set_dr7(vcpu, vcpu->arch.dr7);
769 vcpu->arch.switch_db_regs = (val & DR7_BP_EN_MASK);
777 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
781 res = __kvm_set_dr(vcpu, dr, val);
783 kvm_queue_exception(vcpu, UD_VECTOR);
785 kvm_inject_gp(vcpu, 0);
789 EXPORT_SYMBOL_GPL(kvm_set_dr);
791 static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
795 *val = vcpu->arch.db[dr];
798 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
802 *val = vcpu->arch.dr6;
805 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
809 *val = vcpu->arch.dr7;
816 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
818 if (_kvm_get_dr(vcpu, dr, val)) {
819 kvm_queue_exception(vcpu, UD_VECTOR);
824 EXPORT_SYMBOL_GPL(kvm_get_dr);
827 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
828 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
830 * This list is modified at module load time to reflect the
831 * capabilities of the host cpu. This capabilities test skips MSRs that are
832 * kvm-specific. Those are put in the beginning of the list.
835 #define KVM_SAVE_MSRS_BEGIN 9
836 static u32 msrs_to_save[] = {
837 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
838 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
839 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
840 HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
841 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
844 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
846 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA
849 static unsigned num_msrs_to_save;
851 static u32 emulated_msrs[] = {
852 MSR_IA32_TSCDEADLINE,
853 MSR_IA32_MISC_ENABLE,
858 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
860 u64 old_efer = vcpu->arch.efer;
862 if (efer & efer_reserved_bits)
866 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
869 if (efer & EFER_FFXSR) {
870 struct kvm_cpuid_entry2 *feat;
872 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
873 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
877 if (efer & EFER_SVME) {
878 struct kvm_cpuid_entry2 *feat;
880 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
881 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
886 efer |= vcpu->arch.efer & EFER_LMA;
888 kvm_x86_ops->set_efer(vcpu, efer);
890 vcpu->arch.mmu.base_role.nxe = (efer & EFER_NX) && !tdp_enabled;
892 /* Update reserved bits */
893 if ((efer ^ old_efer) & EFER_NX)
894 kvm_mmu_reset_context(vcpu);
899 void kvm_enable_efer_bits(u64 mask)
901 efer_reserved_bits &= ~mask;
903 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
906 * Writes msr value into into the appropriate "register".
907 * Returns 0 on success, non-0 otherwise.
908 * Assumes vcpu_load() was already called.
910 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
915 case MSR_KERNEL_GS_BASE:
918 if (is_noncanonical_address(data))
921 case MSR_IA32_SYSENTER_EIP:
922 case MSR_IA32_SYSENTER_ESP:
924 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
925 * non-canonical address is written on Intel but not on
926 * AMD (which ignores the top 32-bits, because it does
927 * not implement 64-bit SYSENTER).
929 * 64-bit code should hence be able to write a non-canonical
930 * value on AMD. Making the address canonical ensures that
931 * vmentry does not fail on Intel after writing a non-canonical
932 * value, and that something deterministic happens if the guest
933 * invokes 64-bit SYSENTER.
935 data = get_canonical(data);
937 return kvm_x86_ops->set_msr(vcpu, msr_index, data);
939 EXPORT_SYMBOL_GPL(kvm_set_msr);
942 * Adapt set_msr() to msr_io()'s calling convention
944 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
946 return kvm_set_msr(vcpu, index, *data);
949 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
953 struct pvclock_wall_clock wc;
954 struct timespec boot;
959 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
964 ++version; /* first time write, random junk */
968 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
971 * The guest calculates current wall clock time by adding
972 * system time (updated by kvm_guest_time_update below) to the
973 * wall clock specified here. guest system time equals host
974 * system time for us, thus we must fill in host boot time here.
978 wc.sec = boot.tv_sec;
979 wc.nsec = boot.tv_nsec;
980 wc.version = version;
982 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
985 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
988 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
990 uint32_t quotient, remainder;
992 /* Don't try to replace with do_div(), this one calculates
993 * "(dividend << 32) / divisor" */
995 : "=a" (quotient), "=d" (remainder)
996 : "0" (0), "1" (dividend), "r" (divisor) );
1000 static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
1001 s8 *pshift, u32 *pmultiplier)
1008 tps64 = base_khz * 1000LL;
1009 scaled64 = scaled_khz * 1000LL;
1010 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1015 tps32 = (uint32_t)tps64;
1016 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1017 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1025 *pmultiplier = div_frac(scaled64, tps32);
1027 pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
1028 __func__, base_khz, scaled_khz, shift, *pmultiplier);
1031 static inline u64 get_kernel_ns(void)
1035 WARN_ON(preemptible());
1037 monotonic_to_bootbased(&ts);
1038 return timespec_to_ns(&ts);
1041 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1042 unsigned long max_tsc_khz;
1044 static inline int kvm_tsc_changes_freq(void)
1046 int cpu = get_cpu();
1047 int ret = !boot_cpu_has(X86_FEATURE_CONSTANT_TSC) &&
1048 cpufreq_quick_get(cpu) != 0;
1053 u64 vcpu_tsc_khz(struct kvm_vcpu *vcpu)
1055 if (vcpu->arch.virtual_tsc_khz)
1056 return vcpu->arch.virtual_tsc_khz;
1058 return __this_cpu_read(cpu_tsc_khz);
1061 static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
1065 WARN_ON(preemptible());
1066 if (kvm_tsc_changes_freq())
1067 printk_once(KERN_WARNING
1068 "kvm: unreliable cycle conversion on adjustable rate TSC\n");
1069 ret = nsec * vcpu_tsc_khz(vcpu);
1070 do_div(ret, USEC_PER_SEC);
1074 static void kvm_init_tsc_catchup(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
1076 /* Compute a scale to convert nanoseconds in TSC cycles */
1077 kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
1078 &vcpu->arch.tsc_catchup_shift,
1079 &vcpu->arch.tsc_catchup_mult);
1082 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1084 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.last_tsc_nsec,
1085 vcpu->arch.tsc_catchup_mult,
1086 vcpu->arch.tsc_catchup_shift);
1087 tsc += vcpu->arch.last_tsc_write;
1091 void kvm_write_tsc(struct kvm_vcpu *vcpu, u64 data)
1093 struct kvm *kvm = vcpu->kvm;
1094 u64 offset, ns, elapsed;
1095 unsigned long flags;
1098 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1099 offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
1100 ns = get_kernel_ns();
1101 elapsed = ns - kvm->arch.last_tsc_nsec;
1102 sdiff = data - kvm->arch.last_tsc_write;
1107 * Special case: close write to TSC within 5 seconds of
1108 * another CPU is interpreted as an attempt to synchronize
1109 * The 5 seconds is to accommodate host load / swapping as
1110 * well as any reset of TSC during the boot process.
1112 * In that case, for a reliable TSC, we can match TSC offsets,
1113 * or make a best guest using elapsed value.
1115 if (sdiff < nsec_to_cycles(vcpu, 5ULL * NSEC_PER_SEC) &&
1116 elapsed < 5ULL * NSEC_PER_SEC) {
1117 if (!check_tsc_unstable()) {
1118 offset = kvm->arch.last_tsc_offset;
1119 pr_debug("kvm: matched tsc offset for %llu\n", data);
1121 u64 delta = nsec_to_cycles(vcpu, elapsed);
1123 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1125 ns = kvm->arch.last_tsc_nsec;
1127 kvm->arch.last_tsc_nsec = ns;
1128 kvm->arch.last_tsc_write = data;
1129 kvm->arch.last_tsc_offset = offset;
1130 kvm_x86_ops->write_tsc_offset(vcpu, offset);
1131 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1133 /* Reset of TSC must disable overshoot protection below */
1134 vcpu->arch.hv_clock.tsc_timestamp = 0;
1135 vcpu->arch.last_tsc_write = data;
1136 vcpu->arch.last_tsc_nsec = ns;
1138 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1140 static int kvm_guest_time_update(struct kvm_vcpu *v)
1142 unsigned long flags;
1143 struct kvm_vcpu_arch *vcpu = &v->arch;
1144 unsigned long this_tsc_khz;
1145 s64 kernel_ns, max_kernel_ns;
1148 /* Keep irq disabled to prevent changes to the clock */
1149 local_irq_save(flags);
1150 tsc_timestamp = kvm_x86_ops->read_l1_tsc(v);
1151 kernel_ns = get_kernel_ns();
1152 this_tsc_khz = vcpu_tsc_khz(v);
1153 if (unlikely(this_tsc_khz == 0)) {
1154 local_irq_restore(flags);
1155 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1160 * We may have to catch up the TSC to match elapsed wall clock
1161 * time for two reasons, even if kvmclock is used.
1162 * 1) CPU could have been running below the maximum TSC rate
1163 * 2) Broken TSC compensation resets the base at each VCPU
1164 * entry to avoid unknown leaps of TSC even when running
1165 * again on the same CPU. This may cause apparent elapsed
1166 * time to disappear, and the guest to stand still or run
1169 if (vcpu->tsc_catchup) {
1170 u64 tsc = compute_guest_tsc(v, kernel_ns);
1171 if (tsc > tsc_timestamp) {
1172 kvm_x86_ops->adjust_tsc_offset(v, tsc - tsc_timestamp);
1173 tsc_timestamp = tsc;
1177 local_irq_restore(flags);
1179 if (!vcpu->pv_time_enabled)
1183 * Time as measured by the TSC may go backwards when resetting the base
1184 * tsc_timestamp. The reason for this is that the TSC resolution is
1185 * higher than the resolution of the other clock scales. Thus, many
1186 * possible measurments of the TSC correspond to one measurement of any
1187 * other clock, and so a spread of values is possible. This is not a
1188 * problem for the computation of the nanosecond clock; with TSC rates
1189 * around 1GHZ, there can only be a few cycles which correspond to one
1190 * nanosecond value, and any path through this code will inevitably
1191 * take longer than that. However, with the kernel_ns value itself,
1192 * the precision may be much lower, down to HZ granularity. If the
1193 * first sampling of TSC against kernel_ns ends in the low part of the
1194 * range, and the second in the high end of the range, we can get:
1196 * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new
1198 * As the sampling errors potentially range in the thousands of cycles,
1199 * it is possible such a time value has already been observed by the
1200 * guest. To protect against this, we must compute the system time as
1201 * observed by the guest and ensure the new system time is greater.
1204 if (vcpu->hv_clock.tsc_timestamp && vcpu->last_guest_tsc) {
1205 max_kernel_ns = vcpu->last_guest_tsc -
1206 vcpu->hv_clock.tsc_timestamp;
1207 max_kernel_ns = pvclock_scale_delta(max_kernel_ns,
1208 vcpu->hv_clock.tsc_to_system_mul,
1209 vcpu->hv_clock.tsc_shift);
1210 max_kernel_ns += vcpu->last_kernel_ns;
1213 if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
1214 kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
1215 &vcpu->hv_clock.tsc_shift,
1216 &vcpu->hv_clock.tsc_to_system_mul);
1217 vcpu->hw_tsc_khz = this_tsc_khz;
1220 if (max_kernel_ns > kernel_ns)
1221 kernel_ns = max_kernel_ns;
1223 /* With all the info we got, fill in the values */
1224 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1225 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1226 vcpu->last_kernel_ns = kernel_ns;
1227 vcpu->last_guest_tsc = tsc_timestamp;
1228 vcpu->hv_clock.flags = 0;
1231 * The interface expects us to write an even number signaling that the
1232 * update is finished. Since the guest won't see the intermediate
1233 * state, we just increase by 2 at the end.
1235 vcpu->hv_clock.version += 2;
1237 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1239 sizeof(vcpu->hv_clock));
1243 static bool msr_mtrr_valid(unsigned msr)
1246 case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
1247 case MSR_MTRRfix64K_00000:
1248 case MSR_MTRRfix16K_80000:
1249 case MSR_MTRRfix16K_A0000:
1250 case MSR_MTRRfix4K_C0000:
1251 case MSR_MTRRfix4K_C8000:
1252 case MSR_MTRRfix4K_D0000:
1253 case MSR_MTRRfix4K_D8000:
1254 case MSR_MTRRfix4K_E0000:
1255 case MSR_MTRRfix4K_E8000:
1256 case MSR_MTRRfix4K_F0000:
1257 case MSR_MTRRfix4K_F8000:
1258 case MSR_MTRRdefType:
1259 case MSR_IA32_CR_PAT:
1267 static bool valid_pat_type(unsigned t)
1269 return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
1272 static bool valid_mtrr_type(unsigned t)
1274 return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
1277 bool kvm_mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1281 if (!msr_mtrr_valid(msr))
1284 if (msr == MSR_IA32_CR_PAT) {
1285 for (i = 0; i < 8; i++)
1286 if (!valid_pat_type((data >> (i * 8)) & 0xff))
1289 } else if (msr == MSR_MTRRdefType) {
1292 return valid_mtrr_type(data & 0xff);
1293 } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
1294 for (i = 0; i < 8 ; i++)
1295 if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
1300 /* variable MTRRs */
1301 return valid_mtrr_type(data & 0xff);
1303 EXPORT_SYMBOL_GPL(kvm_mtrr_valid);
1305 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1307 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1309 if (!kvm_mtrr_valid(vcpu, msr, data))
1312 if (msr == MSR_MTRRdefType) {
1313 vcpu->arch.mtrr_state.def_type = data;
1314 vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
1315 } else if (msr == MSR_MTRRfix64K_00000)
1317 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1318 p[1 + msr - MSR_MTRRfix16K_80000] = data;
1319 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1320 p[3 + msr - MSR_MTRRfix4K_C0000] = data;
1321 else if (msr == MSR_IA32_CR_PAT)
1322 vcpu->arch.pat = data;
1323 else { /* Variable MTRRs */
1324 int idx, is_mtrr_mask;
1327 idx = (msr - 0x200) / 2;
1328 is_mtrr_mask = msr - 0x200 - 2 * idx;
1331 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1334 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1338 kvm_mmu_reset_context(vcpu);
1342 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1344 u64 mcg_cap = vcpu->arch.mcg_cap;
1345 unsigned bank_num = mcg_cap & 0xff;
1348 case MSR_IA32_MCG_STATUS:
1349 vcpu->arch.mcg_status = data;
1351 case MSR_IA32_MCG_CTL:
1352 if (!(mcg_cap & MCG_CTL_P))
1354 if (data != 0 && data != ~(u64)0)
1356 vcpu->arch.mcg_ctl = data;
1359 if (msr >= MSR_IA32_MC0_CTL &&
1360 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1361 u32 offset = msr - MSR_IA32_MC0_CTL;
1362 /* only 0 or all 1s can be written to IA32_MCi_CTL
1363 * some Linux kernels though clear bit 10 in bank 4 to
1364 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
1365 * this to avoid an uncatched #GP in the guest
1367 if ((offset & 0x3) == 0 &&
1368 data != 0 && (data | (1 << 10)) != ~(u64)0)
1370 vcpu->arch.mce_banks[offset] = data;
1378 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
1380 struct kvm *kvm = vcpu->kvm;
1381 int lm = is_long_mode(vcpu);
1382 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
1383 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
1384 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
1385 : kvm->arch.xen_hvm_config.blob_size_32;
1386 u32 page_num = data & ~PAGE_MASK;
1387 u64 page_addr = data & PAGE_MASK;
1392 if (page_num >= blob_size)
1395 page = kzalloc(PAGE_SIZE, GFP_KERNEL);
1399 if (copy_from_user(page, blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE))
1401 if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
1410 static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
1412 return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
1415 static bool kvm_hv_msr_partition_wide(u32 msr)
1419 case HV_X64_MSR_GUEST_OS_ID:
1420 case HV_X64_MSR_HYPERCALL:
1428 static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1430 struct kvm *kvm = vcpu->kvm;
1433 case HV_X64_MSR_GUEST_OS_ID:
1434 kvm->arch.hv_guest_os_id = data;
1435 /* setting guest os id to zero disables hypercall page */
1436 if (!kvm->arch.hv_guest_os_id)
1437 kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
1439 case HV_X64_MSR_HYPERCALL: {
1444 /* if guest os id is not set hypercall should remain disabled */
1445 if (!kvm->arch.hv_guest_os_id)
1447 if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
1448 kvm->arch.hv_hypercall = data;
1451 gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
1452 addr = gfn_to_hva(kvm, gfn);
1453 if (kvm_is_error_hva(addr))
1455 kvm_x86_ops->patch_hypercall(vcpu, instructions);
1456 ((unsigned char *)instructions)[3] = 0xc3; /* ret */
1457 if (__copy_to_user((void __user *)addr, instructions, 4))
1459 kvm->arch.hv_hypercall = data;
1463 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1464 "data 0x%llx\n", msr, data);
1470 static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1473 case HV_X64_MSR_APIC_ASSIST_PAGE: {
1476 if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
1477 vcpu->arch.hv_vapic = data;
1480 addr = gfn_to_hva(vcpu->kvm, data >>
1481 HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
1482 if (kvm_is_error_hva(addr))
1484 if (__clear_user((void __user *)addr, PAGE_SIZE))
1486 vcpu->arch.hv_vapic = data;
1489 case HV_X64_MSR_EOI:
1490 return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
1491 case HV_X64_MSR_ICR:
1492 return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
1493 case HV_X64_MSR_TPR:
1494 return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
1496 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1497 "data 0x%llx\n", msr, data);
1504 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
1506 gpa_t gpa = data & ~0x3f;
1508 /* Bits 2:5 are resrved, Should be zero */
1512 vcpu->arch.apf.msr_val = data;
1514 if (!(data & KVM_ASYNC_PF_ENABLED)) {
1515 kvm_clear_async_pf_completion_queue(vcpu);
1516 kvm_async_pf_hash_reset(vcpu);
1520 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
1524 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
1525 kvm_async_pf_wakeup_all(vcpu);
1529 static void kvmclock_reset(struct kvm_vcpu *vcpu)
1531 vcpu->arch.pv_time_enabled = false;
1534 static void accumulate_steal_time(struct kvm_vcpu *vcpu)
1538 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1541 delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
1542 vcpu->arch.st.last_steal = current->sched_info.run_delay;
1543 vcpu->arch.st.accum_steal = delta;
1546 static void record_steal_time(struct kvm_vcpu *vcpu)
1548 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1551 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1552 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
1555 vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
1556 vcpu->arch.st.steal.version += 2;
1557 vcpu->arch.st.accum_steal = 0;
1559 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1560 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
1563 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1567 return set_efer(vcpu, data);
1569 data &= ~(u64)0x40; /* ignore flush filter disable */
1570 data &= ~(u64)0x100; /* ignore ignne emulation enable */
1572 pr_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
1577 case MSR_FAM10H_MMIO_CONF_BASE:
1579 pr_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
1584 case MSR_AMD64_NB_CFG:
1586 case MSR_IA32_DEBUGCTLMSR:
1588 /* We support the non-activated case already */
1590 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
1591 /* Values other than LBR and BTF are vendor-specific,
1592 thus reserved and should throw a #GP */
1595 pr_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
1598 case MSR_IA32_UCODE_REV:
1599 case MSR_IA32_UCODE_WRITE:
1600 case MSR_VM_HSAVE_PA:
1601 case MSR_AMD64_PATCH_LOADER:
1603 case 0x200 ... 0x2ff:
1604 return set_msr_mtrr(vcpu, msr, data);
1605 case MSR_IA32_APICBASE:
1606 kvm_set_apic_base(vcpu, data);
1608 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1609 return kvm_x2apic_msr_write(vcpu, msr, data);
1610 case MSR_IA32_TSCDEADLINE:
1611 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1613 case MSR_IA32_MISC_ENABLE:
1614 vcpu->arch.ia32_misc_enable_msr = data;
1616 case MSR_KVM_WALL_CLOCK_NEW:
1617 case MSR_KVM_WALL_CLOCK:
1618 vcpu->kvm->arch.wall_clock = data;
1619 kvm_write_wall_clock(vcpu->kvm, data);
1621 case MSR_KVM_SYSTEM_TIME_NEW:
1622 case MSR_KVM_SYSTEM_TIME: {
1624 kvmclock_reset(vcpu);
1626 vcpu->arch.time = data;
1627 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1629 /* we verify if the enable bit is set... */
1633 gpa_offset = data & ~(PAGE_MASK | 1);
1635 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
1636 &vcpu->arch.pv_time, data & ~1ULL,
1637 sizeof(struct pvclock_vcpu_time_info)))
1638 vcpu->arch.pv_time_enabled = false;
1640 vcpu->arch.pv_time_enabled = true;
1643 case MSR_KVM_ASYNC_PF_EN:
1644 if (kvm_pv_enable_async_pf(vcpu, data))
1647 case MSR_KVM_STEAL_TIME:
1649 if (unlikely(!sched_info_on()))
1652 if (data & KVM_STEAL_RESERVED_MASK)
1655 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
1656 data & KVM_STEAL_VALID_BITS,
1657 sizeof(struct kvm_steal_time)))
1660 vcpu->arch.st.msr_val = data;
1662 if (!(data & KVM_MSR_ENABLED))
1665 vcpu->arch.st.last_steal = current->sched_info.run_delay;
1668 accumulate_steal_time(vcpu);
1671 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
1675 case MSR_IA32_MCG_CTL:
1676 case MSR_IA32_MCG_STATUS:
1677 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1678 return set_msr_mce(vcpu, msr, data);
1680 /* Performance counters are not protected by a CPUID bit,
1681 * so we should check all of them in the generic path for the sake of
1682 * cross vendor migration.
1683 * Writing a zero into the event select MSRs disables them,
1684 * which we perfectly emulate ;-). Any other value should be at least
1685 * reported, some guests depend on them.
1687 case MSR_P6_EVNTSEL0:
1688 case MSR_P6_EVNTSEL1:
1689 case MSR_K7_EVNTSEL0:
1690 case MSR_K7_EVNTSEL1:
1691 case MSR_K7_EVNTSEL2:
1692 case MSR_K7_EVNTSEL3:
1694 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1695 "0x%x data 0x%llx\n", msr, data);
1697 /* at least RHEL 4 unconditionally writes to the perfctr registers,
1698 * so we ignore writes to make it happy.
1700 case MSR_P6_PERFCTR0:
1701 case MSR_P6_PERFCTR1:
1702 case MSR_K7_PERFCTR0:
1703 case MSR_K7_PERFCTR1:
1704 case MSR_K7_PERFCTR2:
1705 case MSR_K7_PERFCTR3:
1706 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1707 "0x%x data 0x%llx\n", msr, data);
1709 case MSR_K7_CLK_CTL:
1711 * Ignore all writes to this no longer documented MSR.
1712 * Writes are only relevant for old K7 processors,
1713 * all pre-dating SVM, but a recommended workaround from
1714 * AMD for these chips. It is possible to speicify the
1715 * affected processor models on the command line, hence
1716 * the need to ignore the workaround.
1719 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1720 if (kvm_hv_msr_partition_wide(msr)) {
1722 mutex_lock(&vcpu->kvm->lock);
1723 r = set_msr_hyperv_pw(vcpu, msr, data);
1724 mutex_unlock(&vcpu->kvm->lock);
1727 return set_msr_hyperv(vcpu, msr, data);
1729 case MSR_IA32_BBL_CR_CTL3:
1730 /* Drop writes to this legacy MSR -- see rdmsr
1731 * counterpart for further detail.
1733 pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
1736 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
1737 return xen_hvm_config(vcpu, data);
1739 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
1743 pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
1750 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
1754 * Reads an msr value (of 'msr_index') into 'pdata'.
1755 * Returns 0 on success, non-0 otherwise.
1756 * Assumes vcpu_load() was already called.
1758 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1760 return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
1763 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1765 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1767 if (!msr_mtrr_valid(msr))
1770 if (msr == MSR_MTRRdefType)
1771 *pdata = vcpu->arch.mtrr_state.def_type +
1772 (vcpu->arch.mtrr_state.enabled << 10);
1773 else if (msr == MSR_MTRRfix64K_00000)
1775 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1776 *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
1777 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1778 *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
1779 else if (msr == MSR_IA32_CR_PAT)
1780 *pdata = vcpu->arch.pat;
1781 else { /* Variable MTRRs */
1782 int idx, is_mtrr_mask;
1785 idx = (msr - 0x200) / 2;
1786 is_mtrr_mask = msr - 0x200 - 2 * idx;
1789 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1792 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1799 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1802 u64 mcg_cap = vcpu->arch.mcg_cap;
1803 unsigned bank_num = mcg_cap & 0xff;
1806 case MSR_IA32_P5_MC_ADDR:
1807 case MSR_IA32_P5_MC_TYPE:
1810 case MSR_IA32_MCG_CAP:
1811 data = vcpu->arch.mcg_cap;
1813 case MSR_IA32_MCG_CTL:
1814 if (!(mcg_cap & MCG_CTL_P))
1816 data = vcpu->arch.mcg_ctl;
1818 case MSR_IA32_MCG_STATUS:
1819 data = vcpu->arch.mcg_status;
1822 if (msr >= MSR_IA32_MC0_CTL &&
1823 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1824 u32 offset = msr - MSR_IA32_MC0_CTL;
1825 data = vcpu->arch.mce_banks[offset];
1834 static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1837 struct kvm *kvm = vcpu->kvm;
1840 case HV_X64_MSR_GUEST_OS_ID:
1841 data = kvm->arch.hv_guest_os_id;
1843 case HV_X64_MSR_HYPERCALL:
1844 data = kvm->arch.hv_hypercall;
1847 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1855 static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1860 case HV_X64_MSR_VP_INDEX: {
1863 kvm_for_each_vcpu(r, v, vcpu->kvm)
1868 case HV_X64_MSR_EOI:
1869 return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
1870 case HV_X64_MSR_ICR:
1871 return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
1872 case HV_X64_MSR_TPR:
1873 return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
1874 case HV_X64_MSR_APIC_ASSIST_PAGE:
1875 data = vcpu->arch.hv_vapic;
1878 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1885 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1890 case MSR_IA32_PLATFORM_ID:
1891 case MSR_IA32_EBL_CR_POWERON:
1892 case MSR_IA32_DEBUGCTLMSR:
1893 case MSR_IA32_LASTBRANCHFROMIP:
1894 case MSR_IA32_LASTBRANCHTOIP:
1895 case MSR_IA32_LASTINTFROMIP:
1896 case MSR_IA32_LASTINTTOIP:
1898 case MSR_K8_TSEG_ADDR:
1899 case MSR_K8_TSEG_MASK:
1901 case MSR_VM_HSAVE_PA:
1902 case MSR_P6_PERFCTR0:
1903 case MSR_P6_PERFCTR1:
1904 case MSR_P6_EVNTSEL0:
1905 case MSR_P6_EVNTSEL1:
1906 case MSR_K7_EVNTSEL0:
1907 case MSR_K7_PERFCTR0:
1908 case MSR_K8_INT_PENDING_MSG:
1909 case MSR_AMD64_NB_CFG:
1910 case MSR_FAM10H_MMIO_CONF_BASE:
1913 case MSR_IA32_UCODE_REV:
1914 data = 0x100000000ULL;
1917 data = 0x500 | KVM_NR_VAR_MTRR;
1919 case 0x200 ... 0x2ff:
1920 return get_msr_mtrr(vcpu, msr, pdata);
1921 case 0xcd: /* fsb frequency */
1925 * MSR_EBC_FREQUENCY_ID
1926 * Conservative value valid for even the basic CPU models.
1927 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
1928 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
1929 * and 266MHz for model 3, or 4. Set Core Clock
1930 * Frequency to System Bus Frequency Ratio to 1 (bits
1931 * 31:24) even though these are only valid for CPU
1932 * models > 2, however guests may end up dividing or
1933 * multiplying by zero otherwise.
1935 case MSR_EBC_FREQUENCY_ID:
1938 case MSR_IA32_APICBASE:
1939 data = kvm_get_apic_base(vcpu);
1941 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1942 return kvm_x2apic_msr_read(vcpu, msr, pdata);
1944 case MSR_IA32_TSCDEADLINE:
1945 data = kvm_get_lapic_tscdeadline_msr(vcpu);
1947 case MSR_IA32_MISC_ENABLE:
1948 data = vcpu->arch.ia32_misc_enable_msr;
1950 case MSR_IA32_PERF_STATUS:
1951 /* TSC increment by tick */
1953 /* CPU multiplier */
1954 data |= (((uint64_t)4ULL) << 40);
1957 data = vcpu->arch.efer;
1959 case MSR_KVM_WALL_CLOCK:
1960 case MSR_KVM_WALL_CLOCK_NEW:
1961 data = vcpu->kvm->arch.wall_clock;
1963 case MSR_KVM_SYSTEM_TIME:
1964 case MSR_KVM_SYSTEM_TIME_NEW:
1965 data = vcpu->arch.time;
1967 case MSR_KVM_ASYNC_PF_EN:
1968 data = vcpu->arch.apf.msr_val;
1970 case MSR_KVM_STEAL_TIME:
1971 data = vcpu->arch.st.msr_val;
1973 case MSR_IA32_P5_MC_ADDR:
1974 case MSR_IA32_P5_MC_TYPE:
1975 case MSR_IA32_MCG_CAP:
1976 case MSR_IA32_MCG_CTL:
1977 case MSR_IA32_MCG_STATUS:
1978 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1979 return get_msr_mce(vcpu, msr, pdata);
1980 case MSR_K7_CLK_CTL:
1982 * Provide expected ramp-up count for K7. All other
1983 * are set to zero, indicating minimum divisors for
1986 * This prevents guest kernels on AMD host with CPU
1987 * type 6, model 8 and higher from exploding due to
1988 * the rdmsr failing.
1992 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1993 if (kvm_hv_msr_partition_wide(msr)) {
1995 mutex_lock(&vcpu->kvm->lock);
1996 r = get_msr_hyperv_pw(vcpu, msr, pdata);
1997 mutex_unlock(&vcpu->kvm->lock);
2000 return get_msr_hyperv(vcpu, msr, pdata);
2002 case MSR_IA32_BBL_CR_CTL3:
2003 /* This legacy MSR exists but isn't fully documented in current
2004 * silicon. It is however accessed by winxp in very narrow
2005 * scenarios where it sets bit #19, itself documented as
2006 * a "reserved" bit. Best effort attempt to source coherent
2007 * read data here should the balance of the register be
2008 * interpreted by the guest:
2010 * L2 cache control register 3: 64GB range, 256KB size,
2011 * enabled, latency 0x1, configured
2017 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
2020 pr_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
2028 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2031 * Read or write a bunch of msrs. All parameters are kernel addresses.
2033 * @return number of msrs set successfully.
2035 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2036 struct kvm_msr_entry *entries,
2037 int (*do_msr)(struct kvm_vcpu *vcpu,
2038 unsigned index, u64 *data))
2042 idx = srcu_read_lock(&vcpu->kvm->srcu);
2043 for (i = 0; i < msrs->nmsrs; ++i)
2044 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2046 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2052 * Read or write a bunch of msrs. Parameters are user addresses.
2054 * @return number of msrs set successfully.
2056 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2057 int (*do_msr)(struct kvm_vcpu *vcpu,
2058 unsigned index, u64 *data),
2061 struct kvm_msrs msrs;
2062 struct kvm_msr_entry *entries;
2067 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2071 if (msrs.nmsrs >= MAX_IO_MSRS)
2075 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2076 entries = kmalloc(size, GFP_KERNEL);
2081 if (copy_from_user(entries, user_msrs->entries, size))
2084 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2089 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2100 int kvm_dev_ioctl_check_extension(long ext)
2105 case KVM_CAP_IRQCHIP:
2107 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2108 case KVM_CAP_SET_TSS_ADDR:
2109 case KVM_CAP_EXT_CPUID:
2110 case KVM_CAP_CLOCKSOURCE:
2112 case KVM_CAP_NOP_IO_DELAY:
2113 case KVM_CAP_MP_STATE:
2114 case KVM_CAP_SYNC_MMU:
2115 case KVM_CAP_USER_NMI:
2116 case KVM_CAP_REINJECT_CONTROL:
2117 case KVM_CAP_IRQ_INJECT_STATUS:
2118 case KVM_CAP_ASSIGN_DEV_IRQ:
2120 case KVM_CAP_IOEVENTFD:
2122 case KVM_CAP_PIT_STATE2:
2123 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2124 case KVM_CAP_XEN_HVM:
2125 case KVM_CAP_ADJUST_CLOCK:
2126 case KVM_CAP_VCPU_EVENTS:
2127 case KVM_CAP_HYPERV:
2128 case KVM_CAP_HYPERV_VAPIC:
2129 case KVM_CAP_HYPERV_SPIN:
2130 case KVM_CAP_PCI_SEGMENT:
2131 case KVM_CAP_DEBUGREGS:
2132 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2134 case KVM_CAP_ASYNC_PF:
2135 case KVM_CAP_GET_TSC_KHZ:
2138 case KVM_CAP_COALESCED_MMIO:
2139 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2142 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2144 case KVM_CAP_NR_VCPUS:
2145 r = KVM_SOFT_MAX_VCPUS;
2147 case KVM_CAP_MAX_VCPUS:
2150 case KVM_CAP_NR_MEMSLOTS:
2151 r = KVM_MEMORY_SLOTS;
2153 case KVM_CAP_PV_MMU: /* obsolete */
2157 r = iommu_present(&pci_bus_type);
2160 r = KVM_MAX_MCE_BANKS;
2165 case KVM_CAP_TSC_CONTROL:
2166 r = kvm_has_tsc_control;
2168 case KVM_CAP_TSC_DEADLINE_TIMER:
2169 r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
2179 long kvm_arch_dev_ioctl(struct file *filp,
2180 unsigned int ioctl, unsigned long arg)
2182 void __user *argp = (void __user *)arg;
2186 case KVM_GET_MSR_INDEX_LIST: {
2187 struct kvm_msr_list __user *user_msr_list = argp;
2188 struct kvm_msr_list msr_list;
2192 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2195 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
2196 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2199 if (n < msr_list.nmsrs)
2202 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2203 num_msrs_to_save * sizeof(u32)))
2205 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2207 ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
2212 case KVM_GET_SUPPORTED_CPUID: {
2213 struct kvm_cpuid2 __user *cpuid_arg = argp;
2214 struct kvm_cpuid2 cpuid;
2217 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2219 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
2220 cpuid_arg->entries);
2225 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2230 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2233 mce_cap = KVM_MCE_CAP_SUPPORTED;
2235 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2247 static void wbinvd_ipi(void *garbage)
2252 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2254 return vcpu->kvm->arch.iommu_domain &&
2255 !(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY);
2258 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2260 /* Address WBINVD may be executed by guest */
2261 if (need_emulate_wbinvd(vcpu)) {
2262 if (kvm_x86_ops->has_wbinvd_exit())
2263 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2264 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2265 smp_call_function_single(vcpu->cpu,
2266 wbinvd_ipi, NULL, 1);
2269 kvm_x86_ops->vcpu_load(vcpu, cpu);
2270 if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2271 /* Make sure TSC doesn't go backwards */
2275 tsc = kvm_x86_ops->read_l1_tsc(vcpu);
2276 tsc_delta = !vcpu->arch.last_guest_tsc ? 0 :
2277 tsc - vcpu->arch.last_guest_tsc;
2280 mark_tsc_unstable("KVM discovered backwards TSC");
2281 if (check_tsc_unstable()) {
2282 kvm_x86_ops->adjust_tsc_offset(vcpu, -tsc_delta);
2283 vcpu->arch.tsc_catchup = 1;
2285 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2286 if (vcpu->cpu != cpu)
2287 kvm_migrate_timers(vcpu);
2291 accumulate_steal_time(vcpu);
2292 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2295 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2297 kvm_x86_ops->vcpu_put(vcpu);
2298 kvm_put_guest_fpu(vcpu);
2299 vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu);
2302 static int is_efer_nx(void)
2304 unsigned long long efer = 0;
2306 rdmsrl_safe(MSR_EFER, &efer);
2307 return efer & EFER_NX;
2310 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
2313 struct kvm_cpuid_entry2 *e, *entry;
2316 for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
2317 e = &vcpu->arch.cpuid_entries[i];
2318 if (e->function == 0x80000001) {
2323 if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
2324 entry->edx &= ~(1 << 20);
2325 printk(KERN_INFO "kvm: guest NX capability removed\n");
2329 /* when an old userspace process fills a new kernel module */
2330 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
2331 struct kvm_cpuid *cpuid,
2332 struct kvm_cpuid_entry __user *entries)
2335 struct kvm_cpuid_entry *cpuid_entries;
2338 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2341 cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
2345 if (copy_from_user(cpuid_entries, entries,
2346 cpuid->nent * sizeof(struct kvm_cpuid_entry)))
2348 for (i = 0; i < cpuid->nent; i++) {
2349 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
2350 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
2351 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
2352 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
2353 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
2354 vcpu->arch.cpuid_entries[i].index = 0;
2355 vcpu->arch.cpuid_entries[i].flags = 0;
2356 vcpu->arch.cpuid_entries[i].padding[0] = 0;
2357 vcpu->arch.cpuid_entries[i].padding[1] = 0;
2358 vcpu->arch.cpuid_entries[i].padding[2] = 0;
2360 vcpu->arch.cpuid_nent = cpuid->nent;
2361 cpuid_fix_nx_cap(vcpu);
2363 kvm_apic_set_version(vcpu);
2364 kvm_x86_ops->cpuid_update(vcpu);
2368 vfree(cpuid_entries);
2373 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
2374 struct kvm_cpuid2 *cpuid,
2375 struct kvm_cpuid_entry2 __user *entries)
2380 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2383 if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
2384 cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
2386 vcpu->arch.cpuid_nent = cpuid->nent;
2387 kvm_apic_set_version(vcpu);
2388 kvm_x86_ops->cpuid_update(vcpu);
2396 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
2397 struct kvm_cpuid2 *cpuid,
2398 struct kvm_cpuid_entry2 __user *entries)
2403 if (cpuid->nent < vcpu->arch.cpuid_nent)
2406 if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
2407 vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
2412 cpuid->nent = vcpu->arch.cpuid_nent;
2416 static void cpuid_mask(u32 *word, int wordnum)
2418 *word &= boot_cpu_data.x86_capability[wordnum];
2421 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
2424 entry->function = function;
2425 entry->index = index;
2426 cpuid_count(entry->function, entry->index,
2427 &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
2431 static bool supported_xcr0_bit(unsigned bit)
2433 u64 mask = ((u64)1 << bit);
2435 return mask & (XSTATE_FP | XSTATE_SSE | XSTATE_YMM) & host_xcr0;
2438 #define F(x) bit(X86_FEATURE_##x)
2440 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
2441 u32 index, int *nent, int maxnent)
2443 unsigned f_nx = is_efer_nx() ? F(NX) : 0;
2444 #ifdef CONFIG_X86_64
2445 unsigned f_gbpages = (kvm_x86_ops->get_lpage_level() == PT_PDPE_LEVEL)
2447 unsigned f_lm = F(LM);
2449 unsigned f_gbpages = 0;
2452 unsigned f_rdtscp = kvm_x86_ops->rdtscp_supported() ? F(RDTSCP) : 0;
2455 const u32 kvm_supported_word0_x86_features =
2456 F(FPU) | F(VME) | F(DE) | F(PSE) |
2457 F(TSC) | F(MSR) | F(PAE) | F(MCE) |
2458 F(CX8) | F(APIC) | 0 /* Reserved */ | F(SEP) |
2459 F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
2460 F(PAT) | F(PSE36) | 0 /* PSN */ | F(CLFLSH) |
2461 0 /* Reserved, DS, ACPI */ | F(MMX) |
2462 F(FXSR) | F(XMM) | F(XMM2) | F(SELFSNOOP) |
2463 0 /* HTT, TM, Reserved, PBE */;
2464 /* cpuid 0x80000001.edx */
2465 const u32 kvm_supported_word1_x86_features =
2466 F(FPU) | F(VME) | F(DE) | F(PSE) |
2467 F(TSC) | F(MSR) | F(PAE) | F(MCE) |
2468 F(CX8) | F(APIC) | 0 /* Reserved */ | F(SYSCALL) |
2469 F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
2470 F(PAT) | F(PSE36) | 0 /* Reserved */ |
2471 f_nx | 0 /* Reserved */ | F(MMXEXT) | F(MMX) |
2472 F(FXSR) | F(FXSR_OPT) | f_gbpages | f_rdtscp |
2473 0 /* Reserved */ | f_lm | F(3DNOWEXT) | F(3DNOW);
2475 const u32 kvm_supported_word4_x86_features =
2476 F(XMM3) | F(PCLMULQDQ) | 0 /* DTES64, MONITOR */ |
2477 0 /* DS-CPL, VMX, SMX, EST */ |
2478 0 /* TM2 */ | F(SSSE3) | 0 /* CNXT-ID */ | 0 /* Reserved */ |
2479 0 /* Reserved */ | F(CX16) | 0 /* xTPR Update, PDCM */ |
2480 0 /* Reserved, DCA */ | F(XMM4_1) |
2481 F(XMM4_2) | F(X2APIC) | F(MOVBE) | F(POPCNT) |
2482 0 /* Reserved*/ | F(AES) | F(XSAVE) | 0 /* OSXSAVE */ | F(AVX) |
2483 F(F16C) | F(RDRAND);
2484 /* cpuid 0x80000001.ecx */
2485 const u32 kvm_supported_word6_x86_features =
2486 F(LAHF_LM) | F(CMP_LEGACY) | 0 /*SVM*/ | 0 /* ExtApicSpace */ |
2487 F(CR8_LEGACY) | F(ABM) | F(SSE4A) | F(MISALIGNSSE) |
2488 F(3DNOWPREFETCH) | 0 /* OSVW */ | 0 /* IBS */ | F(XOP) |
2489 0 /* SKINIT, WDT, LWP */ | F(FMA4) | F(TBM);
2491 /* cpuid 0xC0000001.edx */
2492 const u32 kvm_supported_word5_x86_features =
2493 F(XSTORE) | F(XSTORE_EN) | F(XCRYPT) | F(XCRYPT_EN) |
2494 F(ACE2) | F(ACE2_EN) | F(PHE) | F(PHE_EN) |
2498 const u32 kvm_supported_word9_x86_features =
2499 F(SMEP) | F(FSGSBASE) | F(ERMS);
2501 /* all calls to cpuid_count() should be made on the same cpu */
2503 do_cpuid_1_ent(entry, function, index);
2508 entry->eax = min(entry->eax, (u32)0xd);
2511 entry->edx &= kvm_supported_word0_x86_features;
2512 cpuid_mask(&entry->edx, 0);
2513 entry->ecx &= kvm_supported_word4_x86_features;
2514 cpuid_mask(&entry->ecx, 4);
2515 /* we support x2apic emulation even if host does not support
2516 * it since we emulate x2apic in software */
2517 entry->ecx |= F(X2APIC);
2519 /* function 2 entries are STATEFUL. That is, repeated cpuid commands
2520 * may return different values. This forces us to get_cpu() before
2521 * issuing the first command, and also to emulate this annoying behavior
2522 * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
2524 int t, times = entry->eax & 0xff;
2526 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
2527 entry->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
2528 for (t = 1; t < times && *nent < maxnent; ++t) {
2529 do_cpuid_1_ent(&entry[t], function, 0);
2530 entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
2535 /* function 4 has additional index. */
2539 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2540 /* read more entries until cache_type is zero */
2541 for (i = 1; *nent < maxnent; ++i) {
2542 cache_type = entry[i - 1].eax & 0x1f;
2545 do_cpuid_1_ent(&entry[i], function, i);
2547 KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2553 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2554 /* Mask ebx against host capbability word 9 */
2556 entry->ebx &= kvm_supported_word9_x86_features;
2557 cpuid_mask(&entry->ebx, 9);
2567 /* function 0xb has additional index. */
2571 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2572 /* read more entries until level_type is zero */
2573 for (i = 1; *nent < maxnent; ++i) {
2574 level_type = entry[i - 1].ecx & 0xff00;
2577 do_cpuid_1_ent(&entry[i], function, i);
2579 KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2587 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2588 for (idx = 1, i = 1; *nent < maxnent && idx < 64; ++idx) {
2589 do_cpuid_1_ent(&entry[i], function, idx);
2590 if (entry[i].eax == 0 || !supported_xcr0_bit(idx))
2593 KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2599 case KVM_CPUID_SIGNATURE: {
2600 char signature[12] = "KVMKVMKVM\0\0";
2601 u32 *sigptr = (u32 *)signature;
2603 entry->ebx = sigptr[0];
2604 entry->ecx = sigptr[1];
2605 entry->edx = sigptr[2];
2608 case KVM_CPUID_FEATURES:
2609 entry->eax = (1 << KVM_FEATURE_CLOCKSOURCE) |
2610 (1 << KVM_FEATURE_NOP_IO_DELAY) |
2611 (1 << KVM_FEATURE_CLOCKSOURCE2) |
2612 (1 << KVM_FEATURE_ASYNC_PF) |
2613 (1 << KVM_FEATURE_CLOCKSOURCE_STABLE_BIT);
2615 if (sched_info_on())
2616 entry->eax |= (1 << KVM_FEATURE_STEAL_TIME);
2623 entry->eax = min(entry->eax, 0x8000001a);
2626 entry->edx &= kvm_supported_word1_x86_features;
2627 cpuid_mask(&entry->edx, 1);
2628 entry->ecx &= kvm_supported_word6_x86_features;
2629 cpuid_mask(&entry->ecx, 6);
2632 unsigned g_phys_as = (entry->eax >> 16) & 0xff;
2633 unsigned virt_as = max((entry->eax >> 8) & 0xff, 48U);
2634 unsigned phys_as = entry->eax & 0xff;
2637 g_phys_as = phys_as;
2638 entry->eax = g_phys_as | (virt_as << 8);
2639 entry->ebx = entry->edx = 0;
2643 entry->ecx = entry->edx = 0;
2649 /*Add support for Centaur's CPUID instruction*/
2651 /*Just support up to 0xC0000004 now*/
2652 entry->eax = min(entry->eax, 0xC0000004);
2655 entry->edx &= kvm_supported_word5_x86_features;
2656 cpuid_mask(&entry->edx, 5);
2658 case 3: /* Processor serial number */
2659 case 5: /* MONITOR/MWAIT */
2660 case 6: /* Thermal management */
2661 case 0xA: /* Architectural Performance Monitoring */
2662 case 0x80000007: /* Advanced power management */
2667 entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
2671 kvm_x86_ops->set_supported_cpuid(function, entry);
2678 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
2679 struct kvm_cpuid_entry2 __user *entries)
2681 struct kvm_cpuid_entry2 *cpuid_entries;
2682 int limit, nent = 0, r = -E2BIG;
2685 if (cpuid->nent < 1)
2687 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2688 cpuid->nent = KVM_MAX_CPUID_ENTRIES;
2690 cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
2694 do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
2695 limit = cpuid_entries[0].eax;
2696 for (func = 1; func <= limit && nent < cpuid->nent; ++func)
2697 do_cpuid_ent(&cpuid_entries[nent], func, 0,
2698 &nent, cpuid->nent);
2700 if (nent >= cpuid->nent)
2703 do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
2704 limit = cpuid_entries[nent - 1].eax;
2705 for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
2706 do_cpuid_ent(&cpuid_entries[nent], func, 0,
2707 &nent, cpuid->nent);
2712 if (nent >= cpuid->nent)
2715 /* Add support for Centaur's CPUID instruction. */
2716 if (boot_cpu_data.x86_vendor == X86_VENDOR_CENTAUR) {
2717 do_cpuid_ent(&cpuid_entries[nent], 0xC0000000, 0,
2718 &nent, cpuid->nent);
2721 if (nent >= cpuid->nent)
2724 limit = cpuid_entries[nent - 1].eax;
2725 for (func = 0xC0000001;
2726 func <= limit && nent < cpuid->nent; ++func)
2727 do_cpuid_ent(&cpuid_entries[nent], func, 0,
2728 &nent, cpuid->nent);
2731 if (nent >= cpuid->nent)
2735 do_cpuid_ent(&cpuid_entries[nent], KVM_CPUID_SIGNATURE, 0, &nent,
2739 if (nent >= cpuid->nent)
2742 do_cpuid_ent(&cpuid_entries[nent], KVM_CPUID_FEATURES, 0, &nent,
2746 if (nent >= cpuid->nent)
2750 if (copy_to_user(entries, cpuid_entries,
2751 nent * sizeof(struct kvm_cpuid_entry2)))
2757 vfree(cpuid_entries);
2762 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2763 struct kvm_lapic_state *s)
2765 memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2770 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2771 struct kvm_lapic_state *s)
2773 memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
2774 kvm_apic_post_state_restore(vcpu);
2775 update_cr8_intercept(vcpu);
2780 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2781 struct kvm_interrupt *irq)
2783 if (irq->irq < 0 || irq->irq >= 256)
2785 if (irqchip_in_kernel(vcpu->kvm))
2788 kvm_queue_interrupt(vcpu, irq->irq, false);
2789 kvm_make_request(KVM_REQ_EVENT, vcpu);
2794 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2796 kvm_inject_nmi(vcpu);
2801 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2802 struct kvm_tpr_access_ctl *tac)
2806 vcpu->arch.tpr_access_reporting = !!tac->enabled;
2810 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2814 unsigned bank_num = mcg_cap & 0xff, bank;
2817 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2819 if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2822 vcpu->arch.mcg_cap = mcg_cap;
2823 /* Init IA32_MCG_CTL to all 1s */
2824 if (mcg_cap & MCG_CTL_P)
2825 vcpu->arch.mcg_ctl = ~(u64)0;
2826 /* Init IA32_MCi_CTL to all 1s */
2827 for (bank = 0; bank < bank_num; bank++)
2828 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2833 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2834 struct kvm_x86_mce *mce)
2836 u64 mcg_cap = vcpu->arch.mcg_cap;
2837 unsigned bank_num = mcg_cap & 0xff;
2838 u64 *banks = vcpu->arch.mce_banks;
2840 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2843 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2844 * reporting is disabled
2846 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2847 vcpu->arch.mcg_ctl != ~(u64)0)
2849 banks += 4 * mce->bank;
2851 * if IA32_MCi_CTL is not all 1s, the uncorrected error
2852 * reporting is disabled for the bank
2854 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2856 if (mce->status & MCI_STATUS_UC) {
2857 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2858 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2859 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2862 if (banks[1] & MCI_STATUS_VAL)
2863 mce->status |= MCI_STATUS_OVER;
2864 banks[2] = mce->addr;
2865 banks[3] = mce->misc;
2866 vcpu->arch.mcg_status = mce->mcg_status;
2867 banks[1] = mce->status;
2868 kvm_queue_exception(vcpu, MC_VECTOR);
2869 } else if (!(banks[1] & MCI_STATUS_VAL)
2870 || !(banks[1] & MCI_STATUS_UC)) {
2871 if (banks[1] & MCI_STATUS_VAL)
2872 mce->status |= MCI_STATUS_OVER;
2873 banks[2] = mce->addr;
2874 banks[3] = mce->misc;
2875 banks[1] = mce->status;
2877 banks[1] |= MCI_STATUS_OVER;
2881 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2882 struct kvm_vcpu_events *events)
2885 events->exception.injected =
2886 vcpu->arch.exception.pending &&
2887 !kvm_exception_is_soft(vcpu->arch.exception.nr);
2888 events->exception.nr = vcpu->arch.exception.nr;
2889 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2890 events->exception.pad = 0;
2891 events->exception.error_code = vcpu->arch.exception.error_code;
2893 events->interrupt.injected =
2894 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
2895 events->interrupt.nr = vcpu->arch.interrupt.nr;
2896 events->interrupt.soft = 0;
2897 events->interrupt.shadow =
2898 kvm_x86_ops->get_interrupt_shadow(vcpu,
2899 KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
2901 events->nmi.injected = vcpu->arch.nmi_injected;
2902 events->nmi.pending = vcpu->arch.nmi_pending != 0;
2903 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
2904 events->nmi.pad = 0;
2906 events->sipi_vector = vcpu->arch.sipi_vector;
2908 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
2909 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2910 | KVM_VCPUEVENT_VALID_SHADOW);
2911 memset(&events->reserved, 0, sizeof(events->reserved));
2914 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
2915 struct kvm_vcpu_events *events)
2917 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
2918 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2919 | KVM_VCPUEVENT_VALID_SHADOW))
2923 vcpu->arch.exception.pending = events->exception.injected;
2924 vcpu->arch.exception.nr = events->exception.nr;
2925 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
2926 vcpu->arch.exception.error_code = events->exception.error_code;
2928 vcpu->arch.interrupt.pending = events->interrupt.injected;
2929 vcpu->arch.interrupt.nr = events->interrupt.nr;
2930 vcpu->arch.interrupt.soft = events->interrupt.soft;
2931 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
2932 kvm_x86_ops->set_interrupt_shadow(vcpu,
2933 events->interrupt.shadow);
2935 vcpu->arch.nmi_injected = events->nmi.injected;
2936 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
2937 vcpu->arch.nmi_pending = events->nmi.pending;
2938 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
2940 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR)
2941 vcpu->arch.sipi_vector = events->sipi_vector;
2943 kvm_make_request(KVM_REQ_EVENT, vcpu);
2948 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
2949 struct kvm_debugregs *dbgregs)
2951 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
2952 dbgregs->dr6 = vcpu->arch.dr6;
2953 dbgregs->dr7 = vcpu->arch.dr7;
2955 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
2958 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
2959 struct kvm_debugregs *dbgregs)
2964 if (dbgregs->dr6 & ~0xffffffffull)
2966 if (dbgregs->dr7 & ~0xffffffffull)
2969 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
2970 vcpu->arch.dr6 = dbgregs->dr6;
2971 vcpu->arch.dr7 = dbgregs->dr7;
2976 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
2977 struct kvm_xsave *guest_xsave)
2980 memcpy(guest_xsave->region,
2981 &vcpu->arch.guest_fpu.state->xsave,
2984 memcpy(guest_xsave->region,
2985 &vcpu->arch.guest_fpu.state->fxsave,
2986 sizeof(struct i387_fxsave_struct));
2987 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
2992 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
2993 struct kvm_xsave *guest_xsave)
2996 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
2999 memcpy(&vcpu->arch.guest_fpu.state->xsave,
3000 guest_xsave->region, xstate_size);
3002 if (xstate_bv & ~XSTATE_FPSSE)
3004 memcpy(&vcpu->arch.guest_fpu.state->fxsave,
3005 guest_xsave->region, sizeof(struct i387_fxsave_struct));
3010 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3011 struct kvm_xcrs *guest_xcrs)
3013 if (!cpu_has_xsave) {
3014 guest_xcrs->nr_xcrs = 0;
3018 guest_xcrs->nr_xcrs = 1;
3019 guest_xcrs->flags = 0;
3020 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3021 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3024 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3025 struct kvm_xcrs *guest_xcrs)
3032 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3035 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3036 /* Only support XCR0 currently */
3037 if (guest_xcrs->xcrs[0].xcr == XCR_XFEATURE_ENABLED_MASK) {
3038 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3039 guest_xcrs->xcrs[0].value);
3047 long kvm_arch_vcpu_ioctl(struct file *filp,
3048 unsigned int ioctl, unsigned long arg)
3050 struct kvm_vcpu *vcpu = filp->private_data;
3051 void __user *argp = (void __user *)arg;
3054 struct kvm_lapic_state *lapic;
3055 struct kvm_xsave *xsave;
3056 struct kvm_xcrs *xcrs;
3062 case KVM_GET_LAPIC: {
3064 if (!vcpu->arch.apic)
3066 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3071 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3075 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3080 case KVM_SET_LAPIC: {
3082 if (!vcpu->arch.apic)
3084 u.lapic = kmalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3089 if (copy_from_user(u.lapic, argp, sizeof(struct kvm_lapic_state)))
3091 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3097 case KVM_INTERRUPT: {
3098 struct kvm_interrupt irq;
3101 if (copy_from_user(&irq, argp, sizeof irq))
3103 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3110 r = kvm_vcpu_ioctl_nmi(vcpu);
3116 case KVM_SET_CPUID: {
3117 struct kvm_cpuid __user *cpuid_arg = argp;
3118 struct kvm_cpuid cpuid;
3121 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3123 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3128 case KVM_SET_CPUID2: {
3129 struct kvm_cpuid2 __user *cpuid_arg = argp;
3130 struct kvm_cpuid2 cpuid;
3133 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3135 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3136 cpuid_arg->entries);
3141 case KVM_GET_CPUID2: {
3142 struct kvm_cpuid2 __user *cpuid_arg = argp;
3143 struct kvm_cpuid2 cpuid;
3146 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3148 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3149 cpuid_arg->entries);
3153 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3159 r = msr_io(vcpu, argp, kvm_get_msr, 1);
3162 r = msr_io(vcpu, argp, do_set_msr, 0);
3164 case KVM_TPR_ACCESS_REPORTING: {
3165 struct kvm_tpr_access_ctl tac;
3168 if (copy_from_user(&tac, argp, sizeof tac))
3170 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3174 if (copy_to_user(argp, &tac, sizeof tac))
3179 case KVM_SET_VAPIC_ADDR: {
3180 struct kvm_vapic_addr va;
3183 if (!irqchip_in_kernel(vcpu->kvm))
3186 if (copy_from_user(&va, argp, sizeof va))
3188 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3191 case KVM_X86_SETUP_MCE: {
3195 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3197 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3200 case KVM_X86_SET_MCE: {
3201 struct kvm_x86_mce mce;
3204 if (copy_from_user(&mce, argp, sizeof mce))
3206 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3209 case KVM_GET_VCPU_EVENTS: {
3210 struct kvm_vcpu_events events;
3212 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3215 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3220 case KVM_SET_VCPU_EVENTS: {
3221 struct kvm_vcpu_events events;
3224 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3227 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3230 case KVM_GET_DEBUGREGS: {
3231 struct kvm_debugregs dbgregs;
3233 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3236 if (copy_to_user(argp, &dbgregs,
3237 sizeof(struct kvm_debugregs)))
3242 case KVM_SET_DEBUGREGS: {
3243 struct kvm_debugregs dbgregs;
3246 if (copy_from_user(&dbgregs, argp,
3247 sizeof(struct kvm_debugregs)))
3250 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3253 case KVM_GET_XSAVE: {
3254 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3259 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3262 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3267 case KVM_SET_XSAVE: {
3268 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3274 if (copy_from_user(u.xsave, argp, sizeof(struct kvm_xsave)))
3277 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3280 case KVM_GET_XCRS: {
3281 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3286 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3289 if (copy_to_user(argp, u.xcrs,
3290 sizeof(struct kvm_xcrs)))
3295 case KVM_SET_XCRS: {
3296 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3302 if (copy_from_user(u.xcrs, argp,
3303 sizeof(struct kvm_xcrs)))
3306 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3309 case KVM_SET_TSC_KHZ: {
3313 if (!kvm_has_tsc_control)
3316 user_tsc_khz = (u32)arg;
3318 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3321 kvm_x86_ops->set_tsc_khz(vcpu, user_tsc_khz);
3326 case KVM_GET_TSC_KHZ: {
3328 if (check_tsc_unstable())
3331 r = vcpu_tsc_khz(vcpu);
3343 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3347 if (addr > (unsigned int)(-3 * PAGE_SIZE))
3349 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3353 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3356 kvm->arch.ept_identity_map_addr = ident_addr;
3360 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3361 u32 kvm_nr_mmu_pages)
3363 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3366 mutex_lock(&kvm->slots_lock);
3367 spin_lock(&kvm->mmu_lock);
3369 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3370 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3372 spin_unlock(&kvm->mmu_lock);
3373 mutex_unlock(&kvm->slots_lock);
3377 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3379 return kvm->arch.n_max_mmu_pages;
3382 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3387 switch (chip->chip_id) {
3388 case KVM_IRQCHIP_PIC_MASTER:
3389 memcpy(&chip->chip.pic,
3390 &pic_irqchip(kvm)->pics[0],
3391 sizeof(struct kvm_pic_state));
3393 case KVM_IRQCHIP_PIC_SLAVE:
3394 memcpy(&chip->chip.pic,
3395 &pic_irqchip(kvm)->pics[1],
3396 sizeof(struct kvm_pic_state));
3398 case KVM_IRQCHIP_IOAPIC:
3399 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3408 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3413 switch (chip->chip_id) {
3414 case KVM_IRQCHIP_PIC_MASTER:
3415 spin_lock(&pic_irqchip(kvm)->lock);
3416 memcpy(&pic_irqchip(kvm)->pics[0],
3418 sizeof(struct kvm_pic_state));
3419 spin_unlock(&pic_irqchip(kvm)->lock);
3421 case KVM_IRQCHIP_PIC_SLAVE:
3422 spin_lock(&pic_irqchip(kvm)->lock);
3423 memcpy(&pic_irqchip(kvm)->pics[1],
3425 sizeof(struct kvm_pic_state));
3426 spin_unlock(&pic_irqchip(kvm)->lock);
3428 case KVM_IRQCHIP_IOAPIC:
3429 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3435 kvm_pic_update_irq(pic_irqchip(kvm));
3439 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3443 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3444 memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
3445 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3449 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3453 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3454 memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
3455 for (i = 0; i < 3; i++)
3456 kvm_pit_load_count(kvm, i, ps->channels[i].count, 0);
3457 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3461 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3465 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3466 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3467 sizeof(ps->channels));
3468 ps->flags = kvm->arch.vpit->pit_state.flags;
3469 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3470 memset(&ps->reserved, 0, sizeof(ps->reserved));
3474 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3476 int r = 0, start = 0;
3478 u32 prev_legacy, cur_legacy;
3479 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3480 prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3481 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3482 if (!prev_legacy && cur_legacy)
3484 memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
3485 sizeof(kvm->arch.vpit->pit_state.channels));
3486 kvm->arch.vpit->pit_state.flags = ps->flags;
3487 for (i = 0; i < 3; i++)
3488 kvm_pit_load_count(kvm, i, kvm->arch.vpit->pit_state.channels[i].count,
3490 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3494 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3495 struct kvm_reinject_control *control)
3497 if (!kvm->arch.vpit)
3499 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3500 kvm->arch.vpit->pit_state.pit_timer.reinject = control->pit_reinject;
3501 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3506 * Get (and clear) the dirty memory log for a memory slot.
3508 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
3509 struct kvm_dirty_log *log)
3512 struct kvm_memory_slot *memslot;
3514 unsigned long is_dirty = 0;
3516 mutex_lock(&kvm->slots_lock);
3519 if (log->slot >= KVM_MEMORY_SLOTS)
3522 memslot = &kvm->memslots->memslots[log->slot];
3524 if (!memslot->dirty_bitmap)
3527 n = kvm_dirty_bitmap_bytes(memslot);
3529 for (i = 0; !is_dirty && i < n/sizeof(long); i++)
3530 is_dirty = memslot->dirty_bitmap[i];
3532 /* If nothing is dirty, don't bother messing with page tables. */
3534 struct kvm_memslots *slots, *old_slots;
3535 unsigned long *dirty_bitmap;
3537 dirty_bitmap = memslot->dirty_bitmap_head;
3538 if (memslot->dirty_bitmap == dirty_bitmap)
3539 dirty_bitmap += n / sizeof(long);
3540 memset(dirty_bitmap, 0, n);
3543 slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
3546 memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
3547 slots->memslots[log->slot].dirty_bitmap = dirty_bitmap;
3548 slots->generation++;
3550 old_slots = kvm->memslots;
3551 rcu_assign_pointer(kvm->memslots, slots);
3552 synchronize_srcu_expedited(&kvm->srcu);
3553 dirty_bitmap = old_slots->memslots[log->slot].dirty_bitmap;
3556 spin_lock(&kvm->mmu_lock);
3557 kvm_mmu_slot_remove_write_access(kvm, log->slot);
3558 spin_unlock(&kvm->mmu_lock);
3561 if (copy_to_user(log->dirty_bitmap, dirty_bitmap, n))
3565 if (clear_user(log->dirty_bitmap, n))
3571 mutex_unlock(&kvm->slots_lock);
3575 long kvm_arch_vm_ioctl(struct file *filp,
3576 unsigned int ioctl, unsigned long arg)
3578 struct kvm *kvm = filp->private_data;
3579 void __user *argp = (void __user *)arg;
3582 * This union makes it completely explicit to gcc-3.x
3583 * that these two variables' stack usage should be
3584 * combined, not added together.
3587 struct kvm_pit_state ps;
3588 struct kvm_pit_state2 ps2;
3589 struct kvm_pit_config pit_config;
3593 case KVM_SET_TSS_ADDR:
3594 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3598 case KVM_SET_IDENTITY_MAP_ADDR: {
3602 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3604 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3609 case KVM_SET_NR_MMU_PAGES:
3610 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3614 case KVM_GET_NR_MMU_PAGES:
3615 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3617 case KVM_CREATE_IRQCHIP: {
3618 struct kvm_pic *vpic;
3620 mutex_lock(&kvm->lock);
3623 goto create_irqchip_unlock;
3625 if (atomic_read(&kvm->online_vcpus))
3626 goto create_irqchip_unlock;
3628 vpic = kvm_create_pic(kvm);
3630 r = kvm_ioapic_init(kvm);
3632 mutex_lock(&kvm->slots_lock);
3633 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3635 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3637 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3639 mutex_unlock(&kvm->slots_lock);
3641 goto create_irqchip_unlock;
3644 goto create_irqchip_unlock;
3646 kvm->arch.vpic = vpic;
3648 r = kvm_setup_default_irq_routing(kvm);
3650 mutex_lock(&kvm->slots_lock);
3651 mutex_lock(&kvm->irq_lock);
3652 kvm_ioapic_destroy(kvm);
3653 kvm_destroy_pic(kvm);
3654 mutex_unlock(&kvm->irq_lock);
3655 mutex_unlock(&kvm->slots_lock);
3657 create_irqchip_unlock:
3658 mutex_unlock(&kvm->lock);
3661 case KVM_CREATE_PIT:
3662 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3664 case KVM_CREATE_PIT2:
3666 if (copy_from_user(&u.pit_config, argp,
3667 sizeof(struct kvm_pit_config)))
3670 mutex_lock(&kvm->slots_lock);
3673 goto create_pit_unlock;
3675 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3679 mutex_unlock(&kvm->slots_lock);
3681 case KVM_IRQ_LINE_STATUS:
3682 case KVM_IRQ_LINE: {
3683 struct kvm_irq_level irq_event;
3686 if (copy_from_user(&irq_event, argp, sizeof irq_event))
3689 if (irqchip_in_kernel(kvm)) {
3691 status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3692 irq_event.irq, irq_event.level);
3693 if (ioctl == KVM_IRQ_LINE_STATUS) {
3695 irq_event.status = status;
3696 if (copy_to_user(argp, &irq_event,
3704 case KVM_GET_IRQCHIP: {
3705 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3706 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
3712 if (copy_from_user(chip, argp, sizeof *chip))
3713 goto get_irqchip_out;
3715 if (!irqchip_in_kernel(kvm))
3716 goto get_irqchip_out;
3717 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3719 goto get_irqchip_out;
3721 if (copy_to_user(argp, chip, sizeof *chip))
3722 goto get_irqchip_out;
3730 case KVM_SET_IRQCHIP: {
3731 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3732 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
3738 if (copy_from_user(chip, argp, sizeof *chip))
3739 goto set_irqchip_out;
3741 if (!irqchip_in_kernel(kvm))
3742 goto set_irqchip_out;
3743 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3745 goto set_irqchip_out;
3755 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
3758 if (!kvm->arch.vpit)
3760 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
3764 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
3771 if (copy_from_user(&u.ps, argp, sizeof u.ps))
3774 if (!kvm->arch.vpit)
3776 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
3782 case KVM_GET_PIT2: {
3784 if (!kvm->arch.vpit)
3786 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
3790 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
3795 case KVM_SET_PIT2: {
3797 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
3800 if (!kvm->arch.vpit)
3802 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
3808 case KVM_REINJECT_CONTROL: {
3809 struct kvm_reinject_control control;
3811 if (copy_from_user(&control, argp, sizeof(control)))
3813 r = kvm_vm_ioctl_reinject(kvm, &control);
3819 case KVM_XEN_HVM_CONFIG: {
3821 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
3822 sizeof(struct kvm_xen_hvm_config)))
3825 if (kvm->arch.xen_hvm_config.flags)
3830 case KVM_SET_CLOCK: {
3831 struct kvm_clock_data user_ns;
3836 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
3844 local_irq_disable();
3845 now_ns = get_kernel_ns();
3846 delta = user_ns.clock - now_ns;
3848 kvm->arch.kvmclock_offset = delta;
3851 case KVM_GET_CLOCK: {
3852 struct kvm_clock_data user_ns;
3855 local_irq_disable();
3856 now_ns = get_kernel_ns();
3857 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
3860 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
3863 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
3876 static void kvm_init_msr_list(void)
3881 /* skip the first msrs in the list. KVM-specific */
3882 for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
3883 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
3886 msrs_to_save[j] = msrs_to_save[i];
3889 num_msrs_to_save = j;
3892 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
3900 if (!(vcpu->arch.apic &&
3901 !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, n, v))
3902 && kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
3913 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
3920 if (!(vcpu->arch.apic &&
3921 !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, n, v))
3922 && kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
3924 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
3934 static void kvm_set_segment(struct kvm_vcpu *vcpu,
3935 struct kvm_segment *var, int seg)
3937 kvm_x86_ops->set_segment(vcpu, var, seg);
3940 void kvm_get_segment(struct kvm_vcpu *vcpu,
3941 struct kvm_segment *var, int seg)
3943 kvm_x86_ops->get_segment(vcpu, var, seg);
3946 static gpa_t translate_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
3951 static gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
3954 struct x86_exception exception;
3956 BUG_ON(!mmu_is_nested(vcpu));
3958 /* NPT walks are always user-walks */
3959 access |= PFERR_USER_MASK;
3960 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, &exception);
3965 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
3966 struct x86_exception *exception)
3968 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3969 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3972 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
3973 struct x86_exception *exception)
3975 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3976 access |= PFERR_FETCH_MASK;
3977 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3980 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
3981 struct x86_exception *exception)
3983 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3984 access |= PFERR_WRITE_MASK;
3985 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3988 /* uses this to access any guest's mapped memory without checking CPL */
3989 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
3990 struct x86_exception *exception)
3992 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
3995 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
3996 struct kvm_vcpu *vcpu, u32 access,
3997 struct x86_exception *exception)
4000 int r = X86EMUL_CONTINUE;
4003 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4005 unsigned offset = addr & (PAGE_SIZE-1);
4006 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4009 if (gpa == UNMAPPED_GVA)
4010 return X86EMUL_PROPAGATE_FAULT;
4011 ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
4013 r = X86EMUL_IO_NEEDED;
4025 /* used for instruction fetching */
4026 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4027 gva_t addr, void *val, unsigned int bytes,
4028 struct x86_exception *exception)
4030 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4031 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4033 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
4034 access | PFERR_FETCH_MASK,
4038 int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
4039 gva_t addr, void *val, unsigned int bytes,
4040 struct x86_exception *exception)
4042 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4043 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4045 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4048 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4050 static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4051 gva_t addr, void *val, unsigned int bytes,
4052 struct x86_exception *exception)
4054 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4055 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
4058 int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4059 gva_t addr, void *val,
4061 struct x86_exception *exception)
4063 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4065 int r = X86EMUL_CONTINUE;
4068 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4071 unsigned offset = addr & (PAGE_SIZE-1);
4072 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4075 if (gpa == UNMAPPED_GVA)
4076 return X86EMUL_PROPAGATE_FAULT;
4077 ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
4079 r = X86EMUL_IO_NEEDED;
4090 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4092 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4093 gpa_t *gpa, struct x86_exception *exception,
4096 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4098 if (vcpu_match_mmio_gva(vcpu, gva) &&
4099 check_write_user_access(vcpu, write, access,
4100 vcpu->arch.access)) {
4101 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4102 (gva & (PAGE_SIZE - 1));
4103 trace_vcpu_match_mmio(gva, *gpa, write, false);
4108 access |= PFERR_WRITE_MASK;
4110 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4112 if (*gpa == UNMAPPED_GVA)
4115 /* For APIC access vmexit */
4116 if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4119 if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
4120 trace_vcpu_match_mmio(gva, *gpa, write, true);
4127 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4128 const void *val, int bytes)
4132 ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
4135 kvm_mmu_pte_write(vcpu, gpa, val, bytes, 1);
4139 struct read_write_emulator_ops {
4140 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4142 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4143 void *val, int bytes);
4144 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4145 int bytes, void *val);
4146 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4147 void *val, int bytes);
4151 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4153 if (vcpu->mmio_read_completed) {
4154 memcpy(val, vcpu->mmio_data, bytes);
4155 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4156 vcpu->mmio_phys_addr, val);
4157 vcpu->mmio_read_completed = 0;
4164 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4165 void *val, int bytes)
4167 return !kvm_read_guest(vcpu->kvm, gpa, val, bytes);
4170 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4171 void *val, int bytes)
4173 return emulator_write_phys(vcpu, gpa, val, bytes);
4176 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4178 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
4179 return vcpu_mmio_write(vcpu, gpa, bytes, val);
4182 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4183 void *val, int bytes)
4185 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
4186 return X86EMUL_IO_NEEDED;
4189 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4190 void *val, int bytes)
4192 memcpy(vcpu->mmio_data, val, bytes);
4193 memcpy(vcpu->run->mmio.data, vcpu->mmio_data, 8);
4194 return X86EMUL_CONTINUE;
4197 static struct read_write_emulator_ops read_emultor = {
4198 .read_write_prepare = read_prepare,
4199 .read_write_emulate = read_emulate,
4200 .read_write_mmio = vcpu_mmio_read,
4201 .read_write_exit_mmio = read_exit_mmio,
4204 static struct read_write_emulator_ops write_emultor = {
4205 .read_write_emulate = write_emulate,
4206 .read_write_mmio = write_mmio,
4207 .read_write_exit_mmio = write_exit_mmio,
4211 static int emulator_read_write_onepage(unsigned long addr, void *val,
4213 struct x86_exception *exception,
4214 struct kvm_vcpu *vcpu,
4215 struct read_write_emulator_ops *ops)
4219 bool write = ops->write;
4221 if (ops->read_write_prepare &&
4222 ops->read_write_prepare(vcpu, val, bytes))
4223 return X86EMUL_CONTINUE;
4225 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4228 return X86EMUL_PROPAGATE_FAULT;
4230 /* For APIC access vmexit */
4234 if (ops->read_write_emulate(vcpu, gpa, val, bytes))
4235 return X86EMUL_CONTINUE;
4239 * Is this MMIO handled locally?
4241 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4242 if (handled == bytes)
4243 return X86EMUL_CONTINUE;
4249 vcpu->mmio_needed = 1;
4250 vcpu->run->exit_reason = KVM_EXIT_MMIO;
4251 vcpu->run->mmio.phys_addr = vcpu->mmio_phys_addr = gpa;
4252 vcpu->mmio_size = bytes;
4253 vcpu->run->mmio.len = min(vcpu->mmio_size, 8);
4254 vcpu->run->mmio.is_write = vcpu->mmio_is_write = write;
4255 vcpu->mmio_index = 0;
4257 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4260 int emulator_read_write(struct x86_emulate_ctxt *ctxt, unsigned long addr,
4261 void *val, unsigned int bytes,
4262 struct x86_exception *exception,
4263 struct read_write_emulator_ops *ops)
4265 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4267 /* Crossing a page boundary? */
4268 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4271 now = -addr & ~PAGE_MASK;
4272 rc = emulator_read_write_onepage(addr, val, now, exception,
4275 if (rc != X86EMUL_CONTINUE)
4282 return emulator_read_write_onepage(addr, val, bytes, exception,
4286 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4290 struct x86_exception *exception)
4292 return emulator_read_write(ctxt, addr, val, bytes,
4293 exception, &read_emultor);
4296 int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4300 struct x86_exception *exception)
4302 return emulator_read_write(ctxt, addr, (void *)val, bytes,
4303 exception, &write_emultor);
4306 #define CMPXCHG_TYPE(t, ptr, old, new) \
4307 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4309 #ifdef CONFIG_X86_64
4310 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4312 # define CMPXCHG64(ptr, old, new) \
4313 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4316 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4321 struct x86_exception *exception)
4323 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4329 /* guests cmpxchg8b have to be emulated atomically */
4330 if (bytes > 8 || (bytes & (bytes - 1)))
4333 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4335 if (gpa == UNMAPPED_GVA ||
4336 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4339 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4342 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
4343 if (is_error_page(page)) {
4344 kvm_release_page_clean(page);
4348 kaddr = kmap_atomic(page, KM_USER0);
4349 kaddr += offset_in_page(gpa);
4352 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4355 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4358 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
4361 exchanged = CMPXCHG64(kaddr, old, new);
4366 kunmap_atomic(kaddr, KM_USER0);
4367 kvm_release_page_dirty(page);
4370 return X86EMUL_CMPXCHG_FAILED;
4372 kvm_mmu_pte_write(vcpu, gpa, new, bytes, 1);
4374 return X86EMUL_CONTINUE;
4377 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
4379 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
4382 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
4386 for (i = 0; i < vcpu->arch.pio.count; i++) {
4387 if (vcpu->arch.pio.in)
4388 r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
4389 vcpu->arch.pio.size, pd);
4391 r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
4392 vcpu->arch.pio.port, vcpu->arch.pio.size,
4396 pd += vcpu->arch.pio.size;
4402 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
4403 int size, unsigned short port, void *val,
4406 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4408 if (vcpu->arch.pio.count)
4411 memset(vcpu->arch.pio_data, 0, size * count);
4413 trace_kvm_pio(0, port, size, count);
4415 vcpu->arch.pio.port = port;
4416 vcpu->arch.pio.in = 1;
4417 vcpu->arch.pio.count = count;
4418 vcpu->arch.pio.size = size;
4420 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4422 memcpy(val, vcpu->arch.pio_data, size * count);
4423 vcpu->arch.pio.count = 0;
4427 vcpu->run->exit_reason = KVM_EXIT_IO;
4428 vcpu->run->io.direction = KVM_EXIT_IO_IN;
4429 vcpu->run->io.size = size;
4430 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4431 vcpu->run->io.count = count;
4432 vcpu->run->io.port = port;
4437 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
4438 int size, unsigned short port,
4439 const void *val, unsigned int count)
4441 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4443 trace_kvm_pio(1, port, size, count);
4445 vcpu->arch.pio.port = port;
4446 vcpu->arch.pio.in = 0;
4447 vcpu->arch.pio.count = count;
4448 vcpu->arch.pio.size = size;
4450 memcpy(vcpu->arch.pio_data, val, size * count);
4452 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4453 vcpu->arch.pio.count = 0;
4457 vcpu->run->exit_reason = KVM_EXIT_IO;
4458 vcpu->run->io.direction = KVM_EXIT_IO_OUT;
4459 vcpu->run->io.size = size;
4460 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4461 vcpu->run->io.count = count;
4462 vcpu->run->io.port = port;
4467 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
4469 return kvm_x86_ops->get_segment_base(vcpu, seg);
4472 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
4474 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
4477 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
4479 if (!need_emulate_wbinvd(vcpu))
4480 return X86EMUL_CONTINUE;
4482 if (kvm_x86_ops->has_wbinvd_exit()) {
4483 int cpu = get_cpu();
4485 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4486 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
4487 wbinvd_ipi, NULL, 1);
4489 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
4492 return X86EMUL_CONTINUE;
4494 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
4496 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
4498 kvm_emulate_wbinvd(emul_to_vcpu(ctxt));
4501 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
4503 return _kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
4506 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
4509 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
4512 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
4514 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
4517 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
4519 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4520 unsigned long value;
4524 value = kvm_read_cr0(vcpu);
4527 value = vcpu->arch.cr2;
4530 value = kvm_read_cr3(vcpu);
4533 value = kvm_read_cr4(vcpu);
4536 value = kvm_get_cr8(vcpu);
4539 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
4546 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
4548 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4553 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4556 vcpu->arch.cr2 = val;
4559 res = kvm_set_cr3(vcpu, val);
4562 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4565 res = kvm_set_cr8(vcpu, val);
4568 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
4575 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
4577 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
4580 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4582 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
4585 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4587 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
4590 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4592 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4595 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4597 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4600 static unsigned long emulator_get_cached_segment_base(
4601 struct x86_emulate_ctxt *ctxt, int seg)
4603 return get_segment_base(emul_to_vcpu(ctxt), seg);
4606 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4607 struct desc_struct *desc, u32 *base3,
4610 struct kvm_segment var;
4612 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
4613 *selector = var.selector;
4616 memset(desc, 0, sizeof(*desc));
4624 set_desc_limit(desc, var.limit);
4625 set_desc_base(desc, (unsigned long)var.base);
4626 #ifdef CONFIG_X86_64
4628 *base3 = var.base >> 32;
4630 desc->type = var.type;
4632 desc->dpl = var.dpl;
4633 desc->p = var.present;
4634 desc->avl = var.avl;
4642 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
4643 struct desc_struct *desc, u32 base3,
4646 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4647 struct kvm_segment var;
4649 var.selector = selector;
4650 var.base = get_desc_base(desc);
4651 #ifdef CONFIG_X86_64
4652 var.base |= ((u64)base3) << 32;
4654 var.limit = get_desc_limit(desc);
4656 var.limit = (var.limit << 12) | 0xfff;
4657 var.type = desc->type;
4658 var.present = desc->p;
4659 var.dpl = desc->dpl;
4664 var.avl = desc->avl;
4665 var.present = desc->p;
4666 var.unusable = !var.present;
4669 kvm_set_segment(vcpu, &var, seg);
4673 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
4674 u32 msr_index, u64 *pdata)
4676 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
4679 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
4680 u32 msr_index, u64 data)
4682 return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
4685 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
4687 emul_to_vcpu(ctxt)->arch.halt_request = 1;
4690 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
4693 kvm_load_guest_fpu(emul_to_vcpu(ctxt));
4695 * CR0.TS may reference the host fpu state, not the guest fpu state,
4696 * so it may be clear at this point.
4701 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
4706 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
4707 struct x86_instruction_info *info,
4708 enum x86_intercept_stage stage)
4710 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
4713 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
4714 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
4716 struct kvm_cpuid_entry2 *cpuid = NULL;
4719 cpuid = kvm_find_cpuid_entry(emul_to_vcpu(ctxt),
4735 static struct x86_emulate_ops emulate_ops = {
4736 .read_std = kvm_read_guest_virt_system,
4737 .write_std = kvm_write_guest_virt_system,
4738 .fetch = kvm_fetch_guest_virt,
4739 .read_emulated = emulator_read_emulated,
4740 .write_emulated = emulator_write_emulated,
4741 .cmpxchg_emulated = emulator_cmpxchg_emulated,
4742 .invlpg = emulator_invlpg,
4743 .pio_in_emulated = emulator_pio_in_emulated,
4744 .pio_out_emulated = emulator_pio_out_emulated,
4745 .get_segment = emulator_get_segment,
4746 .set_segment = emulator_set_segment,
4747 .get_cached_segment_base = emulator_get_cached_segment_base,
4748 .get_gdt = emulator_get_gdt,
4749 .get_idt = emulator_get_idt,
4750 .set_gdt = emulator_set_gdt,
4751 .set_idt = emulator_set_idt,
4752 .get_cr = emulator_get_cr,
4753 .set_cr = emulator_set_cr,
4754 .cpl = emulator_get_cpl,
4755 .get_dr = emulator_get_dr,
4756 .set_dr = emulator_set_dr,
4757 .set_msr = emulator_set_msr,
4758 .get_msr = emulator_get_msr,
4759 .halt = emulator_halt,
4760 .wbinvd = emulator_wbinvd,
4761 .fix_hypercall = emulator_fix_hypercall,
4762 .get_fpu = emulator_get_fpu,
4763 .put_fpu = emulator_put_fpu,
4764 .intercept = emulator_intercept,
4765 .get_cpuid = emulator_get_cpuid,
4768 static void cache_all_regs(struct kvm_vcpu *vcpu)
4770 kvm_register_read(vcpu, VCPU_REGS_RAX);
4771 kvm_register_read(vcpu, VCPU_REGS_RSP);
4772 kvm_register_read(vcpu, VCPU_REGS_RIP);
4773 vcpu->arch.regs_dirty = ~0;
4776 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
4778 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu, mask);
4780 * an sti; sti; sequence only disable interrupts for the first
4781 * instruction. So, if the last instruction, be it emulated or
4782 * not, left the system with the INT_STI flag enabled, it
4783 * means that the last instruction is an sti. We should not
4784 * leave the flag on in this case. The same goes for mov ss
4786 if (!(int_shadow & mask))
4787 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
4790 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
4792 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4793 if (ctxt->exception.vector == PF_VECTOR)
4794 kvm_propagate_fault(vcpu, &ctxt->exception);
4795 else if (ctxt->exception.error_code_valid)
4796 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
4797 ctxt->exception.error_code);
4799 kvm_queue_exception(vcpu, ctxt->exception.vector);
4802 static void init_decode_cache(struct x86_emulate_ctxt *ctxt,
4803 const unsigned long *regs)
4805 memset(&ctxt->twobyte, 0,
4806 (void *)&ctxt->regs - (void *)&ctxt->twobyte);
4807 memcpy(ctxt->regs, regs, sizeof(ctxt->regs));
4809 ctxt->fetch.start = 0;
4810 ctxt->fetch.end = 0;
4811 ctxt->io_read.pos = 0;
4812 ctxt->io_read.end = 0;
4813 ctxt->mem_read.pos = 0;
4814 ctxt->mem_read.end = 0;
4817 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
4819 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4823 * TODO: fix emulate.c to use guest_read/write_register
4824 * instead of direct ->regs accesses, can save hundred cycles
4825 * on Intel for instructions that don't read/change RSP, for
4828 cache_all_regs(vcpu);
4830 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4832 ctxt->eflags = kvm_get_rflags(vcpu);
4833 ctxt->eip = kvm_rip_read(vcpu);
4834 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
4835 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
4836 cs_l ? X86EMUL_MODE_PROT64 :
4837 cs_db ? X86EMUL_MODE_PROT32 :
4838 X86EMUL_MODE_PROT16;
4839 ctxt->guest_mode = is_guest_mode(vcpu);
4841 init_decode_cache(ctxt, vcpu->arch.regs);
4842 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
4845 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
4847 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4850 init_emulate_ctxt(vcpu);
4854 ctxt->_eip = ctxt->eip + inc_eip;
4855 ret = emulate_int_real(ctxt, irq);
4857 if (ret != X86EMUL_CONTINUE)
4858 return EMULATE_FAIL;
4860 ctxt->eip = ctxt->_eip;
4861 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
4862 kvm_rip_write(vcpu, ctxt->eip);
4863 kvm_set_rflags(vcpu, ctxt->eflags);
4865 if (irq == NMI_VECTOR)
4866 vcpu->arch.nmi_pending = 0;
4868 vcpu->arch.interrupt.pending = false;
4870 return EMULATE_DONE;
4872 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
4874 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
4876 int r = EMULATE_DONE;
4878 ++vcpu->stat.insn_emulation_fail;
4879 trace_kvm_emulate_insn_failed(vcpu);
4880 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
4881 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4882 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
4883 vcpu->run->internal.ndata = 0;
4886 kvm_queue_exception(vcpu, UD_VECTOR);
4891 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t gva,
4896 if (emulation_type & EMULTYPE_NO_REEXECUTE)
4903 * if emulation was due to access to shadowed page table
4904 * and it failed try to unshadow page and re-entetr the
4905 * guest to let CPU execute the instruction.
4907 if (kvm_mmu_unprotect_page_virt(vcpu, gva))
4910 gpa = kvm_mmu_gva_to_gpa_system(vcpu, gva, NULL);
4912 if (gpa == UNMAPPED_GVA)
4913 return true; /* let cpu generate fault */
4915 if (!kvm_is_error_hva(gfn_to_hva(vcpu->kvm, gpa >> PAGE_SHIFT)))
4921 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
4928 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4929 bool writeback = true;
4931 kvm_clear_exception_queue(vcpu);
4933 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
4934 init_emulate_ctxt(vcpu);
4935 ctxt->interruptibility = 0;
4936 ctxt->have_exception = false;
4937 ctxt->perm_ok = false;
4939 ctxt->only_vendor_specific_insn
4940 = emulation_type & EMULTYPE_TRAP_UD;
4942 r = x86_decode_insn(ctxt, insn, insn_len);
4944 trace_kvm_emulate_insn_start(vcpu);
4945 ++vcpu->stat.insn_emulation;
4946 if (r != EMULATION_OK) {
4947 if (emulation_type & EMULTYPE_TRAP_UD)
4948 return EMULATE_FAIL;
4949 if (reexecute_instruction(vcpu, cr2, emulation_type))
4950 return EMULATE_DONE;
4951 if (emulation_type & EMULTYPE_SKIP)
4952 return EMULATE_FAIL;
4953 return handle_emulation_failure(vcpu);
4957 if (emulation_type & EMULTYPE_SKIP) {
4958 kvm_rip_write(vcpu, ctxt->_eip);
4959 return EMULATE_DONE;
4962 /* this is needed for vmware backdoor interface to work since it
4963 changes registers values during IO operation */
4964 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
4965 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
4966 memcpy(ctxt->regs, vcpu->arch.regs, sizeof ctxt->regs);
4970 r = x86_emulate_insn(ctxt);
4972 if (r == EMULATION_INTERCEPTED)
4973 return EMULATE_DONE;
4975 if (r == EMULATION_FAILED) {
4976 if (reexecute_instruction(vcpu, cr2, emulation_type))
4977 return EMULATE_DONE;
4979 return handle_emulation_failure(vcpu);
4982 if (ctxt->have_exception) {
4983 inject_emulated_exception(vcpu);
4985 } else if (vcpu->arch.pio.count) {
4986 if (!vcpu->arch.pio.in)
4987 vcpu->arch.pio.count = 0;
4990 r = EMULATE_DO_MMIO;
4991 } else if (vcpu->mmio_needed) {
4992 if (!vcpu->mmio_is_write)
4994 r = EMULATE_DO_MMIO;
4995 } else if (r == EMULATION_RESTART)
5001 toggle_interruptibility(vcpu, ctxt->interruptibility);
5002 kvm_set_rflags(vcpu, ctxt->eflags);
5003 kvm_make_request(KVM_REQ_EVENT, vcpu);
5004 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
5005 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5006 kvm_rip_write(vcpu, ctxt->eip);
5008 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5012 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5014 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5016 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5017 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5018 size, port, &val, 1);
5019 /* do not return to emulator after return from userspace */
5020 vcpu->arch.pio.count = 0;
5023 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5025 static void tsc_bad(void *info)
5027 __this_cpu_write(cpu_tsc_khz, 0);
5030 static void tsc_khz_changed(void *data)
5032 struct cpufreq_freqs *freq = data;
5033 unsigned long khz = 0;
5037 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5038 khz = cpufreq_quick_get(raw_smp_processor_id());
5041 __this_cpu_write(cpu_tsc_khz, khz);
5044 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5047 struct cpufreq_freqs *freq = data;
5049 struct kvm_vcpu *vcpu;
5050 int i, send_ipi = 0;
5053 * We allow guests to temporarily run on slowing clocks,
5054 * provided we notify them after, or to run on accelerating
5055 * clocks, provided we notify them before. Thus time never
5058 * However, we have a problem. We can't atomically update
5059 * the frequency of a given CPU from this function; it is
5060 * merely a notifier, which can be called from any CPU.
5061 * Changing the TSC frequency at arbitrary points in time
5062 * requires a recomputation of local variables related to
5063 * the TSC for each VCPU. We must flag these local variables
5064 * to be updated and be sure the update takes place with the
5065 * new frequency before any guests proceed.
5067 * Unfortunately, the combination of hotplug CPU and frequency
5068 * change creates an intractable locking scenario; the order
5069 * of when these callouts happen is undefined with respect to
5070 * CPU hotplug, and they can race with each other. As such,
5071 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5072 * undefined; you can actually have a CPU frequency change take
5073 * place in between the computation of X and the setting of the
5074 * variable. To protect against this problem, all updates of
5075 * the per_cpu tsc_khz variable are done in an interrupt
5076 * protected IPI, and all callers wishing to update the value
5077 * must wait for a synchronous IPI to complete (which is trivial
5078 * if the caller is on the CPU already). This establishes the
5079 * necessary total order on variable updates.
5081 * Note that because a guest time update may take place
5082 * anytime after the setting of the VCPU's request bit, the
5083 * correct TSC value must be set before the request. However,
5084 * to ensure the update actually makes it to any guest which
5085 * starts running in hardware virtualization between the set
5086 * and the acquisition of the spinlock, we must also ping the
5087 * CPU after setting the request bit.
5091 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
5093 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
5096 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5098 raw_spin_lock(&kvm_lock);
5099 list_for_each_entry(kvm, &vm_list, vm_list) {
5100 kvm_for_each_vcpu(i, vcpu, kvm) {
5101 if (vcpu->cpu != freq->cpu)
5103 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5104 if (vcpu->cpu != smp_processor_id())
5108 raw_spin_unlock(&kvm_lock);
5110 if (freq->old < freq->new && send_ipi) {
5112 * We upscale the frequency. Must make the guest
5113 * doesn't see old kvmclock values while running with
5114 * the new frequency, otherwise we risk the guest sees
5115 * time go backwards.
5117 * In case we update the frequency for another cpu
5118 * (which might be in guest context) send an interrupt
5119 * to kick the cpu out of guest context. Next time
5120 * guest context is entered kvmclock will be updated,
5121 * so the guest will not see stale values.
5123 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5128 static struct notifier_block kvmclock_cpufreq_notifier_block = {
5129 .notifier_call = kvmclock_cpufreq_notifier
5132 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
5133 unsigned long action, void *hcpu)
5135 unsigned int cpu = (unsigned long)hcpu;
5139 case CPU_DOWN_FAILED:
5140 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5142 case CPU_DOWN_PREPARE:
5143 smp_call_function_single(cpu, tsc_bad, NULL, 1);
5149 static struct notifier_block kvmclock_cpu_notifier_block = {
5150 .notifier_call = kvmclock_cpu_notifier,
5151 .priority = -INT_MAX
5154 static void kvm_timer_init(void)
5158 max_tsc_khz = tsc_khz;
5159 register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5160 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5161 #ifdef CONFIG_CPU_FREQ
5162 struct cpufreq_policy policy;
5163 memset(&policy, 0, sizeof(policy));
5165 cpufreq_get_policy(&policy, cpu);
5166 if (policy.cpuinfo.max_freq)
5167 max_tsc_khz = policy.cpuinfo.max_freq;
5170 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
5171 CPUFREQ_TRANSITION_NOTIFIER);
5173 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
5174 for_each_online_cpu(cpu)
5175 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5178 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
5180 static int kvm_is_in_guest(void)
5182 return percpu_read(current_vcpu) != NULL;
5185 static int kvm_is_user_mode(void)
5189 if (percpu_read(current_vcpu))
5190 user_mode = kvm_x86_ops->get_cpl(percpu_read(current_vcpu));
5192 return user_mode != 0;
5195 static unsigned long kvm_get_guest_ip(void)
5197 unsigned long ip = 0;
5199 if (percpu_read(current_vcpu))
5200 ip = kvm_rip_read(percpu_read(current_vcpu));
5205 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5206 .is_in_guest = kvm_is_in_guest,
5207 .is_user_mode = kvm_is_user_mode,
5208 .get_guest_ip = kvm_get_guest_ip,
5211 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
5213 percpu_write(current_vcpu, vcpu);
5215 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
5217 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
5219 percpu_write(current_vcpu, NULL);
5221 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
5223 static void kvm_set_mmio_spte_mask(void)
5226 int maxphyaddr = boot_cpu_data.x86_phys_bits;
5229 * Set the reserved bits and the present bit of an paging-structure
5230 * entry to generate page fault with PFER.RSV = 1.
5232 mask = ((1ull << (62 - maxphyaddr + 1)) - 1) << maxphyaddr;
5235 #ifdef CONFIG_X86_64
5237 * If reserved bit is not supported, clear the present bit to disable
5240 if (maxphyaddr == 52)
5244 kvm_mmu_set_mmio_spte_mask(mask);
5247 int kvm_arch_init(void *opaque)
5250 struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
5253 printk(KERN_ERR "kvm: already loaded the other module\n");
5258 if (!ops->cpu_has_kvm_support()) {
5259 printk(KERN_ERR "kvm: no hardware support\n");
5263 if (ops->disabled_by_bios()) {
5264 printk(KERN_ERR "kvm: disabled by bios\n");
5269 r = kvm_mmu_module_init();
5273 kvm_set_mmio_spte_mask();
5276 kvm_init_msr_list();
5278 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
5279 PT_DIRTY_MASK, PT64_NX_MASK, 0);
5283 perf_register_guest_info_callbacks(&kvm_guest_cbs);
5286 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
5294 void kvm_arch_exit(void)
5296 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
5298 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5299 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
5300 CPUFREQ_TRANSITION_NOTIFIER);
5301 unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5303 kvm_mmu_module_exit();
5306 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
5308 ++vcpu->stat.halt_exits;
5309 if (irqchip_in_kernel(vcpu->kvm)) {
5310 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
5313 vcpu->run->exit_reason = KVM_EXIT_HLT;
5317 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
5319 static inline gpa_t hc_gpa(struct kvm_vcpu *vcpu, unsigned long a0,
5322 if (is_long_mode(vcpu))
5325 return a0 | ((gpa_t)a1 << 32);
5328 int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
5330 u64 param, ingpa, outgpa, ret;
5331 uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
5332 bool fast, longmode;
5336 * hypercall generates UD from non zero cpl and real mode
5339 if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
5340 kvm_queue_exception(vcpu, UD_VECTOR);
5344 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5345 longmode = is_long_mode(vcpu) && cs_l == 1;
5348 param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
5349 (kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
5350 ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
5351 (kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
5352 outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
5353 (kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
5355 #ifdef CONFIG_X86_64
5357 param = kvm_register_read(vcpu, VCPU_REGS_RCX);
5358 ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
5359 outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
5363 code = param & 0xffff;
5364 fast = (param >> 16) & 0x1;
5365 rep_cnt = (param >> 32) & 0xfff;
5366 rep_idx = (param >> 48) & 0xfff;
5368 trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
5371 case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
5372 kvm_vcpu_on_spin(vcpu);
5375 res = HV_STATUS_INVALID_HYPERCALL_CODE;
5379 ret = res | (((u64)rep_done & 0xfff) << 32);
5381 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
5383 kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
5384 kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
5390 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
5392 unsigned long nr, a0, a1, a2, a3, ret;
5395 if (kvm_hv_hypercall_enabled(vcpu->kvm))
5396 return kvm_hv_hypercall(vcpu);
5398 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
5399 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
5400 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
5401 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
5402 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
5404 trace_kvm_hypercall(nr, a0, a1, a2, a3);
5406 if (!is_long_mode(vcpu)) {
5414 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
5420 case KVM_HC_VAPIC_POLL_IRQ:
5424 r = kvm_pv_mmu_op(vcpu, a0, hc_gpa(vcpu, a1, a2), &ret);
5431 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
5432 ++vcpu->stat.hypercalls;
5435 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
5437 int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
5439 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5440 char instruction[3];
5441 unsigned long rip = kvm_rip_read(vcpu);
5444 * Blow out the MMU to ensure that no other VCPU has an active mapping
5445 * to ensure that the updated hypercall appears atomically across all
5448 kvm_mmu_zap_all(vcpu->kvm);
5450 kvm_x86_ops->patch_hypercall(vcpu, instruction);
5452 return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
5455 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
5457 struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
5458 struct kvm_cpuid_entry2 *ej;
5460 int nent = vcpu->arch.cpuid_nent;
5462 e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
5463 /* when no next entry is found, the current entry[i] is reselected */
5466 ej = &vcpu->arch.cpuid_entries[j];
5467 } while (ej->function != e->function);
5469 ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
5474 /* find an entry with matching function, matching index (if needed), and that
5475 * should be read next (if it's stateful) */
5476 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
5477 u32 function, u32 index)
5479 if (e->function != function)
5481 if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
5483 if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
5484 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
5489 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry(struct kvm_vcpu *vcpu,
5490 u32 function, u32 index)
5493 struct kvm_cpuid_entry2 *best = NULL;
5495 for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
5496 struct kvm_cpuid_entry2 *e;
5498 e = &vcpu->arch.cpuid_entries[i];
5499 if (is_matching_cpuid_entry(e, function, index)) {
5500 if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
5501 move_to_next_stateful_cpuid_entry(vcpu, i);
5508 EXPORT_SYMBOL_GPL(kvm_find_cpuid_entry);
5510 int cpuid_maxphyaddr(struct kvm_vcpu *vcpu)
5512 struct kvm_cpuid_entry2 *best;
5514 best = kvm_find_cpuid_entry(vcpu, 0x80000000, 0);
5515 if (!best || best->eax < 0x80000008)
5517 best = kvm_find_cpuid_entry(vcpu, 0x80000008, 0);
5519 return best->eax & 0xff;
5525 * If no match is found, check whether we exceed the vCPU's limit
5526 * and return the content of the highest valid _standard_ leaf instead.
5527 * This is to satisfy the CPUID specification.
5529 static struct kvm_cpuid_entry2* check_cpuid_limit(struct kvm_vcpu *vcpu,
5530 u32 function, u32 index)
5532 struct kvm_cpuid_entry2 *maxlevel;
5534 maxlevel = kvm_find_cpuid_entry(vcpu, function & 0x80000000, 0);
5535 if (!maxlevel || maxlevel->eax >= function)
5537 if (function & 0x80000000) {
5538 maxlevel = kvm_find_cpuid_entry(vcpu, 0, 0);
5542 return kvm_find_cpuid_entry(vcpu, maxlevel->eax, index);
5545 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
5547 u32 function, index;
5548 struct kvm_cpuid_entry2 *best;
5550 function = kvm_register_read(vcpu, VCPU_REGS_RAX);
5551 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
5552 kvm_register_write(vcpu, VCPU_REGS_RAX, 0);
5553 kvm_register_write(vcpu, VCPU_REGS_RBX, 0);
5554 kvm_register_write(vcpu, VCPU_REGS_RCX, 0);
5555 kvm_register_write(vcpu, VCPU_REGS_RDX, 0);
5556 best = kvm_find_cpuid_entry(vcpu, function, index);
5559 best = check_cpuid_limit(vcpu, function, index);
5562 kvm_register_write(vcpu, VCPU_REGS_RAX, best->eax);
5563 kvm_register_write(vcpu, VCPU_REGS_RBX, best->ebx);
5564 kvm_register_write(vcpu, VCPU_REGS_RCX, best->ecx);
5565 kvm_register_write(vcpu, VCPU_REGS_RDX, best->edx);
5567 kvm_x86_ops->skip_emulated_instruction(vcpu);
5568 trace_kvm_cpuid(function,
5569 kvm_register_read(vcpu, VCPU_REGS_RAX),
5570 kvm_register_read(vcpu, VCPU_REGS_RBX),
5571 kvm_register_read(vcpu, VCPU_REGS_RCX),
5572 kvm_register_read(vcpu, VCPU_REGS_RDX));
5574 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
5577 * Check if userspace requested an interrupt window, and that the
5578 * interrupt window is open.
5580 * No need to exit to userspace if we already have an interrupt queued.
5582 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
5584 return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
5585 vcpu->run->request_interrupt_window &&
5586 kvm_arch_interrupt_allowed(vcpu));
5589 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
5591 struct kvm_run *kvm_run = vcpu->run;
5593 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
5594 kvm_run->cr8 = kvm_get_cr8(vcpu);
5595 kvm_run->apic_base = kvm_get_apic_base(vcpu);
5596 if (irqchip_in_kernel(vcpu->kvm))
5597 kvm_run->ready_for_interrupt_injection = 1;
5599 kvm_run->ready_for_interrupt_injection =
5600 kvm_arch_interrupt_allowed(vcpu) &&
5601 !kvm_cpu_has_interrupt(vcpu) &&
5602 !kvm_event_needs_reinjection(vcpu);
5605 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
5609 if (!kvm_x86_ops->update_cr8_intercept)
5612 if (!vcpu->arch.apic)
5615 if (!vcpu->arch.apic->vapic_addr)
5616 max_irr = kvm_lapic_find_highest_irr(vcpu);
5623 tpr = kvm_lapic_get_cr8(vcpu);
5625 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
5628 static void inject_pending_event(struct kvm_vcpu *vcpu)
5630 /* try to reinject previous events if any */
5631 if (vcpu->arch.exception.pending) {
5632 trace_kvm_inj_exception(vcpu->arch.exception.nr,
5633 vcpu->arch.exception.has_error_code,
5634 vcpu->arch.exception.error_code);
5635 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
5636 vcpu->arch.exception.has_error_code,
5637 vcpu->arch.exception.error_code,
5638 vcpu->arch.exception.reinject);
5642 if (vcpu->arch.nmi_injected) {
5643 kvm_x86_ops->set_nmi(vcpu);
5647 if (vcpu->arch.interrupt.pending) {
5648 kvm_x86_ops->set_irq(vcpu);
5652 /* try to inject new event if pending */
5653 if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
5654 --vcpu->arch.nmi_pending;
5655 vcpu->arch.nmi_injected = true;
5656 kvm_x86_ops->set_nmi(vcpu);
5657 } else if (kvm_cpu_has_interrupt(vcpu)) {
5658 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
5659 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
5661 kvm_x86_ops->set_irq(vcpu);
5666 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
5668 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
5669 !vcpu->guest_xcr0_loaded) {
5670 /* kvm_set_xcr() also depends on this */
5671 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
5672 vcpu->guest_xcr0_loaded = 1;
5676 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
5678 if (vcpu->guest_xcr0_loaded) {
5679 if (vcpu->arch.xcr0 != host_xcr0)
5680 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
5681 vcpu->guest_xcr0_loaded = 0;
5685 static void process_nmi(struct kvm_vcpu *vcpu)
5690 * x86 is limited to one NMI running, and one NMI pending after it.
5691 * If an NMI is already in progress, limit further NMIs to just one.
5692 * Otherwise, allow two (and we'll inject the first one immediately).
5694 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
5697 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
5698 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
5699 kvm_make_request(KVM_REQ_EVENT, vcpu);
5702 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
5705 bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
5706 vcpu->run->request_interrupt_window;
5708 if (vcpu->requests) {
5709 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
5710 kvm_mmu_unload(vcpu);
5711 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
5712 __kvm_migrate_timers(vcpu);
5713 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
5714 r = kvm_guest_time_update(vcpu);
5718 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
5719 kvm_mmu_sync_roots(vcpu);
5720 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
5721 kvm_x86_ops->tlb_flush(vcpu);
5722 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
5723 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
5727 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
5728 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5732 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
5733 vcpu->fpu_active = 0;
5734 kvm_x86_ops->fpu_deactivate(vcpu);
5736 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
5737 /* Page is swapped out. Do synthetic halt */
5738 vcpu->arch.apf.halted = true;
5742 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
5743 record_steal_time(vcpu);
5744 if (kvm_check_request(KVM_REQ_NMI, vcpu))
5749 r = kvm_mmu_reload(vcpu);
5753 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
5754 inject_pending_event(vcpu);
5756 /* enable NMI/IRQ window open exits if needed */
5757 if (vcpu->arch.nmi_pending)
5758 kvm_x86_ops->enable_nmi_window(vcpu);
5759 if (kvm_cpu_has_interrupt(vcpu) || req_int_win)
5760 kvm_x86_ops->enable_irq_window(vcpu);
5762 if (kvm_lapic_enabled(vcpu)) {
5763 update_cr8_intercept(vcpu);
5764 kvm_lapic_sync_to_vapic(vcpu);
5770 kvm_x86_ops->prepare_guest_switch(vcpu);
5771 if (vcpu->fpu_active)
5772 kvm_load_guest_fpu(vcpu);
5773 vcpu->mode = IN_GUEST_MODE;
5775 /* We should set ->mode before check ->requests,
5776 * see the comment in make_all_cpus_request.
5780 local_irq_disable();
5782 if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
5783 || need_resched() || signal_pending(current)) {
5784 vcpu->mode = OUTSIDE_GUEST_MODE;
5788 kvm_x86_ops->cancel_injection(vcpu);
5793 kvm_load_guest_xcr0(vcpu);
5795 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
5799 if (unlikely(vcpu->arch.switch_db_regs)) {
5801 set_debugreg(vcpu->arch.eff_db[0], 0);
5802 set_debugreg(vcpu->arch.eff_db[1], 1);
5803 set_debugreg(vcpu->arch.eff_db[2], 2);
5804 set_debugreg(vcpu->arch.eff_db[3], 3);
5807 trace_kvm_entry(vcpu->vcpu_id);
5808 kvm_x86_ops->run(vcpu);
5811 * If the guest has used debug registers, at least dr7
5812 * will be disabled while returning to the host.
5813 * If we don't have active breakpoints in the host, we don't
5814 * care about the messed up debug address registers. But if
5815 * we have some of them active, restore the old state.
5817 if (hw_breakpoint_active())
5818 hw_breakpoint_restore();
5820 vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu);
5822 vcpu->mode = OUTSIDE_GUEST_MODE;
5825 kvm_put_guest_xcr0(vcpu);
5832 * We must have an instruction between local_irq_enable() and
5833 * kvm_guest_exit(), so the timer interrupt isn't delayed by
5834 * the interrupt shadow. The stat.exits increment will do nicely.
5835 * But we need to prevent reordering, hence this barrier():
5843 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
5846 * Profile KVM exit RIPs:
5848 if (unlikely(prof_on == KVM_PROFILING)) {
5849 unsigned long rip = kvm_rip_read(vcpu);
5850 profile_hit(KVM_PROFILING, (void *)rip);
5854 kvm_lapic_sync_from_vapic(vcpu);
5856 r = kvm_x86_ops->handle_exit(vcpu);
5862 static int __vcpu_run(struct kvm_vcpu *vcpu)
5865 struct kvm *kvm = vcpu->kvm;
5867 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
5868 pr_debug("vcpu %d received sipi with vector # %x\n",
5869 vcpu->vcpu_id, vcpu->arch.sipi_vector);
5870 kvm_lapic_reset(vcpu);
5871 r = kvm_arch_vcpu_reset(vcpu);
5874 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5877 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
5881 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
5882 !vcpu->arch.apf.halted)
5883 r = vcpu_enter_guest(vcpu);
5885 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5886 kvm_vcpu_block(vcpu);
5887 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
5888 if (kvm_check_request(KVM_REQ_UNHALT, vcpu))
5890 switch(vcpu->arch.mp_state) {
5891 case KVM_MP_STATE_HALTED:
5892 vcpu->arch.mp_state =
5893 KVM_MP_STATE_RUNNABLE;
5894 case KVM_MP_STATE_RUNNABLE:
5895 vcpu->arch.apf.halted = false;
5897 case KVM_MP_STATE_SIPI_RECEIVED:
5908 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
5909 if (kvm_cpu_has_pending_timer(vcpu))
5910 kvm_inject_pending_timer_irqs(vcpu);
5912 if (dm_request_for_irq_injection(vcpu)) {
5914 vcpu->run->exit_reason = KVM_EXIT_INTR;
5915 ++vcpu->stat.request_irq_exits;
5918 kvm_check_async_pf_completion(vcpu);
5920 if (signal_pending(current)) {
5922 vcpu->run->exit_reason = KVM_EXIT_INTR;
5923 ++vcpu->stat.signal_exits;
5925 if (need_resched()) {
5926 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5928 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
5932 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5937 static int complete_mmio(struct kvm_vcpu *vcpu)
5939 struct kvm_run *run = vcpu->run;
5942 if (!(vcpu->arch.pio.count || vcpu->mmio_needed))
5945 if (vcpu->mmio_needed) {
5946 vcpu->mmio_needed = 0;
5947 if (!vcpu->mmio_is_write)
5948 memcpy(vcpu->mmio_data + vcpu->mmio_index,
5950 vcpu->mmio_index += 8;
5951 if (vcpu->mmio_index < vcpu->mmio_size) {
5952 run->exit_reason = KVM_EXIT_MMIO;
5953 run->mmio.phys_addr = vcpu->mmio_phys_addr + vcpu->mmio_index;
5954 memcpy(run->mmio.data, vcpu->mmio_data + vcpu->mmio_index, 8);
5955 run->mmio.len = min(vcpu->mmio_size - vcpu->mmio_index, 8);
5956 run->mmio.is_write = vcpu->mmio_is_write;
5957 vcpu->mmio_needed = 1;
5960 if (vcpu->mmio_is_write)
5962 vcpu->mmio_read_completed = 1;
5964 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
5965 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
5966 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
5967 if (r != EMULATE_DONE)
5972 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
5977 if (!tsk_used_math(current) && init_fpu(current))
5980 if (vcpu->sigset_active)
5981 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
5983 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
5984 kvm_vcpu_block(vcpu);
5985 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
5990 /* re-sync apic's tpr */
5991 if (!irqchip_in_kernel(vcpu->kvm)) {
5992 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
5998 r = complete_mmio(vcpu);
6002 if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL)
6003 kvm_register_write(vcpu, VCPU_REGS_RAX,
6004 kvm_run->hypercall.ret);
6006 r = __vcpu_run(vcpu);
6009 post_kvm_run_save(vcpu);
6010 if (vcpu->sigset_active)
6011 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
6016 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6018 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
6020 * We are here if userspace calls get_regs() in the middle of
6021 * instruction emulation. Registers state needs to be copied
6022 * back from emulation context to vcpu. Usrapace shouldn't do
6023 * that usually, but some bad designed PV devices (vmware
6024 * backdoor interface) need this to work
6026 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6027 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
6028 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6030 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
6031 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
6032 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
6033 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
6034 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
6035 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
6036 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
6037 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
6038 #ifdef CONFIG_X86_64
6039 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
6040 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
6041 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
6042 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
6043 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
6044 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
6045 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
6046 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
6049 regs->rip = kvm_rip_read(vcpu);
6050 regs->rflags = kvm_get_rflags(vcpu);
6055 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6057 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
6058 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6060 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
6061 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
6062 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
6063 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
6064 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
6065 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
6066 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
6067 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
6068 #ifdef CONFIG_X86_64
6069 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
6070 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
6071 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
6072 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
6073 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
6074 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
6075 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
6076 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
6079 kvm_rip_write(vcpu, regs->rip);
6080 kvm_set_rflags(vcpu, regs->rflags | 0x2 /*X86_EFLAGS_FIXED*/);
6082 vcpu->arch.exception.pending = false;
6084 kvm_make_request(KVM_REQ_EVENT, vcpu);
6089 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
6091 struct kvm_segment cs;
6093 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
6097 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
6099 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
6100 struct kvm_sregs *sregs)
6104 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6105 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6106 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6107 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6108 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6109 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6111 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6112 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6114 kvm_x86_ops->get_idt(vcpu, &dt);
6115 sregs->idt.limit = dt.size;
6116 sregs->idt.base = dt.address;
6117 kvm_x86_ops->get_gdt(vcpu, &dt);
6118 sregs->gdt.limit = dt.size;
6119 sregs->gdt.base = dt.address;
6121 sregs->cr0 = kvm_read_cr0(vcpu);
6122 sregs->cr2 = vcpu->arch.cr2;
6123 sregs->cr3 = kvm_read_cr3(vcpu);
6124 sregs->cr4 = kvm_read_cr4(vcpu);
6125 sregs->cr8 = kvm_get_cr8(vcpu);
6126 sregs->efer = vcpu->arch.efer;
6127 sregs->apic_base = kvm_get_apic_base(vcpu);
6129 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
6131 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
6132 set_bit(vcpu->arch.interrupt.nr,
6133 (unsigned long *)sregs->interrupt_bitmap);
6138 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
6139 struct kvm_mp_state *mp_state)
6141 mp_state->mp_state = vcpu->arch.mp_state;
6145 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
6146 struct kvm_mp_state *mp_state)
6148 vcpu->arch.mp_state = mp_state->mp_state;
6149 kvm_make_request(KVM_REQ_EVENT, vcpu);
6153 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason,
6154 bool has_error_code, u32 error_code)
6156 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6159 init_emulate_ctxt(vcpu);
6161 ret = emulator_task_switch(ctxt, tss_selector, reason,
6162 has_error_code, error_code);
6165 return EMULATE_FAIL;
6167 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
6168 kvm_rip_write(vcpu, ctxt->eip);
6169 kvm_set_rflags(vcpu, ctxt->eflags);
6170 kvm_make_request(KVM_REQ_EVENT, vcpu);
6171 return EMULATE_DONE;
6173 EXPORT_SYMBOL_GPL(kvm_task_switch);
6175 int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
6177 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
6179 * When EFER.LME and CR0.PG are set, the processor is in
6180 * 64-bit mode (though maybe in a 32-bit code segment).
6181 * CR4.PAE and EFER.LMA must be set.
6183 if (!(sregs->cr4 & X86_CR4_PAE)
6184 || !(sregs->efer & EFER_LMA))
6188 * Not in 64-bit mode: EFER.LMA is clear and the code
6189 * segment cannot be 64-bit.
6191 if (sregs->efer & EFER_LMA || sregs->cs.l)
6198 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
6199 struct kvm_sregs *sregs)
6201 int mmu_reset_needed = 0;
6202 int pending_vec, max_bits, idx;
6205 if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
6208 if (kvm_valid_sregs(vcpu, sregs))
6211 dt.size = sregs->idt.limit;
6212 dt.address = sregs->idt.base;
6213 kvm_x86_ops->set_idt(vcpu, &dt);
6214 dt.size = sregs->gdt.limit;
6215 dt.address = sregs->gdt.base;
6216 kvm_x86_ops->set_gdt(vcpu, &dt);
6218 vcpu->arch.cr2 = sregs->cr2;
6219 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
6220 vcpu->arch.cr3 = sregs->cr3;
6221 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
6223 kvm_set_cr8(vcpu, sregs->cr8);
6225 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
6226 kvm_x86_ops->set_efer(vcpu, sregs->efer);
6227 kvm_set_apic_base(vcpu, sregs->apic_base);
6229 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
6230 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
6231 vcpu->arch.cr0 = sregs->cr0;
6233 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
6234 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
6235 if (sregs->cr4 & X86_CR4_OSXSAVE)
6238 idx = srcu_read_lock(&vcpu->kvm->srcu);
6239 if (!is_long_mode(vcpu) && is_pae(vcpu)) {
6240 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
6241 mmu_reset_needed = 1;
6243 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6245 if (mmu_reset_needed)
6246 kvm_mmu_reset_context(vcpu);
6248 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
6249 pending_vec = find_first_bit(
6250 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
6251 if (pending_vec < max_bits) {
6252 kvm_queue_interrupt(vcpu, pending_vec, false);
6253 pr_debug("Set back pending irq %d\n", pending_vec);
6256 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6257 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6258 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6259 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6260 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6261 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6263 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6264 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6266 update_cr8_intercept(vcpu);
6268 /* Older userspace won't unhalt the vcpu on reset. */
6269 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
6270 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
6272 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
6274 kvm_make_request(KVM_REQ_EVENT, vcpu);
6279 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
6280 struct kvm_guest_debug *dbg)
6282 unsigned long rflags;
6285 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
6287 if (vcpu->arch.exception.pending)
6289 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
6290 kvm_queue_exception(vcpu, DB_VECTOR);
6292 kvm_queue_exception(vcpu, BP_VECTOR);
6296 * Read rflags as long as potentially injected trace flags are still
6299 rflags = kvm_get_rflags(vcpu);
6301 vcpu->guest_debug = dbg->control;
6302 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
6303 vcpu->guest_debug = 0;
6305 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
6306 for (i = 0; i < KVM_NR_DB_REGS; ++i)
6307 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
6308 vcpu->arch.switch_db_regs =
6309 (dbg->arch.debugreg[7] & DR7_BP_EN_MASK);
6311 for (i = 0; i < KVM_NR_DB_REGS; i++)
6312 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
6313 vcpu->arch.switch_db_regs = (vcpu->arch.dr7 & DR7_BP_EN_MASK);
6316 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6317 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
6318 get_segment_base(vcpu, VCPU_SREG_CS);
6321 * Trigger an rflags update that will inject or remove the trace
6324 kvm_set_rflags(vcpu, rflags);
6326 kvm_x86_ops->set_guest_debug(vcpu, dbg);
6336 * Translate a guest virtual address to a guest physical address.
6338 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
6339 struct kvm_translation *tr)
6341 unsigned long vaddr = tr->linear_address;
6345 idx = srcu_read_lock(&vcpu->kvm->srcu);
6346 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
6347 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6348 tr->physical_address = gpa;
6349 tr->valid = gpa != UNMAPPED_GVA;
6356 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
6358 struct i387_fxsave_struct *fxsave =
6359 &vcpu->arch.guest_fpu.state->fxsave;
6361 memcpy(fpu->fpr, fxsave->st_space, 128);
6362 fpu->fcw = fxsave->cwd;
6363 fpu->fsw = fxsave->swd;
6364 fpu->ftwx = fxsave->twd;
6365 fpu->last_opcode = fxsave->fop;
6366 fpu->last_ip = fxsave->rip;
6367 fpu->last_dp = fxsave->rdp;
6368 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
6373 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
6375 struct i387_fxsave_struct *fxsave =
6376 &vcpu->arch.guest_fpu.state->fxsave;
6378 memcpy(fxsave->st_space, fpu->fpr, 128);
6379 fxsave->cwd = fpu->fcw;
6380 fxsave->swd = fpu->fsw;
6381 fxsave->twd = fpu->ftwx;
6382 fxsave->fop = fpu->last_opcode;
6383 fxsave->rip = fpu->last_ip;
6384 fxsave->rdp = fpu->last_dp;
6385 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
6390 int fx_init(struct kvm_vcpu *vcpu)
6394 err = fpu_alloc(&vcpu->arch.guest_fpu);
6398 fpu_finit(&vcpu->arch.guest_fpu);
6401 * Ensure guest xcr0 is valid for loading
6403 vcpu->arch.xcr0 = XSTATE_FP;
6405 vcpu->arch.cr0 |= X86_CR0_ET;
6409 EXPORT_SYMBOL_GPL(fx_init);
6411 static void fx_free(struct kvm_vcpu *vcpu)
6413 fpu_free(&vcpu->arch.guest_fpu);
6416 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
6418 if (vcpu->guest_fpu_loaded)
6422 * Restore all possible states in the guest,
6423 * and assume host would use all available bits.
6424 * Guest xcr0 would be loaded later.
6426 vcpu->guest_fpu_loaded = 1;
6427 unlazy_fpu(current);
6428 fpu_restore_checking(&vcpu->arch.guest_fpu);
6432 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
6434 if (!vcpu->guest_fpu_loaded)
6437 vcpu->guest_fpu_loaded = 0;
6438 fpu_save_init(&vcpu->arch.guest_fpu);
6439 ++vcpu->stat.fpu_reload;
6440 kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
6444 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
6446 void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
6448 kvmclock_reset(vcpu);
6451 kvm_x86_ops->vcpu_free(vcpu);
6452 free_cpumask_var(wbinvd_dirty_mask);
6455 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
6458 if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
6459 printk_once(KERN_WARNING
6460 "kvm: SMP vm created on host with unstable TSC; "
6461 "guest TSC will not be reliable\n");
6462 return kvm_x86_ops->vcpu_create(kvm, id);
6465 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
6469 vcpu->arch.mtrr_state.have_fixed = 1;
6471 r = kvm_arch_vcpu_reset(vcpu);
6473 r = kvm_mmu_setup(vcpu);
6479 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
6481 vcpu->arch.apf.msr_val = 0;
6484 kvm_mmu_unload(vcpu);
6488 kvm_x86_ops->vcpu_free(vcpu);
6491 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
6493 atomic_set(&vcpu->arch.nmi_queued, 0);
6494 vcpu->arch.nmi_pending = 0;
6495 vcpu->arch.nmi_injected = false;
6497 vcpu->arch.switch_db_regs = 0;
6498 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
6499 vcpu->arch.dr6 = DR6_FIXED_1;
6500 vcpu->arch.dr7 = DR7_FIXED_1;
6502 kvm_make_request(KVM_REQ_EVENT, vcpu);
6503 vcpu->arch.apf.msr_val = 0;
6504 vcpu->arch.st.msr_val = 0;
6506 kvmclock_reset(vcpu);
6508 kvm_clear_async_pf_completion_queue(vcpu);
6509 kvm_async_pf_hash_reset(vcpu);
6510 vcpu->arch.apf.halted = false;
6512 return kvm_x86_ops->vcpu_reset(vcpu);
6515 int kvm_arch_hardware_enable(void *garbage)
6518 struct kvm_vcpu *vcpu;
6521 kvm_shared_msr_cpu_online();
6522 list_for_each_entry(kvm, &vm_list, vm_list)
6523 kvm_for_each_vcpu(i, vcpu, kvm)
6524 if (vcpu->cpu == smp_processor_id())
6525 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6526 return kvm_x86_ops->hardware_enable(garbage);
6529 void kvm_arch_hardware_disable(void *garbage)
6531 kvm_x86_ops->hardware_disable(garbage);
6532 drop_user_return_notifiers(garbage);
6535 int kvm_arch_hardware_setup(void)
6537 return kvm_x86_ops->hardware_setup();
6540 void kvm_arch_hardware_unsetup(void)
6542 kvm_x86_ops->hardware_unsetup();
6545 void kvm_arch_check_processor_compat(void *rtn)
6547 kvm_x86_ops->check_processor_compatibility(rtn);
6550 bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
6552 return irqchip_in_kernel(vcpu->kvm) == (vcpu->arch.apic != NULL);
6555 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
6561 BUG_ON(vcpu->kvm == NULL);
6564 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
6565 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
6566 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
6567 vcpu->arch.mmu.translate_gpa = translate_gpa;
6568 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
6569 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
6570 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
6572 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
6574 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
6579 vcpu->arch.pio_data = page_address(page);
6581 kvm_init_tsc_catchup(vcpu, max_tsc_khz);
6583 r = kvm_mmu_create(vcpu);
6585 goto fail_free_pio_data;
6587 if (irqchip_in_kernel(kvm)) {
6588 r = kvm_create_lapic(vcpu);
6590 goto fail_mmu_destroy;
6593 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
6595 if (!vcpu->arch.mce_banks) {
6597 goto fail_free_lapic;
6599 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
6601 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL))
6602 goto fail_free_mce_banks;
6604 vcpu->arch.pv_time_enabled = false;
6605 kvm_async_pf_hash_reset(vcpu);
6608 fail_free_mce_banks:
6609 kfree(vcpu->arch.mce_banks);
6611 kvm_free_lapic(vcpu);
6613 kvm_mmu_destroy(vcpu);
6615 free_page((unsigned long)vcpu->arch.pio_data);
6620 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
6624 kfree(vcpu->arch.mce_banks);
6625 kvm_free_lapic(vcpu);
6626 idx = srcu_read_lock(&vcpu->kvm->srcu);
6627 kvm_mmu_destroy(vcpu);
6628 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6629 free_page((unsigned long)vcpu->arch.pio_data);
6632 int kvm_arch_init_vm(struct kvm *kvm)
6634 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6635 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
6637 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
6638 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
6640 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
6645 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
6648 kvm_mmu_unload(vcpu);
6652 static void kvm_free_vcpus(struct kvm *kvm)
6655 struct kvm_vcpu *vcpu;
6658 * Unpin any mmu pages first.
6660 kvm_for_each_vcpu(i, vcpu, kvm) {
6661 kvm_clear_async_pf_completion_queue(vcpu);
6662 kvm_unload_vcpu_mmu(vcpu);
6664 kvm_for_each_vcpu(i, vcpu, kvm)
6665 kvm_arch_vcpu_free(vcpu);
6667 mutex_lock(&kvm->lock);
6668 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
6669 kvm->vcpus[i] = NULL;
6671 atomic_set(&kvm->online_vcpus, 0);
6672 mutex_unlock(&kvm->lock);
6675 void kvm_arch_sync_events(struct kvm *kvm)
6677 kvm_free_all_assigned_devices(kvm);
6681 void kvm_arch_destroy_vm(struct kvm *kvm)
6683 kvm_iommu_unmap_guest(kvm);
6684 kfree(kvm->arch.vpic);
6685 kfree(kvm->arch.vioapic);
6686 kvm_free_vcpus(kvm);
6687 if (kvm->arch.apic_access_page)
6688 put_page(kvm->arch.apic_access_page);
6689 if (kvm->arch.ept_identity_pagetable)
6690 put_page(kvm->arch.ept_identity_pagetable);
6693 int kvm_arch_prepare_memory_region(struct kvm *kvm,
6694 struct kvm_memory_slot *memslot,
6695 struct kvm_memory_slot old,
6696 struct kvm_userspace_memory_region *mem,
6699 int npages = memslot->npages;
6700 int map_flags = MAP_PRIVATE | MAP_ANONYMOUS;
6702 /* Prevent internal slot pages from being moved by fork()/COW. */
6703 if (memslot->id >= KVM_MEMORY_SLOTS)
6704 map_flags = MAP_SHARED | MAP_ANONYMOUS;
6706 /*To keep backward compatibility with older userspace,
6707 *x86 needs to hanlde !user_alloc case.
6710 if (npages && !old.rmap) {
6711 unsigned long userspace_addr;
6713 down_write(¤t->mm->mmap_sem);
6714 userspace_addr = do_mmap(NULL, 0,
6716 PROT_READ | PROT_WRITE,
6719 up_write(¤t->mm->mmap_sem);
6721 if (IS_ERR((void *)userspace_addr))
6722 return PTR_ERR((void *)userspace_addr);
6724 memslot->userspace_addr = userspace_addr;
6732 void kvm_arch_commit_memory_region(struct kvm *kvm,
6733 struct kvm_userspace_memory_region *mem,
6734 struct kvm_memory_slot old,
6738 int nr_mmu_pages = 0, npages = mem->memory_size >> PAGE_SHIFT;
6740 if (!user_alloc && !old.user_alloc && old.rmap && !npages) {
6743 down_write(¤t->mm->mmap_sem);
6744 ret = do_munmap(current->mm, old.userspace_addr,
6745 old.npages * PAGE_SIZE);
6746 up_write(¤t->mm->mmap_sem);
6749 "kvm_vm_ioctl_set_memory_region: "
6750 "failed to munmap memory\n");
6753 if (!kvm->arch.n_requested_mmu_pages)
6754 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
6756 spin_lock(&kvm->mmu_lock);
6758 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
6759 kvm_mmu_slot_remove_write_access(kvm, mem->slot);
6760 spin_unlock(&kvm->mmu_lock);
6763 void kvm_arch_flush_shadow(struct kvm *kvm)
6765 kvm_mmu_zap_all(kvm);
6766 kvm_reload_remote_mmus(kvm);
6769 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
6771 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6772 !vcpu->arch.apf.halted)
6773 || !list_empty_careful(&vcpu->async_pf.done)
6774 || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
6775 || atomic_read(&vcpu->arch.nmi_queued) ||
6776 (kvm_arch_interrupt_allowed(vcpu) &&
6777 kvm_cpu_has_interrupt(vcpu));
6780 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
6783 int cpu = vcpu->cpu;
6785 if (waitqueue_active(&vcpu->wq)) {
6786 wake_up_interruptible(&vcpu->wq);
6787 ++vcpu->stat.halt_wakeup;
6791 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
6792 if (kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE)
6793 smp_send_reschedule(cpu);
6797 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
6799 return kvm_x86_ops->interrupt_allowed(vcpu);
6802 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
6804 unsigned long current_rip = kvm_rip_read(vcpu) +
6805 get_segment_base(vcpu, VCPU_SREG_CS);
6807 return current_rip == linear_rip;
6809 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
6811 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
6813 unsigned long rflags;
6815 rflags = kvm_x86_ops->get_rflags(vcpu);
6816 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6817 rflags &= ~X86_EFLAGS_TF;
6820 EXPORT_SYMBOL_GPL(kvm_get_rflags);
6822 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
6824 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
6825 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
6826 rflags |= X86_EFLAGS_TF;
6827 kvm_x86_ops->set_rflags(vcpu, rflags);
6828 kvm_make_request(KVM_REQ_EVENT, vcpu);
6830 EXPORT_SYMBOL_GPL(kvm_set_rflags);
6832 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
6836 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
6837 is_error_page(work->page))
6840 r = kvm_mmu_reload(vcpu);
6844 if (!vcpu->arch.mmu.direct_map &&
6845 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
6848 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
6851 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
6853 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
6856 static inline u32 kvm_async_pf_next_probe(u32 key)
6858 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
6861 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6863 u32 key = kvm_async_pf_hash_fn(gfn);
6865 while (vcpu->arch.apf.gfns[key] != ~0)
6866 key = kvm_async_pf_next_probe(key);
6868 vcpu->arch.apf.gfns[key] = gfn;
6871 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
6874 u32 key = kvm_async_pf_hash_fn(gfn);
6876 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
6877 (vcpu->arch.apf.gfns[key] != gfn &&
6878 vcpu->arch.apf.gfns[key] != ~0); i++)
6879 key = kvm_async_pf_next_probe(key);
6884 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6886 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
6889 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6893 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
6895 vcpu->arch.apf.gfns[i] = ~0;
6897 j = kvm_async_pf_next_probe(j);
6898 if (vcpu->arch.apf.gfns[j] == ~0)
6900 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
6902 * k lies cyclically in ]i,j]
6904 * |....j i.k.| or |.k..j i...|
6906 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
6907 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
6912 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
6915 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
6919 static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
6922 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
6926 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
6927 struct kvm_async_pf *work)
6929 struct x86_exception fault;
6931 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
6932 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
6934 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
6935 (vcpu->arch.apf.send_user_only &&
6936 kvm_x86_ops->get_cpl(vcpu) == 0))
6937 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
6938 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
6939 fault.vector = PF_VECTOR;
6940 fault.error_code_valid = true;
6941 fault.error_code = 0;
6942 fault.nested_page_fault = false;
6943 fault.address = work->arch.token;
6944 kvm_inject_page_fault(vcpu, &fault);
6948 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
6949 struct kvm_async_pf *work)
6951 struct x86_exception fault;
6954 trace_kvm_async_pf_ready(work->arch.token, work->gva);
6955 if (is_error_page(work->page))
6956 work->arch.token = ~0; /* broadcast wakeup */
6958 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
6960 if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
6961 !apf_get_user(vcpu, &val)) {
6962 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
6963 vcpu->arch.exception.pending &&
6964 vcpu->arch.exception.nr == PF_VECTOR &&
6965 !apf_put_user(vcpu, 0)) {
6966 vcpu->arch.exception.pending = false;
6967 vcpu->arch.exception.nr = 0;
6968 vcpu->arch.exception.has_error_code = false;
6969 vcpu->arch.exception.error_code = 0;
6970 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
6971 fault.vector = PF_VECTOR;
6972 fault.error_code_valid = true;
6973 fault.error_code = 0;
6974 fault.nested_page_fault = false;
6975 fault.address = work->arch.token;
6976 kvm_inject_page_fault(vcpu, &fault);
6979 vcpu->arch.apf.halted = false;
6982 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
6984 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
6987 return kvm_can_do_async_pf(vcpu);
6990 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
6991 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
6992 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
6993 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
6994 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
6995 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
6996 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
6997 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
6998 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
6999 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
7000 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
7001 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);