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