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