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