KVM: Move duplicate halt handling code into kvm_main.c
[pandora-kernel.git] / drivers / kvm / kvm_main.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  *
9  * Authors:
10  *   Avi Kivity   <avi@qumranet.com>
11  *   Yaniv Kamay  <yaniv@qumranet.com>
12  *
13  * This work is licensed under the terms of the GNU GPL, version 2.  See
14  * the COPYING file in the top-level directory.
15  *
16  */
17
18 #include "kvm.h"
19
20 #include <linux/kvm.h>
21 #include <linux/module.h>
22 #include <linux/errno.h>
23 #include <linux/magic.h>
24 #include <asm/processor.h>
25 #include <linux/percpu.h>
26 #include <linux/gfp.h>
27 #include <asm/msr.h>
28 #include <linux/mm.h>
29 #include <linux/miscdevice.h>
30 #include <linux/vmalloc.h>
31 #include <asm/uaccess.h>
32 #include <linux/reboot.h>
33 #include <asm/io.h>
34 #include <linux/debugfs.h>
35 #include <linux/highmem.h>
36 #include <linux/file.h>
37 #include <asm/desc.h>
38 #include <linux/sysdev.h>
39 #include <linux/cpu.h>
40 #include <linux/file.h>
41 #include <linux/fs.h>
42 #include <linux/mount.h>
43 #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         return r;
2395
2396 out_free_vcpus:
2397         kvm_free_vcpu(vcpu);
2398 out_free_run:
2399         free_page((unsigned long)vcpu->run);
2400         vcpu->run = NULL;
2401 out_unlock:
2402         mutex_unlock(&vcpu->mutex);
2403 out:
2404         return r;
2405 }
2406
2407 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
2408 {
2409         u64 efer;
2410         int i;
2411         struct kvm_cpuid_entry *e, *entry;
2412
2413         rdmsrl(MSR_EFER, efer);
2414         entry = NULL;
2415         for (i = 0; i < vcpu->cpuid_nent; ++i) {
2416                 e = &vcpu->cpuid_entries[i];
2417                 if (e->function == 0x80000001) {
2418                         entry = e;
2419                         break;
2420                 }
2421         }
2422         if (entry && (entry->edx & EFER_NX) && !(efer & EFER_NX)) {
2423                 entry->edx &= ~(1 << 20);
2424                 printk(KERN_INFO ": guest NX capability removed\n");
2425         }
2426 }
2427
2428 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
2429                                     struct kvm_cpuid *cpuid,
2430                                     struct kvm_cpuid_entry __user *entries)
2431 {
2432         int r;
2433
2434         r = -E2BIG;
2435         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2436                 goto out;
2437         r = -EFAULT;
2438         if (copy_from_user(&vcpu->cpuid_entries, entries,
2439                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
2440                 goto out;
2441         vcpu->cpuid_nent = cpuid->nent;
2442         cpuid_fix_nx_cap(vcpu);
2443         return 0;
2444
2445 out:
2446         return r;
2447 }
2448
2449 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
2450 {
2451         if (sigset) {
2452                 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
2453                 vcpu->sigset_active = 1;
2454                 vcpu->sigset = *sigset;
2455         } else
2456                 vcpu->sigset_active = 0;
2457         return 0;
2458 }
2459
2460 /*
2461  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
2462  * we have asm/x86/processor.h
2463  */
2464 struct fxsave {
2465         u16     cwd;
2466         u16     swd;
2467         u16     twd;
2468         u16     fop;
2469         u64     rip;
2470         u64     rdp;
2471         u32     mxcsr;
2472         u32     mxcsr_mask;
2473         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
2474 #ifdef CONFIG_X86_64
2475         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
2476 #else
2477         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
2478 #endif
2479 };
2480
2481 static int kvm_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2482 {
2483         struct fxsave *fxsave = (struct fxsave *)vcpu->guest_fx_image;
2484
2485         vcpu_load(vcpu);
2486
2487         memcpy(fpu->fpr, fxsave->st_space, 128);
2488         fpu->fcw = fxsave->cwd;
2489         fpu->fsw = fxsave->swd;
2490         fpu->ftwx = fxsave->twd;
2491         fpu->last_opcode = fxsave->fop;
2492         fpu->last_ip = fxsave->rip;
2493         fpu->last_dp = fxsave->rdp;
2494         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
2495
2496         vcpu_put(vcpu);
2497
2498         return 0;
2499 }
2500
2501 static int kvm_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2502 {
2503         struct fxsave *fxsave = (struct fxsave *)vcpu->guest_fx_image;
2504
2505         vcpu_load(vcpu);
2506
2507         memcpy(fxsave->st_space, fpu->fpr, 128);
2508         fxsave->cwd = fpu->fcw;
2509         fxsave->swd = fpu->fsw;
2510         fxsave->twd = fpu->ftwx;
2511         fxsave->fop = fpu->last_opcode;
2512         fxsave->rip = fpu->last_ip;
2513         fxsave->rdp = fpu->last_dp;
2514         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
2515
2516         vcpu_put(vcpu);
2517
2518         return 0;
2519 }
2520
2521 static long kvm_vcpu_ioctl(struct file *filp,
2522                            unsigned int ioctl, unsigned long arg)
2523 {
2524         struct kvm_vcpu *vcpu = filp->private_data;
2525         void __user *argp = (void __user *)arg;
2526         int r = -EINVAL;
2527
2528         switch (ioctl) {
2529         case KVM_RUN:
2530                 r = -EINVAL;
2531                 if (arg)
2532                         goto out;
2533                 r = kvm_vcpu_ioctl_run(vcpu, vcpu->run);
2534                 break;
2535         case KVM_GET_REGS: {
2536                 struct kvm_regs kvm_regs;
2537
2538                 memset(&kvm_regs, 0, sizeof kvm_regs);
2539                 r = kvm_vcpu_ioctl_get_regs(vcpu, &kvm_regs);
2540                 if (r)
2541                         goto out;
2542                 r = -EFAULT;
2543                 if (copy_to_user(argp, &kvm_regs, sizeof kvm_regs))
2544                         goto out;
2545                 r = 0;
2546                 break;
2547         }
2548         case KVM_SET_REGS: {
2549                 struct kvm_regs kvm_regs;
2550
2551                 r = -EFAULT;
2552                 if (copy_from_user(&kvm_regs, argp, sizeof kvm_regs))
2553                         goto out;
2554                 r = kvm_vcpu_ioctl_set_regs(vcpu, &kvm_regs);
2555                 if (r)
2556                         goto out;
2557                 r = 0;
2558                 break;
2559         }
2560         case KVM_GET_SREGS: {
2561                 struct kvm_sregs kvm_sregs;
2562
2563                 memset(&kvm_sregs, 0, sizeof kvm_sregs);
2564                 r = kvm_vcpu_ioctl_get_sregs(vcpu, &kvm_sregs);
2565                 if (r)
2566                         goto out;
2567                 r = -EFAULT;
2568                 if (copy_to_user(argp, &kvm_sregs, sizeof kvm_sregs))
2569                         goto out;
2570                 r = 0;
2571                 break;
2572         }
2573         case KVM_SET_SREGS: {
2574                 struct kvm_sregs kvm_sregs;
2575
2576                 r = -EFAULT;
2577                 if (copy_from_user(&kvm_sregs, argp, sizeof kvm_sregs))
2578                         goto out;
2579                 r = kvm_vcpu_ioctl_set_sregs(vcpu, &kvm_sregs);
2580                 if (r)
2581                         goto out;
2582                 r = 0;
2583                 break;
2584         }
2585         case KVM_TRANSLATE: {
2586                 struct kvm_translation tr;
2587
2588                 r = -EFAULT;
2589                 if (copy_from_user(&tr, argp, sizeof tr))
2590                         goto out;
2591                 r = kvm_vcpu_ioctl_translate(vcpu, &tr);
2592                 if (r)
2593                         goto out;
2594                 r = -EFAULT;
2595                 if (copy_to_user(argp, &tr, sizeof tr))
2596                         goto out;
2597                 r = 0;
2598                 break;
2599         }
2600         case KVM_INTERRUPT: {
2601                 struct kvm_interrupt irq;
2602
2603                 r = -EFAULT;
2604                 if (copy_from_user(&irq, argp, sizeof irq))
2605                         goto out;
2606                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
2607                 if (r)
2608                         goto out;
2609                 r = 0;
2610                 break;
2611         }
2612         case KVM_DEBUG_GUEST: {
2613                 struct kvm_debug_guest dbg;
2614
2615                 r = -EFAULT;
2616                 if (copy_from_user(&dbg, argp, sizeof dbg))
2617                         goto out;
2618                 r = kvm_vcpu_ioctl_debug_guest(vcpu, &dbg);
2619                 if (r)
2620                         goto out;
2621                 r = 0;
2622                 break;
2623         }
2624         case KVM_GET_MSRS:
2625                 r = msr_io(vcpu, argp, get_msr, 1);
2626                 break;
2627         case KVM_SET_MSRS:
2628                 r = msr_io(vcpu, argp, do_set_msr, 0);
2629                 break;
2630         case KVM_SET_CPUID: {
2631                 struct kvm_cpuid __user *cpuid_arg = argp;
2632                 struct kvm_cpuid cpuid;
2633
2634                 r = -EFAULT;
2635                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2636                         goto out;
2637                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
2638                 if (r)
2639                         goto out;
2640                 break;
2641         }
2642         case KVM_SET_SIGNAL_MASK: {
2643                 struct kvm_signal_mask __user *sigmask_arg = argp;
2644                 struct kvm_signal_mask kvm_sigmask;
2645                 sigset_t sigset, *p;
2646
2647                 p = NULL;
2648                 if (argp) {
2649                         r = -EFAULT;
2650                         if (copy_from_user(&kvm_sigmask, argp,
2651                                            sizeof kvm_sigmask))
2652                                 goto out;
2653                         r = -EINVAL;
2654                         if (kvm_sigmask.len != sizeof sigset)
2655                                 goto out;
2656                         r = -EFAULT;
2657                         if (copy_from_user(&sigset, sigmask_arg->sigset,
2658                                            sizeof sigset))
2659                                 goto out;
2660                         p = &sigset;
2661                 }
2662                 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
2663                 break;
2664         }
2665         case KVM_GET_FPU: {
2666                 struct kvm_fpu fpu;
2667
2668                 memset(&fpu, 0, sizeof fpu);
2669                 r = kvm_vcpu_ioctl_get_fpu(vcpu, &fpu);
2670                 if (r)
2671                         goto out;
2672                 r = -EFAULT;
2673                 if (copy_to_user(argp, &fpu, sizeof fpu))
2674                         goto out;
2675                 r = 0;
2676                 break;
2677         }
2678         case KVM_SET_FPU: {
2679                 struct kvm_fpu fpu;
2680
2681                 r = -EFAULT;
2682                 if (copy_from_user(&fpu, argp, sizeof fpu))
2683                         goto out;
2684                 r = kvm_vcpu_ioctl_set_fpu(vcpu, &fpu);
2685                 if (r)
2686                         goto out;
2687                 r = 0;
2688                 break;
2689         }
2690         default:
2691                 ;
2692         }
2693 out:
2694         return r;
2695 }
2696
2697 static long kvm_vm_ioctl(struct file *filp,
2698                            unsigned int ioctl, unsigned long arg)
2699 {
2700         struct kvm *kvm = filp->private_data;
2701         void __user *argp = (void __user *)arg;
2702         int r = -EINVAL;
2703
2704         switch (ioctl) {
2705         case KVM_CREATE_VCPU:
2706                 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
2707                 if (r < 0)
2708                         goto out;
2709                 break;
2710         case KVM_SET_MEMORY_REGION: {
2711                 struct kvm_memory_region kvm_mem;
2712
2713                 r = -EFAULT;
2714                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
2715                         goto out;
2716                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_mem);
2717                 if (r)
2718                         goto out;
2719                 break;
2720         }
2721         case KVM_GET_DIRTY_LOG: {
2722                 struct kvm_dirty_log log;
2723
2724                 r = -EFAULT;
2725                 if (copy_from_user(&log, argp, sizeof log))
2726                         goto out;
2727                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
2728                 if (r)
2729                         goto out;
2730                 break;
2731         }
2732         case KVM_SET_MEMORY_ALIAS: {
2733                 struct kvm_memory_alias alias;
2734
2735                 r = -EFAULT;
2736                 if (copy_from_user(&alias, argp, sizeof alias))
2737                         goto out;
2738                 r = kvm_vm_ioctl_set_memory_alias(kvm, &alias);
2739                 if (r)
2740                         goto out;
2741                 break;
2742         }
2743         default:
2744                 ;
2745         }
2746 out:
2747         return r;
2748 }
2749
2750 static struct page *kvm_vm_nopage(struct vm_area_struct *vma,
2751                                   unsigned long address,
2752                                   int *type)
2753 {
2754         struct kvm *kvm = vma->vm_file->private_data;
2755         unsigned long pgoff;
2756         struct page *page;
2757
2758         *type = VM_FAULT_MINOR;
2759         pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
2760         page = gfn_to_page(kvm, pgoff);
2761         if (!page)
2762                 return NOPAGE_SIGBUS;
2763         get_page(page);
2764         return page;
2765 }
2766
2767 static struct vm_operations_struct kvm_vm_vm_ops = {
2768         .nopage = kvm_vm_nopage,
2769 };
2770
2771 static int kvm_vm_mmap(struct file *file, struct vm_area_struct *vma)
2772 {
2773         vma->vm_ops = &kvm_vm_vm_ops;
2774         return 0;
2775 }
2776
2777 static struct file_operations kvm_vm_fops = {
2778         .release        = kvm_vm_release,
2779         .unlocked_ioctl = kvm_vm_ioctl,
2780         .compat_ioctl   = kvm_vm_ioctl,
2781         .mmap           = kvm_vm_mmap,
2782 };
2783
2784 static int kvm_dev_ioctl_create_vm(void)
2785 {
2786         int fd, r;
2787         struct inode *inode;
2788         struct file *file;
2789         struct kvm *kvm;
2790
2791         inode = kvmfs_inode(&kvm_vm_fops);
2792         if (IS_ERR(inode)) {
2793                 r = PTR_ERR(inode);
2794                 goto out1;
2795         }
2796
2797         kvm = kvm_create_vm();
2798         if (IS_ERR(kvm)) {
2799                 r = PTR_ERR(kvm);
2800                 goto out2;
2801         }
2802
2803         file = kvmfs_file(inode, kvm);
2804         if (IS_ERR(file)) {
2805                 r = PTR_ERR(file);
2806                 goto out3;
2807         }
2808         kvm->filp = file;
2809
2810         r = get_unused_fd();
2811         if (r < 0)
2812                 goto out4;
2813         fd = r;
2814         fd_install(fd, file);
2815
2816         return fd;
2817
2818 out4:
2819         fput(file);
2820 out3:
2821         kvm_destroy_vm(kvm);
2822 out2:
2823         iput(inode);
2824 out1:
2825         return r;
2826 }
2827
2828 static long kvm_dev_ioctl(struct file *filp,
2829                           unsigned int ioctl, unsigned long arg)
2830 {
2831         void __user *argp = (void __user *)arg;
2832         long r = -EINVAL;
2833
2834         switch (ioctl) {
2835         case KVM_GET_API_VERSION:
2836                 r = -EINVAL;
2837                 if (arg)
2838                         goto out;
2839                 r = KVM_API_VERSION;
2840                 break;
2841         case KVM_CREATE_VM:
2842                 r = -EINVAL;
2843                 if (arg)
2844                         goto out;
2845                 r = kvm_dev_ioctl_create_vm();
2846                 break;
2847         case KVM_GET_MSR_INDEX_LIST: {
2848                 struct kvm_msr_list __user *user_msr_list = argp;
2849                 struct kvm_msr_list msr_list;
2850                 unsigned n;
2851
2852                 r = -EFAULT;
2853                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2854                         goto out;
2855                 n = msr_list.nmsrs;
2856                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
2857                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2858                         goto out;
2859                 r = -E2BIG;
2860                 if (n < num_msrs_to_save)
2861                         goto out;
2862                 r = -EFAULT;
2863                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2864                                  num_msrs_to_save * sizeof(u32)))
2865                         goto out;
2866                 if (copy_to_user(user_msr_list->indices
2867                                  + num_msrs_to_save * sizeof(u32),
2868                                  &emulated_msrs,
2869                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
2870                         goto out;
2871                 r = 0;
2872                 break;
2873         }
2874         case KVM_CHECK_EXTENSION:
2875                 /*
2876                  * No extensions defined at present.
2877                  */
2878                 r = 0;
2879                 break;
2880         case KVM_GET_VCPU_MMAP_SIZE:
2881                 r = -EINVAL;
2882                 if (arg)
2883                         goto out;
2884                 r = 2 * PAGE_SIZE;
2885                 break;
2886         default:
2887                 ;
2888         }
2889 out:
2890         return r;
2891 }
2892
2893 static struct file_operations kvm_chardev_ops = {
2894         .open           = kvm_dev_open,
2895         .release        = kvm_dev_release,
2896         .unlocked_ioctl = kvm_dev_ioctl,
2897         .compat_ioctl   = kvm_dev_ioctl,
2898 };
2899
2900 static struct miscdevice kvm_dev = {
2901         KVM_MINOR,
2902         "kvm",
2903         &kvm_chardev_ops,
2904 };
2905
2906 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
2907                        void *v)
2908 {
2909         if (val == SYS_RESTART) {
2910                 /*
2911                  * Some (well, at least mine) BIOSes hang on reboot if
2912                  * in vmx root mode.
2913                  */
2914                 printk(KERN_INFO "kvm: exiting hardware virtualization\n");
2915                 on_each_cpu(kvm_arch_ops->hardware_disable, NULL, 0, 1);
2916         }
2917         return NOTIFY_OK;
2918 }
2919
2920 static struct notifier_block kvm_reboot_notifier = {
2921         .notifier_call = kvm_reboot,
2922         .priority = 0,
2923 };
2924
2925 /*
2926  * Make sure that a cpu that is being hot-unplugged does not have any vcpus
2927  * cached on it.
2928  */
2929 static void decache_vcpus_on_cpu(int cpu)
2930 {
2931         struct kvm *vm;
2932         struct kvm_vcpu *vcpu;
2933         int i;
2934
2935         spin_lock(&kvm_lock);
2936         list_for_each_entry(vm, &vm_list, vm_list)
2937                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
2938                         vcpu = &vm->vcpus[i];
2939                         /*
2940                          * If the vcpu is locked, then it is running on some
2941                          * other cpu and therefore it is not cached on the
2942                          * cpu in question.
2943                          *
2944                          * If it's not locked, check the last cpu it executed
2945                          * on.
2946                          */
2947                         if (mutex_trylock(&vcpu->mutex)) {
2948                                 if (vcpu->cpu == cpu) {
2949                                         kvm_arch_ops->vcpu_decache(vcpu);
2950                                         vcpu->cpu = -1;
2951                                 }
2952                                 mutex_unlock(&vcpu->mutex);
2953                         }
2954                 }
2955         spin_unlock(&kvm_lock);
2956 }
2957
2958 static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
2959                            void *v)
2960 {
2961         int cpu = (long)v;
2962
2963         switch (val) {
2964         case CPU_DOWN_PREPARE:
2965         case CPU_DOWN_PREPARE_FROZEN:
2966         case CPU_UP_CANCELED:
2967         case CPU_UP_CANCELED_FROZEN:
2968                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
2969                        cpu);
2970                 decache_vcpus_on_cpu(cpu);
2971                 smp_call_function_single(cpu, kvm_arch_ops->hardware_disable,
2972                                          NULL, 0, 1);
2973                 break;
2974         case CPU_ONLINE:
2975         case CPU_ONLINE_FROZEN:
2976                 printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
2977                        cpu);
2978                 smp_call_function_single(cpu, kvm_arch_ops->hardware_enable,
2979                                          NULL, 0, 1);
2980                 break;
2981         }
2982         return NOTIFY_OK;
2983 }
2984
2985 static struct notifier_block kvm_cpu_notifier = {
2986         .notifier_call = kvm_cpu_hotplug,
2987         .priority = 20, /* must be > scheduler priority */
2988 };
2989
2990 static u64 stat_get(void *_offset)
2991 {
2992         unsigned offset = (long)_offset;
2993         u64 total = 0;
2994         struct kvm *kvm;
2995         struct kvm_vcpu *vcpu;
2996         int i;
2997
2998         spin_lock(&kvm_lock);
2999         list_for_each_entry(kvm, &vm_list, vm_list)
3000                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
3001                         vcpu = &kvm->vcpus[i];
3002                         total += *(u32 *)((void *)vcpu + offset);
3003                 }
3004         spin_unlock(&kvm_lock);
3005         return total;
3006 }
3007
3008 static void stat_set(void *offset, u64 val)
3009 {
3010 }
3011
3012 DEFINE_SIMPLE_ATTRIBUTE(stat_fops, stat_get, stat_set, "%llu\n");
3013
3014 static __init void kvm_init_debug(void)
3015 {
3016         struct kvm_stats_debugfs_item *p;
3017
3018         debugfs_dir = debugfs_create_dir("kvm", NULL);
3019         for (p = debugfs_entries; p->name; ++p)
3020                 p->dentry = debugfs_create_file(p->name, 0444, debugfs_dir,
3021                                                 (void *)(long)p->offset,
3022                                                 &stat_fops);
3023 }
3024
3025 static void kvm_exit_debug(void)
3026 {
3027         struct kvm_stats_debugfs_item *p;
3028
3029         for (p = debugfs_entries; p->name; ++p)
3030                 debugfs_remove(p->dentry);
3031         debugfs_remove(debugfs_dir);
3032 }
3033
3034 static int kvm_suspend(struct sys_device *dev, pm_message_t state)
3035 {
3036         decache_vcpus_on_cpu(raw_smp_processor_id());
3037         on_each_cpu(kvm_arch_ops->hardware_disable, NULL, 0, 1);
3038         return 0;
3039 }
3040
3041 static int kvm_resume(struct sys_device *dev)
3042 {
3043         on_each_cpu(kvm_arch_ops->hardware_enable, NULL, 0, 1);
3044         return 0;
3045 }
3046
3047 static struct sysdev_class kvm_sysdev_class = {
3048         set_kset_name("kvm"),
3049         .suspend = kvm_suspend,
3050         .resume = kvm_resume,
3051 };
3052
3053 static struct sys_device kvm_sysdev = {
3054         .id = 0,
3055         .cls = &kvm_sysdev_class,
3056 };
3057
3058 hpa_t bad_page_address;
3059
3060 static int kvmfs_get_sb(struct file_system_type *fs_type, int flags,
3061                         const char *dev_name, void *data, struct vfsmount *mnt)
3062 {
3063         return get_sb_pseudo(fs_type, "kvm:", NULL, KVMFS_SUPER_MAGIC, mnt);
3064 }
3065
3066 static struct file_system_type kvm_fs_type = {
3067         .name           = "kvmfs",
3068         .get_sb         = kvmfs_get_sb,
3069         .kill_sb        = kill_anon_super,
3070 };
3071
3072 int kvm_init_arch(struct kvm_arch_ops *ops, struct module *module)
3073 {
3074         int r;
3075
3076         if (kvm_arch_ops) {
3077                 printk(KERN_ERR "kvm: already loaded the other module\n");
3078                 return -EEXIST;
3079         }
3080
3081         if (!ops->cpu_has_kvm_support()) {
3082                 printk(KERN_ERR "kvm: no hardware support\n");
3083                 return -EOPNOTSUPP;
3084         }
3085         if (ops->disabled_by_bios()) {
3086                 printk(KERN_ERR "kvm: disabled by bios\n");
3087                 return -EOPNOTSUPP;
3088         }
3089
3090         kvm_arch_ops = ops;
3091
3092         r = kvm_arch_ops->hardware_setup();
3093         if (r < 0)
3094                 goto out;
3095
3096         on_each_cpu(kvm_arch_ops->hardware_enable, NULL, 0, 1);
3097         r = register_cpu_notifier(&kvm_cpu_notifier);
3098         if (r)
3099                 goto out_free_1;
3100         register_reboot_notifier(&kvm_reboot_notifier);
3101
3102         r = sysdev_class_register(&kvm_sysdev_class);
3103         if (r)
3104                 goto out_free_2;
3105
3106         r = sysdev_register(&kvm_sysdev);
3107         if (r)
3108                 goto out_free_3;
3109
3110         kvm_chardev_ops.owner = module;
3111
3112         r = misc_register(&kvm_dev);
3113         if (r) {
3114                 printk (KERN_ERR "kvm: misc device register failed\n");
3115                 goto out_free;
3116         }
3117
3118         return r;
3119
3120 out_free:
3121         sysdev_unregister(&kvm_sysdev);
3122 out_free_3:
3123         sysdev_class_unregister(&kvm_sysdev_class);
3124 out_free_2:
3125         unregister_reboot_notifier(&kvm_reboot_notifier);
3126         unregister_cpu_notifier(&kvm_cpu_notifier);
3127 out_free_1:
3128         on_each_cpu(kvm_arch_ops->hardware_disable, NULL, 0, 1);
3129         kvm_arch_ops->hardware_unsetup();
3130 out:
3131         kvm_arch_ops = NULL;
3132         return r;
3133 }
3134
3135 void kvm_exit_arch(void)
3136 {
3137         misc_deregister(&kvm_dev);
3138         sysdev_unregister(&kvm_sysdev);
3139         sysdev_class_unregister(&kvm_sysdev_class);
3140         unregister_reboot_notifier(&kvm_reboot_notifier);
3141         unregister_cpu_notifier(&kvm_cpu_notifier);
3142         on_each_cpu(kvm_arch_ops->hardware_disable, NULL, 0, 1);
3143         kvm_arch_ops->hardware_unsetup();
3144         kvm_arch_ops = NULL;
3145 }
3146
3147 static __init int kvm_init(void)
3148 {
3149         static struct page *bad_page;
3150         int r;
3151
3152         r = kvm_mmu_module_init();
3153         if (r)
3154                 goto out4;
3155
3156         r = register_filesystem(&kvm_fs_type);
3157         if (r)
3158                 goto out3;
3159
3160         kvmfs_mnt = kern_mount(&kvm_fs_type);
3161         r = PTR_ERR(kvmfs_mnt);
3162         if (IS_ERR(kvmfs_mnt))
3163                 goto out2;
3164         kvm_init_debug();
3165
3166         kvm_init_msr_list();
3167
3168         if ((bad_page = alloc_page(GFP_KERNEL)) == NULL) {
3169                 r = -ENOMEM;
3170                 goto out;
3171         }
3172
3173         bad_page_address = page_to_pfn(bad_page) << PAGE_SHIFT;
3174         memset(__va(bad_page_address), 0, PAGE_SIZE);
3175
3176         return 0;
3177
3178 out:
3179         kvm_exit_debug();
3180         mntput(kvmfs_mnt);
3181 out2:
3182         unregister_filesystem(&kvm_fs_type);
3183 out3:
3184         kvm_mmu_module_exit();
3185 out4:
3186         return r;
3187 }
3188
3189 static __exit void kvm_exit(void)
3190 {
3191         kvm_exit_debug();
3192         __free_page(pfn_to_page(bad_page_address >> PAGE_SHIFT));
3193         mntput(kvmfs_mnt);
3194         unregister_filesystem(&kvm_fs_type);
3195         kvm_mmu_module_exit();
3196 }
3197
3198 module_init(kvm_init)
3199 module_exit(kvm_exit)
3200
3201 EXPORT_SYMBOL_GPL(kvm_init_arch);
3202 EXPORT_SYMBOL_GPL(kvm_exit_arch);