]> pilppa.org Git - linux-2.6-omap-h63xx.git/blob - arch/x86/kvm/x86.c
KVM: Make the supported cpuid list a host property rather than a vm property
[linux-2.6-omap-h63xx.git] / arch / x86 / kvm / x86.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * derived from drivers/kvm/kvm_main.c
5  *
6  * Copyright (C) 2006 Qumranet, Inc.
7  *
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 <linux/kvm_host.h>
18 #include "segment_descriptor.h"
19 #include "irq.h"
20 #include "mmu.h"
21
22 #include <linux/kvm.h>
23 #include <linux/fs.h>
24 #include <linux/vmalloc.h>
25 #include <linux/module.h>
26 #include <linux/mman.h>
27 #include <linux/highmem.h>
28
29 #include <asm/uaccess.h>
30 #include <asm/msr.h>
31
32 #define MAX_IO_MSRS 256
33 #define CR0_RESERVED_BITS                                               \
34         (~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
35                           | X86_CR0_ET | X86_CR0_NE | X86_CR0_WP | X86_CR0_AM \
36                           | X86_CR0_NW | X86_CR0_CD | X86_CR0_PG))
37 #define CR4_RESERVED_BITS                                               \
38         (~(unsigned long)(X86_CR4_VME | X86_CR4_PVI | X86_CR4_TSD | X86_CR4_DE\
39                           | X86_CR4_PSE | X86_CR4_PAE | X86_CR4_MCE     \
40                           | X86_CR4_PGE | X86_CR4_PCE | X86_CR4_OSFXSR  \
41                           | X86_CR4_OSXMMEXCPT | X86_CR4_VMXE))
42
43 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
44 #define EFER_RESERVED_BITS 0xfffffffffffff2fe
45
46 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
47 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
48
49 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
50                                     struct kvm_cpuid_entry2 __user *entries);
51
52 struct kvm_x86_ops *kvm_x86_ops;
53
54 struct kvm_stats_debugfs_item debugfs_entries[] = {
55         { "pf_fixed", VCPU_STAT(pf_fixed) },
56         { "pf_guest", VCPU_STAT(pf_guest) },
57         { "tlb_flush", VCPU_STAT(tlb_flush) },
58         { "invlpg", VCPU_STAT(invlpg) },
59         { "exits", VCPU_STAT(exits) },
60         { "io_exits", VCPU_STAT(io_exits) },
61         { "mmio_exits", VCPU_STAT(mmio_exits) },
62         { "signal_exits", VCPU_STAT(signal_exits) },
63         { "irq_window", VCPU_STAT(irq_window_exits) },
64         { "halt_exits", VCPU_STAT(halt_exits) },
65         { "halt_wakeup", VCPU_STAT(halt_wakeup) },
66         { "request_irq", VCPU_STAT(request_irq_exits) },
67         { "irq_exits", VCPU_STAT(irq_exits) },
68         { "host_state_reload", VCPU_STAT(host_state_reload) },
69         { "efer_reload", VCPU_STAT(efer_reload) },
70         { "fpu_reload", VCPU_STAT(fpu_reload) },
71         { "insn_emulation", VCPU_STAT(insn_emulation) },
72         { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
73         { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
74         { "mmu_pte_write", VM_STAT(mmu_pte_write) },
75         { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
76         { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
77         { "mmu_flooded", VM_STAT(mmu_flooded) },
78         { "mmu_recycled", VM_STAT(mmu_recycled) },
79         { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
80         { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
81         { NULL }
82 };
83
84
85 unsigned long segment_base(u16 selector)
86 {
87         struct descriptor_table gdt;
88         struct segment_descriptor *d;
89         unsigned long table_base;
90         unsigned long v;
91
92         if (selector == 0)
93                 return 0;
94
95         asm("sgdt %0" : "=m"(gdt));
96         table_base = gdt.base;
97
98         if (selector & 4) {           /* from ldt */
99                 u16 ldt_selector;
100
101                 asm("sldt %0" : "=g"(ldt_selector));
102                 table_base = segment_base(ldt_selector);
103         }
104         d = (struct segment_descriptor *)(table_base + (selector & ~7));
105         v = d->base_low | ((unsigned long)d->base_mid << 16) |
106                 ((unsigned long)d->base_high << 24);
107 #ifdef CONFIG_X86_64
108         if (d->system == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
109                 v |= ((unsigned long) \
110                       ((struct segment_descriptor_64 *)d)->base_higher) << 32;
111 #endif
112         return v;
113 }
114 EXPORT_SYMBOL_GPL(segment_base);
115
116 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
117 {
118         if (irqchip_in_kernel(vcpu->kvm))
119                 return vcpu->arch.apic_base;
120         else
121                 return vcpu->arch.apic_base;
122 }
123 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
124
125 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
126 {
127         /* TODO: reserve bits check */
128         if (irqchip_in_kernel(vcpu->kvm))
129                 kvm_lapic_set_base(vcpu, data);
130         else
131                 vcpu->arch.apic_base = data;
132 }
133 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
134
135 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
136 {
137         WARN_ON(vcpu->arch.exception.pending);
138         vcpu->arch.exception.pending = true;
139         vcpu->arch.exception.has_error_code = false;
140         vcpu->arch.exception.nr = nr;
141 }
142 EXPORT_SYMBOL_GPL(kvm_queue_exception);
143
144 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, unsigned long addr,
145                            u32 error_code)
146 {
147         ++vcpu->stat.pf_guest;
148         if (vcpu->arch.exception.pending && vcpu->arch.exception.nr == PF_VECTOR) {
149                 printk(KERN_DEBUG "kvm: inject_page_fault:"
150                        " double fault 0x%lx\n", addr);
151                 vcpu->arch.exception.nr = DF_VECTOR;
152                 vcpu->arch.exception.error_code = 0;
153                 return;
154         }
155         vcpu->arch.cr2 = addr;
156         kvm_queue_exception_e(vcpu, PF_VECTOR, error_code);
157 }
158
159 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
160 {
161         WARN_ON(vcpu->arch.exception.pending);
162         vcpu->arch.exception.pending = true;
163         vcpu->arch.exception.has_error_code = true;
164         vcpu->arch.exception.nr = nr;
165         vcpu->arch.exception.error_code = error_code;
166 }
167 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
168
169 static void __queue_exception(struct kvm_vcpu *vcpu)
170 {
171         kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
172                                      vcpu->arch.exception.has_error_code,
173                                      vcpu->arch.exception.error_code);
174 }
175
176 /*
177  * Load the pae pdptrs.  Return true is they are all valid.
178  */
179 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
180 {
181         gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
182         unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
183         int i;
184         int ret;
185         u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
186
187         down_read(&current->mm->mmap_sem);
188         ret = kvm_read_guest_page(vcpu->kvm, pdpt_gfn, pdpte,
189                                   offset * sizeof(u64), sizeof(pdpte));
190         if (ret < 0) {
191                 ret = 0;
192                 goto out;
193         }
194         for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
195                 if ((pdpte[i] & 1) && (pdpte[i] & 0xfffffff0000001e6ull)) {
196                         ret = 0;
197                         goto out;
198                 }
199         }
200         ret = 1;
201
202         memcpy(vcpu->arch.pdptrs, pdpte, sizeof(vcpu->arch.pdptrs));
203 out:
204         up_read(&current->mm->mmap_sem);
205
206         return ret;
207 }
208
209 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
210 {
211         u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
212         bool changed = true;
213         int r;
214
215         if (is_long_mode(vcpu) || !is_pae(vcpu))
216                 return false;
217
218         down_read(&current->mm->mmap_sem);
219         r = kvm_read_guest(vcpu->kvm, vcpu->arch.cr3 & ~31u, pdpte, sizeof(pdpte));
220         if (r < 0)
221                 goto out;
222         changed = memcmp(pdpte, vcpu->arch.pdptrs, sizeof(pdpte)) != 0;
223 out:
224         up_read(&current->mm->mmap_sem);
225
226         return changed;
227 }
228
229 void set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
230 {
231         if (cr0 & CR0_RESERVED_BITS) {
232                 printk(KERN_DEBUG "set_cr0: 0x%lx #GP, reserved bits 0x%lx\n",
233                        cr0, vcpu->arch.cr0);
234                 kvm_inject_gp(vcpu, 0);
235                 return;
236         }
237
238         if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD)) {
239                 printk(KERN_DEBUG "set_cr0: #GP, CD == 0 && NW == 1\n");
240                 kvm_inject_gp(vcpu, 0);
241                 return;
242         }
243
244         if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE)) {
245                 printk(KERN_DEBUG "set_cr0: #GP, set PG flag "
246                        "and a clear PE flag\n");
247                 kvm_inject_gp(vcpu, 0);
248                 return;
249         }
250
251         if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
252 #ifdef CONFIG_X86_64
253                 if ((vcpu->arch.shadow_efer & EFER_LME)) {
254                         int cs_db, cs_l;
255
256                         if (!is_pae(vcpu)) {
257                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
258                                        "in long mode while PAE is disabled\n");
259                                 kvm_inject_gp(vcpu, 0);
260                                 return;
261                         }
262                         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
263                         if (cs_l) {
264                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
265                                        "in long mode while CS.L == 1\n");
266                                 kvm_inject_gp(vcpu, 0);
267                                 return;
268
269                         }
270                 } else
271 #endif
272                 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.cr3)) {
273                         printk(KERN_DEBUG "set_cr0: #GP, pdptrs "
274                                "reserved bits\n");
275                         kvm_inject_gp(vcpu, 0);
276                         return;
277                 }
278
279         }
280
281         kvm_x86_ops->set_cr0(vcpu, cr0);
282         vcpu->arch.cr0 = cr0;
283
284         kvm_mmu_reset_context(vcpu);
285         return;
286 }
287 EXPORT_SYMBOL_GPL(set_cr0);
288
289 void lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
290 {
291         set_cr0(vcpu, (vcpu->arch.cr0 & ~0x0ful) | (msw & 0x0f));
292 }
293 EXPORT_SYMBOL_GPL(lmsw);
294
295 void set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
296 {
297         if (cr4 & CR4_RESERVED_BITS) {
298                 printk(KERN_DEBUG "set_cr4: #GP, reserved bits\n");
299                 kvm_inject_gp(vcpu, 0);
300                 return;
301         }
302
303         if (is_long_mode(vcpu)) {
304                 if (!(cr4 & X86_CR4_PAE)) {
305                         printk(KERN_DEBUG "set_cr4: #GP, clearing PAE while "
306                                "in long mode\n");
307                         kvm_inject_gp(vcpu, 0);
308                         return;
309                 }
310         } else if (is_paging(vcpu) && !is_pae(vcpu) && (cr4 & X86_CR4_PAE)
311                    && !load_pdptrs(vcpu, vcpu->arch.cr3)) {
312                 printk(KERN_DEBUG "set_cr4: #GP, pdptrs reserved bits\n");
313                 kvm_inject_gp(vcpu, 0);
314                 return;
315         }
316
317         if (cr4 & X86_CR4_VMXE) {
318                 printk(KERN_DEBUG "set_cr4: #GP, setting VMXE\n");
319                 kvm_inject_gp(vcpu, 0);
320                 return;
321         }
322         kvm_x86_ops->set_cr4(vcpu, cr4);
323         vcpu->arch.cr4 = cr4;
324         kvm_mmu_reset_context(vcpu);
325 }
326 EXPORT_SYMBOL_GPL(set_cr4);
327
328 void set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
329 {
330         if (cr3 == vcpu->arch.cr3 && !pdptrs_changed(vcpu)) {
331                 kvm_mmu_flush_tlb(vcpu);
332                 return;
333         }
334
335         if (is_long_mode(vcpu)) {
336                 if (cr3 & CR3_L_MODE_RESERVED_BITS) {
337                         printk(KERN_DEBUG "set_cr3: #GP, reserved bits\n");
338                         kvm_inject_gp(vcpu, 0);
339                         return;
340                 }
341         } else {
342                 if (is_pae(vcpu)) {
343                         if (cr3 & CR3_PAE_RESERVED_BITS) {
344                                 printk(KERN_DEBUG
345                                        "set_cr3: #GP, reserved bits\n");
346                                 kvm_inject_gp(vcpu, 0);
347                                 return;
348                         }
349                         if (is_paging(vcpu) && !load_pdptrs(vcpu, cr3)) {
350                                 printk(KERN_DEBUG "set_cr3: #GP, pdptrs "
351                                        "reserved bits\n");
352                                 kvm_inject_gp(vcpu, 0);
353                                 return;
354                         }
355                 }
356                 /*
357                  * We don't check reserved bits in nonpae mode, because
358                  * this isn't enforced, and VMware depends on this.
359                  */
360         }
361
362         down_read(&current->mm->mmap_sem);
363         /*
364          * Does the new cr3 value map to physical memory? (Note, we
365          * catch an invalid cr3 even in real-mode, because it would
366          * cause trouble later on when we turn on paging anyway.)
367          *
368          * A real CPU would silently accept an invalid cr3 and would
369          * attempt to use it - with largely undefined (and often hard
370          * to debug) behavior on the guest side.
371          */
372         if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
373                 kvm_inject_gp(vcpu, 0);
374         else {
375                 vcpu->arch.cr3 = cr3;
376                 vcpu->arch.mmu.new_cr3(vcpu);
377         }
378         up_read(&current->mm->mmap_sem);
379 }
380 EXPORT_SYMBOL_GPL(set_cr3);
381
382 void set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
383 {
384         if (cr8 & CR8_RESERVED_BITS) {
385                 printk(KERN_DEBUG "set_cr8: #GP, reserved bits 0x%lx\n", cr8);
386                 kvm_inject_gp(vcpu, 0);
387                 return;
388         }
389         if (irqchip_in_kernel(vcpu->kvm))
390                 kvm_lapic_set_tpr(vcpu, cr8);
391         else
392                 vcpu->arch.cr8 = cr8;
393 }
394 EXPORT_SYMBOL_GPL(set_cr8);
395
396 unsigned long get_cr8(struct kvm_vcpu *vcpu)
397 {
398         if (irqchip_in_kernel(vcpu->kvm))
399                 return kvm_lapic_get_cr8(vcpu);
400         else
401                 return vcpu->arch.cr8;
402 }
403 EXPORT_SYMBOL_GPL(get_cr8);
404
405 /*
406  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
407  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
408  *
409  * This list is modified at module load time to reflect the
410  * capabilities of the host cpu.
411  */
412 static u32 msrs_to_save[] = {
413         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
414         MSR_K6_STAR,
415 #ifdef CONFIG_X86_64
416         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
417 #endif
418         MSR_IA32_TIME_STAMP_COUNTER,
419 };
420
421 static unsigned num_msrs_to_save;
422
423 static u32 emulated_msrs[] = {
424         MSR_IA32_MISC_ENABLE,
425 };
426
427 #ifdef CONFIG_X86_64
428
429 static void set_efer(struct kvm_vcpu *vcpu, u64 efer)
430 {
431         if (efer & EFER_RESERVED_BITS) {
432                 printk(KERN_DEBUG "set_efer: 0x%llx #GP, reserved bits\n",
433                        efer);
434                 kvm_inject_gp(vcpu, 0);
435                 return;
436         }
437
438         if (is_paging(vcpu)
439             && (vcpu->arch.shadow_efer & EFER_LME) != (efer & EFER_LME)) {
440                 printk(KERN_DEBUG "set_efer: #GP, change LME while paging\n");
441                 kvm_inject_gp(vcpu, 0);
442                 return;
443         }
444
445         kvm_x86_ops->set_efer(vcpu, efer);
446
447         efer &= ~EFER_LMA;
448         efer |= vcpu->arch.shadow_efer & EFER_LMA;
449
450         vcpu->arch.shadow_efer = efer;
451 }
452
453 #endif
454
455 /*
456  * Writes msr value into into the appropriate "register".
457  * Returns 0 on success, non-0 otherwise.
458  * Assumes vcpu_load() was already called.
459  */
460 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
461 {
462         return kvm_x86_ops->set_msr(vcpu, msr_index, data);
463 }
464
465 /*
466  * Adapt set_msr() to msr_io()'s calling convention
467  */
468 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
469 {
470         return kvm_set_msr(vcpu, index, *data);
471 }
472
473
474 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
475 {
476         switch (msr) {
477 #ifdef CONFIG_X86_64
478         case MSR_EFER:
479                 set_efer(vcpu, data);
480                 break;
481 #endif
482         case MSR_IA32_MC0_STATUS:
483                 pr_unimpl(vcpu, "%s: MSR_IA32_MC0_STATUS 0x%llx, nop\n",
484                        __FUNCTION__, data);
485                 break;
486         case MSR_IA32_MCG_STATUS:
487                 pr_unimpl(vcpu, "%s: MSR_IA32_MCG_STATUS 0x%llx, nop\n",
488                         __FUNCTION__, data);
489                 break;
490         case MSR_IA32_UCODE_REV:
491         case MSR_IA32_UCODE_WRITE:
492         case 0x200 ... 0x2ff: /* MTRRs */
493                 break;
494         case MSR_IA32_APICBASE:
495                 kvm_set_apic_base(vcpu, data);
496                 break;
497         case MSR_IA32_MISC_ENABLE:
498                 vcpu->arch.ia32_misc_enable_msr = data;
499                 break;
500         default:
501                 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n", msr, data);
502                 return 1;
503         }
504         return 0;
505 }
506 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
507
508
509 /*
510  * Reads an msr value (of 'msr_index') into 'pdata'.
511  * Returns 0 on success, non-0 otherwise.
512  * Assumes vcpu_load() was already called.
513  */
514 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
515 {
516         return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
517 }
518
519 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
520 {
521         u64 data;
522
523         switch (msr) {
524         case 0xc0010010: /* SYSCFG */
525         case 0xc0010015: /* HWCR */
526         case MSR_IA32_PLATFORM_ID:
527         case MSR_IA32_P5_MC_ADDR:
528         case MSR_IA32_P5_MC_TYPE:
529         case MSR_IA32_MC0_CTL:
530         case MSR_IA32_MCG_STATUS:
531         case MSR_IA32_MCG_CAP:
532         case MSR_IA32_MC0_MISC:
533         case MSR_IA32_MC0_MISC+4:
534         case MSR_IA32_MC0_MISC+8:
535         case MSR_IA32_MC0_MISC+12:
536         case MSR_IA32_MC0_MISC+16:
537         case MSR_IA32_UCODE_REV:
538         case MSR_IA32_PERF_STATUS:
539         case MSR_IA32_EBL_CR_POWERON:
540                 /* MTRR registers */
541         case 0xfe:
542         case 0x200 ... 0x2ff:
543                 data = 0;
544                 break;
545         case 0xcd: /* fsb frequency */
546                 data = 3;
547                 break;
548         case MSR_IA32_APICBASE:
549                 data = kvm_get_apic_base(vcpu);
550                 break;
551         case MSR_IA32_MISC_ENABLE:
552                 data = vcpu->arch.ia32_misc_enable_msr;
553                 break;
554 #ifdef CONFIG_X86_64
555         case MSR_EFER:
556                 data = vcpu->arch.shadow_efer;
557                 break;
558 #endif
559         default:
560                 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
561                 return 1;
562         }
563         *pdata = data;
564         return 0;
565 }
566 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
567
568 /*
569  * Read or write a bunch of msrs. All parameters are kernel addresses.
570  *
571  * @return number of msrs set successfully.
572  */
573 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
574                     struct kvm_msr_entry *entries,
575                     int (*do_msr)(struct kvm_vcpu *vcpu,
576                                   unsigned index, u64 *data))
577 {
578         int i;
579
580         vcpu_load(vcpu);
581
582         for (i = 0; i < msrs->nmsrs; ++i)
583                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
584                         break;
585
586         vcpu_put(vcpu);
587
588         return i;
589 }
590
591 /*
592  * Read or write a bunch of msrs. Parameters are user addresses.
593  *
594  * @return number of msrs set successfully.
595  */
596 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
597                   int (*do_msr)(struct kvm_vcpu *vcpu,
598                                 unsigned index, u64 *data),
599                   int writeback)
600 {
601         struct kvm_msrs msrs;
602         struct kvm_msr_entry *entries;
603         int r, n;
604         unsigned size;
605
606         r = -EFAULT;
607         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
608                 goto out;
609
610         r = -E2BIG;
611         if (msrs.nmsrs >= MAX_IO_MSRS)
612                 goto out;
613
614         r = -ENOMEM;
615         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
616         entries = vmalloc(size);
617         if (!entries)
618                 goto out;
619
620         r = -EFAULT;
621         if (copy_from_user(entries, user_msrs->entries, size))
622                 goto out_free;
623
624         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
625         if (r < 0)
626                 goto out_free;
627
628         r = -EFAULT;
629         if (writeback && copy_to_user(user_msrs->entries, entries, size))
630                 goto out_free;
631
632         r = n;
633
634 out_free:
635         vfree(entries);
636 out:
637         return r;
638 }
639
640 /*
641  * Make sure that a cpu that is being hot-unplugged does not have any vcpus
642  * cached on it.
643  */
644 void decache_vcpus_on_cpu(int cpu)
645 {
646         struct kvm *vm;
647         struct kvm_vcpu *vcpu;
648         int i;
649
650         spin_lock(&kvm_lock);
651         list_for_each_entry(vm, &vm_list, vm_list)
652                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
653                         vcpu = vm->vcpus[i];
654                         if (!vcpu)
655                                 continue;
656                         /*
657                          * If the vcpu is locked, then it is running on some
658                          * other cpu and therefore it is not cached on the
659                          * cpu in question.
660                          *
661                          * If it's not locked, check the last cpu it executed
662                          * on.
663                          */
664                         if (mutex_trylock(&vcpu->mutex)) {
665                                 if (vcpu->cpu == cpu) {
666                                         kvm_x86_ops->vcpu_decache(vcpu);
667                                         vcpu->cpu = -1;
668                                 }
669                                 mutex_unlock(&vcpu->mutex);
670                         }
671                 }
672         spin_unlock(&kvm_lock);
673 }
674
675 int kvm_dev_ioctl_check_extension(long ext)
676 {
677         int r;
678
679         switch (ext) {
680         case KVM_CAP_IRQCHIP:
681         case KVM_CAP_HLT:
682         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
683         case KVM_CAP_USER_MEMORY:
684         case KVM_CAP_SET_TSS_ADDR:
685         case KVM_CAP_EXT_CPUID:
686                 r = 1;
687                 break;
688         case KVM_CAP_VAPIC:
689                 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
690                 break;
691         default:
692                 r = 0;
693                 break;
694         }
695         return r;
696
697 }
698
699 long kvm_arch_dev_ioctl(struct file *filp,
700                         unsigned int ioctl, unsigned long arg)
701 {
702         void __user *argp = (void __user *)arg;
703         long r;
704
705         switch (ioctl) {
706         case KVM_GET_MSR_INDEX_LIST: {
707                 struct kvm_msr_list __user *user_msr_list = argp;
708                 struct kvm_msr_list msr_list;
709                 unsigned n;
710
711                 r = -EFAULT;
712                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
713                         goto out;
714                 n = msr_list.nmsrs;
715                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
716                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
717                         goto out;
718                 r = -E2BIG;
719                 if (n < num_msrs_to_save)
720                         goto out;
721                 r = -EFAULT;
722                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
723                                  num_msrs_to_save * sizeof(u32)))
724                         goto out;
725                 if (copy_to_user(user_msr_list->indices
726                                  + num_msrs_to_save * sizeof(u32),
727                                  &emulated_msrs,
728                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
729                         goto out;
730                 r = 0;
731                 break;
732         }
733         case KVM_GET_SUPPORTED_CPUID: {
734                 struct kvm_cpuid2 __user *cpuid_arg = argp;
735                 struct kvm_cpuid2 cpuid;
736
737                 r = -EFAULT;
738                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
739                         goto out;
740                 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
741                         cpuid_arg->entries);
742                 if (r)
743                         goto out;
744
745                 r = -EFAULT;
746                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
747                         goto out;
748                 r = 0;
749                 break;
750         }
751         default:
752                 r = -EINVAL;
753         }
754 out:
755         return r;
756 }
757
758 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
759 {
760         kvm_x86_ops->vcpu_load(vcpu, cpu);
761 }
762
763 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
764 {
765         kvm_x86_ops->vcpu_put(vcpu);
766         kvm_put_guest_fpu(vcpu);
767 }
768
769 static int is_efer_nx(void)
770 {
771         u64 efer;
772
773         rdmsrl(MSR_EFER, efer);
774         return efer & EFER_NX;
775 }
776
777 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
778 {
779         int i;
780         struct kvm_cpuid_entry2 *e, *entry;
781
782         entry = NULL;
783         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
784                 e = &vcpu->arch.cpuid_entries[i];
785                 if (e->function == 0x80000001) {
786                         entry = e;
787                         break;
788                 }
789         }
790         if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
791                 entry->edx &= ~(1 << 20);
792                 printk(KERN_INFO "kvm: guest NX capability removed\n");
793         }
794 }
795
796 /* when an old userspace process fills a new kernel module */
797 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
798                                     struct kvm_cpuid *cpuid,
799                                     struct kvm_cpuid_entry __user *entries)
800 {
801         int r, i;
802         struct kvm_cpuid_entry *cpuid_entries;
803
804         r = -E2BIG;
805         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
806                 goto out;
807         r = -ENOMEM;
808         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
809         if (!cpuid_entries)
810                 goto out;
811         r = -EFAULT;
812         if (copy_from_user(cpuid_entries, entries,
813                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
814                 goto out_free;
815         for (i = 0; i < cpuid->nent; i++) {
816                 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
817                 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
818                 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
819                 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
820                 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
821                 vcpu->arch.cpuid_entries[i].index = 0;
822                 vcpu->arch.cpuid_entries[i].flags = 0;
823                 vcpu->arch.cpuid_entries[i].padding[0] = 0;
824                 vcpu->arch.cpuid_entries[i].padding[1] = 0;
825                 vcpu->arch.cpuid_entries[i].padding[2] = 0;
826         }
827         vcpu->arch.cpuid_nent = cpuid->nent;
828         cpuid_fix_nx_cap(vcpu);
829         r = 0;
830
831 out_free:
832         vfree(cpuid_entries);
833 out:
834         return r;
835 }
836
837 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
838                                     struct kvm_cpuid2 *cpuid,
839                                     struct kvm_cpuid_entry2 __user *entries)
840 {
841         int r;
842
843         r = -E2BIG;
844         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
845                 goto out;
846         r = -EFAULT;
847         if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
848                            cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
849                 goto out;
850         vcpu->arch.cpuid_nent = cpuid->nent;
851         return 0;
852
853 out:
854         return r;
855 }
856
857 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
858                                     struct kvm_cpuid2 *cpuid,
859                                     struct kvm_cpuid_entry2 __user *entries)
860 {
861         int r;
862
863         r = -E2BIG;
864         if (cpuid->nent < vcpu->arch.cpuid_nent)
865                 goto out;
866         r = -EFAULT;
867         if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
868                            vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
869                 goto out;
870         return 0;
871
872 out:
873         cpuid->nent = vcpu->arch.cpuid_nent;
874         return r;
875 }
876
877 static inline u32 bit(int bitno)
878 {
879         return 1 << (bitno & 31);
880 }
881
882 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
883                           u32 index)
884 {
885         entry->function = function;
886         entry->index = index;
887         cpuid_count(entry->function, entry->index,
888                 &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
889         entry->flags = 0;
890 }
891
892 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
893                          u32 index, int *nent, int maxnent)
894 {
895         const u32 kvm_supported_word0_x86_features = bit(X86_FEATURE_FPU) |
896                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
897                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
898                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
899                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
900                 bit(X86_FEATURE_SEP) | bit(X86_FEATURE_PGE) |
901                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
902                 bit(X86_FEATURE_CLFLSH) | bit(X86_FEATURE_MMX) |
903                 bit(X86_FEATURE_FXSR) | bit(X86_FEATURE_XMM) |
904                 bit(X86_FEATURE_XMM2) | bit(X86_FEATURE_SELFSNOOP);
905         const u32 kvm_supported_word1_x86_features = bit(X86_FEATURE_FPU) |
906                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
907                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
908                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
909                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
910                 bit(X86_FEATURE_PGE) |
911                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
912                 bit(X86_FEATURE_MMX) | bit(X86_FEATURE_FXSR) |
913                 bit(X86_FEATURE_SYSCALL) |
914                 (bit(X86_FEATURE_NX) && is_efer_nx()) |
915 #ifdef CONFIG_X86_64
916                 bit(X86_FEATURE_LM) |
917 #endif
918                 bit(X86_FEATURE_MMXEXT) |
919                 bit(X86_FEATURE_3DNOWEXT) |
920                 bit(X86_FEATURE_3DNOW);
921         const u32 kvm_supported_word3_x86_features =
922                 bit(X86_FEATURE_XMM3) | bit(X86_FEATURE_CX16);
923         const u32 kvm_supported_word6_x86_features =
924                 bit(X86_FEATURE_LAHF_LM) | bit(X86_FEATURE_CMP_LEGACY);
925
926         /* all func 2 cpuid_count() should be called on the same cpu */
927         get_cpu();
928         do_cpuid_1_ent(entry, function, index);
929         ++*nent;
930
931         switch (function) {
932         case 0:
933                 entry->eax = min(entry->eax, (u32)0xb);
934                 break;
935         case 1:
936                 entry->edx &= kvm_supported_word0_x86_features;
937                 entry->ecx &= kvm_supported_word3_x86_features;
938                 break;
939         /* function 2 entries are STATEFUL. That is, repeated cpuid commands
940          * may return different values. This forces us to get_cpu() before
941          * issuing the first command, and also to emulate this annoying behavior
942          * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
943         case 2: {
944                 int t, times = entry->eax & 0xff;
945
946                 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
947                 for (t = 1; t < times && *nent < maxnent; ++t) {
948                         do_cpuid_1_ent(&entry[t], function, 0);
949                         entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
950                         ++*nent;
951                 }
952                 break;
953         }
954         /* function 4 and 0xb have additional index. */
955         case 4: {
956                 int index, cache_type;
957
958                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
959                 /* read more entries until cache_type is zero */
960                 for (index = 1; *nent < maxnent; ++index) {
961                         cache_type = entry[index - 1].eax & 0x1f;
962                         if (!cache_type)
963                                 break;
964                         do_cpuid_1_ent(&entry[index], function, index);
965                         entry[index].flags |=
966                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
967                         ++*nent;
968                 }
969                 break;
970         }
971         case 0xb: {
972                 int index, level_type;
973
974                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
975                 /* read more entries until level_type is zero */
976                 for (index = 1; *nent < maxnent; ++index) {
977                         level_type = entry[index - 1].ecx & 0xff;
978                         if (!level_type)
979                                 break;
980                         do_cpuid_1_ent(&entry[index], function, index);
981                         entry[index].flags |=
982                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
983                         ++*nent;
984                 }
985                 break;
986         }
987         case 0x80000000:
988                 entry->eax = min(entry->eax, 0x8000001a);
989                 break;
990         case 0x80000001:
991                 entry->edx &= kvm_supported_word1_x86_features;
992                 entry->ecx &= kvm_supported_word6_x86_features;
993                 break;
994         }
995         put_cpu();
996 }
997
998 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
999                                     struct kvm_cpuid_entry2 __user *entries)
1000 {
1001         struct kvm_cpuid_entry2 *cpuid_entries;
1002         int limit, nent = 0, r = -E2BIG;
1003         u32 func;
1004
1005         if (cpuid->nent < 1)
1006                 goto out;
1007         r = -ENOMEM;
1008         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
1009         if (!cpuid_entries)
1010                 goto out;
1011
1012         do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
1013         limit = cpuid_entries[0].eax;
1014         for (func = 1; func <= limit && nent < cpuid->nent; ++func)
1015                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1016                                 &nent, cpuid->nent);
1017         r = -E2BIG;
1018         if (nent >= cpuid->nent)
1019                 goto out_free;
1020
1021         do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
1022         limit = cpuid_entries[nent - 1].eax;
1023         for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
1024                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1025                                &nent, cpuid->nent);
1026         r = -EFAULT;
1027         if (copy_to_user(entries, cpuid_entries,
1028                         nent * sizeof(struct kvm_cpuid_entry2)))
1029                 goto out_free;
1030         cpuid->nent = nent;
1031         r = 0;
1032
1033 out_free:
1034         vfree(cpuid_entries);
1035 out:
1036         return r;
1037 }
1038
1039 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
1040                                     struct kvm_lapic_state *s)
1041 {
1042         vcpu_load(vcpu);
1043         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
1044         vcpu_put(vcpu);
1045
1046         return 0;
1047 }
1048
1049 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
1050                                     struct kvm_lapic_state *s)
1051 {
1052         vcpu_load(vcpu);
1053         memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
1054         kvm_apic_post_state_restore(vcpu);
1055         vcpu_put(vcpu);
1056
1057         return 0;
1058 }
1059
1060 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
1061                                     struct kvm_interrupt *irq)
1062 {
1063         if (irq->irq < 0 || irq->irq >= 256)
1064                 return -EINVAL;
1065         if (irqchip_in_kernel(vcpu->kvm))
1066                 return -ENXIO;
1067         vcpu_load(vcpu);
1068
1069         set_bit(irq->irq, vcpu->arch.irq_pending);
1070         set_bit(irq->irq / BITS_PER_LONG, &vcpu->arch.irq_summary);
1071
1072         vcpu_put(vcpu);
1073
1074         return 0;
1075 }
1076
1077 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
1078                                            struct kvm_tpr_access_ctl *tac)
1079 {
1080         if (tac->flags)
1081                 return -EINVAL;
1082         vcpu->arch.tpr_access_reporting = !!tac->enabled;
1083         return 0;
1084 }
1085
1086 long kvm_arch_vcpu_ioctl(struct file *filp,
1087                          unsigned int ioctl, unsigned long arg)
1088 {
1089         struct kvm_vcpu *vcpu = filp->private_data;
1090         void __user *argp = (void __user *)arg;
1091         int r;
1092
1093         switch (ioctl) {
1094         case KVM_GET_LAPIC: {
1095                 struct kvm_lapic_state lapic;
1096
1097                 memset(&lapic, 0, sizeof lapic);
1098                 r = kvm_vcpu_ioctl_get_lapic(vcpu, &lapic);
1099                 if (r)
1100                         goto out;
1101                 r = -EFAULT;
1102                 if (copy_to_user(argp, &lapic, sizeof lapic))
1103                         goto out;
1104                 r = 0;
1105                 break;
1106         }
1107         case KVM_SET_LAPIC: {
1108                 struct kvm_lapic_state lapic;
1109
1110                 r = -EFAULT;
1111                 if (copy_from_user(&lapic, argp, sizeof lapic))
1112                         goto out;
1113                 r = kvm_vcpu_ioctl_set_lapic(vcpu, &lapic);;
1114                 if (r)
1115                         goto out;
1116                 r = 0;
1117                 break;
1118         }
1119         case KVM_INTERRUPT: {
1120                 struct kvm_interrupt irq;
1121
1122                 r = -EFAULT;
1123                 if (copy_from_user(&irq, argp, sizeof irq))
1124                         goto out;
1125                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
1126                 if (r)
1127                         goto out;
1128                 r = 0;
1129                 break;
1130         }
1131         case KVM_SET_CPUID: {
1132                 struct kvm_cpuid __user *cpuid_arg = argp;
1133                 struct kvm_cpuid cpuid;
1134
1135                 r = -EFAULT;
1136                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1137                         goto out;
1138                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
1139                 if (r)
1140                         goto out;
1141                 break;
1142         }
1143         case KVM_SET_CPUID2: {
1144                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1145                 struct kvm_cpuid2 cpuid;
1146
1147                 r = -EFAULT;
1148                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1149                         goto out;
1150                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
1151                                 cpuid_arg->entries);
1152                 if (r)
1153                         goto out;
1154                 break;
1155         }
1156         case KVM_GET_CPUID2: {
1157                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1158                 struct kvm_cpuid2 cpuid;
1159
1160                 r = -EFAULT;
1161                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1162                         goto out;
1163                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
1164                                 cpuid_arg->entries);
1165                 if (r)
1166                         goto out;
1167                 r = -EFAULT;
1168                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1169                         goto out;
1170                 r = 0;
1171                 break;
1172         }
1173         case KVM_GET_MSRS:
1174                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
1175                 break;
1176         case KVM_SET_MSRS:
1177                 r = msr_io(vcpu, argp, do_set_msr, 0);
1178                 break;
1179         case KVM_TPR_ACCESS_REPORTING: {
1180                 struct kvm_tpr_access_ctl tac;
1181
1182                 r = -EFAULT;
1183                 if (copy_from_user(&tac, argp, sizeof tac))
1184                         goto out;
1185                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
1186                 if (r)
1187                         goto out;
1188                 r = -EFAULT;
1189                 if (copy_to_user(argp, &tac, sizeof tac))
1190                         goto out;
1191                 r = 0;
1192                 break;
1193         };
1194         case KVM_SET_VAPIC_ADDR: {
1195                 struct kvm_vapic_addr va;
1196
1197                 r = -EINVAL;
1198                 if (!irqchip_in_kernel(vcpu->kvm))
1199                         goto out;
1200                 r = -EFAULT;
1201                 if (copy_from_user(&va, argp, sizeof va))
1202                         goto out;
1203                 r = 0;
1204                 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
1205                 break;
1206         }
1207         default:
1208                 r = -EINVAL;
1209         }
1210 out:
1211         return r;
1212 }
1213
1214 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
1215 {
1216         int ret;
1217
1218         if (addr > (unsigned int)(-3 * PAGE_SIZE))
1219                 return -1;
1220         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
1221         return ret;
1222 }
1223
1224 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
1225                                           u32 kvm_nr_mmu_pages)
1226 {
1227         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
1228                 return -EINVAL;
1229
1230         down_write(&current->mm->mmap_sem);
1231
1232         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
1233         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
1234
1235         up_write(&current->mm->mmap_sem);
1236         return 0;
1237 }
1238
1239 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
1240 {
1241         return kvm->arch.n_alloc_mmu_pages;
1242 }
1243
1244 gfn_t unalias_gfn(struct kvm *kvm, gfn_t gfn)
1245 {
1246         int i;
1247         struct kvm_mem_alias *alias;
1248
1249         for (i = 0; i < kvm->arch.naliases; ++i) {
1250                 alias = &kvm->arch.aliases[i];
1251                 if (gfn >= alias->base_gfn
1252                     && gfn < alias->base_gfn + alias->npages)
1253                         return alias->target_gfn + gfn - alias->base_gfn;
1254         }
1255         return gfn;
1256 }
1257
1258 /*
1259  * Set a new alias region.  Aliases map a portion of physical memory into
1260  * another portion.  This is useful for memory windows, for example the PC
1261  * VGA region.
1262  */
1263 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
1264                                          struct kvm_memory_alias *alias)
1265 {
1266         int r, n;
1267         struct kvm_mem_alias *p;
1268
1269         r = -EINVAL;
1270         /* General sanity checks */
1271         if (alias->memory_size & (PAGE_SIZE - 1))
1272                 goto out;
1273         if (alias->guest_phys_addr & (PAGE_SIZE - 1))
1274                 goto out;
1275         if (alias->slot >= KVM_ALIAS_SLOTS)
1276                 goto out;
1277         if (alias->guest_phys_addr + alias->memory_size
1278             < alias->guest_phys_addr)
1279                 goto out;
1280         if (alias->target_phys_addr + alias->memory_size
1281             < alias->target_phys_addr)
1282                 goto out;
1283
1284         down_write(&current->mm->mmap_sem);
1285
1286         p = &kvm->arch.aliases[alias->slot];
1287         p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
1288         p->npages = alias->memory_size >> PAGE_SHIFT;
1289         p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
1290
1291         for (n = KVM_ALIAS_SLOTS; n > 0; --n)
1292                 if (kvm->arch.aliases[n - 1].npages)
1293                         break;
1294         kvm->arch.naliases = n;
1295
1296         kvm_mmu_zap_all(kvm);
1297
1298         up_write(&current->mm->mmap_sem);
1299
1300         return 0;
1301
1302 out:
1303         return r;
1304 }
1305
1306 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1307 {
1308         int r;
1309
1310         r = 0;
1311         switch (chip->chip_id) {
1312         case KVM_IRQCHIP_PIC_MASTER:
1313                 memcpy(&chip->chip.pic,
1314                         &pic_irqchip(kvm)->pics[0],
1315                         sizeof(struct kvm_pic_state));
1316                 break;
1317         case KVM_IRQCHIP_PIC_SLAVE:
1318                 memcpy(&chip->chip.pic,
1319                         &pic_irqchip(kvm)->pics[1],
1320                         sizeof(struct kvm_pic_state));
1321                 break;
1322         case KVM_IRQCHIP_IOAPIC:
1323                 memcpy(&chip->chip.ioapic,
1324                         ioapic_irqchip(kvm),
1325                         sizeof(struct kvm_ioapic_state));
1326                 break;
1327         default:
1328                 r = -EINVAL;
1329                 break;
1330         }
1331         return r;
1332 }
1333
1334 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1335 {
1336         int r;
1337
1338         r = 0;
1339         switch (chip->chip_id) {
1340         case KVM_IRQCHIP_PIC_MASTER:
1341                 memcpy(&pic_irqchip(kvm)->pics[0],
1342                         &chip->chip.pic,
1343                         sizeof(struct kvm_pic_state));
1344                 break;
1345         case KVM_IRQCHIP_PIC_SLAVE:
1346                 memcpy(&pic_irqchip(kvm)->pics[1],
1347                         &chip->chip.pic,
1348                         sizeof(struct kvm_pic_state));
1349                 break;
1350         case KVM_IRQCHIP_IOAPIC:
1351                 memcpy(ioapic_irqchip(kvm),
1352                         &chip->chip.ioapic,
1353                         sizeof(struct kvm_ioapic_state));
1354                 break;
1355         default:
1356                 r = -EINVAL;
1357                 break;
1358         }
1359         kvm_pic_update_irq(pic_irqchip(kvm));
1360         return r;
1361 }
1362
1363 /*
1364  * Get (and clear) the dirty memory log for a memory slot.
1365  */
1366 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1367                                       struct kvm_dirty_log *log)
1368 {
1369         int r;
1370         int n;
1371         struct kvm_memory_slot *memslot;
1372         int is_dirty = 0;
1373
1374         down_write(&current->mm->mmap_sem);
1375
1376         r = kvm_get_dirty_log(kvm, log, &is_dirty);
1377         if (r)
1378                 goto out;
1379
1380         /* If nothing is dirty, don't bother messing with page tables. */
1381         if (is_dirty) {
1382                 kvm_mmu_slot_remove_write_access(kvm, log->slot);
1383                 kvm_flush_remote_tlbs(kvm);
1384                 memslot = &kvm->memslots[log->slot];
1385                 n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
1386                 memset(memslot->dirty_bitmap, 0, n);
1387         }
1388         r = 0;
1389 out:
1390         up_write(&current->mm->mmap_sem);
1391         return r;
1392 }
1393
1394 long kvm_arch_vm_ioctl(struct file *filp,
1395                        unsigned int ioctl, unsigned long arg)
1396 {
1397         struct kvm *kvm = filp->private_data;
1398         void __user *argp = (void __user *)arg;
1399         int r = -EINVAL;
1400
1401         switch (ioctl) {
1402         case KVM_SET_TSS_ADDR:
1403                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
1404                 if (r < 0)
1405                         goto out;
1406                 break;
1407         case KVM_SET_MEMORY_REGION: {
1408                 struct kvm_memory_region kvm_mem;
1409                 struct kvm_userspace_memory_region kvm_userspace_mem;
1410
1411                 r = -EFAULT;
1412                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
1413                         goto out;
1414                 kvm_userspace_mem.slot = kvm_mem.slot;
1415                 kvm_userspace_mem.flags = kvm_mem.flags;
1416                 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
1417                 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
1418                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
1419                 if (r)
1420                         goto out;
1421                 break;
1422         }
1423         case KVM_SET_NR_MMU_PAGES:
1424                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
1425                 if (r)
1426                         goto out;
1427                 break;
1428         case KVM_GET_NR_MMU_PAGES:
1429                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
1430                 break;
1431         case KVM_SET_MEMORY_ALIAS: {
1432                 struct kvm_memory_alias alias;
1433
1434                 r = -EFAULT;
1435                 if (copy_from_user(&alias, argp, sizeof alias))
1436                         goto out;
1437                 r = kvm_vm_ioctl_set_memory_alias(kvm, &alias);
1438                 if (r)
1439                         goto out;
1440                 break;
1441         }
1442         case KVM_CREATE_IRQCHIP:
1443                 r = -ENOMEM;
1444                 kvm->arch.vpic = kvm_create_pic(kvm);
1445                 if (kvm->arch.vpic) {
1446                         r = kvm_ioapic_init(kvm);
1447                         if (r) {
1448                                 kfree(kvm->arch.vpic);
1449                                 kvm->arch.vpic = NULL;
1450                                 goto out;
1451                         }
1452                 } else
1453                         goto out;
1454                 break;
1455         case KVM_IRQ_LINE: {
1456                 struct kvm_irq_level irq_event;
1457
1458                 r = -EFAULT;
1459                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
1460                         goto out;
1461                 if (irqchip_in_kernel(kvm)) {
1462                         mutex_lock(&kvm->lock);
1463                         if (irq_event.irq < 16)
1464                                 kvm_pic_set_irq(pic_irqchip(kvm),
1465                                         irq_event.irq,
1466                                         irq_event.level);
1467                         kvm_ioapic_set_irq(kvm->arch.vioapic,
1468                                         irq_event.irq,
1469                                         irq_event.level);
1470                         mutex_unlock(&kvm->lock);
1471                         r = 0;
1472                 }
1473                 break;
1474         }
1475         case KVM_GET_IRQCHIP: {
1476                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1477                 struct kvm_irqchip chip;
1478
1479                 r = -EFAULT;
1480                 if (copy_from_user(&chip, argp, sizeof chip))
1481                         goto out;
1482                 r = -ENXIO;
1483                 if (!irqchip_in_kernel(kvm))
1484                         goto out;
1485                 r = kvm_vm_ioctl_get_irqchip(kvm, &chip);
1486                 if (r)
1487                         goto out;
1488                 r = -EFAULT;
1489                 if (copy_to_user(argp, &chip, sizeof chip))
1490                         goto out;
1491                 r = 0;
1492                 break;
1493         }
1494         case KVM_SET_IRQCHIP: {
1495                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1496                 struct kvm_irqchip chip;
1497
1498                 r = -EFAULT;
1499                 if (copy_from_user(&chip, argp, sizeof chip))
1500                         goto out;
1501                 r = -ENXIO;
1502                 if (!irqchip_in_kernel(kvm))
1503                         goto out;
1504                 r = kvm_vm_ioctl_set_irqchip(kvm, &chip);
1505                 if (r)
1506                         goto out;
1507                 r = 0;
1508                 break;
1509         }
1510         default:
1511                 ;
1512         }
1513 out:
1514         return r;
1515 }
1516
1517 static void kvm_init_msr_list(void)
1518 {
1519         u32 dummy[2];
1520         unsigned i, j;
1521
1522         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
1523                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
1524                         continue;
1525                 if (j < i)
1526                         msrs_to_save[j] = msrs_to_save[i];
1527                 j++;
1528         }
1529         num_msrs_to_save = j;
1530 }
1531
1532 /*
1533  * Only apic need an MMIO device hook, so shortcut now..
1534  */
1535 static struct kvm_io_device *vcpu_find_pervcpu_dev(struct kvm_vcpu *vcpu,
1536                                                 gpa_t addr)
1537 {
1538         struct kvm_io_device *dev;
1539
1540         if (vcpu->arch.apic) {
1541                 dev = &vcpu->arch.apic->dev;
1542                 if (dev->in_range(dev, addr))
1543                         return dev;
1544         }
1545         return NULL;
1546 }
1547
1548
1549 static struct kvm_io_device *vcpu_find_mmio_dev(struct kvm_vcpu *vcpu,
1550                                                 gpa_t addr)
1551 {
1552         struct kvm_io_device *dev;
1553
1554         dev = vcpu_find_pervcpu_dev(vcpu, addr);
1555         if (dev == NULL)
1556                 dev = kvm_io_bus_find_dev(&vcpu->kvm->mmio_bus, addr);
1557         return dev;
1558 }
1559
1560 int emulator_read_std(unsigned long addr,
1561                              void *val,
1562                              unsigned int bytes,
1563                              struct kvm_vcpu *vcpu)
1564 {
1565         void *data = val;
1566         int r = X86EMUL_CONTINUE;
1567
1568         down_read(&current->mm->mmap_sem);
1569         while (bytes) {
1570                 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1571                 unsigned offset = addr & (PAGE_SIZE-1);
1572                 unsigned tocopy = min(bytes, (unsigned)PAGE_SIZE - offset);
1573                 int ret;
1574
1575                 if (gpa == UNMAPPED_GVA) {
1576                         r = X86EMUL_PROPAGATE_FAULT;
1577                         goto out;
1578                 }
1579                 ret = kvm_read_guest(vcpu->kvm, gpa, data, tocopy);
1580                 if (ret < 0) {
1581                         r = X86EMUL_UNHANDLEABLE;
1582                         goto out;
1583                 }
1584
1585                 bytes -= tocopy;
1586                 data += tocopy;
1587                 addr += tocopy;
1588         }
1589 out:
1590         up_read(&current->mm->mmap_sem);
1591         return r;
1592 }
1593 EXPORT_SYMBOL_GPL(emulator_read_std);
1594
1595 static int emulator_read_emulated(unsigned long addr,
1596                                   void *val,
1597                                   unsigned int bytes,
1598                                   struct kvm_vcpu *vcpu)
1599 {
1600         struct kvm_io_device *mmio_dev;
1601         gpa_t                 gpa;
1602
1603         if (vcpu->mmio_read_completed) {
1604                 memcpy(val, vcpu->mmio_data, bytes);
1605                 vcpu->mmio_read_completed = 0;
1606                 return X86EMUL_CONTINUE;
1607         }
1608
1609         down_read(&current->mm->mmap_sem);
1610         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1611         up_read(&current->mm->mmap_sem);
1612
1613         /* For APIC access vmexit */
1614         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1615                 goto mmio;
1616
1617         if (emulator_read_std(addr, val, bytes, vcpu)
1618                         == X86EMUL_CONTINUE)
1619                 return X86EMUL_CONTINUE;
1620         if (gpa == UNMAPPED_GVA)
1621                 return X86EMUL_PROPAGATE_FAULT;
1622
1623 mmio:
1624         /*
1625          * Is this MMIO handled locally?
1626          */
1627         mutex_lock(&vcpu->kvm->lock);
1628         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1629         if (mmio_dev) {
1630                 kvm_iodevice_read(mmio_dev, gpa, bytes, val);
1631                 mutex_unlock(&vcpu->kvm->lock);
1632                 return X86EMUL_CONTINUE;
1633         }
1634         mutex_unlock(&vcpu->kvm->lock);
1635
1636         vcpu->mmio_needed = 1;
1637         vcpu->mmio_phys_addr = gpa;
1638         vcpu->mmio_size = bytes;
1639         vcpu->mmio_is_write = 0;
1640
1641         return X86EMUL_UNHANDLEABLE;
1642 }
1643
1644 static int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
1645                                const void *val, int bytes)
1646 {
1647         int ret;
1648
1649         down_read(&current->mm->mmap_sem);
1650         ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
1651         if (ret < 0) {
1652                 up_read(&current->mm->mmap_sem);
1653                 return 0;
1654         }
1655         kvm_mmu_pte_write(vcpu, gpa, val, bytes);
1656         up_read(&current->mm->mmap_sem);
1657         return 1;
1658 }
1659
1660 static int emulator_write_emulated_onepage(unsigned long addr,
1661                                            const void *val,
1662                                            unsigned int bytes,
1663                                            struct kvm_vcpu *vcpu)
1664 {
1665         struct kvm_io_device *mmio_dev;
1666         gpa_t                 gpa;
1667
1668         down_read(&current->mm->mmap_sem);
1669         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1670         up_read(&current->mm->mmap_sem);
1671
1672         if (gpa == UNMAPPED_GVA) {
1673                 kvm_inject_page_fault(vcpu, addr, 2);
1674                 return X86EMUL_PROPAGATE_FAULT;
1675         }
1676
1677         /* For APIC access vmexit */
1678         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1679                 goto mmio;
1680
1681         if (emulator_write_phys(vcpu, gpa, val, bytes))
1682                 return X86EMUL_CONTINUE;
1683
1684 mmio:
1685         /*
1686          * Is this MMIO handled locally?
1687          */
1688         mutex_lock(&vcpu->kvm->lock);
1689         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1690         if (mmio_dev) {
1691                 kvm_iodevice_write(mmio_dev, gpa, bytes, val);
1692                 mutex_unlock(&vcpu->kvm->lock);
1693                 return X86EMUL_CONTINUE;
1694         }
1695         mutex_unlock(&vcpu->kvm->lock);
1696
1697         vcpu->mmio_needed = 1;
1698         vcpu->mmio_phys_addr = gpa;
1699         vcpu->mmio_size = bytes;
1700         vcpu->mmio_is_write = 1;
1701         memcpy(vcpu->mmio_data, val, bytes);
1702
1703         return X86EMUL_CONTINUE;
1704 }
1705
1706 int emulator_write_emulated(unsigned long addr,
1707                                    const void *val,
1708                                    unsigned int bytes,
1709                                    struct kvm_vcpu *vcpu)
1710 {
1711         /* Crossing a page boundary? */
1712         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
1713                 int rc, now;
1714
1715                 now = -addr & ~PAGE_MASK;
1716                 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
1717                 if (rc != X86EMUL_CONTINUE)
1718                         return rc;
1719                 addr += now;
1720                 val += now;
1721                 bytes -= now;
1722         }
1723         return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
1724 }
1725 EXPORT_SYMBOL_GPL(emulator_write_emulated);
1726
1727 static int emulator_cmpxchg_emulated(unsigned long addr,
1728                                      const void *old,
1729                                      const void *new,
1730                                      unsigned int bytes,
1731                                      struct kvm_vcpu *vcpu)
1732 {
1733         static int reported;
1734
1735         if (!reported) {
1736                 reported = 1;
1737                 printk(KERN_WARNING "kvm: emulating exchange as write\n");
1738         }
1739 #ifndef CONFIG_X86_64
1740         /* guests cmpxchg8b have to be emulated atomically */
1741         if (bytes == 8) {
1742                 gpa_t gpa;
1743                 struct page *page;
1744                 char *kaddr;
1745                 u64 val;
1746
1747                 down_read(&current->mm->mmap_sem);
1748                 gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1749
1750                 if (gpa == UNMAPPED_GVA ||
1751                    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1752                         goto emul_write;
1753
1754                 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
1755                         goto emul_write;
1756
1757                 val = *(u64 *)new;
1758                 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1759                 kaddr = kmap_atomic(page, KM_USER0);
1760                 set_64bit((u64 *)(kaddr + offset_in_page(gpa)), val);
1761                 kunmap_atomic(kaddr, KM_USER0);
1762                 kvm_release_page_dirty(page);
1763         emul_write:
1764                 up_read(&current->mm->mmap_sem);
1765         }
1766 #endif
1767
1768         return emulator_write_emulated(addr, new, bytes, vcpu);
1769 }
1770
1771 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
1772 {
1773         return kvm_x86_ops->get_segment_base(vcpu, seg);
1774 }
1775
1776 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
1777 {
1778         return X86EMUL_CONTINUE;
1779 }
1780
1781 int emulate_clts(struct kvm_vcpu *vcpu)
1782 {
1783         kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 & ~X86_CR0_TS);
1784         return X86EMUL_CONTINUE;
1785 }
1786
1787 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
1788 {
1789         struct kvm_vcpu *vcpu = ctxt->vcpu;
1790
1791         switch (dr) {
1792         case 0 ... 3:
1793                 *dest = kvm_x86_ops->get_dr(vcpu, dr);
1794                 return X86EMUL_CONTINUE;
1795         default:
1796                 pr_unimpl(vcpu, "%s: unexpected dr %u\n", __FUNCTION__, dr);
1797                 return X86EMUL_UNHANDLEABLE;
1798         }
1799 }
1800
1801 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
1802 {
1803         unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
1804         int exception;
1805
1806         kvm_x86_ops->set_dr(ctxt->vcpu, dr, value & mask, &exception);
1807         if (exception) {
1808                 /* FIXME: better handling */
1809                 return X86EMUL_UNHANDLEABLE;
1810         }
1811         return X86EMUL_CONTINUE;
1812 }
1813
1814 void kvm_report_emulation_failure(struct kvm_vcpu *vcpu, const char *context)
1815 {
1816         static int reported;
1817         u8 opcodes[4];
1818         unsigned long rip = vcpu->arch.rip;
1819         unsigned long rip_linear;
1820
1821         rip_linear = rip + get_segment_base(vcpu, VCPU_SREG_CS);
1822
1823         if (reported)
1824                 return;
1825
1826         emulator_read_std(rip_linear, (void *)opcodes, 4, vcpu);
1827
1828         printk(KERN_ERR "emulation failed (%s) rip %lx %02x %02x %02x %02x\n",
1829                context, rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
1830         reported = 1;
1831 }
1832 EXPORT_SYMBOL_GPL(kvm_report_emulation_failure);
1833
1834 struct x86_emulate_ops emulate_ops = {
1835         .read_std            = emulator_read_std,
1836         .read_emulated       = emulator_read_emulated,
1837         .write_emulated      = emulator_write_emulated,
1838         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
1839 };
1840
1841 int emulate_instruction(struct kvm_vcpu *vcpu,
1842                         struct kvm_run *run,
1843                         unsigned long cr2,
1844                         u16 error_code,
1845                         int emulation_type)
1846 {
1847         int r;
1848         struct decode_cache *c;
1849
1850         vcpu->arch.mmio_fault_cr2 = cr2;
1851         kvm_x86_ops->cache_regs(vcpu);
1852
1853         vcpu->mmio_is_write = 0;
1854         vcpu->arch.pio.string = 0;
1855
1856         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
1857                 int cs_db, cs_l;
1858                 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
1859
1860                 vcpu->arch.emulate_ctxt.vcpu = vcpu;
1861                 vcpu->arch.emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
1862                 vcpu->arch.emulate_ctxt.mode =
1863                         (vcpu->arch.emulate_ctxt.eflags & X86_EFLAGS_VM)
1864                         ? X86EMUL_MODE_REAL : cs_l
1865                         ? X86EMUL_MODE_PROT64 : cs_db
1866                         ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
1867
1868                 if (vcpu->arch.emulate_ctxt.mode == X86EMUL_MODE_PROT64) {
1869                         vcpu->arch.emulate_ctxt.cs_base = 0;
1870                         vcpu->arch.emulate_ctxt.ds_base = 0;
1871                         vcpu->arch.emulate_ctxt.es_base = 0;
1872                         vcpu->arch.emulate_ctxt.ss_base = 0;
1873                 } else {
1874                         vcpu->arch.emulate_ctxt.cs_base =
1875                                         get_segment_base(vcpu, VCPU_SREG_CS);
1876                         vcpu->arch.emulate_ctxt.ds_base =
1877                                         get_segment_base(vcpu, VCPU_SREG_DS);
1878                         vcpu->arch.emulate_ctxt.es_base =
1879                                         get_segment_base(vcpu, VCPU_SREG_ES);
1880                         vcpu->arch.emulate_ctxt.ss_base =
1881                                         get_segment_base(vcpu, VCPU_SREG_SS);
1882                 }
1883
1884                 vcpu->arch.emulate_ctxt.gs_base =
1885                                         get_segment_base(vcpu, VCPU_SREG_GS);
1886                 vcpu->arch.emulate_ctxt.fs_base =
1887                                         get_segment_base(vcpu, VCPU_SREG_FS);
1888
1889                 r = x86_decode_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
1890
1891                 /* Reject the instructions other than VMCALL/VMMCALL when
1892                  * try to emulate invalid opcode */
1893                 c = &vcpu->arch.emulate_ctxt.decode;
1894                 if ((emulation_type & EMULTYPE_TRAP_UD) &&
1895                     (!(c->twobyte && c->b == 0x01 &&
1896                       (c->modrm_reg == 0 || c->modrm_reg == 3) &&
1897                        c->modrm_mod == 3 && c->modrm_rm == 1)))
1898                         return EMULATE_FAIL;
1899
1900                 ++vcpu->stat.insn_emulation;
1901                 if (r)  {
1902                         ++vcpu->stat.insn_emulation_fail;
1903                         if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
1904                                 return EMULATE_DONE;
1905                         return EMULATE_FAIL;
1906                 }
1907         }
1908
1909         r = x86_emulate_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
1910
1911         if (vcpu->arch.pio.string)
1912                 return EMULATE_DO_MMIO;
1913
1914         if ((r || vcpu->mmio_is_write) && run) {
1915                 run->exit_reason = KVM_EXIT_MMIO;
1916                 run->mmio.phys_addr = vcpu->mmio_phys_addr;
1917                 memcpy(run->mmio.data, vcpu->mmio_data, 8);
1918                 run->mmio.len = vcpu->mmio_size;
1919                 run->mmio.is_write = vcpu->mmio_is_write;
1920         }
1921
1922         if (r) {
1923                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
1924                         return EMULATE_DONE;
1925                 if (!vcpu->mmio_needed) {
1926                         kvm_report_emulation_failure(vcpu, "mmio");
1927                         return EMULATE_FAIL;
1928                 }
1929                 return EMULATE_DO_MMIO;
1930         }
1931
1932         kvm_x86_ops->decache_regs(vcpu);
1933         kvm_x86_ops->set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
1934
1935         if (vcpu->mmio_is_write) {
1936                 vcpu->mmio_needed = 0;
1937                 return EMULATE_DO_MMIO;
1938         }
1939
1940         return EMULATE_DONE;
1941 }
1942 EXPORT_SYMBOL_GPL(emulate_instruction);
1943
1944 static void free_pio_guest_pages(struct kvm_vcpu *vcpu)
1945 {
1946         int i;
1947
1948         for (i = 0; i < ARRAY_SIZE(vcpu->arch.pio.guest_pages); ++i)
1949                 if (vcpu->arch.pio.guest_pages[i]) {
1950                         kvm_release_page_dirty(vcpu->arch.pio.guest_pages[i]);
1951                         vcpu->arch.pio.guest_pages[i] = NULL;
1952                 }
1953 }
1954
1955 static int pio_copy_data(struct kvm_vcpu *vcpu)
1956 {
1957         void *p = vcpu->arch.pio_data;
1958         void *q;
1959         unsigned bytes;
1960         int nr_pages = vcpu->arch.pio.guest_pages[1] ? 2 : 1;
1961
1962         q = vmap(vcpu->arch.pio.guest_pages, nr_pages, VM_READ|VM_WRITE,
1963                  PAGE_KERNEL);
1964         if (!q) {
1965                 free_pio_guest_pages(vcpu);
1966                 return -ENOMEM;
1967         }
1968         q += vcpu->arch.pio.guest_page_offset;
1969         bytes = vcpu->arch.pio.size * vcpu->arch.pio.cur_count;
1970         if (vcpu->arch.pio.in)
1971                 memcpy(q, p, bytes);
1972         else
1973                 memcpy(p, q, bytes);
1974         q -= vcpu->arch.pio.guest_page_offset;
1975         vunmap(q);
1976         free_pio_guest_pages(vcpu);
1977         return 0;
1978 }
1979
1980 int complete_pio(struct kvm_vcpu *vcpu)
1981 {
1982         struct kvm_pio_request *io = &vcpu->arch.pio;
1983         long delta;
1984         int r;
1985
1986         kvm_x86_ops->cache_regs(vcpu);
1987
1988         if (!io->string) {
1989                 if (io->in)
1990                         memcpy(&vcpu->arch.regs[VCPU_REGS_RAX], vcpu->arch.pio_data,
1991                                io->size);
1992         } else {
1993                 if (io->in) {
1994                         r = pio_copy_data(vcpu);
1995                         if (r) {
1996                                 kvm_x86_ops->cache_regs(vcpu);
1997                                 return r;
1998                         }
1999                 }
2000
2001                 delta = 1;
2002                 if (io->rep) {
2003                         delta *= io->cur_count;
2004                         /*
2005                          * The size of the register should really depend on
2006                          * current address size.
2007                          */
2008                         vcpu->arch.regs[VCPU_REGS_RCX] -= delta;
2009                 }
2010                 if (io->down)
2011                         delta = -delta;
2012                 delta *= io->size;
2013                 if (io->in)
2014                         vcpu->arch.regs[VCPU_REGS_RDI] += delta;
2015                 else
2016                         vcpu->arch.regs[VCPU_REGS_RSI] += delta;
2017         }
2018
2019         kvm_x86_ops->decache_regs(vcpu);
2020
2021         io->count -= io->cur_count;
2022         io->cur_count = 0;
2023
2024         return 0;
2025 }
2026
2027 static void kernel_pio(struct kvm_io_device *pio_dev,
2028                        struct kvm_vcpu *vcpu,
2029                        void *pd)
2030 {
2031         /* TODO: String I/O for in kernel device */
2032
2033         mutex_lock(&vcpu->kvm->lock);
2034         if (vcpu->arch.pio.in)
2035                 kvm_iodevice_read(pio_dev, vcpu->arch.pio.port,
2036                                   vcpu->arch.pio.size,
2037                                   pd);
2038         else
2039                 kvm_iodevice_write(pio_dev, vcpu->arch.pio.port,
2040                                    vcpu->arch.pio.size,
2041                                    pd);
2042         mutex_unlock(&vcpu->kvm->lock);
2043 }
2044
2045 static void pio_string_write(struct kvm_io_device *pio_dev,
2046                              struct kvm_vcpu *vcpu)
2047 {
2048         struct kvm_pio_request *io = &vcpu->arch.pio;
2049         void *pd = vcpu->arch.pio_data;
2050         int i;
2051
2052         mutex_lock(&vcpu->kvm->lock);
2053         for (i = 0; i < io->cur_count; i++) {
2054                 kvm_iodevice_write(pio_dev, io->port,
2055                                    io->size,
2056                                    pd);
2057                 pd += io->size;
2058         }
2059         mutex_unlock(&vcpu->kvm->lock);
2060 }
2061
2062 static struct kvm_io_device *vcpu_find_pio_dev(struct kvm_vcpu *vcpu,
2063                                                gpa_t addr)
2064 {
2065         return kvm_io_bus_find_dev(&vcpu->kvm->pio_bus, addr);
2066 }
2067
2068 int kvm_emulate_pio(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2069                   int size, unsigned port)
2070 {
2071         struct kvm_io_device *pio_dev;
2072
2073         vcpu->run->exit_reason = KVM_EXIT_IO;
2074         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2075         vcpu->run->io.size = vcpu->arch.pio.size = size;
2076         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2077         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = 1;
2078         vcpu->run->io.port = vcpu->arch.pio.port = port;
2079         vcpu->arch.pio.in = in;
2080         vcpu->arch.pio.string = 0;
2081         vcpu->arch.pio.down = 0;
2082         vcpu->arch.pio.guest_page_offset = 0;
2083         vcpu->arch.pio.rep = 0;
2084
2085         kvm_x86_ops->cache_regs(vcpu);
2086         memcpy(vcpu->arch.pio_data, &vcpu->arch.regs[VCPU_REGS_RAX], 4);
2087         kvm_x86_ops->decache_regs(vcpu);
2088
2089         kvm_x86_ops->skip_emulated_instruction(vcpu);
2090
2091         pio_dev = vcpu_find_pio_dev(vcpu, port);
2092         if (pio_dev) {
2093                 kernel_pio(pio_dev, vcpu, vcpu->arch.pio_data);
2094                 complete_pio(vcpu);
2095                 return 1;
2096         }
2097         return 0;
2098 }
2099 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
2100
2101 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2102                   int size, unsigned long count, int down,
2103                   gva_t address, int rep, unsigned port)
2104 {
2105         unsigned now, in_page;
2106         int i, ret = 0;
2107         int nr_pages = 1;
2108         struct page *page;
2109         struct kvm_io_device *pio_dev;
2110
2111         vcpu->run->exit_reason = KVM_EXIT_IO;
2112         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2113         vcpu->run->io.size = vcpu->arch.pio.size = size;
2114         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2115         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = count;
2116         vcpu->run->io.port = vcpu->arch.pio.port = port;
2117         vcpu->arch.pio.in = in;
2118         vcpu->arch.pio.string = 1;
2119         vcpu->arch.pio.down = down;
2120         vcpu->arch.pio.guest_page_offset = offset_in_page(address);
2121         vcpu->arch.pio.rep = rep;
2122
2123         if (!count) {
2124                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2125                 return 1;
2126         }
2127
2128         if (!down)
2129                 in_page = PAGE_SIZE - offset_in_page(address);
2130         else
2131                 in_page = offset_in_page(address) + size;
2132         now = min(count, (unsigned long)in_page / size);
2133         if (!now) {
2134                 /*
2135                  * String I/O straddles page boundary.  Pin two guest pages
2136                  * so that we satisfy atomicity constraints.  Do just one
2137                  * transaction to avoid complexity.
2138                  */
2139                 nr_pages = 2;
2140                 now = 1;
2141         }
2142         if (down) {
2143                 /*
2144                  * String I/O in reverse.  Yuck.  Kill the guest, fix later.
2145                  */
2146                 pr_unimpl(vcpu, "guest string pio down\n");
2147                 kvm_inject_gp(vcpu, 0);
2148                 return 1;
2149         }
2150         vcpu->run->io.count = now;
2151         vcpu->arch.pio.cur_count = now;
2152
2153         if (vcpu->arch.pio.cur_count == vcpu->arch.pio.count)
2154                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2155
2156         for (i = 0; i < nr_pages; ++i) {
2157                 down_read(&current->mm->mmap_sem);
2158                 page = gva_to_page(vcpu, address + i * PAGE_SIZE);
2159                 vcpu->arch.pio.guest_pages[i] = page;
2160                 up_read(&current->mm->mmap_sem);
2161                 if (!page) {
2162                         kvm_inject_gp(vcpu, 0);
2163                         free_pio_guest_pages(vcpu);
2164                         return 1;
2165                 }
2166         }
2167
2168         pio_dev = vcpu_find_pio_dev(vcpu, port);
2169         if (!vcpu->arch.pio.in) {
2170                 /* string PIO write */
2171                 ret = pio_copy_data(vcpu);
2172                 if (ret >= 0 && pio_dev) {
2173                         pio_string_write(pio_dev, vcpu);
2174                         complete_pio(vcpu);
2175                         if (vcpu->arch.pio.count == 0)
2176                                 ret = 1;
2177                 }
2178         } else if (pio_dev)
2179                 pr_unimpl(vcpu, "no string pio read support yet, "
2180                        "port %x size %d count %ld\n",
2181                         port, size, count);
2182
2183         return ret;
2184 }
2185 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
2186
2187 int kvm_arch_init(void *opaque)
2188 {
2189         int r;
2190         struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
2191
2192         if (kvm_x86_ops) {
2193                 printk(KERN_ERR "kvm: already loaded the other module\n");
2194                 r = -EEXIST;
2195                 goto out;
2196         }
2197
2198         if (!ops->cpu_has_kvm_support()) {
2199                 printk(KERN_ERR "kvm: no hardware support\n");
2200                 r = -EOPNOTSUPP;
2201                 goto out;
2202         }
2203         if (ops->disabled_by_bios()) {
2204                 printk(KERN_ERR "kvm: disabled by bios\n");
2205                 r = -EOPNOTSUPP;
2206                 goto out;
2207         }
2208
2209         r = kvm_mmu_module_init();
2210         if (r)
2211                 goto out;
2212
2213         kvm_init_msr_list();
2214
2215         kvm_x86_ops = ops;
2216         kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
2217         return 0;
2218
2219 out:
2220         return r;
2221 }
2222
2223 void kvm_arch_exit(void)
2224 {
2225         kvm_x86_ops = NULL;
2226         kvm_mmu_module_exit();
2227 }
2228
2229 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
2230 {
2231         ++vcpu->stat.halt_exits;
2232         if (irqchip_in_kernel(vcpu->kvm)) {
2233                 vcpu->arch.mp_state = VCPU_MP_STATE_HALTED;
2234                 kvm_vcpu_block(vcpu);
2235                 if (vcpu->arch.mp_state != VCPU_MP_STATE_RUNNABLE)
2236                         return -EINTR;
2237                 return 1;
2238         } else {
2239                 vcpu->run->exit_reason = KVM_EXIT_HLT;
2240                 return 0;
2241         }
2242 }
2243 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
2244
2245 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
2246 {
2247         unsigned long nr, a0, a1, a2, a3, ret;
2248
2249         kvm_x86_ops->cache_regs(vcpu);
2250
2251         nr = vcpu->arch.regs[VCPU_REGS_RAX];
2252         a0 = vcpu->arch.regs[VCPU_REGS_RBX];
2253         a1 = vcpu->arch.regs[VCPU_REGS_RCX];
2254         a2 = vcpu->arch.regs[VCPU_REGS_RDX];
2255         a3 = vcpu->arch.regs[VCPU_REGS_RSI];
2256
2257         if (!is_long_mode(vcpu)) {
2258                 nr &= 0xFFFFFFFF;
2259                 a0 &= 0xFFFFFFFF;
2260                 a1 &= 0xFFFFFFFF;
2261                 a2 &= 0xFFFFFFFF;
2262                 a3 &= 0xFFFFFFFF;
2263         }
2264
2265         switch (nr) {
2266         case KVM_HC_VAPIC_POLL_IRQ:
2267                 ret = 0;
2268                 break;
2269         default:
2270                 ret = -KVM_ENOSYS;
2271                 break;
2272         }
2273         vcpu->arch.regs[VCPU_REGS_RAX] = ret;
2274         kvm_x86_ops->decache_regs(vcpu);
2275         return 0;
2276 }
2277 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
2278
2279 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
2280 {
2281         char instruction[3];
2282         int ret = 0;
2283
2284
2285         /*
2286          * Blow out the MMU to ensure that no other VCPU has an active mapping
2287          * to ensure that the updated hypercall appears atomically across all
2288          * VCPUs.
2289          */
2290         kvm_mmu_zap_all(vcpu->kvm);
2291
2292         kvm_x86_ops->cache_regs(vcpu);
2293         kvm_x86_ops->patch_hypercall(vcpu, instruction);
2294         if (emulator_write_emulated(vcpu->arch.rip, instruction, 3, vcpu)
2295             != X86EMUL_CONTINUE)
2296                 ret = -EFAULT;
2297
2298         return ret;
2299 }
2300
2301 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
2302 {
2303         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
2304 }
2305
2306 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2307 {
2308         struct descriptor_table dt = { limit, base };
2309
2310         kvm_x86_ops->set_gdt(vcpu, &dt);
2311 }
2312
2313 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2314 {
2315         struct descriptor_table dt = { limit, base };
2316
2317         kvm_x86_ops->set_idt(vcpu, &dt);
2318 }
2319
2320 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
2321                    unsigned long *rflags)
2322 {
2323         lmsw(vcpu, msw);
2324         *rflags = kvm_x86_ops->get_rflags(vcpu);
2325 }
2326
2327 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
2328 {
2329         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2330         switch (cr) {
2331         case 0:
2332                 return vcpu->arch.cr0;
2333         case 2:
2334                 return vcpu->arch.cr2;
2335         case 3:
2336                 return vcpu->arch.cr3;
2337         case 4:
2338                 return vcpu->arch.cr4;
2339         case 8:
2340                 return get_cr8(vcpu);
2341         default:
2342                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
2343                 return 0;
2344         }
2345 }
2346
2347 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
2348                      unsigned long *rflags)
2349 {
2350         switch (cr) {
2351         case 0:
2352                 set_cr0(vcpu, mk_cr_64(vcpu->arch.cr0, val));
2353                 *rflags = kvm_x86_ops->get_rflags(vcpu);
2354                 break;
2355         case 2:
2356                 vcpu->arch.cr2 = val;
2357                 break;
2358         case 3:
2359                 set_cr3(vcpu, val);
2360                 break;
2361         case 4:
2362                 set_cr4(vcpu, mk_cr_64(vcpu->arch.cr4, val));
2363                 break;
2364         case 8:
2365                 set_cr8(vcpu, val & 0xfUL);
2366                 break;
2367         default:
2368                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
2369         }
2370 }
2371
2372 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
2373 {
2374         struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
2375         int j, nent = vcpu->arch.cpuid_nent;
2376
2377         e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
2378         /* when no next entry is found, the current entry[i] is reselected */
2379         for (j = i + 1; j == i; j = (j + 1) % nent) {
2380                 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
2381                 if (ej->function == e->function) {
2382                         ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
2383                         return j;
2384                 }
2385         }
2386         return 0; /* silence gcc, even though control never reaches here */
2387 }
2388
2389 /* find an entry with matching function, matching index (if needed), and that
2390  * should be read next (if it's stateful) */
2391 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
2392         u32 function, u32 index)
2393 {
2394         if (e->function != function)
2395                 return 0;
2396         if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
2397                 return 0;
2398         if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
2399                 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
2400                 return 0;
2401         return 1;
2402 }
2403
2404 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
2405 {
2406         int i;
2407         u32 function, index;
2408         struct kvm_cpuid_entry2 *e, *best;
2409
2410         kvm_x86_ops->cache_regs(vcpu);
2411         function = vcpu->arch.regs[VCPU_REGS_RAX];
2412         index = vcpu->arch.regs[VCPU_REGS_RCX];
2413         vcpu->arch.regs[VCPU_REGS_RAX] = 0;
2414         vcpu->arch.regs[VCPU_REGS_RBX] = 0;
2415         vcpu->arch.regs[VCPU_REGS_RCX] = 0;
2416         vcpu->arch.regs[VCPU_REGS_RDX] = 0;
2417         best = NULL;
2418         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
2419                 e = &vcpu->arch.cpuid_entries[i];
2420                 if (is_matching_cpuid_entry(e, function, index)) {
2421                         if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
2422                                 move_to_next_stateful_cpuid_entry(vcpu, i);
2423                         best = e;
2424                         break;
2425                 }
2426                 /*
2427                  * Both basic or both extended?
2428                  */
2429                 if (((e->function ^ function) & 0x80000000) == 0)
2430                         if (!best || e->function > best->function)
2431                                 best = e;
2432         }
2433         if (best) {
2434                 vcpu->arch.regs[VCPU_REGS_RAX] = best->eax;
2435                 vcpu->arch.regs[VCPU_REGS_RBX] = best->ebx;
2436                 vcpu->arch.regs[VCPU_REGS_RCX] = best->ecx;
2437                 vcpu->arch.regs[VCPU_REGS_RDX] = best->edx;
2438         }
2439         kvm_x86_ops->decache_regs(vcpu);
2440         kvm_x86_ops->skip_emulated_instruction(vcpu);
2441 }
2442 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
2443
2444 /*
2445  * Check if userspace requested an interrupt window, and that the
2446  * interrupt window is open.
2447  *
2448  * No need to exit to userspace if we already have an interrupt queued.
2449  */
2450 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu,
2451                                           struct kvm_run *kvm_run)
2452 {
2453         return (!vcpu->arch.irq_summary &&
2454                 kvm_run->request_interrupt_window &&
2455                 vcpu->arch.interrupt_window_open &&
2456                 (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF));
2457 }
2458
2459 static void post_kvm_run_save(struct kvm_vcpu *vcpu,
2460                               struct kvm_run *kvm_run)
2461 {
2462         kvm_run->if_flag = (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
2463         kvm_run->cr8 = get_cr8(vcpu);
2464         kvm_run->apic_base = kvm_get_apic_base(vcpu);
2465         if (irqchip_in_kernel(vcpu->kvm))
2466                 kvm_run->ready_for_interrupt_injection = 1;
2467         else
2468                 kvm_run->ready_for_interrupt_injection =
2469                                         (vcpu->arch.interrupt_window_open &&
2470                                          vcpu->arch.irq_summary == 0);
2471 }
2472
2473 static void vapic_enter(struct kvm_vcpu *vcpu)
2474 {
2475         struct kvm_lapic *apic = vcpu->arch.apic;
2476         struct page *page;
2477
2478         if (!apic || !apic->vapic_addr)
2479                 return;
2480
2481         down_read(&current->mm->mmap_sem);
2482         page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
2483         vcpu->arch.apic->vapic_page = page;
2484         up_read(&current->mm->mmap_sem);
2485 }
2486
2487 static void vapic_exit(struct kvm_vcpu *vcpu)
2488 {
2489         struct kvm_lapic *apic = vcpu->arch.apic;
2490
2491         if (!apic || !apic->vapic_addr)
2492                 return;
2493
2494         kvm_release_page_dirty(apic->vapic_page);
2495         mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
2496 }
2497
2498 static int __vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2499 {
2500         int r;
2501
2502         if (unlikely(vcpu->arch.mp_state == VCPU_MP_STATE_SIPI_RECEIVED)) {
2503                 pr_debug("vcpu %d received sipi with vector # %x\n",
2504                        vcpu->vcpu_id, vcpu->arch.sipi_vector);
2505                 kvm_lapic_reset(vcpu);
2506                 r = kvm_x86_ops->vcpu_reset(vcpu);
2507                 if (r)
2508                         return r;
2509                 vcpu->arch.mp_state = VCPU_MP_STATE_RUNNABLE;
2510         }
2511
2512         vapic_enter(vcpu);
2513
2514 preempted:
2515         if (vcpu->guest_debug.enabled)
2516                 kvm_x86_ops->guest_debug_pre(vcpu);
2517
2518 again:
2519         r = kvm_mmu_reload(vcpu);
2520         if (unlikely(r))
2521                 goto out;
2522
2523         if (vcpu->requests) {
2524                 if (test_and_clear_bit(KVM_REQ_MIGRATE_TIMER, &vcpu->requests))
2525                         __kvm_migrate_apic_timer(vcpu);
2526                 if (test_and_clear_bit(KVM_REQ_REPORT_TPR_ACCESS,
2527                                        &vcpu->requests)) {
2528                         kvm_run->exit_reason = KVM_EXIT_TPR_ACCESS;
2529                         r = 0;
2530                         goto out;
2531                 }
2532         }
2533
2534         kvm_inject_pending_timer_irqs(vcpu);
2535
2536         preempt_disable();
2537
2538         kvm_x86_ops->prepare_guest_switch(vcpu);
2539         kvm_load_guest_fpu(vcpu);
2540
2541         local_irq_disable();
2542
2543         if (need_resched()) {
2544                 local_irq_enable();
2545                 preempt_enable();
2546                 r = 1;
2547                 goto out;
2548         }
2549
2550         if (signal_pending(current)) {
2551                 local_irq_enable();
2552                 preempt_enable();
2553                 r = -EINTR;
2554                 kvm_run->exit_reason = KVM_EXIT_INTR;
2555                 ++vcpu->stat.signal_exits;
2556                 goto out;
2557         }
2558
2559         if (vcpu->arch.exception.pending)
2560                 __queue_exception(vcpu);
2561         else if (irqchip_in_kernel(vcpu->kvm))
2562                 kvm_x86_ops->inject_pending_irq(vcpu);
2563         else
2564                 kvm_x86_ops->inject_pending_vectors(vcpu, kvm_run);
2565
2566         kvm_lapic_sync_to_vapic(vcpu);
2567
2568         vcpu->guest_mode = 1;
2569         kvm_guest_enter();
2570
2571         if (vcpu->requests)
2572                 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
2573                         kvm_x86_ops->tlb_flush(vcpu);
2574
2575         kvm_x86_ops->run(vcpu, kvm_run);
2576
2577         vcpu->guest_mode = 0;
2578         local_irq_enable();
2579
2580         ++vcpu->stat.exits;
2581
2582         /*
2583          * We must have an instruction between local_irq_enable() and
2584          * kvm_guest_exit(), so the timer interrupt isn't delayed by
2585          * the interrupt shadow.  The stat.exits increment will do nicely.
2586          * But we need to prevent reordering, hence this barrier():
2587          */
2588         barrier();
2589
2590         kvm_guest_exit();
2591
2592         preempt_enable();
2593
2594         /*
2595          * Profile KVM exit RIPs:
2596          */
2597         if (unlikely(prof_on == KVM_PROFILING)) {
2598                 kvm_x86_ops->cache_regs(vcpu);
2599                 profile_hit(KVM_PROFILING, (void *)vcpu->arch.rip);
2600         }
2601
2602         if (vcpu->arch.exception.pending && kvm_x86_ops->exception_injected(vcpu))
2603                 vcpu->arch.exception.pending = false;
2604
2605         kvm_lapic_sync_from_vapic(vcpu);
2606
2607         r = kvm_x86_ops->handle_exit(kvm_run, vcpu);
2608
2609         if (r > 0) {
2610                 if (dm_request_for_irq_injection(vcpu, kvm_run)) {
2611                         r = -EINTR;
2612                         kvm_run->exit_reason = KVM_EXIT_INTR;
2613                         ++vcpu->stat.request_irq_exits;
2614                         goto out;
2615                 }
2616                 if (!need_resched())
2617                         goto again;
2618         }
2619
2620 out:
2621         if (r > 0) {
2622                 kvm_resched(vcpu);
2623                 goto preempted;
2624         }
2625
2626         post_kvm_run_save(vcpu, kvm_run);
2627
2628         vapic_exit(vcpu);
2629
2630         return r;
2631 }
2632
2633 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2634 {
2635         int r;
2636         sigset_t sigsaved;
2637
2638         vcpu_load(vcpu);
2639
2640         if (unlikely(vcpu->arch.mp_state == VCPU_MP_STATE_UNINITIALIZED)) {
2641                 kvm_vcpu_block(vcpu);
2642                 vcpu_put(vcpu);
2643                 return -EAGAIN;
2644         }
2645
2646         if (vcpu->sigset_active)
2647                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
2648
2649         /* re-sync apic's tpr */
2650         if (!irqchip_in_kernel(vcpu->kvm))
2651                 set_cr8(vcpu, kvm_run->cr8);
2652
2653         if (vcpu->arch.pio.cur_count) {
2654                 r = complete_pio(vcpu);
2655                 if (r)
2656                         goto out;
2657         }
2658 #if CONFIG_HAS_IOMEM
2659         if (vcpu->mmio_needed) {
2660                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
2661                 vcpu->mmio_read_completed = 1;
2662                 vcpu->mmio_needed = 0;
2663                 r = emulate_instruction(vcpu, kvm_run,
2664                                         vcpu->arch.mmio_fault_cr2, 0,
2665                                         EMULTYPE_NO_DECODE);
2666                 if (r == EMULATE_DO_MMIO) {
2667                         /*
2668                          * Read-modify-write.  Back to userspace.
2669                          */
2670                         r = 0;
2671                         goto out;
2672                 }
2673         }
2674 #endif
2675         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL) {
2676                 kvm_x86_ops->cache_regs(vcpu);
2677                 vcpu->arch.regs[VCPU_REGS_RAX] = kvm_run->hypercall.ret;
2678                 kvm_x86_ops->decache_regs(vcpu);
2679         }
2680
2681         r = __vcpu_run(vcpu, kvm_run);
2682
2683 out:
2684         if (vcpu->sigset_active)
2685                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
2686
2687         vcpu_put(vcpu);
2688         return r;
2689 }
2690
2691 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
2692 {
2693         vcpu_load(vcpu);
2694
2695         kvm_x86_ops->cache_regs(vcpu);
2696
2697         regs->rax = vcpu->arch.regs[VCPU_REGS_RAX];
2698         regs->rbx = vcpu->arch.regs[VCPU_REGS_RBX];
2699         regs->rcx = vcpu->arch.regs[VCPU_REGS_RCX];
2700         regs->rdx = vcpu->arch.regs[VCPU_REGS_RDX];
2701         regs->rsi = vcpu->arch.regs[VCPU_REGS_RSI];
2702         regs->rdi = vcpu->arch.regs[VCPU_REGS_RDI];
2703         regs->rsp = vcpu->arch.regs[VCPU_REGS_RSP];
2704         regs->rbp = vcpu->arch.regs[VCPU_REGS_RBP];
2705 #ifdef CONFIG_X86_64
2706         regs->r8 = vcpu->arch.regs[VCPU_REGS_R8];
2707         regs->r9 = vcpu->arch.regs[VCPU_REGS_R9];
2708         regs->r10 = vcpu->arch.regs[VCPU_REGS_R10];
2709         regs->r11 = vcpu->arch.regs[VCPU_REGS_R11];
2710         regs->r12 = vcpu->arch.regs[VCPU_REGS_R12];
2711         regs->r13 = vcpu->arch.regs[VCPU_REGS_R13];
2712         regs->r14 = vcpu->arch.regs[VCPU_REGS_R14];
2713         regs->r15 = vcpu->arch.regs[VCPU_REGS_R15];
2714 #endif
2715
2716         regs->rip = vcpu->arch.rip;
2717         regs->rflags = kvm_x86_ops->get_rflags(vcpu);
2718
2719         /*
2720          * Don't leak debug flags in case they were set for guest debugging
2721          */
2722         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
2723                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
2724
2725         vcpu_put(vcpu);
2726
2727         return 0;
2728 }
2729
2730 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
2731 {
2732         vcpu_load(vcpu);
2733
2734         vcpu->arch.regs[VCPU_REGS_RAX] = regs->rax;
2735         vcpu->arch.regs[VCPU_REGS_RBX] = regs->rbx;
2736         vcpu->arch.regs[VCPU_REGS_RCX] = regs->rcx;
2737         vcpu->arch.regs[VCPU_REGS_RDX] = regs->rdx;
2738         vcpu->arch.regs[VCPU_REGS_RSI] = regs->rsi;
2739         vcpu->arch.regs[VCPU_REGS_RDI] = regs->rdi;
2740         vcpu->arch.regs[VCPU_REGS_RSP] = regs->rsp;
2741         vcpu->arch.regs[VCPU_REGS_RBP] = regs->rbp;
2742 #ifdef CONFIG_X86_64
2743         vcpu->arch.regs[VCPU_REGS_R8] = regs->r8;
2744         vcpu->arch.regs[VCPU_REGS_R9] = regs->r9;
2745         vcpu->arch.regs[VCPU_REGS_R10] = regs->r10;
2746         vcpu->arch.regs[VCPU_REGS_R11] = regs->r11;
2747         vcpu->arch.regs[VCPU_REGS_R12] = regs->r12;
2748         vcpu->arch.regs[VCPU_REGS_R13] = regs->r13;
2749         vcpu->arch.regs[VCPU_REGS_R14] = regs->r14;
2750         vcpu->arch.regs[VCPU_REGS_R15] = regs->r15;
2751 #endif
2752
2753         vcpu->arch.rip = regs->rip;
2754         kvm_x86_ops->set_rflags(vcpu, regs->rflags);
2755
2756         kvm_x86_ops->decache_regs(vcpu);
2757
2758         vcpu_put(vcpu);
2759
2760         return 0;
2761 }
2762
2763 static void get_segment(struct kvm_vcpu *vcpu,
2764                         struct kvm_segment *var, int seg)
2765 {
2766         return kvm_x86_ops->get_segment(vcpu, var, seg);
2767 }
2768
2769 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
2770 {
2771         struct kvm_segment cs;
2772
2773         get_segment(vcpu, &cs, VCPU_SREG_CS);
2774         *db = cs.db;
2775         *l = cs.l;
2776 }
2777 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
2778
2779 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
2780                                   struct kvm_sregs *sregs)
2781 {
2782         struct descriptor_table dt;
2783         int pending_vec;
2784
2785         vcpu_load(vcpu);
2786
2787         get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
2788         get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
2789         get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
2790         get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
2791         get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
2792         get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
2793
2794         get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
2795         get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
2796
2797         kvm_x86_ops->get_idt(vcpu, &dt);
2798         sregs->idt.limit = dt.limit;
2799         sregs->idt.base = dt.base;
2800         kvm_x86_ops->get_gdt(vcpu, &dt);
2801         sregs->gdt.limit = dt.limit;
2802         sregs->gdt.base = dt.base;
2803
2804         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2805         sregs->cr0 = vcpu->arch.cr0;
2806         sregs->cr2 = vcpu->arch.cr2;
2807         sregs->cr3 = vcpu->arch.cr3;
2808         sregs->cr4 = vcpu->arch.cr4;
2809         sregs->cr8 = get_cr8(vcpu);
2810         sregs->efer = vcpu->arch.shadow_efer;
2811         sregs->apic_base = kvm_get_apic_base(vcpu);
2812
2813         if (irqchip_in_kernel(vcpu->kvm)) {
2814                 memset(sregs->interrupt_bitmap, 0,
2815                        sizeof sregs->interrupt_bitmap);
2816                 pending_vec = kvm_x86_ops->get_irq(vcpu);
2817                 if (pending_vec >= 0)
2818                         set_bit(pending_vec,
2819                                 (unsigned long *)sregs->interrupt_bitmap);
2820         } else
2821                 memcpy(sregs->interrupt_bitmap, vcpu->arch.irq_pending,
2822                        sizeof sregs->interrupt_bitmap);
2823
2824         vcpu_put(vcpu);
2825
2826         return 0;
2827 }
2828
2829 static void set_segment(struct kvm_vcpu *vcpu,
2830                         struct kvm_segment *var, int seg)
2831 {
2832         return kvm_x86_ops->set_segment(vcpu, var, seg);
2833 }
2834
2835 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
2836                                   struct kvm_sregs *sregs)
2837 {
2838         int mmu_reset_needed = 0;
2839         int i, pending_vec, max_bits;
2840         struct descriptor_table dt;
2841
2842         vcpu_load(vcpu);
2843
2844         dt.limit = sregs->idt.limit;
2845         dt.base = sregs->idt.base;
2846         kvm_x86_ops->set_idt(vcpu, &dt);
2847         dt.limit = sregs->gdt.limit;
2848         dt.base = sregs->gdt.base;
2849         kvm_x86_ops->set_gdt(vcpu, &dt);
2850
2851         vcpu->arch.cr2 = sregs->cr2;
2852         mmu_reset_needed |= vcpu->arch.cr3 != sregs->cr3;
2853         vcpu->arch.cr3 = sregs->cr3;
2854
2855         set_cr8(vcpu, sregs->cr8);
2856
2857         mmu_reset_needed |= vcpu->arch.shadow_efer != sregs->efer;
2858 #ifdef CONFIG_X86_64
2859         kvm_x86_ops->set_efer(vcpu, sregs->efer);
2860 #endif
2861         kvm_set_apic_base(vcpu, sregs->apic_base);
2862
2863         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2864
2865         mmu_reset_needed |= vcpu->arch.cr0 != sregs->cr0;
2866         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
2867         vcpu->arch.cr0 = sregs->cr0;
2868
2869         mmu_reset_needed |= vcpu->arch.cr4 != sregs->cr4;
2870         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
2871         if (!is_long_mode(vcpu) && is_pae(vcpu))
2872                 load_pdptrs(vcpu, vcpu->arch.cr3);
2873
2874         if (mmu_reset_needed)
2875                 kvm_mmu_reset_context(vcpu);
2876
2877         if (!irqchip_in_kernel(vcpu->kvm)) {
2878                 memcpy(vcpu->arch.irq_pending, sregs->interrupt_bitmap,
2879                        sizeof vcpu->arch.irq_pending);
2880                 vcpu->arch.irq_summary = 0;
2881                 for (i = 0; i < ARRAY_SIZE(vcpu->arch.irq_pending); ++i)
2882                         if (vcpu->arch.irq_pending[i])
2883                                 __set_bit(i, &vcpu->arch.irq_summary);
2884         } else {
2885                 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
2886                 pending_vec = find_first_bit(
2887                         (const unsigned long *)sregs->interrupt_bitmap,
2888                         max_bits);
2889                 /* Only pending external irq is handled here */
2890                 if (pending_vec < max_bits) {
2891                         kvm_x86_ops->set_irq(vcpu, pending_vec);
2892                         pr_debug("Set back pending irq %d\n",
2893                                  pending_vec);
2894                 }
2895         }
2896
2897         set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
2898         set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
2899         set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
2900         set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
2901         set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
2902         set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
2903
2904         set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
2905         set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
2906
2907         vcpu_put(vcpu);
2908
2909         return 0;
2910 }
2911
2912 int kvm_arch_vcpu_ioctl_debug_guest(struct kvm_vcpu *vcpu,
2913                                     struct kvm_debug_guest *dbg)
2914 {
2915         int r;
2916
2917         vcpu_load(vcpu);
2918
2919         r = kvm_x86_ops->set_guest_debug(vcpu, dbg);
2920
2921         vcpu_put(vcpu);
2922
2923         return r;
2924 }
2925
2926 /*
2927  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
2928  * we have asm/x86/processor.h
2929  */
2930 struct fxsave {
2931         u16     cwd;
2932         u16     swd;
2933         u16     twd;
2934         u16     fop;
2935         u64     rip;
2936         u64     rdp;
2937         u32     mxcsr;
2938         u32     mxcsr_mask;
2939         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
2940 #ifdef CONFIG_X86_64
2941         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
2942 #else
2943         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
2944 #endif
2945 };
2946
2947 /*
2948  * Translate a guest virtual address to a guest physical address.
2949  */
2950 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
2951                                     struct kvm_translation *tr)
2952 {
2953         unsigned long vaddr = tr->linear_address;
2954         gpa_t gpa;
2955
2956         vcpu_load(vcpu);
2957         down_read(&current->mm->mmap_sem);
2958         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, vaddr);
2959         up_read(&current->mm->mmap_sem);
2960         tr->physical_address = gpa;
2961         tr->valid = gpa != UNMAPPED_GVA;
2962         tr->writeable = 1;
2963         tr->usermode = 0;
2964         vcpu_put(vcpu);
2965
2966         return 0;
2967 }
2968
2969 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2970 {
2971         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
2972
2973         vcpu_load(vcpu);
2974
2975         memcpy(fpu->fpr, fxsave->st_space, 128);
2976         fpu->fcw = fxsave->cwd;
2977         fpu->fsw = fxsave->swd;
2978         fpu->ftwx = fxsave->twd;
2979         fpu->last_opcode = fxsave->fop;
2980         fpu->last_ip = fxsave->rip;
2981         fpu->last_dp = fxsave->rdp;
2982         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
2983
2984         vcpu_put(vcpu);
2985
2986         return 0;
2987 }
2988
2989 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2990 {
2991         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
2992
2993         vcpu_load(vcpu);
2994
2995         memcpy(fxsave->st_space, fpu->fpr, 128);
2996         fxsave->cwd = fpu->fcw;
2997         fxsave->swd = fpu->fsw;
2998         fxsave->twd = fpu->ftwx;
2999         fxsave->fop = fpu->last_opcode;
3000         fxsave->rip = fpu->last_ip;
3001         fxsave->rdp = fpu->last_dp;
3002         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
3003
3004         vcpu_put(vcpu);
3005
3006         return 0;
3007 }
3008
3009 void fx_init(struct kvm_vcpu *vcpu)
3010 {
3011         unsigned after_mxcsr_mask;
3012
3013         /* Initialize guest FPU by resetting ours and saving into guest's */
3014         preempt_disable();
3015         fx_save(&vcpu->arch.host_fx_image);
3016         fpu_init();
3017         fx_save(&vcpu->arch.guest_fx_image);
3018         fx_restore(&vcpu->arch.host_fx_image);
3019         preempt_enable();
3020
3021         vcpu->arch.cr0 |= X86_CR0_ET;
3022         after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
3023         vcpu->arch.guest_fx_image.mxcsr = 0x1f80;
3024         memset((void *)&vcpu->arch.guest_fx_image + after_mxcsr_mask,
3025                0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
3026 }
3027 EXPORT_SYMBOL_GPL(fx_init);
3028
3029 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
3030 {
3031         if (!vcpu->fpu_active || vcpu->guest_fpu_loaded)
3032                 return;
3033
3034         vcpu->guest_fpu_loaded = 1;
3035         fx_save(&vcpu->arch.host_fx_image);
3036         fx_restore(&vcpu->arch.guest_fx_image);
3037 }
3038 EXPORT_SYMBOL_GPL(kvm_load_guest_fpu);
3039
3040 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
3041 {
3042         if (!vcpu->guest_fpu_loaded)
3043                 return;
3044
3045         vcpu->guest_fpu_loaded = 0;
3046         fx_save(&vcpu->arch.guest_fx_image);
3047         fx_restore(&vcpu->arch.host_fx_image);
3048         ++vcpu->stat.fpu_reload;
3049 }
3050 EXPORT_SYMBOL_GPL(kvm_put_guest_fpu);
3051
3052 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
3053 {
3054         kvm_x86_ops->vcpu_free(vcpu);
3055 }
3056
3057 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
3058                                                 unsigned int id)
3059 {
3060         return kvm_x86_ops->vcpu_create(kvm, id);
3061 }
3062
3063 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
3064 {
3065         int r;
3066
3067         /* We do fxsave: this must be aligned. */
3068         BUG_ON((unsigned long)&vcpu->arch.host_fx_image & 0xF);
3069
3070         vcpu_load(vcpu);
3071         r = kvm_arch_vcpu_reset(vcpu);
3072         if (r == 0)
3073                 r = kvm_mmu_setup(vcpu);
3074         vcpu_put(vcpu);
3075         if (r < 0)
3076                 goto free_vcpu;
3077
3078         return 0;
3079 free_vcpu:
3080         kvm_x86_ops->vcpu_free(vcpu);
3081         return r;
3082 }
3083
3084 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
3085 {
3086         vcpu_load(vcpu);
3087         kvm_mmu_unload(vcpu);
3088         vcpu_put(vcpu);
3089
3090         kvm_x86_ops->vcpu_free(vcpu);
3091 }
3092
3093 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
3094 {
3095         return kvm_x86_ops->vcpu_reset(vcpu);
3096 }
3097
3098 void kvm_arch_hardware_enable(void *garbage)
3099 {
3100         kvm_x86_ops->hardware_enable(garbage);
3101 }
3102
3103 void kvm_arch_hardware_disable(void *garbage)
3104 {
3105         kvm_x86_ops->hardware_disable(garbage);
3106 }
3107
3108 int kvm_arch_hardware_setup(void)
3109 {
3110         return kvm_x86_ops->hardware_setup();
3111 }
3112
3113 void kvm_arch_hardware_unsetup(void)
3114 {
3115         kvm_x86_ops->hardware_unsetup();
3116 }
3117
3118 void kvm_arch_check_processor_compat(void *rtn)
3119 {
3120         kvm_x86_ops->check_processor_compatibility(rtn);
3121 }
3122
3123 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
3124 {
3125         struct page *page;
3126         struct kvm *kvm;
3127         int r;
3128
3129         BUG_ON(vcpu->kvm == NULL);
3130         kvm = vcpu->kvm;
3131
3132         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
3133         if (!irqchip_in_kernel(kvm) || vcpu->vcpu_id == 0)
3134                 vcpu->arch.mp_state = VCPU_MP_STATE_RUNNABLE;
3135         else
3136                 vcpu->arch.mp_state = VCPU_MP_STATE_UNINITIALIZED;
3137
3138         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
3139         if (!page) {
3140                 r = -ENOMEM;
3141                 goto fail;
3142         }
3143         vcpu->arch.pio_data = page_address(page);
3144
3145         r = kvm_mmu_create(vcpu);
3146         if (r < 0)
3147                 goto fail_free_pio_data;
3148
3149         if (irqchip_in_kernel(kvm)) {
3150                 r = kvm_create_lapic(vcpu);
3151                 if (r < 0)
3152                         goto fail_mmu_destroy;
3153         }
3154
3155         return 0;
3156
3157 fail_mmu_destroy:
3158         kvm_mmu_destroy(vcpu);
3159 fail_free_pio_data:
3160         free_page((unsigned long)vcpu->arch.pio_data);
3161 fail:
3162         return r;
3163 }
3164
3165 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
3166 {
3167         kvm_free_lapic(vcpu);
3168         kvm_mmu_destroy(vcpu);
3169         free_page((unsigned long)vcpu->arch.pio_data);
3170 }
3171
3172 struct  kvm *kvm_arch_create_vm(void)
3173 {
3174         struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
3175
3176         if (!kvm)
3177                 return ERR_PTR(-ENOMEM);
3178
3179         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
3180
3181         return kvm;
3182 }
3183
3184 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
3185 {
3186         vcpu_load(vcpu);
3187         kvm_mmu_unload(vcpu);
3188         vcpu_put(vcpu);
3189 }
3190
3191 static void kvm_free_vcpus(struct kvm *kvm)
3192 {
3193         unsigned int i;
3194
3195         /*
3196          * Unpin any mmu pages first.
3197          */
3198         for (i = 0; i < KVM_MAX_VCPUS; ++i)
3199                 if (kvm->vcpus[i])
3200                         kvm_unload_vcpu_mmu(kvm->vcpus[i]);
3201         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
3202                 if (kvm->vcpus[i]) {
3203                         kvm_arch_vcpu_free(kvm->vcpus[i]);
3204                         kvm->vcpus[i] = NULL;
3205                 }
3206         }
3207
3208 }
3209
3210 void kvm_arch_destroy_vm(struct kvm *kvm)
3211 {
3212         kfree(kvm->arch.vpic);
3213         kfree(kvm->arch.vioapic);
3214         kvm_free_vcpus(kvm);
3215         kvm_free_physmem(kvm);
3216         kfree(kvm);
3217 }
3218
3219 int kvm_arch_set_memory_region(struct kvm *kvm,
3220                                 struct kvm_userspace_memory_region *mem,
3221                                 struct kvm_memory_slot old,
3222                                 int user_alloc)
3223 {
3224         int npages = mem->memory_size >> PAGE_SHIFT;
3225         struct kvm_memory_slot *memslot = &kvm->memslots[mem->slot];
3226
3227         /*To keep backward compatibility with older userspace,
3228          *x86 needs to hanlde !user_alloc case.
3229          */
3230         if (!user_alloc) {
3231                 if (npages && !old.rmap) {
3232                         memslot->userspace_addr = do_mmap(NULL, 0,
3233                                                      npages * PAGE_SIZE,
3234                                                      PROT_READ | PROT_WRITE,
3235                                                      MAP_SHARED | MAP_ANONYMOUS,
3236                                                      0);
3237
3238                         if (IS_ERR((void *)memslot->userspace_addr))
3239                                 return PTR_ERR((void *)memslot->userspace_addr);
3240                 } else {
3241                         if (!old.user_alloc && old.rmap) {
3242                                 int ret;
3243
3244                                 ret = do_munmap(current->mm, old.userspace_addr,
3245                                                 old.npages * PAGE_SIZE);
3246                                 if (ret < 0)
3247                                         printk(KERN_WARNING
3248                                        "kvm_vm_ioctl_set_memory_region: "
3249                                        "failed to munmap memory\n");
3250                         }
3251                 }
3252         }
3253
3254         if (!kvm->arch.n_requested_mmu_pages) {
3255                 unsigned int nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
3256                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
3257         }
3258
3259         kvm_mmu_slot_remove_write_access(kvm, mem->slot);
3260         kvm_flush_remote_tlbs(kvm);
3261
3262         return 0;
3263 }
3264
3265 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
3266 {
3267         return vcpu->arch.mp_state == VCPU_MP_STATE_RUNNABLE
3268                || vcpu->arch.mp_state == VCPU_MP_STATE_SIPI_RECEIVED;
3269 }
3270
3271 static void vcpu_kick_intr(void *info)
3272 {
3273 #ifdef DEBUG
3274         struct kvm_vcpu *vcpu = (struct kvm_vcpu *)info;
3275         printk(KERN_DEBUG "vcpu_kick_intr %p \n", vcpu);
3276 #endif
3277 }
3278
3279 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3280 {
3281         int ipi_pcpu = vcpu->cpu;
3282
3283         if (waitqueue_active(&vcpu->wq)) {
3284                 wake_up_interruptible(&vcpu->wq);
3285                 ++vcpu->stat.halt_wakeup;
3286         }
3287         if (vcpu->guest_mode)
3288                 smp_call_function_single(ipi_pcpu, vcpu_kick_intr, vcpu, 0, 0);
3289 }