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