KVM: Make unloading of FPU state when putting vcpu arch-independent
[pandora-kernel.git] / drivers / 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  *
8  * Authors:
9  *   Avi Kivity   <avi@qumranet.com>
10  *   Yaniv Kamay  <yaniv@qumranet.com>
11  *
12  * This work is licensed under the terms of the GNU GPL, version 2.  See
13  * the COPYING file in the top-level directory.
14  *
15  */
16
17 #include "kvm.h"
18 #include "x86.h"
19 #include "x86_emulate.h"
20 #include "segment_descriptor.h"
21 #include "irq.h"
22
23 #include <linux/kvm.h>
24 #include <linux/fs.h>
25 #include <linux/vmalloc.h>
26 #include <linux/module.h>
27
28 #include <asm/uaccess.h>
29 #include <asm/msr.h>
30
31 #define MAX_IO_MSRS 256
32 #define CR0_RESERVED_BITS                                               \
33         (~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
34                           | X86_CR0_ET | X86_CR0_NE | X86_CR0_WP | X86_CR0_AM \
35                           | X86_CR0_NW | X86_CR0_CD | X86_CR0_PG))
36 #define CR4_RESERVED_BITS                                               \
37         (~(unsigned long)(X86_CR4_VME | X86_CR4_PVI | X86_CR4_TSD | X86_CR4_DE\
38                           | X86_CR4_PSE | X86_CR4_PAE | X86_CR4_MCE     \
39                           | X86_CR4_PGE | X86_CR4_PCE | X86_CR4_OSFXSR  \
40                           | X86_CR4_OSXMMEXCPT | X86_CR4_VMXE))
41
42 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
43 #define EFER_RESERVED_BITS 0xfffffffffffff2fe
44
45 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
46 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
47
48 struct kvm_x86_ops *kvm_x86_ops;
49
50 struct kvm_stats_debugfs_item debugfs_entries[] = {
51         { "pf_fixed", VCPU_STAT(pf_fixed) },
52         { "pf_guest", VCPU_STAT(pf_guest) },
53         { "tlb_flush", VCPU_STAT(tlb_flush) },
54         { "invlpg", VCPU_STAT(invlpg) },
55         { "exits", VCPU_STAT(exits) },
56         { "io_exits", VCPU_STAT(io_exits) },
57         { "mmio_exits", VCPU_STAT(mmio_exits) },
58         { "signal_exits", VCPU_STAT(signal_exits) },
59         { "irq_window", VCPU_STAT(irq_window_exits) },
60         { "halt_exits", VCPU_STAT(halt_exits) },
61         { "halt_wakeup", VCPU_STAT(halt_wakeup) },
62         { "request_irq", VCPU_STAT(request_irq_exits) },
63         { "irq_exits", VCPU_STAT(irq_exits) },
64         { "host_state_reload", VCPU_STAT(host_state_reload) },
65         { "efer_reload", VCPU_STAT(efer_reload) },
66         { "fpu_reload", VCPU_STAT(fpu_reload) },
67         { "insn_emulation", VCPU_STAT(insn_emulation) },
68         { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
69         { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
70         { "mmu_pte_write", VM_STAT(mmu_pte_write) },
71         { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
72         { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
73         { "mmu_flooded", VM_STAT(mmu_flooded) },
74         { "mmu_recycled", VM_STAT(mmu_recycled) },
75         { NULL }
76 };
77
78
79 unsigned long segment_base(u16 selector)
80 {
81         struct descriptor_table gdt;
82         struct segment_descriptor *d;
83         unsigned long table_base;
84         unsigned long v;
85
86         if (selector == 0)
87                 return 0;
88
89         asm("sgdt %0" : "=m"(gdt));
90         table_base = gdt.base;
91
92         if (selector & 4) {           /* from ldt */
93                 u16 ldt_selector;
94
95                 asm("sldt %0" : "=g"(ldt_selector));
96                 table_base = segment_base(ldt_selector);
97         }
98         d = (struct segment_descriptor *)(table_base + (selector & ~7));
99         v = d->base_low | ((unsigned long)d->base_mid << 16) |
100                 ((unsigned long)d->base_high << 24);
101 #ifdef CONFIG_X86_64
102         if (d->system == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
103                 v |= ((unsigned long) \
104                       ((struct segment_descriptor_64 *)d)->base_higher) << 32;
105 #endif
106         return v;
107 }
108 EXPORT_SYMBOL_GPL(segment_base);
109
110 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
111 {
112         if (irqchip_in_kernel(vcpu->kvm))
113                 return vcpu->apic_base;
114         else
115                 return vcpu->apic_base;
116 }
117 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
118
119 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
120 {
121         /* TODO: reserve bits check */
122         if (irqchip_in_kernel(vcpu->kvm))
123                 kvm_lapic_set_base(vcpu, data);
124         else
125                 vcpu->apic_base = data;
126 }
127 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
128
129 static void inject_gp(struct kvm_vcpu *vcpu)
130 {
131         kvm_x86_ops->inject_gp(vcpu, 0);
132 }
133
134 /*
135  * Load the pae pdptrs.  Return true is they are all valid.
136  */
137 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
138 {
139         gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
140         unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
141         int i;
142         int ret;
143         u64 pdpte[ARRAY_SIZE(vcpu->pdptrs)];
144
145         mutex_lock(&vcpu->kvm->lock);
146         ret = kvm_read_guest_page(vcpu->kvm, pdpt_gfn, pdpte,
147                                   offset * sizeof(u64), sizeof(pdpte));
148         if (ret < 0) {
149                 ret = 0;
150                 goto out;
151         }
152         for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
153                 if ((pdpte[i] & 1) && (pdpte[i] & 0xfffffff0000001e6ull)) {
154                         ret = 0;
155                         goto out;
156                 }
157         }
158         ret = 1;
159
160         memcpy(vcpu->pdptrs, pdpte, sizeof(vcpu->pdptrs));
161 out:
162         mutex_unlock(&vcpu->kvm->lock);
163
164         return ret;
165 }
166
167 void set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
168 {
169         if (cr0 & CR0_RESERVED_BITS) {
170                 printk(KERN_DEBUG "set_cr0: 0x%lx #GP, reserved bits 0x%lx\n",
171                        cr0, vcpu->cr0);
172                 inject_gp(vcpu);
173                 return;
174         }
175
176         if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD)) {
177                 printk(KERN_DEBUG "set_cr0: #GP, CD == 0 && NW == 1\n");
178                 inject_gp(vcpu);
179                 return;
180         }
181
182         if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE)) {
183                 printk(KERN_DEBUG "set_cr0: #GP, set PG flag "
184                        "and a clear PE flag\n");
185                 inject_gp(vcpu);
186                 return;
187         }
188
189         if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
190 #ifdef CONFIG_X86_64
191                 if ((vcpu->shadow_efer & EFER_LME)) {
192                         int cs_db, cs_l;
193
194                         if (!is_pae(vcpu)) {
195                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
196                                        "in long mode while PAE is disabled\n");
197                                 inject_gp(vcpu);
198                                 return;
199                         }
200                         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
201                         if (cs_l) {
202                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
203                                        "in long mode while CS.L == 1\n");
204                                 inject_gp(vcpu);
205                                 return;
206
207                         }
208                 } else
209 #endif
210                 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->cr3)) {
211                         printk(KERN_DEBUG "set_cr0: #GP, pdptrs "
212                                "reserved bits\n");
213                         inject_gp(vcpu);
214                         return;
215                 }
216
217         }
218
219         kvm_x86_ops->set_cr0(vcpu, cr0);
220         vcpu->cr0 = cr0;
221
222         mutex_lock(&vcpu->kvm->lock);
223         kvm_mmu_reset_context(vcpu);
224         mutex_unlock(&vcpu->kvm->lock);
225         return;
226 }
227 EXPORT_SYMBOL_GPL(set_cr0);
228
229 void lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
230 {
231         set_cr0(vcpu, (vcpu->cr0 & ~0x0ful) | (msw & 0x0f));
232 }
233 EXPORT_SYMBOL_GPL(lmsw);
234
235 void set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
236 {
237         if (cr4 & CR4_RESERVED_BITS) {
238                 printk(KERN_DEBUG "set_cr4: #GP, reserved bits\n");
239                 inject_gp(vcpu);
240                 return;
241         }
242
243         if (is_long_mode(vcpu)) {
244                 if (!(cr4 & X86_CR4_PAE)) {
245                         printk(KERN_DEBUG "set_cr4: #GP, clearing PAE while "
246                                "in long mode\n");
247                         inject_gp(vcpu);
248                         return;
249                 }
250         } else if (is_paging(vcpu) && !is_pae(vcpu) && (cr4 & X86_CR4_PAE)
251                    && !load_pdptrs(vcpu, vcpu->cr3)) {
252                 printk(KERN_DEBUG "set_cr4: #GP, pdptrs reserved bits\n");
253                 inject_gp(vcpu);
254                 return;
255         }
256
257         if (cr4 & X86_CR4_VMXE) {
258                 printk(KERN_DEBUG "set_cr4: #GP, setting VMXE\n");
259                 inject_gp(vcpu);
260                 return;
261         }
262         kvm_x86_ops->set_cr4(vcpu, cr4);
263         vcpu->cr4 = cr4;
264         mutex_lock(&vcpu->kvm->lock);
265         kvm_mmu_reset_context(vcpu);
266         mutex_unlock(&vcpu->kvm->lock);
267 }
268 EXPORT_SYMBOL_GPL(set_cr4);
269
270 void set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
271 {
272         if (is_long_mode(vcpu)) {
273                 if (cr3 & CR3_L_MODE_RESERVED_BITS) {
274                         printk(KERN_DEBUG "set_cr3: #GP, reserved bits\n");
275                         inject_gp(vcpu);
276                         return;
277                 }
278         } else {
279                 if (is_pae(vcpu)) {
280                         if (cr3 & CR3_PAE_RESERVED_BITS) {
281                                 printk(KERN_DEBUG
282                                        "set_cr3: #GP, reserved bits\n");
283                                 inject_gp(vcpu);
284                                 return;
285                         }
286                         if (is_paging(vcpu) && !load_pdptrs(vcpu, cr3)) {
287                                 printk(KERN_DEBUG "set_cr3: #GP, pdptrs "
288                                        "reserved bits\n");
289                                 inject_gp(vcpu);
290                                 return;
291                         }
292                 }
293                 /*
294                  * We don't check reserved bits in nonpae mode, because
295                  * this isn't enforced, and VMware depends on this.
296                  */
297         }
298
299         mutex_lock(&vcpu->kvm->lock);
300         /*
301          * Does the new cr3 value map to physical memory? (Note, we
302          * catch an invalid cr3 even in real-mode, because it would
303          * cause trouble later on when we turn on paging anyway.)
304          *
305          * A real CPU would silently accept an invalid cr3 and would
306          * attempt to use it - with largely undefined (and often hard
307          * to debug) behavior on the guest side.
308          */
309         if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
310                 inject_gp(vcpu);
311         else {
312                 vcpu->cr3 = cr3;
313                 vcpu->mmu.new_cr3(vcpu);
314         }
315         mutex_unlock(&vcpu->kvm->lock);
316 }
317 EXPORT_SYMBOL_GPL(set_cr3);
318
319 void set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
320 {
321         if (cr8 & CR8_RESERVED_BITS) {
322                 printk(KERN_DEBUG "set_cr8: #GP, reserved bits 0x%lx\n", cr8);
323                 inject_gp(vcpu);
324                 return;
325         }
326         if (irqchip_in_kernel(vcpu->kvm))
327                 kvm_lapic_set_tpr(vcpu, cr8);
328         else
329                 vcpu->cr8 = cr8;
330 }
331 EXPORT_SYMBOL_GPL(set_cr8);
332
333 unsigned long get_cr8(struct kvm_vcpu *vcpu)
334 {
335         if (irqchip_in_kernel(vcpu->kvm))
336                 return kvm_lapic_get_cr8(vcpu);
337         else
338                 return vcpu->cr8;
339 }
340 EXPORT_SYMBOL_GPL(get_cr8);
341
342 /*
343  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
344  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
345  *
346  * This list is modified at module load time to reflect the
347  * capabilities of the host cpu.
348  */
349 static u32 msrs_to_save[] = {
350         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
351         MSR_K6_STAR,
352 #ifdef CONFIG_X86_64
353         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
354 #endif
355         MSR_IA32_TIME_STAMP_COUNTER,
356 };
357
358 static unsigned num_msrs_to_save;
359
360 static u32 emulated_msrs[] = {
361         MSR_IA32_MISC_ENABLE,
362 };
363
364 #ifdef CONFIG_X86_64
365
366 static void set_efer(struct kvm_vcpu *vcpu, u64 efer)
367 {
368         if (efer & EFER_RESERVED_BITS) {
369                 printk(KERN_DEBUG "set_efer: 0x%llx #GP, reserved bits\n",
370                        efer);
371                 inject_gp(vcpu);
372                 return;
373         }
374
375         if (is_paging(vcpu)
376             && (vcpu->shadow_efer & EFER_LME) != (efer & EFER_LME)) {
377                 printk(KERN_DEBUG "set_efer: #GP, change LME while paging\n");
378                 inject_gp(vcpu);
379                 return;
380         }
381
382         kvm_x86_ops->set_efer(vcpu, efer);
383
384         efer &= ~EFER_LMA;
385         efer |= vcpu->shadow_efer & EFER_LMA;
386
387         vcpu->shadow_efer = efer;
388 }
389
390 #endif
391
392 /*
393  * Writes msr value into into the appropriate "register".
394  * Returns 0 on success, non-0 otherwise.
395  * Assumes vcpu_load() was already called.
396  */
397 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
398 {
399         return kvm_x86_ops->set_msr(vcpu, msr_index, data);
400 }
401
402 /*
403  * Adapt set_msr() to msr_io()'s calling convention
404  */
405 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
406 {
407         return kvm_set_msr(vcpu, index, *data);
408 }
409
410
411 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
412 {
413         switch (msr) {
414 #ifdef CONFIG_X86_64
415         case MSR_EFER:
416                 set_efer(vcpu, data);
417                 break;
418 #endif
419         case MSR_IA32_MC0_STATUS:
420                 pr_unimpl(vcpu, "%s: MSR_IA32_MC0_STATUS 0x%llx, nop\n",
421                        __FUNCTION__, data);
422                 break;
423         case MSR_IA32_MCG_STATUS:
424                 pr_unimpl(vcpu, "%s: MSR_IA32_MCG_STATUS 0x%llx, nop\n",
425                         __FUNCTION__, data);
426                 break;
427         case MSR_IA32_UCODE_REV:
428         case MSR_IA32_UCODE_WRITE:
429         case 0x200 ... 0x2ff: /* MTRRs */
430                 break;
431         case MSR_IA32_APICBASE:
432                 kvm_set_apic_base(vcpu, data);
433                 break;
434         case MSR_IA32_MISC_ENABLE:
435                 vcpu->ia32_misc_enable_msr = data;
436                 break;
437         default:
438                 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x\n", msr);
439                 return 1;
440         }
441         return 0;
442 }
443 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
444
445
446 /*
447  * Reads an msr value (of 'msr_index') into 'pdata'.
448  * Returns 0 on success, non-0 otherwise.
449  * Assumes vcpu_load() was already called.
450  */
451 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
452 {
453         return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
454 }
455
456 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
457 {
458         u64 data;
459
460         switch (msr) {
461         case 0xc0010010: /* SYSCFG */
462         case 0xc0010015: /* HWCR */
463         case MSR_IA32_PLATFORM_ID:
464         case MSR_IA32_P5_MC_ADDR:
465         case MSR_IA32_P5_MC_TYPE:
466         case MSR_IA32_MC0_CTL:
467         case MSR_IA32_MCG_STATUS:
468         case MSR_IA32_MCG_CAP:
469         case MSR_IA32_MC0_MISC:
470         case MSR_IA32_MC0_MISC+4:
471         case MSR_IA32_MC0_MISC+8:
472         case MSR_IA32_MC0_MISC+12:
473         case MSR_IA32_MC0_MISC+16:
474         case MSR_IA32_UCODE_REV:
475         case MSR_IA32_PERF_STATUS:
476         case MSR_IA32_EBL_CR_POWERON:
477                 /* MTRR registers */
478         case 0xfe:
479         case 0x200 ... 0x2ff:
480                 data = 0;
481                 break;
482         case 0xcd: /* fsb frequency */
483                 data = 3;
484                 break;
485         case MSR_IA32_APICBASE:
486                 data = kvm_get_apic_base(vcpu);
487                 break;
488         case MSR_IA32_MISC_ENABLE:
489                 data = vcpu->ia32_misc_enable_msr;
490                 break;
491 #ifdef CONFIG_X86_64
492         case MSR_EFER:
493                 data = vcpu->shadow_efer;
494                 break;
495 #endif
496         default:
497                 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
498                 return 1;
499         }
500         *pdata = data;
501         return 0;
502 }
503 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
504
505 /*
506  * Read or write a bunch of msrs. All parameters are kernel addresses.
507  *
508  * @return number of msrs set successfully.
509  */
510 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
511                     struct kvm_msr_entry *entries,
512                     int (*do_msr)(struct kvm_vcpu *vcpu,
513                                   unsigned index, u64 *data))
514 {
515         int i;
516
517         vcpu_load(vcpu);
518
519         for (i = 0; i < msrs->nmsrs; ++i)
520                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
521                         break;
522
523         vcpu_put(vcpu);
524
525         return i;
526 }
527
528 /*
529  * Read or write a bunch of msrs. Parameters are user addresses.
530  *
531  * @return number of msrs set successfully.
532  */
533 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
534                   int (*do_msr)(struct kvm_vcpu *vcpu,
535                                 unsigned index, u64 *data),
536                   int writeback)
537 {
538         struct kvm_msrs msrs;
539         struct kvm_msr_entry *entries;
540         int r, n;
541         unsigned size;
542
543         r = -EFAULT;
544         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
545                 goto out;
546
547         r = -E2BIG;
548         if (msrs.nmsrs >= MAX_IO_MSRS)
549                 goto out;
550
551         r = -ENOMEM;
552         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
553         entries = vmalloc(size);
554         if (!entries)
555                 goto out;
556
557         r = -EFAULT;
558         if (copy_from_user(entries, user_msrs->entries, size))
559                 goto out_free;
560
561         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
562         if (r < 0)
563                 goto out_free;
564
565         r = -EFAULT;
566         if (writeback && copy_to_user(user_msrs->entries, entries, size))
567                 goto out_free;
568
569         r = n;
570
571 out_free:
572         vfree(entries);
573 out:
574         return r;
575 }
576
577 /*
578  * Make sure that a cpu that is being hot-unplugged does not have any vcpus
579  * cached on it.
580  */
581 void decache_vcpus_on_cpu(int cpu)
582 {
583         struct kvm *vm;
584         struct kvm_vcpu *vcpu;
585         int i;
586
587         spin_lock(&kvm_lock);
588         list_for_each_entry(vm, &vm_list, vm_list)
589                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
590                         vcpu = vm->vcpus[i];
591                         if (!vcpu)
592                                 continue;
593                         /*
594                          * If the vcpu is locked, then it is running on some
595                          * other cpu and therefore it is not cached on the
596                          * cpu in question.
597                          *
598                          * If it's not locked, check the last cpu it executed
599                          * on.
600                          */
601                         if (mutex_trylock(&vcpu->mutex)) {
602                                 if (vcpu->cpu == cpu) {
603                                         kvm_x86_ops->vcpu_decache(vcpu);
604                                         vcpu->cpu = -1;
605                                 }
606                                 mutex_unlock(&vcpu->mutex);
607                         }
608                 }
609         spin_unlock(&kvm_lock);
610 }
611
612 int kvm_dev_ioctl_check_extension(long ext)
613 {
614         int r;
615
616         switch (ext) {
617         case KVM_CAP_IRQCHIP:
618         case KVM_CAP_HLT:
619         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
620         case KVM_CAP_USER_MEMORY:
621         case KVM_CAP_SET_TSS_ADDR:
622                 r = 1;
623                 break;
624         default:
625                 r = 0;
626                 break;
627         }
628         return r;
629
630 }
631
632 long kvm_arch_dev_ioctl(struct file *filp,
633                         unsigned int ioctl, unsigned long arg)
634 {
635         void __user *argp = (void __user *)arg;
636         long r;
637
638         switch (ioctl) {
639         case KVM_GET_MSR_INDEX_LIST: {
640                 struct kvm_msr_list __user *user_msr_list = argp;
641                 struct kvm_msr_list msr_list;
642                 unsigned n;
643
644                 r = -EFAULT;
645                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
646                         goto out;
647                 n = msr_list.nmsrs;
648                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
649                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
650                         goto out;
651                 r = -E2BIG;
652                 if (n < num_msrs_to_save)
653                         goto out;
654                 r = -EFAULT;
655                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
656                                  num_msrs_to_save * sizeof(u32)))
657                         goto out;
658                 if (copy_to_user(user_msr_list->indices
659                                  + num_msrs_to_save * sizeof(u32),
660                                  &emulated_msrs,
661                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
662                         goto out;
663                 r = 0;
664                 break;
665         }
666         default:
667                 r = -EINVAL;
668         }
669 out:
670         return r;
671 }
672
673 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
674 {
675         kvm_x86_ops->vcpu_load(vcpu, cpu);
676 }
677
678 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
679 {
680         kvm_x86_ops->vcpu_put(vcpu);
681         kvm_put_guest_fpu(vcpu);
682 }
683
684 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
685 {
686         u64 efer;
687         int i;
688         struct kvm_cpuid_entry *e, *entry;
689
690         rdmsrl(MSR_EFER, efer);
691         entry = NULL;
692         for (i = 0; i < vcpu->cpuid_nent; ++i) {
693                 e = &vcpu->cpuid_entries[i];
694                 if (e->function == 0x80000001) {
695                         entry = e;
696                         break;
697                 }
698         }
699         if (entry && (entry->edx & (1 << 20)) && !(efer & EFER_NX)) {
700                 entry->edx &= ~(1 << 20);
701                 printk(KERN_INFO "kvm: guest NX capability removed\n");
702         }
703 }
704
705 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
706                                     struct kvm_cpuid *cpuid,
707                                     struct kvm_cpuid_entry __user *entries)
708 {
709         int r;
710
711         r = -E2BIG;
712         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
713                 goto out;
714         r = -EFAULT;
715         if (copy_from_user(&vcpu->cpuid_entries, entries,
716                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
717                 goto out;
718         vcpu->cpuid_nent = cpuid->nent;
719         cpuid_fix_nx_cap(vcpu);
720         return 0;
721
722 out:
723         return r;
724 }
725
726 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
727                                     struct kvm_lapic_state *s)
728 {
729         vcpu_load(vcpu);
730         memcpy(s->regs, vcpu->apic->regs, sizeof *s);
731         vcpu_put(vcpu);
732
733         return 0;
734 }
735
736 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
737                                     struct kvm_lapic_state *s)
738 {
739         vcpu_load(vcpu);
740         memcpy(vcpu->apic->regs, s->regs, sizeof *s);
741         kvm_apic_post_state_restore(vcpu);
742         vcpu_put(vcpu);
743
744         return 0;
745 }
746
747 long kvm_arch_vcpu_ioctl(struct file *filp,
748                          unsigned int ioctl, unsigned long arg)
749 {
750         struct kvm_vcpu *vcpu = filp->private_data;
751         void __user *argp = (void __user *)arg;
752         int r;
753
754         switch (ioctl) {
755         case KVM_GET_LAPIC: {
756                 struct kvm_lapic_state lapic;
757
758                 memset(&lapic, 0, sizeof lapic);
759                 r = kvm_vcpu_ioctl_get_lapic(vcpu, &lapic);
760                 if (r)
761                         goto out;
762                 r = -EFAULT;
763                 if (copy_to_user(argp, &lapic, sizeof lapic))
764                         goto out;
765                 r = 0;
766                 break;
767         }
768         case KVM_SET_LAPIC: {
769                 struct kvm_lapic_state lapic;
770
771                 r = -EFAULT;
772                 if (copy_from_user(&lapic, argp, sizeof lapic))
773                         goto out;
774                 r = kvm_vcpu_ioctl_set_lapic(vcpu, &lapic);;
775                 if (r)
776                         goto out;
777                 r = 0;
778                 break;
779         }
780         case KVM_SET_CPUID: {
781                 struct kvm_cpuid __user *cpuid_arg = argp;
782                 struct kvm_cpuid cpuid;
783
784                 r = -EFAULT;
785                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
786                         goto out;
787                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
788                 if (r)
789                         goto out;
790                 break;
791         }
792         case KVM_GET_MSRS:
793                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
794                 break;
795         case KVM_SET_MSRS:
796                 r = msr_io(vcpu, argp, do_set_msr, 0);
797                 break;
798         default:
799                 r = -EINVAL;
800         }
801 out:
802         return r;
803 }
804
805 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
806 {
807         int ret;
808
809         if (addr > (unsigned int)(-3 * PAGE_SIZE))
810                 return -1;
811         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
812         return ret;
813 }
814
815 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
816                                           u32 kvm_nr_mmu_pages)
817 {
818         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
819                 return -EINVAL;
820
821         mutex_lock(&kvm->lock);
822
823         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
824         kvm->n_requested_mmu_pages = kvm_nr_mmu_pages;
825
826         mutex_unlock(&kvm->lock);
827         return 0;
828 }
829
830 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
831 {
832         return kvm->n_alloc_mmu_pages;
833 }
834
835 /*
836  * Set a new alias region.  Aliases map a portion of physical memory into
837  * another portion.  This is useful for memory windows, for example the PC
838  * VGA region.
839  */
840 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
841                                          struct kvm_memory_alias *alias)
842 {
843         int r, n;
844         struct kvm_mem_alias *p;
845
846         r = -EINVAL;
847         /* General sanity checks */
848         if (alias->memory_size & (PAGE_SIZE - 1))
849                 goto out;
850         if (alias->guest_phys_addr & (PAGE_SIZE - 1))
851                 goto out;
852         if (alias->slot >= KVM_ALIAS_SLOTS)
853                 goto out;
854         if (alias->guest_phys_addr + alias->memory_size
855             < alias->guest_phys_addr)
856                 goto out;
857         if (alias->target_phys_addr + alias->memory_size
858             < alias->target_phys_addr)
859                 goto out;
860
861         mutex_lock(&kvm->lock);
862
863         p = &kvm->aliases[alias->slot];
864         p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
865         p->npages = alias->memory_size >> PAGE_SHIFT;
866         p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
867
868         for (n = KVM_ALIAS_SLOTS; n > 0; --n)
869                 if (kvm->aliases[n - 1].npages)
870                         break;
871         kvm->naliases = n;
872
873         kvm_mmu_zap_all(kvm);
874
875         mutex_unlock(&kvm->lock);
876
877         return 0;
878
879 out:
880         return r;
881 }
882
883 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
884 {
885         int r;
886
887         r = 0;
888         switch (chip->chip_id) {
889         case KVM_IRQCHIP_PIC_MASTER:
890                 memcpy(&chip->chip.pic,
891                         &pic_irqchip(kvm)->pics[0],
892                         sizeof(struct kvm_pic_state));
893                 break;
894         case KVM_IRQCHIP_PIC_SLAVE:
895                 memcpy(&chip->chip.pic,
896                         &pic_irqchip(kvm)->pics[1],
897                         sizeof(struct kvm_pic_state));
898                 break;
899         case KVM_IRQCHIP_IOAPIC:
900                 memcpy(&chip->chip.ioapic,
901                         ioapic_irqchip(kvm),
902                         sizeof(struct kvm_ioapic_state));
903                 break;
904         default:
905                 r = -EINVAL;
906                 break;
907         }
908         return r;
909 }
910
911 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
912 {
913         int r;
914
915         r = 0;
916         switch (chip->chip_id) {
917         case KVM_IRQCHIP_PIC_MASTER:
918                 memcpy(&pic_irqchip(kvm)->pics[0],
919                         &chip->chip.pic,
920                         sizeof(struct kvm_pic_state));
921                 break;
922         case KVM_IRQCHIP_PIC_SLAVE:
923                 memcpy(&pic_irqchip(kvm)->pics[1],
924                         &chip->chip.pic,
925                         sizeof(struct kvm_pic_state));
926                 break;
927         case KVM_IRQCHIP_IOAPIC:
928                 memcpy(ioapic_irqchip(kvm),
929                         &chip->chip.ioapic,
930                         sizeof(struct kvm_ioapic_state));
931                 break;
932         default:
933                 r = -EINVAL;
934                 break;
935         }
936         kvm_pic_update_irq(pic_irqchip(kvm));
937         return r;
938 }
939
940 long kvm_arch_vm_ioctl(struct file *filp,
941                        unsigned int ioctl, unsigned long arg)
942 {
943         struct kvm *kvm = filp->private_data;
944         void __user *argp = (void __user *)arg;
945         int r = -EINVAL;
946
947         switch (ioctl) {
948         case KVM_SET_TSS_ADDR:
949                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
950                 if (r < 0)
951                         goto out;
952                 break;
953         case KVM_SET_MEMORY_REGION: {
954                 struct kvm_memory_region kvm_mem;
955                 struct kvm_userspace_memory_region kvm_userspace_mem;
956
957                 r = -EFAULT;
958                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
959                         goto out;
960                 kvm_userspace_mem.slot = kvm_mem.slot;
961                 kvm_userspace_mem.flags = kvm_mem.flags;
962                 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
963                 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
964                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
965                 if (r)
966                         goto out;
967                 break;
968         }
969         case KVM_SET_NR_MMU_PAGES:
970                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
971                 if (r)
972                         goto out;
973                 break;
974         case KVM_GET_NR_MMU_PAGES:
975                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
976                 break;
977         case KVM_SET_MEMORY_ALIAS: {
978                 struct kvm_memory_alias alias;
979
980                 r = -EFAULT;
981                 if (copy_from_user(&alias, argp, sizeof alias))
982                         goto out;
983                 r = kvm_vm_ioctl_set_memory_alias(kvm, &alias);
984                 if (r)
985                         goto out;
986                 break;
987         }
988         case KVM_CREATE_IRQCHIP:
989                 r = -ENOMEM;
990                 kvm->vpic = kvm_create_pic(kvm);
991                 if (kvm->vpic) {
992                         r = kvm_ioapic_init(kvm);
993                         if (r) {
994                                 kfree(kvm->vpic);
995                                 kvm->vpic = NULL;
996                                 goto out;
997                         }
998                 } else
999                         goto out;
1000                 break;
1001         case KVM_IRQ_LINE: {
1002                 struct kvm_irq_level irq_event;
1003
1004                 r = -EFAULT;
1005                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
1006                         goto out;
1007                 if (irqchip_in_kernel(kvm)) {
1008                         mutex_lock(&kvm->lock);
1009                         if (irq_event.irq < 16)
1010                                 kvm_pic_set_irq(pic_irqchip(kvm),
1011                                         irq_event.irq,
1012                                         irq_event.level);
1013                         kvm_ioapic_set_irq(kvm->vioapic,
1014                                         irq_event.irq,
1015                                         irq_event.level);
1016                         mutex_unlock(&kvm->lock);
1017                         r = 0;
1018                 }
1019                 break;
1020         }
1021         case KVM_GET_IRQCHIP: {
1022                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1023                 struct kvm_irqchip chip;
1024
1025                 r = -EFAULT;
1026                 if (copy_from_user(&chip, argp, sizeof chip))
1027                         goto out;
1028                 r = -ENXIO;
1029                 if (!irqchip_in_kernel(kvm))
1030                         goto out;
1031                 r = kvm_vm_ioctl_get_irqchip(kvm, &chip);
1032                 if (r)
1033                         goto out;
1034                 r = -EFAULT;
1035                 if (copy_to_user(argp, &chip, sizeof chip))
1036                         goto out;
1037                 r = 0;
1038                 break;
1039         }
1040         case KVM_SET_IRQCHIP: {
1041                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1042                 struct kvm_irqchip chip;
1043
1044                 r = -EFAULT;
1045                 if (copy_from_user(&chip, argp, sizeof chip))
1046                         goto out;
1047                 r = -ENXIO;
1048                 if (!irqchip_in_kernel(kvm))
1049                         goto out;
1050                 r = kvm_vm_ioctl_set_irqchip(kvm, &chip);
1051                 if (r)
1052                         goto out;
1053                 r = 0;
1054                 break;
1055         }
1056         default:
1057                 ;
1058         }
1059 out:
1060         return r;
1061 }
1062
1063 static void kvm_init_msr_list(void)
1064 {
1065         u32 dummy[2];
1066         unsigned i, j;
1067
1068         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
1069                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
1070                         continue;
1071                 if (j < i)
1072                         msrs_to_save[j] = msrs_to_save[i];
1073                 j++;
1074         }
1075         num_msrs_to_save = j;
1076 }
1077
1078 /*
1079  * Only apic need an MMIO device hook, so shortcut now..
1080  */
1081 static struct kvm_io_device *vcpu_find_pervcpu_dev(struct kvm_vcpu *vcpu,
1082                                                 gpa_t addr)
1083 {
1084         struct kvm_io_device *dev;
1085
1086         if (vcpu->apic) {
1087                 dev = &vcpu->apic->dev;
1088                 if (dev->in_range(dev, addr))
1089                         return dev;
1090         }
1091         return NULL;
1092 }
1093
1094
1095 static struct kvm_io_device *vcpu_find_mmio_dev(struct kvm_vcpu *vcpu,
1096                                                 gpa_t addr)
1097 {
1098         struct kvm_io_device *dev;
1099
1100         dev = vcpu_find_pervcpu_dev(vcpu, addr);
1101         if (dev == NULL)
1102                 dev = kvm_io_bus_find_dev(&vcpu->kvm->mmio_bus, addr);
1103         return dev;
1104 }
1105
1106 int emulator_read_std(unsigned long addr,
1107                              void *val,
1108                              unsigned int bytes,
1109                              struct kvm_vcpu *vcpu)
1110 {
1111         void *data = val;
1112
1113         while (bytes) {
1114                 gpa_t gpa = vcpu->mmu.gva_to_gpa(vcpu, addr);
1115                 unsigned offset = addr & (PAGE_SIZE-1);
1116                 unsigned tocopy = min(bytes, (unsigned)PAGE_SIZE - offset);
1117                 int ret;
1118
1119                 if (gpa == UNMAPPED_GVA)
1120                         return X86EMUL_PROPAGATE_FAULT;
1121                 ret = kvm_read_guest(vcpu->kvm, gpa, data, tocopy);
1122                 if (ret < 0)
1123                         return X86EMUL_UNHANDLEABLE;
1124
1125                 bytes -= tocopy;
1126                 data += tocopy;
1127                 addr += tocopy;
1128         }
1129
1130         return X86EMUL_CONTINUE;
1131 }
1132 EXPORT_SYMBOL_GPL(emulator_read_std);
1133
1134 static int emulator_write_std(unsigned long addr,
1135                               const void *val,
1136                               unsigned int bytes,
1137                               struct kvm_vcpu *vcpu)
1138 {
1139         pr_unimpl(vcpu, "emulator_write_std: addr %lx n %d\n", addr, bytes);
1140         return X86EMUL_UNHANDLEABLE;
1141 }
1142
1143 static int emulator_read_emulated(unsigned long addr,
1144                                   void *val,
1145                                   unsigned int bytes,
1146                                   struct kvm_vcpu *vcpu)
1147 {
1148         struct kvm_io_device *mmio_dev;
1149         gpa_t                 gpa;
1150
1151         if (vcpu->mmio_read_completed) {
1152                 memcpy(val, vcpu->mmio_data, bytes);
1153                 vcpu->mmio_read_completed = 0;
1154                 return X86EMUL_CONTINUE;
1155         }
1156
1157         gpa = vcpu->mmu.gva_to_gpa(vcpu, addr);
1158
1159         /* For APIC access vmexit */
1160         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1161                 goto mmio;
1162
1163         if (emulator_read_std(addr, val, bytes, vcpu)
1164                         == X86EMUL_CONTINUE)
1165                 return X86EMUL_CONTINUE;
1166         if (gpa == UNMAPPED_GVA)
1167                 return X86EMUL_PROPAGATE_FAULT;
1168
1169 mmio:
1170         /*
1171          * Is this MMIO handled locally?
1172          */
1173         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1174         if (mmio_dev) {
1175                 kvm_iodevice_read(mmio_dev, gpa, bytes, val);
1176                 return X86EMUL_CONTINUE;
1177         }
1178
1179         vcpu->mmio_needed = 1;
1180         vcpu->mmio_phys_addr = gpa;
1181         vcpu->mmio_size = bytes;
1182         vcpu->mmio_is_write = 0;
1183
1184         return X86EMUL_UNHANDLEABLE;
1185 }
1186
1187 static int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
1188                                const void *val, int bytes)
1189 {
1190         int ret;
1191
1192         ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
1193         if (ret < 0)
1194                 return 0;
1195         kvm_mmu_pte_write(vcpu, gpa, val, bytes);
1196         return 1;
1197 }
1198
1199 static int emulator_write_emulated_onepage(unsigned long addr,
1200                                            const void *val,
1201                                            unsigned int bytes,
1202                                            struct kvm_vcpu *vcpu)
1203 {
1204         struct kvm_io_device *mmio_dev;
1205         gpa_t                 gpa = vcpu->mmu.gva_to_gpa(vcpu, addr);
1206
1207         if (gpa == UNMAPPED_GVA) {
1208                 kvm_x86_ops->inject_page_fault(vcpu, addr, 2);
1209                 return X86EMUL_PROPAGATE_FAULT;
1210         }
1211
1212         /* For APIC access vmexit */
1213         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1214                 goto mmio;
1215
1216         if (emulator_write_phys(vcpu, gpa, val, bytes))
1217                 return X86EMUL_CONTINUE;
1218
1219 mmio:
1220         /*
1221          * Is this MMIO handled locally?
1222          */
1223         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1224         if (mmio_dev) {
1225                 kvm_iodevice_write(mmio_dev, gpa, bytes, val);
1226                 return X86EMUL_CONTINUE;
1227         }
1228
1229         vcpu->mmio_needed = 1;
1230         vcpu->mmio_phys_addr = gpa;
1231         vcpu->mmio_size = bytes;
1232         vcpu->mmio_is_write = 1;
1233         memcpy(vcpu->mmio_data, val, bytes);
1234
1235         return X86EMUL_CONTINUE;
1236 }
1237
1238 int emulator_write_emulated(unsigned long addr,
1239                                    const void *val,
1240                                    unsigned int bytes,
1241                                    struct kvm_vcpu *vcpu)
1242 {
1243         /* Crossing a page boundary? */
1244         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
1245                 int rc, now;
1246
1247                 now = -addr & ~PAGE_MASK;
1248                 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
1249                 if (rc != X86EMUL_CONTINUE)
1250                         return rc;
1251                 addr += now;
1252                 val += now;
1253                 bytes -= now;
1254         }
1255         return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
1256 }
1257 EXPORT_SYMBOL_GPL(emulator_write_emulated);
1258
1259 static int emulator_cmpxchg_emulated(unsigned long addr,
1260                                      const void *old,
1261                                      const void *new,
1262                                      unsigned int bytes,
1263                                      struct kvm_vcpu *vcpu)
1264 {
1265         static int reported;
1266
1267         if (!reported) {
1268                 reported = 1;
1269                 printk(KERN_WARNING "kvm: emulating exchange as write\n");
1270         }
1271         return emulator_write_emulated(addr, new, bytes, vcpu);
1272 }
1273
1274 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
1275 {
1276         return kvm_x86_ops->get_segment_base(vcpu, seg);
1277 }
1278
1279 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
1280 {
1281         return X86EMUL_CONTINUE;
1282 }
1283
1284 int emulate_clts(struct kvm_vcpu *vcpu)
1285 {
1286         kvm_x86_ops->set_cr0(vcpu, vcpu->cr0 & ~X86_CR0_TS);
1287         return X86EMUL_CONTINUE;
1288 }
1289
1290 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
1291 {
1292         struct kvm_vcpu *vcpu = ctxt->vcpu;
1293
1294         switch (dr) {
1295         case 0 ... 3:
1296                 *dest = kvm_x86_ops->get_dr(vcpu, dr);
1297                 return X86EMUL_CONTINUE;
1298         default:
1299                 pr_unimpl(vcpu, "%s: unexpected dr %u\n", __FUNCTION__, dr);
1300                 return X86EMUL_UNHANDLEABLE;
1301         }
1302 }
1303
1304 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
1305 {
1306         unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
1307         int exception;
1308
1309         kvm_x86_ops->set_dr(ctxt->vcpu, dr, value & mask, &exception);
1310         if (exception) {
1311                 /* FIXME: better handling */
1312                 return X86EMUL_UNHANDLEABLE;
1313         }
1314         return X86EMUL_CONTINUE;
1315 }
1316
1317 void kvm_report_emulation_failure(struct kvm_vcpu *vcpu, const char *context)
1318 {
1319         static int reported;
1320         u8 opcodes[4];
1321         unsigned long rip = vcpu->rip;
1322         unsigned long rip_linear;
1323
1324         rip_linear = rip + get_segment_base(vcpu, VCPU_SREG_CS);
1325
1326         if (reported)
1327                 return;
1328
1329         emulator_read_std(rip_linear, (void *)opcodes, 4, vcpu);
1330
1331         printk(KERN_ERR "emulation failed (%s) rip %lx %02x %02x %02x %02x\n",
1332                context, rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
1333         reported = 1;
1334 }
1335 EXPORT_SYMBOL_GPL(kvm_report_emulation_failure);
1336
1337 struct x86_emulate_ops emulate_ops = {
1338         .read_std            = emulator_read_std,
1339         .write_std           = emulator_write_std,
1340         .read_emulated       = emulator_read_emulated,
1341         .write_emulated      = emulator_write_emulated,
1342         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
1343 };
1344
1345 int emulate_instruction(struct kvm_vcpu *vcpu,
1346                         struct kvm_run *run,
1347                         unsigned long cr2,
1348                         u16 error_code,
1349                         int no_decode)
1350 {
1351         int r;
1352
1353         vcpu->mmio_fault_cr2 = cr2;
1354         kvm_x86_ops->cache_regs(vcpu);
1355
1356         vcpu->mmio_is_write = 0;
1357         vcpu->pio.string = 0;
1358
1359         if (!no_decode) {
1360                 int cs_db, cs_l;
1361                 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
1362
1363                 vcpu->emulate_ctxt.vcpu = vcpu;
1364                 vcpu->emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
1365                 vcpu->emulate_ctxt.cr2 = cr2;
1366                 vcpu->emulate_ctxt.mode =
1367                         (vcpu->emulate_ctxt.eflags & X86_EFLAGS_VM)
1368                         ? X86EMUL_MODE_REAL : cs_l
1369                         ? X86EMUL_MODE_PROT64 : cs_db
1370                         ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
1371
1372                 if (vcpu->emulate_ctxt.mode == X86EMUL_MODE_PROT64) {
1373                         vcpu->emulate_ctxt.cs_base = 0;
1374                         vcpu->emulate_ctxt.ds_base = 0;
1375                         vcpu->emulate_ctxt.es_base = 0;
1376                         vcpu->emulate_ctxt.ss_base = 0;
1377                 } else {
1378                         vcpu->emulate_ctxt.cs_base =
1379                                         get_segment_base(vcpu, VCPU_SREG_CS);
1380                         vcpu->emulate_ctxt.ds_base =
1381                                         get_segment_base(vcpu, VCPU_SREG_DS);
1382                         vcpu->emulate_ctxt.es_base =
1383                                         get_segment_base(vcpu, VCPU_SREG_ES);
1384                         vcpu->emulate_ctxt.ss_base =
1385                                         get_segment_base(vcpu, VCPU_SREG_SS);
1386                 }
1387
1388                 vcpu->emulate_ctxt.gs_base =
1389                                         get_segment_base(vcpu, VCPU_SREG_GS);
1390                 vcpu->emulate_ctxt.fs_base =
1391                                         get_segment_base(vcpu, VCPU_SREG_FS);
1392
1393                 r = x86_decode_insn(&vcpu->emulate_ctxt, &emulate_ops);
1394                 ++vcpu->stat.insn_emulation;
1395                 if (r)  {
1396                         ++vcpu->stat.insn_emulation_fail;
1397                         if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
1398                                 return EMULATE_DONE;
1399                         return EMULATE_FAIL;
1400                 }
1401         }
1402
1403         r = x86_emulate_insn(&vcpu->emulate_ctxt, &emulate_ops);
1404
1405         if (vcpu->pio.string)
1406                 return EMULATE_DO_MMIO;
1407
1408         if ((r || vcpu->mmio_is_write) && run) {
1409                 run->exit_reason = KVM_EXIT_MMIO;
1410                 run->mmio.phys_addr = vcpu->mmio_phys_addr;
1411                 memcpy(run->mmio.data, vcpu->mmio_data, 8);
1412                 run->mmio.len = vcpu->mmio_size;
1413                 run->mmio.is_write = vcpu->mmio_is_write;
1414         }
1415
1416         if (r) {
1417                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
1418                         return EMULATE_DONE;
1419                 if (!vcpu->mmio_needed) {
1420                         kvm_report_emulation_failure(vcpu, "mmio");
1421                         return EMULATE_FAIL;
1422                 }
1423                 return EMULATE_DO_MMIO;
1424         }
1425
1426         kvm_x86_ops->decache_regs(vcpu);
1427         kvm_x86_ops->set_rflags(vcpu, vcpu->emulate_ctxt.eflags);
1428
1429         if (vcpu->mmio_is_write) {
1430                 vcpu->mmio_needed = 0;
1431                 return EMULATE_DO_MMIO;
1432         }
1433
1434         return EMULATE_DONE;
1435 }
1436 EXPORT_SYMBOL_GPL(emulate_instruction);
1437
1438 static void free_pio_guest_pages(struct kvm_vcpu *vcpu)
1439 {
1440         int i;
1441
1442         for (i = 0; i < ARRAY_SIZE(vcpu->pio.guest_pages); ++i)
1443                 if (vcpu->pio.guest_pages[i]) {
1444                         kvm_release_page(vcpu->pio.guest_pages[i]);
1445                         vcpu->pio.guest_pages[i] = NULL;
1446                 }
1447 }
1448
1449 static int pio_copy_data(struct kvm_vcpu *vcpu)
1450 {
1451         void *p = vcpu->pio_data;
1452         void *q;
1453         unsigned bytes;
1454         int nr_pages = vcpu->pio.guest_pages[1] ? 2 : 1;
1455
1456         q = vmap(vcpu->pio.guest_pages, nr_pages, VM_READ|VM_WRITE,
1457                  PAGE_KERNEL);
1458         if (!q) {
1459                 free_pio_guest_pages(vcpu);
1460                 return -ENOMEM;
1461         }
1462         q += vcpu->pio.guest_page_offset;
1463         bytes = vcpu->pio.size * vcpu->pio.cur_count;
1464         if (vcpu->pio.in)
1465                 memcpy(q, p, bytes);
1466         else
1467                 memcpy(p, q, bytes);
1468         q -= vcpu->pio.guest_page_offset;
1469         vunmap(q);
1470         free_pio_guest_pages(vcpu);
1471         return 0;
1472 }
1473
1474 int complete_pio(struct kvm_vcpu *vcpu)
1475 {
1476         struct kvm_pio_request *io = &vcpu->pio;
1477         long delta;
1478         int r;
1479
1480         kvm_x86_ops->cache_regs(vcpu);
1481
1482         if (!io->string) {
1483                 if (io->in)
1484                         memcpy(&vcpu->regs[VCPU_REGS_RAX], vcpu->pio_data,
1485                                io->size);
1486         } else {
1487                 if (io->in) {
1488                         r = pio_copy_data(vcpu);
1489                         if (r) {
1490                                 kvm_x86_ops->cache_regs(vcpu);
1491                                 return r;
1492                         }
1493                 }
1494
1495                 delta = 1;
1496                 if (io->rep) {
1497                         delta *= io->cur_count;
1498                         /*
1499                          * The size of the register should really depend on
1500                          * current address size.
1501                          */
1502                         vcpu->regs[VCPU_REGS_RCX] -= delta;
1503                 }
1504                 if (io->down)
1505                         delta = -delta;
1506                 delta *= io->size;
1507                 if (io->in)
1508                         vcpu->regs[VCPU_REGS_RDI] += delta;
1509                 else
1510                         vcpu->regs[VCPU_REGS_RSI] += delta;
1511         }
1512
1513         kvm_x86_ops->decache_regs(vcpu);
1514
1515         io->count -= io->cur_count;
1516         io->cur_count = 0;
1517
1518         return 0;
1519 }
1520
1521 static void kernel_pio(struct kvm_io_device *pio_dev,
1522                        struct kvm_vcpu *vcpu,
1523                        void *pd)
1524 {
1525         /* TODO: String I/O for in kernel device */
1526
1527         mutex_lock(&vcpu->kvm->lock);
1528         if (vcpu->pio.in)
1529                 kvm_iodevice_read(pio_dev, vcpu->pio.port,
1530                                   vcpu->pio.size,
1531                                   pd);
1532         else
1533                 kvm_iodevice_write(pio_dev, vcpu->pio.port,
1534                                    vcpu->pio.size,
1535                                    pd);
1536         mutex_unlock(&vcpu->kvm->lock);
1537 }
1538
1539 static void pio_string_write(struct kvm_io_device *pio_dev,
1540                              struct kvm_vcpu *vcpu)
1541 {
1542         struct kvm_pio_request *io = &vcpu->pio;
1543         void *pd = vcpu->pio_data;
1544         int i;
1545
1546         mutex_lock(&vcpu->kvm->lock);
1547         for (i = 0; i < io->cur_count; i++) {
1548                 kvm_iodevice_write(pio_dev, io->port,
1549                                    io->size,
1550                                    pd);
1551                 pd += io->size;
1552         }
1553         mutex_unlock(&vcpu->kvm->lock);
1554 }
1555
1556 static struct kvm_io_device *vcpu_find_pio_dev(struct kvm_vcpu *vcpu,
1557                                                gpa_t addr)
1558 {
1559         return kvm_io_bus_find_dev(&vcpu->kvm->pio_bus, addr);
1560 }
1561
1562 int kvm_emulate_pio(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
1563                   int size, unsigned port)
1564 {
1565         struct kvm_io_device *pio_dev;
1566
1567         vcpu->run->exit_reason = KVM_EXIT_IO;
1568         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
1569         vcpu->run->io.size = vcpu->pio.size = size;
1570         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
1571         vcpu->run->io.count = vcpu->pio.count = vcpu->pio.cur_count = 1;
1572         vcpu->run->io.port = vcpu->pio.port = port;
1573         vcpu->pio.in = in;
1574         vcpu->pio.string = 0;
1575         vcpu->pio.down = 0;
1576         vcpu->pio.guest_page_offset = 0;
1577         vcpu->pio.rep = 0;
1578
1579         kvm_x86_ops->cache_regs(vcpu);
1580         memcpy(vcpu->pio_data, &vcpu->regs[VCPU_REGS_RAX], 4);
1581         kvm_x86_ops->decache_regs(vcpu);
1582
1583         kvm_x86_ops->skip_emulated_instruction(vcpu);
1584
1585         pio_dev = vcpu_find_pio_dev(vcpu, port);
1586         if (pio_dev) {
1587                 kernel_pio(pio_dev, vcpu, vcpu->pio_data);
1588                 complete_pio(vcpu);
1589                 return 1;
1590         }
1591         return 0;
1592 }
1593 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
1594
1595 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
1596                   int size, unsigned long count, int down,
1597                   gva_t address, int rep, unsigned port)
1598 {
1599         unsigned now, in_page;
1600         int i, ret = 0;
1601         int nr_pages = 1;
1602         struct page *page;
1603         struct kvm_io_device *pio_dev;
1604
1605         vcpu->run->exit_reason = KVM_EXIT_IO;
1606         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
1607         vcpu->run->io.size = vcpu->pio.size = size;
1608         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
1609         vcpu->run->io.count = vcpu->pio.count = vcpu->pio.cur_count = count;
1610         vcpu->run->io.port = vcpu->pio.port = port;
1611         vcpu->pio.in = in;
1612         vcpu->pio.string = 1;
1613         vcpu->pio.down = down;
1614         vcpu->pio.guest_page_offset = offset_in_page(address);
1615         vcpu->pio.rep = rep;
1616
1617         if (!count) {
1618                 kvm_x86_ops->skip_emulated_instruction(vcpu);
1619                 return 1;
1620         }
1621
1622         if (!down)
1623                 in_page = PAGE_SIZE - offset_in_page(address);
1624         else
1625                 in_page = offset_in_page(address) + size;
1626         now = min(count, (unsigned long)in_page / size);
1627         if (!now) {
1628                 /*
1629                  * String I/O straddles page boundary.  Pin two guest pages
1630                  * so that we satisfy atomicity constraints.  Do just one
1631                  * transaction to avoid complexity.
1632                  */
1633                 nr_pages = 2;
1634                 now = 1;
1635         }
1636         if (down) {
1637                 /*
1638                  * String I/O in reverse.  Yuck.  Kill the guest, fix later.
1639                  */
1640                 pr_unimpl(vcpu, "guest string pio down\n");
1641                 inject_gp(vcpu);
1642                 return 1;
1643         }
1644         vcpu->run->io.count = now;
1645         vcpu->pio.cur_count = now;
1646
1647         if (vcpu->pio.cur_count == vcpu->pio.count)
1648                 kvm_x86_ops->skip_emulated_instruction(vcpu);
1649
1650         for (i = 0; i < nr_pages; ++i) {
1651                 mutex_lock(&vcpu->kvm->lock);
1652                 page = gva_to_page(vcpu, address + i * PAGE_SIZE);
1653                 vcpu->pio.guest_pages[i] = page;
1654                 mutex_unlock(&vcpu->kvm->lock);
1655                 if (!page) {
1656                         inject_gp(vcpu);
1657                         free_pio_guest_pages(vcpu);
1658                         return 1;
1659                 }
1660         }
1661
1662         pio_dev = vcpu_find_pio_dev(vcpu, port);
1663         if (!vcpu->pio.in) {
1664                 /* string PIO write */
1665                 ret = pio_copy_data(vcpu);
1666                 if (ret >= 0 && pio_dev) {
1667                         pio_string_write(pio_dev, vcpu);
1668                         complete_pio(vcpu);
1669                         if (vcpu->pio.count == 0)
1670                                 ret = 1;
1671                 }
1672         } else if (pio_dev)
1673                 pr_unimpl(vcpu, "no string pio read support yet, "
1674                        "port %x size %d count %ld\n",
1675                         port, size, count);
1676
1677         return ret;
1678 }
1679 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
1680
1681 int kvm_arch_init(void *opaque)
1682 {
1683         struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
1684
1685         kvm_init_msr_list();
1686
1687         if (kvm_x86_ops) {
1688                 printk(KERN_ERR "kvm: already loaded the other module\n");
1689                 return -EEXIST;
1690         }
1691
1692         if (!ops->cpu_has_kvm_support()) {
1693                 printk(KERN_ERR "kvm: no hardware support\n");
1694                 return -EOPNOTSUPP;
1695         }
1696         if (ops->disabled_by_bios()) {
1697                 printk(KERN_ERR "kvm: disabled by bios\n");
1698                 return -EOPNOTSUPP;
1699         }
1700
1701         kvm_x86_ops = ops;
1702
1703         return 0;
1704 }
1705
1706 void kvm_arch_exit(void)
1707 {
1708         kvm_x86_ops = NULL;
1709  }
1710
1711 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
1712 {
1713         ++vcpu->stat.halt_exits;
1714         if (irqchip_in_kernel(vcpu->kvm)) {
1715                 vcpu->mp_state = VCPU_MP_STATE_HALTED;
1716                 kvm_vcpu_block(vcpu);
1717                 if (vcpu->mp_state != VCPU_MP_STATE_RUNNABLE)
1718                         return -EINTR;
1719                 return 1;
1720         } else {
1721                 vcpu->run->exit_reason = KVM_EXIT_HLT;
1722                 return 0;
1723         }
1724 }
1725 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
1726
1727 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
1728 {
1729         unsigned long nr, a0, a1, a2, a3, ret;
1730
1731         kvm_x86_ops->cache_regs(vcpu);
1732
1733         nr = vcpu->regs[VCPU_REGS_RAX];
1734         a0 = vcpu->regs[VCPU_REGS_RBX];
1735         a1 = vcpu->regs[VCPU_REGS_RCX];
1736         a2 = vcpu->regs[VCPU_REGS_RDX];
1737         a3 = vcpu->regs[VCPU_REGS_RSI];
1738
1739         if (!is_long_mode(vcpu)) {
1740                 nr &= 0xFFFFFFFF;
1741                 a0 &= 0xFFFFFFFF;
1742                 a1 &= 0xFFFFFFFF;
1743                 a2 &= 0xFFFFFFFF;
1744                 a3 &= 0xFFFFFFFF;
1745         }
1746
1747         switch (nr) {
1748         default:
1749                 ret = -KVM_ENOSYS;
1750                 break;
1751         }
1752         vcpu->regs[VCPU_REGS_RAX] = ret;
1753         kvm_x86_ops->decache_regs(vcpu);
1754         return 0;
1755 }
1756 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
1757
1758 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
1759 {
1760         char instruction[3];
1761         int ret = 0;
1762
1763         mutex_lock(&vcpu->kvm->lock);
1764
1765         /*
1766          * Blow out the MMU to ensure that no other VCPU has an active mapping
1767          * to ensure that the updated hypercall appears atomically across all
1768          * VCPUs.
1769          */
1770         kvm_mmu_zap_all(vcpu->kvm);
1771
1772         kvm_x86_ops->cache_regs(vcpu);
1773         kvm_x86_ops->patch_hypercall(vcpu, instruction);
1774         if (emulator_write_emulated(vcpu->rip, instruction, 3, vcpu)
1775             != X86EMUL_CONTINUE)
1776                 ret = -EFAULT;
1777
1778         mutex_unlock(&vcpu->kvm->lock);
1779
1780         return ret;
1781 }
1782
1783 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
1784 {
1785         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
1786 }
1787
1788 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
1789 {
1790         struct descriptor_table dt = { limit, base };
1791
1792         kvm_x86_ops->set_gdt(vcpu, &dt);
1793 }
1794
1795 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
1796 {
1797         struct descriptor_table dt = { limit, base };
1798
1799         kvm_x86_ops->set_idt(vcpu, &dt);
1800 }
1801
1802 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
1803                    unsigned long *rflags)
1804 {
1805         lmsw(vcpu, msw);
1806         *rflags = kvm_x86_ops->get_rflags(vcpu);
1807 }
1808
1809 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
1810 {
1811         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
1812         switch (cr) {
1813         case 0:
1814                 return vcpu->cr0;
1815         case 2:
1816                 return vcpu->cr2;
1817         case 3:
1818                 return vcpu->cr3;
1819         case 4:
1820                 return vcpu->cr4;
1821         default:
1822                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
1823                 return 0;
1824         }
1825 }
1826
1827 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
1828                      unsigned long *rflags)
1829 {
1830         switch (cr) {
1831         case 0:
1832                 set_cr0(vcpu, mk_cr_64(vcpu->cr0, val));
1833                 *rflags = kvm_x86_ops->get_rflags(vcpu);
1834                 break;
1835         case 2:
1836                 vcpu->cr2 = val;
1837                 break;
1838         case 3:
1839                 set_cr3(vcpu, val);
1840                 break;
1841         case 4:
1842                 set_cr4(vcpu, mk_cr_64(vcpu->cr4, val));
1843                 break;
1844         default:
1845                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
1846         }
1847 }
1848
1849 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
1850 {
1851         int i;
1852         u32 function;
1853         struct kvm_cpuid_entry *e, *best;
1854
1855         kvm_x86_ops->cache_regs(vcpu);
1856         function = vcpu->regs[VCPU_REGS_RAX];
1857         vcpu->regs[VCPU_REGS_RAX] = 0;
1858         vcpu->regs[VCPU_REGS_RBX] = 0;
1859         vcpu->regs[VCPU_REGS_RCX] = 0;
1860         vcpu->regs[VCPU_REGS_RDX] = 0;
1861         best = NULL;
1862         for (i = 0; i < vcpu->cpuid_nent; ++i) {
1863                 e = &vcpu->cpuid_entries[i];
1864                 if (e->function == function) {
1865                         best = e;
1866                         break;
1867                 }
1868                 /*
1869                  * Both basic or both extended?
1870                  */
1871                 if (((e->function ^ function) & 0x80000000) == 0)
1872                         if (!best || e->function > best->function)
1873                                 best = e;
1874         }
1875         if (best) {
1876                 vcpu->regs[VCPU_REGS_RAX] = best->eax;
1877                 vcpu->regs[VCPU_REGS_RBX] = best->ebx;
1878                 vcpu->regs[VCPU_REGS_RCX] = best->ecx;
1879                 vcpu->regs[VCPU_REGS_RDX] = best->edx;
1880         }
1881         kvm_x86_ops->decache_regs(vcpu);
1882         kvm_x86_ops->skip_emulated_instruction(vcpu);
1883 }
1884 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
1885
1886 /*
1887  * Check if userspace requested an interrupt window, and that the
1888  * interrupt window is open.
1889  *
1890  * No need to exit to userspace if we already have an interrupt queued.
1891  */
1892 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu,
1893                                           struct kvm_run *kvm_run)
1894 {
1895         return (!vcpu->irq_summary &&
1896                 kvm_run->request_interrupt_window &&
1897                 vcpu->interrupt_window_open &&
1898                 (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF));
1899 }
1900
1901 static void post_kvm_run_save(struct kvm_vcpu *vcpu,
1902                               struct kvm_run *kvm_run)
1903 {
1904         kvm_run->if_flag = (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
1905         kvm_run->cr8 = get_cr8(vcpu);
1906         kvm_run->apic_base = kvm_get_apic_base(vcpu);
1907         if (irqchip_in_kernel(vcpu->kvm))
1908                 kvm_run->ready_for_interrupt_injection = 1;
1909         else
1910                 kvm_run->ready_for_interrupt_injection =
1911                                         (vcpu->interrupt_window_open &&
1912                                          vcpu->irq_summary == 0);
1913 }
1914
1915 static int __vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
1916 {
1917         int r;
1918
1919         if (unlikely(vcpu->mp_state == VCPU_MP_STATE_SIPI_RECEIVED)) {
1920                 pr_debug("vcpu %d received sipi with vector # %x\n",
1921                        vcpu->vcpu_id, vcpu->sipi_vector);
1922                 kvm_lapic_reset(vcpu);
1923                 r = kvm_x86_ops->vcpu_reset(vcpu);
1924                 if (r)
1925                         return r;
1926                 vcpu->mp_state = VCPU_MP_STATE_RUNNABLE;
1927         }
1928
1929 preempted:
1930         if (vcpu->guest_debug.enabled)
1931                 kvm_x86_ops->guest_debug_pre(vcpu);
1932
1933 again:
1934         r = kvm_mmu_reload(vcpu);
1935         if (unlikely(r))
1936                 goto out;
1937
1938         kvm_inject_pending_timer_irqs(vcpu);
1939
1940         preempt_disable();
1941
1942         kvm_x86_ops->prepare_guest_switch(vcpu);
1943         kvm_load_guest_fpu(vcpu);
1944
1945         local_irq_disable();
1946
1947         if (signal_pending(current)) {
1948                 local_irq_enable();
1949                 preempt_enable();
1950                 r = -EINTR;
1951                 kvm_run->exit_reason = KVM_EXIT_INTR;
1952                 ++vcpu->stat.signal_exits;
1953                 goto out;
1954         }
1955
1956         if (irqchip_in_kernel(vcpu->kvm))
1957                 kvm_x86_ops->inject_pending_irq(vcpu);
1958         else if (!vcpu->mmio_read_completed)
1959                 kvm_x86_ops->inject_pending_vectors(vcpu, kvm_run);
1960
1961         vcpu->guest_mode = 1;
1962         kvm_guest_enter();
1963
1964         if (vcpu->requests)
1965                 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
1966                         kvm_x86_ops->tlb_flush(vcpu);
1967
1968         kvm_x86_ops->run(vcpu, kvm_run);
1969
1970         vcpu->guest_mode = 0;
1971         local_irq_enable();
1972
1973         ++vcpu->stat.exits;
1974
1975         /*
1976          * We must have an instruction between local_irq_enable() and
1977          * kvm_guest_exit(), so the timer interrupt isn't delayed by
1978          * the interrupt shadow.  The stat.exits increment will do nicely.
1979          * But we need to prevent reordering, hence this barrier():
1980          */
1981         barrier();
1982
1983         kvm_guest_exit();
1984
1985         preempt_enable();
1986
1987         /*
1988          * Profile KVM exit RIPs:
1989          */
1990         if (unlikely(prof_on == KVM_PROFILING)) {
1991                 kvm_x86_ops->cache_regs(vcpu);
1992                 profile_hit(KVM_PROFILING, (void *)vcpu->rip);
1993         }
1994
1995         r = kvm_x86_ops->handle_exit(kvm_run, vcpu);
1996
1997         if (r > 0) {
1998                 if (dm_request_for_irq_injection(vcpu, kvm_run)) {
1999                         r = -EINTR;
2000                         kvm_run->exit_reason = KVM_EXIT_INTR;
2001                         ++vcpu->stat.request_irq_exits;
2002                         goto out;
2003                 }
2004                 if (!need_resched())
2005                         goto again;
2006         }
2007
2008 out:
2009         if (r > 0) {
2010                 kvm_resched(vcpu);
2011                 goto preempted;
2012         }
2013
2014         post_kvm_run_save(vcpu, kvm_run);
2015
2016         return r;
2017 }
2018
2019 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2020 {
2021         int r;
2022         sigset_t sigsaved;
2023
2024         vcpu_load(vcpu);
2025
2026         if (unlikely(vcpu->mp_state == VCPU_MP_STATE_UNINITIALIZED)) {
2027                 kvm_vcpu_block(vcpu);
2028                 vcpu_put(vcpu);
2029                 return -EAGAIN;
2030         }
2031
2032         if (vcpu->sigset_active)
2033                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
2034
2035         /* re-sync apic's tpr */
2036         if (!irqchip_in_kernel(vcpu->kvm))
2037                 set_cr8(vcpu, kvm_run->cr8);
2038
2039         if (vcpu->pio.cur_count) {
2040                 r = complete_pio(vcpu);
2041                 if (r)
2042                         goto out;
2043         }
2044 #if CONFIG_HAS_IOMEM
2045         if (vcpu->mmio_needed) {
2046                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
2047                 vcpu->mmio_read_completed = 1;
2048                 vcpu->mmio_needed = 0;
2049                 r = emulate_instruction(vcpu, kvm_run,
2050                                         vcpu->mmio_fault_cr2, 0, 1);
2051                 if (r == EMULATE_DO_MMIO) {
2052                         /*
2053                          * Read-modify-write.  Back to userspace.
2054                          */
2055                         r = 0;
2056                         goto out;
2057                 }
2058         }
2059 #endif
2060         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL) {
2061                 kvm_x86_ops->cache_regs(vcpu);
2062                 vcpu->regs[VCPU_REGS_RAX] = kvm_run->hypercall.ret;
2063                 kvm_x86_ops->decache_regs(vcpu);
2064         }
2065
2066         r = __vcpu_run(vcpu, kvm_run);
2067
2068 out:
2069         if (vcpu->sigset_active)
2070                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
2071
2072         vcpu_put(vcpu);
2073         return r;
2074 }
2075
2076 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
2077 {
2078         vcpu_load(vcpu);
2079
2080         kvm_x86_ops->cache_regs(vcpu);
2081
2082         regs->rax = vcpu->regs[VCPU_REGS_RAX];
2083         regs->rbx = vcpu->regs[VCPU_REGS_RBX];
2084         regs->rcx = vcpu->regs[VCPU_REGS_RCX];
2085         regs->rdx = vcpu->regs[VCPU_REGS_RDX];
2086         regs->rsi = vcpu->regs[VCPU_REGS_RSI];
2087         regs->rdi = vcpu->regs[VCPU_REGS_RDI];
2088         regs->rsp = vcpu->regs[VCPU_REGS_RSP];
2089         regs->rbp = vcpu->regs[VCPU_REGS_RBP];
2090 #ifdef CONFIG_X86_64
2091         regs->r8 = vcpu->regs[VCPU_REGS_R8];
2092         regs->r9 = vcpu->regs[VCPU_REGS_R9];
2093         regs->r10 = vcpu->regs[VCPU_REGS_R10];
2094         regs->r11 = vcpu->regs[VCPU_REGS_R11];
2095         regs->r12 = vcpu->regs[VCPU_REGS_R12];
2096         regs->r13 = vcpu->regs[VCPU_REGS_R13];
2097         regs->r14 = vcpu->regs[VCPU_REGS_R14];
2098         regs->r15 = vcpu->regs[VCPU_REGS_R15];
2099 #endif
2100
2101         regs->rip = vcpu->rip;
2102         regs->rflags = kvm_x86_ops->get_rflags(vcpu);
2103
2104         /*
2105          * Don't leak debug flags in case they were set for guest debugging
2106          */
2107         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
2108                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
2109
2110         vcpu_put(vcpu);
2111
2112         return 0;
2113 }
2114
2115 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
2116 {
2117         vcpu_load(vcpu);
2118
2119         vcpu->regs[VCPU_REGS_RAX] = regs->rax;
2120         vcpu->regs[VCPU_REGS_RBX] = regs->rbx;
2121         vcpu->regs[VCPU_REGS_RCX] = regs->rcx;
2122         vcpu->regs[VCPU_REGS_RDX] = regs->rdx;
2123         vcpu->regs[VCPU_REGS_RSI] = regs->rsi;
2124         vcpu->regs[VCPU_REGS_RDI] = regs->rdi;
2125         vcpu->regs[VCPU_REGS_RSP] = regs->rsp;
2126         vcpu->regs[VCPU_REGS_RBP] = regs->rbp;
2127 #ifdef CONFIG_X86_64
2128         vcpu->regs[VCPU_REGS_R8] = regs->r8;
2129         vcpu->regs[VCPU_REGS_R9] = regs->r9;
2130         vcpu->regs[VCPU_REGS_R10] = regs->r10;
2131         vcpu->regs[VCPU_REGS_R11] = regs->r11;
2132         vcpu->regs[VCPU_REGS_R12] = regs->r12;
2133         vcpu->regs[VCPU_REGS_R13] = regs->r13;
2134         vcpu->regs[VCPU_REGS_R14] = regs->r14;
2135         vcpu->regs[VCPU_REGS_R15] = regs->r15;
2136 #endif
2137
2138         vcpu->rip = regs->rip;
2139         kvm_x86_ops->set_rflags(vcpu, regs->rflags);
2140
2141         kvm_x86_ops->decache_regs(vcpu);
2142
2143         vcpu_put(vcpu);
2144
2145         return 0;
2146 }
2147
2148 static void get_segment(struct kvm_vcpu *vcpu,
2149                         struct kvm_segment *var, int seg)
2150 {
2151         return kvm_x86_ops->get_segment(vcpu, var, seg);
2152 }
2153
2154 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
2155 {
2156         struct kvm_segment cs;
2157
2158         get_segment(vcpu, &cs, VCPU_SREG_CS);
2159         *db = cs.db;
2160         *l = cs.l;
2161 }
2162 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
2163
2164 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
2165                                   struct kvm_sregs *sregs)
2166 {
2167         struct descriptor_table dt;
2168         int pending_vec;
2169
2170         vcpu_load(vcpu);
2171
2172         get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
2173         get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
2174         get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
2175         get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
2176         get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
2177         get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
2178
2179         get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
2180         get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
2181
2182         kvm_x86_ops->get_idt(vcpu, &dt);
2183         sregs->idt.limit = dt.limit;
2184         sregs->idt.base = dt.base;
2185         kvm_x86_ops->get_gdt(vcpu, &dt);
2186         sregs->gdt.limit = dt.limit;
2187         sregs->gdt.base = dt.base;
2188
2189         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2190         sregs->cr0 = vcpu->cr0;
2191         sregs->cr2 = vcpu->cr2;
2192         sregs->cr3 = vcpu->cr3;
2193         sregs->cr4 = vcpu->cr4;
2194         sregs->cr8 = get_cr8(vcpu);
2195         sregs->efer = vcpu->shadow_efer;
2196         sregs->apic_base = kvm_get_apic_base(vcpu);
2197
2198         if (irqchip_in_kernel(vcpu->kvm)) {
2199                 memset(sregs->interrupt_bitmap, 0,
2200                        sizeof sregs->interrupt_bitmap);
2201                 pending_vec = kvm_x86_ops->get_irq(vcpu);
2202                 if (pending_vec >= 0)
2203                         set_bit(pending_vec,
2204                                 (unsigned long *)sregs->interrupt_bitmap);
2205         } else
2206                 memcpy(sregs->interrupt_bitmap, vcpu->irq_pending,
2207                        sizeof sregs->interrupt_bitmap);
2208
2209         vcpu_put(vcpu);
2210
2211         return 0;
2212 }
2213
2214 static void set_segment(struct kvm_vcpu *vcpu,
2215                         struct kvm_segment *var, int seg)
2216 {
2217         return kvm_x86_ops->set_segment(vcpu, var, seg);
2218 }
2219
2220 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
2221                                   struct kvm_sregs *sregs)
2222 {
2223         int mmu_reset_needed = 0;
2224         int i, pending_vec, max_bits;
2225         struct descriptor_table dt;
2226
2227         vcpu_load(vcpu);
2228
2229         dt.limit = sregs->idt.limit;
2230         dt.base = sregs->idt.base;
2231         kvm_x86_ops->set_idt(vcpu, &dt);
2232         dt.limit = sregs->gdt.limit;
2233         dt.base = sregs->gdt.base;
2234         kvm_x86_ops->set_gdt(vcpu, &dt);
2235
2236         vcpu->cr2 = sregs->cr2;
2237         mmu_reset_needed |= vcpu->cr3 != sregs->cr3;
2238         vcpu->cr3 = sregs->cr3;
2239
2240         set_cr8(vcpu, sregs->cr8);
2241
2242         mmu_reset_needed |= vcpu->shadow_efer != sregs->efer;
2243 #ifdef CONFIG_X86_64
2244         kvm_x86_ops->set_efer(vcpu, sregs->efer);
2245 #endif
2246         kvm_set_apic_base(vcpu, sregs->apic_base);
2247
2248         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2249
2250         mmu_reset_needed |= vcpu->cr0 != sregs->cr0;
2251         vcpu->cr0 = sregs->cr0;
2252         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
2253
2254         mmu_reset_needed |= vcpu->cr4 != sregs->cr4;
2255         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
2256         if (!is_long_mode(vcpu) && is_pae(vcpu))
2257                 load_pdptrs(vcpu, vcpu->cr3);
2258
2259         if (mmu_reset_needed)
2260                 kvm_mmu_reset_context(vcpu);
2261
2262         if (!irqchip_in_kernel(vcpu->kvm)) {
2263                 memcpy(vcpu->irq_pending, sregs->interrupt_bitmap,
2264                        sizeof vcpu->irq_pending);
2265                 vcpu->irq_summary = 0;
2266                 for (i = 0; i < ARRAY_SIZE(vcpu->irq_pending); ++i)
2267                         if (vcpu->irq_pending[i])
2268                                 __set_bit(i, &vcpu->irq_summary);
2269         } else {
2270                 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
2271                 pending_vec = find_first_bit(
2272                         (const unsigned long *)sregs->interrupt_bitmap,
2273                         max_bits);
2274                 /* Only pending external irq is handled here */
2275                 if (pending_vec < max_bits) {
2276                         kvm_x86_ops->set_irq(vcpu, pending_vec);
2277                         pr_debug("Set back pending irq %d\n",
2278                                  pending_vec);
2279                 }
2280         }
2281
2282         set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
2283         set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
2284         set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
2285         set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
2286         set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
2287         set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
2288
2289         set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
2290         set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
2291
2292         vcpu_put(vcpu);
2293
2294         return 0;
2295 }
2296
2297 int kvm_arch_vcpu_ioctl_debug_guest(struct kvm_vcpu *vcpu,
2298                                     struct kvm_debug_guest *dbg)
2299 {
2300         int r;
2301
2302         vcpu_load(vcpu);
2303
2304         r = kvm_x86_ops->set_guest_debug(vcpu, dbg);
2305
2306         vcpu_put(vcpu);
2307
2308         return r;
2309 }
2310
2311 /*
2312  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
2313  * we have asm/x86/processor.h
2314  */
2315 struct fxsave {
2316         u16     cwd;
2317         u16     swd;
2318         u16     twd;
2319         u16     fop;
2320         u64     rip;
2321         u64     rdp;
2322         u32     mxcsr;
2323         u32     mxcsr_mask;
2324         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
2325 #ifdef CONFIG_X86_64
2326         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
2327 #else
2328         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
2329 #endif
2330 };
2331
2332 /*
2333  * Translate a guest virtual address to a guest physical address.
2334  */
2335 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
2336                                     struct kvm_translation *tr)
2337 {
2338         unsigned long vaddr = tr->linear_address;
2339         gpa_t gpa;
2340
2341         vcpu_load(vcpu);
2342         mutex_lock(&vcpu->kvm->lock);
2343         gpa = vcpu->mmu.gva_to_gpa(vcpu, vaddr);
2344         tr->physical_address = gpa;
2345         tr->valid = gpa != UNMAPPED_GVA;
2346         tr->writeable = 1;
2347         tr->usermode = 0;
2348         mutex_unlock(&vcpu->kvm->lock);
2349         vcpu_put(vcpu);
2350
2351         return 0;
2352 }
2353
2354 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2355 {
2356         struct fxsave *fxsave = (struct fxsave *)&vcpu->guest_fx_image;
2357
2358         vcpu_load(vcpu);
2359
2360         memcpy(fpu->fpr, fxsave->st_space, 128);
2361         fpu->fcw = fxsave->cwd;
2362         fpu->fsw = fxsave->swd;
2363         fpu->ftwx = fxsave->twd;
2364         fpu->last_opcode = fxsave->fop;
2365         fpu->last_ip = fxsave->rip;
2366         fpu->last_dp = fxsave->rdp;
2367         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
2368
2369         vcpu_put(vcpu);
2370
2371         return 0;
2372 }
2373
2374 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2375 {
2376         struct fxsave *fxsave = (struct fxsave *)&vcpu->guest_fx_image;
2377
2378         vcpu_load(vcpu);
2379
2380         memcpy(fxsave->st_space, fpu->fpr, 128);
2381         fxsave->cwd = fpu->fcw;
2382         fxsave->swd = fpu->fsw;
2383         fxsave->twd = fpu->ftwx;
2384         fxsave->fop = fpu->last_opcode;
2385         fxsave->rip = fpu->last_ip;
2386         fxsave->rdp = fpu->last_dp;
2387         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
2388
2389         vcpu_put(vcpu);
2390
2391         return 0;
2392 }
2393
2394 void fx_init(struct kvm_vcpu *vcpu)
2395 {
2396         unsigned after_mxcsr_mask;
2397
2398         /* Initialize guest FPU by resetting ours and saving into guest's */
2399         preempt_disable();
2400         fx_save(&vcpu->host_fx_image);
2401         fpu_init();
2402         fx_save(&vcpu->guest_fx_image);
2403         fx_restore(&vcpu->host_fx_image);
2404         preempt_enable();
2405
2406         vcpu->cr0 |= X86_CR0_ET;
2407         after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
2408         vcpu->guest_fx_image.mxcsr = 0x1f80;
2409         memset((void *)&vcpu->guest_fx_image + after_mxcsr_mask,
2410                0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
2411 }
2412 EXPORT_SYMBOL_GPL(fx_init);
2413
2414 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
2415 {
2416         if (!vcpu->fpu_active || vcpu->guest_fpu_loaded)
2417                 return;
2418
2419         vcpu->guest_fpu_loaded = 1;
2420         fx_save(&vcpu->host_fx_image);
2421         fx_restore(&vcpu->guest_fx_image);
2422 }
2423 EXPORT_SYMBOL_GPL(kvm_load_guest_fpu);
2424
2425 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
2426 {
2427         if (!vcpu->guest_fpu_loaded)
2428                 return;
2429
2430         vcpu->guest_fpu_loaded = 0;
2431         fx_save(&vcpu->guest_fx_image);
2432         fx_restore(&vcpu->host_fx_image);
2433         ++vcpu->stat.fpu_reload;
2434 }
2435 EXPORT_SYMBOL_GPL(kvm_put_guest_fpu);
2436
2437 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
2438 {
2439         kvm_x86_ops->vcpu_free(vcpu);
2440 }
2441
2442 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
2443                                                 unsigned int id)
2444 {
2445         int r;
2446         struct kvm_vcpu *vcpu = kvm_x86_ops->vcpu_create(kvm, id);
2447
2448         if (IS_ERR(vcpu)) {
2449                 r = -ENOMEM;
2450                 goto fail;
2451         }
2452
2453         /* We do fxsave: this must be aligned. */
2454         BUG_ON((unsigned long)&vcpu->host_fx_image & 0xF);
2455
2456         vcpu_load(vcpu);
2457         r = kvm_arch_vcpu_reset(vcpu);
2458         if (r == 0)
2459                 r = kvm_mmu_setup(vcpu);
2460         vcpu_put(vcpu);
2461         if (r < 0)
2462                 goto free_vcpu;
2463
2464         return vcpu;
2465 free_vcpu:
2466         kvm_x86_ops->vcpu_free(vcpu);
2467 fail:
2468         return ERR_PTR(r);
2469 }
2470
2471 void kvm_arch_vcpu_destory(struct kvm_vcpu *vcpu)
2472 {
2473         vcpu_load(vcpu);
2474         kvm_mmu_unload(vcpu);
2475         vcpu_put(vcpu);
2476
2477         kvm_x86_ops->vcpu_free(vcpu);
2478 }
2479
2480 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
2481 {
2482         return kvm_x86_ops->vcpu_reset(vcpu);
2483 }
2484
2485 void kvm_arch_hardware_enable(void *garbage)
2486 {
2487         kvm_x86_ops->hardware_enable(garbage);
2488 }
2489
2490 void kvm_arch_hardware_disable(void *garbage)
2491 {
2492         kvm_x86_ops->hardware_disable(garbage);
2493 }
2494
2495 int kvm_arch_hardware_setup(void)
2496 {
2497         return kvm_x86_ops->hardware_setup();
2498 }
2499
2500 void kvm_arch_hardware_unsetup(void)
2501 {
2502         kvm_x86_ops->hardware_unsetup();
2503 }
2504
2505 void kvm_arch_check_processor_compat(void *rtn)
2506 {
2507         kvm_x86_ops->check_processor_compatibility(rtn);
2508 }
2509
2510 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
2511 {
2512         struct page *page;
2513         struct kvm *kvm;
2514         int r;
2515
2516         BUG_ON(vcpu->kvm == NULL);
2517         kvm = vcpu->kvm;
2518
2519         vcpu->mmu.root_hpa = INVALID_PAGE;
2520         if (!irqchip_in_kernel(kvm) || vcpu->vcpu_id == 0)
2521                 vcpu->mp_state = VCPU_MP_STATE_RUNNABLE;
2522         else
2523                 vcpu->mp_state = VCPU_MP_STATE_UNINITIALIZED;
2524
2525         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2526         if (!page) {
2527                 r = -ENOMEM;
2528                 goto fail;
2529         }
2530         vcpu->pio_data = page_address(page);
2531
2532         r = kvm_mmu_create(vcpu);
2533         if (r < 0)
2534                 goto fail_free_pio_data;
2535
2536         if (irqchip_in_kernel(kvm)) {
2537                 r = kvm_create_lapic(vcpu);
2538                 if (r < 0)
2539                         goto fail_mmu_destroy;
2540         }
2541
2542         return 0;
2543
2544 fail_mmu_destroy:
2545         kvm_mmu_destroy(vcpu);
2546 fail_free_pio_data:
2547         free_page((unsigned long)vcpu->pio_data);
2548 fail:
2549         return r;
2550 }
2551
2552 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
2553 {
2554         kvm_free_lapic(vcpu);
2555         kvm_mmu_destroy(vcpu);
2556         free_page((unsigned long)vcpu->pio_data);
2557 }
2558
2559 struct  kvm *kvm_arch_create_vm(void)
2560 {
2561         struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
2562
2563         if (!kvm)
2564                 return ERR_PTR(-ENOMEM);
2565
2566         INIT_LIST_HEAD(&kvm->active_mmu_pages);
2567
2568         return kvm;
2569 }
2570
2571 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
2572 {
2573         vcpu_load(vcpu);
2574         kvm_mmu_unload(vcpu);
2575         vcpu_put(vcpu);
2576 }
2577
2578 static void kvm_free_vcpus(struct kvm *kvm)
2579 {
2580         unsigned int i;
2581
2582         /*
2583          * Unpin any mmu pages first.
2584          */
2585         for (i = 0; i < KVM_MAX_VCPUS; ++i)
2586                 if (kvm->vcpus[i])
2587                         kvm_unload_vcpu_mmu(kvm->vcpus[i]);
2588         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
2589                 if (kvm->vcpus[i]) {
2590                         kvm_arch_vcpu_free(kvm->vcpus[i]);
2591                         kvm->vcpus[i] = NULL;
2592                 }
2593         }
2594
2595 }
2596
2597 void kvm_arch_destroy_vm(struct kvm *kvm)
2598 {
2599         kfree(kvm->vpic);
2600         kfree(kvm->vioapic);
2601         kvm_free_vcpus(kvm);
2602         kvm_free_physmem(kvm);
2603         kfree(kvm);
2604 }