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