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