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