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