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