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