OSDN Git Service

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