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