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