KVM: Convert kvm_lock to raw_spinlock
[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_RAW_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         raw_spin_lock(&kvm_lock);
485         list_add(&kvm->vm_list, &vm_list);
486         raw_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         raw_spin_lock(&kvm_lock);
560         list_del(&kvm->vm_list);
561         raw_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 *me)
1488 {
1489         struct kvm *kvm = me->kvm;
1490         struct kvm_vcpu *vcpu;
1491         int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
1492         int yielded = 0;
1493         int pass;
1494         int i;
1495
1496         /*
1497          * We boost the priority of a VCPU that is runnable but not
1498          * currently running, because it got preempted by something
1499          * else and called schedule in __vcpu_run.  Hopefully that
1500          * VCPU is holding the lock that we need and will release it.
1501          * We approximate round-robin by starting at the last boosted VCPU.
1502          */
1503         for (pass = 0; pass < 2 && !yielded; pass++) {
1504                 kvm_for_each_vcpu(i, vcpu, kvm) {
1505                         struct task_struct *task = NULL;
1506                         struct pid *pid;
1507                         if (!pass && i < last_boosted_vcpu) {
1508                                 i = last_boosted_vcpu;
1509                                 continue;
1510                         } else if (pass && i > last_boosted_vcpu)
1511                                 break;
1512                         if (vcpu == me)
1513                                 continue;
1514                         if (waitqueue_active(&vcpu->wq))
1515                                 continue;
1516                         rcu_read_lock();
1517                         pid = rcu_dereference(vcpu->pid);
1518                         if (pid)
1519                                 task = get_pid_task(vcpu->pid, PIDTYPE_PID);
1520                         rcu_read_unlock();
1521                         if (!task)
1522                                 continue;
1523                         if (task->flags & PF_VCPU) {
1524                                 put_task_struct(task);
1525                                 continue;
1526                         }
1527                         if (yield_to(task, 1)) {
1528                                 put_task_struct(task);
1529                                 kvm->last_boosted_vcpu = i;
1530                                 yielded = 1;
1531                                 break;
1532                         }
1533                         put_task_struct(task);
1534                 }
1535         }
1536 }
1537 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
1538
1539 static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1540 {
1541         struct kvm_vcpu *vcpu = vma->vm_file->private_data;
1542         struct page *page;
1543
1544         if (vmf->pgoff == 0)
1545                 page = virt_to_page(vcpu->run);
1546 #ifdef CONFIG_X86
1547         else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
1548                 page = virt_to_page(vcpu->arch.pio_data);
1549 #endif
1550 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
1551         else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
1552                 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
1553 #endif
1554         else
1555                 return VM_FAULT_SIGBUS;
1556         get_page(page);
1557         vmf->page = page;
1558         return 0;
1559 }
1560
1561 static const struct vm_operations_struct kvm_vcpu_vm_ops = {
1562         .fault = kvm_vcpu_fault,
1563 };
1564
1565 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
1566 {
1567         vma->vm_ops = &kvm_vcpu_vm_ops;
1568         return 0;
1569 }
1570
1571 static int kvm_vcpu_release(struct inode *inode, struct file *filp)
1572 {
1573         struct kvm_vcpu *vcpu = filp->private_data;
1574
1575         kvm_put_kvm(vcpu->kvm);
1576         return 0;
1577 }
1578
1579 static struct file_operations kvm_vcpu_fops = {
1580         .release        = kvm_vcpu_release,
1581         .unlocked_ioctl = kvm_vcpu_ioctl,
1582         .compat_ioctl   = kvm_vcpu_ioctl,
1583         .mmap           = kvm_vcpu_mmap,
1584         .llseek         = noop_llseek,
1585 };
1586
1587 /*
1588  * Allocates an inode for the vcpu.
1589  */
1590 static int create_vcpu_fd(struct kvm_vcpu *vcpu)
1591 {
1592         return anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, O_RDWR);
1593 }
1594
1595 /*
1596  * Creates some virtual cpus.  Good luck creating more than one.
1597  */
1598 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
1599 {
1600         int r;
1601         struct kvm_vcpu *vcpu, *v;
1602
1603         vcpu = kvm_arch_vcpu_create(kvm, id);
1604         if (IS_ERR(vcpu))
1605                 return PTR_ERR(vcpu);
1606
1607         preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
1608
1609         r = kvm_arch_vcpu_setup(vcpu);
1610         if (r)
1611                 return r;
1612
1613         mutex_lock(&kvm->lock);
1614         if (atomic_read(&kvm->online_vcpus) == KVM_MAX_VCPUS) {
1615                 r = -EINVAL;
1616                 goto vcpu_destroy;
1617         }
1618
1619         kvm_for_each_vcpu(r, v, kvm)
1620                 if (v->vcpu_id == id) {
1621                         r = -EEXIST;
1622                         goto vcpu_destroy;
1623                 }
1624
1625         BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
1626
1627         /* Now it's all set up, let userspace reach it */
1628         kvm_get_kvm(kvm);
1629         r = create_vcpu_fd(vcpu);
1630         if (r < 0) {
1631                 kvm_put_kvm(kvm);
1632                 goto vcpu_destroy;
1633         }
1634
1635         kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
1636         smp_wmb();
1637         atomic_inc(&kvm->online_vcpus);
1638
1639 #ifdef CONFIG_KVM_APIC_ARCHITECTURE
1640         if (kvm->bsp_vcpu_id == id)
1641                 kvm->bsp_vcpu = vcpu;
1642 #endif
1643         mutex_unlock(&kvm->lock);
1644         return r;
1645
1646 vcpu_destroy:
1647         mutex_unlock(&kvm->lock);
1648         kvm_arch_vcpu_destroy(vcpu);
1649         return r;
1650 }
1651
1652 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
1653 {
1654         if (sigset) {
1655                 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
1656                 vcpu->sigset_active = 1;
1657                 vcpu->sigset = *sigset;
1658         } else
1659                 vcpu->sigset_active = 0;
1660         return 0;
1661 }
1662
1663 static long kvm_vcpu_ioctl(struct file *filp,
1664                            unsigned int ioctl, unsigned long arg)
1665 {
1666         struct kvm_vcpu *vcpu = filp->private_data;
1667         void __user *argp = (void __user *)arg;
1668         int r;
1669         struct kvm_fpu *fpu = NULL;
1670         struct kvm_sregs *kvm_sregs = NULL;
1671
1672         if (vcpu->kvm->mm != current->mm)
1673                 return -EIO;
1674
1675 #if defined(CONFIG_S390) || defined(CONFIG_PPC)
1676         /*
1677          * Special cases: vcpu ioctls that are asynchronous to vcpu execution,
1678          * so vcpu_load() would break it.
1679          */
1680         if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_INTERRUPT)
1681                 return kvm_arch_vcpu_ioctl(filp, ioctl, arg);
1682 #endif
1683
1684
1685         vcpu_load(vcpu);
1686         switch (ioctl) {
1687         case KVM_RUN:
1688                 r = -EINVAL;
1689                 if (arg)
1690                         goto out;
1691                 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
1692                 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
1693                 break;
1694         case KVM_GET_REGS: {
1695                 struct kvm_regs *kvm_regs;
1696
1697                 r = -ENOMEM;
1698                 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
1699                 if (!kvm_regs)
1700                         goto out;
1701                 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
1702                 if (r)
1703                         goto out_free1;
1704                 r = -EFAULT;
1705                 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
1706                         goto out_free1;
1707                 r = 0;
1708 out_free1:
1709                 kfree(kvm_regs);
1710                 break;
1711         }
1712         case KVM_SET_REGS: {
1713                 struct kvm_regs *kvm_regs;
1714
1715                 r = -ENOMEM;
1716                 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
1717                 if (!kvm_regs)
1718                         goto out;
1719                 r = -EFAULT;
1720                 if (copy_from_user(kvm_regs, argp, sizeof(struct kvm_regs)))
1721                         goto out_free2;
1722                 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
1723                 if (r)
1724                         goto out_free2;
1725                 r = 0;
1726 out_free2:
1727                 kfree(kvm_regs);
1728                 break;
1729         }
1730         case KVM_GET_SREGS: {
1731                 kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
1732                 r = -ENOMEM;
1733                 if (!kvm_sregs)
1734                         goto out;
1735                 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
1736                 if (r)
1737                         goto out;
1738                 r = -EFAULT;
1739                 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
1740                         goto out;
1741                 r = 0;
1742                 break;
1743         }
1744         case KVM_SET_SREGS: {
1745                 kvm_sregs = kmalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
1746                 r = -ENOMEM;
1747                 if (!kvm_sregs)
1748                         goto out;
1749                 r = -EFAULT;
1750                 if (copy_from_user(kvm_sregs, argp, sizeof(struct kvm_sregs)))
1751                         goto out;
1752                 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
1753                 if (r)
1754                         goto out;
1755                 r = 0;
1756                 break;
1757         }
1758         case KVM_GET_MP_STATE: {
1759                 struct kvm_mp_state mp_state;
1760
1761                 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
1762                 if (r)
1763                         goto out;
1764                 r = -EFAULT;
1765                 if (copy_to_user(argp, &mp_state, sizeof mp_state))
1766                         goto out;
1767                 r = 0;
1768                 break;
1769         }
1770         case KVM_SET_MP_STATE: {
1771                 struct kvm_mp_state mp_state;
1772
1773                 r = -EFAULT;
1774                 if (copy_from_user(&mp_state, argp, sizeof mp_state))
1775                         goto out;
1776                 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
1777                 if (r)
1778                         goto out;
1779                 r = 0;
1780                 break;
1781         }
1782         case KVM_TRANSLATE: {
1783                 struct kvm_translation tr;
1784
1785                 r = -EFAULT;
1786                 if (copy_from_user(&tr, argp, sizeof tr))
1787                         goto out;
1788                 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
1789                 if (r)
1790                         goto out;
1791                 r = -EFAULT;
1792                 if (copy_to_user(argp, &tr, sizeof tr))
1793                         goto out;
1794                 r = 0;
1795                 break;
1796         }
1797         case KVM_SET_GUEST_DEBUG: {
1798                 struct kvm_guest_debug dbg;
1799
1800                 r = -EFAULT;
1801                 if (copy_from_user(&dbg, argp, sizeof dbg))
1802                         goto out;
1803                 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
1804                 if (r)
1805                         goto out;
1806                 r = 0;
1807                 break;
1808         }
1809         case KVM_SET_SIGNAL_MASK: {
1810                 struct kvm_signal_mask __user *sigmask_arg = argp;
1811                 struct kvm_signal_mask kvm_sigmask;
1812                 sigset_t sigset, *p;
1813
1814                 p = NULL;
1815                 if (argp) {
1816                         r = -EFAULT;
1817                         if (copy_from_user(&kvm_sigmask, argp,
1818                                            sizeof kvm_sigmask))
1819                                 goto out;
1820                         r = -EINVAL;
1821                         if (kvm_sigmask.len != sizeof sigset)
1822                                 goto out;
1823                         r = -EFAULT;
1824                         if (copy_from_user(&sigset, sigmask_arg->sigset,
1825                                            sizeof sigset))
1826                                 goto out;
1827                         p = &sigset;
1828                 }
1829                 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
1830                 break;
1831         }
1832         case KVM_GET_FPU: {
1833                 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
1834                 r = -ENOMEM;
1835                 if (!fpu)
1836                         goto out;
1837                 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
1838                 if (r)
1839                         goto out;
1840                 r = -EFAULT;
1841                 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
1842                         goto out;
1843                 r = 0;
1844                 break;
1845         }
1846         case KVM_SET_FPU: {
1847                 fpu = kmalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
1848                 r = -ENOMEM;
1849                 if (!fpu)
1850                         goto out;
1851                 r = -EFAULT;
1852                 if (copy_from_user(fpu, argp, sizeof(struct kvm_fpu)))
1853                         goto out;
1854                 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
1855                 if (r)
1856                         goto out;
1857                 r = 0;
1858                 break;
1859         }
1860         default:
1861                 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
1862         }
1863 out:
1864         vcpu_put(vcpu);
1865         kfree(fpu);
1866         kfree(kvm_sregs);
1867         return r;
1868 }
1869
1870 static long kvm_vm_ioctl(struct file *filp,
1871                            unsigned int ioctl, unsigned long arg)
1872 {
1873         struct kvm *kvm = filp->private_data;
1874         void __user *argp = (void __user *)arg;
1875         int r;
1876
1877         if (kvm->mm != current->mm)
1878                 return -EIO;
1879         switch (ioctl) {
1880         case KVM_CREATE_VCPU:
1881                 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
1882                 if (r < 0)
1883                         goto out;
1884                 break;
1885         case KVM_SET_USER_MEMORY_REGION: {
1886                 struct kvm_userspace_memory_region kvm_userspace_mem;
1887
1888                 r = -EFAULT;
1889                 if (copy_from_user(&kvm_userspace_mem, argp,
1890                                                 sizeof kvm_userspace_mem))
1891                         goto out;
1892
1893                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 1);
1894                 if (r)
1895                         goto out;
1896                 break;
1897         }
1898         case KVM_GET_DIRTY_LOG: {
1899                 struct kvm_dirty_log log;
1900
1901                 r = -EFAULT;
1902                 if (copy_from_user(&log, argp, sizeof log))
1903                         goto out;
1904                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
1905                 if (r)
1906                         goto out;
1907                 break;
1908         }
1909 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
1910         case KVM_REGISTER_COALESCED_MMIO: {
1911                 struct kvm_coalesced_mmio_zone zone;
1912                 r = -EFAULT;
1913                 if (copy_from_user(&zone, argp, sizeof zone))
1914                         goto out;
1915                 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
1916                 if (r)
1917                         goto out;
1918                 r = 0;
1919                 break;
1920         }
1921         case KVM_UNREGISTER_COALESCED_MMIO: {
1922                 struct kvm_coalesced_mmio_zone zone;
1923                 r = -EFAULT;
1924                 if (copy_from_user(&zone, argp, sizeof zone))
1925                         goto out;
1926                 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
1927                 if (r)
1928                         goto out;
1929                 r = 0;
1930                 break;
1931         }
1932 #endif
1933         case KVM_IRQFD: {
1934                 struct kvm_irqfd data;
1935
1936                 r = -EFAULT;
1937                 if (copy_from_user(&data, argp, sizeof data))
1938                         goto out;
1939                 r = kvm_irqfd(kvm, data.fd, data.gsi, data.flags);
1940                 break;
1941         }
1942         case KVM_IOEVENTFD: {
1943                 struct kvm_ioeventfd data;
1944
1945                 r = -EFAULT;
1946                 if (copy_from_user(&data, argp, sizeof data))
1947                         goto out;
1948                 r = kvm_ioeventfd(kvm, &data);
1949                 break;
1950         }
1951 #ifdef CONFIG_KVM_APIC_ARCHITECTURE
1952         case KVM_SET_BOOT_CPU_ID:
1953                 r = 0;
1954                 mutex_lock(&kvm->lock);
1955                 if (atomic_read(&kvm->online_vcpus) != 0)
1956                         r = -EBUSY;
1957                 else
1958                         kvm->bsp_vcpu_id = arg;
1959                 mutex_unlock(&kvm->lock);
1960                 break;
1961 #endif
1962         default:
1963                 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
1964                 if (r == -ENOTTY)
1965                         r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
1966         }
1967 out:
1968         return r;
1969 }
1970
1971 #ifdef CONFIG_COMPAT
1972 struct compat_kvm_dirty_log {
1973         __u32 slot;
1974         __u32 padding1;
1975         union {
1976                 compat_uptr_t dirty_bitmap; /* one bit per page */
1977                 __u64 padding2;
1978         };
1979 };
1980
1981 static long kvm_vm_compat_ioctl(struct file *filp,
1982                            unsigned int ioctl, unsigned long arg)
1983 {
1984         struct kvm *kvm = filp->private_data;
1985         int r;
1986
1987         if (kvm->mm != current->mm)
1988                 return -EIO;
1989         switch (ioctl) {
1990         case KVM_GET_DIRTY_LOG: {
1991                 struct compat_kvm_dirty_log compat_log;
1992                 struct kvm_dirty_log log;
1993
1994                 r = -EFAULT;
1995                 if (copy_from_user(&compat_log, (void __user *)arg,
1996                                    sizeof(compat_log)))
1997                         goto out;
1998                 log.slot         = compat_log.slot;
1999                 log.padding1     = compat_log.padding1;
2000                 log.padding2     = compat_log.padding2;
2001                 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
2002
2003                 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
2004                 if (r)
2005                         goto out;
2006                 break;
2007         }
2008         default:
2009                 r = kvm_vm_ioctl(filp, ioctl, arg);
2010         }
2011
2012 out:
2013         return r;
2014 }
2015 #endif
2016
2017 static int kvm_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
2018 {
2019         struct page *page[1];
2020         unsigned long addr;
2021         int npages;
2022         gfn_t gfn = vmf->pgoff;
2023         struct kvm *kvm = vma->vm_file->private_data;
2024
2025         addr = gfn_to_hva(kvm, gfn);
2026         if (kvm_is_error_hva(addr))
2027                 return VM_FAULT_SIGBUS;
2028
2029         npages = get_user_pages(current, current->mm, addr, 1, 1, 0, page,
2030                                 NULL);
2031         if (unlikely(npages != 1))
2032                 return VM_FAULT_SIGBUS;
2033
2034         vmf->page = page[0];
2035         return 0;
2036 }
2037
2038 static const struct vm_operations_struct kvm_vm_vm_ops = {
2039         .fault = kvm_vm_fault,
2040 };
2041
2042 static int kvm_vm_mmap(struct file *file, struct vm_area_struct *vma)
2043 {
2044         vma->vm_ops = &kvm_vm_vm_ops;
2045         return 0;
2046 }
2047
2048 static struct file_operations kvm_vm_fops = {
2049         .release        = kvm_vm_release,
2050         .unlocked_ioctl = kvm_vm_ioctl,
2051 #ifdef CONFIG_COMPAT
2052         .compat_ioctl   = kvm_vm_compat_ioctl,
2053 #endif
2054         .mmap           = kvm_vm_mmap,
2055         .llseek         = noop_llseek,
2056 };
2057
2058 static int kvm_dev_ioctl_create_vm(void)
2059 {
2060         int r;
2061         struct kvm *kvm;
2062
2063         kvm = kvm_create_vm();
2064         if (IS_ERR(kvm))
2065                 return PTR_ERR(kvm);
2066 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2067         r = kvm_coalesced_mmio_init(kvm);
2068         if (r < 0) {
2069                 kvm_put_kvm(kvm);
2070                 return r;
2071         }
2072 #endif
2073         r = anon_inode_getfd("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
2074         if (r < 0)
2075                 kvm_put_kvm(kvm);
2076
2077         return r;
2078 }
2079
2080 static long kvm_dev_ioctl_check_extension_generic(long arg)
2081 {
2082         switch (arg) {
2083         case KVM_CAP_USER_MEMORY:
2084         case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
2085         case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
2086 #ifdef CONFIG_KVM_APIC_ARCHITECTURE
2087         case KVM_CAP_SET_BOOT_CPU_ID:
2088 #endif
2089         case KVM_CAP_INTERNAL_ERROR_DATA:
2090                 return 1;
2091 #ifdef CONFIG_HAVE_KVM_IRQCHIP
2092         case KVM_CAP_IRQ_ROUTING:
2093                 return KVM_MAX_IRQ_ROUTES;
2094 #endif
2095         default:
2096                 break;
2097         }
2098         return kvm_dev_ioctl_check_extension(arg);
2099 }
2100
2101 static long kvm_dev_ioctl(struct file *filp,
2102                           unsigned int ioctl, unsigned long arg)
2103 {
2104         long r = -EINVAL;
2105
2106         switch (ioctl) {
2107         case KVM_GET_API_VERSION:
2108                 r = -EINVAL;
2109                 if (arg)
2110                         goto out;
2111                 r = KVM_API_VERSION;
2112                 break;
2113         case KVM_CREATE_VM:
2114                 r = -EINVAL;
2115                 if (arg)
2116                         goto out;
2117                 r = kvm_dev_ioctl_create_vm();
2118                 break;
2119         case KVM_CHECK_EXTENSION:
2120                 r = kvm_dev_ioctl_check_extension_generic(arg);
2121                 break;
2122         case KVM_GET_VCPU_MMAP_SIZE:
2123                 r = -EINVAL;
2124                 if (arg)
2125                         goto out;
2126                 r = PAGE_SIZE;     /* struct kvm_run */
2127 #ifdef CONFIG_X86
2128                 r += PAGE_SIZE;    /* pio data page */
2129 #endif
2130 #ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2131                 r += PAGE_SIZE;    /* coalesced mmio ring page */
2132 #endif
2133                 break;
2134         case KVM_TRACE_ENABLE:
2135         case KVM_TRACE_PAUSE:
2136         case KVM_TRACE_DISABLE:
2137                 r = -EOPNOTSUPP;
2138                 break;
2139         default:
2140                 return kvm_arch_dev_ioctl(filp, ioctl, arg);
2141         }
2142 out:
2143         return r;
2144 }
2145
2146 static struct file_operations kvm_chardev_ops = {
2147         .unlocked_ioctl = kvm_dev_ioctl,
2148         .compat_ioctl   = kvm_dev_ioctl,
2149         .llseek         = noop_llseek,
2150 };
2151
2152 static struct miscdevice kvm_dev = {
2153         KVM_MINOR,
2154         "kvm",
2155         &kvm_chardev_ops,
2156 };
2157
2158 static void hardware_enable_nolock(void *junk)
2159 {
2160         int cpu = raw_smp_processor_id();
2161         int r;
2162
2163         if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
2164                 return;
2165
2166         cpumask_set_cpu(cpu, cpus_hardware_enabled);
2167
2168         r = kvm_arch_hardware_enable(NULL);
2169
2170         if (r) {
2171                 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
2172                 atomic_inc(&hardware_enable_failed);
2173                 printk(KERN_INFO "kvm: enabling virtualization on "
2174                                  "CPU%d failed\n", cpu);
2175         }
2176 }
2177
2178 static void hardware_enable(void *junk)
2179 {
2180         raw_spin_lock(&kvm_lock);
2181         hardware_enable_nolock(junk);
2182         raw_spin_unlock(&kvm_lock);
2183 }
2184
2185 static void hardware_disable_nolock(void *junk)
2186 {
2187         int cpu = raw_smp_processor_id();
2188
2189         if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
2190                 return;
2191         cpumask_clear_cpu(cpu, cpus_hardware_enabled);
2192         kvm_arch_hardware_disable(NULL);
2193 }
2194
2195 static void hardware_disable(void *junk)
2196 {
2197         raw_spin_lock(&kvm_lock);
2198         hardware_disable_nolock(junk);
2199         raw_spin_unlock(&kvm_lock);
2200 }
2201
2202 static void hardware_disable_all_nolock(void)
2203 {
2204         BUG_ON(!kvm_usage_count);
2205
2206         kvm_usage_count--;
2207         if (!kvm_usage_count)
2208                 on_each_cpu(hardware_disable_nolock, NULL, 1);
2209 }
2210
2211 static void hardware_disable_all(void)
2212 {
2213         raw_spin_lock(&kvm_lock);
2214         hardware_disable_all_nolock();
2215         raw_spin_unlock(&kvm_lock);
2216 }
2217
2218 static int hardware_enable_all(void)
2219 {
2220         int r = 0;
2221
2222         raw_spin_lock(&kvm_lock);
2223
2224         kvm_usage_count++;
2225         if (kvm_usage_count == 1) {
2226                 atomic_set(&hardware_enable_failed, 0);
2227                 on_each_cpu(hardware_enable_nolock, NULL, 1);
2228
2229                 if (atomic_read(&hardware_enable_failed)) {
2230                         hardware_disable_all_nolock();
2231                         r = -EBUSY;
2232                 }
2233         }
2234
2235         raw_spin_unlock(&kvm_lock);
2236
2237         return r;
2238 }
2239
2240 static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
2241                            void *v)
2242 {
2243         int cpu = (long)v;
2244
2245         if (!kvm_usage_count)
2246                 return NOTIFY_OK;
2247
2248         val &= ~CPU_TASKS_FROZEN;
2249         switch (val) {
2250         case CPU_DYING:
2251                 printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
2252                        cpu);
2253                 hardware_disable(NULL);
2254                 break;
2255         case CPU_STARTING:
2256                 printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
2257                        cpu);
2258                 hardware_enable(NULL);
2259                 break;
2260         }
2261         return NOTIFY_OK;
2262 }
2263
2264
2265 asmlinkage void kvm_spurious_fault(void)
2266 {
2267         /* Fault while not rebooting.  We want the trace. */
2268         BUG();
2269 }
2270 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
2271
2272 static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
2273                       void *v)
2274 {
2275         /*
2276          * Some (well, at least mine) BIOSes hang on reboot if
2277          * in vmx root mode.
2278          *
2279          * And Intel TXT required VMX off for all cpu when system shutdown.
2280          */
2281         printk(KERN_INFO "kvm: exiting hardware virtualization\n");
2282         kvm_rebooting = true;
2283         on_each_cpu(hardware_disable_nolock, NULL, 1);
2284         return NOTIFY_OK;
2285 }
2286
2287 static struct notifier_block kvm_reboot_notifier = {
2288         .notifier_call = kvm_reboot,
2289         .priority = 0,
2290 };
2291
2292 static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
2293 {
2294         int i;
2295
2296         for (i = 0; i < bus->dev_count; i++) {
2297                 struct kvm_io_device *pos = bus->devs[i];
2298
2299                 kvm_iodevice_destructor(pos);
2300         }
2301         kfree(bus);
2302 }
2303
2304 /* kvm_io_bus_write - called under kvm->slots_lock */
2305 int kvm_io_bus_write(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
2306                      int len, const void *val)
2307 {
2308         int i;
2309         struct kvm_io_bus *bus;
2310
2311         bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
2312         for (i = 0; i < bus->dev_count; i++)
2313                 if (!kvm_iodevice_write(bus->devs[i], addr, len, val))
2314                         return 0;
2315         return -EOPNOTSUPP;
2316 }
2317
2318 /* kvm_io_bus_read - called under kvm->slots_lock */
2319 int kvm_io_bus_read(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
2320                     int len, void *val)
2321 {
2322         int i;
2323         struct kvm_io_bus *bus;
2324
2325         bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
2326         for (i = 0; i < bus->dev_count; i++)
2327                 if (!kvm_iodevice_read(bus->devs[i], addr, len, val))
2328                         return 0;
2329         return -EOPNOTSUPP;
2330 }
2331
2332 /* Caller must hold slots_lock. */
2333 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx,
2334                             struct kvm_io_device *dev)
2335 {
2336         struct kvm_io_bus *new_bus, *bus;
2337
2338         bus = kvm->buses[bus_idx];
2339         if (bus->dev_count > NR_IOBUS_DEVS-1)
2340                 return -ENOSPC;
2341
2342         new_bus = kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL);
2343         if (!new_bus)
2344                 return -ENOMEM;
2345         memcpy(new_bus, bus, sizeof(struct kvm_io_bus));
2346         new_bus->devs[new_bus->dev_count++] = dev;
2347         rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
2348         synchronize_srcu_expedited(&kvm->srcu);
2349         kfree(bus);
2350
2351         return 0;
2352 }
2353
2354 /* Caller must hold slots_lock. */
2355 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
2356                               struct kvm_io_device *dev)
2357 {
2358         int i, r;
2359         struct kvm_io_bus *new_bus, *bus;
2360
2361         new_bus = kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL);
2362         if (!new_bus)
2363                 return -ENOMEM;
2364
2365         bus = kvm->buses[bus_idx];
2366         memcpy(new_bus, bus, sizeof(struct kvm_io_bus));
2367
2368         r = -ENOENT;
2369         for (i = 0; i < new_bus->dev_count; i++)
2370                 if (new_bus->devs[i] == dev) {
2371                         r = 0;
2372                         new_bus->devs[i] = new_bus->devs[--new_bus->dev_count];
2373                         break;
2374                 }
2375
2376         if (r) {
2377                 kfree(new_bus);
2378                 return r;
2379         }
2380
2381         rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
2382         synchronize_srcu_expedited(&kvm->srcu);
2383         kfree(bus);
2384         return r;
2385 }
2386
2387 static struct notifier_block kvm_cpu_notifier = {
2388         .notifier_call = kvm_cpu_hotplug,
2389 };
2390
2391 static int vm_stat_get(void *_offset, u64 *val)
2392 {
2393         unsigned offset = (long)_offset;
2394         struct kvm *kvm;
2395
2396         *val = 0;
2397         raw_spin_lock(&kvm_lock);
2398         list_for_each_entry(kvm, &vm_list, vm_list)
2399                 *val += *(u32 *)((void *)kvm + offset);
2400         raw_spin_unlock(&kvm_lock);
2401         return 0;
2402 }
2403
2404 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
2405
2406 static int vcpu_stat_get(void *_offset, u64 *val)
2407 {
2408         unsigned offset = (long)_offset;
2409         struct kvm *kvm;
2410         struct kvm_vcpu *vcpu;
2411         int i;
2412
2413         *val = 0;
2414         raw_spin_lock(&kvm_lock);
2415         list_for_each_entry(kvm, &vm_list, vm_list)
2416                 kvm_for_each_vcpu(i, vcpu, kvm)
2417                         *val += *(u32 *)((void *)vcpu + offset);
2418
2419         raw_spin_unlock(&kvm_lock);
2420         return 0;
2421 }
2422
2423 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
2424
2425 static const struct file_operations *stat_fops[] = {
2426         [KVM_STAT_VCPU] = &vcpu_stat_fops,
2427         [KVM_STAT_VM]   = &vm_stat_fops,
2428 };
2429
2430 static void kvm_init_debug(void)
2431 {
2432         struct kvm_stats_debugfs_item *p;
2433
2434         kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
2435         for (p = debugfs_entries; p->name; ++p)
2436                 p->dentry = debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
2437                                                 (void *)(long)p->offset,
2438                                                 stat_fops[p->kind]);
2439 }
2440
2441 static void kvm_exit_debug(void)
2442 {
2443         struct kvm_stats_debugfs_item *p;
2444
2445         for (p = debugfs_entries; p->name; ++p)
2446                 debugfs_remove(p->dentry);
2447         debugfs_remove(kvm_debugfs_dir);
2448 }
2449
2450 static int kvm_suspend(struct sys_device *dev, pm_message_t state)
2451 {
2452         if (kvm_usage_count)
2453                 hardware_disable_nolock(NULL);
2454         return 0;
2455 }
2456
2457 static int kvm_resume(struct sys_device *dev)
2458 {
2459         if (kvm_usage_count) {
2460                 WARN_ON(raw_spin_is_locked(&kvm_lock));
2461                 hardware_enable_nolock(NULL);
2462         }
2463         return 0;
2464 }
2465
2466 static struct sysdev_class kvm_sysdev_class = {
2467         .name = "kvm",
2468         .suspend = kvm_suspend,
2469         .resume = kvm_resume,
2470 };
2471
2472 static struct sys_device kvm_sysdev = {
2473         .id = 0,
2474         .cls = &kvm_sysdev_class,
2475 };
2476
2477 struct page *bad_page;
2478 pfn_t bad_pfn;
2479
2480 static inline
2481 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
2482 {
2483         return container_of(pn, struct kvm_vcpu, preempt_notifier);
2484 }
2485
2486 static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
2487 {
2488         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
2489
2490         kvm_arch_vcpu_load(vcpu, cpu);
2491 }
2492
2493 static void kvm_sched_out(struct preempt_notifier *pn,
2494                           struct task_struct *next)
2495 {
2496         struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
2497
2498         kvm_arch_vcpu_put(vcpu);
2499 }
2500
2501 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
2502                   struct module *module)
2503 {
2504         int r;
2505         int cpu;
2506
2507         r = kvm_arch_init(opaque);
2508         if (r)
2509                 goto out_fail;
2510
2511         bad_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2512
2513         if (bad_page == NULL) {
2514                 r = -ENOMEM;
2515                 goto out;
2516         }
2517
2518         bad_pfn = page_to_pfn(bad_page);
2519
2520         hwpoison_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2521
2522         if (hwpoison_page == NULL) {
2523                 r = -ENOMEM;
2524                 goto out_free_0;
2525         }
2526
2527         hwpoison_pfn = page_to_pfn(hwpoison_page);
2528
2529         fault_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2530
2531         if (fault_page == NULL) {
2532                 r = -ENOMEM;
2533                 goto out_free_0;
2534         }
2535
2536         fault_pfn = page_to_pfn(fault_page);
2537
2538         if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
2539                 r = -ENOMEM;
2540                 goto out_free_0;
2541         }
2542
2543         r = kvm_arch_hardware_setup();
2544         if (r < 0)
2545                 goto out_free_0a;
2546
2547         for_each_online_cpu(cpu) {
2548                 smp_call_function_single(cpu,
2549                                 kvm_arch_check_processor_compat,
2550                                 &r, 1);
2551                 if (r < 0)
2552                         goto out_free_1;
2553         }
2554
2555         r = register_cpu_notifier(&kvm_cpu_notifier);
2556         if (r)
2557                 goto out_free_2;
2558         register_reboot_notifier(&kvm_reboot_notifier);
2559
2560         r = sysdev_class_register(&kvm_sysdev_class);
2561         if (r)
2562                 goto out_free_3;
2563
2564         r = sysdev_register(&kvm_sysdev);
2565         if (r)
2566                 goto out_free_4;
2567
2568         /* A kmem cache lets us meet the alignment requirements of fx_save. */
2569         if (!vcpu_align)
2570                 vcpu_align = __alignof__(struct kvm_vcpu);
2571         kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size, vcpu_align,
2572                                            0, NULL);
2573         if (!kvm_vcpu_cache) {
2574                 r = -ENOMEM;
2575                 goto out_free_5;
2576         }
2577
2578         r = kvm_async_pf_init();
2579         if (r)
2580                 goto out_free;
2581
2582         kvm_chardev_ops.owner = module;
2583         kvm_vm_fops.owner = module;
2584         kvm_vcpu_fops.owner = module;
2585
2586         r = misc_register(&kvm_dev);
2587         if (r) {
2588                 printk(KERN_ERR "kvm: misc device register failed\n");
2589                 goto out_unreg;
2590         }
2591
2592         kvm_preempt_ops.sched_in = kvm_sched_in;
2593         kvm_preempt_ops.sched_out = kvm_sched_out;
2594
2595         kvm_init_debug();
2596
2597         return 0;
2598
2599 out_unreg:
2600         kvm_async_pf_deinit();
2601 out_free:
2602         kmem_cache_destroy(kvm_vcpu_cache);
2603 out_free_5:
2604         sysdev_unregister(&kvm_sysdev);
2605 out_free_4:
2606         sysdev_class_unregister(&kvm_sysdev_class);
2607 out_free_3:
2608         unregister_reboot_notifier(&kvm_reboot_notifier);
2609         unregister_cpu_notifier(&kvm_cpu_notifier);
2610 out_free_2:
2611 out_free_1:
2612         kvm_arch_hardware_unsetup();
2613 out_free_0a:
2614         free_cpumask_var(cpus_hardware_enabled);
2615 out_free_0:
2616         if (fault_page)
2617                 __free_page(fault_page);
2618         if (hwpoison_page)
2619                 __free_page(hwpoison_page);
2620         __free_page(bad_page);
2621 out:
2622         kvm_arch_exit();
2623 out_fail:
2624         return r;
2625 }
2626 EXPORT_SYMBOL_GPL(kvm_init);
2627
2628 void kvm_exit(void)
2629 {
2630         kvm_exit_debug();
2631         misc_deregister(&kvm_dev);
2632         kmem_cache_destroy(kvm_vcpu_cache);
2633         kvm_async_pf_deinit();
2634         sysdev_unregister(&kvm_sysdev);
2635         sysdev_class_unregister(&kvm_sysdev_class);
2636         unregister_reboot_notifier(&kvm_reboot_notifier);
2637         unregister_cpu_notifier(&kvm_cpu_notifier);
2638         on_each_cpu(hardware_disable_nolock, NULL, 1);
2639         kvm_arch_hardware_unsetup();
2640         kvm_arch_exit();
2641         free_cpumask_var(cpus_hardware_enabled);
2642         __free_page(hwpoison_page);
2643         __free_page(bad_page);
2644 }
2645 EXPORT_SYMBOL_GPL(kvm_exit);