6cf042789ad14f74325f21b08be15be57bcc31fb
[linux-2.6.git] / virt / 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 "iodev.h"
19
20 #include <linux/kvm_host.h>
21 #include <linux/kvm.h>
22 #include <linux/module.h>
23 #include <linux/errno.h>
24 #include <linux/percpu.h>
25 #include <linux/gfp.h>
26 #include <linux/mm.h>
27 #include <linux/miscdevice.h>
28 #include <linux/vmalloc.h>
29 #include <linux/reboot.h>
30 #include <linux/debugfs.h>
31 #include <linux/highmem.h>
32 #include <linux/file.h>
33 #include <linux/sysdev.h>
34 #include <linux/cpu.h>
35 #include <linux/sched.h>
36 #include <linux/cpumask.h>
37 #include <linux/smp.h>
38 #include <linux/anon_inodes.h>
39 #include <linux/profile.h>
40 #include <linux/kvm_para.h>
41 #include <linux/pagemap.h>
42 #include <linux/mman.h>
43 #include <linux/swap.h>
44
45 #include <asm/processor.h>
46 #include <asm/io.h>
47 #include <asm/uaccess.h>
48 #include <asm/pgtable.h>
49
50 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
51 #include "coalesced_mmio.h"
52 #endif
53
54 MODULE_AUTHOR("Qumranet");
55 MODULE_LICENSE("GPL");
56
57 DEFINE_SPINLOCK(kvm_lock);
58 LIST_HEAD(vm_list);
59
60 static cpumask_t cpus_hardware_enabled;
61
62 struct kmem_cache *kvm_vcpu_cache;
63 EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
64
65 static __read_mostly struct preempt_ops kvm_preempt_ops;
66
67 struct dentry *kvm_debugfs_dir;
68
69 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
70                            unsigned long arg);
71
72 bool kvm_rebooting;
73
74 static inline int valid_vcpu(int n)
75 {
76         return likely(n >= 0 && n < KVM_MAX_VCPUS);
77 }
78
79 inline int is_mmio_pfn(pfn_t pfn)
80 {
81         if (pfn_valid(pfn))
82                 return PageReserved(pfn_to_page(pfn));
83
84         return true;
85 }
86
87 /*
88  * Switches to specified vcpu, until a matching vcpu_put()
89  */
90 void vcpu_load(struct kvm_vcpu *vcpu)
91 {
92         int cpu;
93
94         mutex_lock(&vcpu->mutex);
95         cpu = get_cpu();
96         preempt_notifier_register(&vcpu->preempt_notifier);
97         kvm_arch_vcpu_load(vcpu, cpu);
98         put_cpu();
99 }
100
101 void vcpu_put(struct kvm_vcpu *vcpu)
102 {
103         preempt_disable();
104         kvm_arch_vcpu_put(vcpu);
105         preempt_notifier_unregister(&vcpu->preempt_notifier);
106         preempt_enable();
107         mutex_unlock(&vcpu->mutex);
108 }
109
110 static void ack_flush(void *_completed)
111 {
112 }
113
114 void kvm_flush_remote_tlbs(struct kvm *kvm)
115 {
116         int i, cpu, me;
117         cpumask_t cpus;
118         struct kvm_vcpu *vcpu;
119
120         me = get_cpu();
121         cpus_clear(cpus);
122         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
123                 vcpu = kvm->vcpus[i];
124                 if (!vcpu)
125                         continue;
126                 if (test_and_set_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
127                         continue;
128                 cpu = vcpu->cpu;
129                 if (cpu != -1 && cpu != me)
130                         cpu_set(cpu, cpus);
131         }
132         if (cpus_empty(cpus))
133                 goto out;
134         ++kvm->stat.remote_tlb_flush;
135         smp_call_function_mask(cpus, ack_flush, NULL, 1);
136 out:
137         put_cpu();
138 }
139
140 void kvm_reload_remote_mmus(struct kvm *kvm)
141 {
142         int i, cpu, me;
143         cpumask_t cpus;
144         struct kvm_vcpu *vcpu;
145
146         me = get_cpu();
147         cpus_clear(cpus);
148         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
149                 vcpu = kvm->vcpus[i];
150                 if (!vcpu)
151                         continue;
152                 if (test_and_set_bit(KVM_REQ_MMU_RELOAD, &vcpu->requests))
153                         continue;
154                 cpu = vcpu->cpu;
155                 if (cpu != -1 && cpu != me)
156                         cpu_set(cpu, cpus);
157         }
158         if (cpus_empty(cpus))
159                 goto out;
160         smp_call_function_mask(cpus, ack_flush, NULL, 1);
161 out:
162         put_cpu();
163 }
164
165
166 int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
167 {
168         struct page *page;
169         int r;
170
171         mutex_init(&vcpu->mutex);
172         vcpu->cpu = -1;
173         vcpu->kvm = kvm;
174         vcpu->vcpu_id = id;
175         init_waitqueue_head(&vcpu->wq);
176
177         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
178         if (!page) {
179                 r = -ENOMEM;
180                 goto fail;
181         }
182         vcpu->run = page_address(page);
183
184         r = kvm_arch_vcpu_init(vcpu);
185         if (r < 0)
186                 goto fail_free_run;
187         return 0;
188
189 fail_free_run:
190         free_page((unsigned long)vcpu->run);
191 fail:
192         return r;
193 }
194 EXPORT_SYMBOL_GPL(kvm_vcpu_init);
195
196 void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
197 {
198         kvm_arch_vcpu_uninit(vcpu);
199         free_page((unsigned long)vcpu->run);
200 }
201 EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
202
203 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
204 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
205 {
206         return container_of(mn, struct kvm, mmu_notifier);
207 }
208
209 static void kvm_mmu_notifier_invalidate_page(struct mmu_notifier *mn,
210                                              struct mm_struct *mm,
211                                              unsigned long address)
212 {
213         struct kvm *kvm = mmu_notifier_to_kvm(mn);
214         int need_tlb_flush;
215
216         /*
217          * When ->invalidate_page runs, the linux pte has been zapped
218          * already but the page is still allocated until
219          * ->invalidate_page returns. So if we increase the sequence
220          * here the kvm page fault will notice if the spte can't be
221          * established because the page is going to be freed. If
222          * instead the kvm page fault establishes the spte before
223          * ->invalidate_page runs, kvm_unmap_hva will release it
224          * before returning.
225          *
226          * The sequence increase only need to be seen at spin_unlock
227          * time, and not at spin_lock time.
228          *
229          * Increasing the sequence after the spin_unlock would be
230          * unsafe because the kvm page fault could then establish the
231          * pte after kvm_unmap_hva returned, without noticing the page
232          * is going to be freed.
233          */
234         spin_lock(&kvm->mmu_lock);
235         kvm->mmu_notifier_seq++;
236         need_tlb_flush = kvm_unmap_hva(kvm, address);
237         spin_unlock(&kvm->mmu_lock);
238
239         /* we've to flush the tlb before the pages can be freed */
240         if (need_tlb_flush)
241                 kvm_flush_remote_tlbs(kvm);
242
243 }
244
245 static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
246                                                     struct mm_struct *mm,
247                                                     unsigned long start,
248                                                     unsigned long end)
249 {
250         struct kvm *kvm = mmu_notifier_to_kvm(mn);
251         int need_tlb_flush = 0;
252
253         spin_lock(&kvm->mmu_lock);
254         /*
255          * The count increase must become visible at unlock time as no
256          * spte can be established without taking the mmu_lock and
257          * count is also read inside the mmu_lock critical section.
258          */
259         kvm->mmu_notifier_count++;
260         for (; start < end; start += PAGE_SIZE)
261                 need_tlb_flush |= kvm_unmap_hva(kvm, start);
262         spin_unlock(&kvm->mmu_lock);
263
264         /* we've to flush the tlb before the pages can be freed */
265         if (need_tlb_flush)
266                 kvm_flush_remote_tlbs(kvm);
267 }
268
269 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
270                                                   struct mm_struct *mm,
271                                                   unsigned long start,
272                                                   unsigned long end)
273 {
274         struct kvm *kvm = mmu_notifier_to_kvm(mn);
275
276         spin_lock(&kvm->mmu_lock);
277         /*
278          * This sequence increase will notify the kvm page fault that
279          * the page that is going to be mapped in the spte could have
280          * been freed.
281          */
282         kvm->mmu_notifier_seq++;
283         /*
284          * The above sequence increase must be visible before the
285          * below count decrease but both values are read by the kvm
286          * page fault under mmu_lock spinlock so we don't need to add
287          * a smb_wmb() here in between the two.
288          */
289         kvm->mmu_notifier_count--;
290         spin_unlock(&kvm->mmu_lock);
291
292         BUG_ON(kvm->mmu_notifier_count < 0);
293 }
294
295 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
296                                               struct mm_struct *mm,
297                                               unsigned long address)
298 {
299         struct kvm *kvm = mmu_notifier_to_kvm(mn);
300         int young;
301
302         spin_lock(&kvm->mmu_lock);
303         young = kvm_age_hva(kvm, address);
304         spin_unlock(&kvm->mmu_lock);
305
306         if (young)
307                 kvm_flush_remote_tlbs(kvm);
308
309         return young;
310 }
311
312 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
313         .invalidate_page        = kvm_mmu_notifier_invalidate_page,
314         .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
315         .invalidate_range_end   = kvm_mmu_notifier_invalidate_range_end,
316         .clear_flush_young      = kvm_mmu_notifier_clear_flush_young,
317 };
318 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
319
320 static struct kvm *kvm_create_vm(void)
321 {
322         struct kvm *kvm = kvm_arch_create_vm();
323 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
324         struct page *page;
325 #endif
326
327         if (IS_ERR(kvm))
328                 goto out;
329
330 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
331         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
332         if (!page) {
333                 kfree(kvm);
334                 return ERR_PTR(-ENOMEM);
335         }
336         kvm->coalesced_mmio_ring =
337                         (struct kvm_coalesced_mmio_ring *)page_address(page);
338 #endif
339
340 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
341         {
342                 int err;
343                 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
344                 err = mmu_notifier_register(&kvm->mmu_notifier, current->mm);
345                 if (err) {
346 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
347                         put_page(page);
348 #endif
349                         kfree(kvm);
350                         return ERR_PTR(err);
351                 }
352         }
353 #endif
354
355         kvm->mm = current->mm;
356         atomic_inc(&kvm->mm->mm_count);
357         spin_lock_init(&kvm->mmu_lock);
358         kvm_io_bus_init(&kvm->pio_bus);
359         mutex_init(&kvm->lock);
360         kvm_io_bus_init(&kvm->mmio_bus);
361         init_rwsem(&kvm->slots_lock);
362         atomic_set(&kvm->users_count, 1);
363         spin_lock(&kvm_lock);
364         list_add(&kvm->vm_list, &vm_list);
365         spin_unlock(&kvm_lock);
366 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
367         kvm_coalesced_mmio_init(kvm);
368 #endif
369 out:
370         return kvm;
371 }
372
373 /*
374  * Free any memory in @free but not in @dont.
375  */
376 static void kvm_free_physmem_slot(struct kvm_memory_slot *free,
377                                   struct kvm_memory_slot *dont)
378 {
379         if (!dont || free->rmap != dont->rmap)
380                 vfree(free->rmap);
381
382         if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
383                 vfree(free->dirty_bitmap);
384
385         if (!dont || free->lpage_info != dont->lpage_info)
386                 vfree(free->lpage_info);
387
388         free->npages = 0;
389         free->dirty_bitmap = NULL;
390         free->rmap = NULL;
391         free->lpage_info = NULL;
392 }
393
394 void kvm_free_physmem(struct kvm *kvm)
395 {
396         int i;
397
398         for (i = 0; i < kvm->nmemslots; ++i)
399                 kvm_free_physmem_slot(&kvm->memslots[i], NULL);
400 }
401
402 static void kvm_destroy_vm(struct kvm *kvm)
403 {
404         struct mm_struct *mm = kvm->mm;
405
406         spin_lock(&kvm_lock);
407         list_del(&kvm->vm_list);
408         spin_unlock(&kvm_lock);
409         kvm_io_bus_destroy(&kvm->pio_bus);
410         kvm_io_bus_destroy(&kvm->mmio_bus);
411 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
412         if (kvm->coalesced_mmio_ring != NULL)
413                 free_page((unsigned long)kvm->coalesced_mmio_ring);
414 #endif
415 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
416         mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
417 #endif
418         kvm_arch_destroy_vm(kvm);
419         mmdrop(mm);
420 }
421
422 void kvm_get_kvm(struct kvm *kvm)
423 {
424         atomic_inc(&kvm->users_count);
425 }
426 EXPORT_SYMBOL_GPL(kvm_get_kvm);
427
428 void kvm_put_kvm(struct kvm *kvm)
429 {
430         if (atomic_dec_and_test(&kvm->users_count))
431                 kvm_destroy_vm(kvm);
432 }
433 EXPORT_SYMBOL_GPL(kvm_put_kvm);
434
435
436 static int kvm_vm_release(struct inode *inode, struct file *filp)
437 {
438         struct kvm *kvm = filp->private_data;
439
440         kvm_put_kvm(kvm);
441         return 0;
442 }
443
444 /*
445  * Allocate some memory and give it an address in the guest physical address
446  * space.
447  *
448  * Discontiguous memory is allowed, mostly for framebuffers.
449  *
450  * Must be called holding mmap_sem for write.
451  */
452 int __kvm_set_memory_region(struct kvm *kvm,
453                             struct kvm_userspace_memory_region *mem,
454                             int user_alloc)
455 {
456         int r;
457         gfn_t base_gfn;
458         unsigned long npages;
459         unsigned long i;
460         struct kvm_memory_slot *memslot;
461         struct kvm_memory_slot old, new;
462
463         r = -EINVAL;
464         /* General sanity checks */
465         if (mem->memory_size & (PAGE_SIZE - 1))
466                 goto out;
467         if (mem->guest_phys_addr & (PAGE_SIZE - 1))
468                 goto out;
469         if (mem->slot >= KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS)
470                 goto out;
471         if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
472                 goto out;
473
474         memslot = &kvm->memslots[mem->slot];
475         base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
476         npages = mem->memory_size >> PAGE_SHIFT;
477
478         if (!npages)
479                 mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
480
481         new = old = *memslot;
482
483         new.base_gfn = base_gfn;
484         new.npages = npages;
485         new.flags = mem->flags;
486
487         /* Disallow changing a memory slot's size. */
488         r = -EINVAL;
489         if (npages && old.npages && npages != old.npages)
490                 goto out_free;
491
492         /* Check for overlaps */
493         r = -EEXIST;
494         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
495                 struct kvm_memory_slot *s = &kvm->memslots[i];
496
497                 if (s == memslot)
498                         continue;
499                 if (!((base_gfn + npages <= s->base_gfn) ||
500                       (base_gfn >= s->base_gfn + s->npages)))
501                         goto out_free;
502         }
503
504         /* Free page dirty bitmap if unneeded */
505         if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
506                 new.dirty_bitmap = NULL;
507
508         r = -ENOMEM;
509
510         /* Allocate if a slot is being created */
511 #ifndef CONFIG_S390
512         if (npages && !new.rmap) {
513                 new.rmap = vmalloc(npages * sizeof(struct page *));
514
515                 if (!new.rmap)
516                         goto out_free;
517
518                 memset(new.rmap, 0, npages * sizeof(*new.rmap));
519
520                 new.user_alloc = user_alloc;
521                 /*
522                  * hva_to_rmmap() serialzies with the mmu_lock and to be
523                  * safe it has to ignore memslots with !user_alloc &&
524                  * !userspace_addr.
525                  */
526                 if (user_alloc)
527                         new.userspace_addr = mem->userspace_addr;
528                 else
529                         new.userspace_addr = 0;
530         }
531         if (npages && !new.lpage_info) {
532                 int largepages = npages / KVM_PAGES_PER_HPAGE;
533                 if (npages % KVM_PAGES_PER_HPAGE)
534                         largepages++;
535                 if (base_gfn % KVM_PAGES_PER_HPAGE)
536                         largepages++;
537
538                 new.lpage_info = vmalloc(largepages * sizeof(*new.lpage_info));
539
540                 if (!new.lpage_info)
541                         goto out_free;
542
543                 memset(new.lpage_info, 0, largepages * sizeof(*new.lpage_info));
544
545                 if (base_gfn % KVM_PAGES_PER_HPAGE)
546                         new.lpage_info[0].write_count = 1;
547                 if ((base_gfn+npages) % KVM_PAGES_PER_HPAGE)
548                         new.lpage_info[largepages-1].write_count = 1;
549         }
550
551         /* Allocate page dirty bitmap if needed */
552         if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
553                 unsigned dirty_bytes = ALIGN(npages, BITS_PER_LONG) / 8;
554
555                 new.dirty_bitmap = vmalloc(dirty_bytes);
556                 if (!new.dirty_bitmap)
557                         goto out_free;
558                 memset(new.dirty_bitmap, 0, dirty_bytes);
559         }
560 #endif /* not defined CONFIG_S390 */
561
562         if (!npages)
563                 kvm_arch_flush_shadow(kvm);
564
565         spin_lock(&kvm->mmu_lock);
566         if (mem->slot >= kvm->nmemslots)
567                 kvm->nmemslots = mem->slot + 1;
568
569         *memslot = new;
570         spin_unlock(&kvm->mmu_lock);
571
572         r = kvm_arch_set_memory_region(kvm, mem, old, user_alloc);
573         if (r) {
574                 spin_lock(&kvm->mmu_lock);
575                 *memslot = old;
576                 spin_unlock(&kvm->mmu_lock);
577                 goto out_free;
578         }
579
580         kvm_free_physmem_slot(&old, &new);
581
582         /* map the pages in iommu page table */
583         r = kvm_iommu_map_pages(kvm, base_gfn, npages);
584         if (r)
585                 goto out;
586
587         return 0;
588
589 out_free:
590         kvm_free_physmem_slot(&new, &old);
591 out:
592         return r;
593
594 }
595 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
596
597 int kvm_set_memory_region(struct kvm *kvm,
598                           struct kvm_userspace_memory_region *mem,
599                           int user_alloc)
600 {
601         int r;
602
603         down_write(&kvm->slots_lock);
604         r = __kvm_set_memory_region(kvm, mem, user_alloc);
605         up_write(&kvm->slots_lock);
606         return r;
607 }
608 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
609
610 int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
611                                    struct
612                                    kvm_userspace_memory_region *mem,
613                                    int user_alloc)
614 {
615         if (mem->slot >= KVM_MEMORY_SLOTS)
616                 return -EINVAL;
617         return kvm_set_memory_region(kvm, mem, user_alloc);
618 }
619
620 int kvm_get_dirty_log(struct kvm *kvm,
621                         struct kvm_dirty_log *log, int *is_dirty)
622 {
623         struct kvm_memory_slot *memslot;
624         int r, i;
625         int n;
626         unsigned long any = 0;
627
628         r = -EINVAL;
629         if (log->slot >= KVM_MEMORY_SLOTS)
630                 goto out;
631
632         memslot = &kvm->memslots[log->slot];
633         r = -ENOENT;
634         if (!memslot->dirty_bitmap)
635                 goto out;
636
637         n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
638
639         for (i = 0; !any && i < n/sizeof(long); ++i)
640                 any = memslot->dirty_bitmap[i];
641
642         r = -EFAULT;
643         if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
644                 goto out;
645
646         if (any)
647                 *is_dirty = 1;
648
649         r = 0;
650 out:
651         return r;
652 }
653
654 int is_error_page(struct page *page)
655 {
656         return page == bad_page;
657 }
658 EXPORT_SYMBOL_GPL(is_error_page);
659
660 int is_error_pfn(pfn_t pfn)
661 {
662         return pfn == bad_pfn;
663 }
664 EXPORT_SYMBOL_GPL(is_error_pfn);
665
666 static inline unsigned long bad_hva(void)
667 {
668         return PAGE_OFFSET;
669 }
670
671 int kvm_is_error_hva(unsigned long addr)
672 {
673         return addr == bad_hva();
674 }
675 EXPORT_SYMBOL_GPL(kvm_is_error_hva);
676
677 static struct kvm_memory_slot *__gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
678 {
679         int i;
680
681         for (i = 0; i < kvm->nmemslots; ++i) {
682                 struct kvm_memory_slot *memslot = &kvm->memslots[i];
683
684                 if (gfn >= memslot->base_gfn
685                     && gfn < memslot->base_gfn + memslot->npages)
686                         return memslot;
687         }
688         return NULL;
689 }
690
691 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
692 {
693         gfn = unalias_gfn(kvm, gfn);
694         return __gfn_to_memslot(kvm, gfn);
695 }
696
697 int kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
698 {
699         int i;
700
701         gfn = unalias_gfn(kvm, gfn);
702         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
703                 struct kvm_memory_slot *memslot = &kvm->memslots[i];
704
705                 if (gfn >= memslot->base_gfn
706                     && gfn < memslot->base_gfn + memslot->npages)
707                         return 1;
708         }
709         return 0;
710 }
711 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
712
713 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
714 {
715         struct kvm_memory_slot *slot;
716
717         gfn = unalias_gfn(kvm, gfn);
718         slot = __gfn_to_memslot(kvm, gfn);
719         if (!slot)
720                 return bad_hva();
721         return (slot->userspace_addr + (gfn - slot->base_gfn) * PAGE_SIZE);
722 }
723 EXPORT_SYMBOL_GPL(gfn_to_hva);
724
725 pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
726 {
727         struct page *page[1];
728         unsigned long addr;
729         int npages;
730         pfn_t pfn;
731
732         might_sleep();
733
734         addr = gfn_to_hva(kvm, gfn);
735         if (kvm_is_error_hva(addr)) {
736                 get_page(bad_page);
737                 return page_to_pfn(bad_page);
738         }
739
740         npages = get_user_pages_fast(addr, 1, 1, page);
741
742         if (unlikely(npages != 1)) {
743                 struct vm_area_struct *vma;
744
745                 down_read(&current->mm->mmap_sem);
746                 vma = find_vma(current->mm, addr);
747
748                 if (vma == NULL || addr < vma->vm_start ||
749                     !(vma->vm_flags & VM_PFNMAP)) {
750                         up_read(&current->mm->mmap_sem);
751                         get_page(bad_page);
752                         return page_to_pfn(bad_page);
753                 }
754
755                 pfn = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
756                 up_read(&current->mm->mmap_sem);
757                 BUG_ON(!is_mmio_pfn(pfn));
758         } else
759                 pfn = page_to_pfn(page[0]);
760
761         return pfn;
762 }
763
764 EXPORT_SYMBOL_GPL(gfn_to_pfn);
765
766 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
767 {
768         pfn_t pfn;
769
770         pfn = gfn_to_pfn(kvm, gfn);
771         if (!is_mmio_pfn(pfn))
772                 return pfn_to_page(pfn);
773
774         WARN_ON(is_mmio_pfn(pfn));
775
776         get_page(bad_page);
777         return bad_page;
778 }
779
780 EXPORT_SYMBOL_GPL(gfn_to_page);
781
782 void kvm_release_page_clean(struct page *page)
783 {
784         kvm_release_pfn_clean(page_to_pfn(page));
785 }
786 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
787
788 void kvm_release_pfn_clean(pfn_t pfn)
789 {
790         if (!is_mmio_pfn(pfn))
791                 put_page(pfn_to_page(pfn));
792 }
793 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
794
795 void kvm_release_page_dirty(struct page *page)
796 {
797         kvm_release_pfn_dirty(page_to_pfn(page));
798 }
799 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
800
801 void kvm_release_pfn_dirty(pfn_t pfn)
802 {
803         kvm_set_pfn_dirty(pfn);
804         kvm_release_pfn_clean(pfn);
805 }
806 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
807
808 void kvm_set_page_dirty(struct page *page)
809 {
810         kvm_set_pfn_dirty(page_to_pfn(page));
811 }
812 EXPORT_SYMBOL_GPL(kvm_set_page_dirty);
813
814 void kvm_set_pfn_dirty(pfn_t pfn)
815 {
816         if (!is_mmio_pfn(pfn)) {
817                 struct page *page = pfn_to_page(pfn);
818                 if (!PageReserved(page))
819                         SetPageDirty(page);
820         }
821 }
822 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
823
824 void kvm_set_pfn_accessed(pfn_t pfn)
825 {
826         if (!is_mmio_pfn(pfn))
827                 mark_page_accessed(pfn_to_page(pfn));
828 }
829 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
830
831 void kvm_get_pfn(pfn_t pfn)
832 {
833         if (!is_mmio_pfn(pfn))
834                 get_page(pfn_to_page(pfn));
835 }
836 EXPORT_SYMBOL_GPL(kvm_get_pfn);
837
838 static int next_segment(unsigned long len, int offset)
839 {
840         if (len > PAGE_SIZE - offset)
841                 return PAGE_SIZE - offset;
842         else
843                 return len;
844 }
845
846 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
847                         int len)
848 {
849         int r;
850         unsigned long addr;
851
852         addr = gfn_to_hva(kvm, gfn);
853         if (kvm_is_error_hva(addr))
854                 return -EFAULT;
855         r = copy_from_user(data, (void __user *)addr + offset, len);
856         if (r)
857                 return -EFAULT;
858         return 0;
859 }
860 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
861
862 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
863 {
864         gfn_t gfn = gpa >> PAGE_SHIFT;
865         int seg;
866         int offset = offset_in_page(gpa);
867         int ret;
868
869         while ((seg = next_segment(len, offset)) != 0) {
870                 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
871                 if (ret < 0)
872                         return ret;
873                 offset = 0;
874                 len -= seg;
875                 data += seg;
876                 ++gfn;
877         }
878         return 0;
879 }
880 EXPORT_SYMBOL_GPL(kvm_read_guest);
881
882 int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
883                           unsigned long len)
884 {
885         int r;
886         unsigned long addr;
887         gfn_t gfn = gpa >> PAGE_SHIFT;
888         int offset = offset_in_page(gpa);
889
890         addr = gfn_to_hva(kvm, gfn);
891         if (kvm_is_error_hva(addr))
892                 return -EFAULT;
893         pagefault_disable();
894         r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
895         pagefault_enable();
896         if (r)
897                 return -EFAULT;
898         return 0;
899 }
900 EXPORT_SYMBOL(kvm_read_guest_atomic);
901
902 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
903                          int offset, int len)
904 {
905         int r;
906         unsigned long addr;
907
908         addr = gfn_to_hva(kvm, gfn);
909         if (kvm_is_error_hva(addr))
910                 return -EFAULT;
911         r = copy_to_user((void __user *)addr + offset, data, len);
912         if (r)
913                 return -EFAULT;
914         mark_page_dirty(kvm, gfn);
915         return 0;
916 }
917 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
918
919 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
920                     unsigned long len)
921 {
922         gfn_t gfn = gpa >> PAGE_SHIFT;
923         int seg;
924         int offset = offset_in_page(gpa);
925         int ret;
926
927         while ((seg = next_segment(len, offset)) != 0) {
928                 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
929                 if (ret < 0)
930                         return ret;
931                 offset = 0;
932                 len -= seg;
933                 data += seg;
934                 ++gfn;
935         }
936         return 0;
937 }
938
939 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
940 {
941         return kvm_write_guest_page(kvm, gfn, empty_zero_page, offset, len);
942 }
943 EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
944
945 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
946 {
947         gfn_t gfn = gpa >> PAGE_SHIFT;
948         int seg;
949         int offset = offset_in_page(gpa);
950         int ret;
951
952         while ((seg = next_segment(len, offset)) != 0) {
953                 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
954                 if (ret < 0)
955                         return ret;
956                 offset = 0;
957                 len -= seg;
958                 ++gfn;
959         }
960         return 0;
961 }
962 EXPORT_SYMBOL_GPL(kvm_clear_guest);
963
964 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
965 {
966         struct kvm_memory_slot *memslot;
967
968         gfn = unalias_gfn(kvm, gfn);
969         memslot = __gfn_to_memslot(kvm, gfn);
970         if (memslot && memslot->dirty_bitmap) {
971                 unsigned long rel_gfn = gfn - memslot->base_gfn;
972
973                 /* avoid RMW */
974                 if (!test_bit(rel_gfn, memslot->dirty_bitmap))
975                         set_bit(rel_gfn, memslot->dirty_bitmap);
976         }
977 }
978
979 /*
980  * The vCPU has executed a HLT instruction with in-kernel mode enabled.
981  */
982 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
983 {
984         DEFINE_WAIT(wait);
985
986         for (;;) {
987                 prepare_to_wait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
988
989                 if (kvm_cpu_has_interrupt(vcpu) ||
990                     kvm_cpu_has_pending_timer(vcpu) ||
991                     kvm_arch_vcpu_runnable(vcpu)) {
992                         set_bit(KVM_REQ_UNHALT, &vcpu->requests);
993                         break;
994                 }
995                 if (signal_pending(current))
996                         break;
997
998                 vcpu_put(vcpu);
999                 schedule();
1000                 vcpu_load(vcpu);
1001         }
1002
1003         finish_wait(&vcpu->wq, &wait);
1004 }
1005
1006 void kvm_resched(struct kvm_vcpu *vcpu)
1007 {
1008         if (!need_resched())
1009                 return;
1010         cond_resched();
1011 }
1012 EXPORT_SYMBOL_GPL(kvm_resched);
1013
1014 static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1015 {
1016         struct kvm_vcpu *vcpu = vma->vm_file->private_data;
1017         struct page *page;
1018
1019         if (vmf->pgoff == 0)
1020                 page = virt_to_page(vcpu->run);
1021 #ifdef CONFIG_X86
1022         else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
1023                 page = virt_to_page(vcpu->arch.pio_data);
1024 #endif
1025 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
1026         else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
1027                 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
1028 #endif
1029         else
1030                 return VM_FAULT_SIGBUS;
1031         get_page(page);
1032         vmf->page = page;
1033         return 0;
1034 }
1035
1036 static struct vm_operations_struct kvm_vcpu_vm_ops = {
1037         .fault = kvm_vcpu_fault,
1038 };
1039
1040 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
1041 {
1042         vma->vm_ops = &kvm_vcpu_vm_ops;
1043         return 0;
1044 }
1045
1046 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
1047 {
1048         struct kvm_vcpu *vcpu = filp->private_data;
1049
1050         kvm_put_kvm(vcpu->kvm);
1051         return 0;
1052 }
1053
1054 static const struct file_operations kvm_vcpu_fops = {
1055         .release        = kvm_vcpu_release,
1056         .unlocked_ioctl = kvm_vcpu_ioctl,
1057         .compat_ioctl   = kvm_vcpu_ioctl,
1058         .mmap           = kvm_vcpu_mmap,
1059 };
1060
1061 /*
1062  * Allocates an inode for the vcpu.
1063  */
1064 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
1065 {
1066         int fd = anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, 0);
1067         if (fd < 0)
1068                 kvm_put_kvm(vcpu->kvm);
1069         return fd;
1070 }
1071
1072 /*
1073  * Creates some virtual cpus.  Good luck creating more than one.
1074  */
1075 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, int n)
1076 {
1077         int r;
1078         struct kvm_vcpu *vcpu;
1079
1080         if (!valid_vcpu(n))
1081                 return -EINVAL;
1082
1083         vcpu = kvm_arch_vcpu_create(kvm, n);
1084         if (IS_ERR(vcpu))
1085                 return PTR_ERR(vcpu);
1086
1087         preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
1088
1089         r = kvm_arch_vcpu_setup(vcpu);
1090         if (r)
1091                 return r;
1092
1093         mutex_lock(&kvm->lock);
1094         if (kvm->vcpus[n]) {
1095                 r = -EEXIST;
1096                 goto vcpu_destroy;
1097         }
1098         kvm->vcpus[n] = vcpu;
1099         mutex_unlock(&kvm->lock);
1100
1101         /* Now it's all set up, let userspace reach it */
1102         kvm_get_kvm(kvm);
1103         r = create_vcpu_fd(vcpu);
1104         if (r < 0)
1105                 goto unlink;
1106         return r;
1107
1108 unlink:
1109         mutex_lock(&kvm->lock);
1110         kvm->vcpus[n] = NULL;
1111 vcpu_destroy:
1112         mutex_unlock(&kvm->lock);
1113         kvm_arch_vcpu_destroy(vcpu);
1114         return r;
1115 }
1116
1117 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
1118 {
1119         if (sigset) {
1120                 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
1121                 vcpu->sigset_active = 1;
1122                 vcpu->sigset = *sigset;
1123         } else
1124                 vcpu->sigset_active = 0;
1125         return 0;
1126 }
1127
1128 static long kvm_vcpu_ioctl(struct file *filp,
1129                            unsigned int ioctl, unsigned long arg)
1130 {
1131         struct kvm_vcpu *vcpu = filp->private_data;
1132         void __user *argp = (void __user *)arg;
1133         int r;
1134         struct kvm_fpu *fpu = NULL;
1135         struct kvm_sregs *kvm_sregs = NULL;
1136
1137         if (vcpu->kvm->mm != current->mm)
1138                 return -EIO;
1139         switch (ioctl) {
1140         case KVM_RUN:
1141                 r = -EINVAL;
1142                 if (arg)
1143                         goto out;
1144                 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
1145                 break;
1146         case KVM_GET_REGS: {
1147                 struct kvm_regs *kvm_regs;
1148
1149                 r = -ENOMEM;
1150                 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
1151                 if (!kvm_regs)
1152                         goto out;
1153                 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
1154                 if (r)
1155                         goto out_free1;
1156                 r = -EFAULT;
1157                 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
1158                         goto out_free1;
1159                 r = 0;
1160 out_free1:
1161                 kfree(kvm_regs);
1162                 break;
1163         }
1164         case KVM_SET_REGS: {
1165                 struct kvm_regs *kvm_regs;
1166
1167                 r = -ENOMEM;
1168                 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
1169                 if (!kvm_regs)
1170                         goto out;
1171                 r = -EFAULT;
1172                 if (copy_from_user(kvm_regs, argp, sizeof(struct kvm_regs)))
1173                         goto out_free2;
1174                 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
1175                 if (r)
1176                         goto out_free2;
1177                 r = 0;
1178 out_free2:
1179                 kfree(kvm_regs);
1180                 break;
1181         }
1182         case KVM_GET_SREGS: {
1183                 kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
1184                 r = -ENOMEM;
1185                 if (!kvm_sregs)
1186                         goto out;
1187                 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
1188                 if (r)
1189                         goto out;
1190                 r = -EFAULT;
1191                 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
1192                         goto out;
1193                 r = 0;
1194                 break;
1195         }
1196         case KVM_SET_SREGS: {
1197                 kvm_sregs = kmalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
1198                 r = -ENOMEM;
1199                 if (!kvm_sregs)
1200                         goto out;
1201                 r = -EFAULT;
1202                 if (copy_from_user(kvm_sregs, argp, sizeof(struct kvm_sregs)))
1203                         goto out;
1204                 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
1205                 if (r)
1206                         goto out;
1207                 r = 0;
1208                 break;
1209         }
1210         case KVM_GET_MP_STATE: {
1211                 struct kvm_mp_state mp_state;
1212
1213                 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
1214                 if (r)
1215                         goto out;
1216                 r = -EFAULT;
1217                 if (copy_to_user(argp, &mp_state, sizeof mp_state))
1218                         goto out;
1219                 r = 0;
1220                 break;
1221         }
1222         case KVM_SET_MP_STATE: {
1223                 struct kvm_mp_state mp_state;
1224
1225                 r = -EFAULT;
1226                 if (copy_from_user(&mp_state, argp, sizeof mp_state))
1227                         goto out;
1228                 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
1229                 if (r)
1230                         goto out;
1231                 r = 0;
1232                 break;
1233         }
1234         case KVM_TRANSLATE: {
1235                 struct kvm_translation tr;
1236
1237                 r = -EFAULT;
1238                 if (copy_from_user(&tr, argp, sizeof tr))
1239                         goto out;
1240                 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
1241                 if (r)
1242                         goto out;
1243                 r = -EFAULT;
1244                 if (copy_to_user(argp, &tr, sizeof tr))
1245                         goto out;
1246                 r = 0;
1247                 break;
1248         }
1249         case KVM_DEBUG_GUEST: {
1250                 struct kvm_debug_guest dbg;
1251
1252                 r = -EFAULT;
1253                 if (copy_from_user(&dbg, argp, sizeof dbg))
1254                         goto out;
1255                 r = kvm_arch_vcpu_ioctl_debug_guest(vcpu, &dbg);
1256                 if (r)
1257                         goto out;
1258                 r = 0;
1259                 break;
1260         }
1261         case KVM_SET_SIGNAL_MASK: {
1262                 struct kvm_signal_mask __user *sigmask_arg = argp;
1263                 struct kvm_signal_mask kvm_sigmask;
1264                 sigset_t sigset, *p;
1265
1266                 p = NULL;
1267                 if (argp) {
1268                         r = -EFAULT;
1269                         if (copy_from_user(&kvm_sigmask, argp,
1270                                            sizeof kvm_sigmask))
1271                                 goto out;
1272                         r = -EINVAL;
1273                         if (kvm_sigmask.len != sizeof sigset)
1274                                 goto out;
1275                         r = -EFAULT;
1276                         if (copy_from_user(&sigset, sigmask_arg->sigset,
1277                                            sizeof sigset))
1278                                 goto out;
1279                         p = &sigset;
1280                 }
1281                 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
1282                 break;
1283         }
1284         case KVM_GET_FPU: {
1285                 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
1286                 r = -ENOMEM;
1287                 if (!fpu)
1288                         goto out;
1289                 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
1290                 if (r)
1291                         goto out;
1292                 r = -EFAULT;
1293                 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
1294                         goto out;
1295                 r = 0;
1296                 break;
1297         }
1298         case KVM_SET_FPU: {
1299                 fpu = kmalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
1300                 r = -ENOMEM;
1301                 if (!fpu)
1302                         goto out;
1303                 r = -EFAULT;
1304                 if (copy_from_user(fpu, argp, sizeof(struct kvm_fpu)))
1305                         goto out;
1306                 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
1307                 if (r)
1308                         goto out;
1309                 r = 0;
1310                 break;
1311         }
1312         default:
1313                 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
1314         }
1315 out:
1316         kfree(fpu);
1317         kfree(kvm_sregs);
1318         return r;
1319 }
1320
1321 static long kvm_vm_ioctl(struct file *filp,
1322                            unsigned int ioctl, unsigned long arg)
1323 {
1324         struct kvm *kvm = filp->private_data;
1325         void __user *argp = (void __user *)arg;
1326         int r;
1327
1328         if (kvm->mm != current->mm)
1329                 return -EIO;
1330         switch (ioctl) {
1331         case KVM_CREATE_VCPU:
1332                 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
1333                 if (r < 0)
1334                         goto out;
1335                 break;
1336         case KVM_SET_USER_MEMORY_REGION: {
1337                 struct kvm_userspace_memory_region kvm_userspace_mem;
1338
1339                 r = -EFAULT;
1340                 if (copy_from_user(&kvm_userspace_mem, argp,
1341                                                 sizeof kvm_userspace_mem))
1342                         goto out;
1343
1344                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 1);
1345                 if (r)
1346                         goto out;
1347                 break;
1348         }
1349         case KVM_GET_DIRTY_LOG: {
1350                 struct kvm_dirty_log log;
1351
1352                 r = -EFAULT;
1353                 if (copy_from_user(&log, argp, sizeof log))
1354                         goto out;
1355                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
1356                 if (r)
1357                         goto out;
1358                 break;
1359         }
1360 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
1361         case KVM_REGISTER_COALESCED_MMIO: {
1362                 struct kvm_coalesced_mmio_zone zone;
1363                 r = -EFAULT;
1364                 if (copy_from_user(&zone, argp, sizeof zone))
1365                         goto out;
1366                 r = -ENXIO;
1367                 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
1368                 if (r)
1369                         goto out;
1370                 r = 0;
1371                 break;
1372         }
1373         case KVM_UNREGISTER_COALESCED_MMIO: {
1374                 struct kvm_coalesced_mmio_zone zone;
1375                 r = -EFAULT;
1376                 if (copy_from_user(&zone, argp, sizeof zone))
1377                         goto out;
1378                 r = -ENXIO;
1379                 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
1380                 if (r)
1381                         goto out;
1382                 r = 0;
1383                 break;
1384         }
1385 #endif
1386         default:
1387                 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
1388         }
1389 out:
1390         return r;
1391 }
1392
1393 static int kvm_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1394 {
1395         struct page *page[1];
1396         unsigned long addr;
1397         int npages;
1398         gfn_t gfn = vmf->pgoff;
1399         struct kvm *kvm = vma->vm_file->private_data;
1400
1401         addr = gfn_to_hva(kvm, gfn);
1402         if (kvm_is_error_hva(addr))
1403                 return VM_FAULT_SIGBUS;
1404
1405         npages = get_user_pages(current, current->mm, addr, 1, 1, 0, page,
1406                                 NULL);
1407         if (unlikely(npages != 1))
1408                 return VM_FAULT_SIGBUS;
1409
1410         vmf->page = page[0];
1411         return 0;
1412 }
1413
1414 static struct vm_operations_struct kvm_vm_vm_ops = {
1415         .fault = kvm_vm_fault,
1416 };
1417
1418 static int kvm_vm_mmap(struct file *file, struct vm_area_struct *vma)
1419 {
1420         vma->vm_ops = &kvm_vm_vm_ops;
1421         return 0;
1422 }
1423
1424 static const struct file_operations kvm_vm_fops = {
1425         .release        = kvm_vm_release,
1426         .unlocked_ioctl = kvm_vm_ioctl,
1427         .compat_ioctl   = kvm_vm_ioctl,
1428         .mmap           = kvm_vm_mmap,
1429 };
1430
1431 static int kvm_dev_ioctl_create_vm(void)
1432 {
1433         int fd;
1434         struct kvm *kvm;
1435
1436         kvm = kvm_create_vm();
1437         if (IS_ERR(kvm))
1438                 return PTR_ERR(kvm);
1439         fd = anon_inode_getfd("kvm-vm", &kvm_vm_fops, kvm, 0);
1440         if (fd < 0)
1441                 kvm_put_kvm(kvm);
1442
1443         return fd;
1444 }
1445
1446 static long kvm_dev_ioctl(struct file *filp,
1447                           unsigned int ioctl, unsigned long arg)
1448 {
1449         long r = -EINVAL;
1450
1451         switch (ioctl) {
1452         case KVM_GET_API_VERSION:
1453                 r = -EINVAL;
1454                 if (arg)
1455                         goto out;
1456                 r = KVM_API_VERSION;
1457                 break;
1458         case KVM_CREATE_VM:
1459                 r = -EINVAL;
1460                 if (arg)
1461                         goto out;
1462                 r = kvm_dev_ioctl_create_vm();
1463                 break;
1464         case KVM_CHECK_EXTENSION:
1465                 r = kvm_dev_ioctl_check_extension(arg);
1466                 break;
1467         case KVM_GET_VCPU_MMAP_SIZE:
1468                 r = -EINVAL;
1469                 if (arg)
1470                         goto out;
1471                 r = PAGE_SIZE;     /* struct kvm_run */
1472 #ifdef CONFIG_X86
1473                 r += PAGE_SIZE;    /* pio data page */
1474 #endif
1475 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
1476                 r += PAGE_SIZE;    /* coalesced mmio ring page */
1477 #endif
1478                 break;
1479         case KVM_TRACE_ENABLE:
1480         case KVM_TRACE_PAUSE:
1481         case KVM_TRACE_DISABLE:
1482                 r = kvm_trace_ioctl(ioctl, arg);
1483                 break;
1484         default:
1485                 return kvm_arch_dev_ioctl(filp, ioctl, arg);
1486         }
1487 out:
1488         return r;
1489 }
1490
1491 static struct file_operations kvm_chardev_ops = {
1492         .unlocked_ioctl = kvm_dev_ioctl,
1493         .compat_ioctl   = kvm_dev_ioctl,
1494 };
1495
1496 static struct miscdevice kvm_dev = {
1497         KVM_MINOR,
1498         "kvm",
1499         &kvm_chardev_ops,
1500 };
1501
1502 static void hardware_enable(void *junk)
1503 {
1504         int cpu = raw_smp_processor_id();
1505
1506         if (cpu_isset(cpu, cpus_hardware_enabled))
1507                 return;
1508         cpu_set(cpu, cpus_hardware_enabled);
1509         kvm_arch_hardware_enable(NULL);
1510 }
1511
1512 static void hardware_disable(void *junk)
1513 {
1514         int cpu = raw_smp_processor_id();
1515
1516         if (!cpu_isset(cpu, cpus_hardware_enabled))
1517                 return;
1518         cpu_clear(cpu, cpus_hardware_enabled);
1519         kvm_arch_hardware_disable(NULL);
1520 }
1521
1522 static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
1523                            void *v)
1524 {
1525         int cpu = (long)v;
1526
1527         val &= ~CPU_TASKS_FROZEN;
1528         switch (val) {
1529         case CPU_DYING:
1530                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
1531                        cpu);
1532                 hardware_disable(NULL);
1533                 break;
1534         case CPU_UP_CANCELED:
1535                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
1536                        cpu);
1537                 smp_call_function_single(cpu, hardware_disable, NULL, 1);
1538                 break;
1539         case CPU_ONLINE:
1540                 printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
1541                        cpu);
1542                 smp_call_function_single(cpu, hardware_enable, NULL, 1);
1543                 break;
1544         }
1545         return NOTIFY_OK;
1546 }
1547
1548
1549 asmlinkage void kvm_handle_fault_on_reboot(void)
1550 {
1551         if (kvm_rebooting)
1552                 /* spin while reset goes on */
1553                 while (true)
1554                         ;
1555         /* Fault while not rebooting.  We want the trace. */
1556         BUG();
1557 }
1558 EXPORT_SYMBOL_GPL(kvm_handle_fault_on_reboot);
1559
1560 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
1561                       void *v)
1562 {
1563         if (val == SYS_RESTART) {
1564                 /*
1565                  * Some (well, at least mine) BIOSes hang on reboot if
1566                  * in vmx root mode.
1567                  */
1568                 printk(KERN_INFO "kvm: exiting hardware virtualization\n");
1569                 kvm_rebooting = true;
1570                 on_each_cpu(hardware_disable, NULL, 1);
1571         }
1572         return NOTIFY_OK;
1573 }
1574
1575 static struct notifier_block kvm_reboot_notifier = {
1576         .notifier_call = kvm_reboot,
1577         .priority = 0,
1578 };
1579
1580 void kvm_io_bus_init(struct kvm_io_bus *bus)
1581 {
1582         memset(bus, 0, sizeof(*bus));
1583 }
1584
1585 void kvm_io_bus_destroy(struct kvm_io_bus *bus)
1586 {
1587         int i;
1588
1589         for (i = 0; i < bus->dev_count; i++) {
1590                 struct kvm_io_device *pos = bus->devs[i];
1591
1592                 kvm_iodevice_destructor(pos);
1593         }
1594 }
1595
1596 struct kvm_io_device *kvm_io_bus_find_dev(struct kvm_io_bus *bus,
1597                                           gpa_t addr, int len, int is_write)
1598 {
1599         int i;
1600
1601         for (i = 0; i < bus->dev_count; i++) {
1602                 struct kvm_io_device *pos = bus->devs[i];
1603
1604                 if (pos->in_range(pos, addr, len, is_write))
1605                         return pos;
1606         }
1607
1608         return NULL;
1609 }
1610
1611 void kvm_io_bus_register_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev)
1612 {
1613         BUG_ON(bus->dev_count > (NR_IOBUS_DEVS-1));
1614
1615         bus->devs[bus->dev_count++] = dev;
1616 }
1617
1618 static struct notifier_block kvm_cpu_notifier = {
1619         .notifier_call = kvm_cpu_hotplug,
1620         .priority = 20, /* must be > scheduler priority */
1621 };
1622
1623 static int vm_stat_get(void *_offset, u64 *val)
1624 {
1625         unsigned offset = (long)_offset;
1626         struct kvm *kvm;
1627
1628         *val = 0;
1629         spin_lock(&kvm_lock);
1630         list_for_each_entry(kvm, &vm_list, vm_list)
1631                 *val += *(u32 *)((void *)kvm + offset);
1632         spin_unlock(&kvm_lock);
1633         return 0;
1634 }
1635
1636 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
1637
1638 static int vcpu_stat_get(void *_offset, u64 *val)
1639 {
1640         unsigned offset = (long)_offset;
1641         struct kvm *kvm;
1642         struct kvm_vcpu *vcpu;
1643         int i;
1644
1645         *val = 0;
1646         spin_lock(&kvm_lock);
1647         list_for_each_entry(kvm, &vm_list, vm_list)
1648                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
1649                         vcpu = kvm->vcpus[i];
1650                         if (vcpu)
1651                                 *val += *(u32 *)((void *)vcpu + offset);
1652                 }
1653         spin_unlock(&kvm_lock);
1654         return 0;
1655 }
1656
1657 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
1658
1659 static struct file_operations *stat_fops[] = {
1660         [KVM_STAT_VCPU] = &vcpu_stat_fops,
1661         [KVM_STAT_VM]   = &vm_stat_fops,
1662 };
1663
1664 static void kvm_init_debug(void)
1665 {
1666         struct kvm_stats_debugfs_item *p;
1667
1668         kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
1669         for (p = debugfs_entries; p->name; ++p)
1670                 p->dentry = debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
1671                                                 (void *)(long)p->offset,
1672                                                 stat_fops[p->kind]);
1673 }
1674
1675 static void kvm_exit_debug(void)
1676 {
1677         struct kvm_stats_debugfs_item *p;
1678
1679         for (p = debugfs_entries; p->name; ++p)
1680                 debugfs_remove(p->dentry);
1681         debugfs_remove(kvm_debugfs_dir);
1682 }
1683
1684 static int kvm_suspend(struct sys_device *dev, pm_message_t state)
1685 {
1686         hardware_disable(NULL);
1687         return 0;
1688 }
1689
1690 static int kvm_resume(struct sys_device *dev)
1691 {
1692         hardware_enable(NULL);
1693         return 0;
1694 }
1695
1696 static struct sysdev_class kvm_sysdev_class = {
1697         .name = "kvm",
1698         .suspend = kvm_suspend,
1699         .resume = kvm_resume,
1700 };
1701
1702 static struct sys_device kvm_sysdev = {
1703         .id = 0,
1704         .cls = &kvm_sysdev_class,
1705 };
1706
1707 struct page *bad_page;
1708 pfn_t bad_pfn;
1709
1710 static inline
1711 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
1712 {
1713         return container_of(pn, struct kvm_vcpu, preempt_notifier);
1714 }
1715
1716 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
1717 {
1718         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
1719
1720         kvm_arch_vcpu_load(vcpu, cpu);
1721 }
1722
1723 static void kvm_sched_out(struct preempt_notifier *pn,
1724                           struct task_struct *next)
1725 {
1726         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
1727
1728         kvm_arch_vcpu_put(vcpu);
1729 }
1730
1731 int kvm_init(void *opaque, unsigned int vcpu_size,
1732                   struct module *module)
1733 {
1734         int r;
1735         int cpu;
1736
1737         kvm_init_debug();
1738
1739         r = kvm_arch_init(opaque);
1740         if (r)
1741                 goto out_fail;
1742
1743         bad_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
1744
1745         if (bad_page == NULL) {
1746                 r = -ENOMEM;
1747                 goto out;
1748         }
1749
1750         bad_pfn = page_to_pfn(bad_page);
1751
1752         r = kvm_arch_hardware_setup();
1753         if (r < 0)
1754                 goto out_free_0;
1755
1756         for_each_online_cpu(cpu) {
1757                 smp_call_function_single(cpu,
1758                                 kvm_arch_check_processor_compat,
1759                                 &r, 1);
1760                 if (r < 0)
1761                         goto out_free_1;
1762         }
1763
1764         on_each_cpu(hardware_enable, NULL, 1);
1765         r = register_cpu_notifier(&kvm_cpu_notifier);
1766         if (r)
1767                 goto out_free_2;
1768         register_reboot_notifier(&kvm_reboot_notifier);
1769
1770         r = sysdev_class_register(&kvm_sysdev_class);
1771         if (r)
1772                 goto out_free_3;
1773
1774         r = sysdev_register(&kvm_sysdev);
1775         if (r)
1776                 goto out_free_4;
1777
1778         /* A kmem cache lets us meet the alignment requirements of fx_save. */
1779         kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size,
1780                                            __alignof__(struct kvm_vcpu),
1781                                            0, NULL);
1782         if (!kvm_vcpu_cache) {
1783                 r = -ENOMEM;
1784                 goto out_free_5;
1785         }
1786
1787         kvm_chardev_ops.owner = module;
1788
1789         r = misc_register(&kvm_dev);
1790         if (r) {
1791                 printk(KERN_ERR "kvm: misc device register failed\n");
1792                 goto out_free;
1793         }
1794
1795         kvm_preempt_ops.sched_in = kvm_sched_in;
1796         kvm_preempt_ops.sched_out = kvm_sched_out;
1797
1798         return 0;
1799
1800 out_free:
1801         kmem_cache_destroy(kvm_vcpu_cache);
1802 out_free_5:
1803         sysdev_unregister(&kvm_sysdev);
1804 out_free_4:
1805         sysdev_class_unregister(&kvm_sysdev_class);
1806 out_free_3:
1807         unregister_reboot_notifier(&kvm_reboot_notifier);
1808         unregister_cpu_notifier(&kvm_cpu_notifier);
1809 out_free_2:
1810         on_each_cpu(hardware_disable, NULL, 1);
1811 out_free_1:
1812         kvm_arch_hardware_unsetup();
1813 out_free_0:
1814         __free_page(bad_page);
1815 out:
1816         kvm_arch_exit();
1817         kvm_exit_debug();
1818 out_fail:
1819         return r;
1820 }
1821 EXPORT_SYMBOL_GPL(kvm_init);
1822
1823 void kvm_exit(void)
1824 {
1825         kvm_trace_cleanup();
1826         misc_deregister(&kvm_dev);
1827         kmem_cache_destroy(kvm_vcpu_cache);
1828         sysdev_unregister(&kvm_sysdev);
1829         sysdev_class_unregister(&kvm_sysdev_class);
1830         unregister_reboot_notifier(&kvm_reboot_notifier);
1831         unregister_cpu_notifier(&kvm_cpu_notifier);
1832         on_each_cpu(hardware_disable, NULL, 1);
1833         kvm_arch_hardware_unsetup();
1834         kvm_arch_exit();
1835         kvm_exit_debug();
1836         __free_page(bad_page);
1837 }
1838 EXPORT_SYMBOL_GPL(kvm_exit);