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