thp: kvm mmu transparent hugepage support
[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  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
9  *
10  * Authors:
11  *   Avi Kivity   <avi@qumranet.com>
12  *   Yaniv Kamay  <yaniv@qumranet.com>
13  *
14  * This work is licensed under the terms of the GNU GPL, version 2.  See
15  * the COPYING file in the top-level directory.
16  *
17  */
18
19 #include "iodev.h"
20
21 #include <linux/kvm_host.h>
22 #include <linux/kvm.h>
23 #include <linux/module.h>
24 #include <linux/errno.h>
25 #include <linux/percpu.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/bitops.h>
45 #include <linux/spinlock.h>
46 #include <linux/compat.h>
47 #include <linux/srcu.h>
48 #include <linux/hugetlb.h>
49 #include <linux/slab.h>
50
51 #include <asm/processor.h>
52 #include <asm/io.h>
53 #include <asm/uaccess.h>
54 #include <asm/pgtable.h>
55 #include <asm-generic/bitops/le.h>
56
57 #include "coalesced_mmio.h"
58 #include "async_pf.h"
59
60 #define CREATE_TRACE_POINTS
61 #include <trace/events/kvm.h>
62
63 MODULE_AUTHOR("Qumranet");
64 MODULE_LICENSE("GPL");
65
66 /*
67  * Ordering of locks:
68  *
69  *              kvm->lock --> kvm->slots_lock --> kvm->irq_lock
70  */
71
72 DEFINE_SPINLOCK(kvm_lock);
73 LIST_HEAD(vm_list);
74
75 static cpumask_var_t cpus_hardware_enabled;
76 static int kvm_usage_count = 0;
77 static atomic_t hardware_enable_failed;
78
79 struct kmem_cache *kvm_vcpu_cache;
80 EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
81
82 static __read_mostly struct preempt_ops kvm_preempt_ops;
83
84 struct dentry *kvm_debugfs_dir;
85
86 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
87                            unsigned long arg);
88 static int hardware_enable_all(void);
89 static void hardware_disable_all(void);
90
91 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
92
93 bool kvm_rebooting;
94 EXPORT_SYMBOL_GPL(kvm_rebooting);
95
96 static bool largepages_enabled = true;
97
98 static struct page *hwpoison_page;
99 static pfn_t hwpoison_pfn;
100
101 static struct page *fault_page;
102 static pfn_t fault_pfn;
103
104 inline int kvm_is_mmio_pfn(pfn_t pfn)
105 {
106         if (pfn_valid(pfn)) {
107                 struct page *head;
108                 struct page *tail = pfn_to_page(pfn);
109                 head = compound_head(tail);
110                 if (head != tail) {
111                         smp_rmb();
112                         /*
113                          * head may be a dangling pointer.
114                          * __split_huge_page_refcount clears PageTail
115                          * before overwriting first_page, so if
116                          * PageTail is still there it means the head
117                          * pointer isn't dangling.
118                          */
119                         if (PageTail(tail)) {
120                                 /*
121                                  * the "head" is not a dangling
122                                  * pointer but the hugepage may have
123                                  * been splitted from under us (and we
124                                  * may not hold a reference count on
125                                  * the head page so it can be reused
126                                  * before we run PageReferenced), so
127                                  * we've to recheck PageTail before
128                                  * returning what we just read.
129                                  */
130                                 int reserved = PageReserved(head);
131                                 smp_rmb();
132                                 if (PageTail(tail))
133                                         return reserved;
134                         }
135                 }
136                 return PageReserved(tail);
137         }
138
139         return true;
140 }
141
142 /*
143  * Switches to specified vcpu, until a matching vcpu_put()
144  */
145 void vcpu_load(struct kvm_vcpu *vcpu)
146 {
147         int cpu;
148
149         mutex_lock(&vcpu->mutex);
150         cpu = get_cpu();
151         preempt_notifier_register(&vcpu->preempt_notifier);
152         kvm_arch_vcpu_load(vcpu, cpu);
153         put_cpu();
154 }
155
156 void vcpu_put(struct kvm_vcpu *vcpu)
157 {
158         preempt_disable();
159         kvm_arch_vcpu_put(vcpu);
160         preempt_notifier_unregister(&vcpu->preempt_notifier);
161         preempt_enable();
162         mutex_unlock(&vcpu->mutex);
163 }
164
165 static void ack_flush(void *_completed)
166 {
167 }
168
169 static bool make_all_cpus_request(struct kvm *kvm, unsigned int req)
170 {
171         int i, cpu, me;
172         cpumask_var_t cpus;
173         bool called = true;
174         struct kvm_vcpu *vcpu;
175
176         zalloc_cpumask_var(&cpus, GFP_ATOMIC);
177
178         raw_spin_lock(&kvm->requests_lock);
179         me = smp_processor_id();
180         kvm_for_each_vcpu(i, vcpu, kvm) {
181                 if (kvm_make_check_request(req, vcpu))
182                         continue;
183                 cpu = vcpu->cpu;
184                 if (cpus != NULL && cpu != -1 && cpu != me)
185                         cpumask_set_cpu(cpu, cpus);
186         }
187         if (unlikely(cpus == NULL))
188                 smp_call_function_many(cpu_online_mask, ack_flush, NULL, 1);
189         else if (!cpumask_empty(cpus))
190                 smp_call_function_many(cpus, ack_flush, NULL, 1);
191         else
192                 called = false;
193         raw_spin_unlock(&kvm->requests_lock);
194         free_cpumask_var(cpus);
195         return called;
196 }
197
198 void kvm_flush_remote_tlbs(struct kvm *kvm)
199 {
200         int dirty_count = kvm->tlbs_dirty;
201
202         smp_mb();
203         if (make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
204                 ++kvm->stat.remote_tlb_flush;
205         cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
206 }
207
208 void kvm_reload_remote_mmus(struct kvm *kvm)
209 {
210         make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
211 }
212
213 int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
214 {
215         struct page *page;
216         int r;
217
218         mutex_init(&vcpu->mutex);
219         vcpu->cpu = -1;
220         vcpu->kvm = kvm;
221         vcpu->vcpu_id = id;
222         init_waitqueue_head(&vcpu->wq);
223         kvm_async_pf_vcpu_init(vcpu);
224
225         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
226         if (!page) {
227                 r = -ENOMEM;
228                 goto fail;
229         }
230         vcpu->run = page_address(page);
231
232         r = kvm_arch_vcpu_init(vcpu);
233         if (r < 0)
234                 goto fail_free_run;
235         return 0;
236
237 fail_free_run:
238         free_page((unsigned long)vcpu->run);
239 fail:
240         return r;
241 }
242 EXPORT_SYMBOL_GPL(kvm_vcpu_init);
243
244 void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
245 {
246         kvm_arch_vcpu_uninit(vcpu);
247         free_page((unsigned long)vcpu->run);
248 }
249 EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
250
251 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
252 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
253 {
254         return container_of(mn, struct kvm, mmu_notifier);
255 }
256
257 static void kvm_mmu_notifier_invalidate_page(struct mmu_notifier *mn,
258                                              struct mm_struct *mm,
259                                              unsigned long address)
260 {
261         struct kvm *kvm = mmu_notifier_to_kvm(mn);
262         int need_tlb_flush, idx;
263
264         /*
265          * When ->invalidate_page runs, the linux pte has been zapped
266          * already but the page is still allocated until
267          * ->invalidate_page returns. So if we increase the sequence
268          * here the kvm page fault will notice if the spte can't be
269          * established because the page is going to be freed. If
270          * instead the kvm page fault establishes the spte before
271          * ->invalidate_page runs, kvm_unmap_hva will release it
272          * before returning.
273          *
274          * The sequence increase only need to be seen at spin_unlock
275          * time, and not at spin_lock time.
276          *
277          * Increasing the sequence after the spin_unlock would be
278          * unsafe because the kvm page fault could then establish the
279          * pte after kvm_unmap_hva returned, without noticing the page
280          * is going to be freed.
281          */
282         idx = srcu_read_lock(&kvm->srcu);
283         spin_lock(&kvm->mmu_lock);
284         kvm->mmu_notifier_seq++;
285         need_tlb_flush = kvm_unmap_hva(kvm, address) | kvm->tlbs_dirty;
286         spin_unlock(&kvm->mmu_lock);
287         srcu_read_unlock(&kvm->srcu, idx);
288
289         /* we've to flush the tlb before the pages can be freed */
290         if (need_tlb_flush)
291                 kvm_flush_remote_tlbs(kvm);
292
293 }
294
295 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
296                                         struct mm_struct *mm,
297                                         unsigned long address,
298                                         pte_t pte)
299 {
300         struct kvm *kvm = mmu_notifier_to_kvm(mn);
301         int idx;
302
303         idx = srcu_read_lock(&kvm->srcu);
304         spin_lock(&kvm->mmu_lock);
305         kvm->mmu_notifier_seq++;
306         kvm_set_spte_hva(kvm, address, pte);
307         spin_unlock(&kvm->mmu_lock);
308         srcu_read_unlock(&kvm->srcu, idx);
309 }
310
311 static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
312                                                     struct mm_struct *mm,
313                                                     unsigned long start,
314                                                     unsigned long end)
315 {
316         struct kvm *kvm = mmu_notifier_to_kvm(mn);
317         int need_tlb_flush = 0, idx;
318
319         idx = srcu_read_lock(&kvm->srcu);
320         spin_lock(&kvm->mmu_lock);
321         /*
322          * The count increase must become visible at unlock time as no
323          * spte can be established without taking the mmu_lock and
324          * count is also read inside the mmu_lock critical section.
325          */
326         kvm->mmu_notifier_count++;
327         for (; start < end; start += PAGE_SIZE)
328                 need_tlb_flush |= kvm_unmap_hva(kvm, start);
329         need_tlb_flush |= kvm->tlbs_dirty;
330         spin_unlock(&kvm->mmu_lock);
331         srcu_read_unlock(&kvm->srcu, idx);
332
333         /* we've to flush the tlb before the pages can be freed */
334         if (need_tlb_flush)
335                 kvm_flush_remote_tlbs(kvm);
336 }
337
338 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
339                                                   struct mm_struct *mm,
340                                                   unsigned long start,
341                                                   unsigned long end)
342 {
343         struct kvm *kvm = mmu_notifier_to_kvm(mn);
344
345         spin_lock(&kvm->mmu_lock);
346         /*
347          * This sequence increase will notify the kvm page fault that
348          * the page that is going to be mapped in the spte could have
349          * been freed.
350          */
351         kvm->mmu_notifier_seq++;
352         /*
353          * The above sequence increase must be visible before the
354          * below count decrease but both values are read by the kvm
355          * page fault under mmu_lock spinlock so we don't need to add
356          * a smb_wmb() here in between the two.
357          */
358         kvm->mmu_notifier_count--;
359         spin_unlock(&kvm->mmu_lock);
360
361         BUG_ON(kvm->mmu_notifier_count < 0);
362 }
363
364 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
365                                               struct mm_struct *mm,
366                                               unsigned long address)
367 {
368         struct kvm *kvm = mmu_notifier_to_kvm(mn);
369         int young, idx;
370
371         idx = srcu_read_lock(&kvm->srcu);
372         spin_lock(&kvm->mmu_lock);
373         young = kvm_age_hva(kvm, address);
374         spin_unlock(&kvm->mmu_lock);
375         srcu_read_unlock(&kvm->srcu, idx);
376
377         if (young)
378                 kvm_flush_remote_tlbs(kvm);
379
380         return young;
381 }
382
383 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
384                                      struct mm_struct *mm)
385 {
386         struct kvm *kvm = mmu_notifier_to_kvm(mn);
387         int idx;
388
389         idx = srcu_read_lock(&kvm->srcu);
390         kvm_arch_flush_shadow(kvm);
391         srcu_read_unlock(&kvm->srcu, idx);
392 }
393
394 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
395         .invalidate_page        = kvm_mmu_notifier_invalidate_page,
396         .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
397         .invalidate_range_end   = kvm_mmu_notifier_invalidate_range_end,
398         .clear_flush_young      = kvm_mmu_notifier_clear_flush_young,
399         .change_pte             = kvm_mmu_notifier_change_pte,
400         .release                = kvm_mmu_notifier_release,
401 };
402
403 static int kvm_init_mmu_notifier(struct kvm *kvm)
404 {
405         kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
406         return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
407 }
408
409 #else  /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
410
411 static int kvm_init_mmu_notifier(struct kvm *kvm)
412 {
413         return 0;
414 }
415
416 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
417
418 static struct kvm *kvm_create_vm(void)
419 {
420         int r, i;
421         struct kvm *kvm = kvm_arch_alloc_vm();
422
423         if (!kvm)
424                 return ERR_PTR(-ENOMEM);
425
426         r = kvm_arch_init_vm(kvm);
427         if (r)
428                 goto out_err_nodisable;
429
430         r = hardware_enable_all();
431         if (r)
432                 goto out_err_nodisable;
433
434 #ifdef CONFIG_HAVE_KVM_IRQCHIP
435         INIT_HLIST_HEAD(&kvm->mask_notifier_list);
436         INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
437 #endif
438
439         r = -ENOMEM;
440         kvm->memslots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
441         if (!kvm->memslots)
442                 goto out_err_nosrcu;
443         if (init_srcu_struct(&kvm->srcu))
444                 goto out_err_nosrcu;
445         for (i = 0; i < KVM_NR_BUSES; i++) {
446                 kvm->buses[i] = kzalloc(sizeof(struct kvm_io_bus),
447                                         GFP_KERNEL);
448                 if (!kvm->buses[i])
449                         goto out_err;
450         }
451
452         r = kvm_init_mmu_notifier(kvm);
453         if (r)
454                 goto out_err;
455
456         kvm->mm = current->mm;
457         atomic_inc(&kvm->mm->mm_count);
458         spin_lock_init(&kvm->mmu_lock);
459         raw_spin_lock_init(&kvm->requests_lock);
460         kvm_eventfd_init(kvm);
461         mutex_init(&kvm->lock);
462         mutex_init(&kvm->irq_lock);
463         mutex_init(&kvm->slots_lock);
464         atomic_set(&kvm->users_count, 1);
465         spin_lock(&kvm_lock);
466         list_add(&kvm->vm_list, &vm_list);
467         spin_unlock(&kvm_lock);
468
469         return kvm;
470
471 out_err:
472         cleanup_srcu_struct(&kvm->srcu);
473 out_err_nosrcu:
474         hardware_disable_all();
475 out_err_nodisable:
476         for (i = 0; i < KVM_NR_BUSES; i++)
477                 kfree(kvm->buses[i]);
478         kfree(kvm->memslots);
479         kvm_arch_free_vm(kvm);
480         return ERR_PTR(r);
481 }
482
483 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
484 {
485         if (!memslot->dirty_bitmap)
486                 return;
487
488         if (2 * kvm_dirty_bitmap_bytes(memslot) > PAGE_SIZE)
489                 vfree(memslot->dirty_bitmap_head);
490         else
491                 kfree(memslot->dirty_bitmap_head);
492
493         memslot->dirty_bitmap = NULL;
494         memslot->dirty_bitmap_head = NULL;
495 }
496
497 /*
498  * Free any memory in @free but not in @dont.
499  */
500 static void kvm_free_physmem_slot(struct kvm_memory_slot *free,
501                                   struct kvm_memory_slot *dont)
502 {
503         int i;
504
505         if (!dont || free->rmap != dont->rmap)
506                 vfree(free->rmap);
507
508         if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
509                 kvm_destroy_dirty_bitmap(free);
510
511
512         for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) {
513                 if (!dont || free->lpage_info[i] != dont->lpage_info[i]) {
514                         vfree(free->lpage_info[i]);
515                         free->lpage_info[i] = NULL;
516                 }
517         }
518
519         free->npages = 0;
520         free->rmap = NULL;
521 }
522
523 void kvm_free_physmem(struct kvm *kvm)
524 {
525         int i;
526         struct kvm_memslots *slots = kvm->memslots;
527
528         for (i = 0; i < slots->nmemslots; ++i)
529                 kvm_free_physmem_slot(&slots->memslots[i], NULL);
530
531         kfree(kvm->memslots);
532 }
533
534 static void kvm_destroy_vm(struct kvm *kvm)
535 {
536         int i;
537         struct mm_struct *mm = kvm->mm;
538
539         kvm_arch_sync_events(kvm);
540         spin_lock(&kvm_lock);
541         list_del(&kvm->vm_list);
542         spin_unlock(&kvm_lock);
543         kvm_free_irq_routing(kvm);
544         for (i = 0; i < KVM_NR_BUSES; i++)
545                 kvm_io_bus_destroy(kvm->buses[i]);
546         kvm_coalesced_mmio_free(kvm);
547 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
548         mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
549 #else
550         kvm_arch_flush_shadow(kvm);
551 #endif
552         kvm_arch_destroy_vm(kvm);
553         kvm_free_physmem(kvm);
554         cleanup_srcu_struct(&kvm->srcu);
555         kvm_arch_free_vm(kvm);
556         hardware_disable_all();
557         mmdrop(mm);
558 }
559
560 void kvm_get_kvm(struct kvm *kvm)
561 {
562         atomic_inc(&kvm->users_count);
563 }
564 EXPORT_SYMBOL_GPL(kvm_get_kvm);
565
566 void kvm_put_kvm(struct kvm *kvm)
567 {
568         if (atomic_dec_and_test(&kvm->users_count))
569                 kvm_destroy_vm(kvm);
570 }
571 EXPORT_SYMBOL_GPL(kvm_put_kvm);
572
573
574 static int kvm_vm_release(struct inode *inode, struct file *filp)
575 {
576         struct kvm *kvm = filp->private_data;
577
578         kvm_irqfd_release(kvm);
579
580         kvm_put_kvm(kvm);
581         return 0;
582 }
583
584 /*
585  * Allocation size is twice as large as the actual dirty bitmap size.
586  * This makes it possible to do double buffering: see x86's
587  * kvm_vm_ioctl_get_dirty_log().
588  */
589 static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
590 {
591         unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
592
593         if (dirty_bytes > PAGE_SIZE)
594                 memslot->dirty_bitmap = vzalloc(dirty_bytes);
595         else
596                 memslot->dirty_bitmap = kzalloc(dirty_bytes, GFP_KERNEL);
597
598         if (!memslot->dirty_bitmap)
599                 return -ENOMEM;
600
601         memslot->dirty_bitmap_head = memslot->dirty_bitmap;
602         return 0;
603 }
604
605 /*
606  * Allocate some memory and give it an address in the guest physical address
607  * space.
608  *
609  * Discontiguous memory is allowed, mostly for framebuffers.
610  *
611  * Must be called holding mmap_sem for write.
612  */
613 int __kvm_set_memory_region(struct kvm *kvm,
614                             struct kvm_userspace_memory_region *mem,
615                             int user_alloc)
616 {
617         int r, flush_shadow = 0;
618         gfn_t base_gfn;
619         unsigned long npages;
620         unsigned long i;
621         struct kvm_memory_slot *memslot;
622         struct kvm_memory_slot old, new;
623         struct kvm_memslots *slots, *old_memslots;
624
625         r = -EINVAL;
626         /* General sanity checks */
627         if (mem->memory_size & (PAGE_SIZE - 1))
628                 goto out;
629         if (mem->guest_phys_addr & (PAGE_SIZE - 1))
630                 goto out;
631         if (user_alloc && (mem->userspace_addr & (PAGE_SIZE - 1)))
632                 goto out;
633         if (mem->slot >= KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS)
634                 goto out;
635         if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
636                 goto out;
637
638         memslot = &kvm->memslots->memslots[mem->slot];
639         base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
640         npages = mem->memory_size >> PAGE_SHIFT;
641
642         r = -EINVAL;
643         if (npages > KVM_MEM_MAX_NR_PAGES)
644                 goto out;
645
646         if (!npages)
647                 mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
648
649         new = old = *memslot;
650
651         new.id = mem->slot;
652         new.base_gfn = base_gfn;
653         new.npages = npages;
654         new.flags = mem->flags;
655
656         /* Disallow changing a memory slot's size. */
657         r = -EINVAL;
658         if (npages && old.npages && npages != old.npages)
659                 goto out_free;
660
661         /* Check for overlaps */
662         r = -EEXIST;
663         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
664                 struct kvm_memory_slot *s = &kvm->memslots->memslots[i];
665
666                 if (s == memslot || !s->npages)
667                         continue;
668                 if (!((base_gfn + npages <= s->base_gfn) ||
669                       (base_gfn >= s->base_gfn + s->npages)))
670                         goto out_free;
671         }
672
673         /* Free page dirty bitmap if unneeded */
674         if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
675                 new.dirty_bitmap = NULL;
676
677         r = -ENOMEM;
678
679         /* Allocate if a slot is being created */
680 #ifndef CONFIG_S390
681         if (npages && !new.rmap) {
682                 new.rmap = vzalloc(npages * sizeof(*new.rmap));
683
684                 if (!new.rmap)
685                         goto out_free;
686
687                 new.user_alloc = user_alloc;
688                 new.userspace_addr = mem->userspace_addr;
689         }
690         if (!npages)
691                 goto skip_lpage;
692
693         for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) {
694                 unsigned long ugfn;
695                 unsigned long j;
696                 int lpages;
697                 int level = i + 2;
698
699                 /* Avoid unused variable warning if no large pages */
700                 (void)level;
701
702                 if (new.lpage_info[i])
703                         continue;
704
705                 lpages = 1 + ((base_gfn + npages - 1)
706                              >> KVM_HPAGE_GFN_SHIFT(level));
707                 lpages -= base_gfn >> KVM_HPAGE_GFN_SHIFT(level);
708
709                 new.lpage_info[i] = vzalloc(lpages * sizeof(*new.lpage_info[i]));
710
711                 if (!new.lpage_info[i])
712                         goto out_free;
713
714                 if (base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
715                         new.lpage_info[i][0].write_count = 1;
716                 if ((base_gfn+npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
717                         new.lpage_info[i][lpages - 1].write_count = 1;
718                 ugfn = new.userspace_addr >> PAGE_SHIFT;
719                 /*
720                  * If the gfn and userspace address are not aligned wrt each
721                  * other, or if explicitly asked to, disable large page
722                  * support for this slot
723                  */
724                 if ((base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
725                     !largepages_enabled)
726                         for (j = 0; j < lpages; ++j)
727                                 new.lpage_info[i][j].write_count = 1;
728         }
729
730 skip_lpage:
731
732         /* Allocate page dirty bitmap if needed */
733         if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
734                 if (kvm_create_dirty_bitmap(&new) < 0)
735                         goto out_free;
736                 /* destroy any largepage mappings for dirty tracking */
737                 if (old.npages)
738                         flush_shadow = 1;
739         }
740 #else  /* not defined CONFIG_S390 */
741         new.user_alloc = user_alloc;
742         if (user_alloc)
743                 new.userspace_addr = mem->userspace_addr;
744 #endif /* not defined CONFIG_S390 */
745
746         if (!npages) {
747                 r = -ENOMEM;
748                 slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
749                 if (!slots)
750                         goto out_free;
751                 memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
752                 if (mem->slot >= slots->nmemslots)
753                         slots->nmemslots = mem->slot + 1;
754                 slots->generation++;
755                 slots->memslots[mem->slot].flags |= KVM_MEMSLOT_INVALID;
756
757                 old_memslots = kvm->memslots;
758                 rcu_assign_pointer(kvm->memslots, slots);
759                 synchronize_srcu_expedited(&kvm->srcu);
760                 /* From this point no new shadow pages pointing to a deleted
761                  * memslot will be created.
762                  *
763                  * validation of sp->gfn happens in:
764                  *      - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
765                  *      - kvm_is_visible_gfn (mmu_check_roots)
766                  */
767                 kvm_arch_flush_shadow(kvm);
768                 kfree(old_memslots);
769         }
770
771         r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc);
772         if (r)
773                 goto out_free;
774
775         /* map the pages in iommu page table */
776         if (npages) {
777                 r = kvm_iommu_map_pages(kvm, &new);
778                 if (r)
779                         goto out_free;
780         }
781
782         r = -ENOMEM;
783         slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
784         if (!slots)
785                 goto out_free;
786         memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
787         if (mem->slot >= slots->nmemslots)
788                 slots->nmemslots = mem->slot + 1;
789         slots->generation++;
790
791         /* actual memory is freed via old in kvm_free_physmem_slot below */
792         if (!npages) {
793                 new.rmap = NULL;
794                 new.dirty_bitmap = NULL;
795                 for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i)
796                         new.lpage_info[i] = NULL;
797         }
798
799         slots->memslots[mem->slot] = new;
800         old_memslots = kvm->memslots;
801         rcu_assign_pointer(kvm->memslots, slots);
802         synchronize_srcu_expedited(&kvm->srcu);
803
804         kvm_arch_commit_memory_region(kvm, mem, old, user_alloc);
805
806         kvm_free_physmem_slot(&old, &new);
807         kfree(old_memslots);
808
809         if (flush_shadow)
810                 kvm_arch_flush_shadow(kvm);
811
812         return 0;
813
814 out_free:
815         kvm_free_physmem_slot(&new, &old);
816 out:
817         return r;
818
819 }
820 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
821
822 int kvm_set_memory_region(struct kvm *kvm,
823                           struct kvm_userspace_memory_region *mem,
824                           int user_alloc)
825 {
826         int r;
827
828         mutex_lock(&kvm->slots_lock);
829         r = __kvm_set_memory_region(kvm, mem, user_alloc);
830         mutex_unlock(&kvm->slots_lock);
831         return r;
832 }
833 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
834
835 int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
836                                    struct
837                                    kvm_userspace_memory_region *mem,
838                                    int user_alloc)
839 {
840         if (mem->slot >= KVM_MEMORY_SLOTS)
841                 return -EINVAL;
842         return kvm_set_memory_region(kvm, mem, user_alloc);
843 }
844
845 int kvm_get_dirty_log(struct kvm *kvm,
846                         struct kvm_dirty_log *log, int *is_dirty)
847 {
848         struct kvm_memory_slot *memslot;
849         int r, i;
850         unsigned long n;
851         unsigned long any = 0;
852
853         r = -EINVAL;
854         if (log->slot >= KVM_MEMORY_SLOTS)
855                 goto out;
856
857         memslot = &kvm->memslots->memslots[log->slot];
858         r = -ENOENT;
859         if (!memslot->dirty_bitmap)
860                 goto out;
861
862         n = kvm_dirty_bitmap_bytes(memslot);
863
864         for (i = 0; !any && i < n/sizeof(long); ++i)
865                 any = memslot->dirty_bitmap[i];
866
867         r = -EFAULT;
868         if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
869                 goto out;
870
871         if (any)
872                 *is_dirty = 1;
873
874         r = 0;
875 out:
876         return r;
877 }
878
879 void kvm_disable_largepages(void)
880 {
881         largepages_enabled = false;
882 }
883 EXPORT_SYMBOL_GPL(kvm_disable_largepages);
884
885 int is_error_page(struct page *page)
886 {
887         return page == bad_page || page == hwpoison_page || page == fault_page;
888 }
889 EXPORT_SYMBOL_GPL(is_error_page);
890
891 int is_error_pfn(pfn_t pfn)
892 {
893         return pfn == bad_pfn || pfn == hwpoison_pfn || pfn == fault_pfn;
894 }
895 EXPORT_SYMBOL_GPL(is_error_pfn);
896
897 int is_hwpoison_pfn(pfn_t pfn)
898 {
899         return pfn == hwpoison_pfn;
900 }
901 EXPORT_SYMBOL_GPL(is_hwpoison_pfn);
902
903 int is_fault_pfn(pfn_t pfn)
904 {
905         return pfn == fault_pfn;
906 }
907 EXPORT_SYMBOL_GPL(is_fault_pfn);
908
909 static inline unsigned long bad_hva(void)
910 {
911         return PAGE_OFFSET;
912 }
913
914 int kvm_is_error_hva(unsigned long addr)
915 {
916         return addr == bad_hva();
917 }
918 EXPORT_SYMBOL_GPL(kvm_is_error_hva);
919
920 static struct kvm_memory_slot *__gfn_to_memslot(struct kvm_memslots *slots,
921                                                 gfn_t gfn)
922 {
923         int i;
924
925         for (i = 0; i < slots->nmemslots; ++i) {
926                 struct kvm_memory_slot *memslot = &slots->memslots[i];
927
928                 if (gfn >= memslot->base_gfn
929                     && gfn < memslot->base_gfn + memslot->npages)
930                         return memslot;
931         }
932         return NULL;
933 }
934
935 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
936 {
937         return __gfn_to_memslot(kvm_memslots(kvm), gfn);
938 }
939 EXPORT_SYMBOL_GPL(gfn_to_memslot);
940
941 int kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
942 {
943         int i;
944         struct kvm_memslots *slots = kvm_memslots(kvm);
945
946         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
947                 struct kvm_memory_slot *memslot = &slots->memslots[i];
948
949                 if (memslot->flags & KVM_MEMSLOT_INVALID)
950                         continue;
951
952                 if (gfn >= memslot->base_gfn
953                     && gfn < memslot->base_gfn + memslot->npages)
954                         return 1;
955         }
956         return 0;
957 }
958 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
959
960 unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn)
961 {
962         struct vm_area_struct *vma;
963         unsigned long addr, size;
964
965         size = PAGE_SIZE;
966
967         addr = gfn_to_hva(kvm, gfn);
968         if (kvm_is_error_hva(addr))
969                 return PAGE_SIZE;
970
971         down_read(&current->mm->mmap_sem);
972         vma = find_vma(current->mm, addr);
973         if (!vma)
974                 goto out;
975
976         size = vma_kernel_pagesize(vma);
977
978 out:
979         up_read(&current->mm->mmap_sem);
980
981         return size;
982 }
983
984 int memslot_id(struct kvm *kvm, gfn_t gfn)
985 {
986         int i;
987         struct kvm_memslots *slots = kvm_memslots(kvm);
988         struct kvm_memory_slot *memslot = NULL;
989
990         for (i = 0; i < slots->nmemslots; ++i) {
991                 memslot = &slots->memslots[i];
992
993                 if (gfn >= memslot->base_gfn
994                     && gfn < memslot->base_gfn + memslot->npages)
995                         break;
996         }
997
998         return memslot - slots->memslots;
999 }
1000
1001 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1002                                      gfn_t *nr_pages)
1003 {
1004         if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1005                 return bad_hva();
1006
1007         if (nr_pages)
1008                 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1009
1010         return gfn_to_hva_memslot(slot, gfn);
1011 }
1012
1013 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1014 {
1015         return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1016 }
1017 EXPORT_SYMBOL_GPL(gfn_to_hva);
1018
1019 static pfn_t get_fault_pfn(void)
1020 {
1021         get_page(fault_page);
1022         return fault_pfn;
1023 }
1024
1025 static pfn_t hva_to_pfn(struct kvm *kvm, unsigned long addr, bool atomic,
1026                         bool *async, bool write_fault, bool *writable)
1027 {
1028         struct page *page[1];
1029         int npages = 0;
1030         pfn_t pfn;
1031
1032         /* we can do it either atomically or asynchronously, not both */
1033         BUG_ON(atomic && async);
1034
1035         BUG_ON(!write_fault && !writable);
1036
1037         if (writable)
1038                 *writable = true;
1039
1040         if (atomic || async)
1041                 npages = __get_user_pages_fast(addr, 1, 1, page);
1042
1043         if (unlikely(npages != 1) && !atomic) {
1044                 might_sleep();
1045
1046                 if (writable)
1047                         *writable = write_fault;
1048
1049                 npages = get_user_pages_fast(addr, 1, write_fault, page);
1050
1051                 /* map read fault as writable if possible */
1052                 if (unlikely(!write_fault) && npages == 1) {
1053                         struct page *wpage[1];
1054
1055                         npages = __get_user_pages_fast(addr, 1, 1, wpage);
1056                         if (npages == 1) {
1057                                 *writable = true;
1058                                 put_page(page[0]);
1059                                 page[0] = wpage[0];
1060                         }
1061                         npages = 1;
1062                 }
1063         }
1064
1065         if (unlikely(npages != 1)) {
1066                 struct vm_area_struct *vma;
1067
1068                 if (atomic)
1069                         return get_fault_pfn();
1070
1071                 down_read(&current->mm->mmap_sem);
1072                 if (is_hwpoison_address(addr)) {
1073                         up_read(&current->mm->mmap_sem);
1074                         get_page(hwpoison_page);
1075                         return page_to_pfn(hwpoison_page);
1076                 }
1077
1078                 vma = find_vma_intersection(current->mm, addr, addr+1);
1079
1080                 if (vma == NULL)
1081                         pfn = get_fault_pfn();
1082                 else if ((vma->vm_flags & VM_PFNMAP)) {
1083                         pfn = ((addr - vma->vm_start) >> PAGE_SHIFT) +
1084                                 vma->vm_pgoff;
1085                         BUG_ON(!kvm_is_mmio_pfn(pfn));
1086                 } else {
1087                         if (async && (vma->vm_flags & VM_WRITE))
1088                                 *async = true;
1089                         pfn = get_fault_pfn();
1090                 }
1091                 up_read(&current->mm->mmap_sem);
1092         } else
1093                 pfn = page_to_pfn(page[0]);
1094
1095         return pfn;
1096 }
1097
1098 pfn_t hva_to_pfn_atomic(struct kvm *kvm, unsigned long addr)
1099 {
1100         return hva_to_pfn(kvm, addr, true, NULL, true, NULL);
1101 }
1102 EXPORT_SYMBOL_GPL(hva_to_pfn_atomic);
1103
1104 static pfn_t __gfn_to_pfn(struct kvm *kvm, gfn_t gfn, bool atomic, bool *async,
1105                           bool write_fault, bool *writable)
1106 {
1107         unsigned long addr;
1108
1109         if (async)
1110                 *async = false;
1111
1112         addr = gfn_to_hva(kvm, gfn);
1113         if (kvm_is_error_hva(addr)) {
1114                 get_page(bad_page);
1115                 return page_to_pfn(bad_page);
1116         }
1117
1118         return hva_to_pfn(kvm, addr, atomic, async, write_fault, writable);
1119 }
1120
1121 pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
1122 {
1123         return __gfn_to_pfn(kvm, gfn, true, NULL, true, NULL);
1124 }
1125 EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
1126
1127 pfn_t gfn_to_pfn_async(struct kvm *kvm, gfn_t gfn, bool *async,
1128                        bool write_fault, bool *writable)
1129 {
1130         return __gfn_to_pfn(kvm, gfn, false, async, write_fault, writable);
1131 }
1132 EXPORT_SYMBOL_GPL(gfn_to_pfn_async);
1133
1134 pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1135 {
1136         return __gfn_to_pfn(kvm, gfn, false, NULL, true, NULL);
1137 }
1138 EXPORT_SYMBOL_GPL(gfn_to_pfn);
1139
1140 pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
1141                       bool *writable)
1142 {
1143         return __gfn_to_pfn(kvm, gfn, false, NULL, write_fault, writable);
1144 }
1145 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1146
1147 pfn_t gfn_to_pfn_memslot(struct kvm *kvm,
1148                          struct kvm_memory_slot *slot, gfn_t gfn)
1149 {
1150         unsigned long addr = gfn_to_hva_memslot(slot, gfn);
1151         return hva_to_pfn(kvm, addr, false, NULL, true, NULL);
1152 }
1153
1154 int gfn_to_page_many_atomic(struct kvm *kvm, gfn_t gfn, struct page **pages,
1155                                                                   int nr_pages)
1156 {
1157         unsigned long addr;
1158         gfn_t entry;
1159
1160         addr = gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, &entry);
1161         if (kvm_is_error_hva(addr))
1162                 return -1;
1163
1164         if (entry < nr_pages)
1165                 return 0;
1166
1167         return __get_user_pages_fast(addr, nr_pages, 1, pages);
1168 }
1169 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
1170
1171 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1172 {
1173         pfn_t pfn;
1174
1175         pfn = gfn_to_pfn(kvm, gfn);
1176         if (!kvm_is_mmio_pfn(pfn))
1177                 return pfn_to_page(pfn);
1178
1179         WARN_ON(kvm_is_mmio_pfn(pfn));
1180
1181         get_page(bad_page);
1182         return bad_page;
1183 }
1184
1185 EXPORT_SYMBOL_GPL(gfn_to_page);
1186
1187 void kvm_release_page_clean(struct page *page)
1188 {
1189         kvm_release_pfn_clean(page_to_pfn(page));
1190 }
1191 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
1192
1193 void kvm_release_pfn_clean(pfn_t pfn)
1194 {
1195         if (!kvm_is_mmio_pfn(pfn))
1196                 put_page(pfn_to_page(pfn));
1197 }
1198 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
1199
1200 void kvm_release_page_dirty(struct page *page)
1201 {
1202         kvm_release_pfn_dirty(page_to_pfn(page));
1203 }
1204 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
1205
1206 void kvm_release_pfn_dirty(pfn_t pfn)
1207 {
1208         kvm_set_pfn_dirty(pfn);
1209         kvm_release_pfn_clean(pfn);
1210 }
1211 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
1212
1213 void kvm_set_page_dirty(struct page *page)
1214 {
1215         kvm_set_pfn_dirty(page_to_pfn(page));
1216 }
1217 EXPORT_SYMBOL_GPL(kvm_set_page_dirty);
1218
1219 void kvm_set_pfn_dirty(pfn_t pfn)
1220 {
1221         if (!kvm_is_mmio_pfn(pfn)) {
1222                 struct page *page = pfn_to_page(pfn);
1223                 if (!PageReserved(page))
1224                         SetPageDirty(page);
1225         }
1226 }
1227 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
1228
1229 void kvm_set_pfn_accessed(pfn_t pfn)
1230 {
1231         if (!kvm_is_mmio_pfn(pfn))
1232                 mark_page_accessed(pfn_to_page(pfn));
1233 }
1234 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
1235
1236 void kvm_get_pfn(pfn_t pfn)
1237 {
1238         if (!kvm_is_mmio_pfn(pfn))
1239                 get_page(pfn_to_page(pfn));
1240 }
1241 EXPORT_SYMBOL_GPL(kvm_get_pfn);
1242
1243 static int next_segment(unsigned long len, int offset)
1244 {
1245         if (len > PAGE_SIZE - offset)
1246                 return PAGE_SIZE - offset;
1247         else
1248                 return len;
1249 }
1250
1251 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1252                         int len)
1253 {
1254         int r;
1255         unsigned long addr;
1256
1257         addr = gfn_to_hva(kvm, gfn);
1258         if (kvm_is_error_hva(addr))
1259                 return -EFAULT;
1260         r = copy_from_user(data, (void __user *)addr + offset, len);
1261         if (r)
1262                 return -EFAULT;
1263         return 0;
1264 }
1265 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
1266
1267 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
1268 {
1269         gfn_t gfn = gpa >> PAGE_SHIFT;
1270         int seg;
1271         int offset = offset_in_page(gpa);
1272         int ret;
1273
1274         while ((seg = next_segment(len, offset)) != 0) {
1275                 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
1276                 if (ret < 0)
1277                         return ret;
1278                 offset = 0;
1279                 len -= seg;
1280                 data += seg;
1281                 ++gfn;
1282         }
1283         return 0;
1284 }
1285 EXPORT_SYMBOL_GPL(kvm_read_guest);
1286
1287 int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
1288                           unsigned long len)
1289 {
1290         int r;
1291         unsigned long addr;
1292         gfn_t gfn = gpa >> PAGE_SHIFT;
1293         int offset = offset_in_page(gpa);
1294
1295         addr = gfn_to_hva(kvm, gfn);
1296         if (kvm_is_error_hva(addr))
1297                 return -EFAULT;
1298         pagefault_disable();
1299         r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
1300         pagefault_enable();
1301         if (r)
1302                 return -EFAULT;
1303         return 0;
1304 }
1305 EXPORT_SYMBOL(kvm_read_guest_atomic);
1306
1307 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
1308                          int offset, int len)
1309 {
1310         int r;
1311         unsigned long addr;
1312
1313         addr = gfn_to_hva(kvm, gfn);
1314         if (kvm_is_error_hva(addr))
1315                 return -EFAULT;
1316         r = copy_to_user((void __user *)addr + offset, data, len);
1317         if (r)
1318                 return -EFAULT;
1319         mark_page_dirty(kvm, gfn);
1320         return 0;
1321 }
1322 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
1323
1324 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
1325                     unsigned long len)
1326 {
1327         gfn_t gfn = gpa >> PAGE_SHIFT;
1328         int seg;
1329         int offset = offset_in_page(gpa);
1330         int ret;
1331
1332         while ((seg = next_segment(len, offset)) != 0) {
1333                 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
1334                 if (ret < 0)
1335                         return ret;
1336                 offset = 0;
1337                 len -= seg;
1338                 data += seg;
1339                 ++gfn;
1340         }
1341         return 0;
1342 }
1343
1344 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1345                               gpa_t gpa)
1346 {
1347         struct kvm_memslots *slots = kvm_memslots(kvm);
1348         int offset = offset_in_page(gpa);
1349         gfn_t gfn = gpa >> PAGE_SHIFT;
1350
1351         ghc->gpa = gpa;
1352         ghc->generation = slots->generation;
1353         ghc->memslot = __gfn_to_memslot(slots, gfn);
1354         ghc->hva = gfn_to_hva_many(ghc->memslot, gfn, NULL);
1355         if (!kvm_is_error_hva(ghc->hva))
1356                 ghc->hva += offset;
1357         else
1358                 return -EFAULT;
1359
1360         return 0;
1361 }
1362 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
1363
1364 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1365                            void *data, unsigned long len)
1366 {
1367         struct kvm_memslots *slots = kvm_memslots(kvm);
1368         int r;
1369
1370         if (slots->generation != ghc->generation)
1371                 kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa);
1372
1373         if (kvm_is_error_hva(ghc->hva))
1374                 return -EFAULT;
1375
1376         r = copy_to_user((void __user *)ghc->hva, data, len);
1377         if (r)
1378                 return -EFAULT;
1379         mark_page_dirty_in_slot(kvm, ghc->memslot, ghc->gpa >> PAGE_SHIFT);
1380
1381         return 0;
1382 }
1383 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
1384
1385 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
1386 {
1387         return kvm_write_guest_page(kvm, gfn, (const void *) empty_zero_page,
1388                                     offset, len);
1389 }
1390 EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
1391
1392 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
1393 {
1394         gfn_t gfn = gpa >> PAGE_SHIFT;
1395         int seg;
1396         int offset = offset_in_page(gpa);
1397         int ret;
1398
1399         while ((seg = next_segment(len, offset)) != 0) {
1400                 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
1401                 if (ret < 0)
1402                         return ret;
1403                 offset = 0;
1404                 len -= seg;
1405                 ++gfn;
1406         }
1407         return 0;
1408 }
1409 EXPORT_SYMBOL_GPL(kvm_clear_guest);
1410
1411 void mark_page_dirty_in_slot(struct kvm *kvm, struct kvm_memory_slot *memslot,
1412                              gfn_t gfn)
1413 {
1414         if (memslot && memslot->dirty_bitmap) {
1415                 unsigned long rel_gfn = gfn - memslot->base_gfn;
1416
1417                 generic___set_le_bit(rel_gfn, memslot->dirty_bitmap);
1418         }
1419 }
1420
1421 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
1422 {
1423         struct kvm_memory_slot *memslot;
1424
1425         memslot = gfn_to_memslot(kvm, gfn);
1426         mark_page_dirty_in_slot(kvm, memslot, gfn);
1427 }
1428
1429 /*
1430  * The vCPU has executed a HLT instruction with in-kernel mode enabled.
1431  */
1432 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
1433 {
1434         DEFINE_WAIT(wait);
1435
1436         for (;;) {
1437                 prepare_to_wait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
1438
1439                 if (kvm_arch_vcpu_runnable(vcpu)) {
1440                         kvm_make_request(KVM_REQ_UNHALT, vcpu);
1441                         break;
1442                 }
1443                 if (kvm_cpu_has_pending_timer(vcpu))
1444                         break;
1445                 if (signal_pending(current))
1446                         break;
1447
1448                 schedule();
1449         }
1450
1451         finish_wait(&vcpu->wq, &wait);
1452 }
1453
1454 void kvm_resched(struct kvm_vcpu *vcpu)
1455 {
1456         if (!need_resched())
1457                 return;
1458         cond_resched();
1459 }
1460 EXPORT_SYMBOL_GPL(kvm_resched);
1461
1462 void kvm_vcpu_on_spin(struct kvm_vcpu *vcpu)
1463 {
1464         ktime_t expires;
1465         DEFINE_WAIT(wait);
1466
1467         prepare_to_wait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
1468
1469         /* Sleep for 100 us, and hope lock-holder got scheduled */
1470         expires = ktime_add_ns(ktime_get(), 100000UL);
1471         schedule_hrtimeout(&expires, HRTIMER_MODE_ABS);
1472
1473         finish_wait(&vcpu->wq, &wait);
1474 }
1475 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
1476
1477 static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1478 {
1479         struct kvm_vcpu *vcpu = vma->vm_file->private_data;
1480         struct page *page;
1481
1482         if (vmf->pgoff == 0)
1483                 page = virt_to_page(vcpu->run);
1484 #ifdef CONFIG_X86
1485         else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
1486                 page = virt_to_page(vcpu->arch.pio_data);
1487 #endif
1488 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
1489         else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
1490                 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
1491 #endif
1492         else
1493                 return VM_FAULT_SIGBUS;
1494         get_page(page);
1495         vmf->page = page;
1496         return 0;
1497 }
1498
1499 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
1500         .fault = kvm_vcpu_fault,
1501 };
1502
1503 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
1504 {
1505         vma->vm_ops = &kvm_vcpu_vm_ops;
1506         return 0;
1507 }
1508
1509 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
1510 {
1511         struct kvm_vcpu *vcpu = filp->private_data;
1512
1513         kvm_put_kvm(vcpu->kvm);
1514         return 0;
1515 }
1516
1517 static struct file_operations kvm_vcpu_fops = {
1518         .release        = kvm_vcpu_release,
1519         .unlocked_ioctl = kvm_vcpu_ioctl,
1520         .compat_ioctl   = kvm_vcpu_ioctl,
1521         .mmap           = kvm_vcpu_mmap,
1522         .llseek         = noop_llseek,
1523 };
1524
1525 /*
1526  * Allocates an inode for the vcpu.
1527  */
1528 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
1529 {
1530         return anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, O_RDWR);
1531 }
1532
1533 /*
1534  * Creates some virtual cpus.  Good luck creating more than one.
1535  */
1536 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
1537 {
1538         int r;
1539         struct kvm_vcpu *vcpu, *v;
1540
1541         vcpu = kvm_arch_vcpu_create(kvm, id);
1542         if (IS_ERR(vcpu))
1543                 return PTR_ERR(vcpu);
1544
1545         preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
1546
1547         r = kvm_arch_vcpu_setup(vcpu);
1548         if (r)
1549                 return r;
1550
1551         mutex_lock(&kvm->lock);
1552         if (atomic_read(&kvm->online_vcpus) == KVM_MAX_VCPUS) {
1553                 r = -EINVAL;
1554                 goto vcpu_destroy;
1555         }
1556
1557         kvm_for_each_vcpu(r, v, kvm)
1558                 if (v->vcpu_id == id) {
1559                         r = -EEXIST;
1560                         goto vcpu_destroy;
1561                 }
1562
1563         BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
1564
1565         /* Now it's all set up, let userspace reach it */
1566         kvm_get_kvm(kvm);
1567         r = create_vcpu_fd(vcpu);
1568         if (r < 0) {
1569                 kvm_put_kvm(kvm);
1570                 goto vcpu_destroy;
1571         }
1572
1573         kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
1574         smp_wmb();
1575         atomic_inc(&kvm->online_vcpus);
1576
1577 #ifdef CONFIG_KVM_APIC_ARCHITECTURE
1578         if (kvm->bsp_vcpu_id == id)
1579                 kvm->bsp_vcpu = vcpu;
1580 #endif
1581         mutex_unlock(&kvm->lock);
1582         return r;
1583
1584 vcpu_destroy:
1585         mutex_unlock(&kvm->lock);
1586         kvm_arch_vcpu_destroy(vcpu);
1587         return r;
1588 }
1589
1590 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
1591 {
1592         if (sigset) {
1593                 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
1594                 vcpu->sigset_active = 1;
1595                 vcpu->sigset = *sigset;
1596         } else
1597                 vcpu->sigset_active = 0;
1598         return 0;
1599 }
1600
1601 static long kvm_vcpu_ioctl(struct file *filp,
1602                            unsigned int ioctl, unsigned long arg)
1603 {
1604         struct kvm_vcpu *vcpu = filp->private_data;
1605         void __user *argp = (void __user *)arg;
1606         int r;
1607         struct kvm_fpu *fpu = NULL;
1608         struct kvm_sregs *kvm_sregs = NULL;
1609
1610         if (vcpu->kvm->mm != current->mm)
1611                 return -EIO;
1612
1613 #if defined(CONFIG_S390) || defined(CONFIG_PPC)
1614         /*
1615          * Special cases: vcpu ioctls that are asynchronous to vcpu execution,
1616          * so vcpu_load() would break it.
1617          */
1618         if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_INTERRUPT)
1619                 return kvm_arch_vcpu_ioctl(filp, ioctl, arg);
1620 #endif
1621
1622
1623         vcpu_load(vcpu);
1624         switch (ioctl) {
1625         case KVM_RUN:
1626                 r = -EINVAL;
1627                 if (arg)
1628                         goto out;
1629                 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
1630                 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
1631                 break;
1632         case KVM_GET_REGS: {
1633                 struct kvm_regs *kvm_regs;
1634
1635                 r = -ENOMEM;
1636                 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
1637                 if (!kvm_regs)
1638                         goto out;
1639                 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
1640                 if (r)
1641                         goto out_free1;
1642                 r = -EFAULT;
1643                 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
1644                         goto out_free1;
1645                 r = 0;
1646 out_free1:
1647                 kfree(kvm_regs);
1648                 break;
1649         }
1650         case KVM_SET_REGS: {
1651                 struct kvm_regs *kvm_regs;
1652
1653                 r = -ENOMEM;
1654                 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
1655                 if (!kvm_regs)
1656                         goto out;
1657                 r = -EFAULT;
1658                 if (copy_from_user(kvm_regs, argp, sizeof(struct kvm_regs)))
1659                         goto out_free2;
1660                 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
1661                 if (r)
1662                         goto out_free2;
1663                 r = 0;
1664 out_free2:
1665                 kfree(kvm_regs);
1666                 break;
1667         }
1668         case KVM_GET_SREGS: {
1669                 kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
1670                 r = -ENOMEM;
1671                 if (!kvm_sregs)
1672                         goto out;
1673                 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
1674                 if (r)
1675                         goto out;
1676                 r = -EFAULT;
1677                 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
1678                         goto out;
1679                 r = 0;
1680                 break;
1681         }
1682         case KVM_SET_SREGS: {
1683                 kvm_sregs = kmalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
1684                 r = -ENOMEM;
1685                 if (!kvm_sregs)
1686                         goto out;
1687                 r = -EFAULT;
1688                 if (copy_from_user(kvm_sregs, argp, sizeof(struct kvm_sregs)))
1689                         goto out;
1690                 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
1691                 if (r)
1692                         goto out;
1693                 r = 0;
1694                 break;
1695         }
1696         case KVM_GET_MP_STATE: {
1697                 struct kvm_mp_state mp_state;
1698
1699                 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
1700                 if (r)
1701                         goto out;
1702                 r = -EFAULT;
1703                 if (copy_to_user(argp, &mp_state, sizeof mp_state))
1704                         goto out;
1705                 r = 0;
1706                 break;
1707         }
1708         case KVM_SET_MP_STATE: {
1709                 struct kvm_mp_state mp_state;
1710
1711                 r = -EFAULT;
1712                 if (copy_from_user(&mp_state, argp, sizeof mp_state))
1713                         goto out;
1714                 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
1715                 if (r)
1716                         goto out;
1717                 r = 0;
1718                 break;
1719         }
1720         case KVM_TRANSLATE: {
1721                 struct kvm_translation tr;
1722
1723                 r = -EFAULT;
1724                 if (copy_from_user(&tr, argp, sizeof tr))
1725                         goto out;
1726                 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
1727                 if (r)
1728                         goto out;
1729                 r = -EFAULT;
1730                 if (copy_to_user(argp, &tr, sizeof tr))
1731                         goto out;
1732                 r = 0;
1733                 break;
1734         }
1735         case KVM_SET_GUEST_DEBUG: {
1736                 struct kvm_guest_debug dbg;
1737
1738                 r = -EFAULT;
1739                 if (copy_from_user(&dbg, argp, sizeof dbg))
1740                         goto out;
1741                 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
1742                 if (r)
1743                         goto out;
1744                 r = 0;
1745                 break;
1746         }
1747         case KVM_SET_SIGNAL_MASK: {
1748                 struct kvm_signal_mask __user *sigmask_arg = argp;
1749                 struct kvm_signal_mask kvm_sigmask;
1750                 sigset_t sigset, *p;
1751
1752                 p = NULL;
1753                 if (argp) {
1754                         r = -EFAULT;
1755                         if (copy_from_user(&kvm_sigmask, argp,
1756                                            sizeof kvm_sigmask))
1757                                 goto out;
1758                         r = -EINVAL;
1759                         if (kvm_sigmask.len != sizeof sigset)
1760                                 goto out;
1761                         r = -EFAULT;
1762                         if (copy_from_user(&sigset, sigmask_arg->sigset,
1763                                            sizeof sigset))
1764                                 goto out;
1765                         p = &sigset;
1766                 }
1767                 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
1768                 break;
1769         }
1770         case KVM_GET_FPU: {
1771                 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
1772                 r = -ENOMEM;
1773                 if (!fpu)
1774                         goto out;
1775                 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
1776                 if (r)
1777                         goto out;
1778                 r = -EFAULT;
1779                 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
1780                         goto out;
1781                 r = 0;
1782                 break;
1783         }
1784         case KVM_SET_FPU: {
1785                 fpu = kmalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
1786                 r = -ENOMEM;
1787                 if (!fpu)
1788                         goto out;
1789                 r = -EFAULT;
1790                 if (copy_from_user(fpu, argp, sizeof(struct kvm_fpu)))
1791                         goto out;
1792                 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
1793                 if (r)
1794                         goto out;
1795                 r = 0;
1796                 break;
1797         }
1798         default:
1799                 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
1800         }
1801 out:
1802         vcpu_put(vcpu);
1803         kfree(fpu);
1804         kfree(kvm_sregs);
1805         return r;
1806 }
1807
1808 static long kvm_vm_ioctl(struct file *filp,
1809                            unsigned int ioctl, unsigned long arg)
1810 {
1811         struct kvm *kvm = filp->private_data;
1812         void __user *argp = (void __user *)arg;
1813         int r;
1814
1815         if (kvm->mm != current->mm)
1816                 return -EIO;
1817         switch (ioctl) {
1818         case KVM_CREATE_VCPU:
1819                 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
1820                 if (r < 0)
1821                         goto out;
1822                 break;
1823         case KVM_SET_USER_MEMORY_REGION: {
1824                 struct kvm_userspace_memory_region kvm_userspace_mem;
1825
1826                 r = -EFAULT;
1827                 if (copy_from_user(&kvm_userspace_mem, argp,
1828                                                 sizeof kvm_userspace_mem))
1829                         goto out;
1830
1831                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 1);
1832                 if (r)
1833                         goto out;
1834                 break;
1835         }
1836         case KVM_GET_DIRTY_LOG: {
1837                 struct kvm_dirty_log log;
1838
1839                 r = -EFAULT;
1840                 if (copy_from_user(&log, argp, sizeof log))
1841                         goto out;
1842                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
1843                 if (r)
1844                         goto out;
1845                 break;
1846         }
1847 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
1848         case KVM_REGISTER_COALESCED_MMIO: {
1849                 struct kvm_coalesced_mmio_zone zone;
1850                 r = -EFAULT;
1851                 if (copy_from_user(&zone, argp, sizeof zone))
1852                         goto out;
1853                 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
1854                 if (r)
1855                         goto out;
1856                 r = 0;
1857                 break;
1858         }
1859         case KVM_UNREGISTER_COALESCED_MMIO: {
1860                 struct kvm_coalesced_mmio_zone zone;
1861                 r = -EFAULT;
1862                 if (copy_from_user(&zone, argp, sizeof zone))
1863                         goto out;
1864                 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
1865                 if (r)
1866                         goto out;
1867                 r = 0;
1868                 break;
1869         }
1870 #endif
1871         case KVM_IRQFD: {
1872                 struct kvm_irqfd data;
1873
1874                 r = -EFAULT;
1875                 if (copy_from_user(&data, argp, sizeof data))
1876                         goto out;
1877                 r = kvm_irqfd(kvm, data.fd, data.gsi, data.flags);
1878                 break;
1879         }
1880         case KVM_IOEVENTFD: {
1881                 struct kvm_ioeventfd data;
1882
1883                 r = -EFAULT;
1884                 if (copy_from_user(&data, argp, sizeof data))
1885                         goto out;
1886                 r = kvm_ioeventfd(kvm, &data);
1887                 break;
1888         }
1889 #ifdef CONFIG_KVM_APIC_ARCHITECTURE
1890         case KVM_SET_BOOT_CPU_ID:
1891                 r = 0;
1892                 mutex_lock(&kvm->lock);
1893                 if (atomic_read(&kvm->online_vcpus) != 0)
1894                         r = -EBUSY;
1895                 else
1896                         kvm->bsp_vcpu_id = arg;
1897                 mutex_unlock(&kvm->lock);
1898                 break;
1899 #endif
1900         default:
1901                 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
1902                 if (r == -ENOTTY)
1903                         r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
1904         }
1905 out:
1906         return r;
1907 }
1908
1909 #ifdef CONFIG_COMPAT
1910 struct compat_kvm_dirty_log {
1911         __u32 slot;
1912         __u32 padding1;
1913         union {
1914                 compat_uptr_t dirty_bitmap; /* one bit per page */
1915                 __u64 padding2;
1916         };
1917 };
1918
1919 static long kvm_vm_compat_ioctl(struct file *filp,
1920                            unsigned int ioctl, unsigned long arg)
1921 {
1922         struct kvm *kvm = filp->private_data;
1923         int r;
1924
1925         if (kvm->mm != current->mm)
1926                 return -EIO;
1927         switch (ioctl) {
1928         case KVM_GET_DIRTY_LOG: {
1929                 struct compat_kvm_dirty_log compat_log;
1930                 struct kvm_dirty_log log;
1931
1932                 r = -EFAULT;
1933                 if (copy_from_user(&compat_log, (void __user *)arg,
1934                                    sizeof(compat_log)))
1935                         goto out;
1936                 log.slot         = compat_log.slot;
1937                 log.padding1     = compat_log.padding1;
1938                 log.padding2     = compat_log.padding2;
1939                 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
1940
1941                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
1942                 if (r)
1943                         goto out;
1944                 break;
1945         }
1946         default:
1947                 r = kvm_vm_ioctl(filp, ioctl, arg);
1948         }
1949
1950 out:
1951         return r;
1952 }
1953 #endif
1954
1955 static int kvm_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1956 {
1957         struct page *page[1];
1958         unsigned long addr;
1959         int npages;
1960         gfn_t gfn = vmf->pgoff;
1961         struct kvm *kvm = vma->vm_file->private_data;
1962
1963         addr = gfn_to_hva(kvm, gfn);
1964         if (kvm_is_error_hva(addr))
1965                 return VM_FAULT_SIGBUS;
1966
1967         npages = get_user_pages(current, current->mm, addr, 1, 1, 0, page,
1968                                 NULL);
1969         if (unlikely(npages != 1))
1970                 return VM_FAULT_SIGBUS;
1971
1972         vmf->page = page[0];
1973         return 0;
1974 }
1975
1976 static const struct vm_operations_struct kvm_vm_vm_ops = {
1977         .fault = kvm_vm_fault,
1978 };
1979
1980 static int kvm_vm_mmap(struct file *file, struct vm_area_struct *vma)
1981 {
1982         vma->vm_ops = &kvm_vm_vm_ops;
1983         return 0;
1984 }
1985
1986 static struct file_operations kvm_vm_fops = {
1987         .release        = kvm_vm_release,
1988         .unlocked_ioctl = kvm_vm_ioctl,
1989 #ifdef CONFIG_COMPAT
1990         .compat_ioctl   = kvm_vm_compat_ioctl,
1991 #endif
1992         .mmap           = kvm_vm_mmap,
1993         .llseek         = noop_llseek,
1994 };
1995
1996 static int kvm_dev_ioctl_create_vm(void)
1997 {
1998         int r;
1999         struct kvm *kvm;
2000
2001         kvm = kvm_create_vm();
2002         if (IS_ERR(kvm))
2003                 return PTR_ERR(kvm);
2004 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2005         r = kvm_coalesced_mmio_init(kvm);
2006         if (r < 0) {
2007                 kvm_put_kvm(kvm);
2008                 return r;
2009         }
2010 #endif
2011         r = anon_inode_getfd("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
2012         if (r < 0)
2013                 kvm_put_kvm(kvm);
2014
2015         return r;
2016 }
2017
2018 static long kvm_dev_ioctl_check_extension_generic(long arg)
2019 {
2020         switch (arg) {
2021         case KVM_CAP_USER_MEMORY:
2022         case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
2023         case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
2024 #ifdef CONFIG_KVM_APIC_ARCHITECTURE
2025         case KVM_CAP_SET_BOOT_CPU_ID:
2026 #endif
2027         case KVM_CAP_INTERNAL_ERROR_DATA:
2028                 return 1;
2029 #ifdef CONFIG_HAVE_KVM_IRQCHIP
2030         case KVM_CAP_IRQ_ROUTING:
2031                 return KVM_MAX_IRQ_ROUTES;
2032 #endif
2033         default:
2034                 break;
2035         }
2036         return kvm_dev_ioctl_check_extension(arg);
2037 }
2038
2039 static long kvm_dev_ioctl(struct file *filp,
2040                           unsigned int ioctl, unsigned long arg)
2041 {
2042         long r = -EINVAL;
2043
2044         switch (ioctl) {
2045         case KVM_GET_API_VERSION:
2046                 r = -EINVAL;
2047                 if (arg)
2048                         goto out;
2049                 r = KVM_API_VERSION;
2050                 break;
2051         case KVM_CREATE_VM:
2052                 r = -EINVAL;
2053                 if (arg)
2054                         goto out;
2055                 r = kvm_dev_ioctl_create_vm();
2056                 break;
2057         case KVM_CHECK_EXTENSION:
2058                 r = kvm_dev_ioctl_check_extension_generic(arg);
2059                 break;
2060         case KVM_GET_VCPU_MMAP_SIZE:
2061                 r = -EINVAL;
2062                 if (arg)
2063                         goto out;
2064                 r = PAGE_SIZE;     /* struct kvm_run */
2065 #ifdef CONFIG_X86
2066                 r += PAGE_SIZE;    /* pio data page */
2067 #endif
2068 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2069                 r += PAGE_SIZE;    /* coalesced mmio ring page */
2070 #endif
2071                 break;
2072         case KVM_TRACE_ENABLE:
2073         case KVM_TRACE_PAUSE:
2074         case KVM_TRACE_DISABLE:
2075                 r = -EOPNOTSUPP;
2076                 break;
2077         default:
2078                 return kvm_arch_dev_ioctl(filp, ioctl, arg);
2079         }
2080 out:
2081         return r;
2082 }
2083
2084 static struct file_operations kvm_chardev_ops = {
2085         .unlocked_ioctl = kvm_dev_ioctl,
2086         .compat_ioctl   = kvm_dev_ioctl,
2087         .llseek         = noop_llseek,
2088 };
2089
2090 static struct miscdevice kvm_dev = {
2091         KVM_MINOR,
2092         "kvm",
2093         &kvm_chardev_ops,
2094 };
2095
2096 static void hardware_enable_nolock(void *junk)
2097 {
2098         int cpu = raw_smp_processor_id();
2099         int r;
2100
2101         if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
2102                 return;
2103
2104         cpumask_set_cpu(cpu, cpus_hardware_enabled);
2105
2106         r = kvm_arch_hardware_enable(NULL);
2107
2108         if (r) {
2109                 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
2110                 atomic_inc(&hardware_enable_failed);
2111                 printk(KERN_INFO "kvm: enabling virtualization on "
2112                                  "CPU%d failed\n", cpu);
2113         }
2114 }
2115
2116 static void hardware_enable(void *junk)
2117 {
2118         spin_lock(&kvm_lock);
2119         hardware_enable_nolock(junk);
2120         spin_unlock(&kvm_lock);
2121 }
2122
2123 static void hardware_disable_nolock(void *junk)
2124 {
2125         int cpu = raw_smp_processor_id();
2126
2127         if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
2128                 return;
2129         cpumask_clear_cpu(cpu, cpus_hardware_enabled);
2130         kvm_arch_hardware_disable(NULL);
2131 }
2132
2133 static void hardware_disable(void *junk)
2134 {
2135         spin_lock(&kvm_lock);
2136         hardware_disable_nolock(junk);
2137         spin_unlock(&kvm_lock);
2138 }
2139
2140 static void hardware_disable_all_nolock(void)
2141 {
2142         BUG_ON(!kvm_usage_count);
2143
2144         kvm_usage_count--;
2145         if (!kvm_usage_count)
2146                 on_each_cpu(hardware_disable_nolock, NULL, 1);
2147 }
2148
2149 static void hardware_disable_all(void)
2150 {
2151         spin_lock(&kvm_lock);
2152         hardware_disable_all_nolock();
2153         spin_unlock(&kvm_lock);
2154 }
2155
2156 static int hardware_enable_all(void)
2157 {
2158         int r = 0;
2159
2160         spin_lock(&kvm_lock);
2161
2162         kvm_usage_count++;
2163         if (kvm_usage_count == 1) {
2164                 atomic_set(&hardware_enable_failed, 0);
2165                 on_each_cpu(hardware_enable_nolock, NULL, 1);
2166
2167                 if (atomic_read(&hardware_enable_failed)) {
2168                         hardware_disable_all_nolock();
2169                         r = -EBUSY;
2170                 }
2171         }
2172
2173         spin_unlock(&kvm_lock);
2174
2175         return r;
2176 }
2177
2178 static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
2179                            void *v)
2180 {
2181         int cpu = (long)v;
2182
2183         if (!kvm_usage_count)
2184                 return NOTIFY_OK;
2185
2186         val &= ~CPU_TASKS_FROZEN;
2187         switch (val) {
2188         case CPU_DYING:
2189                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
2190                        cpu);
2191                 hardware_disable(NULL);
2192                 break;
2193         case CPU_STARTING:
2194                 printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
2195                        cpu);
2196                 hardware_enable(NULL);
2197                 break;
2198         }
2199         return NOTIFY_OK;
2200 }
2201
2202
2203 asmlinkage void kvm_spurious_fault(void)
2204 {
2205         /* Fault while not rebooting.  We want the trace. */
2206         BUG();
2207 }
2208 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
2209
2210 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
2211                       void *v)
2212 {
2213         /*
2214          * Some (well, at least mine) BIOSes hang on reboot if
2215          * in vmx root mode.
2216          *
2217          * And Intel TXT required VMX off for all cpu when system shutdown.
2218          */
2219         printk(KERN_INFO "kvm: exiting hardware virtualization\n");
2220         kvm_rebooting = true;
2221         on_each_cpu(hardware_disable_nolock, NULL, 1);
2222         return NOTIFY_OK;
2223 }
2224
2225 static struct notifier_block kvm_reboot_notifier = {
2226         .notifier_call = kvm_reboot,
2227         .priority = 0,
2228 };
2229
2230 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
2231 {
2232         int i;
2233
2234         for (i = 0; i < bus->dev_count; i++) {
2235                 struct kvm_io_device *pos = bus->devs[i];
2236
2237                 kvm_iodevice_destructor(pos);
2238         }
2239         kfree(bus);
2240 }
2241
2242 /* kvm_io_bus_write - called under kvm->slots_lock */
2243 int kvm_io_bus_write(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
2244                      int len, const void *val)
2245 {
2246         int i;
2247         struct kvm_io_bus *bus;
2248
2249         bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
2250         for (i = 0; i < bus->dev_count; i++)
2251                 if (!kvm_iodevice_write(bus->devs[i], addr, len, val))
2252                         return 0;
2253         return -EOPNOTSUPP;
2254 }
2255
2256 /* kvm_io_bus_read - called under kvm->slots_lock */
2257 int kvm_io_bus_read(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
2258                     int len, void *val)
2259 {
2260         int i;
2261         struct kvm_io_bus *bus;
2262
2263         bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
2264         for (i = 0; i < bus->dev_count; i++)
2265                 if (!kvm_iodevice_read(bus->devs[i], addr, len, val))
2266                         return 0;
2267         return -EOPNOTSUPP;
2268 }
2269
2270 /* Caller must hold slots_lock. */
2271 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx,
2272                             struct kvm_io_device *dev)
2273 {
2274         struct kvm_io_bus *new_bus, *bus;
2275
2276         bus = kvm->buses[bus_idx];
2277         if (bus->dev_count > NR_IOBUS_DEVS-1)
2278                 return -ENOSPC;
2279
2280         new_bus = kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL);
2281         if (!new_bus)
2282                 return -ENOMEM;
2283         memcpy(new_bus, bus, sizeof(struct kvm_io_bus));
2284         new_bus->devs[new_bus->dev_count++] = dev;
2285         rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
2286         synchronize_srcu_expedited(&kvm->srcu);
2287         kfree(bus);
2288
2289         return 0;
2290 }
2291
2292 /* Caller must hold slots_lock. */
2293 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
2294                               struct kvm_io_device *dev)
2295 {
2296         int i, r;
2297         struct kvm_io_bus *new_bus, *bus;
2298
2299         new_bus = kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL);
2300         if (!new_bus)
2301                 return -ENOMEM;
2302
2303         bus = kvm->buses[bus_idx];
2304         memcpy(new_bus, bus, sizeof(struct kvm_io_bus));
2305
2306         r = -ENOENT;
2307         for (i = 0; i < new_bus->dev_count; i++)
2308                 if (new_bus->devs[i] == dev) {
2309                         r = 0;
2310                         new_bus->devs[i] = new_bus->devs[--new_bus->dev_count];
2311                         break;
2312                 }
2313
2314         if (r) {
2315                 kfree(new_bus);
2316                 return r;
2317         }
2318
2319         rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
2320         synchronize_srcu_expedited(&kvm->srcu);
2321         kfree(bus);
2322         return r;
2323 }
2324
2325 static struct notifier_block kvm_cpu_notifier = {
2326         .notifier_call = kvm_cpu_hotplug,
2327 };
2328
2329 static int vm_stat_get(void *_offset, u64 *val)
2330 {
2331         unsigned offset = (long)_offset;
2332         struct kvm *kvm;
2333
2334         *val = 0;
2335         spin_lock(&kvm_lock);
2336         list_for_each_entry(kvm, &vm_list, vm_list)
2337                 *val += *(u32 *)((void *)kvm + offset);
2338         spin_unlock(&kvm_lock);
2339         return 0;
2340 }
2341
2342 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
2343
2344 static int vcpu_stat_get(void *_offset, u64 *val)
2345 {
2346         unsigned offset = (long)_offset;
2347         struct kvm *kvm;
2348         struct kvm_vcpu *vcpu;
2349         int i;
2350
2351         *val = 0;
2352         spin_lock(&kvm_lock);
2353         list_for_each_entry(kvm, &vm_list, vm_list)
2354                 kvm_for_each_vcpu(i, vcpu, kvm)
2355                         *val += *(u32 *)((void *)vcpu + offset);
2356
2357         spin_unlock(&kvm_lock);
2358         return 0;
2359 }
2360
2361 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
2362
2363 static const struct file_operations *stat_fops[] = {
2364         [KVM_STAT_VCPU] = &vcpu_stat_fops,
2365         [KVM_STAT_VM]   = &vm_stat_fops,
2366 };
2367
2368 static void kvm_init_debug(void)
2369 {
2370         struct kvm_stats_debugfs_item *p;
2371
2372         kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
2373         for (p = debugfs_entries; p->name; ++p)
2374                 p->dentry = debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
2375                                                 (void *)(long)p->offset,
2376                                                 stat_fops[p->kind]);
2377 }
2378
2379 static void kvm_exit_debug(void)
2380 {
2381         struct kvm_stats_debugfs_item *p;
2382
2383         for (p = debugfs_entries; p->name; ++p)
2384                 debugfs_remove(p->dentry);
2385         debugfs_remove(kvm_debugfs_dir);
2386 }
2387
2388 static int kvm_suspend(struct sys_device *dev, pm_message_t state)
2389 {
2390         if (kvm_usage_count)
2391                 hardware_disable_nolock(NULL);
2392         return 0;
2393 }
2394
2395 static int kvm_resume(struct sys_device *dev)
2396 {
2397         if (kvm_usage_count) {
2398                 WARN_ON(spin_is_locked(&kvm_lock));
2399                 hardware_enable_nolock(NULL);
2400         }
2401         return 0;
2402 }
2403
2404 static struct sysdev_class kvm_sysdev_class = {
2405         .name = "kvm",
2406         .suspend = kvm_suspend,
2407         .resume = kvm_resume,
2408 };
2409
2410 static struct sys_device kvm_sysdev = {
2411         .id = 0,
2412         .cls = &kvm_sysdev_class,
2413 };
2414
2415 struct page *bad_page;
2416 pfn_t bad_pfn;
2417
2418 static inline
2419 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
2420 {
2421         return container_of(pn, struct kvm_vcpu, preempt_notifier);
2422 }
2423
2424 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
2425 {
2426         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
2427
2428         kvm_arch_vcpu_load(vcpu, cpu);
2429 }
2430
2431 static void kvm_sched_out(struct preempt_notifier *pn,
2432                           struct task_struct *next)
2433 {
2434         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
2435
2436         kvm_arch_vcpu_put(vcpu);
2437 }
2438
2439 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
2440                   struct module *module)
2441 {
2442         int r;
2443         int cpu;
2444
2445         r = kvm_arch_init(opaque);
2446         if (r)
2447                 goto out_fail;
2448
2449         bad_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2450
2451         if (bad_page == NULL) {
2452                 r = -ENOMEM;
2453                 goto out;
2454         }
2455
2456         bad_pfn = page_to_pfn(bad_page);
2457
2458         hwpoison_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2459
2460         if (hwpoison_page == NULL) {
2461                 r = -ENOMEM;
2462                 goto out_free_0;
2463         }
2464
2465         hwpoison_pfn = page_to_pfn(hwpoison_page);
2466
2467         fault_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2468
2469         if (fault_page == NULL) {
2470                 r = -ENOMEM;
2471                 goto out_free_0;
2472         }
2473
2474         fault_pfn = page_to_pfn(fault_page);
2475
2476         if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
2477                 r = -ENOMEM;
2478                 goto out_free_0;
2479         }
2480
2481         r = kvm_arch_hardware_setup();
2482         if (r < 0)
2483                 goto out_free_0a;
2484
2485         for_each_online_cpu(cpu) {
2486                 smp_call_function_single(cpu,
2487                                 kvm_arch_check_processor_compat,
2488                                 &r, 1);
2489                 if (r < 0)
2490                         goto out_free_1;
2491         }
2492
2493         r = register_cpu_notifier(&kvm_cpu_notifier);
2494         if (r)
2495                 goto out_free_2;
2496         register_reboot_notifier(&kvm_reboot_notifier);
2497
2498         r = sysdev_class_register(&kvm_sysdev_class);
2499         if (r)
2500                 goto out_free_3;
2501
2502         r = sysdev_register(&kvm_sysdev);
2503         if (r)
2504                 goto out_free_4;
2505
2506         /* A kmem cache lets us meet the alignment requirements of fx_save. */
2507         if (!vcpu_align)
2508                 vcpu_align = __alignof__(struct kvm_vcpu);
2509         kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size, vcpu_align,
2510                                            0, NULL);
2511         if (!kvm_vcpu_cache) {
2512                 r = -ENOMEM;
2513                 goto out_free_5;
2514         }
2515
2516         r = kvm_async_pf_init();
2517         if (r)
2518                 goto out_free;
2519
2520         kvm_chardev_ops.owner = module;
2521         kvm_vm_fops.owner = module;
2522         kvm_vcpu_fops.owner = module;
2523
2524         r = misc_register(&kvm_dev);
2525         if (r) {
2526                 printk(KERN_ERR "kvm: misc device register failed\n");
2527                 goto out_unreg;
2528         }
2529
2530         kvm_preempt_ops.sched_in = kvm_sched_in;
2531         kvm_preempt_ops.sched_out = kvm_sched_out;
2532
2533         kvm_init_debug();
2534
2535         return 0;
2536
2537 out_unreg:
2538         kvm_async_pf_deinit();
2539 out_free:
2540         kmem_cache_destroy(kvm_vcpu_cache);
2541 out_free_5:
2542         sysdev_unregister(&kvm_sysdev);
2543 out_free_4:
2544         sysdev_class_unregister(&kvm_sysdev_class);
2545 out_free_3:
2546         unregister_reboot_notifier(&kvm_reboot_notifier);
2547         unregister_cpu_notifier(&kvm_cpu_notifier);
2548 out_free_2:
2549 out_free_1:
2550         kvm_arch_hardware_unsetup();
2551 out_free_0a:
2552         free_cpumask_var(cpus_hardware_enabled);
2553 out_free_0:
2554         if (fault_page)
2555                 __free_page(fault_page);
2556         if (hwpoison_page)
2557                 __free_page(hwpoison_page);
2558         __free_page(bad_page);
2559 out:
2560         kvm_arch_exit();
2561 out_fail:
2562         return r;
2563 }
2564 EXPORT_SYMBOL_GPL(kvm_init);
2565
2566 void kvm_exit(void)
2567 {
2568         kvm_exit_debug();
2569         misc_deregister(&kvm_dev);
2570         kmem_cache_destroy(kvm_vcpu_cache);
2571         kvm_async_pf_deinit();
2572         sysdev_unregister(&kvm_sysdev);
2573         sysdev_class_unregister(&kvm_sysdev_class);
2574         unregister_reboot_notifier(&kvm_reboot_notifier);
2575         unregister_cpu_notifier(&kvm_cpu_notifier);
2576         on_each_cpu(hardware_disable_nolock, NULL, 1);
2577         kvm_arch_hardware_unsetup();
2578         kvm_arch_exit();
2579         free_cpumask_var(cpus_hardware_enabled);
2580         __free_page(hwpoison_page);
2581         __free_page(bad_page);
2582 }
2583 EXPORT_SYMBOL_GPL(kvm_exit);