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