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