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