]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - drivers/kvm/kvm_main.c
KVM: Remove unneeded kvm_dev_open and kvm_dev_release functions.
[linux-2.6-omap-h63xx.git] / drivers / kvm / kvm_main.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  *
9  * Authors:
10  *   Avi Kivity   <avi@qumranet.com>
11  *   Yaniv Kamay  <yaniv@qumranet.com>
12  *
13  * This work is licensed under the terms of the GNU GPL, version 2.  See
14  * the COPYING file in the top-level directory.
15  *
16  */
17
18 #include "kvm.h"
19 #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         printk(KERN_ERR "emulator_write_std: addr %lx n %d\n",
966                addr, bytes);
967         return X86EMUL_UNHANDLEABLE;
968 }
969
970 static struct kvm_io_device *vcpu_find_mmio_dev(struct kvm_vcpu *vcpu,
971                                                 gpa_t addr)
972 {
973         /*
974          * Note that its important to have this wrapper function because
975          * in the very near future we will be checking for MMIOs against
976          * the LAPIC as well as the general MMIO bus
977          */
978         return kvm_io_bus_find_dev(&vcpu->kvm->mmio_bus, addr);
979 }
980
981 static struct kvm_io_device *vcpu_find_pio_dev(struct kvm_vcpu *vcpu,
982                                                gpa_t addr)
983 {
984         return kvm_io_bus_find_dev(&vcpu->kvm->pio_bus, addr);
985 }
986
987 static int emulator_read_emulated(unsigned long addr,
988                                   void *val,
989                                   unsigned int bytes,
990                                   struct kvm_vcpu *vcpu)
991 {
992         struct kvm_io_device *mmio_dev;
993         gpa_t                 gpa;
994
995         if (vcpu->mmio_read_completed) {
996                 memcpy(val, vcpu->mmio_data, bytes);
997                 vcpu->mmio_read_completed = 0;
998                 return X86EMUL_CONTINUE;
999         } else if (emulator_read_std(addr, val, bytes, vcpu)
1000                    == X86EMUL_CONTINUE)
1001                 return X86EMUL_CONTINUE;
1002
1003         gpa = vcpu->mmu.gva_to_gpa(vcpu, addr);
1004         if (gpa == UNMAPPED_GVA)
1005                 return X86EMUL_PROPAGATE_FAULT;
1006
1007         /*
1008          * Is this MMIO handled locally?
1009          */
1010         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1011         if (mmio_dev) {
1012                 kvm_iodevice_read(mmio_dev, gpa, bytes, val);
1013                 return X86EMUL_CONTINUE;
1014         }
1015
1016         vcpu->mmio_needed = 1;
1017         vcpu->mmio_phys_addr = gpa;
1018         vcpu->mmio_size = bytes;
1019         vcpu->mmio_is_write = 0;
1020
1021         return X86EMUL_UNHANDLEABLE;
1022 }
1023
1024 static int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
1025                                const void *val, int bytes)
1026 {
1027         struct page *page;
1028         void *virt;
1029
1030         if (((gpa + bytes - 1) >> PAGE_SHIFT) != (gpa >> PAGE_SHIFT))
1031                 return 0;
1032         page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1033         if (!page)
1034                 return 0;
1035         mark_page_dirty(vcpu->kvm, gpa >> PAGE_SHIFT);
1036         virt = kmap_atomic(page, KM_USER0);
1037         kvm_mmu_pte_write(vcpu, gpa, val, bytes);
1038         memcpy(virt + offset_in_page(gpa), val, bytes);
1039         kunmap_atomic(virt, KM_USER0);
1040         return 1;
1041 }
1042
1043 static int emulator_write_emulated_onepage(unsigned long addr,
1044                                            const void *val,
1045                                            unsigned int bytes,
1046                                            struct kvm_vcpu *vcpu)
1047 {
1048         struct kvm_io_device *mmio_dev;
1049         gpa_t                 gpa = vcpu->mmu.gva_to_gpa(vcpu, addr);
1050
1051         if (gpa == UNMAPPED_GVA) {
1052                 kvm_arch_ops->inject_page_fault(vcpu, addr, 2);
1053                 return X86EMUL_PROPAGATE_FAULT;
1054         }
1055
1056         if (emulator_write_phys(vcpu, gpa, val, bytes))
1057                 return X86EMUL_CONTINUE;
1058
1059         /*
1060          * Is this MMIO handled locally?
1061          */
1062         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1063         if (mmio_dev) {
1064                 kvm_iodevice_write(mmio_dev, gpa, bytes, val);
1065                 return X86EMUL_CONTINUE;
1066         }
1067
1068         vcpu->mmio_needed = 1;
1069         vcpu->mmio_phys_addr = gpa;
1070         vcpu->mmio_size = bytes;
1071         vcpu->mmio_is_write = 1;
1072         memcpy(vcpu->mmio_data, val, bytes);
1073
1074         return X86EMUL_CONTINUE;
1075 }
1076
1077 int emulator_write_emulated(unsigned long addr,
1078                                    const void *val,
1079                                    unsigned int bytes,
1080                                    struct kvm_vcpu *vcpu)
1081 {
1082         /* Crossing a page boundary? */
1083         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
1084                 int rc, now;
1085
1086                 now = -addr & ~PAGE_MASK;
1087                 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
1088                 if (rc != X86EMUL_CONTINUE)
1089                         return rc;
1090                 addr += now;
1091                 val += now;
1092                 bytes -= now;
1093         }
1094         return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
1095 }
1096 EXPORT_SYMBOL_GPL(emulator_write_emulated);
1097
1098 static int emulator_cmpxchg_emulated(unsigned long addr,
1099                                      const void *old,
1100                                      const void *new,
1101                                      unsigned int bytes,
1102                                      struct kvm_vcpu *vcpu)
1103 {
1104         static int reported;
1105
1106         if (!reported) {
1107                 reported = 1;
1108                 printk(KERN_WARNING "kvm: emulating exchange as write\n");
1109         }
1110         return emulator_write_emulated(addr, new, bytes, vcpu);
1111 }
1112
1113 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
1114 {
1115         return kvm_arch_ops->get_segment_base(vcpu, seg);
1116 }
1117
1118 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
1119 {
1120         return X86EMUL_CONTINUE;
1121 }
1122
1123 int emulate_clts(struct kvm_vcpu *vcpu)
1124 {
1125         unsigned long cr0;
1126
1127         cr0 = vcpu->cr0 & ~X86_CR0_TS;
1128         kvm_arch_ops->set_cr0(vcpu, cr0);
1129         return X86EMUL_CONTINUE;
1130 }
1131
1132 int emulator_get_dr(struct x86_emulate_ctxt* ctxt, int dr, unsigned long *dest)
1133 {
1134         struct kvm_vcpu *vcpu = ctxt->vcpu;
1135
1136         switch (dr) {
1137         case 0 ... 3:
1138                 *dest = kvm_arch_ops->get_dr(vcpu, dr);
1139                 return X86EMUL_CONTINUE;
1140         default:
1141                 printk(KERN_DEBUG "%s: unexpected dr %u\n",
1142                        __FUNCTION__, dr);
1143                 return X86EMUL_UNHANDLEABLE;
1144         }
1145 }
1146
1147 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
1148 {
1149         unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
1150         int exception;
1151
1152         kvm_arch_ops->set_dr(ctxt->vcpu, dr, value & mask, &exception);
1153         if (exception) {
1154                 /* FIXME: better handling */
1155                 return X86EMUL_UNHANDLEABLE;
1156         }
1157         return X86EMUL_CONTINUE;
1158 }
1159
1160 static void report_emulation_failure(struct x86_emulate_ctxt *ctxt)
1161 {
1162         static int reported;
1163         u8 opcodes[4];
1164         unsigned long rip = ctxt->vcpu->rip;
1165         unsigned long rip_linear;
1166
1167         rip_linear = rip + get_segment_base(ctxt->vcpu, VCPU_SREG_CS);
1168
1169         if (reported)
1170                 return;
1171
1172         emulator_read_std(rip_linear, (void *)opcodes, 4, ctxt->vcpu);
1173
1174         printk(KERN_ERR "emulation failed but !mmio_needed?"
1175                " rip %lx %02x %02x %02x %02x\n",
1176                rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
1177         reported = 1;
1178 }
1179
1180 struct x86_emulate_ops emulate_ops = {
1181         .read_std            = emulator_read_std,
1182         .write_std           = emulator_write_std,
1183         .read_emulated       = emulator_read_emulated,
1184         .write_emulated      = emulator_write_emulated,
1185         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
1186 };
1187
1188 int emulate_instruction(struct kvm_vcpu *vcpu,
1189                         struct kvm_run *run,
1190                         unsigned long cr2,
1191                         u16 error_code)
1192 {
1193         struct x86_emulate_ctxt emulate_ctxt;
1194         int r;
1195         int cs_db, cs_l;
1196
1197         vcpu->mmio_fault_cr2 = cr2;
1198         kvm_arch_ops->cache_regs(vcpu);
1199
1200         kvm_arch_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
1201
1202         emulate_ctxt.vcpu = vcpu;
1203         emulate_ctxt.eflags = kvm_arch_ops->get_rflags(vcpu);
1204         emulate_ctxt.cr2 = cr2;
1205         emulate_ctxt.mode = (emulate_ctxt.eflags & X86_EFLAGS_VM)
1206                 ? X86EMUL_MODE_REAL : cs_l
1207                 ? X86EMUL_MODE_PROT64 : cs_db
1208                 ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
1209
1210         if (emulate_ctxt.mode == X86EMUL_MODE_PROT64) {
1211                 emulate_ctxt.cs_base = 0;
1212                 emulate_ctxt.ds_base = 0;
1213                 emulate_ctxt.es_base = 0;
1214                 emulate_ctxt.ss_base = 0;
1215         } else {
1216                 emulate_ctxt.cs_base = get_segment_base(vcpu, VCPU_SREG_CS);
1217                 emulate_ctxt.ds_base = get_segment_base(vcpu, VCPU_SREG_DS);
1218                 emulate_ctxt.es_base = get_segment_base(vcpu, VCPU_SREG_ES);
1219                 emulate_ctxt.ss_base = get_segment_base(vcpu, VCPU_SREG_SS);
1220         }
1221
1222         emulate_ctxt.gs_base = get_segment_base(vcpu, VCPU_SREG_GS);
1223         emulate_ctxt.fs_base = get_segment_base(vcpu, VCPU_SREG_FS);
1224
1225         vcpu->mmio_is_write = 0;
1226         r = x86_emulate_memop(&emulate_ctxt, &emulate_ops);
1227
1228         if ((r || vcpu->mmio_is_write) && run) {
1229                 run->exit_reason = KVM_EXIT_MMIO;
1230                 run->mmio.phys_addr = vcpu->mmio_phys_addr;
1231                 memcpy(run->mmio.data, vcpu->mmio_data, 8);
1232                 run->mmio.len = vcpu->mmio_size;
1233                 run->mmio.is_write = vcpu->mmio_is_write;
1234         }
1235
1236         if (r) {
1237                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
1238                         return EMULATE_DONE;
1239                 if (!vcpu->mmio_needed) {
1240                         report_emulation_failure(&emulate_ctxt);
1241                         return EMULATE_FAIL;
1242                 }
1243                 return EMULATE_DO_MMIO;
1244         }
1245
1246         kvm_arch_ops->decache_regs(vcpu);
1247         kvm_arch_ops->set_rflags(vcpu, emulate_ctxt.eflags);
1248
1249         if (vcpu->mmio_is_write) {
1250                 vcpu->mmio_needed = 0;
1251                 return EMULATE_DO_MMIO;
1252         }
1253
1254         return EMULATE_DONE;
1255 }
1256 EXPORT_SYMBOL_GPL(emulate_instruction);
1257
1258 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
1259 {
1260         if (vcpu->irq_summary)
1261                 return 1;
1262
1263         vcpu->run->exit_reason = KVM_EXIT_HLT;
1264         ++vcpu->stat.halt_exits;
1265         return 0;
1266 }
1267 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
1268
1269 int kvm_hypercall(struct kvm_vcpu *vcpu, struct kvm_run *run)
1270 {
1271         unsigned long nr, a0, a1, a2, a3, a4, a5, ret;
1272
1273         kvm_arch_ops->cache_regs(vcpu);
1274         ret = -KVM_EINVAL;
1275 #ifdef CONFIG_X86_64
1276         if (is_long_mode(vcpu)) {
1277                 nr = vcpu->regs[VCPU_REGS_RAX];
1278                 a0 = vcpu->regs[VCPU_REGS_RDI];
1279                 a1 = vcpu->regs[VCPU_REGS_RSI];
1280                 a2 = vcpu->regs[VCPU_REGS_RDX];
1281                 a3 = vcpu->regs[VCPU_REGS_RCX];
1282                 a4 = vcpu->regs[VCPU_REGS_R8];
1283                 a5 = vcpu->regs[VCPU_REGS_R9];
1284         } else
1285 #endif
1286         {
1287                 nr = vcpu->regs[VCPU_REGS_RBX] & -1u;
1288                 a0 = vcpu->regs[VCPU_REGS_RAX] & -1u;
1289                 a1 = vcpu->regs[VCPU_REGS_RCX] & -1u;
1290                 a2 = vcpu->regs[VCPU_REGS_RDX] & -1u;
1291                 a3 = vcpu->regs[VCPU_REGS_RSI] & -1u;
1292                 a4 = vcpu->regs[VCPU_REGS_RDI] & -1u;
1293                 a5 = vcpu->regs[VCPU_REGS_RBP] & -1u;
1294         }
1295         switch (nr) {
1296         default:
1297                 run->hypercall.nr = nr;
1298                 run->hypercall.args[0] = a0;
1299                 run->hypercall.args[1] = a1;
1300                 run->hypercall.args[2] = a2;
1301                 run->hypercall.args[3] = a3;
1302                 run->hypercall.args[4] = a4;
1303                 run->hypercall.args[5] = a5;
1304                 run->hypercall.ret = ret;
1305                 run->hypercall.longmode = is_long_mode(vcpu);
1306                 kvm_arch_ops->decache_regs(vcpu);
1307                 return 0;
1308         }
1309         vcpu->regs[VCPU_REGS_RAX] = ret;
1310         kvm_arch_ops->decache_regs(vcpu);
1311         return 1;
1312 }
1313 EXPORT_SYMBOL_GPL(kvm_hypercall);
1314
1315 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
1316 {
1317         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
1318 }
1319
1320 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
1321 {
1322         struct descriptor_table dt = { limit, base };
1323
1324         kvm_arch_ops->set_gdt(vcpu, &dt);
1325 }
1326
1327 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
1328 {
1329         struct descriptor_table dt = { limit, base };
1330
1331         kvm_arch_ops->set_idt(vcpu, &dt);
1332 }
1333
1334 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
1335                    unsigned long *rflags)
1336 {
1337         lmsw(vcpu, msw);
1338         *rflags = kvm_arch_ops->get_rflags(vcpu);
1339 }
1340
1341 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
1342 {
1343         kvm_arch_ops->decache_cr4_guest_bits(vcpu);
1344         switch (cr) {
1345         case 0:
1346                 return vcpu->cr0;
1347         case 2:
1348                 return vcpu->cr2;
1349         case 3:
1350                 return vcpu->cr3;
1351         case 4:
1352                 return vcpu->cr4;
1353         default:
1354                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
1355                 return 0;
1356         }
1357 }
1358
1359 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
1360                      unsigned long *rflags)
1361 {
1362         switch (cr) {
1363         case 0:
1364                 set_cr0(vcpu, mk_cr_64(vcpu->cr0, val));
1365                 *rflags = kvm_arch_ops->get_rflags(vcpu);
1366                 break;
1367         case 2:
1368                 vcpu->cr2 = val;
1369                 break;
1370         case 3:
1371                 set_cr3(vcpu, val);
1372                 break;
1373         case 4:
1374                 set_cr4(vcpu, mk_cr_64(vcpu->cr4, val));
1375                 break;
1376         default:
1377                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
1378         }
1379 }
1380
1381 /*
1382  * Register the para guest with the host:
1383  */
1384 static int vcpu_register_para(struct kvm_vcpu *vcpu, gpa_t para_state_gpa)
1385 {
1386         struct kvm_vcpu_para_state *para_state;
1387         hpa_t para_state_hpa, hypercall_hpa;
1388         struct page *para_state_page;
1389         unsigned char *hypercall;
1390         gpa_t hypercall_gpa;
1391
1392         printk(KERN_DEBUG "kvm: guest trying to enter paravirtual mode\n");
1393         printk(KERN_DEBUG ".... para_state_gpa: %08Lx\n", para_state_gpa);
1394
1395         /*
1396          * Needs to be page aligned:
1397          */
1398         if (para_state_gpa != PAGE_ALIGN(para_state_gpa))
1399                 goto err_gp;
1400
1401         para_state_hpa = gpa_to_hpa(vcpu, para_state_gpa);
1402         printk(KERN_DEBUG ".... para_state_hpa: %08Lx\n", para_state_hpa);
1403         if (is_error_hpa(para_state_hpa))
1404                 goto err_gp;
1405
1406         mark_page_dirty(vcpu->kvm, para_state_gpa >> PAGE_SHIFT);
1407         para_state_page = pfn_to_page(para_state_hpa >> PAGE_SHIFT);
1408         para_state = kmap(para_state_page);
1409
1410         printk(KERN_DEBUG "....  guest version: %d\n", para_state->guest_version);
1411         printk(KERN_DEBUG "....           size: %d\n", para_state->size);
1412
1413         para_state->host_version = KVM_PARA_API_VERSION;
1414         /*
1415          * We cannot support guests that try to register themselves
1416          * with a newer API version than the host supports:
1417          */
1418         if (para_state->guest_version > KVM_PARA_API_VERSION) {
1419                 para_state->ret = -KVM_EINVAL;
1420                 goto err_kunmap_skip;
1421         }
1422
1423         hypercall_gpa = para_state->hypercall_gpa;
1424         hypercall_hpa = gpa_to_hpa(vcpu, hypercall_gpa);
1425         printk(KERN_DEBUG ".... hypercall_hpa: %08Lx\n", hypercall_hpa);
1426         if (is_error_hpa(hypercall_hpa)) {
1427                 para_state->ret = -KVM_EINVAL;
1428                 goto err_kunmap_skip;
1429         }
1430
1431         printk(KERN_DEBUG "kvm: para guest successfully registered.\n");
1432         vcpu->para_state_page = para_state_page;
1433         vcpu->para_state_gpa = para_state_gpa;
1434         vcpu->hypercall_gpa = hypercall_gpa;
1435
1436         mark_page_dirty(vcpu->kvm, hypercall_gpa >> PAGE_SHIFT);
1437         hypercall = kmap_atomic(pfn_to_page(hypercall_hpa >> PAGE_SHIFT),
1438                                 KM_USER1) + (hypercall_hpa & ~PAGE_MASK);
1439         kvm_arch_ops->patch_hypercall(vcpu, hypercall);
1440         kunmap_atomic(hypercall, KM_USER1);
1441
1442         para_state->ret = 0;
1443 err_kunmap_skip:
1444         kunmap(para_state_page);
1445         return 0;
1446 err_gp:
1447         return 1;
1448 }
1449
1450 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1451 {
1452         u64 data;
1453
1454         switch (msr) {
1455         case 0xc0010010: /* SYSCFG */
1456         case 0xc0010015: /* HWCR */
1457         case MSR_IA32_PLATFORM_ID:
1458         case MSR_IA32_P5_MC_ADDR:
1459         case MSR_IA32_P5_MC_TYPE:
1460         case MSR_IA32_MC0_CTL:
1461         case MSR_IA32_MCG_STATUS:
1462         case MSR_IA32_MCG_CAP:
1463         case MSR_IA32_MC0_MISC:
1464         case MSR_IA32_MC0_MISC+4:
1465         case MSR_IA32_MC0_MISC+8:
1466         case MSR_IA32_MC0_MISC+12:
1467         case MSR_IA32_MC0_MISC+16:
1468         case MSR_IA32_UCODE_REV:
1469         case MSR_IA32_PERF_STATUS:
1470         case MSR_IA32_EBL_CR_POWERON:
1471                 /* MTRR registers */
1472         case 0xfe:
1473         case 0x200 ... 0x2ff:
1474                 data = 0;
1475                 break;
1476         case 0xcd: /* fsb frequency */
1477                 data = 3;
1478                 break;
1479         case MSR_IA32_APICBASE:
1480                 data = vcpu->apic_base;
1481                 break;
1482         case MSR_IA32_MISC_ENABLE:
1483                 data = vcpu->ia32_misc_enable_msr;
1484                 break;
1485 #ifdef CONFIG_X86_64
1486         case MSR_EFER:
1487                 data = vcpu->shadow_efer;
1488                 break;
1489 #endif
1490         default:
1491                 printk(KERN_ERR "kvm: unhandled rdmsr: 0x%x\n", msr);
1492                 return 1;
1493         }
1494         *pdata = data;
1495         return 0;
1496 }
1497 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
1498
1499 /*
1500  * Reads an msr value (of 'msr_index') into 'pdata'.
1501  * Returns 0 on success, non-0 otherwise.
1502  * Assumes vcpu_load() was already called.
1503  */
1504 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1505 {
1506         return kvm_arch_ops->get_msr(vcpu, msr_index, pdata);
1507 }
1508
1509 #ifdef CONFIG_X86_64
1510
1511 static void set_efer(struct kvm_vcpu *vcpu, u64 efer)
1512 {
1513         if (efer & EFER_RESERVED_BITS) {
1514                 printk(KERN_DEBUG "set_efer: 0x%llx #GP, reserved bits\n",
1515                        efer);
1516                 inject_gp(vcpu);
1517                 return;
1518         }
1519
1520         if (is_paging(vcpu)
1521             && (vcpu->shadow_efer & EFER_LME) != (efer & EFER_LME)) {
1522                 printk(KERN_DEBUG "set_efer: #GP, change LME while paging\n");
1523                 inject_gp(vcpu);
1524                 return;
1525         }
1526
1527         kvm_arch_ops->set_efer(vcpu, efer);
1528
1529         efer &= ~EFER_LMA;
1530         efer |= vcpu->shadow_efer & EFER_LMA;
1531
1532         vcpu->shadow_efer = efer;
1533 }
1534
1535 #endif
1536
1537 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1538 {
1539         switch (msr) {
1540 #ifdef CONFIG_X86_64
1541         case MSR_EFER:
1542                 set_efer(vcpu, data);
1543                 break;
1544 #endif
1545         case MSR_IA32_MC0_STATUS:
1546                 printk(KERN_WARNING "%s: MSR_IA32_MC0_STATUS 0x%llx, nop\n",
1547                        __FUNCTION__, data);
1548                 break;
1549         case MSR_IA32_MCG_STATUS:
1550                 printk(KERN_WARNING "%s: MSR_IA32_MCG_STATUS 0x%llx, nop\n",
1551                         __FUNCTION__, data);
1552                 break;
1553         case MSR_IA32_UCODE_REV:
1554         case MSR_IA32_UCODE_WRITE:
1555         case 0x200 ... 0x2ff: /* MTRRs */
1556                 break;
1557         case MSR_IA32_APICBASE:
1558                 vcpu->apic_base = data;
1559                 break;
1560         case MSR_IA32_MISC_ENABLE:
1561                 vcpu->ia32_misc_enable_msr = data;
1562                 break;
1563         /*
1564          * This is the 'probe whether the host is KVM' logic:
1565          */
1566         case MSR_KVM_API_MAGIC:
1567                 return vcpu_register_para(vcpu, data);
1568
1569         default:
1570                 printk(KERN_ERR "kvm: unhandled wrmsr: 0x%x\n", msr);
1571                 return 1;
1572         }
1573         return 0;
1574 }
1575 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
1576
1577 /*
1578  * Writes msr value into into the appropriate "register".
1579  * Returns 0 on success, non-0 otherwise.
1580  * Assumes vcpu_load() was already called.
1581  */
1582 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
1583 {
1584         return kvm_arch_ops->set_msr(vcpu, msr_index, data);
1585 }
1586
1587 void kvm_resched(struct kvm_vcpu *vcpu)
1588 {
1589         if (!need_resched())
1590                 return;
1591         cond_resched();
1592 }
1593 EXPORT_SYMBOL_GPL(kvm_resched);
1594
1595 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
1596 {
1597         int i;
1598         u32 function;
1599         struct kvm_cpuid_entry *e, *best;
1600
1601         kvm_arch_ops->cache_regs(vcpu);
1602         function = vcpu->regs[VCPU_REGS_RAX];
1603         vcpu->regs[VCPU_REGS_RAX] = 0;
1604         vcpu->regs[VCPU_REGS_RBX] = 0;
1605         vcpu->regs[VCPU_REGS_RCX] = 0;
1606         vcpu->regs[VCPU_REGS_RDX] = 0;
1607         best = NULL;
1608         for (i = 0; i < vcpu->cpuid_nent; ++i) {
1609                 e = &vcpu->cpuid_entries[i];
1610                 if (e->function == function) {
1611                         best = e;
1612                         break;
1613                 }
1614                 /*
1615                  * Both basic or both extended?
1616                  */
1617                 if (((e->function ^ function) & 0x80000000) == 0)
1618                         if (!best || e->function > best->function)
1619                                 best = e;
1620         }
1621         if (best) {
1622                 vcpu->regs[VCPU_REGS_RAX] = best->eax;
1623                 vcpu->regs[VCPU_REGS_RBX] = best->ebx;
1624                 vcpu->regs[VCPU_REGS_RCX] = best->ecx;
1625                 vcpu->regs[VCPU_REGS_RDX] = best->edx;
1626         }
1627         kvm_arch_ops->decache_regs(vcpu);
1628         kvm_arch_ops->skip_emulated_instruction(vcpu);
1629 }
1630 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
1631
1632 static int pio_copy_data(struct kvm_vcpu *vcpu)
1633 {
1634         void *p = vcpu->pio_data;
1635         void *q;
1636         unsigned bytes;
1637         int nr_pages = vcpu->pio.guest_pages[1] ? 2 : 1;
1638
1639         q = vmap(vcpu->pio.guest_pages, nr_pages, VM_READ|VM_WRITE,
1640                  PAGE_KERNEL);
1641         if (!q) {
1642                 free_pio_guest_pages(vcpu);
1643                 return -ENOMEM;
1644         }
1645         q += vcpu->pio.guest_page_offset;
1646         bytes = vcpu->pio.size * vcpu->pio.cur_count;
1647         if (vcpu->pio.in)
1648                 memcpy(q, p, bytes);
1649         else
1650                 memcpy(p, q, bytes);
1651         q -= vcpu->pio.guest_page_offset;
1652         vunmap(q);
1653         free_pio_guest_pages(vcpu);
1654         return 0;
1655 }
1656
1657 static int complete_pio(struct kvm_vcpu *vcpu)
1658 {
1659         struct kvm_pio_request *io = &vcpu->pio;
1660         long delta;
1661         int r;
1662
1663         kvm_arch_ops->cache_regs(vcpu);
1664
1665         if (!io->string) {
1666                 if (io->in)
1667                         memcpy(&vcpu->regs[VCPU_REGS_RAX], vcpu->pio_data,
1668                                io->size);
1669         } else {
1670                 if (io->in) {
1671                         r = pio_copy_data(vcpu);
1672                         if (r) {
1673                                 kvm_arch_ops->cache_regs(vcpu);
1674                                 return r;
1675                         }
1676                 }
1677
1678                 delta = 1;
1679                 if (io->rep) {
1680                         delta *= io->cur_count;
1681                         /*
1682                          * The size of the register should really depend on
1683                          * current address size.
1684                          */
1685                         vcpu->regs[VCPU_REGS_RCX] -= delta;
1686                 }
1687                 if (io->down)
1688                         delta = -delta;
1689                 delta *= io->size;
1690                 if (io->in)
1691                         vcpu->regs[VCPU_REGS_RDI] += delta;
1692                 else
1693                         vcpu->regs[VCPU_REGS_RSI] += delta;
1694         }
1695
1696         kvm_arch_ops->decache_regs(vcpu);
1697
1698         io->count -= io->cur_count;
1699         io->cur_count = 0;
1700
1701         if (!io->count)
1702                 kvm_arch_ops->skip_emulated_instruction(vcpu);
1703         return 0;
1704 }
1705
1706 static void kernel_pio(struct kvm_io_device *pio_dev,
1707                        struct kvm_vcpu *vcpu,
1708                        void *pd)
1709 {
1710         /* TODO: String I/O for in kernel device */
1711
1712         if (vcpu->pio.in)
1713                 kvm_iodevice_read(pio_dev, vcpu->pio.port,
1714                                   vcpu->pio.size,
1715                                   pd);
1716         else
1717                 kvm_iodevice_write(pio_dev, vcpu->pio.port,
1718                                    vcpu->pio.size,
1719                                    pd);
1720 }
1721
1722 static void pio_string_write(struct kvm_io_device *pio_dev,
1723                              struct kvm_vcpu *vcpu)
1724 {
1725         struct kvm_pio_request *io = &vcpu->pio;
1726         void *pd = vcpu->pio_data;
1727         int i;
1728
1729         for (i = 0; i < io->cur_count; i++) {
1730                 kvm_iodevice_write(pio_dev, io->port,
1731                                    io->size,
1732                                    pd);
1733                 pd += io->size;
1734         }
1735 }
1736
1737 int kvm_setup_pio(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
1738                   int size, unsigned long count, int string, int down,
1739                   gva_t address, int rep, unsigned port)
1740 {
1741         unsigned now, in_page;
1742         int i, ret = 0;
1743         int nr_pages = 1;
1744         struct page *page;
1745         struct kvm_io_device *pio_dev;
1746
1747         vcpu->run->exit_reason = KVM_EXIT_IO;
1748         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
1749         vcpu->run->io.size = size;
1750         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
1751         vcpu->run->io.count = count;
1752         vcpu->run->io.port = port;
1753         vcpu->pio.count = count;
1754         vcpu->pio.cur_count = count;
1755         vcpu->pio.size = size;
1756         vcpu->pio.in = in;
1757         vcpu->pio.port = port;
1758         vcpu->pio.string = string;
1759         vcpu->pio.down = down;
1760         vcpu->pio.guest_page_offset = offset_in_page(address);
1761         vcpu->pio.rep = rep;
1762
1763         pio_dev = vcpu_find_pio_dev(vcpu, port);
1764         if (!string) {
1765                 kvm_arch_ops->cache_regs(vcpu);
1766                 memcpy(vcpu->pio_data, &vcpu->regs[VCPU_REGS_RAX], 4);
1767                 kvm_arch_ops->decache_regs(vcpu);
1768                 if (pio_dev) {
1769                         kernel_pio(pio_dev, vcpu, vcpu->pio_data);
1770                         complete_pio(vcpu);
1771                         return 1;
1772                 }
1773                 return 0;
1774         }
1775
1776         if (!count) {
1777                 kvm_arch_ops->skip_emulated_instruction(vcpu);
1778                 return 1;
1779         }
1780
1781         now = min(count, PAGE_SIZE / size);
1782
1783         if (!down)
1784                 in_page = PAGE_SIZE - offset_in_page(address);
1785         else
1786                 in_page = offset_in_page(address) + size;
1787         now = min(count, (unsigned long)in_page / size);
1788         if (!now) {
1789                 /*
1790                  * String I/O straddles page boundary.  Pin two guest pages
1791                  * so that we satisfy atomicity constraints.  Do just one
1792                  * transaction to avoid complexity.
1793                  */
1794                 nr_pages = 2;
1795                 now = 1;
1796         }
1797         if (down) {
1798                 /*
1799                  * String I/O in reverse.  Yuck.  Kill the guest, fix later.
1800                  */
1801                 printk(KERN_ERR "kvm: guest string pio down\n");
1802                 inject_gp(vcpu);
1803                 return 1;
1804         }
1805         vcpu->run->io.count = now;
1806         vcpu->pio.cur_count = now;
1807
1808         for (i = 0; i < nr_pages; ++i) {
1809                 mutex_lock(&vcpu->kvm->lock);
1810                 page = gva_to_page(vcpu, address + i * PAGE_SIZE);
1811                 if (page)
1812                         get_page(page);
1813                 vcpu->pio.guest_pages[i] = page;
1814                 mutex_unlock(&vcpu->kvm->lock);
1815                 if (!page) {
1816                         inject_gp(vcpu);
1817                         free_pio_guest_pages(vcpu);
1818                         return 1;
1819                 }
1820         }
1821
1822         if (!vcpu->pio.in) {
1823                 /* string PIO write */
1824                 ret = pio_copy_data(vcpu);
1825                 if (ret >= 0 && pio_dev) {
1826                         pio_string_write(pio_dev, vcpu);
1827                         complete_pio(vcpu);
1828                         if (vcpu->pio.count == 0)
1829                                 ret = 1;
1830                 }
1831         } else if (pio_dev)
1832                 printk(KERN_ERR "no string pio read support yet, "
1833                        "port %x size %d count %ld\n",
1834                         port, size, count);
1835
1836         return ret;
1837 }
1838 EXPORT_SYMBOL_GPL(kvm_setup_pio);
1839
1840 static int kvm_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
1841 {
1842         int r;
1843         sigset_t sigsaved;
1844
1845         vcpu_load(vcpu);
1846
1847         if (vcpu->sigset_active)
1848                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
1849
1850         /* re-sync apic's tpr */
1851         vcpu->cr8 = kvm_run->cr8;
1852
1853         if (vcpu->pio.cur_count) {
1854                 r = complete_pio(vcpu);
1855                 if (r)
1856                         goto out;
1857         }
1858
1859         if (vcpu->mmio_needed) {
1860                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
1861                 vcpu->mmio_read_completed = 1;
1862                 vcpu->mmio_needed = 0;
1863                 r = emulate_instruction(vcpu, kvm_run,
1864                                         vcpu->mmio_fault_cr2, 0);
1865                 if (r == EMULATE_DO_MMIO) {
1866                         /*
1867                          * Read-modify-write.  Back to userspace.
1868                          */
1869                         r = 0;
1870                         goto out;
1871                 }
1872         }
1873
1874         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL) {
1875                 kvm_arch_ops->cache_regs(vcpu);
1876                 vcpu->regs[VCPU_REGS_RAX] = kvm_run->hypercall.ret;
1877                 kvm_arch_ops->decache_regs(vcpu);
1878         }
1879
1880         r = kvm_arch_ops->run(vcpu, kvm_run);
1881
1882 out:
1883         if (vcpu->sigset_active)
1884                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
1885
1886         vcpu_put(vcpu);
1887         return r;
1888 }
1889
1890 static int kvm_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu,
1891                                    struct kvm_regs *regs)
1892 {
1893         vcpu_load(vcpu);
1894
1895         kvm_arch_ops->cache_regs(vcpu);
1896
1897         regs->rax = vcpu->regs[VCPU_REGS_RAX];
1898         regs->rbx = vcpu->regs[VCPU_REGS_RBX];
1899         regs->rcx = vcpu->regs[VCPU_REGS_RCX];
1900         regs->rdx = vcpu->regs[VCPU_REGS_RDX];
1901         regs->rsi = vcpu->regs[VCPU_REGS_RSI];
1902         regs->rdi = vcpu->regs[VCPU_REGS_RDI];
1903         regs->rsp = vcpu->regs[VCPU_REGS_RSP];
1904         regs->rbp = vcpu->regs[VCPU_REGS_RBP];
1905 #ifdef CONFIG_X86_64
1906         regs->r8 = vcpu->regs[VCPU_REGS_R8];
1907         regs->r9 = vcpu->regs[VCPU_REGS_R9];
1908         regs->r10 = vcpu->regs[VCPU_REGS_R10];
1909         regs->r11 = vcpu->regs[VCPU_REGS_R11];
1910         regs->r12 = vcpu->regs[VCPU_REGS_R12];
1911         regs->r13 = vcpu->regs[VCPU_REGS_R13];
1912         regs->r14 = vcpu->regs[VCPU_REGS_R14];
1913         regs->r15 = vcpu->regs[VCPU_REGS_R15];
1914 #endif
1915
1916         regs->rip = vcpu->rip;
1917         regs->rflags = kvm_arch_ops->get_rflags(vcpu);
1918
1919         /*
1920          * Don't leak debug flags in case they were set for guest debugging
1921          */
1922         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
1923                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
1924
1925         vcpu_put(vcpu);
1926
1927         return 0;
1928 }
1929
1930 static int kvm_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu,
1931                                    struct kvm_regs *regs)
1932 {
1933         vcpu_load(vcpu);
1934
1935         vcpu->regs[VCPU_REGS_RAX] = regs->rax;
1936         vcpu->regs[VCPU_REGS_RBX] = regs->rbx;
1937         vcpu->regs[VCPU_REGS_RCX] = regs->rcx;
1938         vcpu->regs[VCPU_REGS_RDX] = regs->rdx;
1939         vcpu->regs[VCPU_REGS_RSI] = regs->rsi;
1940         vcpu->regs[VCPU_REGS_RDI] = regs->rdi;
1941         vcpu->regs[VCPU_REGS_RSP] = regs->rsp;
1942         vcpu->regs[VCPU_REGS_RBP] = regs->rbp;
1943 #ifdef CONFIG_X86_64
1944         vcpu->regs[VCPU_REGS_R8] = regs->r8;
1945         vcpu->regs[VCPU_REGS_R9] = regs->r9;
1946         vcpu->regs[VCPU_REGS_R10] = regs->r10;
1947         vcpu->regs[VCPU_REGS_R11] = regs->r11;
1948         vcpu->regs[VCPU_REGS_R12] = regs->r12;
1949         vcpu->regs[VCPU_REGS_R13] = regs->r13;
1950         vcpu->regs[VCPU_REGS_R14] = regs->r14;
1951         vcpu->regs[VCPU_REGS_R15] = regs->r15;
1952 #endif
1953
1954         vcpu->rip = regs->rip;
1955         kvm_arch_ops->set_rflags(vcpu, regs->rflags);
1956
1957         kvm_arch_ops->decache_regs(vcpu);
1958
1959         vcpu_put(vcpu);
1960
1961         return 0;
1962 }
1963
1964 static void get_segment(struct kvm_vcpu *vcpu,
1965                         struct kvm_segment *var, int seg)
1966 {
1967         return kvm_arch_ops->get_segment(vcpu, var, seg);
1968 }
1969
1970 static int kvm_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
1971                                     struct kvm_sregs *sregs)
1972 {
1973         struct descriptor_table dt;
1974
1975         vcpu_load(vcpu);
1976
1977         get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
1978         get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
1979         get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
1980         get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
1981         get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
1982         get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
1983
1984         get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
1985         get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
1986
1987         kvm_arch_ops->get_idt(vcpu, &dt);
1988         sregs->idt.limit = dt.limit;
1989         sregs->idt.base = dt.base;
1990         kvm_arch_ops->get_gdt(vcpu, &dt);
1991         sregs->gdt.limit = dt.limit;
1992         sregs->gdt.base = dt.base;
1993
1994         kvm_arch_ops->decache_cr4_guest_bits(vcpu);
1995         sregs->cr0 = vcpu->cr0;
1996         sregs->cr2 = vcpu->cr2;
1997         sregs->cr3 = vcpu->cr3;
1998         sregs->cr4 = vcpu->cr4;
1999         sregs->cr8 = vcpu->cr8;
2000         sregs->efer = vcpu->shadow_efer;
2001         sregs->apic_base = vcpu->apic_base;
2002
2003         memcpy(sregs->interrupt_bitmap, vcpu->irq_pending,
2004                sizeof sregs->interrupt_bitmap);
2005
2006         vcpu_put(vcpu);
2007
2008         return 0;
2009 }
2010
2011 static void set_segment(struct kvm_vcpu *vcpu,
2012                         struct kvm_segment *var, int seg)
2013 {
2014         return kvm_arch_ops->set_segment(vcpu, var, seg);
2015 }
2016
2017 static int kvm_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
2018                                     struct kvm_sregs *sregs)
2019 {
2020         int mmu_reset_needed = 0;
2021         int i;
2022         struct descriptor_table dt;
2023
2024         vcpu_load(vcpu);
2025
2026         dt.limit = sregs->idt.limit;
2027         dt.base = sregs->idt.base;
2028         kvm_arch_ops->set_idt(vcpu, &dt);
2029         dt.limit = sregs->gdt.limit;
2030         dt.base = sregs->gdt.base;
2031         kvm_arch_ops->set_gdt(vcpu, &dt);
2032
2033         vcpu->cr2 = sregs->cr2;
2034         mmu_reset_needed |= vcpu->cr3 != sregs->cr3;
2035         vcpu->cr3 = sregs->cr3;
2036
2037         vcpu->cr8 = sregs->cr8;
2038
2039         mmu_reset_needed |= vcpu->shadow_efer != sregs->efer;
2040 #ifdef CONFIG_X86_64
2041         kvm_arch_ops->set_efer(vcpu, sregs->efer);
2042 #endif
2043         vcpu->apic_base = sregs->apic_base;
2044
2045         kvm_arch_ops->decache_cr4_guest_bits(vcpu);
2046
2047         mmu_reset_needed |= vcpu->cr0 != sregs->cr0;
2048         kvm_arch_ops->set_cr0(vcpu, sregs->cr0);
2049
2050         mmu_reset_needed |= vcpu->cr4 != sregs->cr4;
2051         kvm_arch_ops->set_cr4(vcpu, sregs->cr4);
2052         if (!is_long_mode(vcpu) && is_pae(vcpu))
2053                 load_pdptrs(vcpu, vcpu->cr3);
2054
2055         if (mmu_reset_needed)
2056                 kvm_mmu_reset_context(vcpu);
2057
2058         memcpy(vcpu->irq_pending, sregs->interrupt_bitmap,
2059                sizeof vcpu->irq_pending);
2060         vcpu->irq_summary = 0;
2061         for (i = 0; i < ARRAY_SIZE(vcpu->irq_pending); ++i)
2062                 if (vcpu->irq_pending[i])
2063                         __set_bit(i, &vcpu->irq_summary);
2064
2065         set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
2066         set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
2067         set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
2068         set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
2069         set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
2070         set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
2071
2072         set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
2073         set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
2074
2075         vcpu_put(vcpu);
2076
2077         return 0;
2078 }
2079
2080 /*
2081  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
2082  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
2083  *
2084  * This list is modified at module load time to reflect the
2085  * capabilities of the host cpu.
2086  */
2087 static u32 msrs_to_save[] = {
2088         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
2089         MSR_K6_STAR,
2090 #ifdef CONFIG_X86_64
2091         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
2092 #endif
2093         MSR_IA32_TIME_STAMP_COUNTER,
2094 };
2095
2096 static unsigned num_msrs_to_save;
2097
2098 static u32 emulated_msrs[] = {
2099         MSR_IA32_MISC_ENABLE,
2100 };
2101
2102 static __init void kvm_init_msr_list(void)
2103 {
2104         u32 dummy[2];
2105         unsigned i, j;
2106
2107         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
2108                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
2109                         continue;
2110                 if (j < i)
2111                         msrs_to_save[j] = msrs_to_save[i];
2112                 j++;
2113         }
2114         num_msrs_to_save = j;
2115 }
2116
2117 /*
2118  * Adapt set_msr() to msr_io()'s calling convention
2119  */
2120 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2121 {
2122         return kvm_set_msr(vcpu, index, *data);
2123 }
2124
2125 /*
2126  * Read or write a bunch of msrs. All parameters are kernel addresses.
2127  *
2128  * @return number of msrs set successfully.
2129  */
2130 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2131                     struct kvm_msr_entry *entries,
2132                     int (*do_msr)(struct kvm_vcpu *vcpu,
2133                                   unsigned index, u64 *data))
2134 {
2135         int i;
2136
2137         vcpu_load(vcpu);
2138
2139         for (i = 0; i < msrs->nmsrs; ++i)
2140                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2141                         break;
2142
2143         vcpu_put(vcpu);
2144
2145         return i;
2146 }
2147
2148 /*
2149  * Read or write a bunch of msrs. Parameters are user addresses.
2150  *
2151  * @return number of msrs set successfully.
2152  */
2153 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2154                   int (*do_msr)(struct kvm_vcpu *vcpu,
2155                                 unsigned index, u64 *data),
2156                   int writeback)
2157 {
2158         struct kvm_msrs msrs;
2159         struct kvm_msr_entry *entries;
2160         int r, n;
2161         unsigned size;
2162
2163         r = -EFAULT;
2164         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2165                 goto out;
2166
2167         r = -E2BIG;
2168         if (msrs.nmsrs >= MAX_IO_MSRS)
2169                 goto out;
2170
2171         r = -ENOMEM;
2172         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2173         entries = vmalloc(size);
2174         if (!entries)
2175                 goto out;
2176
2177         r = -EFAULT;
2178         if (copy_from_user(entries, user_msrs->entries, size))
2179                 goto out_free;
2180
2181         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2182         if (r < 0)
2183                 goto out_free;
2184
2185         r = -EFAULT;
2186         if (writeback && copy_to_user(user_msrs->entries, entries, size))
2187                 goto out_free;
2188
2189         r = n;
2190
2191 out_free:
2192         vfree(entries);
2193 out:
2194         return r;
2195 }
2196
2197 /*
2198  * Translate a guest virtual address to a guest physical address.
2199  */
2200 static int kvm_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
2201                                     struct kvm_translation *tr)
2202 {
2203         unsigned long vaddr = tr->linear_address;
2204         gpa_t gpa;
2205
2206         vcpu_load(vcpu);
2207         mutex_lock(&vcpu->kvm->lock);
2208         gpa = vcpu->mmu.gva_to_gpa(vcpu, vaddr);
2209         tr->physical_address = gpa;
2210         tr->valid = gpa != UNMAPPED_GVA;
2211         tr->writeable = 1;
2212         tr->usermode = 0;
2213         mutex_unlock(&vcpu->kvm->lock);
2214         vcpu_put(vcpu);
2215
2216         return 0;
2217 }
2218
2219 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2220                                     struct kvm_interrupt *irq)
2221 {
2222         if (irq->irq < 0 || irq->irq >= 256)
2223                 return -EINVAL;
2224         vcpu_load(vcpu);
2225
2226         set_bit(irq->irq, vcpu->irq_pending);
2227         set_bit(irq->irq / BITS_PER_LONG, &vcpu->irq_summary);
2228
2229         vcpu_put(vcpu);
2230
2231         return 0;
2232 }
2233
2234 static int kvm_vcpu_ioctl_debug_guest(struct kvm_vcpu *vcpu,
2235                                       struct kvm_debug_guest *dbg)
2236 {
2237         int r;
2238
2239         vcpu_load(vcpu);
2240
2241         r = kvm_arch_ops->set_guest_debug(vcpu, dbg);
2242
2243         vcpu_put(vcpu);
2244
2245         return r;
2246 }
2247
2248 static struct page *kvm_vcpu_nopage(struct vm_area_struct *vma,
2249                                     unsigned long address,
2250                                     int *type)
2251 {
2252         struct kvm_vcpu *vcpu = vma->vm_file->private_data;
2253         unsigned long pgoff;
2254         struct page *page;
2255
2256         pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
2257         if (pgoff == 0)
2258                 page = virt_to_page(vcpu->run);
2259         else if (pgoff == KVM_PIO_PAGE_OFFSET)
2260                 page = virt_to_page(vcpu->pio_data);
2261         else
2262                 return NOPAGE_SIGBUS;
2263         get_page(page);
2264         if (type != NULL)
2265                 *type = VM_FAULT_MINOR;
2266
2267         return page;
2268 }
2269
2270 static struct vm_operations_struct kvm_vcpu_vm_ops = {
2271         .nopage = kvm_vcpu_nopage,
2272 };
2273
2274 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2275 {
2276         vma->vm_ops = &kvm_vcpu_vm_ops;
2277         return 0;
2278 }
2279
2280 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2281 {
2282         struct kvm_vcpu *vcpu = filp->private_data;
2283
2284         fput(vcpu->kvm->filp);
2285         return 0;
2286 }
2287
2288 static struct file_operations kvm_vcpu_fops = {
2289         .release        = kvm_vcpu_release,
2290         .unlocked_ioctl = kvm_vcpu_ioctl,
2291         .compat_ioctl   = kvm_vcpu_ioctl,
2292         .mmap           = kvm_vcpu_mmap,
2293 };
2294
2295 /*
2296  * Allocates an inode for the vcpu.
2297  */
2298 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2299 {
2300         int fd, r;
2301         struct inode *inode;
2302         struct file *file;
2303
2304         r = anon_inode_getfd(&fd, &inode, &file,
2305                              "kvm-vcpu", &kvm_vcpu_fops, vcpu);
2306         if (r)
2307                 return r;
2308         atomic_inc(&vcpu->kvm->filp->f_count);
2309         return fd;
2310 }
2311
2312 /*
2313  * Creates some virtual cpus.  Good luck creating more than one.
2314  */
2315 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, int n)
2316 {
2317         int r;
2318         struct kvm_vcpu *vcpu;
2319
2320         if (!valid_vcpu(n))
2321                 return -EINVAL;
2322
2323         vcpu = kvm_arch_ops->vcpu_create(kvm, n);
2324         if (IS_ERR(vcpu))
2325                 return PTR_ERR(vcpu);
2326
2327         preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
2328
2329         /* We do fxsave: this must be aligned. */
2330         BUG_ON((unsigned long)&vcpu->host_fx_image & 0xF);
2331
2332         vcpu_load(vcpu);
2333         r = kvm_mmu_setup(vcpu);
2334         vcpu_put(vcpu);
2335         if (r < 0)
2336                 goto free_vcpu;
2337
2338         mutex_lock(&kvm->lock);
2339         if (kvm->vcpus[n]) {
2340                 r = -EEXIST;
2341                 mutex_unlock(&kvm->lock);
2342                 goto mmu_unload;
2343         }
2344         kvm->vcpus[n] = vcpu;
2345         mutex_unlock(&kvm->lock);
2346
2347         /* Now it's all set up, let userspace reach it */
2348         r = create_vcpu_fd(vcpu);
2349         if (r < 0)
2350                 goto unlink;
2351         return r;
2352
2353 unlink:
2354         mutex_lock(&kvm->lock);
2355         kvm->vcpus[n] = NULL;
2356         mutex_unlock(&kvm->lock);
2357
2358 mmu_unload:
2359         vcpu_load(vcpu);
2360         kvm_mmu_unload(vcpu);
2361         vcpu_put(vcpu);
2362
2363 free_vcpu:
2364         kvm_arch_ops->vcpu_free(vcpu);
2365         return r;
2366 }
2367
2368 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
2369 {
2370         u64 efer;
2371         int i;
2372         struct kvm_cpuid_entry *e, *entry;
2373
2374         rdmsrl(MSR_EFER, efer);
2375         entry = NULL;
2376         for (i = 0; i < vcpu->cpuid_nent; ++i) {
2377                 e = &vcpu->cpuid_entries[i];
2378                 if (e->function == 0x80000001) {
2379                         entry = e;
2380                         break;
2381                 }
2382         }
2383         if (entry && (entry->edx & (1 << 20)) && !(efer & EFER_NX)) {
2384                 entry->edx &= ~(1 << 20);
2385                 printk(KERN_INFO "kvm: guest NX capability removed\n");
2386         }
2387 }
2388
2389 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
2390                                     struct kvm_cpuid *cpuid,
2391                                     struct kvm_cpuid_entry __user *entries)
2392 {
2393         int r;
2394
2395         r = -E2BIG;
2396         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2397                 goto out;
2398         r = -EFAULT;
2399         if (copy_from_user(&vcpu->cpuid_entries, entries,
2400                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
2401                 goto out;
2402         vcpu->cpuid_nent = cpuid->nent;
2403         cpuid_fix_nx_cap(vcpu);
2404         return 0;
2405
2406 out:
2407         return r;
2408 }
2409
2410 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
2411 {
2412         if (sigset) {
2413                 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
2414                 vcpu->sigset_active = 1;
2415                 vcpu->sigset = *sigset;
2416         } else
2417                 vcpu->sigset_active = 0;
2418         return 0;
2419 }
2420
2421 /*
2422  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
2423  * we have asm/x86/processor.h
2424  */
2425 struct fxsave {
2426         u16     cwd;
2427         u16     swd;
2428         u16     twd;
2429         u16     fop;
2430         u64     rip;
2431         u64     rdp;
2432         u32     mxcsr;
2433         u32     mxcsr_mask;
2434         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
2435 #ifdef CONFIG_X86_64
2436         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
2437 #else
2438         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
2439 #endif
2440 };
2441
2442 static int kvm_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2443 {
2444         struct fxsave *fxsave = (struct fxsave *)&vcpu->guest_fx_image;
2445
2446         vcpu_load(vcpu);
2447
2448         memcpy(fpu->fpr, fxsave->st_space, 128);
2449         fpu->fcw = fxsave->cwd;
2450         fpu->fsw = fxsave->swd;
2451         fpu->ftwx = fxsave->twd;
2452         fpu->last_opcode = fxsave->fop;
2453         fpu->last_ip = fxsave->rip;
2454         fpu->last_dp = fxsave->rdp;
2455         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
2456
2457         vcpu_put(vcpu);
2458
2459         return 0;
2460 }
2461
2462 static int kvm_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2463 {
2464         struct fxsave *fxsave = (struct fxsave *)&vcpu->guest_fx_image;
2465
2466         vcpu_load(vcpu);
2467
2468         memcpy(fxsave->st_space, fpu->fpr, 128);
2469         fxsave->cwd = fpu->fcw;
2470         fxsave->swd = fpu->fsw;
2471         fxsave->twd = fpu->ftwx;
2472         fxsave->fop = fpu->last_opcode;
2473         fxsave->rip = fpu->last_ip;
2474         fxsave->rdp = fpu->last_dp;
2475         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
2476
2477         vcpu_put(vcpu);
2478
2479         return 0;
2480 }
2481
2482 static long kvm_vcpu_ioctl(struct file *filp,
2483                            unsigned int ioctl, unsigned long arg)
2484 {
2485         struct kvm_vcpu *vcpu = filp->private_data;
2486         void __user *argp = (void __user *)arg;
2487         int r = -EINVAL;
2488
2489         switch (ioctl) {
2490         case KVM_RUN:
2491                 r = -EINVAL;
2492                 if (arg)
2493                         goto out;
2494                 r = kvm_vcpu_ioctl_run(vcpu, vcpu->run);
2495                 break;
2496         case KVM_GET_REGS: {
2497                 struct kvm_regs kvm_regs;
2498
2499                 memset(&kvm_regs, 0, sizeof kvm_regs);
2500                 r = kvm_vcpu_ioctl_get_regs(vcpu, &kvm_regs);
2501                 if (r)
2502                         goto out;
2503                 r = -EFAULT;
2504                 if (copy_to_user(argp, &kvm_regs, sizeof kvm_regs))
2505                         goto out;
2506                 r = 0;
2507                 break;
2508         }
2509         case KVM_SET_REGS: {
2510                 struct kvm_regs kvm_regs;
2511
2512                 r = -EFAULT;
2513                 if (copy_from_user(&kvm_regs, argp, sizeof kvm_regs))
2514                         goto out;
2515                 r = kvm_vcpu_ioctl_set_regs(vcpu, &kvm_regs);
2516                 if (r)
2517                         goto out;
2518                 r = 0;
2519                 break;
2520         }
2521         case KVM_GET_SREGS: {
2522                 struct kvm_sregs kvm_sregs;
2523
2524                 memset(&kvm_sregs, 0, sizeof kvm_sregs);
2525                 r = kvm_vcpu_ioctl_get_sregs(vcpu, &kvm_sregs);
2526                 if (r)
2527                         goto out;
2528                 r = -EFAULT;
2529                 if (copy_to_user(argp, &kvm_sregs, sizeof kvm_sregs))
2530                         goto out;
2531                 r = 0;
2532                 break;
2533         }
2534         case KVM_SET_SREGS: {
2535                 struct kvm_sregs kvm_sregs;
2536
2537                 r = -EFAULT;
2538                 if (copy_from_user(&kvm_sregs, argp, sizeof kvm_sregs))
2539                         goto out;
2540                 r = kvm_vcpu_ioctl_set_sregs(vcpu, &kvm_sregs);
2541                 if (r)
2542                         goto out;
2543                 r = 0;
2544                 break;
2545         }
2546         case KVM_TRANSLATE: {
2547                 struct kvm_translation tr;
2548
2549                 r = -EFAULT;
2550                 if (copy_from_user(&tr, argp, sizeof tr))
2551                         goto out;
2552                 r = kvm_vcpu_ioctl_translate(vcpu, &tr);
2553                 if (r)
2554                         goto out;
2555                 r = -EFAULT;
2556                 if (copy_to_user(argp, &tr, sizeof tr))
2557                         goto out;
2558                 r = 0;
2559                 break;
2560         }
2561         case KVM_INTERRUPT: {
2562                 struct kvm_interrupt irq;
2563
2564                 r = -EFAULT;
2565                 if (copy_from_user(&irq, argp, sizeof irq))
2566                         goto out;
2567                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
2568                 if (r)
2569                         goto out;
2570                 r = 0;
2571                 break;
2572         }
2573         case KVM_DEBUG_GUEST: {
2574                 struct kvm_debug_guest dbg;
2575
2576                 r = -EFAULT;
2577                 if (copy_from_user(&dbg, argp, sizeof dbg))
2578                         goto out;
2579                 r = kvm_vcpu_ioctl_debug_guest(vcpu, &dbg);
2580                 if (r)
2581                         goto out;
2582                 r = 0;
2583                 break;
2584         }
2585         case KVM_GET_MSRS:
2586                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
2587                 break;
2588         case KVM_SET_MSRS:
2589                 r = msr_io(vcpu, argp, do_set_msr, 0);
2590                 break;
2591         case KVM_SET_CPUID: {
2592                 struct kvm_cpuid __user *cpuid_arg = argp;
2593                 struct kvm_cpuid cpuid;
2594
2595                 r = -EFAULT;
2596                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2597                         goto out;
2598                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
2599                 if (r)
2600                         goto out;
2601                 break;
2602         }
2603         case KVM_SET_SIGNAL_MASK: {
2604                 struct kvm_signal_mask __user *sigmask_arg = argp;
2605                 struct kvm_signal_mask kvm_sigmask;
2606                 sigset_t sigset, *p;
2607
2608                 p = NULL;
2609                 if (argp) {
2610                         r = -EFAULT;
2611                         if (copy_from_user(&kvm_sigmask, argp,
2612                                            sizeof kvm_sigmask))
2613                                 goto out;
2614                         r = -EINVAL;
2615                         if (kvm_sigmask.len != sizeof sigset)
2616                                 goto out;
2617                         r = -EFAULT;
2618                         if (copy_from_user(&sigset, sigmask_arg->sigset,
2619                                            sizeof sigset))
2620                                 goto out;
2621                         p = &sigset;
2622                 }
2623                 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
2624                 break;
2625         }
2626         case KVM_GET_FPU: {
2627                 struct kvm_fpu fpu;
2628
2629                 memset(&fpu, 0, sizeof fpu);
2630                 r = kvm_vcpu_ioctl_get_fpu(vcpu, &fpu);
2631                 if (r)
2632                         goto out;
2633                 r = -EFAULT;
2634                 if (copy_to_user(argp, &fpu, sizeof fpu))
2635                         goto out;
2636                 r = 0;
2637                 break;
2638         }
2639         case KVM_SET_FPU: {
2640                 struct kvm_fpu fpu;
2641
2642                 r = -EFAULT;
2643                 if (copy_from_user(&fpu, argp, sizeof fpu))
2644                         goto out;
2645                 r = kvm_vcpu_ioctl_set_fpu(vcpu, &fpu);
2646                 if (r)
2647                         goto out;
2648                 r = 0;
2649                 break;
2650         }
2651         default:
2652                 ;
2653         }
2654 out:
2655         return r;
2656 }
2657
2658 static long kvm_vm_ioctl(struct file *filp,
2659                            unsigned int ioctl, unsigned long arg)
2660 {
2661         struct kvm *kvm = filp->private_data;
2662         void __user *argp = (void __user *)arg;
2663         int r = -EINVAL;
2664
2665         switch (ioctl) {
2666         case KVM_CREATE_VCPU:
2667                 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
2668                 if (r < 0)
2669                         goto out;
2670                 break;
2671         case KVM_SET_MEMORY_REGION: {
2672                 struct kvm_memory_region kvm_mem;
2673
2674                 r = -EFAULT;
2675                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
2676                         goto out;
2677                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_mem);
2678                 if (r)
2679                         goto out;
2680                 break;
2681         }
2682         case KVM_GET_DIRTY_LOG: {
2683                 struct kvm_dirty_log log;
2684
2685                 r = -EFAULT;
2686                 if (copy_from_user(&log, argp, sizeof log))
2687                         goto out;
2688                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
2689                 if (r)
2690                         goto out;
2691                 break;
2692         }
2693         case KVM_SET_MEMORY_ALIAS: {
2694                 struct kvm_memory_alias alias;
2695
2696                 r = -EFAULT;
2697                 if (copy_from_user(&alias, argp, sizeof alias))
2698                         goto out;
2699                 r = kvm_vm_ioctl_set_memory_alias(kvm, &alias);
2700                 if (r)
2701                         goto out;
2702                 break;
2703         }
2704         default:
2705                 ;
2706         }
2707 out:
2708         return r;
2709 }
2710
2711 static struct page *kvm_vm_nopage(struct vm_area_struct *vma,
2712                                   unsigned long address,
2713                                   int *type)
2714 {
2715         struct kvm *kvm = vma->vm_file->private_data;
2716         unsigned long pgoff;
2717         struct page *page;
2718
2719         pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
2720         page = gfn_to_page(kvm, pgoff);
2721         if (!page)
2722                 return NOPAGE_SIGBUS;
2723         get_page(page);
2724         if (type != NULL)
2725                 *type = VM_FAULT_MINOR;
2726
2727         return page;
2728 }
2729
2730 static struct vm_operations_struct kvm_vm_vm_ops = {
2731         .nopage = kvm_vm_nopage,
2732 };
2733
2734 static int kvm_vm_mmap(struct file *file, struct vm_area_struct *vma)
2735 {
2736         vma->vm_ops = &kvm_vm_vm_ops;
2737         return 0;
2738 }
2739
2740 static struct file_operations kvm_vm_fops = {
2741         .release        = kvm_vm_release,
2742         .unlocked_ioctl = kvm_vm_ioctl,
2743         .compat_ioctl   = kvm_vm_ioctl,
2744         .mmap           = kvm_vm_mmap,
2745 };
2746
2747 static int kvm_dev_ioctl_create_vm(void)
2748 {
2749         int fd, r;
2750         struct inode *inode;
2751         struct file *file;
2752         struct kvm *kvm;
2753
2754         kvm = kvm_create_vm();
2755         if (IS_ERR(kvm))
2756                 return PTR_ERR(kvm);
2757         r = anon_inode_getfd(&fd, &inode, &file, "kvm-vm", &kvm_vm_fops, kvm);
2758         if (r) {
2759                 kvm_destroy_vm(kvm);
2760                 return r;
2761         }
2762
2763         kvm->filp = file;
2764
2765         return fd;
2766 }
2767
2768 static long kvm_dev_ioctl(struct file *filp,
2769                           unsigned int ioctl, unsigned long arg)
2770 {
2771         void __user *argp = (void __user *)arg;
2772         long r = -EINVAL;
2773
2774         switch (ioctl) {
2775         case KVM_GET_API_VERSION:
2776                 r = -EINVAL;
2777                 if (arg)
2778                         goto out;
2779                 r = KVM_API_VERSION;
2780                 break;
2781         case KVM_CREATE_VM:
2782                 r = -EINVAL;
2783                 if (arg)
2784                         goto out;
2785                 r = kvm_dev_ioctl_create_vm();
2786                 break;
2787         case KVM_GET_MSR_INDEX_LIST: {
2788                 struct kvm_msr_list __user *user_msr_list = argp;
2789                 struct kvm_msr_list msr_list;
2790                 unsigned n;
2791
2792                 r = -EFAULT;
2793                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2794                         goto out;
2795                 n = msr_list.nmsrs;
2796                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
2797                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2798                         goto out;
2799                 r = -E2BIG;
2800                 if (n < num_msrs_to_save)
2801                         goto out;
2802                 r = -EFAULT;
2803                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2804                                  num_msrs_to_save * sizeof(u32)))
2805                         goto out;
2806                 if (copy_to_user(user_msr_list->indices
2807                                  + num_msrs_to_save * sizeof(u32),
2808                                  &emulated_msrs,
2809                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
2810                         goto out;
2811                 r = 0;
2812                 break;
2813         }
2814         case KVM_CHECK_EXTENSION:
2815                 /*
2816                  * No extensions defined at present.
2817                  */
2818                 r = 0;
2819                 break;
2820         case KVM_GET_VCPU_MMAP_SIZE:
2821                 r = -EINVAL;
2822                 if (arg)
2823                         goto out;
2824                 r = 2 * PAGE_SIZE;
2825                 break;
2826         default:
2827                 ;
2828         }
2829 out:
2830         return r;
2831 }
2832
2833 static struct file_operations kvm_chardev_ops = {
2834         .unlocked_ioctl = kvm_dev_ioctl,
2835         .compat_ioctl   = kvm_dev_ioctl,
2836 };
2837
2838 static struct miscdevice kvm_dev = {
2839         KVM_MINOR,
2840         "kvm",
2841         &kvm_chardev_ops,
2842 };
2843
2844 /*
2845  * Make sure that a cpu that is being hot-unplugged does not have any vcpus
2846  * cached on it.
2847  */
2848 static void decache_vcpus_on_cpu(int cpu)
2849 {
2850         struct kvm *vm;
2851         struct kvm_vcpu *vcpu;
2852         int i;
2853
2854         spin_lock(&kvm_lock);
2855         list_for_each_entry(vm, &vm_list, vm_list)
2856                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
2857                         vcpu = vm->vcpus[i];
2858                         if (!vcpu)
2859                                 continue;
2860                         /*
2861                          * If the vcpu is locked, then it is running on some
2862                          * other cpu and therefore it is not cached on the
2863                          * cpu in question.
2864                          *
2865                          * If it's not locked, check the last cpu it executed
2866                          * on.
2867                          */
2868                         if (mutex_trylock(&vcpu->mutex)) {
2869                                 if (vcpu->cpu == cpu) {
2870                                         kvm_arch_ops->vcpu_decache(vcpu);
2871                                         vcpu->cpu = -1;
2872                                 }
2873                                 mutex_unlock(&vcpu->mutex);
2874                         }
2875                 }
2876         spin_unlock(&kvm_lock);
2877 }
2878
2879 static void hardware_enable(void *junk)
2880 {
2881         int cpu = raw_smp_processor_id();
2882
2883         if (cpu_isset(cpu, cpus_hardware_enabled))
2884                 return;
2885         cpu_set(cpu, cpus_hardware_enabled);
2886         kvm_arch_ops->hardware_enable(NULL);
2887 }
2888
2889 static void hardware_disable(void *junk)
2890 {
2891         int cpu = raw_smp_processor_id();
2892
2893         if (!cpu_isset(cpu, cpus_hardware_enabled))
2894                 return;
2895         cpu_clear(cpu, cpus_hardware_enabled);
2896         decache_vcpus_on_cpu(cpu);
2897         kvm_arch_ops->hardware_disable(NULL);
2898 }
2899
2900 static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
2901                            void *v)
2902 {
2903         int cpu = (long)v;
2904
2905         switch (val) {
2906         case CPU_DYING:
2907         case CPU_DYING_FROZEN:
2908                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
2909                        cpu);
2910                 hardware_disable(NULL);
2911                 break;
2912         case CPU_UP_CANCELED:
2913         case CPU_UP_CANCELED_FROZEN:
2914                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
2915                        cpu);
2916                 smp_call_function_single(cpu, hardware_disable, NULL, 0, 1);
2917                 break;
2918         case CPU_ONLINE:
2919         case CPU_ONLINE_FROZEN:
2920                 printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
2921                        cpu);
2922                 smp_call_function_single(cpu, hardware_enable, NULL, 0, 1);
2923                 break;
2924         }
2925         return NOTIFY_OK;
2926 }
2927
2928 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
2929                        void *v)
2930 {
2931         if (val == SYS_RESTART) {
2932                 /*
2933                  * Some (well, at least mine) BIOSes hang on reboot if
2934                  * in vmx root mode.
2935                  */
2936                 printk(KERN_INFO "kvm: exiting hardware virtualization\n");
2937                 on_each_cpu(hardware_disable, NULL, 0, 1);
2938         }
2939         return NOTIFY_OK;
2940 }
2941
2942 static struct notifier_block kvm_reboot_notifier = {
2943         .notifier_call = kvm_reboot,
2944         .priority = 0,
2945 };
2946
2947 void kvm_io_bus_init(struct kvm_io_bus *bus)
2948 {
2949         memset(bus, 0, sizeof(*bus));
2950 }
2951
2952 void kvm_io_bus_destroy(struct kvm_io_bus *bus)
2953 {
2954         int i;
2955
2956         for (i = 0; i < bus->dev_count; i++) {
2957                 struct kvm_io_device *pos = bus->devs[i];
2958
2959                 kvm_iodevice_destructor(pos);
2960         }
2961 }
2962
2963 struct kvm_io_device *kvm_io_bus_find_dev(struct kvm_io_bus *bus, gpa_t addr)
2964 {
2965         int i;
2966
2967         for (i = 0; i < bus->dev_count; i++) {
2968                 struct kvm_io_device *pos = bus->devs[i];
2969
2970                 if (pos->in_range(pos, addr))
2971                         return pos;
2972         }
2973
2974         return NULL;
2975 }
2976
2977 void kvm_io_bus_register_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev)
2978 {
2979         BUG_ON(bus->dev_count > (NR_IOBUS_DEVS-1));
2980
2981         bus->devs[bus->dev_count++] = dev;
2982 }
2983
2984 static struct notifier_block kvm_cpu_notifier = {
2985         .notifier_call = kvm_cpu_hotplug,
2986         .priority = 20, /* must be > scheduler priority */
2987 };
2988
2989 static u64 stat_get(void *_offset)
2990 {
2991         unsigned offset = (long)_offset;
2992         u64 total = 0;
2993         struct kvm *kvm;
2994         struct kvm_vcpu *vcpu;
2995         int i;
2996
2997         spin_lock(&kvm_lock);
2998         list_for_each_entry(kvm, &vm_list, vm_list)
2999                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
3000                         vcpu = kvm->vcpus[i];
3001                         if (vcpu)
3002                                 total += *(u32 *)((void *)vcpu + offset);
3003                 }
3004         spin_unlock(&kvm_lock);
3005         return total;
3006 }
3007
3008 DEFINE_SIMPLE_ATTRIBUTE(stat_fops, stat_get, NULL, "%llu\n");
3009
3010 static __init void kvm_init_debug(void)
3011 {
3012         struct kvm_stats_debugfs_item *p;
3013
3014         debugfs_dir = debugfs_create_dir("kvm", NULL);
3015         for (p = debugfs_entries; p->name; ++p)
3016                 p->dentry = debugfs_create_file(p->name, 0444, debugfs_dir,
3017                                                 (void *)(long)p->offset,
3018                                                 &stat_fops);
3019 }
3020
3021 static void kvm_exit_debug(void)
3022 {
3023         struct kvm_stats_debugfs_item *p;
3024
3025         for (p = debugfs_entries; p->name; ++p)
3026                 debugfs_remove(p->dentry);
3027         debugfs_remove(debugfs_dir);
3028 }
3029
3030 static int kvm_suspend(struct sys_device *dev, pm_message_t state)
3031 {
3032         hardware_disable(NULL);
3033         return 0;
3034 }
3035
3036 static int kvm_resume(struct sys_device *dev)
3037 {
3038         hardware_enable(NULL);
3039         return 0;
3040 }
3041
3042 static struct sysdev_class kvm_sysdev_class = {
3043         set_kset_name("kvm"),
3044         .suspend = kvm_suspend,
3045         .resume = kvm_resume,
3046 };
3047
3048 static struct sys_device kvm_sysdev = {
3049         .id = 0,
3050         .cls = &kvm_sysdev_class,
3051 };
3052
3053 hpa_t bad_page_address;
3054
3055 static inline
3056 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
3057 {
3058         return container_of(pn, struct kvm_vcpu, preempt_notifier);
3059 }
3060
3061 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
3062 {
3063         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
3064
3065         kvm_arch_ops->vcpu_load(vcpu, cpu);
3066 }
3067
3068 static void kvm_sched_out(struct preempt_notifier *pn,
3069                           struct task_struct *next)
3070 {
3071         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
3072
3073         kvm_arch_ops->vcpu_put(vcpu);
3074 }
3075
3076 int kvm_init_arch(struct kvm_arch_ops *ops, unsigned int vcpu_size,
3077                   struct module *module)
3078 {
3079         int r;
3080         int cpu;
3081
3082         if (kvm_arch_ops) {
3083                 printk(KERN_ERR "kvm: already loaded the other module\n");
3084                 return -EEXIST;
3085         }
3086
3087         if (!ops->cpu_has_kvm_support()) {
3088                 printk(KERN_ERR "kvm: no hardware support\n");
3089                 return -EOPNOTSUPP;
3090         }
3091         if (ops->disabled_by_bios()) {
3092                 printk(KERN_ERR "kvm: disabled by bios\n");
3093                 return -EOPNOTSUPP;
3094         }
3095
3096         kvm_arch_ops = ops;
3097
3098         r = kvm_arch_ops->hardware_setup();
3099         if (r < 0)
3100                 goto out;
3101
3102         for_each_online_cpu(cpu) {
3103                 smp_call_function_single(cpu,
3104                                 kvm_arch_ops->check_processor_compatibility,
3105                                 &r, 0, 1);
3106                 if (r < 0)
3107                         goto out_free_0;
3108         }
3109
3110         on_each_cpu(hardware_enable, NULL, 0, 1);
3111         r = register_cpu_notifier(&kvm_cpu_notifier);
3112         if (r)
3113                 goto out_free_1;
3114         register_reboot_notifier(&kvm_reboot_notifier);
3115
3116         r = sysdev_class_register(&kvm_sysdev_class);
3117         if (r)
3118                 goto out_free_2;
3119
3120         r = sysdev_register(&kvm_sysdev);
3121         if (r)
3122                 goto out_free_3;
3123
3124         /* A kmem cache lets us meet the alignment requirements of fx_save. */
3125         kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size,
3126                                            __alignof__(struct kvm_vcpu), 0, 0);
3127         if (!kvm_vcpu_cache) {
3128                 r = -ENOMEM;
3129                 goto out_free_4;
3130         }
3131
3132         kvm_chardev_ops.owner = module;
3133
3134         r = misc_register(&kvm_dev);
3135         if (r) {
3136                 printk (KERN_ERR "kvm: misc device register failed\n");
3137                 goto out_free;
3138         }
3139
3140         kvm_preempt_ops.sched_in = kvm_sched_in;
3141         kvm_preempt_ops.sched_out = kvm_sched_out;
3142
3143         return r;
3144
3145 out_free:
3146         kmem_cache_destroy(kvm_vcpu_cache);
3147 out_free_4:
3148         sysdev_unregister(&kvm_sysdev);
3149 out_free_3:
3150         sysdev_class_unregister(&kvm_sysdev_class);
3151 out_free_2:
3152         unregister_reboot_notifier(&kvm_reboot_notifier);
3153         unregister_cpu_notifier(&kvm_cpu_notifier);
3154 out_free_1:
3155         on_each_cpu(hardware_disable, NULL, 0, 1);
3156 out_free_0:
3157         kvm_arch_ops->hardware_unsetup();
3158 out:
3159         kvm_arch_ops = NULL;
3160         return r;
3161 }
3162
3163 void kvm_exit_arch(void)
3164 {
3165         misc_deregister(&kvm_dev);
3166         kmem_cache_destroy(kvm_vcpu_cache);
3167         sysdev_unregister(&kvm_sysdev);
3168         sysdev_class_unregister(&kvm_sysdev_class);
3169         unregister_reboot_notifier(&kvm_reboot_notifier);
3170         unregister_cpu_notifier(&kvm_cpu_notifier);
3171         on_each_cpu(hardware_disable, NULL, 0, 1);
3172         kvm_arch_ops->hardware_unsetup();
3173         kvm_arch_ops = NULL;
3174 }
3175
3176 static __init int kvm_init(void)
3177 {
3178         static struct page *bad_page;
3179         int r;
3180
3181         r = kvm_mmu_module_init();
3182         if (r)
3183                 goto out4;
3184
3185         kvm_init_debug();
3186
3187         kvm_init_msr_list();
3188
3189         if ((bad_page = alloc_page(GFP_KERNEL)) == NULL) {
3190                 r = -ENOMEM;
3191                 goto out;
3192         }
3193
3194         bad_page_address = page_to_pfn(bad_page) << PAGE_SHIFT;
3195         memset(__va(bad_page_address), 0, PAGE_SIZE);
3196
3197         return 0;
3198
3199 out:
3200         kvm_exit_debug();
3201         kvm_mmu_module_exit();
3202 out4:
3203         return r;
3204 }
3205
3206 static __exit void kvm_exit(void)
3207 {
3208         kvm_exit_debug();
3209         __free_page(pfn_to_page(bad_page_address >> PAGE_SHIFT));
3210         kvm_mmu_module_exit();
3211 }
3212
3213 module_init(kvm_init)
3214 module_exit(kvm_exit)
3215
3216 EXPORT_SYMBOL_GPL(kvm_init_arch);
3217 EXPORT_SYMBOL_GPL(kvm_exit_arch);