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