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