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