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