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