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