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