GNU Linux-libre 4.9.309-gnu1
[releases.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 <kvm/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/syscore_ops.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 #include <linux/sort.h>
51 #include <linux/bsearch.h>
52 #include <linux/kthread.h>
53
54 #include <asm/processor.h>
55 #include <asm/io.h>
56 #include <asm/ioctl.h>
57 #include <asm/uaccess.h>
58 #include <asm/pgtable.h>
59
60 #include "coalesced_mmio.h"
61 #include "async_pf.h"
62 #include "vfio.h"
63
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/kvm.h>
66
67 /* Worst case buffer size needed for holding an integer. */
68 #define ITOA_MAX_LEN 12
69
70 MODULE_AUTHOR("Qumranet");
71 MODULE_LICENSE("GPL");
72
73 /* Architectures should define their poll value according to the halt latency */
74 static unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
75 module_param(halt_poll_ns, uint, S_IRUGO | S_IWUSR);
76
77 /* Default doubles per-vcpu halt_poll_ns. */
78 static unsigned int halt_poll_ns_grow = 2;
79 module_param(halt_poll_ns_grow, uint, S_IRUGO | S_IWUSR);
80
81 /* Default resets per-vcpu halt_poll_ns . */
82 static unsigned int halt_poll_ns_shrink;
83 module_param(halt_poll_ns_shrink, uint, S_IRUGO | S_IWUSR);
84
85 /*
86  * Ordering of locks:
87  *
88  *      kvm->lock --> kvm->slots_lock --> kvm->irq_lock
89  */
90
91 DEFINE_MUTEX(kvm_lock);
92 static DEFINE_RAW_SPINLOCK(kvm_count_lock);
93 LIST_HEAD(vm_list);
94
95 static cpumask_var_t cpus_hardware_enabled;
96 static int kvm_usage_count;
97 static atomic_t hardware_enable_failed;
98
99 struct kmem_cache *kvm_vcpu_cache;
100 EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
101
102 static __read_mostly struct preempt_ops kvm_preempt_ops;
103
104 struct dentry *kvm_debugfs_dir;
105 EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
106
107 static int kvm_debugfs_num_entries;
108 static const struct file_operations *stat_fops_per_vm[];
109
110 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
111                            unsigned long arg);
112 #ifdef CONFIG_KVM_COMPAT
113 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
114                                   unsigned long arg);
115 #endif
116 static int hardware_enable_all(void);
117 static void hardware_disable_all(void);
118
119 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
120
121 static void kvm_release_pfn_dirty(kvm_pfn_t pfn);
122 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot, gfn_t gfn);
123
124 __visible bool kvm_rebooting;
125 EXPORT_SYMBOL_GPL(kvm_rebooting);
126
127 static bool largepages_enabled = true;
128
129 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
130                 unsigned long start, unsigned long end)
131 {
132 }
133
134 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
135 {
136         /*
137          * The metadata used by is_zone_device_page() to determine whether or
138          * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
139          * the device has been pinned, e.g. by get_user_pages().  WARN if the
140          * page_count() is zero to help detect bad usage of this helper.
141          */
142         if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
143                 return false;
144
145         return is_zone_device_page(pfn_to_page(pfn));
146 }
147
148 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
149 {
150         /*
151          * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
152          * perspective they are "normal" pages, albeit with slightly different
153          * usage rules.
154          */
155         if (pfn_valid(pfn))
156                 return PageReserved(pfn_to_page(pfn)) &&
157                        !is_zero_pfn(pfn) &&
158                        !kvm_is_zone_device_pfn(pfn);
159
160         return true;
161 }
162
163 /*
164  * Switches to specified vcpu, until a matching vcpu_put()
165  */
166 int vcpu_load(struct kvm_vcpu *vcpu)
167 {
168         int cpu;
169
170         if (mutex_lock_killable(&vcpu->mutex))
171                 return -EINTR;
172         cpu = get_cpu();
173         preempt_notifier_register(&vcpu->preempt_notifier);
174         kvm_arch_vcpu_load(vcpu, cpu);
175         put_cpu();
176         return 0;
177 }
178 EXPORT_SYMBOL_GPL(vcpu_load);
179
180 void vcpu_put(struct kvm_vcpu *vcpu)
181 {
182         preempt_disable();
183         kvm_arch_vcpu_put(vcpu);
184         preempt_notifier_unregister(&vcpu->preempt_notifier);
185         preempt_enable();
186         mutex_unlock(&vcpu->mutex);
187 }
188 EXPORT_SYMBOL_GPL(vcpu_put);
189
190 static void ack_flush(void *_completed)
191 {
192 }
193
194 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
195 {
196         int i, cpu, me;
197         cpumask_var_t cpus;
198         bool called = true;
199         struct kvm_vcpu *vcpu;
200
201         zalloc_cpumask_var(&cpus, GFP_ATOMIC);
202
203         me = get_cpu();
204         kvm_for_each_vcpu(i, vcpu, kvm) {
205                 kvm_make_request(req, vcpu);
206                 cpu = vcpu->cpu;
207
208                 /* Set ->requests bit before we read ->mode. */
209                 smp_mb__after_atomic();
210
211                 if (cpus != NULL && cpu != -1 && cpu != me &&
212                       kvm_vcpu_exiting_guest_mode(vcpu) != OUTSIDE_GUEST_MODE)
213                         cpumask_set_cpu(cpu, cpus);
214         }
215         if (unlikely(cpus == NULL))
216                 smp_call_function_many(cpu_online_mask, ack_flush, NULL, 1);
217         else if (!cpumask_empty(cpus))
218                 smp_call_function_many(cpus, ack_flush, NULL, 1);
219         else
220                 called = false;
221         put_cpu();
222         free_cpumask_var(cpus);
223         return called;
224 }
225
226 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
227 void kvm_flush_remote_tlbs(struct kvm *kvm)
228 {
229         /*
230          * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
231          * kvm_make_all_cpus_request.
232          */
233         long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
234
235         /*
236          * We want to publish modifications to the page tables before reading
237          * mode. Pairs with a memory barrier in arch-specific code.
238          * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
239          * and smp_mb in walk_shadow_page_lockless_begin/end.
240          * - powerpc: smp_mb in kvmppc_prepare_to_enter.
241          *
242          * There is already an smp_mb__after_atomic() before
243          * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
244          * barrier here.
245          */
246         if (kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
247                 ++kvm->stat.remote_tlb_flush;
248         cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
249 }
250 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
251 #endif
252
253 void kvm_reload_remote_mmus(struct kvm *kvm)
254 {
255         kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
256 }
257
258 int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
259 {
260         struct page *page;
261         int r;
262
263         mutex_init(&vcpu->mutex);
264         vcpu->cpu = -1;
265         vcpu->kvm = kvm;
266         vcpu->vcpu_id = id;
267         vcpu->pid = NULL;
268         init_swait_queue_head(&vcpu->wq);
269         kvm_async_pf_vcpu_init(vcpu);
270
271         vcpu->pre_pcpu = -1;
272         INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
273
274         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
275         if (!page) {
276                 r = -ENOMEM;
277                 goto fail;
278         }
279         vcpu->run = page_address(page);
280
281         kvm_vcpu_set_in_spin_loop(vcpu, false);
282         kvm_vcpu_set_dy_eligible(vcpu, false);
283         vcpu->preempted = false;
284
285         r = kvm_arch_vcpu_init(vcpu);
286         if (r < 0)
287                 goto fail_free_run;
288         return 0;
289
290 fail_free_run:
291         free_page((unsigned long)vcpu->run);
292 fail:
293         return r;
294 }
295 EXPORT_SYMBOL_GPL(kvm_vcpu_init);
296
297 void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
298 {
299         put_pid(vcpu->pid);
300         kvm_arch_vcpu_uninit(vcpu);
301         free_page((unsigned long)vcpu->run);
302 }
303 EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
304
305 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
306 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
307 {
308         return container_of(mn, struct kvm, mmu_notifier);
309 }
310
311 static void kvm_mmu_notifier_invalidate_page(struct mmu_notifier *mn,
312                                              struct mm_struct *mm,
313                                              unsigned long address)
314 {
315         struct kvm *kvm = mmu_notifier_to_kvm(mn);
316         int need_tlb_flush, idx;
317
318         /*
319          * When ->invalidate_page runs, the linux pte has been zapped
320          * already but the page is still allocated until
321          * ->invalidate_page returns. So if we increase the sequence
322          * here the kvm page fault will notice if the spte can't be
323          * established because the page is going to be freed. If
324          * instead the kvm page fault establishes the spte before
325          * ->invalidate_page runs, kvm_unmap_hva will release it
326          * before returning.
327          *
328          * The sequence increase only need to be seen at spin_unlock
329          * time, and not at spin_lock time.
330          *
331          * Increasing the sequence after the spin_unlock would be
332          * unsafe because the kvm page fault could then establish the
333          * pte after kvm_unmap_hva returned, without noticing the page
334          * is going to be freed.
335          */
336         idx = srcu_read_lock(&kvm->srcu);
337         spin_lock(&kvm->mmu_lock);
338
339         kvm->mmu_notifier_seq++;
340         need_tlb_flush = kvm_unmap_hva(kvm, address) | kvm->tlbs_dirty;
341         /* we've to flush the tlb before the pages can be freed */
342         if (need_tlb_flush)
343                 kvm_flush_remote_tlbs(kvm);
344
345         spin_unlock(&kvm->mmu_lock);
346
347         kvm_arch_mmu_notifier_invalidate_page(kvm, address);
348
349         srcu_read_unlock(&kvm->srcu, idx);
350 }
351
352 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
353                                         struct mm_struct *mm,
354                                         unsigned long address,
355                                         pte_t pte)
356 {
357         struct kvm *kvm = mmu_notifier_to_kvm(mn);
358         int idx;
359
360         idx = srcu_read_lock(&kvm->srcu);
361         spin_lock(&kvm->mmu_lock);
362         kvm->mmu_notifier_seq++;
363         kvm_set_spte_hva(kvm, address, pte);
364         spin_unlock(&kvm->mmu_lock);
365         srcu_read_unlock(&kvm->srcu, idx);
366 }
367
368 static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
369                                                     struct mm_struct *mm,
370                                                     unsigned long start,
371                                                     unsigned long end)
372 {
373         struct kvm *kvm = mmu_notifier_to_kvm(mn);
374         int need_tlb_flush = 0, idx;
375
376         idx = srcu_read_lock(&kvm->srcu);
377         spin_lock(&kvm->mmu_lock);
378         /*
379          * The count increase must become visible at unlock time as no
380          * spte can be established without taking the mmu_lock and
381          * count is also read inside the mmu_lock critical section.
382          */
383         kvm->mmu_notifier_count++;
384         need_tlb_flush = kvm_unmap_hva_range(kvm, start, end);
385         /* we've to flush the tlb before the pages can be freed */
386         if (need_tlb_flush || kvm->tlbs_dirty)
387                 kvm_flush_remote_tlbs(kvm);
388
389         spin_unlock(&kvm->mmu_lock);
390
391         kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
392
393         srcu_read_unlock(&kvm->srcu, idx);
394 }
395
396 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
397                                                   struct mm_struct *mm,
398                                                   unsigned long start,
399                                                   unsigned long end)
400 {
401         struct kvm *kvm = mmu_notifier_to_kvm(mn);
402
403         spin_lock(&kvm->mmu_lock);
404         /*
405          * This sequence increase will notify the kvm page fault that
406          * the page that is going to be mapped in the spte could have
407          * been freed.
408          */
409         kvm->mmu_notifier_seq++;
410         smp_wmb();
411         /*
412          * The above sequence increase must be visible before the
413          * below count decrease, which is ensured by the smp_wmb above
414          * in conjunction with the smp_rmb in mmu_notifier_retry().
415          */
416         kvm->mmu_notifier_count--;
417         spin_unlock(&kvm->mmu_lock);
418
419         BUG_ON(kvm->mmu_notifier_count < 0);
420 }
421
422 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
423                                               struct mm_struct *mm,
424                                               unsigned long start,
425                                               unsigned long end)
426 {
427         struct kvm *kvm = mmu_notifier_to_kvm(mn);
428         int young, idx;
429
430         idx = srcu_read_lock(&kvm->srcu);
431         spin_lock(&kvm->mmu_lock);
432
433         young = kvm_age_hva(kvm, start, end);
434         if (young)
435                 kvm_flush_remote_tlbs(kvm);
436
437         spin_unlock(&kvm->mmu_lock);
438         srcu_read_unlock(&kvm->srcu, idx);
439
440         return young;
441 }
442
443 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
444                                         struct mm_struct *mm,
445                                         unsigned long start,
446                                         unsigned long end)
447 {
448         struct kvm *kvm = mmu_notifier_to_kvm(mn);
449         int young, idx;
450
451         idx = srcu_read_lock(&kvm->srcu);
452         spin_lock(&kvm->mmu_lock);
453         /*
454          * Even though we do not flush TLB, this will still adversely
455          * affect performance on pre-Haswell Intel EPT, where there is
456          * no EPT Access Bit to clear so that we have to tear down EPT
457          * tables instead. If we find this unacceptable, we can always
458          * add a parameter to kvm_age_hva so that it effectively doesn't
459          * do anything on clear_young.
460          *
461          * Also note that currently we never issue secondary TLB flushes
462          * from clear_young, leaving this job up to the regular system
463          * cadence. If we find this inaccurate, we might come up with a
464          * more sophisticated heuristic later.
465          */
466         young = kvm_age_hva(kvm, start, end);
467         spin_unlock(&kvm->mmu_lock);
468         srcu_read_unlock(&kvm->srcu, idx);
469
470         return young;
471 }
472
473 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
474                                        struct mm_struct *mm,
475                                        unsigned long address)
476 {
477         struct kvm *kvm = mmu_notifier_to_kvm(mn);
478         int young, idx;
479
480         idx = srcu_read_lock(&kvm->srcu);
481         spin_lock(&kvm->mmu_lock);
482         young = kvm_test_age_hva(kvm, address);
483         spin_unlock(&kvm->mmu_lock);
484         srcu_read_unlock(&kvm->srcu, idx);
485
486         return young;
487 }
488
489 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
490                                      struct mm_struct *mm)
491 {
492         struct kvm *kvm = mmu_notifier_to_kvm(mn);
493         int idx;
494
495         idx = srcu_read_lock(&kvm->srcu);
496         kvm_arch_flush_shadow_all(kvm);
497         srcu_read_unlock(&kvm->srcu, idx);
498 }
499
500 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
501         .invalidate_page        = kvm_mmu_notifier_invalidate_page,
502         .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
503         .invalidate_range_end   = kvm_mmu_notifier_invalidate_range_end,
504         .clear_flush_young      = kvm_mmu_notifier_clear_flush_young,
505         .clear_young            = kvm_mmu_notifier_clear_young,
506         .test_young             = kvm_mmu_notifier_test_young,
507         .change_pte             = kvm_mmu_notifier_change_pte,
508         .release                = kvm_mmu_notifier_release,
509 };
510
511 static int kvm_init_mmu_notifier(struct kvm *kvm)
512 {
513         kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
514         return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
515 }
516
517 #else  /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
518
519 static int kvm_init_mmu_notifier(struct kvm *kvm)
520 {
521         return 0;
522 }
523
524 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
525
526 static struct kvm_memslots *kvm_alloc_memslots(void)
527 {
528         int i;
529         struct kvm_memslots *slots;
530
531         slots = kvm_kvzalloc(sizeof(struct kvm_memslots));
532         if (!slots)
533                 return NULL;
534
535         /*
536          * Init kvm generation close to the maximum to easily test the
537          * code of handling generation number wrap-around.
538          */
539         slots->generation = -150;
540         for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
541                 slots->id_to_index[i] = slots->memslots[i].id = i;
542
543         return slots;
544 }
545
546 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
547 {
548         if (!memslot->dirty_bitmap)
549                 return;
550
551         kvfree(memslot->dirty_bitmap);
552         memslot->dirty_bitmap = NULL;
553 }
554
555 /*
556  * Free any memory in @free but not in @dont.
557  */
558 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
559                               struct kvm_memory_slot *dont)
560 {
561         if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
562                 kvm_destroy_dirty_bitmap(free);
563
564         kvm_arch_free_memslot(kvm, free, dont);
565
566         free->npages = 0;
567 }
568
569 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
570 {
571         struct kvm_memory_slot *memslot;
572
573         if (!slots)
574                 return;
575
576         kvm_for_each_memslot(memslot, slots)
577                 kvm_free_memslot(kvm, memslot, NULL);
578
579         kvfree(slots);
580 }
581
582 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
583 {
584         int i;
585
586         if (!kvm->debugfs_dentry)
587                 return;
588
589         debugfs_remove_recursive(kvm->debugfs_dentry);
590
591         if (kvm->debugfs_stat_data) {
592                 for (i = 0; i < kvm_debugfs_num_entries; i++)
593                         kfree(kvm->debugfs_stat_data[i]);
594                 kfree(kvm->debugfs_stat_data);
595         }
596 }
597
598 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
599 {
600         char dir_name[ITOA_MAX_LEN * 2];
601         struct kvm_stat_data *stat_data;
602         struct kvm_stats_debugfs_item *p;
603
604         if (!debugfs_initialized())
605                 return 0;
606
607         snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
608         kvm->debugfs_dentry = debugfs_create_dir(dir_name,
609                                                  kvm_debugfs_dir);
610         if (!kvm->debugfs_dentry)
611                 return -ENOMEM;
612
613         kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
614                                          sizeof(*kvm->debugfs_stat_data),
615                                          GFP_KERNEL);
616         if (!kvm->debugfs_stat_data)
617                 return -ENOMEM;
618
619         for (p = debugfs_entries; p->name; p++) {
620                 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL);
621                 if (!stat_data)
622                         return -ENOMEM;
623
624                 stat_data->kvm = kvm;
625                 stat_data->offset = p->offset;
626                 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
627                 if (!debugfs_create_file(p->name, 0444,
628                                          kvm->debugfs_dentry,
629                                          stat_data,
630                                          stat_fops_per_vm[p->kind]))
631                         return -ENOMEM;
632         }
633         return 0;
634 }
635
636 /*
637  * Called after the VM is otherwise initialized, but just before adding it to
638  * the vm_list.
639  */
640 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
641 {
642         return 0;
643 }
644
645 /*
646  * Called just after removing the VM from the vm_list, but before doing any
647  * other destruction.
648  */
649 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
650 {
651 }
652
653 static struct kvm *kvm_create_vm(unsigned long type)
654 {
655         int r, i;
656         struct kvm *kvm = kvm_arch_alloc_vm();
657
658         if (!kvm)
659                 return ERR_PTR(-ENOMEM);
660
661         spin_lock_init(&kvm->mmu_lock);
662         atomic_inc(&current->mm->mm_count);
663         kvm->mm = current->mm;
664         kvm_eventfd_init(kvm);
665         mutex_init(&kvm->lock);
666         mutex_init(&kvm->irq_lock);
667         mutex_init(&kvm->slots_lock);
668         atomic_set(&kvm->users_count, 1);
669         INIT_LIST_HEAD(&kvm->devices);
670
671         r = kvm_arch_init_vm(kvm, type);
672         if (r)
673                 goto out_err_no_disable;
674
675         r = hardware_enable_all();
676         if (r)
677                 goto out_err_no_disable;
678
679 #ifdef CONFIG_HAVE_KVM_IRQFD
680         INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
681 #endif
682
683         BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
684
685         r = -ENOMEM;
686         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
687                 kvm->memslots[i] = kvm_alloc_memslots();
688                 if (!kvm->memslots[i])
689                         goto out_err_no_srcu;
690         }
691
692         if (init_srcu_struct(&kvm->srcu))
693                 goto out_err_no_srcu;
694         if (init_srcu_struct(&kvm->irq_srcu))
695                 goto out_err_no_irq_srcu;
696         for (i = 0; i < KVM_NR_BUSES; i++) {
697                 kvm->buses[i] = kzalloc(sizeof(struct kvm_io_bus),
698                                         GFP_KERNEL);
699                 if (!kvm->buses[i])
700                         goto out_err_no_mmu_notifier;
701         }
702
703         r = kvm_init_mmu_notifier(kvm);
704         if (r)
705                 goto out_err_no_mmu_notifier;
706
707         r = kvm_arch_post_init_vm(kvm);
708         if (r)
709                 goto out_err;
710
711         mutex_lock(&kvm_lock);
712         list_add(&kvm->vm_list, &vm_list);
713         mutex_unlock(&kvm_lock);
714
715         preempt_notifier_inc();
716
717         return kvm;
718
719 out_err:
720 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
721         if (kvm->mmu_notifier.ops)
722                 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
723 #endif
724 out_err_no_mmu_notifier:
725         cleanup_srcu_struct(&kvm->irq_srcu);
726 out_err_no_irq_srcu:
727         cleanup_srcu_struct(&kvm->srcu);
728 out_err_no_srcu:
729         hardware_disable_all();
730 out_err_no_disable:
731         for (i = 0; i < KVM_NR_BUSES; i++)
732                 kfree(kvm->buses[i]);
733         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
734                 kvm_free_memslots(kvm, kvm->memslots[i]);
735         kvm_arch_free_vm(kvm);
736         mmdrop(current->mm);
737         return ERR_PTR(r);
738 }
739
740 /*
741  * Avoid using vmalloc for a small buffer.
742  * Should not be used when the size is statically known.
743  */
744 void *kvm_kvzalloc(unsigned long size)
745 {
746         if (size > PAGE_SIZE)
747                 return vzalloc(size);
748         else
749                 return kzalloc(size, GFP_KERNEL);
750 }
751
752 static void kvm_destroy_devices(struct kvm *kvm)
753 {
754         struct kvm_device *dev, *tmp;
755
756         /*
757          * We do not need to take the kvm->lock here, because nobody else
758          * has a reference to the struct kvm at this point and therefore
759          * cannot access the devices list anyhow.
760          */
761         list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
762                 list_del(&dev->vm_node);
763                 dev->ops->destroy(dev);
764         }
765 }
766
767 static void kvm_destroy_vm(struct kvm *kvm)
768 {
769         int i;
770         struct mm_struct *mm = kvm->mm;
771
772         kvm_destroy_vm_debugfs(kvm);
773         kvm_arch_sync_events(kvm);
774         mutex_lock(&kvm_lock);
775         list_del(&kvm->vm_list);
776         mutex_unlock(&kvm_lock);
777         kvm_arch_pre_destroy_vm(kvm);
778
779         kvm_free_irq_routing(kvm);
780         for (i = 0; i < KVM_NR_BUSES; i++) {
781                 if (kvm->buses[i])
782                         kvm_io_bus_destroy(kvm->buses[i]);
783                 kvm->buses[i] = NULL;
784         }
785         kvm_coalesced_mmio_free(kvm);
786 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
787         mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
788 #else
789         kvm_arch_flush_shadow_all(kvm);
790 #endif
791         kvm_arch_destroy_vm(kvm);
792         kvm_destroy_devices(kvm);
793         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
794                 kvm_free_memslots(kvm, kvm->memslots[i]);
795         cleanup_srcu_struct(&kvm->irq_srcu);
796         cleanup_srcu_struct(&kvm->srcu);
797         kvm_arch_free_vm(kvm);
798         preempt_notifier_dec();
799         hardware_disable_all();
800         mmdrop(mm);
801 }
802
803 void kvm_get_kvm(struct kvm *kvm)
804 {
805         atomic_inc(&kvm->users_count);
806 }
807 EXPORT_SYMBOL_GPL(kvm_get_kvm);
808
809 void kvm_put_kvm(struct kvm *kvm)
810 {
811         if (atomic_dec_and_test(&kvm->users_count))
812                 kvm_destroy_vm(kvm);
813 }
814 EXPORT_SYMBOL_GPL(kvm_put_kvm);
815
816
817 static int kvm_vm_release(struct inode *inode, struct file *filp)
818 {
819         struct kvm *kvm = filp->private_data;
820
821         kvm_irqfd_release(kvm);
822
823         kvm_put_kvm(kvm);
824         return 0;
825 }
826
827 /*
828  * Allocation size is twice as large as the actual dirty bitmap size.
829  * See x86's kvm_vm_ioctl_get_dirty_log() why this is needed.
830  */
831 static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
832 {
833         unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
834
835         memslot->dirty_bitmap = kvm_kvzalloc(dirty_bytes);
836         if (!memslot->dirty_bitmap)
837                 return -ENOMEM;
838
839         return 0;
840 }
841
842 /*
843  * Insert memslot and re-sort memslots based on their GFN,
844  * so binary search could be used to lookup GFN.
845  * Sorting algorithm takes advantage of having initially
846  * sorted array and known changed memslot position.
847  */
848 static void update_memslots(struct kvm_memslots *slots,
849                             struct kvm_memory_slot *new)
850 {
851         int id = new->id;
852         int i = slots->id_to_index[id];
853         struct kvm_memory_slot *mslots = slots->memslots;
854
855         WARN_ON(mslots[i].id != id);
856         if (!new->npages) {
857                 WARN_ON(!mslots[i].npages);
858                 if (mslots[i].npages)
859                         slots->used_slots--;
860         } else {
861                 if (!mslots[i].npages)
862                         slots->used_slots++;
863         }
864
865         while (i < KVM_MEM_SLOTS_NUM - 1 &&
866                new->base_gfn <= mslots[i + 1].base_gfn) {
867                 if (!mslots[i + 1].npages)
868                         break;
869                 mslots[i] = mslots[i + 1];
870                 slots->id_to_index[mslots[i].id] = i;
871                 i++;
872         }
873
874         /*
875          * The ">=" is needed when creating a slot with base_gfn == 0,
876          * so that it moves before all those with base_gfn == npages == 0.
877          *
878          * On the other hand, if new->npages is zero, the above loop has
879          * already left i pointing to the beginning of the empty part of
880          * mslots, and the ">=" would move the hole backwards in this
881          * case---which is wrong.  So skip the loop when deleting a slot.
882          */
883         if (new->npages) {
884                 while (i > 0 &&
885                        new->base_gfn >= mslots[i - 1].base_gfn) {
886                         mslots[i] = mslots[i - 1];
887                         slots->id_to_index[mslots[i].id] = i;
888                         i--;
889                 }
890         } else
891                 WARN_ON_ONCE(i != slots->used_slots);
892
893         mslots[i] = *new;
894         slots->id_to_index[mslots[i].id] = i;
895 }
896
897 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
898 {
899         u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
900
901 #ifdef __KVM_HAVE_READONLY_MEM
902         valid_flags |= KVM_MEM_READONLY;
903 #endif
904
905         if (mem->flags & ~valid_flags)
906                 return -EINVAL;
907
908         return 0;
909 }
910
911 static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
912                 int as_id, struct kvm_memslots *slots)
913 {
914         struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
915
916         /*
917          * Set the low bit in the generation, which disables SPTE caching
918          * until the end of synchronize_srcu_expedited.
919          */
920         WARN_ON(old_memslots->generation & 1);
921         slots->generation = old_memslots->generation + 1;
922
923         rcu_assign_pointer(kvm->memslots[as_id], slots);
924         synchronize_srcu_expedited(&kvm->srcu);
925
926         /*
927          * Increment the new memslot generation a second time. This prevents
928          * vm exits that race with memslot updates from caching a memslot
929          * generation that will (potentially) be valid forever.
930          */
931         slots->generation++;
932
933         kvm_arch_memslots_updated(kvm, slots);
934
935         return old_memslots;
936 }
937
938 /*
939  * Allocate some memory and give it an address in the guest physical address
940  * space.
941  *
942  * Discontiguous memory is allowed, mostly for framebuffers.
943  *
944  * Must be called holding kvm->slots_lock for write.
945  */
946 int __kvm_set_memory_region(struct kvm *kvm,
947                             const struct kvm_userspace_memory_region *mem)
948 {
949         int r;
950         gfn_t base_gfn;
951         unsigned long npages;
952         struct kvm_memory_slot *slot;
953         struct kvm_memory_slot old, new;
954         struct kvm_memslots *slots = NULL, *old_memslots;
955         int as_id, id;
956         enum kvm_mr_change change;
957
958         r = check_memory_region_flags(mem);
959         if (r)
960                 goto out;
961
962         r = -EINVAL;
963         as_id = mem->slot >> 16;
964         id = (u16)mem->slot;
965
966         /* General sanity checks */
967         if (mem->memory_size & (PAGE_SIZE - 1))
968                 goto out;
969         if (mem->guest_phys_addr & (PAGE_SIZE - 1))
970                 goto out;
971         /* We can read the guest memory with __xxx_user() later on. */
972         if ((id < KVM_USER_MEM_SLOTS) &&
973             ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
974              !access_ok(VERIFY_WRITE,
975                         (void __user *)(unsigned long)mem->userspace_addr,
976                         mem->memory_size)))
977                 goto out;
978         if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
979                 goto out;
980         if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
981                 goto out;
982
983         slot = id_to_memslot(__kvm_memslots(kvm, as_id), id);
984         base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
985         npages = mem->memory_size >> PAGE_SHIFT;
986
987         if (npages > KVM_MEM_MAX_NR_PAGES)
988                 goto out;
989
990         new = old = *slot;
991
992         new.id = id;
993         new.base_gfn = base_gfn;
994         new.npages = npages;
995         new.flags = mem->flags;
996
997         if (npages) {
998                 if (!old.npages)
999                         change = KVM_MR_CREATE;
1000                 else { /* Modify an existing slot. */
1001                         if ((mem->userspace_addr != old.userspace_addr) ||
1002                             (npages != old.npages) ||
1003                             ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1004                                 goto out;
1005
1006                         if (base_gfn != old.base_gfn)
1007                                 change = KVM_MR_MOVE;
1008                         else if (new.flags != old.flags)
1009                                 change = KVM_MR_FLAGS_ONLY;
1010                         else { /* Nothing to change. */
1011                                 r = 0;
1012                                 goto out;
1013                         }
1014                 }
1015         } else {
1016                 if (!old.npages)
1017                         goto out;
1018
1019                 change = KVM_MR_DELETE;
1020                 new.base_gfn = 0;
1021                 new.flags = 0;
1022         }
1023
1024         if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1025                 /* Check for overlaps */
1026                 r = -EEXIST;
1027                 kvm_for_each_memslot(slot, __kvm_memslots(kvm, as_id)) {
1028                         if (slot->id == id)
1029                                 continue;
1030                         if (!((base_gfn + npages <= slot->base_gfn) ||
1031                               (base_gfn >= slot->base_gfn + slot->npages)))
1032                                 goto out;
1033                 }
1034         }
1035
1036         /* Free page dirty bitmap if unneeded */
1037         if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1038                 new.dirty_bitmap = NULL;
1039
1040         r = -ENOMEM;
1041         if (change == KVM_MR_CREATE) {
1042                 new.userspace_addr = mem->userspace_addr;
1043
1044                 if (kvm_arch_create_memslot(kvm, &new, npages))
1045                         goto out_free;
1046         }
1047
1048         /* Allocate page dirty bitmap if needed */
1049         if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
1050                 if (kvm_create_dirty_bitmap(&new) < 0)
1051                         goto out_free;
1052         }
1053
1054         slots = kvm_kvzalloc(sizeof(struct kvm_memslots));
1055         if (!slots)
1056                 goto out_free;
1057         memcpy(slots, __kvm_memslots(kvm, as_id), sizeof(struct kvm_memslots));
1058
1059         if ((change == KVM_MR_DELETE) || (change == KVM_MR_MOVE)) {
1060                 slot = id_to_memslot(slots, id);
1061                 slot->flags |= KVM_MEMSLOT_INVALID;
1062
1063                 old_memslots = install_new_memslots(kvm, as_id, slots);
1064
1065                 /* slot was deleted or moved, clear iommu mapping */
1066                 kvm_iommu_unmap_pages(kvm, &old);
1067                 /* From this point no new shadow pages pointing to a deleted,
1068                  * or moved, memslot will be created.
1069                  *
1070                  * validation of sp->gfn happens in:
1071                  *      - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1072                  *      - kvm_is_visible_gfn (mmu_check_roots)
1073                  */
1074                 kvm_arch_flush_shadow_memslot(kvm, slot);
1075
1076                 /*
1077                  * We can re-use the old_memslots from above, the only difference
1078                  * from the currently installed memslots is the invalid flag.  This
1079                  * will get overwritten by update_memslots anyway.
1080                  */
1081                 slots = old_memslots;
1082         }
1083
1084         r = kvm_arch_prepare_memory_region(kvm, &new, mem, change);
1085         if (r)
1086                 goto out_slots;
1087
1088         /* actual memory is freed via old in kvm_free_memslot below */
1089         if (change == KVM_MR_DELETE) {
1090                 new.dirty_bitmap = NULL;
1091                 memset(&new.arch, 0, sizeof(new.arch));
1092         }
1093
1094         update_memslots(slots, &new);
1095         old_memslots = install_new_memslots(kvm, as_id, slots);
1096
1097         kvm_arch_commit_memory_region(kvm, mem, &old, &new, change);
1098
1099         kvm_free_memslot(kvm, &old, &new);
1100         kvfree(old_memslots);
1101
1102         /*
1103          * IOMMU mapping:  New slots need to be mapped.  Old slots need to be
1104          * un-mapped and re-mapped if their base changes.  Since base change
1105          * unmapping is handled above with slot deletion, mapping alone is
1106          * needed here.  Anything else the iommu might care about for existing
1107          * slots (size changes, userspace addr changes and read-only flag
1108          * changes) is disallowed above, so any other attribute changes getting
1109          * here can be skipped.
1110          */
1111         if (as_id == 0 && (change == KVM_MR_CREATE || change == KVM_MR_MOVE)) {
1112                 r = kvm_iommu_map_pages(kvm, &new);
1113                 return r;
1114         }
1115
1116         return 0;
1117
1118 out_slots:
1119         kvfree(slots);
1120 out_free:
1121         kvm_free_memslot(kvm, &new, &old);
1122 out:
1123         return r;
1124 }
1125 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1126
1127 int kvm_set_memory_region(struct kvm *kvm,
1128                           const struct kvm_userspace_memory_region *mem)
1129 {
1130         int r;
1131
1132         mutex_lock(&kvm->slots_lock);
1133         r = __kvm_set_memory_region(kvm, mem);
1134         mutex_unlock(&kvm->slots_lock);
1135         return r;
1136 }
1137 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1138
1139 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1140                                           struct kvm_userspace_memory_region *mem)
1141 {
1142         if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1143                 return -EINVAL;
1144
1145         return kvm_set_memory_region(kvm, mem);
1146 }
1147
1148 int kvm_get_dirty_log(struct kvm *kvm,
1149                         struct kvm_dirty_log *log, int *is_dirty)
1150 {
1151         struct kvm_memslots *slots;
1152         struct kvm_memory_slot *memslot;
1153         int r, i, as_id, id;
1154         unsigned long n;
1155         unsigned long any = 0;
1156
1157         r = -EINVAL;
1158         as_id = log->slot >> 16;
1159         id = (u16)log->slot;
1160         if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1161                 goto out;
1162
1163         slots = __kvm_memslots(kvm, as_id);
1164         memslot = id_to_memslot(slots, id);
1165         r = -ENOENT;
1166         if (!memslot->dirty_bitmap)
1167                 goto out;
1168
1169         n = kvm_dirty_bitmap_bytes(memslot);
1170
1171         for (i = 0; !any && i < n/sizeof(long); ++i)
1172                 any = memslot->dirty_bitmap[i];
1173
1174         r = -EFAULT;
1175         if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
1176                 goto out;
1177
1178         if (any)
1179                 *is_dirty = 1;
1180
1181         r = 0;
1182 out:
1183         return r;
1184 }
1185 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1186
1187 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1188 /**
1189  * kvm_get_dirty_log_protect - get a snapshot of dirty pages, and if any pages
1190  *      are dirty write protect them for next write.
1191  * @kvm:        pointer to kvm instance
1192  * @log:        slot id and address to which we copy the log
1193  * @is_dirty:   flag set if any page is dirty
1194  *
1195  * We need to keep it in mind that VCPU threads can write to the bitmap
1196  * concurrently. So, to avoid losing track of dirty pages we keep the
1197  * following order:
1198  *
1199  *    1. Take a snapshot of the bit and clear it if needed.
1200  *    2. Write protect the corresponding page.
1201  *    3. Copy the snapshot to the userspace.
1202  *    4. Upon return caller flushes TLB's if needed.
1203  *
1204  * Between 2 and 4, the guest may write to the page using the remaining TLB
1205  * entry.  This is not a problem because the page is reported dirty using
1206  * the snapshot taken before and step 4 ensures that writes done after
1207  * exiting to userspace will be logged for the next call.
1208  *
1209  */
1210 int kvm_get_dirty_log_protect(struct kvm *kvm,
1211                         struct kvm_dirty_log *log, bool *is_dirty)
1212 {
1213         struct kvm_memslots *slots;
1214         struct kvm_memory_slot *memslot;
1215         int r, i, as_id, id;
1216         unsigned long n;
1217         unsigned long *dirty_bitmap;
1218         unsigned long *dirty_bitmap_buffer;
1219
1220         r = -EINVAL;
1221         as_id = log->slot >> 16;
1222         id = (u16)log->slot;
1223         if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1224                 goto out;
1225
1226         slots = __kvm_memslots(kvm, as_id);
1227         memslot = id_to_memslot(slots, id);
1228
1229         dirty_bitmap = memslot->dirty_bitmap;
1230         r = -ENOENT;
1231         if (!dirty_bitmap)
1232                 goto out;
1233
1234         n = kvm_dirty_bitmap_bytes(memslot);
1235
1236         dirty_bitmap_buffer = dirty_bitmap + n / sizeof(long);
1237         memset(dirty_bitmap_buffer, 0, n);
1238
1239         spin_lock(&kvm->mmu_lock);
1240         *is_dirty = false;
1241         for (i = 0; i < n / sizeof(long); i++) {
1242                 unsigned long mask;
1243                 gfn_t offset;
1244
1245                 if (!dirty_bitmap[i])
1246                         continue;
1247
1248                 *is_dirty = true;
1249
1250                 mask = xchg(&dirty_bitmap[i], 0);
1251                 dirty_bitmap_buffer[i] = mask;
1252
1253                 if (mask) {
1254                         offset = i * BITS_PER_LONG;
1255                         kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1256                                                                 offset, mask);
1257                 }
1258         }
1259
1260         spin_unlock(&kvm->mmu_lock);
1261
1262         r = -EFAULT;
1263         if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1264                 goto out;
1265
1266         r = 0;
1267 out:
1268         return r;
1269 }
1270 EXPORT_SYMBOL_GPL(kvm_get_dirty_log_protect);
1271 #endif
1272
1273 bool kvm_largepages_enabled(void)
1274 {
1275         return largepages_enabled;
1276 }
1277
1278 void kvm_disable_largepages(void)
1279 {
1280         largepages_enabled = false;
1281 }
1282 EXPORT_SYMBOL_GPL(kvm_disable_largepages);
1283
1284 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1285 {
1286         return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1287 }
1288 EXPORT_SYMBOL_GPL(gfn_to_memslot);
1289
1290 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1291 {
1292         return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1293 }
1294
1295 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1296 {
1297         struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
1298
1299         if (!memslot || memslot->id >= KVM_USER_MEM_SLOTS ||
1300               memslot->flags & KVM_MEMSLOT_INVALID)
1301                 return false;
1302
1303         return true;
1304 }
1305 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1306
1307 unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn)
1308 {
1309         struct vm_area_struct *vma;
1310         unsigned long addr, size;
1311
1312         size = PAGE_SIZE;
1313
1314         addr = gfn_to_hva(kvm, gfn);
1315         if (kvm_is_error_hva(addr))
1316                 return PAGE_SIZE;
1317
1318         down_read(&current->mm->mmap_sem);
1319         vma = find_vma(current->mm, addr);
1320         if (!vma)
1321                 goto out;
1322
1323         size = vma_kernel_pagesize(vma);
1324
1325 out:
1326         up_read(&current->mm->mmap_sem);
1327
1328         return size;
1329 }
1330
1331 static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1332 {
1333         return slot->flags & KVM_MEM_READONLY;
1334 }
1335
1336 static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1337                                        gfn_t *nr_pages, bool write)
1338 {
1339         if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1340                 return KVM_HVA_ERR_BAD;
1341
1342         if (memslot_is_readonly(slot) && write)
1343                 return KVM_HVA_ERR_RO_BAD;
1344
1345         if (nr_pages)
1346                 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1347
1348         return __gfn_to_hva_memslot(slot, gfn);
1349 }
1350
1351 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1352                                      gfn_t *nr_pages)
1353 {
1354         return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1355 }
1356
1357 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
1358                                         gfn_t gfn)
1359 {
1360         return gfn_to_hva_many(slot, gfn, NULL);
1361 }
1362 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1363
1364 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1365 {
1366         return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1367 }
1368 EXPORT_SYMBOL_GPL(gfn_to_hva);
1369
1370 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1371 {
1372         return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1373 }
1374 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1375
1376 /*
1377  * If writable is set to false, the hva returned by this function is only
1378  * allowed to be read.
1379  */
1380 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1381                                       gfn_t gfn, bool *writable)
1382 {
1383         unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1384
1385         if (!kvm_is_error_hva(hva) && writable)
1386                 *writable = !memslot_is_readonly(slot);
1387
1388         return hva;
1389 }
1390
1391 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1392 {
1393         struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1394
1395         return gfn_to_hva_memslot_prot(slot, gfn, writable);
1396 }
1397
1398 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1399 {
1400         struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1401
1402         return gfn_to_hva_memslot_prot(slot, gfn, writable);
1403 }
1404
1405 static int get_user_page_nowait(unsigned long start, int write,
1406                 struct page **page)
1407 {
1408         int flags = FOLL_NOWAIT | FOLL_HWPOISON;
1409
1410         if (write)
1411                 flags |= FOLL_WRITE;
1412
1413         return get_user_pages(start, 1, flags, page, NULL);
1414 }
1415
1416 static inline int check_user_page_hwpoison(unsigned long addr)
1417 {
1418         int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
1419
1420         rc = get_user_pages(addr, 1, flags, NULL, NULL);
1421         return rc == -EHWPOISON;
1422 }
1423
1424 /*
1425  * The atomic path to get the writable pfn which will be stored in @pfn,
1426  * true indicates success, otherwise false is returned.
1427  */
1428 static bool hva_to_pfn_fast(unsigned long addr, bool atomic, bool *async,
1429                             bool write_fault, bool *writable, kvm_pfn_t *pfn)
1430 {
1431         struct page *page[1];
1432         int npages;
1433
1434         if (!(async || atomic))
1435                 return false;
1436
1437         /*
1438          * Fast pin a writable pfn only if it is a write fault request
1439          * or the caller allows to map a writable pfn for a read fault
1440          * request.
1441          */
1442         if (!(write_fault || writable))
1443                 return false;
1444
1445         npages = __get_user_pages_fast(addr, 1, 1, page);
1446         if (npages == 1) {
1447                 *pfn = page_to_pfn(page[0]);
1448
1449                 if (writable)
1450                         *writable = true;
1451                 return true;
1452         }
1453
1454         return false;
1455 }
1456
1457 /*
1458  * The slow path to get the pfn of the specified host virtual address,
1459  * 1 indicates success, -errno is returned if error is detected.
1460  */
1461 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
1462                            bool *writable, kvm_pfn_t *pfn)
1463 {
1464         struct page *page[1];
1465         int npages = 0;
1466
1467         might_sleep();
1468
1469         if (writable)
1470                 *writable = write_fault;
1471
1472         if (async) {
1473                 down_read(&current->mm->mmap_sem);
1474                 npages = get_user_page_nowait(addr, write_fault, page);
1475                 up_read(&current->mm->mmap_sem);
1476         } else {
1477                 unsigned int flags = FOLL_TOUCH | FOLL_HWPOISON;
1478
1479                 if (write_fault)
1480                         flags |= FOLL_WRITE;
1481
1482                 npages = __get_user_pages_unlocked(current, current->mm, addr, 1,
1483                                                    page, flags);
1484         }
1485         if (npages != 1)
1486                 return npages;
1487
1488         /* map read fault as writable if possible */
1489         if (unlikely(!write_fault) && writable) {
1490                 struct page *wpage[1];
1491
1492                 npages = __get_user_pages_fast(addr, 1, 1, wpage);
1493                 if (npages == 1) {
1494                         *writable = true;
1495                         put_page(page[0]);
1496                         page[0] = wpage[0];
1497                 }
1498
1499                 npages = 1;
1500         }
1501         *pfn = page_to_pfn(page[0]);
1502         return npages;
1503 }
1504
1505 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1506 {
1507         if (unlikely(!(vma->vm_flags & VM_READ)))
1508                 return false;
1509
1510         if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1511                 return false;
1512
1513         return true;
1514 }
1515
1516 static int kvm_try_get_pfn(kvm_pfn_t pfn)
1517 {
1518         if (kvm_is_reserved_pfn(pfn))
1519                 return 1;
1520         return get_page_unless_zero(pfn_to_page(pfn));
1521 }
1522
1523 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1524                                unsigned long addr, bool *async,
1525                                bool write_fault, bool *writable,
1526                                kvm_pfn_t *p_pfn)
1527 {
1528         kvm_pfn_t pfn;
1529         pte_t *ptep;
1530         spinlock_t *ptl;
1531         int r;
1532
1533         r = follow_pte_pmd(vma->vm_mm, addr, &ptep, NULL, &ptl);
1534         if (r) {
1535                 /*
1536                  * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1537                  * not call the fault handler, so do it here.
1538                  */
1539                 bool unlocked = false;
1540                 r = fixup_user_fault(current, current->mm, addr,
1541                                      (write_fault ? FAULT_FLAG_WRITE : 0),
1542                                      &unlocked);
1543                 if (unlocked)
1544                         return -EAGAIN;
1545                 if (r)
1546                         return r;
1547
1548                 r = follow_pte_pmd(vma->vm_mm, addr, &ptep, NULL, &ptl);
1549                 if (r)
1550                         return r;
1551         }
1552
1553         if (write_fault && !pte_write(*ptep)) {
1554                 pfn = KVM_PFN_ERR_RO_FAULT;
1555                 goto out;
1556         }
1557
1558         if (writable)
1559                 *writable = pte_write(*ptep);
1560         pfn = pte_pfn(*ptep);
1561
1562         /*
1563          * Get a reference here because callers of *hva_to_pfn* and
1564          * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1565          * returned pfn.  This is only needed if the VMA has VM_MIXEDMAP
1566          * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1567          * simply do nothing for reserved pfns.
1568          *
1569          * Whoever called remap_pfn_range is also going to call e.g.
1570          * unmap_mapping_range before the underlying pages are freed,
1571          * causing a call to our MMU notifier.
1572          *
1573          * Certain IO or PFNMAP mappings can be backed with valid
1574          * struct pages, but be allocated without refcounting e.g.,
1575          * tail pages of non-compound higher order allocations, which
1576          * would then underflow the refcount when the caller does the
1577          * required put_page. Don't allow those pages here.
1578          */ 
1579         if (!kvm_try_get_pfn(pfn))
1580                 r = -EFAULT;
1581
1582 out:
1583         pte_unmap_unlock(ptep, ptl);
1584         *p_pfn = pfn;
1585
1586         return r;
1587 }
1588
1589 /*
1590  * Pin guest page in memory and return its pfn.
1591  * @addr: host virtual address which maps memory to the guest
1592  * @atomic: whether this function can sleep
1593  * @async: whether this function need to wait IO complete if the
1594  *         host page is not in the memory
1595  * @write_fault: whether we should get a writable host page
1596  * @writable: whether it allows to map a writable host page for !@write_fault
1597  *
1598  * The function will map a writable host page for these two cases:
1599  * 1): @write_fault = true
1600  * 2): @write_fault = false && @writable, @writable will tell the caller
1601  *     whether the mapping is writable.
1602  */
1603 static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
1604                         bool write_fault, bool *writable)
1605 {
1606         struct vm_area_struct *vma;
1607         kvm_pfn_t pfn = 0;
1608         int npages, r;
1609
1610         /* we can do it either atomically or asynchronously, not both */
1611         BUG_ON(atomic && async);
1612
1613         if (hva_to_pfn_fast(addr, atomic, async, write_fault, writable, &pfn))
1614                 return pfn;
1615
1616         if (atomic)
1617                 return KVM_PFN_ERR_FAULT;
1618
1619         npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
1620         if (npages == 1)
1621                 return pfn;
1622
1623         down_read(&current->mm->mmap_sem);
1624         if (npages == -EHWPOISON ||
1625               (!async && check_user_page_hwpoison(addr))) {
1626                 pfn = KVM_PFN_ERR_HWPOISON;
1627                 goto exit;
1628         }
1629
1630 retry:
1631         vma = find_vma_intersection(current->mm, addr, addr + 1);
1632
1633         if (vma == NULL)
1634                 pfn = KVM_PFN_ERR_FAULT;
1635         else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
1636                 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
1637                 if (r == -EAGAIN)
1638                         goto retry;
1639                 if (r < 0)
1640                         pfn = KVM_PFN_ERR_FAULT;
1641         } else {
1642                 if (async && vma_is_valid(vma, write_fault))
1643                         *async = true;
1644                 pfn = KVM_PFN_ERR_FAULT;
1645         }
1646 exit:
1647         up_read(&current->mm->mmap_sem);
1648         return pfn;
1649 }
1650
1651 kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
1652                                bool atomic, bool *async, bool write_fault,
1653                                bool *writable)
1654 {
1655         unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
1656
1657         if (addr == KVM_HVA_ERR_RO_BAD) {
1658                 if (writable)
1659                         *writable = false;
1660                 return KVM_PFN_ERR_RO_FAULT;
1661         }
1662
1663         if (kvm_is_error_hva(addr)) {
1664                 if (writable)
1665                         *writable = false;
1666                 return KVM_PFN_NOSLOT;
1667         }
1668
1669         /* Do not map writable pfn in the readonly memslot. */
1670         if (writable && memslot_is_readonly(slot)) {
1671                 *writable = false;
1672                 writable = NULL;
1673         }
1674
1675         return hva_to_pfn(addr, atomic, async, write_fault,
1676                           writable);
1677 }
1678 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
1679
1680 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
1681                       bool *writable)
1682 {
1683         return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
1684                                     write_fault, writable);
1685 }
1686 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1687
1688 kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
1689 {
1690         return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
1691 }
1692 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
1693
1694 kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
1695 {
1696         return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
1697 }
1698 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
1699
1700 kvm_pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
1701 {
1702         return gfn_to_pfn_memslot_atomic(gfn_to_memslot(kvm, gfn), gfn);
1703 }
1704 EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
1705
1706 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
1707 {
1708         return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1709 }
1710 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
1711
1712 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1713 {
1714         return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
1715 }
1716 EXPORT_SYMBOL_GPL(gfn_to_pfn);
1717
1718 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1719 {
1720         return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1721 }
1722 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
1723
1724 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1725                             struct page **pages, int nr_pages)
1726 {
1727         unsigned long addr;
1728         gfn_t entry;
1729
1730         addr = gfn_to_hva_many(slot, gfn, &entry);
1731         if (kvm_is_error_hva(addr))
1732                 return -1;
1733
1734         if (entry < nr_pages)
1735                 return 0;
1736
1737         return __get_user_pages_fast(addr, nr_pages, 1, pages);
1738 }
1739 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
1740
1741 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
1742 {
1743         if (is_error_noslot_pfn(pfn))
1744                 return KVM_ERR_PTR_BAD_PAGE;
1745
1746         if (kvm_is_reserved_pfn(pfn)) {
1747                 WARN_ON(1);
1748                 return KVM_ERR_PTR_BAD_PAGE;
1749         }
1750
1751         return pfn_to_page(pfn);
1752 }
1753
1754 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1755 {
1756         kvm_pfn_t pfn;
1757
1758         pfn = gfn_to_pfn(kvm, gfn);
1759
1760         return kvm_pfn_to_page(pfn);
1761 }
1762 EXPORT_SYMBOL_GPL(gfn_to_page);
1763
1764 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
1765 {
1766         kvm_pfn_t pfn;
1767
1768         pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
1769
1770         return kvm_pfn_to_page(pfn);
1771 }
1772 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
1773
1774 void kvm_release_page_clean(struct page *page)
1775 {
1776         WARN_ON(is_error_page(page));
1777
1778         kvm_release_pfn_clean(page_to_pfn(page));
1779 }
1780 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
1781
1782 void kvm_release_pfn_clean(kvm_pfn_t pfn)
1783 {
1784         if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
1785                 put_page(pfn_to_page(pfn));
1786 }
1787 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
1788
1789 void kvm_release_page_dirty(struct page *page)
1790 {
1791         WARN_ON(is_error_page(page));
1792
1793         kvm_release_pfn_dirty(page_to_pfn(page));
1794 }
1795 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
1796
1797 static void kvm_release_pfn_dirty(kvm_pfn_t pfn)
1798 {
1799         kvm_set_pfn_dirty(pfn);
1800         kvm_release_pfn_clean(pfn);
1801 }
1802
1803 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
1804 {
1805         if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn)) {
1806                 struct page *page = pfn_to_page(pfn);
1807
1808                 if (!PageReserved(page))
1809                         SetPageDirty(page);
1810         }
1811 }
1812 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
1813
1814 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
1815 {
1816         if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
1817                 mark_page_accessed(pfn_to_page(pfn));
1818 }
1819 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
1820
1821 void kvm_get_pfn(kvm_pfn_t pfn)
1822 {
1823         if (!kvm_is_reserved_pfn(pfn))
1824                 get_page(pfn_to_page(pfn));
1825 }
1826 EXPORT_SYMBOL_GPL(kvm_get_pfn);
1827
1828 static int next_segment(unsigned long len, int offset)
1829 {
1830         if (len > PAGE_SIZE - offset)
1831                 return PAGE_SIZE - offset;
1832         else
1833                 return len;
1834 }
1835
1836 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
1837                                  void *data, int offset, int len)
1838 {
1839         int r;
1840         unsigned long addr;
1841
1842         addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
1843         if (kvm_is_error_hva(addr))
1844                 return -EFAULT;
1845         r = __copy_from_user(data, (void __user *)addr + offset, len);
1846         if (r)
1847                 return -EFAULT;
1848         return 0;
1849 }
1850
1851 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1852                         int len)
1853 {
1854         struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1855
1856         return __kvm_read_guest_page(slot, gfn, data, offset, len);
1857 }
1858 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
1859
1860 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
1861                              int offset, int len)
1862 {
1863         struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1864
1865         return __kvm_read_guest_page(slot, gfn, data, offset, len);
1866 }
1867 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
1868
1869 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
1870 {
1871         gfn_t gfn = gpa >> PAGE_SHIFT;
1872         int seg;
1873         int offset = offset_in_page(gpa);
1874         int ret;
1875
1876         while ((seg = next_segment(len, offset)) != 0) {
1877                 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
1878                 if (ret < 0)
1879                         return ret;
1880                 offset = 0;
1881                 len -= seg;
1882                 data += seg;
1883                 ++gfn;
1884         }
1885         return 0;
1886 }
1887 EXPORT_SYMBOL_GPL(kvm_read_guest);
1888
1889 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
1890 {
1891         gfn_t gfn = gpa >> PAGE_SHIFT;
1892         int seg;
1893         int offset = offset_in_page(gpa);
1894         int ret;
1895
1896         while ((seg = next_segment(len, offset)) != 0) {
1897                 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
1898                 if (ret < 0)
1899                         return ret;
1900                 offset = 0;
1901                 len -= seg;
1902                 data += seg;
1903                 ++gfn;
1904         }
1905         return 0;
1906 }
1907 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
1908
1909 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1910                                    void *data, int offset, unsigned long len)
1911 {
1912         int r;
1913         unsigned long addr;
1914
1915         addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
1916         if (kvm_is_error_hva(addr))
1917                 return -EFAULT;
1918         pagefault_disable();
1919         r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
1920         pagefault_enable();
1921         if (r)
1922                 return -EFAULT;
1923         return 0;
1924 }
1925
1926 int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
1927                           unsigned long len)
1928 {
1929         gfn_t gfn = gpa >> PAGE_SHIFT;
1930         struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1931         int offset = offset_in_page(gpa);
1932
1933         return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
1934 }
1935 EXPORT_SYMBOL_GPL(kvm_read_guest_atomic);
1936
1937 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
1938                                void *data, unsigned long len)
1939 {
1940         gfn_t gfn = gpa >> PAGE_SHIFT;
1941         struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1942         int offset = offset_in_page(gpa);
1943
1944         return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
1945 }
1946 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
1947
1948 static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
1949                                   const void *data, int offset, int len)
1950 {
1951         int r;
1952         unsigned long addr;
1953
1954         addr = gfn_to_hva_memslot(memslot, gfn);
1955         if (kvm_is_error_hva(addr))
1956                 return -EFAULT;
1957         r = __copy_to_user((void __user *)addr + offset, data, len);
1958         if (r)
1959                 return -EFAULT;
1960         mark_page_dirty_in_slot(memslot, gfn);
1961         return 0;
1962 }
1963
1964 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
1965                          const void *data, int offset, int len)
1966 {
1967         struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1968
1969         return __kvm_write_guest_page(slot, gfn, data, offset, len);
1970 }
1971 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
1972
1973 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
1974                               const void *data, int offset, int len)
1975 {
1976         struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1977
1978         return __kvm_write_guest_page(slot, gfn, data, offset, len);
1979 }
1980 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
1981
1982 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
1983                     unsigned long len)
1984 {
1985         gfn_t gfn = gpa >> PAGE_SHIFT;
1986         int seg;
1987         int offset = offset_in_page(gpa);
1988         int ret;
1989
1990         while ((seg = next_segment(len, offset)) != 0) {
1991                 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
1992                 if (ret < 0)
1993                         return ret;
1994                 offset = 0;
1995                 len -= seg;
1996                 data += seg;
1997                 ++gfn;
1998         }
1999         return 0;
2000 }
2001 EXPORT_SYMBOL_GPL(kvm_write_guest);
2002
2003 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2004                          unsigned long len)
2005 {
2006         gfn_t gfn = gpa >> PAGE_SHIFT;
2007         int seg;
2008         int offset = offset_in_page(gpa);
2009         int ret;
2010
2011         while ((seg = next_segment(len, offset)) != 0) {
2012                 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2013                 if (ret < 0)
2014                         return ret;
2015                 offset = 0;
2016                 len -= seg;
2017                 data += seg;
2018                 ++gfn;
2019         }
2020         return 0;
2021 }
2022 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2023
2024 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2025                               gpa_t gpa, unsigned long len)
2026 {
2027         struct kvm_memslots *slots = kvm_memslots(kvm);
2028         int offset = offset_in_page(gpa);
2029         gfn_t start_gfn = gpa >> PAGE_SHIFT;
2030         gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2031         gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2032         gfn_t nr_pages_avail;
2033
2034         ghc->gpa = gpa;
2035         ghc->generation = slots->generation;
2036         ghc->len = len;
2037         ghc->memslot = gfn_to_memslot(kvm, start_gfn);
2038         ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn, NULL);
2039         if (!kvm_is_error_hva(ghc->hva) && nr_pages_needed <= 1) {
2040                 ghc->hva += offset;
2041         } else {
2042                 /*
2043                  * If the requested region crosses two memslots, we still
2044                  * verify that the entire region is valid here.
2045                  */
2046                 while (start_gfn <= end_gfn) {
2047                         ghc->memslot = gfn_to_memslot(kvm, start_gfn);
2048                         ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2049                                                    &nr_pages_avail);
2050                         if (kvm_is_error_hva(ghc->hva))
2051                                 return -EFAULT;
2052                         start_gfn += nr_pages_avail;
2053                 }
2054                 /* Use the slow path for cross page reads and writes. */
2055                 ghc->memslot = NULL;
2056         }
2057         return 0;
2058 }
2059 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2060
2061 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2062                            void *data, unsigned long len)
2063 {
2064         struct kvm_memslots *slots = kvm_memslots(kvm);
2065         int r;
2066
2067         BUG_ON(len > ghc->len);
2068
2069         if (slots->generation != ghc->generation)
2070                 kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa, ghc->len);
2071
2072         if (kvm_is_error_hva(ghc->hva))
2073                 return -EFAULT;
2074
2075         if (unlikely(!ghc->memslot))
2076                 return kvm_write_guest(kvm, ghc->gpa, data, len);
2077
2078         r = __copy_to_user((void __user *)ghc->hva, data, len);
2079         if (r)
2080                 return -EFAULT;
2081         mark_page_dirty_in_slot(ghc->memslot, ghc->gpa >> PAGE_SHIFT);
2082
2083         return 0;
2084 }
2085 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
2086
2087 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2088                            void *data, unsigned long len)
2089 {
2090         struct kvm_memslots *slots = kvm_memslots(kvm);
2091         int r;
2092
2093         BUG_ON(len > ghc->len);
2094
2095         if (slots->generation != ghc->generation)
2096                 kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa, ghc->len);
2097
2098         if (kvm_is_error_hva(ghc->hva))
2099                 return -EFAULT;
2100
2101         if (unlikely(!ghc->memslot))
2102                 return kvm_read_guest(kvm, ghc->gpa, data, len);
2103
2104         r = __copy_from_user(data, (void __user *)ghc->hva, len);
2105         if (r)
2106                 return -EFAULT;
2107
2108         return 0;
2109 }
2110 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
2111
2112 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
2113 {
2114         const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2115
2116         return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
2117 }
2118 EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
2119
2120 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2121 {
2122         gfn_t gfn = gpa >> PAGE_SHIFT;
2123         int seg;
2124         int offset = offset_in_page(gpa);
2125         int ret;
2126
2127         while ((seg = next_segment(len, offset)) != 0) {
2128                 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
2129                 if (ret < 0)
2130                         return ret;
2131                 offset = 0;
2132                 len -= seg;
2133                 ++gfn;
2134         }
2135         return 0;
2136 }
2137 EXPORT_SYMBOL_GPL(kvm_clear_guest);
2138
2139 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot,
2140                                     gfn_t gfn)
2141 {
2142         if (memslot && memslot->dirty_bitmap) {
2143                 unsigned long rel_gfn = gfn - memslot->base_gfn;
2144
2145                 set_bit_le(rel_gfn, memslot->dirty_bitmap);
2146         }
2147 }
2148
2149 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2150 {
2151         struct kvm_memory_slot *memslot;
2152
2153         memslot = gfn_to_memslot(kvm, gfn);
2154         mark_page_dirty_in_slot(memslot, gfn);
2155 }
2156 EXPORT_SYMBOL_GPL(mark_page_dirty);
2157
2158 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2159 {
2160         struct kvm_memory_slot *memslot;
2161
2162         memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2163         mark_page_dirty_in_slot(memslot, gfn);
2164 }
2165 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2166
2167 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2168 {
2169         unsigned int old, val, grow;
2170
2171         old = val = vcpu->halt_poll_ns;
2172         grow = READ_ONCE(halt_poll_ns_grow);
2173         /* 10us base */
2174         if (val == 0 && grow)
2175                 val = 10000;
2176         else
2177                 val *= grow;
2178
2179         if (val > halt_poll_ns)
2180                 val = halt_poll_ns;
2181
2182         vcpu->halt_poll_ns = val;
2183         trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
2184 }
2185
2186 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2187 {
2188         unsigned int old, val, shrink;
2189
2190         old = val = vcpu->halt_poll_ns;
2191         shrink = READ_ONCE(halt_poll_ns_shrink);
2192         if (shrink == 0)
2193                 val = 0;
2194         else
2195                 val /= shrink;
2196
2197         vcpu->halt_poll_ns = val;
2198         trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
2199 }
2200
2201 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2202 {
2203         if (kvm_arch_vcpu_runnable(vcpu)) {
2204                 kvm_make_request(KVM_REQ_UNHALT, vcpu);
2205                 return -EINTR;
2206         }
2207         if (kvm_cpu_has_pending_timer(vcpu))
2208                 return -EINTR;
2209         if (signal_pending(current))
2210                 return -EINTR;
2211
2212         return 0;
2213 }
2214
2215 /*
2216  * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2217  */
2218 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
2219 {
2220         ktime_t start, cur;
2221         DECLARE_SWAITQUEUE(wait);
2222         bool waited = false;
2223         u64 block_ns;
2224
2225         start = cur = ktime_get();
2226         if (vcpu->halt_poll_ns) {
2227                 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
2228
2229                 ++vcpu->stat.halt_attempted_poll;
2230                 do {
2231                         /*
2232                          * This sets KVM_REQ_UNHALT if an interrupt
2233                          * arrives.
2234                          */
2235                         if (kvm_vcpu_check_block(vcpu) < 0) {
2236                                 ++vcpu->stat.halt_successful_poll;
2237                                 if (!vcpu_valid_wakeup(vcpu))
2238                                         ++vcpu->stat.halt_poll_invalid;
2239                                 goto out;
2240                         }
2241                         cur = ktime_get();
2242                 } while (single_task_running() && ktime_before(cur, stop));
2243         }
2244
2245         kvm_arch_vcpu_blocking(vcpu);
2246
2247         for (;;) {
2248                 prepare_to_swait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
2249
2250                 if (kvm_vcpu_check_block(vcpu) < 0)
2251                         break;
2252
2253                 waited = true;
2254                 schedule();
2255         }
2256
2257         finish_swait(&vcpu->wq, &wait);
2258         cur = ktime_get();
2259
2260         kvm_arch_vcpu_unblocking(vcpu);
2261 out:
2262         block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2263
2264         if (!vcpu_valid_wakeup(vcpu))
2265                 shrink_halt_poll_ns(vcpu);
2266         else if (halt_poll_ns) {
2267                 if (block_ns <= vcpu->halt_poll_ns)
2268                         ;
2269                 /* we had a long block, shrink polling */
2270                 else if (vcpu->halt_poll_ns && block_ns > halt_poll_ns)
2271                         shrink_halt_poll_ns(vcpu);
2272                 /* we had a short halt and our poll time is too small */
2273                 else if (vcpu->halt_poll_ns < halt_poll_ns &&
2274                         block_ns < halt_poll_ns)
2275                         grow_halt_poll_ns(vcpu);
2276         } else
2277                 vcpu->halt_poll_ns = 0;
2278
2279         trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
2280         kvm_arch_vcpu_block_finish(vcpu);
2281 }
2282 EXPORT_SYMBOL_GPL(kvm_vcpu_block);
2283
2284 #ifndef CONFIG_S390
2285 void kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
2286 {
2287         struct swait_queue_head *wqp;
2288
2289         wqp = kvm_arch_vcpu_wq(vcpu);
2290         if (swait_active(wqp)) {
2291                 swake_up(wqp);
2292                 ++vcpu->stat.halt_wakeup;
2293         }
2294
2295 }
2296 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2297
2298 /*
2299  * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2300  */
2301 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2302 {
2303         int me;
2304         int cpu = vcpu->cpu;
2305
2306         kvm_vcpu_wake_up(vcpu);
2307         me = get_cpu();
2308         if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2309                 if (kvm_arch_vcpu_should_kick(vcpu))
2310                         smp_send_reschedule(cpu);
2311         put_cpu();
2312 }
2313 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
2314 #endif /* !CONFIG_S390 */
2315
2316 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
2317 {
2318         struct pid *pid;
2319         struct task_struct *task = NULL;
2320         int ret = 0;
2321
2322         rcu_read_lock();
2323         pid = rcu_dereference(target->pid);
2324         if (pid)
2325                 task = get_pid_task(pid, PIDTYPE_PID);
2326         rcu_read_unlock();
2327         if (!task)
2328                 return ret;
2329         ret = yield_to(task, 1);
2330         put_task_struct(task);
2331
2332         return ret;
2333 }
2334 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2335
2336 /*
2337  * Helper that checks whether a VCPU is eligible for directed yield.
2338  * Most eligible candidate to yield is decided by following heuristics:
2339  *
2340  *  (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2341  *  (preempted lock holder), indicated by @in_spin_loop.
2342  *  Set at the beiginning and cleared at the end of interception/PLE handler.
2343  *
2344  *  (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2345  *  chance last time (mostly it has become eligible now since we have probably
2346  *  yielded to lockholder in last iteration. This is done by toggling
2347  *  @dy_eligible each time a VCPU checked for eligibility.)
2348  *
2349  *  Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2350  *  to preempted lock-holder could result in wrong VCPU selection and CPU
2351  *  burning. Giving priority for a potential lock-holder increases lock
2352  *  progress.
2353  *
2354  *  Since algorithm is based on heuristics, accessing another VCPU data without
2355  *  locking does not harm. It may result in trying to yield to  same VCPU, fail
2356  *  and continue with next VCPU and so on.
2357  */
2358 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
2359 {
2360 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
2361         bool eligible;
2362
2363         eligible = !vcpu->spin_loop.in_spin_loop ||
2364                     vcpu->spin_loop.dy_eligible;
2365
2366         if (vcpu->spin_loop.in_spin_loop)
2367                 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2368
2369         return eligible;
2370 #else
2371         return true;
2372 #endif
2373 }
2374
2375 void kvm_vcpu_on_spin(struct kvm_vcpu *me)
2376 {
2377         struct kvm *kvm = me->kvm;
2378         struct kvm_vcpu *vcpu;
2379         int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
2380         int yielded = 0;
2381         int try = 3;
2382         int pass;
2383         int i;
2384
2385         kvm_vcpu_set_in_spin_loop(me, true);
2386         /*
2387          * We boost the priority of a VCPU that is runnable but not
2388          * currently running, because it got preempted by something
2389          * else and called schedule in __vcpu_run.  Hopefully that
2390          * VCPU is holding the lock that we need and will release it.
2391          * We approximate round-robin by starting at the last boosted VCPU.
2392          */
2393         for (pass = 0; pass < 2 && !yielded && try; pass++) {
2394                 kvm_for_each_vcpu(i, vcpu, kvm) {
2395                         if (!pass && i <= last_boosted_vcpu) {
2396                                 i = last_boosted_vcpu;
2397                                 continue;
2398                         } else if (pass && i > last_boosted_vcpu)
2399                                 break;
2400                         if (!ACCESS_ONCE(vcpu->preempted))
2401                                 continue;
2402                         if (vcpu == me)
2403                                 continue;
2404                         if (swait_active(&vcpu->wq) && !kvm_arch_vcpu_runnable(vcpu))
2405                                 continue;
2406                         if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
2407                                 continue;
2408
2409                         yielded = kvm_vcpu_yield_to(vcpu);
2410                         if (yielded > 0) {
2411                                 kvm->last_boosted_vcpu = i;
2412                                 break;
2413                         } else if (yielded < 0) {
2414                                 try--;
2415                                 if (!try)
2416                                         break;
2417                         }
2418                 }
2419         }
2420         kvm_vcpu_set_in_spin_loop(me, false);
2421
2422         /* Ensure vcpu is not eligible during next spinloop */
2423         kvm_vcpu_set_dy_eligible(me, false);
2424 }
2425 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
2426
2427 static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
2428 {
2429         struct kvm_vcpu *vcpu = vma->vm_file->private_data;
2430         struct page *page;
2431
2432         if (vmf->pgoff == 0)
2433                 page = virt_to_page(vcpu->run);
2434 #ifdef CONFIG_X86
2435         else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
2436                 page = virt_to_page(vcpu->arch.pio_data);
2437 #endif
2438 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2439         else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
2440                 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
2441 #endif
2442         else
2443                 return kvm_arch_vcpu_fault(vcpu, vmf);
2444         get_page(page);
2445         vmf->page = page;
2446         return 0;
2447 }
2448
2449 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
2450         .fault = kvm_vcpu_fault,
2451 };
2452
2453 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2454 {
2455         vma->vm_ops = &kvm_vcpu_vm_ops;
2456         return 0;
2457 }
2458
2459 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2460 {
2461         struct kvm_vcpu *vcpu = filp->private_data;
2462
2463         debugfs_remove_recursive(vcpu->debugfs_dentry);
2464         kvm_put_kvm(vcpu->kvm);
2465         return 0;
2466 }
2467
2468 static struct file_operations kvm_vcpu_fops = {
2469         .release        = kvm_vcpu_release,
2470         .unlocked_ioctl = kvm_vcpu_ioctl,
2471 #ifdef CONFIG_KVM_COMPAT
2472         .compat_ioctl   = kvm_vcpu_compat_ioctl,
2473 #endif
2474         .mmap           = kvm_vcpu_mmap,
2475         .llseek         = noop_llseek,
2476 };
2477
2478 /*
2479  * Allocates an inode for the vcpu.
2480  */
2481 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2482 {
2483         return anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
2484 }
2485
2486 static int kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
2487 {
2488         char dir_name[ITOA_MAX_LEN * 2];
2489         int ret;
2490
2491         if (!kvm_arch_has_vcpu_debugfs())
2492                 return 0;
2493
2494         if (!debugfs_initialized())
2495                 return 0;
2496
2497         snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
2498         vcpu->debugfs_dentry = debugfs_create_dir(dir_name,
2499                                                                 vcpu->kvm->debugfs_dentry);
2500         if (!vcpu->debugfs_dentry)
2501                 return -ENOMEM;
2502
2503         ret = kvm_arch_create_vcpu_debugfs(vcpu);
2504         if (ret < 0) {
2505                 debugfs_remove_recursive(vcpu->debugfs_dentry);
2506                 return ret;
2507         }
2508
2509         return 0;
2510 }
2511
2512 /*
2513  * Creates some virtual cpus.  Good luck creating more than one.
2514  */
2515 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
2516 {
2517         int r;
2518         struct kvm_vcpu *vcpu;
2519
2520         if (id >= KVM_MAX_VCPU_ID)
2521                 return -EINVAL;
2522
2523         mutex_lock(&kvm->lock);
2524         if (kvm->created_vcpus == KVM_MAX_VCPUS) {
2525                 mutex_unlock(&kvm->lock);
2526                 return -EINVAL;
2527         }
2528
2529         kvm->created_vcpus++;
2530         mutex_unlock(&kvm->lock);
2531
2532         vcpu = kvm_arch_vcpu_create(kvm, id);
2533         if (IS_ERR(vcpu)) {
2534                 r = PTR_ERR(vcpu);
2535                 goto vcpu_decrement;
2536         }
2537
2538         preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
2539
2540         r = kvm_arch_vcpu_setup(vcpu);
2541         if (r)
2542                 goto vcpu_destroy;
2543
2544         r = kvm_create_vcpu_debugfs(vcpu);
2545         if (r)
2546                 goto vcpu_destroy;
2547
2548         mutex_lock(&kvm->lock);
2549         if (kvm_get_vcpu_by_id(kvm, id)) {
2550                 r = -EEXIST;
2551                 goto unlock_vcpu_destroy;
2552         }
2553
2554         BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
2555
2556         /* Now it's all set up, let userspace reach it */
2557         kvm_get_kvm(kvm);
2558         r = create_vcpu_fd(vcpu);
2559         if (r < 0) {
2560                 kvm_put_kvm(kvm);
2561                 goto unlock_vcpu_destroy;
2562         }
2563
2564         kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
2565
2566         /*
2567          * Pairs with smp_rmb() in kvm_get_vcpu.  Write kvm->vcpus
2568          * before kvm->online_vcpu's incremented value.
2569          */
2570         smp_wmb();
2571         atomic_inc(&kvm->online_vcpus);
2572
2573         mutex_unlock(&kvm->lock);
2574         kvm_arch_vcpu_postcreate(vcpu);
2575         return r;
2576
2577 unlock_vcpu_destroy:
2578         mutex_unlock(&kvm->lock);
2579         debugfs_remove_recursive(vcpu->debugfs_dentry);
2580 vcpu_destroy:
2581         kvm_arch_vcpu_destroy(vcpu);
2582 vcpu_decrement:
2583         mutex_lock(&kvm->lock);
2584         kvm->created_vcpus--;
2585         mutex_unlock(&kvm->lock);
2586         return r;
2587 }
2588
2589 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
2590 {
2591         if (sigset) {
2592                 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
2593                 vcpu->sigset_active = 1;
2594                 vcpu->sigset = *sigset;
2595         } else
2596                 vcpu->sigset_active = 0;
2597         return 0;
2598 }
2599
2600 static long kvm_vcpu_ioctl(struct file *filp,
2601                            unsigned int ioctl, unsigned long arg)
2602 {
2603         struct kvm_vcpu *vcpu = filp->private_data;
2604         void __user *argp = (void __user *)arg;
2605         int r;
2606         struct kvm_fpu *fpu = NULL;
2607         struct kvm_sregs *kvm_sregs = NULL;
2608
2609         if (vcpu->kvm->mm != current->mm)
2610                 return -EIO;
2611
2612         if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
2613                 return -EINVAL;
2614
2615 #if defined(CONFIG_S390) || defined(CONFIG_PPC) || defined(CONFIG_MIPS)
2616         /*
2617          * Special cases: vcpu ioctls that are asynchronous to vcpu execution,
2618          * so vcpu_load() would break it.
2619          */
2620         if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_S390_IRQ || ioctl == KVM_INTERRUPT)
2621                 return kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2622 #endif
2623
2624
2625         r = vcpu_load(vcpu);
2626         if (r)
2627                 return r;
2628         switch (ioctl) {
2629         case KVM_RUN:
2630                 r = -EINVAL;
2631                 if (arg)
2632                         goto out;
2633                 if (unlikely(vcpu->pid != current->pids[PIDTYPE_PID].pid)) {
2634                         /* The thread running this VCPU changed. */
2635                         struct pid *oldpid = vcpu->pid;
2636                         struct pid *newpid = get_task_pid(current, PIDTYPE_PID);
2637
2638                         rcu_assign_pointer(vcpu->pid, newpid);
2639                         if (oldpid)
2640                                 synchronize_rcu();
2641                         put_pid(oldpid);
2642                 }
2643                 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
2644                 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
2645                 break;
2646         case KVM_GET_REGS: {
2647                 struct kvm_regs *kvm_regs;
2648
2649                 r = -ENOMEM;
2650                 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
2651                 if (!kvm_regs)
2652                         goto out;
2653                 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
2654                 if (r)
2655                         goto out_free1;
2656                 r = -EFAULT;
2657                 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
2658                         goto out_free1;
2659                 r = 0;
2660 out_free1:
2661                 kfree(kvm_regs);
2662                 break;
2663         }
2664         case KVM_SET_REGS: {
2665                 struct kvm_regs *kvm_regs;
2666
2667                 r = -ENOMEM;
2668                 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
2669                 if (IS_ERR(kvm_regs)) {
2670                         r = PTR_ERR(kvm_regs);
2671                         goto out;
2672                 }
2673                 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
2674                 kfree(kvm_regs);
2675                 break;
2676         }
2677         case KVM_GET_SREGS: {
2678                 kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
2679                 r = -ENOMEM;
2680                 if (!kvm_sregs)
2681                         goto out;
2682                 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
2683                 if (r)
2684                         goto out;
2685                 r = -EFAULT;
2686                 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
2687                         goto out;
2688                 r = 0;
2689                 break;
2690         }
2691         case KVM_SET_SREGS: {
2692                 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
2693                 if (IS_ERR(kvm_sregs)) {
2694                         r = PTR_ERR(kvm_sregs);
2695                         kvm_sregs = NULL;
2696                         goto out;
2697                 }
2698                 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
2699                 break;
2700         }
2701         case KVM_GET_MP_STATE: {
2702                 struct kvm_mp_state mp_state;
2703
2704                 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
2705                 if (r)
2706                         goto out;
2707                 r = -EFAULT;
2708                 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
2709                         goto out;
2710                 r = 0;
2711                 break;
2712         }
2713         case KVM_SET_MP_STATE: {
2714                 struct kvm_mp_state mp_state;
2715
2716                 r = -EFAULT;
2717                 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
2718                         goto out;
2719                 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
2720                 break;
2721         }
2722         case KVM_TRANSLATE: {
2723                 struct kvm_translation tr;
2724
2725                 r = -EFAULT;
2726                 if (copy_from_user(&tr, argp, sizeof(tr)))
2727                         goto out;
2728                 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
2729                 if (r)
2730                         goto out;
2731                 r = -EFAULT;
2732                 if (copy_to_user(argp, &tr, sizeof(tr)))
2733                         goto out;
2734                 r = 0;
2735                 break;
2736         }
2737         case KVM_SET_GUEST_DEBUG: {
2738                 struct kvm_guest_debug dbg;
2739
2740                 r = -EFAULT;
2741                 if (copy_from_user(&dbg, argp, sizeof(dbg)))
2742                         goto out;
2743                 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
2744                 break;
2745         }
2746         case KVM_SET_SIGNAL_MASK: {
2747                 struct kvm_signal_mask __user *sigmask_arg = argp;
2748                 struct kvm_signal_mask kvm_sigmask;
2749                 sigset_t sigset, *p;
2750
2751                 p = NULL;
2752                 if (argp) {
2753                         r = -EFAULT;
2754                         if (copy_from_user(&kvm_sigmask, argp,
2755                                            sizeof(kvm_sigmask)))
2756                                 goto out;
2757                         r = -EINVAL;
2758                         if (kvm_sigmask.len != sizeof(sigset))
2759                                 goto out;
2760                         r = -EFAULT;
2761                         if (copy_from_user(&sigset, sigmask_arg->sigset,
2762                                            sizeof(sigset)))
2763                                 goto out;
2764                         p = &sigset;
2765                 }
2766                 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
2767                 break;
2768         }
2769         case KVM_GET_FPU: {
2770                 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
2771                 r = -ENOMEM;
2772                 if (!fpu)
2773                         goto out;
2774                 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
2775                 if (r)
2776                         goto out;
2777                 r = -EFAULT;
2778                 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
2779                         goto out;
2780                 r = 0;
2781                 break;
2782         }
2783         case KVM_SET_FPU: {
2784                 fpu = memdup_user(argp, sizeof(*fpu));
2785                 if (IS_ERR(fpu)) {
2786                         r = PTR_ERR(fpu);
2787                         fpu = NULL;
2788                         goto out;
2789                 }
2790                 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
2791                 break;
2792         }
2793         default:
2794                 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2795         }
2796 out:
2797         vcpu_put(vcpu);
2798         kfree(fpu);
2799         kfree(kvm_sregs);
2800         return r;
2801 }
2802
2803 #ifdef CONFIG_KVM_COMPAT
2804 static long kvm_vcpu_compat_ioctl(struct file *filp,
2805                                   unsigned int ioctl, unsigned long arg)
2806 {
2807         struct kvm_vcpu *vcpu = filp->private_data;
2808         void __user *argp = compat_ptr(arg);
2809         int r;
2810
2811         if (vcpu->kvm->mm != current->mm)
2812                 return -EIO;
2813
2814         switch (ioctl) {
2815         case KVM_SET_SIGNAL_MASK: {
2816                 struct kvm_signal_mask __user *sigmask_arg = argp;
2817                 struct kvm_signal_mask kvm_sigmask;
2818                 compat_sigset_t csigset;
2819                 sigset_t sigset;
2820
2821                 if (argp) {
2822                         r = -EFAULT;
2823                         if (copy_from_user(&kvm_sigmask, argp,
2824                                            sizeof(kvm_sigmask)))
2825                                 goto out;
2826                         r = -EINVAL;
2827                         if (kvm_sigmask.len != sizeof(csigset))
2828                                 goto out;
2829                         r = -EFAULT;
2830                         if (copy_from_user(&csigset, sigmask_arg->sigset,
2831                                            sizeof(csigset)))
2832                                 goto out;
2833                         sigset_from_compat(&sigset, &csigset);
2834                         r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
2835                 } else
2836                         r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
2837                 break;
2838         }
2839         default:
2840                 r = kvm_vcpu_ioctl(filp, ioctl, arg);
2841         }
2842
2843 out:
2844         return r;
2845 }
2846 #endif
2847
2848 static int kvm_device_ioctl_attr(struct kvm_device *dev,
2849                                  int (*accessor)(struct kvm_device *dev,
2850                                                  struct kvm_device_attr *attr),
2851                                  unsigned long arg)
2852 {
2853         struct kvm_device_attr attr;
2854
2855         if (!accessor)
2856                 return -EPERM;
2857
2858         if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
2859                 return -EFAULT;
2860
2861         return accessor(dev, &attr);
2862 }
2863
2864 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
2865                              unsigned long arg)
2866 {
2867         struct kvm_device *dev = filp->private_data;
2868
2869         if (dev->kvm->mm != current->mm)
2870                 return -EIO;
2871
2872         switch (ioctl) {
2873         case KVM_SET_DEVICE_ATTR:
2874                 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
2875         case KVM_GET_DEVICE_ATTR:
2876                 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
2877         case KVM_HAS_DEVICE_ATTR:
2878                 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
2879         default:
2880                 if (dev->ops->ioctl)
2881                         return dev->ops->ioctl(dev, ioctl, arg);
2882
2883                 return -ENOTTY;
2884         }
2885 }
2886
2887 static int kvm_device_release(struct inode *inode, struct file *filp)
2888 {
2889         struct kvm_device *dev = filp->private_data;
2890         struct kvm *kvm = dev->kvm;
2891
2892         kvm_put_kvm(kvm);
2893         return 0;
2894 }
2895
2896 static const struct file_operations kvm_device_fops = {
2897         .unlocked_ioctl = kvm_device_ioctl,
2898 #ifdef CONFIG_KVM_COMPAT
2899         .compat_ioctl = kvm_device_ioctl,
2900 #endif
2901         .release = kvm_device_release,
2902 };
2903
2904 struct kvm_device *kvm_device_from_filp(struct file *filp)
2905 {
2906         if (filp->f_op != &kvm_device_fops)
2907                 return NULL;
2908
2909         return filp->private_data;
2910 }
2911
2912 static struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
2913 #ifdef CONFIG_KVM_MPIC
2914         [KVM_DEV_TYPE_FSL_MPIC_20]      = &kvm_mpic_ops,
2915         [KVM_DEV_TYPE_FSL_MPIC_42]      = &kvm_mpic_ops,
2916 #endif
2917
2918 #ifdef CONFIG_KVM_XICS
2919         [KVM_DEV_TYPE_XICS]             = &kvm_xics_ops,
2920 #endif
2921 };
2922
2923 int kvm_register_device_ops(struct kvm_device_ops *ops, u32 type)
2924 {
2925         if (type >= ARRAY_SIZE(kvm_device_ops_table))
2926                 return -ENOSPC;
2927
2928         if (kvm_device_ops_table[type] != NULL)
2929                 return -EEXIST;
2930
2931         kvm_device_ops_table[type] = ops;
2932         return 0;
2933 }
2934
2935 void kvm_unregister_device_ops(u32 type)
2936 {
2937         if (kvm_device_ops_table[type] != NULL)
2938                 kvm_device_ops_table[type] = NULL;
2939 }
2940
2941 static int kvm_ioctl_create_device(struct kvm *kvm,
2942                                    struct kvm_create_device *cd)
2943 {
2944         struct kvm_device_ops *ops = NULL;
2945         struct kvm_device *dev;
2946         bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
2947         int ret;
2948
2949         if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
2950                 return -ENODEV;
2951
2952         ops = kvm_device_ops_table[cd->type];
2953         if (ops == NULL)
2954                 return -ENODEV;
2955
2956         if (test)
2957                 return 0;
2958
2959         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2960         if (!dev)
2961                 return -ENOMEM;
2962
2963         dev->ops = ops;
2964         dev->kvm = kvm;
2965
2966         mutex_lock(&kvm->lock);
2967         ret = ops->create(dev, cd->type);
2968         if (ret < 0) {
2969                 mutex_unlock(&kvm->lock);
2970                 kfree(dev);
2971                 return ret;
2972         }
2973         list_add(&dev->vm_node, &kvm->devices);
2974         mutex_unlock(&kvm->lock);
2975
2976         if (ops->init)
2977                 ops->init(dev);
2978
2979         kvm_get_kvm(kvm);
2980         ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
2981         if (ret < 0) {
2982                 kvm_put_kvm(kvm);
2983                 mutex_lock(&kvm->lock);
2984                 list_del(&dev->vm_node);
2985                 mutex_unlock(&kvm->lock);
2986                 ops->destroy(dev);
2987                 return ret;
2988         }
2989
2990         cd->fd = ret;
2991         return 0;
2992 }
2993
2994 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
2995 {
2996         switch (arg) {
2997         case KVM_CAP_USER_MEMORY:
2998         case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
2999         case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
3000         case KVM_CAP_INTERNAL_ERROR_DATA:
3001 #ifdef CONFIG_HAVE_KVM_MSI
3002         case KVM_CAP_SIGNAL_MSI:
3003 #endif
3004 #ifdef CONFIG_HAVE_KVM_IRQFD
3005         case KVM_CAP_IRQFD:
3006         case KVM_CAP_IRQFD_RESAMPLE:
3007 #endif
3008         case KVM_CAP_IOEVENTFD_ANY_LENGTH:
3009         case KVM_CAP_CHECK_EXTENSION_VM:
3010                 return 1;
3011 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3012         case KVM_CAP_IRQ_ROUTING:
3013                 return KVM_MAX_IRQ_ROUTES;
3014 #endif
3015 #if KVM_ADDRESS_SPACE_NUM > 1
3016         case KVM_CAP_MULTI_ADDRESS_SPACE:
3017                 return KVM_ADDRESS_SPACE_NUM;
3018 #endif
3019         case KVM_CAP_MAX_VCPU_ID:
3020                 return KVM_MAX_VCPU_ID;
3021         default:
3022                 break;
3023         }
3024         return kvm_vm_ioctl_check_extension(kvm, arg);
3025 }
3026
3027 static long kvm_vm_ioctl(struct file *filp,
3028                            unsigned int ioctl, unsigned long arg)
3029 {
3030         struct kvm *kvm = filp->private_data;
3031         void __user *argp = (void __user *)arg;
3032         int r;
3033
3034         if (kvm->mm != current->mm)
3035                 return -EIO;
3036         switch (ioctl) {
3037         case KVM_CREATE_VCPU:
3038                 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
3039                 break;
3040         case KVM_SET_USER_MEMORY_REGION: {
3041                 struct kvm_userspace_memory_region kvm_userspace_mem;
3042
3043                 r = -EFAULT;
3044                 if (copy_from_user(&kvm_userspace_mem, argp,
3045                                                 sizeof(kvm_userspace_mem)))
3046                         goto out;
3047
3048                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
3049                 break;
3050         }
3051         case KVM_GET_DIRTY_LOG: {
3052                 struct kvm_dirty_log log;
3053
3054                 r = -EFAULT;
3055                 if (copy_from_user(&log, argp, sizeof(log)))
3056                         goto out;
3057                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3058                 break;
3059         }
3060 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
3061         case KVM_REGISTER_COALESCED_MMIO: {
3062                 struct kvm_coalesced_mmio_zone zone;
3063
3064                 r = -EFAULT;
3065                 if (copy_from_user(&zone, argp, sizeof(zone)))
3066                         goto out;
3067                 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
3068                 break;
3069         }
3070         case KVM_UNREGISTER_COALESCED_MMIO: {
3071                 struct kvm_coalesced_mmio_zone zone;
3072
3073                 r = -EFAULT;
3074                 if (copy_from_user(&zone, argp, sizeof(zone)))
3075                         goto out;
3076                 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
3077                 break;
3078         }
3079 #endif
3080         case KVM_IRQFD: {
3081                 struct kvm_irqfd data;
3082
3083                 r = -EFAULT;
3084                 if (copy_from_user(&data, argp, sizeof(data)))
3085                         goto out;
3086                 r = kvm_irqfd(kvm, &data);
3087                 break;
3088         }
3089         case KVM_IOEVENTFD: {
3090                 struct kvm_ioeventfd data;
3091
3092                 r = -EFAULT;
3093                 if (copy_from_user(&data, argp, sizeof(data)))
3094                         goto out;
3095                 r = kvm_ioeventfd(kvm, &data);
3096                 break;
3097         }
3098 #ifdef CONFIG_HAVE_KVM_MSI
3099         case KVM_SIGNAL_MSI: {
3100                 struct kvm_msi msi;
3101
3102                 r = -EFAULT;
3103                 if (copy_from_user(&msi, argp, sizeof(msi)))
3104                         goto out;
3105                 r = kvm_send_userspace_msi(kvm, &msi);
3106                 break;
3107         }
3108 #endif
3109 #ifdef __KVM_HAVE_IRQ_LINE
3110         case KVM_IRQ_LINE_STATUS:
3111         case KVM_IRQ_LINE: {
3112                 struct kvm_irq_level irq_event;
3113
3114                 r = -EFAULT;
3115                 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
3116                         goto out;
3117
3118                 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3119                                         ioctl == KVM_IRQ_LINE_STATUS);
3120                 if (r)
3121                         goto out;
3122
3123                 r = -EFAULT;
3124                 if (ioctl == KVM_IRQ_LINE_STATUS) {
3125                         if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
3126                                 goto out;
3127                 }
3128
3129                 r = 0;
3130                 break;
3131         }
3132 #endif
3133 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3134         case KVM_SET_GSI_ROUTING: {
3135                 struct kvm_irq_routing routing;
3136                 struct kvm_irq_routing __user *urouting;
3137                 struct kvm_irq_routing_entry *entries = NULL;
3138
3139                 r = -EFAULT;
3140                 if (copy_from_user(&routing, argp, sizeof(routing)))
3141                         goto out;
3142                 r = -EINVAL;
3143                 if (routing.nr > KVM_MAX_IRQ_ROUTES)
3144                         goto out;
3145                 if (routing.flags)
3146                         goto out;
3147                 if (routing.nr) {
3148                         r = -ENOMEM;
3149                         entries = vmalloc(routing.nr * sizeof(*entries));
3150                         if (!entries)
3151                                 goto out;
3152                         r = -EFAULT;
3153                         urouting = argp;
3154                         if (copy_from_user(entries, urouting->entries,
3155                                            routing.nr * sizeof(*entries)))
3156                                 goto out_free_irq_routing;
3157                 }
3158                 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3159                                         routing.flags);
3160 out_free_irq_routing:
3161                 vfree(entries);
3162                 break;
3163         }
3164 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
3165         case KVM_CREATE_DEVICE: {
3166                 struct kvm_create_device cd;
3167
3168                 r = -EFAULT;
3169                 if (copy_from_user(&cd, argp, sizeof(cd)))
3170                         goto out;
3171
3172                 r = kvm_ioctl_create_device(kvm, &cd);
3173                 if (r)
3174                         goto out;
3175
3176                 r = -EFAULT;
3177                 if (copy_to_user(argp, &cd, sizeof(cd)))
3178                         goto out;
3179
3180                 r = 0;
3181                 break;
3182         }
3183         case KVM_CHECK_EXTENSION:
3184                 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3185                 break;
3186         default:
3187                 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
3188         }
3189 out:
3190         return r;
3191 }
3192
3193 #ifdef CONFIG_KVM_COMPAT
3194 struct compat_kvm_dirty_log {
3195         __u32 slot;
3196         __u32 padding1;
3197         union {
3198                 compat_uptr_t dirty_bitmap; /* one bit per page */
3199                 __u64 padding2;
3200         };
3201 };
3202
3203 static long kvm_vm_compat_ioctl(struct file *filp,
3204                            unsigned int ioctl, unsigned long arg)
3205 {
3206         struct kvm *kvm = filp->private_data;
3207         int r;
3208
3209         if (kvm->mm != current->mm)
3210                 return -EIO;
3211         switch (ioctl) {
3212         case KVM_GET_DIRTY_LOG: {
3213                 struct compat_kvm_dirty_log compat_log;
3214                 struct kvm_dirty_log log;
3215
3216                 r = -EFAULT;
3217                 if (copy_from_user(&compat_log, (void __user *)arg,
3218                                    sizeof(compat_log)))
3219                         goto out;
3220                 log.slot         = compat_log.slot;
3221                 log.padding1     = compat_log.padding1;
3222                 log.padding2     = compat_log.padding2;
3223                 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3224
3225                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3226                 break;
3227         }
3228         default:
3229                 r = kvm_vm_ioctl(filp, ioctl, arg);
3230         }
3231
3232 out:
3233         return r;
3234 }
3235 #endif
3236
3237 static struct file_operations kvm_vm_fops = {
3238         .release        = kvm_vm_release,
3239         .unlocked_ioctl = kvm_vm_ioctl,
3240 #ifdef CONFIG_KVM_COMPAT
3241         .compat_ioctl   = kvm_vm_compat_ioctl,
3242 #endif
3243         .llseek         = noop_llseek,
3244 };
3245
3246 static int kvm_dev_ioctl_create_vm(unsigned long type)
3247 {
3248         int r;
3249         struct kvm *kvm;
3250         struct file *file;
3251
3252         kvm = kvm_create_vm(type);
3253         if (IS_ERR(kvm))
3254                 return PTR_ERR(kvm);
3255 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
3256         r = kvm_coalesced_mmio_init(kvm);
3257         if (r < 0) {
3258                 kvm_put_kvm(kvm);
3259                 return r;
3260         }
3261 #endif
3262         r = get_unused_fd_flags(O_CLOEXEC);
3263         if (r < 0) {
3264                 kvm_put_kvm(kvm);
3265                 return r;
3266         }
3267         file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
3268         if (IS_ERR(file)) {
3269                 put_unused_fd(r);
3270                 kvm_put_kvm(kvm);
3271                 return PTR_ERR(file);
3272         }
3273
3274         if (kvm_create_vm_debugfs(kvm, r) < 0) {
3275                 put_unused_fd(r);
3276                 fput(file);
3277                 return -ENOMEM;
3278         }
3279
3280         fd_install(r, file);
3281         return r;
3282 }
3283
3284 static long kvm_dev_ioctl(struct file *filp,
3285                           unsigned int ioctl, unsigned long arg)
3286 {
3287         long r = -EINVAL;
3288
3289         switch (ioctl) {
3290         case KVM_GET_API_VERSION:
3291                 if (arg)
3292                         goto out;
3293                 r = KVM_API_VERSION;
3294                 break;
3295         case KVM_CREATE_VM:
3296                 r = kvm_dev_ioctl_create_vm(arg);
3297                 break;
3298         case KVM_CHECK_EXTENSION:
3299                 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
3300                 break;
3301         case KVM_GET_VCPU_MMAP_SIZE:
3302                 if (arg)
3303                         goto out;
3304                 r = PAGE_SIZE;     /* struct kvm_run */
3305 #ifdef CONFIG_X86
3306                 r += PAGE_SIZE;    /* pio data page */
3307 #endif
3308 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
3309                 r += PAGE_SIZE;    /* coalesced mmio ring page */
3310 #endif
3311                 break;
3312         case KVM_TRACE_ENABLE:
3313         case KVM_TRACE_PAUSE:
3314         case KVM_TRACE_DISABLE:
3315                 r = -EOPNOTSUPP;
3316                 break;
3317         default:
3318                 return kvm_arch_dev_ioctl(filp, ioctl, arg);
3319         }
3320 out:
3321         return r;
3322 }
3323
3324 static struct file_operations kvm_chardev_ops = {
3325         .unlocked_ioctl = kvm_dev_ioctl,
3326         .compat_ioctl   = kvm_dev_ioctl,
3327         .llseek         = noop_llseek,
3328 };
3329
3330 static struct miscdevice kvm_dev = {
3331         KVM_MINOR,
3332         "kvm",
3333         &kvm_chardev_ops,
3334 };
3335
3336 static void hardware_enable_nolock(void *junk)
3337 {
3338         int cpu = raw_smp_processor_id();
3339         int r;
3340
3341         if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
3342                 return;
3343
3344         cpumask_set_cpu(cpu, cpus_hardware_enabled);
3345
3346         r = kvm_arch_hardware_enable();
3347
3348         if (r) {
3349                 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3350                 atomic_inc(&hardware_enable_failed);
3351                 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
3352         }
3353 }
3354
3355 static int kvm_starting_cpu(unsigned int cpu)
3356 {
3357         raw_spin_lock(&kvm_count_lock);
3358         if (kvm_usage_count)
3359                 hardware_enable_nolock(NULL);
3360         raw_spin_unlock(&kvm_count_lock);
3361         return 0;
3362 }
3363
3364 static void hardware_disable_nolock(void *junk)
3365 {
3366         int cpu = raw_smp_processor_id();
3367
3368         if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
3369                 return;
3370         cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3371         kvm_arch_hardware_disable();
3372 }
3373
3374 static int kvm_dying_cpu(unsigned int cpu)
3375 {
3376         raw_spin_lock(&kvm_count_lock);
3377         if (kvm_usage_count)
3378                 hardware_disable_nolock(NULL);
3379         raw_spin_unlock(&kvm_count_lock);
3380         return 0;
3381 }
3382
3383 static void hardware_disable_all_nolock(void)
3384 {
3385         BUG_ON(!kvm_usage_count);
3386
3387         kvm_usage_count--;
3388         if (!kvm_usage_count)
3389                 on_each_cpu(hardware_disable_nolock, NULL, 1);
3390 }
3391
3392 static void hardware_disable_all(void)
3393 {
3394         raw_spin_lock(&kvm_count_lock);
3395         hardware_disable_all_nolock();
3396         raw_spin_unlock(&kvm_count_lock);
3397 }
3398
3399 static int hardware_enable_all(void)
3400 {
3401         int r = 0;
3402
3403         raw_spin_lock(&kvm_count_lock);
3404
3405         kvm_usage_count++;
3406         if (kvm_usage_count == 1) {
3407                 atomic_set(&hardware_enable_failed, 0);
3408                 on_each_cpu(hardware_enable_nolock, NULL, 1);
3409
3410                 if (atomic_read(&hardware_enable_failed)) {
3411                         hardware_disable_all_nolock();
3412                         r = -EBUSY;
3413                 }
3414         }
3415
3416         raw_spin_unlock(&kvm_count_lock);
3417
3418         return r;
3419 }
3420
3421 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
3422                       void *v)
3423 {
3424         /*
3425          * Some (well, at least mine) BIOSes hang on reboot if
3426          * in vmx root mode.
3427          *
3428          * And Intel TXT required VMX off for all cpu when system shutdown.
3429          */
3430         pr_info("kvm: exiting hardware virtualization\n");
3431         kvm_rebooting = true;
3432         on_each_cpu(hardware_disable_nolock, NULL, 1);
3433         return NOTIFY_OK;
3434 }
3435
3436 static struct notifier_block kvm_reboot_notifier = {
3437         .notifier_call = kvm_reboot,
3438         .priority = 0,
3439 };
3440
3441 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
3442 {
3443         int i;
3444
3445         for (i = 0; i < bus->dev_count; i++) {
3446                 struct kvm_io_device *pos = bus->range[i].dev;
3447
3448                 kvm_iodevice_destructor(pos);
3449         }
3450         kfree(bus);
3451 }
3452
3453 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
3454                                  const struct kvm_io_range *r2)
3455 {
3456         gpa_t addr1 = r1->addr;
3457         gpa_t addr2 = r2->addr;
3458
3459         if (addr1 < addr2)
3460                 return -1;
3461
3462         /* If r2->len == 0, match the exact address.  If r2->len != 0,
3463          * accept any overlapping write.  Any order is acceptable for
3464          * overlapping ranges, because kvm_io_bus_get_first_dev ensures
3465          * we process all of them.
3466          */
3467         if (r2->len) {
3468                 addr1 += r1->len;
3469                 addr2 += r2->len;
3470         }
3471
3472         if (addr1 > addr2)
3473                 return 1;
3474
3475         return 0;
3476 }
3477
3478 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
3479 {
3480         return kvm_io_bus_cmp(p1, p2);
3481 }
3482
3483 static int kvm_io_bus_insert_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev,
3484                           gpa_t addr, int len)
3485 {
3486         bus->range[bus->dev_count++] = (struct kvm_io_range) {
3487                 .addr = addr,
3488                 .len = len,
3489                 .dev = dev,
3490         };
3491
3492         sort(bus->range, bus->dev_count, sizeof(struct kvm_io_range),
3493                 kvm_io_bus_sort_cmp, NULL);
3494
3495         return 0;
3496 }
3497
3498 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
3499                              gpa_t addr, int len)
3500 {
3501         struct kvm_io_range *range, key;
3502         int off;
3503
3504         key = (struct kvm_io_range) {
3505                 .addr = addr,
3506                 .len = len,
3507         };
3508
3509         range = bsearch(&key, bus->range, bus->dev_count,
3510                         sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
3511         if (range == NULL)
3512                 return -ENOENT;
3513
3514         off = range - bus->range;
3515
3516         while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
3517                 off--;
3518
3519         return off;
3520 }
3521
3522 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3523                               struct kvm_io_range *range, const void *val)
3524 {
3525         int idx;
3526
3527         idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3528         if (idx < 0)
3529                 return -EOPNOTSUPP;
3530
3531         while (idx < bus->dev_count &&
3532                 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3533                 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
3534                                         range->len, val))
3535                         return idx;
3536                 idx++;
3537         }
3538
3539         return -EOPNOTSUPP;
3540 }
3541
3542 /* kvm_io_bus_write - called under kvm->slots_lock */
3543 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3544                      int len, const void *val)
3545 {
3546         struct kvm_io_bus *bus;
3547         struct kvm_io_range range;
3548         int r;
3549
3550         range = (struct kvm_io_range) {
3551                 .addr = addr,
3552                 .len = len,
3553         };
3554
3555         bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3556         if (!bus)
3557                 return -ENOMEM;
3558         r = __kvm_io_bus_write(vcpu, bus, &range, val);
3559         return r < 0 ? r : 0;
3560 }
3561
3562 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
3563 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
3564                             gpa_t addr, int len, const void *val, long cookie)
3565 {
3566         struct kvm_io_bus *bus;
3567         struct kvm_io_range range;
3568
3569         range = (struct kvm_io_range) {
3570                 .addr = addr,
3571                 .len = len,
3572         };
3573
3574         bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3575         if (!bus)
3576                 return -ENOMEM;
3577
3578         /* First try the device referenced by cookie. */
3579         if ((cookie >= 0) && (cookie < bus->dev_count) &&
3580             (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
3581                 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
3582                                         val))
3583                         return cookie;
3584
3585         /*
3586          * cookie contained garbage; fall back to search and return the
3587          * correct cookie value.
3588          */
3589         return __kvm_io_bus_write(vcpu, bus, &range, val);
3590 }
3591
3592 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3593                              struct kvm_io_range *range, void *val)
3594 {
3595         int idx;
3596
3597         idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3598         if (idx < 0)
3599                 return -EOPNOTSUPP;
3600
3601         while (idx < bus->dev_count &&
3602                 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3603                 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
3604                                        range->len, val))
3605                         return idx;
3606                 idx++;
3607         }
3608
3609         return -EOPNOTSUPP;
3610 }
3611 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
3612
3613 /* kvm_io_bus_read - called under kvm->slots_lock */
3614 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3615                     int len, void *val)
3616 {
3617         struct kvm_io_bus *bus;
3618         struct kvm_io_range range;
3619         int r;
3620
3621         range = (struct kvm_io_range) {
3622                 .addr = addr,
3623                 .len = len,
3624         };
3625
3626         bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3627         if (!bus)
3628                 return -ENOMEM;
3629         r = __kvm_io_bus_read(vcpu, bus, &range, val);
3630         return r < 0 ? r : 0;
3631 }
3632
3633
3634 /* Caller must hold slots_lock. */
3635 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
3636                             int len, struct kvm_io_device *dev)
3637 {
3638         struct kvm_io_bus *new_bus, *bus;
3639
3640         bus = kvm->buses[bus_idx];
3641         if (!bus)
3642                 return -ENOMEM;
3643
3644         /* exclude ioeventfd which is limited by maximum fd */
3645         if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
3646                 return -ENOSPC;
3647
3648         new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count + 1) *
3649                           sizeof(struct kvm_io_range)), GFP_KERNEL);
3650         if (!new_bus)
3651                 return -ENOMEM;
3652         memcpy(new_bus, bus, sizeof(*bus) + (bus->dev_count *
3653                sizeof(struct kvm_io_range)));
3654         kvm_io_bus_insert_dev(new_bus, dev, addr, len);
3655         rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3656         synchronize_srcu_expedited(&kvm->srcu);
3657         kfree(bus);
3658
3659         return 0;
3660 }
3661
3662 /* Caller must hold slots_lock. */
3663 void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3664                                struct kvm_io_device *dev)
3665 {
3666         int i, j;
3667         struct kvm_io_bus *new_bus, *bus;
3668
3669         bus = kvm->buses[bus_idx];
3670         if (!bus)
3671                 return;
3672
3673         for (i = 0; i < bus->dev_count; i++)
3674                 if (bus->range[i].dev == dev) {
3675                         break;
3676                 }
3677
3678         if (i == bus->dev_count)
3679                 return;
3680
3681         new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count - 1) *
3682                           sizeof(struct kvm_io_range)), GFP_KERNEL);
3683         if (new_bus) {
3684                 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
3685                 new_bus->dev_count--;
3686                 memcpy(new_bus->range + i, bus->range + i + 1,
3687                        (new_bus->dev_count - i) * sizeof(struct kvm_io_range));
3688         } else {
3689                 pr_err("kvm: failed to shrink bus, removing it completely\n");
3690                 for (j = 0; j < bus->dev_count; j++) {
3691                         if (j == i)
3692                                 continue;
3693                         kvm_iodevice_destructor(bus->range[j].dev);
3694                 }
3695         }
3696
3697         rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3698         synchronize_srcu_expedited(&kvm->srcu);
3699         kfree(bus);
3700         return;
3701 }
3702
3703 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3704                                          gpa_t addr)
3705 {
3706         struct kvm_io_bus *bus;
3707         int dev_idx, srcu_idx;
3708         struct kvm_io_device *iodev = NULL;
3709
3710         srcu_idx = srcu_read_lock(&kvm->srcu);
3711
3712         bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
3713         if (!bus)
3714                 goto out_unlock;
3715
3716         dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
3717         if (dev_idx < 0)
3718                 goto out_unlock;
3719
3720         iodev = bus->range[dev_idx].dev;
3721
3722 out_unlock:
3723         srcu_read_unlock(&kvm->srcu, srcu_idx);
3724
3725         return iodev;
3726 }
3727 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
3728
3729 static int kvm_debugfs_open(struct inode *inode, struct file *file,
3730                            int (*get)(void *, u64 *), int (*set)(void *, u64),
3731                            const char *fmt)
3732 {
3733         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3734                                           inode->i_private;
3735
3736         /* The debugfs files are a reference to the kvm struct which
3737          * is still valid when kvm_destroy_vm is called.
3738          * To avoid the race between open and the removal of the debugfs
3739          * directory we test against the users count.
3740          */
3741         if (!atomic_add_unless(&stat_data->kvm->users_count, 1, 0))
3742                 return -ENOENT;
3743
3744         if (simple_attr_open(inode, file, get, set, fmt)) {
3745                 kvm_put_kvm(stat_data->kvm);
3746                 return -ENOMEM;
3747         }
3748
3749         return 0;
3750 }
3751
3752 static int kvm_debugfs_release(struct inode *inode, struct file *file)
3753 {
3754         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3755                                           inode->i_private;
3756
3757         simple_attr_release(inode, file);
3758         kvm_put_kvm(stat_data->kvm);
3759
3760         return 0;
3761 }
3762
3763 static int vm_stat_get_per_vm(void *data, u64 *val)
3764 {
3765         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3766
3767         *val = *(ulong *)((void *)stat_data->kvm + stat_data->offset);
3768
3769         return 0;
3770 }
3771
3772 static int vm_stat_get_per_vm_open(struct inode *inode, struct file *file)
3773 {
3774         __simple_attr_check_format("%llu\n", 0ull);
3775         return kvm_debugfs_open(inode, file, vm_stat_get_per_vm,
3776                                 NULL, "%llu\n");
3777 }
3778
3779 static const struct file_operations vm_stat_get_per_vm_fops = {
3780         .owner   = THIS_MODULE,
3781         .open    = vm_stat_get_per_vm_open,
3782         .release = kvm_debugfs_release,
3783         .read    = simple_attr_read,
3784         .write   = simple_attr_write,
3785         .llseek  = generic_file_llseek,
3786 };
3787
3788 static int vcpu_stat_get_per_vm(void *data, u64 *val)
3789 {
3790         int i;
3791         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3792         struct kvm_vcpu *vcpu;
3793
3794         *val = 0;
3795
3796         kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
3797                 *val += *(u64 *)((void *)vcpu + stat_data->offset);
3798
3799         return 0;
3800 }
3801
3802 static int vcpu_stat_get_per_vm_open(struct inode *inode, struct file *file)
3803 {
3804         __simple_attr_check_format("%llu\n", 0ull);
3805         return kvm_debugfs_open(inode, file, vcpu_stat_get_per_vm,
3806                                  NULL, "%llu\n");
3807 }
3808
3809 static const struct file_operations vcpu_stat_get_per_vm_fops = {
3810         .owner   = THIS_MODULE,
3811         .open    = vcpu_stat_get_per_vm_open,
3812         .release = kvm_debugfs_release,
3813         .read    = simple_attr_read,
3814         .write   = simple_attr_write,
3815         .llseek  = generic_file_llseek,
3816 };
3817
3818 static const struct file_operations *stat_fops_per_vm[] = {
3819         [KVM_STAT_VCPU] = &vcpu_stat_get_per_vm_fops,
3820         [KVM_STAT_VM]   = &vm_stat_get_per_vm_fops,
3821 };
3822
3823 static int vm_stat_get(void *_offset, u64 *val)
3824 {
3825         unsigned offset = (long)_offset;
3826         struct kvm *kvm;
3827         struct kvm_stat_data stat_tmp = {.offset = offset};
3828         u64 tmp_val;
3829
3830         *val = 0;
3831         mutex_lock(&kvm_lock);
3832         list_for_each_entry(kvm, &vm_list, vm_list) {
3833                 stat_tmp.kvm = kvm;
3834                 vm_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
3835                 *val += tmp_val;
3836         }
3837         mutex_unlock(&kvm_lock);
3838         return 0;
3839 }
3840
3841 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
3842
3843 static int vcpu_stat_get(void *_offset, u64 *val)
3844 {
3845         unsigned offset = (long)_offset;
3846         struct kvm *kvm;
3847         struct kvm_stat_data stat_tmp = {.offset = offset};
3848         u64 tmp_val;
3849
3850         *val = 0;
3851         mutex_lock(&kvm_lock);
3852         list_for_each_entry(kvm, &vm_list, vm_list) {
3853                 stat_tmp.kvm = kvm;
3854                 vcpu_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
3855                 *val += tmp_val;
3856         }
3857         mutex_unlock(&kvm_lock);
3858         return 0;
3859 }
3860
3861 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
3862
3863 static const struct file_operations *stat_fops[] = {
3864         [KVM_STAT_VCPU] = &vcpu_stat_fops,
3865         [KVM_STAT_VM]   = &vm_stat_fops,
3866 };
3867
3868 static int kvm_init_debug(void)
3869 {
3870         int r = -EEXIST;
3871         struct kvm_stats_debugfs_item *p;
3872
3873         kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
3874         if (kvm_debugfs_dir == NULL)
3875                 goto out;
3876
3877         kvm_debugfs_num_entries = 0;
3878         for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
3879                 if (!debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
3880                                          (void *)(long)p->offset,
3881                                          stat_fops[p->kind]))
3882                         goto out_dir;
3883         }
3884
3885         return 0;
3886
3887 out_dir:
3888         debugfs_remove_recursive(kvm_debugfs_dir);
3889 out:
3890         return r;
3891 }
3892
3893 static int kvm_suspend(void)
3894 {
3895         if (kvm_usage_count)
3896                 hardware_disable_nolock(NULL);
3897         return 0;
3898 }
3899
3900 static void kvm_resume(void)
3901 {
3902         if (kvm_usage_count) {
3903                 WARN_ON(raw_spin_is_locked(&kvm_count_lock));
3904                 hardware_enable_nolock(NULL);
3905         }
3906 }
3907
3908 static struct syscore_ops kvm_syscore_ops = {
3909         .suspend = kvm_suspend,
3910         .resume = kvm_resume,
3911 };
3912
3913 static inline
3914 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
3915 {
3916         return container_of(pn, struct kvm_vcpu, preempt_notifier);
3917 }
3918
3919 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
3920 {
3921         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
3922
3923         if (vcpu->preempted)
3924                 vcpu->preempted = false;
3925
3926         kvm_arch_sched_in(vcpu, cpu);
3927
3928         kvm_arch_vcpu_load(vcpu, cpu);
3929 }
3930
3931 static void kvm_sched_out(struct preempt_notifier *pn,
3932                           struct task_struct *next)
3933 {
3934         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
3935
3936         if (current->state == TASK_RUNNING)
3937                 vcpu->preempted = true;
3938         kvm_arch_vcpu_put(vcpu);
3939 }
3940
3941 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
3942                   struct module *module)
3943 {
3944         int r;
3945         int cpu;
3946
3947         r = kvm_arch_init(opaque);
3948         if (r)
3949                 goto out_fail;
3950
3951         /*
3952          * kvm_arch_init makes sure there's at most one caller
3953          * for architectures that support multiple implementations,
3954          * like intel and amd on x86.
3955          * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
3956          * conflicts in case kvm is already setup for another implementation.
3957          */
3958         r = kvm_irqfd_init();
3959         if (r)
3960                 goto out_irqfd;
3961
3962         if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
3963                 r = -ENOMEM;
3964                 goto out_free_0;
3965         }
3966
3967         r = kvm_arch_hardware_setup();
3968         if (r < 0)
3969                 goto out_free_0a;
3970
3971         for_each_online_cpu(cpu) {
3972                 smp_call_function_single(cpu,
3973                                 kvm_arch_check_processor_compat,
3974                                 &r, 1);
3975                 if (r < 0)
3976                         goto out_free_1;
3977         }
3978
3979         r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "AP_KVM_STARTING",
3980                                       kvm_starting_cpu, kvm_dying_cpu);
3981         if (r)
3982                 goto out_free_2;
3983         register_reboot_notifier(&kvm_reboot_notifier);
3984
3985         /* A kmem cache lets us meet the alignment requirements of fx_save. */
3986         if (!vcpu_align)
3987                 vcpu_align = __alignof__(struct kvm_vcpu);
3988         kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size, vcpu_align,
3989                                            SLAB_ACCOUNT, NULL);
3990         if (!kvm_vcpu_cache) {
3991                 r = -ENOMEM;
3992                 goto out_free_3;
3993         }
3994
3995         r = kvm_async_pf_init();
3996         if (r)
3997                 goto out_free;
3998
3999         kvm_chardev_ops.owner = module;
4000         kvm_vm_fops.owner = module;
4001         kvm_vcpu_fops.owner = module;
4002
4003         r = misc_register(&kvm_dev);
4004         if (r) {
4005                 pr_err("kvm: misc device register failed\n");
4006                 goto out_unreg;
4007         }
4008
4009         register_syscore_ops(&kvm_syscore_ops);
4010
4011         kvm_preempt_ops.sched_in = kvm_sched_in;
4012         kvm_preempt_ops.sched_out = kvm_sched_out;
4013
4014         r = kvm_init_debug();
4015         if (r) {
4016                 pr_err("kvm: create debugfs files failed\n");
4017                 goto out_undebugfs;
4018         }
4019
4020         r = kvm_vfio_ops_init();
4021         WARN_ON(r);
4022
4023         return 0;
4024
4025 out_undebugfs:
4026         unregister_syscore_ops(&kvm_syscore_ops);
4027         misc_deregister(&kvm_dev);
4028 out_unreg:
4029         kvm_async_pf_deinit();
4030 out_free:
4031         kmem_cache_destroy(kvm_vcpu_cache);
4032 out_free_3:
4033         unregister_reboot_notifier(&kvm_reboot_notifier);
4034         cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4035 out_free_2:
4036 out_free_1:
4037         kvm_arch_hardware_unsetup();
4038 out_free_0a:
4039         free_cpumask_var(cpus_hardware_enabled);
4040 out_free_0:
4041         kvm_irqfd_exit();
4042 out_irqfd:
4043         kvm_arch_exit();
4044 out_fail:
4045         return r;
4046 }
4047 EXPORT_SYMBOL_GPL(kvm_init);
4048
4049 void kvm_exit(void)
4050 {
4051         debugfs_remove_recursive(kvm_debugfs_dir);
4052         misc_deregister(&kvm_dev);
4053         kmem_cache_destroy(kvm_vcpu_cache);
4054         kvm_async_pf_deinit();
4055         unregister_syscore_ops(&kvm_syscore_ops);
4056         unregister_reboot_notifier(&kvm_reboot_notifier);
4057         cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4058         on_each_cpu(hardware_disable_nolock, NULL, 1);
4059         kvm_arch_hardware_unsetup();
4060         kvm_arch_exit();
4061         kvm_irqfd_exit();
4062         free_cpumask_var(cpus_hardware_enabled);
4063         kvm_vfio_ops_exit();
4064 }
4065 EXPORT_SYMBOL_GPL(kvm_exit);
4066
4067 struct kvm_vm_worker_thread_context {
4068         struct kvm *kvm;
4069         struct task_struct *parent;
4070         struct completion init_done;
4071         kvm_vm_thread_fn_t thread_fn;
4072         uintptr_t data;
4073         int err;
4074 };
4075
4076 static int kvm_vm_worker_thread(void *context)
4077 {
4078         /*
4079          * The init_context is allocated on the stack of the parent thread, so
4080          * we have to locally copy anything that is needed beyond initialization
4081          */
4082         struct kvm_vm_worker_thread_context *init_context = context;
4083         struct kvm *kvm = init_context->kvm;
4084         kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
4085         uintptr_t data = init_context->data;
4086         int err;
4087
4088         err = kthread_park(current);
4089         /* kthread_park(current) is never supposed to return an error */
4090         WARN_ON(err != 0);
4091         if (err)
4092                 goto init_complete;
4093
4094         err = cgroup_attach_task_all(init_context->parent, current);
4095         if (err) {
4096                 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
4097                         __func__, err);
4098                 goto init_complete;
4099         }
4100
4101         set_user_nice(current, task_nice(init_context->parent));
4102
4103 init_complete:
4104         init_context->err = err;
4105         complete(&init_context->init_done);
4106         init_context = NULL;
4107
4108         if (err)
4109                 return err;
4110
4111         /* Wait to be woken up by the spawner before proceeding. */
4112         kthread_parkme();
4113
4114         if (!kthread_should_stop())
4115                 err = thread_fn(kvm, data);
4116
4117         return err;
4118 }
4119
4120 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
4121                                 uintptr_t data, const char *name,
4122                                 struct task_struct **thread_ptr)
4123 {
4124         struct kvm_vm_worker_thread_context init_context = {};
4125         struct task_struct *thread;
4126
4127         *thread_ptr = NULL;
4128         init_context.kvm = kvm;
4129         init_context.parent = current;
4130         init_context.thread_fn = thread_fn;
4131         init_context.data = data;
4132         init_completion(&init_context.init_done);
4133
4134         thread = kthread_run(kvm_vm_worker_thread, &init_context,
4135                              "%s-%d", name, task_pid_nr(current));
4136         if (IS_ERR(thread))
4137                 return PTR_ERR(thread);
4138
4139         /* kthread_run is never supposed to return NULL */
4140         WARN_ON(thread == NULL);
4141
4142         wait_for_completion(&init_context.init_done);
4143
4144         if (!init_context.err)
4145                 *thread_ptr = thread;
4146
4147         return init_context.err;
4148 }