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