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