GNU Linux-libre 4.19.207-gnu1
[releases.git] / virt / kvm / kvm_main.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
9  *
10  * Authors:
11  *   Avi Kivity   <avi@qumranet.com>
12  *   Yaniv Kamay  <yaniv@qumranet.com>
13  *
14  * This work is licensed under the terms of the GNU GPL, version 2.  See
15  * the COPYING file in the top-level directory.
16  *
17  */
18
19 #include <kvm/iodev.h>
20
21 #include <linux/kvm_host.h>
22 #include <linux/kvm.h>
23 #include <linux/module.h>
24 #include <linux/errno.h>
25 #include <linux/percpu.h>
26 #include <linux/mm.h>
27 #include <linux/miscdevice.h>
28 #include <linux/vmalloc.h>
29 #include <linux/reboot.h>
30 #include <linux/debugfs.h>
31 #include <linux/highmem.h>
32 #include <linux/file.h>
33 #include <linux/syscore_ops.h>
34 #include <linux/cpu.h>
35 #include <linux/sched/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         BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
2755
2756         /* Now it's all set up, let userspace reach it */
2757         kvm_get_kvm(kvm);
2758         r = create_vcpu_fd(vcpu);
2759         if (r < 0) {
2760                 kvm_put_kvm(kvm);
2761                 goto unlock_vcpu_destroy;
2762         }
2763
2764         kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
2765
2766         /*
2767          * Pairs with smp_rmb() in kvm_get_vcpu.  Write kvm->vcpus
2768          * before kvm->online_vcpu's incremented value.
2769          */
2770         smp_wmb();
2771         atomic_inc(&kvm->online_vcpus);
2772
2773         mutex_unlock(&kvm->lock);
2774         kvm_arch_vcpu_postcreate(vcpu);
2775         return r;
2776
2777 unlock_vcpu_destroy:
2778         mutex_unlock(&kvm->lock);
2779         debugfs_remove_recursive(vcpu->debugfs_dentry);
2780 vcpu_destroy:
2781         kvm_arch_vcpu_destroy(vcpu);
2782 vcpu_decrement:
2783         mutex_lock(&kvm->lock);
2784         kvm->created_vcpus--;
2785         mutex_unlock(&kvm->lock);
2786         return r;
2787 }
2788
2789 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
2790 {
2791         if (sigset) {
2792                 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
2793                 vcpu->sigset_active = 1;
2794                 vcpu->sigset = *sigset;
2795         } else
2796                 vcpu->sigset_active = 0;
2797         return 0;
2798 }
2799
2800 static long kvm_vcpu_ioctl(struct file *filp,
2801                            unsigned int ioctl, unsigned long arg)
2802 {
2803         struct kvm_vcpu *vcpu = filp->private_data;
2804         void __user *argp = (void __user *)arg;
2805         int r;
2806         struct kvm_fpu *fpu = NULL;
2807         struct kvm_sregs *kvm_sregs = NULL;
2808
2809         if (vcpu->kvm->mm != current->mm)
2810                 return -EIO;
2811
2812         if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
2813                 return -EINVAL;
2814
2815         /*
2816          * Some architectures have vcpu ioctls that are asynchronous to vcpu
2817          * execution; mutex_lock() would break them.
2818          */
2819         r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
2820         if (r != -ENOIOCTLCMD)
2821                 return r;
2822
2823         if (mutex_lock_killable(&vcpu->mutex))
2824                 return -EINTR;
2825         switch (ioctl) {
2826         case KVM_RUN: {
2827                 struct pid *oldpid;
2828                 r = -EINVAL;
2829                 if (arg)
2830                         goto out;
2831                 oldpid = rcu_access_pointer(vcpu->pid);
2832                 if (unlikely(oldpid != task_pid(current))) {
2833                         /* The thread running this VCPU changed. */
2834                         struct pid *newpid;
2835
2836                         r = kvm_arch_vcpu_run_pid_change(vcpu);
2837                         if (r)
2838                                 break;
2839
2840                         newpid = get_task_pid(current, PIDTYPE_PID);
2841                         rcu_assign_pointer(vcpu->pid, newpid);
2842                         if (oldpid)
2843                                 synchronize_rcu();
2844                         put_pid(oldpid);
2845                 }
2846                 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
2847                 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
2848                 break;
2849         }
2850         case KVM_GET_REGS: {
2851                 struct kvm_regs *kvm_regs;
2852
2853                 r = -ENOMEM;
2854                 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
2855                 if (!kvm_regs)
2856                         goto out;
2857                 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
2858                 if (r)
2859                         goto out_free1;
2860                 r = -EFAULT;
2861                 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
2862                         goto out_free1;
2863                 r = 0;
2864 out_free1:
2865                 kfree(kvm_regs);
2866                 break;
2867         }
2868         case KVM_SET_REGS: {
2869                 struct kvm_regs *kvm_regs;
2870
2871                 r = -ENOMEM;
2872                 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
2873                 if (IS_ERR(kvm_regs)) {
2874                         r = PTR_ERR(kvm_regs);
2875                         goto out;
2876                 }
2877                 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
2878                 kfree(kvm_regs);
2879                 break;
2880         }
2881         case KVM_GET_SREGS: {
2882                 kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
2883                 r = -ENOMEM;
2884                 if (!kvm_sregs)
2885                         goto out;
2886                 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
2887                 if (r)
2888                         goto out;
2889                 r = -EFAULT;
2890                 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
2891                         goto out;
2892                 r = 0;
2893                 break;
2894         }
2895         case KVM_SET_SREGS: {
2896                 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
2897                 if (IS_ERR(kvm_sregs)) {
2898                         r = PTR_ERR(kvm_sregs);
2899                         kvm_sregs = NULL;
2900                         goto out;
2901                 }
2902                 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
2903                 break;
2904         }
2905         case KVM_GET_MP_STATE: {
2906                 struct kvm_mp_state mp_state;
2907
2908                 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
2909                 if (r)
2910                         goto out;
2911                 r = -EFAULT;
2912                 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
2913                         goto out;
2914                 r = 0;
2915                 break;
2916         }
2917         case KVM_SET_MP_STATE: {
2918                 struct kvm_mp_state mp_state;
2919
2920                 r = -EFAULT;
2921                 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
2922                         goto out;
2923                 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
2924                 break;
2925         }
2926         case KVM_TRANSLATE: {
2927                 struct kvm_translation tr;
2928
2929                 r = -EFAULT;
2930                 if (copy_from_user(&tr, argp, sizeof(tr)))
2931                         goto out;
2932                 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
2933                 if (r)
2934                         goto out;
2935                 r = -EFAULT;
2936                 if (copy_to_user(argp, &tr, sizeof(tr)))
2937                         goto out;
2938                 r = 0;
2939                 break;
2940         }
2941         case KVM_SET_GUEST_DEBUG: {
2942                 struct kvm_guest_debug dbg;
2943
2944                 r = -EFAULT;
2945                 if (copy_from_user(&dbg, argp, sizeof(dbg)))
2946                         goto out;
2947                 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
2948                 break;
2949         }
2950         case KVM_SET_SIGNAL_MASK: {
2951                 struct kvm_signal_mask __user *sigmask_arg = argp;
2952                 struct kvm_signal_mask kvm_sigmask;
2953                 sigset_t sigset, *p;
2954
2955                 p = NULL;
2956                 if (argp) {
2957                         r = -EFAULT;
2958                         if (copy_from_user(&kvm_sigmask, argp,
2959                                            sizeof(kvm_sigmask)))
2960                                 goto out;
2961                         r = -EINVAL;
2962                         if (kvm_sigmask.len != sizeof(sigset))
2963                                 goto out;
2964                         r = -EFAULT;
2965                         if (copy_from_user(&sigset, sigmask_arg->sigset,
2966                                            sizeof(sigset)))
2967                                 goto out;
2968                         p = &sigset;
2969                 }
2970                 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
2971                 break;
2972         }
2973         case KVM_GET_FPU: {
2974                 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
2975                 r = -ENOMEM;
2976                 if (!fpu)
2977                         goto out;
2978                 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
2979                 if (r)
2980                         goto out;
2981                 r = -EFAULT;
2982                 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
2983                         goto out;
2984                 r = 0;
2985                 break;
2986         }
2987         case KVM_SET_FPU: {
2988                 fpu = memdup_user(argp, sizeof(*fpu));
2989                 if (IS_ERR(fpu)) {
2990                         r = PTR_ERR(fpu);
2991                         fpu = NULL;
2992                         goto out;
2993                 }
2994                 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
2995                 break;
2996         }
2997         default:
2998                 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2999         }
3000 out:
3001         mutex_unlock(&vcpu->mutex);
3002         kfree(fpu);
3003         kfree(kvm_sregs);
3004         return r;
3005 }
3006
3007 #ifdef CONFIG_KVM_COMPAT
3008 static long kvm_vcpu_compat_ioctl(struct file *filp,
3009                                   unsigned int ioctl, unsigned long arg)
3010 {
3011         struct kvm_vcpu *vcpu = filp->private_data;
3012         void __user *argp = compat_ptr(arg);
3013         int r;
3014
3015         if (vcpu->kvm->mm != current->mm)
3016                 return -EIO;
3017
3018         switch (ioctl) {
3019         case KVM_SET_SIGNAL_MASK: {
3020                 struct kvm_signal_mask __user *sigmask_arg = argp;
3021                 struct kvm_signal_mask kvm_sigmask;
3022                 sigset_t sigset;
3023
3024                 if (argp) {
3025                         r = -EFAULT;
3026                         if (copy_from_user(&kvm_sigmask, argp,
3027                                            sizeof(kvm_sigmask)))
3028                                 goto out;
3029                         r = -EINVAL;
3030                         if (kvm_sigmask.len != sizeof(compat_sigset_t))
3031                                 goto out;
3032                         r = -EFAULT;
3033                         if (get_compat_sigset(&sigset, (void *)sigmask_arg->sigset))
3034                                 goto out;
3035                         r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
3036                 } else
3037                         r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
3038                 break;
3039         }
3040         default:
3041                 r = kvm_vcpu_ioctl(filp, ioctl, arg);
3042         }
3043
3044 out:
3045         return r;
3046 }
3047 #endif
3048
3049 static int kvm_device_ioctl_attr(struct kvm_device *dev,
3050                                  int (*accessor)(struct kvm_device *dev,
3051                                                  struct kvm_device_attr *attr),
3052                                  unsigned long arg)
3053 {
3054         struct kvm_device_attr attr;
3055
3056         if (!accessor)
3057                 return -EPERM;
3058
3059         if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
3060                 return -EFAULT;
3061
3062         return accessor(dev, &attr);
3063 }
3064
3065 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
3066                              unsigned long arg)
3067 {
3068         struct kvm_device *dev = filp->private_data;
3069
3070         if (dev->kvm->mm != current->mm)
3071                 return -EIO;
3072
3073         switch (ioctl) {
3074         case KVM_SET_DEVICE_ATTR:
3075                 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
3076         case KVM_GET_DEVICE_ATTR:
3077                 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
3078         case KVM_HAS_DEVICE_ATTR:
3079                 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
3080         default:
3081                 if (dev->ops->ioctl)
3082                         return dev->ops->ioctl(dev, ioctl, arg);
3083
3084                 return -ENOTTY;
3085         }
3086 }
3087
3088 static int kvm_device_release(struct inode *inode, struct file *filp)
3089 {
3090         struct kvm_device *dev = filp->private_data;
3091         struct kvm *kvm = dev->kvm;
3092
3093         kvm_put_kvm(kvm);
3094         return 0;
3095 }
3096
3097 static const struct file_operations kvm_device_fops = {
3098         .unlocked_ioctl = kvm_device_ioctl,
3099         .release = kvm_device_release,
3100         KVM_COMPAT(kvm_device_ioctl),
3101 };
3102
3103 struct kvm_device *kvm_device_from_filp(struct file *filp)
3104 {
3105         if (filp->f_op != &kvm_device_fops)
3106                 return NULL;
3107
3108         return filp->private_data;
3109 }
3110
3111 static struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
3112 #ifdef CONFIG_KVM_MPIC
3113         [KVM_DEV_TYPE_FSL_MPIC_20]      = &kvm_mpic_ops,
3114         [KVM_DEV_TYPE_FSL_MPIC_42]      = &kvm_mpic_ops,
3115 #endif
3116 };
3117
3118 int kvm_register_device_ops(struct kvm_device_ops *ops, u32 type)
3119 {
3120         if (type >= ARRAY_SIZE(kvm_device_ops_table))
3121                 return -ENOSPC;
3122
3123         if (kvm_device_ops_table[type] != NULL)
3124                 return -EEXIST;
3125
3126         kvm_device_ops_table[type] = ops;
3127         return 0;
3128 }
3129
3130 void kvm_unregister_device_ops(u32 type)
3131 {
3132         if (kvm_device_ops_table[type] != NULL)
3133                 kvm_device_ops_table[type] = NULL;
3134 }
3135
3136 static int kvm_ioctl_create_device(struct kvm *kvm,
3137                                    struct kvm_create_device *cd)
3138 {
3139         struct kvm_device_ops *ops = NULL;
3140         struct kvm_device *dev;
3141         bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
3142         int type;
3143         int ret;
3144
3145         if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
3146                 return -ENODEV;
3147
3148         type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
3149         ops = kvm_device_ops_table[type];
3150         if (ops == NULL)
3151                 return -ENODEV;
3152
3153         if (test)
3154                 return 0;
3155
3156         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3157         if (!dev)
3158                 return -ENOMEM;
3159
3160         dev->ops = ops;
3161         dev->kvm = kvm;
3162
3163         mutex_lock(&kvm->lock);
3164         ret = ops->create(dev, type);
3165         if (ret < 0) {
3166                 mutex_unlock(&kvm->lock);
3167                 kfree(dev);
3168                 return ret;
3169         }
3170         list_add(&dev->vm_node, &kvm->devices);
3171         mutex_unlock(&kvm->lock);
3172
3173         if (ops->init)
3174                 ops->init(dev);
3175
3176         kvm_get_kvm(kvm);
3177         ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
3178         if (ret < 0) {
3179                 kvm_put_kvm(kvm);
3180                 mutex_lock(&kvm->lock);
3181                 list_del(&dev->vm_node);
3182                 mutex_unlock(&kvm->lock);
3183                 ops->destroy(dev);
3184                 return ret;
3185         }
3186
3187         cd->fd = ret;
3188         return 0;
3189 }
3190
3191 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3192 {
3193         switch (arg) {
3194         case KVM_CAP_USER_MEMORY:
3195         case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3196         case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
3197         case KVM_CAP_INTERNAL_ERROR_DATA:
3198 #ifdef CONFIG_HAVE_KVM_MSI
3199         case KVM_CAP_SIGNAL_MSI:
3200 #endif
3201 #ifdef CONFIG_HAVE_KVM_IRQFD
3202         case KVM_CAP_IRQFD:
3203         case KVM_CAP_IRQFD_RESAMPLE:
3204 #endif
3205         case KVM_CAP_IOEVENTFD_ANY_LENGTH:
3206         case KVM_CAP_CHECK_EXTENSION_VM:
3207                 return 1;
3208 #ifdef CONFIG_KVM_MMIO
3209         case KVM_CAP_COALESCED_MMIO:
3210                 return KVM_COALESCED_MMIO_PAGE_OFFSET;
3211 #endif
3212 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3213         case KVM_CAP_IRQ_ROUTING:
3214                 return KVM_MAX_IRQ_ROUTES;
3215 #endif
3216 #if KVM_ADDRESS_SPACE_NUM > 1
3217         case KVM_CAP_MULTI_ADDRESS_SPACE:
3218                 return KVM_ADDRESS_SPACE_NUM;
3219 #endif
3220         default:
3221                 break;
3222         }
3223         return kvm_vm_ioctl_check_extension(kvm, arg);
3224 }
3225
3226 static long kvm_vm_ioctl(struct file *filp,
3227                            unsigned int ioctl, unsigned long arg)
3228 {
3229         struct kvm *kvm = filp->private_data;
3230         void __user *argp = (void __user *)arg;
3231         int r;
3232
3233         if (kvm->mm != current->mm)
3234                 return -EIO;
3235         switch (ioctl) {
3236         case KVM_CREATE_VCPU:
3237                 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
3238                 break;
3239         case KVM_SET_USER_MEMORY_REGION: {
3240                 struct kvm_userspace_memory_region kvm_userspace_mem;
3241
3242                 r = -EFAULT;
3243                 if (copy_from_user(&kvm_userspace_mem, argp,
3244                                                 sizeof(kvm_userspace_mem)))
3245                         goto out;
3246
3247                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
3248                 break;
3249         }
3250         case KVM_GET_DIRTY_LOG: {
3251                 struct kvm_dirty_log log;
3252
3253                 r = -EFAULT;
3254                 if (copy_from_user(&log, argp, sizeof(log)))
3255                         goto out;
3256                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3257                 break;
3258         }
3259 #ifdef CONFIG_KVM_MMIO
3260         case KVM_REGISTER_COALESCED_MMIO: {
3261                 struct kvm_coalesced_mmio_zone zone;
3262
3263                 r = -EFAULT;
3264                 if (copy_from_user(&zone, argp, sizeof(zone)))
3265                         goto out;
3266                 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
3267                 break;
3268         }
3269         case KVM_UNREGISTER_COALESCED_MMIO: {
3270                 struct kvm_coalesced_mmio_zone zone;
3271
3272                 r = -EFAULT;
3273                 if (copy_from_user(&zone, argp, sizeof(zone)))
3274                         goto out;
3275                 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
3276                 break;
3277         }
3278 #endif
3279         case KVM_IRQFD: {
3280                 struct kvm_irqfd data;
3281
3282                 r = -EFAULT;
3283                 if (copy_from_user(&data, argp, sizeof(data)))
3284                         goto out;
3285                 r = kvm_irqfd(kvm, &data);
3286                 break;
3287         }
3288         case KVM_IOEVENTFD: {
3289                 struct kvm_ioeventfd data;
3290
3291                 r = -EFAULT;
3292                 if (copy_from_user(&data, argp, sizeof(data)))
3293                         goto out;
3294                 r = kvm_ioeventfd(kvm, &data);
3295                 break;
3296         }
3297 #ifdef CONFIG_HAVE_KVM_MSI
3298         case KVM_SIGNAL_MSI: {
3299                 struct kvm_msi msi;
3300
3301                 r = -EFAULT;
3302                 if (copy_from_user(&msi, argp, sizeof(msi)))
3303                         goto out;
3304                 r = kvm_send_userspace_msi(kvm, &msi);
3305                 break;
3306         }
3307 #endif
3308 #ifdef __KVM_HAVE_IRQ_LINE
3309         case KVM_IRQ_LINE_STATUS:
3310         case KVM_IRQ_LINE: {
3311                 struct kvm_irq_level irq_event;
3312
3313                 r = -EFAULT;
3314                 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
3315                         goto out;
3316
3317                 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3318                                         ioctl == KVM_IRQ_LINE_STATUS);
3319                 if (r)
3320                         goto out;
3321
3322                 r = -EFAULT;
3323                 if (ioctl == KVM_IRQ_LINE_STATUS) {
3324                         if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
3325                                 goto out;
3326                 }
3327
3328                 r = 0;
3329                 break;
3330         }
3331 #endif
3332 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3333         case KVM_SET_GSI_ROUTING: {
3334                 struct kvm_irq_routing routing;
3335                 struct kvm_irq_routing __user *urouting;
3336                 struct kvm_irq_routing_entry *entries = NULL;
3337
3338                 r = -EFAULT;
3339                 if (copy_from_user(&routing, argp, sizeof(routing)))
3340                         goto out;
3341                 r = -EINVAL;
3342                 if (!kvm_arch_can_set_irq_routing(kvm))
3343                         goto out;
3344                 if (routing.nr > KVM_MAX_IRQ_ROUTES)
3345                         goto out;
3346                 if (routing.flags)
3347                         goto out;
3348                 if (routing.nr) {
3349                         r = -ENOMEM;
3350                         entries = vmalloc(array_size(sizeof(*entries),
3351                                                      routing.nr));
3352                         if (!entries)
3353                                 goto out;
3354                         r = -EFAULT;
3355                         urouting = argp;
3356                         if (copy_from_user(entries, urouting->entries,
3357                                            routing.nr * sizeof(*entries)))
3358                                 goto out_free_irq_routing;
3359                 }
3360                 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3361                                         routing.flags);
3362 out_free_irq_routing:
3363                 vfree(entries);
3364                 break;
3365         }
3366 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
3367         case KVM_CREATE_DEVICE: {
3368                 struct kvm_create_device cd;
3369
3370                 r = -EFAULT;
3371                 if (copy_from_user(&cd, argp, sizeof(cd)))
3372                         goto out;
3373
3374                 r = kvm_ioctl_create_device(kvm, &cd);
3375                 if (r)
3376                         goto out;
3377
3378                 r = -EFAULT;
3379                 if (copy_to_user(argp, &cd, sizeof(cd)))
3380                         goto out;
3381
3382                 r = 0;
3383                 break;
3384         }
3385         case KVM_CHECK_EXTENSION:
3386                 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3387                 break;
3388         default:
3389                 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
3390         }
3391 out:
3392         return r;
3393 }
3394
3395 #ifdef CONFIG_KVM_COMPAT
3396 struct compat_kvm_dirty_log {
3397         __u32 slot;
3398         __u32 padding1;
3399         union {
3400                 compat_uptr_t dirty_bitmap; /* one bit per page */
3401                 __u64 padding2;
3402         };
3403 };
3404
3405 static long kvm_vm_compat_ioctl(struct file *filp,
3406                            unsigned int ioctl, unsigned long arg)
3407 {
3408         struct kvm *kvm = filp->private_data;
3409         int r;
3410
3411         if (kvm->mm != current->mm)
3412                 return -EIO;
3413         switch (ioctl) {
3414         case KVM_GET_DIRTY_LOG: {
3415                 struct compat_kvm_dirty_log compat_log;
3416                 struct kvm_dirty_log log;
3417
3418                 if (copy_from_user(&compat_log, (void __user *)arg,
3419                                    sizeof(compat_log)))
3420                         return -EFAULT;
3421                 log.slot         = compat_log.slot;
3422                 log.padding1     = compat_log.padding1;
3423                 log.padding2     = compat_log.padding2;
3424                 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3425
3426                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3427                 break;
3428         }
3429         default:
3430                 r = kvm_vm_ioctl(filp, ioctl, arg);
3431         }
3432         return r;
3433 }
3434 #endif
3435
3436 static struct file_operations kvm_vm_fops = {
3437         .release        = kvm_vm_release,
3438         .unlocked_ioctl = kvm_vm_ioctl,
3439         .llseek         = noop_llseek,
3440         KVM_COMPAT(kvm_vm_compat_ioctl),
3441 };
3442
3443 static int kvm_dev_ioctl_create_vm(unsigned long type)
3444 {
3445         int r;
3446         struct kvm *kvm;
3447         struct file *file;
3448
3449         kvm = kvm_create_vm(type);
3450         if (IS_ERR(kvm))
3451                 return PTR_ERR(kvm);
3452 #ifdef CONFIG_KVM_MMIO
3453         r = kvm_coalesced_mmio_init(kvm);
3454         if (r < 0)
3455                 goto put_kvm;
3456 #endif
3457         r = get_unused_fd_flags(O_CLOEXEC);
3458         if (r < 0)
3459                 goto put_kvm;
3460
3461         file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
3462         if (IS_ERR(file)) {
3463                 put_unused_fd(r);
3464                 r = PTR_ERR(file);
3465                 goto put_kvm;
3466         }
3467
3468         /*
3469          * Don't call kvm_put_kvm anymore at this point; file->f_op is
3470          * already set, with ->release() being kvm_vm_release().  In error
3471          * cases it will be called by the final fput(file) and will take
3472          * care of doing kvm_put_kvm(kvm).
3473          */
3474         if (kvm_create_vm_debugfs(kvm, r) < 0) {
3475                 put_unused_fd(r);
3476                 fput(file);
3477                 return -ENOMEM;
3478         }
3479         kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
3480
3481         fd_install(r, file);
3482         return r;
3483
3484 put_kvm:
3485         kvm_put_kvm(kvm);
3486         return r;
3487 }
3488
3489 static long kvm_dev_ioctl(struct file *filp,
3490                           unsigned int ioctl, unsigned long arg)
3491 {
3492         long r = -EINVAL;
3493
3494         switch (ioctl) {
3495         case KVM_GET_API_VERSION:
3496                 if (arg)
3497                         goto out;
3498                 r = KVM_API_VERSION;
3499                 break;
3500         case KVM_CREATE_VM:
3501                 r = kvm_dev_ioctl_create_vm(arg);
3502                 break;
3503         case KVM_CHECK_EXTENSION:
3504                 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
3505                 break;
3506         case KVM_GET_VCPU_MMAP_SIZE:
3507                 if (arg)
3508                         goto out;
3509                 r = PAGE_SIZE;     /* struct kvm_run */
3510 #ifdef CONFIG_X86
3511                 r += PAGE_SIZE;    /* pio data page */
3512 #endif
3513 #ifdef CONFIG_KVM_MMIO
3514                 r += PAGE_SIZE;    /* coalesced mmio ring page */
3515 #endif
3516                 break;
3517         case KVM_TRACE_ENABLE:
3518         case KVM_TRACE_PAUSE:
3519         case KVM_TRACE_DISABLE:
3520                 r = -EOPNOTSUPP;
3521                 break;
3522         default:
3523                 return kvm_arch_dev_ioctl(filp, ioctl, arg);
3524         }
3525 out:
3526         return r;
3527 }
3528
3529 static struct file_operations kvm_chardev_ops = {
3530         .unlocked_ioctl = kvm_dev_ioctl,
3531         .llseek         = noop_llseek,
3532         KVM_COMPAT(kvm_dev_ioctl),
3533 };
3534
3535 static struct miscdevice kvm_dev = {
3536         KVM_MINOR,
3537         "kvm",
3538         &kvm_chardev_ops,
3539 };
3540
3541 static void hardware_enable_nolock(void *junk)
3542 {
3543         int cpu = raw_smp_processor_id();
3544         int r;
3545
3546         if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
3547                 return;
3548
3549         cpumask_set_cpu(cpu, cpus_hardware_enabled);
3550
3551         r = kvm_arch_hardware_enable();
3552
3553         if (r) {
3554                 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3555                 atomic_inc(&hardware_enable_failed);
3556                 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
3557         }
3558 }
3559
3560 static int kvm_starting_cpu(unsigned int cpu)
3561 {
3562         raw_spin_lock(&kvm_count_lock);
3563         if (kvm_usage_count)
3564                 hardware_enable_nolock(NULL);
3565         raw_spin_unlock(&kvm_count_lock);
3566         return 0;
3567 }
3568
3569 static void hardware_disable_nolock(void *junk)
3570 {
3571         int cpu = raw_smp_processor_id();
3572
3573         if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
3574                 return;
3575         cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3576         kvm_arch_hardware_disable();
3577 }
3578
3579 static int kvm_dying_cpu(unsigned int cpu)
3580 {
3581         raw_spin_lock(&kvm_count_lock);
3582         if (kvm_usage_count)
3583                 hardware_disable_nolock(NULL);
3584         raw_spin_unlock(&kvm_count_lock);
3585         return 0;
3586 }
3587
3588 static void hardware_disable_all_nolock(void)
3589 {
3590         BUG_ON(!kvm_usage_count);
3591
3592         kvm_usage_count--;
3593         if (!kvm_usage_count)
3594                 on_each_cpu(hardware_disable_nolock, NULL, 1);
3595 }
3596
3597 static void hardware_disable_all(void)
3598 {
3599         raw_spin_lock(&kvm_count_lock);
3600         hardware_disable_all_nolock();
3601         raw_spin_unlock(&kvm_count_lock);
3602 }
3603
3604 static int hardware_enable_all(void)
3605 {
3606         int r = 0;
3607
3608         raw_spin_lock(&kvm_count_lock);
3609
3610         kvm_usage_count++;
3611         if (kvm_usage_count == 1) {
3612                 atomic_set(&hardware_enable_failed, 0);
3613                 on_each_cpu(hardware_enable_nolock, NULL, 1);
3614
3615                 if (atomic_read(&hardware_enable_failed)) {
3616                         hardware_disable_all_nolock();
3617                         r = -EBUSY;
3618                 }
3619         }
3620
3621         raw_spin_unlock(&kvm_count_lock);
3622
3623         return r;
3624 }
3625
3626 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
3627                       void *v)
3628 {
3629         /*
3630          * Some (well, at least mine) BIOSes hang on reboot if
3631          * in vmx root mode.
3632          *
3633          * And Intel TXT required VMX off for all cpu when system shutdown.
3634          */
3635         pr_info("kvm: exiting hardware virtualization\n");
3636         kvm_rebooting = true;
3637         on_each_cpu(hardware_disable_nolock, NULL, 1);
3638         return NOTIFY_OK;
3639 }
3640
3641 static struct notifier_block kvm_reboot_notifier = {
3642         .notifier_call = kvm_reboot,
3643         .priority = 0,
3644 };
3645
3646 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
3647 {
3648         int i;
3649
3650         for (i = 0; i < bus->dev_count; i++) {
3651                 struct kvm_io_device *pos = bus->range[i].dev;
3652
3653                 kvm_iodevice_destructor(pos);
3654         }
3655         kfree(bus);
3656 }
3657
3658 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
3659                                  const struct kvm_io_range *r2)
3660 {
3661         gpa_t addr1 = r1->addr;
3662         gpa_t addr2 = r2->addr;
3663
3664         if (addr1 < addr2)
3665                 return -1;
3666
3667         /* If r2->len == 0, match the exact address.  If r2->len != 0,
3668          * accept any overlapping write.  Any order is acceptable for
3669          * overlapping ranges, because kvm_io_bus_get_first_dev ensures
3670          * we process all of them.
3671          */
3672         if (r2->len) {
3673                 addr1 += r1->len;
3674                 addr2 += r2->len;
3675         }
3676
3677         if (addr1 > addr2)
3678                 return 1;
3679
3680         return 0;
3681 }
3682
3683 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
3684 {
3685         return kvm_io_bus_cmp(p1, p2);
3686 }
3687
3688 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
3689                              gpa_t addr, int len)
3690 {
3691         struct kvm_io_range *range, key;
3692         int off;
3693
3694         key = (struct kvm_io_range) {
3695                 .addr = addr,
3696                 .len = len,
3697         };
3698
3699         range = bsearch(&key, bus->range, bus->dev_count,
3700                         sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
3701         if (range == NULL)
3702                 return -ENOENT;
3703
3704         off = range - bus->range;
3705
3706         while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
3707                 off--;
3708
3709         return off;
3710 }
3711
3712 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3713                               struct kvm_io_range *range, const void *val)
3714 {
3715         int idx;
3716
3717         idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3718         if (idx < 0)
3719                 return -EOPNOTSUPP;
3720
3721         while (idx < bus->dev_count &&
3722                 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3723                 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
3724                                         range->len, val))
3725                         return idx;
3726                 idx++;
3727         }
3728
3729         return -EOPNOTSUPP;
3730 }
3731
3732 /* kvm_io_bus_write - called under kvm->slots_lock */
3733 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3734                      int len, const void *val)
3735 {
3736         struct kvm_io_bus *bus;
3737         struct kvm_io_range range;
3738         int r;
3739
3740         range = (struct kvm_io_range) {
3741                 .addr = addr,
3742                 .len = len,
3743         };
3744
3745         bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3746         if (!bus)
3747                 return -ENOMEM;
3748         r = __kvm_io_bus_write(vcpu, bus, &range, val);
3749         return r < 0 ? r : 0;
3750 }
3751
3752 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
3753 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
3754                             gpa_t addr, int len, const void *val, long cookie)
3755 {
3756         struct kvm_io_bus *bus;
3757         struct kvm_io_range range;
3758
3759         range = (struct kvm_io_range) {
3760                 .addr = addr,
3761                 .len = len,
3762         };
3763
3764         bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3765         if (!bus)
3766                 return -ENOMEM;
3767
3768         /* First try the device referenced by cookie. */
3769         if ((cookie >= 0) && (cookie < bus->dev_count) &&
3770             (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
3771                 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
3772                                         val))
3773                         return cookie;
3774
3775         /*
3776          * cookie contained garbage; fall back to search and return the
3777          * correct cookie value.
3778          */
3779         return __kvm_io_bus_write(vcpu, bus, &range, val);
3780 }
3781
3782 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3783                              struct kvm_io_range *range, void *val)
3784 {
3785         int idx;
3786
3787         idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3788         if (idx < 0)
3789                 return -EOPNOTSUPP;
3790
3791         while (idx < bus->dev_count &&
3792                 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3793                 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
3794                                        range->len, val))
3795                         return idx;
3796                 idx++;
3797         }
3798
3799         return -EOPNOTSUPP;
3800 }
3801 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
3802
3803 /* kvm_io_bus_read - called under kvm->slots_lock */
3804 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3805                     int len, void *val)
3806 {
3807         struct kvm_io_bus *bus;
3808         struct kvm_io_range range;
3809         int r;
3810
3811         range = (struct kvm_io_range) {
3812                 .addr = addr,
3813                 .len = len,
3814         };
3815
3816         bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3817         if (!bus)
3818                 return -ENOMEM;
3819         r = __kvm_io_bus_read(vcpu, bus, &range, val);
3820         return r < 0 ? r : 0;
3821 }
3822
3823
3824 /* Caller must hold slots_lock. */
3825 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
3826                             int len, struct kvm_io_device *dev)
3827 {
3828         int i;
3829         struct kvm_io_bus *new_bus, *bus;
3830         struct kvm_io_range range;
3831
3832         bus = kvm_get_bus(kvm, bus_idx);
3833         if (!bus)
3834                 return -ENOMEM;
3835
3836         /* exclude ioeventfd which is limited by maximum fd */
3837         if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
3838                 return -ENOSPC;
3839
3840         new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count + 1) *
3841                           sizeof(struct kvm_io_range)), GFP_KERNEL);
3842         if (!new_bus)
3843                 return -ENOMEM;
3844
3845         range = (struct kvm_io_range) {
3846                 .addr = addr,
3847                 .len = len,
3848                 .dev = dev,
3849         };
3850
3851         for (i = 0; i < bus->dev_count; i++)
3852                 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
3853                         break;
3854
3855         memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
3856         new_bus->dev_count++;
3857         new_bus->range[i] = range;
3858         memcpy(new_bus->range + i + 1, bus->range + i,
3859                 (bus->dev_count - i) * sizeof(struct kvm_io_range));
3860         rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3861         synchronize_srcu_expedited(&kvm->srcu);
3862         kfree(bus);
3863
3864         return 0;
3865 }
3866
3867 /* Caller must hold slots_lock. */
3868 void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3869                                struct kvm_io_device *dev)
3870 {
3871         int i, j;
3872         struct kvm_io_bus *new_bus, *bus;
3873
3874         bus = kvm_get_bus(kvm, bus_idx);
3875         if (!bus)
3876                 return;
3877
3878         for (i = 0; i < bus->dev_count; i++)
3879                 if (bus->range[i].dev == dev) {
3880                         break;
3881                 }
3882
3883         if (i == bus->dev_count)
3884                 return;
3885
3886         new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count - 1) *
3887                           sizeof(struct kvm_io_range)), GFP_KERNEL);
3888         if (new_bus) {
3889                 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
3890                 new_bus->dev_count--;
3891                 memcpy(new_bus->range + i, bus->range + i + 1,
3892                        (new_bus->dev_count - i) * sizeof(struct kvm_io_range));
3893         } else {
3894                 pr_err("kvm: failed to shrink bus, removing it completely\n");
3895                 for (j = 0; j < bus->dev_count; j++) {
3896                         if (j == i)
3897                                 continue;
3898                         kvm_iodevice_destructor(bus->range[j].dev);
3899                 }
3900         }
3901
3902         rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3903         synchronize_srcu_expedited(&kvm->srcu);
3904         kfree(bus);
3905         return;
3906 }
3907
3908 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3909                                          gpa_t addr)
3910 {
3911         struct kvm_io_bus *bus;
3912         int dev_idx, srcu_idx;
3913         struct kvm_io_device *iodev = NULL;
3914
3915         srcu_idx = srcu_read_lock(&kvm->srcu);
3916
3917         bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
3918         if (!bus)
3919                 goto out_unlock;
3920
3921         dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
3922         if (dev_idx < 0)
3923                 goto out_unlock;
3924
3925         iodev = bus->range[dev_idx].dev;
3926
3927 out_unlock:
3928         srcu_read_unlock(&kvm->srcu, srcu_idx);
3929
3930         return iodev;
3931 }
3932 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
3933
3934 static int kvm_debugfs_open(struct inode *inode, struct file *file,
3935                            int (*get)(void *, u64 *), int (*set)(void *, u64),
3936                            const char *fmt)
3937 {
3938         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3939                                           inode->i_private;
3940
3941         /* The debugfs files are a reference to the kvm struct which
3942          * is still valid when kvm_destroy_vm is called.
3943          * To avoid the race between open and the removal of the debugfs
3944          * directory we test against the users count.
3945          */
3946         if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
3947                 return -ENOENT;
3948
3949         if (simple_attr_open(inode, file, get,
3950                              stat_data->mode & S_IWUGO ? set : NULL,
3951                              fmt)) {
3952                 kvm_put_kvm(stat_data->kvm);
3953                 return -ENOMEM;
3954         }
3955
3956         return 0;
3957 }
3958
3959 static int kvm_debugfs_release(struct inode *inode, struct file *file)
3960 {
3961         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3962                                           inode->i_private;
3963
3964         simple_attr_release(inode, file);
3965         kvm_put_kvm(stat_data->kvm);
3966
3967         return 0;
3968 }
3969
3970 static int vm_stat_get_per_vm(void *data, u64 *val)
3971 {
3972         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3973
3974         *val = *(ulong *)((void *)stat_data->kvm + stat_data->offset);
3975
3976         return 0;
3977 }
3978
3979 static int vm_stat_clear_per_vm(void *data, u64 val)
3980 {
3981         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3982
3983         if (val)
3984                 return -EINVAL;
3985
3986         *(ulong *)((void *)stat_data->kvm + stat_data->offset) = 0;
3987
3988         return 0;
3989 }
3990
3991 static int vm_stat_get_per_vm_open(struct inode *inode, struct file *file)
3992 {
3993         __simple_attr_check_format("%llu\n", 0ull);
3994         return kvm_debugfs_open(inode, file, vm_stat_get_per_vm,
3995                                 vm_stat_clear_per_vm, "%llu\n");
3996 }
3997
3998 static const struct file_operations vm_stat_get_per_vm_fops = {
3999         .owner   = THIS_MODULE,
4000         .open    = vm_stat_get_per_vm_open,
4001         .release = kvm_debugfs_release,
4002         .read    = simple_attr_read,
4003         .write   = simple_attr_write,
4004         .llseek  = no_llseek,
4005 };
4006
4007 static int vcpu_stat_get_per_vm(void *data, u64 *val)
4008 {
4009         int i;
4010         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4011         struct kvm_vcpu *vcpu;
4012
4013         *val = 0;
4014
4015         kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
4016                 *val += *(u64 *)((void *)vcpu + stat_data->offset);
4017
4018         return 0;
4019 }
4020
4021 static int vcpu_stat_clear_per_vm(void *data, u64 val)
4022 {
4023         int i;
4024         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4025         struct kvm_vcpu *vcpu;
4026
4027         if (val)
4028                 return -EINVAL;
4029
4030         kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
4031                 *(u64 *)((void *)vcpu + stat_data->offset) = 0;
4032
4033         return 0;
4034 }
4035
4036 static int vcpu_stat_get_per_vm_open(struct inode *inode, struct file *file)
4037 {
4038         __simple_attr_check_format("%llu\n", 0ull);
4039         return kvm_debugfs_open(inode, file, vcpu_stat_get_per_vm,
4040                                  vcpu_stat_clear_per_vm, "%llu\n");
4041 }
4042
4043 static const struct file_operations vcpu_stat_get_per_vm_fops = {
4044         .owner   = THIS_MODULE,
4045         .open    = vcpu_stat_get_per_vm_open,
4046         .release = kvm_debugfs_release,
4047         .read    = simple_attr_read,
4048         .write   = simple_attr_write,
4049         .llseek  = no_llseek,
4050 };
4051
4052 static const struct file_operations *stat_fops_per_vm[] = {
4053         [KVM_STAT_VCPU] = &vcpu_stat_get_per_vm_fops,
4054         [KVM_STAT_VM]   = &vm_stat_get_per_vm_fops,
4055 };
4056
4057 static int vm_stat_get(void *_offset, u64 *val)
4058 {
4059         unsigned offset = (long)_offset;
4060         struct kvm *kvm;
4061         struct kvm_stat_data stat_tmp = {.offset = offset};
4062         u64 tmp_val;
4063
4064         *val = 0;
4065         mutex_lock(&kvm_lock);
4066         list_for_each_entry(kvm, &vm_list, vm_list) {
4067                 stat_tmp.kvm = kvm;
4068                 vm_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
4069                 *val += tmp_val;
4070         }
4071         mutex_unlock(&kvm_lock);
4072         return 0;
4073 }
4074
4075 static int vm_stat_clear(void *_offset, u64 val)
4076 {
4077         unsigned offset = (long)_offset;
4078         struct kvm *kvm;
4079         struct kvm_stat_data stat_tmp = {.offset = offset};
4080
4081         if (val)
4082                 return -EINVAL;
4083
4084         mutex_lock(&kvm_lock);
4085         list_for_each_entry(kvm, &vm_list, vm_list) {
4086                 stat_tmp.kvm = kvm;
4087                 vm_stat_clear_per_vm((void *)&stat_tmp, 0);
4088         }
4089         mutex_unlock(&kvm_lock);
4090
4091         return 0;
4092 }
4093
4094 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
4095
4096 static int vcpu_stat_get(void *_offset, u64 *val)
4097 {
4098         unsigned offset = (long)_offset;
4099         struct kvm *kvm;
4100         struct kvm_stat_data stat_tmp = {.offset = offset};
4101         u64 tmp_val;
4102
4103         *val = 0;
4104         mutex_lock(&kvm_lock);
4105         list_for_each_entry(kvm, &vm_list, vm_list) {
4106                 stat_tmp.kvm = kvm;
4107                 vcpu_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
4108                 *val += tmp_val;
4109         }
4110         mutex_unlock(&kvm_lock);
4111         return 0;
4112 }
4113
4114 static int vcpu_stat_clear(void *_offset, u64 val)
4115 {
4116         unsigned offset = (long)_offset;
4117         struct kvm *kvm;
4118         struct kvm_stat_data stat_tmp = {.offset = offset};
4119
4120         if (val)
4121                 return -EINVAL;
4122
4123         mutex_lock(&kvm_lock);
4124         list_for_each_entry(kvm, &vm_list, vm_list) {
4125                 stat_tmp.kvm = kvm;
4126                 vcpu_stat_clear_per_vm((void *)&stat_tmp, 0);
4127         }
4128         mutex_unlock(&kvm_lock);
4129
4130         return 0;
4131 }
4132
4133 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
4134                         "%llu\n");
4135
4136 static const struct file_operations *stat_fops[] = {
4137         [KVM_STAT_VCPU] = &vcpu_stat_fops,
4138         [KVM_STAT_VM]   = &vm_stat_fops,
4139 };
4140
4141 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
4142 {
4143         struct kobj_uevent_env *env;
4144         unsigned long long created, active;
4145
4146         if (!kvm_dev.this_device || !kvm)
4147                 return;
4148
4149         mutex_lock(&kvm_lock);
4150         if (type == KVM_EVENT_CREATE_VM) {
4151                 kvm_createvm_count++;
4152                 kvm_active_vms++;
4153         } else if (type == KVM_EVENT_DESTROY_VM) {
4154                 kvm_active_vms--;
4155         }
4156         created = kvm_createvm_count;
4157         active = kvm_active_vms;
4158         mutex_unlock(&kvm_lock);
4159
4160         env = kzalloc(sizeof(*env), GFP_KERNEL);
4161         if (!env)
4162                 return;
4163
4164         add_uevent_var(env, "CREATED=%llu", created);
4165         add_uevent_var(env, "COUNT=%llu", active);
4166
4167         if (type == KVM_EVENT_CREATE_VM) {
4168                 add_uevent_var(env, "EVENT=create");
4169                 kvm->userspace_pid = task_pid_nr(current);
4170         } else if (type == KVM_EVENT_DESTROY_VM) {
4171                 add_uevent_var(env, "EVENT=destroy");
4172         }
4173         add_uevent_var(env, "PID=%d", kvm->userspace_pid);
4174
4175         if (!IS_ERR_OR_NULL(kvm->debugfs_dentry)) {
4176                 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL);
4177
4178                 if (p) {
4179                         tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
4180                         if (!IS_ERR(tmp))
4181                                 add_uevent_var(env, "STATS_PATH=%s", tmp);
4182                         kfree(p);
4183                 }
4184         }
4185         /* no need for checks, since we are adding at most only 5 keys */
4186         env->envp[env->envp_idx++] = NULL;
4187         kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
4188         kfree(env);
4189 }
4190
4191 static void kvm_init_debug(void)
4192 {
4193         struct kvm_stats_debugfs_item *p;
4194
4195         kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
4196
4197         kvm_debugfs_num_entries = 0;
4198         for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
4199                 int mode = p->mode ? p->mode : 0644;
4200                 debugfs_create_file(p->name, mode, kvm_debugfs_dir,
4201                                     (void *)(long)p->offset,
4202                                     stat_fops[p->kind]);
4203         }
4204 }
4205
4206 static int kvm_suspend(void)
4207 {
4208         if (kvm_usage_count)
4209                 hardware_disable_nolock(NULL);
4210         return 0;
4211 }
4212
4213 static void kvm_resume(void)
4214 {
4215         if (kvm_usage_count) {
4216                 WARN_ON(raw_spin_is_locked(&kvm_count_lock));
4217                 hardware_enable_nolock(NULL);
4218         }
4219 }
4220
4221 static struct syscore_ops kvm_syscore_ops = {
4222         .suspend = kvm_suspend,
4223         .resume = kvm_resume,
4224 };
4225
4226 static inline
4227 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
4228 {
4229         return container_of(pn, struct kvm_vcpu, preempt_notifier);
4230 }
4231
4232 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
4233 {
4234         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4235
4236         if (vcpu->preempted)
4237                 vcpu->preempted = false;
4238
4239         kvm_arch_sched_in(vcpu, cpu);
4240
4241         kvm_arch_vcpu_load(vcpu, cpu);
4242 }
4243
4244 static void kvm_sched_out(struct preempt_notifier *pn,
4245                           struct task_struct *next)
4246 {
4247         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4248
4249         if (current->state == TASK_RUNNING)
4250                 vcpu->preempted = true;
4251         kvm_arch_vcpu_put(vcpu);
4252 }
4253
4254 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
4255                   struct module *module)
4256 {
4257         int r;
4258         int cpu;
4259
4260         r = kvm_arch_init(opaque);
4261         if (r)
4262                 goto out_fail;
4263
4264         /*
4265          * kvm_arch_init makes sure there's at most one caller
4266          * for architectures that support multiple implementations,
4267          * like intel and amd on x86.
4268          * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
4269          * conflicts in case kvm is already setup for another implementation.
4270          */
4271         r = kvm_irqfd_init();
4272         if (r)
4273                 goto out_irqfd;
4274
4275         if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
4276                 r = -ENOMEM;
4277                 goto out_free_0;
4278         }
4279
4280         r = kvm_arch_hardware_setup();
4281         if (r < 0)
4282                 goto out_free_0a;
4283
4284         for_each_online_cpu(cpu) {
4285                 smp_call_function_single(cpu,
4286                                 kvm_arch_check_processor_compat,
4287                                 &r, 1);
4288                 if (r < 0)
4289                         goto out_free_1;
4290         }
4291
4292         r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
4293                                       kvm_starting_cpu, kvm_dying_cpu);
4294         if (r)
4295                 goto out_free_2;
4296         register_reboot_notifier(&kvm_reboot_notifier);
4297
4298         /* A kmem cache lets us meet the alignment requirements of fx_save. */
4299         if (!vcpu_align)
4300                 vcpu_align = __alignof__(struct kvm_vcpu);
4301         kvm_vcpu_cache =
4302                 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
4303                                            SLAB_ACCOUNT,
4304                                            offsetof(struct kvm_vcpu, arch),
4305                                            sizeof_field(struct kvm_vcpu, arch),
4306                                            NULL);
4307         if (!kvm_vcpu_cache) {
4308                 r = -ENOMEM;
4309                 goto out_free_3;
4310         }
4311
4312         r = kvm_async_pf_init();
4313         if (r)
4314                 goto out_free;
4315
4316         kvm_chardev_ops.owner = module;
4317         kvm_vm_fops.owner = module;
4318         kvm_vcpu_fops.owner = module;
4319
4320         r = misc_register(&kvm_dev);
4321         if (r) {
4322                 pr_err("kvm: misc device register failed\n");
4323                 goto out_unreg;
4324         }
4325
4326         register_syscore_ops(&kvm_syscore_ops);
4327
4328         kvm_preempt_ops.sched_in = kvm_sched_in;
4329         kvm_preempt_ops.sched_out = kvm_sched_out;
4330
4331         kvm_init_debug();
4332
4333         r = kvm_vfio_ops_init();
4334         WARN_ON(r);
4335
4336         return 0;
4337
4338 out_unreg:
4339         kvm_async_pf_deinit();
4340 out_free:
4341         kmem_cache_destroy(kvm_vcpu_cache);
4342 out_free_3:
4343         unregister_reboot_notifier(&kvm_reboot_notifier);
4344         cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4345 out_free_2:
4346 out_free_1:
4347         kvm_arch_hardware_unsetup();
4348 out_free_0a:
4349         free_cpumask_var(cpus_hardware_enabled);
4350 out_free_0:
4351         kvm_irqfd_exit();
4352 out_irqfd:
4353         kvm_arch_exit();
4354 out_fail:
4355         return r;
4356 }
4357 EXPORT_SYMBOL_GPL(kvm_init);
4358
4359 void kvm_exit(void)
4360 {
4361         debugfs_remove_recursive(kvm_debugfs_dir);
4362         misc_deregister(&kvm_dev);
4363         kmem_cache_destroy(kvm_vcpu_cache);
4364         kvm_async_pf_deinit();
4365         unregister_syscore_ops(&kvm_syscore_ops);
4366         unregister_reboot_notifier(&kvm_reboot_notifier);
4367         cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4368         on_each_cpu(hardware_disable_nolock, NULL, 1);
4369         kvm_arch_hardware_unsetup();
4370         kvm_arch_exit();
4371         kvm_irqfd_exit();
4372         free_cpumask_var(cpus_hardware_enabled);
4373         kvm_vfio_ops_exit();
4374 }
4375 EXPORT_SYMBOL_GPL(kvm_exit);
4376
4377 struct kvm_vm_worker_thread_context {
4378         struct kvm *kvm;
4379         struct task_struct *parent;
4380         struct completion init_done;
4381         kvm_vm_thread_fn_t thread_fn;
4382         uintptr_t data;
4383         int err;
4384 };
4385
4386 static int kvm_vm_worker_thread(void *context)
4387 {
4388         /*
4389          * The init_context is allocated on the stack of the parent thread, so
4390          * we have to locally copy anything that is needed beyond initialization
4391          */
4392         struct kvm_vm_worker_thread_context *init_context = context;
4393         struct kvm *kvm = init_context->kvm;
4394         kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
4395         uintptr_t data = init_context->data;
4396         int err;
4397
4398         err = kthread_park(current);
4399         /* kthread_park(current) is never supposed to return an error */
4400         WARN_ON(err != 0);
4401         if (err)
4402                 goto init_complete;
4403
4404         err = cgroup_attach_task_all(init_context->parent, current);
4405         if (err) {
4406                 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
4407                         __func__, err);
4408                 goto init_complete;
4409         }
4410
4411         set_user_nice(current, task_nice(init_context->parent));
4412
4413 init_complete:
4414         init_context->err = err;
4415         complete(&init_context->init_done);
4416         init_context = NULL;
4417
4418         if (err)
4419                 return err;
4420
4421         /* Wait to be woken up by the spawner before proceeding. */
4422         kthread_parkme();
4423
4424         if (!kthread_should_stop())
4425                 err = thread_fn(kvm, data);
4426
4427         return err;
4428 }
4429
4430 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
4431                                 uintptr_t data, const char *name,
4432                                 struct task_struct **thread_ptr)
4433 {
4434         struct kvm_vm_worker_thread_context init_context = {};
4435         struct task_struct *thread;
4436
4437         *thread_ptr = NULL;
4438         init_context.kvm = kvm;
4439         init_context.parent = current;
4440         init_context.thread_fn = thread_fn;
4441         init_context.data = data;
4442         init_completion(&init_context.init_done);
4443
4444         thread = kthread_run(kvm_vm_worker_thread, &init_context,
4445                              "%s-%d", name, task_pid_nr(current));
4446         if (IS_ERR(thread))
4447                 return PTR_ERR(thread);
4448
4449         /* kthread_run is never supposed to return NULL */
4450         WARN_ON(thread == NULL);
4451
4452         wait_for_completion(&init_context.init_done);
4453
4454         if (!init_context.err)
4455                 *thread_ptr = thread;
4456
4457         return init_context.err;
4458 }