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