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