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