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