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