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