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