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