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