mm-only debug patch...
[mmotm.git] / arch / x86 / kvm / x86.c
blob11a6f2f440ae78ca0d14aa560c386c9bf1d1176b
1 /*
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
10 * Authors:
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>
22 #include "irq.h"
23 #include "mmu.h"
24 #include "i8254.h"
25 #include "tss.h"
26 #include "kvm_cache_regs.h"
27 #include "x86.h"
29 #include <linux/clocksource.h>
30 #include <linux/interrupt.h>
31 #include <linux/kvm.h>
32 #include <linux/fs.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 <trace/events/kvm.h>
41 #undef TRACE_INCLUDE_FILE
42 #define CREATE_TRACE_POINTS
43 #include "trace.h"
45 #include <asm/uaccess.h>
46 #include <asm/msr.h>
47 #include <asm/desc.h>
48 #include <asm/mtrr.h>
49 #include <asm/mce.h>
51 #define MAX_IO_MSRS 256
52 #define CR0_RESERVED_BITS \
53 (~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
54 | X86_CR0_ET | X86_CR0_NE | X86_CR0_WP | X86_CR0_AM \
55 | X86_CR0_NW | X86_CR0_CD | X86_CR0_PG))
56 #define CR4_RESERVED_BITS \
57 (~(unsigned long)(X86_CR4_VME | X86_CR4_PVI | X86_CR4_TSD | X86_CR4_DE\
58 | X86_CR4_PSE | X86_CR4_PAE | X86_CR4_MCE \
59 | X86_CR4_PGE | X86_CR4_PCE | X86_CR4_OSFXSR \
60 | X86_CR4_OSXMMEXCPT | X86_CR4_VMXE))
62 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
64 #define KVM_MAX_MCE_BANKS 32
65 #define KVM_MCE_CAP_SUPPORTED MCG_CTL_P
67 /* EFER defaults:
68 * - enable syscall per default because its emulated by KVM
69 * - enable LME and LMA per default on 64 bit KVM
71 #ifdef CONFIG_X86_64
72 static u64 __read_mostly efer_reserved_bits = 0xfffffffffffffafeULL;
73 #else
74 static u64 __read_mostly efer_reserved_bits = 0xfffffffffffffffeULL;
75 #endif
77 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
78 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
80 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
81 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
82 struct kvm_cpuid_entry2 __user *entries);
84 struct kvm_x86_ops *kvm_x86_ops;
85 EXPORT_SYMBOL_GPL(kvm_x86_ops);
87 int ignore_msrs = 0;
88 module_param_named(ignore_msrs, ignore_msrs, bool, S_IRUGO | S_IWUSR);
90 struct kvm_stats_debugfs_item debugfs_entries[] = {
91 { "pf_fixed", VCPU_STAT(pf_fixed) },
92 { "pf_guest", VCPU_STAT(pf_guest) },
93 { "tlb_flush", VCPU_STAT(tlb_flush) },
94 { "invlpg", VCPU_STAT(invlpg) },
95 { "exits", VCPU_STAT(exits) },
96 { "io_exits", VCPU_STAT(io_exits) },
97 { "mmio_exits", VCPU_STAT(mmio_exits) },
98 { "signal_exits", VCPU_STAT(signal_exits) },
99 { "irq_window", VCPU_STAT(irq_window_exits) },
100 { "nmi_window", VCPU_STAT(nmi_window_exits) },
101 { "halt_exits", VCPU_STAT(halt_exits) },
102 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
103 { "hypercalls", VCPU_STAT(hypercalls) },
104 { "request_irq", VCPU_STAT(request_irq_exits) },
105 { "irq_exits", VCPU_STAT(irq_exits) },
106 { "host_state_reload", VCPU_STAT(host_state_reload) },
107 { "efer_reload", VCPU_STAT(efer_reload) },
108 { "fpu_reload", VCPU_STAT(fpu_reload) },
109 { "insn_emulation", VCPU_STAT(insn_emulation) },
110 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
111 { "irq_injections", VCPU_STAT(irq_injections) },
112 { "nmi_injections", VCPU_STAT(nmi_injections) },
113 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
114 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
115 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
116 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
117 { "mmu_flooded", VM_STAT(mmu_flooded) },
118 { "mmu_recycled", VM_STAT(mmu_recycled) },
119 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
120 { "mmu_unsync", VM_STAT(mmu_unsync) },
121 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
122 { "largepages", VM_STAT(lpages) },
123 { NULL }
126 unsigned long segment_base(u16 selector)
128 struct descriptor_table gdt;
129 struct desc_struct *d;
130 unsigned long table_base;
131 unsigned long v;
133 if (selector == 0)
134 return 0;
136 kvm_get_gdt(&gdt);
137 table_base = gdt.base;
139 if (selector & 4) { /* from ldt */
140 u16 ldt_selector = kvm_read_ldt();
142 table_base = segment_base(ldt_selector);
144 d = (struct desc_struct *)(table_base + (selector & ~7));
145 v = get_desc_base(d);
146 #ifdef CONFIG_X86_64
147 if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
148 v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
149 #endif
150 return v;
152 EXPORT_SYMBOL_GPL(segment_base);
154 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
156 if (irqchip_in_kernel(vcpu->kvm))
157 return vcpu->arch.apic_base;
158 else
159 return vcpu->arch.apic_base;
161 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
163 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
165 /* TODO: reserve bits check */
166 if (irqchip_in_kernel(vcpu->kvm))
167 kvm_lapic_set_base(vcpu, data);
168 else
169 vcpu->arch.apic_base = data;
171 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
173 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
175 WARN_ON(vcpu->arch.exception.pending);
176 vcpu->arch.exception.pending = true;
177 vcpu->arch.exception.has_error_code = false;
178 vcpu->arch.exception.nr = nr;
180 EXPORT_SYMBOL_GPL(kvm_queue_exception);
182 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, unsigned long addr,
183 u32 error_code)
185 ++vcpu->stat.pf_guest;
187 if (vcpu->arch.exception.pending) {
188 switch(vcpu->arch.exception.nr) {
189 case DF_VECTOR:
190 /* triple fault -> shutdown */
191 set_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests);
192 return;
193 case PF_VECTOR:
194 vcpu->arch.exception.nr = DF_VECTOR;
195 vcpu->arch.exception.error_code = 0;
196 return;
197 default:
198 /* replace previous exception with a new one in a hope
199 that instruction re-execution will regenerate lost
200 exception */
201 vcpu->arch.exception.pending = false;
202 break;
205 vcpu->arch.cr2 = addr;
206 kvm_queue_exception_e(vcpu, PF_VECTOR, error_code);
209 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
211 vcpu->arch.nmi_pending = 1;
213 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
215 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
217 WARN_ON(vcpu->arch.exception.pending);
218 vcpu->arch.exception.pending = true;
219 vcpu->arch.exception.has_error_code = true;
220 vcpu->arch.exception.nr = nr;
221 vcpu->arch.exception.error_code = error_code;
223 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
226 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
227 * a #GP and return false.
229 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
231 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
232 return true;
233 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
234 return false;
236 EXPORT_SYMBOL_GPL(kvm_require_cpl);
238 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
240 unsigned long rflags;
242 rflags = kvm_x86_ops->get_rflags(vcpu);
243 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
244 rflags &= ~(unsigned long)(X86_EFLAGS_TF | X86_EFLAGS_RF);
245 return rflags;
247 EXPORT_SYMBOL_GPL(kvm_get_rflags);
249 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
251 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
252 rflags |= X86_EFLAGS_TF | X86_EFLAGS_RF;
253 kvm_x86_ops->set_rflags(vcpu, rflags);
255 EXPORT_SYMBOL_GPL(kvm_set_rflags);
258 * Load the pae pdptrs. Return true is they are all valid.
260 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
262 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
263 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
264 int i;
265 int ret;
266 u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
268 ret = kvm_read_guest_page(vcpu->kvm, pdpt_gfn, pdpte,
269 offset * sizeof(u64), sizeof(pdpte));
270 if (ret < 0) {
271 ret = 0;
272 goto out;
274 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
275 if (is_present_gpte(pdpte[i]) &&
276 (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
277 ret = 0;
278 goto out;
281 ret = 1;
283 memcpy(vcpu->arch.pdptrs, pdpte, sizeof(vcpu->arch.pdptrs));
284 __set_bit(VCPU_EXREG_PDPTR,
285 (unsigned long *)&vcpu->arch.regs_avail);
286 __set_bit(VCPU_EXREG_PDPTR,
287 (unsigned long *)&vcpu->arch.regs_dirty);
288 out:
290 return ret;
292 EXPORT_SYMBOL_GPL(load_pdptrs);
294 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
296 u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
297 bool changed = true;
298 int r;
300 if (is_long_mode(vcpu) || !is_pae(vcpu))
301 return false;
303 if (!test_bit(VCPU_EXREG_PDPTR,
304 (unsigned long *)&vcpu->arch.regs_avail))
305 return true;
307 r = kvm_read_guest(vcpu->kvm, vcpu->arch.cr3 & ~31u, pdpte, sizeof(pdpte));
308 if (r < 0)
309 goto out;
310 changed = memcmp(pdpte, vcpu->arch.pdptrs, sizeof(pdpte)) != 0;
311 out:
313 return changed;
316 void kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
318 if (cr0 & CR0_RESERVED_BITS) {
319 printk(KERN_DEBUG "set_cr0: 0x%lx #GP, reserved bits 0x%lx\n",
320 cr0, vcpu->arch.cr0);
321 kvm_inject_gp(vcpu, 0);
322 return;
325 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD)) {
326 printk(KERN_DEBUG "set_cr0: #GP, CD == 0 && NW == 1\n");
327 kvm_inject_gp(vcpu, 0);
328 return;
331 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE)) {
332 printk(KERN_DEBUG "set_cr0: #GP, set PG flag "
333 "and a clear PE flag\n");
334 kvm_inject_gp(vcpu, 0);
335 return;
338 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
339 #ifdef CONFIG_X86_64
340 if ((vcpu->arch.shadow_efer & EFER_LME)) {
341 int cs_db, cs_l;
343 if (!is_pae(vcpu)) {
344 printk(KERN_DEBUG "set_cr0: #GP, start paging "
345 "in long mode while PAE is disabled\n");
346 kvm_inject_gp(vcpu, 0);
347 return;
349 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
350 if (cs_l) {
351 printk(KERN_DEBUG "set_cr0: #GP, start paging "
352 "in long mode while CS.L == 1\n");
353 kvm_inject_gp(vcpu, 0);
354 return;
357 } else
358 #endif
359 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.cr3)) {
360 printk(KERN_DEBUG "set_cr0: #GP, pdptrs "
361 "reserved bits\n");
362 kvm_inject_gp(vcpu, 0);
363 return;
368 kvm_x86_ops->set_cr0(vcpu, cr0);
369 vcpu->arch.cr0 = cr0;
371 kvm_mmu_reset_context(vcpu);
372 return;
374 EXPORT_SYMBOL_GPL(kvm_set_cr0);
376 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
378 kvm_set_cr0(vcpu, (vcpu->arch.cr0 & ~0x0ful) | (msw & 0x0f));
380 EXPORT_SYMBOL_GPL(kvm_lmsw);
382 void kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
384 unsigned long old_cr4 = vcpu->arch.cr4;
385 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE;
387 if (cr4 & CR4_RESERVED_BITS) {
388 printk(KERN_DEBUG "set_cr4: #GP, reserved bits\n");
389 kvm_inject_gp(vcpu, 0);
390 return;
393 if (is_long_mode(vcpu)) {
394 if (!(cr4 & X86_CR4_PAE)) {
395 printk(KERN_DEBUG "set_cr4: #GP, clearing PAE while "
396 "in long mode\n");
397 kvm_inject_gp(vcpu, 0);
398 return;
400 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
401 && ((cr4 ^ old_cr4) & pdptr_bits)
402 && !load_pdptrs(vcpu, vcpu->arch.cr3)) {
403 printk(KERN_DEBUG "set_cr4: #GP, pdptrs reserved bits\n");
404 kvm_inject_gp(vcpu, 0);
405 return;
408 if (cr4 & X86_CR4_VMXE) {
409 printk(KERN_DEBUG "set_cr4: #GP, setting VMXE\n");
410 kvm_inject_gp(vcpu, 0);
411 return;
413 kvm_x86_ops->set_cr4(vcpu, cr4);
414 vcpu->arch.cr4 = cr4;
415 vcpu->arch.mmu.base_role.cr4_pge = (cr4 & X86_CR4_PGE) && !tdp_enabled;
416 kvm_mmu_reset_context(vcpu);
418 EXPORT_SYMBOL_GPL(kvm_set_cr4);
420 void kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
422 if (cr3 == vcpu->arch.cr3 && !pdptrs_changed(vcpu)) {
423 kvm_mmu_sync_roots(vcpu);
424 kvm_mmu_flush_tlb(vcpu);
425 return;
428 if (is_long_mode(vcpu)) {
429 if (cr3 & CR3_L_MODE_RESERVED_BITS) {
430 printk(KERN_DEBUG "set_cr3: #GP, reserved bits\n");
431 kvm_inject_gp(vcpu, 0);
432 return;
434 } else {
435 if (is_pae(vcpu)) {
436 if (cr3 & CR3_PAE_RESERVED_BITS) {
437 printk(KERN_DEBUG
438 "set_cr3: #GP, reserved bits\n");
439 kvm_inject_gp(vcpu, 0);
440 return;
442 if (is_paging(vcpu) && !load_pdptrs(vcpu, cr3)) {
443 printk(KERN_DEBUG "set_cr3: #GP, pdptrs "
444 "reserved bits\n");
445 kvm_inject_gp(vcpu, 0);
446 return;
450 * We don't check reserved bits in nonpae mode, because
451 * this isn't enforced, and VMware depends on this.
456 * Does the new cr3 value map to physical memory? (Note, we
457 * catch an invalid cr3 even in real-mode, because it would
458 * cause trouble later on when we turn on paging anyway.)
460 * A real CPU would silently accept an invalid cr3 and would
461 * attempt to use it - with largely undefined (and often hard
462 * to debug) behavior on the guest side.
464 if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
465 kvm_inject_gp(vcpu, 0);
466 else {
467 vcpu->arch.cr3 = cr3;
468 vcpu->arch.mmu.new_cr3(vcpu);
471 EXPORT_SYMBOL_GPL(kvm_set_cr3);
473 void kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
475 if (cr8 & CR8_RESERVED_BITS) {
476 printk(KERN_DEBUG "set_cr8: #GP, reserved bits 0x%lx\n", cr8);
477 kvm_inject_gp(vcpu, 0);
478 return;
480 if (irqchip_in_kernel(vcpu->kvm))
481 kvm_lapic_set_tpr(vcpu, cr8);
482 else
483 vcpu->arch.cr8 = cr8;
485 EXPORT_SYMBOL_GPL(kvm_set_cr8);
487 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
489 if (irqchip_in_kernel(vcpu->kvm))
490 return kvm_lapic_get_cr8(vcpu);
491 else
492 return vcpu->arch.cr8;
494 EXPORT_SYMBOL_GPL(kvm_get_cr8);
496 static inline u32 bit(int bitno)
498 return 1 << (bitno & 31);
502 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
503 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
505 * This list is modified at module load time to reflect the
506 * capabilities of the host cpu.
508 static u32 msrs_to_save[] = {
509 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
510 MSR_K6_STAR,
511 #ifdef CONFIG_X86_64
512 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
513 #endif
514 MSR_IA32_TSC, MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
515 MSR_IA32_PERF_STATUS, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA
518 static unsigned num_msrs_to_save;
520 static u32 emulated_msrs[] = {
521 MSR_IA32_MISC_ENABLE,
524 static void set_efer(struct kvm_vcpu *vcpu, u64 efer)
526 if (efer & efer_reserved_bits) {
527 printk(KERN_DEBUG "set_efer: 0x%llx #GP, reserved bits\n",
528 efer);
529 kvm_inject_gp(vcpu, 0);
530 return;
533 if (is_paging(vcpu)
534 && (vcpu->arch.shadow_efer & EFER_LME) != (efer & EFER_LME)) {
535 printk(KERN_DEBUG "set_efer: #GP, change LME while paging\n");
536 kvm_inject_gp(vcpu, 0);
537 return;
540 if (efer & EFER_FFXSR) {
541 struct kvm_cpuid_entry2 *feat;
543 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
544 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT))) {
545 printk(KERN_DEBUG "set_efer: #GP, enable FFXSR w/o CPUID capability\n");
546 kvm_inject_gp(vcpu, 0);
547 return;
551 if (efer & EFER_SVME) {
552 struct kvm_cpuid_entry2 *feat;
554 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
555 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM))) {
556 printk(KERN_DEBUG "set_efer: #GP, enable SVM w/o SVM\n");
557 kvm_inject_gp(vcpu, 0);
558 return;
562 kvm_x86_ops->set_efer(vcpu, efer);
564 efer &= ~EFER_LMA;
565 efer |= vcpu->arch.shadow_efer & EFER_LMA;
567 vcpu->arch.shadow_efer = efer;
569 vcpu->arch.mmu.base_role.nxe = (efer & EFER_NX) && !tdp_enabled;
570 kvm_mmu_reset_context(vcpu);
573 void kvm_enable_efer_bits(u64 mask)
575 efer_reserved_bits &= ~mask;
577 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
581 * Writes msr value into into the appropriate "register".
582 * Returns 0 on success, non-0 otherwise.
583 * Assumes vcpu_load() was already called.
585 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
587 return kvm_x86_ops->set_msr(vcpu, msr_index, data);
591 * Adapt set_msr() to msr_io()'s calling convention
593 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
595 return kvm_set_msr(vcpu, index, *data);
598 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
600 static int version;
601 struct pvclock_wall_clock wc;
602 struct timespec now, sys, boot;
604 if (!wall_clock)
605 return;
607 version++;
609 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
612 * The guest calculates current wall clock time by adding
613 * system time (updated by kvm_write_guest_time below) to the
614 * wall clock specified here. guest system time equals host
615 * system time for us, thus we must fill in host boot time here.
617 now = current_kernel_time();
618 ktime_get_ts(&sys);
619 boot = ns_to_timespec(timespec_to_ns(&now) - timespec_to_ns(&sys));
621 wc.sec = boot.tv_sec;
622 wc.nsec = boot.tv_nsec;
623 wc.version = version;
625 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
627 version++;
628 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
631 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
633 uint32_t quotient, remainder;
635 /* Don't try to replace with do_div(), this one calculates
636 * "(dividend << 32) / divisor" */
637 __asm__ ( "divl %4"
638 : "=a" (quotient), "=d" (remainder)
639 : "0" (0), "1" (dividend), "r" (divisor) );
640 return quotient;
643 static void kvm_set_time_scale(uint32_t tsc_khz, struct pvclock_vcpu_time_info *hv_clock)
645 uint64_t nsecs = 1000000000LL;
646 int32_t shift = 0;
647 uint64_t tps64;
648 uint32_t tps32;
650 tps64 = tsc_khz * 1000LL;
651 while (tps64 > nsecs*2) {
652 tps64 >>= 1;
653 shift--;
656 tps32 = (uint32_t)tps64;
657 while (tps32 <= (uint32_t)nsecs) {
658 tps32 <<= 1;
659 shift++;
662 hv_clock->tsc_shift = shift;
663 hv_clock->tsc_to_system_mul = div_frac(nsecs, tps32);
665 pr_debug("%s: tsc_khz %u, tsc_shift %d, tsc_mul %u\n",
666 __func__, tsc_khz, hv_clock->tsc_shift,
667 hv_clock->tsc_to_system_mul);
670 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
672 static void kvm_write_guest_time(struct kvm_vcpu *v)
674 struct timespec ts;
675 unsigned long flags;
676 struct kvm_vcpu_arch *vcpu = &v->arch;
677 void *shared_kaddr;
678 unsigned long this_tsc_khz;
680 if ((!vcpu->time_page))
681 return;
683 this_tsc_khz = get_cpu_var(cpu_tsc_khz);
684 if (unlikely(vcpu->hv_clock_tsc_khz != this_tsc_khz)) {
685 kvm_set_time_scale(this_tsc_khz, &vcpu->hv_clock);
686 vcpu->hv_clock_tsc_khz = this_tsc_khz;
688 put_cpu_var(cpu_tsc_khz);
690 /* Keep irq disabled to prevent changes to the clock */
691 local_irq_save(flags);
692 kvm_get_msr(v, MSR_IA32_TSC, &vcpu->hv_clock.tsc_timestamp);
693 ktime_get_ts(&ts);
694 local_irq_restore(flags);
696 /* With all the info we got, fill in the values */
698 vcpu->hv_clock.system_time = ts.tv_nsec +
699 (NSEC_PER_SEC * (u64)ts.tv_sec);
701 * The interface expects us to write an even number signaling that the
702 * update is finished. Since the guest won't see the intermediate
703 * state, we just increase by 2 at the end.
705 vcpu->hv_clock.version += 2;
707 shared_kaddr = kmap_atomic(vcpu->time_page, KM_USER0);
709 memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
710 sizeof(vcpu->hv_clock));
712 kunmap_atomic(shared_kaddr, KM_USER0);
714 mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
717 static int kvm_request_guest_time_update(struct kvm_vcpu *v)
719 struct kvm_vcpu_arch *vcpu = &v->arch;
721 if (!vcpu->time_page)
722 return 0;
723 set_bit(KVM_REQ_KVMCLOCK_UPDATE, &v->requests);
724 return 1;
727 static bool msr_mtrr_valid(unsigned msr)
729 switch (msr) {
730 case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
731 case MSR_MTRRfix64K_00000:
732 case MSR_MTRRfix16K_80000:
733 case MSR_MTRRfix16K_A0000:
734 case MSR_MTRRfix4K_C0000:
735 case MSR_MTRRfix4K_C8000:
736 case MSR_MTRRfix4K_D0000:
737 case MSR_MTRRfix4K_D8000:
738 case MSR_MTRRfix4K_E0000:
739 case MSR_MTRRfix4K_E8000:
740 case MSR_MTRRfix4K_F0000:
741 case MSR_MTRRfix4K_F8000:
742 case MSR_MTRRdefType:
743 case MSR_IA32_CR_PAT:
744 return true;
745 case 0x2f8:
746 return true;
748 return false;
751 static bool valid_pat_type(unsigned t)
753 return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
756 static bool valid_mtrr_type(unsigned t)
758 return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
761 static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
763 int i;
765 if (!msr_mtrr_valid(msr))
766 return false;
768 if (msr == MSR_IA32_CR_PAT) {
769 for (i = 0; i < 8; i++)
770 if (!valid_pat_type((data >> (i * 8)) & 0xff))
771 return false;
772 return true;
773 } else if (msr == MSR_MTRRdefType) {
774 if (data & ~0xcff)
775 return false;
776 return valid_mtrr_type(data & 0xff);
777 } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
778 for (i = 0; i < 8 ; i++)
779 if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
780 return false;
781 return true;
784 /* variable MTRRs */
785 return valid_mtrr_type(data & 0xff);
788 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
790 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
792 if (!mtrr_valid(vcpu, msr, data))
793 return 1;
795 if (msr == MSR_MTRRdefType) {
796 vcpu->arch.mtrr_state.def_type = data;
797 vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
798 } else if (msr == MSR_MTRRfix64K_00000)
799 p[0] = data;
800 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
801 p[1 + msr - MSR_MTRRfix16K_80000] = data;
802 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
803 p[3 + msr - MSR_MTRRfix4K_C0000] = data;
804 else if (msr == MSR_IA32_CR_PAT)
805 vcpu->arch.pat = data;
806 else { /* Variable MTRRs */
807 int idx, is_mtrr_mask;
808 u64 *pt;
810 idx = (msr - 0x200) / 2;
811 is_mtrr_mask = msr - 0x200 - 2 * idx;
812 if (!is_mtrr_mask)
813 pt =
814 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
815 else
816 pt =
817 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
818 *pt = data;
821 kvm_mmu_reset_context(vcpu);
822 return 0;
825 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
827 u64 mcg_cap = vcpu->arch.mcg_cap;
828 unsigned bank_num = mcg_cap & 0xff;
830 switch (msr) {
831 case MSR_IA32_MCG_STATUS:
832 vcpu->arch.mcg_status = data;
833 break;
834 case MSR_IA32_MCG_CTL:
835 if (!(mcg_cap & MCG_CTL_P))
836 return 1;
837 if (data != 0 && data != ~(u64)0)
838 return -1;
839 vcpu->arch.mcg_ctl = data;
840 break;
841 default:
842 if (msr >= MSR_IA32_MC0_CTL &&
843 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
844 u32 offset = msr - MSR_IA32_MC0_CTL;
845 /* only 0 or all 1s can be written to IA32_MCi_CTL */
846 if ((offset & 0x3) == 0 &&
847 data != 0 && data != ~(u64)0)
848 return -1;
849 vcpu->arch.mce_banks[offset] = data;
850 break;
852 return 1;
854 return 0;
857 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
859 switch (msr) {
860 case MSR_EFER:
861 set_efer(vcpu, data);
862 break;
863 case MSR_K7_HWCR:
864 data &= ~(u64)0x40; /* ignore flush filter disable */
865 if (data != 0) {
866 pr_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
867 data);
868 return 1;
870 break;
871 case MSR_FAM10H_MMIO_CONF_BASE:
872 if (data != 0) {
873 pr_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
874 "0x%llx\n", data);
875 return 1;
877 break;
878 case MSR_AMD64_NB_CFG:
879 break;
880 case MSR_IA32_DEBUGCTLMSR:
881 if (!data) {
882 /* We support the non-activated case already */
883 break;
884 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
885 /* Values other than LBR and BTF are vendor-specific,
886 thus reserved and should throw a #GP */
887 return 1;
889 pr_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
890 __func__, data);
891 break;
892 case MSR_IA32_UCODE_REV:
893 case MSR_IA32_UCODE_WRITE:
894 case MSR_VM_HSAVE_PA:
895 case MSR_AMD64_PATCH_LOADER:
896 break;
897 case 0x200 ... 0x2ff:
898 return set_msr_mtrr(vcpu, msr, data);
899 case MSR_IA32_APICBASE:
900 kvm_set_apic_base(vcpu, data);
901 break;
902 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
903 return kvm_x2apic_msr_write(vcpu, msr, data);
904 case MSR_IA32_MISC_ENABLE:
905 vcpu->arch.ia32_misc_enable_msr = data;
906 break;
907 case MSR_KVM_WALL_CLOCK:
908 vcpu->kvm->arch.wall_clock = data;
909 kvm_write_wall_clock(vcpu->kvm, data);
910 break;
911 case MSR_KVM_SYSTEM_TIME: {
912 if (vcpu->arch.time_page) {
913 kvm_release_page_dirty(vcpu->arch.time_page);
914 vcpu->arch.time_page = NULL;
917 vcpu->arch.time = data;
919 /* we verify if the enable bit is set... */
920 if (!(data & 1))
921 break;
923 /* ...but clean it before doing the actual write */
924 vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
926 vcpu->arch.time_page =
927 gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
929 if (is_error_page(vcpu->arch.time_page)) {
930 kvm_release_page_clean(vcpu->arch.time_page);
931 vcpu->arch.time_page = NULL;
934 kvm_request_guest_time_update(vcpu);
935 break;
937 case MSR_IA32_MCG_CTL:
938 case MSR_IA32_MCG_STATUS:
939 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
940 return set_msr_mce(vcpu, msr, data);
942 /* Performance counters are not protected by a CPUID bit,
943 * so we should check all of them in the generic path for the sake of
944 * cross vendor migration.
945 * Writing a zero into the event select MSRs disables them,
946 * which we perfectly emulate ;-). Any other value should be at least
947 * reported, some guests depend on them.
949 case MSR_P6_EVNTSEL0:
950 case MSR_P6_EVNTSEL1:
951 case MSR_K7_EVNTSEL0:
952 case MSR_K7_EVNTSEL1:
953 case MSR_K7_EVNTSEL2:
954 case MSR_K7_EVNTSEL3:
955 if (data != 0)
956 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
957 "0x%x data 0x%llx\n", msr, data);
958 break;
959 /* at least RHEL 4 unconditionally writes to the perfctr registers,
960 * so we ignore writes to make it happy.
962 case MSR_P6_PERFCTR0:
963 case MSR_P6_PERFCTR1:
964 case MSR_K7_PERFCTR0:
965 case MSR_K7_PERFCTR1:
966 case MSR_K7_PERFCTR2:
967 case MSR_K7_PERFCTR3:
968 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
969 "0x%x data 0x%llx\n", msr, data);
970 break;
971 default:
972 if (!ignore_msrs) {
973 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
974 msr, data);
975 return 1;
976 } else {
977 pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
978 msr, data);
979 break;
982 return 0;
984 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
988 * Reads an msr value (of 'msr_index') into 'pdata'.
989 * Returns 0 on success, non-0 otherwise.
990 * Assumes vcpu_load() was already called.
992 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
994 return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
997 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
999 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1001 if (!msr_mtrr_valid(msr))
1002 return 1;
1004 if (msr == MSR_MTRRdefType)
1005 *pdata = vcpu->arch.mtrr_state.def_type +
1006 (vcpu->arch.mtrr_state.enabled << 10);
1007 else if (msr == MSR_MTRRfix64K_00000)
1008 *pdata = p[0];
1009 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1010 *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
1011 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1012 *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
1013 else if (msr == MSR_IA32_CR_PAT)
1014 *pdata = vcpu->arch.pat;
1015 else { /* Variable MTRRs */
1016 int idx, is_mtrr_mask;
1017 u64 *pt;
1019 idx = (msr - 0x200) / 2;
1020 is_mtrr_mask = msr - 0x200 - 2 * idx;
1021 if (!is_mtrr_mask)
1022 pt =
1023 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1024 else
1025 pt =
1026 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1027 *pdata = *pt;
1030 return 0;
1033 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1035 u64 data;
1036 u64 mcg_cap = vcpu->arch.mcg_cap;
1037 unsigned bank_num = mcg_cap & 0xff;
1039 switch (msr) {
1040 case MSR_IA32_P5_MC_ADDR:
1041 case MSR_IA32_P5_MC_TYPE:
1042 data = 0;
1043 break;
1044 case MSR_IA32_MCG_CAP:
1045 data = vcpu->arch.mcg_cap;
1046 break;
1047 case MSR_IA32_MCG_CTL:
1048 if (!(mcg_cap & MCG_CTL_P))
1049 return 1;
1050 data = vcpu->arch.mcg_ctl;
1051 break;
1052 case MSR_IA32_MCG_STATUS:
1053 data = vcpu->arch.mcg_status;
1054 break;
1055 default:
1056 if (msr >= MSR_IA32_MC0_CTL &&
1057 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1058 u32 offset = msr - MSR_IA32_MC0_CTL;
1059 data = vcpu->arch.mce_banks[offset];
1060 break;
1062 return 1;
1064 *pdata = data;
1065 return 0;
1068 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1070 u64 data;
1072 switch (msr) {
1073 case MSR_IA32_PLATFORM_ID:
1074 case MSR_IA32_UCODE_REV:
1075 case MSR_IA32_EBL_CR_POWERON:
1076 case MSR_IA32_DEBUGCTLMSR:
1077 case MSR_IA32_LASTBRANCHFROMIP:
1078 case MSR_IA32_LASTBRANCHTOIP:
1079 case MSR_IA32_LASTINTFROMIP:
1080 case MSR_IA32_LASTINTTOIP:
1081 case MSR_K8_SYSCFG:
1082 case MSR_K7_HWCR:
1083 case MSR_VM_HSAVE_PA:
1084 case MSR_P6_PERFCTR0:
1085 case MSR_P6_PERFCTR1:
1086 case MSR_P6_EVNTSEL0:
1087 case MSR_P6_EVNTSEL1:
1088 case MSR_K7_EVNTSEL0:
1089 case MSR_K7_PERFCTR0:
1090 case MSR_K8_INT_PENDING_MSG:
1091 case MSR_AMD64_NB_CFG:
1092 case MSR_FAM10H_MMIO_CONF_BASE:
1093 data = 0;
1094 break;
1095 case MSR_MTRRcap:
1096 data = 0x500 | KVM_NR_VAR_MTRR;
1097 break;
1098 case 0x200 ... 0x2ff:
1099 return get_msr_mtrr(vcpu, msr, pdata);
1100 case 0xcd: /* fsb frequency */
1101 data = 3;
1102 break;
1103 case MSR_IA32_APICBASE:
1104 data = kvm_get_apic_base(vcpu);
1105 break;
1106 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1107 return kvm_x2apic_msr_read(vcpu, msr, pdata);
1108 break;
1109 case MSR_IA32_MISC_ENABLE:
1110 data = vcpu->arch.ia32_misc_enable_msr;
1111 break;
1112 case MSR_IA32_PERF_STATUS:
1113 /* TSC increment by tick */
1114 data = 1000ULL;
1115 /* CPU multiplier */
1116 data |= (((uint64_t)4ULL) << 40);
1117 break;
1118 case MSR_EFER:
1119 data = vcpu->arch.shadow_efer;
1120 break;
1121 case MSR_KVM_WALL_CLOCK:
1122 data = vcpu->kvm->arch.wall_clock;
1123 break;
1124 case MSR_KVM_SYSTEM_TIME:
1125 data = vcpu->arch.time;
1126 break;
1127 case MSR_IA32_P5_MC_ADDR:
1128 case MSR_IA32_P5_MC_TYPE:
1129 case MSR_IA32_MCG_CAP:
1130 case MSR_IA32_MCG_CTL:
1131 case MSR_IA32_MCG_STATUS:
1132 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1133 return get_msr_mce(vcpu, msr, pdata);
1134 default:
1135 if (!ignore_msrs) {
1136 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
1137 return 1;
1138 } else {
1139 pr_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
1140 data = 0;
1142 break;
1144 *pdata = data;
1145 return 0;
1147 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
1150 * Read or write a bunch of msrs. All parameters are kernel addresses.
1152 * @return number of msrs set successfully.
1154 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
1155 struct kvm_msr_entry *entries,
1156 int (*do_msr)(struct kvm_vcpu *vcpu,
1157 unsigned index, u64 *data))
1159 int i;
1161 vcpu_load(vcpu);
1163 down_read(&vcpu->kvm->slots_lock);
1164 for (i = 0; i < msrs->nmsrs; ++i)
1165 if (do_msr(vcpu, entries[i].index, &entries[i].data))
1166 break;
1167 up_read(&vcpu->kvm->slots_lock);
1169 vcpu_put(vcpu);
1171 return i;
1175 * Read or write a bunch of msrs. Parameters are user addresses.
1177 * @return number of msrs set successfully.
1179 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
1180 int (*do_msr)(struct kvm_vcpu *vcpu,
1181 unsigned index, u64 *data),
1182 int writeback)
1184 struct kvm_msrs msrs;
1185 struct kvm_msr_entry *entries;
1186 int r, n;
1187 unsigned size;
1189 r = -EFAULT;
1190 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
1191 goto out;
1193 r = -E2BIG;
1194 if (msrs.nmsrs >= MAX_IO_MSRS)
1195 goto out;
1197 r = -ENOMEM;
1198 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
1199 entries = vmalloc(size);
1200 if (!entries)
1201 goto out;
1203 r = -EFAULT;
1204 if (copy_from_user(entries, user_msrs->entries, size))
1205 goto out_free;
1207 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
1208 if (r < 0)
1209 goto out_free;
1211 r = -EFAULT;
1212 if (writeback && copy_to_user(user_msrs->entries, entries, size))
1213 goto out_free;
1215 r = n;
1217 out_free:
1218 vfree(entries);
1219 out:
1220 return r;
1223 int kvm_dev_ioctl_check_extension(long ext)
1225 int r;
1227 switch (ext) {
1228 case KVM_CAP_IRQCHIP:
1229 case KVM_CAP_HLT:
1230 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
1231 case KVM_CAP_SET_TSS_ADDR:
1232 case KVM_CAP_EXT_CPUID:
1233 case KVM_CAP_CLOCKSOURCE:
1234 case KVM_CAP_PIT:
1235 case KVM_CAP_NOP_IO_DELAY:
1236 case KVM_CAP_MP_STATE:
1237 case KVM_CAP_SYNC_MMU:
1238 case KVM_CAP_REINJECT_CONTROL:
1239 case KVM_CAP_IRQ_INJECT_STATUS:
1240 case KVM_CAP_ASSIGN_DEV_IRQ:
1241 case KVM_CAP_IRQFD:
1242 case KVM_CAP_IOEVENTFD:
1243 case KVM_CAP_PIT2:
1244 case KVM_CAP_PIT_STATE2:
1245 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
1246 r = 1;
1247 break;
1248 case KVM_CAP_COALESCED_MMIO:
1249 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
1250 break;
1251 case KVM_CAP_VAPIC:
1252 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
1253 break;
1254 case KVM_CAP_NR_VCPUS:
1255 r = KVM_MAX_VCPUS;
1256 break;
1257 case KVM_CAP_NR_MEMSLOTS:
1258 r = KVM_MEMORY_SLOTS;
1259 break;
1260 case KVM_CAP_PV_MMU: /* obsolete */
1261 r = 0;
1262 break;
1263 case KVM_CAP_IOMMU:
1264 r = iommu_found();
1265 break;
1266 case KVM_CAP_MCE:
1267 r = KVM_MAX_MCE_BANKS;
1268 break;
1269 default:
1270 r = 0;
1271 break;
1273 return r;
1277 long kvm_arch_dev_ioctl(struct file *filp,
1278 unsigned int ioctl, unsigned long arg)
1280 void __user *argp = (void __user *)arg;
1281 long r;
1283 switch (ioctl) {
1284 case KVM_GET_MSR_INDEX_LIST: {
1285 struct kvm_msr_list __user *user_msr_list = argp;
1286 struct kvm_msr_list msr_list;
1287 unsigned n;
1289 r = -EFAULT;
1290 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
1291 goto out;
1292 n = msr_list.nmsrs;
1293 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
1294 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
1295 goto out;
1296 r = -E2BIG;
1297 if (n < msr_list.nmsrs)
1298 goto out;
1299 r = -EFAULT;
1300 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
1301 num_msrs_to_save * sizeof(u32)))
1302 goto out;
1303 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
1304 &emulated_msrs,
1305 ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
1306 goto out;
1307 r = 0;
1308 break;
1310 case KVM_GET_SUPPORTED_CPUID: {
1311 struct kvm_cpuid2 __user *cpuid_arg = argp;
1312 struct kvm_cpuid2 cpuid;
1314 r = -EFAULT;
1315 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1316 goto out;
1317 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
1318 cpuid_arg->entries);
1319 if (r)
1320 goto out;
1322 r = -EFAULT;
1323 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1324 goto out;
1325 r = 0;
1326 break;
1328 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
1329 u64 mce_cap;
1331 mce_cap = KVM_MCE_CAP_SUPPORTED;
1332 r = -EFAULT;
1333 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
1334 goto out;
1335 r = 0;
1336 break;
1338 default:
1339 r = -EINVAL;
1341 out:
1342 return r;
1345 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1347 kvm_x86_ops->vcpu_load(vcpu, cpu);
1348 if (unlikely(per_cpu(cpu_tsc_khz, cpu) == 0))
1349 per_cpu(cpu_tsc_khz, cpu) = cpufreq_quick_get(cpu);
1350 kvm_request_guest_time_update(vcpu);
1353 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
1355 kvm_x86_ops->vcpu_put(vcpu);
1356 kvm_put_guest_fpu(vcpu);
1359 static int is_efer_nx(void)
1361 unsigned long long efer = 0;
1363 rdmsrl_safe(MSR_EFER, &efer);
1364 return efer & EFER_NX;
1367 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
1369 int i;
1370 struct kvm_cpuid_entry2 *e, *entry;
1372 entry = NULL;
1373 for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
1374 e = &vcpu->arch.cpuid_entries[i];
1375 if (e->function == 0x80000001) {
1376 entry = e;
1377 break;
1380 if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
1381 entry->edx &= ~(1 << 20);
1382 printk(KERN_INFO "kvm: guest NX capability removed\n");
1386 /* when an old userspace process fills a new kernel module */
1387 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
1388 struct kvm_cpuid *cpuid,
1389 struct kvm_cpuid_entry __user *entries)
1391 int r, i;
1392 struct kvm_cpuid_entry *cpuid_entries;
1394 r = -E2BIG;
1395 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1396 goto out;
1397 r = -ENOMEM;
1398 cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
1399 if (!cpuid_entries)
1400 goto out;
1401 r = -EFAULT;
1402 if (copy_from_user(cpuid_entries, entries,
1403 cpuid->nent * sizeof(struct kvm_cpuid_entry)))
1404 goto out_free;
1405 for (i = 0; i < cpuid->nent; i++) {
1406 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
1407 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
1408 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
1409 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
1410 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
1411 vcpu->arch.cpuid_entries[i].index = 0;
1412 vcpu->arch.cpuid_entries[i].flags = 0;
1413 vcpu->arch.cpuid_entries[i].padding[0] = 0;
1414 vcpu->arch.cpuid_entries[i].padding[1] = 0;
1415 vcpu->arch.cpuid_entries[i].padding[2] = 0;
1417 vcpu->arch.cpuid_nent = cpuid->nent;
1418 cpuid_fix_nx_cap(vcpu);
1419 r = 0;
1420 kvm_apic_set_version(vcpu);
1422 out_free:
1423 vfree(cpuid_entries);
1424 out:
1425 return r;
1428 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
1429 struct kvm_cpuid2 *cpuid,
1430 struct kvm_cpuid_entry2 __user *entries)
1432 int r;
1434 r = -E2BIG;
1435 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1436 goto out;
1437 r = -EFAULT;
1438 if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
1439 cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
1440 goto out;
1441 vcpu->arch.cpuid_nent = cpuid->nent;
1442 kvm_apic_set_version(vcpu);
1443 return 0;
1445 out:
1446 return r;
1449 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
1450 struct kvm_cpuid2 *cpuid,
1451 struct kvm_cpuid_entry2 __user *entries)
1453 int r;
1455 r = -E2BIG;
1456 if (cpuid->nent < vcpu->arch.cpuid_nent)
1457 goto out;
1458 r = -EFAULT;
1459 if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
1460 vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
1461 goto out;
1462 return 0;
1464 out:
1465 cpuid->nent = vcpu->arch.cpuid_nent;
1466 return r;
1469 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1470 u32 index)
1472 entry->function = function;
1473 entry->index = index;
1474 cpuid_count(entry->function, entry->index,
1475 &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
1476 entry->flags = 0;
1479 #define F(x) bit(X86_FEATURE_##x)
1481 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1482 u32 index, int *nent, int maxnent)
1484 unsigned f_nx = is_efer_nx() ? F(NX) : 0;
1485 unsigned f_gbpages = kvm_x86_ops->gb_page_enable() ? F(GBPAGES) : 0;
1486 #ifdef CONFIG_X86_64
1487 unsigned f_lm = F(LM);
1488 #else
1489 unsigned f_lm = 0;
1490 #endif
1492 /* cpuid 1.edx */
1493 const u32 kvm_supported_word0_x86_features =
1494 F(FPU) | F(VME) | F(DE) | F(PSE) |
1495 F(TSC) | F(MSR) | F(PAE) | F(MCE) |
1496 F(CX8) | F(APIC) | 0 /* Reserved */ | F(SEP) |
1497 F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
1498 F(PAT) | F(PSE36) | 0 /* PSN */ | F(CLFLSH) |
1499 0 /* Reserved, DS, ACPI */ | F(MMX) |
1500 F(FXSR) | F(XMM) | F(XMM2) | F(SELFSNOOP) |
1501 0 /* HTT, TM, Reserved, PBE */;
1502 /* cpuid 0x80000001.edx */
1503 const u32 kvm_supported_word1_x86_features =
1504 F(FPU) | F(VME) | F(DE) | F(PSE) |
1505 F(TSC) | F(MSR) | F(PAE) | F(MCE) |
1506 F(CX8) | F(APIC) | 0 /* Reserved */ | F(SYSCALL) |
1507 F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
1508 F(PAT) | F(PSE36) | 0 /* Reserved */ |
1509 f_nx | 0 /* Reserved */ | F(MMXEXT) | F(MMX) |
1510 F(FXSR) | F(FXSR_OPT) | f_gbpages | 0 /* RDTSCP */ |
1511 0 /* Reserved */ | f_lm | F(3DNOWEXT) | F(3DNOW);
1512 /* cpuid 1.ecx */
1513 const u32 kvm_supported_word4_x86_features =
1514 F(XMM3) | 0 /* Reserved, DTES64, MONITOR */ |
1515 0 /* DS-CPL, VMX, SMX, EST */ |
1516 0 /* TM2 */ | F(SSSE3) | 0 /* CNXT-ID */ | 0 /* Reserved */ |
1517 0 /* Reserved */ | F(CX16) | 0 /* xTPR Update, PDCM */ |
1518 0 /* Reserved, DCA */ | F(XMM4_1) |
1519 F(XMM4_2) | F(X2APIC) | F(MOVBE) | F(POPCNT) |
1520 0 /* Reserved, XSAVE, OSXSAVE */;
1521 /* cpuid 0x80000001.ecx */
1522 const u32 kvm_supported_word6_x86_features =
1523 F(LAHF_LM) | F(CMP_LEGACY) | F(SVM) | 0 /* ExtApicSpace */ |
1524 F(CR8_LEGACY) | F(ABM) | F(SSE4A) | F(MISALIGNSSE) |
1525 F(3DNOWPREFETCH) | 0 /* OSVW */ | 0 /* IBS */ | F(SSE5) |
1526 0 /* SKINIT */ | 0 /* WDT */;
1528 /* all calls to cpuid_count() should be made on the same cpu */
1529 get_cpu();
1530 do_cpuid_1_ent(entry, function, index);
1531 ++*nent;
1533 switch (function) {
1534 case 0:
1535 entry->eax = min(entry->eax, (u32)0xb);
1536 break;
1537 case 1:
1538 entry->edx &= kvm_supported_word0_x86_features;
1539 entry->ecx &= kvm_supported_word4_x86_features;
1540 /* we support x2apic emulation even if host does not support
1541 * it since we emulate x2apic in software */
1542 entry->ecx |= F(X2APIC);
1543 break;
1544 /* function 2 entries are STATEFUL. That is, repeated cpuid commands
1545 * may return different values. This forces us to get_cpu() before
1546 * issuing the first command, and also to emulate this annoying behavior
1547 * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
1548 case 2: {
1549 int t, times = entry->eax & 0xff;
1551 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1552 entry->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
1553 for (t = 1; t < times && *nent < maxnent; ++t) {
1554 do_cpuid_1_ent(&entry[t], function, 0);
1555 entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1556 ++*nent;
1558 break;
1560 /* function 4 and 0xb have additional index. */
1561 case 4: {
1562 int i, cache_type;
1564 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1565 /* read more entries until cache_type is zero */
1566 for (i = 1; *nent < maxnent; ++i) {
1567 cache_type = entry[i - 1].eax & 0x1f;
1568 if (!cache_type)
1569 break;
1570 do_cpuid_1_ent(&entry[i], function, i);
1571 entry[i].flags |=
1572 KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1573 ++*nent;
1575 break;
1577 case 0xb: {
1578 int i, level_type;
1580 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1581 /* read more entries until level_type is zero */
1582 for (i = 1; *nent < maxnent; ++i) {
1583 level_type = entry[i - 1].ecx & 0xff00;
1584 if (!level_type)
1585 break;
1586 do_cpuid_1_ent(&entry[i], function, i);
1587 entry[i].flags |=
1588 KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1589 ++*nent;
1591 break;
1593 case 0x80000000:
1594 entry->eax = min(entry->eax, 0x8000001a);
1595 break;
1596 case 0x80000001:
1597 entry->edx &= kvm_supported_word1_x86_features;
1598 entry->ecx &= kvm_supported_word6_x86_features;
1599 break;
1601 put_cpu();
1604 #undef F
1606 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
1607 struct kvm_cpuid_entry2 __user *entries)
1609 struct kvm_cpuid_entry2 *cpuid_entries;
1610 int limit, nent = 0, r = -E2BIG;
1611 u32 func;
1613 if (cpuid->nent < 1)
1614 goto out;
1615 if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1616 cpuid->nent = KVM_MAX_CPUID_ENTRIES;
1617 r = -ENOMEM;
1618 cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
1619 if (!cpuid_entries)
1620 goto out;
1622 do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
1623 limit = cpuid_entries[0].eax;
1624 for (func = 1; func <= limit && nent < cpuid->nent; ++func)
1625 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1626 &nent, cpuid->nent);
1627 r = -E2BIG;
1628 if (nent >= cpuid->nent)
1629 goto out_free;
1631 do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
1632 limit = cpuid_entries[nent - 1].eax;
1633 for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
1634 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1635 &nent, cpuid->nent);
1636 r = -E2BIG;
1637 if (nent >= cpuid->nent)
1638 goto out_free;
1640 r = -EFAULT;
1641 if (copy_to_user(entries, cpuid_entries,
1642 nent * sizeof(struct kvm_cpuid_entry2)))
1643 goto out_free;
1644 cpuid->nent = nent;
1645 r = 0;
1647 out_free:
1648 vfree(cpuid_entries);
1649 out:
1650 return r;
1653 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
1654 struct kvm_lapic_state *s)
1656 vcpu_load(vcpu);
1657 memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
1658 vcpu_put(vcpu);
1660 return 0;
1663 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
1664 struct kvm_lapic_state *s)
1666 vcpu_load(vcpu);
1667 memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
1668 kvm_apic_post_state_restore(vcpu);
1669 update_cr8_intercept(vcpu);
1670 vcpu_put(vcpu);
1672 return 0;
1675 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
1676 struct kvm_interrupt *irq)
1678 if (irq->irq < 0 || irq->irq >= 256)
1679 return -EINVAL;
1680 if (irqchip_in_kernel(vcpu->kvm))
1681 return -ENXIO;
1682 vcpu_load(vcpu);
1684 kvm_queue_interrupt(vcpu, irq->irq, false);
1686 vcpu_put(vcpu);
1688 return 0;
1691 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
1693 vcpu_load(vcpu);
1694 kvm_inject_nmi(vcpu);
1695 vcpu_put(vcpu);
1697 return 0;
1700 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
1701 struct kvm_tpr_access_ctl *tac)
1703 if (tac->flags)
1704 return -EINVAL;
1705 vcpu->arch.tpr_access_reporting = !!tac->enabled;
1706 return 0;
1709 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
1710 u64 mcg_cap)
1712 int r;
1713 unsigned bank_num = mcg_cap & 0xff, bank;
1715 r = -EINVAL;
1716 if (!bank_num)
1717 goto out;
1718 if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
1719 goto out;
1720 r = 0;
1721 vcpu->arch.mcg_cap = mcg_cap;
1722 /* Init IA32_MCG_CTL to all 1s */
1723 if (mcg_cap & MCG_CTL_P)
1724 vcpu->arch.mcg_ctl = ~(u64)0;
1725 /* Init IA32_MCi_CTL to all 1s */
1726 for (bank = 0; bank < bank_num; bank++)
1727 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
1728 out:
1729 return r;
1732 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
1733 struct kvm_x86_mce *mce)
1735 u64 mcg_cap = vcpu->arch.mcg_cap;
1736 unsigned bank_num = mcg_cap & 0xff;
1737 u64 *banks = vcpu->arch.mce_banks;
1739 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
1740 return -EINVAL;
1742 * if IA32_MCG_CTL is not all 1s, the uncorrected error
1743 * reporting is disabled
1745 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
1746 vcpu->arch.mcg_ctl != ~(u64)0)
1747 return 0;
1748 banks += 4 * mce->bank;
1750 * if IA32_MCi_CTL is not all 1s, the uncorrected error
1751 * reporting is disabled for the bank
1753 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
1754 return 0;
1755 if (mce->status & MCI_STATUS_UC) {
1756 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
1757 !(vcpu->arch.cr4 & X86_CR4_MCE)) {
1758 printk(KERN_DEBUG "kvm: set_mce: "
1759 "injects mce exception while "
1760 "previous one is in progress!\n");
1761 set_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests);
1762 return 0;
1764 if (banks[1] & MCI_STATUS_VAL)
1765 mce->status |= MCI_STATUS_OVER;
1766 banks[2] = mce->addr;
1767 banks[3] = mce->misc;
1768 vcpu->arch.mcg_status = mce->mcg_status;
1769 banks[1] = mce->status;
1770 kvm_queue_exception(vcpu, MC_VECTOR);
1771 } else if (!(banks[1] & MCI_STATUS_VAL)
1772 || !(banks[1] & MCI_STATUS_UC)) {
1773 if (banks[1] & MCI_STATUS_VAL)
1774 mce->status |= MCI_STATUS_OVER;
1775 banks[2] = mce->addr;
1776 banks[3] = mce->misc;
1777 banks[1] = mce->status;
1778 } else
1779 banks[1] |= MCI_STATUS_OVER;
1780 return 0;
1783 long kvm_arch_vcpu_ioctl(struct file *filp,
1784 unsigned int ioctl, unsigned long arg)
1786 struct kvm_vcpu *vcpu = filp->private_data;
1787 void __user *argp = (void __user *)arg;
1788 int r;
1789 struct kvm_lapic_state *lapic = NULL;
1791 switch (ioctl) {
1792 case KVM_GET_LAPIC: {
1793 lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
1795 r = -ENOMEM;
1796 if (!lapic)
1797 goto out;
1798 r = kvm_vcpu_ioctl_get_lapic(vcpu, lapic);
1799 if (r)
1800 goto out;
1801 r = -EFAULT;
1802 if (copy_to_user(argp, lapic, sizeof(struct kvm_lapic_state)))
1803 goto out;
1804 r = 0;
1805 break;
1807 case KVM_SET_LAPIC: {
1808 lapic = kmalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
1809 r = -ENOMEM;
1810 if (!lapic)
1811 goto out;
1812 r = -EFAULT;
1813 if (copy_from_user(lapic, argp, sizeof(struct kvm_lapic_state)))
1814 goto out;
1815 r = kvm_vcpu_ioctl_set_lapic(vcpu, lapic);
1816 if (r)
1817 goto out;
1818 r = 0;
1819 break;
1821 case KVM_INTERRUPT: {
1822 struct kvm_interrupt irq;
1824 r = -EFAULT;
1825 if (copy_from_user(&irq, argp, sizeof irq))
1826 goto out;
1827 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
1828 if (r)
1829 goto out;
1830 r = 0;
1831 break;
1833 case KVM_NMI: {
1834 r = kvm_vcpu_ioctl_nmi(vcpu);
1835 if (r)
1836 goto out;
1837 r = 0;
1838 break;
1840 case KVM_SET_CPUID: {
1841 struct kvm_cpuid __user *cpuid_arg = argp;
1842 struct kvm_cpuid cpuid;
1844 r = -EFAULT;
1845 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1846 goto out;
1847 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
1848 if (r)
1849 goto out;
1850 break;
1852 case KVM_SET_CPUID2: {
1853 struct kvm_cpuid2 __user *cpuid_arg = argp;
1854 struct kvm_cpuid2 cpuid;
1856 r = -EFAULT;
1857 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1858 goto out;
1859 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
1860 cpuid_arg->entries);
1861 if (r)
1862 goto out;
1863 break;
1865 case KVM_GET_CPUID2: {
1866 struct kvm_cpuid2 __user *cpuid_arg = argp;
1867 struct kvm_cpuid2 cpuid;
1869 r = -EFAULT;
1870 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1871 goto out;
1872 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
1873 cpuid_arg->entries);
1874 if (r)
1875 goto out;
1876 r = -EFAULT;
1877 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1878 goto out;
1879 r = 0;
1880 break;
1882 case KVM_GET_MSRS:
1883 r = msr_io(vcpu, argp, kvm_get_msr, 1);
1884 break;
1885 case KVM_SET_MSRS:
1886 r = msr_io(vcpu, argp, do_set_msr, 0);
1887 break;
1888 case KVM_TPR_ACCESS_REPORTING: {
1889 struct kvm_tpr_access_ctl tac;
1891 r = -EFAULT;
1892 if (copy_from_user(&tac, argp, sizeof tac))
1893 goto out;
1894 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
1895 if (r)
1896 goto out;
1897 r = -EFAULT;
1898 if (copy_to_user(argp, &tac, sizeof tac))
1899 goto out;
1900 r = 0;
1901 break;
1903 case KVM_SET_VAPIC_ADDR: {
1904 struct kvm_vapic_addr va;
1906 r = -EINVAL;
1907 if (!irqchip_in_kernel(vcpu->kvm))
1908 goto out;
1909 r = -EFAULT;
1910 if (copy_from_user(&va, argp, sizeof va))
1911 goto out;
1912 r = 0;
1913 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
1914 break;
1916 case KVM_X86_SETUP_MCE: {
1917 u64 mcg_cap;
1919 r = -EFAULT;
1920 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
1921 goto out;
1922 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
1923 break;
1925 case KVM_X86_SET_MCE: {
1926 struct kvm_x86_mce mce;
1928 r = -EFAULT;
1929 if (copy_from_user(&mce, argp, sizeof mce))
1930 goto out;
1931 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
1932 break;
1934 default:
1935 r = -EINVAL;
1937 out:
1938 kfree(lapic);
1939 return r;
1942 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
1944 int ret;
1946 if (addr > (unsigned int)(-3 * PAGE_SIZE))
1947 return -1;
1948 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
1949 return ret;
1952 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
1953 u64 ident_addr)
1955 kvm->arch.ept_identity_map_addr = ident_addr;
1956 return 0;
1959 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
1960 u32 kvm_nr_mmu_pages)
1962 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
1963 return -EINVAL;
1965 down_write(&kvm->slots_lock);
1966 spin_lock(&kvm->mmu_lock);
1968 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
1969 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
1971 spin_unlock(&kvm->mmu_lock);
1972 up_write(&kvm->slots_lock);
1973 return 0;
1976 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
1978 return kvm->arch.n_alloc_mmu_pages;
1981 gfn_t unalias_gfn(struct kvm *kvm, gfn_t gfn)
1983 int i;
1984 struct kvm_mem_alias *alias;
1986 for (i = 0; i < kvm->arch.naliases; ++i) {
1987 alias = &kvm->arch.aliases[i];
1988 if (gfn >= alias->base_gfn
1989 && gfn < alias->base_gfn + alias->npages)
1990 return alias->target_gfn + gfn - alias->base_gfn;
1992 return gfn;
1996 * Set a new alias region. Aliases map a portion of physical memory into
1997 * another portion. This is useful for memory windows, for example the PC
1998 * VGA region.
2000 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
2001 struct kvm_memory_alias *alias)
2003 int r, n;
2004 struct kvm_mem_alias *p;
2006 r = -EINVAL;
2007 /* General sanity checks */
2008 if (alias->memory_size & (PAGE_SIZE - 1))
2009 goto out;
2010 if (alias->guest_phys_addr & (PAGE_SIZE - 1))
2011 goto out;
2012 if (alias->slot >= KVM_ALIAS_SLOTS)
2013 goto out;
2014 if (alias->guest_phys_addr + alias->memory_size
2015 < alias->guest_phys_addr)
2016 goto out;
2017 if (alias->target_phys_addr + alias->memory_size
2018 < alias->target_phys_addr)
2019 goto out;
2021 down_write(&kvm->slots_lock);
2022 spin_lock(&kvm->mmu_lock);
2024 p = &kvm->arch.aliases[alias->slot];
2025 p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
2026 p->npages = alias->memory_size >> PAGE_SHIFT;
2027 p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
2029 for (n = KVM_ALIAS_SLOTS; n > 0; --n)
2030 if (kvm->arch.aliases[n - 1].npages)
2031 break;
2032 kvm->arch.naliases = n;
2034 spin_unlock(&kvm->mmu_lock);
2035 kvm_mmu_zap_all(kvm);
2037 up_write(&kvm->slots_lock);
2039 return 0;
2041 out:
2042 return r;
2045 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2047 int r;
2049 r = 0;
2050 switch (chip->chip_id) {
2051 case KVM_IRQCHIP_PIC_MASTER:
2052 memcpy(&chip->chip.pic,
2053 &pic_irqchip(kvm)->pics[0],
2054 sizeof(struct kvm_pic_state));
2055 break;
2056 case KVM_IRQCHIP_PIC_SLAVE:
2057 memcpy(&chip->chip.pic,
2058 &pic_irqchip(kvm)->pics[1],
2059 sizeof(struct kvm_pic_state));
2060 break;
2061 case KVM_IRQCHIP_IOAPIC:
2062 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
2063 break;
2064 default:
2065 r = -EINVAL;
2066 break;
2068 return r;
2071 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2073 int r;
2075 r = 0;
2076 switch (chip->chip_id) {
2077 case KVM_IRQCHIP_PIC_MASTER:
2078 spin_lock(&pic_irqchip(kvm)->lock);
2079 memcpy(&pic_irqchip(kvm)->pics[0],
2080 &chip->chip.pic,
2081 sizeof(struct kvm_pic_state));
2082 spin_unlock(&pic_irqchip(kvm)->lock);
2083 break;
2084 case KVM_IRQCHIP_PIC_SLAVE:
2085 spin_lock(&pic_irqchip(kvm)->lock);
2086 memcpy(&pic_irqchip(kvm)->pics[1],
2087 &chip->chip.pic,
2088 sizeof(struct kvm_pic_state));
2089 spin_unlock(&pic_irqchip(kvm)->lock);
2090 break;
2091 case KVM_IRQCHIP_IOAPIC:
2092 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
2093 break;
2094 default:
2095 r = -EINVAL;
2096 break;
2098 kvm_pic_update_irq(pic_irqchip(kvm));
2099 return r;
2102 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2104 int r = 0;
2106 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2107 memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
2108 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2109 return r;
2112 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2114 int r = 0;
2116 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2117 memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
2118 kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
2119 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2120 return r;
2123 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2125 int r = 0;
2127 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2128 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
2129 sizeof(ps->channels));
2130 ps->flags = kvm->arch.vpit->pit_state.flags;
2131 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2132 return r;
2135 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2137 int r = 0, start = 0;
2138 u32 prev_legacy, cur_legacy;
2139 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2140 prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
2141 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
2142 if (!prev_legacy && cur_legacy)
2143 start = 1;
2144 memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
2145 sizeof(kvm->arch.vpit->pit_state.channels));
2146 kvm->arch.vpit->pit_state.flags = ps->flags;
2147 kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
2148 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2149 return r;
2152 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
2153 struct kvm_reinject_control *control)
2155 if (!kvm->arch.vpit)
2156 return -ENXIO;
2157 mutex_lock(&kvm->arch.vpit->pit_state.lock);
2158 kvm->arch.vpit->pit_state.pit_timer.reinject = control->pit_reinject;
2159 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2160 return 0;
2164 * Get (and clear) the dirty memory log for a memory slot.
2166 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
2167 struct kvm_dirty_log *log)
2169 int r;
2170 int n;
2171 struct kvm_memory_slot *memslot;
2172 int is_dirty = 0;
2174 down_write(&kvm->slots_lock);
2176 r = kvm_get_dirty_log(kvm, log, &is_dirty);
2177 if (r)
2178 goto out;
2180 /* If nothing is dirty, don't bother messing with page tables. */
2181 if (is_dirty) {
2182 spin_lock(&kvm->mmu_lock);
2183 kvm_mmu_slot_remove_write_access(kvm, log->slot);
2184 spin_unlock(&kvm->mmu_lock);
2185 memslot = &kvm->memslots[log->slot];
2186 n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
2187 memset(memslot->dirty_bitmap, 0, n);
2189 r = 0;
2190 out:
2191 up_write(&kvm->slots_lock);
2192 return r;
2195 long kvm_arch_vm_ioctl(struct file *filp,
2196 unsigned int ioctl, unsigned long arg)
2198 struct kvm *kvm = filp->private_data;
2199 void __user *argp = (void __user *)arg;
2200 int r = -ENOTTY;
2202 * This union makes it completely explicit to gcc-3.x
2203 * that these two variables' stack usage should be
2204 * combined, not added together.
2206 union {
2207 struct kvm_pit_state ps;
2208 struct kvm_pit_state2 ps2;
2209 struct kvm_memory_alias alias;
2210 struct kvm_pit_config pit_config;
2211 } u;
2213 switch (ioctl) {
2214 case KVM_SET_TSS_ADDR:
2215 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
2216 if (r < 0)
2217 goto out;
2218 break;
2219 case KVM_SET_IDENTITY_MAP_ADDR: {
2220 u64 ident_addr;
2222 r = -EFAULT;
2223 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
2224 goto out;
2225 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
2226 if (r < 0)
2227 goto out;
2228 break;
2230 case KVM_SET_MEMORY_REGION: {
2231 struct kvm_memory_region kvm_mem;
2232 struct kvm_userspace_memory_region kvm_userspace_mem;
2234 r = -EFAULT;
2235 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
2236 goto out;
2237 kvm_userspace_mem.slot = kvm_mem.slot;
2238 kvm_userspace_mem.flags = kvm_mem.flags;
2239 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
2240 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
2241 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
2242 if (r)
2243 goto out;
2244 break;
2246 case KVM_SET_NR_MMU_PAGES:
2247 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
2248 if (r)
2249 goto out;
2250 break;
2251 case KVM_GET_NR_MMU_PAGES:
2252 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
2253 break;
2254 case KVM_SET_MEMORY_ALIAS:
2255 r = -EFAULT;
2256 if (copy_from_user(&u.alias, argp, sizeof(struct kvm_memory_alias)))
2257 goto out;
2258 r = kvm_vm_ioctl_set_memory_alias(kvm, &u.alias);
2259 if (r)
2260 goto out;
2261 break;
2262 case KVM_CREATE_IRQCHIP:
2263 r = -ENOMEM;
2264 kvm->arch.vpic = kvm_create_pic(kvm);
2265 if (kvm->arch.vpic) {
2266 r = kvm_ioapic_init(kvm);
2267 if (r) {
2268 kfree(kvm->arch.vpic);
2269 kvm->arch.vpic = NULL;
2270 goto out;
2272 } else
2273 goto out;
2274 r = kvm_setup_default_irq_routing(kvm);
2275 if (r) {
2276 kfree(kvm->arch.vpic);
2277 kfree(kvm->arch.vioapic);
2278 goto out;
2280 break;
2281 case KVM_CREATE_PIT:
2282 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
2283 goto create_pit;
2284 case KVM_CREATE_PIT2:
2285 r = -EFAULT;
2286 if (copy_from_user(&u.pit_config, argp,
2287 sizeof(struct kvm_pit_config)))
2288 goto out;
2289 create_pit:
2290 down_write(&kvm->slots_lock);
2291 r = -EEXIST;
2292 if (kvm->arch.vpit)
2293 goto create_pit_unlock;
2294 r = -ENOMEM;
2295 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
2296 if (kvm->arch.vpit)
2297 r = 0;
2298 create_pit_unlock:
2299 up_write(&kvm->slots_lock);
2300 break;
2301 case KVM_IRQ_LINE_STATUS:
2302 case KVM_IRQ_LINE: {
2303 struct kvm_irq_level irq_event;
2305 r = -EFAULT;
2306 if (copy_from_user(&irq_event, argp, sizeof irq_event))
2307 goto out;
2308 if (irqchip_in_kernel(kvm)) {
2309 __s32 status;
2310 status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
2311 irq_event.irq, irq_event.level);
2312 if (ioctl == KVM_IRQ_LINE_STATUS) {
2313 irq_event.status = status;
2314 if (copy_to_user(argp, &irq_event,
2315 sizeof irq_event))
2316 goto out;
2318 r = 0;
2320 break;
2322 case KVM_GET_IRQCHIP: {
2323 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
2324 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
2326 r = -ENOMEM;
2327 if (!chip)
2328 goto out;
2329 r = -EFAULT;
2330 if (copy_from_user(chip, argp, sizeof *chip))
2331 goto get_irqchip_out;
2332 r = -ENXIO;
2333 if (!irqchip_in_kernel(kvm))
2334 goto get_irqchip_out;
2335 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
2336 if (r)
2337 goto get_irqchip_out;
2338 r = -EFAULT;
2339 if (copy_to_user(argp, chip, sizeof *chip))
2340 goto get_irqchip_out;
2341 r = 0;
2342 get_irqchip_out:
2343 kfree(chip);
2344 if (r)
2345 goto out;
2346 break;
2348 case KVM_SET_IRQCHIP: {
2349 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
2350 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
2352 r = -ENOMEM;
2353 if (!chip)
2354 goto out;
2355 r = -EFAULT;
2356 if (copy_from_user(chip, argp, sizeof *chip))
2357 goto set_irqchip_out;
2358 r = -ENXIO;
2359 if (!irqchip_in_kernel(kvm))
2360 goto set_irqchip_out;
2361 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
2362 if (r)
2363 goto set_irqchip_out;
2364 r = 0;
2365 set_irqchip_out:
2366 kfree(chip);
2367 if (r)
2368 goto out;
2369 break;
2371 case KVM_GET_PIT: {
2372 r = -EFAULT;
2373 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
2374 goto out;
2375 r = -ENXIO;
2376 if (!kvm->arch.vpit)
2377 goto out;
2378 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
2379 if (r)
2380 goto out;
2381 r = -EFAULT;
2382 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
2383 goto out;
2384 r = 0;
2385 break;
2387 case KVM_SET_PIT: {
2388 r = -EFAULT;
2389 if (copy_from_user(&u.ps, argp, sizeof u.ps))
2390 goto out;
2391 r = -ENXIO;
2392 if (!kvm->arch.vpit)
2393 goto out;
2394 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
2395 if (r)
2396 goto out;
2397 r = 0;
2398 break;
2400 case KVM_GET_PIT2: {
2401 r = -ENXIO;
2402 if (!kvm->arch.vpit)
2403 goto out;
2404 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
2405 if (r)
2406 goto out;
2407 r = -EFAULT;
2408 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
2409 goto out;
2410 r = 0;
2411 break;
2413 case KVM_SET_PIT2: {
2414 r = -EFAULT;
2415 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
2416 goto out;
2417 r = -ENXIO;
2418 if (!kvm->arch.vpit)
2419 goto out;
2420 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
2421 if (r)
2422 goto out;
2423 r = 0;
2424 break;
2426 case KVM_REINJECT_CONTROL: {
2427 struct kvm_reinject_control control;
2428 r = -EFAULT;
2429 if (copy_from_user(&control, argp, sizeof(control)))
2430 goto out;
2431 r = kvm_vm_ioctl_reinject(kvm, &control);
2432 if (r)
2433 goto out;
2434 r = 0;
2435 break;
2437 default:
2440 out:
2441 return r;
2444 static void kvm_init_msr_list(void)
2446 u32 dummy[2];
2447 unsigned i, j;
2449 for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
2450 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
2451 continue;
2452 if (j < i)
2453 msrs_to_save[j] = msrs_to_save[i];
2454 j++;
2456 num_msrs_to_save = j;
2459 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
2460 const void *v)
2462 if (vcpu->arch.apic &&
2463 !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, len, v))
2464 return 0;
2466 return kvm_io_bus_write(&vcpu->kvm->mmio_bus, addr, len, v);
2469 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
2471 if (vcpu->arch.apic &&
2472 !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, len, v))
2473 return 0;
2475 return kvm_io_bus_read(&vcpu->kvm->mmio_bus, addr, len, v);
2478 static int kvm_read_guest_virt(gva_t addr, void *val, unsigned int bytes,
2479 struct kvm_vcpu *vcpu)
2481 void *data = val;
2482 int r = X86EMUL_CONTINUE;
2484 while (bytes) {
2485 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2486 unsigned offset = addr & (PAGE_SIZE-1);
2487 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
2488 int ret;
2490 if (gpa == UNMAPPED_GVA) {
2491 r = X86EMUL_PROPAGATE_FAULT;
2492 goto out;
2494 ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
2495 if (ret < 0) {
2496 r = X86EMUL_UNHANDLEABLE;
2497 goto out;
2500 bytes -= toread;
2501 data += toread;
2502 addr += toread;
2504 out:
2505 return r;
2508 static int kvm_write_guest_virt(gva_t addr, void *val, unsigned int bytes,
2509 struct kvm_vcpu *vcpu)
2511 void *data = val;
2512 int r = X86EMUL_CONTINUE;
2514 while (bytes) {
2515 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2516 unsigned offset = addr & (PAGE_SIZE-1);
2517 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
2518 int ret;
2520 if (gpa == UNMAPPED_GVA) {
2521 r = X86EMUL_PROPAGATE_FAULT;
2522 goto out;
2524 ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
2525 if (ret < 0) {
2526 r = X86EMUL_UNHANDLEABLE;
2527 goto out;
2530 bytes -= towrite;
2531 data += towrite;
2532 addr += towrite;
2534 out:
2535 return r;
2539 static int emulator_read_emulated(unsigned long addr,
2540 void *val,
2541 unsigned int bytes,
2542 struct kvm_vcpu *vcpu)
2544 gpa_t gpa;
2546 if (vcpu->mmio_read_completed) {
2547 memcpy(val, vcpu->mmio_data, bytes);
2548 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
2549 vcpu->mmio_phys_addr, *(u64 *)val);
2550 vcpu->mmio_read_completed = 0;
2551 return X86EMUL_CONTINUE;
2554 gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2556 /* For APIC access vmexit */
2557 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
2558 goto mmio;
2560 if (kvm_read_guest_virt(addr, val, bytes, vcpu)
2561 == X86EMUL_CONTINUE)
2562 return X86EMUL_CONTINUE;
2563 if (gpa == UNMAPPED_GVA)
2564 return X86EMUL_PROPAGATE_FAULT;
2566 mmio:
2568 * Is this MMIO handled locally?
2570 if (!vcpu_mmio_read(vcpu, gpa, bytes, val)) {
2571 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes, gpa, *(u64 *)val);
2572 return X86EMUL_CONTINUE;
2575 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
2577 vcpu->mmio_needed = 1;
2578 vcpu->mmio_phys_addr = gpa;
2579 vcpu->mmio_size = bytes;
2580 vcpu->mmio_is_write = 0;
2582 return X86EMUL_UNHANDLEABLE;
2585 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
2586 const void *val, int bytes)
2588 int ret;
2590 ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
2591 if (ret < 0)
2592 return 0;
2593 kvm_mmu_pte_write(vcpu, gpa, val, bytes, 1);
2594 return 1;
2597 static int emulator_write_emulated_onepage(unsigned long addr,
2598 const void *val,
2599 unsigned int bytes,
2600 struct kvm_vcpu *vcpu)
2602 gpa_t gpa;
2604 gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2606 if (gpa == UNMAPPED_GVA) {
2607 kvm_inject_page_fault(vcpu, addr, 2);
2608 return X86EMUL_PROPAGATE_FAULT;
2611 /* For APIC access vmexit */
2612 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
2613 goto mmio;
2615 if (emulator_write_phys(vcpu, gpa, val, bytes))
2616 return X86EMUL_CONTINUE;
2618 mmio:
2619 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
2621 * Is this MMIO handled locally?
2623 if (!vcpu_mmio_write(vcpu, gpa, bytes, val))
2624 return X86EMUL_CONTINUE;
2626 vcpu->mmio_needed = 1;
2627 vcpu->mmio_phys_addr = gpa;
2628 vcpu->mmio_size = bytes;
2629 vcpu->mmio_is_write = 1;
2630 memcpy(vcpu->mmio_data, val, bytes);
2632 return X86EMUL_CONTINUE;
2635 int emulator_write_emulated(unsigned long addr,
2636 const void *val,
2637 unsigned int bytes,
2638 struct kvm_vcpu *vcpu)
2640 /* Crossing a page boundary? */
2641 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
2642 int rc, now;
2644 now = -addr & ~PAGE_MASK;
2645 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
2646 if (rc != X86EMUL_CONTINUE)
2647 return rc;
2648 addr += now;
2649 val += now;
2650 bytes -= now;
2652 return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
2654 EXPORT_SYMBOL_GPL(emulator_write_emulated);
2656 static int emulator_cmpxchg_emulated(unsigned long addr,
2657 const void *old,
2658 const void *new,
2659 unsigned int bytes,
2660 struct kvm_vcpu *vcpu)
2662 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
2663 #ifndef CONFIG_X86_64
2664 /* guests cmpxchg8b have to be emulated atomically */
2665 if (bytes == 8) {
2666 gpa_t gpa;
2667 struct page *page;
2668 char *kaddr;
2669 u64 val;
2671 gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2673 if (gpa == UNMAPPED_GVA ||
2674 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
2675 goto emul_write;
2677 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
2678 goto emul_write;
2680 val = *(u64 *)new;
2682 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
2684 kaddr = kmap_atomic(page, KM_USER0);
2685 set_64bit((u64 *)(kaddr + offset_in_page(gpa)), val);
2686 kunmap_atomic(kaddr, KM_USER0);
2687 kvm_release_page_dirty(page);
2689 emul_write:
2690 #endif
2692 return emulator_write_emulated(addr, new, bytes, vcpu);
2695 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
2697 return kvm_x86_ops->get_segment_base(vcpu, seg);
2700 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
2702 kvm_mmu_invlpg(vcpu, address);
2703 return X86EMUL_CONTINUE;
2706 int emulate_clts(struct kvm_vcpu *vcpu)
2708 kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 & ~X86_CR0_TS);
2709 return X86EMUL_CONTINUE;
2712 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
2714 struct kvm_vcpu *vcpu = ctxt->vcpu;
2716 switch (dr) {
2717 case 0 ... 3:
2718 *dest = kvm_x86_ops->get_dr(vcpu, dr);
2719 return X86EMUL_CONTINUE;
2720 default:
2721 pr_unimpl(vcpu, "%s: unexpected dr %u\n", __func__, dr);
2722 return X86EMUL_UNHANDLEABLE;
2726 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
2728 unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
2729 int exception;
2731 kvm_x86_ops->set_dr(ctxt->vcpu, dr, value & mask, &exception);
2732 if (exception) {
2733 /* FIXME: better handling */
2734 return X86EMUL_UNHANDLEABLE;
2736 return X86EMUL_CONTINUE;
2739 void kvm_report_emulation_failure(struct kvm_vcpu *vcpu, const char *context)
2741 u8 opcodes[4];
2742 unsigned long rip = kvm_rip_read(vcpu);
2743 unsigned long rip_linear;
2745 if (!printk_ratelimit())
2746 return;
2748 rip_linear = rip + get_segment_base(vcpu, VCPU_SREG_CS);
2750 kvm_read_guest_virt(rip_linear, (void *)opcodes, 4, vcpu);
2752 printk(KERN_ERR "emulation failed (%s) rip %lx %02x %02x %02x %02x\n",
2753 context, rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
2755 EXPORT_SYMBOL_GPL(kvm_report_emulation_failure);
2757 static struct x86_emulate_ops emulate_ops = {
2758 .read_std = kvm_read_guest_virt,
2759 .read_emulated = emulator_read_emulated,
2760 .write_emulated = emulator_write_emulated,
2761 .cmpxchg_emulated = emulator_cmpxchg_emulated,
2764 static void cache_all_regs(struct kvm_vcpu *vcpu)
2766 kvm_register_read(vcpu, VCPU_REGS_RAX);
2767 kvm_register_read(vcpu, VCPU_REGS_RSP);
2768 kvm_register_read(vcpu, VCPU_REGS_RIP);
2769 vcpu->arch.regs_dirty = ~0;
2772 int emulate_instruction(struct kvm_vcpu *vcpu,
2773 unsigned long cr2,
2774 u16 error_code,
2775 int emulation_type)
2777 int r, shadow_mask;
2778 struct decode_cache *c;
2779 struct kvm_run *run = vcpu->run;
2781 kvm_clear_exception_queue(vcpu);
2782 vcpu->arch.mmio_fault_cr2 = cr2;
2784 * TODO: fix emulate.c to use guest_read/write_register
2785 * instead of direct ->regs accesses, can save hundred cycles
2786 * on Intel for instructions that don't read/change RSP, for
2787 * for example.
2789 cache_all_regs(vcpu);
2791 vcpu->mmio_is_write = 0;
2792 vcpu->arch.pio.string = 0;
2794 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
2795 int cs_db, cs_l;
2796 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
2798 vcpu->arch.emulate_ctxt.vcpu = vcpu;
2799 vcpu->arch.emulate_ctxt.eflags = kvm_get_rflags(vcpu);
2800 vcpu->arch.emulate_ctxt.mode =
2801 (vcpu->arch.emulate_ctxt.eflags & X86_EFLAGS_VM)
2802 ? X86EMUL_MODE_REAL : cs_l
2803 ? X86EMUL_MODE_PROT64 : cs_db
2804 ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
2806 r = x86_decode_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
2808 /* Only allow emulation of specific instructions on #UD
2809 * (namely VMMCALL, sysenter, sysexit, syscall)*/
2810 c = &vcpu->arch.emulate_ctxt.decode;
2811 if (emulation_type & EMULTYPE_TRAP_UD) {
2812 if (!c->twobyte)
2813 return EMULATE_FAIL;
2814 switch (c->b) {
2815 case 0x01: /* VMMCALL */
2816 if (c->modrm_mod != 3 || c->modrm_rm != 1)
2817 return EMULATE_FAIL;
2818 break;
2819 case 0x34: /* sysenter */
2820 case 0x35: /* sysexit */
2821 if (c->modrm_mod != 0 || c->modrm_rm != 0)
2822 return EMULATE_FAIL;
2823 break;
2824 case 0x05: /* syscall */
2825 if (c->modrm_mod != 0 || c->modrm_rm != 0)
2826 return EMULATE_FAIL;
2827 break;
2828 default:
2829 return EMULATE_FAIL;
2832 if (!(c->modrm_reg == 0 || c->modrm_reg == 3))
2833 return EMULATE_FAIL;
2836 ++vcpu->stat.insn_emulation;
2837 if (r) {
2838 ++vcpu->stat.insn_emulation_fail;
2839 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
2840 return EMULATE_DONE;
2841 return EMULATE_FAIL;
2845 if (emulation_type & EMULTYPE_SKIP) {
2846 kvm_rip_write(vcpu, vcpu->arch.emulate_ctxt.decode.eip);
2847 return EMULATE_DONE;
2850 r = x86_emulate_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
2851 shadow_mask = vcpu->arch.emulate_ctxt.interruptibility;
2853 if (r == 0)
2854 kvm_x86_ops->set_interrupt_shadow(vcpu, shadow_mask);
2856 if (vcpu->arch.pio.string)
2857 return EMULATE_DO_MMIO;
2859 if ((r || vcpu->mmio_is_write) && run) {
2860 run->exit_reason = KVM_EXIT_MMIO;
2861 run->mmio.phys_addr = vcpu->mmio_phys_addr;
2862 memcpy(run->mmio.data, vcpu->mmio_data, 8);
2863 run->mmio.len = vcpu->mmio_size;
2864 run->mmio.is_write = vcpu->mmio_is_write;
2867 if (r) {
2868 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
2869 return EMULATE_DONE;
2870 if (!vcpu->mmio_needed) {
2871 kvm_report_emulation_failure(vcpu, "mmio");
2872 return EMULATE_FAIL;
2874 return EMULATE_DO_MMIO;
2877 kvm_set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
2879 if (vcpu->mmio_is_write) {
2880 vcpu->mmio_needed = 0;
2881 return EMULATE_DO_MMIO;
2884 return EMULATE_DONE;
2886 EXPORT_SYMBOL_GPL(emulate_instruction);
2888 static int pio_copy_data(struct kvm_vcpu *vcpu)
2890 void *p = vcpu->arch.pio_data;
2891 gva_t q = vcpu->arch.pio.guest_gva;
2892 unsigned bytes;
2893 int ret;
2895 bytes = vcpu->arch.pio.size * vcpu->arch.pio.cur_count;
2896 if (vcpu->arch.pio.in)
2897 ret = kvm_write_guest_virt(q, p, bytes, vcpu);
2898 else
2899 ret = kvm_read_guest_virt(q, p, bytes, vcpu);
2900 return ret;
2903 int complete_pio(struct kvm_vcpu *vcpu)
2905 struct kvm_pio_request *io = &vcpu->arch.pio;
2906 long delta;
2907 int r;
2908 unsigned long val;
2910 if (!io->string) {
2911 if (io->in) {
2912 val = kvm_register_read(vcpu, VCPU_REGS_RAX);
2913 memcpy(&val, vcpu->arch.pio_data, io->size);
2914 kvm_register_write(vcpu, VCPU_REGS_RAX, val);
2916 } else {
2917 if (io->in) {
2918 r = pio_copy_data(vcpu);
2919 if (r)
2920 return r;
2923 delta = 1;
2924 if (io->rep) {
2925 delta *= io->cur_count;
2927 * The size of the register should really depend on
2928 * current address size.
2930 val = kvm_register_read(vcpu, VCPU_REGS_RCX);
2931 val -= delta;
2932 kvm_register_write(vcpu, VCPU_REGS_RCX, val);
2934 if (io->down)
2935 delta = -delta;
2936 delta *= io->size;
2937 if (io->in) {
2938 val = kvm_register_read(vcpu, VCPU_REGS_RDI);
2939 val += delta;
2940 kvm_register_write(vcpu, VCPU_REGS_RDI, val);
2941 } else {
2942 val = kvm_register_read(vcpu, VCPU_REGS_RSI);
2943 val += delta;
2944 kvm_register_write(vcpu, VCPU_REGS_RSI, val);
2948 io->count -= io->cur_count;
2949 io->cur_count = 0;
2951 return 0;
2954 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
2956 /* TODO: String I/O for in kernel device */
2957 int r;
2959 if (vcpu->arch.pio.in)
2960 r = kvm_io_bus_read(&vcpu->kvm->pio_bus, vcpu->arch.pio.port,
2961 vcpu->arch.pio.size, pd);
2962 else
2963 r = kvm_io_bus_write(&vcpu->kvm->pio_bus, vcpu->arch.pio.port,
2964 vcpu->arch.pio.size, pd);
2965 return r;
2968 static int pio_string_write(struct kvm_vcpu *vcpu)
2970 struct kvm_pio_request *io = &vcpu->arch.pio;
2971 void *pd = vcpu->arch.pio_data;
2972 int i, r = 0;
2974 for (i = 0; i < io->cur_count; i++) {
2975 if (kvm_io_bus_write(&vcpu->kvm->pio_bus,
2976 io->port, io->size, pd)) {
2977 r = -EOPNOTSUPP;
2978 break;
2980 pd += io->size;
2982 return r;
2985 int kvm_emulate_pio(struct kvm_vcpu *vcpu, int in, int size, unsigned port)
2987 unsigned long val;
2989 vcpu->run->exit_reason = KVM_EXIT_IO;
2990 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2991 vcpu->run->io.size = vcpu->arch.pio.size = size;
2992 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2993 vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = 1;
2994 vcpu->run->io.port = vcpu->arch.pio.port = port;
2995 vcpu->arch.pio.in = in;
2996 vcpu->arch.pio.string = 0;
2997 vcpu->arch.pio.down = 0;
2998 vcpu->arch.pio.rep = 0;
3000 trace_kvm_pio(vcpu->run->io.direction == KVM_EXIT_IO_OUT, port,
3001 size, 1);
3003 val = kvm_register_read(vcpu, VCPU_REGS_RAX);
3004 memcpy(vcpu->arch.pio_data, &val, 4);
3006 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
3007 complete_pio(vcpu);
3008 return 1;
3010 return 0;
3012 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
3014 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, int in,
3015 int size, unsigned long count, int down,
3016 gva_t address, int rep, unsigned port)
3018 unsigned now, in_page;
3019 int ret = 0;
3021 vcpu->run->exit_reason = KVM_EXIT_IO;
3022 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
3023 vcpu->run->io.size = vcpu->arch.pio.size = size;
3024 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
3025 vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = count;
3026 vcpu->run->io.port = vcpu->arch.pio.port = port;
3027 vcpu->arch.pio.in = in;
3028 vcpu->arch.pio.string = 1;
3029 vcpu->arch.pio.down = down;
3030 vcpu->arch.pio.rep = rep;
3032 trace_kvm_pio(vcpu->run->io.direction == KVM_EXIT_IO_OUT, port,
3033 size, count);
3035 if (!count) {
3036 kvm_x86_ops->skip_emulated_instruction(vcpu);
3037 return 1;
3040 if (!down)
3041 in_page = PAGE_SIZE - offset_in_page(address);
3042 else
3043 in_page = offset_in_page(address) + size;
3044 now = min(count, (unsigned long)in_page / size);
3045 if (!now)
3046 now = 1;
3047 if (down) {
3049 * String I/O in reverse. Yuck. Kill the guest, fix later.
3051 pr_unimpl(vcpu, "guest string pio down\n");
3052 kvm_inject_gp(vcpu, 0);
3053 return 1;
3055 vcpu->run->io.count = now;
3056 vcpu->arch.pio.cur_count = now;
3058 if (vcpu->arch.pio.cur_count == vcpu->arch.pio.count)
3059 kvm_x86_ops->skip_emulated_instruction(vcpu);
3061 vcpu->arch.pio.guest_gva = address;
3063 if (!vcpu->arch.pio.in) {
3064 /* string PIO write */
3065 ret = pio_copy_data(vcpu);
3066 if (ret == X86EMUL_PROPAGATE_FAULT) {
3067 kvm_inject_gp(vcpu, 0);
3068 return 1;
3070 if (ret == 0 && !pio_string_write(vcpu)) {
3071 complete_pio(vcpu);
3072 if (vcpu->arch.pio.count == 0)
3073 ret = 1;
3076 /* no string PIO read support yet */
3078 return ret;
3080 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
3082 static void bounce_off(void *info)
3084 /* nothing */
3087 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
3088 void *data)
3090 struct cpufreq_freqs *freq = data;
3091 struct kvm *kvm;
3092 struct kvm_vcpu *vcpu;
3093 int i, send_ipi = 0;
3095 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
3096 return 0;
3097 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
3098 return 0;
3099 per_cpu(cpu_tsc_khz, freq->cpu) = freq->new;
3101 spin_lock(&kvm_lock);
3102 list_for_each_entry(kvm, &vm_list, vm_list) {
3103 kvm_for_each_vcpu(i, vcpu, kvm) {
3104 if (vcpu->cpu != freq->cpu)
3105 continue;
3106 if (!kvm_request_guest_time_update(vcpu))
3107 continue;
3108 if (vcpu->cpu != smp_processor_id())
3109 send_ipi++;
3112 spin_unlock(&kvm_lock);
3114 if (freq->old < freq->new && send_ipi) {
3116 * We upscale the frequency. Must make the guest
3117 * doesn't see old kvmclock values while running with
3118 * the new frequency, otherwise we risk the guest sees
3119 * time go backwards.
3121 * In case we update the frequency for another cpu
3122 * (which might be in guest context) send an interrupt
3123 * to kick the cpu out of guest context. Next time
3124 * guest context is entered kvmclock will be updated,
3125 * so the guest will not see stale values.
3127 smp_call_function_single(freq->cpu, bounce_off, NULL, 1);
3129 return 0;
3132 static struct notifier_block kvmclock_cpufreq_notifier_block = {
3133 .notifier_call = kvmclock_cpufreq_notifier
3136 static void kvm_timer_init(void)
3138 int cpu;
3140 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
3141 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
3142 CPUFREQ_TRANSITION_NOTIFIER);
3143 for_each_online_cpu(cpu)
3144 per_cpu(cpu_tsc_khz, cpu) = cpufreq_get(cpu);
3145 } else {
3146 for_each_possible_cpu(cpu)
3147 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
3151 int kvm_arch_init(void *opaque)
3153 int r;
3154 struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
3156 if (kvm_x86_ops) {
3157 printk(KERN_ERR "kvm: already loaded the other module\n");
3158 r = -EEXIST;
3159 goto out;
3162 if (!ops->cpu_has_kvm_support()) {
3163 printk(KERN_ERR "kvm: no hardware support\n");
3164 r = -EOPNOTSUPP;
3165 goto out;
3167 if (ops->disabled_by_bios()) {
3168 printk(KERN_ERR "kvm: disabled by bios\n");
3169 r = -EOPNOTSUPP;
3170 goto out;
3173 r = kvm_mmu_module_init();
3174 if (r)
3175 goto out;
3177 kvm_init_msr_list();
3179 kvm_x86_ops = ops;
3180 kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
3181 kvm_mmu_set_base_ptes(PT_PRESENT_MASK);
3182 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
3183 PT_DIRTY_MASK, PT64_NX_MASK, 0);
3185 kvm_timer_init();
3187 return 0;
3189 out:
3190 return r;
3193 void kvm_arch_exit(void)
3195 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
3196 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
3197 CPUFREQ_TRANSITION_NOTIFIER);
3198 kvm_x86_ops = NULL;
3199 kvm_mmu_module_exit();
3202 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
3204 ++vcpu->stat.halt_exits;
3205 if (irqchip_in_kernel(vcpu->kvm)) {
3206 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
3207 return 1;
3208 } else {
3209 vcpu->run->exit_reason = KVM_EXIT_HLT;
3210 return 0;
3213 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
3215 static inline gpa_t hc_gpa(struct kvm_vcpu *vcpu, unsigned long a0,
3216 unsigned long a1)
3218 if (is_long_mode(vcpu))
3219 return a0;
3220 else
3221 return a0 | ((gpa_t)a1 << 32);
3224 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
3226 unsigned long nr, a0, a1, a2, a3, ret;
3227 int r = 1;
3229 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
3230 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
3231 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
3232 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
3233 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
3235 trace_kvm_hypercall(nr, a0, a1, a2, a3);
3237 if (!is_long_mode(vcpu)) {
3238 nr &= 0xFFFFFFFF;
3239 a0 &= 0xFFFFFFFF;
3240 a1 &= 0xFFFFFFFF;
3241 a2 &= 0xFFFFFFFF;
3242 a3 &= 0xFFFFFFFF;
3245 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
3246 ret = -KVM_EPERM;
3247 goto out;
3250 switch (nr) {
3251 case KVM_HC_VAPIC_POLL_IRQ:
3252 ret = 0;
3253 break;
3254 case KVM_HC_MMU_OP:
3255 r = kvm_pv_mmu_op(vcpu, a0, hc_gpa(vcpu, a1, a2), &ret);
3256 break;
3257 default:
3258 ret = -KVM_ENOSYS;
3259 break;
3261 out:
3262 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
3263 ++vcpu->stat.hypercalls;
3264 return r;
3266 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
3268 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
3270 char instruction[3];
3271 int ret = 0;
3272 unsigned long rip = kvm_rip_read(vcpu);
3276 * Blow out the MMU to ensure that no other VCPU has an active mapping
3277 * to ensure that the updated hypercall appears atomically across all
3278 * VCPUs.
3280 kvm_mmu_zap_all(vcpu->kvm);
3282 kvm_x86_ops->patch_hypercall(vcpu, instruction);
3283 if (emulator_write_emulated(rip, instruction, 3, vcpu)
3284 != X86EMUL_CONTINUE)
3285 ret = -EFAULT;
3287 return ret;
3290 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
3292 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
3295 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
3297 struct descriptor_table dt = { limit, base };
3299 kvm_x86_ops->set_gdt(vcpu, &dt);
3302 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
3304 struct descriptor_table dt = { limit, base };
3306 kvm_x86_ops->set_idt(vcpu, &dt);
3309 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
3310 unsigned long *rflags)
3312 kvm_lmsw(vcpu, msw);
3313 *rflags = kvm_get_rflags(vcpu);
3316 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
3318 unsigned long value;
3320 kvm_x86_ops->decache_cr4_guest_bits(vcpu);
3321 switch (cr) {
3322 case 0:
3323 value = vcpu->arch.cr0;
3324 break;
3325 case 2:
3326 value = vcpu->arch.cr2;
3327 break;
3328 case 3:
3329 value = vcpu->arch.cr3;
3330 break;
3331 case 4:
3332 value = vcpu->arch.cr4;
3333 break;
3334 case 8:
3335 value = kvm_get_cr8(vcpu);
3336 break;
3337 default:
3338 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
3339 return 0;
3342 return value;
3345 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
3346 unsigned long *rflags)
3348 switch (cr) {
3349 case 0:
3350 kvm_set_cr0(vcpu, mk_cr_64(vcpu->arch.cr0, val));
3351 *rflags = kvm_get_rflags(vcpu);
3352 break;
3353 case 2:
3354 vcpu->arch.cr2 = val;
3355 break;
3356 case 3:
3357 kvm_set_cr3(vcpu, val);
3358 break;
3359 case 4:
3360 kvm_set_cr4(vcpu, mk_cr_64(vcpu->arch.cr4, val));
3361 break;
3362 case 8:
3363 kvm_set_cr8(vcpu, val & 0xfUL);
3364 break;
3365 default:
3366 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
3370 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
3372 struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
3373 int j, nent = vcpu->arch.cpuid_nent;
3375 e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
3376 /* when no next entry is found, the current entry[i] is reselected */
3377 for (j = i + 1; ; j = (j + 1) % nent) {
3378 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
3379 if (ej->function == e->function) {
3380 ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
3381 return j;
3384 return 0; /* silence gcc, even though control never reaches here */
3387 /* find an entry with matching function, matching index (if needed), and that
3388 * should be read next (if it's stateful) */
3389 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
3390 u32 function, u32 index)
3392 if (e->function != function)
3393 return 0;
3394 if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
3395 return 0;
3396 if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
3397 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
3398 return 0;
3399 return 1;
3402 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry(struct kvm_vcpu *vcpu,
3403 u32 function, u32 index)
3405 int i;
3406 struct kvm_cpuid_entry2 *best = NULL;
3408 for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
3409 struct kvm_cpuid_entry2 *e;
3411 e = &vcpu->arch.cpuid_entries[i];
3412 if (is_matching_cpuid_entry(e, function, index)) {
3413 if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
3414 move_to_next_stateful_cpuid_entry(vcpu, i);
3415 best = e;
3416 break;
3419 * Both basic or both extended?
3421 if (((e->function ^ function) & 0x80000000) == 0)
3422 if (!best || e->function > best->function)
3423 best = e;
3425 return best;
3428 int cpuid_maxphyaddr(struct kvm_vcpu *vcpu)
3430 struct kvm_cpuid_entry2 *best;
3432 best = kvm_find_cpuid_entry(vcpu, 0x80000008, 0);
3433 if (best)
3434 return best->eax & 0xff;
3435 return 36;
3438 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
3440 u32 function, index;
3441 struct kvm_cpuid_entry2 *best;
3443 function = kvm_register_read(vcpu, VCPU_REGS_RAX);
3444 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
3445 kvm_register_write(vcpu, VCPU_REGS_RAX, 0);
3446 kvm_register_write(vcpu, VCPU_REGS_RBX, 0);
3447 kvm_register_write(vcpu, VCPU_REGS_RCX, 0);
3448 kvm_register_write(vcpu, VCPU_REGS_RDX, 0);
3449 best = kvm_find_cpuid_entry(vcpu, function, index);
3450 if (best) {
3451 kvm_register_write(vcpu, VCPU_REGS_RAX, best->eax);
3452 kvm_register_write(vcpu, VCPU_REGS_RBX, best->ebx);
3453 kvm_register_write(vcpu, VCPU_REGS_RCX, best->ecx);
3454 kvm_register_write(vcpu, VCPU_REGS_RDX, best->edx);
3456 kvm_x86_ops->skip_emulated_instruction(vcpu);
3457 trace_kvm_cpuid(function,
3458 kvm_register_read(vcpu, VCPU_REGS_RAX),
3459 kvm_register_read(vcpu, VCPU_REGS_RBX),
3460 kvm_register_read(vcpu, VCPU_REGS_RCX),
3461 kvm_register_read(vcpu, VCPU_REGS_RDX));
3463 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
3466 * Check if userspace requested an interrupt window, and that the
3467 * interrupt window is open.
3469 * No need to exit to userspace if we already have an interrupt queued.
3471 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
3473 return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
3474 vcpu->run->request_interrupt_window &&
3475 kvm_arch_interrupt_allowed(vcpu));
3478 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
3480 struct kvm_run *kvm_run = vcpu->run;
3482 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
3483 kvm_run->cr8 = kvm_get_cr8(vcpu);
3484 kvm_run->apic_base = kvm_get_apic_base(vcpu);
3485 if (irqchip_in_kernel(vcpu->kvm))
3486 kvm_run->ready_for_interrupt_injection = 1;
3487 else
3488 kvm_run->ready_for_interrupt_injection =
3489 kvm_arch_interrupt_allowed(vcpu) &&
3490 !kvm_cpu_has_interrupt(vcpu) &&
3491 !kvm_event_needs_reinjection(vcpu);
3494 static void vapic_enter(struct kvm_vcpu *vcpu)
3496 struct kvm_lapic *apic = vcpu->arch.apic;
3497 struct page *page;
3499 if (!apic || !apic->vapic_addr)
3500 return;
3502 page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
3504 vcpu->arch.apic->vapic_page = page;
3507 static void vapic_exit(struct kvm_vcpu *vcpu)
3509 struct kvm_lapic *apic = vcpu->arch.apic;
3511 if (!apic || !apic->vapic_addr)
3512 return;
3514 down_read(&vcpu->kvm->slots_lock);
3515 kvm_release_page_dirty(apic->vapic_page);
3516 mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
3517 up_read(&vcpu->kvm->slots_lock);
3520 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
3522 int max_irr, tpr;
3524 if (!kvm_x86_ops->update_cr8_intercept)
3525 return;
3527 if (!vcpu->arch.apic)
3528 return;
3530 if (!vcpu->arch.apic->vapic_addr)
3531 max_irr = kvm_lapic_find_highest_irr(vcpu);
3532 else
3533 max_irr = -1;
3535 if (max_irr != -1)
3536 max_irr >>= 4;
3538 tpr = kvm_lapic_get_cr8(vcpu);
3540 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
3543 static void inject_pending_event(struct kvm_vcpu *vcpu)
3545 /* try to reinject previous events if any */
3546 if (vcpu->arch.exception.pending) {
3547 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
3548 vcpu->arch.exception.has_error_code,
3549 vcpu->arch.exception.error_code);
3550 return;
3553 if (vcpu->arch.nmi_injected) {
3554 kvm_x86_ops->set_nmi(vcpu);
3555 return;
3558 if (vcpu->arch.interrupt.pending) {
3559 kvm_x86_ops->set_irq(vcpu);
3560 return;
3563 /* try to inject new event if pending */
3564 if (vcpu->arch.nmi_pending) {
3565 if (kvm_x86_ops->nmi_allowed(vcpu)) {
3566 vcpu->arch.nmi_pending = false;
3567 vcpu->arch.nmi_injected = true;
3568 kvm_x86_ops->set_nmi(vcpu);
3570 } else if (kvm_cpu_has_interrupt(vcpu)) {
3571 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
3572 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
3573 false);
3574 kvm_x86_ops->set_irq(vcpu);
3579 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
3581 int r;
3582 bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
3583 vcpu->run->request_interrupt_window;
3585 if (vcpu->requests)
3586 if (test_and_clear_bit(KVM_REQ_MMU_RELOAD, &vcpu->requests))
3587 kvm_mmu_unload(vcpu);
3589 r = kvm_mmu_reload(vcpu);
3590 if (unlikely(r))
3591 goto out;
3593 if (vcpu->requests) {
3594 if (test_and_clear_bit(KVM_REQ_MIGRATE_TIMER, &vcpu->requests))
3595 __kvm_migrate_timers(vcpu);
3596 if (test_and_clear_bit(KVM_REQ_KVMCLOCK_UPDATE, &vcpu->requests))
3597 kvm_write_guest_time(vcpu);
3598 if (test_and_clear_bit(KVM_REQ_MMU_SYNC, &vcpu->requests))
3599 kvm_mmu_sync_roots(vcpu);
3600 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
3601 kvm_x86_ops->tlb_flush(vcpu);
3602 if (test_and_clear_bit(KVM_REQ_REPORT_TPR_ACCESS,
3603 &vcpu->requests)) {
3604 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
3605 r = 0;
3606 goto out;
3608 if (test_and_clear_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests)) {
3609 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
3610 r = 0;
3611 goto out;
3615 preempt_disable();
3617 kvm_x86_ops->prepare_guest_switch(vcpu);
3618 kvm_load_guest_fpu(vcpu);
3620 local_irq_disable();
3622 clear_bit(KVM_REQ_KICK, &vcpu->requests);
3623 smp_mb__after_clear_bit();
3625 if (vcpu->requests || need_resched() || signal_pending(current)) {
3626 set_bit(KVM_REQ_KICK, &vcpu->requests);
3627 local_irq_enable();
3628 preempt_enable();
3629 r = 1;
3630 goto out;
3633 inject_pending_event(vcpu);
3635 /* enable NMI/IRQ window open exits if needed */
3636 if (vcpu->arch.nmi_pending)
3637 kvm_x86_ops->enable_nmi_window(vcpu);
3638 else if (kvm_cpu_has_interrupt(vcpu) || req_int_win)
3639 kvm_x86_ops->enable_irq_window(vcpu);
3641 if (kvm_lapic_enabled(vcpu)) {
3642 update_cr8_intercept(vcpu);
3643 kvm_lapic_sync_to_vapic(vcpu);
3646 up_read(&vcpu->kvm->slots_lock);
3648 kvm_guest_enter();
3650 if (unlikely(vcpu->arch.switch_db_regs)) {
3651 set_debugreg(0, 7);
3652 set_debugreg(vcpu->arch.eff_db[0], 0);
3653 set_debugreg(vcpu->arch.eff_db[1], 1);
3654 set_debugreg(vcpu->arch.eff_db[2], 2);
3655 set_debugreg(vcpu->arch.eff_db[3], 3);
3658 trace_kvm_entry(vcpu->vcpu_id);
3659 kvm_x86_ops->run(vcpu);
3661 if (unlikely(vcpu->arch.switch_db_regs || test_thread_flag(TIF_DEBUG))) {
3662 set_debugreg(current->thread.debugreg0, 0);
3663 set_debugreg(current->thread.debugreg1, 1);
3664 set_debugreg(current->thread.debugreg2, 2);
3665 set_debugreg(current->thread.debugreg3, 3);
3666 set_debugreg(current->thread.debugreg6, 6);
3667 set_debugreg(current->thread.debugreg7, 7);
3670 set_bit(KVM_REQ_KICK, &vcpu->requests);
3671 local_irq_enable();
3673 ++vcpu->stat.exits;
3676 * We must have an instruction between local_irq_enable() and
3677 * kvm_guest_exit(), so the timer interrupt isn't delayed by
3678 * the interrupt shadow. The stat.exits increment will do nicely.
3679 * But we need to prevent reordering, hence this barrier():
3681 barrier();
3683 kvm_guest_exit();
3685 preempt_enable();
3687 down_read(&vcpu->kvm->slots_lock);
3690 * Profile KVM exit RIPs:
3692 if (unlikely(prof_on == KVM_PROFILING)) {
3693 unsigned long rip = kvm_rip_read(vcpu);
3694 profile_hit(KVM_PROFILING, (void *)rip);
3698 kvm_lapic_sync_from_vapic(vcpu);
3700 r = kvm_x86_ops->handle_exit(vcpu);
3701 out:
3702 return r;
3706 static int __vcpu_run(struct kvm_vcpu *vcpu)
3708 int r;
3710 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
3711 pr_debug("vcpu %d received sipi with vector # %x\n",
3712 vcpu->vcpu_id, vcpu->arch.sipi_vector);
3713 kvm_lapic_reset(vcpu);
3714 r = kvm_arch_vcpu_reset(vcpu);
3715 if (r)
3716 return r;
3717 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3720 down_read(&vcpu->kvm->slots_lock);
3721 vapic_enter(vcpu);
3723 r = 1;
3724 while (r > 0) {
3725 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE)
3726 r = vcpu_enter_guest(vcpu);
3727 else {
3728 up_read(&vcpu->kvm->slots_lock);
3729 kvm_vcpu_block(vcpu);
3730 down_read(&vcpu->kvm->slots_lock);
3731 if (test_and_clear_bit(KVM_REQ_UNHALT, &vcpu->requests))
3733 switch(vcpu->arch.mp_state) {
3734 case KVM_MP_STATE_HALTED:
3735 vcpu->arch.mp_state =
3736 KVM_MP_STATE_RUNNABLE;
3737 case KVM_MP_STATE_RUNNABLE:
3738 break;
3739 case KVM_MP_STATE_SIPI_RECEIVED:
3740 default:
3741 r = -EINTR;
3742 break;
3747 if (r <= 0)
3748 break;
3750 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
3751 if (kvm_cpu_has_pending_timer(vcpu))
3752 kvm_inject_pending_timer_irqs(vcpu);
3754 if (dm_request_for_irq_injection(vcpu)) {
3755 r = -EINTR;
3756 vcpu->run->exit_reason = KVM_EXIT_INTR;
3757 ++vcpu->stat.request_irq_exits;
3759 if (signal_pending(current)) {
3760 r = -EINTR;
3761 vcpu->run->exit_reason = KVM_EXIT_INTR;
3762 ++vcpu->stat.signal_exits;
3764 if (need_resched()) {
3765 up_read(&vcpu->kvm->slots_lock);
3766 kvm_resched(vcpu);
3767 down_read(&vcpu->kvm->slots_lock);
3771 up_read(&vcpu->kvm->slots_lock);
3772 post_kvm_run_save(vcpu);
3774 vapic_exit(vcpu);
3776 return r;
3779 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
3781 int r;
3782 sigset_t sigsaved;
3784 vcpu_load(vcpu);
3786 if (vcpu->sigset_active)
3787 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
3789 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
3790 kvm_vcpu_block(vcpu);
3791 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
3792 r = -EAGAIN;
3793 goto out;
3796 /* re-sync apic's tpr */
3797 if (!irqchip_in_kernel(vcpu->kvm))
3798 kvm_set_cr8(vcpu, kvm_run->cr8);
3800 if (vcpu->arch.pio.cur_count) {
3801 r = complete_pio(vcpu);
3802 if (r)
3803 goto out;
3805 #if CONFIG_HAS_IOMEM
3806 if (vcpu->mmio_needed) {
3807 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
3808 vcpu->mmio_read_completed = 1;
3809 vcpu->mmio_needed = 0;
3811 down_read(&vcpu->kvm->slots_lock);
3812 r = emulate_instruction(vcpu, vcpu->arch.mmio_fault_cr2, 0,
3813 EMULTYPE_NO_DECODE);
3814 up_read(&vcpu->kvm->slots_lock);
3815 if (r == EMULATE_DO_MMIO) {
3817 * Read-modify-write. Back to userspace.
3819 r = 0;
3820 goto out;
3823 #endif
3824 if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL)
3825 kvm_register_write(vcpu, VCPU_REGS_RAX,
3826 kvm_run->hypercall.ret);
3828 r = __vcpu_run(vcpu);
3830 out:
3831 if (vcpu->sigset_active)
3832 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
3834 vcpu_put(vcpu);
3835 return r;
3838 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
3840 vcpu_load(vcpu);
3842 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
3843 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
3844 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
3845 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
3846 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
3847 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
3848 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
3849 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
3850 #ifdef CONFIG_X86_64
3851 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
3852 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
3853 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
3854 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
3855 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
3856 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
3857 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
3858 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
3859 #endif
3861 regs->rip = kvm_rip_read(vcpu);
3862 regs->rflags = kvm_get_rflags(vcpu);
3864 vcpu_put(vcpu);
3866 return 0;
3869 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
3871 vcpu_load(vcpu);
3873 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
3874 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
3875 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
3876 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
3877 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
3878 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
3879 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
3880 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
3881 #ifdef CONFIG_X86_64
3882 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
3883 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
3884 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
3885 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
3886 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
3887 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
3888 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
3889 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
3890 #endif
3892 kvm_rip_write(vcpu, regs->rip);
3893 kvm_set_rflags(vcpu, regs->rflags);
3895 vcpu->arch.exception.pending = false;
3897 vcpu_put(vcpu);
3899 return 0;
3902 void kvm_get_segment(struct kvm_vcpu *vcpu,
3903 struct kvm_segment *var, int seg)
3905 kvm_x86_ops->get_segment(vcpu, var, seg);
3908 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3910 struct kvm_segment cs;
3912 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
3913 *db = cs.db;
3914 *l = cs.l;
3916 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
3918 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
3919 struct kvm_sregs *sregs)
3921 struct descriptor_table dt;
3923 vcpu_load(vcpu);
3925 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
3926 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
3927 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
3928 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
3929 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
3930 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
3932 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
3933 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
3935 kvm_x86_ops->get_idt(vcpu, &dt);
3936 sregs->idt.limit = dt.limit;
3937 sregs->idt.base = dt.base;
3938 kvm_x86_ops->get_gdt(vcpu, &dt);
3939 sregs->gdt.limit = dt.limit;
3940 sregs->gdt.base = dt.base;
3942 kvm_x86_ops->decache_cr4_guest_bits(vcpu);
3943 sregs->cr0 = vcpu->arch.cr0;
3944 sregs->cr2 = vcpu->arch.cr2;
3945 sregs->cr3 = vcpu->arch.cr3;
3946 sregs->cr4 = vcpu->arch.cr4;
3947 sregs->cr8 = kvm_get_cr8(vcpu);
3948 sregs->efer = vcpu->arch.shadow_efer;
3949 sregs->apic_base = kvm_get_apic_base(vcpu);
3951 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
3953 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
3954 set_bit(vcpu->arch.interrupt.nr,
3955 (unsigned long *)sregs->interrupt_bitmap);
3957 vcpu_put(vcpu);
3959 return 0;
3962 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
3963 struct kvm_mp_state *mp_state)
3965 vcpu_load(vcpu);
3966 mp_state->mp_state = vcpu->arch.mp_state;
3967 vcpu_put(vcpu);
3968 return 0;
3971 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
3972 struct kvm_mp_state *mp_state)
3974 vcpu_load(vcpu);
3975 vcpu->arch.mp_state = mp_state->mp_state;
3976 vcpu_put(vcpu);
3977 return 0;
3980 static void kvm_set_segment(struct kvm_vcpu *vcpu,
3981 struct kvm_segment *var, int seg)
3983 kvm_x86_ops->set_segment(vcpu, var, seg);
3986 static void seg_desct_to_kvm_desct(struct desc_struct *seg_desc, u16 selector,
3987 struct kvm_segment *kvm_desct)
3989 kvm_desct->base = get_desc_base(seg_desc);
3990 kvm_desct->limit = get_desc_limit(seg_desc);
3991 if (seg_desc->g) {
3992 kvm_desct->limit <<= 12;
3993 kvm_desct->limit |= 0xfff;
3995 kvm_desct->selector = selector;
3996 kvm_desct->type = seg_desc->type;
3997 kvm_desct->present = seg_desc->p;
3998 kvm_desct->dpl = seg_desc->dpl;
3999 kvm_desct->db = seg_desc->d;
4000 kvm_desct->s = seg_desc->s;
4001 kvm_desct->l = seg_desc->l;
4002 kvm_desct->g = seg_desc->g;
4003 kvm_desct->avl = seg_desc->avl;
4004 if (!selector)
4005 kvm_desct->unusable = 1;
4006 else
4007 kvm_desct->unusable = 0;
4008 kvm_desct->padding = 0;
4011 static void get_segment_descriptor_dtable(struct kvm_vcpu *vcpu,
4012 u16 selector,
4013 struct descriptor_table *dtable)
4015 if (selector & 1 << 2) {
4016 struct kvm_segment kvm_seg;
4018 kvm_get_segment(vcpu, &kvm_seg, VCPU_SREG_LDTR);
4020 if (kvm_seg.unusable)
4021 dtable->limit = 0;
4022 else
4023 dtable->limit = kvm_seg.limit;
4024 dtable->base = kvm_seg.base;
4026 else
4027 kvm_x86_ops->get_gdt(vcpu, dtable);
4030 /* allowed just for 8 bytes segments */
4031 static int load_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
4032 struct desc_struct *seg_desc)
4034 struct descriptor_table dtable;
4035 u16 index = selector >> 3;
4037 get_segment_descriptor_dtable(vcpu, selector, &dtable);
4039 if (dtable.limit < index * 8 + 7) {
4040 kvm_queue_exception_e(vcpu, GP_VECTOR, selector & 0xfffc);
4041 return 1;
4043 return kvm_read_guest_virt(dtable.base + index*8, seg_desc, sizeof(*seg_desc), vcpu);
4046 /* allowed just for 8 bytes segments */
4047 static int save_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
4048 struct desc_struct *seg_desc)
4050 struct descriptor_table dtable;
4051 u16 index = selector >> 3;
4053 get_segment_descriptor_dtable(vcpu, selector, &dtable);
4055 if (dtable.limit < index * 8 + 7)
4056 return 1;
4057 return kvm_write_guest_virt(dtable.base + index*8, seg_desc, sizeof(*seg_desc), vcpu);
4060 static u32 get_tss_base_addr(struct kvm_vcpu *vcpu,
4061 struct desc_struct *seg_desc)
4063 u32 base_addr = get_desc_base(seg_desc);
4065 return vcpu->arch.mmu.gva_to_gpa(vcpu, base_addr);
4068 static u16 get_segment_selector(struct kvm_vcpu *vcpu, int seg)
4070 struct kvm_segment kvm_seg;
4072 kvm_get_segment(vcpu, &kvm_seg, seg);
4073 return kvm_seg.selector;
4076 static int load_segment_descriptor_to_kvm_desct(struct kvm_vcpu *vcpu,
4077 u16 selector,
4078 struct kvm_segment *kvm_seg)
4080 struct desc_struct seg_desc;
4082 if (load_guest_segment_descriptor(vcpu, selector, &seg_desc))
4083 return 1;
4084 seg_desct_to_kvm_desct(&seg_desc, selector, kvm_seg);
4085 return 0;
4088 static int kvm_load_realmode_segment(struct kvm_vcpu *vcpu, u16 selector, int seg)
4090 struct kvm_segment segvar = {
4091 .base = selector << 4,
4092 .limit = 0xffff,
4093 .selector = selector,
4094 .type = 3,
4095 .present = 1,
4096 .dpl = 3,
4097 .db = 0,
4098 .s = 1,
4099 .l = 0,
4100 .g = 0,
4101 .avl = 0,
4102 .unusable = 0,
4104 kvm_x86_ops->set_segment(vcpu, &segvar, seg);
4105 return 0;
4108 static int is_vm86_segment(struct kvm_vcpu *vcpu, int seg)
4110 return (seg != VCPU_SREG_LDTR) &&
4111 (seg != VCPU_SREG_TR) &&
4112 (kvm_get_rflags(vcpu) & X86_EFLAGS_VM);
4115 int kvm_load_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
4116 int type_bits, int seg)
4118 struct kvm_segment kvm_seg;
4120 if (is_vm86_segment(vcpu, seg) || !(vcpu->arch.cr0 & X86_CR0_PE))
4121 return kvm_load_realmode_segment(vcpu, selector, seg);
4122 if (load_segment_descriptor_to_kvm_desct(vcpu, selector, &kvm_seg))
4123 return 1;
4124 kvm_seg.type |= type_bits;
4126 if (seg != VCPU_SREG_SS && seg != VCPU_SREG_CS &&
4127 seg != VCPU_SREG_LDTR)
4128 if (!kvm_seg.s)
4129 kvm_seg.unusable = 1;
4131 kvm_set_segment(vcpu, &kvm_seg, seg);
4132 return 0;
4135 static void save_state_to_tss32(struct kvm_vcpu *vcpu,
4136 struct tss_segment_32 *tss)
4138 tss->cr3 = vcpu->arch.cr3;
4139 tss->eip = kvm_rip_read(vcpu);
4140 tss->eflags = kvm_get_rflags(vcpu);
4141 tss->eax = kvm_register_read(vcpu, VCPU_REGS_RAX);
4142 tss->ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
4143 tss->edx = kvm_register_read(vcpu, VCPU_REGS_RDX);
4144 tss->ebx = kvm_register_read(vcpu, VCPU_REGS_RBX);
4145 tss->esp = kvm_register_read(vcpu, VCPU_REGS_RSP);
4146 tss->ebp = kvm_register_read(vcpu, VCPU_REGS_RBP);
4147 tss->esi = kvm_register_read(vcpu, VCPU_REGS_RSI);
4148 tss->edi = kvm_register_read(vcpu, VCPU_REGS_RDI);
4149 tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
4150 tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
4151 tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
4152 tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
4153 tss->fs = get_segment_selector(vcpu, VCPU_SREG_FS);
4154 tss->gs = get_segment_selector(vcpu, VCPU_SREG_GS);
4155 tss->ldt_selector = get_segment_selector(vcpu, VCPU_SREG_LDTR);
4158 static int load_state_from_tss32(struct kvm_vcpu *vcpu,
4159 struct tss_segment_32 *tss)
4161 kvm_set_cr3(vcpu, tss->cr3);
4163 kvm_rip_write(vcpu, tss->eip);
4164 kvm_set_rflags(vcpu, tss->eflags | 2);
4166 kvm_register_write(vcpu, VCPU_REGS_RAX, tss->eax);
4167 kvm_register_write(vcpu, VCPU_REGS_RCX, tss->ecx);
4168 kvm_register_write(vcpu, VCPU_REGS_RDX, tss->edx);
4169 kvm_register_write(vcpu, VCPU_REGS_RBX, tss->ebx);
4170 kvm_register_write(vcpu, VCPU_REGS_RSP, tss->esp);
4171 kvm_register_write(vcpu, VCPU_REGS_RBP, tss->ebp);
4172 kvm_register_write(vcpu, VCPU_REGS_RSI, tss->esi);
4173 kvm_register_write(vcpu, VCPU_REGS_RDI, tss->edi);
4175 if (kvm_load_segment_descriptor(vcpu, tss->ldt_selector, 0, VCPU_SREG_LDTR))
4176 return 1;
4178 if (kvm_load_segment_descriptor(vcpu, tss->es, 1, VCPU_SREG_ES))
4179 return 1;
4181 if (kvm_load_segment_descriptor(vcpu, tss->cs, 9, VCPU_SREG_CS))
4182 return 1;
4184 if (kvm_load_segment_descriptor(vcpu, tss->ss, 1, VCPU_SREG_SS))
4185 return 1;
4187 if (kvm_load_segment_descriptor(vcpu, tss->ds, 1, VCPU_SREG_DS))
4188 return 1;
4190 if (kvm_load_segment_descriptor(vcpu, tss->fs, 1, VCPU_SREG_FS))
4191 return 1;
4193 if (kvm_load_segment_descriptor(vcpu, tss->gs, 1, VCPU_SREG_GS))
4194 return 1;
4195 return 0;
4198 static void save_state_to_tss16(struct kvm_vcpu *vcpu,
4199 struct tss_segment_16 *tss)
4201 tss->ip = kvm_rip_read(vcpu);
4202 tss->flag = kvm_get_rflags(vcpu);
4203 tss->ax = kvm_register_read(vcpu, VCPU_REGS_RAX);
4204 tss->cx = kvm_register_read(vcpu, VCPU_REGS_RCX);
4205 tss->dx = kvm_register_read(vcpu, VCPU_REGS_RDX);
4206 tss->bx = kvm_register_read(vcpu, VCPU_REGS_RBX);
4207 tss->sp = kvm_register_read(vcpu, VCPU_REGS_RSP);
4208 tss->bp = kvm_register_read(vcpu, VCPU_REGS_RBP);
4209 tss->si = kvm_register_read(vcpu, VCPU_REGS_RSI);
4210 tss->di = kvm_register_read(vcpu, VCPU_REGS_RDI);
4212 tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
4213 tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
4214 tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
4215 tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
4216 tss->ldt = get_segment_selector(vcpu, VCPU_SREG_LDTR);
4219 static int load_state_from_tss16(struct kvm_vcpu *vcpu,
4220 struct tss_segment_16 *tss)
4222 kvm_rip_write(vcpu, tss->ip);
4223 kvm_set_rflags(vcpu, tss->flag | 2);
4224 kvm_register_write(vcpu, VCPU_REGS_RAX, tss->ax);
4225 kvm_register_write(vcpu, VCPU_REGS_RCX, tss->cx);
4226 kvm_register_write(vcpu, VCPU_REGS_RDX, tss->dx);
4227 kvm_register_write(vcpu, VCPU_REGS_RBX, tss->bx);
4228 kvm_register_write(vcpu, VCPU_REGS_RSP, tss->sp);
4229 kvm_register_write(vcpu, VCPU_REGS_RBP, tss->bp);
4230 kvm_register_write(vcpu, VCPU_REGS_RSI, tss->si);
4231 kvm_register_write(vcpu, VCPU_REGS_RDI, tss->di);
4233 if (kvm_load_segment_descriptor(vcpu, tss->ldt, 0, VCPU_SREG_LDTR))
4234 return 1;
4236 if (kvm_load_segment_descriptor(vcpu, tss->es, 1, VCPU_SREG_ES))
4237 return 1;
4239 if (kvm_load_segment_descriptor(vcpu, tss->cs, 9, VCPU_SREG_CS))
4240 return 1;
4242 if (kvm_load_segment_descriptor(vcpu, tss->ss, 1, VCPU_SREG_SS))
4243 return 1;
4245 if (kvm_load_segment_descriptor(vcpu, tss->ds, 1, VCPU_SREG_DS))
4246 return 1;
4247 return 0;
4250 static int kvm_task_switch_16(struct kvm_vcpu *vcpu, u16 tss_selector,
4251 u16 old_tss_sel, u32 old_tss_base,
4252 struct desc_struct *nseg_desc)
4254 struct tss_segment_16 tss_segment_16;
4255 int ret = 0;
4257 if (kvm_read_guest(vcpu->kvm, old_tss_base, &tss_segment_16,
4258 sizeof tss_segment_16))
4259 goto out;
4261 save_state_to_tss16(vcpu, &tss_segment_16);
4263 if (kvm_write_guest(vcpu->kvm, old_tss_base, &tss_segment_16,
4264 sizeof tss_segment_16))
4265 goto out;
4267 if (kvm_read_guest(vcpu->kvm, get_tss_base_addr(vcpu, nseg_desc),
4268 &tss_segment_16, sizeof tss_segment_16))
4269 goto out;
4271 if (old_tss_sel != 0xffff) {
4272 tss_segment_16.prev_task_link = old_tss_sel;
4274 if (kvm_write_guest(vcpu->kvm,
4275 get_tss_base_addr(vcpu, nseg_desc),
4276 &tss_segment_16.prev_task_link,
4277 sizeof tss_segment_16.prev_task_link))
4278 goto out;
4281 if (load_state_from_tss16(vcpu, &tss_segment_16))
4282 goto out;
4284 ret = 1;
4285 out:
4286 return ret;
4289 static int kvm_task_switch_32(struct kvm_vcpu *vcpu, u16 tss_selector,
4290 u16 old_tss_sel, u32 old_tss_base,
4291 struct desc_struct *nseg_desc)
4293 struct tss_segment_32 tss_segment_32;
4294 int ret = 0;
4296 if (kvm_read_guest(vcpu->kvm, old_tss_base, &tss_segment_32,
4297 sizeof tss_segment_32))
4298 goto out;
4300 save_state_to_tss32(vcpu, &tss_segment_32);
4302 if (kvm_write_guest(vcpu->kvm, old_tss_base, &tss_segment_32,
4303 sizeof tss_segment_32))
4304 goto out;
4306 if (kvm_read_guest(vcpu->kvm, get_tss_base_addr(vcpu, nseg_desc),
4307 &tss_segment_32, sizeof tss_segment_32))
4308 goto out;
4310 if (old_tss_sel != 0xffff) {
4311 tss_segment_32.prev_task_link = old_tss_sel;
4313 if (kvm_write_guest(vcpu->kvm,
4314 get_tss_base_addr(vcpu, nseg_desc),
4315 &tss_segment_32.prev_task_link,
4316 sizeof tss_segment_32.prev_task_link))
4317 goto out;
4320 if (load_state_from_tss32(vcpu, &tss_segment_32))
4321 goto out;
4323 ret = 1;
4324 out:
4325 return ret;
4328 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason)
4330 struct kvm_segment tr_seg;
4331 struct desc_struct cseg_desc;
4332 struct desc_struct nseg_desc;
4333 int ret = 0;
4334 u32 old_tss_base = get_segment_base(vcpu, VCPU_SREG_TR);
4335 u16 old_tss_sel = get_segment_selector(vcpu, VCPU_SREG_TR);
4337 old_tss_base = vcpu->arch.mmu.gva_to_gpa(vcpu, old_tss_base);
4339 /* FIXME: Handle errors. Failure to read either TSS or their
4340 * descriptors should generate a pagefault.
4342 if (load_guest_segment_descriptor(vcpu, tss_selector, &nseg_desc))
4343 goto out;
4345 if (load_guest_segment_descriptor(vcpu, old_tss_sel, &cseg_desc))
4346 goto out;
4348 if (reason != TASK_SWITCH_IRET) {
4349 int cpl;
4351 cpl = kvm_x86_ops->get_cpl(vcpu);
4352 if ((tss_selector & 3) > nseg_desc.dpl || cpl > nseg_desc.dpl) {
4353 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
4354 return 1;
4358 if (!nseg_desc.p || get_desc_limit(&nseg_desc) < 0x67) {
4359 kvm_queue_exception_e(vcpu, TS_VECTOR, tss_selector & 0xfffc);
4360 return 1;
4363 if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) {
4364 cseg_desc.type &= ~(1 << 1); //clear the B flag
4365 save_guest_segment_descriptor(vcpu, old_tss_sel, &cseg_desc);
4368 if (reason == TASK_SWITCH_IRET) {
4369 u32 eflags = kvm_get_rflags(vcpu);
4370 kvm_set_rflags(vcpu, eflags & ~X86_EFLAGS_NT);
4373 /* set back link to prev task only if NT bit is set in eflags
4374 note that old_tss_sel is not used afetr this point */
4375 if (reason != TASK_SWITCH_CALL && reason != TASK_SWITCH_GATE)
4376 old_tss_sel = 0xffff;
4378 /* set back link to prev task only if NT bit is set in eflags
4379 note that old_tss_sel is not used afetr this point */
4380 if (reason != TASK_SWITCH_CALL && reason != TASK_SWITCH_GATE)
4381 old_tss_sel = 0xffff;
4383 if (nseg_desc.type & 8)
4384 ret = kvm_task_switch_32(vcpu, tss_selector, old_tss_sel,
4385 old_tss_base, &nseg_desc);
4386 else
4387 ret = kvm_task_switch_16(vcpu, tss_selector, old_tss_sel,
4388 old_tss_base, &nseg_desc);
4390 if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE) {
4391 u32 eflags = kvm_get_rflags(vcpu);
4392 kvm_set_rflags(vcpu, eflags | X86_EFLAGS_NT);
4395 if (reason != TASK_SWITCH_IRET) {
4396 nseg_desc.type |= (1 << 1);
4397 save_guest_segment_descriptor(vcpu, tss_selector,
4398 &nseg_desc);
4401 kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 | X86_CR0_TS);
4402 seg_desct_to_kvm_desct(&nseg_desc, tss_selector, &tr_seg);
4403 tr_seg.type = 11;
4404 kvm_set_segment(vcpu, &tr_seg, VCPU_SREG_TR);
4405 out:
4406 return ret;
4408 EXPORT_SYMBOL_GPL(kvm_task_switch);
4410 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
4411 struct kvm_sregs *sregs)
4413 int mmu_reset_needed = 0;
4414 int pending_vec, max_bits;
4415 struct descriptor_table dt;
4417 vcpu_load(vcpu);
4419 dt.limit = sregs->idt.limit;
4420 dt.base = sregs->idt.base;
4421 kvm_x86_ops->set_idt(vcpu, &dt);
4422 dt.limit = sregs->gdt.limit;
4423 dt.base = sregs->gdt.base;
4424 kvm_x86_ops->set_gdt(vcpu, &dt);
4426 vcpu->arch.cr2 = sregs->cr2;
4427 mmu_reset_needed |= vcpu->arch.cr3 != sregs->cr3;
4428 vcpu->arch.cr3 = sregs->cr3;
4430 kvm_set_cr8(vcpu, sregs->cr8);
4432 mmu_reset_needed |= vcpu->arch.shadow_efer != sregs->efer;
4433 kvm_x86_ops->set_efer(vcpu, sregs->efer);
4434 kvm_set_apic_base(vcpu, sregs->apic_base);
4436 kvm_x86_ops->decache_cr4_guest_bits(vcpu);
4438 mmu_reset_needed |= vcpu->arch.cr0 != sregs->cr0;
4439 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
4440 vcpu->arch.cr0 = sregs->cr0;
4442 mmu_reset_needed |= vcpu->arch.cr4 != sregs->cr4;
4443 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
4444 if (!is_long_mode(vcpu) && is_pae(vcpu))
4445 load_pdptrs(vcpu, vcpu->arch.cr3);
4447 if (mmu_reset_needed)
4448 kvm_mmu_reset_context(vcpu);
4450 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
4451 pending_vec = find_first_bit(
4452 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
4453 if (pending_vec < max_bits) {
4454 kvm_queue_interrupt(vcpu, pending_vec, false);
4455 pr_debug("Set back pending irq %d\n", pending_vec);
4456 if (irqchip_in_kernel(vcpu->kvm))
4457 kvm_pic_clear_isr_ack(vcpu->kvm);
4460 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
4461 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
4462 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
4463 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
4464 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
4465 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
4467 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
4468 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
4470 update_cr8_intercept(vcpu);
4472 /* Older userspace won't unhalt the vcpu on reset. */
4473 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
4474 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
4475 !(vcpu->arch.cr0 & X86_CR0_PE))
4476 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
4478 vcpu_put(vcpu);
4480 return 0;
4483 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
4484 struct kvm_guest_debug *dbg)
4486 unsigned long rflags;
4487 int i;
4489 vcpu_load(vcpu);
4492 * Read rflags as long as potentially injected trace flags are still
4493 * filtered out.
4495 rflags = kvm_get_rflags(vcpu);
4497 vcpu->guest_debug = dbg->control;
4498 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
4499 vcpu->guest_debug = 0;
4501 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
4502 for (i = 0; i < KVM_NR_DB_REGS; ++i)
4503 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
4504 vcpu->arch.switch_db_regs =
4505 (dbg->arch.debugreg[7] & DR7_BP_EN_MASK);
4506 } else {
4507 for (i = 0; i < KVM_NR_DB_REGS; i++)
4508 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
4509 vcpu->arch.switch_db_regs = (vcpu->arch.dr7 & DR7_BP_EN_MASK);
4513 * Trigger an rflags update that will inject or remove the trace
4514 * flags.
4516 kvm_set_rflags(vcpu, rflags);
4518 kvm_x86_ops->set_guest_debug(vcpu, dbg);
4520 if (vcpu->guest_debug & KVM_GUESTDBG_INJECT_DB)
4521 kvm_queue_exception(vcpu, DB_VECTOR);
4522 else if (vcpu->guest_debug & KVM_GUESTDBG_INJECT_BP)
4523 kvm_queue_exception(vcpu, BP_VECTOR);
4525 vcpu_put(vcpu);
4527 return 0;
4531 * fxsave fpu state. Taken from x86_64/processor.h. To be killed when
4532 * we have asm/x86/processor.h
4534 struct fxsave {
4535 u16 cwd;
4536 u16 swd;
4537 u16 twd;
4538 u16 fop;
4539 u64 rip;
4540 u64 rdp;
4541 u32 mxcsr;
4542 u32 mxcsr_mask;
4543 u32 st_space[32]; /* 8*16 bytes for each FP-reg = 128 bytes */
4544 #ifdef CONFIG_X86_64
4545 u32 xmm_space[64]; /* 16*16 bytes for each XMM-reg = 256 bytes */
4546 #else
4547 u32 xmm_space[32]; /* 8*16 bytes for each XMM-reg = 128 bytes */
4548 #endif
4552 * Translate a guest virtual address to a guest physical address.
4554 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
4555 struct kvm_translation *tr)
4557 unsigned long vaddr = tr->linear_address;
4558 gpa_t gpa;
4560 vcpu_load(vcpu);
4561 down_read(&vcpu->kvm->slots_lock);
4562 gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, vaddr);
4563 up_read(&vcpu->kvm->slots_lock);
4564 tr->physical_address = gpa;
4565 tr->valid = gpa != UNMAPPED_GVA;
4566 tr->writeable = 1;
4567 tr->usermode = 0;
4568 vcpu_put(vcpu);
4570 return 0;
4573 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
4575 struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
4577 vcpu_load(vcpu);
4579 memcpy(fpu->fpr, fxsave->st_space, 128);
4580 fpu->fcw = fxsave->cwd;
4581 fpu->fsw = fxsave->swd;
4582 fpu->ftwx = fxsave->twd;
4583 fpu->last_opcode = fxsave->fop;
4584 fpu->last_ip = fxsave->rip;
4585 fpu->last_dp = fxsave->rdp;
4586 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
4588 vcpu_put(vcpu);
4590 return 0;
4593 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
4595 struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
4597 vcpu_load(vcpu);
4599 memcpy(fxsave->st_space, fpu->fpr, 128);
4600 fxsave->cwd = fpu->fcw;
4601 fxsave->swd = fpu->fsw;
4602 fxsave->twd = fpu->ftwx;
4603 fxsave->fop = fpu->last_opcode;
4604 fxsave->rip = fpu->last_ip;
4605 fxsave->rdp = fpu->last_dp;
4606 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
4608 vcpu_put(vcpu);
4610 return 0;
4613 void fx_init(struct kvm_vcpu *vcpu)
4615 unsigned after_mxcsr_mask;
4618 * Touch the fpu the first time in non atomic context as if
4619 * this is the first fpu instruction the exception handler
4620 * will fire before the instruction returns and it'll have to
4621 * allocate ram with GFP_KERNEL.
4623 if (!used_math())
4624 kvm_fx_save(&vcpu->arch.host_fx_image);
4626 /* Initialize guest FPU by resetting ours and saving into guest's */
4627 preempt_disable();
4628 kvm_fx_save(&vcpu->arch.host_fx_image);
4629 kvm_fx_finit();
4630 kvm_fx_save(&vcpu->arch.guest_fx_image);
4631 kvm_fx_restore(&vcpu->arch.host_fx_image);
4632 preempt_enable();
4634 vcpu->arch.cr0 |= X86_CR0_ET;
4635 after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
4636 vcpu->arch.guest_fx_image.mxcsr = 0x1f80;
4637 memset((void *)&vcpu->arch.guest_fx_image + after_mxcsr_mask,
4638 0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
4640 EXPORT_SYMBOL_GPL(fx_init);
4642 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
4644 if (!vcpu->fpu_active || vcpu->guest_fpu_loaded)
4645 return;
4647 vcpu->guest_fpu_loaded = 1;
4648 kvm_fx_save(&vcpu->arch.host_fx_image);
4649 kvm_fx_restore(&vcpu->arch.guest_fx_image);
4651 EXPORT_SYMBOL_GPL(kvm_load_guest_fpu);
4653 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
4655 if (!vcpu->guest_fpu_loaded)
4656 return;
4658 vcpu->guest_fpu_loaded = 0;
4659 kvm_fx_save(&vcpu->arch.guest_fx_image);
4660 kvm_fx_restore(&vcpu->arch.host_fx_image);
4661 ++vcpu->stat.fpu_reload;
4663 EXPORT_SYMBOL_GPL(kvm_put_guest_fpu);
4665 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
4667 if (vcpu->arch.time_page) {
4668 kvm_release_page_dirty(vcpu->arch.time_page);
4669 vcpu->arch.time_page = NULL;
4672 kvm_x86_ops->vcpu_free(vcpu);
4675 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
4676 unsigned int id)
4678 return kvm_x86_ops->vcpu_create(kvm, id);
4681 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
4683 int r;
4685 /* We do fxsave: this must be aligned. */
4686 BUG_ON((unsigned long)&vcpu->arch.host_fx_image & 0xF);
4688 vcpu->arch.mtrr_state.have_fixed = 1;
4689 vcpu_load(vcpu);
4690 r = kvm_arch_vcpu_reset(vcpu);
4691 if (r == 0)
4692 r = kvm_mmu_setup(vcpu);
4693 vcpu_put(vcpu);
4694 if (r < 0)
4695 goto free_vcpu;
4697 return 0;
4698 free_vcpu:
4699 kvm_x86_ops->vcpu_free(vcpu);
4700 return r;
4703 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
4705 vcpu_load(vcpu);
4706 kvm_mmu_unload(vcpu);
4707 vcpu_put(vcpu);
4709 kvm_x86_ops->vcpu_free(vcpu);
4712 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
4714 vcpu->arch.nmi_pending = false;
4715 vcpu->arch.nmi_injected = false;
4717 vcpu->arch.switch_db_regs = 0;
4718 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
4719 vcpu->arch.dr6 = DR6_FIXED_1;
4720 vcpu->arch.dr7 = DR7_FIXED_1;
4722 return kvm_x86_ops->vcpu_reset(vcpu);
4725 int kvm_arch_hardware_enable(void *garbage)
4728 * Since this may be called from a hotplug notifcation,
4729 * we can't get the CPU frequency directly.
4731 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
4732 int cpu = raw_smp_processor_id();
4733 per_cpu(cpu_tsc_khz, cpu) = 0;
4735 return kvm_x86_ops->hardware_enable(garbage);
4738 void kvm_arch_hardware_disable(void *garbage)
4740 kvm_x86_ops->hardware_disable(garbage);
4743 int kvm_arch_hardware_setup(void)
4745 return kvm_x86_ops->hardware_setup();
4748 void kvm_arch_hardware_unsetup(void)
4750 kvm_x86_ops->hardware_unsetup();
4753 void kvm_arch_check_processor_compat(void *rtn)
4755 kvm_x86_ops->check_processor_compatibility(rtn);
4758 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
4760 struct page *page;
4761 struct kvm *kvm;
4762 int r;
4764 BUG_ON(vcpu->kvm == NULL);
4765 kvm = vcpu->kvm;
4767 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
4768 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
4769 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
4770 else
4771 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
4773 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
4774 if (!page) {
4775 r = -ENOMEM;
4776 goto fail;
4778 vcpu->arch.pio_data = page_address(page);
4780 r = kvm_mmu_create(vcpu);
4781 if (r < 0)
4782 goto fail_free_pio_data;
4784 if (irqchip_in_kernel(kvm)) {
4785 r = kvm_create_lapic(vcpu);
4786 if (r < 0)
4787 goto fail_mmu_destroy;
4790 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
4791 GFP_KERNEL);
4792 if (!vcpu->arch.mce_banks) {
4793 r = -ENOMEM;
4794 goto fail_mmu_destroy;
4796 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
4798 return 0;
4800 fail_mmu_destroy:
4801 kvm_mmu_destroy(vcpu);
4802 fail_free_pio_data:
4803 free_page((unsigned long)vcpu->arch.pio_data);
4804 fail:
4805 return r;
4808 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
4810 kvm_free_lapic(vcpu);
4811 down_read(&vcpu->kvm->slots_lock);
4812 kvm_mmu_destroy(vcpu);
4813 up_read(&vcpu->kvm->slots_lock);
4814 free_page((unsigned long)vcpu->arch.pio_data);
4817 struct kvm *kvm_arch_create_vm(void)
4819 struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
4821 if (!kvm)
4822 return ERR_PTR(-ENOMEM);
4824 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
4825 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
4827 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
4828 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
4830 rdtscll(kvm->arch.vm_init_tsc);
4832 return kvm;
4835 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
4837 vcpu_load(vcpu);
4838 kvm_mmu_unload(vcpu);
4839 vcpu_put(vcpu);
4842 static void kvm_free_vcpus(struct kvm *kvm)
4844 unsigned int i;
4845 struct kvm_vcpu *vcpu;
4848 * Unpin any mmu pages first.
4850 kvm_for_each_vcpu(i, vcpu, kvm)
4851 kvm_unload_vcpu_mmu(vcpu);
4852 kvm_for_each_vcpu(i, vcpu, kvm)
4853 kvm_arch_vcpu_free(vcpu);
4855 mutex_lock(&kvm->lock);
4856 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
4857 kvm->vcpus[i] = NULL;
4859 atomic_set(&kvm->online_vcpus, 0);
4860 mutex_unlock(&kvm->lock);
4863 void kvm_arch_sync_events(struct kvm *kvm)
4865 kvm_free_all_assigned_devices(kvm);
4868 void kvm_arch_destroy_vm(struct kvm *kvm)
4870 kvm_iommu_unmap_guest(kvm);
4871 kvm_free_pit(kvm);
4872 kfree(kvm->arch.vpic);
4873 kfree(kvm->arch.vioapic);
4874 kvm_free_vcpus(kvm);
4875 kvm_free_physmem(kvm);
4876 if (kvm->arch.apic_access_page)
4877 put_page(kvm->arch.apic_access_page);
4878 if (kvm->arch.ept_identity_pagetable)
4879 put_page(kvm->arch.ept_identity_pagetable);
4880 kfree(kvm);
4883 int kvm_arch_set_memory_region(struct kvm *kvm,
4884 struct kvm_userspace_memory_region *mem,
4885 struct kvm_memory_slot old,
4886 int user_alloc)
4888 int npages = mem->memory_size >> PAGE_SHIFT;
4889 struct kvm_memory_slot *memslot = &kvm->memslots[mem->slot];
4891 /*To keep backward compatibility with older userspace,
4892 *x86 needs to hanlde !user_alloc case.
4894 if (!user_alloc) {
4895 if (npages && !old.rmap) {
4896 unsigned long userspace_addr;
4898 down_write(&current->mm->mmap_sem);
4899 userspace_addr = do_mmap(NULL, 0,
4900 npages * PAGE_SIZE,
4901 PROT_READ | PROT_WRITE,
4902 MAP_PRIVATE | MAP_ANONYMOUS,
4904 up_write(&current->mm->mmap_sem);
4906 if (IS_ERR((void *)userspace_addr))
4907 return PTR_ERR((void *)userspace_addr);
4909 /* set userspace_addr atomically for kvm_hva_to_rmapp */
4910 spin_lock(&kvm->mmu_lock);
4911 memslot->userspace_addr = userspace_addr;
4912 spin_unlock(&kvm->mmu_lock);
4913 } else {
4914 if (!old.user_alloc && old.rmap) {
4915 int ret;
4917 down_write(&current->mm->mmap_sem);
4918 ret = do_munmap(current->mm, old.userspace_addr,
4919 old.npages * PAGE_SIZE);
4920 up_write(&current->mm->mmap_sem);
4921 if (ret < 0)
4922 printk(KERN_WARNING
4923 "kvm_vm_ioctl_set_memory_region: "
4924 "failed to munmap memory\n");
4929 spin_lock(&kvm->mmu_lock);
4930 if (!kvm->arch.n_requested_mmu_pages) {
4931 unsigned int nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
4932 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
4935 kvm_mmu_slot_remove_write_access(kvm, mem->slot);
4936 spin_unlock(&kvm->mmu_lock);
4938 return 0;
4941 void kvm_arch_flush_shadow(struct kvm *kvm)
4943 kvm_mmu_zap_all(kvm);
4944 kvm_reload_remote_mmus(kvm);
4947 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
4949 return vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE
4950 || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
4951 || vcpu->arch.nmi_pending ||
4952 (kvm_arch_interrupt_allowed(vcpu) &&
4953 kvm_cpu_has_interrupt(vcpu));
4956 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
4958 int me;
4959 int cpu = vcpu->cpu;
4961 if (waitqueue_active(&vcpu->wq)) {
4962 wake_up_interruptible(&vcpu->wq);
4963 ++vcpu->stat.halt_wakeup;
4966 me = get_cpu();
4967 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
4968 if (!test_and_set_bit(KVM_REQ_KICK, &vcpu->requests))
4969 smp_send_reschedule(cpu);
4970 put_cpu();
4973 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
4975 return kvm_x86_ops->interrupt_allowed(vcpu);
4978 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
4979 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
4980 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
4981 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
4982 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);