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