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