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