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>
44 #undef TRACE_INCLUDE_FILE
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 unsigned long segment_base(u16 selector)
228 struct descriptor_table gdt;
229 struct desc_struct *d;
230 unsigned long table_base;
237 table_base = gdt.base;
239 if (selector & 4) { /* from ldt */
240 u16 ldt_selector = kvm_read_ldt();
242 table_base = segment_base(ldt_selector);
244 d = (struct desc_struct *)(table_base + (selector & ~7));
245 v = get_desc_base(d);
247 if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
248 v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
252 EXPORT_SYMBOL_GPL(segment_base);
254 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
256 if (irqchip_in_kernel(vcpu->kvm))
257 return vcpu->arch.apic_base;
259 return vcpu->arch.apic_base;
261 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
263 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
265 /* TODO: reserve bits check */
266 if (irqchip_in_kernel(vcpu->kvm))
267 kvm_lapic_set_base(vcpu, data);
269 vcpu->arch.apic_base = data;
271 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
273 #define EXCPT_BENIGN 0
274 #define EXCPT_CONTRIBUTORY 1
277 static int exception_class(int vector)
287 return EXCPT_CONTRIBUTORY;
294 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
295 unsigned nr, bool has_error, u32 error_code)
300 if (!vcpu->arch.exception.pending) {
302 vcpu->arch.exception.pending = true;
303 vcpu->arch.exception.has_error_code = has_error;
304 vcpu->arch.exception.nr = nr;
305 vcpu->arch.exception.error_code = error_code;
309 /* to check exception */
310 prev_nr = vcpu->arch.exception.nr;
311 if (prev_nr == DF_VECTOR) {
312 /* triple fault -> shutdown */
313 set_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests);
316 class1 = exception_class(prev_nr);
317 class2 = exception_class(nr);
318 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
319 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
320 /* generate double fault per SDM Table 5-5 */
321 vcpu->arch.exception.pending = true;
322 vcpu->arch.exception.has_error_code = true;
323 vcpu->arch.exception.nr = DF_VECTOR;
324 vcpu->arch.exception.error_code = 0;
326 /* replace previous exception with a new one in a hope
327 that instruction re-execution will regenerate lost
332 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
334 kvm_multiple_exception(vcpu, nr, false, 0);
336 EXPORT_SYMBOL_GPL(kvm_queue_exception);
338 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, unsigned long addr,
341 ++vcpu->stat.pf_guest;
342 vcpu->arch.cr2 = addr;
343 kvm_queue_exception_e(vcpu, PF_VECTOR, error_code);
346 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
348 vcpu->arch.nmi_pending = 1;
350 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
352 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
354 kvm_multiple_exception(vcpu, nr, true, error_code);
356 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
359 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
360 * a #GP and return false.
362 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
364 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
366 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
369 EXPORT_SYMBOL_GPL(kvm_require_cpl);
372 * Load the pae pdptrs. Return true is they are all valid.
374 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
376 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
377 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
380 u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
382 ret = kvm_read_guest_page(vcpu->kvm, pdpt_gfn, pdpte,
383 offset * sizeof(u64), sizeof(pdpte));
388 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
389 if (is_present_gpte(pdpte[i]) &&
390 (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
397 memcpy(vcpu->arch.pdptrs, pdpte, sizeof(vcpu->arch.pdptrs));
398 __set_bit(VCPU_EXREG_PDPTR,
399 (unsigned long *)&vcpu->arch.regs_avail);
400 __set_bit(VCPU_EXREG_PDPTR,
401 (unsigned long *)&vcpu->arch.regs_dirty);
406 EXPORT_SYMBOL_GPL(load_pdptrs);
408 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
410 u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
414 if (is_long_mode(vcpu) || !is_pae(vcpu))
417 if (!test_bit(VCPU_EXREG_PDPTR,
418 (unsigned long *)&vcpu->arch.regs_avail))
421 r = kvm_read_guest(vcpu->kvm, vcpu->arch.cr3 & ~31u, pdpte, sizeof(pdpte));
424 changed = memcmp(pdpte, vcpu->arch.pdptrs, sizeof(pdpte)) != 0;
430 void kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
435 if (cr0 & 0xffffffff00000000UL) {
436 printk(KERN_DEBUG "set_cr0: 0x%lx #GP, reserved bits 0x%lx\n",
437 cr0, kvm_read_cr0(vcpu));
438 kvm_inject_gp(vcpu, 0);
443 cr0 &= ~CR0_RESERVED_BITS;
445 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD)) {
446 printk(KERN_DEBUG "set_cr0: #GP, CD == 0 && NW == 1\n");
447 kvm_inject_gp(vcpu, 0);
451 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE)) {
452 printk(KERN_DEBUG "set_cr0: #GP, set PG flag "
453 "and a clear PE flag\n");
454 kvm_inject_gp(vcpu, 0);
458 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
460 if ((vcpu->arch.efer & EFER_LME)) {
464 printk(KERN_DEBUG "set_cr0: #GP, start paging "
465 "in long mode while PAE is disabled\n");
466 kvm_inject_gp(vcpu, 0);
469 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
471 printk(KERN_DEBUG "set_cr0: #GP, start paging "
472 "in long mode while CS.L == 1\n");
473 kvm_inject_gp(vcpu, 0);
479 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.cr3)) {
480 printk(KERN_DEBUG "set_cr0: #GP, pdptrs "
482 kvm_inject_gp(vcpu, 0);
488 kvm_x86_ops->set_cr0(vcpu, cr0);
489 vcpu->arch.cr0 = cr0;
491 kvm_mmu_reset_context(vcpu);
494 EXPORT_SYMBOL_GPL(kvm_set_cr0);
496 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
498 kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0ful) | (msw & 0x0f));
500 EXPORT_SYMBOL_GPL(kvm_lmsw);
502 void kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
504 unsigned long old_cr4 = kvm_read_cr4(vcpu);
505 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE;
507 if (cr4 & CR4_RESERVED_BITS) {
508 printk(KERN_DEBUG "set_cr4: #GP, reserved bits\n");
509 kvm_inject_gp(vcpu, 0);
513 if (is_long_mode(vcpu)) {
514 if (!(cr4 & X86_CR4_PAE)) {
515 printk(KERN_DEBUG "set_cr4: #GP, clearing PAE while "
517 kvm_inject_gp(vcpu, 0);
520 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
521 && ((cr4 ^ old_cr4) & pdptr_bits)
522 && !load_pdptrs(vcpu, vcpu->arch.cr3)) {
523 printk(KERN_DEBUG "set_cr4: #GP, pdptrs reserved bits\n");
524 kvm_inject_gp(vcpu, 0);
528 if (cr4 & X86_CR4_VMXE) {
529 printk(KERN_DEBUG "set_cr4: #GP, setting VMXE\n");
530 kvm_inject_gp(vcpu, 0);
533 kvm_x86_ops->set_cr4(vcpu, cr4);
534 vcpu->arch.cr4 = cr4;
535 vcpu->arch.mmu.base_role.cr4_pge = (cr4 & X86_CR4_PGE) && !tdp_enabled;
536 kvm_mmu_reset_context(vcpu);
538 EXPORT_SYMBOL_GPL(kvm_set_cr4);
540 void kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
542 if (cr3 == vcpu->arch.cr3 && !pdptrs_changed(vcpu)) {
543 kvm_mmu_sync_roots(vcpu);
544 kvm_mmu_flush_tlb(vcpu);
548 if (is_long_mode(vcpu)) {
549 if (cr3 & CR3_L_MODE_RESERVED_BITS) {
550 printk(KERN_DEBUG "set_cr3: #GP, reserved bits\n");
551 kvm_inject_gp(vcpu, 0);
556 if (cr3 & CR3_PAE_RESERVED_BITS) {
558 "set_cr3: #GP, reserved bits\n");
559 kvm_inject_gp(vcpu, 0);
562 if (is_paging(vcpu) && !load_pdptrs(vcpu, cr3)) {
563 printk(KERN_DEBUG "set_cr3: #GP, pdptrs "
565 kvm_inject_gp(vcpu, 0);
570 * We don't check reserved bits in nonpae mode, because
571 * this isn't enforced, and VMware depends on this.
576 * Does the new cr3 value map to physical memory? (Note, we
577 * catch an invalid cr3 even in real-mode, because it would
578 * cause trouble later on when we turn on paging anyway.)
580 * A real CPU would silently accept an invalid cr3 and would
581 * attempt to use it - with largely undefined (and often hard
582 * to debug) behavior on the guest side.
584 if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
585 kvm_inject_gp(vcpu, 0);
587 vcpu->arch.cr3 = cr3;
588 vcpu->arch.mmu.new_cr3(vcpu);
591 EXPORT_SYMBOL_GPL(kvm_set_cr3);
593 void kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
595 if (cr8 & CR8_RESERVED_BITS) {
596 printk(KERN_DEBUG "set_cr8: #GP, reserved bits 0x%lx\n", cr8);
597 kvm_inject_gp(vcpu, 0);
600 if (irqchip_in_kernel(vcpu->kvm))
601 kvm_lapic_set_tpr(vcpu, cr8);
603 vcpu->arch.cr8 = cr8;
605 EXPORT_SYMBOL_GPL(kvm_set_cr8);
607 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
609 if (irqchip_in_kernel(vcpu->kvm))
610 return kvm_lapic_get_cr8(vcpu);
612 return vcpu->arch.cr8;
614 EXPORT_SYMBOL_GPL(kvm_get_cr8);
616 static inline u32 bit(int bitno)
618 return 1 << (bitno & 31);
622 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
623 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
625 * This list is modified at module load time to reflect the
626 * capabilities of the host cpu. This capabilities test skips MSRs that are
627 * kvm-specific. Those are put in the beginning of the list.
630 #define KVM_SAVE_MSRS_BEGIN 5
631 static u32 msrs_to_save[] = {
632 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
633 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
634 HV_X64_MSR_APIC_ASSIST_PAGE,
635 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
638 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
640 MSR_IA32_TSC, MSR_IA32_PERF_STATUS, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA
643 static unsigned num_msrs_to_save;
645 static u32 emulated_msrs[] = {
646 MSR_IA32_MISC_ENABLE,
649 static void set_efer(struct kvm_vcpu *vcpu, u64 efer)
651 if (efer & efer_reserved_bits) {
652 printk(KERN_DEBUG "set_efer: 0x%llx #GP, reserved bits\n",
654 kvm_inject_gp(vcpu, 0);
659 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME)) {
660 printk(KERN_DEBUG "set_efer: #GP, change LME while paging\n");
661 kvm_inject_gp(vcpu, 0);
665 if (efer & EFER_FFXSR) {
666 struct kvm_cpuid_entry2 *feat;
668 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
669 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT))) {
670 printk(KERN_DEBUG "set_efer: #GP, enable FFXSR w/o CPUID capability\n");
671 kvm_inject_gp(vcpu, 0);
676 if (efer & EFER_SVME) {
677 struct kvm_cpuid_entry2 *feat;
679 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
680 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM))) {
681 printk(KERN_DEBUG "set_efer: #GP, enable SVM w/o SVM\n");
682 kvm_inject_gp(vcpu, 0);
687 kvm_x86_ops->set_efer(vcpu, efer);
690 efer |= vcpu->arch.efer & EFER_LMA;
692 vcpu->arch.efer = efer;
694 vcpu->arch.mmu.base_role.nxe = (efer & EFER_NX) && !tdp_enabled;
695 kvm_mmu_reset_context(vcpu);
698 void kvm_enable_efer_bits(u64 mask)
700 efer_reserved_bits &= ~mask;
702 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
706 * Writes msr value into into the appropriate "register".
707 * Returns 0 on success, non-0 otherwise.
708 * Assumes vcpu_load() was already called.
710 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
712 return kvm_x86_ops->set_msr(vcpu, msr_index, data);
716 * Adapt set_msr() to msr_io()'s calling convention
718 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
720 return kvm_set_msr(vcpu, index, *data);
723 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
726 struct pvclock_wall_clock wc;
727 struct timespec boot;
734 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
737 * The guest calculates current wall clock time by adding
738 * system time (updated by kvm_write_guest_time below) to the
739 * wall clock specified here. guest system time equals host
740 * system time for us, thus we must fill in host boot time here.
744 wc.sec = boot.tv_sec;
745 wc.nsec = boot.tv_nsec;
746 wc.version = version;
748 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
751 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
754 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
756 uint32_t quotient, remainder;
758 /* Don't try to replace with do_div(), this one calculates
759 * "(dividend << 32) / divisor" */
761 : "=a" (quotient), "=d" (remainder)
762 : "0" (0), "1" (dividend), "r" (divisor) );
766 static void kvm_set_time_scale(uint32_t tsc_khz, struct pvclock_vcpu_time_info *hv_clock)
768 uint64_t nsecs = 1000000000LL;
773 tps64 = tsc_khz * 1000LL;
774 while (tps64 > nsecs*2) {
779 tps32 = (uint32_t)tps64;
780 while (tps32 <= (uint32_t)nsecs) {
785 hv_clock->tsc_shift = shift;
786 hv_clock->tsc_to_system_mul = div_frac(nsecs, tps32);
788 pr_debug("%s: tsc_khz %u, tsc_shift %d, tsc_mul %u\n",
789 __func__, tsc_khz, hv_clock->tsc_shift,
790 hv_clock->tsc_to_system_mul);
793 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
795 static void kvm_write_guest_time(struct kvm_vcpu *v)
799 struct kvm_vcpu_arch *vcpu = &v->arch;
801 unsigned long this_tsc_khz;
803 if ((!vcpu->time_page))
806 this_tsc_khz = get_cpu_var(cpu_tsc_khz);
807 if (unlikely(vcpu->hv_clock_tsc_khz != this_tsc_khz)) {
808 kvm_set_time_scale(this_tsc_khz, &vcpu->hv_clock);
809 vcpu->hv_clock_tsc_khz = this_tsc_khz;
811 put_cpu_var(cpu_tsc_khz);
813 /* Keep irq disabled to prevent changes to the clock */
814 local_irq_save(flags);
815 kvm_get_msr(v, MSR_IA32_TSC, &vcpu->hv_clock.tsc_timestamp);
817 monotonic_to_bootbased(&ts);
818 local_irq_restore(flags);
820 /* With all the info we got, fill in the values */
822 vcpu->hv_clock.system_time = ts.tv_nsec +
823 (NSEC_PER_SEC * (u64)ts.tv_sec) + v->kvm->arch.kvmclock_offset;
826 * The interface expects us to write an even number signaling that the
827 * update is finished. Since the guest won't see the intermediate
828 * state, we just increase by 2 at the end.
830 vcpu->hv_clock.version += 2;
832 shared_kaddr = kmap_atomic(vcpu->time_page, KM_USER0);
834 memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
835 sizeof(vcpu->hv_clock));
837 kunmap_atomic(shared_kaddr, KM_USER0);
839 mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
842 static int kvm_request_guest_time_update(struct kvm_vcpu *v)
844 struct kvm_vcpu_arch *vcpu = &v->arch;
846 if (!vcpu->time_page)
848 set_bit(KVM_REQ_KVMCLOCK_UPDATE, &v->requests);
852 static bool msr_mtrr_valid(unsigned msr)
855 case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
856 case MSR_MTRRfix64K_00000:
857 case MSR_MTRRfix16K_80000:
858 case MSR_MTRRfix16K_A0000:
859 case MSR_MTRRfix4K_C0000:
860 case MSR_MTRRfix4K_C8000:
861 case MSR_MTRRfix4K_D0000:
862 case MSR_MTRRfix4K_D8000:
863 case MSR_MTRRfix4K_E0000:
864 case MSR_MTRRfix4K_E8000:
865 case MSR_MTRRfix4K_F0000:
866 case MSR_MTRRfix4K_F8000:
867 case MSR_MTRRdefType:
868 case MSR_IA32_CR_PAT:
876 static bool valid_pat_type(unsigned t)
878 return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
881 static bool valid_mtrr_type(unsigned t)
883 return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
886 static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
890 if (!msr_mtrr_valid(msr))
893 if (msr == MSR_IA32_CR_PAT) {
894 for (i = 0; i < 8; i++)
895 if (!valid_pat_type((data >> (i * 8)) & 0xff))
898 } else if (msr == MSR_MTRRdefType) {
901 return valid_mtrr_type(data & 0xff);
902 } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
903 for (i = 0; i < 8 ; i++)
904 if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
910 return valid_mtrr_type(data & 0xff);
913 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
915 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
917 if (!mtrr_valid(vcpu, msr, data))
920 if (msr == MSR_MTRRdefType) {
921 vcpu->arch.mtrr_state.def_type = data;
922 vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
923 } else if (msr == MSR_MTRRfix64K_00000)
925 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
926 p[1 + msr - MSR_MTRRfix16K_80000] = data;
927 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
928 p[3 + msr - MSR_MTRRfix4K_C0000] = data;
929 else if (msr == MSR_IA32_CR_PAT)
930 vcpu->arch.pat = data;
931 else { /* Variable MTRRs */
932 int idx, is_mtrr_mask;
935 idx = (msr - 0x200) / 2;
936 is_mtrr_mask = msr - 0x200 - 2 * idx;
939 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
942 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
946 kvm_mmu_reset_context(vcpu);
950 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
952 u64 mcg_cap = vcpu->arch.mcg_cap;
953 unsigned bank_num = mcg_cap & 0xff;
956 case MSR_IA32_MCG_STATUS:
957 vcpu->arch.mcg_status = data;
959 case MSR_IA32_MCG_CTL:
960 if (!(mcg_cap & MCG_CTL_P))
962 if (data != 0 && data != ~(u64)0)
964 vcpu->arch.mcg_ctl = data;
967 if (msr >= MSR_IA32_MC0_CTL &&
968 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
969 u32 offset = msr - MSR_IA32_MC0_CTL;
970 /* only 0 or all 1s can be written to IA32_MCi_CTL */
971 if ((offset & 0x3) == 0 &&
972 data != 0 && data != ~(u64)0)
974 vcpu->arch.mce_banks[offset] = data;
982 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
984 struct kvm *kvm = vcpu->kvm;
985 int lm = is_long_mode(vcpu);
986 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
987 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
988 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
989 : kvm->arch.xen_hvm_config.blob_size_32;
990 u32 page_num = data & ~PAGE_MASK;
991 u64 page_addr = data & PAGE_MASK;
996 if (page_num >= blob_size)
999 page = kzalloc(PAGE_SIZE, GFP_KERNEL);
1003 if (copy_from_user(page, blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE))
1005 if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
1014 static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
1016 return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
1019 static bool kvm_hv_msr_partition_wide(u32 msr)
1023 case HV_X64_MSR_GUEST_OS_ID:
1024 case HV_X64_MSR_HYPERCALL:
1032 static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1034 struct kvm *kvm = vcpu->kvm;
1037 case HV_X64_MSR_GUEST_OS_ID:
1038 kvm->arch.hv_guest_os_id = data;
1039 /* setting guest os id to zero disables hypercall page */
1040 if (!kvm->arch.hv_guest_os_id)
1041 kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
1043 case HV_X64_MSR_HYPERCALL: {
1048 /* if guest os id is not set hypercall should remain disabled */
1049 if (!kvm->arch.hv_guest_os_id)
1051 if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
1052 kvm->arch.hv_hypercall = data;
1055 gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
1056 addr = gfn_to_hva(kvm, gfn);
1057 if (kvm_is_error_hva(addr))
1059 kvm_x86_ops->patch_hypercall(vcpu, instructions);
1060 ((unsigned char *)instructions)[3] = 0xc3; /* ret */
1061 if (copy_to_user((void __user *)addr, instructions, 4))
1063 kvm->arch.hv_hypercall = data;
1067 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1068 "data 0x%llx\n", msr, data);
1074 static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1077 case HV_X64_MSR_APIC_ASSIST_PAGE: {
1080 if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
1081 vcpu->arch.hv_vapic = data;
1084 addr = gfn_to_hva(vcpu->kvm, data >>
1085 HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
1086 if (kvm_is_error_hva(addr))
1088 if (clear_user((void __user *)addr, PAGE_SIZE))
1090 vcpu->arch.hv_vapic = data;
1093 case HV_X64_MSR_EOI:
1094 return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
1095 case HV_X64_MSR_ICR:
1096 return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
1097 case HV_X64_MSR_TPR:
1098 return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
1100 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1101 "data 0x%llx\n", msr, data);
1108 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1112 set_efer(vcpu, data);
1115 data &= ~(u64)0x40; /* ignore flush filter disable */
1117 pr_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
1122 case MSR_FAM10H_MMIO_CONF_BASE:
1124 pr_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
1129 case MSR_AMD64_NB_CFG:
1131 case MSR_IA32_DEBUGCTLMSR:
1133 /* We support the non-activated case already */
1135 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
1136 /* Values other than LBR and BTF are vendor-specific,
1137 thus reserved and should throw a #GP */
1140 pr_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
1143 case MSR_IA32_UCODE_REV:
1144 case MSR_IA32_UCODE_WRITE:
1145 case MSR_VM_HSAVE_PA:
1146 case MSR_AMD64_PATCH_LOADER:
1148 case 0x200 ... 0x2ff:
1149 return set_msr_mtrr(vcpu, msr, data);
1150 case MSR_IA32_APICBASE:
1151 kvm_set_apic_base(vcpu, data);
1153 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1154 return kvm_x2apic_msr_write(vcpu, msr, data);
1155 case MSR_IA32_MISC_ENABLE:
1156 vcpu->arch.ia32_misc_enable_msr = data;
1158 case MSR_KVM_WALL_CLOCK:
1159 vcpu->kvm->arch.wall_clock = data;
1160 kvm_write_wall_clock(vcpu->kvm, data);
1162 case MSR_KVM_SYSTEM_TIME: {
1163 if (vcpu->arch.time_page) {
1164 kvm_release_page_dirty(vcpu->arch.time_page);
1165 vcpu->arch.time_page = NULL;
1168 vcpu->arch.time = data;
1170 /* we verify if the enable bit is set... */
1174 /* ...but clean it before doing the actual write */
1175 vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
1177 vcpu->arch.time_page =
1178 gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
1180 if (is_error_page(vcpu->arch.time_page)) {
1181 kvm_release_page_clean(vcpu->arch.time_page);
1182 vcpu->arch.time_page = NULL;
1185 kvm_request_guest_time_update(vcpu);
1188 case MSR_IA32_MCG_CTL:
1189 case MSR_IA32_MCG_STATUS:
1190 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1191 return set_msr_mce(vcpu, msr, data);
1193 /* Performance counters are not protected by a CPUID bit,
1194 * so we should check all of them in the generic path for the sake of
1195 * cross vendor migration.
1196 * Writing a zero into the event select MSRs disables them,
1197 * which we perfectly emulate ;-). Any other value should be at least
1198 * reported, some guests depend on them.
1200 case MSR_P6_EVNTSEL0:
1201 case MSR_P6_EVNTSEL1:
1202 case MSR_K7_EVNTSEL0:
1203 case MSR_K7_EVNTSEL1:
1204 case MSR_K7_EVNTSEL2:
1205 case MSR_K7_EVNTSEL3:
1207 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1208 "0x%x data 0x%llx\n", msr, data);
1210 /* at least RHEL 4 unconditionally writes to the perfctr registers,
1211 * so we ignore writes to make it happy.
1213 case MSR_P6_PERFCTR0:
1214 case MSR_P6_PERFCTR1:
1215 case MSR_K7_PERFCTR0:
1216 case MSR_K7_PERFCTR1:
1217 case MSR_K7_PERFCTR2:
1218 case MSR_K7_PERFCTR3:
1219 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1220 "0x%x data 0x%llx\n", msr, data);
1222 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1223 if (kvm_hv_msr_partition_wide(msr)) {
1225 mutex_lock(&vcpu->kvm->lock);
1226 r = set_msr_hyperv_pw(vcpu, msr, data);
1227 mutex_unlock(&vcpu->kvm->lock);
1230 return set_msr_hyperv(vcpu, msr, data);
1233 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
1234 return xen_hvm_config(vcpu, data);
1236 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
1240 pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
1247 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
1251 * Reads an msr value (of 'msr_index') into 'pdata'.
1252 * Returns 0 on success, non-0 otherwise.
1253 * Assumes vcpu_load() was already called.
1255 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1257 return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
1260 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1262 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1264 if (!msr_mtrr_valid(msr))
1267 if (msr == MSR_MTRRdefType)
1268 *pdata = vcpu->arch.mtrr_state.def_type +
1269 (vcpu->arch.mtrr_state.enabled << 10);
1270 else if (msr == MSR_MTRRfix64K_00000)
1272 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1273 *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
1274 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1275 *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
1276 else if (msr == MSR_IA32_CR_PAT)
1277 *pdata = vcpu->arch.pat;
1278 else { /* Variable MTRRs */
1279 int idx, is_mtrr_mask;
1282 idx = (msr - 0x200) / 2;
1283 is_mtrr_mask = msr - 0x200 - 2 * idx;
1286 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1289 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1296 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1299 u64 mcg_cap = vcpu->arch.mcg_cap;
1300 unsigned bank_num = mcg_cap & 0xff;
1303 case MSR_IA32_P5_MC_ADDR:
1304 case MSR_IA32_P5_MC_TYPE:
1307 case MSR_IA32_MCG_CAP:
1308 data = vcpu->arch.mcg_cap;
1310 case MSR_IA32_MCG_CTL:
1311 if (!(mcg_cap & MCG_CTL_P))
1313 data = vcpu->arch.mcg_ctl;
1315 case MSR_IA32_MCG_STATUS:
1316 data = vcpu->arch.mcg_status;
1319 if (msr >= MSR_IA32_MC0_CTL &&
1320 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1321 u32 offset = msr - MSR_IA32_MC0_CTL;
1322 data = vcpu->arch.mce_banks[offset];
1331 static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1334 struct kvm *kvm = vcpu->kvm;
1337 case HV_X64_MSR_GUEST_OS_ID:
1338 data = kvm->arch.hv_guest_os_id;
1340 case HV_X64_MSR_HYPERCALL:
1341 data = kvm->arch.hv_hypercall;
1344 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1352 static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1357 case HV_X64_MSR_VP_INDEX: {
1360 kvm_for_each_vcpu(r, v, vcpu->kvm)
1365 case HV_X64_MSR_EOI:
1366 return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
1367 case HV_X64_MSR_ICR:
1368 return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
1369 case HV_X64_MSR_TPR:
1370 return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
1372 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1379 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1384 case MSR_IA32_PLATFORM_ID:
1385 case MSR_IA32_UCODE_REV:
1386 case MSR_IA32_EBL_CR_POWERON:
1387 case MSR_IA32_DEBUGCTLMSR:
1388 case MSR_IA32_LASTBRANCHFROMIP:
1389 case MSR_IA32_LASTBRANCHTOIP:
1390 case MSR_IA32_LASTINTFROMIP:
1391 case MSR_IA32_LASTINTTOIP:
1394 case MSR_VM_HSAVE_PA:
1395 case MSR_P6_PERFCTR0:
1396 case MSR_P6_PERFCTR1:
1397 case MSR_P6_EVNTSEL0:
1398 case MSR_P6_EVNTSEL1:
1399 case MSR_K7_EVNTSEL0:
1400 case MSR_K7_PERFCTR0:
1401 case MSR_K8_INT_PENDING_MSG:
1402 case MSR_AMD64_NB_CFG:
1403 case MSR_FAM10H_MMIO_CONF_BASE:
1407 data = 0x500 | KVM_NR_VAR_MTRR;
1409 case 0x200 ... 0x2ff:
1410 return get_msr_mtrr(vcpu, msr, pdata);
1411 case 0xcd: /* fsb frequency */
1414 case MSR_IA32_APICBASE:
1415 data = kvm_get_apic_base(vcpu);
1417 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1418 return kvm_x2apic_msr_read(vcpu, msr, pdata);
1420 case MSR_IA32_MISC_ENABLE:
1421 data = vcpu->arch.ia32_misc_enable_msr;
1423 case MSR_IA32_PERF_STATUS:
1424 /* TSC increment by tick */
1426 /* CPU multiplier */
1427 data |= (((uint64_t)4ULL) << 40);
1430 data = vcpu->arch.efer;
1432 case MSR_KVM_WALL_CLOCK:
1433 data = vcpu->kvm->arch.wall_clock;
1435 case MSR_KVM_SYSTEM_TIME:
1436 data = vcpu->arch.time;
1438 case MSR_IA32_P5_MC_ADDR:
1439 case MSR_IA32_P5_MC_TYPE:
1440 case MSR_IA32_MCG_CAP:
1441 case MSR_IA32_MCG_CTL:
1442 case MSR_IA32_MCG_STATUS:
1443 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1444 return get_msr_mce(vcpu, msr, pdata);
1445 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1446 if (kvm_hv_msr_partition_wide(msr)) {
1448 mutex_lock(&vcpu->kvm->lock);
1449 r = get_msr_hyperv_pw(vcpu, msr, pdata);
1450 mutex_unlock(&vcpu->kvm->lock);
1453 return get_msr_hyperv(vcpu, msr, pdata);
1457 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
1460 pr_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
1468 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
1471 * Read or write a bunch of msrs. All parameters are kernel addresses.
1473 * @return number of msrs set successfully.
1475 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
1476 struct kvm_msr_entry *entries,
1477 int (*do_msr)(struct kvm_vcpu *vcpu,
1478 unsigned index, u64 *data))
1484 idx = srcu_read_lock(&vcpu->kvm->srcu);
1485 for (i = 0; i < msrs->nmsrs; ++i)
1486 if (do_msr(vcpu, entries[i].index, &entries[i].data))
1488 srcu_read_unlock(&vcpu->kvm->srcu, idx);
1496 * Read or write a bunch of msrs. Parameters are user addresses.
1498 * @return number of msrs set successfully.
1500 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
1501 int (*do_msr)(struct kvm_vcpu *vcpu,
1502 unsigned index, u64 *data),
1505 struct kvm_msrs msrs;
1506 struct kvm_msr_entry *entries;
1511 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
1515 if (msrs.nmsrs >= MAX_IO_MSRS)
1519 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
1520 entries = vmalloc(size);
1525 if (copy_from_user(entries, user_msrs->entries, size))
1528 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
1533 if (writeback && copy_to_user(user_msrs->entries, entries, size))
1544 int kvm_dev_ioctl_check_extension(long ext)
1549 case KVM_CAP_IRQCHIP:
1551 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
1552 case KVM_CAP_SET_TSS_ADDR:
1553 case KVM_CAP_EXT_CPUID:
1554 case KVM_CAP_CLOCKSOURCE:
1556 case KVM_CAP_NOP_IO_DELAY:
1557 case KVM_CAP_MP_STATE:
1558 case KVM_CAP_SYNC_MMU:
1559 case KVM_CAP_REINJECT_CONTROL:
1560 case KVM_CAP_IRQ_INJECT_STATUS:
1561 case KVM_CAP_ASSIGN_DEV_IRQ:
1563 case KVM_CAP_IOEVENTFD:
1565 case KVM_CAP_PIT_STATE2:
1566 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
1567 case KVM_CAP_XEN_HVM:
1568 case KVM_CAP_ADJUST_CLOCK:
1569 case KVM_CAP_VCPU_EVENTS:
1570 case KVM_CAP_HYPERV:
1571 case KVM_CAP_HYPERV_VAPIC:
1572 case KVM_CAP_HYPERV_SPIN:
1573 case KVM_CAP_PCI_SEGMENT:
1574 case KVM_CAP_X86_ROBUST_SINGLESTEP:
1577 case KVM_CAP_COALESCED_MMIO:
1578 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
1581 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
1583 case KVM_CAP_NR_VCPUS:
1586 case KVM_CAP_NR_MEMSLOTS:
1587 r = KVM_MEMORY_SLOTS;
1589 case KVM_CAP_PV_MMU: /* obsolete */
1596 r = KVM_MAX_MCE_BANKS;
1606 long kvm_arch_dev_ioctl(struct file *filp,
1607 unsigned int ioctl, unsigned long arg)
1609 void __user *argp = (void __user *)arg;
1613 case KVM_GET_MSR_INDEX_LIST: {
1614 struct kvm_msr_list __user *user_msr_list = argp;
1615 struct kvm_msr_list msr_list;
1619 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
1622 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
1623 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
1626 if (n < msr_list.nmsrs)
1629 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
1630 num_msrs_to_save * sizeof(u32)))
1632 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
1634 ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
1639 case KVM_GET_SUPPORTED_CPUID: {
1640 struct kvm_cpuid2 __user *cpuid_arg = argp;
1641 struct kvm_cpuid2 cpuid;
1644 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1646 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
1647 cpuid_arg->entries);
1652 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1657 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
1660 mce_cap = KVM_MCE_CAP_SUPPORTED;
1662 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
1674 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1676 kvm_x86_ops->vcpu_load(vcpu, cpu);
1677 if (unlikely(per_cpu(cpu_tsc_khz, cpu) == 0)) {
1678 unsigned long khz = cpufreq_quick_get(cpu);
1681 per_cpu(cpu_tsc_khz, cpu) = khz;
1683 kvm_request_guest_time_update(vcpu);
1686 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
1688 kvm_put_guest_fpu(vcpu);
1689 kvm_x86_ops->vcpu_put(vcpu);
1692 static int is_efer_nx(void)
1694 unsigned long long efer = 0;
1696 rdmsrl_safe(MSR_EFER, &efer);
1697 return efer & EFER_NX;
1700 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
1703 struct kvm_cpuid_entry2 *e, *entry;
1706 for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
1707 e = &vcpu->arch.cpuid_entries[i];
1708 if (e->function == 0x80000001) {
1713 if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
1714 entry->edx &= ~(1 << 20);
1715 printk(KERN_INFO "kvm: guest NX capability removed\n");
1719 /* when an old userspace process fills a new kernel module */
1720 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
1721 struct kvm_cpuid *cpuid,
1722 struct kvm_cpuid_entry __user *entries)
1725 struct kvm_cpuid_entry *cpuid_entries;
1728 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1731 cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
1735 if (copy_from_user(cpuid_entries, entries,
1736 cpuid->nent * sizeof(struct kvm_cpuid_entry)))
1738 for (i = 0; i < cpuid->nent; i++) {
1739 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
1740 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
1741 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
1742 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
1743 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
1744 vcpu->arch.cpuid_entries[i].index = 0;
1745 vcpu->arch.cpuid_entries[i].flags = 0;
1746 vcpu->arch.cpuid_entries[i].padding[0] = 0;
1747 vcpu->arch.cpuid_entries[i].padding[1] = 0;
1748 vcpu->arch.cpuid_entries[i].padding[2] = 0;
1750 vcpu->arch.cpuid_nent = cpuid->nent;
1751 cpuid_fix_nx_cap(vcpu);
1753 kvm_apic_set_version(vcpu);
1754 kvm_x86_ops->cpuid_update(vcpu);
1757 vfree(cpuid_entries);
1762 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
1763 struct kvm_cpuid2 *cpuid,
1764 struct kvm_cpuid_entry2 __user *entries)
1769 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1772 if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
1773 cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
1775 vcpu->arch.cpuid_nent = cpuid->nent;
1776 kvm_apic_set_version(vcpu);
1777 kvm_x86_ops->cpuid_update(vcpu);
1784 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
1785 struct kvm_cpuid2 *cpuid,
1786 struct kvm_cpuid_entry2 __user *entries)
1791 if (cpuid->nent < vcpu->arch.cpuid_nent)
1794 if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
1795 vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
1800 cpuid->nent = vcpu->arch.cpuid_nent;
1804 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1807 entry->function = function;
1808 entry->index = index;
1809 cpuid_count(entry->function, entry->index,
1810 &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
1814 #define F(x) bit(X86_FEATURE_##x)
1816 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1817 u32 index, int *nent, int maxnent)
1819 unsigned f_nx = is_efer_nx() ? F(NX) : 0;
1820 #ifdef CONFIG_X86_64
1821 unsigned f_gbpages = (kvm_x86_ops->get_lpage_level() == PT_PDPE_LEVEL)
1823 unsigned f_lm = F(LM);
1825 unsigned f_gbpages = 0;
1828 unsigned f_rdtscp = kvm_x86_ops->rdtscp_supported() ? F(RDTSCP) : 0;
1831 const u32 kvm_supported_word0_x86_features =
1832 F(FPU) | F(VME) | F(DE) | F(PSE) |
1833 F(TSC) | F(MSR) | F(PAE) | F(MCE) |
1834 F(CX8) | F(APIC) | 0 /* Reserved */ | F(SEP) |
1835 F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
1836 F(PAT) | F(PSE36) | 0 /* PSN */ | F(CLFLSH) |
1837 0 /* Reserved, DS, ACPI */ | F(MMX) |
1838 F(FXSR) | F(XMM) | F(XMM2) | F(SELFSNOOP) |
1839 0 /* HTT, TM, Reserved, PBE */;
1840 /* cpuid 0x80000001.edx */
1841 const u32 kvm_supported_word1_x86_features =
1842 F(FPU) | F(VME) | F(DE) | F(PSE) |
1843 F(TSC) | F(MSR) | F(PAE) | F(MCE) |
1844 F(CX8) | F(APIC) | 0 /* Reserved */ | F(SYSCALL) |
1845 F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
1846 F(PAT) | F(PSE36) | 0 /* Reserved */ |
1847 f_nx | 0 /* Reserved */ | F(MMXEXT) | F(MMX) |
1848 F(FXSR) | F(FXSR_OPT) | f_gbpages | f_rdtscp |
1849 0 /* Reserved */ | f_lm | F(3DNOWEXT) | F(3DNOW);
1851 const u32 kvm_supported_word4_x86_features =
1852 F(XMM3) | 0 /* Reserved, DTES64, MONITOR */ |
1853 0 /* DS-CPL, VMX, SMX, EST */ |
1854 0 /* TM2 */ | F(SSSE3) | 0 /* CNXT-ID */ | 0 /* Reserved */ |
1855 0 /* Reserved */ | F(CX16) | 0 /* xTPR Update, PDCM */ |
1856 0 /* Reserved, DCA */ | F(XMM4_1) |
1857 F(XMM4_2) | F(X2APIC) | F(MOVBE) | F(POPCNT) |
1858 0 /* Reserved, XSAVE, OSXSAVE */;
1859 /* cpuid 0x80000001.ecx */
1860 const u32 kvm_supported_word6_x86_features =
1861 F(LAHF_LM) | F(CMP_LEGACY) | F(SVM) | 0 /* ExtApicSpace */ |
1862 F(CR8_LEGACY) | F(ABM) | F(SSE4A) | F(MISALIGNSSE) |
1863 F(3DNOWPREFETCH) | 0 /* OSVW */ | 0 /* IBS */ | F(SSE5) |
1864 0 /* SKINIT */ | 0 /* WDT */;
1866 /* all calls to cpuid_count() should be made on the same cpu */
1868 do_cpuid_1_ent(entry, function, index);
1873 entry->eax = min(entry->eax, (u32)0xb);
1876 entry->edx &= kvm_supported_word0_x86_features;
1877 entry->ecx &= kvm_supported_word4_x86_features;
1878 /* we support x2apic emulation even if host does not support
1879 * it since we emulate x2apic in software */
1880 entry->ecx |= F(X2APIC);
1882 /* function 2 entries are STATEFUL. That is, repeated cpuid commands
1883 * may return different values. This forces us to get_cpu() before
1884 * issuing the first command, and also to emulate this annoying behavior
1885 * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
1887 int t, times = entry->eax & 0xff;
1889 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1890 entry->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
1891 for (t = 1; t < times && *nent < maxnent; ++t) {
1892 do_cpuid_1_ent(&entry[t], function, 0);
1893 entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1898 /* function 4 and 0xb have additional index. */
1902 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1903 /* read more entries until cache_type is zero */
1904 for (i = 1; *nent < maxnent; ++i) {
1905 cache_type = entry[i - 1].eax & 0x1f;
1908 do_cpuid_1_ent(&entry[i], function, i);
1910 KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1918 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1919 /* read more entries until level_type is zero */
1920 for (i = 1; *nent < maxnent; ++i) {
1921 level_type = entry[i - 1].ecx & 0xff00;
1924 do_cpuid_1_ent(&entry[i], function, i);
1926 KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1932 entry->eax = min(entry->eax, 0x8000001a);
1935 entry->edx &= kvm_supported_word1_x86_features;
1936 entry->ecx &= kvm_supported_word6_x86_features;
1944 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
1945 struct kvm_cpuid_entry2 __user *entries)
1947 struct kvm_cpuid_entry2 *cpuid_entries;
1948 int limit, nent = 0, r = -E2BIG;
1951 if (cpuid->nent < 1)
1953 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1954 cpuid->nent = KVM_MAX_CPUID_ENTRIES;
1956 cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
1960 do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
1961 limit = cpuid_entries[0].eax;
1962 for (func = 1; func <= limit && nent < cpuid->nent; ++func)
1963 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1964 &nent, cpuid->nent);
1966 if (nent >= cpuid->nent)
1969 do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
1970 limit = cpuid_entries[nent - 1].eax;
1971 for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
1972 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1973 &nent, cpuid->nent);
1975 if (nent >= cpuid->nent)
1979 if (copy_to_user(entries, cpuid_entries,
1980 nent * sizeof(struct kvm_cpuid_entry2)))
1986 vfree(cpuid_entries);
1991 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
1992 struct kvm_lapic_state *s)
1995 memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2001 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2002 struct kvm_lapic_state *s)
2005 memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
2006 kvm_apic_post_state_restore(vcpu);
2007 update_cr8_intercept(vcpu);
2013 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2014 struct kvm_interrupt *irq)
2016 if (irq->irq < 0 || irq->irq >= 256)
2018 if (irqchip_in_kernel(vcpu->kvm))
2022 kvm_queue_interrupt(vcpu, irq->irq, false);
2029 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2032 kvm_inject_nmi(vcpu);
2038 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2039 struct kvm_tpr_access_ctl *tac)
2043 vcpu->arch.tpr_access_reporting = !!tac->enabled;
2047 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2051 unsigned bank_num = mcg_cap & 0xff, bank;
2054 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2056 if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2059 vcpu->arch.mcg_cap = mcg_cap;
2060 /* Init IA32_MCG_CTL to all 1s */
2061 if (mcg_cap & MCG_CTL_P)
2062 vcpu->arch.mcg_ctl = ~(u64)0;
2063 /* Init IA32_MCi_CTL to all 1s */
2064 for (bank = 0; bank < bank_num; bank++)
2065 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2070 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2071 struct kvm_x86_mce *mce)
2073 u64 mcg_cap = vcpu->arch.mcg_cap;
2074 unsigned bank_num = mcg_cap & 0xff;
2075 u64 *banks = vcpu->arch.mce_banks;
2077 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2080 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2081 * reporting is disabled
2083 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2084 vcpu->arch.mcg_ctl != ~(u64)0)
2086 banks += 4 * mce->bank;
2088 * if IA32_MCi_CTL is not all 1s, the uncorrected error
2089 * reporting is disabled for the bank
2091 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2093 if (mce->status & MCI_STATUS_UC) {
2094 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2095 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2096 printk(KERN_DEBUG "kvm: set_mce: "
2097 "injects mce exception while "
2098 "previous one is in progress!\n");
2099 set_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests);
2102 if (banks[1] & MCI_STATUS_VAL)
2103 mce->status |= MCI_STATUS_OVER;
2104 banks[2] = mce->addr;
2105 banks[3] = mce->misc;
2106 vcpu->arch.mcg_status = mce->mcg_status;
2107 banks[1] = mce->status;
2108 kvm_queue_exception(vcpu, MC_VECTOR);
2109 } else if (!(banks[1] & MCI_STATUS_VAL)
2110 || !(banks[1] & MCI_STATUS_UC)) {
2111 if (banks[1] & MCI_STATUS_VAL)
2112 mce->status |= MCI_STATUS_OVER;
2113 banks[2] = mce->addr;
2114 banks[3] = mce->misc;
2115 banks[1] = mce->status;
2117 banks[1] |= MCI_STATUS_OVER;
2121 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2122 struct kvm_vcpu_events *events)
2126 events->exception.injected = vcpu->arch.exception.pending;
2127 events->exception.nr = vcpu->arch.exception.nr;
2128 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2129 events->exception.error_code = vcpu->arch.exception.error_code;
2131 events->interrupt.injected = vcpu->arch.interrupt.pending;
2132 events->interrupt.nr = vcpu->arch.interrupt.nr;
2133 events->interrupt.soft = vcpu->arch.interrupt.soft;
2135 events->nmi.injected = vcpu->arch.nmi_injected;
2136 events->nmi.pending = vcpu->arch.nmi_pending;
2137 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
2139 events->sipi_vector = vcpu->arch.sipi_vector;
2141 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
2142 | KVM_VCPUEVENT_VALID_SIPI_VECTOR);
2147 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
2148 struct kvm_vcpu_events *events)
2150 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
2151 | KVM_VCPUEVENT_VALID_SIPI_VECTOR))
2156 vcpu->arch.exception.pending = events->exception.injected;
2157 vcpu->arch.exception.nr = events->exception.nr;
2158 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
2159 vcpu->arch.exception.error_code = events->exception.error_code;
2161 vcpu->arch.interrupt.pending = events->interrupt.injected;
2162 vcpu->arch.interrupt.nr = events->interrupt.nr;
2163 vcpu->arch.interrupt.soft = events->interrupt.soft;
2164 if (vcpu->arch.interrupt.pending && irqchip_in_kernel(vcpu->kvm))
2165 kvm_pic_clear_isr_ack(vcpu->kvm);
2167 vcpu->arch.nmi_injected = events->nmi.injected;
2168 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
2169 vcpu->arch.nmi_pending = events->nmi.pending;
2170 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
2172 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR)
2173 vcpu->arch.sipi_vector = events->sipi_vector;
2180 long kvm_arch_vcpu_ioctl(struct file *filp,
2181 unsigned int ioctl, unsigned long arg)
2183 struct kvm_vcpu *vcpu = filp->private_data;
2184 void __user *argp = (void __user *)arg;
2186 struct kvm_lapic_state *lapic = NULL;
2189 case KVM_GET_LAPIC: {
2191 if (!vcpu->arch.apic)
2193 lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
2198 r = kvm_vcpu_ioctl_get_lapic(vcpu, lapic);
2202 if (copy_to_user(argp, lapic, sizeof(struct kvm_lapic_state)))
2207 case KVM_SET_LAPIC: {
2209 if (!vcpu->arch.apic)
2211 lapic = kmalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
2216 if (copy_from_user(lapic, argp, sizeof(struct kvm_lapic_state)))
2218 r = kvm_vcpu_ioctl_set_lapic(vcpu, lapic);
2224 case KVM_INTERRUPT: {
2225 struct kvm_interrupt irq;
2228 if (copy_from_user(&irq, argp, sizeof irq))
2230 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
2237 r = kvm_vcpu_ioctl_nmi(vcpu);
2243 case KVM_SET_CPUID: {
2244 struct kvm_cpuid __user *cpuid_arg = argp;
2245 struct kvm_cpuid cpuid;
2248 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2250 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
2255 case KVM_SET_CPUID2: {
2256 struct kvm_cpuid2 __user *cpuid_arg = argp;
2257 struct kvm_cpuid2 cpuid;
2260 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2262 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
2263 cpuid_arg->entries);
2268 case KVM_GET_CPUID2: {
2269 struct kvm_cpuid2 __user *cpuid_arg = argp;
2270 struct kvm_cpuid2 cpuid;
2273 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2275 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
2276 cpuid_arg->entries);
2280 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2286 r = msr_io(vcpu, argp, kvm_get_msr, 1);
2289 r = msr_io(vcpu, argp, do_set_msr, 0);
2291 case KVM_TPR_ACCESS_REPORTING: {
2292 struct kvm_tpr_access_ctl tac;
2295 if (copy_from_user(&tac, argp, sizeof tac))
2297 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
2301 if (copy_to_user(argp, &tac, sizeof tac))
2306 case KVM_SET_VAPIC_ADDR: {
2307 struct kvm_vapic_addr va;
2310 if (!irqchip_in_kernel(vcpu->kvm))
2313 if (copy_from_user(&va, argp, sizeof va))
2316 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
2319 case KVM_X86_SETUP_MCE: {
2323 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
2325 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
2328 case KVM_X86_SET_MCE: {
2329 struct kvm_x86_mce mce;
2332 if (copy_from_user(&mce, argp, sizeof mce))
2334 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
2337 case KVM_GET_VCPU_EVENTS: {
2338 struct kvm_vcpu_events events;
2340 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
2343 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
2348 case KVM_SET_VCPU_EVENTS: {
2349 struct kvm_vcpu_events events;
2352 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
2355 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
2366 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
2370 if (addr > (unsigned int)(-3 * PAGE_SIZE))
2372 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
2376 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
2379 kvm->arch.ept_identity_map_addr = ident_addr;
2383 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
2384 u32 kvm_nr_mmu_pages)
2386 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
2389 mutex_lock(&kvm->slots_lock);
2390 spin_lock(&kvm->mmu_lock);
2392 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
2393 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
2395 spin_unlock(&kvm->mmu_lock);
2396 mutex_unlock(&kvm->slots_lock);
2400 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
2402 return kvm->arch.n_alloc_mmu_pages;
2405 gfn_t unalias_gfn_instantiation(struct kvm *kvm, gfn_t gfn)
2408 struct kvm_mem_alias *alias;
2409 struct kvm_mem_aliases *aliases;
2411 aliases = rcu_dereference(kvm->arch.aliases);
2413 for (i = 0; i < aliases->naliases; ++i) {
2414 alias = &aliases->aliases[i];
2415 if (alias->flags & KVM_ALIAS_INVALID)
2417 if (gfn >= alias->base_gfn
2418 && gfn < alias->base_gfn + alias->npages)
2419 return alias->target_gfn + gfn - alias->base_gfn;
2424 gfn_t unalias_gfn(struct kvm *kvm, gfn_t gfn)
2427 struct kvm_mem_alias *alias;
2428 struct kvm_mem_aliases *aliases;
2430 aliases = rcu_dereference(kvm->arch.aliases);
2432 for (i = 0; i < aliases->naliases; ++i) {
2433 alias = &aliases->aliases[i];
2434 if (gfn >= alias->base_gfn
2435 && gfn < alias->base_gfn + alias->npages)
2436 return alias->target_gfn + gfn - alias->base_gfn;
2442 * Set a new alias region. Aliases map a portion of physical memory into
2443 * another portion. This is useful for memory windows, for example the PC
2446 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
2447 struct kvm_memory_alias *alias)
2450 struct kvm_mem_alias *p;
2451 struct kvm_mem_aliases *aliases, *old_aliases;
2454 /* General sanity checks */
2455 if (alias->memory_size & (PAGE_SIZE - 1))
2457 if (alias->guest_phys_addr & (PAGE_SIZE - 1))
2459 if (alias->slot >= KVM_ALIAS_SLOTS)
2461 if (alias->guest_phys_addr + alias->memory_size
2462 < alias->guest_phys_addr)
2464 if (alias->target_phys_addr + alias->memory_size
2465 < alias->target_phys_addr)
2469 aliases = kzalloc(sizeof(struct kvm_mem_aliases), GFP_KERNEL);
2473 mutex_lock(&kvm->slots_lock);
2475 /* invalidate any gfn reference in case of deletion/shrinking */
2476 memcpy(aliases, kvm->arch.aliases, sizeof(struct kvm_mem_aliases));
2477 aliases->aliases[alias->slot].flags |= KVM_ALIAS_INVALID;
2478 old_aliases = kvm->arch.aliases;
2479 rcu_assign_pointer(kvm->arch.aliases, aliases);
2480 synchronize_srcu_expedited(&kvm->srcu);
2481 kvm_mmu_zap_all(kvm);
2485 aliases = kzalloc(sizeof(struct kvm_mem_aliases), GFP_KERNEL);
2489 memcpy(aliases, kvm->arch.aliases, sizeof(struct kvm_mem_aliases));
2491 p = &aliases->aliases[alias->slot];
2492 p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
2493 p->npages = alias->memory_size >> PAGE_SHIFT;
2494 p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
2495 p->flags &= ~(KVM_ALIAS_INVALID);
2497 for (n = KVM_ALIAS_SLOTS; n > 0; --n)
2498 if (aliases->aliases[n - 1].npages)
2500 aliases->naliases = n;
2502 old_aliases = kvm->arch.aliases;
2503 rcu_assign_pointer(kvm->arch.aliases, aliases);
2504 synchronize_srcu_expedited(&kvm->srcu);
2509 mutex_unlock(&kvm->slots_lock);
2514 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2519 switch (chip->chip_id) {
2520 case KVM_IRQCHIP_PIC_MASTER:
2521 memcpy(&chip->chip.pic,
2522 &pic_irqchip(kvm)->pics[0],
2523 sizeof(struct kvm_pic_state));
2525 case KVM_IRQCHIP_PIC_SLAVE:
2526 memcpy(&chip->chip.pic,
2527 &pic_irqchip(kvm)->pics[1],
2528 sizeof(struct kvm_pic_state));
2530 case KVM_IRQCHIP_IOAPIC:
2531 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
2540 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2545 switch (chip->chip_id) {
2546 case KVM_IRQCHIP_PIC_MASTER:
2547 raw_spin_lock(&pic_irqchip(kvm)->lock);
2548 memcpy(&pic_irqchip(kvm)->pics[0],
2550 sizeof(struct kvm_pic_state));
2551 raw_spin_unlock(&pic_irqchip(kvm)->lock);
2553 case KVM_IRQCHIP_PIC_SLAVE:
2554 raw_spin_lock(&pic_irqchip(kvm)->lock);
2555 memcpy(&pic_irqchip(kvm)->pics[1],
2557 sizeof(struct kvm_pic_state));
2558 raw_spin_unlock(&pic_irqchip(kvm)->lock);
2560 case KVM_IRQCHIP_IOAPIC:
2561 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
2567 kvm_pic_update_irq(pic_irqchip(kvm));
2571 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2575 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2576 memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
2577 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2581 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2585 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2586 memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
2587 kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
2588 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2592 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2596 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2597 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
2598 sizeof(ps->channels));
2599 ps->flags = kvm->arch.vpit->pit_state.flags;
2600 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2604 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2606 int r = 0, start = 0;
2607 u32 prev_legacy, cur_legacy;
2608 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2609 prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
2610 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
2611 if (!prev_legacy && cur_legacy)
2613 memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
2614 sizeof(kvm->arch.vpit->pit_state.channels));
2615 kvm->arch.vpit->pit_state.flags = ps->flags;
2616 kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
2617 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2621 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
2622 struct kvm_reinject_control *control)
2624 if (!kvm->arch.vpit)
2626 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2627 kvm->arch.vpit->pit_state.pit_timer.reinject = control->pit_reinject;
2628 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2633 * Get (and clear) the dirty memory log for a memory slot.
2635 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
2636 struct kvm_dirty_log *log)
2639 struct kvm_memory_slot *memslot;
2640 unsigned long is_dirty = 0;
2641 unsigned long *dirty_bitmap = NULL;
2643 mutex_lock(&kvm->slots_lock);
2646 if (log->slot >= KVM_MEMORY_SLOTS)
2649 memslot = &kvm->memslots->memslots[log->slot];
2651 if (!memslot->dirty_bitmap)
2654 n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
2657 dirty_bitmap = vmalloc(n);
2660 memset(dirty_bitmap, 0, n);
2662 for (i = 0; !is_dirty && i < n/sizeof(long); i++)
2663 is_dirty = memslot->dirty_bitmap[i];
2665 /* If nothing is dirty, don't bother messing with page tables. */
2667 struct kvm_memslots *slots, *old_slots;
2669 spin_lock(&kvm->mmu_lock);
2670 kvm_mmu_slot_remove_write_access(kvm, log->slot);
2671 spin_unlock(&kvm->mmu_lock);
2673 slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
2677 memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
2678 slots->memslots[log->slot].dirty_bitmap = dirty_bitmap;
2680 old_slots = kvm->memslots;
2681 rcu_assign_pointer(kvm->memslots, slots);
2682 synchronize_srcu_expedited(&kvm->srcu);
2683 dirty_bitmap = old_slots->memslots[log->slot].dirty_bitmap;
2688 if (copy_to_user(log->dirty_bitmap, dirty_bitmap, n))
2691 vfree(dirty_bitmap);
2693 mutex_unlock(&kvm->slots_lock);
2697 long kvm_arch_vm_ioctl(struct file *filp,
2698 unsigned int ioctl, unsigned long arg)
2700 struct kvm *kvm = filp->private_data;
2701 void __user *argp = (void __user *)arg;
2704 * This union makes it completely explicit to gcc-3.x
2705 * that these two variables' stack usage should be
2706 * combined, not added together.
2709 struct kvm_pit_state ps;
2710 struct kvm_pit_state2 ps2;
2711 struct kvm_memory_alias alias;
2712 struct kvm_pit_config pit_config;
2716 case KVM_SET_TSS_ADDR:
2717 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
2721 case KVM_SET_IDENTITY_MAP_ADDR: {
2725 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
2727 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
2732 case KVM_SET_MEMORY_REGION: {
2733 struct kvm_memory_region kvm_mem;
2734 struct kvm_userspace_memory_region kvm_userspace_mem;
2737 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
2739 kvm_userspace_mem.slot = kvm_mem.slot;
2740 kvm_userspace_mem.flags = kvm_mem.flags;
2741 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
2742 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
2743 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
2748 case KVM_SET_NR_MMU_PAGES:
2749 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
2753 case KVM_GET_NR_MMU_PAGES:
2754 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
2756 case KVM_SET_MEMORY_ALIAS:
2758 if (copy_from_user(&u.alias, argp, sizeof(struct kvm_memory_alias)))
2760 r = kvm_vm_ioctl_set_memory_alias(kvm, &u.alias);
2764 case KVM_CREATE_IRQCHIP: {
2765 struct kvm_pic *vpic;
2767 mutex_lock(&kvm->lock);
2770 goto create_irqchip_unlock;
2772 vpic = kvm_create_pic(kvm);
2774 r = kvm_ioapic_init(kvm);
2776 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
2779 goto create_irqchip_unlock;
2782 goto create_irqchip_unlock;
2784 kvm->arch.vpic = vpic;
2786 r = kvm_setup_default_irq_routing(kvm);
2788 mutex_lock(&kvm->irq_lock);
2789 kvm_ioapic_destroy(kvm);
2790 kvm_destroy_pic(kvm);
2791 mutex_unlock(&kvm->irq_lock);
2793 create_irqchip_unlock:
2794 mutex_unlock(&kvm->lock);
2797 case KVM_CREATE_PIT:
2798 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
2800 case KVM_CREATE_PIT2:
2802 if (copy_from_user(&u.pit_config, argp,
2803 sizeof(struct kvm_pit_config)))
2806 mutex_lock(&kvm->slots_lock);
2809 goto create_pit_unlock;
2811 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
2815 mutex_unlock(&kvm->slots_lock);
2817 case KVM_IRQ_LINE_STATUS:
2818 case KVM_IRQ_LINE: {
2819 struct kvm_irq_level irq_event;
2822 if (copy_from_user(&irq_event, argp, sizeof irq_event))
2824 if (irqchip_in_kernel(kvm)) {
2826 status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
2827 irq_event.irq, irq_event.level);
2828 if (ioctl == KVM_IRQ_LINE_STATUS) {
2829 irq_event.status = status;
2830 if (copy_to_user(argp, &irq_event,
2838 case KVM_GET_IRQCHIP: {
2839 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
2840 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
2846 if (copy_from_user(chip, argp, sizeof *chip))
2847 goto get_irqchip_out;
2849 if (!irqchip_in_kernel(kvm))
2850 goto get_irqchip_out;
2851 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
2853 goto get_irqchip_out;
2855 if (copy_to_user(argp, chip, sizeof *chip))
2856 goto get_irqchip_out;
2864 case KVM_SET_IRQCHIP: {
2865 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
2866 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
2872 if (copy_from_user(chip, argp, sizeof *chip))
2873 goto set_irqchip_out;
2875 if (!irqchip_in_kernel(kvm))
2876 goto set_irqchip_out;
2877 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
2879 goto set_irqchip_out;
2889 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
2892 if (!kvm->arch.vpit)
2894 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
2898 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
2905 if (copy_from_user(&u.ps, argp, sizeof u.ps))
2908 if (!kvm->arch.vpit)
2910 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
2916 case KVM_GET_PIT2: {
2918 if (!kvm->arch.vpit)
2920 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
2924 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
2929 case KVM_SET_PIT2: {
2931 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
2934 if (!kvm->arch.vpit)
2936 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
2942 case KVM_REINJECT_CONTROL: {
2943 struct kvm_reinject_control control;
2945 if (copy_from_user(&control, argp, sizeof(control)))
2947 r = kvm_vm_ioctl_reinject(kvm, &control);
2953 case KVM_XEN_HVM_CONFIG: {
2955 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
2956 sizeof(struct kvm_xen_hvm_config)))
2959 if (kvm->arch.xen_hvm_config.flags)
2964 case KVM_SET_CLOCK: {
2965 struct timespec now;
2966 struct kvm_clock_data user_ns;
2971 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
2980 now_ns = timespec_to_ns(&now);
2981 delta = user_ns.clock - now_ns;
2982 kvm->arch.kvmclock_offset = delta;
2985 case KVM_GET_CLOCK: {
2986 struct timespec now;
2987 struct kvm_clock_data user_ns;
2991 now_ns = timespec_to_ns(&now);
2992 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
2996 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
3009 static void kvm_init_msr_list(void)
3014 /* skip the first msrs in the list. KVM-specific */
3015 for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
3016 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
3019 msrs_to_save[j] = msrs_to_save[i];
3022 num_msrs_to_save = j;
3025 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
3028 if (vcpu->arch.apic &&
3029 !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, len, v))
3032 return kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, len, v);
3035 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
3037 if (vcpu->arch.apic &&
3038 !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, len, v))
3041 return kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, len, v);
3044 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva, u32 *error)
3046 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3047 return vcpu->arch.mmu.gva_to_gpa(vcpu, gva, access, error);
3050 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva, u32 *error)
3052 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3053 access |= PFERR_FETCH_MASK;
3054 return vcpu->arch.mmu.gva_to_gpa(vcpu, gva, access, error);
3057 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva, u32 *error)
3059 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3060 access |= PFERR_WRITE_MASK;
3061 return vcpu->arch.mmu.gva_to_gpa(vcpu, gva, access, error);
3064 /* uses this to access any guest's mapped memory without checking CPL */
3065 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva, u32 *error)
3067 return vcpu->arch.mmu.gva_to_gpa(vcpu, gva, 0, error);
3070 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
3071 struct kvm_vcpu *vcpu, u32 access,
3075 int r = X86EMUL_CONTINUE;
3078 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr, access, error);
3079 unsigned offset = addr & (PAGE_SIZE-1);
3080 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
3083 if (gpa == UNMAPPED_GVA) {
3084 r = X86EMUL_PROPAGATE_FAULT;
3087 ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
3089 r = X86EMUL_UNHANDLEABLE;
3101 /* used for instruction fetching */
3102 static int kvm_fetch_guest_virt(gva_t addr, void *val, unsigned int bytes,
3103 struct kvm_vcpu *vcpu, u32 *error)
3105 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3106 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
3107 access | PFERR_FETCH_MASK, error);
3110 static int kvm_read_guest_virt(gva_t addr, void *val, unsigned int bytes,
3111 struct kvm_vcpu *vcpu, u32 *error)
3113 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3114 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
3118 static int kvm_read_guest_virt_system(gva_t addr, void *val, unsigned int bytes,
3119 struct kvm_vcpu *vcpu, u32 *error)
3121 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, error);
3124 static int kvm_write_guest_virt(gva_t addr, void *val, unsigned int bytes,
3125 struct kvm_vcpu *vcpu, u32 *error)
3128 int r = X86EMUL_CONTINUE;
3131 gpa_t gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, error);
3132 unsigned offset = addr & (PAGE_SIZE-1);
3133 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
3136 if (gpa == UNMAPPED_GVA) {
3137 r = X86EMUL_PROPAGATE_FAULT;
3140 ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
3142 r = X86EMUL_UNHANDLEABLE;
3155 static int emulator_read_emulated(unsigned long addr,
3158 struct kvm_vcpu *vcpu)
3163 if (vcpu->mmio_read_completed) {
3164 memcpy(val, vcpu->mmio_data, bytes);
3165 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
3166 vcpu->mmio_phys_addr, *(u64 *)val);
3167 vcpu->mmio_read_completed = 0;
3168 return X86EMUL_CONTINUE;
3171 gpa = kvm_mmu_gva_to_gpa_read(vcpu, addr, &error_code);
3173 if (gpa == UNMAPPED_GVA) {
3174 kvm_inject_page_fault(vcpu, addr, error_code);
3175 return X86EMUL_PROPAGATE_FAULT;
3178 /* For APIC access vmexit */
3179 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3182 if (kvm_read_guest_virt(addr, val, bytes, vcpu, NULL)
3183 == X86EMUL_CONTINUE)
3184 return X86EMUL_CONTINUE;
3188 * Is this MMIO handled locally?
3190 if (!vcpu_mmio_read(vcpu, gpa, bytes, val)) {
3191 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes, gpa, *(u64 *)val);
3192 return X86EMUL_CONTINUE;
3195 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
3197 vcpu->mmio_needed = 1;
3198 vcpu->mmio_phys_addr = gpa;
3199 vcpu->mmio_size = bytes;
3200 vcpu->mmio_is_write = 0;
3202 return X86EMUL_UNHANDLEABLE;
3205 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
3206 const void *val, int bytes)
3210 ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
3213 kvm_mmu_pte_write(vcpu, gpa, val, bytes, 1);
3217 static int emulator_write_emulated_onepage(unsigned long addr,
3220 struct kvm_vcpu *vcpu)
3225 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, &error_code);
3227 if (gpa == UNMAPPED_GVA) {
3228 kvm_inject_page_fault(vcpu, addr, error_code);
3229 return X86EMUL_PROPAGATE_FAULT;
3232 /* For APIC access vmexit */
3233 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3236 if (emulator_write_phys(vcpu, gpa, val, bytes))
3237 return X86EMUL_CONTINUE;
3240 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
3242 * Is this MMIO handled locally?
3244 if (!vcpu_mmio_write(vcpu, gpa, bytes, val))
3245 return X86EMUL_CONTINUE;
3247 vcpu->mmio_needed = 1;
3248 vcpu->mmio_phys_addr = gpa;
3249 vcpu->mmio_size = bytes;
3250 vcpu->mmio_is_write = 1;
3251 memcpy(vcpu->mmio_data, val, bytes);
3253 return X86EMUL_CONTINUE;
3256 int emulator_write_emulated(unsigned long addr,
3259 struct kvm_vcpu *vcpu)
3261 /* Crossing a page boundary? */
3262 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
3265 now = -addr & ~PAGE_MASK;
3266 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
3267 if (rc != X86EMUL_CONTINUE)
3273 return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
3275 EXPORT_SYMBOL_GPL(emulator_write_emulated);
3277 static int emulator_cmpxchg_emulated(unsigned long addr,
3281 struct kvm_vcpu *vcpu)
3283 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
3284 #ifndef CONFIG_X86_64
3285 /* guests cmpxchg8b have to be emulated atomically */
3292 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
3294 if (gpa == UNMAPPED_GVA ||
3295 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3298 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
3303 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
3305 kaddr = kmap_atomic(page, KM_USER0);
3306 set_64bit((u64 *)(kaddr + offset_in_page(gpa)), val);
3307 kunmap_atomic(kaddr, KM_USER0);
3308 kvm_release_page_dirty(page);
3313 return emulator_write_emulated(addr, new, bytes, vcpu);
3316 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
3318 return kvm_x86_ops->get_segment_base(vcpu, seg);
3321 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
3323 kvm_mmu_invlpg(vcpu, address);
3324 return X86EMUL_CONTINUE;
3327 int emulate_clts(struct kvm_vcpu *vcpu)
3329 kvm_x86_ops->set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
3330 kvm_x86_ops->fpu_activate(vcpu);
3331 return X86EMUL_CONTINUE;
3334 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
3336 return kvm_x86_ops->get_dr(ctxt->vcpu, dr, dest);
3339 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
3341 unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
3343 return kvm_x86_ops->set_dr(ctxt->vcpu, dr, value & mask);
3346 void kvm_report_emulation_failure(struct kvm_vcpu *vcpu, const char *context)
3349 unsigned long rip = kvm_rip_read(vcpu);
3350 unsigned long rip_linear;
3352 if (!printk_ratelimit())
3355 rip_linear = rip + get_segment_base(vcpu, VCPU_SREG_CS);
3357 kvm_read_guest_virt(rip_linear, (void *)opcodes, 4, vcpu, NULL);
3359 printk(KERN_ERR "emulation failed (%s) rip %lx %02x %02x %02x %02x\n",
3360 context, rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
3362 EXPORT_SYMBOL_GPL(kvm_report_emulation_failure);
3364 static struct x86_emulate_ops emulate_ops = {
3365 .read_std = kvm_read_guest_virt_system,
3366 .fetch = kvm_fetch_guest_virt,
3367 .read_emulated = emulator_read_emulated,
3368 .write_emulated = emulator_write_emulated,
3369 .cmpxchg_emulated = emulator_cmpxchg_emulated,
3372 static void cache_all_regs(struct kvm_vcpu *vcpu)
3374 kvm_register_read(vcpu, VCPU_REGS_RAX);
3375 kvm_register_read(vcpu, VCPU_REGS_RSP);
3376 kvm_register_read(vcpu, VCPU_REGS_RIP);
3377 vcpu->arch.regs_dirty = ~0;
3380 int emulate_instruction(struct kvm_vcpu *vcpu,
3386 struct decode_cache *c;
3387 struct kvm_run *run = vcpu->run;
3389 kvm_clear_exception_queue(vcpu);
3390 vcpu->arch.mmio_fault_cr2 = cr2;
3392 * TODO: fix emulate.c to use guest_read/write_register
3393 * instead of direct ->regs accesses, can save hundred cycles
3394 * on Intel for instructions that don't read/change RSP, for
3397 cache_all_regs(vcpu);
3399 vcpu->mmio_is_write = 0;
3400 vcpu->arch.pio.string = 0;
3402 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
3404 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
3406 vcpu->arch.emulate_ctxt.vcpu = vcpu;
3407 vcpu->arch.emulate_ctxt.eflags = kvm_get_rflags(vcpu);
3408 vcpu->arch.emulate_ctxt.mode =
3409 (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
3410 (vcpu->arch.emulate_ctxt.eflags & X86_EFLAGS_VM)
3411 ? X86EMUL_MODE_VM86 : cs_l
3412 ? X86EMUL_MODE_PROT64 : cs_db
3413 ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
3415 r = x86_decode_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
3417 /* Only allow emulation of specific instructions on #UD
3418 * (namely VMMCALL, sysenter, sysexit, syscall)*/
3419 c = &vcpu->arch.emulate_ctxt.decode;
3420 if (emulation_type & EMULTYPE_TRAP_UD) {
3422 return EMULATE_FAIL;
3424 case 0x01: /* VMMCALL */
3425 if (c->modrm_mod != 3 || c->modrm_rm != 1)
3426 return EMULATE_FAIL;
3428 case 0x34: /* sysenter */
3429 case 0x35: /* sysexit */
3430 if (c->modrm_mod != 0 || c->modrm_rm != 0)
3431 return EMULATE_FAIL;
3433 case 0x05: /* syscall */
3434 if (c->modrm_mod != 0 || c->modrm_rm != 0)
3435 return EMULATE_FAIL;
3438 return EMULATE_FAIL;
3441 if (!(c->modrm_reg == 0 || c->modrm_reg == 3))
3442 return EMULATE_FAIL;
3445 ++vcpu->stat.insn_emulation;
3447 ++vcpu->stat.insn_emulation_fail;
3448 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
3449 return EMULATE_DONE;
3450 return EMULATE_FAIL;
3454 if (emulation_type & EMULTYPE_SKIP) {
3455 kvm_rip_write(vcpu, vcpu->arch.emulate_ctxt.decode.eip);
3456 return EMULATE_DONE;
3459 r = x86_emulate_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
3460 shadow_mask = vcpu->arch.emulate_ctxt.interruptibility;
3463 kvm_x86_ops->set_interrupt_shadow(vcpu, shadow_mask);
3465 if (vcpu->arch.pio.string)
3466 return EMULATE_DO_MMIO;
3468 if ((r || vcpu->mmio_is_write) && run) {
3469 run->exit_reason = KVM_EXIT_MMIO;
3470 run->mmio.phys_addr = vcpu->mmio_phys_addr;
3471 memcpy(run->mmio.data, vcpu->mmio_data, 8);
3472 run->mmio.len = vcpu->mmio_size;
3473 run->mmio.is_write = vcpu->mmio_is_write;
3477 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
3478 return EMULATE_DONE;
3479 if (!vcpu->mmio_needed) {
3480 kvm_report_emulation_failure(vcpu, "mmio");
3481 return EMULATE_FAIL;
3483 return EMULATE_DO_MMIO;
3486 kvm_set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
3488 if (vcpu->mmio_is_write) {
3489 vcpu->mmio_needed = 0;
3490 return EMULATE_DO_MMIO;
3493 return EMULATE_DONE;
3495 EXPORT_SYMBOL_GPL(emulate_instruction);
3497 static int pio_copy_data(struct kvm_vcpu *vcpu)
3499 void *p = vcpu->arch.pio_data;
3500 gva_t q = vcpu->arch.pio.guest_gva;
3505 bytes = vcpu->arch.pio.size * vcpu->arch.pio.cur_count;
3506 if (vcpu->arch.pio.in)
3507 ret = kvm_write_guest_virt(q, p, bytes, vcpu, &error_code);
3509 ret = kvm_read_guest_virt(q, p, bytes, vcpu, &error_code);
3511 if (ret == X86EMUL_PROPAGATE_FAULT)
3512 kvm_inject_page_fault(vcpu, q, error_code);
3517 int complete_pio(struct kvm_vcpu *vcpu)
3519 struct kvm_pio_request *io = &vcpu->arch.pio;
3526 val = kvm_register_read(vcpu, VCPU_REGS_RAX);
3527 memcpy(&val, vcpu->arch.pio_data, io->size);
3528 kvm_register_write(vcpu, VCPU_REGS_RAX, val);
3532 r = pio_copy_data(vcpu);
3539 delta *= io->cur_count;
3541 * The size of the register should really depend on
3542 * current address size.
3544 val = kvm_register_read(vcpu, VCPU_REGS_RCX);
3546 kvm_register_write(vcpu, VCPU_REGS_RCX, val);
3552 val = kvm_register_read(vcpu, VCPU_REGS_RDI);
3554 kvm_register_write(vcpu, VCPU_REGS_RDI, val);
3556 val = kvm_register_read(vcpu, VCPU_REGS_RSI);
3558 kvm_register_write(vcpu, VCPU_REGS_RSI, val);
3562 io->count -= io->cur_count;
3568 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
3570 /* TODO: String I/O for in kernel device */
3573 if (vcpu->arch.pio.in)
3574 r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
3575 vcpu->arch.pio.size, pd);
3577 r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
3578 vcpu->arch.pio.port, vcpu->arch.pio.size,
3583 static int pio_string_write(struct kvm_vcpu *vcpu)
3585 struct kvm_pio_request *io = &vcpu->arch.pio;
3586 void *pd = vcpu->arch.pio_data;
3589 for (i = 0; i < io->cur_count; i++) {
3590 if (kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
3591 io->port, io->size, pd)) {
3600 int kvm_emulate_pio(struct kvm_vcpu *vcpu, int in, int size, unsigned port)
3604 trace_kvm_pio(!in, port, size, 1);
3606 vcpu->run->exit_reason = KVM_EXIT_IO;
3607 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
3608 vcpu->run->io.size = vcpu->arch.pio.size = size;
3609 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
3610 vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = 1;
3611 vcpu->run->io.port = vcpu->arch.pio.port = port;
3612 vcpu->arch.pio.in = in;
3613 vcpu->arch.pio.string = 0;
3614 vcpu->arch.pio.down = 0;
3615 vcpu->arch.pio.rep = 0;
3617 if (!vcpu->arch.pio.in) {
3618 val = kvm_register_read(vcpu, VCPU_REGS_RAX);
3619 memcpy(vcpu->arch.pio_data, &val, 4);
3622 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
3628 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
3630 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, int in,
3631 int size, unsigned long count, int down,
3632 gva_t address, int rep, unsigned port)
3634 unsigned now, in_page;
3637 trace_kvm_pio(!in, port, size, count);
3639 vcpu->run->exit_reason = KVM_EXIT_IO;
3640 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
3641 vcpu->run->io.size = vcpu->arch.pio.size = size;
3642 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
3643 vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = count;
3644 vcpu->run->io.port = vcpu->arch.pio.port = port;
3645 vcpu->arch.pio.in = in;
3646 vcpu->arch.pio.string = 1;
3647 vcpu->arch.pio.down = down;
3648 vcpu->arch.pio.rep = rep;
3651 kvm_x86_ops->skip_emulated_instruction(vcpu);
3656 in_page = PAGE_SIZE - offset_in_page(address);
3658 in_page = offset_in_page(address) + size;
3659 now = min(count, (unsigned long)in_page / size);
3664 * String I/O in reverse. Yuck. Kill the guest, fix later.
3666 pr_unimpl(vcpu, "guest string pio down\n");
3667 kvm_inject_gp(vcpu, 0);
3670 vcpu->run->io.count = now;
3671 vcpu->arch.pio.cur_count = now;
3673 if (vcpu->arch.pio.cur_count == vcpu->arch.pio.count)
3674 kvm_x86_ops->skip_emulated_instruction(vcpu);
3676 vcpu->arch.pio.guest_gva = address;
3678 if (!vcpu->arch.pio.in) {
3679 /* string PIO write */
3680 ret = pio_copy_data(vcpu);
3681 if (ret == X86EMUL_PROPAGATE_FAULT)
3683 if (ret == 0 && !pio_string_write(vcpu)) {
3685 if (vcpu->arch.pio.count == 0)
3689 /* no string PIO read support yet */
3693 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
3695 static void bounce_off(void *info)
3700 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
3703 struct cpufreq_freqs *freq = data;
3705 struct kvm_vcpu *vcpu;
3706 int i, send_ipi = 0;
3708 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
3710 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
3712 per_cpu(cpu_tsc_khz, freq->cpu) = freq->new;
3714 spin_lock(&kvm_lock);
3715 list_for_each_entry(kvm, &vm_list, vm_list) {
3716 kvm_for_each_vcpu(i, vcpu, kvm) {
3717 if (vcpu->cpu != freq->cpu)
3719 if (!kvm_request_guest_time_update(vcpu))
3721 if (vcpu->cpu != smp_processor_id())
3725 spin_unlock(&kvm_lock);
3727 if (freq->old < freq->new && send_ipi) {
3729 * We upscale the frequency. Must make the guest
3730 * doesn't see old kvmclock values while running with
3731 * the new frequency, otherwise we risk the guest sees
3732 * time go backwards.
3734 * In case we update the frequency for another cpu
3735 * (which might be in guest context) send an interrupt
3736 * to kick the cpu out of guest context. Next time
3737 * guest context is entered kvmclock will be updated,
3738 * so the guest will not see stale values.
3740 smp_call_function_single(freq->cpu, bounce_off, NULL, 1);
3745 static struct notifier_block kvmclock_cpufreq_notifier_block = {
3746 .notifier_call = kvmclock_cpufreq_notifier
3749 static void kvm_timer_init(void)
3753 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
3754 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
3755 CPUFREQ_TRANSITION_NOTIFIER);
3756 for_each_online_cpu(cpu) {
3757 unsigned long khz = cpufreq_get(cpu);
3760 per_cpu(cpu_tsc_khz, cpu) = khz;
3763 for_each_possible_cpu(cpu)
3764 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
3768 int kvm_arch_init(void *opaque)
3771 struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
3774 printk(KERN_ERR "kvm: already loaded the other module\n");
3779 if (!ops->cpu_has_kvm_support()) {
3780 printk(KERN_ERR "kvm: no hardware support\n");
3784 if (ops->disabled_by_bios()) {
3785 printk(KERN_ERR "kvm: disabled by bios\n");
3790 r = kvm_mmu_module_init();
3794 kvm_init_msr_list();
3797 kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
3798 kvm_mmu_set_base_ptes(PT_PRESENT_MASK);
3799 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
3800 PT_DIRTY_MASK, PT64_NX_MASK, 0);
3810 void kvm_arch_exit(void)
3812 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
3813 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
3814 CPUFREQ_TRANSITION_NOTIFIER);
3816 kvm_mmu_module_exit();
3819 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
3821 ++vcpu->stat.halt_exits;
3822 if (irqchip_in_kernel(vcpu->kvm)) {
3823 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
3826 vcpu->run->exit_reason = KVM_EXIT_HLT;
3830 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
3832 static inline gpa_t hc_gpa(struct kvm_vcpu *vcpu, unsigned long a0,
3835 if (is_long_mode(vcpu))
3838 return a0 | ((gpa_t)a1 << 32);
3841 int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
3843 u64 param, ingpa, outgpa, ret;
3844 uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
3845 bool fast, longmode;
3849 * hypercall generates UD from non zero cpl and real mode
3852 if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
3853 kvm_queue_exception(vcpu, UD_VECTOR);
3857 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
3858 longmode = is_long_mode(vcpu) && cs_l == 1;
3861 param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
3862 (kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
3863 ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
3864 (kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
3865 outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
3866 (kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
3868 #ifdef CONFIG_X86_64
3870 param = kvm_register_read(vcpu, VCPU_REGS_RCX);
3871 ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
3872 outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
3876 code = param & 0xffff;
3877 fast = (param >> 16) & 0x1;
3878 rep_cnt = (param >> 32) & 0xfff;
3879 rep_idx = (param >> 48) & 0xfff;
3881 trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
3884 case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
3885 kvm_vcpu_on_spin(vcpu);
3888 res = HV_STATUS_INVALID_HYPERCALL_CODE;
3892 ret = res | (((u64)rep_done & 0xfff) << 32);
3894 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
3896 kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
3897 kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
3903 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
3905 unsigned long nr, a0, a1, a2, a3, ret;
3908 if (kvm_hv_hypercall_enabled(vcpu->kvm))
3909 return kvm_hv_hypercall(vcpu);
3911 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
3912 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
3913 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
3914 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
3915 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
3917 trace_kvm_hypercall(nr, a0, a1, a2, a3);
3919 if (!is_long_mode(vcpu)) {
3927 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
3933 case KVM_HC_VAPIC_POLL_IRQ:
3937 r = kvm_pv_mmu_op(vcpu, a0, hc_gpa(vcpu, a1, a2), &ret);
3944 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
3945 ++vcpu->stat.hypercalls;
3948 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
3950 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
3952 char instruction[3];
3953 unsigned long rip = kvm_rip_read(vcpu);
3956 * Blow out the MMU to ensure that no other VCPU has an active mapping
3957 * to ensure that the updated hypercall appears atomically across all
3960 kvm_mmu_zap_all(vcpu->kvm);
3962 kvm_x86_ops->patch_hypercall(vcpu, instruction);
3964 return emulator_write_emulated(rip, instruction, 3, vcpu);
3967 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
3969 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
3972 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
3974 struct descriptor_table dt = { limit, base };
3976 kvm_x86_ops->set_gdt(vcpu, &dt);
3979 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
3981 struct descriptor_table dt = { limit, base };
3983 kvm_x86_ops->set_idt(vcpu, &dt);
3986 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
3987 unsigned long *rflags)
3989 kvm_lmsw(vcpu, msw);
3990 *rflags = kvm_get_rflags(vcpu);
3993 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
3995 unsigned long value;
3999 value = kvm_read_cr0(vcpu);
4002 value = vcpu->arch.cr2;
4005 value = vcpu->arch.cr3;
4008 value = kvm_read_cr4(vcpu);
4011 value = kvm_get_cr8(vcpu);
4014 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
4021 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
4022 unsigned long *rflags)
4026 kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4027 *rflags = kvm_get_rflags(vcpu);
4030 vcpu->arch.cr2 = val;
4033 kvm_set_cr3(vcpu, val);
4036 kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4039 kvm_set_cr8(vcpu, val & 0xfUL);
4042 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
4046 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
4048 struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
4049 int j, nent = vcpu->arch.cpuid_nent;
4051 e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
4052 /* when no next entry is found, the current entry[i] is reselected */
4053 for (j = i + 1; ; j = (j + 1) % nent) {
4054 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
4055 if (ej->function == e->function) {
4056 ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
4060 return 0; /* silence gcc, even though control never reaches here */
4063 /* find an entry with matching function, matching index (if needed), and that
4064 * should be read next (if it's stateful) */
4065 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
4066 u32 function, u32 index)
4068 if (e->function != function)
4070 if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
4072 if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
4073 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
4078 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry(struct kvm_vcpu *vcpu,
4079 u32 function, u32 index)
4082 struct kvm_cpuid_entry2 *best = NULL;
4084 for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
4085 struct kvm_cpuid_entry2 *e;
4087 e = &vcpu->arch.cpuid_entries[i];
4088 if (is_matching_cpuid_entry(e, function, index)) {
4089 if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
4090 move_to_next_stateful_cpuid_entry(vcpu, i);
4095 * Both basic or both extended?
4097 if (((e->function ^ function) & 0x80000000) == 0)
4098 if (!best || e->function > best->function)
4103 EXPORT_SYMBOL_GPL(kvm_find_cpuid_entry);
4105 int cpuid_maxphyaddr(struct kvm_vcpu *vcpu)
4107 struct kvm_cpuid_entry2 *best;
4109 best = kvm_find_cpuid_entry(vcpu, 0x80000008, 0);
4111 return best->eax & 0xff;
4115 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
4117 u32 function, index;
4118 struct kvm_cpuid_entry2 *best;
4120 function = kvm_register_read(vcpu, VCPU_REGS_RAX);
4121 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
4122 kvm_register_write(vcpu, VCPU_REGS_RAX, 0);
4123 kvm_register_write(vcpu, VCPU_REGS_RBX, 0);
4124 kvm_register_write(vcpu, VCPU_REGS_RCX, 0);
4125 kvm_register_write(vcpu, VCPU_REGS_RDX, 0);
4126 best = kvm_find_cpuid_entry(vcpu, function, index);
4128 kvm_register_write(vcpu, VCPU_REGS_RAX, best->eax);
4129 kvm_register_write(vcpu, VCPU_REGS_RBX, best->ebx);
4130 kvm_register_write(vcpu, VCPU_REGS_RCX, best->ecx);
4131 kvm_register_write(vcpu, VCPU_REGS_RDX, best->edx);
4133 kvm_x86_ops->skip_emulated_instruction(vcpu);
4134 trace_kvm_cpuid(function,
4135 kvm_register_read(vcpu, VCPU_REGS_RAX),
4136 kvm_register_read(vcpu, VCPU_REGS_RBX),
4137 kvm_register_read(vcpu, VCPU_REGS_RCX),
4138 kvm_register_read(vcpu, VCPU_REGS_RDX));
4140 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
4143 * Check if userspace requested an interrupt window, and that the
4144 * interrupt window is open.
4146 * No need to exit to userspace if we already have an interrupt queued.
4148 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
4150 return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
4151 vcpu->run->request_interrupt_window &&
4152 kvm_arch_interrupt_allowed(vcpu));
4155 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
4157 struct kvm_run *kvm_run = vcpu->run;
4159 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
4160 kvm_run->cr8 = kvm_get_cr8(vcpu);
4161 kvm_run->apic_base = kvm_get_apic_base(vcpu);
4162 if (irqchip_in_kernel(vcpu->kvm))
4163 kvm_run->ready_for_interrupt_injection = 1;
4165 kvm_run->ready_for_interrupt_injection =
4166 kvm_arch_interrupt_allowed(vcpu) &&
4167 !kvm_cpu_has_interrupt(vcpu) &&
4168 !kvm_event_needs_reinjection(vcpu);
4171 static void vapic_enter(struct kvm_vcpu *vcpu)
4173 struct kvm_lapic *apic = vcpu->arch.apic;
4176 if (!apic || !apic->vapic_addr)
4179 page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
4181 vcpu->arch.apic->vapic_page = page;
4184 static void vapic_exit(struct kvm_vcpu *vcpu)
4186 struct kvm_lapic *apic = vcpu->arch.apic;
4189 if (!apic || !apic->vapic_addr)
4192 idx = srcu_read_lock(&vcpu->kvm->srcu);
4193 kvm_release_page_dirty(apic->vapic_page);
4194 mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
4195 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4198 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
4202 if (!kvm_x86_ops->update_cr8_intercept)
4205 if (!vcpu->arch.apic)
4208 if (!vcpu->arch.apic->vapic_addr)
4209 max_irr = kvm_lapic_find_highest_irr(vcpu);
4216 tpr = kvm_lapic_get_cr8(vcpu);
4218 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
4221 static void inject_pending_event(struct kvm_vcpu *vcpu)
4223 /* try to reinject previous events if any */
4224 if (vcpu->arch.exception.pending) {
4225 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
4226 vcpu->arch.exception.has_error_code,
4227 vcpu->arch.exception.error_code);
4231 if (vcpu->arch.nmi_injected) {
4232 kvm_x86_ops->set_nmi(vcpu);
4236 if (vcpu->arch.interrupt.pending) {
4237 kvm_x86_ops->set_irq(vcpu);
4241 /* try to inject new event if pending */
4242 if (vcpu->arch.nmi_pending) {
4243 if (kvm_x86_ops->nmi_allowed(vcpu)) {
4244 vcpu->arch.nmi_pending = false;
4245 vcpu->arch.nmi_injected = true;
4246 kvm_x86_ops->set_nmi(vcpu);
4248 } else if (kvm_cpu_has_interrupt(vcpu)) {
4249 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
4250 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
4252 kvm_x86_ops->set_irq(vcpu);
4257 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
4260 bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
4261 vcpu->run->request_interrupt_window;
4264 if (test_and_clear_bit(KVM_REQ_MMU_RELOAD, &vcpu->requests))
4265 kvm_mmu_unload(vcpu);
4267 r = kvm_mmu_reload(vcpu);
4271 if (vcpu->requests) {
4272 if (test_and_clear_bit(KVM_REQ_MIGRATE_TIMER, &vcpu->requests))
4273 __kvm_migrate_timers(vcpu);
4274 if (test_and_clear_bit(KVM_REQ_KVMCLOCK_UPDATE, &vcpu->requests))
4275 kvm_write_guest_time(vcpu);
4276 if (test_and_clear_bit(KVM_REQ_MMU_SYNC, &vcpu->requests))
4277 kvm_mmu_sync_roots(vcpu);
4278 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
4279 kvm_x86_ops->tlb_flush(vcpu);
4280 if (test_and_clear_bit(KVM_REQ_REPORT_TPR_ACCESS,
4282 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
4286 if (test_and_clear_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests)) {
4287 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4291 if (test_and_clear_bit(KVM_REQ_DEACTIVATE_FPU, &vcpu->requests)) {
4292 vcpu->fpu_active = 0;
4293 kvm_x86_ops->fpu_deactivate(vcpu);
4299 kvm_x86_ops->prepare_guest_switch(vcpu);
4300 if (vcpu->fpu_active)
4301 kvm_load_guest_fpu(vcpu);
4303 local_irq_disable();
4305 clear_bit(KVM_REQ_KICK, &vcpu->requests);
4306 smp_mb__after_clear_bit();
4308 if (vcpu->requests || need_resched() || signal_pending(current)) {
4309 set_bit(KVM_REQ_KICK, &vcpu->requests);
4316 inject_pending_event(vcpu);
4318 /* enable NMI/IRQ window open exits if needed */
4319 if (vcpu->arch.nmi_pending)
4320 kvm_x86_ops->enable_nmi_window(vcpu);
4321 else if (kvm_cpu_has_interrupt(vcpu) || req_int_win)
4322 kvm_x86_ops->enable_irq_window(vcpu);
4324 if (kvm_lapic_enabled(vcpu)) {
4325 update_cr8_intercept(vcpu);
4326 kvm_lapic_sync_to_vapic(vcpu);
4329 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
4333 if (unlikely(vcpu->arch.switch_db_regs)) {
4335 set_debugreg(vcpu->arch.eff_db[0], 0);
4336 set_debugreg(vcpu->arch.eff_db[1], 1);
4337 set_debugreg(vcpu->arch.eff_db[2], 2);
4338 set_debugreg(vcpu->arch.eff_db[3], 3);
4341 trace_kvm_entry(vcpu->vcpu_id);
4342 kvm_x86_ops->run(vcpu);
4345 * If the guest has used debug registers, at least dr7
4346 * will be disabled while returning to the host.
4347 * If we don't have active breakpoints in the host, we don't
4348 * care about the messed up debug address registers. But if
4349 * we have some of them active, restore the old state.
4351 if (hw_breakpoint_active())
4352 hw_breakpoint_restore();
4354 set_bit(KVM_REQ_KICK, &vcpu->requests);
4360 * We must have an instruction between local_irq_enable() and
4361 * kvm_guest_exit(), so the timer interrupt isn't delayed by
4362 * the interrupt shadow. The stat.exits increment will do nicely.
4363 * But we need to prevent reordering, hence this barrier():
4371 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
4374 * Profile KVM exit RIPs:
4376 if (unlikely(prof_on == KVM_PROFILING)) {
4377 unsigned long rip = kvm_rip_read(vcpu);
4378 profile_hit(KVM_PROFILING, (void *)rip);
4382 kvm_lapic_sync_from_vapic(vcpu);
4384 r = kvm_x86_ops->handle_exit(vcpu);
4390 static int __vcpu_run(struct kvm_vcpu *vcpu)
4393 struct kvm *kvm = vcpu->kvm;
4395 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
4396 pr_debug("vcpu %d received sipi with vector # %x\n",
4397 vcpu->vcpu_id, vcpu->arch.sipi_vector);
4398 kvm_lapic_reset(vcpu);
4399 r = kvm_arch_vcpu_reset(vcpu);
4402 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
4405 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
4410 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE)
4411 r = vcpu_enter_guest(vcpu);
4413 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
4414 kvm_vcpu_block(vcpu);
4415 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
4416 if (test_and_clear_bit(KVM_REQ_UNHALT, &vcpu->requests))
4418 switch(vcpu->arch.mp_state) {
4419 case KVM_MP_STATE_HALTED:
4420 vcpu->arch.mp_state =
4421 KVM_MP_STATE_RUNNABLE;
4422 case KVM_MP_STATE_RUNNABLE:
4424 case KVM_MP_STATE_SIPI_RECEIVED:
4435 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
4436 if (kvm_cpu_has_pending_timer(vcpu))
4437 kvm_inject_pending_timer_irqs(vcpu);
4439 if (dm_request_for_irq_injection(vcpu)) {
4441 vcpu->run->exit_reason = KVM_EXIT_INTR;
4442 ++vcpu->stat.request_irq_exits;
4444 if (signal_pending(current)) {
4446 vcpu->run->exit_reason = KVM_EXIT_INTR;
4447 ++vcpu->stat.signal_exits;
4449 if (need_resched()) {
4450 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
4452 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
4456 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
4457 post_kvm_run_save(vcpu);
4464 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
4471 if (vcpu->sigset_active)
4472 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
4474 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
4475 kvm_vcpu_block(vcpu);
4476 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
4481 /* re-sync apic's tpr */
4482 if (!irqchip_in_kernel(vcpu->kvm))
4483 kvm_set_cr8(vcpu, kvm_run->cr8);
4485 if (vcpu->arch.pio.cur_count) {
4486 r = complete_pio(vcpu);
4490 if (vcpu->mmio_needed) {
4491 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
4492 vcpu->mmio_read_completed = 1;
4493 vcpu->mmio_needed = 0;
4495 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
4496 r = emulate_instruction(vcpu, vcpu->arch.mmio_fault_cr2, 0,
4497 EMULTYPE_NO_DECODE);
4498 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
4499 if (r == EMULATE_DO_MMIO) {
4501 * Read-modify-write. Back to userspace.
4507 if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL)
4508 kvm_register_write(vcpu, VCPU_REGS_RAX,
4509 kvm_run->hypercall.ret);
4511 r = __vcpu_run(vcpu);
4514 if (vcpu->sigset_active)
4515 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
4521 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
4525 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
4526 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
4527 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
4528 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
4529 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
4530 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
4531 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
4532 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
4533 #ifdef CONFIG_X86_64
4534 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
4535 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
4536 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
4537 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
4538 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
4539 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
4540 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
4541 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
4544 regs->rip = kvm_rip_read(vcpu);
4545 regs->rflags = kvm_get_rflags(vcpu);
4552 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
4556 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
4557 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
4558 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
4559 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
4560 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
4561 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
4562 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
4563 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
4564 #ifdef CONFIG_X86_64
4565 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
4566 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
4567 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
4568 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
4569 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
4570 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
4571 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
4572 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
4575 kvm_rip_write(vcpu, regs->rip);
4576 kvm_set_rflags(vcpu, regs->rflags);
4578 vcpu->arch.exception.pending = false;
4585 void kvm_get_segment(struct kvm_vcpu *vcpu,
4586 struct kvm_segment *var, int seg)
4588 kvm_x86_ops->get_segment(vcpu, var, seg);
4591 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
4593 struct kvm_segment cs;
4595 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
4599 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
4601 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
4602 struct kvm_sregs *sregs)
4604 struct descriptor_table dt;
4608 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
4609 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
4610 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
4611 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
4612 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
4613 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
4615 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
4616 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
4618 kvm_x86_ops->get_idt(vcpu, &dt);
4619 sregs->idt.limit = dt.limit;
4620 sregs->idt.base = dt.base;
4621 kvm_x86_ops->get_gdt(vcpu, &dt);
4622 sregs->gdt.limit = dt.limit;
4623 sregs->gdt.base = dt.base;
4625 sregs->cr0 = kvm_read_cr0(vcpu);
4626 sregs->cr2 = vcpu->arch.cr2;
4627 sregs->cr3 = vcpu->arch.cr3;
4628 sregs->cr4 = kvm_read_cr4(vcpu);
4629 sregs->cr8 = kvm_get_cr8(vcpu);
4630 sregs->efer = vcpu->arch.efer;
4631 sregs->apic_base = kvm_get_apic_base(vcpu);
4633 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
4635 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
4636 set_bit(vcpu->arch.interrupt.nr,
4637 (unsigned long *)sregs->interrupt_bitmap);
4644 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
4645 struct kvm_mp_state *mp_state)
4648 mp_state->mp_state = vcpu->arch.mp_state;
4653 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
4654 struct kvm_mp_state *mp_state)
4657 vcpu->arch.mp_state = mp_state->mp_state;
4662 static void kvm_set_segment(struct kvm_vcpu *vcpu,
4663 struct kvm_segment *var, int seg)
4665 kvm_x86_ops->set_segment(vcpu, var, seg);
4668 static void seg_desct_to_kvm_desct(struct desc_struct *seg_desc, u16 selector,
4669 struct kvm_segment *kvm_desct)
4671 kvm_desct->base = get_desc_base(seg_desc);
4672 kvm_desct->limit = get_desc_limit(seg_desc);
4674 kvm_desct->limit <<= 12;
4675 kvm_desct->limit |= 0xfff;
4677 kvm_desct->selector = selector;
4678 kvm_desct->type = seg_desc->type;
4679 kvm_desct->present = seg_desc->p;
4680 kvm_desct->dpl = seg_desc->dpl;
4681 kvm_desct->db = seg_desc->d;
4682 kvm_desct->s = seg_desc->s;
4683 kvm_desct->l = seg_desc->l;
4684 kvm_desct->g = seg_desc->g;
4685 kvm_desct->avl = seg_desc->avl;
4687 kvm_desct->unusable = 1;
4689 kvm_desct->unusable = 0;
4690 kvm_desct->padding = 0;
4693 static void get_segment_descriptor_dtable(struct kvm_vcpu *vcpu,
4695 struct descriptor_table *dtable)
4697 if (selector & 1 << 2) {
4698 struct kvm_segment kvm_seg;
4700 kvm_get_segment(vcpu, &kvm_seg, VCPU_SREG_LDTR);
4702 if (kvm_seg.unusable)
4705 dtable->limit = kvm_seg.limit;
4706 dtable->base = kvm_seg.base;
4709 kvm_x86_ops->get_gdt(vcpu, dtable);
4712 /* allowed just for 8 bytes segments */
4713 static int load_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
4714 struct desc_struct *seg_desc)
4716 struct descriptor_table dtable;
4717 u16 index = selector >> 3;
4722 get_segment_descriptor_dtable(vcpu, selector, &dtable);
4724 if (dtable.limit < index * 8 + 7) {
4725 kvm_queue_exception_e(vcpu, GP_VECTOR, selector & 0xfffc);
4726 return X86EMUL_PROPAGATE_FAULT;
4728 addr = dtable.base + index * 8;
4729 ret = kvm_read_guest_virt_system(addr, seg_desc, sizeof(*seg_desc),
4731 if (ret == X86EMUL_PROPAGATE_FAULT)
4732 kvm_inject_page_fault(vcpu, addr, err);
4737 /* allowed just for 8 bytes segments */
4738 static int save_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
4739 struct desc_struct *seg_desc)
4741 struct descriptor_table dtable;
4742 u16 index = selector >> 3;
4744 get_segment_descriptor_dtable(vcpu, selector, &dtable);
4746 if (dtable.limit < index * 8 + 7)
4748 return kvm_write_guest_virt(dtable.base + index*8, seg_desc, sizeof(*seg_desc), vcpu, NULL);
4751 static gpa_t get_tss_base_addr_write(struct kvm_vcpu *vcpu,
4752 struct desc_struct *seg_desc)
4754 u32 base_addr = get_desc_base(seg_desc);
4756 return kvm_mmu_gva_to_gpa_write(vcpu, base_addr, NULL);
4759 static gpa_t get_tss_base_addr_read(struct kvm_vcpu *vcpu,
4760 struct desc_struct *seg_desc)
4762 u32 base_addr = get_desc_base(seg_desc);
4764 return kvm_mmu_gva_to_gpa_read(vcpu, base_addr, NULL);
4767 static u16 get_segment_selector(struct kvm_vcpu *vcpu, int seg)
4769 struct kvm_segment kvm_seg;
4771 kvm_get_segment(vcpu, &kvm_seg, seg);
4772 return kvm_seg.selector;
4775 static int kvm_load_realmode_segment(struct kvm_vcpu *vcpu, u16 selector, int seg)
4777 struct kvm_segment segvar = {
4778 .base = selector << 4,
4780 .selector = selector,
4791 kvm_x86_ops->set_segment(vcpu, &segvar, seg);
4792 return X86EMUL_CONTINUE;
4795 static int is_vm86_segment(struct kvm_vcpu *vcpu, int seg)
4797 return (seg != VCPU_SREG_LDTR) &&
4798 (seg != VCPU_SREG_TR) &&
4799 (kvm_get_rflags(vcpu) & X86_EFLAGS_VM);
4802 int kvm_load_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector, int seg)
4804 struct kvm_segment kvm_seg;
4805 struct desc_struct seg_desc;
4807 unsigned err_vec = GP_VECTOR;
4809 bool null_selector = !(selector & ~0x3); /* 0000-0003 are null */
4812 if (is_vm86_segment(vcpu, seg) || !is_protmode(vcpu))
4813 return kvm_load_realmode_segment(vcpu, selector, seg);
4815 /* NULL selector is not valid for TR, CS and SS */
4816 if ((seg == VCPU_SREG_CS || seg == VCPU_SREG_SS || seg == VCPU_SREG_TR)
4820 /* TR should be in GDT only */
4821 if (seg == VCPU_SREG_TR && (selector & (1 << 2)))
4824 ret = load_guest_segment_descriptor(vcpu, selector, &seg_desc);
4828 seg_desct_to_kvm_desct(&seg_desc, selector, &kvm_seg);
4830 if (null_selector) { /* for NULL selector skip all following checks */
4831 kvm_seg.unusable = 1;
4835 err_code = selector & 0xfffc;
4836 err_vec = GP_VECTOR;
4838 /* can't load system descriptor into segment selecor */
4839 if (seg <= VCPU_SREG_GS && !kvm_seg.s)
4842 if (!kvm_seg.present) {
4843 err_vec = (seg == VCPU_SREG_SS) ? SS_VECTOR : NP_VECTOR;
4849 cpl = kvm_x86_ops->get_cpl(vcpu);
4854 * segment is not a writable data segment or segment
4855 * selector's RPL != CPL or segment selector's RPL != CPL
4857 if (rpl != cpl || (kvm_seg.type & 0xa) != 0x2 || dpl != cpl)
4861 if (!(kvm_seg.type & 8))
4864 if (kvm_seg.type & 4) {
4870 if (rpl > cpl || dpl != cpl)
4873 /* CS(RPL) <- CPL */
4874 selector = (selector & 0xfffc) | cpl;
4877 if (kvm_seg.s || (kvm_seg.type != 1 && kvm_seg.type != 9))
4880 case VCPU_SREG_LDTR:
4881 if (kvm_seg.s || kvm_seg.type != 2)
4884 default: /* DS, ES, FS, or GS */
4886 * segment is not a data or readable code segment or
4887 * ((segment is a data or nonconforming code segment)
4888 * and (both RPL and CPL > DPL))
4890 if ((kvm_seg.type & 0xa) == 0x8 ||
4891 (((kvm_seg.type & 0xc) != 0xc) && (rpl > dpl && cpl > dpl)))
4896 if (!kvm_seg.unusable && kvm_seg.s) {
4897 /* mark segment as accessed */
4900 save_guest_segment_descriptor(vcpu, selector, &seg_desc);
4903 kvm_set_segment(vcpu, &kvm_seg, seg);
4904 return X86EMUL_CONTINUE;
4906 kvm_queue_exception_e(vcpu, err_vec, err_code);
4907 return X86EMUL_PROPAGATE_FAULT;
4910 static void save_state_to_tss32(struct kvm_vcpu *vcpu,
4911 struct tss_segment_32 *tss)
4913 tss->cr3 = vcpu->arch.cr3;
4914 tss->eip = kvm_rip_read(vcpu);
4915 tss->eflags = kvm_get_rflags(vcpu);
4916 tss->eax = kvm_register_read(vcpu, VCPU_REGS_RAX);
4917 tss->ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
4918 tss->edx = kvm_register_read(vcpu, VCPU_REGS_RDX);
4919 tss->ebx = kvm_register_read(vcpu, VCPU_REGS_RBX);
4920 tss->esp = kvm_register_read(vcpu, VCPU_REGS_RSP);
4921 tss->ebp = kvm_register_read(vcpu, VCPU_REGS_RBP);
4922 tss->esi = kvm_register_read(vcpu, VCPU_REGS_RSI);
4923 tss->edi = kvm_register_read(vcpu, VCPU_REGS_RDI);
4924 tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
4925 tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
4926 tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
4927 tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
4928 tss->fs = get_segment_selector(vcpu, VCPU_SREG_FS);
4929 tss->gs = get_segment_selector(vcpu, VCPU_SREG_GS);
4930 tss->ldt_selector = get_segment_selector(vcpu, VCPU_SREG_LDTR);
4933 static void kvm_load_segment_selector(struct kvm_vcpu *vcpu, u16 sel, int seg)
4935 struct kvm_segment kvm_seg;
4936 kvm_get_segment(vcpu, &kvm_seg, seg);
4937 kvm_seg.selector = sel;
4938 kvm_set_segment(vcpu, &kvm_seg, seg);
4941 static int load_state_from_tss32(struct kvm_vcpu *vcpu,
4942 struct tss_segment_32 *tss)
4944 kvm_set_cr3(vcpu, tss->cr3);
4946 kvm_rip_write(vcpu, tss->eip);
4947 kvm_set_rflags(vcpu, tss->eflags | 2);
4949 kvm_register_write(vcpu, VCPU_REGS_RAX, tss->eax);
4950 kvm_register_write(vcpu, VCPU_REGS_RCX, tss->ecx);
4951 kvm_register_write(vcpu, VCPU_REGS_RDX, tss->edx);
4952 kvm_register_write(vcpu, VCPU_REGS_RBX, tss->ebx);
4953 kvm_register_write(vcpu, VCPU_REGS_RSP, tss->esp);
4954 kvm_register_write(vcpu, VCPU_REGS_RBP, tss->ebp);
4955 kvm_register_write(vcpu, VCPU_REGS_RSI, tss->esi);
4956 kvm_register_write(vcpu, VCPU_REGS_RDI, tss->edi);
4959 * SDM says that segment selectors are loaded before segment
4962 kvm_load_segment_selector(vcpu, tss->ldt_selector, VCPU_SREG_LDTR);
4963 kvm_load_segment_selector(vcpu, tss->es, VCPU_SREG_ES);
4964 kvm_load_segment_selector(vcpu, tss->cs, VCPU_SREG_CS);
4965 kvm_load_segment_selector(vcpu, tss->ss, VCPU_SREG_SS);
4966 kvm_load_segment_selector(vcpu, tss->ds, VCPU_SREG_DS);
4967 kvm_load_segment_selector(vcpu, tss->fs, VCPU_SREG_FS);
4968 kvm_load_segment_selector(vcpu, tss->gs, VCPU_SREG_GS);
4971 * Now load segment descriptors. If fault happenes at this stage
4972 * it is handled in a context of new task
4974 if (kvm_load_segment_descriptor(vcpu, tss->ldt_selector, VCPU_SREG_LDTR))
4977 if (kvm_load_segment_descriptor(vcpu, tss->es, VCPU_SREG_ES))
4980 if (kvm_load_segment_descriptor(vcpu, tss->cs, VCPU_SREG_CS))
4983 if (kvm_load_segment_descriptor(vcpu, tss->ss, VCPU_SREG_SS))
4986 if (kvm_load_segment_descriptor(vcpu, tss->ds, VCPU_SREG_DS))
4989 if (kvm_load_segment_descriptor(vcpu, tss->fs, VCPU_SREG_FS))
4992 if (kvm_load_segment_descriptor(vcpu, tss->gs, VCPU_SREG_GS))
4997 static void save_state_to_tss16(struct kvm_vcpu *vcpu,
4998 struct tss_segment_16 *tss)
5000 tss->ip = kvm_rip_read(vcpu);
5001 tss->flag = kvm_get_rflags(vcpu);
5002 tss->ax = kvm_register_read(vcpu, VCPU_REGS_RAX);
5003 tss->cx = kvm_register_read(vcpu, VCPU_REGS_RCX);
5004 tss->dx = kvm_register_read(vcpu, VCPU_REGS_RDX);
5005 tss->bx = kvm_register_read(vcpu, VCPU_REGS_RBX);
5006 tss->sp = kvm_register_read(vcpu, VCPU_REGS_RSP);
5007 tss->bp = kvm_register_read(vcpu, VCPU_REGS_RBP);
5008 tss->si = kvm_register_read(vcpu, VCPU_REGS_RSI);
5009 tss->di = kvm_register_read(vcpu, VCPU_REGS_RDI);
5011 tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
5012 tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
5013 tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
5014 tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
5015 tss->ldt = get_segment_selector(vcpu, VCPU_SREG_LDTR);
5018 static int load_state_from_tss16(struct kvm_vcpu *vcpu,
5019 struct tss_segment_16 *tss)
5021 kvm_rip_write(vcpu, tss->ip);
5022 kvm_set_rflags(vcpu, tss->flag | 2);
5023 kvm_register_write(vcpu, VCPU_REGS_RAX, tss->ax);
5024 kvm_register_write(vcpu, VCPU_REGS_RCX, tss->cx);
5025 kvm_register_write(vcpu, VCPU_REGS_RDX, tss->dx);
5026 kvm_register_write(vcpu, VCPU_REGS_RBX, tss->bx);
5027 kvm_register_write(vcpu, VCPU_REGS_RSP, tss->sp);
5028 kvm_register_write(vcpu, VCPU_REGS_RBP, tss->bp);
5029 kvm_register_write(vcpu, VCPU_REGS_RSI, tss->si);
5030 kvm_register_write(vcpu, VCPU_REGS_RDI, tss->di);
5033 * SDM says that segment selectors are loaded before segment
5036 kvm_load_segment_selector(vcpu, tss->ldt, VCPU_SREG_LDTR);
5037 kvm_load_segment_selector(vcpu, tss->es, VCPU_SREG_ES);
5038 kvm_load_segment_selector(vcpu, tss->cs, VCPU_SREG_CS);
5039 kvm_load_segment_selector(vcpu, tss->ss, VCPU_SREG_SS);
5040 kvm_load_segment_selector(vcpu, tss->ds, VCPU_SREG_DS);
5043 * Now load segment descriptors. If fault happenes at this stage
5044 * it is handled in a context of new task
5046 if (kvm_load_segment_descriptor(vcpu, tss->ldt, VCPU_SREG_LDTR))
5049 if (kvm_load_segment_descriptor(vcpu, tss->es, VCPU_SREG_ES))
5052 if (kvm_load_segment_descriptor(vcpu, tss->cs, VCPU_SREG_CS))
5055 if (kvm_load_segment_descriptor(vcpu, tss->ss, VCPU_SREG_SS))
5058 if (kvm_load_segment_descriptor(vcpu, tss->ds, VCPU_SREG_DS))
5063 static int kvm_task_switch_16(struct kvm_vcpu *vcpu, u16 tss_selector,
5064 u16 old_tss_sel, u32 old_tss_base,
5065 struct desc_struct *nseg_desc)
5067 struct tss_segment_16 tss_segment_16;
5070 if (kvm_read_guest(vcpu->kvm, old_tss_base, &tss_segment_16,
5071 sizeof tss_segment_16))
5074 save_state_to_tss16(vcpu, &tss_segment_16);
5076 if (kvm_write_guest(vcpu->kvm, old_tss_base, &tss_segment_16,
5077 sizeof tss_segment_16))
5080 if (kvm_read_guest(vcpu->kvm, get_tss_base_addr_read(vcpu, nseg_desc),
5081 &tss_segment_16, sizeof tss_segment_16))
5084 if (old_tss_sel != 0xffff) {
5085 tss_segment_16.prev_task_link = old_tss_sel;
5087 if (kvm_write_guest(vcpu->kvm,
5088 get_tss_base_addr_write(vcpu, nseg_desc),
5089 &tss_segment_16.prev_task_link,
5090 sizeof tss_segment_16.prev_task_link))
5094 if (load_state_from_tss16(vcpu, &tss_segment_16))
5102 static int kvm_task_switch_32(struct kvm_vcpu *vcpu, u16 tss_selector,
5103 u16 old_tss_sel, u32 old_tss_base,
5104 struct desc_struct *nseg_desc)
5106 struct tss_segment_32 tss_segment_32;
5109 if (kvm_read_guest(vcpu->kvm, old_tss_base, &tss_segment_32,
5110 sizeof tss_segment_32))
5113 save_state_to_tss32(vcpu, &tss_segment_32);
5115 if (kvm_write_guest(vcpu->kvm, old_tss_base, &tss_segment_32,
5116 sizeof tss_segment_32))
5119 if (kvm_read_guest(vcpu->kvm, get_tss_base_addr_read(vcpu, nseg_desc),
5120 &tss_segment_32, sizeof tss_segment_32))
5123 if (old_tss_sel != 0xffff) {
5124 tss_segment_32.prev_task_link = old_tss_sel;
5126 if (kvm_write_guest(vcpu->kvm,
5127 get_tss_base_addr_write(vcpu, nseg_desc),
5128 &tss_segment_32.prev_task_link,
5129 sizeof tss_segment_32.prev_task_link))
5133 if (load_state_from_tss32(vcpu, &tss_segment_32))
5141 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason)
5143 struct kvm_segment tr_seg;
5144 struct desc_struct cseg_desc;
5145 struct desc_struct nseg_desc;
5147 u32 old_tss_base = get_segment_base(vcpu, VCPU_SREG_TR);
5148 u16 old_tss_sel = get_segment_selector(vcpu, VCPU_SREG_TR);
5150 old_tss_base = kvm_mmu_gva_to_gpa_write(vcpu, old_tss_base, NULL);
5152 /* FIXME: Handle errors. Failure to read either TSS or their
5153 * descriptors should generate a pagefault.
5155 if (load_guest_segment_descriptor(vcpu, tss_selector, &nseg_desc))
5158 if (load_guest_segment_descriptor(vcpu, old_tss_sel, &cseg_desc))
5161 if (reason != TASK_SWITCH_IRET) {
5164 cpl = kvm_x86_ops->get_cpl(vcpu);
5165 if ((tss_selector & 3) > nseg_desc.dpl || cpl > nseg_desc.dpl) {
5166 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
5171 if (!nseg_desc.p || get_desc_limit(&nseg_desc) < 0x67) {
5172 kvm_queue_exception_e(vcpu, TS_VECTOR, tss_selector & 0xfffc);
5176 if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) {
5177 cseg_desc.type &= ~(1 << 1); //clear the B flag
5178 save_guest_segment_descriptor(vcpu, old_tss_sel, &cseg_desc);
5181 if (reason == TASK_SWITCH_IRET) {
5182 u32 eflags = kvm_get_rflags(vcpu);
5183 kvm_set_rflags(vcpu, eflags & ~X86_EFLAGS_NT);
5186 /* set back link to prev task only if NT bit is set in eflags
5187 note that old_tss_sel is not used afetr this point */
5188 if (reason != TASK_SWITCH_CALL && reason != TASK_SWITCH_GATE)
5189 old_tss_sel = 0xffff;
5191 if (nseg_desc.type & 8)
5192 ret = kvm_task_switch_32(vcpu, tss_selector, old_tss_sel,
5193 old_tss_base, &nseg_desc);
5195 ret = kvm_task_switch_16(vcpu, tss_selector, old_tss_sel,
5196 old_tss_base, &nseg_desc);
5198 if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE) {
5199 u32 eflags = kvm_get_rflags(vcpu);
5200 kvm_set_rflags(vcpu, eflags | X86_EFLAGS_NT);
5203 if (reason != TASK_SWITCH_IRET) {
5204 nseg_desc.type |= (1 << 1);
5205 save_guest_segment_descriptor(vcpu, tss_selector,
5209 kvm_x86_ops->set_cr0(vcpu, kvm_read_cr0(vcpu) | X86_CR0_TS);
5210 seg_desct_to_kvm_desct(&nseg_desc, tss_selector, &tr_seg);
5212 kvm_set_segment(vcpu, &tr_seg, VCPU_SREG_TR);
5216 EXPORT_SYMBOL_GPL(kvm_task_switch);
5218 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
5219 struct kvm_sregs *sregs)
5221 int mmu_reset_needed = 0;
5222 int pending_vec, max_bits;
5223 struct descriptor_table dt;
5227 dt.limit = sregs->idt.limit;
5228 dt.base = sregs->idt.base;
5229 kvm_x86_ops->set_idt(vcpu, &dt);
5230 dt.limit = sregs->gdt.limit;
5231 dt.base = sregs->gdt.base;
5232 kvm_x86_ops->set_gdt(vcpu, &dt);
5234 vcpu->arch.cr2 = sregs->cr2;
5235 mmu_reset_needed |= vcpu->arch.cr3 != sregs->cr3;
5236 vcpu->arch.cr3 = sregs->cr3;
5238 kvm_set_cr8(vcpu, sregs->cr8);
5240 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
5241 kvm_x86_ops->set_efer(vcpu, sregs->efer);
5242 kvm_set_apic_base(vcpu, sregs->apic_base);
5244 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
5245 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
5246 vcpu->arch.cr0 = sregs->cr0;
5248 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
5249 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
5250 if (!is_long_mode(vcpu) && is_pae(vcpu)) {
5251 load_pdptrs(vcpu, vcpu->arch.cr3);
5252 mmu_reset_needed = 1;
5255 if (mmu_reset_needed)
5256 kvm_mmu_reset_context(vcpu);
5258 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
5259 pending_vec = find_first_bit(
5260 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
5261 if (pending_vec < max_bits) {
5262 kvm_queue_interrupt(vcpu, pending_vec, false);
5263 pr_debug("Set back pending irq %d\n", pending_vec);
5264 if (irqchip_in_kernel(vcpu->kvm))
5265 kvm_pic_clear_isr_ack(vcpu->kvm);
5268 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
5269 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
5270 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
5271 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
5272 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
5273 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
5275 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
5276 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
5278 update_cr8_intercept(vcpu);
5280 /* Older userspace won't unhalt the vcpu on reset. */
5281 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
5282 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
5284 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5291 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
5292 struct kvm_guest_debug *dbg)
5294 unsigned long rflags;
5299 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
5301 if (vcpu->arch.exception.pending)
5303 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
5304 kvm_queue_exception(vcpu, DB_VECTOR);
5306 kvm_queue_exception(vcpu, BP_VECTOR);
5310 * Read rflags as long as potentially injected trace flags are still
5313 rflags = kvm_get_rflags(vcpu);
5315 vcpu->guest_debug = dbg->control;
5316 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
5317 vcpu->guest_debug = 0;
5319 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5320 for (i = 0; i < KVM_NR_DB_REGS; ++i)
5321 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
5322 vcpu->arch.switch_db_regs =
5323 (dbg->arch.debugreg[7] & DR7_BP_EN_MASK);
5325 for (i = 0; i < KVM_NR_DB_REGS; i++)
5326 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
5327 vcpu->arch.switch_db_regs = (vcpu->arch.dr7 & DR7_BP_EN_MASK);
5330 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5331 vcpu->arch.singlestep_cs =
5332 get_segment_selector(vcpu, VCPU_SREG_CS);
5333 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu);
5337 * Trigger an rflags update that will inject or remove the trace
5340 kvm_set_rflags(vcpu, rflags);
5342 kvm_x86_ops->set_guest_debug(vcpu, dbg);
5353 * fxsave fpu state. Taken from x86_64/processor.h. To be killed when
5354 * we have asm/x86/processor.h
5365 u32 st_space[32]; /* 8*16 bytes for each FP-reg = 128 bytes */
5366 #ifdef CONFIG_X86_64
5367 u32 xmm_space[64]; /* 16*16 bytes for each XMM-reg = 256 bytes */
5369 u32 xmm_space[32]; /* 8*16 bytes for each XMM-reg = 128 bytes */
5374 * Translate a guest virtual address to a guest physical address.
5376 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
5377 struct kvm_translation *tr)
5379 unsigned long vaddr = tr->linear_address;
5384 idx = srcu_read_lock(&vcpu->kvm->srcu);
5385 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
5386 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5387 tr->physical_address = gpa;
5388 tr->valid = gpa != UNMAPPED_GVA;
5396 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
5398 struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
5402 memcpy(fpu->fpr, fxsave->st_space, 128);
5403 fpu->fcw = fxsave->cwd;
5404 fpu->fsw = fxsave->swd;
5405 fpu->ftwx = fxsave->twd;
5406 fpu->last_opcode = fxsave->fop;
5407 fpu->last_ip = fxsave->rip;
5408 fpu->last_dp = fxsave->rdp;
5409 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
5416 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
5418 struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
5422 memcpy(fxsave->st_space, fpu->fpr, 128);
5423 fxsave->cwd = fpu->fcw;
5424 fxsave->swd = fpu->fsw;
5425 fxsave->twd = fpu->ftwx;
5426 fxsave->fop = fpu->last_opcode;
5427 fxsave->rip = fpu->last_ip;
5428 fxsave->rdp = fpu->last_dp;
5429 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
5436 void fx_init(struct kvm_vcpu *vcpu)
5438 unsigned after_mxcsr_mask;
5441 * Touch the fpu the first time in non atomic context as if
5442 * this is the first fpu instruction the exception handler
5443 * will fire before the instruction returns and it'll have to
5444 * allocate ram with GFP_KERNEL.
5447 kvm_fx_save(&vcpu->arch.host_fx_image);
5449 /* Initialize guest FPU by resetting ours and saving into guest's */
5451 kvm_fx_save(&vcpu->arch.host_fx_image);
5453 kvm_fx_save(&vcpu->arch.guest_fx_image);
5454 kvm_fx_restore(&vcpu->arch.host_fx_image);
5457 vcpu->arch.cr0 |= X86_CR0_ET;
5458 after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
5459 vcpu->arch.guest_fx_image.mxcsr = 0x1f80;
5460 memset((void *)&vcpu->arch.guest_fx_image + after_mxcsr_mask,
5461 0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
5463 EXPORT_SYMBOL_GPL(fx_init);
5465 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
5467 if (vcpu->guest_fpu_loaded)
5470 vcpu->guest_fpu_loaded = 1;
5471 kvm_fx_save(&vcpu->arch.host_fx_image);
5472 kvm_fx_restore(&vcpu->arch.guest_fx_image);
5476 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
5478 if (!vcpu->guest_fpu_loaded)
5481 vcpu->guest_fpu_loaded = 0;
5482 kvm_fx_save(&vcpu->arch.guest_fx_image);
5483 kvm_fx_restore(&vcpu->arch.host_fx_image);
5484 ++vcpu->stat.fpu_reload;
5485 set_bit(KVM_REQ_DEACTIVATE_FPU, &vcpu->requests);
5489 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
5491 if (vcpu->arch.time_page) {
5492 kvm_release_page_dirty(vcpu->arch.time_page);
5493 vcpu->arch.time_page = NULL;
5496 kvm_x86_ops->vcpu_free(vcpu);
5499 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
5502 return kvm_x86_ops->vcpu_create(kvm, id);
5505 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
5509 /* We do fxsave: this must be aligned. */
5510 BUG_ON((unsigned long)&vcpu->arch.host_fx_image & 0xF);
5512 vcpu->arch.mtrr_state.have_fixed = 1;
5514 r = kvm_arch_vcpu_reset(vcpu);
5516 r = kvm_mmu_setup(vcpu);
5523 kvm_x86_ops->vcpu_free(vcpu);
5527 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
5530 kvm_mmu_unload(vcpu);
5533 kvm_x86_ops->vcpu_free(vcpu);
5536 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
5538 vcpu->arch.nmi_pending = false;
5539 vcpu->arch.nmi_injected = false;
5541 vcpu->arch.switch_db_regs = 0;
5542 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
5543 vcpu->arch.dr6 = DR6_FIXED_1;
5544 vcpu->arch.dr7 = DR7_FIXED_1;
5546 return kvm_x86_ops->vcpu_reset(vcpu);
5549 int kvm_arch_hardware_enable(void *garbage)
5552 * Since this may be called from a hotplug notifcation,
5553 * we can't get the CPU frequency directly.
5555 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5556 int cpu = raw_smp_processor_id();
5557 per_cpu(cpu_tsc_khz, cpu) = 0;
5560 kvm_shared_msr_cpu_online();
5562 return kvm_x86_ops->hardware_enable(garbage);
5565 void kvm_arch_hardware_disable(void *garbage)
5567 kvm_x86_ops->hardware_disable(garbage);
5568 drop_user_return_notifiers(garbage);
5571 int kvm_arch_hardware_setup(void)
5573 return kvm_x86_ops->hardware_setup();
5576 void kvm_arch_hardware_unsetup(void)
5578 kvm_x86_ops->hardware_unsetup();
5581 void kvm_arch_check_processor_compat(void *rtn)
5583 kvm_x86_ops->check_processor_compatibility(rtn);
5586 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
5592 BUG_ON(vcpu->kvm == NULL);
5595 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
5596 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
5597 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5599 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
5601 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
5606 vcpu->arch.pio_data = page_address(page);
5608 r = kvm_mmu_create(vcpu);
5610 goto fail_free_pio_data;
5612 if (irqchip_in_kernel(kvm)) {
5613 r = kvm_create_lapic(vcpu);
5615 goto fail_mmu_destroy;
5618 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
5620 if (!vcpu->arch.mce_banks) {
5622 goto fail_free_lapic;
5624 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
5628 kvm_free_lapic(vcpu);
5630 kvm_mmu_destroy(vcpu);
5632 free_page((unsigned long)vcpu->arch.pio_data);
5637 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
5641 kfree(vcpu->arch.mce_banks);
5642 kvm_free_lapic(vcpu);
5643 idx = srcu_read_lock(&vcpu->kvm->srcu);
5644 kvm_mmu_destroy(vcpu);
5645 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5646 free_page((unsigned long)vcpu->arch.pio_data);
5649 struct kvm *kvm_arch_create_vm(void)
5651 struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
5654 return ERR_PTR(-ENOMEM);
5656 kvm->arch.aliases = kzalloc(sizeof(struct kvm_mem_aliases), GFP_KERNEL);
5657 if (!kvm->arch.aliases) {
5659 return ERR_PTR(-ENOMEM);
5662 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
5663 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
5665 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
5666 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
5668 rdtscll(kvm->arch.vm_init_tsc);
5673 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
5676 kvm_mmu_unload(vcpu);
5680 static void kvm_free_vcpus(struct kvm *kvm)
5683 struct kvm_vcpu *vcpu;
5686 * Unpin any mmu pages first.
5688 kvm_for_each_vcpu(i, vcpu, kvm)
5689 kvm_unload_vcpu_mmu(vcpu);
5690 kvm_for_each_vcpu(i, vcpu, kvm)
5691 kvm_arch_vcpu_free(vcpu);
5693 mutex_lock(&kvm->lock);
5694 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
5695 kvm->vcpus[i] = NULL;
5697 atomic_set(&kvm->online_vcpus, 0);
5698 mutex_unlock(&kvm->lock);
5701 void kvm_arch_sync_events(struct kvm *kvm)
5703 kvm_free_all_assigned_devices(kvm);
5706 void kvm_arch_destroy_vm(struct kvm *kvm)
5708 kvm_iommu_unmap_guest(kvm);
5710 kfree(kvm->arch.vpic);
5711 kfree(kvm->arch.vioapic);
5712 kvm_free_vcpus(kvm);
5713 kvm_free_physmem(kvm);
5714 if (kvm->arch.apic_access_page)
5715 put_page(kvm->arch.apic_access_page);
5716 if (kvm->arch.ept_identity_pagetable)
5717 put_page(kvm->arch.ept_identity_pagetable);
5718 cleanup_srcu_struct(&kvm->srcu);
5719 kfree(kvm->arch.aliases);
5723 int kvm_arch_prepare_memory_region(struct kvm *kvm,
5724 struct kvm_memory_slot *memslot,
5725 struct kvm_memory_slot old,
5726 struct kvm_userspace_memory_region *mem,
5729 int npages = memslot->npages;
5731 /*To keep backward compatibility with older userspace,
5732 *x86 needs to hanlde !user_alloc case.
5735 if (npages && !old.rmap) {
5736 unsigned long userspace_addr;
5738 down_write(¤t->mm->mmap_sem);
5739 userspace_addr = do_mmap(NULL, 0,
5741 PROT_READ | PROT_WRITE,
5742 MAP_PRIVATE | MAP_ANONYMOUS,
5744 up_write(¤t->mm->mmap_sem);
5746 if (IS_ERR((void *)userspace_addr))
5747 return PTR_ERR((void *)userspace_addr);
5749 memslot->userspace_addr = userspace_addr;
5757 void kvm_arch_commit_memory_region(struct kvm *kvm,
5758 struct kvm_userspace_memory_region *mem,
5759 struct kvm_memory_slot old,
5763 int npages = mem->memory_size >> PAGE_SHIFT;
5765 if (!user_alloc && !old.user_alloc && old.rmap && !npages) {
5768 down_write(¤t->mm->mmap_sem);
5769 ret = do_munmap(current->mm, old.userspace_addr,
5770 old.npages * PAGE_SIZE);
5771 up_write(¤t->mm->mmap_sem);
5774 "kvm_vm_ioctl_set_memory_region: "
5775 "failed to munmap memory\n");
5778 spin_lock(&kvm->mmu_lock);
5779 if (!kvm->arch.n_requested_mmu_pages) {
5780 unsigned int nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
5781 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
5784 kvm_mmu_slot_remove_write_access(kvm, mem->slot);
5785 spin_unlock(&kvm->mmu_lock);
5788 void kvm_arch_flush_shadow(struct kvm *kvm)
5790 kvm_mmu_zap_all(kvm);
5791 kvm_reload_remote_mmus(kvm);
5794 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
5796 return vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE
5797 || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
5798 || vcpu->arch.nmi_pending ||
5799 (kvm_arch_interrupt_allowed(vcpu) &&
5800 kvm_cpu_has_interrupt(vcpu));
5803 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
5806 int cpu = vcpu->cpu;
5808 if (waitqueue_active(&vcpu->wq)) {
5809 wake_up_interruptible(&vcpu->wq);
5810 ++vcpu->stat.halt_wakeup;
5814 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
5815 if (!test_and_set_bit(KVM_REQ_KICK, &vcpu->requests))
5816 smp_send_reschedule(cpu);
5820 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
5822 return kvm_x86_ops->interrupt_allowed(vcpu);
5825 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
5827 unsigned long rflags;
5829 rflags = kvm_x86_ops->get_rflags(vcpu);
5830 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
5831 rflags &= ~(unsigned long)(X86_EFLAGS_TF | X86_EFLAGS_RF);
5834 EXPORT_SYMBOL_GPL(kvm_get_rflags);
5836 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
5838 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
5839 vcpu->arch.singlestep_cs ==
5840 get_segment_selector(vcpu, VCPU_SREG_CS) &&
5841 vcpu->arch.singlestep_rip == kvm_rip_read(vcpu))
5842 rflags |= X86_EFLAGS_TF | X86_EFLAGS_RF;
5843 kvm_x86_ops->set_rflags(vcpu, rflags);
5845 EXPORT_SYMBOL_GPL(kvm_set_rflags);
5847 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
5848 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
5849 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
5850 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
5851 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
5852 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
5853 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
5854 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
5855 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
5856 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
5857 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);