GNU Linux-libre 4.14.262-gnu1
[releases.git] / virt / kvm / kvm_main.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
9  *
10  * Authors:
11  *   Avi Kivity   <avi@qumranet.com>
12  *   Yaniv Kamay  <yaniv@qumranet.com>
13  *
14  * This work is licensed under the terms of the GNU GPL, version 2.  See
15  * the COPYING file in the top-level directory.
16  *
17  */
18
19 #include <kvm/iodev.h>
20
21 #include <linux/kvm_host.h>
22 #include <linux/kvm.h>
23 #include <linux/module.h>
24 #include <linux/errno.h>
25 #include <linux/percpu.h>
26 #include <linux/mm.h>
27 #include <linux/miscdevice.h>
28 #include <linux/vmalloc.h>
29 #include <linux/reboot.h>
30 #include <linux/debugfs.h>
31 #include <linux/highmem.h>
32 #include <linux/file.h>
33 #include <linux/syscore_ops.h>
34 #include <linux/cpu.h>
35 #include <linux/sched/signal.h>
36 #include <linux/sched/mm.h>
37 #include <linux/sched/stat.h>
38 #include <linux/cpumask.h>
39 #include <linux/smp.h>
40 #include <linux/anon_inodes.h>
41 #include <linux/profile.h>
42 #include <linux/kvm_para.h>
43 #include <linux/pagemap.h>
44 #include <linux/mman.h>
45 #include <linux/swap.h>
46 #include <linux/bitops.h>
47 #include <linux/spinlock.h>
48 #include <linux/compat.h>
49 #include <linux/srcu.h>
50 #include <linux/hugetlb.h>
51 #include <linux/slab.h>
52 #include <linux/sort.h>
53 #include <linux/bsearch.h>
54 #include <linux/kthread.h>
55
56 #include <asm/processor.h>
57 #include <asm/io.h>
58 #include <asm/ioctl.h>
59 #include <linux/uaccess.h>
60 #include <asm/pgtable.h>
61
62 #include "coalesced_mmio.h"
63 #include "async_pf.h"
64 #include "vfio.h"
65
66 #define CREATE_TRACE_POINTS
67 #include <trace/events/kvm.h>
68
69 /* Worst case buffer size needed for holding an integer. */
70 #define ITOA_MAX_LEN 12
71
72 MODULE_AUTHOR("Qumranet");
73 MODULE_LICENSE("GPL");
74
75 /* Architectures should define their poll value according to the halt latency */
76 unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
77 module_param(halt_poll_ns, uint, 0644);
78 EXPORT_SYMBOL_GPL(halt_poll_ns);
79
80 /* Default doubles per-vcpu halt_poll_ns. */
81 unsigned int halt_poll_ns_grow = 2;
82 module_param(halt_poll_ns_grow, uint, 0644);
83 EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
84
85 /* Default resets per-vcpu halt_poll_ns . */
86 unsigned int halt_poll_ns_shrink;
87 module_param(halt_poll_ns_shrink, uint, 0644);
88 EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
89
90 /*
91  * Ordering of locks:
92  *
93  *      kvm->lock --> kvm->slots_lock --> kvm->irq_lock
94  */
95
96 DEFINE_MUTEX(kvm_lock);
97 static DEFINE_RAW_SPINLOCK(kvm_count_lock);
98 LIST_HEAD(vm_list);
99
100 static cpumask_var_t cpus_hardware_enabled;
101 static int kvm_usage_count;
102 static atomic_t hardware_enable_failed;
103
104 struct kmem_cache *kvm_vcpu_cache;
105 EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
106
107 static __read_mostly struct preempt_ops kvm_preempt_ops;
108
109 struct dentry *kvm_debugfs_dir;
110 EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
111
112 static int kvm_debugfs_num_entries;
113 static const struct file_operations *stat_fops_per_vm[];
114
115 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
116                            unsigned long arg);
117 #ifdef CONFIG_KVM_COMPAT
118 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
119                                   unsigned long arg);
120 #endif
121 static int hardware_enable_all(void);
122 static void hardware_disable_all(void);
123
124 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
125
126 static void kvm_release_pfn_dirty(kvm_pfn_t pfn);
127 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot, gfn_t gfn);
128
129 __visible bool kvm_rebooting;
130 EXPORT_SYMBOL_GPL(kvm_rebooting);
131
132 static bool largepages_enabled = true;
133
134 #define KVM_EVENT_CREATE_VM 0
135 #define KVM_EVENT_DESTROY_VM 1
136 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
137 static unsigned long long kvm_createvm_count;
138 static unsigned long long kvm_active_vms;
139
140 __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
141                 unsigned long start, unsigned long end)
142 {
143 }
144
145 bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
146 {
147         /*
148          * The metadata used by is_zone_device_page() to determine whether or
149          * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
150          * the device has been pinned, e.g. by get_user_pages().  WARN if the
151          * page_count() is zero to help detect bad usage of this helper.
152          */
153         if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
154                 return false;
155
156         return is_zone_device_page(pfn_to_page(pfn));
157 }
158
159 bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
160 {
161         /*
162          * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
163          * perspective they are "normal" pages, albeit with slightly different
164          * usage rules.
165          */
166         if (pfn_valid(pfn))
167                 return PageReserved(pfn_to_page(pfn)) &&
168                        !is_zero_pfn(pfn) &&
169                        !kvm_is_zone_device_pfn(pfn);
170
171         return true;
172 }
173
174 /*
175  * Switches to specified vcpu, until a matching vcpu_put()
176  */
177 int vcpu_load(struct kvm_vcpu *vcpu)
178 {
179         int cpu;
180
181         if (mutex_lock_killable(&vcpu->mutex))
182                 return -EINTR;
183         cpu = get_cpu();
184         preempt_notifier_register(&vcpu->preempt_notifier);
185         kvm_arch_vcpu_load(vcpu, cpu);
186         put_cpu();
187         return 0;
188 }
189 EXPORT_SYMBOL_GPL(vcpu_load);
190
191 void vcpu_put(struct kvm_vcpu *vcpu)
192 {
193         preempt_disable();
194         kvm_arch_vcpu_put(vcpu);
195         preempt_notifier_unregister(&vcpu->preempt_notifier);
196         preempt_enable();
197         mutex_unlock(&vcpu->mutex);
198 }
199 EXPORT_SYMBOL_GPL(vcpu_put);
200
201 /* TODO: merge with kvm_arch_vcpu_should_kick */
202 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
203 {
204         int mode = kvm_vcpu_exiting_guest_mode(vcpu);
205
206         /*
207          * We need to wait for the VCPU to reenable interrupts and get out of
208          * READING_SHADOW_PAGE_TABLES mode.
209          */
210         if (req & KVM_REQUEST_WAIT)
211                 return mode != OUTSIDE_GUEST_MODE;
212
213         /*
214          * Need to kick a running VCPU, but otherwise there is nothing to do.
215          */
216         return mode == IN_GUEST_MODE;
217 }
218
219 static void ack_flush(void *_completed)
220 {
221 }
222
223 static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
224 {
225         if (unlikely(!cpus))
226                 cpus = cpu_online_mask;
227
228         if (cpumask_empty(cpus))
229                 return false;
230
231         smp_call_function_many(cpus, ack_flush, NULL, wait);
232         return true;
233 }
234
235 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
236 {
237         int i, cpu, me;
238         cpumask_var_t cpus;
239         bool called;
240         struct kvm_vcpu *vcpu;
241
242         zalloc_cpumask_var(&cpus, GFP_ATOMIC);
243
244         me = get_cpu();
245         kvm_for_each_vcpu(i, vcpu, kvm) {
246                 kvm_make_request(req, vcpu);
247                 cpu = vcpu->cpu;
248
249                 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
250                         continue;
251
252                 if (cpus != NULL && cpu != -1 && cpu != me &&
253                     kvm_request_needs_ipi(vcpu, req))
254                         __cpumask_set_cpu(cpu, cpus);
255         }
256         called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT));
257         put_cpu();
258         free_cpumask_var(cpus);
259         return called;
260 }
261
262 #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
263 void kvm_flush_remote_tlbs(struct kvm *kvm)
264 {
265         /*
266          * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
267          * kvm_make_all_cpus_request.
268          */
269         long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
270
271         /*
272          * We want to publish modifications to the page tables before reading
273          * mode. Pairs with a memory barrier in arch-specific code.
274          * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
275          * and smp_mb in walk_shadow_page_lockless_begin/end.
276          * - powerpc: smp_mb in kvmppc_prepare_to_enter.
277          *
278          * There is already an smp_mb__after_atomic() before
279          * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
280          * barrier here.
281          */
282         if (kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
283                 ++kvm->stat.remote_tlb_flush;
284         cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
285 }
286 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
287 #endif
288
289 void kvm_reload_remote_mmus(struct kvm *kvm)
290 {
291         kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
292 }
293
294 int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
295 {
296         struct page *page;
297         int r;
298
299         mutex_init(&vcpu->mutex);
300         vcpu->cpu = -1;
301         vcpu->kvm = kvm;
302         vcpu->vcpu_id = id;
303         vcpu->pid = NULL;
304         init_swait_queue_head(&vcpu->wq);
305         kvm_async_pf_vcpu_init(vcpu);
306
307         vcpu->pre_pcpu = -1;
308         INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
309
310         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
311         if (!page) {
312                 r = -ENOMEM;
313                 goto fail;
314         }
315         vcpu->run = page_address(page);
316
317         kvm_vcpu_set_in_spin_loop(vcpu, false);
318         kvm_vcpu_set_dy_eligible(vcpu, false);
319         vcpu->preempted = false;
320
321         r = kvm_arch_vcpu_init(vcpu);
322         if (r < 0)
323                 goto fail_free_run;
324         return 0;
325
326 fail_free_run:
327         free_page((unsigned long)vcpu->run);
328 fail:
329         return r;
330 }
331 EXPORT_SYMBOL_GPL(kvm_vcpu_init);
332
333 void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
334 {
335         /*
336          * no need for rcu_read_lock as VCPU_RUN is the only place that
337          * will change the vcpu->pid pointer and on uninit all file
338          * descriptors are already gone.
339          */
340         put_pid(rcu_dereference_protected(vcpu->pid, 1));
341         kvm_arch_vcpu_uninit(vcpu);
342         free_page((unsigned long)vcpu->run);
343 }
344 EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
345
346 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
347 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
348 {
349         return container_of(mn, struct kvm, mmu_notifier);
350 }
351
352 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
353                                         struct mm_struct *mm,
354                                         unsigned long address,
355                                         pte_t pte)
356 {
357         struct kvm *kvm = mmu_notifier_to_kvm(mn);
358         int idx;
359
360         idx = srcu_read_lock(&kvm->srcu);
361         spin_lock(&kvm->mmu_lock);
362         kvm->mmu_notifier_seq++;
363         kvm_set_spte_hva(kvm, address, pte);
364         spin_unlock(&kvm->mmu_lock);
365         srcu_read_unlock(&kvm->srcu, idx);
366 }
367
368 static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
369                                                     struct mm_struct *mm,
370                                                     unsigned long start,
371                                                     unsigned long end)
372 {
373         struct kvm *kvm = mmu_notifier_to_kvm(mn);
374         int need_tlb_flush = 0, idx;
375
376         idx = srcu_read_lock(&kvm->srcu);
377         spin_lock(&kvm->mmu_lock);
378         /*
379          * The count increase must become visible at unlock time as no
380          * spte can be established without taking the mmu_lock and
381          * count is also read inside the mmu_lock critical section.
382          */
383         kvm->mmu_notifier_count++;
384         need_tlb_flush = kvm_unmap_hva_range(kvm, start, end);
385         /* we've to flush the tlb before the pages can be freed */
386         if (need_tlb_flush || kvm->tlbs_dirty)
387                 kvm_flush_remote_tlbs(kvm);
388
389         spin_unlock(&kvm->mmu_lock);
390
391         kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
392
393         srcu_read_unlock(&kvm->srcu, idx);
394 }
395
396 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
397                                                   struct mm_struct *mm,
398                                                   unsigned long start,
399                                                   unsigned long end)
400 {
401         struct kvm *kvm = mmu_notifier_to_kvm(mn);
402
403         spin_lock(&kvm->mmu_lock);
404         /*
405          * This sequence increase will notify the kvm page fault that
406          * the page that is going to be mapped in the spte could have
407          * been freed.
408          */
409         kvm->mmu_notifier_seq++;
410         smp_wmb();
411         /*
412          * The above sequence increase must be visible before the
413          * below count decrease, which is ensured by the smp_wmb above
414          * in conjunction with the smp_rmb in mmu_notifier_retry().
415          */
416         kvm->mmu_notifier_count--;
417         spin_unlock(&kvm->mmu_lock);
418
419         BUG_ON(kvm->mmu_notifier_count < 0);
420 }
421
422 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
423                                               struct mm_struct *mm,
424                                               unsigned long start,
425                                               unsigned long end)
426 {
427         struct kvm *kvm = mmu_notifier_to_kvm(mn);
428         int young, idx;
429
430         idx = srcu_read_lock(&kvm->srcu);
431         spin_lock(&kvm->mmu_lock);
432
433         young = kvm_age_hva(kvm, start, end);
434         if (young)
435                 kvm_flush_remote_tlbs(kvm);
436
437         spin_unlock(&kvm->mmu_lock);
438         srcu_read_unlock(&kvm->srcu, idx);
439
440         return young;
441 }
442
443 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
444                                         struct mm_struct *mm,
445                                         unsigned long start,
446                                         unsigned long end)
447 {
448         struct kvm *kvm = mmu_notifier_to_kvm(mn);
449         int young, idx;
450
451         idx = srcu_read_lock(&kvm->srcu);
452         spin_lock(&kvm->mmu_lock);
453         /*
454          * Even though we do not flush TLB, this will still adversely
455          * affect performance on pre-Haswell Intel EPT, where there is
456          * no EPT Access Bit to clear so that we have to tear down EPT
457          * tables instead. If we find this unacceptable, we can always
458          * add a parameter to kvm_age_hva so that it effectively doesn't
459          * do anything on clear_young.
460          *
461          * Also note that currently we never issue secondary TLB flushes
462          * from clear_young, leaving this job up to the regular system
463          * cadence. If we find this inaccurate, we might come up with a
464          * more sophisticated heuristic later.
465          */
466         young = kvm_age_hva(kvm, start, end);
467         spin_unlock(&kvm->mmu_lock);
468         srcu_read_unlock(&kvm->srcu, idx);
469
470         return young;
471 }
472
473 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
474                                        struct mm_struct *mm,
475                                        unsigned long address)
476 {
477         struct kvm *kvm = mmu_notifier_to_kvm(mn);
478         int young, idx;
479
480         idx = srcu_read_lock(&kvm->srcu);
481         spin_lock(&kvm->mmu_lock);
482         young = kvm_test_age_hva(kvm, address);
483         spin_unlock(&kvm->mmu_lock);
484         srcu_read_unlock(&kvm->srcu, idx);
485
486         return young;
487 }
488
489 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
490                                      struct mm_struct *mm)
491 {
492         struct kvm *kvm = mmu_notifier_to_kvm(mn);
493         int idx;
494
495         idx = srcu_read_lock(&kvm->srcu);
496         kvm_arch_flush_shadow_all(kvm);
497         srcu_read_unlock(&kvm->srcu, idx);
498 }
499
500 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
501         .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
502         .invalidate_range_end   = kvm_mmu_notifier_invalidate_range_end,
503         .clear_flush_young      = kvm_mmu_notifier_clear_flush_young,
504         .clear_young            = kvm_mmu_notifier_clear_young,
505         .test_young             = kvm_mmu_notifier_test_young,
506         .change_pte             = kvm_mmu_notifier_change_pte,
507         .release                = kvm_mmu_notifier_release,
508 };
509
510 static int kvm_init_mmu_notifier(struct kvm *kvm)
511 {
512         kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
513         return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
514 }
515
516 #else  /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
517
518 static int kvm_init_mmu_notifier(struct kvm *kvm)
519 {
520         return 0;
521 }
522
523 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
524
525 static struct kvm_memslots *kvm_alloc_memslots(void)
526 {
527         int i;
528         struct kvm_memslots *slots;
529
530         slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
531         if (!slots)
532                 return NULL;
533
534         for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
535                 slots->id_to_index[i] = slots->memslots[i].id = i;
536
537         return slots;
538 }
539
540 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
541 {
542         if (!memslot->dirty_bitmap)
543                 return;
544
545         kvfree(memslot->dirty_bitmap);
546         memslot->dirty_bitmap = NULL;
547 }
548
549 /*
550  * Free any memory in @free but not in @dont.
551  */
552 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
553                               struct kvm_memory_slot *dont)
554 {
555         if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
556                 kvm_destroy_dirty_bitmap(free);
557
558         kvm_arch_free_memslot(kvm, free, dont);
559
560         free->npages = 0;
561 }
562
563 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
564 {
565         struct kvm_memory_slot *memslot;
566
567         if (!slots)
568                 return;
569
570         kvm_for_each_memslot(memslot, slots)
571                 kvm_free_memslot(kvm, memslot, NULL);
572
573         kvfree(slots);
574 }
575
576 static void kvm_destroy_vm_debugfs(struct kvm *kvm)
577 {
578         int i;
579
580         if (!kvm->debugfs_dentry)
581                 return;
582
583         debugfs_remove_recursive(kvm->debugfs_dentry);
584
585         if (kvm->debugfs_stat_data) {
586                 for (i = 0; i < kvm_debugfs_num_entries; i++)
587                         kfree(kvm->debugfs_stat_data[i]);
588                 kfree(kvm->debugfs_stat_data);
589         }
590 }
591
592 static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
593 {
594         char dir_name[ITOA_MAX_LEN * 2];
595         struct kvm_stat_data *stat_data;
596         struct kvm_stats_debugfs_item *p;
597
598         if (!debugfs_initialized())
599                 return 0;
600
601         snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
602         kvm->debugfs_dentry = debugfs_create_dir(dir_name,
603                                                  kvm_debugfs_dir);
604         if (!kvm->debugfs_dentry)
605                 return -ENOMEM;
606
607         kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
608                                          sizeof(*kvm->debugfs_stat_data),
609                                          GFP_KERNEL);
610         if (!kvm->debugfs_stat_data)
611                 return -ENOMEM;
612
613         for (p = debugfs_entries; p->name; p++) {
614                 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL);
615                 if (!stat_data)
616                         return -ENOMEM;
617
618                 stat_data->kvm = kvm;
619                 stat_data->offset = p->offset;
620                 stat_data->mode = p->mode ? p->mode : 0644;
621                 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
622                 if (!debugfs_create_file(p->name, stat_data->mode,
623                                          kvm->debugfs_dentry,
624                                          stat_data,
625                                          stat_fops_per_vm[p->kind]))
626                         return -ENOMEM;
627         }
628         return 0;
629 }
630
631 /*
632  * Called after the VM is otherwise initialized, but just before adding it to
633  * the vm_list.
634  */
635 int __weak kvm_arch_post_init_vm(struct kvm *kvm)
636 {
637         return 0;
638 }
639
640 /*
641  * Called just after removing the VM from the vm_list, but before doing any
642  * other destruction.
643  */
644 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
645 {
646 }
647
648 static struct kvm *kvm_create_vm(unsigned long type)
649 {
650         int r, i;
651         struct kvm *kvm = kvm_arch_alloc_vm();
652
653         if (!kvm)
654                 return ERR_PTR(-ENOMEM);
655
656         spin_lock_init(&kvm->mmu_lock);
657         mmgrab(current->mm);
658         kvm->mm = current->mm;
659         kvm_eventfd_init(kvm);
660         mutex_init(&kvm->lock);
661         mutex_init(&kvm->irq_lock);
662         mutex_init(&kvm->slots_lock);
663         refcount_set(&kvm->users_count, 1);
664         INIT_LIST_HEAD(&kvm->devices);
665
666         r = kvm_arch_init_vm(kvm, type);
667         if (r)
668                 goto out_err_no_disable;
669
670         r = hardware_enable_all();
671         if (r)
672                 goto out_err_no_disable;
673
674 #ifdef CONFIG_HAVE_KVM_IRQFD
675         INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
676 #endif
677
678         BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
679
680         r = -ENOMEM;
681         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
682                 struct kvm_memslots *slots = kvm_alloc_memslots();
683                 if (!slots)
684                         goto out_err_no_srcu;
685                 /*
686                  * Generations must be different for each address space.
687                  * Init kvm generation close to the maximum to easily test the
688                  * code of handling generation number wrap-around.
689                  */
690                 slots->generation = i * 2 - 150;
691                 rcu_assign_pointer(kvm->memslots[i], slots);
692         }
693
694         if (init_srcu_struct(&kvm->srcu))
695                 goto out_err_no_srcu;
696         if (init_srcu_struct(&kvm->irq_srcu))
697                 goto out_err_no_irq_srcu;
698         for (i = 0; i < KVM_NR_BUSES; i++) {
699                 rcu_assign_pointer(kvm->buses[i],
700                         kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL));
701                 if (!kvm->buses[i])
702                         goto out_err_no_mmu_notifier;
703         }
704
705         r = kvm_init_mmu_notifier(kvm);
706         if (r)
707                 goto out_err_no_mmu_notifier;
708
709         r = kvm_arch_post_init_vm(kvm);
710         if (r)
711                 goto out_err;
712
713         mutex_lock(&kvm_lock);
714         list_add(&kvm->vm_list, &vm_list);
715         mutex_unlock(&kvm_lock);
716
717         preempt_notifier_inc();
718
719         return kvm;
720
721 out_err:
722 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
723         if (kvm->mmu_notifier.ops)
724                 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
725 #endif
726 out_err_no_mmu_notifier:
727         cleanup_srcu_struct(&kvm->irq_srcu);
728 out_err_no_irq_srcu:
729         cleanup_srcu_struct(&kvm->srcu);
730 out_err_no_srcu:
731         hardware_disable_all();
732 out_err_no_disable:
733         refcount_set(&kvm->users_count, 0);
734         for (i = 0; i < KVM_NR_BUSES; i++)
735                 kfree(kvm_get_bus(kvm, i));
736         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
737                 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
738         kvm_arch_free_vm(kvm);
739         mmdrop(current->mm);
740         return ERR_PTR(r);
741 }
742
743 static void kvm_destroy_devices(struct kvm *kvm)
744 {
745         struct kvm_device *dev, *tmp;
746
747         /*
748          * We do not need to take the kvm->lock here, because nobody else
749          * has a reference to the struct kvm at this point and therefore
750          * cannot access the devices list anyhow.
751          */
752         list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
753                 list_del(&dev->vm_node);
754                 dev->ops->destroy(dev);
755         }
756 }
757
758 static void kvm_destroy_vm(struct kvm *kvm)
759 {
760         int i;
761         struct mm_struct *mm = kvm->mm;
762
763         kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
764         kvm_destroy_vm_debugfs(kvm);
765         kvm_arch_sync_events(kvm);
766         mutex_lock(&kvm_lock);
767         list_del(&kvm->vm_list);
768         mutex_unlock(&kvm_lock);
769         kvm_arch_pre_destroy_vm(kvm);
770
771         kvm_free_irq_routing(kvm);
772         for (i = 0; i < KVM_NR_BUSES; i++) {
773                 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
774
775                 if (bus)
776                         kvm_io_bus_destroy(bus);
777                 kvm->buses[i] = NULL;
778         }
779         kvm_coalesced_mmio_free(kvm);
780 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
781         mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
782 #else
783         kvm_arch_flush_shadow_all(kvm);
784 #endif
785         kvm_arch_destroy_vm(kvm);
786         kvm_destroy_devices(kvm);
787         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
788                 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
789         cleanup_srcu_struct(&kvm->irq_srcu);
790         cleanup_srcu_struct(&kvm->srcu);
791         kvm_arch_free_vm(kvm);
792         preempt_notifier_dec();
793         hardware_disable_all();
794         mmdrop(mm);
795 }
796
797 void kvm_get_kvm(struct kvm *kvm)
798 {
799         refcount_inc(&kvm->users_count);
800 }
801 EXPORT_SYMBOL_GPL(kvm_get_kvm);
802
803 void kvm_put_kvm(struct kvm *kvm)
804 {
805         if (refcount_dec_and_test(&kvm->users_count))
806                 kvm_destroy_vm(kvm);
807 }
808 EXPORT_SYMBOL_GPL(kvm_put_kvm);
809
810
811 static int kvm_vm_release(struct inode *inode, struct file *filp)
812 {
813         struct kvm *kvm = filp->private_data;
814
815         kvm_irqfd_release(kvm);
816
817         kvm_put_kvm(kvm);
818         return 0;
819 }
820
821 /*
822  * Allocation size is twice as large as the actual dirty bitmap size.
823  * See x86's kvm_vm_ioctl_get_dirty_log() why this is needed.
824  */
825 static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
826 {
827         unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
828
829         memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL);
830         if (!memslot->dirty_bitmap)
831                 return -ENOMEM;
832
833         return 0;
834 }
835
836 /*
837  * Insert memslot and re-sort memslots based on their GFN,
838  * so binary search could be used to lookup GFN.
839  * Sorting algorithm takes advantage of having initially
840  * sorted array and known changed memslot position.
841  */
842 static void update_memslots(struct kvm_memslots *slots,
843                             struct kvm_memory_slot *new)
844 {
845         int id = new->id;
846         int i = slots->id_to_index[id];
847         struct kvm_memory_slot *mslots = slots->memslots;
848
849         WARN_ON(mslots[i].id != id);
850         if (!new->npages) {
851                 WARN_ON(!mslots[i].npages);
852                 if (mslots[i].npages)
853                         slots->used_slots--;
854         } else {
855                 if (!mslots[i].npages)
856                         slots->used_slots++;
857         }
858
859         while (i < KVM_MEM_SLOTS_NUM - 1 &&
860                new->base_gfn <= mslots[i + 1].base_gfn) {
861                 if (!mslots[i + 1].npages)
862                         break;
863                 mslots[i] = mslots[i + 1];
864                 slots->id_to_index[mslots[i].id] = i;
865                 i++;
866         }
867
868         /*
869          * The ">=" is needed when creating a slot with base_gfn == 0,
870          * so that it moves before all those with base_gfn == npages == 0.
871          *
872          * On the other hand, if new->npages is zero, the above loop has
873          * already left i pointing to the beginning of the empty part of
874          * mslots, and the ">=" would move the hole backwards in this
875          * case---which is wrong.  So skip the loop when deleting a slot.
876          */
877         if (new->npages) {
878                 while (i > 0 &&
879                        new->base_gfn >= mslots[i - 1].base_gfn) {
880                         mslots[i] = mslots[i - 1];
881                         slots->id_to_index[mslots[i].id] = i;
882                         i--;
883                 }
884         } else
885                 WARN_ON_ONCE(i != slots->used_slots);
886
887         mslots[i] = *new;
888         slots->id_to_index[mslots[i].id] = i;
889 }
890
891 static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
892 {
893         u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
894
895 #ifdef __KVM_HAVE_READONLY_MEM
896         valid_flags |= KVM_MEM_READONLY;
897 #endif
898
899         if (mem->flags & ~valid_flags)
900                 return -EINVAL;
901
902         return 0;
903 }
904
905 static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
906                 int as_id, struct kvm_memslots *slots)
907 {
908         struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
909         u64 gen;
910
911         /*
912          * Set the low bit in the generation, which disables SPTE caching
913          * until the end of synchronize_srcu_expedited.
914          */
915         WARN_ON(old_memslots->generation & 1);
916         slots->generation = old_memslots->generation + 1;
917
918         rcu_assign_pointer(kvm->memslots[as_id], slots);
919         synchronize_srcu_expedited(&kvm->srcu);
920
921         /*
922          * Increment the new memslot generation a second time. This prevents
923          * vm exits that race with memslot updates from caching a memslot
924          * generation that will (potentially) be valid forever.
925          *
926          * Generations must be unique even across address spaces.  We do not need
927          * a global counter for that, instead the generation space is evenly split
928          * across address spaces.  For example, with two address spaces, address
929          * space 0 will use generations 0, 4, 8, ... while * address space 1 will
930          * use generations 2, 6, 10, 14, ...
931          */
932         gen = slots->generation + KVM_ADDRESS_SPACE_NUM * 2 - 1;
933
934         kvm_arch_memslots_updated(kvm, gen);
935
936         slots->generation = gen;
937
938         return old_memslots;
939 }
940
941 /*
942  * Allocate some memory and give it an address in the guest physical address
943  * space.
944  *
945  * Discontiguous memory is allowed, mostly for framebuffers.
946  *
947  * Must be called holding kvm->slots_lock for write.
948  */
949 int __kvm_set_memory_region(struct kvm *kvm,
950                             const struct kvm_userspace_memory_region *mem)
951 {
952         int r;
953         gfn_t base_gfn;
954         unsigned long npages;
955         struct kvm_memory_slot *slot;
956         struct kvm_memory_slot old, new;
957         struct kvm_memslots *slots = NULL, *old_memslots;
958         int as_id, id;
959         enum kvm_mr_change change;
960
961         r = check_memory_region_flags(mem);
962         if (r)
963                 goto out;
964
965         r = -EINVAL;
966         as_id = mem->slot >> 16;
967         id = (u16)mem->slot;
968
969         /* General sanity checks */
970         if (mem->memory_size & (PAGE_SIZE - 1))
971                 goto out;
972         if (mem->guest_phys_addr & (PAGE_SIZE - 1))
973                 goto out;
974         /* We can read the guest memory with __xxx_user() later on. */
975         if ((id < KVM_USER_MEM_SLOTS) &&
976             ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
977              !access_ok(VERIFY_WRITE,
978                         (void __user *)(unsigned long)mem->userspace_addr,
979                         mem->memory_size)))
980                 goto out;
981         if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
982                 goto out;
983         if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
984                 goto out;
985
986         slot = id_to_memslot(__kvm_memslots(kvm, as_id), id);
987         base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
988         npages = mem->memory_size >> PAGE_SHIFT;
989
990         if (npages > KVM_MEM_MAX_NR_PAGES)
991                 goto out;
992
993         new = old = *slot;
994
995         new.id = id;
996         new.base_gfn = base_gfn;
997         new.npages = npages;
998         new.flags = mem->flags;
999
1000         if (npages) {
1001                 if (!old.npages)
1002                         change = KVM_MR_CREATE;
1003                 else { /* Modify an existing slot. */
1004                         if ((mem->userspace_addr != old.userspace_addr) ||
1005                             (npages != old.npages) ||
1006                             ((new.flags ^ old.flags) & KVM_MEM_READONLY))
1007                                 goto out;
1008
1009                         if (base_gfn != old.base_gfn)
1010                                 change = KVM_MR_MOVE;
1011                         else if (new.flags != old.flags)
1012                                 change = KVM_MR_FLAGS_ONLY;
1013                         else { /* Nothing to change. */
1014                                 r = 0;
1015                                 goto out;
1016                         }
1017                 }
1018         } else {
1019                 if (!old.npages)
1020                         goto out;
1021
1022                 change = KVM_MR_DELETE;
1023                 new.base_gfn = 0;
1024                 new.flags = 0;
1025         }
1026
1027         if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1028                 /* Check for overlaps */
1029                 r = -EEXIST;
1030                 kvm_for_each_memslot(slot, __kvm_memslots(kvm, as_id)) {
1031                         if (slot->id == id)
1032                                 continue;
1033                         if (!((base_gfn + npages <= slot->base_gfn) ||
1034                               (base_gfn >= slot->base_gfn + slot->npages)))
1035                                 goto out;
1036                 }
1037         }
1038
1039         /* Free page dirty bitmap if unneeded */
1040         if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
1041                 new.dirty_bitmap = NULL;
1042
1043         r = -ENOMEM;
1044         if (change == KVM_MR_CREATE) {
1045                 new.userspace_addr = mem->userspace_addr;
1046
1047                 if (kvm_arch_create_memslot(kvm, &new, npages))
1048                         goto out_free;
1049         }
1050
1051         /* Allocate page dirty bitmap if needed */
1052         if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
1053                 if (kvm_create_dirty_bitmap(&new) < 0)
1054                         goto out_free;
1055         }
1056
1057         slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
1058         if (!slots)
1059                 goto out_free;
1060         memcpy(slots, __kvm_memslots(kvm, as_id), sizeof(struct kvm_memslots));
1061
1062         if ((change == KVM_MR_DELETE) || (change == KVM_MR_MOVE)) {
1063                 slot = id_to_memslot(slots, id);
1064                 slot->flags |= KVM_MEMSLOT_INVALID;
1065
1066                 old_memslots = install_new_memslots(kvm, as_id, slots);
1067
1068                 /* From this point no new shadow pages pointing to a deleted,
1069                  * or moved, memslot will be created.
1070                  *
1071                  * validation of sp->gfn happens in:
1072                  *      - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1073                  *      - kvm_is_visible_gfn (mmu_check_roots)
1074                  */
1075                 kvm_arch_flush_shadow_memslot(kvm, slot);
1076
1077                 /*
1078                  * We can re-use the old_memslots from above, the only difference
1079                  * from the currently installed memslots is the invalid flag.  This
1080                  * will get overwritten by update_memslots anyway.
1081                  */
1082                 slots = old_memslots;
1083         }
1084
1085         r = kvm_arch_prepare_memory_region(kvm, &new, mem, change);
1086         if (r)
1087                 goto out_slots;
1088
1089         /* actual memory is freed via old in kvm_free_memslot below */
1090         if (change == KVM_MR_DELETE) {
1091                 new.dirty_bitmap = NULL;
1092                 memset(&new.arch, 0, sizeof(new.arch));
1093         }
1094
1095         update_memslots(slots, &new);
1096         old_memslots = install_new_memslots(kvm, as_id, slots);
1097
1098         kvm_arch_commit_memory_region(kvm, mem, &old, &new, change);
1099
1100         kvm_free_memslot(kvm, &old, &new);
1101         kvfree(old_memslots);
1102         return 0;
1103
1104 out_slots:
1105         kvfree(slots);
1106 out_free:
1107         kvm_free_memslot(kvm, &new, &old);
1108 out:
1109         return r;
1110 }
1111 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1112
1113 int kvm_set_memory_region(struct kvm *kvm,
1114                           const struct kvm_userspace_memory_region *mem)
1115 {
1116         int r;
1117
1118         mutex_lock(&kvm->slots_lock);
1119         r = __kvm_set_memory_region(kvm, mem);
1120         mutex_unlock(&kvm->slots_lock);
1121         return r;
1122 }
1123 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1124
1125 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1126                                           struct kvm_userspace_memory_region *mem)
1127 {
1128         if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1129                 return -EINVAL;
1130
1131         return kvm_set_memory_region(kvm, mem);
1132 }
1133
1134 int kvm_get_dirty_log(struct kvm *kvm,
1135                         struct kvm_dirty_log *log, int *is_dirty)
1136 {
1137         struct kvm_memslots *slots;
1138         struct kvm_memory_slot *memslot;
1139         int i, as_id, id;
1140         unsigned long n;
1141         unsigned long any = 0;
1142
1143         as_id = log->slot >> 16;
1144         id = (u16)log->slot;
1145         if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1146                 return -EINVAL;
1147
1148         slots = __kvm_memslots(kvm, as_id);
1149         memslot = id_to_memslot(slots, id);
1150         if (!memslot->dirty_bitmap)
1151                 return -ENOENT;
1152
1153         n = kvm_dirty_bitmap_bytes(memslot);
1154
1155         for (i = 0; !any && i < n/sizeof(long); ++i)
1156                 any = memslot->dirty_bitmap[i];
1157
1158         if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
1159                 return -EFAULT;
1160
1161         if (any)
1162                 *is_dirty = 1;
1163         return 0;
1164 }
1165 EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1166
1167 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1168 /**
1169  * kvm_get_dirty_log_protect - get a snapshot of dirty pages, and if any pages
1170  *      are dirty write protect them for next write.
1171  * @kvm:        pointer to kvm instance
1172  * @log:        slot id and address to which we copy the log
1173  * @is_dirty:   flag set if any page is dirty
1174  *
1175  * We need to keep it in mind that VCPU threads can write to the bitmap
1176  * concurrently. So, to avoid losing track of dirty pages we keep the
1177  * following order:
1178  *
1179  *    1. Take a snapshot of the bit and clear it if needed.
1180  *    2. Write protect the corresponding page.
1181  *    3. Copy the snapshot to the userspace.
1182  *    4. Upon return caller flushes TLB's if needed.
1183  *
1184  * Between 2 and 4, the guest may write to the page using the remaining TLB
1185  * entry.  This is not a problem because the page is reported dirty using
1186  * the snapshot taken before and step 4 ensures that writes done after
1187  * exiting to userspace will be logged for the next call.
1188  *
1189  */
1190 int kvm_get_dirty_log_protect(struct kvm *kvm,
1191                         struct kvm_dirty_log *log, bool *is_dirty)
1192 {
1193         struct kvm_memslots *slots;
1194         struct kvm_memory_slot *memslot;
1195         int i, as_id, id;
1196         unsigned long n;
1197         unsigned long *dirty_bitmap;
1198         unsigned long *dirty_bitmap_buffer;
1199
1200         as_id = log->slot >> 16;
1201         id = (u16)log->slot;
1202         if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1203                 return -EINVAL;
1204
1205         slots = __kvm_memslots(kvm, as_id);
1206         memslot = id_to_memslot(slots, id);
1207
1208         dirty_bitmap = memslot->dirty_bitmap;
1209         if (!dirty_bitmap)
1210                 return -ENOENT;
1211
1212         n = kvm_dirty_bitmap_bytes(memslot);
1213
1214         dirty_bitmap_buffer = dirty_bitmap + n / sizeof(long);
1215         memset(dirty_bitmap_buffer, 0, n);
1216
1217         spin_lock(&kvm->mmu_lock);
1218         *is_dirty = false;
1219         for (i = 0; i < n / sizeof(long); i++) {
1220                 unsigned long mask;
1221                 gfn_t offset;
1222
1223                 if (!dirty_bitmap[i])
1224                         continue;
1225
1226                 *is_dirty = true;
1227
1228                 mask = xchg(&dirty_bitmap[i], 0);
1229                 dirty_bitmap_buffer[i] = mask;
1230
1231                 if (mask) {
1232                         offset = i * BITS_PER_LONG;
1233                         kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1234                                                                 offset, mask);
1235                 }
1236         }
1237
1238         spin_unlock(&kvm->mmu_lock);
1239         if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1240                 return -EFAULT;
1241         return 0;
1242 }
1243 EXPORT_SYMBOL_GPL(kvm_get_dirty_log_protect);
1244 #endif
1245
1246 bool kvm_largepages_enabled(void)
1247 {
1248         return largepages_enabled;
1249 }
1250
1251 void kvm_disable_largepages(void)
1252 {
1253         largepages_enabled = false;
1254 }
1255 EXPORT_SYMBOL_GPL(kvm_disable_largepages);
1256
1257 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1258 {
1259         return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1260 }
1261 EXPORT_SYMBOL_GPL(gfn_to_memslot);
1262
1263 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1264 {
1265         return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1266 }
1267
1268 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1269 {
1270         struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
1271
1272         if (!memslot || memslot->id >= KVM_USER_MEM_SLOTS ||
1273               memslot->flags & KVM_MEMSLOT_INVALID)
1274                 return false;
1275
1276         return true;
1277 }
1278 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1279
1280 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
1281 {
1282         struct vm_area_struct *vma;
1283         unsigned long addr, size;
1284
1285         size = PAGE_SIZE;
1286
1287         addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
1288         if (kvm_is_error_hva(addr))
1289                 return PAGE_SIZE;
1290
1291         down_read(&current->mm->mmap_sem);
1292         vma = find_vma(current->mm, addr);
1293         if (!vma)
1294                 goto out;
1295
1296         size = vma_kernel_pagesize(vma);
1297
1298 out:
1299         up_read(&current->mm->mmap_sem);
1300
1301         return size;
1302 }
1303
1304 static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1305 {
1306         return slot->flags & KVM_MEM_READONLY;
1307 }
1308
1309 static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1310                                        gfn_t *nr_pages, bool write)
1311 {
1312         if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1313                 return KVM_HVA_ERR_BAD;
1314
1315         if (memslot_is_readonly(slot) && write)
1316                 return KVM_HVA_ERR_RO_BAD;
1317
1318         if (nr_pages)
1319                 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1320
1321         return __gfn_to_hva_memslot(slot, gfn);
1322 }
1323
1324 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1325                                      gfn_t *nr_pages)
1326 {
1327         return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1328 }
1329
1330 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
1331                                         gfn_t gfn)
1332 {
1333         return gfn_to_hva_many(slot, gfn, NULL);
1334 }
1335 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1336
1337 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1338 {
1339         return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1340 }
1341 EXPORT_SYMBOL_GPL(gfn_to_hva);
1342
1343 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1344 {
1345         return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1346 }
1347 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1348
1349 /*
1350  * If writable is set to false, the hva returned by this function is only
1351  * allowed to be read.
1352  */
1353 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1354                                       gfn_t gfn, bool *writable)
1355 {
1356         unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1357
1358         if (!kvm_is_error_hva(hva) && writable)
1359                 *writable = !memslot_is_readonly(slot);
1360
1361         return hva;
1362 }
1363
1364 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1365 {
1366         struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1367
1368         return gfn_to_hva_memslot_prot(slot, gfn, writable);
1369 }
1370
1371 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1372 {
1373         struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1374
1375         return gfn_to_hva_memslot_prot(slot, gfn, writable);
1376 }
1377
1378 static int get_user_page_nowait(unsigned long start, int write,
1379                 struct page **page)
1380 {
1381         int flags = FOLL_NOWAIT | FOLL_HWPOISON;
1382
1383         if (write)
1384                 flags |= FOLL_WRITE;
1385
1386         return get_user_pages(start, 1, flags, page, NULL);
1387 }
1388
1389 static inline int check_user_page_hwpoison(unsigned long addr)
1390 {
1391         int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
1392
1393         rc = get_user_pages(addr, 1, flags, NULL, NULL);
1394         return rc == -EHWPOISON;
1395 }
1396
1397 /*
1398  * The atomic path to get the writable pfn which will be stored in @pfn,
1399  * true indicates success, otherwise false is returned.
1400  */
1401 static bool hva_to_pfn_fast(unsigned long addr, bool atomic, bool *async,
1402                             bool write_fault, bool *writable, kvm_pfn_t *pfn)
1403 {
1404         struct page *page[1];
1405         int npages;
1406
1407         if (!(async || atomic))
1408                 return false;
1409
1410         /*
1411          * Fast pin a writable pfn only if it is a write fault request
1412          * or the caller allows to map a writable pfn for a read fault
1413          * request.
1414          */
1415         if (!(write_fault || writable))
1416                 return false;
1417
1418         npages = __get_user_pages_fast(addr, 1, 1, page);
1419         if (npages == 1) {
1420                 *pfn = page_to_pfn(page[0]);
1421
1422                 if (writable)
1423                         *writable = true;
1424                 return true;
1425         }
1426
1427         return false;
1428 }
1429
1430 /*
1431  * The slow path to get the pfn of the specified host virtual address,
1432  * 1 indicates success, -errno is returned if error is detected.
1433  */
1434 static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
1435                            bool *writable, kvm_pfn_t *pfn)
1436 {
1437         struct page *page[1];
1438         int npages = 0;
1439
1440         might_sleep();
1441
1442         if (writable)
1443                 *writable = write_fault;
1444
1445         if (async) {
1446                 down_read(&current->mm->mmap_sem);
1447                 npages = get_user_page_nowait(addr, write_fault, page);
1448                 up_read(&current->mm->mmap_sem);
1449         } else {
1450                 unsigned int flags = FOLL_HWPOISON;
1451
1452                 if (write_fault)
1453                         flags |= FOLL_WRITE;
1454
1455                 npages = get_user_pages_unlocked(addr, 1, page, flags);
1456         }
1457         if (npages != 1)
1458                 return npages;
1459
1460         /* map read fault as writable if possible */
1461         if (unlikely(!write_fault) && writable) {
1462                 struct page *wpage[1];
1463
1464                 npages = __get_user_pages_fast(addr, 1, 1, wpage);
1465                 if (npages == 1) {
1466                         *writable = true;
1467                         put_page(page[0]);
1468                         page[0] = wpage[0];
1469                 }
1470
1471                 npages = 1;
1472         }
1473         *pfn = page_to_pfn(page[0]);
1474         return npages;
1475 }
1476
1477 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1478 {
1479         if (unlikely(!(vma->vm_flags & VM_READ)))
1480                 return false;
1481
1482         if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1483                 return false;
1484
1485         return true;
1486 }
1487
1488 static int kvm_try_get_pfn(kvm_pfn_t pfn)
1489 {
1490         if (kvm_is_reserved_pfn(pfn))
1491                 return 1;
1492         return get_page_unless_zero(pfn_to_page(pfn));
1493 }
1494
1495 static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1496                                unsigned long addr, bool *async,
1497                                bool write_fault, bool *writable,
1498                                kvm_pfn_t *p_pfn)
1499 {
1500         kvm_pfn_t pfn;
1501         pte_t *ptep;
1502         spinlock_t *ptl;
1503         int r;
1504
1505         r = follow_pte_pmd(vma->vm_mm, addr, NULL, NULL, &ptep, NULL, &ptl);
1506         if (r) {
1507                 /*
1508                  * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1509                  * not call the fault handler, so do it here.
1510                  */
1511                 bool unlocked = false;
1512                 r = fixup_user_fault(current, current->mm, addr,
1513                                      (write_fault ? FAULT_FLAG_WRITE : 0),
1514                                      &unlocked);
1515                 if (unlocked)
1516                         return -EAGAIN;
1517                 if (r)
1518                         return r;
1519
1520                 r = follow_pte_pmd(vma->vm_mm, addr, NULL, NULL, &ptep, NULL, &ptl);
1521                 if (r)
1522                         return r;
1523         }
1524
1525         if (write_fault && !pte_write(*ptep)) {
1526                 pfn = KVM_PFN_ERR_RO_FAULT;
1527                 goto out;
1528         }
1529
1530         if (writable)
1531                 *writable = pte_write(*ptep);
1532         pfn = pte_pfn(*ptep);
1533
1534         /*
1535          * Get a reference here because callers of *hva_to_pfn* and
1536          * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1537          * returned pfn.  This is only needed if the VMA has VM_MIXEDMAP
1538          * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1539          * simply do nothing for reserved pfns.
1540          *
1541          * Whoever called remap_pfn_range is also going to call e.g.
1542          * unmap_mapping_range before the underlying pages are freed,
1543          * causing a call to our MMU notifier.
1544          *
1545          * Certain IO or PFNMAP mappings can be backed with valid
1546          * struct pages, but be allocated without refcounting e.g.,
1547          * tail pages of non-compound higher order allocations, which
1548          * would then underflow the refcount when the caller does the
1549          * required put_page. Don't allow those pages here.
1550          */ 
1551         if (!kvm_try_get_pfn(pfn))
1552                 r = -EFAULT;
1553
1554 out:
1555         pte_unmap_unlock(ptep, ptl);
1556         *p_pfn = pfn;
1557
1558         return r;
1559 }
1560
1561 /*
1562  * Pin guest page in memory and return its pfn.
1563  * @addr: host virtual address which maps memory to the guest
1564  * @atomic: whether this function can sleep
1565  * @async: whether this function need to wait IO complete if the
1566  *         host page is not in the memory
1567  * @write_fault: whether we should get a writable host page
1568  * @writable: whether it allows to map a writable host page for !@write_fault
1569  *
1570  * The function will map a writable host page for these two cases:
1571  * 1): @write_fault = true
1572  * 2): @write_fault = false && @writable, @writable will tell the caller
1573  *     whether the mapping is writable.
1574  */
1575 static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
1576                         bool write_fault, bool *writable)
1577 {
1578         struct vm_area_struct *vma;
1579         kvm_pfn_t pfn = 0;
1580         int npages, r;
1581
1582         /* we can do it either atomically or asynchronously, not both */
1583         BUG_ON(atomic && async);
1584
1585         if (hva_to_pfn_fast(addr, atomic, async, write_fault, writable, &pfn))
1586                 return pfn;
1587
1588         if (atomic)
1589                 return KVM_PFN_ERR_FAULT;
1590
1591         npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
1592         if (npages == 1)
1593                 return pfn;
1594
1595         down_read(&current->mm->mmap_sem);
1596         if (npages == -EHWPOISON ||
1597               (!async && check_user_page_hwpoison(addr))) {
1598                 pfn = KVM_PFN_ERR_HWPOISON;
1599                 goto exit;
1600         }
1601
1602 retry:
1603         vma = find_vma_intersection(current->mm, addr, addr + 1);
1604
1605         if (vma == NULL)
1606                 pfn = KVM_PFN_ERR_FAULT;
1607         else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
1608                 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
1609                 if (r == -EAGAIN)
1610                         goto retry;
1611                 if (r < 0)
1612                         pfn = KVM_PFN_ERR_FAULT;
1613         } else {
1614                 if (async && vma_is_valid(vma, write_fault))
1615                         *async = true;
1616                 pfn = KVM_PFN_ERR_FAULT;
1617         }
1618 exit:
1619         up_read(&current->mm->mmap_sem);
1620         return pfn;
1621 }
1622
1623 kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
1624                                bool atomic, bool *async, bool write_fault,
1625                                bool *writable)
1626 {
1627         unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
1628
1629         if (addr == KVM_HVA_ERR_RO_BAD) {
1630                 if (writable)
1631                         *writable = false;
1632                 return KVM_PFN_ERR_RO_FAULT;
1633         }
1634
1635         if (kvm_is_error_hva(addr)) {
1636                 if (writable)
1637                         *writable = false;
1638                 return KVM_PFN_NOSLOT;
1639         }
1640
1641         /* Do not map writable pfn in the readonly memslot. */
1642         if (writable && memslot_is_readonly(slot)) {
1643                 *writable = false;
1644                 writable = NULL;
1645         }
1646
1647         return hva_to_pfn(addr, atomic, async, write_fault,
1648                           writable);
1649 }
1650 EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
1651
1652 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
1653                       bool *writable)
1654 {
1655         return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
1656                                     write_fault, writable);
1657 }
1658 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1659
1660 kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
1661 {
1662         return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
1663 }
1664 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
1665
1666 kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
1667 {
1668         return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
1669 }
1670 EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
1671
1672 kvm_pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
1673 {
1674         return gfn_to_pfn_memslot_atomic(gfn_to_memslot(kvm, gfn), gfn);
1675 }
1676 EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
1677
1678 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
1679 {
1680         return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1681 }
1682 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
1683
1684 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1685 {
1686         return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
1687 }
1688 EXPORT_SYMBOL_GPL(gfn_to_pfn);
1689
1690 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1691 {
1692         return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1693 }
1694 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
1695
1696 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1697                             struct page **pages, int nr_pages)
1698 {
1699         unsigned long addr;
1700         gfn_t entry = 0;
1701
1702         addr = gfn_to_hva_many(slot, gfn, &entry);
1703         if (kvm_is_error_hva(addr))
1704                 return -1;
1705
1706         if (entry < nr_pages)
1707                 return 0;
1708
1709         return __get_user_pages_fast(addr, nr_pages, 1, pages);
1710 }
1711 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
1712
1713 static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
1714 {
1715         if (is_error_noslot_pfn(pfn))
1716                 return KVM_ERR_PTR_BAD_PAGE;
1717
1718         if (kvm_is_reserved_pfn(pfn)) {
1719                 WARN_ON(1);
1720                 return KVM_ERR_PTR_BAD_PAGE;
1721         }
1722
1723         return pfn_to_page(pfn);
1724 }
1725
1726 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1727 {
1728         kvm_pfn_t pfn;
1729
1730         pfn = gfn_to_pfn(kvm, gfn);
1731
1732         return kvm_pfn_to_page(pfn);
1733 }
1734 EXPORT_SYMBOL_GPL(gfn_to_page);
1735
1736 struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
1737 {
1738         kvm_pfn_t pfn;
1739
1740         pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
1741
1742         return kvm_pfn_to_page(pfn);
1743 }
1744 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
1745
1746 void kvm_release_page_clean(struct page *page)
1747 {
1748         WARN_ON(is_error_page(page));
1749
1750         kvm_release_pfn_clean(page_to_pfn(page));
1751 }
1752 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
1753
1754 void kvm_release_pfn_clean(kvm_pfn_t pfn)
1755 {
1756         if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
1757                 put_page(pfn_to_page(pfn));
1758 }
1759 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
1760
1761 void kvm_release_page_dirty(struct page *page)
1762 {
1763         WARN_ON(is_error_page(page));
1764
1765         kvm_release_pfn_dirty(page_to_pfn(page));
1766 }
1767 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
1768
1769 static void kvm_release_pfn_dirty(kvm_pfn_t pfn)
1770 {
1771         kvm_set_pfn_dirty(pfn);
1772         kvm_release_pfn_clean(pfn);
1773 }
1774
1775 void kvm_set_pfn_dirty(kvm_pfn_t pfn)
1776 {
1777         if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn)) {
1778                 struct page *page = pfn_to_page(pfn);
1779
1780                 if (!PageReserved(page))
1781                         SetPageDirty(page);
1782         }
1783 }
1784 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
1785
1786 void kvm_set_pfn_accessed(kvm_pfn_t pfn)
1787 {
1788         if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
1789                 mark_page_accessed(pfn_to_page(pfn));
1790 }
1791 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
1792
1793 void kvm_get_pfn(kvm_pfn_t pfn)
1794 {
1795         if (!kvm_is_reserved_pfn(pfn))
1796                 get_page(pfn_to_page(pfn));
1797 }
1798 EXPORT_SYMBOL_GPL(kvm_get_pfn);
1799
1800 static int next_segment(unsigned long len, int offset)
1801 {
1802         if (len > PAGE_SIZE - offset)
1803                 return PAGE_SIZE - offset;
1804         else
1805                 return len;
1806 }
1807
1808 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
1809                                  void *data, int offset, int len)
1810 {
1811         int r;
1812         unsigned long addr;
1813
1814         addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
1815         if (kvm_is_error_hva(addr))
1816                 return -EFAULT;
1817         r = __copy_from_user(data, (void __user *)addr + offset, len);
1818         if (r)
1819                 return -EFAULT;
1820         return 0;
1821 }
1822
1823 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1824                         int len)
1825 {
1826         struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1827
1828         return __kvm_read_guest_page(slot, gfn, data, offset, len);
1829 }
1830 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
1831
1832 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
1833                              int offset, int len)
1834 {
1835         struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1836
1837         return __kvm_read_guest_page(slot, gfn, data, offset, len);
1838 }
1839 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
1840
1841 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
1842 {
1843         gfn_t gfn = gpa >> PAGE_SHIFT;
1844         int seg;
1845         int offset = offset_in_page(gpa);
1846         int ret;
1847
1848         while ((seg = next_segment(len, offset)) != 0) {
1849                 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
1850                 if (ret < 0)
1851                         return ret;
1852                 offset = 0;
1853                 len -= seg;
1854                 data += seg;
1855                 ++gfn;
1856         }
1857         return 0;
1858 }
1859 EXPORT_SYMBOL_GPL(kvm_read_guest);
1860
1861 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
1862 {
1863         gfn_t gfn = gpa >> PAGE_SHIFT;
1864         int seg;
1865         int offset = offset_in_page(gpa);
1866         int ret;
1867
1868         while ((seg = next_segment(len, offset)) != 0) {
1869                 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
1870                 if (ret < 0)
1871                         return ret;
1872                 offset = 0;
1873                 len -= seg;
1874                 data += seg;
1875                 ++gfn;
1876         }
1877         return 0;
1878 }
1879 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
1880
1881 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1882                                    void *data, int offset, unsigned long len)
1883 {
1884         int r;
1885         unsigned long addr;
1886
1887         addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
1888         if (kvm_is_error_hva(addr))
1889                 return -EFAULT;
1890         pagefault_disable();
1891         r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
1892         pagefault_enable();
1893         if (r)
1894                 return -EFAULT;
1895         return 0;
1896 }
1897
1898 int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
1899                           unsigned long len)
1900 {
1901         gfn_t gfn = gpa >> PAGE_SHIFT;
1902         struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1903         int offset = offset_in_page(gpa);
1904
1905         return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
1906 }
1907 EXPORT_SYMBOL_GPL(kvm_read_guest_atomic);
1908
1909 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
1910                                void *data, unsigned long len)
1911 {
1912         gfn_t gfn = gpa >> PAGE_SHIFT;
1913         struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1914         int offset = offset_in_page(gpa);
1915
1916         return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
1917 }
1918 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
1919
1920 static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
1921                                   const void *data, int offset, int len)
1922 {
1923         int r;
1924         unsigned long addr;
1925
1926         addr = gfn_to_hva_memslot(memslot, gfn);
1927         if (kvm_is_error_hva(addr))
1928                 return -EFAULT;
1929         r = __copy_to_user((void __user *)addr + offset, data, len);
1930         if (r)
1931                 return -EFAULT;
1932         mark_page_dirty_in_slot(memslot, gfn);
1933         return 0;
1934 }
1935
1936 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
1937                          const void *data, int offset, int len)
1938 {
1939         struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1940
1941         return __kvm_write_guest_page(slot, gfn, data, offset, len);
1942 }
1943 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
1944
1945 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
1946                               const void *data, int offset, int len)
1947 {
1948         struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1949
1950         return __kvm_write_guest_page(slot, gfn, data, offset, len);
1951 }
1952 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
1953
1954 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
1955                     unsigned long len)
1956 {
1957         gfn_t gfn = gpa >> PAGE_SHIFT;
1958         int seg;
1959         int offset = offset_in_page(gpa);
1960         int ret;
1961
1962         while ((seg = next_segment(len, offset)) != 0) {
1963                 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
1964                 if (ret < 0)
1965                         return ret;
1966                 offset = 0;
1967                 len -= seg;
1968                 data += seg;
1969                 ++gfn;
1970         }
1971         return 0;
1972 }
1973 EXPORT_SYMBOL_GPL(kvm_write_guest);
1974
1975 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
1976                          unsigned long len)
1977 {
1978         gfn_t gfn = gpa >> PAGE_SHIFT;
1979         int seg;
1980         int offset = offset_in_page(gpa);
1981         int ret;
1982
1983         while ((seg = next_segment(len, offset)) != 0) {
1984                 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
1985                 if (ret < 0)
1986                         return ret;
1987                 offset = 0;
1988                 len -= seg;
1989                 data += seg;
1990                 ++gfn;
1991         }
1992         return 0;
1993 }
1994 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
1995
1996 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
1997                                        struct gfn_to_hva_cache *ghc,
1998                                        gpa_t gpa, unsigned long len)
1999 {
2000         int offset = offset_in_page(gpa);
2001         gfn_t start_gfn = gpa >> PAGE_SHIFT;
2002         gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2003         gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2004         gfn_t nr_pages_avail;
2005
2006         ghc->gpa = gpa;
2007         ghc->generation = slots->generation;
2008         ghc->len = len;
2009         ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2010         ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn, NULL);
2011         if (!kvm_is_error_hva(ghc->hva) && nr_pages_needed <= 1) {
2012                 ghc->hva += offset;
2013         } else {
2014                 /*
2015                  * If the requested region crosses two memslots, we still
2016                  * verify that the entire region is valid here.
2017                  */
2018                 while (start_gfn <= end_gfn) {
2019                         nr_pages_avail = 0;
2020                         ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2021                         ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2022                                                    &nr_pages_avail);
2023                         if (kvm_is_error_hva(ghc->hva))
2024                                 return -EFAULT;
2025                         start_gfn += nr_pages_avail;
2026                 }
2027                 /* Use the slow path for cross page reads and writes. */
2028                 ghc->memslot = NULL;
2029         }
2030         return 0;
2031 }
2032
2033 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2034                               gpa_t gpa, unsigned long len)
2035 {
2036         struct kvm_memslots *slots = kvm_memslots(kvm);
2037         return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2038 }
2039 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
2040
2041 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2042                                   void *data, unsigned int offset,
2043                                   unsigned long len)
2044 {
2045         struct kvm_memslots *slots = kvm_memslots(kvm);
2046         int r;
2047         gpa_t gpa = ghc->gpa + offset;
2048
2049         BUG_ON(len + offset > ghc->len);
2050
2051         if (slots->generation != ghc->generation)
2052                 __kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len);
2053
2054         if (kvm_is_error_hva(ghc->hva))
2055                 return -EFAULT;
2056
2057         if (unlikely(!ghc->memslot))
2058                 return kvm_write_guest(kvm, gpa, data, len);
2059
2060         r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
2061         if (r)
2062                 return -EFAULT;
2063         mark_page_dirty_in_slot(ghc->memslot, gpa >> PAGE_SHIFT);
2064
2065         return 0;
2066 }
2067 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
2068
2069 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2070                            void *data, unsigned long len)
2071 {
2072         return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
2073 }
2074 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
2075
2076 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2077                            void *data, unsigned long len)
2078 {
2079         struct kvm_memslots *slots = kvm_memslots(kvm);
2080         int r;
2081
2082         BUG_ON(len > ghc->len);
2083
2084         if (slots->generation != ghc->generation)
2085                 __kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len);
2086
2087         if (kvm_is_error_hva(ghc->hva))
2088                 return -EFAULT;
2089
2090         if (unlikely(!ghc->memslot))
2091                 return kvm_read_guest(kvm, ghc->gpa, data, len);
2092
2093         r = __copy_from_user(data, (void __user *)ghc->hva, len);
2094         if (r)
2095                 return -EFAULT;
2096
2097         return 0;
2098 }
2099 EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
2100
2101 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
2102 {
2103         const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2104
2105         return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
2106 }
2107 EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
2108
2109 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2110 {
2111         gfn_t gfn = gpa >> PAGE_SHIFT;
2112         int seg;
2113         int offset = offset_in_page(gpa);
2114         int ret;
2115
2116         while ((seg = next_segment(len, offset)) != 0) {
2117                 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
2118                 if (ret < 0)
2119                         return ret;
2120                 offset = 0;
2121                 len -= seg;
2122                 ++gfn;
2123         }
2124         return 0;
2125 }
2126 EXPORT_SYMBOL_GPL(kvm_clear_guest);
2127
2128 static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot,
2129                                     gfn_t gfn)
2130 {
2131         if (memslot && memslot->dirty_bitmap) {
2132                 unsigned long rel_gfn = gfn - memslot->base_gfn;
2133
2134                 set_bit_le(rel_gfn, memslot->dirty_bitmap);
2135         }
2136 }
2137
2138 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2139 {
2140         struct kvm_memory_slot *memslot;
2141
2142         memslot = gfn_to_memslot(kvm, gfn);
2143         mark_page_dirty_in_slot(memslot, gfn);
2144 }
2145 EXPORT_SYMBOL_GPL(mark_page_dirty);
2146
2147 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2148 {
2149         struct kvm_memory_slot *memslot;
2150
2151         memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2152         mark_page_dirty_in_slot(memslot, gfn);
2153 }
2154 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2155
2156 void kvm_sigset_activate(struct kvm_vcpu *vcpu)
2157 {
2158         if (!vcpu->sigset_active)
2159                 return;
2160
2161         /*
2162          * This does a lockless modification of ->real_blocked, which is fine
2163          * because, only current can change ->real_blocked and all readers of
2164          * ->real_blocked don't care as long ->real_blocked is always a subset
2165          * of ->blocked.
2166          */
2167         sigprocmask(SIG_SETMASK, &vcpu->sigset, &current->real_blocked);
2168 }
2169
2170 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
2171 {
2172         if (!vcpu->sigset_active)
2173                 return;
2174
2175         sigprocmask(SIG_SETMASK, &current->real_blocked, NULL);
2176         sigemptyset(&current->real_blocked);
2177 }
2178
2179 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2180 {
2181         unsigned int old, val, grow;
2182
2183         old = val = vcpu->halt_poll_ns;
2184         grow = READ_ONCE(halt_poll_ns_grow);
2185         /* 10us base */
2186         if (val == 0 && grow)
2187                 val = 10000;
2188         else
2189                 val *= grow;
2190
2191         if (val > halt_poll_ns)
2192                 val = halt_poll_ns;
2193
2194         vcpu->halt_poll_ns = val;
2195         trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
2196 }
2197
2198 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2199 {
2200         unsigned int old, val, shrink;
2201
2202         old = val = vcpu->halt_poll_ns;
2203         shrink = READ_ONCE(halt_poll_ns_shrink);
2204         if (shrink == 0)
2205                 val = 0;
2206         else
2207                 val /= shrink;
2208
2209         vcpu->halt_poll_ns = val;
2210         trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
2211 }
2212
2213 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2214 {
2215         if (kvm_arch_vcpu_runnable(vcpu)) {
2216                 kvm_make_request(KVM_REQ_UNHALT, vcpu);
2217                 return -EINTR;
2218         }
2219         if (kvm_cpu_has_pending_timer(vcpu))
2220                 return -EINTR;
2221         if (signal_pending(current))
2222                 return -EINTR;
2223
2224         return 0;
2225 }
2226
2227 /*
2228  * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2229  */
2230 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
2231 {
2232         ktime_t start, cur;
2233         DECLARE_SWAITQUEUE(wait);
2234         bool waited = false;
2235         u64 block_ns;
2236
2237         start = cur = ktime_get();
2238         if (vcpu->halt_poll_ns) {
2239                 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
2240
2241                 ++vcpu->stat.halt_attempted_poll;
2242                 do {
2243                         /*
2244                          * This sets KVM_REQ_UNHALT if an interrupt
2245                          * arrives.
2246                          */
2247                         if (kvm_vcpu_check_block(vcpu) < 0) {
2248                                 ++vcpu->stat.halt_successful_poll;
2249                                 if (!vcpu_valid_wakeup(vcpu))
2250                                         ++vcpu->stat.halt_poll_invalid;
2251                                 goto out;
2252                         }
2253                         cur = ktime_get();
2254                 } while (single_task_running() && ktime_before(cur, stop));
2255         }
2256
2257         kvm_arch_vcpu_blocking(vcpu);
2258
2259         for (;;) {
2260                 prepare_to_swait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
2261
2262                 if (kvm_vcpu_check_block(vcpu) < 0)
2263                         break;
2264
2265                 waited = true;
2266                 schedule();
2267         }
2268
2269         finish_swait(&vcpu->wq, &wait);
2270         cur = ktime_get();
2271
2272         kvm_arch_vcpu_unblocking(vcpu);
2273 out:
2274         block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2275
2276         if (!vcpu_valid_wakeup(vcpu))
2277                 shrink_halt_poll_ns(vcpu);
2278         else if (halt_poll_ns) {
2279                 if (block_ns <= vcpu->halt_poll_ns)
2280                         ;
2281                 /* we had a long block, shrink polling */
2282                 else if (vcpu->halt_poll_ns && block_ns > halt_poll_ns)
2283                         shrink_halt_poll_ns(vcpu);
2284                 /* we had a short halt and our poll time is too small */
2285                 else if (vcpu->halt_poll_ns < halt_poll_ns &&
2286                         block_ns < halt_poll_ns)
2287                         grow_halt_poll_ns(vcpu);
2288         } else
2289                 vcpu->halt_poll_ns = 0;
2290
2291         trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
2292         kvm_arch_vcpu_block_finish(vcpu);
2293 }
2294 EXPORT_SYMBOL_GPL(kvm_vcpu_block);
2295
2296 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
2297 {
2298         struct swait_queue_head *wqp;
2299
2300         wqp = kvm_arch_vcpu_wq(vcpu);
2301         if (swq_has_sleeper(wqp)) {
2302                 swake_up(wqp);
2303                 ++vcpu->stat.halt_wakeup;
2304                 return true;
2305         }
2306
2307         return false;
2308 }
2309 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2310
2311 #ifndef CONFIG_S390
2312 /*
2313  * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2314  */
2315 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2316 {
2317         int me;
2318         int cpu = vcpu->cpu;
2319
2320         if (kvm_vcpu_wake_up(vcpu))
2321                 return;
2322
2323         me = get_cpu();
2324         if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2325                 if (kvm_arch_vcpu_should_kick(vcpu))
2326                         smp_send_reschedule(cpu);
2327         put_cpu();
2328 }
2329 EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
2330 #endif /* !CONFIG_S390 */
2331
2332 int kvm_vcpu_yield_to(struct kvm_vcpu *target)
2333 {
2334         struct pid *pid;
2335         struct task_struct *task = NULL;
2336         int ret = 0;
2337
2338         rcu_read_lock();
2339         pid = rcu_dereference(target->pid);
2340         if (pid)
2341                 task = get_pid_task(pid, PIDTYPE_PID);
2342         rcu_read_unlock();
2343         if (!task)
2344                 return ret;
2345         ret = yield_to(task, 1);
2346         put_task_struct(task);
2347
2348         return ret;
2349 }
2350 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2351
2352 /*
2353  * Helper that checks whether a VCPU is eligible for directed yield.
2354  * Most eligible candidate to yield is decided by following heuristics:
2355  *
2356  *  (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2357  *  (preempted lock holder), indicated by @in_spin_loop.
2358  *  Set at the beiginning and cleared at the end of interception/PLE handler.
2359  *
2360  *  (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2361  *  chance last time (mostly it has become eligible now since we have probably
2362  *  yielded to lockholder in last iteration. This is done by toggling
2363  *  @dy_eligible each time a VCPU checked for eligibility.)
2364  *
2365  *  Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2366  *  to preempted lock-holder could result in wrong VCPU selection and CPU
2367  *  burning. Giving priority for a potential lock-holder increases lock
2368  *  progress.
2369  *
2370  *  Since algorithm is based on heuristics, accessing another VCPU data without
2371  *  locking does not harm. It may result in trying to yield to  same VCPU, fail
2372  *  and continue with next VCPU and so on.
2373  */
2374 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
2375 {
2376 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
2377         bool eligible;
2378
2379         eligible = !vcpu->spin_loop.in_spin_loop ||
2380                     vcpu->spin_loop.dy_eligible;
2381
2382         if (vcpu->spin_loop.in_spin_loop)
2383                 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2384
2385         return eligible;
2386 #else
2387         return true;
2388 #endif
2389 }
2390
2391 /*
2392  * Unlike kvm_arch_vcpu_runnable, this function is called outside
2393  * a vcpu_load/vcpu_put pair.  However, for most architectures
2394  * kvm_arch_vcpu_runnable does not require vcpu_load.
2395  */
2396 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
2397 {
2398         return kvm_arch_vcpu_runnable(vcpu);
2399 }
2400
2401 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
2402 {
2403         if (kvm_arch_dy_runnable(vcpu))
2404                 return true;
2405
2406 #ifdef CONFIG_KVM_ASYNC_PF
2407         if (!list_empty_careful(&vcpu->async_pf.done))
2408                 return true;
2409 #endif
2410
2411         return false;
2412 }
2413
2414 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
2415 {
2416         struct kvm *kvm = me->kvm;
2417         struct kvm_vcpu *vcpu;
2418         int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
2419         int yielded = 0;
2420         int try = 3;
2421         int pass;
2422         int i;
2423
2424         kvm_vcpu_set_in_spin_loop(me, true);
2425         /*
2426          * We boost the priority of a VCPU that is runnable but not
2427          * currently running, because it got preempted by something
2428          * else and called schedule in __vcpu_run.  Hopefully that
2429          * VCPU is holding the lock that we need and will release it.
2430          * We approximate round-robin by starting at the last boosted VCPU.
2431          */
2432         for (pass = 0; pass < 2 && !yielded && try; pass++) {
2433                 kvm_for_each_vcpu(i, vcpu, kvm) {
2434                         if (!pass && i <= last_boosted_vcpu) {
2435                                 i = last_boosted_vcpu;
2436                                 continue;
2437                         } else if (pass && i > last_boosted_vcpu)
2438                                 break;
2439                         if (!ACCESS_ONCE(vcpu->preempted))
2440                                 continue;
2441                         if (vcpu == me)
2442                                 continue;
2443                         if (swait_active(&vcpu->wq) && !vcpu_dy_runnable(vcpu))
2444                                 continue;
2445                         if (yield_to_kernel_mode && !kvm_arch_vcpu_in_kernel(vcpu))
2446                                 continue;
2447                         if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
2448                                 continue;
2449
2450                         yielded = kvm_vcpu_yield_to(vcpu);
2451                         if (yielded > 0) {
2452                                 kvm->last_boosted_vcpu = i;
2453                                 break;
2454                         } else if (yielded < 0) {
2455                                 try--;
2456                                 if (!try)
2457                                         break;
2458                         }
2459                 }
2460         }
2461         kvm_vcpu_set_in_spin_loop(me, false);
2462
2463         /* Ensure vcpu is not eligible during next spinloop */
2464         kvm_vcpu_set_dy_eligible(me, false);
2465 }
2466 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
2467
2468 static int kvm_vcpu_fault(struct vm_fault *vmf)
2469 {
2470         struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
2471         struct page *page;
2472
2473         if (vmf->pgoff == 0)
2474                 page = virt_to_page(vcpu->run);
2475 #ifdef CONFIG_X86
2476         else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
2477                 page = virt_to_page(vcpu->arch.pio_data);
2478 #endif
2479 #ifdef CONFIG_KVM_MMIO
2480         else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
2481                 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
2482 #endif
2483         else
2484                 return kvm_arch_vcpu_fault(vcpu, vmf);
2485         get_page(page);
2486         vmf->page = page;
2487         return 0;
2488 }
2489
2490 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
2491         .fault = kvm_vcpu_fault,
2492 };
2493
2494 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2495 {
2496         vma->vm_ops = &kvm_vcpu_vm_ops;
2497         return 0;
2498 }
2499
2500 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2501 {
2502         struct kvm_vcpu *vcpu = filp->private_data;
2503
2504         debugfs_remove_recursive(vcpu->debugfs_dentry);
2505         kvm_put_kvm(vcpu->kvm);
2506         return 0;
2507 }
2508
2509 static struct file_operations kvm_vcpu_fops = {
2510         .release        = kvm_vcpu_release,
2511         .unlocked_ioctl = kvm_vcpu_ioctl,
2512 #ifdef CONFIG_KVM_COMPAT
2513         .compat_ioctl   = kvm_vcpu_compat_ioctl,
2514 #endif
2515         .mmap           = kvm_vcpu_mmap,
2516         .llseek         = noop_llseek,
2517 };
2518
2519 /*
2520  * Allocates an inode for the vcpu.
2521  */
2522 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2523 {
2524         return anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
2525 }
2526
2527 static int kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
2528 {
2529         char dir_name[ITOA_MAX_LEN * 2];
2530         int ret;
2531
2532         if (!kvm_arch_has_vcpu_debugfs())
2533                 return 0;
2534
2535         if (!debugfs_initialized())
2536                 return 0;
2537
2538         snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
2539         vcpu->debugfs_dentry = debugfs_create_dir(dir_name,
2540                                                                 vcpu->kvm->debugfs_dentry);
2541         if (!vcpu->debugfs_dentry)
2542                 return -ENOMEM;
2543
2544         ret = kvm_arch_create_vcpu_debugfs(vcpu);
2545         if (ret < 0) {
2546                 debugfs_remove_recursive(vcpu->debugfs_dentry);
2547                 return ret;
2548         }
2549
2550         return 0;
2551 }
2552
2553 /*
2554  * Creates some virtual cpus.  Good luck creating more than one.
2555  */
2556 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
2557 {
2558         int r;
2559         struct kvm_vcpu *vcpu;
2560
2561         if (id >= KVM_MAX_VCPU_ID)
2562                 return -EINVAL;
2563
2564         mutex_lock(&kvm->lock);
2565         if (kvm->created_vcpus == KVM_MAX_VCPUS) {
2566                 mutex_unlock(&kvm->lock);
2567                 return -EINVAL;
2568         }
2569
2570         kvm->created_vcpus++;
2571         mutex_unlock(&kvm->lock);
2572
2573         vcpu = kvm_arch_vcpu_create(kvm, id);
2574         if (IS_ERR(vcpu)) {
2575                 r = PTR_ERR(vcpu);
2576                 goto vcpu_decrement;
2577         }
2578
2579         preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
2580
2581         r = kvm_arch_vcpu_setup(vcpu);
2582         if (r)
2583                 goto vcpu_destroy;
2584
2585         r = kvm_create_vcpu_debugfs(vcpu);
2586         if (r)
2587                 goto vcpu_destroy;
2588
2589         mutex_lock(&kvm->lock);
2590         if (kvm_get_vcpu_by_id(kvm, id)) {
2591                 r = -EEXIST;
2592                 goto unlock_vcpu_destroy;
2593         }
2594
2595         BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
2596
2597         /* Now it's all set up, let userspace reach it */
2598         kvm_get_kvm(kvm);
2599         r = create_vcpu_fd(vcpu);
2600         if (r < 0) {
2601                 kvm_put_kvm(kvm);
2602                 goto unlock_vcpu_destroy;
2603         }
2604
2605         kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
2606
2607         /*
2608          * Pairs with smp_rmb() in kvm_get_vcpu.  Write kvm->vcpus
2609          * before kvm->online_vcpu's incremented value.
2610          */
2611         smp_wmb();
2612         atomic_inc(&kvm->online_vcpus);
2613
2614         mutex_unlock(&kvm->lock);
2615         kvm_arch_vcpu_postcreate(vcpu);
2616         return r;
2617
2618 unlock_vcpu_destroy:
2619         mutex_unlock(&kvm->lock);
2620         debugfs_remove_recursive(vcpu->debugfs_dentry);
2621 vcpu_destroy:
2622         kvm_arch_vcpu_destroy(vcpu);
2623 vcpu_decrement:
2624         mutex_lock(&kvm->lock);
2625         kvm->created_vcpus--;
2626         mutex_unlock(&kvm->lock);
2627         return r;
2628 }
2629
2630 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
2631 {
2632         if (sigset) {
2633                 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
2634                 vcpu->sigset_active = 1;
2635                 vcpu->sigset = *sigset;
2636         } else
2637                 vcpu->sigset_active = 0;
2638         return 0;
2639 }
2640
2641 static long kvm_vcpu_ioctl(struct file *filp,
2642                            unsigned int ioctl, unsigned long arg)
2643 {
2644         struct kvm_vcpu *vcpu = filp->private_data;
2645         void __user *argp = (void __user *)arg;
2646         int r;
2647         struct kvm_fpu *fpu = NULL;
2648         struct kvm_sregs *kvm_sregs = NULL;
2649
2650         if (vcpu->kvm->mm != current->mm)
2651                 return -EIO;
2652
2653         if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
2654                 return -EINVAL;
2655
2656 #if defined(CONFIG_S390) || defined(CONFIG_PPC) || defined(CONFIG_MIPS)
2657         /*
2658          * Special cases: vcpu ioctls that are asynchronous to vcpu execution,
2659          * so vcpu_load() would break it.
2660          */
2661         if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_S390_IRQ || ioctl == KVM_INTERRUPT)
2662                 return kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2663 #endif
2664
2665
2666         r = vcpu_load(vcpu);
2667         if (r)
2668                 return r;
2669         switch (ioctl) {
2670         case KVM_RUN: {
2671                 struct pid *oldpid;
2672                 r = -EINVAL;
2673                 if (arg)
2674                         goto out;
2675                 oldpid = rcu_access_pointer(vcpu->pid);
2676                 if (unlikely(oldpid != current->pids[PIDTYPE_PID].pid)) {
2677                         /* The thread running this VCPU changed. */
2678                         struct pid *newpid = get_task_pid(current, PIDTYPE_PID);
2679
2680                         rcu_assign_pointer(vcpu->pid, newpid);
2681                         if (oldpid)
2682                                 synchronize_rcu();
2683                         put_pid(oldpid);
2684                 }
2685                 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
2686                 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
2687                 break;
2688         }
2689         case KVM_GET_REGS: {
2690                 struct kvm_regs *kvm_regs;
2691
2692                 r = -ENOMEM;
2693                 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
2694                 if (!kvm_regs)
2695                         goto out;
2696                 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
2697                 if (r)
2698                         goto out_free1;
2699                 r = -EFAULT;
2700                 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
2701                         goto out_free1;
2702                 r = 0;
2703 out_free1:
2704                 kfree(kvm_regs);
2705                 break;
2706         }
2707         case KVM_SET_REGS: {
2708                 struct kvm_regs *kvm_regs;
2709
2710                 r = -ENOMEM;
2711                 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
2712                 if (IS_ERR(kvm_regs)) {
2713                         r = PTR_ERR(kvm_regs);
2714                         goto out;
2715                 }
2716                 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
2717                 kfree(kvm_regs);
2718                 break;
2719         }
2720         case KVM_GET_SREGS: {
2721                 kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
2722                 r = -ENOMEM;
2723                 if (!kvm_sregs)
2724                         goto out;
2725                 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
2726                 if (r)
2727                         goto out;
2728                 r = -EFAULT;
2729                 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
2730                         goto out;
2731                 r = 0;
2732                 break;
2733         }
2734         case KVM_SET_SREGS: {
2735                 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
2736                 if (IS_ERR(kvm_sregs)) {
2737                         r = PTR_ERR(kvm_sregs);
2738                         kvm_sregs = NULL;
2739                         goto out;
2740                 }
2741                 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
2742                 break;
2743         }
2744         case KVM_GET_MP_STATE: {
2745                 struct kvm_mp_state mp_state;
2746
2747                 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
2748                 if (r)
2749                         goto out;
2750                 r = -EFAULT;
2751                 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
2752                         goto out;
2753                 r = 0;
2754                 break;
2755         }
2756         case KVM_SET_MP_STATE: {
2757                 struct kvm_mp_state mp_state;
2758
2759                 r = -EFAULT;
2760                 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
2761                         goto out;
2762                 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
2763                 break;
2764         }
2765         case KVM_TRANSLATE: {
2766                 struct kvm_translation tr;
2767
2768                 r = -EFAULT;
2769                 if (copy_from_user(&tr, argp, sizeof(tr)))
2770                         goto out;
2771                 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
2772                 if (r)
2773                         goto out;
2774                 r = -EFAULT;
2775                 if (copy_to_user(argp, &tr, sizeof(tr)))
2776                         goto out;
2777                 r = 0;
2778                 break;
2779         }
2780         case KVM_SET_GUEST_DEBUG: {
2781                 struct kvm_guest_debug dbg;
2782
2783                 r = -EFAULT;
2784                 if (copy_from_user(&dbg, argp, sizeof(dbg)))
2785                         goto out;
2786                 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
2787                 break;
2788         }
2789         case KVM_SET_SIGNAL_MASK: {
2790                 struct kvm_signal_mask __user *sigmask_arg = argp;
2791                 struct kvm_signal_mask kvm_sigmask;
2792                 sigset_t sigset, *p;
2793
2794                 p = NULL;
2795                 if (argp) {
2796                         r = -EFAULT;
2797                         if (copy_from_user(&kvm_sigmask, argp,
2798                                            sizeof(kvm_sigmask)))
2799                                 goto out;
2800                         r = -EINVAL;
2801                         if (kvm_sigmask.len != sizeof(sigset))
2802                                 goto out;
2803                         r = -EFAULT;
2804                         if (copy_from_user(&sigset, sigmask_arg->sigset,
2805                                            sizeof(sigset)))
2806                                 goto out;
2807                         p = &sigset;
2808                 }
2809                 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
2810                 break;
2811         }
2812         case KVM_GET_FPU: {
2813                 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
2814                 r = -ENOMEM;
2815                 if (!fpu)
2816                         goto out;
2817                 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
2818                 if (r)
2819                         goto out;
2820                 r = -EFAULT;
2821                 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
2822                         goto out;
2823                 r = 0;
2824                 break;
2825         }
2826         case KVM_SET_FPU: {
2827                 fpu = memdup_user(argp, sizeof(*fpu));
2828                 if (IS_ERR(fpu)) {
2829                         r = PTR_ERR(fpu);
2830                         fpu = NULL;
2831                         goto out;
2832                 }
2833                 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
2834                 break;
2835         }
2836         default:
2837                 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2838         }
2839 out:
2840         vcpu_put(vcpu);
2841         kfree(fpu);
2842         kfree(kvm_sregs);
2843         return r;
2844 }
2845
2846 #ifdef CONFIG_KVM_COMPAT
2847 static long kvm_vcpu_compat_ioctl(struct file *filp,
2848                                   unsigned int ioctl, unsigned long arg)
2849 {
2850         struct kvm_vcpu *vcpu = filp->private_data;
2851         void __user *argp = compat_ptr(arg);
2852         int r;
2853
2854         if (vcpu->kvm->mm != current->mm)
2855                 return -EIO;
2856
2857         switch (ioctl) {
2858         case KVM_SET_SIGNAL_MASK: {
2859                 struct kvm_signal_mask __user *sigmask_arg = argp;
2860                 struct kvm_signal_mask kvm_sigmask;
2861                 compat_sigset_t csigset;
2862                 sigset_t sigset;
2863
2864                 if (argp) {
2865                         r = -EFAULT;
2866                         if (copy_from_user(&kvm_sigmask, argp,
2867                                            sizeof(kvm_sigmask)))
2868                                 goto out;
2869                         r = -EINVAL;
2870                         if (kvm_sigmask.len != sizeof(csigset))
2871                                 goto out;
2872                         r = -EFAULT;
2873                         if (copy_from_user(&csigset, sigmask_arg->sigset,
2874                                            sizeof(csigset)))
2875                                 goto out;
2876                         sigset_from_compat(&sigset, &csigset);
2877                         r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
2878                 } else
2879                         r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
2880                 break;
2881         }
2882         default:
2883                 r = kvm_vcpu_ioctl(filp, ioctl, arg);
2884         }
2885
2886 out:
2887         return r;
2888 }
2889 #endif
2890
2891 static int kvm_device_ioctl_attr(struct kvm_device *dev,
2892                                  int (*accessor)(struct kvm_device *dev,
2893                                                  struct kvm_device_attr *attr),
2894                                  unsigned long arg)
2895 {
2896         struct kvm_device_attr attr;
2897
2898         if (!accessor)
2899                 return -EPERM;
2900
2901         if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
2902                 return -EFAULT;
2903
2904         return accessor(dev, &attr);
2905 }
2906
2907 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
2908                              unsigned long arg)
2909 {
2910         struct kvm_device *dev = filp->private_data;
2911
2912         if (dev->kvm->mm != current->mm)
2913                 return -EIO;
2914
2915         switch (ioctl) {
2916         case KVM_SET_DEVICE_ATTR:
2917                 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
2918         case KVM_GET_DEVICE_ATTR:
2919                 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
2920         case KVM_HAS_DEVICE_ATTR:
2921                 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
2922         default:
2923                 if (dev->ops->ioctl)
2924                         return dev->ops->ioctl(dev, ioctl, arg);
2925
2926                 return -ENOTTY;
2927         }
2928 }
2929
2930 static int kvm_device_release(struct inode *inode, struct file *filp)
2931 {
2932         struct kvm_device *dev = filp->private_data;
2933         struct kvm *kvm = dev->kvm;
2934
2935         kvm_put_kvm(kvm);
2936         return 0;
2937 }
2938
2939 static const struct file_operations kvm_device_fops = {
2940         .unlocked_ioctl = kvm_device_ioctl,
2941 #ifdef CONFIG_KVM_COMPAT
2942         .compat_ioctl = kvm_device_ioctl,
2943 #endif
2944         .release = kvm_device_release,
2945 };
2946
2947 struct kvm_device *kvm_device_from_filp(struct file *filp)
2948 {
2949         if (filp->f_op != &kvm_device_fops)
2950                 return NULL;
2951
2952         return filp->private_data;
2953 }
2954
2955 static struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
2956 #ifdef CONFIG_KVM_MPIC
2957         [KVM_DEV_TYPE_FSL_MPIC_20]      = &kvm_mpic_ops,
2958         [KVM_DEV_TYPE_FSL_MPIC_42]      = &kvm_mpic_ops,
2959 #endif
2960 };
2961
2962 int kvm_register_device_ops(struct kvm_device_ops *ops, u32 type)
2963 {
2964         if (type >= ARRAY_SIZE(kvm_device_ops_table))
2965                 return -ENOSPC;
2966
2967         if (kvm_device_ops_table[type] != NULL)
2968                 return -EEXIST;
2969
2970         kvm_device_ops_table[type] = ops;
2971         return 0;
2972 }
2973
2974 void kvm_unregister_device_ops(u32 type)
2975 {
2976         if (kvm_device_ops_table[type] != NULL)
2977                 kvm_device_ops_table[type] = NULL;
2978 }
2979
2980 static int kvm_ioctl_create_device(struct kvm *kvm,
2981                                    struct kvm_create_device *cd)
2982 {
2983         struct kvm_device_ops *ops = NULL;
2984         struct kvm_device *dev;
2985         bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
2986         int type;
2987         int ret;
2988
2989         if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
2990                 return -ENODEV;
2991
2992         type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
2993         ops = kvm_device_ops_table[type];
2994         if (ops == NULL)
2995                 return -ENODEV;
2996
2997         if (test)
2998                 return 0;
2999
3000         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3001         if (!dev)
3002                 return -ENOMEM;
3003
3004         dev->ops = ops;
3005         dev->kvm = kvm;
3006
3007         mutex_lock(&kvm->lock);
3008         ret = ops->create(dev, type);
3009         if (ret < 0) {
3010                 mutex_unlock(&kvm->lock);
3011                 kfree(dev);
3012                 return ret;
3013         }
3014         list_add(&dev->vm_node, &kvm->devices);
3015         mutex_unlock(&kvm->lock);
3016
3017         if (ops->init)
3018                 ops->init(dev);
3019
3020         kvm_get_kvm(kvm);
3021         ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
3022         if (ret < 0) {
3023                 kvm_put_kvm(kvm);
3024                 mutex_lock(&kvm->lock);
3025                 list_del(&dev->vm_node);
3026                 mutex_unlock(&kvm->lock);
3027                 ops->destroy(dev);
3028                 return ret;
3029         }
3030
3031         cd->fd = ret;
3032         return 0;
3033 }
3034
3035 static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3036 {
3037         switch (arg) {
3038         case KVM_CAP_USER_MEMORY:
3039         case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3040         case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
3041         case KVM_CAP_INTERNAL_ERROR_DATA:
3042 #ifdef CONFIG_HAVE_KVM_MSI
3043         case KVM_CAP_SIGNAL_MSI:
3044 #endif
3045 #ifdef CONFIG_HAVE_KVM_IRQFD
3046         case KVM_CAP_IRQFD:
3047         case KVM_CAP_IRQFD_RESAMPLE:
3048 #endif
3049         case KVM_CAP_IOEVENTFD_ANY_LENGTH:
3050         case KVM_CAP_CHECK_EXTENSION_VM:
3051                 return 1;
3052 #ifdef CONFIG_KVM_MMIO
3053         case KVM_CAP_COALESCED_MMIO:
3054                 return KVM_COALESCED_MMIO_PAGE_OFFSET;
3055 #endif
3056 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3057         case KVM_CAP_IRQ_ROUTING:
3058                 return KVM_MAX_IRQ_ROUTES;
3059 #endif
3060 #if KVM_ADDRESS_SPACE_NUM > 1
3061         case KVM_CAP_MULTI_ADDRESS_SPACE:
3062                 return KVM_ADDRESS_SPACE_NUM;
3063 #endif
3064         default:
3065                 break;
3066         }
3067         return kvm_vm_ioctl_check_extension(kvm, arg);
3068 }
3069
3070 static long kvm_vm_ioctl(struct file *filp,
3071                            unsigned int ioctl, unsigned long arg)
3072 {
3073         struct kvm *kvm = filp->private_data;
3074         void __user *argp = (void __user *)arg;
3075         int r;
3076
3077         if (kvm->mm != current->mm)
3078                 return -EIO;
3079         switch (ioctl) {
3080         case KVM_CREATE_VCPU:
3081                 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
3082                 break;
3083         case KVM_SET_USER_MEMORY_REGION: {
3084                 struct kvm_userspace_memory_region kvm_userspace_mem;
3085
3086                 r = -EFAULT;
3087                 if (copy_from_user(&kvm_userspace_mem, argp,
3088                                                 sizeof(kvm_userspace_mem)))
3089                         goto out;
3090
3091                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
3092                 break;
3093         }
3094         case KVM_GET_DIRTY_LOG: {
3095                 struct kvm_dirty_log log;
3096
3097                 r = -EFAULT;
3098                 if (copy_from_user(&log, argp, sizeof(log)))
3099                         goto out;
3100                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3101                 break;
3102         }
3103 #ifdef CONFIG_KVM_MMIO
3104         case KVM_REGISTER_COALESCED_MMIO: {
3105                 struct kvm_coalesced_mmio_zone zone;
3106
3107                 r = -EFAULT;
3108                 if (copy_from_user(&zone, argp, sizeof(zone)))
3109                         goto out;
3110                 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
3111                 break;
3112         }
3113         case KVM_UNREGISTER_COALESCED_MMIO: {
3114                 struct kvm_coalesced_mmio_zone zone;
3115
3116                 r = -EFAULT;
3117                 if (copy_from_user(&zone, argp, sizeof(zone)))
3118                         goto out;
3119                 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
3120                 break;
3121         }
3122 #endif
3123         case KVM_IRQFD: {
3124                 struct kvm_irqfd data;
3125
3126                 r = -EFAULT;
3127                 if (copy_from_user(&data, argp, sizeof(data)))
3128                         goto out;
3129                 r = kvm_irqfd(kvm, &data);
3130                 break;
3131         }
3132         case KVM_IOEVENTFD: {
3133                 struct kvm_ioeventfd data;
3134
3135                 r = -EFAULT;
3136                 if (copy_from_user(&data, argp, sizeof(data)))
3137                         goto out;
3138                 r = kvm_ioeventfd(kvm, &data);
3139                 break;
3140         }
3141 #ifdef CONFIG_HAVE_KVM_MSI
3142         case KVM_SIGNAL_MSI: {
3143                 struct kvm_msi msi;
3144
3145                 r = -EFAULT;
3146                 if (copy_from_user(&msi, argp, sizeof(msi)))
3147                         goto out;
3148                 r = kvm_send_userspace_msi(kvm, &msi);
3149                 break;
3150         }
3151 #endif
3152 #ifdef __KVM_HAVE_IRQ_LINE
3153         case KVM_IRQ_LINE_STATUS:
3154         case KVM_IRQ_LINE: {
3155                 struct kvm_irq_level irq_event;
3156
3157                 r = -EFAULT;
3158                 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
3159                         goto out;
3160
3161                 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3162                                         ioctl == KVM_IRQ_LINE_STATUS);
3163                 if (r)
3164                         goto out;
3165
3166                 r = -EFAULT;
3167                 if (ioctl == KVM_IRQ_LINE_STATUS) {
3168                         if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
3169                                 goto out;
3170                 }
3171
3172                 r = 0;
3173                 break;
3174         }
3175 #endif
3176 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3177         case KVM_SET_GSI_ROUTING: {
3178                 struct kvm_irq_routing routing;
3179                 struct kvm_irq_routing __user *urouting;
3180                 struct kvm_irq_routing_entry *entries = NULL;
3181
3182                 r = -EFAULT;
3183                 if (copy_from_user(&routing, argp, sizeof(routing)))
3184                         goto out;
3185                 r = -EINVAL;
3186                 if (!kvm_arch_can_set_irq_routing(kvm))
3187                         goto out;
3188                 if (routing.nr > KVM_MAX_IRQ_ROUTES)
3189                         goto out;
3190                 if (routing.flags)
3191                         goto out;
3192                 if (routing.nr) {
3193                         r = -ENOMEM;
3194                         entries = vmalloc(routing.nr * sizeof(*entries));
3195                         if (!entries)
3196                                 goto out;
3197                         r = -EFAULT;
3198                         urouting = argp;
3199                         if (copy_from_user(entries, urouting->entries,
3200                                            routing.nr * sizeof(*entries)))
3201                                 goto out_free_irq_routing;
3202                 }
3203                 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3204                                         routing.flags);
3205 out_free_irq_routing:
3206                 vfree(entries);
3207                 break;
3208         }
3209 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
3210         case KVM_CREATE_DEVICE: {
3211                 struct kvm_create_device cd;
3212
3213                 r = -EFAULT;
3214                 if (copy_from_user(&cd, argp, sizeof(cd)))
3215                         goto out;
3216
3217                 r = kvm_ioctl_create_device(kvm, &cd);
3218                 if (r)
3219                         goto out;
3220
3221                 r = -EFAULT;
3222                 if (copy_to_user(argp, &cd, sizeof(cd)))
3223                         goto out;
3224
3225                 r = 0;
3226                 break;
3227         }
3228         case KVM_CHECK_EXTENSION:
3229                 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3230                 break;
3231         default:
3232                 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
3233         }
3234 out:
3235         return r;
3236 }
3237
3238 #ifdef CONFIG_KVM_COMPAT
3239 struct compat_kvm_dirty_log {
3240         __u32 slot;
3241         __u32 padding1;
3242         union {
3243                 compat_uptr_t dirty_bitmap; /* one bit per page */
3244                 __u64 padding2;
3245         };
3246 };
3247
3248 static long kvm_vm_compat_ioctl(struct file *filp,
3249                            unsigned int ioctl, unsigned long arg)
3250 {
3251         struct kvm *kvm = filp->private_data;
3252         int r;
3253
3254         if (kvm->mm != current->mm)
3255                 return -EIO;
3256         switch (ioctl) {
3257         case KVM_GET_DIRTY_LOG: {
3258                 struct compat_kvm_dirty_log compat_log;
3259                 struct kvm_dirty_log log;
3260
3261                 if (copy_from_user(&compat_log, (void __user *)arg,
3262                                    sizeof(compat_log)))
3263                         return -EFAULT;
3264                 log.slot         = compat_log.slot;
3265                 log.padding1     = compat_log.padding1;
3266                 log.padding2     = compat_log.padding2;
3267                 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3268
3269                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3270                 break;
3271         }
3272         default:
3273                 r = kvm_vm_ioctl(filp, ioctl, arg);
3274         }
3275         return r;
3276 }
3277 #endif
3278
3279 static struct file_operations kvm_vm_fops = {
3280         .release        = kvm_vm_release,
3281         .unlocked_ioctl = kvm_vm_ioctl,
3282 #ifdef CONFIG_KVM_COMPAT
3283         .compat_ioctl   = kvm_vm_compat_ioctl,
3284 #endif
3285         .llseek         = noop_llseek,
3286 };
3287
3288 static int kvm_dev_ioctl_create_vm(unsigned long type)
3289 {
3290         int r;
3291         struct kvm *kvm;
3292         struct file *file;
3293
3294         kvm = kvm_create_vm(type);
3295         if (IS_ERR(kvm))
3296                 return PTR_ERR(kvm);
3297 #ifdef CONFIG_KVM_MMIO
3298         r = kvm_coalesced_mmio_init(kvm);
3299         if (r < 0) {
3300                 kvm_put_kvm(kvm);
3301                 return r;
3302         }
3303 #endif
3304         r = get_unused_fd_flags(O_CLOEXEC);
3305         if (r < 0) {
3306                 kvm_put_kvm(kvm);
3307                 return r;
3308         }
3309         file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
3310         if (IS_ERR(file)) {
3311                 put_unused_fd(r);
3312                 kvm_put_kvm(kvm);
3313                 return PTR_ERR(file);
3314         }
3315
3316         /*
3317          * Don't call kvm_put_kvm anymore at this point; file->f_op is
3318          * already set, with ->release() being kvm_vm_release().  In error
3319          * cases it will be called by the final fput(file) and will take
3320          * care of doing kvm_put_kvm(kvm).
3321          */
3322         if (kvm_create_vm_debugfs(kvm, r) < 0) {
3323                 put_unused_fd(r);
3324                 fput(file);
3325                 return -ENOMEM;
3326         }
3327         kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
3328
3329         fd_install(r, file);
3330         return r;
3331 }
3332
3333 static long kvm_dev_ioctl(struct file *filp,
3334                           unsigned int ioctl, unsigned long arg)
3335 {
3336         long r = -EINVAL;
3337
3338         switch (ioctl) {
3339         case KVM_GET_API_VERSION:
3340                 if (arg)
3341                         goto out;
3342                 r = KVM_API_VERSION;
3343                 break;
3344         case KVM_CREATE_VM:
3345                 r = kvm_dev_ioctl_create_vm(arg);
3346                 break;
3347         case KVM_CHECK_EXTENSION:
3348                 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
3349                 break;
3350         case KVM_GET_VCPU_MMAP_SIZE:
3351                 if (arg)
3352                         goto out;
3353                 r = PAGE_SIZE;     /* struct kvm_run */
3354 #ifdef CONFIG_X86
3355                 r += PAGE_SIZE;    /* pio data page */
3356 #endif
3357 #ifdef CONFIG_KVM_MMIO
3358                 r += PAGE_SIZE;    /* coalesced mmio ring page */
3359 #endif
3360                 break;
3361         case KVM_TRACE_ENABLE:
3362         case KVM_TRACE_PAUSE:
3363         case KVM_TRACE_DISABLE:
3364                 r = -EOPNOTSUPP;
3365                 break;
3366         default:
3367                 return kvm_arch_dev_ioctl(filp, ioctl, arg);
3368         }
3369 out:
3370         return r;
3371 }
3372
3373 static struct file_operations kvm_chardev_ops = {
3374         .unlocked_ioctl = kvm_dev_ioctl,
3375         .compat_ioctl   = kvm_dev_ioctl,
3376         .llseek         = noop_llseek,
3377 };
3378
3379 static struct miscdevice kvm_dev = {
3380         KVM_MINOR,
3381         "kvm",
3382         &kvm_chardev_ops,
3383 };
3384
3385 static void hardware_enable_nolock(void *junk)
3386 {
3387         int cpu = raw_smp_processor_id();
3388         int r;
3389
3390         if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
3391                 return;
3392
3393         cpumask_set_cpu(cpu, cpus_hardware_enabled);
3394
3395         r = kvm_arch_hardware_enable();
3396
3397         if (r) {
3398                 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3399                 atomic_inc(&hardware_enable_failed);
3400                 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
3401         }
3402 }
3403
3404 static int kvm_starting_cpu(unsigned int cpu)
3405 {
3406         raw_spin_lock(&kvm_count_lock);
3407         if (kvm_usage_count)
3408                 hardware_enable_nolock(NULL);
3409         raw_spin_unlock(&kvm_count_lock);
3410         return 0;
3411 }
3412
3413 static void hardware_disable_nolock(void *junk)
3414 {
3415         int cpu = raw_smp_processor_id();
3416
3417         if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
3418                 return;
3419         cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3420         kvm_arch_hardware_disable();
3421 }
3422
3423 static int kvm_dying_cpu(unsigned int cpu)
3424 {
3425         raw_spin_lock(&kvm_count_lock);
3426         if (kvm_usage_count)
3427                 hardware_disable_nolock(NULL);
3428         raw_spin_unlock(&kvm_count_lock);
3429         return 0;
3430 }
3431
3432 static void hardware_disable_all_nolock(void)
3433 {
3434         BUG_ON(!kvm_usage_count);
3435
3436         kvm_usage_count--;
3437         if (!kvm_usage_count)
3438                 on_each_cpu(hardware_disable_nolock, NULL, 1);
3439 }
3440
3441 static void hardware_disable_all(void)
3442 {
3443         raw_spin_lock(&kvm_count_lock);
3444         hardware_disable_all_nolock();
3445         raw_spin_unlock(&kvm_count_lock);
3446 }
3447
3448 static int hardware_enable_all(void)
3449 {
3450         int r = 0;
3451
3452         raw_spin_lock(&kvm_count_lock);
3453
3454         kvm_usage_count++;
3455         if (kvm_usage_count == 1) {
3456                 atomic_set(&hardware_enable_failed, 0);
3457                 on_each_cpu(hardware_enable_nolock, NULL, 1);
3458
3459                 if (atomic_read(&hardware_enable_failed)) {
3460                         hardware_disable_all_nolock();
3461                         r = -EBUSY;
3462                 }
3463         }
3464
3465         raw_spin_unlock(&kvm_count_lock);
3466
3467         return r;
3468 }
3469
3470 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
3471                       void *v)
3472 {
3473         /*
3474          * Some (well, at least mine) BIOSes hang on reboot if
3475          * in vmx root mode.
3476          *
3477          * And Intel TXT required VMX off for all cpu when system shutdown.
3478          */
3479         pr_info("kvm: exiting hardware virtualization\n");
3480         kvm_rebooting = true;
3481         on_each_cpu(hardware_disable_nolock, NULL, 1);
3482         return NOTIFY_OK;
3483 }
3484
3485 static struct notifier_block kvm_reboot_notifier = {
3486         .notifier_call = kvm_reboot,
3487         .priority = 0,
3488 };
3489
3490 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
3491 {
3492         int i;
3493
3494         for (i = 0; i < bus->dev_count; i++) {
3495                 struct kvm_io_device *pos = bus->range[i].dev;
3496
3497                 kvm_iodevice_destructor(pos);
3498         }
3499         kfree(bus);
3500 }
3501
3502 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
3503                                  const struct kvm_io_range *r2)
3504 {
3505         gpa_t addr1 = r1->addr;
3506         gpa_t addr2 = r2->addr;
3507
3508         if (addr1 < addr2)
3509                 return -1;
3510
3511         /* If r2->len == 0, match the exact address.  If r2->len != 0,
3512          * accept any overlapping write.  Any order is acceptable for
3513          * overlapping ranges, because kvm_io_bus_get_first_dev ensures
3514          * we process all of them.
3515          */
3516         if (r2->len) {
3517                 addr1 += r1->len;
3518                 addr2 += r2->len;
3519         }
3520
3521         if (addr1 > addr2)
3522                 return 1;
3523
3524         return 0;
3525 }
3526
3527 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
3528 {
3529         return kvm_io_bus_cmp(p1, p2);
3530 }
3531
3532 static int kvm_io_bus_insert_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev,
3533                           gpa_t addr, int len)
3534 {
3535         bus->range[bus->dev_count++] = (struct kvm_io_range) {
3536                 .addr = addr,
3537                 .len = len,
3538                 .dev = dev,
3539         };
3540
3541         sort(bus->range, bus->dev_count, sizeof(struct kvm_io_range),
3542                 kvm_io_bus_sort_cmp, NULL);
3543
3544         return 0;
3545 }
3546
3547 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
3548                              gpa_t addr, int len)
3549 {
3550         struct kvm_io_range *range, key;
3551         int off;
3552
3553         key = (struct kvm_io_range) {
3554                 .addr = addr,
3555                 .len = len,
3556         };
3557
3558         range = bsearch(&key, bus->range, bus->dev_count,
3559                         sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
3560         if (range == NULL)
3561                 return -ENOENT;
3562
3563         off = range - bus->range;
3564
3565         while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
3566                 off--;
3567
3568         return off;
3569 }
3570
3571 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3572                               struct kvm_io_range *range, const void *val)
3573 {
3574         int idx;
3575
3576         idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3577         if (idx < 0)
3578                 return -EOPNOTSUPP;
3579
3580         while (idx < bus->dev_count &&
3581                 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3582                 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
3583                                         range->len, val))
3584                         return idx;
3585                 idx++;
3586         }
3587
3588         return -EOPNOTSUPP;
3589 }
3590
3591 /* kvm_io_bus_write - called under kvm->slots_lock */
3592 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3593                      int len, const void *val)
3594 {
3595         struct kvm_io_bus *bus;
3596         struct kvm_io_range range;
3597         int r;
3598
3599         range = (struct kvm_io_range) {
3600                 .addr = addr,
3601                 .len = len,
3602         };
3603
3604         bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3605         if (!bus)
3606                 return -ENOMEM;
3607         r = __kvm_io_bus_write(vcpu, bus, &range, val);
3608         return r < 0 ? r : 0;
3609 }
3610
3611 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
3612 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
3613                             gpa_t addr, int len, const void *val, long cookie)
3614 {
3615         struct kvm_io_bus *bus;
3616         struct kvm_io_range range;
3617
3618         range = (struct kvm_io_range) {
3619                 .addr = addr,
3620                 .len = len,
3621         };
3622
3623         bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3624         if (!bus)
3625                 return -ENOMEM;
3626
3627         /* First try the device referenced by cookie. */
3628         if ((cookie >= 0) && (cookie < bus->dev_count) &&
3629             (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
3630                 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
3631                                         val))
3632                         return cookie;
3633
3634         /*
3635          * cookie contained garbage; fall back to search and return the
3636          * correct cookie value.
3637          */
3638         return __kvm_io_bus_write(vcpu, bus, &range, val);
3639 }
3640
3641 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
3642                              struct kvm_io_range *range, void *val)
3643 {
3644         int idx;
3645
3646         idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3647         if (idx < 0)
3648                 return -EOPNOTSUPP;
3649
3650         while (idx < bus->dev_count &&
3651                 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3652                 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
3653                                        range->len, val))
3654                         return idx;
3655                 idx++;
3656         }
3657
3658         return -EOPNOTSUPP;
3659 }
3660 EXPORT_SYMBOL_GPL(kvm_io_bus_write);
3661
3662 /* kvm_io_bus_read - called under kvm->slots_lock */
3663 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
3664                     int len, void *val)
3665 {
3666         struct kvm_io_bus *bus;
3667         struct kvm_io_range range;
3668         int r;
3669
3670         range = (struct kvm_io_range) {
3671                 .addr = addr,
3672                 .len = len,
3673         };
3674
3675         bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
3676         if (!bus)
3677                 return -ENOMEM;
3678         r = __kvm_io_bus_read(vcpu, bus, &range, val);
3679         return r < 0 ? r : 0;
3680 }
3681
3682
3683 /* Caller must hold slots_lock. */
3684 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
3685                             int len, struct kvm_io_device *dev)
3686 {
3687         struct kvm_io_bus *new_bus, *bus;
3688
3689         bus = kvm_get_bus(kvm, bus_idx);
3690         if (!bus)
3691                 return -ENOMEM;
3692
3693         /* exclude ioeventfd which is limited by maximum fd */
3694         if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
3695                 return -ENOSPC;
3696
3697         new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count + 1) *
3698                           sizeof(struct kvm_io_range)), GFP_KERNEL);
3699         if (!new_bus)
3700                 return -ENOMEM;
3701         memcpy(new_bus, bus, sizeof(*bus) + (bus->dev_count *
3702                sizeof(struct kvm_io_range)));
3703         kvm_io_bus_insert_dev(new_bus, dev, addr, len);
3704         rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3705         synchronize_srcu_expedited(&kvm->srcu);
3706         kfree(bus);
3707
3708         return 0;
3709 }
3710
3711 /* Caller must hold slots_lock. */
3712 void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3713                                struct kvm_io_device *dev)
3714 {
3715         int i, j;
3716         struct kvm_io_bus *new_bus, *bus;
3717
3718         bus = kvm_get_bus(kvm, bus_idx);
3719         if (!bus)
3720                 return;
3721
3722         for (i = 0; i < bus->dev_count; i++)
3723                 if (bus->range[i].dev == dev) {
3724                         break;
3725                 }
3726
3727         if (i == bus->dev_count)
3728                 return;
3729
3730         new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count - 1) *
3731                           sizeof(struct kvm_io_range)), GFP_KERNEL);
3732         if (new_bus) {
3733                 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
3734                 new_bus->dev_count--;
3735                 memcpy(new_bus->range + i, bus->range + i + 1,
3736                        (new_bus->dev_count - i) * sizeof(struct kvm_io_range));
3737         } else {
3738                 pr_err("kvm: failed to shrink bus, removing it completely\n");
3739                 for (j = 0; j < bus->dev_count; j++) {
3740                         if (j == i)
3741                                 continue;
3742                         kvm_iodevice_destructor(bus->range[j].dev);
3743                 }
3744         }
3745
3746         rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3747         synchronize_srcu_expedited(&kvm->srcu);
3748         kfree(bus);
3749         return;
3750 }
3751
3752 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3753                                          gpa_t addr)
3754 {
3755         struct kvm_io_bus *bus;
3756         int dev_idx, srcu_idx;
3757         struct kvm_io_device *iodev = NULL;
3758
3759         srcu_idx = srcu_read_lock(&kvm->srcu);
3760
3761         bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
3762         if (!bus)
3763                 goto out_unlock;
3764
3765         dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
3766         if (dev_idx < 0)
3767                 goto out_unlock;
3768
3769         iodev = bus->range[dev_idx].dev;
3770
3771 out_unlock:
3772         srcu_read_unlock(&kvm->srcu, srcu_idx);
3773
3774         return iodev;
3775 }
3776 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
3777
3778 static int kvm_debugfs_open(struct inode *inode, struct file *file,
3779                            int (*get)(void *, u64 *), int (*set)(void *, u64),
3780                            const char *fmt)
3781 {
3782         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3783                                           inode->i_private;
3784
3785         /* The debugfs files are a reference to the kvm struct which
3786          * is still valid when kvm_destroy_vm is called.
3787          * To avoid the race between open and the removal of the debugfs
3788          * directory we test against the users count.
3789          */
3790         if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
3791                 return -ENOENT;
3792
3793         if (simple_attr_open(inode, file, get,
3794                              stat_data->mode & S_IWUGO ? set : NULL,
3795                              fmt)) {
3796                 kvm_put_kvm(stat_data->kvm);
3797                 return -ENOMEM;
3798         }
3799
3800         return 0;
3801 }
3802
3803 static int kvm_debugfs_release(struct inode *inode, struct file *file)
3804 {
3805         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3806                                           inode->i_private;
3807
3808         simple_attr_release(inode, file);
3809         kvm_put_kvm(stat_data->kvm);
3810
3811         return 0;
3812 }
3813
3814 static int vm_stat_get_per_vm(void *data, u64 *val)
3815 {
3816         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3817
3818         *val = *(ulong *)((void *)stat_data->kvm + stat_data->offset);
3819
3820         return 0;
3821 }
3822
3823 static int vm_stat_clear_per_vm(void *data, u64 val)
3824 {
3825         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3826
3827         if (val)
3828                 return -EINVAL;
3829
3830         *(ulong *)((void *)stat_data->kvm + stat_data->offset) = 0;
3831
3832         return 0;
3833 }
3834
3835 static int vm_stat_get_per_vm_open(struct inode *inode, struct file *file)
3836 {
3837         __simple_attr_check_format("%llu\n", 0ull);
3838         return kvm_debugfs_open(inode, file, vm_stat_get_per_vm,
3839                                 vm_stat_clear_per_vm, "%llu\n");
3840 }
3841
3842 static const struct file_operations vm_stat_get_per_vm_fops = {
3843         .owner   = THIS_MODULE,
3844         .open    = vm_stat_get_per_vm_open,
3845         .release = kvm_debugfs_release,
3846         .read    = simple_attr_read,
3847         .write   = simple_attr_write,
3848         .llseek  = no_llseek,
3849 };
3850
3851 static int vcpu_stat_get_per_vm(void *data, u64 *val)
3852 {
3853         int i;
3854         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3855         struct kvm_vcpu *vcpu;
3856
3857         *val = 0;
3858
3859         kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
3860                 *val += *(u64 *)((void *)vcpu + stat_data->offset);
3861
3862         return 0;
3863 }
3864
3865 static int vcpu_stat_clear_per_vm(void *data, u64 val)
3866 {
3867         int i;
3868         struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3869         struct kvm_vcpu *vcpu;
3870
3871         if (val)
3872                 return -EINVAL;
3873
3874         kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
3875                 *(u64 *)((void *)vcpu + stat_data->offset) = 0;
3876
3877         return 0;
3878 }
3879
3880 static int vcpu_stat_get_per_vm_open(struct inode *inode, struct file *file)
3881 {
3882         __simple_attr_check_format("%llu\n", 0ull);
3883         return kvm_debugfs_open(inode, file, vcpu_stat_get_per_vm,
3884                                  vcpu_stat_clear_per_vm, "%llu\n");
3885 }
3886
3887 static const struct file_operations vcpu_stat_get_per_vm_fops = {
3888         .owner   = THIS_MODULE,
3889         .open    = vcpu_stat_get_per_vm_open,
3890         .release = kvm_debugfs_release,
3891         .read    = simple_attr_read,
3892         .write   = simple_attr_write,
3893         .llseek  = no_llseek,
3894 };
3895
3896 static const struct file_operations *stat_fops_per_vm[] = {
3897         [KVM_STAT_VCPU] = &vcpu_stat_get_per_vm_fops,
3898         [KVM_STAT_VM]   = &vm_stat_get_per_vm_fops,
3899 };
3900
3901 static int vm_stat_get(void *_offset, u64 *val)
3902 {
3903         unsigned offset = (long)_offset;
3904         struct kvm *kvm;
3905         struct kvm_stat_data stat_tmp = {.offset = offset};
3906         u64 tmp_val;
3907
3908         *val = 0;
3909         mutex_lock(&kvm_lock);
3910         list_for_each_entry(kvm, &vm_list, vm_list) {
3911                 stat_tmp.kvm = kvm;
3912                 vm_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
3913                 *val += tmp_val;
3914         }
3915         mutex_unlock(&kvm_lock);
3916         return 0;
3917 }
3918
3919 static int vm_stat_clear(void *_offset, u64 val)
3920 {
3921         unsigned offset = (long)_offset;
3922         struct kvm *kvm;
3923         struct kvm_stat_data stat_tmp = {.offset = offset};
3924
3925         if (val)
3926                 return -EINVAL;
3927
3928         mutex_lock(&kvm_lock);
3929         list_for_each_entry(kvm, &vm_list, vm_list) {
3930                 stat_tmp.kvm = kvm;
3931                 vm_stat_clear_per_vm((void *)&stat_tmp, 0);
3932         }
3933         mutex_unlock(&kvm_lock);
3934
3935         return 0;
3936 }
3937
3938 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
3939
3940 static int vcpu_stat_get(void *_offset, u64 *val)
3941 {
3942         unsigned offset = (long)_offset;
3943         struct kvm *kvm;
3944         struct kvm_stat_data stat_tmp = {.offset = offset};
3945         u64 tmp_val;
3946
3947         *val = 0;
3948         mutex_lock(&kvm_lock);
3949         list_for_each_entry(kvm, &vm_list, vm_list) {
3950                 stat_tmp.kvm = kvm;
3951                 vcpu_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
3952                 *val += tmp_val;
3953         }
3954         mutex_unlock(&kvm_lock);
3955         return 0;
3956 }
3957
3958 static int vcpu_stat_clear(void *_offset, u64 val)
3959 {
3960         unsigned offset = (long)_offset;
3961         struct kvm *kvm;
3962         struct kvm_stat_data stat_tmp = {.offset = offset};
3963
3964         if (val)
3965                 return -EINVAL;
3966
3967         mutex_lock(&kvm_lock);
3968         list_for_each_entry(kvm, &vm_list, vm_list) {
3969                 stat_tmp.kvm = kvm;
3970                 vcpu_stat_clear_per_vm((void *)&stat_tmp, 0);
3971         }
3972         mutex_unlock(&kvm_lock);
3973
3974         return 0;
3975 }
3976
3977 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
3978                         "%llu\n");
3979
3980 static const struct file_operations *stat_fops[] = {
3981         [KVM_STAT_VCPU] = &vcpu_stat_fops,
3982         [KVM_STAT_VM]   = &vm_stat_fops,
3983 };
3984
3985 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
3986 {
3987         struct kobj_uevent_env *env;
3988         unsigned long long created, active;
3989
3990         if (!kvm_dev.this_device || !kvm)
3991                 return;
3992
3993         mutex_lock(&kvm_lock);
3994         if (type == KVM_EVENT_CREATE_VM) {
3995                 kvm_createvm_count++;
3996                 kvm_active_vms++;
3997         } else if (type == KVM_EVENT_DESTROY_VM) {
3998                 kvm_active_vms--;
3999         }
4000         created = kvm_createvm_count;
4001         active = kvm_active_vms;
4002         mutex_unlock(&kvm_lock);
4003
4004         env = kzalloc(sizeof(*env), GFP_KERNEL);
4005         if (!env)
4006                 return;
4007
4008         add_uevent_var(env, "CREATED=%llu", created);
4009         add_uevent_var(env, "COUNT=%llu", active);
4010
4011         if (type == KVM_EVENT_CREATE_VM) {
4012                 add_uevent_var(env, "EVENT=create");
4013                 kvm->userspace_pid = task_pid_nr(current);
4014         } else if (type == KVM_EVENT_DESTROY_VM) {
4015                 add_uevent_var(env, "EVENT=destroy");
4016         }
4017         add_uevent_var(env, "PID=%d", kvm->userspace_pid);
4018
4019         if (!IS_ERR_OR_NULL(kvm->debugfs_dentry)) {
4020                 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL);
4021
4022                 if (p) {
4023                         tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
4024                         if (!IS_ERR(tmp))
4025                                 add_uevent_var(env, "STATS_PATH=%s", tmp);
4026                         kfree(p);
4027                 }
4028         }
4029         /* no need for checks, since we are adding at most only 5 keys */
4030         env->envp[env->envp_idx++] = NULL;
4031         kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
4032         kfree(env);
4033 }
4034
4035 static int kvm_init_debug(void)
4036 {
4037         int r = -EEXIST;
4038         struct kvm_stats_debugfs_item *p;
4039
4040         kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
4041         if (kvm_debugfs_dir == NULL)
4042                 goto out;
4043
4044         kvm_debugfs_num_entries = 0;
4045         for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
4046                 int mode = p->mode ? p->mode : 0644;
4047                 if (!debugfs_create_file(p->name, mode, kvm_debugfs_dir,
4048                                          (void *)(long)p->offset,
4049                                          stat_fops[p->kind]))
4050                         goto out_dir;
4051         }
4052
4053         return 0;
4054
4055 out_dir:
4056         debugfs_remove_recursive(kvm_debugfs_dir);
4057 out:
4058         return r;
4059 }
4060
4061 static int kvm_suspend(void)
4062 {
4063         if (kvm_usage_count)
4064                 hardware_disable_nolock(NULL);
4065         return 0;
4066 }
4067
4068 static void kvm_resume(void)
4069 {
4070         if (kvm_usage_count) {
4071                 WARN_ON(raw_spin_is_locked(&kvm_count_lock));
4072                 hardware_enable_nolock(NULL);
4073         }
4074 }
4075
4076 static struct syscore_ops kvm_syscore_ops = {
4077         .suspend = kvm_suspend,
4078         .resume = kvm_resume,
4079 };
4080
4081 static inline
4082 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
4083 {
4084         return container_of(pn, struct kvm_vcpu, preempt_notifier);
4085 }
4086
4087 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
4088 {
4089         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4090
4091         if (vcpu->preempted)
4092                 vcpu->preempted = false;
4093
4094         kvm_arch_sched_in(vcpu, cpu);
4095
4096         kvm_arch_vcpu_load(vcpu, cpu);
4097 }
4098
4099 static void kvm_sched_out(struct preempt_notifier *pn,
4100                           struct task_struct *next)
4101 {
4102         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4103
4104         if (current->state == TASK_RUNNING)
4105                 vcpu->preempted = true;
4106         kvm_arch_vcpu_put(vcpu);
4107 }
4108
4109 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
4110                   struct module *module)
4111 {
4112         int r;
4113         int cpu;
4114
4115         r = kvm_arch_init(opaque);
4116         if (r)
4117                 goto out_fail;
4118
4119         /*
4120          * kvm_arch_init makes sure there's at most one caller
4121          * for architectures that support multiple implementations,
4122          * like intel and amd on x86.
4123          * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
4124          * conflicts in case kvm is already setup for another implementation.
4125          */
4126         r = kvm_irqfd_init();
4127         if (r)
4128                 goto out_irqfd;
4129
4130         if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
4131                 r = -ENOMEM;
4132                 goto out_free_0;
4133         }
4134
4135         r = kvm_arch_hardware_setup();
4136         if (r < 0)
4137                 goto out_free_0a;
4138
4139         for_each_online_cpu(cpu) {
4140                 smp_call_function_single(cpu,
4141                                 kvm_arch_check_processor_compat,
4142                                 &r, 1);
4143                 if (r < 0)
4144                         goto out_free_1;
4145         }
4146
4147         r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
4148                                       kvm_starting_cpu, kvm_dying_cpu);
4149         if (r)
4150                 goto out_free_2;
4151         register_reboot_notifier(&kvm_reboot_notifier);
4152
4153         /* A kmem cache lets us meet the alignment requirements of fx_save. */
4154         if (!vcpu_align)
4155                 vcpu_align = __alignof__(struct kvm_vcpu);
4156         kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size, vcpu_align,
4157                                            SLAB_ACCOUNT, NULL);
4158         if (!kvm_vcpu_cache) {
4159                 r = -ENOMEM;
4160                 goto out_free_3;
4161         }
4162
4163         r = kvm_async_pf_init();
4164         if (r)
4165                 goto out_free;
4166
4167         kvm_chardev_ops.owner = module;
4168         kvm_vm_fops.owner = module;
4169         kvm_vcpu_fops.owner = module;
4170
4171         r = misc_register(&kvm_dev);
4172         if (r) {
4173                 pr_err("kvm: misc device register failed\n");
4174                 goto out_unreg;
4175         }
4176
4177         register_syscore_ops(&kvm_syscore_ops);
4178
4179         kvm_preempt_ops.sched_in = kvm_sched_in;
4180         kvm_preempt_ops.sched_out = kvm_sched_out;
4181
4182         r = kvm_init_debug();
4183         if (r) {
4184                 pr_err("kvm: create debugfs files failed\n");
4185                 goto out_undebugfs;
4186         }
4187
4188         r = kvm_vfio_ops_init();
4189         WARN_ON(r);
4190
4191         return 0;
4192
4193 out_undebugfs:
4194         unregister_syscore_ops(&kvm_syscore_ops);
4195         misc_deregister(&kvm_dev);
4196 out_unreg:
4197         kvm_async_pf_deinit();
4198 out_free:
4199         kmem_cache_destroy(kvm_vcpu_cache);
4200 out_free_3:
4201         unregister_reboot_notifier(&kvm_reboot_notifier);
4202         cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4203 out_free_2:
4204 out_free_1:
4205         kvm_arch_hardware_unsetup();
4206 out_free_0a:
4207         free_cpumask_var(cpus_hardware_enabled);
4208 out_free_0:
4209         kvm_irqfd_exit();
4210 out_irqfd:
4211         kvm_arch_exit();
4212 out_fail:
4213         return r;
4214 }
4215 EXPORT_SYMBOL_GPL(kvm_init);
4216
4217 void kvm_exit(void)
4218 {
4219         debugfs_remove_recursive(kvm_debugfs_dir);
4220         misc_deregister(&kvm_dev);
4221         kmem_cache_destroy(kvm_vcpu_cache);
4222         kvm_async_pf_deinit();
4223         unregister_syscore_ops(&kvm_syscore_ops);
4224         unregister_reboot_notifier(&kvm_reboot_notifier);
4225         cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
4226         on_each_cpu(hardware_disable_nolock, NULL, 1);
4227         kvm_arch_hardware_unsetup();
4228         kvm_arch_exit();
4229         kvm_irqfd_exit();
4230         free_cpumask_var(cpus_hardware_enabled);
4231         kvm_vfio_ops_exit();
4232 }
4233 EXPORT_SYMBOL_GPL(kvm_exit);
4234
4235 struct kvm_vm_worker_thread_context {
4236         struct kvm *kvm;
4237         struct task_struct *parent;
4238         struct completion init_done;
4239         kvm_vm_thread_fn_t thread_fn;
4240         uintptr_t data;
4241         int err;
4242 };
4243
4244 static int kvm_vm_worker_thread(void *context)
4245 {
4246         /*
4247          * The init_context is allocated on the stack of the parent thread, so
4248          * we have to locally copy anything that is needed beyond initialization
4249          */
4250         struct kvm_vm_worker_thread_context *init_context = context;
4251         struct kvm *kvm = init_context->kvm;
4252         kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
4253         uintptr_t data = init_context->data;
4254         int err;
4255
4256         err = kthread_park(current);
4257         /* kthread_park(current) is never supposed to return an error */
4258         WARN_ON(err != 0);
4259         if (err)
4260                 goto init_complete;
4261
4262         err = cgroup_attach_task_all(init_context->parent, current);
4263         if (err) {
4264                 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
4265                         __func__, err);
4266                 goto init_complete;
4267         }
4268
4269         set_user_nice(current, task_nice(init_context->parent));
4270
4271 init_complete:
4272         init_context->err = err;
4273         complete(&init_context->init_done);
4274         init_context = NULL;
4275
4276         if (err)
4277                 return err;
4278
4279         /* Wait to be woken up by the spawner before proceeding. */
4280         kthread_parkme();
4281
4282         if (!kthread_should_stop())
4283                 err = thread_fn(kvm, data);
4284
4285         return err;
4286 }
4287
4288 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
4289                                 uintptr_t data, const char *name,
4290                                 struct task_struct **thread_ptr)
4291 {
4292         struct kvm_vm_worker_thread_context init_context = {};
4293         struct task_struct *thread;
4294
4295         *thread_ptr = NULL;
4296         init_context.kvm = kvm;
4297         init_context.parent = current;
4298         init_context.thread_fn = thread_fn;
4299         init_context.data = data;
4300         init_completion(&init_context.init_done);
4301
4302         thread = kthread_run(kvm_vm_worker_thread, &init_context,
4303                              "%s-%d", name, task_pid_nr(current));
4304         if (IS_ERR(thread))
4305                 return PTR_ERR(thread);
4306
4307         /* kthread_run is never supposed to return NULL */
4308         WARN_ON(thread == NULL);
4309
4310         wait_for_completion(&init_context.init_done);
4311
4312         if (!init_context.err)
4313                 *thread_ptr = thread;
4314
4315         return init_context.err;
4316 }