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