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