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