KVM: fix build warning within __kvm_set_memory_region() on s390
[linux-2.6.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/sysdev.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
51 #include <asm/processor.h>
52 #include <asm/io.h>
53 #include <asm/uaccess.h>
54 #include <asm/pgtable.h>
55 #include <asm-generic/bitops/le.h>
56
57 #include "coalesced_mmio.h"
58 #include "async_pf.h"
59
60 #define CREATE_TRACE_POINTS
61 #include <trace/events/kvm.h>
62
63 MODULE_AUTHOR("Qumranet");
64 MODULE_LICENSE("GPL");
65
66 /*
67  * Ordering of locks:
68  *
69  *              kvm->lock --> kvm->slots_lock --> kvm->irq_lock
70  */
71
72 DEFINE_SPINLOCK(kvm_lock);
73 LIST_HEAD(vm_list);
74
75 static cpumask_var_t cpus_hardware_enabled;
76 static int kvm_usage_count = 0;
77 static atomic_t hardware_enable_failed;
78
79 struct kmem_cache *kvm_vcpu_cache;
80 EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
81
82 static __read_mostly struct preempt_ops kvm_preempt_ops;
83
84 struct dentry *kvm_debugfs_dir;
85
86 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
87                            unsigned long arg);
88 static int hardware_enable_all(void);
89 static void hardware_disable_all(void);
90
91 static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
92
93 bool kvm_rebooting;
94 EXPORT_SYMBOL_GPL(kvm_rebooting);
95
96 static bool largepages_enabled = true;
97
98 static struct page *hwpoison_page;
99 static pfn_t hwpoison_pfn;
100
101 static struct page *fault_page;
102 static pfn_t fault_pfn;
103
104 inline int kvm_is_mmio_pfn(pfn_t pfn)
105 {
106         if (pfn_valid(pfn)) {
107                 int reserved;
108                 struct page *tail = pfn_to_page(pfn);
109                 struct page *head = compound_trans_head(tail);
110                 reserved = PageReserved(head);
111                 if (head != tail) {
112                         /*
113                          * "head" is not a dangling pointer
114                          * (compound_trans_head takes care of that)
115                          * but the hugepage may have been splitted
116                          * from under us (and we may not hold a
117                          * reference count on the head page so it can
118                          * be reused before we run PageReferenced), so
119                          * we've to check PageTail before returning
120                          * what we just read.
121                          */
122                         smp_rmb();
123                         if (PageTail(tail))
124                                 return reserved;
125                 }
126                 return PageReserved(tail);
127         }
128
129         return true;
130 }
131
132 /*
133  * Switches to specified vcpu, until a matching vcpu_put()
134  */
135 void vcpu_load(struct kvm_vcpu *vcpu)
136 {
137         int cpu;
138
139         mutex_lock(&vcpu->mutex);
140         cpu = get_cpu();
141         preempt_notifier_register(&vcpu->preempt_notifier);
142         kvm_arch_vcpu_load(vcpu, cpu);
143         put_cpu();
144 }
145
146 void vcpu_put(struct kvm_vcpu *vcpu)
147 {
148         preempt_disable();
149         kvm_arch_vcpu_put(vcpu);
150         preempt_notifier_unregister(&vcpu->preempt_notifier);
151         preempt_enable();
152         mutex_unlock(&vcpu->mutex);
153 }
154
155 static void ack_flush(void *_completed)
156 {
157 }
158
159 static bool make_all_cpus_request(struct kvm *kvm, unsigned int req)
160 {
161         int i, cpu, me;
162         cpumask_var_t cpus;
163         bool called = true;
164         struct kvm_vcpu *vcpu;
165
166         zalloc_cpumask_var(&cpus, GFP_ATOMIC);
167
168         raw_spin_lock(&kvm->requests_lock);
169         me = smp_processor_id();
170         kvm_for_each_vcpu(i, vcpu, kvm) {
171                 if (kvm_make_check_request(req, vcpu))
172                         continue;
173                 cpu = vcpu->cpu;
174                 if (cpus != NULL && cpu != -1 && cpu != me)
175                         cpumask_set_cpu(cpu, cpus);
176         }
177         if (unlikely(cpus == NULL))
178                 smp_call_function_many(cpu_online_mask, ack_flush, NULL, 1);
179         else if (!cpumask_empty(cpus))
180                 smp_call_function_many(cpus, ack_flush, NULL, 1);
181         else
182                 called = false;
183         raw_spin_unlock(&kvm->requests_lock);
184         free_cpumask_var(cpus);
185         return called;
186 }
187
188 void kvm_flush_remote_tlbs(struct kvm *kvm)
189 {
190         int dirty_count = kvm->tlbs_dirty;
191
192         smp_mb();
193         if (make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
194                 ++kvm->stat.remote_tlb_flush;
195         cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
196 }
197
198 void kvm_reload_remote_mmus(struct kvm *kvm)
199 {
200         make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
201 }
202
203 int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
204 {
205         struct page *page;
206         int r;
207
208         mutex_init(&vcpu->mutex);
209         vcpu->cpu = -1;
210         vcpu->kvm = kvm;
211         vcpu->vcpu_id = id;
212         init_waitqueue_head(&vcpu->wq);
213         kvm_async_pf_vcpu_init(vcpu);
214
215         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
216         if (!page) {
217                 r = -ENOMEM;
218                 goto fail;
219         }
220         vcpu->run = page_address(page);
221
222         r = kvm_arch_vcpu_init(vcpu);
223         if (r < 0)
224                 goto fail_free_run;
225         return 0;
226
227 fail_free_run:
228         free_page((unsigned long)vcpu->run);
229 fail:
230         return r;
231 }
232 EXPORT_SYMBOL_GPL(kvm_vcpu_init);
233
234 void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
235 {
236         kvm_arch_vcpu_uninit(vcpu);
237         free_page((unsigned long)vcpu->run);
238 }
239 EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
240
241 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
242 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
243 {
244         return container_of(mn, struct kvm, mmu_notifier);
245 }
246
247 static void kvm_mmu_notifier_invalidate_page(struct mmu_notifier *mn,
248                                              struct mm_struct *mm,
249                                              unsigned long address)
250 {
251         struct kvm *kvm = mmu_notifier_to_kvm(mn);
252         int need_tlb_flush, idx;
253
254         /*
255          * When ->invalidate_page runs, the linux pte has been zapped
256          * already but the page is still allocated until
257          * ->invalidate_page returns. So if we increase the sequence
258          * here the kvm page fault will notice if the spte can't be
259          * established because the page is going to be freed. If
260          * instead the kvm page fault establishes the spte before
261          * ->invalidate_page runs, kvm_unmap_hva will release it
262          * before returning.
263          *
264          * The sequence increase only need to be seen at spin_unlock
265          * time, and not at spin_lock time.
266          *
267          * Increasing the sequence after the spin_unlock would be
268          * unsafe because the kvm page fault could then establish the
269          * pte after kvm_unmap_hva returned, without noticing the page
270          * is going to be freed.
271          */
272         idx = srcu_read_lock(&kvm->srcu);
273         spin_lock(&kvm->mmu_lock);
274         kvm->mmu_notifier_seq++;
275         need_tlb_flush = kvm_unmap_hva(kvm, address) | kvm->tlbs_dirty;
276         spin_unlock(&kvm->mmu_lock);
277         srcu_read_unlock(&kvm->srcu, idx);
278
279         /* we've to flush the tlb before the pages can be freed */
280         if (need_tlb_flush)
281                 kvm_flush_remote_tlbs(kvm);
282
283 }
284
285 static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
286                                         struct mm_struct *mm,
287                                         unsigned long address,
288                                         pte_t pte)
289 {
290         struct kvm *kvm = mmu_notifier_to_kvm(mn);
291         int idx;
292
293         idx = srcu_read_lock(&kvm->srcu);
294         spin_lock(&kvm->mmu_lock);
295         kvm->mmu_notifier_seq++;
296         kvm_set_spte_hva(kvm, address, pte);
297         spin_unlock(&kvm->mmu_lock);
298         srcu_read_unlock(&kvm->srcu, idx);
299 }
300
301 static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
302                                                     struct mm_struct *mm,
303                                                     unsigned long start,
304                                                     unsigned long end)
305 {
306         struct kvm *kvm = mmu_notifier_to_kvm(mn);
307         int need_tlb_flush = 0, idx;
308
309         idx = srcu_read_lock(&kvm->srcu);
310         spin_lock(&kvm->mmu_lock);
311         /*
312          * The count increase must become visible at unlock time as no
313          * spte can be established without taking the mmu_lock and
314          * count is also read inside the mmu_lock critical section.
315          */
316         kvm->mmu_notifier_count++;
317         for (; start < end; start += PAGE_SIZE)
318                 need_tlb_flush |= kvm_unmap_hva(kvm, start);
319         need_tlb_flush |= kvm->tlbs_dirty;
320         spin_unlock(&kvm->mmu_lock);
321         srcu_read_unlock(&kvm->srcu, idx);
322
323         /* we've to flush the tlb before the pages can be freed */
324         if (need_tlb_flush)
325                 kvm_flush_remote_tlbs(kvm);
326 }
327
328 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
329                                                   struct mm_struct *mm,
330                                                   unsigned long start,
331                                                   unsigned long end)
332 {
333         struct kvm *kvm = mmu_notifier_to_kvm(mn);
334
335         spin_lock(&kvm->mmu_lock);
336         /*
337          * This sequence increase will notify the kvm page fault that
338          * the page that is going to be mapped in the spte could have
339          * been freed.
340          */
341         kvm->mmu_notifier_seq++;
342         /*
343          * The above sequence increase must be visible before the
344          * below count decrease but both values are read by the kvm
345          * page fault under mmu_lock spinlock so we don't need to add
346          * a smb_wmb() here in between the two.
347          */
348         kvm->mmu_notifier_count--;
349         spin_unlock(&kvm->mmu_lock);
350
351         BUG_ON(kvm->mmu_notifier_count < 0);
352 }
353
354 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
355                                               struct mm_struct *mm,
356                                               unsigned long address)
357 {
358         struct kvm *kvm = mmu_notifier_to_kvm(mn);
359         int young, idx;
360
361         idx = srcu_read_lock(&kvm->srcu);
362         spin_lock(&kvm->mmu_lock);
363         young = kvm_age_hva(kvm, address);
364         spin_unlock(&kvm->mmu_lock);
365         srcu_read_unlock(&kvm->srcu, idx);
366
367         if (young)
368                 kvm_flush_remote_tlbs(kvm);
369
370         return young;
371 }
372
373 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
374                                        struct mm_struct *mm,
375                                        unsigned long address)
376 {
377         struct kvm *kvm = mmu_notifier_to_kvm(mn);
378         int young, idx;
379
380         idx = srcu_read_lock(&kvm->srcu);
381         spin_lock(&kvm->mmu_lock);
382         young = kvm_test_age_hva(kvm, address);
383         spin_unlock(&kvm->mmu_lock);
384         srcu_read_unlock(&kvm->srcu, idx);
385
386         return young;
387 }
388
389 static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
390                                      struct mm_struct *mm)
391 {
392         struct kvm *kvm = mmu_notifier_to_kvm(mn);
393         int idx;
394
395         idx = srcu_read_lock(&kvm->srcu);
396         kvm_arch_flush_shadow(kvm);
397         srcu_read_unlock(&kvm->srcu, idx);
398 }
399
400 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
401         .invalidate_page        = kvm_mmu_notifier_invalidate_page,
402         .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
403         .invalidate_range_end   = kvm_mmu_notifier_invalidate_range_end,
404         .clear_flush_young      = kvm_mmu_notifier_clear_flush_young,
405         .test_young             = kvm_mmu_notifier_test_young,
406         .change_pte             = kvm_mmu_notifier_change_pte,
407         .release                = kvm_mmu_notifier_release,
408 };
409
410 static int kvm_init_mmu_notifier(struct kvm *kvm)
411 {
412         kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
413         return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
414 }
415
416 #else  /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
417
418 static int kvm_init_mmu_notifier(struct kvm *kvm)
419 {
420         return 0;
421 }
422
423 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
424
425 static struct kvm *kvm_create_vm(void)
426 {
427         int r, i;
428         struct kvm *kvm = kvm_arch_alloc_vm();
429
430         if (!kvm)
431                 return ERR_PTR(-ENOMEM);
432
433         r = kvm_arch_init_vm(kvm);
434         if (r)
435                 goto out_err_nodisable;
436
437         r = hardware_enable_all();
438         if (r)
439                 goto out_err_nodisable;
440
441 #ifdef CONFIG_HAVE_KVM_IRQCHIP
442         INIT_HLIST_HEAD(&kvm->mask_notifier_list);
443         INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
444 #endif
445
446         r = -ENOMEM;
447         kvm->memslots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
448         if (!kvm->memslots)
449                 goto out_err_nosrcu;
450         if (init_srcu_struct(&kvm->srcu))
451                 goto out_err_nosrcu;
452         for (i = 0; i < KVM_NR_BUSES; i++) {
453                 kvm->buses[i] = kzalloc(sizeof(struct kvm_io_bus),
454                                         GFP_KERNEL);
455                 if (!kvm->buses[i])
456                         goto out_err;
457         }
458
459         r = kvm_init_mmu_notifier(kvm);
460         if (r)
461                 goto out_err;
462
463         kvm->mm = current->mm;
464         atomic_inc(&kvm->mm->mm_count);
465         spin_lock_init(&kvm->mmu_lock);
466         raw_spin_lock_init(&kvm->requests_lock);
467         kvm_eventfd_init(kvm);
468         mutex_init(&kvm->lock);
469         mutex_init(&kvm->irq_lock);
470         mutex_init(&kvm->slots_lock);
471         atomic_set(&kvm->users_count, 1);
472         spin_lock(&kvm_lock);
473         list_add(&kvm->vm_list, &vm_list);
474         spin_unlock(&kvm_lock);
475
476         return kvm;
477
478 out_err:
479         cleanup_srcu_struct(&kvm->srcu);
480 out_err_nosrcu:
481         hardware_disable_all();
482 out_err_nodisable:
483         for (i = 0; i < KVM_NR_BUSES; i++)
484                 kfree(kvm->buses[i]);
485         kfree(kvm->memslots);
486         kvm_arch_free_vm(kvm);
487         return ERR_PTR(r);
488 }
489
490 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
491 {
492         if (!memslot->dirty_bitmap)
493                 return;
494
495         if (2 * kvm_dirty_bitmap_bytes(memslot) > PAGE_SIZE)
496                 vfree(memslot->dirty_bitmap_head);
497         else
498                 kfree(memslot->dirty_bitmap_head);
499
500         memslot->dirty_bitmap = NULL;
501         memslot->dirty_bitmap_head = NULL;
502 }
503
504 /*
505  * Free any memory in @free but not in @dont.
506  */
507 static void kvm_free_physmem_slot(struct kvm_memory_slot *free,
508                                   struct kvm_memory_slot *dont)
509 {
510         int i;
511
512         if (!dont || free->rmap != dont->rmap)
513                 vfree(free->rmap);
514
515         if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
516                 kvm_destroy_dirty_bitmap(free);
517
518
519         for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) {
520                 if (!dont || free->lpage_info[i] != dont->lpage_info[i]) {
521                         vfree(free->lpage_info[i]);
522                         free->lpage_info[i] = NULL;
523                 }
524         }
525
526         free->npages = 0;
527         free->rmap = NULL;
528 }
529
530 void kvm_free_physmem(struct kvm *kvm)
531 {
532         int i;
533         struct kvm_memslots *slots = kvm->memslots;
534
535         for (i = 0; i < slots->nmemslots; ++i)
536                 kvm_free_physmem_slot(&slots->memslots[i], NULL);
537
538         kfree(kvm->memslots);
539 }
540
541 static void kvm_destroy_vm(struct kvm *kvm)
542 {
543         int i;
544         struct mm_struct *mm = kvm->mm;
545
546         kvm_arch_sync_events(kvm);
547         spin_lock(&kvm_lock);
548         list_del(&kvm->vm_list);
549         spin_unlock(&kvm_lock);
550         kvm_free_irq_routing(kvm);
551         for (i = 0; i < KVM_NR_BUSES; i++)
552                 kvm_io_bus_destroy(kvm->buses[i]);
553         kvm_coalesced_mmio_free(kvm);
554 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
555         mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
556 #else
557         kvm_arch_flush_shadow(kvm);
558 #endif
559         kvm_arch_destroy_vm(kvm);
560         kvm_free_physmem(kvm);
561         cleanup_srcu_struct(&kvm->srcu);
562         kvm_arch_free_vm(kvm);
563         hardware_disable_all();
564         mmdrop(mm);
565 }
566
567 void kvm_get_kvm(struct kvm *kvm)
568 {
569         atomic_inc(&kvm->users_count);
570 }
571 EXPORT_SYMBOL_GPL(kvm_get_kvm);
572
573 void kvm_put_kvm(struct kvm *kvm)
574 {
575         if (atomic_dec_and_test(&kvm->users_count))
576                 kvm_destroy_vm(kvm);
577 }
578 EXPORT_SYMBOL_GPL(kvm_put_kvm);
579
580
581 static int kvm_vm_release(struct inode *inode, struct file *filp)
582 {
583         struct kvm *kvm = filp->private_data;
584
585         kvm_irqfd_release(kvm);
586
587         kvm_put_kvm(kvm);
588         return 0;
589 }
590
591 #ifndef CONFIG_S390
592 /*
593  * Allocation size is twice as large as the actual dirty bitmap size.
594  * This makes it possible to do double buffering: see x86's
595  * kvm_vm_ioctl_get_dirty_log().
596  */
597 static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
598 {
599         unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
600
601         if (dirty_bytes > PAGE_SIZE)
602                 memslot->dirty_bitmap = vzalloc(dirty_bytes);
603         else
604                 memslot->dirty_bitmap = kzalloc(dirty_bytes, GFP_KERNEL);
605
606         if (!memslot->dirty_bitmap)
607                 return -ENOMEM;
608
609         memslot->dirty_bitmap_head = memslot->dirty_bitmap;
610         return 0;
611 }
612 #endif /* !CONFIG_S390 */
613
614 /*
615  * Allocate some memory and give it an address in the guest physical address
616  * space.
617  *
618  * Discontiguous memory is allowed, mostly for framebuffers.
619  *
620  * Must be called holding mmap_sem for write.
621  */
622 int __kvm_set_memory_region(struct kvm *kvm,
623                             struct kvm_userspace_memory_region *mem,
624                             int user_alloc)
625 {
626         int r;
627         gfn_t base_gfn;
628         unsigned long npages;
629         unsigned long i;
630         struct kvm_memory_slot *memslot;
631         struct kvm_memory_slot old, new;
632         struct kvm_memslots *slots, *old_memslots;
633
634         r = -EINVAL;
635         /* General sanity checks */
636         if (mem->memory_size & (PAGE_SIZE - 1))
637                 goto out;
638         if (mem->guest_phys_addr & (PAGE_SIZE - 1))
639                 goto out;
640         if (user_alloc && (mem->userspace_addr & (PAGE_SIZE - 1)))
641                 goto out;
642         if (mem->slot >= KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS)
643                 goto out;
644         if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
645                 goto out;
646
647         memslot = &kvm->memslots->memslots[mem->slot];
648         base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
649         npages = mem->memory_size >> PAGE_SHIFT;
650
651         r = -EINVAL;
652         if (npages > KVM_MEM_MAX_NR_PAGES)
653                 goto out;
654
655         if (!npages)
656                 mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
657
658         new = old = *memslot;
659
660         new.id = mem->slot;
661         new.base_gfn = base_gfn;
662         new.npages = npages;
663         new.flags = mem->flags;
664
665         /* Disallow changing a memory slot's size. */
666         r = -EINVAL;
667         if (npages && old.npages && npages != old.npages)
668                 goto out_free;
669
670         /* Check for overlaps */
671         r = -EEXIST;
672         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
673                 struct kvm_memory_slot *s = &kvm->memslots->memslots[i];
674
675                 if (s == memslot || !s->npages)
676                         continue;
677                 if (!((base_gfn + npages <= s->base_gfn) ||
678                       (base_gfn >= s->base_gfn + s->npages)))
679                         goto out_free;
680         }
681
682         /* Free page dirty bitmap if unneeded */
683         if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
684                 new.dirty_bitmap = NULL;
685
686         r = -ENOMEM;
687
688         /* Allocate if a slot is being created */
689 #ifndef CONFIG_S390
690         if (npages && !new.rmap) {
691                 new.rmap = vzalloc(npages * sizeof(*new.rmap));
692
693                 if (!new.rmap)
694                         goto out_free;
695
696                 new.user_alloc = user_alloc;
697                 new.userspace_addr = mem->userspace_addr;
698         }
699         if (!npages)
700                 goto skip_lpage;
701
702         for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) {
703                 unsigned long ugfn;
704                 unsigned long j;
705                 int lpages;
706                 int level = i + 2;
707
708                 /* Avoid unused variable warning if no large pages */
709                 (void)level;
710
711                 if (new.lpage_info[i])
712                         continue;
713
714                 lpages = 1 + ((base_gfn + npages - 1)
715                              >> KVM_HPAGE_GFN_SHIFT(level));
716                 lpages -= base_gfn >> KVM_HPAGE_GFN_SHIFT(level);
717
718                 new.lpage_info[i] = vzalloc(lpages * sizeof(*new.lpage_info[i]));
719
720                 if (!new.lpage_info[i])
721                         goto out_free;
722
723                 if (base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
724                         new.lpage_info[i][0].write_count = 1;
725                 if ((base_gfn+npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
726                         new.lpage_info[i][lpages - 1].write_count = 1;
727                 ugfn = new.userspace_addr >> PAGE_SHIFT;
728                 /*
729                  * If the gfn and userspace address are not aligned wrt each
730                  * other, or if explicitly asked to, disable large page
731                  * support for this slot
732                  */
733                 if ((base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
734                     !largepages_enabled)
735                         for (j = 0; j < lpages; ++j)
736                                 new.lpage_info[i][j].write_count = 1;
737         }
738
739 skip_lpage:
740
741         /* Allocate page dirty bitmap if needed */
742         if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
743                 if (kvm_create_dirty_bitmap(&new) < 0)
744                         goto out_free;
745                 /* destroy any largepage mappings for dirty tracking */
746         }
747 #else  /* not defined CONFIG_S390 */
748         new.user_alloc = user_alloc;
749         if (user_alloc)
750                 new.userspace_addr = mem->userspace_addr;
751 #endif /* not defined CONFIG_S390 */
752
753         if (!npages) {
754                 r = -ENOMEM;
755                 slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
756                 if (!slots)
757                         goto out_free;
758                 memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
759                 if (mem->slot >= slots->nmemslots)
760                         slots->nmemslots = mem->slot + 1;
761                 slots->generation++;
762                 slots->memslots[mem->slot].flags |= KVM_MEMSLOT_INVALID;
763
764                 old_memslots = kvm->memslots;
765                 rcu_assign_pointer(kvm->memslots, slots);
766                 synchronize_srcu_expedited(&kvm->srcu);
767                 /* From this point no new shadow pages pointing to a deleted
768                  * memslot will be created.
769                  *
770                  * validation of sp->gfn happens in:
771                  *      - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
772                  *      - kvm_is_visible_gfn (mmu_check_roots)
773                  */
774                 kvm_arch_flush_shadow(kvm);
775                 kfree(old_memslots);
776         }
777
778         r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc);
779         if (r)
780                 goto out_free;
781
782         /* map the pages in iommu page table */
783         if (npages) {
784                 r = kvm_iommu_map_pages(kvm, &new);
785                 if (r)
786                         goto out_free;
787         }
788
789         r = -ENOMEM;
790         slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
791         if (!slots)
792                 goto out_free;
793         memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
794         if (mem->slot >= slots->nmemslots)
795                 slots->nmemslots = mem->slot + 1;
796         slots->generation++;
797
798         /* actual memory is freed via old in kvm_free_physmem_slot below */
799         if (!npages) {
800                 new.rmap = NULL;
801                 new.dirty_bitmap = NULL;
802                 for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i)
803                         new.lpage_info[i] = NULL;
804         }
805
806         slots->memslots[mem->slot] = new;
807         old_memslots = kvm->memslots;
808         rcu_assign_pointer(kvm->memslots, slots);
809         synchronize_srcu_expedited(&kvm->srcu);
810
811         kvm_arch_commit_memory_region(kvm, mem, old, user_alloc);
812
813         kvm_free_physmem_slot(&old, &new);
814         kfree(old_memslots);
815
816         return 0;
817
818 out_free:
819         kvm_free_physmem_slot(&new, &old);
820 out:
821         return r;
822
823 }
824 EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
825
826 int kvm_set_memory_region(struct kvm *kvm,
827                           struct kvm_userspace_memory_region *mem,
828                           int user_alloc)
829 {
830         int r;
831
832         mutex_lock(&kvm->slots_lock);
833         r = __kvm_set_memory_region(kvm, mem, user_alloc);
834         mutex_unlock(&kvm->slots_lock);
835         return r;
836 }
837 EXPORT_SYMBOL_GPL(kvm_set_memory_region);
838
839 int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
840                                    struct
841                                    kvm_userspace_memory_region *mem,
842                                    int user_alloc)
843 {
844         if (mem->slot >= KVM_MEMORY_SLOTS)
845                 return -EINVAL;
846         return kvm_set_memory_region(kvm, mem, user_alloc);
847 }
848
849 int kvm_get_dirty_log(struct kvm *kvm,
850                         struct kvm_dirty_log *log, int *is_dirty)
851 {
852         struct kvm_memory_slot *memslot;
853         int r, i;
854         unsigned long n;
855         unsigned long any = 0;
856
857         r = -EINVAL;
858         if (log->slot >= KVM_MEMORY_SLOTS)
859                 goto out;
860
861         memslot = &kvm->memslots->memslots[log->slot];
862         r = -ENOENT;
863         if (!memslot->dirty_bitmap)
864                 goto out;
865
866         n = kvm_dirty_bitmap_bytes(memslot);
867
868         for (i = 0; !any && i < n/sizeof(long); ++i)
869                 any = memslot->dirty_bitmap[i];
870
871         r = -EFAULT;
872         if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
873                 goto out;
874
875         if (any)
876                 *is_dirty = 1;
877
878         r = 0;
879 out:
880         return r;
881 }
882
883 void kvm_disable_largepages(void)
884 {
885         largepages_enabled = false;
886 }
887 EXPORT_SYMBOL_GPL(kvm_disable_largepages);
888
889 int is_error_page(struct page *page)
890 {
891         return page == bad_page || page == hwpoison_page || page == fault_page;
892 }
893 EXPORT_SYMBOL_GPL(is_error_page);
894
895 int is_error_pfn(pfn_t pfn)
896 {
897         return pfn == bad_pfn || pfn == hwpoison_pfn || pfn == fault_pfn;
898 }
899 EXPORT_SYMBOL_GPL(is_error_pfn);
900
901 int is_hwpoison_pfn(pfn_t pfn)
902 {
903         return pfn == hwpoison_pfn;
904 }
905 EXPORT_SYMBOL_GPL(is_hwpoison_pfn);
906
907 int is_fault_pfn(pfn_t pfn)
908 {
909         return pfn == fault_pfn;
910 }
911 EXPORT_SYMBOL_GPL(is_fault_pfn);
912
913 static inline unsigned long bad_hva(void)
914 {
915         return PAGE_OFFSET;
916 }
917
918 int kvm_is_error_hva(unsigned long addr)
919 {
920         return addr == bad_hva();
921 }
922 EXPORT_SYMBOL_GPL(kvm_is_error_hva);
923
924 static struct kvm_memory_slot *__gfn_to_memslot(struct kvm_memslots *slots,
925                                                 gfn_t gfn)
926 {
927         int i;
928
929         for (i = 0; i < slots->nmemslots; ++i) {
930                 struct kvm_memory_slot *memslot = &slots->memslots[i];
931
932                 if (gfn >= memslot->base_gfn
933                     && gfn < memslot->base_gfn + memslot->npages)
934                         return memslot;
935         }
936         return NULL;
937 }
938
939 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
940 {
941         return __gfn_to_memslot(kvm_memslots(kvm), gfn);
942 }
943 EXPORT_SYMBOL_GPL(gfn_to_memslot);
944
945 int kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
946 {
947         int i;
948         struct kvm_memslots *slots = kvm_memslots(kvm);
949
950         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
951                 struct kvm_memory_slot *memslot = &slots->memslots[i];
952
953                 if (memslot->flags & KVM_MEMSLOT_INVALID)
954                         continue;
955
956                 if (gfn >= memslot->base_gfn
957                     && gfn < memslot->base_gfn + memslot->npages)
958                         return 1;
959         }
960         return 0;
961 }
962 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
963
964 unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn)
965 {
966         struct vm_area_struct *vma;
967         unsigned long addr, size;
968
969         size = PAGE_SIZE;
970
971         addr = gfn_to_hva(kvm, gfn);
972         if (kvm_is_error_hva(addr))
973                 return PAGE_SIZE;
974
975         down_read(&current->mm->mmap_sem);
976         vma = find_vma(current->mm, addr);
977         if (!vma)
978                 goto out;
979
980         size = vma_kernel_pagesize(vma);
981
982 out:
983         up_read(&current->mm->mmap_sem);
984
985         return size;
986 }
987
988 int memslot_id(struct kvm *kvm, gfn_t gfn)
989 {
990         int i;
991         struct kvm_memslots *slots = kvm_memslots(kvm);
992         struct kvm_memory_slot *memslot = NULL;
993
994         for (i = 0; i < slots->nmemslots; ++i) {
995                 memslot = &slots->memslots[i];
996
997                 if (gfn >= memslot->base_gfn
998                     && gfn < memslot->base_gfn + memslot->npages)
999                         break;
1000         }
1001
1002         return memslot - slots->memslots;
1003 }
1004
1005 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1006                                      gfn_t *nr_pages)
1007 {
1008         if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1009                 return bad_hva();
1010
1011         if (nr_pages)
1012                 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1013
1014         return gfn_to_hva_memslot(slot, gfn);
1015 }
1016
1017 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1018 {
1019         return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1020 }
1021 EXPORT_SYMBOL_GPL(gfn_to_hva);
1022
1023 static pfn_t get_fault_pfn(void)
1024 {
1025         get_page(fault_page);
1026         return fault_pfn;
1027 }
1028
1029 static pfn_t hva_to_pfn(struct kvm *kvm, unsigned long addr, bool atomic,
1030                         bool *async, bool write_fault, bool *writable)
1031 {
1032         struct page *page[1];
1033         int npages = 0;
1034         pfn_t pfn;
1035
1036         /* we can do it either atomically or asynchronously, not both */
1037         BUG_ON(atomic && async);
1038
1039         BUG_ON(!write_fault && !writable);
1040
1041         if (writable)
1042                 *writable = true;
1043
1044         if (atomic || async)
1045                 npages = __get_user_pages_fast(addr, 1, 1, page);
1046
1047         if (unlikely(npages != 1) && !atomic) {
1048                 might_sleep();
1049
1050                 if (writable)
1051                         *writable = write_fault;
1052
1053                 npages = get_user_pages_fast(addr, 1, write_fault, page);
1054
1055                 /* map read fault as writable if possible */
1056                 if (unlikely(!write_fault) && npages == 1) {
1057                         struct page *wpage[1];
1058
1059                         npages = __get_user_pages_fast(addr, 1, 1, wpage);
1060                         if (npages == 1) {
1061                                 *writable = true;
1062                                 put_page(page[0]);
1063                                 page[0] = wpage[0];
1064                         }
1065                         npages = 1;
1066                 }
1067         }
1068
1069         if (unlikely(npages != 1)) {
1070                 struct vm_area_struct *vma;
1071
1072                 if (atomic)
1073                         return get_fault_pfn();
1074
1075                 down_read(&current->mm->mmap_sem);
1076                 if (is_hwpoison_address(addr)) {
1077                         up_read(&current->mm->mmap_sem);
1078                         get_page(hwpoison_page);
1079                         return page_to_pfn(hwpoison_page);
1080                 }
1081
1082                 vma = find_vma_intersection(current->mm, addr, addr+1);
1083
1084                 if (vma == NULL)
1085                         pfn = get_fault_pfn();
1086                 else if ((vma->vm_flags & VM_PFNMAP)) {
1087                         pfn = ((addr - vma->vm_start) >> PAGE_SHIFT) +
1088                                 vma->vm_pgoff;
1089                         BUG_ON(!kvm_is_mmio_pfn(pfn));
1090                 } else {
1091                         if (async && (vma->vm_flags & VM_WRITE))
1092                                 *async = true;
1093                         pfn = get_fault_pfn();
1094                 }
1095                 up_read(&current->mm->mmap_sem);
1096         } else
1097                 pfn = page_to_pfn(page[0]);
1098
1099         return pfn;
1100 }
1101
1102 pfn_t hva_to_pfn_atomic(struct kvm *kvm, unsigned long addr)
1103 {
1104         return hva_to_pfn(kvm, addr, true, NULL, true, NULL);
1105 }
1106 EXPORT_SYMBOL_GPL(hva_to_pfn_atomic);
1107
1108 static pfn_t __gfn_to_pfn(struct kvm *kvm, gfn_t gfn, bool atomic, bool *async,
1109                           bool write_fault, bool *writable)
1110 {
1111         unsigned long addr;
1112
1113         if (async)
1114                 *async = false;
1115
1116         addr = gfn_to_hva(kvm, gfn);
1117         if (kvm_is_error_hva(addr)) {
1118                 get_page(bad_page);
1119                 return page_to_pfn(bad_page);
1120         }
1121
1122         return hva_to_pfn(kvm, addr, atomic, async, write_fault, writable);
1123 }
1124
1125 pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
1126 {
1127         return __gfn_to_pfn(kvm, gfn, true, NULL, true, NULL);
1128 }
1129 EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
1130
1131 pfn_t gfn_to_pfn_async(struct kvm *kvm, gfn_t gfn, bool *async,
1132                        bool write_fault, bool *writable)
1133 {
1134         return __gfn_to_pfn(kvm, gfn, false, async, write_fault, writable);
1135 }
1136 EXPORT_SYMBOL_GPL(gfn_to_pfn_async);
1137
1138 pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1139 {
1140         return __gfn_to_pfn(kvm, gfn, false, NULL, true, NULL);
1141 }
1142 EXPORT_SYMBOL_GPL(gfn_to_pfn);
1143
1144 pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
1145                       bool *writable)
1146 {
1147         return __gfn_to_pfn(kvm, gfn, false, NULL, write_fault, writable);
1148 }
1149 EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1150
1151 pfn_t gfn_to_pfn_memslot(struct kvm *kvm,
1152                          struct kvm_memory_slot *slot, gfn_t gfn)
1153 {
1154         unsigned long addr = gfn_to_hva_memslot(slot, gfn);
1155         return hva_to_pfn(kvm, addr, false, NULL, true, NULL);
1156 }
1157
1158 int gfn_to_page_many_atomic(struct kvm *kvm, gfn_t gfn, struct page **pages,
1159                                                                   int nr_pages)
1160 {
1161         unsigned long addr;
1162         gfn_t entry;
1163
1164         addr = gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, &entry);
1165         if (kvm_is_error_hva(addr))
1166                 return -1;
1167
1168         if (entry < nr_pages)
1169                 return 0;
1170
1171         return __get_user_pages_fast(addr, nr_pages, 1, pages);
1172 }
1173 EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
1174
1175 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1176 {
1177         pfn_t pfn;
1178
1179         pfn = gfn_to_pfn(kvm, gfn);
1180         if (!kvm_is_mmio_pfn(pfn))
1181                 return pfn_to_page(pfn);
1182
1183         WARN_ON(kvm_is_mmio_pfn(pfn));
1184
1185         get_page(bad_page);
1186         return bad_page;
1187 }
1188
1189 EXPORT_SYMBOL_GPL(gfn_to_page);
1190
1191 void kvm_release_page_clean(struct page *page)
1192 {
1193         kvm_release_pfn_clean(page_to_pfn(page));
1194 }
1195 EXPORT_SYMBOL_GPL(kvm_release_page_clean);
1196
1197 void kvm_release_pfn_clean(pfn_t pfn)
1198 {
1199         if (!kvm_is_mmio_pfn(pfn))
1200                 put_page(pfn_to_page(pfn));
1201 }
1202 EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
1203
1204 void kvm_release_page_dirty(struct page *page)
1205 {
1206         kvm_release_pfn_dirty(page_to_pfn(page));
1207 }
1208 EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
1209
1210 void kvm_release_pfn_dirty(pfn_t pfn)
1211 {
1212         kvm_set_pfn_dirty(pfn);
1213         kvm_release_pfn_clean(pfn);
1214 }
1215 EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
1216
1217 void kvm_set_page_dirty(struct page *page)
1218 {
1219         kvm_set_pfn_dirty(page_to_pfn(page));
1220 }
1221 EXPORT_SYMBOL_GPL(kvm_set_page_dirty);
1222
1223 void kvm_set_pfn_dirty(pfn_t pfn)
1224 {
1225         if (!kvm_is_mmio_pfn(pfn)) {
1226                 struct page *page = pfn_to_page(pfn);
1227                 if (!PageReserved(page))
1228                         SetPageDirty(page);
1229         }
1230 }
1231 EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
1232
1233 void kvm_set_pfn_accessed(pfn_t pfn)
1234 {
1235         if (!kvm_is_mmio_pfn(pfn))
1236                 mark_page_accessed(pfn_to_page(pfn));
1237 }
1238 EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
1239
1240 void kvm_get_pfn(pfn_t pfn)
1241 {
1242         if (!kvm_is_mmio_pfn(pfn))
1243                 get_page(pfn_to_page(pfn));
1244 }
1245 EXPORT_SYMBOL_GPL(kvm_get_pfn);
1246
1247 static int next_segment(unsigned long len, int offset)
1248 {
1249         if (len > PAGE_SIZE - offset)
1250                 return PAGE_SIZE - offset;
1251         else
1252                 return len;
1253 }
1254
1255 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1256                         int len)
1257 {
1258         int r;
1259         unsigned long addr;
1260
1261         addr = gfn_to_hva(kvm, gfn);
1262         if (kvm_is_error_hva(addr))
1263                 return -EFAULT;
1264         r = copy_from_user(data, (void __user *)addr + offset, len);
1265         if (r)
1266                 return -EFAULT;
1267         return 0;
1268 }
1269 EXPORT_SYMBOL_GPL(kvm_read_guest_page);
1270
1271 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
1272 {
1273         gfn_t gfn = gpa >> PAGE_SHIFT;
1274         int seg;
1275         int offset = offset_in_page(gpa);
1276         int ret;
1277
1278         while ((seg = next_segment(len, offset)) != 0) {
1279                 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
1280                 if (ret < 0)
1281                         return ret;
1282                 offset = 0;
1283                 len -= seg;
1284                 data += seg;
1285                 ++gfn;
1286         }
1287         return 0;
1288 }
1289 EXPORT_SYMBOL_GPL(kvm_read_guest);
1290
1291 int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
1292                           unsigned long len)
1293 {
1294         int r;
1295         unsigned long addr;
1296         gfn_t gfn = gpa >> PAGE_SHIFT;
1297         int offset = offset_in_page(gpa);
1298
1299         addr = gfn_to_hva(kvm, gfn);
1300         if (kvm_is_error_hva(addr))
1301                 return -EFAULT;
1302         pagefault_disable();
1303         r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
1304         pagefault_enable();
1305         if (r)
1306                 return -EFAULT;
1307         return 0;
1308 }
1309 EXPORT_SYMBOL(kvm_read_guest_atomic);
1310
1311 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
1312                          int offset, int len)
1313 {
1314         int r;
1315         unsigned long addr;
1316
1317         addr = gfn_to_hva(kvm, gfn);
1318         if (kvm_is_error_hva(addr))
1319                 return -EFAULT;
1320         r = copy_to_user((void __user *)addr + offset, data, len);
1321         if (r)
1322                 return -EFAULT;
1323         mark_page_dirty(kvm, gfn);
1324         return 0;
1325 }
1326 EXPORT_SYMBOL_GPL(kvm_write_guest_page);
1327
1328 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
1329                     unsigned long len)
1330 {
1331         gfn_t gfn = gpa >> PAGE_SHIFT;
1332         int seg;
1333         int offset = offset_in_page(gpa);
1334         int ret;
1335
1336         while ((seg = next_segment(len, offset)) != 0) {
1337                 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
1338                 if (ret < 0)
1339                         return ret;
1340                 offset = 0;
1341                 len -= seg;
1342                 data += seg;
1343                 ++gfn;
1344         }
1345         return 0;
1346 }
1347
1348 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1349                               gpa_t gpa)
1350 {
1351         struct kvm_memslots *slots = kvm_memslots(kvm);
1352         int offset = offset_in_page(gpa);
1353         gfn_t gfn = gpa >> PAGE_SHIFT;
1354
1355         ghc->gpa = gpa;
1356         ghc->generation = slots->generation;
1357         ghc->memslot = __gfn_to_memslot(slots, gfn);
1358         ghc->hva = gfn_to_hva_many(ghc->memslot, gfn, NULL);
1359         if (!kvm_is_error_hva(ghc->hva))
1360                 ghc->hva += offset;
1361         else
1362                 return -EFAULT;
1363
1364         return 0;
1365 }
1366 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
1367
1368 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1369                            void *data, unsigned long len)
1370 {
1371         struct kvm_memslots *slots = kvm_memslots(kvm);
1372         int r;
1373
1374         if (slots->generation != ghc->generation)
1375                 kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa);
1376
1377         if (kvm_is_error_hva(ghc->hva))
1378                 return -EFAULT;
1379
1380         r = copy_to_user((void __user *)ghc->hva, data, len);
1381         if (r)
1382                 return -EFAULT;
1383         mark_page_dirty_in_slot(kvm, ghc->memslot, ghc->gpa >> PAGE_SHIFT);
1384
1385         return 0;
1386 }
1387 EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
1388
1389 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
1390 {
1391         return kvm_write_guest_page(kvm, gfn, (const void *) empty_zero_page,
1392                                     offset, len);
1393 }
1394 EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
1395
1396 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
1397 {
1398         gfn_t gfn = gpa >> PAGE_SHIFT;
1399         int seg;
1400         int offset = offset_in_page(gpa);
1401         int ret;
1402
1403         while ((seg = next_segment(len, offset)) != 0) {
1404                 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
1405                 if (ret < 0)
1406                         return ret;
1407                 offset = 0;
1408                 len -= seg;
1409                 ++gfn;
1410         }
1411         return 0;
1412 }
1413 EXPORT_SYMBOL_GPL(kvm_clear_guest);
1414
1415 void mark_page_dirty_in_slot(struct kvm *kvm, struct kvm_memory_slot *memslot,
1416                              gfn_t gfn)
1417 {
1418         if (memslot && memslot->dirty_bitmap) {
1419                 unsigned long rel_gfn = gfn - memslot->base_gfn;
1420
1421                 generic___set_le_bit(rel_gfn, memslot->dirty_bitmap);
1422         }
1423 }
1424
1425 void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
1426 {
1427         struct kvm_memory_slot *memslot;
1428
1429         memslot = gfn_to_memslot(kvm, gfn);
1430         mark_page_dirty_in_slot(kvm, memslot, gfn);
1431 }
1432
1433 /*
1434  * The vCPU has executed a HLT instruction with in-kernel mode enabled.
1435  */
1436 void kvm_vcpu_block(struct kvm_vcpu *vcpu)
1437 {
1438         DEFINE_WAIT(wait);
1439
1440         for (;;) {
1441                 prepare_to_wait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
1442
1443                 if (kvm_arch_vcpu_runnable(vcpu)) {
1444                         kvm_make_request(KVM_REQ_UNHALT, vcpu);
1445                         break;
1446                 }
1447                 if (kvm_cpu_has_pending_timer(vcpu))
1448                         break;
1449                 if (signal_pending(current))
1450                         break;
1451
1452                 schedule();
1453         }
1454
1455         finish_wait(&vcpu->wq, &wait);
1456 }
1457
1458 void kvm_resched(struct kvm_vcpu *vcpu)
1459 {
1460         if (!need_resched())
1461                 return;
1462         cond_resched();
1463 }
1464 EXPORT_SYMBOL_GPL(kvm_resched);
1465
1466 void kvm_vcpu_on_spin(struct kvm_vcpu *vcpu)
1467 {
1468         ktime_t expires;
1469         DEFINE_WAIT(wait);
1470
1471         prepare_to_wait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
1472
1473         /* Sleep for 100 us, and hope lock-holder got scheduled */
1474         expires = ktime_add_ns(ktime_get(), 100000UL);
1475         schedule_hrtimeout(&expires, HRTIMER_MODE_ABS);
1476
1477         finish_wait(&vcpu->wq, &wait);
1478 }
1479 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
1480
1481 static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1482 {
1483         struct kvm_vcpu *vcpu = vma->vm_file->private_data;
1484         struct page *page;
1485
1486         if (vmf->pgoff == 0)
1487                 page = virt_to_page(vcpu->run);
1488 #ifdef CONFIG_X86
1489         else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
1490                 page = virt_to_page(vcpu->arch.pio_data);
1491 #endif
1492 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
1493         else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
1494                 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
1495 #endif
1496         else
1497                 return VM_FAULT_SIGBUS;
1498         get_page(page);
1499         vmf->page = page;
1500         return 0;
1501 }
1502
1503 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
1504         .fault = kvm_vcpu_fault,
1505 };
1506
1507 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
1508 {
1509         vma->vm_ops = &kvm_vcpu_vm_ops;
1510         return 0;
1511 }
1512
1513 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
1514 {
1515         struct kvm_vcpu *vcpu = filp->private_data;
1516
1517         kvm_put_kvm(vcpu->kvm);
1518         return 0;
1519 }
1520
1521 static struct file_operations kvm_vcpu_fops = {
1522         .release        = kvm_vcpu_release,
1523         .unlocked_ioctl = kvm_vcpu_ioctl,
1524         .compat_ioctl   = kvm_vcpu_ioctl,
1525         .mmap           = kvm_vcpu_mmap,
1526         .llseek         = noop_llseek,
1527 };
1528
1529 /*
1530  * Allocates an inode for the vcpu.
1531  */
1532 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
1533 {
1534         return anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, O_RDWR);
1535 }
1536
1537 /*
1538  * Creates some virtual cpus.  Good luck creating more than one.
1539  */
1540 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
1541 {
1542         int r;
1543         struct kvm_vcpu *vcpu, *v;
1544
1545         vcpu = kvm_arch_vcpu_create(kvm, id);
1546         if (IS_ERR(vcpu))
1547                 return PTR_ERR(vcpu);
1548
1549         preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
1550
1551         r = kvm_arch_vcpu_setup(vcpu);
1552         if (r)
1553                 return r;
1554
1555         mutex_lock(&kvm->lock);
1556         if (atomic_read(&kvm->online_vcpus) == KVM_MAX_VCPUS) {
1557                 r = -EINVAL;
1558                 goto vcpu_destroy;
1559         }
1560
1561         kvm_for_each_vcpu(r, v, kvm)
1562                 if (v->vcpu_id == id) {
1563                         r = -EEXIST;
1564                         goto vcpu_destroy;
1565                 }
1566
1567         BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
1568
1569         /* Now it's all set up, let userspace reach it */
1570         kvm_get_kvm(kvm);
1571         r = create_vcpu_fd(vcpu);
1572         if (r < 0) {
1573                 kvm_put_kvm(kvm);
1574                 goto vcpu_destroy;
1575         }
1576
1577         kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
1578         smp_wmb();
1579         atomic_inc(&kvm->online_vcpus);
1580
1581 #ifdef CONFIG_KVM_APIC_ARCHITECTURE
1582         if (kvm->bsp_vcpu_id == id)
1583                 kvm->bsp_vcpu = vcpu;
1584 #endif
1585         mutex_unlock(&kvm->lock);
1586         return r;
1587
1588 vcpu_destroy:
1589         mutex_unlock(&kvm->lock);
1590         kvm_arch_vcpu_destroy(vcpu);
1591         return r;
1592 }
1593
1594 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
1595 {
1596         if (sigset) {
1597                 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
1598                 vcpu->sigset_active = 1;
1599                 vcpu->sigset = *sigset;
1600         } else
1601                 vcpu->sigset_active = 0;
1602         return 0;
1603 }
1604
1605 static long kvm_vcpu_ioctl(struct file *filp,
1606                            unsigned int ioctl, unsigned long arg)
1607 {
1608         struct kvm_vcpu *vcpu = filp->private_data;
1609         void __user *argp = (void __user *)arg;
1610         int r;
1611         struct kvm_fpu *fpu = NULL;
1612         struct kvm_sregs *kvm_sregs = NULL;
1613
1614         if (vcpu->kvm->mm != current->mm)
1615                 return -EIO;
1616
1617 #if defined(CONFIG_S390) || defined(CONFIG_PPC)
1618         /*
1619          * Special cases: vcpu ioctls that are asynchronous to vcpu execution,
1620          * so vcpu_load() would break it.
1621          */
1622         if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_INTERRUPT)
1623                 return kvm_arch_vcpu_ioctl(filp, ioctl, arg);
1624 #endif
1625
1626
1627         vcpu_load(vcpu);
1628         switch (ioctl) {
1629         case KVM_RUN:
1630                 r = -EINVAL;
1631                 if (arg)
1632                         goto out;
1633                 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
1634                 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
1635                 break;
1636         case KVM_GET_REGS: {
1637                 struct kvm_regs *kvm_regs;
1638
1639                 r = -ENOMEM;
1640                 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
1641                 if (!kvm_regs)
1642                         goto out;
1643                 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
1644                 if (r)
1645                         goto out_free1;
1646                 r = -EFAULT;
1647                 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
1648                         goto out_free1;
1649                 r = 0;
1650 out_free1:
1651                 kfree(kvm_regs);
1652                 break;
1653         }
1654         case KVM_SET_REGS: {
1655                 struct kvm_regs *kvm_regs;
1656
1657                 r = -ENOMEM;
1658                 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
1659                 if (!kvm_regs)
1660                         goto out;
1661                 r = -EFAULT;
1662                 if (copy_from_user(kvm_regs, argp, sizeof(struct kvm_regs)))
1663                         goto out_free2;
1664                 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
1665                 if (r)
1666                         goto out_free2;
1667                 r = 0;
1668 out_free2:
1669                 kfree(kvm_regs);
1670                 break;
1671         }
1672         case KVM_GET_SREGS: {
1673                 kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
1674                 r = -ENOMEM;
1675                 if (!kvm_sregs)
1676                         goto out;
1677                 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
1678                 if (r)
1679                         goto out;
1680                 r = -EFAULT;
1681                 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
1682                         goto out;
1683                 r = 0;
1684                 break;
1685         }
1686         case KVM_SET_SREGS: {
1687                 kvm_sregs = kmalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
1688                 r = -ENOMEM;
1689                 if (!kvm_sregs)
1690                         goto out;
1691                 r = -EFAULT;
1692                 if (copy_from_user(kvm_sregs, argp, sizeof(struct kvm_sregs)))
1693                         goto out;
1694                 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
1695                 if (r)
1696                         goto out;
1697                 r = 0;
1698                 break;
1699         }
1700         case KVM_GET_MP_STATE: {
1701                 struct kvm_mp_state mp_state;
1702
1703                 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
1704                 if (r)
1705                         goto out;
1706                 r = -EFAULT;
1707                 if (copy_to_user(argp, &mp_state, sizeof mp_state))
1708                         goto out;
1709                 r = 0;
1710                 break;
1711         }
1712         case KVM_SET_MP_STATE: {
1713                 struct kvm_mp_state mp_state;
1714
1715                 r = -EFAULT;
1716                 if (copy_from_user(&mp_state, argp, sizeof mp_state))
1717                         goto out;
1718                 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
1719                 if (r)
1720                         goto out;
1721                 r = 0;
1722                 break;
1723         }
1724         case KVM_TRANSLATE: {
1725                 struct kvm_translation tr;
1726
1727                 r = -EFAULT;
1728                 if (copy_from_user(&tr, argp, sizeof tr))
1729                         goto out;
1730                 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
1731                 if (r)
1732                         goto out;
1733                 r = -EFAULT;
1734                 if (copy_to_user(argp, &tr, sizeof tr))
1735                         goto out;
1736                 r = 0;
1737                 break;
1738         }
1739         case KVM_SET_GUEST_DEBUG: {
1740                 struct kvm_guest_debug dbg;
1741
1742                 r = -EFAULT;
1743                 if (copy_from_user(&dbg, argp, sizeof dbg))
1744                         goto out;
1745                 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
1746                 if (r)
1747                         goto out;
1748                 r = 0;
1749                 break;
1750         }
1751         case KVM_SET_SIGNAL_MASK: {
1752                 struct kvm_signal_mask __user *sigmask_arg = argp;
1753                 struct kvm_signal_mask kvm_sigmask;
1754                 sigset_t sigset, *p;
1755
1756                 p = NULL;
1757                 if (argp) {
1758                         r = -EFAULT;
1759                         if (copy_from_user(&kvm_sigmask, argp,
1760                                            sizeof kvm_sigmask))
1761                                 goto out;
1762                         r = -EINVAL;
1763                         if (kvm_sigmask.len != sizeof sigset)
1764                                 goto out;
1765                         r = -EFAULT;
1766                         if (copy_from_user(&sigset, sigmask_arg->sigset,
1767                                            sizeof sigset))
1768                                 goto out;
1769                         p = &sigset;
1770                 }
1771                 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
1772                 break;
1773         }
1774         case KVM_GET_FPU: {
1775                 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
1776                 r = -ENOMEM;
1777                 if (!fpu)
1778                         goto out;
1779                 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
1780                 if (r)
1781                         goto out;
1782                 r = -EFAULT;
1783                 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
1784                         goto out;
1785                 r = 0;
1786                 break;
1787         }
1788         case KVM_SET_FPU: {
1789                 fpu = kmalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
1790                 r = -ENOMEM;
1791                 if (!fpu)
1792                         goto out;
1793                 r = -EFAULT;
1794                 if (copy_from_user(fpu, argp, sizeof(struct kvm_fpu)))
1795                         goto out;
1796                 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
1797                 if (r)
1798                         goto out;
1799                 r = 0;
1800                 break;
1801         }
1802         default:
1803                 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
1804         }
1805 out:
1806         vcpu_put(vcpu);
1807         kfree(fpu);
1808         kfree(kvm_sregs);
1809         return r;
1810 }
1811
1812 static long kvm_vm_ioctl(struct file *filp,
1813                            unsigned int ioctl, unsigned long arg)
1814 {
1815         struct kvm *kvm = filp->private_data;
1816         void __user *argp = (void __user *)arg;
1817         int r;
1818
1819         if (kvm->mm != current->mm)
1820                 return -EIO;
1821         switch (ioctl) {
1822         case KVM_CREATE_VCPU:
1823                 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
1824                 if (r < 0)
1825                         goto out;
1826                 break;
1827         case KVM_SET_USER_MEMORY_REGION: {
1828                 struct kvm_userspace_memory_region kvm_userspace_mem;
1829
1830                 r = -EFAULT;
1831                 if (copy_from_user(&kvm_userspace_mem, argp,
1832                                                 sizeof kvm_userspace_mem))
1833                         goto out;
1834
1835                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 1);
1836                 if (r)
1837                         goto out;
1838                 break;
1839         }
1840         case KVM_GET_DIRTY_LOG: {
1841                 struct kvm_dirty_log log;
1842
1843                 r = -EFAULT;
1844                 if (copy_from_user(&log, argp, sizeof log))
1845                         goto out;
1846                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
1847                 if (r)
1848                         goto out;
1849                 break;
1850         }
1851 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
1852         case KVM_REGISTER_COALESCED_MMIO: {
1853                 struct kvm_coalesced_mmio_zone zone;
1854                 r = -EFAULT;
1855                 if (copy_from_user(&zone, argp, sizeof zone))
1856                         goto out;
1857                 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
1858                 if (r)
1859                         goto out;
1860                 r = 0;
1861                 break;
1862         }
1863         case KVM_UNREGISTER_COALESCED_MMIO: {
1864                 struct kvm_coalesced_mmio_zone zone;
1865                 r = -EFAULT;
1866                 if (copy_from_user(&zone, argp, sizeof zone))
1867                         goto out;
1868                 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
1869                 if (r)
1870                         goto out;
1871                 r = 0;
1872                 break;
1873         }
1874 #endif
1875         case KVM_IRQFD: {
1876                 struct kvm_irqfd data;
1877
1878                 r = -EFAULT;
1879                 if (copy_from_user(&data, argp, sizeof data))
1880                         goto out;
1881                 r = kvm_irqfd(kvm, data.fd, data.gsi, data.flags);
1882                 break;
1883         }
1884         case KVM_IOEVENTFD: {
1885                 struct kvm_ioeventfd data;
1886
1887                 r = -EFAULT;
1888                 if (copy_from_user(&data, argp, sizeof data))
1889                         goto out;
1890                 r = kvm_ioeventfd(kvm, &data);
1891                 break;
1892         }
1893 #ifdef CONFIG_KVM_APIC_ARCHITECTURE
1894         case KVM_SET_BOOT_CPU_ID:
1895                 r = 0;
1896                 mutex_lock(&kvm->lock);
1897                 if (atomic_read(&kvm->online_vcpus) != 0)
1898                         r = -EBUSY;
1899                 else
1900                         kvm->bsp_vcpu_id = arg;
1901                 mutex_unlock(&kvm->lock);
1902                 break;
1903 #endif
1904         default:
1905                 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
1906                 if (r == -ENOTTY)
1907                         r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
1908         }
1909 out:
1910         return r;
1911 }
1912
1913 #ifdef CONFIG_COMPAT
1914 struct compat_kvm_dirty_log {
1915         __u32 slot;
1916         __u32 padding1;
1917         union {
1918                 compat_uptr_t dirty_bitmap; /* one bit per page */
1919                 __u64 padding2;
1920         };
1921 };
1922
1923 static long kvm_vm_compat_ioctl(struct file *filp,
1924                            unsigned int ioctl, unsigned long arg)
1925 {
1926         struct kvm *kvm = filp->private_data;
1927         int r;
1928
1929         if (kvm->mm != current->mm)
1930                 return -EIO;
1931         switch (ioctl) {
1932         case KVM_GET_DIRTY_LOG: {
1933                 struct compat_kvm_dirty_log compat_log;
1934                 struct kvm_dirty_log log;
1935
1936                 r = -EFAULT;
1937                 if (copy_from_user(&compat_log, (void __user *)arg,
1938                                    sizeof(compat_log)))
1939                         goto out;
1940                 log.slot         = compat_log.slot;
1941                 log.padding1     = compat_log.padding1;
1942                 log.padding2     = compat_log.padding2;
1943                 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
1944
1945                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
1946                 if (r)
1947                         goto out;
1948                 break;
1949         }
1950         default:
1951                 r = kvm_vm_ioctl(filp, ioctl, arg);
1952         }
1953
1954 out:
1955         return r;
1956 }
1957 #endif
1958
1959 static int kvm_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1960 {
1961         struct page *page[1];
1962         unsigned long addr;
1963         int npages;
1964         gfn_t gfn = vmf->pgoff;
1965         struct kvm *kvm = vma->vm_file->private_data;
1966
1967         addr = gfn_to_hva(kvm, gfn);
1968         if (kvm_is_error_hva(addr))
1969                 return VM_FAULT_SIGBUS;
1970
1971         npages = get_user_pages(current, current->mm, addr, 1, 1, 0, page,
1972                                 NULL);
1973         if (unlikely(npages != 1))
1974                 return VM_FAULT_SIGBUS;
1975
1976         vmf->page = page[0];
1977         return 0;
1978 }
1979
1980 static const struct vm_operations_struct kvm_vm_vm_ops = {
1981         .fault = kvm_vm_fault,
1982 };
1983
1984 static int kvm_vm_mmap(struct file *file, struct vm_area_struct *vma)
1985 {
1986         vma->vm_ops = &kvm_vm_vm_ops;
1987         return 0;
1988 }
1989
1990 static struct file_operations kvm_vm_fops = {
1991         .release        = kvm_vm_release,
1992         .unlocked_ioctl = kvm_vm_ioctl,
1993 #ifdef CONFIG_COMPAT
1994         .compat_ioctl   = kvm_vm_compat_ioctl,
1995 #endif
1996         .mmap           = kvm_vm_mmap,
1997         .llseek         = noop_llseek,
1998 };
1999
2000 static int kvm_dev_ioctl_create_vm(void)
2001 {
2002         int r;
2003         struct kvm *kvm;
2004
2005         kvm = kvm_create_vm();
2006         if (IS_ERR(kvm))
2007                 return PTR_ERR(kvm);
2008 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2009         r = kvm_coalesced_mmio_init(kvm);
2010         if (r < 0) {
2011                 kvm_put_kvm(kvm);
2012                 return r;
2013         }
2014 #endif
2015         r = anon_inode_getfd("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
2016         if (r < 0)
2017                 kvm_put_kvm(kvm);
2018
2019         return r;
2020 }
2021
2022 static long kvm_dev_ioctl_check_extension_generic(long arg)
2023 {
2024         switch (arg) {
2025         case KVM_CAP_USER_MEMORY:
2026         case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
2027         case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
2028 #ifdef CONFIG_KVM_APIC_ARCHITECTURE
2029         case KVM_CAP_SET_BOOT_CPU_ID:
2030 #endif
2031         case KVM_CAP_INTERNAL_ERROR_DATA:
2032                 return 1;
2033 #ifdef CONFIG_HAVE_KVM_IRQCHIP
2034         case KVM_CAP_IRQ_ROUTING:
2035                 return KVM_MAX_IRQ_ROUTES;
2036 #endif
2037         default:
2038                 break;
2039         }
2040         return kvm_dev_ioctl_check_extension(arg);
2041 }
2042
2043 static long kvm_dev_ioctl(struct file *filp,
2044                           unsigned int ioctl, unsigned long arg)
2045 {
2046         long r = -EINVAL;
2047
2048         switch (ioctl) {
2049         case KVM_GET_API_VERSION:
2050                 r = -EINVAL;
2051                 if (arg)
2052                         goto out;
2053                 r = KVM_API_VERSION;
2054                 break;
2055         case KVM_CREATE_VM:
2056                 r = -EINVAL;
2057                 if (arg)
2058                         goto out;
2059                 r = kvm_dev_ioctl_create_vm();
2060                 break;
2061         case KVM_CHECK_EXTENSION:
2062                 r = kvm_dev_ioctl_check_extension_generic(arg);
2063                 break;
2064         case KVM_GET_VCPU_MMAP_SIZE:
2065                 r = -EINVAL;
2066                 if (arg)
2067                         goto out;
2068                 r = PAGE_SIZE;     /* struct kvm_run */
2069 #ifdef CONFIG_X86
2070                 r += PAGE_SIZE;    /* pio data page */
2071 #endif
2072 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2073                 r += PAGE_SIZE;    /* coalesced mmio ring page */
2074 #endif
2075                 break;
2076         case KVM_TRACE_ENABLE:
2077         case KVM_TRACE_PAUSE:
2078         case KVM_TRACE_DISABLE:
2079                 r = -EOPNOTSUPP;
2080                 break;
2081         default:
2082                 return kvm_arch_dev_ioctl(filp, ioctl, arg);
2083         }
2084 out:
2085         return r;
2086 }
2087
2088 static struct file_operations kvm_chardev_ops = {
2089         .unlocked_ioctl = kvm_dev_ioctl,
2090         .compat_ioctl   = kvm_dev_ioctl,
2091         .llseek         = noop_llseek,
2092 };
2093
2094 static struct miscdevice kvm_dev = {
2095         KVM_MINOR,
2096         "kvm",
2097         &kvm_chardev_ops,
2098 };
2099
2100 static void hardware_enable_nolock(void *junk)
2101 {
2102         int cpu = raw_smp_processor_id();
2103         int r;
2104
2105         if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
2106                 return;
2107
2108         cpumask_set_cpu(cpu, cpus_hardware_enabled);
2109
2110         r = kvm_arch_hardware_enable(NULL);
2111
2112         if (r) {
2113                 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
2114                 atomic_inc(&hardware_enable_failed);
2115                 printk(KERN_INFO "kvm: enabling virtualization on "
2116                                  "CPU%d failed\n", cpu);
2117         }
2118 }
2119
2120 static void hardware_enable(void *junk)
2121 {
2122         spin_lock(&kvm_lock);
2123         hardware_enable_nolock(junk);
2124         spin_unlock(&kvm_lock);
2125 }
2126
2127 static void hardware_disable_nolock(void *junk)
2128 {
2129         int cpu = raw_smp_processor_id();
2130
2131         if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
2132                 return;
2133         cpumask_clear_cpu(cpu, cpus_hardware_enabled);
2134         kvm_arch_hardware_disable(NULL);
2135 }
2136
2137 static void hardware_disable(void *junk)
2138 {
2139         spin_lock(&kvm_lock);
2140         hardware_disable_nolock(junk);
2141         spin_unlock(&kvm_lock);
2142 }
2143
2144 static void hardware_disable_all_nolock(void)
2145 {
2146         BUG_ON(!kvm_usage_count);
2147
2148         kvm_usage_count--;
2149         if (!kvm_usage_count)
2150                 on_each_cpu(hardware_disable_nolock, NULL, 1);
2151 }
2152
2153 static void hardware_disable_all(void)
2154 {
2155         spin_lock(&kvm_lock);
2156         hardware_disable_all_nolock();
2157         spin_unlock(&kvm_lock);
2158 }
2159
2160 static int hardware_enable_all(void)
2161 {
2162         int r = 0;
2163
2164         spin_lock(&kvm_lock);
2165
2166         kvm_usage_count++;
2167         if (kvm_usage_count == 1) {
2168                 atomic_set(&hardware_enable_failed, 0);
2169                 on_each_cpu(hardware_enable_nolock, NULL, 1);
2170
2171                 if (atomic_read(&hardware_enable_failed)) {
2172                         hardware_disable_all_nolock();
2173                         r = -EBUSY;
2174                 }
2175         }
2176
2177         spin_unlock(&kvm_lock);
2178
2179         return r;
2180 }
2181
2182 static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
2183                            void *v)
2184 {
2185         int cpu = (long)v;
2186
2187         if (!kvm_usage_count)
2188                 return NOTIFY_OK;
2189
2190         val &= ~CPU_TASKS_FROZEN;
2191         switch (val) {
2192         case CPU_DYING:
2193                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
2194                        cpu);
2195                 hardware_disable(NULL);
2196                 break;
2197         case CPU_STARTING:
2198                 printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
2199                        cpu);
2200                 hardware_enable(NULL);
2201                 break;
2202         }
2203         return NOTIFY_OK;
2204 }
2205
2206
2207 asmlinkage void kvm_spurious_fault(void)
2208 {
2209         /* Fault while not rebooting.  We want the trace. */
2210         BUG();
2211 }
2212 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
2213
2214 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
2215                       void *v)
2216 {
2217         /*
2218          * Some (well, at least mine) BIOSes hang on reboot if
2219          * in vmx root mode.
2220          *
2221          * And Intel TXT required VMX off for all cpu when system shutdown.
2222          */
2223         printk(KERN_INFO "kvm: exiting hardware virtualization\n");
2224         kvm_rebooting = true;
2225         on_each_cpu(hardware_disable_nolock, NULL, 1);
2226         return NOTIFY_OK;
2227 }
2228
2229 static struct notifier_block kvm_reboot_notifier = {
2230         .notifier_call = kvm_reboot,
2231         .priority = 0,
2232 };
2233
2234 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
2235 {
2236         int i;
2237
2238         for (i = 0; i < bus->dev_count; i++) {
2239                 struct kvm_io_device *pos = bus->devs[i];
2240
2241                 kvm_iodevice_destructor(pos);
2242         }
2243         kfree(bus);
2244 }
2245
2246 /* kvm_io_bus_write - called under kvm->slots_lock */
2247 int kvm_io_bus_write(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
2248                      int len, const void *val)
2249 {
2250         int i;
2251         struct kvm_io_bus *bus;
2252
2253         bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
2254         for (i = 0; i < bus->dev_count; i++)
2255                 if (!kvm_iodevice_write(bus->devs[i], addr, len, val))
2256                         return 0;
2257         return -EOPNOTSUPP;
2258 }
2259
2260 /* kvm_io_bus_read - called under kvm->slots_lock */
2261 int kvm_io_bus_read(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
2262                     int len, void *val)
2263 {
2264         int i;
2265         struct kvm_io_bus *bus;
2266
2267         bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
2268         for (i = 0; i < bus->dev_count; i++)
2269                 if (!kvm_iodevice_read(bus->devs[i], addr, len, val))
2270                         return 0;
2271         return -EOPNOTSUPP;
2272 }
2273
2274 /* Caller must hold slots_lock. */
2275 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx,
2276                             struct kvm_io_device *dev)
2277 {
2278         struct kvm_io_bus *new_bus, *bus;
2279
2280         bus = kvm->buses[bus_idx];
2281         if (bus->dev_count > NR_IOBUS_DEVS-1)
2282                 return -ENOSPC;
2283
2284         new_bus = kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL);
2285         if (!new_bus)
2286                 return -ENOMEM;
2287         memcpy(new_bus, bus, sizeof(struct kvm_io_bus));
2288         new_bus->devs[new_bus->dev_count++] = dev;
2289         rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
2290         synchronize_srcu_expedited(&kvm->srcu);
2291         kfree(bus);
2292
2293         return 0;
2294 }
2295
2296 /* Caller must hold slots_lock. */
2297 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
2298                               struct kvm_io_device *dev)
2299 {
2300         int i, r;
2301         struct kvm_io_bus *new_bus, *bus;
2302
2303         new_bus = kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL);
2304         if (!new_bus)
2305                 return -ENOMEM;
2306
2307         bus = kvm->buses[bus_idx];
2308         memcpy(new_bus, bus, sizeof(struct kvm_io_bus));
2309
2310         r = -ENOENT;
2311         for (i = 0; i < new_bus->dev_count; i++)
2312                 if (new_bus->devs[i] == dev) {
2313                         r = 0;
2314                         new_bus->devs[i] = new_bus->devs[--new_bus->dev_count];
2315                         break;
2316                 }
2317
2318         if (r) {
2319                 kfree(new_bus);
2320                 return r;
2321         }
2322
2323         rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
2324         synchronize_srcu_expedited(&kvm->srcu);
2325         kfree(bus);
2326         return r;
2327 }
2328
2329 static struct notifier_block kvm_cpu_notifier = {
2330         .notifier_call = kvm_cpu_hotplug,
2331 };
2332
2333 static int vm_stat_get(void *_offset, u64 *val)
2334 {
2335         unsigned offset = (long)_offset;
2336         struct kvm *kvm;
2337
2338         *val = 0;
2339         spin_lock(&kvm_lock);
2340         list_for_each_entry(kvm, &vm_list, vm_list)
2341                 *val += *(u32 *)((void *)kvm + offset);
2342         spin_unlock(&kvm_lock);
2343         return 0;
2344 }
2345
2346 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
2347
2348 static int vcpu_stat_get(void *_offset, u64 *val)
2349 {
2350         unsigned offset = (long)_offset;
2351         struct kvm *kvm;
2352         struct kvm_vcpu *vcpu;
2353         int i;
2354
2355         *val = 0;
2356         spin_lock(&kvm_lock);
2357         list_for_each_entry(kvm, &vm_list, vm_list)
2358                 kvm_for_each_vcpu(i, vcpu, kvm)
2359                         *val += *(u32 *)((void *)vcpu + offset);
2360
2361         spin_unlock(&kvm_lock);
2362         return 0;
2363 }
2364
2365 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
2366
2367 static const struct file_operations *stat_fops[] = {
2368         [KVM_STAT_VCPU] = &vcpu_stat_fops,
2369         [KVM_STAT_VM]   = &vm_stat_fops,
2370 };
2371
2372 static void kvm_init_debug(void)
2373 {
2374         struct kvm_stats_debugfs_item *p;
2375
2376         kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
2377         for (p = debugfs_entries; p->name; ++p)
2378                 p->dentry = debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
2379                                                 (void *)(long)p->offset,
2380                                                 stat_fops[p->kind]);
2381 }
2382
2383 static void kvm_exit_debug(void)
2384 {
2385         struct kvm_stats_debugfs_item *p;
2386
2387         for (p = debugfs_entries; p->name; ++p)
2388                 debugfs_remove(p->dentry);
2389         debugfs_remove(kvm_debugfs_dir);
2390 }
2391
2392 static int kvm_suspend(struct sys_device *dev, pm_message_t state)
2393 {
2394         if (kvm_usage_count)
2395                 hardware_disable_nolock(NULL);
2396         return 0;
2397 }
2398
2399 static int kvm_resume(struct sys_device *dev)
2400 {
2401         if (kvm_usage_count) {
2402                 WARN_ON(spin_is_locked(&kvm_lock));
2403                 hardware_enable_nolock(NULL);
2404         }
2405         return 0;
2406 }
2407
2408 static struct sysdev_class kvm_sysdev_class = {
2409         .name = "kvm",
2410         .suspend = kvm_suspend,
2411         .resume = kvm_resume,
2412 };
2413
2414 static struct sys_device kvm_sysdev = {
2415         .id = 0,
2416         .cls = &kvm_sysdev_class,
2417 };
2418
2419 struct page *bad_page;
2420 pfn_t bad_pfn;
2421
2422 static inline
2423 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
2424 {
2425         return container_of(pn, struct kvm_vcpu, preempt_notifier);
2426 }
2427
2428 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
2429 {
2430         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
2431
2432         kvm_arch_vcpu_load(vcpu, cpu);
2433 }
2434
2435 static void kvm_sched_out(struct preempt_notifier *pn,
2436                           struct task_struct *next)
2437 {
2438         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
2439
2440         kvm_arch_vcpu_put(vcpu);
2441 }
2442
2443 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
2444                   struct module *module)
2445 {
2446         int r;
2447         int cpu;
2448
2449         r = kvm_arch_init(opaque);
2450         if (r)
2451                 goto out_fail;
2452
2453         bad_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2454
2455         if (bad_page == NULL) {
2456                 r = -ENOMEM;
2457                 goto out;
2458         }
2459
2460         bad_pfn = page_to_pfn(bad_page);
2461
2462         hwpoison_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2463
2464         if (hwpoison_page == NULL) {
2465                 r = -ENOMEM;
2466                 goto out_free_0;
2467         }
2468
2469         hwpoison_pfn = page_to_pfn(hwpoison_page);
2470
2471         fault_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2472
2473         if (fault_page == NULL) {
2474                 r = -ENOMEM;
2475                 goto out_free_0;
2476         }
2477
2478         fault_pfn = page_to_pfn(fault_page);
2479
2480         if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
2481                 r = -ENOMEM;
2482                 goto out_free_0;
2483         }
2484
2485         r = kvm_arch_hardware_setup();
2486         if (r < 0)
2487                 goto out_free_0a;
2488
2489         for_each_online_cpu(cpu) {
2490                 smp_call_function_single(cpu,
2491                                 kvm_arch_check_processor_compat,
2492                                 &r, 1);
2493                 if (r < 0)
2494                         goto out_free_1;
2495         }
2496
2497         r = register_cpu_notifier(&kvm_cpu_notifier);
2498         if (r)
2499                 goto out_free_2;
2500         register_reboot_notifier(&kvm_reboot_notifier);
2501
2502         r = sysdev_class_register(&kvm_sysdev_class);
2503         if (r)
2504                 goto out_free_3;
2505
2506         r = sysdev_register(&kvm_sysdev);
2507         if (r)
2508                 goto out_free_4;
2509
2510         /* A kmem cache lets us meet the alignment requirements of fx_save. */
2511         if (!vcpu_align)
2512                 vcpu_align = __alignof__(struct kvm_vcpu);
2513         kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size, vcpu_align,
2514                                            0, NULL);
2515         if (!kvm_vcpu_cache) {
2516                 r = -ENOMEM;
2517                 goto out_free_5;
2518         }
2519
2520         r = kvm_async_pf_init();
2521         if (r)
2522                 goto out_free;
2523
2524         kvm_chardev_ops.owner = module;
2525         kvm_vm_fops.owner = module;
2526         kvm_vcpu_fops.owner = module;
2527
2528         r = misc_register(&kvm_dev);
2529         if (r) {
2530                 printk(KERN_ERR "kvm: misc device register failed\n");
2531                 goto out_unreg;
2532         }
2533
2534         kvm_preempt_ops.sched_in = kvm_sched_in;
2535         kvm_preempt_ops.sched_out = kvm_sched_out;
2536
2537         kvm_init_debug();
2538
2539         return 0;
2540
2541 out_unreg:
2542         kvm_async_pf_deinit();
2543 out_free:
2544         kmem_cache_destroy(kvm_vcpu_cache);
2545 out_free_5:
2546         sysdev_unregister(&kvm_sysdev);
2547 out_free_4:
2548         sysdev_class_unregister(&kvm_sysdev_class);
2549 out_free_3:
2550         unregister_reboot_notifier(&kvm_reboot_notifier);
2551         unregister_cpu_notifier(&kvm_cpu_notifier);
2552 out_free_2:
2553 out_free_1:
2554         kvm_arch_hardware_unsetup();
2555 out_free_0a:
2556         free_cpumask_var(cpus_hardware_enabled);
2557 out_free_0:
2558         if (fault_page)
2559                 __free_page(fault_page);
2560         if (hwpoison_page)
2561                 __free_page(hwpoison_page);
2562         __free_page(bad_page);
2563 out:
2564         kvm_arch_exit();
2565 out_fail:
2566         return r;
2567 }
2568 EXPORT_SYMBOL_GPL(kvm_init);
2569
2570 void kvm_exit(void)
2571 {
2572         kvm_exit_debug();
2573         misc_deregister(&kvm_dev);
2574         kmem_cache_destroy(kvm_vcpu_cache);
2575         kvm_async_pf_deinit();
2576         sysdev_unregister(&kvm_sysdev);
2577         sysdev_class_unregister(&kvm_sysdev_class);
2578         unregister_reboot_notifier(&kvm_reboot_notifier);
2579         unregister_cpu_notifier(&kvm_cpu_notifier);
2580         on_each_cpu(hardware_disable_nolock, NULL, 1);
2581         kvm_arch_hardware_unsetup();
2582         kvm_arch_exit();
2583         free_cpumask_var(cpus_hardware_enabled);
2584         __free_page(hwpoison_page);
2585         __free_page(bad_page);
2586 }
2587 EXPORT_SYMBOL_GPL(kvm_exit);