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