]> err.no Git - linux-2.6/blob - drivers/kvm/kvm_main.c
KVM: Fold kvm_run::exit_type into kvm_run::exit_reason
[linux-2.6] / drivers / kvm / kvm_main.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  *
9  * Authors:
10  *   Avi Kivity   <avi@qumranet.com>
11  *   Yaniv Kamay  <yaniv@qumranet.com>
12  *
13  * This work is licensed under the terms of the GNU GPL, version 2.  See
14  * the COPYING file in the top-level directory.
15  *
16  */
17
18 #include "kvm.h"
19
20 #include <linux/kvm.h>
21 #include <linux/module.h>
22 #include <linux/errno.h>
23 #include <linux/magic.h>
24 #include <asm/processor.h>
25 #include <linux/percpu.h>
26 #include <linux/gfp.h>
27 #include <asm/msr.h>
28 #include <linux/mm.h>
29 #include <linux/miscdevice.h>
30 #include <linux/vmalloc.h>
31 #include <asm/uaccess.h>
32 #include <linux/reboot.h>
33 #include <asm/io.h>
34 #include <linux/debugfs.h>
35 #include <linux/highmem.h>
36 #include <linux/file.h>
37 #include <asm/desc.h>
38 #include <linux/sysdev.h>
39 #include <linux/cpu.h>
40 #include <linux/file.h>
41 #include <linux/fs.h>
42 #include <linux/mount.h>
43
44 #include "x86_emulate.h"
45 #include "segment_descriptor.h"
46
47 MODULE_AUTHOR("Qumranet");
48 MODULE_LICENSE("GPL");
49
50 static DEFINE_SPINLOCK(kvm_lock);
51 static LIST_HEAD(vm_list);
52
53 struct kvm_arch_ops *kvm_arch_ops;
54 struct kvm_stat kvm_stat;
55 EXPORT_SYMBOL_GPL(kvm_stat);
56
57 static struct kvm_stats_debugfs_item {
58         const char *name;
59         u32 *data;
60         struct dentry *dentry;
61 } debugfs_entries[] = {
62         { "pf_fixed", &kvm_stat.pf_fixed },
63         { "pf_guest", &kvm_stat.pf_guest },
64         { "tlb_flush", &kvm_stat.tlb_flush },
65         { "invlpg", &kvm_stat.invlpg },
66         { "exits", &kvm_stat.exits },
67         { "io_exits", &kvm_stat.io_exits },
68         { "mmio_exits", &kvm_stat.mmio_exits },
69         { "signal_exits", &kvm_stat.signal_exits },
70         { "irq_window", &kvm_stat.irq_window_exits },
71         { "halt_exits", &kvm_stat.halt_exits },
72         { "request_irq", &kvm_stat.request_irq_exits },
73         { "irq_exits", &kvm_stat.irq_exits },
74         { NULL, NULL }
75 };
76
77 static struct dentry *debugfs_dir;
78
79 struct vfsmount *kvmfs_mnt;
80
81 #define MAX_IO_MSRS 256
82
83 #define CR0_RESEVED_BITS 0xffffffff1ffaffc0ULL
84 #define LMSW_GUEST_MASK 0x0eULL
85 #define CR4_RESEVED_BITS (~((1ULL << 11) - 1))
86 #define CR8_RESEVED_BITS (~0x0fULL)
87 #define EFER_RESERVED_BITS 0xfffffffffffff2fe
88
89 #ifdef CONFIG_X86_64
90 // LDT or TSS descriptor in the GDT. 16 bytes.
91 struct segment_descriptor_64 {
92         struct segment_descriptor s;
93         u32 base_higher;
94         u32 pad_zero;
95 };
96
97 #endif
98
99 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
100                            unsigned long arg);
101
102 static struct inode *kvmfs_inode(struct file_operations *fops)
103 {
104         int error = -ENOMEM;
105         struct inode *inode = new_inode(kvmfs_mnt->mnt_sb);
106
107         if (!inode)
108                 goto eexit_1;
109
110         inode->i_fop = fops;
111
112         /*
113          * Mark the inode dirty from the very beginning,
114          * that way it will never be moved to the dirty
115          * list because mark_inode_dirty() will think
116          * that it already _is_ on the dirty list.
117          */
118         inode->i_state = I_DIRTY;
119         inode->i_mode = S_IRUSR | S_IWUSR;
120         inode->i_uid = current->fsuid;
121         inode->i_gid = current->fsgid;
122         inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
123         return inode;
124
125 eexit_1:
126         return ERR_PTR(error);
127 }
128
129 static struct file *kvmfs_file(struct inode *inode, void *private_data)
130 {
131         struct file *file = get_empty_filp();
132
133         if (!file)
134                 return ERR_PTR(-ENFILE);
135
136         file->f_path.mnt = mntget(kvmfs_mnt);
137         file->f_path.dentry = d_alloc_anon(inode);
138         if (!file->f_path.dentry)
139                 return ERR_PTR(-ENOMEM);
140         file->f_mapping = inode->i_mapping;
141
142         file->f_pos = 0;
143         file->f_flags = O_RDWR;
144         file->f_op = inode->i_fop;
145         file->f_mode = FMODE_READ | FMODE_WRITE;
146         file->f_version = 0;
147         file->private_data = private_data;
148         return file;
149 }
150
151 unsigned long segment_base(u16 selector)
152 {
153         struct descriptor_table gdt;
154         struct segment_descriptor *d;
155         unsigned long table_base;
156         typedef unsigned long ul;
157         unsigned long v;
158
159         if (selector == 0)
160                 return 0;
161
162         asm ("sgdt %0" : "=m"(gdt));
163         table_base = gdt.base;
164
165         if (selector & 4) {           /* from ldt */
166                 u16 ldt_selector;
167
168                 asm ("sldt %0" : "=g"(ldt_selector));
169                 table_base = segment_base(ldt_selector);
170         }
171         d = (struct segment_descriptor *)(table_base + (selector & ~7));
172         v = d->base_low | ((ul)d->base_mid << 16) | ((ul)d->base_high << 24);
173 #ifdef CONFIG_X86_64
174         if (d->system == 0
175             && (d->type == 2 || d->type == 9 || d->type == 11))
176                 v |= ((ul)((struct segment_descriptor_64 *)d)->base_higher) << 32;
177 #endif
178         return v;
179 }
180 EXPORT_SYMBOL_GPL(segment_base);
181
182 static inline int valid_vcpu(int n)
183 {
184         return likely(n >= 0 && n < KVM_MAX_VCPUS);
185 }
186
187 int kvm_read_guest(struct kvm_vcpu *vcpu, gva_t addr, unsigned long size,
188                    void *dest)
189 {
190         unsigned char *host_buf = dest;
191         unsigned long req_size = size;
192
193         while (size) {
194                 hpa_t paddr;
195                 unsigned now;
196                 unsigned offset;
197                 hva_t guest_buf;
198
199                 paddr = gva_to_hpa(vcpu, addr);
200
201                 if (is_error_hpa(paddr))
202                         break;
203
204                 guest_buf = (hva_t)kmap_atomic(
205                                         pfn_to_page(paddr >> PAGE_SHIFT),
206                                         KM_USER0);
207                 offset = addr & ~PAGE_MASK;
208                 guest_buf |= offset;
209                 now = min(size, PAGE_SIZE - offset);
210                 memcpy(host_buf, (void*)guest_buf, now);
211                 host_buf += now;
212                 addr += now;
213                 size -= now;
214                 kunmap_atomic((void *)(guest_buf & PAGE_MASK), KM_USER0);
215         }
216         return req_size - size;
217 }
218 EXPORT_SYMBOL_GPL(kvm_read_guest);
219
220 int kvm_write_guest(struct kvm_vcpu *vcpu, gva_t addr, unsigned long size,
221                     void *data)
222 {
223         unsigned char *host_buf = data;
224         unsigned long req_size = size;
225
226         while (size) {
227                 hpa_t paddr;
228                 unsigned now;
229                 unsigned offset;
230                 hva_t guest_buf;
231                 gfn_t gfn;
232
233                 paddr = gva_to_hpa(vcpu, addr);
234
235                 if (is_error_hpa(paddr))
236                         break;
237
238                 gfn = vcpu->mmu.gva_to_gpa(vcpu, addr) >> PAGE_SHIFT;
239                 mark_page_dirty(vcpu->kvm, gfn);
240                 guest_buf = (hva_t)kmap_atomic(
241                                 pfn_to_page(paddr >> PAGE_SHIFT), KM_USER0);
242                 offset = addr & ~PAGE_MASK;
243                 guest_buf |= offset;
244                 now = min(size, PAGE_SIZE - offset);
245                 memcpy((void*)guest_buf, host_buf, now);
246                 host_buf += now;
247                 addr += now;
248                 size -= now;
249                 kunmap_atomic((void *)(guest_buf & PAGE_MASK), KM_USER0);
250         }
251         return req_size - size;
252 }
253 EXPORT_SYMBOL_GPL(kvm_write_guest);
254
255 /*
256  * Switches to specified vcpu, until a matching vcpu_put()
257  */
258 static void vcpu_load(struct kvm_vcpu *vcpu)
259 {
260         mutex_lock(&vcpu->mutex);
261         kvm_arch_ops->vcpu_load(vcpu);
262 }
263
264 /*
265  * Switches to specified vcpu, until a matching vcpu_put(). Will return NULL
266  * if the slot is not populated.
267  */
268 static struct kvm_vcpu *vcpu_load_slot(struct kvm *kvm, int slot)
269 {
270         struct kvm_vcpu *vcpu = &kvm->vcpus[slot];
271
272         mutex_lock(&vcpu->mutex);
273         if (!vcpu->vmcs) {
274                 mutex_unlock(&vcpu->mutex);
275                 return NULL;
276         }
277         kvm_arch_ops->vcpu_load(vcpu);
278         return vcpu;
279 }
280
281 static void vcpu_put(struct kvm_vcpu *vcpu)
282 {
283         kvm_arch_ops->vcpu_put(vcpu);
284         mutex_unlock(&vcpu->mutex);
285 }
286
287 static struct kvm *kvm_create_vm(void)
288 {
289         struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
290         int i;
291
292         if (!kvm)
293                 return ERR_PTR(-ENOMEM);
294
295         spin_lock_init(&kvm->lock);
296         INIT_LIST_HEAD(&kvm->active_mmu_pages);
297         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
298                 struct kvm_vcpu *vcpu = &kvm->vcpus[i];
299
300                 mutex_init(&vcpu->mutex);
301                 vcpu->cpu = -1;
302                 vcpu->kvm = kvm;
303                 vcpu->mmu.root_hpa = INVALID_PAGE;
304                 INIT_LIST_HEAD(&vcpu->free_pages);
305                 spin_lock(&kvm_lock);
306                 list_add(&kvm->vm_list, &vm_list);
307                 spin_unlock(&kvm_lock);
308         }
309         return kvm;
310 }
311
312 static int kvm_dev_open(struct inode *inode, struct file *filp)
313 {
314         return 0;
315 }
316
317 /*
318  * Free any memory in @free but not in @dont.
319  */
320 static void kvm_free_physmem_slot(struct kvm_memory_slot *free,
321                                   struct kvm_memory_slot *dont)
322 {
323         int i;
324
325         if (!dont || free->phys_mem != dont->phys_mem)
326                 if (free->phys_mem) {
327                         for (i = 0; i < free->npages; ++i)
328                                 if (free->phys_mem[i])
329                                         __free_page(free->phys_mem[i]);
330                         vfree(free->phys_mem);
331                 }
332
333         if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
334                 vfree(free->dirty_bitmap);
335
336         free->phys_mem = NULL;
337         free->npages = 0;
338         free->dirty_bitmap = NULL;
339 }
340
341 static void kvm_free_physmem(struct kvm *kvm)
342 {
343         int i;
344
345         for (i = 0; i < kvm->nmemslots; ++i)
346                 kvm_free_physmem_slot(&kvm->memslots[i], NULL);
347 }
348
349 static void kvm_free_vcpu(struct kvm_vcpu *vcpu)
350 {
351         if (!vcpu->vmcs)
352                 return;
353
354         vcpu_load(vcpu);
355         kvm_mmu_destroy(vcpu);
356         vcpu_put(vcpu);
357         kvm_arch_ops->vcpu_free(vcpu);
358         free_page((unsigned long)vcpu->run);
359         vcpu->run = NULL;
360 }
361
362 static void kvm_free_vcpus(struct kvm *kvm)
363 {
364         unsigned int i;
365
366         for (i = 0; i < KVM_MAX_VCPUS; ++i)
367                 kvm_free_vcpu(&kvm->vcpus[i]);
368 }
369
370 static int kvm_dev_release(struct inode *inode, struct file *filp)
371 {
372         return 0;
373 }
374
375 static void kvm_destroy_vm(struct kvm *kvm)
376 {
377         spin_lock(&kvm_lock);
378         list_del(&kvm->vm_list);
379         spin_unlock(&kvm_lock);
380         kvm_free_vcpus(kvm);
381         kvm_free_physmem(kvm);
382         kfree(kvm);
383 }
384
385 static int kvm_vm_release(struct inode *inode, struct file *filp)
386 {
387         struct kvm *kvm = filp->private_data;
388
389         kvm_destroy_vm(kvm);
390         return 0;
391 }
392
393 static void inject_gp(struct kvm_vcpu *vcpu)
394 {
395         kvm_arch_ops->inject_gp(vcpu, 0);
396 }
397
398 /*
399  * Load the pae pdptrs.  Return true is they are all valid.
400  */
401 static int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
402 {
403         gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
404         unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
405         int i;
406         u64 pdpte;
407         u64 *pdpt;
408         int ret;
409         struct kvm_memory_slot *memslot;
410
411         spin_lock(&vcpu->kvm->lock);
412         memslot = gfn_to_memslot(vcpu->kvm, pdpt_gfn);
413         /* FIXME: !memslot - emulate? 0xff? */
414         pdpt = kmap_atomic(gfn_to_page(memslot, pdpt_gfn), KM_USER0);
415
416         ret = 1;
417         for (i = 0; i < 4; ++i) {
418                 pdpte = pdpt[offset + i];
419                 if ((pdpte & 1) && (pdpte & 0xfffffff0000001e6ull)) {
420                         ret = 0;
421                         goto out;
422                 }
423         }
424
425         for (i = 0; i < 4; ++i)
426                 vcpu->pdptrs[i] = pdpt[offset + i];
427
428 out:
429         kunmap_atomic(pdpt, KM_USER0);
430         spin_unlock(&vcpu->kvm->lock);
431
432         return ret;
433 }
434
435 void set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
436 {
437         if (cr0 & CR0_RESEVED_BITS) {
438                 printk(KERN_DEBUG "set_cr0: 0x%lx #GP, reserved bits 0x%lx\n",
439                        cr0, vcpu->cr0);
440                 inject_gp(vcpu);
441                 return;
442         }
443
444         if ((cr0 & CR0_NW_MASK) && !(cr0 & CR0_CD_MASK)) {
445                 printk(KERN_DEBUG "set_cr0: #GP, CD == 0 && NW == 1\n");
446                 inject_gp(vcpu);
447                 return;
448         }
449
450         if ((cr0 & CR0_PG_MASK) && !(cr0 & CR0_PE_MASK)) {
451                 printk(KERN_DEBUG "set_cr0: #GP, set PG flag "
452                        "and a clear PE flag\n");
453                 inject_gp(vcpu);
454                 return;
455         }
456
457         if (!is_paging(vcpu) && (cr0 & CR0_PG_MASK)) {
458 #ifdef CONFIG_X86_64
459                 if ((vcpu->shadow_efer & EFER_LME)) {
460                         int cs_db, cs_l;
461
462                         if (!is_pae(vcpu)) {
463                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
464                                        "in long mode while PAE is disabled\n");
465                                 inject_gp(vcpu);
466                                 return;
467                         }
468                         kvm_arch_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
469                         if (cs_l) {
470                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
471                                        "in long mode while CS.L == 1\n");
472                                 inject_gp(vcpu);
473                                 return;
474
475                         }
476                 } else
477 #endif
478                 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->cr3)) {
479                         printk(KERN_DEBUG "set_cr0: #GP, pdptrs "
480                                "reserved bits\n");
481                         inject_gp(vcpu);
482                         return;
483                 }
484
485         }
486
487         kvm_arch_ops->set_cr0(vcpu, cr0);
488         vcpu->cr0 = cr0;
489
490         spin_lock(&vcpu->kvm->lock);
491         kvm_mmu_reset_context(vcpu);
492         spin_unlock(&vcpu->kvm->lock);
493         return;
494 }
495 EXPORT_SYMBOL_GPL(set_cr0);
496
497 void lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
498 {
499         kvm_arch_ops->decache_cr0_cr4_guest_bits(vcpu);
500         set_cr0(vcpu, (vcpu->cr0 & ~0x0ful) | (msw & 0x0f));
501 }
502 EXPORT_SYMBOL_GPL(lmsw);
503
504 void set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
505 {
506         if (cr4 & CR4_RESEVED_BITS) {
507                 printk(KERN_DEBUG "set_cr4: #GP, reserved bits\n");
508                 inject_gp(vcpu);
509                 return;
510         }
511
512         if (is_long_mode(vcpu)) {
513                 if (!(cr4 & CR4_PAE_MASK)) {
514                         printk(KERN_DEBUG "set_cr4: #GP, clearing PAE while "
515                                "in long mode\n");
516                         inject_gp(vcpu);
517                         return;
518                 }
519         } else if (is_paging(vcpu) && !is_pae(vcpu) && (cr4 & CR4_PAE_MASK)
520                    && !load_pdptrs(vcpu, vcpu->cr3)) {
521                 printk(KERN_DEBUG "set_cr4: #GP, pdptrs reserved bits\n");
522                 inject_gp(vcpu);
523         }
524
525         if (cr4 & CR4_VMXE_MASK) {
526                 printk(KERN_DEBUG "set_cr4: #GP, setting VMXE\n");
527                 inject_gp(vcpu);
528                 return;
529         }
530         kvm_arch_ops->set_cr4(vcpu, cr4);
531         spin_lock(&vcpu->kvm->lock);
532         kvm_mmu_reset_context(vcpu);
533         spin_unlock(&vcpu->kvm->lock);
534 }
535 EXPORT_SYMBOL_GPL(set_cr4);
536
537 void set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
538 {
539         if (is_long_mode(vcpu)) {
540                 if (cr3 & CR3_L_MODE_RESEVED_BITS) {
541                         printk(KERN_DEBUG "set_cr3: #GP, reserved bits\n");
542                         inject_gp(vcpu);
543                         return;
544                 }
545         } else {
546                 if (cr3 & CR3_RESEVED_BITS) {
547                         printk(KERN_DEBUG "set_cr3: #GP, reserved bits\n");
548                         inject_gp(vcpu);
549                         return;
550                 }
551                 if (is_paging(vcpu) && is_pae(vcpu) &&
552                     !load_pdptrs(vcpu, cr3)) {
553                         printk(KERN_DEBUG "set_cr3: #GP, pdptrs "
554                                "reserved bits\n");
555                         inject_gp(vcpu);
556                         return;
557                 }
558         }
559
560         vcpu->cr3 = cr3;
561         spin_lock(&vcpu->kvm->lock);
562         /*
563          * Does the new cr3 value map to physical memory? (Note, we
564          * catch an invalid cr3 even in real-mode, because it would
565          * cause trouble later on when we turn on paging anyway.)
566          *
567          * A real CPU would silently accept an invalid cr3 and would
568          * attempt to use it - with largely undefined (and often hard
569          * to debug) behavior on the guest side.
570          */
571         if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
572                 inject_gp(vcpu);
573         else
574                 vcpu->mmu.new_cr3(vcpu);
575         spin_unlock(&vcpu->kvm->lock);
576 }
577 EXPORT_SYMBOL_GPL(set_cr3);
578
579 void set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
580 {
581         if ( cr8 & CR8_RESEVED_BITS) {
582                 printk(KERN_DEBUG "set_cr8: #GP, reserved bits 0x%lx\n", cr8);
583                 inject_gp(vcpu);
584                 return;
585         }
586         vcpu->cr8 = cr8;
587 }
588 EXPORT_SYMBOL_GPL(set_cr8);
589
590 void fx_init(struct kvm_vcpu *vcpu)
591 {
592         struct __attribute__ ((__packed__)) fx_image_s {
593                 u16 control; //fcw
594                 u16 status; //fsw
595                 u16 tag; // ftw
596                 u16 opcode; //fop
597                 u64 ip; // fpu ip
598                 u64 operand;// fpu dp
599                 u32 mxcsr;
600                 u32 mxcsr_mask;
601
602         } *fx_image;
603
604         fx_save(vcpu->host_fx_image);
605         fpu_init();
606         fx_save(vcpu->guest_fx_image);
607         fx_restore(vcpu->host_fx_image);
608
609         fx_image = (struct fx_image_s *)vcpu->guest_fx_image;
610         fx_image->mxcsr = 0x1f80;
611         memset(vcpu->guest_fx_image + sizeof(struct fx_image_s),
612                0, FX_IMAGE_SIZE - sizeof(struct fx_image_s));
613 }
614 EXPORT_SYMBOL_GPL(fx_init);
615
616 static void do_remove_write_access(struct kvm_vcpu *vcpu, int slot)
617 {
618         spin_lock(&vcpu->kvm->lock);
619         kvm_mmu_slot_remove_write_access(vcpu, slot);
620         spin_unlock(&vcpu->kvm->lock);
621 }
622
623 /*
624  * Allocate some memory and give it an address in the guest physical address
625  * space.
626  *
627  * Discontiguous memory is allowed, mostly for framebuffers.
628  */
629 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
630                                           struct kvm_memory_region *mem)
631 {
632         int r;
633         gfn_t base_gfn;
634         unsigned long npages;
635         unsigned long i;
636         struct kvm_memory_slot *memslot;
637         struct kvm_memory_slot old, new;
638         int memory_config_version;
639
640         r = -EINVAL;
641         /* General sanity checks */
642         if (mem->memory_size & (PAGE_SIZE - 1))
643                 goto out;
644         if (mem->guest_phys_addr & (PAGE_SIZE - 1))
645                 goto out;
646         if (mem->slot >= KVM_MEMORY_SLOTS)
647                 goto out;
648         if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
649                 goto out;
650
651         memslot = &kvm->memslots[mem->slot];
652         base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
653         npages = mem->memory_size >> PAGE_SHIFT;
654
655         if (!npages)
656                 mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
657
658 raced:
659         spin_lock(&kvm->lock);
660
661         memory_config_version = kvm->memory_config_version;
662         new = old = *memslot;
663
664         new.base_gfn = base_gfn;
665         new.npages = npages;
666         new.flags = mem->flags;
667
668         /* Disallow changing a memory slot's size. */
669         r = -EINVAL;
670         if (npages && old.npages && npages != old.npages)
671                 goto out_unlock;
672
673         /* Check for overlaps */
674         r = -EEXIST;
675         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
676                 struct kvm_memory_slot *s = &kvm->memslots[i];
677
678                 if (s == memslot)
679                         continue;
680                 if (!((base_gfn + npages <= s->base_gfn) ||
681                       (base_gfn >= s->base_gfn + s->npages)))
682                         goto out_unlock;
683         }
684         /*
685          * Do memory allocations outside lock.  memory_config_version will
686          * detect any races.
687          */
688         spin_unlock(&kvm->lock);
689
690         /* Deallocate if slot is being removed */
691         if (!npages)
692                 new.phys_mem = NULL;
693
694         /* Free page dirty bitmap if unneeded */
695         if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
696                 new.dirty_bitmap = NULL;
697
698         r = -ENOMEM;
699
700         /* Allocate if a slot is being created */
701         if (npages && !new.phys_mem) {
702                 new.phys_mem = vmalloc(npages * sizeof(struct page *));
703
704                 if (!new.phys_mem)
705                         goto out_free;
706
707                 memset(new.phys_mem, 0, npages * sizeof(struct page *));
708                 for (i = 0; i < npages; ++i) {
709                         new.phys_mem[i] = alloc_page(GFP_HIGHUSER
710                                                      | __GFP_ZERO);
711                         if (!new.phys_mem[i])
712                                 goto out_free;
713                         set_page_private(new.phys_mem[i],0);
714                 }
715         }
716
717         /* Allocate page dirty bitmap if needed */
718         if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
719                 unsigned dirty_bytes = ALIGN(npages, BITS_PER_LONG) / 8;
720
721                 new.dirty_bitmap = vmalloc(dirty_bytes);
722                 if (!new.dirty_bitmap)
723                         goto out_free;
724                 memset(new.dirty_bitmap, 0, dirty_bytes);
725         }
726
727         spin_lock(&kvm->lock);
728
729         if (memory_config_version != kvm->memory_config_version) {
730                 spin_unlock(&kvm->lock);
731                 kvm_free_physmem_slot(&new, &old);
732                 goto raced;
733         }
734
735         r = -EAGAIN;
736         if (kvm->busy)
737                 goto out_unlock;
738
739         if (mem->slot >= kvm->nmemslots)
740                 kvm->nmemslots = mem->slot + 1;
741
742         *memslot = new;
743         ++kvm->memory_config_version;
744
745         spin_unlock(&kvm->lock);
746
747         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
748                 struct kvm_vcpu *vcpu;
749
750                 vcpu = vcpu_load_slot(kvm, i);
751                 if (!vcpu)
752                         continue;
753                 if (new.flags & KVM_MEM_LOG_DIRTY_PAGES)
754                         do_remove_write_access(vcpu, mem->slot);
755                 kvm_mmu_reset_context(vcpu);
756                 vcpu_put(vcpu);
757         }
758
759         kvm_free_physmem_slot(&old, &new);
760         return 0;
761
762 out_unlock:
763         spin_unlock(&kvm->lock);
764 out_free:
765         kvm_free_physmem_slot(&new, &old);
766 out:
767         return r;
768 }
769
770 /*
771  * Get (and clear) the dirty memory log for a memory slot.
772  */
773 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
774                                       struct kvm_dirty_log *log)
775 {
776         struct kvm_memory_slot *memslot;
777         int r, i;
778         int n;
779         int cleared;
780         unsigned long any = 0;
781
782         spin_lock(&kvm->lock);
783
784         /*
785          * Prevent changes to guest memory configuration even while the lock
786          * is not taken.
787          */
788         ++kvm->busy;
789         spin_unlock(&kvm->lock);
790         r = -EINVAL;
791         if (log->slot >= KVM_MEMORY_SLOTS)
792                 goto out;
793
794         memslot = &kvm->memslots[log->slot];
795         r = -ENOENT;
796         if (!memslot->dirty_bitmap)
797                 goto out;
798
799         n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
800
801         for (i = 0; !any && i < n/sizeof(long); ++i)
802                 any = memslot->dirty_bitmap[i];
803
804         r = -EFAULT;
805         if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
806                 goto out;
807
808         if (any) {
809                 cleared = 0;
810                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
811                         struct kvm_vcpu *vcpu;
812
813                         vcpu = vcpu_load_slot(kvm, i);
814                         if (!vcpu)
815                                 continue;
816                         if (!cleared) {
817                                 do_remove_write_access(vcpu, log->slot);
818                                 memset(memslot->dirty_bitmap, 0, n);
819                                 cleared = 1;
820                         }
821                         kvm_arch_ops->tlb_flush(vcpu);
822                         vcpu_put(vcpu);
823                 }
824         }
825
826         r = 0;
827
828 out:
829         spin_lock(&kvm->lock);
830         --kvm->busy;
831         spin_unlock(&kvm->lock);
832         return r;
833 }
834
835 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
836 {
837         int i;
838
839         for (i = 0; i < kvm->nmemslots; ++i) {
840                 struct kvm_memory_slot *memslot = &kvm->memslots[i];
841
842                 if (gfn >= memslot->base_gfn
843                     && gfn < memslot->base_gfn + memslot->npages)
844                         return memslot;
845         }
846         return NULL;
847 }
848 EXPORT_SYMBOL_GPL(gfn_to_memslot);
849
850 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
851 {
852         int i;
853         struct kvm_memory_slot *memslot = NULL;
854         unsigned long rel_gfn;
855
856         for (i = 0; i < kvm->nmemslots; ++i) {
857                 memslot = &kvm->memslots[i];
858
859                 if (gfn >= memslot->base_gfn
860                     && gfn < memslot->base_gfn + memslot->npages) {
861
862                         if (!memslot || !memslot->dirty_bitmap)
863                                 return;
864
865                         rel_gfn = gfn - memslot->base_gfn;
866
867                         /* avoid RMW */
868                         if (!test_bit(rel_gfn, memslot->dirty_bitmap))
869                                 set_bit(rel_gfn, memslot->dirty_bitmap);
870                         return;
871                 }
872         }
873 }
874
875 static int emulator_read_std(unsigned long addr,
876                              unsigned long *val,
877                              unsigned int bytes,
878                              struct x86_emulate_ctxt *ctxt)
879 {
880         struct kvm_vcpu *vcpu = ctxt->vcpu;
881         void *data = val;
882
883         while (bytes) {
884                 gpa_t gpa = vcpu->mmu.gva_to_gpa(vcpu, addr);
885                 unsigned offset = addr & (PAGE_SIZE-1);
886                 unsigned tocopy = min(bytes, (unsigned)PAGE_SIZE - offset);
887                 unsigned long pfn;
888                 struct kvm_memory_slot *memslot;
889                 void *page;
890
891                 if (gpa == UNMAPPED_GVA)
892                         return X86EMUL_PROPAGATE_FAULT;
893                 pfn = gpa >> PAGE_SHIFT;
894                 memslot = gfn_to_memslot(vcpu->kvm, pfn);
895                 if (!memslot)
896                         return X86EMUL_UNHANDLEABLE;
897                 page = kmap_atomic(gfn_to_page(memslot, pfn), KM_USER0);
898
899                 memcpy(data, page + offset, tocopy);
900
901                 kunmap_atomic(page, KM_USER0);
902
903                 bytes -= tocopy;
904                 data += tocopy;
905                 addr += tocopy;
906         }
907
908         return X86EMUL_CONTINUE;
909 }
910
911 static int emulator_write_std(unsigned long addr,
912                               unsigned long val,
913                               unsigned int bytes,
914                               struct x86_emulate_ctxt *ctxt)
915 {
916         printk(KERN_ERR "emulator_write_std: addr %lx n %d\n",
917                addr, bytes);
918         return X86EMUL_UNHANDLEABLE;
919 }
920
921 static int emulator_read_emulated(unsigned long addr,
922                                   unsigned long *val,
923                                   unsigned int bytes,
924                                   struct x86_emulate_ctxt *ctxt)
925 {
926         struct kvm_vcpu *vcpu = ctxt->vcpu;
927
928         if (vcpu->mmio_read_completed) {
929                 memcpy(val, vcpu->mmio_data, bytes);
930                 vcpu->mmio_read_completed = 0;
931                 return X86EMUL_CONTINUE;
932         } else if (emulator_read_std(addr, val, bytes, ctxt)
933                    == X86EMUL_CONTINUE)
934                 return X86EMUL_CONTINUE;
935         else {
936                 gpa_t gpa = vcpu->mmu.gva_to_gpa(vcpu, addr);
937
938                 if (gpa == UNMAPPED_GVA)
939                         return X86EMUL_PROPAGATE_FAULT;
940                 vcpu->mmio_needed = 1;
941                 vcpu->mmio_phys_addr = gpa;
942                 vcpu->mmio_size = bytes;
943                 vcpu->mmio_is_write = 0;
944
945                 return X86EMUL_UNHANDLEABLE;
946         }
947 }
948
949 static int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
950                                unsigned long val, int bytes)
951 {
952         struct kvm_memory_slot *m;
953         struct page *page;
954         void *virt;
955
956         if (((gpa + bytes - 1) >> PAGE_SHIFT) != (gpa >> PAGE_SHIFT))
957                 return 0;
958         m = gfn_to_memslot(vcpu->kvm, gpa >> PAGE_SHIFT);
959         if (!m)
960                 return 0;
961         page = gfn_to_page(m, gpa >> PAGE_SHIFT);
962         kvm_mmu_pre_write(vcpu, gpa, bytes);
963         mark_page_dirty(vcpu->kvm, gpa >> PAGE_SHIFT);
964         virt = kmap_atomic(page, KM_USER0);
965         memcpy(virt + offset_in_page(gpa), &val, bytes);
966         kunmap_atomic(virt, KM_USER0);
967         kvm_mmu_post_write(vcpu, gpa, bytes);
968         return 1;
969 }
970
971 static int emulator_write_emulated(unsigned long addr,
972                                    unsigned long val,
973                                    unsigned int bytes,
974                                    struct x86_emulate_ctxt *ctxt)
975 {
976         struct kvm_vcpu *vcpu = ctxt->vcpu;
977         gpa_t gpa = vcpu->mmu.gva_to_gpa(vcpu, addr);
978
979         if (gpa == UNMAPPED_GVA)
980                 return X86EMUL_PROPAGATE_FAULT;
981
982         if (emulator_write_phys(vcpu, gpa, val, bytes))
983                 return X86EMUL_CONTINUE;
984
985         vcpu->mmio_needed = 1;
986         vcpu->mmio_phys_addr = gpa;
987         vcpu->mmio_size = bytes;
988         vcpu->mmio_is_write = 1;
989         memcpy(vcpu->mmio_data, &val, bytes);
990
991         return X86EMUL_CONTINUE;
992 }
993
994 static int emulator_cmpxchg_emulated(unsigned long addr,
995                                      unsigned long old,
996                                      unsigned long new,
997                                      unsigned int bytes,
998                                      struct x86_emulate_ctxt *ctxt)
999 {
1000         static int reported;
1001
1002         if (!reported) {
1003                 reported = 1;
1004                 printk(KERN_WARNING "kvm: emulating exchange as write\n");
1005         }
1006         return emulator_write_emulated(addr, new, bytes, ctxt);
1007 }
1008
1009 #ifdef CONFIG_X86_32
1010
1011 static int emulator_cmpxchg8b_emulated(unsigned long addr,
1012                                        unsigned long old_lo,
1013                                        unsigned long old_hi,
1014                                        unsigned long new_lo,
1015                                        unsigned long new_hi,
1016                                        struct x86_emulate_ctxt *ctxt)
1017 {
1018         static int reported;
1019         int r;
1020
1021         if (!reported) {
1022                 reported = 1;
1023                 printk(KERN_WARNING "kvm: emulating exchange8b as write\n");
1024         }
1025         r = emulator_write_emulated(addr, new_lo, 4, ctxt);
1026         if (r != X86EMUL_CONTINUE)
1027                 return r;
1028         return emulator_write_emulated(addr+4, new_hi, 4, ctxt);
1029 }
1030
1031 #endif
1032
1033 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
1034 {
1035         return kvm_arch_ops->get_segment_base(vcpu, seg);
1036 }
1037
1038 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
1039 {
1040         return X86EMUL_CONTINUE;
1041 }
1042
1043 int emulate_clts(struct kvm_vcpu *vcpu)
1044 {
1045         unsigned long cr0;
1046
1047         kvm_arch_ops->decache_cr0_cr4_guest_bits(vcpu);
1048         cr0 = vcpu->cr0 & ~CR0_TS_MASK;
1049         kvm_arch_ops->set_cr0(vcpu, cr0);
1050         return X86EMUL_CONTINUE;
1051 }
1052
1053 int emulator_get_dr(struct x86_emulate_ctxt* ctxt, int dr, unsigned long *dest)
1054 {
1055         struct kvm_vcpu *vcpu = ctxt->vcpu;
1056
1057         switch (dr) {
1058         case 0 ... 3:
1059                 *dest = kvm_arch_ops->get_dr(vcpu, dr);
1060                 return X86EMUL_CONTINUE;
1061         default:
1062                 printk(KERN_DEBUG "%s: unexpected dr %u\n",
1063                        __FUNCTION__, dr);
1064                 return X86EMUL_UNHANDLEABLE;
1065         }
1066 }
1067
1068 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
1069 {
1070         unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
1071         int exception;
1072
1073         kvm_arch_ops->set_dr(ctxt->vcpu, dr, value & mask, &exception);
1074         if (exception) {
1075                 /* FIXME: better handling */
1076                 return X86EMUL_UNHANDLEABLE;
1077         }
1078         return X86EMUL_CONTINUE;
1079 }
1080
1081 static void report_emulation_failure(struct x86_emulate_ctxt *ctxt)
1082 {
1083         static int reported;
1084         u8 opcodes[4];
1085         unsigned long rip = ctxt->vcpu->rip;
1086         unsigned long rip_linear;
1087
1088         rip_linear = rip + get_segment_base(ctxt->vcpu, VCPU_SREG_CS);
1089
1090         if (reported)
1091                 return;
1092
1093         emulator_read_std(rip_linear, (void *)opcodes, 4, ctxt);
1094
1095         printk(KERN_ERR "emulation failed but !mmio_needed?"
1096                " rip %lx %02x %02x %02x %02x\n",
1097                rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
1098         reported = 1;
1099 }
1100
1101 struct x86_emulate_ops emulate_ops = {
1102         .read_std            = emulator_read_std,
1103         .write_std           = emulator_write_std,
1104         .read_emulated       = emulator_read_emulated,
1105         .write_emulated      = emulator_write_emulated,
1106         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
1107 #ifdef CONFIG_X86_32
1108         .cmpxchg8b_emulated  = emulator_cmpxchg8b_emulated,
1109 #endif
1110 };
1111
1112 int emulate_instruction(struct kvm_vcpu *vcpu,
1113                         struct kvm_run *run,
1114                         unsigned long cr2,
1115                         u16 error_code)
1116 {
1117         struct x86_emulate_ctxt emulate_ctxt;
1118         int r;
1119         int cs_db, cs_l;
1120
1121         kvm_arch_ops->cache_regs(vcpu);
1122
1123         kvm_arch_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
1124
1125         emulate_ctxt.vcpu = vcpu;
1126         emulate_ctxt.eflags = kvm_arch_ops->get_rflags(vcpu);
1127         emulate_ctxt.cr2 = cr2;
1128         emulate_ctxt.mode = (emulate_ctxt.eflags & X86_EFLAGS_VM)
1129                 ? X86EMUL_MODE_REAL : cs_l
1130                 ? X86EMUL_MODE_PROT64 : cs_db
1131                 ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
1132
1133         if (emulate_ctxt.mode == X86EMUL_MODE_PROT64) {
1134                 emulate_ctxt.cs_base = 0;
1135                 emulate_ctxt.ds_base = 0;
1136                 emulate_ctxt.es_base = 0;
1137                 emulate_ctxt.ss_base = 0;
1138         } else {
1139                 emulate_ctxt.cs_base = get_segment_base(vcpu, VCPU_SREG_CS);
1140                 emulate_ctxt.ds_base = get_segment_base(vcpu, VCPU_SREG_DS);
1141                 emulate_ctxt.es_base = get_segment_base(vcpu, VCPU_SREG_ES);
1142                 emulate_ctxt.ss_base = get_segment_base(vcpu, VCPU_SREG_SS);
1143         }
1144
1145         emulate_ctxt.gs_base = get_segment_base(vcpu, VCPU_SREG_GS);
1146         emulate_ctxt.fs_base = get_segment_base(vcpu, VCPU_SREG_FS);
1147
1148         vcpu->mmio_is_write = 0;
1149         r = x86_emulate_memop(&emulate_ctxt, &emulate_ops);
1150
1151         if ((r || vcpu->mmio_is_write) && run) {
1152                 run->mmio.phys_addr = vcpu->mmio_phys_addr;
1153                 memcpy(run->mmio.data, vcpu->mmio_data, 8);
1154                 run->mmio.len = vcpu->mmio_size;
1155                 run->mmio.is_write = vcpu->mmio_is_write;
1156         }
1157
1158         if (r) {
1159                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
1160                         return EMULATE_DONE;
1161                 if (!vcpu->mmio_needed) {
1162                         report_emulation_failure(&emulate_ctxt);
1163                         return EMULATE_FAIL;
1164                 }
1165                 return EMULATE_DO_MMIO;
1166         }
1167
1168         kvm_arch_ops->decache_regs(vcpu);
1169         kvm_arch_ops->set_rflags(vcpu, emulate_ctxt.eflags);
1170
1171         if (vcpu->mmio_is_write)
1172                 return EMULATE_DO_MMIO;
1173
1174         return EMULATE_DONE;
1175 }
1176 EXPORT_SYMBOL_GPL(emulate_instruction);
1177
1178 int kvm_hypercall(struct kvm_vcpu *vcpu, struct kvm_run *run)
1179 {
1180         unsigned long nr, a0, a1, a2, a3, a4, a5, ret;
1181
1182         kvm_arch_ops->cache_regs(vcpu);
1183         ret = -KVM_EINVAL;
1184 #ifdef CONFIG_X86_64
1185         if (is_long_mode(vcpu)) {
1186                 nr = vcpu->regs[VCPU_REGS_RAX];
1187                 a0 = vcpu->regs[VCPU_REGS_RDI];
1188                 a1 = vcpu->regs[VCPU_REGS_RSI];
1189                 a2 = vcpu->regs[VCPU_REGS_RDX];
1190                 a3 = vcpu->regs[VCPU_REGS_RCX];
1191                 a4 = vcpu->regs[VCPU_REGS_R8];
1192                 a5 = vcpu->regs[VCPU_REGS_R9];
1193         } else
1194 #endif
1195         {
1196                 nr = vcpu->regs[VCPU_REGS_RBX] & -1u;
1197                 a0 = vcpu->regs[VCPU_REGS_RAX] & -1u;
1198                 a1 = vcpu->regs[VCPU_REGS_RCX] & -1u;
1199                 a2 = vcpu->regs[VCPU_REGS_RDX] & -1u;
1200                 a3 = vcpu->regs[VCPU_REGS_RSI] & -1u;
1201                 a4 = vcpu->regs[VCPU_REGS_RDI] & -1u;
1202                 a5 = vcpu->regs[VCPU_REGS_RBP] & -1u;
1203         }
1204         switch (nr) {
1205         default:
1206                 run->hypercall.args[0] = a0;
1207                 run->hypercall.args[1] = a1;
1208                 run->hypercall.args[2] = a2;
1209                 run->hypercall.args[3] = a3;
1210                 run->hypercall.args[4] = a4;
1211                 run->hypercall.args[5] = a5;
1212                 run->hypercall.ret = ret;
1213                 run->hypercall.longmode = is_long_mode(vcpu);
1214                 kvm_arch_ops->decache_regs(vcpu);
1215                 return 0;
1216         }
1217         vcpu->regs[VCPU_REGS_RAX] = ret;
1218         kvm_arch_ops->decache_regs(vcpu);
1219         return 1;
1220 }
1221 EXPORT_SYMBOL_GPL(kvm_hypercall);
1222
1223 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
1224 {
1225         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
1226 }
1227
1228 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
1229 {
1230         struct descriptor_table dt = { limit, base };
1231
1232         kvm_arch_ops->set_gdt(vcpu, &dt);
1233 }
1234
1235 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
1236 {
1237         struct descriptor_table dt = { limit, base };
1238
1239         kvm_arch_ops->set_idt(vcpu, &dt);
1240 }
1241
1242 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
1243                    unsigned long *rflags)
1244 {
1245         lmsw(vcpu, msw);
1246         *rflags = kvm_arch_ops->get_rflags(vcpu);
1247 }
1248
1249 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
1250 {
1251         kvm_arch_ops->decache_cr0_cr4_guest_bits(vcpu);
1252         switch (cr) {
1253         case 0:
1254                 return vcpu->cr0;
1255         case 2:
1256                 return vcpu->cr2;
1257         case 3:
1258                 return vcpu->cr3;
1259         case 4:
1260                 return vcpu->cr4;
1261         default:
1262                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
1263                 return 0;
1264         }
1265 }
1266
1267 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
1268                      unsigned long *rflags)
1269 {
1270         switch (cr) {
1271         case 0:
1272                 set_cr0(vcpu, mk_cr_64(vcpu->cr0, val));
1273                 *rflags = kvm_arch_ops->get_rflags(vcpu);
1274                 break;
1275         case 2:
1276                 vcpu->cr2 = val;
1277                 break;
1278         case 3:
1279                 set_cr3(vcpu, val);
1280                 break;
1281         case 4:
1282                 set_cr4(vcpu, mk_cr_64(vcpu->cr4, val));
1283                 break;
1284         default:
1285                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
1286         }
1287 }
1288
1289 /*
1290  * Register the para guest with the host:
1291  */
1292 static int vcpu_register_para(struct kvm_vcpu *vcpu, gpa_t para_state_gpa)
1293 {
1294         struct kvm_vcpu_para_state *para_state;
1295         hpa_t para_state_hpa, hypercall_hpa;
1296         struct page *para_state_page;
1297         unsigned char *hypercall;
1298         gpa_t hypercall_gpa;
1299
1300         printk(KERN_DEBUG "kvm: guest trying to enter paravirtual mode\n");
1301         printk(KERN_DEBUG ".... para_state_gpa: %08Lx\n", para_state_gpa);
1302
1303         /*
1304          * Needs to be page aligned:
1305          */
1306         if (para_state_gpa != PAGE_ALIGN(para_state_gpa))
1307                 goto err_gp;
1308
1309         para_state_hpa = gpa_to_hpa(vcpu, para_state_gpa);
1310         printk(KERN_DEBUG ".... para_state_hpa: %08Lx\n", para_state_hpa);
1311         if (is_error_hpa(para_state_hpa))
1312                 goto err_gp;
1313
1314         mark_page_dirty(vcpu->kvm, para_state_gpa >> PAGE_SHIFT);
1315         para_state_page = pfn_to_page(para_state_hpa >> PAGE_SHIFT);
1316         para_state = kmap_atomic(para_state_page, KM_USER0);
1317
1318         printk(KERN_DEBUG "....  guest version: %d\n", para_state->guest_version);
1319         printk(KERN_DEBUG "....           size: %d\n", para_state->size);
1320
1321         para_state->host_version = KVM_PARA_API_VERSION;
1322         /*
1323          * We cannot support guests that try to register themselves
1324          * with a newer API version than the host supports:
1325          */
1326         if (para_state->guest_version > KVM_PARA_API_VERSION) {
1327                 para_state->ret = -KVM_EINVAL;
1328                 goto err_kunmap_skip;
1329         }
1330
1331         hypercall_gpa = para_state->hypercall_gpa;
1332         hypercall_hpa = gpa_to_hpa(vcpu, hypercall_gpa);
1333         printk(KERN_DEBUG ".... hypercall_hpa: %08Lx\n", hypercall_hpa);
1334         if (is_error_hpa(hypercall_hpa)) {
1335                 para_state->ret = -KVM_EINVAL;
1336                 goto err_kunmap_skip;
1337         }
1338
1339         printk(KERN_DEBUG "kvm: para guest successfully registered.\n");
1340         vcpu->para_state_page = para_state_page;
1341         vcpu->para_state_gpa = para_state_gpa;
1342         vcpu->hypercall_gpa = hypercall_gpa;
1343
1344         mark_page_dirty(vcpu->kvm, hypercall_gpa >> PAGE_SHIFT);
1345         hypercall = kmap_atomic(pfn_to_page(hypercall_hpa >> PAGE_SHIFT),
1346                                 KM_USER1) + (hypercall_hpa & ~PAGE_MASK);
1347         kvm_arch_ops->patch_hypercall(vcpu, hypercall);
1348         kunmap_atomic(hypercall, KM_USER1);
1349
1350         para_state->ret = 0;
1351 err_kunmap_skip:
1352         kunmap_atomic(para_state, KM_USER0);
1353         return 0;
1354 err_gp:
1355         return 1;
1356 }
1357
1358 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1359 {
1360         u64 data;
1361
1362         switch (msr) {
1363         case 0xc0010010: /* SYSCFG */
1364         case 0xc0010015: /* HWCR */
1365         case MSR_IA32_PLATFORM_ID:
1366         case MSR_IA32_P5_MC_ADDR:
1367         case MSR_IA32_P5_MC_TYPE:
1368         case MSR_IA32_MC0_CTL:
1369         case MSR_IA32_MCG_STATUS:
1370         case MSR_IA32_MCG_CAP:
1371         case MSR_IA32_MC0_MISC:
1372         case MSR_IA32_MC0_MISC+4:
1373         case MSR_IA32_MC0_MISC+8:
1374         case MSR_IA32_MC0_MISC+12:
1375         case MSR_IA32_MC0_MISC+16:
1376         case MSR_IA32_UCODE_REV:
1377         case MSR_IA32_PERF_STATUS:
1378                 /* MTRR registers */
1379         case 0xfe:
1380         case 0x200 ... 0x2ff:
1381                 data = 0;
1382                 break;
1383         case 0xcd: /* fsb frequency */
1384                 data = 3;
1385                 break;
1386         case MSR_IA32_APICBASE:
1387                 data = vcpu->apic_base;
1388                 break;
1389         case MSR_IA32_MISC_ENABLE:
1390                 data = vcpu->ia32_misc_enable_msr;
1391                 break;
1392 #ifdef CONFIG_X86_64
1393         case MSR_EFER:
1394                 data = vcpu->shadow_efer;
1395                 break;
1396 #endif
1397         default:
1398                 printk(KERN_ERR "kvm: unhandled rdmsr: 0x%x\n", msr);
1399                 return 1;
1400         }
1401         *pdata = data;
1402         return 0;
1403 }
1404 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
1405
1406 /*
1407  * Reads an msr value (of 'msr_index') into 'pdata'.
1408  * Returns 0 on success, non-0 otherwise.
1409  * Assumes vcpu_load() was already called.
1410  */
1411 static int get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1412 {
1413         return kvm_arch_ops->get_msr(vcpu, msr_index, pdata);
1414 }
1415
1416 #ifdef CONFIG_X86_64
1417
1418 static void set_efer(struct kvm_vcpu *vcpu, u64 efer)
1419 {
1420         if (efer & EFER_RESERVED_BITS) {
1421                 printk(KERN_DEBUG "set_efer: 0x%llx #GP, reserved bits\n",
1422                        efer);
1423                 inject_gp(vcpu);
1424                 return;
1425         }
1426
1427         if (is_paging(vcpu)
1428             && (vcpu->shadow_efer & EFER_LME) != (efer & EFER_LME)) {
1429                 printk(KERN_DEBUG "set_efer: #GP, change LME while paging\n");
1430                 inject_gp(vcpu);
1431                 return;
1432         }
1433
1434         kvm_arch_ops->set_efer(vcpu, efer);
1435
1436         efer &= ~EFER_LMA;
1437         efer |= vcpu->shadow_efer & EFER_LMA;
1438
1439         vcpu->shadow_efer = efer;
1440 }
1441
1442 #endif
1443
1444 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1445 {
1446         switch (msr) {
1447 #ifdef CONFIG_X86_64
1448         case MSR_EFER:
1449                 set_efer(vcpu, data);
1450                 break;
1451 #endif
1452         case MSR_IA32_MC0_STATUS:
1453                 printk(KERN_WARNING "%s: MSR_IA32_MC0_STATUS 0x%llx, nop\n",
1454                        __FUNCTION__, data);
1455                 break;
1456         case MSR_IA32_UCODE_REV:
1457         case MSR_IA32_UCODE_WRITE:
1458         case 0x200 ... 0x2ff: /* MTRRs */
1459                 break;
1460         case MSR_IA32_APICBASE:
1461                 vcpu->apic_base = data;
1462                 break;
1463         case MSR_IA32_MISC_ENABLE:
1464                 vcpu->ia32_misc_enable_msr = data;
1465                 break;
1466         /*
1467          * This is the 'probe whether the host is KVM' logic:
1468          */
1469         case MSR_KVM_API_MAGIC:
1470                 return vcpu_register_para(vcpu, data);
1471
1472         default:
1473                 printk(KERN_ERR "kvm: unhandled wrmsr: 0x%x\n", msr);
1474                 return 1;
1475         }
1476         return 0;
1477 }
1478 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
1479
1480 /*
1481  * Writes msr value into into the appropriate "register".
1482  * Returns 0 on success, non-0 otherwise.
1483  * Assumes vcpu_load() was already called.
1484  */
1485 static int set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
1486 {
1487         return kvm_arch_ops->set_msr(vcpu, msr_index, data);
1488 }
1489
1490 void kvm_resched(struct kvm_vcpu *vcpu)
1491 {
1492         vcpu_put(vcpu);
1493         cond_resched();
1494         vcpu_load(vcpu);
1495 }
1496 EXPORT_SYMBOL_GPL(kvm_resched);
1497
1498 void load_msrs(struct vmx_msr_entry *e, int n)
1499 {
1500         int i;
1501
1502         for (i = 0; i < n; ++i)
1503                 wrmsrl(e[i].index, e[i].data);
1504 }
1505 EXPORT_SYMBOL_GPL(load_msrs);
1506
1507 void save_msrs(struct vmx_msr_entry *e, int n)
1508 {
1509         int i;
1510
1511         for (i = 0; i < n; ++i)
1512                 rdmsrl(e[i].index, e[i].data);
1513 }
1514 EXPORT_SYMBOL_GPL(save_msrs);
1515
1516 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
1517 {
1518         int i;
1519         u32 function;
1520         struct kvm_cpuid_entry *e, *best;
1521
1522         kvm_arch_ops->cache_regs(vcpu);
1523         function = vcpu->regs[VCPU_REGS_RAX];
1524         vcpu->regs[VCPU_REGS_RAX] = 0;
1525         vcpu->regs[VCPU_REGS_RBX] = 0;
1526         vcpu->regs[VCPU_REGS_RCX] = 0;
1527         vcpu->regs[VCPU_REGS_RDX] = 0;
1528         best = NULL;
1529         for (i = 0; i < vcpu->cpuid_nent; ++i) {
1530                 e = &vcpu->cpuid_entries[i];
1531                 if (e->function == function) {
1532                         best = e;
1533                         break;
1534                 }
1535                 /*
1536                  * Both basic or both extended?
1537                  */
1538                 if (((e->function ^ function) & 0x80000000) == 0)
1539                         if (!best || e->function > best->function)
1540                                 best = e;
1541         }
1542         if (best) {
1543                 vcpu->regs[VCPU_REGS_RAX] = best->eax;
1544                 vcpu->regs[VCPU_REGS_RBX] = best->ebx;
1545                 vcpu->regs[VCPU_REGS_RCX] = best->ecx;
1546                 vcpu->regs[VCPU_REGS_RDX] = best->edx;
1547         }
1548         kvm_arch_ops->decache_regs(vcpu);
1549         kvm_arch_ops->skip_emulated_instruction(vcpu);
1550 }
1551 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
1552
1553 static void complete_pio(struct kvm_vcpu *vcpu)
1554 {
1555         struct kvm_io *io = &vcpu->run->io;
1556         long delta;
1557
1558         kvm_arch_ops->cache_regs(vcpu);
1559
1560         if (!io->string) {
1561                 if (io->direction == KVM_EXIT_IO_IN)
1562                         memcpy(&vcpu->regs[VCPU_REGS_RAX], &io->value,
1563                                io->size);
1564         } else {
1565                 delta = 1;
1566                 if (io->rep) {
1567                         delta *= io->count;
1568                         /*
1569                          * The size of the register should really depend on
1570                          * current address size.
1571                          */
1572                         vcpu->regs[VCPU_REGS_RCX] -= delta;
1573                 }
1574                 if (io->string_down)
1575                         delta = -delta;
1576                 delta *= io->size;
1577                 if (io->direction == KVM_EXIT_IO_IN)
1578                         vcpu->regs[VCPU_REGS_RDI] += delta;
1579                 else
1580                         vcpu->regs[VCPU_REGS_RSI] += delta;
1581         }
1582
1583         vcpu->pio_pending = 0;
1584         vcpu->run->io_completed = 0;
1585
1586         kvm_arch_ops->decache_regs(vcpu);
1587
1588         kvm_arch_ops->skip_emulated_instruction(vcpu);
1589 }
1590
1591 static int kvm_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
1592 {
1593         int r;
1594
1595         vcpu_load(vcpu);
1596
1597         /* re-sync apic's tpr */
1598         vcpu->cr8 = kvm_run->cr8;
1599
1600         if (kvm_run->io_completed) {
1601                 if (vcpu->pio_pending)
1602                         complete_pio(vcpu);
1603                 else {
1604                         memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
1605                         vcpu->mmio_read_completed = 1;
1606                 }
1607         }
1608
1609         vcpu->mmio_needed = 0;
1610
1611         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL) {
1612                 kvm_arch_ops->cache_regs(vcpu);
1613                 vcpu->regs[VCPU_REGS_RAX] = kvm_run->hypercall.ret;
1614                 kvm_arch_ops->decache_regs(vcpu);
1615         }
1616
1617         r = kvm_arch_ops->run(vcpu, kvm_run);
1618
1619         vcpu_put(vcpu);
1620         return r;
1621 }
1622
1623 static int kvm_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu,
1624                                    struct kvm_regs *regs)
1625 {
1626         vcpu_load(vcpu);
1627
1628         kvm_arch_ops->cache_regs(vcpu);
1629
1630         regs->rax = vcpu->regs[VCPU_REGS_RAX];
1631         regs->rbx = vcpu->regs[VCPU_REGS_RBX];
1632         regs->rcx = vcpu->regs[VCPU_REGS_RCX];
1633         regs->rdx = vcpu->regs[VCPU_REGS_RDX];
1634         regs->rsi = vcpu->regs[VCPU_REGS_RSI];
1635         regs->rdi = vcpu->regs[VCPU_REGS_RDI];
1636         regs->rsp = vcpu->regs[VCPU_REGS_RSP];
1637         regs->rbp = vcpu->regs[VCPU_REGS_RBP];
1638 #ifdef CONFIG_X86_64
1639         regs->r8 = vcpu->regs[VCPU_REGS_R8];
1640         regs->r9 = vcpu->regs[VCPU_REGS_R9];
1641         regs->r10 = vcpu->regs[VCPU_REGS_R10];
1642         regs->r11 = vcpu->regs[VCPU_REGS_R11];
1643         regs->r12 = vcpu->regs[VCPU_REGS_R12];
1644         regs->r13 = vcpu->regs[VCPU_REGS_R13];
1645         regs->r14 = vcpu->regs[VCPU_REGS_R14];
1646         regs->r15 = vcpu->regs[VCPU_REGS_R15];
1647 #endif
1648
1649         regs->rip = vcpu->rip;
1650         regs->rflags = kvm_arch_ops->get_rflags(vcpu);
1651
1652         /*
1653          * Don't leak debug flags in case they were set for guest debugging
1654          */
1655         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
1656                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
1657
1658         vcpu_put(vcpu);
1659
1660         return 0;
1661 }
1662
1663 static int kvm_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu,
1664                                    struct kvm_regs *regs)
1665 {
1666         vcpu_load(vcpu);
1667
1668         vcpu->regs[VCPU_REGS_RAX] = regs->rax;
1669         vcpu->regs[VCPU_REGS_RBX] = regs->rbx;
1670         vcpu->regs[VCPU_REGS_RCX] = regs->rcx;
1671         vcpu->regs[VCPU_REGS_RDX] = regs->rdx;
1672         vcpu->regs[VCPU_REGS_RSI] = regs->rsi;
1673         vcpu->regs[VCPU_REGS_RDI] = regs->rdi;
1674         vcpu->regs[VCPU_REGS_RSP] = regs->rsp;
1675         vcpu->regs[VCPU_REGS_RBP] = regs->rbp;
1676 #ifdef CONFIG_X86_64
1677         vcpu->regs[VCPU_REGS_R8] = regs->r8;
1678         vcpu->regs[VCPU_REGS_R9] = regs->r9;
1679         vcpu->regs[VCPU_REGS_R10] = regs->r10;
1680         vcpu->regs[VCPU_REGS_R11] = regs->r11;
1681         vcpu->regs[VCPU_REGS_R12] = regs->r12;
1682         vcpu->regs[VCPU_REGS_R13] = regs->r13;
1683         vcpu->regs[VCPU_REGS_R14] = regs->r14;
1684         vcpu->regs[VCPU_REGS_R15] = regs->r15;
1685 #endif
1686
1687         vcpu->rip = regs->rip;
1688         kvm_arch_ops->set_rflags(vcpu, regs->rflags);
1689
1690         kvm_arch_ops->decache_regs(vcpu);
1691
1692         vcpu_put(vcpu);
1693
1694         return 0;
1695 }
1696
1697 static void get_segment(struct kvm_vcpu *vcpu,
1698                         struct kvm_segment *var, int seg)
1699 {
1700         return kvm_arch_ops->get_segment(vcpu, var, seg);
1701 }
1702
1703 static int kvm_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
1704                                     struct kvm_sregs *sregs)
1705 {
1706         struct descriptor_table dt;
1707
1708         vcpu_load(vcpu);
1709
1710         get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
1711         get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
1712         get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
1713         get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
1714         get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
1715         get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
1716
1717         get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
1718         get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
1719
1720         kvm_arch_ops->get_idt(vcpu, &dt);
1721         sregs->idt.limit = dt.limit;
1722         sregs->idt.base = dt.base;
1723         kvm_arch_ops->get_gdt(vcpu, &dt);
1724         sregs->gdt.limit = dt.limit;
1725         sregs->gdt.base = dt.base;
1726
1727         kvm_arch_ops->decache_cr0_cr4_guest_bits(vcpu);
1728         sregs->cr0 = vcpu->cr0;
1729         sregs->cr2 = vcpu->cr2;
1730         sregs->cr3 = vcpu->cr3;
1731         sregs->cr4 = vcpu->cr4;
1732         sregs->cr8 = vcpu->cr8;
1733         sregs->efer = vcpu->shadow_efer;
1734         sregs->apic_base = vcpu->apic_base;
1735
1736         memcpy(sregs->interrupt_bitmap, vcpu->irq_pending,
1737                sizeof sregs->interrupt_bitmap);
1738
1739         vcpu_put(vcpu);
1740
1741         return 0;
1742 }
1743
1744 static void set_segment(struct kvm_vcpu *vcpu,
1745                         struct kvm_segment *var, int seg)
1746 {
1747         return kvm_arch_ops->set_segment(vcpu, var, seg);
1748 }
1749
1750 static int kvm_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
1751                                     struct kvm_sregs *sregs)
1752 {
1753         int mmu_reset_needed = 0;
1754         int i;
1755         struct descriptor_table dt;
1756
1757         vcpu_load(vcpu);
1758
1759         set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
1760         set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
1761         set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
1762         set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
1763         set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
1764         set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
1765
1766         set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
1767         set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
1768
1769         dt.limit = sregs->idt.limit;
1770         dt.base = sregs->idt.base;
1771         kvm_arch_ops->set_idt(vcpu, &dt);
1772         dt.limit = sregs->gdt.limit;
1773         dt.base = sregs->gdt.base;
1774         kvm_arch_ops->set_gdt(vcpu, &dt);
1775
1776         vcpu->cr2 = sregs->cr2;
1777         mmu_reset_needed |= vcpu->cr3 != sregs->cr3;
1778         vcpu->cr3 = sregs->cr3;
1779
1780         vcpu->cr8 = sregs->cr8;
1781
1782         mmu_reset_needed |= vcpu->shadow_efer != sregs->efer;
1783 #ifdef CONFIG_X86_64
1784         kvm_arch_ops->set_efer(vcpu, sregs->efer);
1785 #endif
1786         vcpu->apic_base = sregs->apic_base;
1787
1788         kvm_arch_ops->decache_cr0_cr4_guest_bits(vcpu);
1789
1790         mmu_reset_needed |= vcpu->cr0 != sregs->cr0;
1791         kvm_arch_ops->set_cr0_no_modeswitch(vcpu, sregs->cr0);
1792
1793         mmu_reset_needed |= vcpu->cr4 != sregs->cr4;
1794         kvm_arch_ops->set_cr4(vcpu, sregs->cr4);
1795         if (!is_long_mode(vcpu) && is_pae(vcpu))
1796                 load_pdptrs(vcpu, vcpu->cr3);
1797
1798         if (mmu_reset_needed)
1799                 kvm_mmu_reset_context(vcpu);
1800
1801         memcpy(vcpu->irq_pending, sregs->interrupt_bitmap,
1802                sizeof vcpu->irq_pending);
1803         vcpu->irq_summary = 0;
1804         for (i = 0; i < NR_IRQ_WORDS; ++i)
1805                 if (vcpu->irq_pending[i])
1806                         __set_bit(i, &vcpu->irq_summary);
1807
1808         vcpu_put(vcpu);
1809
1810         return 0;
1811 }
1812
1813 /*
1814  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1815  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1816  *
1817  * This list is modified at module load time to reflect the
1818  * capabilities of the host cpu.
1819  */
1820 static u32 msrs_to_save[] = {
1821         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1822         MSR_K6_STAR,
1823 #ifdef CONFIG_X86_64
1824         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1825 #endif
1826         MSR_IA32_TIME_STAMP_COUNTER,
1827 };
1828
1829 static unsigned num_msrs_to_save;
1830
1831 static u32 emulated_msrs[] = {
1832         MSR_IA32_MISC_ENABLE,
1833 };
1834
1835 static __init void kvm_init_msr_list(void)
1836 {
1837         u32 dummy[2];
1838         unsigned i, j;
1839
1840         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
1841                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
1842                         continue;
1843                 if (j < i)
1844                         msrs_to_save[j] = msrs_to_save[i];
1845                 j++;
1846         }
1847         num_msrs_to_save = j;
1848 }
1849
1850 /*
1851  * Adapt set_msr() to msr_io()'s calling convention
1852  */
1853 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1854 {
1855         return set_msr(vcpu, index, *data);
1856 }
1857
1858 /*
1859  * Read or write a bunch of msrs. All parameters are kernel addresses.
1860  *
1861  * @return number of msrs set successfully.
1862  */
1863 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
1864                     struct kvm_msr_entry *entries,
1865                     int (*do_msr)(struct kvm_vcpu *vcpu,
1866                                   unsigned index, u64 *data))
1867 {
1868         int i;
1869
1870         vcpu_load(vcpu);
1871
1872         for (i = 0; i < msrs->nmsrs; ++i)
1873                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
1874                         break;
1875
1876         vcpu_put(vcpu);
1877
1878         return i;
1879 }
1880
1881 /*
1882  * Read or write a bunch of msrs. Parameters are user addresses.
1883  *
1884  * @return number of msrs set successfully.
1885  */
1886 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
1887                   int (*do_msr)(struct kvm_vcpu *vcpu,
1888                                 unsigned index, u64 *data),
1889                   int writeback)
1890 {
1891         struct kvm_msrs msrs;
1892         struct kvm_msr_entry *entries;
1893         int r, n;
1894         unsigned size;
1895
1896         r = -EFAULT;
1897         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
1898                 goto out;
1899
1900         r = -E2BIG;
1901         if (msrs.nmsrs >= MAX_IO_MSRS)
1902                 goto out;
1903
1904         r = -ENOMEM;
1905         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
1906         entries = vmalloc(size);
1907         if (!entries)
1908                 goto out;
1909
1910         r = -EFAULT;
1911         if (copy_from_user(entries, user_msrs->entries, size))
1912                 goto out_free;
1913
1914         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
1915         if (r < 0)
1916                 goto out_free;
1917
1918         r = -EFAULT;
1919         if (writeback && copy_to_user(user_msrs->entries, entries, size))
1920                 goto out_free;
1921
1922         r = n;
1923
1924 out_free:
1925         vfree(entries);
1926 out:
1927         return r;
1928 }
1929
1930 /*
1931  * Translate a guest virtual address to a guest physical address.
1932  */
1933 static int kvm_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
1934                                     struct kvm_translation *tr)
1935 {
1936         unsigned long vaddr = tr->linear_address;
1937         gpa_t gpa;
1938
1939         vcpu_load(vcpu);
1940         spin_lock(&vcpu->kvm->lock);
1941         gpa = vcpu->mmu.gva_to_gpa(vcpu, vaddr);
1942         tr->physical_address = gpa;
1943         tr->valid = gpa != UNMAPPED_GVA;
1944         tr->writeable = 1;
1945         tr->usermode = 0;
1946         spin_unlock(&vcpu->kvm->lock);
1947         vcpu_put(vcpu);
1948
1949         return 0;
1950 }
1951
1952 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
1953                                     struct kvm_interrupt *irq)
1954 {
1955         if (irq->irq < 0 || irq->irq >= 256)
1956                 return -EINVAL;
1957         vcpu_load(vcpu);
1958
1959         set_bit(irq->irq, vcpu->irq_pending);
1960         set_bit(irq->irq / BITS_PER_LONG, &vcpu->irq_summary);
1961
1962         vcpu_put(vcpu);
1963
1964         return 0;
1965 }
1966
1967 static int kvm_vcpu_ioctl_debug_guest(struct kvm_vcpu *vcpu,
1968                                       struct kvm_debug_guest *dbg)
1969 {
1970         int r;
1971
1972         vcpu_load(vcpu);
1973
1974         r = kvm_arch_ops->set_guest_debug(vcpu, dbg);
1975
1976         vcpu_put(vcpu);
1977
1978         return r;
1979 }
1980
1981 static struct page *kvm_vcpu_nopage(struct vm_area_struct *vma,
1982                                     unsigned long address,
1983                                     int *type)
1984 {
1985         struct kvm_vcpu *vcpu = vma->vm_file->private_data;
1986         unsigned long pgoff;
1987         struct page *page;
1988
1989         *type = VM_FAULT_MINOR;
1990         pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
1991         if (pgoff != 0)
1992                 return NOPAGE_SIGBUS;
1993         page = virt_to_page(vcpu->run);
1994         get_page(page);
1995         return page;
1996 }
1997
1998 static struct vm_operations_struct kvm_vcpu_vm_ops = {
1999         .nopage = kvm_vcpu_nopage,
2000 };
2001
2002 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2003 {
2004         vma->vm_ops = &kvm_vcpu_vm_ops;
2005         return 0;
2006 }
2007
2008 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2009 {
2010         struct kvm_vcpu *vcpu = filp->private_data;
2011
2012         fput(vcpu->kvm->filp);
2013         return 0;
2014 }
2015
2016 static struct file_operations kvm_vcpu_fops = {
2017         .release        = kvm_vcpu_release,
2018         .unlocked_ioctl = kvm_vcpu_ioctl,
2019         .compat_ioctl   = kvm_vcpu_ioctl,
2020         .mmap           = kvm_vcpu_mmap,
2021 };
2022
2023 /*
2024  * Allocates an inode for the vcpu.
2025  */
2026 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2027 {
2028         int fd, r;
2029         struct inode *inode;
2030         struct file *file;
2031
2032         atomic_inc(&vcpu->kvm->filp->f_count);
2033         inode = kvmfs_inode(&kvm_vcpu_fops);
2034         if (IS_ERR(inode)) {
2035                 r = PTR_ERR(inode);
2036                 goto out1;
2037         }
2038
2039         file = kvmfs_file(inode, vcpu);
2040         if (IS_ERR(file)) {
2041                 r = PTR_ERR(file);
2042                 goto out2;
2043         }
2044
2045         r = get_unused_fd();
2046         if (r < 0)
2047                 goto out3;
2048         fd = r;
2049         fd_install(fd, file);
2050
2051         return fd;
2052
2053 out3:
2054         fput(file);
2055 out2:
2056         iput(inode);
2057 out1:
2058         fput(vcpu->kvm->filp);
2059         return r;
2060 }
2061
2062 /*
2063  * Creates some virtual cpus.  Good luck creating more than one.
2064  */
2065 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, int n)
2066 {
2067         int r;
2068         struct kvm_vcpu *vcpu;
2069         struct page *page;
2070
2071         r = -EINVAL;
2072         if (!valid_vcpu(n))
2073                 goto out;
2074
2075         vcpu = &kvm->vcpus[n];
2076
2077         mutex_lock(&vcpu->mutex);
2078
2079         if (vcpu->vmcs) {
2080                 mutex_unlock(&vcpu->mutex);
2081                 return -EEXIST;
2082         }
2083
2084         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2085         r = -ENOMEM;
2086         if (!page)
2087                 goto out_unlock;
2088         vcpu->run = page_address(page);
2089
2090         vcpu->host_fx_image = (char*)ALIGN((hva_t)vcpu->fx_buf,
2091                                            FX_IMAGE_ALIGN);
2092         vcpu->guest_fx_image = vcpu->host_fx_image + FX_IMAGE_SIZE;
2093
2094         r = kvm_arch_ops->vcpu_create(vcpu);
2095         if (r < 0)
2096                 goto out_free_vcpus;
2097
2098         r = kvm_mmu_create(vcpu);
2099         if (r < 0)
2100                 goto out_free_vcpus;
2101
2102         kvm_arch_ops->vcpu_load(vcpu);
2103         r = kvm_mmu_setup(vcpu);
2104         if (r >= 0)
2105                 r = kvm_arch_ops->vcpu_setup(vcpu);
2106         vcpu_put(vcpu);
2107
2108         if (r < 0)
2109                 goto out_free_vcpus;
2110
2111         r = create_vcpu_fd(vcpu);
2112         if (r < 0)
2113                 goto out_free_vcpus;
2114
2115         return r;
2116
2117 out_free_vcpus:
2118         kvm_free_vcpu(vcpu);
2119 out_unlock:
2120         mutex_unlock(&vcpu->mutex);
2121 out:
2122         return r;
2123 }
2124
2125 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
2126                                     struct kvm_cpuid *cpuid,
2127                                     struct kvm_cpuid_entry __user *entries)
2128 {
2129         int r;
2130
2131         r = -E2BIG;
2132         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2133                 goto out;
2134         r = -EFAULT;
2135         if (copy_from_user(&vcpu->cpuid_entries, entries,
2136                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
2137                 goto out;
2138         vcpu->cpuid_nent = cpuid->nent;
2139         return 0;
2140
2141 out:
2142         return r;
2143 }
2144
2145 static long kvm_vcpu_ioctl(struct file *filp,
2146                            unsigned int ioctl, unsigned long arg)
2147 {
2148         struct kvm_vcpu *vcpu = filp->private_data;
2149         void __user *argp = (void __user *)arg;
2150         int r = -EINVAL;
2151
2152         switch (ioctl) {
2153         case KVM_RUN:
2154                 r = kvm_vcpu_ioctl_run(vcpu, vcpu->run);
2155                 break;
2156         case KVM_GET_REGS: {
2157                 struct kvm_regs kvm_regs;
2158
2159                 memset(&kvm_regs, 0, sizeof kvm_regs);
2160                 r = kvm_vcpu_ioctl_get_regs(vcpu, &kvm_regs);
2161                 if (r)
2162                         goto out;
2163                 r = -EFAULT;
2164                 if (copy_to_user(argp, &kvm_regs, sizeof kvm_regs))
2165                         goto out;
2166                 r = 0;
2167                 break;
2168         }
2169         case KVM_SET_REGS: {
2170                 struct kvm_regs kvm_regs;
2171
2172                 r = -EFAULT;
2173                 if (copy_from_user(&kvm_regs, argp, sizeof kvm_regs))
2174                         goto out;
2175                 r = kvm_vcpu_ioctl_set_regs(vcpu, &kvm_regs);
2176                 if (r)
2177                         goto out;
2178                 r = 0;
2179                 break;
2180         }
2181         case KVM_GET_SREGS: {
2182                 struct kvm_sregs kvm_sregs;
2183
2184                 memset(&kvm_sregs, 0, sizeof kvm_sregs);
2185                 r = kvm_vcpu_ioctl_get_sregs(vcpu, &kvm_sregs);
2186                 if (r)
2187                         goto out;
2188                 r = -EFAULT;
2189                 if (copy_to_user(argp, &kvm_sregs, sizeof kvm_sregs))
2190                         goto out;
2191                 r = 0;
2192                 break;
2193         }
2194         case KVM_SET_SREGS: {
2195                 struct kvm_sregs kvm_sregs;
2196
2197                 r = -EFAULT;
2198                 if (copy_from_user(&kvm_sregs, argp, sizeof kvm_sregs))
2199                         goto out;
2200                 r = kvm_vcpu_ioctl_set_sregs(vcpu, &kvm_sregs);
2201                 if (r)
2202                         goto out;
2203                 r = 0;
2204                 break;
2205         }
2206         case KVM_TRANSLATE: {
2207                 struct kvm_translation tr;
2208
2209                 r = -EFAULT;
2210                 if (copy_from_user(&tr, argp, sizeof tr))
2211                         goto out;
2212                 r = kvm_vcpu_ioctl_translate(vcpu, &tr);
2213                 if (r)
2214                         goto out;
2215                 r = -EFAULT;
2216                 if (copy_to_user(argp, &tr, sizeof tr))
2217                         goto out;
2218                 r = 0;
2219                 break;
2220         }
2221         case KVM_INTERRUPT: {
2222                 struct kvm_interrupt irq;
2223
2224                 r = -EFAULT;
2225                 if (copy_from_user(&irq, argp, sizeof irq))
2226                         goto out;
2227                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
2228                 if (r)
2229                         goto out;
2230                 r = 0;
2231                 break;
2232         }
2233         case KVM_DEBUG_GUEST: {
2234                 struct kvm_debug_guest dbg;
2235
2236                 r = -EFAULT;
2237                 if (copy_from_user(&dbg, argp, sizeof dbg))
2238                         goto out;
2239                 r = kvm_vcpu_ioctl_debug_guest(vcpu, &dbg);
2240                 if (r)
2241                         goto out;
2242                 r = 0;
2243                 break;
2244         }
2245         case KVM_GET_MSRS:
2246                 r = msr_io(vcpu, argp, get_msr, 1);
2247                 break;
2248         case KVM_SET_MSRS:
2249                 r = msr_io(vcpu, argp, do_set_msr, 0);
2250                 break;
2251         case KVM_SET_CPUID: {
2252                 struct kvm_cpuid __user *cpuid_arg = argp;
2253                 struct kvm_cpuid cpuid;
2254
2255                 r = -EFAULT;
2256                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2257                         goto out;
2258                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
2259                 if (r)
2260                         goto out;
2261                 break;
2262         }
2263         default:
2264                 ;
2265         }
2266 out:
2267         return r;
2268 }
2269
2270 static long kvm_vm_ioctl(struct file *filp,
2271                            unsigned int ioctl, unsigned long arg)
2272 {
2273         struct kvm *kvm = filp->private_data;
2274         void __user *argp = (void __user *)arg;
2275         int r = -EINVAL;
2276
2277         switch (ioctl) {
2278         case KVM_CREATE_VCPU:
2279                 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
2280                 if (r < 0)
2281                         goto out;
2282                 break;
2283         case KVM_SET_MEMORY_REGION: {
2284                 struct kvm_memory_region kvm_mem;
2285
2286                 r = -EFAULT;
2287                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
2288                         goto out;
2289                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_mem);
2290                 if (r)
2291                         goto out;
2292                 break;
2293         }
2294         case KVM_GET_DIRTY_LOG: {
2295                 struct kvm_dirty_log log;
2296
2297                 r = -EFAULT;
2298                 if (copy_from_user(&log, argp, sizeof log))
2299                         goto out;
2300                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
2301                 if (r)
2302                         goto out;
2303                 break;
2304         }
2305         default:
2306                 ;
2307         }
2308 out:
2309         return r;
2310 }
2311
2312 static struct page *kvm_vm_nopage(struct vm_area_struct *vma,
2313                                   unsigned long address,
2314                                   int *type)
2315 {
2316         struct kvm *kvm = vma->vm_file->private_data;
2317         unsigned long pgoff;
2318         struct kvm_memory_slot *slot;
2319         struct page *page;
2320
2321         *type = VM_FAULT_MINOR;
2322         pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
2323         slot = gfn_to_memslot(kvm, pgoff);
2324         if (!slot)
2325                 return NOPAGE_SIGBUS;
2326         page = gfn_to_page(slot, pgoff);
2327         if (!page)
2328                 return NOPAGE_SIGBUS;
2329         get_page(page);
2330         return page;
2331 }
2332
2333 static struct vm_operations_struct kvm_vm_vm_ops = {
2334         .nopage = kvm_vm_nopage,
2335 };
2336
2337 static int kvm_vm_mmap(struct file *file, struct vm_area_struct *vma)
2338 {
2339         vma->vm_ops = &kvm_vm_vm_ops;
2340         return 0;
2341 }
2342
2343 static struct file_operations kvm_vm_fops = {
2344         .release        = kvm_vm_release,
2345         .unlocked_ioctl = kvm_vm_ioctl,
2346         .compat_ioctl   = kvm_vm_ioctl,
2347         .mmap           = kvm_vm_mmap,
2348 };
2349
2350 static int kvm_dev_ioctl_create_vm(void)
2351 {
2352         int fd, r;
2353         struct inode *inode;
2354         struct file *file;
2355         struct kvm *kvm;
2356
2357         inode = kvmfs_inode(&kvm_vm_fops);
2358         if (IS_ERR(inode)) {
2359                 r = PTR_ERR(inode);
2360                 goto out1;
2361         }
2362
2363         kvm = kvm_create_vm();
2364         if (IS_ERR(kvm)) {
2365                 r = PTR_ERR(kvm);
2366                 goto out2;
2367         }
2368
2369         file = kvmfs_file(inode, kvm);
2370         if (IS_ERR(file)) {
2371                 r = PTR_ERR(file);
2372                 goto out3;
2373         }
2374         kvm->filp = file;
2375
2376         r = get_unused_fd();
2377         if (r < 0)
2378                 goto out4;
2379         fd = r;
2380         fd_install(fd, file);
2381
2382         return fd;
2383
2384 out4:
2385         fput(file);
2386 out3:
2387         kvm_destroy_vm(kvm);
2388 out2:
2389         iput(inode);
2390 out1:
2391         return r;
2392 }
2393
2394 static long kvm_dev_ioctl(struct file *filp,
2395                           unsigned int ioctl, unsigned long arg)
2396 {
2397         void __user *argp = (void __user *)arg;
2398         int r = -EINVAL;
2399
2400         switch (ioctl) {
2401         case KVM_GET_API_VERSION:
2402                 r = KVM_API_VERSION;
2403                 break;
2404         case KVM_CREATE_VM:
2405                 r = kvm_dev_ioctl_create_vm();
2406                 break;
2407         case KVM_GET_MSR_INDEX_LIST: {
2408                 struct kvm_msr_list __user *user_msr_list = argp;
2409                 struct kvm_msr_list msr_list;
2410                 unsigned n;
2411
2412                 r = -EFAULT;
2413                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2414                         goto out;
2415                 n = msr_list.nmsrs;
2416                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
2417                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2418                         goto out;
2419                 r = -E2BIG;
2420                 if (n < num_msrs_to_save)
2421                         goto out;
2422                 r = -EFAULT;
2423                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2424                                  num_msrs_to_save * sizeof(u32)))
2425                         goto out;
2426                 if (copy_to_user(user_msr_list->indices
2427                                  + num_msrs_to_save * sizeof(u32),
2428                                  &emulated_msrs,
2429                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
2430                         goto out;
2431                 r = 0;
2432                 break;
2433         }
2434         case KVM_CHECK_EXTENSION:
2435                 /*
2436                  * No extensions defined at present.
2437                  */
2438                 r = 0;
2439                 break;
2440         default:
2441                 ;
2442         }
2443 out:
2444         return r;
2445 }
2446
2447 static struct file_operations kvm_chardev_ops = {
2448         .open           = kvm_dev_open,
2449         .release        = kvm_dev_release,
2450         .unlocked_ioctl = kvm_dev_ioctl,
2451         .compat_ioctl   = kvm_dev_ioctl,
2452 };
2453
2454 static struct miscdevice kvm_dev = {
2455         KVM_MINOR,
2456         "kvm",
2457         &kvm_chardev_ops,
2458 };
2459
2460 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
2461                        void *v)
2462 {
2463         if (val == SYS_RESTART) {
2464                 /*
2465                  * Some (well, at least mine) BIOSes hang on reboot if
2466                  * in vmx root mode.
2467                  */
2468                 printk(KERN_INFO "kvm: exiting hardware virtualization\n");
2469                 on_each_cpu(kvm_arch_ops->hardware_disable, NULL, 0, 1);
2470         }
2471         return NOTIFY_OK;
2472 }
2473
2474 static struct notifier_block kvm_reboot_notifier = {
2475         .notifier_call = kvm_reboot,
2476         .priority = 0,
2477 };
2478
2479 /*
2480  * Make sure that a cpu that is being hot-unplugged does not have any vcpus
2481  * cached on it.
2482  */
2483 static void decache_vcpus_on_cpu(int cpu)
2484 {
2485         struct kvm *vm;
2486         struct kvm_vcpu *vcpu;
2487         int i;
2488
2489         spin_lock(&kvm_lock);
2490         list_for_each_entry(vm, &vm_list, vm_list)
2491                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
2492                         vcpu = &vm->vcpus[i];
2493                         /*
2494                          * If the vcpu is locked, then it is running on some
2495                          * other cpu and therefore it is not cached on the
2496                          * cpu in question.
2497                          *
2498                          * If it's not locked, check the last cpu it executed
2499                          * on.
2500                          */
2501                         if (mutex_trylock(&vcpu->mutex)) {
2502                                 if (vcpu->cpu == cpu) {
2503                                         kvm_arch_ops->vcpu_decache(vcpu);
2504                                         vcpu->cpu = -1;
2505                                 }
2506                                 mutex_unlock(&vcpu->mutex);
2507                         }
2508                 }
2509         spin_unlock(&kvm_lock);
2510 }
2511
2512 static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
2513                            void *v)
2514 {
2515         int cpu = (long)v;
2516
2517         switch (val) {
2518         case CPU_DOWN_PREPARE:
2519         case CPU_UP_CANCELED:
2520                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
2521                        cpu);
2522                 decache_vcpus_on_cpu(cpu);
2523                 smp_call_function_single(cpu, kvm_arch_ops->hardware_disable,
2524                                          NULL, 0, 1);
2525                 break;
2526         case CPU_ONLINE:
2527                 printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
2528                        cpu);
2529                 smp_call_function_single(cpu, kvm_arch_ops->hardware_enable,
2530                                          NULL, 0, 1);
2531                 break;
2532         }
2533         return NOTIFY_OK;
2534 }
2535
2536 static struct notifier_block kvm_cpu_notifier = {
2537         .notifier_call = kvm_cpu_hotplug,
2538         .priority = 20, /* must be > scheduler priority */
2539 };
2540
2541 static __init void kvm_init_debug(void)
2542 {
2543         struct kvm_stats_debugfs_item *p;
2544
2545         debugfs_dir = debugfs_create_dir("kvm", NULL);
2546         for (p = debugfs_entries; p->name; ++p)
2547                 p->dentry = debugfs_create_u32(p->name, 0444, debugfs_dir,
2548                                                p->data);
2549 }
2550
2551 static void kvm_exit_debug(void)
2552 {
2553         struct kvm_stats_debugfs_item *p;
2554
2555         for (p = debugfs_entries; p->name; ++p)
2556                 debugfs_remove(p->dentry);
2557         debugfs_remove(debugfs_dir);
2558 }
2559
2560 static int kvm_suspend(struct sys_device *dev, pm_message_t state)
2561 {
2562         decache_vcpus_on_cpu(raw_smp_processor_id());
2563         on_each_cpu(kvm_arch_ops->hardware_disable, NULL, 0, 1);
2564         return 0;
2565 }
2566
2567 static int kvm_resume(struct sys_device *dev)
2568 {
2569         on_each_cpu(kvm_arch_ops->hardware_enable, NULL, 0, 1);
2570         return 0;
2571 }
2572
2573 static struct sysdev_class kvm_sysdev_class = {
2574         set_kset_name("kvm"),
2575         .suspend = kvm_suspend,
2576         .resume = kvm_resume,
2577 };
2578
2579 static struct sys_device kvm_sysdev = {
2580         .id = 0,
2581         .cls = &kvm_sysdev_class,
2582 };
2583
2584 hpa_t bad_page_address;
2585
2586 static int kvmfs_get_sb(struct file_system_type *fs_type, int flags,
2587                         const char *dev_name, void *data, struct vfsmount *mnt)
2588 {
2589         return get_sb_pseudo(fs_type, "kvm:", NULL, KVMFS_SUPER_MAGIC, mnt);
2590 }
2591
2592 static struct file_system_type kvm_fs_type = {
2593         .name           = "kvmfs",
2594         .get_sb         = kvmfs_get_sb,
2595         .kill_sb        = kill_anon_super,
2596 };
2597
2598 int kvm_init_arch(struct kvm_arch_ops *ops, struct module *module)
2599 {
2600         int r;
2601
2602         if (kvm_arch_ops) {
2603                 printk(KERN_ERR "kvm: already loaded the other module\n");
2604                 return -EEXIST;
2605         }
2606
2607         if (!ops->cpu_has_kvm_support()) {
2608                 printk(KERN_ERR "kvm: no hardware support\n");
2609                 return -EOPNOTSUPP;
2610         }
2611         if (ops->disabled_by_bios()) {
2612                 printk(KERN_ERR "kvm: disabled by bios\n");
2613                 return -EOPNOTSUPP;
2614         }
2615
2616         kvm_arch_ops = ops;
2617
2618         r = kvm_arch_ops->hardware_setup();
2619         if (r < 0)
2620                 goto out;
2621
2622         on_each_cpu(kvm_arch_ops->hardware_enable, NULL, 0, 1);
2623         r = register_cpu_notifier(&kvm_cpu_notifier);
2624         if (r)
2625                 goto out_free_1;
2626         register_reboot_notifier(&kvm_reboot_notifier);
2627
2628         r = sysdev_class_register(&kvm_sysdev_class);
2629         if (r)
2630                 goto out_free_2;
2631
2632         r = sysdev_register(&kvm_sysdev);
2633         if (r)
2634                 goto out_free_3;
2635
2636         kvm_chardev_ops.owner = module;
2637
2638         r = misc_register(&kvm_dev);
2639         if (r) {
2640                 printk (KERN_ERR "kvm: misc device register failed\n");
2641                 goto out_free;
2642         }
2643
2644         return r;
2645
2646 out_free:
2647         sysdev_unregister(&kvm_sysdev);
2648 out_free_3:
2649         sysdev_class_unregister(&kvm_sysdev_class);
2650 out_free_2:
2651         unregister_reboot_notifier(&kvm_reboot_notifier);
2652         unregister_cpu_notifier(&kvm_cpu_notifier);
2653 out_free_1:
2654         on_each_cpu(kvm_arch_ops->hardware_disable, NULL, 0, 1);
2655         kvm_arch_ops->hardware_unsetup();
2656 out:
2657         kvm_arch_ops = NULL;
2658         return r;
2659 }
2660
2661 void kvm_exit_arch(void)
2662 {
2663         misc_deregister(&kvm_dev);
2664         sysdev_unregister(&kvm_sysdev);
2665         sysdev_class_unregister(&kvm_sysdev_class);
2666         unregister_reboot_notifier(&kvm_reboot_notifier);
2667         unregister_cpu_notifier(&kvm_cpu_notifier);
2668         on_each_cpu(kvm_arch_ops->hardware_disable, NULL, 0, 1);
2669         kvm_arch_ops->hardware_unsetup();
2670         kvm_arch_ops = NULL;
2671 }
2672
2673 static __init int kvm_init(void)
2674 {
2675         static struct page *bad_page;
2676         int r;
2677
2678         r = register_filesystem(&kvm_fs_type);
2679         if (r)
2680                 goto out3;
2681
2682         kvmfs_mnt = kern_mount(&kvm_fs_type);
2683         r = PTR_ERR(kvmfs_mnt);
2684         if (IS_ERR(kvmfs_mnt))
2685                 goto out2;
2686         kvm_init_debug();
2687
2688         kvm_init_msr_list();
2689
2690         if ((bad_page = alloc_page(GFP_KERNEL)) == NULL) {
2691                 r = -ENOMEM;
2692                 goto out;
2693         }
2694
2695         bad_page_address = page_to_pfn(bad_page) << PAGE_SHIFT;
2696         memset(__va(bad_page_address), 0, PAGE_SIZE);
2697
2698         return 0;
2699
2700 out:
2701         kvm_exit_debug();
2702         mntput(kvmfs_mnt);
2703 out2:
2704         unregister_filesystem(&kvm_fs_type);
2705 out3:
2706         return r;
2707 }
2708
2709 static __exit void kvm_exit(void)
2710 {
2711         kvm_exit_debug();
2712         __free_page(pfn_to_page(bad_page_address >> PAGE_SHIFT));
2713         mntput(kvmfs_mnt);
2714         unregister_filesystem(&kvm_fs_type);
2715 }
2716
2717 module_init(kvm_init)
2718 module_exit(kvm_exit)
2719
2720 EXPORT_SYMBOL_GPL(kvm_init_arch);
2721 EXPORT_SYMBOL_GPL(kvm_exit_arch);