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