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