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