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