Merge branch 'x86-fpu-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git...
[linux-flexiantxendom0-3.2.10.git] / arch / x86 / kvm / x86.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * derived from drivers/kvm/kvm_main.c
5  *
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.
10  *
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>
16  *
17  * This work is licensed under the terms of the GNU GPL, version 2.  See
18  * the COPYING file in the top-level directory.
19  *
20  */
21
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"
30
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 <trace/events/kvm.h>
50
51 #define CREATE_TRACE_POINTS
52 #include "trace.h"
53
54 #include <asm/debugreg.h>
55 #include <asm/msr.h>
56 #include <asm/desc.h>
57 #include <asm/mtrr.h>
58 #include <asm/mce.h>
59 #include <asm/i387.h>
60 #include <asm/fpu-internal.h> /* Ugh! */
61 #include <asm/xcr.h>
62 #include <asm/pvclock.h>
63 #include <asm/div64.h>
64
65 #define MAX_IO_MSRS 256
66 #define KVM_MAX_MCE_BANKS 32
67 #define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
68
69 #define emul_to_vcpu(ctxt) \
70         container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
71
72 /* EFER defaults:
73  * - enable syscall per default because its emulated by KVM
74  * - enable LME and LMA per default on 64 bit KVM
75  */
76 #ifdef CONFIG_X86_64
77 static
78 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
79 #else
80 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
81 #endif
82
83 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
84 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
85
86 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
87 static void process_nmi(struct kvm_vcpu *vcpu);
88
89 struct kvm_x86_ops *kvm_x86_ops;
90 EXPORT_SYMBOL_GPL(kvm_x86_ops);
91
92 static bool ignore_msrs = 0;
93 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
94
95 bool kvm_has_tsc_control;
96 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
97 u32  kvm_max_guest_tsc_khz;
98 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
99
100 #define KVM_NR_SHARED_MSRS 16
101
102 struct kvm_shared_msrs_global {
103         int nr;
104         u32 msrs[KVM_NR_SHARED_MSRS];
105 };
106
107 struct kvm_shared_msrs {
108         struct user_return_notifier urn;
109         bool registered;
110         struct kvm_shared_msr_values {
111                 u64 host;
112                 u64 curr;
113         } values[KVM_NR_SHARED_MSRS];
114 };
115
116 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
117 static DEFINE_PER_CPU(struct kvm_shared_msrs, shared_msrs);
118
119 struct kvm_stats_debugfs_item debugfs_entries[] = {
120         { "pf_fixed", VCPU_STAT(pf_fixed) },
121         { "pf_guest", VCPU_STAT(pf_guest) },
122         { "tlb_flush", VCPU_STAT(tlb_flush) },
123         { "invlpg", VCPU_STAT(invlpg) },
124         { "exits", VCPU_STAT(exits) },
125         { "io_exits", VCPU_STAT(io_exits) },
126         { "mmio_exits", VCPU_STAT(mmio_exits) },
127         { "signal_exits", VCPU_STAT(signal_exits) },
128         { "irq_window", VCPU_STAT(irq_window_exits) },
129         { "nmi_window", VCPU_STAT(nmi_window_exits) },
130         { "halt_exits", VCPU_STAT(halt_exits) },
131         { "halt_wakeup", VCPU_STAT(halt_wakeup) },
132         { "hypercalls", VCPU_STAT(hypercalls) },
133         { "request_irq", VCPU_STAT(request_irq_exits) },
134         { "irq_exits", VCPU_STAT(irq_exits) },
135         { "host_state_reload", VCPU_STAT(host_state_reload) },
136         { "efer_reload", VCPU_STAT(efer_reload) },
137         { "fpu_reload", VCPU_STAT(fpu_reload) },
138         { "insn_emulation", VCPU_STAT(insn_emulation) },
139         { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
140         { "irq_injections", VCPU_STAT(irq_injections) },
141         { "nmi_injections", VCPU_STAT(nmi_injections) },
142         { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
143         { "mmu_pte_write", VM_STAT(mmu_pte_write) },
144         { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
145         { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
146         { "mmu_flooded", VM_STAT(mmu_flooded) },
147         { "mmu_recycled", VM_STAT(mmu_recycled) },
148         { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
149         { "mmu_unsync", VM_STAT(mmu_unsync) },
150         { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
151         { "largepages", VM_STAT(lpages) },
152         { NULL }
153 };
154
155 u64 __read_mostly host_xcr0;
156
157 int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
158
159 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
160 {
161         int i;
162         for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
163                 vcpu->arch.apf.gfns[i] = ~0;
164 }
165
166 static void kvm_on_user_return(struct user_return_notifier *urn)
167 {
168         unsigned slot;
169         struct kvm_shared_msrs *locals
170                 = container_of(urn, struct kvm_shared_msrs, urn);
171         struct kvm_shared_msr_values *values;
172
173         for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
174                 values = &locals->values[slot];
175                 if (values->host != values->curr) {
176                         wrmsrl(shared_msrs_global.msrs[slot], values->host);
177                         values->curr = values->host;
178                 }
179         }
180         locals->registered = false;
181         user_return_notifier_unregister(urn);
182 }
183
184 static void shared_msr_update(unsigned slot, u32 msr)
185 {
186         struct kvm_shared_msrs *smsr;
187         u64 value;
188
189         smsr = &__get_cpu_var(shared_msrs);
190         /* only read, and nobody should modify it at this time,
191          * so don't need lock */
192         if (slot >= shared_msrs_global.nr) {
193                 printk(KERN_ERR "kvm: invalid MSR slot!");
194                 return;
195         }
196         rdmsrl_safe(msr, &value);
197         smsr->values[slot].host = value;
198         smsr->values[slot].curr = value;
199 }
200
201 void kvm_define_shared_msr(unsigned slot, u32 msr)
202 {
203         if (slot >= shared_msrs_global.nr)
204                 shared_msrs_global.nr = slot + 1;
205         shared_msrs_global.msrs[slot] = msr;
206         /* we need ensured the shared_msr_global have been updated */
207         smp_wmb();
208 }
209 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
210
211 static void kvm_shared_msr_cpu_online(void)
212 {
213         unsigned i;
214
215         for (i = 0; i < shared_msrs_global.nr; ++i)
216                 shared_msr_update(i, shared_msrs_global.msrs[i]);
217 }
218
219 void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
220 {
221         struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
222
223         if (((value ^ smsr->values[slot].curr) & mask) == 0)
224                 return;
225         smsr->values[slot].curr = value;
226         wrmsrl(shared_msrs_global.msrs[slot], value);
227         if (!smsr->registered) {
228                 smsr->urn.on_user_return = kvm_on_user_return;
229                 user_return_notifier_register(&smsr->urn);
230                 smsr->registered = true;
231         }
232 }
233 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
234
235 static void drop_user_return_notifiers(void *ignore)
236 {
237         struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
238
239         if (smsr->registered)
240                 kvm_on_user_return(&smsr->urn);
241 }
242
243 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
244 {
245         if (irqchip_in_kernel(vcpu->kvm))
246                 return vcpu->arch.apic_base;
247         else
248                 return vcpu->arch.apic_base;
249 }
250 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
251
252 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
253 {
254         /* TODO: reserve bits check */
255         if (irqchip_in_kernel(vcpu->kvm))
256                 kvm_lapic_set_base(vcpu, data);
257         else
258                 vcpu->arch.apic_base = data;
259 }
260 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
261
262 #define EXCPT_BENIGN            0
263 #define EXCPT_CONTRIBUTORY      1
264 #define EXCPT_PF                2
265
266 static int exception_class(int vector)
267 {
268         switch (vector) {
269         case PF_VECTOR:
270                 return EXCPT_PF;
271         case DE_VECTOR:
272         case TS_VECTOR:
273         case NP_VECTOR:
274         case SS_VECTOR:
275         case GP_VECTOR:
276                 return EXCPT_CONTRIBUTORY;
277         default:
278                 break;
279         }
280         return EXCPT_BENIGN;
281 }
282
283 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
284                 unsigned nr, bool has_error, u32 error_code,
285                 bool reinject)
286 {
287         u32 prev_nr;
288         int class1, class2;
289
290         kvm_make_request(KVM_REQ_EVENT, vcpu);
291
292         if (!vcpu->arch.exception.pending) {
293         queue:
294                 vcpu->arch.exception.pending = true;
295                 vcpu->arch.exception.has_error_code = has_error;
296                 vcpu->arch.exception.nr = nr;
297                 vcpu->arch.exception.error_code = error_code;
298                 vcpu->arch.exception.reinject = reinject;
299                 return;
300         }
301
302         /* to check exception */
303         prev_nr = vcpu->arch.exception.nr;
304         if (prev_nr == DF_VECTOR) {
305                 /* triple fault -> shutdown */
306                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
307                 return;
308         }
309         class1 = exception_class(prev_nr);
310         class2 = exception_class(nr);
311         if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
312                 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
313                 /* generate double fault per SDM Table 5-5 */
314                 vcpu->arch.exception.pending = true;
315                 vcpu->arch.exception.has_error_code = true;
316                 vcpu->arch.exception.nr = DF_VECTOR;
317                 vcpu->arch.exception.error_code = 0;
318         } else
319                 /* replace previous exception with a new one in a hope
320                    that instruction re-execution will regenerate lost
321                    exception */
322                 goto queue;
323 }
324
325 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
326 {
327         kvm_multiple_exception(vcpu, nr, false, 0, false);
328 }
329 EXPORT_SYMBOL_GPL(kvm_queue_exception);
330
331 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
332 {
333         kvm_multiple_exception(vcpu, nr, false, 0, true);
334 }
335 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
336
337 void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
338 {
339         if (err)
340                 kvm_inject_gp(vcpu, 0);
341         else
342                 kvm_x86_ops->skip_emulated_instruction(vcpu);
343 }
344 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
345
346 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
347 {
348         ++vcpu->stat.pf_guest;
349         vcpu->arch.cr2 = fault->address;
350         kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
351 }
352 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
353
354 void kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
355 {
356         if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
357                 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
358         else
359                 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
360 }
361
362 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
363 {
364         atomic_inc(&vcpu->arch.nmi_queued);
365         kvm_make_request(KVM_REQ_NMI, vcpu);
366 }
367 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
368
369 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
370 {
371         kvm_multiple_exception(vcpu, nr, true, error_code, false);
372 }
373 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
374
375 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
376 {
377         kvm_multiple_exception(vcpu, nr, true, error_code, true);
378 }
379 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
380
381 /*
382  * Checks if cpl <= required_cpl; if true, return true.  Otherwise queue
383  * a #GP and return false.
384  */
385 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
386 {
387         if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
388                 return true;
389         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
390         return false;
391 }
392 EXPORT_SYMBOL_GPL(kvm_require_cpl);
393
394 /*
395  * This function will be used to read from the physical memory of the currently
396  * running guest. The difference to kvm_read_guest_page is that this function
397  * can read from guest physical or from the guest's guest physical memory.
398  */
399 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
400                             gfn_t ngfn, void *data, int offset, int len,
401                             u32 access)
402 {
403         gfn_t real_gfn;
404         gpa_t ngpa;
405
406         ngpa     = gfn_to_gpa(ngfn);
407         real_gfn = mmu->translate_gpa(vcpu, ngpa, access);
408         if (real_gfn == UNMAPPED_GVA)
409                 return -EFAULT;
410
411         real_gfn = gpa_to_gfn(real_gfn);
412
413         return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
414 }
415 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
416
417 int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
418                                void *data, int offset, int len, u32 access)
419 {
420         return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
421                                        data, offset, len, access);
422 }
423
424 /*
425  * Load the pae pdptrs.  Return true is they are all valid.
426  */
427 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
428 {
429         gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
430         unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
431         int i;
432         int ret;
433         u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
434
435         ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
436                                       offset * sizeof(u64), sizeof(pdpte),
437                                       PFERR_USER_MASK|PFERR_WRITE_MASK);
438         if (ret < 0) {
439                 ret = 0;
440                 goto out;
441         }
442         for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
443                 if (is_present_gpte(pdpte[i]) &&
444                     (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
445                         ret = 0;
446                         goto out;
447                 }
448         }
449         ret = 1;
450
451         memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
452         __set_bit(VCPU_EXREG_PDPTR,
453                   (unsigned long *)&vcpu->arch.regs_avail);
454         __set_bit(VCPU_EXREG_PDPTR,
455                   (unsigned long *)&vcpu->arch.regs_dirty);
456 out:
457
458         return ret;
459 }
460 EXPORT_SYMBOL_GPL(load_pdptrs);
461
462 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
463 {
464         u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
465         bool changed = true;
466         int offset;
467         gfn_t gfn;
468         int r;
469
470         if (is_long_mode(vcpu) || !is_pae(vcpu))
471                 return false;
472
473         if (!test_bit(VCPU_EXREG_PDPTR,
474                       (unsigned long *)&vcpu->arch.regs_avail))
475                 return true;
476
477         gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
478         offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
479         r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
480                                        PFERR_USER_MASK | PFERR_WRITE_MASK);
481         if (r < 0)
482                 goto out;
483         changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
484 out:
485
486         return changed;
487 }
488
489 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
490 {
491         unsigned long old_cr0 = kvm_read_cr0(vcpu);
492         unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
493                                     X86_CR0_CD | X86_CR0_NW;
494
495         cr0 |= X86_CR0_ET;
496
497 #ifdef CONFIG_X86_64
498         if (cr0 & 0xffffffff00000000UL)
499                 return 1;
500 #endif
501
502         cr0 &= ~CR0_RESERVED_BITS;
503
504         if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
505                 return 1;
506
507         if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
508                 return 1;
509
510         if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
511 #ifdef CONFIG_X86_64
512                 if ((vcpu->arch.efer & EFER_LME)) {
513                         int cs_db, cs_l;
514
515                         if (!is_pae(vcpu))
516                                 return 1;
517                         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
518                         if (cs_l)
519                                 return 1;
520                 } else
521 #endif
522                 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
523                                                  kvm_read_cr3(vcpu)))
524                         return 1;
525         }
526
527         kvm_x86_ops->set_cr0(vcpu, cr0);
528
529         if ((cr0 ^ old_cr0) & X86_CR0_PG) {
530                 kvm_clear_async_pf_completion_queue(vcpu);
531                 kvm_async_pf_hash_reset(vcpu);
532         }
533
534         if ((cr0 ^ old_cr0) & update_bits)
535                 kvm_mmu_reset_context(vcpu);
536         return 0;
537 }
538 EXPORT_SYMBOL_GPL(kvm_set_cr0);
539
540 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
541 {
542         (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
543 }
544 EXPORT_SYMBOL_GPL(kvm_lmsw);
545
546 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
547 {
548         u64 xcr0;
549
550         /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now  */
551         if (index != XCR_XFEATURE_ENABLED_MASK)
552                 return 1;
553         xcr0 = xcr;
554         if (kvm_x86_ops->get_cpl(vcpu) != 0)
555                 return 1;
556         if (!(xcr0 & XSTATE_FP))
557                 return 1;
558         if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
559                 return 1;
560         if (xcr0 & ~host_xcr0)
561                 return 1;
562         vcpu->arch.xcr0 = xcr0;
563         vcpu->guest_xcr0_loaded = 0;
564         return 0;
565 }
566
567 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
568 {
569         if (__kvm_set_xcr(vcpu, index, xcr)) {
570                 kvm_inject_gp(vcpu, 0);
571                 return 1;
572         }
573         return 0;
574 }
575 EXPORT_SYMBOL_GPL(kvm_set_xcr);
576
577 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
578 {
579         unsigned long old_cr4 = kvm_read_cr4(vcpu);
580         unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
581                                    X86_CR4_PAE | X86_CR4_SMEP;
582         if (cr4 & CR4_RESERVED_BITS)
583                 return 1;
584
585         if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
586                 return 1;
587
588         if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
589                 return 1;
590
591         if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_RDWRGSFS))
592                 return 1;
593
594         if (is_long_mode(vcpu)) {
595                 if (!(cr4 & X86_CR4_PAE))
596                         return 1;
597         } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
598                    && ((cr4 ^ old_cr4) & pdptr_bits)
599                    && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
600                                    kvm_read_cr3(vcpu)))
601                 return 1;
602
603         if (kvm_x86_ops->set_cr4(vcpu, cr4))
604                 return 1;
605
606         if ((cr4 ^ old_cr4) & pdptr_bits)
607                 kvm_mmu_reset_context(vcpu);
608
609         if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
610                 kvm_update_cpuid(vcpu);
611
612         return 0;
613 }
614 EXPORT_SYMBOL_GPL(kvm_set_cr4);
615
616 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
617 {
618         if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
619                 kvm_mmu_sync_roots(vcpu);
620                 kvm_mmu_flush_tlb(vcpu);
621                 return 0;
622         }
623
624         if (is_long_mode(vcpu)) {
625                 if (cr3 & CR3_L_MODE_RESERVED_BITS)
626                         return 1;
627         } else {
628                 if (is_pae(vcpu)) {
629                         if (cr3 & CR3_PAE_RESERVED_BITS)
630                                 return 1;
631                         if (is_paging(vcpu) &&
632                             !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
633                                 return 1;
634                 }
635                 /*
636                  * We don't check reserved bits in nonpae mode, because
637                  * this isn't enforced, and VMware depends on this.
638                  */
639         }
640
641         /*
642          * Does the new cr3 value map to physical memory? (Note, we
643          * catch an invalid cr3 even in real-mode, because it would
644          * cause trouble later on when we turn on paging anyway.)
645          *
646          * A real CPU would silently accept an invalid cr3 and would
647          * attempt to use it - with largely undefined (and often hard
648          * to debug) behavior on the guest side.
649          */
650         if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
651                 return 1;
652         vcpu->arch.cr3 = cr3;
653         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
654         vcpu->arch.mmu.new_cr3(vcpu);
655         return 0;
656 }
657 EXPORT_SYMBOL_GPL(kvm_set_cr3);
658
659 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
660 {
661         if (cr8 & CR8_RESERVED_BITS)
662                 return 1;
663         if (irqchip_in_kernel(vcpu->kvm))
664                 kvm_lapic_set_tpr(vcpu, cr8);
665         else
666                 vcpu->arch.cr8 = cr8;
667         return 0;
668 }
669 EXPORT_SYMBOL_GPL(kvm_set_cr8);
670
671 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
672 {
673         if (irqchip_in_kernel(vcpu->kvm))
674                 return kvm_lapic_get_cr8(vcpu);
675         else
676                 return vcpu->arch.cr8;
677 }
678 EXPORT_SYMBOL_GPL(kvm_get_cr8);
679
680 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
681 {
682         switch (dr) {
683         case 0 ... 3:
684                 vcpu->arch.db[dr] = val;
685                 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
686                         vcpu->arch.eff_db[dr] = val;
687                 break;
688         case 4:
689                 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
690                         return 1; /* #UD */
691                 /* fall through */
692         case 6:
693                 if (val & 0xffffffff00000000ULL)
694                         return -1; /* #GP */
695                 vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
696                 break;
697         case 5:
698                 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
699                         return 1; /* #UD */
700                 /* fall through */
701         default: /* 7 */
702                 if (val & 0xffffffff00000000ULL)
703                         return -1; /* #GP */
704                 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
705                 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
706                         kvm_x86_ops->set_dr7(vcpu, vcpu->arch.dr7);
707                         vcpu->arch.switch_db_regs = (val & DR7_BP_EN_MASK);
708                 }
709                 break;
710         }
711
712         return 0;
713 }
714
715 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
716 {
717         int res;
718
719         res = __kvm_set_dr(vcpu, dr, val);
720         if (res > 0)
721                 kvm_queue_exception(vcpu, UD_VECTOR);
722         else if (res < 0)
723                 kvm_inject_gp(vcpu, 0);
724
725         return res;
726 }
727 EXPORT_SYMBOL_GPL(kvm_set_dr);
728
729 static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
730 {
731         switch (dr) {
732         case 0 ... 3:
733                 *val = vcpu->arch.db[dr];
734                 break;
735         case 4:
736                 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
737                         return 1;
738                 /* fall through */
739         case 6:
740                 *val = vcpu->arch.dr6;
741                 break;
742         case 5:
743                 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
744                         return 1;
745                 /* fall through */
746         default: /* 7 */
747                 *val = vcpu->arch.dr7;
748                 break;
749         }
750
751         return 0;
752 }
753
754 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
755 {
756         if (_kvm_get_dr(vcpu, dr, val)) {
757                 kvm_queue_exception(vcpu, UD_VECTOR);
758                 return 1;
759         }
760         return 0;
761 }
762 EXPORT_SYMBOL_GPL(kvm_get_dr);
763
764 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
765 {
766         u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
767         u64 data;
768         int err;
769
770         err = kvm_pmu_read_pmc(vcpu, ecx, &data);
771         if (err)
772                 return err;
773         kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
774         kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
775         return err;
776 }
777 EXPORT_SYMBOL_GPL(kvm_rdpmc);
778
779 /*
780  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
781  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
782  *
783  * This list is modified at module load time to reflect the
784  * capabilities of the host cpu. This capabilities test skips MSRs that are
785  * kvm-specific. Those are put in the beginning of the list.
786  */
787
788 #define KVM_SAVE_MSRS_BEGIN     9
789 static u32 msrs_to_save[] = {
790         MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
791         MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
792         HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
793         HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
794         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
795         MSR_STAR,
796 #ifdef CONFIG_X86_64
797         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
798 #endif
799         MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA
800 };
801
802 static unsigned num_msrs_to_save;
803
804 static u32 emulated_msrs[] = {
805         MSR_IA32_TSCDEADLINE,
806         MSR_IA32_MISC_ENABLE,
807         MSR_IA32_MCG_STATUS,
808         MSR_IA32_MCG_CTL,
809 };
810
811 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
812 {
813         u64 old_efer = vcpu->arch.efer;
814
815         if (efer & efer_reserved_bits)
816                 return 1;
817
818         if (is_paging(vcpu)
819             && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
820                 return 1;
821
822         if (efer & EFER_FFXSR) {
823                 struct kvm_cpuid_entry2 *feat;
824
825                 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
826                 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
827                         return 1;
828         }
829
830         if (efer & EFER_SVME) {
831                 struct kvm_cpuid_entry2 *feat;
832
833                 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
834                 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
835                         return 1;
836         }
837
838         efer &= ~EFER_LMA;
839         efer |= vcpu->arch.efer & EFER_LMA;
840
841         kvm_x86_ops->set_efer(vcpu, efer);
842
843         vcpu->arch.mmu.base_role.nxe = (efer & EFER_NX) && !tdp_enabled;
844
845         /* Update reserved bits */
846         if ((efer ^ old_efer) & EFER_NX)
847                 kvm_mmu_reset_context(vcpu);
848
849         return 0;
850 }
851
852 void kvm_enable_efer_bits(u64 mask)
853 {
854        efer_reserved_bits &= ~mask;
855 }
856 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
857
858
859 /*
860  * Writes msr value into into the appropriate "register".
861  * Returns 0 on success, non-0 otherwise.
862  * Assumes vcpu_load() was already called.
863  */
864 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
865 {
866         return kvm_x86_ops->set_msr(vcpu, msr_index, data);
867 }
868
869 /*
870  * Adapt set_msr() to msr_io()'s calling convention
871  */
872 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
873 {
874         return kvm_set_msr(vcpu, index, *data);
875 }
876
877 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
878 {
879         int version;
880         int r;
881         struct pvclock_wall_clock wc;
882         struct timespec boot;
883
884         if (!wall_clock)
885                 return;
886
887         r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
888         if (r)
889                 return;
890
891         if (version & 1)
892                 ++version;  /* first time write, random junk */
893
894         ++version;
895
896         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
897
898         /*
899          * The guest calculates current wall clock time by adding
900          * system time (updated by kvm_guest_time_update below) to the
901          * wall clock specified here.  guest system time equals host
902          * system time for us, thus we must fill in host boot time here.
903          */
904         getboottime(&boot);
905
906         wc.sec = boot.tv_sec;
907         wc.nsec = boot.tv_nsec;
908         wc.version = version;
909
910         kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
911
912         version++;
913         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
914 }
915
916 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
917 {
918         uint32_t quotient, remainder;
919
920         /* Don't try to replace with do_div(), this one calculates
921          * "(dividend << 32) / divisor" */
922         __asm__ ( "divl %4"
923                   : "=a" (quotient), "=d" (remainder)
924                   : "0" (0), "1" (dividend), "r" (divisor) );
925         return quotient;
926 }
927
928 static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
929                                s8 *pshift, u32 *pmultiplier)
930 {
931         uint64_t scaled64;
932         int32_t  shift = 0;
933         uint64_t tps64;
934         uint32_t tps32;
935
936         tps64 = base_khz * 1000LL;
937         scaled64 = scaled_khz * 1000LL;
938         while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
939                 tps64 >>= 1;
940                 shift--;
941         }
942
943         tps32 = (uint32_t)tps64;
944         while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
945                 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
946                         scaled64 >>= 1;
947                 else
948                         tps32 <<= 1;
949                 shift++;
950         }
951
952         *pshift = shift;
953         *pmultiplier = div_frac(scaled64, tps32);
954
955         pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
956                  __func__, base_khz, scaled_khz, shift, *pmultiplier);
957 }
958
959 static inline u64 get_kernel_ns(void)
960 {
961         struct timespec ts;
962
963         WARN_ON(preemptible());
964         ktime_get_ts(&ts);
965         monotonic_to_bootbased(&ts);
966         return timespec_to_ns(&ts);
967 }
968
969 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
970 unsigned long max_tsc_khz;
971
972 static inline int kvm_tsc_changes_freq(void)
973 {
974         int cpu = get_cpu();
975         int ret = !boot_cpu_has(X86_FEATURE_CONSTANT_TSC) &&
976                   cpufreq_quick_get(cpu) != 0;
977         put_cpu();
978         return ret;
979 }
980
981 u64 vcpu_tsc_khz(struct kvm_vcpu *vcpu)
982 {
983         if (vcpu->arch.virtual_tsc_khz)
984                 return vcpu->arch.virtual_tsc_khz;
985         else
986                 return __this_cpu_read(cpu_tsc_khz);
987 }
988
989 static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
990 {
991         u64 ret;
992
993         WARN_ON(preemptible());
994         if (kvm_tsc_changes_freq())
995                 printk_once(KERN_WARNING
996                  "kvm: unreliable cycle conversion on adjustable rate TSC\n");
997         ret = nsec * vcpu_tsc_khz(vcpu);
998         do_div(ret, USEC_PER_SEC);
999         return ret;
1000 }
1001
1002 static void kvm_init_tsc_catchup(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
1003 {
1004         /* Compute a scale to convert nanoseconds in TSC cycles */
1005         kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
1006                            &vcpu->arch.tsc_catchup_shift,
1007                            &vcpu->arch.tsc_catchup_mult);
1008 }
1009
1010 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1011 {
1012         u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.last_tsc_nsec,
1013                                       vcpu->arch.tsc_catchup_mult,
1014                                       vcpu->arch.tsc_catchup_shift);
1015         tsc += vcpu->arch.last_tsc_write;
1016         return tsc;
1017 }
1018
1019 void kvm_write_tsc(struct kvm_vcpu *vcpu, u64 data)
1020 {
1021         struct kvm *kvm = vcpu->kvm;
1022         u64 offset, ns, elapsed;
1023         unsigned long flags;
1024         s64 sdiff;
1025
1026         raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1027         offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
1028         ns = get_kernel_ns();
1029         elapsed = ns - kvm->arch.last_tsc_nsec;
1030         sdiff = data - kvm->arch.last_tsc_write;
1031         if (sdiff < 0)
1032                 sdiff = -sdiff;
1033
1034         /*
1035          * Special case: close write to TSC within 5 seconds of
1036          * another CPU is interpreted as an attempt to synchronize
1037          * The 5 seconds is to accommodate host load / swapping as
1038          * well as any reset of TSC during the boot process.
1039          *
1040          * In that case, for a reliable TSC, we can match TSC offsets,
1041          * or make a best guest using elapsed value.
1042          */
1043         if (sdiff < nsec_to_cycles(vcpu, 5ULL * NSEC_PER_SEC) &&
1044             elapsed < 5ULL * NSEC_PER_SEC) {
1045                 if (!check_tsc_unstable()) {
1046                         offset = kvm->arch.last_tsc_offset;
1047                         pr_debug("kvm: matched tsc offset for %llu\n", data);
1048                 } else {
1049                         u64 delta = nsec_to_cycles(vcpu, elapsed);
1050                         offset += delta;
1051                         pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1052                 }
1053                 ns = kvm->arch.last_tsc_nsec;
1054         }
1055         kvm->arch.last_tsc_nsec = ns;
1056         kvm->arch.last_tsc_write = data;
1057         kvm->arch.last_tsc_offset = offset;
1058         kvm_x86_ops->write_tsc_offset(vcpu, offset);
1059         raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1060
1061         /* Reset of TSC must disable overshoot protection below */
1062         vcpu->arch.hv_clock.tsc_timestamp = 0;
1063         vcpu->arch.last_tsc_write = data;
1064         vcpu->arch.last_tsc_nsec = ns;
1065 }
1066 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1067
1068 static int kvm_guest_time_update(struct kvm_vcpu *v)
1069 {
1070         unsigned long flags;
1071         struct kvm_vcpu_arch *vcpu = &v->arch;
1072         void *shared_kaddr;
1073         unsigned long this_tsc_khz;
1074         s64 kernel_ns, max_kernel_ns;
1075         u64 tsc_timestamp;
1076
1077         /* Keep irq disabled to prevent changes to the clock */
1078         local_irq_save(flags);
1079         tsc_timestamp = kvm_x86_ops->read_l1_tsc(v);
1080         kernel_ns = get_kernel_ns();
1081         this_tsc_khz = vcpu_tsc_khz(v);
1082         if (unlikely(this_tsc_khz == 0)) {
1083                 local_irq_restore(flags);
1084                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1085                 return 1;
1086         }
1087
1088         /*
1089          * We may have to catch up the TSC to match elapsed wall clock
1090          * time for two reasons, even if kvmclock is used.
1091          *   1) CPU could have been running below the maximum TSC rate
1092          *   2) Broken TSC compensation resets the base at each VCPU
1093          *      entry to avoid unknown leaps of TSC even when running
1094          *      again on the same CPU.  This may cause apparent elapsed
1095          *      time to disappear, and the guest to stand still or run
1096          *      very slowly.
1097          */
1098         if (vcpu->tsc_catchup) {
1099                 u64 tsc = compute_guest_tsc(v, kernel_ns);
1100                 if (tsc > tsc_timestamp) {
1101                         kvm_x86_ops->adjust_tsc_offset(v, tsc - tsc_timestamp);
1102                         tsc_timestamp = tsc;
1103                 }
1104         }
1105
1106         local_irq_restore(flags);
1107
1108         if (!vcpu->time_page)
1109                 return 0;
1110
1111         /*
1112          * Time as measured by the TSC may go backwards when resetting the base
1113          * tsc_timestamp.  The reason for this is that the TSC resolution is
1114          * higher than the resolution of the other clock scales.  Thus, many
1115          * possible measurments of the TSC correspond to one measurement of any
1116          * other clock, and so a spread of values is possible.  This is not a
1117          * problem for the computation of the nanosecond clock; with TSC rates
1118          * around 1GHZ, there can only be a few cycles which correspond to one
1119          * nanosecond value, and any path through this code will inevitably
1120          * take longer than that.  However, with the kernel_ns value itself,
1121          * the precision may be much lower, down to HZ granularity.  If the
1122          * first sampling of TSC against kernel_ns ends in the low part of the
1123          * range, and the second in the high end of the range, we can get:
1124          *
1125          * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new
1126          *
1127          * As the sampling errors potentially range in the thousands of cycles,
1128          * it is possible such a time value has already been observed by the
1129          * guest.  To protect against this, we must compute the system time as
1130          * observed by the guest and ensure the new system time is greater.
1131          */
1132         max_kernel_ns = 0;
1133         if (vcpu->hv_clock.tsc_timestamp && vcpu->last_guest_tsc) {
1134                 max_kernel_ns = vcpu->last_guest_tsc -
1135                                 vcpu->hv_clock.tsc_timestamp;
1136                 max_kernel_ns = pvclock_scale_delta(max_kernel_ns,
1137                                     vcpu->hv_clock.tsc_to_system_mul,
1138                                     vcpu->hv_clock.tsc_shift);
1139                 max_kernel_ns += vcpu->last_kernel_ns;
1140         }
1141
1142         if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
1143                 kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
1144                                    &vcpu->hv_clock.tsc_shift,
1145                                    &vcpu->hv_clock.tsc_to_system_mul);
1146                 vcpu->hw_tsc_khz = this_tsc_khz;
1147         }
1148
1149         if (max_kernel_ns > kernel_ns)
1150                 kernel_ns = max_kernel_ns;
1151
1152         /* With all the info we got, fill in the values */
1153         vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1154         vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1155         vcpu->last_kernel_ns = kernel_ns;
1156         vcpu->last_guest_tsc = tsc_timestamp;
1157         vcpu->hv_clock.flags = 0;
1158
1159         /*
1160          * The interface expects us to write an even number signaling that the
1161          * update is finished. Since the guest won't see the intermediate
1162          * state, we just increase by 2 at the end.
1163          */
1164         vcpu->hv_clock.version += 2;
1165
1166         shared_kaddr = kmap_atomic(vcpu->time_page);
1167
1168         memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
1169                sizeof(vcpu->hv_clock));
1170
1171         kunmap_atomic(shared_kaddr);
1172
1173         mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
1174         return 0;
1175 }
1176
1177 static bool msr_mtrr_valid(unsigned msr)
1178 {
1179         switch (msr) {
1180         case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
1181         case MSR_MTRRfix64K_00000:
1182         case MSR_MTRRfix16K_80000:
1183         case MSR_MTRRfix16K_A0000:
1184         case MSR_MTRRfix4K_C0000:
1185         case MSR_MTRRfix4K_C8000:
1186         case MSR_MTRRfix4K_D0000:
1187         case MSR_MTRRfix4K_D8000:
1188         case MSR_MTRRfix4K_E0000:
1189         case MSR_MTRRfix4K_E8000:
1190         case MSR_MTRRfix4K_F0000:
1191         case MSR_MTRRfix4K_F8000:
1192         case MSR_MTRRdefType:
1193         case MSR_IA32_CR_PAT:
1194                 return true;
1195         case 0x2f8:
1196                 return true;
1197         }
1198         return false;
1199 }
1200
1201 static bool valid_pat_type(unsigned t)
1202 {
1203         return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
1204 }
1205
1206 static bool valid_mtrr_type(unsigned t)
1207 {
1208         return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
1209 }
1210
1211 static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1212 {
1213         int i;
1214
1215         if (!msr_mtrr_valid(msr))
1216                 return false;
1217
1218         if (msr == MSR_IA32_CR_PAT) {
1219                 for (i = 0; i < 8; i++)
1220                         if (!valid_pat_type((data >> (i * 8)) & 0xff))
1221                                 return false;
1222                 return true;
1223         } else if (msr == MSR_MTRRdefType) {
1224                 if (data & ~0xcff)
1225                         return false;
1226                 return valid_mtrr_type(data & 0xff);
1227         } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
1228                 for (i = 0; i < 8 ; i++)
1229                         if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
1230                                 return false;
1231                 return true;
1232         }
1233
1234         /* variable MTRRs */
1235         return valid_mtrr_type(data & 0xff);
1236 }
1237
1238 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1239 {
1240         u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1241
1242         if (!mtrr_valid(vcpu, msr, data))
1243                 return 1;
1244
1245         if (msr == MSR_MTRRdefType) {
1246                 vcpu->arch.mtrr_state.def_type = data;
1247                 vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
1248         } else if (msr == MSR_MTRRfix64K_00000)
1249                 p[0] = data;
1250         else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1251                 p[1 + msr - MSR_MTRRfix16K_80000] = data;
1252         else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1253                 p[3 + msr - MSR_MTRRfix4K_C0000] = data;
1254         else if (msr == MSR_IA32_CR_PAT)
1255                 vcpu->arch.pat = data;
1256         else {  /* Variable MTRRs */
1257                 int idx, is_mtrr_mask;
1258                 u64 *pt;
1259
1260                 idx = (msr - 0x200) / 2;
1261                 is_mtrr_mask = msr - 0x200 - 2 * idx;
1262                 if (!is_mtrr_mask)
1263                         pt =
1264                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1265                 else
1266                         pt =
1267                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1268                 *pt = data;
1269         }
1270
1271         kvm_mmu_reset_context(vcpu);
1272         return 0;
1273 }
1274
1275 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1276 {
1277         u64 mcg_cap = vcpu->arch.mcg_cap;
1278         unsigned bank_num = mcg_cap & 0xff;
1279
1280         switch (msr) {
1281         case MSR_IA32_MCG_STATUS:
1282                 vcpu->arch.mcg_status = data;
1283                 break;
1284         case MSR_IA32_MCG_CTL:
1285                 if (!(mcg_cap & MCG_CTL_P))
1286                         return 1;
1287                 if (data != 0 && data != ~(u64)0)
1288                         return -1;
1289                 vcpu->arch.mcg_ctl = data;
1290                 break;
1291         default:
1292                 if (msr >= MSR_IA32_MC0_CTL &&
1293                     msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1294                         u32 offset = msr - MSR_IA32_MC0_CTL;
1295                         /* only 0 or all 1s can be written to IA32_MCi_CTL
1296                          * some Linux kernels though clear bit 10 in bank 4 to
1297                          * workaround a BIOS/GART TBL issue on AMD K8s, ignore
1298                          * this to avoid an uncatched #GP in the guest
1299                          */
1300                         if ((offset & 0x3) == 0 &&
1301                             data != 0 && (data | (1 << 10)) != ~(u64)0)
1302                                 return -1;
1303                         vcpu->arch.mce_banks[offset] = data;
1304                         break;
1305                 }
1306                 return 1;
1307         }
1308         return 0;
1309 }
1310
1311 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
1312 {
1313         struct kvm *kvm = vcpu->kvm;
1314         int lm = is_long_mode(vcpu);
1315         u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
1316                 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
1317         u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
1318                 : kvm->arch.xen_hvm_config.blob_size_32;
1319         u32 page_num = data & ~PAGE_MASK;
1320         u64 page_addr = data & PAGE_MASK;
1321         u8 *page;
1322         int r;
1323
1324         r = -E2BIG;
1325         if (page_num >= blob_size)
1326                 goto out;
1327         r = -ENOMEM;
1328         page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
1329         if (IS_ERR(page)) {
1330                 r = PTR_ERR(page);
1331                 goto out;
1332         }
1333         if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
1334                 goto out_free;
1335         r = 0;
1336 out_free:
1337         kfree(page);
1338 out:
1339         return r;
1340 }
1341
1342 static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
1343 {
1344         return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
1345 }
1346
1347 static bool kvm_hv_msr_partition_wide(u32 msr)
1348 {
1349         bool r = false;
1350         switch (msr) {
1351         case HV_X64_MSR_GUEST_OS_ID:
1352         case HV_X64_MSR_HYPERCALL:
1353                 r = true;
1354                 break;
1355         }
1356
1357         return r;
1358 }
1359
1360 static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1361 {
1362         struct kvm *kvm = vcpu->kvm;
1363
1364         switch (msr) {
1365         case HV_X64_MSR_GUEST_OS_ID:
1366                 kvm->arch.hv_guest_os_id = data;
1367                 /* setting guest os id to zero disables hypercall page */
1368                 if (!kvm->arch.hv_guest_os_id)
1369                         kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
1370                 break;
1371         case HV_X64_MSR_HYPERCALL: {
1372                 u64 gfn;
1373                 unsigned long addr;
1374                 u8 instructions[4];
1375
1376                 /* if guest os id is not set hypercall should remain disabled */
1377                 if (!kvm->arch.hv_guest_os_id)
1378                         break;
1379                 if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
1380                         kvm->arch.hv_hypercall = data;
1381                         break;
1382                 }
1383                 gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
1384                 addr = gfn_to_hva(kvm, gfn);
1385                 if (kvm_is_error_hva(addr))
1386                         return 1;
1387                 kvm_x86_ops->patch_hypercall(vcpu, instructions);
1388                 ((unsigned char *)instructions)[3] = 0xc3; /* ret */
1389                 if (__copy_to_user((void __user *)addr, instructions, 4))
1390                         return 1;
1391                 kvm->arch.hv_hypercall = data;
1392                 break;
1393         }
1394         default:
1395                 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1396                           "data 0x%llx\n", msr, data);
1397                 return 1;
1398         }
1399         return 0;
1400 }
1401
1402 static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1403 {
1404         switch (msr) {
1405         case HV_X64_MSR_APIC_ASSIST_PAGE: {
1406                 unsigned long addr;
1407
1408                 if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
1409                         vcpu->arch.hv_vapic = data;
1410                         break;
1411                 }
1412                 addr = gfn_to_hva(vcpu->kvm, data >>
1413                                   HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
1414                 if (kvm_is_error_hva(addr))
1415                         return 1;
1416                 if (__clear_user((void __user *)addr, PAGE_SIZE))
1417                         return 1;
1418                 vcpu->arch.hv_vapic = data;
1419                 break;
1420         }
1421         case HV_X64_MSR_EOI:
1422                 return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
1423         case HV_X64_MSR_ICR:
1424                 return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
1425         case HV_X64_MSR_TPR:
1426                 return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
1427         default:
1428                 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1429                           "data 0x%llx\n", msr, data);
1430                 return 1;
1431         }
1432
1433         return 0;
1434 }
1435
1436 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
1437 {
1438         gpa_t gpa = data & ~0x3f;
1439
1440         /* Bits 2:5 are resrved, Should be zero */
1441         if (data & 0x3c)
1442                 return 1;
1443
1444         vcpu->arch.apf.msr_val = data;
1445
1446         if (!(data & KVM_ASYNC_PF_ENABLED)) {
1447                 kvm_clear_async_pf_completion_queue(vcpu);
1448                 kvm_async_pf_hash_reset(vcpu);
1449                 return 0;
1450         }
1451
1452         if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa))
1453                 return 1;
1454
1455         vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
1456         kvm_async_pf_wakeup_all(vcpu);
1457         return 0;
1458 }
1459
1460 static void kvmclock_reset(struct kvm_vcpu *vcpu)
1461 {
1462         if (vcpu->arch.time_page) {
1463                 kvm_release_page_dirty(vcpu->arch.time_page);
1464                 vcpu->arch.time_page = NULL;
1465         }
1466 }
1467
1468 static void accumulate_steal_time(struct kvm_vcpu *vcpu)
1469 {
1470         u64 delta;
1471
1472         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1473                 return;
1474
1475         delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
1476         vcpu->arch.st.last_steal = current->sched_info.run_delay;
1477         vcpu->arch.st.accum_steal = delta;
1478 }
1479
1480 static void record_steal_time(struct kvm_vcpu *vcpu)
1481 {
1482         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1483                 return;
1484
1485         if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1486                 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
1487                 return;
1488
1489         vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
1490         vcpu->arch.st.steal.version += 2;
1491         vcpu->arch.st.accum_steal = 0;
1492
1493         kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1494                 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
1495 }
1496
1497 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1498 {
1499         bool pr = false;
1500
1501         switch (msr) {
1502         case MSR_EFER:
1503                 return set_efer(vcpu, data);
1504         case MSR_K7_HWCR:
1505                 data &= ~(u64)0x40;     /* ignore flush filter disable */
1506                 data &= ~(u64)0x100;    /* ignore ignne emulation enable */
1507                 if (data != 0) {
1508                         pr_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
1509                                 data);
1510                         return 1;
1511                 }
1512                 break;
1513         case MSR_FAM10H_MMIO_CONF_BASE:
1514                 if (data != 0) {
1515                         pr_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
1516                                 "0x%llx\n", data);
1517                         return 1;
1518                 }
1519                 break;
1520         case MSR_AMD64_NB_CFG:
1521                 break;
1522         case MSR_IA32_DEBUGCTLMSR:
1523                 if (!data) {
1524                         /* We support the non-activated case already */
1525                         break;
1526                 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
1527                         /* Values other than LBR and BTF are vendor-specific,
1528                            thus reserved and should throw a #GP */
1529                         return 1;
1530                 }
1531                 pr_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
1532                         __func__, data);
1533                 break;
1534         case MSR_IA32_UCODE_REV:
1535         case MSR_IA32_UCODE_WRITE:
1536         case MSR_VM_HSAVE_PA:
1537         case MSR_AMD64_PATCH_LOADER:
1538                 break;
1539         case 0x200 ... 0x2ff:
1540                 return set_msr_mtrr(vcpu, msr, data);
1541         case MSR_IA32_APICBASE:
1542                 kvm_set_apic_base(vcpu, data);
1543                 break;
1544         case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1545                 return kvm_x2apic_msr_write(vcpu, msr, data);
1546         case MSR_IA32_TSCDEADLINE:
1547                 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1548                 break;
1549         case MSR_IA32_MISC_ENABLE:
1550                 vcpu->arch.ia32_misc_enable_msr = data;
1551                 break;
1552         case MSR_KVM_WALL_CLOCK_NEW:
1553         case MSR_KVM_WALL_CLOCK:
1554                 vcpu->kvm->arch.wall_clock = data;
1555                 kvm_write_wall_clock(vcpu->kvm, data);
1556                 break;
1557         case MSR_KVM_SYSTEM_TIME_NEW:
1558         case MSR_KVM_SYSTEM_TIME: {
1559                 kvmclock_reset(vcpu);
1560
1561                 vcpu->arch.time = data;
1562                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1563
1564                 /* we verify if the enable bit is set... */
1565                 if (!(data & 1))
1566                         break;
1567
1568                 /* ...but clean it before doing the actual write */
1569                 vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
1570
1571                 vcpu->arch.time_page =
1572                                 gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
1573
1574                 if (is_error_page(vcpu->arch.time_page)) {
1575                         kvm_release_page_clean(vcpu->arch.time_page);
1576                         vcpu->arch.time_page = NULL;
1577                 }
1578                 break;
1579         }
1580         case MSR_KVM_ASYNC_PF_EN:
1581                 if (kvm_pv_enable_async_pf(vcpu, data))
1582                         return 1;
1583                 break;
1584         case MSR_KVM_STEAL_TIME:
1585
1586                 if (unlikely(!sched_info_on()))
1587                         return 1;
1588
1589                 if (data & KVM_STEAL_RESERVED_MASK)
1590                         return 1;
1591
1592                 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
1593                                                         data & KVM_STEAL_VALID_BITS))
1594                         return 1;
1595
1596                 vcpu->arch.st.msr_val = data;
1597
1598                 if (!(data & KVM_MSR_ENABLED))
1599                         break;
1600
1601                 vcpu->arch.st.last_steal = current->sched_info.run_delay;
1602
1603                 preempt_disable();
1604                 accumulate_steal_time(vcpu);
1605                 preempt_enable();
1606
1607                 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
1608
1609                 break;
1610
1611         case MSR_IA32_MCG_CTL:
1612         case MSR_IA32_MCG_STATUS:
1613         case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1614                 return set_msr_mce(vcpu, msr, data);
1615
1616         /* Performance counters are not protected by a CPUID bit,
1617          * so we should check all of them in the generic path for the sake of
1618          * cross vendor migration.
1619          * Writing a zero into the event select MSRs disables them,
1620          * which we perfectly emulate ;-). Any other value should be at least
1621          * reported, some guests depend on them.
1622          */
1623         case MSR_K7_EVNTSEL0:
1624         case MSR_K7_EVNTSEL1:
1625         case MSR_K7_EVNTSEL2:
1626         case MSR_K7_EVNTSEL3:
1627                 if (data != 0)
1628                         pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1629                                 "0x%x data 0x%llx\n", msr, data);
1630                 break;
1631         /* at least RHEL 4 unconditionally writes to the perfctr registers,
1632          * so we ignore writes to make it happy.
1633          */
1634         case MSR_K7_PERFCTR0:
1635         case MSR_K7_PERFCTR1:
1636         case MSR_K7_PERFCTR2:
1637         case MSR_K7_PERFCTR3:
1638                 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1639                         "0x%x data 0x%llx\n", msr, data);
1640                 break;
1641         case MSR_P6_PERFCTR0:
1642         case MSR_P6_PERFCTR1:
1643                 pr = true;
1644         case MSR_P6_EVNTSEL0:
1645         case MSR_P6_EVNTSEL1:
1646                 if (kvm_pmu_msr(vcpu, msr))
1647                         return kvm_pmu_set_msr(vcpu, msr, data);
1648
1649                 if (pr || data != 0)
1650                         pr_unimpl(vcpu, "disabled perfctr wrmsr: "
1651                                 "0x%x data 0x%llx\n", msr, data);
1652                 break;
1653         case MSR_K7_CLK_CTL:
1654                 /*
1655                  * Ignore all writes to this no longer documented MSR.
1656                  * Writes are only relevant for old K7 processors,
1657                  * all pre-dating SVM, but a recommended workaround from
1658                  * AMD for these chips. It is possible to speicify the
1659                  * affected processor models on the command line, hence
1660                  * the need to ignore the workaround.
1661                  */
1662                 break;
1663         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1664                 if (kvm_hv_msr_partition_wide(msr)) {
1665                         int r;
1666                         mutex_lock(&vcpu->kvm->lock);
1667                         r = set_msr_hyperv_pw(vcpu, msr, data);
1668                         mutex_unlock(&vcpu->kvm->lock);
1669                         return r;
1670                 } else
1671                         return set_msr_hyperv(vcpu, msr, data);
1672                 break;
1673         case MSR_IA32_BBL_CR_CTL3:
1674                 /* Drop writes to this legacy MSR -- see rdmsr
1675                  * counterpart for further detail.
1676                  */
1677                 pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
1678                 break;
1679         default:
1680                 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
1681                         return xen_hvm_config(vcpu, data);
1682                 if (kvm_pmu_msr(vcpu, msr))
1683                         return kvm_pmu_set_msr(vcpu, msr, data);
1684                 if (!ignore_msrs) {
1685                         pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
1686                                 msr, data);
1687                         return 1;
1688                 } else {
1689                         pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
1690                                 msr, data);
1691                         break;
1692                 }
1693         }
1694         return 0;
1695 }
1696 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
1697
1698
1699 /*
1700  * Reads an msr value (of 'msr_index') into 'pdata'.
1701  * Returns 0 on success, non-0 otherwise.
1702  * Assumes vcpu_load() was already called.
1703  */
1704 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1705 {
1706         return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
1707 }
1708
1709 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1710 {
1711         u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1712
1713         if (!msr_mtrr_valid(msr))
1714                 return 1;
1715
1716         if (msr == MSR_MTRRdefType)
1717                 *pdata = vcpu->arch.mtrr_state.def_type +
1718                          (vcpu->arch.mtrr_state.enabled << 10);
1719         else if (msr == MSR_MTRRfix64K_00000)
1720                 *pdata = p[0];
1721         else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1722                 *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
1723         else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1724                 *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
1725         else if (msr == MSR_IA32_CR_PAT)
1726                 *pdata = vcpu->arch.pat;
1727         else {  /* Variable MTRRs */
1728                 int idx, is_mtrr_mask;
1729                 u64 *pt;
1730
1731                 idx = (msr - 0x200) / 2;
1732                 is_mtrr_mask = msr - 0x200 - 2 * idx;
1733                 if (!is_mtrr_mask)
1734                         pt =
1735                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1736                 else
1737                         pt =
1738                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1739                 *pdata = *pt;
1740         }
1741
1742         return 0;
1743 }
1744
1745 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1746 {
1747         u64 data;
1748         u64 mcg_cap = vcpu->arch.mcg_cap;
1749         unsigned bank_num = mcg_cap & 0xff;
1750
1751         switch (msr) {
1752         case MSR_IA32_P5_MC_ADDR:
1753         case MSR_IA32_P5_MC_TYPE:
1754                 data = 0;
1755                 break;
1756         case MSR_IA32_MCG_CAP:
1757                 data = vcpu->arch.mcg_cap;
1758                 break;
1759         case MSR_IA32_MCG_CTL:
1760                 if (!(mcg_cap & MCG_CTL_P))
1761                         return 1;
1762                 data = vcpu->arch.mcg_ctl;
1763                 break;
1764         case MSR_IA32_MCG_STATUS:
1765                 data = vcpu->arch.mcg_status;
1766                 break;
1767         default:
1768                 if (msr >= MSR_IA32_MC0_CTL &&
1769                     msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1770                         u32 offset = msr - MSR_IA32_MC0_CTL;
1771                         data = vcpu->arch.mce_banks[offset];
1772                         break;
1773                 }
1774                 return 1;
1775         }
1776         *pdata = data;
1777         return 0;
1778 }
1779
1780 static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1781 {
1782         u64 data = 0;
1783         struct kvm *kvm = vcpu->kvm;
1784
1785         switch (msr) {
1786         case HV_X64_MSR_GUEST_OS_ID:
1787                 data = kvm->arch.hv_guest_os_id;
1788                 break;
1789         case HV_X64_MSR_HYPERCALL:
1790                 data = kvm->arch.hv_hypercall;
1791                 break;
1792         default:
1793                 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1794                 return 1;
1795         }
1796
1797         *pdata = data;
1798         return 0;
1799 }
1800
1801 static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1802 {
1803         u64 data = 0;
1804
1805         switch (msr) {
1806         case HV_X64_MSR_VP_INDEX: {
1807                 int r;
1808                 struct kvm_vcpu *v;
1809                 kvm_for_each_vcpu(r, v, vcpu->kvm)
1810                         if (v == vcpu)
1811                                 data = r;
1812                 break;
1813         }
1814         case HV_X64_MSR_EOI:
1815                 return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
1816         case HV_X64_MSR_ICR:
1817                 return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
1818         case HV_X64_MSR_TPR:
1819                 return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
1820         case HV_X64_MSR_APIC_ASSIST_PAGE:
1821                 data = vcpu->arch.hv_vapic;
1822                 break;
1823         default:
1824                 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1825                 return 1;
1826         }
1827         *pdata = data;
1828         return 0;
1829 }
1830
1831 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1832 {
1833         u64 data;
1834
1835         switch (msr) {
1836         case MSR_IA32_PLATFORM_ID:
1837         case MSR_IA32_EBL_CR_POWERON:
1838         case MSR_IA32_DEBUGCTLMSR:
1839         case MSR_IA32_LASTBRANCHFROMIP:
1840         case MSR_IA32_LASTBRANCHTOIP:
1841         case MSR_IA32_LASTINTFROMIP:
1842         case MSR_IA32_LASTINTTOIP:
1843         case MSR_K8_SYSCFG:
1844         case MSR_K7_HWCR:
1845         case MSR_VM_HSAVE_PA:
1846         case MSR_K7_EVNTSEL0:
1847         case MSR_K7_PERFCTR0:
1848         case MSR_K8_INT_PENDING_MSG:
1849         case MSR_AMD64_NB_CFG:
1850         case MSR_FAM10H_MMIO_CONF_BASE:
1851                 data = 0;
1852                 break;
1853         case MSR_P6_PERFCTR0:
1854         case MSR_P6_PERFCTR1:
1855         case MSR_P6_EVNTSEL0:
1856         case MSR_P6_EVNTSEL1:
1857                 if (kvm_pmu_msr(vcpu, msr))
1858                         return kvm_pmu_get_msr(vcpu, msr, pdata);
1859                 data = 0;
1860                 break;
1861         case MSR_IA32_UCODE_REV:
1862                 data = 0x100000000ULL;
1863                 break;
1864         case MSR_MTRRcap:
1865                 data = 0x500 | KVM_NR_VAR_MTRR;
1866                 break;
1867         case 0x200 ... 0x2ff:
1868                 return get_msr_mtrr(vcpu, msr, pdata);
1869         case 0xcd: /* fsb frequency */
1870                 data = 3;
1871                 break;
1872                 /*
1873                  * MSR_EBC_FREQUENCY_ID
1874                  * Conservative value valid for even the basic CPU models.
1875                  * Models 0,1: 000 in bits 23:21 indicating a bus speed of
1876                  * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
1877                  * and 266MHz for model 3, or 4. Set Core Clock
1878                  * Frequency to System Bus Frequency Ratio to 1 (bits
1879                  * 31:24) even though these are only valid for CPU
1880                  * models > 2, however guests may end up dividing or
1881                  * multiplying by zero otherwise.
1882                  */
1883         case MSR_EBC_FREQUENCY_ID:
1884                 data = 1 << 24;
1885                 break;
1886         case MSR_IA32_APICBASE:
1887                 data = kvm_get_apic_base(vcpu);
1888                 break;
1889         case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1890                 return kvm_x2apic_msr_read(vcpu, msr, pdata);
1891                 break;
1892         case MSR_IA32_TSCDEADLINE:
1893                 data = kvm_get_lapic_tscdeadline_msr(vcpu);
1894                 break;
1895         case MSR_IA32_MISC_ENABLE:
1896                 data = vcpu->arch.ia32_misc_enable_msr;
1897                 break;
1898         case MSR_IA32_PERF_STATUS:
1899                 /* TSC increment by tick */
1900                 data = 1000ULL;
1901                 /* CPU multiplier */
1902                 data |= (((uint64_t)4ULL) << 40);
1903                 break;
1904         case MSR_EFER:
1905                 data = vcpu->arch.efer;
1906                 break;
1907         case MSR_KVM_WALL_CLOCK:
1908         case MSR_KVM_WALL_CLOCK_NEW:
1909                 data = vcpu->kvm->arch.wall_clock;
1910                 break;
1911         case MSR_KVM_SYSTEM_TIME:
1912         case MSR_KVM_SYSTEM_TIME_NEW:
1913                 data = vcpu->arch.time;
1914                 break;
1915         case MSR_KVM_ASYNC_PF_EN:
1916                 data = vcpu->arch.apf.msr_val;
1917                 break;
1918         case MSR_KVM_STEAL_TIME:
1919                 data = vcpu->arch.st.msr_val;
1920                 break;
1921         case MSR_IA32_P5_MC_ADDR:
1922         case MSR_IA32_P5_MC_TYPE:
1923         case MSR_IA32_MCG_CAP:
1924         case MSR_IA32_MCG_CTL:
1925         case MSR_IA32_MCG_STATUS:
1926         case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1927                 return get_msr_mce(vcpu, msr, pdata);
1928         case MSR_K7_CLK_CTL:
1929                 /*
1930                  * Provide expected ramp-up count for K7. All other
1931                  * are set to zero, indicating minimum divisors for
1932                  * every field.
1933                  *
1934                  * This prevents guest kernels on AMD host with CPU
1935                  * type 6, model 8 and higher from exploding due to
1936                  * the rdmsr failing.
1937                  */
1938                 data = 0x20000000;
1939                 break;
1940         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1941                 if (kvm_hv_msr_partition_wide(msr)) {
1942                         int r;
1943                         mutex_lock(&vcpu->kvm->lock);
1944                         r = get_msr_hyperv_pw(vcpu, msr, pdata);
1945                         mutex_unlock(&vcpu->kvm->lock);
1946                         return r;
1947                 } else
1948                         return get_msr_hyperv(vcpu, msr, pdata);
1949                 break;
1950         case MSR_IA32_BBL_CR_CTL3:
1951                 /* This legacy MSR exists but isn't fully documented in current
1952                  * silicon.  It is however accessed by winxp in very narrow
1953                  * scenarios where it sets bit #19, itself documented as
1954                  * a "reserved" bit.  Best effort attempt to source coherent
1955                  * read data here should the balance of the register be
1956                  * interpreted by the guest:
1957                  *
1958                  * L2 cache control register 3: 64GB range, 256KB size,
1959                  * enabled, latency 0x1, configured
1960                  */
1961                 data = 0xbe702111;
1962                 break;
1963         default:
1964                 if (kvm_pmu_msr(vcpu, msr))
1965                         return kvm_pmu_get_msr(vcpu, msr, pdata);
1966                 if (!ignore_msrs) {
1967                         pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
1968                         return 1;
1969                 } else {
1970                         pr_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
1971                         data = 0;
1972                 }
1973                 break;
1974         }
1975         *pdata = data;
1976         return 0;
1977 }
1978 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
1979
1980 /*
1981  * Read or write a bunch of msrs. All parameters are kernel addresses.
1982  *
1983  * @return number of msrs set successfully.
1984  */
1985 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
1986                     struct kvm_msr_entry *entries,
1987                     int (*do_msr)(struct kvm_vcpu *vcpu,
1988                                   unsigned index, u64 *data))
1989 {
1990         int i, idx;
1991
1992         idx = srcu_read_lock(&vcpu->kvm->srcu);
1993         for (i = 0; i < msrs->nmsrs; ++i)
1994                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
1995                         break;
1996         srcu_read_unlock(&vcpu->kvm->srcu, idx);
1997
1998         return i;
1999 }
2000
2001 /*
2002  * Read or write a bunch of msrs. Parameters are user addresses.
2003  *
2004  * @return number of msrs set successfully.
2005  */
2006 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2007                   int (*do_msr)(struct kvm_vcpu *vcpu,
2008                                 unsigned index, u64 *data),
2009                   int writeback)
2010 {
2011         struct kvm_msrs msrs;
2012         struct kvm_msr_entry *entries;
2013         int r, n;
2014         unsigned size;
2015
2016         r = -EFAULT;
2017         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2018                 goto out;
2019
2020         r = -E2BIG;
2021         if (msrs.nmsrs >= MAX_IO_MSRS)
2022                 goto out;
2023
2024         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2025         entries = memdup_user(user_msrs->entries, size);
2026         if (IS_ERR(entries)) {
2027                 r = PTR_ERR(entries);
2028                 goto out;
2029         }
2030
2031         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2032         if (r < 0)
2033                 goto out_free;
2034
2035         r = -EFAULT;
2036         if (writeback && copy_to_user(user_msrs->entries, entries, size))
2037                 goto out_free;
2038
2039         r = n;
2040
2041 out_free:
2042         kfree(entries);
2043 out:
2044         return r;
2045 }
2046
2047 int kvm_dev_ioctl_check_extension(long ext)
2048 {
2049         int r;
2050
2051         switch (ext) {
2052         case KVM_CAP_IRQCHIP:
2053         case KVM_CAP_HLT:
2054         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2055         case KVM_CAP_SET_TSS_ADDR:
2056         case KVM_CAP_EXT_CPUID:
2057         case KVM_CAP_CLOCKSOURCE:
2058         case KVM_CAP_PIT:
2059         case KVM_CAP_NOP_IO_DELAY:
2060         case KVM_CAP_MP_STATE:
2061         case KVM_CAP_SYNC_MMU:
2062         case KVM_CAP_USER_NMI:
2063         case KVM_CAP_REINJECT_CONTROL:
2064         case KVM_CAP_IRQ_INJECT_STATUS:
2065         case KVM_CAP_ASSIGN_DEV_IRQ:
2066         case KVM_CAP_IRQFD:
2067         case KVM_CAP_IOEVENTFD:
2068         case KVM_CAP_PIT2:
2069         case KVM_CAP_PIT_STATE2:
2070         case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2071         case KVM_CAP_XEN_HVM:
2072         case KVM_CAP_ADJUST_CLOCK:
2073         case KVM_CAP_VCPU_EVENTS:
2074         case KVM_CAP_HYPERV:
2075         case KVM_CAP_HYPERV_VAPIC:
2076         case KVM_CAP_HYPERV_SPIN:
2077         case KVM_CAP_PCI_SEGMENT:
2078         case KVM_CAP_DEBUGREGS:
2079         case KVM_CAP_X86_ROBUST_SINGLESTEP:
2080         case KVM_CAP_XSAVE:
2081         case KVM_CAP_ASYNC_PF:
2082         case KVM_CAP_GET_TSC_KHZ:
2083                 r = 1;
2084                 break;
2085         case KVM_CAP_COALESCED_MMIO:
2086                 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2087                 break;
2088         case KVM_CAP_VAPIC:
2089                 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2090                 break;
2091         case KVM_CAP_NR_VCPUS:
2092                 r = KVM_SOFT_MAX_VCPUS;
2093                 break;
2094         case KVM_CAP_MAX_VCPUS:
2095                 r = KVM_MAX_VCPUS;
2096                 break;
2097         case KVM_CAP_NR_MEMSLOTS:
2098                 r = KVM_MEMORY_SLOTS;
2099                 break;
2100         case KVM_CAP_PV_MMU:    /* obsolete */
2101                 r = 0;
2102                 break;
2103         case KVM_CAP_IOMMU:
2104                 r = iommu_present(&pci_bus_type);
2105                 break;
2106         case KVM_CAP_MCE:
2107                 r = KVM_MAX_MCE_BANKS;
2108                 break;
2109         case KVM_CAP_XCRS:
2110                 r = cpu_has_xsave;
2111                 break;
2112         case KVM_CAP_TSC_CONTROL:
2113                 r = kvm_has_tsc_control;
2114                 break;
2115         case KVM_CAP_TSC_DEADLINE_TIMER:
2116                 r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
2117                 break;
2118         default:
2119                 r = 0;
2120                 break;
2121         }
2122         return r;
2123
2124 }
2125
2126 long kvm_arch_dev_ioctl(struct file *filp,
2127                         unsigned int ioctl, unsigned long arg)
2128 {
2129         void __user *argp = (void __user *)arg;
2130         long r;
2131
2132         switch (ioctl) {
2133         case KVM_GET_MSR_INDEX_LIST: {
2134                 struct kvm_msr_list __user *user_msr_list = argp;
2135                 struct kvm_msr_list msr_list;
2136                 unsigned n;
2137
2138                 r = -EFAULT;
2139                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2140                         goto out;
2141                 n = msr_list.nmsrs;
2142                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
2143                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2144                         goto out;
2145                 r = -E2BIG;
2146                 if (n < msr_list.nmsrs)
2147                         goto out;
2148                 r = -EFAULT;
2149                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2150                                  num_msrs_to_save * sizeof(u32)))
2151                         goto out;
2152                 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2153                                  &emulated_msrs,
2154                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
2155                         goto out;
2156                 r = 0;
2157                 break;
2158         }
2159         case KVM_GET_SUPPORTED_CPUID: {
2160                 struct kvm_cpuid2 __user *cpuid_arg = argp;
2161                 struct kvm_cpuid2 cpuid;
2162
2163                 r = -EFAULT;
2164                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2165                         goto out;
2166                 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
2167                                                       cpuid_arg->entries);
2168                 if (r)
2169                         goto out;
2170
2171                 r = -EFAULT;
2172                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2173                         goto out;
2174                 r = 0;
2175                 break;
2176         }
2177         case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2178                 u64 mce_cap;
2179
2180                 mce_cap = KVM_MCE_CAP_SUPPORTED;
2181                 r = -EFAULT;
2182                 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2183                         goto out;
2184                 r = 0;
2185                 break;
2186         }
2187         default:
2188                 r = -EINVAL;
2189         }
2190 out:
2191         return r;
2192 }
2193
2194 static void wbinvd_ipi(void *garbage)
2195 {
2196         wbinvd();
2197 }
2198
2199 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2200 {
2201         return vcpu->kvm->arch.iommu_domain &&
2202                 !(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY);
2203 }
2204
2205 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2206 {
2207         /* Address WBINVD may be executed by guest */
2208         if (need_emulate_wbinvd(vcpu)) {
2209                 if (kvm_x86_ops->has_wbinvd_exit())
2210                         cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2211                 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2212                         smp_call_function_single(vcpu->cpu,
2213                                         wbinvd_ipi, NULL, 1);
2214         }
2215
2216         kvm_x86_ops->vcpu_load(vcpu, cpu);
2217         if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2218                 /* Make sure TSC doesn't go backwards */
2219                 s64 tsc_delta;
2220                 u64 tsc;
2221
2222                 tsc = kvm_x86_ops->read_l1_tsc(vcpu);
2223                 tsc_delta = !vcpu->arch.last_guest_tsc ? 0 :
2224                              tsc - vcpu->arch.last_guest_tsc;
2225
2226                 if (tsc_delta < 0)
2227                         mark_tsc_unstable("KVM discovered backwards TSC");
2228                 if (check_tsc_unstable()) {
2229                         kvm_x86_ops->adjust_tsc_offset(vcpu, -tsc_delta);
2230                         vcpu->arch.tsc_catchup = 1;
2231                 }
2232                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2233                 if (vcpu->cpu != cpu)
2234                         kvm_migrate_timers(vcpu);
2235                 vcpu->cpu = cpu;
2236         }
2237
2238         accumulate_steal_time(vcpu);
2239         kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2240 }
2241
2242 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2243 {
2244         kvm_x86_ops->vcpu_put(vcpu);
2245         kvm_put_guest_fpu(vcpu);
2246         vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu);
2247 }
2248
2249 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2250                                     struct kvm_lapic_state *s)
2251 {
2252         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2253
2254         return 0;
2255 }
2256
2257 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2258                                     struct kvm_lapic_state *s)
2259 {
2260         memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
2261         kvm_apic_post_state_restore(vcpu);
2262         update_cr8_intercept(vcpu);
2263
2264         return 0;
2265 }
2266
2267 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2268                                     struct kvm_interrupt *irq)
2269 {
2270         if (irq->irq < 0 || irq->irq >= 256)
2271                 return -EINVAL;
2272         if (irqchip_in_kernel(vcpu->kvm))
2273                 return -ENXIO;
2274
2275         kvm_queue_interrupt(vcpu, irq->irq, false);
2276         kvm_make_request(KVM_REQ_EVENT, vcpu);
2277
2278         return 0;
2279 }
2280
2281 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2282 {
2283         kvm_inject_nmi(vcpu);
2284
2285         return 0;
2286 }
2287
2288 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2289                                            struct kvm_tpr_access_ctl *tac)
2290 {
2291         if (tac->flags)
2292                 return -EINVAL;
2293         vcpu->arch.tpr_access_reporting = !!tac->enabled;
2294         return 0;
2295 }
2296
2297 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2298                                         u64 mcg_cap)
2299 {
2300         int r;
2301         unsigned bank_num = mcg_cap & 0xff, bank;
2302
2303         r = -EINVAL;
2304         if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2305                 goto out;
2306         if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2307                 goto out;
2308         r = 0;
2309         vcpu->arch.mcg_cap = mcg_cap;
2310         /* Init IA32_MCG_CTL to all 1s */
2311         if (mcg_cap & MCG_CTL_P)
2312                 vcpu->arch.mcg_ctl = ~(u64)0;
2313         /* Init IA32_MCi_CTL to all 1s */
2314         for (bank = 0; bank < bank_num; bank++)
2315                 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2316 out:
2317         return r;
2318 }
2319
2320 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2321                                       struct kvm_x86_mce *mce)
2322 {
2323         u64 mcg_cap = vcpu->arch.mcg_cap;
2324         unsigned bank_num = mcg_cap & 0xff;
2325         u64 *banks = vcpu->arch.mce_banks;
2326
2327         if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2328                 return -EINVAL;
2329         /*
2330          * if IA32_MCG_CTL is not all 1s, the uncorrected error
2331          * reporting is disabled
2332          */
2333         if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2334             vcpu->arch.mcg_ctl != ~(u64)0)
2335                 return 0;
2336         banks += 4 * mce->bank;
2337         /*
2338          * if IA32_MCi_CTL is not all 1s, the uncorrected error
2339          * reporting is disabled for the bank
2340          */
2341         if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2342                 return 0;
2343         if (mce->status & MCI_STATUS_UC) {
2344                 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2345                     !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2346                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2347                         return 0;
2348                 }
2349                 if (banks[1] & MCI_STATUS_VAL)
2350                         mce->status |= MCI_STATUS_OVER;
2351                 banks[2] = mce->addr;
2352                 banks[3] = mce->misc;
2353                 vcpu->arch.mcg_status = mce->mcg_status;
2354                 banks[1] = mce->status;
2355                 kvm_queue_exception(vcpu, MC_VECTOR);
2356         } else if (!(banks[1] & MCI_STATUS_VAL)
2357                    || !(banks[1] & MCI_STATUS_UC)) {
2358                 if (banks[1] & MCI_STATUS_VAL)
2359                         mce->status |= MCI_STATUS_OVER;
2360                 banks[2] = mce->addr;
2361                 banks[3] = mce->misc;
2362                 banks[1] = mce->status;
2363         } else
2364                 banks[1] |= MCI_STATUS_OVER;
2365         return 0;
2366 }
2367
2368 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2369                                                struct kvm_vcpu_events *events)
2370 {
2371         process_nmi(vcpu);
2372         events->exception.injected =
2373                 vcpu->arch.exception.pending &&
2374                 !kvm_exception_is_soft(vcpu->arch.exception.nr);
2375         events->exception.nr = vcpu->arch.exception.nr;
2376         events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2377         events->exception.pad = 0;
2378         events->exception.error_code = vcpu->arch.exception.error_code;
2379
2380         events->interrupt.injected =
2381                 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
2382         events->interrupt.nr = vcpu->arch.interrupt.nr;
2383         events->interrupt.soft = 0;
2384         events->interrupt.shadow =
2385                 kvm_x86_ops->get_interrupt_shadow(vcpu,
2386                         KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
2387
2388         events->nmi.injected = vcpu->arch.nmi_injected;
2389         events->nmi.pending = vcpu->arch.nmi_pending != 0;
2390         events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
2391         events->nmi.pad = 0;
2392
2393         events->sipi_vector = vcpu->arch.sipi_vector;
2394
2395         events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
2396                          | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2397                          | KVM_VCPUEVENT_VALID_SHADOW);
2398         memset(&events->reserved, 0, sizeof(events->reserved));
2399 }
2400
2401 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
2402                                               struct kvm_vcpu_events *events)
2403 {
2404         if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
2405                               | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2406                               | KVM_VCPUEVENT_VALID_SHADOW))
2407                 return -EINVAL;
2408
2409         process_nmi(vcpu);
2410         vcpu->arch.exception.pending = events->exception.injected;
2411         vcpu->arch.exception.nr = events->exception.nr;
2412         vcpu->arch.exception.has_error_code = events->exception.has_error_code;
2413         vcpu->arch.exception.error_code = events->exception.error_code;
2414
2415         vcpu->arch.interrupt.pending = events->interrupt.injected;
2416         vcpu->arch.interrupt.nr = events->interrupt.nr;
2417         vcpu->arch.interrupt.soft = events->interrupt.soft;
2418         if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
2419                 kvm_x86_ops->set_interrupt_shadow(vcpu,
2420                                                   events->interrupt.shadow);
2421
2422         vcpu->arch.nmi_injected = events->nmi.injected;
2423         if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
2424                 vcpu->arch.nmi_pending = events->nmi.pending;
2425         kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
2426
2427         if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR)
2428                 vcpu->arch.sipi_vector = events->sipi_vector;
2429
2430         kvm_make_request(KVM_REQ_EVENT, vcpu);
2431
2432         return 0;
2433 }
2434
2435 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
2436                                              struct kvm_debugregs *dbgregs)
2437 {
2438         memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
2439         dbgregs->dr6 = vcpu->arch.dr6;
2440         dbgregs->dr7 = vcpu->arch.dr7;
2441         dbgregs->flags = 0;
2442         memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
2443 }
2444
2445 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
2446                                             struct kvm_debugregs *dbgregs)
2447 {
2448         if (dbgregs->flags)
2449                 return -EINVAL;
2450
2451         memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
2452         vcpu->arch.dr6 = dbgregs->dr6;
2453         vcpu->arch.dr7 = dbgregs->dr7;
2454
2455         return 0;
2456 }
2457
2458 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
2459                                          struct kvm_xsave *guest_xsave)
2460 {
2461         if (cpu_has_xsave)
2462                 memcpy(guest_xsave->region,
2463                         &vcpu->arch.guest_fpu.state->xsave,
2464                         xstate_size);
2465         else {
2466                 memcpy(guest_xsave->region,
2467                         &vcpu->arch.guest_fpu.state->fxsave,
2468                         sizeof(struct i387_fxsave_struct));
2469                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
2470                         XSTATE_FPSSE;
2471         }
2472 }
2473
2474 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
2475                                         struct kvm_xsave *guest_xsave)
2476 {
2477         u64 xstate_bv =
2478                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
2479
2480         if (cpu_has_xsave)
2481                 memcpy(&vcpu->arch.guest_fpu.state->xsave,
2482                         guest_xsave->region, xstate_size);
2483         else {
2484                 if (xstate_bv & ~XSTATE_FPSSE)
2485                         return -EINVAL;
2486                 memcpy(&vcpu->arch.guest_fpu.state->fxsave,
2487                         guest_xsave->region, sizeof(struct i387_fxsave_struct));
2488         }
2489         return 0;
2490 }
2491
2492 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
2493                                         struct kvm_xcrs *guest_xcrs)
2494 {
2495         if (!cpu_has_xsave) {
2496                 guest_xcrs->nr_xcrs = 0;
2497                 return;
2498         }
2499
2500         guest_xcrs->nr_xcrs = 1;
2501         guest_xcrs->flags = 0;
2502         guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
2503         guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
2504 }
2505
2506 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
2507                                        struct kvm_xcrs *guest_xcrs)
2508 {
2509         int i, r = 0;
2510
2511         if (!cpu_has_xsave)
2512                 return -EINVAL;
2513
2514         if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
2515                 return -EINVAL;
2516
2517         for (i = 0; i < guest_xcrs->nr_xcrs; i++)
2518                 /* Only support XCR0 currently */
2519                 if (guest_xcrs->xcrs[0].xcr == XCR_XFEATURE_ENABLED_MASK) {
2520                         r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
2521                                 guest_xcrs->xcrs[0].value);
2522                         break;
2523                 }
2524         if (r)
2525                 r = -EINVAL;
2526         return r;
2527 }
2528
2529 long kvm_arch_vcpu_ioctl(struct file *filp,
2530                          unsigned int ioctl, unsigned long arg)
2531 {
2532         struct kvm_vcpu *vcpu = filp->private_data;
2533         void __user *argp = (void __user *)arg;
2534         int r;
2535         union {
2536                 struct kvm_lapic_state *lapic;
2537                 struct kvm_xsave *xsave;
2538                 struct kvm_xcrs *xcrs;
2539                 void *buffer;
2540         } u;
2541
2542         u.buffer = NULL;
2543         switch (ioctl) {
2544         case KVM_GET_LAPIC: {
2545                 r = -EINVAL;
2546                 if (!vcpu->arch.apic)
2547                         goto out;
2548                 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
2549
2550                 r = -ENOMEM;
2551                 if (!u.lapic)
2552                         goto out;
2553                 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
2554                 if (r)
2555                         goto out;
2556                 r = -EFAULT;
2557                 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
2558                         goto out;
2559                 r = 0;
2560                 break;
2561         }
2562         case KVM_SET_LAPIC: {
2563                 r = -EINVAL;
2564                 if (!vcpu->arch.apic)
2565                         goto out;
2566                 u.lapic = memdup_user(argp, sizeof(*u.lapic));
2567                 if (IS_ERR(u.lapic)) {
2568                         r = PTR_ERR(u.lapic);
2569                         goto out;
2570                 }
2571
2572                 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
2573                 if (r)
2574                         goto out;
2575                 r = 0;
2576                 break;
2577         }
2578         case KVM_INTERRUPT: {
2579                 struct kvm_interrupt irq;
2580
2581                 r = -EFAULT;
2582                 if (copy_from_user(&irq, argp, sizeof irq))
2583                         goto out;
2584                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
2585                 if (r)
2586                         goto out;
2587                 r = 0;
2588                 break;
2589         }
2590         case KVM_NMI: {
2591                 r = kvm_vcpu_ioctl_nmi(vcpu);
2592                 if (r)
2593                         goto out;
2594                 r = 0;
2595                 break;
2596         }
2597         case KVM_SET_CPUID: {
2598                 struct kvm_cpuid __user *cpuid_arg = argp;
2599                 struct kvm_cpuid cpuid;
2600
2601                 r = -EFAULT;
2602                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2603                         goto out;
2604                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
2605                 if (r)
2606                         goto out;
2607                 break;
2608         }
2609         case KVM_SET_CPUID2: {
2610                 struct kvm_cpuid2 __user *cpuid_arg = argp;
2611                 struct kvm_cpuid2 cpuid;
2612
2613                 r = -EFAULT;
2614                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2615                         goto out;
2616                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
2617                                               cpuid_arg->entries);
2618                 if (r)
2619                         goto out;
2620                 break;
2621         }
2622         case KVM_GET_CPUID2: {
2623                 struct kvm_cpuid2 __user *cpuid_arg = argp;
2624                 struct kvm_cpuid2 cpuid;
2625
2626                 r = -EFAULT;
2627                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2628                         goto out;
2629                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
2630                                               cpuid_arg->entries);
2631                 if (r)
2632                         goto out;
2633                 r = -EFAULT;
2634                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2635                         goto out;
2636                 r = 0;
2637                 break;
2638         }
2639         case KVM_GET_MSRS:
2640                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
2641                 break;
2642         case KVM_SET_MSRS:
2643                 r = msr_io(vcpu, argp, do_set_msr, 0);
2644                 break;
2645         case KVM_TPR_ACCESS_REPORTING: {
2646                 struct kvm_tpr_access_ctl tac;
2647
2648                 r = -EFAULT;
2649                 if (copy_from_user(&tac, argp, sizeof tac))
2650                         goto out;
2651                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
2652                 if (r)
2653                         goto out;
2654                 r = -EFAULT;
2655                 if (copy_to_user(argp, &tac, sizeof tac))
2656                         goto out;
2657                 r = 0;
2658                 break;
2659         };
2660         case KVM_SET_VAPIC_ADDR: {
2661                 struct kvm_vapic_addr va;
2662
2663                 r = -EINVAL;
2664                 if (!irqchip_in_kernel(vcpu->kvm))
2665                         goto out;
2666                 r = -EFAULT;
2667                 if (copy_from_user(&va, argp, sizeof va))
2668                         goto out;
2669                 r = 0;
2670                 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
2671                 break;
2672         }
2673         case KVM_X86_SETUP_MCE: {
2674                 u64 mcg_cap;
2675
2676                 r = -EFAULT;
2677                 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
2678                         goto out;
2679                 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
2680                 break;
2681         }
2682         case KVM_X86_SET_MCE: {
2683                 struct kvm_x86_mce mce;
2684
2685                 r = -EFAULT;
2686                 if (copy_from_user(&mce, argp, sizeof mce))
2687                         goto out;
2688                 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
2689                 break;
2690         }
2691         case KVM_GET_VCPU_EVENTS: {
2692                 struct kvm_vcpu_events events;
2693
2694                 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
2695
2696                 r = -EFAULT;
2697                 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
2698                         break;
2699                 r = 0;
2700                 break;
2701         }
2702         case KVM_SET_VCPU_EVENTS: {
2703                 struct kvm_vcpu_events events;
2704
2705                 r = -EFAULT;
2706                 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
2707                         break;
2708
2709                 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
2710                 break;
2711         }
2712         case KVM_GET_DEBUGREGS: {
2713                 struct kvm_debugregs dbgregs;
2714
2715                 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
2716
2717                 r = -EFAULT;
2718                 if (copy_to_user(argp, &dbgregs,
2719                                  sizeof(struct kvm_debugregs)))
2720                         break;
2721                 r = 0;
2722                 break;
2723         }
2724         case KVM_SET_DEBUGREGS: {
2725                 struct kvm_debugregs dbgregs;
2726
2727                 r = -EFAULT;
2728                 if (copy_from_user(&dbgregs, argp,
2729                                    sizeof(struct kvm_debugregs)))
2730                         break;
2731
2732                 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
2733                 break;
2734         }
2735         case KVM_GET_XSAVE: {
2736                 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
2737                 r = -ENOMEM;
2738                 if (!u.xsave)
2739                         break;
2740
2741                 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
2742
2743                 r = -EFAULT;
2744                 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
2745                         break;
2746                 r = 0;
2747                 break;
2748         }
2749         case KVM_SET_XSAVE: {
2750                 u.xsave = memdup_user(argp, sizeof(*u.xsave));
2751                 if (IS_ERR(u.xsave)) {
2752                         r = PTR_ERR(u.xsave);
2753                         goto out;
2754                 }
2755
2756                 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
2757                 break;
2758         }
2759         case KVM_GET_XCRS: {
2760                 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
2761                 r = -ENOMEM;
2762                 if (!u.xcrs)
2763                         break;
2764
2765                 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
2766
2767                 r = -EFAULT;
2768                 if (copy_to_user(argp, u.xcrs,
2769                                  sizeof(struct kvm_xcrs)))
2770                         break;
2771                 r = 0;
2772                 break;
2773         }
2774         case KVM_SET_XCRS: {
2775                 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
2776                 if (IS_ERR(u.xcrs)) {
2777                         r = PTR_ERR(u.xcrs);
2778                         goto out;
2779                 }
2780
2781                 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
2782                 break;
2783         }
2784         case KVM_SET_TSC_KHZ: {
2785                 u32 user_tsc_khz;
2786
2787                 r = -EINVAL;
2788                 if (!kvm_has_tsc_control)
2789                         break;
2790
2791                 user_tsc_khz = (u32)arg;
2792
2793                 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
2794                         goto out;
2795
2796                 kvm_x86_ops->set_tsc_khz(vcpu, user_tsc_khz);
2797
2798                 r = 0;
2799                 goto out;
2800         }
2801         case KVM_GET_TSC_KHZ: {
2802                 r = -EIO;
2803                 if (check_tsc_unstable())
2804                         goto out;
2805
2806                 r = vcpu_tsc_khz(vcpu);
2807
2808                 goto out;
2809         }
2810         default:
2811                 r = -EINVAL;
2812         }
2813 out:
2814         kfree(u.buffer);
2815         return r;
2816 }
2817
2818 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
2819 {
2820         int ret;
2821
2822         if (addr > (unsigned int)(-3 * PAGE_SIZE))
2823                 return -1;
2824         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
2825         return ret;
2826 }
2827
2828 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
2829                                               u64 ident_addr)
2830 {
2831         kvm->arch.ept_identity_map_addr = ident_addr;
2832         return 0;
2833 }
2834
2835 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
2836                                           u32 kvm_nr_mmu_pages)
2837 {
2838         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
2839                 return -EINVAL;
2840
2841         mutex_lock(&kvm->slots_lock);
2842         spin_lock(&kvm->mmu_lock);
2843
2844         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
2845         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
2846
2847         spin_unlock(&kvm->mmu_lock);
2848         mutex_unlock(&kvm->slots_lock);
2849         return 0;
2850 }
2851
2852 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
2853 {
2854         return kvm->arch.n_max_mmu_pages;
2855 }
2856
2857 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2858 {
2859         int r;
2860
2861         r = 0;
2862         switch (chip->chip_id) {
2863         case KVM_IRQCHIP_PIC_MASTER:
2864                 memcpy(&chip->chip.pic,
2865                         &pic_irqchip(kvm)->pics[0],
2866                         sizeof(struct kvm_pic_state));
2867                 break;
2868         case KVM_IRQCHIP_PIC_SLAVE:
2869                 memcpy(&chip->chip.pic,
2870                         &pic_irqchip(kvm)->pics[1],
2871                         sizeof(struct kvm_pic_state));
2872                 break;
2873         case KVM_IRQCHIP_IOAPIC:
2874                 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
2875                 break;
2876         default:
2877                 r = -EINVAL;
2878                 break;
2879         }
2880         return r;
2881 }
2882
2883 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2884 {
2885         int r;
2886
2887         r = 0;
2888         switch (chip->chip_id) {
2889         case KVM_IRQCHIP_PIC_MASTER:
2890                 spin_lock(&pic_irqchip(kvm)->lock);
2891                 memcpy(&pic_irqchip(kvm)->pics[0],
2892                         &chip->chip.pic,
2893                         sizeof(struct kvm_pic_state));
2894                 spin_unlock(&pic_irqchip(kvm)->lock);
2895                 break;
2896         case KVM_IRQCHIP_PIC_SLAVE:
2897                 spin_lock(&pic_irqchip(kvm)->lock);
2898                 memcpy(&pic_irqchip(kvm)->pics[1],
2899                         &chip->chip.pic,
2900                         sizeof(struct kvm_pic_state));
2901                 spin_unlock(&pic_irqchip(kvm)->lock);
2902                 break;
2903         case KVM_IRQCHIP_IOAPIC:
2904                 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
2905                 break;
2906         default:
2907                 r = -EINVAL;
2908                 break;
2909         }
2910         kvm_pic_update_irq(pic_irqchip(kvm));
2911         return r;
2912 }
2913
2914 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2915 {
2916         int r = 0;
2917
2918         mutex_lock(&kvm->arch.vpit->pit_state.lock);
2919         memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
2920         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2921         return r;
2922 }
2923
2924 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2925 {
2926         int r = 0;
2927
2928         mutex_lock(&kvm->arch.vpit->pit_state.lock);
2929         memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
2930         kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
2931         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2932         return r;
2933 }
2934
2935 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2936 {
2937         int r = 0;
2938
2939         mutex_lock(&kvm->arch.vpit->pit_state.lock);
2940         memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
2941                 sizeof(ps->channels));
2942         ps->flags = kvm->arch.vpit->pit_state.flags;
2943         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2944         memset(&ps->reserved, 0, sizeof(ps->reserved));
2945         return r;
2946 }
2947
2948 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2949 {
2950         int r = 0, start = 0;
2951         u32 prev_legacy, cur_legacy;
2952         mutex_lock(&kvm->arch.vpit->pit_state.lock);
2953         prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
2954         cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
2955         if (!prev_legacy && cur_legacy)
2956                 start = 1;
2957         memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
2958                sizeof(kvm->arch.vpit->pit_state.channels));
2959         kvm->arch.vpit->pit_state.flags = ps->flags;
2960         kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
2961         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2962         return r;
2963 }
2964
2965 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
2966                                  struct kvm_reinject_control *control)
2967 {
2968         if (!kvm->arch.vpit)
2969                 return -ENXIO;
2970         mutex_lock(&kvm->arch.vpit->pit_state.lock);
2971         kvm->arch.vpit->pit_state.pit_timer.reinject = control->pit_reinject;
2972         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2973         return 0;
2974 }
2975
2976 /**
2977  * write_protect_slot - write protect a slot for dirty logging
2978  * @kvm: the kvm instance
2979  * @memslot: the slot we protect
2980  * @dirty_bitmap: the bitmap indicating which pages are dirty
2981  * @nr_dirty_pages: the number of dirty pages
2982  *
2983  * We have two ways to find all sptes to protect:
2984  * 1. Use kvm_mmu_slot_remove_write_access() which walks all shadow pages and
2985  *    checks ones that have a spte mapping a page in the slot.
2986  * 2. Use kvm_mmu_rmap_write_protect() for each gfn found in the bitmap.
2987  *
2988  * Generally speaking, if there are not so many dirty pages compared to the
2989  * number of shadow pages, we should use the latter.
2990  *
2991  * Note that letting others write into a page marked dirty in the old bitmap
2992  * by using the remaining tlb entry is not a problem.  That page will become
2993  * write protected again when we flush the tlb and then be reported dirty to
2994  * the user space by copying the old bitmap.
2995  */
2996 static void write_protect_slot(struct kvm *kvm,
2997                                struct kvm_memory_slot *memslot,
2998                                unsigned long *dirty_bitmap,
2999                                unsigned long nr_dirty_pages)
3000 {
3001         /* Not many dirty pages compared to # of shadow pages. */
3002         if (nr_dirty_pages < kvm->arch.n_used_mmu_pages) {
3003                 unsigned long gfn_offset;
3004
3005                 for_each_set_bit(gfn_offset, dirty_bitmap, memslot->npages) {
3006                         unsigned long gfn = memslot->base_gfn + gfn_offset;
3007
3008                         spin_lock(&kvm->mmu_lock);
3009                         kvm_mmu_rmap_write_protect(kvm, gfn, memslot);
3010                         spin_unlock(&kvm->mmu_lock);
3011                 }
3012                 kvm_flush_remote_tlbs(kvm);
3013         } else {
3014                 spin_lock(&kvm->mmu_lock);
3015                 kvm_mmu_slot_remove_write_access(kvm, memslot->id);
3016                 spin_unlock(&kvm->mmu_lock);
3017         }
3018 }
3019
3020 /*
3021  * Get (and clear) the dirty memory log for a memory slot.
3022  */
3023 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
3024                                       struct kvm_dirty_log *log)
3025 {
3026         int r;
3027         struct kvm_memory_slot *memslot;
3028         unsigned long n, nr_dirty_pages;
3029
3030         mutex_lock(&kvm->slots_lock);
3031
3032         r = -EINVAL;
3033         if (log->slot >= KVM_MEMORY_SLOTS)
3034                 goto out;
3035
3036         memslot = id_to_memslot(kvm->memslots, log->slot);
3037         r = -ENOENT;
3038         if (!memslot->dirty_bitmap)
3039                 goto out;
3040
3041         n = kvm_dirty_bitmap_bytes(memslot);
3042         nr_dirty_pages = memslot->nr_dirty_pages;
3043
3044         /* If nothing is dirty, don't bother messing with page tables. */
3045         if (nr_dirty_pages) {
3046                 struct kvm_memslots *slots, *old_slots;
3047                 unsigned long *dirty_bitmap, *dirty_bitmap_head;
3048
3049                 dirty_bitmap = memslot->dirty_bitmap;
3050                 dirty_bitmap_head = memslot->dirty_bitmap_head;
3051                 if (dirty_bitmap == dirty_bitmap_head)
3052                         dirty_bitmap_head += n / sizeof(long);
3053                 memset(dirty_bitmap_head, 0, n);
3054
3055                 r = -ENOMEM;
3056                 slots = kmemdup(kvm->memslots, sizeof(*kvm->memslots), GFP_KERNEL);
3057                 if (!slots)
3058                         goto out;
3059
3060                 memslot = id_to_memslot(slots, log->slot);
3061                 memslot->nr_dirty_pages = 0;
3062                 memslot->dirty_bitmap = dirty_bitmap_head;
3063                 update_memslots(slots, NULL);
3064
3065                 old_slots = kvm->memslots;
3066                 rcu_assign_pointer(kvm->memslots, slots);
3067                 synchronize_srcu_expedited(&kvm->srcu);
3068                 kfree(old_slots);
3069
3070                 write_protect_slot(kvm, memslot, dirty_bitmap, nr_dirty_pages);
3071
3072                 r = -EFAULT;
3073                 if (copy_to_user(log->dirty_bitmap, dirty_bitmap, n))
3074                         goto out;
3075         } else {
3076                 r = -EFAULT;
3077                 if (clear_user(log->dirty_bitmap, n))
3078                         goto out;
3079         }
3080
3081         r = 0;
3082 out:
3083         mutex_unlock(&kvm->slots_lock);
3084         return r;
3085 }
3086
3087 long kvm_arch_vm_ioctl(struct file *filp,
3088                        unsigned int ioctl, unsigned long arg)
3089 {
3090         struct kvm *kvm = filp->private_data;
3091         void __user *argp = (void __user *)arg;
3092         int r = -ENOTTY;
3093         /*
3094          * This union makes it completely explicit to gcc-3.x
3095          * that these two variables' stack usage should be
3096          * combined, not added together.
3097          */
3098         union {
3099                 struct kvm_pit_state ps;
3100                 struct kvm_pit_state2 ps2;
3101                 struct kvm_pit_config pit_config;
3102         } u;
3103
3104         switch (ioctl) {
3105         case KVM_SET_TSS_ADDR:
3106                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3107                 if (r < 0)
3108                         goto out;
3109                 break;
3110         case KVM_SET_IDENTITY_MAP_ADDR: {
3111                 u64 ident_addr;
3112
3113                 r = -EFAULT;
3114                 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3115                         goto out;
3116                 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3117                 if (r < 0)
3118                         goto out;
3119                 break;
3120         }
3121         case KVM_SET_NR_MMU_PAGES:
3122                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3123                 if (r)
3124                         goto out;
3125                 break;
3126         case KVM_GET_NR_MMU_PAGES:
3127                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3128                 break;
3129         case KVM_CREATE_IRQCHIP: {
3130                 struct kvm_pic *vpic;
3131
3132                 mutex_lock(&kvm->lock);
3133                 r = -EEXIST;
3134                 if (kvm->arch.vpic)
3135                         goto create_irqchip_unlock;
3136                 r = -ENOMEM;
3137                 vpic = kvm_create_pic(kvm);
3138                 if (vpic) {
3139                         r = kvm_ioapic_init(kvm);
3140                         if (r) {
3141                                 mutex_lock(&kvm->slots_lock);
3142                                 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3143                                                           &vpic->dev_master);
3144                                 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3145                                                           &vpic->dev_slave);
3146                                 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3147                                                           &vpic->dev_eclr);
3148                                 mutex_unlock(&kvm->slots_lock);
3149                                 kfree(vpic);
3150                                 goto create_irqchip_unlock;
3151                         }
3152                 } else
3153                         goto create_irqchip_unlock;
3154                 smp_wmb();
3155                 kvm->arch.vpic = vpic;
3156                 smp_wmb();
3157                 r = kvm_setup_default_irq_routing(kvm);
3158                 if (r) {
3159                         mutex_lock(&kvm->slots_lock);
3160                         mutex_lock(&kvm->irq_lock);
3161                         kvm_ioapic_destroy(kvm);
3162                         kvm_destroy_pic(kvm);
3163                         mutex_unlock(&kvm->irq_lock);
3164                         mutex_unlock(&kvm->slots_lock);
3165                 }
3166         create_irqchip_unlock:
3167                 mutex_unlock(&kvm->lock);
3168                 break;
3169         }
3170         case KVM_CREATE_PIT:
3171                 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3172                 goto create_pit;
3173         case KVM_CREATE_PIT2:
3174                 r = -EFAULT;
3175                 if (copy_from_user(&u.pit_config, argp,
3176                                    sizeof(struct kvm_pit_config)))
3177                         goto out;
3178         create_pit:
3179                 mutex_lock(&kvm->slots_lock);
3180                 r = -EEXIST;
3181                 if (kvm->arch.vpit)
3182                         goto create_pit_unlock;
3183                 r = -ENOMEM;
3184                 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3185                 if (kvm->arch.vpit)
3186                         r = 0;
3187         create_pit_unlock:
3188                 mutex_unlock(&kvm->slots_lock);
3189                 break;
3190         case KVM_IRQ_LINE_STATUS:
3191         case KVM_IRQ_LINE: {
3192                 struct kvm_irq_level irq_event;
3193
3194                 r = -EFAULT;
3195                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
3196                         goto out;
3197                 r = -ENXIO;
3198                 if (irqchip_in_kernel(kvm)) {
3199                         __s32 status;
3200                         status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3201                                         irq_event.irq, irq_event.level);
3202                         if (ioctl == KVM_IRQ_LINE_STATUS) {
3203                                 r = -EFAULT;
3204                                 irq_event.status = status;
3205                                 if (copy_to_user(argp, &irq_event,
3206                                                         sizeof irq_event))
3207                                         goto out;
3208                         }
3209                         r = 0;
3210                 }
3211                 break;
3212         }
3213         case KVM_GET_IRQCHIP: {
3214                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3215                 struct kvm_irqchip *chip;
3216
3217                 chip = memdup_user(argp, sizeof(*chip));
3218                 if (IS_ERR(chip)) {
3219                         r = PTR_ERR(chip);
3220                         goto out;
3221                 }
3222
3223                 r = -ENXIO;
3224                 if (!irqchip_in_kernel(kvm))
3225                         goto get_irqchip_out;
3226                 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3227                 if (r)
3228                         goto get_irqchip_out;
3229                 r = -EFAULT;
3230                 if (copy_to_user(argp, chip, sizeof *chip))
3231                         goto get_irqchip_out;
3232                 r = 0;
3233         get_irqchip_out:
3234                 kfree(chip);
3235                 if (r)
3236                         goto out;
3237                 break;
3238         }
3239         case KVM_SET_IRQCHIP: {
3240                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3241                 struct kvm_irqchip *chip;
3242
3243                 chip = memdup_user(argp, sizeof(*chip));
3244                 if (IS_ERR(chip)) {
3245                         r = PTR_ERR(chip);
3246                         goto out;
3247                 }
3248
3249                 r = -ENXIO;
3250                 if (!irqchip_in_kernel(kvm))
3251                         goto set_irqchip_out;
3252                 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3253                 if (r)
3254                         goto set_irqchip_out;
3255                 r = 0;
3256         set_irqchip_out:
3257                 kfree(chip);
3258                 if (r)
3259                         goto out;
3260                 break;
3261         }
3262         case KVM_GET_PIT: {
3263                 r = -EFAULT;
3264                 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
3265                         goto out;
3266                 r = -ENXIO;
3267                 if (!kvm->arch.vpit)
3268                         goto out;
3269                 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
3270                 if (r)
3271                         goto out;
3272                 r = -EFAULT;
3273                 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
3274                         goto out;
3275                 r = 0;
3276                 break;
3277         }
3278         case KVM_SET_PIT: {
3279                 r = -EFAULT;
3280                 if (copy_from_user(&u.ps, argp, sizeof u.ps))
3281                         goto out;
3282                 r = -ENXIO;
3283                 if (!kvm->arch.vpit)
3284                         goto out;
3285                 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
3286                 if (r)
3287                         goto out;
3288                 r = 0;
3289                 break;
3290         }
3291         case KVM_GET_PIT2: {
3292                 r = -ENXIO;
3293                 if (!kvm->arch.vpit)
3294                         goto out;
3295                 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
3296                 if (r)
3297                         goto out;
3298                 r = -EFAULT;
3299                 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
3300                         goto out;
3301                 r = 0;
3302                 break;
3303         }
3304         case KVM_SET_PIT2: {
3305                 r = -EFAULT;
3306                 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
3307                         goto out;
3308                 r = -ENXIO;
3309                 if (!kvm->arch.vpit)
3310                         goto out;
3311                 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
3312                 if (r)
3313                         goto out;
3314                 r = 0;
3315                 break;
3316         }
3317         case KVM_REINJECT_CONTROL: {
3318                 struct kvm_reinject_control control;
3319                 r =  -EFAULT;
3320                 if (copy_from_user(&control, argp, sizeof(control)))
3321                         goto out;
3322                 r = kvm_vm_ioctl_reinject(kvm, &control);
3323                 if (r)
3324                         goto out;
3325                 r = 0;
3326                 break;
3327         }
3328         case KVM_XEN_HVM_CONFIG: {
3329                 r = -EFAULT;
3330                 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
3331                                    sizeof(struct kvm_xen_hvm_config)))
3332                         goto out;
3333                 r = -EINVAL;
3334                 if (kvm->arch.xen_hvm_config.flags)
3335                         goto out;
3336                 r = 0;
3337                 break;
3338         }
3339         case KVM_SET_CLOCK: {
3340                 struct kvm_clock_data user_ns;
3341                 u64 now_ns;
3342                 s64 delta;
3343
3344                 r = -EFAULT;
3345                 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
3346                         goto out;
3347
3348                 r = -EINVAL;
3349                 if (user_ns.flags)
3350                         goto out;
3351
3352                 r = 0;
3353                 local_irq_disable();
3354                 now_ns = get_kernel_ns();
3355                 delta = user_ns.clock - now_ns;
3356                 local_irq_enable();
3357                 kvm->arch.kvmclock_offset = delta;
3358                 break;
3359         }
3360         case KVM_GET_CLOCK: {
3361                 struct kvm_clock_data user_ns;
3362                 u64 now_ns;
3363
3364                 local_irq_disable();
3365                 now_ns = get_kernel_ns();
3366                 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
3367                 local_irq_enable();
3368                 user_ns.flags = 0;
3369                 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
3370
3371                 r = -EFAULT;
3372                 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
3373                         goto out;
3374                 r = 0;
3375                 break;
3376         }
3377
3378         default:
3379                 ;
3380         }
3381 out:
3382         return r;
3383 }
3384
3385 static void kvm_init_msr_list(void)
3386 {
3387         u32 dummy[2];
3388         unsigned i, j;
3389
3390         /* skip the first msrs in the list. KVM-specific */
3391         for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
3392                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
3393                         continue;
3394                 if (j < i)
3395                         msrs_to_save[j] = msrs_to_save[i];
3396                 j++;
3397         }
3398         num_msrs_to_save = j;
3399 }
3400
3401 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
3402                            const void *v)
3403 {
3404         int handled = 0;
3405         int n;
3406
3407         do {
3408                 n = min(len, 8);
3409                 if (!(vcpu->arch.apic &&
3410                       !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, n, v))
3411                     && kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
3412                         break;
3413                 handled += n;
3414                 addr += n;
3415                 len -= n;
3416                 v += n;
3417         } while (len);
3418
3419         return handled;
3420 }
3421
3422 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
3423 {
3424         int handled = 0;
3425         int n;
3426
3427         do {
3428                 n = min(len, 8);
3429                 if (!(vcpu->arch.apic &&
3430                       !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, n, v))
3431                     && kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
3432                         break;
3433                 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
3434                 handled += n;
3435                 addr += n;
3436                 len -= n;
3437                 v += n;
3438         } while (len);
3439
3440         return handled;
3441 }
3442
3443 static void kvm_set_segment(struct kvm_vcpu *vcpu,
3444                         struct kvm_segment *var, int seg)
3445 {
3446         kvm_x86_ops->set_segment(vcpu, var, seg);
3447 }
3448
3449 void kvm_get_segment(struct kvm_vcpu *vcpu,
3450                      struct kvm_segment *var, int seg)
3451 {
3452         kvm_x86_ops->get_segment(vcpu, var, seg);
3453 }
3454
3455 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
3456 {
3457         gpa_t t_gpa;
3458         struct x86_exception exception;
3459
3460         BUG_ON(!mmu_is_nested(vcpu));
3461
3462         /* NPT walks are always user-walks */
3463         access |= PFERR_USER_MASK;
3464         t_gpa  = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, &exception);
3465
3466         return t_gpa;
3467 }
3468
3469 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
3470                               struct x86_exception *exception)
3471 {
3472         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3473         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3474 }
3475
3476  gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
3477                                 struct x86_exception *exception)
3478 {
3479         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3480         access |= PFERR_FETCH_MASK;
3481         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3482 }
3483
3484 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
3485                                struct x86_exception *exception)
3486 {
3487         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3488         access |= PFERR_WRITE_MASK;
3489         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3490 }
3491
3492 /* uses this to access any guest's mapped memory without checking CPL */
3493 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
3494                                 struct x86_exception *exception)
3495 {
3496         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
3497 }
3498
3499 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
3500                                       struct kvm_vcpu *vcpu, u32 access,
3501                                       struct x86_exception *exception)
3502 {
3503         void *data = val;
3504         int r = X86EMUL_CONTINUE;
3505
3506         while (bytes) {
3507                 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
3508                                                             exception);
3509                 unsigned offset = addr & (PAGE_SIZE-1);
3510                 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
3511                 int ret;
3512
3513                 if (gpa == UNMAPPED_GVA)
3514                         return X86EMUL_PROPAGATE_FAULT;
3515                 ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
3516                 if (ret < 0) {
3517                         r = X86EMUL_IO_NEEDED;
3518                         goto out;
3519                 }
3520
3521                 bytes -= toread;
3522                 data += toread;
3523                 addr += toread;
3524         }
3525 out:
3526         return r;
3527 }
3528
3529 /* used for instruction fetching */
3530 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
3531                                 gva_t addr, void *val, unsigned int bytes,
3532                                 struct x86_exception *exception)
3533 {
3534         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3535         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3536
3537         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
3538                                           access | PFERR_FETCH_MASK,
3539                                           exception);
3540 }
3541
3542 int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
3543                                gva_t addr, void *val, unsigned int bytes,
3544                                struct x86_exception *exception)
3545 {
3546         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3547         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3548
3549         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
3550                                           exception);
3551 }
3552 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
3553
3554 static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
3555                                       gva_t addr, void *val, unsigned int bytes,
3556                                       struct x86_exception *exception)
3557 {
3558         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3559         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
3560 }
3561
3562 int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
3563                                        gva_t addr, void *val,
3564                                        unsigned int bytes,
3565                                        struct x86_exception *exception)
3566 {
3567         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3568         void *data = val;
3569         int r = X86EMUL_CONTINUE;
3570
3571         while (bytes) {
3572                 gpa_t gpa =  vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
3573                                                              PFERR_WRITE_MASK,
3574                                                              exception);
3575                 unsigned offset = addr & (PAGE_SIZE-1);
3576                 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
3577                 int ret;
3578
3579                 if (gpa == UNMAPPED_GVA)
3580                         return X86EMUL_PROPAGATE_FAULT;
3581                 ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
3582                 if (ret < 0) {
3583                         r = X86EMUL_IO_NEEDED;
3584                         goto out;
3585                 }
3586
3587                 bytes -= towrite;
3588                 data += towrite;
3589                 addr += towrite;
3590         }
3591 out:
3592         return r;
3593 }
3594 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
3595
3596 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
3597                                 gpa_t *gpa, struct x86_exception *exception,
3598                                 bool write)
3599 {
3600         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3601
3602         if (vcpu_match_mmio_gva(vcpu, gva) &&
3603                   check_write_user_access(vcpu, write, access,
3604                   vcpu->arch.access)) {
3605                 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
3606                                         (gva & (PAGE_SIZE - 1));
3607                 trace_vcpu_match_mmio(gva, *gpa, write, false);
3608                 return 1;
3609         }
3610
3611         if (write)
3612                 access |= PFERR_WRITE_MASK;
3613
3614         *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3615
3616         if (*gpa == UNMAPPED_GVA)
3617                 return -1;
3618
3619         /* For APIC access vmexit */
3620         if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3621                 return 1;
3622
3623         if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
3624                 trace_vcpu_match_mmio(gva, *gpa, write, true);
3625                 return 1;
3626         }
3627
3628         return 0;
3629 }
3630
3631 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
3632                         const void *val, int bytes)
3633 {
3634         int ret;
3635
3636         ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
3637         if (ret < 0)
3638                 return 0;
3639         kvm_mmu_pte_write(vcpu, gpa, val, bytes);
3640         return 1;
3641 }
3642
3643 struct read_write_emulator_ops {
3644         int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
3645                                   int bytes);
3646         int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
3647                                   void *val, int bytes);
3648         int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
3649                                int bytes, void *val);
3650         int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
3651                                     void *val, int bytes);
3652         bool write;
3653 };
3654
3655 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
3656 {
3657         if (vcpu->mmio_read_completed) {
3658                 memcpy(val, vcpu->mmio_data, bytes);
3659                 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
3660                                vcpu->mmio_phys_addr, *(u64 *)val);
3661                 vcpu->mmio_read_completed = 0;
3662                 return 1;
3663         }
3664
3665         return 0;
3666 }
3667
3668 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
3669                         void *val, int bytes)
3670 {
3671         return !kvm_read_guest(vcpu->kvm, gpa, val, bytes);
3672 }
3673
3674 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
3675                          void *val, int bytes)
3676 {
3677         return emulator_write_phys(vcpu, gpa, val, bytes);
3678 }
3679
3680 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
3681 {
3682         trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
3683         return vcpu_mmio_write(vcpu, gpa, bytes, val);
3684 }
3685
3686 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
3687                           void *val, int bytes)
3688 {
3689         trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
3690         return X86EMUL_IO_NEEDED;
3691 }
3692
3693 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
3694                            void *val, int bytes)
3695 {
3696         memcpy(vcpu->mmio_data, val, bytes);
3697         memcpy(vcpu->run->mmio.data, vcpu->mmio_data, 8);
3698         return X86EMUL_CONTINUE;
3699 }
3700
3701 static struct read_write_emulator_ops read_emultor = {
3702         .read_write_prepare = read_prepare,
3703         .read_write_emulate = read_emulate,
3704         .read_write_mmio = vcpu_mmio_read,
3705         .read_write_exit_mmio = read_exit_mmio,
3706 };
3707
3708 static struct read_write_emulator_ops write_emultor = {
3709         .read_write_emulate = write_emulate,
3710         .read_write_mmio = write_mmio,
3711         .read_write_exit_mmio = write_exit_mmio,
3712         .write = true,
3713 };
3714
3715 static int emulator_read_write_onepage(unsigned long addr, void *val,
3716                                        unsigned int bytes,
3717                                        struct x86_exception *exception,
3718                                        struct kvm_vcpu *vcpu,
3719                                        struct read_write_emulator_ops *ops)
3720 {
3721         gpa_t gpa;
3722         int handled, ret;
3723         bool write = ops->write;
3724
3725         if (ops->read_write_prepare &&
3726                   ops->read_write_prepare(vcpu, val, bytes))
3727                 return X86EMUL_CONTINUE;
3728
3729         ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
3730
3731         if (ret < 0)
3732                 return X86EMUL_PROPAGATE_FAULT;
3733
3734         /* For APIC access vmexit */
3735         if (ret)
3736                 goto mmio;
3737
3738         if (ops->read_write_emulate(vcpu, gpa, val, bytes))
3739                 return X86EMUL_CONTINUE;
3740
3741 mmio:
3742         /*
3743          * Is this MMIO handled locally?
3744          */
3745         handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
3746         if (handled == bytes)
3747                 return X86EMUL_CONTINUE;
3748
3749         gpa += handled;
3750         bytes -= handled;
3751         val += handled;
3752
3753         vcpu->mmio_needed = 1;
3754         vcpu->run->exit_reason = KVM_EXIT_MMIO;
3755         vcpu->run->mmio.phys_addr = vcpu->mmio_phys_addr = gpa;
3756         vcpu->mmio_size = bytes;
3757         vcpu->run->mmio.len = min(vcpu->mmio_size, 8);
3758         vcpu->run->mmio.is_write = vcpu->mmio_is_write = write;
3759         vcpu->mmio_index = 0;
3760
3761         return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
3762 }
3763
3764 int emulator_read_write(struct x86_emulate_ctxt *ctxt, unsigned long addr,
3765                         void *val, unsigned int bytes,
3766                         struct x86_exception *exception,
3767                         struct read_write_emulator_ops *ops)
3768 {
3769         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3770
3771         /* Crossing a page boundary? */
3772         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
3773                 int rc, now;
3774
3775                 now = -addr & ~PAGE_MASK;
3776                 rc = emulator_read_write_onepage(addr, val, now, exception,
3777                                                  vcpu, ops);
3778
3779                 if (rc != X86EMUL_CONTINUE)
3780                         return rc;
3781                 addr += now;
3782                 val += now;
3783                 bytes -= now;
3784         }
3785
3786         return emulator_read_write_onepage(addr, val, bytes, exception,
3787                                            vcpu, ops);
3788 }
3789
3790 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
3791                                   unsigned long addr,
3792                                   void *val,
3793                                   unsigned int bytes,
3794                                   struct x86_exception *exception)
3795 {
3796         return emulator_read_write(ctxt, addr, val, bytes,
3797                                    exception, &read_emultor);
3798 }
3799
3800 int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
3801                             unsigned long addr,
3802                             const void *val,
3803                             unsigned int bytes,
3804                             struct x86_exception *exception)
3805 {
3806         return emulator_read_write(ctxt, addr, (void *)val, bytes,
3807                                    exception, &write_emultor);
3808 }
3809
3810 #define CMPXCHG_TYPE(t, ptr, old, new) \
3811         (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
3812
3813 #ifdef CONFIG_X86_64
3814 #  define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
3815 #else
3816 #  define CMPXCHG64(ptr, old, new) \
3817         (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
3818 #endif
3819
3820 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
3821                                      unsigned long addr,
3822                                      const void *old,
3823                                      const void *new,
3824                                      unsigned int bytes,
3825                                      struct x86_exception *exception)
3826 {
3827         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3828         gpa_t gpa;
3829         struct page *page;
3830         char *kaddr;
3831         bool exchanged;
3832
3833         /* guests cmpxchg8b have to be emulated atomically */
3834         if (bytes > 8 || (bytes & (bytes - 1)))
3835                 goto emul_write;
3836
3837         gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
3838
3839         if (gpa == UNMAPPED_GVA ||
3840             (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3841                 goto emul_write;
3842
3843         if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
3844                 goto emul_write;
3845
3846         page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
3847         if (is_error_page(page)) {
3848                 kvm_release_page_clean(page);
3849                 goto emul_write;
3850         }
3851
3852         kaddr = kmap_atomic(page);
3853         kaddr += offset_in_page(gpa);
3854         switch (bytes) {
3855         case 1:
3856                 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
3857                 break;
3858         case 2:
3859                 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
3860                 break;
3861         case 4:
3862                 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
3863                 break;
3864         case 8:
3865                 exchanged = CMPXCHG64(kaddr, old, new);
3866                 break;
3867         default:
3868                 BUG();
3869         }
3870         kunmap_atomic(kaddr);
3871         kvm_release_page_dirty(page);
3872
3873         if (!exchanged)
3874                 return X86EMUL_CMPXCHG_FAILED;
3875
3876         kvm_mmu_pte_write(vcpu, gpa, new, bytes);
3877
3878         return X86EMUL_CONTINUE;
3879
3880 emul_write:
3881         printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
3882
3883         return emulator_write_emulated(ctxt, addr, new, bytes, exception);
3884 }
3885
3886 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
3887 {
3888         /* TODO: String I/O for in kernel device */
3889         int r;
3890
3891         if (vcpu->arch.pio.in)
3892                 r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
3893                                     vcpu->arch.pio.size, pd);
3894         else
3895                 r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
3896                                      vcpu->arch.pio.port, vcpu->arch.pio.size,
3897                                      pd);
3898         return r;
3899 }
3900
3901 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
3902                                unsigned short port, void *val,
3903                                unsigned int count, bool in)
3904 {
3905         trace_kvm_pio(!in, port, size, count);
3906
3907         vcpu->arch.pio.port = port;
3908         vcpu->arch.pio.in = in;
3909         vcpu->arch.pio.count  = count;
3910         vcpu->arch.pio.size = size;
3911
3912         if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
3913                 vcpu->arch.pio.count = 0;
3914                 return 1;
3915         }
3916
3917         vcpu->run->exit_reason = KVM_EXIT_IO;
3918         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
3919         vcpu->run->io.size = size;
3920         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
3921         vcpu->run->io.count = count;
3922         vcpu->run->io.port = port;
3923
3924         return 0;
3925 }
3926
3927 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
3928                                     int size, unsigned short port, void *val,
3929                                     unsigned int count)
3930 {
3931         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3932         int ret;
3933
3934         if (vcpu->arch.pio.count)
3935                 goto data_avail;
3936
3937         ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
3938         if (ret) {
3939 data_avail:
3940                 memcpy(val, vcpu->arch.pio_data, size * count);
3941                 vcpu->arch.pio.count = 0;
3942                 return 1;
3943         }
3944
3945         return 0;
3946 }
3947
3948 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
3949                                      int size, unsigned short port,
3950                                      const void *val, unsigned int count)
3951 {
3952         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3953
3954         memcpy(vcpu->arch.pio_data, val, size * count);
3955         return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
3956 }
3957
3958 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
3959 {
3960         return kvm_x86_ops->get_segment_base(vcpu, seg);
3961 }
3962
3963 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
3964 {
3965         kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
3966 }
3967
3968 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
3969 {
3970         if (!need_emulate_wbinvd(vcpu))
3971                 return X86EMUL_CONTINUE;
3972
3973         if (kvm_x86_ops->has_wbinvd_exit()) {
3974                 int cpu = get_cpu();
3975
3976                 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3977                 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
3978                                 wbinvd_ipi, NULL, 1);
3979                 put_cpu();
3980                 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
3981         } else
3982                 wbinvd();
3983         return X86EMUL_CONTINUE;
3984 }
3985 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
3986
3987 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
3988 {
3989         kvm_emulate_wbinvd(emul_to_vcpu(ctxt));
3990 }
3991
3992 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
3993 {
3994         return _kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
3995 }
3996
3997 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
3998 {
3999
4000         return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
4001 }
4002
4003 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
4004 {
4005         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
4006 }
4007
4008 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
4009 {
4010         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4011         unsigned long value;
4012
4013         switch (cr) {
4014         case 0:
4015                 value = kvm_read_cr0(vcpu);
4016                 break;
4017         case 2:
4018                 value = vcpu->arch.cr2;
4019                 break;
4020         case 3:
4021                 value = kvm_read_cr3(vcpu);
4022                 break;
4023         case 4:
4024                 value = kvm_read_cr4(vcpu);
4025                 break;
4026         case 8:
4027                 value = kvm_get_cr8(vcpu);
4028                 break;
4029         default:
4030                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
4031                 return 0;
4032         }
4033
4034         return value;
4035 }
4036
4037 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
4038 {
4039         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4040         int res = 0;
4041
4042         switch (cr) {
4043         case 0:
4044                 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4045                 break;
4046         case 2:
4047                 vcpu->arch.cr2 = val;
4048                 break;
4049         case 3:
4050                 res = kvm_set_cr3(vcpu, val);
4051                 break;
4052         case 4:
4053                 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4054                 break;
4055         case 8:
4056                 res = kvm_set_cr8(vcpu, val);
4057                 break;
4058         default:
4059                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
4060                 res = -1;
4061         }
4062
4063         return res;
4064 }
4065
4066 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
4067 {
4068         return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
4069 }
4070
4071 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4072 {
4073         kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
4074 }
4075
4076 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4077 {
4078         kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
4079 }
4080
4081 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4082 {
4083         kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4084 }
4085
4086 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4087 {
4088         kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4089 }
4090
4091 static unsigned long emulator_get_cached_segment_base(
4092         struct x86_emulate_ctxt *ctxt, int seg)
4093 {
4094         return get_segment_base(emul_to_vcpu(ctxt), seg);
4095 }
4096
4097 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4098                                  struct desc_struct *desc, u32 *base3,
4099                                  int seg)
4100 {
4101         struct kvm_segment var;
4102
4103         kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
4104         *selector = var.selector;
4105
4106         if (var.unusable)
4107                 return false;
4108
4109         if (var.g)
4110                 var.limit >>= 12;
4111         set_desc_limit(desc, var.limit);
4112         set_desc_base(desc, (unsigned long)var.base);
4113 #ifdef CONFIG_X86_64
4114         if (base3)
4115                 *base3 = var.base >> 32;
4116 #endif
4117         desc->type = var.type;
4118         desc->s = var.s;
4119         desc->dpl = var.dpl;
4120         desc->p = var.present;
4121         desc->avl = var.avl;
4122         desc->l = var.l;
4123         desc->d = var.db;
4124         desc->g = var.g;
4125
4126         return true;
4127 }
4128
4129 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
4130                                  struct desc_struct *desc, u32 base3,
4131                                  int seg)
4132 {
4133         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4134         struct kvm_segment var;
4135
4136         var.selector = selector;
4137         var.base = get_desc_base(desc);
4138 #ifdef CONFIG_X86_64
4139         var.base |= ((u64)base3) << 32;
4140 #endif
4141         var.limit = get_desc_limit(desc);
4142         if (desc->g)
4143                 var.limit = (var.limit << 12) | 0xfff;
4144         var.type = desc->type;
4145         var.present = desc->p;
4146         var.dpl = desc->dpl;
4147         var.db = desc->d;
4148         var.s = desc->s;
4149         var.l = desc->l;
4150         var.g = desc->g;
4151         var.avl = desc->avl;
4152         var.present = desc->p;
4153         var.unusable = !var.present;
4154         var.padding = 0;
4155
4156         kvm_set_segment(vcpu, &var, seg);
4157         return;
4158 }
4159
4160 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
4161                             u32 msr_index, u64 *pdata)
4162 {
4163         return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
4164 }
4165
4166 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
4167                             u32 msr_index, u64 data)
4168 {
4169         return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
4170 }
4171
4172 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
4173                              u32 pmc, u64 *pdata)
4174 {
4175         return kvm_pmu_read_pmc(emul_to_vcpu(ctxt), pmc, pdata);
4176 }
4177
4178 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
4179 {
4180         emul_to_vcpu(ctxt)->arch.halt_request = 1;
4181 }
4182
4183 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
4184 {
4185         preempt_disable();
4186         kvm_load_guest_fpu(emul_to_vcpu(ctxt));
4187         /*
4188          * CR0.TS may reference the host fpu state, not the guest fpu state,
4189          * so it may be clear at this point.
4190          */
4191         clts();
4192 }
4193
4194 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
4195 {
4196         preempt_enable();
4197 }
4198
4199 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
4200                               struct x86_instruction_info *info,
4201                               enum x86_intercept_stage stage)
4202 {
4203         return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
4204 }
4205
4206 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
4207                                u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
4208 {
4209         struct kvm_cpuid_entry2 *cpuid = NULL;
4210
4211         if (eax && ecx)
4212                 cpuid = kvm_find_cpuid_entry(emul_to_vcpu(ctxt),
4213                                             *eax, *ecx);
4214
4215         if (cpuid) {
4216                 *eax = cpuid->eax;
4217                 *ecx = cpuid->ecx;
4218                 if (ebx)
4219                         *ebx = cpuid->ebx;
4220                 if (edx)
4221                         *edx = cpuid->edx;
4222                 return true;
4223         }
4224
4225         return false;
4226 }
4227
4228 static struct x86_emulate_ops emulate_ops = {
4229         .read_std            = kvm_read_guest_virt_system,
4230         .write_std           = kvm_write_guest_virt_system,
4231         .fetch               = kvm_fetch_guest_virt,
4232         .read_emulated       = emulator_read_emulated,
4233         .write_emulated      = emulator_write_emulated,
4234         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
4235         .invlpg              = emulator_invlpg,
4236         .pio_in_emulated     = emulator_pio_in_emulated,
4237         .pio_out_emulated    = emulator_pio_out_emulated,
4238         .get_segment         = emulator_get_segment,
4239         .set_segment         = emulator_set_segment,
4240         .get_cached_segment_base = emulator_get_cached_segment_base,
4241         .get_gdt             = emulator_get_gdt,
4242         .get_idt             = emulator_get_idt,
4243         .set_gdt             = emulator_set_gdt,
4244         .set_idt             = emulator_set_idt,
4245         .get_cr              = emulator_get_cr,
4246         .set_cr              = emulator_set_cr,
4247         .cpl                 = emulator_get_cpl,
4248         .get_dr              = emulator_get_dr,
4249         .set_dr              = emulator_set_dr,
4250         .set_msr             = emulator_set_msr,
4251         .get_msr             = emulator_get_msr,
4252         .read_pmc            = emulator_read_pmc,
4253         .halt                = emulator_halt,
4254         .wbinvd              = emulator_wbinvd,
4255         .fix_hypercall       = emulator_fix_hypercall,
4256         .get_fpu             = emulator_get_fpu,
4257         .put_fpu             = emulator_put_fpu,
4258         .intercept           = emulator_intercept,
4259         .get_cpuid           = emulator_get_cpuid,
4260 };
4261
4262 static void cache_all_regs(struct kvm_vcpu *vcpu)
4263 {
4264         kvm_register_read(vcpu, VCPU_REGS_RAX);
4265         kvm_register_read(vcpu, VCPU_REGS_RSP);
4266         kvm_register_read(vcpu, VCPU_REGS_RIP);
4267         vcpu->arch.regs_dirty = ~0;
4268 }
4269
4270 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
4271 {
4272         u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu, mask);
4273         /*
4274          * an sti; sti; sequence only disable interrupts for the first
4275          * instruction. So, if the last instruction, be it emulated or
4276          * not, left the system with the INT_STI flag enabled, it
4277          * means that the last instruction is an sti. We should not
4278          * leave the flag on in this case. The same goes for mov ss
4279          */
4280         if (!(int_shadow & mask))
4281                 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
4282 }
4283
4284 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
4285 {
4286         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4287         if (ctxt->exception.vector == PF_VECTOR)
4288                 kvm_propagate_fault(vcpu, &ctxt->exception);
4289         else if (ctxt->exception.error_code_valid)
4290                 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
4291                                       ctxt->exception.error_code);
4292         else
4293                 kvm_queue_exception(vcpu, ctxt->exception.vector);
4294 }
4295
4296 static void init_decode_cache(struct x86_emulate_ctxt *ctxt,
4297                               const unsigned long *regs)
4298 {
4299         memset(&ctxt->twobyte, 0,
4300                (void *)&ctxt->regs - (void *)&ctxt->twobyte);
4301         memcpy(ctxt->regs, regs, sizeof(ctxt->regs));
4302
4303         ctxt->fetch.start = 0;
4304         ctxt->fetch.end = 0;
4305         ctxt->io_read.pos = 0;
4306         ctxt->io_read.end = 0;
4307         ctxt->mem_read.pos = 0;
4308         ctxt->mem_read.end = 0;
4309 }
4310
4311 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
4312 {
4313         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4314         int cs_db, cs_l;
4315
4316         /*
4317          * TODO: fix emulate.c to use guest_read/write_register
4318          * instead of direct ->regs accesses, can save hundred cycles
4319          * on Intel for instructions that don't read/change RSP, for
4320          * for example.
4321          */
4322         cache_all_regs(vcpu);
4323
4324         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4325
4326         ctxt->eflags = kvm_get_rflags(vcpu);
4327         ctxt->eip = kvm_rip_read(vcpu);
4328         ctxt->mode = (!is_protmode(vcpu))               ? X86EMUL_MODE_REAL :
4329                      (ctxt->eflags & X86_EFLAGS_VM)     ? X86EMUL_MODE_VM86 :
4330                      cs_l                               ? X86EMUL_MODE_PROT64 :
4331                      cs_db                              ? X86EMUL_MODE_PROT32 :
4332                                                           X86EMUL_MODE_PROT16;
4333         ctxt->guest_mode = is_guest_mode(vcpu);
4334
4335         init_decode_cache(ctxt, vcpu->arch.regs);
4336         vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
4337 }
4338
4339 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
4340 {
4341         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4342         int ret;
4343
4344         init_emulate_ctxt(vcpu);
4345
4346         ctxt->op_bytes = 2;
4347         ctxt->ad_bytes = 2;
4348         ctxt->_eip = ctxt->eip + inc_eip;
4349         ret = emulate_int_real(ctxt, irq);
4350
4351         if (ret != X86EMUL_CONTINUE)
4352                 return EMULATE_FAIL;
4353
4354         ctxt->eip = ctxt->_eip;
4355         memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
4356         kvm_rip_write(vcpu, ctxt->eip);
4357         kvm_set_rflags(vcpu, ctxt->eflags);
4358
4359         if (irq == NMI_VECTOR)
4360                 vcpu->arch.nmi_pending = 0;
4361         else
4362                 vcpu->arch.interrupt.pending = false;
4363
4364         return EMULATE_DONE;
4365 }
4366 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
4367
4368 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
4369 {
4370         int r = EMULATE_DONE;
4371
4372         ++vcpu->stat.insn_emulation_fail;
4373         trace_kvm_emulate_insn_failed(vcpu);
4374         if (!is_guest_mode(vcpu)) {
4375                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4376                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
4377                 vcpu->run->internal.ndata = 0;
4378                 r = EMULATE_FAIL;
4379         }
4380         kvm_queue_exception(vcpu, UD_VECTOR);
4381
4382         return r;
4383 }
4384
4385 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t gva)
4386 {
4387         gpa_t gpa;
4388
4389         if (tdp_enabled)
4390                 return false;
4391
4392         /*
4393          * if emulation was due to access to shadowed page table
4394          * and it failed try to unshadow page and re-entetr the
4395          * guest to let CPU execute the instruction.
4396          */
4397         if (kvm_mmu_unprotect_page_virt(vcpu, gva))
4398                 return true;
4399
4400         gpa = kvm_mmu_gva_to_gpa_system(vcpu, gva, NULL);
4401
4402         if (gpa == UNMAPPED_GVA)
4403                 return true; /* let cpu generate fault */
4404
4405         if (!kvm_is_error_hva(gfn_to_hva(vcpu->kvm, gpa >> PAGE_SHIFT)))
4406                 return true;
4407
4408         return false;
4409 }
4410
4411 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
4412                               unsigned long cr2,  int emulation_type)
4413 {
4414         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4415         unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
4416
4417         last_retry_eip = vcpu->arch.last_retry_eip;
4418         last_retry_addr = vcpu->arch.last_retry_addr;
4419
4420         /*
4421          * If the emulation is caused by #PF and it is non-page_table
4422          * writing instruction, it means the VM-EXIT is caused by shadow
4423          * page protected, we can zap the shadow page and retry this
4424          * instruction directly.
4425          *
4426          * Note: if the guest uses a non-page-table modifying instruction
4427          * on the PDE that points to the instruction, then we will unmap
4428          * the instruction and go to an infinite loop. So, we cache the
4429          * last retried eip and the last fault address, if we meet the eip
4430          * and the address again, we can break out of the potential infinite
4431          * loop.
4432          */
4433         vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
4434
4435         if (!(emulation_type & EMULTYPE_RETRY))
4436                 return false;
4437
4438         if (x86_page_table_writing_insn(ctxt))
4439                 return false;
4440
4441         if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
4442                 return false;
4443
4444         vcpu->arch.last_retry_eip = ctxt->eip;
4445         vcpu->arch.last_retry_addr = cr2;
4446
4447         if (!vcpu->arch.mmu.direct_map)
4448                 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
4449
4450         kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
4451
4452         return true;
4453 }
4454
4455 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
4456                             unsigned long cr2,
4457                             int emulation_type,
4458                             void *insn,
4459                             int insn_len)
4460 {
4461         int r;
4462         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4463         bool writeback = true;
4464
4465         kvm_clear_exception_queue(vcpu);
4466
4467         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
4468                 init_emulate_ctxt(vcpu);
4469                 ctxt->interruptibility = 0;
4470                 ctxt->have_exception = false;
4471                 ctxt->perm_ok = false;
4472
4473                 ctxt->only_vendor_specific_insn
4474                         = emulation_type & EMULTYPE_TRAP_UD;
4475
4476                 r = x86_decode_insn(ctxt, insn, insn_len);
4477
4478                 trace_kvm_emulate_insn_start(vcpu);
4479                 ++vcpu->stat.insn_emulation;
4480                 if (r != EMULATION_OK)  {
4481                         if (emulation_type & EMULTYPE_TRAP_UD)
4482                                 return EMULATE_FAIL;
4483                         if (reexecute_instruction(vcpu, cr2))
4484                                 return EMULATE_DONE;
4485                         if (emulation_type & EMULTYPE_SKIP)
4486                                 return EMULATE_FAIL;
4487                         return handle_emulation_failure(vcpu);
4488                 }
4489         }
4490
4491         if (emulation_type & EMULTYPE_SKIP) {
4492                 kvm_rip_write(vcpu, ctxt->_eip);
4493                 return EMULATE_DONE;
4494         }
4495
4496         if (retry_instruction(ctxt, cr2, emulation_type))
4497                 return EMULATE_DONE;
4498
4499         /* this is needed for vmware backdoor interface to work since it
4500            changes registers values  during IO operation */
4501         if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
4502                 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
4503                 memcpy(ctxt->regs, vcpu->arch.regs, sizeof ctxt->regs);
4504         }
4505
4506 restart:
4507         r = x86_emulate_insn(ctxt);
4508
4509         if (r == EMULATION_INTERCEPTED)
4510                 return EMULATE_DONE;
4511
4512         if (r == EMULATION_FAILED) {
4513                 if (reexecute_instruction(vcpu, cr2))
4514                         return EMULATE_DONE;
4515
4516                 return handle_emulation_failure(vcpu);
4517         }
4518
4519         if (ctxt->have_exception) {
4520                 inject_emulated_exception(vcpu);
4521                 r = EMULATE_DONE;
4522         } else if (vcpu->arch.pio.count) {
4523                 if (!vcpu->arch.pio.in)
4524                         vcpu->arch.pio.count = 0;
4525                 else
4526                         writeback = false;
4527                 r = EMULATE_DO_MMIO;
4528         } else if (vcpu->mmio_needed) {
4529                 if (!vcpu->mmio_is_write)
4530                         writeback = false;
4531                 r = EMULATE_DO_MMIO;
4532         } else if (r == EMULATION_RESTART)
4533                 goto restart;
4534         else
4535                 r = EMULATE_DONE;
4536
4537         if (writeback) {
4538                 toggle_interruptibility(vcpu, ctxt->interruptibility);
4539                 kvm_set_rflags(vcpu, ctxt->eflags);
4540                 kvm_make_request(KVM_REQ_EVENT, vcpu);
4541                 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
4542                 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
4543                 kvm_rip_write(vcpu, ctxt->eip);
4544         } else
4545                 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
4546
4547         return r;
4548 }
4549 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
4550
4551 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
4552 {
4553         unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
4554         int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
4555                                             size, port, &val, 1);
4556         /* do not return to emulator after return from userspace */
4557         vcpu->arch.pio.count = 0;
4558         return ret;
4559 }
4560 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
4561
4562 static void tsc_bad(void *info)
4563 {
4564         __this_cpu_write(cpu_tsc_khz, 0);
4565 }
4566
4567 static void tsc_khz_changed(void *data)
4568 {
4569         struct cpufreq_freqs *freq = data;
4570         unsigned long khz = 0;
4571
4572         if (data)
4573                 khz = freq->new;
4574         else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
4575                 khz = cpufreq_quick_get(raw_smp_processor_id());
4576         if (!khz)
4577                 khz = tsc_khz;
4578         __this_cpu_write(cpu_tsc_khz, khz);
4579 }
4580
4581 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
4582                                      void *data)
4583 {
4584         struct cpufreq_freqs *freq = data;
4585         struct kvm *kvm;
4586         struct kvm_vcpu *vcpu;
4587         int i, send_ipi = 0;
4588
4589         /*
4590          * We allow guests to temporarily run on slowing clocks,
4591          * provided we notify them after, or to run on accelerating
4592          * clocks, provided we notify them before.  Thus time never
4593          * goes backwards.
4594          *
4595          * However, we have a problem.  We can't atomically update
4596          * the frequency of a given CPU from this function; it is
4597          * merely a notifier, which can be called from any CPU.
4598          * Changing the TSC frequency at arbitrary points in time
4599          * requires a recomputation of local variables related to
4600          * the TSC for each VCPU.  We must flag these local variables
4601          * to be updated and be sure the update takes place with the
4602          * new frequency before any guests proceed.
4603          *
4604          * Unfortunately, the combination of hotplug CPU and frequency
4605          * change creates an intractable locking scenario; the order
4606          * of when these callouts happen is undefined with respect to
4607          * CPU hotplug, and they can race with each other.  As such,
4608          * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
4609          * undefined; you can actually have a CPU frequency change take
4610          * place in between the computation of X and the setting of the
4611          * variable.  To protect against this problem, all updates of
4612          * the per_cpu tsc_khz variable are done in an interrupt
4613          * protected IPI, and all callers wishing to update the value
4614          * must wait for a synchronous IPI to complete (which is trivial
4615          * if the caller is on the CPU already).  This establishes the
4616          * necessary total order on variable updates.
4617          *
4618          * Note that because a guest time update may take place
4619          * anytime after the setting of the VCPU's request bit, the
4620          * correct TSC value must be set before the request.  However,
4621          * to ensure the update actually makes it to any guest which
4622          * starts running in hardware virtualization between the set
4623          * and the acquisition of the spinlock, we must also ping the
4624          * CPU after setting the request bit.
4625          *
4626          */
4627
4628         if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
4629                 return 0;
4630         if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
4631                 return 0;
4632
4633         smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
4634
4635         raw_spin_lock(&kvm_lock);
4636         list_for_each_entry(kvm, &vm_list, vm_list) {
4637                 kvm_for_each_vcpu(i, vcpu, kvm) {
4638                         if (vcpu->cpu != freq->cpu)
4639                                 continue;
4640                         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4641                         if (vcpu->cpu != smp_processor_id())
4642                                 send_ipi = 1;
4643                 }
4644         }
4645         raw_spin_unlock(&kvm_lock);
4646
4647         if (freq->old < freq->new && send_ipi) {
4648                 /*
4649                  * We upscale the frequency.  Must make the guest
4650                  * doesn't see old kvmclock values while running with
4651                  * the new frequency, otherwise we risk the guest sees
4652                  * time go backwards.
4653                  *
4654                  * In case we update the frequency for another cpu
4655                  * (which might be in guest context) send an interrupt
4656                  * to kick the cpu out of guest context.  Next time
4657                  * guest context is entered kvmclock will be updated,
4658                  * so the guest will not see stale values.
4659                  */
4660                 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
4661         }
4662         return 0;
4663 }
4664
4665 static struct notifier_block kvmclock_cpufreq_notifier_block = {
4666         .notifier_call  = kvmclock_cpufreq_notifier
4667 };
4668
4669 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
4670                                         unsigned long action, void *hcpu)
4671 {
4672         unsigned int cpu = (unsigned long)hcpu;
4673
4674         switch (action) {
4675                 case CPU_ONLINE:
4676                 case CPU_DOWN_FAILED:
4677                         smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
4678                         break;
4679                 case CPU_DOWN_PREPARE:
4680                         smp_call_function_single(cpu, tsc_bad, NULL, 1);
4681                         break;
4682         }
4683         return NOTIFY_OK;
4684 }
4685
4686 static struct notifier_block kvmclock_cpu_notifier_block = {
4687         .notifier_call  = kvmclock_cpu_notifier,
4688         .priority = -INT_MAX
4689 };
4690
4691 static void kvm_timer_init(void)
4692 {
4693         int cpu;
4694
4695         max_tsc_khz = tsc_khz;
4696         register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
4697         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
4698 #ifdef CONFIG_CPU_FREQ
4699                 struct cpufreq_policy policy;
4700                 memset(&policy, 0, sizeof(policy));
4701                 cpu = get_cpu();
4702                 cpufreq_get_policy(&policy, cpu);
4703                 if (policy.cpuinfo.max_freq)
4704                         max_tsc_khz = policy.cpuinfo.max_freq;
4705                 put_cpu();
4706 #endif
4707                 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
4708                                           CPUFREQ_TRANSITION_NOTIFIER);
4709         }
4710         pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
4711         for_each_online_cpu(cpu)
4712                 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
4713 }
4714
4715 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
4716
4717 int kvm_is_in_guest(void)
4718 {
4719         return __this_cpu_read(current_vcpu) != NULL;
4720 }
4721
4722 static int kvm_is_user_mode(void)
4723 {
4724         int user_mode = 3;
4725
4726         if (__this_cpu_read(current_vcpu))
4727                 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
4728
4729         return user_mode != 0;
4730 }
4731
4732 static unsigned long kvm_get_guest_ip(void)
4733 {
4734         unsigned long ip = 0;
4735
4736         if (__this_cpu_read(current_vcpu))
4737                 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
4738
4739         return ip;
4740 }
4741
4742 static struct perf_guest_info_callbacks kvm_guest_cbs = {
4743         .is_in_guest            = kvm_is_in_guest,
4744         .is_user_mode           = kvm_is_user_mode,
4745         .get_guest_ip           = kvm_get_guest_ip,
4746 };
4747
4748 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
4749 {
4750         __this_cpu_write(current_vcpu, vcpu);
4751 }
4752 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
4753
4754 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
4755 {
4756         __this_cpu_write(current_vcpu, NULL);
4757 }
4758 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
4759
4760 static void kvm_set_mmio_spte_mask(void)
4761 {
4762         u64 mask;
4763         int maxphyaddr = boot_cpu_data.x86_phys_bits;
4764
4765         /*
4766          * Set the reserved bits and the present bit of an paging-structure
4767          * entry to generate page fault with PFER.RSV = 1.
4768          */
4769         mask = ((1ull << (62 - maxphyaddr + 1)) - 1) << maxphyaddr;
4770         mask |= 1ull;
4771
4772 #ifdef CONFIG_X86_64
4773         /*
4774          * If reserved bit is not supported, clear the present bit to disable
4775          * mmio page fault.
4776          */
4777         if (maxphyaddr == 52)
4778                 mask &= ~1ull;
4779 #endif
4780
4781         kvm_mmu_set_mmio_spte_mask(mask);
4782 }
4783
4784 int kvm_arch_init(void *opaque)
4785 {
4786         int r;
4787         struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
4788
4789         if (kvm_x86_ops) {
4790                 printk(KERN_ERR "kvm: already loaded the other module\n");
4791                 r = -EEXIST;
4792                 goto out;
4793         }
4794
4795         if (!ops->cpu_has_kvm_support()) {
4796                 printk(KERN_ERR "kvm: no hardware support\n");
4797                 r = -EOPNOTSUPP;
4798                 goto out;
4799         }
4800         if (ops->disabled_by_bios()) {
4801                 printk(KERN_ERR "kvm: disabled by bios\n");
4802                 r = -EOPNOTSUPP;
4803                 goto out;
4804         }
4805
4806         r = kvm_mmu_module_init();
4807         if (r)
4808                 goto out;
4809
4810         kvm_set_mmio_spte_mask();
4811         kvm_init_msr_list();
4812
4813         kvm_x86_ops = ops;
4814         kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
4815                         PT_DIRTY_MASK, PT64_NX_MASK, 0);
4816
4817         kvm_timer_init();
4818
4819         perf_register_guest_info_callbacks(&kvm_guest_cbs);
4820
4821         if (cpu_has_xsave)
4822                 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
4823
4824         return 0;
4825
4826 out:
4827         return r;
4828 }
4829
4830 void kvm_arch_exit(void)
4831 {
4832         perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
4833
4834         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
4835                 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
4836                                             CPUFREQ_TRANSITION_NOTIFIER);
4837         unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
4838         kvm_x86_ops = NULL;
4839         kvm_mmu_module_exit();
4840 }
4841
4842 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
4843 {
4844         ++vcpu->stat.halt_exits;
4845         if (irqchip_in_kernel(vcpu->kvm)) {
4846                 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
4847                 return 1;
4848         } else {
4849                 vcpu->run->exit_reason = KVM_EXIT_HLT;
4850                 return 0;
4851         }
4852 }
4853 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
4854
4855 int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
4856 {
4857         u64 param, ingpa, outgpa, ret;
4858         uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
4859         bool fast, longmode;
4860         int cs_db, cs_l;
4861
4862         /*
4863          * hypercall generates UD from non zero cpl and real mode
4864          * per HYPER-V spec
4865          */
4866         if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
4867                 kvm_queue_exception(vcpu, UD_VECTOR);
4868                 return 0;
4869         }
4870
4871         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4872         longmode = is_long_mode(vcpu) && cs_l == 1;
4873
4874         if (!longmode) {
4875                 param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
4876                         (kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
4877                 ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
4878                         (kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
4879                 outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
4880                         (kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
4881         }
4882 #ifdef CONFIG_X86_64
4883         else {
4884                 param = kvm_register_read(vcpu, VCPU_REGS_RCX);
4885                 ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
4886                 outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
4887         }
4888 #endif
4889
4890         code = param & 0xffff;
4891         fast = (param >> 16) & 0x1;
4892         rep_cnt = (param >> 32) & 0xfff;
4893         rep_idx = (param >> 48) & 0xfff;
4894
4895         trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
4896
4897         switch (code) {
4898         case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
4899                 kvm_vcpu_on_spin(vcpu);
4900                 break;
4901         default:
4902                 res = HV_STATUS_INVALID_HYPERCALL_CODE;
4903                 break;
4904         }
4905
4906         ret = res | (((u64)rep_done & 0xfff) << 32);
4907         if (longmode) {
4908                 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
4909         } else {
4910                 kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
4911                 kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
4912         }
4913
4914         return 1;
4915 }
4916
4917 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
4918 {
4919         unsigned long nr, a0, a1, a2, a3, ret;
4920         int r = 1;
4921
4922         if (kvm_hv_hypercall_enabled(vcpu->kvm))
4923                 return kvm_hv_hypercall(vcpu);
4924
4925         nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
4926         a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
4927         a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
4928         a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
4929         a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
4930
4931         trace_kvm_hypercall(nr, a0, a1, a2, a3);
4932
4933         if (!is_long_mode(vcpu)) {
4934                 nr &= 0xFFFFFFFF;
4935                 a0 &= 0xFFFFFFFF;
4936                 a1 &= 0xFFFFFFFF;
4937                 a2 &= 0xFFFFFFFF;
4938                 a3 &= 0xFFFFFFFF;
4939         }
4940
4941         if (kvm_x86_ops->get_cpl(vcpu) != 0) {
4942                 ret = -KVM_EPERM;
4943                 goto out;
4944         }
4945
4946         switch (nr) {
4947         case KVM_HC_VAPIC_POLL_IRQ:
4948                 ret = 0;
4949                 break;
4950         default:
4951                 ret = -KVM_ENOSYS;
4952                 break;
4953         }
4954 out:
4955         kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
4956         ++vcpu->stat.hypercalls;
4957         return r;
4958 }
4959 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
4960
4961 int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
4962 {
4963         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4964         char instruction[3];
4965         unsigned long rip = kvm_rip_read(vcpu);
4966
4967         /*
4968          * Blow out the MMU to ensure that no other VCPU has an active mapping
4969          * to ensure that the updated hypercall appears atomically across all
4970          * VCPUs.
4971          */
4972         kvm_mmu_zap_all(vcpu->kvm);
4973
4974         kvm_x86_ops->patch_hypercall(vcpu, instruction);
4975
4976         return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
4977 }
4978
4979 /*
4980  * Check if userspace requested an interrupt window, and that the
4981  * interrupt window is open.
4982  *
4983  * No need to exit to userspace if we already have an interrupt queued.
4984  */
4985 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
4986 {
4987         return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
4988                 vcpu->run->request_interrupt_window &&
4989                 kvm_arch_interrupt_allowed(vcpu));
4990 }
4991
4992 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
4993 {
4994         struct kvm_run *kvm_run = vcpu->run;
4995
4996         kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
4997         kvm_run->cr8 = kvm_get_cr8(vcpu);
4998         kvm_run->apic_base = kvm_get_apic_base(vcpu);
4999         if (irqchip_in_kernel(vcpu->kvm))
5000                 kvm_run->ready_for_interrupt_injection = 1;
5001         else
5002                 kvm_run->ready_for_interrupt_injection =
5003                         kvm_arch_interrupt_allowed(vcpu) &&
5004                         !kvm_cpu_has_interrupt(vcpu) &&
5005                         !kvm_event_needs_reinjection(vcpu);
5006 }
5007
5008 static void vapic_enter(struct kvm_vcpu *vcpu)
5009 {
5010         struct kvm_lapic *apic = vcpu->arch.apic;
5011         struct page *page;
5012
5013         if (!apic || !apic->vapic_addr)
5014                 return;
5015
5016         page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
5017
5018         vcpu->arch.apic->vapic_page = page;
5019 }
5020
5021 static void vapic_exit(struct kvm_vcpu *vcpu)
5022 {
5023         struct kvm_lapic *apic = vcpu->arch.apic;
5024         int idx;
5025
5026         if (!apic || !apic->vapic_addr)
5027                 return;
5028
5029         idx = srcu_read_lock(&vcpu->kvm->srcu);
5030         kvm_release_page_dirty(apic->vapic_page);
5031         mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
5032         srcu_read_unlock(&vcpu->kvm->srcu, idx);
5033 }
5034
5035 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
5036 {
5037         int max_irr, tpr;
5038
5039         if (!kvm_x86_ops->update_cr8_intercept)
5040                 return;
5041
5042         if (!vcpu->arch.apic)
5043                 return;
5044
5045         if (!vcpu->arch.apic->vapic_addr)
5046                 max_irr = kvm_lapic_find_highest_irr(vcpu);
5047         else
5048                 max_irr = -1;
5049
5050         if (max_irr != -1)
5051                 max_irr >>= 4;
5052
5053         tpr = kvm_lapic_get_cr8(vcpu);
5054
5055         kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
5056 }
5057
5058 static void inject_pending_event(struct kvm_vcpu *vcpu)
5059 {
5060         /* try to reinject previous events if any */
5061         if (vcpu->arch.exception.pending) {
5062                 trace_kvm_inj_exception(vcpu->arch.exception.nr,
5063                                         vcpu->arch.exception.has_error_code,
5064                                         vcpu->arch.exception.error_code);
5065                 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
5066                                           vcpu->arch.exception.has_error_code,
5067                                           vcpu->arch.exception.error_code,
5068                                           vcpu->arch.exception.reinject);
5069                 return;
5070         }
5071
5072         if (vcpu->arch.nmi_injected) {
5073                 kvm_x86_ops->set_nmi(vcpu);
5074                 return;
5075         }
5076
5077         if (vcpu->arch.interrupt.pending) {
5078                 kvm_x86_ops->set_irq(vcpu);
5079                 return;
5080         }
5081
5082         /* try to inject new event if pending */
5083         if (vcpu->arch.nmi_pending) {
5084                 if (kvm_x86_ops->nmi_allowed(vcpu)) {
5085                         --vcpu->arch.nmi_pending;
5086                         vcpu->arch.nmi_injected = true;
5087                         kvm_x86_ops->set_nmi(vcpu);
5088                 }
5089         } else if (kvm_cpu_has_interrupt(vcpu)) {
5090                 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
5091                         kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
5092                                             false);
5093                         kvm_x86_ops->set_irq(vcpu);
5094                 }
5095         }
5096 }
5097
5098 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
5099 {
5100         if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
5101                         !vcpu->guest_xcr0_loaded) {
5102                 /* kvm_set_xcr() also depends on this */
5103                 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
5104                 vcpu->guest_xcr0_loaded = 1;
5105         }
5106 }
5107
5108 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
5109 {
5110         if (vcpu->guest_xcr0_loaded) {
5111                 if (vcpu->arch.xcr0 != host_xcr0)
5112                         xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
5113                 vcpu->guest_xcr0_loaded = 0;
5114         }
5115 }
5116
5117 static void process_nmi(struct kvm_vcpu *vcpu)
5118 {
5119         unsigned limit = 2;
5120
5121         /*
5122          * x86 is limited to one NMI running, and one NMI pending after it.
5123          * If an NMI is already in progress, limit further NMIs to just one.
5124          * Otherwise, allow two (and we'll inject the first one immediately).
5125          */
5126         if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
5127                 limit = 1;
5128
5129         vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
5130         vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
5131         kvm_make_request(KVM_REQ_EVENT, vcpu);
5132 }
5133
5134 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
5135 {
5136         int r;
5137         bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
5138                 vcpu->run->request_interrupt_window;
5139         bool req_immediate_exit = 0;
5140
5141         if (vcpu->requests) {
5142                 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
5143                         kvm_mmu_unload(vcpu);
5144                 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
5145                         __kvm_migrate_timers(vcpu);
5146                 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
5147                         r = kvm_guest_time_update(vcpu);
5148                         if (unlikely(r))
5149                                 goto out;
5150                 }
5151                 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
5152                         kvm_mmu_sync_roots(vcpu);
5153                 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
5154                         kvm_x86_ops->tlb_flush(vcpu);
5155                 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
5156                         vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
5157                         r = 0;
5158                         goto out;
5159                 }
5160                 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
5161                         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5162                         r = 0;
5163                         goto out;
5164                 }
5165                 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
5166                         vcpu->fpu_active = 0;
5167                         kvm_x86_ops->fpu_deactivate(vcpu);
5168                 }
5169                 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
5170                         /* Page is swapped out. Do synthetic halt */
5171                         vcpu->arch.apf.halted = true;
5172                         r = 1;
5173                         goto out;
5174                 }
5175                 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
5176                         record_steal_time(vcpu);
5177                 if (kvm_check_request(KVM_REQ_NMI, vcpu))
5178                         process_nmi(vcpu);
5179                 req_immediate_exit =
5180                         kvm_check_request(KVM_REQ_IMMEDIATE_EXIT, vcpu);
5181                 if (kvm_check_request(KVM_REQ_PMU, vcpu))
5182                         kvm_handle_pmu_event(vcpu);
5183                 if (kvm_check_request(KVM_REQ_PMI, vcpu))
5184                         kvm_deliver_pmi(vcpu);
5185         }
5186
5187         r = kvm_mmu_reload(vcpu);
5188         if (unlikely(r))
5189                 goto out;
5190
5191         if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
5192                 inject_pending_event(vcpu);
5193
5194                 /* enable NMI/IRQ window open exits if needed */
5195                 if (vcpu->arch.nmi_pending)
5196                         kvm_x86_ops->enable_nmi_window(vcpu);
5197                 else if (kvm_cpu_has_interrupt(vcpu) || req_int_win)
5198                         kvm_x86_ops->enable_irq_window(vcpu);
5199
5200                 if (kvm_lapic_enabled(vcpu)) {
5201                         update_cr8_intercept(vcpu);
5202                         kvm_lapic_sync_to_vapic(vcpu);
5203                 }
5204         }
5205
5206         preempt_disable();
5207
5208         kvm_x86_ops->prepare_guest_switch(vcpu);
5209         if (vcpu->fpu_active)
5210                 kvm_load_guest_fpu(vcpu);
5211         kvm_load_guest_xcr0(vcpu);
5212
5213         vcpu->mode = IN_GUEST_MODE;
5214
5215         /* We should set ->mode before check ->requests,
5216          * see the comment in make_all_cpus_request.
5217          */
5218         smp_mb();
5219
5220         local_irq_disable();
5221
5222         if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
5223             || need_resched() || signal_pending(current)) {
5224                 vcpu->mode = OUTSIDE_GUEST_MODE;
5225                 smp_wmb();
5226                 local_irq_enable();
5227                 preempt_enable();
5228                 kvm_x86_ops->cancel_injection(vcpu);
5229                 r = 1;
5230                 goto out;
5231         }
5232
5233         srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
5234
5235         if (req_immediate_exit)
5236                 smp_send_reschedule(vcpu->cpu);
5237
5238         kvm_guest_enter();
5239
5240         if (unlikely(vcpu->arch.switch_db_regs)) {
5241                 set_debugreg(0, 7);
5242                 set_debugreg(vcpu->arch.eff_db[0], 0);
5243                 set_debugreg(vcpu->arch.eff_db[1], 1);
5244                 set_debugreg(vcpu->arch.eff_db[2], 2);
5245                 set_debugreg(vcpu->arch.eff_db[3], 3);
5246         }
5247
5248         trace_kvm_entry(vcpu->vcpu_id);
5249         kvm_x86_ops->run(vcpu);
5250
5251         /*
5252          * If the guest has used debug registers, at least dr7
5253          * will be disabled while returning to the host.
5254          * If we don't have active breakpoints in the host, we don't
5255          * care about the messed up debug address registers. But if
5256          * we have some of them active, restore the old state.
5257          */
5258         if (hw_breakpoint_active())
5259                 hw_breakpoint_restore();
5260
5261         vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu);
5262
5263         vcpu->mode = OUTSIDE_GUEST_MODE;
5264         smp_wmb();
5265         local_irq_enable();
5266
5267         ++vcpu->stat.exits;
5268
5269         /*
5270          * We must have an instruction between local_irq_enable() and
5271          * kvm_guest_exit(), so the timer interrupt isn't delayed by
5272          * the interrupt shadow.  The stat.exits increment will do nicely.
5273          * But we need to prevent reordering, hence this barrier():
5274          */
5275         barrier();
5276
5277         kvm_guest_exit();
5278
5279         preempt_enable();
5280
5281         vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
5282
5283         /*
5284          * Profile KVM exit RIPs:
5285          */
5286         if (unlikely(prof_on == KVM_PROFILING)) {
5287                 unsigned long rip = kvm_rip_read(vcpu);
5288                 profile_hit(KVM_PROFILING, (void *)rip);
5289         }
5290
5291
5292         kvm_lapic_sync_from_vapic(vcpu);
5293
5294         r = kvm_x86_ops->handle_exit(vcpu);
5295 out:
5296         return r;
5297 }
5298
5299
5300 static int __vcpu_run(struct kvm_vcpu *vcpu)
5301 {
5302         int r;
5303         struct kvm *kvm = vcpu->kvm;
5304
5305         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
5306                 pr_debug("vcpu %d received sipi with vector # %x\n",
5307                          vcpu->vcpu_id, vcpu->arch.sipi_vector);
5308                 kvm_lapic_reset(vcpu);
5309                 r = kvm_arch_vcpu_reset(vcpu);
5310                 if (r)
5311                         return r;
5312                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5313         }
5314
5315         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
5316         vapic_enter(vcpu);
5317
5318         r = 1;
5319         while (r > 0) {
5320                 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
5321                     !vcpu->arch.apf.halted)
5322                         r = vcpu_enter_guest(vcpu);
5323                 else {
5324                         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5325                         kvm_vcpu_block(vcpu);
5326                         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
5327                         if (kvm_check_request(KVM_REQ_UNHALT, vcpu))
5328                         {
5329                                 switch(vcpu->arch.mp_state) {
5330                                 case KVM_MP_STATE_HALTED:
5331                                         vcpu->arch.mp_state =
5332                                                 KVM_MP_STATE_RUNNABLE;
5333                                 case KVM_MP_STATE_RUNNABLE:
5334                                         vcpu->arch.apf.halted = false;
5335                                         break;
5336                                 case KVM_MP_STATE_SIPI_RECEIVED:
5337                                 default:
5338                                         r = -EINTR;
5339                                         break;
5340                                 }
5341                         }
5342                 }
5343
5344                 if (r <= 0)
5345                         break;
5346
5347                 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
5348                 if (kvm_cpu_has_pending_timer(vcpu))
5349                         kvm_inject_pending_timer_irqs(vcpu);
5350
5351                 if (dm_request_for_irq_injection(vcpu)) {
5352                         r = -EINTR;
5353                         vcpu->run->exit_reason = KVM_EXIT_INTR;
5354                         ++vcpu->stat.request_irq_exits;
5355                 }
5356
5357                 kvm_check_async_pf_completion(vcpu);
5358
5359                 if (signal_pending(current)) {
5360                         r = -EINTR;
5361                         vcpu->run->exit_reason = KVM_EXIT_INTR;
5362                         ++vcpu->stat.signal_exits;
5363                 }
5364                 if (need_resched()) {
5365                         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5366                         kvm_resched(vcpu);
5367                         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
5368                 }
5369         }
5370
5371         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5372
5373         vapic_exit(vcpu);
5374
5375         return r;
5376 }
5377
5378 static int complete_mmio(struct kvm_vcpu *vcpu)
5379 {
5380         struct kvm_run *run = vcpu->run;
5381         int r;
5382
5383         if (!(vcpu->arch.pio.count || vcpu->mmio_needed))
5384                 return 1;
5385
5386         if (vcpu->mmio_needed) {
5387                 vcpu->mmio_needed = 0;
5388                 if (!vcpu->mmio_is_write)
5389                         memcpy(vcpu->mmio_data + vcpu->mmio_index,
5390                                run->mmio.data, 8);
5391                 vcpu->mmio_index += 8;
5392                 if (vcpu->mmio_index < vcpu->mmio_size) {
5393                         run->exit_reason = KVM_EXIT_MMIO;
5394                         run->mmio.phys_addr = vcpu->mmio_phys_addr + vcpu->mmio_index;
5395                         memcpy(run->mmio.data, vcpu->mmio_data + vcpu->mmio_index, 8);
5396                         run->mmio.len = min(vcpu->mmio_size - vcpu->mmio_index, 8);
5397                         run->mmio.is_write = vcpu->mmio_is_write;
5398                         vcpu->mmio_needed = 1;
5399                         return 0;
5400                 }
5401                 if (vcpu->mmio_is_write)
5402                         return 1;
5403                 vcpu->mmio_read_completed = 1;
5404         }
5405         vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
5406         r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
5407         srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
5408         if (r != EMULATE_DONE)
5409                 return 0;
5410         return 1;
5411 }
5412
5413 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
5414 {
5415         int r;
5416         sigset_t sigsaved;
5417
5418         if (!tsk_used_math(current) && init_fpu(current))
5419                 return -ENOMEM;
5420
5421         if (vcpu->sigset_active)
5422                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
5423
5424         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
5425                 kvm_vcpu_block(vcpu);
5426                 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
5427                 r = -EAGAIN;
5428                 goto out;
5429         }
5430
5431         /* re-sync apic's tpr */
5432         if (!irqchip_in_kernel(vcpu->kvm)) {
5433                 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
5434                         r = -EINVAL;
5435                         goto out;
5436                 }
5437         }
5438
5439         r = complete_mmio(vcpu);
5440         if (r <= 0)
5441                 goto out;
5442
5443         r = __vcpu_run(vcpu);
5444
5445 out:
5446         post_kvm_run_save(vcpu);
5447         if (vcpu->sigset_active)
5448                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
5449
5450         return r;
5451 }
5452
5453 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
5454 {
5455         if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
5456                 /*
5457                  * We are here if userspace calls get_regs() in the middle of
5458                  * instruction emulation. Registers state needs to be copied
5459                  * back from emulation context to vcpu. Usrapace shouldn't do
5460                  * that usually, but some bad designed PV devices (vmware
5461                  * backdoor interface) need this to work
5462                  */
5463                 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5464                 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
5465                 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5466         }
5467         regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
5468         regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
5469         regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
5470         regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
5471         regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
5472         regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
5473         regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
5474         regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
5475 #ifdef CONFIG_X86_64
5476         regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
5477         regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
5478         regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
5479         regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
5480         regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
5481         regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
5482         regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
5483         regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
5484 #endif
5485
5486         regs->rip = kvm_rip_read(vcpu);
5487         regs->rflags = kvm_get_rflags(vcpu);
5488
5489         return 0;
5490 }
5491
5492 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
5493 {
5494         vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
5495         vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5496
5497         kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
5498         kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
5499         kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
5500         kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
5501         kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
5502         kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
5503         kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
5504         kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
5505 #ifdef CONFIG_X86_64
5506         kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
5507         kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
5508         kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
5509         kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
5510         kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
5511         kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
5512         kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
5513         kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
5514 #endif
5515
5516         kvm_rip_write(vcpu, regs->rip);
5517         kvm_set_rflags(vcpu, regs->rflags);
5518
5519         vcpu->arch.exception.pending = false;
5520
5521         kvm_make_request(KVM_REQ_EVENT, vcpu);
5522
5523         return 0;
5524 }
5525
5526 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
5527 {
5528         struct kvm_segment cs;
5529
5530         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
5531         *db = cs.db;
5532         *l = cs.l;
5533 }
5534 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
5535
5536 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
5537                                   struct kvm_sregs *sregs)
5538 {
5539         struct desc_ptr dt;
5540
5541         kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
5542         kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
5543         kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
5544         kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
5545         kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
5546         kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
5547
5548         kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
5549         kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
5550
5551         kvm_x86_ops->get_idt(vcpu, &dt);
5552         sregs->idt.limit = dt.size;
5553         sregs->idt.base = dt.address;
5554         kvm_x86_ops->get_gdt(vcpu, &dt);
5555         sregs->gdt.limit = dt.size;
5556         sregs->gdt.base = dt.address;
5557
5558         sregs->cr0 = kvm_read_cr0(vcpu);
5559         sregs->cr2 = vcpu->arch.cr2;
5560         sregs->cr3 = kvm_read_cr3(vcpu);
5561         sregs->cr4 = kvm_read_cr4(vcpu);
5562         sregs->cr8 = kvm_get_cr8(vcpu);
5563         sregs->efer = vcpu->arch.efer;
5564         sregs->apic_base = kvm_get_apic_base(vcpu);
5565
5566         memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
5567
5568         if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
5569                 set_bit(vcpu->arch.interrupt.nr,
5570                         (unsigned long *)sregs->interrupt_bitmap);
5571
5572         return 0;
5573 }
5574
5575 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
5576                                     struct kvm_mp_state *mp_state)
5577 {
5578         mp_state->mp_state = vcpu->arch.mp_state;
5579         return 0;
5580 }
5581
5582 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
5583                                     struct kvm_mp_state *mp_state)
5584 {
5585         vcpu->arch.mp_state = mp_state->mp_state;
5586         kvm_make_request(KVM_REQ_EVENT, vcpu);
5587         return 0;
5588 }
5589
5590 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason,
5591                     bool has_error_code, u32 error_code)
5592 {
5593         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5594         int ret;
5595
5596         init_emulate_ctxt(vcpu);
5597
5598         ret = emulator_task_switch(ctxt, tss_selector, reason,
5599                                    has_error_code, error_code);
5600
5601         if (ret)
5602                 return EMULATE_FAIL;
5603
5604         memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
5605         kvm_rip_write(vcpu, ctxt->eip);
5606         kvm_set_rflags(vcpu, ctxt->eflags);
5607         kvm_make_request(KVM_REQ_EVENT, vcpu);
5608         return EMULATE_DONE;
5609 }
5610 EXPORT_SYMBOL_GPL(kvm_task_switch);
5611
5612 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
5613                                   struct kvm_sregs *sregs)
5614 {
5615         int mmu_reset_needed = 0;
5616         int pending_vec, max_bits, idx;
5617         struct desc_ptr dt;
5618
5619         dt.size = sregs->idt.limit;
5620         dt.address = sregs->idt.base;
5621         kvm_x86_ops->set_idt(vcpu, &dt);
5622         dt.size = sregs->gdt.limit;
5623         dt.address = sregs->gdt.base;
5624         kvm_x86_ops->set_gdt(vcpu, &dt);
5625
5626         vcpu->arch.cr2 = sregs->cr2;
5627         mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
5628         vcpu->arch.cr3 = sregs->cr3;
5629         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
5630
5631         kvm_set_cr8(vcpu, sregs->cr8);
5632
5633         mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
5634         kvm_x86_ops->set_efer(vcpu, sregs->efer);
5635         kvm_set_apic_base(vcpu, sregs->apic_base);
5636
5637         mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
5638         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
5639         vcpu->arch.cr0 = sregs->cr0;
5640
5641         mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
5642         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
5643         if (sregs->cr4 & X86_CR4_OSXSAVE)
5644                 kvm_update_cpuid(vcpu);
5645
5646         idx = srcu_read_lock(&vcpu->kvm->srcu);
5647         if (!is_long_mode(vcpu) && is_pae(vcpu)) {
5648                 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
5649                 mmu_reset_needed = 1;
5650         }
5651         srcu_read_unlock(&vcpu->kvm->srcu, idx);
5652
5653         if (mmu_reset_needed)
5654                 kvm_mmu_reset_context(vcpu);
5655
5656         max_bits = (sizeof sregs->interrupt_bitmap) << 3;
5657         pending_vec = find_first_bit(
5658                 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
5659         if (pending_vec < max_bits) {
5660                 kvm_queue_interrupt(vcpu, pending_vec, false);
5661                 pr_debug("Set back pending irq %d\n", pending_vec);
5662         }
5663
5664         kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
5665         kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
5666         kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
5667         kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
5668         kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
5669         kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
5670
5671         kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
5672         kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
5673
5674         update_cr8_intercept(vcpu);
5675
5676         /* Older userspace won't unhalt the vcpu on reset. */
5677         if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
5678             sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
5679             !is_protmode(vcpu))
5680                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5681
5682         kvm_make_request(KVM_REQ_EVENT, vcpu);
5683
5684         return 0;
5685 }
5686
5687 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
5688                                         struct kvm_guest_debug *dbg)
5689 {
5690         unsigned long rflags;
5691         int i, r;
5692
5693         if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
5694                 r = -EBUSY;
5695                 if (vcpu->arch.exception.pending)
5696                         goto out;
5697                 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
5698                         kvm_queue_exception(vcpu, DB_VECTOR);
5699                 else
5700                         kvm_queue_exception(vcpu, BP_VECTOR);
5701         }
5702
5703         /*
5704          * Read rflags as long as potentially injected trace flags are still
5705          * filtered out.
5706          */
5707         rflags = kvm_get_rflags(vcpu);
5708
5709         vcpu->guest_debug = dbg->control;
5710         if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
5711                 vcpu->guest_debug = 0;
5712
5713         if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5714                 for (i = 0; i < KVM_NR_DB_REGS; ++i)
5715                         vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
5716                 vcpu->arch.switch_db_regs =
5717                         (dbg->arch.debugreg[7] & DR7_BP_EN_MASK);
5718         } else {
5719                 for (i = 0; i < KVM_NR_DB_REGS; i++)
5720                         vcpu->arch.eff_db[i] = vcpu->arch.db[i];
5721                 vcpu->arch.switch_db_regs = (vcpu->arch.dr7 & DR7_BP_EN_MASK);
5722         }
5723
5724         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
5725                 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
5726                         get_segment_base(vcpu, VCPU_SREG_CS);
5727
5728         /*
5729          * Trigger an rflags update that will inject or remove the trace
5730          * flags.
5731          */
5732         kvm_set_rflags(vcpu, rflags);
5733
5734         kvm_x86_ops->set_guest_debug(vcpu, dbg);
5735
5736         r = 0;
5737
5738 out:
5739
5740         return r;
5741 }
5742
5743 /*
5744  * Translate a guest virtual address to a guest physical address.
5745  */
5746 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
5747                                     struct kvm_translation *tr)
5748 {
5749         unsigned long vaddr = tr->linear_address;
5750         gpa_t gpa;
5751         int idx;
5752
5753         idx = srcu_read_lock(&vcpu->kvm->srcu);
5754         gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
5755         srcu_read_unlock(&vcpu->kvm->srcu, idx);
5756         tr->physical_address = gpa;
5757         tr->valid = gpa != UNMAPPED_GVA;
5758         tr->writeable = 1;
5759         tr->usermode = 0;
5760
5761         return 0;
5762 }
5763
5764 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
5765 {
5766         struct i387_fxsave_struct *fxsave =
5767                         &vcpu->arch.guest_fpu.state->fxsave;
5768
5769         memcpy(fpu->fpr, fxsave->st_space, 128);
5770         fpu->fcw = fxsave->cwd;
5771         fpu->fsw = fxsave->swd;
5772         fpu->ftwx = fxsave->twd;
5773         fpu->last_opcode = fxsave->fop;
5774         fpu->last_ip = fxsave->rip;
5775         fpu->last_dp = fxsave->rdp;
5776         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
5777
5778         return 0;
5779 }
5780
5781 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
5782 {
5783         struct i387_fxsave_struct *fxsave =
5784                         &vcpu->arch.guest_fpu.state->fxsave;
5785
5786         memcpy(fxsave->st_space, fpu->fpr, 128);
5787         fxsave->cwd = fpu->fcw;
5788         fxsave->swd = fpu->fsw;
5789         fxsave->twd = fpu->ftwx;
5790         fxsave->fop = fpu->last_opcode;
5791         fxsave->rip = fpu->last_ip;
5792         fxsave->rdp = fpu->last_dp;
5793         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
5794
5795         return 0;
5796 }
5797
5798 int fx_init(struct kvm_vcpu *vcpu)
5799 {
5800         int err;
5801
5802         err = fpu_alloc(&vcpu->arch.guest_fpu);
5803         if (err)
5804                 return err;
5805
5806         fpu_finit(&vcpu->arch.guest_fpu);
5807
5808         /*
5809          * Ensure guest xcr0 is valid for loading
5810          */
5811         vcpu->arch.xcr0 = XSTATE_FP;
5812
5813         vcpu->arch.cr0 |= X86_CR0_ET;
5814
5815         return 0;
5816 }
5817 EXPORT_SYMBOL_GPL(fx_init);
5818
5819 static void fx_free(struct kvm_vcpu *vcpu)
5820 {
5821         fpu_free(&vcpu->arch.guest_fpu);
5822 }
5823
5824 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
5825 {
5826         if (vcpu->guest_fpu_loaded)
5827                 return;
5828
5829         /*
5830          * Restore all possible states in the guest,
5831          * and assume host would use all available bits.
5832          * Guest xcr0 would be loaded later.
5833          */
5834         kvm_put_guest_xcr0(vcpu);
5835         vcpu->guest_fpu_loaded = 1;
5836         unlazy_fpu(current);
5837         fpu_restore_checking(&vcpu->arch.guest_fpu);
5838         trace_kvm_fpu(1);
5839 }
5840
5841 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
5842 {
5843         kvm_put_guest_xcr0(vcpu);
5844
5845         if (!vcpu->guest_fpu_loaded)
5846                 return;
5847
5848         vcpu->guest_fpu_loaded = 0;
5849         fpu_save_init(&vcpu->arch.guest_fpu);
5850         ++vcpu->stat.fpu_reload;
5851         kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
5852         trace_kvm_fpu(0);
5853 }
5854
5855 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
5856 {
5857         kvmclock_reset(vcpu);
5858
5859         free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
5860         fx_free(vcpu);
5861         kvm_x86_ops->vcpu_free(vcpu);
5862 }
5863
5864 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
5865                                                 unsigned int id)
5866 {
5867         if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
5868                 printk_once(KERN_WARNING
5869                 "kvm: SMP vm created on host with unstable TSC; "
5870                 "guest TSC will not be reliable\n");
5871         return kvm_x86_ops->vcpu_create(kvm, id);
5872 }
5873
5874 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
5875 {
5876         int r;
5877
5878         vcpu->arch.mtrr_state.have_fixed = 1;
5879         vcpu_load(vcpu);
5880         r = kvm_arch_vcpu_reset(vcpu);
5881         if (r == 0)
5882                 r = kvm_mmu_setup(vcpu);
5883         vcpu_put(vcpu);
5884
5885         return r;
5886 }
5887
5888 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
5889 {
5890         vcpu->arch.apf.msr_val = 0;
5891
5892         vcpu_load(vcpu);
5893         kvm_mmu_unload(vcpu);
5894         vcpu_put(vcpu);
5895
5896         fx_free(vcpu);
5897         kvm_x86_ops->vcpu_free(vcpu);
5898 }
5899
5900 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
5901 {
5902         atomic_set(&vcpu->arch.nmi_queued, 0);
5903         vcpu->arch.nmi_pending = 0;
5904         vcpu->arch.nmi_injected = false;
5905
5906         vcpu->arch.switch_db_regs = 0;
5907         memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
5908         vcpu->arch.dr6 = DR6_FIXED_1;
5909         vcpu->arch.dr7 = DR7_FIXED_1;
5910
5911         kvm_make_request(KVM_REQ_EVENT, vcpu);
5912         vcpu->arch.apf.msr_val = 0;
5913         vcpu->arch.st.msr_val = 0;
5914
5915         kvmclock_reset(vcpu);
5916
5917         kvm_clear_async_pf_completion_queue(vcpu);
5918         kvm_async_pf_hash_reset(vcpu);
5919         vcpu->arch.apf.halted = false;
5920
5921         kvm_pmu_reset(vcpu);
5922
5923         return kvm_x86_ops->vcpu_reset(vcpu);
5924 }
5925
5926 int kvm_arch_hardware_enable(void *garbage)
5927 {
5928         struct kvm *kvm;
5929         struct kvm_vcpu *vcpu;
5930         int i;
5931
5932         kvm_shared_msr_cpu_online();
5933         list_for_each_entry(kvm, &vm_list, vm_list)
5934                 kvm_for_each_vcpu(i, vcpu, kvm)
5935                         if (vcpu->cpu == smp_processor_id())
5936                                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5937         return kvm_x86_ops->hardware_enable(garbage);
5938 }
5939
5940 void kvm_arch_hardware_disable(void *garbage)
5941 {
5942         kvm_x86_ops->hardware_disable(garbage);
5943         drop_user_return_notifiers(garbage);
5944 }
5945
5946 int kvm_arch_hardware_setup(void)
5947 {
5948         return kvm_x86_ops->hardware_setup();
5949 }
5950
5951 void kvm_arch_hardware_unsetup(void)
5952 {
5953         kvm_x86_ops->hardware_unsetup();
5954 }
5955
5956 void kvm_arch_check_processor_compat(void *rtn)
5957 {
5958         kvm_x86_ops->check_processor_compatibility(rtn);
5959 }
5960
5961 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
5962 {
5963         struct page *page;
5964         struct kvm *kvm;
5965         int r;
5966
5967         BUG_ON(vcpu->kvm == NULL);
5968         kvm = vcpu->kvm;
5969
5970         vcpu->arch.emulate_ctxt.ops = &emulate_ops;
5971         if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
5972                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5973         else
5974                 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
5975
5976         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
5977         if (!page) {
5978                 r = -ENOMEM;
5979                 goto fail;
5980         }
5981         vcpu->arch.pio_data = page_address(page);
5982
5983         kvm_init_tsc_catchup(vcpu, max_tsc_khz);
5984
5985         r = kvm_mmu_create(vcpu);
5986         if (r < 0)
5987                 goto fail_free_pio_data;
5988
5989         if (irqchip_in_kernel(kvm)) {
5990                 r = kvm_create_lapic(vcpu);
5991                 if (r < 0)
5992                         goto fail_mmu_destroy;
5993         }
5994
5995         vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
5996                                        GFP_KERNEL);
5997         if (!vcpu->arch.mce_banks) {
5998                 r = -ENOMEM;
5999                 goto fail_free_lapic;
6000         }
6001         vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
6002
6003         if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL))
6004                 goto fail_free_mce_banks;
6005
6006         kvm_async_pf_hash_reset(vcpu);
6007         kvm_pmu_init(vcpu);
6008
6009         return 0;
6010 fail_free_mce_banks:
6011         kfree(vcpu->arch.mce_banks);
6012 fail_free_lapic:
6013         kvm_free_lapic(vcpu);
6014 fail_mmu_destroy:
6015         kvm_mmu_destroy(vcpu);
6016 fail_free_pio_data:
6017         free_page((unsigned long)vcpu->arch.pio_data);
6018 fail:
6019         return r;
6020 }
6021
6022 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
6023 {
6024         int idx;
6025
6026         kvm_pmu_destroy(vcpu);
6027         kfree(vcpu->arch.mce_banks);
6028         kvm_free_lapic(vcpu);
6029         idx = srcu_read_lock(&vcpu->kvm->srcu);
6030         kvm_mmu_destroy(vcpu);
6031         srcu_read_unlock(&vcpu->kvm->srcu, idx);
6032         free_page((unsigned long)vcpu->arch.pio_data);
6033 }
6034
6035 int kvm_arch_init_vm(struct kvm *kvm)
6036 {
6037         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6038         INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
6039
6040         /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
6041         set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
6042
6043         raw_spin_lock_init(&kvm->arch.tsc_write_lock);
6044
6045         return 0;
6046 }
6047
6048 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
6049 {
6050         vcpu_load(vcpu);
6051         kvm_mmu_unload(vcpu);
6052         vcpu_put(vcpu);
6053 }
6054
6055 static void kvm_free_vcpus(struct kvm *kvm)
6056 {
6057         unsigned int i;
6058         struct kvm_vcpu *vcpu;
6059
6060         /*
6061          * Unpin any mmu pages first.
6062          */
6063         kvm_for_each_vcpu(i, vcpu, kvm) {
6064                 kvm_clear_async_pf_completion_queue(vcpu);
6065                 kvm_unload_vcpu_mmu(vcpu);
6066         }
6067         kvm_for_each_vcpu(i, vcpu, kvm)
6068                 kvm_arch_vcpu_free(vcpu);
6069
6070         mutex_lock(&kvm->lock);
6071         for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
6072                 kvm->vcpus[i] = NULL;
6073
6074         atomic_set(&kvm->online_vcpus, 0);
6075         mutex_unlock(&kvm->lock);
6076 }
6077
6078 void kvm_arch_sync_events(struct kvm *kvm)
6079 {
6080         kvm_free_all_assigned_devices(kvm);
6081         kvm_free_pit(kvm);
6082 }
6083
6084 void kvm_arch_destroy_vm(struct kvm *kvm)
6085 {
6086         kvm_iommu_unmap_guest(kvm);
6087         kfree(kvm->arch.vpic);
6088         kfree(kvm->arch.vioapic);
6089         kvm_free_vcpus(kvm);
6090         if (kvm->arch.apic_access_page)
6091                 put_page(kvm->arch.apic_access_page);
6092         if (kvm->arch.ept_identity_pagetable)
6093                 put_page(kvm->arch.ept_identity_pagetable);
6094 }
6095
6096 int kvm_arch_prepare_memory_region(struct kvm *kvm,
6097                                 struct kvm_memory_slot *memslot,
6098                                 struct kvm_memory_slot old,
6099                                 struct kvm_userspace_memory_region *mem,
6100                                 int user_alloc)
6101 {
6102         int npages = memslot->npages;
6103         int map_flags = MAP_PRIVATE | MAP_ANONYMOUS;
6104
6105         /* Prevent internal slot pages from being moved by fork()/COW. */
6106         if (memslot->id >= KVM_MEMORY_SLOTS)
6107                 map_flags = MAP_SHARED | MAP_ANONYMOUS;
6108
6109         /*To keep backward compatibility with older userspace,
6110          *x86 needs to hanlde !user_alloc case.
6111          */
6112         if (!user_alloc) {
6113                 if (npages && !old.rmap) {
6114                         unsigned long userspace_addr;
6115
6116                         down_write(&current->mm->mmap_sem);
6117                         userspace_addr = do_mmap(NULL, 0,
6118                                                  npages * PAGE_SIZE,
6119                                                  PROT_READ | PROT_WRITE,
6120                                                  map_flags,
6121                                                  0);
6122                         up_write(&current->mm->mmap_sem);
6123
6124                         if (IS_ERR((void *)userspace_addr))
6125                                 return PTR_ERR((void *)userspace_addr);
6126
6127                         memslot->userspace_addr = userspace_addr;
6128                 }
6129         }
6130
6131
6132         return 0;
6133 }
6134
6135 void kvm_arch_commit_memory_region(struct kvm *kvm,
6136                                 struct kvm_userspace_memory_region *mem,
6137                                 struct kvm_memory_slot old,
6138                                 int user_alloc)
6139 {
6140
6141         int nr_mmu_pages = 0, npages = mem->memory_size >> PAGE_SHIFT;
6142
6143         if (!user_alloc && !old.user_alloc && old.rmap && !npages) {
6144                 int ret;
6145
6146                 down_write(&current->mm->mmap_sem);
6147                 ret = do_munmap(current->mm, old.userspace_addr,
6148                                 old.npages * PAGE_SIZE);
6149                 up_write(&current->mm->mmap_sem);
6150                 if (ret < 0)
6151                         printk(KERN_WARNING
6152                                "kvm_vm_ioctl_set_memory_region: "
6153                                "failed to munmap memory\n");
6154         }
6155
6156         if (!kvm->arch.n_requested_mmu_pages)
6157                 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
6158
6159         spin_lock(&kvm->mmu_lock);
6160         if (nr_mmu_pages)
6161                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
6162         kvm_mmu_slot_remove_write_access(kvm, mem->slot);
6163         spin_unlock(&kvm->mmu_lock);
6164 }
6165
6166 void kvm_arch_flush_shadow(struct kvm *kvm)
6167 {
6168         kvm_mmu_zap_all(kvm);
6169         kvm_reload_remote_mmus(kvm);
6170 }
6171
6172 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
6173 {
6174         return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6175                 !vcpu->arch.apf.halted)
6176                 || !list_empty_careful(&vcpu->async_pf.done)
6177                 || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
6178                 || atomic_read(&vcpu->arch.nmi_queued) ||
6179                 (kvm_arch_interrupt_allowed(vcpu) &&
6180                  kvm_cpu_has_interrupt(vcpu));
6181 }
6182
6183 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
6184 {
6185         int me;
6186         int cpu = vcpu->cpu;
6187
6188         if (waitqueue_active(&vcpu->wq)) {
6189                 wake_up_interruptible(&vcpu->wq);
6190                 ++vcpu->stat.halt_wakeup;
6191         }
6192
6193         me = get_cpu();
6194         if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
6195                 if (kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE)
6196                         smp_send_reschedule(cpu);
6197         put_cpu();
6198 }
6199
6200 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
6201 {
6202         return kvm_x86_ops->interrupt_allowed(vcpu);
6203 }
6204
6205 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
6206 {
6207         unsigned long current_rip = kvm_rip_read(vcpu) +
6208                 get_segment_base(vcpu, VCPU_SREG_CS);
6209
6210         return current_rip == linear_rip;
6211 }
6212 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
6213
6214 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
6215 {
6216         unsigned long rflags;
6217
6218         rflags = kvm_x86_ops->get_rflags(vcpu);
6219         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6220                 rflags &= ~X86_EFLAGS_TF;
6221         return rflags;
6222 }
6223 EXPORT_SYMBOL_GPL(kvm_get_rflags);
6224
6225 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
6226 {
6227         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
6228             kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
6229                 rflags |= X86_EFLAGS_TF;
6230         kvm_x86_ops->set_rflags(vcpu, rflags);
6231         kvm_make_request(KVM_REQ_EVENT, vcpu);
6232 }
6233 EXPORT_SYMBOL_GPL(kvm_set_rflags);
6234
6235 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
6236 {
6237         int r;
6238
6239         if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
6240               is_error_page(work->page))
6241                 return;
6242
6243         r = kvm_mmu_reload(vcpu);
6244         if (unlikely(r))
6245                 return;
6246
6247         if (!vcpu->arch.mmu.direct_map &&
6248               work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
6249                 return;
6250
6251         vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
6252 }
6253
6254 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
6255 {
6256         return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
6257 }
6258
6259 static inline u32 kvm_async_pf_next_probe(u32 key)
6260 {
6261         return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
6262 }
6263
6264 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6265 {
6266         u32 key = kvm_async_pf_hash_fn(gfn);
6267
6268         while (vcpu->arch.apf.gfns[key] != ~0)
6269                 key = kvm_async_pf_next_probe(key);
6270
6271         vcpu->arch.apf.gfns[key] = gfn;
6272 }
6273
6274 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
6275 {
6276         int i;
6277         u32 key = kvm_async_pf_hash_fn(gfn);
6278
6279         for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
6280                      (vcpu->arch.apf.gfns[key] != gfn &&
6281                       vcpu->arch.apf.gfns[key] != ~0); i++)
6282                 key = kvm_async_pf_next_probe(key);
6283
6284         return key;
6285 }
6286
6287 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6288 {
6289         return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
6290 }
6291
6292 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6293 {
6294         u32 i, j, k;
6295
6296         i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
6297         while (true) {
6298                 vcpu->arch.apf.gfns[i] = ~0;
6299                 do {
6300                         j = kvm_async_pf_next_probe(j);
6301                         if (vcpu->arch.apf.gfns[j] == ~0)
6302                                 return;
6303                         k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
6304                         /*
6305                          * k lies cyclically in ]i,j]
6306                          * |    i.k.j |
6307                          * |....j i.k.| or  |.k..j i...|
6308                          */
6309                 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
6310                 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
6311                 i = j;
6312         }
6313 }
6314
6315 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
6316 {
6317
6318         return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
6319                                       sizeof(val));
6320 }
6321
6322 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
6323                                      struct kvm_async_pf *work)
6324 {
6325         struct x86_exception fault;
6326
6327         trace_kvm_async_pf_not_present(work->arch.token, work->gva);
6328         kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
6329
6330         if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
6331             (vcpu->arch.apf.send_user_only &&
6332              kvm_x86_ops->get_cpl(vcpu) == 0))
6333                 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
6334         else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
6335                 fault.vector = PF_VECTOR;
6336                 fault.error_code_valid = true;
6337                 fault.error_code = 0;
6338                 fault.nested_page_fault = false;
6339                 fault.address = work->arch.token;
6340                 kvm_inject_page_fault(vcpu, &fault);
6341         }
6342 }
6343
6344 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
6345                                  struct kvm_async_pf *work)
6346 {
6347         struct x86_exception fault;
6348
6349         trace_kvm_async_pf_ready(work->arch.token, work->gva);
6350         if (is_error_page(work->page))
6351                 work->arch.token = ~0; /* broadcast wakeup */
6352         else
6353                 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
6354
6355         if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
6356             !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
6357                 fault.vector = PF_VECTOR;
6358                 fault.error_code_valid = true;
6359                 fault.error_code = 0;
6360                 fault.nested_page_fault = false;
6361                 fault.address = work->arch.token;
6362                 kvm_inject_page_fault(vcpu, &fault);
6363         }
6364         vcpu->arch.apf.halted = false;
6365 }
6366
6367 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
6368 {
6369         if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
6370                 return true;
6371         else
6372                 return !kvm_event_needs_reinjection(vcpu) &&
6373                         kvm_x86_ops->interrupt_allowed(vcpu);
6374 }
6375
6376 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
6377 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
6378 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
6379 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
6380 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
6381 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
6382 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
6383 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
6384 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
6385 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
6386 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
6387 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);