KVM: x86 emulator: Any legacy prefix after a REX prefix nullifies its effect
[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;
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                 if (r)  {
1298                         if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
1299                                 return EMULATE_DONE;
1300                         return EMULATE_FAIL;
1301                 }
1302         }
1303
1304         r = x86_emulate_insn(&vcpu->emulate_ctxt, &emulate_ops);
1305
1306         if (vcpu->pio.string)
1307                 return EMULATE_DO_MMIO;
1308
1309         if ((r || vcpu->mmio_is_write) && run) {
1310                 run->exit_reason = KVM_EXIT_MMIO;
1311                 run->mmio.phys_addr = vcpu->mmio_phys_addr;
1312                 memcpy(run->mmio.data, vcpu->mmio_data, 8);
1313                 run->mmio.len = vcpu->mmio_size;
1314                 run->mmio.is_write = vcpu->mmio_is_write;
1315         }
1316
1317         if (r) {
1318                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
1319                         return EMULATE_DONE;
1320                 if (!vcpu->mmio_needed) {
1321                         kvm_report_emulation_failure(vcpu, "mmio");
1322                         return EMULATE_FAIL;
1323                 }
1324                 return EMULATE_DO_MMIO;
1325         }
1326
1327         kvm_x86_ops->decache_regs(vcpu);
1328         kvm_x86_ops->set_rflags(vcpu, vcpu->emulate_ctxt.eflags);
1329
1330         if (vcpu->mmio_is_write) {
1331                 vcpu->mmio_needed = 0;
1332                 return EMULATE_DO_MMIO;
1333         }
1334
1335         return EMULATE_DONE;
1336 }
1337 EXPORT_SYMBOL_GPL(emulate_instruction);
1338
1339 /*
1340  * The vCPU has executed a HLT instruction with in-kernel mode enabled.
1341  */
1342 static void kvm_vcpu_block(struct kvm_vcpu *vcpu)
1343 {
1344         DECLARE_WAITQUEUE(wait, current);
1345
1346         add_wait_queue(&vcpu->wq, &wait);
1347
1348         /*
1349          * We will block until either an interrupt or a signal wakes us up
1350          */
1351         while (!kvm_cpu_has_interrupt(vcpu)
1352                && !signal_pending(current)
1353                && vcpu->mp_state != VCPU_MP_STATE_RUNNABLE
1354                && vcpu->mp_state != VCPU_MP_STATE_SIPI_RECEIVED) {
1355                 set_current_state(TASK_INTERRUPTIBLE);
1356                 vcpu_put(vcpu);
1357                 schedule();
1358                 vcpu_load(vcpu);
1359         }
1360
1361         __set_current_state(TASK_RUNNING);
1362         remove_wait_queue(&vcpu->wq, &wait);
1363 }
1364
1365 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
1366 {
1367         ++vcpu->stat.halt_exits;
1368         if (irqchip_in_kernel(vcpu->kvm)) {
1369                 vcpu->mp_state = VCPU_MP_STATE_HALTED;
1370                 kvm_vcpu_block(vcpu);
1371                 if (vcpu->mp_state != VCPU_MP_STATE_RUNNABLE)
1372                         return -EINTR;
1373                 return 1;
1374         } else {
1375                 vcpu->run->exit_reason = KVM_EXIT_HLT;
1376                 return 0;
1377         }
1378 }
1379 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
1380
1381 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
1382 {
1383         unsigned long nr, a0, a1, a2, a3, ret;
1384
1385         kvm_x86_ops->cache_regs(vcpu);
1386
1387         nr = vcpu->regs[VCPU_REGS_RAX];
1388         a0 = vcpu->regs[VCPU_REGS_RBX];
1389         a1 = vcpu->regs[VCPU_REGS_RCX];
1390         a2 = vcpu->regs[VCPU_REGS_RDX];
1391         a3 = vcpu->regs[VCPU_REGS_RSI];
1392
1393         if (!is_long_mode(vcpu)) {
1394                 nr &= 0xFFFFFFFF;
1395                 a0 &= 0xFFFFFFFF;
1396                 a1 &= 0xFFFFFFFF;
1397                 a2 &= 0xFFFFFFFF;
1398                 a3 &= 0xFFFFFFFF;
1399         }
1400
1401         switch (nr) {
1402         default:
1403                 ret = -KVM_ENOSYS;
1404                 break;
1405         }
1406         vcpu->regs[VCPU_REGS_RAX] = ret;
1407         kvm_x86_ops->decache_regs(vcpu);
1408         return 0;
1409 }
1410 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
1411
1412 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
1413 {
1414         char instruction[3];
1415         int ret = 0;
1416
1417         mutex_lock(&vcpu->kvm->lock);
1418
1419         /*
1420          * Blow out the MMU to ensure that no other VCPU has an active mapping
1421          * to ensure that the updated hypercall appears atomically across all
1422          * VCPUs.
1423          */
1424         kvm_mmu_zap_all(vcpu->kvm);
1425
1426         kvm_x86_ops->cache_regs(vcpu);
1427         kvm_x86_ops->patch_hypercall(vcpu, instruction);
1428         if (emulator_write_emulated(vcpu->rip, instruction, 3, vcpu)
1429             != X86EMUL_CONTINUE)
1430                 ret = -EFAULT;
1431
1432         mutex_unlock(&vcpu->kvm->lock);
1433
1434         return ret;
1435 }
1436
1437 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
1438 {
1439         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
1440 }
1441
1442 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
1443 {
1444         struct descriptor_table dt = { limit, base };
1445
1446         kvm_x86_ops->set_gdt(vcpu, &dt);
1447 }
1448
1449 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
1450 {
1451         struct descriptor_table dt = { limit, base };
1452
1453         kvm_x86_ops->set_idt(vcpu, &dt);
1454 }
1455
1456 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
1457                    unsigned long *rflags)
1458 {
1459         lmsw(vcpu, msw);
1460         *rflags = kvm_x86_ops->get_rflags(vcpu);
1461 }
1462
1463 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
1464 {
1465         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
1466         switch (cr) {
1467         case 0:
1468                 return vcpu->cr0;
1469         case 2:
1470                 return vcpu->cr2;
1471         case 3:
1472                 return vcpu->cr3;
1473         case 4:
1474                 return vcpu->cr4;
1475         default:
1476                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
1477                 return 0;
1478         }
1479 }
1480
1481 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
1482                      unsigned long *rflags)
1483 {
1484         switch (cr) {
1485         case 0:
1486                 set_cr0(vcpu, mk_cr_64(vcpu->cr0, val));
1487                 *rflags = kvm_x86_ops->get_rflags(vcpu);
1488                 break;
1489         case 2:
1490                 vcpu->cr2 = val;
1491                 break;
1492         case 3:
1493                 set_cr3(vcpu, val);
1494                 break;
1495         case 4:
1496                 set_cr4(vcpu, mk_cr_64(vcpu->cr4, val));
1497                 break;
1498         default:
1499                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
1500         }
1501 }
1502
1503 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1504 {
1505         u64 data;
1506
1507         switch (msr) {
1508         case 0xc0010010: /* SYSCFG */
1509         case 0xc0010015: /* HWCR */
1510         case MSR_IA32_PLATFORM_ID:
1511         case MSR_IA32_P5_MC_ADDR:
1512         case MSR_IA32_P5_MC_TYPE:
1513         case MSR_IA32_MC0_CTL:
1514         case MSR_IA32_MCG_STATUS:
1515         case MSR_IA32_MCG_CAP:
1516         case MSR_IA32_MC0_MISC:
1517         case MSR_IA32_MC0_MISC+4:
1518         case MSR_IA32_MC0_MISC+8:
1519         case MSR_IA32_MC0_MISC+12:
1520         case MSR_IA32_MC0_MISC+16:
1521         case MSR_IA32_UCODE_REV:
1522         case MSR_IA32_PERF_STATUS:
1523         case MSR_IA32_EBL_CR_POWERON:
1524                 /* MTRR registers */
1525         case 0xfe:
1526         case 0x200 ... 0x2ff:
1527                 data = 0;
1528                 break;
1529         case 0xcd: /* fsb frequency */
1530                 data = 3;
1531                 break;
1532         case MSR_IA32_APICBASE:
1533                 data = kvm_get_apic_base(vcpu);
1534                 break;
1535         case MSR_IA32_MISC_ENABLE:
1536                 data = vcpu->ia32_misc_enable_msr;
1537                 break;
1538 #ifdef CONFIG_X86_64
1539         case MSR_EFER:
1540                 data = vcpu->shadow_efer;
1541                 break;
1542 #endif
1543         default:
1544                 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
1545                 return 1;
1546         }
1547         *pdata = data;
1548         return 0;
1549 }
1550 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
1551
1552 /*
1553  * Reads an msr value (of 'msr_index') into 'pdata'.
1554  * Returns 0 on success, non-0 otherwise.
1555  * Assumes vcpu_load() was already called.
1556  */
1557 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1558 {
1559         return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
1560 }
1561
1562 #ifdef CONFIG_X86_64
1563
1564 static void set_efer(struct kvm_vcpu *vcpu, u64 efer)
1565 {
1566         if (efer & EFER_RESERVED_BITS) {
1567                 printk(KERN_DEBUG "set_efer: 0x%llx #GP, reserved bits\n",
1568                        efer);
1569                 inject_gp(vcpu);
1570                 return;
1571         }
1572
1573         if (is_paging(vcpu)
1574             && (vcpu->shadow_efer & EFER_LME) != (efer & EFER_LME)) {
1575                 printk(KERN_DEBUG "set_efer: #GP, change LME while paging\n");
1576                 inject_gp(vcpu);
1577                 return;
1578         }
1579
1580         kvm_x86_ops->set_efer(vcpu, efer);
1581
1582         efer &= ~EFER_LMA;
1583         efer |= vcpu->shadow_efer & EFER_LMA;
1584
1585         vcpu->shadow_efer = efer;
1586 }
1587
1588 #endif
1589
1590 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1591 {
1592         switch (msr) {
1593 #ifdef CONFIG_X86_64
1594         case MSR_EFER:
1595                 set_efer(vcpu, data);
1596                 break;
1597 #endif
1598         case MSR_IA32_MC0_STATUS:
1599                 pr_unimpl(vcpu, "%s: MSR_IA32_MC0_STATUS 0x%llx, nop\n",
1600                        __FUNCTION__, data);
1601                 break;
1602         case MSR_IA32_MCG_STATUS:
1603                 pr_unimpl(vcpu, "%s: MSR_IA32_MCG_STATUS 0x%llx, nop\n",
1604                         __FUNCTION__, data);
1605                 break;
1606         case MSR_IA32_UCODE_REV:
1607         case MSR_IA32_UCODE_WRITE:
1608         case 0x200 ... 0x2ff: /* MTRRs */
1609                 break;
1610         case MSR_IA32_APICBASE:
1611                 kvm_set_apic_base(vcpu, data);
1612                 break;
1613         case MSR_IA32_MISC_ENABLE:
1614                 vcpu->ia32_misc_enable_msr = data;
1615                 break;
1616         default:
1617                 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x\n", msr);
1618                 return 1;
1619         }
1620         return 0;
1621 }
1622 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
1623
1624 /*
1625  * Writes msr value into into the appropriate "register".
1626  * Returns 0 on success, non-0 otherwise.
1627  * Assumes vcpu_load() was already called.
1628  */
1629 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
1630 {
1631         return kvm_x86_ops->set_msr(vcpu, msr_index, data);
1632 }
1633
1634 void kvm_resched(struct kvm_vcpu *vcpu)
1635 {
1636         if (!need_resched())
1637                 return;
1638         cond_resched();
1639 }
1640 EXPORT_SYMBOL_GPL(kvm_resched);
1641
1642 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
1643 {
1644         int i;
1645         u32 function;
1646         struct kvm_cpuid_entry *e, *best;
1647
1648         kvm_x86_ops->cache_regs(vcpu);
1649         function = vcpu->regs[VCPU_REGS_RAX];
1650         vcpu->regs[VCPU_REGS_RAX] = 0;
1651         vcpu->regs[VCPU_REGS_RBX] = 0;
1652         vcpu->regs[VCPU_REGS_RCX] = 0;
1653         vcpu->regs[VCPU_REGS_RDX] = 0;
1654         best = NULL;
1655         for (i = 0; i < vcpu->cpuid_nent; ++i) {
1656                 e = &vcpu->cpuid_entries[i];
1657                 if (e->function == function) {
1658                         best = e;
1659                         break;
1660                 }
1661                 /*
1662                  * Both basic or both extended?
1663                  */
1664                 if (((e->function ^ function) & 0x80000000) == 0)
1665                         if (!best || e->function > best->function)
1666                                 best = e;
1667         }
1668         if (best) {
1669                 vcpu->regs[VCPU_REGS_RAX] = best->eax;
1670                 vcpu->regs[VCPU_REGS_RBX] = best->ebx;
1671                 vcpu->regs[VCPU_REGS_RCX] = best->ecx;
1672                 vcpu->regs[VCPU_REGS_RDX] = best->edx;
1673         }
1674         kvm_x86_ops->decache_regs(vcpu);
1675         kvm_x86_ops->skip_emulated_instruction(vcpu);
1676 }
1677 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
1678
1679 static int pio_copy_data(struct kvm_vcpu *vcpu)
1680 {
1681         void *p = vcpu->pio_data;
1682         void *q;
1683         unsigned bytes;
1684         int nr_pages = vcpu->pio.guest_pages[1] ? 2 : 1;
1685
1686         q = vmap(vcpu->pio.guest_pages, nr_pages, VM_READ|VM_WRITE,
1687                  PAGE_KERNEL);
1688         if (!q) {
1689                 free_pio_guest_pages(vcpu);
1690                 return -ENOMEM;
1691         }
1692         q += vcpu->pio.guest_page_offset;
1693         bytes = vcpu->pio.size * vcpu->pio.cur_count;
1694         if (vcpu->pio.in)
1695                 memcpy(q, p, bytes);
1696         else
1697                 memcpy(p, q, bytes);
1698         q -= vcpu->pio.guest_page_offset;
1699         vunmap(q);
1700         free_pio_guest_pages(vcpu);
1701         return 0;
1702 }
1703
1704 static int complete_pio(struct kvm_vcpu *vcpu)
1705 {
1706         struct kvm_pio_request *io = &vcpu->pio;
1707         long delta;
1708         int r;
1709
1710         kvm_x86_ops->cache_regs(vcpu);
1711
1712         if (!io->string) {
1713                 if (io->in)
1714                         memcpy(&vcpu->regs[VCPU_REGS_RAX], vcpu->pio_data,
1715                                io->size);
1716         } else {
1717                 if (io->in) {
1718                         r = pio_copy_data(vcpu);
1719                         if (r) {
1720                                 kvm_x86_ops->cache_regs(vcpu);
1721                                 return r;
1722                         }
1723                 }
1724
1725                 delta = 1;
1726                 if (io->rep) {
1727                         delta *= io->cur_count;
1728                         /*
1729                          * The size of the register should really depend on
1730                          * current address size.
1731                          */
1732                         vcpu->regs[VCPU_REGS_RCX] -= delta;
1733                 }
1734                 if (io->down)
1735                         delta = -delta;
1736                 delta *= io->size;
1737                 if (io->in)
1738                         vcpu->regs[VCPU_REGS_RDI] += delta;
1739                 else
1740                         vcpu->regs[VCPU_REGS_RSI] += delta;
1741         }
1742
1743         kvm_x86_ops->decache_regs(vcpu);
1744
1745         io->count -= io->cur_count;
1746         io->cur_count = 0;
1747
1748         return 0;
1749 }
1750
1751 static void kernel_pio(struct kvm_io_device *pio_dev,
1752                        struct kvm_vcpu *vcpu,
1753                        void *pd)
1754 {
1755         /* TODO: String I/O for in kernel device */
1756
1757         mutex_lock(&vcpu->kvm->lock);
1758         if (vcpu->pio.in)
1759                 kvm_iodevice_read(pio_dev, vcpu->pio.port,
1760                                   vcpu->pio.size,
1761                                   pd);
1762         else
1763                 kvm_iodevice_write(pio_dev, vcpu->pio.port,
1764                                    vcpu->pio.size,
1765                                    pd);
1766         mutex_unlock(&vcpu->kvm->lock);
1767 }
1768
1769 static void pio_string_write(struct kvm_io_device *pio_dev,
1770                              struct kvm_vcpu *vcpu)
1771 {
1772         struct kvm_pio_request *io = &vcpu->pio;
1773         void *pd = vcpu->pio_data;
1774         int i;
1775
1776         mutex_lock(&vcpu->kvm->lock);
1777         for (i = 0; i < io->cur_count; i++) {
1778                 kvm_iodevice_write(pio_dev, io->port,
1779                                    io->size,
1780                                    pd);
1781                 pd += io->size;
1782         }
1783         mutex_unlock(&vcpu->kvm->lock);
1784 }
1785
1786 int kvm_emulate_pio (struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
1787                   int size, unsigned port)
1788 {
1789         struct kvm_io_device *pio_dev;
1790
1791         vcpu->run->exit_reason = KVM_EXIT_IO;
1792         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
1793         vcpu->run->io.size = vcpu->pio.size = size;
1794         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
1795         vcpu->run->io.count = vcpu->pio.count = vcpu->pio.cur_count = 1;
1796         vcpu->run->io.port = vcpu->pio.port = port;
1797         vcpu->pio.in = in;
1798         vcpu->pio.string = 0;
1799         vcpu->pio.down = 0;
1800         vcpu->pio.guest_page_offset = 0;
1801         vcpu->pio.rep = 0;
1802
1803         kvm_x86_ops->cache_regs(vcpu);
1804         memcpy(vcpu->pio_data, &vcpu->regs[VCPU_REGS_RAX], 4);
1805         kvm_x86_ops->decache_regs(vcpu);
1806
1807         kvm_x86_ops->skip_emulated_instruction(vcpu);
1808
1809         pio_dev = vcpu_find_pio_dev(vcpu, port);
1810         if (pio_dev) {
1811                 kernel_pio(pio_dev, vcpu, vcpu->pio_data);
1812                 complete_pio(vcpu);
1813                 return 1;
1814         }
1815         return 0;
1816 }
1817 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
1818
1819 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
1820                   int size, unsigned long count, int down,
1821                   gva_t address, int rep, unsigned port)
1822 {
1823         unsigned now, in_page;
1824         int i, ret = 0;
1825         int nr_pages = 1;
1826         struct page *page;
1827         struct kvm_io_device *pio_dev;
1828
1829         vcpu->run->exit_reason = KVM_EXIT_IO;
1830         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
1831         vcpu->run->io.size = vcpu->pio.size = size;
1832         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
1833         vcpu->run->io.count = vcpu->pio.count = vcpu->pio.cur_count = count;
1834         vcpu->run->io.port = vcpu->pio.port = port;
1835         vcpu->pio.in = in;
1836         vcpu->pio.string = 1;
1837         vcpu->pio.down = down;
1838         vcpu->pio.guest_page_offset = offset_in_page(address);
1839         vcpu->pio.rep = rep;
1840
1841         if (!count) {
1842                 kvm_x86_ops->skip_emulated_instruction(vcpu);
1843                 return 1;
1844         }
1845
1846         if (!down)
1847                 in_page = PAGE_SIZE - offset_in_page(address);
1848         else
1849                 in_page = offset_in_page(address) + size;
1850         now = min(count, (unsigned long)in_page / size);
1851         if (!now) {
1852                 /*
1853                  * String I/O straddles page boundary.  Pin two guest pages
1854                  * so that we satisfy atomicity constraints.  Do just one
1855                  * transaction to avoid complexity.
1856                  */
1857                 nr_pages = 2;
1858                 now = 1;
1859         }
1860         if (down) {
1861                 /*
1862                  * String I/O in reverse.  Yuck.  Kill the guest, fix later.
1863                  */
1864                 pr_unimpl(vcpu, "guest string pio down\n");
1865                 inject_gp(vcpu);
1866                 return 1;
1867         }
1868         vcpu->run->io.count = now;
1869         vcpu->pio.cur_count = now;
1870
1871         if (vcpu->pio.cur_count == vcpu->pio.count)
1872                 kvm_x86_ops->skip_emulated_instruction(vcpu);
1873
1874         for (i = 0; i < nr_pages; ++i) {
1875                 mutex_lock(&vcpu->kvm->lock);
1876                 page = gva_to_page(vcpu, address + i * PAGE_SIZE);
1877                 if (page)
1878                         get_page(page);
1879                 vcpu->pio.guest_pages[i] = page;
1880                 mutex_unlock(&vcpu->kvm->lock);
1881                 if (!page) {
1882                         inject_gp(vcpu);
1883                         free_pio_guest_pages(vcpu);
1884                         return 1;
1885                 }
1886         }
1887
1888         pio_dev = vcpu_find_pio_dev(vcpu, port);
1889         if (!vcpu->pio.in) {
1890                 /* string PIO write */
1891                 ret = pio_copy_data(vcpu);
1892                 if (ret >= 0 && pio_dev) {
1893                         pio_string_write(pio_dev, vcpu);
1894                         complete_pio(vcpu);
1895                         if (vcpu->pio.count == 0)
1896                                 ret = 1;
1897                 }
1898         } else if (pio_dev)
1899                 pr_unimpl(vcpu, "no string pio read support yet, "
1900                        "port %x size %d count %ld\n",
1901                         port, size, count);
1902
1903         return ret;
1904 }
1905 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
1906
1907 /*
1908  * Check if userspace requested an interrupt window, and that the
1909  * interrupt window is open.
1910  *
1911  * No need to exit to userspace if we already have an interrupt queued.
1912  */
1913 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu,
1914                                           struct kvm_run *kvm_run)
1915 {
1916         return (!vcpu->irq_summary &&
1917                 kvm_run->request_interrupt_window &&
1918                 vcpu->interrupt_window_open &&
1919                 (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF));
1920 }
1921
1922 static void post_kvm_run_save(struct kvm_vcpu *vcpu,
1923                               struct kvm_run *kvm_run)
1924 {
1925         kvm_run->if_flag = (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
1926         kvm_run->cr8 = get_cr8(vcpu);
1927         kvm_run->apic_base = kvm_get_apic_base(vcpu);
1928         if (irqchip_in_kernel(vcpu->kvm))
1929                 kvm_run->ready_for_interrupt_injection = 1;
1930         else
1931                 kvm_run->ready_for_interrupt_injection =
1932                                         (vcpu->interrupt_window_open &&
1933                                          vcpu->irq_summary == 0);
1934 }
1935
1936 static int __vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
1937 {
1938         int r;
1939
1940         if (unlikely(vcpu->mp_state == VCPU_MP_STATE_SIPI_RECEIVED)) {
1941                 printk("vcpu %d received sipi with vector # %x\n",
1942                        vcpu->vcpu_id, vcpu->sipi_vector);
1943                 kvm_lapic_reset(vcpu);
1944                 kvm_x86_ops->vcpu_reset(vcpu);
1945                 vcpu->mp_state = VCPU_MP_STATE_RUNNABLE;
1946         }
1947
1948 preempted:
1949         if (vcpu->guest_debug.enabled)
1950                 kvm_x86_ops->guest_debug_pre(vcpu);
1951
1952 again:
1953         r = kvm_mmu_reload(vcpu);
1954         if (unlikely(r))
1955                 goto out;
1956
1957         preempt_disable();
1958
1959         kvm_x86_ops->prepare_guest_switch(vcpu);
1960         kvm_load_guest_fpu(vcpu);
1961
1962         local_irq_disable();
1963
1964         if (signal_pending(current)) {
1965                 local_irq_enable();
1966                 preempt_enable();
1967                 r = -EINTR;
1968                 kvm_run->exit_reason = KVM_EXIT_INTR;
1969                 ++vcpu->stat.signal_exits;
1970                 goto out;
1971         }
1972
1973         if (irqchip_in_kernel(vcpu->kvm))
1974                 kvm_x86_ops->inject_pending_irq(vcpu);
1975         else if (!vcpu->mmio_read_completed)
1976                 kvm_x86_ops->inject_pending_vectors(vcpu, kvm_run);
1977
1978         vcpu->guest_mode = 1;
1979         kvm_guest_enter();
1980
1981         if (vcpu->requests)
1982                 if (test_and_clear_bit(KVM_TLB_FLUSH, &vcpu->requests))
1983                         kvm_x86_ops->tlb_flush(vcpu);
1984
1985         kvm_x86_ops->run(vcpu, kvm_run);
1986
1987         vcpu->guest_mode = 0;
1988         local_irq_enable();
1989
1990         ++vcpu->stat.exits;
1991
1992         /*
1993          * We must have an instruction between local_irq_enable() and
1994          * kvm_guest_exit(), so the timer interrupt isn't delayed by
1995          * the interrupt shadow.  The stat.exits increment will do nicely.
1996          * But we need to prevent reordering, hence this barrier():
1997          */
1998         barrier();
1999
2000         kvm_guest_exit();
2001
2002         preempt_enable();
2003
2004         /*
2005          * Profile KVM exit RIPs:
2006          */
2007         if (unlikely(prof_on == KVM_PROFILING)) {
2008                 kvm_x86_ops->cache_regs(vcpu);
2009                 profile_hit(KVM_PROFILING, (void *)vcpu->rip);
2010         }
2011
2012         r = kvm_x86_ops->handle_exit(kvm_run, vcpu);
2013
2014         if (r > 0) {
2015                 if (dm_request_for_irq_injection(vcpu, kvm_run)) {
2016                         r = -EINTR;
2017                         kvm_run->exit_reason = KVM_EXIT_INTR;
2018                         ++vcpu->stat.request_irq_exits;
2019                         goto out;
2020                 }
2021                 if (!need_resched()) {
2022                         ++vcpu->stat.light_exits;
2023                         goto again;
2024                 }
2025         }
2026
2027 out:
2028         if (r > 0) {
2029                 kvm_resched(vcpu);
2030                 goto preempted;
2031         }
2032
2033         post_kvm_run_save(vcpu, kvm_run);
2034
2035         return r;
2036 }
2037
2038
2039 static int kvm_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2040 {
2041         int r;
2042         sigset_t sigsaved;
2043
2044         vcpu_load(vcpu);
2045
2046         if (unlikely(vcpu->mp_state == VCPU_MP_STATE_UNINITIALIZED)) {
2047                 kvm_vcpu_block(vcpu);
2048                 vcpu_put(vcpu);
2049                 return -EAGAIN;
2050         }
2051
2052         if (vcpu->sigset_active)
2053                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
2054
2055         /* re-sync apic's tpr */
2056         if (!irqchip_in_kernel(vcpu->kvm))
2057                 set_cr8(vcpu, kvm_run->cr8);
2058
2059         if (vcpu->pio.cur_count) {
2060                 r = complete_pio(vcpu);
2061                 if (r)
2062                         goto out;
2063         }
2064
2065         if (vcpu->mmio_needed) {
2066                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
2067                 vcpu->mmio_read_completed = 1;
2068                 vcpu->mmio_needed = 0;
2069                 r = emulate_instruction(vcpu, kvm_run,
2070                                         vcpu->mmio_fault_cr2, 0, 1);
2071                 if (r == EMULATE_DO_MMIO) {
2072                         /*
2073                          * Read-modify-write.  Back to userspace.
2074                          */
2075                         r = 0;
2076                         goto out;
2077                 }
2078         }
2079
2080         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL) {
2081                 kvm_x86_ops->cache_regs(vcpu);
2082                 vcpu->regs[VCPU_REGS_RAX] = kvm_run->hypercall.ret;
2083                 kvm_x86_ops->decache_regs(vcpu);
2084         }
2085
2086         r = __vcpu_run(vcpu, kvm_run);
2087
2088 out:
2089         if (vcpu->sigset_active)
2090                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
2091
2092         vcpu_put(vcpu);
2093         return r;
2094 }
2095
2096 static int kvm_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu,
2097                                    struct kvm_regs *regs)
2098 {
2099         vcpu_load(vcpu);
2100
2101         kvm_x86_ops->cache_regs(vcpu);
2102
2103         regs->rax = vcpu->regs[VCPU_REGS_RAX];
2104         regs->rbx = vcpu->regs[VCPU_REGS_RBX];
2105         regs->rcx = vcpu->regs[VCPU_REGS_RCX];
2106         regs->rdx = vcpu->regs[VCPU_REGS_RDX];
2107         regs->rsi = vcpu->regs[VCPU_REGS_RSI];
2108         regs->rdi = vcpu->regs[VCPU_REGS_RDI];
2109         regs->rsp = vcpu->regs[VCPU_REGS_RSP];
2110         regs->rbp = vcpu->regs[VCPU_REGS_RBP];
2111 #ifdef CONFIG_X86_64
2112         regs->r8 = vcpu->regs[VCPU_REGS_R8];
2113         regs->r9 = vcpu->regs[VCPU_REGS_R9];
2114         regs->r10 = vcpu->regs[VCPU_REGS_R10];
2115         regs->r11 = vcpu->regs[VCPU_REGS_R11];
2116         regs->r12 = vcpu->regs[VCPU_REGS_R12];
2117         regs->r13 = vcpu->regs[VCPU_REGS_R13];
2118         regs->r14 = vcpu->regs[VCPU_REGS_R14];
2119         regs->r15 = vcpu->regs[VCPU_REGS_R15];
2120 #endif
2121
2122         regs->rip = vcpu->rip;
2123         regs->rflags = kvm_x86_ops->get_rflags(vcpu);
2124
2125         /*
2126          * Don't leak debug flags in case they were set for guest debugging
2127          */
2128         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
2129                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
2130
2131         vcpu_put(vcpu);
2132
2133         return 0;
2134 }
2135
2136 static int kvm_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu,
2137                                    struct kvm_regs *regs)
2138 {
2139         vcpu_load(vcpu);
2140
2141         vcpu->regs[VCPU_REGS_RAX] = regs->rax;
2142         vcpu->regs[VCPU_REGS_RBX] = regs->rbx;
2143         vcpu->regs[VCPU_REGS_RCX] = regs->rcx;
2144         vcpu->regs[VCPU_REGS_RDX] = regs->rdx;
2145         vcpu->regs[VCPU_REGS_RSI] = regs->rsi;
2146         vcpu->regs[VCPU_REGS_RDI] = regs->rdi;
2147         vcpu->regs[VCPU_REGS_RSP] = regs->rsp;
2148         vcpu->regs[VCPU_REGS_RBP] = regs->rbp;
2149 #ifdef CONFIG_X86_64
2150         vcpu->regs[VCPU_REGS_R8] = regs->r8;
2151         vcpu->regs[VCPU_REGS_R9] = regs->r9;
2152         vcpu->regs[VCPU_REGS_R10] = regs->r10;
2153         vcpu->regs[VCPU_REGS_R11] = regs->r11;
2154         vcpu->regs[VCPU_REGS_R12] = regs->r12;
2155         vcpu->regs[VCPU_REGS_R13] = regs->r13;
2156         vcpu->regs[VCPU_REGS_R14] = regs->r14;
2157         vcpu->regs[VCPU_REGS_R15] = regs->r15;
2158 #endif
2159
2160         vcpu->rip = regs->rip;
2161         kvm_x86_ops->set_rflags(vcpu, regs->rflags);
2162
2163         kvm_x86_ops->decache_regs(vcpu);
2164
2165         vcpu_put(vcpu);
2166
2167         return 0;
2168 }
2169
2170 static void get_segment(struct kvm_vcpu *vcpu,
2171                         struct kvm_segment *var, int seg)
2172 {
2173         return kvm_x86_ops->get_segment(vcpu, var, seg);
2174 }
2175
2176 static int kvm_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
2177                                     struct kvm_sregs *sregs)
2178 {
2179         struct descriptor_table dt;
2180         int pending_vec;
2181
2182         vcpu_load(vcpu);
2183
2184         get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
2185         get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
2186         get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
2187         get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
2188         get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
2189         get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
2190
2191         get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
2192         get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
2193
2194         kvm_x86_ops->get_idt(vcpu, &dt);
2195         sregs->idt.limit = dt.limit;
2196         sregs->idt.base = dt.base;
2197         kvm_x86_ops->get_gdt(vcpu, &dt);
2198         sregs->gdt.limit = dt.limit;
2199         sregs->gdt.base = dt.base;
2200
2201         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2202         sregs->cr0 = vcpu->cr0;
2203         sregs->cr2 = vcpu->cr2;
2204         sregs->cr3 = vcpu->cr3;
2205         sregs->cr4 = vcpu->cr4;
2206         sregs->cr8 = get_cr8(vcpu);
2207         sregs->efer = vcpu->shadow_efer;
2208         sregs->apic_base = kvm_get_apic_base(vcpu);
2209
2210         if (irqchip_in_kernel(vcpu->kvm)) {
2211                 memset(sregs->interrupt_bitmap, 0,
2212                        sizeof sregs->interrupt_bitmap);
2213                 pending_vec = kvm_x86_ops->get_irq(vcpu);
2214                 if (pending_vec >= 0)
2215                         set_bit(pending_vec, (unsigned long *)sregs->interrupt_bitmap);
2216         } else
2217                 memcpy(sregs->interrupt_bitmap, vcpu->irq_pending,
2218                        sizeof sregs->interrupt_bitmap);
2219
2220         vcpu_put(vcpu);
2221
2222         return 0;
2223 }
2224
2225 static void set_segment(struct kvm_vcpu *vcpu,
2226                         struct kvm_segment *var, int seg)
2227 {
2228         return kvm_x86_ops->set_segment(vcpu, var, seg);
2229 }
2230
2231 static int kvm_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
2232                                     struct kvm_sregs *sregs)
2233 {
2234         int mmu_reset_needed = 0;
2235         int i, pending_vec, max_bits;
2236         struct descriptor_table dt;
2237
2238         vcpu_load(vcpu);
2239
2240         dt.limit = sregs->idt.limit;
2241         dt.base = sregs->idt.base;
2242         kvm_x86_ops->set_idt(vcpu, &dt);
2243         dt.limit = sregs->gdt.limit;
2244         dt.base = sregs->gdt.base;
2245         kvm_x86_ops->set_gdt(vcpu, &dt);
2246
2247         vcpu->cr2 = sregs->cr2;
2248         mmu_reset_needed |= vcpu->cr3 != sregs->cr3;
2249         vcpu->cr3 = sregs->cr3;
2250
2251         set_cr8(vcpu, sregs->cr8);
2252
2253         mmu_reset_needed |= vcpu->shadow_efer != sregs->efer;
2254 #ifdef CONFIG_X86_64
2255         kvm_x86_ops->set_efer(vcpu, sregs->efer);
2256 #endif
2257         kvm_set_apic_base(vcpu, sregs->apic_base);
2258
2259         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2260
2261         mmu_reset_needed |= vcpu->cr0 != sregs->cr0;
2262         vcpu->cr0 = sregs->cr0;
2263         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
2264
2265         mmu_reset_needed |= vcpu->cr4 != sregs->cr4;
2266         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
2267         if (!is_long_mode(vcpu) && is_pae(vcpu))
2268                 load_pdptrs(vcpu, vcpu->cr3);
2269
2270         if (mmu_reset_needed)
2271                 kvm_mmu_reset_context(vcpu);
2272
2273         if (!irqchip_in_kernel(vcpu->kvm)) {
2274                 memcpy(vcpu->irq_pending, sregs->interrupt_bitmap,
2275                        sizeof vcpu->irq_pending);
2276                 vcpu->irq_summary = 0;
2277                 for (i = 0; i < ARRAY_SIZE(vcpu->irq_pending); ++i)
2278                         if (vcpu->irq_pending[i])
2279                                 __set_bit(i, &vcpu->irq_summary);
2280         } else {
2281                 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
2282                 pending_vec = find_first_bit(
2283                         (const unsigned long *)sregs->interrupt_bitmap,
2284                         max_bits);
2285                 /* Only pending external irq is handled here */
2286                 if (pending_vec < max_bits) {
2287                         kvm_x86_ops->set_irq(vcpu, pending_vec);
2288                         printk("Set back pending irq %d\n", pending_vec);
2289                 }
2290         }
2291
2292         set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
2293         set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
2294         set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
2295         set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
2296         set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
2297         set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
2298
2299         set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
2300         set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
2301
2302         vcpu_put(vcpu);
2303
2304         return 0;
2305 }
2306
2307 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
2308 {
2309         struct kvm_segment cs;
2310
2311         get_segment(vcpu, &cs, VCPU_SREG_CS);
2312         *db = cs.db;
2313         *l = cs.l;
2314 }
2315 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
2316
2317 /*
2318  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
2319  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
2320  *
2321  * This list is modified at module load time to reflect the
2322  * capabilities of the host cpu.
2323  */
2324 static u32 msrs_to_save[] = {
2325         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
2326         MSR_K6_STAR,
2327 #ifdef CONFIG_X86_64
2328         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
2329 #endif
2330         MSR_IA32_TIME_STAMP_COUNTER,
2331 };
2332
2333 static unsigned num_msrs_to_save;
2334
2335 static u32 emulated_msrs[] = {
2336         MSR_IA32_MISC_ENABLE,
2337 };
2338
2339 static __init void kvm_init_msr_list(void)
2340 {
2341         u32 dummy[2];
2342         unsigned i, j;
2343
2344         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
2345                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
2346                         continue;
2347                 if (j < i)
2348                         msrs_to_save[j] = msrs_to_save[i];
2349                 j++;
2350         }
2351         num_msrs_to_save = j;
2352 }
2353
2354 /*
2355  * Adapt set_msr() to msr_io()'s calling convention
2356  */
2357 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2358 {
2359         return kvm_set_msr(vcpu, index, *data);
2360 }
2361
2362 /*
2363  * Read or write a bunch of msrs. All parameters are kernel addresses.
2364  *
2365  * @return number of msrs set successfully.
2366  */
2367 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2368                     struct kvm_msr_entry *entries,
2369                     int (*do_msr)(struct kvm_vcpu *vcpu,
2370                                   unsigned index, u64 *data))
2371 {
2372         int i;
2373
2374         vcpu_load(vcpu);
2375
2376         for (i = 0; i < msrs->nmsrs; ++i)
2377                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2378                         break;
2379
2380         vcpu_put(vcpu);
2381
2382         return i;
2383 }
2384
2385 /*
2386  * Read or write a bunch of msrs. Parameters are user addresses.
2387  *
2388  * @return number of msrs set successfully.
2389  */
2390 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2391                   int (*do_msr)(struct kvm_vcpu *vcpu,
2392                                 unsigned index, u64 *data),
2393                   int writeback)
2394 {
2395         struct kvm_msrs msrs;
2396         struct kvm_msr_entry *entries;
2397         int r, n;
2398         unsigned size;
2399
2400         r = -EFAULT;
2401         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2402                 goto out;
2403
2404         r = -E2BIG;
2405         if (msrs.nmsrs >= MAX_IO_MSRS)
2406                 goto out;
2407
2408         r = -ENOMEM;
2409         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2410         entries = vmalloc(size);
2411         if (!entries)
2412                 goto out;
2413
2414         r = -EFAULT;
2415         if (copy_from_user(entries, user_msrs->entries, size))
2416                 goto out_free;
2417
2418         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2419         if (r < 0)
2420                 goto out_free;
2421
2422         r = -EFAULT;
2423         if (writeback && copy_to_user(user_msrs->entries, entries, size))
2424                 goto out_free;
2425
2426         r = n;
2427
2428 out_free:
2429         vfree(entries);
2430 out:
2431         return r;
2432 }
2433
2434 /*
2435  * Translate a guest virtual address to a guest physical address.
2436  */
2437 static int kvm_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
2438                                     struct kvm_translation *tr)
2439 {
2440         unsigned long vaddr = tr->linear_address;
2441         gpa_t gpa;
2442
2443         vcpu_load(vcpu);
2444         mutex_lock(&vcpu->kvm->lock);
2445         gpa = vcpu->mmu.gva_to_gpa(vcpu, vaddr);
2446         tr->physical_address = gpa;
2447         tr->valid = gpa != UNMAPPED_GVA;
2448         tr->writeable = 1;
2449         tr->usermode = 0;
2450         mutex_unlock(&vcpu->kvm->lock);
2451         vcpu_put(vcpu);
2452
2453         return 0;
2454 }
2455
2456 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2457                                     struct kvm_interrupt *irq)
2458 {
2459         if (irq->irq < 0 || irq->irq >= 256)
2460                 return -EINVAL;
2461         if (irqchip_in_kernel(vcpu->kvm))
2462                 return -ENXIO;
2463         vcpu_load(vcpu);
2464
2465         set_bit(irq->irq, vcpu->irq_pending);
2466         set_bit(irq->irq / BITS_PER_LONG, &vcpu->irq_summary);
2467
2468         vcpu_put(vcpu);
2469
2470         return 0;
2471 }
2472
2473 static int kvm_vcpu_ioctl_debug_guest(struct kvm_vcpu *vcpu,
2474                                       struct kvm_debug_guest *dbg)
2475 {
2476         int r;
2477
2478         vcpu_load(vcpu);
2479
2480         r = kvm_x86_ops->set_guest_debug(vcpu, dbg);
2481
2482         vcpu_put(vcpu);
2483
2484         return r;
2485 }
2486
2487 static struct page *kvm_vcpu_nopage(struct vm_area_struct *vma,
2488                                     unsigned long address,
2489                                     int *type)
2490 {
2491         struct kvm_vcpu *vcpu = vma->vm_file->private_data;
2492         unsigned long pgoff;
2493         struct page *page;
2494
2495         pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
2496         if (pgoff == 0)
2497                 page = virt_to_page(vcpu->run);
2498         else if (pgoff == KVM_PIO_PAGE_OFFSET)
2499                 page = virt_to_page(vcpu->pio_data);
2500         else
2501                 return NOPAGE_SIGBUS;
2502         get_page(page);
2503         if (type != NULL)
2504                 *type = VM_FAULT_MINOR;
2505
2506         return page;
2507 }
2508
2509 static struct vm_operations_struct kvm_vcpu_vm_ops = {
2510         .nopage = kvm_vcpu_nopage,
2511 };
2512
2513 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2514 {
2515         vma->vm_ops = &kvm_vcpu_vm_ops;
2516         return 0;
2517 }
2518
2519 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2520 {
2521         struct kvm_vcpu *vcpu = filp->private_data;
2522
2523         fput(vcpu->kvm->filp);
2524         return 0;
2525 }
2526
2527 static struct file_operations kvm_vcpu_fops = {
2528         .release        = kvm_vcpu_release,
2529         .unlocked_ioctl = kvm_vcpu_ioctl,
2530         .compat_ioctl   = kvm_vcpu_ioctl,
2531         .mmap           = kvm_vcpu_mmap,
2532 };
2533
2534 /*
2535  * Allocates an inode for the vcpu.
2536  */
2537 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2538 {
2539         int fd, r;
2540         struct inode *inode;
2541         struct file *file;
2542
2543         r = anon_inode_getfd(&fd, &inode, &file,
2544                              "kvm-vcpu", &kvm_vcpu_fops, vcpu);
2545         if (r)
2546                 return r;
2547         atomic_inc(&vcpu->kvm->filp->f_count);
2548         return fd;
2549 }
2550
2551 /*
2552  * Creates some virtual cpus.  Good luck creating more than one.
2553  */
2554 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, int n)
2555 {
2556         int r;
2557         struct kvm_vcpu *vcpu;
2558
2559         if (!valid_vcpu(n))
2560                 return -EINVAL;
2561
2562         vcpu = kvm_x86_ops->vcpu_create(kvm, n);
2563         if (IS_ERR(vcpu))
2564                 return PTR_ERR(vcpu);
2565
2566         preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
2567
2568         /* We do fxsave: this must be aligned. */
2569         BUG_ON((unsigned long)&vcpu->host_fx_image & 0xF);
2570
2571         vcpu_load(vcpu);
2572         r = kvm_mmu_setup(vcpu);
2573         vcpu_put(vcpu);
2574         if (r < 0)
2575                 goto free_vcpu;
2576
2577         mutex_lock(&kvm->lock);
2578         if (kvm->vcpus[n]) {
2579                 r = -EEXIST;
2580                 mutex_unlock(&kvm->lock);
2581                 goto mmu_unload;
2582         }
2583         kvm->vcpus[n] = vcpu;
2584         mutex_unlock(&kvm->lock);
2585
2586         /* Now it's all set up, let userspace reach it */
2587         r = create_vcpu_fd(vcpu);
2588         if (r < 0)
2589                 goto unlink;
2590         return r;
2591
2592 unlink:
2593         mutex_lock(&kvm->lock);
2594         kvm->vcpus[n] = NULL;
2595         mutex_unlock(&kvm->lock);
2596
2597 mmu_unload:
2598         vcpu_load(vcpu);
2599         kvm_mmu_unload(vcpu);
2600         vcpu_put(vcpu);
2601
2602 free_vcpu:
2603         kvm_x86_ops->vcpu_free(vcpu);
2604         return r;
2605 }
2606
2607 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
2608 {
2609         u64 efer;
2610         int i;
2611         struct kvm_cpuid_entry *e, *entry;
2612
2613         rdmsrl(MSR_EFER, efer);
2614         entry = NULL;
2615         for (i = 0; i < vcpu->cpuid_nent; ++i) {
2616                 e = &vcpu->cpuid_entries[i];
2617                 if (e->function == 0x80000001) {
2618                         entry = e;
2619                         break;
2620                 }
2621         }
2622         if (entry && (entry->edx & (1 << 20)) && !(efer & EFER_NX)) {
2623                 entry->edx &= ~(1 << 20);
2624                 printk(KERN_INFO "kvm: guest NX capability removed\n");
2625         }
2626 }
2627
2628 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
2629                                     struct kvm_cpuid *cpuid,
2630                                     struct kvm_cpuid_entry __user *entries)
2631 {
2632         int r;
2633
2634         r = -E2BIG;
2635         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2636                 goto out;
2637         r = -EFAULT;
2638         if (copy_from_user(&vcpu->cpuid_entries, entries,
2639                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
2640                 goto out;
2641         vcpu->cpuid_nent = cpuid->nent;
2642         cpuid_fix_nx_cap(vcpu);
2643         return 0;
2644
2645 out:
2646         return r;
2647 }
2648
2649 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
2650 {
2651         if (sigset) {
2652                 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
2653                 vcpu->sigset_active = 1;
2654                 vcpu->sigset = *sigset;
2655         } else
2656                 vcpu->sigset_active = 0;
2657         return 0;
2658 }
2659
2660 /*
2661  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
2662  * we have asm/x86/processor.h
2663  */
2664 struct fxsave {
2665         u16     cwd;
2666         u16     swd;
2667         u16     twd;
2668         u16     fop;
2669         u64     rip;
2670         u64     rdp;
2671         u32     mxcsr;
2672         u32     mxcsr_mask;
2673         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
2674 #ifdef CONFIG_X86_64
2675         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
2676 #else
2677         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
2678 #endif
2679 };
2680
2681 static int kvm_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2682 {
2683         struct fxsave *fxsave = (struct fxsave *)&vcpu->guest_fx_image;
2684
2685         vcpu_load(vcpu);
2686
2687         memcpy(fpu->fpr, fxsave->st_space, 128);
2688         fpu->fcw = fxsave->cwd;
2689         fpu->fsw = fxsave->swd;
2690         fpu->ftwx = fxsave->twd;
2691         fpu->last_opcode = fxsave->fop;
2692         fpu->last_ip = fxsave->rip;
2693         fpu->last_dp = fxsave->rdp;
2694         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
2695
2696         vcpu_put(vcpu);
2697
2698         return 0;
2699 }
2700
2701 static int kvm_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2702 {
2703         struct fxsave *fxsave = (struct fxsave *)&vcpu->guest_fx_image;
2704
2705         vcpu_load(vcpu);
2706
2707         memcpy(fxsave->st_space, fpu->fpr, 128);
2708         fxsave->cwd = fpu->fcw;
2709         fxsave->swd = fpu->fsw;
2710         fxsave->twd = fpu->ftwx;
2711         fxsave->fop = fpu->last_opcode;
2712         fxsave->rip = fpu->last_ip;
2713         fxsave->rdp = fpu->last_dp;
2714         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
2715
2716         vcpu_put(vcpu);
2717
2718         return 0;
2719 }
2720
2721 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2722                                     struct kvm_lapic_state *s)
2723 {
2724         vcpu_load(vcpu);
2725         memcpy(s->regs, vcpu->apic->regs, sizeof *s);
2726         vcpu_put(vcpu);
2727
2728         return 0;
2729 }
2730
2731 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2732                                     struct kvm_lapic_state *s)
2733 {
2734         vcpu_load(vcpu);
2735         memcpy(vcpu->apic->regs, s->regs, sizeof *s);
2736         kvm_apic_post_state_restore(vcpu);
2737         vcpu_put(vcpu);
2738
2739         return 0;
2740 }
2741
2742 static long kvm_vcpu_ioctl(struct file *filp,
2743                            unsigned int ioctl, unsigned long arg)
2744 {
2745         struct kvm_vcpu *vcpu = filp->private_data;
2746         void __user *argp = (void __user *)arg;
2747         int r = -EINVAL;
2748
2749         switch (ioctl) {
2750         case KVM_RUN:
2751                 r = -EINVAL;
2752                 if (arg)
2753                         goto out;
2754                 r = kvm_vcpu_ioctl_run(vcpu, vcpu->run);
2755                 break;
2756         case KVM_GET_REGS: {
2757                 struct kvm_regs kvm_regs;
2758
2759                 memset(&kvm_regs, 0, sizeof kvm_regs);
2760                 r = kvm_vcpu_ioctl_get_regs(vcpu, &kvm_regs);
2761                 if (r)
2762                         goto out;
2763                 r = -EFAULT;
2764                 if (copy_to_user(argp, &kvm_regs, sizeof kvm_regs))
2765                         goto out;
2766                 r = 0;
2767                 break;
2768         }
2769         case KVM_SET_REGS: {
2770                 struct kvm_regs kvm_regs;
2771
2772                 r = -EFAULT;
2773                 if (copy_from_user(&kvm_regs, argp, sizeof kvm_regs))
2774                         goto out;
2775                 r = kvm_vcpu_ioctl_set_regs(vcpu, &kvm_regs);
2776                 if (r)
2777                         goto out;
2778                 r = 0;
2779                 break;
2780         }
2781         case KVM_GET_SREGS: {
2782                 struct kvm_sregs kvm_sregs;
2783
2784                 memset(&kvm_sregs, 0, sizeof kvm_sregs);
2785                 r = kvm_vcpu_ioctl_get_sregs(vcpu, &kvm_sregs);
2786                 if (r)
2787                         goto out;
2788                 r = -EFAULT;
2789                 if (copy_to_user(argp, &kvm_sregs, sizeof kvm_sregs))
2790                         goto out;
2791                 r = 0;
2792                 break;
2793         }
2794         case KVM_SET_SREGS: {
2795                 struct kvm_sregs kvm_sregs;
2796
2797                 r = -EFAULT;
2798                 if (copy_from_user(&kvm_sregs, argp, sizeof kvm_sregs))
2799                         goto out;
2800                 r = kvm_vcpu_ioctl_set_sregs(vcpu, &kvm_sregs);
2801                 if (r)
2802                         goto out;
2803                 r = 0;
2804                 break;
2805         }
2806         case KVM_TRANSLATE: {
2807                 struct kvm_translation tr;
2808
2809                 r = -EFAULT;
2810                 if (copy_from_user(&tr, argp, sizeof tr))
2811                         goto out;
2812                 r = kvm_vcpu_ioctl_translate(vcpu, &tr);
2813                 if (r)
2814                         goto out;
2815                 r = -EFAULT;
2816                 if (copy_to_user(argp, &tr, sizeof tr))
2817                         goto out;
2818                 r = 0;
2819                 break;
2820         }
2821         case KVM_INTERRUPT: {
2822                 struct kvm_interrupt irq;
2823
2824                 r = -EFAULT;
2825                 if (copy_from_user(&irq, argp, sizeof irq))
2826                         goto out;
2827                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
2828                 if (r)
2829                         goto out;
2830                 r = 0;
2831                 break;
2832         }
2833         case KVM_DEBUG_GUEST: {
2834                 struct kvm_debug_guest dbg;
2835
2836                 r = -EFAULT;
2837                 if (copy_from_user(&dbg, argp, sizeof dbg))
2838                         goto out;
2839                 r = kvm_vcpu_ioctl_debug_guest(vcpu, &dbg);
2840                 if (r)
2841                         goto out;
2842                 r = 0;
2843                 break;
2844         }
2845         case KVM_GET_MSRS:
2846                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
2847                 break;
2848         case KVM_SET_MSRS:
2849                 r = msr_io(vcpu, argp, do_set_msr, 0);
2850                 break;
2851         case KVM_SET_CPUID: {
2852                 struct kvm_cpuid __user *cpuid_arg = argp;
2853                 struct kvm_cpuid cpuid;
2854
2855                 r = -EFAULT;
2856                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2857                         goto out;
2858                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
2859                 if (r)
2860                         goto out;
2861                 break;
2862         }
2863         case KVM_SET_SIGNAL_MASK: {
2864                 struct kvm_signal_mask __user *sigmask_arg = argp;
2865                 struct kvm_signal_mask kvm_sigmask;
2866                 sigset_t sigset, *p;
2867
2868                 p = NULL;
2869                 if (argp) {
2870                         r = -EFAULT;
2871                         if (copy_from_user(&kvm_sigmask, argp,
2872                                            sizeof kvm_sigmask))
2873                                 goto out;
2874                         r = -EINVAL;
2875                         if (kvm_sigmask.len != sizeof sigset)
2876                                 goto out;
2877                         r = -EFAULT;
2878                         if (copy_from_user(&sigset, sigmask_arg->sigset,
2879                                            sizeof sigset))
2880                                 goto out;
2881                         p = &sigset;
2882                 }
2883                 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
2884                 break;
2885         }
2886         case KVM_GET_FPU: {
2887                 struct kvm_fpu fpu;
2888
2889                 memset(&fpu, 0, sizeof fpu);
2890                 r = kvm_vcpu_ioctl_get_fpu(vcpu, &fpu);
2891                 if (r)
2892                         goto out;
2893                 r = -EFAULT;
2894                 if (copy_to_user(argp, &fpu, sizeof fpu))
2895                         goto out;
2896                 r = 0;
2897                 break;
2898         }
2899         case KVM_SET_FPU: {
2900                 struct kvm_fpu fpu;
2901
2902                 r = -EFAULT;
2903                 if (copy_from_user(&fpu, argp, sizeof fpu))
2904                         goto out;
2905                 r = kvm_vcpu_ioctl_set_fpu(vcpu, &fpu);
2906                 if (r)
2907                         goto out;
2908                 r = 0;
2909                 break;
2910         }
2911         case KVM_GET_LAPIC: {
2912                 struct kvm_lapic_state lapic;
2913
2914                 memset(&lapic, 0, sizeof lapic);
2915                 r = kvm_vcpu_ioctl_get_lapic(vcpu, &lapic);
2916                 if (r)
2917                         goto out;
2918                 r = -EFAULT;
2919                 if (copy_to_user(argp, &lapic, sizeof lapic))
2920                         goto out;
2921                 r = 0;
2922                 break;
2923         }
2924         case KVM_SET_LAPIC: {
2925                 struct kvm_lapic_state lapic;
2926
2927                 r = -EFAULT;
2928                 if (copy_from_user(&lapic, argp, sizeof lapic))
2929                         goto out;
2930                 r = kvm_vcpu_ioctl_set_lapic(vcpu, &lapic);;
2931                 if (r)
2932                         goto out;
2933                 r = 0;
2934                 break;
2935         }
2936         default:
2937                 ;
2938         }
2939 out:
2940         return r;
2941 }
2942
2943 static long kvm_vm_ioctl(struct file *filp,
2944                            unsigned int ioctl, unsigned long arg)
2945 {
2946         struct kvm *kvm = filp->private_data;
2947         void __user *argp = (void __user *)arg;
2948         int r = -EINVAL;
2949
2950         switch (ioctl) {
2951         case KVM_CREATE_VCPU:
2952                 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
2953                 if (r < 0)
2954                         goto out;
2955                 break;
2956         case KVM_SET_MEMORY_REGION: {
2957                 struct kvm_memory_region kvm_mem;
2958
2959                 r = -EFAULT;
2960                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
2961                         goto out;
2962                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_mem);
2963                 if (r)
2964                         goto out;
2965                 break;
2966         }
2967         case KVM_GET_DIRTY_LOG: {
2968                 struct kvm_dirty_log log;
2969
2970                 r = -EFAULT;
2971                 if (copy_from_user(&log, argp, sizeof log))
2972                         goto out;
2973                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
2974                 if (r)
2975                         goto out;
2976                 break;
2977         }
2978         case KVM_SET_MEMORY_ALIAS: {
2979                 struct kvm_memory_alias alias;
2980
2981                 r = -EFAULT;
2982                 if (copy_from_user(&alias, argp, sizeof alias))
2983                         goto out;
2984                 r = kvm_vm_ioctl_set_memory_alias(kvm, &alias);
2985                 if (r)
2986                         goto out;
2987                 break;
2988         }
2989         case KVM_CREATE_IRQCHIP:
2990                 r = -ENOMEM;
2991                 kvm->vpic = kvm_create_pic(kvm);
2992                 if (kvm->vpic) {
2993                         r = kvm_ioapic_init(kvm);
2994                         if (r) {
2995                                 kfree(kvm->vpic);
2996                                 kvm->vpic = NULL;
2997                                 goto out;
2998                         }
2999                 }
3000                 else
3001                         goto out;
3002                 break;
3003         case KVM_IRQ_LINE: {
3004                 struct kvm_irq_level irq_event;
3005
3006                 r = -EFAULT;
3007                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
3008                         goto out;
3009                 if (irqchip_in_kernel(kvm)) {
3010                         mutex_lock(&kvm->lock);
3011                         if (irq_event.irq < 16)
3012                                 kvm_pic_set_irq(pic_irqchip(kvm),
3013                                         irq_event.irq,
3014                                         irq_event.level);
3015                         kvm_ioapic_set_irq(kvm->vioapic,
3016                                         irq_event.irq,
3017                                         irq_event.level);
3018                         mutex_unlock(&kvm->lock);
3019                         r = 0;
3020                 }
3021                 break;
3022         }
3023         case KVM_GET_IRQCHIP: {
3024                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3025                 struct kvm_irqchip chip;
3026
3027                 r = -EFAULT;
3028                 if (copy_from_user(&chip, argp, sizeof chip))
3029                         goto out;
3030                 r = -ENXIO;
3031                 if (!irqchip_in_kernel(kvm))
3032                         goto out;
3033                 r = kvm_vm_ioctl_get_irqchip(kvm, &chip);
3034                 if (r)
3035                         goto out;
3036                 r = -EFAULT;
3037                 if (copy_to_user(argp, &chip, sizeof chip))
3038                         goto out;
3039                 r = 0;
3040                 break;
3041         }
3042         case KVM_SET_IRQCHIP: {
3043                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3044                 struct kvm_irqchip chip;
3045
3046                 r = -EFAULT;
3047                 if (copy_from_user(&chip, argp, sizeof chip))
3048                         goto out;
3049                 r = -ENXIO;
3050                 if (!irqchip_in_kernel(kvm))
3051                         goto out;
3052                 r = kvm_vm_ioctl_set_irqchip(kvm, &chip);
3053                 if (r)
3054                         goto out;
3055                 r = 0;
3056                 break;
3057         }
3058         default:
3059                 ;
3060         }
3061 out:
3062         return r;
3063 }
3064
3065 static struct page *kvm_vm_nopage(struct vm_area_struct *vma,
3066                                   unsigned long address,
3067                                   int *type)
3068 {
3069         struct kvm *kvm = vma->vm_file->private_data;
3070         unsigned long pgoff;
3071         struct page *page;
3072
3073         pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
3074         page = gfn_to_page(kvm, pgoff);
3075         if (!page)
3076                 return NOPAGE_SIGBUS;
3077         get_page(page);
3078         if (type != NULL)
3079                 *type = VM_FAULT_MINOR;
3080
3081         return page;
3082 }
3083
3084 static struct vm_operations_struct kvm_vm_vm_ops = {
3085         .nopage = kvm_vm_nopage,
3086 };
3087
3088 static int kvm_vm_mmap(struct file *file, struct vm_area_struct *vma)
3089 {
3090         vma->vm_ops = &kvm_vm_vm_ops;
3091         return 0;
3092 }
3093
3094 static struct file_operations kvm_vm_fops = {
3095         .release        = kvm_vm_release,
3096         .unlocked_ioctl = kvm_vm_ioctl,
3097         .compat_ioctl   = kvm_vm_ioctl,
3098         .mmap           = kvm_vm_mmap,
3099 };
3100
3101 static int kvm_dev_ioctl_create_vm(void)
3102 {
3103         int fd, r;
3104         struct inode *inode;
3105         struct file *file;
3106         struct kvm *kvm;
3107
3108         kvm = kvm_create_vm();
3109         if (IS_ERR(kvm))
3110                 return PTR_ERR(kvm);
3111         r = anon_inode_getfd(&fd, &inode, &file, "kvm-vm", &kvm_vm_fops, kvm);
3112         if (r) {
3113                 kvm_destroy_vm(kvm);
3114                 return r;
3115         }
3116
3117         kvm->filp = file;
3118
3119         return fd;
3120 }
3121
3122 static long kvm_dev_ioctl(struct file *filp,
3123                           unsigned int ioctl, unsigned long arg)
3124 {
3125         void __user *argp = (void __user *)arg;
3126         long r = -EINVAL;
3127
3128         switch (ioctl) {
3129         case KVM_GET_API_VERSION:
3130                 r = -EINVAL;
3131                 if (arg)
3132                         goto out;
3133                 r = KVM_API_VERSION;
3134                 break;
3135         case KVM_CREATE_VM:
3136                 r = -EINVAL;
3137                 if (arg)
3138                         goto out;
3139                 r = kvm_dev_ioctl_create_vm();
3140                 break;
3141         case KVM_GET_MSR_INDEX_LIST: {
3142                 struct kvm_msr_list __user *user_msr_list = argp;
3143                 struct kvm_msr_list msr_list;
3144                 unsigned n;
3145
3146                 r = -EFAULT;
3147                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
3148                         goto out;
3149                 n = msr_list.nmsrs;
3150                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
3151                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
3152                         goto out;
3153                 r = -E2BIG;
3154                 if (n < num_msrs_to_save)
3155                         goto out;
3156                 r = -EFAULT;
3157                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3158                                  num_msrs_to_save * sizeof(u32)))
3159                         goto out;
3160                 if (copy_to_user(user_msr_list->indices
3161                                  + num_msrs_to_save * sizeof(u32),
3162                                  &emulated_msrs,
3163                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
3164                         goto out;
3165                 r = 0;
3166                 break;
3167         }
3168         case KVM_CHECK_EXTENSION: {
3169                 int ext = (long)argp;
3170
3171                 switch (ext) {
3172                 case KVM_CAP_IRQCHIP:
3173                 case KVM_CAP_HLT:
3174                         r = 1;
3175                         break;
3176                 default:
3177                         r = 0;
3178                         break;
3179                 }
3180                 break;
3181         }
3182         case KVM_GET_VCPU_MMAP_SIZE:
3183                 r = -EINVAL;
3184                 if (arg)
3185                         goto out;
3186                 r = 2 * PAGE_SIZE;
3187                 break;
3188         default:
3189                 ;
3190         }
3191 out:
3192         return r;
3193 }
3194
3195 static struct file_operations kvm_chardev_ops = {
3196         .unlocked_ioctl = kvm_dev_ioctl,
3197         .compat_ioctl   = kvm_dev_ioctl,
3198 };
3199
3200 static struct miscdevice kvm_dev = {
3201         KVM_MINOR,
3202         "kvm",
3203         &kvm_chardev_ops,
3204 };
3205
3206 /*
3207  * Make sure that a cpu that is being hot-unplugged does not have any vcpus
3208  * cached on it.
3209  */
3210 static void decache_vcpus_on_cpu(int cpu)
3211 {
3212         struct kvm *vm;
3213         struct kvm_vcpu *vcpu;
3214         int i;
3215
3216         spin_lock(&kvm_lock);
3217         list_for_each_entry(vm, &vm_list, vm_list)
3218                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
3219                         vcpu = vm->vcpus[i];
3220                         if (!vcpu)
3221                                 continue;
3222                         /*
3223                          * If the vcpu is locked, then it is running on some
3224                          * other cpu and therefore it is not cached on the
3225                          * cpu in question.
3226                          *
3227                          * If it's not locked, check the last cpu it executed
3228                          * on.
3229                          */
3230                         if (mutex_trylock(&vcpu->mutex)) {
3231                                 if (vcpu->cpu == cpu) {
3232                                         kvm_x86_ops->vcpu_decache(vcpu);
3233                                         vcpu->cpu = -1;
3234                                 }
3235                                 mutex_unlock(&vcpu->mutex);
3236                         }
3237                 }
3238         spin_unlock(&kvm_lock);
3239 }
3240
3241 static void hardware_enable(void *junk)
3242 {
3243         int cpu = raw_smp_processor_id();
3244
3245         if (cpu_isset(cpu, cpus_hardware_enabled))
3246                 return;
3247         cpu_set(cpu, cpus_hardware_enabled);
3248         kvm_x86_ops->hardware_enable(NULL);
3249 }
3250
3251 static void hardware_disable(void *junk)
3252 {
3253         int cpu = raw_smp_processor_id();
3254
3255         if (!cpu_isset(cpu, cpus_hardware_enabled))
3256                 return;
3257         cpu_clear(cpu, cpus_hardware_enabled);
3258         decache_vcpus_on_cpu(cpu);
3259         kvm_x86_ops->hardware_disable(NULL);
3260 }
3261
3262 static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
3263                            void *v)
3264 {
3265         int cpu = (long)v;
3266
3267         switch (val) {
3268         case CPU_DYING:
3269         case CPU_DYING_FROZEN:
3270                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
3271                        cpu);
3272                 hardware_disable(NULL);
3273                 break;
3274         case CPU_UP_CANCELED:
3275         case CPU_UP_CANCELED_FROZEN:
3276                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
3277                        cpu);
3278                 smp_call_function_single(cpu, hardware_disable, NULL, 0, 1);
3279                 break;
3280         case CPU_ONLINE:
3281         case CPU_ONLINE_FROZEN:
3282                 printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
3283                        cpu);
3284                 smp_call_function_single(cpu, hardware_enable, NULL, 0, 1);
3285                 break;
3286         }
3287         return NOTIFY_OK;
3288 }
3289
3290 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
3291                        void *v)
3292 {
3293         if (val == SYS_RESTART) {
3294                 /*
3295                  * Some (well, at least mine) BIOSes hang on reboot if
3296                  * in vmx root mode.
3297                  */
3298                 printk(KERN_INFO "kvm: exiting hardware virtualization\n");
3299                 on_each_cpu(hardware_disable, NULL, 0, 1);
3300         }
3301         return NOTIFY_OK;
3302 }
3303
3304 static struct notifier_block kvm_reboot_notifier = {
3305         .notifier_call = kvm_reboot,
3306         .priority = 0,
3307 };
3308
3309 void kvm_io_bus_init(struct kvm_io_bus *bus)
3310 {
3311         memset(bus, 0, sizeof(*bus));
3312 }
3313
3314 void kvm_io_bus_destroy(struct kvm_io_bus *bus)
3315 {
3316         int i;
3317
3318         for (i = 0; i < bus->dev_count; i++) {
3319                 struct kvm_io_device *pos = bus->devs[i];
3320
3321                 kvm_iodevice_destructor(pos);
3322         }
3323 }
3324
3325 struct kvm_io_device *kvm_io_bus_find_dev(struct kvm_io_bus *bus, gpa_t addr)
3326 {
3327         int i;
3328
3329         for (i = 0; i < bus->dev_count; i++) {
3330                 struct kvm_io_device *pos = bus->devs[i];
3331
3332                 if (pos->in_range(pos, addr))
3333                         return pos;
3334         }
3335
3336         return NULL;
3337 }
3338
3339 void kvm_io_bus_register_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev)
3340 {
3341         BUG_ON(bus->dev_count > (NR_IOBUS_DEVS-1));
3342
3343         bus->devs[bus->dev_count++] = dev;
3344 }
3345
3346 static struct notifier_block kvm_cpu_notifier = {
3347         .notifier_call = kvm_cpu_hotplug,
3348         .priority = 20, /* must be > scheduler priority */
3349 };
3350
3351 static u64 stat_get(void *_offset)
3352 {
3353         unsigned offset = (long)_offset;
3354         u64 total = 0;
3355         struct kvm *kvm;
3356         struct kvm_vcpu *vcpu;
3357         int i;
3358
3359         spin_lock(&kvm_lock);
3360         list_for_each_entry(kvm, &vm_list, vm_list)
3361                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
3362                         vcpu = kvm->vcpus[i];
3363                         if (vcpu)
3364                                 total += *(u32 *)((void *)vcpu + offset);
3365                 }
3366         spin_unlock(&kvm_lock);
3367         return total;
3368 }
3369
3370 DEFINE_SIMPLE_ATTRIBUTE(stat_fops, stat_get, NULL, "%llu\n");
3371
3372 static __init void kvm_init_debug(void)
3373 {
3374         struct kvm_stats_debugfs_item *p;
3375
3376         debugfs_dir = debugfs_create_dir("kvm", NULL);
3377         for (p = debugfs_entries; p->name; ++p)
3378                 p->dentry = debugfs_create_file(p->name, 0444, debugfs_dir,
3379                                                 (void *)(long)p->offset,
3380                                                 &stat_fops);
3381 }
3382
3383 static void kvm_exit_debug(void)
3384 {
3385         struct kvm_stats_debugfs_item *p;
3386
3387         for (p = debugfs_entries; p->name; ++p)
3388                 debugfs_remove(p->dentry);
3389         debugfs_remove(debugfs_dir);
3390 }
3391
3392 static int kvm_suspend(struct sys_device *dev, pm_message_t state)
3393 {
3394         hardware_disable(NULL);
3395         return 0;
3396 }
3397
3398 static int kvm_resume(struct sys_device *dev)
3399 {
3400         hardware_enable(NULL);
3401         return 0;
3402 }
3403
3404 static struct sysdev_class kvm_sysdev_class = {
3405         .name = "kvm",
3406         .suspend = kvm_suspend,
3407         .resume = kvm_resume,
3408 };
3409
3410 static struct sys_device kvm_sysdev = {
3411         .id = 0,
3412         .cls = &kvm_sysdev_class,
3413 };
3414
3415 hpa_t bad_page_address;
3416
3417 static inline
3418 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
3419 {
3420         return container_of(pn, struct kvm_vcpu, preempt_notifier);
3421 }
3422
3423 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
3424 {
3425         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
3426
3427         kvm_x86_ops->vcpu_load(vcpu, cpu);
3428 }
3429
3430 static void kvm_sched_out(struct preempt_notifier *pn,
3431                           struct task_struct *next)
3432 {
3433         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
3434
3435         kvm_x86_ops->vcpu_put(vcpu);
3436 }
3437
3438 int kvm_init_x86(struct kvm_x86_ops *ops, unsigned int vcpu_size,
3439                   struct module *module)
3440 {
3441         int r;
3442         int cpu;
3443
3444         if (kvm_x86_ops) {
3445                 printk(KERN_ERR "kvm: already loaded the other module\n");
3446                 return -EEXIST;
3447         }
3448
3449         if (!ops->cpu_has_kvm_support()) {
3450                 printk(KERN_ERR "kvm: no hardware support\n");
3451                 return -EOPNOTSUPP;
3452         }
3453         if (ops->disabled_by_bios()) {
3454                 printk(KERN_ERR "kvm: disabled by bios\n");
3455                 return -EOPNOTSUPP;
3456         }
3457
3458         kvm_x86_ops = ops;
3459
3460         r = kvm_x86_ops->hardware_setup();
3461         if (r < 0)
3462                 goto out;
3463
3464         for_each_online_cpu(cpu) {
3465                 smp_call_function_single(cpu,
3466                                 kvm_x86_ops->check_processor_compatibility,
3467                                 &r, 0, 1);
3468                 if (r < 0)
3469                         goto out_free_0;
3470         }
3471
3472         on_each_cpu(hardware_enable, NULL, 0, 1);
3473         r = register_cpu_notifier(&kvm_cpu_notifier);
3474         if (r)
3475                 goto out_free_1;
3476         register_reboot_notifier(&kvm_reboot_notifier);
3477
3478         r = sysdev_class_register(&kvm_sysdev_class);
3479         if (r)
3480                 goto out_free_2;
3481
3482         r = sysdev_register(&kvm_sysdev);
3483         if (r)
3484                 goto out_free_3;
3485
3486         /* A kmem cache lets us meet the alignment requirements of fx_save. */
3487         kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size,
3488                                            __alignof__(struct kvm_vcpu), 0, 0);
3489         if (!kvm_vcpu_cache) {
3490                 r = -ENOMEM;
3491                 goto out_free_4;
3492         }
3493
3494         kvm_chardev_ops.owner = module;
3495
3496         r = misc_register(&kvm_dev);
3497         if (r) {
3498                 printk (KERN_ERR "kvm: misc device register failed\n");
3499                 goto out_free;
3500         }
3501
3502         kvm_preempt_ops.sched_in = kvm_sched_in;
3503         kvm_preempt_ops.sched_out = kvm_sched_out;
3504
3505         kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
3506
3507         return 0;
3508
3509 out_free:
3510         kmem_cache_destroy(kvm_vcpu_cache);
3511 out_free_4:
3512         sysdev_unregister(&kvm_sysdev);
3513 out_free_3:
3514         sysdev_class_unregister(&kvm_sysdev_class);
3515 out_free_2:
3516         unregister_reboot_notifier(&kvm_reboot_notifier);
3517         unregister_cpu_notifier(&kvm_cpu_notifier);
3518 out_free_1:
3519         on_each_cpu(hardware_disable, NULL, 0, 1);
3520 out_free_0:
3521         kvm_x86_ops->hardware_unsetup();
3522 out:
3523         kvm_x86_ops = NULL;
3524         return r;
3525 }
3526
3527 void kvm_exit_x86(void)
3528 {
3529         misc_deregister(&kvm_dev);
3530         kmem_cache_destroy(kvm_vcpu_cache);
3531         sysdev_unregister(&kvm_sysdev);
3532         sysdev_class_unregister(&kvm_sysdev_class);
3533         unregister_reboot_notifier(&kvm_reboot_notifier);
3534         unregister_cpu_notifier(&kvm_cpu_notifier);
3535         on_each_cpu(hardware_disable, NULL, 0, 1);
3536         kvm_x86_ops->hardware_unsetup();
3537         kvm_x86_ops = NULL;
3538 }
3539
3540 static __init int kvm_init(void)
3541 {
3542         static struct page *bad_page;
3543         int r;
3544
3545         r = kvm_mmu_module_init();
3546         if (r)
3547                 goto out4;
3548
3549         kvm_init_debug();
3550
3551         kvm_init_msr_list();
3552
3553         if ((bad_page = alloc_page(GFP_KERNEL)) == NULL) {
3554                 r = -ENOMEM;
3555                 goto out;
3556         }
3557
3558         bad_page_address = page_to_pfn(bad_page) << PAGE_SHIFT;
3559         memset(__va(bad_page_address), 0, PAGE_SIZE);
3560
3561         return 0;
3562
3563 out:
3564         kvm_exit_debug();
3565         kvm_mmu_module_exit();
3566 out4:
3567         return r;
3568 }
3569
3570 static __exit void kvm_exit(void)
3571 {
3572         kvm_exit_debug();
3573         __free_page(pfn_to_page(bad_page_address >> PAGE_SHIFT));
3574         kvm_mmu_module_exit();
3575 }
3576
3577 module_init(kvm_init)
3578 module_exit(kvm_exit)
3579
3580 EXPORT_SYMBOL_GPL(kvm_init_x86);
3581 EXPORT_SYMBOL_GPL(kvm_exit_x86);