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