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