KVM: MMU: Fold fix_read_pf() into set_pte_common()
[safe/jmp/linux-2.6] / drivers / kvm / kvm_main.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  *
9  * Authors:
10  *   Avi Kivity   <avi@qumranet.com>
11  *   Yaniv Kamay  <yaniv@qumranet.com>
12  *
13  * This work is licensed under the terms of the GNU GPL, version 2.  See
14  * the COPYING file in the top-level directory.
15  *
16  */
17
18 #include "kvm.h"
19
20 #include <linux/kvm.h>
21 #include <linux/module.h>
22 #include <linux/errno.h>
23 #include <linux/magic.h>
24 #include <asm/processor.h>
25 #include <linux/percpu.h>
26 #include <linux/gfp.h>
27 #include <asm/msr.h>
28 #include <linux/mm.h>
29 #include <linux/miscdevice.h>
30 #include <linux/vmalloc.h>
31 #include <asm/uaccess.h>
32 #include <linux/reboot.h>
33 #include <asm/io.h>
34 #include <linux/debugfs.h>
35 #include <linux/highmem.h>
36 #include <linux/file.h>
37 #include <asm/desc.h>
38 #include <linux/sysdev.h>
39 #include <linux/cpu.h>
40 #include <linux/file.h>
41 #include <linux/fs.h>
42 #include <linux/mount.h>
43 #include <linux/sched.h>
44
45 #include "x86_emulate.h"
46 #include "segment_descriptor.h"
47
48 MODULE_AUTHOR("Qumranet");
49 MODULE_LICENSE("GPL");
50
51 static DEFINE_SPINLOCK(kvm_lock);
52 static LIST_HEAD(vm_list);
53
54 struct kvm_arch_ops *kvm_arch_ops;
55
56 #define STAT_OFFSET(x) offsetof(struct kvm_vcpu, stat.x)
57
58 static struct kvm_stats_debugfs_item {
59         const char *name;
60         int offset;
61         struct dentry *dentry;
62 } debugfs_entries[] = {
63         { "pf_fixed", STAT_OFFSET(pf_fixed) },
64         { "pf_guest", STAT_OFFSET(pf_guest) },
65         { "tlb_flush", STAT_OFFSET(tlb_flush) },
66         { "invlpg", STAT_OFFSET(invlpg) },
67         { "exits", STAT_OFFSET(exits) },
68         { "io_exits", STAT_OFFSET(io_exits) },
69         { "mmio_exits", STAT_OFFSET(mmio_exits) },
70         { "signal_exits", STAT_OFFSET(signal_exits) },
71         { "irq_window", STAT_OFFSET(irq_window_exits) },
72         { "halt_exits", STAT_OFFSET(halt_exits) },
73         { "request_irq", STAT_OFFSET(request_irq_exits) },
74         { "irq_exits", STAT_OFFSET(irq_exits) },
75         { "light_exits", STAT_OFFSET(light_exits) },
76         { "efer_reload", STAT_OFFSET(efer_reload) },
77         { NULL }
78 };
79
80 static struct dentry *debugfs_dir;
81
82 struct vfsmount *kvmfs_mnt;
83
84 #define MAX_IO_MSRS 256
85
86 #define CR0_RESEVED_BITS 0xffffffff1ffaffc0ULL
87 #define LMSW_GUEST_MASK 0x0eULL
88 #define CR4_RESEVED_BITS (~((1ULL << 11) - 1))
89 #define CR8_RESEVED_BITS (~0x0fULL)
90 #define EFER_RESERVED_BITS 0xfffffffffffff2fe
91
92 #ifdef CONFIG_X86_64
93 // LDT or TSS descriptor in the GDT. 16 bytes.
94 struct segment_descriptor_64 {
95         struct segment_descriptor s;
96         u32 base_higher;
97         u32 pad_zero;
98 };
99
100 #endif
101
102 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
103                            unsigned long arg);
104
105 static struct inode *kvmfs_inode(struct file_operations *fops)
106 {
107         int error = -ENOMEM;
108         struct inode *inode = new_inode(kvmfs_mnt->mnt_sb);
109
110         if (!inode)
111                 goto eexit_1;
112
113         inode->i_fop = fops;
114
115         /*
116          * Mark the inode dirty from the very beginning,
117          * that way it will never be moved to the dirty
118          * list because mark_inode_dirty() will think
119          * that it already _is_ on the dirty list.
120          */
121         inode->i_state = I_DIRTY;
122         inode->i_mode = S_IRUSR | S_IWUSR;
123         inode->i_uid = current->fsuid;
124         inode->i_gid = current->fsgid;
125         inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
126         return inode;
127
128 eexit_1:
129         return ERR_PTR(error);
130 }
131
132 static struct file *kvmfs_file(struct inode *inode, void *private_data)
133 {
134         struct file *file = get_empty_filp();
135
136         if (!file)
137                 return ERR_PTR(-ENFILE);
138
139         file->f_path.mnt = mntget(kvmfs_mnt);
140         file->f_path.dentry = d_alloc_anon(inode);
141         if (!file->f_path.dentry)
142                 return ERR_PTR(-ENOMEM);
143         file->f_mapping = inode->i_mapping;
144
145         file->f_pos = 0;
146         file->f_flags = O_RDWR;
147         file->f_op = inode->i_fop;
148         file->f_mode = FMODE_READ | FMODE_WRITE;
149         file->f_version = 0;
150         file->private_data = private_data;
151         return file;
152 }
153
154 unsigned long segment_base(u16 selector)
155 {
156         struct descriptor_table gdt;
157         struct segment_descriptor *d;
158         unsigned long table_base;
159         typedef unsigned long ul;
160         unsigned long v;
161
162         if (selector == 0)
163                 return 0;
164
165         asm ("sgdt %0" : "=m"(gdt));
166         table_base = gdt.base;
167
168         if (selector & 4) {           /* from ldt */
169                 u16 ldt_selector;
170
171                 asm ("sldt %0" : "=g"(ldt_selector));
172                 table_base = segment_base(ldt_selector);
173         }
174         d = (struct segment_descriptor *)(table_base + (selector & ~7));
175         v = d->base_low | ((ul)d->base_mid << 16) | ((ul)d->base_high << 24);
176 #ifdef CONFIG_X86_64
177         if (d->system == 0
178             && (d->type == 2 || d->type == 9 || d->type == 11))
179                 v |= ((ul)((struct segment_descriptor_64 *)d)->base_higher) << 32;
180 #endif
181         return v;
182 }
183 EXPORT_SYMBOL_GPL(segment_base);
184
185 static inline int valid_vcpu(int n)
186 {
187         return likely(n >= 0 && n < KVM_MAX_VCPUS);
188 }
189
190 int kvm_read_guest(struct kvm_vcpu *vcpu, gva_t addr, unsigned long size,
191                    void *dest)
192 {
193         unsigned char *host_buf = dest;
194         unsigned long req_size = size;
195
196         while (size) {
197                 hpa_t paddr;
198                 unsigned now;
199                 unsigned offset;
200                 hva_t guest_buf;
201
202                 paddr = gva_to_hpa(vcpu, addr);
203
204                 if (is_error_hpa(paddr))
205                         break;
206
207                 guest_buf = (hva_t)kmap_atomic(
208                                         pfn_to_page(paddr >> PAGE_SHIFT),
209                                         KM_USER0);
210                 offset = addr & ~PAGE_MASK;
211                 guest_buf |= offset;
212                 now = min(size, PAGE_SIZE - offset);
213                 memcpy(host_buf, (void*)guest_buf, now);
214                 host_buf += now;
215                 addr += now;
216                 size -= now;
217                 kunmap_atomic((void *)(guest_buf & PAGE_MASK), KM_USER0);
218         }
219         return req_size - size;
220 }
221 EXPORT_SYMBOL_GPL(kvm_read_guest);
222
223 int kvm_write_guest(struct kvm_vcpu *vcpu, gva_t addr, unsigned long size,
224                     void *data)
225 {
226         unsigned char *host_buf = data;
227         unsigned long req_size = size;
228
229         while (size) {
230                 hpa_t paddr;
231                 unsigned now;
232                 unsigned offset;
233                 hva_t guest_buf;
234                 gfn_t gfn;
235
236                 paddr = gva_to_hpa(vcpu, addr);
237
238                 if (is_error_hpa(paddr))
239                         break;
240
241                 gfn = vcpu->mmu.gva_to_gpa(vcpu, addr) >> PAGE_SHIFT;
242                 mark_page_dirty(vcpu->kvm, gfn);
243                 guest_buf = (hva_t)kmap_atomic(
244                                 pfn_to_page(paddr >> PAGE_SHIFT), KM_USER0);
245                 offset = addr & ~PAGE_MASK;
246                 guest_buf |= offset;
247                 now = min(size, PAGE_SIZE - offset);
248                 memcpy((void*)guest_buf, host_buf, now);
249                 host_buf += now;
250                 addr += now;
251                 size -= now;
252                 kunmap_atomic((void *)(guest_buf & PAGE_MASK), KM_USER0);
253         }
254         return req_size - size;
255 }
256 EXPORT_SYMBOL_GPL(kvm_write_guest);
257
258 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
259 {
260         if (!vcpu->fpu_active || vcpu->guest_fpu_loaded)
261                 return;
262
263         vcpu->guest_fpu_loaded = 1;
264         fx_save(vcpu->host_fx_image);
265         fx_restore(vcpu->guest_fx_image);
266 }
267 EXPORT_SYMBOL_GPL(kvm_load_guest_fpu);
268
269 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
270 {
271         if (!vcpu->guest_fpu_loaded)
272                 return;
273
274         vcpu->guest_fpu_loaded = 0;
275         fx_save(vcpu->guest_fx_image);
276         fx_restore(vcpu->host_fx_image);
277 }
278 EXPORT_SYMBOL_GPL(kvm_put_guest_fpu);
279
280 /*
281  * Switches to specified vcpu, until a matching vcpu_put()
282  */
283 static void vcpu_load(struct kvm_vcpu *vcpu)
284 {
285         mutex_lock(&vcpu->mutex);
286         kvm_arch_ops->vcpu_load(vcpu);
287 }
288
289 /*
290  * Switches to specified vcpu, until a matching vcpu_put(). Will return NULL
291  * if the slot is not populated.
292  */
293 static struct kvm_vcpu *vcpu_load_slot(struct kvm *kvm, int slot)
294 {
295         struct kvm_vcpu *vcpu = &kvm->vcpus[slot];
296
297         mutex_lock(&vcpu->mutex);
298         if (!vcpu->vmcs) {
299                 mutex_unlock(&vcpu->mutex);
300                 return NULL;
301         }
302         kvm_arch_ops->vcpu_load(vcpu);
303         return vcpu;
304 }
305
306 static void vcpu_put(struct kvm_vcpu *vcpu)
307 {
308         kvm_arch_ops->vcpu_put(vcpu);
309         mutex_unlock(&vcpu->mutex);
310 }
311
312 static struct kvm *kvm_create_vm(void)
313 {
314         struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
315         int i;
316
317         if (!kvm)
318                 return ERR_PTR(-ENOMEM);
319
320         spin_lock_init(&kvm->lock);
321         INIT_LIST_HEAD(&kvm->active_mmu_pages);
322         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
323                 struct kvm_vcpu *vcpu = &kvm->vcpus[i];
324
325                 mutex_init(&vcpu->mutex);
326                 vcpu->cpu = -1;
327                 vcpu->kvm = kvm;
328                 vcpu->mmu.root_hpa = INVALID_PAGE;
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         case MSR_IA32_EBL_CR_POWERON:
1474                 /* MTRR registers */
1475         case 0xfe:
1476         case 0x200 ... 0x2ff:
1477                 data = 0;
1478                 break;
1479         case 0xcd: /* fsb frequency */
1480                 data = 3;
1481                 break;
1482         case MSR_IA32_APICBASE:
1483                 data = vcpu->apic_base;
1484                 break;
1485         case MSR_IA32_MISC_ENABLE:
1486                 data = vcpu->ia32_misc_enable_msr;
1487                 break;
1488 #ifdef CONFIG_X86_64
1489         case MSR_EFER:
1490                 data = vcpu->shadow_efer;
1491                 break;
1492 #endif
1493         default:
1494                 printk(KERN_ERR "kvm: unhandled rdmsr: 0x%x\n", msr);
1495                 return 1;
1496         }
1497         *pdata = data;
1498         return 0;
1499 }
1500 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
1501
1502 /*
1503  * Reads an msr value (of 'msr_index') into 'pdata'.
1504  * Returns 0 on success, non-0 otherwise.
1505  * Assumes vcpu_load() was already called.
1506  */
1507 static int get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1508 {
1509         return kvm_arch_ops->get_msr(vcpu, msr_index, pdata);
1510 }
1511
1512 #ifdef CONFIG_X86_64
1513
1514 static void set_efer(struct kvm_vcpu *vcpu, u64 efer)
1515 {
1516         if (efer & EFER_RESERVED_BITS) {
1517                 printk(KERN_DEBUG "set_efer: 0x%llx #GP, reserved bits\n",
1518                        efer);
1519                 inject_gp(vcpu);
1520                 return;
1521         }
1522
1523         if (is_paging(vcpu)
1524             && (vcpu->shadow_efer & EFER_LME) != (efer & EFER_LME)) {
1525                 printk(KERN_DEBUG "set_efer: #GP, change LME while paging\n");
1526                 inject_gp(vcpu);
1527                 return;
1528         }
1529
1530         kvm_arch_ops->set_efer(vcpu, efer);
1531
1532         efer &= ~EFER_LMA;
1533         efer |= vcpu->shadow_efer & EFER_LMA;
1534
1535         vcpu->shadow_efer = efer;
1536 }
1537
1538 #endif
1539
1540 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1541 {
1542         switch (msr) {
1543 #ifdef CONFIG_X86_64
1544         case MSR_EFER:
1545                 set_efer(vcpu, data);
1546                 break;
1547 #endif
1548         case MSR_IA32_MC0_STATUS:
1549                 printk(KERN_WARNING "%s: MSR_IA32_MC0_STATUS 0x%llx, nop\n",
1550                        __FUNCTION__, data);
1551                 break;
1552         case MSR_IA32_MCG_STATUS:
1553                 printk(KERN_WARNING "%s: MSR_IA32_MCG_STATUS 0x%llx, nop\n",
1554                         __FUNCTION__, data);
1555                 break;
1556         case MSR_IA32_UCODE_REV:
1557         case MSR_IA32_UCODE_WRITE:
1558         case 0x200 ... 0x2ff: /* MTRRs */
1559                 break;
1560         case MSR_IA32_APICBASE:
1561                 vcpu->apic_base = data;
1562                 break;
1563         case MSR_IA32_MISC_ENABLE:
1564                 vcpu->ia32_misc_enable_msr = data;
1565                 break;
1566         /*
1567          * This is the 'probe whether the host is KVM' logic:
1568          */
1569         case MSR_KVM_API_MAGIC:
1570                 return vcpu_register_para(vcpu, data);
1571
1572         default:
1573                 printk(KERN_ERR "kvm: unhandled wrmsr: 0x%x\n", msr);
1574                 return 1;
1575         }
1576         return 0;
1577 }
1578 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
1579
1580 /*
1581  * Writes msr value into into the appropriate "register".
1582  * Returns 0 on success, non-0 otherwise.
1583  * Assumes vcpu_load() was already called.
1584  */
1585 static int set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
1586 {
1587         return kvm_arch_ops->set_msr(vcpu, msr_index, data);
1588 }
1589
1590 void kvm_resched(struct kvm_vcpu *vcpu)
1591 {
1592         if (!need_resched())
1593                 return;
1594         vcpu_put(vcpu);
1595         cond_resched();
1596         vcpu_load(vcpu);
1597 }
1598 EXPORT_SYMBOL_GPL(kvm_resched);
1599
1600 void load_msrs(struct vmx_msr_entry *e, int n)
1601 {
1602         int i;
1603
1604         for (i = 0; i < n; ++i)
1605                 wrmsrl(e[i].index, e[i].data);
1606 }
1607 EXPORT_SYMBOL_GPL(load_msrs);
1608
1609 void save_msrs(struct vmx_msr_entry *e, int n)
1610 {
1611         int i;
1612
1613         for (i = 0; i < n; ++i)
1614                 rdmsrl(e[i].index, e[i].data);
1615 }
1616 EXPORT_SYMBOL_GPL(save_msrs);
1617
1618 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
1619 {
1620         int i;
1621         u32 function;
1622         struct kvm_cpuid_entry *e, *best;
1623
1624         kvm_arch_ops->cache_regs(vcpu);
1625         function = vcpu->regs[VCPU_REGS_RAX];
1626         vcpu->regs[VCPU_REGS_RAX] = 0;
1627         vcpu->regs[VCPU_REGS_RBX] = 0;
1628         vcpu->regs[VCPU_REGS_RCX] = 0;
1629         vcpu->regs[VCPU_REGS_RDX] = 0;
1630         best = NULL;
1631         for (i = 0; i < vcpu->cpuid_nent; ++i) {
1632                 e = &vcpu->cpuid_entries[i];
1633                 if (e->function == function) {
1634                         best = e;
1635                         break;
1636                 }
1637                 /*
1638                  * Both basic or both extended?
1639                  */
1640                 if (((e->function ^ function) & 0x80000000) == 0)
1641                         if (!best || e->function > best->function)
1642                                 best = e;
1643         }
1644         if (best) {
1645                 vcpu->regs[VCPU_REGS_RAX] = best->eax;
1646                 vcpu->regs[VCPU_REGS_RBX] = best->ebx;
1647                 vcpu->regs[VCPU_REGS_RCX] = best->ecx;
1648                 vcpu->regs[VCPU_REGS_RDX] = best->edx;
1649         }
1650         kvm_arch_ops->decache_regs(vcpu);
1651         kvm_arch_ops->skip_emulated_instruction(vcpu);
1652 }
1653 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
1654
1655 static int pio_copy_data(struct kvm_vcpu *vcpu)
1656 {
1657         void *p = vcpu->pio_data;
1658         void *q;
1659         unsigned bytes;
1660         int nr_pages = vcpu->pio.guest_pages[1] ? 2 : 1;
1661
1662         kvm_arch_ops->vcpu_put(vcpu);
1663         q = vmap(vcpu->pio.guest_pages, nr_pages, VM_READ|VM_WRITE,
1664                  PAGE_KERNEL);
1665         if (!q) {
1666                 kvm_arch_ops->vcpu_load(vcpu);
1667                 free_pio_guest_pages(vcpu);
1668                 return -ENOMEM;
1669         }
1670         q += vcpu->pio.guest_page_offset;
1671         bytes = vcpu->pio.size * vcpu->pio.cur_count;
1672         if (vcpu->pio.in)
1673                 memcpy(q, p, bytes);
1674         else
1675                 memcpy(p, q, bytes);
1676         q -= vcpu->pio.guest_page_offset;
1677         vunmap(q);
1678         kvm_arch_ops->vcpu_load(vcpu);
1679         free_pio_guest_pages(vcpu);
1680         return 0;
1681 }
1682
1683 static int complete_pio(struct kvm_vcpu *vcpu)
1684 {
1685         struct kvm_pio_request *io = &vcpu->pio;
1686         long delta;
1687         int r;
1688
1689         kvm_arch_ops->cache_regs(vcpu);
1690
1691         if (!io->string) {
1692                 if (io->in)
1693                         memcpy(&vcpu->regs[VCPU_REGS_RAX], vcpu->pio_data,
1694                                io->size);
1695         } else {
1696                 if (io->in) {
1697                         r = pio_copy_data(vcpu);
1698                         if (r) {
1699                                 kvm_arch_ops->cache_regs(vcpu);
1700                                 return r;
1701                         }
1702                 }
1703
1704                 delta = 1;
1705                 if (io->rep) {
1706                         delta *= io->cur_count;
1707                         /*
1708                          * The size of the register should really depend on
1709                          * current address size.
1710                          */
1711                         vcpu->regs[VCPU_REGS_RCX] -= delta;
1712                 }
1713                 if (io->down)
1714                         delta = -delta;
1715                 delta *= io->size;
1716                 if (io->in)
1717                         vcpu->regs[VCPU_REGS_RDI] += delta;
1718                 else
1719                         vcpu->regs[VCPU_REGS_RSI] += delta;
1720         }
1721
1722         kvm_arch_ops->decache_regs(vcpu);
1723
1724         io->count -= io->cur_count;
1725         io->cur_count = 0;
1726
1727         if (!io->count)
1728                 kvm_arch_ops->skip_emulated_instruction(vcpu);
1729         return 0;
1730 }
1731
1732 int kvm_setup_pio(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
1733                   int size, unsigned long count, int string, int down,
1734                   gva_t address, int rep, unsigned port)
1735 {
1736         unsigned now, in_page;
1737         int i;
1738         int nr_pages = 1;
1739         struct page *page;
1740
1741         vcpu->run->exit_reason = KVM_EXIT_IO;
1742         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
1743         vcpu->run->io.size = size;
1744         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
1745         vcpu->run->io.count = count;
1746         vcpu->run->io.port = port;
1747         vcpu->pio.count = count;
1748         vcpu->pio.cur_count = count;
1749         vcpu->pio.size = size;
1750         vcpu->pio.in = in;
1751         vcpu->pio.string = string;
1752         vcpu->pio.down = down;
1753         vcpu->pio.guest_page_offset = offset_in_page(address);
1754         vcpu->pio.rep = rep;
1755
1756         if (!string) {
1757                 kvm_arch_ops->cache_regs(vcpu);
1758                 memcpy(vcpu->pio_data, &vcpu->regs[VCPU_REGS_RAX], 4);
1759                 kvm_arch_ops->decache_regs(vcpu);
1760                 return 0;
1761         }
1762
1763         if (!count) {
1764                 kvm_arch_ops->skip_emulated_instruction(vcpu);
1765                 return 1;
1766         }
1767
1768         now = min(count, PAGE_SIZE / size);
1769
1770         if (!down)
1771                 in_page = PAGE_SIZE - offset_in_page(address);
1772         else
1773                 in_page = offset_in_page(address) + size;
1774         now = min(count, (unsigned long)in_page / size);
1775         if (!now) {
1776                 /*
1777                  * String I/O straddles page boundary.  Pin two guest pages
1778                  * so that we satisfy atomicity constraints.  Do just one
1779                  * transaction to avoid complexity.
1780                  */
1781                 nr_pages = 2;
1782                 now = 1;
1783         }
1784         if (down) {
1785                 /*
1786                  * String I/O in reverse.  Yuck.  Kill the guest, fix later.
1787                  */
1788                 printk(KERN_ERR "kvm: guest string pio down\n");
1789                 inject_gp(vcpu);
1790                 return 1;
1791         }
1792         vcpu->run->io.count = now;
1793         vcpu->pio.cur_count = now;
1794
1795         for (i = 0; i < nr_pages; ++i) {
1796                 spin_lock(&vcpu->kvm->lock);
1797                 page = gva_to_page(vcpu, address + i * PAGE_SIZE);
1798                 if (page)
1799                         get_page(page);
1800                 vcpu->pio.guest_pages[i] = page;
1801                 spin_unlock(&vcpu->kvm->lock);
1802                 if (!page) {
1803                         inject_gp(vcpu);
1804                         free_pio_guest_pages(vcpu);
1805                         return 1;
1806                 }
1807         }
1808
1809         if (!vcpu->pio.in)
1810                 return pio_copy_data(vcpu);
1811         return 0;
1812 }
1813 EXPORT_SYMBOL_GPL(kvm_setup_pio);
1814
1815 static int kvm_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
1816 {
1817         int r;
1818         sigset_t sigsaved;
1819
1820         vcpu_load(vcpu);
1821
1822         if (vcpu->sigset_active)
1823                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
1824
1825         /* re-sync apic's tpr */
1826         vcpu->cr8 = kvm_run->cr8;
1827
1828         if (vcpu->pio.cur_count) {
1829                 r = complete_pio(vcpu);
1830                 if (r)
1831                         goto out;
1832         }
1833
1834         if (vcpu->mmio_needed) {
1835                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
1836                 vcpu->mmio_read_completed = 1;
1837                 vcpu->mmio_needed = 0;
1838                 r = emulate_instruction(vcpu, kvm_run,
1839                                         vcpu->mmio_fault_cr2, 0);
1840                 if (r == EMULATE_DO_MMIO) {
1841                         /*
1842                          * Read-modify-write.  Back to userspace.
1843                          */
1844                         kvm_run->exit_reason = KVM_EXIT_MMIO;
1845                         r = 0;
1846                         goto out;
1847                 }
1848         }
1849
1850         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL) {
1851                 kvm_arch_ops->cache_regs(vcpu);
1852                 vcpu->regs[VCPU_REGS_RAX] = kvm_run->hypercall.ret;
1853                 kvm_arch_ops->decache_regs(vcpu);
1854         }
1855
1856         r = kvm_arch_ops->run(vcpu, kvm_run);
1857
1858 out:
1859         if (vcpu->sigset_active)
1860                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
1861
1862         vcpu_put(vcpu);
1863         return r;
1864 }
1865
1866 static int kvm_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu,
1867                                    struct kvm_regs *regs)
1868 {
1869         vcpu_load(vcpu);
1870
1871         kvm_arch_ops->cache_regs(vcpu);
1872
1873         regs->rax = vcpu->regs[VCPU_REGS_RAX];
1874         regs->rbx = vcpu->regs[VCPU_REGS_RBX];
1875         regs->rcx = vcpu->regs[VCPU_REGS_RCX];
1876         regs->rdx = vcpu->regs[VCPU_REGS_RDX];
1877         regs->rsi = vcpu->regs[VCPU_REGS_RSI];
1878         regs->rdi = vcpu->regs[VCPU_REGS_RDI];
1879         regs->rsp = vcpu->regs[VCPU_REGS_RSP];
1880         regs->rbp = vcpu->regs[VCPU_REGS_RBP];
1881 #ifdef CONFIG_X86_64
1882         regs->r8 = vcpu->regs[VCPU_REGS_R8];
1883         regs->r9 = vcpu->regs[VCPU_REGS_R9];
1884         regs->r10 = vcpu->regs[VCPU_REGS_R10];
1885         regs->r11 = vcpu->regs[VCPU_REGS_R11];
1886         regs->r12 = vcpu->regs[VCPU_REGS_R12];
1887         regs->r13 = vcpu->regs[VCPU_REGS_R13];
1888         regs->r14 = vcpu->regs[VCPU_REGS_R14];
1889         regs->r15 = vcpu->regs[VCPU_REGS_R15];
1890 #endif
1891
1892         regs->rip = vcpu->rip;
1893         regs->rflags = kvm_arch_ops->get_rflags(vcpu);
1894
1895         /*
1896          * Don't leak debug flags in case they were set for guest debugging
1897          */
1898         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
1899                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
1900
1901         vcpu_put(vcpu);
1902
1903         return 0;
1904 }
1905
1906 static int kvm_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu,
1907                                    struct kvm_regs *regs)
1908 {
1909         vcpu_load(vcpu);
1910
1911         vcpu->regs[VCPU_REGS_RAX] = regs->rax;
1912         vcpu->regs[VCPU_REGS_RBX] = regs->rbx;
1913         vcpu->regs[VCPU_REGS_RCX] = regs->rcx;
1914         vcpu->regs[VCPU_REGS_RDX] = regs->rdx;
1915         vcpu->regs[VCPU_REGS_RSI] = regs->rsi;
1916         vcpu->regs[VCPU_REGS_RDI] = regs->rdi;
1917         vcpu->regs[VCPU_REGS_RSP] = regs->rsp;
1918         vcpu->regs[VCPU_REGS_RBP] = regs->rbp;
1919 #ifdef CONFIG_X86_64
1920         vcpu->regs[VCPU_REGS_R8] = regs->r8;
1921         vcpu->regs[VCPU_REGS_R9] = regs->r9;
1922         vcpu->regs[VCPU_REGS_R10] = regs->r10;
1923         vcpu->regs[VCPU_REGS_R11] = regs->r11;
1924         vcpu->regs[VCPU_REGS_R12] = regs->r12;
1925         vcpu->regs[VCPU_REGS_R13] = regs->r13;
1926         vcpu->regs[VCPU_REGS_R14] = regs->r14;
1927         vcpu->regs[VCPU_REGS_R15] = regs->r15;
1928 #endif
1929
1930         vcpu->rip = regs->rip;
1931         kvm_arch_ops->set_rflags(vcpu, regs->rflags);
1932
1933         kvm_arch_ops->decache_regs(vcpu);
1934
1935         vcpu_put(vcpu);
1936
1937         return 0;
1938 }
1939
1940 static void get_segment(struct kvm_vcpu *vcpu,
1941                         struct kvm_segment *var, int seg)
1942 {
1943         return kvm_arch_ops->get_segment(vcpu, var, seg);
1944 }
1945
1946 static int kvm_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
1947                                     struct kvm_sregs *sregs)
1948 {
1949         struct descriptor_table dt;
1950
1951         vcpu_load(vcpu);
1952
1953         get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
1954         get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
1955         get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
1956         get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
1957         get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
1958         get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
1959
1960         get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
1961         get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
1962
1963         kvm_arch_ops->get_idt(vcpu, &dt);
1964         sregs->idt.limit = dt.limit;
1965         sregs->idt.base = dt.base;
1966         kvm_arch_ops->get_gdt(vcpu, &dt);
1967         sregs->gdt.limit = dt.limit;
1968         sregs->gdt.base = dt.base;
1969
1970         kvm_arch_ops->decache_cr4_guest_bits(vcpu);
1971         sregs->cr0 = vcpu->cr0;
1972         sregs->cr2 = vcpu->cr2;
1973         sregs->cr3 = vcpu->cr3;
1974         sregs->cr4 = vcpu->cr4;
1975         sregs->cr8 = vcpu->cr8;
1976         sregs->efer = vcpu->shadow_efer;
1977         sregs->apic_base = vcpu->apic_base;
1978
1979         memcpy(sregs->interrupt_bitmap, vcpu->irq_pending,
1980                sizeof sregs->interrupt_bitmap);
1981
1982         vcpu_put(vcpu);
1983
1984         return 0;
1985 }
1986
1987 static void set_segment(struct kvm_vcpu *vcpu,
1988                         struct kvm_segment *var, int seg)
1989 {
1990         return kvm_arch_ops->set_segment(vcpu, var, seg);
1991 }
1992
1993 static int kvm_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
1994                                     struct kvm_sregs *sregs)
1995 {
1996         int mmu_reset_needed = 0;
1997         int i;
1998         struct descriptor_table dt;
1999
2000         vcpu_load(vcpu);
2001
2002         dt.limit = sregs->idt.limit;
2003         dt.base = sregs->idt.base;
2004         kvm_arch_ops->set_idt(vcpu, &dt);
2005         dt.limit = sregs->gdt.limit;
2006         dt.base = sregs->gdt.base;
2007         kvm_arch_ops->set_gdt(vcpu, &dt);
2008
2009         vcpu->cr2 = sregs->cr2;
2010         mmu_reset_needed |= vcpu->cr3 != sregs->cr3;
2011         vcpu->cr3 = sregs->cr3;
2012
2013         vcpu->cr8 = sregs->cr8;
2014
2015         mmu_reset_needed |= vcpu->shadow_efer != sregs->efer;
2016 #ifdef CONFIG_X86_64
2017         kvm_arch_ops->set_efer(vcpu, sregs->efer);
2018 #endif
2019         vcpu->apic_base = sregs->apic_base;
2020
2021         kvm_arch_ops->decache_cr4_guest_bits(vcpu);
2022
2023         mmu_reset_needed |= vcpu->cr0 != sregs->cr0;
2024         kvm_arch_ops->set_cr0(vcpu, sregs->cr0);
2025
2026         mmu_reset_needed |= vcpu->cr4 != sregs->cr4;
2027         kvm_arch_ops->set_cr4(vcpu, sregs->cr4);
2028         if (!is_long_mode(vcpu) && is_pae(vcpu))
2029                 load_pdptrs(vcpu, vcpu->cr3);
2030
2031         if (mmu_reset_needed)
2032                 kvm_mmu_reset_context(vcpu);
2033
2034         memcpy(vcpu->irq_pending, sregs->interrupt_bitmap,
2035                sizeof vcpu->irq_pending);
2036         vcpu->irq_summary = 0;
2037         for (i = 0; i < NR_IRQ_WORDS; ++i)
2038                 if (vcpu->irq_pending[i])
2039                         __set_bit(i, &vcpu->irq_summary);
2040
2041         set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
2042         set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
2043         set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
2044         set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
2045         set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
2046         set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
2047
2048         set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
2049         set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
2050
2051         vcpu_put(vcpu);
2052
2053         return 0;
2054 }
2055
2056 /*
2057  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
2058  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
2059  *
2060  * This list is modified at module load time to reflect the
2061  * capabilities of the host cpu.
2062  */
2063 static u32 msrs_to_save[] = {
2064         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
2065         MSR_K6_STAR,
2066 #ifdef CONFIG_X86_64
2067         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
2068 #endif
2069         MSR_IA32_TIME_STAMP_COUNTER,
2070 };
2071
2072 static unsigned num_msrs_to_save;
2073
2074 static u32 emulated_msrs[] = {
2075         MSR_IA32_MISC_ENABLE,
2076 };
2077
2078 static __init void kvm_init_msr_list(void)
2079 {
2080         u32 dummy[2];
2081         unsigned i, j;
2082
2083         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
2084                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
2085                         continue;
2086                 if (j < i)
2087                         msrs_to_save[j] = msrs_to_save[i];
2088                 j++;
2089         }
2090         num_msrs_to_save = j;
2091 }
2092
2093 /*
2094  * Adapt set_msr() to msr_io()'s calling convention
2095  */
2096 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2097 {
2098         return set_msr(vcpu, index, *data);
2099 }
2100
2101 /*
2102  * Read or write a bunch of msrs. All parameters are kernel addresses.
2103  *
2104  * @return number of msrs set successfully.
2105  */
2106 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2107                     struct kvm_msr_entry *entries,
2108                     int (*do_msr)(struct kvm_vcpu *vcpu,
2109                                   unsigned index, u64 *data))
2110 {
2111         int i;
2112
2113         vcpu_load(vcpu);
2114
2115         for (i = 0; i < msrs->nmsrs; ++i)
2116                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2117                         break;
2118
2119         vcpu_put(vcpu);
2120
2121         return i;
2122 }
2123
2124 /*
2125  * Read or write a bunch of msrs. Parameters are user addresses.
2126  *
2127  * @return number of msrs set successfully.
2128  */
2129 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2130                   int (*do_msr)(struct kvm_vcpu *vcpu,
2131                                 unsigned index, u64 *data),
2132                   int writeback)
2133 {
2134         struct kvm_msrs msrs;
2135         struct kvm_msr_entry *entries;
2136         int r, n;
2137         unsigned size;
2138
2139         r = -EFAULT;
2140         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2141                 goto out;
2142
2143         r = -E2BIG;
2144         if (msrs.nmsrs >= MAX_IO_MSRS)
2145                 goto out;
2146
2147         r = -ENOMEM;
2148         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2149         entries = vmalloc(size);
2150         if (!entries)
2151                 goto out;
2152
2153         r = -EFAULT;
2154         if (copy_from_user(entries, user_msrs->entries, size))
2155                 goto out_free;
2156
2157         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2158         if (r < 0)
2159                 goto out_free;
2160
2161         r = -EFAULT;
2162         if (writeback && copy_to_user(user_msrs->entries, entries, size))
2163                 goto out_free;
2164
2165         r = n;
2166
2167 out_free:
2168         vfree(entries);
2169 out:
2170         return r;
2171 }
2172
2173 /*
2174  * Translate a guest virtual address to a guest physical address.
2175  */
2176 static int kvm_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
2177                                     struct kvm_translation *tr)
2178 {
2179         unsigned long vaddr = tr->linear_address;
2180         gpa_t gpa;
2181
2182         vcpu_load(vcpu);
2183         spin_lock(&vcpu->kvm->lock);
2184         gpa = vcpu->mmu.gva_to_gpa(vcpu, vaddr);
2185         tr->physical_address = gpa;
2186         tr->valid = gpa != UNMAPPED_GVA;
2187         tr->writeable = 1;
2188         tr->usermode = 0;
2189         spin_unlock(&vcpu->kvm->lock);
2190         vcpu_put(vcpu);
2191
2192         return 0;
2193 }
2194
2195 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2196                                     struct kvm_interrupt *irq)
2197 {
2198         if (irq->irq < 0 || irq->irq >= 256)
2199                 return -EINVAL;
2200         vcpu_load(vcpu);
2201
2202         set_bit(irq->irq, vcpu->irq_pending);
2203         set_bit(irq->irq / BITS_PER_LONG, &vcpu->irq_summary);
2204
2205         vcpu_put(vcpu);
2206
2207         return 0;
2208 }
2209
2210 static int kvm_vcpu_ioctl_debug_guest(struct kvm_vcpu *vcpu,
2211                                       struct kvm_debug_guest *dbg)
2212 {
2213         int r;
2214
2215         vcpu_load(vcpu);
2216
2217         r = kvm_arch_ops->set_guest_debug(vcpu, dbg);
2218
2219         vcpu_put(vcpu);
2220
2221         return r;
2222 }
2223
2224 static struct page *kvm_vcpu_nopage(struct vm_area_struct *vma,
2225                                     unsigned long address,
2226                                     int *type)
2227 {
2228         struct kvm_vcpu *vcpu = vma->vm_file->private_data;
2229         unsigned long pgoff;
2230         struct page *page;
2231
2232         *type = VM_FAULT_MINOR;
2233         pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
2234         if (pgoff == 0)
2235                 page = virt_to_page(vcpu->run);
2236         else if (pgoff == KVM_PIO_PAGE_OFFSET)
2237                 page = virt_to_page(vcpu->pio_data);
2238         else
2239                 return NOPAGE_SIGBUS;
2240         get_page(page);
2241         return page;
2242 }
2243
2244 static struct vm_operations_struct kvm_vcpu_vm_ops = {
2245         .nopage = kvm_vcpu_nopage,
2246 };
2247
2248 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2249 {
2250         vma->vm_ops = &kvm_vcpu_vm_ops;
2251         return 0;
2252 }
2253
2254 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2255 {
2256         struct kvm_vcpu *vcpu = filp->private_data;
2257
2258         fput(vcpu->kvm->filp);
2259         return 0;
2260 }
2261
2262 static struct file_operations kvm_vcpu_fops = {
2263         .release        = kvm_vcpu_release,
2264         .unlocked_ioctl = kvm_vcpu_ioctl,
2265         .compat_ioctl   = kvm_vcpu_ioctl,
2266         .mmap           = kvm_vcpu_mmap,
2267 };
2268
2269 /*
2270  * Allocates an inode for the vcpu.
2271  */
2272 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2273 {
2274         int fd, r;
2275         struct inode *inode;
2276         struct file *file;
2277
2278         atomic_inc(&vcpu->kvm->filp->f_count);
2279         inode = kvmfs_inode(&kvm_vcpu_fops);
2280         if (IS_ERR(inode)) {
2281                 r = PTR_ERR(inode);
2282                 goto out1;
2283         }
2284
2285         file = kvmfs_file(inode, vcpu);
2286         if (IS_ERR(file)) {
2287                 r = PTR_ERR(file);
2288                 goto out2;
2289         }
2290
2291         r = get_unused_fd();
2292         if (r < 0)
2293                 goto out3;
2294         fd = r;
2295         fd_install(fd, file);
2296
2297         return fd;
2298
2299 out3:
2300         fput(file);
2301 out2:
2302         iput(inode);
2303 out1:
2304         fput(vcpu->kvm->filp);
2305         return r;
2306 }
2307
2308 /*
2309  * Creates some virtual cpus.  Good luck creating more than one.
2310  */
2311 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, int n)
2312 {
2313         int r;
2314         struct kvm_vcpu *vcpu;
2315         struct page *page;
2316
2317         r = -EINVAL;
2318         if (!valid_vcpu(n))
2319                 goto out;
2320
2321         vcpu = &kvm->vcpus[n];
2322
2323         mutex_lock(&vcpu->mutex);
2324
2325         if (vcpu->vmcs) {
2326                 mutex_unlock(&vcpu->mutex);
2327                 return -EEXIST;
2328         }
2329
2330         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2331         r = -ENOMEM;
2332         if (!page)
2333                 goto out_unlock;
2334         vcpu->run = page_address(page);
2335
2336         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2337         r = -ENOMEM;
2338         if (!page)
2339                 goto out_free_run;
2340         vcpu->pio_data = page_address(page);
2341
2342         vcpu->host_fx_image = (char*)ALIGN((hva_t)vcpu->fx_buf,
2343                                            FX_IMAGE_ALIGN);
2344         vcpu->guest_fx_image = vcpu->host_fx_image + FX_IMAGE_SIZE;
2345         vcpu->cr0 = 0x10;
2346
2347         r = kvm_arch_ops->vcpu_create(vcpu);
2348         if (r < 0)
2349                 goto out_free_vcpus;
2350
2351         r = kvm_mmu_create(vcpu);
2352         if (r < 0)
2353                 goto out_free_vcpus;
2354
2355         kvm_arch_ops->vcpu_load(vcpu);
2356         r = kvm_mmu_setup(vcpu);
2357         if (r >= 0)
2358                 r = kvm_arch_ops->vcpu_setup(vcpu);
2359         vcpu_put(vcpu);
2360
2361         if (r < 0)
2362                 goto out_free_vcpus;
2363
2364         r = create_vcpu_fd(vcpu);
2365         if (r < 0)
2366                 goto out_free_vcpus;
2367
2368         return r;
2369
2370 out_free_vcpus:
2371         kvm_free_vcpu(vcpu);
2372 out_free_run:
2373         free_page((unsigned long)vcpu->run);
2374         vcpu->run = NULL;
2375 out_unlock:
2376         mutex_unlock(&vcpu->mutex);
2377 out:
2378         return r;
2379 }
2380
2381 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
2382 {
2383         u64 efer;
2384         int i;
2385         struct kvm_cpuid_entry *e, *entry;
2386
2387         rdmsrl(MSR_EFER, efer);
2388         entry = NULL;
2389         for (i = 0; i < vcpu->cpuid_nent; ++i) {
2390                 e = &vcpu->cpuid_entries[i];
2391                 if (e->function == 0x80000001) {
2392                         entry = e;
2393                         break;
2394                 }
2395         }
2396         if (entry && (entry->edx & EFER_NX) && !(efer & EFER_NX)) {
2397                 entry->edx &= ~(1 << 20);
2398                 printk(KERN_INFO ": guest NX capability removed\n");
2399         }
2400 }
2401
2402 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
2403                                     struct kvm_cpuid *cpuid,
2404                                     struct kvm_cpuid_entry __user *entries)
2405 {
2406         int r;
2407
2408         r = -E2BIG;
2409         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2410                 goto out;
2411         r = -EFAULT;
2412         if (copy_from_user(&vcpu->cpuid_entries, entries,
2413                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
2414                 goto out;
2415         vcpu->cpuid_nent = cpuid->nent;
2416         cpuid_fix_nx_cap(vcpu);
2417         return 0;
2418
2419 out:
2420         return r;
2421 }
2422
2423 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
2424 {
2425         if (sigset) {
2426                 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
2427                 vcpu->sigset_active = 1;
2428                 vcpu->sigset = *sigset;
2429         } else
2430                 vcpu->sigset_active = 0;
2431         return 0;
2432 }
2433
2434 /*
2435  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
2436  * we have asm/x86/processor.h
2437  */
2438 struct fxsave {
2439         u16     cwd;
2440         u16     swd;
2441         u16     twd;
2442         u16     fop;
2443         u64     rip;
2444         u64     rdp;
2445         u32     mxcsr;
2446         u32     mxcsr_mask;
2447         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
2448 #ifdef CONFIG_X86_64
2449         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
2450 #else
2451         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
2452 #endif
2453 };
2454
2455 static int kvm_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2456 {
2457         struct fxsave *fxsave = (struct fxsave *)vcpu->guest_fx_image;
2458
2459         vcpu_load(vcpu);
2460
2461         memcpy(fpu->fpr, fxsave->st_space, 128);
2462         fpu->fcw = fxsave->cwd;
2463         fpu->fsw = fxsave->swd;
2464         fpu->ftwx = fxsave->twd;
2465         fpu->last_opcode = fxsave->fop;
2466         fpu->last_ip = fxsave->rip;
2467         fpu->last_dp = fxsave->rdp;
2468         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
2469
2470         vcpu_put(vcpu);
2471
2472         return 0;
2473 }
2474
2475 static int kvm_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2476 {
2477         struct fxsave *fxsave = (struct fxsave *)vcpu->guest_fx_image;
2478
2479         vcpu_load(vcpu);
2480
2481         memcpy(fxsave->st_space, fpu->fpr, 128);
2482         fxsave->cwd = fpu->fcw;
2483         fxsave->swd = fpu->fsw;
2484         fxsave->twd = fpu->ftwx;
2485         fxsave->fop = fpu->last_opcode;
2486         fxsave->rip = fpu->last_ip;
2487         fxsave->rdp = fpu->last_dp;
2488         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
2489
2490         vcpu_put(vcpu);
2491
2492         return 0;
2493 }
2494
2495 static long kvm_vcpu_ioctl(struct file *filp,
2496                            unsigned int ioctl, unsigned long arg)
2497 {
2498         struct kvm_vcpu *vcpu = filp->private_data;
2499         void __user *argp = (void __user *)arg;
2500         int r = -EINVAL;
2501
2502         switch (ioctl) {
2503         case KVM_RUN:
2504                 r = -EINVAL;
2505                 if (arg)
2506                         goto out;
2507                 r = kvm_vcpu_ioctl_run(vcpu, vcpu->run);
2508                 break;
2509         case KVM_GET_REGS: {
2510                 struct kvm_regs kvm_regs;
2511
2512                 memset(&kvm_regs, 0, sizeof kvm_regs);
2513                 r = kvm_vcpu_ioctl_get_regs(vcpu, &kvm_regs);
2514                 if (r)
2515                         goto out;
2516                 r = -EFAULT;
2517                 if (copy_to_user(argp, &kvm_regs, sizeof kvm_regs))
2518                         goto out;
2519                 r = 0;
2520                 break;
2521         }
2522         case KVM_SET_REGS: {
2523                 struct kvm_regs kvm_regs;
2524
2525                 r = -EFAULT;
2526                 if (copy_from_user(&kvm_regs, argp, sizeof kvm_regs))
2527                         goto out;
2528                 r = kvm_vcpu_ioctl_set_regs(vcpu, &kvm_regs);
2529                 if (r)
2530                         goto out;
2531                 r = 0;
2532                 break;
2533         }
2534         case KVM_GET_SREGS: {
2535                 struct kvm_sregs kvm_sregs;
2536
2537                 memset(&kvm_sregs, 0, sizeof kvm_sregs);
2538                 r = kvm_vcpu_ioctl_get_sregs(vcpu, &kvm_sregs);
2539                 if (r)
2540                         goto out;
2541                 r = -EFAULT;
2542                 if (copy_to_user(argp, &kvm_sregs, sizeof kvm_sregs))
2543                         goto out;
2544                 r = 0;
2545                 break;
2546         }
2547         case KVM_SET_SREGS: {
2548                 struct kvm_sregs kvm_sregs;
2549
2550                 r = -EFAULT;
2551                 if (copy_from_user(&kvm_sregs, argp, sizeof kvm_sregs))
2552                         goto out;
2553                 r = kvm_vcpu_ioctl_set_sregs(vcpu, &kvm_sregs);
2554                 if (r)
2555                         goto out;
2556                 r = 0;
2557                 break;
2558         }
2559         case KVM_TRANSLATE: {
2560                 struct kvm_translation tr;
2561
2562                 r = -EFAULT;
2563                 if (copy_from_user(&tr, argp, sizeof tr))
2564                         goto out;
2565                 r = kvm_vcpu_ioctl_translate(vcpu, &tr);
2566                 if (r)
2567                         goto out;
2568                 r = -EFAULT;
2569                 if (copy_to_user(argp, &tr, sizeof tr))
2570                         goto out;
2571                 r = 0;
2572                 break;
2573         }
2574         case KVM_INTERRUPT: {
2575                 struct kvm_interrupt irq;
2576
2577                 r = -EFAULT;
2578                 if (copy_from_user(&irq, argp, sizeof irq))
2579                         goto out;
2580                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
2581                 if (r)
2582                         goto out;
2583                 r = 0;
2584                 break;
2585         }
2586         case KVM_DEBUG_GUEST: {
2587                 struct kvm_debug_guest dbg;
2588
2589                 r = -EFAULT;
2590                 if (copy_from_user(&dbg, argp, sizeof dbg))
2591                         goto out;
2592                 r = kvm_vcpu_ioctl_debug_guest(vcpu, &dbg);
2593                 if (r)
2594                         goto out;
2595                 r = 0;
2596                 break;
2597         }
2598         case KVM_GET_MSRS:
2599                 r = msr_io(vcpu, argp, get_msr, 1);
2600                 break;
2601         case KVM_SET_MSRS:
2602                 r = msr_io(vcpu, argp, do_set_msr, 0);
2603                 break;
2604         case KVM_SET_CPUID: {
2605                 struct kvm_cpuid __user *cpuid_arg = argp;
2606                 struct kvm_cpuid cpuid;
2607
2608                 r = -EFAULT;
2609                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2610                         goto out;
2611                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
2612                 if (r)
2613                         goto out;
2614                 break;
2615         }
2616         case KVM_SET_SIGNAL_MASK: {
2617                 struct kvm_signal_mask __user *sigmask_arg = argp;
2618                 struct kvm_signal_mask kvm_sigmask;
2619                 sigset_t sigset, *p;
2620
2621                 p = NULL;
2622                 if (argp) {
2623                         r = -EFAULT;
2624                         if (copy_from_user(&kvm_sigmask, argp,
2625                                            sizeof kvm_sigmask))
2626                                 goto out;
2627                         r = -EINVAL;
2628                         if (kvm_sigmask.len != sizeof sigset)
2629                                 goto out;
2630                         r = -EFAULT;
2631                         if (copy_from_user(&sigset, sigmask_arg->sigset,
2632                                            sizeof sigset))
2633                                 goto out;
2634                         p = &sigset;
2635                 }
2636                 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
2637                 break;
2638         }
2639         case KVM_GET_FPU: {
2640                 struct kvm_fpu fpu;
2641
2642                 memset(&fpu, 0, sizeof fpu);
2643                 r = kvm_vcpu_ioctl_get_fpu(vcpu, &fpu);
2644                 if (r)
2645                         goto out;
2646                 r = -EFAULT;
2647                 if (copy_to_user(argp, &fpu, sizeof fpu))
2648                         goto out;
2649                 r = 0;
2650                 break;
2651         }
2652         case KVM_SET_FPU: {
2653                 struct kvm_fpu fpu;
2654
2655                 r = -EFAULT;
2656                 if (copy_from_user(&fpu, argp, sizeof fpu))
2657                         goto out;
2658                 r = kvm_vcpu_ioctl_set_fpu(vcpu, &fpu);
2659                 if (r)
2660                         goto out;
2661                 r = 0;
2662                 break;
2663         }
2664         default:
2665                 ;
2666         }
2667 out:
2668         return r;
2669 }
2670
2671 static long kvm_vm_ioctl(struct file *filp,
2672                            unsigned int ioctl, unsigned long arg)
2673 {
2674         struct kvm *kvm = filp->private_data;
2675         void __user *argp = (void __user *)arg;
2676         int r = -EINVAL;
2677
2678         switch (ioctl) {
2679         case KVM_CREATE_VCPU:
2680                 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
2681                 if (r < 0)
2682                         goto out;
2683                 break;
2684         case KVM_SET_MEMORY_REGION: {
2685                 struct kvm_memory_region kvm_mem;
2686
2687                 r = -EFAULT;
2688                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
2689                         goto out;
2690                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_mem);
2691                 if (r)
2692                         goto out;
2693                 break;
2694         }
2695         case KVM_GET_DIRTY_LOG: {
2696                 struct kvm_dirty_log log;
2697
2698                 r = -EFAULT;
2699                 if (copy_from_user(&log, argp, sizeof log))
2700                         goto out;
2701                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
2702                 if (r)
2703                         goto out;
2704                 break;
2705         }
2706         case KVM_SET_MEMORY_ALIAS: {
2707                 struct kvm_memory_alias alias;
2708
2709                 r = -EFAULT;
2710                 if (copy_from_user(&alias, argp, sizeof alias))
2711                         goto out;
2712                 r = kvm_vm_ioctl_set_memory_alias(kvm, &alias);
2713                 if (r)
2714                         goto out;
2715                 break;
2716         }
2717         default:
2718                 ;
2719         }
2720 out:
2721         return r;
2722 }
2723
2724 static struct page *kvm_vm_nopage(struct vm_area_struct *vma,
2725                                   unsigned long address,
2726                                   int *type)
2727 {
2728         struct kvm *kvm = vma->vm_file->private_data;
2729         unsigned long pgoff;
2730         struct page *page;
2731
2732         *type = VM_FAULT_MINOR;
2733         pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
2734         page = gfn_to_page(kvm, pgoff);
2735         if (!page)
2736                 return NOPAGE_SIGBUS;
2737         get_page(page);
2738         return page;
2739 }
2740
2741 static struct vm_operations_struct kvm_vm_vm_ops = {
2742         .nopage = kvm_vm_nopage,
2743 };
2744
2745 static int kvm_vm_mmap(struct file *file, struct vm_area_struct *vma)
2746 {
2747         vma->vm_ops = &kvm_vm_vm_ops;
2748         return 0;
2749 }
2750
2751 static struct file_operations kvm_vm_fops = {
2752         .release        = kvm_vm_release,
2753         .unlocked_ioctl = kvm_vm_ioctl,
2754         .compat_ioctl   = kvm_vm_ioctl,
2755         .mmap           = kvm_vm_mmap,
2756 };
2757
2758 static int kvm_dev_ioctl_create_vm(void)
2759 {
2760         int fd, r;
2761         struct inode *inode;
2762         struct file *file;
2763         struct kvm *kvm;
2764
2765         inode = kvmfs_inode(&kvm_vm_fops);
2766         if (IS_ERR(inode)) {
2767                 r = PTR_ERR(inode);
2768                 goto out1;
2769         }
2770
2771         kvm = kvm_create_vm();
2772         if (IS_ERR(kvm)) {
2773                 r = PTR_ERR(kvm);
2774                 goto out2;
2775         }
2776
2777         file = kvmfs_file(inode, kvm);
2778         if (IS_ERR(file)) {
2779                 r = PTR_ERR(file);
2780                 goto out3;
2781         }
2782         kvm->filp = file;
2783
2784         r = get_unused_fd();
2785         if (r < 0)
2786                 goto out4;
2787         fd = r;
2788         fd_install(fd, file);
2789
2790         return fd;
2791
2792 out4:
2793         fput(file);
2794 out3:
2795         kvm_destroy_vm(kvm);
2796 out2:
2797         iput(inode);
2798 out1:
2799         return r;
2800 }
2801
2802 static long kvm_dev_ioctl(struct file *filp,
2803                           unsigned int ioctl, unsigned long arg)
2804 {
2805         void __user *argp = (void __user *)arg;
2806         long r = -EINVAL;
2807
2808         switch (ioctl) {
2809         case KVM_GET_API_VERSION:
2810                 r = -EINVAL;
2811                 if (arg)
2812                         goto out;
2813                 r = KVM_API_VERSION;
2814                 break;
2815         case KVM_CREATE_VM:
2816                 r = -EINVAL;
2817                 if (arg)
2818                         goto out;
2819                 r = kvm_dev_ioctl_create_vm();
2820                 break;
2821         case KVM_GET_MSR_INDEX_LIST: {
2822                 struct kvm_msr_list __user *user_msr_list = argp;
2823                 struct kvm_msr_list msr_list;
2824                 unsigned n;
2825
2826                 r = -EFAULT;
2827                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2828                         goto out;
2829                 n = msr_list.nmsrs;
2830                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
2831                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2832                         goto out;
2833                 r = -E2BIG;
2834                 if (n < num_msrs_to_save)
2835                         goto out;
2836                 r = -EFAULT;
2837                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2838                                  num_msrs_to_save * sizeof(u32)))
2839                         goto out;
2840                 if (copy_to_user(user_msr_list->indices
2841                                  + num_msrs_to_save * sizeof(u32),
2842                                  &emulated_msrs,
2843                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
2844                         goto out;
2845                 r = 0;
2846                 break;
2847         }
2848         case KVM_CHECK_EXTENSION:
2849                 /*
2850                  * No extensions defined at present.
2851                  */
2852                 r = 0;
2853                 break;
2854         case KVM_GET_VCPU_MMAP_SIZE:
2855                 r = -EINVAL;
2856                 if (arg)
2857                         goto out;
2858                 r = 2 * PAGE_SIZE;
2859                 break;
2860         default:
2861                 ;
2862         }
2863 out:
2864         return r;
2865 }
2866
2867 static struct file_operations kvm_chardev_ops = {
2868         .open           = kvm_dev_open,
2869         .release        = kvm_dev_release,
2870         .unlocked_ioctl = kvm_dev_ioctl,
2871         .compat_ioctl   = kvm_dev_ioctl,
2872 };
2873
2874 static struct miscdevice kvm_dev = {
2875         KVM_MINOR,
2876         "kvm",
2877         &kvm_chardev_ops,
2878 };
2879
2880 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
2881                        void *v)
2882 {
2883         if (val == SYS_RESTART) {
2884                 /*
2885                  * Some (well, at least mine) BIOSes hang on reboot if
2886                  * in vmx root mode.
2887                  */
2888                 printk(KERN_INFO "kvm: exiting hardware virtualization\n");
2889                 on_each_cpu(kvm_arch_ops->hardware_disable, NULL, 0, 1);
2890         }
2891         return NOTIFY_OK;
2892 }
2893
2894 static struct notifier_block kvm_reboot_notifier = {
2895         .notifier_call = kvm_reboot,
2896         .priority = 0,
2897 };
2898
2899 /*
2900  * Make sure that a cpu that is being hot-unplugged does not have any vcpus
2901  * cached on it.
2902  */
2903 static void decache_vcpus_on_cpu(int cpu)
2904 {
2905         struct kvm *vm;
2906         struct kvm_vcpu *vcpu;
2907         int i;
2908
2909         spin_lock(&kvm_lock);
2910         list_for_each_entry(vm, &vm_list, vm_list)
2911                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
2912                         vcpu = &vm->vcpus[i];
2913                         /*
2914                          * If the vcpu is locked, then it is running on some
2915                          * other cpu and therefore it is not cached on the
2916                          * cpu in question.
2917                          *
2918                          * If it's not locked, check the last cpu it executed
2919                          * on.
2920                          */
2921                         if (mutex_trylock(&vcpu->mutex)) {
2922                                 if (vcpu->cpu == cpu) {
2923                                         kvm_arch_ops->vcpu_decache(vcpu);
2924                                         vcpu->cpu = -1;
2925                                 }
2926                                 mutex_unlock(&vcpu->mutex);
2927                         }
2928                 }
2929         spin_unlock(&kvm_lock);
2930 }
2931
2932 static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
2933                            void *v)
2934 {
2935         int cpu = (long)v;
2936
2937         switch (val) {
2938         case CPU_DOWN_PREPARE:
2939         case CPU_DOWN_PREPARE_FROZEN:
2940         case CPU_UP_CANCELED:
2941         case CPU_UP_CANCELED_FROZEN:
2942                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
2943                        cpu);
2944                 decache_vcpus_on_cpu(cpu);
2945                 smp_call_function_single(cpu, kvm_arch_ops->hardware_disable,
2946                                          NULL, 0, 1);
2947                 break;
2948         case CPU_ONLINE:
2949         case CPU_ONLINE_FROZEN:
2950                 printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
2951                        cpu);
2952                 smp_call_function_single(cpu, kvm_arch_ops->hardware_enable,
2953                                          NULL, 0, 1);
2954                 break;
2955         }
2956         return NOTIFY_OK;
2957 }
2958
2959 static struct notifier_block kvm_cpu_notifier = {
2960         .notifier_call = kvm_cpu_hotplug,
2961         .priority = 20, /* must be > scheduler priority */
2962 };
2963
2964 static u64 stat_get(void *_offset)
2965 {
2966         unsigned offset = (long)_offset;
2967         u64 total = 0;
2968         struct kvm *kvm;
2969         struct kvm_vcpu *vcpu;
2970         int i;
2971
2972         spin_lock(&kvm_lock);
2973         list_for_each_entry(kvm, &vm_list, vm_list)
2974                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
2975                         vcpu = &kvm->vcpus[i];
2976                         total += *(u32 *)((void *)vcpu + offset);
2977                 }
2978         spin_unlock(&kvm_lock);
2979         return total;
2980 }
2981
2982 static void stat_set(void *offset, u64 val)
2983 {
2984 }
2985
2986 DEFINE_SIMPLE_ATTRIBUTE(stat_fops, stat_get, stat_set, "%llu\n");
2987
2988 static __init void kvm_init_debug(void)
2989 {
2990         struct kvm_stats_debugfs_item *p;
2991
2992         debugfs_dir = debugfs_create_dir("kvm", NULL);
2993         for (p = debugfs_entries; p->name; ++p)
2994                 p->dentry = debugfs_create_file(p->name, 0444, debugfs_dir,
2995                                                 (void *)(long)p->offset,
2996                                                 &stat_fops);
2997 }
2998
2999 static void kvm_exit_debug(void)
3000 {
3001         struct kvm_stats_debugfs_item *p;
3002
3003         for (p = debugfs_entries; p->name; ++p)
3004                 debugfs_remove(p->dentry);
3005         debugfs_remove(debugfs_dir);
3006 }
3007
3008 static int kvm_suspend(struct sys_device *dev, pm_message_t state)
3009 {
3010         decache_vcpus_on_cpu(raw_smp_processor_id());
3011         on_each_cpu(kvm_arch_ops->hardware_disable, NULL, 0, 1);
3012         return 0;
3013 }
3014
3015 static int kvm_resume(struct sys_device *dev)
3016 {
3017         on_each_cpu(kvm_arch_ops->hardware_enable, NULL, 0, 1);
3018         return 0;
3019 }
3020
3021 static struct sysdev_class kvm_sysdev_class = {
3022         set_kset_name("kvm"),
3023         .suspend = kvm_suspend,
3024         .resume = kvm_resume,
3025 };
3026
3027 static struct sys_device kvm_sysdev = {
3028         .id = 0,
3029         .cls = &kvm_sysdev_class,
3030 };
3031
3032 hpa_t bad_page_address;
3033
3034 static int kvmfs_get_sb(struct file_system_type *fs_type, int flags,
3035                         const char *dev_name, void *data, struct vfsmount *mnt)
3036 {
3037         return get_sb_pseudo(fs_type, "kvm:", NULL, KVMFS_SUPER_MAGIC, mnt);
3038 }
3039
3040 static struct file_system_type kvm_fs_type = {
3041         .name           = "kvmfs",
3042         .get_sb         = kvmfs_get_sb,
3043         .kill_sb        = kill_anon_super,
3044 };
3045
3046 int kvm_init_arch(struct kvm_arch_ops *ops, struct module *module)
3047 {
3048         int r;
3049
3050         if (kvm_arch_ops) {
3051                 printk(KERN_ERR "kvm: already loaded the other module\n");
3052                 return -EEXIST;
3053         }
3054
3055         if (!ops->cpu_has_kvm_support()) {
3056                 printk(KERN_ERR "kvm: no hardware support\n");
3057                 return -EOPNOTSUPP;
3058         }
3059         if (ops->disabled_by_bios()) {
3060                 printk(KERN_ERR "kvm: disabled by bios\n");
3061                 return -EOPNOTSUPP;
3062         }
3063
3064         kvm_arch_ops = ops;
3065
3066         r = kvm_arch_ops->hardware_setup();
3067         if (r < 0)
3068                 goto out;
3069
3070         on_each_cpu(kvm_arch_ops->hardware_enable, NULL, 0, 1);
3071         r = register_cpu_notifier(&kvm_cpu_notifier);
3072         if (r)
3073                 goto out_free_1;
3074         register_reboot_notifier(&kvm_reboot_notifier);
3075
3076         r = sysdev_class_register(&kvm_sysdev_class);
3077         if (r)
3078                 goto out_free_2;
3079
3080         r = sysdev_register(&kvm_sysdev);
3081         if (r)
3082                 goto out_free_3;
3083
3084         kvm_chardev_ops.owner = module;
3085
3086         r = misc_register(&kvm_dev);
3087         if (r) {
3088                 printk (KERN_ERR "kvm: misc device register failed\n");
3089                 goto out_free;
3090         }
3091
3092         return r;
3093
3094 out_free:
3095         sysdev_unregister(&kvm_sysdev);
3096 out_free_3:
3097         sysdev_class_unregister(&kvm_sysdev_class);
3098 out_free_2:
3099         unregister_reboot_notifier(&kvm_reboot_notifier);
3100         unregister_cpu_notifier(&kvm_cpu_notifier);
3101 out_free_1:
3102         on_each_cpu(kvm_arch_ops->hardware_disable, NULL, 0, 1);
3103         kvm_arch_ops->hardware_unsetup();
3104 out:
3105         kvm_arch_ops = NULL;
3106         return r;
3107 }
3108
3109 void kvm_exit_arch(void)
3110 {
3111         misc_deregister(&kvm_dev);
3112         sysdev_unregister(&kvm_sysdev);
3113         sysdev_class_unregister(&kvm_sysdev_class);
3114         unregister_reboot_notifier(&kvm_reboot_notifier);
3115         unregister_cpu_notifier(&kvm_cpu_notifier);
3116         on_each_cpu(kvm_arch_ops->hardware_disable, NULL, 0, 1);
3117         kvm_arch_ops->hardware_unsetup();
3118         kvm_arch_ops = NULL;
3119 }
3120
3121 static __init int kvm_init(void)
3122 {
3123         static struct page *bad_page;
3124         int r;
3125
3126         r = kvm_mmu_module_init();
3127         if (r)
3128                 goto out4;
3129
3130         r = register_filesystem(&kvm_fs_type);
3131         if (r)
3132                 goto out3;
3133
3134         kvmfs_mnt = kern_mount(&kvm_fs_type);
3135         r = PTR_ERR(kvmfs_mnt);
3136         if (IS_ERR(kvmfs_mnt))
3137                 goto out2;
3138         kvm_init_debug();
3139
3140         kvm_init_msr_list();
3141
3142         if ((bad_page = alloc_page(GFP_KERNEL)) == NULL) {
3143                 r = -ENOMEM;
3144                 goto out;
3145         }
3146
3147         bad_page_address = page_to_pfn(bad_page) << PAGE_SHIFT;
3148         memset(__va(bad_page_address), 0, PAGE_SIZE);
3149
3150         return 0;
3151
3152 out:
3153         kvm_exit_debug();
3154         mntput(kvmfs_mnt);
3155 out2:
3156         unregister_filesystem(&kvm_fs_type);
3157 out3:
3158         kvm_mmu_module_exit();
3159 out4:
3160         return r;
3161 }
3162
3163 static __exit void kvm_exit(void)
3164 {
3165         kvm_exit_debug();
3166         __free_page(pfn_to_page(bad_page_address >> PAGE_SHIFT));
3167         mntput(kvmfs_mnt);
3168         unregister_filesystem(&kvm_fs_type);
3169         kvm_mmu_module_exit();
3170 }
3171
3172 module_init(kvm_init)
3173 module_exit(kvm_exit)
3174
3175 EXPORT_SYMBOL_GPL(kvm_init_arch);
3176 EXPORT_SYMBOL_GPL(kvm_exit_arch);