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