mfd: wm8350-i2c: Make sure the i2c regmap functions are compiled
[linux/fpc-iii.git] / arch / x86 / kvm / x86.c
blob06b37a671b1274b12f3826af4a62f7dc1a26f969
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
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11 * Authors:
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
14 * Amit Shah <amit.shah@qumranet.com>
15 * Ben-Ami Yassour <benami@il.ibm.com>
17 * This work is licensed under the terms of the GNU GPL, version 2. See
18 * the COPYING file in the top-level directory.
22 #include <linux/kvm_host.h>
23 #include "irq.h"
24 #include "mmu.h"
25 #include "i8254.h"
26 #include "tss.h"
27 #include "kvm_cache_regs.h"
28 #include "x86.h"
29 #include "cpuid.h"
31 #include <linux/clocksource.h>
32 #include <linux/interrupt.h>
33 #include <linux/kvm.h>
34 #include <linux/fs.h>
35 #include <linux/vmalloc.h>
36 #include <linux/module.h>
37 #include <linux/mman.h>
38 #include <linux/highmem.h>
39 #include <linux/iommu.h>
40 #include <linux/intel-iommu.h>
41 #include <linux/cpufreq.h>
42 #include <linux/user-return-notifier.h>
43 #include <linux/srcu.h>
44 #include <linux/slab.h>
45 #include <linux/perf_event.h>
46 #include <linux/uaccess.h>
47 #include <linux/hash.h>
48 #include <linux/pci.h>
49 #include <linux/timekeeper_internal.h>
50 #include <linux/pvclock_gtod.h>
51 #include <trace/events/kvm.h>
53 #define CREATE_TRACE_POINTS
54 #include "trace.h"
56 #include <asm/debugreg.h>
57 #include <asm/msr.h>
58 #include <asm/desc.h>
59 #include <asm/mtrr.h>
60 #include <asm/mce.h>
61 #include <asm/i387.h>
62 #include <asm/fpu-internal.h> /* Ugh! */
63 #include <asm/xcr.h>
64 #include <asm/pvclock.h>
65 #include <asm/div64.h>
67 #define MAX_IO_MSRS 256
68 #define KVM_MAX_MCE_BANKS 32
69 #define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
71 #define emul_to_vcpu(ctxt) \
72 container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
74 /* EFER defaults:
75 * - enable syscall per default because its emulated by KVM
76 * - enable LME and LMA per default on 64 bit KVM
78 #ifdef CONFIG_X86_64
79 static
80 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
81 #else
82 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
83 #endif
85 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
86 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
88 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
89 static void process_nmi(struct kvm_vcpu *vcpu);
91 struct kvm_x86_ops *kvm_x86_ops;
92 EXPORT_SYMBOL_GPL(kvm_x86_ops);
94 static bool ignore_msrs = 0;
95 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
97 unsigned int min_timer_period_us = 500;
98 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
100 bool kvm_has_tsc_control;
101 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
102 u32 kvm_max_guest_tsc_khz;
103 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
105 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
106 static u32 tsc_tolerance_ppm = 250;
107 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
109 #define KVM_NR_SHARED_MSRS 16
111 struct kvm_shared_msrs_global {
112 int nr;
113 u32 msrs[KVM_NR_SHARED_MSRS];
116 struct kvm_shared_msrs {
117 struct user_return_notifier urn;
118 bool registered;
119 struct kvm_shared_msr_values {
120 u64 host;
121 u64 curr;
122 } values[KVM_NR_SHARED_MSRS];
125 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
126 static struct kvm_shared_msrs __percpu *shared_msrs;
128 struct kvm_stats_debugfs_item debugfs_entries[] = {
129 { "pf_fixed", VCPU_STAT(pf_fixed) },
130 { "pf_guest", VCPU_STAT(pf_guest) },
131 { "tlb_flush", VCPU_STAT(tlb_flush) },
132 { "invlpg", VCPU_STAT(invlpg) },
133 { "exits", VCPU_STAT(exits) },
134 { "io_exits", VCPU_STAT(io_exits) },
135 { "mmio_exits", VCPU_STAT(mmio_exits) },
136 { "signal_exits", VCPU_STAT(signal_exits) },
137 { "irq_window", VCPU_STAT(irq_window_exits) },
138 { "nmi_window", VCPU_STAT(nmi_window_exits) },
139 { "halt_exits", VCPU_STAT(halt_exits) },
140 { "halt_wakeup", VCPU_STAT(halt_wakeup) },
141 { "hypercalls", VCPU_STAT(hypercalls) },
142 { "request_irq", VCPU_STAT(request_irq_exits) },
143 { "irq_exits", VCPU_STAT(irq_exits) },
144 { "host_state_reload", VCPU_STAT(host_state_reload) },
145 { "efer_reload", VCPU_STAT(efer_reload) },
146 { "fpu_reload", VCPU_STAT(fpu_reload) },
147 { "insn_emulation", VCPU_STAT(insn_emulation) },
148 { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
149 { "irq_injections", VCPU_STAT(irq_injections) },
150 { "nmi_injections", VCPU_STAT(nmi_injections) },
151 { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
152 { "mmu_pte_write", VM_STAT(mmu_pte_write) },
153 { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
154 { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
155 { "mmu_flooded", VM_STAT(mmu_flooded) },
156 { "mmu_recycled", VM_STAT(mmu_recycled) },
157 { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
158 { "mmu_unsync", VM_STAT(mmu_unsync) },
159 { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
160 { "largepages", VM_STAT(lpages) },
161 { NULL }
164 u64 __read_mostly host_xcr0;
166 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
168 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
170 int i;
171 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
172 vcpu->arch.apf.gfns[i] = ~0;
175 static void kvm_on_user_return(struct user_return_notifier *urn)
177 unsigned slot;
178 struct kvm_shared_msrs *locals
179 = container_of(urn, struct kvm_shared_msrs, urn);
180 struct kvm_shared_msr_values *values;
182 for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
183 values = &locals->values[slot];
184 if (values->host != values->curr) {
185 wrmsrl(shared_msrs_global.msrs[slot], values->host);
186 values->curr = values->host;
189 locals->registered = false;
190 user_return_notifier_unregister(urn);
193 static void shared_msr_update(unsigned slot, u32 msr)
195 u64 value;
196 unsigned int cpu = smp_processor_id();
197 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
199 /* only read, and nobody should modify it at this time,
200 * so don't need lock */
201 if (slot >= shared_msrs_global.nr) {
202 printk(KERN_ERR "kvm: invalid MSR slot!");
203 return;
205 rdmsrl_safe(msr, &value);
206 smsr->values[slot].host = value;
207 smsr->values[slot].curr = value;
210 void kvm_define_shared_msr(unsigned slot, u32 msr)
212 if (slot >= shared_msrs_global.nr)
213 shared_msrs_global.nr = slot + 1;
214 shared_msrs_global.msrs[slot] = msr;
215 /* we need ensured the shared_msr_global have been updated */
216 smp_wmb();
218 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
220 static void kvm_shared_msr_cpu_online(void)
222 unsigned i;
224 for (i = 0; i < shared_msrs_global.nr; ++i)
225 shared_msr_update(i, shared_msrs_global.msrs[i]);
228 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
230 unsigned int cpu = smp_processor_id();
231 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
232 int err;
234 if (((value ^ smsr->values[slot].curr) & mask) == 0)
235 return 0;
236 smsr->values[slot].curr = value;
237 err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
238 if (err)
239 return 1;
241 if (!smsr->registered) {
242 smsr->urn.on_user_return = kvm_on_user_return;
243 user_return_notifier_register(&smsr->urn);
244 smsr->registered = true;
246 return 0;
248 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
250 static void drop_user_return_notifiers(void *ignore)
252 unsigned int cpu = smp_processor_id();
253 struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
255 if (smsr->registered)
256 kvm_on_user_return(&smsr->urn);
259 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
261 return vcpu->arch.apic_base;
263 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
265 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
267 /* TODO: reserve bits check */
268 kvm_lapic_set_base(vcpu, data);
270 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
272 asmlinkage void kvm_spurious_fault(void)
274 /* Fault while not rebooting. We want the trace. */
275 BUG();
277 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
279 #define EXCPT_BENIGN 0
280 #define EXCPT_CONTRIBUTORY 1
281 #define EXCPT_PF 2
283 static int exception_class(int vector)
285 switch (vector) {
286 case PF_VECTOR:
287 return EXCPT_PF;
288 case DE_VECTOR:
289 case TS_VECTOR:
290 case NP_VECTOR:
291 case SS_VECTOR:
292 case GP_VECTOR:
293 return EXCPT_CONTRIBUTORY;
294 default:
295 break;
297 return EXCPT_BENIGN;
300 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
301 unsigned nr, bool has_error, u32 error_code,
302 bool reinject)
304 u32 prev_nr;
305 int class1, class2;
307 kvm_make_request(KVM_REQ_EVENT, vcpu);
309 if (!vcpu->arch.exception.pending) {
310 queue:
311 vcpu->arch.exception.pending = true;
312 vcpu->arch.exception.has_error_code = has_error;
313 vcpu->arch.exception.nr = nr;
314 vcpu->arch.exception.error_code = error_code;
315 vcpu->arch.exception.reinject = reinject;
316 return;
319 /* to check exception */
320 prev_nr = vcpu->arch.exception.nr;
321 if (prev_nr == DF_VECTOR) {
322 /* triple fault -> shutdown */
323 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
324 return;
326 class1 = exception_class(prev_nr);
327 class2 = exception_class(nr);
328 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
329 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
330 /* generate double fault per SDM Table 5-5 */
331 vcpu->arch.exception.pending = true;
332 vcpu->arch.exception.has_error_code = true;
333 vcpu->arch.exception.nr = DF_VECTOR;
334 vcpu->arch.exception.error_code = 0;
335 } else
336 /* replace previous exception with a new one in a hope
337 that instruction re-execution will regenerate lost
338 exception */
339 goto queue;
342 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
344 kvm_multiple_exception(vcpu, nr, false, 0, false);
346 EXPORT_SYMBOL_GPL(kvm_queue_exception);
348 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
350 kvm_multiple_exception(vcpu, nr, false, 0, true);
352 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
354 void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
356 if (err)
357 kvm_inject_gp(vcpu, 0);
358 else
359 kvm_x86_ops->skip_emulated_instruction(vcpu);
361 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
363 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
365 ++vcpu->stat.pf_guest;
366 vcpu->arch.cr2 = fault->address;
367 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
369 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
371 void kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
373 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
374 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
375 else
376 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
379 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
381 atomic_inc(&vcpu->arch.nmi_queued);
382 kvm_make_request(KVM_REQ_NMI, vcpu);
384 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
386 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
388 kvm_multiple_exception(vcpu, nr, true, error_code, false);
390 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
392 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
394 kvm_multiple_exception(vcpu, nr, true, error_code, true);
396 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
399 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
400 * a #GP and return false.
402 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
404 if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
405 return true;
406 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
407 return false;
409 EXPORT_SYMBOL_GPL(kvm_require_cpl);
412 * This function will be used to read from the physical memory of the currently
413 * running guest. The difference to kvm_read_guest_page is that this function
414 * can read from guest physical or from the guest's guest physical memory.
416 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
417 gfn_t ngfn, void *data, int offset, int len,
418 u32 access)
420 gfn_t real_gfn;
421 gpa_t ngpa;
423 ngpa = gfn_to_gpa(ngfn);
424 real_gfn = mmu->translate_gpa(vcpu, ngpa, access);
425 if (real_gfn == UNMAPPED_GVA)
426 return -EFAULT;
428 real_gfn = gpa_to_gfn(real_gfn);
430 return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
432 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
434 int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
435 void *data, int offset, int len, u32 access)
437 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
438 data, offset, len, access);
442 * Load the pae pdptrs. Return true is they are all valid.
444 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
446 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
447 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
448 int i;
449 int ret;
450 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
452 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
453 offset * sizeof(u64), sizeof(pdpte),
454 PFERR_USER_MASK|PFERR_WRITE_MASK);
455 if (ret < 0) {
456 ret = 0;
457 goto out;
459 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
460 if (is_present_gpte(pdpte[i]) &&
461 (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
462 ret = 0;
463 goto out;
466 ret = 1;
468 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
469 __set_bit(VCPU_EXREG_PDPTR,
470 (unsigned long *)&vcpu->arch.regs_avail);
471 __set_bit(VCPU_EXREG_PDPTR,
472 (unsigned long *)&vcpu->arch.regs_dirty);
473 out:
475 return ret;
477 EXPORT_SYMBOL_GPL(load_pdptrs);
479 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
481 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
482 bool changed = true;
483 int offset;
484 gfn_t gfn;
485 int r;
487 if (is_long_mode(vcpu) || !is_pae(vcpu))
488 return false;
490 if (!test_bit(VCPU_EXREG_PDPTR,
491 (unsigned long *)&vcpu->arch.regs_avail))
492 return true;
494 gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
495 offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
496 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
497 PFERR_USER_MASK | PFERR_WRITE_MASK);
498 if (r < 0)
499 goto out;
500 changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
501 out:
503 return changed;
506 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
508 unsigned long old_cr0 = kvm_read_cr0(vcpu);
509 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
510 X86_CR0_CD | X86_CR0_NW;
512 cr0 |= X86_CR0_ET;
514 #ifdef CONFIG_X86_64
515 if (cr0 & 0xffffffff00000000UL)
516 return 1;
517 #endif
519 cr0 &= ~CR0_RESERVED_BITS;
521 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
522 return 1;
524 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
525 return 1;
527 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
528 #ifdef CONFIG_X86_64
529 if ((vcpu->arch.efer & EFER_LME)) {
530 int cs_db, cs_l;
532 if (!is_pae(vcpu))
533 return 1;
534 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
535 if (cs_l)
536 return 1;
537 } else
538 #endif
539 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
540 kvm_read_cr3(vcpu)))
541 return 1;
544 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
545 return 1;
547 kvm_x86_ops->set_cr0(vcpu, cr0);
549 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
550 kvm_clear_async_pf_completion_queue(vcpu);
551 kvm_async_pf_hash_reset(vcpu);
554 if ((cr0 ^ old_cr0) & update_bits)
555 kvm_mmu_reset_context(vcpu);
556 return 0;
558 EXPORT_SYMBOL_GPL(kvm_set_cr0);
560 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
562 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
564 EXPORT_SYMBOL_GPL(kvm_lmsw);
566 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
568 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
569 !vcpu->guest_xcr0_loaded) {
570 /* kvm_set_xcr() also depends on this */
571 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
572 vcpu->guest_xcr0_loaded = 1;
576 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
578 if (vcpu->guest_xcr0_loaded) {
579 if (vcpu->arch.xcr0 != host_xcr0)
580 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
581 vcpu->guest_xcr0_loaded = 0;
585 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
587 u64 xcr0;
589 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
590 if (index != XCR_XFEATURE_ENABLED_MASK)
591 return 1;
592 xcr0 = xcr;
593 if (!(xcr0 & XSTATE_FP))
594 return 1;
595 if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
596 return 1;
597 if (xcr0 & ~host_xcr0)
598 return 1;
599 kvm_put_guest_xcr0(vcpu);
600 vcpu->arch.xcr0 = xcr0;
601 return 0;
604 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
606 if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
607 __kvm_set_xcr(vcpu, index, xcr)) {
608 kvm_inject_gp(vcpu, 0);
609 return 1;
611 return 0;
613 EXPORT_SYMBOL_GPL(kvm_set_xcr);
615 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
617 unsigned long old_cr4 = kvm_read_cr4(vcpu);
618 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
619 X86_CR4_PAE | X86_CR4_SMEP;
620 if (cr4 & CR4_RESERVED_BITS)
621 return 1;
623 if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
624 return 1;
626 if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
627 return 1;
629 if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_FSGSBASE))
630 return 1;
632 if (is_long_mode(vcpu)) {
633 if (!(cr4 & X86_CR4_PAE))
634 return 1;
635 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
636 && ((cr4 ^ old_cr4) & pdptr_bits)
637 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
638 kvm_read_cr3(vcpu)))
639 return 1;
641 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
642 if (!guest_cpuid_has_pcid(vcpu))
643 return 1;
645 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
646 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
647 return 1;
650 if (kvm_x86_ops->set_cr4(vcpu, cr4))
651 return 1;
653 if (((cr4 ^ old_cr4) & pdptr_bits) ||
654 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
655 kvm_mmu_reset_context(vcpu);
657 if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
658 kvm_update_cpuid(vcpu);
660 return 0;
662 EXPORT_SYMBOL_GPL(kvm_set_cr4);
664 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
666 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
667 kvm_mmu_sync_roots(vcpu);
668 kvm_mmu_flush_tlb(vcpu);
669 return 0;
672 if (is_long_mode(vcpu)) {
673 if (kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE)) {
674 if (cr3 & CR3_PCID_ENABLED_RESERVED_BITS)
675 return 1;
676 } else
677 if (cr3 & CR3_L_MODE_RESERVED_BITS)
678 return 1;
679 } else {
680 if (is_pae(vcpu)) {
681 if (cr3 & CR3_PAE_RESERVED_BITS)
682 return 1;
683 if (is_paging(vcpu) &&
684 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
685 return 1;
688 * We don't check reserved bits in nonpae mode, because
689 * this isn't enforced, and VMware depends on this.
693 vcpu->arch.cr3 = cr3;
694 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
695 vcpu->arch.mmu.new_cr3(vcpu);
696 return 0;
698 EXPORT_SYMBOL_GPL(kvm_set_cr3);
700 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
702 if (cr8 & CR8_RESERVED_BITS)
703 return 1;
704 if (irqchip_in_kernel(vcpu->kvm))
705 kvm_lapic_set_tpr(vcpu, cr8);
706 else
707 vcpu->arch.cr8 = cr8;
708 return 0;
710 EXPORT_SYMBOL_GPL(kvm_set_cr8);
712 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
714 if (irqchip_in_kernel(vcpu->kvm))
715 return kvm_lapic_get_cr8(vcpu);
716 else
717 return vcpu->arch.cr8;
719 EXPORT_SYMBOL_GPL(kvm_get_cr8);
721 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
723 unsigned long dr7;
725 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
726 dr7 = vcpu->arch.guest_debug_dr7;
727 else
728 dr7 = vcpu->arch.dr7;
729 kvm_x86_ops->set_dr7(vcpu, dr7);
730 vcpu->arch.switch_db_regs = (dr7 & DR7_BP_EN_MASK);
733 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
735 switch (dr) {
736 case 0 ... 3:
737 vcpu->arch.db[dr] = val;
738 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
739 vcpu->arch.eff_db[dr] = val;
740 break;
741 case 4:
742 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
743 return 1; /* #UD */
744 /* fall through */
745 case 6:
746 if (val & 0xffffffff00000000ULL)
747 return -1; /* #GP */
748 vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
749 break;
750 case 5:
751 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
752 return 1; /* #UD */
753 /* fall through */
754 default: /* 7 */
755 if (val & 0xffffffff00000000ULL)
756 return -1; /* #GP */
757 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
758 kvm_update_dr7(vcpu);
759 break;
762 return 0;
765 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
767 int res;
769 res = __kvm_set_dr(vcpu, dr, val);
770 if (res > 0)
771 kvm_queue_exception(vcpu, UD_VECTOR);
772 else if (res < 0)
773 kvm_inject_gp(vcpu, 0);
775 return res;
777 EXPORT_SYMBOL_GPL(kvm_set_dr);
779 static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
781 switch (dr) {
782 case 0 ... 3:
783 *val = vcpu->arch.db[dr];
784 break;
785 case 4:
786 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
787 return 1;
788 /* fall through */
789 case 6:
790 *val = vcpu->arch.dr6;
791 break;
792 case 5:
793 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
794 return 1;
795 /* fall through */
796 default: /* 7 */
797 *val = vcpu->arch.dr7;
798 break;
801 return 0;
804 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
806 if (_kvm_get_dr(vcpu, dr, val)) {
807 kvm_queue_exception(vcpu, UD_VECTOR);
808 return 1;
810 return 0;
812 EXPORT_SYMBOL_GPL(kvm_get_dr);
814 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
816 u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
817 u64 data;
818 int err;
820 err = kvm_pmu_read_pmc(vcpu, ecx, &data);
821 if (err)
822 return err;
823 kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
824 kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
825 return err;
827 EXPORT_SYMBOL_GPL(kvm_rdpmc);
830 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
831 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
833 * This list is modified at module load time to reflect the
834 * capabilities of the host cpu. This capabilities test skips MSRs that are
835 * kvm-specific. Those are put in the beginning of the list.
838 #define KVM_SAVE_MSRS_BEGIN 10
839 static u32 msrs_to_save[] = {
840 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
841 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
842 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
843 HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
844 MSR_KVM_PV_EOI_EN,
845 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
846 MSR_STAR,
847 #ifdef CONFIG_X86_64
848 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
849 #endif
850 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
851 MSR_IA32_FEATURE_CONTROL
854 static unsigned num_msrs_to_save;
856 static const u32 emulated_msrs[] = {
857 MSR_IA32_TSC_ADJUST,
858 MSR_IA32_TSCDEADLINE,
859 MSR_IA32_MISC_ENABLE,
860 MSR_IA32_MCG_STATUS,
861 MSR_IA32_MCG_CTL,
864 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
866 if (efer & efer_reserved_bits)
867 return false;
869 if (efer & EFER_FFXSR) {
870 struct kvm_cpuid_entry2 *feat;
872 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
873 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
874 return false;
877 if (efer & EFER_SVME) {
878 struct kvm_cpuid_entry2 *feat;
880 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
881 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
882 return false;
885 return true;
887 EXPORT_SYMBOL_GPL(kvm_valid_efer);
889 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
891 u64 old_efer = vcpu->arch.efer;
893 if (!kvm_valid_efer(vcpu, efer))
894 return 1;
896 if (is_paging(vcpu)
897 && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
898 return 1;
900 efer &= ~EFER_LMA;
901 efer |= vcpu->arch.efer & EFER_LMA;
903 kvm_x86_ops->set_efer(vcpu, efer);
905 /* Update reserved bits */
906 if ((efer ^ old_efer) & EFER_NX)
907 kvm_mmu_reset_context(vcpu);
909 return 0;
912 void kvm_enable_efer_bits(u64 mask)
914 efer_reserved_bits &= ~mask;
916 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
919 * Writes msr value into into the appropriate "register".
920 * Returns 0 on success, non-0 otherwise.
921 * Assumes vcpu_load() was already called.
923 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
925 switch (msr->index) {
926 case MSR_FS_BASE:
927 case MSR_GS_BASE:
928 case MSR_KERNEL_GS_BASE:
929 case MSR_CSTAR:
930 case MSR_LSTAR:
931 if (is_noncanonical_address(msr->data))
932 return 1;
933 break;
934 case MSR_IA32_SYSENTER_EIP:
935 case MSR_IA32_SYSENTER_ESP:
937 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
938 * non-canonical address is written on Intel but not on
939 * AMD (which ignores the top 32-bits, because it does
940 * not implement 64-bit SYSENTER).
942 * 64-bit code should hence be able to write a non-canonical
943 * value on AMD. Making the address canonical ensures that
944 * vmentry does not fail on Intel after writing a non-canonical
945 * value, and that something deterministic happens if the guest
946 * invokes 64-bit SYSENTER.
948 msr->data = get_canonical(msr->data);
950 return kvm_x86_ops->set_msr(vcpu, msr);
952 EXPORT_SYMBOL_GPL(kvm_set_msr);
955 * Adapt set_msr() to msr_io()'s calling convention
957 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
959 struct msr_data msr;
961 msr.data = *data;
962 msr.index = index;
963 msr.host_initiated = true;
964 return kvm_set_msr(vcpu, &msr);
967 #ifdef CONFIG_X86_64
968 struct pvclock_gtod_data {
969 seqcount_t seq;
971 struct { /* extract of a clocksource struct */
972 int vclock_mode;
973 cycle_t cycle_last;
974 cycle_t mask;
975 u32 mult;
976 u32 shift;
977 } clock;
979 /* open coded 'struct timespec' */
980 u64 monotonic_time_snsec;
981 time_t monotonic_time_sec;
984 static struct pvclock_gtod_data pvclock_gtod_data;
986 static void update_pvclock_gtod(struct timekeeper *tk)
988 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
990 write_seqcount_begin(&vdata->seq);
992 /* copy pvclock gtod data */
993 vdata->clock.vclock_mode = tk->clock->archdata.vclock_mode;
994 vdata->clock.cycle_last = tk->clock->cycle_last;
995 vdata->clock.mask = tk->clock->mask;
996 vdata->clock.mult = tk->mult;
997 vdata->clock.shift = tk->shift;
999 vdata->monotonic_time_sec = tk->xtime_sec
1000 + tk->wall_to_monotonic.tv_sec;
1001 vdata->monotonic_time_snsec = tk->xtime_nsec
1002 + (tk->wall_to_monotonic.tv_nsec
1003 << tk->shift);
1004 while (vdata->monotonic_time_snsec >=
1005 (((u64)NSEC_PER_SEC) << tk->shift)) {
1006 vdata->monotonic_time_snsec -=
1007 ((u64)NSEC_PER_SEC) << tk->shift;
1008 vdata->monotonic_time_sec++;
1011 write_seqcount_end(&vdata->seq);
1013 #endif
1016 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1018 int version;
1019 int r;
1020 struct pvclock_wall_clock wc;
1021 struct timespec boot;
1023 if (!wall_clock)
1024 return;
1026 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1027 if (r)
1028 return;
1030 if (version & 1)
1031 ++version; /* first time write, random junk */
1033 ++version;
1035 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1038 * The guest calculates current wall clock time by adding
1039 * system time (updated by kvm_guest_time_update below) to the
1040 * wall clock specified here. guest system time equals host
1041 * system time for us, thus we must fill in host boot time here.
1043 getboottime(&boot);
1045 if (kvm->arch.kvmclock_offset) {
1046 struct timespec ts = ns_to_timespec(kvm->arch.kvmclock_offset);
1047 boot = timespec_sub(boot, ts);
1049 wc.sec = boot.tv_sec;
1050 wc.nsec = boot.tv_nsec;
1051 wc.version = version;
1053 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1055 version++;
1056 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1059 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1061 uint32_t quotient, remainder;
1063 /* Don't try to replace with do_div(), this one calculates
1064 * "(dividend << 32) / divisor" */
1065 __asm__ ( "divl %4"
1066 : "=a" (quotient), "=d" (remainder)
1067 : "0" (0), "1" (dividend), "r" (divisor) );
1068 return quotient;
1071 static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
1072 s8 *pshift, u32 *pmultiplier)
1074 uint64_t scaled64;
1075 int32_t shift = 0;
1076 uint64_t tps64;
1077 uint32_t tps32;
1079 tps64 = base_khz * 1000LL;
1080 scaled64 = scaled_khz * 1000LL;
1081 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1082 tps64 >>= 1;
1083 shift--;
1086 tps32 = (uint32_t)tps64;
1087 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1088 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1089 scaled64 >>= 1;
1090 else
1091 tps32 <<= 1;
1092 shift++;
1095 *pshift = shift;
1096 *pmultiplier = div_frac(scaled64, tps32);
1098 pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
1099 __func__, base_khz, scaled_khz, shift, *pmultiplier);
1102 static inline u64 get_kernel_ns(void)
1104 struct timespec ts;
1106 ktime_get_ts(&ts);
1107 monotonic_to_bootbased(&ts);
1108 return timespec_to_ns(&ts);
1111 #ifdef CONFIG_X86_64
1112 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1113 #endif
1115 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1116 unsigned long max_tsc_khz;
1118 static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
1120 return pvclock_scale_delta(nsec, vcpu->arch.virtual_tsc_mult,
1121 vcpu->arch.virtual_tsc_shift);
1124 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1126 u64 v = (u64)khz * (1000000 + ppm);
1127 do_div(v, 1000000);
1128 return v;
1131 static void kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
1133 u32 thresh_lo, thresh_hi;
1134 int use_scaling = 0;
1136 /* tsc_khz can be zero if TSC calibration fails */
1137 if (this_tsc_khz == 0)
1138 return;
1140 /* Compute a scale to convert nanoseconds in TSC cycles */
1141 kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
1142 &vcpu->arch.virtual_tsc_shift,
1143 &vcpu->arch.virtual_tsc_mult);
1144 vcpu->arch.virtual_tsc_khz = this_tsc_khz;
1147 * Compute the variation in TSC rate which is acceptable
1148 * within the range of tolerance and decide if the
1149 * rate being applied is within that bounds of the hardware
1150 * rate. If so, no scaling or compensation need be done.
1152 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1153 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1154 if (this_tsc_khz < thresh_lo || this_tsc_khz > thresh_hi) {
1155 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", this_tsc_khz, thresh_lo, thresh_hi);
1156 use_scaling = 1;
1158 kvm_x86_ops->set_tsc_khz(vcpu, this_tsc_khz, use_scaling);
1161 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1163 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1164 vcpu->arch.virtual_tsc_mult,
1165 vcpu->arch.virtual_tsc_shift);
1166 tsc += vcpu->arch.this_tsc_write;
1167 return tsc;
1170 void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1172 #ifdef CONFIG_X86_64
1173 bool vcpus_matched;
1174 struct kvm_arch *ka = &vcpu->kvm->arch;
1175 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1177 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1178 atomic_read(&vcpu->kvm->online_vcpus));
1181 * Once the masterclock is enabled, always perform request in
1182 * order to update it.
1184 * In order to enable masterclock, the host clocksource must be TSC
1185 * and the vcpus need to have matched TSCs. When that happens,
1186 * perform request to enable masterclock.
1188 if (ka->use_master_clock ||
1189 (gtod->clock.vclock_mode == VCLOCK_TSC && vcpus_matched))
1190 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1192 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1193 atomic_read(&vcpu->kvm->online_vcpus),
1194 ka->use_master_clock, gtod->clock.vclock_mode);
1195 #endif
1198 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1200 u64 curr_offset = kvm_x86_ops->read_tsc_offset(vcpu);
1201 vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1204 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1206 struct kvm *kvm = vcpu->kvm;
1207 u64 offset, ns, elapsed;
1208 unsigned long flags;
1209 s64 usdiff;
1210 bool matched;
1211 u64 data = msr->data;
1213 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1214 offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
1215 ns = get_kernel_ns();
1216 elapsed = ns - kvm->arch.last_tsc_nsec;
1218 if (vcpu->arch.virtual_tsc_khz) {
1219 int faulted = 0;
1221 /* n.b - signed multiplication and division required */
1222 usdiff = data - kvm->arch.last_tsc_write;
1223 #ifdef CONFIG_X86_64
1224 usdiff = (usdiff * 1000) / vcpu->arch.virtual_tsc_khz;
1225 #else
1226 /* do_div() only does unsigned */
1227 asm("1: idivl %[divisor]\n"
1228 "2: xor %%edx, %%edx\n"
1229 " movl $0, %[faulted]\n"
1230 "3:\n"
1231 ".section .fixup,\"ax\"\n"
1232 "4: movl $1, %[faulted]\n"
1233 " jmp 3b\n"
1234 ".previous\n"
1236 _ASM_EXTABLE(1b, 4b)
1238 : "=A"(usdiff), [faulted] "=r" (faulted)
1239 : "A"(usdiff * 1000), [divisor] "rm"(vcpu->arch.virtual_tsc_khz));
1241 #endif
1242 do_div(elapsed, 1000);
1243 usdiff -= elapsed;
1244 if (usdiff < 0)
1245 usdiff = -usdiff;
1247 /* idivl overflow => difference is larger than USEC_PER_SEC */
1248 if (faulted)
1249 usdiff = USEC_PER_SEC;
1250 } else
1251 usdiff = USEC_PER_SEC; /* disable TSC match window below */
1254 * Special case: TSC write with a small delta (1 second) of virtual
1255 * cycle time against real time is interpreted as an attempt to
1256 * synchronize the CPU.
1258 * For a reliable TSC, we can match TSC offsets, and for an unstable
1259 * TSC, we add elapsed time in this computation. We could let the
1260 * compensation code attempt to catch up if we fall behind, but
1261 * it's better to try to match offsets from the beginning.
1263 if (usdiff < USEC_PER_SEC &&
1264 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1265 if (!check_tsc_unstable()) {
1266 offset = kvm->arch.cur_tsc_offset;
1267 pr_debug("kvm: matched tsc offset for %llu\n", data);
1268 } else {
1269 u64 delta = nsec_to_cycles(vcpu, elapsed);
1270 data += delta;
1271 offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
1272 pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1274 matched = true;
1275 } else {
1277 * We split periods of matched TSC writes into generations.
1278 * For each generation, we track the original measured
1279 * nanosecond time, offset, and write, so if TSCs are in
1280 * sync, we can match exact offset, and if not, we can match
1281 * exact software computation in compute_guest_tsc()
1283 * These values are tracked in kvm->arch.cur_xxx variables.
1285 kvm->arch.cur_tsc_generation++;
1286 kvm->arch.cur_tsc_nsec = ns;
1287 kvm->arch.cur_tsc_write = data;
1288 kvm->arch.cur_tsc_offset = offset;
1289 matched = false;
1290 pr_debug("kvm: new tsc generation %u, clock %llu\n",
1291 kvm->arch.cur_tsc_generation, data);
1295 * We also track th most recent recorded KHZ, write and time to
1296 * allow the matching interval to be extended at each write.
1298 kvm->arch.last_tsc_nsec = ns;
1299 kvm->arch.last_tsc_write = data;
1300 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1302 /* Reset of TSC must disable overshoot protection below */
1303 vcpu->arch.hv_clock.tsc_timestamp = 0;
1304 vcpu->arch.last_guest_tsc = data;
1306 /* Keep track of which generation this VCPU has synchronized to */
1307 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1308 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1309 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1311 if (guest_cpuid_has_tsc_adjust(vcpu) && !msr->host_initiated)
1312 update_ia32_tsc_adjust_msr(vcpu, offset);
1313 kvm_x86_ops->write_tsc_offset(vcpu, offset);
1314 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1316 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1317 if (matched)
1318 kvm->arch.nr_vcpus_matched_tsc++;
1319 else
1320 kvm->arch.nr_vcpus_matched_tsc = 0;
1322 kvm_track_tsc_matching(vcpu);
1323 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1326 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1328 #ifdef CONFIG_X86_64
1330 static cycle_t read_tsc(void)
1332 cycle_t ret;
1333 u64 last;
1336 * Empirically, a fence (of type that depends on the CPU)
1337 * before rdtsc is enough to ensure that rdtsc is ordered
1338 * with respect to loads. The various CPU manuals are unclear
1339 * as to whether rdtsc can be reordered with later loads,
1340 * but no one has ever seen it happen.
1342 rdtsc_barrier();
1343 ret = (cycle_t)vget_cycles();
1345 last = pvclock_gtod_data.clock.cycle_last;
1347 if (likely(ret >= last))
1348 return ret;
1351 * GCC likes to generate cmov here, but this branch is extremely
1352 * predictable (it's just a funciton of time and the likely is
1353 * very likely) and there's a data dependence, so force GCC
1354 * to generate a branch instead. I don't barrier() because
1355 * we don't actually need a barrier, and if this function
1356 * ever gets inlined it will generate worse code.
1358 asm volatile ("");
1359 return last;
1362 static inline u64 vgettsc(cycle_t *cycle_now)
1364 long v;
1365 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1367 *cycle_now = read_tsc();
1369 v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
1370 return v * gtod->clock.mult;
1373 static int do_monotonic(struct timespec *ts, cycle_t *cycle_now)
1375 unsigned long seq;
1376 u64 ns;
1377 int mode;
1378 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1380 ts->tv_nsec = 0;
1381 do {
1382 seq = read_seqcount_begin(&gtod->seq);
1383 mode = gtod->clock.vclock_mode;
1384 ts->tv_sec = gtod->monotonic_time_sec;
1385 ns = gtod->monotonic_time_snsec;
1386 ns += vgettsc(cycle_now);
1387 ns >>= gtod->clock.shift;
1388 } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
1389 timespec_add_ns(ts, ns);
1391 return mode;
1394 /* returns true if host is using tsc clocksource */
1395 static bool kvm_get_time_and_clockread(s64 *kernel_ns, cycle_t *cycle_now)
1397 struct timespec ts;
1399 /* checked again under seqlock below */
1400 if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
1401 return false;
1403 if (do_monotonic(&ts, cycle_now) != VCLOCK_TSC)
1404 return false;
1406 monotonic_to_bootbased(&ts);
1407 *kernel_ns = timespec_to_ns(&ts);
1409 return true;
1411 #endif
1415 * Assuming a stable TSC across physical CPUS, and a stable TSC
1416 * across virtual CPUs, the following condition is possible.
1417 * Each numbered line represents an event visible to both
1418 * CPUs at the next numbered event.
1420 * "timespecX" represents host monotonic time. "tscX" represents
1421 * RDTSC value.
1423 * VCPU0 on CPU0 | VCPU1 on CPU1
1425 * 1. read timespec0,tsc0
1426 * 2. | timespec1 = timespec0 + N
1427 * | tsc1 = tsc0 + M
1428 * 3. transition to guest | transition to guest
1429 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1430 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
1431 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1433 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1435 * - ret0 < ret1
1436 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1437 * ...
1438 * - 0 < N - M => M < N
1440 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1441 * always the case (the difference between two distinct xtime instances
1442 * might be smaller then the difference between corresponding TSC reads,
1443 * when updating guest vcpus pvclock areas).
1445 * To avoid that problem, do not allow visibility of distinct
1446 * system_timestamp/tsc_timestamp values simultaneously: use a master
1447 * copy of host monotonic time values. Update that master copy
1448 * in lockstep.
1450 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1454 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1456 #ifdef CONFIG_X86_64
1457 struct kvm_arch *ka = &kvm->arch;
1458 int vclock_mode;
1459 bool host_tsc_clocksource, vcpus_matched;
1461 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1462 atomic_read(&kvm->online_vcpus));
1465 * If the host uses TSC clock, then passthrough TSC as stable
1466 * to the guest.
1468 host_tsc_clocksource = kvm_get_time_and_clockread(
1469 &ka->master_kernel_ns,
1470 &ka->master_cycle_now);
1472 ka->use_master_clock = host_tsc_clocksource & vcpus_matched;
1474 if (ka->use_master_clock)
1475 atomic_set(&kvm_guest_has_master_clock, 1);
1477 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1478 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1479 vcpus_matched);
1480 #endif
1483 static void kvm_gen_update_masterclock(struct kvm *kvm)
1485 #ifdef CONFIG_X86_64
1486 int i;
1487 struct kvm_vcpu *vcpu;
1488 struct kvm_arch *ka = &kvm->arch;
1490 spin_lock(&ka->pvclock_gtod_sync_lock);
1491 kvm_make_mclock_inprogress_request(kvm);
1492 /* no guest entries from this point */
1493 pvclock_update_vm_gtod_copy(kvm);
1495 kvm_for_each_vcpu(i, vcpu, kvm)
1496 set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
1498 /* guest entries allowed */
1499 kvm_for_each_vcpu(i, vcpu, kvm)
1500 clear_bit(KVM_REQ_MCLOCK_INPROGRESS, &vcpu->requests);
1502 spin_unlock(&ka->pvclock_gtod_sync_lock);
1503 #endif
1506 static int kvm_guest_time_update(struct kvm_vcpu *v)
1508 unsigned long flags, this_tsc_khz;
1509 struct kvm_vcpu_arch *vcpu = &v->arch;
1510 struct kvm_arch *ka = &v->kvm->arch;
1511 s64 kernel_ns, max_kernel_ns;
1512 u64 tsc_timestamp, host_tsc;
1513 struct pvclock_vcpu_time_info guest_hv_clock;
1514 u8 pvclock_flags;
1515 bool use_master_clock;
1517 kernel_ns = 0;
1518 host_tsc = 0;
1521 * If the host uses TSC clock, then passthrough TSC as stable
1522 * to the guest.
1524 spin_lock(&ka->pvclock_gtod_sync_lock);
1525 use_master_clock = ka->use_master_clock;
1526 if (use_master_clock) {
1527 host_tsc = ka->master_cycle_now;
1528 kernel_ns = ka->master_kernel_ns;
1530 spin_unlock(&ka->pvclock_gtod_sync_lock);
1532 /* Keep irq disabled to prevent changes to the clock */
1533 local_irq_save(flags);
1534 this_tsc_khz = __get_cpu_var(cpu_tsc_khz);
1535 if (unlikely(this_tsc_khz == 0)) {
1536 local_irq_restore(flags);
1537 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1538 return 1;
1540 if (!use_master_clock) {
1541 host_tsc = native_read_tsc();
1542 kernel_ns = get_kernel_ns();
1545 tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc);
1548 * We may have to catch up the TSC to match elapsed wall clock
1549 * time for two reasons, even if kvmclock is used.
1550 * 1) CPU could have been running below the maximum TSC rate
1551 * 2) Broken TSC compensation resets the base at each VCPU
1552 * entry to avoid unknown leaps of TSC even when running
1553 * again on the same CPU. This may cause apparent elapsed
1554 * time to disappear, and the guest to stand still or run
1555 * very slowly.
1557 if (vcpu->tsc_catchup) {
1558 u64 tsc = compute_guest_tsc(v, kernel_ns);
1559 if (tsc > tsc_timestamp) {
1560 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
1561 tsc_timestamp = tsc;
1565 local_irq_restore(flags);
1567 if (!vcpu->pv_time_enabled)
1568 return 0;
1571 * Time as measured by the TSC may go backwards when resetting the base
1572 * tsc_timestamp. The reason for this is that the TSC resolution is
1573 * higher than the resolution of the other clock scales. Thus, many
1574 * possible measurments of the TSC correspond to one measurement of any
1575 * other clock, and so a spread of values is possible. This is not a
1576 * problem for the computation of the nanosecond clock; with TSC rates
1577 * around 1GHZ, there can only be a few cycles which correspond to one
1578 * nanosecond value, and any path through this code will inevitably
1579 * take longer than that. However, with the kernel_ns value itself,
1580 * the precision may be much lower, down to HZ granularity. If the
1581 * first sampling of TSC against kernel_ns ends in the low part of the
1582 * range, and the second in the high end of the range, we can get:
1584 * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new
1586 * As the sampling errors potentially range in the thousands of cycles,
1587 * it is possible such a time value has already been observed by the
1588 * guest. To protect against this, we must compute the system time as
1589 * observed by the guest and ensure the new system time is greater.
1591 max_kernel_ns = 0;
1592 if (vcpu->hv_clock.tsc_timestamp) {
1593 max_kernel_ns = vcpu->last_guest_tsc -
1594 vcpu->hv_clock.tsc_timestamp;
1595 max_kernel_ns = pvclock_scale_delta(max_kernel_ns,
1596 vcpu->hv_clock.tsc_to_system_mul,
1597 vcpu->hv_clock.tsc_shift);
1598 max_kernel_ns += vcpu->last_kernel_ns;
1601 if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
1602 kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
1603 &vcpu->hv_clock.tsc_shift,
1604 &vcpu->hv_clock.tsc_to_system_mul);
1605 vcpu->hw_tsc_khz = this_tsc_khz;
1608 /* with a master <monotonic time, tsc value> tuple,
1609 * pvclock clock reads always increase at the (scaled) rate
1610 * of guest TSC - no need to deal with sampling errors.
1612 if (!use_master_clock) {
1613 if (max_kernel_ns > kernel_ns)
1614 kernel_ns = max_kernel_ns;
1616 /* With all the info we got, fill in the values */
1617 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1618 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1619 vcpu->last_kernel_ns = kernel_ns;
1620 vcpu->last_guest_tsc = tsc_timestamp;
1623 * The interface expects us to write an even number signaling that the
1624 * update is finished. Since the guest won't see the intermediate
1625 * state, we just increase by 2 at the end.
1627 vcpu->hv_clock.version += 2;
1629 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
1630 &guest_hv_clock, sizeof(guest_hv_clock))))
1631 return 0;
1633 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
1634 pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
1636 if (vcpu->pvclock_set_guest_stopped_request) {
1637 pvclock_flags |= PVCLOCK_GUEST_STOPPED;
1638 vcpu->pvclock_set_guest_stopped_request = false;
1641 /* If the host uses TSC clocksource, then it is stable */
1642 if (use_master_clock)
1643 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
1645 vcpu->hv_clock.flags = pvclock_flags;
1647 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1648 &vcpu->hv_clock,
1649 sizeof(vcpu->hv_clock));
1650 return 0;
1654 * kvmclock updates which are isolated to a given vcpu, such as
1655 * vcpu->cpu migration, should not allow system_timestamp from
1656 * the rest of the vcpus to remain static. Otherwise ntp frequency
1657 * correction applies to one vcpu's system_timestamp but not
1658 * the others.
1660 * So in those cases, request a kvmclock update for all vcpus.
1661 * The worst case for a remote vcpu to update its kvmclock
1662 * is then bounded by maximum nohz sleep latency.
1665 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
1667 int i;
1668 struct kvm *kvm = v->kvm;
1669 struct kvm_vcpu *vcpu;
1671 kvm_for_each_vcpu(i, vcpu, kvm) {
1672 set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
1673 kvm_vcpu_kick(vcpu);
1677 static bool msr_mtrr_valid(unsigned msr)
1679 switch (msr) {
1680 case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
1681 case MSR_MTRRfix64K_00000:
1682 case MSR_MTRRfix16K_80000:
1683 case MSR_MTRRfix16K_A0000:
1684 case MSR_MTRRfix4K_C0000:
1685 case MSR_MTRRfix4K_C8000:
1686 case MSR_MTRRfix4K_D0000:
1687 case MSR_MTRRfix4K_D8000:
1688 case MSR_MTRRfix4K_E0000:
1689 case MSR_MTRRfix4K_E8000:
1690 case MSR_MTRRfix4K_F0000:
1691 case MSR_MTRRfix4K_F8000:
1692 case MSR_MTRRdefType:
1693 case MSR_IA32_CR_PAT:
1694 return true;
1695 case 0x2f8:
1696 return true;
1698 return false;
1701 static bool valid_pat_type(unsigned t)
1703 return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
1706 static bool valid_mtrr_type(unsigned t)
1708 return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
1711 bool kvm_mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1713 int i;
1715 if (!msr_mtrr_valid(msr))
1716 return false;
1718 if (msr == MSR_IA32_CR_PAT) {
1719 for (i = 0; i < 8; i++)
1720 if (!valid_pat_type((data >> (i * 8)) & 0xff))
1721 return false;
1722 return true;
1723 } else if (msr == MSR_MTRRdefType) {
1724 if (data & ~0xcff)
1725 return false;
1726 return valid_mtrr_type(data & 0xff);
1727 } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
1728 for (i = 0; i < 8 ; i++)
1729 if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
1730 return false;
1731 return true;
1734 /* variable MTRRs */
1735 return valid_mtrr_type(data & 0xff);
1737 EXPORT_SYMBOL_GPL(kvm_mtrr_valid);
1739 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1741 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1743 if (!kvm_mtrr_valid(vcpu, msr, data))
1744 return 1;
1746 if (msr == MSR_MTRRdefType) {
1747 vcpu->arch.mtrr_state.def_type = data;
1748 vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
1749 } else if (msr == MSR_MTRRfix64K_00000)
1750 p[0] = data;
1751 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1752 p[1 + msr - MSR_MTRRfix16K_80000] = data;
1753 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1754 p[3 + msr - MSR_MTRRfix4K_C0000] = data;
1755 else if (msr == MSR_IA32_CR_PAT)
1756 vcpu->arch.pat = data;
1757 else { /* Variable MTRRs */
1758 int idx, is_mtrr_mask;
1759 u64 *pt;
1761 idx = (msr - 0x200) / 2;
1762 is_mtrr_mask = msr - 0x200 - 2 * idx;
1763 if (!is_mtrr_mask)
1764 pt =
1765 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1766 else
1767 pt =
1768 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1769 *pt = data;
1772 kvm_mmu_reset_context(vcpu);
1773 return 0;
1776 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1778 u64 mcg_cap = vcpu->arch.mcg_cap;
1779 unsigned bank_num = mcg_cap & 0xff;
1781 switch (msr) {
1782 case MSR_IA32_MCG_STATUS:
1783 vcpu->arch.mcg_status = data;
1784 break;
1785 case MSR_IA32_MCG_CTL:
1786 if (!(mcg_cap & MCG_CTL_P))
1787 return 1;
1788 if (data != 0 && data != ~(u64)0)
1789 return -1;
1790 vcpu->arch.mcg_ctl = data;
1791 break;
1792 default:
1793 if (msr >= MSR_IA32_MC0_CTL &&
1794 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1795 u32 offset = msr - MSR_IA32_MC0_CTL;
1796 /* only 0 or all 1s can be written to IA32_MCi_CTL
1797 * some Linux kernels though clear bit 10 in bank 4 to
1798 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
1799 * this to avoid an uncatched #GP in the guest
1801 if ((offset & 0x3) == 0 &&
1802 data != 0 && (data | (1 << 10)) != ~(u64)0)
1803 return -1;
1804 vcpu->arch.mce_banks[offset] = data;
1805 break;
1807 return 1;
1809 return 0;
1812 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
1814 struct kvm *kvm = vcpu->kvm;
1815 int lm = is_long_mode(vcpu);
1816 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
1817 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
1818 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
1819 : kvm->arch.xen_hvm_config.blob_size_32;
1820 u32 page_num = data & ~PAGE_MASK;
1821 u64 page_addr = data & PAGE_MASK;
1822 u8 *page;
1823 int r;
1825 r = -E2BIG;
1826 if (page_num >= blob_size)
1827 goto out;
1828 r = -ENOMEM;
1829 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
1830 if (IS_ERR(page)) {
1831 r = PTR_ERR(page);
1832 goto out;
1834 if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
1835 goto out_free;
1836 r = 0;
1837 out_free:
1838 kfree(page);
1839 out:
1840 return r;
1843 static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
1845 return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
1848 static bool kvm_hv_msr_partition_wide(u32 msr)
1850 bool r = false;
1851 switch (msr) {
1852 case HV_X64_MSR_GUEST_OS_ID:
1853 case HV_X64_MSR_HYPERCALL:
1854 r = true;
1855 break;
1858 return r;
1861 static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1863 struct kvm *kvm = vcpu->kvm;
1865 switch (msr) {
1866 case HV_X64_MSR_GUEST_OS_ID:
1867 kvm->arch.hv_guest_os_id = data;
1868 /* setting guest os id to zero disables hypercall page */
1869 if (!kvm->arch.hv_guest_os_id)
1870 kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
1871 break;
1872 case HV_X64_MSR_HYPERCALL: {
1873 u64 gfn;
1874 unsigned long addr;
1875 u8 instructions[4];
1877 /* if guest os id is not set hypercall should remain disabled */
1878 if (!kvm->arch.hv_guest_os_id)
1879 break;
1880 if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
1881 kvm->arch.hv_hypercall = data;
1882 break;
1884 gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
1885 addr = gfn_to_hva(kvm, gfn);
1886 if (kvm_is_error_hva(addr))
1887 return 1;
1888 kvm_x86_ops->patch_hypercall(vcpu, instructions);
1889 ((unsigned char *)instructions)[3] = 0xc3; /* ret */
1890 if (__copy_to_user((void __user *)addr, instructions, 4))
1891 return 1;
1892 kvm->arch.hv_hypercall = data;
1893 break;
1895 default:
1896 vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1897 "data 0x%llx\n", msr, data);
1898 return 1;
1900 return 0;
1903 static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1905 switch (msr) {
1906 case HV_X64_MSR_APIC_ASSIST_PAGE: {
1907 unsigned long addr;
1909 if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
1910 vcpu->arch.hv_vapic = data;
1911 break;
1913 addr = gfn_to_hva(vcpu->kvm, data >>
1914 HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
1915 if (kvm_is_error_hva(addr))
1916 return 1;
1917 if (__clear_user((void __user *)addr, PAGE_SIZE))
1918 return 1;
1919 vcpu->arch.hv_vapic = data;
1920 break;
1922 case HV_X64_MSR_EOI:
1923 return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
1924 case HV_X64_MSR_ICR:
1925 return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
1926 case HV_X64_MSR_TPR:
1927 return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
1928 default:
1929 vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1930 "data 0x%llx\n", msr, data);
1931 return 1;
1934 return 0;
1937 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
1939 gpa_t gpa = data & ~0x3f;
1941 /* Bits 2:5 are reserved, Should be zero */
1942 if (data & 0x3c)
1943 return 1;
1945 vcpu->arch.apf.msr_val = data;
1947 if (!(data & KVM_ASYNC_PF_ENABLED)) {
1948 kvm_clear_async_pf_completion_queue(vcpu);
1949 kvm_async_pf_hash_reset(vcpu);
1950 return 0;
1953 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
1954 sizeof(u32)))
1955 return 1;
1957 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
1958 kvm_async_pf_wakeup_all(vcpu);
1959 return 0;
1962 static void kvmclock_reset(struct kvm_vcpu *vcpu)
1964 vcpu->arch.pv_time_enabled = false;
1967 static void accumulate_steal_time(struct kvm_vcpu *vcpu)
1969 u64 delta;
1971 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1972 return;
1974 delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
1975 vcpu->arch.st.last_steal = current->sched_info.run_delay;
1976 vcpu->arch.st.accum_steal = delta;
1979 static void record_steal_time(struct kvm_vcpu *vcpu)
1981 accumulate_steal_time(vcpu);
1983 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1984 return;
1986 if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1987 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
1988 return;
1990 vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
1991 vcpu->arch.st.steal.version += 2;
1992 vcpu->arch.st.accum_steal = 0;
1994 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1995 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
1998 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2000 bool pr = false;
2001 u32 msr = msr_info->index;
2002 u64 data = msr_info->data;
2004 switch (msr) {
2005 case MSR_AMD64_NB_CFG:
2006 case MSR_IA32_UCODE_REV:
2007 case MSR_IA32_UCODE_WRITE:
2008 case MSR_VM_HSAVE_PA:
2009 case MSR_AMD64_PATCH_LOADER:
2010 case MSR_AMD64_BU_CFG2:
2011 break;
2013 case MSR_EFER:
2014 return set_efer(vcpu, data);
2015 case MSR_K7_HWCR:
2016 data &= ~(u64)0x40; /* ignore flush filter disable */
2017 data &= ~(u64)0x100; /* ignore ignne emulation enable */
2018 data &= ~(u64)0x8; /* ignore TLB cache disable */
2019 if (data != 0) {
2020 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2021 data);
2022 return 1;
2024 break;
2025 case MSR_FAM10H_MMIO_CONF_BASE:
2026 if (data != 0) {
2027 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2028 "0x%llx\n", data);
2029 return 1;
2031 break;
2032 case MSR_IA32_DEBUGCTLMSR:
2033 if (!data) {
2034 /* We support the non-activated case already */
2035 break;
2036 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2037 /* Values other than LBR and BTF are vendor-specific,
2038 thus reserved and should throw a #GP */
2039 return 1;
2041 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2042 __func__, data);
2043 break;
2044 case 0x200 ... 0x2ff:
2045 return set_msr_mtrr(vcpu, msr, data);
2046 case MSR_IA32_APICBASE:
2047 kvm_set_apic_base(vcpu, data);
2048 break;
2049 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2050 return kvm_x2apic_msr_write(vcpu, msr, data);
2051 case MSR_IA32_TSCDEADLINE:
2052 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2053 break;
2054 case MSR_IA32_TSC_ADJUST:
2055 if (guest_cpuid_has_tsc_adjust(vcpu)) {
2056 if (!msr_info->host_initiated) {
2057 u64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2058 kvm_x86_ops->adjust_tsc_offset(vcpu, adj, true);
2060 vcpu->arch.ia32_tsc_adjust_msr = data;
2062 break;
2063 case MSR_IA32_MISC_ENABLE:
2064 vcpu->arch.ia32_misc_enable_msr = data;
2065 break;
2066 case MSR_KVM_WALL_CLOCK_NEW:
2067 case MSR_KVM_WALL_CLOCK:
2068 vcpu->kvm->arch.wall_clock = data;
2069 kvm_write_wall_clock(vcpu->kvm, data);
2070 break;
2071 case MSR_KVM_SYSTEM_TIME_NEW:
2072 case MSR_KVM_SYSTEM_TIME: {
2073 u64 gpa_offset;
2074 kvmclock_reset(vcpu);
2076 vcpu->arch.time = data;
2077 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2079 /* we verify if the enable bit is set... */
2080 if (!(data & 1))
2081 break;
2083 gpa_offset = data & ~(PAGE_MASK | 1);
2085 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2086 &vcpu->arch.pv_time, data & ~1ULL,
2087 sizeof(struct pvclock_vcpu_time_info)))
2088 vcpu->arch.pv_time_enabled = false;
2089 else
2090 vcpu->arch.pv_time_enabled = true;
2092 break;
2094 case MSR_KVM_ASYNC_PF_EN:
2095 if (kvm_pv_enable_async_pf(vcpu, data))
2096 return 1;
2097 break;
2098 case MSR_KVM_STEAL_TIME:
2100 if (unlikely(!sched_info_on()))
2101 return 1;
2103 if (data & KVM_STEAL_RESERVED_MASK)
2104 return 1;
2106 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2107 data & KVM_STEAL_VALID_BITS,
2108 sizeof(struct kvm_steal_time)))
2109 return 1;
2111 vcpu->arch.st.msr_val = data;
2113 if (!(data & KVM_MSR_ENABLED))
2114 break;
2116 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2118 break;
2119 case MSR_KVM_PV_EOI_EN:
2120 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2121 return 1;
2122 break;
2124 case MSR_IA32_MCG_CTL:
2125 case MSR_IA32_MCG_STATUS:
2126 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
2127 return set_msr_mce(vcpu, msr, data);
2129 /* Performance counters are not protected by a CPUID bit,
2130 * so we should check all of them in the generic path for the sake of
2131 * cross vendor migration.
2132 * Writing a zero into the event select MSRs disables them,
2133 * which we perfectly emulate ;-). Any other value should be at least
2134 * reported, some guests depend on them.
2136 case MSR_K7_EVNTSEL0:
2137 case MSR_K7_EVNTSEL1:
2138 case MSR_K7_EVNTSEL2:
2139 case MSR_K7_EVNTSEL3:
2140 if (data != 0)
2141 vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
2142 "0x%x data 0x%llx\n", msr, data);
2143 break;
2144 /* at least RHEL 4 unconditionally writes to the perfctr registers,
2145 * so we ignore writes to make it happy.
2147 case MSR_K7_PERFCTR0:
2148 case MSR_K7_PERFCTR1:
2149 case MSR_K7_PERFCTR2:
2150 case MSR_K7_PERFCTR3:
2151 vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
2152 "0x%x data 0x%llx\n", msr, data);
2153 break;
2154 case MSR_P6_PERFCTR0:
2155 case MSR_P6_PERFCTR1:
2156 pr = true;
2157 case MSR_P6_EVNTSEL0:
2158 case MSR_P6_EVNTSEL1:
2159 if (kvm_pmu_msr(vcpu, msr))
2160 return kvm_pmu_set_msr(vcpu, msr_info);
2162 if (pr || data != 0)
2163 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2164 "0x%x data 0x%llx\n", msr, data);
2165 break;
2166 case MSR_K7_CLK_CTL:
2168 * Ignore all writes to this no longer documented MSR.
2169 * Writes are only relevant for old K7 processors,
2170 * all pre-dating SVM, but a recommended workaround from
2171 * AMD for these chips. It is possible to specify the
2172 * affected processor models on the command line, hence
2173 * the need to ignore the workaround.
2175 break;
2176 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2177 if (kvm_hv_msr_partition_wide(msr)) {
2178 int r;
2179 mutex_lock(&vcpu->kvm->lock);
2180 r = set_msr_hyperv_pw(vcpu, msr, data);
2181 mutex_unlock(&vcpu->kvm->lock);
2182 return r;
2183 } else
2184 return set_msr_hyperv(vcpu, msr, data);
2185 break;
2186 case MSR_IA32_BBL_CR_CTL3:
2187 /* Drop writes to this legacy MSR -- see rdmsr
2188 * counterpart for further detail.
2190 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
2191 break;
2192 case MSR_AMD64_OSVW_ID_LENGTH:
2193 if (!guest_cpuid_has_osvw(vcpu))
2194 return 1;
2195 vcpu->arch.osvw.length = data;
2196 break;
2197 case MSR_AMD64_OSVW_STATUS:
2198 if (!guest_cpuid_has_osvw(vcpu))
2199 return 1;
2200 vcpu->arch.osvw.status = data;
2201 break;
2202 default:
2203 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2204 return xen_hvm_config(vcpu, data);
2205 if (kvm_pmu_msr(vcpu, msr))
2206 return kvm_pmu_set_msr(vcpu, msr_info);
2207 if (!ignore_msrs) {
2208 vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
2209 msr, data);
2210 return 1;
2211 } else {
2212 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
2213 msr, data);
2214 break;
2217 return 0;
2219 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2223 * Reads an msr value (of 'msr_index') into 'pdata'.
2224 * Returns 0 on success, non-0 otherwise.
2225 * Assumes vcpu_load() was already called.
2227 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2229 return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
2232 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2234 u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
2236 if (!msr_mtrr_valid(msr))
2237 return 1;
2239 if (msr == MSR_MTRRdefType)
2240 *pdata = vcpu->arch.mtrr_state.def_type +
2241 (vcpu->arch.mtrr_state.enabled << 10);
2242 else if (msr == MSR_MTRRfix64K_00000)
2243 *pdata = p[0];
2244 else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
2245 *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
2246 else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
2247 *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
2248 else if (msr == MSR_IA32_CR_PAT)
2249 *pdata = vcpu->arch.pat;
2250 else { /* Variable MTRRs */
2251 int idx, is_mtrr_mask;
2252 u64 *pt;
2254 idx = (msr - 0x200) / 2;
2255 is_mtrr_mask = msr - 0x200 - 2 * idx;
2256 if (!is_mtrr_mask)
2257 pt =
2258 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
2259 else
2260 pt =
2261 (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
2262 *pdata = *pt;
2265 return 0;
2268 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2270 u64 data;
2271 u64 mcg_cap = vcpu->arch.mcg_cap;
2272 unsigned bank_num = mcg_cap & 0xff;
2274 switch (msr) {
2275 case MSR_IA32_P5_MC_ADDR:
2276 case MSR_IA32_P5_MC_TYPE:
2277 data = 0;
2278 break;
2279 case MSR_IA32_MCG_CAP:
2280 data = vcpu->arch.mcg_cap;
2281 break;
2282 case MSR_IA32_MCG_CTL:
2283 if (!(mcg_cap & MCG_CTL_P))
2284 return 1;
2285 data = vcpu->arch.mcg_ctl;
2286 break;
2287 case MSR_IA32_MCG_STATUS:
2288 data = vcpu->arch.mcg_status;
2289 break;
2290 default:
2291 if (msr >= MSR_IA32_MC0_CTL &&
2292 msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
2293 u32 offset = msr - MSR_IA32_MC0_CTL;
2294 data = vcpu->arch.mce_banks[offset];
2295 break;
2297 return 1;
2299 *pdata = data;
2300 return 0;
2303 static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2305 u64 data = 0;
2306 struct kvm *kvm = vcpu->kvm;
2308 switch (msr) {
2309 case HV_X64_MSR_GUEST_OS_ID:
2310 data = kvm->arch.hv_guest_os_id;
2311 break;
2312 case HV_X64_MSR_HYPERCALL:
2313 data = kvm->arch.hv_hypercall;
2314 break;
2315 default:
2316 vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
2317 return 1;
2320 *pdata = data;
2321 return 0;
2324 static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2326 u64 data = 0;
2328 switch (msr) {
2329 case HV_X64_MSR_VP_INDEX: {
2330 int r;
2331 struct kvm_vcpu *v;
2332 kvm_for_each_vcpu(r, v, vcpu->kvm)
2333 if (v == vcpu)
2334 data = r;
2335 break;
2337 case HV_X64_MSR_EOI:
2338 return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
2339 case HV_X64_MSR_ICR:
2340 return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
2341 case HV_X64_MSR_TPR:
2342 return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
2343 case HV_X64_MSR_APIC_ASSIST_PAGE:
2344 data = vcpu->arch.hv_vapic;
2345 break;
2346 default:
2347 vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
2348 return 1;
2350 *pdata = data;
2351 return 0;
2354 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2356 u64 data;
2358 switch (msr) {
2359 case MSR_IA32_PLATFORM_ID:
2360 case MSR_IA32_EBL_CR_POWERON:
2361 case MSR_IA32_DEBUGCTLMSR:
2362 case MSR_IA32_LASTBRANCHFROMIP:
2363 case MSR_IA32_LASTBRANCHTOIP:
2364 case MSR_IA32_LASTINTFROMIP:
2365 case MSR_IA32_LASTINTTOIP:
2366 case MSR_K8_SYSCFG:
2367 case MSR_K7_HWCR:
2368 case MSR_VM_HSAVE_PA:
2369 case MSR_K7_EVNTSEL0:
2370 case MSR_K7_EVNTSEL1:
2371 case MSR_K7_EVNTSEL2:
2372 case MSR_K7_EVNTSEL3:
2373 case MSR_K7_PERFCTR0:
2374 case MSR_K7_PERFCTR1:
2375 case MSR_K7_PERFCTR2:
2376 case MSR_K7_PERFCTR3:
2377 case MSR_K8_INT_PENDING_MSG:
2378 case MSR_AMD64_NB_CFG:
2379 case MSR_FAM10H_MMIO_CONF_BASE:
2380 case MSR_AMD64_BU_CFG2:
2381 data = 0;
2382 break;
2383 case MSR_P6_PERFCTR0:
2384 case MSR_P6_PERFCTR1:
2385 case MSR_P6_EVNTSEL0:
2386 case MSR_P6_EVNTSEL1:
2387 if (kvm_pmu_msr(vcpu, msr))
2388 return kvm_pmu_get_msr(vcpu, msr, pdata);
2389 data = 0;
2390 break;
2391 case MSR_IA32_UCODE_REV:
2392 data = 0x100000000ULL;
2393 break;
2394 case MSR_MTRRcap:
2395 data = 0x500 | KVM_NR_VAR_MTRR;
2396 break;
2397 case 0x200 ... 0x2ff:
2398 return get_msr_mtrr(vcpu, msr, pdata);
2399 case 0xcd: /* fsb frequency */
2400 data = 3;
2401 break;
2403 * MSR_EBC_FREQUENCY_ID
2404 * Conservative value valid for even the basic CPU models.
2405 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2406 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2407 * and 266MHz for model 3, or 4. Set Core Clock
2408 * Frequency to System Bus Frequency Ratio to 1 (bits
2409 * 31:24) even though these are only valid for CPU
2410 * models > 2, however guests may end up dividing or
2411 * multiplying by zero otherwise.
2413 case MSR_EBC_FREQUENCY_ID:
2414 data = 1 << 24;
2415 break;
2416 case MSR_IA32_APICBASE:
2417 data = kvm_get_apic_base(vcpu);
2418 break;
2419 case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2420 return kvm_x2apic_msr_read(vcpu, msr, pdata);
2421 break;
2422 case MSR_IA32_TSCDEADLINE:
2423 data = kvm_get_lapic_tscdeadline_msr(vcpu);
2424 break;
2425 case MSR_IA32_TSC_ADJUST:
2426 data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2427 break;
2428 case MSR_IA32_MISC_ENABLE:
2429 data = vcpu->arch.ia32_misc_enable_msr;
2430 break;
2431 case MSR_IA32_PERF_STATUS:
2432 /* TSC increment by tick */
2433 data = 1000ULL;
2434 /* CPU multiplier */
2435 data |= (((uint64_t)4ULL) << 40);
2436 break;
2437 case MSR_EFER:
2438 data = vcpu->arch.efer;
2439 break;
2440 case MSR_KVM_WALL_CLOCK:
2441 case MSR_KVM_WALL_CLOCK_NEW:
2442 data = vcpu->kvm->arch.wall_clock;
2443 break;
2444 case MSR_KVM_SYSTEM_TIME:
2445 case MSR_KVM_SYSTEM_TIME_NEW:
2446 data = vcpu->arch.time;
2447 break;
2448 case MSR_KVM_ASYNC_PF_EN:
2449 data = vcpu->arch.apf.msr_val;
2450 break;
2451 case MSR_KVM_STEAL_TIME:
2452 data = vcpu->arch.st.msr_val;
2453 break;
2454 case MSR_KVM_PV_EOI_EN:
2455 data = vcpu->arch.pv_eoi.msr_val;
2456 break;
2457 case MSR_IA32_P5_MC_ADDR:
2458 case MSR_IA32_P5_MC_TYPE:
2459 case MSR_IA32_MCG_CAP:
2460 case MSR_IA32_MCG_CTL:
2461 case MSR_IA32_MCG_STATUS:
2462 case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
2463 return get_msr_mce(vcpu, msr, pdata);
2464 case MSR_K7_CLK_CTL:
2466 * Provide expected ramp-up count for K7. All other
2467 * are set to zero, indicating minimum divisors for
2468 * every field.
2470 * This prevents guest kernels on AMD host with CPU
2471 * type 6, model 8 and higher from exploding due to
2472 * the rdmsr failing.
2474 data = 0x20000000;
2475 break;
2476 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2477 if (kvm_hv_msr_partition_wide(msr)) {
2478 int r;
2479 mutex_lock(&vcpu->kvm->lock);
2480 r = get_msr_hyperv_pw(vcpu, msr, pdata);
2481 mutex_unlock(&vcpu->kvm->lock);
2482 return r;
2483 } else
2484 return get_msr_hyperv(vcpu, msr, pdata);
2485 break;
2486 case MSR_IA32_BBL_CR_CTL3:
2487 /* This legacy MSR exists but isn't fully documented in current
2488 * silicon. It is however accessed by winxp in very narrow
2489 * scenarios where it sets bit #19, itself documented as
2490 * a "reserved" bit. Best effort attempt to source coherent
2491 * read data here should the balance of the register be
2492 * interpreted by the guest:
2494 * L2 cache control register 3: 64GB range, 256KB size,
2495 * enabled, latency 0x1, configured
2497 data = 0xbe702111;
2498 break;
2499 case MSR_AMD64_OSVW_ID_LENGTH:
2500 if (!guest_cpuid_has_osvw(vcpu))
2501 return 1;
2502 data = vcpu->arch.osvw.length;
2503 break;
2504 case MSR_AMD64_OSVW_STATUS:
2505 if (!guest_cpuid_has_osvw(vcpu))
2506 return 1;
2507 data = vcpu->arch.osvw.status;
2508 break;
2509 default:
2510 if (kvm_pmu_msr(vcpu, msr))
2511 return kvm_pmu_get_msr(vcpu, msr, pdata);
2512 if (!ignore_msrs) {
2513 vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
2514 return 1;
2515 } else {
2516 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
2517 data = 0;
2519 break;
2521 *pdata = data;
2522 return 0;
2524 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2527 * Read or write a bunch of msrs. All parameters are kernel addresses.
2529 * @return number of msrs set successfully.
2531 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2532 struct kvm_msr_entry *entries,
2533 int (*do_msr)(struct kvm_vcpu *vcpu,
2534 unsigned index, u64 *data))
2536 int i, idx;
2538 idx = srcu_read_lock(&vcpu->kvm->srcu);
2539 for (i = 0; i < msrs->nmsrs; ++i)
2540 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2541 break;
2542 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2544 return i;
2548 * Read or write a bunch of msrs. Parameters are user addresses.
2550 * @return number of msrs set successfully.
2552 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2553 int (*do_msr)(struct kvm_vcpu *vcpu,
2554 unsigned index, u64 *data),
2555 int writeback)
2557 struct kvm_msrs msrs;
2558 struct kvm_msr_entry *entries;
2559 int r, n;
2560 unsigned size;
2562 r = -EFAULT;
2563 if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2564 goto out;
2566 r = -E2BIG;
2567 if (msrs.nmsrs >= MAX_IO_MSRS)
2568 goto out;
2570 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2571 entries = memdup_user(user_msrs->entries, size);
2572 if (IS_ERR(entries)) {
2573 r = PTR_ERR(entries);
2574 goto out;
2577 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2578 if (r < 0)
2579 goto out_free;
2581 r = -EFAULT;
2582 if (writeback && copy_to_user(user_msrs->entries, entries, size))
2583 goto out_free;
2585 r = n;
2587 out_free:
2588 kfree(entries);
2589 out:
2590 return r;
2593 int kvm_dev_ioctl_check_extension(long ext)
2595 int r;
2597 switch (ext) {
2598 case KVM_CAP_IRQCHIP:
2599 case KVM_CAP_HLT:
2600 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2601 case KVM_CAP_SET_TSS_ADDR:
2602 case KVM_CAP_EXT_CPUID:
2603 case KVM_CAP_CLOCKSOURCE:
2604 case KVM_CAP_PIT:
2605 case KVM_CAP_NOP_IO_DELAY:
2606 case KVM_CAP_MP_STATE:
2607 case KVM_CAP_SYNC_MMU:
2608 case KVM_CAP_USER_NMI:
2609 case KVM_CAP_REINJECT_CONTROL:
2610 case KVM_CAP_IRQ_INJECT_STATUS:
2611 case KVM_CAP_IRQFD:
2612 case KVM_CAP_IOEVENTFD:
2613 case KVM_CAP_PIT2:
2614 case KVM_CAP_PIT_STATE2:
2615 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2616 case KVM_CAP_XEN_HVM:
2617 case KVM_CAP_ADJUST_CLOCK:
2618 case KVM_CAP_VCPU_EVENTS:
2619 case KVM_CAP_HYPERV:
2620 case KVM_CAP_HYPERV_VAPIC:
2621 case KVM_CAP_HYPERV_SPIN:
2622 case KVM_CAP_PCI_SEGMENT:
2623 case KVM_CAP_DEBUGREGS:
2624 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2625 case KVM_CAP_XSAVE:
2626 case KVM_CAP_ASYNC_PF:
2627 case KVM_CAP_GET_TSC_KHZ:
2628 case KVM_CAP_KVMCLOCK_CTRL:
2629 case KVM_CAP_READONLY_MEM:
2630 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2631 case KVM_CAP_ASSIGN_DEV_IRQ:
2632 case KVM_CAP_PCI_2_3:
2633 #endif
2634 r = 1;
2635 break;
2636 case KVM_CAP_COALESCED_MMIO:
2637 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2638 break;
2639 case KVM_CAP_VAPIC:
2640 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2641 break;
2642 case KVM_CAP_NR_VCPUS:
2643 r = KVM_SOFT_MAX_VCPUS;
2644 break;
2645 case KVM_CAP_MAX_VCPUS:
2646 r = KVM_MAX_VCPUS;
2647 break;
2648 case KVM_CAP_NR_MEMSLOTS:
2649 r = KVM_USER_MEM_SLOTS;
2650 break;
2651 case KVM_CAP_PV_MMU: /* obsolete */
2652 r = 0;
2653 break;
2654 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2655 case KVM_CAP_IOMMU:
2656 r = iommu_present(&pci_bus_type);
2657 break;
2658 #endif
2659 case KVM_CAP_MCE:
2660 r = KVM_MAX_MCE_BANKS;
2661 break;
2662 case KVM_CAP_XCRS:
2663 r = cpu_has_xsave;
2664 break;
2665 case KVM_CAP_TSC_CONTROL:
2666 r = kvm_has_tsc_control;
2667 break;
2668 case KVM_CAP_TSC_DEADLINE_TIMER:
2669 r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
2670 break;
2671 default:
2672 r = 0;
2673 break;
2675 return r;
2679 long kvm_arch_dev_ioctl(struct file *filp,
2680 unsigned int ioctl, unsigned long arg)
2682 void __user *argp = (void __user *)arg;
2683 long r;
2685 switch (ioctl) {
2686 case KVM_GET_MSR_INDEX_LIST: {
2687 struct kvm_msr_list __user *user_msr_list = argp;
2688 struct kvm_msr_list msr_list;
2689 unsigned n;
2691 r = -EFAULT;
2692 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2693 goto out;
2694 n = msr_list.nmsrs;
2695 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
2696 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2697 goto out;
2698 r = -E2BIG;
2699 if (n < msr_list.nmsrs)
2700 goto out;
2701 r = -EFAULT;
2702 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2703 num_msrs_to_save * sizeof(u32)))
2704 goto out;
2705 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2706 &emulated_msrs,
2707 ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
2708 goto out;
2709 r = 0;
2710 break;
2712 case KVM_GET_SUPPORTED_CPUID: {
2713 struct kvm_cpuid2 __user *cpuid_arg = argp;
2714 struct kvm_cpuid2 cpuid;
2716 r = -EFAULT;
2717 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2718 goto out;
2719 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
2720 cpuid_arg->entries);
2721 if (r)
2722 goto out;
2724 r = -EFAULT;
2725 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2726 goto out;
2727 r = 0;
2728 break;
2730 case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2731 u64 mce_cap;
2733 mce_cap = KVM_MCE_CAP_SUPPORTED;
2734 r = -EFAULT;
2735 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2736 goto out;
2737 r = 0;
2738 break;
2740 default:
2741 r = -EINVAL;
2743 out:
2744 return r;
2747 static void wbinvd_ipi(void *garbage)
2749 wbinvd();
2752 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2754 return vcpu->kvm->arch.iommu_domain &&
2755 !(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY);
2758 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2760 /* Address WBINVD may be executed by guest */
2761 if (need_emulate_wbinvd(vcpu)) {
2762 if (kvm_x86_ops->has_wbinvd_exit())
2763 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2764 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2765 smp_call_function_single(vcpu->cpu,
2766 wbinvd_ipi, NULL, 1);
2769 kvm_x86_ops->vcpu_load(vcpu, cpu);
2771 /* Apply any externally detected TSC adjustments (due to suspend) */
2772 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2773 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2774 vcpu->arch.tsc_offset_adjustment = 0;
2775 set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
2778 if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2779 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2780 native_read_tsc() - vcpu->arch.last_host_tsc;
2781 if (tsc_delta < 0)
2782 mark_tsc_unstable("KVM discovered backwards TSC");
2783 if (check_tsc_unstable()) {
2784 u64 offset = kvm_x86_ops->compute_tsc_offset(vcpu,
2785 vcpu->arch.last_guest_tsc);
2786 kvm_x86_ops->write_tsc_offset(vcpu, offset);
2787 vcpu->arch.tsc_catchup = 1;
2790 * On a host with synchronized TSC, there is no need to update
2791 * kvmclock on vcpu->cpu migration
2793 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
2794 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2795 if (vcpu->cpu != cpu)
2796 kvm_migrate_timers(vcpu);
2797 vcpu->cpu = cpu;
2800 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2803 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2805 kvm_x86_ops->vcpu_put(vcpu);
2806 kvm_put_guest_fpu(vcpu);
2807 vcpu->arch.last_host_tsc = native_read_tsc();
2810 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2811 struct kvm_lapic_state *s)
2813 kvm_x86_ops->sync_pir_to_irr(vcpu);
2814 memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2816 return 0;
2819 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2820 struct kvm_lapic_state *s)
2822 kvm_apic_post_state_restore(vcpu, s);
2823 update_cr8_intercept(vcpu);
2825 return 0;
2828 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2829 struct kvm_interrupt *irq)
2831 if (irq->irq >= KVM_NR_INTERRUPTS)
2832 return -EINVAL;
2833 if (irqchip_in_kernel(vcpu->kvm))
2834 return -ENXIO;
2836 kvm_queue_interrupt(vcpu, irq->irq, false);
2837 kvm_make_request(KVM_REQ_EVENT, vcpu);
2839 return 0;
2842 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2844 kvm_inject_nmi(vcpu);
2846 return 0;
2849 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2850 struct kvm_tpr_access_ctl *tac)
2852 if (tac->flags)
2853 return -EINVAL;
2854 vcpu->arch.tpr_access_reporting = !!tac->enabled;
2855 return 0;
2858 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2859 u64 mcg_cap)
2861 int r;
2862 unsigned bank_num = mcg_cap & 0xff, bank;
2864 r = -EINVAL;
2865 if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2866 goto out;
2867 if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2868 goto out;
2869 r = 0;
2870 vcpu->arch.mcg_cap = mcg_cap;
2871 /* Init IA32_MCG_CTL to all 1s */
2872 if (mcg_cap & MCG_CTL_P)
2873 vcpu->arch.mcg_ctl = ~(u64)0;
2874 /* Init IA32_MCi_CTL to all 1s */
2875 for (bank = 0; bank < bank_num; bank++)
2876 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2877 out:
2878 return r;
2881 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2882 struct kvm_x86_mce *mce)
2884 u64 mcg_cap = vcpu->arch.mcg_cap;
2885 unsigned bank_num = mcg_cap & 0xff;
2886 u64 *banks = vcpu->arch.mce_banks;
2888 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2889 return -EINVAL;
2891 * if IA32_MCG_CTL is not all 1s, the uncorrected error
2892 * reporting is disabled
2894 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2895 vcpu->arch.mcg_ctl != ~(u64)0)
2896 return 0;
2897 banks += 4 * mce->bank;
2899 * if IA32_MCi_CTL is not all 1s, the uncorrected error
2900 * reporting is disabled for the bank
2902 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2903 return 0;
2904 if (mce->status & MCI_STATUS_UC) {
2905 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2906 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2907 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2908 return 0;
2910 if (banks[1] & MCI_STATUS_VAL)
2911 mce->status |= MCI_STATUS_OVER;
2912 banks[2] = mce->addr;
2913 banks[3] = mce->misc;
2914 vcpu->arch.mcg_status = mce->mcg_status;
2915 banks[1] = mce->status;
2916 kvm_queue_exception(vcpu, MC_VECTOR);
2917 } else if (!(banks[1] & MCI_STATUS_VAL)
2918 || !(banks[1] & MCI_STATUS_UC)) {
2919 if (banks[1] & MCI_STATUS_VAL)
2920 mce->status |= MCI_STATUS_OVER;
2921 banks[2] = mce->addr;
2922 banks[3] = mce->misc;
2923 banks[1] = mce->status;
2924 } else
2925 banks[1] |= MCI_STATUS_OVER;
2926 return 0;
2929 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2930 struct kvm_vcpu_events *events)
2932 process_nmi(vcpu);
2933 events->exception.injected =
2934 vcpu->arch.exception.pending &&
2935 !kvm_exception_is_soft(vcpu->arch.exception.nr);
2936 events->exception.nr = vcpu->arch.exception.nr;
2937 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2938 events->exception.pad = 0;
2939 events->exception.error_code = vcpu->arch.exception.error_code;
2941 events->interrupt.injected =
2942 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
2943 events->interrupt.nr = vcpu->arch.interrupt.nr;
2944 events->interrupt.soft = 0;
2945 events->interrupt.shadow =
2946 kvm_x86_ops->get_interrupt_shadow(vcpu,
2947 KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
2949 events->nmi.injected = vcpu->arch.nmi_injected;
2950 events->nmi.pending = vcpu->arch.nmi_pending != 0;
2951 events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
2952 events->nmi.pad = 0;
2954 events->sipi_vector = 0; /* never valid when reporting to user space */
2956 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
2957 | KVM_VCPUEVENT_VALID_SHADOW);
2958 memset(&events->reserved, 0, sizeof(events->reserved));
2961 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
2962 struct kvm_vcpu_events *events)
2964 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
2965 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2966 | KVM_VCPUEVENT_VALID_SHADOW))
2967 return -EINVAL;
2969 process_nmi(vcpu);
2970 vcpu->arch.exception.pending = events->exception.injected;
2971 vcpu->arch.exception.nr = events->exception.nr;
2972 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
2973 vcpu->arch.exception.error_code = events->exception.error_code;
2975 vcpu->arch.interrupt.pending = events->interrupt.injected;
2976 vcpu->arch.interrupt.nr = events->interrupt.nr;
2977 vcpu->arch.interrupt.soft = events->interrupt.soft;
2978 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
2979 kvm_x86_ops->set_interrupt_shadow(vcpu,
2980 events->interrupt.shadow);
2982 vcpu->arch.nmi_injected = events->nmi.injected;
2983 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
2984 vcpu->arch.nmi_pending = events->nmi.pending;
2985 kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
2987 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
2988 kvm_vcpu_has_lapic(vcpu))
2989 vcpu->arch.apic->sipi_vector = events->sipi_vector;
2991 kvm_make_request(KVM_REQ_EVENT, vcpu);
2993 return 0;
2996 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
2997 struct kvm_debugregs *dbgregs)
2999 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3000 dbgregs->dr6 = vcpu->arch.dr6;
3001 dbgregs->dr7 = vcpu->arch.dr7;
3002 dbgregs->flags = 0;
3003 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3006 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3007 struct kvm_debugregs *dbgregs)
3009 if (dbgregs->flags)
3010 return -EINVAL;
3012 if (dbgregs->dr6 & ~0xffffffffull)
3013 return -EINVAL;
3014 if (dbgregs->dr7 & ~0xffffffffull)
3015 return -EINVAL;
3017 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3018 vcpu->arch.dr6 = dbgregs->dr6;
3019 vcpu->arch.dr7 = dbgregs->dr7;
3021 return 0;
3024 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3025 struct kvm_xsave *guest_xsave)
3027 if (cpu_has_xsave)
3028 memcpy(guest_xsave->region,
3029 &vcpu->arch.guest_fpu.state->xsave,
3030 xstate_size);
3031 else {
3032 memcpy(guest_xsave->region,
3033 &vcpu->arch.guest_fpu.state->fxsave,
3034 sizeof(struct i387_fxsave_struct));
3035 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3036 XSTATE_FPSSE;
3040 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3041 struct kvm_xsave *guest_xsave)
3043 u64 xstate_bv =
3044 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3046 if (cpu_has_xsave)
3047 memcpy(&vcpu->arch.guest_fpu.state->xsave,
3048 guest_xsave->region, xstate_size);
3049 else {
3050 if (xstate_bv & ~XSTATE_FPSSE)
3051 return -EINVAL;
3052 memcpy(&vcpu->arch.guest_fpu.state->fxsave,
3053 guest_xsave->region, sizeof(struct i387_fxsave_struct));
3055 return 0;
3058 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3059 struct kvm_xcrs *guest_xcrs)
3061 if (!cpu_has_xsave) {
3062 guest_xcrs->nr_xcrs = 0;
3063 return;
3066 guest_xcrs->nr_xcrs = 1;
3067 guest_xcrs->flags = 0;
3068 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3069 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3072 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3073 struct kvm_xcrs *guest_xcrs)
3075 int i, r = 0;
3077 if (!cpu_has_xsave)
3078 return -EINVAL;
3080 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3081 return -EINVAL;
3083 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3084 /* Only support XCR0 currently */
3085 if (guest_xcrs->xcrs[0].xcr == XCR_XFEATURE_ENABLED_MASK) {
3086 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3087 guest_xcrs->xcrs[0].value);
3088 break;
3090 if (r)
3091 r = -EINVAL;
3092 return r;
3096 * kvm_set_guest_paused() indicates to the guest kernel that it has been
3097 * stopped by the hypervisor. This function will be called from the host only.
3098 * EINVAL is returned when the host attempts to set the flag for a guest that
3099 * does not support pv clocks.
3101 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3103 if (!vcpu->arch.pv_time_enabled)
3104 return -EINVAL;
3105 vcpu->arch.pvclock_set_guest_stopped_request = true;
3106 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3107 return 0;
3110 long kvm_arch_vcpu_ioctl(struct file *filp,
3111 unsigned int ioctl, unsigned long arg)
3113 struct kvm_vcpu *vcpu = filp->private_data;
3114 void __user *argp = (void __user *)arg;
3115 int r;
3116 union {
3117 struct kvm_lapic_state *lapic;
3118 struct kvm_xsave *xsave;
3119 struct kvm_xcrs *xcrs;
3120 void *buffer;
3121 } u;
3123 u.buffer = NULL;
3124 switch (ioctl) {
3125 case KVM_GET_LAPIC: {
3126 r = -EINVAL;
3127 if (!vcpu->arch.apic)
3128 goto out;
3129 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3131 r = -ENOMEM;
3132 if (!u.lapic)
3133 goto out;
3134 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3135 if (r)
3136 goto out;
3137 r = -EFAULT;
3138 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3139 goto out;
3140 r = 0;
3141 break;
3143 case KVM_SET_LAPIC: {
3144 r = -EINVAL;
3145 if (!vcpu->arch.apic)
3146 goto out;
3147 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3148 if (IS_ERR(u.lapic))
3149 return PTR_ERR(u.lapic);
3151 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3152 break;
3154 case KVM_INTERRUPT: {
3155 struct kvm_interrupt irq;
3157 r = -EFAULT;
3158 if (copy_from_user(&irq, argp, sizeof irq))
3159 goto out;
3160 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3161 break;
3163 case KVM_NMI: {
3164 r = kvm_vcpu_ioctl_nmi(vcpu);
3165 break;
3167 case KVM_SET_CPUID: {
3168 struct kvm_cpuid __user *cpuid_arg = argp;
3169 struct kvm_cpuid cpuid;
3171 r = -EFAULT;
3172 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3173 goto out;
3174 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3175 break;
3177 case KVM_SET_CPUID2: {
3178 struct kvm_cpuid2 __user *cpuid_arg = argp;
3179 struct kvm_cpuid2 cpuid;
3181 r = -EFAULT;
3182 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3183 goto out;
3184 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3185 cpuid_arg->entries);
3186 break;
3188 case KVM_GET_CPUID2: {
3189 struct kvm_cpuid2 __user *cpuid_arg = argp;
3190 struct kvm_cpuid2 cpuid;
3192 r = -EFAULT;
3193 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3194 goto out;
3195 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3196 cpuid_arg->entries);
3197 if (r)
3198 goto out;
3199 r = -EFAULT;
3200 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3201 goto out;
3202 r = 0;
3203 break;
3205 case KVM_GET_MSRS:
3206 r = msr_io(vcpu, argp, kvm_get_msr, 1);
3207 break;
3208 case KVM_SET_MSRS:
3209 r = msr_io(vcpu, argp, do_set_msr, 0);
3210 break;
3211 case KVM_TPR_ACCESS_REPORTING: {
3212 struct kvm_tpr_access_ctl tac;
3214 r = -EFAULT;
3215 if (copy_from_user(&tac, argp, sizeof tac))
3216 goto out;
3217 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3218 if (r)
3219 goto out;
3220 r = -EFAULT;
3221 if (copy_to_user(argp, &tac, sizeof tac))
3222 goto out;
3223 r = 0;
3224 break;
3226 case KVM_SET_VAPIC_ADDR: {
3227 struct kvm_vapic_addr va;
3229 r = -EINVAL;
3230 if (!irqchip_in_kernel(vcpu->kvm))
3231 goto out;
3232 r = -EFAULT;
3233 if (copy_from_user(&va, argp, sizeof va))
3234 goto out;
3235 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3236 break;
3238 case KVM_X86_SETUP_MCE: {
3239 u64 mcg_cap;
3241 r = -EFAULT;
3242 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3243 goto out;
3244 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3245 break;
3247 case KVM_X86_SET_MCE: {
3248 struct kvm_x86_mce mce;
3250 r = -EFAULT;
3251 if (copy_from_user(&mce, argp, sizeof mce))
3252 goto out;
3253 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3254 break;
3256 case KVM_GET_VCPU_EVENTS: {
3257 struct kvm_vcpu_events events;
3259 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3261 r = -EFAULT;
3262 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3263 break;
3264 r = 0;
3265 break;
3267 case KVM_SET_VCPU_EVENTS: {
3268 struct kvm_vcpu_events events;
3270 r = -EFAULT;
3271 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3272 break;
3274 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3275 break;
3277 case KVM_GET_DEBUGREGS: {
3278 struct kvm_debugregs dbgregs;
3280 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3282 r = -EFAULT;
3283 if (copy_to_user(argp, &dbgregs,
3284 sizeof(struct kvm_debugregs)))
3285 break;
3286 r = 0;
3287 break;
3289 case KVM_SET_DEBUGREGS: {
3290 struct kvm_debugregs dbgregs;
3292 r = -EFAULT;
3293 if (copy_from_user(&dbgregs, argp,
3294 sizeof(struct kvm_debugregs)))
3295 break;
3297 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3298 break;
3300 case KVM_GET_XSAVE: {
3301 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3302 r = -ENOMEM;
3303 if (!u.xsave)
3304 break;
3306 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3308 r = -EFAULT;
3309 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3310 break;
3311 r = 0;
3312 break;
3314 case KVM_SET_XSAVE: {
3315 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3316 if (IS_ERR(u.xsave))
3317 return PTR_ERR(u.xsave);
3319 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3320 break;
3322 case KVM_GET_XCRS: {
3323 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3324 r = -ENOMEM;
3325 if (!u.xcrs)
3326 break;
3328 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3330 r = -EFAULT;
3331 if (copy_to_user(argp, u.xcrs,
3332 sizeof(struct kvm_xcrs)))
3333 break;
3334 r = 0;
3335 break;
3337 case KVM_SET_XCRS: {
3338 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3339 if (IS_ERR(u.xcrs))
3340 return PTR_ERR(u.xcrs);
3342 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3343 break;
3345 case KVM_SET_TSC_KHZ: {
3346 u32 user_tsc_khz;
3348 r = -EINVAL;
3349 user_tsc_khz = (u32)arg;
3351 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3352 goto out;
3354 if (user_tsc_khz == 0)
3355 user_tsc_khz = tsc_khz;
3357 kvm_set_tsc_khz(vcpu, user_tsc_khz);
3359 r = 0;
3360 goto out;
3362 case KVM_GET_TSC_KHZ: {
3363 r = vcpu->arch.virtual_tsc_khz;
3364 goto out;
3366 case KVM_KVMCLOCK_CTRL: {
3367 r = kvm_set_guest_paused(vcpu);
3368 goto out;
3370 default:
3371 r = -EINVAL;
3373 out:
3374 kfree(u.buffer);
3375 return r;
3378 int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3380 return VM_FAULT_SIGBUS;
3383 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3385 int ret;
3387 if (addr > (unsigned int)(-3 * PAGE_SIZE))
3388 return -EINVAL;
3389 ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3390 return ret;
3393 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3394 u64 ident_addr)
3396 kvm->arch.ept_identity_map_addr = ident_addr;
3397 return 0;
3400 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3401 u32 kvm_nr_mmu_pages)
3403 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3404 return -EINVAL;
3406 mutex_lock(&kvm->slots_lock);
3408 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3409 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3411 mutex_unlock(&kvm->slots_lock);
3412 return 0;
3415 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3417 return kvm->arch.n_max_mmu_pages;
3420 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3422 int r;
3424 r = 0;
3425 switch (chip->chip_id) {
3426 case KVM_IRQCHIP_PIC_MASTER:
3427 memcpy(&chip->chip.pic,
3428 &pic_irqchip(kvm)->pics[0],
3429 sizeof(struct kvm_pic_state));
3430 break;
3431 case KVM_IRQCHIP_PIC_SLAVE:
3432 memcpy(&chip->chip.pic,
3433 &pic_irqchip(kvm)->pics[1],
3434 sizeof(struct kvm_pic_state));
3435 break;
3436 case KVM_IRQCHIP_IOAPIC:
3437 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3438 break;
3439 default:
3440 r = -EINVAL;
3441 break;
3443 return r;
3446 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3448 int r;
3450 r = 0;
3451 switch (chip->chip_id) {
3452 case KVM_IRQCHIP_PIC_MASTER:
3453 spin_lock(&pic_irqchip(kvm)->lock);
3454 memcpy(&pic_irqchip(kvm)->pics[0],
3455 &chip->chip.pic,
3456 sizeof(struct kvm_pic_state));
3457 spin_unlock(&pic_irqchip(kvm)->lock);
3458 break;
3459 case KVM_IRQCHIP_PIC_SLAVE:
3460 spin_lock(&pic_irqchip(kvm)->lock);
3461 memcpy(&pic_irqchip(kvm)->pics[1],
3462 &chip->chip.pic,
3463 sizeof(struct kvm_pic_state));
3464 spin_unlock(&pic_irqchip(kvm)->lock);
3465 break;
3466 case KVM_IRQCHIP_IOAPIC:
3467 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3468 break;
3469 default:
3470 r = -EINVAL;
3471 break;
3473 kvm_pic_update_irq(pic_irqchip(kvm));
3474 return r;
3477 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3479 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3480 memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
3481 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3482 return 0;
3485 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3487 int i;
3488 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3489 memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
3490 for (i = 0; i < 3; i++)
3491 kvm_pit_load_count(kvm, i, ps->channels[i].count, 0);
3492 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3493 return 0;
3496 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3498 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3499 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3500 sizeof(ps->channels));
3501 ps->flags = kvm->arch.vpit->pit_state.flags;
3502 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3503 memset(&ps->reserved, 0, sizeof(ps->reserved));
3504 return 0;
3507 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3509 int start = 0;
3510 int i;
3511 u32 prev_legacy, cur_legacy;
3512 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3513 prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3514 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3515 if (!prev_legacy && cur_legacy)
3516 start = 1;
3517 memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
3518 sizeof(kvm->arch.vpit->pit_state.channels));
3519 kvm->arch.vpit->pit_state.flags = ps->flags;
3520 for (i = 0; i < 3; i++)
3521 kvm_pit_load_count(kvm, i, kvm->arch.vpit->pit_state.channels[i].count, start);
3522 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3523 return 0;
3526 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3527 struct kvm_reinject_control *control)
3529 if (!kvm->arch.vpit)
3530 return -ENXIO;
3531 mutex_lock(&kvm->arch.vpit->pit_state.lock);
3532 kvm->arch.vpit->pit_state.reinject = control->pit_reinject;
3533 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3534 return 0;
3538 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
3539 * @kvm: kvm instance
3540 * @log: slot id and address to which we copy the log
3542 * We need to keep it in mind that VCPU threads can write to the bitmap
3543 * concurrently. So, to avoid losing data, we keep the following order for
3544 * each bit:
3546 * 1. Take a snapshot of the bit and clear it if needed.
3547 * 2. Write protect the corresponding page.
3548 * 3. Flush TLB's if needed.
3549 * 4. Copy the snapshot to the userspace.
3551 * Between 2 and 3, the guest may write to the page using the remaining TLB
3552 * entry. This is not a problem because the page will be reported dirty at
3553 * step 4 using the snapshot taken before and step 3 ensures that successive
3554 * writes will be logged for the next call.
3556 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
3558 int r;
3559 struct kvm_memory_slot *memslot;
3560 unsigned long n, i;
3561 unsigned long *dirty_bitmap;
3562 unsigned long *dirty_bitmap_buffer;
3563 bool is_dirty = false;
3565 mutex_lock(&kvm->slots_lock);
3567 r = -EINVAL;
3568 if (log->slot >= KVM_USER_MEM_SLOTS)
3569 goto out;
3571 memslot = id_to_memslot(kvm->memslots, log->slot);
3573 dirty_bitmap = memslot->dirty_bitmap;
3574 r = -ENOENT;
3575 if (!dirty_bitmap)
3576 goto out;
3578 n = kvm_dirty_bitmap_bytes(memslot);
3580 dirty_bitmap_buffer = dirty_bitmap + n / sizeof(long);
3581 memset(dirty_bitmap_buffer, 0, n);
3583 spin_lock(&kvm->mmu_lock);
3585 for (i = 0; i < n / sizeof(long); i++) {
3586 unsigned long mask;
3587 gfn_t offset;
3589 if (!dirty_bitmap[i])
3590 continue;
3592 is_dirty = true;
3594 mask = xchg(&dirty_bitmap[i], 0);
3595 dirty_bitmap_buffer[i] = mask;
3597 offset = i * BITS_PER_LONG;
3598 kvm_mmu_write_protect_pt_masked(kvm, memslot, offset, mask);
3600 if (is_dirty)
3601 kvm_flush_remote_tlbs(kvm);
3603 spin_unlock(&kvm->mmu_lock);
3605 r = -EFAULT;
3606 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
3607 goto out;
3609 r = 0;
3610 out:
3611 mutex_unlock(&kvm->slots_lock);
3612 return r;
3615 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
3616 bool line_status)
3618 if (!irqchip_in_kernel(kvm))
3619 return -ENXIO;
3621 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3622 irq_event->irq, irq_event->level,
3623 line_status);
3624 return 0;
3627 long kvm_arch_vm_ioctl(struct file *filp,
3628 unsigned int ioctl, unsigned long arg)
3630 struct kvm *kvm = filp->private_data;
3631 void __user *argp = (void __user *)arg;
3632 int r = -ENOTTY;
3634 * This union makes it completely explicit to gcc-3.x
3635 * that these two variables' stack usage should be
3636 * combined, not added together.
3638 union {
3639 struct kvm_pit_state ps;
3640 struct kvm_pit_state2 ps2;
3641 struct kvm_pit_config pit_config;
3642 } u;
3644 switch (ioctl) {
3645 case KVM_SET_TSS_ADDR:
3646 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3647 break;
3648 case KVM_SET_IDENTITY_MAP_ADDR: {
3649 u64 ident_addr;
3651 r = -EFAULT;
3652 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3653 goto out;
3654 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3655 break;
3657 case KVM_SET_NR_MMU_PAGES:
3658 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3659 break;
3660 case KVM_GET_NR_MMU_PAGES:
3661 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3662 break;
3663 case KVM_CREATE_IRQCHIP: {
3664 struct kvm_pic *vpic;
3666 mutex_lock(&kvm->lock);
3667 r = -EEXIST;
3668 if (kvm->arch.vpic)
3669 goto create_irqchip_unlock;
3670 r = -EINVAL;
3671 if (atomic_read(&kvm->online_vcpus))
3672 goto create_irqchip_unlock;
3673 r = -ENOMEM;
3674 vpic = kvm_create_pic(kvm);
3675 if (vpic) {
3676 r = kvm_ioapic_init(kvm);
3677 if (r) {
3678 mutex_lock(&kvm->slots_lock);
3679 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3680 &vpic->dev_master);
3681 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3682 &vpic->dev_slave);
3683 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3684 &vpic->dev_eclr);
3685 mutex_unlock(&kvm->slots_lock);
3686 kfree(vpic);
3687 goto create_irqchip_unlock;
3689 } else
3690 goto create_irqchip_unlock;
3691 smp_wmb();
3692 kvm->arch.vpic = vpic;
3693 smp_wmb();
3694 r = kvm_setup_default_irq_routing(kvm);
3695 if (r) {
3696 mutex_lock(&kvm->slots_lock);
3697 mutex_lock(&kvm->irq_lock);
3698 kvm_ioapic_destroy(kvm);
3699 kvm_destroy_pic(kvm);
3700 mutex_unlock(&kvm->irq_lock);
3701 mutex_unlock(&kvm->slots_lock);
3703 create_irqchip_unlock:
3704 mutex_unlock(&kvm->lock);
3705 break;
3707 case KVM_CREATE_PIT:
3708 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3709 goto create_pit;
3710 case KVM_CREATE_PIT2:
3711 r = -EFAULT;
3712 if (copy_from_user(&u.pit_config, argp,
3713 sizeof(struct kvm_pit_config)))
3714 goto out;
3715 create_pit:
3716 mutex_lock(&kvm->slots_lock);
3717 r = -EEXIST;
3718 if (kvm->arch.vpit)
3719 goto create_pit_unlock;
3720 r = -ENOMEM;
3721 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3722 if (kvm->arch.vpit)
3723 r = 0;
3724 create_pit_unlock:
3725 mutex_unlock(&kvm->slots_lock);
3726 break;
3727 case KVM_GET_IRQCHIP: {
3728 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3729 struct kvm_irqchip *chip;
3731 chip = memdup_user(argp, sizeof(*chip));
3732 if (IS_ERR(chip)) {
3733 r = PTR_ERR(chip);
3734 goto out;
3737 r = -ENXIO;
3738 if (!irqchip_in_kernel(kvm))
3739 goto get_irqchip_out;
3740 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3741 if (r)
3742 goto get_irqchip_out;
3743 r = -EFAULT;
3744 if (copy_to_user(argp, chip, sizeof *chip))
3745 goto get_irqchip_out;
3746 r = 0;
3747 get_irqchip_out:
3748 kfree(chip);
3749 break;
3751 case KVM_SET_IRQCHIP: {
3752 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3753 struct kvm_irqchip *chip;
3755 chip = memdup_user(argp, sizeof(*chip));
3756 if (IS_ERR(chip)) {
3757 r = PTR_ERR(chip);
3758 goto out;
3761 r = -ENXIO;
3762 if (!irqchip_in_kernel(kvm))
3763 goto set_irqchip_out;
3764 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3765 if (r)
3766 goto set_irqchip_out;
3767 r = 0;
3768 set_irqchip_out:
3769 kfree(chip);
3770 break;
3772 case KVM_GET_PIT: {
3773 r = -EFAULT;
3774 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
3775 goto out;
3776 r = -ENXIO;
3777 if (!kvm->arch.vpit)
3778 goto out;
3779 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
3780 if (r)
3781 goto out;
3782 r = -EFAULT;
3783 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
3784 goto out;
3785 r = 0;
3786 break;
3788 case KVM_SET_PIT: {
3789 r = -EFAULT;
3790 if (copy_from_user(&u.ps, argp, sizeof u.ps))
3791 goto out;
3792 r = -ENXIO;
3793 if (!kvm->arch.vpit)
3794 goto out;
3795 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
3796 break;
3798 case KVM_GET_PIT2: {
3799 r = -ENXIO;
3800 if (!kvm->arch.vpit)
3801 goto out;
3802 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
3803 if (r)
3804 goto out;
3805 r = -EFAULT;
3806 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
3807 goto out;
3808 r = 0;
3809 break;
3811 case KVM_SET_PIT2: {
3812 r = -EFAULT;
3813 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
3814 goto out;
3815 r = -ENXIO;
3816 if (!kvm->arch.vpit)
3817 goto out;
3818 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
3819 break;
3821 case KVM_REINJECT_CONTROL: {
3822 struct kvm_reinject_control control;
3823 r = -EFAULT;
3824 if (copy_from_user(&control, argp, sizeof(control)))
3825 goto out;
3826 r = kvm_vm_ioctl_reinject(kvm, &control);
3827 break;
3829 case KVM_XEN_HVM_CONFIG: {
3830 r = -EFAULT;
3831 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
3832 sizeof(struct kvm_xen_hvm_config)))
3833 goto out;
3834 r = -EINVAL;
3835 if (kvm->arch.xen_hvm_config.flags)
3836 goto out;
3837 r = 0;
3838 break;
3840 case KVM_SET_CLOCK: {
3841 struct kvm_clock_data user_ns;
3842 u64 now_ns;
3843 s64 delta;
3845 r = -EFAULT;
3846 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
3847 goto out;
3849 r = -EINVAL;
3850 if (user_ns.flags)
3851 goto out;
3853 r = 0;
3854 local_irq_disable();
3855 now_ns = get_kernel_ns();
3856 delta = user_ns.clock - now_ns;
3857 local_irq_enable();
3858 kvm->arch.kvmclock_offset = delta;
3859 kvm_gen_update_masterclock(kvm);
3860 break;
3862 case KVM_GET_CLOCK: {
3863 struct kvm_clock_data user_ns;
3864 u64 now_ns;
3866 local_irq_disable();
3867 now_ns = get_kernel_ns();
3868 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
3869 local_irq_enable();
3870 user_ns.flags = 0;
3871 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
3873 r = -EFAULT;
3874 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
3875 goto out;
3876 r = 0;
3877 break;
3880 default:
3883 out:
3884 return r;
3887 static void kvm_init_msr_list(void)
3889 u32 dummy[2];
3890 unsigned i, j;
3892 /* skip the first msrs in the list. KVM-specific */
3893 for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
3894 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
3895 continue;
3896 if (j < i)
3897 msrs_to_save[j] = msrs_to_save[i];
3898 j++;
3900 num_msrs_to_save = j;
3903 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
3904 const void *v)
3906 int handled = 0;
3907 int n;
3909 do {
3910 n = min(len, 8);
3911 if (!(vcpu->arch.apic &&
3912 !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, n, v))
3913 && kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
3914 break;
3915 handled += n;
3916 addr += n;
3917 len -= n;
3918 v += n;
3919 } while (len);
3921 return handled;
3924 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
3926 int handled = 0;
3927 int n;
3929 do {
3930 n = min(len, 8);
3931 if (!(vcpu->arch.apic &&
3932 !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, n, v))
3933 && kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
3934 break;
3935 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
3936 handled += n;
3937 addr += n;
3938 len -= n;
3939 v += n;
3940 } while (len);
3942 return handled;
3945 static void kvm_set_segment(struct kvm_vcpu *vcpu,
3946 struct kvm_segment *var, int seg)
3948 kvm_x86_ops->set_segment(vcpu, var, seg);
3951 void kvm_get_segment(struct kvm_vcpu *vcpu,
3952 struct kvm_segment *var, int seg)
3954 kvm_x86_ops->get_segment(vcpu, var, seg);
3957 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
3959 gpa_t t_gpa;
3960 struct x86_exception exception;
3962 BUG_ON(!mmu_is_nested(vcpu));
3964 /* NPT walks are always user-walks */
3965 access |= PFERR_USER_MASK;
3966 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, &exception);
3968 return t_gpa;
3971 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
3972 struct x86_exception *exception)
3974 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3975 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3978 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
3979 struct x86_exception *exception)
3981 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3982 access |= PFERR_FETCH_MASK;
3983 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3986 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
3987 struct x86_exception *exception)
3989 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3990 access |= PFERR_WRITE_MASK;
3991 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3994 /* uses this to access any guest's mapped memory without checking CPL */
3995 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
3996 struct x86_exception *exception)
3998 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
4001 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4002 struct kvm_vcpu *vcpu, u32 access,
4003 struct x86_exception *exception)
4005 void *data = val;
4006 int r = X86EMUL_CONTINUE;
4008 while (bytes) {
4009 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4010 exception);
4011 unsigned offset = addr & (PAGE_SIZE-1);
4012 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4013 int ret;
4015 if (gpa == UNMAPPED_GVA)
4016 return X86EMUL_PROPAGATE_FAULT;
4017 ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
4018 if (ret < 0) {
4019 r = X86EMUL_IO_NEEDED;
4020 goto out;
4023 bytes -= toread;
4024 data += toread;
4025 addr += toread;
4027 out:
4028 return r;
4031 /* used for instruction fetching */
4032 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4033 gva_t addr, void *val, unsigned int bytes,
4034 struct x86_exception *exception)
4036 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4037 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4039 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
4040 access | PFERR_FETCH_MASK,
4041 exception);
4044 int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
4045 gva_t addr, void *val, unsigned int bytes,
4046 struct x86_exception *exception)
4048 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4049 u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4051 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4052 exception);
4054 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4056 static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4057 gva_t addr, void *val, unsigned int bytes,
4058 struct x86_exception *exception)
4060 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4061 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
4064 int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4065 gva_t addr, void *val,
4066 unsigned int bytes,
4067 struct x86_exception *exception)
4069 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4070 void *data = val;
4071 int r = X86EMUL_CONTINUE;
4073 while (bytes) {
4074 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4075 PFERR_WRITE_MASK,
4076 exception);
4077 unsigned offset = addr & (PAGE_SIZE-1);
4078 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4079 int ret;
4081 if (gpa == UNMAPPED_GVA)
4082 return X86EMUL_PROPAGATE_FAULT;
4083 ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
4084 if (ret < 0) {
4085 r = X86EMUL_IO_NEEDED;
4086 goto out;
4089 bytes -= towrite;
4090 data += towrite;
4091 addr += towrite;
4093 out:
4094 return r;
4096 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4098 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4099 gpa_t *gpa, struct x86_exception *exception,
4100 bool write)
4102 u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
4103 | (write ? PFERR_WRITE_MASK : 0);
4105 if (vcpu_match_mmio_gva(vcpu, gva)
4106 && !permission_fault(vcpu->arch.walk_mmu, vcpu->arch.access, access)) {
4107 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4108 (gva & (PAGE_SIZE - 1));
4109 trace_vcpu_match_mmio(gva, *gpa, write, false);
4110 return 1;
4113 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4115 if (*gpa == UNMAPPED_GVA)
4116 return -1;
4118 /* For APIC access vmexit */
4119 if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4120 return 1;
4122 if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
4123 trace_vcpu_match_mmio(gva, *gpa, write, true);
4124 return 1;
4127 return 0;
4130 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4131 const void *val, int bytes)
4133 int ret;
4135 ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
4136 if (ret < 0)
4137 return 0;
4138 kvm_mmu_pte_write(vcpu, gpa, val, bytes);
4139 return 1;
4142 struct read_write_emulator_ops {
4143 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4144 int bytes);
4145 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4146 void *val, int bytes);
4147 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4148 int bytes, void *val);
4149 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4150 void *val, int bytes);
4151 bool write;
4154 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4156 if (vcpu->mmio_read_completed) {
4157 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4158 vcpu->mmio_fragments[0].gpa, *(u64 *)val);
4159 vcpu->mmio_read_completed = 0;
4160 return 1;
4163 return 0;
4166 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4167 void *val, int bytes)
4169 return !kvm_read_guest(vcpu->kvm, gpa, val, bytes);
4172 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4173 void *val, int bytes)
4175 return emulator_write_phys(vcpu, gpa, val, bytes);
4178 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4180 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
4181 return vcpu_mmio_write(vcpu, gpa, bytes, val);
4184 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4185 void *val, int bytes)
4187 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
4188 return X86EMUL_IO_NEEDED;
4191 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4192 void *val, int bytes)
4194 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
4196 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
4197 return X86EMUL_CONTINUE;
4200 static const struct read_write_emulator_ops read_emultor = {
4201 .read_write_prepare = read_prepare,
4202 .read_write_emulate = read_emulate,
4203 .read_write_mmio = vcpu_mmio_read,
4204 .read_write_exit_mmio = read_exit_mmio,
4207 static const struct read_write_emulator_ops write_emultor = {
4208 .read_write_emulate = write_emulate,
4209 .read_write_mmio = write_mmio,
4210 .read_write_exit_mmio = write_exit_mmio,
4211 .write = true,
4214 static int emulator_read_write_onepage(unsigned long addr, void *val,
4215 unsigned int bytes,
4216 struct x86_exception *exception,
4217 struct kvm_vcpu *vcpu,
4218 const struct read_write_emulator_ops *ops)
4220 gpa_t gpa;
4221 int handled, ret;
4222 bool write = ops->write;
4223 struct kvm_mmio_fragment *frag;
4225 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4227 if (ret < 0)
4228 return X86EMUL_PROPAGATE_FAULT;
4230 /* For APIC access vmexit */
4231 if (ret)
4232 goto mmio;
4234 if (ops->read_write_emulate(vcpu, gpa, val, bytes))
4235 return X86EMUL_CONTINUE;
4237 mmio:
4239 * Is this MMIO handled locally?
4241 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4242 if (handled == bytes)
4243 return X86EMUL_CONTINUE;
4245 gpa += handled;
4246 bytes -= handled;
4247 val += handled;
4249 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
4250 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
4251 frag->gpa = gpa;
4252 frag->data = val;
4253 frag->len = bytes;
4254 return X86EMUL_CONTINUE;
4257 int emulator_read_write(struct x86_emulate_ctxt *ctxt, unsigned long addr,
4258 void *val, unsigned int bytes,
4259 struct x86_exception *exception,
4260 const struct read_write_emulator_ops *ops)
4262 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4263 gpa_t gpa;
4264 int rc;
4266 if (ops->read_write_prepare &&
4267 ops->read_write_prepare(vcpu, val, bytes))
4268 return X86EMUL_CONTINUE;
4270 vcpu->mmio_nr_fragments = 0;
4272 /* Crossing a page boundary? */
4273 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4274 int now;
4276 now = -addr & ~PAGE_MASK;
4277 rc = emulator_read_write_onepage(addr, val, now, exception,
4278 vcpu, ops);
4280 if (rc != X86EMUL_CONTINUE)
4281 return rc;
4282 addr += now;
4283 val += now;
4284 bytes -= now;
4287 rc = emulator_read_write_onepage(addr, val, bytes, exception,
4288 vcpu, ops);
4289 if (rc != X86EMUL_CONTINUE)
4290 return rc;
4292 if (!vcpu->mmio_nr_fragments)
4293 return rc;
4295 gpa = vcpu->mmio_fragments[0].gpa;
4297 vcpu->mmio_needed = 1;
4298 vcpu->mmio_cur_fragment = 0;
4300 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
4301 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
4302 vcpu->run->exit_reason = KVM_EXIT_MMIO;
4303 vcpu->run->mmio.phys_addr = gpa;
4305 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4308 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4309 unsigned long addr,
4310 void *val,
4311 unsigned int bytes,
4312 struct x86_exception *exception)
4314 return emulator_read_write(ctxt, addr, val, bytes,
4315 exception, &read_emultor);
4318 int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4319 unsigned long addr,
4320 const void *val,
4321 unsigned int bytes,
4322 struct x86_exception *exception)
4324 return emulator_read_write(ctxt, addr, (void *)val, bytes,
4325 exception, &write_emultor);
4328 #define CMPXCHG_TYPE(t, ptr, old, new) \
4329 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4331 #ifdef CONFIG_X86_64
4332 # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4333 #else
4334 # define CMPXCHG64(ptr, old, new) \
4335 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4336 #endif
4338 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4339 unsigned long addr,
4340 const void *old,
4341 const void *new,
4342 unsigned int bytes,
4343 struct x86_exception *exception)
4345 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4346 gpa_t gpa;
4347 struct page *page;
4348 char *kaddr;
4349 bool exchanged;
4351 /* guests cmpxchg8b have to be emulated atomically */
4352 if (bytes > 8 || (bytes & (bytes - 1)))
4353 goto emul_write;
4355 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4357 if (gpa == UNMAPPED_GVA ||
4358 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4359 goto emul_write;
4361 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4362 goto emul_write;
4364 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
4365 if (is_error_page(page))
4366 goto emul_write;
4368 kaddr = kmap_atomic(page);
4369 kaddr += offset_in_page(gpa);
4370 switch (bytes) {
4371 case 1:
4372 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4373 break;
4374 case 2:
4375 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4376 break;
4377 case 4:
4378 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
4379 break;
4380 case 8:
4381 exchanged = CMPXCHG64(kaddr, old, new);
4382 break;
4383 default:
4384 BUG();
4386 kunmap_atomic(kaddr);
4387 kvm_release_page_dirty(page);
4389 if (!exchanged)
4390 return X86EMUL_CMPXCHG_FAILED;
4392 kvm_mmu_pte_write(vcpu, gpa, new, bytes);
4394 return X86EMUL_CONTINUE;
4396 emul_write:
4397 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
4399 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
4402 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
4404 /* TODO: String I/O for in kernel device */
4405 int r;
4407 if (vcpu->arch.pio.in)
4408 r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
4409 vcpu->arch.pio.size, pd);
4410 else
4411 r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
4412 vcpu->arch.pio.port, vcpu->arch.pio.size,
4413 pd);
4414 return r;
4417 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
4418 unsigned short port, void *val,
4419 unsigned int count, bool in)
4421 trace_kvm_pio(!in, port, size, count);
4423 vcpu->arch.pio.port = port;
4424 vcpu->arch.pio.in = in;
4425 vcpu->arch.pio.count = count;
4426 vcpu->arch.pio.size = size;
4428 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4429 vcpu->arch.pio.count = 0;
4430 return 1;
4433 vcpu->run->exit_reason = KVM_EXIT_IO;
4434 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
4435 vcpu->run->io.size = size;
4436 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4437 vcpu->run->io.count = count;
4438 vcpu->run->io.port = port;
4440 return 0;
4443 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
4444 int size, unsigned short port, void *val,
4445 unsigned int count)
4447 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4448 int ret;
4450 if (vcpu->arch.pio.count)
4451 goto data_avail;
4453 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
4454 if (ret) {
4455 data_avail:
4456 memcpy(val, vcpu->arch.pio_data, size * count);
4457 vcpu->arch.pio.count = 0;
4458 return 1;
4461 return 0;
4464 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
4465 int size, unsigned short port,
4466 const void *val, unsigned int count)
4468 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4470 memcpy(vcpu->arch.pio_data, val, size * count);
4471 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
4474 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
4476 return kvm_x86_ops->get_segment_base(vcpu, seg);
4479 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
4481 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
4484 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
4486 if (!need_emulate_wbinvd(vcpu))
4487 return X86EMUL_CONTINUE;
4489 if (kvm_x86_ops->has_wbinvd_exit()) {
4490 int cpu = get_cpu();
4492 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4493 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
4494 wbinvd_ipi, NULL, 1);
4495 put_cpu();
4496 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
4497 } else
4498 wbinvd();
4499 return X86EMUL_CONTINUE;
4501 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
4503 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
4505 kvm_emulate_wbinvd(emul_to_vcpu(ctxt));
4508 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
4510 return _kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
4513 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
4516 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
4519 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
4521 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
4524 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
4526 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4527 unsigned long value;
4529 switch (cr) {
4530 case 0:
4531 value = kvm_read_cr0(vcpu);
4532 break;
4533 case 2:
4534 value = vcpu->arch.cr2;
4535 break;
4536 case 3:
4537 value = kvm_read_cr3(vcpu);
4538 break;
4539 case 4:
4540 value = kvm_read_cr4(vcpu);
4541 break;
4542 case 8:
4543 value = kvm_get_cr8(vcpu);
4544 break;
4545 default:
4546 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4547 return 0;
4550 return value;
4553 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
4555 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4556 int res = 0;
4558 switch (cr) {
4559 case 0:
4560 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4561 break;
4562 case 2:
4563 vcpu->arch.cr2 = val;
4564 break;
4565 case 3:
4566 res = kvm_set_cr3(vcpu, val);
4567 break;
4568 case 4:
4569 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4570 break;
4571 case 8:
4572 res = kvm_set_cr8(vcpu, val);
4573 break;
4574 default:
4575 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4576 res = -1;
4579 return res;
4582 static void emulator_set_rflags(struct x86_emulate_ctxt *ctxt, ulong val)
4584 kvm_set_rflags(emul_to_vcpu(ctxt), val);
4587 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
4589 return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
4592 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4594 kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
4597 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4599 kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
4602 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4604 kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4607 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4609 kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4612 static unsigned long emulator_get_cached_segment_base(
4613 struct x86_emulate_ctxt *ctxt, int seg)
4615 return get_segment_base(emul_to_vcpu(ctxt), seg);
4618 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4619 struct desc_struct *desc, u32 *base3,
4620 int seg)
4622 struct kvm_segment var;
4624 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
4625 *selector = var.selector;
4627 if (var.unusable) {
4628 memset(desc, 0, sizeof(*desc));
4629 return false;
4632 if (var.g)
4633 var.limit >>= 12;
4634 set_desc_limit(desc, var.limit);
4635 set_desc_base(desc, (unsigned long)var.base);
4636 #ifdef CONFIG_X86_64
4637 if (base3)
4638 *base3 = var.base >> 32;
4639 #endif
4640 desc->type = var.type;
4641 desc->s = var.s;
4642 desc->dpl = var.dpl;
4643 desc->p = var.present;
4644 desc->avl = var.avl;
4645 desc->l = var.l;
4646 desc->d = var.db;
4647 desc->g = var.g;
4649 return true;
4652 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
4653 struct desc_struct *desc, u32 base3,
4654 int seg)
4656 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4657 struct kvm_segment var;
4659 var.selector = selector;
4660 var.base = get_desc_base(desc);
4661 #ifdef CONFIG_X86_64
4662 var.base |= ((u64)base3) << 32;
4663 #endif
4664 var.limit = get_desc_limit(desc);
4665 if (desc->g)
4666 var.limit = (var.limit << 12) | 0xfff;
4667 var.type = desc->type;
4668 var.present = desc->p;
4669 var.dpl = desc->dpl;
4670 var.db = desc->d;
4671 var.s = desc->s;
4672 var.l = desc->l;
4673 var.g = desc->g;
4674 var.avl = desc->avl;
4675 var.present = desc->p;
4676 var.unusable = !var.present;
4677 var.padding = 0;
4679 kvm_set_segment(vcpu, &var, seg);
4680 return;
4683 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
4684 u32 msr_index, u64 *pdata)
4686 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
4689 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
4690 u32 msr_index, u64 data)
4692 struct msr_data msr;
4694 msr.data = data;
4695 msr.index = msr_index;
4696 msr.host_initiated = false;
4697 return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
4700 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
4701 u32 pmc, u64 *pdata)
4703 return kvm_pmu_read_pmc(emul_to_vcpu(ctxt), pmc, pdata);
4706 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
4708 emul_to_vcpu(ctxt)->arch.halt_request = 1;
4711 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
4713 preempt_disable();
4714 kvm_load_guest_fpu(emul_to_vcpu(ctxt));
4716 * CR0.TS may reference the host fpu state, not the guest fpu state,
4717 * so it may be clear at this point.
4719 clts();
4722 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
4724 preempt_enable();
4727 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
4728 struct x86_instruction_info *info,
4729 enum x86_intercept_stage stage)
4731 return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
4734 static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
4735 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
4737 kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
4740 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
4742 return kvm_register_read(emul_to_vcpu(ctxt), reg);
4745 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
4747 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
4750 static const struct x86_emulate_ops emulate_ops = {
4751 .read_gpr = emulator_read_gpr,
4752 .write_gpr = emulator_write_gpr,
4753 .read_std = kvm_read_guest_virt_system,
4754 .write_std = kvm_write_guest_virt_system,
4755 .fetch = kvm_fetch_guest_virt,
4756 .read_emulated = emulator_read_emulated,
4757 .write_emulated = emulator_write_emulated,
4758 .cmpxchg_emulated = emulator_cmpxchg_emulated,
4759 .invlpg = emulator_invlpg,
4760 .pio_in_emulated = emulator_pio_in_emulated,
4761 .pio_out_emulated = emulator_pio_out_emulated,
4762 .get_segment = emulator_get_segment,
4763 .set_segment = emulator_set_segment,
4764 .get_cached_segment_base = emulator_get_cached_segment_base,
4765 .get_gdt = emulator_get_gdt,
4766 .get_idt = emulator_get_idt,
4767 .set_gdt = emulator_set_gdt,
4768 .set_idt = emulator_set_idt,
4769 .get_cr = emulator_get_cr,
4770 .set_cr = emulator_set_cr,
4771 .set_rflags = emulator_set_rflags,
4772 .cpl = emulator_get_cpl,
4773 .get_dr = emulator_get_dr,
4774 .set_dr = emulator_set_dr,
4775 .set_msr = emulator_set_msr,
4776 .get_msr = emulator_get_msr,
4777 .read_pmc = emulator_read_pmc,
4778 .halt = emulator_halt,
4779 .wbinvd = emulator_wbinvd,
4780 .fix_hypercall = emulator_fix_hypercall,
4781 .get_fpu = emulator_get_fpu,
4782 .put_fpu = emulator_put_fpu,
4783 .intercept = emulator_intercept,
4784 .get_cpuid = emulator_get_cpuid,
4787 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
4789 u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu, mask);
4791 * an sti; sti; sequence only disable interrupts for the first
4792 * instruction. So, if the last instruction, be it emulated or
4793 * not, left the system with the INT_STI flag enabled, it
4794 * means that the last instruction is an sti. We should not
4795 * leave the flag on in this case. The same goes for mov ss
4797 if (!(int_shadow & mask))
4798 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
4801 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
4803 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4804 if (ctxt->exception.vector == PF_VECTOR)
4805 kvm_propagate_fault(vcpu, &ctxt->exception);
4806 else if (ctxt->exception.error_code_valid)
4807 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
4808 ctxt->exception.error_code);
4809 else
4810 kvm_queue_exception(vcpu, ctxt->exception.vector);
4813 static void init_decode_cache(struct x86_emulate_ctxt *ctxt)
4815 memset(&ctxt->twobyte, 0,
4816 (void *)&ctxt->_regs - (void *)&ctxt->twobyte);
4818 ctxt->fetch.start = 0;
4819 ctxt->fetch.end = 0;
4820 ctxt->io_read.pos = 0;
4821 ctxt->io_read.end = 0;
4822 ctxt->mem_read.pos = 0;
4823 ctxt->mem_read.end = 0;
4826 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
4828 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4829 int cs_db, cs_l;
4831 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4833 ctxt->eflags = kvm_get_rflags(vcpu);
4834 ctxt->eip = kvm_rip_read(vcpu);
4835 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
4836 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
4837 cs_l ? X86EMUL_MODE_PROT64 :
4838 cs_db ? X86EMUL_MODE_PROT32 :
4839 X86EMUL_MODE_PROT16;
4840 ctxt->guest_mode = is_guest_mode(vcpu);
4842 init_decode_cache(ctxt);
4843 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
4846 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
4848 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4849 int ret;
4851 init_emulate_ctxt(vcpu);
4853 ctxt->op_bytes = 2;
4854 ctxt->ad_bytes = 2;
4855 ctxt->_eip = ctxt->eip + inc_eip;
4856 ret = emulate_int_real(ctxt, irq);
4858 if (ret != X86EMUL_CONTINUE)
4859 return EMULATE_FAIL;
4861 ctxt->eip = ctxt->_eip;
4862 kvm_rip_write(vcpu, ctxt->eip);
4863 kvm_set_rflags(vcpu, ctxt->eflags);
4865 if (irq == NMI_VECTOR)
4866 vcpu->arch.nmi_pending = 0;
4867 else
4868 vcpu->arch.interrupt.pending = false;
4870 return EMULATE_DONE;
4872 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
4874 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
4876 int r = EMULATE_DONE;
4878 ++vcpu->stat.insn_emulation_fail;
4879 trace_kvm_emulate_insn_failed(vcpu);
4880 if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
4881 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4882 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
4883 vcpu->run->internal.ndata = 0;
4884 r = EMULATE_FAIL;
4886 kvm_queue_exception(vcpu, UD_VECTOR);
4888 return r;
4891 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
4892 bool write_fault_to_shadow_pgtable,
4893 int emulation_type)
4895 gpa_t gpa = cr2;
4896 pfn_t pfn;
4898 if (emulation_type & EMULTYPE_NO_REEXECUTE)
4899 return false;
4901 if (!vcpu->arch.mmu.direct_map) {
4903 * Write permission should be allowed since only
4904 * write access need to be emulated.
4906 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
4909 * If the mapping is invalid in guest, let cpu retry
4910 * it to generate fault.
4912 if (gpa == UNMAPPED_GVA)
4913 return true;
4917 * Do not retry the unhandleable instruction if it faults on the
4918 * readonly host memory, otherwise it will goto a infinite loop:
4919 * retry instruction -> write #PF -> emulation fail -> retry
4920 * instruction -> ...
4922 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
4925 * If the instruction failed on the error pfn, it can not be fixed,
4926 * report the error to userspace.
4928 if (is_error_noslot_pfn(pfn))
4929 return false;
4931 kvm_release_pfn_clean(pfn);
4933 /* The instructions are well-emulated on direct mmu. */
4934 if (vcpu->arch.mmu.direct_map) {
4935 unsigned int indirect_shadow_pages;
4937 spin_lock(&vcpu->kvm->mmu_lock);
4938 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
4939 spin_unlock(&vcpu->kvm->mmu_lock);
4941 if (indirect_shadow_pages)
4942 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
4944 return true;
4948 * if emulation was due to access to shadowed page table
4949 * and it failed try to unshadow page and re-enter the
4950 * guest to let CPU execute the instruction.
4952 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
4955 * If the access faults on its page table, it can not
4956 * be fixed by unprotecting shadow page and it should
4957 * be reported to userspace.
4959 return !write_fault_to_shadow_pgtable;
4962 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
4963 unsigned long cr2, int emulation_type)
4965 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4966 unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
4968 last_retry_eip = vcpu->arch.last_retry_eip;
4969 last_retry_addr = vcpu->arch.last_retry_addr;
4972 * If the emulation is caused by #PF and it is non-page_table
4973 * writing instruction, it means the VM-EXIT is caused by shadow
4974 * page protected, we can zap the shadow page and retry this
4975 * instruction directly.
4977 * Note: if the guest uses a non-page-table modifying instruction
4978 * on the PDE that points to the instruction, then we will unmap
4979 * the instruction and go to an infinite loop. So, we cache the
4980 * last retried eip and the last fault address, if we meet the eip
4981 * and the address again, we can break out of the potential infinite
4982 * loop.
4984 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
4986 if (!(emulation_type & EMULTYPE_RETRY))
4987 return false;
4989 if (x86_page_table_writing_insn(ctxt))
4990 return false;
4992 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
4993 return false;
4995 vcpu->arch.last_retry_eip = ctxt->eip;
4996 vcpu->arch.last_retry_addr = cr2;
4998 if (!vcpu->arch.mmu.direct_map)
4999 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5001 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5003 return true;
5006 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
5007 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
5009 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
5010 unsigned long *db)
5012 u32 dr6 = 0;
5013 int i;
5014 u32 enable, rwlen;
5016 enable = dr7;
5017 rwlen = dr7 >> 16;
5018 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
5019 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
5020 dr6 |= (1 << i);
5021 return dr6;
5024 static void kvm_vcpu_check_singlestep(struct kvm_vcpu *vcpu, int *r)
5026 struct kvm_run *kvm_run = vcpu->run;
5029 * Use the "raw" value to see if TF was passed to the processor.
5030 * Note that the new value of the flags has not been saved yet.
5032 * This is correct even for TF set by the guest, because "the
5033 * processor will not generate this exception after the instruction
5034 * that sets the TF flag".
5036 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5038 if (unlikely(rflags & X86_EFLAGS_TF)) {
5039 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5040 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1;
5041 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
5042 kvm_run->debug.arch.exception = DB_VECTOR;
5043 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5044 *r = EMULATE_USER_EXIT;
5045 } else {
5046 vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF;
5048 * "Certain debug exceptions may clear bit 0-3. The
5049 * remaining contents of the DR6 register are never
5050 * cleared by the processor".
5052 vcpu->arch.dr6 &= ~15;
5053 vcpu->arch.dr6 |= DR6_BS;
5054 kvm_queue_exception(vcpu, DB_VECTOR);
5059 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
5061 struct kvm_run *kvm_run = vcpu->run;
5062 unsigned long eip = vcpu->arch.emulate_ctxt.eip;
5063 u32 dr6 = 0;
5065 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
5066 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
5067 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5068 vcpu->arch.guest_debug_dr7,
5069 vcpu->arch.eff_db);
5071 if (dr6 != 0) {
5072 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
5073 kvm_run->debug.arch.pc = kvm_rip_read(vcpu) +
5074 get_segment_base(vcpu, VCPU_SREG_CS);
5076 kvm_run->debug.arch.exception = DB_VECTOR;
5077 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5078 *r = EMULATE_USER_EXIT;
5079 return true;
5083 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK)) {
5084 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5085 vcpu->arch.dr7,
5086 vcpu->arch.db);
5088 if (dr6 != 0) {
5089 vcpu->arch.dr6 &= ~15;
5090 vcpu->arch.dr6 |= dr6;
5091 kvm_queue_exception(vcpu, DB_VECTOR);
5092 *r = EMULATE_DONE;
5093 return true;
5097 return false;
5100 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
5101 unsigned long cr2,
5102 int emulation_type,
5103 void *insn,
5104 int insn_len)
5106 int r;
5107 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5108 bool writeback = true;
5109 bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
5112 * Clear write_fault_to_shadow_pgtable here to ensure it is
5113 * never reused.
5115 vcpu->arch.write_fault_to_shadow_pgtable = false;
5116 kvm_clear_exception_queue(vcpu);
5118 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
5119 init_emulate_ctxt(vcpu);
5122 * We will reenter on the same instruction since
5123 * we do not set complete_userspace_io. This does not
5124 * handle watchpoints yet, those would be handled in
5125 * the emulate_ops.
5127 if (kvm_vcpu_check_breakpoint(vcpu, &r))
5128 return r;
5130 ctxt->interruptibility = 0;
5131 ctxt->have_exception = false;
5132 ctxt->perm_ok = false;
5134 ctxt->only_vendor_specific_insn
5135 = emulation_type & EMULTYPE_TRAP_UD;
5137 r = x86_decode_insn(ctxt, insn, insn_len);
5139 trace_kvm_emulate_insn_start(vcpu);
5140 ++vcpu->stat.insn_emulation;
5141 if (r != EMULATION_OK) {
5142 if (emulation_type & EMULTYPE_TRAP_UD)
5143 return EMULATE_FAIL;
5144 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5145 emulation_type))
5146 return EMULATE_DONE;
5147 if (emulation_type & EMULTYPE_SKIP)
5148 return EMULATE_FAIL;
5149 return handle_emulation_failure(vcpu);
5153 if (emulation_type & EMULTYPE_SKIP) {
5154 kvm_rip_write(vcpu, ctxt->_eip);
5155 return EMULATE_DONE;
5158 if (retry_instruction(ctxt, cr2, emulation_type))
5159 return EMULATE_DONE;
5161 /* this is needed for vmware backdoor interface to work since it
5162 changes registers values during IO operation */
5163 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
5164 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5165 emulator_invalidate_register_cache(ctxt);
5168 restart:
5169 r = x86_emulate_insn(ctxt);
5171 if (r == EMULATION_INTERCEPTED)
5172 return EMULATE_DONE;
5174 if (r == EMULATION_FAILED) {
5175 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5176 emulation_type))
5177 return EMULATE_DONE;
5179 return handle_emulation_failure(vcpu);
5182 if (ctxt->have_exception) {
5183 inject_emulated_exception(vcpu);
5184 r = EMULATE_DONE;
5185 } else if (vcpu->arch.pio.count) {
5186 if (!vcpu->arch.pio.in) {
5187 /* FIXME: return into emulator if single-stepping. */
5188 vcpu->arch.pio.count = 0;
5189 } else {
5190 writeback = false;
5191 vcpu->arch.complete_userspace_io = complete_emulated_pio;
5193 r = EMULATE_USER_EXIT;
5194 } else if (vcpu->mmio_needed) {
5195 if (!vcpu->mmio_is_write)
5196 writeback = false;
5197 r = EMULATE_USER_EXIT;
5198 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
5199 } else if (r == EMULATION_RESTART)
5200 goto restart;
5201 else
5202 r = EMULATE_DONE;
5204 if (writeback) {
5205 toggle_interruptibility(vcpu, ctxt->interruptibility);
5206 kvm_make_request(KVM_REQ_EVENT, vcpu);
5207 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5208 kvm_rip_write(vcpu, ctxt->eip);
5209 if (r == EMULATE_DONE)
5210 kvm_vcpu_check_singlestep(vcpu, &r);
5211 kvm_set_rflags(vcpu, ctxt->eflags);
5212 } else
5213 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5215 return r;
5217 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5219 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5221 unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5222 int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5223 size, port, &val, 1);
5224 /* do not return to emulator after return from userspace */
5225 vcpu->arch.pio.count = 0;
5226 return ret;
5228 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5230 static void tsc_bad(void *info)
5232 __this_cpu_write(cpu_tsc_khz, 0);
5235 static void tsc_khz_changed(void *data)
5237 struct cpufreq_freqs *freq = data;
5238 unsigned long khz = 0;
5240 if (data)
5241 khz = freq->new;
5242 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5243 khz = cpufreq_quick_get(raw_smp_processor_id());
5244 if (!khz)
5245 khz = tsc_khz;
5246 __this_cpu_write(cpu_tsc_khz, khz);
5249 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5250 void *data)
5252 struct cpufreq_freqs *freq = data;
5253 struct kvm *kvm;
5254 struct kvm_vcpu *vcpu;
5255 int i, send_ipi = 0;
5258 * We allow guests to temporarily run on slowing clocks,
5259 * provided we notify them after, or to run on accelerating
5260 * clocks, provided we notify them before. Thus time never
5261 * goes backwards.
5263 * However, we have a problem. We can't atomically update
5264 * the frequency of a given CPU from this function; it is
5265 * merely a notifier, which can be called from any CPU.
5266 * Changing the TSC frequency at arbitrary points in time
5267 * requires a recomputation of local variables related to
5268 * the TSC for each VCPU. We must flag these local variables
5269 * to be updated and be sure the update takes place with the
5270 * new frequency before any guests proceed.
5272 * Unfortunately, the combination of hotplug CPU and frequency
5273 * change creates an intractable locking scenario; the order
5274 * of when these callouts happen is undefined with respect to
5275 * CPU hotplug, and they can race with each other. As such,
5276 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5277 * undefined; you can actually have a CPU frequency change take
5278 * place in between the computation of X and the setting of the
5279 * variable. To protect against this problem, all updates of
5280 * the per_cpu tsc_khz variable are done in an interrupt
5281 * protected IPI, and all callers wishing to update the value
5282 * must wait for a synchronous IPI to complete (which is trivial
5283 * if the caller is on the CPU already). This establishes the
5284 * necessary total order on variable updates.
5286 * Note that because a guest time update may take place
5287 * anytime after the setting of the VCPU's request bit, the
5288 * correct TSC value must be set before the request. However,
5289 * to ensure the update actually makes it to any guest which
5290 * starts running in hardware virtualization between the set
5291 * and the acquisition of the spinlock, we must also ping the
5292 * CPU after setting the request bit.
5296 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
5297 return 0;
5298 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
5299 return 0;
5301 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5303 raw_spin_lock(&kvm_lock);
5304 list_for_each_entry(kvm, &vm_list, vm_list) {
5305 kvm_for_each_vcpu(i, vcpu, kvm) {
5306 if (vcpu->cpu != freq->cpu)
5307 continue;
5308 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5309 if (vcpu->cpu != smp_processor_id())
5310 send_ipi = 1;
5313 raw_spin_unlock(&kvm_lock);
5315 if (freq->old < freq->new && send_ipi) {
5317 * We upscale the frequency. Must make the guest
5318 * doesn't see old kvmclock values while running with
5319 * the new frequency, otherwise we risk the guest sees
5320 * time go backwards.
5322 * In case we update the frequency for another cpu
5323 * (which might be in guest context) send an interrupt
5324 * to kick the cpu out of guest context. Next time
5325 * guest context is entered kvmclock will be updated,
5326 * so the guest will not see stale values.
5328 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5330 return 0;
5333 static struct notifier_block kvmclock_cpufreq_notifier_block = {
5334 .notifier_call = kvmclock_cpufreq_notifier
5337 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
5338 unsigned long action, void *hcpu)
5340 unsigned int cpu = (unsigned long)hcpu;
5342 switch (action) {
5343 case CPU_ONLINE:
5344 case CPU_DOWN_FAILED:
5345 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5346 break;
5347 case CPU_DOWN_PREPARE:
5348 smp_call_function_single(cpu, tsc_bad, NULL, 1);
5349 break;
5351 return NOTIFY_OK;
5354 static struct notifier_block kvmclock_cpu_notifier_block = {
5355 .notifier_call = kvmclock_cpu_notifier,
5356 .priority = -INT_MAX
5359 static void kvm_timer_init(void)
5361 int cpu;
5363 max_tsc_khz = tsc_khz;
5364 register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5365 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5366 #ifdef CONFIG_CPU_FREQ
5367 struct cpufreq_policy policy;
5368 memset(&policy, 0, sizeof(policy));
5369 cpu = get_cpu();
5370 cpufreq_get_policy(&policy, cpu);
5371 if (policy.cpuinfo.max_freq)
5372 max_tsc_khz = policy.cpuinfo.max_freq;
5373 put_cpu();
5374 #endif
5375 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
5376 CPUFREQ_TRANSITION_NOTIFIER);
5378 pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
5379 for_each_online_cpu(cpu)
5380 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5383 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
5385 int kvm_is_in_guest(void)
5387 return __this_cpu_read(current_vcpu) != NULL;
5390 static int kvm_is_user_mode(void)
5392 int user_mode = 3;
5394 if (__this_cpu_read(current_vcpu))
5395 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
5397 return user_mode != 0;
5400 static unsigned long kvm_get_guest_ip(void)
5402 unsigned long ip = 0;
5404 if (__this_cpu_read(current_vcpu))
5405 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
5407 return ip;
5410 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5411 .is_in_guest = kvm_is_in_guest,
5412 .is_user_mode = kvm_is_user_mode,
5413 .get_guest_ip = kvm_get_guest_ip,
5416 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
5418 __this_cpu_write(current_vcpu, vcpu);
5420 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
5422 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
5424 __this_cpu_write(current_vcpu, NULL);
5426 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
5428 static void kvm_set_mmio_spte_mask(void)
5430 u64 mask;
5431 int maxphyaddr = boot_cpu_data.x86_phys_bits;
5434 * Set the reserved bits and the present bit of an paging-structure
5435 * entry to generate page fault with PFER.RSV = 1.
5437 /* Mask the reserved physical address bits. */
5438 mask = ((1ull << (51 - maxphyaddr + 1)) - 1) << maxphyaddr;
5440 /* Bit 62 is always reserved for 32bit host. */
5441 mask |= 0x3ull << 62;
5443 /* Set the present bit. */
5444 mask |= 1ull;
5446 #ifdef CONFIG_X86_64
5448 * If reserved bit is not supported, clear the present bit to disable
5449 * mmio page fault.
5451 if (maxphyaddr == 52)
5452 mask &= ~1ull;
5453 #endif
5455 kvm_mmu_set_mmio_spte_mask(mask);
5458 #ifdef CONFIG_X86_64
5459 static void pvclock_gtod_update_fn(struct work_struct *work)
5461 struct kvm *kvm;
5463 struct kvm_vcpu *vcpu;
5464 int i;
5466 raw_spin_lock(&kvm_lock);
5467 list_for_each_entry(kvm, &vm_list, vm_list)
5468 kvm_for_each_vcpu(i, vcpu, kvm)
5469 set_bit(KVM_REQ_MASTERCLOCK_UPDATE, &vcpu->requests);
5470 atomic_set(&kvm_guest_has_master_clock, 0);
5471 raw_spin_unlock(&kvm_lock);
5474 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
5477 * Notification about pvclock gtod data update.
5479 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
5480 void *priv)
5482 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
5483 struct timekeeper *tk = priv;
5485 update_pvclock_gtod(tk);
5487 /* disable master clock if host does not trust, or does not
5488 * use, TSC clocksource
5490 if (gtod->clock.vclock_mode != VCLOCK_TSC &&
5491 atomic_read(&kvm_guest_has_master_clock) != 0)
5492 queue_work(system_long_wq, &pvclock_gtod_work);
5494 return 0;
5497 static struct notifier_block pvclock_gtod_notifier = {
5498 .notifier_call = pvclock_gtod_notify,
5500 #endif
5502 int kvm_arch_init(void *opaque)
5504 int r;
5505 struct kvm_x86_ops *ops = opaque;
5507 if (kvm_x86_ops) {
5508 printk(KERN_ERR "kvm: already loaded the other module\n");
5509 r = -EEXIST;
5510 goto out;
5513 if (!ops->cpu_has_kvm_support()) {
5514 printk(KERN_ERR "kvm: no hardware support\n");
5515 r = -EOPNOTSUPP;
5516 goto out;
5518 if (ops->disabled_by_bios()) {
5519 printk(KERN_ERR "kvm: disabled by bios\n");
5520 r = -EOPNOTSUPP;
5521 goto out;
5524 r = -ENOMEM;
5525 shared_msrs = alloc_percpu(struct kvm_shared_msrs);
5526 if (!shared_msrs) {
5527 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
5528 goto out;
5531 r = kvm_mmu_module_init();
5532 if (r)
5533 goto out_free_percpu;
5535 kvm_set_mmio_spte_mask();
5536 kvm_init_msr_list();
5538 kvm_x86_ops = ops;
5539 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
5540 PT_DIRTY_MASK, PT64_NX_MASK, 0);
5542 kvm_timer_init();
5544 perf_register_guest_info_callbacks(&kvm_guest_cbs);
5546 if (cpu_has_xsave)
5547 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
5549 kvm_lapic_init();
5550 #ifdef CONFIG_X86_64
5551 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
5552 #endif
5554 return 0;
5556 out_free_percpu:
5557 free_percpu(shared_msrs);
5558 out:
5559 return r;
5562 void kvm_arch_exit(void)
5564 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
5566 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5567 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
5568 CPUFREQ_TRANSITION_NOTIFIER);
5569 unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5570 #ifdef CONFIG_X86_64
5571 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
5572 #endif
5573 kvm_x86_ops = NULL;
5574 kvm_mmu_module_exit();
5575 free_percpu(shared_msrs);
5578 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
5580 ++vcpu->stat.halt_exits;
5581 if (irqchip_in_kernel(vcpu->kvm)) {
5582 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
5583 return 1;
5584 } else {
5585 vcpu->run->exit_reason = KVM_EXIT_HLT;
5586 return 0;
5589 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
5591 int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
5593 u64 param, ingpa, outgpa, ret;
5594 uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
5595 bool fast, longmode;
5596 int cs_db, cs_l;
5599 * hypercall generates UD from non zero cpl and real mode
5600 * per HYPER-V spec
5602 if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
5603 kvm_queue_exception(vcpu, UD_VECTOR);
5604 return 0;
5607 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5608 longmode = is_long_mode(vcpu) && cs_l == 1;
5610 if (!longmode) {
5611 param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
5612 (kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
5613 ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
5614 (kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
5615 outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
5616 (kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
5618 #ifdef CONFIG_X86_64
5619 else {
5620 param = kvm_register_read(vcpu, VCPU_REGS_RCX);
5621 ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
5622 outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
5624 #endif
5626 code = param & 0xffff;
5627 fast = (param >> 16) & 0x1;
5628 rep_cnt = (param >> 32) & 0xfff;
5629 rep_idx = (param >> 48) & 0xfff;
5631 trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
5633 switch (code) {
5634 case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
5635 kvm_vcpu_on_spin(vcpu);
5636 break;
5637 default:
5638 res = HV_STATUS_INVALID_HYPERCALL_CODE;
5639 break;
5642 ret = res | (((u64)rep_done & 0xfff) << 32);
5643 if (longmode) {
5644 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
5645 } else {
5646 kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
5647 kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
5650 return 1;
5654 * kvm_pv_kick_cpu_op: Kick a vcpu.
5656 * @apicid - apicid of vcpu to be kicked.
5658 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
5660 struct kvm_lapic_irq lapic_irq;
5662 lapic_irq.shorthand = 0;
5663 lapic_irq.dest_mode = 0;
5664 lapic_irq.dest_id = apicid;
5666 lapic_irq.delivery_mode = APIC_DM_REMRD;
5667 kvm_irq_delivery_to_apic(kvm, 0, &lapic_irq, NULL);
5670 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
5672 unsigned long nr, a0, a1, a2, a3, ret;
5673 int r = 1;
5675 if (kvm_hv_hypercall_enabled(vcpu->kvm))
5676 return kvm_hv_hypercall(vcpu);
5678 nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
5679 a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
5680 a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
5681 a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
5682 a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
5684 trace_kvm_hypercall(nr, a0, a1, a2, a3);
5686 if (!is_long_mode(vcpu)) {
5687 nr &= 0xFFFFFFFF;
5688 a0 &= 0xFFFFFFFF;
5689 a1 &= 0xFFFFFFFF;
5690 a2 &= 0xFFFFFFFF;
5691 a3 &= 0xFFFFFFFF;
5694 if (kvm_x86_ops->get_cpl(vcpu) != 0) {
5695 ret = -KVM_EPERM;
5696 goto out;
5699 switch (nr) {
5700 case KVM_HC_VAPIC_POLL_IRQ:
5701 ret = 0;
5702 break;
5703 case KVM_HC_KICK_CPU:
5704 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
5705 ret = 0;
5706 break;
5707 default:
5708 ret = -KVM_ENOSYS;
5709 break;
5711 out:
5712 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
5713 ++vcpu->stat.hypercalls;
5714 return r;
5716 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
5718 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
5720 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5721 char instruction[3];
5722 unsigned long rip = kvm_rip_read(vcpu);
5724 kvm_x86_ops->patch_hypercall(vcpu, instruction);
5726 return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
5730 * Check if userspace requested an interrupt window, and that the
5731 * interrupt window is open.
5733 * No need to exit to userspace if we already have an interrupt queued.
5735 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
5737 return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
5738 vcpu->run->request_interrupt_window &&
5739 kvm_arch_interrupt_allowed(vcpu));
5742 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
5744 struct kvm_run *kvm_run = vcpu->run;
5746 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
5747 kvm_run->cr8 = kvm_get_cr8(vcpu);
5748 kvm_run->apic_base = kvm_get_apic_base(vcpu);
5749 if (irqchip_in_kernel(vcpu->kvm))
5750 kvm_run->ready_for_interrupt_injection = 1;
5751 else
5752 kvm_run->ready_for_interrupt_injection =
5753 kvm_arch_interrupt_allowed(vcpu) &&
5754 !kvm_cpu_has_interrupt(vcpu) &&
5755 !kvm_event_needs_reinjection(vcpu);
5758 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
5760 int max_irr, tpr;
5762 if (!kvm_x86_ops->update_cr8_intercept)
5763 return;
5765 if (!vcpu->arch.apic)
5766 return;
5768 if (!vcpu->arch.apic->vapic_addr)
5769 max_irr = kvm_lapic_find_highest_irr(vcpu);
5770 else
5771 max_irr = -1;
5773 if (max_irr != -1)
5774 max_irr >>= 4;
5776 tpr = kvm_lapic_get_cr8(vcpu);
5778 kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
5781 static void inject_pending_event(struct kvm_vcpu *vcpu)
5783 /* try to reinject previous events if any */
5784 if (vcpu->arch.exception.pending) {
5785 trace_kvm_inj_exception(vcpu->arch.exception.nr,
5786 vcpu->arch.exception.has_error_code,
5787 vcpu->arch.exception.error_code);
5788 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
5789 vcpu->arch.exception.has_error_code,
5790 vcpu->arch.exception.error_code,
5791 vcpu->arch.exception.reinject);
5792 return;
5795 if (vcpu->arch.nmi_injected) {
5796 kvm_x86_ops->set_nmi(vcpu);
5797 return;
5800 if (vcpu->arch.interrupt.pending) {
5801 kvm_x86_ops->set_irq(vcpu);
5802 return;
5805 /* try to inject new event if pending */
5806 if (vcpu->arch.nmi_pending) {
5807 if (kvm_x86_ops->nmi_allowed(vcpu)) {
5808 --vcpu->arch.nmi_pending;
5809 vcpu->arch.nmi_injected = true;
5810 kvm_x86_ops->set_nmi(vcpu);
5812 } else if (kvm_cpu_has_injectable_intr(vcpu)) {
5813 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
5814 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
5815 false);
5816 kvm_x86_ops->set_irq(vcpu);
5821 static void process_nmi(struct kvm_vcpu *vcpu)
5823 unsigned limit = 2;
5826 * x86 is limited to one NMI running, and one NMI pending after it.
5827 * If an NMI is already in progress, limit further NMIs to just one.
5828 * Otherwise, allow two (and we'll inject the first one immediately).
5830 if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
5831 limit = 1;
5833 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
5834 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
5835 kvm_make_request(KVM_REQ_EVENT, vcpu);
5838 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
5840 u64 eoi_exit_bitmap[4];
5841 u32 tmr[8];
5843 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
5844 return;
5846 memset(eoi_exit_bitmap, 0, 32);
5847 memset(tmr, 0, 32);
5849 kvm_ioapic_scan_entry(vcpu, eoi_exit_bitmap, tmr);
5850 kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
5851 kvm_apic_update_tmr(vcpu, tmr);
5854 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
5856 int r;
5857 bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
5858 vcpu->run->request_interrupt_window;
5859 bool req_immediate_exit = false;
5861 if (vcpu->requests) {
5862 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
5863 kvm_mmu_unload(vcpu);
5864 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
5865 __kvm_migrate_timers(vcpu);
5866 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
5867 kvm_gen_update_masterclock(vcpu->kvm);
5868 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
5869 kvm_gen_kvmclock_update(vcpu);
5870 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
5871 r = kvm_guest_time_update(vcpu);
5872 if (unlikely(r))
5873 goto out;
5875 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
5876 kvm_mmu_sync_roots(vcpu);
5877 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
5878 kvm_x86_ops->tlb_flush(vcpu);
5879 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
5880 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
5881 r = 0;
5882 goto out;
5884 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
5885 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5886 r = 0;
5887 goto out;
5889 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
5890 vcpu->fpu_active = 0;
5891 kvm_x86_ops->fpu_deactivate(vcpu);
5893 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
5894 /* Page is swapped out. Do synthetic halt */
5895 vcpu->arch.apf.halted = true;
5896 r = 1;
5897 goto out;
5899 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
5900 record_steal_time(vcpu);
5901 if (kvm_check_request(KVM_REQ_NMI, vcpu))
5902 process_nmi(vcpu);
5903 if (kvm_check_request(KVM_REQ_PMU, vcpu))
5904 kvm_handle_pmu_event(vcpu);
5905 if (kvm_check_request(KVM_REQ_PMI, vcpu))
5906 kvm_deliver_pmi(vcpu);
5907 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
5908 vcpu_scan_ioapic(vcpu);
5911 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
5912 kvm_apic_accept_events(vcpu);
5913 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
5914 r = 1;
5915 goto out;
5918 inject_pending_event(vcpu);
5920 /* enable NMI/IRQ window open exits if needed */
5921 if (vcpu->arch.nmi_pending)
5922 req_immediate_exit =
5923 kvm_x86_ops->enable_nmi_window(vcpu) != 0;
5924 else if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
5925 req_immediate_exit =
5926 kvm_x86_ops->enable_irq_window(vcpu) != 0;
5928 if (kvm_lapic_enabled(vcpu)) {
5930 * Update architecture specific hints for APIC
5931 * virtual interrupt delivery.
5933 if (kvm_x86_ops->hwapic_irr_update)
5934 kvm_x86_ops->hwapic_irr_update(vcpu,
5935 kvm_lapic_find_highest_irr(vcpu));
5936 update_cr8_intercept(vcpu);
5937 kvm_lapic_sync_to_vapic(vcpu);
5941 r = kvm_mmu_reload(vcpu);
5942 if (unlikely(r)) {
5943 goto cancel_injection;
5946 preempt_disable();
5948 kvm_x86_ops->prepare_guest_switch(vcpu);
5949 if (vcpu->fpu_active)
5950 kvm_load_guest_fpu(vcpu);
5951 kvm_load_guest_xcr0(vcpu);
5953 vcpu->mode = IN_GUEST_MODE;
5955 /* We should set ->mode before check ->requests,
5956 * see the comment in make_all_cpus_request.
5958 smp_mb();
5960 local_irq_disable();
5962 if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
5963 || need_resched() || signal_pending(current)) {
5964 vcpu->mode = OUTSIDE_GUEST_MODE;
5965 smp_wmb();
5966 local_irq_enable();
5967 preempt_enable();
5968 r = 1;
5969 goto cancel_injection;
5972 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
5974 if (req_immediate_exit)
5975 smp_send_reschedule(vcpu->cpu);
5977 kvm_guest_enter();
5979 if (unlikely(vcpu->arch.switch_db_regs)) {
5980 set_debugreg(0, 7);
5981 set_debugreg(vcpu->arch.eff_db[0], 0);
5982 set_debugreg(vcpu->arch.eff_db[1], 1);
5983 set_debugreg(vcpu->arch.eff_db[2], 2);
5984 set_debugreg(vcpu->arch.eff_db[3], 3);
5987 trace_kvm_entry(vcpu->vcpu_id);
5988 kvm_x86_ops->run(vcpu);
5991 * If the guest has used debug registers, at least dr7
5992 * will be disabled while returning to the host.
5993 * If we don't have active breakpoints in the host, we don't
5994 * care about the messed up debug address registers. But if
5995 * we have some of them active, restore the old state.
5997 if (hw_breakpoint_active())
5998 hw_breakpoint_restore();
6000 vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu,
6001 native_read_tsc());
6003 vcpu->mode = OUTSIDE_GUEST_MODE;
6004 smp_wmb();
6006 /* Interrupt is enabled by handle_external_intr() */
6007 kvm_x86_ops->handle_external_intr(vcpu);
6009 ++vcpu->stat.exits;
6012 * We must have an instruction between local_irq_enable() and
6013 * kvm_guest_exit(), so the timer interrupt isn't delayed by
6014 * the interrupt shadow. The stat.exits increment will do nicely.
6015 * But we need to prevent reordering, hence this barrier():
6017 barrier();
6019 kvm_guest_exit();
6021 preempt_enable();
6023 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6026 * Profile KVM exit RIPs:
6028 if (unlikely(prof_on == KVM_PROFILING)) {
6029 unsigned long rip = kvm_rip_read(vcpu);
6030 profile_hit(KVM_PROFILING, (void *)rip);
6033 if (unlikely(vcpu->arch.tsc_always_catchup))
6034 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6036 if (vcpu->arch.apic_attention)
6037 kvm_lapic_sync_from_vapic(vcpu);
6039 r = kvm_x86_ops->handle_exit(vcpu);
6040 return r;
6042 cancel_injection:
6043 kvm_x86_ops->cancel_injection(vcpu);
6044 if (unlikely(vcpu->arch.apic_attention))
6045 kvm_lapic_sync_from_vapic(vcpu);
6046 out:
6047 return r;
6051 static int __vcpu_run(struct kvm_vcpu *vcpu)
6053 int r;
6054 struct kvm *kvm = vcpu->kvm;
6056 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6058 r = 1;
6059 while (r > 0) {
6060 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6061 !vcpu->arch.apf.halted)
6062 r = vcpu_enter_guest(vcpu);
6063 else {
6064 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6065 kvm_vcpu_block(vcpu);
6066 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6067 if (kvm_check_request(KVM_REQ_UNHALT, vcpu)) {
6068 kvm_apic_accept_events(vcpu);
6069 switch(vcpu->arch.mp_state) {
6070 case KVM_MP_STATE_HALTED:
6071 vcpu->arch.pv.pv_unhalted = false;
6072 vcpu->arch.mp_state =
6073 KVM_MP_STATE_RUNNABLE;
6074 case KVM_MP_STATE_RUNNABLE:
6075 vcpu->arch.apf.halted = false;
6076 break;
6077 case KVM_MP_STATE_INIT_RECEIVED:
6078 break;
6079 default:
6080 r = -EINTR;
6081 break;
6086 if (r <= 0)
6087 break;
6089 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
6090 if (kvm_cpu_has_pending_timer(vcpu))
6091 kvm_inject_pending_timer_irqs(vcpu);
6093 if (dm_request_for_irq_injection(vcpu)) {
6094 r = -EINTR;
6095 vcpu->run->exit_reason = KVM_EXIT_INTR;
6096 ++vcpu->stat.request_irq_exits;
6099 kvm_check_async_pf_completion(vcpu);
6101 if (signal_pending(current)) {
6102 r = -EINTR;
6103 vcpu->run->exit_reason = KVM_EXIT_INTR;
6104 ++vcpu->stat.signal_exits;
6106 if (need_resched()) {
6107 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6108 kvm_resched(vcpu);
6109 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6113 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6115 return r;
6118 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
6120 int r;
6121 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6122 r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
6123 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6124 if (r != EMULATE_DONE)
6125 return 0;
6126 return 1;
6129 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
6131 BUG_ON(!vcpu->arch.pio.count);
6133 return complete_emulated_io(vcpu);
6137 * Implements the following, as a state machine:
6139 * read:
6140 * for each fragment
6141 * for each mmio piece in the fragment
6142 * write gpa, len
6143 * exit
6144 * copy data
6145 * execute insn
6147 * write:
6148 * for each fragment
6149 * for each mmio piece in the fragment
6150 * write gpa, len
6151 * copy data
6152 * exit
6154 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
6156 struct kvm_run *run = vcpu->run;
6157 struct kvm_mmio_fragment *frag;
6158 unsigned len;
6160 BUG_ON(!vcpu->mmio_needed);
6162 /* Complete previous fragment */
6163 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
6164 len = min(8u, frag->len);
6165 if (!vcpu->mmio_is_write)
6166 memcpy(frag->data, run->mmio.data, len);
6168 if (frag->len <= 8) {
6169 /* Switch to the next fragment. */
6170 frag++;
6171 vcpu->mmio_cur_fragment++;
6172 } else {
6173 /* Go forward to the next mmio piece. */
6174 frag->data += len;
6175 frag->gpa += len;
6176 frag->len -= len;
6179 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
6180 vcpu->mmio_needed = 0;
6182 /* FIXME: return into emulator if single-stepping. */
6183 if (vcpu->mmio_is_write)
6184 return 1;
6185 vcpu->mmio_read_completed = 1;
6186 return complete_emulated_io(vcpu);
6189 run->exit_reason = KVM_EXIT_MMIO;
6190 run->mmio.phys_addr = frag->gpa;
6191 if (vcpu->mmio_is_write)
6192 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
6193 run->mmio.len = min(8u, frag->len);
6194 run->mmio.is_write = vcpu->mmio_is_write;
6195 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6196 return 0;
6200 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
6202 int r;
6203 sigset_t sigsaved;
6205 if (!tsk_used_math(current) && init_fpu(current))
6206 return -ENOMEM;
6208 if (vcpu->sigset_active)
6209 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
6211 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
6212 kvm_vcpu_block(vcpu);
6213 kvm_apic_accept_events(vcpu);
6214 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
6215 r = -EAGAIN;
6216 goto out;
6219 /* re-sync apic's tpr */
6220 if (!irqchip_in_kernel(vcpu->kvm)) {
6221 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
6222 r = -EINVAL;
6223 goto out;
6227 if (unlikely(vcpu->arch.complete_userspace_io)) {
6228 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
6229 vcpu->arch.complete_userspace_io = NULL;
6230 r = cui(vcpu);
6231 if (r <= 0)
6232 goto out;
6233 } else
6234 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
6236 r = __vcpu_run(vcpu);
6238 out:
6239 post_kvm_run_save(vcpu);
6240 if (vcpu->sigset_active)
6241 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
6243 return r;
6246 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6248 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
6250 * We are here if userspace calls get_regs() in the middle of
6251 * instruction emulation. Registers state needs to be copied
6252 * back from emulation context to vcpu. Userspace shouldn't do
6253 * that usually, but some bad designed PV devices (vmware
6254 * backdoor interface) need this to work
6256 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
6257 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6259 regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
6260 regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
6261 regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
6262 regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
6263 regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
6264 regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
6265 regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
6266 regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
6267 #ifdef CONFIG_X86_64
6268 regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
6269 regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
6270 regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
6271 regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
6272 regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
6273 regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
6274 regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
6275 regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
6276 #endif
6278 regs->rip = kvm_rip_read(vcpu);
6279 regs->rflags = kvm_get_rflags(vcpu);
6281 return 0;
6284 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6286 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
6287 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6289 kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
6290 kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
6291 kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
6292 kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
6293 kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
6294 kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
6295 kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
6296 kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
6297 #ifdef CONFIG_X86_64
6298 kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
6299 kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
6300 kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
6301 kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
6302 kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
6303 kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
6304 kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
6305 kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
6306 #endif
6308 kvm_rip_write(vcpu, regs->rip);
6309 kvm_set_rflags(vcpu, regs->rflags);
6311 vcpu->arch.exception.pending = false;
6313 kvm_make_request(KVM_REQ_EVENT, vcpu);
6315 return 0;
6318 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
6320 struct kvm_segment cs;
6322 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
6323 *db = cs.db;
6324 *l = cs.l;
6326 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
6328 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
6329 struct kvm_sregs *sregs)
6331 struct desc_ptr dt;
6333 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6334 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6335 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6336 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6337 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6338 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6340 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6341 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6343 kvm_x86_ops->get_idt(vcpu, &dt);
6344 sregs->idt.limit = dt.size;
6345 sregs->idt.base = dt.address;
6346 kvm_x86_ops->get_gdt(vcpu, &dt);
6347 sregs->gdt.limit = dt.size;
6348 sregs->gdt.base = dt.address;
6350 sregs->cr0 = kvm_read_cr0(vcpu);
6351 sregs->cr2 = vcpu->arch.cr2;
6352 sregs->cr3 = kvm_read_cr3(vcpu);
6353 sregs->cr4 = kvm_read_cr4(vcpu);
6354 sregs->cr8 = kvm_get_cr8(vcpu);
6355 sregs->efer = vcpu->arch.efer;
6356 sregs->apic_base = kvm_get_apic_base(vcpu);
6358 memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
6360 if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
6361 set_bit(vcpu->arch.interrupt.nr,
6362 (unsigned long *)sregs->interrupt_bitmap);
6364 return 0;
6367 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
6368 struct kvm_mp_state *mp_state)
6370 kvm_apic_accept_events(vcpu);
6371 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
6372 vcpu->arch.pv.pv_unhalted)
6373 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
6374 else
6375 mp_state->mp_state = vcpu->arch.mp_state;
6377 return 0;
6380 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
6381 struct kvm_mp_state *mp_state)
6383 if (!kvm_vcpu_has_lapic(vcpu) &&
6384 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
6385 return -EINVAL;
6387 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
6388 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
6389 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
6390 } else
6391 vcpu->arch.mp_state = mp_state->mp_state;
6392 kvm_make_request(KVM_REQ_EVENT, vcpu);
6393 return 0;
6396 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
6397 int reason, bool has_error_code, u32 error_code)
6399 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6400 int ret;
6402 init_emulate_ctxt(vcpu);
6404 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
6405 has_error_code, error_code);
6407 if (ret)
6408 return EMULATE_FAIL;
6410 kvm_rip_write(vcpu, ctxt->eip);
6411 kvm_set_rflags(vcpu, ctxt->eflags);
6412 kvm_make_request(KVM_REQ_EVENT, vcpu);
6413 return EMULATE_DONE;
6415 EXPORT_SYMBOL_GPL(kvm_task_switch);
6417 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
6418 struct kvm_sregs *sregs)
6420 int mmu_reset_needed = 0;
6421 int pending_vec, max_bits, idx;
6422 struct desc_ptr dt;
6424 if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
6425 return -EINVAL;
6427 dt.size = sregs->idt.limit;
6428 dt.address = sregs->idt.base;
6429 kvm_x86_ops->set_idt(vcpu, &dt);
6430 dt.size = sregs->gdt.limit;
6431 dt.address = sregs->gdt.base;
6432 kvm_x86_ops->set_gdt(vcpu, &dt);
6434 vcpu->arch.cr2 = sregs->cr2;
6435 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
6436 vcpu->arch.cr3 = sregs->cr3;
6437 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
6439 kvm_set_cr8(vcpu, sregs->cr8);
6441 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
6442 kvm_x86_ops->set_efer(vcpu, sregs->efer);
6443 kvm_set_apic_base(vcpu, sregs->apic_base);
6445 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
6446 kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
6447 vcpu->arch.cr0 = sregs->cr0;
6449 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
6450 kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
6451 if (sregs->cr4 & X86_CR4_OSXSAVE)
6452 kvm_update_cpuid(vcpu);
6454 idx = srcu_read_lock(&vcpu->kvm->srcu);
6455 if (!is_long_mode(vcpu) && is_pae(vcpu)) {
6456 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
6457 mmu_reset_needed = 1;
6459 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6461 if (mmu_reset_needed)
6462 kvm_mmu_reset_context(vcpu);
6464 max_bits = KVM_NR_INTERRUPTS;
6465 pending_vec = find_first_bit(
6466 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
6467 if (pending_vec < max_bits) {
6468 kvm_queue_interrupt(vcpu, pending_vec, false);
6469 pr_debug("Set back pending irq %d\n", pending_vec);
6472 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6473 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6474 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6475 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6476 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6477 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6479 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6480 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6482 update_cr8_intercept(vcpu);
6484 /* Older userspace won't unhalt the vcpu on reset. */
6485 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
6486 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
6487 !is_protmode(vcpu))
6488 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
6490 kvm_make_request(KVM_REQ_EVENT, vcpu);
6492 return 0;
6495 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
6496 struct kvm_guest_debug *dbg)
6498 unsigned long rflags;
6499 int i, r;
6501 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
6502 r = -EBUSY;
6503 if (vcpu->arch.exception.pending)
6504 goto out;
6505 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
6506 kvm_queue_exception(vcpu, DB_VECTOR);
6507 else
6508 kvm_queue_exception(vcpu, BP_VECTOR);
6512 * Read rflags as long as potentially injected trace flags are still
6513 * filtered out.
6515 rflags = kvm_get_rflags(vcpu);
6517 vcpu->guest_debug = dbg->control;
6518 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
6519 vcpu->guest_debug = 0;
6521 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
6522 for (i = 0; i < KVM_NR_DB_REGS; ++i)
6523 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
6524 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
6525 } else {
6526 for (i = 0; i < KVM_NR_DB_REGS; i++)
6527 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
6529 kvm_update_dr7(vcpu);
6531 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6532 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
6533 get_segment_base(vcpu, VCPU_SREG_CS);
6536 * Trigger an rflags update that will inject or remove the trace
6537 * flags.
6539 kvm_set_rflags(vcpu, rflags);
6541 kvm_x86_ops->update_db_bp_intercept(vcpu);
6543 r = 0;
6545 out:
6547 return r;
6551 * Translate a guest virtual address to a guest physical address.
6553 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
6554 struct kvm_translation *tr)
6556 unsigned long vaddr = tr->linear_address;
6557 gpa_t gpa;
6558 int idx;
6560 idx = srcu_read_lock(&vcpu->kvm->srcu);
6561 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
6562 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6563 tr->physical_address = gpa;
6564 tr->valid = gpa != UNMAPPED_GVA;
6565 tr->writeable = 1;
6566 tr->usermode = 0;
6568 return 0;
6571 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
6573 struct i387_fxsave_struct *fxsave =
6574 &vcpu->arch.guest_fpu.state->fxsave;
6576 memcpy(fpu->fpr, fxsave->st_space, 128);
6577 fpu->fcw = fxsave->cwd;
6578 fpu->fsw = fxsave->swd;
6579 fpu->ftwx = fxsave->twd;
6580 fpu->last_opcode = fxsave->fop;
6581 fpu->last_ip = fxsave->rip;
6582 fpu->last_dp = fxsave->rdp;
6583 memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
6585 return 0;
6588 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
6590 struct i387_fxsave_struct *fxsave =
6591 &vcpu->arch.guest_fpu.state->fxsave;
6593 memcpy(fxsave->st_space, fpu->fpr, 128);
6594 fxsave->cwd = fpu->fcw;
6595 fxsave->swd = fpu->fsw;
6596 fxsave->twd = fpu->ftwx;
6597 fxsave->fop = fpu->last_opcode;
6598 fxsave->rip = fpu->last_ip;
6599 fxsave->rdp = fpu->last_dp;
6600 memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
6602 return 0;
6605 int fx_init(struct kvm_vcpu *vcpu)
6607 int err;
6609 err = fpu_alloc(&vcpu->arch.guest_fpu);
6610 if (err)
6611 return err;
6613 fpu_finit(&vcpu->arch.guest_fpu);
6616 * Ensure guest xcr0 is valid for loading
6618 vcpu->arch.xcr0 = XSTATE_FP;
6620 vcpu->arch.cr0 |= X86_CR0_ET;
6622 return 0;
6624 EXPORT_SYMBOL_GPL(fx_init);
6626 static void fx_free(struct kvm_vcpu *vcpu)
6628 fpu_free(&vcpu->arch.guest_fpu);
6631 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
6633 if (vcpu->guest_fpu_loaded)
6634 return;
6637 * Restore all possible states in the guest,
6638 * and assume host would use all available bits.
6639 * Guest xcr0 would be loaded later.
6641 kvm_put_guest_xcr0(vcpu);
6642 vcpu->guest_fpu_loaded = 1;
6643 __kernel_fpu_begin();
6644 fpu_restore_checking(&vcpu->arch.guest_fpu);
6645 trace_kvm_fpu(1);
6648 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
6650 kvm_put_guest_xcr0(vcpu);
6652 if (!vcpu->guest_fpu_loaded)
6653 return;
6655 vcpu->guest_fpu_loaded = 0;
6656 fpu_save_init(&vcpu->arch.guest_fpu);
6657 __kernel_fpu_end();
6658 ++vcpu->stat.fpu_reload;
6659 kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
6660 trace_kvm_fpu(0);
6663 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
6665 kvmclock_reset(vcpu);
6667 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
6668 fx_free(vcpu);
6669 kvm_x86_ops->vcpu_free(vcpu);
6672 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
6673 unsigned int id)
6675 if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
6676 printk_once(KERN_WARNING
6677 "kvm: SMP vm created on host with unstable TSC; "
6678 "guest TSC will not be reliable\n");
6679 return kvm_x86_ops->vcpu_create(kvm, id);
6682 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
6684 int r;
6686 vcpu->arch.mtrr_state.have_fixed = 1;
6687 r = vcpu_load(vcpu);
6688 if (r)
6689 return r;
6690 kvm_vcpu_reset(vcpu);
6691 r = kvm_mmu_setup(vcpu);
6692 vcpu_put(vcpu);
6694 return r;
6697 int kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
6699 int r;
6700 struct msr_data msr;
6702 r = vcpu_load(vcpu);
6703 if (r)
6704 return r;
6705 msr.data = 0x0;
6706 msr.index = MSR_IA32_TSC;
6707 msr.host_initiated = true;
6708 kvm_write_tsc(vcpu, &msr);
6709 vcpu_put(vcpu);
6711 return r;
6714 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
6716 int r;
6717 vcpu->arch.apf.msr_val = 0;
6719 r = vcpu_load(vcpu);
6720 BUG_ON(r);
6721 kvm_mmu_unload(vcpu);
6722 vcpu_put(vcpu);
6724 fx_free(vcpu);
6725 kvm_x86_ops->vcpu_free(vcpu);
6728 void kvm_vcpu_reset(struct kvm_vcpu *vcpu)
6730 atomic_set(&vcpu->arch.nmi_queued, 0);
6731 vcpu->arch.nmi_pending = 0;
6732 vcpu->arch.nmi_injected = false;
6734 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
6735 vcpu->arch.dr6 = DR6_FIXED_1;
6736 vcpu->arch.dr7 = DR7_FIXED_1;
6737 kvm_update_dr7(vcpu);
6739 kvm_make_request(KVM_REQ_EVENT, vcpu);
6740 vcpu->arch.apf.msr_val = 0;
6741 vcpu->arch.st.msr_val = 0;
6743 kvmclock_reset(vcpu);
6745 kvm_clear_async_pf_completion_queue(vcpu);
6746 kvm_async_pf_hash_reset(vcpu);
6747 vcpu->arch.apf.halted = false;
6749 kvm_pmu_reset(vcpu);
6751 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
6752 vcpu->arch.regs_avail = ~0;
6753 vcpu->arch.regs_dirty = ~0;
6755 kvm_x86_ops->vcpu_reset(vcpu);
6758 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, unsigned int vector)
6760 struct kvm_segment cs;
6762 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
6763 cs.selector = vector << 8;
6764 cs.base = vector << 12;
6765 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
6766 kvm_rip_write(vcpu, 0);
6769 int kvm_arch_hardware_enable(void *garbage)
6771 struct kvm *kvm;
6772 struct kvm_vcpu *vcpu;
6773 int i;
6774 int ret;
6775 u64 local_tsc;
6776 u64 max_tsc = 0;
6777 bool stable, backwards_tsc = false;
6779 kvm_shared_msr_cpu_online();
6780 ret = kvm_x86_ops->hardware_enable(garbage);
6781 if (ret != 0)
6782 return ret;
6784 local_tsc = native_read_tsc();
6785 stable = !check_tsc_unstable();
6786 list_for_each_entry(kvm, &vm_list, vm_list) {
6787 kvm_for_each_vcpu(i, vcpu, kvm) {
6788 if (!stable && vcpu->cpu == smp_processor_id())
6789 set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
6790 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
6791 backwards_tsc = true;
6792 if (vcpu->arch.last_host_tsc > max_tsc)
6793 max_tsc = vcpu->arch.last_host_tsc;
6799 * Sometimes, even reliable TSCs go backwards. This happens on
6800 * platforms that reset TSC during suspend or hibernate actions, but
6801 * maintain synchronization. We must compensate. Fortunately, we can
6802 * detect that condition here, which happens early in CPU bringup,
6803 * before any KVM threads can be running. Unfortunately, we can't
6804 * bring the TSCs fully up to date with real time, as we aren't yet far
6805 * enough into CPU bringup that we know how much real time has actually
6806 * elapsed; our helper function, get_kernel_ns() will be using boot
6807 * variables that haven't been updated yet.
6809 * So we simply find the maximum observed TSC above, then record the
6810 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
6811 * the adjustment will be applied. Note that we accumulate
6812 * adjustments, in case multiple suspend cycles happen before some VCPU
6813 * gets a chance to run again. In the event that no KVM threads get a
6814 * chance to run, we will miss the entire elapsed period, as we'll have
6815 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
6816 * loose cycle time. This isn't too big a deal, since the loss will be
6817 * uniform across all VCPUs (not to mention the scenario is extremely
6818 * unlikely). It is possible that a second hibernate recovery happens
6819 * much faster than a first, causing the observed TSC here to be
6820 * smaller; this would require additional padding adjustment, which is
6821 * why we set last_host_tsc to the local tsc observed here.
6823 * N.B. - this code below runs only on platforms with reliable TSC,
6824 * as that is the only way backwards_tsc is set above. Also note
6825 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
6826 * have the same delta_cyc adjustment applied if backwards_tsc
6827 * is detected. Note further, this adjustment is only done once,
6828 * as we reset last_host_tsc on all VCPUs to stop this from being
6829 * called multiple times (one for each physical CPU bringup).
6831 * Platforms with unreliable TSCs don't have to deal with this, they
6832 * will be compensated by the logic in vcpu_load, which sets the TSC to
6833 * catchup mode. This will catchup all VCPUs to real time, but cannot
6834 * guarantee that they stay in perfect synchronization.
6836 if (backwards_tsc) {
6837 u64 delta_cyc = max_tsc - local_tsc;
6838 list_for_each_entry(kvm, &vm_list, vm_list) {
6839 kvm_for_each_vcpu(i, vcpu, kvm) {
6840 vcpu->arch.tsc_offset_adjustment += delta_cyc;
6841 vcpu->arch.last_host_tsc = local_tsc;
6842 set_bit(KVM_REQ_MASTERCLOCK_UPDATE,
6843 &vcpu->requests);
6847 * We have to disable TSC offset matching.. if you were
6848 * booting a VM while issuing an S4 host suspend....
6849 * you may have some problem. Solving this issue is
6850 * left as an exercise to the reader.
6852 kvm->arch.last_tsc_nsec = 0;
6853 kvm->arch.last_tsc_write = 0;
6857 return 0;
6860 void kvm_arch_hardware_disable(void *garbage)
6862 kvm_x86_ops->hardware_disable(garbage);
6863 drop_user_return_notifiers(garbage);
6866 int kvm_arch_hardware_setup(void)
6868 return kvm_x86_ops->hardware_setup();
6871 void kvm_arch_hardware_unsetup(void)
6873 kvm_x86_ops->hardware_unsetup();
6876 void kvm_arch_check_processor_compat(void *rtn)
6878 kvm_x86_ops->check_processor_compatibility(rtn);
6881 bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
6883 return irqchip_in_kernel(vcpu->kvm) == (vcpu->arch.apic != NULL);
6886 struct static_key kvm_no_apic_vcpu __read_mostly;
6888 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
6890 struct page *page;
6891 struct kvm *kvm;
6892 int r;
6894 BUG_ON(vcpu->kvm == NULL);
6895 kvm = vcpu->kvm;
6897 vcpu->arch.pv.pv_unhalted = false;
6898 vcpu->arch.emulate_ctxt.ops = &emulate_ops;
6899 if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
6900 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
6901 else
6902 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
6904 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
6905 if (!page) {
6906 r = -ENOMEM;
6907 goto fail;
6909 vcpu->arch.pio_data = page_address(page);
6911 kvm_set_tsc_khz(vcpu, max_tsc_khz);
6913 r = kvm_mmu_create(vcpu);
6914 if (r < 0)
6915 goto fail_free_pio_data;
6917 if (irqchip_in_kernel(kvm)) {
6918 r = kvm_create_lapic(vcpu);
6919 if (r < 0)
6920 goto fail_mmu_destroy;
6921 } else
6922 static_key_slow_inc(&kvm_no_apic_vcpu);
6924 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
6925 GFP_KERNEL);
6926 if (!vcpu->arch.mce_banks) {
6927 r = -ENOMEM;
6928 goto fail_free_lapic;
6930 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
6932 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
6933 r = -ENOMEM;
6934 goto fail_free_mce_banks;
6937 r = fx_init(vcpu);
6938 if (r)
6939 goto fail_free_wbinvd_dirty_mask;
6941 vcpu->arch.ia32_tsc_adjust_msr = 0x0;
6942 vcpu->arch.pv_time_enabled = false;
6943 kvm_async_pf_hash_reset(vcpu);
6944 kvm_pmu_init(vcpu);
6946 return 0;
6947 fail_free_wbinvd_dirty_mask:
6948 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
6949 fail_free_mce_banks:
6950 kfree(vcpu->arch.mce_banks);
6951 fail_free_lapic:
6952 kvm_free_lapic(vcpu);
6953 fail_mmu_destroy:
6954 kvm_mmu_destroy(vcpu);
6955 fail_free_pio_data:
6956 free_page((unsigned long)vcpu->arch.pio_data);
6957 fail:
6958 return r;
6961 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
6963 int idx;
6965 kvm_pmu_destroy(vcpu);
6966 kfree(vcpu->arch.mce_banks);
6967 kvm_free_lapic(vcpu);
6968 idx = srcu_read_lock(&vcpu->kvm->srcu);
6969 kvm_mmu_destroy(vcpu);
6970 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6971 free_page((unsigned long)vcpu->arch.pio_data);
6972 if (!irqchip_in_kernel(vcpu->kvm))
6973 static_key_slow_dec(&kvm_no_apic_vcpu);
6976 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
6978 if (type)
6979 return -EINVAL;
6981 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6982 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
6983 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
6985 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
6986 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
6987 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
6988 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
6989 &kvm->arch.irq_sources_bitmap);
6991 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
6992 mutex_init(&kvm->arch.apic_map_lock);
6993 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
6995 pvclock_update_vm_gtod_copy(kvm);
6997 return 0;
7000 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
7002 int r;
7003 r = vcpu_load(vcpu);
7004 BUG_ON(r);
7005 kvm_mmu_unload(vcpu);
7006 vcpu_put(vcpu);
7009 static void kvm_free_vcpus(struct kvm *kvm)
7011 unsigned int i;
7012 struct kvm_vcpu *vcpu;
7015 * Unpin any mmu pages first.
7017 kvm_for_each_vcpu(i, vcpu, kvm) {
7018 kvm_clear_async_pf_completion_queue(vcpu);
7019 kvm_unload_vcpu_mmu(vcpu);
7021 kvm_for_each_vcpu(i, vcpu, kvm)
7022 kvm_arch_vcpu_free(vcpu);
7024 mutex_lock(&kvm->lock);
7025 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
7026 kvm->vcpus[i] = NULL;
7028 atomic_set(&kvm->online_vcpus, 0);
7029 mutex_unlock(&kvm->lock);
7032 void kvm_arch_sync_events(struct kvm *kvm)
7034 kvm_free_all_assigned_devices(kvm);
7035 kvm_free_pit(kvm);
7038 void kvm_arch_destroy_vm(struct kvm *kvm)
7040 if (current->mm == kvm->mm) {
7042 * Free memory regions allocated on behalf of userspace,
7043 * unless the the memory map has changed due to process exit
7044 * or fd copying.
7046 struct kvm_userspace_memory_region mem;
7047 memset(&mem, 0, sizeof(mem));
7048 mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
7049 kvm_set_memory_region(kvm, &mem);
7051 mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
7052 kvm_set_memory_region(kvm, &mem);
7054 mem.slot = TSS_PRIVATE_MEMSLOT;
7055 kvm_set_memory_region(kvm, &mem);
7057 kvm_iommu_unmap_guest(kvm);
7058 kfree(kvm->arch.vpic);
7059 kfree(kvm->arch.vioapic);
7060 kvm_free_vcpus(kvm);
7061 if (kvm->arch.apic_access_page)
7062 put_page(kvm->arch.apic_access_page);
7063 if (kvm->arch.ept_identity_pagetable)
7064 put_page(kvm->arch.ept_identity_pagetable);
7065 kfree(rcu_dereference_check(kvm->arch.apic_map, 1));
7068 void kvm_arch_free_memslot(struct kvm_memory_slot *free,
7069 struct kvm_memory_slot *dont)
7071 int i;
7073 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7074 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
7075 kvm_kvfree(free->arch.rmap[i]);
7076 free->arch.rmap[i] = NULL;
7078 if (i == 0)
7079 continue;
7081 if (!dont || free->arch.lpage_info[i - 1] !=
7082 dont->arch.lpage_info[i - 1]) {
7083 kvm_kvfree(free->arch.lpage_info[i - 1]);
7084 free->arch.lpage_info[i - 1] = NULL;
7089 int kvm_arch_create_memslot(struct kvm_memory_slot *slot, unsigned long npages)
7091 int i;
7093 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7094 unsigned long ugfn;
7095 int lpages;
7096 int level = i + 1;
7098 lpages = gfn_to_index(slot->base_gfn + npages - 1,
7099 slot->base_gfn, level) + 1;
7101 slot->arch.rmap[i] =
7102 kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
7103 if (!slot->arch.rmap[i])
7104 goto out_free;
7105 if (i == 0)
7106 continue;
7108 slot->arch.lpage_info[i - 1] = kvm_kvzalloc(lpages *
7109 sizeof(*slot->arch.lpage_info[i - 1]));
7110 if (!slot->arch.lpage_info[i - 1])
7111 goto out_free;
7113 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
7114 slot->arch.lpage_info[i - 1][0].write_count = 1;
7115 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
7116 slot->arch.lpage_info[i - 1][lpages - 1].write_count = 1;
7117 ugfn = slot->userspace_addr >> PAGE_SHIFT;
7119 * If the gfn and userspace address are not aligned wrt each
7120 * other, or if explicitly asked to, disable large page
7121 * support for this slot
7123 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
7124 !kvm_largepages_enabled()) {
7125 unsigned long j;
7127 for (j = 0; j < lpages; ++j)
7128 slot->arch.lpage_info[i - 1][j].write_count = 1;
7132 return 0;
7134 out_free:
7135 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7136 kvm_kvfree(slot->arch.rmap[i]);
7137 slot->arch.rmap[i] = NULL;
7138 if (i == 0)
7139 continue;
7141 kvm_kvfree(slot->arch.lpage_info[i - 1]);
7142 slot->arch.lpage_info[i - 1] = NULL;
7144 return -ENOMEM;
7147 void kvm_arch_memslots_updated(struct kvm *kvm)
7150 * memslots->generation has been incremented.
7151 * mmio generation may have reached its maximum value.
7153 kvm_mmu_invalidate_mmio_sptes(kvm);
7156 int kvm_arch_prepare_memory_region(struct kvm *kvm,
7157 struct kvm_memory_slot *memslot,
7158 struct kvm_userspace_memory_region *mem,
7159 enum kvm_mr_change change)
7162 * Only private memory slots need to be mapped here since
7163 * KVM_SET_MEMORY_REGION ioctl is no longer supported.
7165 if ((memslot->id >= KVM_USER_MEM_SLOTS) && (change == KVM_MR_CREATE)) {
7166 unsigned long userspace_addr;
7169 * MAP_SHARED to prevent internal slot pages from being moved
7170 * by fork()/COW.
7172 userspace_addr = vm_mmap(NULL, 0, memslot->npages * PAGE_SIZE,
7173 PROT_READ | PROT_WRITE,
7174 MAP_SHARED | MAP_ANONYMOUS, 0);
7176 if (IS_ERR((void *)userspace_addr))
7177 return PTR_ERR((void *)userspace_addr);
7179 memslot->userspace_addr = userspace_addr;
7182 return 0;
7185 void kvm_arch_commit_memory_region(struct kvm *kvm,
7186 struct kvm_userspace_memory_region *mem,
7187 const struct kvm_memory_slot *old,
7188 enum kvm_mr_change change)
7191 int nr_mmu_pages = 0;
7193 if ((mem->slot >= KVM_USER_MEM_SLOTS) && (change == KVM_MR_DELETE)) {
7194 int ret;
7196 ret = vm_munmap(old->userspace_addr,
7197 old->npages * PAGE_SIZE);
7198 if (ret < 0)
7199 printk(KERN_WARNING
7200 "kvm_vm_ioctl_set_memory_region: "
7201 "failed to munmap memory\n");
7204 if (!kvm->arch.n_requested_mmu_pages)
7205 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
7207 if (nr_mmu_pages)
7208 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
7210 * Write protect all pages for dirty logging.
7211 * Existing largepage mappings are destroyed here and new ones will
7212 * not be created until the end of the logging.
7214 if ((change != KVM_MR_DELETE) && (mem->flags & KVM_MEM_LOG_DIRTY_PAGES))
7215 kvm_mmu_slot_remove_write_access(kvm, mem->slot);
7218 void kvm_arch_flush_shadow_all(struct kvm *kvm)
7220 kvm_mmu_invalidate_zap_all_pages(kvm);
7223 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
7224 struct kvm_memory_slot *slot)
7226 kvm_mmu_invalidate_zap_all_pages(kvm);
7229 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
7231 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
7232 !vcpu->arch.apf.halted)
7233 || !list_empty_careful(&vcpu->async_pf.done)
7234 || kvm_apic_has_events(vcpu)
7235 || vcpu->arch.pv.pv_unhalted
7236 || atomic_read(&vcpu->arch.nmi_queued) ||
7237 (kvm_arch_interrupt_allowed(vcpu) &&
7238 kvm_cpu_has_interrupt(vcpu));
7241 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
7243 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
7246 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
7248 return kvm_x86_ops->interrupt_allowed(vcpu);
7251 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
7253 unsigned long current_rip = kvm_rip_read(vcpu) +
7254 get_segment_base(vcpu, VCPU_SREG_CS);
7256 return current_rip == linear_rip;
7258 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
7260 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
7262 unsigned long rflags;
7264 rflags = kvm_x86_ops->get_rflags(vcpu);
7265 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7266 rflags &= ~X86_EFLAGS_TF;
7267 return rflags;
7269 EXPORT_SYMBOL_GPL(kvm_get_rflags);
7271 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
7273 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
7274 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
7275 rflags |= X86_EFLAGS_TF;
7276 kvm_x86_ops->set_rflags(vcpu, rflags);
7277 kvm_make_request(KVM_REQ_EVENT, vcpu);
7279 EXPORT_SYMBOL_GPL(kvm_set_rflags);
7281 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
7283 int r;
7285 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
7286 is_error_page(work->page))
7287 return;
7289 r = kvm_mmu_reload(vcpu);
7290 if (unlikely(r))
7291 return;
7293 if (!vcpu->arch.mmu.direct_map &&
7294 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
7295 return;
7297 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
7300 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
7302 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
7305 static inline u32 kvm_async_pf_next_probe(u32 key)
7307 return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
7310 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
7312 u32 key = kvm_async_pf_hash_fn(gfn);
7314 while (vcpu->arch.apf.gfns[key] != ~0)
7315 key = kvm_async_pf_next_probe(key);
7317 vcpu->arch.apf.gfns[key] = gfn;
7320 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
7322 int i;
7323 u32 key = kvm_async_pf_hash_fn(gfn);
7325 for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
7326 (vcpu->arch.apf.gfns[key] != gfn &&
7327 vcpu->arch.apf.gfns[key] != ~0); i++)
7328 key = kvm_async_pf_next_probe(key);
7330 return key;
7333 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
7335 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
7338 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
7340 u32 i, j, k;
7342 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
7343 while (true) {
7344 vcpu->arch.apf.gfns[i] = ~0;
7345 do {
7346 j = kvm_async_pf_next_probe(j);
7347 if (vcpu->arch.apf.gfns[j] == ~0)
7348 return;
7349 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
7351 * k lies cyclically in ]i,j]
7352 * | i.k.j |
7353 * |....j i.k.| or |.k..j i...|
7355 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
7356 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
7357 i = j;
7361 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
7364 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
7365 sizeof(val));
7368 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
7369 struct kvm_async_pf *work)
7371 struct x86_exception fault;
7373 trace_kvm_async_pf_not_present(work->arch.token, work->gva);
7374 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
7376 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
7377 (vcpu->arch.apf.send_user_only &&
7378 kvm_x86_ops->get_cpl(vcpu) == 0))
7379 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
7380 else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
7381 fault.vector = PF_VECTOR;
7382 fault.error_code_valid = true;
7383 fault.error_code = 0;
7384 fault.nested_page_fault = false;
7385 fault.address = work->arch.token;
7386 kvm_inject_page_fault(vcpu, &fault);
7390 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
7391 struct kvm_async_pf *work)
7393 struct x86_exception fault;
7395 trace_kvm_async_pf_ready(work->arch.token, work->gva);
7396 if (is_error_page(work->page))
7397 work->arch.token = ~0; /* broadcast wakeup */
7398 else
7399 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
7401 if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
7402 !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
7403 fault.vector = PF_VECTOR;
7404 fault.error_code_valid = true;
7405 fault.error_code = 0;
7406 fault.nested_page_fault = false;
7407 fault.address = work->arch.token;
7408 kvm_inject_page_fault(vcpu, &fault);
7410 vcpu->arch.apf.halted = false;
7411 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7414 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
7416 if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
7417 return true;
7418 else
7419 return !kvm_event_needs_reinjection(vcpu) &&
7420 kvm_x86_ops->interrupt_allowed(vcpu);
7423 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
7424 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
7425 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
7426 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
7427 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
7428 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
7429 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
7430 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
7431 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
7432 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
7433 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
7434 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
7435 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);