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