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