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