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