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