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