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