KVM: VMX: Only reset MMU when necessary
[linux-2.6.git] / arch / x86 / kvm / x86.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * derived from drivers/kvm/kvm_main.c
5  *
6  * Copyright (C) 2006 Qumranet, Inc.
7  * Copyright (C) 2008 Qumranet, Inc.
8  * Copyright IBM Corporation, 2008
9  *
10  * Authors:
11  *   Avi Kivity   <avi@qumranet.com>
12  *   Yaniv Kamay  <yaniv@qumranet.com>
13  *   Amit Shah    <amit.shah@qumranet.com>
14  *   Ben-Ami Yassour <benami@il.ibm.com>
15  *
16  * This work is licensed under the terms of the GNU GPL, version 2.  See
17  * the COPYING file in the top-level directory.
18  *
19  */
20
21 #include <linux/kvm_host.h>
22 #include "irq.h"
23 #include "mmu.h"
24 #include "i8254.h"
25 #include "tss.h"
26 #include "kvm_cache_regs.h"
27 #include "x86.h"
28
29 #include <linux/clocksource.h>
30 #include <linux/interrupt.h>
31 #include <linux/kvm.h>
32 #include <linux/fs.h>
33 #include <linux/vmalloc.h>
34 #include <linux/module.h>
35 #include <linux/mman.h>
36 #include <linux/highmem.h>
37 #include <linux/iommu.h>
38 #include <linux/intel-iommu.h>
39 #include <linux/cpufreq.h>
40 #include <linux/user-return-notifier.h>
41 #include <linux/srcu.h>
42 #include <linux/slab.h>
43 #include <linux/perf_event.h>
44 #include <trace/events/kvm.h>
45
46 #define CREATE_TRACE_POINTS
47 #include "trace.h"
48
49 #include <asm/debugreg.h>
50 #include <asm/uaccess.h>
51 #include <asm/msr.h>
52 #include <asm/desc.h>
53 #include <asm/mtrr.h>
54 #include <asm/mce.h>
55
56 #define MAX_IO_MSRS 256
57 #define CR0_RESERVED_BITS                                               \
58         (~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
59                           | X86_CR0_ET | X86_CR0_NE | X86_CR0_WP | X86_CR0_AM \
60                           | X86_CR0_NW | X86_CR0_CD | X86_CR0_PG))
61 #define CR4_RESERVED_BITS                                               \
62         (~(unsigned long)(X86_CR4_VME | X86_CR4_PVI | X86_CR4_TSD | X86_CR4_DE\
63                           | X86_CR4_PSE | X86_CR4_PAE | X86_CR4_MCE     \
64                           | X86_CR4_PGE | X86_CR4_PCE | X86_CR4_OSFXSR  \
65                           | X86_CR4_OSXMMEXCPT | X86_CR4_VMXE))
66
67 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
68
69 #define KVM_MAX_MCE_BANKS 32
70 #define KVM_MCE_CAP_SUPPORTED MCG_CTL_P
71
72 /* EFER defaults:
73  * - enable syscall per default because its emulated by KVM
74  * - enable LME and LMA per default on 64 bit KVM
75  */
76 #ifdef CONFIG_X86_64
77 static u64 __read_mostly efer_reserved_bits = 0xfffffffffffffafeULL;
78 #else
79 static u64 __read_mostly efer_reserved_bits = 0xfffffffffffffffeULL;
80 #endif
81
82 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
83 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
84
85 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
86 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
87                                     struct kvm_cpuid_entry2 __user *entries);
88
89 struct kvm_x86_ops *kvm_x86_ops;
90 EXPORT_SYMBOL_GPL(kvm_x86_ops);
91
92 int ignore_msrs = 0;
93 module_param_named(ignore_msrs, ignore_msrs, bool, S_IRUGO | S_IWUSR);
94
95 #define KVM_NR_SHARED_MSRS 16
96
97 struct kvm_shared_msrs_global {
98         int nr;
99         u32 msrs[KVM_NR_SHARED_MSRS];
100 };
101
102 struct kvm_shared_msrs {
103         struct user_return_notifier urn;
104         bool registered;
105         struct kvm_shared_msr_values {
106                 u64 host;
107                 u64 curr;
108         } values[KVM_NR_SHARED_MSRS];
109 };
110
111 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
112 static DEFINE_PER_CPU(struct kvm_shared_msrs, shared_msrs);
113
114 struct kvm_stats_debugfs_item debugfs_entries[] = {
115         { "pf_fixed", VCPU_STAT(pf_fixed) },
116         { "pf_guest", VCPU_STAT(pf_guest) },
117         { "tlb_flush", VCPU_STAT(tlb_flush) },
118         { "invlpg", VCPU_STAT(invlpg) },
119         { "exits", VCPU_STAT(exits) },
120         { "io_exits", VCPU_STAT(io_exits) },
121         { "mmio_exits", VCPU_STAT(mmio_exits) },
122         { "signal_exits", VCPU_STAT(signal_exits) },
123         { "irq_window", VCPU_STAT(irq_window_exits) },
124         { "nmi_window", VCPU_STAT(nmi_window_exits) },
125         { "halt_exits", VCPU_STAT(halt_exits) },
126         { "halt_wakeup", VCPU_STAT(halt_wakeup) },
127         { "hypercalls", VCPU_STAT(hypercalls) },
128         { "request_irq", VCPU_STAT(request_irq_exits) },
129         { "irq_exits", VCPU_STAT(irq_exits) },
130         { "host_state_reload", VCPU_STAT(host_state_reload) },
131         { "efer_reload", VCPU_STAT(efer_reload) },
132         { "fpu_reload", VCPU_STAT(fpu_reload) },
133         { "insn_emulation", VCPU_STAT(insn_emulation) },
134         { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
135         { "irq_injections", VCPU_STAT(irq_injections) },
136         { "nmi_injections", VCPU_STAT(nmi_injections) },
137         { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
138         { "mmu_pte_write", VM_STAT(mmu_pte_write) },
139         { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
140         { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
141         { "mmu_flooded", VM_STAT(mmu_flooded) },
142         { "mmu_recycled", VM_STAT(mmu_recycled) },
143         { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
144         { "mmu_unsync", VM_STAT(mmu_unsync) },
145         { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
146         { "largepages", VM_STAT(lpages) },
147         { NULL }
148 };
149
150 static void kvm_on_user_return(struct user_return_notifier *urn)
151 {
152         unsigned slot;
153         struct kvm_shared_msrs *locals
154                 = container_of(urn, struct kvm_shared_msrs, urn);
155         struct kvm_shared_msr_values *values;
156
157         for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
158                 values = &locals->values[slot];
159                 if (values->host != values->curr) {
160                         wrmsrl(shared_msrs_global.msrs[slot], values->host);
161                         values->curr = values->host;
162                 }
163         }
164         locals->registered = false;
165         user_return_notifier_unregister(urn);
166 }
167
168 static void shared_msr_update(unsigned slot, u32 msr)
169 {
170         struct kvm_shared_msrs *smsr;
171         u64 value;
172
173         smsr = &__get_cpu_var(shared_msrs);
174         /* only read, and nobody should modify it at this time,
175          * so don't need lock */
176         if (slot >= shared_msrs_global.nr) {
177                 printk(KERN_ERR "kvm: invalid MSR slot!");
178                 return;
179         }
180         rdmsrl_safe(msr, &value);
181         smsr->values[slot].host = value;
182         smsr->values[slot].curr = value;
183 }
184
185 void kvm_define_shared_msr(unsigned slot, u32 msr)
186 {
187         if (slot >= shared_msrs_global.nr)
188                 shared_msrs_global.nr = slot + 1;
189         shared_msrs_global.msrs[slot] = msr;
190         /* we need ensured the shared_msr_global have been updated */
191         smp_wmb();
192 }
193 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
194
195 static void kvm_shared_msr_cpu_online(void)
196 {
197         unsigned i;
198
199         for (i = 0; i < shared_msrs_global.nr; ++i)
200                 shared_msr_update(i, shared_msrs_global.msrs[i]);
201 }
202
203 void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
204 {
205         struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
206
207         if (((value ^ smsr->values[slot].curr) & mask) == 0)
208                 return;
209         smsr->values[slot].curr = value;
210         wrmsrl(shared_msrs_global.msrs[slot], value);
211         if (!smsr->registered) {
212                 smsr->urn.on_user_return = kvm_on_user_return;
213                 user_return_notifier_register(&smsr->urn);
214                 smsr->registered = true;
215         }
216 }
217 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
218
219 static void drop_user_return_notifiers(void *ignore)
220 {
221         struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
222
223         if (smsr->registered)
224                 kvm_on_user_return(&smsr->urn);
225 }
226
227 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
228 {
229         if (irqchip_in_kernel(vcpu->kvm))
230                 return vcpu->arch.apic_base;
231         else
232                 return vcpu->arch.apic_base;
233 }
234 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
235
236 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
237 {
238         /* TODO: reserve bits check */
239         if (irqchip_in_kernel(vcpu->kvm))
240                 kvm_lapic_set_base(vcpu, data);
241         else
242                 vcpu->arch.apic_base = data;
243 }
244 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
245
246 #define EXCPT_BENIGN            0
247 #define EXCPT_CONTRIBUTORY      1
248 #define EXCPT_PF                2
249
250 static int exception_class(int vector)
251 {
252         switch (vector) {
253         case PF_VECTOR:
254                 return EXCPT_PF;
255         case DE_VECTOR:
256         case TS_VECTOR:
257         case NP_VECTOR:
258         case SS_VECTOR:
259         case GP_VECTOR:
260                 return EXCPT_CONTRIBUTORY;
261         default:
262                 break;
263         }
264         return EXCPT_BENIGN;
265 }
266
267 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
268                 unsigned nr, bool has_error, u32 error_code,
269                 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         vcpu_load(vcpu);
1545
1546         idx = srcu_read_lock(&vcpu->kvm->srcu);
1547         for (i = 0; i < msrs->nmsrs; ++i)
1548                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
1549                         break;
1550         srcu_read_unlock(&vcpu->kvm->srcu, idx);
1551
1552         vcpu_put(vcpu);
1553
1554         return i;
1555 }
1556
1557 /*
1558  * Read or write a bunch of msrs. Parameters are user addresses.
1559  *
1560  * @return number of msrs set successfully.
1561  */
1562 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
1563                   int (*do_msr)(struct kvm_vcpu *vcpu,
1564                                 unsigned index, u64 *data),
1565                   int writeback)
1566 {
1567         struct kvm_msrs msrs;
1568         struct kvm_msr_entry *entries;
1569         int r, n;
1570         unsigned size;
1571
1572         r = -EFAULT;
1573         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
1574                 goto out;
1575
1576         r = -E2BIG;
1577         if (msrs.nmsrs >= MAX_IO_MSRS)
1578                 goto out;
1579
1580         r = -ENOMEM;
1581         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
1582         entries = kmalloc(size, GFP_KERNEL);
1583         if (!entries)
1584                 goto out;
1585
1586         r = -EFAULT;
1587         if (copy_from_user(entries, user_msrs->entries, size))
1588                 goto out_free;
1589
1590         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
1591         if (r < 0)
1592                 goto out_free;
1593
1594         r = -EFAULT;
1595         if (writeback && copy_to_user(user_msrs->entries, entries, size))
1596                 goto out_free;
1597
1598         r = n;
1599
1600 out_free:
1601         kfree(entries);
1602 out:
1603         return r;
1604 }
1605
1606 int kvm_dev_ioctl_check_extension(long ext)
1607 {
1608         int r;
1609
1610         switch (ext) {
1611         case KVM_CAP_IRQCHIP:
1612         case KVM_CAP_HLT:
1613         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
1614         case KVM_CAP_SET_TSS_ADDR:
1615         case KVM_CAP_EXT_CPUID:
1616         case KVM_CAP_CLOCKSOURCE:
1617         case KVM_CAP_PIT:
1618         case KVM_CAP_NOP_IO_DELAY:
1619         case KVM_CAP_MP_STATE:
1620         case KVM_CAP_SYNC_MMU:
1621         case KVM_CAP_REINJECT_CONTROL:
1622         case KVM_CAP_IRQ_INJECT_STATUS:
1623         case KVM_CAP_ASSIGN_DEV_IRQ:
1624         case KVM_CAP_IRQFD:
1625         case KVM_CAP_IOEVENTFD:
1626         case KVM_CAP_PIT2:
1627         case KVM_CAP_PIT_STATE2:
1628         case KVM_CAP_SET_IDENTITY_MAP_ADDR:
1629         case KVM_CAP_XEN_HVM:
1630         case KVM_CAP_ADJUST_CLOCK:
1631         case KVM_CAP_VCPU_EVENTS:
1632         case KVM_CAP_HYPERV:
1633         case KVM_CAP_HYPERV_VAPIC:
1634         case KVM_CAP_HYPERV_SPIN:
1635         case KVM_CAP_PCI_SEGMENT:
1636         case KVM_CAP_DEBUGREGS:
1637         case KVM_CAP_X86_ROBUST_SINGLESTEP:
1638                 r = 1;
1639                 break;
1640         case KVM_CAP_COALESCED_MMIO:
1641                 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
1642                 break;
1643         case KVM_CAP_VAPIC:
1644                 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
1645                 break;
1646         case KVM_CAP_NR_VCPUS:
1647                 r = KVM_MAX_VCPUS;
1648                 break;
1649         case KVM_CAP_NR_MEMSLOTS:
1650                 r = KVM_MEMORY_SLOTS;
1651                 break;
1652         case KVM_CAP_PV_MMU:    /* obsolete */
1653                 r = 0;
1654                 break;
1655         case KVM_CAP_IOMMU:
1656                 r = iommu_found();
1657                 break;
1658         case KVM_CAP_MCE:
1659                 r = KVM_MAX_MCE_BANKS;
1660                 break;
1661         default:
1662                 r = 0;
1663                 break;
1664         }
1665         return r;
1666
1667 }
1668
1669 long kvm_arch_dev_ioctl(struct file *filp,
1670                         unsigned int ioctl, unsigned long arg)
1671 {
1672         void __user *argp = (void __user *)arg;
1673         long r;
1674
1675         switch (ioctl) {
1676         case KVM_GET_MSR_INDEX_LIST: {
1677                 struct kvm_msr_list __user *user_msr_list = argp;
1678                 struct kvm_msr_list msr_list;
1679                 unsigned n;
1680
1681                 r = -EFAULT;
1682                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
1683                         goto out;
1684                 n = msr_list.nmsrs;
1685                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
1686                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
1687                         goto out;
1688                 r = -E2BIG;
1689                 if (n < msr_list.nmsrs)
1690                         goto out;
1691                 r = -EFAULT;
1692                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
1693                                  num_msrs_to_save * sizeof(u32)))
1694                         goto out;
1695                 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
1696                                  &emulated_msrs,
1697                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
1698                         goto out;
1699                 r = 0;
1700                 break;
1701         }
1702         case KVM_GET_SUPPORTED_CPUID: {
1703                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1704                 struct kvm_cpuid2 cpuid;
1705
1706                 r = -EFAULT;
1707                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1708                         goto out;
1709                 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
1710                                                       cpuid_arg->entries);
1711                 if (r)
1712                         goto out;
1713
1714                 r = -EFAULT;
1715                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1716                         goto out;
1717                 r = 0;
1718                 break;
1719         }
1720         case KVM_X86_GET_MCE_CAP_SUPPORTED: {
1721                 u64 mce_cap;
1722
1723                 mce_cap = KVM_MCE_CAP_SUPPORTED;
1724                 r = -EFAULT;
1725                 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
1726                         goto out;
1727                 r = 0;
1728                 break;
1729         }
1730         default:
1731                 r = -EINVAL;
1732         }
1733 out:
1734         return r;
1735 }
1736
1737 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1738 {
1739         kvm_x86_ops->vcpu_load(vcpu, cpu);
1740         if (unlikely(per_cpu(cpu_tsc_khz, cpu) == 0)) {
1741                 unsigned long khz = cpufreq_quick_get(cpu);
1742                 if (!khz)
1743                         khz = tsc_khz;
1744                 per_cpu(cpu_tsc_khz, cpu) = khz;
1745         }
1746         kvm_request_guest_time_update(vcpu);
1747 }
1748
1749 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
1750 {
1751         kvm_x86_ops->vcpu_put(vcpu);
1752         kvm_put_guest_fpu(vcpu);
1753 }
1754
1755 static int is_efer_nx(void)
1756 {
1757         unsigned long long efer = 0;
1758
1759         rdmsrl_safe(MSR_EFER, &efer);
1760         return efer & EFER_NX;
1761 }
1762
1763 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
1764 {
1765         int i;
1766         struct kvm_cpuid_entry2 *e, *entry;
1767
1768         entry = NULL;
1769         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
1770                 e = &vcpu->arch.cpuid_entries[i];
1771                 if (e->function == 0x80000001) {
1772                         entry = e;
1773                         break;
1774                 }
1775         }
1776         if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
1777                 entry->edx &= ~(1 << 20);
1778                 printk(KERN_INFO "kvm: guest NX capability removed\n");
1779         }
1780 }
1781
1782 /* when an old userspace process fills a new kernel module */
1783 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
1784                                     struct kvm_cpuid *cpuid,
1785                                     struct kvm_cpuid_entry __user *entries)
1786 {
1787         int r, i;
1788         struct kvm_cpuid_entry *cpuid_entries;
1789
1790         r = -E2BIG;
1791         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1792                 goto out;
1793         r = -ENOMEM;
1794         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
1795         if (!cpuid_entries)
1796                 goto out;
1797         r = -EFAULT;
1798         if (copy_from_user(cpuid_entries, entries,
1799                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
1800                 goto out_free;
1801         vcpu_load(vcpu);
1802         for (i = 0; i < cpuid->nent; i++) {
1803                 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
1804                 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
1805                 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
1806                 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
1807                 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
1808                 vcpu->arch.cpuid_entries[i].index = 0;
1809                 vcpu->arch.cpuid_entries[i].flags = 0;
1810                 vcpu->arch.cpuid_entries[i].padding[0] = 0;
1811                 vcpu->arch.cpuid_entries[i].padding[1] = 0;
1812                 vcpu->arch.cpuid_entries[i].padding[2] = 0;
1813         }
1814         vcpu->arch.cpuid_nent = cpuid->nent;
1815         cpuid_fix_nx_cap(vcpu);
1816         r = 0;
1817         kvm_apic_set_version(vcpu);
1818         kvm_x86_ops->cpuid_update(vcpu);
1819         vcpu_put(vcpu);
1820
1821 out_free:
1822         vfree(cpuid_entries);
1823 out:
1824         return r;
1825 }
1826
1827 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
1828                                      struct kvm_cpuid2 *cpuid,
1829                                      struct kvm_cpuid_entry2 __user *entries)
1830 {
1831         int r;
1832
1833         r = -E2BIG;
1834         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1835                 goto out;
1836         r = -EFAULT;
1837         if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
1838                            cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
1839                 goto out;
1840         vcpu_load(vcpu);
1841         vcpu->arch.cpuid_nent = cpuid->nent;
1842         kvm_apic_set_version(vcpu);
1843         kvm_x86_ops->cpuid_update(vcpu);
1844         vcpu_put(vcpu);
1845         return 0;
1846
1847 out:
1848         return r;
1849 }
1850
1851 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
1852                                      struct kvm_cpuid2 *cpuid,
1853                                      struct kvm_cpuid_entry2 __user *entries)
1854 {
1855         int r;
1856
1857         vcpu_load(vcpu);
1858         r = -E2BIG;
1859         if (cpuid->nent < vcpu->arch.cpuid_nent)
1860                 goto out;
1861         r = -EFAULT;
1862         if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
1863                          vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
1864                 goto out;
1865         return 0;
1866
1867 out:
1868         cpuid->nent = vcpu->arch.cpuid_nent;
1869         vcpu_put(vcpu);
1870         return r;
1871 }
1872
1873 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1874                            u32 index)
1875 {
1876         entry->function = function;
1877         entry->index = index;
1878         cpuid_count(entry->function, entry->index,
1879                     &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
1880         entry->flags = 0;
1881 }
1882
1883 #define F(x) bit(X86_FEATURE_##x)
1884
1885 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1886                          u32 index, int *nent, int maxnent)
1887 {
1888         unsigned f_nx = is_efer_nx() ? F(NX) : 0;
1889 #ifdef CONFIG_X86_64
1890         unsigned f_gbpages = (kvm_x86_ops->get_lpage_level() == PT_PDPE_LEVEL)
1891                                 ? F(GBPAGES) : 0;
1892         unsigned f_lm = F(LM);
1893 #else
1894         unsigned f_gbpages = 0;
1895         unsigned f_lm = 0;
1896 #endif
1897         unsigned f_rdtscp = kvm_x86_ops->rdtscp_supported() ? F(RDTSCP) : 0;
1898
1899         /* cpuid 1.edx */
1900         const u32 kvm_supported_word0_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(SEP) |
1904                 F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
1905                 F(PAT) | F(PSE36) | 0 /* PSN */ | F(CLFLSH) |
1906                 0 /* Reserved, DS, ACPI */ | F(MMX) |
1907                 F(FXSR) | F(XMM) | F(XMM2) | F(SELFSNOOP) |
1908                 0 /* HTT, TM, Reserved, PBE */;
1909         /* cpuid 0x80000001.edx */
1910         const u32 kvm_supported_word1_x86_features =
1911                 F(FPU) | F(VME) | F(DE) | F(PSE) |
1912                 F(TSC) | F(MSR) | F(PAE) | F(MCE) |
1913                 F(CX8) | F(APIC) | 0 /* Reserved */ | F(SYSCALL) |
1914                 F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
1915                 F(PAT) | F(PSE36) | 0 /* Reserved */ |
1916                 f_nx | 0 /* Reserved */ | F(MMXEXT) | F(MMX) |
1917                 F(FXSR) | F(FXSR_OPT) | f_gbpages | f_rdtscp |
1918                 0 /* Reserved */ | f_lm | F(3DNOWEXT) | F(3DNOW);
1919         /* cpuid 1.ecx */
1920         const u32 kvm_supported_word4_x86_features =
1921                 F(XMM3) | 0 /* Reserved, DTES64, MONITOR */ |
1922                 0 /* DS-CPL, VMX, SMX, EST */ |
1923                 0 /* TM2 */ | F(SSSE3) | 0 /* CNXT-ID */ | 0 /* Reserved */ |
1924                 0 /* Reserved */ | F(CX16) | 0 /* xTPR Update, PDCM */ |
1925                 0 /* Reserved, DCA */ | F(XMM4_1) |
1926                 F(XMM4_2) | F(X2APIC) | F(MOVBE) | F(POPCNT) |
1927                 0 /* Reserved, XSAVE, OSXSAVE */;
1928         /* cpuid 0x80000001.ecx */
1929         const u32 kvm_supported_word6_x86_features =
1930                 F(LAHF_LM) | F(CMP_LEGACY) | F(SVM) | 0 /* ExtApicSpace */ |
1931                 F(CR8_LEGACY) | F(ABM) | F(SSE4A) | F(MISALIGNSSE) |
1932                 F(3DNOWPREFETCH) | 0 /* OSVW */ | 0 /* IBS */ | F(SSE5) |
1933                 0 /* SKINIT */ | 0 /* WDT */;
1934
1935         /* all calls to cpuid_count() should be made on the same cpu */
1936         get_cpu();
1937         do_cpuid_1_ent(entry, function, index);
1938         ++*nent;
1939
1940         switch (function) {
1941         case 0:
1942                 entry->eax = min(entry->eax, (u32)0xb);
1943                 break;
1944         case 1:
1945                 entry->edx &= kvm_supported_word0_x86_features;
1946                 entry->ecx &= kvm_supported_word4_x86_features;
1947                 /* we support x2apic emulation even if host does not support
1948                  * it since we emulate x2apic in software */
1949                 entry->ecx |= F(X2APIC);
1950                 break;
1951         /* function 2 entries are STATEFUL. That is, repeated cpuid commands
1952          * may return different values. This forces us to get_cpu() before
1953          * issuing the first command, and also to emulate this annoying behavior
1954          * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
1955         case 2: {
1956                 int t, times = entry->eax & 0xff;
1957
1958                 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1959                 entry->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
1960                 for (t = 1; t < times && *nent < maxnent; ++t) {
1961                         do_cpuid_1_ent(&entry[t], function, 0);
1962                         entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1963                         ++*nent;
1964                 }
1965                 break;
1966         }
1967         /* function 4 and 0xb have additional index. */
1968         case 4: {
1969                 int i, cache_type;
1970
1971                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1972                 /* read more entries until cache_type is zero */
1973                 for (i = 1; *nent < maxnent; ++i) {
1974                         cache_type = entry[i - 1].eax & 0x1f;
1975                         if (!cache_type)
1976                                 break;
1977                         do_cpuid_1_ent(&entry[i], function, i);
1978                         entry[i].flags |=
1979                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1980                         ++*nent;
1981                 }
1982                 break;
1983         }
1984         case 0xb: {
1985                 int i, level_type;
1986
1987                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1988                 /* read more entries until level_type is zero */
1989                 for (i = 1; *nent < maxnent; ++i) {
1990                         level_type = entry[i - 1].ecx & 0xff00;
1991                         if (!level_type)
1992                                 break;
1993                         do_cpuid_1_ent(&entry[i], function, i);
1994                         entry[i].flags |=
1995                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1996                         ++*nent;
1997                 }
1998                 break;
1999         }
2000         case KVM_CPUID_SIGNATURE: {
2001                 char signature[12] = "KVMKVMKVM\0\0";
2002                 u32 *sigptr = (u32 *)signature;
2003                 entry->eax = 0;
2004                 entry->ebx = sigptr[0];
2005                 entry->ecx = sigptr[1];
2006                 entry->edx = sigptr[2];
2007                 break;
2008         }
2009         case KVM_CPUID_FEATURES:
2010                 entry->eax = (1 << KVM_FEATURE_CLOCKSOURCE) |
2011                              (1 << KVM_FEATURE_NOP_IO_DELAY) |
2012                              (1 << KVM_FEATURE_CLOCKSOURCE2) |
2013                              (1 << KVM_FEATURE_CLOCKSOURCE_STABLE_BIT);
2014                 entry->ebx = 0;
2015                 entry->ecx = 0;
2016                 entry->edx = 0;
2017                 break;
2018         case 0x80000000:
2019                 entry->eax = min(entry->eax, 0x8000001a);
2020                 break;
2021         case 0x80000001:
2022                 entry->edx &= kvm_supported_word1_x86_features;
2023                 entry->ecx &= kvm_supported_word6_x86_features;
2024                 break;
2025         }
2026
2027         kvm_x86_ops->set_supported_cpuid(function, entry);
2028
2029         put_cpu();
2030 }
2031
2032 #undef F
2033
2034 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
2035                                      struct kvm_cpuid_entry2 __user *entries)
2036 {
2037         struct kvm_cpuid_entry2 *cpuid_entries;
2038         int limit, nent = 0, r = -E2BIG;
2039         u32 func;
2040
2041         if (cpuid->nent < 1)
2042                 goto out;
2043         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2044                 cpuid->nent = KVM_MAX_CPUID_ENTRIES;
2045         r = -ENOMEM;
2046         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
2047         if (!cpuid_entries)
2048                 goto out;
2049
2050         do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
2051         limit = cpuid_entries[0].eax;
2052         for (func = 1; func <= limit && nent < cpuid->nent; ++func)
2053                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
2054                              &nent, cpuid->nent);
2055         r = -E2BIG;
2056         if (nent >= cpuid->nent)
2057                 goto out_free;
2058
2059         do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
2060         limit = cpuid_entries[nent - 1].eax;
2061         for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
2062                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
2063                              &nent, cpuid->nent);
2064
2065
2066
2067         r = -E2BIG;
2068         if (nent >= cpuid->nent)
2069                 goto out_free;
2070
2071         do_cpuid_ent(&cpuid_entries[nent], KVM_CPUID_SIGNATURE, 0, &nent,
2072                      cpuid->nent);
2073
2074         r = -E2BIG;
2075         if (nent >= cpuid->nent)
2076                 goto out_free;
2077
2078         do_cpuid_ent(&cpuid_entries[nent], KVM_CPUID_FEATURES, 0, &nent,
2079                      cpuid->nent);
2080
2081         r = -E2BIG;
2082         if (nent >= cpuid->nent)
2083                 goto out_free;
2084
2085         r = -EFAULT;
2086         if (copy_to_user(entries, cpuid_entries,
2087                          nent * sizeof(struct kvm_cpuid_entry2)))
2088                 goto out_free;
2089         cpuid->nent = nent;
2090         r = 0;
2091
2092 out_free:
2093         vfree(cpuid_entries);
2094 out:
2095         return r;
2096 }
2097
2098 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2099                                     struct kvm_lapic_state *s)
2100 {
2101         vcpu_load(vcpu);
2102         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2103         vcpu_put(vcpu);
2104
2105         return 0;
2106 }
2107
2108 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2109                                     struct kvm_lapic_state *s)
2110 {
2111         vcpu_load(vcpu);
2112         memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
2113         kvm_apic_post_state_restore(vcpu);
2114         update_cr8_intercept(vcpu);
2115         vcpu_put(vcpu);
2116
2117         return 0;
2118 }
2119
2120 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2121                                     struct kvm_interrupt *irq)
2122 {
2123         if (irq->irq < 0 || irq->irq >= 256)
2124                 return -EINVAL;
2125         if (irqchip_in_kernel(vcpu->kvm))
2126                 return -ENXIO;
2127         vcpu_load(vcpu);
2128
2129         kvm_queue_interrupt(vcpu, irq->irq, false);
2130
2131         vcpu_put(vcpu);
2132
2133         return 0;
2134 }
2135
2136 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2137 {
2138         vcpu_load(vcpu);
2139         kvm_inject_nmi(vcpu);
2140         vcpu_put(vcpu);
2141
2142         return 0;
2143 }
2144
2145 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2146                                            struct kvm_tpr_access_ctl *tac)
2147 {
2148         if (tac->flags)
2149                 return -EINVAL;
2150         vcpu->arch.tpr_access_reporting = !!tac->enabled;
2151         return 0;
2152 }
2153
2154 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2155                                         u64 mcg_cap)
2156 {
2157         int r;
2158         unsigned bank_num = mcg_cap & 0xff, bank;
2159
2160         vcpu_load(vcpu);
2161         r = -EINVAL;
2162         if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2163                 goto out;
2164         if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2165                 goto out;
2166         r = 0;
2167         vcpu->arch.mcg_cap = mcg_cap;
2168         /* Init IA32_MCG_CTL to all 1s */
2169         if (mcg_cap & MCG_CTL_P)
2170                 vcpu->arch.mcg_ctl = ~(u64)0;
2171         /* Init IA32_MCi_CTL to all 1s */
2172         for (bank = 0; bank < bank_num; bank++)
2173                 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2174 out:
2175         vcpu_put(vcpu);
2176         return r;
2177 }
2178
2179 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2180                                       struct kvm_x86_mce *mce)
2181 {
2182         u64 mcg_cap = vcpu->arch.mcg_cap;
2183         unsigned bank_num = mcg_cap & 0xff;
2184         u64 *banks = vcpu->arch.mce_banks;
2185
2186         if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2187                 return -EINVAL;
2188         /*
2189          * if IA32_MCG_CTL is not all 1s, the uncorrected error
2190          * reporting is disabled
2191          */
2192         if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2193             vcpu->arch.mcg_ctl != ~(u64)0)
2194                 return 0;
2195         banks += 4 * mce->bank;
2196         /*
2197          * if IA32_MCi_CTL is not all 1s, the uncorrected error
2198          * reporting is disabled for the bank
2199          */
2200         if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2201                 return 0;
2202         if (mce->status & MCI_STATUS_UC) {
2203                 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2204                     !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2205                         printk(KERN_DEBUG "kvm: set_mce: "
2206                                "injects mce exception while "
2207                                "previous one is in progress!\n");
2208                         set_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests);
2209                         return 0;
2210                 }
2211                 if (banks[1] & MCI_STATUS_VAL)
2212                         mce->status |= MCI_STATUS_OVER;
2213                 banks[2] = mce->addr;
2214                 banks[3] = mce->misc;
2215                 vcpu->arch.mcg_status = mce->mcg_status;
2216                 banks[1] = mce->status;
2217                 kvm_queue_exception(vcpu, MC_VECTOR);
2218         } else if (!(banks[1] & MCI_STATUS_VAL)
2219                    || !(banks[1] & MCI_STATUS_UC)) {
2220                 if (banks[1] & MCI_STATUS_VAL)
2221                         mce->status |= MCI_STATUS_OVER;
2222                 banks[2] = mce->addr;
2223                 banks[3] = mce->misc;
2224                 banks[1] = mce->status;
2225         } else
2226                 banks[1] |= MCI_STATUS_OVER;
2227         return 0;
2228 }
2229
2230 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2231                                                struct kvm_vcpu_events *events)
2232 {
2233         vcpu_load(vcpu);
2234
2235         events->exception.injected =
2236                 vcpu->arch.exception.pending &&
2237                 !kvm_exception_is_soft(vcpu->arch.exception.nr);
2238         events->exception.nr = vcpu->arch.exception.nr;
2239         events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2240         events->exception.error_code = vcpu->arch.exception.error_code;
2241
2242         events->interrupt.injected =
2243                 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
2244         events->interrupt.nr = vcpu->arch.interrupt.nr;
2245         events->interrupt.soft = 0;
2246         events->interrupt.shadow =
2247                 kvm_x86_ops->get_interrupt_shadow(vcpu,
2248                         KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
2249
2250         events->nmi.injected = vcpu->arch.nmi_injected;
2251         events->nmi.pending = vcpu->arch.nmi_pending;
2252         events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
2253
2254         events->sipi_vector = vcpu->arch.sipi_vector;
2255
2256         events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
2257                          | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2258                          | KVM_VCPUEVENT_VALID_SHADOW);
2259
2260         vcpu_put(vcpu);
2261 }
2262
2263 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
2264                                               struct kvm_vcpu_events *events)
2265 {
2266         if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
2267                               | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2268                               | KVM_VCPUEVENT_VALID_SHADOW))
2269                 return -EINVAL;
2270
2271         vcpu_load(vcpu);
2272
2273         vcpu->arch.exception.pending = events->exception.injected;
2274         vcpu->arch.exception.nr = events->exception.nr;
2275         vcpu->arch.exception.has_error_code = events->exception.has_error_code;
2276         vcpu->arch.exception.error_code = events->exception.error_code;
2277
2278         vcpu->arch.interrupt.pending = events->interrupt.injected;
2279         vcpu->arch.interrupt.nr = events->interrupt.nr;
2280         vcpu->arch.interrupt.soft = events->interrupt.soft;
2281         if (vcpu->arch.interrupt.pending && irqchip_in_kernel(vcpu->kvm))
2282                 kvm_pic_clear_isr_ack(vcpu->kvm);
2283         if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
2284                 kvm_x86_ops->set_interrupt_shadow(vcpu,
2285                                                   events->interrupt.shadow);
2286
2287         vcpu->arch.nmi_injected = events->nmi.injected;
2288         if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
2289                 vcpu->arch.nmi_pending = events->nmi.pending;
2290         kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
2291
2292         if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR)
2293                 vcpu->arch.sipi_vector = events->sipi_vector;
2294
2295         vcpu_put(vcpu);
2296
2297         return 0;
2298 }
2299
2300 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
2301                                              struct kvm_debugregs *dbgregs)
2302 {
2303         vcpu_load(vcpu);
2304
2305         memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
2306         dbgregs->dr6 = vcpu->arch.dr6;
2307         dbgregs->dr7 = vcpu->arch.dr7;
2308         dbgregs->flags = 0;
2309
2310         vcpu_put(vcpu);
2311 }
2312
2313 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
2314                                             struct kvm_debugregs *dbgregs)
2315 {
2316         if (dbgregs->flags)
2317                 return -EINVAL;
2318
2319         vcpu_load(vcpu);
2320
2321         memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
2322         vcpu->arch.dr6 = dbgregs->dr6;
2323         vcpu->arch.dr7 = dbgregs->dr7;
2324
2325         vcpu_put(vcpu);
2326
2327         return 0;
2328 }
2329
2330 long kvm_arch_vcpu_ioctl(struct file *filp,
2331                          unsigned int ioctl, unsigned long arg)
2332 {
2333         struct kvm_vcpu *vcpu = filp->private_data;
2334         void __user *argp = (void __user *)arg;
2335         int r;
2336         struct kvm_lapic_state *lapic = NULL;
2337
2338         switch (ioctl) {
2339         case KVM_GET_LAPIC: {
2340                 r = -EINVAL;
2341                 if (!vcpu->arch.apic)
2342                         goto out;
2343                 lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
2344
2345                 r = -ENOMEM;
2346                 if (!lapic)
2347                         goto out;
2348                 r = kvm_vcpu_ioctl_get_lapic(vcpu, lapic);
2349                 if (r)
2350                         goto out;
2351                 r = -EFAULT;
2352                 if (copy_to_user(argp, lapic, sizeof(struct kvm_lapic_state)))
2353                         goto out;
2354                 r = 0;
2355                 break;
2356         }
2357         case KVM_SET_LAPIC: {
2358                 r = -EINVAL;
2359                 if (!vcpu->arch.apic)
2360                         goto out;
2361                 lapic = kmalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
2362                 r = -ENOMEM;
2363                 if (!lapic)
2364                         goto out;
2365                 r = -EFAULT;
2366                 if (copy_from_user(lapic, argp, sizeof(struct kvm_lapic_state)))
2367                         goto out;
2368                 r = kvm_vcpu_ioctl_set_lapic(vcpu, lapic);
2369                 if (r)
2370                         goto out;
2371                 r = 0;
2372                 break;
2373         }
2374         case KVM_INTERRUPT: {
2375                 struct kvm_interrupt irq;
2376
2377                 r = -EFAULT;
2378                 if (copy_from_user(&irq, argp, sizeof irq))
2379                         goto out;
2380                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
2381                 if (r)
2382                         goto out;
2383                 r = 0;
2384                 break;
2385         }
2386         case KVM_NMI: {
2387                 r = kvm_vcpu_ioctl_nmi(vcpu);
2388                 if (r)
2389                         goto out;
2390                 r = 0;
2391                 break;
2392         }
2393         case KVM_SET_CPUID: {
2394                 struct kvm_cpuid __user *cpuid_arg = argp;
2395                 struct kvm_cpuid cpuid;
2396
2397                 r = -EFAULT;
2398                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2399                         goto out;
2400                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
2401                 if (r)
2402                         goto out;
2403                 break;
2404         }
2405         case KVM_SET_CPUID2: {
2406                 struct kvm_cpuid2 __user *cpuid_arg = argp;
2407                 struct kvm_cpuid2 cpuid;
2408
2409                 r = -EFAULT;
2410                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2411                         goto out;
2412                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
2413                                               cpuid_arg->entries);
2414                 if (r)
2415                         goto out;
2416                 break;
2417         }
2418         case KVM_GET_CPUID2: {
2419                 struct kvm_cpuid2 __user *cpuid_arg = argp;
2420                 struct kvm_cpuid2 cpuid;
2421
2422                 r = -EFAULT;
2423                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2424                         goto out;
2425                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
2426                                               cpuid_arg->entries);
2427                 if (r)
2428                         goto out;
2429                 r = -EFAULT;
2430                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2431                         goto out;
2432                 r = 0;
2433                 break;
2434         }
2435         case KVM_GET_MSRS:
2436                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
2437                 break;
2438         case KVM_SET_MSRS:
2439                 r = msr_io(vcpu, argp, do_set_msr, 0);
2440                 break;
2441         case KVM_TPR_ACCESS_REPORTING: {
2442                 struct kvm_tpr_access_ctl tac;
2443
2444                 r = -EFAULT;
2445                 if (copy_from_user(&tac, argp, sizeof tac))
2446                         goto out;
2447                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
2448                 if (r)
2449                         goto out;
2450                 r = -EFAULT;
2451                 if (copy_to_user(argp, &tac, sizeof tac))
2452                         goto out;
2453                 r = 0;
2454                 break;
2455         };
2456         case KVM_SET_VAPIC_ADDR: {
2457                 struct kvm_vapic_addr va;
2458
2459                 r = -EINVAL;
2460                 if (!irqchip_in_kernel(vcpu->kvm))
2461                         goto out;
2462                 r = -EFAULT;
2463                 if (copy_from_user(&va, argp, sizeof va))
2464                         goto out;
2465                 r = 0;
2466                 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
2467                 break;
2468         }
2469         case KVM_X86_SETUP_MCE: {
2470                 u64 mcg_cap;
2471
2472                 r = -EFAULT;
2473                 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
2474                         goto out;
2475                 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
2476                 break;
2477         }
2478         case KVM_X86_SET_MCE: {
2479                 struct kvm_x86_mce mce;
2480
2481                 r = -EFAULT;
2482                 if (copy_from_user(&mce, argp, sizeof mce))
2483                         goto out;
2484                 vcpu_load(vcpu);
2485                 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
2486                 vcpu_put(vcpu);
2487                 break;
2488         }
2489         case KVM_GET_VCPU_EVENTS: {
2490                 struct kvm_vcpu_events events;
2491
2492                 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
2493
2494                 r = -EFAULT;
2495                 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
2496                         break;
2497                 r = 0;
2498                 break;
2499         }
2500         case KVM_SET_VCPU_EVENTS: {
2501                 struct kvm_vcpu_events events;
2502
2503                 r = -EFAULT;
2504                 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
2505                         break;
2506
2507                 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
2508                 break;
2509         }
2510         case KVM_GET_DEBUGREGS: {
2511                 struct kvm_debugregs dbgregs;
2512
2513                 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
2514
2515                 r = -EFAULT;
2516                 if (copy_to_user(argp, &dbgregs,
2517                                  sizeof(struct kvm_debugregs)))
2518                         break;
2519                 r = 0;
2520                 break;
2521         }
2522         case KVM_SET_DEBUGREGS: {
2523                 struct kvm_debugregs dbgregs;
2524
2525                 r = -EFAULT;
2526                 if (copy_from_user(&dbgregs, argp,
2527                                    sizeof(struct kvm_debugregs)))
2528                         break;
2529
2530                 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
2531                 break;
2532         }
2533         default:
2534                 r = -EINVAL;
2535         }
2536 out:
2537         kfree(lapic);
2538         return r;
2539 }
2540
2541 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
2542 {
2543         int ret;
2544
2545         if (addr > (unsigned int)(-3 * PAGE_SIZE))
2546                 return -1;
2547         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
2548         return ret;
2549 }
2550
2551 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
2552                                               u64 ident_addr)
2553 {
2554         kvm->arch.ept_identity_map_addr = ident_addr;
2555         return 0;
2556 }
2557
2558 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
2559                                           u32 kvm_nr_mmu_pages)
2560 {
2561         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
2562                 return -EINVAL;
2563
2564         mutex_lock(&kvm->slots_lock);
2565         spin_lock(&kvm->mmu_lock);
2566
2567         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
2568         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
2569
2570         spin_unlock(&kvm->mmu_lock);
2571         mutex_unlock(&kvm->slots_lock);
2572         return 0;
2573 }
2574
2575 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
2576 {
2577         return kvm->arch.n_alloc_mmu_pages;
2578 }
2579
2580 gfn_t unalias_gfn_instantiation(struct kvm *kvm, gfn_t gfn)
2581 {
2582         int i;
2583         struct kvm_mem_alias *alias;
2584         struct kvm_mem_aliases *aliases;
2585
2586         aliases = kvm_aliases(kvm);
2587
2588         for (i = 0; i < aliases->naliases; ++i) {
2589                 alias = &aliases->aliases[i];
2590                 if (alias->flags & KVM_ALIAS_INVALID)
2591                         continue;
2592                 if (gfn >= alias->base_gfn
2593                     && gfn < alias->base_gfn + alias->npages)
2594                         return alias->target_gfn + gfn - alias->base_gfn;
2595         }
2596         return gfn;
2597 }
2598
2599 gfn_t unalias_gfn(struct kvm *kvm, gfn_t gfn)
2600 {
2601         int i;
2602         struct kvm_mem_alias *alias;
2603         struct kvm_mem_aliases *aliases;
2604
2605         aliases = kvm_aliases(kvm);
2606
2607         for (i = 0; i < aliases->naliases; ++i) {
2608                 alias = &aliases->aliases[i];
2609                 if (gfn >= alias->base_gfn
2610                     && gfn < alias->base_gfn + alias->npages)
2611                         return alias->target_gfn + gfn - alias->base_gfn;
2612         }
2613         return gfn;
2614 }
2615
2616 /*
2617  * Set a new alias region.  Aliases map a portion of physical memory into
2618  * another portion.  This is useful for memory windows, for example the PC
2619  * VGA region.
2620  */
2621 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
2622                                          struct kvm_memory_alias *alias)
2623 {
2624         int r, n;
2625         struct kvm_mem_alias *p;
2626         struct kvm_mem_aliases *aliases, *old_aliases;
2627
2628         r = -EINVAL;
2629         /* General sanity checks */
2630         if (alias->memory_size & (PAGE_SIZE - 1))
2631                 goto out;
2632         if (alias->guest_phys_addr & (PAGE_SIZE - 1))
2633                 goto out;
2634         if (alias->slot >= KVM_ALIAS_SLOTS)
2635                 goto out;
2636         if (alias->guest_phys_addr + alias->memory_size
2637             < alias->guest_phys_addr)
2638                 goto out;
2639         if (alias->target_phys_addr + alias->memory_size
2640             < alias->target_phys_addr)
2641                 goto out;
2642
2643         r = -ENOMEM;
2644         aliases = kzalloc(sizeof(struct kvm_mem_aliases), GFP_KERNEL);
2645         if (!aliases)
2646                 goto out;
2647
2648         mutex_lock(&kvm->slots_lock);
2649
2650         /* invalidate any gfn reference in case of deletion/shrinking */
2651         memcpy(aliases, kvm->arch.aliases, sizeof(struct kvm_mem_aliases));
2652         aliases->aliases[alias->slot].flags |= KVM_ALIAS_INVALID;
2653         old_aliases = kvm->arch.aliases;
2654         rcu_assign_pointer(kvm->arch.aliases, aliases);
2655         synchronize_srcu_expedited(&kvm->srcu);
2656         kvm_mmu_zap_all(kvm);
2657         kfree(old_aliases);
2658
2659         r = -ENOMEM;
2660         aliases = kzalloc(sizeof(struct kvm_mem_aliases), GFP_KERNEL);
2661         if (!aliases)
2662                 goto out_unlock;
2663
2664         memcpy(aliases, kvm->arch.aliases, sizeof(struct kvm_mem_aliases));
2665
2666         p = &aliases->aliases[alias->slot];
2667         p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
2668         p->npages = alias->memory_size >> PAGE_SHIFT;
2669         p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
2670         p->flags &= ~(KVM_ALIAS_INVALID);
2671
2672         for (n = KVM_ALIAS_SLOTS; n > 0; --n)
2673                 if (aliases->aliases[n - 1].npages)
2674                         break;
2675         aliases->naliases = n;
2676
2677         old_aliases = kvm->arch.aliases;
2678         rcu_assign_pointer(kvm->arch.aliases, aliases);
2679         synchronize_srcu_expedited(&kvm->srcu);
2680         kfree(old_aliases);
2681         r = 0;
2682
2683 out_unlock:
2684         mutex_unlock(&kvm->slots_lock);
2685 out:
2686         return r;
2687 }
2688
2689 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2690 {
2691         int r;
2692
2693         r = 0;
2694         switch (chip->chip_id) {
2695         case KVM_IRQCHIP_PIC_MASTER:
2696                 memcpy(&chip->chip.pic,
2697                         &pic_irqchip(kvm)->pics[0],
2698                         sizeof(struct kvm_pic_state));
2699                 break;
2700         case KVM_IRQCHIP_PIC_SLAVE:
2701                 memcpy(&chip->chip.pic,
2702                         &pic_irqchip(kvm)->pics[1],
2703                         sizeof(struct kvm_pic_state));
2704                 break;
2705         case KVM_IRQCHIP_IOAPIC:
2706                 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
2707                 break;
2708         default:
2709                 r = -EINVAL;
2710                 break;
2711         }
2712         return r;
2713 }
2714
2715 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
2716 {
2717         int r;
2718
2719         r = 0;
2720         switch (chip->chip_id) {
2721         case KVM_IRQCHIP_PIC_MASTER:
2722                 raw_spin_lock(&pic_irqchip(kvm)->lock);
2723                 memcpy(&pic_irqchip(kvm)->pics[0],
2724                         &chip->chip.pic,
2725                         sizeof(struct kvm_pic_state));
2726                 raw_spin_unlock(&pic_irqchip(kvm)->lock);
2727                 break;
2728         case KVM_IRQCHIP_PIC_SLAVE:
2729                 raw_spin_lock(&pic_irqchip(kvm)->lock);
2730                 memcpy(&pic_irqchip(kvm)->pics[1],
2731                         &chip->chip.pic,
2732                         sizeof(struct kvm_pic_state));
2733                 raw_spin_unlock(&pic_irqchip(kvm)->lock);
2734                 break;
2735         case KVM_IRQCHIP_IOAPIC:
2736                 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
2737                 break;
2738         default:
2739                 r = -EINVAL;
2740                 break;
2741         }
2742         kvm_pic_update_irq(pic_irqchip(kvm));
2743         return r;
2744 }
2745
2746 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2747 {
2748         int r = 0;
2749
2750         mutex_lock(&kvm->arch.vpit->pit_state.lock);
2751         memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
2752         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2753         return r;
2754 }
2755
2756 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
2757 {
2758         int r = 0;
2759
2760         mutex_lock(&kvm->arch.vpit->pit_state.lock);
2761         memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
2762         kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
2763         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2764         return r;
2765 }
2766
2767 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2768 {
2769         int r = 0;
2770
2771         mutex_lock(&kvm->arch.vpit->pit_state.lock);
2772         memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
2773                 sizeof(ps->channels));
2774         ps->flags = kvm->arch.vpit->pit_state.flags;
2775         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2776         return r;
2777 }
2778
2779 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
2780 {
2781         int r = 0, start = 0;
2782         u32 prev_legacy, cur_legacy;
2783         mutex_lock(&kvm->arch.vpit->pit_state.lock);
2784         prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
2785         cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
2786         if (!prev_legacy && cur_legacy)
2787                 start = 1;
2788         memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
2789                sizeof(kvm->arch.vpit->pit_state.channels));
2790         kvm->arch.vpit->pit_state.flags = ps->flags;
2791         kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
2792         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2793         return r;
2794 }
2795
2796 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
2797                                  struct kvm_reinject_control *control)
2798 {
2799         if (!kvm->arch.vpit)
2800                 return -ENXIO;
2801         mutex_lock(&kvm->arch.vpit->pit_state.lock);
2802         kvm->arch.vpit->pit_state.pit_timer.reinject = control->pit_reinject;
2803         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
2804         return 0;
2805 }
2806
2807 /*
2808  * Get (and clear) the dirty memory log for a memory slot.
2809  */
2810 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
2811                                       struct kvm_dirty_log *log)
2812 {
2813         int r, i;
2814         struct kvm_memory_slot *memslot;
2815         unsigned long n;
2816         unsigned long is_dirty = 0;
2817
2818         mutex_lock(&kvm->slots_lock);
2819
2820         r = -EINVAL;
2821         if (log->slot >= KVM_MEMORY_SLOTS)
2822                 goto out;
2823
2824         memslot = &kvm->memslots->memslots[log->slot];
2825         r = -ENOENT;
2826         if (!memslot->dirty_bitmap)
2827                 goto out;
2828
2829         n = kvm_dirty_bitmap_bytes(memslot);
2830
2831         for (i = 0; !is_dirty && i < n/sizeof(long); i++)
2832                 is_dirty = memslot->dirty_bitmap[i];
2833
2834         /* If nothing is dirty, don't bother messing with page tables. */
2835         if (is_dirty) {
2836                 struct kvm_memslots *slots, *old_slots;
2837                 unsigned long *dirty_bitmap;
2838
2839                 spin_lock(&kvm->mmu_lock);
2840                 kvm_mmu_slot_remove_write_access(kvm, log->slot);
2841                 spin_unlock(&kvm->mmu_lock);
2842
2843                 r = -ENOMEM;
2844                 dirty_bitmap = vmalloc(n);
2845                 if (!dirty_bitmap)
2846                         goto out;
2847                 memset(dirty_bitmap, 0, n);
2848
2849                 r = -ENOMEM;
2850                 slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
2851                 if (!slots) {
2852                         vfree(dirty_bitmap);
2853                         goto out;
2854                 }
2855                 memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
2856                 slots->memslots[log->slot].dirty_bitmap = dirty_bitmap;
2857
2858                 old_slots = kvm->memslots;
2859                 rcu_assign_pointer(kvm->memslots, slots);
2860                 synchronize_srcu_expedited(&kvm->srcu);
2861                 dirty_bitmap = old_slots->memslots[log->slot].dirty_bitmap;
2862                 kfree(old_slots);
2863
2864                 r = -EFAULT;
2865                 if (copy_to_user(log->dirty_bitmap, dirty_bitmap, n)) {
2866                         vfree(dirty_bitmap);
2867                         goto out;
2868                 }
2869                 vfree(dirty_bitmap);
2870         } else {
2871                 r = -EFAULT;
2872                 if (clear_user(log->dirty_bitmap, n))
2873                         goto out;
2874         }
2875
2876         r = 0;
2877 out:
2878         mutex_unlock(&kvm->slots_lock);
2879         return r;
2880 }
2881
2882 long kvm_arch_vm_ioctl(struct file *filp,
2883                        unsigned int ioctl, unsigned long arg)
2884 {
2885         struct kvm *kvm = filp->private_data;
2886         void __user *argp = (void __user *)arg;
2887         int r = -ENOTTY;
2888         /*
2889          * This union makes it completely explicit to gcc-3.x
2890          * that these two variables' stack usage should be
2891          * combined, not added together.
2892          */
2893         union {
2894                 struct kvm_pit_state ps;
2895                 struct kvm_pit_state2 ps2;
2896                 struct kvm_memory_alias alias;
2897                 struct kvm_pit_config pit_config;
2898         } u;
2899
2900         switch (ioctl) {
2901         case KVM_SET_TSS_ADDR:
2902                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
2903                 if (r < 0)
2904                         goto out;
2905                 break;
2906         case KVM_SET_IDENTITY_MAP_ADDR: {
2907                 u64 ident_addr;
2908
2909                 r = -EFAULT;
2910                 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
2911                         goto out;
2912                 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
2913                 if (r < 0)
2914                         goto out;
2915                 break;
2916         }
2917         case KVM_SET_MEMORY_REGION: {
2918                 struct kvm_memory_region kvm_mem;
2919                 struct kvm_userspace_memory_region kvm_userspace_mem;
2920
2921                 r = -EFAULT;
2922                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
2923                         goto out;
2924                 kvm_userspace_mem.slot = kvm_mem.slot;
2925                 kvm_userspace_mem.flags = kvm_mem.flags;
2926                 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
2927                 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
2928                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
2929                 if (r)
2930                         goto out;
2931                 break;
2932         }
2933         case KVM_SET_NR_MMU_PAGES:
2934                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
2935                 if (r)
2936                         goto out;
2937                 break;
2938         case KVM_GET_NR_MMU_PAGES:
2939                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
2940                 break;
2941         case KVM_SET_MEMORY_ALIAS:
2942                 r = -EFAULT;
2943                 if (copy_from_user(&u.alias, argp, sizeof(struct kvm_memory_alias)))
2944                         goto out;
2945                 r = kvm_vm_ioctl_set_memory_alias(kvm, &u.alias);
2946                 if (r)
2947                         goto out;
2948                 break;
2949         case KVM_CREATE_IRQCHIP: {
2950                 struct kvm_pic *vpic;
2951
2952                 mutex_lock(&kvm->lock);
2953                 r = -EEXIST;
2954                 if (kvm->arch.vpic)
2955                         goto create_irqchip_unlock;
2956                 r = -ENOMEM;
2957                 vpic = kvm_create_pic(kvm);
2958                 if (vpic) {
2959                         r = kvm_ioapic_init(kvm);
2960                         if (r) {
2961                                 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
2962                                                           &vpic->dev);
2963                                 kfree(vpic);
2964                                 goto create_irqchip_unlock;
2965                         }
2966                 } else
2967                         goto create_irqchip_unlock;
2968                 smp_wmb();
2969                 kvm->arch.vpic = vpic;
2970                 smp_wmb();
2971                 r = kvm_setup_default_irq_routing(kvm);
2972                 if (r) {
2973                         mutex_lock(&kvm->irq_lock);
2974                         kvm_ioapic_destroy(kvm);
2975                         kvm_destroy_pic(kvm);
2976                         mutex_unlock(&kvm->irq_lock);
2977                 }
2978         create_irqchip_unlock:
2979                 mutex_unlock(&kvm->lock);
2980                 break;
2981         }
2982         case KVM_CREATE_PIT:
2983                 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
2984                 goto create_pit;
2985         case KVM_CREATE_PIT2:
2986                 r = -EFAULT;
2987                 if (copy_from_user(&u.pit_config, argp,
2988                                    sizeof(struct kvm_pit_config)))
2989                         goto out;
2990         create_pit:
2991                 mutex_lock(&kvm->slots_lock);
2992                 r = -EEXIST;
2993                 if (kvm->arch.vpit)
2994                         goto create_pit_unlock;
2995                 r = -ENOMEM;
2996                 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
2997                 if (kvm->arch.vpit)
2998                         r = 0;
2999         create_pit_unlock:
3000                 mutex_unlock(&kvm->slots_lock);
3001                 break;
3002         case KVM_IRQ_LINE_STATUS:
3003         case KVM_IRQ_LINE: {
3004                 struct kvm_irq_level irq_event;
3005
3006                 r = -EFAULT;
3007                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
3008                         goto out;
3009                 r = -ENXIO;
3010                 if (irqchip_in_kernel(kvm)) {
3011                         __s32 status;
3012                         status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3013                                         irq_event.irq, irq_event.level);
3014                         if (ioctl == KVM_IRQ_LINE_STATUS) {
3015                                 r = -EFAULT;
3016                                 irq_event.status = status;
3017                                 if (copy_to_user(argp, &irq_event,
3018                                                         sizeof irq_event))
3019                                         goto out;
3020                         }
3021                         r = 0;
3022                 }
3023                 break;
3024         }
3025         case KVM_GET_IRQCHIP: {
3026                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3027                 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
3028
3029                 r = -ENOMEM;
3030                 if (!chip)
3031                         goto out;
3032                 r = -EFAULT;
3033                 if (copy_from_user(chip, argp, sizeof *chip))
3034                         goto get_irqchip_out;
3035                 r = -ENXIO;
3036                 if (!irqchip_in_kernel(kvm))
3037                         goto get_irqchip_out;
3038                 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3039                 if (r)
3040                         goto get_irqchip_out;
3041                 r = -EFAULT;
3042                 if (copy_to_user(argp, chip, sizeof *chip))
3043                         goto get_irqchip_out;
3044                 r = 0;
3045         get_irqchip_out:
3046                 kfree(chip);
3047                 if (r)
3048                         goto out;
3049                 break;
3050         }
3051         case KVM_SET_IRQCHIP: {
3052                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3053                 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
3054
3055                 r = -ENOMEM;
3056                 if (!chip)
3057                         goto out;
3058                 r = -EFAULT;
3059                 if (copy_from_user(chip, argp, sizeof *chip))
3060                         goto set_irqchip_out;
3061                 r = -ENXIO;
3062                 if (!irqchip_in_kernel(kvm))
3063                         goto set_irqchip_out;
3064                 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3065                 if (r)
3066                         goto set_irqchip_out;
3067                 r = 0;
3068         set_irqchip_out:
3069                 kfree(chip);
3070                 if (r)
3071                         goto out;
3072                 break;
3073         }
3074         case KVM_GET_PIT: {
3075                 r = -EFAULT;
3076                 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
3077                         goto out;
3078                 r = -ENXIO;
3079                 if (!kvm->arch.vpit)
3080                         goto out;
3081                 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
3082                 if (r)
3083                         goto out;
3084                 r = -EFAULT;
3085                 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
3086                         goto out;
3087                 r = 0;
3088                 break;
3089         }
3090         case KVM_SET_PIT: {
3091                 r = -EFAULT;
3092                 if (copy_from_user(&u.ps, argp, sizeof u.ps))
3093                         goto out;
3094                 r = -ENXIO;
3095                 if (!kvm->arch.vpit)
3096                         goto out;
3097                 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
3098                 if (r)
3099                         goto out;
3100                 r = 0;
3101                 break;
3102         }
3103         case KVM_GET_PIT2: {
3104                 r = -ENXIO;
3105                 if (!kvm->arch.vpit)
3106                         goto out;
3107                 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
3108                 if (r)
3109                         goto out;
3110                 r = -EFAULT;
3111                 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
3112                         goto out;
3113                 r = 0;
3114                 break;
3115         }
3116         case KVM_SET_PIT2: {
3117                 r = -EFAULT;
3118                 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
3119                         goto out;
3120                 r = -ENXIO;
3121                 if (!kvm->arch.vpit)
3122                         goto out;
3123                 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
3124                 if (r)
3125                         goto out;
3126                 r = 0;
3127                 break;
3128         }
3129         case KVM_REINJECT_CONTROL: {
3130                 struct kvm_reinject_control control;
3131                 r =  -EFAULT;
3132                 if (copy_from_user(&control, argp, sizeof(control)))
3133                         goto out;
3134                 r = kvm_vm_ioctl_reinject(kvm, &control);
3135                 if (r)
3136                         goto out;
3137                 r = 0;
3138                 break;
3139         }
3140         case KVM_XEN_HVM_CONFIG: {
3141                 r = -EFAULT;
3142                 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
3143                                    sizeof(struct kvm_xen_hvm_config)))
3144                         goto out;
3145                 r = -EINVAL;
3146                 if (kvm->arch.xen_hvm_config.flags)
3147                         goto out;
3148                 r = 0;
3149                 break;
3150         }
3151         case KVM_SET_CLOCK: {
3152                 struct timespec now;
3153                 struct kvm_clock_data user_ns;
3154                 u64 now_ns;
3155                 s64 delta;
3156
3157                 r = -EFAULT;
3158                 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
3159                         goto out;
3160
3161                 r = -EINVAL;
3162                 if (user_ns.flags)
3163                         goto out;
3164
3165                 r = 0;
3166                 ktime_get_ts(&now);
3167                 now_ns = timespec_to_ns(&now);
3168                 delta = user_ns.clock - now_ns;
3169                 kvm->arch.kvmclock_offset = delta;
3170                 break;
3171         }
3172         case KVM_GET_CLOCK: {
3173                 struct timespec now;
3174                 struct kvm_clock_data user_ns;
3175                 u64 now_ns;
3176
3177                 ktime_get_ts(&now);
3178                 now_ns = timespec_to_ns(&now);
3179                 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
3180                 user_ns.flags = 0;
3181
3182                 r = -EFAULT;
3183                 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
3184                         goto out;
3185                 r = 0;
3186                 break;
3187         }
3188
3189         default:
3190                 ;
3191         }
3192 out:
3193         return r;
3194 }
3195
3196 static void kvm_init_msr_list(void)
3197 {
3198         u32 dummy[2];
3199         unsigned i, j;
3200
3201         /* skip the first msrs in the list. KVM-specific */
3202         for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
3203                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
3204                         continue;
3205                 if (j < i)
3206                         msrs_to_save[j] = msrs_to_save[i];
3207                 j++;
3208         }
3209         num_msrs_to_save = j;
3210 }
3211
3212 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
3213                            const void *v)
3214 {
3215         if (vcpu->arch.apic &&
3216             !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, len, v))
3217                 return 0;
3218
3219         return kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, len, v);
3220 }
3221
3222 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
3223 {
3224         if (vcpu->arch.apic &&
3225             !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, len, v))
3226                 return 0;
3227
3228         return kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, len, v);
3229 }
3230
3231 static void kvm_set_segment(struct kvm_vcpu *vcpu,
3232                         struct kvm_segment *var, int seg)
3233 {
3234         kvm_x86_ops->set_segment(vcpu, var, seg);
3235 }
3236
3237 void kvm_get_segment(struct kvm_vcpu *vcpu,
3238                      struct kvm_segment *var, int seg)
3239 {
3240         kvm_x86_ops->get_segment(vcpu, var, seg);
3241 }
3242
3243 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva, u32 *error)
3244 {
3245         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3246         return vcpu->arch.mmu.gva_to_gpa(vcpu, gva, access, error);
3247 }
3248
3249  gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva, u32 *error)
3250 {
3251         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3252         access |= PFERR_FETCH_MASK;
3253         return vcpu->arch.mmu.gva_to_gpa(vcpu, gva, access, error);
3254 }
3255
3256 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva, u32 *error)
3257 {
3258         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3259         access |= PFERR_WRITE_MASK;
3260         return vcpu->arch.mmu.gva_to_gpa(vcpu, gva, access, error);
3261 }
3262
3263 /* uses this to access any guest's mapped memory without checking CPL */
3264 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva, u32 *error)
3265 {
3266         return vcpu->arch.mmu.gva_to_gpa(vcpu, gva, 0, error);
3267 }
3268
3269 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
3270                                       struct kvm_vcpu *vcpu, u32 access,
3271                                       u32 *error)
3272 {
3273         void *data = val;
3274         int r = X86EMUL_CONTINUE;
3275
3276         while (bytes) {
3277                 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr, access, error);
3278                 unsigned offset = addr & (PAGE_SIZE-1);
3279                 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
3280                 int ret;
3281
3282                 if (gpa == UNMAPPED_GVA) {
3283                         r = X86EMUL_PROPAGATE_FAULT;
3284                         goto out;
3285                 }
3286                 ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
3287                 if (ret < 0) {
3288                         r = X86EMUL_IO_NEEDED;
3289                         goto out;
3290                 }
3291
3292                 bytes -= toread;
3293                 data += toread;
3294                 addr += toread;
3295         }
3296 out:
3297         return r;
3298 }
3299
3300 /* used for instruction fetching */
3301 static int kvm_fetch_guest_virt(gva_t addr, void *val, unsigned int bytes,
3302                                 struct kvm_vcpu *vcpu, u32 *error)
3303 {
3304         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3305         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
3306                                           access | PFERR_FETCH_MASK, error);
3307 }
3308
3309 static int kvm_read_guest_virt(gva_t addr, void *val, unsigned int bytes,
3310                                struct kvm_vcpu *vcpu, u32 *error)
3311 {
3312         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3313         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
3314                                           error);
3315 }
3316
3317 static int kvm_read_guest_virt_system(gva_t addr, void *val, unsigned int bytes,
3318                                struct kvm_vcpu *vcpu, u32 *error)
3319 {
3320         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, error);
3321 }
3322
3323 static int kvm_write_guest_virt_system(gva_t addr, void *val,
3324                                        unsigned int bytes,
3325                                        struct kvm_vcpu *vcpu,
3326                                        u32 *error)
3327 {
3328         void *data = val;
3329         int r = X86EMUL_CONTINUE;
3330
3331         while (bytes) {
3332                 gpa_t gpa =  vcpu->arch.mmu.gva_to_gpa(vcpu, addr,
3333                                                        PFERR_WRITE_MASK, error);
3334                 unsigned offset = addr & (PAGE_SIZE-1);
3335                 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
3336                 int ret;
3337
3338                 if (gpa == UNMAPPED_GVA) {
3339                         r = X86EMUL_PROPAGATE_FAULT;
3340                         goto out;
3341                 }
3342                 ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
3343                 if (ret < 0) {
3344                         r = X86EMUL_IO_NEEDED;
3345                         goto out;
3346                 }
3347
3348                 bytes -= towrite;
3349                 data += towrite;
3350                 addr += towrite;
3351         }
3352 out:
3353         return r;
3354 }
3355
3356 static int emulator_read_emulated(unsigned long addr,
3357                                   void *val,
3358                                   unsigned int bytes,
3359                                   unsigned int *error_code,
3360                                   struct kvm_vcpu *vcpu)
3361 {
3362         gpa_t                 gpa;
3363
3364         if (vcpu->mmio_read_completed) {
3365                 memcpy(val, vcpu->mmio_data, bytes);
3366                 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
3367                                vcpu->mmio_phys_addr, *(u64 *)val);
3368                 vcpu->mmio_read_completed = 0;
3369                 return X86EMUL_CONTINUE;
3370         }
3371
3372         gpa = kvm_mmu_gva_to_gpa_read(vcpu, addr, error_code);
3373
3374         if (gpa == UNMAPPED_GVA)
3375                 return X86EMUL_PROPAGATE_FAULT;
3376
3377         /* For APIC access vmexit */
3378         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3379                 goto mmio;
3380
3381         if (kvm_read_guest_virt(addr, val, bytes, vcpu, NULL)
3382                                 == X86EMUL_CONTINUE)
3383                 return X86EMUL_CONTINUE;
3384
3385 mmio:
3386         /*
3387          * Is this MMIO handled locally?
3388          */
3389         if (!vcpu_mmio_read(vcpu, gpa, bytes, val)) {
3390                 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes, gpa, *(u64 *)val);
3391                 return X86EMUL_CONTINUE;
3392         }
3393
3394         trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
3395
3396         vcpu->mmio_needed = 1;
3397         vcpu->run->exit_reason = KVM_EXIT_MMIO;
3398         vcpu->run->mmio.phys_addr = vcpu->mmio_phys_addr = gpa;
3399         vcpu->run->mmio.len = vcpu->mmio_size = bytes;
3400         vcpu->run->mmio.is_write = vcpu->mmio_is_write = 0;
3401
3402         return X86EMUL_IO_NEEDED;
3403 }
3404
3405 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
3406                           const void *val, int bytes)
3407 {
3408         int ret;
3409
3410         ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
3411         if (ret < 0)
3412                 return 0;
3413         kvm_mmu_pte_write(vcpu, gpa, val, bytes, 1);
3414         return 1;
3415 }
3416
3417 static int emulator_write_emulated_onepage(unsigned long addr,
3418                                            const void *val,
3419                                            unsigned int bytes,
3420                                            unsigned int *error_code,
3421                                            struct kvm_vcpu *vcpu)
3422 {
3423         gpa_t                 gpa;
3424
3425         gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, error_code);
3426
3427         if (gpa == UNMAPPED_GVA)
3428                 return X86EMUL_PROPAGATE_FAULT;
3429
3430         /* For APIC access vmexit */
3431         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3432                 goto mmio;
3433
3434         if (emulator_write_phys(vcpu, gpa, val, bytes))
3435                 return X86EMUL_CONTINUE;
3436
3437 mmio:
3438         trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
3439         /*
3440          * Is this MMIO handled locally?
3441          */
3442         if (!vcpu_mmio_write(vcpu, gpa, bytes, val))
3443                 return X86EMUL_CONTINUE;
3444
3445         vcpu->mmio_needed = 1;
3446         vcpu->run->exit_reason = KVM_EXIT_MMIO;
3447         vcpu->run->mmio.phys_addr = vcpu->mmio_phys_addr = gpa;
3448         vcpu->run->mmio.len = vcpu->mmio_size = bytes;
3449         vcpu->run->mmio.is_write = vcpu->mmio_is_write = 1;
3450         memcpy(vcpu->run->mmio.data, val, bytes);
3451
3452         return X86EMUL_CONTINUE;
3453 }
3454
3455 int emulator_write_emulated(unsigned long addr,
3456                             const void *val,
3457                             unsigned int bytes,
3458                             unsigned int *error_code,
3459                             struct kvm_vcpu *vcpu)
3460 {
3461         /* Crossing a page boundary? */
3462         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
3463                 int rc, now;
3464
3465                 now = -addr & ~PAGE_MASK;
3466                 rc = emulator_write_emulated_onepage(addr, val, now, error_code,
3467                                                      vcpu);
3468                 if (rc != X86EMUL_CONTINUE)
3469                         return rc;
3470                 addr += now;
3471                 val += now;
3472                 bytes -= now;
3473         }
3474         return emulator_write_emulated_onepage(addr, val, bytes, error_code,
3475                                                vcpu);
3476 }
3477
3478 #define CMPXCHG_TYPE(t, ptr, old, new) \
3479         (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
3480
3481 #ifdef CONFIG_X86_64
3482 #  define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
3483 #else
3484 #  define CMPXCHG64(ptr, old, new) \
3485         (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
3486 #endif
3487
3488 static int emulator_cmpxchg_emulated(unsigned long addr,
3489                                      const void *old,
3490                                      const void *new,
3491                                      unsigned int bytes,
3492                                      unsigned int *error_code,
3493                                      struct kvm_vcpu *vcpu)
3494 {
3495         gpa_t gpa;
3496         struct page *page;
3497         char *kaddr;
3498         bool exchanged;
3499
3500         /* guests cmpxchg8b have to be emulated atomically */
3501         if (bytes > 8 || (bytes & (bytes - 1)))
3502                 goto emul_write;
3503
3504         gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
3505
3506         if (gpa == UNMAPPED_GVA ||
3507             (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
3508                 goto emul_write;
3509
3510         if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
3511                 goto emul_write;
3512
3513         page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
3514
3515         kaddr = kmap_atomic(page, KM_USER0);
3516         kaddr += offset_in_page(gpa);
3517         switch (bytes) {
3518         case 1:
3519                 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
3520                 break;
3521         case 2:
3522                 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
3523                 break;
3524         case 4:
3525                 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
3526                 break;
3527         case 8:
3528                 exchanged = CMPXCHG64(kaddr, old, new);
3529                 break;
3530         default:
3531                 BUG();
3532         }
3533         kunmap_atomic(kaddr, KM_USER0);
3534         kvm_release_page_dirty(page);
3535
3536         if (!exchanged)
3537                 return X86EMUL_CMPXCHG_FAILED;
3538
3539         kvm_mmu_pte_write(vcpu, gpa, new, bytes, 1);
3540
3541         return X86EMUL_CONTINUE;
3542
3543 emul_write:
3544         printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
3545
3546         return emulator_write_emulated(addr, new, bytes, error_code, vcpu);
3547 }
3548
3549 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
3550 {
3551         /* TODO: String I/O for in kernel device */
3552         int r;
3553
3554         if (vcpu->arch.pio.in)
3555                 r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
3556                                     vcpu->arch.pio.size, pd);
3557         else
3558                 r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
3559                                      vcpu->arch.pio.port, vcpu->arch.pio.size,
3560                                      pd);
3561         return r;
3562 }
3563
3564
3565 static int emulator_pio_in_emulated(int size, unsigned short port, void *val,
3566                              unsigned int count, struct kvm_vcpu *vcpu)
3567 {
3568         if (vcpu->arch.pio.count)
3569                 goto data_avail;
3570
3571         trace_kvm_pio(1, port, size, 1);
3572
3573         vcpu->arch.pio.port = port;
3574         vcpu->arch.pio.in = 1;
3575         vcpu->arch.pio.count  = count;
3576         vcpu->arch.pio.size = size;
3577
3578         if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
3579         data_avail:
3580                 memcpy(val, vcpu->arch.pio_data, size * count);
3581                 vcpu->arch.pio.count = 0;
3582                 return 1;
3583         }
3584
3585         vcpu->run->exit_reason = KVM_EXIT_IO;
3586         vcpu->run->io.direction = KVM_EXIT_IO_IN;
3587         vcpu->run->io.size = size;
3588         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
3589         vcpu->run->io.count = count;
3590         vcpu->run->io.port = port;
3591
3592         return 0;
3593 }
3594
3595 static int emulator_pio_out_emulated(int size, unsigned short port,
3596                               const void *val, unsigned int count,
3597                               struct kvm_vcpu *vcpu)
3598 {
3599         trace_kvm_pio(0, port, size, 1);
3600
3601         vcpu->arch.pio.port = port;
3602         vcpu->arch.pio.in = 0;
3603         vcpu->arch.pio.count = count;
3604         vcpu->arch.pio.size = size;
3605
3606         memcpy(vcpu->arch.pio_data, val, size * count);
3607
3608         if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
3609                 vcpu->arch.pio.count = 0;
3610                 return 1;
3611         }
3612
3613         vcpu->run->exit_reason = KVM_EXIT_IO;
3614         vcpu->run->io.direction = KVM_EXIT_IO_OUT;
3615         vcpu->run->io.size = size;
3616         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
3617         vcpu->run->io.count = count;
3618         vcpu->run->io.port = port;
3619
3620         return 0;
3621 }
3622
3623 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
3624 {
3625         return kvm_x86_ops->get_segment_base(vcpu, seg);
3626 }
3627
3628 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
3629 {
3630         kvm_mmu_invlpg(vcpu, address);
3631         return X86EMUL_CONTINUE;
3632 }
3633
3634 int emulate_clts(struct kvm_vcpu *vcpu)
3635 {
3636         kvm_x86_ops->set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
3637         kvm_x86_ops->fpu_activate(vcpu);
3638         return X86EMUL_CONTINUE;
3639 }
3640
3641 int emulator_get_dr(int dr, unsigned long *dest, struct kvm_vcpu *vcpu)
3642 {
3643         return _kvm_get_dr(vcpu, dr, dest);
3644 }
3645
3646 int emulator_set_dr(int dr, unsigned long value, struct kvm_vcpu *vcpu)
3647 {
3648
3649         return __kvm_set_dr(vcpu, dr, value);
3650 }
3651
3652 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
3653 {
3654         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
3655 }
3656
3657 static unsigned long emulator_get_cr(int cr, struct kvm_vcpu *vcpu)
3658 {
3659         unsigned long value;
3660
3661         switch (cr) {
3662         case 0:
3663                 value = kvm_read_cr0(vcpu);
3664                 break;
3665         case 2:
3666                 value = vcpu->arch.cr2;
3667                 break;
3668         case 3:
3669                 value = vcpu->arch.cr3;
3670                 break;
3671         case 4:
3672                 value = kvm_read_cr4(vcpu);
3673                 break;
3674         case 8:
3675                 value = kvm_get_cr8(vcpu);
3676                 break;
3677         default:
3678                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
3679                 return 0;
3680         }
3681
3682         return value;
3683 }
3684
3685 static int emulator_set_cr(int cr, unsigned long val, struct kvm_vcpu *vcpu)
3686 {
3687         int res = 0;
3688
3689         switch (cr) {
3690         case 0:
3691                 res = __kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
3692                 break;
3693         case 2:
3694                 vcpu->arch.cr2 = val;
3695                 break;
3696         case 3:
3697                 res = __kvm_set_cr3(vcpu, val);
3698                 break;
3699         case 4:
3700                 res = __kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
3701                 break;
3702         case 8:
3703                 res = __kvm_set_cr8(vcpu, val & 0xfUL);
3704                 break;
3705         default:
3706                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
3707                 res = -1;
3708         }
3709
3710         return res;
3711 }
3712
3713 static int emulator_get_cpl(struct kvm_vcpu *vcpu)
3714 {
3715         return kvm_x86_ops->get_cpl(vcpu);
3716 }
3717
3718 static void emulator_get_gdt(struct desc_ptr *dt, struct kvm_vcpu *vcpu)
3719 {
3720         kvm_x86_ops->get_gdt(vcpu, dt);
3721 }
3722
3723 static unsigned long emulator_get_cached_segment_base(int seg,
3724                                                       struct kvm_vcpu *vcpu)
3725 {
3726         return get_segment_base(vcpu, seg);
3727 }
3728
3729 static bool emulator_get_cached_descriptor(struct desc_struct *desc, int seg,
3730                                            struct kvm_vcpu *vcpu)
3731 {
3732         struct kvm_segment var;
3733
3734         kvm_get_segment(vcpu, &var, seg);
3735
3736         if (var.unusable)
3737                 return false;
3738
3739         if (var.g)
3740                 var.limit >>= 12;
3741         set_desc_limit(desc, var.limit);
3742         set_desc_base(desc, (unsigned long)var.base);
3743         desc->type = var.type;
3744         desc->s = var.s;
3745         desc->dpl = var.dpl;
3746         desc->p = var.present;
3747         desc->avl = var.avl;
3748         desc->l = var.l;
3749         desc->d = var.db;
3750         desc->g = var.g;
3751
3752         return true;
3753 }
3754
3755 static void emulator_set_cached_descriptor(struct desc_struct *desc, int seg,
3756                                            struct kvm_vcpu *vcpu)
3757 {
3758         struct kvm_segment var;
3759
3760         /* needed to preserve selector */
3761         kvm_get_segment(vcpu, &var, seg);
3762
3763         var.base = get_desc_base(desc);
3764         var.limit = get_desc_limit(desc);
3765         if (desc->g)
3766                 var.limit = (var.limit << 12) | 0xfff;
3767         var.type = desc->type;
3768         var.present = desc->p;
3769         var.dpl = desc->dpl;
3770         var.db = desc->d;
3771         var.s = desc->s;
3772         var.l = desc->l;
3773         var.g = desc->g;
3774         var.avl = desc->avl;
3775         var.present = desc->p;
3776         var.unusable = !var.present;
3777         var.padding = 0;
3778
3779         kvm_set_segment(vcpu, &var, seg);
3780         return;
3781 }
3782
3783 static u16 emulator_get_segment_selector(int seg, struct kvm_vcpu *vcpu)
3784 {
3785         struct kvm_segment kvm_seg;
3786
3787         kvm_get_segment(vcpu, &kvm_seg, seg);
3788         return kvm_seg.selector;
3789 }
3790
3791 static void emulator_set_segment_selector(u16 sel, int seg,
3792                                           struct kvm_vcpu *vcpu)
3793 {
3794         struct kvm_segment kvm_seg;
3795
3796         kvm_get_segment(vcpu, &kvm_seg, seg);
3797         kvm_seg.selector = sel;
3798         kvm_set_segment(vcpu, &kvm_seg, seg);
3799 }
3800
3801 static struct x86_emulate_ops emulate_ops = {
3802         .read_std            = kvm_read_guest_virt_system,
3803         .write_std           = kvm_write_guest_virt_system,
3804         .fetch               = kvm_fetch_guest_virt,
3805         .read_emulated       = emulator_read_emulated,
3806         .write_emulated      = emulator_write_emulated,
3807         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
3808         .pio_in_emulated     = emulator_pio_in_emulated,
3809         .pio_out_emulated    = emulator_pio_out_emulated,
3810         .get_cached_descriptor = emulator_get_cached_descriptor,
3811         .set_cached_descriptor = emulator_set_cached_descriptor,
3812         .get_segment_selector = emulator_get_segment_selector,
3813         .set_segment_selector = emulator_set_segment_selector,
3814         .get_cached_segment_base = emulator_get_cached_segment_base,
3815         .get_gdt             = emulator_get_gdt,
3816         .get_cr              = emulator_get_cr,
3817         .set_cr              = emulator_set_cr,
3818         .cpl                 = emulator_get_cpl,
3819         .get_dr              = emulator_get_dr,
3820         .set_dr              = emulator_set_dr,
3821         .set_msr             = kvm_set_msr,
3822         .get_msr             = kvm_get_msr,
3823 };
3824
3825 static void cache_all_regs(struct kvm_vcpu *vcpu)
3826 {
3827         kvm_register_read(vcpu, VCPU_REGS_RAX);
3828         kvm_register_read(vcpu, VCPU_REGS_RSP);
3829         kvm_register_read(vcpu, VCPU_REGS_RIP);
3830         vcpu->arch.regs_dirty = ~0;
3831 }
3832
3833 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
3834 {
3835         u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu, mask);
3836         /*
3837          * an sti; sti; sequence only disable interrupts for the first
3838          * instruction. So, if the last instruction, be it emulated or
3839          * not, left the system with the INT_STI flag enabled, it
3840          * means that the last instruction is an sti. We should not
3841          * leave the flag on in this case. The same goes for mov ss
3842          */
3843         if (!(int_shadow & mask))
3844                 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
3845 }
3846
3847 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
3848 {
3849         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
3850         if (ctxt->exception == PF_VECTOR)
3851                 kvm_inject_page_fault(vcpu, ctxt->cr2, ctxt->error_code);
3852         else if (ctxt->error_code_valid)
3853                 kvm_queue_exception_e(vcpu, ctxt->exception, ctxt->error_code);
3854         else
3855                 kvm_queue_exception(vcpu, ctxt->exception);
3856 }
3857
3858 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
3859 {
3860         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
3861
3862         ++vcpu->stat.insn_emulation_fail;
3863         trace_kvm_emulate_insn_failed(vcpu);
3864         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3865         vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
3866         vcpu->run->internal.ndata = 0;
3867         kvm_queue_exception(vcpu, UD_VECTOR);
3868         return EMULATE_FAIL;
3869 }
3870
3871 int emulate_instruction(struct kvm_vcpu *vcpu,
3872                         unsigned long cr2,
3873                         u16 error_code,
3874                         int emulation_type)
3875 {
3876         int r;
3877         struct decode_cache *c = &vcpu->arch.emulate_ctxt.decode;
3878
3879         kvm_clear_exception_queue(vcpu);
3880         vcpu->arch.mmio_fault_cr2 = cr2;
3881         /*
3882          * TODO: fix emulate.c to use guest_read/write_register
3883          * instead of direct ->regs accesses, can save hundred cycles
3884          * on Intel for instructions that don't read/change RSP, for
3885          * for example.
3886          */
3887         cache_all_regs(vcpu);
3888
3889         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
3890                 int cs_db, cs_l;
3891                 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
3892
3893                 vcpu->arch.emulate_ctxt.vcpu = vcpu;
3894                 vcpu->arch.emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
3895                 vcpu->arch.emulate_ctxt.eip = kvm_rip_read(vcpu);
3896                 vcpu->arch.emulate_ctxt.mode =
3897                         (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
3898                         (vcpu->arch.emulate_ctxt.eflags & X86_EFLAGS_VM)
3899                         ? X86EMUL_MODE_VM86 : cs_l
3900                         ? X86EMUL_MODE_PROT64 : cs_db
3901                         ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
3902                 memset(c, 0, sizeof(struct decode_cache));
3903                 memcpy(c->regs, vcpu->arch.regs, sizeof c->regs);
3904                 vcpu->arch.emulate_ctxt.interruptibility = 0;
3905                 vcpu->arch.emulate_ctxt.exception = -1;
3906
3907                 r = x86_decode_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
3908                 trace_kvm_emulate_insn_start(vcpu);
3909
3910                 /* Only allow emulation of specific instructions on #UD
3911                  * (namely VMMCALL, sysenter, sysexit, syscall)*/
3912                 if (emulation_type & EMULTYPE_TRAP_UD) {
3913                         if (!c->twobyte)
3914                                 return EMULATE_FAIL;
3915                         switch (c->b) {
3916                         case 0x01: /* VMMCALL */
3917                                 if (c->modrm_mod != 3 || c->modrm_rm != 1)
3918                                         return EMULATE_FAIL;
3919                                 break;
3920                         case 0x34: /* sysenter */
3921                         case 0x35: /* sysexit */
3922                                 if (c->modrm_mod != 0 || c->modrm_rm != 0)
3923                                         return EMULATE_FAIL;
3924                                 break;
3925                         case 0x05: /* syscall */
3926                                 if (c->modrm_mod != 0 || c->modrm_rm != 0)
3927                                         return EMULATE_FAIL;
3928                                 break;
3929                         default:
3930                                 return EMULATE_FAIL;
3931                         }
3932
3933                         if (!(c->modrm_reg == 0 || c->modrm_reg == 3))
3934                                 return EMULATE_FAIL;
3935                 }
3936
3937                 ++vcpu->stat.insn_emulation;
3938                 if (r)  {
3939                         if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
3940                                 return EMULATE_DONE;
3941                         if (emulation_type & EMULTYPE_SKIP)
3942                                 return EMULATE_FAIL;
3943                         return handle_emulation_failure(vcpu);
3944                 }
3945         }
3946
3947         if (emulation_type & EMULTYPE_SKIP) {
3948                 kvm_rip_write(vcpu, vcpu->arch.emulate_ctxt.decode.eip);
3949                 return EMULATE_DONE;
3950         }
3951
3952         /* this is needed for vmware backdor interface to work since it
3953            changes registers values  during IO operation */
3954         memcpy(c->regs, vcpu->arch.regs, sizeof c->regs);
3955
3956 restart:
3957         r = x86_emulate_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
3958
3959         if (r) { /* emulation failed */
3960                 /*
3961                  * if emulation was due to access to shadowed page table
3962                  * and it failed try to unshadow page and re-entetr the
3963                  * guest to let CPU execute the instruction.
3964                  */
3965                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
3966                         return EMULATE_DONE;
3967
3968                 return handle_emulation_failure(vcpu);
3969         }
3970
3971         toggle_interruptibility(vcpu, vcpu->arch.emulate_ctxt.interruptibility);
3972         kvm_x86_ops->set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
3973         memcpy(vcpu->arch.regs, c->regs, sizeof c->regs);
3974         kvm_rip_write(vcpu, vcpu->arch.emulate_ctxt.eip);
3975
3976         if (vcpu->arch.emulate_ctxt.exception >= 0) {
3977                 inject_emulated_exception(vcpu);
3978                 return EMULATE_DONE;
3979         }
3980
3981         if (vcpu->arch.pio.count) {
3982                 if (!vcpu->arch.pio.in)
3983                         vcpu->arch.pio.count = 0;
3984                 return EMULATE_DO_MMIO;
3985         }
3986
3987         if (vcpu->mmio_needed) {
3988                 if (vcpu->mmio_is_write)
3989                         vcpu->mmio_needed = 0;
3990                 return EMULATE_DO_MMIO;
3991         }
3992
3993         if (vcpu->arch.emulate_ctxt.restart)
3994                 goto restart;
3995
3996         return EMULATE_DONE;
3997 }
3998 EXPORT_SYMBOL_GPL(emulate_instruction);
3999
4000 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
4001 {
4002         unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
4003         int ret = emulator_pio_out_emulated(size, port, &val, 1, vcpu);
4004         /* do not return to emulator after return from userspace */
4005         vcpu->arch.pio.count = 0;
4006         return ret;
4007 }
4008 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
4009
4010 static void bounce_off(void *info)
4011 {
4012         /* nothing */
4013 }
4014
4015 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
4016                                      void *data)
4017 {
4018         struct cpufreq_freqs *freq = data;
4019         struct kvm *kvm;
4020         struct kvm_vcpu *vcpu;
4021         int i, send_ipi = 0;
4022
4023         if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
4024                 return 0;
4025         if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
4026                 return 0;
4027         per_cpu(cpu_tsc_khz, freq->cpu) = freq->new;
4028
4029         spin_lock(&kvm_lock);
4030         list_for_each_entry(kvm, &vm_list, vm_list) {
4031                 kvm_for_each_vcpu(i, vcpu, kvm) {
4032                         if (vcpu->cpu != freq->cpu)
4033                                 continue;
4034                         if (!kvm_request_guest_time_update(vcpu))
4035                                 continue;
4036                         if (vcpu->cpu != smp_processor_id())
4037                                 send_ipi++;
4038                 }
4039         }
4040         spin_unlock(&kvm_lock);
4041
4042         if (freq->old < freq->new && send_ipi) {
4043                 /*
4044                  * We upscale the frequency.  Must make the guest
4045                  * doesn't see old kvmclock values while running with
4046                  * the new frequency, otherwise we risk the guest sees
4047                  * time go backwards.
4048                  *
4049                  * In case we update the frequency for another cpu
4050                  * (which might be in guest context) send an interrupt
4051                  * to kick the cpu out of guest context.  Next time
4052                  * guest context is entered kvmclock will be updated,
4053                  * so the guest will not see stale values.
4054                  */
4055                 smp_call_function_single(freq->cpu, bounce_off, NULL, 1);
4056         }
4057         return 0;
4058 }
4059
4060 static struct notifier_block kvmclock_cpufreq_notifier_block = {
4061         .notifier_call  = kvmclock_cpufreq_notifier
4062 };
4063
4064 static void kvm_timer_init(void)
4065 {
4066         int cpu;
4067
4068         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
4069                 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
4070                                           CPUFREQ_TRANSITION_NOTIFIER);
4071                 for_each_online_cpu(cpu) {
4072                         unsigned long khz = cpufreq_get(cpu);
4073                         if (!khz)
4074                                 khz = tsc_khz;
4075                         per_cpu(cpu_tsc_khz, cpu) = khz;
4076                 }
4077         } else {
4078                 for_each_possible_cpu(cpu)
4079                         per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
4080         }
4081 }
4082
4083 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
4084
4085 static int kvm_is_in_guest(void)
4086 {
4087         return percpu_read(current_vcpu) != NULL;
4088 }
4089
4090 static int kvm_is_user_mode(void)
4091 {
4092         int user_mode = 3;
4093
4094         if (percpu_read(current_vcpu))
4095                 user_mode = kvm_x86_ops->get_cpl(percpu_read(current_vcpu));
4096
4097         return user_mode != 0;
4098 }
4099
4100 static unsigned long kvm_get_guest_ip(void)
4101 {
4102         unsigned long ip = 0;
4103
4104         if (percpu_read(current_vcpu))
4105                 ip = kvm_rip_read(percpu_read(current_vcpu));
4106
4107         return ip;
4108 }
4109
4110 static struct perf_guest_info_callbacks kvm_guest_cbs = {
4111         .is_in_guest            = kvm_is_in_guest,
4112         .is_user_mode           = kvm_is_user_mode,
4113         .get_guest_ip           = kvm_get_guest_ip,
4114 };
4115
4116 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
4117 {
4118         percpu_write(current_vcpu, vcpu);
4119 }
4120 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
4121
4122 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
4123 {
4124         percpu_write(current_vcpu, NULL);
4125 }
4126 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
4127
4128 int kvm_arch_init(void *opaque)
4129 {
4130         int r;
4131         struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
4132
4133         if (kvm_x86_ops) {
4134                 printk(KERN_ERR "kvm: already loaded the other module\n");
4135                 r = -EEXIST;
4136                 goto out;
4137         }
4138
4139         if (!ops->cpu_has_kvm_support()) {
4140                 printk(KERN_ERR "kvm: no hardware support\n");
4141                 r = -EOPNOTSUPP;
4142                 goto out;
4143         }
4144         if (ops->disabled_by_bios()) {
4145                 printk(KERN_ERR "kvm: disabled by bios\n");
4146                 r = -EOPNOTSUPP;
4147                 goto out;
4148         }
4149
4150         r = kvm_mmu_module_init();
4151         if (r)
4152                 goto out;
4153
4154         kvm_init_msr_list();
4155
4156         kvm_x86_ops = ops;
4157         kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
4158         kvm_mmu_set_base_ptes(PT_PRESENT_MASK);
4159         kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
4160                         PT_DIRTY_MASK, PT64_NX_MASK, 0);
4161
4162         kvm_timer_init();
4163
4164         perf_register_guest_info_callbacks(&kvm_guest_cbs);
4165
4166         return 0;
4167
4168 out:
4169         return r;
4170 }
4171
4172 void kvm_arch_exit(void)
4173 {
4174         perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
4175
4176         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
4177                 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
4178                                             CPUFREQ_TRANSITION_NOTIFIER);
4179         kvm_x86_ops = NULL;
4180         kvm_mmu_module_exit();
4181 }
4182
4183 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
4184 {
4185         ++vcpu->stat.halt_exits;
4186         if (irqchip_in_kernel(vcpu->kvm)) {
4187                 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
4188                 return 1;
4189         } else {
4190                 vcpu->run->exit_reason = KVM_EXIT_HLT;
4191                 return 0;
4192         }
4193 }
4194 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
4195
4196 static inline gpa_t hc_gpa(struct kvm_vcpu *vcpu, unsigned long a0,
4197                            unsigned long a1)
4198 {
4199         if (is_long_mode(vcpu))
4200                 return a0;
4201         else
4202                 return a0 | ((gpa_t)a1 << 32);
4203 }
4204
4205 int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
4206 {
4207         u64 param, ingpa, outgpa, ret;
4208         uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
4209         bool fast, longmode;
4210         int cs_db, cs_l;
4211
4212         /*
4213          * hypercall generates UD from non zero cpl and real mode
4214          * per HYPER-V spec
4215          */
4216         if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
4217                 kvm_queue_exception(vcpu, UD_VECTOR);
4218                 return 0;
4219         }
4220
4221         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4222         longmode = is_long_mode(vcpu) && cs_l == 1;
4223
4224         if (!longmode) {
4225                 param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
4226                         (kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
4227                 ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
4228                         (kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
4229                 outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
4230                         (kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
4231         }
4232 #ifdef CONFIG_X86_64
4233         else {
4234                 param = kvm_register_read(vcpu, VCPU_REGS_RCX);
4235                 ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
4236                 outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
4237         }
4238 #endif
4239
4240         code = param & 0xffff;
4241         fast = (param >> 16) & 0x1;
4242         rep_cnt = (param >> 32) & 0xfff;
4243         rep_idx = (param >> 48) & 0xfff;
4244
4245         trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
4246
4247         switch (code) {
4248         case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
4249                 kvm_vcpu_on_spin(vcpu);
4250                 break;
4251         default:
4252                 res = HV_STATUS_INVALID_HYPERCALL_CODE;
4253                 break;
4254         }
4255
4256         ret = res | (((u64)rep_done & 0xfff) << 32);
4257         if (longmode) {
4258                 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
4259         } else {
4260                 kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
4261                 kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
4262         }
4263
4264         return 1;
4265 }
4266
4267 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
4268 {
4269         unsigned long nr, a0, a1, a2, a3, ret;
4270         int r = 1;
4271
4272         if (kvm_hv_hypercall_enabled(vcpu->kvm))
4273                 return kvm_hv_hypercall(vcpu);
4274
4275         nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
4276         a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
4277         a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
4278         a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
4279         a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
4280
4281         trace_kvm_hypercall(nr, a0, a1, a2, a3);
4282
4283         if (!is_long_mode(vcpu)) {
4284                 nr &= 0xFFFFFFFF;
4285                 a0 &= 0xFFFFFFFF;
4286                 a1 &= 0xFFFFFFFF;
4287                 a2 &= 0xFFFFFFFF;
4288                 a3 &= 0xFFFFFFFF;
4289         }
4290
4291         if (kvm_x86_ops->get_cpl(vcpu) != 0) {
4292                 ret = -KVM_EPERM;
4293                 goto out;
4294         }
4295
4296         switch (nr) {
4297         case KVM_HC_VAPIC_POLL_IRQ:
4298                 ret = 0;
4299                 break;
4300         case KVM_HC_MMU_OP:
4301                 r = kvm_pv_mmu_op(vcpu, a0, hc_gpa(vcpu, a1, a2), &ret);
4302                 break;
4303         default:
4304                 ret = -KVM_ENOSYS;
4305                 break;
4306         }
4307 out:
4308         kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
4309         ++vcpu->stat.hypercalls;
4310         return r;
4311 }
4312 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
4313
4314 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
4315 {
4316         char instruction[3];
4317         unsigned long rip = kvm_rip_read(vcpu);
4318
4319         /*
4320          * Blow out the MMU to ensure that no other VCPU has an active mapping
4321          * to ensure that the updated hypercall appears atomically across all
4322          * VCPUs.
4323          */
4324         kvm_mmu_zap_all(vcpu->kvm);
4325
4326         kvm_x86_ops->patch_hypercall(vcpu, instruction);
4327
4328         return emulator_write_emulated(rip, instruction, 3, NULL, vcpu);
4329 }
4330
4331 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
4332 {
4333         struct desc_ptr dt = { limit, base };
4334
4335         kvm_x86_ops->set_gdt(vcpu, &dt);
4336 }
4337
4338 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
4339 {
4340         struct desc_ptr dt = { limit, base };
4341
4342         kvm_x86_ops->set_idt(vcpu, &dt);
4343 }
4344
4345 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
4346 {
4347         struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
4348         int j, nent = vcpu->arch.cpuid_nent;
4349
4350         e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
4351         /* when no next entry is found, the current entry[i] is reselected */
4352         for (j = i + 1; ; j = (j + 1) % nent) {
4353                 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
4354                 if (ej->function == e->function) {
4355                         ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
4356                         return j;
4357                 }
4358         }
4359         return 0; /* silence gcc, even though control never reaches here */
4360 }
4361
4362 /* find an entry with matching function, matching index (if needed), and that
4363  * should be read next (if it's stateful) */
4364 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
4365         u32 function, u32 index)
4366 {
4367         if (e->function != function)
4368                 return 0;
4369         if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
4370                 return 0;
4371         if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
4372             !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
4373                 return 0;
4374         return 1;
4375 }
4376
4377 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry(struct kvm_vcpu *vcpu,
4378                                               u32 function, u32 index)
4379 {
4380         int i;
4381         struct kvm_cpuid_entry2 *best = NULL;
4382
4383         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
4384                 struct kvm_cpuid_entry2 *e;
4385
4386                 e = &vcpu->arch.cpuid_entries[i];
4387                 if (is_matching_cpuid_entry(e, function, index)) {
4388                         if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
4389                                 move_to_next_stateful_cpuid_entry(vcpu, i);
4390                         best = e;
4391                         break;
4392                 }
4393                 /*
4394                  * Both basic or both extended?
4395                  */
4396                 if (((e->function ^ function) & 0x80000000) == 0)
4397                         if (!best || e->function > best->function)
4398                                 best = e;
4399         }
4400         return best;
4401 }
4402 EXPORT_SYMBOL_GPL(kvm_find_cpuid_entry);
4403
4404 int cpuid_maxphyaddr(struct kvm_vcpu *vcpu)
4405 {
4406         struct kvm_cpuid_entry2 *best;
4407
4408         best = kvm_find_cpuid_entry(vcpu, 0x80000000, 0);
4409         if (!best || best->eax < 0x80000008)
4410                 goto not_found;
4411         best = kvm_find_cpuid_entry(vcpu, 0x80000008, 0);
4412         if (best)
4413                 return best->eax & 0xff;
4414 not_found:
4415         return 36;
4416 }
4417
4418 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
4419 {
4420         u32 function, index;
4421         struct kvm_cpuid_entry2 *best;
4422
4423         function = kvm_register_read(vcpu, VCPU_REGS_RAX);
4424         index = kvm_register_read(vcpu, VCPU_REGS_RCX);
4425         kvm_register_write(vcpu, VCPU_REGS_RAX, 0);
4426         kvm_register_write(vcpu, VCPU_REGS_RBX, 0);
4427         kvm_register_write(vcpu, VCPU_REGS_RCX, 0);
4428         kvm_register_write(vcpu, VCPU_REGS_RDX, 0);
4429         best = kvm_find_cpuid_entry(vcpu, function, index);
4430         if (best) {
4431                 kvm_register_write(vcpu, VCPU_REGS_RAX, best->eax);
4432                 kvm_register_write(vcpu, VCPU_REGS_RBX, best->ebx);
4433                 kvm_register_write(vcpu, VCPU_REGS_RCX, best->ecx);
4434                 kvm_register_write(vcpu, VCPU_REGS_RDX, best->edx);
4435         }
4436         kvm_x86_ops->skip_emulated_instruction(vcpu);
4437         trace_kvm_cpuid(function,
4438                         kvm_register_read(vcpu, VCPU_REGS_RAX),
4439                         kvm_register_read(vcpu, VCPU_REGS_RBX),
4440                         kvm_register_read(vcpu, VCPU_REGS_RCX),
4441                         kvm_register_read(vcpu, VCPU_REGS_RDX));
4442 }
4443 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
4444
4445 /*
4446  * Check if userspace requested an interrupt window, and that the
4447  * interrupt window is open.
4448  *
4449  * No need to exit to userspace if we already have an interrupt queued.
4450  */
4451 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
4452 {
4453         return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
4454                 vcpu->run->request_interrupt_window &&
4455                 kvm_arch_interrupt_allowed(vcpu));
4456 }
4457
4458 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
4459 {
4460         struct kvm_run *kvm_run = vcpu->run;
4461
4462         kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
4463         kvm_run->cr8 = kvm_get_cr8(vcpu);
4464         kvm_run->apic_base = kvm_get_apic_base(vcpu);
4465         if (irqchip_in_kernel(vcpu->kvm))
4466                 kvm_run->ready_for_interrupt_injection = 1;
4467         else
4468                 kvm_run->ready_for_interrupt_injection =
4469                         kvm_arch_interrupt_allowed(vcpu) &&
4470                         !kvm_cpu_has_interrupt(vcpu) &&
4471                         !kvm_event_needs_reinjection(vcpu);
4472 }
4473
4474 static void vapic_enter(struct kvm_vcpu *vcpu)
4475 {
4476         struct kvm_lapic *apic = vcpu->arch.apic;
4477         struct page *page;
4478
4479         if (!apic || !apic->vapic_addr)
4480                 return;
4481
4482         page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
4483
4484         vcpu->arch.apic->vapic_page = page;
4485 }
4486
4487 static void vapic_exit(struct kvm_vcpu *vcpu)
4488 {
4489         struct kvm_lapic *apic = vcpu->arch.apic;
4490         int idx;
4491
4492         if (!apic || !apic->vapic_addr)
4493                 return;
4494
4495         idx = srcu_read_lock(&vcpu->kvm->srcu);
4496         kvm_release_page_dirty(apic->vapic_page);
4497         mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
4498         srcu_read_unlock(&vcpu->kvm->srcu, idx);
4499 }
4500
4501 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
4502 {
4503         int max_irr, tpr;
4504
4505         if (!kvm_x86_ops->update_cr8_intercept)
4506                 return;
4507
4508         if (!vcpu->arch.apic)
4509                 return;
4510
4511         if (!vcpu->arch.apic->vapic_addr)
4512                 max_irr = kvm_lapic_find_highest_irr(vcpu);
4513         else
4514                 max_irr = -1;
4515
4516         if (max_irr != -1)
4517                 max_irr >>= 4;
4518
4519         tpr = kvm_lapic_get_cr8(vcpu);
4520
4521         kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
4522 }
4523
4524 static void inject_pending_event(struct kvm_vcpu *vcpu)
4525 {
4526         /* try to reinject previous events if any */
4527         if (vcpu->arch.exception.pending) {
4528                 trace_kvm_inj_exception(vcpu->arch.exception.nr,
4529                                         vcpu->arch.exception.has_error_code,
4530                                         vcpu->arch.exception.error_code);
4531                 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
4532                                           vcpu->arch.exception.has_error_code,
4533                                           vcpu->arch.exception.error_code,
4534                                           vcpu->arch.exception.reinject);
4535                 return;
4536         }
4537
4538         if (vcpu->arch.nmi_injected) {
4539                 kvm_x86_ops->set_nmi(vcpu);
4540                 return;
4541         }
4542
4543         if (vcpu->arch.interrupt.pending) {
4544                 kvm_x86_ops->set_irq(vcpu);
4545                 return;
4546         }
4547
4548         /* try to inject new event if pending */
4549         if (vcpu->arch.nmi_pending) {
4550                 if (kvm_x86_ops->nmi_allowed(vcpu)) {
4551                         vcpu->arch.nmi_pending = false;
4552                         vcpu->arch.nmi_injected = true;
4553                         kvm_x86_ops->set_nmi(vcpu);
4554                 }
4555         } else if (kvm_cpu_has_interrupt(vcpu)) {
4556                 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
4557                         kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
4558                                             false);
4559                         kvm_x86_ops->set_irq(vcpu);
4560                 }
4561         }
4562 }
4563
4564 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
4565 {
4566         int r;
4567         bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
4568                 vcpu->run->request_interrupt_window;
4569
4570         if (vcpu->requests)
4571                 if (test_and_clear_bit(KVM_REQ_MMU_RELOAD, &vcpu->requests))
4572                         kvm_mmu_unload(vcpu);
4573
4574         r = kvm_mmu_reload(vcpu);
4575         if (unlikely(r))
4576                 goto out;
4577
4578         if (vcpu->requests) {
4579                 if (test_and_clear_bit(KVM_REQ_MIGRATE_TIMER, &vcpu->requests))
4580                         __kvm_migrate_timers(vcpu);
4581                 if (test_and_clear_bit(KVM_REQ_KVMCLOCK_UPDATE, &vcpu->requests))
4582                         kvm_write_guest_time(vcpu);
4583                 if (test_and_clear_bit(KVM_REQ_MMU_SYNC, &vcpu->requests))
4584                         kvm_mmu_sync_roots(vcpu);
4585                 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
4586                         kvm_x86_ops->tlb_flush(vcpu);
4587                 if (test_and_clear_bit(KVM_REQ_REPORT_TPR_ACCESS,
4588                                        &vcpu->requests)) {
4589                         vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
4590                         r = 0;
4591                         goto out;
4592                 }
4593                 if (test_and_clear_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests)) {
4594                         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4595                         r = 0;
4596                         goto out;
4597                 }
4598                 if (test_and_clear_bit(KVM_REQ_DEACTIVATE_FPU, &vcpu->requests)) {
4599                         vcpu->fpu_active = 0;
4600                         kvm_x86_ops->fpu_deactivate(vcpu);
4601                 }
4602         }
4603
4604         preempt_disable();
4605
4606         kvm_x86_ops->prepare_guest_switch(vcpu);
4607         if (vcpu->fpu_active)
4608                 kvm_load_guest_fpu(vcpu);
4609
4610         atomic_set(&vcpu->guest_mode, 1);
4611         smp_wmb();
4612
4613         local_irq_disable();
4614
4615         if (!atomic_read(&vcpu->guest_mode) || vcpu->requests
4616             || need_resched() || signal_pending(current)) {
4617                 atomic_set(&vcpu->guest_mode, 0);
4618                 smp_wmb();
4619                 local_irq_enable();
4620                 preempt_enable();
4621                 r = 1;
4622                 goto out;
4623         }
4624
4625         inject_pending_event(vcpu);
4626
4627         /* enable NMI/IRQ window open exits if needed */
4628         if (vcpu->arch.nmi_pending)
4629                 kvm_x86_ops->enable_nmi_window(vcpu);
4630         else if (kvm_cpu_has_interrupt(vcpu) || req_int_win)
4631                 kvm_x86_ops->enable_irq_window(vcpu);
4632
4633         if (kvm_lapic_enabled(vcpu)) {
4634                 update_cr8_intercept(vcpu);
4635                 kvm_lapic_sync_to_vapic(vcpu);
4636         }
4637
4638         srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
4639
4640         kvm_guest_enter();
4641
4642         if (unlikely(vcpu->arch.switch_db_regs)) {
4643                 set_debugreg(0, 7);
4644                 set_debugreg(vcpu->arch.eff_db[0], 0);
4645                 set_debugreg(vcpu->arch.eff_db[1], 1);
4646                 set_debugreg(vcpu->arch.eff_db[2], 2);
4647                 set_debugreg(vcpu->arch.eff_db[3], 3);
4648         }
4649
4650         trace_kvm_entry(vcpu->vcpu_id);
4651         kvm_x86_ops->run(vcpu);
4652
4653         /*
4654          * If the guest has used debug registers, at least dr7
4655          * will be disabled while returning to the host.
4656          * If we don't have active breakpoints in the host, we don't
4657          * care about the messed up debug address registers. But if
4658          * we have some of them active, restore the old state.
4659          */
4660         if (hw_breakpoint_active())
4661                 hw_breakpoint_restore();
4662
4663         atomic_set(&vcpu->guest_mode, 0);
4664         smp_wmb();
4665         local_irq_enable();
4666
4667         ++vcpu->stat.exits;
4668
4669         /*
4670          * We must have an instruction between local_irq_enable() and
4671          * kvm_guest_exit(), so the timer interrupt isn't delayed by
4672          * the interrupt shadow.  The stat.exits increment will do nicely.
4673          * But we need to prevent reordering, hence this barrier():
4674          */
4675         barrier();
4676
4677         kvm_guest_exit();
4678
4679         preempt_enable();
4680
4681         vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
4682
4683         /*
4684          * Profile KVM exit RIPs:
4685          */
4686         if (unlikely(prof_on == KVM_PROFILING)) {
4687                 unsigned long rip = kvm_rip_read(vcpu);
4688                 profile_hit(KVM_PROFILING, (void *)rip);
4689         }
4690
4691
4692         kvm_lapic_sync_from_vapic(vcpu);
4693
4694         r = kvm_x86_ops->handle_exit(vcpu);
4695 out:
4696         return r;
4697 }
4698
4699
4700 static int __vcpu_run(struct kvm_vcpu *vcpu)
4701 {
4702         int r;
4703         struct kvm *kvm = vcpu->kvm;
4704
4705         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
4706                 pr_debug("vcpu %d received sipi with vector # %x\n",
4707                          vcpu->vcpu_id, vcpu->arch.sipi_vector);
4708                 kvm_lapic_reset(vcpu);
4709                 r = kvm_arch_vcpu_reset(vcpu);
4710                 if (r)
4711                         return r;
4712                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
4713         }
4714
4715         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
4716         vapic_enter(vcpu);
4717
4718         r = 1;
4719         while (r > 0) {
4720                 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE)
4721                         r = vcpu_enter_guest(vcpu);
4722                 else {
4723                         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
4724                         kvm_vcpu_block(vcpu);
4725                         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
4726                         if (test_and_clear_bit(KVM_REQ_UNHALT, &vcpu->requests))
4727                         {
4728                                 switch(vcpu->arch.mp_state) {
4729                                 case KVM_MP_STATE_HALTED:
4730                                         vcpu->arch.mp_state =
4731                                                 KVM_MP_STATE_RUNNABLE;
4732                                 case KVM_MP_STATE_RUNNABLE:
4733                                         break;
4734                                 case KVM_MP_STATE_SIPI_RECEIVED:
4735                                 default:
4736                                         r = -EINTR;
4737                                         break;
4738                                 }
4739                         }
4740                 }
4741
4742                 if (r <= 0)
4743                         break;
4744
4745                 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
4746                 if (kvm_cpu_has_pending_timer(vcpu))
4747                         kvm_inject_pending_timer_irqs(vcpu);
4748
4749                 if (dm_request_for_irq_injection(vcpu)) {
4750                         r = -EINTR;
4751                         vcpu->run->exit_reason = KVM_EXIT_INTR;
4752                         ++vcpu->stat.request_irq_exits;
4753                 }
4754                 if (signal_pending(current)) {
4755                         r = -EINTR;
4756                         vcpu->run->exit_reason = KVM_EXIT_INTR;
4757                         ++vcpu->stat.signal_exits;
4758                 }
4759                 if (need_resched()) {
4760                         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
4761                         kvm_resched(vcpu);
4762                         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
4763                 }
4764         }
4765
4766         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
4767
4768         vapic_exit(vcpu);
4769
4770         return r;
4771 }
4772
4773 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
4774 {
4775         int r;
4776         sigset_t sigsaved;
4777
4778         vcpu_load(vcpu);
4779
4780         if (vcpu->sigset_active)
4781                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
4782
4783         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
4784                 kvm_vcpu_block(vcpu);
4785                 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
4786                 r = -EAGAIN;
4787                 goto out;
4788         }
4789
4790         /* re-sync apic's tpr */
4791         if (!irqchip_in_kernel(vcpu->kvm))
4792                 kvm_set_cr8(vcpu, kvm_run->cr8);
4793
4794         if (vcpu->arch.pio.count || vcpu->mmio_needed ||
4795             vcpu->arch.emulate_ctxt.restart) {
4796                 if (vcpu->mmio_needed) {
4797                         memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
4798                         vcpu->mmio_read_completed = 1;
4799                         vcpu->mmio_needed = 0;
4800                 }
4801                 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
4802                 r = emulate_instruction(vcpu, 0, 0, EMULTYPE_NO_DECODE);
4803                 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
4804                 if (r != EMULATE_DONE) {
4805                         r = 0;
4806                         goto out;
4807                 }
4808         }
4809         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL)
4810                 kvm_register_write(vcpu, VCPU_REGS_RAX,
4811                                      kvm_run->hypercall.ret);
4812
4813         r = __vcpu_run(vcpu);
4814
4815 out:
4816         post_kvm_run_save(vcpu);
4817         if (vcpu->sigset_active)
4818                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
4819
4820         vcpu_put(vcpu);
4821         return r;
4822 }
4823
4824 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
4825 {
4826         vcpu_load(vcpu);
4827
4828         regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
4829         regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
4830         regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
4831         regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
4832         regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
4833         regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
4834         regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
4835         regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
4836 #ifdef CONFIG_X86_64
4837         regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
4838         regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
4839         regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
4840         regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
4841         regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
4842         regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
4843         regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
4844         regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
4845 #endif
4846
4847         regs->rip = kvm_rip_read(vcpu);
4848         regs->rflags = kvm_get_rflags(vcpu);
4849
4850         vcpu_put(vcpu);
4851
4852         return 0;
4853 }
4854
4855 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
4856 {
4857         vcpu_load(vcpu);
4858
4859         kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
4860         kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
4861         kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
4862         kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
4863         kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
4864         kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
4865         kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
4866         kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
4867 #ifdef CONFIG_X86_64
4868         kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
4869         kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
4870         kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
4871         kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
4872         kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
4873         kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
4874         kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
4875         kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
4876 #endif
4877
4878         kvm_rip_write(vcpu, regs->rip);
4879         kvm_set_rflags(vcpu, regs->rflags);
4880
4881         vcpu->arch.exception.pending = false;
4882
4883         vcpu_put(vcpu);
4884
4885         return 0;
4886 }
4887
4888 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
4889 {
4890         struct kvm_segment cs;
4891
4892         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
4893         *db = cs.db;
4894         *l = cs.l;
4895 }
4896 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
4897
4898 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
4899                                   struct kvm_sregs *sregs)
4900 {
4901         struct desc_ptr dt;
4902
4903         vcpu_load(vcpu);
4904
4905         kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
4906         kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
4907         kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
4908         kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
4909         kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
4910         kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
4911
4912         kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
4913         kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
4914
4915         kvm_x86_ops->get_idt(vcpu, &dt);
4916         sregs->idt.limit = dt.size;
4917         sregs->idt.base = dt.address;
4918         kvm_x86_ops->get_gdt(vcpu, &dt);
4919         sregs->gdt.limit = dt.size;
4920         sregs->gdt.base = dt.address;
4921
4922         sregs->cr0 = kvm_read_cr0(vcpu);
4923         sregs->cr2 = vcpu->arch.cr2;
4924         sregs->cr3 = vcpu->arch.cr3;
4925         sregs->cr4 = kvm_read_cr4(vcpu);
4926         sregs->cr8 = kvm_get_cr8(vcpu);
4927         sregs->efer = vcpu->arch.efer;
4928         sregs->apic_base = kvm_get_apic_base(vcpu);
4929
4930         memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
4931
4932         if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
4933                 set_bit(vcpu->arch.interrupt.nr,
4934                         (unsigned long *)sregs->interrupt_bitmap);
4935
4936         vcpu_put(vcpu);
4937
4938         return 0;
4939 }
4940
4941 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
4942                                     struct kvm_mp_state *mp_state)
4943 {
4944         vcpu_load(vcpu);
4945         mp_state->mp_state = vcpu->arch.mp_state;
4946         vcpu_put(vcpu);
4947         return 0;
4948 }
4949
4950 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
4951                                     struct kvm_mp_state *mp_state)
4952 {
4953         vcpu_load(vcpu);
4954         vcpu->arch.mp_state = mp_state->mp_state;
4955         vcpu_put(vcpu);
4956         return 0;
4957 }
4958
4959 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason,
4960                     bool has_error_code, u32 error_code)
4961 {
4962         struct decode_cache *c = &vcpu->arch.emulate_ctxt.decode;
4963         int cs_db, cs_l, ret;
4964         cache_all_regs(vcpu);
4965
4966         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4967
4968         vcpu->arch.emulate_ctxt.vcpu = vcpu;
4969         vcpu->arch.emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
4970         vcpu->arch.emulate_ctxt.eip = kvm_rip_read(vcpu);
4971         vcpu->arch.emulate_ctxt.mode =
4972                 (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
4973                 (vcpu->arch.emulate_ctxt.eflags & X86_EFLAGS_VM)
4974                 ? X86EMUL_MODE_VM86 : cs_l
4975                 ? X86EMUL_MODE_PROT64 : cs_db
4976                 ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
4977         memset(c, 0, sizeof(struct decode_cache));
4978         memcpy(c->regs, vcpu->arch.regs, sizeof c->regs);
4979
4980         ret = emulator_task_switch(&vcpu->arch.emulate_ctxt, &emulate_ops,
4981                                    tss_selector, reason, has_error_code,
4982                                    error_code);
4983
4984         if (ret)
4985                 return EMULATE_FAIL;
4986
4987         memcpy(vcpu->arch.regs, c->regs, sizeof c->regs);
4988         kvm_rip_write(vcpu, vcpu->arch.emulate_ctxt.eip);
4989         kvm_x86_ops->set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
4990         return EMULATE_DONE;
4991 }
4992 EXPORT_SYMBOL_GPL(kvm_task_switch);
4993
4994 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
4995                                   struct kvm_sregs *sregs)
4996 {
4997         int mmu_reset_needed = 0;
4998         int pending_vec, max_bits;
4999         struct desc_ptr dt;
5000
5001         vcpu_load(vcpu);
5002
5003         dt.size = sregs->idt.limit;
5004         dt.address = sregs->idt.base;
5005         kvm_x86_ops->set_idt(vcpu, &dt);
5006         dt.size = sregs->gdt.limit;
5007         dt.address = sregs->gdt.base;
5008         kvm_x86_ops->set_gdt(vcpu, &dt);
5009
5010         vcpu->arch.cr2 = sregs->cr2;
5011         mmu_reset_needed |= vcpu->arch.cr3 != sregs->cr3;
5012         vcpu->arch.cr3 = sregs->cr3;
5013
5014         kvm_set_cr8(vcpu, sregs->cr8);
5015
5016         mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
5017         kvm_x86_ops->set_efer(vcpu, sregs->efer);
5018         kvm_set_apic_base(vcpu, sregs->apic_base);
5019
5020         mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
5021         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
5022         vcpu->arch.cr0 = sregs->cr0;
5023
5024         mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
5025         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
5026         if (!is_long_mode(vcpu) && is_pae(vcpu)) {
5027                 load_pdptrs(vcpu, vcpu->arch.cr3);
5028                 mmu_reset_needed = 1;
5029         }
5030
5031         if (mmu_reset_needed)
5032                 kvm_mmu_reset_context(vcpu);
5033
5034         max_bits = (sizeof sregs->interrupt_bitmap) << 3;
5035         pending_vec = find_first_bit(
5036                 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
5037         if (pending_vec < max_bits) {
5038                 kvm_queue_interrupt(vcpu, pending_vec, false);
5039                 pr_debug("Set back pending irq %d\n", pending_vec);
5040                 if (irqchip_in_kernel(vcpu->kvm))
5041                         kvm_pic_clear_isr_ack(vcpu->kvm);
5042         }
5043
5044         kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
5045         kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
5046         kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
5047         kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
5048         kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
5049         kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
5050
5051         kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
5052         kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
5053
5054         update_cr8_intercept(vcpu);
5055
5056         /* Older userspace won't unhalt the vcpu on reset. */
5057         if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
5058             sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
5059             !is_protmode(vcpu))
5060                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5061
5062         vcpu_put(vcpu);
5063
5064         return 0;
5065 }
5066
5067 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
5068                                         struct kvm_guest_debug *dbg)
5069 {
5070         unsigned long rflags;
5071         int i, r;
5072
5073         vcpu_load(vcpu);
5074
5075         if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
5076                 r = -EBUSY;
5077                 if (vcpu->arch.exception.pending)
5078                         goto unlock_out;
5079                 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
5080                         kvm_queue_exception(vcpu, DB_VECTOR);
5081                 else
5082                         kvm_queue_exception(vcpu, BP_VECTOR);
5083         }
5084
5085         /*
5086          * Read rflags as long as potentially injected trace flags are still
5087          * filtered out.
5088          */
5089         rflags = kvm_get_rflags(vcpu);
5090
5091         vcpu->guest_debug = dbg->control;
5092         if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
5093                 vcpu->guest_debug = 0;
5094
5095         if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5096                 for (i = 0; i < KVM_NR_DB_REGS; ++i)
5097                         vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
5098                 vcpu->arch.switch_db_regs =
5099                         (dbg->arch.debugreg[7] & DR7_BP_EN_MASK);
5100         } else {
5101                 for (i = 0; i < KVM_NR_DB_REGS; i++)
5102                         vcpu->arch.eff_db[i] = vcpu->arch.db[i];
5103                 vcpu->arch.switch_db_regs = (vcpu->arch.dr7 & DR7_BP_EN_MASK);
5104         }
5105
5106         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
5107                 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
5108                         get_segment_base(vcpu, VCPU_SREG_CS);
5109
5110         /*
5111          * Trigger an rflags update that will inject or remove the trace
5112          * flags.
5113          */
5114         kvm_set_rflags(vcpu, rflags);
5115
5116         kvm_x86_ops->set_guest_debug(vcpu, dbg);
5117
5118         r = 0;
5119
5120 unlock_out:
5121         vcpu_put(vcpu);
5122
5123         return r;
5124 }
5125
5126 /*
5127  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
5128  * we have asm/x86/processor.h
5129  */
5130 struct fxsave {
5131         u16     cwd;
5132         u16     swd;
5133         u16     twd;
5134         u16     fop;
5135         u64     rip;
5136         u64     rdp;
5137         u32     mxcsr;
5138         u32     mxcsr_mask;
5139         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
5140 #ifdef CONFIG_X86_64
5141         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
5142 #else
5143         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
5144 #endif
5145 };
5146
5147 /*
5148  * Translate a guest virtual address to a guest physical address.
5149  */
5150 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
5151                                     struct kvm_translation *tr)
5152 {
5153         unsigned long vaddr = tr->linear_address;
5154         gpa_t gpa;
5155         int idx;
5156
5157         vcpu_load(vcpu);
5158         idx = srcu_read_lock(&vcpu->kvm->srcu);
5159         gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
5160         srcu_read_unlock(&vcpu->kvm->srcu, idx);
5161         tr->physical_address = gpa;
5162         tr->valid = gpa != UNMAPPED_GVA;
5163         tr->writeable = 1;
5164         tr->usermode = 0;
5165         vcpu_put(vcpu);
5166
5167         return 0;
5168 }
5169
5170 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
5171 {
5172         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
5173
5174         vcpu_load(vcpu);
5175
5176         memcpy(fpu->fpr, fxsave->st_space, 128);
5177         fpu->fcw = fxsave->cwd;
5178         fpu->fsw = fxsave->swd;
5179         fpu->ftwx = fxsave->twd;
5180         fpu->last_opcode = fxsave->fop;
5181         fpu->last_ip = fxsave->rip;
5182         fpu->last_dp = fxsave->rdp;
5183         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
5184
5185         vcpu_put(vcpu);
5186
5187         return 0;
5188 }
5189
5190 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
5191 {
5192         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
5193
5194         vcpu_load(vcpu);
5195
5196         memcpy(fxsave->st_space, fpu->fpr, 128);
5197         fxsave->cwd = fpu->fcw;
5198         fxsave->swd = fpu->fsw;
5199         fxsave->twd = fpu->ftwx;
5200         fxsave->fop = fpu->last_opcode;
5201         fxsave->rip = fpu->last_ip;
5202         fxsave->rdp = fpu->last_dp;
5203         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
5204
5205         vcpu_put(vcpu);
5206
5207         return 0;
5208 }
5209
5210 void fx_init(struct kvm_vcpu *vcpu)
5211 {
5212         unsigned after_mxcsr_mask;
5213
5214         /*
5215          * Touch the fpu the first time in non atomic context as if
5216          * this is the first fpu instruction the exception handler
5217          * will fire before the instruction returns and it'll have to
5218          * allocate ram with GFP_KERNEL.
5219          */
5220         if (!used_math())
5221                 kvm_fx_save(&vcpu->arch.host_fx_image);
5222
5223         /* Initialize guest FPU by resetting ours and saving into guest's */
5224         preempt_disable();
5225         kvm_fx_save(&vcpu->arch.host_fx_image);
5226         kvm_fx_finit();
5227         kvm_fx_save(&vcpu->arch.guest_fx_image);
5228         kvm_fx_restore(&vcpu->arch.host_fx_image);
5229         preempt_enable();
5230
5231         vcpu->arch.cr0 |= X86_CR0_ET;
5232         after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
5233         vcpu->arch.guest_fx_image.mxcsr = 0x1f80;
5234         memset((void *)&vcpu->arch.guest_fx_image + after_mxcsr_mask,
5235                0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
5236 }
5237 EXPORT_SYMBOL_GPL(fx_init);
5238
5239 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
5240 {
5241         if (vcpu->guest_fpu_loaded)
5242                 return;
5243
5244         vcpu->guest_fpu_loaded = 1;
5245         kvm_fx_save(&vcpu->arch.host_fx_image);
5246         kvm_fx_restore(&vcpu->arch.guest_fx_image);
5247         trace_kvm_fpu(1);
5248 }
5249
5250 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
5251 {
5252         if (!vcpu->guest_fpu_loaded)
5253                 return;
5254
5255         vcpu->guest_fpu_loaded = 0;
5256         kvm_fx_save(&vcpu->arch.guest_fx_image);
5257         kvm_fx_restore(&vcpu->arch.host_fx_image);
5258         ++vcpu->stat.fpu_reload;
5259         set_bit(KVM_REQ_DEACTIVATE_FPU, &vcpu->requests);
5260         trace_kvm_fpu(0);
5261 }
5262
5263 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
5264 {
5265         if (vcpu->arch.time_page) {
5266                 kvm_release_page_dirty(vcpu->arch.time_page);
5267                 vcpu->arch.time_page = NULL;
5268         }
5269
5270         kvm_x86_ops->vcpu_free(vcpu);
5271 }
5272
5273 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
5274                                                 unsigned int id)
5275 {
5276         return kvm_x86_ops->vcpu_create(kvm, id);
5277 }
5278
5279 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
5280 {
5281         int r;
5282
5283         /* We do fxsave: this must be aligned. */
5284         BUG_ON((unsigned long)&vcpu->arch.host_fx_image & 0xF);
5285
5286         vcpu->arch.mtrr_state.have_fixed = 1;
5287         vcpu_load(vcpu);
5288         r = kvm_arch_vcpu_reset(vcpu);
5289         if (r == 0)
5290                 r = kvm_mmu_setup(vcpu);
5291         vcpu_put(vcpu);
5292         if (r < 0)
5293                 goto free_vcpu;
5294
5295         return 0;
5296 free_vcpu:
5297         kvm_x86_ops->vcpu_free(vcpu);
5298         return r;
5299 }
5300
5301 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
5302 {
5303         vcpu_load(vcpu);
5304         kvm_mmu_unload(vcpu);
5305         vcpu_put(vcpu);
5306
5307         kvm_x86_ops->vcpu_free(vcpu);
5308 }
5309
5310 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
5311 {
5312         vcpu->arch.nmi_pending = false;
5313         vcpu->arch.nmi_injected = false;
5314
5315         vcpu->arch.switch_db_regs = 0;
5316         memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
5317         vcpu->arch.dr6 = DR6_FIXED_1;
5318         vcpu->arch.dr7 = DR7_FIXED_1;
5319
5320         return kvm_x86_ops->vcpu_reset(vcpu);
5321 }
5322
5323 int kvm_arch_hardware_enable(void *garbage)
5324 {
5325         /*
5326          * Since this may be called from a hotplug notifcation,
5327          * we can't get the CPU frequency directly.
5328          */
5329         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5330                 int cpu = raw_smp_processor_id();
5331                 per_cpu(cpu_tsc_khz, cpu) = 0;
5332         }
5333
5334         kvm_shared_msr_cpu_online();
5335
5336         return kvm_x86_ops->hardware_enable(garbage);
5337 }
5338
5339 void kvm_arch_hardware_disable(void *garbage)
5340 {
5341         kvm_x86_ops->hardware_disable(garbage);
5342         drop_user_return_notifiers(garbage);
5343 }
5344
5345 int kvm_arch_hardware_setup(void)
5346 {
5347         return kvm_x86_ops->hardware_setup();
5348 }
5349
5350 void kvm_arch_hardware_unsetup(void)
5351 {
5352         kvm_x86_ops->hardware_unsetup();
5353 }
5354
5355 void kvm_arch_check_processor_compat(void *rtn)
5356 {
5357         kvm_x86_ops->check_processor_compatibility(rtn);
5358 }
5359
5360 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
5361 {
5362         struct page *page;
5363         struct kvm *kvm;
5364         int r;
5365
5366         BUG_ON(vcpu->kvm == NULL);
5367         kvm = vcpu->kvm;
5368
5369         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
5370         if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
5371                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5372         else
5373                 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
5374
5375         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
5376         if (!page) {
5377                 r = -ENOMEM;
5378                 goto fail;
5379         }
5380         vcpu->arch.pio_data = page_address(page);
5381
5382         r = kvm_mmu_create(vcpu);
5383         if (r < 0)
5384                 goto fail_free_pio_data;
5385
5386         if (irqchip_in_kernel(kvm)) {
5387                 r = kvm_create_lapic(vcpu);
5388                 if (r < 0)
5389                         goto fail_mmu_destroy;
5390         }
5391
5392         vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
5393                                        GFP_KERNEL);
5394         if (!vcpu->arch.mce_banks) {
5395                 r = -ENOMEM;
5396                 goto fail_free_lapic;
5397         }
5398         vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
5399
5400         return 0;
5401 fail_free_lapic:
5402         kvm_free_lapic(vcpu);
5403 fail_mmu_destroy:
5404         kvm_mmu_destroy(vcpu);
5405 fail_free_pio_data:
5406         free_page((unsigned long)vcpu->arch.pio_data);
5407 fail:
5408         return r;
5409 }
5410
5411 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
5412 {
5413         int idx;
5414
5415         kfree(vcpu->arch.mce_banks);
5416         kvm_free_lapic(vcpu);
5417         idx = srcu_read_lock(&vcpu->kvm->srcu);
5418         kvm_mmu_destroy(vcpu);
5419         srcu_read_unlock(&vcpu->kvm->srcu, idx);
5420         free_page((unsigned long)vcpu->arch.pio_data);
5421 }
5422
5423 struct  kvm *kvm_arch_create_vm(void)
5424 {
5425         struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
5426
5427         if (!kvm)
5428                 return ERR_PTR(-ENOMEM);
5429
5430         kvm->arch.aliases = kzalloc(sizeof(struct kvm_mem_aliases), GFP_KERNEL);
5431         if (!kvm->arch.aliases) {
5432                 kfree(kvm);
5433                 return ERR_PTR(-ENOMEM);
5434         }
5435
5436         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
5437         INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
5438
5439         /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
5440         set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
5441
5442         rdtscll(kvm->arch.vm_init_tsc);
5443
5444         return kvm;
5445 }
5446
5447 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
5448 {
5449         vcpu_load(vcpu);
5450         kvm_mmu_unload(vcpu);
5451         vcpu_put(vcpu);
5452 }
5453
5454 static void kvm_free_vcpus(struct kvm *kvm)
5455 {
5456         unsigned int i;
5457         struct kvm_vcpu *vcpu;
5458
5459         /*
5460          * Unpin any mmu pages first.
5461          */
5462         kvm_for_each_vcpu(i, vcpu, kvm)
5463                 kvm_unload_vcpu_mmu(vcpu);
5464         kvm_for_each_vcpu(i, vcpu, kvm)
5465                 kvm_arch_vcpu_free(vcpu);
5466
5467         mutex_lock(&kvm->lock);
5468         for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
5469                 kvm->vcpus[i] = NULL;
5470
5471         atomic_set(&kvm->online_vcpus, 0);
5472         mutex_unlock(&kvm->lock);
5473 }
5474
5475 void kvm_arch_sync_events(struct kvm *kvm)
5476 {
5477         kvm_free_all_assigned_devices(kvm);
5478 }
5479
5480 void kvm_arch_destroy_vm(struct kvm *kvm)
5481 {
5482         kvm_iommu_unmap_guest(kvm);
5483         kvm_free_pit(kvm);
5484         kfree(kvm->arch.vpic);
5485         kfree(kvm->arch.vioapic);
5486         kvm_free_vcpus(kvm);
5487         kvm_free_physmem(kvm);
5488         if (kvm->arch.apic_access_page)
5489                 put_page(kvm->arch.apic_access_page);
5490         if (kvm->arch.ept_identity_pagetable)
5491                 put_page(kvm->arch.ept_identity_pagetable);
5492         cleanup_srcu_struct(&kvm->srcu);
5493         kfree(kvm->arch.aliases);
5494         kfree(kvm);
5495 }
5496
5497 int kvm_arch_prepare_memory_region(struct kvm *kvm,
5498                                 struct kvm_memory_slot *memslot,
5499                                 struct kvm_memory_slot old,
5500                                 struct kvm_userspace_memory_region *mem,
5501                                 int user_alloc)
5502 {
5503         int npages = memslot->npages;
5504
5505         /*To keep backward compatibility with older userspace,
5506          *x86 needs to hanlde !user_alloc case.
5507          */
5508         if (!user_alloc) {
5509                 if (npages && !old.rmap) {
5510                         unsigned long userspace_addr;
5511
5512                         down_write(&current->mm->mmap_sem);
5513                         userspace_addr = do_mmap(NULL, 0,
5514                                                  npages * PAGE_SIZE,
5515                                                  PROT_READ | PROT_WRITE,
5516                                                  MAP_PRIVATE | MAP_ANONYMOUS,
5517                                                  0);
5518                         up_write(&current->mm->mmap_sem);
5519
5520                         if (IS_ERR((void *)userspace_addr))
5521                                 return PTR_ERR((void *)userspace_addr);
5522
5523                         memslot->userspace_addr = userspace_addr;
5524                 }
5525         }
5526
5527
5528         return 0;
5529 }
5530
5531 void kvm_arch_commit_memory_region(struct kvm *kvm,
5532                                 struct kvm_userspace_memory_region *mem,
5533                                 struct kvm_memory_slot old,
5534                                 int user_alloc)
5535 {
5536
5537         int npages = mem->memory_size >> PAGE_SHIFT;
5538
5539         if (!user_alloc && !old.user_alloc && old.rmap && !npages) {
5540                 int ret;
5541
5542                 down_write(&current->mm->mmap_sem);
5543                 ret = do_munmap(current->mm, old.userspace_addr,
5544                                 old.npages * PAGE_SIZE);
5545                 up_write(&current->mm->mmap_sem);
5546                 if (ret < 0)
5547                         printk(KERN_WARNING
5548                                "kvm_vm_ioctl_set_memory_region: "
5549                                "failed to munmap memory\n");
5550         }
5551
5552         spin_lock(&kvm->mmu_lock);
5553         if (!kvm->arch.n_requested_mmu_pages) {
5554                 unsigned int nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
5555                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
5556         }
5557
5558         kvm_mmu_slot_remove_write_access(kvm, mem->slot);
5559         spin_unlock(&kvm->mmu_lock);
5560 }
5561
5562 void kvm_arch_flush_shadow(struct kvm *kvm)
5563 {
5564         kvm_mmu_zap_all(kvm);
5565         kvm_reload_remote_mmus(kvm);
5566 }
5567
5568 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
5569 {
5570         return vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE
5571                 || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
5572                 || vcpu->arch.nmi_pending ||
5573                 (kvm_arch_interrupt_allowed(vcpu) &&
5574                  kvm_cpu_has_interrupt(vcpu));
5575 }
5576
5577 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
5578 {
5579         int me;
5580         int cpu = vcpu->cpu;
5581
5582         if (waitqueue_active(&vcpu->wq)) {
5583                 wake_up_interruptible(&vcpu->wq);
5584                 ++vcpu->stat.halt_wakeup;
5585         }
5586
5587         me = get_cpu();
5588         if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
5589                 if (atomic_xchg(&vcpu->guest_mode, 0))
5590                         smp_send_reschedule(cpu);
5591         put_cpu();
5592 }
5593
5594 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
5595 {
5596         return kvm_x86_ops->interrupt_allowed(vcpu);
5597 }
5598
5599 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
5600 {
5601         unsigned long current_rip = kvm_rip_read(vcpu) +
5602                 get_segment_base(vcpu, VCPU_SREG_CS);
5603
5604         return current_rip == linear_rip;
5605 }
5606 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
5607
5608 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
5609 {
5610         unsigned long rflags;
5611
5612         rflags = kvm_x86_ops->get_rflags(vcpu);
5613         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
5614                 rflags &= ~X86_EFLAGS_TF;
5615         return rflags;
5616 }
5617 EXPORT_SYMBOL_GPL(kvm_get_rflags);
5618
5619 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
5620 {
5621         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
5622             kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
5623                 rflags |= X86_EFLAGS_TF;
5624         kvm_x86_ops->set_rflags(vcpu, rflags);
5625 }
5626 EXPORT_SYMBOL_GPL(kvm_set_rflags);
5627
5628 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
5629 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
5630 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
5631 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
5632 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
5633 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
5634 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
5635 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
5636 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
5637 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
5638 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
5639 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);