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