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