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