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