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
11 * Avi Kivity <avi@qumranet.com>
12 * Yaniv Kamay <yaniv@qumranet.com>
13 * Amit Shah <amit.shah@qumranet.com>
14 * Ben-Ami Yassour <benami@il.ibm.com>
16 * This work is licensed under the terms of the GNU GPL, version 2. See
17 * the COPYING file in the top-level directory.
21 #include <linux/kvm_host.h>
26 #include "kvm_cache_regs.h"
29 #include <linux/clocksource.h>
30 #include <linux/interrupt.h>
31 #include <linux/kvm.h>
33 #include <linux/vmalloc.h>
34 #include <linux/module.h>
35 #include <linux/mman.h>
36 #include <linux/highmem.h>
37 #include <linux/iommu.h>
38 #include <linux/intel-iommu.h>
39 #include <linux/cpufreq.h>
40 #include <linux/user-return-notifier.h>
41 #include <linux/srcu.h>
42 #include <linux/slab.h>
43 #include <trace/events/kvm.h>
45 #define CREATE_TRACE_POINTS
48 #include <asm/debugreg.h>
49 #include <asm/uaccess.h>
55 #define MAX_IO_MSRS 256
56 #define CR0_RESERVED_BITS \
57 (~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
58 | X86_CR0_ET | X86_CR0_NE | X86_CR0_WP | X86_CR0_AM \
59 | X86_CR0_NW | X86_CR0_CD | X86_CR0_PG))
60 #define CR4_RESERVED_BITS \
61 (~(unsigned long)(X86_CR4_VME | X86_CR4_PVI | X86_CR4_TSD | X86_CR4_DE\
62 | X86_CR4_PSE | X86_CR4_PAE | X86_CR4_MCE \
63 | X86_CR4_PGE | X86_CR4_PCE | X86_CR4_OSFXSR \
64 | X86_CR4_OSXMMEXCPT | X86_CR4_VMXE))
66 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
68 #define KVM_MAX_MCE_BANKS 32
69 #define KVM_MCE_CAP_SUPPORTED MCG_CTL_P
72 * - enable syscall per default because its emulated by KVM
73 * - enable LME and LMA per default on 64 bit KVM
76 static u64 __read_mostly efer_reserved_bits = 0xfffffffffffffafeULL;
78 static u64 __read_mostly efer_reserved_bits = 0xfffffffffffffffeULL;
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);
88 struct kvm_x86_ops *kvm_x86_ops;
89 EXPORT_SYMBOL_GPL(kvm_x86_ops);
92 module_param_named(ignore_msrs, ignore_msrs, bool, S_IRUGO | S_IWUSR);
94 #define KVM_NR_SHARED_MSRS 16
96 struct kvm_shared_msrs_global {
98 u32 msrs[KVM_NR_SHARED_MSRS];
101 struct kvm_shared_msrs {
102 struct user_return_notifier urn;
104 struct kvm_shared_msr_values {
107 } values[KVM_NR_SHARED_MSRS];
110 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
111 static DEFINE_PER_CPU(struct kvm_shared_msrs, shared_msrs);
113 struct kvm_stats_debugfs_item debugfs_entries[] = {
114 { "pf_fixed", VCPU_STAT(pf_fixed) },
115 { "pf_guest", VCPU_STAT(pf_guest) },
116 { "tlb_flush", VCPU_STAT(tlb_flush) },
117 { "invlpg", VCPU_STAT(invlpg) },
118 { "exits", VCPU_STAT(exits) },
119 { "io_exits", VCPU_STAT(io_exits) },
120 { "mmio_exits", VCPU_STAT(mmio_exits) },
121 { "signal_exits", VCPU_STAT(signal_exits) },
122 { "irq_window", VCPU_STAT(irq_window_exits) },
123 { "nmi_window", VCPU_STAT(nmi_window_exits) },
124 { "halt_exits", VCPU_STAT(halt_exits) },
125 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
126 { "hypercalls", VCPU_STAT(hypercalls) },
127 { "request_irq", VCPU_STAT(request_irq_exits) },
128 { "irq_exits", VCPU_STAT(irq_exits) },
129 { "host_state_reload", VCPU_STAT(host_state_reload) },
130 { "efer_reload", VCPU_STAT(efer_reload) },
131 { "fpu_reload", VCPU_STAT(fpu_reload) },
132 { "insn_emulation", VCPU_STAT(insn_emulation) },
133 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
134 { "irq_injections", VCPU_STAT(irq_injections) },
135 { "nmi_injections", VCPU_STAT(nmi_injections) },
136 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
137 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
138 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
139 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
140 { "mmu_flooded", VM_STAT(mmu_flooded) },
141 { "mmu_recycled", VM_STAT(mmu_recycled) },
142 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
143 { "mmu_unsync", VM_STAT(mmu_unsync) },
144 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
145 { "largepages", VM_STAT(lpages) },
149 static void kvm_on_user_return(struct user_return_notifier *urn)
152 struct kvm_shared_msrs *locals
153 = container_of(urn, struct kvm_shared_msrs, urn);
154 struct kvm_shared_msr_values *values;
156 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
157 values = &locals->values[slot];
158 if (values->host != values->curr) {
159 wrmsrl(shared_msrs_global.msrs[slot], values->host);
160 values->curr = values->host;
163 locals->registered = false;
164 user_return_notifier_unregister(urn);
167 static void shared_msr_update(unsigned slot, u32 msr)
169 struct kvm_shared_msrs *smsr;
172 smsr = &__get_cpu_var(shared_msrs);
173 /* only read, and nobody should modify it at this time,
174 * so don't need lock */
175 if (slot >= shared_msrs_global.nr) {
176 printk(KERN_ERR "kvm: invalid MSR slot!");
179 rdmsrl_safe(msr, &value);
180 smsr->values[slot].host = value;
181 smsr->values[slot].curr = value;
184 void kvm_define_shared_msr(unsigned slot, u32 msr)
186 if (slot >= shared_msrs_global.nr)
187 shared_msrs_global.nr = slot + 1;
188 shared_msrs_global.msrs[slot] = msr;
189 /* we need ensured the shared_msr_global have been updated */
192 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
194 static void kvm_shared_msr_cpu_online(void)
198 for (i = 0; i < shared_msrs_global.nr; ++i)
199 shared_msr_update(i, shared_msrs_global.msrs[i]);
202 void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
204 struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
206 if (((value ^ smsr->values[slot].curr) & mask) == 0)
208 smsr->values[slot].curr = value;
209 wrmsrl(shared_msrs_global.msrs[slot], value);
210 if (!smsr->registered) {
211 smsr->urn.on_user_return = kvm_on_user_return;
212 user_return_notifier_register(&smsr->urn);
213 smsr->registered = true;
216 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
218 static void drop_user_return_notifiers(void *ignore)
220 struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
222 if (smsr->registered)
223 kvm_on_user_return(&smsr->urn);
226 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
228 if (irqchip_in_kernel(vcpu->kvm))
229 return vcpu->arch.apic_base;
231 return vcpu->arch.apic_base;
233 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
235 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
237 /* TODO: reserve bits check */
238 if (irqchip_in_kernel(vcpu->kvm))
239 kvm_lapic_set_base(vcpu, data);
241 vcpu->arch.apic_base = data;
243 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
245 #define EXCPT_BENIGN 0
246 #define EXCPT_CONTRIBUTORY 1
249 static int exception_class(int vector)
259 return EXCPT_CONTRIBUTORY;
266 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
267 unsigned nr, bool has_error, u32 error_code)
272 if (!vcpu->arch.exception.pending) {
274 vcpu->arch.exception.pending = true;
275 vcpu->arch.exception.has_error_code = has_error;
276 vcpu->arch.exception.nr = nr;
277 vcpu->arch.exception.error_code = error_code;
281 /* to check exception */
282 prev_nr = vcpu->arch.exception.nr;
283 if (prev_nr == DF_VECTOR) {
284 /* triple fault -> shutdown */
285 set_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests);
288 class1 = exception_class(prev_nr);
289 class2 = exception_class(nr);
290 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
291 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
292 /* generate double fault per SDM Table 5-5 */
293 vcpu->arch.exception.pending = true;
294 vcpu->arch.exception.has_error_code = true;
295 vcpu->arch.exception.nr = DF_VECTOR;
296 vcpu->arch.exception.error_code = 0;
298 /* replace previous exception with a new one in a hope
299 that instruction re-execution will regenerate lost
304 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
306 kvm_multiple_exception(vcpu, nr, false, 0);
308 EXPORT_SYMBOL_GPL(kvm_queue_exception);
310 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, unsigned long addr,
313 ++vcpu->stat.pf_guest;
314 vcpu->arch.cr2 = addr;
315 kvm_queue_exception_e(vcpu, PF_VECTOR, error_code);
318 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
320 vcpu->arch.nmi_pending = 1;
322 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
324 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
326 kvm_multiple_exception(vcpu, nr, true, error_code);
328 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
331 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
332 * a #GP and return false.
334 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
336 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
338 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
341 EXPORT_SYMBOL_GPL(kvm_require_cpl);
344 * Load the pae pdptrs. Return true is they are all valid.
346 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
348 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
349 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
352 u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
354 ret = kvm_read_guest_page(vcpu->kvm, pdpt_gfn, pdpte,
355 offset * sizeof(u64), sizeof(pdpte));
360 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
361 if (is_present_gpte(pdpte[i]) &&
362 (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
369 memcpy(vcpu->arch.pdptrs, pdpte, sizeof(vcpu->arch.pdptrs));
370 __set_bit(VCPU_EXREG_PDPTR,
371 (unsigned long *)&vcpu->arch.regs_avail);
372 __set_bit(VCPU_EXREG_PDPTR,
373 (unsigned long *)&vcpu->arch.regs_dirty);
378 EXPORT_SYMBOL_GPL(load_pdptrs);
380 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
382 u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
386 if (is_long_mode(vcpu) || !is_pae(vcpu))
389 if (!test_bit(VCPU_EXREG_PDPTR,
390 (unsigned long *)&vcpu->arch.regs_avail))
393 r = kvm_read_guest(vcpu->kvm, vcpu->arch.cr3 & ~31u, pdpte, sizeof(pdpte));
396 changed = memcmp(pdpte, vcpu->arch.pdptrs, sizeof(pdpte)) != 0;
402 void kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
407 if (cr0 & 0xffffffff00000000UL) {
408 kvm_inject_gp(vcpu, 0);
413 cr0 &= ~CR0_RESERVED_BITS;
415 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD)) {
416 kvm_inject_gp(vcpu, 0);
420 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE)) {
421 kvm_inject_gp(vcpu, 0);
425 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
427 if ((vcpu->arch.efer & EFER_LME)) {
431 kvm_inject_gp(vcpu, 0);
434 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
436 kvm_inject_gp(vcpu, 0);
442 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.cr3)) {
443 kvm_inject_gp(vcpu, 0);
449 kvm_x86_ops->set_cr0(vcpu, cr0);
451 kvm_mmu_reset_context(vcpu);
454 EXPORT_SYMBOL_GPL(kvm_set_cr0);
456 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
458 kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0ful) | (msw & 0x0f));
460 EXPORT_SYMBOL_GPL(kvm_lmsw);
462 void kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
464 unsigned long old_cr4 = kvm_read_cr4(vcpu);
465 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE;
467 if (cr4 & CR4_RESERVED_BITS) {
468 kvm_inject_gp(vcpu, 0);
472 if (is_long_mode(vcpu)) {
473 if (!(cr4 & X86_CR4_PAE)) {
474 kvm_inject_gp(vcpu, 0);
477 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
478 && ((cr4 ^ old_cr4) & pdptr_bits)
479 && !load_pdptrs(vcpu, vcpu->arch.cr3)) {
480 kvm_inject_gp(vcpu, 0);
484 if (cr4 & X86_CR4_VMXE) {
485 kvm_inject_gp(vcpu, 0);
488 kvm_x86_ops->set_cr4(vcpu, cr4);
489 vcpu->arch.cr4 = cr4;
490 vcpu->arch.mmu.base_role.cr4_pge = (cr4 & X86_CR4_PGE) && !tdp_enabled;
491 kvm_mmu_reset_context(vcpu);
493 EXPORT_SYMBOL_GPL(kvm_set_cr4);
495 void kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
497 if (cr3 == vcpu->arch.cr3 && !pdptrs_changed(vcpu)) {
498 kvm_mmu_sync_roots(vcpu);
499 kvm_mmu_flush_tlb(vcpu);
503 if (is_long_mode(vcpu)) {
504 if (cr3 & CR3_L_MODE_RESERVED_BITS) {
505 kvm_inject_gp(vcpu, 0);
510 if (cr3 & CR3_PAE_RESERVED_BITS) {
511 kvm_inject_gp(vcpu, 0);
514 if (is_paging(vcpu) && !load_pdptrs(vcpu, cr3)) {
515 kvm_inject_gp(vcpu, 0);
520 * We don't check reserved bits in nonpae mode, because
521 * this isn't enforced, and VMware depends on this.
526 * Does the new cr3 value map to physical memory? (Note, we
527 * catch an invalid cr3 even in real-mode, because it would
528 * cause trouble later on when we turn on paging anyway.)
530 * A real CPU would silently accept an invalid cr3 and would
531 * attempt to use it - with largely undefined (and often hard
532 * to debug) behavior on the guest side.
534 if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
535 kvm_inject_gp(vcpu, 0);
537 vcpu->arch.cr3 = cr3;
538 vcpu->arch.mmu.new_cr3(vcpu);
541 EXPORT_SYMBOL_GPL(kvm_set_cr3);
543 void kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
545 if (cr8 & CR8_RESERVED_BITS) {
546 kvm_inject_gp(vcpu, 0);
549 if (irqchip_in_kernel(vcpu->kvm))
550 kvm_lapic_set_tpr(vcpu, cr8);
552 vcpu->arch.cr8 = cr8;
554 EXPORT_SYMBOL_GPL(kvm_set_cr8);
556 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
558 if (irqchip_in_kernel(vcpu->kvm))
559 return kvm_lapic_get_cr8(vcpu);
561 return vcpu->arch.cr8;
563 EXPORT_SYMBOL_GPL(kvm_get_cr8);
565 static inline u32 bit(int bitno)
567 return 1 << (bitno & 31);
571 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
572 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
574 * This list is modified at module load time to reflect the
575 * capabilities of the host cpu. This capabilities test skips MSRs that are
576 * kvm-specific. Those are put in the beginning of the list.
579 #define KVM_SAVE_MSRS_BEGIN 5
580 static u32 msrs_to_save[] = {
581 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
582 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
583 HV_X64_MSR_APIC_ASSIST_PAGE,
584 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
587 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
589 MSR_IA32_TSC, MSR_IA32_PERF_STATUS, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA
592 static unsigned num_msrs_to_save;
594 static u32 emulated_msrs[] = {
595 MSR_IA32_MISC_ENABLE,
598 static void set_efer(struct kvm_vcpu *vcpu, u64 efer)
600 if (efer & efer_reserved_bits) {
601 kvm_inject_gp(vcpu, 0);
606 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME)) {
607 kvm_inject_gp(vcpu, 0);
611 if (efer & EFER_FFXSR) {
612 struct kvm_cpuid_entry2 *feat;
614 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
615 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT))) {
616 kvm_inject_gp(vcpu, 0);
621 if (efer & EFER_SVME) {
622 struct kvm_cpuid_entry2 *feat;
624 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
625 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM))) {
626 kvm_inject_gp(vcpu, 0);
631 kvm_x86_ops->set_efer(vcpu, efer);
634 efer |= vcpu->arch.efer & EFER_LMA;
636 vcpu->arch.efer = efer;
638 vcpu->arch.mmu.base_role.nxe = (efer & EFER_NX) && !tdp_enabled;
639 kvm_mmu_reset_context(vcpu);
642 void kvm_enable_efer_bits(u64 mask)
644 efer_reserved_bits &= ~mask;
646 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
650 * Writes msr value into into the appropriate "register".
651 * Returns 0 on success, non-0 otherwise.
652 * Assumes vcpu_load() was already called.
654 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
656 return kvm_x86_ops->set_msr(vcpu, msr_index, data);
660 * Adapt set_msr() to msr_io()'s calling convention
662 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
664 return kvm_set_msr(vcpu, index, *data);
667 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
670 struct pvclock_wall_clock wc;
671 struct timespec boot;
678 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
681 * The guest calculates current wall clock time by adding
682 * system time (updated by kvm_write_guest_time below) to the
683 * wall clock specified here. guest system time equals host
684 * system time for us, thus we must fill in host boot time here.
688 wc.sec = boot.tv_sec;
689 wc.nsec = boot.tv_nsec;
690 wc.version = version;
692 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
695 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
698 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
700 uint32_t quotient, remainder;
702 /* Don't try to replace with do_div(), this one calculates
703 * "(dividend << 32) / divisor" */
705 : "=a" (quotient), "=d" (remainder)
706 : "0" (0), "1" (dividend), "r" (divisor) );
710 static void kvm_set_time_scale(uint32_t tsc_khz, struct pvclock_vcpu_time_info *hv_clock)
712 uint64_t nsecs = 1000000000LL;
717 tps64 = tsc_khz * 1000LL;
718 while (tps64 > nsecs*2) {
723 tps32 = (uint32_t)tps64;
724 while (tps32 <= (uint32_t)nsecs) {
729 hv_clock->tsc_shift = shift;
730 hv_clock->tsc_to_system_mul = div_frac(nsecs, tps32);
732 pr_debug("%s: tsc_khz %u, tsc_shift %d, tsc_mul %u\n",
733 __func__, tsc_khz, hv_clock->tsc_shift,
734 hv_clock->tsc_to_system_mul);
737 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
739 static void kvm_write_guest_time(struct kvm_vcpu *v)
743 struct kvm_vcpu_arch *vcpu = &v->arch;
745 unsigned long this_tsc_khz;
747 if ((!vcpu->time_page))
750 this_tsc_khz = get_cpu_var(cpu_tsc_khz);
751 if (unlikely(vcpu->hv_clock_tsc_khz != this_tsc_khz)) {
752 kvm_set_time_scale(this_tsc_khz, &vcpu->hv_clock);
753 vcpu->hv_clock_tsc_khz = this_tsc_khz;
755 put_cpu_var(cpu_tsc_khz);
757 /* Keep irq disabled to prevent changes to the clock */
758 local_irq_save(flags);
759 kvm_get_msr(v, MSR_IA32_TSC, &vcpu->hv_clock.tsc_timestamp);
761 monotonic_to_bootbased(&ts);
762 local_irq_restore(flags);
764 /* With all the info we got, fill in the values */
766 vcpu->hv_clock.system_time = ts.tv_nsec +
767 (NSEC_PER_SEC * (u64)ts.tv_sec) + v->kvm->arch.kvmclock_offset;
770 * The interface expects us to write an even number signaling that the
771 * update is finished. Since the guest won't see the intermediate
772 * state, we just increase by 2 at the end.
774 vcpu->hv_clock.version += 2;
776 shared_kaddr = kmap_atomic(vcpu->time_page, KM_USER0);
778 memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
779 sizeof(vcpu->hv_clock));
781 kunmap_atomic(shared_kaddr, KM_USER0);
783 mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
786 static int kvm_request_guest_time_update(struct kvm_vcpu *v)
788 struct kvm_vcpu_arch *vcpu = &v->arch;
790 if (!vcpu->time_page)
792 set_bit(KVM_REQ_KVMCLOCK_UPDATE, &v->requests);
796 static bool msr_mtrr_valid(unsigned msr)
799 case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
800 case MSR_MTRRfix64K_00000:
801 case MSR_MTRRfix16K_80000:
802 case MSR_MTRRfix16K_A0000:
803 case MSR_MTRRfix4K_C0000:
804 case MSR_MTRRfix4K_C8000:
805 case MSR_MTRRfix4K_D0000:
806 case MSR_MTRRfix4K_D8000:
807 case MSR_MTRRfix4K_E0000:
808 case MSR_MTRRfix4K_E8000:
809 case MSR_MTRRfix4K_F0000:
810 case MSR_MTRRfix4K_F8000:
811 case MSR_MTRRdefType:
812 case MSR_IA32_CR_PAT:
820 static bool valid_pat_type(unsigned t)
822 return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
825 static bool valid_mtrr_type(unsigned t)
827 return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
830 static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
834 if (!msr_mtrr_valid(msr))
837 if (msr == MSR_IA32_CR_PAT) {
838 for (i = 0; i < 8; i++)
839 if (!valid_pat_type((data >> (i * 8)) & 0xff))
842 } else if (msr == MSR_MTRRdefType) {
845 return valid_mtrr_type(data & 0xff);
846 } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
847 for (i = 0; i < 8 ; i++)
848 if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
854 return valid_mtrr_type(data & 0xff);
857 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
859 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
861 if (!mtrr_valid(vcpu, msr, data))
864 if (msr == MSR_MTRRdefType) {
865 vcpu->arch.mtrr_state.def_type = data;
866 vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
867 } else if (msr == MSR_MTRRfix64K_00000)
869 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
870 p[1 + msr - MSR_MTRRfix16K_80000] = data;
871 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
872 p[3 + msr - MSR_MTRRfix4K_C0000] = data;
873 else if (msr == MSR_IA32_CR_PAT)
874 vcpu->arch.pat = data;
875 else { /* Variable MTRRs */
876 int idx, is_mtrr_mask;
879 idx = (msr - 0x200) / 2;
880 is_mtrr_mask = msr - 0x200 - 2 * idx;
883 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
886 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
890 kvm_mmu_reset_context(vcpu);
894 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
896 u64 mcg_cap = vcpu->arch.mcg_cap;
897 unsigned bank_num = mcg_cap & 0xff;
900 case MSR_IA32_MCG_STATUS:
901 vcpu->arch.mcg_status = data;
903 case MSR_IA32_MCG_CTL:
904 if (!(mcg_cap & MCG_CTL_P))
906 if (data != 0 && data != ~(u64)0)
908 vcpu->arch.mcg_ctl = data;
911 if (msr >= MSR_IA32_MC0_CTL &&
912 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
913 u32 offset = msr - MSR_IA32_MC0_CTL;
914 /* only 0 or all 1s can be written to IA32_MCi_CTL
915 * some Linux kernels though clear bit 10 in bank 4 to
916 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
917 * this to avoid an uncatched #GP in the guest
919 if ((offset & 0x3) == 0 &&
920 data != 0 && (data | (1 << 10)) != ~(u64)0)
922 vcpu->arch.mce_banks[offset] = data;
930 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
932 struct kvm *kvm = vcpu->kvm;
933 int lm = is_long_mode(vcpu);
934 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
935 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
936 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
937 : kvm->arch.xen_hvm_config.blob_size_32;
938 u32 page_num = data & ~PAGE_MASK;
939 u64 page_addr = data & PAGE_MASK;
944 if (page_num >= blob_size)
947 page = kzalloc(PAGE_SIZE, GFP_KERNEL);
951 if (copy_from_user(page, blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE))
953 if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
962 static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
964 return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
967 static bool kvm_hv_msr_partition_wide(u32 msr)
971 case HV_X64_MSR_GUEST_OS_ID:
972 case HV_X64_MSR_HYPERCALL:
980 static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
982 struct kvm *kvm = vcpu->kvm;
985 case HV_X64_MSR_GUEST_OS_ID:
986 kvm->arch.hv_guest_os_id = data;
987 /* setting guest os id to zero disables hypercall page */
988 if (!kvm->arch.hv_guest_os_id)
989 kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
991 case HV_X64_MSR_HYPERCALL: {
996 /* if guest os id is not set hypercall should remain disabled */
997 if (!kvm->arch.hv_guest_os_id)
999 if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
1000 kvm->arch.hv_hypercall = data;
1003 gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
1004 addr = gfn_to_hva(kvm, gfn);
1005 if (kvm_is_error_hva(addr))
1007 kvm_x86_ops->patch_hypercall(vcpu, instructions);
1008 ((unsigned char *)instructions)[3] = 0xc3; /* ret */
1009 if (copy_to_user((void __user *)addr, instructions, 4))
1011 kvm->arch.hv_hypercall = data;
1015 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1016 "data 0x%llx\n", msr, data);
1022 static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1025 case HV_X64_MSR_APIC_ASSIST_PAGE: {
1028 if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
1029 vcpu->arch.hv_vapic = data;
1032 addr = gfn_to_hva(vcpu->kvm, data >>
1033 HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
1034 if (kvm_is_error_hva(addr))
1036 if (clear_user((void __user *)addr, PAGE_SIZE))
1038 vcpu->arch.hv_vapic = data;
1041 case HV_X64_MSR_EOI:
1042 return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
1043 case HV_X64_MSR_ICR:
1044 return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
1045 case HV_X64_MSR_TPR:
1046 return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
1048 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1049 "data 0x%llx\n", msr, data);
1056 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1060 set_efer(vcpu, data);
1063 data &= ~(u64)0x40; /* ignore flush filter disable */
1064 data &= ~(u64)0x100; /* ignore ignne emulation enable */
1066 pr_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
1071 case MSR_FAM10H_MMIO_CONF_BASE:
1073 pr_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
1078 case MSR_AMD64_NB_CFG:
1080 case MSR_IA32_DEBUGCTLMSR:
1082 /* We support the non-activated case already */
1084 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
1085 /* Values other than LBR and BTF are vendor-specific,
1086 thus reserved and should throw a #GP */
1089 pr_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
1092 case MSR_IA32_UCODE_REV:
1093 case MSR_IA32_UCODE_WRITE:
1094 case MSR_VM_HSAVE_PA:
1095 case MSR_AMD64_PATCH_LOADER:
1097 case 0x200 ... 0x2ff:
1098 return set_msr_mtrr(vcpu, msr, data);
1099 case MSR_IA32_APICBASE:
1100 kvm_set_apic_base(vcpu, data);
1102 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1103 return kvm_x2apic_msr_write(vcpu, msr, data);
1104 case MSR_IA32_MISC_ENABLE:
1105 vcpu->arch.ia32_misc_enable_msr = data;
1107 case MSR_KVM_WALL_CLOCK:
1108 vcpu->kvm->arch.wall_clock = data;
1109 kvm_write_wall_clock(vcpu->kvm, data);
1111 case MSR_KVM_SYSTEM_TIME: {
1112 if (vcpu->arch.time_page) {
1113 kvm_release_page_dirty(vcpu->arch.time_page);
1114 vcpu->arch.time_page = NULL;
1117 vcpu->arch.time = data;
1119 /* we verify if the enable bit is set... */
1123 /* ...but clean it before doing the actual write */
1124 vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
1126 vcpu->arch.time_page =
1127 gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
1129 if (is_error_page(vcpu->arch.time_page)) {
1130 kvm_release_page_clean(vcpu->arch.time_page);
1131 vcpu->arch.time_page = NULL;
1134 kvm_request_guest_time_update(vcpu);
1137 case MSR_IA32_MCG_CTL:
1138 case MSR_IA32_MCG_STATUS:
1139 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1140 return set_msr_mce(vcpu, msr, data);
1142 /* Performance counters are not protected by a CPUID bit,
1143 * so we should check all of them in the generic path for the sake of
1144 * cross vendor migration.
1145 * Writing a zero into the event select MSRs disables them,
1146 * which we perfectly emulate ;-). Any other value should be at least
1147 * reported, some guests depend on them.
1149 case MSR_P6_EVNTSEL0:
1150 case MSR_P6_EVNTSEL1:
1151 case MSR_K7_EVNTSEL0:
1152 case MSR_K7_EVNTSEL1:
1153 case MSR_K7_EVNTSEL2:
1154 case MSR_K7_EVNTSEL3:
1156 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1157 "0x%x data 0x%llx\n", msr, data);
1159 /* at least RHEL 4 unconditionally writes to the perfctr registers,
1160 * so we ignore writes to make it happy.
1162 case MSR_P6_PERFCTR0:
1163 case MSR_P6_PERFCTR1:
1164 case MSR_K7_PERFCTR0:
1165 case MSR_K7_PERFCTR1:
1166 case MSR_K7_PERFCTR2:
1167 case MSR_K7_PERFCTR3:
1168 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1169 "0x%x data 0x%llx\n", msr, data);
1171 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1172 if (kvm_hv_msr_partition_wide(msr)) {
1174 mutex_lock(&vcpu->kvm->lock);
1175 r = set_msr_hyperv_pw(vcpu, msr, data);
1176 mutex_unlock(&vcpu->kvm->lock);
1179 return set_msr_hyperv(vcpu, msr, data);
1182 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
1183 return xen_hvm_config(vcpu, data);
1185 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
1189 pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
1196 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
1200 * Reads an msr value (of 'msr_index') into 'pdata'.
1201 * Returns 0 on success, non-0 otherwise.
1202 * Assumes vcpu_load() was already called.
1204 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1206 return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
1209 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1211 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1213 if (!msr_mtrr_valid(msr))
1216 if (msr == MSR_MTRRdefType)
1217 *pdata = vcpu->arch.mtrr_state.def_type +
1218 (vcpu->arch.mtrr_state.enabled << 10);
1219 else if (msr == MSR_MTRRfix64K_00000)
1221 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1222 *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
1223 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1224 *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
1225 else if (msr == MSR_IA32_CR_PAT)
1226 *pdata = vcpu->arch.pat;
1227 else { /* Variable MTRRs */
1228 int idx, is_mtrr_mask;
1231 idx = (msr - 0x200) / 2;
1232 is_mtrr_mask = msr - 0x200 - 2 * idx;
1235 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1238 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1245 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1248 u64 mcg_cap = vcpu->arch.mcg_cap;
1249 unsigned bank_num = mcg_cap & 0xff;
1252 case MSR_IA32_P5_MC_ADDR:
1253 case MSR_IA32_P5_MC_TYPE:
1256 case MSR_IA32_MCG_CAP:
1257 data = vcpu->arch.mcg_cap;
1259 case MSR_IA32_MCG_CTL:
1260 if (!(mcg_cap & MCG_CTL_P))
1262 data = vcpu->arch.mcg_ctl;
1264 case MSR_IA32_MCG_STATUS:
1265 data = vcpu->arch.mcg_status;
1268 if (msr >= MSR_IA32_MC0_CTL &&
1269 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1270 u32 offset = msr - MSR_IA32_MC0_CTL;
1271 data = vcpu->arch.mce_banks[offset];
1280 static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1283 struct kvm *kvm = vcpu->kvm;
1286 case HV_X64_MSR_GUEST_OS_ID:
1287 data = kvm->arch.hv_guest_os_id;
1289 case HV_X64_MSR_HYPERCALL:
1290 data = kvm->arch.hv_hypercall;
1293 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1301 static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1306 case HV_X64_MSR_VP_INDEX: {
1309 kvm_for_each_vcpu(r, v, vcpu->kvm)
1314 case HV_X64_MSR_EOI:
1315 return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
1316 case HV_X64_MSR_ICR:
1317 return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
1318 case HV_X64_MSR_TPR:
1319 return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
1321 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1328 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1333 case MSR_IA32_PLATFORM_ID:
1334 case MSR_IA32_UCODE_REV:
1335 case MSR_IA32_EBL_CR_POWERON:
1336 case MSR_IA32_DEBUGCTLMSR:
1337 case MSR_IA32_LASTBRANCHFROMIP:
1338 case MSR_IA32_LASTBRANCHTOIP:
1339 case MSR_IA32_LASTINTFROMIP:
1340 case MSR_IA32_LASTINTTOIP:
1343 case MSR_VM_HSAVE_PA:
1344 case MSR_P6_PERFCTR0:
1345 case MSR_P6_PERFCTR1:
1346 case MSR_P6_EVNTSEL0:
1347 case MSR_P6_EVNTSEL1:
1348 case MSR_K7_EVNTSEL0:
1349 case MSR_K7_PERFCTR0:
1350 case MSR_K8_INT_PENDING_MSG:
1351 case MSR_AMD64_NB_CFG:
1352 case MSR_FAM10H_MMIO_CONF_BASE:
1356 data = 0x500 | KVM_NR_VAR_MTRR;
1358 case 0x200 ... 0x2ff:
1359 return get_msr_mtrr(vcpu, msr, pdata);
1360 case 0xcd: /* fsb frequency */
1363 case MSR_IA32_APICBASE:
1364 data = kvm_get_apic_base(vcpu);
1366 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1367 return kvm_x2apic_msr_read(vcpu, msr, pdata);
1369 case MSR_IA32_MISC_ENABLE:
1370 data = vcpu->arch.ia32_misc_enable_msr;
1372 case MSR_IA32_PERF_STATUS:
1373 /* TSC increment by tick */
1375 /* CPU multiplier */
1376 data |= (((uint64_t)4ULL) << 40);
1379 data = vcpu->arch.efer;
1381 case MSR_KVM_WALL_CLOCK:
1382 data = vcpu->kvm->arch.wall_clock;
1384 case MSR_KVM_SYSTEM_TIME:
1385 data = vcpu->arch.time;
1387 case MSR_IA32_P5_MC_ADDR:
1388 case MSR_IA32_P5_MC_TYPE:
1389 case MSR_IA32_MCG_CAP:
1390 case MSR_IA32_MCG_CTL:
1391 case MSR_IA32_MCG_STATUS:
1392 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1393 return get_msr_mce(vcpu, msr, pdata);
1394 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1395 if (kvm_hv_msr_partition_wide(msr)) {
1397 mutex_lock(&vcpu->kvm->lock);
1398 r = get_msr_hyperv_pw(vcpu, msr, pdata);
1399 mutex_unlock(&vcpu->kvm->lock);
1402 return get_msr_hyperv(vcpu, msr, pdata);
1406 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
1409 pr_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
1417 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
1420 * Read or write a bunch of msrs. All parameters are kernel addresses.
1422 * @return number of msrs set successfully.
1424 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
1425 struct kvm_msr_entry *entries,
1426 int (*do_msr)(struct kvm_vcpu *vcpu,
1427 unsigned index, u64 *data))
1433 idx = srcu_read_lock(&vcpu->kvm->srcu);
1434 for (i = 0; i < msrs->nmsrs; ++i)
1435 if (do_msr(vcpu, entries[i].index, &entries[i].data))
1437 srcu_read_unlock(&vcpu->kvm->srcu, idx);
1445 * Read or write a bunch of msrs. Parameters are user addresses.
1447 * @return number of msrs set successfully.
1449 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
1450 int (*do_msr)(struct kvm_vcpu *vcpu,
1451 unsigned index, u64 *data),
1454 struct kvm_msrs msrs;
1455 struct kvm_msr_entry *entries;
1460 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
1464 if (msrs.nmsrs >= MAX_IO_MSRS)
1468 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
1469 entries = vmalloc(size);
1474 if (copy_from_user(entries, user_msrs->entries, size))
1477 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
1482 if (writeback && copy_to_user(user_msrs->entries, entries, size))
1493 int kvm_dev_ioctl_check_extension(long ext)
1498 case KVM_CAP_IRQCHIP:
1500 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
1501 case KVM_CAP_SET_TSS_ADDR:
1502 case KVM_CAP_EXT_CPUID:
1503 case KVM_CAP_CLOCKSOURCE:
1505 case KVM_CAP_NOP_IO_DELAY:
1506 case KVM_CAP_MP_STATE:
1507 case KVM_CAP_SYNC_MMU:
1508 case KVM_CAP_REINJECT_CONTROL:
1509 case KVM_CAP_IRQ_INJECT_STATUS:
1510 case KVM_CAP_ASSIGN_DEV_IRQ:
1512 case KVM_CAP_IOEVENTFD:
1514 case KVM_CAP_PIT_STATE2:
1515 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
1516 case KVM_CAP_XEN_HVM:
1517 case KVM_CAP_ADJUST_CLOCK:
1518 case KVM_CAP_VCPU_EVENTS:
1519 case KVM_CAP_HYPERV:
1520 case KVM_CAP_HYPERV_VAPIC:
1521 case KVM_CAP_HYPERV_SPIN:
1522 case KVM_CAP_PCI_SEGMENT:
1523 case KVM_CAP_DEBUGREGS:
1524 case KVM_CAP_X86_ROBUST_SINGLESTEP:
1527 case KVM_CAP_COALESCED_MMIO:
1528 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
1531 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
1533 case KVM_CAP_NR_VCPUS:
1536 case KVM_CAP_NR_MEMSLOTS:
1537 r = KVM_MEMORY_SLOTS;
1539 case KVM_CAP_PV_MMU: /* obsolete */
1546 r = KVM_MAX_MCE_BANKS;
1556 long kvm_arch_dev_ioctl(struct file *filp,
1557 unsigned int ioctl, unsigned long arg)
1559 void __user *argp = (void __user *)arg;
1563 case KVM_GET_MSR_INDEX_LIST: {
1564 struct kvm_msr_list __user *user_msr_list = argp;
1565 struct kvm_msr_list msr_list;
1569 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
1572 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
1573 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
1576 if (n < msr_list.nmsrs)
1579 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
1580 num_msrs_to_save * sizeof(u32)))
1582 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
1584 ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
1589 case KVM_GET_SUPPORTED_CPUID: {
1590 struct kvm_cpuid2 __user *cpuid_arg = argp;
1591 struct kvm_cpuid2 cpuid;
1594 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1596 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
1597 cpuid_arg->entries);
1602 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1607 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
1610 mce_cap = KVM_MCE_CAP_SUPPORTED;
1612 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
1624 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1626 kvm_x86_ops->vcpu_load(vcpu, cpu);
1627 if (unlikely(per_cpu(cpu_tsc_khz, cpu) == 0)) {
1628 unsigned long khz = cpufreq_quick_get(cpu);
1631 per_cpu(cpu_tsc_khz, cpu) = khz;
1633 kvm_request_guest_time_update(vcpu);
1636 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
1638 kvm_put_guest_fpu(vcpu);
1639 kvm_x86_ops->vcpu_put(vcpu);
1642 static int is_efer_nx(void)
1644 unsigned long long efer = 0;
1646 rdmsrl_safe(MSR_EFER, &efer);
1647 return efer & EFER_NX;
1650 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
1653 struct kvm_cpuid_entry2 *e, *entry;
1656 for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
1657 e = &vcpu->arch.cpuid_entries[i];
1658 if (e->function == 0x80000001) {
1663 if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
1664 entry->edx &= ~(1 << 20);
1665 printk(KERN_INFO "kvm: guest NX capability removed\n");
1669 /* when an old userspace process fills a new kernel module */
1670 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
1671 struct kvm_cpuid *cpuid,
1672 struct kvm_cpuid_entry __user *entries)
1675 struct kvm_cpuid_entry *cpuid_entries;
1678 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1681 cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
1685 if (copy_from_user(cpuid_entries, entries,
1686 cpuid->nent * sizeof(struct kvm_cpuid_entry)))
1688 for (i = 0; i < cpuid->nent; i++) {
1689 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
1690 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
1691 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
1692 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
1693 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
1694 vcpu->arch.cpuid_entries[i].index = 0;
1695 vcpu->arch.cpuid_entries[i].flags = 0;
1696 vcpu->arch.cpuid_entries[i].padding[0] = 0;
1697 vcpu->arch.cpuid_entries[i].padding[1] = 0;
1698 vcpu->arch.cpuid_entries[i].padding[2] = 0;
1700 vcpu->arch.cpuid_nent = cpuid->nent;
1701 cpuid_fix_nx_cap(vcpu);
1703 kvm_apic_set_version(vcpu);
1704 kvm_x86_ops->cpuid_update(vcpu);
1707 vfree(cpuid_entries);
1712 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
1713 struct kvm_cpuid2 *cpuid,
1714 struct kvm_cpuid_entry2 __user *entries)
1719 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1722 if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
1723 cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
1725 vcpu->arch.cpuid_nent = cpuid->nent;
1726 kvm_apic_set_version(vcpu);
1727 kvm_x86_ops->cpuid_update(vcpu);
1734 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
1735 struct kvm_cpuid2 *cpuid,
1736 struct kvm_cpuid_entry2 __user *entries)
1741 if (cpuid->nent < vcpu->arch.cpuid_nent)
1744 if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
1745 vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
1750 cpuid->nent = vcpu->arch.cpuid_nent;
1754 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1757 entry->function = function;
1758 entry->index = index;
1759 cpuid_count(entry->function, entry->index,
1760 &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
1764 #define F(x) bit(X86_FEATURE_##x)
1766 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1767 u32 index, int *nent, int maxnent)
1769 unsigned f_nx = is_efer_nx() ? F(NX) : 0;
1770 #ifdef CONFIG_X86_64
1771 unsigned f_gbpages = (kvm_x86_ops->get_lpage_level() == PT_PDPE_LEVEL)
1773 unsigned f_lm = F(LM);
1775 unsigned f_gbpages = 0;
1778 unsigned f_rdtscp = kvm_x86_ops->rdtscp_supported() ? F(RDTSCP) : 0;
1781 const u32 kvm_supported_word0_x86_features =
1782 F(FPU) | F(VME) | F(DE) | F(PSE) |
1783 F(TSC) | F(MSR) | F(PAE) | F(MCE) |
1784 F(CX8) | F(APIC) | 0 /* Reserved */ | F(SEP) |
1785 F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
1786 F(PAT) | F(PSE36) | 0 /* PSN */ | F(CLFLSH) |
1787 0 /* Reserved, DS, ACPI */ | F(MMX) |
1788 F(FXSR) | F(XMM) | F(XMM2) | F(SELFSNOOP) |
1789 0 /* HTT, TM, Reserved, PBE */;
1790 /* cpuid 0x80000001.edx */
1791 const u32 kvm_supported_word1_x86_features =
1792 F(FPU) | F(VME) | F(DE) | F(PSE) |
1793 F(TSC) | F(MSR) | F(PAE) | F(MCE) |
1794 F(CX8) | F(APIC) | 0 /* Reserved */ | F(SYSCALL) |
1795 F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
1796 F(PAT) | F(PSE36) | 0 /* Reserved */ |
1797 f_nx | 0 /* Reserved */ | F(MMXEXT) | F(MMX) |
1798 F(FXSR) | F(FXSR_OPT) | f_gbpages | f_rdtscp |
1799 0 /* Reserved */ | f_lm | F(3DNOWEXT) | F(3DNOW);
1801 const u32 kvm_supported_word4_x86_features =
1802 F(XMM3) | 0 /* Reserved, DTES64, MONITOR */ |
1803 0 /* DS-CPL, VMX, SMX, EST */ |
1804 0 /* TM2 */ | F(SSSE3) | 0 /* CNXT-ID */ | 0 /* Reserved */ |
1805 0 /* Reserved */ | F(CX16) | 0 /* xTPR Update, PDCM */ |
1806 0 /* Reserved, DCA */ | F(XMM4_1) |
1807 F(XMM4_2) | F(X2APIC) | F(MOVBE) | F(POPCNT) |
1808 0 /* Reserved, XSAVE, OSXSAVE */;
1809 /* cpuid 0x80000001.ecx */
1810 const u32 kvm_supported_word6_x86_features =
1811 F(LAHF_LM) | F(CMP_LEGACY) | F(SVM) | 0 /* ExtApicSpace */ |
1812 F(CR8_LEGACY) | F(ABM) | F(SSE4A) | F(MISALIGNSSE) |
1813 F(3DNOWPREFETCH) | 0 /* OSVW */ | 0 /* IBS */ | F(SSE5) |
1814 0 /* SKINIT */ | 0 /* WDT */;
1816 /* all calls to cpuid_count() should be made on the same cpu */
1818 do_cpuid_1_ent(entry, function, index);
1823 entry->eax = min(entry->eax, (u32)0xb);
1826 entry->edx &= kvm_supported_word0_x86_features;
1827 entry->ecx &= kvm_supported_word4_x86_features;
1828 /* we support x2apic emulation even if host does not support
1829 * it since we emulate x2apic in software */
1830 entry->ecx |= F(X2APIC);
1832 /* function 2 entries are STATEFUL. That is, repeated cpuid commands
1833 * may return different values. This forces us to get_cpu() before
1834 * issuing the first command, and also to emulate this annoying behavior
1835 * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
1837 int t, times = entry->eax & 0xff;
1839 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1840 entry->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
1841 for (t = 1; t < times && *nent < maxnent; ++t) {
1842 do_cpuid_1_ent(&entry[t], function, 0);
1843 entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1848 /* function 4 and 0xb have additional index. */
1852 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1853 /* read more entries until cache_type is zero */
1854 for (i = 1; *nent < maxnent; ++i) {
1855 cache_type = entry[i - 1].eax & 0x1f;
1858 do_cpuid_1_ent(&entry[i], function, i);
1860 KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1868 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1869 /* read more entries until level_type is zero */
1870 for (i = 1; *nent < maxnent; ++i) {
1871 level_type = entry[i - 1].ecx & 0xff00;
1874 do_cpuid_1_ent(&entry[i], function, i);
1876 KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1882 entry->eax = min(entry->eax, 0x8000001a);
1885 entry->edx &= kvm_supported_word1_x86_features;
1886 entry->ecx &= kvm_supported_word6_x86_features;
1894 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
1895 struct kvm_cpuid_entry2 __user *entries)
1897 struct kvm_cpuid_entry2 *cpuid_entries;
1898 int limit, nent = 0, r = -E2BIG;
1901 if (cpuid->nent < 1)
1903 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1904 cpuid->nent = KVM_MAX_CPUID_ENTRIES;
1906 cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
1910 do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
1911 limit = cpuid_entries[0].eax;
1912 for (func = 1; func <= limit && nent < cpuid->nent; ++func)
1913 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1914 &nent, cpuid->nent);
1916 if (nent >= cpuid->nent)
1919 do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
1920 limit = cpuid_entries[nent - 1].eax;
1921 for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
1922 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1923 &nent, cpuid->nent);
1925 if (nent >= cpuid->nent)
1929 if (copy_to_user(entries, cpuid_entries,
1930 nent * sizeof(struct kvm_cpuid_entry2)))
1936 vfree(cpuid_entries);
1941 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
1942 struct kvm_lapic_state *s)
1945 memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
1951 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
1952 struct kvm_lapic_state *s)
1955 memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
1956 kvm_apic_post_state_restore(vcpu);
1957 update_cr8_intercept(vcpu);
1963 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
1964 struct kvm_interrupt *irq)
1966 if (irq->irq < 0 || irq->irq >= 256)
1968 if (irqchip_in_kernel(vcpu->kvm))
1972 kvm_queue_interrupt(vcpu, irq->irq, false);
1979 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
1982 kvm_inject_nmi(vcpu);
1988 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
1989 struct kvm_tpr_access_ctl *tac)
1993 vcpu->arch.tpr_access_reporting = !!tac->enabled;
1997 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2001 unsigned bank_num = mcg_cap & 0xff, bank;
2004 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2006 if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2009 vcpu->arch.mcg_cap = mcg_cap;
2010 /* Init IA32_MCG_CTL to all 1s */
2011 if (mcg_cap & MCG_CTL_P)
2012 vcpu->arch.mcg_ctl = ~(u64)0;
2013 /* Init IA32_MCi_CTL to all 1s */
2014 for (bank = 0; bank < bank_num; bank++)
2015 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2020 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2021 struct kvm_x86_mce *mce)
2023 u64 mcg_cap = vcpu->arch.mcg_cap;
2024 unsigned bank_num = mcg_cap & 0xff;
2025 u64 *banks = vcpu->arch.mce_banks;
2027 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2030 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2031 * reporting is disabled
2033 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2034 vcpu->arch.mcg_ctl != ~(u64)0)
2036 banks += 4 * mce->bank;
2038 * if IA32_MCi_CTL is not all 1s, the uncorrected error
2039 * reporting is disabled for the bank
2041 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2043 if (mce->status & MCI_STATUS_UC) {
2044 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2045 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2046 printk(KERN_DEBUG "kvm: set_mce: "
2047 "injects mce exception while "
2048 "previous one is in progress!\n");
2049 set_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests);
2052 if (banks[1] & MCI_STATUS_VAL)
2053 mce->status |= MCI_STATUS_OVER;
2054 banks[2] = mce->addr;
2055 banks[3] = mce->misc;
2056 vcpu->arch.mcg_status = mce->mcg_status;
2057 banks[1] = mce->status;
2058 kvm_queue_exception(vcpu, MC_VECTOR);
2059 } else if (!(banks[1] & MCI_STATUS_VAL)
2060 || !(banks[1] & MCI_STATUS_UC)) {
2061 if (banks[1] & MCI_STATUS_VAL)
2062 mce->status |= MCI_STATUS_OVER;
2063 banks[2] = mce->addr;
2064 banks[3] = mce->misc;
2065 banks[1] = mce->status;
2067 banks[1] |= MCI_STATUS_OVER;
2071 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2072 struct kvm_vcpu_events *events)
2076 events->exception.injected =
2077 vcpu->arch.exception.pending &&
2078 !kvm_exception_is_soft(vcpu->arch.exception.nr);
2079 events->exception.nr = vcpu->arch.exception.nr;
2080 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2081 events->exception.error_code = vcpu->arch.exception.error_code;
2083 events->interrupt.injected =
2084 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
2085 events->interrupt.nr = vcpu->arch.interrupt.nr;
2086 events->interrupt.soft = 0;
2087 events->interrupt.shadow =
2088 kvm_x86_ops->get_interrupt_shadow(vcpu,
2089 KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
2091 events->nmi.injected = vcpu->arch.nmi_injected;
2092 events->nmi.pending = vcpu->arch.nmi_pending;
2093 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
2095 events->sipi_vector = vcpu->arch.sipi_vector;
2097 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
2098 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2099 | KVM_VCPUEVENT_VALID_SHADOW);
2104 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
2105 struct kvm_vcpu_events *events)
2107 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
2108 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2109 | KVM_VCPUEVENT_VALID_SHADOW))
2114 vcpu->arch.exception.pending = events->exception.injected;
2115 vcpu->arch.exception.nr = events->exception.nr;
2116 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
2117 vcpu->arch.exception.error_code = events->exception.error_code;
2119 vcpu->arch.interrupt.pending = events->interrupt.injected;
2120 vcpu->arch.interrupt.nr = events->interrupt.nr;
2121 vcpu->arch.interrupt.soft = events->interrupt.soft;
2122 if (vcpu->arch.interrupt.pending && irqchip_in_kernel(vcpu->kvm))
2123 kvm_pic_clear_isr_ack(vcpu->kvm);
2124 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
2125 kvm_x86_ops->set_interrupt_shadow(vcpu,
2126 events->interrupt.shadow);
2128 vcpu->arch.nmi_injected = events->nmi.injected;
2129 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
2130 vcpu->arch.nmi_pending = events->nmi.pending;
2131 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
2133 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR)
2134 vcpu->arch.sipi_vector = events->sipi_vector;
2141 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
2142 struct kvm_debugregs *dbgregs)
2146 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
2147 dbgregs->dr6 = vcpu->arch.dr6;
2148 dbgregs->dr7 = vcpu->arch.dr7;
2154 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
2155 struct kvm_debugregs *dbgregs)
2162 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
2163 vcpu->arch.dr6 = dbgregs->dr6;
2164 vcpu->arch.dr7 = dbgregs->dr7;
2171 long kvm_arch_vcpu_ioctl(struct file *filp,
2172 unsigned int ioctl, unsigned long arg)
2174 struct kvm_vcpu *vcpu = filp->private_data;
2175 void __user *argp = (void __user *)arg;
2177 struct kvm_lapic_state *lapic = NULL;
2180 case KVM_GET_LAPIC: {
2182 if (!vcpu->arch.apic)
2184 lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
2189 r = kvm_vcpu_ioctl_get_lapic(vcpu, lapic);
2193 if (copy_to_user(argp, lapic, sizeof(struct kvm_lapic_state)))
2198 case KVM_SET_LAPIC: {
2200 if (!vcpu->arch.apic)
2202 lapic = kmalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
2207 if (copy_from_user(lapic, argp, sizeof(struct kvm_lapic_state)))
2209 r = kvm_vcpu_ioctl_set_lapic(vcpu, lapic);
2215 case KVM_INTERRUPT: {
2216 struct kvm_interrupt irq;
2219 if (copy_from_user(&irq, argp, sizeof irq))
2221 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
2228 r = kvm_vcpu_ioctl_nmi(vcpu);
2234 case KVM_SET_CPUID: {
2235 struct kvm_cpuid __user *cpuid_arg = argp;
2236 struct kvm_cpuid cpuid;
2239 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2241 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
2246 case KVM_SET_CPUID2: {
2247 struct kvm_cpuid2 __user *cpuid_arg = argp;
2248 struct kvm_cpuid2 cpuid;
2251 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2253 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
2254 cpuid_arg->entries);
2259 case KVM_GET_CPUID2: {
2260 struct kvm_cpuid2 __user *cpuid_arg = argp;
2261 struct kvm_cpuid2 cpuid;
2264 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2266 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
2267 cpuid_arg->entries);
2271 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2277 r = msr_io(vcpu, argp, kvm_get_msr, 1);
2280 r = msr_io(vcpu, argp, do_set_msr, 0);
2282 case KVM_TPR_ACCESS_REPORTING: {
2283 struct kvm_tpr_access_ctl tac;
2286 if (copy_from_user(&tac, argp, sizeof tac))
2288 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
2292 if (copy_to_user(argp, &tac, sizeof tac))
2297 case KVM_SET_VAPIC_ADDR: {
2298 struct kvm_vapic_addr va;
2301 if (!irqchip_in_kernel(vcpu->kvm))
2304 if (copy_from_user(&va, argp, sizeof va))
2307 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
2310 case KVM_X86_SETUP_MCE: {
2314 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
2316 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
2319 case KVM_X86_SET_MCE: {
2320 struct kvm_x86_mce mce;
2323 if (copy_from_user(&mce, argp, sizeof mce))
2325 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
2328 case KVM_GET_VCPU_EVENTS: {
2329 struct kvm_vcpu_events events;
2331 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
2334 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
2339 case KVM_SET_VCPU_EVENTS: {
2340 struct kvm_vcpu_events events;
2343 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
2346 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
2349 case KVM_GET_DEBUGREGS: {
2350 struct kvm_debugregs dbgregs;
2352 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
2355 if (copy_to_user(argp, &dbgregs,
2356 sizeof(struct kvm_debugregs)))
2361 case KVM_SET_DEBUGREGS: {
2362 struct kvm_debugregs dbgregs;
2365 if (copy_from_user(&dbgregs, argp,
2366 sizeof(struct kvm_debugregs)))
2369 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
2380 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
2384 if (addr > (unsigned int)(-3 * PAGE_SIZE))
2386 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
2390 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
2393 kvm->arch.ept_identity_map_addr = ident_addr;
2397 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
2398 u32 kvm_nr_mmu_pages)
2400 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
2403 mutex_lock(&kvm->slots_lock);
2404 spin_lock(&kvm->mmu_lock);
2406 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
2407 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
2409 spin_unlock(&kvm->mmu_lock);
2410 mutex_unlock(&kvm->slots_lock);
2414 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
2416 return kvm->arch.n_alloc_mmu_pages;
2419 gfn_t unalias_gfn_instantiation(struct kvm *kvm, gfn_t gfn)
2422 struct kvm_mem_alias *alias;
2423 struct kvm_mem_aliases *aliases;
2425 aliases = rcu_dereference(kvm->arch.aliases);
2427 for (i = 0; i < aliases->naliases; ++i) {
2428 alias = &aliases->aliases[i];
2429 if (alias->flags & KVM_ALIAS_INVALID)
2431 if (gfn >= alias->base_gfn
2432 && gfn < alias->base_gfn + alias->npages)
2433 return alias->target_gfn + gfn - alias->base_gfn;
2438 gfn_t unalias_gfn(struct kvm *kvm, gfn_t gfn)
2441 struct kvm_mem_alias *alias;
2442 struct kvm_mem_aliases *aliases;
2444 aliases = rcu_dereference(kvm->arch.aliases);
2446 for (i = 0; i < aliases->naliases; ++i) {
2447 alias = &aliases->aliases[i];
2448 if (gfn >= alias->base_gfn
2449 && gfn < alias->base_gfn + alias->npages)
2450 return alias->target_gfn + gfn - alias->base_gfn;
2456 * Set a new alias region. Aliases map a portion of physical memory into
2457 * another portion. This is useful for memory windows, for example the PC
2460 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
2461 struct kvm_memory_alias *alias)
2464 struct kvm_mem_alias *p;
2465 struct kvm_mem_aliases *aliases, *old_aliases;
2468 /* General sanity checks */
2469 if (alias->memory_size & (PAGE_SIZE - 1))
2471 if (alias->guest_phys_addr & (PAGE_SIZE - 1))
2473 if (alias->slot >= KVM_ALIAS_SLOTS)
2475 if (alias->guest_phys_addr + alias->memory_size
2476 < alias->guest_phys_addr)
2478 if (alias->target_phys_addr + alias->memory_size
2479 < alias->target_phys_addr)
2483 aliases = kzalloc(sizeof(struct kvm_mem_aliases), GFP_KERNEL);
2487 mutex_lock(&kvm->slots_lock);
2489 /* invalidate any gfn reference in case of deletion/shrinking */
2490 memcpy(aliases, kvm->arch.aliases, sizeof(struct kvm_mem_aliases));
2491 aliases->aliases[alias->slot].flags |= KVM_ALIAS_INVALID;
2492 old_aliases = kvm->arch.aliases;
2493 rcu_assign_pointer(kvm->arch.aliases, aliases);
2494 synchronize_srcu_expedited(&kvm->srcu);
2495 kvm_mmu_zap_all(kvm);
2499 aliases = kzalloc(sizeof(struct kvm_mem_aliases), GFP_KERNEL);
2503 memcpy(aliases, kvm->arch.aliases, sizeof(struct kvm_mem_aliases));
2505 p = &aliases->aliases[alias->slot];
2506 p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
2507 p->npages = alias->memory_size >> PAGE_SHIFT;
2508 p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
2509 p->flags &= ~(KVM_ALIAS_INVALID);
2511 for (n = KVM_ALIAS_SLOTS; n > 0; --n)
2512 if (aliases->aliases[n - 1].npages)
2514 aliases->naliases = n;
2516 old_aliases = kvm->arch.aliases;
2517 rcu_assign_pointer(kvm->arch.aliases, aliases);
2518 synchronize_srcu_expedited(&kvm->srcu);
2523 mutex_unlock(&kvm->slots_lock);
2528 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2533 switch (chip->chip_id) {
2534 case KVM_IRQCHIP_PIC_MASTER:
2535 memcpy(&chip->chip.pic,
2536 &pic_irqchip(kvm)->pics[0],
2537 sizeof(struct kvm_pic_state));
2539 case KVM_IRQCHIP_PIC_SLAVE:
2540 memcpy(&chip->chip.pic,
2541 &pic_irqchip(kvm)->pics[1],
2542 sizeof(struct kvm_pic_state));
2544 case KVM_IRQCHIP_IOAPIC:
2545 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
2554 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2559 switch (chip->chip_id) {
2560 case KVM_IRQCHIP_PIC_MASTER:
2561 raw_spin_lock(&pic_irqchip(kvm)->lock);
2562 memcpy(&pic_irqchip(kvm)->pics[0],
2564 sizeof(struct kvm_pic_state));
2565 raw_spin_unlock(&pic_irqchip(kvm)->lock);
2567 case KVM_IRQCHIP_PIC_SLAVE:
2568 raw_spin_lock(&pic_irqchip(kvm)->lock);
2569 memcpy(&pic_irqchip(kvm)->pics[1],
2571 sizeof(struct kvm_pic_state));
2572 raw_spin_unlock(&pic_irqchip(kvm)->lock);
2574 case KVM_IRQCHIP_IOAPIC:
2575 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
2581 kvm_pic_update_irq(pic_irqchip(kvm));
2585 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2589 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2590 memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
2591 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2595 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2599 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2600 memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
2601 kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
2602 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2606 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2610 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2611 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
2612 sizeof(ps->channels));
2613 ps->flags = kvm->arch.vpit->pit_state.flags;
2614 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2618 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2620 int r = 0, start = 0;
2621 u32 prev_legacy, cur_legacy;
2622 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2623 prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
2624 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
2625 if (!prev_legacy && cur_legacy)
2627 memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
2628 sizeof(kvm->arch.vpit->pit_state.channels));
2629 kvm->arch.vpit->pit_state.flags = ps->flags;
2630 kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
2631 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2635 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
2636 struct kvm_reinject_control *control)
2638 if (!kvm->arch.vpit)
2640 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2641 kvm->arch.vpit->pit_state.pit_timer.reinject = control->pit_reinject;
2642 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2647 * Get (and clear) the dirty memory log for a memory slot.
2649 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
2650 struct kvm_dirty_log *log)
2653 struct kvm_memory_slot *memslot;
2655 unsigned long is_dirty = 0;
2656 unsigned long *dirty_bitmap = NULL;
2658 mutex_lock(&kvm->slots_lock);
2661 if (log->slot >= KVM_MEMORY_SLOTS)
2664 memslot = &kvm->memslots->memslots[log->slot];
2666 if (!memslot->dirty_bitmap)
2669 n = kvm_dirty_bitmap_bytes(memslot);
2672 dirty_bitmap = vmalloc(n);
2675 memset(dirty_bitmap, 0, n);
2677 for (i = 0; !is_dirty && i < n/sizeof(long); i++)
2678 is_dirty = memslot->dirty_bitmap[i];
2680 /* If nothing is dirty, don't bother messing with page tables. */
2682 struct kvm_memslots *slots, *old_slots;
2684 spin_lock(&kvm->mmu_lock);
2685 kvm_mmu_slot_remove_write_access(kvm, log->slot);
2686 spin_unlock(&kvm->mmu_lock);
2688 slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
2692 memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
2693 slots->memslots[log->slot].dirty_bitmap = dirty_bitmap;
2695 old_slots = kvm->memslots;
2696 rcu_assign_pointer(kvm->memslots, slots);
2697 synchronize_srcu_expedited(&kvm->srcu);
2698 dirty_bitmap = old_slots->memslots[log->slot].dirty_bitmap;
2703 if (copy_to_user(log->dirty_bitmap, dirty_bitmap, n))
2706 vfree(dirty_bitmap);
2708 mutex_unlock(&kvm->slots_lock);
2712 long kvm_arch_vm_ioctl(struct file *filp,
2713 unsigned int ioctl, unsigned long arg)
2715 struct kvm *kvm = filp->private_data;
2716 void __user *argp = (void __user *)arg;
2719 * This union makes it completely explicit to gcc-3.x
2720 * that these two variables' stack usage should be
2721 * combined, not added together.
2724 struct kvm_pit_state ps;
2725 struct kvm_pit_state2 ps2;
2726 struct kvm_memory_alias alias;
2727 struct kvm_pit_config pit_config;
2731 case KVM_SET_TSS_ADDR:
2732 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
2736 case KVM_SET_IDENTITY_MAP_ADDR: {
2740 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
2742 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
2747 case KVM_SET_MEMORY_REGION: {
2748 struct kvm_memory_region kvm_mem;
2749 struct kvm_userspace_memory_region kvm_userspace_mem;
2752 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
2754 kvm_userspace_mem.slot = kvm_mem.slot;
2755 kvm_userspace_mem.flags = kvm_mem.flags;
2756 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
2757 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
2758 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
2763 case KVM_SET_NR_MMU_PAGES:
2764 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
2768 case KVM_GET_NR_MMU_PAGES:
2769 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
2771 case KVM_SET_MEMORY_ALIAS:
2773 if (copy_from_user(&u.alias, argp, sizeof(struct kvm_memory_alias)))
2775 r = kvm_vm_ioctl_set_memory_alias(kvm, &u.alias);
2779 case KVM_CREATE_IRQCHIP: {
2780 struct kvm_pic *vpic;
2782 mutex_lock(&kvm->lock);
2785 goto create_irqchip_unlock;
2787 vpic = kvm_create_pic(kvm);
2789 r = kvm_ioapic_init(kvm);
2791 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
2794 goto create_irqchip_unlock;
2797 goto create_irqchip_unlock;
2799 kvm->arch.vpic = vpic;
2801 r = kvm_setup_default_irq_routing(kvm);
2803 mutex_lock(&kvm->irq_lock);
2804 kvm_ioapic_destroy(kvm);
2805 kvm_destroy_pic(kvm);
2806 mutex_unlock(&kvm->irq_lock);
2808 create_irqchip_unlock:
2809 mutex_unlock(&kvm->lock);
2812 case KVM_CREATE_PIT:
2813 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
2815 case KVM_CREATE_PIT2:
2817 if (copy_from_user(&u.pit_config, argp,
2818 sizeof(struct kvm_pit_config)))
2821 mutex_lock(&kvm->slots_lock);
2824 goto create_pit_unlock;
2826 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
2830 mutex_unlock(&kvm->slots_lock);
2832 case KVM_IRQ_LINE_STATUS:
2833 case KVM_IRQ_LINE: {
2834 struct kvm_irq_level irq_event;
2837 if (copy_from_user(&irq_event, argp, sizeof irq_event))
2839 if (irqchip_in_kernel(kvm)) {
2841 status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
2842 irq_event.irq, irq_event.level);
2843 if (ioctl == KVM_IRQ_LINE_STATUS) {
2844 irq_event.status = status;
2845 if (copy_to_user(argp, &irq_event,
2853 case KVM_GET_IRQCHIP: {
2854 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
2855 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
2861 if (copy_from_user(chip, argp, sizeof *chip))
2862 goto get_irqchip_out;
2864 if (!irqchip_in_kernel(kvm))
2865 goto get_irqchip_out;
2866 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
2868 goto get_irqchip_out;
2870 if (copy_to_user(argp, chip, sizeof *chip))
2871 goto get_irqchip_out;
2879 case KVM_SET_IRQCHIP: {
2880 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
2881 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
2887 if (copy_from_user(chip, argp, sizeof *chip))
2888 goto set_irqchip_out;
2890 if (!irqchip_in_kernel(kvm))
2891 goto set_irqchip_out;
2892 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
2894 goto set_irqchip_out;
2904 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
2907 if (!kvm->arch.vpit)
2909 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
2913 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
2920 if (copy_from_user(&u.ps, argp, sizeof u.ps))
2923 if (!kvm->arch.vpit)
2925 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
2931 case KVM_GET_PIT2: {
2933 if (!kvm->arch.vpit)
2935 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
2939 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
2944 case KVM_SET_PIT2: {
2946 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
2949 if (!kvm->arch.vpit)
2951 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
2957 case KVM_REINJECT_CONTROL: {
2958 struct kvm_reinject_control control;
2960 if (copy_from_user(&control, argp, sizeof(control)))
2962 r = kvm_vm_ioctl_reinject(kvm, &control);
2968 case KVM_XEN_HVM_CONFIG: {
2970 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
2971 sizeof(struct kvm_xen_hvm_config)))
2974 if (kvm->arch.xen_hvm_config.flags)
2979 case KVM_SET_CLOCK: {
2980 struct timespec now;
2981 struct kvm_clock_data user_ns;
2986 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
2995 now_ns = timespec_to_ns(&now);
2996 delta = user_ns.clock - now_ns;
2997 kvm->arch.kvmclock_offset = delta;
3000 case KVM_GET_CLOCK: {
3001 struct timespec now;
3002 struct kvm_clock_data user_ns;
3006 now_ns = timespec_to_ns(&now);
3007 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
3011 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
3024 static void kvm_init_msr_list(void)
3029 /* skip the first msrs in the list. KVM-specific */
3030 for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
3031 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
3034 msrs_to_save[j] = msrs_to_save[i];
3037 num_msrs_to_save = j;
3040 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
3043 if (vcpu->arch.apic &&
3044 !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, len, v))
3047 return kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, len, v);
3050 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
3052 if (vcpu->arch.apic &&
3053 !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, len, v))
3056 return kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, len, v);
3059 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva, u32 *error)
3061 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3062 return vcpu->arch.mmu.gva_to_gpa(vcpu, gva, access, error);
3065 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva, u32 *error)
3067 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3068 access |= PFERR_FETCH_MASK;
3069 return vcpu->arch.mmu.gva_to_gpa(vcpu, gva, access, error);
3072 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva, u32 *error)
3074 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3075 access |= PFERR_WRITE_MASK;
3076 return vcpu->arch.mmu.gva_to_gpa(vcpu, gva, access, error);
3079 /* uses this to access any guest's mapped memory without checking CPL */
3080 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva, u32 *error)
3082 return vcpu->arch.mmu.gva_to_gpa(vcpu, gva, 0, error);
3085 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
3086 struct kvm_vcpu *vcpu, u32 access,
3090 int r = X86EMUL_CONTINUE;
3093 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr, access, error);
3094 unsigned offset = addr & (PAGE_SIZE-1);
3095 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
3098 if (gpa == UNMAPPED_GVA) {
3099 r = X86EMUL_PROPAGATE_FAULT;
3102 ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
3104 r = X86EMUL_UNHANDLEABLE;
3116 /* used for instruction fetching */
3117 static int kvm_fetch_guest_virt(gva_t addr, void *val, unsigned int bytes,
3118 struct kvm_vcpu *vcpu, u32 *error)
3120 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3121 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
3122 access | PFERR_FETCH_MASK, error);
3125 static int kvm_read_guest_virt(gva_t addr, void *val, unsigned int bytes,
3126 struct kvm_vcpu *vcpu, u32 *error)
3128 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3129 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
3133 static int kvm_read_guest_virt_system(gva_t addr, void *val, unsigned int bytes,
3134 struct kvm_vcpu *vcpu, u32 *error)
3136 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, error);
3139 static int kvm_write_guest_virt(gva_t addr, void *val, unsigned int bytes,
3140 struct kvm_vcpu *vcpu, u32 *error)
3143 int r = X86EMUL_CONTINUE;
3146 gpa_t gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, error);
3147 unsigned offset = addr & (PAGE_SIZE-1);
3148 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
3151 if (gpa == UNMAPPED_GVA) {
3152 r = X86EMUL_PROPAGATE_FAULT;
3155 ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
3157 r = X86EMUL_UNHANDLEABLE;
3170 static int emulator_read_emulated(unsigned long addr,
3173 struct kvm_vcpu *vcpu)
3178 if (vcpu->mmio_read_completed) {
3179 memcpy(val, vcpu->mmio_data, bytes);
3180 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
3181 vcpu->mmio_phys_addr, *(u64 *)val);
3182 vcpu->mmio_read_completed = 0;
3183 return X86EMUL_CONTINUE;
3186 gpa = kvm_mmu_gva_to_gpa_read(vcpu, addr, &error_code);
3188 if (gpa == UNMAPPED_GVA) {
3189 kvm_inject_page_fault(vcpu, addr, error_code);
3190 return X86EMUL_PROPAGATE_FAULT;
3193 /* For APIC access vmexit */
3194 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3197 if (kvm_read_guest_virt(addr, val, bytes, vcpu, NULL)
3198 == X86EMUL_CONTINUE)
3199 return X86EMUL_CONTINUE;
3203 * Is this MMIO handled locally?
3205 if (!vcpu_mmio_read(vcpu, gpa, bytes, val)) {
3206 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes, gpa, *(u64 *)val);
3207 return X86EMUL_CONTINUE;
3210 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
3212 vcpu->mmio_needed = 1;
3213 vcpu->mmio_phys_addr = gpa;
3214 vcpu->mmio_size = bytes;
3215 vcpu->mmio_is_write = 0;
3217 return X86EMUL_UNHANDLEABLE;
3220 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
3221 const void *val, int bytes)
3225 ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
3228 kvm_mmu_pte_write(vcpu, gpa, val, bytes, 1);
3232 static int emulator_write_emulated_onepage(unsigned long addr,
3235 struct kvm_vcpu *vcpu)
3240 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, &error_code);
3242 if (gpa == UNMAPPED_GVA) {
3243 kvm_inject_page_fault(vcpu, addr, error_code);
3244 return X86EMUL_PROPAGATE_FAULT;
3247 /* For APIC access vmexit */
3248 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3251 if (emulator_write_phys(vcpu, gpa, val, bytes))
3252 return X86EMUL_CONTINUE;
3255 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
3257 * Is this MMIO handled locally?
3259 if (!vcpu_mmio_write(vcpu, gpa, bytes, val))
3260 return X86EMUL_CONTINUE;
3262 vcpu->mmio_needed = 1;
3263 vcpu->mmio_phys_addr = gpa;
3264 vcpu->mmio_size = bytes;
3265 vcpu->mmio_is_write = 1;
3266 memcpy(vcpu->mmio_data, val, bytes);
3268 return X86EMUL_CONTINUE;
3271 int emulator_write_emulated(unsigned long addr,
3274 struct kvm_vcpu *vcpu)
3276 /* Crossing a page boundary? */
3277 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
3280 now = -addr & ~PAGE_MASK;
3281 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
3282 if (rc != X86EMUL_CONTINUE)
3288 return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
3290 EXPORT_SYMBOL_GPL(emulator_write_emulated);
3292 static int emulator_cmpxchg_emulated(unsigned long addr,
3296 struct kvm_vcpu *vcpu)
3298 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
3299 #ifndef CONFIG_X86_64
3300 /* guests cmpxchg8b have to be emulated atomically */
3307 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
3309 if (gpa == UNMAPPED_GVA ||
3310 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3313 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
3318 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
3320 kaddr = kmap_atomic(page, KM_USER0);
3321 set_64bit((u64 *)(kaddr + offset_in_page(gpa)), val);
3322 kunmap_atomic(kaddr, KM_USER0);
3323 kvm_release_page_dirty(page);
3328 return emulator_write_emulated(addr, new, bytes, vcpu);
3331 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
3333 return kvm_x86_ops->get_segment_base(vcpu, seg);
3336 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
3338 kvm_mmu_invlpg(vcpu, address);
3339 return X86EMUL_CONTINUE;
3342 int emulate_clts(struct kvm_vcpu *vcpu)
3344 kvm_x86_ops->set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
3345 kvm_x86_ops->fpu_activate(vcpu);
3346 return X86EMUL_CONTINUE;
3349 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
3351 return kvm_x86_ops->get_dr(ctxt->vcpu, dr, dest);
3354 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
3356 unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
3358 return kvm_x86_ops->set_dr(ctxt->vcpu, dr, value & mask);
3361 void kvm_report_emulation_failure(struct kvm_vcpu *vcpu, const char *context)
3364 unsigned long rip = kvm_rip_read(vcpu);
3365 unsigned long rip_linear;
3367 if (!printk_ratelimit())
3370 rip_linear = rip + get_segment_base(vcpu, VCPU_SREG_CS);
3372 kvm_read_guest_virt(rip_linear, (void *)opcodes, 4, vcpu, NULL);
3374 printk(KERN_ERR "emulation failed (%s) rip %lx %02x %02x %02x %02x\n",
3375 context, rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
3377 EXPORT_SYMBOL_GPL(kvm_report_emulation_failure);
3379 static struct x86_emulate_ops emulate_ops = {
3380 .read_std = kvm_read_guest_virt_system,
3381 .fetch = kvm_fetch_guest_virt,
3382 .read_emulated = emulator_read_emulated,
3383 .write_emulated = emulator_write_emulated,
3384 .cmpxchg_emulated = emulator_cmpxchg_emulated,
3387 static void cache_all_regs(struct kvm_vcpu *vcpu)
3389 kvm_register_read(vcpu, VCPU_REGS_RAX);
3390 kvm_register_read(vcpu, VCPU_REGS_RSP);
3391 kvm_register_read(vcpu, VCPU_REGS_RIP);
3392 vcpu->arch.regs_dirty = ~0;
3395 int emulate_instruction(struct kvm_vcpu *vcpu,
3401 struct decode_cache *c;
3402 struct kvm_run *run = vcpu->run;
3404 kvm_clear_exception_queue(vcpu);
3405 vcpu->arch.mmio_fault_cr2 = cr2;
3407 * TODO: fix emulate.c to use guest_read/write_register
3408 * instead of direct ->regs accesses, can save hundred cycles
3409 * on Intel for instructions that don't read/change RSP, for
3412 cache_all_regs(vcpu);
3414 vcpu->mmio_is_write = 0;
3415 vcpu->arch.pio.string = 0;
3417 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
3419 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
3421 vcpu->arch.emulate_ctxt.vcpu = vcpu;
3422 vcpu->arch.emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
3423 vcpu->arch.emulate_ctxt.mode =
3424 (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
3425 (vcpu->arch.emulate_ctxt.eflags & X86_EFLAGS_VM)
3426 ? X86EMUL_MODE_VM86 : cs_l
3427 ? X86EMUL_MODE_PROT64 : cs_db
3428 ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
3430 r = x86_decode_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
3432 /* Only allow emulation of specific instructions on #UD
3433 * (namely VMMCALL, sysenter, sysexit, syscall)*/
3434 c = &vcpu->arch.emulate_ctxt.decode;
3435 if (emulation_type & EMULTYPE_TRAP_UD) {
3437 return EMULATE_FAIL;
3439 case 0x01: /* VMMCALL */
3440 if (c->modrm_mod != 3 || c->modrm_rm != 1)
3441 return EMULATE_FAIL;
3443 case 0x34: /* sysenter */
3444 case 0x35: /* sysexit */
3445 if (c->modrm_mod != 0 || c->modrm_rm != 0)
3446 return EMULATE_FAIL;
3448 case 0x05: /* syscall */
3449 if (c->modrm_mod != 0 || c->modrm_rm != 0)
3450 return EMULATE_FAIL;
3453 return EMULATE_FAIL;
3456 if (!(c->modrm_reg == 0 || c->modrm_reg == 3))
3457 return EMULATE_FAIL;
3460 ++vcpu->stat.insn_emulation;
3462 ++vcpu->stat.insn_emulation_fail;
3463 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
3464 return EMULATE_DONE;
3465 return EMULATE_FAIL;
3469 if (emulation_type & EMULTYPE_SKIP) {
3470 kvm_rip_write(vcpu, vcpu->arch.emulate_ctxt.decode.eip);
3471 return EMULATE_DONE;
3474 r = x86_emulate_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
3475 shadow_mask = vcpu->arch.emulate_ctxt.interruptibility;
3478 kvm_x86_ops->set_interrupt_shadow(vcpu, shadow_mask);
3480 if (vcpu->arch.pio.string)
3481 return EMULATE_DO_MMIO;
3483 if (r || vcpu->mmio_is_write) {
3484 run->exit_reason = KVM_EXIT_MMIO;
3485 run->mmio.phys_addr = vcpu->mmio_phys_addr;
3486 memcpy(run->mmio.data, vcpu->mmio_data, 8);
3487 run->mmio.len = vcpu->mmio_size;
3488 run->mmio.is_write = vcpu->mmio_is_write;
3492 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
3493 return EMULATE_DONE;
3494 if (!vcpu->mmio_needed) {
3495 kvm_report_emulation_failure(vcpu, "mmio");
3496 return EMULATE_FAIL;
3498 return EMULATE_DO_MMIO;
3501 kvm_x86_ops->set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
3503 if (vcpu->mmio_is_write) {
3504 vcpu->mmio_needed = 0;
3505 return EMULATE_DO_MMIO;
3508 return EMULATE_DONE;
3510 EXPORT_SYMBOL_GPL(emulate_instruction);
3512 static int pio_copy_data(struct kvm_vcpu *vcpu)
3514 void *p = vcpu->arch.pio_data;
3515 gva_t q = vcpu->arch.pio.guest_gva;
3520 bytes = vcpu->arch.pio.size * vcpu->arch.pio.cur_count;
3521 if (vcpu->arch.pio.in)
3522 ret = kvm_write_guest_virt(q, p, bytes, vcpu, &error_code);
3524 ret = kvm_read_guest_virt(q, p, bytes, vcpu, &error_code);
3526 if (ret == X86EMUL_PROPAGATE_FAULT)
3527 kvm_inject_page_fault(vcpu, q, error_code);
3532 int complete_pio(struct kvm_vcpu *vcpu)
3534 struct kvm_pio_request *io = &vcpu->arch.pio;
3541 val = kvm_register_read(vcpu, VCPU_REGS_RAX);
3542 memcpy(&val, vcpu->arch.pio_data, io->size);
3543 kvm_register_write(vcpu, VCPU_REGS_RAX, val);
3547 r = pio_copy_data(vcpu);
3554 delta *= io->cur_count;
3556 * The size of the register should really depend on
3557 * current address size.
3559 val = kvm_register_read(vcpu, VCPU_REGS_RCX);
3561 kvm_register_write(vcpu, VCPU_REGS_RCX, val);
3567 val = kvm_register_read(vcpu, VCPU_REGS_RDI);
3569 kvm_register_write(vcpu, VCPU_REGS_RDI, val);
3571 val = kvm_register_read(vcpu, VCPU_REGS_RSI);
3573 kvm_register_write(vcpu, VCPU_REGS_RSI, val);
3577 io->count -= io->cur_count;
3583 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
3585 /* TODO: String I/O for in kernel device */
3588 if (vcpu->arch.pio.in)
3589 r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
3590 vcpu->arch.pio.size, pd);
3592 r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
3593 vcpu->arch.pio.port, vcpu->arch.pio.size,
3598 static int pio_string_write(struct kvm_vcpu *vcpu)
3600 struct kvm_pio_request *io = &vcpu->arch.pio;
3601 void *pd = vcpu->arch.pio_data;
3604 for (i = 0; i < io->cur_count; i++) {
3605 if (kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
3606 io->port, io->size, pd)) {
3615 int kvm_emulate_pio(struct kvm_vcpu *vcpu, int in, int size, unsigned port)
3619 trace_kvm_pio(!in, port, size, 1);
3621 vcpu->run->exit_reason = KVM_EXIT_IO;
3622 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
3623 vcpu->run->io.size = vcpu->arch.pio.size = size;
3624 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
3625 vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = 1;
3626 vcpu->run->io.port = vcpu->arch.pio.port = port;
3627 vcpu->arch.pio.in = in;
3628 vcpu->arch.pio.string = 0;
3629 vcpu->arch.pio.down = 0;
3630 vcpu->arch.pio.rep = 0;
3632 if (!vcpu->arch.pio.in) {
3633 val = kvm_register_read(vcpu, VCPU_REGS_RAX);
3634 memcpy(vcpu->arch.pio_data, &val, 4);
3637 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
3643 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
3645 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, int in,
3646 int size, unsigned long count, int down,
3647 gva_t address, int rep, unsigned port)
3649 unsigned now, in_page;
3652 trace_kvm_pio(!in, port, size, count);
3654 vcpu->run->exit_reason = KVM_EXIT_IO;
3655 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
3656 vcpu->run->io.size = vcpu->arch.pio.size = size;
3657 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
3658 vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = count;
3659 vcpu->run->io.port = vcpu->arch.pio.port = port;
3660 vcpu->arch.pio.in = in;
3661 vcpu->arch.pio.string = 1;
3662 vcpu->arch.pio.down = down;
3663 vcpu->arch.pio.rep = rep;
3666 kvm_x86_ops->skip_emulated_instruction(vcpu);
3671 in_page = PAGE_SIZE - offset_in_page(address);
3673 in_page = offset_in_page(address) + size;
3674 now = min(count, (unsigned long)in_page / size);
3679 * String I/O in reverse. Yuck. Kill the guest, fix later.
3681 pr_unimpl(vcpu, "guest string pio down\n");
3682 kvm_inject_gp(vcpu, 0);
3685 vcpu->run->io.count = now;
3686 vcpu->arch.pio.cur_count = now;
3688 if (vcpu->arch.pio.cur_count == vcpu->arch.pio.count)
3689 kvm_x86_ops->skip_emulated_instruction(vcpu);
3691 vcpu->arch.pio.guest_gva = address;
3693 if (!vcpu->arch.pio.in) {
3694 /* string PIO write */
3695 ret = pio_copy_data(vcpu);
3696 if (ret == X86EMUL_PROPAGATE_FAULT)
3698 if (ret == 0 && !pio_string_write(vcpu)) {
3700 if (vcpu->arch.pio.count == 0)
3704 /* no string PIO read support yet */
3708 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
3710 static void bounce_off(void *info)
3715 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
3718 struct cpufreq_freqs *freq = data;
3720 struct kvm_vcpu *vcpu;
3721 int i, send_ipi = 0;
3723 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
3725 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
3727 per_cpu(cpu_tsc_khz, freq->cpu) = freq->new;
3729 spin_lock(&kvm_lock);
3730 list_for_each_entry(kvm, &vm_list, vm_list) {
3731 kvm_for_each_vcpu(i, vcpu, kvm) {
3732 if (vcpu->cpu != freq->cpu)
3734 if (!kvm_request_guest_time_update(vcpu))
3736 if (vcpu->cpu != smp_processor_id())
3740 spin_unlock(&kvm_lock);
3742 if (freq->old < freq->new && send_ipi) {
3744 * We upscale the frequency. Must make the guest
3745 * doesn't see old kvmclock values while running with
3746 * the new frequency, otherwise we risk the guest sees
3747 * time go backwards.
3749 * In case we update the frequency for another cpu
3750 * (which might be in guest context) send an interrupt
3751 * to kick the cpu out of guest context. Next time
3752 * guest context is entered kvmclock will be updated,
3753 * so the guest will not see stale values.
3755 smp_call_function_single(freq->cpu, bounce_off, NULL, 1);
3760 static struct notifier_block kvmclock_cpufreq_notifier_block = {
3761 .notifier_call = kvmclock_cpufreq_notifier
3764 static void kvm_timer_init(void)
3768 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
3769 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
3770 CPUFREQ_TRANSITION_NOTIFIER);
3771 for_each_online_cpu(cpu) {
3772 unsigned long khz = cpufreq_get(cpu);
3775 per_cpu(cpu_tsc_khz, cpu) = khz;
3778 for_each_possible_cpu(cpu)
3779 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
3783 int kvm_arch_init(void *opaque)
3786 struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
3789 printk(KERN_ERR "kvm: already loaded the other module\n");
3794 if (!ops->cpu_has_kvm_support()) {
3795 printk(KERN_ERR "kvm: no hardware support\n");
3799 if (ops->disabled_by_bios()) {
3800 printk(KERN_ERR "kvm: disabled by bios\n");
3805 r = kvm_mmu_module_init();
3809 kvm_init_msr_list();
3812 kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
3813 kvm_mmu_set_base_ptes(PT_PRESENT_MASK);
3814 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
3815 PT_DIRTY_MASK, PT64_NX_MASK, 0);
3825 void kvm_arch_exit(void)
3827 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
3828 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
3829 CPUFREQ_TRANSITION_NOTIFIER);
3831 kvm_mmu_module_exit();
3834 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
3836 ++vcpu->stat.halt_exits;
3837 if (irqchip_in_kernel(vcpu->kvm)) {
3838 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
3841 vcpu->run->exit_reason = KVM_EXIT_HLT;
3845 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
3847 static inline gpa_t hc_gpa(struct kvm_vcpu *vcpu, unsigned long a0,
3850 if (is_long_mode(vcpu))
3853 return a0 | ((gpa_t)a1 << 32);
3856 int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
3858 u64 param, ingpa, outgpa, ret;
3859 uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
3860 bool fast, longmode;
3864 * hypercall generates UD from non zero cpl and real mode
3867 if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
3868 kvm_queue_exception(vcpu, UD_VECTOR);
3872 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
3873 longmode = is_long_mode(vcpu) && cs_l == 1;
3876 param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
3877 (kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
3878 ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
3879 (kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
3880 outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
3881 (kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
3883 #ifdef CONFIG_X86_64
3885 param = kvm_register_read(vcpu, VCPU_REGS_RCX);
3886 ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
3887 outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
3891 code = param & 0xffff;
3892 fast = (param >> 16) & 0x1;
3893 rep_cnt = (param >> 32) & 0xfff;
3894 rep_idx = (param >> 48) & 0xfff;
3896 trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
3899 case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
3900 kvm_vcpu_on_spin(vcpu);
3903 res = HV_STATUS_INVALID_HYPERCALL_CODE;
3907 ret = res | (((u64)rep_done & 0xfff) << 32);
3909 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
3911 kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
3912 kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
3918 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
3920 unsigned long nr, a0, a1, a2, a3, ret;
3923 if (kvm_hv_hypercall_enabled(vcpu->kvm))
3924 return kvm_hv_hypercall(vcpu);
3926 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
3927 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
3928 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
3929 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
3930 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
3932 trace_kvm_hypercall(nr, a0, a1, a2, a3);
3934 if (!is_long_mode(vcpu)) {
3942 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
3948 case KVM_HC_VAPIC_POLL_IRQ:
3952 r = kvm_pv_mmu_op(vcpu, a0, hc_gpa(vcpu, a1, a2), &ret);
3959 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
3960 ++vcpu->stat.hypercalls;
3963 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
3965 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
3967 char instruction[3];
3968 unsigned long rip = kvm_rip_read(vcpu);
3971 * Blow out the MMU to ensure that no other VCPU has an active mapping
3972 * to ensure that the updated hypercall appears atomically across all
3975 kvm_mmu_zap_all(vcpu->kvm);
3977 kvm_x86_ops->patch_hypercall(vcpu, instruction);
3979 return emulator_write_emulated(rip, instruction, 3, vcpu);
3982 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
3984 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
3987 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
3989 struct desc_ptr dt = { limit, base };
3991 kvm_x86_ops->set_gdt(vcpu, &dt);
3994 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
3996 struct desc_ptr dt = { limit, base };
3998 kvm_x86_ops->set_idt(vcpu, &dt);
4001 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
4002 unsigned long *rflags)
4004 kvm_lmsw(vcpu, msw);
4005 *rflags = kvm_get_rflags(vcpu);
4008 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
4010 unsigned long value;
4014 value = kvm_read_cr0(vcpu);
4017 value = vcpu->arch.cr2;
4020 value = vcpu->arch.cr3;
4023 value = kvm_read_cr4(vcpu);
4026 value = kvm_get_cr8(vcpu);
4029 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
4036 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
4037 unsigned long *rflags)
4041 kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4042 *rflags = kvm_get_rflags(vcpu);
4045 vcpu->arch.cr2 = val;
4048 kvm_set_cr3(vcpu, val);
4051 kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4054 kvm_set_cr8(vcpu, val & 0xfUL);
4057 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
4061 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
4063 struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
4064 int j, nent = vcpu->arch.cpuid_nent;
4066 e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
4067 /* when no next entry is found, the current entry[i] is reselected */
4068 for (j = i + 1; ; j = (j + 1) % nent) {
4069 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
4070 if (ej->function == e->function) {
4071 ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
4075 return 0; /* silence gcc, even though control never reaches here */
4078 /* find an entry with matching function, matching index (if needed), and that
4079 * should be read next (if it's stateful) */
4080 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
4081 u32 function, u32 index)
4083 if (e->function != function)
4085 if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
4087 if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
4088 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
4093 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry(struct kvm_vcpu *vcpu,
4094 u32 function, u32 index)
4097 struct kvm_cpuid_entry2 *best = NULL;
4099 for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
4100 struct kvm_cpuid_entry2 *e;
4102 e = &vcpu->arch.cpuid_entries[i];
4103 if (is_matching_cpuid_entry(e, function, index)) {
4104 if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
4105 move_to_next_stateful_cpuid_entry(vcpu, i);
4110 * Both basic or both extended?
4112 if (((e->function ^ function) & 0x80000000) == 0)
4113 if (!best || e->function > best->function)
4118 EXPORT_SYMBOL_GPL(kvm_find_cpuid_entry);
4120 int cpuid_maxphyaddr(struct kvm_vcpu *vcpu)
4122 struct kvm_cpuid_entry2 *best;
4124 best = kvm_find_cpuid_entry(vcpu, 0x80000008, 0);
4126 return best->eax & 0xff;
4130 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
4132 u32 function, index;
4133 struct kvm_cpuid_entry2 *best;
4135 function = kvm_register_read(vcpu, VCPU_REGS_RAX);
4136 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
4137 kvm_register_write(vcpu, VCPU_REGS_RAX, 0);
4138 kvm_register_write(vcpu, VCPU_REGS_RBX, 0);
4139 kvm_register_write(vcpu, VCPU_REGS_RCX, 0);
4140 kvm_register_write(vcpu, VCPU_REGS_RDX, 0);
4141 best = kvm_find_cpuid_entry(vcpu, function, index);
4143 kvm_register_write(vcpu, VCPU_REGS_RAX, best->eax);
4144 kvm_register_write(vcpu, VCPU_REGS_RBX, best->ebx);
4145 kvm_register_write(vcpu, VCPU_REGS_RCX, best->ecx);
4146 kvm_register_write(vcpu, VCPU_REGS_RDX, best->edx);
4148 kvm_x86_ops->skip_emulated_instruction(vcpu);
4149 trace_kvm_cpuid(function,
4150 kvm_register_read(vcpu, VCPU_REGS_RAX),
4151 kvm_register_read(vcpu, VCPU_REGS_RBX),
4152 kvm_register_read(vcpu, VCPU_REGS_RCX),
4153 kvm_register_read(vcpu, VCPU_REGS_RDX));
4155 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
4158 * Check if userspace requested an interrupt window, and that the
4159 * interrupt window is open.
4161 * No need to exit to userspace if we already have an interrupt queued.
4163 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
4165 return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
4166 vcpu->run->request_interrupt_window &&
4167 kvm_arch_interrupt_allowed(vcpu));
4170 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
4172 struct kvm_run *kvm_run = vcpu->run;
4174 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
4175 kvm_run->cr8 = kvm_get_cr8(vcpu);
4176 kvm_run->apic_base = kvm_get_apic_base(vcpu);
4177 if (irqchip_in_kernel(vcpu->kvm))
4178 kvm_run->ready_for_interrupt_injection = 1;
4180 kvm_run->ready_for_interrupt_injection =
4181 kvm_arch_interrupt_allowed(vcpu) &&
4182 !kvm_cpu_has_interrupt(vcpu) &&
4183 !kvm_event_needs_reinjection(vcpu);
4186 static void vapic_enter(struct kvm_vcpu *vcpu)
4188 struct kvm_lapic *apic = vcpu->arch.apic;
4191 if (!apic || !apic->vapic_addr)
4194 page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
4196 vcpu->arch.apic->vapic_page = page;
4199 static void vapic_exit(struct kvm_vcpu *vcpu)
4201 struct kvm_lapic *apic = vcpu->arch.apic;
4204 if (!apic || !apic->vapic_addr)
4207 idx = srcu_read_lock(&vcpu->kvm->srcu);
4208 kvm_release_page_dirty(apic->vapic_page);
4209 mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
4210 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4213 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
4217 if (!kvm_x86_ops->update_cr8_intercept)
4220 if (!vcpu->arch.apic)
4223 if (!vcpu->arch.apic->vapic_addr)
4224 max_irr = kvm_lapic_find_highest_irr(vcpu);
4231 tpr = kvm_lapic_get_cr8(vcpu);
4233 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
4236 static void inject_pending_event(struct kvm_vcpu *vcpu)
4238 /* try to reinject previous events if any */
4239 if (vcpu->arch.exception.pending) {
4240 trace_kvm_inj_exception(vcpu->arch.exception.nr,
4241 vcpu->arch.exception.has_error_code,
4242 vcpu->arch.exception.error_code);
4243 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
4244 vcpu->arch.exception.has_error_code,
4245 vcpu->arch.exception.error_code);
4249 if (vcpu->arch.nmi_injected) {
4250 kvm_x86_ops->set_nmi(vcpu);
4254 if (vcpu->arch.interrupt.pending) {
4255 kvm_x86_ops->set_irq(vcpu);
4259 /* try to inject new event if pending */
4260 if (vcpu->arch.nmi_pending) {
4261 if (kvm_x86_ops->nmi_allowed(vcpu)) {
4262 vcpu->arch.nmi_pending = false;
4263 vcpu->arch.nmi_injected = true;
4264 kvm_x86_ops->set_nmi(vcpu);
4266 } else if (kvm_cpu_has_interrupt(vcpu)) {
4267 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
4268 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
4270 kvm_x86_ops->set_irq(vcpu);
4275 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
4278 bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
4279 vcpu->run->request_interrupt_window;
4282 if (test_and_clear_bit(KVM_REQ_MMU_RELOAD, &vcpu->requests))
4283 kvm_mmu_unload(vcpu);
4285 r = kvm_mmu_reload(vcpu);
4289 if (vcpu->requests) {
4290 if (test_and_clear_bit(KVM_REQ_MIGRATE_TIMER, &vcpu->requests))
4291 __kvm_migrate_timers(vcpu);
4292 if (test_and_clear_bit(KVM_REQ_KVMCLOCK_UPDATE, &vcpu->requests))
4293 kvm_write_guest_time(vcpu);
4294 if (test_and_clear_bit(KVM_REQ_MMU_SYNC, &vcpu->requests))
4295 kvm_mmu_sync_roots(vcpu);
4296 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
4297 kvm_x86_ops->tlb_flush(vcpu);
4298 if (test_and_clear_bit(KVM_REQ_REPORT_TPR_ACCESS,
4300 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
4304 if (test_and_clear_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests)) {
4305 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4309 if (test_and_clear_bit(KVM_REQ_DEACTIVATE_FPU, &vcpu->requests)) {
4310 vcpu->fpu_active = 0;
4311 kvm_x86_ops->fpu_deactivate(vcpu);
4317 kvm_x86_ops->prepare_guest_switch(vcpu);
4318 if (vcpu->fpu_active)
4319 kvm_load_guest_fpu(vcpu);
4321 local_irq_disable();
4323 clear_bit(KVM_REQ_KICK, &vcpu->requests);
4324 smp_mb__after_clear_bit();
4326 if (vcpu->requests || need_resched() || signal_pending(current)) {
4327 set_bit(KVM_REQ_KICK, &vcpu->requests);
4334 inject_pending_event(vcpu);
4336 /* enable NMI/IRQ window open exits if needed */
4337 if (vcpu->arch.nmi_pending)
4338 kvm_x86_ops->enable_nmi_window(vcpu);
4339 else if (kvm_cpu_has_interrupt(vcpu) || req_int_win)
4340 kvm_x86_ops->enable_irq_window(vcpu);
4342 if (kvm_lapic_enabled(vcpu)) {
4343 update_cr8_intercept(vcpu);
4344 kvm_lapic_sync_to_vapic(vcpu);
4347 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
4351 if (unlikely(vcpu->arch.switch_db_regs)) {
4353 set_debugreg(vcpu->arch.eff_db[0], 0);
4354 set_debugreg(vcpu->arch.eff_db[1], 1);
4355 set_debugreg(vcpu->arch.eff_db[2], 2);
4356 set_debugreg(vcpu->arch.eff_db[3], 3);
4359 trace_kvm_entry(vcpu->vcpu_id);
4360 kvm_x86_ops->run(vcpu);
4363 * If the guest has used debug registers, at least dr7
4364 * will be disabled while returning to the host.
4365 * If we don't have active breakpoints in the host, we don't
4366 * care about the messed up debug address registers. But if
4367 * we have some of them active, restore the old state.
4369 if (hw_breakpoint_active())
4370 hw_breakpoint_restore();
4372 set_bit(KVM_REQ_KICK, &vcpu->requests);
4378 * We must have an instruction between local_irq_enable() and
4379 * kvm_guest_exit(), so the timer interrupt isn't delayed by
4380 * the interrupt shadow. The stat.exits increment will do nicely.
4381 * But we need to prevent reordering, hence this barrier():
4389 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
4392 * Profile KVM exit RIPs:
4394 if (unlikely(prof_on == KVM_PROFILING)) {
4395 unsigned long rip = kvm_rip_read(vcpu);
4396 profile_hit(KVM_PROFILING, (void *)rip);
4400 kvm_lapic_sync_from_vapic(vcpu);
4402 r = kvm_x86_ops->handle_exit(vcpu);
4408 static int __vcpu_run(struct kvm_vcpu *vcpu)
4411 struct kvm *kvm = vcpu->kvm;
4413 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
4414 pr_debug("vcpu %d received sipi with vector # %x\n",
4415 vcpu->vcpu_id, vcpu->arch.sipi_vector);
4416 kvm_lapic_reset(vcpu);
4417 r = kvm_arch_vcpu_reset(vcpu);
4420 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
4423 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
4428 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE)
4429 r = vcpu_enter_guest(vcpu);
4431 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
4432 kvm_vcpu_block(vcpu);
4433 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
4434 if (test_and_clear_bit(KVM_REQ_UNHALT, &vcpu->requests))
4436 switch(vcpu->arch.mp_state) {
4437 case KVM_MP_STATE_HALTED:
4438 vcpu->arch.mp_state =
4439 KVM_MP_STATE_RUNNABLE;
4440 case KVM_MP_STATE_RUNNABLE:
4442 case KVM_MP_STATE_SIPI_RECEIVED:
4453 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
4454 if (kvm_cpu_has_pending_timer(vcpu))
4455 kvm_inject_pending_timer_irqs(vcpu);
4457 if (dm_request_for_irq_injection(vcpu)) {
4459 vcpu->run->exit_reason = KVM_EXIT_INTR;
4460 ++vcpu->stat.request_irq_exits;
4462 if (signal_pending(current)) {
4464 vcpu->run->exit_reason = KVM_EXIT_INTR;
4465 ++vcpu->stat.signal_exits;
4467 if (need_resched()) {
4468 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
4470 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
4474 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
4475 post_kvm_run_save(vcpu);
4482 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
4489 if (vcpu->sigset_active)
4490 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
4492 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
4493 kvm_vcpu_block(vcpu);
4494 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
4499 /* re-sync apic's tpr */
4500 if (!irqchip_in_kernel(vcpu->kvm))
4501 kvm_set_cr8(vcpu, kvm_run->cr8);
4503 if (vcpu->arch.pio.cur_count) {
4504 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
4505 r = complete_pio(vcpu);
4506 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
4510 if (vcpu->mmio_needed) {
4511 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
4512 vcpu->mmio_read_completed = 1;
4513 vcpu->mmio_needed = 0;
4515 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
4516 r = emulate_instruction(vcpu, vcpu->arch.mmio_fault_cr2, 0,
4517 EMULTYPE_NO_DECODE);
4518 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
4519 if (r == EMULATE_DO_MMIO) {
4521 * Read-modify-write. Back to userspace.
4527 if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL)
4528 kvm_register_write(vcpu, VCPU_REGS_RAX,
4529 kvm_run->hypercall.ret);
4531 r = __vcpu_run(vcpu);
4534 if (vcpu->sigset_active)
4535 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
4541 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
4545 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
4546 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
4547 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
4548 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
4549 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
4550 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
4551 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
4552 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
4553 #ifdef CONFIG_X86_64
4554 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
4555 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
4556 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
4557 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
4558 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
4559 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
4560 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
4561 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
4564 regs->rip = kvm_rip_read(vcpu);
4565 regs->rflags = kvm_get_rflags(vcpu);
4572 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
4576 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
4577 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
4578 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
4579 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
4580 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
4581 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
4582 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
4583 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
4584 #ifdef CONFIG_X86_64
4585 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
4586 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
4587 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
4588 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
4589 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
4590 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
4591 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
4592 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
4595 kvm_rip_write(vcpu, regs->rip);
4596 kvm_set_rflags(vcpu, regs->rflags);
4598 vcpu->arch.exception.pending = false;
4605 void kvm_get_segment(struct kvm_vcpu *vcpu,
4606 struct kvm_segment *var, int seg)
4608 kvm_x86_ops->get_segment(vcpu, var, seg);
4611 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
4613 struct kvm_segment cs;
4615 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
4619 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
4621 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
4622 struct kvm_sregs *sregs)
4628 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
4629 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
4630 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
4631 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
4632 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
4633 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
4635 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
4636 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
4638 kvm_x86_ops->get_idt(vcpu, &dt);
4639 sregs->idt.limit = dt.size;
4640 sregs->idt.base = dt.address;
4641 kvm_x86_ops->get_gdt(vcpu, &dt);
4642 sregs->gdt.limit = dt.size;
4643 sregs->gdt.base = dt.address;
4645 sregs->cr0 = kvm_read_cr0(vcpu);
4646 sregs->cr2 = vcpu->arch.cr2;
4647 sregs->cr3 = vcpu->arch.cr3;
4648 sregs->cr4 = kvm_read_cr4(vcpu);
4649 sregs->cr8 = kvm_get_cr8(vcpu);
4650 sregs->efer = vcpu->arch.efer;
4651 sregs->apic_base = kvm_get_apic_base(vcpu);
4653 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
4655 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
4656 set_bit(vcpu->arch.interrupt.nr,
4657 (unsigned long *)sregs->interrupt_bitmap);
4664 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
4665 struct kvm_mp_state *mp_state)
4668 mp_state->mp_state = vcpu->arch.mp_state;
4673 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
4674 struct kvm_mp_state *mp_state)
4677 vcpu->arch.mp_state = mp_state->mp_state;
4682 static void kvm_set_segment(struct kvm_vcpu *vcpu,
4683 struct kvm_segment *var, int seg)
4685 kvm_x86_ops->set_segment(vcpu, var, seg);
4688 static void seg_desct_to_kvm_desct(struct desc_struct *seg_desc, u16 selector,
4689 struct kvm_segment *kvm_desct)
4691 kvm_desct->base = get_desc_base(seg_desc);
4692 kvm_desct->limit = get_desc_limit(seg_desc);
4694 kvm_desct->limit <<= 12;
4695 kvm_desct->limit |= 0xfff;
4697 kvm_desct->selector = selector;
4698 kvm_desct->type = seg_desc->type;
4699 kvm_desct->present = seg_desc->p;
4700 kvm_desct->dpl = seg_desc->dpl;
4701 kvm_desct->db = seg_desc->d;
4702 kvm_desct->s = seg_desc->s;
4703 kvm_desct->l = seg_desc->l;
4704 kvm_desct->g = seg_desc->g;
4705 kvm_desct->avl = seg_desc->avl;
4707 kvm_desct->unusable = 1;
4709 kvm_desct->unusable = 0;
4710 kvm_desct->padding = 0;
4713 static void get_segment_descriptor_dtable(struct kvm_vcpu *vcpu,
4715 struct desc_ptr *dtable)
4717 if (selector & 1 << 2) {
4718 struct kvm_segment kvm_seg;
4720 kvm_get_segment(vcpu, &kvm_seg, VCPU_SREG_LDTR);
4722 if (kvm_seg.unusable)
4725 dtable->size = kvm_seg.limit;
4726 dtable->address = kvm_seg.base;
4729 kvm_x86_ops->get_gdt(vcpu, dtable);
4732 /* allowed just for 8 bytes segments */
4733 static int load_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
4734 struct desc_struct *seg_desc)
4736 struct desc_ptr dtable;
4737 u16 index = selector >> 3;
4742 get_segment_descriptor_dtable(vcpu, selector, &dtable);
4744 if (dtable.size < index * 8 + 7) {
4745 kvm_queue_exception_e(vcpu, GP_VECTOR, selector & 0xfffc);
4746 return X86EMUL_PROPAGATE_FAULT;
4748 addr = dtable.base + index * 8;
4749 ret = kvm_read_guest_virt_system(addr, seg_desc, sizeof(*seg_desc),
4751 if (ret == X86EMUL_PROPAGATE_FAULT)
4752 kvm_inject_page_fault(vcpu, addr, err);
4757 /* allowed just for 8 bytes segments */
4758 static int save_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
4759 struct desc_struct *seg_desc)
4761 struct desc_ptr dtable;
4762 u16 index = selector >> 3;
4764 get_segment_descriptor_dtable(vcpu, selector, &dtable);
4766 if (dtable.size < index * 8 + 7)
4768 return kvm_write_guest_virt(dtable.address + index*8, seg_desc, sizeof(*seg_desc), vcpu, NULL);
4771 static gpa_t get_tss_base_addr_write(struct kvm_vcpu *vcpu,
4772 struct desc_struct *seg_desc)
4774 u32 base_addr = get_desc_base(seg_desc);
4776 return kvm_mmu_gva_to_gpa_write(vcpu, base_addr, NULL);
4779 static gpa_t get_tss_base_addr_read(struct kvm_vcpu *vcpu,
4780 struct desc_struct *seg_desc)
4782 u32 base_addr = get_desc_base(seg_desc);
4784 return kvm_mmu_gva_to_gpa_read(vcpu, base_addr, NULL);
4787 static u16 get_segment_selector(struct kvm_vcpu *vcpu, int seg)
4789 struct kvm_segment kvm_seg;
4791 kvm_get_segment(vcpu, &kvm_seg, seg);
4792 return kvm_seg.selector;
4795 static int kvm_load_realmode_segment(struct kvm_vcpu *vcpu, u16 selector, int seg)
4797 struct kvm_segment segvar = {
4798 .base = selector << 4,
4800 .selector = selector,
4811 kvm_x86_ops->set_segment(vcpu, &segvar, seg);
4812 return X86EMUL_CONTINUE;
4815 static int is_vm86_segment(struct kvm_vcpu *vcpu, int seg)
4817 return (seg != VCPU_SREG_LDTR) &&
4818 (seg != VCPU_SREG_TR) &&
4819 (kvm_get_rflags(vcpu) & X86_EFLAGS_VM);
4822 int kvm_load_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector, int seg)
4824 struct kvm_segment kvm_seg;
4825 struct desc_struct seg_desc;
4827 unsigned err_vec = GP_VECTOR;
4829 bool null_selector = !(selector & ~0x3); /* 0000-0003 are null */
4832 if (is_vm86_segment(vcpu, seg) || !is_protmode(vcpu))
4833 return kvm_load_realmode_segment(vcpu, selector, seg);
4835 /* NULL selector is not valid for TR, CS and SS */
4836 if ((seg == VCPU_SREG_CS || seg == VCPU_SREG_SS || seg == VCPU_SREG_TR)
4840 /* TR should be in GDT only */
4841 if (seg == VCPU_SREG_TR && (selector & (1 << 2)))
4844 ret = load_guest_segment_descriptor(vcpu, selector, &seg_desc);
4848 seg_desct_to_kvm_desct(&seg_desc, selector, &kvm_seg);
4850 if (null_selector) { /* for NULL selector skip all following checks */
4851 kvm_seg.unusable = 1;
4855 err_code = selector & 0xfffc;
4856 err_vec = GP_VECTOR;
4858 /* can't load system descriptor into segment selecor */
4859 if (seg <= VCPU_SREG_GS && !kvm_seg.s)
4862 if (!kvm_seg.present) {
4863 err_vec = (seg == VCPU_SREG_SS) ? SS_VECTOR : NP_VECTOR;
4869 cpl = kvm_x86_ops->get_cpl(vcpu);
4874 * segment is not a writable data segment or segment
4875 * selector's RPL != CPL or segment selector's RPL != CPL
4877 if (rpl != cpl || (kvm_seg.type & 0xa) != 0x2 || dpl != cpl)
4881 if (!(kvm_seg.type & 8))
4884 if (kvm_seg.type & 4) {
4890 if (rpl > cpl || dpl != cpl)
4893 /* CS(RPL) <- CPL */
4894 selector = (selector & 0xfffc) | cpl;
4897 if (kvm_seg.s || (kvm_seg.type != 1 && kvm_seg.type != 9))
4900 case VCPU_SREG_LDTR:
4901 if (kvm_seg.s || kvm_seg.type != 2)
4904 default: /* DS, ES, FS, or GS */
4906 * segment is not a data or readable code segment or
4907 * ((segment is a data or nonconforming code segment)
4908 * and (both RPL and CPL > DPL))
4910 if ((kvm_seg.type & 0xa) == 0x8 ||
4911 (((kvm_seg.type & 0xc) != 0xc) && (rpl > dpl && cpl > dpl)))
4916 if (!kvm_seg.unusable && kvm_seg.s) {
4917 /* mark segment as accessed */
4920 save_guest_segment_descriptor(vcpu, selector, &seg_desc);
4923 kvm_set_segment(vcpu, &kvm_seg, seg);
4924 return X86EMUL_CONTINUE;
4926 kvm_queue_exception_e(vcpu, err_vec, err_code);
4927 return X86EMUL_PROPAGATE_FAULT;
4930 static void save_state_to_tss32(struct kvm_vcpu *vcpu,
4931 struct tss_segment_32 *tss)
4933 tss->cr3 = vcpu->arch.cr3;
4934 tss->eip = kvm_rip_read(vcpu);
4935 tss->eflags = kvm_get_rflags(vcpu);
4936 tss->eax = kvm_register_read(vcpu, VCPU_REGS_RAX);
4937 tss->ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
4938 tss->edx = kvm_register_read(vcpu, VCPU_REGS_RDX);
4939 tss->ebx = kvm_register_read(vcpu, VCPU_REGS_RBX);
4940 tss->esp = kvm_register_read(vcpu, VCPU_REGS_RSP);
4941 tss->ebp = kvm_register_read(vcpu, VCPU_REGS_RBP);
4942 tss->esi = kvm_register_read(vcpu, VCPU_REGS_RSI);
4943 tss->edi = kvm_register_read(vcpu, VCPU_REGS_RDI);
4944 tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
4945 tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
4946 tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
4947 tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
4948 tss->fs = get_segment_selector(vcpu, VCPU_SREG_FS);
4949 tss->gs = get_segment_selector(vcpu, VCPU_SREG_GS);
4950 tss->ldt_selector = get_segment_selector(vcpu, VCPU_SREG_LDTR);
4953 static void kvm_load_segment_selector(struct kvm_vcpu *vcpu, u16 sel, int seg)
4955 struct kvm_segment kvm_seg;
4956 kvm_get_segment(vcpu, &kvm_seg, seg);
4957 kvm_seg.selector = sel;
4958 kvm_set_segment(vcpu, &kvm_seg, seg);
4961 static int load_state_from_tss32(struct kvm_vcpu *vcpu,
4962 struct tss_segment_32 *tss)
4964 kvm_set_cr3(vcpu, tss->cr3);
4966 kvm_rip_write(vcpu, tss->eip);
4967 kvm_set_rflags(vcpu, tss->eflags | 2);
4969 kvm_register_write(vcpu, VCPU_REGS_RAX, tss->eax);
4970 kvm_register_write(vcpu, VCPU_REGS_RCX, tss->ecx);
4971 kvm_register_write(vcpu, VCPU_REGS_RDX, tss->edx);
4972 kvm_register_write(vcpu, VCPU_REGS_RBX, tss->ebx);
4973 kvm_register_write(vcpu, VCPU_REGS_RSP, tss->esp);
4974 kvm_register_write(vcpu, VCPU_REGS_RBP, tss->ebp);
4975 kvm_register_write(vcpu, VCPU_REGS_RSI, tss->esi);
4976 kvm_register_write(vcpu, VCPU_REGS_RDI, tss->edi);
4979 * SDM says that segment selectors are loaded before segment
4982 kvm_load_segment_selector(vcpu, tss->ldt_selector, VCPU_SREG_LDTR);
4983 kvm_load_segment_selector(vcpu, tss->es, VCPU_SREG_ES);
4984 kvm_load_segment_selector(vcpu, tss->cs, VCPU_SREG_CS);
4985 kvm_load_segment_selector(vcpu, tss->ss, VCPU_SREG_SS);
4986 kvm_load_segment_selector(vcpu, tss->ds, VCPU_SREG_DS);
4987 kvm_load_segment_selector(vcpu, tss->fs, VCPU_SREG_FS);
4988 kvm_load_segment_selector(vcpu, tss->gs, VCPU_SREG_GS);
4991 * Now load segment descriptors. If fault happenes at this stage
4992 * it is handled in a context of new task
4994 if (kvm_load_segment_descriptor(vcpu, tss->ldt_selector, VCPU_SREG_LDTR))
4997 if (kvm_load_segment_descriptor(vcpu, tss->es, VCPU_SREG_ES))
5000 if (kvm_load_segment_descriptor(vcpu, tss->cs, VCPU_SREG_CS))
5003 if (kvm_load_segment_descriptor(vcpu, tss->ss, VCPU_SREG_SS))
5006 if (kvm_load_segment_descriptor(vcpu, tss->ds, VCPU_SREG_DS))
5009 if (kvm_load_segment_descriptor(vcpu, tss->fs, VCPU_SREG_FS))
5012 if (kvm_load_segment_descriptor(vcpu, tss->gs, VCPU_SREG_GS))
5017 static void save_state_to_tss16(struct kvm_vcpu *vcpu,
5018 struct tss_segment_16 *tss)
5020 tss->ip = kvm_rip_read(vcpu);
5021 tss->flag = kvm_get_rflags(vcpu);
5022 tss->ax = kvm_register_read(vcpu, VCPU_REGS_RAX);
5023 tss->cx = kvm_register_read(vcpu, VCPU_REGS_RCX);
5024 tss->dx = kvm_register_read(vcpu, VCPU_REGS_RDX);
5025 tss->bx = kvm_register_read(vcpu, VCPU_REGS_RBX);
5026 tss->sp = kvm_register_read(vcpu, VCPU_REGS_RSP);
5027 tss->bp = kvm_register_read(vcpu, VCPU_REGS_RBP);
5028 tss->si = kvm_register_read(vcpu, VCPU_REGS_RSI);
5029 tss->di = kvm_register_read(vcpu, VCPU_REGS_RDI);
5031 tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
5032 tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
5033 tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
5034 tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
5035 tss->ldt = get_segment_selector(vcpu, VCPU_SREG_LDTR);
5038 static int load_state_from_tss16(struct kvm_vcpu *vcpu,
5039 struct tss_segment_16 *tss)
5041 kvm_rip_write(vcpu, tss->ip);
5042 kvm_set_rflags(vcpu, tss->flag | 2);
5043 kvm_register_write(vcpu, VCPU_REGS_RAX, tss->ax);
5044 kvm_register_write(vcpu, VCPU_REGS_RCX, tss->cx);
5045 kvm_register_write(vcpu, VCPU_REGS_RDX, tss->dx);
5046 kvm_register_write(vcpu, VCPU_REGS_RBX, tss->bx);
5047 kvm_register_write(vcpu, VCPU_REGS_RSP, tss->sp);
5048 kvm_register_write(vcpu, VCPU_REGS_RBP, tss->bp);
5049 kvm_register_write(vcpu, VCPU_REGS_RSI, tss->si);
5050 kvm_register_write(vcpu, VCPU_REGS_RDI, tss->di);
5053 * SDM says that segment selectors are loaded before segment
5056 kvm_load_segment_selector(vcpu, tss->ldt, VCPU_SREG_LDTR);
5057 kvm_load_segment_selector(vcpu, tss->es, VCPU_SREG_ES);
5058 kvm_load_segment_selector(vcpu, tss->cs, VCPU_SREG_CS);
5059 kvm_load_segment_selector(vcpu, tss->ss, VCPU_SREG_SS);
5060 kvm_load_segment_selector(vcpu, tss->ds, VCPU_SREG_DS);
5063 * Now load segment descriptors. If fault happenes at this stage
5064 * it is handled in a context of new task
5066 if (kvm_load_segment_descriptor(vcpu, tss->ldt, VCPU_SREG_LDTR))
5069 if (kvm_load_segment_descriptor(vcpu, tss->es, VCPU_SREG_ES))
5072 if (kvm_load_segment_descriptor(vcpu, tss->cs, VCPU_SREG_CS))
5075 if (kvm_load_segment_descriptor(vcpu, tss->ss, VCPU_SREG_SS))
5078 if (kvm_load_segment_descriptor(vcpu, tss->ds, VCPU_SREG_DS))
5083 static int kvm_task_switch_16(struct kvm_vcpu *vcpu, u16 tss_selector,
5084 u16 old_tss_sel, u32 old_tss_base,
5085 struct desc_struct *nseg_desc)
5087 struct tss_segment_16 tss_segment_16;
5090 if (kvm_read_guest(vcpu->kvm, old_tss_base, &tss_segment_16,
5091 sizeof tss_segment_16))
5094 save_state_to_tss16(vcpu, &tss_segment_16);
5096 if (kvm_write_guest(vcpu->kvm, old_tss_base, &tss_segment_16,
5097 sizeof tss_segment_16))
5100 if (kvm_read_guest(vcpu->kvm, get_tss_base_addr_read(vcpu, nseg_desc),
5101 &tss_segment_16, sizeof tss_segment_16))
5104 if (old_tss_sel != 0xffff) {
5105 tss_segment_16.prev_task_link = old_tss_sel;
5107 if (kvm_write_guest(vcpu->kvm,
5108 get_tss_base_addr_write(vcpu, nseg_desc),
5109 &tss_segment_16.prev_task_link,
5110 sizeof tss_segment_16.prev_task_link))
5114 if (load_state_from_tss16(vcpu, &tss_segment_16))
5122 static int kvm_task_switch_32(struct kvm_vcpu *vcpu, u16 tss_selector,
5123 u16 old_tss_sel, u32 old_tss_base,
5124 struct desc_struct *nseg_desc)
5126 struct tss_segment_32 tss_segment_32;
5129 if (kvm_read_guest(vcpu->kvm, old_tss_base, &tss_segment_32,
5130 sizeof tss_segment_32))
5133 save_state_to_tss32(vcpu, &tss_segment_32);
5135 if (kvm_write_guest(vcpu->kvm, old_tss_base, &tss_segment_32,
5136 sizeof tss_segment_32))
5139 if (kvm_read_guest(vcpu->kvm, get_tss_base_addr_read(vcpu, nseg_desc),
5140 &tss_segment_32, sizeof tss_segment_32))
5143 if (old_tss_sel != 0xffff) {
5144 tss_segment_32.prev_task_link = old_tss_sel;
5146 if (kvm_write_guest(vcpu->kvm,
5147 get_tss_base_addr_write(vcpu, nseg_desc),
5148 &tss_segment_32.prev_task_link,
5149 sizeof tss_segment_32.prev_task_link))
5153 if (load_state_from_tss32(vcpu, &tss_segment_32))
5161 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason)
5163 struct kvm_segment tr_seg;
5164 struct desc_struct cseg_desc;
5165 struct desc_struct nseg_desc;
5167 u32 old_tss_base = get_segment_base(vcpu, VCPU_SREG_TR);
5168 u16 old_tss_sel = get_segment_selector(vcpu, VCPU_SREG_TR);
5171 old_tss_base = kvm_mmu_gva_to_gpa_write(vcpu, old_tss_base, NULL);
5173 /* FIXME: Handle errors. Failure to read either TSS or their
5174 * descriptors should generate a pagefault.
5176 if (load_guest_segment_descriptor(vcpu, tss_selector, &nseg_desc))
5179 if (load_guest_segment_descriptor(vcpu, old_tss_sel, &cseg_desc))
5182 if (reason != TASK_SWITCH_IRET) {
5185 cpl = kvm_x86_ops->get_cpl(vcpu);
5186 if ((tss_selector & 3) > nseg_desc.dpl || cpl > nseg_desc.dpl) {
5187 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
5192 desc_limit = get_desc_limit(&nseg_desc);
5194 ((desc_limit < 0x67 && (nseg_desc.type & 8)) ||
5195 desc_limit < 0x2b)) {
5196 kvm_queue_exception_e(vcpu, TS_VECTOR, tss_selector & 0xfffc);
5200 if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) {
5201 cseg_desc.type &= ~(1 << 1); //clear the B flag
5202 save_guest_segment_descriptor(vcpu, old_tss_sel, &cseg_desc);
5205 if (reason == TASK_SWITCH_IRET) {
5206 u32 eflags = kvm_get_rflags(vcpu);
5207 kvm_set_rflags(vcpu, eflags & ~X86_EFLAGS_NT);
5210 /* set back link to prev task only if NT bit is set in eflags
5211 note that old_tss_sel is not used afetr this point */
5212 if (reason != TASK_SWITCH_CALL && reason != TASK_SWITCH_GATE)
5213 old_tss_sel = 0xffff;
5215 if (nseg_desc.type & 8)
5216 ret = kvm_task_switch_32(vcpu, tss_selector, old_tss_sel,
5217 old_tss_base, &nseg_desc);
5219 ret = kvm_task_switch_16(vcpu, tss_selector, old_tss_sel,
5220 old_tss_base, &nseg_desc);
5222 if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE) {
5223 u32 eflags = kvm_get_rflags(vcpu);
5224 kvm_set_rflags(vcpu, eflags | X86_EFLAGS_NT);
5227 if (reason != TASK_SWITCH_IRET) {
5228 nseg_desc.type |= (1 << 1);
5229 save_guest_segment_descriptor(vcpu, tss_selector,
5233 kvm_x86_ops->set_cr0(vcpu, kvm_read_cr0(vcpu) | X86_CR0_TS);
5234 seg_desct_to_kvm_desct(&nseg_desc, tss_selector, &tr_seg);
5236 kvm_set_segment(vcpu, &tr_seg, VCPU_SREG_TR);
5240 EXPORT_SYMBOL_GPL(kvm_task_switch);
5242 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
5243 struct kvm_sregs *sregs)
5245 int mmu_reset_needed = 0;
5246 int pending_vec, max_bits;
5251 dt.size = sregs->idt.limit;
5252 dt.address = sregs->idt.base;
5253 kvm_x86_ops->set_idt(vcpu, &dt);
5254 dt.size = sregs->gdt.limit;
5255 dt.address = sregs->gdt.base;
5256 kvm_x86_ops->set_gdt(vcpu, &dt);
5258 vcpu->arch.cr2 = sregs->cr2;
5259 mmu_reset_needed |= vcpu->arch.cr3 != sregs->cr3;
5260 vcpu->arch.cr3 = sregs->cr3;
5262 kvm_set_cr8(vcpu, sregs->cr8);
5264 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
5265 kvm_x86_ops->set_efer(vcpu, sregs->efer);
5266 kvm_set_apic_base(vcpu, sregs->apic_base);
5268 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
5269 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
5270 vcpu->arch.cr0 = sregs->cr0;
5272 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
5273 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
5274 if (!is_long_mode(vcpu) && is_pae(vcpu)) {
5275 load_pdptrs(vcpu, vcpu->arch.cr3);
5276 mmu_reset_needed = 1;
5279 if (mmu_reset_needed)
5280 kvm_mmu_reset_context(vcpu);
5282 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
5283 pending_vec = find_first_bit(
5284 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
5285 if (pending_vec < max_bits) {
5286 kvm_queue_interrupt(vcpu, pending_vec, false);
5287 pr_debug("Set back pending irq %d\n", pending_vec);
5288 if (irqchip_in_kernel(vcpu->kvm))
5289 kvm_pic_clear_isr_ack(vcpu->kvm);
5292 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
5293 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
5294 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
5295 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
5296 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
5297 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
5299 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
5300 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
5302 update_cr8_intercept(vcpu);
5304 /* Older userspace won't unhalt the vcpu on reset. */
5305 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
5306 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
5308 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5315 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
5316 struct kvm_guest_debug *dbg)
5318 unsigned long rflags;
5323 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
5325 if (vcpu->arch.exception.pending)
5327 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
5328 kvm_queue_exception(vcpu, DB_VECTOR);
5330 kvm_queue_exception(vcpu, BP_VECTOR);
5334 * Read rflags as long as potentially injected trace flags are still
5337 rflags = kvm_get_rflags(vcpu);
5339 vcpu->guest_debug = dbg->control;
5340 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
5341 vcpu->guest_debug = 0;
5343 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5344 for (i = 0; i < KVM_NR_DB_REGS; ++i)
5345 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
5346 vcpu->arch.switch_db_regs =
5347 (dbg->arch.debugreg[7] & DR7_BP_EN_MASK);
5349 for (i = 0; i < KVM_NR_DB_REGS; i++)
5350 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
5351 vcpu->arch.switch_db_regs = (vcpu->arch.dr7 & DR7_BP_EN_MASK);
5354 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
5355 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
5356 get_segment_base(vcpu, VCPU_SREG_CS);
5359 * Trigger an rflags update that will inject or remove the trace
5362 kvm_set_rflags(vcpu, rflags);
5364 kvm_x86_ops->set_guest_debug(vcpu, dbg);
5375 * fxsave fpu state. Taken from x86_64/processor.h. To be killed when
5376 * we have asm/x86/processor.h
5387 u32 st_space[32]; /* 8*16 bytes for each FP-reg = 128 bytes */
5388 #ifdef CONFIG_X86_64
5389 u32 xmm_space[64]; /* 16*16 bytes for each XMM-reg = 256 bytes */
5391 u32 xmm_space[32]; /* 8*16 bytes for each XMM-reg = 128 bytes */
5396 * Translate a guest virtual address to a guest physical address.
5398 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
5399 struct kvm_translation *tr)
5401 unsigned long vaddr = tr->linear_address;
5406 idx = srcu_read_lock(&vcpu->kvm->srcu);
5407 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
5408 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5409 tr->physical_address = gpa;
5410 tr->valid = gpa != UNMAPPED_GVA;
5418 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
5420 struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
5424 memcpy(fpu->fpr, fxsave->st_space, 128);
5425 fpu->fcw = fxsave->cwd;
5426 fpu->fsw = fxsave->swd;
5427 fpu->ftwx = fxsave->twd;
5428 fpu->last_opcode = fxsave->fop;
5429 fpu->last_ip = fxsave->rip;
5430 fpu->last_dp = fxsave->rdp;
5431 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
5438 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
5440 struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
5444 memcpy(fxsave->st_space, fpu->fpr, 128);
5445 fxsave->cwd = fpu->fcw;
5446 fxsave->swd = fpu->fsw;
5447 fxsave->twd = fpu->ftwx;
5448 fxsave->fop = fpu->last_opcode;
5449 fxsave->rip = fpu->last_ip;
5450 fxsave->rdp = fpu->last_dp;
5451 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
5458 void fx_init(struct kvm_vcpu *vcpu)
5460 unsigned after_mxcsr_mask;
5463 * Touch the fpu the first time in non atomic context as if
5464 * this is the first fpu instruction the exception handler
5465 * will fire before the instruction returns and it'll have to
5466 * allocate ram with GFP_KERNEL.
5469 kvm_fx_save(&vcpu->arch.host_fx_image);
5471 /* Initialize guest FPU by resetting ours and saving into guest's */
5473 kvm_fx_save(&vcpu->arch.host_fx_image);
5475 kvm_fx_save(&vcpu->arch.guest_fx_image);
5476 kvm_fx_restore(&vcpu->arch.host_fx_image);
5479 vcpu->arch.cr0 |= X86_CR0_ET;
5480 after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
5481 vcpu->arch.guest_fx_image.mxcsr = 0x1f80;
5482 memset((void *)&vcpu->arch.guest_fx_image + after_mxcsr_mask,
5483 0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
5485 EXPORT_SYMBOL_GPL(fx_init);
5487 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
5489 if (vcpu->guest_fpu_loaded)
5492 vcpu->guest_fpu_loaded = 1;
5493 kvm_fx_save(&vcpu->arch.host_fx_image);
5494 kvm_fx_restore(&vcpu->arch.guest_fx_image);
5498 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
5500 if (!vcpu->guest_fpu_loaded)
5503 vcpu->guest_fpu_loaded = 0;
5504 kvm_fx_save(&vcpu->arch.guest_fx_image);
5505 kvm_fx_restore(&vcpu->arch.host_fx_image);
5506 ++vcpu->stat.fpu_reload;
5507 set_bit(KVM_REQ_DEACTIVATE_FPU, &vcpu->requests);
5511 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
5513 if (vcpu->arch.time_page) {
5514 kvm_release_page_dirty(vcpu->arch.time_page);
5515 vcpu->arch.time_page = NULL;
5518 kvm_x86_ops->vcpu_free(vcpu);
5521 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
5524 return kvm_x86_ops->vcpu_create(kvm, id);
5527 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
5531 /* We do fxsave: this must be aligned. */
5532 BUG_ON((unsigned long)&vcpu->arch.host_fx_image & 0xF);
5534 vcpu->arch.mtrr_state.have_fixed = 1;
5536 r = kvm_arch_vcpu_reset(vcpu);
5538 r = kvm_mmu_setup(vcpu);
5545 kvm_x86_ops->vcpu_free(vcpu);
5549 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
5552 kvm_mmu_unload(vcpu);
5555 kvm_x86_ops->vcpu_free(vcpu);
5558 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
5560 vcpu->arch.nmi_pending = false;
5561 vcpu->arch.nmi_injected = false;
5563 vcpu->arch.switch_db_regs = 0;
5564 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
5565 vcpu->arch.dr6 = DR6_FIXED_1;
5566 vcpu->arch.dr7 = DR7_FIXED_1;
5568 return kvm_x86_ops->vcpu_reset(vcpu);
5571 int kvm_arch_hardware_enable(void *garbage)
5574 * Since this may be called from a hotplug notifcation,
5575 * we can't get the CPU frequency directly.
5577 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5578 int cpu = raw_smp_processor_id();
5579 per_cpu(cpu_tsc_khz, cpu) = 0;
5582 kvm_shared_msr_cpu_online();
5584 return kvm_x86_ops->hardware_enable(garbage);
5587 void kvm_arch_hardware_disable(void *garbage)
5589 kvm_x86_ops->hardware_disable(garbage);
5590 drop_user_return_notifiers(garbage);
5593 int kvm_arch_hardware_setup(void)
5595 return kvm_x86_ops->hardware_setup();
5598 void kvm_arch_hardware_unsetup(void)
5600 kvm_x86_ops->hardware_unsetup();
5603 void kvm_arch_check_processor_compat(void *rtn)
5605 kvm_x86_ops->check_processor_compatibility(rtn);
5608 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
5614 BUG_ON(vcpu->kvm == NULL);
5617 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
5618 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
5619 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5621 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
5623 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
5628 vcpu->arch.pio_data = page_address(page);
5630 r = kvm_mmu_create(vcpu);
5632 goto fail_free_pio_data;
5634 if (irqchip_in_kernel(kvm)) {
5635 r = kvm_create_lapic(vcpu);
5637 goto fail_mmu_destroy;
5640 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
5642 if (!vcpu->arch.mce_banks) {
5644 goto fail_free_lapic;
5646 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
5650 kvm_free_lapic(vcpu);
5652 kvm_mmu_destroy(vcpu);
5654 free_page((unsigned long)vcpu->arch.pio_data);
5659 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
5663 kfree(vcpu->arch.mce_banks);
5664 kvm_free_lapic(vcpu);
5665 idx = srcu_read_lock(&vcpu->kvm->srcu);
5666 kvm_mmu_destroy(vcpu);
5667 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5668 free_page((unsigned long)vcpu->arch.pio_data);
5671 struct kvm *kvm_arch_create_vm(void)
5673 struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
5676 return ERR_PTR(-ENOMEM);
5678 kvm->arch.aliases = kzalloc(sizeof(struct kvm_mem_aliases), GFP_KERNEL);
5679 if (!kvm->arch.aliases) {
5681 return ERR_PTR(-ENOMEM);
5684 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
5685 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
5687 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
5688 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
5690 rdtscll(kvm->arch.vm_init_tsc);
5695 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
5698 kvm_mmu_unload(vcpu);
5702 static void kvm_free_vcpus(struct kvm *kvm)
5705 struct kvm_vcpu *vcpu;
5708 * Unpin any mmu pages first.
5710 kvm_for_each_vcpu(i, vcpu, kvm)
5711 kvm_unload_vcpu_mmu(vcpu);
5712 kvm_for_each_vcpu(i, vcpu, kvm)
5713 kvm_arch_vcpu_free(vcpu);
5715 mutex_lock(&kvm->lock);
5716 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
5717 kvm->vcpus[i] = NULL;
5719 atomic_set(&kvm->online_vcpus, 0);
5720 mutex_unlock(&kvm->lock);
5723 void kvm_arch_sync_events(struct kvm *kvm)
5725 kvm_free_all_assigned_devices(kvm);
5728 void kvm_arch_destroy_vm(struct kvm *kvm)
5730 kvm_iommu_unmap_guest(kvm);
5732 kfree(kvm->arch.vpic);
5733 kfree(kvm->arch.vioapic);
5734 kvm_free_vcpus(kvm);
5735 kvm_free_physmem(kvm);
5736 if (kvm->arch.apic_access_page)
5737 put_page(kvm->arch.apic_access_page);
5738 if (kvm->arch.ept_identity_pagetable)
5739 put_page(kvm->arch.ept_identity_pagetable);
5740 cleanup_srcu_struct(&kvm->srcu);
5741 kfree(kvm->arch.aliases);
5745 int kvm_arch_prepare_memory_region(struct kvm *kvm,
5746 struct kvm_memory_slot *memslot,
5747 struct kvm_memory_slot old,
5748 struct kvm_userspace_memory_region *mem,
5751 int npages = memslot->npages;
5753 /*To keep backward compatibility with older userspace,
5754 *x86 needs to hanlde !user_alloc case.
5757 if (npages && !old.rmap) {
5758 unsigned long userspace_addr;
5760 down_write(¤t->mm->mmap_sem);
5761 userspace_addr = do_mmap(NULL, 0,
5763 PROT_READ | PROT_WRITE,
5764 MAP_PRIVATE | MAP_ANONYMOUS,
5766 up_write(¤t->mm->mmap_sem);
5768 if (IS_ERR((void *)userspace_addr))
5769 return PTR_ERR((void *)userspace_addr);
5771 memslot->userspace_addr = userspace_addr;
5779 void kvm_arch_commit_memory_region(struct kvm *kvm,
5780 struct kvm_userspace_memory_region *mem,
5781 struct kvm_memory_slot old,
5785 int npages = mem->memory_size >> PAGE_SHIFT;
5787 if (!user_alloc && !old.user_alloc && old.rmap && !npages) {
5790 down_write(¤t->mm->mmap_sem);
5791 ret = do_munmap(current->mm, old.userspace_addr,
5792 old.npages * PAGE_SIZE);
5793 up_write(¤t->mm->mmap_sem);
5796 "kvm_vm_ioctl_set_memory_region: "
5797 "failed to munmap memory\n");
5800 spin_lock(&kvm->mmu_lock);
5801 if (!kvm->arch.n_requested_mmu_pages) {
5802 unsigned int nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
5803 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
5806 kvm_mmu_slot_remove_write_access(kvm, mem->slot);
5807 spin_unlock(&kvm->mmu_lock);
5810 void kvm_arch_flush_shadow(struct kvm *kvm)
5812 kvm_mmu_zap_all(kvm);
5813 kvm_reload_remote_mmus(kvm);
5816 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
5818 return vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE
5819 || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
5820 || vcpu->arch.nmi_pending ||
5821 (kvm_arch_interrupt_allowed(vcpu) &&
5822 kvm_cpu_has_interrupt(vcpu));
5825 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
5828 int cpu = vcpu->cpu;
5830 if (waitqueue_active(&vcpu->wq)) {
5831 wake_up_interruptible(&vcpu->wq);
5832 ++vcpu->stat.halt_wakeup;
5836 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
5837 if (!test_and_set_bit(KVM_REQ_KICK, &vcpu->requests))
5838 smp_send_reschedule(cpu);
5842 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
5844 return kvm_x86_ops->interrupt_allowed(vcpu);
5847 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
5849 unsigned long current_rip = kvm_rip_read(vcpu) +
5850 get_segment_base(vcpu, VCPU_SREG_CS);
5852 return current_rip == linear_rip;
5854 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
5856 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
5858 unsigned long rflags;
5860 rflags = kvm_x86_ops->get_rflags(vcpu);
5861 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
5862 rflags &= ~X86_EFLAGS_TF;
5865 EXPORT_SYMBOL_GPL(kvm_get_rflags);
5867 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
5869 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
5870 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
5871 rflags |= X86_EFLAGS_TF;
5872 kvm_x86_ops->set_rflags(vcpu, rflags);
5874 EXPORT_SYMBOL_GPL(kvm_set_rflags);
5876 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
5877 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
5878 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
5879 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
5880 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
5881 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
5882 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
5883 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
5884 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
5885 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
5886 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
5887 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);