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