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